[ { "text": "[INST] Given the following code containing errors, provide Common Weakness 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_mem_writeb_mode4and5_16bpp(CirrusVGAState * s,\n\t\t\t\t\t unsigned mode,\n\t\t\t\t\t unsigned offset,\n\t\t\t\t\t uint32_t mem_value)\n{\n int x;\n unsigned val = mem_value;\n uint8_t *dst;\n\n dst = s->vram_ptr + offset;\n for (x = 0; x < 8; x++) {\n\tif (val & 0x80) {\n\t *dst = s->cirrus_shadow_gr1;\n\t *(dst + 1) = s->gr[0x11];\n\t} else if (mode == 5) {\n\t *dst = s->cirrus_shadow_gr0;\n\t *(dst + 1) = s->gr[0x10];\n\t}\n\tval <<= 1;\n\tdst += 2;\n }\n cpu_physical_memory_set_dirty(s->vram_offset + offset);\n cpu_physical_memory_set_dirty(s->vram_offset + offset + 15);\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: shmem_alloc_page(gfp_t gfp, struct shmem_inode_info *info,\n\t\t unsigned long idx)\n{\n\tstruct vm_area_struct pvma;\n\tstruct page *page;\n\n\tmemset(&pvma, 0, sizeof(struct vm_area_struct));\n\tpvma.vm_policy = mpol_shared_policy_lookup(&info->policy, idx);\n\tpvma.vm_pgoff = idx;\n\tpvma.vm_end = PAGE_SIZE;\n\tpage = alloc_page_vma(gfp | __GFP_ZERO, &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 int setup_frame(int sig, struct k_sigaction *ka,\n\t\t sigset_t *set, struct pt_regs * regs)\n{\n\tvoid __user *restorer;\n\tstruct sigframe __user *frame;\n\tint err = 0;\n\tint usig;\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\tusig = current_thread_info()->exec_domain\n\t\t&& current_thread_info()->exec_domain->signal_invmap\n\t\t&& sig < 32\n\t\t? current_thread_info()->exec_domain->signal_invmap[sig]\n\t\t: sig;\n\n\terr = __put_user(usig, &frame->sig);\n\tif (err)\n\t\tgoto give_sigsegv;\n\n\terr = setup_sigcontext(&frame->sc, &frame->fpstate, regs, set->sig[0]);\n\tif (err)\n\t\tgoto give_sigsegv;\n\n\tif (_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 (current->binfmt->hasvdso)\n\t\trestorer = VDSO32_SYMBOL(current->mm->context.vdso, sigreturn);\n\telse\n\t\trestorer = &frame->retcode;\n\tif (ka->sa.sa_flags & SA_RESTORER)\n\t\trestorer = ka->sa.sa_restorer;\n\n\t/* Set up to return from userspace. */\n\terr |= __put_user(restorer, &frame->pretcode);\n\t \n\t/*\n\t * This is popl %eax ; movl $,%eax ; int $0x80\n\t *\n\t * WE DO NOT USE IT ANY MORE! It's only left here for historical\n\t * reasons and because gdb uses it as a signature to notice\n\t * signal handler stack frames.\n\t */\n\terr |= __put_user(0xb858, (short __user *)(frame->retcode+0));\n\terr |= __put_user(__NR_sigreturn, (int __user *)(frame->retcode+2));\n\terr |= __put_user(0x80cd, (short __user *)(frame->retcode+6));\n\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\tregs->ax = (unsigned long) sig;\n\tregs->dx = (unsigned long) 0;\n\tregs->cx = (unsigned long) 0;\n\n\tregs->ds = __USER_DS;\n\tregs->es = __USER_DS;\n\tregs->ss = __USER_DS;\n\tregs->cs = __USER_CS;\n\n\t/*\n\t * Clear TF when entering the signal handler, but\n\t * notify any tracer that was single-stepping it.\n\t * The tracer may want to single-step inside the\n\t * handler too.\n\t */\n\tregs->flags &= ~TF_MASK;\n\tif (test_thread_flag(TIF_SINGLESTEP))\n\t\tptrace_notify(SIGTRAP);\n\n#if DEBUG_SIG\n\tprintk(\"SIG deliver (%s:%d): sp=%p pc=%p ra=%p\\n\",\n\t\tcurrent->comm, current->pid, frame, regs->ip, frame->pretcode);\n#endif\n\n\treturn 0;\n\ngive_sigsegv:\n\tforce_sigsegv(sig, current);\n\treturn -EFAULT;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'x86: clear DF before calling signal handler\n\nThe Linux kernel currently does not clear the direction flag before\ncalling a signal handler, whereas the x86/x86-64 ABI requires that.\n\nLinux had this behavior/bug forever, but this becomes a real problem\nwith gcc version 4.3, which assumes that the direction flag is\ncorrectly cleared at the entry of a function.\n\nThis patches changes the setup_frame() functions to clear the\ndirection before entering the signal handler.\n\nSigned-off-by: Aurelien Jarno \nSigned-off-by: Ingo Molnar \nAcked-by: H. Peter Anvin '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _gnutls_server_name_recv_params (gnutls_session_t session,\n\t\t\t\t const opaque * data, size_t _data_size)\n{\n int i;\n const unsigned char *p;\n uint16_t len, type;\n ssize_t data_size = _data_size;\n int server_names = 0;\n\n if (session->security_parameters.entity == GNUTLS_SERVER)\n {\n DECR_LENGTH_RET (data_size, 2, 0);\n len = _gnutls_read_uint16 (data);\n\n if (len != data_size)\n\t{\n\t /* This is unexpected packet length, but\n\t * just ignore it, for now.\n\t */\n\t gnutls_assert ();\n\t return 0;\n\t}\n\n p = data + 2;\n\n /* Count all server_names in the packet. */\n while (data_size > 0)\n\t{\n\t DECR_LENGTH_RET (data_size, 1, 0);\n\t p++;\n\n\t DECR_LEN (data_size, 2);\n\t len = _gnutls_read_uint16 (p);\n\t p += 2;\n\n\t DECR_LENGTH_RET (data_size, len, 0);\n\t server_names++;\n\n\t p += len;\n\t}\n\n session->security_parameters.extensions.server_names_size =\n\tserver_names;\n if (server_names == 0)\n\treturn 0;\t\t/* no names found */\n\n /* we cannot accept more server names.\n */\n if (server_names > MAX_SERVER_NAME_EXTENSIONS)\n\tserver_names = MAX_SERVER_NAME_EXTENSIONS;\n\n p = data + 2;\n for (i = 0; i < server_names; i++)\n\t{\n\t type = *p;\n\t p++;\n\n\t len = _gnutls_read_uint16 (p);\n\t p += 2;\n\n\t switch (type)\n\t {\n\t case 0:\t\t/* NAME_DNS */\n\t if (len <= MAX_SERVER_NAME_SIZE)\n\t\t{\n\t\t memcpy (session->security_parameters.extensions.\n\t\t\t server_names[i].name, p, len);\n\t\t session->security_parameters.extensions.\n\t\t server_names[i].name_length = len;\n\t\t session->security_parameters.extensions.\n\t\t server_names[i].type = GNUTLS_NAME_DNS;\n\t\t break;\n\t\t}\n\t }\n\n\t /* move to next record */\n\t p += len;\n\t}\n }\n return 0;\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 int do_change_type(struct nameidata *nd, int flag)\n{\n\tstruct vfsmount *m, *mnt = nd->mnt;\n\tint recurse = flag & MS_REC;\n\tint type = flag & ~MS_REC;\n\n\tif (nd->dentry != nd->mnt->mnt_root)\n\t\treturn -EINVAL;\n\n\tdown_write(&namespace_sem);\n\tspin_lock(&vfsmount_lock);\n\tfor (m = mnt; m; m = (recurse ? next_mnt(m, mnt) : NULL))\n\t\tchange_mnt_propagation(m, type);\n\tspin_unlock(&vfsmount_lock);\n\tup_write(&namespace_sem);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-269'], 'message': 'check privileges before setting mount propagation\n\nThere's a missing check for CAP_SYS_ADMIN in do_change_type().\n\nSigned-off-by: Miklos Szeredi \nCc: Al Viro \nCc: Christoph Hellwig \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 dentry * real_lookup(struct dentry * parent, struct qstr * name, struct nameidata *nd)\n{\n\tstruct dentry * result;\n\tstruct inode *dir = parent->d_inode;\n\n\tmutex_lock(&dir->i_mutex);\n\t/*\n\t * First re-do the cached lookup just in case it was created\n\t * while we waited for the directory semaphore..\n\t *\n\t * FIXME! This could use version numbering or similar to\n\t * avoid unnecessary cache lookups.\n\t *\n\t * The \"dcache_lock\" is purely to protect the RCU list walker\n\t * from concurrent renames at this point (we mustn't get false\n\t * negatives from the RCU list walk here, unlike the optimistic\n\t * fast walk).\n\t *\n\t * so doing d_lookup() (with seqlock), instead of lockfree __d_lookup\n\t */\n\tresult = d_lookup(parent, name);\n\tif (!result) {\n\t\tstruct dentry * dentry = d_alloc(parent, name);\n\t\tresult = ERR_PTR(-ENOMEM);\n\t\tif (dentry) {\n\t\t\tresult = dir->i_op->lookup(dir, dentry, nd);\n\t\t\tif (result)\n\t\t\t\tdput(dentry);\n\t\t\telse\n\t\t\t\tresult = dentry;\n\t\t}\n\t\tmutex_unlock(&dir->i_mutex);\n\t\treturn result;\n\t}\n\n\t/*\n\t * Uhhuh! Nasty case: the cache was re-populated while\n\t * we waited on the semaphore. Need to revalidate.\n\t */\n\tmutex_unlock(&dir->i_mutex);\n\tif (result->d_op && result->d_op->d_revalidate) {\n\t\tresult = do_revalidate(result, nd);\n\t\tif (!result)\n\t\t\tresult = ERR_PTR(-ENOENT);\n\t}\n\treturn result;\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: static void file_change(struct diff_options *options,\n\t\t unsigned old_mode, unsigned new_mode,\n\t\t const unsigned char *old_sha1,\n\t\t const unsigned char *new_sha1,\n\t\t const char *base, const char *path)\n{\n\ttree_difference = REV_TREE_DIFFERENT;\n\tDIFF_OPT_SET(options, HAS_CHANGES);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix buffer overflow in git diff\n\nIf PATH_MAX on your system is smaller than a path stored, it may cause\nbuffer overflow and stack corruption in diff_addremove() and diff_change()\nfunctions when running git-diff\n\nSigned-off-by: Dmitry Potapov \nSigned-off-by: Junio C Hamano '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static struct page *syscall_nopage(struct vm_area_struct *vma,\n\t\t\t\tunsigned long adr, int *type)\n{\n\tstruct page *p = virt_to_page(adr - vma->vm_start + syscall_page);\n\tget_page(p);\n\treturn p;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': '[PATCH] i386 vDSO: use install_special_mapping\n\nThis patch uses install_special_mapping for the i386 vDSO setup, consolidating\nduplicated code.\n\nSigned-off-by: Roland McGrath \nCc: Ingo Molnar \nCc: Paul Mackerras \nCc: Benjamin Herrenschmidt \nCc: Andi Kleen \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int 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_malloc(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-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_colr_getdata(jp2_box_t *box, jas_stream_t *in)\n{\n\tjp2_colr_t *colr = &box->data.colr;\n\tcolr->csid = 0;\n\tcolr->iccp = 0;\n\tcolr->iccplen = 0;\n\n\tif (jp2_getuint8(in, &colr->method) || jp2_getuint8(in, &colr->pri) ||\n\t jp2_getuint8(in, &colr->approx)) {\n\t\treturn -1;\n\t}\n\tswitch (colr->method) {\n\tcase JP2_COLR_ENUM:\n\t\tif (jp2_getuint32(in, &colr->csid)) {\n\t\t\treturn -1;\n\t\t}\n\t\tbreak;\n\tcase JP2_COLR_ICC:\n\t\tcolr->iccplen = box->datalen - 3;\n\t\tif (!(colr->iccp = jas_malloc(colr->iccplen * sizeof(uint_fast8_t)))) {\n\t\t\treturn -1;\n\t\t}\n\t\tif (jas_stream_read(in, colr->iccp, colr->iccplen) != colr->iccplen) {\n\t\t\treturn -1;\n\t\t}\n\t\tbreak;\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 jpc_qcx_getcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate,\n jas_stream_t *in, uint_fast16_t len)\n{\n\tuint_fast8_t tmp;\n\tint n;\n\tint i;\n\n\t/* Eliminate compiler warning about unused variables. */\n\tcstate = 0;\n\n\tn = 0;\n\tif (jpc_getuint8(in, &tmp)) {\n\t\treturn -1;\n\t}\n\t++n;\n\tcompparms->qntsty = tmp & 0x1f;\n\tcompparms->numguard = (tmp >> 5) & 7;\n\tswitch (compparms->qntsty) {\n\tcase JPC_QCX_SIQNT:\n\t\tcompparms->numstepsizes = 1;\n\t\tbreak;\n\tcase JPC_QCX_NOQNT:\n\t\tcompparms->numstepsizes = (len - n);\n\t\tbreak;\n\tcase JPC_QCX_SEQNT:\n\t\t/* XXX - this is a hack */\n\t\tcompparms->numstepsizes = (len - n) / 2;\n\t\tbreak;\n\t}\n\tif (compparms->numstepsizes > 0) {\n\t\tcompparms->stepsizes = jas_malloc(compparms->numstepsizes *\n\t\t sizeof(uint_fast16_t));\n\t\tassert(compparms->stepsizes);\n\t\tfor (i = 0; i < compparms->numstepsizes; ++i) {\n\t\t\tif (compparms->qntsty == JPC_QCX_NOQNT) {\n\t\t\t\tif (jpc_getuint8(in, &tmp)) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tcompparms->stepsizes[i] = JPC_QCX_EXPN(tmp >> 3);\n\t\t\t} else {\n\t\t\t\tif (jpc_getuint16(in, &compparms->stepsizes[i])) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tcompparms->stepsizes = 0;\n\t}\n\tif (jas_stream_error(in) || jas_stream_eof(in)) {\n\t\tjpc_qcx_destroycompparms(compparms);\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: jas_image_t *jp2_decode(jas_stream_t *in, char *optstr)\n{\n\tjp2_box_t *box;\n\tint found;\n\tjas_image_t *image;\n\tjp2_dec_t *dec;\n\tbool samedtype;\n\tint dtype;\n\tunsigned int i;\n\tjp2_cmap_t *cmapd;\n\tjp2_pclr_t *pclrd;\n\tjp2_cdef_t *cdefd;\n\tunsigned int channo;\n\tint newcmptno;\n\tint_fast32_t *lutents;\n#if 0\n\tjp2_cdefchan_t *cdefent;\n\tint cmptno;\n#endif\n\tjp2_cmapent_t *cmapent;\n\tjas_icchdr_t icchdr;\n\tjas_iccprof_t *iccprof;\n\n\tdec = 0;\n\tbox = 0;\n\timage = 0;\n\n\tif (!(dec = jp2_dec_create())) {\n\t\tgoto error;\n\t}\n\n\t/* Get the first box. This should be a JP box. */\n\tif (!(box = jp2_box_get(in))) {\n\t\tjas_eprintf(\"error: cannot get box\\n\");\n\t\tgoto error;\n\t}\n\tif (box->type != JP2_BOX_JP) {\n\t\tjas_eprintf(\"error: expecting signature box\\n\");\n\t\tgoto error;\n\t}\n\tif (box->data.jp.magic != JP2_JP_MAGIC) {\n\t\tjas_eprintf(\"incorrect magic number\\n\");\n\t\tgoto error;\n\t}\n\tjp2_box_destroy(box);\n\tbox = 0;\n\n\t/* Get the second box. This should be a FTYP box. */\n\tif (!(box = jp2_box_get(in))) {\n\t\tgoto error;\n\t}\n\tif (box->type != JP2_BOX_FTYP) {\n\t\tjas_eprintf(\"expecting file type box\\n\");\n\t\tgoto error;\n\t}\n\tjp2_box_destroy(box);\n\tbox = 0;\n\n\t/* Get more boxes... */\n\tfound = 0;\n\twhile ((box = jp2_box_get(in))) {\n\t\tif (jas_getdbglevel() >= 1) {\n\t\t\tjas_eprintf(\"box type %s\\n\", box->info->name);\n\t\t}\n\t\tswitch (box->type) {\n\t\tcase JP2_BOX_JP2C:\n\t\t\tfound = 1;\n\t\t\tbreak;\n\t\tcase JP2_BOX_IHDR:\n\t\t\tif (!dec->ihdr) {\n\t\t\t\tdec->ihdr = box;\n\t\t\t\tbox = 0;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase JP2_BOX_BPCC:\n\t\t\tif (!dec->bpcc) {\n\t\t\t\tdec->bpcc = box;\n\t\t\t\tbox = 0;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase JP2_BOX_CDEF:\n\t\t\tif (!dec->cdef) {\n\t\t\t\tdec->cdef = box;\n\t\t\t\tbox = 0;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase JP2_BOX_PCLR:\n\t\t\tif (!dec->pclr) {\n\t\t\t\tdec->pclr = box;\n\t\t\t\tbox = 0;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase JP2_BOX_CMAP:\n\t\t\tif (!dec->cmap) {\n\t\t\t\tdec->cmap = box;\n\t\t\t\tbox = 0;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase JP2_BOX_COLR:\n\t\t\tif (!dec->colr) {\n\t\t\t\tdec->colr = box;\n\t\t\t\tbox = 0;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tif (box) {\n\t\t\tjp2_box_destroy(box);\n\t\t\tbox = 0;\n\t\t}\n\t\tif (found) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (!found) {\n\t\tjas_eprintf(\"error: no code stream found\\n\");\n\t\tgoto error;\n\t}\n\n\tif (!(dec->image = jpc_decode(in, optstr))) {\n\t\tjas_eprintf(\"error: cannot decode code stream\\n\");\n\t\tgoto error;\n\t}\n\n\t/* An IHDR box must be present. */\n\tif (!dec->ihdr) {\n\t\tjas_eprintf(\"error: missing IHDR box\\n\");\n\t\tgoto error;\n\t}\n\n\t/* Does the number of components indicated in the IHDR box match\n\t the value specified in the code stream? */\n\tif (dec->ihdr->data.ihdr.numcmpts != JAS_CAST(uint, jas_image_numcmpts(dec->image))) {\n\t\tjas_eprintf(\"warning: number of components mismatch\\n\");\n\t}\n\n\t/* At least one component must be present. */\n\tif (!jas_image_numcmpts(dec->image)) {\n\t\tjas_eprintf(\"error: no components\\n\");\n\t\tgoto error;\n\t}\n\n\t/* Determine if all components have the same data type. */\n\tsamedtype = true;\n\tdtype = jas_image_cmptdtype(dec->image, 0);\n\tfor (i = 1; i < JAS_CAST(uint, jas_image_numcmpts(dec->image)); ++i) {\n\t\tif (jas_image_cmptdtype(dec->image, i) != dtype) {\n\t\t\tsamedtype = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/* Is the component data type indicated in the IHDR box consistent\n\t with the data in the code stream? */\n\tif ((samedtype && dec->ihdr->data.ihdr.bpc != JP2_DTYPETOBPC(dtype)) ||\n\t (!samedtype && dec->ihdr->data.ihdr.bpc != JP2_IHDR_BPCNULL)) {\n\t\tjas_eprintf(\"warning: component data type mismatch\\n\");\n\t}\n\n\t/* Is the compression type supported? */\n\tif (dec->ihdr->data.ihdr.comptype != JP2_IHDR_COMPTYPE) {\n\t\tjas_eprintf(\"error: unsupported compression type\\n\");\n\t\tgoto error;\n\t}\n\n\tif (dec->bpcc) {\n\t\t/* Is the number of components indicated in the BPCC box\n\t\t consistent with the code stream data? */\n\t\tif (dec->bpcc->data.bpcc.numcmpts != JAS_CAST(uint, jas_image_numcmpts(\n\t\t dec->image))) {\n\t\t\tjas_eprintf(\"warning: number of components mismatch\\n\");\n\t\t}\n\t\t/* Is the component data type information indicated in the BPCC\n\t\t box consistent with the code stream data? */\n\t\tif (!samedtype) {\n\t\t\tfor (i = 0; i < JAS_CAST(uint, jas_image_numcmpts(dec->image)); ++i) {\n\t\t\t\tif (jas_image_cmptdtype(dec->image, i) != JP2_BPCTODTYPE(dec->bpcc->data.bpcc.bpcs[i])) {\n\t\t\t\t\tjas_eprintf(\"warning: component data type mismatch\\n\");\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tjas_eprintf(\"warning: superfluous BPCC box\\n\");\n\t\t}\n\t}\n\n\t/* A COLR box must be present. */\n\tif (!dec->colr) {\n\t\tjas_eprintf(\"error: no COLR box\\n\");\n\t\tgoto error;\n\t}\n\n\tswitch (dec->colr->data.colr.method) {\n\tcase JP2_COLR_ENUM:\n\t\tjas_image_setclrspc(dec->image, jp2_getcs(&dec->colr->data.colr));\n\t\tbreak;\n\tcase JP2_COLR_ICC:\n\t\ticcprof = jas_iccprof_createfrombuf(dec->colr->data.colr.iccp,\n\t\t dec->colr->data.colr.iccplen);\n\t\tif (!iccprof) {\n\t\t\tjas_eprintf(\"error: failed to parse ICC profile\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tjas_iccprof_gethdr(iccprof, &icchdr);\n\t\tjas_eprintf(\"ICC Profile CS %08x\\n\", icchdr.colorspc);\n\t\tjas_image_setclrspc(dec->image, fromiccpcs(icchdr.colorspc));\n\t\tdec->image->cmprof_ = jas_cmprof_createfromiccprof(iccprof);\n\t\tassert(dec->image->cmprof_);\n\t\tjas_iccprof_destroy(iccprof);\n\t\tbreak;\n\t}\n\n\t/* If a CMAP box is present, a PCLR box must also be present. */\n\tif (dec->cmap && !dec->pclr) {\n\t\tjas_eprintf(\"warning: missing PCLR box or superfluous CMAP box\\n\");\n\t\tjp2_box_destroy(dec->cmap);\n\t\tdec->cmap = 0;\n\t}\n\n\t/* If a CMAP box is not present, a PCLR box must not be present. */\n\tif (!dec->cmap && dec->pclr) {\n\t\tjas_eprintf(\"warning: missing CMAP box or superfluous PCLR box\\n\");\n\t\tjp2_box_destroy(dec->pclr);\n\t\tdec->pclr = 0;\n\t}\n\n\t/* Determine the number of channels (which is essentially the number\n\t of components after any palette mappings have been applied). */\n\tdec->numchans = dec->cmap ? dec->cmap->data.cmap.numchans : JAS_CAST(uint, jas_image_numcmpts(dec->image));\n\n\t/* Perform a basic sanity check on the CMAP box if present. */\n\tif (dec->cmap) {\n\t\tfor (i = 0; i < dec->numchans; ++i) {\n\t\t\t/* Is the component number reasonable? */\n\t\t\tif (dec->cmap->data.cmap.ents[i].cmptno >= JAS_CAST(uint, jas_image_numcmpts(dec->image))) {\n\t\t\t\tjas_eprintf(\"error: invalid component number in CMAP box\\n\");\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t\t/* Is the LUT index reasonable? */\n\t\t\tif (dec->cmap->data.cmap.ents[i].pcol >= dec->pclr->data.pclr.numchans) {\n\t\t\t\tjas_eprintf(\"error: invalid CMAP LUT index\\n\");\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Allocate space for the channel-number to component-number LUT. */\n\tif (!(dec->chantocmptlut = jas_malloc(dec->numchans * sizeof(uint_fast16_t)))) {\n\t\tjas_eprintf(\"error: no memory\\n\");\n\t\tgoto error;\n\t}\n\n\tif (!dec->cmap) {\n\t\tfor (i = 0; i < dec->numchans; ++i) {\n\t\t\tdec->chantocmptlut[i] = i;\n\t\t}\n\t} else {\n\t\tcmapd = &dec->cmap->data.cmap;\n\t\tpclrd = &dec->pclr->data.pclr;\n\t\tcdefd = &dec->cdef->data.cdef;\n\t\tfor (channo = 0; channo < cmapd->numchans; ++channo) {\n\t\t\tcmapent = &cmapd->ents[channo];\n\t\t\tif (cmapent->map == JP2_CMAP_DIRECT) {\n\t\t\t\tdec->chantocmptlut[channo] = channo;\n\t\t\t} else if (cmapent->map == JP2_CMAP_PALETTE) {\n\t\t\t\tlutents = jas_malloc(pclrd->numlutents * sizeof(int_fast32_t));\n\t\t\t\tfor (i = 0; i < pclrd->numlutents; ++i) {\n\t\t\t\t\tlutents[i] = pclrd->lutdata[cmapent->pcol + i * pclrd->numchans];\n\t\t\t\t}\n\t\t\t\tnewcmptno = jas_image_numcmpts(dec->image);\n\t\t\t\tjas_image_depalettize(dec->image, cmapent->cmptno, pclrd->numlutents, lutents, JP2_BPCTODTYPE(pclrd->bpc[cmapent->pcol]), newcmptno);\n\t\t\t\tdec->chantocmptlut[channo] = newcmptno;\n\t\t\t\tjas_free(lutents);\n#if 0\n\t\t\t\tif (dec->cdef) {\n\t\t\t\t\tcdefent = jp2_cdef_lookup(cdefd, channo);\n\t\t\t\t\tif (!cdefent) {\n\t\t\t\t\t\tabort();\n\t\t\t\t\t}\n\t\t\t\tjas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), cdefent->type, cdefent->assoc));\n\t\t\t\t} else {\n\t\t\t\tjas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), 0, channo + 1));\n\t\t\t\t}\n#endif\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Mark all components as being of unknown type. */\n\n\tfor (i = 0; i < JAS_CAST(uint, jas_image_numcmpts(dec->image)); ++i) {\n\t\tjas_image_setcmpttype(dec->image, i, JAS_IMAGE_CT_UNKNOWN);\n\t}\n\n\t/* Determine the type of each component. */\n\tif (dec->cdef) {\n\t\tfor (i = 0; i < dec->numchans; ++i) {\n\t\t\t/* Is the channel number reasonable? */\n\t\t\tif (dec->cdef->data.cdef.ents[i].channo >= dec->numchans) {\n\t\t\t\tjas_eprintf(\"error: invalid channel number in CDEF box\\n\");\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t\tjas_image_setcmpttype(dec->image,\n\t\t\t dec->chantocmptlut[dec->cdef->data.cdef.ents[i].channo],\n\t\t\t jp2_getct(jas_image_clrspc(dec->image),\n\t\t\t dec->cdef->data.cdef.ents[i].type, dec->cdef->data.cdef.ents[i].assoc));\n\t\t}\n\t} else {\n\t\tfor (i = 0; i < dec->numchans; ++i) {\n\t\t\tjas_image_setcmpttype(dec->image, dec->chantocmptlut[i],\n\t\t\t jp2_getct(jas_image_clrspc(dec->image), 0, i + 1));\n\t\t}\n\t}\n\n\t/* Delete any components that are not of interest. */\n\tfor (i = jas_image_numcmpts(dec->image); i > 0; --i) {\n\t\tif (jas_image_cmpttype(dec->image, i - 1) == JAS_IMAGE_CT_UNKNOWN) {\n\t\t\tjas_image_delcmpt(dec->image, i - 1);\n\t\t}\n\t}\n\n\t/* Ensure that some components survived. */\n\tif (!jas_image_numcmpts(dec->image)) {\n\t\tjas_eprintf(\"error: no components\\n\");\n\t\tgoto error;\n\t}\n#if 0\njas_eprintf(\"no of components is %d\\n\", jas_image_numcmpts(dec->image));\n#endif\n\n\t/* Prevent the image from being destroyed later. */\n\timage = dec->image;\n\tdec->image = 0;\n\n\tjp2_dec_destroy(dec);\n\n\treturn image;\n\nerror:\n\tif (box) {\n\t\tjp2_box_destroy(box);\n\t}\n\tif (dec) {\n\t\tjp2_dec_destroy(dec);\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 jpc_unk_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)\n{\n\tjpc_unk_t *unk = &ms->parms.unk;\n\n\t/* Eliminate compiler warning about unused variables. */\n\tcstate = 0;\n\n\tif (ms->len > 0) {\n\t\tif (!(unk->data = jas_malloc(ms->len * sizeof(unsigned char)))) {\n\t\t\treturn -1;\n\t\t}\n\t\tif (jas_stream_read(in, (char *) unk->data, ms->len) != JAS_CAST(int, ms->len)) {\n\t\t\tjas_free(unk->data);\n\t\t\treturn -1;\n\t\t}\n\t\tunk->len = ms->len;\n\t} else {\n\t\tunk->data = 0;\n\t\tunk->len = 0;\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: char *jas_strdup(const char *s)\n{\n\tint n;\n\tchar *p;\n\tn = strlen(s) + 1;\n\tif (!(p = jas_malloc(n * sizeof(char)))) {\n\t\treturn 0;\n\t}\n\tstrcpy(p, s);\n\treturn p;\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_colres(jpc_fix_t *a, int numrows, int numcols,\n int stride, 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_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\tdstptr2 = dstptr;\n\t\t\tsrcptr2 = srcptr;\n\t\t\tfor (i = 0; i < numcols; ++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 += numcols;\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 < numcols; ++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 < numcols; ++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 += numcols;\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: _dbus_validate_signature_with_reason (const DBusString *type_str,\n int type_pos,\n int len)\n{\n const unsigned char *p;\n const unsigned char *end;\n int last;\n int struct_depth;\n int array_depth;\n int dict_entry_depth;\n DBusValidity result;\n\n int element_count;\n DBusList *element_count_stack;\n\n result = DBUS_VALID;\n element_count_stack = NULL;\n\n if (!_dbus_list_append (&element_count_stack, _DBUS_INT_TO_POINTER (0)))\n {\n result = DBUS_VALIDITY_UNKNOWN_OOM_ERROR;\n goto out;\n }\n\n _dbus_assert (type_str != NULL);\n _dbus_assert (type_pos < _DBUS_INT32_MAX - len);\n _dbus_assert (len >= 0);\n _dbus_assert (type_pos >= 0);\n\n if (len > DBUS_MAXIMUM_SIGNATURE_LENGTH)\n {\n result = DBUS_INVALID_SIGNATURE_TOO_LONG;\n goto out;\n }\n\n p = _dbus_string_get_const_data_len (type_str, type_pos, 0);\n\n end = _dbus_string_get_const_data_len (type_str, type_pos + len, 0);\n struct_depth = 0;\n array_depth = 0;\n dict_entry_depth = 0;\n last = DBUS_TYPE_INVALID;\n\n while (p != end)\n {\n switch (*p)\n {\n case DBUS_TYPE_BYTE:\n case DBUS_TYPE_BOOLEAN:\n case DBUS_TYPE_INT16:\n case DBUS_TYPE_UINT16:\n case DBUS_TYPE_INT32:\n case DBUS_TYPE_UINT32:\n case DBUS_TYPE_INT64:\n case DBUS_TYPE_UINT64:\n case DBUS_TYPE_DOUBLE:\n case DBUS_TYPE_STRING:\n case DBUS_TYPE_OBJECT_PATH:\n case DBUS_TYPE_SIGNATURE:\n case DBUS_TYPE_VARIANT:\n break;\n\n case DBUS_TYPE_ARRAY:\n array_depth += 1;\n if (array_depth > DBUS_MAXIMUM_TYPE_RECURSION_DEPTH)\n {\n result = DBUS_INVALID_EXCEEDED_MAXIMUM_ARRAY_RECURSION;\n goto out;\n }\n break;\n\n case DBUS_STRUCT_BEGIN_CHAR:\n struct_depth += 1;\n\n if (struct_depth > DBUS_MAXIMUM_TYPE_RECURSION_DEPTH)\n {\n result = DBUS_INVALID_EXCEEDED_MAXIMUM_STRUCT_RECURSION;\n goto out;\n }\n \n if (!_dbus_list_append (&element_count_stack, \n _DBUS_INT_TO_POINTER (0)))\n {\n result = DBUS_VALIDITY_UNKNOWN_OOM_ERROR;\n goto out;\n }\n\n break;\n\n case DBUS_STRUCT_END_CHAR:\n if (struct_depth == 0)\n {\n result = DBUS_INVALID_STRUCT_ENDED_BUT_NOT_STARTED;\n goto out;\n }\n\n if (last == DBUS_STRUCT_BEGIN_CHAR)\n {\n result = DBUS_INVALID_STRUCT_HAS_NO_FIELDS;\n goto out;\n }\n\n _dbus_list_pop_last (&element_count_stack);\n\n struct_depth -= 1;\n break;\n\n case DBUS_DICT_ENTRY_BEGIN_CHAR:\n if (last != DBUS_TYPE_ARRAY)\n {\n result = DBUS_INVALID_DICT_ENTRY_NOT_INSIDE_ARRAY;\n goto out;\n }\n \n dict_entry_depth += 1;\n\n if (dict_entry_depth > DBUS_MAXIMUM_TYPE_RECURSION_DEPTH)\n {\n result = DBUS_INVALID_EXCEEDED_MAXIMUM_DICT_ENTRY_RECURSION;\n goto out;\n }\n\n if (!_dbus_list_append (&element_count_stack, \n _DBUS_INT_TO_POINTER (0)))\n {\n result = DBUS_VALIDITY_UNKNOWN_OOM_ERROR;\n goto out;\n }\n\n break;\n\n case DBUS_DICT_ENTRY_END_CHAR:\n if (dict_entry_depth == 0)\n {\n result = DBUS_INVALID_DICT_ENTRY_ENDED_BUT_NOT_STARTED;\n goto out;\n }\n \n dict_entry_depth -= 1;\n\n element_count = \n _DBUS_POINTER_TO_INT (_dbus_list_pop_last (&element_count_stack));\n\n if (element_count != 2)\n {\n if (element_count == 0)\n result = DBUS_INVALID_DICT_ENTRY_HAS_NO_FIELDS;\n else if (element_count == 1)\n result = DBUS_INVALID_DICT_ENTRY_HAS_ONLY_ONE_FIELD;\n else\n result = DBUS_INVALID_DICT_ENTRY_HAS_TOO_MANY_FIELDS;\n \n goto out;\n }\n break;\n \n case DBUS_TYPE_STRUCT: /* doesn't appear in signatures */\n case DBUS_TYPE_DICT_ENTRY: /* ditto */\n default:\n result = DBUS_INVALID_UNKNOWN_TYPECODE;\n\t goto out;\n }\n\n if (*p != DBUS_TYPE_ARRAY && \n *p != DBUS_DICT_ENTRY_BEGIN_CHAR && \n\t *p != DBUS_STRUCT_BEGIN_CHAR) \n {\n element_count = \n _DBUS_POINTER_TO_INT (_dbus_list_pop_last (&element_count_stack));\n\n ++element_count;\n\n if (!_dbus_list_append (&element_count_stack, \n _DBUS_INT_TO_POINTER (element_count)))\n {\n result = DBUS_VALIDITY_UNKNOWN_OOM_ERROR;\n goto out;\n }\n }\n \n if (array_depth > 0)\n {\n if (*p == DBUS_TYPE_ARRAY && p != end)\n {\n\t const char *p1;\n\t p1 = p + 1;\n if (*p1 == DBUS_STRUCT_END_CHAR ||\n *p1 == DBUS_DICT_ENTRY_END_CHAR)\n {\n result = DBUS_INVALID_MISSING_ARRAY_ELEMENT_TYPE;\n goto out;\n }\n }\n else\n\t {\n array_depth = 0;\n\t }\n }\n\n if (last == DBUS_DICT_ENTRY_BEGIN_CHAR &&\n !dbus_type_is_basic (*p))\n {\n result = DBUS_INVALID_DICT_KEY_MUST_BE_BASIC_TYPE;\n goto out;\n }\n \n last = *p;\n ++p;\n }\n\n\n if (array_depth > 0)\n {\n result = DBUS_INVALID_MISSING_ARRAY_ELEMENT_TYPE;\n goto out;\n }\n \n if (struct_depth > 0)\n {\n result = DBUS_INVALID_STRUCT_STARTED_BUT_NOT_ENDED;\n goto out;\n }\n \n if (dict_entry_depth > 0)\n {\n result = DBUS_INVALID_DICT_ENTRY_STARTED_BUT_NOT_ENDED;\n goto out;\n }\n \n _dbus_assert (last != DBUS_TYPE_ARRAY);\n _dbus_assert (last != DBUS_STRUCT_BEGIN_CHAR);\n _dbus_assert (last != DBUS_DICT_ENTRY_BEGIN_CHAR);\n\n result = DBUS_VALID;\n\nout:\n _dbus_list_clear (&element_count_stack);\n return result;\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: static long do_splice_from(struct pipe_inode_info *pipe, struct file *out,\n\t\t\t loff_t *ppos, size_t len, unsigned int flags)\n{\n\tint ret;\n\n\tif (unlikely(!out->f_op || !out->f_op->splice_write))\n\t\treturn -EINVAL;\n\n\tif (unlikely(!(out->f_mode & FMODE_WRITE)))\n\t\treturn -EBADF;\n\n\tret = rw_verify_area(WRITE, out, ppos, len);\n\tif (unlikely(ret < 0))\n\t\treturn ret;\n\n\treturn out->f_op->splice_write(pipe, out, ppos, len, flags);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'Don't allow splice() to files opened with O_APPEND\n\nThis is debatable, but while we're debating it, let's disallow the\ncombination of splice and an O_APPEND destination.\n\nIt's not entirely clear what the semantics of O_APPEND should be, and\nPOSIX apparently expects pwrite() to ignore O_APPEND, for example. So\nwe could make up any semantics we want, including the old ones.\n\nBut Miklos convinced me that we should at least give it some thought,\nand that accepting writes at arbitrary offsets is wrong at least for\nIS_APPEND() files (which always have O_APPEND set, even if the reverse\nisn't true: you can obviously have O_APPEND set on a regular file).\n\nSo disallow O_APPEND entirely for now. I doubt anybody cares, and this\nway we have one less gray area to worry about.\n\nReported-and-argued-for-by: Miklos Szeredi \nAcked-by: Jens Axboe \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 audit_chunk *alloc_chunk(int count)\n{\n\tstruct audit_chunk *chunk;\n\tsize_t size;\n\tint i;\n\n\tsize = offsetof(struct audit_chunk, owners) + count * sizeof(struct node);\n\tchunk = kzalloc(size, GFP_KERNEL);\n\tif (!chunk)\n\t\treturn NULL;\n\n\tINIT_LIST_HEAD(&chunk->hash);\n\tINIT_LIST_HEAD(&chunk->trees);\n\tchunk->count = count;\n\tfor (i = 0; i < count; i++) {\n\t\tINIT_LIST_HEAD(&chunk->owners[i].list);\n\t\tchunk->owners[i].index = i;\n\t}\n\tinotify_init_watch(&chunk->watch);\n\treturn chunk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'Fix inotify watch removal/umount races\n\nInotify watch removals suck violently.\n\nTo kick the watch out we need (in this order) inode->inotify_mutex and\nih->mutex. That's fine if we have a hold on inode; however, for all\nother cases we need to make damn sure we don't race with umount. We can\n*NOT* just grab a reference to a watch - inotify_unmount_inodes() will\nhappily sail past it and we'll end with reference to inode potentially\noutliving its superblock.\n\nIdeally we just want to grab an active reference to superblock if we\ncan; that will make sure we won't go into inotify_umount_inodes() until\nwe are done. Cleanup is just deactivate_super().\n\nHowever, that leaves a messy case - what if we *are* racing with\numount() and active references to superblock can't be acquired anymore?\nWe can bump ->s_count, grab ->s_umount, which will almost certainly wait\nuntil the superblock is shut down and the watch in question is pining\nfor fjords. That's fine, but there is a problem - we might have hit the\nwindow between ->s_active getting to 0 / ->s_count - below S_BIAS (i.e.\nthe moment when superblock is past the point of no return and is heading\nfor shutdown) and the moment when deactivate_super() acquires\n->s_umount.\n\nWe could just do drop_super() yield() and retry, but that's rather\nantisocial and this stuff is luser-triggerable. OTOH, having grabbed\n->s_umount and having found that we'd got there first (i.e. that\n->s_root is non-NULL) we know that we won't race with\ninotify_umount_inodes().\n\nSo we could grab a reference to watch and do the rest as above, just\nwith drop_super() instead of deactivate_super(), right? Wrong. We had\nto drop ih->mutex before we could grab ->s_umount. So the watch\ncould've been gone already.\n\nThat still can be dealt with - we need to save watch->wd, do idr_find()\nand compare its result with our pointer. If they match, we either have\nthe damn thing still alive or we'd lost not one but two races at once,\nthe watch had been killed and a new one got created with the same ->wd\nat the same address. That couldn't have happened in inotify_destroy(),\nbut inotify_rm_wd() could run into that. Still, \"new one got created\"\nis not a problem - we have every right to kill it or leave it alone,\nwhatever's more convenient.\n\nSo we can use idr_find(...) == watch && watch->inode->i_sb == sb as\n\"grab it and kill it\" check. If it's been our original watch, we are\nfine, if it's a newcomer - nevermind, just pretend that we'd won the\nrace and kill the fscker anyway; we are safe since we know that its\nsuperblock won't be going away.\n\nAnd yes, this is far beyond mere \"not very pretty\"; so's the entire\nconcept of inotify to start with.\n\nSigned-off-by: Al Viro \nAcked-by: Greg KH \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int blk_fill_sgv4_hdr_rq(struct request_queue *q, struct request *rq,\n\t\t\t\tstruct sg_io_v4 *hdr, struct bsg_device *bd,\n\t\t\t\tfmode_t has_write_perm)\n{\n\tif (hdr->request_len > BLK_MAX_CDB) {\n\t\trq->cmd = kzalloc(hdr->request_len, GFP_KERNEL);\n\t\tif (!rq->cmd)\n\t\t\treturn -ENOMEM;\n\t}\n\n\tif (copy_from_user(rq->cmd, (void *)(unsigned long)hdr->request,\n\t\t\t hdr->request_len))\n\t\treturn -EFAULT;\n\n\tif (hdr->subprotocol == BSG_SUB_PROTOCOL_SCSI_CMD) {\n\t\tif (blk_verify_command(&q->cmd_filter, rq->cmd, has_write_perm))\n\t\t\treturn -EPERM;\n\t} else if (!capable(CAP_SYS_RAWIO))\n\t\treturn -EPERM;\n\n\t/*\n\t * fill in request structure\n\t */\n\trq->cmd_len = hdr->request_len;\n\trq->cmd_type = REQ_TYPE_BLOCK_PC;\n\n\trq->timeout = (hdr->timeout * HZ) / 1000;\n\tif (!rq->timeout)\n\t\trq->timeout = q->sg_timeout;\n\tif (!rq->timeout)\n\t\trq->timeout = BLK_DEFAULT_SG_TIMEOUT;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'Enforce a minimum SG_IO timeout\n\nThere's no point in having too short SG_IO timeouts, since if the\ncommand does end up timing out, we'll end up through the reset sequence\nthat is several seconds long in order to abort the command that timed\nout.\n\nAs a result, shorter timeouts than a few seconds simply do not make\nsense, as the recovery would be longer than the timeout itself.\n\nAdd a BLK_MIN_SG_TIMEOUT to match the existign BLK_DEFAULT_SG_TIMEOUT.\n\nSuggested-by: Alan Cox \nAcked-by: Tejun Heo \nAcked-by: Jens Axboe \nCc: Jeff Garzik \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void ms_adpcm_reset2 (_AFmoduleinst *i)\n{\n\tms_adpcm_data\t*d = (ms_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: static status ParseFormat (AFfilehandle filehandle, AFvirtualfile *fp,\n\tuint32_t id, size_t size)\n{\n\t_Track\t\t*track;\n\tuint16_t\tformatTag, channelCount;\n\tuint32_t\tsampleRate, averageBytesPerSecond;\n\tuint16_t\tblockAlign;\n\t_WAVEInfo\t*wave;\n\n\tassert(filehandle != NULL);\n\tassert(fp != NULL);\n\tassert(!memcmp(&id, \"fmt \", 4));\n\n\ttrack = _af_filehandle_get_track(filehandle, AF_DEFAULT_TRACK);\n\n\tassert(filehandle->formatSpecific != NULL);\n\twave = (_WAVEInfo *) filehandle->formatSpecific;\n\n\taf_read_uint16_le(&formatTag, fp);\n\taf_read_uint16_le(&channelCount, fp);\n\taf_read_uint32_le(&sampleRate, fp);\n\taf_read_uint32_le(&averageBytesPerSecond, fp);\n\taf_read_uint16_le(&blockAlign, fp);\n\n\ttrack->f.channelCount = channelCount;\n\ttrack->f.sampleRate = sampleRate;\n\ttrack->f.byteOrder = AF_BYTEORDER_LITTLEENDIAN;\n\n\t/* Default to uncompressed audio data. */\n\ttrack->f.compressionType = AF_COMPRESSION_NONE;\n\n\tswitch (formatTag)\n\t{\n\t\tcase WAVE_FORMAT_PCM:\n\t\t{\n\t\t\tuint16_t\tbitsPerSample;\n\n\t\t\taf_read_uint16_le(&bitsPerSample, fp);\n\n\t\t\ttrack->f.sampleWidth = bitsPerSample;\n\n\t\t\tif (bitsPerSample == 0 || bitsPerSample > 32)\n\t\t\t{\n\t\t\t\t_af_error(AF_BAD_WIDTH,\n\t\t\t\t\t\"bad sample width of %d bits\",\n\t\t\t\t\tbitsPerSample);\n\t\t\t\treturn AF_FAIL;\n\t\t\t}\n\n\t\t\tif (bitsPerSample <= 8)\n\t\t\t\ttrack->f.sampleFormat = AF_SAMPFMT_UNSIGNED;\n\t\t\telse\n\t\t\t\ttrack->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;\n\t\t}\n\t\tbreak;\n\n\t\tcase WAVE_FORMAT_MULAW:\n\t\tcase IBM_FORMAT_MULAW:\n\t\t\ttrack->f.sampleWidth = 16;\n\t\t\ttrack->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;\n\t\t\ttrack->f.compressionType = AF_COMPRESSION_G711_ULAW;\n\t\t\tbreak;\n\n\t\tcase WAVE_FORMAT_ALAW:\n\t\tcase IBM_FORMAT_ALAW:\n\t\t\ttrack->f.sampleWidth = 16;\n\t\t\ttrack->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;\n\t\t\ttrack->f.compressionType = AF_COMPRESSION_G711_ALAW;\n\t\t\tbreak;\n\n\t\tcase WAVE_FORMAT_IEEE_FLOAT:\n\t\t{\n\t\t\tuint16_t\tbitsPerSample;\n\n\t\t\taf_read_uint16_le(&bitsPerSample, fp);\n\n\t\t\tif (bitsPerSample == 64)\n\t\t\t{\n\t\t\t\ttrack->f.sampleWidth = 64;\n\t\t\t\ttrack->f.sampleFormat = AF_SAMPFMT_DOUBLE;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ttrack->f.sampleWidth = 32;\n\t\t\t\ttrack->f.sampleFormat = AF_SAMPFMT_FLOAT;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\t\tcase WAVE_FORMAT_ADPCM:\n\t\t{\n\t\t\tuint16_t\tbitsPerSample, extraByteCount,\n\t\t\t\t\tsamplesPerBlock, numCoefficients;\n\t\t\tint\t\ti;\n\t\t\tAUpvlist\tpv;\n\t\t\tlong\t\tl;\n\t\t\tvoid\t\t*v;\n\n\t\t\tif (track->f.channelCount != 1 &&\n\t\t\t\ttrack->f.channelCount != 2)\n\t\t\t{\n\t\t\t\t_af_error(AF_BAD_CHANNELS,\n\t\t\t\t\t\"WAVE file with MS ADPCM compression \"\n\t\t\t\t\t\"must have 1 or 2 channels\");\n\t\t\t}\n\n\t\t\taf_read_uint16_le(&bitsPerSample, fp);\n\t\t\taf_read_uint16_le(&extraByteCount, fp);\n\t\t\taf_read_uint16_le(&samplesPerBlock, fp);\n\t\t\taf_read_uint16_le(&numCoefficients, fp);\n\n\t\t\t/* numCoefficients should be at least 7. */\n\t\t\tassert(numCoefficients >= 7 && numCoefficients <= 255);\n\n\t\t\tfor (i=0; imsadpcmCoefficients[i][0] = a0;\n\t\t\t\twave->msadpcmCoefficients[i][1] = a1;\n\t\t\t}\n\n\t\t\ttrack->f.sampleWidth = 16;\n\t\t\ttrack->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;\n\t\t\ttrack->f.compressionType = AF_COMPRESSION_MS_ADPCM;\n\t\t\ttrack->f.byteOrder = _AF_BYTEORDER_NATIVE;\n\n\t\t\t/* Create the parameter list. */\n\t\t\tpv = AUpvnew(4);\n\t\t\tAUpvsetparam(pv, 0, _AF_MS_ADPCM_NUM_COEFFICIENTS);\n\t\t\tAUpvsetvaltype(pv, 0, AU_PVTYPE_LONG);\n\t\t\tl = numCoefficients;\n\t\t\tAUpvsetval(pv, 0, &l);\n\n\t\t\tAUpvsetparam(pv, 1, _AF_MS_ADPCM_COEFFICIENTS);\n\t\t\tAUpvsetvaltype(pv, 1, AU_PVTYPE_PTR);\n\t\t\tv = wave->msadpcmCoefficients;\n\t\t\tAUpvsetval(pv, 1, &v);\n\n\t\t\tAUpvsetparam(pv, 2, _AF_SAMPLES_PER_BLOCK);\n\t\t\tAUpvsetvaltype(pv, 2, AU_PVTYPE_LONG);\n\t\t\tl = samplesPerBlock;\n\t\t\tAUpvsetval(pv, 2, &l);\n\n\t\t\tAUpvsetparam(pv, 3, _AF_BLOCK_SIZE);\n\t\t\tAUpvsetvaltype(pv, 3, AU_PVTYPE_LONG);\n\t\t\tl = blockAlign;\n\t\t\tAUpvsetval(pv, 3, &l);\n\n\t\t\ttrack->f.compressionParams = pv;\n\t\t}\n\t\tbreak;\n\n\t\tcase WAVE_FORMAT_DVI_ADPCM:\n\t\t{\n\t\t\tAUpvlist\tpv;\n\t\t\tlong\t\tl;\n\n\t\t\tuint16_t\tbitsPerSample, extraByteCount,\n\t\t\t\t\tsamplesPerBlock;\n\n\t\t\taf_read_uint16_le(&bitsPerSample, fp);\n\t\t\taf_read_uint16_le(&extraByteCount, fp);\n\t\t\taf_read_uint16_le(&samplesPerBlock, fp);\n\n\t\t\ttrack->f.sampleWidth = 16;\n\t\t\ttrack->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;\n\t\t\ttrack->f.compressionType = AF_COMPRESSION_IMA;\n\t\t\ttrack->f.byteOrder = _AF_BYTEORDER_NATIVE;\n\n\t\t\t/* Create the parameter list. */\n\t\t\tpv = AUpvnew(2);\n\t\t\tAUpvsetparam(pv, 0, _AF_SAMPLES_PER_BLOCK);\n\t\t\tAUpvsetvaltype(pv, 0, AU_PVTYPE_LONG);\n\t\t\tl = samplesPerBlock;\n\t\t\tAUpvsetval(pv, 0, &l);\n\n\t\t\tAUpvsetparam(pv, 1, _AF_BLOCK_SIZE);\n\t\t\tAUpvsetvaltype(pv, 1, AU_PVTYPE_LONG);\n\t\t\tl = blockAlign;\n\t\t\tAUpvsetval(pv, 1, &l);\n\n\t\t\ttrack->f.compressionParams = pv;\n\t\t}\n\t\tbreak;\n\n\t\tcase WAVE_FORMAT_YAMAHA_ADPCM:\n\t\tcase WAVE_FORMAT_OKI_ADPCM:\n\t\tcase WAVE_FORMAT_CREATIVE_ADPCM:\n\t\tcase IBM_FORMAT_ADPCM:\n\t\t\t_af_error(AF_BAD_NOT_IMPLEMENTED, \"WAVE ADPCM data format 0x%x is not currently supported\", formatTag);\n\t\t\treturn AF_FAIL;\n\t\t\tbreak;\n\n\t\tcase WAVE_FORMAT_MPEG:\n\t\t\t_af_error(AF_BAD_NOT_IMPLEMENTED, \"WAVE MPEG data format is not supported\");\n\t\t\treturn AF_FAIL;\n\t\t\tbreak;\n\n\t\tcase WAVE_FORMAT_MPEGLAYER3:\n\t\t\t_af_error(AF_BAD_NOT_IMPLEMENTED, \"WAVE MPEG layer 3 data format is not supported\");\n\t\t\treturn AF_FAIL;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\t_af_error(AF_BAD_NOT_IMPLEMENTED, \"WAVE file data format 0x%x not currently supported\", formatTag);\n\t\t\treturn AF_FAIL;\n\t\t\tbreak;\n\t}\n\n\t_af_set_sample_format(&track->f, track->f.sampleFormat, track->f.sampleWidth);\n\n\treturn AF_SUCCEED;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], '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: struct nfs_server *nfs4_create_referral_server(struct nfs_clone_mount *data,\n\t\t\t\t\t struct nfs_fh *mntfh)\n{\n\tstruct nfs_client *parent_client;\n\tstruct nfs_server *server, *parent_server;\n\tstruct nfs_fattr fattr;\n\tint error;\n\n\tdprintk(\"--> nfs4_create_referral_server()\\n\");\n\n\tserver = nfs_alloc_server();\n\tif (!server)\n\t\treturn ERR_PTR(-ENOMEM);\n\n\tparent_server = NFS_SB(data->sb);\n\tparent_client = parent_server->nfs_client;\n\n\t/* Get a client representation.\n\t * Note: NFSv4 always uses TCP, */\n\terror = nfs4_set_client(server, data->hostname, data->addr,\n\t\t\tparent_client->cl_ipaddr,\n\t\t\tdata->authflavor,\n\t\t\tparent_server->client->cl_xprt->prot,\n\t\t\tparent_client->retrans_timeo,\n\t\t\tparent_client->retrans_count);\n\tif (error < 0)\n\t\tgoto error;\n\n\t/* Initialise the client representation from the parent server */\n\tnfs_server_copy_userdata(server, parent_server);\n\tserver->caps |= NFS_CAP_ATOMIC_OPEN;\n\n\terror = nfs_init_server_rpcclient(server, data->authflavor);\n\tif (error < 0)\n\t\tgoto error;\n\n\tBUG_ON(!server->nfs_client);\n\tBUG_ON(!server->nfs_client->rpc_ops);\n\tBUG_ON(!server->nfs_client->rpc_ops->file_inode_ops);\n\n\t/* Probe the root fh to retrieve its FSID and filehandle */\n\terror = nfs4_path_walk(server, mntfh, data->mnt_path);\n\tif (error < 0)\n\t\tgoto error;\n\n\t/* probe the filesystem info for this server filesystem */\n\terror = nfs_probe_fsinfo(server, mntfh, &fattr);\n\tif (error < 0)\n\t\tgoto error;\n\n\tdprintk(\"Referral FSID: %llx:%llx\\n\",\n\t\t(unsigned long long) server->fsid.major,\n\t\t(unsigned long long) server->fsid.minor);\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_create_referral_server() = %p\\n\", server);\n\treturn server;\n\nerror:\n\tnfs_free_server(server);\n\tdprintk(\"<-- nfs4_create_referral_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: int huft_build(b, n, s, d, e, t, m)\nunsigned *b; /* code lengths in bits (all assumed <= BMAX) */\nunsigned n; /* number of codes (assumed <= N_MAX) */\nunsigned s; /* number of simple-valued codes (0..s-1) */\nush *d; /* list of base values for non-simple codes */\nush *e; /* list of extra bits for non-simple codes */\nstruct huft **t; /* result: starting table */\nint *m; /* maximum lookup bits, returns actual */\n/* Given a list of code lengths and a maximum table size, make a set of\n tables to decode that set of codes. Return zero on success, one if\n the given code set is incomplete (the tables are still built in this\n case), two if the input is invalid (all zero length codes or an\n oversubscribed set of lengths), and three if not enough memory. */\n{\n unsigned a; /* counter for codes of length k */\n unsigned c[BMAX+1]; /* bit length count table */\n unsigned f; /* i repeats in table every f entries */\n int g; /* maximum code length */\n int h; /* table level */\n register unsigned i; /* counter, current code */\n register unsigned j; /* counter */\n register int k; /* number of bits in current code */\n int l; /* bits per table (returned in m) */\n register unsigned *p; /* pointer into c[], b[], or v[] */\n register struct huft *q; /* points to current table */\n struct huft r; /* table entry for structure assignment */\n struct huft *u[BMAX]; /* table stack */\n unsigned v[N_MAX]; /* values in order of bit length */\n register int w; /* bits before this table == (l * h) */\n unsigned x[BMAX+1]; /* bit offsets, then code stack */\n unsigned *xp; /* pointer into x */\n int y; /* number of dummy codes added */\n unsigned z; /* number of entries in current table */\n\n\n /* Generate counts for each bit length */\n memzero(c, sizeof(c));\n p = b; i = n;\n do {\n Tracecv(*p, (stderr, (n-i >= ' ' && n-i <= '~' ? \"%c %d\\n\" : \"0x%x %d\\n\"),\n\t n-i, *p));\n c[*p]++; /* assume all entries <= BMAX */\n p++; /* Can't combine with above line (Solaris bug) */\n } while (--i);\n if (c[0] == n) /* null input--all zero length codes */\n {\n q = (struct huft *) malloc (2 * sizeof *q);\n if (!q)\n return 3;\n hufts += 2;\n q[0].v.t = (struct huft *) NULL;\n q[1].e = 99; /* invalid code marker */\n q[1].b = 1;\n *t = q + 1;\n *m = 1;\n return 0;\n }\n\n\n /* Find minimum and maximum length, bound *m by those */\n l = *m;\n for (j = 1; j <= BMAX; j++)\n if (c[j])\n break;\n k = j; /* minimum code length */\n if ((unsigned)l < j)\n l = j;\n for (i = BMAX; i; i--)\n if (c[i])\n break;\n g = i; /* maximum code length */\n if ((unsigned)l > i)\n l = i;\n *m = l;\n\n\n /* Adjust last length count to fill out codes, if needed */\n for (y = 1 << j; j < i; j++, y <<= 1)\n if ((y -= c[j]) < 0)\n return 2; /* bad input: more codes than bits */\n if ((y -= c[i]) < 0)\n return 2;\n c[i] += y;\n\n\n /* Generate starting offsets into the value table for each length */\n x[1] = j = 0;\n p = c + 1; xp = x + 2;\n while (--i) { /* note that i == g from above */\n *xp++ = (j += *p++);\n }\n\n\n /* Make a table of values in order of bit lengths */\n p = b; i = 0;\n do {\n if ((j = *p++) != 0)\n v[x[j]++] = i;\n } while (++i < n);\n n = x[g]; /* set n to length of v */\n\n\n /* Generate the Huffman codes and for each, make the table entries */\n x[0] = i = 0; /* first Huffman code is zero */\n p = v; /* grab values in bit order */\n h = -1; /* no tables yet--level -1 */\n w = -l; /* bits decoded == (l * h) */\n u[0] = (struct huft *)NULL; /* just to keep compilers happy */\n q = (struct huft *)NULL; /* ditto */\n z = 0; /* ditto */\n\n /* go through the bit lengths (k already is bits in shortest code) */\n for (; k <= g; k++)\n {\n a = c[k];\n while (a--)\n {\n /* here i is the Huffman code of length k bits for value *p */\n /* make tables up to required level */\n while (k > w + l)\n {\n h++;\n w += l; /* previous table always l bits */\n\n /* compute minimum size table less than or equal to l bits */\n z = (z = g - w) > (unsigned)l ? l : z; /* upper limit on table size */\n if ((f = 1 << (j = k - w)) > a + 1) /* try a k-w bit table */\n { /* too few codes for k-w bit table */\n f -= a + 1; /* deduct codes from patterns left */\n xp = c + k;\n\t if (j < z)\n\t while (++j < z) /* try smaller tables up to z bits */\n\t {\n\t if ((f <<= 1) <= *++xp)\n\t\tbreak; /* enough codes to use up j bits */\n\t f -= *xp; /* else deduct codes from patterns */\n\t }\n }\n z = 1 << j; /* table entries for j-bit table */\n\n /* allocate and link in new table */\n if ((q = (struct huft *)malloc((z + 1)*sizeof(struct huft))) ==\n (struct huft *)NULL)\n {\n if (h)\n huft_free(u[0]);\n return 3; /* not enough memory */\n }\n hufts += z + 1; /* track memory usage */\n *t = q + 1; /* link to list for huft_free() */\n *(t = &(q->v.t)) = (struct huft *)NULL;\n u[h] = ++q; /* table starts after link */\n\n /* connect to last table, if there is one */\n if (h)\n {\n x[h] = i; /* save pattern for backing up */\n r.b = (uch)l; /* bits to dump before this table */\n r.e = (uch)(16 + j); /* bits in this table */\n r.v.t = q; /* pointer to this table */\n j = i >> (w - l); /* (get around Turbo C bug) */\n u[h-1][j] = r; /* connect to last table */\n }\n }\n\n /* set up table entry in r */\n r.b = (uch)(k - w);\n if (p >= v + n)\n r.e = 99; /* out of values--invalid code */\n else if (*p < s)\n {\n r.e = (uch)(*p < 256 ? 16 : 15); /* 256 is end-of-block code */\n r.v.n = (ush)(*p); /* simple code is just the value */\n\tp++; /* one compiler does not like *p++ */\n }\n else\n {\n r.e = (uch)e[*p - s]; /* non-simple--look up in lists */\n r.v.n = d[*p++ - s];\n }\n\n /* fill code-like entries with r */\n f = 1 << (k - w);\n for (j = i >> w; j < z; j += f)\n q[j] = r;\n\n /* backwards increment the k-bit code i */\n for (j = 1 << (k - 1); i & j; j >>= 1)\n i ^= j;\n i ^= j;\n\n /* backup over finished tables */\n while ((i & ((1 << w) - 1)) != x[h])\n {\n h--; /* don't need to update q */\n w -= l;\n }\n }\n }\n\n\n /* Return true (1) if we were given an incomplete table */\n return y != 0 && g != 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'avoid creating an undersized buffer for the hufts table\n\nA malformed input file can cause gzip to crash with a segmentation\nviolation or hang in an endless loop.\nReported in .\n* NEWS (Bug fixes): Mention 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 nr_getname(struct socket *sock, struct sockaddr *uaddr,\n\tint *uaddr_len, int peer)\n{\n\tstruct full_sockaddr_ax25 *sax = (struct full_sockaddr_ax25 *)uaddr;\n\tstruct sock *sk = sock->sk;\n\tstruct nr_sock *nr = nr_sk(sk);\n\n\tlock_sock(sk);\n\tif (peer != 0) {\n\t\tif (sk->sk_state != TCP_ESTABLISHED) {\n\t\t\trelease_sock(sk);\n\t\t\treturn -ENOTCONN;\n\t\t}\n\t\tsax->fsa_ax25.sax25_family = AF_NETROM;\n\t\tsax->fsa_ax25.sax25_ndigis = 1;\n\t\tsax->fsa_ax25.sax25_call = nr->user_addr;\n\t\tsax->fsa_digipeater[0] = nr->dest_addr;\n\t\t*uaddr_len = sizeof(struct full_sockaddr_ax25);\n\t} else {\n\t\tsax->fsa_ax25.sax25_family = AF_NETROM;\n\t\tsax->fsa_ax25.sax25_ndigis = 0;\n\t\tsax->fsa_ax25.sax25_call = nr->source_addr;\n\t\t*uaddr_len = sizeof(struct sockaddr_ax25);\n\t}\n\trelease_sock(sk);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'netrom: Fix nr_getname() leak\n\nnr_getname() can leak kernel memory to user.\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: static __inline__ int cbq_dump_police(struct sk_buff *skb, struct cbq_class *cl)\n{\n\tunsigned char\t *b = skb->tail;\n\tstruct tc_cbq_police opt;\n\n\tif (cl->police) {\n\t\topt.police = cl->police;\n\t\tRTA_PUT(skb, TCA_CBQ_POLICE, sizeof(opt), &opt);\n\t}\n\treturn skb->len;\n\nrtattr_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: __rta_reserve(struct sk_buff *skb, int attrtype, int attrlen)\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\treturn rta;\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\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: check for invalid characters in device name and mountpoint\n\nIt's apparently possible to corrupt the mtab if you pass embedded\nnewlines to addmntent. Apparently tabs are also a problem with certain\nearlier glibc versions. Backslashes are also a minor issue apparently,\nbut we can't reasonably filter those.\n\nMake sure that neither the devname or mountpoint contain any problematic\ncharacters before allowing the mount to proceed.\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: x86_decode_insn(struct x86_emulate_ctxt *ctxt, struct x86_emulate_ops *ops)\n{\n\tstruct decode_cache *c = &ctxt->decode;\n\tint rc = 0;\n\tint mode = ctxt->mode;\n\tint def_op_bytes, def_ad_bytes, group;\n\n\t/* Shadow copy of register state. Committed on successful emulation. */\n\n\tmemset(c, 0, sizeof(struct decode_cache));\n\tc->eip = kvm_rip_read(ctxt->vcpu);\n\tctxt->cs_base = seg_base(ctxt, VCPU_SREG_CS);\n\tmemcpy(c->regs, ctxt->vcpu->arch.regs, sizeof c->regs);\n\n\tswitch (mode) {\n\tcase X86EMUL_MODE_REAL:\n\tcase X86EMUL_MODE_PROT16:\n\t\tdef_op_bytes = def_ad_bytes = 2;\n\t\tbreak;\n\tcase X86EMUL_MODE_PROT32:\n\t\tdef_op_bytes = def_ad_bytes = 4;\n\t\tbreak;\n#ifdef CONFIG_X86_64\n\tcase X86EMUL_MODE_PROT64:\n\t\tdef_op_bytes = 4;\n\t\tdef_ad_bytes = 8;\n\t\tbreak;\n#endif\n\tdefault:\n\t\treturn -1;\n\t}\n\n\tc->op_bytes = def_op_bytes;\n\tc->ad_bytes = def_ad_bytes;\n\n\t/* Legacy prefixes. */\n\tfor (;;) {\n\t\tswitch (c->b = insn_fetch(u8, 1, c->eip)) {\n\t\tcase 0x66:\t/* operand-size override */\n\t\t\t/* switch between 2/4 bytes */\n\t\t\tc->op_bytes = def_op_bytes ^ 6;\n\t\t\tbreak;\n\t\tcase 0x67:\t/* address-size override */\n\t\t\tif (mode == X86EMUL_MODE_PROT64)\n\t\t\t\t/* switch between 4/8 bytes */\n\t\t\t\tc->ad_bytes = def_ad_bytes ^ 12;\n\t\t\telse\n\t\t\t\t/* switch between 2/4 bytes */\n\t\t\t\tc->ad_bytes = def_ad_bytes ^ 6;\n\t\t\tbreak;\n\t\tcase 0x26:\t/* ES override */\n\t\tcase 0x2e:\t/* CS override */\n\t\tcase 0x36:\t/* SS override */\n\t\tcase 0x3e:\t/* DS override */\n\t\t\tset_seg_override(c, (c->b >> 3) & 3);\n\t\t\tbreak;\n\t\tcase 0x64:\t/* FS override */\n\t\tcase 0x65:\t/* GS override */\n\t\t\tset_seg_override(c, c->b & 7);\n\t\t\tbreak;\n\t\tcase 0x40 ... 0x4f: /* REX */\n\t\t\tif (mode != X86EMUL_MODE_PROT64)\n\t\t\t\tgoto done_prefixes;\n\t\t\tc->rex_prefix = c->b;\n\t\t\tcontinue;\n\t\tcase 0xf0:\t/* LOCK */\n\t\t\tc->lock_prefix = 1;\n\t\t\tbreak;\n\t\tcase 0xf2:\t/* REPNE/REPNZ */\n\t\t\tc->rep_prefix = REPNE_PREFIX;\n\t\t\tbreak;\n\t\tcase 0xf3:\t/* REP/REPE/REPZ */\n\t\t\tc->rep_prefix = REPE_PREFIX;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tgoto done_prefixes;\n\t\t}\n\n\t\t/* Any legacy prefix after a REX prefix nullifies its effect. */\n\n\t\tc->rex_prefix = 0;\n\t}\n\ndone_prefixes:\n\n\t/* REX prefix. */\n\tif (c->rex_prefix)\n\t\tif (c->rex_prefix & 8)\n\t\t\tc->op_bytes = 8;\t/* REX.W */\n\n\t/* Opcode byte(s). */\n\tc->d = opcode_table[c->b];\n\tif (c->d == 0) {\n\t\t/* Two-byte opcode? */\n\t\tif (c->b == 0x0f) {\n\t\t\tc->twobyte = 1;\n\t\t\tc->b = insn_fetch(u8, 1, c->eip);\n\t\t\tc->d = twobyte_table[c->b];\n\t\t}\n\t}\n\n\tif (mode == X86EMUL_MODE_PROT64 && (c->d & No64)) {\n\t\tkvm_report_emulation_failure(ctxt->vcpu, \"invalid x86/64 instruction\");;\n\t\treturn -1;\n\t}\n\n\tif (c->d & Group) {\n\t\tgroup = c->d & GroupMask;\n\t\tc->modrm = insn_fetch(u8, 1, c->eip);\n\t\t--c->eip;\n\n\t\tgroup = (group << 3) + ((c->modrm >> 3) & 7);\n\t\tif ((c->d & GroupDual) && (c->modrm >> 6) == 3)\n\t\t\tc->d = group2_table[group];\n\t\telse\n\t\t\tc->d = group_table[group];\n\t}\n\n\t/* Unrecognised? */\n\tif (c->d == 0) {\n\t\tDPRINTF(\"Cannot emulate %02x\\n\", c->b);\n\t\treturn -1;\n\t}\n\n\tif (mode == X86EMUL_MODE_PROT64 && (c->d & Stack))\n\t\tc->op_bytes = 8;\n\n\t/* ModRM and SIB bytes. */\n\tif (c->d & ModRM)\n\t\trc = decode_modrm(ctxt, ops);\n\telse if (c->d & MemAbs)\n\t\trc = decode_abs(ctxt, ops);\n\tif (rc)\n\t\tgoto done;\n\n\tif (!c->has_seg_override)\n\t\tset_seg_override(c, VCPU_SREG_DS);\n\n\tif (!(!c->twobyte && c->b == 0x8d))\n\t\tc->modrm_ea += seg_override_base(ctxt, c);\n\n\tif (c->ad_bytes != 8)\n\t\tc->modrm_ea = (u32)c->modrm_ea;\n\t/*\n\t * Decode and fetch the source operand: register, memory\n\t * or immediate.\n\t */\n\tswitch (c->d & SrcMask) {\n\tcase SrcNone:\n\t\tbreak;\n\tcase SrcReg:\n\t\tdecode_register_operand(&c->src, c, 0);\n\t\tbreak;\n\tcase SrcMem16:\n\t\tc->src.bytes = 2;\n\t\tgoto srcmem_common;\n\tcase SrcMem32:\n\t\tc->src.bytes = 4;\n\t\tgoto srcmem_common;\n\tcase SrcMem:\n\t\tc->src.bytes = (c->d & ByteOp) ? 1 :\n\t\t\t\t\t\t\t c->op_bytes;\n\t\t/* Don't fetch the address for invlpg: it could be unmapped. */\n\t\tif (c->twobyte && c->b == 0x01 && c->modrm_reg == 7)\n\t\t\tbreak;\n\tsrcmem_common:\n\t\t/*\n\t\t * For instructions with a ModR/M byte, switch to register\n\t\t * access if Mod = 3.\n\t\t */\n\t\tif ((c->d & ModRM) && c->modrm_mod == 3) {\n\t\t\tc->src.type = OP_REG;\n\t\t\tc->src.val = c->modrm_val;\n\t\t\tc->src.ptr = c->modrm_ptr;\n\t\t\tbreak;\n\t\t}\n\t\tc->src.type = OP_MEM;\n\t\tbreak;\n\tcase SrcImm:\n\tcase SrcImmU:\n\t\tc->src.type = OP_IMM;\n\t\tc->src.ptr = (unsigned long *)c->eip;\n\t\tc->src.bytes = (c->d & ByteOp) ? 1 : c->op_bytes;\n\t\tif (c->src.bytes == 8)\n\t\t\tc->src.bytes = 4;\n\t\t/* NB. Immediates are sign-extended as necessary. */\n\t\tswitch (c->src.bytes) {\n\t\tcase 1:\n\t\t\tc->src.val = insn_fetch(s8, 1, c->eip);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tc->src.val = insn_fetch(s16, 2, c->eip);\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tc->src.val = insn_fetch(s32, 4, c->eip);\n\t\t\tbreak;\n\t\t}\n\t\tif ((c->d & SrcMask) == SrcImmU) {\n\t\t\tswitch (c->src.bytes) {\n\t\t\tcase 1:\n\t\t\t\tc->src.val &= 0xff;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tc->src.val &= 0xffff;\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\tc->src.val &= 0xffffffff;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase SrcImmByte:\n\tcase SrcImmUByte:\n\t\tc->src.type = OP_IMM;\n\t\tc->src.ptr = (unsigned long *)c->eip;\n\t\tc->src.bytes = 1;\n\t\tif ((c->d & SrcMask) == SrcImmByte)\n\t\t\tc->src.val = insn_fetch(s8, 1, c->eip);\n\t\telse\n\t\t\tc->src.val = insn_fetch(u8, 1, c->eip);\n\t\tbreak;\n\tcase SrcOne:\n\t\tc->src.bytes = 1;\n\t\tc->src.val = 1;\n\t\tbreak;\n\t}\n\n\t/*\n\t * Decode and fetch the second source operand: register, memory\n\t * or immediate.\n\t */\n\tswitch (c->d & Src2Mask) {\n\tcase Src2None:\n\t\tbreak;\n\tcase Src2CL:\n\t\tc->src2.bytes = 1;\n\t\tc->src2.val = c->regs[VCPU_REGS_RCX] & 0x8;\n\t\tbreak;\n\tcase Src2ImmByte:\n\t\tc->src2.type = OP_IMM;\n\t\tc->src2.ptr = (unsigned long *)c->eip;\n\t\tc->src2.bytes = 1;\n\t\tc->src2.val = insn_fetch(u8, 1, c->eip);\n\t\tbreak;\n\tcase Src2Imm16:\n\t\tc->src2.type = OP_IMM;\n\t\tc->src2.ptr = (unsigned long *)c->eip;\n\t\tc->src2.bytes = 2;\n\t\tc->src2.val = insn_fetch(u16, 2, c->eip);\n\t\tbreak;\n\tcase Src2One:\n\t\tc->src2.bytes = 1;\n\t\tc->src2.val = 1;\n\t\tbreak;\n\t}\n\n\t/* Decode and fetch the destination operand: register or memory. */\n\tswitch (c->d & DstMask) {\n\tcase ImplicitOps:\n\t\t/* Special instructions do their own operand decoding. */\n\t\treturn 0;\n\tcase DstReg:\n\t\tdecode_register_operand(&c->dst, c,\n\t\t\t c->twobyte && (c->b == 0xb6 || c->b == 0xb7));\n\t\tbreak;\n\tcase DstMem:\n\t\tif ((c->d & ModRM) && c->modrm_mod == 3) {\n\t\t\tc->dst.bytes = (c->d & ByteOp) ? 1 : c->op_bytes;\n\t\t\tc->dst.type = OP_REG;\n\t\t\tc->dst.val = c->dst.orig_val = c->modrm_val;\n\t\t\tc->dst.ptr = c->modrm_ptr;\n\t\t\tbreak;\n\t\t}\n\t\tc->dst.type = OP_MEM;\n\t\tbreak;\n\tcase DstAcc:\n\t\tc->dst.type = OP_REG;\n\t\tc->dst.bytes = c->op_bytes;\n\t\tc->dst.ptr = &c->regs[VCPU_REGS_RAX];\n\t\tswitch (c->op_bytes) {\n\t\t\tcase 1:\n\t\t\t\tc->dst.val = *(u8 *)c->dst.ptr;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tc->dst.val = *(u16 *)c->dst.ptr;\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\tc->dst.val = *(u32 *)c->dst.ptr;\n\t\t\t\tbreak;\n\t\t}\n\t\tc->dst.orig_val = c->dst.val;\n\t\tbreak;\n\t}\n\n\tif (c->rip_relative)\n\t\tc->modrm_ea += c->eip;\n\ndone:\n\treturn (rc == X86EMUL_UNHANDLEABLE) ? -1 : 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: add_connection_real (NMAGConfSettings *self, NMAGConfConnection *connection)\n{\n\tNMAGConfSettingsPrivate *priv = NMA_GCONF_SETTINGS_GET_PRIVATE (self);\n\n\tg_return_if_fail (connection != NULL);\n\n\tpriv->connections = g_slist_prepend (priv->connections, connection);\n\tg_signal_connect (connection, \"new-secrets-requested\",\n\t\t\t\t G_CALLBACK (connection_new_secrets_requested_cb),\n\t\t\t\t self);\n\n\tg_signal_connect (connection, \"removed\", G_CALLBACK (connection_removed), self);\n\n\t/* Export the connection over dbus if requested */\n\tif (priv->bus) {\n\t\tnm_exported_connection_register_object (NM_EXPORTED_CONNECTION (connection),\n\t\t NM_CONNECTION_SCOPE_USER,\n\t\t priv->bus);\n\t\tdbus_g_connection_unref (priv->bus);\n\t}\n\n\tnm_settings_signal_new_connection (NM_SETTINGS (self), NM_EXPORTED_CONNECTION (connection));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'applet: fix dbus connection refcounting after 8627880e07c8345f69ed639325280c7f62a8f894'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: get_settings (NMExportedConnection *exported)\n{\n\tNMConnection *connection;\n\tGHashTable *settings;\n\n\tconnection = nm_exported_connection_get_connection (exported);\n\n\tutils_fill_connection_certs (connection);\n\tsettings = nm_connection_to_hash (connection);\n\tutils_clear_filled_connection_certs (connection);\n\n\treturn settings;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'core: fix CA cert mishandling after cert file deletion (deb #560067) (rh #546793)\n\nIf a connection was created with a CA certificate, but the user later\nmoved or deleted that CA certificate, the applet would simply provide the\nconnection to NetworkManager without any CA certificate. This could cause\nNM to connect to the original network (or a network spoofing the original\nnetwork) without verifying the identity of the network as the user\nexpects.\n\nIn the future we can/should do better here by (1) alerting the user that\nsome connection is now no longer complete by flagging it in the connection\neditor or notifying the user somehow, and (2) by using a freaking' cert\nstore already (not that Linux has one yet).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: hb_ot_layout_build_glyph_classes (hb_face_t *face,\n\t\t\t\t uint16_t num_total_glyphs,\n\t\t\t\t hb_codepoint_t *glyphs,\n\t\t\t\t unsigned char *klasses,\n\t\t\t\t uint16_t count)\n{\n if (HB_OBJECT_IS_INERT (face))\n return;\n\n hb_ot_layout_t *layout = &face->ot_layout;\n\n if (HB_UNLIKELY (!count || !glyphs || !klasses))\n return;\n\n if (layout->new_gdef.len == 0) {\n layout->new_gdef.klasses = (unsigned char *) calloc (num_total_glyphs, sizeof (unsigned char));\n layout->new_gdef.len = count;\n }\n\n for (unsigned int i = 0; i < count; i++)\n _hb_ot_layout_set_glyph_class (face, glyphs[i], (hb_ot_layout_glyph_class_t) klasses[i]);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': '[HB/GDEF] Fix bug in building synthetic GDEF table'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _gnutls_x509_oid2mac_algorithm (const char *oid)\n{\n gnutls_mac_algorithm_t ret = 0;\n\n GNUTLS_HASH_LOOP (if (strcmp (oid, p->oid) == 0)\n\t\t {\n\t\t ret = p->id; break;}\n );\n\n if (ret == 0)\n return GNUTLS_MAC_UNKNOWN;\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': '(_gnutls_x509_oid2mac_algorithm): Don't crash trying to strcmp the\nNULL OID value in the hash_algorithms array, which happens when the\ninput OID doesn't match our OIDs for SHA1, MD5, MD2 or RIPEMD160.\nReported by satyakumar .'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int Server::getUserID(const QString &name) {\n\tif (qhUserIDCache.contains(name))\n\t\treturn qhUserIDCache.value(name);\n\tint id = -2;\n\temit nameToIdSig(id, name);\n\tif (id != -2) {\n\t\tqhUserIDCache.insert(name, id);\n\t\tqhUserNameCache.insert(id, name);\n\t\treturn id;\n\t}\n\tTransactionHolder th;\n\n\tQSqlQuery &query = *th.qsqQuery;\n\tSQLPREP(\"SELECT `user_id` FROM `%1users` WHERE `server_id` = ? AND `name` like ?\");\n\tquery.addBindValue(iServerNum);\n\tquery.addBindValue(name);\n\tSQLEXEC();\n\tif (query.next()) {\n\t\tid = query.value(0).toInt();\n\t\tqhUserIDCache.insert(name, id);\n\t\tqhUserNameCache.insert(id, name);\n\t}\n\treturn id;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Don't crash on long usernames'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: long keyctl_session_to_parent(void)\n{\n#ifdef TIF_NOTIFY_RESUME\n\tstruct task_struct *me, *parent;\n\tconst struct cred *mycred, *pcred;\n\tstruct cred *cred, *oldcred;\n\tkey_ref_t keyring_r;\n\tint ret;\n\n\tkeyring_r = lookup_user_key(KEY_SPEC_SESSION_KEYRING, 0, KEY_LINK);\n\tif (IS_ERR(keyring_r))\n\t\treturn PTR_ERR(keyring_r);\n\n\t/* our parent is going to need a new cred struct, a new tgcred struct\n\t * and new security data, so we allocate them here to prevent ENOMEM in\n\t * our parent */\n\tret = -ENOMEM;\n\tcred = cred_alloc_blank();\n\tif (!cred)\n\t\tgoto error_keyring;\n\n\tcred->tgcred->session_keyring = key_ref_to_ptr(keyring_r);\n\tkeyring_r = NULL;\n\n\tme = current;\n\trcu_read_lock();\n\twrite_lock_irq(&tasklist_lock);\n\n\tparent = me->real_parent;\n\tret = -EPERM;\n\n\t/* the parent mustn't be init and mustn't be a kernel thread */\n\tif (parent->pid <= 1 || !parent->mm)\n\t\tgoto not_permitted;\n\n\t/* the parent must be single threaded */\n\tif (!thread_group_empty(parent))\n\t\tgoto not_permitted;\n\n\t/* the parent and the child must have different session keyrings or\n\t * there's no point */\n\tmycred = current_cred();\n\tpcred = __task_cred(parent);\n\tif (mycred == pcred ||\n\t mycred->tgcred->session_keyring == pcred->tgcred->session_keyring)\n\t\tgoto already_same;\n\n\t/* the parent must have the same effective ownership and mustn't be\n\t * SUID/SGID */\n\tif (pcred->uid\t!= mycred->euid\t||\n\t pcred->euid\t!= mycred->euid\t||\n\t pcred->suid\t!= mycred->euid\t||\n\t pcred->gid\t!= mycred->egid\t||\n\t pcred->egid\t!= mycred->egid\t||\n\t pcred->sgid\t!= mycred->egid)\n\t\tgoto not_permitted;\n\n\t/* the keyrings must have the same UID */\n\tif (pcred->tgcred->session_keyring->uid != mycred->euid ||\n\t mycred->tgcred->session_keyring->uid != mycred->euid)\n\t\tgoto not_permitted;\n\n\t/* if there's an already pending keyring replacement, then we replace\n\t * that */\n\toldcred = parent->replacement_session_keyring;\n\n\t/* the replacement session keyring is applied just prior to userspace\n\t * restarting */\n\tparent->replacement_session_keyring = cred;\n\tcred = NULL;\n\tset_ti_thread_flag(task_thread_info(parent), TIF_NOTIFY_RESUME);\n\n\twrite_unlock_irq(&tasklist_lock);\n\trcu_read_unlock();\n\tif (oldcred)\n\t\tput_cred(oldcred);\n\treturn 0;\n\nalready_same:\n\tret = 0;\nnot_permitted:\n\twrite_unlock_irq(&tasklist_lock);\n\trcu_read_unlock();\n\tput_cred(cred);\n\treturn ret;\n\nerror_keyring:\n\tkey_ref_put(keyring_r);\n\treturn ret;\n\n#else /* !TIF_NOTIFY_RESUME */\n\t/*\n\t * To be removed when TIF_NOTIFY_RESUME has been implemented on\n\t * m68k/xtensa\n\t */\n#warning TIF_NOTIFY_RESUME not implemented\n\treturn -EOPNOTSUPP;\n#endif /* !TIF_NOTIFY_RESUME */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'KEYS: Fix bug in keyctl_session_to_parent() if parent has no session keyring\n\nFix a bug in keyctl_session_to_parent() whereby it tries to check the ownership\nof the parent process's session keyring whether or not the parent has a session\nkeyring [CVE-2010-2960].\n\nThis results in the following oops:\n\n BUG: unable to handle kernel NULL pointer dereference at 00000000000000a0\n IP: [] keyctl_session_to_parent+0x251/0x443\n ...\n Call Trace:\n [] ? keyctl_session_to_parent+0x67/0x443\n [] ? __do_fault+0x24b/0x3d0\n [] sys_keyctl+0xb4/0xb8\n [] system_call_fastpath+0x16/0x1b\n\nif the parent process has no session keyring.\n\nIf the system is using pam_keyinit then it mostly protected against this as all\nprocesses derived from a login will have inherited the session keyring created\nby pam_keyinit during the log in procedure.\n\nTo test this, pam_keyinit calls need to be commented out in /etc/pam.d/.\n\nReported-by: Tavis Ormandy \nSigned-off-by: David Howells \nAcked-by: Tavis Ormandy \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 vmx_vcpu_setup(struct vcpu_vmx *vmx)\n{\n\tu32 host_sysenter_cs, msr_low, msr_high;\n\tu32 junk;\n\tu64 host_pat, tsc_this, tsc_base;\n\tunsigned long a;\n\tstruct desc_ptr dt;\n\tint i;\n\tunsigned long kvm_vmx_return;\n\tu32 exec_control;\n\n\t/* I/O */\n\tvmcs_write64(IO_BITMAP_A, __pa(vmx_io_bitmap_a));\n\tvmcs_write64(IO_BITMAP_B, __pa(vmx_io_bitmap_b));\n\n\tif (cpu_has_vmx_msr_bitmap())\n\t\tvmcs_write64(MSR_BITMAP, __pa(vmx_msr_bitmap_legacy));\n\n\tvmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */\n\n\t/* Control */\n\tvmcs_write32(PIN_BASED_VM_EXEC_CONTROL,\n\t\tvmcs_config.pin_based_exec_ctrl);\n\n\texec_control = vmcs_config.cpu_based_exec_ctrl;\n\tif (!vm_need_tpr_shadow(vmx->vcpu.kvm)) {\n\t\texec_control &= ~CPU_BASED_TPR_SHADOW;\n#ifdef CONFIG_X86_64\n\t\texec_control |= CPU_BASED_CR8_STORE_EXITING |\n\t\t\t\tCPU_BASED_CR8_LOAD_EXITING;\n#endif\n\t}\n\tif (!enable_ept)\n\t\texec_control |= CPU_BASED_CR3_STORE_EXITING |\n\t\t\t\tCPU_BASED_CR3_LOAD_EXITING |\n\t\t\t\tCPU_BASED_INVLPG_EXITING;\n\tvmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);\n\n\tif (cpu_has_secondary_exec_ctrls()) {\n\t\texec_control = vmcs_config.cpu_based_2nd_exec_ctrl;\n\t\tif (!vm_need_virtualize_apic_accesses(vmx->vcpu.kvm))\n\t\t\texec_control &=\n\t\t\t\t~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;\n\t\tif (vmx->vpid == 0)\n\t\t\texec_control &= ~SECONDARY_EXEC_ENABLE_VPID;\n\t\tif (!enable_ept) {\n\t\t\texec_control &= ~SECONDARY_EXEC_ENABLE_EPT;\n\t\t\tenable_unrestricted_guest = 0;\n\t\t}\n\t\tif (!enable_unrestricted_guest)\n\t\t\texec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;\n\t\tif (!ple_gap)\n\t\t\texec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;\n\t\tvmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);\n\t}\n\n\tif (ple_gap) {\n\t\tvmcs_write32(PLE_GAP, ple_gap);\n\t\tvmcs_write32(PLE_WINDOW, ple_window);\n\t}\n\n\tvmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, !!bypass_guest_pf);\n\tvmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, !!bypass_guest_pf);\n\tvmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */\n\n\tvmcs_writel(HOST_CR0, read_cr0() | X86_CR0_TS); /* 22.2.3 */\n\tvmcs_writel(HOST_CR4, read_cr4()); /* 22.2.3, 22.2.5 */\n\tvmcs_writel(HOST_CR3, read_cr3()); /* 22.2.3 FIXME: shadow tables */\n\n\tvmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */\n\tvmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */\n\tvmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */\n\tvmcs_write16(HOST_FS_SELECTOR, kvm_read_fs()); /* 22.2.4 */\n\tvmcs_write16(HOST_GS_SELECTOR, kvm_read_gs()); /* 22.2.4 */\n\tvmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */\n#ifdef CONFIG_X86_64\n\trdmsrl(MSR_FS_BASE, a);\n\tvmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */\n\trdmsrl(MSR_GS_BASE, a);\n\tvmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */\n#else\n\tvmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */\n\tvmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */\n#endif\n\n\tvmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */\n\n\tnative_store_idt(&dt);\n\tvmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */\n\n\tasm(\"mov $.Lkvm_vmx_return, %0\" : \"=r\"(kvm_vmx_return));\n\tvmcs_writel(HOST_RIP, kvm_vmx_return); /* 22.2.5 */\n\tvmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);\n\tvmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);\n\tvmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));\n\tvmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);\n\tvmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));\n\n\trdmsr(MSR_IA32_SYSENTER_CS, host_sysenter_cs, junk);\n\tvmcs_write32(HOST_IA32_SYSENTER_CS, host_sysenter_cs);\n\trdmsrl(MSR_IA32_SYSENTER_ESP, a);\n\tvmcs_writel(HOST_IA32_SYSENTER_ESP, a); /* 22.2.3 */\n\trdmsrl(MSR_IA32_SYSENTER_EIP, a);\n\tvmcs_writel(HOST_IA32_SYSENTER_EIP, a); /* 22.2.3 */\n\n\tif (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {\n\t\trdmsr(MSR_IA32_CR_PAT, msr_low, msr_high);\n\t\thost_pat = msr_low | ((u64) msr_high << 32);\n\t\tvmcs_write64(HOST_IA32_PAT, host_pat);\n\t}\n\tif (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {\n\t\trdmsr(MSR_IA32_CR_PAT, msr_low, msr_high);\n\t\thost_pat = msr_low | ((u64) msr_high << 32);\n\t\t/* Write the default value follow host pat */\n\t\tvmcs_write64(GUEST_IA32_PAT, host_pat);\n\t\t/* Keep arch.pat sync with GUEST_IA32_PAT */\n\t\tvmx->vcpu.arch.pat = host_pat;\n\t}\n\n\tfor (i = 0; i < NR_VMX_MSR; ++i) {\n\t\tu32 index = vmx_msr_index[i];\n\t\tu32 data_low, data_high;\n\t\tint j = vmx->nmsrs;\n\n\t\tif (rdmsr_safe(index, &data_low, &data_high) < 0)\n\t\t\tcontinue;\n\t\tif (wrmsr_safe(index, data_low, data_high) < 0)\n\t\t\tcontinue;\n\t\tvmx->guest_msrs[j].index = i;\n\t\tvmx->guest_msrs[j].data = 0;\n\t\tvmx->guest_msrs[j].mask = -1ull;\n\t\t++vmx->nmsrs;\n\t}\n\n\tvmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);\n\n\t/* 22.2.1, 20.8.1 */\n\tvmcs_write32(VM_ENTRY_CONTROLS, vmcs_config.vmentry_ctrl);\n\n\tvmcs_writel(CR0_GUEST_HOST_MASK, ~0UL);\n\tvmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;\n\tif (enable_ept)\n\t\tvmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;\n\tvmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);\n\n\ttsc_base = vmx->vcpu.kvm->arch.vm_init_tsc;\n\trdtscll(tsc_this);\n\tif (tsc_this < vmx->vcpu.kvm->arch.vm_init_tsc)\n\t\ttsc_base = tsc_this;\n\n\tguest_write_tsc(0, tsc_base);\n\n\treturn 0;\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: */\nxmlNodePtr\nxmlXPathNextFollowing(xmlXPathParserContextPtr ctxt, xmlNodePtr cur) {\n if ((ctxt == NULL) || (ctxt->context == NULL)) return(NULL);\n if ((ctxt->context->node->type == XML_ATTRIBUTE_NODE) ||\n\t(ctxt->context->node->type == XML_NAMESPACE_DECL))\n\treturn(NULL);\n if (cur != NULL) {\n if ((cur->type == XML_ATTRIBUTE_NODE) ||\n (cur->type == XML_NAMESPACE_DECL))\n return(NULL);\n if (cur->children != NULL)\n return cur->children ;\n }\n if (cur == NULL) cur = ctxt->context->node;\n if (cur == NULL) return(NULL) ; /* ERROR */\n if (cur->next != NULL) return(cur->next) ;\n do {\n cur = cur->parent;\n if (cur == NULL) break;\n if (cur == (xmlNodePtr) ctxt->context->doc) return(NULL);\n if (cur->next != NULL) return(cur->next);\n } while (cur != NULL); ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix a change of semantic on XPath preceding and following axis\n\nThis was introduced in the prevous fix, while preceding-sibling and\nfollowing sibling axis are empty for attributes and namespaces,\npreceding and following axis should still work based on the parent\nelement. However the parent element is not available for a namespace\nnode, so we keep the axis empty in that case.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int sk_receive_skb(struct sock *sk, struct sk_buff *skb, const int nested)\n{\n\tint rc = NET_RX_SUCCESS;\n\n\tif (sk_filter(sk, skb))\n\t\tgoto discard_and_relse;\n\n\tskb->dev = NULL;\n\n\tif (nested)\n\t\tbh_lock_sock_nested(sk);\n\telse\n\t\tbh_lock_sock(sk);\n\tif (!sock_owned_by_user(sk)) {\n\t\t/*\n\t\t * trylock + unlock semantics:\n\t\t */\n\t\tmutex_acquire(&sk->sk_lock.dep_map, 0, 1, _RET_IP_);\n\n\t\trc = sk_backlog_rcv(sk, skb);\n\n\t\tmutex_release(&sk->sk_lock.dep_map, 1, _RET_IP_);\n\t} else if (sk_add_backlog(sk, skb)) {\n\t\tbh_unlock_sock(sk);\n\t\tatomic_inc(&sk->sk_drops);\n\t\tgoto discard_and_relse;\n\t}\n\n\tbh_unlock_sock(sk);\nout:\n\tsock_put(sk);\n\treturn rc;\ndiscard_and_relse:\n\tkfree_skb(skb);\n\tgoto out;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'net: sk_add_backlog() take rmem_alloc into account\n\nCurrent socket backlog limit is not enough to really stop DDOS attacks,\nbecause user thread spend many time to process a full backlog each\nround, and user might crazy spin on socket lock.\n\nWe should add backlog size and receive_queue size (aka rmem_alloc) to\npace writers, and let user run without being slow down too much.\n\nIntroduce a sk_rcvqueues_full() helper, to avoid taking socket lock in\nstress situations.\n\nUnder huge stress from a multiqueue/RPS enabled NIC, a single flow udp\nreceiver can now process ~200.000 pps (instead of ~100 pps before the\npatch) on a 8 core machine.\n\nSigned-off-by: Eric Dumazet \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: readconf_main(void)\n{\nint sep = 0;\nstruct stat statbuf;\nuschar *s, *filename;\nuschar *list = config_main_filelist;\n\n/* Loop through the possible file names */\n\nwhile((filename = string_nextinlist(&list, &sep, big_buffer, big_buffer_size))\n != NULL)\n {\n /* Cut out all the fancy processing unless specifically wanted */\n\n #if defined(CONFIGURE_FILE_USE_NODE) || defined(CONFIGURE_FILE_USE_EUID)\n uschar *suffix = filename + Ustrlen(filename);\n\n /* Try for the node-specific file if a node name exists */\n\n #ifdef CONFIGURE_FILE_USE_NODE\n struct utsname uts;\n if (uname(&uts) >= 0)\n {\n #ifdef CONFIGURE_FILE_USE_EUID\n sprintf(CS suffix, \".%ld.%.256s\", (long int)original_euid, uts.nodename);\n config_file = Ufopen(filename, \"rb\");\n if (config_file == NULL)\n #endif /* CONFIGURE_FILE_USE_EUID */\n {\n sprintf(CS suffix, \".%.256s\", uts.nodename);\n config_file = Ufopen(filename, \"rb\");\n }\n }\n #endif /* CONFIGURE_FILE_USE_NODE */\n\n /* Otherwise, try the generic name, possibly with the euid added */\n\n #ifdef CONFIGURE_FILE_USE_EUID\n if (config_file == NULL)\n {\n sprintf(CS suffix, \".%ld\", (long int)original_euid);\n config_file = Ufopen(filename, \"rb\");\n }\n #endif /* CONFIGURE_FILE_USE_EUID */\n\n /* Finally, try the unadorned name */\n\n if (config_file == NULL)\n {\n *suffix = 0;\n config_file = Ufopen(filename, \"rb\");\n }\n #else /* if neither defined */\n\n /* This is the common case when the fancy processing is not included. */\n\n config_file = Ufopen(filename, \"rb\");\n #endif\n\n /* If the file does not exist, continue to try any others. For any other\n error, break out (and die). */\n\n if (config_file != NULL || errno != ENOENT) break;\n }\n\n/* On success, save the name for verification; config_filename is used when\nlogging configuration errors (it changes for .included files) whereas\nconfig_main_filename is the name shown by -bP. Failure to open a configuration\nfile is a serious disaster. */\n\nif (config_file != NULL)\n {\n config_filename = config_main_filename = string_copy(filename);\n }\nelse\n {\n if (filename == NULL)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"non-existent configuration file(s): \"\n \"%s\", config_main_filelist);\n else\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"%s\", string_open_failed(errno,\n \"configuration file %s\", filename));\n }\n\n/* Check the status of the file we have opened, unless it was specified on\nthe command line, in which case privilege was given away at the start. */\n\nif (!config_changed)\n {\n if (fstat(fileno(config_file), &statbuf) != 0)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to stat configuration file %s\",\n big_buffer);\n\n if ((statbuf.st_uid != root_uid && /* owner not root */\n statbuf.st_uid != exim_uid /* owner not exim */\n #ifdef CONFIGURE_OWNER\n && statbuf.st_uid != config_uid /* owner not the special one */\n #endif\n ) || /* or */\n (statbuf.st_gid != exim_gid /* group not exim & */\n #ifdef CONFIGURE_GROUP\n && statbuf.st_gid != config_gid /* group not the special one */\n #endif\n && (statbuf.st_mode & 020) != 0) || /* group writeable */\n /* or */\n ((statbuf.st_mode & 2) != 0)) /* world writeable */\n\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Exim configuration file %s has the \"\n \"wrong owner, group, or mode\", big_buffer);\n }\n\n/* Process the main configuration settings. They all begin with a lower case\nletter. If we see something starting with an upper case letter, it is taken as\na macro definition. */\n\nwhile ((s = get_config_line()) != NULL)\n {\n if (isupper(s[0])) read_macro_assignment(s);\n\n else if (Ustrncmp(s, \"domainlist\", 10) == 0)\n read_named_list(&domainlist_anchor, &domainlist_count,\n MAX_NAMED_LIST, s+10, US\"domain list\");\n\n else if (Ustrncmp(s, \"hostlist\", 8) == 0)\n read_named_list(&hostlist_anchor, &hostlist_count,\n MAX_NAMED_LIST, s+8, US\"host list\");\n\n else if (Ustrncmp(s, US\"addresslist\", 11) == 0)\n read_named_list(&addresslist_anchor, &addresslist_count,\n MAX_NAMED_LIST, s+11, US\"address list\");\n\n else if (Ustrncmp(s, US\"localpartlist\", 13) == 0)\n read_named_list(&localpartlist_anchor, &localpartlist_count,\n MAX_NAMED_LIST, s+13, US\"local part list\");\n\n else\n (void) readconf_handle_option(s, optionlist_config, optionlist_config_size,\n NULL, US\"main option \\\"%s\\\" unknown\");\n }\n\n\n/* If local_sender_retain is set, local_from_check must be unset. */\n\nif (local_sender_retain && local_from_check)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"both local_from_check and \"\n \"local_sender_retain are set; this combination is not allowed\");\n\n/* If the timezone string is empty, set it to NULL, implying no TZ variable\nwanted. */\n\nif (timezone_string != NULL && *timezone_string == 0) timezone_string = NULL;\n\n/* The max retry interval must not be greater than 24 hours. */\n\nif (retry_interval_max > 24*60*60) retry_interval_max = 24*60*60;\n\n/* remote_max_parallel must be > 0 */\n\nif (remote_max_parallel <= 0) remote_max_parallel = 1;\n\n/* Save the configured setting of freeze_tell, so we can re-instate it at the\nstart of a new SMTP message. */\n\nfreeze_tell_config = freeze_tell;\n\n/* The primary host name may be required for expansion of spool_directory\nand log_file_path, so make sure it is set asap. It is obtained from uname(),\nbut if that yields an unqualified value, make a FQDN by using gethostbyname to\ncanonize it. Some people like upper case letters in their host names, so we\ndon't force the case. */\n\nif (primary_hostname == NULL)\n {\n uschar *hostname;\n struct utsname uts;\n if (uname(&uts) < 0)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"uname() failed to yield host name\");\n hostname = US uts.nodename;\n\n if (Ustrchr(hostname, '.') == NULL)\n {\n int af = AF_INET;\n struct hostent *hostdata;\n\n #if HAVE_IPV6\n if (!disable_ipv6 && (dns_ipv4_lookup == NULL ||\n match_isinlist(hostname, &dns_ipv4_lookup, 0, NULL, NULL, MCL_DOMAIN,\n TRUE, NULL) != OK))\n af = AF_INET6;\n #else\n af = AF_INET;\n #endif\n\n for (;;)\n {\n #if HAVE_IPV6\n #if HAVE_GETIPNODEBYNAME\n int error_num;\n hostdata = getipnodebyname(CS hostname, af, 0, &error_num);\n #else\n hostdata = gethostbyname2(CS hostname, af);\n #endif\n #else\n hostdata = gethostbyname(CS hostname);\n #endif\n\n if (hostdata != NULL)\n {\n hostname = US hostdata->h_name;\n break;\n }\n\n if (af == AF_INET) break;\n af = AF_INET;\n }\n }\n\n primary_hostname = string_copy(hostname);\n }\n\n/* Set up default value for smtp_active_hostname */\n\nsmtp_active_hostname = primary_hostname;\n\n/* If spool_directory wasn't set in the build-time configuration, it must have\ngot set above. Of course, writing to the log may not work if log_file_path is\nnot set, but it will at least get to syslog or somewhere, with any luck. */\n\nif (*spool_directory == 0)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"spool_directory undefined: cannot \"\n \"proceed\");\n\n/* Expand the spool directory name; it may, for example, contain the primary\nhost name. Same comment about failure. */\n\ns = expand_string(spool_directory);\nif (s == NULL)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to expand spool_directory \"\n \"\\\"%s\\\": %s\", spool_directory, expand_string_message);\nspool_directory = s;\n\n/* Expand log_file_path, which must contain \"%s\" in any component that isn't\nthe null string or \"syslog\". It is also allowed to contain one instance of %D.\nHowever, it must NOT contain % followed by anything else. */\n\nif (*log_file_path != 0)\n {\n uschar *ss, *sss;\n int sep = ':'; /* Fixed for log file path */\n s = expand_string(log_file_path);\n if (s == NULL)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to expand log_file_path \"\n \"\\\"%s\\\": %s\", log_file_path, expand_string_message);\n\n ss = s;\n while ((sss = string_nextinlist(&ss,&sep,big_buffer,big_buffer_size)) != NULL)\n {\n uschar *t;\n if (sss[0] == 0 || Ustrcmp(sss, \"syslog\") == 0) continue;\n t = Ustrstr(sss, \"%s\");\n if (t == NULL)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"log_file_path \\\"%s\\\" does not \"\n \"contain \\\"%%s\\\"\", sss);\n *t = 'X';\n t = Ustrchr(sss, '%');\n if (t != NULL)\n {\n if (t[1] != 'D' || Ustrchr(t+2, '%') != NULL)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"log_file_path \\\"%s\\\" contains \"\n \"unexpected \\\"%%\\\" character\", s);\n }\n }\n\n log_file_path = s;\n }\n\n/* Interpret syslog_facility into an integer argument for 'ident' param to\nopenlog(). Default is LOG_MAIL set in globals.c. Allow the user to omit the\nleading \"log_\". */\n\nif (syslog_facility_str != NULL)\n {\n int i;\n uschar *s = syslog_facility_str;\n\n if ((Ustrlen(syslog_facility_str) >= 4) &&\n (strncmpic(syslog_facility_str, US\"log_\", 4) == 0))\n s += 4;\n\n for (i = 0; i < syslog_list_size; i++)\n {\n if (strcmpic(s, syslog_list[i].name) == 0)\n {\n syslog_facility = syslog_list[i].value;\n break;\n }\n }\n\n if (i >= syslog_list_size)\n {\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"failed to interpret syslog_facility \\\"%s\\\"\", syslog_facility_str);\n }\n }\n\n/* Expand pid_file_path */\n\nif (*pid_file_path != 0)\n {\n s = expand_string(pid_file_path);\n if (s == NULL)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to expand pid_file_path \"\n \"\\\"%s\\\": %s\", pid_file_path, expand_string_message);\n pid_file_path = s;\n }\n\n/* Compile the regex for matching a UUCP-style \"From_\" line in an incoming\nmessage. */\n\nregex_From = regex_must_compile(uucp_from_pattern, FALSE, TRUE);\n\n/* Unpick the SMTP rate limiting options, if set */\n\nif (smtp_ratelimit_mail != NULL)\n {\n unpick_ratelimit(smtp_ratelimit_mail, &smtp_rlm_threshold,\n &smtp_rlm_base, &smtp_rlm_factor, &smtp_rlm_limit);\n }\n\nif (smtp_ratelimit_rcpt != NULL)\n {\n unpick_ratelimit(smtp_ratelimit_rcpt, &smtp_rlr_threshold,\n &smtp_rlr_base, &smtp_rlr_factor, &smtp_rlr_limit);\n }\n\n/* The qualify domains default to the primary host name */\n\nif (qualify_domain_sender == NULL)\n qualify_domain_sender = primary_hostname;\nif (qualify_domain_recipient == NULL)\n qualify_domain_recipient = qualify_domain_sender;\n\n/* Setting system_filter_user in the configuration sets the gid as well if a\nname is given, but a numerical value does not. */\n\nif (system_filter_uid_set && !system_filter_gid_set)\n {\n struct passwd *pw = getpwuid(system_filter_uid);\n if (pw == NULL)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Failed to look up uid %ld\",\n (long int)system_filter_uid);\n system_filter_gid = pw->pw_gid;\n system_filter_gid_set = TRUE;\n }\n\n/* If the errors_reply_to field is set, check that it is syntactically valid\nand ensure it contains a domain. */\n\nif (errors_reply_to != NULL)\n {\n uschar *errmess;\n int start, end, domain;\n uschar *recipient = parse_extract_address(errors_reply_to, &errmess,\n &start, &end, &domain, FALSE);\n\n if (recipient == NULL)\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"error in errors_reply_to (%s): %s\", errors_reply_to, errmess);\n\n if (domain == 0)\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"errors_reply_to (%s) does not contain a domain\", errors_reply_to);\n }\n\n/* If smtp_accept_queue or smtp_accept_max_per_host is set, then\nsmtp_accept_max must also be set. */\n\nif (smtp_accept_max == 0 &&\n (smtp_accept_queue > 0 || smtp_accept_max_per_host != NULL))\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"smtp_accept_max must be set if smtp_accept_queue or \"\n \"smtp_accept_max_per_host is set\");\n\n/* Set up the host number if anything is specified. It is an expanded string\nso that it can be computed from the host name, for example. We do this last\nso as to ensure that everything else is set up before the expansion. */\n\nif (host_number_string != NULL)\n {\n uschar *end;\n uschar *s = expand_string(host_number_string);\n long int n = Ustrtol(s, &end, 0);\n while (isspace(*end)) end++;\n if (*end != 0)\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"localhost_number value is not a number: %s\", s);\n if (n > LOCALHOST_MAX)\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"localhost_number is greater than the maximum allowed value (%d)\",\n LOCALHOST_MAX);\n host_number = n;\n }\n\n#ifdef SUPPORT_TLS\n/* If tls_verify_hosts is set, tls_verify_certificates must also be set */\n\nif ((tls_verify_hosts != NULL || tls_try_verify_hosts != NULL) &&\n tls_verify_certificates == NULL)\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"tls_%sverify_hosts is set, but tls_verify_certificates is not set\",\n (tls_verify_hosts != NULL)? \"\" : \"try_\");\n\n/* If openssl_options is set, validate it */\nif (openssl_options != NULL)\n {\n# ifdef USE_GNUTLS\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"openssl_options is set but we're using GnuTLS\");\n# else\n long dummy;\n if (!(tls_openssl_options_parse(openssl_options, &dummy)))\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"openssl_options parse error: %s\", openssl_options);\n# endif\n }\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'Don't allow a configure file which is writeable by the Exim user or group\n\n(Bug 1044, CVE-2010-4345)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: 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);\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\tif (client->server->timeout) \n\t\t\talarm(client->server->timeout);\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\t\t\tif (client->difmap) g_free(client->difmap) ;\n \tif (client->difffile>=0) { \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)\n\t\t\terr(\"Request too big!\");\n#ifdef DODBG\n\t\tprintf(\"%s from %Lu (%Lu) 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);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (((ssize_t)((off_t)request.from + len) > client->exportsize) ||\n\t\t ((client->server->flags & F_READONLY) && request.type)) {\n\t\t\tDEBUG(\"[RANGE!]\");\n\t\t\tERROR(client, reply);\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_AUTOREADONLY) ||\n\t\t\t\t\texpwrite(request.from, buf, len,\n\t\t\t\t\t\tclient)) {\n\t\t\t\tDEBUG(\"Write failed: %m\" );\n\t\t\t\tERROR(client, reply);\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);\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'], 'message': 'r134: CVE-2005-3534'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xsltGenerateIdFunction(xmlXPathParserContextPtr ctxt, int nargs){\n xmlNodePtr cur = NULL;\n unsigned long val;\n xmlChar str[20];\n\n if (nargs == 0) {\n\tcur = ctxt->context->node;\n } else if (nargs == 1) {\n\txmlXPathObjectPtr obj;\n\txmlNodeSetPtr nodelist;\n\tint i, ret;\n\n\tif ((ctxt->value == NULL) || (ctxt->value->type != XPATH_NODESET)) {\n\t ctxt->error = XPATH_INVALID_TYPE;\n\t xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL,\n\t\t\"generate-id() : invalid arg expecting a node-set\\n\");\n\t return;\n\t}\n\tobj = valuePop(ctxt);\n\tnodelist = obj->nodesetval;\n\tif ((nodelist == NULL) || (nodelist->nodeNr <= 0)) {\n\t xmlXPathFreeObject(obj);\n\t valuePush(ctxt, xmlXPathNewCString(\"\"));\n\t return;\n\t}\n\tcur = nodelist->nodeTab[0];\n\tfor (i = 1;i < nodelist->nodeNr;i++) {\n\t ret = xmlXPathCmpNodes(cur, nodelist->nodeTab[i]);\n\t if (ret == -1)\n\t cur = nodelist->nodeTab[i];\n\t}\n\txmlXPathFreeObject(obj);\n } else {\n\txsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL,\n\t\t\"generate-id() : invalid number of args %d\\n\", nargs);\n\tctxt->error = XPATH_INVALID_ARITY;\n\treturn;\n }\n /*\n * Okay this is ugly but should work, use the NodePtr address\n * to forge the ID\n */\n val = (unsigned long)((char *)cur - (char *)0);\n val /= sizeof(xmlNode);\n sprintf((char *)str, \"id%ld\", val);\n valuePush(ctxt, xmlXPathNewString(str));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Fix generate-id() to not expose object addresses\n\nAs pointed out by Chris Evans it's better\nsecurity wise to not expose object addresses directly, use a diff\nw.r.t. the document root own address to avoid this\n* libxslt/functions.c: fix IDs generation 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 ssize_t clusterip_proc_write(struct file *file, const char __user *input,\n\t\t\t\tsize_t size, loff_t *ofs)\n{\n\tstruct clusterip_config *c = PDE(file->f_path.dentry->d_inode)->data;\n#define PROC_WRITELEN\t10\n\tchar buffer[PROC_WRITELEN+1];\n\tunsigned long nodenum;\n\n\tif (copy_from_user(buffer, input, PROC_WRITELEN))\n\t\treturn -EFAULT;\n\n\tif (*buffer == '+') {\n\t\tnodenum = simple_strtoul(buffer+1, NULL, 10);\n\t\tif (clusterip_add_node(c, nodenum))\n\t\t\treturn -ENOMEM;\n\t} else if (*buffer == '-') {\n\t\tnodenum = simple_strtoul(buffer+1, NULL,10);\n\t\tif (clusterip_del_node(c, nodenum))\n\t\t\treturn -ENOENT;\n\t} else\n\t\treturn -EIO;\n\n\treturn size;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'netfilter: ipt_CLUSTERIP: fix buffer overflow\n\n'buffer' string is copied from userspace. It is not checked whether it is\nzero terminated. This may lead to overflow inside of simple_strtoul().\nChangli Gao suggested to copy not more than user supplied 'size' bytes.\n\nIt was introduced before the git epoch. Files \"ipt_CLUSTERIP/*\" are\nroot writable only by default, however, on some setups permissions might be\nrelaxed to e.g. network admin user.\n\nSigned-off-by: Vasiliy Kulikov \nAcked-by: Changli Gao \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: msg_t* MsgDup(msg_t* pOld)\n{\n\tmsg_t* pNew;\n\trsRetVal localRet;\n\n\tassert(pOld != NULL);\n\n\tBEGINfunc\n\tif(msgConstructWithTime(&pNew, &pOld->tTIMESTAMP, pOld->ttGenTime) != RS_RET_OK) {\n\t\treturn NULL;\n\t}\n\n\t/* now copy the message properties */\n\tpNew->iRefCount = 1;\n\tpNew->iSeverity = pOld->iSeverity;\n\tpNew->iFacility = pOld->iFacility;\n\tpNew->msgFlags = pOld->msgFlags;\n\tpNew->iProtocolVersion = pOld->iProtocolVersion;\n\tpNew->ttGenTime = pOld->ttGenTime;\n\tpNew->offMSG = pOld->offMSG;\n\tpNew->iLenRawMsg = pOld->iLenRawMsg;\n\tpNew->iLenMSG = pOld->iLenMSG;\n\tpNew->iLenTAG = pOld->iLenTAG;\n\tpNew->iLenHOSTNAME = pOld->iLenHOSTNAME;\n\tif((pOld->msgFlags & NEEDS_DNSRESOL) == 1) {\n\t\t\tlocalRet = msgSetFromSockinfo(pNew, pOld->rcvFrom.pfrominet);\n\t\t\tif(localRet != RS_RET_OK) {\n\t\t\t\t/* if something fails, we accept loss of this property, it is\n\t\t\t\t * better than losing the whole message.\n\t\t\t\t */\n\t\t\t\tpNew->msgFlags &= ~NEEDS_DNSRESOL;\n\t\t\t}\n\t} else {\n\t\tif(pOld->rcvFrom.pRcvFrom != NULL) {\n\t\t\tpNew->rcvFrom.pRcvFrom = pOld->rcvFrom.pRcvFrom;\n\t\t\tprop.AddRef(pNew->rcvFrom.pRcvFrom);\n\t\t}\n\t}\n\tif(pOld->pRcvFromIP != NULL) {\n\t\tpNew->pRcvFromIP = pOld->pRcvFromIP;\n\t\tprop.AddRef(pNew->pRcvFromIP);\n\t}\n\tif(pOld->pInputName != NULL) {\n\t\tpNew->pInputName = pOld->pInputName;\n\t\tprop.AddRef(pNew->pInputName);\n\t}\n\t/* enable this, if someone actually uses UxTradMsg, delete after some time has\n\t * passed and nobody complained -- rgerhards, 2009-06-16\n\tpNew->offAfterPRI = pOld->offAfterPRI;\n\t*/\n\tif(pOld->iLenTAG > 0) {\n\t\tif(pOld->iLenTAG < CONF_TAG_BUFSIZE) {\n\t\t\tmemcpy(pNew->TAG.szBuf, pOld->TAG.szBuf, pOld->iLenTAG);\n\t\t} else {\n\t\t\tif((pNew->TAG.pszTAG = srUtilStrDup(pOld->TAG.pszTAG, pOld->iLenTAG)) == NULL) {\n\t\t\t\tmsgDestruct(&pNew);\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tpNew->iLenTAG = pOld->iLenTAG;\n\t\t}\n\t}\n\tif(pOld->iLenRawMsg < CONF_RAWMSG_BUFSIZE) {\n\t\tmemcpy(pNew->szRawMsg, pOld->szRawMsg, pOld->iLenRawMsg + 1);\n\t\tpNew->pszRawMsg = pNew->szRawMsg;\n\t} else {\n\t\ttmpCOPYSZ(RawMsg);\n\t}\n\tif(pOld->iLenHOSTNAME < CONF_HOSTNAME_BUFSIZE) {\n\t\tmemcpy(pNew->szHOSTNAME, pOld->szHOSTNAME, pOld->iLenHOSTNAME + 1);\n\t\tpNew->pszHOSTNAME = pNew->szHOSTNAME;\n\t} else {\n\t\ttmpCOPYSZ(HOSTNAME);\n\t}\n\n\ttmpCOPYCSTR(ProgName);\n\ttmpCOPYCSTR(StrucData);\n\ttmpCOPYCSTR(APPNAME);\n\ttmpCOPYCSTR(PROCID);\n\ttmpCOPYCSTR(MSGID);\n\n\t/* we do not copy all other cache properties, as we do not even know\n\t * if they are needed once again. So we let them re-create if needed.\n\t */\n\n\tENDfunc\n\treturn pNew;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772'], 'message': 'backporting abort condition fix from 5.7.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: void \nmono_reflection_create_dynamic_method (MonoReflectionDynamicMethod *mb)\n{ ; 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_read(VirtIOBlockReq *req)\n{\n BlockDriverAIOCB *acb;\n uint64_t sector;\n\n sector = ldq_p(&req->out->sector);\n\n if (sector & req->dev->sector_mask) {\n virtio_blk_rw_complete(req, -EIO);\n return;\n }\n\n acb = bdrv_aio_readv(req->dev->bs, sector, &req->qiov,\n req->qiov.size / BDRV_SECTOR_SIZE,\n virtio_blk_rw_complete, req);\n if (!acb) {\n virtio_blk_rw_complete(req, -EIO);\n }\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_NPPVariable(int variable)\n{\n const char *str;\n\n switch (variable) {\n#define _(VAL) case VAL: str = #VAL; break;\n\t_(NPPVpluginNameString);\n\t_(NPPVpluginDescriptionString);\n\t_(NPPVpluginWindowBool);\n\t_(NPPVpluginTransparentBool);\n\t_(NPPVjavaClass);\n\t_(NPPVpluginWindowSize);\n\t_(NPPVpluginTimerInterval);\n\t_(NPPVpluginScriptableInstance);\n\t_(NPPVpluginScriptableIID);\n\t_(NPPVjavascriptPushCallerBool);\n\t_(NPPVpluginKeepLibraryInMemory);\n\t_(NPPVpluginNeedsXEmbed);\n\t_(NPPVpluginScriptableNPObject);\n\t_(NPPVformValue);\n#undef _\n default:\n\tswitch (variable & 0xff) {\n#define _(VAL, VAR) case VAL: str = #VAR; break\n\t _(10, NPPVpluginScriptableInstance);\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: static NOINLINE void attach_option(\n\t\tstruct option_set **opt_list,\n\t\tconst struct dhcp_optflag *optflag,\n\t\tchar *buffer,\n\t\tint length)\n{\n\tstruct option_set *existing, *new, **curr;\n\tchar *allocated = NULL;\n\n\texisting = udhcp_find_option(*opt_list, optflag->code);\n\tif (!existing) {\n\t\tlog2(\"Attaching option %02x to list\", optflag->code);\n\t\tallocated = allocate_tempopt_if_needed(optflag, buffer, &length);\n#if ENABLE_FEATURE_UDHCP_RFC3397\n\t\tif ((optflag->flags & OPTION_TYPE_MASK) == OPTION_DNS_STRING) {\n\t\t\t/* reuse buffer and length for RFC1035-formatted string */\n\t\t\tallocated = buffer = (char *)dname_enc(NULL, 0, buffer, &length);\n\t\t}\n#endif\n\t\t/* make a new option */\n\t\tnew = xmalloc(sizeof(*new));\n\t\tnew->data = xmalloc(length + OPT_DATA);\n\t\tnew->data[OPT_CODE] = optflag->code;\n\t\tnew->data[OPT_LEN] = length;\n\t\tmemcpy(new->data + OPT_DATA, (allocated ? allocated : buffer), length);\n\n\t\tcurr = opt_list;\n\t\twhile (*curr && (*curr)->data[OPT_CODE] < optflag->code)\n\t\t\tcurr = &(*curr)->next;\n\n\t\tnew->next = *curr;\n\t\t*curr = new;\n\t\tgoto ret;\n\t}\n\n\tif (optflag->flags & OPTION_LIST) {\n\t\tunsigned old_len;\n\n\t\t/* add it to an existing option */\n\t\tlog2(\"Attaching option %02x to existing member of list\", optflag->code);\n\t\tallocated = allocate_tempopt_if_needed(optflag, buffer, &length);\n\t\told_len = existing->data[OPT_LEN];\n#if ENABLE_FEATURE_UDHCP_RFC3397\n\t\tif ((optflag->flags & OPTION_TYPE_MASK) == OPTION_DNS_STRING) {\n\t\t\t/* reuse buffer and length for RFC1035-formatted string */\n\t\t\tallocated = buffer = (char *)dname_enc(existing->data + OPT_DATA, old_len, buffer, &length);\n\t\t}\n#endif\n\t\tif (old_len + length < 255) {\n\t\t\t/* actually 255 is ok too, but adding a space can overlow it */\n\n\t\t\texisting->data = xrealloc(existing->data, OPT_DATA + 1 + old_len + length);\n\t\t\tif ((optflag->flags & OPTION_TYPE_MASK) == OPTION_STRING) {\n\t\t\t\t/* add space separator between STRING options in a list */\n\t\t\t\texisting->data[OPT_DATA + old_len] = ' ';\n\t\t\t\told_len++;\n\t\t\t}\n\t\t\tmemcpy(existing->data + OPT_DATA + old_len, buffer, length);\n\t\t\texisting->data[OPT_LEN] = old_len + length;\n\t\t} /* else, ignore the data, we could put this in a second option in the future */\n\t} /* else, ignore the new data */\n\n ret:\n\tfree(allocated);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'udhcpc: sanitize hostnames in incoming packets. Closes 3979.\n\nThe following options are replaced with string \"bad\" if they\ncontain malformed hostname:\nHOST_NAME, DOMAIN_NAME, NIS_DOMAIN, TFTP_SERVER_NAME\n\nfunction old new delta\nxmalloc_optname_optval 850 888 +38\nattach_option 440 443 +3\nlen_of_option_as_string 13 14 +1\ndhcp_option_lengths 13 14 +1\n------------------------------------------------------------------------------\n(add/remove: 0/0 grow/shrink: 4/0 up/down: 43/0) Total: 43 bytes\n\nSigned-off-by: Denys Vlasenko '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: gif_read (GifContext *context, guchar *buffer, size_t len)\n{\n\tgint retval;\n#ifdef IO_GIFDEBUG\n\tgint i;\n#endif\n\tif (context->file) {\n#ifdef IO_GIFDEBUG\n\t\tcount += len;\n\t\tg_print (\"Fsize :%d\\tcount :%d\\t\", len, count);\n#endif\n\t\tretval = (fread(buffer, len, 1, context->file) != 0);\n\n if (!retval && ferror (context->file))\n g_set_error (context->error,\n G_FILE_ERROR,\n g_file_error_from_errno (errno),\n _(\"Failure reading GIF: %s\"), strerror (errno));\n \n#ifdef IO_GIFDEBUG\n\t\tif (len < 100) {\n\t\t\tfor (i = 0; i < len; i++)\n\t\t\t\tg_print (\"%d \", buffer[i]);\n\t\t}\n\t\tg_print (\"\\n\");\n#endif\n \n\t\treturn retval;\n\t} else {\n#ifdef IO_GIFDEBUG\n/* \t\tg_print (\"\\tlooking for %d bytes. size == %d, ptr == %d\\n\", len, context->size, context->ptr); */\n#endif\n\t\tif ((context->size - context->ptr) >= len) {\n#ifdef IO_GIFDEBUG\n\t\t\tcount += len;\n#endif\n\t\t\tmemcpy (buffer, context->buf + context->ptr, len);\n\t\t\tcontext->ptr += len;\n\t\t\tcontext->amount_needed = 0;\n#ifdef IO_GIFDEBUG\n\t\t\tg_print (\"Psize :%d\\tcount :%d\\t\", len, count);\n\t\t\tif (len < 100) {\n\t\t\t\tfor (i = 0; i < len; i++)\n\t\t\t\t\tg_print (\"%d \", buffer[i]);\n\t\t\t}\n\t\t\tg_print (\"\\n\");\n#endif\n\t\t\treturn TRUE;\n\t\t}\n\t\tcontext->amount_needed = len - (context->size - context->ptr);\n\t}\n\treturn 0;\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__gif_image_load_increment (gpointer data,\n const guchar *buf, guint size,\n GError **error)\n{\n\tgint retval;\n\tGifContext *context = (GifContext *) data;\n\n context->error = error;\n \n\tif (context->amount_needed == 0) {\n\t\t/* we aren't looking for some bytes. */\n\t\t/* we can use buf now, but we don't want to keep it around at all.\n\t\t * it will be gone by the end of the call. */\n\t\tcontext->buf = (guchar*) buf; /* very dubious const cast */\n\t\tcontext->ptr = 0;\n\t\tcontext->size = size;\n\t} else {\n\t\t/* we need some bytes */\n\t\tif (size < context->amount_needed) {\n\t\t\tcontext->amount_needed -= size;\n\t\t\t/* copy it over and return */\n\t\t\tmemcpy (context->buf + context->size, buf, size);\n\t\t\tcontext->size += size;\n\t\t\treturn TRUE;\n\t\t} else if (size == context->amount_needed) {\n\t\t\tmemcpy (context->buf + context->size, buf, size);\n\t\t\tcontext->size += size;\n\t\t} else {\n\t\t\tcontext->buf = g_realloc (context->buf, context->size + size);\n\t\t\tmemcpy (context->buf + context->size, buf, size);\n\t\t\tcontext->size += size;\n\t\t}\n\t}\n\n\tretval = gif_main_loop (context);\n\n\tif (retval == -2)\n\t\treturn FALSE;\n\tif (retval == -1) {\n\t\t/* we didn't have enough memory */\n\t\t/* prepare for the next image_load_increment */\n\t\tif (context->buf == buf) {\n\t\t\tg_assert (context->size == size);\n\t\t\tcontext->buf = (guchar *)g_new (guchar, context->amount_needed + (context->size - context->ptr));\n\t\t\tmemcpy (context->buf, buf + context->ptr, context->size - context->ptr);\n\t\t} else {\n\t\t\t/* copy the left overs to the begining of the buffer */\n\t\t\t/* and realloc the memory */\n\t\t\tmemmove (context->buf, context->buf + context->ptr, context->size - context->ptr);\n\t\t\tcontext->buf = g_realloc (context->buf, context->amount_needed + (context->size - context->ptr));\n\t\t}\n\t\tcontext->size = context->size - context->ptr;\n\t\tcontext->ptr = 0;\n\t} else {\n\t\t/* we are prolly all done */\n\t\tif (context->buf == buf)\n\t\t\tcontext->buf = NULL;\n\t}\n\treturn 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_timespec(const unsigned long jiffies, struct timespec *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\tvalue->tv_sec = div_long_long_rem(nsec, NSEC_PER_SEC, &value->tv_nsec);\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 int sgi_timer_set(struct k_itimer *timr, int flags,\n\tstruct itimerspec * new_setting,\n\tstruct itimerspec * old_setting)\n{\n\tunsigned long when, period, irqflags;\n\tint err = 0;\n\tcnodeid_t nodeid;\n\tstruct mmtimer *base;\n\tstruct rb_node *n;\n\n\tif (old_setting)\n\t\tsgi_timer_get(timr, old_setting);\n\n\tsgi_timer_del(timr);\n\twhen = timespec_to_ns(new_setting->it_value);\n\tperiod = timespec_to_ns(new_setting->it_interval);\n\n\tif (when == 0)\n\t\t/* Clear timer */\n\t\treturn 0;\n\n\tbase = kmalloc(sizeof(struct mmtimer), GFP_KERNEL);\n\tif (base == NULL)\n\t\treturn -ENOMEM;\n\n\tif (flags & TIMER_ABSTIME) {\n\t\tstruct timespec n;\n\t\tunsigned long now;\n\n\t\tgetnstimeofday(&n);\n\t\tnow = timespec_to_ns(n);\n\t\tif (when > now)\n\t\t\twhen -= now;\n\t\telse\n\t\t\t/* Fire the timer immediately */\n\t\t\twhen = 0;\n\t}\n\n\t/*\n\t * Convert to sgi clock period. Need to keep rtc_time() as near as possible\n\t * to getnstimeofday() in order to be as faithful as possible to the time\n\t * specified.\n\t */\n\twhen = (when + sgi_clock_period - 1) / sgi_clock_period + rtc_time();\n\tperiod = (period + sgi_clock_period - 1) / sgi_clock_period;\n\n\t/*\n\t * We are allocating a local SHub comparator. If we would be moved to another\n\t * cpu then another SHub may be local to us. Prohibit that by switching off\n\t * preemption.\n\t */\n\tpreempt_disable();\n\n\tnodeid = cpu_to_node(smp_processor_id());\n\n\t/* Lock the node timer structure */\n\tspin_lock_irqsave(&timers[nodeid].lock, irqflags);\n\n\tbase->timer = timr;\n\tbase->cpu = smp_processor_id();\n\n\ttimr->it.mmtimer.clock = TIMER_SET;\n\ttimr->it.mmtimer.node = nodeid;\n\ttimr->it.mmtimer.incr = period;\n\ttimr->it.mmtimer.expires = when;\n\n\tn = timers[nodeid].next;\n\n\t/* Add the new struct mmtimer to node's timer list */\n\tmmtimer_add_list(base);\n\n\tif (timers[nodeid].next == n) {\n\t\t/* No need to reprogram comparator for now */\n\t\tspin_unlock_irqrestore(&timers[nodeid].lock, irqflags);\n\t\tpreempt_enable();\n\t\treturn err;\n\t}\n\n\t/* We need to reprogram the comparator */\n\tif (n)\n\t\tmmtimer_disable_int(cnodeid_to_nasid(nodeid), COMPARATOR);\n\n\tmmtimer_set_next_timer(nodeid);\n\n\t/* Unlock the node timer structure */\n\tspin_unlock_irqrestore(&timers[nodeid].lock, irqflags);\n\n\tpreempt_enable();\n\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'remove div_long_long_rem\n\nx86 is the only arch right now, which provides an optimized for\ndiv_long_long_rem and it has the downside that one has to be very careful that\nthe divide doesn't overflow.\n\nThe API is a little akward, as the arguments for the unsigned divide are\nsigned. The signed version also doesn't handle a negative divisor and\nproduces worse code on 64bit archs.\n\nThere is little incentive to keep this API alive, so this converts the few\nusers to the new API.\n\nSigned-off-by: Roman Zippel \nCc: Ralf Baechle \nCc: Ingo Molnar \nCc: Thomas Gleixner \nCc: john stultz \nCc: Christoph Lameter \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: */\nstatic int\nxmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op)\n{\n int total = 0;\n int equal, ret;\n xmlXPathCompExprPtr comp;\n xmlXPathObjectPtr arg1, arg2;\n xmlNodePtr bak;\n xmlDocPtr bakd;\n int pp;\n int cs;\n\n CHECK_ERROR0;\n comp = ctxt->comp;\n switch (op->op) {\n case XPATH_OP_END:\n return (0);\n case XPATH_OP_AND:\n\t bakd = ctxt->context->doc;\n\t bak = ctxt->context->node;\n\t pp = ctxt->context->proximityPosition;\n\t cs = ctxt->context->contextSize;\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t CHECK_ERROR0;\n xmlXPathBooleanFunction(ctxt, 1);\n if ((ctxt->value == NULL) || (ctxt->value->boolval == 0))\n return (total);\n arg2 = valuePop(ctxt);\n\t ctxt->context->doc = bakd;\n\t ctxt->context->node = bak;\n\t ctxt->context->proximityPosition = pp;\n\t ctxt->context->contextSize = cs;\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);\n\t if (ctxt->error) {\n\t\txmlXPathFreeObject(arg2);\n\t\treturn(0);\n\t }\n xmlXPathBooleanFunction(ctxt, 1);\n arg1 = valuePop(ctxt);\n arg1->boolval &= arg2->boolval;\n valuePush(ctxt, arg1);\n\t xmlXPathReleaseObject(ctxt->context, arg2);\n return (total);\n case XPATH_OP_OR:\n\t bakd = ctxt->context->doc;\n\t bak = ctxt->context->node;\n\t pp = ctxt->context->proximityPosition;\n\t cs = ctxt->context->contextSize;\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t CHECK_ERROR0;\n xmlXPathBooleanFunction(ctxt, 1);\n if ((ctxt->value == NULL) || (ctxt->value->boolval == 1))\n return (total);\n arg2 = valuePop(ctxt);\n\t ctxt->context->doc = bakd;\n\t ctxt->context->node = bak;\n\t ctxt->context->proximityPosition = pp;\n\t ctxt->context->contextSize = cs;\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);\n\t if (ctxt->error) {\n\t\txmlXPathFreeObject(arg2);\n\t\treturn(0);\n\t }\n xmlXPathBooleanFunction(ctxt, 1);\n arg1 = valuePop(ctxt);\n arg1->boolval |= arg2->boolval;\n valuePush(ctxt, arg1);\n\t xmlXPathReleaseObject(ctxt->context, arg2);\n return (total);\n case XPATH_OP_EQUAL:\n\t bakd = ctxt->context->doc;\n\t bak = ctxt->context->node;\n\t pp = ctxt->context->proximityPosition;\n\t cs = ctxt->context->contextSize;\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t CHECK_ERROR0;\n\t ctxt->context->doc = bakd;\n\t ctxt->context->node = bak;\n\t ctxt->context->proximityPosition = pp;\n\t ctxt->context->contextSize = cs;\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);\n\t CHECK_ERROR0;\n\t if (op->value)\n\t\tequal = xmlXPathEqualValues(ctxt);\n\t else\n\t\tequal = xmlXPathNotEqualValues(ctxt);\n\t valuePush(ctxt, xmlXPathCacheNewBoolean(ctxt->context, equal));\n return (total);\n case XPATH_OP_CMP:\n\t bakd = ctxt->context->doc;\n\t bak = ctxt->context->node;\n\t pp = ctxt->context->proximityPosition;\n\t cs = ctxt->context->contextSize;\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t CHECK_ERROR0;\n\t ctxt->context->doc = bakd;\n\t ctxt->context->node = bak;\n\t ctxt->context->proximityPosition = pp;\n\t ctxt->context->contextSize = cs;\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);\n\t CHECK_ERROR0;\n ret = xmlXPathCompareValues(ctxt, op->value, op->value2);\n\t valuePush(ctxt, xmlXPathCacheNewBoolean(ctxt->context, ret));\n return (total);\n case XPATH_OP_PLUS:\n\t bakd = ctxt->context->doc;\n\t bak = ctxt->context->node;\n\t pp = ctxt->context->proximityPosition;\n\t cs = ctxt->context->contextSize;\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t CHECK_ERROR0;\n if (op->ch2 != -1) {\n\t\tctxt->context->doc = bakd;\n\t\tctxt->context->node = bak;\n\t\tctxt->context->proximityPosition = pp;\n\t\tctxt->context->contextSize = cs;\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);\n\t }\n\t CHECK_ERROR0;\n if (op->value == 0)\n xmlXPathSubValues(ctxt);\n else if (op->value == 1)\n xmlXPathAddValues(ctxt);\n else if (op->value == 2)\n xmlXPathValueFlipSign(ctxt);\n else if (op->value == 3) {\n CAST_TO_NUMBER;\n CHECK_TYPE0(XPATH_NUMBER);\n }\n return (total);\n case XPATH_OP_MULT:\n\t bakd = ctxt->context->doc;\n\t bak = ctxt->context->node;\n\t pp = ctxt->context->proximityPosition;\n\t cs = ctxt->context->contextSize;\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t CHECK_ERROR0;\n\t ctxt->context->doc = bakd;\n\t ctxt->context->node = bak;\n\t ctxt->context->proximityPosition = pp;\n\t ctxt->context->contextSize = cs;\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);\n\t CHECK_ERROR0;\n if (op->value == 0)\n xmlXPathMultValues(ctxt);\n else if (op->value == 1)\n xmlXPathDivValues(ctxt);\n else if (op->value == 2)\n xmlXPathModValues(ctxt);\n return (total);\n case XPATH_OP_UNION:\n\t bakd = ctxt->context->doc;\n\t bak = ctxt->context->node;\n\t pp = ctxt->context->proximityPosition;\n\t cs = ctxt->context->contextSize;\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t CHECK_ERROR0;\n\t ctxt->context->doc = bakd;\n\t ctxt->context->node = bak;\n\t ctxt->context->proximityPosition = pp;\n\t ctxt->context->contextSize = cs;\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);\n\t CHECK_ERROR0;\n CHECK_TYPE0(XPATH_NODESET);\n arg2 = valuePop(ctxt);\n\n CHECK_TYPE0(XPATH_NODESET);\n arg1 = valuePop(ctxt);\n\n\t if ((arg1->nodesetval == NULL) ||\n\t\t((arg2->nodesetval != NULL) &&\n\t\t (arg2->nodesetval->nodeNr != 0)))\n\t {\n\t\targ1->nodesetval = xmlXPathNodeSetMerge(arg1->nodesetval,\n\t\t\t\t\t\t\targ2->nodesetval);\n\t }\n\n valuePush(ctxt, arg1);\n\t xmlXPathReleaseObject(ctxt->context, arg2);\n return (total);\n case XPATH_OP_ROOT:\n xmlXPathRoot(ctxt);\n return (total);\n case XPATH_OP_NODE:\n if (op->ch1 != -1)\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t CHECK_ERROR0;\n if (op->ch2 != -1)\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);\n\t CHECK_ERROR0;\n\t valuePush(ctxt, xmlXPathCacheNewNodeSet(ctxt->context,\n\t\tctxt->context->node));\n return (total);\n case XPATH_OP_RESET:\n if (op->ch1 != -1)\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t CHECK_ERROR0;\n if (op->ch2 != -1)\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);\n\t CHECK_ERROR0;\n ctxt->context->node = NULL;\n return (total);\n case XPATH_OP_COLLECT:{\n if (op->ch1 == -1)\n return (total);\n\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t\tCHECK_ERROR0;\n\n total += xmlXPathNodeCollectAndTest(ctxt, op, NULL, NULL, 0);\n return (total);\n }\n case XPATH_OP_VALUE:\n valuePush(ctxt,\n xmlXPathCacheObjectCopy(ctxt->context,\n\t\t\t(xmlXPathObjectPtr) op->value4));\n return (total);\n case XPATH_OP_VARIABLE:{\n\t\txmlXPathObjectPtr val;\n\n if (op->ch1 != -1)\n total +=\n xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n if (op->value5 == NULL) {\n\t\t val = xmlXPathVariableLookup(ctxt->context, op->value4);\n\t\t if (val == NULL) {\n\t\t\tctxt->error = XPATH_UNDEF_VARIABLE_ERROR;\n\t\t\treturn(0);\n\t\t }\n valuePush(ctxt, val);\n\t\t} else {\n const xmlChar *URI;\n\n URI = xmlXPathNsLookup(ctxt->context, op->value5);\n if (URI == NULL) {\n xmlGenericError(xmlGenericErrorContext,\n \"xmlXPathCompOpEval: variable %s bound to undefined prefix %s\\n\",\n (char *) op->value4, (char *)op->value5);\n return (total);\n }\n\t\t val = xmlXPathVariableLookupNS(ctxt->context,\n op->value4, URI);\n\t\t if (val == NULL) {\n\t\t\tctxt->error = XPATH_UNDEF_VARIABLE_ERROR;\n\t\t\treturn(0);\n\t\t }\n valuePush(ctxt, val);\n }\n return (total);\n }\n case XPATH_OP_FUNCTION:{\n xmlXPathFunction func;\n const xmlChar *oldFunc, *oldFuncURI;\n\t\tint i;\n\n if (op->ch1 != -1)\n total +=\n xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t\tif (ctxt->valueNr < op->value) {\n\t\t xmlGenericError(xmlGenericErrorContext,\n\t\t\t \"xmlXPathCompOpEval: parameter error\\n\");\n\t\t ctxt->error = XPATH_INVALID_OPERAND;\n\t\t return (total);\n\t\t}\n\t\tfor (i = 0; i < op->value; i++)\n\t\t if (ctxt->valueTab[(ctxt->valueNr - 1) - i] == NULL) {\n\t\t\txmlGenericError(xmlGenericErrorContext,\n\t\t\t\t\"xmlXPathCompOpEval: parameter error\\n\");\n\t\t\tctxt->error = XPATH_INVALID_OPERAND;\n\t\t\treturn (total);\n\t\t }\n if (op->cache != NULL)\n XML_CAST_FPTR(func) = op->cache;\n else {\n const xmlChar *URI = NULL;\n\n if (op->value5 == NULL)\n func =\n xmlXPathFunctionLookup(ctxt->context,\n op->value4);\n else {\n URI = xmlXPathNsLookup(ctxt->context, op->value5);\n if (URI == NULL) {\n xmlGenericError(xmlGenericErrorContext,\n \"xmlXPathCompOpEval: function %s bound to undefined prefix %s\\n\",\n (char *)op->value4, (char *)op->value5);\n return (total);\n }\n func = xmlXPathFunctionLookupNS(ctxt->context,\n op->value4, URI);\n }\n if (func == NULL) {\n xmlGenericError(xmlGenericErrorContext,\n \"xmlXPathCompOpEval: function %s not found\\n\",\n (char *)op->value4);\n XP_ERROR0(XPATH_UNKNOWN_FUNC_ERROR);\n }\n op->cache = XML_CAST_FPTR(func);\n op->cacheURI = (void *) URI;\n }\n oldFunc = ctxt->context->function;\n oldFuncURI = ctxt->context->functionURI;\n ctxt->context->function = op->value4;\n ctxt->context->functionURI = op->cacheURI;\n func(ctxt, op->value);\n ctxt->context->function = oldFunc;\n ctxt->context->functionURI = oldFuncURI;\n return (total);\n }\n case XPATH_OP_ARG:\n\t bakd = ctxt->context->doc;\n\t bak = ctxt->context->node;\n\t pp = ctxt->context->proximityPosition;\n\t cs = ctxt->context->contextSize;\n if (op->ch1 != -1)\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t ctxt->context->contextSize = cs;\n\t ctxt->context->proximityPosition = pp;\n\t ctxt->context->node = bak;\n\t ctxt->context->doc = bakd;\n\t CHECK_ERROR0;\n if (op->ch2 != -1) {\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);\n\t ctxt->context->doc = bakd;\n\t ctxt->context->node = bak;\n\t CHECK_ERROR0;\n\t }\n return (total);\n case XPATH_OP_PREDICATE:\n case XPATH_OP_FILTER:{\n xmlXPathObjectPtr res;\n xmlXPathObjectPtr obj, tmp;\n xmlNodeSetPtr newset = NULL;\n xmlNodeSetPtr oldset;\n xmlNodePtr oldnode;\n\t\txmlDocPtr oldDoc;\n int i;\n\n /*\n * Optimization for ()[1] selection i.e. the first elem\n */\n if ((op->ch1 != -1) && (op->ch2 != -1) &&\n#ifdef XP_OPTIMIZED_FILTER_FIRST\n\t\t /*\n\t\t * FILTER TODO: Can we assume that the inner processing\n\t\t * will result in an ordered list if we have an\n\t\t * XPATH_OP_FILTER?\n\t\t * What about an additional field or flag on\n\t\t * xmlXPathObject like @sorted ? This way we wouln'd need\n\t\t * to assume anything, so it would be more robust and\n\t\t * easier to optimize.\n\t\t */\n ((comp->steps[op->ch1].op == XPATH_OP_SORT) || /* 18 */\n\t\t (comp->steps[op->ch1].op == XPATH_OP_FILTER)) && /* 17 */\n#else\n\t\t (comp->steps[op->ch1].op == XPATH_OP_SORT) &&\n#endif\n (comp->steps[op->ch2].op == XPATH_OP_VALUE)) { /* 12 */\n xmlXPathObjectPtr val;\n\n val = comp->steps[op->ch2].value4;\n if ((val != NULL) && (val->type == XPATH_NUMBER) &&\n (val->floatval == 1.0)) {\n xmlNodePtr first = NULL;\n\n total +=\n xmlXPathCompOpEvalFirst(ctxt,\n &comp->steps[op->ch1],\n &first);\n\t\t\tCHECK_ERROR0;\n /*\n * The nodeset should be in document order,\n * Keep only the first value\n */\n if ((ctxt->value != NULL) &&\n (ctxt->value->type == XPATH_NODESET) &&\n (ctxt->value->nodesetval != NULL) &&\n (ctxt->value->nodesetval->nodeNr > 1))\n ctxt->value->nodesetval->nodeNr = 1;\n return (total);\n }\n }\n /*\n * Optimization for ()[last()] selection i.e. the last elem\n */\n if ((op->ch1 != -1) && (op->ch2 != -1) &&\n (comp->steps[op->ch1].op == XPATH_OP_SORT) &&\n (comp->steps[op->ch2].op == XPATH_OP_SORT)) {\n int f = comp->steps[op->ch2].ch1;\n\n if ((f != -1) &&\n (comp->steps[f].op == XPATH_OP_FUNCTION) &&\n (comp->steps[f].value5 == NULL) &&\n (comp->steps[f].value == 0) &&\n (comp->steps[f].value4 != NULL) &&\n (xmlStrEqual\n (comp->steps[f].value4, BAD_CAST \"last\"))) {\n xmlNodePtr last = NULL;\n\n total +=\n xmlXPathCompOpEvalLast(ctxt,\n &comp->steps[op->ch1],\n &last);\n\t\t\tCHECK_ERROR0;\n /*\n * The nodeset should be in document order,\n * Keep only the last value\n */\n if ((ctxt->value != NULL) &&\n (ctxt->value->type == XPATH_NODESET) &&\n (ctxt->value->nodesetval != NULL) &&\n (ctxt->value->nodesetval->nodeTab != NULL) &&\n (ctxt->value->nodesetval->nodeNr > 1)) {\n ctxt->value->nodesetval->nodeTab[0] =\n ctxt->value->nodesetval->nodeTab[ctxt->\n value->\n nodesetval->\n nodeNr -\n 1];\n ctxt->value->nodesetval->nodeNr = 1;\n }\n return (total);\n }\n }\n\t\t/*\n\t\t* Process inner predicates first.\n\t\t* Example \"index[parent::book][1]\":\n\t\t* ...\n\t\t* PREDICATE <-- we are here \"[1]\"\n\t\t* PREDICATE <-- process \"[parent::book]\" first\n\t\t* SORT\n\t\t* COLLECT 'parent' 'name' 'node' book\n\t\t* NODE\n\t\t* ELEM Object is a number : 1\n\t\t*/\n if (op->ch1 != -1)\n total +=\n xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t\tCHECK_ERROR0;\n if (op->ch2 == -1)\n return (total);\n if (ctxt->value == NULL)\n return (total);\n\n oldnode = ctxt->context->node;\n\n#ifdef LIBXML_XPTR_ENABLED\n /*\n * Hum are we filtering the result of an XPointer expression\n */\n if (ctxt->value->type == XPATH_LOCATIONSET) {\n xmlLocationSetPtr newlocset = NULL;\n xmlLocationSetPtr oldlocset;\n\n /*\n * Extract the old locset, and then evaluate the result of the\n * expression for all the element in the locset. use it to grow\n * up a new locset.\n */\n CHECK_TYPE0(XPATH_LOCATIONSET);\n obj = valuePop(ctxt);\n oldlocset = obj->user;\n ctxt->context->node = NULL;\n\n if ((oldlocset == NULL) || (oldlocset->locNr == 0)) {\n ctxt->context->contextSize = 0;\n ctxt->context->proximityPosition = 0;\n if (op->ch2 != -1)\n total +=\n xmlXPathCompOpEval(ctxt,\n &comp->steps[op->ch2]);\n res = valuePop(ctxt);\n if (res != NULL) {\n\t\t\t xmlXPathReleaseObject(ctxt->context, res);\n\t\t\t}\n valuePush(ctxt, obj);\n CHECK_ERROR0;\n return (total);\n }\n newlocset = xmlXPtrLocationSetCreate(NULL);\n\n for (i = 0; i < oldlocset->locNr; i++) {\n /*\n * Run the evaluation with a node list made of a\n * single item in the nodelocset.\n */\n ctxt->context->node = oldlocset->locTab[i]->user;\n ctxt->context->contextSize = oldlocset->locNr;\n ctxt->context->proximityPosition = i + 1;\n\t\t\ttmp = xmlXPathCacheNewNodeSet(ctxt->context,\n\t\t\t ctxt->context->node);\n valuePush(ctxt, tmp);\n\n if (op->ch2 != -1)\n total +=\n xmlXPathCompOpEval(ctxt,\n &comp->steps[op->ch2]);\n\t\t\tif (ctxt->error != XPATH_EXPRESSION_OK) {\n\t\t\t xmlXPathFreeObject(obj);\n\t\t\t return(0);\n\t\t\t}\n\n /*\n * The result of the evaluation need to be tested to\n * decided whether the filter succeeded or not\n */\n res = valuePop(ctxt);\n if (xmlXPathEvaluatePredicateResult(ctxt, res)) {\n xmlXPtrLocationSetAdd(newlocset,\n xmlXPathObjectCopy\n (oldlocset->locTab[i]));\n }\n\n /*\n * Cleanup\n */\n if (res != NULL) {\n\t\t\t xmlXPathReleaseObject(ctxt->context, res);\n\t\t\t}\n if (ctxt->value == tmp) {\n res = valuePop(ctxt);\n\t\t\t xmlXPathReleaseObject(ctxt->context, res);\n }\n\n ctxt->context->node = NULL;\n }\n\n /*\n * The result is used as the new evaluation locset.\n */\n\t\t xmlXPathReleaseObject(ctxt->context, obj);\n ctxt->context->node = NULL;\n ctxt->context->contextSize = -1;\n ctxt->context->proximityPosition = -1;\n valuePush(ctxt, xmlXPtrWrapLocationSet(newlocset));\n ctxt->context->node = oldnode;\n return (total);\n }\n#endif /* LIBXML_XPTR_ENABLED */\n\n /*\n * Extract the old set, and then evaluate the result of the\n * expression for all the element in the set. use it to grow\n * up a new set.\n */\n CHECK_TYPE0(XPATH_NODESET);\n obj = valuePop(ctxt);\n oldset = obj->nodesetval;\n\n oldnode = ctxt->context->node;\n\t\toldDoc = ctxt->context->doc;\n ctxt->context->node = NULL;\n\n if ((oldset == NULL) || (oldset->nodeNr == 0)) {\n ctxt->context->contextSize = 0;\n ctxt->context->proximityPosition = 0;\n/*\n if (op->ch2 != -1)\n total +=\n xmlXPathCompOpEval(ctxt,\n &comp->steps[op->ch2]);\n\t\t CHECK_ERROR0;\n res = valuePop(ctxt);\n if (res != NULL)\n xmlXPathFreeObject(res);\n*/\n valuePush(ctxt, obj);\n ctxt->context->node = oldnode;\n CHECK_ERROR0;\n } else {\n\t\t tmp = NULL;\n /*\n * Initialize the new set.\n\t\t * Also set the xpath document in case things like\n\t\t * key() evaluation are attempted on the predicate\n */\n newset = xmlXPathNodeSetCreate(NULL);\n\t\t /*\n\t\t * SPEC XPath 1.0:\n\t\t * \"For each node in the node-set to be filtered, the\n\t\t * PredicateExpr is evaluated with that node as the\n\t\t * context node, with the number of nodes in the\n\t\t * node-set as the context size, and with the proximity\n\t\t * position of the node in the node-set with respect to\n\t\t * the axis as the context position;\"\n\t\t * @oldset is the node-set\" to be filtered.\n\t\t *\n\t\t * SPEC XPath 1.0:\n\t\t * \"only predicates change the context position and\n\t\t * context size (see [2.4 Predicates]).\"\n\t\t * Example:\n\t\t * node-set context pos\n\t\t * nA 1\n\t\t * nB 2\n\t\t * nC 3\n\t\t * After applying predicate [position() > 1] :\n\t\t * node-set context pos\n\t\t * nB 1\n\t\t * nC 2\n\t\t *\n\t\t * removed the first node in the node-set, then\n\t\t * the context position of the\n\t\t */\n for (i = 0; i < oldset->nodeNr; i++) {\n /*\n * Run the evaluation with a node list made of\n * a single item in the nodeset.\n */\n ctxt->context->node = oldset->nodeTab[i];\n\t\t\tif ((oldset->nodeTab[i]->type != XML_NAMESPACE_DECL) &&\n\t\t\t (oldset->nodeTab[i]->doc != NULL))\n\t\t ctxt->context->doc = oldset->nodeTab[i]->doc;\n\t\t\tif (tmp == NULL) {\n\t\t\t tmp = xmlXPathCacheNewNodeSet(ctxt->context,\n\t\t\t\tctxt->context->node);\n\t\t\t} else {\n\t\t\t xmlXPathNodeSetAddUnique(tmp->nodesetval,\n\t\t\t\tctxt->context->node);\n\t\t\t}\n valuePush(ctxt, tmp);\n ctxt->context->contextSize = oldset->nodeNr;\n ctxt->context->proximityPosition = i + 1;\n\t\t\t/*\n\t\t\t* Evaluate the predicate against the context node.\n\t\t\t* Can/should we optimize position() predicates\n\t\t\t* here (e.g. \"[1]\")?\n\t\t\t*/\n if (op->ch2 != -1)\n total +=\n xmlXPathCompOpEval(ctxt,\n &comp->steps[op->ch2]);\n\t\t\tif (ctxt->error != XPATH_EXPRESSION_OK) {\n\t\t\t xmlXPathFreeNodeSet(newset);\n\t\t\t xmlXPathFreeObject(obj);\n\t\t\t return(0);\n\t\t\t}\n\n /*\n * The result of the evaluation needs to be tested to\n * decide whether the filter succeeded or not\n */\n\t\t\t/*\n\t\t\t* OPTIMIZE TODO: Can we use\n\t\t\t* xmlXPathNodeSetAdd*Unique()* instead?\n\t\t\t*/\n res = valuePop(ctxt);\n if (xmlXPathEvaluatePredicateResult(ctxt, res)) {\n xmlXPathNodeSetAdd(newset, oldset->nodeTab[i]);\n }\n\n /*\n * Cleanup\n */\n if (res != NULL) {\n\t\t\t xmlXPathReleaseObject(ctxt->context, res);\n\t\t\t}\n if (ctxt->value == tmp) {\n valuePop(ctxt);\n\t\t\t xmlXPathNodeSetClear(tmp->nodesetval, 1);\n\t\t\t /*\n\t\t\t * Don't free the temporary nodeset\n\t\t\t * in order to avoid massive recreation inside this\n\t\t\t * loop.\n\t\t\t */\n } else\n\t\t\t tmp = NULL;\n ctxt->context->node = NULL;\n }\n\t\t if (tmp != NULL)\n\t\t\txmlXPathReleaseObject(ctxt->context, tmp);\n /*\n * The result is used as the new evaluation set.\n */\n\t\t xmlXPathReleaseObject(ctxt->context, obj);\n ctxt->context->node = NULL;\n ctxt->context->contextSize = -1;\n ctxt->context->proximityPosition = -1;\n\t\t /* may want to move this past the '}' later */\n\t\t ctxt->context->doc = oldDoc;\n\t\t valuePush(ctxt,\n\t\t\txmlXPathCacheWrapNodeSet(ctxt->context, newset));\n }\n ctxt->context->node = oldnode;\n return (total);\n }\n case XPATH_OP_SORT:\n if (op->ch1 != -1)\n total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n\t CHECK_ERROR0;\n if ((ctxt->value != NULL) &&\n (ctxt->value->type == XPATH_NODESET) &&\n (ctxt->value->nodesetval != NULL) &&\n\t\t(ctxt->value->nodesetval->nodeNr > 1))\n\t {\n xmlXPathNodeSetSort(ctxt->value->nodesetval);\n\t }\n return (total);\n#ifdef LIBXML_XPTR_ENABLED\n case XPATH_OP_RANGETO:{\n xmlXPathObjectPtr range;\n xmlXPathObjectPtr res, obj;\n xmlXPathObjectPtr tmp;\n xmlLocationSetPtr newlocset = NULL;\n\t\t xmlLocationSetPtr oldlocset;\n xmlNodeSetPtr oldset;\n int i, j;\n\n if (op->ch1 != -1)\n total +=\n xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);\n if (op->ch2 == -1)\n return (total);\n\n if (ctxt->value->type == XPATH_LOCATIONSET) {\n /*\n * Extract the old locset, and then evaluate the result of the\n * expression for all the element in the locset. use it to grow\n * up a new locset.\n */\n CHECK_TYPE0(XPATH_LOCATIONSET);\n obj = valuePop(ctxt);\n oldlocset = obj->user;\n\n if ((oldlocset == NULL) || (oldlocset->locNr == 0)) {\n\t\t ctxt->context->node = NULL;\n ctxt->context->contextSize = 0;\n ctxt->context->proximityPosition = 0;\n total += xmlXPathCompOpEval(ctxt,&comp->steps[op->ch2]);\n res = valuePop(ctxt);\n if (res != NULL) {\n\t\t\t xmlXPathReleaseObject(ctxt->context, res);\n\t\t\t}\n valuePush(ctxt, obj);\n CHECK_ERROR0;\n return (total);\n }\n newlocset = xmlXPtrLocationSetCreate(NULL);\n\n for (i = 0; i < oldlocset->locNr; i++) {\n /*\n * Run the evaluation with a node list made of a\n * single item in the nodelocset.\n */\n ctxt->context->node = oldlocset->locTab[i]->user;\n ctxt->context->contextSize = oldlocset->locNr;\n ctxt->context->proximityPosition = i + 1;\n\t\t\ttmp = xmlXPathCacheNewNodeSet(ctxt->context,\n\t\t\t ctxt->context->node);\n valuePush(ctxt, tmp);\n\n if (op->ch2 != -1)\n total +=\n xmlXPathCompOpEval(ctxt,\n &comp->steps[op->ch2]);\n\t\t\tif (ctxt->error != XPATH_EXPRESSION_OK) {\n\t\t\t xmlXPathFreeObject(obj);\n\t\t\t return(0);\n\t\t\t}\n\n res = valuePop(ctxt);\n\t\t\tif (res->type == XPATH_LOCATIONSET) {\n\t\t\t xmlLocationSetPtr rloc =\n\t\t\t (xmlLocationSetPtr)res->user;\n\t\t\t for (j=0; jlocNr; j++) {\n\t\t\t range = xmlXPtrNewRange(\n\t\t\t\t oldlocset->locTab[i]->user,\n\t\t\t\t oldlocset->locTab[i]->index,\n\t\t\t\t rloc->locTab[j]->user2,\n\t\t\t\t rloc->locTab[j]->index2);\n\t\t\t\tif (range != NULL) {\n\t\t\t\t xmlXPtrLocationSetAdd(newlocset, range);\n\t\t\t\t}\n\t\t\t }\n\t\t\t} else {\n\t\t\t range = xmlXPtrNewRangeNodeObject(\n\t\t\t\t(xmlNodePtr)oldlocset->locTab[i]->user, res);\n if (range != NULL) {\n xmlXPtrLocationSetAdd(newlocset,range);\n\t\t\t }\n }\n\n /*\n * Cleanup\n */\n if (res != NULL) {\n\t\t\t xmlXPathReleaseObject(ctxt->context, res);\n\t\t\t}\n if (ctxt->value == tmp) {\n res = valuePop(ctxt);\n\t\t\t xmlXPathReleaseObject(ctxt->context, res);\n }\n\n ctxt->context->node = NULL;\n }\n\t\t} else {\t/* Not a location set */\n CHECK_TYPE0(XPATH_NODESET);\n obj = valuePop(ctxt);\n oldset = obj->nodesetval;\n ctxt->context->node = NULL;\n\n newlocset = xmlXPtrLocationSetCreate(NULL);\n\n if (oldset != NULL) {\n for (i = 0; i < oldset->nodeNr; i++) {\n /*\n * Run the evaluation with a node list made of a single item\n * in the nodeset.\n */\n ctxt->context->node = oldset->nodeTab[i];\n\t\t\t /*\n\t\t\t * OPTIMIZE TODO: Avoid recreation for every iteration.\n\t\t\t */\n\t\t\t tmp = xmlXPathCacheNewNodeSet(ctxt->context,\n\t\t\t\tctxt->context->node);\n valuePush(ctxt, tmp);\n\n if (op->ch2 != -1)\n total +=\n xmlXPathCompOpEval(ctxt,\n &comp->steps[op->ch2]);\n\t\t\t if (ctxt->error != XPATH_EXPRESSION_OK) {\n\t\t\t\txmlXPathFreeObject(obj);\n\t\t\t\treturn(0);\n\t\t\t }\n\n res = valuePop(ctxt);\n range =\n xmlXPtrNewRangeNodeObject(oldset->nodeTab[i],\n res);\n if (range != NULL) {\n xmlXPtrLocationSetAdd(newlocset, range);\n }\n\n /*\n * Cleanup\n */\n if (res != NULL) {\n\t\t\t\txmlXPathReleaseObject(ctxt->context, res);\n\t\t\t }\n if (ctxt->value == tmp) {\n res = valuePop(ctxt);\n\t\t\t\txmlXPathReleaseObject(ctxt->context, res);\n }\n\n ctxt->context->node = NULL;\n }\n }\n }\n\n /*\n * The result is used as the new evaluation set.\n */\n\t\txmlXPathReleaseObject(ctxt->context, obj);\n ctxt->context->node = NULL;\n ctxt->context->contextSize = -1;\n ctxt->context->proximityPosition = -1;\n valuePush(ctxt, xmlXPtrWrapLocationSet(newlocset));\n return (total);\n }\n#endif /* LIBXML_XPTR_ENABLED */\n }\n xmlGenericError(xmlGenericErrorContext,\n \"XPath: unknown precompiled operation %d\\n\", op->op); ; 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 SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag,\n uint32_t lun, void *hba_private)\n{\n SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);\n SCSIRequest *req;\n SCSIDiskReq *r;\n\n req = scsi_req_alloc(&scsi_disk_reqops, &s->qdev, tag, lun, hba_private);\n r = DO_UPCAST(SCSIDiskReq, req, req);\n r->iov.iov_base = qemu_blockalign(s->bs, SCSI_DMA_BUF_SIZE);\n return req;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'scsi-disk: lazily allocate bounce buffer\n\nIt will not be needed for reads and writes if the HBA provides a sglist.\nIn addition, this lets scsi-disk refuse commands with an excessive\nallocation length, as well as limit memory on usual well-behaved guests.\n\nSigned-off-by: Paolo Bonzini \nSigned-off-by: Kevin Wolf '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void cmd_help(void)\n{\n prot_printf(nntp_out, \"100 Supported commands:\\r\\n\");\n\n if ((nntp_capa & MODE_READ) && (nntp_userid || allowanonymous)) {\n\tprot_printf(nntp_out, \"\\tARTICLE [ message-id | number ]\\r\\n\"\n\t\t \"\\t\\tRetrieve entirety of the specified article.\\r\\n\");\n }\n if (!nntp_authstate) {\n\tif (!nntp_userid) {\n\t prot_printf(nntp_out, \"\\tAUTHINFO SASL mechanism [initial-response]\\r\\n\"\n\t\t\t\"\\t\\tPerform an authentication exchange using the specified\\r\\n\"\n\t\t\t\"\\t\\tSASL mechanism.\\r\\n\");\n\t prot_printf(nntp_out, \"\\tAUTHINFO USER username\\r\\n\"\n\t\t\t\"\\t\\tPresent username for authentication.\\r\\n\");\n\t}\n\tprot_printf(nntp_out, \"\\tAUTHINFO PASS password\\r\\n\"\n\t\t \"\\t\\tPresent clear-text password for authentication.\\r\\n\");\n }\n if ((nntp_capa & MODE_READ) && (nntp_userid || allowanonymous)) {\n\tprot_printf(nntp_out, \"\\tBODY [ message-id | number ]\\r\\n\"\n\t\t \"\\t\\tRetrieve body of the specified article.\\r\\n\");\n }\n prot_printf(nntp_out, \"\\tCAPABILITIES\\r\\n\"\n\t\t\"\\t\\tList the current server capabilities.\\r\\n\");\n if (nntp_capa & MODE_FEED) {\n\tprot_printf(nntp_out, \"\\tCHECK message-id\\r\\n\"\n\t\t \"\\t\\tCheck if the server wants the specified article.\\r\\n\");\n }\n if ((nntp_capa & MODE_READ) && (nntp_userid || allowanonymous)) {\n\tprot_printf(nntp_out, \"\\tDATE\\r\\n\"\n\t\t \"\\t\\tRequest the current server UTC date and time.\\r\\n\");\n\tprot_printf(nntp_out, \"\\tGROUP group\\r\\n\"\n\t\t \"\\t\\tSelect a newsgroup for article retrieval.\\r\\n\");\n\tprot_printf(nntp_out, \"\\tHDR header [ message-id | range ]\\r\\n\"\n\t\t \"\\t\\tRetrieve the specified header/metadata from the\\r\\n\"\n\t\t \"\\t\\tspecified article(s).\\r\\n\");\n }\n prot_printf(nntp_out, \"\\tHEAD [ message-id | number ]\\r\\n\"\n\t\t\"\\t\\tRetrieve the headers of the specified article.\\r\\n\");\n prot_printf(nntp_out, \"\\tHELP\\r\\n\"\n\t\t\"\\t\\tRequest command summary (this text).\\r\\n\");\n if (nntp_capa & MODE_FEED) {\n\tprot_printf(nntp_out, \"\\tIHAVE message-id\\r\\n\"\n\t\t \"\\t\\tPresent/transfer the specified article to the server.\\r\\n\");\n }\n if ((nntp_capa & MODE_READ) && (nntp_userid || allowanonymous)) {\n\tprot_printf(nntp_out, \"\\tLAST\\r\\n\"\n\t\t \"\\t\\tSelect the previous article.\\r\\n\");\n }\n prot_printf(nntp_out, \"\\tLIST [ ACTIVE wildmat ]\\r\\n\"\n\t\t\"\\t\\tList the (subset of) valid newsgroups.\\r\\n\");\n if ((nntp_capa & MODE_READ) && (nntp_userid || allowanonymous)) {\n\tprot_printf(nntp_out, \"\\tLIST HEADERS [ MSGID | RANGE ]\\r\\n\"\n\t\t \"\\t\\tList the headers and metadata items available via HDR.\\r\\n\");\n\tprot_printf(nntp_out, \"\\tLIST NEWSGROUPS [wildmat]\\r\\n\"\n\t\t \"\\t\\tList the descriptions of the specified newsgroups.\\r\\n\");\n\tprot_printf(nntp_out, \"\\tLIST OVERVIEW.FMT\\r\\n\"\n\t\t \"\\t\\tList the headers and metadata items available via OVER.\\r\\n\");\n\tprot_printf(nntp_out, \"\\tLISTGROUP [group [range]]\\r\\n\"\n\t\t \"\\t\\tList the article numbers in the specified newsgroup.\\r\\n\");\n\tif (config_getswitch(IMAPOPT_ALLOWNEWNEWS))\n\t prot_printf(nntp_out, \"\\tNEWNEWS wildmat date time [GMT]\\r\\n\"\n\t\t\t\"\\t\\tList the newly arrived articles in the specified newsgroup(s)\\r\\n\"\n\t\t\t\"\\t\\tsince the specified date and time.\\r\\n\");\n\tprot_printf(nntp_out, \"\\tNEXT\\r\\n\"\n\t\t \"\\t\\tSelect the next article.\\r\\n\");\n\tprot_printf(nntp_out, \"\\tOVER [ message-id | range ]\\r\\n\"\n\t\t \"\\t\\tRetrieve the overview information for the specified article(s).\\r\\n\");\n\tprot_printf(nntp_out, \"\\tPOST\\r\\n\"\n\t\t \"\\t\\tPost an article to the server.\\r\\n\");\n }\n\n prot_printf(nntp_out, \"\\tQUIT\\r\\n\"\n\t\t\"\\t\\tTerminate the session.\\r\\n\");\n if (tls_enabled() && !nntp_starttls_done && !nntp_authstate) {\n\tprot_printf(nntp_out, \"\\tSTARTTLS\\r\\n\"\n\t\t \"\\t\\tStart a TLS negotiation.\\r\\n\");\n }\n prot_printf(nntp_out, \"\\tSTAT [ message-id | number ]\\r\\n\"\n\t\t\"\\t\\tCheck if the specified article exists.\\r\\n\");\n if (nntp_capa & MODE_FEED) {\n\tprot_printf(nntp_out, \"\\tTAKETHIS message-id\\r\\n\"\n\t\t \"\\t\\tTransfer the specified article to the server.\\r\\n\");\n }\n if ((nntp_capa & MODE_READ) && (nntp_userid || allowanonymous)) {\n\tprot_printf(nntp_out, \"\\tXPAT header message-id|range wildmat\\r\\n\"\n\t\t \"\\t\\tList the specified article(s) in which the contents\\r\\n\"\n\t\t \"\\t\\tof the specified header/metadata matches the wildmat.\\r\\n\");\n }\n prot_printf(nntp_out, \".\\r\\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: assemble_mountinfo(struct parsed_mount_info *parsed_info,\n\t\t const char *thisprogram, const char *mountpoint,\n\t\t const char *orig_dev, char *orgoptions)\n{\n\tint rc;\n\n\trc = drop_child_privs();\n\tif (rc)\n\t\tgoto assemble_exit;\n\n\tif (getuid()) {\n\t\trc = check_fstab(thisprogram, mountpoint, orig_dev,\n\t\t\t\t &orgoptions);\n\t\tif (rc)\n\t\t\tgoto assemble_exit;\n\n\t\t/* enable any default user mount flags */\n\t\tparsed_info->flags |= CIFS_SETUID_FLAGS;\n\t}\n\n\trc = get_pw_from_env(parsed_info);\n\tif (rc)\n\t\tgoto assemble_exit;\n\n\tif (orgoptions) {\n\t\trc = parse_options(orgoptions, parsed_info);\n\t\tif (rc)\n\t\t\tgoto assemble_exit;\n\t}\n\n\tif (getuid()) {\n\t\tif (!(parsed_info->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 assemble_exit;\n\t\t}\n\t}\n\n\tparsed_info->flags &= ~(MS_USERS | MS_USER);\n\n\trc = parse_unc(orig_dev, parsed_info);\n\tif (rc)\n\t\tgoto assemble_exit;\n\n\trc = resolve_host(parsed_info);\n\tif (rc)\n\t\tgoto assemble_exit;\n\n\tif (!parsed_info->got_user) {\n\t\t/*\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\t */\n\t\tif (getenv(\"USER\"))\n\t\t\tstrlcpy(parsed_info->username, getenv(\"USER\"),\n\t\t\t\tsizeof(parsed_info->username));\n\t\telse\n\t\t\tstrlcpy(parsed_info->username, getusername(),\n\t\t\t\tsizeof(parsed_info->username));\n\t\tparsed_info->got_user = 1;\n\t}\n\n\tif (!parsed_info->got_password) {\n\t\t/* getpass is obsolete, but there's apparently nothing that replaces it */\n\t\tchar *tmp_pass = getpass(\"Password: \");\n\t\tif (!tmp_pass) {\n\t\t\tfprintf(stderr, \"Error reading password, exiting\\n\");\n\t\t\trc = EX_SYSERR;\n\t\t\tgoto assemble_exit;\n\t\t}\n\t\trc = set_password(parsed_info, tmp_pass);\n\t\tif (rc)\n\t\t\tgoto assemble_exit;\n\t}\n\n\t/* copy in ver= string. It's not really needed, but what the hell */\n\tstrlcat(parsed_info->options, \",ver=\", sizeof(parsed_info->options));\n\tstrlcat(parsed_info->options, OPTIONS_VERSION, sizeof(parsed_info->options));\n\n\t/* copy in user= string */\n\tif (parsed_info->got_user) {\n\t\tstrlcat(parsed_info->options, \",user=\",\n\t\t\tsizeof(parsed_info->options));\n\t\tstrlcat(parsed_info->options, parsed_info->username,\n\t\t\tsizeof(parsed_info->options));\n\t}\n\n\tif (*parsed_info->domain) {\n\t\tstrlcat(parsed_info->options, \",domain=\",\n\t\t\tsizeof(parsed_info->options));\n\t\tstrlcat(parsed_info->options, parsed_info->domain,\n\t\t\tsizeof(parsed_info->options));\n\t}\n\nassemble_exit:\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: static int _expand_arg(pam_handle_t *pamh, char **value)\n{\n const char *orig=*value, *tmpptr=NULL;\n char *ptr; /*\n\t\t * Sure would be nice to use tmpptr but it needs to be\n\t\t * a constant so that the compiler will shut up when I\n\t\t * call pam_getenv and _pam_get_item_byname -- sigh\n\t\t */\n\n /* No unexpanded variable can be bigger than BUF_SIZE */\n char type, tmpval[BUF_SIZE];\n\n /* I know this shouldn't be hard-coded but it's so much easier this way */\n char tmp[MAX_ENV];\n\n D((\"Remember to initialize tmp!\"));\n memset(tmp, 0, MAX_ENV);\n\n /*\n * (possibly non-existent) environment variables can be used as values\n * by prepending a \"$\" and wrapping in {} (ie: ${HOST}), can escape with \"\\\"\n * (possibly non-existent) PAM items can be used as values\n * by prepending a \"@\" and wrapping in {} (ie: @{PAM_RHOST}, can escape\n *\n */\n D((\"Expanding <%s>\",orig));\n while (*orig) { /* while there is some input to deal with */\n if ('\\\\' == *orig) {\n ++orig;\n if ('$' != *orig && '@' != *orig) {\n\tD((\"Unrecognized escaped character: <%c> - ignoring\", *orig));\n\tpam_syslog(pamh, LOG_ERR,\n\t\t \"Unrecognized escaped character: <%c> - ignoring\",\n\t\t *orig);\n } else if ((strlen(tmp) + 1) < MAX_ENV) {\n\ttmp[strlen(tmp)] = *orig++; /* Note the increment */\n } else {\n\t/* is it really a good idea to try to log this? */\n\tD((\"Variable buffer overflow: <%s> + <%s>\", tmp, tmpptr));\n\tpam_syslog (pamh, LOG_ERR, \"Variable buffer overflow: <%s> + <%s>\",\n\t\t tmp, tmpptr);\n }\n continue;\n }\n if ('$' == *orig || '@' == *orig) {\n if ('{' != *(orig+1)) {\n\tD((\"Expandable variables must be wrapped in {}\"\n\t \" <%s> - ignoring\", orig));\n\tpam_syslog(pamh, LOG_ERR, \"Expandable variables must be wrapped in {}\"\n\t\t \" <%s> - ignoring\", orig);\n\tif ((strlen(tmp) + 1) < MAX_ENV) {\n\t tmp[strlen(tmp)] = *orig++; /* Note the increment */\n\t}\n\tcontinue;\n } else {\n\tD((\"Expandable argument: <%s>\", orig));\n\ttype = *orig;\n\torig+=2; /* skip the ${ or @{ characters */\n\tptr = strchr(orig, '}');\n\tif (ptr) {\n\t *ptr++ = '\\0';\n\t} else {\n\t D((\"Unterminated expandable variable: <%s>\", orig-2));\n\t pam_syslog(pamh, LOG_ERR,\n\t\t \"Unterminated expandable variable: <%s>\", orig-2);\n\t return PAM_ABORT;\n\t}\n\tstrncpy(tmpval, orig, sizeof(tmpval));\n\ttmpval[sizeof(tmpval)-1] = '\\0';\n\torig=ptr;\n\t/*\n\t * so, we know we need to expand tmpval, it is either\n\t * an environment variable or a PAM_ITEM. type will tell us which\n\t */\n\tswitch (type) {\n\n\tcase '$':\n\t D((\"Expanding env var: <%s>\",tmpval));\n\t tmpptr = pam_getenv(pamh, tmpval);\n\t D((\"Expanded to <%s>\", tmpptr));\n\t break;\n\n\tcase '@':\n\t D((\"Expanding pam item: <%s>\",tmpval));\n\t tmpptr = _pam_get_item_byname(pamh, tmpval);\n\t D((\"Expanded to <%s>\", tmpptr));\n\t break;\n\n\tdefault:\n\t D((\"Impossible error, type == <%c>\", type));\n\t pam_syslog(pamh, LOG_CRIT, \"Impossible error, type == <%c>\", type);\n\t return PAM_ABORT;\n\t} /* switch */\n\n\tif (tmpptr) {\n\t if ((strlen(tmp) + strlen(tmpptr)) < MAX_ENV) {\n\t strcat(tmp, tmpptr);\n\t } else {\n\t /* is it really a good idea to try to log this? */\n\t D((\"Variable buffer overflow: <%s> + <%s>\", tmp, tmpptr));\n\t pam_syslog (pamh, LOG_ERR,\n\t\t\t\"Variable buffer overflow: <%s> + <%s>\", tmp, tmpptr);\n\t }\n\t}\n } /* if ('{' != *orig++) */\n } else { /* if ( '$' == *orig || '@' == *orig) */\n if ((strlen(tmp) + 1) < MAX_ENV) {\n\ttmp[strlen(tmp)] = *orig++; /* Note the increment */\n } else {\n\t/* is it really a good idea to try to log this? */\n\tD((\"Variable buffer overflow: <%s> + <%s>\", tmp, tmpptr));\n\tpam_syslog(pamh, LOG_ERR,\n\t\t \"Variable buffer overflow: <%s> + <%s>\", tmp, tmpptr);\n }\n }\n } /* for (;*orig;) */\n\n if (strlen(tmp) > strlen(*value)) {\n free(*value);\n if ((*value = malloc(strlen(tmp) +1)) == NULL) {\n D((\"Couldn't malloc %d bytes for expanded var\", strlen(tmp)+1));\n pam_syslog (pamh, LOG_ERR, \"Couldn't malloc %lu bytes for expanded var\",\n\t (unsigned long)strlen(tmp)+1);\n return PAM_BUF_ERR;\n }\n }\n strcpy(*value, tmp);\n memset(tmp,'\\0',sizeof(tmp));\n D((\"Exit.\"));\n\n return PAM_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'pam_env: abort when encountering an overflowed environment variable expansion\n\n* modules/pam_env/pam_env.c (_expand_arg): Abort when encountering an\noverflowed environment variable expansion.\nFixes CVE-2011-3149.\nBug-Ubuntu: https://bugs.launchpad.net/ubuntu/+source/pam/+bug/874565'" }, { "text": "[INST] Given the following code containing errors, provide Common 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 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': 'Don't give the Guard flag to relays without the CVE-2011-2768 fix'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: gnutls_session_get_data (gnutls_session_t session,\n void *session_data, size_t * session_data_size)\n{\n\n gnutls_datum_t psession;\n int ret;\n\n if (session->internals.resumable == RESUME_FALSE)\n return GNUTLS_E_INVALID_SESSION;\n\n psession.data = session_data;\n\n ret = _gnutls_session_pack (session, &psession);\n if (ret < 0)\n {\n gnutls_assert ();\n return ret;\n }\n\n if (psession.size > *session_data_size)\n {\n ret = GNUTLS_E_SHORT_MEMORY_BUFFER;\n goto error;\n }\n *session_data_size = psession.size;\n\n if (session_data != NULL)\n memcpy (session_data, psession.data, psession.size);\n\n ret = 0;\n\nerror:\n _gnutls_free_datum (&psession);\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'bug fix in gnutls_session_get_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: char *suhosin_encrypt_single_cookie(char *name, int name_len, char *value, int value_len, char *key TSRMLS_DC)\n{\n\tchar buffer[4096];\n char buffer2[4096];\n\tchar *buf = buffer, *buf2 = buffer2, *d, *d_url;\n int 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)) {\nencrypt_return_plain:\n\t\t\tif (buf != buffer) {\n\t\t\t\tefree(buf);\n\t\t\t}\n\t\t\treturn estrndup(value, value_len);\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 encrypt_return_plain;\n\t\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_encrypt_string(buf2, value_len, buf, name_len, key TSRMLS_CC);\n\td_url = php_url_encode(d, strlen(d), &l);\n\tefree(d);\n if (buf != buffer) {\n\t\tefree(buf);\n\t}\n if (buf2 != buffer2) {\n\t\tefree(buf2);\n\t}\n\treturn d_url;\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: xmlDictCreate(void) {\n xmlDictPtr dict;\n\n if (!xmlDictInitialized)\n if (!xmlInitializeDict())\n return(NULL);\n\n#ifdef DICT_DEBUG_PATTERNS\n fprintf(stderr, \"C\");\n#endif\n\n dict = xmlMalloc(sizeof(xmlDict));\n if (dict) {\n dict->ref_counter = 1;\n\n dict->size = MIN_DICT_SIZE;\n\tdict->nbElems = 0;\n dict->dict = xmlMalloc(MIN_DICT_SIZE * sizeof(xmlDictEntry));\n\tdict->strings = NULL;\n\tdict->subdict = NULL;\n if (dict->dict) {\n\t memset(dict->dict, 0, MIN_DICT_SIZE * sizeof(xmlDictEntry));\n\t return(dict);\n }\n xmlFree(dict);\n }\n return(NULL);\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: dotraplinkage void __kprobes do_int3(struct pt_regs *regs, long error_code)\n{\n#ifdef CONFIG_KGDB_LOW_LEVEL_TRAP\n\tif (kgdb_ll_trap(DIE_INT3, \"int3\", regs, error_code, 3, SIGTRAP)\n\t\t\t== NOTIFY_STOP)\n\t\treturn;\n#endif /* CONFIG_KGDB_LOW_LEVEL_TRAP */\n#ifdef CONFIG_KPROBES\n\tif (notify_die(DIE_INT3, \"int3\", regs, error_code, 3, SIGTRAP)\n\t\t\t== NOTIFY_STOP)\n\t\treturn;\n#else\n\tif (notify_die(DIE_TRAP, \"int3\", regs, error_code, 3, SIGTRAP)\n\t\t\t== NOTIFY_STOP)\n\t\treturn;\n#endif\n\n\tpreempt_conditional_sti(regs);\n\tdo_trap(3, SIGTRAP, \"int3\", regs, error_code, NULL);\n\tpreempt_conditional_cli(regs);\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: bgp_capability_as4 (struct peer *peer, struct capability_header *hdr)\n{\n as_t as4 = stream_getl (BGP_INPUT(peer));\n \n if (BGP_DEBUG (as4, AS4))\n zlog_debug (\"%s [AS4] about to set cap PEER_CAP_AS4_RCV, got as4 %u\",\n peer->host, as4);\n SET_FLAG (peer->cap, PEER_CAP_AS4_RCV);\n \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: GnashImage::GnashImage(iterator data, size_t width, size_t height,\n ImageType type, ImageLocation location)\n :\n _type(type),\n _location(location),\n _width(width),\n _height(height),\n _data(data)\n{\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'Fix crash in GnashImage.cpp'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,\n\t\t\t\t\tunsigned long addr, unsigned long end,\n\t\t\t\t\tstruct mm_walk *walk)\n{\n\tstruct vm_area_struct *vma = walk->private;\n\tpte_t *pte;\n\tspinlock_t *ptl;\n\n\tsplit_huge_page_pmd(walk->mm, pmd);\n\n\tpte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);\n\tfor (; addr != end; pte++, addr += PAGE_SIZE)\n\t\tif (is_target_pte_for_mc(vma, addr, *pte, NULL))\n\t\t\tmc.precharge++;\t/* increment precharge temporarily */\n\tpte_unmap_unlock(pte - 1, ptl);\n\tcond_resched();\n\n\treturn 0;\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_property_info(const cdf_property_info_t *info, size_t count)\n{\n\tcdf_timestamp_t tp;\n\tstruct timespec ts;\n\tchar buf[64];\n\tsize_t i, j;\n\n\tfor (i = 0; i < count; i++) {\n\t\tcdf_print_property_name(buf, sizeof(buf), info[i].pi_id);\n\t\t(void)fprintf(stderr, \"%\" SIZE_T_FORMAT \"u) %s: \", i, buf);\n\t\tswitch (info[i].pi_type) {\n\t\tcase CDF_NULL:\n\t\t\tbreak;\n\t\tcase CDF_SIGNED16:\n\t\t\t(void)fprintf(stderr, \"signed 16 [%hd]\\n\",\n\t\t\t info[i].pi_s16);\n\t\t\tbreak;\n\t\tcase CDF_SIGNED32:\n\t\t\t(void)fprintf(stderr, \"signed 32 [%d]\\n\",\n\t\t\t info[i].pi_s32);\n\t\t\tbreak;\n\t\tcase CDF_UNSIGNED32:\n\t\t\t(void)fprintf(stderr, \"unsigned 32 [%u]\\n\",\n\t\t\t info[i].pi_u32);\n\t\t\tbreak;\n\t\tcase CDF_LENGTH32_STRING:\n\t\t\t(void)fprintf(stderr, \"string %u [%.*s]\\n\",\n\t\t\t info[i].pi_str.s_len,\n\t\t\t info[i].pi_str.s_len, info[i].pi_str.s_buf);\n\t\t\tbreak;\n\t\tcase CDF_LENGTH32_WSTRING:\n\t\t\t(void)fprintf(stderr, \"string %u [\",\n\t\t\t info[i].pi_str.s_len);\n\t\t\tfor (j = 0; j < info[i].pi_str.s_len - 1; j++)\n\t\t\t (void)fputc(info[i].pi_str.s_buf[j << 1], stderr);\n\t\t\t(void)fprintf(stderr, \"]\\n\");\n\t\t\tbreak;\n\t\tcase CDF_FILETIME:\n\t\t\ttp = info[i].pi_tp;\n\t\t\tif (tp < 1000000000000000LL) {\n\t\t\t\tcdf_print_elapsed_time(buf, sizeof(buf), tp);\n\t\t\t\t(void)fprintf(stderr, \"timestamp %s\\n\", buf);\n\t\t\t} else {\n\t\t\t\tcdf_timestamp_to_timespec(&ts, tp);\n\t\t\t\t(void)fprintf(stderr, \"timestamp %s\",\n\t\t\t\t cdf_ctime(&ts.tv_sec));\n\t\t\t}\n\t\t\tbreak;\n\t\tcase CDF_CLIPBOARD:\n\t\t\t(void)fprintf(stderr, \"CLIPBOARD %u\\n\", info[i].pi_u32);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tDPRINTF((\"Don't know how to deal with %x\\n\",\n\t\t\t info[i].pi_type));\n\t\t\tbreak;\n\t\t}\n\t}\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: _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 uint8_t 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 if (ciphertext.size == 0)\n {\n gnutls_assert ();\n return GNUTLS_E_DECRYPTION_FAILED;\n }\n }\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': 'better check decrypted 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: _crypt_extended_r(const char *key, const char *setting,\n\tstruct php_crypt_extended_data *data)\n{\n\tint\t\ti;\n\tuint32_t\tcount, salt, l, r0, r1, keybuf[2];\n\tu_char\t\t*p, *q;\n\n\tif (!data->initialized)\n\t\tdes_init_local(data);\n\n\t/*\n\t * Copy the key, shifting each character up by one bit\n\t * and padding with zeros.\n\t */\n\tq = (u_char *) keybuf;\n\twhile (q - (u_char *) keybuf < sizeof(keybuf)) {\n\t\tif ((*q++ = *key << 1))\n\t\t\tkey++;\n\t}\n\tif (des_setkey((u_char *) keybuf, data))\n\t\treturn(NULL);\n\n\tif (*setting == _PASSWORD_EFMT1) {\n\t\t/*\n\t\t * \"new\"-style:\n\t\t *\tsetting - underscore, 4 chars of count, 4 chars of salt\n\t\t *\tkey - unlimited characters\n\t\t */\n\t\tfor (i = 1, count = 0; i < 5; i++) {\n\t\t\tint value = ascii_to_bin(setting[i]);\n\t\t\tif (ascii64[value] != setting[i])\n\t\t\t\treturn(NULL);\n\t\t\tcount |= value << (i - 1) * 6;\n\t\t}\n\t\tif (!count)\n\t\t\treturn(NULL);\n\n\t\tfor (i = 5, salt = 0; i < 9; i++) {\n\t\t\tint value = ascii_to_bin(setting[i]);\n\t\t\tif (ascii64[value] != setting[i])\n\t\t\t\treturn(NULL);\n\t\t\tsalt |= value << (i - 5) * 6;\n\t\t}\n\n\t\twhile (*key) {\n\t\t\t/*\n\t\t\t * Encrypt the key with itself.\n\t\t\t */\n\t\t\tif (des_cipher((u_char *) keybuf, (u_char *) keybuf,\n\t\t\t 0, 1, data))\n\t\t\t\treturn(NULL);\n\t\t\t/*\n\t\t\t * And XOR with the next 8 characters of the key.\n\t\t\t */\n\t\t\tq = (u_char *) keybuf;\n\t\t\twhile (q - (u_char *) keybuf < sizeof(keybuf) && *key)\n\t\t\t\t*q++ ^= *key++ << 1;\n\n\t\t\tif (des_setkey((u_char *) keybuf, data))\n\t\t\t\treturn(NULL);\n\t\t}\n\t\tmemcpy(data->output, setting, 9);\n\t\tdata->output[9] = '\\0';\n\t\tp = (u_char *) data->output + 9;\n\t} else {\n\t\t/*\n\t\t * \"old\"-style:\n\t\t *\tsetting - 2 chars of salt\n\t\t *\tkey - up to 8 characters\n\t\t */\n\t\tcount = 25;\n\n\t\tif (ascii_is_unsafe(setting[0]) || ascii_is_unsafe(setting[1]))\n\t\t\treturn(NULL);\n\n\t\tsalt = (ascii_to_bin(setting[1]) << 6)\n\t\t | ascii_to_bin(setting[0]);\n\n\t\tdata->output[0] = setting[0];\n\t\tdata->output[1] = setting[1];\n\t\tp = (u_char *) data->output + 2;\n\t}\n\tsetup_salt(salt, data);\n\t/*\n\t * Do it.\n\t */\n\tif (do_des(0, 0, &r0, &r1, count, data))\n\t\treturn(NULL);\n\t/*\n\t * Now encode the result...\n\t */\n\tl = (r0 >> 8);\n\t*p++ = ascii64[(l >> 18) & 0x3f];\n\t*p++ = ascii64[(l >> 12) & 0x3f];\n\t*p++ = ascii64[(l >> 6) & 0x3f];\n\t*p++ = ascii64[l & 0x3f];\n\n\tl = (r0 << 16) | ((r1 >> 16) & 0xffff);\n\t*p++ = ascii64[(l >> 18) & 0x3f];\n\t*p++ = ascii64[(l >> 12) & 0x3f];\n\t*p++ = ascii64[(l >> 6) & 0x3f];\n\t*p++ = ascii64[l & 0x3f];\n\n\tl = r1 << 2;\n\t*p++ = ascii64[(l >> 12) & 0x3f];\n\t*p++ = ascii64[(l >> 6) & 0x3f];\n\t*p++ = ascii64[l & 0x3f];\n\t*p = 0;\n\n\treturn(data->output);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'fix CVE-2012-2143'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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\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 bug #61065'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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 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() overflow\n\n* malloc.c (calloc): Check multiplication overflow in calloc(),\nassuming REDIRECT_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: handle_client_accesses(CMD_Request *rx_message, CMD_Reply *tx_message)\n{\n CLG_Status result;\n RPT_ClientAccess_Report report;\n unsigned long nc;\n IPAddr ip;\n int i;\n struct timeval now;\n\n LCL_ReadCookedTime(&now, NULL);\n\n nc = ntohl(rx_message->data.client_accesses.n_clients);\n tx_message->status = htons(STT_SUCCESS);\n tx_message->reply = htons(RPY_CLIENT_ACCESSES);\n tx_message->data.client_accesses.n_clients = htonl(nc);\n\n printf(\"%d %d\\n\", (int)sizeof(RPY_ClientAccesses_Client), (int)offsetof(CMD_Reply, data.client_accesses.clients));\n\n for (i=0; idata.client_accesses.client_ips[i], &ip);\n UTI_IPHostToNetwork(&ip, &tx_message->data.client_accesses.clients[i].ip);\n\n result = CLG_GetClientAccessReportByIP(&ip, &report, now.tv_sec);\n switch (result) {\n case CLG_SUCCESS:\n tx_message->data.client_accesses.clients[i].client_hits = htonl(report.client_hits);\n tx_message->data.client_accesses.clients[i].peer_hits = htonl(report.peer_hits);\n tx_message->data.client_accesses.clients[i].cmd_hits_auth = htonl(report.cmd_hits_auth);\n tx_message->data.client_accesses.clients[i].cmd_hits_normal = htonl(report.cmd_hits_normal);\n tx_message->data.client_accesses.clients[i].cmd_hits_bad = htonl(report.cmd_hits_bad);\n tx_message->data.client_accesses.clients[i].last_ntp_hit_ago = htonl(report.last_ntp_hit_ago);\n tx_message->data.client_accesses.clients[i].last_cmd_hit_ago = htonl(report.last_cmd_hit_ago);\n printf(\"%s %lu %lu %lu %lu %lu %lu %lu\\n\", UTI_IPToString(&ip), report.client_hits, report.peer_hits, report.cmd_hits_auth, report.cmd_hits_normal, report.cmd_hits_bad, report.last_ntp_hit_ago, report.last_cmd_hit_ago);\n break;\n case CLG_EMPTYSUBNET:\n /* Signal back to the client that this single client address\n was unknown */\n ip.family = IPADDR_UNSPEC;\n UTI_IPHostToNetwork(&ip, &tx_message->data.client_accesses.clients[i].ip);\n break;\n case CLG_INACTIVE:\n tx_message->status = htons(STT_INACTIVE);\n return;\n default:\n assert(0);\n break;\n }\n }\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'Don't send uninitialized data in command replies\n\nThe RPY_SUBNETS_ACCESSED and RPY_CLIENT_ACCESSES command replies can\ncontain uninitalized data from stack when the client logging is disabled\nor a bad subnet is requested. These commands were never used by chronyc\nand they require the client to be authenticated since version 1.25.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void _out_verify(conn_t out, nad_t nad) {\n int attr, ns;\n jid_t from, to;\n conn_t in;\n char *rkey;\n int valid;\n\n attr = nad_find_attr(nad, 0, -1, \"from\", NULL);\n if(attr < 0 || (from = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {\n log_debug(ZONE, \"missing or invalid from on db verify packet\");\n nad_free(nad);\n return;\n }\n\n attr = nad_find_attr(nad, 0, -1, \"to\", NULL);\n if(attr < 0 || (to = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {\n log_debug(ZONE, \"missing or invalid to on db verify packet\");\n jid_free(from);\n nad_free(nad);\n return;\n }\n\n attr = nad_find_attr(nad, 0, -1, \"id\", NULL);\n if(attr < 0) {\n log_debug(ZONE, \"missing id on db verify packet\");\n jid_free(from);\n jid_free(to);\n nad_free(nad);\n return;\n }\n\n /* get the incoming conn */\n in = xhash_getx(out->s2s->in, NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr));\n if(in == NULL) {\n log_debug(ZONE, \"got a verify for incoming conn %.*s, but it doesn't exist, dropping the packet\", NAD_AVAL_L(nad, attr), NAD_AVAL(nad, attr));\n jid_free(from);\n jid_free(to);\n nad_free(nad);\n return;\n }\n\n rkey = s2s_route_key(NULL, to->domain, from->domain);\n\n attr = nad_find_attr(nad, 0, -1, \"type\", \"valid\");\n if(attr >= 0) {\n xhash_put(in->states, pstrdup(xhash_pool(in->states), rkey), (void *) conn_VALID);\n log_write(in->s2s->log, LOG_NOTICE, \"[%d] [%s, port=%d] incoming route '%s' is now valid%s%s\", in->fd->fd, in->ip, in->port, rkey, (in->s->flags & SX_SSL_WRAPPER) ? \", TLS negotiated\" : \"\", in->s->compressed ? \", ZLIB compression enabled\" : \"\");\n valid = 1;\n } else {\n log_write(in->s2s->log, LOG_NOTICE, \"[%d] [%s, port=%d] incoming route '%s' is now invalid\", in->fd->fd, in->ip, in->port, rkey);\n valid = 0;\n }\n\n free(rkey);\n\n nad_free(nad);\n\n /* decrement outstanding verify counter */\n --out->verify;\n\n /* let them know what happened */\n nad = nad_new();\n\n ns = nad_add_namespace(nad, uri_DIALBACK, \"db\");\n nad_append_elem(nad, ns, \"result\", 0);\n nad_append_attr(nad, -1, \"to\", from->domain);\n nad_append_attr(nad, -1, \"from\", to->domain);\n nad_append_attr(nad, -1, \"type\", valid ? \"valid\" : \"invalid\");\n\n /* off it goes */\n sx_nad_write(in->s, nad);\n\n /* if invalid, close the stream */\n if (!valid) {\n /* generate stream error */\n sx_error(in->s, stream_err_INVALID_ID, \"dialback negotiation failed\");\n\n /* close the incoming stream */\n sx_close(in->s);\n }\n\n jid_free(from);\n jid_free(to);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fixed possibility of Unsolicited Dialback Attacks'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void ip_options_build(struct sk_buff * skb, struct ip_options * opt,\n\t\t\t __be32 daddr, struct rtable *rt, int is_frag)\n{\n\tunsigned char *iph = skb_network_header(skb);\n\n\tmemcpy(&(IPCB(skb)->opt), opt, sizeof(struct ip_options));\n\tmemcpy(iph+sizeof(struct iphdr), opt->__data, opt->optlen);\n\topt = &(IPCB(skb)->opt);\n\n\tif (opt->srr)\n\t\tmemcpy(iph+opt->srr+iph[opt->srr+1]-4, &daddr, 4);\n\n\tif (!is_frag) {\n\t\tif (opt->rr_needaddr)\n\t\t\tip_rt_get_source(iph+opt->rr+iph[opt->rr+2]-5, rt);\n\t\tif (opt->ts_needaddr)\n\t\t\tip_rt_get_source(iph+opt->ts+iph[opt->ts+2]-9, rt);\n\t\tif (opt->ts_needtime) {\n\t\t\tstruct timespec tv;\n\t\t\t__be32 midtime;\n\t\t\tgetnstimeofday(&tv);\n\t\t\tmidtime = htonl((tv.tv_sec % 86400) * MSEC_PER_SEC + tv.tv_nsec / NSEC_PER_MSEC);\n\t\t\tmemcpy(iph+opt->ts+iph[opt->ts+2]-5, &midtime, 4);\n\t\t}\n\t\treturn;\n\t}\n\tif (opt->rr) {\n\t\tmemset(iph+opt->rr, IPOPT_NOP, iph[opt->rr+1]);\n\t\topt->rr = 0;\n\t\topt->rr_needaddr = 0;\n\t}\n\tif (opt->ts) {\n\t\tmemset(iph+opt->ts, IPOPT_NOP, iph[opt->ts+1]);\n\t\topt->ts = 0;\n\t\topt->ts_needaddr = opt->ts_needtime = 0;\n\t}\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: struct dst_entry *inet_csk_route_req(struct sock *sk,\n\t\t\t\t const struct request_sock *req)\n{\n\tstruct rtable *rt;\n\tconst struct inet_request_sock *ireq = inet_rsk(req);\n\tstruct ip_options *opt = inet_rsk(req)->opt;\n\tstruct net *net = sock_net(sk);\n\tstruct flowi4 fl4;\n\n\tflowi4_init_output(&fl4, sk->sk_bound_dev_if, sk->sk_mark,\n\t\t\t RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE,\n\t\t\t sk->sk_protocol, inet_sk_flowi_flags(sk),\n\t\t\t (opt && opt->srr) ? opt->faddr : ireq->rmt_addr,\n\t\t\t ireq->loc_addr, ireq->rmt_port, inet_sk(sk)->inet_sport);\n\tsecurity_req_classify_flow(req, flowi4_to_flowi(&fl4));\n\trt = ip_route_output_flow(net, &fl4, sk);\n\tif (IS_ERR(rt))\n\t\tgoto no_route;\n\tif (opt && opt->is_strictroute && rt->rt_dst != rt->rt_gateway)\n\t\tgoto route_err;\n\treturn &rt->dst;\n\nroute_err:\n\tip_rt_put(rt);\nno_route:\n\tIP_INC_STATS_BH(net, IPSTATS_MIB_OUTNOROUTES);\n\treturn NULL;\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: int cipso_v4_req_setattr(struct request_sock *req,\n\t\t\t const struct cipso_v4_doi *doi_def,\n\t\t\t const struct netlbl_lsm_secattr *secattr)\n{\n\tint ret_val = -EPERM;\n\tunsigned char *buf = NULL;\n\tu32 buf_len;\n\tu32 opt_len;\n\tstruct ip_options *opt = NULL;\n\tstruct inet_request_sock *req_inet;\n\n\t/* We allocate the maximum CIPSO option size here so we are probably\n\t * being a little wasteful, but it makes our life _much_ easier later\n\t * on and after all we are only talking about 40 bytes. */\n\tbuf_len = CIPSO_V4_OPT_LEN_MAX;\n\tbuf = kmalloc(buf_len, GFP_ATOMIC);\n\tif (buf == NULL) {\n\t\tret_val = -ENOMEM;\n\t\tgoto req_setattr_failure;\n\t}\n\n\tret_val = cipso_v4_genopt(buf, buf_len, doi_def, secattr);\n\tif (ret_val < 0)\n\t\tgoto req_setattr_failure;\n\tbuf_len = ret_val;\n\n\t/* We can't use ip_options_get() directly because it makes a call to\n\t * ip_options_get_alloc() which allocates memory with GFP_KERNEL and\n\t * we won't always have CAP_NET_RAW even though we _always_ want to\n\t * set the IPOPT_CIPSO option. */\n\topt_len = (buf_len + 3) & ~3;\n\topt = kzalloc(sizeof(*opt) + opt_len, GFP_ATOMIC);\n\tif (opt == NULL) {\n\t\tret_val = -ENOMEM;\n\t\tgoto req_setattr_failure;\n\t}\n\tmemcpy(opt->__data, buf, buf_len);\n\topt->optlen = opt_len;\n\topt->cipso = sizeof(struct iphdr);\n\tkfree(buf);\n\tbuf = NULL;\n\n\treq_inet = inet_rsk(req);\n\topt = xchg(&req_inet->opt, opt);\n\tkfree(opt);\n\n\treturn 0;\n\nreq_setattr_failure:\n\tkfree(buf);\n\tkfree(opt);\n\treturn ret_val;\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 img->numsamples = img->width * img->height * CHANNEL_COUNT;\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 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: don't overflow memory allocation\n\nCarefully selected width/height values could cause the size of a later\nallocation to overflow, resulting in a buffer much too small to store\nthe data which would then written beyond its end.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xsltAttrListTemplateProcess(xsltTransformContextPtr ctxt, \n\t xmlNodePtr target, xmlAttrPtr attrs)\n{\n xmlAttrPtr attr, copy, last;\n xmlNodePtr oldInsert, text;\n xmlNsPtr origNs = NULL, copyNs = NULL;\n const xmlChar *value;\n xmlChar *valueAVT;\n\n if ((ctxt == NULL) || (target == NULL) || (attrs == NULL) ||\n (target->type != XML_ELEMENT_NODE))\n\treturn(NULL);\n\n oldInsert = ctxt->insert;\n ctxt->insert = target; \n\n /*\n * Instantiate LRE-attributes.\n */\n if (target->properties) {\n\tlast = target->properties;\n\twhile (last->next != NULL)\n\t last = last->next;\n } else {\n\tlast = NULL;\n }\n attr = attrs;\n do {\n\t/*\n\t* Skip XSLT attributes.\n\t*/\n#ifdef XSLT_REFACTORED\n\tif (attr->psvi == xsltXSLTAttrMarker) {\n\t goto next_attribute;\n\t}\n#else\n\tif ((attr->ns != NULL) &&\n\t xmlStrEqual(attr->ns->href, XSLT_NAMESPACE))\n\t{\n\t goto next_attribute;\n\t}\n#endif\n\t/*\n\t* Get the value.\n\t*/\n\tif (attr->children != NULL) {\n\t if ((attr->children->type != XML_TEXT_NODE) ||\n\t\t(attr->children->next != NULL))\n\t {\n\t\txsltTransformError(ctxt, NULL, attr->parent,\n\t\t \"Internal error: The children of an attribute node of a \"\n\t\t \"literal result element are not in the expected form.\\n\");\n\t\tgoto error;\n\t }\n\t value = attr->children->content;\n\t if (value == NULL)\n\t\tvalue = xmlDictLookup(ctxt->dict, BAD_CAST \"\", 0);\n\t} else\n\t value = xmlDictLookup(ctxt->dict, BAD_CAST \"\", 0);\n\n\t/*\n\t* Create a new attribute.\n\t*/\n\tcopy = xmlNewDocProp(target->doc, attr->name, NULL);\n\tif (copy == NULL) {\n\t if (attr->ns) {\n\t\txsltTransformError(ctxt, NULL, attr->parent,\n\t\t \"Internal error: Failed to create attribute '{%s}%s'.\\n\",\n\t\t attr->ns->href, attr->name);\n\t } else {\n\t\txsltTransformError(ctxt, NULL, attr->parent,\n\t\t \"Internal error: Failed to create attribute '%s'.\\n\",\n\t\t attr->name);\n\t }\n\t goto error;\n\t}\n\t/*\n\t* Attach it to the target element.\n\t*/\n\tcopy->parent = target;\n\tif (last == NULL) {\n\t target->properties = copy;\n\t last = copy;\n\t} else {\n\t last->next = copy;\n\t copy->prev = last;\n\t last = copy;\n\t}\n\t/*\n\t* Set the namespace. Avoid lookups of same namespaces.\n\t*/\n\tif (attr->ns != origNs) {\n\t origNs = attr->ns;\n\t if (attr->ns != NULL) {\n#ifdef XSLT_REFACTORED\n\t\tcopyNs = xsltGetSpecialNamespace(ctxt, attr->parent,\n\t\t attr->ns->href, attr->ns->prefix, target);\n#else\n\t\tcopyNs = xsltGetNamespace(ctxt, attr->parent,\n\t\t attr->ns, target);\n#endif\n\t\tif (copyNs == NULL)\n\t\t goto error;\n\t } else\n\t\tcopyNs = NULL;\n\t}\n\tcopy->ns = copyNs;\n\n\t/*\n\t* Set the value.\n\t*/\n\ttext = xmlNewText(NULL);\n\tif (text != NULL) {\n\t copy->last = copy->children = text;\n\t text->parent = (xmlNodePtr) copy;\n\t text->doc = copy->doc;\n\n\t if (attr->psvi != NULL) {\n\t\t/*\n\t\t* Evaluate the Attribute Value Template.\n\t\t*/\n\t\tvalueAVT = xsltEvalAVT(ctxt, attr->psvi, attr->parent);\n\t\tif (valueAVT == NULL) {\n\t\t /*\n\t\t * TODO: Damn, we need an easy mechanism to report\n\t\t * qualified names!\n\t\t */\n\t\t if (attr->ns) {\n\t\t\txsltTransformError(ctxt, NULL, attr->parent,\n\t\t\t \"Internal error: Failed to evaluate the AVT \"\n\t\t\t \"of attribute '{%s}%s'.\\n\",\n\t\t\t attr->ns->href, attr->name);\n\t\t } else {\n\t\t\txsltTransformError(ctxt, NULL, attr->parent,\n\t\t\t \"Internal error: Failed to evaluate the AVT \"\n\t\t\t \"of attribute '%s'.\\n\",\n\t\t\t attr->name);\n\t\t }\n\t\t text->content = xmlStrdup(BAD_CAST \"\");\n\t\t goto error;\n\t\t} else {\n\t\t text->content = valueAVT;\n\t\t}\n\t } else if ((ctxt->internalized) &&\n\t\t(target->doc != NULL) &&\n\t\t(target->doc->dict == ctxt->dict))\n\t {\n\t\ttext->content = (xmlChar *) value;\n\t } else {\n\t\ttext->content = xmlStrdup(value);\n\t }\n if ((copy != NULL) && (text != NULL) &&\n (xmlIsID(copy->doc, copy->parent, copy)))\n xmlAddID(NULL, copy->doc, text->content, copy);\n\t}\n\nnext_attribute:\n\tattr = attr->next;\n } while (attr != NULL);\n\n /*\n * Apply attribute-sets.\n * The creation of such attributes will not overwrite any existing\n * attribute.\n */\n attr = attrs;\n do {\n#ifdef XSLT_REFACTORED\n\tif ((attr->psvi == xsltXSLTAttrMarker) &&\n\t xmlStrEqual(attr->name, (const xmlChar *)\"use-attribute-sets\"))\n\t{\n\t xsltApplyAttributeSet(ctxt, ctxt->node, (xmlNodePtr) attr, NULL);\n\t}\n#else\n\tif ((attr->ns != NULL) &&\n\t xmlStrEqual(attr->name, (const xmlChar *)\"use-attribute-sets\") &&\n\t xmlStrEqual(attr->ns->href, XSLT_NAMESPACE))\n\t{\n\t xsltApplyAttributeSet(ctxt, ctxt->node, (xmlNodePtr) attr, NULL);\n\t}\n#endif\n\tattr = attr->next;\n } while (attr != NULL);\n\n ctxt->insert = oldInsert;\n return(target->properties);\n\nerror:\n ctxt->insert = oldInsert;\n return(NULL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'Fix a dictionary string usage\n\nRaised in chromium, but also affecting xsltproc\nAlso updated AUTHORS to list Chris and other contributors'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ext4_split_extent_at(handle_t *handle,\n\t\t\t struct inode *inode,\n\t\t\t struct ext4_ext_path *path,\n\t\t\t ext4_lblk_t split,\n\t\t\t int split_flag,\n\t\t\t int flags)\n{\n\text4_fsblk_t newblock;\n\text4_lblk_t ee_block;\n\tstruct ext4_extent *ex, newex, orig_ex;\n\tstruct ext4_extent *ex2 = NULL;\n\tunsigned int ee_len, depth;\n\tint err = 0;\n\n\text_debug(\"ext4_split_extents_at: inode %lu, logical\"\n\t\t\"block %llu\\n\", inode->i_ino, (unsigned long long)split);\n\n\text4_ext_show_leaf(inode, path);\n\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\tnewblock = split - ee_block + ext4_ext_pblock(ex);\n\n\tBUG_ON(split < ee_block || split >= (ee_block + ee_len));\n\n\terr = ext4_ext_get_access(handle, inode, path + depth);\n\tif (err)\n\t\tgoto out;\n\n\tif (split == ee_block) {\n\t\t/*\n\t\t * case b: block @split is the block that the extent begins with\n\t\t * then we just change the state of the extent, and splitting\n\t\t * is not needed.\n\t\t */\n\t\tif (split_flag & EXT4_EXT_MARK_UNINIT2)\n\t\t\text4_ext_mark_uninitialized(ex);\n\t\telse\n\t\t\text4_ext_mark_initialized(ex);\n\n\t\tif (!(flags & EXT4_GET_BLOCKS_PRE_IO))\n\t\t\text4_ext_try_to_merge(handle, inode, path, ex);\n\n\t\terr = ext4_ext_dirty(handle, inode, path + path->p_depth);\n\t\tgoto out;\n\t}\n\n\t/* case a */\n\tmemcpy(&orig_ex, ex, sizeof(orig_ex));\n\tex->ee_len = cpu_to_le16(split - ee_block);\n\tif (split_flag & EXT4_EXT_MARK_UNINIT1)\n\t\text4_ext_mark_uninitialized(ex);\n\n\t/*\n\t * path may lead to new leaf, not to original leaf any more\n\t * after ext4_ext_insert_extent() returns,\n\t */\n\terr = ext4_ext_dirty(handle, inode, path + depth);\n\tif (err)\n\t\tgoto fix_extent_len;\n\n\tex2 = &newex;\n\tex2->ee_block = cpu_to_le32(split);\n\tex2->ee_len = cpu_to_le16(ee_len - (split - ee_block));\n\text4_ext_store_pblock(ex2, newblock);\n\tif (split_flag & EXT4_EXT_MARK_UNINIT2)\n\t\text4_ext_mark_uninitialized(ex2);\n\n\terr = ext4_ext_insert_extent(handle, inode, path, &newex, flags);\n\tif (err == -ENOSPC && (EXT4_EXT_MAY_ZEROOUT & split_flag)) {\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_len = cpu_to_le16(ee_len);\n\t\text4_ext_try_to_merge(handle, inode, path, ex);\n\t\terr = ext4_ext_dirty(handle, inode, path + path->p_depth);\n\t\tgoto out;\n\t} else if (err)\n\t\tgoto fix_extent_len;\n\nout:\n\text4_ext_show_leaf(inode, path);\n\treturn err;\n\nfix_extent_len:\n\tex->ee_len = orig_ex.ee_len;\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-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: realloc_trans_if_necessary(struct dfa *d, int new_state)\n{\n /* Make sure that the trans and fail arrays are allocated large enough\n to hold a pointer for the new state. */\n if (new_state >= d->tralloc)\n {\n int oldalloc = d->tralloc;\n\n while (new_state >= d->tralloc)\n d->tralloc *= 2;\n REALLOC(d->realtrans, d->tralloc + 1);\n d->trans = d->realtrans + 1;\n REALLOC(d->fails, d->tralloc);\n REALLOC(d->success, d->tralloc);\n REALLOC(d->newlines, d->tralloc);\n while (oldalloc < d->tralloc)\n {\n d->trans[oldalloc] = NULL;\n d->fails[oldalloc++] = NULL;\n }\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: epsclosure (position_set *s, struct dfa const *d)\n{\n int i, j;\n char *visited;\t/* array of booleans, enough to use char, not int */\n position p, old;\n\n CALLOC(visited, d->tindex);\n\n for (i = 0; i < s->nelem; ++i)\n if (d->tokens[s->elems[i].index] >= NOTCHAR\n && d->tokens[s->elems[i].index] != BACKREF\n#if MBS_SUPPORT\n && d->tokens[s->elems[i].index] != ANYCHAR\n && d->tokens[s->elems[i].index] != MBCSET\n#endif\n && d->tokens[s->elems[i].index] < CSET)\n {\n old = s->elems[i];\n p.constraint = old.constraint;\n delete(s->elems[i], s);\n if (visited[old.index])\n {\n --i;\n continue;\n }\n visited[old.index] = 1;\n switch (d->tokens[old.index])\n {\n case BEGLINE:\n p.constraint &= BEGLINE_CONSTRAINT;\n break;\n case ENDLINE:\n p.constraint &= ENDLINE_CONSTRAINT;\n break;\n case BEGWORD:\n p.constraint &= BEGWORD_CONSTRAINT;\n break;\n case ENDWORD:\n p.constraint &= ENDWORD_CONSTRAINT;\n break;\n case LIMWORD:\n p.constraint &= LIMWORD_CONSTRAINT;\n break;\n case NOTLIMWORD:\n p.constraint &= NOTLIMWORD_CONSTRAINT;\n break;\n default:\n break;\n }\n for (j = 0; j < d->follows[old.index].nelem; ++j)\n {\n p.index = d->follows[old.index].elems[j].index;\n insert(p, s);\n }\n /* Force rescan to start at the beginning. */\n i = -1;\n }\n\n free(visited);\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: dfaoptimize (struct dfa *d)\n{\n unsigned int i;\n\n if (!MBS_SUPPORT || !using_utf8())\n return;\n\n for (i = 0; i < d->tindex; ++i)\n {\n switch(d->tokens[i])\n {\n case ANYCHAR:\n /* Lowered. */\n abort ();\n case MBCSET:\n /* Requires multi-byte algorithm. */\n return;\n default:\n break;\n }\n }\n\n free_mbdata (d);\n d->mb_cur_max = 1;\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: free_mbdata (struct dfa *d)\n{\n unsigned int i;\n\n free(d->multibyte_prop);\n d->multibyte_prop = NULL;\n\n for (i = 0; i < d->nmbcsets; ++i)\n {\n unsigned int j;\n struct mb_char_classes *p = &(d->mbcsets[i]);\n free(p->chars);\n free(p->ch_classes);\n free(p->range_sts);\n free(p->range_ends);\n\n for (j = 0; j < p->nequivs; ++j)\n free(p->equivs[j]);\n free(p->equivs);\n\n for (j = 0; j < p->ncoll_elems; ++j)\n free(p->coll_elems[j]);\n free(p->coll_elems);\n }\n\n free(d->mbcsets);\n d->mbcsets = NULL;\n d->nmbcsets = 0;\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: grep (int fd, char const *file, struct stats *stats)\n{\n int nlines, i;\n int not_text;\n size_t residue, save;\n char oldc;\n char *beg;\n char *lim;\n char eol = eolbyte;\n\n if (!reset (fd, file, stats))\n return 0;\n\n if (file && directories == RECURSE_DIRECTORIES\n && S_ISDIR (stats->stat.st_mode))\n {\n /* Close fd now, so that we don't open a lot of file descriptors\n when we recurse deeply. */\n if (close (fd) != 0)\n suppressible_error (file, errno);\n return grepdir (file, stats) - 2;\n }\n\n totalcc = 0;\n lastout = 0;\n totalnl = 0;\n outleft = max_count;\n after_last_match = 0;\n pending = 0;\n\n nlines = 0;\n residue = 0;\n save = 0;\n\n if (! fillbuf (save, stats))\n {\n suppressible_error (filename, errno);\n return 0;\n }\n\n not_text = (((binary_files == BINARY_BINARY_FILES && !out_quiet)\n || binary_files == WITHOUT_MATCH_BINARY_FILES)\n && memchr (bufbeg, eol ? '\\0' : '\\200', buflim - bufbeg));\n if (not_text && binary_files == WITHOUT_MATCH_BINARY_FILES)\n return 0;\n done_on_match += not_text;\n out_quiet += not_text;\n\n for (;;)\n {\n lastnl = bufbeg;\n if (lastout)\n lastout = bufbeg;\n\n beg = bufbeg + save;\n\n /* no more data to scan (eof) except for maybe a residue -> break */\n if (beg == buflim)\n break;\n\n /* Determine new residue (the length of an incomplete line at the end of\n the buffer, 0 means there is no incomplete last line). */\n oldc = beg[-1];\n beg[-1] = eol;\n for (lim = buflim; lim[-1] != eol; lim--)\n continue;\n beg[-1] = oldc;\n if (lim == beg)\n lim = beg - residue;\n beg -= residue;\n residue = buflim - lim;\n\n if (beg < lim)\n {\n if (outleft)\n nlines += grepbuf (beg, lim);\n if (pending)\n prpending (lim);\n if ((!outleft && !pending) || (nlines && done_on_match && !out_invert))\n goto finish_grep;\n }\n\n /* The last OUT_BEFORE lines at the end of the buffer will be needed as\n leading context if there is a matching line at the begin of the\n next data. Make beg point to their begin. */\n i = 0;\n beg = lim;\n while (i < out_before && beg > bufbeg && beg != lastout)\n {\n ++i;\n do\n --beg;\n while (beg[-1] != eol);\n }\n\n /* detect if leading context is discontinuous from last printed line. */\n if (beg != lastout)\n lastout = 0;\n\n /* Handle some details and read more data to scan. */\n save = residue + lim - beg;\n if (out_byte)\n totalcc = add_count (totalcc, buflim - bufbeg - save);\n if (out_line)\n nlscan (beg);\n if (! fillbuf (save, stats))\n {\n suppressible_error (filename, errno);\n goto finish_grep;\n }\n }\n if (residue)\n {\n *buflim++ = eol;\n if (outleft)\n nlines += grepbuf (bufbeg + save - residue, buflim);\n if (pending)\n prpending (buflim);\n }\n\n finish_grep:\n done_on_match -= not_text;\n out_quiet -= not_text;\n if ((not_text & ~out_quiet) && nlines != 0)\n printf (_(\"Binary file %s matches\\n\"), filename);\n return nlines;\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_send_tls(gnutls_session * session, xmlNode * msg)\n{\n char *xml_text = NULL;\n\n# if 0\n const char *name = crm_element_name(msg);\n\n if (safe_str_neq(name, \"cib_command\")) {\n xmlNodeSetName(msg, \"cib_result\");\n }\n# endif\n xml_text = dump_xml_unformatted(msg);\n if (xml_text != NULL) {\n char *unsent = xml_text;\n int len = strlen(xml_text);\n int rc = 0;\n\n len++; /* null char */\n crm_trace(\"Message size: %d\", len);\n\n while (TRUE) {\n rc = gnutls_record_send(*session, unsent, len);\n crm_debug(\"Sent %d bytes\", rc);\n\n if (rc == GNUTLS_E_INTERRUPTED || rc == GNUTLS_E_AGAIN) {\n crm_debug(\"Retry\");\n\n } else if (rc < 0) {\n crm_debug(\"Connection terminated\");\n break;\n\n } else if (rc < len) {\n crm_debug(\"Only sent %d of %d bytes\", rc, len);\n len -= rc;\n unsent += rc;\n } else {\n break;\n }\n }\n\n }\n free(xml_text);\n return NULL;\n\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_remote_listen(gpointer data)\n{\n int lpc = 0;\n int csock = 0;\n unsigned laddr;\n time_t now = 0;\n time_t start = time(NULL);\n struct sockaddr_in addr;\n int ssock = *(int *)data;\n\n#ifdef HAVE_GNUTLS_GNUTLS_H\n gnutls_session *session = NULL;\n#endif\n cib_client_t *new_client = NULL;\n\n xmlNode *login = NULL;\n const char *user = NULL;\n const char *pass = NULL;\n const char *tmp = NULL;\n\n#ifdef HAVE_DECL_NANOSLEEP\n const struct timespec sleepfast = { 0, 10000000 }; /* 10 millisec */\n#endif\n\n static struct mainloop_fd_callbacks remote_client_fd_callbacks = \n {\n .dispatch = cib_remote_msg,\n .destroy = cib_remote_connection_destroy,\n }; \n \n /* accept the connection */\n laddr = sizeof(addr);\n csock = accept(ssock, (struct sockaddr *)&addr, &laddr);\n crm_debug(\"New %s connection from %s\",\n ssock == remote_tls_fd ? \"secure\" : \"clear-text\", inet_ntoa(addr.sin_addr));\n\n if (csock == -1) {\n crm_err(\"accept socket failed\");\n return TRUE;\n }\n\n if (ssock == remote_tls_fd) {\n#ifdef HAVE_GNUTLS_GNUTLS_H\n /* create gnutls session for the server socket */\n session = create_tls_session(csock, GNUTLS_SERVER);\n if (session == NULL) {\n crm_err(\"TLS session creation failed\");\n close(csock);\n return TRUE;\n }\n#endif\n }\n\n do {\n crm_trace(\"Iter: %d\", lpc++);\n if (ssock == remote_tls_fd) {\n#ifdef HAVE_GNUTLS_GNUTLS_H\n login = crm_recv_remote_msg(session, TRUE);\n#endif\n } else {\n login = crm_recv_remote_msg(GINT_TO_POINTER(csock), FALSE);\n }\n if (login != NULL) {\n break;\n }\n#ifdef HAVE_DECL_NANOSLEEP\n nanosleep(&sleepfast, NULL);\n#else\n sleep(1);\n#endif\n now = time(NULL);\n\n /* Peers have 3s to connect */\n } while (login == NULL && (start - now) < 4);\n\n crm_log_xml_info(login, \"Login: \");\n if (login == NULL) {\n goto bail;\n }\n\n tmp = crm_element_name(login);\n if (safe_str_neq(tmp, \"cib_command\")) {\n crm_err(\"Wrong tag: %s\", tmp);\n goto bail;\n }\n\n tmp = crm_element_value(login, \"op\");\n if (safe_str_neq(tmp, \"authenticate\")) {\n crm_err(\"Wrong operation: %s\", tmp);\n goto bail;\n }\n\n user = crm_element_value(login, \"user\");\n pass = crm_element_value(login, \"password\");\n\n /* Non-root daemons can only validate the password of the\n * user they're running as\n */\n if (check_group_membership(user, CRM_DAEMON_GROUP) == FALSE) {\n crm_err(\"User is not a member of the required group\");\n goto bail;\n\n } else if (authenticate_user(user, pass) == FALSE) {\n crm_err(\"PAM auth failed\");\n goto bail;\n }\n\n /* send ACK */\n num_clients++;\n new_client = calloc(1, sizeof(cib_client_t));\n new_client->name = crm_element_value_copy(login, \"name\");\n\n CRM_CHECK(new_client->id == NULL, free(new_client->id));\n new_client->id = crm_generate_uuid();\n\n#if ENABLE_ACL\n new_client->user = strdup(user);\n#endif\n\n new_client->callback_id = NULL;\n if (ssock == remote_tls_fd) {\n#ifdef HAVE_GNUTLS_GNUTLS_H\n new_client->encrypted = TRUE;\n new_client->session = session;\n#endif\n } else {\n new_client->session = GINT_TO_POINTER(csock);\n }\n\n free_xml(login);\n login = create_xml_node(NULL, \"cib_result\");\n crm_xml_add(login, F_CIB_OPERATION, CRM_OP_REGISTER);\n crm_xml_add(login, F_CIB_CLIENTID, new_client->id);\n crm_send_remote_msg(new_client->session, login, new_client->encrypted);\n free_xml(login);\n\n new_client->remote = mainloop_add_fd(\n \"cib-remote-client\", G_PRIORITY_DEFAULT, csock, new_client, &remote_client_fd_callbacks);\n\n g_hash_table_insert(client_list, new_client->id, new_client);\n\n return TRUE;\n\n bail:\n if (ssock == remote_tls_fd) {\n#ifdef HAVE_GNUTLS_GNUTLS_H\n gnutls_bye(*session, GNUTLS_SHUT_RDWR);\n gnutls_deinit(*session);\n gnutls_free(session);\n#endif\n }\n close(csock);\n free_xml(login);\n return TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'High: core: Internal tls api improvements for reuse with future LRMD tls backend.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: goa_ews_client_autodiscover (GoaEwsClient *client,\n const gchar *email,\n const gchar *password,\n const gchar *username,\n const gchar *server,\n GCancellable *cancellable,\n GAsyncReadyCallback callback,\n gpointer user_data)\n{\n AutodiscoverData *data;\n AutodiscoverAuthData *auth;\n gchar *url1;\n gchar *url2;\n xmlDoc *doc;\n xmlOutputBuffer *buf;\n\n g_return_if_fail (GOA_IS_EWS_CLIENT (client));\n g_return_if_fail (email != NULL || email[0] != '\\0');\n g_return_if_fail (password != NULL || password[0] != '\\0');\n g_return_if_fail (username != NULL || username[0] != '\\0');\n g_return_if_fail (server != NULL || server[0] != '\\0');\n g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));\n\n doc = ews_client_create_autodiscover_xml (email);\n buf = xmlAllocOutputBuffer (NULL);\n xmlNodeDumpOutput (buf, doc, xmlDocGetRootElement (doc), 0, 1, NULL);\n xmlOutputBufferFlush (buf);\n\n url1 = g_strdup_printf (\"https://%s/autodiscover/autodiscover.xml\", server);\n url2 = g_strdup_printf (\"https://autodiscover.%s/autodiscover/autodiscover.xml\", server);\n\n /* http://msdn.microsoft.com/en-us/library/ee332364.aspx says we are\n * supposed to try $domain and then autodiscover.$domain. But some\n * people have broken firewalls on the former which drop packets\n * instead of rejecting connections, and make the request take ages\n * to time out. So run both queries in parallel and let the fastest\n * (successful) one win.\n */\n data = g_slice_new0 (AutodiscoverData);\n data->buf = buf;\n data->res = g_simple_async_result_new (G_OBJECT (client), callback, user_data, goa_ews_client_autodiscover);\n data->msgs[0] = ews_client_create_msg_for_url (url1, buf);\n data->msgs[1] = ews_client_create_msg_for_url (url2, buf);\n data->session = soup_session_async_new_with_options (SOUP_SESSION_USE_NTLM, TRUE,\n SOUP_SESSION_USE_THREAD_CONTEXT, TRUE,\n NULL);\n if (cancellable != NULL)\n {\n data->cancellable = g_object_ref (cancellable);\n data->cancellable_id = g_cancellable_connect (data->cancellable,\n G_CALLBACK (ews_client_autodiscover_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 (AutodiscoverAuthData);\n auth->username = g_strdup (username);\n auth->password = g_strdup (password);\n g_signal_connect_data (data->session,\n \"authenticate\",\n G_CALLBACK (ews_client_authenticate),\n auth,\n ews_client_autodiscover_auth_data_free,\n 0);\n\n soup_session_queue_message (data->session, data->msgs[0], ews_client_autodiscover_response_cb, data);\n soup_session_queue_message (data->session, data->msgs[1], ews_client_autodiscover_response_cb, data);\n\n g_free (url2);\n g_free (url1);\n xmlFreeDoc (doc);\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 GCancellable *cancellable,\n GAsyncReadyCallback callback,\n gpointer user_data)\n{\n CheckData *data;\n CheckAuthData *auth;\n SoupLogger *logger;\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_USE_THREAD_CONTEXT, TRUE,\n NULL);\n logger = soup_logger_new (SOUP_LOGGER_LOG_BODY, -1);\n soup_logger_set_printer (logger, http_client_log_printer, NULL, NULL);\n soup_session_add_feature (data->session, SOUP_SESSION_FEATURE (logger));\n g_object_unref (logger);\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\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: ews_client_autodiscover_response_cb (SoupSession *session, SoupMessage *msg, gpointer user_data)\n{\n GError *error;\n AutodiscoverData *data = user_data;\n GTlsCertificateFlags cert_flags;\n gboolean op_res;\n gboolean using_https;\n guint status;\n gint idx;\n gsize size;\n xmlDoc *doc;\n xmlNode *node;\n\n status = msg->status_code;\n if (status == SOUP_STATUS_NONE)\n return;\n\n error = NULL;\n op_res = FALSE;\n size = sizeof (data->msgs) / sizeof (data->msgs[0]);\n\n for (idx = 0; idx < size; idx++)\n {\n if (data->msgs[idx] == msg)\n break;\n }\n if (idx == size)\n return;\n\n data->msgs[idx] = NULL;\n\n if (status == SOUP_STATUS_CANCELLED)\n goto out;\n else if (status != SOUP_STATUS_OK)\n {\n g_set_error (&error,\n GOA_ERROR,\n GOA_ERROR_FAILED, /* TODO: more specific */\n _(\"Code: %u - Unexpected response from server\"),\n status);\n goto out;\n }\n\n if (!data->accept_ssl_errors)\n {\n using_https = soup_message_get_https_status (msg, NULL, &cert_flags);\n if (using_https && cert_flags != 0)\n {\n goa_utils_set_error_ssl (&error, cert_flags);\n goto out;\n }\n }\n\n soup_buffer_free (soup_message_body_flatten (SOUP_MESSAGE (msg)->response_body));\n g_debug (\"The response headers\");\n g_debug (\"===================\");\n g_debug (\"%s\", SOUP_MESSAGE (msg)->response_body->data);\n\n doc = xmlReadMemory (msg->response_body->data, msg->response_body->length, \"autodiscover.xml\", NULL, 0);\n if (doc == NULL)\n {\n g_set_error (&error,\n GOA_ERROR,\n GOA_ERROR_FAILED, /* TODO: more specific */\n _(\"Failed to parse autodiscover response XML\"));\n goto out;\n }\n\n node = xmlDocGetRootElement (doc);\n if (g_strcmp0 ((gchar *) node->name, \"Autodiscover\"))\n {\n g_set_error (&error,\n GOA_ERROR,\n GOA_ERROR_FAILED, /* TODO: more specific */\n _(\"Failed to find Autodiscover element\"));\n goto out;\n }\n\n for (node = node->children; node; node = node->next)\n {\n if (ews_client_check_node (node, \"Response\"))\n break;\n }\n if (node == NULL)\n {\n g_set_error (&error,\n GOA_ERROR,\n GOA_ERROR_FAILED, /* TODO: more specific */\n _(\"Failed to find Response element\"));\n goto out;\n }\n\n for (node = node->children; node; node = node->next)\n {\n if (ews_client_check_node (node, \"Account\"))\n break;\n }\n if (node == NULL)\n {\n g_set_error (&error,\n GOA_ERROR,\n GOA_ERROR_FAILED, /* TODO: more specific */\n _(\"Failed to find Account element\"));\n goto out;\n }\n\n for (node = node->children; node; node = node->next)\n {\n if (ews_client_check_node (node, \"Protocol\"))\n {\n op_res = ews_client_autodiscover_parse_protocol (node);\n break;\n }\n }\n if (!op_res)\n {\n g_set_error (&error,\n GOA_ERROR,\n GOA_ERROR_FAILED, /* TODO: more specific*/\n _(\"Failed to find ASUrl and OABUrl in autodiscover response\"));\n goto out;\n }\n\n for (idx = 0; idx < size; idx++)\n {\n if (data->msgs[idx] != NULL)\n {\n /* Since we are cancelling from the same thread that we queued the\n * message, the callback (ie. this function) will be invoked before\n * soup_session_cancel_message returns.\n */\n soup_session_cancel_message (data->session, data->msgs[idx], SOUP_STATUS_NONE);\n data->msgs[idx] = NULL;\n }\n }\n\n out:\n /* error == NULL, if we are being aborted by the GCancellable */\n if (!op_res)\n {\n for (idx = 0; idx < size; idx++)\n {\n if (data->msgs[idx] != NULL)\n {\n /* There's another request outstanding.\n * Hope that it has better luck.\n */\n g_clear_error (&error);\n return;\n }\n }\n if (error != NULL)\n g_simple_async_result_take_error (data->res, error);\n }\n\n g_simple_async_result_set_op_res_gboolean (data->res, op_res);\n g_simple_async_result_complete_in_idle (data->res);\n g_idle_add (ews_client_autodiscover_data_free, data);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates\n\nFor providers like Exchange which use libsoup to talk to a HTTPS\nserver it is not enough to warn the user about an invalid certificate.\nWe should make sure that we abort the connection before any\ncredentials have been sent.\n\nFixes: CVE-2013-1799'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int processCommand(redisClient *c) {\n struct redisCommand *cmd;\n\n /* The QUIT command is handled separately. Normal command procs will\n * go through checking for replication and QUIT will cause trouble\n * when FORCE_REPLICATION is enabled and would be implemented in\n * a regular command proc. */\n if (!strcasecmp(c->argv[0]->ptr,\"quit\")) {\n addReply(c,shared.ok);\n c->flags |= REDIS_CLOSE_AFTER_REPLY;\n return REDIS_ERR;\n }\n\n /* Now lookup the command and check ASAP about trivial error conditions\n * such wrong arity, bad command name and so forth. */\n cmd = lookupCommand(c->argv[0]->ptr);\n if (!cmd) {\n addReplyErrorFormat(c,\"unknown command '%s'\",\n (char*)c->argv[0]->ptr);\n return REDIS_OK;\n } else if ((cmd->arity > 0 && cmd->arity != c->argc) ||\n (c->argc < -cmd->arity)) {\n addReplyErrorFormat(c,\"wrong number of arguments for '%s' command\",\n cmd->name);\n return REDIS_OK;\n }\n\n /* Check if the user is authenticated */\n if (server.requirepass && !c->authenticated && cmd->proc != authCommand) {\n addReplyError(c,\"operation not permitted\");\n return REDIS_OK;\n }\n\n /* Handle the maxmemory directive.\n *\n * First we try to free some memory if possible (if there are volatile\n * keys in the dataset). If there are not the only thing we can do\n * is returning an error. */\n if (server.maxmemory) freeMemoryIfNeeded();\n if (server.maxmemory && (cmd->flags & REDIS_CMD_DENYOOM) &&\n zmalloc_used_memory() > server.maxmemory)\n {\n addReplyError(c,\"command not allowed when used memory > 'maxmemory'\");\n return REDIS_OK;\n }\n\n /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */\n if ((dictSize(c->pubsub_channels) > 0 || listLength(c->pubsub_patterns) > 0)\n &&\n cmd->proc != subscribeCommand && cmd->proc != unsubscribeCommand &&\n cmd->proc != psubscribeCommand && cmd->proc != punsubscribeCommand) {\n addReplyError(c,\"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context\");\n return REDIS_OK;\n }\n\n /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and\n * we are a slave with a broken link with master. */\n if (server.masterhost && server.replstate != REDIS_REPL_CONNECTED &&\n server.repl_serve_stale_data == 0 &&\n cmd->proc != infoCommand && cmd->proc != slaveofCommand)\n {\n addReplyError(c,\n \"link with MASTER is down and slave-serve-stale-data is set to no\");\n return REDIS_OK;\n }\n\n /* Loading DB? Return an error if the command is not INFO */\n if (server.loading && cmd->proc != infoCommand) {\n addReply(c, shared.loadingerr);\n return REDIS_OK;\n }\n\n /* Exec the command */\n if (c->flags & REDIS_MULTI &&\n cmd->proc != execCommand && cmd->proc != discardCommand &&\n cmd->proc != multiCommand && cmd->proc != watchCommand)\n {\n queueMultiCommand(c,cmd);\n addReply(c,shared.queued);\n } else {\n if (server.vm_enabled && server.vm_max_threads > 0 &&\n blockClientOnSwappedKeys(c,cmd)) return REDIS_ERR;\n call(c,cmd);\n }\n return REDIS_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'initial changes needed to turn the current VM code into a cache system. Tons of work to do still.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline int pmd_present(pmd_t pmd)\n{\n\treturn pmd_flags(pmd) & _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: int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)\n{\n\tstruct page *page;\n\tstruct kvm *kvm;\n\tint r;\n\n\tBUG_ON(vcpu->kvm == NULL);\n\tkvm = vcpu->kvm;\n\n\tvcpu->arch.emulate_ctxt.ops = &emulate_ops;\n\tif (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu))\n\t\tvcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;\n\telse\n\t\tvcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;\n\n\tpage = alloc_page(GFP_KERNEL | __GFP_ZERO);\n\tif (!page) {\n\t\tr = -ENOMEM;\n\t\tgoto fail;\n\t}\n\tvcpu->arch.pio_data = page_address(page);\n\n\tkvm_set_tsc_khz(vcpu, max_tsc_khz);\n\n\tr = kvm_mmu_create(vcpu);\n\tif (r < 0)\n\t\tgoto fail_free_pio_data;\n\n\tif (irqchip_in_kernel(kvm)) {\n\t\tr = kvm_create_lapic(vcpu);\n\t\tif (r < 0)\n\t\t\tgoto fail_mmu_destroy;\n\t} else\n\t\tstatic_key_slow_inc(&kvm_no_apic_vcpu);\n\n\tvcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,\n\t\t\t\t GFP_KERNEL);\n\tif (!vcpu->arch.mce_banks) {\n\t\tr = -ENOMEM;\n\t\tgoto fail_free_lapic;\n\t}\n\tvcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;\n\n\tif (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL))\n\t\tgoto fail_free_mce_banks;\n\n\tr = fx_init(vcpu);\n\tif (r)\n\t\tgoto fail_free_wbinvd_dirty_mask;\n\n\tvcpu->arch.ia32_tsc_adjust_msr = 0x0;\n\tkvm_async_pf_hash_reset(vcpu);\n\tkvm_pmu_init(vcpu);\n\n\treturn 0;\nfail_free_wbinvd_dirty_mask:\n\tfree_cpumask_var(vcpu->arch.wbinvd_dirty_mask);\nfail_free_mce_banks:\n\tkfree(vcpu->arch.mce_banks);\nfail_free_lapic:\n\tkvm_free_lapic(vcpu);\nfail_mmu_destroy:\n\tkvm_mmu_destroy(vcpu);\nfail_free_pio_data:\n\tfree_page((unsigned long)vcpu->arch.pio_data);\nfail:\n\treturn r;\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_GINIT_FUNCTION(libxml)\n{\n\tlibxml_globals->stream_context = NULL;\n\tlibxml_globals->error_buffer.c = NULL;\n\tlibxml_globals->error_list = NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Fixed external entity loading'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int dcbnl_cee_fill(struct sk_buff *skb, struct net_device *netdev)\n{\n\tstruct nlattr *cee, *app;\n\tstruct dcb_app_type *itr;\n\tconst struct dcbnl_rtnl_ops *ops = netdev->dcbnl_ops;\n\tint dcbx, i, err = -EMSGSIZE;\n\tu8 value;\n\n\tif (nla_put_string(skb, DCB_ATTR_IFNAME, netdev->name))\n\t\tgoto nla_put_failure;\n\tcee = nla_nest_start(skb, DCB_ATTR_CEE);\n\tif (!cee)\n\t\tgoto nla_put_failure;\n\n\t/* local pg */\n\tif (ops->getpgtccfgtx && ops->getpgbwgcfgtx) {\n\t\terr = dcbnl_cee_pg_fill(skb, netdev, 1);\n\t\tif (err)\n\t\t\tgoto nla_put_failure;\n\t}\n\n\tif (ops->getpgtccfgrx && ops->getpgbwgcfgrx) {\n\t\terr = dcbnl_cee_pg_fill(skb, netdev, 0);\n\t\tif (err)\n\t\t\tgoto nla_put_failure;\n\t}\n\n\t/* local pfc */\n\tif (ops->getpfccfg) {\n\t\tstruct nlattr *pfc_nest = nla_nest_start(skb, DCB_ATTR_CEE_PFC);\n\n\t\tif (!pfc_nest)\n\t\t\tgoto nla_put_failure;\n\n\t\tfor (i = DCB_PFC_UP_ATTR_0; i <= DCB_PFC_UP_ATTR_7; i++) {\n\t\t\tops->getpfccfg(netdev, i - DCB_PFC_UP_ATTR_0, &value);\n\t\t\tif (nla_put_u8(skb, i, value))\n\t\t\t\tgoto nla_put_failure;\n\t\t}\n\t\tnla_nest_end(skb, pfc_nest);\n\t}\n\n\t/* local app */\n\tspin_lock(&dcb_lock);\n\tapp = nla_nest_start(skb, DCB_ATTR_CEE_APP_TABLE);\n\tif (!app)\n\t\tgoto dcb_unlock;\n\n\tlist_for_each_entry(itr, &dcb_app_list, list) {\n\t\tif (itr->ifindex == netdev->ifindex) {\n\t\t\tstruct nlattr *app_nest = nla_nest_start(skb,\n\t\t\t\t\t\t\t\t DCB_ATTR_APP);\n\t\t\tif (!app_nest)\n\t\t\t\tgoto dcb_unlock;\n\n\t\t\terr = nla_put_u8(skb, DCB_APP_ATTR_IDTYPE,\n\t\t\t\t\t itr->app.selector);\n\t\t\tif (err)\n\t\t\t\tgoto dcb_unlock;\n\n\t\t\terr = nla_put_u16(skb, DCB_APP_ATTR_ID,\n\t\t\t\t\t itr->app.protocol);\n\t\t\tif (err)\n\t\t\t\tgoto dcb_unlock;\n\n\t\t\terr = nla_put_u8(skb, DCB_APP_ATTR_PRIORITY,\n\t\t\t\t\t itr->app.priority);\n\t\t\tif (err)\n\t\t\t\tgoto dcb_unlock;\n\n\t\t\tnla_nest_end(skb, app_nest);\n\t\t}\n\t}\n\tnla_nest_end(skb, app);\n\n\tif (netdev->dcbnl_ops->getdcbx)\n\t\tdcbx = netdev->dcbnl_ops->getdcbx(netdev);\n\telse\n\t\tdcbx = -EOPNOTSUPP;\n\n\tspin_unlock(&dcb_lock);\n\n\t/* features flags */\n\tif (ops->getfeatcfg) {\n\t\tstruct nlattr *feat = nla_nest_start(skb, DCB_ATTR_CEE_FEAT);\n\t\tif (!feat)\n\t\t\tgoto nla_put_failure;\n\n\t\tfor (i = DCB_FEATCFG_ATTR_ALL + 1; i <= DCB_FEATCFG_ATTR_MAX;\n\t\t i++)\n\t\t\tif (!ops->getfeatcfg(netdev, i, &value) &&\n\t\t\t nla_put_u8(skb, i, value))\n\t\t\t\tgoto nla_put_failure;\n\n\t\tnla_nest_end(skb, feat);\n\t}\n\n\t/* peer info if available */\n\tif (ops->cee_peer_getpg) {\n\t\tstruct cee_pg pg;\n\t\terr = ops->cee_peer_getpg(netdev, &pg);\n\t\tif (!err &&\n\t\t nla_put(skb, DCB_ATTR_CEE_PEER_PG, sizeof(pg), &pg))\n\t\t\tgoto nla_put_failure;\n\t}\n\n\tif (ops->cee_peer_getpfc) {\n\t\tstruct cee_pfc pfc;\n\t\terr = ops->cee_peer_getpfc(netdev, &pfc);\n\t\tif (!err &&\n\t\t nla_put(skb, DCB_ATTR_CEE_PEER_PFC, sizeof(pfc), &pfc))\n\t\t\tgoto nla_put_failure;\n\t}\n\n\tif (ops->peer_getappinfo && ops->peer_getapptable) {\n\t\terr = dcbnl_build_peer_app(netdev, skb,\n\t\t\t\t\t DCB_ATTR_CEE_PEER_APP_TABLE,\n\t\t\t\t\t DCB_ATTR_CEE_PEER_APP_INFO,\n\t\t\t\t\t DCB_ATTR_CEE_PEER_APP);\n\t\tif (err)\n\t\t\tgoto nla_put_failure;\n\t}\n\tnla_nest_end(skb, cee);\n\n\t/* DCBX state */\n\tif (dcbx >= 0) {\n\t\terr = nla_put_u8(skb, DCB_ATTR_DCBX, dcbx);\n\t\tif (err)\n\t\t\tgoto nla_put_failure;\n\t}\n\treturn 0;\n\ndcb_unlock:\n\tspin_unlock(&dcb_lock);\nnla_put_failure:\n\treturn err;\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: static int FNAME(walk_addr_generic)(struct guest_walker *walker,\n\t\t\t\t struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,\n\t\t\t\t gva_t addr, u32 access)\n{\n\tpt_element_t pte;\n\tpt_element_t __user *ptep_user;\n\tgfn_t table_gfn;\n\tunsigned index, pt_access, uninitialized_var(pte_access);\n\tgpa_t pte_gpa;\n\tbool eperm, present, rsvd_fault;\n\tint offset, write_fault, user_fault, fetch_fault;\n\n\twrite_fault = access & PFERR_WRITE_MASK;\n\tuser_fault = access & PFERR_USER_MASK;\n\tfetch_fault = access & PFERR_FETCH_MASK;\n\n\ttrace_kvm_mmu_pagetable_walk(addr, write_fault, user_fault,\n\t\t\t\t fetch_fault);\nwalk:\n\tpresent = true;\n\teperm = rsvd_fault = false;\n\twalker->level = mmu->root_level;\n\tpte = mmu->get_cr3(vcpu);\n\n#if PTTYPE == 64\n\tif (walker->level == PT32E_ROOT_LEVEL) {\n\t\tpte = kvm_pdptr_read_mmu(vcpu, mmu, (addr >> 30) & 3);\n\t\ttrace_kvm_mmu_paging_element(pte, walker->level);\n\t\tif (!is_present_gpte(pte)) {\n\t\t\tpresent = false;\n\t\t\tgoto error;\n\t\t}\n\t\t--walker->level;\n\t}\n#endif\n\tASSERT((!is_long_mode(vcpu) && is_pae(vcpu)) ||\n\t (mmu->get_cr3(vcpu) & CR3_NONPAE_RESERVED_BITS) == 0);\n\n\tpt_access = ACC_ALL;\n\n\tfor (;;) {\n\t\tgfn_t real_gfn;\n\t\tunsigned long host_addr;\n\n\t\tindex = PT_INDEX(addr, walker->level);\n\n\t\ttable_gfn = gpte_to_gfn(pte);\n\t\toffset = index * sizeof(pt_element_t);\n\t\tpte_gpa = gfn_to_gpa(table_gfn) + offset;\n\t\twalker->table_gfn[walker->level - 1] = table_gfn;\n\t\twalker->pte_gpa[walker->level - 1] = pte_gpa;\n\n\t\treal_gfn = mmu->translate_gpa(vcpu, gfn_to_gpa(table_gfn),\n\t\t\t\t\t PFERR_USER_MASK|PFERR_WRITE_MASK);\n\t\tif (unlikely(real_gfn == UNMAPPED_GVA)) {\n\t\t\tpresent = false;\n\t\t\tbreak;\n\t\t}\n\t\treal_gfn = gpa_to_gfn(real_gfn);\n\n\t\thost_addr = gfn_to_hva(vcpu->kvm, real_gfn);\n\t\tif (unlikely(kvm_is_error_hva(host_addr))) {\n\t\t\tpresent = false;\n\t\t\tbreak;\n\t\t}\n\n\t\tptep_user = (pt_element_t __user *)((void *)host_addr + offset);\n\t\tif (unlikely(copy_from_user(&pte, ptep_user, sizeof(pte)))) {\n\t\t\tpresent = false;\n\t\t\tbreak;\n\t\t}\n\n\t\ttrace_kvm_mmu_paging_element(pte, walker->level);\n\n\t\tif (unlikely(!is_present_gpte(pte))) {\n\t\t\tpresent = false;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (unlikely(is_rsvd_bits_set(&vcpu->arch.mmu, pte,\n\t\t\t\t\t walker->level))) {\n\t\t\trsvd_fault = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (unlikely(write_fault && !is_writable_pte(pte)\n\t\t\t && (user_fault || is_write_protection(vcpu))))\n\t\t\teperm = true;\n\n\t\tif (unlikely(user_fault && !(pte & PT_USER_MASK)))\n\t\t\teperm = true;\n\n#if PTTYPE == 64\n\t\tif (unlikely(fetch_fault && (pte & PT64_NX_MASK)))\n\t\t\teperm = true;\n#endif\n\n\t\tif (!eperm && !rsvd_fault\n\t\t && unlikely(!(pte & PT_ACCESSED_MASK))) {\n\t\t\tint ret;\n\t\t\ttrace_kvm_mmu_set_accessed_bit(table_gfn, index,\n\t\t\t\t\t\t sizeof(pte));\n\t\t\tret = FNAME(cmpxchg_gpte)(vcpu, mmu, table_gfn,\n\t\t\t\t\tindex, pte, pte|PT_ACCESSED_MASK);\n\t\t\tif (ret < 0) {\n\t\t\t\tpresent = false;\n\t\t\t\tbreak;\n\t\t\t} else if (ret)\n\t\t\t\tgoto walk;\n\n\t\t\tmark_page_dirty(vcpu->kvm, table_gfn);\n\t\t\tpte |= PT_ACCESSED_MASK;\n\t\t}\n\n\t\tpte_access = pt_access & FNAME(gpte_access)(vcpu, pte);\n\n\t\twalker->ptes[walker->level - 1] = pte;\n\n\t\tif ((walker->level == PT_PAGE_TABLE_LEVEL) ||\n\t\t ((walker->level == PT_DIRECTORY_LEVEL) &&\n\t\t\t\tis_large_pte(pte) &&\n\t\t\t\t(PTTYPE == 64 || is_pse(vcpu))) ||\n\t\t ((walker->level == PT_PDPE_LEVEL) &&\n\t\t\t\tis_large_pte(pte) &&\n\t\t\t\tmmu->root_level == PT64_ROOT_LEVEL)) {\n\t\t\tint lvl = walker->level;\n\t\t\tgpa_t real_gpa;\n\t\t\tgfn_t gfn;\n\t\t\tu32 ac;\n\n\t\t\tgfn = gpte_to_gfn_lvl(pte, lvl);\n\t\t\tgfn += (addr & PT_LVL_OFFSET_MASK(lvl)) >> PAGE_SHIFT;\n\n\t\t\tif (PTTYPE == 32 &&\n\t\t\t walker->level == PT_DIRECTORY_LEVEL &&\n\t\t\t is_cpuid_PSE36())\n\t\t\t\tgfn += pse36_gfn_delta(pte);\n\n\t\t\tac = write_fault | fetch_fault | user_fault;\n\n\t\t\treal_gpa = mmu->translate_gpa(vcpu, gfn_to_gpa(gfn),\n\t\t\t\t\t\t ac);\n\t\t\tif (real_gpa == UNMAPPED_GVA)\n\t\t\t\treturn 0;\n\n\t\t\twalker->gfn = real_gpa >> PAGE_SHIFT;\n\n\t\t\tbreak;\n\t\t}\n\n\t\tpt_access = pte_access;\n\t\t--walker->level;\n\t}\n\n\tif (unlikely(!present || eperm || rsvd_fault))\n\t\tgoto error;\n\n\tif (write_fault && unlikely(!is_dirty_gpte(pte))) {\n\t\tint ret;\n\n\t\ttrace_kvm_mmu_set_dirty_bit(table_gfn, index, sizeof(pte));\n\t\tret = FNAME(cmpxchg_gpte)(vcpu, mmu, table_gfn, index, pte,\n\t\t\t pte|PT_DIRTY_MASK);\n\t\tif (ret < 0) {\n\t\t\tpresent = false;\n\t\t\tgoto error;\n\t\t} else if (ret)\n\t\t\tgoto walk;\n\n\t\tmark_page_dirty(vcpu->kvm, table_gfn);\n\t\tpte |= PT_DIRTY_MASK;\n\t\twalker->ptes[walker->level - 1] = pte;\n\t}\n\n\twalker->pt_access = pt_access;\n\twalker->pte_access = pte_access;\n\tpgprintk(\"%s: pte %llx pte_access %x pt_access %x\\n\",\n\t\t __func__, (u64)pte, pte_access, pt_access);\n\treturn 1;\n\nerror:\n\twalker->fault.vector = PF_VECTOR;\n\twalker->fault.error_code_valid = true;\n\twalker->fault.error_code = 0;\n\tif (present)\n\t\twalker->fault.error_code |= PFERR_PRESENT_MASK;\n\n\twalker->fault.error_code |= write_fault | user_fault;\n\n\tif (fetch_fault && mmu->nx)\n\t\twalker->fault.error_code |= PFERR_FETCH_MASK;\n\tif (rsvd_fault)\n\t\twalker->fault.error_code |= PFERR_RSVD_MASK;\n\n\twalker->fault.address = addr;\n\twalker->fault.nested_page_fault = mmu != vcpu->arch.walk_mmu;\n\n\ttrace_kvm_mmu_walker_error(walker->fault.error_code);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'KVM: Validate userspace_addr of memslot when registered\n\nThis way, we can avoid checking the user space address many times when\nwe read the guest memory.\n\nAlthough we can do the same for write if we check which slots are\nwritable, we do not care write now: reading the guest memory happens\nmore often than writing.\n\n[avi: change VERIFY_READ to VERIFY_WRITE]\n\nSigned-off-by: Takuya Yoshikawa \nSigned-off-by: Avi Kivity '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void pdfobj_flag(struct pdf_struct *pdf, struct pdf_obj *obj, enum pdf_flag flag)\n{\n const char *s= \"\";\n pdf->flags |= 1 << flag;\n if (!cli_debug_flag)\n\treturn;\n switch (flag) {\n\tcase UNTERMINATED_OBJ_DICT:\n\t s = \"dictionary not terminated\";\n\t break;\n\tcase ESCAPED_COMMON_PDFNAME:\n\t /* like /JavaScript */\n\t s = \"escaped common pdfname\";\n\t break;\n\tcase BAD_STREAM_FILTERS:\n\t s = \"duplicate stream filters\";\n\t break;\n\tcase BAD_PDF_VERSION:\n\t s = \"bad pdf version\";\n\t break;\n\tcase BAD_PDF_HEADERPOS:\n\t s = \"bad pdf header position\";\n\t break;\n\tcase BAD_PDF_TRAILER:\n\t s = \"bad pdf trailer\";\n\t break;\n\tcase BAD_PDF_TOOMANYOBJS:\n\t s = \"too many pdf objs\";\n\t break;\n\tcase BAD_FLATE:\n\t s = \"bad deflate stream\";\n\t break;\n\tcase BAD_FLATESTART:\n\t s = \"bad deflate stream start\";\n\t break;\n\tcase BAD_STREAMSTART:\n\t s = \"bad stream start\";\n\t break;\n\tcase UNKNOWN_FILTER:\n\t s = \"unknown filter used\";\n\t break;\n\tcase BAD_ASCIIDECODE:\n\t s = \"bad ASCII decode\";\n\t break;\n\tcase HEX_JAVASCRIPT:\n\t s = \"hex javascript\";\n\t break;\n\tcase BAD_INDOBJ:\n\t s = \"referencing nonexistent obj\";\n\t break;\n\tcase HAS_OPENACTION:\n\t s = \"has /OpenAction\";\n\t break;\n\tcase HAS_LAUNCHACTION:\n\t s = \"has /LaunchAction\";\n\t break;\n\tcase BAD_STREAMLEN:\n\t s = \"bad /Length, too small\";\n\t break;\n\tcase ENCRYPTED_PDF:\n\t s = \"PDF is encrypted\";\n\t break;\n\tcase LINEARIZED_PDF:\n\t s = \"linearized PDF\";\n\t break;\n\tcase MANY_FILTERS:\n\t s = \"more than 2 filters per obj\";\n\t break;\n }\n cli_dbgmsg(\"cli_pdf: %s flagged in object %u %u\\n\", s, obj->id>>8, obj->id&0xff);\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: int iscsi_decode_text_input(\n\tu8 phase,\n\tu8 sender,\n\tchar *textbuf,\n\tu32 length,\n\tstruct iscsi_conn *conn)\n{\n\tstruct iscsi_param_list *param_list = conn->param_list;\n\tchar *tmpbuf, *start = NULL, *end = NULL;\n\n\ttmpbuf = kzalloc(length + 1, GFP_KERNEL);\n\tif (!tmpbuf) {\n\t\tpr_err(\"Unable to allocate memory for tmpbuf.\\n\");\n\t\treturn -1;\n\t}\n\n\tmemcpy(tmpbuf, textbuf, length);\n\ttmpbuf[length] = '\\0';\n\tstart = tmpbuf;\n\tend = (start + length);\n\n\twhile (start < end) {\n\t\tchar *key, *value;\n\t\tstruct iscsi_param *param;\n\n\t\tif (iscsi_extract_key_value(start, &key, &value) < 0) {\n\t\t\tkfree(tmpbuf);\n\t\t\treturn -1;\n\t\t}\n\n\t\tpr_debug(\"Got key: %s=%s\\n\", key, value);\n\n\t\tif (phase & PHASE_SECURITY) {\n\t\t\tif (iscsi_check_for_auth_key(key) > 0) {\n\t\t\t\tchar *tmpptr = key + strlen(key);\n\t\t\t\t*tmpptr = '=';\n\t\t\t\tkfree(tmpbuf);\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\n\t\tparam = iscsi_check_key(key, phase, sender, param_list);\n\t\tif (!param) {\n\t\t\tif (iscsi_add_notunderstood_response(key,\n\t\t\t\t\tvalue, param_list) < 0) {\n\t\t\t\tkfree(tmpbuf);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tstart += strlen(key) + strlen(value) + 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (iscsi_check_value(param, value) < 0) {\n\t\t\tkfree(tmpbuf);\n\t\t\treturn -1;\n\t\t}\n\n\t\tstart += strlen(key) + strlen(value) + 2;\n\n\t\tif (IS_PSTATE_PROPOSER(param)) {\n\t\t\tif (iscsi_check_proposer_state(param, value) < 0) {\n\t\t\t\tkfree(tmpbuf);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tSET_PSTATE_RESPONSE_GOT(param);\n\t\t} else {\n\t\t\tif (iscsi_check_acceptor_state(param, value, conn) < 0) {\n\t\t\t\tkfree(tmpbuf);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tSET_PSTATE_ACCEPTOR(param);\n\t\t}\n\t}\n\n\tkfree(tmpbuf);\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: \tvirtual bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) {\n\t\tCSmartPtr spSession = WebSock.GetSession();\n\n\t\tif (sPageName == \"settings\") {\n\t\t\t// Admin Check\n\t\t\tif (!spSession->IsAdmin()) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treturn SettingsPage(WebSock, Tmpl);\n\t\t} else if (sPageName == \"adduser\") {\n\t\t\t// Admin Check\n\t\t\tif (!spSession->IsAdmin()) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treturn UserPage(WebSock, Tmpl);\n\t\t} else if (sPageName == \"addnetwork\") {\n\t\t\tCUser* pUser = SafeGetUserFromParam(WebSock);\n\n\t\t\t// Admin||Self Check\n\t\t\tif (!spSession->IsAdmin() && (!spSession->GetUser() || spSession->GetUser() != pUser)) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (pUser) {\n\t\t\t\treturn NetworkPage(WebSock, Tmpl, pUser);\n\t\t\t}\n\n\t\t\tWebSock.PrintErrorPage(\"No such username\");\n\t\t\treturn true;\n\t\t} else if (sPageName == \"editnetwork\") {\n\t\t\tCIRCNetwork* pNetwork = SafeGetNetworkFromParam(WebSock);\n\n\t\t\t// Admin||Self Check\n\t\t\tif (!spSession->IsAdmin() && (!spSession->GetUser() || spSession->GetUser() != pNetwork->GetUser())) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!pNetwork) {\n\t\t\t\tWebSock.PrintErrorPage(\"No such username or network\");\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\treturn NetworkPage(WebSock, Tmpl, pNetwork->GetUser(), pNetwork);\n\n\t\t} else if (sPageName == \"delnetwork\") {\n\t\t\tCString sUser = WebSock.GetParam(\"user\");\n\t\t\tif (sUser.empty() && !WebSock.IsPost()) {\n\t\t\t\tsUser = WebSock.GetParam(\"user\", false);\n\t\t\t}\n\n\t\t\tCUser* pUser = CZNC::Get().FindUser(sUser);\n\n\t\t\t// Admin||Self Check\n\t\t\tif (!spSession->IsAdmin() && (!spSession->GetUser() || spSession->GetUser() != pUser)) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treturn DelNetwork(WebSock, pUser, Tmpl);\n\t\t} else if (sPageName == \"editchan\") {\n\t\t\tCIRCNetwork* pNetwork = SafeGetNetworkFromParam(WebSock);\n\n\t\t\t// Admin||Self Check\n\t\t\tif (!spSession->IsAdmin() && (!spSession->GetUser() || spSession->GetUser() != pNetwork->GetUser())) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!pNetwork) {\n\t\t\t\tWebSock.PrintErrorPage(\"No such username or network\");\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tCString sChan = WebSock.GetParam(\"name\");\n\t\t\tif(sChan.empty() && !WebSock.IsPost()) {\n\t\t\t\tsChan = WebSock.GetParam(\"name\", false);\n\t\t\t}\n\t\t\tCChan* pChan = pNetwork->FindChan(sChan);\n\t\t\tif (!pChan) {\n\t\t\t\tWebSock.PrintErrorPage(\"No such channel\");\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\treturn ChanPage(WebSock, Tmpl, pNetwork, pChan);\n\t\t} else if (sPageName == \"addchan\") {\n\t\t\tCIRCNetwork* pNetwork = SafeGetNetworkFromParam(WebSock);\n\n\t\t\t// Admin||Self Check\n\t\t\tif (!spSession->IsAdmin() && (!spSession->GetUser() || spSession->GetUser() != pNetwork->GetUser())) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (pNetwork) {\n\t\t\t\treturn ChanPage(WebSock, Tmpl, pNetwork);\n\t\t\t}\n\n\t\t\tWebSock.PrintErrorPage(\"No such username or network\");\n\t\t\treturn true;\n\t\t} else if (sPageName == \"delchan\") {\n\t\t\tCIRCNetwork* pNetwork = SafeGetNetworkFromParam(WebSock);\n\n\t\t\t// Admin||Self Check\n\t\t\tif (!spSession->IsAdmin() && (!spSession->GetUser() || spSession->GetUser() != pNetwork->GetUser())) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (pNetwork) {\n\t\t\t\treturn DelChan(WebSock, pNetwork);\n\t\t\t}\n\n\t\t\tWebSock.PrintErrorPage(\"No such username or network\");\n\t\t\treturn true;\n\t\t} else if (sPageName == \"deluser\") {\n\t\t\tif (!spSession->IsAdmin()) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!WebSock.IsPost()) {\n\t\t\t\t// Show the \"Are you sure?\" page:\n\n\t\t\t\tCString sUser = WebSock.GetParam(\"user\", false);\n\t\t\t\tCUser* pUser = CZNC::Get().FindUser(sUser);\n\n\t\t\t\tif (!pUser) {\n\t\t\t\t\tWebSock.PrintErrorPage(\"No such username\");\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\tTmpl.SetFile(\"del_user.tmpl\");\n\t\t\t\tTmpl[\"Username\"] = sUser;\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t// The \"Are you sure?\" page has been submitted with \"Yes\",\n\t\t\t// so we actually delete the user now:\n\n\t\t\tCString sUser = WebSock.GetParam(\"user\");\n\t\t\tCUser* pUser = CZNC::Get().FindUser(sUser);\n\n\t\t\tif (pUser && pUser == spSession->GetUser()) {\n\t\t\t\tWebSock.PrintErrorPage(\"Please don't delete yourself, suicide is not the answer!\");\n\t\t\t\treturn true;\n\t\t\t} else if (CZNC::Get().DeleteUser(sUser)) {\n\t\t\t\tWebSock.Redirect(\"listusers\");\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tWebSock.PrintErrorPage(\"No such username\");\n\t\t\treturn true;\n\t\t} else if (sPageName == \"edituser\") {\n\t\t\tCString sUserName = SafeGetUserNameParam(WebSock);\n\t\t\tCUser* pUser = CZNC::Get().FindUser(sUserName);\n\n\t\t\tif(!pUser) {\n\t\t\t\tif(sUserName.empty()) {\n\t\t\t\t\tpUser = spSession->GetUser();\n\t\t\t\t} // else: the \"no such user\" message will be printed.\n\t\t\t}\n\n\t\t\t// Admin||Self Check\n\t\t\tif (!spSession->IsAdmin() && (!spSession->GetUser() || spSession->GetUser() != pUser)) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (pUser) {\n\t\t\t\treturn UserPage(WebSock, Tmpl, pUser);\n\t\t\t}\n\n\t\t\tWebSock.PrintErrorPage(\"No such username\");\n\t\t\treturn true;\n\t\t} else if (sPageName == \"listusers\" && spSession->IsAdmin()) {\n\t\t\treturn ListUsersPage(WebSock, Tmpl);\n\t\t} else if (sPageName == \"traffic\" && spSession->IsAdmin()) {\n\t\t\treturn TrafficPage(WebSock, Tmpl);\n\t\t} else if (sPageName == \"index\") {\n\t\t\treturn true;\n\t\t} else if (sPageName == \"add_listener\") {\n\t\t\t// Admin Check\n\t\t\tif (!spSession->IsAdmin()) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treturn AddListener(WebSock, Tmpl);\n\t\t} else if (sPageName == \"del_listener\") {\n\t\t\t// Admin Check\n\t\t\tif (!spSession->IsAdmin()) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treturn DelListener(WebSock, Tmpl);\n\t\t}\n\n\t\treturn false;\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'Fix NULL pointer dereference in webadmin.\n\nTriggerable by any non-admin, if webadmin is loaded.\n\nThe only affected version is 1.0\n\nThanks to ChauffeR (Simone Esposito) for reporting 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: ZrtpQueue::takeInDataPacket(void)\n{\n InetHostAddress network_address;\n tpport_t transport_port;\n\n uint32 nextSize = (uint32)getNextDataPacketSize();\n unsigned char* buffer = new unsigned char[nextSize];\n int32 rtn = (int32)recvData(buffer, nextSize, network_address, transport_port);\n if ( (rtn < 0) || ((uint32)rtn > getMaxRecvPacketSize()) ){\n delete buffer;\n return 0;\n }\n\n IncomingZRTPPkt* packet = NULL;\n // check if this could be a real RTP/SRTP packet.\n if ((*buffer & 0xf0) != 0x10) {\n return (rtpDataPacket(buffer, rtn, network_address, transport_port));\n }\n\n // We assume all other packets are ZRTP packets here. Process\n // if ZRTP processing is enabled. Because valid RTP packets are\n // already handled we delete any packets here after processing.\n if (enableZrtp && zrtpEngine != NULL) {\n // Get CRC value into crc (see above how to compute the offset)\n uint16_t temp = rtn - CRC_SIZE;\n uint32_t crc = *(uint32_t*)(buffer + temp);\n crc = ntohl(crc);\n\n if (!zrtpCheckCksum(buffer, temp, crc)) {\n delete buffer;\n if (zrtpUserCallback != NULL)\n zrtpUserCallback->showMessage(Warning, WarningCRCmismatch);\n return 0;\n }\n\n packet = new IncomingZRTPPkt(buffer,rtn);\n\n uint32 magic = packet->getZrtpMagic();\n\n // Check if it is really a ZRTP packet, if not delete it and return 0\n if (magic != ZRTP_MAGIC || zrtpEngine == NULL) {\n delete packet;\n return 0;\n }\n // cover the case if the other party sends _only_ ZRTP packets at the\n // beginning of a session. Start ZRTP in this case as well.\n if (!started) {\n startZrtp();\n }\n // this now points beyond the undefined and length field.\n // We need them, thus adjust\n unsigned char* extHeader =\n const_cast(packet->getHdrExtContent());\n extHeader -= 4;\n\n // store peer's SSRC, used when creating the CryptoContext\n peerSSRC = packet->getSSRC();\n zrtpEngine->processZrtpMessage(extHeader, peerSSRC, rtn);\n }\n delete packet;\n return 0;\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 AuthorizationManager::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 } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'SERVER-9983 Do not needlessly lock when looking up privileges for the __system@local user.\n\nUncorrected, this can cause replica set heartbeats to stall behind operations\nthat hold the read lock for a long time.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ber_skip_contextual_tag(int length)\n{\n\treturn _ber_skip_length(length) + 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: int ber_skip_sequence_tag(int length)\n{\n\treturn 1 + _ber_skip_length(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: BOOL ber_read_bit_string(wStream* s, int* length, BYTE* padding)\n{\n\tif(!ber_read_universal_tag(s, BER_TAG_BIT_STRING, FALSE) ||\n\t\t!ber_read_length(s, length))\n\t\treturn FALSE;\n\n\tif(Stream_GetRemainingLength(s) < 1)\n\t\treturn FALSE;\n\tStream_Read_UINT8(s, *padding);\n\treturn TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int credssp_skip_nego_token(int length)\n{\n\tlength = der_skip_octet_string(length);\n\tlength += der_skip_contextual_tag(length);\n\treturn length;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: rdpCredssp* credssp_new(freerdp* instance, rdpTransport* transport, rdpSettings* settings)\n{\n\trdpCredssp* credssp;\n\n\tcredssp = (rdpCredssp*) malloc(sizeof(rdpCredssp));\n\tZeroMemory(credssp, sizeof(rdpCredssp));\n\n\tif (credssp != NULL)\n\t{\n\t\tHKEY hKey;\n\t\tLONG status;\n\t\tDWORD dwType;\n\t\tDWORD dwSize;\n\n\t\tcredssp->instance = instance;\n\t\tcredssp->settings = settings;\n\t\tcredssp->server = settings->ServerMode;\n\t\tcredssp->transport = transport;\n\t\tcredssp->send_seq_num = 0;\n\t\tcredssp->recv_seq_num = 0;\n\t\tZeroMemory(&credssp->negoToken, sizeof(SecBuffer));\n\t\tZeroMemory(&credssp->pubKeyAuth, sizeof(SecBuffer));\n\t\tZeroMemory(&credssp->authInfo, sizeof(SecBuffer));\n\n\t\tif (credssp->server)\n\t\t{\n\t\t\tstatus = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(\"Software\\\\FreeRDP\\\\Server\"),\n\t\t\t\t\t0, KEY_READ | KEY_WOW64_64KEY, &hKey);\n\n\t\t\tif (status == ERROR_SUCCESS)\n\t\t\t{\n\t\t\t\tstatus = RegQueryValueEx(hKey, _T(\"SspiModule\"), NULL, &dwType, NULL, &dwSize);\n\n\t\t\t\tif (status == ERROR_SUCCESS)\n\t\t\t\t{\n\t\t\t\t\tcredssp->SspiModule = (LPTSTR) malloc(dwSize + sizeof(TCHAR));\n\n\t\t\t\t\tstatus = RegQueryValueEx(hKey, _T(\"SspiModule\"), NULL, &dwType,\n\t\t\t\t\t\t\t(BYTE*) credssp->SspiModule, &dwSize);\n\n\t\t\t\t\tif (status == ERROR_SUCCESS)\n\t\t\t\t\t{\n\t\t\t\t\t\t_tprintf(_T(\"Using SSPI Module: %s\\n\"), credssp->SspiModule);\n\t\t\t\t\t\tRegCloseKey(hKey);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn credssp;\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: xmlParseStringPEReference(xmlParserCtxtPtr ctxt, const xmlChar **str) {\n const xmlChar *ptr;\n xmlChar cur;\n xmlChar *name;\n xmlEntityPtr entity = NULL;\n\n if ((str == NULL) || (*str == NULL)) return(NULL);\n ptr = *str;\n cur = *ptr;\n if (cur != '%')\n return(NULL);\n ptr++;\n name = xmlParseStringName(ctxt, &ptr);\n if (name == NULL) {\n\txmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,\n\t\t \"xmlParseStringPEReference: no name\\n\");\n\t*str = ptr;\n\treturn(NULL);\n }\n cur = *ptr;\n if (cur != ';') {\n\txmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);\n\txmlFree(name);\n\t*str = ptr;\n\treturn(NULL);\n }\n ptr++;\n\n /*\n * Increate the number of entity references parsed\n */\n ctxt->nbentities++;\n\n /*\n * Request the entity from SAX\n */\n if ((ctxt->sax != NULL) &&\n\t(ctxt->sax->getParameterEntity != NULL))\n\tentity = ctxt->sax->getParameterEntity(ctxt->userData,\n\t\t\t\t\t name);\n if (entity == NULL) {\n\t/*\n\t * [ WFC: Entity Declared ]\n\t * In a document without any DTD, a document with only an\n\t * internal DTD subset which contains no parameter entity\n\t * references, or a document with \"standalone='yes'\", ...\n\t * ... The declaration of a parameter entity must precede\n\t * any reference to it...\n\t */\n\tif ((ctxt->standalone == 1) ||\n\t ((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) {\n\t xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,\n\t\t \"PEReference: %%%s; not found\\n\", name);\n\t} else {\n\t /*\n\t * [ VC: Entity Declared ]\n\t * In a document with an external subset or external\n\t * parameter entities with \"standalone='no'\", ...\n\t * ... The declaration of a parameter entity must\n\t * precede any reference to it...\n\t */\n\t xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,\n\t\t\t \"PEReference: %%%s; not found\\n\",\n\t\t\t name, NULL);\n\t ctxt->valid = 0;\n\t}\n } else {\n\t/*\n\t * Internal checking in case the entity quest barfed\n\t */\n\tif ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) &&\n\t (entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) {\n\t xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,\n\t\t\t \"%%%s; is not a parameter entity\\n\",\n\t\t\t name, NULL);\n\t}\n }\n ctxt->hasPErefs = 1;\n xmlFree(name);\n *str = ptr;\n return(entity);\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: static void xml_parser_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC)\n{\n\txml_parser *parser = (xml_parser *)rsrc->ptr;\n\t\n\tif (parser->parser) {\n\t\tXML_ParserFree(parser->parser);\n\t}\n\tif (parser->ltags) {\n\t\tint inx;\n\t\tfor (inx = 0; inx < parser->level; inx++)\n\t\t\tefree(parser->ltags[ inx ]);\n\t\tefree(parser->ltags);\n\t}\n\tif (parser->startElementHandler) {\n\t\tzval_ptr_dtor(&parser->startElementHandler);\n\t}\n\tif (parser->endElementHandler) {\n\t\tzval_ptr_dtor(&parser->endElementHandler);\n\t}\n\tif (parser->characterDataHandler) {\n\t\tzval_ptr_dtor(&parser->characterDataHandler);\n\t}\n\tif (parser->processingInstructionHandler) {\n\t\tzval_ptr_dtor(&parser->processingInstructionHandler);\n\t}\n\tif (parser->defaultHandler) {\n\t\tzval_ptr_dtor(&parser->defaultHandler);\n\t}\n\tif (parser->unparsedEntityDeclHandler) {\n\t\tzval_ptr_dtor(&parser->unparsedEntityDeclHandler);\n\t}\n\tif (parser->notationDeclHandler) {\n\t\tzval_ptr_dtor(&parser->notationDeclHandler);\n\t}\n\tif (parser->externalEntityRefHandler) {\n\t\tzval_ptr_dtor(&parser->externalEntityRefHandler);\n\t}\n\tif (parser->unknownEncodingHandler) {\n\t\tzval_ptr_dtor(&parser->unknownEncodingHandler);\n\t}\n\tif (parser->startNamespaceDeclHandler) {\n\t\tzval_ptr_dtor(&parser->startNamespaceDeclHandler);\n\t}\n\tif (parser->endNamespaceDeclHandler) {\n\t\tzval_ptr_dtor(&parser->endNamespaceDeclHandler);\n\t}\n\tif (parser->baseURI) {\n\t\tefree(parser->baseURI);\n\t}\n\tif (parser->object) {\n\t\tzval_ptr_dtor(&parser->object);\n\t}\n\n\tefree(parser);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'truncate results at depth of 255 to prevent corruption'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void br_multicast_del_pg(struct net_bridge *br,\n\t\t\t\tstruct net_bridge_port_group *pg)\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\n\tmdb = mlock_dereference(br->mdb, br);\n\n\tmp = br_mdb_ip_get(mdb, &pg->addr);\n\tif (WARN_ON(!mp))\n\t\treturn;\n\n\tfor (pp = &mp->ports;\n\t (p = mlock_dereference(*pp, br)) != NULL;\n\t pp = &p->next) {\n\t\tif (p != pg)\n\t\t\tcontinue;\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\n\t\tif (!mp->ports && !mp->mglist &&\n\t\t netif_running(br->dev))\n\t\t\tmod_timer(&mp->timer, jiffies);\n\n\t\treturn;\n\t}\n\n\tWARN_ON(1);\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: \tvoid createDirectory(const string &path) const {\n\t\t// We do not use makeDirTree() here. If an attacker creates a directory\n\t\t// just before we do, then we want to abort because we want the directory\n\t\t// to have specific permissions.\n\t\tif (mkdir(path.c_str(), parseModeString(\"u=rwx,g=rx,o=rx\")) == -1) {\n\t\t\tint e = errno;\n\t\t\tthrow FileSystemException(\"Cannot create server instance directory '\" +\n\t\t\t\tpath + \"'\", e, path);\n\t\t}\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 ps_files_open(ps_files *data, const char *key TSRMLS_DC)\n{\n\tchar buf[MAXPATHLEN];\n\n\tif (data->fd < 0 || !data->lastkey || strcmp(key, data->lastkey)) {\n\t\tif (data->lastkey) {\n\t\t\tefree(data->lastkey);\n\t\t\tdata->lastkey = NULL;\n\t\t}\n\n\t\tps_files_close(data);\n\n\t\tif (!ps_files_valid_key(key)) {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"The session id is too long or contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,'\");\n\t\t\tPS(invalid_session_id) = 1;\n\t\t\treturn;\n\t\t}\n\t\tif (!ps_files_path_create(buf, sizeof(buf), data, key)) {\n\t\t\treturn;\n\t\t}\n\n\t\tdata->lastkey = estrdup(key);\n\n\t\tdata->fd = VCWD_OPEN_MODE(buf, O_CREAT | O_RDWR | O_BINARY, data->filemode);\n\n\t\tif (data->fd != -1) {\n#ifndef PHP_WIN32\n\t\t\t/* check to make sure that the opened file is not a symlink, linking to data outside of allowable dirs */\n\t\t\tif (PG(open_basedir)) {\n\t\t\t\tstruct stat sbuf;\n\n\t\t\t\tif (fstat(data->fd, &sbuf)) {\n\t\t\t\t\tclose(data->fd);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (S_ISLNK(sbuf.st_mode) && php_check_open_basedir(buf TSRMLS_CC)) {\n\t\t\t\t\tclose(data->fd);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n#endif\n\t\t\tflock(data->fd, LOCK_EX);\n\n#ifdef F_SETFD\n# ifndef FD_CLOEXEC\n# define FD_CLOEXEC 1\n# endif\n\t\t\tif (fcntl(data->fd, F_SETFD, FD_CLOEXEC)) {\n\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"fcntl(%d, F_SETFD, FD_CLOEXEC) failed: %s (%d)\", data->fd, strerror(errno), errno);\n\t\t\t}\n#endif\n\t\t} else {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"open(%s, O_RDWR) failed: %s (%d)\", buf, strerror(errno), errno);\n\t\t}\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'Strict session'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: 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\t\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: void CLASS apply_tiff()\n{\n int max_samp=0, raw=-1, thm=-1, i;\n struct jhead jh;\n\n thumb_misc = 16;\n if (thumb_offset) {\n fseek (ifp, thumb_offset, SEEK_SET);\n if (ljpeg_start (&jh, 1)) {\n thumb_misc = jh.bits;\n thumb_width = jh.wide;\n thumb_height = jh.high;\n }\n }\n for (i=0; i < tiff_nifds; i++) {\n if (max_samp < tiff_ifd[i].samples)\n\tmax_samp = tiff_ifd[i].samples;\n if (max_samp > 3) max_samp = 3;\n if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) &&\n\t(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 &&\n\ttiff_ifd[i].t_width*tiff_ifd[i].t_height > raw_width*raw_height) {\n raw_width = tiff_ifd[i].t_width;\n raw_height = tiff_ifd[i].t_height;\n tiff_bps = tiff_ifd[i].bps;\n tiff_compress = tiff_ifd[i].comp;\n data_offset = tiff_ifd[i].offset;\n tiff_flip = tiff_ifd[i].t_flip;\n tiff_samples = tiff_ifd[i].samples;\n tile_width = tiff_ifd[i].t_tile_width;\n tile_length = tiff_ifd[i].t_tile_length;\n#ifdef LIBRAW_LIBRARY_BUILD\n data_size = tile_length < INT_MAX && tile_length>0 ? tiff_ifd[i].tile_maxbytes: tiff_ifd[i].bytes;\n#endif\n raw = i;\n }\n }\n if (!tile_width ) tile_width = INT_MAX;\n if (!tile_length) tile_length = INT_MAX;\n for (i=tiff_nifds; i--; )\n if (tiff_ifd[i].t_flip) tiff_flip = tiff_ifd[i].t_flip;\n if (raw >= 0 && !load_raw)\n switch (tiff_compress) {\n case 32767:\n\tif (tiff_ifd[raw].bytes == raw_width*raw_height) {\n\t tiff_bps = 12;\n\t load_raw = &CLASS sony_arw2_load_raw;\t\t\tbreak;\n\t}\n\tif (tiff_ifd[raw].bytes*8 != raw_width*raw_height*tiff_bps) {\n\t raw_height += 8;\n\t load_raw = &CLASS sony_arw_load_raw;\t\t\tbreak;\n\t}\n\tload_flags = 79;\n case 32769:\n\tload_flags++;\n case 32770:\n case 32773: goto slr;\n case 0: case 1:\n\tif (tiff_ifd[raw].bytes*5 == raw_width*raw_height*8) {\n\t load_flags = 81;\n\t tiff_bps = 12;\n\t} slr:\n\tswitch (tiff_bps) {\n\t case 8: load_raw = &CLASS eight_bit_load_raw;\tbreak;\n\t case 12: if (tiff_ifd[raw].phint == 2)\n\t\t load_flags = 6;\n\t\t load_raw = &CLASS packed_load_raw;\t\tbreak;\n\t case 14: load_flags = 0;\n\t case 16: load_raw = &CLASS unpacked_load_raw;\t\tbreak;\n\t}\n\tbreak;\n case 6: case 7: case 99:\n\tload_raw = &CLASS lossless_jpeg_load_raw;\t\tbreak;\n case 262:\n\tload_raw = &CLASS kodak_262_load_raw;\t\t\tbreak;\n case 34713:\n\tif ((raw_width+9)/10*16*raw_height == tiff_ifd[raw].bytes) {\n\t load_raw = &CLASS packed_load_raw;\n\t load_flags = 1;\n\t} else if (raw_width*raw_height*2 == tiff_ifd[raw].bytes) {\n\t load_raw = &CLASS unpacked_load_raw;\n\t load_flags = 4;\n\t order = 0x4d4d;\n\t} else\n\t load_raw = &CLASS nikon_load_raw;\t\t\tbreak;\n case 34892:\n\tload_raw = &CLASS lossy_dng_load_raw;\t\t\tbreak;\n case 65535:\n\tload_raw = &CLASS pentax_load_raw;\t\t\tbreak;\n case 65000:\n\tswitch (tiff_ifd[raw].phint) {\n\t case 2: load_raw = &CLASS kodak_rgb_load_raw; filters = 0; break;\n\t case 6: load_raw = &CLASS kodak_ycbcr_load_raw; filters = 0; break;\n\t case 32803: load_raw = &CLASS kodak_65000_load_raw;\n\t}\n case 32867: break;\n default: is_raw = 0;\n }\n if (!dng_version)\n if ( (tiff_samples == 3 && tiff_ifd[raw].bytes &&\n\t tiff_bps != 14 && tiff_bps != 2048 && \n\t tiff_compress != 32769 && tiff_compress != 32770)\n || (tiff_bps == 8 && !strstr(make,\"KODAK\") && !strstr(make,\"Kodak\") &&\n\t !strstr(model2,\"DEBUG RAW\")))\n is_raw = 0;\n for (i=0; i < tiff_nifds; i++)\n if (i != raw && tiff_ifd[i].samples == max_samp &&\n\ttiff_ifd[i].t_width * tiff_ifd[i].t_height / SQR(tiff_ifd[i].bps+1) >\n\t thumb_width * thumb_height / SQR(thumb_misc+1)\n\t&& tiff_ifd[i].comp != 34892) {\n thumb_width = tiff_ifd[i].t_width;\n thumb_height = tiff_ifd[i].t_height;\n thumb_offset = tiff_ifd[i].offset;\n thumb_length = tiff_ifd[i].bytes;\n thumb_misc = tiff_ifd[i].bps;\n thm = i;\n }\n if (thm >= 0) {\n thumb_misc |= tiff_ifd[thm].samples << 5;\n switch (tiff_ifd[thm].comp) {\n case 0:\n\twrite_thumb = &CLASS layer_thumb;\n\tbreak;\n case 1:\n\tif (tiff_ifd[thm].bps <= 8)\n\t write_thumb = &CLASS ppm_thumb;\n\telse if (!strcmp(make,\"Imacon\"))\n\t write_thumb = &CLASS ppm16_thumb;\n\telse\n\t thumb_load_raw = &CLASS kodak_thumb_load_raw;\n\tbreak;\n case 65000:\n\tthumb_load_raw = tiff_ifd[thm].phint == 6 ?\n\t\t&CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw;\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'cumulated data checks patch'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int main( int argc, char *argv[] )\n{\n FILE *f;\n\n int ret;\n size_t n, buflen;\n int server_fd = -1;\n\n unsigned char *p, *end;\n unsigned char buf[2048];\n unsigned char hash[20];\n const char *pers = \"dh_client\";\n\n entropy_context entropy;\n ctr_drbg_context ctr_drbg;\n rsa_context rsa;\n dhm_context dhm;\n aes_context aes;\n\n ((void) argc);\n ((void) argv);\n\n memset( &rsa, 0, sizeof( rsa ) );\n memset( &dhm, 0, sizeof( dhm ) );\n\n /*\n * 1. Setup the RNG\n */\n printf( \"\\n . Seeding the random number generator\" );\n fflush( stdout );\n\n entropy_init( &entropy );\n if( ( ret = ctr_drbg_init( &ctr_drbg, entropy_func, &entropy,\n (const unsigned char *) pers,\n strlen( pers ) ) ) != 0 )\n {\n printf( \" failed\\n ! ctr_drbg_init returned %d\\n\", ret );\n goto exit;\n }\n\n /*\n * 2. Read the server's public RSA key\n */\n printf( \"\\n . Reading public key from rsa_pub.txt\" );\n fflush( stdout );\n\n if( ( f = fopen( \"rsa_pub.txt\", \"rb\" ) ) == NULL )\n {\n ret = 1;\n printf( \" failed\\n ! Could not open rsa_pub.txt\\n\" \\\n \" ! Please run rsa_genkey first\\n\\n\" );\n goto exit;\n }\n\n rsa_init( &rsa, RSA_PKCS_V15, 0 );\n\n if( ( ret = mpi_read_file( &rsa.N, 16, f ) ) != 0 ||\n ( ret = mpi_read_file( &rsa.E, 16, f ) ) != 0 )\n {\n printf( \" failed\\n ! mpi_read_file returned %d\\n\\n\", ret );\n goto exit;\n }\n\n rsa.len = ( mpi_msb( &rsa.N ) + 7 ) >> 3;\n\n fclose( f );\n\n /*\n * 3. Initiate the connection\n */\n printf( \"\\n . Connecting to tcp/%s/%d\", SERVER_NAME,\n SERVER_PORT );\n fflush( stdout );\n\n if( ( ret = net_connect( &server_fd, SERVER_NAME,\n SERVER_PORT ) ) != 0 )\n {\n printf( \" failed\\n ! net_connect returned %d\\n\\n\", ret );\n goto exit;\n }\n\n /*\n * 4a. First get the buffer length\n */\n printf( \"\\n . Receiving the server's DH parameters\" );\n fflush( stdout );\n\n memset( buf, 0, sizeof( buf ) );\n\n if( ( ret = net_recv( &server_fd, buf, 2 ) ) != 2 )\n {\n printf( \" failed\\n ! net_recv returned %d\\n\\n\", ret );\n goto exit;\n }\n\n n = buflen = ( buf[0] << 8 ) | buf[1];\n if( buflen < 1 || buflen > sizeof( buf ) )\n {\n printf( \" failed\\n ! Got an invalid buffer length\\n\\n\" );\n goto exit;\n }\n\n /*\n * 4b. Get the DHM parameters: P, G and Ys = G^Xs mod P\n */\n memset( buf, 0, sizeof( buf ) );\n\n if( ( ret = net_recv( &server_fd, buf, n ) ) != (int) n )\n {\n printf( \" failed\\n ! net_recv returned %d\\n\\n\", ret );\n goto exit;\n }\n\n p = buf, end = buf + buflen;\n\n if( ( ret = dhm_read_params( &dhm, &p, end ) ) != 0 )\n {\n printf( \" failed\\n ! dhm_read_params returned %d\\n\\n\", ret );\n goto exit;\n }\n\n if( dhm.len < 64 || dhm.len > 512 )\n {\n ret = 1;\n printf( \" failed\\n ! Invalid DHM modulus size\\n\\n\" );\n goto exit;\n }\n\n /*\n * 5. Check that the server's RSA signature matches\n * the SHA-1 hash of (P,G,Ys)\n */\n printf( \"\\n . Verifying the server's RSA signature\" );\n fflush( stdout );\n\n p += 2;\n\n if( ( n = (size_t) ( end - p ) ) != rsa.len )\n {\n ret = 1;\n printf( \" failed\\n ! Invalid RSA signature size\\n\\n\" );\n goto exit;\n }\n\n sha1( buf, (int)( p - 2 - buf ), hash );\n\n if( ( ret = rsa_pkcs1_verify( &rsa, RSA_PUBLIC, SIG_RSA_SHA1,\n 0, hash, p ) ) != 0 )\n {\n printf( \" failed\\n ! rsa_pkcs1_verify returned %d\\n\\n\", ret );\n goto exit;\n }\n\n /*\n * 6. Send our public value: Yc = G ^ Xc mod P\n */\n printf( \"\\n . Sending own public value to server\" );\n fflush( stdout );\n\n n = dhm.len;\n if( ( ret = dhm_make_public( &dhm, dhm.len, buf, n,\n ctr_drbg_random, &ctr_drbg ) ) != 0 )\n {\n printf( \" failed\\n ! dhm_make_public returned %d\\n\\n\", ret );\n goto exit;\n }\n\n if( ( ret = net_send( &server_fd, buf, n ) ) != (int) n )\n {\n printf( \" failed\\n ! net_send returned %d\\n\\n\", ret );\n goto exit;\n }\n\n /*\n * 7. Derive the shared secret: K = Ys ^ Xc mod P\n */\n printf( \"\\n . Shared secret: \" );\n fflush( stdout );\n\n n = dhm.len;\n if( ( ret = dhm_calc_secret( &dhm, buf, &n ) ) != 0 )\n {\n printf( \" failed\\n ! dhm_calc_secret returned %d\\n\\n\", ret );\n goto exit;\n }\n\n for( n = 0; n < 16; n++ )\n printf( \"%02x\", buf[n] );\n\n /*\n * 8. Setup the AES-256 decryption key\n *\n * This is an overly simplified example; best practice is\n * to hash the shared secret with a random value to derive\n * the keying material for the encryption/decryption keys,\n * IVs and MACs.\n */\n printf( \"...\\n . Receiving and decrypting the ciphertext\" );\n fflush( stdout );\n\n aes_setkey_dec( &aes, buf, 256 );\n\n memset( buf, 0, sizeof( buf ) );\n\n if( ( ret = net_recv( &server_fd, buf, 16 ) ) != 16 )\n {\n printf( \" failed\\n ! net_recv returned %d\\n\\n\", ret );\n goto exit;\n }\n\n aes_crypt_ecb( &aes, AES_DECRYPT, buf, buf );\n buf[16] = '\\0';\n printf( \"\\n . Plaintext is \\\"%s\\\"\\n\\n\", (char *) buf );\n\nexit:\n\n net_close( server_fd );\n rsa_free( &rsa );\n dhm_free( &dhm );\n\n#if defined(_WIN32)\n printf( \" + Press Enter to exit this program.\\n\" );\n fflush( stdout ); getchar();\n#endif\n\n return( ret );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int x509parse_verifycrl(x509_cert *crt, x509_cert *ca,\n x509_crl *crl_list)\n{\n int flags = 0;\n int hash_id;\n unsigned char hash[64];\n\n if( ca == NULL )\n return( flags );\n\n /*\n * TODO: What happens if no CRL is present?\n * Suggestion: Revocation state should be unknown if no CRL is present.\n * For backwards compatibility this is not yet implemented.\n */\n\n while( crl_list != NULL )\n {\n if( crl_list->version == 0 ||\n crl_list->issuer_raw.len != ca->subject_raw.len ||\n memcmp( crl_list->issuer_raw.p, ca->subject_raw.p,\n crl_list->issuer_raw.len ) != 0 )\n {\n crl_list = crl_list->next;\n continue;\n }\n\n /*\n * Check if CRL is correctly signed by the trusted CA\n */\n hash_id = crl_list->sig_alg;\n\n x509_hash( crl_list->tbs.p, crl_list->tbs.len, hash_id, hash );\n\n if( !rsa_pkcs1_verify( &ca->rsa, RSA_PUBLIC, hash_id,\n 0, hash, crl_list->sig.p ) == 0 )\n {\n /*\n * CRL is not trusted\n */\n flags |= BADCRL_NOT_TRUSTED;\n break;\n }\n\n /*\n * Check for validity of CRL (Do not drop out)\n */\n if( x509parse_time_expired( &crl_list->next_update ) )\n flags |= BADCRL_EXPIRED;\n\n /*\n * Check if certificate is revoked\n */\n if( x509parse_revoked(crt, crl_list) )\n {\n flags |= BADCERT_REVOKED;\n break;\n }\n\n crl_list = crl_list->next;\n }\n return flags;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ssl_parse_client_key_exchange( ssl_context *ssl )\n{\n int ret;\n size_t i, n = 0;\n\n SSL_DEBUG_MSG( 2, ( \"=> parse client key exchange\" ) );\n\n if( ( ret = ssl_read_record( ssl ) ) != 0 )\n {\n SSL_DEBUG_RET( 1, \"ssl_read_record\", ret );\n return( ret );\n }\n\n if( ssl->in_msgtype != SSL_MSG_HANDSHAKE )\n {\n SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n }\n\n if( ssl->in_msg[0] != SSL_HS_CLIENT_KEY_EXCHANGE )\n {\n SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n }\n\n if( ssl->session_negotiate->ciphersuite == TLS_DHE_RSA_WITH_DES_CBC_SHA ||\n ssl->session_negotiate->ciphersuite == TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA ||\n ssl->session_negotiate->ciphersuite == TLS_DHE_RSA_WITH_AES_128_CBC_SHA ||\n ssl->session_negotiate->ciphersuite == TLS_DHE_RSA_WITH_AES_256_CBC_SHA ||\n ssl->session_negotiate->ciphersuite == TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 ||\n ssl->session_negotiate->ciphersuite == TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 ||\n ssl->session_negotiate->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA ||\n ssl->session_negotiate->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA ||\n ssl->session_negotiate->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 ||\n ssl->session_negotiate->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 ||\n ssl->session_negotiate->ciphersuite == TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 ||\n ssl->session_negotiate->ciphersuite == TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 )\n {\n#if !defined(POLARSSL_DHM_C)\n SSL_DEBUG_MSG( 1, ( \"support for dhm is not available\" ) );\n return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE );\n#else\n /*\n * Receive G^Y mod P, premaster = (G^Y)^X mod P\n */\n n = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5];\n\n if( n < 1 || n > ssl->handshake->dhm_ctx.len ||\n n + 6 != ssl->in_hslen )\n {\n SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n }\n\n if( ( ret = dhm_read_public( &ssl->handshake->dhm_ctx,\n ssl->in_msg + 6, n ) ) != 0 )\n {\n SSL_DEBUG_RET( 1, \"dhm_read_public\", ret );\n return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_DHM_RP );\n }\n\n SSL_DEBUG_MPI( 3, \"DHM: GY\", &ssl->handshake->dhm_ctx.GY );\n\n ssl->handshake->pmslen = ssl->handshake->dhm_ctx.len;\n\n if( ( ret = dhm_calc_secret( &ssl->handshake->dhm_ctx,\n ssl->handshake->premaster,\n &ssl->handshake->pmslen ) ) != 0 )\n {\n SSL_DEBUG_RET( 1, \"dhm_calc_secret\", ret );\n return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_DHM_CS );\n }\n\n SSL_DEBUG_MPI( 3, \"DHM: K \", &ssl->handshake->dhm_ctx.K );\n#endif\n }\n else\n {\n if( ssl->rsa_key == NULL )\n {\n SSL_DEBUG_MSG( 1, ( \"got no private key\" ) );\n return( POLARSSL_ERR_SSL_PRIVATE_KEY_REQUIRED );\n }\n\n /*\n * Decrypt the premaster using own private RSA key\n */\n i = 4;\n if( ssl->rsa_key )\n n = ssl->rsa_key_len( ssl->rsa_key );\n ssl->handshake->pmslen = 48;\n\n if( ssl->minor_ver != SSL_MINOR_VERSION_0 )\n {\n i += 2;\n if( ssl->in_msg[4] != ( ( n >> 8 ) & 0xFF ) ||\n ssl->in_msg[5] != ( ( n ) & 0xFF ) )\n {\n SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n }\n }\n\n if( ssl->in_hslen != i + n )\n {\n SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n }\n\n if( ssl->rsa_key ) {\n ret = ssl->rsa_decrypt( ssl->rsa_key, RSA_PRIVATE,\n &ssl->handshake->pmslen,\n ssl->in_msg + i,\n ssl->handshake->premaster,\n sizeof(ssl->handshake->premaster) );\n }\n\n if( ret != 0 || ssl->handshake->pmslen != 48 ||\n ssl->handshake->premaster[0] != ssl->max_major_ver ||\n ssl->handshake->premaster[1] != ssl->max_minor_ver )\n {\n SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n\n /*\n * Protection against Bleichenbacher's attack:\n * invalid PKCS#1 v1.5 padding must not cause\n * the connection to end immediately; instead,\n * send a bad_record_mac later in the handshake.\n */\n ssl->handshake->pmslen = 48;\n\n ret = ssl->f_rng( ssl->p_rng, ssl->handshake->premaster,\n ssl->handshake->pmslen );\n if( ret != 0 )\n return( ret );\n }\n }\n\n if( ( ret = ssl_derive_keys( ssl ) ) != 0 )\n {\n SSL_DEBUG_RET( 1, \"ssl_derive_keys\", ret );\n return( ret );\n }\n\n ssl->state++;\n\n SSL_DEBUG_MSG( 2, ( \"<= parse client key exchange\" ) );\n\n return( 0 );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int x509parse_verify_top(\n x509_cert *child, x509_cert *trust_ca,\n x509_crl *ca_crl, int path_cnt, int *flags,\n int (*f_vrfy)(void *, x509_cert *, int, int *),\n void *p_vrfy )\n{\n int hash_id, ret;\n int ca_flags = 0, check_path_cnt = path_cnt + 1;\n unsigned char hash[64];\n\n if( x509parse_time_expired( &child->valid_to ) )\n *flags |= BADCERT_EXPIRED;\n\n /*\n * Child is the top of the chain. Check against the trust_ca list.\n */\n *flags |= BADCERT_NOT_TRUSTED;\n\n while( trust_ca != NULL )\n {\n if( trust_ca->version == 0 ||\n child->issuer_raw.len != trust_ca->subject_raw.len ||\n memcmp( child->issuer_raw.p, trust_ca->subject_raw.p,\n child->issuer_raw.len ) != 0 )\n {\n trust_ca = trust_ca->next;\n continue;\n }\n\n /*\n * Reduce path_len to check against if top of the chain is\n * the same as the trusted CA\n */\n if( child->subject_raw.len == trust_ca->subject_raw.len &&\n memcmp( child->subject_raw.p, trust_ca->subject_raw.p,\n child->issuer_raw.len ) == 0 ) \n {\n check_path_cnt--;\n }\n\n if( trust_ca->max_pathlen > 0 &&\n trust_ca->max_pathlen < check_path_cnt )\n {\n trust_ca = trust_ca->next;\n continue;\n }\n\n hash_id = child->sig_alg;\n\n x509_hash( child->tbs.p, child->tbs.len, hash_id, hash );\n\n if( rsa_pkcs1_verify( &trust_ca->rsa, RSA_PUBLIC, hash_id,\n 0, hash, child->sig.p ) != 0 )\n {\n trust_ca = trust_ca->next;\n continue;\n }\n\n /*\n * Top of chain is signed by a trusted CA\n */\n *flags &= ~BADCERT_NOT_TRUSTED;\n break;\n }\n\n /*\n * If top of chain is not the same as the trusted CA send a verify request\n * to the callback for any issues with validity and CRL presence for the\n * trusted CA certificate.\n */\n if( trust_ca != NULL &&\n ( child->subject_raw.len != trust_ca->subject_raw.len ||\n memcmp( child->subject_raw.p, trust_ca->subject_raw.p,\n child->issuer_raw.len ) != 0 ) )\n {\n /* Check trusted CA's CRL for then chain's top crt */\n *flags |= x509parse_verifycrl( child, trust_ca, ca_crl );\n\n if( x509parse_time_expired( &trust_ca->valid_to ) )\n ca_flags |= BADCERT_EXPIRED;\n\n if( NULL != f_vrfy )\n {\n if( ( ret = f_vrfy( p_vrfy, trust_ca, path_cnt + 1, &ca_flags ) ) != 0 )\n return( ret );\n }\n }\n\n /* Call callback on top cert */\n if( NULL != f_vrfy )\n {\n if( ( ret = f_vrfy(p_vrfy, child, path_cnt, flags ) ) != 0 )\n return( ret );\n }\n\n *flags |= ca_flags;\n\n return( 0 );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int crt_to_pubkey(const gnutls_datum_t *raw_crt, gnutls_datum_t * out)\n{\ngnutls_pubkey_t pub = NULL;\ngnutls_x509_crt_t crt = NULL;\nint ret;\n\n\tout->data = NULL;\n\n\tret = gnutls_x509_crt_init(&crt);\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(DANE_E_PUBKEY_ERROR);\n\n\tret = gnutls_pubkey_init( &pub);\n\tif (ret < 0) {\n\t gnutls_assert();\n\t\tret = DANE_E_PUBKEY_ERROR;\n\t\tgoto cleanup;\n\t}\n\t\t\n\tret = gnutls_x509_crt_import(crt, raw_crt, GNUTLS_X509_FMT_DER);\n\tif (ret < 0) {\n\t gnutls_assert();\n\t\tret = DANE_E_PUBKEY_ERROR;\n\t\tgoto cleanup;\n\t}\n\n\tret = gnutls_pubkey_import_x509(pub, crt, 0);\n\tif (ret < 0) {\n\t gnutls_assert();\n\t\tret = DANE_E_PUBKEY_ERROR;\n\t\tgoto cleanup;\n\t}\n\n\tret = gnutls_pubkey_export2(pub, GNUTLS_X509_FMT_DER, out);\n\tif (ret < 0) {\n\t gnutls_assert();\n\t\tret = DANE_E_PUBKEY_ERROR;\n\t\tgoto cleanup;\n\t}\n\t\n\tret = 0;\n\tgoto clean_certs;\n\ncleanup:\n\tfree(out->data);\n\tout->data = NULL;\nclean_certs:\n\tif (pub)\n\t\tgnutls_pubkey_deinit(pub);\n\tif (crt)\n\t\tgnutls_x509_crt_deinit(crt);\n\n\treturn ret;\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: void* ipc_rcu_alloc(int size)\n{\n\tvoid* out;\n\t/* \n\t * We prepend the allocation with the rcu struct, and\n\t * workqueue if necessary (for vmalloc). \n\t */\n\tif (rcu_use_vmalloc(size)) {\n\t\tout = vmalloc(HDRLEN_VMALLOC + size);\n\t\tif (out) {\n\t\t\tout += HDRLEN_VMALLOC;\n\t\t\tcontainer_of(out, struct ipc_rcu_hdr, data)->is_vmalloc = 1;\n\t\t\tcontainer_of(out, struct ipc_rcu_hdr, data)->refcount = 1;\n\t\t}\n\t} else {\n\t\tout = kmalloc(HDRLEN_KMALLOC + size, GFP_KERNEL);\n\t\tif (out) {\n\t\t\tout += HDRLEN_KMALLOC;\n\t\t\tcontainer_of(out, struct ipc_rcu_hdr, data)->is_vmalloc = 0;\n\t\t\tcontainer_of(out, struct ipc_rcu_hdr, data)->refcount = 1;\n\t\t}\n\t}\n\n\treturn out;\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: SYSCALL_DEFINE4(semtimedop, int, semid, struct sembuf __user *, tsops,\n\t\tunsigned, nsops, const struct timespec __user *, timeout)\n{\n\tint error = -EINVAL;\n\tstruct sem_array *sma;\n\tstruct sembuf fast_sops[SEMOPM_FAST];\n\tstruct sembuf* sops = fast_sops, *sop;\n\tstruct sem_undo *un;\n\tint undos = 0, alter = 0, max;\n\tstruct sem_queue queue;\n\tunsigned long jiffies_left = 0;\n\tstruct ipc_namespace *ns;\n\tstruct list_head tasks;\n\n\tns = current->nsproxy->ipc_ns;\n\n\tif (nsops < 1 || semid < 0)\n\t\treturn -EINVAL;\n\tif (nsops > ns->sc_semopm)\n\t\treturn -E2BIG;\n\tif(nsops > SEMOPM_FAST) {\n\t\tsops = kmalloc(sizeof(*sops)*nsops,GFP_KERNEL);\n\t\tif(sops==NULL)\n\t\t\treturn -ENOMEM;\n\t}\n\tif (copy_from_user (sops, tsops, nsops * sizeof(*tsops))) {\n\t\terror=-EFAULT;\n\t\tgoto out_free;\n\t}\n\tif (timeout) {\n\t\tstruct timespec _timeout;\n\t\tif (copy_from_user(&_timeout, timeout, sizeof(*timeout))) {\n\t\t\terror = -EFAULT;\n\t\t\tgoto out_free;\n\t\t}\n\t\tif (_timeout.tv_sec < 0 || _timeout.tv_nsec < 0 ||\n\t\t\t_timeout.tv_nsec >= 1000000000L) {\n\t\t\terror = -EINVAL;\n\t\t\tgoto out_free;\n\t\t}\n\t\tjiffies_left = timespec_to_jiffies(&_timeout);\n\t}\n\tmax = 0;\n\tfor (sop = sops; sop < sops + nsops; sop++) {\n\t\tif (sop->sem_num >= max)\n\t\t\tmax = sop->sem_num;\n\t\tif (sop->sem_flg & SEM_UNDO)\n\t\t\tundos = 1;\n\t\tif (sop->sem_op != 0)\n\t\t\talter = 1;\n\t}\n\n\tif (undos) {\n\t\tun = find_alloc_undo(ns, semid);\n\t\tif (IS_ERR(un)) {\n\t\t\terror = PTR_ERR(un);\n\t\t\tgoto out_free;\n\t\t}\n\t} else\n\t\tun = NULL;\n\n\tINIT_LIST_HEAD(&tasks);\n\n\trcu_read_lock();\n\tsma = sem_obtain_object_check(ns, semid);\n\tif (IS_ERR(sma)) {\n\t\tif (un)\n\t\t\trcu_read_unlock();\n\t\terror = PTR_ERR(sma);\n\t\tgoto out_free;\n\t}\n\n\terror = -EFBIG;\n\tif (max >= sma->sem_nsems) {\n\t\trcu_read_unlock();\n\t\tgoto out_wakeup;\n\t}\n\n\terror = -EACCES;\n\tif (ipcperms(ns, &sma->sem_perm, alter ? S_IWUGO : S_IRUGO)) {\n\t\trcu_read_unlock();\n\t\tgoto out_wakeup;\n\t}\n\n\terror = security_sem_semop(sma, sops, nsops, alter);\n\tif (error) {\n\t\trcu_read_unlock();\n\t\tgoto out_wakeup;\n\t}\n\n\t/*\n\t * semid identifiers are not unique - find_alloc_undo may have\n\t * allocated an undo structure, it was invalidated by an RMID\n\t * and now a new array with received the same id. Check and fail.\n\t * This case can be detected checking un->semid. The existence of\n\t * \"un\" itself is guaranteed by rcu.\n\t */\n\terror = -EIDRM;\n\tipc_lock_object(&sma->sem_perm);\n\tif (un) {\n\t\tif (un->semid == -1) {\n\t\t\trcu_read_unlock();\n\t\t\tgoto out_unlock_free;\n\t\t} else {\n\t\t\t/*\n\t\t\t * rcu lock can be released, \"un\" cannot disappear:\n\t\t\t * - sem_lock is acquired, thus IPC_RMID is\n\t\t\t * impossible.\n\t\t\t * - exit_sem is impossible, it always operates on\n\t\t\t * current (or a dead task).\n\t\t\t */\n\n\t\t\trcu_read_unlock();\n\t\t}\n\t}\n\n\terror = try_atomic_semop (sma, sops, nsops, un, task_tgid_vnr(current));\n\tif (error <= 0) {\n\t\tif (alter && error == 0)\n\t\t\tdo_smart_update(sma, sops, nsops, 1, &tasks);\n\n\t\tgoto out_unlock_free;\n\t}\n\n\t/* We need to sleep on this operation, so we put the current\n\t * task into the pending queue and go to sleep.\n\t */\n\t\t\n\tqueue.sops = sops;\n\tqueue.nsops = nsops;\n\tqueue.undo = un;\n\tqueue.pid = task_tgid_vnr(current);\n\tqueue.alter = alter;\n\n\tif (nsops == 1) {\n\t\tstruct sem *curr;\n\t\tcurr = &sma->sem_base[sops->sem_num];\n\n\t\tif (alter)\n\t\t\tlist_add_tail(&queue.list, &curr->sem_pending);\n\t\telse\n\t\t\tlist_add(&queue.list, &curr->sem_pending);\n\t} else {\n\t\tif (alter)\n\t\t\tlist_add_tail(&queue.list, &sma->sem_pending);\n\t\telse\n\t\t\tlist_add(&queue.list, &sma->sem_pending);\n\t\tsma->complex_count++;\n\t}\n\n\tqueue.status = -EINTR;\n\tqueue.sleeper = current;\n\nsleep_again:\n\tcurrent->state = TASK_INTERRUPTIBLE;\n\tsem_unlock(sma);\n\n\tif (timeout)\n\t\tjiffies_left = schedule_timeout(jiffies_left);\n\telse\n\t\tschedule();\n\n\terror = get_queue_result(&queue);\n\n\tif (error != -EINTR) {\n\t\t/* fast path: update_queue already obtained all requested\n\t\t * resources.\n\t\t * Perform a smp_mb(): User space could assume that semop()\n\t\t * is a memory barrier: Without the mb(), the cpu could\n\t\t * speculatively read in user space stale data that was\n\t\t * overwritten by the previous owner of the semaphore.\n\t\t */\n\t\tsmp_mb();\n\n\t\tgoto out_free;\n\t}\n\n\tsma = sem_obtain_lock(ns, semid);\n\n\t/*\n\t * Wait until it's guaranteed that no wakeup_sem_queue_do() is ongoing.\n\t */\n\terror = get_queue_result(&queue);\n\n\t/*\n\t * Array removed? If yes, leave without sem_unlock().\n\t */\n\tif (IS_ERR(sma)) {\n\t\tgoto out_free;\n\t}\n\n\n\t/*\n\t * If queue.status != -EINTR we are woken up by another process.\n\t * Leave without unlink_queue(), but with sem_unlock().\n\t */\n\n\tif (error != -EINTR) {\n\t\tgoto out_unlock_free;\n\t}\n\n\t/*\n\t * If an interrupt occurred we have to clean up the queue\n\t */\n\tif (timeout && jiffies_left == 0)\n\t\terror = -EAGAIN;\n\n\t/*\n\t * If the wakeup was spurious, just retry\n\t */\n\tif (error == -EINTR && !signal_pending(current))\n\t\tgoto sleep_again;\n\n\tunlink_queue(sma, &queue);\n\nout_unlock_free:\n\tsem_unlock(sma);\nout_wakeup:\n\twake_up_sem_queue_do(&tasks);\nout_free:\n\tif(sops != fast_sops)\n\t\tkfree(sops);\n\treturn error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'ipc,sem: fine grained locking for semtimedop\n\nIntroduce finer grained locking for semtimedop, to handle the common case\nof a program wanting to manipulate one semaphore from an array with\nmultiple semaphores.\n\nIf the call is a semop manipulating just one semaphore in an array with\nmultiple semaphores, only take the lock for that semaphore itself.\n\nIf the call needs to manipulate multiple semaphores, or another caller is\nin a transaction that manipulates multiple semaphores, the sem_array lock\nis taken, as well as all the locks for the individual semaphores.\n\nOn a 24 CPU system, performance numbers with the semop-multi\ntest with N threads and N semaphores, look like this:\n\n\tvanilla\t\tDavidlohr's\tDavidlohr's +\tDavidlohr's +\nthreads\t\t\tpatches\t\trwlock patches\tv3 patches\n10\t610652\t\t726325\t\t1783589\t\t2142206\n20\t341570\t\t365699\t\t1520453\t\t1977878\n30\t288102\t\t307037\t\t1498167\t\t2037995\n40\t290714\t\t305955\t\t1612665\t\t2256484\n50\t288620\t\t312890\t\t1733453\t\t2650292\n60\t289987\t\t306043\t\t1649360\t\t2388008\n70\t291298\t\t306347\t\t1723167\t\t2717486\n80\t290948\t\t305662\t\t1729545\t\t2763582\n90\t290996\t\t306680\t\t1736021\t\t2757524\n100\t292243\t\t306700\t\t1773700\t\t3059159\n\n[davidlohr.bueso@hp.com: do not call sem_lock when bogus sma]\n[davidlohr.bueso@hp.com: make refcounter atomic]\nSigned-off-by: Rik van Riel \nSuggested-by: Linus Torvalds \nAcked-by: Davidlohr Bueso \nCc: Chegu Vinod \nCc: Jason Low \nReviewed-by: Michel Lespinasse \nCc: Peter Hurley \nCc: Stanislav Kinsbursky \nTested-by: Emmanuel Benisty \nTested-by: Sedat Dilek \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int client_func(const test_param_t *test)\n{\n\tstruct gg_session *gs;\n\tstruct gg_login_params glp;\n\tchar tmp;\n\n\tgg_proxy_host = HOST_PROXY;\n\tgg_proxy_port = 8080;\n\tgg_proxy_enabled = test->proxy_mode;\n\n\tmemset(&glp, 0, sizeof(glp));\n\tglp.uin = 1;\n\tglp.password = \"dupa.8\";\n\tglp.async = test->async_mode;\n\tglp.resolver = GG_RESOLVER_PTHREAD;\n\n\tif (test->server)\n\t\tglp.server_addr = inet_addr(HOST_LOCAL);\n\n\tif (test->ssl_mode)\n\t\tglp.tls = GG_SSL_REQUIRED;\n\n\twhile (read(timeout_pipe[0], &tmp, 1) != -1);\n\n\tgs = gg_login(&glp);\n\n\tif (gs == NULL)\n\t\treturn 0;\n\n\tif (!test->async_mode) {\n\t\tgg_free_session(gs);\n\t\treturn 1;\n\t} else {\n\t\tfor (;;) {\n\t\t\tfd_set rd, wr;\n\t\t\tint res;\n\t\t\tint max_fd;\n\t\t\tstruct timeval *tv_ptr = NULL;\n\n#ifdef CLIENT_TIMEOUT\n\t\t\tstruct timeval tv;\n\n\t\t\ttv.tv_sec = CLIENT_TIMEOUT;\n\t\t\ttv.tv_usec = 0;\n\t\t\ttv_ptr = &tv;\n#endif\n\n\t\t\tFD_ZERO(&rd);\n\t\t\tFD_ZERO(&wr);\n\n\t\t\tmax_fd = timeout_pipe[0];\n\n\t\t\tif (gs->fd > max_fd)\n\t\t\t\tmax_fd = gs->fd;\n\n\t\t\tFD_SET(timeout_pipe[0], &rd);\n\n\t\t\tif ((gs->check & GG_CHECK_READ))\n\t\t\t\tFD_SET(gs->fd, &rd);\n\n\t\t\tif ((gs->check & GG_CHECK_WRITE))\n\t\t\t\tFD_SET(gs->fd, &wr);\n\n\t\t\tres = select(max_fd + 1, &rd, &wr, NULL, tv_ptr);\n\n\t\t\tif (res == 0) {\n\t\t\t\tdebug(\"Test timeout\\n\");\n\t\t\t\tgg_free_session(gs);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\t\n\t\t\tif (res == -1 && errno != EINTR) {\n\t\t\t\tdebug(\"select() failed: %s\\n\", strerror(errno));\n\t\t\t\tgg_free_session(gs);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif (res == -1)\n\t\t\t\tcontinue;\n\n\t\t\tif (FD_ISSET(timeout_pipe[0], &rd)) {\n\t\t\t\tif (read(timeout_pipe[0], &tmp, 1) != 1) {\n\t\t\t\t\tdebug(\"Test error\\n\");\n\t\t\t\t\tgg_free_session(gs);\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\n\t\t\t\tif (!gs->soft_timeout) {\n\t\t\t\t\tdebug(\"Hard timeout\\n\");\n\t\t\t\t\tgg_free_session(gs);\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (FD_ISSET(gs->fd, &rd) || FD_ISSET(gs->fd, &wr) || (FD_ISSET(timeout_pipe[0], &rd) && gs->soft_timeout)) {\n\t\t\t\tstruct gg_event *ge;\n\t\t\t\t\n\t\t\t\tif (FD_ISSET(timeout_pipe[0], &rd)) {\n\t\t\t\t\tdebug(\"Soft timeout\\n\");\n\t\t\t\t\tgs->timeout = 0;\n\t\t\t\t}\n\t\t\n\t\t\t\tge = gg_watch_fd(gs);\n\n\t\t\t\tif (!ge) {\n\t\t\t\t\tdebug(\"gg_watch_fd() failed\\n\");\n\t\t\t\t\tgg_free_session(gs);\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\n\t\t\t\tswitch (ge->type) {\n\t\t\t\t\tcase GG_EVENT_CONN_SUCCESS:\n\t\t\t\t\t\tgg_event_free(ge);\n\t\t\t\t\t\tgg_free_session(gs);\n\t\t\t\t\t\treturn 1;\n\n\t\t\t\t\tcase GG_EVENT_CONN_FAILED:\n\t\t\t\t\t\tgg_event_free(ge);\n\t\t\t\t\t\tgg_free_session(gs);\n\t\t\t\t\t\treturn 0;\n\n\t\t\t\t\tcase GG_EVENT_NONE:\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tdebug(\"Unknown event %d\\n\", ge->type);\n\t\t\t\t\t\tgg_event_free(ge);\n\t\t\t\t\t\tgg_free_session(gs);\n\t\t\t\t\t\treturn -1;\n\t\t\t\t}\n\n\t\t\t\tgg_event_free(ge);\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-310'], 'message': 'Odk\u0105d biblioteka weryfikuje certyfikaty ci\u0119\u017cko testowa\u0107 z self-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: find_referral_tgs(kdc_realm_t *kdc_active_realm, krb5_kdc_req *request,\n krb5_principal *krbtgt_princ)\n{\n krb5_error_code retval = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;\n char **realms = NULL, *hostname = NULL;\n krb5_data srealm = request->server->realm;\n\n if (!is_referral_req(kdc_active_realm, request))\n goto cleanup;\n\n hostname = data2string(krb5_princ_component(kdc_context,\n request->server, 1));\n if (hostname == NULL) {\n retval = ENOMEM;\n goto cleanup;\n }\n /* If the hostname doesn't contain a '.', it's not a FQDN. */\n if (strchr(hostname, '.') == NULL)\n goto cleanup;\n retval = krb5_get_host_realm(kdc_context, hostname, &realms);\n if (retval) {\n /* no match found */\n kdc_err(kdc_context, retval, \"unable to find realm of host\");\n goto cleanup;\n }\n /* Don't return a referral to the empty realm or the service realm. */\n if (realms == NULL || realms[0] == '\\0' ||\n data_eq_string(srealm, realms[0])) {\n retval = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;\n goto cleanup;\n }\n retval = krb5_build_principal(kdc_context, krbtgt_princ,\n srealm.length, srealm.data,\n \"krbtgt\", realms[0], (char *)0);\ncleanup:\n krb5_free_host_realm(kdc_context, realms);\n free(hostname);\n\n return retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'KDC null deref due to referrals [CVE-2013-1417]\n\nAn authenticated remote client can cause a KDC to crash by making a\nvalid TGS-REQ to a KDC serving a realm with a single-component name.\nThe process_tgs_req() function dereferences a null pointer because an\nunusual failure condition causes a helper function to return success.\n\nWhile attempting to provide cross-realm referrals for host-based\nservice principals, the find_referral_tgs() function could return a\nTGS principal for a zero-length realm name (indicating that the\nhostname in the service principal has no known realm associated with\nit).\n\nSubsequently, the find_alternate_tgs() function would attempt to\nconstruct a path to this empty-string realm, and return success along\nwith a null pointer in its output parameter. This happens because\nkrb5_walk_realm_tree() returns a list of length one when it attempts\nto construct a transit path between a single-component realm and the\nempty-string realm. This list causes a loop in find_alternate_tgs()\nto iterate over zero elements, resulting in the unexpected output of a\nnull pointer, which process_tgs_req() proceeds to dereference because\nthere is no error condition.\n\nAdd an error condition to find_referral_tgs() when\nkrb5_get_host_realm() returns an empty realm name. Also add an error\ncondition to find_alternate_tgs() to handle the length-one output from\nkrb5_walk_realm_tree().\n\nThe vulnerable configuration is not likely to arise in practice.\n(Realm names that have a single component are likely to be test\nrealms.) Releases prior to krb5-1.11 are not vulnerable.\n\nThanks to Sol Jerome for reporting this problem.\n\nCVSSv2: AV:N/AC:M/Au:S/C:N/I:N/A:P/E:H/RL:O/RC:C\n\n(cherry picked from commit 3c7f1c21ffaaf6c90f1045f0f5440303c766acc0)\n\nticket: 7668\nversion_fixed: 1.11.4\nstatus: resolved'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: unsigned long lh_char_hash(const void *k)\n{\n\tunsigned int h = 0;\n\tconst char* data = (const char*)k;\n \n\twhile( *data!=0 ) h = h*129 + (unsigned int)(*data++) + LH_PRIME;\n\n\treturn h;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-310'], 'message': 'Patch to address the following issues:\n\n* CVE-2013-6371: hash collision denial of service\n* CVE-2013-6370: buffer overflow if size_t is larger than int'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void *hashtable_get(hashtable_t *hashtable, const char *key)\n{\n pair_t *pair;\n size_t hash;\n bucket_t *bucket;\n\n hash = hash_str(key);\n bucket = &hashtable->buckets[hash % num_buckets(hashtable)];\n\n pair = hashtable_find_pair(hashtable, bucket, key, hash);\n if(!pair)\n return NULL;\n\n return pair->value;\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 read_conf(FILE *conffile)\n{\n char *buffer, *line, *val;\n\n buffer = loadfile(conffile);\n for (line = strtok(buffer, \"\\r\\n\"); line; line = strtok(NULL, \"\\r\\n\")) {\n if (!strncmp(line, \"export \", 7))\n continue;\n val = strchr(line, '=');\n if (!val) {\n printf(\"invalid configuration line\\n\");\n break;\n }\n *val++ = '\\0';\n\n if (!strcmp(line, \"JSON_INDENT\"))\n conf.indent = atoi(val);\n if (!strcmp(line, \"JSON_COMPACT\"))\n conf.compact = atoi(val);\n if (!strcmp(line, \"JSON_ENSURE_ASCII\"))\n conf.ensure_ascii = atoi(val);\n if (!strcmp(line, \"JSON_PRESERVE_ORDER\"))\n conf.preserve_order = atoi(val);\n if (!strcmp(line, \"JSON_SORT_KEYS\"))\n conf.sort_keys = atoi(val);\n if (!strcmp(line, \"STRIP\"))\n conf.strip = atoi(val);\n }\n\n free(buffer);\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 early_init_amd(struct cpuinfo_x86 *c)\n{\n\tearly_init_amd_mc(c);\n\n\t/*\n\t * c->x86_power is 8000_0007 edx. Bit 8 is TSC runs at constant rate\n\t * with P/T states and does not stop in deep C-states\n\t */\n\tif (c->x86_power & (1 << 8)) {\n\t\tset_cpu_cap(c, X86_FEATURE_CONSTANT_TSC);\n\t\tset_cpu_cap(c, X86_FEATURE_NONSTOP_TSC);\n\t\tif (!check_tsc_unstable())\n\t\t\tsched_clock_stable = 1;\n\t}\n\n#ifdef CONFIG_X86_64\n\tset_cpu_cap(c, X86_FEATURE_SYSCALL32);\n#else\n\t/* Set MTRR capability flag if appropriate */\n\tif (c->x86 == 5)\n\t\tif (c->x86_model == 13 || c->x86_model == 9 ||\n\t\t (c->x86_model == 8 && c->x86_mask >= 8))\n\t\t\tset_cpu_cap(c, X86_FEATURE_K6_MTRR);\n#endif\n#if defined(CONFIG_X86_LOCAL_APIC) && defined(CONFIG_PCI)\n\t/* check CPU config space for extended APIC ID */\n\tif (cpu_has_apic && c->x86 >= 0xf) {\n\t\tunsigned int val;\n\t\tval = read_pci_config(0, 24, 0, 0x68);\n\t\tif ((val & ((1 << 17) | (1 << 18))) == ((1 << 17) | (1 << 18)))\n\t\t\tset_cpu_cap(c, X86_FEATURE_EXTD_APICID);\n\t}\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'x86, cpu, amd: Add workaround for family 16h, erratum 793\n\nThis adds the workaround for erratum 793 as a precaution in case not\nevery BIOS implements it. This addresses CVE-2013-6885.\n\nErratum text:\n\n[Revision Guide for AMD Family 16h Models 00h-0Fh Processors,\ndocument 51810 Rev. 3.04 November 2013]\n\n793 Specific Combination of Writes to Write Combined Memory Types and\nLocked Instructions May Cause Core Hang\n\nDescription\n\nUnder a highly specific and detailed set of internal timing\nconditions, a locked instruction may trigger a timing sequence whereby\nthe write to a write combined memory type is not flushed, causing the\nlocked instruction to stall indefinitely.\n\nPotential Effect on System\n\nProcessor core hang.\n\nSuggested Workaround\n\nBIOS should set MSR\nC001_1020[15] = 1b.\n\nFix Planned\n\nNo fix planned\n\n[ hpa: updated description, fixed typo in MSR name ]\n\nSigned-off-by: Borislav Petkov \nLink: http://lkml.kernel.org/r/20140114230711.GS29865@pd.tnic\nTested-by: Aravind Gopalakrishnan \nSigned-off-by: H. Peter Anvin '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int dummy_ipv6_recv_error(struct sock *sk, struct msghdr *msg, int len)\n{\n\treturn -EAFNOSUPPORT;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'inet: fix addr_len/msg->msg_namelen assignment in recv_error and rxpmtu functions\n\nCommit bceaa90240b6019ed73b49965eac7d167610be69 (\"inet: prevent leakage\nof uninitialized memory to user in recv syscalls\") conditionally updated\naddr_len if the msg_name is written to. The recv_error and rxpmtu\nfunctions relied on the recvmsg functions to set up addr_len before.\n\nAs this does not happen any more we have to pass addr_len to those\nfunctions as well and set it to the size of the corresponding sockaddr\nlength.\n\nThis broke traceroute and such.\n\nFixes: bceaa90240b6 (\"inet: prevent leakage of uninitialized memory to user in recv syscalls\")\nReported-by: Brad Spengler \nReported-by: Tom Labanowski\nCc: mpb \nCc: David S. Miller \nCc: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static bool winbind_name_list_to_sid_string_list(struct pwb_context *ctx,\n\t\t\t\t\t\t const char *user,\n\t\t\t\t\t\t const char *name_list,\n\t\t\t\t\t\t char *sid_list_buffer,\n\t\t\t\t\t\t int sid_list_buffer_size)\n{\n\tbool result = false;\n\tchar *current_name = NULL;\n\tconst char *search_location;\n\tconst char *comma;\n\tint len;\n\n\tif (sid_list_buffer_size > 0) {\n\t\tsid_list_buffer[0] = 0;\n\t}\n\n\tsearch_location = name_list;\n\twhile ((comma = strchr(search_location, ',')) != NULL) {\n\t\tcurrent_name = strndup(search_location,\n\t\t\t\t comma - search_location);\n\t\tif (NULL == current_name) {\n\t\t\tgoto out;\n\t\t}\n\n\t\tif (!winbind_name_to_sid_string(ctx, user,\n\t\t\t\t\t\tcurrent_name,\n\t\t\t\t\t\tsid_list_buffer,\n\t\t\t\t\t\tsid_list_buffer_size)) {\n\t\t\t/*\n\t\t\t * If one group name failed, we must not fail\n\t\t\t * the authentication totally, continue with\n\t\t\t * the following group names. If user belongs to\n\t\t\t * one of the valid groups, we must allow it\n\t\t\t * login. -- BoYang\n\t\t\t */\n\n\t\t\t_pam_log(ctx, LOG_INFO, \"cannot convert group %s to sid, \"\n\t\t\t\t \"check if group %s is valid group.\", current_name,\n\t\t\t\t current_name);\n\t\t\t_make_remark_format(ctx, PAM_TEXT_INFO, _(\"Cannot convert group %s \"\n\t\t\t\t\t\"to sid, please contact your administrator to see \"\n\t\t\t\t\t\"if group %s is valid.\"), current_name, current_name);\n\t\t\tSAFE_FREE(current_name);\n\t\t\tsearch_location = comma + 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tSAFE_FREE(current_name);\n\n\t\tif (!safe_append_string(sid_list_buffer, \",\",\n\t\t\t\t\tsid_list_buffer_size)) {\n\t\t\tgoto out;\n\t\t}\n\n\t\tsearch_location = comma + 1;\n\t}\n\n\tif (!winbind_name_to_sid_string(ctx, user, search_location,\n\t\t\t\t\tsid_list_buffer,\n\t\t\t\t\tsid_list_buffer_size)) {\n\t\t_pam_log(ctx, LOG_INFO, \"cannot convert group %s to sid, \"\n\t\t\t \"check if group %s is valid group.\", search_location,\n\t\t\t search_location);\n\t\t_make_remark_format(ctx, PAM_TEXT_INFO, _(\"Cannot convert group %s \"\n\t\t\t\t\"to sid, please contact your administrator to see \"\n\t\t\t\t\"if group %s is valid.\"), search_location, search_location);\n\t\t/*\n\t\t * The lookup of the last name failed..\n\t\t * It results in require_member_of_sid ends with ','\n\t\t * It is malformated parameter here, overwrite the last ','.\n\t\t */\n\t\tlen = strlen(sid_list_buffer);\n\t\tif ((len != 0) && (sid_list_buffer[len - 1] == ',')) {\n\t\t\tsid_list_buffer[len - 1] = '\\0';\n\t\t}\n\t}\n\n\tresult = true;\n\nout:\n\tSAFE_FREE(current_name);\n\treturn result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'fail authentication for single group name which cannot be converted to sid\n\nfurthermore if more than one name is supplied and no sid is converted\nthen also fail.\n\nBug: https://bugzilla.samba.org/show_bug.cgi?id=8598\n\nSigned-off-by: Noel Power \nReviewed-by: Andreas Schneider \nReviewed-by: David Disseldorp \n\nAutobuild-User(master): David Disseldorp \nAutobuild-Date(master): Fri Nov 29 15:45:11 CET 2013 on sn-devel-104'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void init_sasl_conn(conn *c) {\n assert(c);\n /* should something else be returned? */\n if (!settings.sasl)\n return;\n\n if (!c->sasl_conn) {\n int result=sasl_server_new(\"memcached\",\n NULL,\n my_sasl_hostname[0] ? my_sasl_hostname : NULL,\n NULL, NULL,\n NULL, 0, &c->sasl_conn);\n if (result != SASL_OK) {\n if (settings.verbose) {\n fprintf(stderr, \"Failed to initialize SASL conn.\\n\");\n }\n c->sasl_conn = NULL;\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287'], 'message': 'explicitly record sasl auth states\n\nIt was previously possible to bypass authentication due to implicit\nstate management. Now we explicitly consider ourselves\nunauthenticated on any new connections and authentication attempts.\n\nbug316\n\nSigned-off-by: Dustin Sallings '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool BSONObj::valid() const {\n int mySize = objsize();\n\n try {\n BSONObjIterator it(*this);\n while( it.moreWithEOO() ) {\n // both throw exception on failure\n BSONElement e = it.next(true);\n if ( e.size() >= mySize )\n return false;\n\n e.validate();\n\n if (e.eoo()) {\n if (it.moreWithEOO())\n return false;\n return true;\n }\n else if (e.isABSONObj()) {\n if(!e.embeddedObject().valid())\n return false;\n }\n else if (e.type() == CodeWScope) {\n if(!e.codeWScopeObject().valid())\n return false;\n }\n }\n }\n catch (...) {\n }\n return false;\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: QueryParamsTest()\n : cxxtools::unit::TestSuite(\"queryparams\")\n {\n registerMethod(\"testQueryParams\", *this, &QueryParamsTest::testQueryParams);\n registerMethod(\"testCopy\", *this, &QueryParamsTest::testCopy);\n registerMethod(\"testParseUrl\", *this, &QueryParamsTest::testParseUrl);\n registerMethod(\"testParseUrlSpecialChar\", *this, &QueryParamsTest::testParseUrlSpecialChar);\n registerMethod(\"testCount\", *this, &QueryParamsTest::testCount);\n registerMethod(\"testCombine\", *this, &QueryParamsTest::testCombine);\n registerMethod(\"testIterator\", *this, &QueryParamsTest::testIterator);\n registerMethod(\"testGetUrl\", *this, &QueryParamsTest::testGetUrl);\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: static Bigint * Balloc(int k)\n{\n\tint x;\n\tBigint *rv;\n\n\t_THREAD_PRIVATE_MUTEX_LOCK(dtoa_mutex);\n\tif ((rv = freelist[k])) {\n\t\tfreelist[k] = rv->next;\n\t} else {\n\t\tx = 1 << k;\n\t\trv = (Bigint *)MALLOC(sizeof(Bigint) + (x-1)*sizeof(Long));\n\t\trv->k = k;\n\t\trv->maxwds = x;\n\t}\n\t_THREAD_PRIVATE_MUTEX_UNLOCK(dtoa_mutex);\n\trv->sign = rv->wds = 0;\n\treturn rv;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Added missing allocation 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: PHP_FUNCTION(imageaffinematrixget)\n{\n\tdouble affine[6];\n\tlong type;\n\tzval *options;\n\tzval **tmp;\n\tint res = GD_FALSE, i;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"l|z\", &type, &options) == FAILURE) {\n\t\treturn;\n\t}\n\n\tswitch((gdAffineStandardMatrix)type) {\n\t\tcase GD_AFFINE_TRANSLATE:\n\t\tcase GD_AFFINE_SCALE: {\n\t\t\tdouble x, y;\n\t\t\tif (Z_TYPE_P(options) != IS_ARRAY) {\n\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Array expected as options\");\n\t\t\t}\n\t\t\tif (zend_hash_find(HASH_OF(options), \"x\", sizeof(\"x\"), (void **)&tmp) != FAILURE) {\n\t\t\t\tconvert_to_double_ex(tmp);\n\t\t\t\tx = Z_DVAL_PP(tmp);\n\t\t\t} else {\n\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Missing x position\");\n\t\t\t\tRETURN_FALSE;\n\t\t\t}\n\n\t\t\tif (zend_hash_find(HASH_OF(options), \"y\", sizeof(\"y\"), (void **)&tmp) != FAILURE) {\n\t\t\t\tconvert_to_double_ex(tmp);\n\t\t\t\ty = Z_DVAL_PP(tmp);\n\t\t\t} else {\n\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Missing y position\");\n\t\t\t\tRETURN_FALSE;\n\t\t\t}\n\t\t\t\n\t\t\tif (type == GD_AFFINE_TRANSLATE) {\n\t\t\t\tres = gdAffineTranslate(affine, x, y);\n\t\t\t} else {\n\t\t\t\tres = gdAffineScale(affine, x, y);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tcase GD_AFFINE_ROTATE:\n\t\tcase GD_AFFINE_SHEAR_HORIZONTAL:\n\t\tcase GD_AFFINE_SHEAR_VERTICAL: {\n\t\t\tdouble angle;\n\n\t\t\tconvert_to_double_ex(&options);\n\t\t\tangle = Z_DVAL_P(options);\n\n\t\t\tif (type == GD_AFFINE_SHEAR_HORIZONTAL) {\n\t\t\t\tres = gdAffineShearHorizontal(affine, angle);\n\t\t\t} else if (type == GD_AFFINE_SHEAR_VERTICAL) {\n\t\t\t\tres = gdAffineShearVertical(affine, angle);\n\t\t\t} else {\n\t\t\t\tres = gdAffineRotate(affine, angle);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tdefault:\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Invalid type for element %li\", type);\n\t\t\tRETURN_FALSE;\n\t}\n\n\tif (res == GD_FALSE) {\n\t\tRETURN_FALSE;\n\t} else {\n\t\tarray_init(return_value);\n\t\tfor (i = 0; i < 6; i++) {\n\t\t\tadd_index_double(return_value, i, affine[i]);\n\t\t}\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: plpython2_validator(PG_FUNCTION_ARGS)\n{\n\treturn plpython_validator(fcinfo);\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: _outConstraint(StringInfo str, const Constraint *node)\n{\n\tWRITE_NODE_TYPE(\"CONSTRAINT\");\n\n\tWRITE_STRING_FIELD(conname);\n\tWRITE_BOOL_FIELD(deferrable);\n\tWRITE_BOOL_FIELD(initdeferred);\n\tWRITE_LOCATION_FIELD(location);\n\n\tappendStringInfoString(str, \" :contype \");\n\tswitch (node->contype)\n\t{\n\t\tcase CONSTR_NULL:\n\t\t\tappendStringInfoString(str, \"NULL\");\n\t\t\tbreak;\n\n\t\tcase CONSTR_NOTNULL:\n\t\t\tappendStringInfoString(str, \"NOT_NULL\");\n\t\t\tbreak;\n\n\t\tcase CONSTR_DEFAULT:\n\t\t\tappendStringInfoString(str, \"DEFAULT\");\n\t\t\tWRITE_NODE_FIELD(raw_expr);\n\t\t\tWRITE_STRING_FIELD(cooked_expr);\n\t\t\tbreak;\n\n\t\tcase CONSTR_CHECK:\n\t\t\tappendStringInfoString(str, \"CHECK\");\n\t\t\tWRITE_BOOL_FIELD(is_no_inherit);\n\t\t\tWRITE_NODE_FIELD(raw_expr);\n\t\t\tWRITE_STRING_FIELD(cooked_expr);\n\t\t\tbreak;\n\n\t\tcase CONSTR_PRIMARY:\n\t\t\tappendStringInfoString(str, \"PRIMARY_KEY\");\n\t\t\tWRITE_NODE_FIELD(keys);\n\t\t\tWRITE_NODE_FIELD(options);\n\t\t\tWRITE_STRING_FIELD(indexname);\n\t\t\tWRITE_STRING_FIELD(indexspace);\n\t\t\t/* access_method and where_clause not currently used */\n\t\t\tbreak;\n\n\t\tcase CONSTR_UNIQUE:\n\t\t\tappendStringInfoString(str, \"UNIQUE\");\n\t\t\tWRITE_NODE_FIELD(keys);\n\t\t\tWRITE_NODE_FIELD(options);\n\t\t\tWRITE_STRING_FIELD(indexname);\n\t\t\tWRITE_STRING_FIELD(indexspace);\n\t\t\t/* access_method and where_clause not currently used */\n\t\t\tbreak;\n\n\t\tcase CONSTR_EXCLUSION:\n\t\t\tappendStringInfoString(str, \"EXCLUSION\");\n\t\t\tWRITE_NODE_FIELD(exclusions);\n\t\t\tWRITE_NODE_FIELD(options);\n\t\t\tWRITE_STRING_FIELD(indexname);\n\t\t\tWRITE_STRING_FIELD(indexspace);\n\t\t\tWRITE_STRING_FIELD(access_method);\n\t\t\tWRITE_NODE_FIELD(where_clause);\n\t\t\tbreak;\n\n\t\tcase CONSTR_FOREIGN:\n\t\t\tappendStringInfoString(str, \"FOREIGN_KEY\");\n\t\t\tWRITE_NODE_FIELD(pktable);\n\t\t\tWRITE_NODE_FIELD(fk_attrs);\n\t\t\tWRITE_NODE_FIELD(pk_attrs);\n\t\t\tWRITE_CHAR_FIELD(fk_matchtype);\n\t\t\tWRITE_CHAR_FIELD(fk_upd_action);\n\t\t\tWRITE_CHAR_FIELD(fk_del_action);\n\t\t\tWRITE_NODE_FIELD(old_conpfeqop);\n\t\t\tWRITE_BOOL_FIELD(skip_validation);\n\t\t\tWRITE_BOOL_FIELD(initially_valid);\n\t\t\tbreak;\n\n\t\tcase CONSTR_ATTR_DEFERRABLE:\n\t\t\tappendStringInfoString(str, \"ATTR_DEFERRABLE\");\n\t\t\tbreak;\n\n\t\tcase CONSTR_ATTR_NOT_DEFERRABLE:\n\t\t\tappendStringInfoString(str, \"ATTR_NOT_DEFERRABLE\");\n\t\t\tbreak;\n\n\t\tcase CONSTR_ATTR_DEFERRED:\n\t\t\tappendStringInfoString(str, \"ATTR_DEFERRED\");\n\t\t\tbreak;\n\n\t\tcase CONSTR_ATTR_IMMEDIATE:\n\t\t\tappendStringInfoString(str, \"ATTR_IMMEDIATE\");\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tappendStringInfo(str, \"\",\n\t\t\t\t\t\t\t (int) node->contype);\n\t\t\tbreak;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'Avoid repeated name lookups during table and index DDL.\n\nIf the name lookups come to different conclusions due to concurrent\nactivity, we might perform some parts of the DDL on a different table\nthan other parts. At least in the case of CREATE INDEX, this can be\nused to cause the permissions checks to be performed against a\ndifferent table than the index creation, allowing for a privilege\nescalation attack.\n\nThis changes the calling convention for DefineIndex, CreateTrigger,\ntransformIndexStmt, transformAlterTableStmt, CheckIndexCompatible\n(in 9.2 and newer), and AlterTable (in 9.1 and older). In addition,\nCheckRelationOwnership is removed in 9.2 and newer and the calling\nconvention is changed in older branches. A field has also been added\nto the Constraint node (FkConstraint in 8.4). Third-party code calling\nthese functions or using the Constraint node will require updating.\n\nReport by Andres Freund. Patch by Robert Haas and Andres Freund,\nreviewed by Tom Lane.\n\nSecurity: CVE-2014-0062'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)\n{\n\tObjectAddress obj;\n\tListCell *def_item;\n\tListCell *oid_item;\n\n\t/*\n\t * Re-parse the index and constraint definitions, and attach them to the\n\t * appropriate work queue entries.\tWe do this before dropping because in\n\t * the case of a FOREIGN KEY constraint, we might not yet have exclusive\n\t * lock on the table the constraint is attached to, and we need to get\n\t * that before dropping. It's safe because the parser won't actually look\n\t * at the catalogs to detect the existing entry.\n\t */\n\tforboth(oid_item, tab->changedConstraintOids,\n\t\t\tdef_item, tab->changedConstraintDefs)\n\t\tATPostAlterTypeParse(lfirst_oid(oid_item), (char *) lfirst(def_item),\n\t\t\t\t\t\t\t wqueue, lockmode, tab->rewrite);\n\tforboth(oid_item, tab->changedIndexOids,\n\t\t\tdef_item, tab->changedIndexDefs)\n\t\tATPostAlterTypeParse(lfirst_oid(oid_item), (char *) lfirst(def_item),\n\t\t\t\t\t\t\t wqueue, lockmode, tab->rewrite);\n\n\t/*\n\t * Now we can drop the existing constraints and indexes --- constraints\n\t * first, since some of them might depend on the indexes. In fact, we\n\t * have to delete FOREIGN KEY constraints before UNIQUE constraints, but\n\t * we already ordered the constraint list to ensure that would happen. It\n\t * should be okay to use DROP_RESTRICT here, since nothing else should be\n\t * depending on these objects.\n\t */\n\tforeach(oid_item, tab->changedConstraintOids)\n\t{\n\t\tobj.classId = ConstraintRelationId;\n\t\tobj.objectId = lfirst_oid(oid_item);\n\t\tobj.objectSubId = 0;\n\t\tperformDeletion(&obj, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);\n\t}\n\n\tforeach(oid_item, tab->changedIndexOids)\n\t{\n\t\tobj.classId = RelationRelationId;\n\t\tobj.objectId = lfirst_oid(oid_item);\n\t\tobj.objectSubId = 0;\n\t\tperformDeletion(&obj, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);\n\t}\n\n\t/*\n\t * The objects will get recreated during subsequent passes over the work\n\t * queue.\n\t */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'Avoid repeated name lookups during table and index DDL.\n\nIf the name lookups come to different conclusions due to concurrent\nactivity, we might perform some parts of the DDL on a different table\nthan other parts. At least in the case of CREATE INDEX, this can be\nused to cause the permissions checks to be performed against a\ndifferent table than the index creation, allowing for a privilege\nescalation attack.\n\nThis changes the calling convention for DefineIndex, CreateTrigger,\ntransformIndexStmt, transformAlterTableStmt, CheckIndexCompatible\n(in 9.2 and newer), and AlterTable (in 9.1 and older). In addition,\nCheckRelationOwnership is removed in 9.2 and newer and the calling\nconvention is changed in older branches. A field has also been added\nto the Constraint node (FkConstraint in 8.4). Third-party code calling\nthese functions or using the Constraint node will require updating.\n\nReport by Andres Freund. Patch by Robert Haas and Andres Freund,\nreviewed by Tom Lane.\n\nSecurity: CVE-2014-0062'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: queryin(char *buf)\n{\n\tQPRS_STATE\tstate;\n\tint32\t\ti;\n\tltxtquery *query;\n\tint32\t\tcommonlen;\n\tITEM\t *ptr;\n\tNODE\t *tmp;\n\tint32\t\tpos = 0;\n\n#ifdef BS_DEBUG\n\tchar\t\tpbuf[16384],\n\t\t\t *cur;\n#endif\n\n\t/* init state */\n\tstate.buf = buf;\n\tstate.state = WAITOPERAND;\n\tstate.count = 0;\n\tstate.num = 0;\n\tstate.str = NULL;\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);\n\tif (!state.num)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_SYNTAX_ERROR),\n\t\t\t\t errmsg(\"syntax error\"),\n\t\t\t\t errdetail(\"Empty query.\")));\n\n\t/* make finish struct */\n\tcommonlen = COMPUTESIZE(state.num, state.sumlen);\n\tquery = (ltxtquery *) palloc(commonlen);\n\tSET_VARSIZE(query, commonlen);\n\tquery->size = state.num;\n\tptr = GETQUERY(query);\n\n\t/* set item in polish notation */\n\tfor (i = 0; i < state.num; i++)\n\t{\n\t\tptr[i].type = state.str->type;\n\t\tptr[i].val = state.str->val;\n\t\tptr[i].distance = state.str->distance;\n\t\tptr[i].length = state.str->length;\n\t\tptr[i].flag = state.str->flag;\n\t\ttmp = state.str->next;\n\t\tpfree(state.str);\n\t\tstate.str = tmp;\n\t}\n\n\t/* set user friendly-operand view */\n\tmemcpy((void *) GETOPERAND(query), (void *) state.op, state.sumlen);\n\tpfree(state.op);\n\n\t/* set left operand's position for every operator */\n\tpos = 0;\n\tfindoprnd(ptr, &pos);\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: txid_current_snapshot(PG_FUNCTION_ARGS)\n{\n\tTxidSnapshot *snap;\n\tuint32\t\tnxip,\n\t\t\t\ti,\n\t\t\t\tsize;\n\tTxidEpoch\tstate;\n\tSnapshot\tcur;\n\n\tcur = GetActiveSnapshot();\n\tif (cur == NULL)\n\t\telog(ERROR, \"no active snapshot set\");\n\n\tload_xid_epoch(&state);\n\n\t/* allocate */\n\tnxip = cur->xcnt;\n\tsize = TXID_SNAPSHOT_SIZE(nxip);\n\tsnap = palloc(size);\n\tSET_VARSIZE(snap, size);\n\n\t/* fill */\n\tsnap->xmin = convert_xid(cur->xmin, &state);\n\tsnap->xmax = convert_xid(cur->xmax, &state);\n\tsnap->nxip = nxip;\n\tfor (i = 0; i < nxip; i++)\n\t\tsnap->xip[i] = convert_xid(cur->xip[i], &state);\n\n\t/* we want them guaranteed to be in ascending order */\n\tsort_snapshot(snap);\n\n\tPG_RETURN_POINTER(snap);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Predict integer overflow to avoid buffer overruns.\n\nSeveral functions, mostly type input functions, calculated an allocation\nsize such that the calculation wrapped to a small positive value when\narguments implied a sufficiently-large requirement. Writes past the end\nof the inadvertent small allocation followed shortly thereafter.\nCoverity identified the path_in() vulnerability; code inspection led to\nthe rest. In passing, add check_stack_depth() to prevent stack overflow\nin related functions.\n\nBack-patch to 8.4 (all supported versions). The non-comment hstore\nchanges touch code that did not exist in 8.4, so that part stops at 9.0.\n\nNoah Misch and Heikki Linnakangas, reviewed by Tom Lane.\n\nSecurity: CVE-2014-0064'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: hstore_from_record(PG_FUNCTION_ARGS)\n{\n\tHeapTupleHeader rec;\n\tint32\t\tbuflen;\n\tHStore\t *out;\n\tPairs\t *pairs;\n\tOid\t\t\ttupType;\n\tint32\t\ttupTypmod;\n\tTupleDesc\ttupdesc;\n\tHeapTupleData tuple;\n\tRecordIOData *my_extra;\n\tint\t\t\tncolumns;\n\tint\t\t\ti,\n\t\t\t\tj;\n\tDatum\t *values;\n\tbool\t *nulls;\n\n\tif (PG_ARGISNULL(0))\n\t{\n\t\tOid\t\t\targtype = get_fn_expr_argtype(fcinfo->flinfo, 0);\n\n\t\t/*\n\t\t * have no tuple to look at, so the only source of type info is the\n\t\t * argtype. The lookup_rowtype_tupdesc call below will error out if we\n\t\t * don't have a known composite type oid here.\n\t\t */\n\t\ttupType = argtype;\n\t\ttupTypmod = -1;\n\n\t\trec = NULL;\n\t}\n\telse\n\t{\n\t\trec = PG_GETARG_HEAPTUPLEHEADER(0);\n\n\t\t/* Extract type info from the tuple itself */\n\t\ttupType = HeapTupleHeaderGetTypeId(rec);\n\t\ttupTypmod = HeapTupleHeaderGetTypMod(rec);\n\t}\n\n\ttupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);\n\tncolumns = tupdesc->natts;\n\n\t/*\n\t * We arrange to look up the needed I/O info just once per series of\n\t * calls, assuming the record type doesn't change underneath us.\n\t */\n\tmy_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;\n\tif (my_extra == NULL ||\n\t\tmy_extra->ncolumns != ncolumns)\n\t{\n\t\tfcinfo->flinfo->fn_extra =\n\t\t\tMemoryContextAlloc(fcinfo->flinfo->fn_mcxt,\n\t\t\t\t\t\t\t sizeof(RecordIOData) - sizeof(ColumnIOData)\n\t\t\t\t\t\t\t + ncolumns * sizeof(ColumnIOData));\n\t\tmy_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;\n\t\tmy_extra->record_type = InvalidOid;\n\t\tmy_extra->record_typmod = 0;\n\t}\n\n\tif (my_extra->record_type != tupType ||\n\t\tmy_extra->record_typmod != tupTypmod)\n\t{\n\t\tMemSet(my_extra, 0,\n\t\t\t sizeof(RecordIOData) - sizeof(ColumnIOData)\n\t\t\t + ncolumns * sizeof(ColumnIOData));\n\t\tmy_extra->record_type = tupType;\n\t\tmy_extra->record_typmod = tupTypmod;\n\t\tmy_extra->ncolumns = ncolumns;\n\t}\n\n\tpairs = palloc(ncolumns * sizeof(Pairs));\n\n\tif (rec)\n\t{\n\t\t/* Build a temporary HeapTuple control structure */\n\t\ttuple.t_len = HeapTupleHeaderGetDatumLength(rec);\n\t\tItemPointerSetInvalid(&(tuple.t_self));\n\t\ttuple.t_tableOid = InvalidOid;\n\t\ttuple.t_data = rec;\n\n\t\tvalues = (Datum *) palloc(ncolumns * sizeof(Datum));\n\t\tnulls = (bool *) palloc(ncolumns * sizeof(bool));\n\n\t\t/* Break down the tuple into fields */\n\t\theap_deform_tuple(&tuple, tupdesc, values, nulls);\n\t}\n\telse\n\t{\n\t\tvalues = NULL;\n\t\tnulls = NULL;\n\t}\n\n\tfor (i = 0, j = 0; i < ncolumns; ++i)\n\t{\n\t\tColumnIOData *column_info = &my_extra->columns[i];\n\t\tOid\t\t\tcolumn_type = tupdesc->attrs[i]->atttypid;\n\t\tchar\t *value;\n\n\t\t/* Ignore dropped columns in datatype */\n\t\tif (tupdesc->attrs[i]->attisdropped)\n\t\t\tcontinue;\n\n\t\tpairs[j].key = NameStr(tupdesc->attrs[i]->attname);\n\t\tpairs[j].keylen = hstoreCheckKeyLen(strlen(NameStr(tupdesc->attrs[i]->attname)));\n\n\t\tif (!nulls || nulls[i])\n\t\t{\n\t\t\tpairs[j].val = NULL;\n\t\t\tpairs[j].vallen = 4;\n\t\t\tpairs[j].isnull = true;\n\t\t\tpairs[j].needfree = false;\n\t\t\t++j;\n\t\t\tcontinue;\n\t\t}\n\n\t\t/*\n\t\t * Convert the column value to text\n\t\t */\n\t\tif (column_info->column_type != column_type)\n\t\t{\n\t\t\tbool\t\ttypIsVarlena;\n\n\t\t\tgetTypeOutputInfo(column_type,\n\t\t\t\t\t\t\t &column_info->typiofunc,\n\t\t\t\t\t\t\t &typIsVarlena);\n\t\t\tfmgr_info_cxt(column_info->typiofunc, &column_info->proc,\n\t\t\t\t\t\t fcinfo->flinfo->fn_mcxt);\n\t\t\tcolumn_info->column_type = column_type;\n\t\t}\n\n\t\tvalue = OutputFunctionCall(&column_info->proc, values[i]);\n\n\t\tpairs[j].val = value;\n\t\tpairs[j].vallen = hstoreCheckValLen(strlen(value));\n\t\tpairs[j].isnull = false;\n\t\tpairs[j].needfree = false;\n\t\t++j;\n\t}\n\n\tncolumns = hstoreUniquePairs(pairs, j, &buflen);\n\n\tout = hstorePairs(pairs, ncolumns, buflen);\n\n\tReleaseTupleDesc(tupdesc);\n\n\tPG_RETURN_POINTER(out);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Predict integer overflow to avoid buffer overruns.\n\nSeveral functions, mostly type input functions, calculated an allocation\nsize such that the calculation wrapped to a small positive value when\narguments implied a sufficiently-large requirement. Writes past the end\nof the inadvertent small allocation followed shortly thereafter.\nCoverity identified the path_in() vulnerability; code inspection led to\nthe rest. In passing, add check_stack_depth() to prevent stack overflow\nin related functions.\n\nBack-patch to 8.4 (all supported versions). The non-comment hstore\nchanges touch code that did not exist in 8.4, so that part stops at 9.0.\n\nNoah Misch and Heikki Linnakangas, reviewed by Tom Lane.\n\nSecurity: CVE-2014-0064'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: BaseBackup(void)\n{\n\tPGresult *res;\n\tchar\t *sysidentifier;\n\tuint32\t\tlatesttli;\n\tuint32\t\tstarttli;\n\tchar\t\tcurrent_path[MAXPGPATH];\n\tchar\t\tescaped_label[MAXPGPATH];\n\tint\t\t\ti;\n\tchar\t\txlogstart[64];\n\tchar\t\txlogend[64];\n\tint\t\t\tminServerMajor,\n\t\t\t\tmaxServerMajor;\n\tint\t\t\tserverMajor;\n\n\t/*\n\t * Connect in replication mode to the server\n\t */\n\tconn = GetConnection();\n\tif (!conn)\n\t\t/* Error message already written in GetConnection() */\n\t\texit(1);\n\n\t/*\n\t * Check server version. BASE_BACKUP command was introduced in 9.1, so we\n\t * can't work with servers older than 9.1.\n\t */\n\tminServerMajor = 901;\n\tmaxServerMajor = PG_VERSION_NUM / 100;\n\tserverMajor = PQserverVersion(conn) / 100;\n\tif (serverMajor < minServerMajor || serverMajor > maxServerMajor)\n\t{\n\t\tconst char *serverver = PQparameterStatus(conn, \"server_version\");\n\n\t\tfprintf(stderr, _(\"%s: incompatible server version %s\\n\"),\n\t\t\t\tprogname, serverver ? serverver : \"'unknown'\");\n\t\tdisconnect_and_exit(1);\n\t}\n\n\t/*\n\t * If WAL streaming was requested, also check that the server is new\n\t * enough for that.\n\t */\n\tif (streamwal && !CheckServerVersionForStreaming(conn))\n\t{\n\t\t/* Error message already written in CheckServerVersionForStreaming() */\n\t\tdisconnect_and_exit(1);\n\t}\n\n\t/*\n\t * Build contents of recovery.conf if requested\n\t */\n\tif (writerecoveryconf)\n\t\tGenerateRecoveryConf(conn);\n\n\t/*\n\t * Run IDENTIFY_SYSTEM so we can get the timeline\n\t */\n\tres = PQexec(conn, \"IDENTIFY_SYSTEM\");\n\tif (PQresultStatus(res) != PGRES_TUPLES_OK)\n\t{\n\t\tfprintf(stderr, _(\"%s: could not send replication command \\\"%s\\\": %s\"),\n\t\t\t\tprogname, \"IDENTIFY_SYSTEM\", PQerrorMessage(conn));\n\t\tdisconnect_and_exit(1);\n\t}\n\tif (PQntuples(res) != 1 || PQnfields(res) != 3)\n\t{\n\t\tfprintf(stderr,\n\t\t\t\t_(\"%s: could not identify system: got %d rows and %d fields, expected %d rows and %d fields\\n\"),\n\t\t\t\tprogname, PQntuples(res), PQnfields(res), 1, 3);\n\t\tdisconnect_and_exit(1);\n\t}\n\tsysidentifier = pg_strdup(PQgetvalue(res, 0, 0));\n\tlatesttli = atoi(PQgetvalue(res, 0, 1));\n\tPQclear(res);\n\n\t/*\n\t * Start the actual backup\n\t */\n\tPQescapeStringConn(conn, escaped_label, label, sizeof(escaped_label), &i);\n\tsnprintf(current_path, sizeof(current_path),\n\t\t\t \"BASE_BACKUP LABEL '%s' %s %s %s %s\",\n\t\t\t escaped_label,\n\t\t\t showprogress ? \"PROGRESS\" : \"\",\n\t\t\t includewal && !streamwal ? \"WAL\" : \"\",\n\t\t\t fastcheckpoint ? \"FAST\" : \"\",\n\t\t\t includewal ? \"NOWAIT\" : \"\");\n\n\tif (PQsendQuery(conn, current_path) == 0)\n\t{\n\t\tfprintf(stderr, _(\"%s: could not send replication command \\\"%s\\\": %s\"),\n\t\t\t\tprogname, \"BASE_BACKUP\", PQerrorMessage(conn));\n\t\tdisconnect_and_exit(1);\n\t}\n\n\t/*\n\t * Get the starting xlog position\n\t */\n\tres = PQgetResult(conn);\n\tif (PQresultStatus(res) != PGRES_TUPLES_OK)\n\t{\n\t\tfprintf(stderr, _(\"%s: could not initiate base backup: %s\"),\n\t\t\t\tprogname, PQerrorMessage(conn));\n\t\tdisconnect_and_exit(1);\n\t}\n\tif (PQntuples(res) != 1)\n\t{\n\t\tfprintf(stderr,\n\t\t\t\t_(\"%s: server returned unexpected response to BASE_BACKUP command; got %d rows and %d fields, expected %d rows and %d fields\\n\"),\n\t\t\t\tprogname, PQntuples(res), PQnfields(res), 1, 2);\n\t\tdisconnect_and_exit(1);\n\t}\n\n\tstrcpy(xlogstart, PQgetvalue(res, 0, 0));\n\n\t/*\n\t * 9.3 and later sends the TLI of the starting point. With older servers,\n\t * assume it's the same as the latest timeline reported by\n\t * IDENTIFY_SYSTEM.\n\t */\n\tif (PQnfields(res) >= 2)\n\t\tstarttli = atoi(PQgetvalue(res, 0, 1));\n\telse\n\t\tstarttli = latesttli;\n\tPQclear(res);\n\tMemSet(xlogend, 0, sizeof(xlogend));\n\n\tif (verbose && includewal)\n\t\tfprintf(stderr, _(\"transaction log start point: %s on timeline %u\\n\"),\n\t\t\t\txlogstart, starttli);\n\n\t/*\n\t * Get the header\n\t */\n\tres = PQgetResult(conn);\n\tif (PQresultStatus(res) != PGRES_TUPLES_OK)\n\t{\n\t\tfprintf(stderr, _(\"%s: could not get backup header: %s\"),\n\t\t\t\tprogname, PQerrorMessage(conn));\n\t\tdisconnect_and_exit(1);\n\t}\n\tif (PQntuples(res) < 1)\n\t{\n\t\tfprintf(stderr, _(\"%s: no data returned from server\\n\"), progname);\n\t\tdisconnect_and_exit(1);\n\t}\n\n\t/*\n\t * Sum up the total size, for progress reporting\n\t */\n\ttotalsize = totaldone = 0;\n\ttablespacecount = PQntuples(res);\n\tfor (i = 0; i < PQntuples(res); i++)\n\t{\n\t\ttotalsize += atol(PQgetvalue(res, i, 2));\n\n\t\t/*\n\t\t * Verify tablespace directories are empty. Don't bother with the\n\t\t * first once since it can be relocated, and it will be checked before\n\t\t * we do anything anyway.\n\t\t */\n\t\tif (format == 'p' && !PQgetisnull(res, i, 1))\n\t\t\tverify_dir_is_empty_or_create(PQgetvalue(res, i, 1));\n\t}\n\n\t/*\n\t * When writing to stdout, require a single tablespace\n\t */\n\tif (format == 't' && strcmp(basedir, \"-\") == 0 && PQntuples(res) > 1)\n\t{\n\t\tfprintf(stderr,\n\t\t\t\t_(\"%s: can only write single tablespace to stdout, database has %d\\n\"),\n\t\t\t\tprogname, PQntuples(res));\n\t\tdisconnect_and_exit(1);\n\t}\n\n\t/*\n\t * If we're streaming WAL, start the streaming session before we start\n\t * receiving the actual data chunks.\n\t */\n\tif (streamwal)\n\t{\n\t\tif (verbose)\n\t\t\tfprintf(stderr, _(\"%s: starting background WAL receiver\\n\"),\n\t\t\t\t\tprogname);\n\t\tStartLogStreamer(xlogstart, starttli, sysidentifier);\n\t}\n\n\t/*\n\t * Start receiving chunks\n\t */\n\tfor (i = 0; i < PQntuples(res); i++)\n\t{\n\t\tif (format == 't')\n\t\t\tReceiveTarFile(conn, res, i);\n\t\telse\n\t\t\tReceiveAndUnpackTarFile(conn, res, i);\n\t}\t\t\t\t\t\t\t/* Loop over all tablespaces */\n\n\tif (showprogress)\n\t{\n\t\tprogress_report(PQntuples(res), NULL, true);\n\t\tfprintf(stderr, \"\\n\");\t/* Need to move to next line */\n\t}\n\tPQclear(res);\n\n\t/*\n\t * Get the stop position\n\t */\n\tres = PQgetResult(conn);\n\tif (PQresultStatus(res) != PGRES_TUPLES_OK)\n\t{\n\t\tfprintf(stderr,\n\t\t _(\"%s: could not get transaction log end position from server: %s\"),\n\t\t\t\tprogname, PQerrorMessage(conn));\n\t\tdisconnect_and_exit(1);\n\t}\n\tif (PQntuples(res) != 1)\n\t{\n\t\tfprintf(stderr,\n\t\t\t _(\"%s: no transaction log end position returned from server\\n\"),\n\t\t\t\tprogname);\n\t\tdisconnect_and_exit(1);\n\t}\n\tstrcpy(xlogend, PQgetvalue(res, 0, 0));\n\tif (verbose && includewal)\n\t\tfprintf(stderr, \"transaction log end point: %s\\n\", xlogend);\n\tPQclear(res);\n\n\tres = PQgetResult(conn);\n\tif (PQresultStatus(res) != PGRES_COMMAND_OK)\n\t{\n\t\tfprintf(stderr, _(\"%s: final receive failed: %s\"),\n\t\t\t\tprogname, PQerrorMessage(conn));\n\t\tdisconnect_and_exit(1);\n\t}\n\n\tif (bgchild > 0)\n\t{\n#ifndef WIN32\n\t\tint\t\t\tstatus;\n\t\tint\t\t\tr;\n#else\n\t\tDWORD\t\tstatus;\n\t\tuint32\t\thi,\n\t\t\t\t\tlo;\n#endif\n\n\t\tif (verbose)\n\t\t\tfprintf(stderr,\n\t\t\t\t\t_(\"%s: waiting for background process to finish streaming ...\\n\"), progname);\n\n#ifndef WIN32\n\t\tif (write(bgpipe[1], xlogend, strlen(xlogend)) != strlen(xlogend))\n\t\t{\n\t\t\tfprintf(stderr,\n\t\t\t\t\t_(\"%s: could not send command to background pipe: %s\\n\"),\n\t\t\t\t\tprogname, strerror(errno));\n\t\t\tdisconnect_and_exit(1);\n\t\t}\n\n\t\t/* Just wait for the background process to exit */\n\t\tr = waitpid(bgchild, &status, 0);\n\t\tif (r == -1)\n\t\t{\n\t\t\tfprintf(stderr, _(\"%s: could not wait for child process: %s\\n\"),\n\t\t\t\t\tprogname, strerror(errno));\n\t\t\tdisconnect_and_exit(1);\n\t\t}\n\t\tif (r != bgchild)\n\t\t{\n\t\t\tfprintf(stderr, _(\"%s: child %d died, expected %d\\n\"),\n\t\t\t\t\tprogname, r, (int) bgchild);\n\t\t\tdisconnect_and_exit(1);\n\t\t}\n\t\tif (!WIFEXITED(status))\n\t\t{\n\t\t\tfprintf(stderr, _(\"%s: child process did not exit normally\\n\"),\n\t\t\t\t\tprogname);\n\t\t\tdisconnect_and_exit(1);\n\t\t}\n\t\tif (WEXITSTATUS(status) != 0)\n\t\t{\n\t\t\tfprintf(stderr, _(\"%s: child process exited with error %d\\n\"),\n\t\t\t\t\tprogname, WEXITSTATUS(status));\n\t\t\tdisconnect_and_exit(1);\n\t\t}\n\t\t/* Exited normally, we're happy! */\n#else\t\t\t\t\t\t\t/* WIN32 */\n\n\t\t/*\n\t\t * On Windows, since we are in the same process, we can just store the\n\t\t * value directly in the variable, and then set the flag that says\n\t\t * it's there.\n\t\t */\n\t\tif (sscanf(xlogend, \"%X/%X\", &hi, &lo) != 2)\n\t\t{\n\t\t\tfprintf(stderr,\n\t\t\t\t _(\"%s: could not parse transaction log location \\\"%s\\\"\\n\"),\n\t\t\t\t\tprogname, xlogend);\n\t\t\tdisconnect_and_exit(1);\n\t\t}\n\t\txlogendptr = ((uint64) hi) << 32 | lo;\n\t\tInterlockedIncrement(&has_xlogendptr);\n\n\t\t/* First wait for the thread to exit */\n\t\tif (WaitForSingleObjectEx((HANDLE) bgchild, INFINITE, FALSE) !=\n\t\t\tWAIT_OBJECT_0)\n\t\t{\n\t\t\t_dosmaperr(GetLastError());\n\t\t\tfprintf(stderr, _(\"%s: could not wait for child thread: %s\\n\"),\n\t\t\t\t\tprogname, strerror(errno));\n\t\t\tdisconnect_and_exit(1);\n\t\t}\n\t\tif (GetExitCodeThread((HANDLE) bgchild, &status) == 0)\n\t\t{\n\t\t\t_dosmaperr(GetLastError());\n\t\t\tfprintf(stderr, _(\"%s: could not get child thread exit status: %s\\n\"),\n\t\t\t\t\tprogname, strerror(errno));\n\t\t\tdisconnect_and_exit(1);\n\t\t}\n\t\tif (status != 0)\n\t\t{\n\t\t\tfprintf(stderr, _(\"%s: child thread exited with error %u\\n\"),\n\t\t\t\t\tprogname, (unsigned int) status);\n\t\t\tdisconnect_and_exit(1);\n\t\t}\n\t\t/* Exited normally, we're happy */\n#endif\n\t}\n\n\t/* Free the recovery.conf contents */\n\tdestroyPQExpBuffer(recoveryconfcontents);\n\n\t/*\n\t * End of copy data. Final result is already checked inside the loop.\n\t */\n\tPQclear(res);\n\tPQfinish(conn);\n\n\tif (verbose)\n\t\tfprintf(stderr, \"%s: base backup completed\\n\", progname);\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: ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res, int rownum)\n{\n\tchar\t\tcurrent_path[MAXPGPATH];\n\tchar\t\tfilename[MAXPGPATH];\n\tint\t\t\tcurrent_len_left;\n\tint\t\t\tcurrent_padding = 0;\n\tbool\t\tbasetablespace = PQgetisnull(res, rownum, 0);\n\tchar\t *copybuf = NULL;\n\tFILE\t *file = NULL;\n\n\tif (basetablespace)\n\t\tstrcpy(current_path, basedir);\n\telse\n\t\tstrcpy(current_path, PQgetvalue(res, rownum, 1));\n\n\t/*\n\t * Get the COPY data\n\t */\n\tres = PQgetResult(conn);\n\tif (PQresultStatus(res) != PGRES_COPY_OUT)\n\t{\n\t\tfprintf(stderr, _(\"%s: could not get COPY data stream: %s\"),\n\t\t\t\tprogname, PQerrorMessage(conn));\n\t\tdisconnect_and_exit(1);\n\t}\n\n\twhile (1)\n\t{\n\t\tint\t\t\tr;\n\n\t\tif (copybuf != NULL)\n\t\t{\n\t\t\tPQfreemem(copybuf);\n\t\t\tcopybuf = NULL;\n\t\t}\n\n\t\tr = PQgetCopyData(conn, ©buf, 0);\n\n\t\tif (r == -1)\n\t\t{\n\t\t\t/*\n\t\t\t * End of chunk\n\t\t\t */\n\t\t\tif (file)\n\t\t\t\tfclose(file);\n\n\t\t\tbreak;\n\t\t}\n\t\telse if (r == -2)\n\t\t{\n\t\t\tfprintf(stderr, _(\"%s: could not read COPY data: %s\"),\n\t\t\t\t\tprogname, PQerrorMessage(conn));\n\t\t\tdisconnect_and_exit(1);\n\t\t}\n\n\t\tif (file == NULL)\n\t\t{\n\t\t\tint\t\t\tfilemode;\n\n\t\t\t/*\n\t\t\t * No current file, so this must be the header for a new file\n\t\t\t */\n\t\t\tif (r != 512)\n\t\t\t{\n\t\t\t\tfprintf(stderr, _(\"%s: invalid tar block header size: %d\\n\"),\n\t\t\t\t\t\tprogname, r);\n\t\t\t\tdisconnect_and_exit(1);\n\t\t\t}\n\t\t\ttotaldone += 512;\n\n\t\t\tif (sscanf(copybuf + 124, \"%11o\", ¤t_len_left) != 1)\n\t\t\t{\n\t\t\t\tfprintf(stderr, _(\"%s: could not parse file size\\n\"),\n\t\t\t\t\t\tprogname);\n\t\t\t\tdisconnect_and_exit(1);\n\t\t\t}\n\n\t\t\t/* Set permissions on the file */\n\t\t\tif (sscanf(©buf[100], \"%07o \", &filemode) != 1)\n\t\t\t{\n\t\t\t\tfprintf(stderr, _(\"%s: could not parse file mode\\n\"),\n\t\t\t\t\t\tprogname);\n\t\t\t\tdisconnect_and_exit(1);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * All files are padded up to 512 bytes\n\t\t\t */\n\t\t\tcurrent_padding =\n\t\t\t\t((current_len_left + 511) & ~511) - current_len_left;\n\n\t\t\t/*\n\t\t\t * First part of header is zero terminated filename\n\t\t\t */\n\t\t\tsnprintf(filename, sizeof(filename), \"%s/%s\", current_path,\n\t\t\t\t\t copybuf);\n\t\t\tif (filename[strlen(filename) - 1] == '/')\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\t * Ends in a slash means directory or symlink to directory\n\t\t\t\t */\n\t\t\t\tif (copybuf[156] == '5')\n\t\t\t\t{\n\t\t\t\t\t/*\n\t\t\t\t\t * Directory\n\t\t\t\t\t */\n\t\t\t\t\tfilename[strlen(filename) - 1] = '\\0';\t\t/* Remove trailing slash */\n\t\t\t\t\tif (mkdir(filename, S_IRWXU) != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * When streaming WAL, pg_xlog will have been created\n\t\t\t\t\t\t * by the wal receiver process. Also, when transaction\n\t\t\t\t\t\t * log directory location was specified, pg_xlog has\n\t\t\t\t\t\t * already been created as a symbolic link before\n\t\t\t\t\t\t * starting the actual backup. So just ignore failure\n\t\t\t\t\t\t * on them.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tif ((!streamwal && (strcmp(xlog_dir, \"\") == 0))\n\t\t\t\t\t\t\t|| strcmp(filename + strlen(filename) - 8, \"/pg_xlog\") != 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfprintf(stderr,\n\t\t\t\t\t\t\t_(\"%s: could not create directory \\\"%s\\\": %s\\n\"),\n\t\t\t\t\t\t\t\t\tprogname, filename, strerror(errno));\n\t\t\t\t\t\t\tdisconnect_and_exit(1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n#ifndef WIN32\n\t\t\t\t\tif (chmod(filename, (mode_t) filemode))\n\t\t\t\t\t\tfprintf(stderr,\n\t\t\t\t\t\t\t\t_(\"%s: could not set permissions on directory \\\"%s\\\": %s\\n\"),\n\t\t\t\t\t\t\t\tprogname, filename, strerror(errno));\n#endif\n\t\t\t\t}\n\t\t\t\telse if (copybuf[156] == '2')\n\t\t\t\t{\n\t\t\t\t\t/*\n\t\t\t\t\t * Symbolic link\n\t\t\t\t\t */\n\t\t\t\t\tfilename[strlen(filename) - 1] = '\\0';\t\t/* Remove trailing slash */\n\t\t\t\t\tif (symlink(©buf[157], filename) != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tfprintf(stderr,\n\t\t\t\t\t\t\t\t_(\"%s: could not create symbolic link from \\\"%s\\\" to \\\"%s\\\": %s\\n\"),\n\t\t\t\t\t\t progname, filename, ©buf[157], strerror(errno));\n\t\t\t\t\t\tdisconnect_and_exit(1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tfprintf(stderr,\n\t\t\t\t\t\t\t_(\"%s: unrecognized link indicator \\\"%c\\\"\\n\"),\n\t\t\t\t\t\t\tprogname, copybuf[156]);\n\t\t\t\t\tdisconnect_and_exit(1);\n\t\t\t\t}\n\t\t\t\tcontinue;\t\t/* directory or link handled */\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * regular file\n\t\t\t */\n\t\t\tfile = fopen(filename, \"wb\");\n\t\t\tif (!file)\n\t\t\t{\n\t\t\t\tfprintf(stderr, _(\"%s: could not create file \\\"%s\\\": %s\\n\"),\n\t\t\t\t\t\tprogname, filename, strerror(errno));\n\t\t\t\tdisconnect_and_exit(1);\n\t\t\t}\n\n#ifndef WIN32\n\t\t\tif (chmod(filename, (mode_t) filemode))\n\t\t\t\tfprintf(stderr, _(\"%s: could not set permissions on file \\\"%s\\\": %s\\n\"),\n\t\t\t\t\t\tprogname, filename, strerror(errno));\n#endif\n\n\t\t\tif (current_len_left == 0)\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\t * Done with this file, next one will be a new tar header\n\t\t\t\t */\n\t\t\t\tfclose(file);\n\t\t\t\tfile = NULL;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\t\t\t\t\t\t/* new file */\n\t\telse\n\t\t{\n\t\t\t/*\n\t\t\t * Continuing blocks in existing file\n\t\t\t */\n\t\t\tif (current_len_left == 0 && r == current_padding)\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\t * Received the padding block for this file, ignore it and\n\t\t\t\t * close the file, then move on to the next tar header.\n\t\t\t\t */\n\t\t\t\tfclose(file);\n\t\t\t\tfile = NULL;\n\t\t\t\ttotaldone += r;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (fwrite(copybuf, r, 1, file) != 1)\n\t\t\t{\n\t\t\t\tfprintf(stderr, _(\"%s: could not write to file \\\"%s\\\": %s\\n\"),\n\t\t\t\t\t\tprogname, filename, strerror(errno));\n\t\t\t\tdisconnect_and_exit(1);\n\t\t\t}\n\t\t\ttotaldone += r;\n\t\t\tprogress_report(rownum, filename, false);\n\n\t\t\tcurrent_len_left -= r;\n\t\t\tif (current_len_left == 0 && current_padding == 0)\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\t * Received the last block, and there is no padding to be\n\t\t\t\t * expected. Close the file and move on to the next tar\n\t\t\t\t * header.\n\t\t\t\t */\n\t\t\t\tfclose(file);\n\t\t\t\tfile = NULL;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\t\t\t\t\t\t/* continuing data in existing file */\n\t}\t\t\t\t\t\t\t/* loop over all data blocks */\n\tprogress_report(rownum, filename, true);\n\n\tif (file != NULL)\n\t{\n\t\tfprintf(stderr,\n\t\t\t\t_(\"%s: COPY stream ended before last file was finished\\n\"),\n\t\t\t\tprogname);\n\t\tdisconnect_and_exit(1);\n\t}\n\n\tif (copybuf != NULL)\n\t\tPQfreemem(copybuf);\n\n\tif (basetablespace && writerecoveryconf)\n\t\tWriteRecoveryConf();\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 void *virtio_scsi_load_request(QEMUFile *f, SCSIRequest *sreq)\n{\n SCSIBus *bus = sreq->bus;\n VirtIOSCSI *s = container_of(bus, VirtIOSCSI, bus);\n VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s);\n VirtIOSCSIReq *req;\n uint32_t n;\n\n req = g_malloc(sizeof(*req));\n qemu_get_be32s(f, &n);\n assert(n < vs->conf.num_queues);\n qemu_get_buffer(f, (unsigned char *)&req->elem, sizeof(req->elem));\n virtio_scsi_parse_req(s, vs->cmd_vqs[n], req);\n\n scsi_req_ref(sreq);\n req->sreq = sreq;\n if (req->sreq->cmd.mode != SCSI_XFER_NONE) {\n int req_mode =\n (req->elem.in_num > 1 ? SCSI_XFER_FROM_DEV : SCSI_XFER_TO_DEV);\n\n assert(req->sreq->cmd.mode == req_mode);\n }\n return req;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'virtio-scsi: fix buffer overrun on invalid state load\n\nCVE-2013-4542\n\nhw/scsi/scsi-bus.c invokes load_request.\n\n virtio_scsi_load_request does:\n qemu_get_buffer(f, (unsigned char *)&req->elem, sizeof(req->elem));\n\nthis probably can make elem invalid, for example,\nmake in_num or out_num huge, then:\n\n virtio_scsi_parse_req(s, vs->cmd_vqs[n], req);\n\nwill do:\n\n if (req->elem.out_num > 1) {\n qemu_sgl_init_external(req, &req->elem.out_sg[1],\n &req->elem.out_addr[1],\n req->elem.out_num - 1);\n } else {\n qemu_sgl_init_external(req, &req->elem.in_sg[1],\n &req->elem.in_addr[1],\n req->elem.in_num - 1);\n }\n\nand this will access out of array bounds.\n\nNote: this adds security checks within assert calls since\nSCSIBusInfo's load_request cannot fail.\nFor now simply disable builds with NDEBUG - there seems\nto be little value in supporting these.\n\nCc: Andreas F\u00e4rber \nSigned-off-by: Michael S. Tsirkin \nSigned-off-by: Juan Quintela '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int nfs_can_extend_write(struct file *file, struct page *page, struct inode *inode)\n{\n\tif (file->f_flags & O_DSYNC)\n\t\treturn 0;\n\tif (NFS_PROTO(inode)->have_delegation(inode, FMODE_WRITE))\n\t\treturn 1;\n\tif (nfs_write_pageuptodate(page, inode) && (inode->i_flock == NULL ||\n\t\t\t(inode->i_flock->fl_start == 0 &&\n\t\t\tinode->i_flock->fl_end == OFFSET_MAX &&\n\t\t\tinode->i_flock->fl_type != F_RDLCK)))\n\t\treturn 1;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-200'], 'message': 'nfs: always make sure page is up-to-date before extending a write to cover the entire page\n\nWe should always make sure the cached page is up-to-date when we're\ndetermining whether we can extend a write to cover the full page -- even\nif we've received a write delegation from the server.\n\nCommit c7559663 added logic to skip this check if we have a write\ndelegation, which can lead to data corruption such as the following\nscenario if client B receives a write delegation from the NFS server:\n\nClient A:\n # echo 123456789 > /mnt/file\n\nClient B:\n # echo abcdefghi >> /mnt/file\n # cat /mnt/file\n 0\ufffdD0\ufffdabcdefghi\n\nJust because we hold a write delegation doesn't mean that we've read in\nthe entire page contents.\n\nCc: # v3.11+\nSigned-off-by: Scott Mayhew \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: \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, in_type;\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#ifndef COMPILE_ONLY\n\t\tfile_mdump(m);\n#endif\n\t}\n\n\tif (m->flag & INDIR) {\n\t\tint off = m->in_offset;\n\t\tif (m->in_op & FILE_OPINDIRECT) {\n\t\t\tconst union VALUETYPE *q = CAST(const union VALUETYPE *,\n\t\t\t ((const void *)(s + offset + off)));\n\t\t\tswitch (cvt_flip(m->in_type, flip)) {\n\t\t\tcase FILE_BYTE:\n\t\t\t\toff = q->b;\n\t\t\t\tbreak;\n\t\t\tcase FILE_SHORT:\n\t\t\t\toff = q->h;\n\t\t\t\tbreak;\n\t\t\tcase FILE_BESHORT:\n\t\t\t\toff = (short)((q->hs[0]<<8)|(q->hs[1]));\n\t\t\t\tbreak;\n\t\t\tcase FILE_LESHORT:\n\t\t\t\toff = (short)((q->hs[1]<<8)|(q->hs[0]));\n\t\t\t\tbreak;\n\t\t\tcase FILE_LONG:\n\t\t\t\toff = q->l;\n\t\t\t\tbreak;\n\t\t\tcase FILE_BELONG:\n\t\t\tcase FILE_BEID3:\n\t\t\t\toff = (int32_t)((q->hl[0]<<24)|(q->hl[1]<<16)|\n\t\t\t\t\t\t (q->hl[2]<<8)|(q->hl[3]));\n\t\t\t\tbreak;\n\t\t\tcase FILE_LEID3:\n\t\t\tcase FILE_LELONG:\n\t\t\t\toff = (int32_t)((q->hl[3]<<24)|(q->hl[2]<<16)|\n\t\t\t\t\t\t (q->hl[1]<<8)|(q->hl[0]));\n\t\t\t\tbreak;\n\t\t\tcase FILE_MELONG:\n\t\t\t\toff = (int32_t)((q->hl[1]<<24)|(q->hl[0]<<16)|\n\t\t\t\t\t\t (q->hl[3]<<8)|(q->hl[2]));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\t\tfprintf(stderr, \"indirect offs=%u\\n\", off);\n\t\t}\n\t\tswitch (in_type = cvt_flip(m->in_type, flip)) {\n\t\tcase FILE_BYTE:\n\t\t\tif (nbytes < offset || 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 || 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 || 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 || 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 || 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 || 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 || 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 || 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\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\tswitch (in_type) {\n\t\tcase FILE_LEID3:\n\t\tcase FILE_BEID3:\n\t\t\toffset = ((((offset >> 0) & 0x7f) << 0) |\n\t\t\t\t (((offset >> 8) & 0x7f) << 7) |\n\t\t\t\t (((offset >> 16) & 0x7f) << 14) |\n\t\t\t\t (((offset >> 24) & 0x7f) << 21)) + 10;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\tif (m->flag & INDIROFFADD) {\n\t\t\toffset += ms->c.li[cont_level-1].off;\n\t\t\tif (offset == 0) {\n\t\t\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\t\t\tfprintf(stderr,\n\t\t\t\t\t \"indirect *zero* offset\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\t\tfprintf(stderr, \"indirect +offs=%u\\n\", offset);\n\t\t}\n\t\tif (mcopy(ms, p, m->type, 0, s, offset, nbytes, count) == -1)\n\t\t\treturn -1;\n\t\tms->offset = offset;\n\n\t\tif ((ms->flags & MAGIC_DEBUG) != 0) {\n\t\t\tmdebug(offset, (char *)(void *)p,\n\t\t\t sizeof(union VALUETYPE));\n#ifndef COMPILE_ONLY\n\t\t\tfile_mdump(m);\n#endif\n\t\t}\n\t}\n\n\t/* Verify we have enough data to match magic type */\n\tswitch (m->type) {\n\tcase FILE_BYTE:\n\t\tif (nbytes < (offset + 1)) /* should alway be true */\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_SHORT:\n\tcase FILE_BESHORT:\n\tcase FILE_LESHORT:\n\t\tif (nbytes < (offset + 2))\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_LONG:\n\tcase FILE_BELONG:\n\tcase FILE_LELONG:\n\tcase FILE_MELONG:\n\tcase FILE_DATE:\n\tcase FILE_BEDATE:\n\tcase FILE_LEDATE:\n\tcase FILE_MEDATE:\n\tcase FILE_LDATE:\n\tcase FILE_BELDATE:\n\tcase FILE_LELDATE:\n\tcase FILE_MELDATE:\n\tcase FILE_FLOAT:\n\tcase FILE_BEFLOAT:\n\tcase FILE_LEFLOAT:\n\t\tif (nbytes < (offset + 4))\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_DOUBLE:\n\tcase FILE_BEDOUBLE:\n\tcase FILE_LEDOUBLE:\n\t\tif (nbytes < (offset + 8))\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_STRING:\n\tcase FILE_PSTRING:\n\tcase FILE_SEARCH:\n\t\tif (nbytes < (offset + m->vallen))\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_REGEX:\n\t\tif (nbytes < offset)\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_INDIRECT:\n\t\tif (nbytes < offset)\n\t\t\treturn 0;\n\t\tsbuf = ms->o.buf;\n\t\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 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, F(m->desc, \"%u\"), offset) == -1)\n\t\t\t\treturn -1;\n\t\t\tif (file_printf(ms, \"%s\", rbuf) == -1)\n\t\t\t\treturn -1;\n\t\t\tfree(rbuf);\n\t\t}\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\tcase FILE_CLEAR:\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': 'PR/313: Aaron Reffett: Check properly for exceeding the offset.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int qcow2_alloc_clusters_at(BlockDriverState *bs, uint64_t offset,\n int nb_clusters)\n{\n BDRVQcowState *s = bs->opaque;\n uint64_t cluster_index;\n uint64_t old_free_cluster_index;\n uint64_t i;\n int refcount, ret;\n\n assert(nb_clusters >= 0);\n if (nb_clusters == 0) {\n return 0;\n }\n\n /* Check how many clusters there are free */\n cluster_index = offset >> s->cluster_bits;\n for(i = 0; i < nb_clusters; i++) {\n refcount = get_refcount(bs, cluster_index++);\n\n if (refcount < 0) {\n return refcount;\n } else if (refcount != 0) {\n break;\n }\n }\n\n /* And then allocate them */\n old_free_cluster_index = s->free_cluster_index;\n s->free_cluster_index = cluster_index + i;\n\n ret = update_refcount(bs, offset, i << s->cluster_bits, 1,\n QCOW2_DISCARD_NEVER);\n if (ret < 0) {\n return ret;\n }\n\n s->free_cluster_index = old_free_cluster_index;\n\n return i;\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: nfqnl_build_packet_message(struct net *net, struct nfqnl_instance *queue,\n\t\t\t struct nf_queue_entry *entry,\n\t\t\t __be32 **packet_id_ptr)\n{\n\tsize_t size;\n\tsize_t data_len = 0, cap_len = 0;\n\tunsigned int hlen = 0;\n\tstruct sk_buff *skb;\n\tstruct nlattr *nla;\n\tstruct nfqnl_msg_packet_hdr *pmsg;\n\tstruct nlmsghdr *nlh;\n\tstruct nfgenmsg *nfmsg;\n\tstruct sk_buff *entskb = entry->skb;\n\tstruct net_device *indev;\n\tstruct net_device *outdev;\n\tstruct nf_conn *ct = NULL;\n\tenum ip_conntrack_info uninitialized_var(ctinfo);\n\tbool csum_verify;\n\n\tsize = nlmsg_total_size(sizeof(struct nfgenmsg))\n\t\t+ nla_total_size(sizeof(struct nfqnl_msg_packet_hdr))\n\t\t+ nla_total_size(sizeof(u_int32_t))\t/* ifindex */\n\t\t+ nla_total_size(sizeof(u_int32_t))\t/* ifindex */\n#ifdef CONFIG_BRIDGE_NETFILTER\n\t\t+ nla_total_size(sizeof(u_int32_t))\t/* ifindex */\n\t\t+ nla_total_size(sizeof(u_int32_t))\t/* ifindex */\n#endif\n\t\t+ nla_total_size(sizeof(u_int32_t))\t/* mark */\n\t\t+ nla_total_size(sizeof(struct nfqnl_msg_packet_hw))\n\t\t+ nla_total_size(sizeof(u_int32_t))\t/* skbinfo */\n\t\t+ nla_total_size(sizeof(u_int32_t));\t/* cap_len */\n\n\tif (entskb->tstamp.tv64)\n\t\tsize += nla_total_size(sizeof(struct nfqnl_msg_packet_timestamp));\n\n\tif (entry->hook <= NF_INET_FORWARD ||\n\t (entry->hook == NF_INET_POST_ROUTING && entskb->sk == NULL))\n\t\tcsum_verify = !skb_csum_unnecessary(entskb);\n\telse\n\t\tcsum_verify = false;\n\n\toutdev = entry->outdev;\n\n\tswitch ((enum nfqnl_config_mode)ACCESS_ONCE(queue->copy_mode)) {\n\tcase NFQNL_COPY_META:\n\tcase NFQNL_COPY_NONE:\n\t\tbreak;\n\n\tcase NFQNL_COPY_PACKET:\n\t\tif (!(queue->flags & NFQA_CFG_F_GSO) &&\n\t\t entskb->ip_summed == CHECKSUM_PARTIAL &&\n\t\t skb_checksum_help(entskb))\n\t\t\treturn NULL;\n\n\t\tdata_len = ACCESS_ONCE(queue->copy_range);\n\t\tif (data_len > entskb->len)\n\t\t\tdata_len = entskb->len;\n\n\t\thlen = skb_zerocopy_headlen(entskb);\n\t\thlen = min_t(unsigned int, hlen, data_len);\n\t\tsize += sizeof(struct nlattr) + hlen;\n\t\tcap_len = entskb->len;\n\t\tbreak;\n\t}\n\n\tif (queue->flags & NFQA_CFG_F_CONNTRACK)\n\t\tct = nfqnl_ct_get(entskb, &size, &ctinfo);\n\n\tif (queue->flags & NFQA_CFG_F_UID_GID) {\n\t\tsize += (nla_total_size(sizeof(u_int32_t))\t/* uid */\n\t\t\t+ nla_total_size(sizeof(u_int32_t)));\t/* gid */\n\t}\n\n\tskb = nfnetlink_alloc_skb(net, size, queue->peer_portid,\n\t\t\t\t GFP_ATOMIC);\n\tif (!skb)\n\t\treturn NULL;\n\n\tnlh = nlmsg_put(skb, 0, 0,\n\t\t\tNFNL_SUBSYS_QUEUE << 8 | NFQNL_MSG_PACKET,\n\t\t\tsizeof(struct nfgenmsg), 0);\n\tif (!nlh) {\n\t\tkfree_skb(skb);\n\t\treturn NULL;\n\t}\n\tnfmsg = nlmsg_data(nlh);\n\tnfmsg->nfgen_family = entry->pf;\n\tnfmsg->version = NFNETLINK_V0;\n\tnfmsg->res_id = htons(queue->queue_num);\n\n\tnla = __nla_reserve(skb, NFQA_PACKET_HDR, sizeof(*pmsg));\n\tpmsg = nla_data(nla);\n\tpmsg->hw_protocol\t= entskb->protocol;\n\tpmsg->hook\t\t= entry->hook;\n\t*packet_id_ptr\t\t= &pmsg->packet_id;\n\n\tindev = entry->indev;\n\tif (indev) {\n#ifndef CONFIG_BRIDGE_NETFILTER\n\t\tif (nla_put_be32(skb, NFQA_IFINDEX_INDEV, htonl(indev->ifindex)))\n\t\t\tgoto nla_put_failure;\n#else\n\t\tif (entry->pf == PF_BRIDGE) {\n\t\t\t/* Case 1: indev is physical input device, we need to\n\t\t\t * look for bridge group (when called from\n\t\t\t * netfilter_bridge) */\n\t\t\tif (nla_put_be32(skb, NFQA_IFINDEX_PHYSINDEV,\n\t\t\t\t\t htonl(indev->ifindex)) ||\n\t\t\t/* this is the bridge group \"brX\" */\n\t\t\t/* rcu_read_lock()ed by __nf_queue */\n\t\t\t nla_put_be32(skb, NFQA_IFINDEX_INDEV,\n\t\t\t\t\t htonl(br_port_get_rcu(indev)->br->dev->ifindex)))\n\t\t\t\tgoto nla_put_failure;\n\t\t} else {\n\t\t\t/* Case 2: indev is bridge group, we need to look for\n\t\t\t * physical device (when called from ipv4) */\n\t\t\tif (nla_put_be32(skb, NFQA_IFINDEX_INDEV,\n\t\t\t\t\t htonl(indev->ifindex)))\n\t\t\t\tgoto nla_put_failure;\n\t\t\tif (entskb->nf_bridge && entskb->nf_bridge->physindev &&\n\t\t\t nla_put_be32(skb, NFQA_IFINDEX_PHYSINDEV,\n\t\t\t\t\t htonl(entskb->nf_bridge->physindev->ifindex)))\n\t\t\t\tgoto nla_put_failure;\n\t\t}\n#endif\n\t}\n\n\tif (outdev) {\n#ifndef CONFIG_BRIDGE_NETFILTER\n\t\tif (nla_put_be32(skb, NFQA_IFINDEX_OUTDEV, htonl(outdev->ifindex)))\n\t\t\tgoto nla_put_failure;\n#else\n\t\tif (entry->pf == PF_BRIDGE) {\n\t\t\t/* Case 1: outdev is physical output device, we need to\n\t\t\t * look for bridge group (when called from\n\t\t\t * netfilter_bridge) */\n\t\t\tif (nla_put_be32(skb, NFQA_IFINDEX_PHYSOUTDEV,\n\t\t\t\t\t htonl(outdev->ifindex)) ||\n\t\t\t/* this is the bridge group \"brX\" */\n\t\t\t/* rcu_read_lock()ed by __nf_queue */\n\t\t\t nla_put_be32(skb, NFQA_IFINDEX_OUTDEV,\n\t\t\t\t\t htonl(br_port_get_rcu(outdev)->br->dev->ifindex)))\n\t\t\t\tgoto nla_put_failure;\n\t\t} else {\n\t\t\t/* Case 2: outdev is bridge group, we need to look for\n\t\t\t * physical output device (when called from ipv4) */\n\t\t\tif (nla_put_be32(skb, NFQA_IFINDEX_OUTDEV,\n\t\t\t\t\t htonl(outdev->ifindex)))\n\t\t\t\tgoto nla_put_failure;\n\t\t\tif (entskb->nf_bridge && entskb->nf_bridge->physoutdev &&\n\t\t\t nla_put_be32(skb, NFQA_IFINDEX_PHYSOUTDEV,\n\t\t\t\t\t htonl(entskb->nf_bridge->physoutdev->ifindex)))\n\t\t\t\tgoto nla_put_failure;\n\t\t}\n#endif\n\t}\n\n\tif (entskb->mark &&\n\t nla_put_be32(skb, NFQA_MARK, htonl(entskb->mark)))\n\t\tgoto nla_put_failure;\n\n\tif (indev && entskb->dev &&\n\t entskb->mac_header != entskb->network_header) {\n\t\tstruct nfqnl_msg_packet_hw phw;\n\t\tint len;\n\n\t\tmemset(&phw, 0, sizeof(phw));\n\t\tlen = dev_parse_header(entskb, phw.hw_addr);\n\t\tif (len) {\n\t\t\tphw.hw_addrlen = htons(len);\n\t\t\tif (nla_put(skb, NFQA_HWADDR, sizeof(phw), &phw))\n\t\t\t\tgoto nla_put_failure;\n\t\t}\n\t}\n\n\tif (entskb->tstamp.tv64) {\n\t\tstruct nfqnl_msg_packet_timestamp ts;\n\t\tstruct timeval tv = ktime_to_timeval(entskb->tstamp);\n\t\tts.sec = cpu_to_be64(tv.tv_sec);\n\t\tts.usec = cpu_to_be64(tv.tv_usec);\n\n\t\tif (nla_put(skb, NFQA_TIMESTAMP, sizeof(ts), &ts))\n\t\t\tgoto nla_put_failure;\n\t}\n\n\tif ((queue->flags & NFQA_CFG_F_UID_GID) && entskb->sk &&\n\t nfqnl_put_sk_uidgid(skb, entskb->sk) < 0)\n\t\tgoto nla_put_failure;\n\n\tif (ct && nfqnl_ct_put(skb, ct, ctinfo) < 0)\n\t\tgoto nla_put_failure;\n\n\tif (cap_len > data_len &&\n\t nla_put_be32(skb, NFQA_CAP_LEN, htonl(cap_len)))\n\t\tgoto nla_put_failure;\n\n\tif (nfqnl_put_packet_info(skb, entskb, csum_verify))\n\t\tgoto nla_put_failure;\n\n\tif (data_len) {\n\t\tstruct nlattr *nla;\n\n\t\tif (skb_tailroom(skb) < sizeof(*nla) + hlen)\n\t\t\tgoto nla_put_failure;\n\n\t\tnla = (struct nlattr *)skb_put(skb, sizeof(*nla));\n\t\tnla->nla_type = NFQA_PAYLOAD;\n\t\tnla->nla_len = nla_attr_size(data_len);\n\n\t\tskb_zerocopy(skb, entskb, data_len, hlen);\n\t}\n\n\tnlh->nlmsg_len = skb->len;\n\treturn skb;\n\nnla_put_failure:\n\tkfree_skb(skb);\n\tnet_err_ratelimited(\"nf_queue: error creating packet message\\n\");\n\treturn NULL;\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: cert_hostcheck(const char *match_pattern, const char *hostname)\n{\n if(!match_pattern || !*match_pattern ||\n !hostname || !*hostname) /* sanity check */\n return 0;\n\n if(Curl_raw_equal(hostname, match_pattern)) /* trivial case */\n return 1;\n\n if(hostmatch(hostname,match_pattern) == HOST_MATCH)\n return 1;\n return 0;\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 size_t curl_read_cb(void *ptr, size_t size, size_t nmemb, void *opaque)\n{\n CURLState *s = ((CURLState*)opaque);\n size_t realsize = size * nmemb;\n int i;\n\n DPRINTF(\"CURL: Just reading %zd bytes\\n\", realsize);\n\n if (!s || !s->orig_buf)\n goto read_end;\n\n memcpy(s->orig_buf + s->buf_off, ptr, realsize);\n s->buf_off += realsize;\n\n for(i=0; iacb[i];\n\n if (!acb)\n continue;\n\n if ((s->buf_off >= acb->end)) {\n qemu_iovec_from_buf(acb->qiov, 0, s->orig_buf + acb->start,\n acb->end - acb->start);\n acb->common.cb(acb->common.opaque, 0);\n qemu_aio_release(acb);\n s->acb[i] = NULL;\n }\n }\n\nread_end:\n return realsize;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'curl: check data size before memcpy to local buffer. (CVE-2014-0144)\n\ncurl_read_cb is callback function for libcurl when data arrives. The\ndata size passed in here is not guaranteed to be within the range of\nrequest we submitted, so we may overflow the guest IO buffer. Check the\nreal size we have before memcpy to buffer to avoid overflow.\n\nSigned-off-by: Fam Zheng \nReviewed-by: Stefan Hajnoczi \nSigned-off-by: Kevin Wolf \nReviewed-by: Max Reitz \nSigned-off-by: Stefan Hajnoczi '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static unsigned xenvif_tx_build_gops(struct xenvif *vif, int budget)\n{\n\tstruct gnttab_map_grant_ref *gop = vif->tx_map_ops, *request_gop;\n\tstruct sk_buff *skb;\n\tint ret;\n\n\twhile (skb_queue_len(&vif->tx_queue) < budget) {\n\t\tstruct xen_netif_tx_request txreq;\n\t\tstruct xen_netif_tx_request txfrags[XEN_NETBK_LEGACY_SLOTS_MAX];\n\t\tstruct xen_netif_extra_info extras[XEN_NETIF_EXTRA_TYPE_MAX-1];\n\t\tu16 pending_idx;\n\t\tRING_IDX idx;\n\t\tint work_to_do;\n\t\tunsigned int data_len;\n\t\tpending_ring_idx_t index;\n\n\t\tif (vif->tx.sring->req_prod - vif->tx.req_cons >\n\t\t XEN_NETIF_TX_RING_SIZE) {\n\t\t\tnetdev_err(vif->dev,\n\t\t\t\t \"Impossible number of requests. \"\n\t\t\t\t \"req_prod %d, req_cons %d, size %ld\\n\",\n\t\t\t\t vif->tx.sring->req_prod, vif->tx.req_cons,\n\t\t\t\t XEN_NETIF_TX_RING_SIZE);\n\t\t\txenvif_fatal_tx_err(vif);\n\t\t\tcontinue;\n\t\t}\n\n\t\twork_to_do = RING_HAS_UNCONSUMED_REQUESTS(&vif->tx);\n\t\tif (!work_to_do)\n\t\t\tbreak;\n\n\t\tidx = vif->tx.req_cons;\n\t\trmb(); /* Ensure that we see the request before we copy it. */\n\t\tmemcpy(&txreq, RING_GET_REQUEST(&vif->tx, idx), sizeof(txreq));\n\n\t\t/* Credit-based scheduling. */\n\t\tif (txreq.size > vif->remaining_credit &&\n\t\t tx_credit_exceeded(vif, txreq.size))\n\t\t\tbreak;\n\n\t\tvif->remaining_credit -= txreq.size;\n\n\t\twork_to_do--;\n\t\tvif->tx.req_cons = ++idx;\n\n\t\tmemset(extras, 0, sizeof(extras));\n\t\tif (txreq.flags & XEN_NETTXF_extra_info) {\n\t\t\twork_to_do = xenvif_get_extras(vif, extras,\n\t\t\t\t\t\t work_to_do);\n\t\t\tidx = vif->tx.req_cons;\n\t\t\tif (unlikely(work_to_do < 0))\n\t\t\t\tbreak;\n\t\t}\n\n\t\tret = xenvif_count_requests(vif, &txreq, txfrags, work_to_do);\n\t\tif (unlikely(ret < 0))\n\t\t\tbreak;\n\n\t\tidx += ret;\n\n\t\tif (unlikely(txreq.size < ETH_HLEN)) {\n\t\t\tnetdev_dbg(vif->dev,\n\t\t\t\t \"Bad packet size: %d\\n\", txreq.size);\n\t\t\txenvif_tx_err(vif, &txreq, idx);\n\t\t\tbreak;\n\t\t}\n\n\t\t/* No crossing a page as the payload mustn't fragment. */\n\t\tif (unlikely((txreq.offset + txreq.size) > PAGE_SIZE)) {\n\t\t\tnetdev_err(vif->dev,\n\t\t\t\t \"txreq.offset: %x, size: %u, end: %lu\\n\",\n\t\t\t\t txreq.offset, txreq.size,\n\t\t\t\t (txreq.offset&~PAGE_MASK) + txreq.size);\n\t\t\txenvif_fatal_tx_err(vif);\n\t\t\tbreak;\n\t\t}\n\n\t\tindex = pending_index(vif->pending_cons);\n\t\tpending_idx = vif->pending_ring[index];\n\n\t\tdata_len = (txreq.size > PKT_PROT_LEN &&\n\t\t\t ret < XEN_NETBK_LEGACY_SLOTS_MAX) ?\n\t\t\tPKT_PROT_LEN : txreq.size;\n\n\t\tskb = xenvif_alloc_skb(data_len);\n\t\tif (unlikely(skb == NULL)) {\n\t\t\tnetdev_dbg(vif->dev,\n\t\t\t\t \"Can't allocate a skb in start_xmit.\\n\");\n\t\t\txenvif_tx_err(vif, &txreq, idx);\n\t\t\tbreak;\n\t\t}\n\n\t\tif (extras[XEN_NETIF_EXTRA_TYPE_GSO - 1].type) {\n\t\t\tstruct xen_netif_extra_info *gso;\n\t\t\tgso = &extras[XEN_NETIF_EXTRA_TYPE_GSO - 1];\n\n\t\t\tif (xenvif_set_skb_gso(vif, skb, gso)) {\n\t\t\t\t/* Failure in xenvif_set_skb_gso is fatal. */\n\t\t\t\tkfree_skb(skb);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\txenvif_tx_create_gop(vif, pending_idx, &txreq, gop);\n\n\t\tgop++;\n\n\t\tXENVIF_TX_CB(skb)->pending_idx = pending_idx;\n\n\t\t__skb_put(skb, data_len);\n\n\t\tskb_shinfo(skb)->nr_frags = ret;\n\t\tif (data_len < txreq.size) {\n\t\t\tskb_shinfo(skb)->nr_frags++;\n\t\t\tfrag_set_pending_idx(&skb_shinfo(skb)->frags[0],\n\t\t\t\t\t pending_idx);\n\t\t} else {\n\t\t\tfrag_set_pending_idx(&skb_shinfo(skb)->frags[0],\n\t\t\t\t\t INVALID_PENDING_IDX);\n\t\t}\n\n\t\tvif->pending_cons++;\n\n\t\trequest_gop = xenvif_get_requests(vif, skb, txfrags, gop);\n\t\tif (request_gop == NULL) {\n\t\t\tkfree_skb(skb);\n\t\t\txenvif_tx_err(vif, &txreq, idx);\n\t\t\tbreak;\n\t\t}\n\t\tgop = request_gop;\n\n\t\t__skb_queue_tail(&vif->tx_queue, skb);\n\n\t\tvif->tx.req_cons = idx;\n\n\t\tif ((gop-vif->tx_map_ops) >= ARRAY_SIZE(vif->tx_map_ops))\n\t\t\tbreak;\n\t}\n\n\treturn gop - vif->tx_map_ops;\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: void ath_tx_aggr_sleep(struct ieee80211_sta *sta, struct ath_softc *sc,\n\t\t struct ath_node *an)\n{\n\tstruct ath_atx_tid *tid;\n\tstruct ath_atx_ac *ac;\n\tstruct ath_txq *txq;\n\tbool buffered;\n\tint tidno;\n\n\tfor (tidno = 0, tid = &an->tid[tidno];\n\t tidno < IEEE80211_NUM_TIDS; tidno++, tid++) {\n\n\t\tif (!tid->sched)\n\t\t\tcontinue;\n\n\t\tac = tid->ac;\n\t\ttxq = ac->txq;\n\n\t\tath_txq_lock(sc, txq);\n\n\t\tbuffered = ath_tid_has_buffered(tid);\n\n\t\ttid->sched = false;\n\t\tlist_del(&tid->list);\n\n\t\tif (ac->sched) {\n\t\t\tac->sched = false;\n\t\t\tlist_del(&ac->list);\n\t\t}\n\n\t\tath_txq_unlock(sc, txq);\n\n\t\tieee80211_sta_set_buffered(sta, tidno, buffered);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362', 'CWE-241'], 'message': 'ath9k: protect tid->sched check\n\nWe check tid->sched without a lock taken on ath_tx_aggr_sleep(). That\nis race condition which can result of doing list_del(&tid->list) twice\n(second time with poisoned list node) and cause crash like shown below:\n\n[424271.637220] BUG: unable to handle kernel paging request at 00100104\n[424271.637328] IP: [] ath_tx_aggr_sleep+0x62/0xe0 [ath9k]\n...\n[424271.639953] Call Trace:\n[424271.639998] [] ? ath9k_get_survey+0x110/0x110 [ath9k]\n[424271.640083] [] ath9k_sta_notify+0x42/0x50 [ath9k]\n[424271.640177] [] sta_ps_start+0x8f/0x1c0 [mac80211]\n[424271.640258] [] ? free_compound_page+0x2e/0x40\n[424271.640346] [] ieee80211_rx_handlers+0x9d5/0x2340 [mac80211]\n[424271.640437] [] ? kmem_cache_free+0x1d8/0x1f0\n[424271.640510] [] ? kfree_skbmem+0x34/0x90\n[424271.640578] [] ? put_page+0x2c/0x40\n[424271.640640] [] ? kfree_skbmem+0x34/0x90\n[424271.640706] [] ? kfree_skbmem+0x34/0x90\n[424271.640787] [] ? ieee80211_rx_handlers_result+0x73/0x1d0 [mac80211]\n[424271.640897] [] ieee80211_prepare_and_rx_handle+0x520/0xad0 [mac80211]\n[424271.641009] [] ? ieee80211_rx_handlers+0x2ed/0x2340 [mac80211]\n[424271.641104] [] ? ip_output+0x7e/0xd0\n[424271.641182] [] ieee80211_rx+0x307/0x7c0 [mac80211]\n[424271.641266] [] ath_rx_tasklet+0x88e/0xf70 [ath9k]\n[424271.641358] [] ? ieee80211_rx+0x1dc/0x7c0 [mac80211]\n[424271.641445] [] ath9k_tasklet+0xcb/0x130 [ath9k]\n\nBug report:\nhttps://bugzilla.kernel.org/show_bug.cgi?id=70551\n\nReported-and-tested-by: Max Sydorenko \nCc: stable@vger.kernel.org\nSigned-off-by: Stanislaw Gruszka \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: static ssize_t n_tty_write(struct tty_struct *tty, struct file *file,\n\t\t\t const unsigned char *buf, size_t nr)\n{\n\tconst unsigned char *b = buf;\n\tDECLARE_WAITQUEUE(wait, current);\n\tint c;\n\tssize_t retval = 0;\n\n\t/* Job control check -- must be done at start (POSIX.1 7.1.1.4). */\n\tif (L_TOSTOP(tty) && file->f_op->write != redirected_tty_write) {\n\t\tretval = tty_check_change(tty);\n\t\tif (retval)\n\t\t\treturn retval;\n\t}\n\n\tdown_read(&tty->termios_rwsem);\n\n\t/* Write out any echoed characters that are still pending */\n\tprocess_echoes(tty);\n\n\tadd_wait_queue(&tty->write_wait, &wait);\n\twhile (1) {\n\t\tset_current_state(TASK_INTERRUPTIBLE);\n\t\tif (signal_pending(current)) {\n\t\t\tretval = -ERESTARTSYS;\n\t\t\tbreak;\n\t\t}\n\t\tif (tty_hung_up_p(file) || (tty->link && !tty->link->count)) {\n\t\t\tretval = -EIO;\n\t\t\tbreak;\n\t\t}\n\t\tif (O_OPOST(tty)) {\n\t\t\twhile (nr > 0) {\n\t\t\t\tssize_t num = process_output_block(tty, b, nr);\n\t\t\t\tif (num < 0) {\n\t\t\t\t\tif (num == -EAGAIN)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tretval = num;\n\t\t\t\t\tgoto break_out;\n\t\t\t\t}\n\t\t\t\tb += num;\n\t\t\t\tnr -= num;\n\t\t\t\tif (nr == 0)\n\t\t\t\t\tbreak;\n\t\t\t\tc = *b;\n\t\t\t\tif (process_output(c, tty) < 0)\n\t\t\t\t\tbreak;\n\t\t\t\tb++; nr--;\n\t\t\t}\n\t\t\tif (tty->ops->flush_chars)\n\t\t\t\ttty->ops->flush_chars(tty);\n\t\t} else {\n\t\t\twhile (nr > 0) {\n\t\t\t\tc = tty->ops->write(tty, b, nr);\n\t\t\t\tif (c < 0) {\n\t\t\t\t\tretval = c;\n\t\t\t\t\tgoto break_out;\n\t\t\t\t}\n\t\t\t\tif (!c)\n\t\t\t\t\tbreak;\n\t\t\t\tb += c;\n\t\t\t\tnr -= c;\n\t\t\t}\n\t\t}\n\t\tif (!nr)\n\t\t\tbreak;\n\t\tif (file->f_flags & O_NONBLOCK) {\n\t\t\tretval = -EAGAIN;\n\t\t\tbreak;\n\t\t}\n\t\tup_read(&tty->termios_rwsem);\n\n\t\tschedule();\n\n\t\tdown_read(&tty->termios_rwsem);\n\t}\nbreak_out:\n\t__set_current_state(TASK_RUNNING);\n\tremove_wait_queue(&tty->write_wait, &wait);\n\tif (b - buf != nr && tty->fasync)\n\t\tset_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);\n\tup_read(&tty->termios_rwsem);\n\treturn (b - buf) ? b - buf : retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'n_tty: Fix n_tty_write crash when echoing in raw mode\n\nThe tty atomic_write_lock does not provide an exclusion guarantee for\nthe tty driver if the termios settings are LECHO & !OPOST. And since\nit is unexpected and not allowed to call TTY buffer helpers like\ntty_insert_flip_string concurrently, this may lead to crashes when\nconcurrect writers call pty_write. In that case the following two\nwriters:\n* the ECHOing from a workqueue and\n* pty_write from the process\nrace and can overflow the corresponding TTY buffer like follows.\n\nIf we look into tty_insert_flip_string_fixed_flag, there is:\n int space = __tty_buffer_request_room(port, goal, flags);\n struct tty_buffer *tb = port->buf.tail;\n ...\n memcpy(char_buf_ptr(tb, tb->used), chars, space);\n ...\n tb->used += space;\n\nso the race of the two can result in something like this:\n A B\n__tty_buffer_request_room\n __tty_buffer_request_room\nmemcpy(buf(tb->used), ...)\ntb->used += space;\n memcpy(buf(tb->used), ...) ->BOOM\n\nB's memcpy is past the tty_buffer due to the previous A's tb->used\nincrement.\n\nSince the N_TTY line discipline input processing can output\nconcurrently with a tty write, obtain the N_TTY ldisc output_lock to\nserialize echo output with normal tty writes. This ensures the tty\nbuffer helper tty_insert_flip_string is not called concurrently and\neverything is fine.\n\nNote that this is nicely reproducible by an ordinary user using\nforkpty and some setup around that (raw termios + ECHO). And it is\npresent in kernels at least after commit\nd945cb9cce20ac7143c2de8d88b187f62db99bdc (pty: Rework the pty layer to\nuse the normal buffering logic) in 2.6.31-rc3.\n\njs: add more info to the commit log\njs: switch to bool\njs: lock unconditionally\njs: lock only the tty->ops->write call\n\nReferences: CVE-2014-0196\nReported-and-tested-by: Jiri Slaby \nSigned-off-by: Peter Hurley \nSigned-off-by: Jiri Slaby \nCc: Linus Torvalds \nCc: Alan Cox \nCc: \nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int packet_diag_dump(struct sk_buff *skb, struct netlink_callback *cb)\n{\n\tint num = 0, s_num = cb->args[0];\n\tstruct packet_diag_req *req;\n\tstruct net *net;\n\tstruct sock *sk;\n\tbool may_report_filterinfo;\n\n\tnet = sock_net(skb->sk);\n\treq = nlmsg_data(cb->nlh);\n\tmay_report_filterinfo = ns_capable(net->user_ns, CAP_NET_ADMIN);\n\n\tmutex_lock(&net->packet.sklist_lock);\n\tsk_for_each(sk, &net->packet.sklist) {\n\t\tif (!net_eq(sock_net(sk), net))\n\t\t\tcontinue;\n\t\tif (num < s_num)\n\t\t\tgoto next;\n\n\t\tif (sk_diag_fill(sk, skb, req,\n\t\t\t\t may_report_filterinfo,\n\t\t\t\t sk_user_ns(NETLINK_CB(cb->skb).sk),\n\t\t\t\t NETLINK_CB(cb->skb).portid,\n\t\t\t\t cb->nlh->nlmsg_seq, NLM_F_MULTI,\n\t\t\t\t sock_i_ino(sk)) < 0)\n\t\t\tgoto done;\nnext:\n\t\tnum++;\n\t}\ndone:\n\tmutex_unlock(&net->packet.sklist_lock);\n\tcb->args[0] = num;\n\n\treturn skb->len;\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 xfrm_user_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh)\n{\n\tstruct net *net = sock_net(skb->sk);\n\tstruct nlattr *attrs[XFRMA_MAX+1];\n\tconst struct xfrm_link *link;\n\tint type, err;\n\n\ttype = nlh->nlmsg_type;\n\tif (type > XFRM_MSG_MAX)\n\t\treturn -EINVAL;\n\n\ttype -= XFRM_MSG_BASE;\n\tlink = &xfrm_dispatch[type];\n\n\t/* All operations require privileges, even GET */\n\tif (!ns_capable(net->user_ns, CAP_NET_ADMIN))\n\t\treturn -EPERM;\n\n\tif ((type == (XFRM_MSG_GETSA - XFRM_MSG_BASE) ||\n\t type == (XFRM_MSG_GETPOLICY - XFRM_MSG_BASE)) &&\n\t (nlh->nlmsg_flags & NLM_F_DUMP)) {\n\t\tif (link->dump == NULL)\n\t\t\treturn -EINVAL;\n\n\t\t{\n\t\t\tstruct netlink_dump_control c = {\n\t\t\t\t.dump = link->dump,\n\t\t\t\t.done = link->done,\n\t\t\t};\n\t\t\treturn netlink_dump_start(net->xfrm.nlsk, skb, nlh, &c);\n\t\t}\n\t}\n\n\terr = nlmsg_parse(nlh, xfrm_msg_min[type], attrs, XFRMA_MAX,\n\t\t\t xfrma_policy);\n\tif (err < 0)\n\t\treturn err;\n\n\tif (link->doit == NULL)\n\t\treturn -EINVAL;\n\n\treturn link->doit(skb, nlh, attrs);\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 crypto_user_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh)\n{\n\tstruct nlattr *attrs[CRYPTOCFGA_MAX+1];\n\tconst struct crypto_link *link;\n\tint type, err;\n\n\ttype = nlh->nlmsg_type;\n\tif (type > CRYPTO_MSG_MAX)\n\t\treturn -EINVAL;\n\n\ttype -= CRYPTO_MSG_BASE;\n\tlink = &crypto_dispatch[type];\n\n\tif (!capable(CAP_NET_ADMIN))\n\t\treturn -EPERM;\n\n\tif ((type == (CRYPTO_MSG_GETALG - CRYPTO_MSG_BASE) &&\n\t (nlh->nlmsg_flags & NLM_F_DUMP))) {\n\t\tstruct crypto_alg *alg;\n\t\tu16 dump_alloc = 0;\n\n\t\tif (link->dump == NULL)\n\t\t\treturn -EINVAL;\n\n\t\tlist_for_each_entry(alg, &crypto_alg_list, cra_list)\n\t\t\tdump_alloc += CRYPTO_REPORT_MAXSIZE;\n\n\t\t{\n\t\t\tstruct netlink_dump_control c = {\n\t\t\t\t.dump = link->dump,\n\t\t\t\t.done = link->done,\n\t\t\t\t.min_dump_alloc = dump_alloc,\n\t\t\t};\n\t\t\treturn netlink_dump_start(crypto_nlsk, skb, nlh, &c);\n\t\t}\n\t}\n\n\terr = nlmsg_parse(nlh, crypto_msg_min[type], attrs, CRYPTOCFGA_MAX,\n\t\t\t crypto_policy);\n\tif (err < 0)\n\t\treturn err;\n\n\tif (link->doit == NULL)\n\t\treturn -EINVAL;\n\n\treturn link->doit(skb, nlh, attrs);\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: queue_unlock(struct futex_q *q, struct futex_hash_bucket *hb)\n{\n\tspin_unlock(&hb->lock);\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 apparmor_bprm_set_creds(struct linux_binprm *bprm)\n{\n\tstruct aa_task_cxt *cxt;\n\tstruct aa_profile *profile, *new_profile = NULL;\n\tstruct aa_namespace *ns;\n\tchar *buffer = NULL;\n\tunsigned int state;\n\tstruct file_perms perms = {};\n\tstruct path_cond cond = {\n\t\tbprm->file->f_path.dentry->d_inode->i_uid,\n\t\tbprm->file->f_path.dentry->d_inode->i_mode\n\t};\n\tconst char *name = NULL, *target = NULL, *info = NULL;\n\tint error = cap_bprm_set_creds(bprm);\n\tif (error)\n\t\treturn error;\n\n\tif (bprm->cred_prepared)\n\t\treturn 0;\n\n\tcxt = bprm->cred->security;\n\tBUG_ON(!cxt);\n\n\tprofile = aa_get_profile(aa_newest_version(cxt->profile));\n\t/*\n\t * get the namespace from the replacement profile as replacement\n\t * can change the namespace\n\t */\n\tns = profile->ns;\n\tstate = profile->file.start;\n\n\t/* buffer freed below, name is pointer into buffer */\n\terror = aa_path_name(&bprm->file->f_path, profile->path_flags, &buffer,\n\t\t\t &name, &info);\n\tif (error) {\n\t\tif (profile->flags &\n\t\t (PFLAG_IX_ON_NAME_ERROR | PFLAG_UNCONFINED))\n\t\t\terror = 0;\n\t\tname = bprm->filename;\n\t\tgoto audit;\n\t}\n\n\t/* Test for onexec first as onexec directives override other\n\t * x transitions.\n\t */\n\tif (unconfined(profile)) {\n\t\t/* unconfined task */\n\t\tif (cxt->onexec)\n\t\t\t/* change_profile on exec already been granted */\n\t\t\tnew_profile = aa_get_profile(cxt->onexec);\n\t\telse\n\t\t\tnew_profile = find_attach(ns, &ns->base.profiles, name);\n\t\tif (!new_profile)\n\t\t\tgoto cleanup;\n\t\tgoto apply;\n\t}\n\n\t/* find exec permissions for name */\n\tstate = aa_str_perms(profile->file.dfa, state, name, &cond, &perms);\n\tif (cxt->onexec) {\n\t\tstruct file_perms cp;\n\t\tinfo = \"change_profile onexec\";\n\t\tif (!(perms.allow & AA_MAY_ONEXEC))\n\t\t\tgoto audit;\n\n\t\t/* test if this exec can be paired with change_profile onexec.\n\t\t * onexec permission is linked to exec with a standard pairing\n\t\t * exec\\0change_profile\n\t\t */\n\t\tstate = aa_dfa_null_transition(profile->file.dfa, state);\n\t\tcp = change_profile_perms(profile, cxt->onexec->ns,\n\t\t\t\t\t cxt->onexec->base.name,\n\t\t\t\t\t AA_MAY_ONEXEC, state);\n\n\t\tif (!(cp.allow & AA_MAY_ONEXEC))\n\t\t\tgoto audit;\n\t\tnew_profile = aa_get_profile(aa_newest_version(cxt->onexec));\n\t\tgoto apply;\n\t}\n\n\tif (perms.allow & MAY_EXEC) {\n\t\t/* exec permission determine how to transition */\n\t\tnew_profile = x_to_profile(profile, name, perms.xindex);\n\t\tif (!new_profile) {\n\t\t\tif (perms.xindex & AA_X_INHERIT) {\n\t\t\t\t/* (p|c|n)ix - don't change profile but do\n\t\t\t\t * use the newest version, which was picked\n\t\t\t\t * up above when getting profile\n\t\t\t\t */\n\t\t\t\tinfo = \"ix fallback\";\n\t\t\t\tnew_profile = aa_get_profile(profile);\n\t\t\t\tgoto x_clear;\n\t\t\t} else if (perms.xindex & AA_X_UNCONFINED) {\n\t\t\t\tnew_profile = aa_get_profile(ns->unconfined);\n\t\t\t\tinfo = \"ux fallback\";\n\t\t\t} else {\n\t\t\t\terror = -ENOENT;\n\t\t\t\tinfo = \"profile not found\";\n\t\t\t}\n\t\t}\n\t} else if (COMPLAIN_MODE(profile)) {\n\t\t/* no exec permission - are we in learning mode */\n\t\tnew_profile = aa_new_null_profile(profile, 0);\n\t\tif (!new_profile) {\n\t\t\terror = -ENOMEM;\n\t\t\tinfo = \"could not create null profile\";\n\t\t} else {\n\t\t\terror = -EACCES;\n\t\t\ttarget = new_profile->base.hname;\n\t\t}\n\t\tperms.xindex |= AA_X_UNSAFE;\n\t} else\n\t\t/* fail exec */\n\t\terror = -EACCES;\n\n\tif (!new_profile)\n\t\tgoto audit;\n\n\tif (bprm->unsafe & LSM_UNSAFE_SHARE) {\n\t\t/* FIXME: currently don't mediate shared state */\n\t\t;\n\t}\n\n\tif (bprm->unsafe & (LSM_UNSAFE_PTRACE | LSM_UNSAFE_PTRACE_CAP)) {\n\t\terror = may_change_ptraced_domain(current, new_profile);\n\t\tif (error) {\n\t\t\taa_put_profile(new_profile);\n\t\t\tgoto audit;\n\t\t}\n\t}\n\n\t/* Determine if secure exec is needed.\n\t * Can be at this point for the following reasons:\n\t * 1. unconfined switching to confined\n\t * 2. confined switching to different confinement\n\t * 3. confined switching to unconfined\n\t *\n\t * Cases 2 and 3 are marked as requiring secure exec\n\t * (unless policy specified \"unsafe exec\")\n\t *\n\t * bprm->unsafe is used to cache the AA_X_UNSAFE permission\n\t * to avoid having to recompute in secureexec\n\t */\n\tif (!(perms.xindex & AA_X_UNSAFE)) {\n\t\tAA_DEBUG(\"scrubbing environment variables for %s profile=%s\\n\",\n\t\t\t name, new_profile->base.hname);\n\t\tbprm->unsafe |= AA_SECURE_X_NEEDED;\n\t}\napply:\n\ttarget = new_profile->base.hname;\n\t/* when transitioning profiles clear unsafe personality bits */\n\tbprm->per_clear |= PER_CLEAR_ON_SETID;\n\nx_clear:\n\taa_put_profile(cxt->profile);\n\t/* transfer new profile reference will be released when cxt is freed */\n\tcxt->profile = new_profile;\n\n\t/* clear out all temporary/transitional state from the context */\n\taa_put_profile(cxt->previous);\n\taa_put_profile(cxt->onexec);\n\tcxt->previous = NULL;\n\tcxt->onexec = NULL;\n\tcxt->token = 0;\n\naudit:\n\terror = aa_audit_file(profile, &perms, GFP_KERNEL, OP_EXEC, MAY_EXEC,\n\t\t\t name, target, cond.uid, info, error);\n\ncleanup:\n\taa_put_profile(profile);\n\tkfree(buffer);\n\n\treturn error;\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: sdap_ad_tokengroups_get_posix_members(TALLOC_CTX *mem_ctx,\n struct sdap_ad_tokengroups_initgr_posix_state *state,\n size_t num_sids,\n char **sids,\n size_t *_num_missing,\n char ***_missing,\n size_t *_num_valid,\n char ***_valid_groups)\n{\n TALLOC_CTX *tmp_ctx = NULL;\n struct sss_domain_info *domain = NULL;\n struct ldb_message *msg = NULL;\n const char *attrs[] = {SYSDB_NAME, SYSDB_POSIX, NULL};\n const char *is_posix = NULL;\n const char *name = NULL;\n char *sid = NULL;\n char **valid_groups = NULL;\n size_t num_valid_groups;\n char **missing_sids = NULL;\n size_t num_missing_sids;\n size_t i;\n errno_t ret;\n\n tmp_ctx = talloc_new(NULL);\n if (tmp_ctx == NULL) {\n DEBUG(SSSDBG_CRIT_FAILURE, \"talloc_new() failed\\n\");\n ret = ENOMEM;\n goto done;\n }\n\n num_valid_groups = 0;\n valid_groups = talloc_zero_array(tmp_ctx, char*, num_sids + 1);\n if (valid_groups == NULL) {\n ret = ENOMEM;\n goto done;\n }\n\n num_missing_sids = 0;\n missing_sids = talloc_zero_array(tmp_ctx, char*, num_sids + 1);\n if (missing_sids == NULL) {\n ret = ENOMEM;\n goto done;\n }\n\n /* For each SID check if it is already present in the cache. If yes, we\n * will get name of the group and update the membership. Otherwise we need\n * to remember the SID and download missing groups one by one. */\n for (i = 0; i < num_sids; i++) {\n sid = sids[i];\n DEBUG(SSSDBG_TRACE_LIBS, \"Processing membership SID [%s]\\n\", sid);\n\n domain = sss_get_domain_by_sid_ldap_fallback(state->domain, sid);\n if (domain == NULL) {\n DEBUG(SSSDBG_MINOR_FAILURE, \"Domain not found for SID %s\\n\", sid);\n continue;\n }\n\n ret = sysdb_search_group_by_sid_str(tmp_ctx, domain->sysdb, domain,\n sid, attrs, &msg);\n if (ret == EOK) {\n is_posix = ldb_msg_find_attr_as_string(msg, SYSDB_POSIX, NULL);\n if (is_posix != NULL && strcmp(is_posix, \"FALSE\") == 0) {\n /* skip non-posix group */\n continue;\n }\n\n /* we will update membership of this group */\n name = ldb_msg_find_attr_as_string(msg, SYSDB_NAME, NULL);\n if (name == NULL) {\n DEBUG(SSSDBG_MINOR_FAILURE,\n \"Could not retrieve group name from sysdb\\n\");\n ret = EINVAL;\n goto done;\n }\n\n valid_groups[num_valid_groups] = sysdb_group_strdn(valid_groups,\n domain->name,\n name);\n if (valid_groups[num_valid_groups] == NULL) {\n ret = ENOMEM;\n goto done;\n }\n num_valid_groups++;\n } else if (ret == ENOENT) {\n if (_missing != NULL) {\n /* we need to download this group */\n missing_sids[num_missing_sids] = talloc_steal(missing_sids,\n sid);\n num_missing_sids++;\n\n DEBUG(SSSDBG_TRACE_FUNC, \"Missing SID %s will be downloaded\\n\",\n sid);\n }\n\n /* else: We have downloaded missing groups but some of them may\n * remained missing because they are outside of search base. We\n * will just ignore them and continue with the next group. */\n } else {\n DEBUG(SSSDBG_MINOR_FAILURE, \"Could not look up SID %s in sysdb: \"\n \"[%s]\\n\", sid, strerror(ret));\n goto done;\n }\n }\n\n valid_groups[num_valid_groups] = NULL;\n missing_sids[num_missing_sids] = NULL;\n\n /* return list of missing groups */\n if (_missing != NULL) {\n *_missing = talloc_steal(mem_ctx, missing_sids);\n *_num_missing = num_missing_sids;\n }\n\n /* return list of missing groups */\n if (_valid_groups != NULL) {\n *_valid_groups = talloc_steal(mem_ctx, valid_groups);\n *_num_valid = num_valid_groups;\n }\n\n ret = EOK;\n\ndone:\n talloc_free(tmp_ctx);\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'AD: process non-posix nested groups using tokenGroups\n\nWhen initgr is performed for AD supporting tokenGroups, do not skip\nnon-posix groups.\n\nResolves:\nhttps://fedorahosted.org/sssd/ticket/2343\n\nReviewed-by: Michal \u017didek \n(cherry picked from commit 4932db6258ccfb612a3a28eb6a618c2f042b9d58)'" }, { "text": "[INST] Given the following code containing errors, provide Common 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_read_value_type (asn1_node root, const char *name, void *ivalue,\n\t\t int *len, unsigned int *etype)\n{\n asn1_node node, p, p2;\n int len2, len3, result;\n int value_size = *len;\n unsigned char *value = ivalue;\n unsigned type;\n\n node = asn1_find_node (root, name);\n if (node == NULL)\n return ASN1_ELEMENT_NOT_FOUND;\n\n type = type_field (node->type);\n\n if ((type != ASN1_ETYPE_NULL) &&\n (type != ASN1_ETYPE_CHOICE) &&\n !(node->type & CONST_DEFAULT) && !(node->type & CONST_ASSIGN) &&\n (node->value == NULL))\n return ASN1_VALUE_NOT_FOUND;\n\n if (etype)\n *etype = type;\n switch (type)\n {\n case ASN1_ETYPE_NULL:\n PUT_STR_VALUE (value, value_size, \"NULL\");\n break;\n case ASN1_ETYPE_BOOLEAN:\n if ((node->type & CONST_DEFAULT) && (node->value == NULL))\n\t{\n\t p = node->down;\n\t while (type_field (p->type) != ASN1_ETYPE_DEFAULT)\n\t p = p->right;\n\t if (p->type & CONST_TRUE)\n\t {\n\t PUT_STR_VALUE (value, value_size, \"TRUE\");\n\t }\n\t else\n\t {\n\t PUT_STR_VALUE (value, value_size, \"FALSE\");\n\t }\n\t}\n else if (node->value[0] == 'T')\n\t{\n\t PUT_STR_VALUE (value, value_size, \"TRUE\");\n\t}\n else\n\t{\n\t PUT_STR_VALUE (value, value_size, \"FALSE\");\n\t}\n break;\n case ASN1_ETYPE_INTEGER:\n case ASN1_ETYPE_ENUMERATED:\n if ((node->type & CONST_DEFAULT) && (node->value == NULL))\n\t{\n\t p = node->down;\n\t while (type_field (p->type) != ASN1_ETYPE_DEFAULT)\n\t p = p->right;\n\t if ((isdigit (p->value[0])) || (p->value[0] == '-')\n\t || (p->value[0] == '+'))\n\t {\n\t result = _asn1_convert_integer\n\t\t (p->value, value, value_size, len);\n if (result != ASN1_SUCCESS)\n\t\treturn result;\n\t }\n\t else\n\t {\t\t\t/* is an identifier like v1 */\n\t p2 = node->down;\n\t while (p2)\n\t\t{\n\t\t if (type_field (p2->type) == ASN1_ETYPE_CONSTANT)\n\t\t {\n\t\t if (!_asn1_strcmp (p2->name, p->value))\n\t\t\t{\n\t\t\t result = _asn1_convert_integer\n\t\t\t (p2->value, value, value_size,\n\t\t\t len);\n\t\t\t if (result != ASN1_SUCCESS)\n\t\t\t return result;\n\t\t\t break;\n\t\t\t}\n\t\t }\n\t\t p2 = p2->right;\n\t\t}\n\t }\n\t}\n else\n\t{\n\t len2 = -1;\n\t result = asn1_get_octet_der\n\t (node->value, node->value_len, &len2, value, value_size,\n\t len);\n if (result != ASN1_SUCCESS)\n\t return result;\n\t}\n break;\n case ASN1_ETYPE_OBJECT_ID:\n if (node->type & CONST_ASSIGN)\n\t{\n\t value[0] = 0;\n\t p = node->down;\n\t while (p)\n\t {\n\t if (type_field (p->type) == ASN1_ETYPE_CONSTANT)\n\t\t{\n\t\t ADD_STR_VALUE (value, value_size, p->value);\n\t\t if (p->right)\n\t\t {\n\t\t ADD_STR_VALUE (value, value_size, \".\");\n\t\t }\n\t\t}\n\t p = p->right;\n\t }\n\t *len = _asn1_strlen (value) + 1;\n\t}\n else if ((node->type & CONST_DEFAULT) && (node->value == NULL))\n\t{\n\t p = node->down;\n\t while (type_field (p->type) != ASN1_ETYPE_DEFAULT)\n\t p = p->right;\n\t PUT_STR_VALUE (value, value_size, p->value);\n\t}\n else\n\t{\n\t PUT_STR_VALUE (value, value_size, node->value);\n\t}\n break;\n case ASN1_ETYPE_GENERALIZED_TIME:\n case ASN1_ETYPE_UTC_TIME:\n PUT_AS_STR_VALUE (value, value_size, node->value, node->value_len);\n break;\n case ASN1_ETYPE_OCTET_STRING:\n case ASN1_ETYPE_GENERALSTRING:\n case ASN1_ETYPE_NUMERIC_STRING:\n case ASN1_ETYPE_IA5_STRING:\n case ASN1_ETYPE_TELETEX_STRING:\n case ASN1_ETYPE_PRINTABLE_STRING:\n case ASN1_ETYPE_UNIVERSAL_STRING:\n case ASN1_ETYPE_BMP_STRING:\n case ASN1_ETYPE_UTF8_STRING:\n case ASN1_ETYPE_VISIBLE_STRING:\n len2 = -1;\n result = asn1_get_octet_der\n\t (node->value, node->value_len, &len2, value, value_size,\n\t len);\n if (result != ASN1_SUCCESS)\n\treturn result;\n break;\n case ASN1_ETYPE_BIT_STRING:\n len2 = -1;\n result = asn1_get_bit_der\n\t (node->value, node->value_len, &len2, value, value_size,\n\t len);\n if (result != ASN1_SUCCESS)\n\treturn result;\n break;\n case ASN1_ETYPE_CHOICE:\n PUT_STR_VALUE (value, value_size, node->down->name);\n break;\n case ASN1_ETYPE_ANY:\n len3 = -1;\n len2 = asn1_get_length_der (node->value, node->value_len, &len3);\n if (len2 < 0)\n\treturn ASN1_DER_ERROR;\n PUT_VALUE (value, value_size, node->value + len3, len2);\n break;\n default:\n return ASN1_ELEMENT_NOT_FOUND;\n break;\n }\n return ASN1_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'safer usage of memcpy().'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (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\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\tif (pi_state != NULL) {\n\t\t/*\n\t\t * We will have to lookup the pi_state again, so free this one\n\t\t * to keep the accounting correct.\n\t\t */\n\t\tfree_pi_state(pi_state);\n\t\tpi_state = NULL;\n\t}\n\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 */\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\n\t\t\t * space value of uaddr2 should be vpid. It\n\t\t\t * cannot be changed by the top waiter as it\n\t\t\t * is blocked on hb2 lock if it tries to do\n\t\t\t * so. If something fiddled with it behind our\n\t\t\t * back the pi state lookup might unearth\n\t\t\t * it. So we rather use the known value than\n\t\t\t * rereading and handing potential crap to\n\t\t\t * lookup_pi_state.\n\t\t\t */\n\t\t\tret = lookup_pi_state(ret, hb2, &key2, &pi_state, NULL);\n\t\t}\n\n\t\tswitch (ret) {\n\t\tcase 0:\n\t\t\tbreak;\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/* The owner was exiting, try again. */\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\twake_futex(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/* Prepare the waiter to take the rt_mutex. */\n\t\t\tatomic_inc(&pi_state->refcount);\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, 1);\n\t\t\tif (ret == 1) {\n\t\t\t\t/* We got the lock. */\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/* -EDEADLK */\n\t\t\t\tthis->pi_state = NULL;\n\t\t\t\tfree_pi_state(pi_state);\n\t\t\t\tgoto out_unlock;\n\t\t\t}\n\t\t}\n\t\trequeue_futex(this, hb1, hb2, &key2);\n\t\tdrop_count++;\n\t}\n\nout_unlock:\n\tdouble_unlock_hb(hb1, hb2);\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\tif (pi_state != NULL)\n\t\tfree_pi_state(pi_state);\n\treturn ret ? ret : task_count;\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: 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, APLOG_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, APLOG_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, APLOG_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, APLOG_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, APLOG_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, APLOG_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, APLOG_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, APLOG_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, APLOG_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, APLOG_ALERT, errno, wsgi_server,\n \"mod_wsgi (pid=%d): Unable to change to uid=%ld.\",\n getpid(), (long)daemon->group->uid);\n\n /*\n * On true UNIX systems this should always succeed at\n * this point. With certain Linux kernel versions though\n * we can get back EAGAIN where the target user had\n * reached their process limit. In that case will be left\n * running as wrong user. Just exit on all failures to be\n * safe. Don't die immediately to avoid a fork bomb.\n */\n\n sleep(20);\n\n exit(-1);\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, APLOG_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-254'], 'message': 'When there is any sort of error in setting up daemon process group, kill the process rather than risk running in an unexpected 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: unsigned int FUZ_rand(unsigned int* src)\n{\n U32 rand32 = *src;\n rand32 *= PRIME1;\n rand32 += PRIME2;\n rand32 = FUZ_rotl32(rand32, 13);\n *src = rand32;\n return rand32;\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(struct task_struct *child, addr_t addr, addr_t data)\n{\n\tstruct user *dummy = NULL;\n\taddr_t offset;\n\n\tif (addr < (addr_t) &dummy->regs.acrs) {\n\t\t/*\n\t\t * psw and gprs are stored on the stack\n\t\t */\n\t\tif (addr == (addr_t) &dummy->regs.psw.mask) {\n\t\t\tunsigned long mask = PSW_MASK_USER;\n\n\t\t\tmask |= is_ri_task(child) ? PSW_MASK_RI : 0;\n\t\t\tif ((data & ~mask) != PSW_USER_BITS)\n\t\t\t\treturn -EINVAL;\n\t\t\tif ((data & PSW_MASK_EA) && !(data & PSW_MASK_BA))\n\t\t\t\treturn -EINVAL;\n\t\t}\n\t\t*(addr_t *)((addr_t) &task_pt_regs(child)->psw + addr) = data;\n\n\t} else if (addr < (addr_t) (&dummy->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) &dummy->regs.acrs;\n#ifdef CONFIG_64BIT\n\t\t/*\n\t\t * Very special case: old & broken 64 bit gdb writing\n\t\t * to acrs[15] with a 64 bit value. Ignore the lower\n\t\t * half of the value and write the upper 32 bit to\n\t\t * acrs[15]. Sick...\n\t\t */\n\t\tif (addr == (addr_t) &dummy->regs.acrs[15])\n\t\t\tchild->thread.acrs[15] = (unsigned int) (data >> 32);\n\t\telse\n#endif\n\t\t*(addr_t *)((addr_t) &child->thread.acrs + offset) = data;\n\n\t} else if (addr == (addr_t) &dummy->regs.orig_gpr2) {\n\t\t/*\n\t\t * orig_gpr2 is stored on the kernel stack\n\t\t */\n\t\ttask_pt_regs(child)->orig_gpr2 = data;\n\n\t} else if (addr < (addr_t) &dummy->regs.fp_regs) {\n\t\t/*\n\t\t * prevent writes 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) (&dummy->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) &dummy->regs.fp_regs.fpc)\n\t\t\tif ((unsigned int) data != 0 ||\n\t\t\t test_fp_ctl(data >> (BITS_PER_LONG - 32)))\n\t\t\t\treturn -EINVAL;\n\t\toffset = addr - (addr_t) &dummy->regs.fp_regs;\n\t\t*(addr_t *)((addr_t) &child->thread.fp_regs + offset) = data;\n\n\t} else if (addr < (addr_t) (&dummy->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) &dummy->regs.per_info;\n\t\t__poke_user_per(child, addr, data);\n\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: acc_ctx_cont(OM_uint32 *minstat,\n\t gss_buffer_t buf,\n\t gss_ctx_id_t *ctx,\n\t gss_buffer_t *responseToken,\n\t gss_buffer_t *mechListMIC,\n\t OM_uint32 *negState,\n\t send_token_flag *return_token)\n{\n\tOM_uint32 ret, tmpmin;\n\tgss_OID supportedMech;\n\tspnego_gss_ctx_id_t sc;\n\tunsigned int len;\n\tunsigned char *ptr, *bufstart;\n\n\tsc = (spnego_gss_ctx_id_t)*ctx;\n\tret = GSS_S_DEFECTIVE_TOKEN;\n\t*negState = REJECT;\n\t*minstat = 0;\n\tsupportedMech = GSS_C_NO_OID;\n\t*return_token = ERROR_TOKEN_SEND;\n\t*responseToken = *mechListMIC = GSS_C_NO_BUFFER;\n\n\tptr = bufstart = buf->value;\n#define REMAIN (buf->length - (ptr - bufstart))\n\tif (REMAIN > INT_MAX)\n\t\treturn GSS_S_DEFECTIVE_TOKEN;\n\n\t/*\n\t * Attempt to work with old Sun SPNEGO.\n\t */\n\tif (*ptr == HEADER_ID) {\n\t\tret = g_verify_token_header(gss_mech_spnego,\n\t\t\t\t\t &len, &ptr, 0, REMAIN);\n\t\tif (ret) {\n\t\t\t*minstat = ret;\n\t\t\treturn GSS_S_DEFECTIVE_TOKEN;\n\t\t}\n\t}\n\tif (*ptr != (CONTEXT | 0x01)) {\n\t\treturn GSS_S_DEFECTIVE_TOKEN;\n\t}\n\tret = get_negTokenResp(minstat, ptr, REMAIN,\n\t\t\t negState, &supportedMech,\n\t\t\t responseToken, mechListMIC);\n\tif (ret != GSS_S_COMPLETE)\n\t\tgoto cleanup;\n\n\tif (*responseToken == GSS_C_NO_BUFFER &&\n\t *mechListMIC == GSS_C_NO_BUFFER) {\n\n\t\tret = GSS_S_DEFECTIVE_TOKEN;\n\t\tgoto cleanup;\n\t}\n\tif (supportedMech != GSS_C_NO_OID) {\n\t\tret = GSS_S_DEFECTIVE_TOKEN;\n\t\tgoto cleanup;\n\t}\n\tsc->firstpass = 0;\n\t*negState = ACCEPT_INCOMPLETE;\n\t*return_token = CONT_TOKEN_SEND;\ncleanup:\n\tif (supportedMech != GSS_C_NO_OID) {\n\t\tgeneric_gss_release_oid(&tmpmin, &supportedMech);\n\t}\n\treturn ret;\n#undef REMAIN\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix null deref in SPNEGO acceptor [CVE-2014-4344]\n\nWhen processing a continuation token, acc_ctx_cont was dereferencing\nthe initial byte of the token without checking the length. This could\nresult in a null dereference.\n\nCVE-2014-4344:\n\nIn MIT krb5 1.5 and newer, an unauthenticated or partially\nauthenticated remote attacker can cause a NULL dereference and\napplication crash during a SPNEGO negotiation by sending an empty\ntoken as the second or later context token from initiator to acceptor.\nThe attacker must provide at least one valid context token in the\nsecurity context negotiation before sending the empty token. This can\nbe done by an unauthenticated attacker by forcing SPNEGO to\nrenegotiate the underlying mechanism, or by using IAKERB to wrap an\nunauthenticated AS-REQ as the first token.\n\n CVSSv2 Vector: AV:N/AC:L/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C\n\n[kaduk@mit.edu: CVE summary, CVSSv2 vector]\n\nticket: 7970 (new)\nsubject: NULL dereference in SPNEGO acceptor for continuation tokens [CVE-2014-4344]\ntarget_version: 1.12.2\ntags: pullup'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int change_mount_flags(struct vfsmount *mnt, int ms_flags)\n{\n\tint error = 0;\n\tint readonly_request = 0;\n\n\tif (ms_flags & MS_RDONLY)\n\t\treadonly_request = 1;\n\tif (readonly_request == __mnt_is_readonly(mnt))\n\t\treturn 0;\n\n\tif (mnt->mnt_flags & MNT_LOCK_READONLY)\n\t\treturn -EPERM;\n\n\tif (readonly_request)\n\t\terror = mnt_make_readonly(real_mount(mnt));\n\telse\n\t\t__mnt_unmake_readonly(real_mount(mnt));\n\treturn error;\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 vbe_ioport_write_data(void *opaque, uint32_t addr, uint32_t val)\n{\n VGACommonState *s = opaque;\n\n if (s->vbe_index <= VBE_DISPI_INDEX_NB) {\n#ifdef DEBUG_BOCHS_VBE\n printf(\"VBE: write index=0x%x val=0x%x\\n\", s->vbe_index, val);\n#endif\n switch(s->vbe_index) {\n case VBE_DISPI_INDEX_ID:\n if (val == VBE_DISPI_ID0 ||\n val == VBE_DISPI_ID1 ||\n val == VBE_DISPI_ID2 ||\n val == VBE_DISPI_ID3 ||\n val == VBE_DISPI_ID4) {\n s->vbe_regs[s->vbe_index] = val;\n }\n break;\n case VBE_DISPI_INDEX_XRES:\n if ((val <= VBE_DISPI_MAX_XRES) && ((val & 7) == 0)) {\n s->vbe_regs[s->vbe_index] = val;\n }\n break;\n case VBE_DISPI_INDEX_YRES:\n if (val <= VBE_DISPI_MAX_YRES) {\n s->vbe_regs[s->vbe_index] = val;\n }\n break;\n case VBE_DISPI_INDEX_BPP:\n if (val == 0)\n val = 8;\n if (val == 4 || val == 8 || val == 15 ||\n val == 16 || val == 24 || val == 32) {\n s->vbe_regs[s->vbe_index] = val;\n }\n break;\n case VBE_DISPI_INDEX_BANK:\n if (s->vbe_regs[VBE_DISPI_INDEX_BPP] == 4) {\n val &= (s->vbe_bank_mask >> 2);\n } else {\n val &= s->vbe_bank_mask;\n }\n s->vbe_regs[s->vbe_index] = val;\n s->bank_offset = (val << 16);\n vga_update_memory_access(s);\n break;\n case VBE_DISPI_INDEX_ENABLE:\n if ((val & VBE_DISPI_ENABLED) &&\n !(s->vbe_regs[VBE_DISPI_INDEX_ENABLE] & VBE_DISPI_ENABLED)) {\n int h, shift_control;\n\n s->vbe_regs[VBE_DISPI_INDEX_VIRT_WIDTH] =\n s->vbe_regs[VBE_DISPI_INDEX_XRES];\n s->vbe_regs[VBE_DISPI_INDEX_VIRT_HEIGHT] =\n s->vbe_regs[VBE_DISPI_INDEX_YRES];\n s->vbe_regs[VBE_DISPI_INDEX_X_OFFSET] = 0;\n s->vbe_regs[VBE_DISPI_INDEX_Y_OFFSET] = 0;\n\n if (s->vbe_regs[VBE_DISPI_INDEX_BPP] == 4)\n s->vbe_line_offset = s->vbe_regs[VBE_DISPI_INDEX_XRES] >> 1;\n else\n s->vbe_line_offset = s->vbe_regs[VBE_DISPI_INDEX_XRES] *\n ((s->vbe_regs[VBE_DISPI_INDEX_BPP] + 7) >> 3);\n s->vbe_start_addr = 0;\n\n /* clear the screen (should be done in BIOS) */\n if (!(val & VBE_DISPI_NOCLEARMEM)) {\n memset(s->vram_ptr, 0,\n s->vbe_regs[VBE_DISPI_INDEX_YRES] * s->vbe_line_offset);\n }\n\n /* we initialize the VGA graphic mode (should be done\n in BIOS) */\n /* graphic mode + memory map 1 */\n s->gr[VGA_GFX_MISC] = (s->gr[VGA_GFX_MISC] & ~0x0c) | 0x04 |\n VGA_GR06_GRAPHICS_MODE;\n s->cr[VGA_CRTC_MODE] |= 3; /* no CGA modes */\n s->cr[VGA_CRTC_OFFSET] = s->vbe_line_offset >> 3;\n /* width */\n s->cr[VGA_CRTC_H_DISP] =\n (s->vbe_regs[VBE_DISPI_INDEX_XRES] >> 3) - 1;\n /* height (only meaningful if < 1024) */\n h = s->vbe_regs[VBE_DISPI_INDEX_YRES] - 1;\n s->cr[VGA_CRTC_V_DISP_END] = h;\n s->cr[VGA_CRTC_OVERFLOW] = (s->cr[VGA_CRTC_OVERFLOW] & ~0x42) |\n ((h >> 7) & 0x02) | ((h >> 3) & 0x40);\n /* line compare to 1023 */\n s->cr[VGA_CRTC_LINE_COMPARE] = 0xff;\n s->cr[VGA_CRTC_OVERFLOW] |= 0x10;\n s->cr[VGA_CRTC_MAX_SCAN] |= 0x40;\n\n if (s->vbe_regs[VBE_DISPI_INDEX_BPP] == 4) {\n shift_control = 0;\n s->sr[VGA_SEQ_CLOCK_MODE] &= ~8; /* no double line */\n } else {\n shift_control = 2;\n /* set chain 4 mode */\n s->sr[VGA_SEQ_MEMORY_MODE] |= VGA_SR04_CHN_4M;\n /* activate all planes */\n s->sr[VGA_SEQ_PLANE_WRITE] |= VGA_SR02_ALL_PLANES;\n }\n s->gr[VGA_GFX_MODE] = (s->gr[VGA_GFX_MODE] & ~0x60) |\n (shift_control << 5);\n s->cr[VGA_CRTC_MAX_SCAN] &= ~0x9f; /* no double scan */\n } else {\n /* XXX: the bios should do that */\n s->bank_offset = 0;\n }\n s->dac_8bit = (val & VBE_DISPI_8BIT_DAC) > 0;\n s->vbe_regs[s->vbe_index] = val;\n vga_update_memory_access(s);\n break;\n case VBE_DISPI_INDEX_VIRT_WIDTH:\n {\n int w, h, line_offset;\n\n if (val < s->vbe_regs[VBE_DISPI_INDEX_XRES])\n return;\n w = val;\n if (s->vbe_regs[VBE_DISPI_INDEX_BPP] == 4)\n line_offset = w >> 1;\n else\n line_offset = w * ((s->vbe_regs[VBE_DISPI_INDEX_BPP] + 7) >> 3);\n h = s->vbe_size / line_offset;\n /* XXX: support weird bochs semantics ? */\n if (h < s->vbe_regs[VBE_DISPI_INDEX_YRES])\n return;\n s->vbe_regs[VBE_DISPI_INDEX_VIRT_WIDTH] = w;\n s->vbe_regs[VBE_DISPI_INDEX_VIRT_HEIGHT] = h;\n s->vbe_line_offset = line_offset;\n }\n break;\n case VBE_DISPI_INDEX_X_OFFSET:\n case VBE_DISPI_INDEX_Y_OFFSET:\n {\n int x;\n s->vbe_regs[s->vbe_index] = val;\n s->vbe_start_addr = s->vbe_line_offset * s->vbe_regs[VBE_DISPI_INDEX_Y_OFFSET];\n x = s->vbe_regs[VBE_DISPI_INDEX_X_OFFSET];\n if (s->vbe_regs[VBE_DISPI_INDEX_BPP] == 4)\n s->vbe_start_addr += x >> 1;\n else\n s->vbe_start_addr += x * ((s->vbe_regs[VBE_DISPI_INDEX_BPP] + 7) >> 3);\n s->vbe_start_addr >>= 2;\n }\n break;\n default:\n break;\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'vbe: rework sanity checks\n\nPlug a bunch of holes in the bochs dispi interface parameter checking.\nAdd a function doing verification on all registers. Call that\nunconditionally on every register write. That way we should catch\neverything, even changing one register affecting the valid range of\nanother register.\n\nSome of the holes have been added by commit\ne9c6149f6ae6873f14a12eea554925b6aa4c4dec. Before that commit the\nmaximum possible framebuffer (VBE_DISPI_MAX_XRES * VBE_DISPI_MAX_YRES *\n32 bpp) has been smaller than the qemu vga memory (8MB) and the checking\nfor VBE_DISPI_MAX_XRES + VBE_DISPI_MAX_YRES + VBE_DISPI_MAX_BPP was ok.\n\nSome of the holes have been there forever, such as\nVBE_DISPI_INDEX_X_OFFSET and VBE_DISPI_INDEX_Y_OFFSET register writes\nlacking any verification.\n\nSecurity impact:\n\n(1) Guest can make the ui (gtk/vnc/...) use memory rages outside the vga\nframe buffer as source -> host memory leak. Memory isn't leaked to\nthe guest but to the vnc client though.\n\n(2) Qemu will segfault in case the memory range happens to include\nunmapped areas -> Guest can DoS itself.\n\nThe guest can not modify host memory, so I don't think this can be used\nby the guest to escape.\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: static int ceph_x_verify_authorizer_reply(struct ceph_auth_client *ac,\n\t\t\t\t\t struct ceph_authorizer *a, size_t len)\n{\n\tstruct ceph_x_authorizer *au = (void *)a;\n\tstruct ceph_x_ticket_handler *th;\n\tint ret = 0;\n\tstruct ceph_x_authorize_reply reply;\n\tvoid *p = au->reply_buf;\n\tvoid *end = p + sizeof(au->reply_buf);\n\n\tth = get_ticket_handler(ac, au->service);\n\tif (IS_ERR(th))\n\t\treturn PTR_ERR(th);\n\tret = ceph_x_decrypt(&th->session_key, &p, end, &reply, sizeof(reply));\n\tif (ret < 0)\n\t\treturn ret;\n\tif (ret != sizeof(reply))\n\t\treturn -EPERM;\n\n\tif (au->nonce + 1 != le64_to_cpu(reply.nonce_plus_one))\n\t\tret = -EPERM;\n\telse\n\t\tret = 0;\n\tdout(\"verify_authorizer_reply nonce %llx got %llx ret %d\\n\",\n\t au->nonce, le64_to_cpu(reply.nonce_plus_one), ret);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-119'], 'message': 'libceph: do not hard code max auth ticket len\n\nWe hard code cephx auth ticket buffer size to 256 bytes. This isn't\nenough for any moderate setups and, in case tickets themselves are not\nencrypted, leads to buffer overflows (ceph_x_decrypt() errors out, but\nceph_decode_copy() doesn't - it's just a memcpy() wrapper). Since the\nbuffer is allocated dynamically anyway, allocated it a bit later, at\nthe point where we know how much is going to be needed.\n\nFixes: http://tracker.ceph.com/issues/8979\n\nCc: stable@vger.kernel.org\nSigned-off-by: Ilya Dryomov \nReviewed-by: Sage Weil '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: evbuffer_ptr_memcmp(const struct evbuffer *buf, const struct evbuffer_ptr *pos,\n const char *mem, size_t len)\n{\n\tstruct evbuffer_chain *chain;\n\tsize_t position;\n\tint r;\n\n\tASSERT_EVBUFFER_LOCKED(buf);\n\n\tif (pos->pos + len > buf->total_len)\n\t\treturn -1;\n\n\tchain = pos->_internal.chain;\n\tposition = pos->_internal.pos_in_chain;\n\twhile (len && chain) {\n\t\tsize_t n_comparable;\n\t\tif (len + position > chain->off)\n\t\t\tn_comparable = chain->off - position;\n\t\telse\n\t\t\tn_comparable = len;\n\t\tr = memcmp(chain->buffer + chain->misalign + position, mem,\n\t\t n_comparable);\n\t\tif (r)\n\t\t\treturn r;\n\t\tmem += n_comparable;\n\t\tlen -= n_comparable;\n\t\tposition = 0;\n\t\tchain = chain->next;\n\t}\n\n\treturn 0;\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_prepend(struct evbuffer *buf, const void *data, size_t datlen)\n{\n\tstruct evbuffer_chain *chain, *tmp;\n\tint result = -1;\n\n\tEVBUFFER_LOCK(buf);\n\n\tif (buf->freeze_start) {\n\t\tgoto done;\n\t}\n\n\tchain = buf->first;\n\n\tif (chain == NULL) {\n\t\tchain = evbuffer_chain_new(datlen);\n\t\tif (!chain)\n\t\t\tgoto done;\n\t\tevbuffer_chain_insert(buf, chain);\n\t}\n\n\t/* we cannot touch immutable buffers */\n\tif ((chain->flags & EVBUFFER_IMMUTABLE) == 0) {\n\t\t/* If this chain is empty, we can treat it as\n\t\t * 'empty at the beginning' rather than 'empty at the end' */\n\t\tif (chain->off == 0)\n\t\t\tchain->misalign = chain->buffer_len;\n\n\t\tif ((size_t)chain->misalign >= datlen) {\n\t\t\t/* we have enough space to fit everything */\n\t\t\tmemcpy(chain->buffer + chain->misalign - datlen,\n\t\t\t data, datlen);\n\t\t\tchain->off += datlen;\n\t\t\tchain->misalign -= datlen;\n\t\t\tbuf->total_len += datlen;\n\t\t\tbuf->n_add_for_cb += datlen;\n\t\t\tgoto out;\n\t\t} else if (chain->misalign) {\n\t\t\t/* we can only fit some of the data. */\n\t\t\tmemcpy(chain->buffer,\n\t\t\t (char*)data + datlen - chain->misalign,\n\t\t\t (size_t)chain->misalign);\n\t\t\tchain->off += (size_t)chain->misalign;\n\t\t\tbuf->total_len += (size_t)chain->misalign;\n\t\t\tbuf->n_add_for_cb += (size_t)chain->misalign;\n\t\t\tdatlen -= (size_t)chain->misalign;\n\t\t\tchain->misalign = 0;\n\t\t}\n\t}\n\n\t/* we need to add another chain */\n\tif ((tmp = evbuffer_chain_new(datlen)) == NULL)\n\t\tgoto done;\n\tbuf->first = tmp;\n\tif (buf->last_with_datap == &buf->first)\n\t\tbuf->last_with_datap = &tmp->next;\n\n\ttmp->next = chain;\n\n\ttmp->off = datlen;\n\ttmp->misalign = tmp->buffer_len - datlen;\n\n\tmemcpy(tmp->buffer + tmp->misalign, data, datlen);\n\tbuf->total_len += datlen;\n\tbuf->n_add_for_cb += (size_t)chain->misalign;\n\nout:\n\tevbuffer_invoke_callbacks(buf);\n\tresult = 0;\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_ptr_set(struct evbuffer *buf, struct evbuffer_ptr *pos,\n size_t position, enum evbuffer_ptr_how how)\n{\n\tsize_t left = position;\n\tstruct evbuffer_chain *chain = NULL;\n\tint result = 0;\n\n\tEVBUFFER_LOCK(buf);\n\n\tswitch (how) {\n\tcase EVBUFFER_PTR_SET:\n\t\tchain = buf->first;\n\t\tpos->pos = position;\n\t\tposition = 0;\n\t\tbreak;\n\tcase EVBUFFER_PTR_ADD:\n\t\t/* this avoids iterating over all previous chains if\n\t\t we just want to advance the position */\n\t\tchain = pos->internal_.chain;\n\t\tpos->pos += position;\n\t\tposition = pos->internal_.pos_in_chain;\n\t\tbreak;\n\t}\n\n\twhile (chain && position + left >= chain->off) {\n\t\tleft -= chain->off - position;\n\t\tchain = chain->next;\n\t\tposition = 0;\n\t}\n\tif (chain) {\n\t\tpos->internal_.chain = chain;\n\t\tpos->internal_.pos_in_chain = position + left;\n\t} else if (left == 0) {\n\t\t/* The first byte in the (nonexistent) chain after the last chain */\n\t\tpos->internal_.chain = NULL;\n\t\tpos->internal_.pos_in_chain = 0;\n\t} else {\n\t\tPTR_NOT_FOUND(pos);\n\t\tresult = -1;\n\t}\n\n\tEVBUFFER_UNLOCK(buf);\n\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: xfs_da3_fixhashpath(\n\tstruct xfs_da_state\t*state,\n\tstruct xfs_da_state_path *path)\n{\n\tstruct xfs_da_state_blk\t*blk;\n\tstruct xfs_da_intnode\t*node;\n\tstruct xfs_da_node_entry *btree;\n\txfs_dahash_t\t\tlasthash=0;\n\tint\t\t\tlevel;\n\tint\t\t\tcount;\n\tstruct xfs_inode\t*dp = state->args->dp;\n\n\ttrace_xfs_da_fixhashpath(state->args);\n\n\tlevel = path->active-1;\n\tblk = &path->blk[ level ];\n\tswitch (blk->magic) {\n\tcase XFS_ATTR_LEAF_MAGIC:\n\t\tlasthash = xfs_attr_leaf_lasthash(blk->bp, &count);\n\t\tif (count == 0)\n\t\t\treturn;\n\t\tbreak;\n\tcase XFS_DIR2_LEAFN_MAGIC:\n\t\tlasthash = xfs_dir2_leafn_lasthash(dp, blk->bp, &count);\n\t\tif (count == 0)\n\t\t\treturn;\n\t\tbreak;\n\tcase XFS_DA_NODE_MAGIC:\n\t\tlasthash = xfs_da3_node_lasthash(dp, blk->bp, &count);\n\t\tif (count == 0)\n\t\t\treturn;\n\t\tbreak;\n\t}\n\tfor (blk--, level--; level >= 0; blk--, level--) {\n\t\tstruct xfs_da3_icnode_hdr nodehdr;\n\n\t\tnode = blk->bp->b_addr;\n\t\tdp->d_ops->node_hdr_from_disk(&nodehdr, node);\n\t\tbtree = dp->d_ops->node_tree_p(node);\n\t\tif (be32_to_cpu(btree->hashval) == lasthash)\n\t\t\tbreak;\n\t\tblk->hashval = lasthash;\n\t\tbtree[blk->index].hashval = cpu_to_be32(lasthash);\n\t\txfs_trans_log_buf(state->args->trans, blk->bp,\n\t\t\t\t XFS_DA_LOGRANGE(node, &btree[blk->index],\n\t\t\t\t\t\t sizeof(*btree)));\n\n\t\tlasthash = be32_to_cpu(btree[nodehdr.count - 1].hashval);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'xfs: fix directory hash ordering bug\n\nCommit f5ea1100 (\"xfs: add CRCs to dir2/da node blocks\") introduced\nin 3.10 incorrectly converted the btree hash index array pointer in\nxfs_da3_fixhashpath(). It resulted in the the current hash always\nbeing compared against the first entry in the btree rather than the\ncurrent block index into the btree block's hash entry array. As a\nresult, it was comparing the wrong hashes, and so could misorder the\nentries in the btree.\n\nFor most cases, this doesn't cause any problems as it requires hash\ncollisions to expose the ordering problem. However, when there are\nhash collisions within a directory there is a very good probability\nthat the entries will be ordered incorrectly and that actually\nmatters when duplicate hashes are placed into or removed from the\nbtree block hash entry array.\n\nThis bug results in an on-disk directory corruption and that results\nin directory verifier functions throwing corruption warnings into\nthe logs. While no data or directory entries are lost, access to\nthem may be compromised, and attempts to remove entries from a\ndirectory that has suffered from this corruption may result in a\nfilesystem shutdown. xfs_repair will fix the directory hash\nordering without data loss occuring.\n\n[dchinner: wrote useful a commit message]\n\ncc: \nReported-by: Hannes Frederic Sowa \nSigned-off-by: Mark Tinguely \nReviewed-by: Ben Myers \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: copy_ciphersuites(gnutls_session_t session,\n\t\t gnutls_buffer_st * cdata, int add_scsv)\n{\n\tint ret;\n\tuint8_t cipher_suites[MAX_CIPHERSUITE_SIZE + 2]; /* allow space for SCSV */\n\tint cipher_suites_size;\n\tsize_t init_length = cdata->length;\n\n\tret =\n\t _gnutls_supported_ciphersuites(session, cipher_suites,\n\t\t\t\t\t sizeof(cipher_suites) - 2);\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(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 (eg SRP).\n\t */\n\tret =\n\t _gnutls_remove_unwanted_ciphersuites(session, cipher_suites,\n\t\t\t\t\t\t ret, NULL, 0);\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\t/* If no cipher suites were enabled.\n\t */\n\tif (ret == 0)\n\t\treturn\n\t\t gnutls_assert_val(GNUTLS_E_INSUFFICIENT_CREDENTIALS);\n\n\tcipher_suites_size = ret;\n\tif (add_scsv) {\n\t\tcipher_suites[cipher_suites_size] = 0x00;\n\t\tcipher_suites[cipher_suites_size + 1] = 0xff;\n\t\tcipher_suites_size += 2;\n\n\t\tret = _gnutls_ext_sr_send_cs(session);\n\t\tif (ret < 0)\n\t\t\treturn gnutls_assert_val(ret);\n\t}\n\n\tret =\n\t _gnutls_buffer_append_data_prefix(cdata, 16, cipher_suites,\n\t\t\t\t\t cipher_suites_size);\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\tret = cdata->length - init_length;\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'handshake: add FALLBACK_SCSV priority option\n\nThis allows clients to enable the TLS_FALLBACK_SCSV mechanism during\nthe handshake, as defined in RFC7507.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static char *memdup(const char *src, size_t buffer_length)\n{\n size_t length;\n bool add = FALSE;\n char *buffer;\n\n if(buffer_length)\n length = buffer_length;\n else if(src) {\n length = strlen(src);\n add = TRUE;\n }\n else\n /* no length and a NULL src pointer! */\n return strdup(\"\");\n\n buffer = malloc(length+add);\n if(!buffer)\n return NULL; /* fail */\n\n memcpy(buffer, src, length);\n\n /* if length unknown do null termination */\n if(add)\n buffer[length] = '\\0';\n\n return buffer;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'curl_easy_duphandle: CURLOPT_COPYPOSTFIELDS read out of bounds\n\nWhen duplicating a handle, the data to post was duplicated using\nstrdup() when it could be binary and contain zeroes and it was not even\nzero terminated! This caused read out of bounds crashes/segfaults.\n\nSince the lib/strdup.c file no longer is easily shared with the curl\ntool with this change, it now uses its own version instead.\n\nBug: http://curl.haxx.se/docs/adv_20141105.html\nCVE: CVE-2014-3707\nReported-By: Symeon Paraschoudis'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction)\n{\n QCA::Initializer init;\n QByteArray temp = cipherText;\n\n //do padding ourselves\n if (direction)\n {\n while ((temp.length() % 8) != 0) temp.append('\\0');\n }\n else\n {\n temp = b64ToByte(temp);\n while ((temp.length() % 8) != 0) temp.append('\\0');\n }\n\n QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;\n QCA::Cipher cipher(m_type, QCA::Cipher::ECB, QCA::Cipher::NoPadding, dir, m_key);\n QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray();\n temp2 += cipher.final().toByteArray();\n\n if (!cipher.ok())\n return cipherText;\n\n if (direction)\n temp2 = byteToB64(temp2);\n\n return temp2;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Check for invalid input in encrypted buffers\n\nThe ECB Blowfish decryption function assumed that encrypted input would\nalways come in blocks of 12 characters, as specified. However, buggy\nclients or annoying people may not adhere to that assumption, causing\nthe core to crash while trying to process the invalid base64 input.\n\nWith this commit we make sure that we're not overstepping the bounds of\nthe input string while decoding it; instead we bail out early and display\nthe original input. Fixes #1314.\n\nThanks to Tucos for finding that one!'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ssl_parse_supported_elliptic_curves( ssl_context *ssl,\n const unsigned char *buf,\n size_t len )\n{\n size_t list_size, our_size;\n const unsigned char *p;\n const ecp_curve_info *curve_info, **curves;\n\n list_size = ( ( buf[0] << 8 ) | ( buf[1] ) );\n if( list_size + 2 != len ||\n list_size % 2 != 0 )\n {\n SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );\n }\n\n /* Don't allow our peer to make us allocate too much memory,\n * and leave room for a final 0 */\n our_size = list_size / 2 + 1;\n if( our_size > POLARSSL_ECP_DP_MAX )\n our_size = POLARSSL_ECP_DP_MAX;\n\n if( ( curves = polarssl_malloc( our_size * sizeof( *curves ) ) ) == NULL )\n return( POLARSSL_ERR_SSL_MALLOC_FAILED );\n\n /* explicit void pointer cast for buggy MS compiler */\n memset( (void *) curves, 0, our_size * sizeof( *curves ) );\n ssl->handshake->curves = curves;\n\n p = buf + 2;\n while( list_size > 0 && our_size > 1 )\n {\n curve_info = ecp_curve_info_from_tls_id( ( p[0] << 8 ) | p[1] );\n\n if( curve_info != NULL )\n {\n *curves++ = curve_info;\n our_size--;\n }\n\n list_size -= 2;\n p += 2;\n }\n\n return( 0 );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Fix memory leak with crafted ClientHello'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int handle_emulation_failure(struct kvm_vcpu *vcpu)\n{\n\tint r = EMULATE_DONE;\n\n\t++vcpu->stat.insn_emulation_fail;\n\ttrace_kvm_emulate_insn_failed(vcpu);\n\tif (!is_guest_mode(vcpu)) {\n\t\tvcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;\n\t\tvcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;\n\t\tvcpu->run->internal.ndata = 0;\n\t\tr = EMULATE_FAIL;\n\t}\n\tkvm_queue_exception(vcpu, UD_VECTOR);\n\n\treturn r;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'KVM: x86: Don't report guest userspace emulation error to userspace\n\nCommit fc3a9157d314 (\"KVM: X86: Don't report L2 emulation failures to\nuser-space\") disabled the reporting of L2 (nested guest) emulation failures to\nuserspace due to race-condition between a vmexit and the instruction emulator.\nThe same rational applies also to userspace applications that are permitted by\nthe guest OS to access MMIO area or perform PIO.\n\nThis patch extends the current behavior - of injecting a #UD instead of\nreporting it to userspace - also for guest userspace code.\n\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: yaml_parser_save_simple_key(yaml_parser_t *parser)\n{\n /*\n * A simple key is required at the current position if the scanner is in\n * the block context and the current column coincides with the indentation\n * level.\n */\n\n int required = (!parser->flow_level\n && parser->indent == (ptrdiff_t)parser->mark.column);\n\n /*\n * A simple key is required only when it is the first token in the current\n * line. Therefore it is always allowed. But we add a check anyway.\n */\n\n assert(parser->simple_key_allowed || !required); /* Impossible. */\n\n /*\n * If the current position may start a simple key, save it.\n */\n\n if (parser->simple_key_allowed)\n {\n yaml_simple_key_t simple_key;\n simple_key.possible = 1;\n simple_key.required = required;\n simple_key.token_number = \n parser->tokens_parsed + (parser->tokens.tail - parser->tokens.head);\n simple_key.mark = parser->mark;\n\n if (!yaml_parser_remove_simple_key(parser)) return 0;\n\n *(parser->simple_keys.top-1) = simple_key;\n }\n\n return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix for https://bitbucket.org/xi/libyaml/issue/10/\n\nhttps://bitbucket.org/xi/libyaml/issue/10/wrapped-strings-cause-assert-failure\n\nCommenting out the assert makes the scanner do the right thing and\nresults in just a simple parse failure.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: match(struct magic_set *ms, struct magic *magic, uint32_t nmagic,\n const unsigned char *s, size_t nbytes, size_t offset, int mode, int text,\n int flip, int recursion_level, int *printed_something, int *need_separator,\n int *returnval)\n{\n\tuint32_t magindex = 0;\n\tunsigned int cont_level = 0;\n\tint returnvalv = 0, e; /* if a match is found it is set to 1*/\n\tint firstline = 1; /* a flag to print X\\n X\\n- X */\n\tint print = (ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0;\n\n\tif (returnval == NULL)\n\t\treturnval = &returnvalv;\n\n\tif (file_check_mem(ms, cont_level) == -1)\n\t\treturn -1;\n\n\tfor (magindex = 0; magindex < nmagic; magindex++) {\n\t\tint flush = 0;\n\t\tstruct magic *m = &magic[magindex];\n\n\t\tif (m->type != FILE_NAME)\n\t\tif ((IS_STRING(m->type) &&\n#define FLT (STRING_BINTEST | STRING_TEXTTEST)\n\t\t ((text && (m->str_flags & FLT) == STRING_BINTEST) ||\n\t\t (!text && (m->str_flags & FLT) == STRING_TEXTTEST))) ||\n\t\t (m->flag & mode) != mode) {\n\t\t\t/* Skip sub-tests */\n\t\t\twhile (magindex + 1 < nmagic &&\n magic[magindex + 1].cont_level != 0 &&\n\t\t\t ++magindex)\n\t\t\t\tcontinue;\n\t\t\tcontinue; /* Skip to next top-level test*/\n\t\t}\n\n\t\tms->offset = m->offset;\n\t\tms->line = m->lineno;\n\n\t\t/* if main entry matches, print it... */\n\t\tswitch (mget(ms, s, m, nbytes, offset, cont_level, mode, text,\n\t\t flip, recursion_level + 1, printed_something,\n\t\t need_separator, returnval)) {\n\t\tcase -1:\n\t\t\treturn -1;\n\t\tcase 0:\n\t\t\tflush = m->reln != '!';\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (m->type == FILE_INDIRECT)\n\t\t\t\t*returnval = 1;\n\n\t\t\tswitch (magiccheck(ms, m)) {\n\t\t\tcase -1:\n\t\t\t\treturn -1;\n\t\t\tcase 0:\n\t\t\t\tflush++;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tflush = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tif (flush) {\n\t\t\t/*\n\t\t\t * main entry didn't match,\n\t\t\t * flush its continuations\n\t\t\t */\n\t\t\twhile (magindex < nmagic - 1 &&\n\t\t\t magic[magindex + 1].cont_level != 0)\n\t\t\t\tmagindex++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif ((e = handle_annotation(ms, m)) != 0) {\n\t\t\t*need_separator = 1;\n\t\t\t*printed_something = 1;\n\t\t\t*returnval = 1;\n\t\t\treturn e;\n\t\t}\n\t\t/*\n\t\t * If we are going to print something, we'll need to print\n\t\t * a blank before we print something else.\n\t\t */\n\t\tif (*m->desc) {\n\t\t\t*need_separator = 1;\n\t\t\t*printed_something = 1;\n\t\t\tif (print_sep(ms, firstline) == -1)\n\t\t\t\treturn -1;\n\t\t}\n\n\n\t\tif (print && mprint(ms, m) == -1)\n\t\t\treturn -1;\n\n\t\tms->c.li[cont_level].off = moffset(ms, m);\n\n\t\t/* and any continuations that match */\n\t\tif (file_check_mem(ms, ++cont_level) == -1)\n\t\t\treturn -1;\n\n\t\twhile (magindex + 1 < nmagic &&\n\t\t magic[magindex + 1].cont_level != 0) {\n\t\t\tm = &magic[++magindex];\n\t\t\tms->line = m->lineno; /* for messages */\n\n\t\t\tif (cont_level < m->cont_level)\n\t\t\t\tcontinue;\n\t\t\tif (cont_level > m->cont_level) {\n\t\t\t\t/*\n\t\t\t\t * We're at the end of the level\n\t\t\t\t * \"cont_level\" continuations.\n\t\t\t\t */\n\t\t\t\tcont_level = m->cont_level;\n\t\t\t}\n\t\t\tms->offset = m->offset;\n\t\t\tif (m->flag & OFFADD) {\n\t\t\t\tms->offset +=\n\t\t\t\t ms->c.li[cont_level - 1].off;\n\t\t\t}\n\n#ifdef ENABLE_CONDITIONALS\n\t\t\tif (m->cond == COND_ELSE ||\n\t\t\t m->cond == COND_ELIF) {\n\t\t\t\tif (ms->c.li[cont_level].last_match == 1)\n\t\t\t\t\tcontinue;\n\t\t\t}\n#endif\n\t\t\tswitch (mget(ms, s, m, nbytes, offset, cont_level, mode,\n\t\t\t text, flip, recursion_level + 1, printed_something,\n\t\t\t need_separator, returnval)) {\n\t\t\tcase -1:\n\t\t\t\treturn -1;\n\t\t\tcase 0:\n\t\t\t\tif (m->reln != '!')\n\t\t\t\t\tcontinue;\n\t\t\t\tflush = 1;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif (m->type == FILE_INDIRECT)\n\t\t\t\t\t*returnval = 1;\n\t\t\t\tflush = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tswitch (flush ? 1 : magiccheck(ms, m)) {\n\t\t\tcase -1:\n\t\t\t\treturn -1;\n\t\t\tcase 0:\n#ifdef ENABLE_CONDITIONALS\n\t\t\t\tms->c.li[cont_level].last_match = 0;\n#endif\n\t\t\t\tbreak;\n\t\t\tdefault:\n#ifdef ENABLE_CONDITIONALS\n\t\t\t\tms->c.li[cont_level].last_match = 1;\n#endif\n\t\t\t\tif (m->type == FILE_CLEAR)\n\t\t\t\t\tms->c.li[cont_level].got_match = 0;\n\t\t\t\telse if (ms->c.li[cont_level].got_match) {\n\t\t\t\t\tif (m->type == FILE_DEFAULT)\n\t\t\t\t\t\tbreak;\n\t\t\t\t} else\n\t\t\t\t\tms->c.li[cont_level].got_match = 1;\n\t\t\t\tif ((e = handle_annotation(ms, m)) != 0) {\n\t\t\t\t\t*need_separator = 1;\n\t\t\t\t\t*printed_something = 1;\n\t\t\t\t\t*returnval = 1;\n\t\t\t\t\treturn e;\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * If we are going to print something,\n\t\t\t\t * make sure that we have a separator first.\n\t\t\t\t */\n\t\t\t\tif (*m->desc) {\n\t\t\t\t\tif (!*printed_something) {\n\t\t\t\t\t\t*printed_something = 1;\n\t\t\t\t\t\tif (print_sep(ms, firstline)\n\t\t\t\t\t\t == -1)\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * This continuation matched. Print\n\t\t\t\t * its message, with a blank before it\n\t\t\t\t * if the previous item printed and\n\t\t\t\t * this item isn't empty.\n\t\t\t\t */\n\t\t\t\t/* space if previous printed */\n\t\t\t\tif (*need_separator\n\t\t\t\t && ((m->flag & NOSPACE) == 0)\n\t\t\t\t && *m->desc) {\n\t\t\t\t\tif (print &&\n\t\t\t\t\t file_printf(ms, \" \") == -1)\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t*need_separator = 0;\n\t\t\t\t}\n\t\t\t\tif (print && mprint(ms, m) == -1)\n\t\t\t\t\treturn -1;\n\n\t\t\t\tms->c.li[cont_level].off = moffset(ms, m);\n\n\t\t\t\tif (*m->desc)\n\t\t\t\t\t*need_separator = 1;\n\n\t\t\t\t/*\n\t\t\t\t * If we see any continuations\n\t\t\t\t * at a higher level,\n\t\t\t\t * process them.\n\t\t\t\t */\n\t\t\t\tif (file_check_mem(ms, ++cont_level) == -1)\n\t\t\t\t\treturn -1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (*printed_something) {\n\t\t\tfirstline = 0;\n\t\t\tif (print)\n\t\t\t\t*returnval = 1;\n\t\t}\n\t\tif ((ms->flags & MAGIC_CONTINUE) == 0 && *printed_something) {\n\t\t\treturn *returnval; /* don't keep searching */\n\t\t}\n\t}\n\treturn *returnval; /* This is hit if -k is set or there is no match */\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: toomany(struct magic_set *ms, const char *name, uint16_t num)\n{\n\tif (file_printf(ms, \", too many %s header sections (%u)\", name, num\n\t ) == -1)\n\t\treturn -1;\n\treturn 0;\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_colgrp(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 * JPC_QMFB_COLGRPSIZE];\n#else\n\tjpc_fix_t joinbuf[bufsize * JPC_QMFB_COLGRPSIZE];\n#endif\n\tjpc_fix_t *buf = joinbuf;\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 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 * JPC_QMFB_COLGRPSIZE * 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\tdstptr2 = dstptr;\n\t\tsrcptr2 = srcptr;\n\t\tfor (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {\n\t\t\t*dstptr2 = *srcptr2;\n\t\t\t++dstptr2;\n\t\t\t++srcptr2;\n\t\t}\n\t\tsrcptr += stride;\n\t\tdstptr += JPC_QMFB_COLGRPSIZE;\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\tdstptr2 = dstptr;\n\t\tsrcptr2 = srcptr;\n\t\tfor (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {\n\t\t\t*dstptr2 = *srcptr2;\n\t\t\t++dstptr2;\n\t\t\t++srcptr2;\n\t\t}\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\tdstptr2 = dstptr;\n\t\tsrcptr2 = srcptr;\n\t\tfor (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {\n\t\t\t*dstptr2 = *srcptr2;\n\t\t\t++dstptr2;\n\t\t\t++srcptr2;\n\t\t}\n\t\tdstptr += 2 * stride;\n\t\tsrcptr += JPC_QMFB_COLGRPSIZE;\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: krb5_gss_inquire_sec_context_by_oid (OM_uint32 *minor_status,\n const gss_ctx_id_t context_handle,\n const gss_OID desired_object,\n gss_buffer_set_t *data_set)\n{\n krb5_gss_ctx_id_rec *ctx;\n size_t i;\n\n if (minor_status == NULL)\n return GSS_S_CALL_INACCESSIBLE_WRITE;\n\n *minor_status = 0;\n\n if (desired_object == GSS_C_NO_OID)\n return GSS_S_CALL_INACCESSIBLE_READ;\n\n if (data_set == NULL)\n return GSS_S_CALL_INACCESSIBLE_WRITE;\n\n *data_set = GSS_C_NO_BUFFER_SET;\n\n ctx = (krb5_gss_ctx_id_rec *) context_handle;\n\n if (!ctx->established)\n return GSS_S_NO_CONTEXT;\n\n for (i = 0; i < sizeof(krb5_gss_inquire_sec_context_by_oid_ops)/\n sizeof(krb5_gss_inquire_sec_context_by_oid_ops[0]); i++) {\n if (g_OID_prefix_equal(desired_object, &krb5_gss_inquire_sec_context_by_oid_ops[i].oid)) {\n return (*krb5_gss_inquire_sec_context_by_oid_ops[i].func)(minor_status,\n context_handle,\n desired_object,\n data_set);\n }\n }\n\n *minor_status = EINVAL;\n\n return GSS_S_UNAVAILABLE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'Fix gss_process_context_token() [CVE-2014-5352]\n\n[MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not\nactually delete the context; that leaves the caller with a dangling\npointer and no way to know that it is invalid. Instead, mark the\ncontext as terminated, and check for terminated contexts in the GSS\nfunctions which expect established contexts. Also add checks in\nexport_sec_context and pseudo_random, and adjust t_prf.c for the\npseudo_random check.\n\nticket: 8055 (new)\ntarget_version: 1.13.1\ntags: pullup'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: krb5_gss_inquire_context(minor_status, context_handle, initiator_name,\n acceptor_name, lifetime_rec, mech_type, ret_flags,\n locally_initiated, opened)\n OM_uint32 *minor_status;\n gss_ctx_id_t context_handle;\n gss_name_t *initiator_name;\n gss_name_t *acceptor_name;\n OM_uint32 *lifetime_rec;\n gss_OID *mech_type;\n OM_uint32 *ret_flags;\n int *locally_initiated;\n int *opened;\n{\n krb5_context context;\n krb5_error_code code;\n krb5_gss_ctx_id_rec *ctx;\n krb5_gss_name_t initiator, acceptor;\n krb5_timestamp now;\n krb5_deltat lifetime;\n\n if (initiator_name)\n *initiator_name = (gss_name_t) NULL;\n if (acceptor_name)\n *acceptor_name = (gss_name_t) NULL;\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 initiator = NULL;\n acceptor = NULL;\n context = ctx->k5_context;\n\n if ((code = krb5_timeofday(context, &now))) {\n *minor_status = code;\n save_error_info(*minor_status, context);\n return(GSS_S_FAILURE);\n }\n\n if ((lifetime = ctx->krb_times.endtime - now) < 0)\n lifetime = 0;\n\n if (initiator_name) {\n if ((code = kg_duplicate_name(context,\n ctx->initiate ? ctx->here : ctx->there,\n &initiator))) {\n *minor_status = code;\n save_error_info(*minor_status, context);\n return(GSS_S_FAILURE);\n }\n }\n\n if (acceptor_name) {\n if ((code = kg_duplicate_name(context,\n ctx->initiate ? ctx->there : ctx->here,\n &acceptor))) {\n if (initiator)\n kg_release_name(context, &initiator);\n *minor_status = code;\n save_error_info(*minor_status, context);\n return(GSS_S_FAILURE);\n }\n }\n\n if (initiator_name)\n *initiator_name = (gss_name_t) initiator;\n\n if (acceptor_name)\n *acceptor_name = (gss_name_t) acceptor;\n\n if (lifetime_rec)\n *lifetime_rec = lifetime;\n\n if (mech_type)\n *mech_type = (gss_OID) ctx->mech_used;\n\n if (ret_flags)\n *ret_flags = ctx->gss_flags;\n\n if (locally_initiated)\n *locally_initiated = ctx->initiate;\n\n if (opened)\n *opened = ctx->established;\n\n *minor_status = 0;\n return((lifetime == 0)?GSS_S_CONTEXT_EXPIRED: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: check_exclusion_constraint(Relation heap, Relation index, IndexInfo *indexInfo,\n\t\t\t\t\t\t ItemPointer tupleid, Datum *values, bool *isnull,\n\t\t\t\t\t\t EState *estate, bool newIndex, bool errorOK)\n{\n\tOid\t\t *constr_procs = indexInfo->ii_ExclusionProcs;\n\tuint16\t *constr_strats = indexInfo->ii_ExclusionStrats;\n\tOid\t\t *index_collations = index->rd_indcollation;\n\tint\t\t\tindex_natts = index->rd_index->indnatts;\n\tIndexScanDesc index_scan;\n\tHeapTuple\ttup;\n\tScanKeyData scankeys[INDEX_MAX_KEYS];\n\tSnapshotData DirtySnapshot;\n\tint\t\t\ti;\n\tbool\t\tconflict;\n\tbool\t\tfound_self;\n\tExprContext *econtext;\n\tTupleTableSlot *existing_slot;\n\tTupleTableSlot *save_scantuple;\n\n\t/*\n\t * If any of the input values are NULL, the constraint check is assumed to\n\t * pass (i.e., we assume the operators are strict).\n\t */\n\tfor (i = 0; i < index_natts; i++)\n\t{\n\t\tif (isnull[i])\n\t\t\treturn true;\n\t}\n\n\t/*\n\t * Search the tuples that are in the index for any violations, including\n\t * tuples that aren't visible yet.\n\t */\n\tInitDirtySnapshot(DirtySnapshot);\n\n\tfor (i = 0; i < index_natts; i++)\n\t{\n\t\tScanKeyEntryInitialize(&scankeys[i],\n\t\t\t\t\t\t\t 0,\n\t\t\t\t\t\t\t i + 1,\n\t\t\t\t\t\t\t constr_strats[i],\n\t\t\t\t\t\t\t InvalidOid,\n\t\t\t\t\t\t\t index_collations[i],\n\t\t\t\t\t\t\t constr_procs[i],\n\t\t\t\t\t\t\t values[i]);\n\t}\n\n\t/*\n\t * Need a TupleTableSlot to put existing tuples in.\n\t *\n\t * To use FormIndexDatum, we have to make the econtext's scantuple point\n\t * to this slot. Be sure to save and restore caller's value for\n\t * scantuple.\n\t */\n\texisting_slot = MakeSingleTupleTableSlot(RelationGetDescr(heap));\n\n\tecontext = GetPerTupleExprContext(estate);\n\tsave_scantuple = econtext->ecxt_scantuple;\n\tecontext->ecxt_scantuple = existing_slot;\n\n\t/*\n\t * May have to restart scan from this point if a potential conflict is\n\t * found.\n\t */\nretry:\n\tconflict = false;\n\tfound_self = false;\n\tindex_scan = index_beginscan(heap, index, &DirtySnapshot, index_natts, 0);\n\tindex_rescan(index_scan, scankeys, index_natts, NULL, 0);\n\n\twhile ((tup = index_getnext(index_scan,\n\t\t\t\t\t\t\t\tForwardScanDirection)) != NULL)\n\t{\n\t\tTransactionId xwait;\n\t\tDatum\t\texisting_values[INDEX_MAX_KEYS];\n\t\tbool\t\texisting_isnull[INDEX_MAX_KEYS];\n\t\tchar\t *error_new;\n\t\tchar\t *error_existing;\n\n\t\t/*\n\t\t * Ignore the entry for the tuple we're trying to check.\n\t\t */\n\t\tif (ItemPointerEquals(tupleid, &tup->t_self))\n\t\t{\n\t\t\tif (found_self)\t\t/* should not happen */\n\t\t\t\telog(ERROR, \"found self tuple multiple times in index \\\"%s\\\"\",\n\t\t\t\t\t RelationGetRelationName(index));\n\t\t\tfound_self = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\t/*\n\t\t * Extract the index column values and isnull flags from the existing\n\t\t * tuple.\n\t\t */\n\t\tExecStoreTuple(tup, existing_slot, InvalidBuffer, false);\n\t\tFormIndexDatum(indexInfo, existing_slot, estate,\n\t\t\t\t\t existing_values, existing_isnull);\n\n\t\t/* If lossy indexscan, must recheck the condition */\n\t\tif (index_scan->xs_recheck)\n\t\t{\n\t\t\tif (!index_recheck_constraint(index,\n\t\t\t\t\t\t\t\t\t\t constr_procs,\n\t\t\t\t\t\t\t\t\t\t existing_values,\n\t\t\t\t\t\t\t\t\t\t existing_isnull,\n\t\t\t\t\t\t\t\t\t\t values))\n\t\t\t\tcontinue;\t\t/* tuple doesn't actually match, so no\n\t\t\t\t\t\t\t\t * conflict */\n\t\t}\n\n\t\t/*\n\t\t * At this point we have either a conflict or a potential conflict. If\n\t\t * we're not supposed to raise error, just return the fact of the\n\t\t * potential conflict without waiting to see if it's real.\n\t\t */\n\t\tif (errorOK)\n\t\t{\n\t\t\tconflict = true;\n\t\t\tbreak;\n\t\t}\n\n\t\t/*\n\t\t * If an in-progress transaction is affecting the visibility of this\n\t\t * tuple, we need to wait for it to complete and then recheck. For\n\t\t * simplicity we do rechecking by just restarting the whole scan ---\n\t\t * this case probably doesn't happen often enough to be worth trying\n\t\t * harder, and anyway we don't want to hold any index internal locks\n\t\t * while waiting.\n\t\t */\n\t\txwait = TransactionIdIsValid(DirtySnapshot.xmin) ?\n\t\t\tDirtySnapshot.xmin : DirtySnapshot.xmax;\n\n\t\tif (TransactionIdIsValid(xwait))\n\t\t{\n\t\t\tindex_endscan(index_scan);\n\t\t\tXactLockTableWait(xwait, heap, &tup->t_data->t_ctid,\n\t\t\t\t\t\t\t XLTW_RecheckExclusionConstr);\n\t\t\tgoto retry;\n\t\t}\n\n\t\t/*\n\t\t * We have a definite conflict. Report it.\n\t\t */\n\t\terror_new = BuildIndexValueDescription(index, values, isnull);\n\t\terror_existing = BuildIndexValueDescription(index, existing_values,\n\t\t\t\t\t\t\t\t\t\t\t\t\texisting_isnull);\n\t\tif (newIndex)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_EXCLUSION_VIOLATION),\n\t\t\t\t\t errmsg(\"could not create exclusion constraint \\\"%s\\\"\",\n\t\t\t\t\t\t\tRelationGetRelationName(index)),\n\t\t\t\t\t errdetail(\"Key %s conflicts with key %s.\",\n\t\t\t\t\t\t\t error_new, error_existing),\n\t\t\t\t\t errtableconstraint(heap,\n\t\t\t\t\t\t\t\t\t\tRelationGetRelationName(index))));\n\t\telse\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_EXCLUSION_VIOLATION),\n\t\t\t\t\t errmsg(\"conflicting key value violates exclusion constraint \\\"%s\\\"\",\n\t\t\t\t\t\t\tRelationGetRelationName(index)),\n\t\t\t\t\t errdetail(\"Key %s conflicts with existing key %s.\",\n\t\t\t\t\t\t\t error_new, error_existing),\n\t\t\t\t\t errtableconstraint(heap,\n\t\t\t\t\t\t\t\t\t\tRelationGetRelationName(index))));\n\t}\n\n\tindex_endscan(index_scan);\n\n\t/*\n\t * Ordinarily, at this point the search should have found the originally\n\t * inserted tuple, unless we exited the loop early because of conflict.\n\t * However, it is possible to define exclusion constraints for which that\n\t * wouldn't be true --- for instance, if the operator is <>. So we no\n\t * longer complain if found_self is still false.\n\t */\n\n\tecontext->ecxt_scantuple = save_scantuple;\n\n\tExecDropSingleTupleTableSlot(existing_slot);\n\n\treturn !conflict;\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: ExecWithCheckOptions(ResultRelInfo *resultRelInfo,\n\t\t\t\t\t TupleTableSlot *slot, EState *estate)\n{\n\tExprContext *econtext;\n\tListCell *l1,\n\t\t\t *l2;\n\n\t/*\n\t * We will use the EState's per-tuple context for evaluating constraint\n\t * expressions (creating it if it's not already there).\n\t */\n\tecontext = GetPerTupleExprContext(estate);\n\n\t/* Arrange for econtext's scan tuple to be the tuple under test */\n\tecontext->ecxt_scantuple = slot;\n\n\t/* Check each of the constraints */\n\tforboth(l1, resultRelInfo->ri_WithCheckOptions,\n\t\t\tl2, resultRelInfo->ri_WithCheckOptionExprs)\n\t{\n\t\tWithCheckOption *wco = (WithCheckOption *) lfirst(l1);\n\t\tExprState *wcoExpr = (ExprState *) lfirst(l2);\n\n\t\t/*\n\t\t * WITH CHECK OPTION checks are intended to ensure that the new tuple\n\t\t * is visible (in the case of a view) or that it passes the\n\t\t * 'with-check' policy (in the case of row security).\n\t\t * If the qual evaluates to NULL or FALSE, then the new tuple won't be\n\t\t * included in the view or doesn't pass the 'with-check' policy for the\n\t\t * table. We need ExecQual to return FALSE for NULL to handle the view\n\t\t * case (the opposite of what we do above for CHECK constraints).\n\t\t */\n\t\tif (!ExecQual((List *) wcoExpr, econtext, false))\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_WITH_CHECK_OPTION_VIOLATION),\n\t\t\t\t errmsg(\"new row violates WITH CHECK OPTION for \\\"%s\\\"\",\n\t\t\t\t\t\twco->viewname),\n\t\t\t\t\t errdetail(\"Failing row contains %s.\",\n\t\t\t\t\t\t\t ExecBuildSlotValueDescription(slot,\n\t\t\t\t\t\t\tRelationGetDescr(resultRelInfo->ri_RelationDesc),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 64))));\n\t}\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: open_patch_file (char const *filename)\n{\n file_offset file_pos = 0;\n file_offset pos;\n struct stat st;\n\n if (!filename || !*filename || strEQ (filename, \"-\"))\n pfp = stdin;\n else\n {\n\tpfp = fopen (filename, binary_transput ? \"rb\" : \"r\");\n\tif (!pfp)\n\t pfatal (\"Can't open patch file %s\", quotearg (filename));\n }\n#if HAVE_SETMODE_DOS\n if (binary_transput)\n {\n\tif (isatty (fileno (pfp)))\n\t fatal (\"cannot read binary data from tty on this platform\");\n\tsetmode (fileno (pfp), O_BINARY);\n }\n#endif\n if (fstat (fileno (pfp), &st) != 0)\n pfatal (\"fstat\");\n if (S_ISREG (st.st_mode) && (pos = file_tell (pfp)) != -1)\n file_pos = pos;\n else\n {\n\tsize_t charsread;\n\tint fd = make_tempfile (&TMPPATNAME, 'p', NULL, O_RDWR | O_BINARY, 0);\n\tFILE *read_pfp = pfp;\n\tTMPPATNAME_needs_removal = true;\n\tpfp = fdopen (fd, \"w+b\");\n\tif (! pfp)\n\t pfatal (\"Can't open stream for file %s\", quotearg (TMPPATNAME));\n\tfor (st.st_size = 0;\n\t (charsread = fread (buf, 1, bufsize, read_pfp)) != 0;\n\t st.st_size += charsread)\n\t if (fwrite (buf, 1, charsread, pfp) != charsread)\n\t write_fatal ();\n\tif (ferror (read_pfp) || fclose (read_pfp) != 0)\n\t read_fatal ();\n\tif (fflush (pfp) != 0\n\t || file_seek (pfp, (file_offset) 0, SEEK_SET) != 0)\n\t write_fatal ();\n }\n p_filesize = st.st_size;\n if (p_filesize != (file_offset) p_filesize)\n fatal (\"patch file is too long\");\n next_intuit_at (file_pos, 1);\n set_hunkmax();\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: NUM_numpart_to_char(NUMProc *Np, int id)\n{\n\tint\t\t\tend;\n\n\tif (IS_ROMAN(Np->Num))\n\t\treturn;\n\n\t/* Note: in this elog() output not set '\\0' in 'inout' */\n\n#ifdef DEBUG_TO_FROM_CHAR\n\n\t/*\n\t * Np->num_curr is number of current item in format-picture, it is not\n\t * current position in inout!\n\t */\n\telog(DEBUG_elog_output,\n\t\t \"SIGN_WROTE: %d, CURRENT: %d, NUMBER_P: \\\"%s\\\", INOUT: \\\"%s\\\"\",\n\t\t Np->sign_wrote,\n\t\t Np->num_curr,\n\t\t Np->number_p,\n\t\t Np->inout);\n#endif\n\tNp->num_in = FALSE;\n\n\t/*\n\t * Write sign if real number will write to output Note: IS_PREDEC_SPACE()\n\t * handle \"9.9\" --> \" .1\"\n\t */\n\tif (Np->sign_wrote == FALSE &&\n\t\t(Np->num_curr >= Np->out_pre_spaces || (IS_ZERO(Np->Num) && Np->Num->zero_start == Np->num_curr)) &&\n\t\t(IS_PREDEC_SPACE(Np) == FALSE || (Np->last_relevant && *Np->last_relevant == '.')))\n\t{\n\t\tif (IS_LSIGN(Np->Num))\n\t\t{\n\t\t\tif (Np->Num->lsign == NUM_LSIGN_PRE)\n\t\t\t{\n\t\t\t\tif (Np->sign == '-')\n\t\t\t\t\tstrcpy(Np->inout_p, Np->L_negative_sign);\n\t\t\t\telse\n\t\t\t\t\tstrcpy(Np->inout_p, Np->L_positive_sign);\n\t\t\t\tNp->inout_p += strlen(Np->inout_p);\n\t\t\t\tNp->sign_wrote = TRUE;\n\t\t\t}\n\t\t}\n\t\telse if (IS_BRACKET(Np->Num))\n\t\t{\n\t\t\t*Np->inout_p = Np->sign == '+' ? ' ' : '<';\n\t\t\t++Np->inout_p;\n\t\t\tNp->sign_wrote = TRUE;\n\t\t}\n\t\telse if (Np->sign == '+')\n\t\t{\n\t\t\tif (!IS_FILLMODE(Np->Num))\n\t\t\t{\n\t\t\t\t*Np->inout_p = ' ';\t\t/* Write + */\n\t\t\t\t++Np->inout_p;\n\t\t\t}\n\t\t\tNp->sign_wrote = TRUE;\n\t\t}\n\t\telse if (Np->sign == '-')\n\t\t{\t\t\t\t\t\t/* Write - */\n\t\t\t*Np->inout_p = '-';\n\t\t\t++Np->inout_p;\n\t\t\tNp->sign_wrote = TRUE;\n\t\t}\n\t}\n\n\n\t/*\n\t * digits / FM / Zero / Dec. point\n\t */\n\tif (id == NUM_9 || id == NUM_0 || id == NUM_D || id == NUM_DEC)\n\t{\n\t\tif (Np->num_curr < Np->out_pre_spaces &&\n\t\t\t(Np->Num->zero_start > Np->num_curr || !IS_ZERO(Np->Num)))\n\t\t{\n\t\t\t/*\n\t\t\t * Write blank space\n\t\t\t */\n\t\t\tif (!IS_FILLMODE(Np->Num))\n\t\t\t{\n\t\t\t\t*Np->inout_p = ' ';\t\t/* Write ' ' */\n\t\t\t\t++Np->inout_p;\n\t\t\t}\n\t\t}\n\t\telse if (IS_ZERO(Np->Num) &&\n\t\t\t\t Np->num_curr < Np->out_pre_spaces &&\n\t\t\t\t Np->Num->zero_start <= Np->num_curr)\n\t\t{\n\t\t\t/*\n\t\t\t * Write ZERO\n\t\t\t */\n\t\t\t*Np->inout_p = '0'; /* Write '0' */\n\t\t\t++Np->inout_p;\n\t\t\tNp->num_in = TRUE;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t/*\n\t\t\t * Write Decimal point\n\t\t\t */\n\t\t\tif (*Np->number_p == '.')\n\t\t\t{\n\t\t\t\tif (!Np->last_relevant || *Np->last_relevant != '.')\n\t\t\t\t{\n\t\t\t\t\tstrcpy(Np->inout_p, Np->decimal);\t/* Write DEC/D */\n\t\t\t\t\tNp->inout_p += strlen(Np->inout_p);\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t * Ora 'n' -- FM9.9 --> 'n.'\n\t\t\t\t */\n\t\t\t\telse if (IS_FILLMODE(Np->Num) &&\n\t\t\t\t\t\t Np->last_relevant && *Np->last_relevant == '.')\n\t\t\t\t{\n\t\t\t\t\tstrcpy(Np->inout_p, Np->decimal);\t/* Write DEC/D */\n\t\t\t\t\tNp->inout_p += strlen(Np->inout_p);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\t * Write Digits\n\t\t\t\t */\n\t\t\t\tif (Np->last_relevant && Np->number_p > Np->last_relevant &&\n\t\t\t\t\tid != NUM_0)\n\t\t\t\t\t;\n\n\t\t\t\t/*\n\t\t\t\t * '0.1' -- 9.9 --> ' .1'\n\t\t\t\t */\n\t\t\t\telse if (IS_PREDEC_SPACE(Np))\n\t\t\t\t{\n\t\t\t\t\tif (!IS_FILLMODE(Np->Num))\n\t\t\t\t\t{\n\t\t\t\t\t\t*Np->inout_p = ' ';\n\t\t\t\t\t\t++Np->inout_p;\n\t\t\t\t\t}\n\n\t\t\t\t\t/*\n\t\t\t\t\t * '0' -- FM9.9 --> '0.'\n\t\t\t\t\t */\n\t\t\t\t\telse if (Np->last_relevant && *Np->last_relevant == '.')\n\t\t\t\t\t{\n\t\t\t\t\t\t*Np->inout_p = '0';\n\t\t\t\t\t\t++Np->inout_p;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t*Np->inout_p = *Np->number_p;\t\t/* Write DIGIT */\n\t\t\t\t\t++Np->inout_p;\n\t\t\t\t\tNp->num_in = TRUE;\n\t\t\t\t}\n\t\t\t}\n\t\t\t++Np->number_p;\n\t\t}\n\n\t\tend = Np->num_count + (Np->out_pre_spaces ? 1 : 0) + (IS_DECIMAL(Np->Num) ? 1 : 0);\n\n\t\tif (Np->last_relevant && Np->last_relevant == Np->number_p)\n\t\t\tend = Np->num_curr;\n\n\t\tif (Np->num_curr + 1 == end)\n\t\t{\n\t\t\tif (Np->sign_wrote == TRUE && IS_BRACKET(Np->Num))\n\t\t\t{\n\t\t\t\t*Np->inout_p = Np->sign == '+' ? ' ' : '>';\n\t\t\t\t++Np->inout_p;\n\t\t\t}\n\t\t\telse if (IS_LSIGN(Np->Num) && Np->Num->lsign == NUM_LSIGN_POST)\n\t\t\t{\n\t\t\t\tif (Np->sign == '-')\n\t\t\t\t\tstrcpy(Np->inout_p, Np->L_negative_sign);\n\t\t\t\telse\n\t\t\t\t\tstrcpy(Np->inout_p, Np->L_positive_sign);\n\t\t\t\tNp->inout_p += strlen(Np->inout_p);\n\t\t\t}\n\t\t}\n\t}\n\n\t++Np->num_curr;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'to_char(): prevent accesses beyond the allocated buffer\n\nPreviously very long field masks for floats could access memory\nbeyond the existing buffer allocated to hold the result.\n\nReported by Andres Freund and Peter Geoghegan.\tBackpatch to all\nsupported versions.\n\nSecurity: CVE-2015-0241'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: pq_getstring(StringInfo s)\n{\n\tint\t\t\ti;\n\n\tresetStringInfo(s);\n\n\t/* Read until we get the terminating '\\0' */\n\tfor (;;)\n\t{\n\t\twhile (PqRecvPointer >= PqRecvLength)\n\t\t{\n\t\t\tif (pq_recvbuf())\t/* If nothing in buffer, then recv some */\n\t\t\t\treturn EOF;\t\t/* Failed to recv data */\n\t\t}\n\n\t\tfor (i = PqRecvPointer; i < PqRecvLength; i++)\n\t\t{\n\t\t\tif (PqRecvBuffer[i] == '\\0')\n\t\t\t{\n\t\t\t\t/* include the '\\0' in the copy */\n\t\t\t\tappendBinaryStringInfo(s, PqRecvBuffer + PqRecvPointer,\n\t\t\t\t\t\t\t\t\t i - PqRecvPointer + 1);\n\t\t\t\tPqRecvPointer = i + 1;\t/* advance past \\0 */\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\n\t\t/* If we're here we haven't got the \\0 in the buffer yet. */\n\t\tappendBinaryStringInfo(s, PqRecvBuffer + PqRecvPointer,\n\t\t\t\t\t\t\t PqRecvLength - PqRecvPointer);\n\t\tPqRecvPointer = PqRecvLength;\n\t}\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: pq_getbyte_if_available(unsigned char *c)\n{\n\tint\t\t\tr;\n\n\tif (PqRecvPointer < PqRecvLength)\n\t{\n\t\t*c = PqRecvBuffer[PqRecvPointer++];\n\t\treturn 1;\n\t}\n\n\t/* Put the socket into non-blocking mode */\n\tsocket_set_nonblocking(true);\n\n\tr = secure_read(MyProcPort, c, 1);\n\tif (r < 0)\n\t{\n\t\t/*\n\t\t * Ok if no data available without blocking or interrupted (though\n\t\t * EINTR really shouldn't happen with a non-blocking socket). Report\n\t\t * other errors.\n\t\t */\n\t\tif (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)\n\t\t\tr = 0;\n\t\telse\n\t\t{\n\t\t\t/*\n\t\t\t * Careful: an ereport() that tries to write to the client would\n\t\t\t * cause recursion to here, leading to stack overflow and core\n\t\t\t * dump! This message must go *only* to the postmaster log.\n\t\t\t */\n\t\t\tereport(COMMERROR,\n\t\t\t\t\t(errcode_for_socket_access(),\n\t\t\t\t\t errmsg(\"could not receive data from client: %m\")));\n\t\t\tr = EOF;\n\t\t}\n\t}\n\telse if (r == 0)\n\t{\n\t\t/* EOF detected */\n\t\tr = EOF;\n\t}\n\n\treturn r;\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_core(struct magic_set *ms, int clazz, int swap, int fd, off_t off,\n int num, size_t size, off_t fsize, int *flags)\n{\n\tElf32_Phdr ph32;\n\tElf64_Phdr ph64;\n\tsize_t offset, len;\n\tunsigned char nbuf[BUFSIZ];\n\tssize_t bufsize;\n\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\t/*\n\t * Loop through all the program headers.\n\t */\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\t\toff += size;\n\n\t\tif (fsize != SIZE_UNKNOWN && xph_offset > fsize) {\n\t\t\t/* Perhaps warn here */\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (xph_type != PT_NOTE)\n\t\t\tcontinue;\n\n\t\t/*\n\t\t * This is a PT_NOTE section; loop through all the notes\n\t\t * in the section.\n\t\t */\n\t\tlen = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf);\n\t\tif ((bufsize = pread(fd, nbuf, len, xph_offset)) == -1) {\n\t\t\tfile_badread(ms);\n\t\t\treturn -1;\n\t\t}\n\t\toffset = 0;\n\t\tfor (;;) {\n\t\t\tif (offset >= (size_t)bufsize)\n\t\t\t\tbreak;\n\t\t\toffset = donote(ms, nbuf, offset, (size_t)bufsize,\n\t\t\t clazz, swap, 4, flags);\n\t\t\tif (offset == 0)\n\t\t\t\tbreak;\n\n\t\t}\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-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: keyid_from_fingerprint( const byte *fprint, size_t fprint_len, u32 *keyid )\n{\n u32 dummy_keyid[2];\n\n if( !keyid )\n keyid = dummy_keyid;\n\n if (fprint_len != 20)\n {\n /* This is special as we have to lookup the key first. */\n PKT_public_key pk;\n int rc;\n\n memset (&pk, 0, sizeof pk);\n rc = get_pubkey_byfprint (&pk, fprint, fprint_len);\n if( rc )\n {\n log_error(\"Oops: keyid_from_fingerprint: no pubkey\\n\");\n keyid[0] = 0;\n keyid[1] = 0;\n }\n else\n keyid_from_pk (&pk, keyid);\n }\n else\n {\n const byte *dp = fprint;\n keyid[0] = dp[12] << 24 | dp[13] << 16 | dp[14] << 8 | dp[15] ;\n keyid[1] = dp[16] << 24 | dp[17] << 16 | dp[18] << 8 | dp[19] ;\n }\n\n return keyid[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: keyid_from_pk (PKT_public_key *pk, u32 *keyid)\n{\n u32 lowbits;\n u32 dummy_keyid[2];\n\n if (!keyid)\n keyid = dummy_keyid;\n\n if( pk->keyid[0] || pk->keyid[1] )\n {\n keyid[0] = pk->keyid[0];\n keyid[1] = pk->keyid[1];\n lowbits = keyid[1];\n }\n else\n {\n const byte *dp;\n gcry_md_hd_t md;\n\n md = do_fingerprint_md(pk);\n if(md)\n\t{\n\t dp = gcry_md_read ( md, 0 );\n\t keyid[0] = dp[12] << 24 | dp[13] << 16 | dp[14] << 8 | dp[15] ;\n\t keyid[1] = dp[16] << 24 | dp[17] << 16 | dp[18] << 8 | dp[19] ;\n\t lowbits = keyid[1];\n\t gcry_md_close (md);\n\t pk->keyid[0] = keyid[0];\n\t pk->keyid[1] = keyid[1];\n\t}\n else\n\tpk->keyid[0]=pk->keyid[1]=keyid[0]=keyid[1]=lowbits=0xFFFFFFFF;\n }\n\n return lowbits;\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_signature (IOBUF inp, int pkttype, unsigned long pktlen,\n\t\t PKT_signature * sig)\n{\n int md5_len = 0;\n unsigned n;\n int is_v4 = 0;\n int rc = 0;\n int i, ndata;\n\n if (pktlen < 16)\n {\n log_error (\"packet(%d) too short\\n\", pkttype);\n if (list_mode)\n es_fputs (\":signature packet: [too short]\\n\", listfp);\n goto leave;\n }\n sig->version = iobuf_get_noeof (inp);\n pktlen--;\n if (sig->version == 4)\n is_v4 = 1;\n else if (sig->version != 2 && sig->version != 3)\n {\n log_error (\"packet(%d) with unknown version %d\\n\",\n\t\t pkttype, sig->version);\n if (list_mode)\n es_fputs (\":signature packet: [unknown version]\\n\", listfp);\n rc = gpg_error (GPG_ERR_INV_PACKET);\n goto leave;\n }\n\n if (!is_v4)\n {\n md5_len = iobuf_get_noeof (inp);\n pktlen--;\n }\n sig->sig_class = iobuf_get_noeof (inp);\n pktlen--;\n if (!is_v4)\n {\n sig->timestamp = read_32 (inp);\n pktlen -= 4;\n sig->keyid[0] = read_32 (inp);\n pktlen -= 4;\n sig->keyid[1] = read_32 (inp);\n pktlen -= 4;\n }\n sig->pubkey_algo = iobuf_get_noeof (inp);\n pktlen--;\n sig->digest_algo = iobuf_get_noeof (inp);\n pktlen--;\n sig->flags.exportable = 1;\n sig->flags.revocable = 1;\n if (is_v4) /* Read subpackets. */\n {\n n = read_16 (inp);\n pktlen -= 2; /* Length of hashed data. */\n if (n > 10000)\n\t{\n\t log_error (\"signature packet: hashed data too long\\n\");\n if (list_mode)\n es_fputs (\":signature packet: [hashed data too long]\\n\", listfp);\n\t rc = GPG_ERR_INV_PACKET;\n\t goto leave;\n\t}\n if (n)\n\t{\n\t sig->hashed = xmalloc (sizeof (*sig->hashed) + n - 1);\n\t sig->hashed->size = n;\n\t sig->hashed->len = n;\n\t if (iobuf_read (inp, sig->hashed->data, n) != n)\n\t {\n\t log_error (\"premature eof while reading \"\n\t\t\t \"hashed signature data\\n\");\n if (list_mode)\n es_fputs (\":signature packet: [premature eof]\\n\", listfp);\n\t rc = -1;\n\t goto leave;\n\t }\n\t pktlen -= n;\n\t}\n n = read_16 (inp);\n pktlen -= 2; /* Length of unhashed data. */\n if (n > 10000)\n\t{\n\t log_error (\"signature packet: unhashed data too long\\n\");\n if (list_mode)\n es_fputs (\":signature packet: [unhashed data too long]\\n\", listfp);\n\t rc = GPG_ERR_INV_PACKET;\n\t goto leave;\n\t}\n if (n)\n\t{\n\t sig->unhashed = xmalloc (sizeof (*sig->unhashed) + n - 1);\n\t sig->unhashed->size = n;\n\t sig->unhashed->len = n;\n\t if (iobuf_read (inp, sig->unhashed->data, n) != n)\n\t {\n\t log_error (\"premature eof while reading \"\n\t\t\t \"unhashed signature data\\n\");\n if (list_mode)\n es_fputs (\":signature packet: [premature eof]\\n\", listfp);\n\t rc = -1;\n\t goto leave;\n\t }\n\t pktlen -= n;\n\t}\n }\n\n if (pktlen < 5) /* Sanity check. */\n {\n log_error (\"packet(%d) too short\\n\", pkttype);\n if (list_mode)\n es_fputs (\":signature packet: [too short]\\n\", listfp);\n rc = GPG_ERR_INV_PACKET;\n goto leave;\n }\n\n sig->digest_start[0] = iobuf_get_noeof (inp);\n pktlen--;\n sig->digest_start[1] = iobuf_get_noeof (inp);\n pktlen--;\n\n if (is_v4 && sig->pubkey_algo) /* Extract required information. */\n {\n const byte *p;\n size_t len;\n\n /* Set sig->flags.unknown_critical if there is a critical bit\n * set for packets which we do not understand. */\n if (!parse_sig_subpkt (sig->hashed, SIGSUBPKT_TEST_CRITICAL, NULL)\n\t || !parse_sig_subpkt (sig->unhashed, SIGSUBPKT_TEST_CRITICAL, NULL))\n\tsig->flags.unknown_critical = 1;\n\n p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_SIG_CREATED, NULL);\n if (p)\n\tsig->timestamp = buffer_to_u32 (p);\n else if (!(sig->pubkey_algo >= 100 && sig->pubkey_algo <= 110)\n\t && opt.verbose)\n\tlog_info (\"signature packet without timestamp\\n\");\n\n p = parse_sig_subpkt2 (sig, SIGSUBPKT_ISSUER, NULL);\n if (p)\n\t{\n\t sig->keyid[0] = buffer_to_u32 (p);\n\t sig->keyid[1] = buffer_to_u32 (p + 4);\n\t}\n else if (!(sig->pubkey_algo >= 100 && sig->pubkey_algo <= 110)\n\t && opt.verbose)\n\tlog_info (\"signature packet without keyid\\n\");\n\n p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_SIG_EXPIRE, NULL);\n if (p && buffer_to_u32 (p))\n\tsig->expiredate = sig->timestamp + buffer_to_u32 (p);\n if (sig->expiredate && sig->expiredate <= make_timestamp ())\n\tsig->flags.expired = 1;\n\n p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_POLICY, NULL);\n if (p)\n\tsig->flags.policy_url = 1;\n\n p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_KS, NULL);\n if (p)\n\tsig->flags.pref_ks = 1;\n\n p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_NOTATION, NULL);\n if (p)\n\tsig->flags.notation = 1;\n\n p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_REVOCABLE, NULL);\n if (p && *p == 0)\n\tsig->flags.revocable = 0;\n\n p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_TRUST, &len);\n if (p && len == 2)\n\t{\n\t sig->trust_depth = p[0];\n\t sig->trust_value = p[1];\n\n\t /* Only look for a regexp if there is also a trust\n\t subpacket. */\n\t sig->trust_regexp =\n\t parse_sig_subpkt (sig->hashed, SIGSUBPKT_REGEXP, &len);\n\n\t /* If the regular expression is of 0 length, there is no\n\t regular expression. */\n\t if (len == 0)\n\t sig->trust_regexp = NULL;\n\t}\n\n /* We accept the exportable subpacket from either the hashed or\n unhashed areas as older versions of gpg put it in the\n unhashed area. In theory, anyway, we should never see this\n packet off of a local keyring. */\n\n p = parse_sig_subpkt2 (sig, SIGSUBPKT_EXPORTABLE, NULL);\n if (p && *p == 0)\n\tsig->flags.exportable = 0;\n\n /* Find all revocation keys. */\n if (sig->sig_class == 0x1F)\n\tparse_revkeys (sig);\n }\n\n if (list_mode)\n {\n es_fprintf (listfp, \":signature packet: algo %d, keyid %08lX%08lX\\n\"\n \"\\tversion %d, created %lu, md5len %d, sigclass 0x%02x\\n\"\n \"\\tdigest algo %d, begin of digest %02x %02x\\n\",\n sig->pubkey_algo,\n (ulong) sig->keyid[0], (ulong) sig->keyid[1],\n sig->version, (ulong) sig->timestamp, md5_len, sig->sig_class,\n sig->digest_algo, sig->digest_start[0], sig->digest_start[1]);\n if (is_v4)\n\t{\n\t parse_sig_subpkt (sig->hashed, SIGSUBPKT_LIST_HASHED, NULL);\n\t parse_sig_subpkt (sig->unhashed, SIGSUBPKT_LIST_UNHASHED, NULL);\n\t}\n }\n\n ndata = pubkey_get_nsig (sig->pubkey_algo);\n if (!ndata)\n {\n if (list_mode)\n\tes_fprintf (listfp, \"\\tunknown algorithm %d\\n\", sig->pubkey_algo);\n unknown_pubkey_warning (sig->pubkey_algo);\n\n /* We store the plain material in data[0], so that we are able\n * to write it back with build_packet(). */\n if (pktlen > (5 * MAX_EXTERN_MPI_BITS / 8))\n\t{\n\t /* We include a limit to avoid too trivial DoS attacks by\n\t having gpg allocate too much memory. */\n\t log_error (\"signature packet: too much data\\n\");\n\t rc = GPG_ERR_INV_PACKET;\n\t}\n else\n\t{\n\t sig->data[0] =\n\t gcry_mpi_set_opaque (NULL, read_rest (inp, pktlen), pktlen * 8);\n\t pktlen = 0;\n\t}\n }\n else\n {\n for (i = 0; i < ndata; i++)\n\t{\n\t n = pktlen;\n\t sig->data[i] = mpi_read (inp, &n, 0);\n\t pktlen -= n;\n\t if (list_mode)\n\t {\n\t es_fprintf (listfp, \"\\tdata: \");\n\t mpi_print (listfp, sig->data[i], mpi_print_mode);\n\t es_putc ('\\n', listfp);\n\t }\n\t if (!sig->data[i])\n\t rc = GPG_ERR_INV_PACKET;\n\t}\n }\n\n leave:\n iobuf_skip_rest (inp, pktlen, 0);\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Use inline functions to convert buffer data to scalars.\n\n* common/host2net.h (buf16_to_ulong, buf16_to_uint): New.\n(buf16_to_ushort, buf16_to_u16): New.\n(buf32_to_size_t, buf32_to_ulong, buf32_to_uint, buf32_to_u32): New.\n--\n\nCommit 91b826a38880fd8a989318585eb502582636ddd8 was not enough to\navoid all sign extension on shift problems. Hanno B\u00f6ck found a case\nwith an invalid read due to this problem. To fix that once and for\nall almost all uses of \"<< 24\" and \"<< 8\" are changed by this patch to\nuse an inline function from host2net.h.\n\nSigned-off-by: Werner Koch '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: getsrv (const char *name,struct srventry **list)\n{\n int srvcount=0;\n u16 count;\n int i, rc;\n\n *list = NULL;\n\n#ifdef USE_ADNS\n {\n adns_state state;\n adns_answer *answer = NULL;\n\n rc = adns_init (&state, adns_if_noerrprint, NULL);\n if (rc)\n {\n log_error (\"error initializing adns: %s\\n\", strerror (errno));\n return -1;\n }\n\n rc = adns_synchronous (state, name, adns_r_srv, adns_qf_quoteok_query,\n &answer);\n if (rc)\n {\n log_error (\"DNS query failed: %s\\n\", strerror (errno));\n adns_finish (state);\n return -1;\n }\n if (answer->status != adns_s_ok\n || answer->type != adns_r_srv || !answer->nrrs)\n {\n log_error (\"DNS query returned an error or no records: %s (%s)\\n\",\n adns_strerror (answer->status),\n adns_errabbrev (answer->status));\n adns_free (answer);\n adns_finish (state);\n return 0;\n }\n\n for (count = 0; count < answer->nrrs; count++)\n {\n struct srventry *srv = NULL;\n struct srventry *newlist;\n\n if (strlen (answer->rrs.srvha[count].ha.host) >= MAXDNAME)\n {\n log_info (\"hostname in SRV record too long - skipped\\n\");\n continue;\n }\n\n newlist = xtryrealloc (*list, (srvcount+1)*sizeof(struct srventry));\n if (!newlist)\n goto fail;\n *list = newlist;\n memset (&(*list)[srvcount], 0, sizeof(struct srventry));\n srv = &(*list)[srvcount];\n srvcount++;\n\n srv->priority = answer->rrs.srvha[count].priority;\n srv->weight = answer->rrs.srvha[count].weight;\n srv->port = answer->rrs.srvha[count].port;\n strcpy (srv->target, answer->rrs.srvha[count].ha.host);\n }\n\n adns_free (answer);\n adns_finish (state);\n }\n#else /*!USE_ADNS*/\n {\n unsigned char answer[2048];\n HEADER *header = (HEADER *)answer;\n unsigned char *pt, *emsg;\n int r;\n u16 dlen;\n\n r = res_query (name, C_IN, T_SRV, answer, sizeof answer);\n if (r < sizeof (HEADER) || r > sizeof answer)\n return -1;\n if (header->rcode != NOERROR || !(count=ntohs (header->ancount)))\n return 0; /* Error or no record found. */\n\n emsg = &answer[r];\n pt = &answer[sizeof(HEADER)];\n\n /* Skip over the query */\n rc = dn_skipname (pt, emsg);\n if (rc == -1)\n goto fail;\n\n pt += rc + QFIXEDSZ;\n\n while (count-- > 0 && pt < emsg)\n {\n struct srventry *srv=NULL;\n u16 type,class;\n struct srventry *newlist;\n\n newlist = xtryrealloc (*list, (srvcount+1)*sizeof(struct srventry));\n if (!newlist)\n goto fail;\n *list = newlist;\n memset(&(*list)[srvcount],0,sizeof(struct srventry));\n srv=&(*list)[srvcount];\n srvcount++;\n\n rc = dn_skipname(pt,emsg); /* the name we just queried for */\n if (rc == -1)\n goto fail;\n pt+=rc;\n\n /* Truncated message? */\n if((emsg-pt)<16)\n goto fail;\n\n type=*pt++ << 8;\n type|=*pt++;\n /* We asked for SRV and got something else !? */\n if(type!=T_SRV)\n goto fail;\n\n class=*pt++ << 8;\n class|=*pt++;\n /* We asked for IN and got something else !? */\n if(class!=C_IN)\n goto fail;\n\n pt+=4; /* ttl */\n dlen=*pt++ << 8;\n dlen|=*pt++;\n srv->priority=*pt++ << 8;\n srv->priority|=*pt++;\n srv->weight=*pt++ << 8;\n srv->weight|=*pt++;\n srv->port=*pt++ << 8;\n srv->port|=*pt++;\n\n /* Get the name. 2782 doesn't allow name compression, but\n dn_expand still works to pull the name out of the\n packet. */\n rc = dn_expand(answer,emsg,pt,srv->target,MAXDNAME);\n if (rc == 1 && srv->target[0] == 0) /* \".\" */\n {\n xfree(*list);\n *list = NULL;\n return 0;\n }\n if (rc == -1)\n goto fail;\n pt += rc;\n /* Corrupt packet? */\n if (dlen != rc+6)\n goto fail;\n }\n }\n#endif /*!USE_ADNS*/\n\n /* Now we have an array of all the srv records. */\n\n /* Order by priority */\n qsort(*list,srvcount,sizeof(struct srventry),priosort);\n\n /* For each priority, move the zero-weighted items first. */\n for (i=0; i < srvcount; i++)\n {\n int j;\n\n for (j=i;j < srvcount && (*list)[i].priority == (*list)[j].priority; j++)\n {\n if((*list)[j].weight==0)\n {\n /* Swap j with i */\n if(j!=i)\n {\n struct srventry temp;\n\n memcpy (&temp,&(*list)[j],sizeof(struct srventry));\n memcpy (&(*list)[j],&(*list)[i],sizeof(struct srventry));\n memcpy (&(*list)[i],&temp,sizeof(struct srventry));\n }\n\n break;\n }\n }\n }\n\n /* Run the RFC-2782 weighting algorithm. We don't need very high\n quality randomness for this, so regular libc srand/rand is\n sufficient. Fixme: It is a bit questionaly to reinitalize srand\n - better use a gnupg fucntion for this. */\n srand(time(NULL)*getpid());\n\n for (i=0; i < srvcount; i++)\n {\n int j;\n float prio_count=0,chose;\n\n for (j=i; j < srvcount && (*list)[i].priority == (*list)[j].priority; j++)\n {\n prio_count+=(*list)[j].weight;\n (*list)[j].run_count=prio_count;\n }\n\n chose=prio_count*rand()/RAND_MAX;\n\n for (j=i;j \"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: next_packet (unsigned char const **bufptr, size_t *buflen,\n unsigned char const **r_data, size_t *r_datalen, int *r_pkttype,\n size_t *r_ntotal)\n{\n const unsigned char *buf = *bufptr;\n size_t len = *buflen;\n int c, ctb, pkttype;\n unsigned long pktlen;\n\n if (!len)\n return gpg_error (GPG_ERR_NO_DATA);\n\n ctb = *buf++; len--;\n if ( !(ctb & 0x80) )\n return gpg_error (GPG_ERR_INV_PACKET); /* Invalid CTB. */\n\n pktlen = 0;\n if ((ctb & 0x40)) /* New style (OpenPGP) CTB. */\n {\n pkttype = (ctb & 0x3f);\n if (!len)\n return gpg_error (GPG_ERR_INV_PACKET); /* No 1st length byte. */\n c = *buf++; len--;\n if (pkttype == PKT_COMPRESSED)\n return gpg_error (GPG_ERR_UNEXPECTED); /* ... packet in a keyblock. */\n if ( c < 192 )\n pktlen = c;\n else if ( c < 224 )\n {\n pktlen = (c - 192) * 256;\n if (!len)\n return gpg_error (GPG_ERR_INV_PACKET); /* No 2nd length byte. */\n c = *buf++; len--;\n pktlen += c + 192;\n }\n else if (c == 255)\n {\n if (len <4 )\n return gpg_error (GPG_ERR_INV_PACKET); /* No length bytes. */\n pktlen = (*buf++) << 24;\n pktlen |= (*buf++) << 16;\n pktlen |= (*buf++) << 8;\n pktlen |= (*buf++);\n len -= 4;\n }\n else /* Partial length encoding is not allowed for key packets. */\n return gpg_error (GPG_ERR_UNEXPECTED);\n }\n else /* Old style CTB. */\n {\n int lenbytes;\n\n pktlen = 0;\n pkttype = (ctb>>2)&0xf;\n lenbytes = ((ctb&3)==3)? 0 : (1<<(ctb & 3));\n if (!lenbytes) /* Not allowed in key packets. */\n return gpg_error (GPG_ERR_UNEXPECTED);\n if (len < lenbytes)\n return gpg_error (GPG_ERR_INV_PACKET); /* Not enough length bytes. */\n for (; lenbytes; lenbytes--)\n {\n pktlen <<= 8;\n pktlen |= *buf++; len--;\n\t}\n }\n\n /* Do some basic sanity check. */\n switch (pkttype)\n {\n case PKT_SIGNATURE:\n case PKT_SECRET_KEY:\n case PKT_PUBLIC_KEY:\n case PKT_SECRET_SUBKEY:\n case PKT_MARKER:\n case PKT_RING_TRUST:\n case PKT_USER_ID:\n case PKT_PUBLIC_SUBKEY:\n case PKT_OLD_COMMENT:\n case PKT_ATTRIBUTE:\n case PKT_COMMENT:\n case PKT_GPG_CONTROL:\n break; /* Okay these are allowed packets. */\n default:\n return gpg_error (GPG_ERR_UNEXPECTED);\n }\n\n if (pktlen == (unsigned long)(-1))\n return gpg_error (GPG_ERR_INV_PACKET);\n\n if (pktlen > len)\n return gpg_error (GPG_ERR_INV_PACKET); /* Packet length header too long. */\n\n *r_data = buf;\n *r_datalen = pktlen;\n *r_pkttype = pkttype;\n *r_ntotal = (buf - *bufptr) + pktlen;\n\n *bufptr = buf + pktlen;\n *buflen = len - pktlen;\n if (!*buflen)\n *bufptr = NULL;\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Use inline functions to convert buffer data to scalars.\n\n* common/host2net.h (buf16_to_ulong, buf16_to_uint): New.\n(buf16_to_ushort, buf16_to_u16): New.\n(buf32_to_size_t, buf32_to_ulong, buf32_to_uint, buf32_to_u32): New.\n--\n\nCommit 91b826a38880fd8a989318585eb502582636ddd8 was not enough to\navoid all sign extension on shift problems. Hanno B\u00f6ck found a case\nwith an invalid read due to this problem. To fix that once and for\nall almost all uses of \"<< 24\" and \"<< 8\" are changed by this patch to\nuse an inline function from host2net.h.\n\nSigned-off-by: Werner Koch '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xfs_attr_rmtval_set(\n\tstruct xfs_da_args\t*args)\n{\n\tstruct xfs_inode\t*dp = args->dp;\n\tstruct xfs_mount\t*mp = dp->i_mount;\n\tstruct xfs_bmbt_irec\tmap;\n\txfs_dablk_t\t\tlblkno;\n\txfs_fileoff_t\t\tlfileoff = 0;\n\t__uint8_t\t\t*src = args->value;\n\tint\t\t\tblkcnt;\n\tint\t\t\tvaluelen;\n\tint\t\t\tnmap;\n\tint\t\t\terror;\n\tint\t\t\toffset = 0;\n\n\ttrace_xfs_attr_rmtval_set(args);\n\n\t/*\n\t * Find a \"hole\" in the attribute address space large enough for\n\t * us to drop the new attribute's value into. Because CRC enable\n\t * attributes have headers, we can't just do a straight byte to FSB\n\t * conversion and have to take the header space into account.\n\t */\n\tblkcnt = xfs_attr3_rmt_blocks(mp, args->valuelen);\n\terror = xfs_bmap_first_unused(args->trans, args->dp, blkcnt, &lfileoff,\n\t\t\t\t\t\t XFS_ATTR_FORK);\n\tif (error)\n\t\treturn error;\n\n\targs->rmtblkno = lblkno = (xfs_dablk_t)lfileoff;\n\targs->rmtblkcnt = blkcnt;\n\n\t/*\n\t * Roll through the \"value\", allocating blocks on disk as required.\n\t */\n\twhile (blkcnt > 0) {\n\t\tint\tcommitted;\n\n\t\t/*\n\t\t * Allocate a single extent, up to the size of the value.\n\t\t */\n\t\txfs_bmap_init(args->flist, args->firstblock);\n\t\tnmap = 1;\n\t\terror = xfs_bmapi_write(args->trans, dp, (xfs_fileoff_t)lblkno,\n\t\t\t\t blkcnt,\n\t\t\t\t XFS_BMAPI_ATTRFORK | XFS_BMAPI_METADATA,\n\t\t\t\t args->firstblock, args->total, &map, &nmap,\n\t\t\t\t args->flist);\n\t\tif (!error) {\n\t\t\terror = xfs_bmap_finish(&args->trans, args->flist,\n\t\t\t\t\t\t&committed);\n\t\t}\n\t\tif (error) {\n\t\t\tASSERT(committed);\n\t\t\targs->trans = NULL;\n\t\t\txfs_bmap_cancel(args->flist);\n\t\t\treturn(error);\n\t\t}\n\n\t\t/*\n\t\t * bmap_finish() may have committed the last trans and started\n\t\t * a new one. We need the inode to be in all transactions.\n\t\t */\n\t\tif (committed)\n\t\t\txfs_trans_ijoin(args->trans, dp, 0);\n\n\t\tASSERT(nmap == 1);\n\t\tASSERT((map.br_startblock != DELAYSTARTBLOCK) &&\n\t\t (map.br_startblock != HOLESTARTBLOCK));\n\t\tlblkno += map.br_blockcount;\n\t\tblkcnt -= map.br_blockcount;\n\n\t\t/*\n\t\t * Start the next trans in the chain.\n\t\t */\n\t\terror = xfs_trans_roll(&args->trans, dp);\n\t\tif (error)\n\t\t\treturn (error);\n\t}\n\n\t/*\n\t * Roll through the \"value\", copying the attribute value to the\n\t * already-allocated blocks. Blocks are written synchronously\n\t * so that we can know they are all on disk before we turn off\n\t * the INCOMPLETE flag.\n\t */\n\tlblkno = args->rmtblkno;\n\tblkcnt = args->rmtblkcnt;\n\tvaluelen = args->valuelen;\n\twhile (valuelen > 0) {\n\t\tstruct xfs_buf\t*bp;\n\t\txfs_daddr_t\tdblkno;\n\t\tint\t\tdblkcnt;\n\n\t\tASSERT(blkcnt > 0);\n\n\t\txfs_bmap_init(args->flist, args->firstblock);\n\t\tnmap = 1;\n\t\terror = xfs_bmapi_read(dp, (xfs_fileoff_t)lblkno,\n\t\t\t\t blkcnt, &map, &nmap,\n\t\t\t\t XFS_BMAPI_ATTRFORK);\n\t\tif (error)\n\t\t\treturn(error);\n\t\tASSERT(nmap == 1);\n\t\tASSERT((map.br_startblock != DELAYSTARTBLOCK) &&\n\t\t (map.br_startblock != HOLESTARTBLOCK));\n\n\t\tdblkno = XFS_FSB_TO_DADDR(mp, map.br_startblock),\n\t\tdblkcnt = XFS_FSB_TO_BB(mp, map.br_blockcount);\n\n\t\tbp = xfs_buf_get(mp->m_ddev_targp, dblkno, dblkcnt, 0);\n\t\tif (!bp)\n\t\t\treturn ENOMEM;\n\t\tbp->b_ops = &xfs_attr3_rmt_buf_ops;\n\n\t\txfs_attr_rmtval_copyin(mp, bp, args->dp->i_ino, &offset,\n\t\t\t\t &valuelen, &src);\n\n\t\terror = xfs_bwrite(bp);\t/* GROT: NOTE: synchronous write */\n\t\txfs_buf_relse(bp);\n\t\tif (error)\n\t\t\treturn error;\n\n\n\t\t/* roll attribute extent map forwards */\n\t\tlblkno += map.br_blockcount;\n\t\tblkcnt -= map.br_blockcount;\n\t}\n\tASSERT(valuelen == 0);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'xfs: remote attribute overwrite causes transaction overrun\n\nCommit e461fcb (\"xfs: remote attribute lookups require the value\nlength\") passes the remote attribute length in the xfs_da_args\nstructure on lookup so that CRC calculations and validity checking\ncan be performed correctly by related code. This, unfortunately has\nthe side effect of changing the args->valuelen parameter in cases\nwhere it shouldn't.\n\nThat is, when we replace a remote attribute, the incoming\nreplacement stores the value and length in args->value and\nargs->valuelen, but then the lookup which finds the existing remote\nattribute overwrites args->valuelen with the length of the remote\nattribute being replaced. Hence when we go to create the new\nattribute, we create it of the size of the existing remote\nattribute, not the size it is supposed to be. When the new attribute\nis much smaller than the old attribute, this results in a\ntransaction overrun and an ASSERT() failure on a debug kernel:\n\nXFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331\n\nFix this by keeping the remote attribute value length separate to\nthe attribute value length in the xfs_da_args structure. The enables\nus to pass the length of the remote attribute to be removed without\noverwriting the new attribute's length.\n\nAlso, ensure that when we save remote block contexts for a later\nrename we zero the original state variables so that we don't confuse\nthe state of the attribute to be removes with the state of the new\nattribute that we just added. [Spotted by Brain Foster.]\n\nSigned-off-by: Dave Chinner \nReviewed-by: Brian Foster \nSigned-off-by: Dave Chinner '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xfs_attr_calc_size(\n\tstruct xfs_inode \t*ip,\n\tint\t\t\tnamelen,\n\tint\t\t\tvaluelen,\n\tint\t\t\t*local)\n{\n\tstruct xfs_mount \t*mp = ip->i_mount;\n\tint\t\t\tsize;\n\tint\t\t\tnblks;\n\n\t/*\n\t * Determine space new attribute will use, and if it would be\n\t * \"local\" or \"remote\" (note: local != inline).\n\t */\n\tsize = xfs_attr_leaf_newentsize(namelen, valuelen,\n\t\t\t\t\tmp->m_sb.sb_blocksize, local);\n\n\tnblks = XFS_DAENTER_SPACE_RES(mp, XFS_ATTR_FORK);\n\tif (*local) {\n\t\tif (size > (mp->m_sb.sb_blocksize >> 1)) {\n\t\t\t/* Double split possible */\n\t\t\tnblks *= 2;\n\t\t}\n\t} else {\n\t\t/*\n\t\t * Out of line attribute, cannot double split, but\n\t\t * make room for the attribute value itself.\n\t\t */\n\t\tuint\tdblocks = XFS_B_TO_FSB(mp, valuelen);\n\t\tnblks += dblocks;\n\t\tnblks += XFS_NEXTENTADD_SPACE_RES(mp, dblocks, XFS_ATTR_FORK);\n\t}\n\n\treturn nblks;\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: void mark_files_ro(struct super_block *sb)\n{\n\tstruct file *f;\n\n\tlg_global_lock(&files_lglock);\n\tdo_file_list_for_each_entry(sb, f) {\n\t\tif (!file_count(f))\n\t\t\tcontinue;\n\t\tif (!(f->f_mode & FMODE_WRITE))\n\t\t\tcontinue;\n\t\tspin_lock(&f->f_lock);\n\t\tf->f_mode &= ~FMODE_WRITE;\n\t\tspin_unlock(&f->f_lock);\n\t\tif (file_check_writeable(f) != 0)\n\t\t\tcontinue;\n\t\t__mnt_drop_write(f->f_path.mnt);\n\t\tfile_release_write(f);\n\t} while_file_list_for_each_entry;\n\tlg_global_unlock(&files_lglock);\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: static void iov_fault_in_pages_read(struct iovec *iov, unsigned long len)\n{\n\twhile (!iov->iov_len)\n\t\tiov++;\n\n\twhile (len > 0) {\n\t\tunsigned long this_len;\n\n\t\tthis_len = min_t(unsigned long, len, iov->iov_len);\n\t\tfault_in_pages_readable(iov->iov_base, this_len);\n\t\tlen -= this_len;\n\t\tiov++;\n\t}\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 xrstor_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:\"XRSTORS\"\\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:\"XRSTOR\"\\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: int basic_authentication(zval* this_ptr, smart_str* soap_headers TSRMLS_DC)\n{\n\tzval **login, **password;\n\n\tif (zend_hash_find(Z_OBJPROP_P(this_ptr), \"_login\", sizeof(\"_login\"), (void **)&login) == SUCCESS &&\n\t\t\t!zend_hash_exists(Z_OBJPROP_P(this_ptr), \"_digest\", sizeof(\"_digest\"))) {\n\t\tunsigned char* buf;\n\t\tint len;\n\t\tsmart_str auth = {0};\n\n\t\tsmart_str_appendl(&auth, Z_STRVAL_PP(login), Z_STRLEN_PP(login));\n\t\tsmart_str_appendc(&auth, ':');\n\t\tif (zend_hash_find(Z_OBJPROP_P(this_ptr), \"_password\", sizeof(\"_password\"), (void **)&password) == SUCCESS) {\n\t\t\tsmart_str_appendl(&auth, Z_STRVAL_PP(password), Z_STRLEN_PP(password));\n\t\t}\n\t\tsmart_str_0(&auth);\n\t\tbuf = php_base64_encode((unsigned char*)auth.c, auth.len, &len);\n\t\tsmart_str_append_const(soap_headers, \"Authorization: Basic \");\n\t\tsmart_str_appendl(soap_headers, (char*)buf, len);\n\t\tsmart_str_append_const(soap_headers, \"\\r\\n\");\n\t\tefree(buf);\n\t\tsmart_str_free(&auth);\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-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_sid_request(enum request_types request_type, const char *sid,\n struct berval **berval)\n{\n int ret;\n struct passwd pwd;\n struct passwd *pwd_result = NULL;\n struct group grp;\n struct group *grp_result = NULL;\n char *domain_name = NULL;\n char *fq_name = NULL;\n char *object_name = NULL;\n char *sep;\n size_t buf_len;\n char *buf = NULL;\n enum sss_id_type id_type;\n struct sss_nss_kv *kv_list = NULL;\n\n ret = sss_nss_getnamebysid(sid, &fq_name, &id_type);\n if (ret != 0) {\n if (ret == ENOENT) {\n ret = LDAP_NO_SUCH_OBJECT;\n } else {\n ret = LDAP_OPERATIONS_ERROR;\n }\n goto done;\n }\n\n sep = strchr(fq_name, SSSD_DOMAIN_SEPARATOR);\n if (sep == NULL) {\n ret = LDAP_OPERATIONS_ERROR;\n goto done;\n }\n\n object_name = strndup(fq_name, (sep - fq_name));\n domain_name = strdup(sep + 1);\n if (object_name == NULL || domain_name == NULL) {\n ret = LDAP_OPERATIONS_ERROR;\n goto done;\n }\n\n if (request_type == REQ_SIMPLE) {\n ret = pack_ber_name(domain_name, object_name, berval);\n goto done;\n }\n\n ret = get_buffer(&buf_len, &buf);\n if (ret != LDAP_SUCCESS) {\n goto done;\n }\n\n switch(id_type) {\n case SSS_ID_TYPE_UID:\n case SSS_ID_TYPE_BOTH:\n ret = getpwnam_r(fq_name, &pwd, buf, buf_len, &pwd_result);\n if (ret != 0) {\n ret = LDAP_NO_SUCH_OBJECT;\n goto done;\n }\n\n if (pwd_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(pwd.pw_name, &kv_list, &id_type);\n if (ret != 0 || !(id_type == SSS_ID_TYPE_UID\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_user((request_type == REQ_FULL ? RESP_USER\n : RESP_USER_GROUPLIST),\n domain_name, pwd.pw_name, pwd.pw_uid,\n pwd.pw_gid, pwd.pw_gecos, pwd.pw_dir,\n pwd.pw_shell, kv_list, berval);\n break;\n case SSS_ID_TYPE_GID:\n ret = getgrnam_r(fq_name, &grp, buf, buf_len, &grp_result);\n if (ret != 0) {\n ret = LDAP_NO_SUCH_OBJECT;\n goto done;\n }\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 break;\n default:\n ret = LDAP_OPERATIONS_ERROR;\n goto done;\n }\n\ndone:\n sss_nss_free_kv(kv_list);\n free(fq_name);\n free(object_name);\n free(domain_name);\n free(buf);\n\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: static int ipa_extdom_init_ctx(Slapi_PBlock *pb, struct ipa_extdom_ctx **_ctx)\n{\n struct ipa_extdom_ctx *ctx;\n Slapi_Entry *e;\n int ret;\n\n ctx = calloc(1, sizeof(struct ipa_extdom_ctx));\n if (!ctx) {\n return LDAP_OPERATIONS_ERROR;\n }\n\n ret = slapi_pblock_get(pb, SLAPI_PLUGIN_IDENTITY, &ctx->plugin_id);\n if ((ret != 0) || (NULL == ctx->plugin_id)) {\n LOG_FATAL(\"Could not get identity or identity was NULL\\n\");\n if (ret == 0) {\n ret = -1;\n }\n goto done;\n }\n\n slapi_pblock_get(pb, SLAPI_PLUGIN_CONFIG_ENTRY, &e);\n if (!e) {\n LOG_FATAL(\"Plugin configuration not found!\\n\");\n ret = -1;\n goto done;\n }\n\n ctx->base_dn = slapi_entry_attr_get_charptr(e, \"nsslapd-basedn\");\n if (!ctx->base_dn) {\n LOG_FATAL(\"Base DN not found in plugin configuration not found!\\n\");\n ret = -1;\n goto done;\n }\n\n\ndone:\n if (ret) {\n free(ctx);\n } else {\n *_ctx = ctx;\n }\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-19'], 'message': 'extdom: make nss buffer configurable\n\nThe get*_r_wrapper() calls expect a maximum buffer size to avoid memory\nshortage if too many threads try to allocate buffers e.g. for large\ngroups. With this patch this size can be configured by setting\nipaExtdomMaxNssBufSize in the plugin config object\ncn=ipa_extdom_extop,cn=plugins,cn=config.\n\nRelated to https://fedorahosted.org/freeipa/ticket/4908\n\nReviewed-By: Alexander Bokovoy '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xmlBufAdd(xmlBufPtr buf, const xmlChar *str, int len) {\n unsigned int needSize;\n\n if ((str == NULL) || (buf == NULL) || (buf->error))\n\treturn -1;\n CHECK_COMPAT(buf)\n\n if (buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) return -1;\n if (len < -1) {\n#ifdef DEBUG_BUFFER\n xmlGenericError(xmlGenericErrorContext,\n\t\t\"xmlBufAdd: len < 0\\n\");\n#endif\n\treturn -1;\n }\n if (len == 0) return 0;\n\n if (len < 0)\n len = xmlStrlen(str);\n\n if (len < 0) return -1;\n if (len == 0) return 0;\n\n needSize = buf->use + len + 2;\n if (needSize > buf->size){\n if (!xmlBufResize(buf, needSize)){\n\t xmlBufMemoryError(buf, \"growing buffer\");\n return XML_ERR_NO_MEMORY;\n }\n }\n\n memmove(&buf->content[buf->use], str, len*sizeof(xmlChar));\n buf->use += len;\n buf->content[buf->use] = 0;\n UPDATE_COMPAT(buf)\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-1819 Enforce the reader to run in constant memory\n\nOne of the operation on the reader could resolve entities\nleading to the classic expansion issue. Make sure the\nbuffer used for xmlreader operation is bounded.\nIntroduce a new allocation type for the buffers for this effect.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int main(int argc, char** argv)\n{\n /* Kernel starts us with all fd's closed.\n * But it's dangerous:\n * fprintf(stderr) can dump messages into random fds, etc.\n * Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null.\n */\n int fd = xopen(\"/dev/null\", O_RDWR);\n while (fd < 2)\n\tfd = xdup(fd);\n if (fd > 2)\n\tclose(fd);\n\n if (argc < 8)\n {\n /* percent specifier: %s %c %p %u %g %t %e %h */\n /* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/\n error_msg_and_die(\"Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]\", argv[0]);\n }\n\n /* Not needed on 2.6.30.\n * At least 2.6.18 has a bug where\n * argv[1] = \"SIGNO CORE_SIZE_LIMIT PID ...\"\n * argv[2] = \"CORE_SIZE_LIMIT PID ...\"\n * and so on. Fixing it:\n */\n if (strchr(argv[1], ' '))\n {\n int i;\n for (i = 1; argv[i]; i++)\n {\n strchrnul(argv[i], ' ')[0] = '\\0';\n }\n }\n\n logmode = LOGMODE_JOURNAL;\n\n /* Parse abrt.conf */\n load_abrt_conf();\n /* ... and plugins/CCpp.conf */\n bool setting_MakeCompatCore;\n bool setting_SaveBinaryImage;\n {\n map_string_t *settings = new_map_string();\n load_abrt_plugin_conf_file(\"CCpp.conf\", settings);\n const char *value;\n value = get_map_string_item_or_NULL(settings, \"MakeCompatCore\");\n setting_MakeCompatCore = value && string_to_bool(value);\n value = get_map_string_item_or_NULL(settings, \"SaveBinaryImage\");\n setting_SaveBinaryImage = value && string_to_bool(value);\n value = get_map_string_item_or_NULL(settings, \"VerboseLog\");\n if (value)\n g_verbose = xatoi_positive(value);\n free_map_string(settings);\n }\n\n errno = 0;\n const char* signal_str = argv[1];\n int signal_no = xatoi_positive(signal_str);\n off_t ulimit_c = strtoull(argv[2], NULL, 10);\n if (ulimit_c < 0) /* unlimited? */\n {\n /* set to max possible >0 value */\n ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1));\n }\n const char *pid_str = argv[3];\n pid_t pid = xatoi_positive(argv[3]);\n uid_t uid = xatoi_positive(argv[4]);\n if (errno || pid <= 0)\n {\n perror_msg_and_die(\"PID '%s' or limit '%s' is bogus\", argv[3], argv[2]);\n }\n\n {\n char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN\"/abrt/saved_core_pattern\");\n /* If we have a saved pattern and it's not a \"|PROG ARGS\" thing... */\n if (s && s[0] != '|')\n core_basename = s;\n else\n free(s);\n }\n\n struct utsname uts;\n if (!argv[8]) /* no HOSTNAME? */\n {\n uname(&uts);\n argv[8] = uts.nodename;\n }\n\n char path[PATH_MAX];\n\n int src_fd_binary = -1;\n char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL);\n if (executable && strstr(executable, \"/abrt-hook-ccpp\"))\n {\n error_msg_and_die(\"PID %lu is '%s', not dumping it to avoid recursion\",\n (long)pid, executable);\n }\n\n user_pwd = get_cwd(pid); /* may be NULL on error */\n log_notice(\"user_pwd:'%s'\", user_pwd);\n\n sprintf(path, \"/proc/%lu/status\", (long)pid);\n proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL);\n\n uid_t fsuid = uid;\n uid_t tmp_fsuid = get_fsuid();\n int suid_policy = dump_suid_policy();\n if (tmp_fsuid != uid)\n {\n /* use root for suided apps unless it's explicitly set to UNSAFE */\n fsuid = 0;\n if (suid_policy == DUMP_SUID_UNSAFE)\n {\n fsuid = tmp_fsuid;\n }\n }\n\n /* Open a fd to compat coredump, if requested and is possible */\n if (setting_MakeCompatCore && ulimit_c != 0)\n /* note: checks \"user_pwd == NULL\" inside; updates core_basename */\n user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]);\n\n if (executable == NULL)\n {\n /* readlink on /proc/$PID/exe failed, don't create abrt dump dir */\n error_msg(\"Can't read /proc/%lu/exe link\", (long)pid);\n goto create_user_core;\n }\n\n const char *signame = NULL;\n switch (signal_no)\n {\n case SIGILL : signame = \"ILL\" ; break;\n case SIGFPE : signame = \"FPE\" ; break;\n case SIGSEGV: signame = \"SEGV\"; break;\n case SIGBUS : signame = \"BUS\" ; break; //Bus error (bad memory access)\n case SIGABRT: signame = \"ABRT\"; break; //usually when abort() was called\n // We have real-world reports from users who see buggy programs\n // dying with SIGTRAP, uncommented it too:\n case SIGTRAP: signame = \"TRAP\"; break; //Trace/breakpoint trap\n // These usually aren't caused by bugs:\n //case SIGQUIT: signame = \"QUIT\"; break; //Quit from keyboard\n //case SIGSYS : signame = \"SYS\" ; break; //Bad argument to routine (SVr4)\n //case SIGXCPU: signame = \"XCPU\"; break; //CPU time limit exceeded (4.2BSD)\n //case SIGXFSZ: signame = \"XFSZ\"; break; //File size limit exceeded (4.2BSD)\n default: goto create_user_core; // not a signal we care about\n }\n\n if (!daemon_is_ok())\n {\n /* not an error, exit with exit code 0 */\n log(\"abrtd is not running. If it crashed, \"\n \"/proc/sys/kernel/core_pattern contains a stale value, \"\n \"consider resetting it to 'core'\"\n );\n goto create_user_core;\n }\n\n if (g_settings_nMaxCrashReportsSize > 0)\n {\n /* If free space is less than 1/4 of MaxCrashReportsSize... */\n if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location))\n goto create_user_core;\n }\n\n /* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes\n * if they happen too often. Else, write new marker value.\n */\n snprintf(path, sizeof(path), \"%s/last-ccpp\", g_settings_dump_location);\n if (check_recent_crash_file(path, executable))\n {\n /* It is a repeating crash */\n goto create_user_core;\n }\n\n const char *last_slash = strrchr(executable, '/');\n if (last_slash && strncmp(++last_slash, \"abrt\", 4) == 0)\n {\n /* If abrtd/abrt-foo crashes, we don't want to create a _directory_,\n * since that can make new copy of abrtd to process it,\n * and maybe crash again...\n * Unlike dirs, mere files are ignored by abrtd.\n */\n snprintf(path, sizeof(path), \"%s/%s-coredump\", g_settings_dump_location, last_slash);\n int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600);\n off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE);\n if (core_size < 0 || fsync(abrt_core_fd) != 0)\n {\n unlink(path);\n /* copyfd_eof logs the error including errno string,\n * but it does not log file name */\n error_msg_and_die(\"Error saving '%s'\", path);\n }\n log(\"Saved core dump of pid %lu (%s) to %s (%llu bytes)\", (long)pid, executable, path, (long long)core_size);\n return 0;\n }\n\n unsigned path_len = snprintf(path, sizeof(path), \"%s/ccpp-%s-%lu.new\",\n g_settings_dump_location, iso_date_string(NULL), (long)pid);\n if (path_len >= (sizeof(path) - sizeof(\"/\"FILENAME_COREDUMP)))\n {\n goto create_user_core;\n }\n\n /* use fsuid instead of uid, so we don't expose any sensitive\n * information of suided app in /var/tmp/abrt\n */\n dd = dd_create(path, fsuid, DEFAULT_DUMP_DIR_MODE);\n if (dd)\n {\n char *rootdir = get_rootdir(pid);\n\n dd_create_basic_files(dd, fsuid, (rootdir && strcmp(rootdir, \"/\") != 0) ? rootdir : NULL);\n\n char source_filename[sizeof(\"/proc/%lu/somewhat_long_name\") + sizeof(long)*3];\n int source_base_ofs = sprintf(source_filename, \"/proc/%lu/smaps\", (long)pid);\n source_base_ofs -= strlen(\"smaps\");\n char *dest_filename = concat_path_file(dd->dd_dirname, \"also_somewhat_longish_name\");\n char *dest_base = strrchr(dest_filename, '/') + 1;\n\n // Disabled for now: /proc/PID/smaps tends to be BIG,\n // and not much more informative than /proc/PID/maps:\n //copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);\n\n strcpy(source_filename + source_base_ofs, \"maps\");\n strcpy(dest_base, FILENAME_MAPS);\n copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);\n\n strcpy(source_filename + source_base_ofs, \"limits\");\n strcpy(dest_base, FILENAME_LIMITS);\n copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);\n\n strcpy(source_filename + source_base_ofs, \"cgroup\");\n strcpy(dest_base, FILENAME_CGROUP);\n copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);\n\n strcpy(dest_base, FILENAME_OPEN_FDS);\n dump_fd_info(dest_filename, source_filename, source_base_ofs, dd->dd_uid, dd->dd_gid);\n\n free(dest_filename);\n\n dd_save_text(dd, FILENAME_ANALYZER, \"CCpp\");\n dd_save_text(dd, FILENAME_TYPE, \"CCpp\");\n dd_save_text(dd, FILENAME_EXECUTABLE, executable);\n dd_save_text(dd, FILENAME_PID, pid_str);\n dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status);\n if (user_pwd)\n dd_save_text(dd, FILENAME_PWD, user_pwd);\n if (rootdir)\n {\n if (strcmp(rootdir, \"/\") != 0)\n dd_save_text(dd, FILENAME_ROOTDIR, rootdir);\n }\n\n char *reason = xasprintf(\"%s killed by SIG%s\",\n last_slash, signame ? signame : signal_str);\n dd_save_text(dd, FILENAME_REASON, reason);\n free(reason);\n\n char *cmdline = get_cmdline(pid);\n dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : \"\");\n free(cmdline);\n\n char *environ = get_environ(pid);\n dd_save_text(dd, FILENAME_ENVIRON, environ ? : \"\");\n free(environ);\n\n char *fips_enabled = xmalloc_fopen_fgetline_fclose(\"/proc/sys/crypto/fips_enabled\");\n if (fips_enabled)\n {\n if (strcmp(fips_enabled, \"0\") != 0)\n dd_save_text(dd, \"fips_enabled\", fips_enabled);\n free(fips_enabled);\n }\n\n dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION);\n\n if (src_fd_binary > 0)\n {\n strcpy(path + path_len, \"/\"FILENAME_BINARY);\n int dst_fd = create_or_die(path);\n off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE);\n if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0)\n {\n dd_delete(dd);\n error_msg_and_die(\"Error saving '%s'\", path);\n }\n close(src_fd_binary);\n }\n\n strcpy(path + path_len, \"/\"FILENAME_COREDUMP);\n int abrt_core_fd = create_or_die(path);\n\n /* We write both coredumps at once.\n * We can't write user coredump first, since it might be truncated\n * and thus can't be copied and used as abrt coredump;\n * and if we write abrt coredump first and then copy it as user one,\n * then we have a race when process exits but coredump does not exist yet:\n * $ echo -e '#include\\nmain(){raise(SIGSEGV);}' | gcc -o test -x c -\n * $ rm -f core*; ulimit -c unlimited; ./test; ls -l core*\n * 21631 Segmentation fault (core dumped) ./test\n * ls: cannot access core*: No such file or directory <=== BAD\n */\n off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c);\n if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0)\n {\n unlink(path);\n dd_delete(dd);\n if (user_core_fd >= 0)\n {\n xchdir(user_pwd);\n unlink(core_basename);\n }\n /* copyfd_sparse logs the error including errno string,\n * but it does not log file name */\n error_msg_and_die(\"Error writing '%s'\", path);\n }\n if (user_core_fd >= 0\n /* error writing user coredump? */\n && (fsync(user_core_fd) != 0 || close(user_core_fd) != 0\n /* user coredump is too big? */\n || (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c)\n )\n ) {\n /* nuke it (silently) */\n xchdir(user_pwd);\n unlink(core_basename);\n }\n\n/* Because of #1211835 and #1126850 */\n#if 0\n /* Save JVM crash log if it exists. (JVM's coredump per se\n * is nearly useless for JVM developers)\n */\n {\n char *java_log = xasprintf(\"/tmp/jvm-%lu/hs_error.log\", (long)pid);\n int src_fd = open(java_log, O_RDONLY);\n free(java_log);\n\n /* If we couldn't open the error log in /tmp directory we can try to\n * read the log from the current directory. It may produce AVC, it\n * may produce some error log but all these are expected.\n */\n if (src_fd < 0)\n {\n java_log = xasprintf(\"%s/hs_err_pid%lu.log\", user_pwd, (long)pid);\n src_fd = open(java_log, O_RDONLY);\n free(java_log);\n }\n\n if (src_fd >= 0)\n {\n strcpy(path + path_len, \"/hs_err.log\");\n int dst_fd = create_or_die(path);\n off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE);\n if (close(dst_fd) != 0 || sz < 0)\n {\n dd_delete(dd);\n error_msg_and_die(\"Error saving '%s'\", path);\n }\n close(src_fd);\n }\n }\n#endif\n\n /* We close dumpdir before we start catering for crash storm case.\n * Otherwise, delete_dump_dir's from other concurrent\n * CCpp's won't be able to delete our dump (their delete_dump_dir\n * will wait for us), and we won't be able to delete their dumps.\n * Classic deadlock.\n */\n dd_close(dd);\n path[path_len] = '\\0'; /* path now contains only directory name */\n char *newpath = xstrndup(path, path_len - (sizeof(\".new\")-1));\n if (rename(path, newpath) == 0)\n strcpy(path, newpath);\n free(newpath);\n\n log(\"Saved core dump of pid %lu (%s) to %s (%llu bytes)\", (long)pid, executable, path, (long long)core_size);\n\n notify_new_path(path);\n\n /* rhbz#539551: \"abrt going crazy when crashing process is respawned\" */\n if (g_settings_nMaxCrashReportsSize > 0)\n {\n /* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming\n * kicks in first, and we don't \"fight\" with it:\n */\n unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4;\n maxsize |= 63;\n trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path);\n }\n\n free(rootdir);\n return 0;\n }\n\n /* We didn't create abrt dump, but may need to create compat coredump */\n create_user_core:\n if (user_core_fd >= 0)\n {\n off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE);\n if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0)\n {\n /* perror first, otherwise unlink may trash errno */\n perror_msg(\"Error writing '%s'\", full_core_basename);\n xchdir(user_pwd);\n unlink(core_basename);\n return 1;\n }\n if (ulimit_c == 0 || core_size > ulimit_c)\n {\n xchdir(user_pwd);\n unlink(core_basename);\n return 1;\n }\n log(\"Saved core dump of pid %lu to %s (%llu bytes)\", (long)pid, full_core_basename, (long long)core_size);\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59'], 'message': 'ccpp: do not read data from root directories\n\nUsers are allowed to modify /proc/[pid]/root to any directory by running\ntheir own MOUNT namespace.\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: int main(int argc, char** argv)\n{\n /* Kernel starts us with all fd's closed.\n * But it's dangerous:\n * fprintf(stderr) can dump messages into random fds, etc.\n * Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null.\n */\n int fd = xopen(\"/dev/null\", O_RDWR);\n while (fd < 2)\n\tfd = xdup(fd);\n if (fd > 2)\n\tclose(fd);\n\n if (argc < 8)\n {\n /* percent specifier: %s %c %p %u %g %t %e %h */\n /* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/\n error_msg_and_die(\"Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]\", argv[0]);\n }\n\n /* Not needed on 2.6.30.\n * At least 2.6.18 has a bug where\n * argv[1] = \"SIGNO CORE_SIZE_LIMIT PID ...\"\n * argv[2] = \"CORE_SIZE_LIMIT PID ...\"\n * and so on. Fixing it:\n */\n if (strchr(argv[1], ' '))\n {\n int i;\n for (i = 1; argv[i]; i++)\n {\n strchrnul(argv[i], ' ')[0] = '\\0';\n }\n }\n\n logmode = LOGMODE_JOURNAL;\n\n /* Parse abrt.conf */\n load_abrt_conf();\n /* ... and plugins/CCpp.conf */\n bool setting_MakeCompatCore;\n bool setting_SaveBinaryImage;\n {\n map_string_t *settings = new_map_string();\n load_abrt_plugin_conf_file(\"CCpp.conf\", settings);\n const char *value;\n value = get_map_string_item_or_NULL(settings, \"MakeCompatCore\");\n setting_MakeCompatCore = value && string_to_bool(value);\n value = get_map_string_item_or_NULL(settings, \"SaveBinaryImage\");\n setting_SaveBinaryImage = value && string_to_bool(value);\n value = get_map_string_item_or_NULL(settings, \"VerboseLog\");\n if (value)\n g_verbose = xatoi_positive(value);\n free_map_string(settings);\n }\n\n errno = 0;\n const char* signal_str = argv[1];\n int signal_no = xatoi_positive(signal_str);\n off_t ulimit_c = strtoull(argv[2], NULL, 10);\n if (ulimit_c < 0) /* unlimited? */\n {\n /* set to max possible >0 value */\n ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1));\n }\n const char *pid_str = argv[3];\n pid_t pid = xatoi_positive(argv[3]);\n uid_t uid = xatoi_positive(argv[4]);\n if (errno || pid <= 0)\n {\n perror_msg_and_die(\"PID '%s' or limit '%s' is bogus\", argv[3], argv[2]);\n }\n\n {\n char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN\"/abrt/saved_core_pattern\");\n /* If we have a saved pattern and it's not a \"|PROG ARGS\" thing... */\n if (s && s[0] != '|')\n core_basename = s;\n else\n free(s);\n }\n\n struct utsname uts;\n if (!argv[8]) /* no HOSTNAME? */\n {\n uname(&uts);\n argv[8] = uts.nodename;\n }\n\n char path[PATH_MAX];\n\n int src_fd_binary = -1;\n char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL);\n if (executable && strstr(executable, \"/abrt-hook-ccpp\"))\n {\n error_msg_and_die(\"PID %lu is '%s', not dumping it to avoid recursion\",\n (long)pid, executable);\n }\n\n user_pwd = get_cwd(pid); /* may be NULL on error */\n log_notice(\"user_pwd:'%s'\", user_pwd);\n\n sprintf(path, \"/proc/%lu/status\", (long)pid);\n proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL);\n\n uid_t fsuid = uid;\n uid_t tmp_fsuid = get_fsuid();\n int suid_policy = dump_suid_policy();\n if (tmp_fsuid != uid)\n {\n /* use root for suided apps unless it's explicitly set to UNSAFE */\n fsuid = 0;\n if (suid_policy == DUMP_SUID_UNSAFE)\n {\n fsuid = tmp_fsuid;\n }\n }\n\n /* Open a fd to compat coredump, if requested and is possible */\n if (setting_MakeCompatCore && ulimit_c != 0)\n /* note: checks \"user_pwd == NULL\" inside; updates core_basename */\n user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]);\n\n if (executable == NULL)\n {\n /* readlink on /proc/$PID/exe failed, don't create abrt dump dir */\n error_msg(\"Can't read /proc/%lu/exe link\", (long)pid);\n goto create_user_core;\n }\n\n const char *signame = NULL;\n switch (signal_no)\n {\n case SIGILL : signame = \"ILL\" ; break;\n case SIGFPE : signame = \"FPE\" ; break;\n case SIGSEGV: signame = \"SEGV\"; break;\n case SIGBUS : signame = \"BUS\" ; break; //Bus error (bad memory access)\n case SIGABRT: signame = \"ABRT\"; break; //usually when abort() was called\n // We have real-world reports from users who see buggy programs\n // dying with SIGTRAP, uncommented it too:\n case SIGTRAP: signame = \"TRAP\"; break; //Trace/breakpoint trap\n // These usually aren't caused by bugs:\n //case SIGQUIT: signame = \"QUIT\"; break; //Quit from keyboard\n //case SIGSYS : signame = \"SYS\" ; break; //Bad argument to routine (SVr4)\n //case SIGXCPU: signame = \"XCPU\"; break; //CPU time limit exceeded (4.2BSD)\n //case SIGXFSZ: signame = \"XFSZ\"; break; //File size limit exceeded (4.2BSD)\n default: goto create_user_core; // not a signal we care about\n }\n\n if (!daemon_is_ok())\n {\n /* not an error, exit with exit code 0 */\n log(\"abrtd is not running. If it crashed, \"\n \"/proc/sys/kernel/core_pattern contains a stale value, \"\n \"consider resetting it to 'core'\"\n );\n goto create_user_core;\n }\n\n if (g_settings_nMaxCrashReportsSize > 0)\n {\n /* If free space is less than 1/4 of MaxCrashReportsSize... */\n if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location))\n goto create_user_core;\n }\n\n /* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes\n * if they happen too often. Else, write new marker value.\n */\n snprintf(path, sizeof(path), \"%s/last-ccpp\", g_settings_dump_location);\n if (check_recent_crash_file(path, executable))\n {\n /* It is a repeating crash */\n goto create_user_core;\n }\n\n const char *last_slash = strrchr(executable, '/');\n if (last_slash && strncmp(++last_slash, \"abrt\", 4) == 0)\n {\n /* If abrtd/abrt-foo crashes, we don't want to create a _directory_,\n * since that can make new copy of abrtd to process it,\n * and maybe crash again...\n * Unlike dirs, mere files are ignored by abrtd.\n */\n snprintf(path, sizeof(path), \"%s/%s-coredump\", g_settings_dump_location, last_slash);\n int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600);\n off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE);\n if (core_size < 0 || fsync(abrt_core_fd) != 0)\n {\n unlink(path);\n /* copyfd_eof logs the error including errno string,\n * but it does not log file name */\n error_msg_and_die(\"Error saving '%s'\", path);\n }\n log(\"Saved core dump of pid %lu (%s) to %s (%llu bytes)\", (long)pid, executable, path, (long long)core_size);\n return 0;\n }\n\n unsigned path_len = snprintf(path, sizeof(path), \"%s/ccpp-%s-%lu.new\",\n g_settings_dump_location, iso_date_string(NULL), (long)pid);\n if (path_len >= (sizeof(path) - sizeof(\"/\"FILENAME_COREDUMP)))\n {\n goto create_user_core;\n }\n\n /* use fsuid instead of uid, so we don't expose any sensitive\n * information of suided app in /var/tmp/abrt\n *\n * dd_create_skeleton() creates a new directory and leaves ownership to\n * the current user, hence, we have to call dd_reset_ownership() after the\n * directory is populated.\n */\n dd = dd_create_skeleton(path, fsuid, DEFAULT_DUMP_DIR_MODE, /*no flags*/0);\n if (dd)\n {\n char *rootdir = get_rootdir(pid);\n\n dd_create_basic_files(dd, fsuid, NULL);\n\n char source_filename[sizeof(\"/proc/%lu/somewhat_long_name\") + sizeof(long)*3];\n int source_base_ofs = sprintf(source_filename, \"/proc/%lu/smaps\", (long)pid);\n source_base_ofs -= strlen(\"smaps\");\n char *dest_filename = concat_path_file(dd->dd_dirname, \"also_somewhat_longish_name\");\n char *dest_base = strrchr(dest_filename, '/') + 1;\n\n // Disabled for now: /proc/PID/smaps tends to be BIG,\n // and not much more informative than /proc/PID/maps:\n //copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);\n\n strcpy(source_filename + source_base_ofs, \"maps\");\n strcpy(dest_base, FILENAME_MAPS);\n copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);\n\n strcpy(source_filename + source_base_ofs, \"limits\");\n strcpy(dest_base, FILENAME_LIMITS);\n copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);\n\n strcpy(source_filename + source_base_ofs, \"cgroup\");\n strcpy(dest_base, FILENAME_CGROUP);\n copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);\n\n strcpy(dest_base, FILENAME_OPEN_FDS);\n dump_fd_info(dest_filename, source_filename, source_base_ofs, dd->dd_uid, dd->dd_gid);\n\n free(dest_filename);\n\n dd_save_text(dd, FILENAME_ANALYZER, \"CCpp\");\n dd_save_text(dd, FILENAME_TYPE, \"CCpp\");\n dd_save_text(dd, FILENAME_EXECUTABLE, executable);\n dd_save_text(dd, FILENAME_PID, pid_str);\n dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status);\n if (user_pwd)\n dd_save_text(dd, FILENAME_PWD, user_pwd);\n if (rootdir)\n {\n if (strcmp(rootdir, \"/\") != 0)\n dd_save_text(dd, FILENAME_ROOTDIR, rootdir);\n }\n\n char *reason = xasprintf(\"%s killed by SIG%s\",\n last_slash, signame ? signame : signal_str);\n dd_save_text(dd, FILENAME_REASON, reason);\n free(reason);\n\n char *cmdline = get_cmdline(pid);\n dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : \"\");\n free(cmdline);\n\n char *environ = get_environ(pid);\n dd_save_text(dd, FILENAME_ENVIRON, environ ? : \"\");\n free(environ);\n\n char *fips_enabled = xmalloc_fopen_fgetline_fclose(\"/proc/sys/crypto/fips_enabled\");\n if (fips_enabled)\n {\n if (strcmp(fips_enabled, \"0\") != 0)\n dd_save_text(dd, \"fips_enabled\", fips_enabled);\n free(fips_enabled);\n }\n\n dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION);\n\n if (src_fd_binary > 0)\n {\n strcpy(path + path_len, \"/\"FILENAME_BINARY);\n int dst_fd = create_or_die(path);\n off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE);\n if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0)\n {\n dd_delete(dd);\n error_msg_and_die(\"Error saving '%s'\", path);\n }\n close(src_fd_binary);\n }\n\n strcpy(path + path_len, \"/\"FILENAME_COREDUMP);\n int abrt_core_fd = create_or_die(path);\n\n /* We write both coredumps at once.\n * We can't write user coredump first, since it might be truncated\n * and thus can't be copied and used as abrt coredump;\n * and if we write abrt coredump first and then copy it as user one,\n * then we have a race when process exits but coredump does not exist yet:\n * $ echo -e '#include\\nmain(){raise(SIGSEGV);}' | gcc -o test -x c -\n * $ rm -f core*; ulimit -c unlimited; ./test; ls -l core*\n * 21631 Segmentation fault (core dumped) ./test\n * ls: cannot access core*: No such file or directory <=== BAD\n */\n off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c);\n if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0)\n {\n unlink(path);\n dd_delete(dd);\n if (user_core_fd >= 0)\n {\n xchdir(user_pwd);\n unlink(core_basename);\n }\n /* copyfd_sparse logs the error including errno string,\n * but it does not log file name */\n error_msg_and_die(\"Error writing '%s'\", path);\n }\n if (user_core_fd >= 0\n /* error writing user coredump? */\n && (fsync(user_core_fd) != 0 || close(user_core_fd) != 0\n /* user coredump is too big? */\n || (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c)\n )\n ) {\n /* nuke it (silently) */\n xchdir(user_pwd);\n unlink(core_basename);\n }\n\n/* Because of #1211835 and #1126850 */\n#if 0\n /* Save JVM crash log if it exists. (JVM's coredump per se\n * is nearly useless for JVM developers)\n */\n {\n char *java_log = xasprintf(\"/tmp/jvm-%lu/hs_error.log\", (long)pid);\n int src_fd = open(java_log, O_RDONLY);\n free(java_log);\n\n /* If we couldn't open the error log in /tmp directory we can try to\n * read the log from the current directory. It may produce AVC, it\n * may produce some error log but all these are expected.\n */\n if (src_fd < 0)\n {\n java_log = xasprintf(\"%s/hs_err_pid%lu.log\", user_pwd, (long)pid);\n src_fd = open(java_log, O_RDONLY);\n free(java_log);\n }\n\n if (src_fd >= 0)\n {\n strcpy(path + path_len, \"/hs_err.log\");\n int dst_fd = create_or_die(path);\n off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE);\n if (close(dst_fd) != 0 || sz < 0)\n {\n dd_delete(dd);\n error_msg_and_die(\"Error saving '%s'\", path);\n }\n close(src_fd);\n }\n }\n#endif\n\n /* And finally set the right uid and gid */\n dd_reset_ownership(dd);\n\n /* We close dumpdir before we start catering for crash storm case.\n * Otherwise, delete_dump_dir's from other concurrent\n * CCpp's won't be able to delete our dump (their delete_dump_dir\n * will wait for us), and we won't be able to delete their dumps.\n * Classic deadlock.\n */\n dd_close(dd);\n path[path_len] = '\\0'; /* path now contains only directory name */\n char *newpath = xstrndup(path, path_len - (sizeof(\".new\")-1));\n if (rename(path, newpath) == 0)\n strcpy(path, newpath);\n free(newpath);\n\n log(\"Saved core dump of pid %lu (%s) to %s (%llu bytes)\", (long)pid, executable, path, (long long)core_size);\n\n notify_new_path(path);\n\n /* rhbz#539551: \"abrt going crazy when crashing process is respawned\" */\n if (g_settings_nMaxCrashReportsSize > 0)\n {\n /* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming\n * kicks in first, and we don't \"fight\" with it:\n */\n unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4;\n maxsize |= 63;\n trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path);\n }\n\n free(rootdir);\n return 0;\n }\n\n /* We didn't create abrt dump, but may need to create compat coredump */\n create_user_core:\n if (user_core_fd >= 0)\n {\n off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE);\n if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0)\n {\n /* perror first, otherwise unlink may trash errno */\n perror_msg(\"Error writing '%s'\", full_core_basename);\n xchdir(user_pwd);\n unlink(core_basename);\n return 1;\n }\n if (ulimit_c == 0 || core_size > ulimit_c)\n {\n xchdir(user_pwd);\n unlink(core_basename);\n return 1;\n }\n log(\"Saved core dump of pid %lu to %s (%llu bytes)\", (long)pid, full_core_basename, (long long)core_size);\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'ccpp: do not override existing files by compat cores\n\nImplement all checks used in kernel's do_coredump() and require\nnon-relative path if suid_dumpable is 2.\n\nRelated: #1212818\n\nSigned-off-by: Jakub Filak '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static gboolean key_value_ok(gchar *key, gchar *value)\n{\n char *i;\n\n /* check key, it has to be valid filename and will end up in the\n * bugzilla */\n for (i = key; *i != 0; i++)\n {\n if (!isalpha(*i) && (*i != '-') && (*i != '_') && (*i != ' '))\n return FALSE;\n }\n\n /* check value of 'basename', it has to be valid non-hidden directory\n * name */\n if (strcmp(key, \"basename\") == 0\n || strcmp(key, FILENAME_TYPE) == 0\n )\n {\n if (!str_is_correct_filename(value))\n {\n error_msg(\"Value of '%s' ('%s') is not a valid directory name\",\n key, value);\n return FALSE;\n }\n }\n\n return TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59'], 'message': 'daemon, dbus: allow only root to create CCpp, Koops, vmcore and xorg\n\nFlorian Weimer :\n This prevents users from feeding things that are not actually\n coredumps and excerpts from /proc to these analyzers.\n\n For example, it should not be possible to trigger a rule with\n \u201cEVENT=post-create analyzer=CCpp\u201d using NewProblem\n\nRelated: #1212861\n\nSigned-off-by: Jakub Filak '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static char *sanitize_cookie_path(const char *cookie_path)\n{\n size_t len;\n char *new_path = strdup(cookie_path);\n if(!new_path)\n return NULL;\n\n /* some stupid site sends path attribute with '\"'. */\n if(new_path[0] == '\\\"') {\n memmove((void *)new_path, (const void *)(new_path + 1), strlen(new_path));\n }\n if(new_path[strlen(new_path) - 1] == '\\\"') {\n new_path[strlen(new_path) - 1] = 0x0;\n }\n\n /* RFC6265 5.2.4 The Path Attribute */\n if(new_path[0] != '/') {\n /* Let cookie-path be the default-path. */\n free(new_path);\n new_path = strdup(\"/\");\n return new_path;\n }\n\n /* convert /hoge/ to /hoge */\n len = strlen(new_path);\n if(1 < len && new_path[len - 1] == '/') {\n new_path[len - 1] = 0x0;\n }\n\n return new_path;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'cookie: cookie parser out of boundary memory access\n\nThe internal libcurl function called sanitize_cookie_path() that cleans\nup the path element as given to it from a remote site or when read from\na file, did not properly validate the input. If given a path that\nconsisted of a single double-quote, libcurl would index a newly\nallocated memory area with index -1 and assign a zero to it, thus\ndestroying heap memory it wasn't supposed to.\n\nCVE-2015-3145\n\nBug: http://curl.haxx.se/docs/adv_20150422C.html\nReported-by: Hanno B\u00f6ck'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static PHP_FUNCTION(xmlwriter_open_uri)\n{\n\tchar *valid_file = NULL;\n\txmlwriter_object *intern;\n\txmlTextWriterPtr ptr;\n\tchar *source;\n\tchar resolved_path[MAXPATHLEN + 1];\n\tint source_len;\n\n#ifdef ZEND_ENGINE_2\n\tzval *this = getThis();\n\tze_xmlwriter_object *ze_obj = NULL;\n#endif\n\n#ifndef ZEND_ENGINE_2\n\txmlOutputBufferPtr out_buffer;\n\tvoid *ioctx;\n#endif\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s\", &source, &source_len) == FAILURE) {\n\t\treturn;\n\t}\n\t\n#ifdef ZEND_ENGINE_2\n\tif (this) {\n\t\t/* We do not use XMLWRITER_FROM_OBJECT, xmlwriter init function here */\n\t\tze_obj = (ze_xmlwriter_object*) zend_object_store_get_object(this TSRMLS_CC); \n\t}\n#endif\n\n\tif (source_len == 0) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Empty string as source\");\n\t\tRETURN_FALSE;\n\t}\n\n\tvalid_file = _xmlwriter_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC);\n\tif (!valid_file) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Unable to resolve file path\");\n\t\tRETURN_FALSE;\n\t}\n\n\t/* TODO: Fix either the PHP stream or libxml APIs: it can then detect when a given \n\t\t path is valid and not report out of memory error. Once it is done, remove the\n\t\t directory check in _xmlwriter_get_valid_file_path */\n#ifndef ZEND_ENGINE_2\n\tioctx = php_xmlwriter_streams_IO_open_write_wrapper(valid_file TSRMLS_CC);\n\tif (ioctx == NULL) {\n\t\tRETURN_FALSE;\n\t}\n\n\tout_buffer = xmlOutputBufferCreateIO(php_xmlwriter_streams_IO_write, \n\t\tphp_xmlwriter_streams_IO_close, ioctx, NULL);\n\n\tif (out_buffer == NULL) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Unable to create output buffer\");\n\t\tRETURN_FALSE;\n\t}\n\tptr = xmlNewTextWriter(out_buffer);\n#else\n\tptr = xmlNewTextWriterFilename(valid_file, 0);\n#endif\n\n\tif (!ptr) {\n\t\tRETURN_FALSE;\n\t}\n\n\tintern = emalloc(sizeof(xmlwriter_object));\n\tintern->ptr = ptr;\n\tintern->output = NULL;\n#ifndef ZEND_ENGINE_2\n\tintern->uri_output = out_buffer;\n#else\n\tif (this) {\n\t\tif (ze_obj->xmlwriter_ptr) {\n\t\t\txmlwriter_free_resource_ptr(ze_obj->xmlwriter_ptr TSRMLS_CC);\n\t\t}\n\t\tze_obj->xmlwriter_ptr = intern;\n\t\tRETURN_TRUE;\n\t} else\n#endif\n\t{\n\t\tZEND_REGISTER_RESOURCE(return_value,intern,le_xmlwriter);\n\t}\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: struct dump_dir *create_dump_dir_from_problem_data(problem_data_t *problem_data, const char *base_dir_name)\n{\n INITIALIZE_LIBREPORT();\n\n char *type = problem_data_get_content_or_NULL(problem_data, FILENAME_ANALYZER);\n\n if (!type)\n {\n error_msg(_(\"Missing required item: '%s'\"), FILENAME_ANALYZER);\n return NULL;\n }\n\n uid_t uid = (uid_t)-1L;\n char *uid_str = problem_data_get_content_or_NULL(problem_data, FILENAME_UID);\n\n if (uid_str)\n {\n char *endptr;\n errno = 0;\n long val = strtol(uid_str, &endptr, 10);\n\n if (errno != 0 || endptr == uid_str || *endptr != '\\0' || INT_MAX < val)\n {\n error_msg(_(\"uid value is not valid: '%s'\"), uid_str);\n return NULL;\n }\n\n uid = (uid_t)val;\n }\n\n struct timeval tv;\n if (gettimeofday(&tv, NULL) < 0)\n {\n perror_msg(\"gettimeofday()\");\n return NULL;\n }\n\n char *problem_id = xasprintf(\"%s-%s.%ld-%lu\"NEW_PD_SUFFIX, type, iso_date_string(&(tv.tv_sec)), (long)tv.tv_usec, (long)getpid());\n\n log_info(\"Saving to %s/%s with uid %d\", base_dir_name, problem_id, uid);\n\n struct dump_dir *dd;\n if (base_dir_name)\n dd = try_dd_create(base_dir_name, problem_id, uid);\n else\n {\n /* Try /var/run/abrt */\n dd = try_dd_create(LOCALSTATEDIR\"/run/abrt\", problem_id, uid);\n /* Try $HOME/tmp */\n if (!dd)\n {\n char *home = getenv(\"HOME\");\n if (home && home[0])\n {\n home = concat_path_file(home, \"tmp\");\n /*mkdir(home, 0777); - do we want this? */\n dd = try_dd_create(home, problem_id, uid);\n free(home);\n }\n }\n//TODO: try user's home dir obtained by getpwuid(getuid())?\n /* Try system temporary directory */\n if (!dd)\n dd = try_dd_create(LARGE_DATA_TMP_DIR, problem_id, uid);\n }\n\n if (!dd) /* try_dd_create() already emitted the error message */\n goto ret;\n\n GHashTableIter iter;\n char *name;\n struct problem_item *value;\n g_hash_table_iter_init(&iter, problem_data);\n while (g_hash_table_iter_next(&iter, (void**)&name, (void**)&value))\n {\n if (value->flags & CD_FLAG_BIN)\n {\n char *dest = concat_path_file(dd->dd_dirname, name);\n log_info(\"copying '%s' to '%s'\", value->content, dest);\n off_t copied = copy_file(value->content, dest, DEFAULT_DUMP_DIR_MODE | S_IROTH);\n if (copied < 0)\n error_msg(\"Can't copy %s to %s\", value->content, dest);\n else\n log_info(\"copied %li bytes\", (unsigned long)copied);\n free(dest);\n\n continue;\n }\n\n /* only files should contain '/' and those are handled earlier */\n if (name[0] == '.' || strchr(name, '/'))\n {\n error_msg(\"Problem data field name contains disallowed chars: '%s'\", name);\n continue;\n }\n\n dd_save_text(dd, name, value->content);\n }\n\n /* need to create basic files AFTER we save the pd to dump_dir\n * otherwise we can't skip already created files like in case when\n * reporting from anaconda where we can't read /etc/{system,redhat}-release\n * and os_release is taken from anaconda\n */\n dd_create_basic_files(dd, uid, NULL);\n\n problem_id[strlen(problem_id) - strlen(NEW_PD_SUFFIX)] = '\\0';\n char* new_path = concat_path_file(base_dir_name, problem_id);\n log_info(\"Renaming from '%s' to '%s'\", dd->dd_dirname, new_path);\n dd_rename(dd, new_path);\n\n ret:\n free(problem_id);\n return dd;\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 int run_post_create(const char *dirname)\n{\n /* If doesn't start with \"g_settings_dump_location/\"... */\n if (!dir_is_in_dump_location(dirname))\n {\n /* Then refuse to operate on it (someone is attacking us??) */\n error_msg(\"Bad problem directory name '%s', should start with: '%s'\", dirname, g_settings_dump_location);\n return 400; /* Bad Request */\n }\n if (g_settings_privatereports)\n {\n struct stat statbuf;\n if (lstat(dirname, &statbuf) != 0 || !S_ISDIR(statbuf.st_mode))\n {\n error_msg(\"Path '%s' isn't directory\", dirname);\n return 404; /* Not Found */\n }\n /* Get ABRT's group gid */\n struct group *gr = getgrnam(\"abrt\");\n if (!gr)\n {\n error_msg(\"Group 'abrt' does not exist\");\n return 500;\n }\n if (statbuf.st_uid != 0 || !(statbuf.st_gid == 0 || statbuf.st_gid == gr->gr_gid) || statbuf.st_mode & 07)\n {\n error_msg(\"Problem directory '%s' isn't owned by root:abrt or others are not restricted from access\", dirname);\n return 403;\n }\n struct dump_dir *dd = dd_opendir(dirname, DD_OPEN_READONLY);\n const bool complete = dd && problem_dump_dir_is_complete(dd);\n dd_close(dd);\n if (complete)\n {\n error_msg(\"Problem directory '%s' has already been processed\", dirname);\n return 403;\n }\n }\n else if (!dump_dir_accessible_by_uid(dirname, client_uid))\n {\n if (errno == ENOTDIR)\n {\n error_msg(\"Path '%s' isn't problem directory\", dirname);\n return 404; /* Not Found */\n }\n error_msg(\"Problem directory '%s' can't be accessed by user with uid %ld\", dirname, (long)client_uid);\n return 403; /* Forbidden */\n }\n\n int child_stdout_fd;\n int child_pid = spawn_event_handler_child(dirname, \"post-create\", &child_stdout_fd);\n\n char *dup_of_dir = NULL;\n struct strbuf *cmd_output = strbuf_new();\n\n bool child_is_post_create = 1; /* else it is a notify child */\n\n read_child_output:\n //log(\"Reading from event fd %d\", child_stdout_fd);\n\n /* Read streamed data and split lines */\n for (;;)\n {\n char buf[250]; /* usually we get one line, no need to have big buf */\n errno = 0;\n int r = safe_read(child_stdout_fd, buf, sizeof(buf) - 1);\n if (r <= 0)\n break;\n buf[r] = '\\0';\n\n /* split lines in the current buffer */\n char *raw = buf;\n char *newline;\n while ((newline = strchr(raw, '\\n')) != NULL)\n {\n *newline = '\\0';\n strbuf_append_str(cmd_output, raw);\n char *msg = cmd_output->buf;\n\n /* Hmm, DUP_OF_DIR: ends up in syslog. move log() into 'else'? */\n log(\"%s\", msg);\n\n if (child_is_post_create\n && prefixcmp(msg, \"DUP_OF_DIR: \") == 0\n ) {\n free(dup_of_dir);\n dup_of_dir = xstrdup(msg + strlen(\"DUP_OF_DIR: \"));\n }\n\n strbuf_clear(cmd_output);\n /* jump to next line */\n raw = newline + 1;\n }\n\n /* beginning of next line. the line continues by next read */\n strbuf_append_str(cmd_output, raw);\n }\n\n /* EOF/error */\n\n /* Wait for child to actually exit, collect status */\n int status = 0;\n if (safe_waitpid(child_pid, &status, 0) <= 0)\n /* should not happen */\n perror_msg(\"waitpid(%d)\", child_pid);\n\n /* If it was a \"notify[-dup]\" event, then we're done */\n if (!child_is_post_create)\n goto ret;\n\n /* exit 0 means \"this is a good, non-dup dir\" */\n /* exit with 1 + \"DUP_OF_DIR: dir\" string => dup */\n if (status != 0)\n {\n if (WIFSIGNALED(status))\n {\n log(\"'post-create' on '%s' killed by signal %d\",\n dirname, WTERMSIG(status));\n goto delete_bad_dir;\n }\n /* else: it is WIFEXITED(status) */\n if (!dup_of_dir)\n {\n log(\"'post-create' on '%s' exited with %d\",\n dirname, WEXITSTATUS(status));\n goto delete_bad_dir;\n }\n }\n\n const char *work_dir = (dup_of_dir ? dup_of_dir : dirname);\n\n /* Load problem_data (from the *first dir* if this one is a dup) */\n struct dump_dir *dd = dd_opendir(work_dir, /*flags:*/ 0);\n if (!dd)\n /* dd_opendir already emitted error msg */\n goto delete_bad_dir;\n\n /* Update count */\n char *count_str = dd_load_text_ext(dd, FILENAME_COUNT, DD_FAIL_QUIETLY_ENOENT);\n unsigned long count = strtoul(count_str, NULL, 10);\n\n /* Don't increase crash count if we are working with newly uploaded\n * directory (remote crash) which already has its crash count set.\n */\n if ((status != 0 && dup_of_dir) || count == 0)\n {\n count++;\n char new_count_str[sizeof(long)*3 + 2];\n sprintf(new_count_str, \"%lu\", count);\n dd_save_text(dd, FILENAME_COUNT, new_count_str);\n\n /* This condition can be simplified to either\n * (status * != 0 && * dup_of_dir) or (count == 1). But the\n * chosen form is much more reliable and safe. We must not call\n * dd_opendir() to locked dd otherwise we go into a deadlock.\n */\n if (strcmp(dd->dd_dirname, dirname) != 0)\n {\n /* Update the last occurrence file by the time file of the new problem */\n struct dump_dir *new_dd = dd_opendir(dirname, DD_OPEN_READONLY);\n char *last_ocr = NULL;\n if (new_dd)\n {\n /* TIME must exists in a valid dump directory but we don't want to die\n * due to broken duplicated dump directory */\n last_ocr = dd_load_text_ext(new_dd, FILENAME_TIME,\n DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT);\n dd_close(new_dd);\n }\n else\n { /* dd_opendir() already produced a message with good information about failure */\n error_msg(\"Can't read the last occurrence file from the new dump directory.\");\n }\n\n if (!last_ocr)\n { /* the new dump directory may lie in the dump location for some time */\n log(\"Using current time for the last occurrence file which may be incorrect.\");\n time_t t = time(NULL);\n last_ocr = xasprintf(\"%lu\", (long)t);\n }\n\n dd_save_text(dd, FILENAME_LAST_OCCURRENCE, last_ocr);\n\n free(last_ocr);\n }\n }\n\n /* Reset mode/uig/gid to correct values for all files created by event run */\n dd_sanitize_mode_and_owner(dd);\n\n dd_close(dd);\n\n if (!dup_of_dir)\n log_notice(\"New problem directory %s, processing\", work_dir);\n else\n {\n log_warning(\"Deleting problem directory %s (dup of %s)\",\n strrchr(dirname, '/') + 1,\n strrchr(dup_of_dir, '/') + 1);\n delete_dump_dir(dirname);\n }\n\n /* Run \"notify[-dup]\" event */\n int fd;\n child_pid = spawn_event_handler_child(\n work_dir,\n (dup_of_dir ? \"notify-dup\" : \"notify\"),\n &fd\n );\n //log(\"Started notify, fd %d -> %d\", fd, child_stdout_fd);\n xmove_fd(fd, child_stdout_fd);\n child_is_post_create = 0;\n strbuf_clear(cmd_output);\n free(dup_of_dir);\n dup_of_dir = NULL;\n goto read_child_output;\n\n delete_bad_dir:\n log_warning(\"Deleting problem directory '%s'\", dirname);\n delete_dump_dir(dirname);\n\n ret:\n strbuf_free(cmd_output);\n free(dup_of_dir);\n close(child_stdout_fd);\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'lib: add functions validating dump dir\n\nMove the code from abrt-server to shared library and fix the condition\nvalidating dump dir's path.\n\nAs of now, abrt is allowed to process only direct sub-directories of the\ndump locations.\n\nSigned-off-by: Jakub Filak '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int dd_delete_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 if (!str_is_correct_filename(name))\n error_msg_and_die(\"Cannot delete item. '%s' is not a valid file name\", name);\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-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_create_skeleton(const char *dir, uid_t uid, mode_t mode, int flags)\n{\n /* a little trick to copy read bits from file mode to exec bit of dir mode*/\n mode_t dir_mode = mode | ((mode & 0444) >> 2);\n struct dump_dir *dd = dd_init();\n\n dd->mode = mode;\n\n /* Unlike dd_opendir, can't use realpath: the directory doesn't exist yet,\n * realpath will always return NULL. We don't really have to:\n * dd_opendir(\".\") makes sense, dd_create(\".\") does not.\n */\n dir = dd->dd_dirname = rm_trailing_slashes(dir);\n\n const char *last_component = strrchr(dir, '/');\n if (last_component)\n last_component++;\n else\n last_component = dir;\n if (dot_or_dotdot(last_component))\n {\n /* dd_create(\".\"), dd_create(\"..\"), dd_create(\"dir/.\"),\n * dd_create(\"dir/..\") and similar are madness, refuse them.\n */\n error_msg(\"Bad dir name '%s'\", dir);\n dd_close(dd);\n return NULL;\n }\n\n /* Was creating it with mode 0700 and user as the owner, but this allows\n * the user to replace any file in the directory, changing security-sensitive data\n * (e.g. \"uid\", \"analyzer\", \"executable\")\n */\n int r;\n if ((flags & DD_CREATE_PARENTS))\n r = g_mkdir_with_parents(dd->dd_dirname, dir_mode);\n else\n r = mkdir(dd->dd_dirname, dir_mode);\n\n if (r != 0)\n {\n perror_msg(\"Can't create directory '%s'\", dir);\n dd_close(dd);\n return NULL;\n }\n\n if (dd_lock(dd, CREATE_LOCK_USLEEP, /*flags:*/ 0) < 0)\n {\n dd_close(dd);\n return NULL;\n }\n\n /* mkdir's mode (above) can be affected by umask, fix it */\n if (chmod(dir, dir_mode) == -1)\n {\n perror_msg(\"Can't change mode of '%s'\", dir);\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 (uid != (uid_t)-1L)\n {\n dd->dd_uid = 0;\n dd->dd_uid = 0;\n\n#if DUMP_DIR_OWNED_BY_USER > 0\n /* Check crashed application's uid */\n struct passwd *pw = getpwuid(uid);\n if (pw)\n dd->dd_uid = pw->pw_uid;\n else\n error_msg(\"User %lu does not exist, using uid 0\", (long)uid);\n\n /* Get ABRT's group gid */\n struct group *gr = getgrnam(\"abrt\");\n if (gr)\n dd->dd_gid = gr->gr_gid;\n else\n error_msg(\"Group 'abrt' does not exist, using gid 0\");\n#else\n /* Get ABRT's user uid */\n struct passwd *pw = getpwnam(\"abrt\");\n if (pw)\n dd->dd_uid = pw->pw_uid;\n else\n error_msg(\"User 'abrt' does not exist, using uid 0\");\n\n /* Get crashed application's gid */\n pw = getpwuid(uid);\n if (pw)\n dd->dd_gid = pw->pw_gid;\n else\n error_msg(\"User %lu does not exist, using gid 0\", (long)uid);\n#endif\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: static void dd_unlock(struct dump_dir *dd)\n{\n if (dd->locked)\n {\n dd->locked = 0;\n\n unsigned dirname_len = strlen(dd->dd_dirname);\n char lock_buf[dirname_len + sizeof(\"/.lock\")];\n strcpy(lock_buf, dd->dd_dirname);\n strcpy(lock_buf + dirname_len, \"/.lock\");\n xunlink(lock_buf);\n\n log_info(\"Unlocked '%s'\", lock_buf);\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: static MYSQL *db_connect(char *host, char *database,\n char *user, char *passwd)\n{\n MYSQL *mysql;\n if (verbose)\n fprintf(stdout, \"Connecting to %s\\n\", host ? host : \"localhost\");\n if (!(mysql= mysql_init(NULL)))\n return 0;\n if (opt_compress)\n mysql_options(mysql,MYSQL_OPT_COMPRESS,NullS);\n if (opt_local_file)\n mysql_options(mysql,MYSQL_OPT_LOCAL_INFILE,\n\t\t (char*) &opt_local_file);\n#ifdef HAVE_OPENSSL\n if (opt_use_ssl)\n {\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 (opt_bind_addr)\n mysql_options(mysql,MYSQL_OPT_BIND,opt_bind_addr);\n#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)\n if (shared_memory_base_name)\n mysql_options(mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);\n#endif\n\n if (opt_plugin_dir && *opt_plugin_dir)\n mysql_options(mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir);\n\n if (opt_default_auth && *opt_default_auth)\n mysql_options(mysql, MYSQL_DEFAULT_AUTH, opt_default_auth);\n\n mysql_options(mysql, MYSQL_SET_CHARSET_NAME, default_charset);\n mysql_options(mysql, MYSQL_OPT_CONNECT_ATTR_RESET, 0);\n mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD,\n \"program_name\", \"mysqlimport\");\n if (!(mysql_real_connect(mysql,host,user,passwd,\n database,opt_mysql_port,opt_mysql_unix_port,\n 0)))\n {\n ignore_errors=0;\t /* NO RETURN FROM db_error */\n db_error(mysql);\n }\n mysql->reconnect= 0;\n if (verbose)\n fprintf(stdout, \"Selecting database %s\\n\", database);\n if (mysql_select_db(mysql, database))\n {\n ignore_errors=0;\n db_error(mysql);\n }\n return mysql;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-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: int main(int argc, char **argv)\n{\n int error;\n my_bool first_argument_uses_wildcards=0;\n char *wild;\n MYSQL mysql;\n MY_INIT(argv[0]);\n if (load_defaults(\"my\",load_default_groups,&argc,&argv))\n exit(1);\n\n get_options(&argc,&argv);\n\n wild=0;\n if (argc)\n {\n char *pos= argv[argc-1], *to;\n for (to= pos ; *pos ; pos++, to++)\n {\n switch (*pos) {\n case '*':\n\t*pos= '%';\n\tfirst_argument_uses_wildcards= 1;\n\tbreak;\n case '?':\n\t*pos= '_';\n\tfirst_argument_uses_wildcards= 1;\n\tbreak;\n case '%':\n case '_':\n\tfirst_argument_uses_wildcards= 1;\n\tbreak;\n case '\\\\':\n\tpos++;\n default: break;\n }\n *to= *pos;\n } \n *to= *pos; /* just to copy a '\\0' if '\\\\' was used */\n }\n if (first_argument_uses_wildcards)\n wild= argv[--argc];\n else if (argc == 3)\t\t\t/* We only want one field */\n wild= argv[--argc];\n\n if (argc > 2)\n {\n fprintf(stderr,\"%s: Too many arguments\\n\",my_progname);\n exit(1);\n }\n mysql_init(&mysql);\n if (opt_compress)\n mysql_options(&mysql,MYSQL_OPT_COMPRESS,NullS);\n#ifdef HAVE_OPENSSL\n if (opt_use_ssl)\n mysql_ssl_set(&mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,\n\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 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_real_connect(&mysql,host,user,opt_password,\n\t\t\t (first_argument_uses_wildcards) ? \"\" :\n argv[0],opt_mysql_port,opt_mysql_unix_port,\n\t\t\t 0)))\n {\n fprintf(stderr,\"%s: %s\\n\",my_progname,mysql_error(&mysql));\n exit(1);\n }\n mysql.reconnect= 1;\n\n switch (argc) {\n case 0: error=list_dbs(&mysql,wild); break;\n case 1:\n if (opt_status)\n error=list_table_status(&mysql,argv[0],wild);\n else\n error=list_tables(&mysql,argv[0],wild);\n break;\n default:\n if (opt_status && ! wild)\n error=list_table_status(&mysql,argv[0],argv[1]);\n else\n error=list_fields(&mysql,argv[0],argv[1],wild);\n break;\n }\n mysql_close(&mysql);\t\t\t/* Close & free connection */\n my_free(opt_password);\n#ifdef HAVE_SMEM\n my_free(shared_memory_base_name);\n#endif\n my_end(my_end_arg);\n exit(error ? 1 : 0);\n return 0;\t\t\t\t/* No compiler warnings */\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: void ping_unhash(struct sock *sk)\n{\n\tstruct inet_sock *isk = inet_sk(sk);\n\tpr_debug(\"ping_unhash(isk=%p,isk->num=%u)\\n\", isk, isk->inet_num);\n\tif (sk_hashed(sk)) {\n\t\twrite_lock_bh(&ping_table.lock);\n\t\thlist_nulls_del(&sk->sk_nulls_node);\n\t\tsock_put(sk);\n\t\tisk->inet_num = 0;\n\t\tisk->inet_sport = 0;\n\t\tsock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);\n\t\twrite_unlock_bh(&ping_table.lock);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'ipv4: Missing sk_nulls_node_init() in ping_unhash().\n\nIf we don't do that, then the poison value is left in the ->pprev\nbacklink.\n\nThis can cause crashes if we do a disconnect, followed by a connect().\n\nTested-by: Linus Torvalds \nReported-by: Wen 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 is_integer(char *string)\n{\n if (isdigit(string[0]) || string[0] == '-' || string[0] == '+') {\n while (*++string && isdigit(*string))\n ; /* deliberately empty */\n if (!*string)\n return 1;\n }\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.\n\n- Don't overflow the small cs_start buffer (reported by Niels\n Thykier via the debian tracker (Jakub Wilk), found with a\n fuzzer (\"American fuzzy lop\")).\n\n- Cast arguments to functions to unsigned char.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PHP_FUNCTION(chroot)\n{\n\tchar *str;\n\tint ret, str_len;\n\t\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s\", &str, &str_len) == FAILURE) {\n\t\tRETURN_FALSE;\n\t}\n\t\n\tret = chroot(str);\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\tphp_clear_stat_cache(1, NULL, 0 TSRMLS_CC);\n\t\n\tret = chdir(\"/\");\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\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: PHP_FUNCTION(pcntl_alarm)\n{\n\tlong seconds;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"l\", &seconds) == FAILURE)\n\t\treturn;\n\t\n\tRETURN_LONG ((long) alarm(seconds));\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_login(ftpbuf_t *ftp, const char *user, const char *pass TSRMLS_DC)\n{\n#if HAVE_OPENSSL_EXT\n\tSSL_CTX\t*ctx = NULL;\n\tlong ssl_ctx_options = SSL_OP_ALL;\n#endif\n\tif (ftp == NULL) {\n\t\treturn 0;\n\t}\n\n#if HAVE_OPENSSL_EXT\n\tif (ftp->use_ssl && !ftp->ssl_active) {\n\t\tif (!ftp_putcmd(ftp, \"AUTH\", \"TLS\")) {\n\t\t\treturn 0;\n\t\t}\n\t\tif (!ftp_getresp(ftp)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\t\n\t\tif (ftp->resp != 234) {\n\t\t\tif (!ftp_putcmd(ftp, \"AUTH\", \"SSL\")) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (!ftp_getresp(ftp)) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\t\t\n\t\t\tif (ftp->resp != 334) {\n\t\t\t\treturn 0;\n\t\t\t} else {\n\t\t\t\tftp->old_ssl = 1;\n\t\t\t\tftp->use_ssl_for_data = 1;\n\t\t\t}\n\t\t}\n\t\t\n\t\tctx = SSL_CTX_new(SSLv23_client_method());\n\t\tif (ctx == NULL) {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"failed to create the SSL context\");\n\t\t\treturn 0;\n\t\t}\n\n#if OPENSSL_VERSION_NUMBER >= 0x0090605fL\n\t\tssl_ctx_options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;\n#endif\n\t\tSSL_CTX_set_options(ctx, ssl_ctx_options);\n\n\t\tftp->ssl_handle = SSL_new(ctx);\n\t\tif (ftp->ssl_handle == NULL) {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"failed to create the SSL handle\");\n\t\t\tSSL_CTX_free(ctx);\n\t\t\treturn 0;\n\t\t}\n\n\t\tSSL_set_fd(ftp->ssl_handle, ftp->fd);\n\n\t\tif (SSL_connect(ftp->ssl_handle) <= 0) {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"SSL/TLS handshake failed\");\n\t\t\tSSL_shutdown(ftp->ssl_handle);\n\t\t\tSSL_free(ftp->ssl_handle);\n\t\t\treturn 0;\n\t\t}\n\n\t\tftp->ssl_active = 1;\n\n\t\tif (!ftp->old_ssl) {\n\n\t\t\t/* set protection buffersize to zero */\n\t\t\tif (!ftp_putcmd(ftp, \"PBSZ\", \"0\")) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (!ftp_getresp(ftp)) {\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\t/* enable data conn encryption */\n\t\t\tif (!ftp_putcmd(ftp, \"PROT\", \"P\")) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (!ftp_getresp(ftp)) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\t\n\t\t\tftp->use_ssl_for_data = (ftp->resp >= 200 && ftp->resp <=299);\t\t\n\t\t}\n\t}\n#endif\n\n\tif (!ftp_putcmd(ftp, \"USER\", user)) {\n\t\treturn 0;\n\t}\n\tif (!ftp_getresp(ftp)) {\n\t\treturn 0;\n\t}\n\tif (ftp->resp == 230) {\n\t\treturn 1;\n\t}\n\tif (ftp->resp != 331) {\n\t\treturn 0;\n\t}\n\tif (!ftp_putcmd(ftp, \"PASS\", pass)) {\n\t\treturn 0;\n\t}\n\tif (!ftp_getresp(ftp)) {\n\t\treturn 0;\n\t}\n\treturn (ftp->resp == 230);\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_chmod(ftpbuf_t *ftp, const int mode, const char *filename, const int filename_len)\n{\n\tchar *buffer;\n\n\tif (ftp == NULL || filename_len <= 0) {\n\t\treturn 0;\n\t}\n\n\tspprintf(&buffer, 0, \"CHMOD %o %s\", mode, filename);\n\n\tif (!ftp_putcmd(ftp, \"SITE\", buffer)) {\n\t\tefree(buffer);\n\t\treturn 0;\n\t}\n\n\tefree(buffer);\n\n\tif (!ftp_getresp(ftp) || ftp->resp != 200) {\n\t\treturn 0;\n\t}\n\t\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'Fix bug #69545 - avoid overflow when reading list'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ftp_genlist(ftpbuf_t *ftp, const char *cmd, const char *path TSRMLS_DC)\n{\n\tphp_stream\t*tmpstream = NULL;\n\tdatabuf_t\t*data = NULL;\n\tchar\t\t*ptr;\n\tint\t\tch, lastch;\n\tsize_t\t\tsize, rcvd;\n\tsize_t\t\tlines;\n\tchar\t\t**ret = NULL;\n\tchar\t\t**entry;\n\tchar\t\t*text;\n\n\n\tif ((tmpstream = php_stream_fopen_tmpfile()) == NULL) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Unable to create temporary file. Check permissions in temporary files directory.\");\n\t\treturn NULL;\n\t}\n\n\tif (!ftp_type(ftp, FTPTYPE_ASCII)) {\n\t\tgoto bail;\n\t}\n\n\tif ((data = ftp_getdata(ftp TSRMLS_CC)) == NULL) {\n\t\tgoto bail;\n\t}\n\tftp->data = data;\n\n\tif (!ftp_putcmd(ftp, cmd, path)) {\n\t\tgoto bail;\n\t}\n\tif (!ftp_getresp(ftp) || (ftp->resp != 150 && ftp->resp != 125 && ftp->resp != 226)) {\n\t\tgoto bail;\n\t}\n\n\t/* some servers don't open a ftp-data connection if the directory is empty */\n\tif (ftp->resp == 226) {\n\t\tftp->data = data_close(ftp, data);\n\t\tphp_stream_close(tmpstream);\n\t\treturn ecalloc(1, sizeof(char*));\n\t}\n\n\t/* pull data buffer into tmpfile */\n\tif ((data = data_accept(data, ftp TSRMLS_CC)) == NULL) {\n\t\tgoto bail;\n\t}\n\tsize = 0;\n\tlines = 0;\n\tlastch = 0;\n\twhile ((rcvd = my_recv(ftp, data->fd, data->buf, FTP_BUFSIZE))) {\n\t\tif (rcvd == -1 || rcvd > ((size_t)(-1))-size) {\n\t\t\tgoto bail;\n\t\t}\n\n\t\tphp_stream_write(tmpstream, data->buf, rcvd);\n\n\t\tsize += rcvd;\n\t\tfor (ptr = data->buf; rcvd; rcvd--, ptr++) {\n\t\t\tif (*ptr == '\\n' && lastch == '\\r') {\n\t\t\t\tlines++;\n\t\t\t} else {\n\t\t\t\tsize++;\n\t\t\t}\n\t\t\tlastch = *ptr;\n\t\t}\n\t}\n\n\tftp->data = data_close(ftp, data);\n\n\tphp_stream_rewind(tmpstream);\n\n\tret = safe_emalloc((lines + 1), sizeof(char*), size);\n\n\tentry = ret;\n\ttext = (char*) (ret + lines + 1);\n\t*entry = text;\n\tlastch = 0;\n\twhile ((ch = php_stream_getc(tmpstream)) != EOF) {\n\t\tif (ch == '\\n' && lastch == '\\r') {\n\t\t\t*(text - 1) = 0;\n\t\t\t*++entry = text;\n\t\t} else {\n\t\t\t*text++ = ch;\n\t\t}\n\t\tlastch = ch;\n\t}\n\t*entry = NULL;\n\n\tphp_stream_close(tmpstream);\n\n\tif (!ftp_getresp(ftp) || (ftp->resp != 226 && ftp->resp != 250)) {\n\t\tefree(ret);\n\t\treturn NULL;\n\t}\n\n\treturn ret;\nbail:\n\tftp->data = data_close(ftp, data);\n\tphp_stream_close(tmpstream);\n\tif (ret)\n\t\tefree(ret);\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'improve fix for Bug #69545'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: tChecksumCheckResult ParaNdis_CheckRxChecksum(\n PARANDIS_ADAPTER *pContext,\n ULONG virtioFlags,\n tCompletePhysicalAddress *pPacketPages,\n ULONG ulPacketLength,\n ULONG ulDataOffset)\n{\n tOffloadSettingsFlags f = pContext->Offload.flags;\n tChecksumCheckResult res;\n tTcpIpPacketParsingResult ppr;\n ULONG flagsToCalculate = 0;\n res.value = 0;\n\n //VIRTIO_NET_HDR_F_NEEDS_CSUM - we need to calculate TCP/UDP CS\n //VIRTIO_NET_HDR_F_DATA_VALID - host tells us TCP/UDP CS is OK\n\n if (f.fRxIPChecksum) flagsToCalculate |= pcrIpChecksum; // check only\n\n if (!(virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID))\n {\n if (virtioFlags & VIRTIO_NET_HDR_F_NEEDS_CSUM)\n {\n flagsToCalculate |= pcrFixXxpChecksum | pcrTcpChecksum | pcrUdpChecksum;\n }\n else\n {\n if (f.fRxTCPChecksum) flagsToCalculate |= pcrTcpV4Checksum;\n if (f.fRxUDPChecksum) flagsToCalculate |= pcrUdpV4Checksum;\n if (f.fRxTCPv6Checksum) flagsToCalculate |= pcrTcpV6Checksum;\n if (f.fRxUDPv6Checksum) flagsToCalculate |= pcrUdpV6Checksum;\n }\n }\n\n ppr = ParaNdis_CheckSumVerify(pPacketPages, ulPacketLength - ETH_HEADER_SIZE, ulDataOffset + ETH_HEADER_SIZE, flagsToCalculate, __FUNCTION__);\n\n if (ppr.ipCheckSum == ppresIPTooShort || ppr.xxpStatus == ppresXxpIncomplete)\n {\n res.flags.IpOK = FALSE;\n res.flags.IpFailed = TRUE;\n return res;\n }\n\n if (virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID)\n {\n pContext->extraStatistics.framesRxCSHwOK++;\n ppr.xxpCheckSum = ppresCSOK;\n }\n\n if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment)\n {\n if (f.fRxIPChecksum)\n {\n res.flags.IpOK = ppr.ipCheckSum == ppresCSOK;\n res.flags.IpFailed = ppr.ipCheckSum == ppresCSBad;\n }\n if(ppr.xxpStatus == ppresXxpKnown)\n {\n if(ppr.TcpUdp == ppresIsTCP) /* TCP */\n {\n if (f.fRxTCPChecksum)\n {\n res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;\n res.flags.TcpFailed = !res.flags.TcpOK;\n }\n }\n else /* UDP */\n {\n if (f.fRxUDPChecksum)\n {\n res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;\n res.flags.UdpFailed = !res.flags.UdpOK;\n }\n }\n }\n }\n else if (ppr.ipStatus == ppresIPV6)\n {\n if(ppr.xxpStatus == ppresXxpKnown)\n {\n if(ppr.TcpUdp == ppresIsTCP) /* TCP */\n {\n if (f.fRxTCPv6Checksum)\n {\n res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;\n res.flags.TcpFailed = !res.flags.TcpOK;\n }\n }\n else /* UDP */\n {\n if (f.fRxUDPv6Checksum)\n {\n res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;\n res.flags.UdpFailed = !res.flags.UdpOK;\n }\n }\n }\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: 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: ProcessTCPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)\n{\n ULONG tcpipDataAt;\n tTcpIpPacketParsingResult res = _res;\n tcpipDataAt = ipHeaderSize + sizeof(TCPHeader);\n res.xxpStatus = ppresXxpIncomplete;\n res.TcpUdp = ppresIsTCP;\n\n if (len >= tcpipDataAt)\n {\n TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);\n res.xxpStatus = ppresXxpKnown;\n tcpipDataAt = ipHeaderSize + TCP_HEADER_LENGTH(pTcpHeader);\n res.XxpIpHeaderSize = tcpipDataAt;\n }\n else\n {\n DPrintf(2, (\"tcp: %d < min headers %d\\n\", len, tcpipDataAt));\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(imagefilledarc)\n{\n\tzval *IM;\n\tlong cx, cy, w, h, ST, E, col, style;\n\tgdImagePtr im;\n\tint e, st;\n\t\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"rllllllll\", &IM, &cx, &cy, &w, &h, &ST, &E, &col, &style) == FAILURE) {\n\t\treturn;\n\t}\n\n\tZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, \"Image\", le_gd);\n\n\te = E;\n\tif (e < 0) {\n\t\te %= 360;\n\t}\n\n\tst = ST;\n\tif (st < 0) {\n\t\tst %= 360;\n\t}\n\n\tgdImageFilledArc(im, cx, cy, w, h, st, e, col, style);\n\n\tRETURN_TRUE;\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: static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)\n{\n\tX509_STORE *store = NULL;\n\n\tstore = X509_STORE_new();\n\n\t/* Load the CAs we trust */\n\tif (conf->ca_file || conf->ca_path)\n\t\tif(!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {\n\t\t\tERROR(LOG_PREFIX \": X509_STORE 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\n#ifdef X509_V_FLAG_CRL_CHECK\n\tif (conf->check_crl)\n\t\tX509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);\n#endif\n\treturn store;\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: int lxc_attach(const char* name, const char* lxcpath, lxc_attach_exec_t exec_function, void* exec_payload, lxc_attach_options_t* options, pid_t* attached_process)\n{\n\tint ret, status;\n\tpid_t init_pid, pid, attached_pid, expected;\n\tstruct lxc_proc_context_info *init_ctx;\n\tchar* cwd;\n\tchar* new_cwd;\n\tint ipc_sockets[2];\n\tsigned long personality;\n\n\tif (!options)\n\t\toptions = &attach_static_default_options;\n\n\tinit_pid = lxc_cmd_get_init_pid(name, lxcpath);\n\tif (init_pid < 0) {\n\t\tERROR(\"failed to get the init pid\");\n\t\treturn -1;\n\t}\n\n\tinit_ctx = lxc_proc_get_context_info(init_pid);\n\tif (!init_ctx) {\n\t\tERROR(\"failed to get context of the init process, pid = %ld\", (long)init_pid);\n\t\treturn -1;\n\t}\n\n\tpersonality = get_personality(name, lxcpath);\n\tif (init_ctx->personality < 0) {\n\t\tERROR(\"Failed to get personality of the container\");\n\t\tlxc_proc_put_context_info(init_ctx);\n\t\treturn -1;\n\t}\n\tinit_ctx->personality = personality;\n\n\tif (!fetch_seccomp(name, lxcpath, init_ctx, options))\n\t\tWARN(\"Failed to get seccomp policy\");\n\n\tcwd = getcwd(NULL, 0);\n\n\t/* determine which namespaces the container was created with\n\t * by asking lxc-start, if necessary\n\t */\n\tif (options->namespaces == -1) {\n\t\toptions->namespaces = lxc_cmd_get_clone_flags(name, lxcpath);\n\t\t/* call failed */\n\t\tif (options->namespaces == -1) {\n\t\t\tERROR(\"failed to automatically determine the \"\n\t\t\t \"namespaces which the container unshared\");\n\t\t\tfree(cwd);\n\t\t\tlxc_proc_put_context_info(init_ctx);\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\t/* create a socket pair for IPC communication; set SOCK_CLOEXEC in order\n\t * to make sure we don't irritate other threads that want to fork+exec away\n\t *\n\t * IMPORTANT: if the initial process is multithreaded and another call\n\t * just fork()s away without exec'ing directly after, the socket fd will\n\t * exist in the forked process from the other thread and any close() in\n\t * our own child process will not really cause the socket to close properly,\n\t * potentiall causing the parent to hang.\n\t *\n\t * For this reason, while IPC is still active, we have to use shutdown()\n\t * if the child exits prematurely in order to signal that the socket\n\t * is closed and cannot assume that the child exiting will automatically\n\t * do that.\n\t *\n\t * IPC mechanism: (X is receiver)\n\t * initial process intermediate attached\n\t * X <--- send pid of\n\t * attached proc,\n\t * then exit\n\t * send 0 ------------------------------------> X\n\t * [do initialization]\n\t * X <------------------------------------ send 1\n\t * [add to cgroup, ...]\n\t * send 2 ------------------------------------> X\n\t * close socket close socket\n\t * run program\n\t */\n\tret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, ipc_sockets);\n\tif (ret < 0) {\n\t\tSYSERROR(\"could not set up required IPC mechanism for attaching\");\n\t\tfree(cwd);\n\t\tlxc_proc_put_context_info(init_ctx);\n\t\treturn -1;\n\t}\n\n\t/* create intermediate subprocess, three reasons:\n\t * 1. runs all pthread_atfork handlers and the\n\t * child will no longer be threaded\n\t * (we can't properly setns() in a threaded process)\n\t * 2. we can't setns() in the child itself, since\n\t * we want to make sure we are properly attached to\n\t * the pidns\n\t * 3. also, the initial thread has to put the attached\n\t * process into the cgroup, which we can only do if\n\t * we didn't already setns() (otherwise, user\n\t * namespaces will hate us)\n\t */\n\tpid = fork();\n\n\tif (pid < 0) {\n\t\tSYSERROR(\"failed to create first subprocess\");\n\t\tfree(cwd);\n\t\tlxc_proc_put_context_info(init_ctx);\n\t\treturn -1;\n\t}\n\n\tif (pid) {\n\t\tpid_t to_cleanup_pid = pid;\n\n\t\t/* initial thread, we close the socket that is for the\n\t\t * subprocesses\n\t\t */\n\t\tclose(ipc_sockets[1]);\n\t\tfree(cwd);\n\n\t\t/* attach to cgroup, if requested */\n\t\tif (options->attach_flags & LXC_ATTACH_MOVE_TO_CGROUP) {\n\t\t\tif (!cgroup_attach(name, lxcpath, pid))\n\t\t\t\tgoto cleanup_error;\n\t\t}\n\n\t\t/* Let the child process know to go ahead */\n\t\tstatus = 0;\n\t\tret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status));\n\t\tif (ret <= 0) {\n\t\t\tERROR(\"error using IPC to notify attached process for initialization (0)\");\n\t\t\tgoto cleanup_error;\n\t\t}\n\n\t\t/* get pid from intermediate process */\n\t\tret = lxc_read_nointr_expect(ipc_sockets[0], &attached_pid, sizeof(attached_pid), NULL);\n\t\tif (ret <= 0) {\n\t\t\tif (ret != 0)\n\t\t\t\tERROR(\"error using IPC to receive pid of attached process\");\n\t\t\tgoto cleanup_error;\n\t\t}\n\n\t\t/* ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\\) - issue #313 */\n\t\tif (options->stdin_fd == 0) {\n\t\t\tsignal(SIGINT, SIG_IGN);\n\t\t\tsignal(SIGQUIT, SIG_IGN);\n\t\t}\n\n\t\t/* reap intermediate process */\n\t\tret = wait_for_pid(pid);\n\t\tif (ret < 0)\n\t\t\tgoto cleanup_error;\n\n\t\t/* we will always have to reap the grandchild now */\n\t\tto_cleanup_pid = attached_pid;\n\n\t\t/* tell attached process it may start initializing */\n\t\tstatus = 0;\n\t\tret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status));\n\t\tif (ret <= 0) {\n\t\t\tERROR(\"error using IPC to notify attached process for initialization (0)\");\n\t\t\tgoto cleanup_error;\n\t\t}\n\n\t\t/* wait for the attached process to finish initializing */\n\t\texpected = 1;\n\t\tret = lxc_read_nointr_expect(ipc_sockets[0], &status, sizeof(status), &expected);\n\t\tif (ret <= 0) {\n\t\t\tif (ret != 0)\n\t\t\t\tERROR(\"error using IPC to receive notification from attached process (1)\");\n\t\t\tgoto cleanup_error;\n\t\t}\n\n\t\t/* tell attached process we're done */\n\t\tstatus = 2;\n\t\tret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status));\n\t\tif (ret <= 0) {\n\t\t\tERROR(\"error using IPC to notify attached process for initialization (2)\");\n\t\t\tgoto cleanup_error;\n\t\t}\n\n\t\t/* now shut down communication with child, we're done */\n\t\tshutdown(ipc_sockets[0], SHUT_RDWR);\n\t\tclose(ipc_sockets[0]);\n\t\tlxc_proc_put_context_info(init_ctx);\n\n\t\t/* we're done, the child process should now execute whatever\n\t\t * it is that the user requested. The parent can now track it\n\t\t * with waitpid() or similar.\n\t\t */\n\n\t\t*attached_process = attached_pid;\n\t\treturn 0;\n\n\tcleanup_error:\n\t\t/* first shut down the socket, then wait for the pid,\n\t\t * otherwise the pid we're waiting for may never exit\n\t\t */\n\t\tshutdown(ipc_sockets[0], SHUT_RDWR);\n\t\tclose(ipc_sockets[0]);\n\t\tif (to_cleanup_pid)\n\t\t\t(void) wait_for_pid(to_cleanup_pid);\n\t\tlxc_proc_put_context_info(init_ctx);\n\t\treturn -1;\n\t}\n\n\t/* first subprocess begins here, we close the socket that is for the\n\t * initial thread\n\t */\n\tclose(ipc_sockets[0]);\n\n\t/* Wait for the parent to have setup cgroups */\n\texpected = 0;\n\tstatus = -1;\n\tret = lxc_read_nointr_expect(ipc_sockets[1], &status, sizeof(status), &expected);\n\tif (ret <= 0) {\n\t\tERROR(\"error communicating with child process\");\n\t\tshutdown(ipc_sockets[1], SHUT_RDWR);\n\t\trexit(-1);\n\t}\n\n\t/* attach now, create another subprocess later, since pid namespaces\n\t * only really affect the children of the current process\n\t */\n\tret = lxc_attach_to_ns(init_pid, options->namespaces);\n\tif (ret < 0) {\n\t\tERROR(\"failed to enter the namespace\");\n\t\tshutdown(ipc_sockets[1], SHUT_RDWR);\n\t\trexit(-1);\n\t}\n\n\t/* attach succeeded, try to cwd */\n\tif (options->initial_cwd)\n\t\tnew_cwd = options->initial_cwd;\n\telse\n\t\tnew_cwd = cwd;\n\tret = chdir(new_cwd);\n\tif (ret < 0)\n\t\tWARN(\"could not change directory to '%s'\", new_cwd);\n\tfree(cwd);\n\n\t/* now create the real child process */\n\t{\n\t\tstruct attach_clone_payload payload = {\n\t\t\t.ipc_socket = ipc_sockets[1],\n\t\t\t.options = options,\n\t\t\t.init_ctx = init_ctx,\n\t\t\t.exec_function = exec_function,\n\t\t\t.exec_payload = exec_payload\n\t\t};\n\t\t/* We use clone_parent here to make this subprocess a direct child of\n\t\t * the initial process. Then this intermediate process can exit and\n\t\t * the parent can directly track the attached process.\n\t\t */\n\t\tpid = lxc_clone(attach_child_main, &payload, CLONE_PARENT);\n\t}\n\n\t/* shouldn't happen, clone() should always return positive pid */\n\tif (pid <= 0) {\n\t\tSYSERROR(\"failed to create subprocess\");\n\t\tshutdown(ipc_sockets[1], SHUT_RDWR);\n\t\trexit(-1);\n\t}\n\n\t/* tell grandparent the pid of the pid of the newly created child */\n\tret = lxc_write_nointr(ipc_sockets[1], &pid, sizeof(pid));\n\tif (ret != sizeof(pid)) {\n\t\t/* if this really happens here, this is very unfortunate, since the\n\t\t * parent will not know the pid of the attached process and will\n\t\t * not be able to wait for it (and we won't either due to CLONE_PARENT)\n\t\t * so the parent won't be able to reap it and the attached process\n\t\t * will remain a zombie\n\t\t */\n\t\tERROR(\"error using IPC to notify main process of pid of the attached process\");\n\t\tshutdown(ipc_sockets[1], SHUT_RDWR);\n\t\trexit(-1);\n\t}\n\n\t/* the rest is in the hands of the initial and the attached process */\n\trexit(0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-17'], 'message': 'CVE-2015-1334: Don't use the container's /proc during attach\n\nA user could otherwise over-mount /proc and prevent the apparmor profile\nor selinux label from being written which combined with a modified\n/bin/sh or other commonly used binary would lead to unconfined code\nexecution.\n\nReported-by: Roman Fiedler\nSigned-off-by: St\u00e9phane Graber '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: sg_start_req(Sg_request *srp, unsigned char *cmd)\n{\n\tint res;\n\tstruct request *rq;\n\tSg_fd *sfp = srp->parentfp;\n\tsg_io_hdr_t *hp = &srp->header;\n\tint dxfer_len = (int) hp->dxfer_len;\n\tint dxfer_dir = hp->dxfer_direction;\n\tunsigned int iov_count = hp->iovec_count;\n\tSg_scatter_hold *req_schp = &srp->data;\n\tSg_scatter_hold *rsv_schp = &sfp->reserve;\n\tstruct request_queue *q = sfp->parentdp->device->request_queue;\n\tstruct rq_map_data *md, map_data;\n\tint rw = hp->dxfer_direction == SG_DXFER_TO_DEV ? WRITE : READ;\n\tunsigned char *long_cmdp = NULL;\n\n\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t\t \"sg_start_req: dxfer_len=%d\\n\",\n\t\t\t\t dxfer_len));\n\n\tif (hp->cmd_len > BLK_MAX_CDB) {\n\t\tlong_cmdp = kzalloc(hp->cmd_len, GFP_KERNEL);\n\t\tif (!long_cmdp)\n\t\t\treturn -ENOMEM;\n\t}\n\n\t/*\n\t * NOTE\n\t *\n\t * With scsi-mq enabled, there are a fixed number of preallocated\n\t * requests equal in number to shost->can_queue. If all of the\n\t * preallocated requests are already in use, then using GFP_ATOMIC with\n\t * blk_get_request() will return -EWOULDBLOCK, whereas using GFP_KERNEL\n\t * will cause blk_get_request() to sleep until an active command\n\t * completes, freeing up a request. Neither option is ideal, but\n\t * GFP_KERNEL is the better choice to prevent userspace from getting an\n\t * unexpected EWOULDBLOCK.\n\t *\n\t * With scsi-mq disabled, blk_get_request() with GFP_KERNEL usually\n\t * does not sleep except under memory pressure.\n\t */\n\trq = blk_get_request(q, rw, GFP_KERNEL);\n\tif (IS_ERR(rq)) {\n\t\tkfree(long_cmdp);\n\t\treturn PTR_ERR(rq);\n\t}\n\n\tblk_rq_set_block_pc(rq);\n\n\tif (hp->cmd_len > BLK_MAX_CDB)\n\t\trq->cmd = long_cmdp;\n\tmemcpy(rq->cmd, cmd, hp->cmd_len);\n\trq->cmd_len = hp->cmd_len;\n\n\tsrp->rq = rq;\n\trq->end_io_data = srp;\n\trq->sense = srp->sense_b;\n\trq->retries = SG_DEFAULT_RETRIES;\n\n\tif ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE))\n\t\treturn 0;\n\n\tif (sg_allow_dio && hp->flags & SG_FLAG_DIRECT_IO &&\n\t dxfer_dir != SG_DXFER_UNKNOWN && !iov_count &&\n\t !sfp->parentdp->device->host->unchecked_isa_dma &&\n\t blk_rq_aligned(q, (unsigned long)hp->dxferp, dxfer_len))\n\t\tmd = NULL;\n\telse\n\t\tmd = &map_data;\n\n\tif (md) {\n\t\tif (!sg_res_in_use(sfp) && dxfer_len <= rsv_schp->bufflen)\n\t\t\tsg_link_reserve(sfp, srp, dxfer_len);\n\t\telse {\n\t\t\tres = sg_build_indirect(req_schp, sfp, dxfer_len);\n\t\t\tif (res)\n\t\t\t\treturn res;\n\t\t}\n\n\t\tmd->pages = req_schp->pages;\n\t\tmd->page_order = req_schp->page_order;\n\t\tmd->nr_entries = req_schp->k_use_sg;\n\t\tmd->offset = 0;\n\t\tmd->null_mapped = hp->dxferp ? 0 : 1;\n\t\tif (dxfer_dir == SG_DXFER_TO_FROM_DEV)\n\t\t\tmd->from_user = 1;\n\t\telse\n\t\t\tmd->from_user = 0;\n\t}\n\n\tif (iov_count) {\n\t\tint size = sizeof(struct iovec) * iov_count;\n\t\tstruct iovec *iov;\n\t\tstruct iov_iter i;\n\n\t\tiov = memdup_user(hp->dxferp, size);\n\t\tif (IS_ERR(iov))\n\t\t\treturn PTR_ERR(iov);\n\n\t\tiov_iter_init(&i, rw, iov, iov_count,\n\t\t\t min_t(size_t, hp->dxfer_len,\n\t\t\t\t iov_length(iov, iov_count)));\n\n\t\tres = blk_rq_map_user_iov(q, rq, md, &i, GFP_ATOMIC);\n\t\tkfree(iov);\n\t} else\n\t\tres = blk_rq_map_user(q, rq, md, hp->dxferp,\n\t\t\t\t hp->dxfer_len, GFP_ATOMIC);\n\n\tif (!res) {\n\t\tsrp->bio = rq->bio;\n\n\t\tif (!md) {\n\t\t\treq_schp->dio_in_use = 1;\n\t\t\thp->info |= SG_INFO_DIRECT_IO;\n\t\t}\n\t}\n\treturn res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-189'], 'message': 'sg_start_req(): make sure that there's not too many elements in iovec\n\nunfortunately, allowing an arbitrary 16bit value means a possibility of\noverflow in the calculation of total number of pages in bio_map_user_iov() -\nwe rely on there being no more than PAGE_SIZE members of sum in the\nfirst loop there. If that sum wraps around, we end up allocating\ntoo small array of pointers to pages and it's easy to overflow it in\nthe second loop.\n\nX-Coverup: TINC (and there's no lumber cartel either)\nCc: stable@vger.kernel.org # way, way back\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: Debug(const char *fmtstr,\n va_list args)\n{\n /* Ignored */\n#ifdef VMX86_DEBUG\n sLog(log_warning, \"Debug callback invoked. \\n\");\n#endif\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: static int mem_read(jas_stream_obj_t *obj, char *buf, int cnt)\n{\n\tint n;\n\tassert(cnt >= 0);\n\tassert(buf);\n\n\tJAS_DBGLOG(100, (\"mem_read(%p, %p, %d)\\n\", obj, buf, cnt));\n\tjas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;\n\tn = m->len_ - m->pos_;\n\tcnt = JAS_MIN(n, cnt);\n\tmemcpy(buf, &m->buf_[m->pos_], cnt);\n\tm->pos_ += cnt;\n\treturn cnt;\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_dpy_switch(DisplayChangeListener *dcl,\n DisplaySurface *surface)\n{\n VncDisplay *vd = container_of(dcl, VncDisplay, dcl);\n VncState *vs;\n\n vnc_abort_display_jobs(vd);\n\n /* server surface */\n qemu_pixman_image_unref(vd->server);\n vd->ds = surface;\n vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,\n surface_width(vd->ds),\n surface_height(vd->ds),\n NULL, 0);\n\n /* guest surface */\n#if 0 /* FIXME */\n if (ds_get_bytes_per_pixel(ds) != vd->guest.ds->pf.bytes_per_pixel)\n console_color_init(ds);\n#endif\n qemu_pixman_image_unref(vd->guest.fb);\n vd->guest.fb = pixman_image_ref(surface->image);\n vd->guest.format = surface->format;\n VNC_SET_VISIBLE_PIXELS_DIRTY(vd->guest.dirty,\n surface_width(vd->ds),\n surface_height(vd->ds));\n\n QTAILQ_FOREACH(vs, &vd->clients, next) {\n vnc_colordepth(vs);\n vnc_desktop_resize(vs);\n if (vs->vd->cursor) {\n vnc_cursor_define(vs);\n }\n VNC_SET_VISIBLE_PIXELS_DIRTY(vs->dirty,\n surface_width(vd->ds),\n surface_height(vd->ds));\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, serialize)\n{\n\tspl_SplObjectStorage *intern = (spl_SplObjectStorage*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\n\tspl_SplObjectStorageElement *element;\n\tzval members, *pmembers, *flags;\n\tHashPosition pos;\n\tphp_serialize_data_t var_hash;\n\tsmart_str buf = {0};\n\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\n\tPHP_VAR_SERIALIZE_INIT(var_hash);\n\t\n\t/* storage */\n\tsmart_str_appendl(&buf, \"x:\", 2);\n\tMAKE_STD_ZVAL(flags);\n\tZVAL_LONG(flags, zend_hash_num_elements(&intern->storage));\n\tphp_var_serialize(&buf, &flags, &var_hash TSRMLS_CC);\n\tzval_ptr_dtor(&flags);\n\n\tzend_hash_internal_pointer_reset_ex(&intern->storage, &pos);\n\n\twhile(zend_hash_has_more_elements_ex(&intern->storage, &pos) == SUCCESS) {\n\t\tif (zend_hash_get_current_data_ex(&intern->storage, (void**)&element, &pos) == FAILURE) {\n\t\t\tsmart_str_free(&buf);\n\t\t\tPHP_VAR_SERIALIZE_DESTROY(var_hash);\n\t\t\tRETURN_NULL();\n\t\t}\n\t\tphp_var_serialize(&buf, &element->obj, &var_hash TSRMLS_CC);\n\t\tsmart_str_appendc(&buf, ',');\n\t\tphp_var_serialize(&buf, &element->inf, &var_hash TSRMLS_CC);\n\t\tsmart_str_appendc(&buf, ';');\n\t\tzend_hash_move_forward_ex(&intern->storage, &pos);\n\t}\n\n\t/* members */\n\tsmart_str_appendl(&buf, \"m:\", 2);\n\tINIT_PZVAL(&members);\n\tZ_ARRVAL(members) = zend_std_get_properties(getThis() TSRMLS_CC);\n\tZ_TYPE(members) = IS_ARRAY;\n\tpmembers = &members;\n\tphp_var_serialize(&buf, &pmembers, &var_hash TSRMLS_CC); /* finishes the string */\n\n\t/* done */\n\tPHP_VAR_SERIALIZE_DESTROY(var_hash);\n\n\tif (buf.c) {\n\t\tRETURN_STRINGL(buf.c, buf.len, 0);\n\t} else {\n\t\tRETURN_NULL();\n\t}\n\t\n} /* }}} */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': '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, key)\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\tRETURN_LONG(intern->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: static int spl_dllist_object_count_elements(zval *object, long *count TSRMLS_DC) /* {{{ */\n{\n\tspl_dllist_object *intern = (spl_dllist_object*)zend_object_store_get_object(object TSRMLS_CC);\n\n\tif (intern->fptr_count) {\n\t\tzval *rv;\n\t\tzend_call_method_with_0_params(&object, intern->std.ce, &intern->fptr_count, \"count\", &rv);\n\t\tif (rv) {\n\t\t\tzval_ptr_dtor(&intern->retval);\n\t\t\tMAKE_STD_ZVAL(intern->retval);\n\t\t\tZVAL_ZVAL(intern->retval, rv, 1, 1);\n\t\t\tconvert_to_long(intern->retval);\n\t\t\t*count = (long) Z_LVAL_P(intern->retval);\n\t\t\treturn SUCCESS;\n\t\t}\n\t\t*count = 0;\n\t\treturn FAILURE;\n\t}\n\n\t*count = spl_ptr_llist_count(intern->llist);\n\treturn SUCCESS;\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: int setpwnam(struct passwd *pwd)\n{\n\tFILE *fp = NULL, *pwf = NULL;\n\tint save_errno;\n\tint found;\n\tint namelen;\n\tint buflen = 256;\n\tint contlen, rc;\n\tchar *linebuf = NULL;\n\tchar *tmpname = NULL;\n\tchar *atomic_dir = \"/etc\";\n\n\tpw_init();\n\n\tif ((fp = xfmkstemp(&tmpname, atomic_dir)) == NULL)\n\t\treturn -1;\n\n\t/* ptmp should be owned by root.root or root.wheel */\n\tif (fchown(fileno(fp), (uid_t) 0, (gid_t) 0) < 0)\n\t\tgoto fail;\n\n\t/* acquire exclusive lock */\n\tif (lckpwdf() < 0)\n\t\tgoto fail;\n\tpwf = fopen(PASSWD_FILE, \"r\");\n\tif (!pwf)\n\t\tgoto fail;\n\n\tnamelen = strlen(pwd->pw_name);\n\n\tlinebuf = malloc(buflen);\n\tif (!linebuf)\n\t\tgoto fail;\n\n\t/* parse the passwd file */\n\tfound = false;\n\n\t/* Do you wonder why I don't use getpwent? Read comments at top of\n\t * file */\n\twhile (fgets(linebuf, buflen, pwf) != NULL) {\n\t\tcontlen = strlen(linebuf);\n\t\twhile (linebuf[contlen - 1] != '\\n' && !feof(pwf)) {\n\t\t\tchar *tmp;\n\t\t\t/* Extend input buffer if it failed getting the whole line,\n\t\t\t * so now we double the buffer size */\n\t\t\tbuflen *= 2;\n\t\t\ttmp = realloc(linebuf, buflen);\n\t\t\tif (tmp == NULL)\n\t\t\t\tgoto fail;\n\t\t\tlinebuf = tmp;\n\t\t\t/* And fill the rest of the buffer */\n\t\t\tif (fgets(&linebuf[contlen], buflen / 2, pwf) == NULL)\n\t\t\t\tbreak;\n\t\t\tcontlen = strlen(linebuf);\n\t\t\t/* That was a lot of work for nothing. Gimme perl! */\n\t\t}\n\n\t\t/* Is this the username we were sent to change? */\n\t\tif (!found && linebuf[namelen] == ':' &&\n\t\t !strncmp(linebuf, pwd->pw_name, namelen)) {\n\t\t\t/* Yes! So go forth in the name of the Lord and\n\t\t\t * change it! */\n\t\t\tif (putpwent(pwd, fp) < 0)\n\t\t\t\tgoto fail;\n\t\t\tfound = true;\n\t\t\tcontinue;\n\t\t}\n\t\t/* Nothing in particular happened, copy input to output */\n\t\tfputs(linebuf, fp);\n\t}\n\n\t/* xfmkstemp is too restrictive by default for passwd file */\n\tif (fchmod(fileno(fp), 0644) < 0)\n\t\tgoto fail;\n\trc = close_stream(fp);\n\tfp = NULL;\n\tif (rc != 0)\n\t\tgoto fail;\n\n\tfclose(pwf);\t/* I don't think I want to know if this failed */\n\tpwf = NULL;\n\n\tif (!found) {\n\t\terrno = ENOENT;\t/* give me something better */\n\t\tgoto fail;\n\t}\n\n\t/* we don't care if we can't remove the backup file */\n\tunlink(PASSWD_FILE \".OLD\");\n\t/* we don't care if we can't create the backup file */\n\tignore_result(link(PASSWD_FILE, PASSWD_FILE \".OLD\"));\n\t/* we DO care if we can't rename to the passwd file */\n\tif (rename(tmpname, PASSWD_FILE) < 0)\n\t\tgoto fail;\n\t/* finally: success */\n\tulckpwdf();\n\treturn 0;\n\n fail:\n\tsave_errno = errno;\n\tulckpwdf();\n\tif (fp != NULL)\n\t\tfclose(fp);\n\tif (tmpname != NULL)\n\t\tunlink(tmpname);\n\tfree(tmpname);\n\tif (pwf != NULL)\n\t\tfclose(pwf);\n\tfree(linebuf);\n\terrno = save_errno;\n\treturn -1;\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 int php_zip_add_file(struct zip *za, const char *filename, size_t filename_len, \n\tchar *entry_name, size_t entry_name_len, long offset_start, long offset_len TSRMLS_DC) /* {{{ */\n{\n\tstruct zip_source *zs;\n\tint cur_idx;\n\tchar resolved_path[MAXPATHLEN];\n\tzval exists_flag;\n\n\n\tif (ZIP_OPENBASEDIR_CHECKPATH(filename)) {\n\t\treturn -1;\n\t}\n\n\tif (!expand_filepath(filename, resolved_path TSRMLS_CC)) {\n\t\treturn -1;\n\t}\n\n\tphp_stat(resolved_path, strlen(resolved_path), FS_EXISTS, &exists_flag TSRMLS_CC);\n\tif (!Z_BVAL(exists_flag)) {\n\t\treturn -1;\n\t}\n\n\tzs = zip_source_file(za, resolved_path, offset_start, offset_len);\n\tif (!zs) {\n\t\treturn -1;\n\t}\n\n\tcur_idx = zip_name_locate(za, (const char *)entry_name, 0);\n\t/* TODO: fix _zip_replace */\n\tif (cur_idx<0) {\n\t\t/* reset the error */\n\t\tif (za->error.str) {\n\t\t\t_zip_error_fini(&za->error);\n\t\t}\n\t\t_zip_error_init(&za->error);\n\t} else {\n\t\tif (zip_delete(za, cur_idx) == -1) {\n\t\t\tzip_source_free(zs);\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tif (zip_add(za, entry_name, zs) == -1) {\n\t\treturn -1;\n\t} else {\n\t\treturn 1;\n\t}\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: bilinear_box_make_weights (PixopsFilterDimension *dim,\n\t\t\t double scale)\n{\n int n = ceil (1/scale + 3.0);\n double *pixel_weights = g_malloc_n (sizeof (double) * SUBSAMPLE, n);\n double w;\n int offset, i;\n\n dim->offset = -1.0;\n dim->n = n;\n dim->weights = pixel_weights;\n\n for (offset = 0; offset < SUBSAMPLE; offset++)\n {\n double x = (double)offset / SUBSAMPLE;\n double a = x + 1 / scale;\n\n for (i = 0; i < n; i++)\n {\n w = linear_box_half (0.5 + i - a, 0.5 + i - x);\n w += linear_box_half (1.5 + x - i, 1.5 + a - i);\n \n *(pixel_weights++) = w * scale;\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'pixops: Fail make_weights functions on OOM\n\nThe weights could grow very large under certain circumstances, in\nparticular in security-relevant conditions, including the testsuite.\nBy allowing the weight allocation to fail, this can be worked around.\n\nhttps://bugzilla.gnome.org/show_bug.cgi?id=754387'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void parse_data_for_row_pseudocolor(TGAContext *ctx)\n{\n\tguchar *s = ctx->in->data;\n\tguint upper_bound = ctx->pbuf->width;\n\tguchar *p = ctx->pptr;\n\n\tfor (; upper_bound; upper_bound--, s++) {\n\t\t*p++ = ctx->cmap->cols[*s].r;\n\t\t*p++ = ctx->cmap->cols[*s].g;\n\t\t*p++ = ctx->cmap->cols[*s].b;\n\t\tif (ctx->hdr->cmap_bpp == 32)\n\t\t\t*p++ = ctx->cmap->cols[*s].a;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'tga: Wrap TGAColormap struct in its own API\n\nInstead of poking into it directly.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,\n\t\t\t ssize_t size, void *private)\n{\n ext4_io_end_t *io_end = iocb->private;\n\tstruct workqueue_struct *wq;\n\n\t/* if not async direct IO or dio with 0 bytes write, just return */\n\tif (!io_end || !size)\n\t\treturn;\n\n\text_debug(\"ext4_end_io_dio(): io_end 0x%p\"\n\t\t \"for inode %lu, iocb 0x%p, offset %llu, size %llu\\n\",\n \t\t iocb->private, io_end->inode->i_ino, iocb, offset,\n\t\t size);\n\n\t/* if not aio dio with unwritten extents, just free io and return */\n\tif (io_end->flag != EXT4_IO_UNWRITTEN){\n\t\text4_free_io_end(io_end);\n\t\tiocb->private = NULL;\n\t\treturn;\n\t}\n\n\tio_end->offset = offset;\n\tio_end->size = size;\n\twq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;\n\n\t/* queue the work to convert unwritten extents to written */\n\tqueue_work(wq, &io_end->work);\n\n\t/* Add the io_end to per-inode completed aio dio list*/\n\tlist_add_tail(&io_end->list,\n\t\t &EXT4_I(io_end->inode)->i_completed_io_list);\n\tiocb->private = NULL;\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 void ext4_invalidatepage(struct page *page, unsigned long offset)\n{\n\tjournal_t *journal = EXT4_JOURNAL(page->mapping->host);\n\n\t/*\n\t * If it's a full truncate we just forget about the pending dirtying\n\t */\n\tif (offset == 0)\n\t\tClearPageChecked(page);\n\n\tif (journal)\n\t\tjbd2_journal_invalidatepage(journal, page, offset);\n\telse\n\t\tblock_invalidatepage(page, offset);\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 int mount_entry_on_relative_rootfs(struct mntent *mntent,\n\t\t\t\t\t const char *rootfs)\n{\n\tchar path[MAXPATHLEN];\n\tint ret;\n\n\t/* relative to root mount point */\n\tret = snprintf(path, sizeof(path), \"%s/%s\", rootfs, mntent->mnt_dir);\n\tif (ret >= sizeof(path)) {\n\t\tERROR(\"path name too long\");\n\t\treturn -1;\n\t}\n\n\treturn mount_entry_on_generic(mntent, 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 fill_autodev(const struct lxc_rootfs *rootfs)\n{\n\tint ret;\n\tchar path[MAXPATHLEN];\n\tint i;\n\tmode_t cmask;\n\n\tINFO(\"Creating initial consoles under container /dev\");\n\n\tret = snprintf(path, MAXPATHLEN, \"%s/dev\", rootfs->path ? rootfs->mount : \"\");\n\tif (ret < 0 || ret >= MAXPATHLEN) {\n\t\tERROR(\"Error calculating container /dev location\");\n\t\treturn -1;\n\t}\n\n\tif (!dir_exists(path)) // ignore, just don't try to fill in\n\t\treturn 0;\n\n\tINFO(\"Populating container /dev\");\n\tcmask = umask(S_IXUSR | S_IXGRP | S_IXOTH);\n\tfor (i = 0; i < sizeof(lxc_devs) / sizeof(lxc_devs[0]); i++) {\n\t\tconst struct lxc_devs *d = &lxc_devs[i];\n\t\tret = snprintf(path, MAXPATHLEN, \"%s/dev/%s\", rootfs->path ? rootfs->mount : \"\", d->name);\n\t\tif (ret < 0 || ret >= MAXPATHLEN)\n\t\t\treturn -1;\n\t\tret = mknod(path, d->mode, makedev(d->maj, d->min));\n\t\tif (ret && errno != EEXIST) {\n\t\t\tchar hostpath[MAXPATHLEN];\n\t\t\tFILE *pathfile;\n\n\t\t\t// Unprivileged containers cannot create devices, so\n\t\t\t// bind mount the device from the host\n\t\t\tret = snprintf(hostpath, MAXPATHLEN, \"/dev/%s\", d->name);\n\t\t\tif (ret < 0 || ret >= MAXPATHLEN)\n\t\t\t\treturn -1;\n\t\t\tpathfile = fopen(path, \"wb\");\n\t\t\tif (!pathfile) {\n\t\t\t\tSYSERROR(\"Failed to create device mount target '%s'\", path);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tfclose(pathfile);\n\t\t\tif (mount(hostpath, path, 0, MS_BIND, NULL) != 0) {\n\t\t\t\tSYSERROR(\"Failed bind mounting device %s from host into container\",\n\t\t\t\t\td->name);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t}\n\tumask(cmask);\n\n\tINFO(\"Populated container /dev\");\n\treturn 0;\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 void vmxnet3_process_tx_queue(VMXNET3State *s, int qidx)\n{\n struct Vmxnet3_TxDesc txd;\n uint32_t txd_idx;\n uint32_t data_len;\n hwaddr data_pa;\n\n for (;;) {\n if (!vmxnet3_pop_next_tx_descr(s, qidx, &txd, &txd_idx)) {\n break;\n }\n\n vmxnet3_dump_tx_descr(&txd);\n\n if (!s->skip_current_tx_pkt) {\n data_len = (txd.len > 0) ? txd.len : VMXNET3_MAX_TX_BUF_SIZE;\n data_pa = le64_to_cpu(txd.addr);\n\n if (!vmxnet_tx_pkt_add_raw_fragment(s->tx_pkt,\n data_pa,\n data_len)) {\n s->skip_current_tx_pkt = true;\n }\n }\n\n if (s->tx_sop) {\n vmxnet3_tx_retrieve_metadata(s, &txd);\n s->tx_sop = false;\n }\n\n if (txd.eop) {\n if (!s->skip_current_tx_pkt) {\n vmxnet_tx_pkt_parse(s->tx_pkt);\n\n if (s->needs_vlan) {\n vmxnet_tx_pkt_setup_vlan_header(s->tx_pkt, s->tci);\n }\n\n vmxnet3_send_packet(s, qidx);\n } else {\n vmxnet3_on_tx_done_update_stats(s, qidx,\n VMXNET3_PKT_STATUS_ERROR);\n }\n\n vmxnet3_complete_packet(s, qidx, txd_idx);\n s->tx_sop = true;\n s->skip_current_tx_pkt = false;\n vmxnet_tx_pkt_reset(s->tx_pkt);\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'net/vmxnet3: Refine l2 header validation\n\nValidation of l2 header length assumed minimal packet size as\neth_header + 2 * vlan_header regardless of the actual protocol.\n\nThis caused crash for valid non-IP packets shorter than 22 bytes, as\n'tx_pkt->packet_type' hasn't been assigned for such packets, and\n'vmxnet3_on_tx_done_update_stats()' expects it to be properly set.\n\nRefine header length validation in 'vmxnet_tx_pkt_parse_headers'.\nCheck its return value during packet processing flow.\n\nAs a side effect, in case IPv4 and IPv6 header validation failure,\ncorrupt packets will be dropped.\n\nSigned-off-by: Dana Rubin \nSigned-off-by: Shmulik Ladkani \nSigned-off-by: Jason Wang '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: crypto_xmit(\n\tstruct peer *peer,\t/* peer structure pointer */\n\tstruct pkt *xpkt,\t/* transmit packet pointer */\n\tstruct recvbuf *rbufp,\t/* receive buffer pointer */\n\tint\tstart,\t\t/* offset to extension field */\n\tstruct exten *ep,\t/* extension pointer */\n\tkeyid_t cookie\t\t/* session cookie */\n\t)\n{\n\tstruct exten *fp;\t/* extension pointers */\n\tstruct cert_info *cp, *xp, *yp; /* cert info/value pointer */\n\tsockaddr_u *srcadr_sin; /* source address */\n\tu_int32\t*pkt;\t\t/* packet pointer */\n\tu_int\topcode;\t\t/* extension field opcode */\n\tchar\tcertname[MAXHOSTNAME + 1]; /* subject name buffer */\n\tchar\tstatstr[NTP_MAXSTRLEN]; /* statistics for filegen */\n\ttstamp_t tstamp;\n\tstruct calendar tscal;\n\tu_int\tvallen;\n\tstruct value vtemp;\n\tassocid_t associd;\n\tint\trval;\n\tint\tlen;\n\tkeyid_t tcookie;\n\n\t/*\n\t * Generate the requested extension field request code, length\n\t * and association ID. If this is a response and the host is not\n\t * synchronized, light the error bit and go home.\n\t */\n\tpkt = (u_int32 *)xpkt + start / 4;\n\tfp = (struct exten *)pkt;\n\topcode = ntohl(ep->opcode);\n\tif (peer != NULL) {\n\t\tsrcadr_sin = &peer->srcadr;\n\t\tif (!(opcode & CRYPTO_RESP))\n\t\t\tpeer->opcode = ep->opcode;\n\t} else {\n\t\tsrcadr_sin = &rbufp->recv_srcadr;\n\t}\n\tassocid = (associd_t) ntohl(ep->associd);\n\tlen = 8;\n\tfp->opcode = htonl((opcode & 0xffff0000) | len);\n\tfp->associd = ep->associd;\n\trval = XEVNT_OK;\n\ttstamp = crypto_time();\n\tswitch (opcode & 0xffff0000) {\n\n\t/*\n\t * Send association request and response with status word and\n\t * host name. Note, this message is not signed and the filestamp\n\t * contains only the status word.\n\t */\n\tcase CRYPTO_ASSOC:\n\tcase CRYPTO_ASSOC | CRYPTO_RESP:\n\t\tlen = crypto_send(fp, &hostval, start);\n\t\tfp->fstamp = htonl(crypto_flags);\n\t\tbreak;\n\n\t/*\n\t * Send certificate request. Use the values from the extension\n\t * field.\n\t */\n\tcase CRYPTO_CERT:\n\t\tmemset(&vtemp, 0, sizeof(vtemp));\n\t\tvtemp.tstamp = ep->tstamp;\n\t\tvtemp.fstamp = ep->fstamp;\n\t\tvtemp.vallen = ep->vallen;\n\t\tvtemp.ptr = (u_char *)ep->pkt;\n\t\tlen = crypto_send(fp, &vtemp, start);\n\t\tbreak;\n\n\t/*\n\t * Send sign request. Use the host certificate, which is self-\n\t * signed and may or may not be trusted.\n\t */\n\tcase CRYPTO_SIGN:\n\t\t(void)ntpcal_ntp_to_date(&tscal, tstamp, NULL);\n\t\tif ((calcomp(&tscal, &(cert_host->first)) < 0)\n\t\t|| (calcomp(&tscal, &(cert_host->last)) > 0))\n\t\t\trval = XEVNT_PER;\n\t\telse\n\t\t\tlen = crypto_send(fp, &cert_host->cert, start);\n\t\tbreak;\n\n\t/*\n\t * Send certificate response. Use the name in the extension\n\t * field to find the certificate in the cache. If the request\n\t * contains no subject name, assume the name of this host. This\n\t * is for backwards compatibility. Private certificates are\n\t * never sent.\n\t *\n\t * There may be several certificates matching the request. First\n\t * choice is a self-signed trusted certificate; second choice is\n\t * any certificate signed by another host. There is no third\n\t * choice. \n\t */\n\tcase CRYPTO_CERT | CRYPTO_RESP:\n\t\tvallen = ntohl(ep->vallen);\t/* Must be <64k */\n\t\tif (vallen == 0 || vallen > MAXHOSTNAME ||\n\t\t len - VALUE_LEN < vallen) {\n\t\t\trval = XEVNT_LEN;\n\t\t\tbreak;\n\t\t}\n\n\t\t/*\n\t\t * Find all public valid certificates with matching\n\t\t * subject. If a self-signed, trusted certificate is\n\t\t * found, use that certificate. If not, use the last non\n\t\t * self-signed certificate.\n\t\t */\n\t\tmemcpy(certname, ep->pkt, vallen);\n\t\tcertname[vallen] = '\\0';\n\t\txp = yp = NULL;\n\t\tfor (cp = cinfo; cp != NULL; cp = cp->link) {\n\t\t\tif (cp->flags & (CERT_PRIV | CERT_ERROR))\n\t\t\t\tcontinue;\n\n\t\t\tif (strcmp(certname, cp->subject) != 0)\n\t\t\t\tcontinue;\n\n\t\t\tif (strcmp(certname, cp->issuer) != 0)\n\t\t\t\typ = cp;\n\t\t\telse if (cp ->flags & CERT_TRUST)\n\t\t\t\txp = cp;\n\t\t\tcontinue;\n\t\t}\n\n\t\t/*\n\t\t * Be careful who you trust. If the certificate is not\n\t\t * found, return an empty response. Note that we dont\n\t\t * enforce lifetimes here.\n\t\t *\n\t\t * The timestamp and filestamp are taken from the\n\t\t * certificate value structure. For all certificates the\n\t\t * timestamp is the latest signature update time. For\n\t\t * host and imported certificates the filestamp is the\n\t\t * creation epoch. For signed certificates the filestamp\n\t\t * is the creation epoch of the trusted certificate at\n\t\t * the root of the certificate trail. In principle, this\n\t\t * allows strong checking for signature masquerade.\n\t\t */\n\t\tif (xp == NULL)\n\t\t\txp = yp;\n\t\tif (xp == NULL)\n\t\t\tbreak;\n\n\t\tif (tstamp == 0)\n\t\t\tbreak;\n\n\t\tlen = crypto_send(fp, &xp->cert, start);\n\t\tbreak;\n\n\t/*\n\t * Send challenge in Schnorr (IFF) identity scheme.\n\t */\n\tcase CRYPTO_IFF:\n\t\tif (peer == NULL)\n\t\t\tbreak;\t\t/* hack attack */\n\n\t\tif ((rval = crypto_alice(peer, &vtemp)) == XEVNT_OK) {\n\t\t\tlen = crypto_send(fp, &vtemp, start);\n\t\t\tvalue_free(&vtemp);\n\t\t}\n\t\tbreak;\n\n\t/*\n\t * Send response in Schnorr (IFF) identity scheme.\n\t */\n\tcase CRYPTO_IFF | CRYPTO_RESP:\n\t\tif ((rval = crypto_bob(ep, &vtemp)) == XEVNT_OK) {\n\t\t\tlen = crypto_send(fp, &vtemp, start);\n\t\t\tvalue_free(&vtemp);\n\t\t}\n\t\tbreak;\n\n\t/*\n\t * Send challenge in Guillou-Quisquater (GQ) identity scheme.\n\t */\n\tcase CRYPTO_GQ:\n\t\tif (peer == NULL)\n\t\t\tbreak;\t\t/* hack attack */\n\n\t\tif ((rval = crypto_alice2(peer, &vtemp)) == XEVNT_OK) {\n\t\t\tlen = crypto_send(fp, &vtemp, start);\n\t\t\tvalue_free(&vtemp);\n\t\t}\n\t\tbreak;\n\n\t/*\n\t * Send response in Guillou-Quisquater (GQ) identity scheme.\n\t */\n\tcase CRYPTO_GQ | CRYPTO_RESP:\n\t\tif ((rval = crypto_bob2(ep, &vtemp)) == XEVNT_OK) {\n\t\t\tlen = crypto_send(fp, &vtemp, start);\n\t\t\tvalue_free(&vtemp);\n\t\t}\n\t\tbreak;\n\n\t/*\n\t * Send challenge in MV identity scheme.\n\t */\n\tcase CRYPTO_MV:\n\t\tif (peer == NULL)\n\t\t\tbreak;\t\t/* hack attack */\n\n\t\tif ((rval = crypto_alice3(peer, &vtemp)) == XEVNT_OK) {\n\t\t\tlen = crypto_send(fp, &vtemp, start);\n\t\t\tvalue_free(&vtemp);\n\t\t}\n\t\tbreak;\n\n\t/*\n\t * Send response in MV identity scheme.\n\t */\n\tcase CRYPTO_MV | CRYPTO_RESP:\n\t\tif ((rval = crypto_bob3(ep, &vtemp)) == XEVNT_OK) {\n\t\t\tlen = crypto_send(fp, &vtemp, start);\n\t\t\tvalue_free(&vtemp);\n\t\t}\n\t\tbreak;\n\n\t/*\n\t * Send certificate sign response. The integrity of the request\n\t * certificate has already been verified on the receive side.\n\t * Sign the response using the local server key. Use the\n\t * filestamp from the request and use the timestamp as the\n\t * current time. Light the error bit if the certificate is\n\t * invalid or contains an unverified signature.\n\t */\n\tcase CRYPTO_SIGN | CRYPTO_RESP:\n\t\tif ((rval = cert_sign(ep, &vtemp)) == XEVNT_OK) {\n\t\t\tlen = crypto_send(fp, &vtemp, start);\n\t\t\tvalue_free(&vtemp);\n\t\t}\n\t\tbreak;\n\n\t/*\n\t * Send public key and signature. Use the values from the public\n\t * key.\n\t */\n\tcase CRYPTO_COOK:\n\t\tlen = crypto_send(fp, &pubkey, start);\n\t\tbreak;\n\n\t/*\n\t * Encrypt and send cookie and signature. Light the error bit if\n\t * anything goes wrong.\n\t */\n\tcase CRYPTO_COOK | CRYPTO_RESP:\n\t\tvallen = ntohl(ep->vallen);\t/* Must be <64k */\n\t\tif ( vallen == 0\n\t\t || (vallen >= MAX_VALLEN)\n\t\t || (opcode & 0x0000ffff) < VALUE_LEN + vallen) {\n\t\t\trval = XEVNT_LEN;\n\t\t\tbreak;\n\t\t}\n\t\tif (peer == NULL)\n\t\t\ttcookie = cookie;\n\t\telse\n\t\t\ttcookie = peer->hcookie;\n\t\tif ((rval = crypto_encrypt((const u_char *)ep->pkt, vallen, &tcookie, &vtemp))\n\t\t == XEVNT_OK) {\n\t\t\tlen = crypto_send(fp, &vtemp, start);\n\t\t\tvalue_free(&vtemp);\n\t\t}\n\t\tbreak;\n\n\t/*\n\t * Find peer and send autokey data and signature in broadcast\n\t * server and symmetric modes. Use the values in the autokey\n\t * structure. If no association is found, either the server has\n\t * restarted with new associations or some perp has replayed an\n\t * old message, in which case light the error bit.\n\t */\n\tcase CRYPTO_AUTO | CRYPTO_RESP:\n\t\tif (peer == NULL) {\n\t\t\tif ((peer = findpeerbyassoc(associd)) == NULL) {\n\t\t\t\trval = XEVNT_ERR;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tpeer->flags &= ~FLAG_ASSOC;\n\t\tlen = crypto_send(fp, &peer->sndval, start);\n\t\tbreak;\n\n\t/*\n\t * Send leapseconds values and signature. Use the values from\n\t * the tai structure. If no table has been loaded, just send an\n\t * empty request.\n\t */\n\tcase CRYPTO_LEAP | CRYPTO_RESP:\n\t\tlen = crypto_send(fp, &tai_leap, start);\n\t\tbreak;\n\n\t/*\n\t * Default - Send a valid command for unknown requests; send\n\t * an error response for unknown resonses.\n\t */\n\tdefault:\n\t\tif (opcode & CRYPTO_RESP)\n\t\t\trval = XEVNT_ERR;\n\t}\n\n\t/*\n\t * In case of error, flame the log. If a request, toss the\n\t * puppy; if a response, return so the sender can flame, too.\n\t */\n\tif (rval != XEVNT_OK) {\n\t\tu_int32\tuint32;\n\n\t\tuint32 = CRYPTO_ERROR;\n\t\topcode |= uint32;\n\t\tfp->opcode |= htonl(uint32);\n\t\tsnprintf(statstr, sizeof(statstr),\n\t\t \"%04x %d %02x %s\", opcode, associd, rval,\n\t\t eventstr(rval));\n\t\trecord_crypto_stats(srcadr_sin, statstr);\n\t\tDPRINTF(1, (\"crypto_xmit: %s\\n\", statstr));\n\t\tif (!(opcode & CRYPTO_RESP))\n\t\t\treturn (0);\n\t}\n\tDPRINTF(1, (\"crypto_xmit: flags 0x%x offset %d len %d code 0x%x associd %d\\n\",\n\t\t crypto_flags, start, len, opcode >> 16, associd));\n\treturn (len);\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: cookedprint(\n\tint datatype,\n\tint length,\n\tconst char *data,\n\tint status,\n\tint quiet,\n\tFILE *fp\n\t)\n{\n\tchar *name;\n\tchar *value;\n\tchar output_raw;\n\tint fmt;\n\tl_fp lfp;\n\tsockaddr_u hval;\n\tu_long uval;\n\tint narr;\n\tsize_t len;\n\tl_fp lfparr[8];\n\tchar b[12];\n\tchar bn[2 * MAXVARLEN];\n\tchar bv[2 * MAXVALLEN];\n\n\tUNUSED_ARG(datatype);\n\n\tif (!quiet)\n\t\tfprintf(fp, \"status=%04x %s,\\n\", status,\n\t\t\tstatustoa(datatype, status));\n\n\tstartoutput();\n\twhile (nextvar(&length, &data, &name, &value)) {\n\t\tfmt = varfmt(name);\n\t\toutput_raw = 0;\n\t\tswitch (fmt) {\n\n\t\tcase PADDING:\n\t\t\toutput_raw = '*';\n\t\t\tbreak;\n\n\t\tcase TS:\n\t\t\tif (!decodets(value, &lfp))\n\t\t\t\toutput_raw = '?';\n\t\t\telse\n\t\t\t\toutput(fp, name, prettydate(&lfp));\n\t\t\tbreak;\n\n\t\tcase HA:\t/* fallthru */\n\t\tcase NA:\n\t\t\tif (!decodenetnum(value, &hval)) {\n\t\t\t\toutput_raw = '?';\n\t\t\t} else if (fmt == HA){\n\t\t\t\toutput(fp, name, nntohost(&hval));\n\t\t\t} else {\n\t\t\t\toutput(fp, name, stoa(&hval));\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase RF:\n\t\t\tif (decodenetnum(value, &hval)) {\n\t\t\t\tif (ISREFCLOCKADR(&hval))\n\t\t\t\t\toutput(fp, name,\n\t\t\t\t\t refnumtoa(&hval));\n\t\t\t\telse\n\t\t\t\t\toutput(fp, name, stoa(&hval));\n\t\t\t} else if (strlen(value) <= 4) {\n\t\t\t\toutput(fp, name, value);\n\t\t\t} else {\n\t\t\t\toutput_raw = '?';\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase LP:\n\t\t\tif (!decodeuint(value, &uval) || uval > 3) {\n\t\t\t\toutput_raw = '?';\n\t\t\t} else {\n\t\t\t\tb[0] = (0x2 & uval)\n\t\t\t\t\t ? '1'\n\t\t\t\t\t : '0';\n\t\t\t\tb[1] = (0x1 & uval)\n\t\t\t\t\t ? '1'\n\t\t\t\t\t : '0';\n\t\t\t\tb[2] = '\\0';\n\t\t\t\toutput(fp, name, b);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase OC:\n\t\t\tif (!decodeuint(value, &uval)) {\n\t\t\t\toutput_raw = '?';\n\t\t\t} else {\n\t\t\t\tsnprintf(b, sizeof(b), \"%03lo\", uval);\n\t\t\t\toutput(fp, name, b);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase AR:\n\t\t\tif (!decodearr(value, &narr, lfparr))\n\t\t\t\toutput_raw = '?';\n\t\t\telse\n\t\t\t\toutputarr(fp, name, narr, lfparr);\n\t\t\tbreak;\n\n\t\tcase FX:\n\t\t\tif (!decodeuint(value, &uval))\n\t\t\t\toutput_raw = '?';\n\t\t\telse\n\t\t\t\toutput(fp, name, tstflags(uval));\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tfprintf(stderr, \"Internal error in cookedprint, %s=%s, fmt %d\\n\",\n\t\t\t\tname, value, fmt);\n\t\t\toutput_raw = '?';\n\t\t\tbreak;\n\t\t}\n\n\t\tif (output_raw != 0) {\n\t\t\tatoascii(name, MAXVARLEN, bn, sizeof(bn));\n\t\t\tatoascii(value, MAXVALLEN, bv, sizeof(bv));\n\t\t\tif (output_raw != '*') {\n\t\t\t\tlen = strlen(bv);\n\t\t\t\tbv[len] = output_raw;\n\t\t\t\tbv[len+1] = '\\0';\n\t\t\t}\n\t\t\toutput(fp, bn, bv);\n\t\t}\n\t}\n\tendoutput(fp);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': '[TALOS-CAN-0063] avoid buffer overrun in ntpq'" }, { "text": "[INST] Given the following code containing errors, provide Common 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_init_sec_context(OM_uint32 *minor_status,\n gss_cred_id_t claimant_cred_handle,\n gss_ctx_id_t *context_handle,\n gss_name_t target_name,\n gss_OID mech_type,\n OM_uint32 req_flags,\n OM_uint32 time_req,\n gss_channel_bindings_t input_chan_bindings,\n gss_buffer_t input_token,\n gss_OID *actual_mech_type,\n gss_buffer_t output_token,\n OM_uint32 *ret_flags,\n OM_uint32 *time_rec)\n{\n OM_uint32 major_status = GSS_S_FAILURE;\n krb5_error_code code;\n iakerb_ctx_id_t ctx;\n krb5_gss_cred_id_t kcred;\n krb5_gss_name_t kname;\n krb5_boolean cred_locked = FALSE;\n int initialContextToken = (*context_handle == GSS_C_NO_CONTEXT);\n\n if (initialContextToken) {\n code = iakerb_alloc_context(&ctx);\n if (code != 0) {\n *minor_status = code;\n goto cleanup;\n }\n if (claimant_cred_handle == GSS_C_NO_CREDENTIAL) {\n major_status = iakerb_gss_acquire_cred(minor_status, NULL,\n GSS_C_INDEFINITE,\n GSS_C_NULL_OID_SET,\n GSS_C_INITIATE,\n &ctx->defcred, NULL, NULL);\n if (GSS_ERROR(major_status))\n goto cleanup;\n claimant_cred_handle = ctx->defcred;\n }\n } else {\n ctx = (iakerb_ctx_id_t)*context_handle;\n if (claimant_cred_handle == GSS_C_NO_CREDENTIAL)\n claimant_cred_handle = ctx->defcred;\n }\n\n kname = (krb5_gss_name_t)target_name;\n\n major_status = kg_cred_resolve(minor_status, ctx->k5c,\n claimant_cred_handle, target_name);\n if (GSS_ERROR(major_status))\n goto cleanup;\n cred_locked = TRUE;\n kcred = (krb5_gss_cred_id_t)claimant_cred_handle;\n\n major_status = GSS_S_FAILURE;\n\n if (initialContextToken) {\n code = iakerb_get_initial_state(ctx, kcred, kname, time_req,\n &ctx->state);\n if (code != 0) {\n *minor_status = code;\n goto cleanup;\n }\n *context_handle = (gss_ctx_id_t)ctx;\n }\n\n if (ctx->state != IAKERB_AP_REQ) {\n /* We need to do IAKERB. */\n code = iakerb_initiator_step(ctx,\n kcred,\n kname,\n time_req,\n input_token,\n output_token);\n if (code == KRB5_BAD_MSIZE)\n major_status = GSS_S_DEFECTIVE_TOKEN;\n if (code != 0) {\n *minor_status = code;\n goto cleanup;\n }\n }\n\n if (ctx->state == IAKERB_AP_REQ) {\n krb5_gss_ctx_ext_rec exts;\n\n if (cred_locked) {\n k5_mutex_unlock(&kcred->lock);\n cred_locked = FALSE;\n }\n\n iakerb_make_exts(ctx, &exts);\n\n if (ctx->gssc == GSS_C_NO_CONTEXT)\n input_token = GSS_C_NO_BUFFER;\n\n /* IAKERB is finished, or we skipped to Kerberos directly. */\n major_status = krb5_gss_init_sec_context_ext(minor_status,\n (gss_cred_id_t) kcred,\n &ctx->gssc,\n target_name,\n (gss_OID)gss_mech_iakerb,\n req_flags,\n time_req,\n input_chan_bindings,\n input_token,\n NULL,\n output_token,\n ret_flags,\n time_rec,\n &exts);\n if (major_status == GSS_S_COMPLETE) {\n *context_handle = ctx->gssc;\n ctx->gssc = GSS_C_NO_CONTEXT;\n iakerb_release_context(ctx);\n }\n if (actual_mech_type != NULL)\n *actual_mech_type = (gss_OID)gss_mech_krb5;\n } else {\n if (actual_mech_type != NULL)\n *actual_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 major_status = GSS_S_CONTINUE_NEEDED;\n }\n\ncleanup:\n if (cred_locked)\n k5_mutex_unlock(&kcred->lock);\n if (initialContextToken && GSS_ERROR(major_status)) {\n iakerb_release_context(ctx);\n *context_handle = GSS_C_NO_CONTEXT;\n }\n\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: acc_ctx_hints(OM_uint32 *minor_status,\n\t gss_ctx_id_t *ctx,\n\t spnego_gss_cred_id_t spcred,\n\t gss_buffer_t *mechListMIC,\n\t OM_uint32 *negState,\n\t send_token_flag *return_token)\n{\n\tOM_uint32 tmpmin, ret;\n\tgss_OID_set supported_mechSet;\n\tspnego_gss_ctx_id_t sc = NULL;\n\n\t*mechListMIC = GSS_C_NO_BUFFER;\n\tsupported_mechSet = GSS_C_NO_OID_SET;\n\t*return_token = NO_TOKEN_SEND;\n\t*negState = REJECT;\n\t*minor_status = 0;\n\n\t/* A hint request must be the first token received. */\n\tif (*ctx != GSS_C_NO_CONTEXT)\n\t return GSS_S_DEFECTIVE_TOKEN;\n\n\tret = get_negotiable_mechs(minor_status, spcred, GSS_C_ACCEPT,\n\t\t\t\t &supported_mechSet);\n\tif (ret != GSS_S_COMPLETE)\n\t\tgoto cleanup;\n\n\tret = make_NegHints(minor_status, mechListMIC);\n\tif (ret != GSS_S_COMPLETE)\n\t\tgoto cleanup;\n\n\tsc = create_spnego_ctx();\n\tif (sc == NULL) {\n\t\tret = GSS_S_FAILURE;\n\t\tgoto cleanup;\n\t}\n\tif (put_mech_set(supported_mechSet, &sc->DER_mechTypes) < 0) {\n\t\tret = GSS_S_FAILURE;\n\t\tgoto cleanup;\n\t}\n\tsc->internal_mech = GSS_C_NO_OID;\n\n\t*negState = ACCEPT_INCOMPLETE;\n\t*return_token = INIT_TOKEN_SEND;\n\tsc->firstpass = 1;\n\t*ctx = (gss_ctx_id_t)sc;\n\tsc = NULL;\n\tret = GSS_S_COMPLETE;\n\ncleanup:\n\trelease_spnego_ctx(&sc);\n\tgss_release_oid_set(&tmpmin, &supported_mechSet);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695]\n\nThe SPNEGO mechanism currently replaces its context handle with the\nmechanism context handle upon establishment, under the assumption that\nmost GSS functions are only called after context establishment. This\nassumption is incorrect, and can lead to aliasing violations for some\nprograms. Maintain the SPNEGO context structure after context\nestablishment and refer to it in all GSS methods. Add initiate and\nopened flags to the SPNEGO context structure for use in\ngss_inquire_context() prior to context establishment.\n\nCVE-2015-2695:\n\nIn MIT krb5 1.5 and later, applications which call\ngss_inquire_context() on a partially-established SPNEGO context can\ncause the GSS-API library to read from a pointer using the wrong type,\ngenerally causing a process crash. This bug may go unnoticed, because\nthe most common SPNEGO authentication scenario establishes the context\nafter just one call to gss_accept_sec_context(). Java server\napplications using the native JGSS provider are vulnerable to this\nbug. A carefully crafted SPNEGO packet might allow the\ngss_inquire_context() call to succeed with attacker-determined\nresults, but applications should not make access control decisions\nbased on gss_inquire_context() results prior to context establishment.\n\n CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C\n\n[ghudson@mit.edu: several bugfixes, style changes, and edge-case\nbehavior changes; commit message and CVE description]\n\nticket: 8244\ntarget_version: 1.14\ntags: pullup'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: spnego_gss_wrap_iov(OM_uint32 *minor_status,\n\t\t gss_ctx_id_t context_handle,\n\t\t int conf_req_flag,\n\t\t gss_qop_t qop_req,\n\t\t int *conf_state,\n\t\t gss_iov_buffer_desc *iov,\n\t\t int iov_count)\n{\n\tOM_uint32 ret;\n\tret = gss_wrap_iov(minor_status,\n\t\t\t context_handle,\n\t\t\t conf_req_flag,\n\t\t\t qop_req,\n\t\t\t conf_state,\n\t\t\t iov,\n\t\t\t iov_count);\n\treturn (ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695]\n\nThe SPNEGO mechanism currently replaces its context handle with the\nmechanism context handle upon establishment, under the assumption that\nmost GSS functions are only called after context establishment. This\nassumption is incorrect, and can lead to aliasing violations for some\nprograms. Maintain the SPNEGO context structure after context\nestablishment and refer to it in all GSS methods. Add initiate and\nopened flags to the SPNEGO context structure for use in\ngss_inquire_context() prior to context establishment.\n\nCVE-2015-2695:\n\nIn MIT krb5 1.5 and later, applications which call\ngss_inquire_context() on a partially-established SPNEGO context can\ncause the GSS-API library to read from a pointer using the wrong type,\ngenerally causing a process crash. This bug may go unnoticed, because\nthe most common SPNEGO authentication scenario establishes the context\nafter just one call to gss_accept_sec_context(). Java server\napplications using the native JGSS provider are vulnerable to this\nbug. A carefully crafted SPNEGO packet might allow the\ngss_inquire_context() call to succeed with attacker-determined\nresults, but applications should not make access control decisions\nbased on gss_inquire_context() results prior to context establishment.\n\n CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C\n\n[ghudson@mit.edu: several bugfixes, style changes, and edge-case\nbehavior changes; commit message and CVE description]\n\nticket: 8244\ntarget_version: 1.14\ntags: pullup'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: spnego_gss_unwrap(\n\t\tOM_uint32 *minor_status,\n\t\tgss_ctx_id_t context_handle,\n\t\tgss_buffer_t input_message_buffer,\n\t\tgss_buffer_t output_message_buffer,\n\t\tint *conf_state,\n\t\tgss_qop_t *qop_state)\n{\n\tOM_uint32 ret;\n\tret = gss_unwrap(minor_status,\n\t\t\tcontext_handle,\n\t\t\tinput_message_buffer,\n\t\t\toutput_message_buffer,\n\t\t\tconf_state,\n\t\t\tqop_state);\n\n\treturn (ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695]\n\nThe SPNEGO mechanism currently replaces its context handle with the\nmechanism context handle upon establishment, under the assumption that\nmost GSS functions are only called after context establishment. This\nassumption is incorrect, and can lead to aliasing violations for some\nprograms. Maintain the SPNEGO context structure after context\nestablishment and refer to it in all GSS methods. Add initiate and\nopened flags to the SPNEGO context structure for use in\ngss_inquire_context() prior to context establishment.\n\nCVE-2015-2695:\n\nIn MIT krb5 1.5 and later, applications which call\ngss_inquire_context() on a partially-established SPNEGO context can\ncause the GSS-API library to read from a pointer using the wrong type,\ngenerally causing a process crash. This bug may go unnoticed, because\nthe most common SPNEGO authentication scenario establishes the context\nafter just one call to gss_accept_sec_context(). Java server\napplications using the native JGSS provider are vulnerable to this\nbug. A carefully crafted SPNEGO packet might allow the\ngss_inquire_context() call to succeed with attacker-determined\nresults, but applications should not make access control decisions\nbased on gss_inquire_context() results prior to context establishment.\n\n CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C\n\n[ghudson@mit.edu: several bugfixes, style changes, and edge-case\nbehavior changes; commit message and CVE description]\n\nticket: 8244\ntarget_version: 1.14\ntags: pullup'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xmlStringLenDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int len,\n\t\t int what, xmlChar end, xmlChar end2, xmlChar end3) {\n xmlChar *buffer = NULL;\n size_t buffer_size = 0;\n size_t nbchars = 0;\n\n xmlChar *current = NULL;\n xmlChar *rep = NULL;\n const xmlChar *last;\n xmlEntityPtr ent;\n int c,l;\n\n if ((ctxt == NULL) || (str == NULL) || (len < 0))\n\treturn(NULL);\n last = str + len;\n\n if (((ctxt->depth > 40) &&\n ((ctxt->options & XML_PARSE_HUGE) == 0)) ||\n\t(ctxt->depth > 1024)) {\n\txmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);\n\treturn(NULL);\n }\n\n /*\n * allocate a translation buffer.\n */\n buffer_size = XML_PARSER_BIG_BUFFER_SIZE;\n buffer = (xmlChar *) xmlMallocAtomic(buffer_size);\n if (buffer == NULL) goto mem_error;\n\n /*\n * OK loop until we reach one of the ending char or a size limit.\n * we are operating on already parsed values.\n */\n if (str < last)\n\tc = CUR_SCHAR(str, l);\n else\n c = 0;\n while ((c != 0) && (c != end) && /* non input consuming loop */\n\t (c != end2) && (c != end3)) {\n\n\tif (c == 0) break;\n if ((c == '&') && (str[1] == '#')) {\n\t int val = xmlParseStringCharRef(ctxt, &str);\n\t if (val != 0) {\n\t\tCOPY_BUF(0,buffer,nbchars,val);\n\t }\n\t if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {\n\t growBuffer(buffer, XML_PARSER_BUFFER_SIZE);\n\t }\n\t} else if ((c == '&') && (what & XML_SUBSTITUTE_REF)) {\n\t if (xmlParserDebugEntities)\n\t\txmlGenericError(xmlGenericErrorContext,\n\t\t\t\"String decoding Entity Reference: %.30s\\n\",\n\t\t\tstr);\n\t ent = xmlParseStringEntityRef(ctxt, &str);\n\t if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) ||\n\t (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR))\n\t goto int_error;\n\t xmlParserEntityCheck(ctxt, 0, ent, 0);\n\t if (ent != NULL)\n\t ctxt->nbentities += ent->checked / 2;\n\t if ((ent != NULL) &&\n\t\t(ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) {\n\t\tif (ent->content != NULL) {\n\t\t COPY_BUF(0,buffer,nbchars,ent->content[0]);\n\t\t if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {\n\t\t\tgrowBuffer(buffer, XML_PARSER_BUFFER_SIZE);\n\t\t }\n\t\t} else {\n\t\t xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR,\n\t\t\t \"predefined entity has no content\\n\");\n\t\t}\n\t } else if ((ent != NULL) && (ent->content != NULL)) {\n\t\tctxt->depth++;\n\t\trep = xmlStringDecodeEntities(ctxt, ent->content, what,\n\t\t\t 0, 0, 0);\n\t\tctxt->depth--;\n\n\t\tif (rep != NULL) {\n\t\t current = rep;\n\t\t while (*current != 0) { /* non input consuming loop */\n\t\t\tbuffer[nbchars++] = *current++;\n\t\t\tif (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {\n\t\t\t if (xmlParserEntityCheck(ctxt, nbchars, ent, 0))\n\t\t\t\tgoto int_error;\n\t\t\t growBuffer(buffer, XML_PARSER_BUFFER_SIZE);\n\t\t\t}\n\t\t }\n\t\t xmlFree(rep);\n\t\t rep = NULL;\n\t\t}\n\t } else if (ent != NULL) {\n\t\tint i = xmlStrlen(ent->name);\n\t\tconst xmlChar *cur = ent->name;\n\n\t\tbuffer[nbchars++] = '&';\n\t\tif (nbchars + i + XML_PARSER_BUFFER_SIZE > buffer_size) {\n\t\t growBuffer(buffer, i + XML_PARSER_BUFFER_SIZE);\n\t\t}\n\t\tfor (;i > 0;i--)\n\t\t buffer[nbchars++] = *cur++;\n\t\tbuffer[nbchars++] = ';';\n\t }\n\t} else if (c == '%' && (what & XML_SUBSTITUTE_PEREF)) {\n\t if (xmlParserDebugEntities)\n\t\txmlGenericError(xmlGenericErrorContext,\n\t\t\t\"String decoding PE Reference: %.30s\\n\", str);\n\t ent = xmlParseStringPEReference(ctxt, &str);\n\t if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP)\n\t goto int_error;\n\t xmlParserEntityCheck(ctxt, 0, ent, 0);\n\t if (ent != NULL)\n\t ctxt->nbentities += ent->checked / 2;\n\t if (ent != NULL) {\n if (ent->content == NULL) {\n\t\t xmlLoadEntityContent(ctxt, ent);\n\t\t}\n\t\tctxt->depth++;\n\t\trep = xmlStringDecodeEntities(ctxt, ent->content, what,\n\t\t\t 0, 0, 0);\n\t\tctxt->depth--;\n\t\tif (rep != NULL) {\n\t\t current = rep;\n\t\t while (*current != 0) { /* non input consuming loop */\n\t\t\tbuffer[nbchars++] = *current++;\n\t\t\tif (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {\n\t\t\t if (xmlParserEntityCheck(ctxt, nbchars, ent, 0))\n\t\t\t goto int_error;\n\t\t\t growBuffer(buffer, XML_PARSER_BUFFER_SIZE);\n\t\t\t}\n\t\t }\n\t\t xmlFree(rep);\n\t\t rep = NULL;\n\t\t}\n\t }\n\t} else {\n\t COPY_BUF(l,buffer,nbchars,c);\n\t str += l;\n\t if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {\n\t growBuffer(buffer, XML_PARSER_BUFFER_SIZE);\n\t }\n\t}\n\tif (str < last)\n\t c = CUR_SCHAR(str, l);\n\telse\n\t c = 0;\n }\n buffer[nbchars] = 0;\n return(buffer);\n\nmem_error:\n xmlErrMemory(ctxt, NULL);\nint_error:\n if (rep != NULL)\n xmlFree(rep);\n if (buffer != NULL)\n xmlFree(buffer);\n return(NULL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-5312 Another entity expansion issue\n\nFor https://bugzilla.gnome.org/show_bug.cgi?id=756733\nIt is one case where the code in place to detect entities expansions\nfailed to exit when the situation was detected, leading to DoS\nProblem reported by Kostya Serebryany @ Google\nPatch provided by David Drysdale @ 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: _PUBLIC_ codepoint_t next_codepoint_handle(struct smb_iconv_handle *ic,\n\t\t\t\t const char *str, size_t *size)\n{\n\treturn next_codepoint_handle_ext(ic, str, CH_UNIX, size);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2015-5330: Fix handling of unicode near string endings\n\nUntil now next_codepoint_ext() and next_codepoint_handle_ext() were\nusing strnlen(str, 5) to determine how much string they should try to\ndecode. This ended up looking past the end of the string when it was not\nnull terminated and the final character looked like a multi-byte encoding.\nThe fix is to let the caller say how long the string can be.\n\nBug: https://bugzilla.samba.org/show_bug.cgi?id=11599\n\nSigned-off-by: Douglas Bagnall \nPair-programmed-with: Andrew Bartlett \nReviewed-by: Ralph Boehme '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: png_set_PLTE(png_structrp png_ptr, png_inforp info_ptr,\n png_const_colorp palette, int num_palette)\n{\n\n png_uint_32 max_palette_length;\n\n png_debug1(1, \"in %s storage function\", \"PLTE\");\n\n if (png_ptr == NULL || info_ptr == NULL)\n return;\n\n max_palette_length = (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ?\n (1 << png_ptr->bit_depth) : PNG_MAX_PALETTE_LENGTH;\n\n if (num_palette < 0 || num_palette > max_palette_length)\n {\n if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)\n png_error(png_ptr, \"Invalid palette length\");\n\n else\n {\n png_warning(png_ptr, \"Invalid palette length\");\n\n return;\n }\n }\n\n if ((num_palette > 0 && palette == NULL) ||\n (num_palette == 0\n# ifdef PNG_MNG_FEATURES_SUPPORTED\n && (png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) == 0\n# endif\n ))\n {\n png_error(png_ptr, \"Invalid palette\");\n }\n\n /* It may not actually be necessary to set png_ptr->palette here;\n * we do it for backward compatibility with the way the png_handle_tRNS\n * function used to do the allocation.\n *\n * 1.6.0: the above statement appears to be incorrect; something has to set\n * the palette inside png_struct on read.\n */\n png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);\n\n /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead\n * of num_palette entries, in case of an invalid PNG file or incorrect\n * call to png_set_PLTE() with too-large sample values.\n */\n png_ptr->palette = png_voidcast(png_colorp, png_calloc(png_ptr,\n PNG_MAX_PALETTE_LENGTH * (sizeof (png_color))));\n\n if (num_palette > 0)\n memcpy(png_ptr->palette, palette, num_palette * (sizeof (png_color)));\n info_ptr->palette = png_ptr->palette;\n info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;\n\n info_ptr->free_me |= PNG_FREE_PLTE;\n\n info_ptr->valid |= PNG_INFO_PLTE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': '[libpng16] 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\txmlFree((xmlChar *) encoding);\n\t\treturn(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\txmlFree((xmlChar *) encoding);\n\t\treturn(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': 'Fail parsing early on if encoding conversion failed\n\nFor https://bugzilla.gnome.org/show_bug.cgi?id=751631\n\nIf we fail conversing the current input stream while\nprocessing the encoding declaration of the XMLDecl\nthen it's safer to just abort there and not try to\nreport further errors.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,\n\t\t\t struct btrfs_root *root,\n\t\t\t struct inode *inode,\n\t\t\t u64 new_size, u32 min_type)\n{\n\tstruct btrfs_path *path;\n\tstruct extent_buffer *leaf;\n\tstruct btrfs_file_extent_item *fi;\n\tstruct btrfs_key key;\n\tstruct btrfs_key found_key;\n\tu64 extent_start = 0;\n\tu64 extent_num_bytes = 0;\n\tu64 extent_offset = 0;\n\tu64 item_end = 0;\n\tu64 last_size = new_size;\n\tu32 found_type = (u8)-1;\n\tint found_extent;\n\tint del_item;\n\tint pending_del_nr = 0;\n\tint pending_del_slot = 0;\n\tint extent_type = -1;\n\tint ret;\n\tint err = 0;\n\tu64 ino = btrfs_ino(inode);\n\tu64 bytes_deleted = 0;\n\tbool be_nice = 0;\n\tbool should_throttle = 0;\n\tbool should_end = 0;\n\n\tBUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);\n\n\t/*\n\t * for non-free space inodes and ref cows, we want to back off from\n\t * time to time\n\t */\n\tif (!btrfs_is_free_space_inode(inode) &&\n\t test_bit(BTRFS_ROOT_REF_COWS, &root->state))\n\t\tbe_nice = 1;\n\n\tpath = btrfs_alloc_path();\n\tif (!path)\n\t\treturn -ENOMEM;\n\tpath->reada = -1;\n\n\t/*\n\t * We want to drop from the next block forward in case this new size is\n\t * not block aligned since we will be keeping the last block of the\n\t * extent just the way it is.\n\t */\n\tif (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||\n\t root == root->fs_info->tree_root)\n\t\tbtrfs_drop_extent_cache(inode, ALIGN(new_size,\n\t\t\t\t\troot->sectorsize), (u64)-1, 0);\n\n\t/*\n\t * This function is also used to drop the items in the log tree before\n\t * we relog the inode, so if root != BTRFS_I(inode)->root, it means\n\t * it is used to drop the loged items. So we shouldn't kill the delayed\n\t * items.\n\t */\n\tif (min_type == 0 && root == BTRFS_I(inode)->root)\n\t\tbtrfs_kill_delayed_inode_items(inode);\n\n\tkey.objectid = ino;\n\tkey.offset = (u64)-1;\n\tkey.type = (u8)-1;\n\nsearch_again:\n\t/*\n\t * with a 16K leaf size and 128MB extents, you can actually queue\n\t * up a huge file in a single leaf. Most of the time that\n\t * bytes_deleted is > 0, it will be huge by the time we get here\n\t */\n\tif (be_nice && bytes_deleted > 32 * 1024 * 1024) {\n\t\tif (btrfs_should_end_transaction(trans, root)) {\n\t\t\terr = -EAGAIN;\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\n\tpath->leave_spinning = 1;\n\tret = btrfs_search_slot(trans, root, &key, path, -1, 1);\n\tif (ret < 0) {\n\t\terr = ret;\n\t\tgoto out;\n\t}\n\n\tif (ret > 0) {\n\t\t/* there are no items in the tree for us to truncate, we're\n\t\t * done\n\t\t */\n\t\tif (path->slots[0] == 0)\n\t\t\tgoto out;\n\t\tpath->slots[0]--;\n\t}\n\n\twhile (1) {\n\t\tfi = NULL;\n\t\tleaf = path->nodes[0];\n\t\tbtrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);\n\t\tfound_type = found_key.type;\n\n\t\tif (found_key.objectid != ino)\n\t\t\tbreak;\n\n\t\tif (found_type < min_type)\n\t\t\tbreak;\n\n\t\titem_end = found_key.offset;\n\t\tif (found_type == BTRFS_EXTENT_DATA_KEY) {\n\t\t\tfi = btrfs_item_ptr(leaf, path->slots[0],\n\t\t\t\t\t struct btrfs_file_extent_item);\n\t\t\textent_type = btrfs_file_extent_type(leaf, fi);\n\t\t\tif (extent_type != BTRFS_FILE_EXTENT_INLINE) {\n\t\t\t\titem_end +=\n\t\t\t\t btrfs_file_extent_num_bytes(leaf, fi);\n\t\t\t} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {\n\t\t\t\titem_end += btrfs_file_extent_inline_len(leaf,\n\t\t\t\t\t\t\t path->slots[0], fi);\n\t\t\t}\n\t\t\titem_end--;\n\t\t}\n\t\tif (found_type > min_type) {\n\t\t\tdel_item = 1;\n\t\t} else {\n\t\t\tif (item_end < new_size)\n\t\t\t\tbreak;\n\t\t\tif (found_key.offset >= new_size)\n\t\t\t\tdel_item = 1;\n\t\t\telse\n\t\t\t\tdel_item = 0;\n\t\t}\n\t\tfound_extent = 0;\n\t\t/* FIXME, shrink the extent if the ref count is only 1 */\n\t\tif (found_type != BTRFS_EXTENT_DATA_KEY)\n\t\t\tgoto delete;\n\n\t\tif (del_item)\n\t\t\tlast_size = found_key.offset;\n\t\telse\n\t\t\tlast_size = new_size;\n\n\t\tif (extent_type != BTRFS_FILE_EXTENT_INLINE) {\n\t\t\tu64 num_dec;\n\t\t\textent_start = btrfs_file_extent_disk_bytenr(leaf, fi);\n\t\t\tif (!del_item) {\n\t\t\t\tu64 orig_num_bytes =\n\t\t\t\t\tbtrfs_file_extent_num_bytes(leaf, fi);\n\t\t\t\textent_num_bytes = ALIGN(new_size -\n\t\t\t\t\t\tfound_key.offset,\n\t\t\t\t\t\troot->sectorsize);\n\t\t\t\tbtrfs_set_file_extent_num_bytes(leaf, fi,\n\t\t\t\t\t\t\t extent_num_bytes);\n\t\t\t\tnum_dec = (orig_num_bytes -\n\t\t\t\t\t extent_num_bytes);\n\t\t\t\tif (test_bit(BTRFS_ROOT_REF_COWS,\n\t\t\t\t\t &root->state) &&\n\t\t\t\t extent_start != 0)\n\t\t\t\t\tinode_sub_bytes(inode, num_dec);\n\t\t\t\tbtrfs_mark_buffer_dirty(leaf);\n\t\t\t} else {\n\t\t\t\textent_num_bytes =\n\t\t\t\t\tbtrfs_file_extent_disk_num_bytes(leaf,\n\t\t\t\t\t\t\t\t\t fi);\n\t\t\t\textent_offset = found_key.offset -\n\t\t\t\t\tbtrfs_file_extent_offset(leaf, fi);\n\n\t\t\t\t/* FIXME blocksize != 4096 */\n\t\t\t\tnum_dec = btrfs_file_extent_num_bytes(leaf, fi);\n\t\t\t\tif (extent_start != 0) {\n\t\t\t\t\tfound_extent = 1;\n\t\t\t\t\tif (test_bit(BTRFS_ROOT_REF_COWS,\n\t\t\t\t\t\t &root->state))\n\t\t\t\t\t\tinode_sub_bytes(inode, num_dec);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {\n\t\t\t/*\n\t\t\t * we can't truncate inline items that have had\n\t\t\t * special encodings\n\t\t\t */\n\t\t\tif (!del_item &&\n\t\t\t btrfs_file_extent_compression(leaf, fi) == 0 &&\n\t\t\t btrfs_file_extent_encryption(leaf, fi) == 0 &&\n\t\t\t btrfs_file_extent_other_encoding(leaf, fi) == 0) {\n\t\t\t\tu32 size = new_size - found_key.offset;\n\n\t\t\t\tif (test_bit(BTRFS_ROOT_REF_COWS, &root->state))\n\t\t\t\t\tinode_sub_bytes(inode, item_end + 1 -\n\t\t\t\t\t\t\tnew_size);\n\n\t\t\t\t/*\n\t\t\t\t * update the ram bytes to properly reflect\n\t\t\t\t * the new size of our item\n\t\t\t\t */\n\t\t\t\tbtrfs_set_file_extent_ram_bytes(leaf, fi, size);\n\t\t\t\tsize =\n\t\t\t\t btrfs_file_extent_calc_inline_size(size);\n\t\t\t\tbtrfs_truncate_item(root, path, size, 1);\n\t\t\t} else if (test_bit(BTRFS_ROOT_REF_COWS,\n\t\t\t\t\t &root->state)) {\n\t\t\t\tinode_sub_bytes(inode, item_end + 1 -\n\t\t\t\t\t\tfound_key.offset);\n\t\t\t}\n\t\t}\ndelete:\n\t\tif (del_item) {\n\t\t\tif (!pending_del_nr) {\n\t\t\t\t/* no pending yet, add ourselves */\n\t\t\t\tpending_del_slot = path->slots[0];\n\t\t\t\tpending_del_nr = 1;\n\t\t\t} else if (pending_del_nr &&\n\t\t\t\t path->slots[0] + 1 == pending_del_slot) {\n\t\t\t\t/* hop on the pending chunk */\n\t\t\t\tpending_del_nr++;\n\t\t\t\tpending_del_slot = path->slots[0];\n\t\t\t} else {\n\t\t\t\tBUG();\n\t\t\t}\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t\tshould_throttle = 0;\n\n\t\tif (found_extent &&\n\t\t (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||\n\t\t root == root->fs_info->tree_root)) {\n\t\t\tbtrfs_set_path_blocking(path);\n\t\t\tbytes_deleted += extent_num_bytes;\n\t\t\tret = btrfs_free_extent(trans, root, extent_start,\n\t\t\t\t\t\textent_num_bytes, 0,\n\t\t\t\t\t\tbtrfs_header_owner(leaf),\n\t\t\t\t\t\tino, extent_offset, 0);\n\t\t\tBUG_ON(ret);\n\t\t\tif (btrfs_should_throttle_delayed_refs(trans, root))\n\t\t\t\tbtrfs_async_run_delayed_refs(root,\n\t\t\t\t\ttrans->delayed_ref_updates * 2, 0);\n\t\t\tif (be_nice) {\n\t\t\t\tif (truncate_space_check(trans, root,\n\t\t\t\t\t\t\t extent_num_bytes)) {\n\t\t\t\t\tshould_end = 1;\n\t\t\t\t}\n\t\t\t\tif (btrfs_should_throttle_delayed_refs(trans,\n\t\t\t\t\t\t\t\t root)) {\n\t\t\t\t\tshould_throttle = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (found_type == BTRFS_INODE_ITEM_KEY)\n\t\t\tbreak;\n\n\t\tif (path->slots[0] == 0 ||\n\t\t path->slots[0] != pending_del_slot ||\n\t\t should_throttle || should_end) {\n\t\t\tif (pending_del_nr) {\n\t\t\t\tret = btrfs_del_items(trans, root, path,\n\t\t\t\t\t\tpending_del_slot,\n\t\t\t\t\t\tpending_del_nr);\n\t\t\t\tif (ret) {\n\t\t\t\t\tbtrfs_abort_transaction(trans,\n\t\t\t\t\t\t\t\troot, ret);\n\t\t\t\t\tgoto error;\n\t\t\t\t}\n\t\t\t\tpending_del_nr = 0;\n\t\t\t}\n\t\t\tbtrfs_release_path(path);\n\t\t\tif (should_throttle) {\n\t\t\t\tunsigned long updates = trans->delayed_ref_updates;\n\t\t\t\tif (updates) {\n\t\t\t\t\ttrans->delayed_ref_updates = 0;\n\t\t\t\t\tret = btrfs_run_delayed_refs(trans, root, updates * 2);\n\t\t\t\t\tif (ret && !err)\n\t\t\t\t\t\terr = ret;\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*\n\t\t\t * if we failed to refill our space rsv, bail out\n\t\t\t * and let the transaction restart\n\t\t\t */\n\t\t\tif (should_end) {\n\t\t\t\terr = -EAGAIN;\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t\tgoto search_again;\n\t\t} else {\n\t\t\tpath->slots[0]--;\n\t\t}\n\t}\nout:\n\tif (pending_del_nr) {\n\t\tret = btrfs_del_items(trans, root, path, pending_del_slot,\n\t\t\t\t pending_del_nr);\n\t\tif (ret)\n\t\t\tbtrfs_abort_transaction(trans, root, ret);\n\t}\nerror:\n\tif (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)\n\t\tbtrfs_ordered_update_i_size(inode, last_size, NULL);\n\n\tbtrfs_free_path(path);\n\n\tif (be_nice && bytes_deleted > 32 * 1024 * 1024) {\n\t\tunsigned long updates = trans->delayed_ref_updates;\n\t\tif (updates) {\n\t\t\ttrans->delayed_ref_updates = 0;\n\t\t\tret = btrfs_run_delayed_refs(trans, root, updates * 2);\n\t\t\tif (ret && !err)\n\t\t\t\terr = ret;\n\t\t}\n\t}\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Btrfs: fix truncation of compressed and inlined extents\n\nWhen truncating a file to a smaller size which consists of an inline\nextent that is compressed, we did not discard (or made unusable) the\ndata between the new file size and the old file size, wasting metadata\nspace and allowing for the truncated data to be leaked and the data\ncorruption/loss mentioned below.\nWe were also not correctly decrementing the number of bytes used by the\ninode, we were setting it to zero, giving a wrong report for callers of\nthe stat(2) syscall. The fsck tool also reported an error about a mismatch\nbetween the nbytes of the file versus the real space used by the file.\n\nNow because we weren't discarding the truncated region of the file, it\nwas possible for a caller of the clone ioctl to actually read the data\nthat was truncated, allowing for a security breach without requiring root\naccess to the system, using only standard filesystem operations. The\nscenario is the following:\n\n 1) User A creates a file which consists of an inline and compressed\n extent with a size of 2000 bytes - the file is not accessible to\n any other users (no read, write or execution permission for anyone\n else);\n\n 2) The user truncates the file to a size of 1000 bytes;\n\n 3) User A makes the file world readable;\n\n 4) User B creates a file consisting of an inline extent of 2000 bytes;\n\n 5) User B issues a clone operation from user A's file into its own\n file (using a length argument of 0, clone the whole range);\n\n 6) User B now gets to see the 1000 bytes that user A truncated from\n its file before it made its file world readbale. User B also lost\n the bytes in the range [1000, 2000[ bytes from its own file, but\n that might be ok if his/her intention was reading stale data from\n user A that was never supposed to be public.\n\nNote that this contrasts with the case where we truncate a file from 2000\nbytes to 1000 bytes and then truncate it back from 1000 to 2000 bytes. In\nthis case reading any byte from the range [1000, 2000[ will return a value\nof 0x00, instead of the original data.\n\nThis problem exists since the clone ioctl was added and happens both with\nand without my recent data loss and file corruption fixes for the clone\nioctl (patch \"Btrfs: fix file corruption and data loss after cloning\ninline extents\").\n\nSo fix this by truncating the compressed inline extents as we do for the\nnon-compressed case, which involves decompressing, if the data isn't already\nin the page cache, compressing the truncated version of the extent, writing\nthe compressed content into the inline extent and then truncate it.\n\nThe following test case for fstests reproduces the problem. In order for\nthe test to pass both this fix and my previous fix for the clone ioctl\nthat forbids cloning a smaller inline extent into a larger one,\nwhich is titled \"Btrfs: fix file corruption and data loss after cloning\ninline extents\", are needed. Without that other fix the test fails in a\ndifferent way that does not leak the truncated data, instead part of\ndestination file gets replaced with zeroes (because the destination file\nhas a larger inline extent than the source).\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\n rm -f $seqres.full\n\n _scratch_mkfs >>$seqres.full 2>&1\n _scratch_mount \"-o compress\"\n\n # Create our test files. File foo is going to be the source of a clone operation\n # and consists of a single inline extent with an uncompressed size of 512 bytes,\n # while file bar consists of a single inline extent with an uncompressed size of\n # 256 bytes. For our test's purpose, it's important that file bar has an inline\n # extent with a size smaller than foo's inline extent.\n $XFS_IO_PROG -f -c \"pwrite -S 0xa1 0 128\" \\\n -c \"pwrite -S 0x2a 128 384\" \\\n $SCRATCH_MNT/foo | _filter_xfs_io\n $XFS_IO_PROG -f -c \"pwrite -S 0xbb 0 256\" $SCRATCH_MNT/bar | _filter_xfs_io\n\n # Now durably persist all metadata and data. We do this to make sure that we get\n # on disk an inline extent with a size of 512 bytes for file foo.\n sync\n\n # Now truncate our file foo to a smaller size. Because it consists of a\n # compressed and inline extent, btrfs did not shrink the inline extent to the\n # new size (if the extent was not compressed, btrfs would shrink it to 128\n # bytes), it only updates the inode's i_size to 128 bytes.\n $XFS_IO_PROG -c \"truncate 128\" $SCRATCH_MNT/foo\n\n # Now clone foo's inline extent into bar.\n # This clone operation should fail with errno EOPNOTSUPP because the source\n # file consists only of an inline extent and the file's size is smaller than\n # the inline extent of the destination (128 bytes < 256 bytes). However the\n # clone ioctl was not prepared to deal with a file that has a size smaller\n # than the size of its inline extent (something that happens only for compressed\n # inline extents), resulting in copying the full inline extent from the source\n # file into the destination file.\n #\n # Note that btrfs' clone operation for inline extents consists of removing the\n # inline extent from the destination inode and copy the inline extent from the\n # source inode into the destination inode, meaning that if the destination\n # inode's inline extent is larger (N bytes) than the source inode's inline\n # extent (M bytes), some bytes (N - M bytes) will be lost from the destination\n # file. Btrfs could copy the source inline extent's data into the destination's\n # inline extent so that we would not lose any data, but that's currently not\n # done due to the complexity that would be needed to deal with such cases\n # (specially when one or both extents are compressed), returning EOPNOTSUPP, as\n # it's normally not a very common case to clone very small files (only case\n # where we get inline extents) and copying inline extents does not save any\n # space (unlike for normal, non-inlined extents).\n $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/foo $SCRATCH_MNT/bar\n\n # Now because the above clone operation used to succeed, and due to foo's inline\n # extent not being shinked by the truncate operation, our file bar got the whole\n # inline extent copied from foo, making us lose the last 128 bytes from bar\n # which got replaced by the bytes in range [128, 256[ from foo before foo was\n # truncated - in other words, data loss from bar and being able to read old and\n # stale data from foo that should not be possible to read anymore through normal\n # filesystem operations. Contrast with the case where we truncate a file from a\n # size N to a smaller size M, truncate it back to size N and then read the range\n # [M, N[, we should always get the value 0x00 for all the bytes in that range.\n\n # We expected the clone operation to fail with errno EOPNOTSUPP and therefore\n # not modify our file's bar data/metadata. So its content should be 256 bytes\n # long with all bytes having the value 0xbb.\n #\n # Without the btrfs bug fix, the clone operation succeeded and resulted in\n # leaking truncated data from foo, the bytes that belonged to its range\n # [128, 256[, and losing data from bar in that same range. So reading the\n # file gave us the following content:\n #\n # 0000000 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1\n # *\n # 0000200 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a\n # *\n # 0000400\n echo \"File bar's content after the clone operation:\"\n od -t x1 $SCRATCH_MNT/bar\n\n # Also because the foo's inline extent was not shrunk by the truncate\n # operation, btrfs' fsck, which is run by the fstests framework everytime a\n # test completes, failed reporting the following error:\n #\n # root 5 inode 257 errors 400, nbytes wrong\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: void ldap_decode_attribs_bare(TALLOC_CTX *mem_ctx, struct asn1_data *data,\n\t\t\t struct ldb_message_element **attributes,\n\t\t\t int *num_attributes)\n{\n\twhile (asn1_peek_tag(data, ASN1_SEQUENCE(0))) {\n\t\tstruct ldb_message_element attrib;\n\t\tZERO_STRUCT(attrib);\n\t\tldap_decode_attrib(mem_ctx, data, &attrib);\n\t\tadd_attrib_to_array_talloc(mem_ctx, &attrib,\n\t\t\t\t\t attributes, num_attributes);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-7540: s4: libcli: ldap message - Ensure all asn1_XX returns are checked.\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=9187\n\nSigned-off-by: Jeremy Allison \nReviewed-by: Ronnie Sahlberg \n\nAutobuild-User(master): Jeremy Allison \nAutobuild-Date(master): Fri Sep 26 03:15:00 CEST 2014 on sn-devel-104\n\n(cherry picked from commit 69a7e3cfdc8dbba9c8dcfdfae82d2894c7247e15)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool asn1_write_BOOLEAN(struct asn1_data *data, bool v)\n{\n\tasn1_push_tag(data, ASN1_BOOLEAN);\n\tasn1_write_uint8(data, v ? 0xFF : 0);\n\tasn1_pop_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: bool asn1_write_enumerated(struct asn1_data *data, uint8_t v)\n{\n\tif (!asn1_push_tag(data, ASN1_ENUMERATED)) return false;\n\tasn1_write_uint8(data, v);\n\tasn1_pop_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: SMBC_attr_server(TALLOC_CTX *ctx,\n SMBCCTX *context,\n const char *server,\n uint16_t port,\n const char *share,\n char **pp_workgroup,\n char **pp_username,\n char **pp_password)\n{\n int flags;\n\tstruct cli_state *ipc_cli = NULL;\n\tstruct rpc_pipe_client *pipe_hnd = NULL;\n NTSTATUS nt_status;\n\tSMBCSRV *srv=NULL;\n\tSMBCSRV *ipc_srv=NULL;\n\n\t/*\n\t * Use srv->cli->desthost and srv->cli->share instead of\n\t * server and share below to connect to the actual share,\n\t * i.e., a normal share or a referred share from\n\t * 'msdfs proxy' share.\n\t */\n\tsrv = SMBC_server(ctx, context, true, server, port, share,\n\t\t\tpp_workgroup, pp_username, pp_password);\n\tif (!srv) {\n\t\treturn NULL;\n\t}\n\tserver = smbXcli_conn_remote_name(srv->cli->conn);\n\tshare = srv->cli->share;\n\n /*\n * See if we've already created this special connection. Reference\n * our \"special\" share name '*IPC$', which is an impossible real share\n * name due to the leading asterisk.\n */\n ipc_srv = SMBC_find_server(ctx, context, server, \"*IPC$\",\n pp_workgroup, pp_username, pp_password);\n if (!ipc_srv) {\n\n /* We didn't find a cached connection. Get the password */\n\t\tif (!*pp_password || (*pp_password)[0] == '\\0') {\n /* ... then retrieve it now. */\n\t\t\tSMBC_call_auth_fn(ctx, context, server, share,\n pp_workgroup,\n pp_username,\n pp_password);\n\t\t\tif (!*pp_workgroup || !*pp_username || !*pp_password) {\n\t\t\t\terrno = ENOMEM;\n\t\t\t\treturn NULL;\n\t\t\t}\n }\n\n flags = 0;\n if (smbc_getOptionUseKerberos(context)) {\n flags |= CLI_FULL_CONNECTION_USE_KERBEROS;\n }\n if (smbc_getOptionUseCCache(context)) {\n flags |= CLI_FULL_CONNECTION_USE_CCACHE;\n }\n\n nt_status = cli_full_connection(&ipc_cli,\n\t\t\t\t\t\tlp_netbios_name(), server,\n\t\t\t\t\t\tNULL, 0, \"IPC$\", \"?????\",\n\t\t\t\t\t\t*pp_username,\n\t\t\t\t\t\t*pp_workgroup,\n\t\t\t\t\t\t*pp_password,\n\t\t\t\t\t\tflags,\n\t\t\t\t\t\tSMB_SIGNING_DEFAULT);\n if (! NT_STATUS_IS_OK(nt_status)) {\n DEBUG(1,(\"cli_full_connection failed! (%s)\\n\",\n nt_errstr(nt_status)));\n errno = ENOTSUP;\n return NULL;\n }\n\n\t\tif (context->internal->smb_encryption_level) {\n\t\t\t/* Attempt UNIX smb encryption. */\n\t\t\tif (!NT_STATUS_IS_OK(cli_force_encryption(ipc_cli,\n *pp_username,\n *pp_password,\n *pp_workgroup))) {\n\n\t\t\t\t/*\n\t\t\t\t * context->smb_encryption_level ==\n\t\t\t\t * 1 means don't fail if encryption can't be\n\t\t\t\t * negotiated, == 2 means fail if encryption\n\t\t\t\t * can't be negotiated.\n\t\t\t\t */\n\n\t\t\t\tDEBUG(4,(\" SMB encrypt failed on IPC$\\n\"));\n\n\t\t\t\tif (context->internal->smb_encryption_level == 2) {\n\t\t cli_shutdown(ipc_cli);\n\t\t\t\t\terrno = EPERM;\n\t\t\t\t\treturn NULL;\n\t\t\t\t}\n\t\t\t}\n\t\t\tDEBUG(4,(\" SMB encrypt ok on IPC$\\n\"));\n\t\t}\n\n ipc_srv = SMB_MALLOC_P(SMBCSRV);\n if (!ipc_srv) {\n errno = ENOMEM;\n cli_shutdown(ipc_cli);\n return NULL;\n }\n\n ZERO_STRUCTP(ipc_srv);\n ipc_srv->cli = ipc_cli;\n\n nt_status = cli_rpc_pipe_open_noauth(\n\t\t\tipc_srv->cli, &ndr_table_lsarpc, &pipe_hnd);\n if (!NT_STATUS_IS_OK(nt_status)) {\n DEBUG(1, (\"cli_nt_session_open fail!\\n\"));\n errno = ENOTSUP;\n cli_shutdown(ipc_srv->cli);\n free(ipc_srv);\n return NULL;\n }\n\n /*\n * Some systems don't support\n * SEC_FLAG_MAXIMUM_ALLOWED, but NT sends 0x2000000\n * so we might as well do it too.\n */\n\n nt_status = rpccli_lsa_open_policy(\n pipe_hnd,\n talloc_tos(),\n True,\n GENERIC_EXECUTE_ACCESS,\n &ipc_srv->pol);\n\n if (!NT_STATUS_IS_OK(nt_status)) {\n errno = SMBC_errno(context, ipc_srv->cli);\n cli_shutdown(ipc_srv->cli);\n free(ipc_srv);\n return NULL;\n }\n\n /* now add it to the cache (internal or external) */\n\n errno = 0; /* let cache function set errno if it likes */\n if (smbc_getFunctionAddCachedServer(context)(context, ipc_srv,\n server,\n \"*IPC$\",\n *pp_workgroup,\n *pp_username)) {\n DEBUG(3, (\" Failed to add server to cache\\n\"));\n if (errno == 0) {\n errno = ENOMEM;\n }\n cli_shutdown(ipc_srv->cli);\n free(ipc_srv);\n return NULL;\n }\n\n DLIST_ADD(context->internal->servers, ipc_srv);\n }\n\n return ipc_srv;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'CVE-2015-5296: s3:libsmb: force signing when requiring encryption in SMBC_server_internal()\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=11536\n\nSigned-off-by: Stefan Metzmacher \nReviewed-by: Jeremy Allison '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int pptp_connect(struct socket *sock, struct sockaddr *uservaddr,\n\tint sockaddr_len, int flags)\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\tstruct rtable *rt;\n\tstruct flowi4 fl4;\n\tint error = 0;\n\n\tif (sp->sa_protocol != PX_PROTO_PPTP)\n\t\treturn -EINVAL;\n\n\tif (lookup_chan_dst(sp->sa_addr.pptp.call_id, sp->sa_addr.pptp.sin_addr.s_addr))\n\t\treturn -EALREADY;\n\n\tlock_sock(sk);\n\t/* Check for already bound sockets */\n\tif (sk->sk_state & PPPOX_CONNECTED) {\n\t\terror = -EBUSY;\n\t\tgoto end;\n\t}\n\n\t/* Check for already disconnected sockets, on attempts to disconnect */\n\tif (sk->sk_state & PPPOX_DEAD) {\n\t\terror = -EALREADY;\n\t\tgoto end;\n\t}\n\n\tif (!opt->src_addr.sin_addr.s_addr || !sp->sa_addr.pptp.sin_addr.s_addr) {\n\t\terror = -EINVAL;\n\t\tgoto end;\n\t}\n\n\tpo->chan.private = sk;\n\tpo->chan.ops = &pptp_chan_ops;\n\n\trt = ip_route_output_ports(sock_net(sk), &fl4, sk,\n\t\t\t\t opt->dst_addr.sin_addr.s_addr,\n\t\t\t\t opt->src_addr.sin_addr.s_addr,\n\t\t\t\t 0, 0,\n\t\t\t\t IPPROTO_GRE, RT_CONN_FLAGS(sk), 0);\n\tif (IS_ERR(rt)) {\n\t\terror = -EHOSTUNREACH;\n\t\tgoto end;\n\t}\n\tsk_setup_caps(sk, &rt->dst);\n\n\tpo->chan.mtu = dst_mtu(&rt->dst);\n\tif (!po->chan.mtu)\n\t\tpo->chan.mtu = PPP_MRU;\n\tip_rt_put(rt);\n\tpo->chan.mtu -= PPTP_HEADER_OVERHEAD;\n\n\tpo->chan.hdrlen = 2 + sizeof(struct pptp_gre_header);\n\terror = ppp_register_channel(&po->chan);\n\tif (error) {\n\t\tpr_err(\"PPTP: failed to register PPP channel (%d)\\n\", error);\n\t\tgoto end;\n\t}\n\n\topt->dst_addr = sp->sa_addr.pptp;\n\tsk->sk_state = PPPOX_CONNECTED;\n\n end:\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: void recv_additional_file_list(int f)\n{\n\tstruct file_list *flist;\n\tint ndx = read_ndx(f);\n\tif (ndx == NDX_FLIST_EOF) {\n\t\tflist_eof = 1;\n\t\tif (DEBUG_GTE(FLIST, 3))\n\t\t\trprintf(FINFO, \"[%s] flist_eof=1\\n\", who_am_i());\n\t\tchange_local_filter_dir(NULL, 0, 0);\n\t} else {\n\t\tndx = NDX_FLIST_OFFSET - ndx;\n\t\tif (ndx < 0 || ndx >= dir_flist->used) {\n\t\t\tndx = NDX_FLIST_OFFSET - ndx;\n\t\t\trprintf(FERROR,\n\t\t\t\t\"[%s] Invalid dir index: %d (%d - %d)\\n\",\n\t\t\t\twho_am_i(), ndx, NDX_FLIST_OFFSET,\n\t\t\t\tNDX_FLIST_OFFSET - dir_flist->used + 1);\n\t\t\texit_cleanup(RERR_PROTOCOL);\n\t\t}\n\t\tif (DEBUG_GTE(FLIST, 3)) {\n\t\t\trprintf(FINFO, \"[%s] receiving flist for dir %d\\n\",\n\t\t\t\twho_am_i(), ndx);\n\t\t}\n\t\tflist = recv_file_list(f);\n\t\tflist->parent_ndx = ndx;\n\t}\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: long tty_ioctl(struct file *file, unsigned int cmd, unsigned long arg)\n{\n\tstruct tty_struct *tty = file_tty(file);\n\tstruct tty_struct *real_tty;\n\tvoid __user *p = (void __user *)arg;\n\tint retval;\n\tstruct tty_ldisc *ld;\n\n\tif (tty_paranoia_check(tty, file_inode(file), \"tty_ioctl\"))\n\t\treturn -EINVAL;\n\n\treal_tty = tty_pair_get_tty(tty);\n\n\t/*\n\t * Factor out some common prep work\n\t */\n\tswitch (cmd) {\n\tcase TIOCSETD:\n\tcase TIOCSBRK:\n\tcase TIOCCBRK:\n\tcase TCSBRK:\n\tcase TCSBRKP:\n\t\tretval = tty_check_change(tty);\n\t\tif (retval)\n\t\t\treturn retval;\n\t\tif (cmd != TIOCCBRK) {\n\t\t\ttty_wait_until_sent(tty, 0);\n\t\t\tif (signal_pending(current))\n\t\t\t\treturn -EINTR;\n\t\t}\n\t\tbreak;\n\t}\n\n\t/*\n\t *\tNow do the stuff.\n\t */\n\tswitch (cmd) {\n\tcase TIOCSTI:\n\t\treturn tiocsti(tty, p);\n\tcase TIOCGWINSZ:\n\t\treturn tiocgwinsz(real_tty, p);\n\tcase TIOCSWINSZ:\n\t\treturn tiocswinsz(real_tty, p);\n\tcase TIOCCONS:\n\t\treturn real_tty != tty ? -EINVAL : tioccons(file);\n\tcase FIONBIO:\n\t\treturn fionbio(file, p);\n\tcase TIOCEXCL:\n\t\tset_bit(TTY_EXCLUSIVE, &tty->flags);\n\t\treturn 0;\n\tcase TIOCNXCL:\n\t\tclear_bit(TTY_EXCLUSIVE, &tty->flags);\n\t\treturn 0;\n\tcase TIOCGEXCL:\n\t{\n\t\tint excl = test_bit(TTY_EXCLUSIVE, &tty->flags);\n\t\treturn put_user(excl, (int __user *)p);\n\t}\n\tcase TIOCNOTTY:\n\t\tif (current->signal->tty != tty)\n\t\t\treturn -ENOTTY;\n\t\tno_tty();\n\t\treturn 0;\n\tcase TIOCSCTTY:\n\t\treturn tiocsctty(real_tty, file, arg);\n\tcase TIOCGPGRP:\n\t\treturn tiocgpgrp(tty, real_tty, p);\n\tcase TIOCSPGRP:\n\t\treturn tiocspgrp(tty, real_tty, p);\n\tcase TIOCGSID:\n\t\treturn tiocgsid(tty, real_tty, p);\n\tcase TIOCGETD:\n\t\treturn put_user(tty->ldisc->ops->num, (int __user *)p);\n\tcase TIOCSETD:\n\t\treturn tiocsetd(tty, p);\n\tcase TIOCVHANGUP:\n\t\tif (!capable(CAP_SYS_ADMIN))\n\t\t\treturn -EPERM;\n\t\ttty_vhangup(tty);\n\t\treturn 0;\n\tcase TIOCGDEV:\n\t{\n\t\tunsigned int ret = new_encode_dev(tty_devnum(real_tty));\n\t\treturn put_user(ret, (unsigned int __user *)p);\n\t}\n\t/*\n\t * Break handling\n\t */\n\tcase TIOCSBRK:\t/* Turn break on, unconditionally */\n\t\tif (tty->ops->break_ctl)\n\t\t\treturn tty->ops->break_ctl(tty, -1);\n\t\treturn 0;\n\tcase TIOCCBRK:\t/* Turn break off, unconditionally */\n\t\tif (tty->ops->break_ctl)\n\t\t\treturn tty->ops->break_ctl(tty, 0);\n\t\treturn 0;\n\tcase TCSBRK: /* SVID version: non-zero arg --> no break */\n\t\t/* non-zero arg means wait for all output data\n\t\t * to be sent (performed above) but don't send break.\n\t\t * This is used by the tcdrain() termios function.\n\t\t */\n\t\tif (!arg)\n\t\t\treturn send_break(tty, 250);\n\t\treturn 0;\n\tcase TCSBRKP:\t/* support for POSIX tcsendbreak() */\n\t\treturn send_break(tty, arg ? arg*100 : 250);\n\n\tcase TIOCMGET:\n\t\treturn tty_tiocmget(tty, p);\n\tcase TIOCMSET:\n\tcase TIOCMBIC:\n\tcase TIOCMBIS:\n\t\treturn tty_tiocmset(tty, cmd, p);\n\tcase TIOCGICOUNT:\n\t\tretval = tty_tiocgicount(tty, p);\n\t\t/* For the moment allow fall through to the old method */\n \tif (retval != -EINVAL)\n\t\t\treturn retval;\n\t\tbreak;\n\tcase TCFLSH:\n\t\tswitch (arg) {\n\t\tcase TCIFLUSH:\n\t\tcase TCIOFLUSH:\n\t\t/* flush tty buffer and allow ldisc to process ioctl */\n\t\t\ttty_buffer_flush(tty, NULL);\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tcase TIOCSSERIAL:\n\t\ttty_warn_deprecated_flags(p);\n\t\tbreak;\n\t}\n\tif (tty->ops->ioctl) {\n\t\tretval = tty->ops->ioctl(tty, cmd, arg);\n\t\tif (retval != -ENOIOCTLCMD)\n\t\t\treturn retval;\n\t}\n\tld = tty_ldisc_ref_wait(tty);\n\tretval = -EINVAL;\n\tif (ld->ops->ioctl) {\n\t\tretval = ld->ops->ioctl(tty, file, cmd, arg);\n\t\tif (retval == -ENOIOCTLCMD)\n\t\t\tretval = -ENOTTY;\n\t}\n\ttty_ldisc_deref(ld);\n\treturn retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-362'], 'message': 'tty: Fix unsafe ldisc reference via ioctl(TIOCGETD)\n\nioctl(TIOCGETD) retrieves the line discipline id directly from the\nldisc because the line discipline id (c_line) in termios is untrustworthy;\nuserspace may have set termios via ioctl(TCSETS*) without actually\nchanging the line discipline via ioctl(TIOCSETD).\n\nHowever, directly accessing the current ldisc via tty->ldisc is\nunsafe; the ldisc ptr dereferenced may be stale if the line discipline\nis changing via ioctl(TIOCSETD) or hangup.\n\nWait for the line discipline reference (just like read() or write())\nto retrieve the \"current\" line discipline id.\n\nCc: \nSigned-off-by: Peter Hurley \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: authreadkeys(\n\tconst char *file\n\t)\n{\n\tFILE\t*fp;\n\tchar\t*line;\n\tchar\t*token;\n\tkeyid_t\tkeyno;\n\tint\tkeytype;\n\tchar\tbuf[512];\t\t/* lots of room for line */\n\tu_char\tkeystr[32];\t\t/* Bug 2537 */\n\tsize_t\tlen;\n\tsize_t\tj;\n\tu_int nerr;\n\tKeyDataT *list = NULL;\n\tKeyDataT *next = NULL;\n\t/*\n\t * Open file. Complain and return if it can't be opened.\n\t */\n\tfp = fopen(file, \"r\");\n\tif (fp == NULL) {\n\t\tmsyslog(LOG_ERR, \"authreadkeys: file '%s': %m\",\n\t\t file);\n\t\tgoto onerror;\n\t}\n\tINIT_SSL();\n\n\t/*\n\t * Now read lines from the file, looking for key entries. Put\n\t * the data into temporary store for later propagation to avoid\n\t * two-pass processing.\n\t */\n\tnerr = 0;\n\twhile ((line = fgets(buf, sizeof buf, fp)) != NULL) {\n\t\tif (nerr > nerr_maxlimit)\n\t\t\tbreak;\n\t\ttoken = nexttok(&line);\n\t\tif (token == NULL)\n\t\t\tcontinue;\n\t\t\n\t\t/*\n\t\t * First is key number. See if it is okay.\n\t\t */\n\t\tkeyno = atoi(token);\n\t\tif (keyno == 0) {\n\t\t\tlog_maybe(&nerr,\n\t\t\t\t \"authreadkeys: cannot change key %s\",\n\t\t\t\t token);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (keyno > NTP_MAXKEY) {\n\t\t\tlog_maybe(&nerr,\n\t\t\t\t \"authreadkeys: key %s > %d reserved for Autokey\",\n\t\t\t\t token, NTP_MAXKEY);\n\t\t\tcontinue;\n\t\t}\n\n\t\t/*\n\t\t * Next is keytype. See if that is all right.\n\t\t */\n\t\ttoken = nexttok(&line);\n\t\tif (token == NULL) {\n\t\t\tlog_maybe(&nerr,\n\t\t\t\t \"authreadkeys: no key type for key %d\",\n\t\t\t\t keyno);\n\t\t\tcontinue;\n\t\t}\n#ifdef OPENSSL\n\t\t/*\n\t\t * The key type is the NID used by the message digest \n\t\t * algorithm. There are a number of inconsistencies in\n\t\t * the OpenSSL database. We attempt to discover them\n\t\t * here and prevent use of inconsistent data later.\n\t\t */\n\t\tkeytype = keytype_from_text(token, NULL);\n\t\tif (keytype == 0) {\n\t\t\tlog_maybe(&nerr,\n\t\t\t\t \"authreadkeys: invalid type for key %d\",\n\t\t\t\t keyno);\n\t\t\tcontinue;\n\t\t}\n\t\tif (EVP_get_digestbynid(keytype) == NULL) {\n\t\t\tlog_maybe(&nerr,\n\t\t\t\t \"authreadkeys: no algorithm for key %d\",\n\t\t\t\t keyno);\n\t\t\tcontinue;\n\t\t}\n#else\t/* !OPENSSL follows */\n\n\t\t/*\n\t\t * The key type is unused, but is required to be 'M' or\n\t\t * 'm' for compatibility.\n\t\t */\n\t\tif (!(*token == 'M' || *token == 'm')) {\n\t\t\tlog_maybe(&nerr,\n\t\t\t\t \"authreadkeys: invalid type for key %d\",\n\t\t\t\t keyno);\n\t\t\tcontinue;\n\t\t}\n\t\tkeytype = KEY_TYPE_MD5;\n#endif\t/* !OPENSSL */\n\n\t\t/*\n\t\t * Finally, get key and insert it. If it is longer than 20\n\t\t * characters, it is a binary string encoded in hex;\n\t\t * otherwise, it is a text string of printable ASCII\n\t\t * characters.\n\t\t */\n\t\ttoken = nexttok(&line);\n\t\tif (token == NULL) {\n\t\t\tlog_maybe(&nerr,\n\t\t\t\t \"authreadkeys: no key for key %d\", keyno);\n\t\t\tcontinue;\n\t\t}\n\t\tnext = NULL;\n\t\tlen = strlen(token);\n\t\tif (len <= 20) {\t/* Bug 2537 */\n\t\t\tnext = emalloc(sizeof(KeyDataT) + len);\n\t\t\tnext->keyid = keyno;\n\t\t\tnext->keytype = keytype;\n\t\t\tnext->seclen = len;\n\t\t\tmemcpy(next->secbuf, token, len);\n\t\t} else {\n\t\t\tstatic const char hex[] = \"0123456789abcdef\";\n\t\t\tu_char\ttemp;\n\t\t\tchar\t*ptr;\n\t\t\tsize_t\tjlim;\n\n\t\t\tjlim = min(len, 2 * sizeof(keystr));\n\t\t\tfor (j = 0; j < jlim; j++) {\n\t\t\t\tptr = strchr(hex, tolower((unsigned char)token[j]));\n\t\t\t\tif (ptr == NULL)\n\t\t\t\t\tbreak;\t/* abort decoding */\n\t\t\t\ttemp = (u_char)(ptr - hex);\n\t\t\t\tif (j & 1)\n\t\t\t\t\tkeystr[j / 2] |= temp;\n\t\t\t\telse\n\t\t\t\t\tkeystr[j / 2] = temp << 4;\n\t\t\t}\n\t\t\tif (j < jlim) {\n\t\t\t\tlog_maybe(&nerr,\n\t\t\t\t\t \"authreadkeys: invalid hex digit for key %d\",\n\t\t\t\t\t keyno);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlen = jlim/2; /* hmmmm.... what about odd length?!? */\n\t\t\tnext = emalloc(sizeof(KeyDataT) + len);\n\t\t\tnext->keyid = keyno;\n\t\t\tnext->keytype = keytype;\n\t\t\tnext->seclen = len;\n\t\t\tmemcpy(next->secbuf, keystr, len);\n\t\t}\n\t\tINSIST(NULL != next);\n\t\tnext->next = list;\n\t\tlist = next;\n\t}\n\tfclose(fp);\n\tif (nerr > nerr_maxlimit) {\n\t\tmsyslog(LOG_ERR,\n\t\t\t\"authreadkeys: rejecting file '%s' after %u errors (emergency break)\",\n\t\t\tfile, nerr);\n\t\tgoto onerror;\n\t}\n\tif (nerr > 0) {\n\t\tmsyslog(LOG_ERR,\n\t\t\t\"authreadkeys: rejecting file '%s' after %u error(s)\",\n\t\t\tfile, nerr);\n\t\tgoto onerror;\n\t}\n\n\t/* first remove old file-based keys */\n\tauth_delkeys();\n\t/* insert the new key material */\n\twhile (NULL != (next = list)) {\n\t\tlist = next->next;\n\t\tMD5auth_setkey(next->keyid, next->keytype,\n\t\t\t next->secbuf, next->seclen);\n\t\t/* purge secrets from memory before free()ing it */\n\t\tmemset(next, 0, sizeof(*next) + next->seclen);\n\t\tfree(next);\n\t}\n\treturn (1);\n\n onerror:\n\t/* Mop up temporary storage before bailing out. */\n\twhile (NULL != (next = list)) {\n\t\tlist = next->next;\n\t\t/* purge secrets from memory before free()ing it */\n\t\tmemset(next, 0, sizeof(*next) + next->seclen);\n\t\tfree(next);\n\t}\n\treturn (0);\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: nextvar(\n\tint *datalen,\n\tconst char **datap,\n\tchar **vname,\n\tchar **vvalue\n\t)\n{\n\tconst char *cp;\n\tconst char *np;\n\tconst char *cpend;\n\tsize_t srclen;\n\tsize_t len;\n\tstatic char name[MAXVARLEN];\n\tstatic char value[MAXVALLEN];\n\n\tcp = *datap;\n\tcpend = cp + *datalen;\n\n\t/*\n\t * Space past commas and white space\n\t */\n\twhile (cp < cpend && (*cp == ',' || isspace((int)*cp)))\n\t\tcp++;\n\tif (cp >= cpend)\n\t\treturn 0;\n\n\t/*\n\t * Copy name until we hit a ',', an '=', a '\\r' or a '\\n'. Backspace\n\t * over any white space and terminate it.\n\t */\n\tsrclen = strcspn(cp, \",=\\r\\n\");\n\tsrclen = min(srclen, (size_t)(cpend - cp));\n\tlen = srclen;\n\twhile (len > 0 && isspace((unsigned char)cp[len - 1]))\n\t\tlen--;\n\tif (len > 0)\n\t\tmemcpy(name, cp, len);\n\tname[len] = '\\0';\n\t*vname = name;\n\tcp += srclen;\n\n\t/*\n\t * Check if we hit the end of the buffer or a ','. If so we are done.\n\t */\n\tif (cp >= cpend || *cp == ',' || *cp == '\\r' || *cp == '\\n') {\n\t\tif (cp < cpend)\n\t\t\tcp++;\n\t\t*datap = cp;\n\t\t*datalen = cpend - cp;\n\t\t*vvalue = NULL;\n\t\treturn 1;\n\t}\n\n\t/*\n\t * So far, so good. Copy out the value\n\t */\n\tcp++;\t/* past '=' */\n\twhile (cp < cpend && (isspace((unsigned char)*cp) && *cp != '\\r' && *cp != '\\n'))\n\t\tcp++;\n\tnp = cp;\n\tif ('\"' == *np) {\n\t\tdo {\n\t\t\tnp++;\n\t\t} while (np < cpend && '\"' != *np);\n\t\tif (np < cpend && '\"' == *np)\n\t\t\tnp++;\n\t} else {\n\t\twhile (np < cpend && ',' != *np && '\\r' != *np)\n\t\t\tnp++;\n\t}\n\tlen = np - cp;\n\tif (np > cpend || len >= sizeof(value) ||\n\t (np < cpend && ',' != *np && '\\r' != *np))\n\t\treturn 0;\n\tmemcpy(value, cp, len);\n\t/*\n\t * Trim off any trailing whitespace\n\t */\n\twhile (len > 0 && isspace((unsigned char)value[len - 1]))\n\t\tlen--;\n\tvalue[len] = '\\0';\n\n\t/*\n\t * Return this. All done.\n\t */\n\tif (np < cpend && ',' == *np)\n\t\tnp++;\n\t*datap = np;\n\t*datalen = cpend - np;\n\t*vvalue = value;\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': '[Bug 2937] (NTPQ) nextvar() missing 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: get_clkbug_info(\n\tsockaddr_u *srcadr,\n\tendpt *inter,\n\tstruct req_pkt *inpkt\n\t)\n{\n\tregister int i;\n\tregister struct info_clkbug *ic;\n\tregister u_int32 *clkaddr;\n\tregister int items;\n\tstruct refclockbug bug;\n\tsockaddr_u addr;\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 = (u_int32 *)&inpkt->u;\n\n\tic = (struct info_clkbug *)prepare_pkt(srcadr, inter, inpkt,\n\t\t\t\t\t sizeof(struct info_clkbug));\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\tZERO(bug);\n\t\trefclock_buginfo(&addr, &bug);\n\t\tif (bug.nvalues == 0 && bug.ntimes == 0) {\n\t\t\treq_ack(srcadr, inter, inpkt, INFO_ERR_NODATA);\n\t\t\treturn;\n\t\t}\n\n\t\tic->clockadr = NSRCADR(&addr);\n\t\ti = bug.nvalues;\n\t\tif (i > NUMCBUGVALUES)\n\t\t i = NUMCBUGVALUES;\n\t\tic->nvalues = (u_char)i;\n\t\tic->svalues = htons((u_short) (bug.svalues & ((1<= 0)\n\t\t ic->values[i] = htonl(bug.values[i]);\n\n\t\ti = bug.ntimes;\n\t\tif (i > NUMCBUGTIMES)\n\t\t i = NUMCBUGTIMES;\n\t\tic->ntimes = (u_char)i;\n\t\tic->stimes = htonl(bug.stimes);\n\t\twhile (--i >= 0) {\n\t\t\tHTONL_FP(&bug.times[i], &ic->times[i]);\n\t\t}\n\n\t\tic = (struct info_clkbug *)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: yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, int yyrule)\n{\n unsigned long int yylno = yyrline[yyrule];\n int yynrhs = yyr2[yyrule];\n int yyi;\n YYFPRINTF (stderr, \"Reducing stack by rule %d (line %lu):\\n\",\n yyrule - 1, yylno);\n /* The symbols being reduced. */\n for (yyi = 0; yyi < yynrhs; yyi++)\n {\n YYFPRINTF (stderr, \" $%d = \", yyi + 1);\n yy_symbol_print (stderr,\n yystos[yyssp[yyi + 1 - yynrhs]],\n &(yyvsp[(yyi + 1) - (yynrhs)])\n );\n YYFPRINTF (stderr, \"\\n\");\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-19'], 'message': '[Sec 2942]: Off-path DoS attack on auth broadcast mode. HStenn.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void usage(void)\n{\n PRINT_VERSION;\n puts(\"Copyright (c) 2011, Oracle and/or its affiliates. \"\n \"All rights reserved.\\n\");\n puts(\"Enable or disable plugins.\");\n printf(\"\\nUsage: %s [options] ENABLE|DISABLE\\n\\nOptions:\\n\",\n my_progname);\n my_print_help(my_long_options);\n puts(\"\\n\");\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: void CertManager::setPeerX509(X509* x)\n{\n if (x == 0) return;\n\n X509_NAME* issuer = x->GetIssuer();\n X509_NAME* subject = x->GetSubject();\n ASN1_STRING* before = x->GetBefore();\n ASN1_STRING* after = x->GetAfter();\n\n peerX509_ = NEW_YS X509(issuer->GetName(), issuer->GetLength(),\n subject->GetName(), subject->GetLength(), (const char*) before->data,\n before->length, (const char*) after->data, after->length);\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 ssize_t generic_perform_write(struct file *file,\n\t\t\t\tstruct iov_iter *i, loff_t pos)\n{\n\tstruct address_space *mapping = file->f_mapping;\n\tconst struct address_space_operations *a_ops = mapping->a_ops;\n\tlong status = 0;\n\tssize_t written = 0;\n\tunsigned int flags = 0;\n\n\t/*\n\t * Copies from kernel address space cannot fail (NFSD is a big user).\n\t */\n\tif (segment_eq(get_fs(), KERNEL_DS))\n\t\tflags |= AOP_FLAG_UNINTERRUPTIBLE;\n\n\tdo {\n\t\tstruct page *page;\n\t\tpgoff_t index;\t\t/* Pagecache index for current page */\n\t\tunsigned long offset;\t/* Offset into pagecache page */\n\t\tunsigned long bytes;\t/* Bytes to write to page */\n\t\tsize_t copied;\t\t/* Bytes copied from user */\n\t\tvoid *fsdata;\n\n\t\toffset = (pos & (PAGE_CACHE_SIZE - 1));\n\t\tindex = pos >> PAGE_CACHE_SHIFT;\n\t\tbytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,\n\t\t\t\t\t\tiov_iter_count(i));\n\nagain:\n\n\t\t/*\n\t\t * Bring in the user page that we will copy from _first_.\n\t\t * Otherwise there's a nasty deadlock on copying from the\n\t\t * same page as we're writing to, without it being marked\n\t\t * up-to-date.\n\t\t *\n\t\t * Not only is this an optimisation, but it is also required\n\t\t * to check that the address is actually valid, when atomic\n\t\t * usercopies are used, below.\n\t\t */\n\t\tif (unlikely(iov_iter_fault_in_readable(i, bytes))) {\n\t\t\tstatus = -EFAULT;\n\t\t\tbreak;\n\t\t}\n\n\t\tstatus = a_ops->write_begin(file, mapping, pos, bytes, flags,\n\t\t\t\t\t\t&page, &fsdata);\n\t\tif (unlikely(status))\n\t\t\tbreak;\n\n\t\tpagefault_disable();\n\t\tcopied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);\n\t\tpagefault_enable();\n\t\tflush_dcache_page(page);\n\n\t\tstatus = a_ops->write_end(file, mapping, pos, bytes, copied,\n\t\t\t\t\t\tpage, fsdata);\n\t\tif (unlikely(status < 0))\n\t\t\tbreak;\n\t\tcopied = status;\n\n\t\tcond_resched();\n\n\t\tif (unlikely(copied == 0)) {\n\t\t\t/*\n\t\t\t * If we were unable to copy any data at all, we must\n\t\t\t * fall back to a single segment length write.\n\t\t\t *\n\t\t\t * If we didn't fallback here, we could livelock\n\t\t\t * because not all segments in the iov can be copied at\n\t\t\t * once without a pagefault.\n\t\t\t */\n\t\t\tbytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,\n\t\t\t\t\t\tiov_iter_single_seg_count(i));\n\t\t\tgoto again;\n\t\t}\n\t\tiov_iter_advance(i, copied);\n\t\tpos += copied;\n\t\twritten += copied;\n\n\t\tbalance_dirty_pages_ratelimited(mapping);\n\n\t} while (iov_iter_count(i));\n\n\treturn written ? written : status;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'fix writev regression: pan hanging unkillable and un-straceable\n\nFrederik Himpe reported an unkillable and un-straceable pan process.\n\nZero length iovecs can go into an infinite loop in writev, because the\niovec iterator does not always advance over them.\n\nThe sequence required to trigger this is not trivial. I think it\nrequires that a zero-length iovec be followed by a non-zero-length iovec\nwhich causes a pagefault in the atomic usercopy. This causes the writev\ncode to drop back into single-segment copy mode, which then tries to\ncopy the 0 bytes of the zero-length iovec; a zero length copy looks like\na failure though, so it loops.\n\nPut a test into iov_iter_advance to catch zero-length iovecs. We could\njust put the test in the fallback path, but I feel it is more robust to\nskip over zero-length iovecs throughout the code (iovec iterator may be\nused in filesystems too, so it should be robust).\n\nSigned-off-by: Nick Piggin \nSigned-off-by: Ingo Molnar \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void jas_matrix_divpow2(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\trowstep = jas_matrix_rowstep(matrix);\n\tfor (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,\n\t rowstart += rowstep) {\n\t\tfor (j = matrix->numcols_, data = rowstart; j > 0; --j,\n\t\t ++data) {\n\t\t\t*data = (*data >= 0) ? ((*data) >> n) :\n\t\t\t (-((-(*data)) >> n));\n\t\t}\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Added fix for CVE-2016-2089.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: rename_principal_2_svc(rprinc_arg *arg, struct svc_req *rqstp)\n{\n static generic_ret ret;\n char *prime_arg1,\n *prime_arg2;\n gss_buffer_desc client_name,\n service_name;\n OM_uint32 minor_stat;\n kadm5_server_handle_t handle;\n restriction_t *rp;\n const char *errmsg = NULL;\n size_t tlen1, tlen2, clen, slen;\n char *tdots1, *tdots2, *cdots, *sdots;\n\n xdr_free(xdr_generic_ret, &ret);\n\n if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))\n goto exit_func;\n\n if ((ret.code = check_handle((void *)handle)))\n goto exit_func;\n\n if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {\n ret.code = KADM5_FAILURE;\n goto exit_func;\n }\n if (krb5_unparse_name(handle->context, arg->src, &prime_arg1) ||\n krb5_unparse_name(handle->context, arg->dest, &prime_arg2)) {\n ret.code = KADM5_BAD_PRINCIPAL;\n goto exit_func;\n }\n tlen1 = strlen(prime_arg1);\n trunc_name(&tlen1, &tdots1);\n tlen2 = strlen(prime_arg2);\n trunc_name(&tlen2, &tdots2);\n clen = client_name.length;\n trunc_name(&clen, &cdots);\n slen = service_name.length;\n trunc_name(&slen, &sdots);\n\n ret.code = KADM5_OK;\n if (! CHANGEPW_SERVICE(rqstp)) {\n if (!kadm5int_acl_check(handle->context, rqst2name(rqstp),\n ACL_DELETE, arg->src, NULL))\n ret.code = KADM5_AUTH_DELETE;\n /* any restrictions at all on the ADD kills the RENAME */\n if (!kadm5int_acl_check(handle->context, rqst2name(rqstp),\n ACL_ADD, arg->dest, &rp) || rp) {\n if (ret.code == KADM5_AUTH_DELETE)\n ret.code = KADM5_AUTH_INSUFFICIENT;\n else\n ret.code = KADM5_AUTH_ADD;\n }\n } else\n ret.code = KADM5_AUTH_INSUFFICIENT;\n if (ret.code != KADM5_OK) {\n /* okay to cast lengths to int because trunc_name limits max value */\n krb5_klog_syslog(LOG_NOTICE,\n _(\"Unauthorized request: kadm5_rename_principal, \"\n \"%.*s%s to %.*s%s, \"\n \"client=%.*s%s, service=%.*s%s, addr=%s\"),\n (int)tlen1, prime_arg1, tdots1,\n (int)tlen2, prime_arg2, tdots2,\n (int)clen, (char *)client_name.value, cdots,\n (int)slen, (char *)service_name.value, sdots,\n client_addr(rqstp->rq_xprt));\n } else {\n ret.code = kadm5_rename_principal((void *)handle, arg->src,\n arg->dest);\n if( ret.code != 0 )\n errmsg = krb5_get_error_message(handle->context, ret.code);\n\n /* okay to cast lengths to int because trunc_name limits max value */\n krb5_klog_syslog(LOG_NOTICE,\n _(\"Request: kadm5_rename_principal, \"\n \"%.*s%s to %.*s%s, %s, \"\n \"client=%.*s%s, service=%.*s%s, addr=%s\"),\n (int)tlen1, prime_arg1, tdots1,\n (int)tlen2, prime_arg2, tdots2,\n errmsg ? errmsg : _(\"success\"),\n (int)clen, (char *)client_name.value, cdots,\n (int)slen, (char *)service_name.value, sdots,\n client_addr(rqstp->rq_xprt));\n\n if (errmsg != NULL)\n krb5_free_error_message(handle->context, errmsg);\n\n }\n free(prime_arg1);\n free(prime_arg2);\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: generic_ret *init_2_svc(krb5_ui_4 *arg, struct svc_req *rqstp)\n{\n static generic_ret ret;\n gss_buffer_desc client_name,\n service_name;\n kadm5_server_handle_t handle;\n OM_uint32 minor_stat;\n const char *errmsg = NULL;\n size_t clen, slen;\n char *cdots, *sdots;\n\n xdr_free(xdr_generic_ret, &ret);\n\n if ((ret.code = new_server_handle(*arg, rqstp, &handle)))\n goto exit_func;\n if (! (ret.code = check_handle((void *)handle))) {\n ret.api_version = handle->api_version;\n }\n\n free_server_handle(handle);\n\n if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {\n ret.code = KADM5_FAILURE;\n goto exit_func;\n }\n\n if (ret.code != 0)\n errmsg = krb5_get_error_message(NULL, ret.code);\n\n clen = client_name.length;\n trunc_name(&clen, &cdots);\n slen = service_name.length;\n trunc_name(&slen, &sdots);\n /* okay to cast lengths to int because trunc_name limits max value */\n krb5_klog_syslog(LOG_NOTICE, _(\"Request: kadm5_init, %.*s%s, %s, \"\n \"client=%.*s%s, service=%.*s%s, addr=%s, \"\n \"vers=%d, flavor=%d\"),\n (int)clen, (char *)client_name.value, cdots,\n errmsg ? errmsg : _(\"success\"),\n (int)clen, (char *)client_name.value, cdots,\n (int)slen, (char *)service_name.value, sdots,\n client_addr(rqstp->rq_xprt),\n ret.api_version & ~(KADM5_API_VERSION_MASK),\n rqstp->rq_cred.oa_flavor);\n if (errmsg != NULL)\n krb5_free_error_message(NULL, errmsg);\n gss_release_buffer(&minor_stat, &client_name);\n gss_release_buffer(&minor_stat, &service_name);\n\nexit_func:\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: uint64 ReadCodedSizeValue(const binary * InBuffer, uint32 & BufferSize, uint64 & SizeUnknown)\n{\n binary SizeBitMask = 1 << 7;\n uint64 Result = 0x7F;\n unsigned int SizeIdx, PossibleSizeLength = 0;\n binary PossibleSize[8];\n memset(PossibleSize, 0, 8);\n\n SizeUnknown = 0x7F; // the last bit is discarded when computing the size\n for (SizeIdx = 0; SizeIdx < BufferSize && SizeIdx < 8; SizeIdx++) {\n if (InBuffer[0] & (SizeBitMask >> SizeIdx)) {\n // ID found\n PossibleSizeLength = SizeIdx + 1;\n SizeBitMask >>= SizeIdx;\n for (SizeIdx = 0; SizeIdx < PossibleSizeLength; SizeIdx++) {\n PossibleSize[SizeIdx] = InBuffer[SizeIdx];\n }\n for (SizeIdx = 0; SizeIdx < PossibleSizeLength - 1; SizeIdx++) {\n Result <<= 7;\n Result |= 0xFF;\n }\n\n Result = 0;\n Result |= PossibleSize[0] & ~SizeBitMask;\n for (unsigned int i = 1; i \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'EbmlElement: don't read beyond end of buffer when reading variable length integers'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (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_memory_stat(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC) /* {{{ */\n{\n\ttime_t timestamp = 0;\n\tphp_stream_memory_data *ms = (php_stream_memory_data*)stream->abstract;\n\tassert(ms != NULL);\n\n\tmemset(ssb, 0, sizeof(php_stream_statbuf));\n\t/* read-only across the board */\n\t\n\tssb->sb.st_mode = ms->mode & TEMP_STREAM_READONLY ? 0444 : 0666;\n\n\tssb->sb.st_size = ms->fsize;\n\tssb->sb.st_mode |= S_IFREG; /* regular file */\n\n#ifdef NETWARE\n\tssb->sb.st_mtime.tv_sec = timestamp;\n\tssb->sb.st_atime.tv_sec = timestamp;\n\tssb->sb.st_ctime.tv_sec = timestamp;\n#else\n\tssb->sb.st_mtime = timestamp;\n\tssb->sb.st_atime = timestamp;\n\tssb->sb.st_ctime = timestamp;\n#endif\n\n\tssb->sb.st_nlink = 1;\n\tssb->sb.st_rdev = -1;\n\t/* this is only for APC, so use /dev/null device - no chance of conflict there! */\n\tssb->sb.st_dev = 0xC;\n\t/* generate unique inode number for alias/filename, so no phars will conflict */\n\tssb->sb.st_ino = 0;\n\n#ifndef PHP_WIN32\n\tssb->sb.st_blksize = -1;\n#endif\n\n#if !defined(PHP_WIN32) && !defined(__BEOS__)\n\tssb->sb.st_blocks = -1;\n#endif\n\n\treturn 0;\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: int migrate_page_move_mapping(struct address_space *mapping,\n\t\tstruct page *newpage, struct page *page,\n\t\tstruct buffer_head *head, enum migrate_mode mode,\n\t\tint extra_count)\n{\n\tint expected_count = 1 + extra_count;\n\tvoid **pslot;\n\n\tif (!mapping) {\n\t\t/* Anonymous page without mapping */\n\t\tif (page_count(page) != expected_count)\n\t\t\treturn -EAGAIN;\n\n\t\t/* No turning back from here */\n\t\tset_page_memcg(newpage, page_memcg(page));\n\t\tnewpage->index = page->index;\n\t\tnewpage->mapping = page->mapping;\n\t\tif (PageSwapBacked(page))\n\t\t\tSetPageSwapBacked(newpage);\n\n\t\treturn MIGRATEPAGE_SUCCESS;\n\t}\n\n\tspin_lock_irq(&mapping->tree_lock);\n\n\tpslot = radix_tree_lookup_slot(&mapping->page_tree,\n \t\t\t\t\tpage_index(page));\n\n\texpected_count += 1 + page_has_private(page);\n\tif (page_count(page) != expected_count ||\n\t\tradix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) {\n\t\tspin_unlock_irq(&mapping->tree_lock);\n\t\treturn -EAGAIN;\n\t}\n\n\tif (!page_freeze_refs(page, expected_count)) {\n\t\tspin_unlock_irq(&mapping->tree_lock);\n\t\treturn -EAGAIN;\n\t}\n\n\t/*\n\t * In the async migration case of moving a page with buffers, lock the\n\t * buffers using trylock before the mapping is moved. If the mapping\n\t * was moved, we later failed to lock the buffers and could not move\n\t * the mapping back due to an elevated page count, we would have to\n\t * block waiting on other references to be dropped.\n\t */\n\tif (mode == MIGRATE_ASYNC && head &&\n\t\t\t!buffer_migrate_lock_buffers(head, mode)) {\n\t\tpage_unfreeze_refs(page, expected_count);\n\t\tspin_unlock_irq(&mapping->tree_lock);\n\t\treturn -EAGAIN;\n\t}\n\n\t/*\n\t * Now we know that no one else is looking at the page:\n\t * no turning back from here.\n\t */\n\tset_page_memcg(newpage, page_memcg(page));\n\tnewpage->index = page->index;\n\tnewpage->mapping = page->mapping;\n\tif (PageSwapBacked(page))\n\t\tSetPageSwapBacked(newpage);\n\n\tget_page(newpage);\t/* add cache reference */\n\tif (PageSwapCache(page)) {\n\t\tSetPageSwapCache(newpage);\n\t\tset_page_private(newpage, page_private(page));\n\t}\n\n\tradix_tree_replace_slot(pslot, newpage);\n\n\t/*\n\t * Drop cache reference from old page by unfreezing\n\t * to one less reference.\n\t * We know this isn't the last reference.\n\t */\n\tpage_unfreeze_refs(page, expected_count - 1);\n\n\t/*\n\t * If moved to a different zone then also account\n\t * the page for that zone. Other VM counters will be\n\t * taken care of when we establish references to the\n\t * new page and drop references to the old page.\n\t *\n\t * Note that anonymous pages are accounted for\n\t * via NR_FILE_PAGES and NR_ANON_PAGES if they\n\t * are mapped to swap space.\n\t */\n\t__dec_zone_page_state(page, NR_FILE_PAGES);\n\t__inc_zone_page_state(newpage, NR_FILE_PAGES);\n\tif (!PageSwapCache(page) && PageSwapBacked(page)) {\n\t\t__dec_zone_page_state(page, NR_SHMEM);\n\t\t__inc_zone_page_state(newpage, NR_SHMEM);\n\t}\n\tspin_unlock_irq(&mapping->tree_lock);\n\n\treturn MIGRATEPAGE_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'mm: migrate dirty page without clear_page_dirty_for_io etc\n\nclear_page_dirty_for_io() has accumulated writeback and memcg subtleties\nsince v2.6.16 first introduced page migration; and the set_page_dirty()\nwhich completed its migration of PageDirty, later had to be moderated to\n__set_page_dirty_nobuffers(); then PageSwapBacked had to skip that too.\n\nNo actual problems seen with this procedure recently, but if you look into\nwhat the clear_page_dirty_for_io(page)+set_page_dirty(newpage) is actually\nachieving, it turns out to be nothing more than moving the PageDirty flag,\nand its NR_FILE_DIRTY stat from one zone to another.\n\nIt would be good to avoid a pile of irrelevant decrementations and\nincrementations, and improper event counting, and unnecessary descent of\nthe radix_tree under tree_lock (to set the PAGECACHE_TAG_DIRTY which\nradix_tree_replace_slot() left in place anyway).\n\nDo the NR_FILE_DIRTY movement, like the other stats movements, while\ninterrupts still disabled in migrate_page_move_mapping(); and don't even\nbother if the zone is the same. Do the PageDirty movement there under\ntree_lock too, where old page is frozen and newpage not yet visible:\nbearing in mind that as soon as newpage becomes visible in radix_tree, an\nun-page-locked set_page_dirty() might interfere (or perhaps that's just\nnot possible: anything doing so should already hold an additional\nreference to the old page, preventing its migration; but play safe).\n\nBut we do still need to transfer PageDirty in migrate_page_copy(), for\nthose who don't go the mapping route through migrate_page_move_mapping().\n\nSigned-off-by: Hugh Dickins \nCc: Christoph Lameter \nCc: \"Kirill A. Shutemov\" \nCc: Rik van Riel \nCc: Vlastimil Babka \nCc: Davidlohr Bueso \nCc: Oleg Nesterov \nCc: Sasha Levin \nCc: Dmitry Vyukov \nCc: KOSAKI Motohiro \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int snd_seq_ioctl_remove_events(struct snd_seq_client *client,\n\t\t\t\t void __user *arg)\n{\n\tstruct snd_seq_remove_events info;\n\n\tif (copy_from_user(&info, arg, sizeof(info)))\n\t\treturn -EFAULT;\n\n\t/*\n\t * Input mostly not implemented XXX.\n\t */\n\tif (info.remove_mode & SNDRV_SEQ_REMOVE_INPUT) {\n\t\t/*\n\t\t * No restrictions so for a user client we can clear\n\t\t * the whole fifo\n\t\t */\n\t\tif (client->type == USER_CLIENT)\n\t\t\tsnd_seq_fifo_clear(client->data.user.fifo);\n\t}\n\n\tif (info.remove_mode & SNDRV_SEQ_REMOVE_OUTPUT)\n\t\tsnd_seq_queue_remove_cells(client->number, &info);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'ALSA: seq: Fix missing NULL check at remove_events ioctl\n\nsnd_seq_ioctl_remove_events() calls snd_seq_fifo_clear()\nunconditionally even if there is no FIFO assigned, and this leads to\nan Oops due to NULL dereference. The fix is just to add a proper NULL\ncheck.\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_timer_start_slave(struct snd_timer_instance *timeri)\n{\n\tunsigned long flags;\n\n\tspin_lock_irqsave(&slave_active_lock, flags);\n\ttimeri->flags |= SNDRV_TIMER_IFLG_RUNNING;\n\tif (timeri->master)\n\t\tlist_add_tail(&timeri->active_list,\n\t\t\t &timeri->master->slave_active_head);\n\tspin_unlock_irqrestore(&slave_active_lock, flags);\n\treturn 1; /* delayed start */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-200', 'CWE-362'], 'message': 'ALSA: timer: Harden slave timer list handling\n\nA slave timer instance might be still accessible in a racy way while\noperating the master instance as it lacks of locking. Since the\nmaster operation is mostly protected with timer->lock, we should cope\nwith it while changing the slave instance, too. Also, some linked\nlists (active_list and ack_list) of slave instances aren't unlinked\nimmediately at stopping or closing, and this may lead to unexpected\naccesses.\n\nThis patch tries to address these issues. It adds spin lock of\ntimer->lock (either from master or slave, which is equivalent) in a\nfew places. For avoiding a deadlock, we ensure that the global\nslave_active_lock is always locked at first before each timer lock.\n\nAlso, ack and active_list of slave instances are properly unlinked at\nsnd_timer_stop() and snd_timer_close().\n\nLast but not least, remove the superfluous call of _snd_timer_stop()\nat removing slave links. This is a noop, and calling it may confuse\nreaders wrt locking. Further cleanup will follow in a later patch.\n\nActually we've got reports of use-after-free by syzkaller fuzzer, and\nthis hopefully fixes these issues.\n\nReported-by: Dmitry Vyukov \nCc: \nSigned-off-by: Takashi Iwai '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void rng_backend_request_entropy(RngBackend *s, size_t size,\n EntropyReceiveFunc *receive_entropy,\n void *opaque)\n{\n RngBackendClass *k = RNG_BACKEND_GET_CLASS(s);\n\n if (k->request_entropy) {\n k->request_entropy(s, size, receive_entropy, opaque);\n }\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: int make_http_soap_request(zval *this_ptr,\n zend_string *buf,\n char *location,\n char *soapaction,\n int soap_version,\n zval *return_value)\n{\n\tzend_string *request;\n\tsmart_str soap_headers = {0};\n\tsmart_str soap_headers_z = {0};\n\tint err;\n\tphp_url *phpurl = NULL;\n\tphp_stream *stream;\n\tzval *trace, *tmp;\n\tint use_proxy = 0;\n\tint use_ssl;\n\tzend_string *http_body;\n\tchar *content_type, *http_version, *cookie_itt;\n\tint http_close;\n\tzend_string *http_headers;\n\tchar *connection;\n\tint http_1_1;\n\tint http_status;\n\tint content_type_xml = 0;\n\tzend_long redirect_max = 20;\n\tchar *content_encoding;\n\tchar *http_msg = NULL;\n\tzend_bool old_allow_url_fopen;\n\tphp_stream_context *context = NULL;\n\tzend_bool has_authorization = 0;\n\tzend_bool has_proxy_authorization = 0;\n\tzend_bool has_cookies = 0;\n\n\tif (this_ptr == NULL || Z_TYPE_P(this_ptr) != IS_OBJECT) {\n\t\treturn FALSE;\n\t}\n\n\trequest = buf;\n\t/* Compress request */\n\tif ((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), \"compression\", sizeof(\"compression\")-1)) != NULL && Z_TYPE_P(tmp) == IS_LONG) {\n\t\tint level = Z_LVAL_P(tmp) & 0x0f;\n\t\tint kind = Z_LVAL_P(tmp) & SOAP_COMPRESSION_DEFLATE;\n\n\t\tif (level > 9) {level = 9;}\n\n\t if ((Z_LVAL_P(tmp) & SOAP_COMPRESSION_ACCEPT) != 0) {\n\t\t\tsmart_str_append_const(&soap_headers_z,\"Accept-Encoding: gzip, deflate\\r\\n\");\n\t }\n\t if (level > 0) {\n\t\t\tzval func;\n\t\t\tzval retval;\n\t\t\tzval params[3];\n\t\t\tint n;\n\n\t\t\tZVAL_STR_COPY(¶ms[0], buf);\n\t\t\tZVAL_LONG(¶ms[1], level);\n\t\t\tif (kind == SOAP_COMPRESSION_DEFLATE) {\n\t\t\t\tn = 2;\n\t\t\t\tZVAL_STRING(&func, \"gzcompress\");\n\t\t\t\tsmart_str_append_const(&soap_headers_z,\"Content-Encoding: deflate\\r\\n\");\n\t\t\t} else {\n\t\t\t\tn = 3;\n\t\t\t\tZVAL_STRING(&func, \"gzencode\");\n\t\t\t\tsmart_str_append_const(&soap_headers_z,\"Content-Encoding: gzip\\r\\n\");\n\t\t\t\tZVAL_LONG(¶ms[2], 0x1f);\n\t\t\t}\n\t\t\tif (call_user_function(CG(function_table), (zval*)NULL, &func, &retval, n, params) == SUCCESS &&\n\t\t\t Z_TYPE(retval) == IS_STRING) {\n\t\t\t\tzval_ptr_dtor(¶ms[0]);\n\t\t\t\tzval_ptr_dtor(&func);\n\t\t\t\trequest = Z_STR(retval);\n\t\t\t} else {\n\t\t\t\tzval_ptr_dtor(¶ms[0]);\n\t\t\t\tzval_ptr_dtor(&func);\n\t\t\t\tif (request != buf) {\n\t\t\t\t\tzend_string_release(request);\n\t\t\t\t}\n\t\t\t\tsmart_str_free(&soap_headers_z);\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t }\n\t}\n\n\tif ((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), \"httpsocket\", sizeof(\"httpsocket\")-1)) != NULL) {\n\t\tphp_stream_from_zval_no_verify(stream,tmp);\n\t\tif ((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), \"_use_proxy\", sizeof(\"_use_proxy\")-1)) != NULL && Z_TYPE_P(tmp) == IS_LONG) {\n\t\t\tuse_proxy = Z_LVAL_P(tmp);\n\t\t}\n\t} else {\n\t\tstream = NULL;\n\t}\n\n\tif (location != NULL && location[0] != '\\000') {\n\t\tphpurl = php_url_parse(location);\n\t}\n\n\tif (NULL != (tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr),\n\t\t\t\"_stream_context\", sizeof(\"_stream_context\")-1))) {\n\t\tcontext = php_stream_context_from_zval(tmp, 0);\n\t}\n\n\tif (context &&\n\t\t(tmp = php_stream_context_get_option(context, \"http\", \"max_redirects\")) != NULL) {\n\t\tif (Z_TYPE_P(tmp) != IS_STRING || !is_numeric_string(Z_STRVAL_P(tmp), Z_STRLEN_P(tmp), &redirect_max, NULL, 1)) {\n\t\t\tif (Z_TYPE_P(tmp) == IS_LONG)\n\t\t\t\tredirect_max = Z_LVAL_P(tmp);\n\t\t}\n\t}\n\ntry_again:\n\tif (phpurl == NULL || phpurl->host == NULL) {\n\t if (phpurl != NULL) {php_url_free(phpurl);}\n\t\tif (request != buf) {\n\t\t\tzend_string_release(request);\n\t\t}\n\t\tadd_soap_fault(this_ptr, \"HTTP\", \"Unable to parse URL\", NULL, NULL);\n\t\tsmart_str_free(&soap_headers_z);\n\t\treturn FALSE;\n\t}\n\n\tuse_ssl = 0;\n\tif (phpurl->scheme != NULL && strcmp(phpurl->scheme, \"https\") == 0) {\n\t\tuse_ssl = 1;\n\t} else if (phpurl->scheme == NULL || strcmp(phpurl->scheme, \"http\") != 0) {\n\t\tphp_url_free(phpurl);\n\t\tif (request != buf) {\n\t\t\tzend_string_release(request);\n\t\t}\n\t\tadd_soap_fault(this_ptr, \"HTTP\", \"Unknown protocol. Only http and https are allowed.\", NULL, NULL);\n\t\tsmart_str_free(&soap_headers_z);\n\t\treturn FALSE;\n\t}\n\n\told_allow_url_fopen = PG(allow_url_fopen);\n\tPG(allow_url_fopen) = 1;\n\tif (use_ssl && php_stream_locate_url_wrapper(\"https://\", NULL, STREAM_LOCATE_WRAPPERS_ONLY) == NULL) {\n\t\tphp_url_free(phpurl);\n\t\tif (request != buf) {\n\t\t\tzend_string_release(request);\n\t\t}\n\t\tadd_soap_fault(this_ptr, \"HTTP\", \"SSL support is not available in this build\", NULL, NULL);\n\t\tPG(allow_url_fopen) = old_allow_url_fopen;\n\t\tsmart_str_free(&soap_headers_z);\n\t\treturn FALSE;\n\t}\n\n\tif (phpurl->port == 0) {\n\t\tphpurl->port = use_ssl ? 443 : 80;\n\t}\n\n\t/* Check if request to the same host */\n\tif (stream != NULL) {\n\t php_url *orig;\n\t\tif ((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), \"httpurl\", sizeof(\"httpurl\")-1)) != NULL &&\n\t\t (orig = (php_url *) zend_fetch_resource_ex(tmp, \"httpurl\", le_url)) != NULL &&\n\t\t ((use_proxy && !use_ssl) ||\n\t\t (((use_ssl && orig->scheme != NULL && strcmp(orig->scheme, \"https\") == 0) ||\n\t\t (!use_ssl && orig->scheme == NULL) ||\n\t\t (!use_ssl && strcmp(orig->scheme, \"https\") != 0)) &&\n\t\t strcmp(orig->host, phpurl->host) == 0 &&\n\t\t orig->port == phpurl->port))) {\n } else {\n\t\t\tphp_stream_close(stream);\n\t\t\tzend_hash_str_del(Z_OBJPROP_P(this_ptr), \"httpurl\", sizeof(\"httpurl\")-1);\n\t\t\tzend_hash_str_del(Z_OBJPROP_P(this_ptr), \"httpsocket\", sizeof(\"httpsocket\")-1);\n\t\t\tzend_hash_str_del(Z_OBJPROP_P(this_ptr), \"_use_proxy\", sizeof(\"_use_proxy\")-1);\n\t\t\tstream = NULL;\n\t\t\tuse_proxy = 0;\n }\n\t}\n\n\t/* Check if keep-alive connection is still opened */\n\tif (stream != NULL && php_stream_eof(stream)) {\n\t\tphp_stream_close(stream);\n\t\tzend_hash_str_del(Z_OBJPROP_P(this_ptr), \"httpurl\", sizeof(\"httpurl\")-1);\n\t\tzend_hash_str_del(Z_OBJPROP_P(this_ptr), \"httpsocket\", sizeof(\"httpsocket\")-1);\n\t\tzend_hash_str_del(Z_OBJPROP_P(this_ptr), \"_use_proxy\", sizeof(\"_use_proxy\")-1);\n\t\tstream = NULL;\n\t\tuse_proxy = 0;\n\t}\n\n\tif (!stream) {\n\t\tstream = http_connect(this_ptr, phpurl, use_ssl, context, &use_proxy);\n\t\tif (stream) {\n\t\t\tphp_stream_auto_cleanup(stream);\n\t\t\tadd_property_resource(this_ptr, \"httpsocket\", stream->res);\n\t\t\tGC_REFCOUNT(stream->res)++;\n\t\t\tadd_property_long(this_ptr, \"_use_proxy\", use_proxy);\n\t\t} else {\n\t\t\tphp_url_free(phpurl);\n\t\t\tif (request != buf) {\n\t\t\t\tzend_string_release(request);\n\t\t\t}\n\t\t\tadd_soap_fault(this_ptr, \"HTTP\", \"Could not connect to host\", NULL, NULL);\n\t\t\tPG(allow_url_fopen) = old_allow_url_fopen;\n\t\t\tsmart_str_free(&soap_headers_z);\n\t\t\treturn FALSE;\n\t\t}\n\t}\n\tPG(allow_url_fopen) = old_allow_url_fopen;\n\n\tif (stream) {\n\t\tzval *cookies, *login, *password;\n\t\tzend_resource *ret = zend_register_resource(phpurl, le_url);\n\n\t\tadd_property_resource(this_ptr, \"httpurl\", ret);\n\t\tGC_REFCOUNT(ret)++;\n\t\t/*zend_list_addref(ret);*/\n\n\t\tif (context &&\n\t\t (tmp = php_stream_context_get_option(context, \"http\", \"protocol_version\")) != NULL &&\n\t\t Z_TYPE_P(tmp) == IS_DOUBLE &&\n\t\t Z_DVAL_P(tmp) == 1.0) {\n\t\t\thttp_1_1 = 0;\n\t\t} else {\n\t\t\thttp_1_1 = 1;\n\t\t}\n\n\t\tsmart_str_append_const(&soap_headers, \"POST \");\n\t\tif (use_proxy && !use_ssl) {\n\t\t\tsmart_str_appends(&soap_headers, phpurl->scheme);\n\t\t\tsmart_str_append_const(&soap_headers, \"://\");\n\t\t\tsmart_str_appends(&soap_headers, phpurl->host);\n\t\t\tsmart_str_appendc(&soap_headers, ':');\n\t\t\tsmart_str_append_unsigned(&soap_headers, phpurl->port);\n\t\t}\n\t\tif (phpurl->path) {\n\t\t\tsmart_str_appends(&soap_headers, phpurl->path);\n\t\t} else {\n\t\t\tsmart_str_appendc(&soap_headers, '/');\n\t\t}\n\t\tif (phpurl->query) {\n\t\t\tsmart_str_appendc(&soap_headers, '?');\n\t\t\tsmart_str_appends(&soap_headers, phpurl->query);\n\t\t}\n\t\tif (phpurl->fragment) {\n\t\t\tsmart_str_appendc(&soap_headers, '#');\n\t\t\tsmart_str_appends(&soap_headers, phpurl->fragment);\n\t\t}\n\t\tif (http_1_1) {\n\t\t\tsmart_str_append_const(&soap_headers, \" HTTP/1.1\\r\\n\");\n\t\t} else {\n\t\t\tsmart_str_append_const(&soap_headers, \" HTTP/1.0\\r\\n\");\n\t\t}\n\t\tsmart_str_append_const(&soap_headers, \"Host: \");\n\t\tsmart_str_appends(&soap_headers, phpurl->host);\n\t\tif (phpurl->port != (use_ssl?443:80)) {\n\t\t\tsmart_str_appendc(&soap_headers, ':');\n\t\t\tsmart_str_append_unsigned(&soap_headers, phpurl->port);\n\t\t}\n\t\tif (!http_1_1 ||\n\t\t\t((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), \"_keep_alive\", sizeof(\"_keep_alive\")-1)) != NULL &&\n\t\t\t (Z_TYPE_P(tmp) == IS_FALSE || (Z_TYPE_P(tmp) == IS_LONG && Z_LVAL_P(tmp) == 0)))) {\n\t\t\tsmart_str_append_const(&soap_headers, \"\\r\\n\"\n\t\t\t\t\"Connection: close\\r\\n\");\n\t\t} else {\n\t\t\tsmart_str_append_const(&soap_headers, \"\\r\\n\"\n\t\t\t\t\"Connection: Keep-Alive\\r\\n\");\n\t\t}\n\t\tif ((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), \"_user_agent\", sizeof(\"_user_agent\")-1)) != NULL &&\n\t\t Z_TYPE_P(tmp) == IS_STRING) {\n\t\t\tif (Z_STRLEN_P(tmp) > 0) {\n\t\t\t\tsmart_str_append_const(&soap_headers, \"User-Agent: \");\n\t\t\t\tsmart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));\n\t\t\t\tsmart_str_append_const(&soap_headers, \"\\r\\n\");\n\t\t\t}\n\t\t} else if (context &&\n\t\t (tmp = php_stream_context_get_option(context, \"http\", \"user_agent\")) != NULL &&\n\t\t Z_TYPE_P(tmp) == IS_STRING) {\n\t\t\tif (Z_STRLEN_P(tmp) > 0) {\n\t\t\t\tsmart_str_append_const(&soap_headers, \"User-Agent: \");\n\t\t\t\tsmart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));\n\t\t\t\tsmart_str_append_const(&soap_headers, \"\\r\\n\");\n\t\t\t}\n\t\t} else if (FG(user_agent)) {\n\t\t\tsmart_str_append_const(&soap_headers, \"User-Agent: \");\n\t\t\tsmart_str_appends(&soap_headers, FG(user_agent));\n\t\t\tsmart_str_append_const(&soap_headers, \"\\r\\n\");\n\t\t} else {\n\t\t\tsmart_str_append_const(&soap_headers, \"User-Agent: PHP-SOAP/\"PHP_VERSION\"\\r\\n\");\n\t\t}\n\n\t\tsmart_str_append_smart_str(&soap_headers, &soap_headers_z);\n\n\t\tif (soap_version == SOAP_1_2) {\n\t\t\tsmart_str_append_const(&soap_headers,\"Content-Type: application/soap+xml; charset=utf-8\");\n\t\t\tif (soapaction) {\n\t\t\t\tsmart_str_append_const(&soap_headers,\"; action=\\\"\");\n\t\t\t\tsmart_str_appends(&soap_headers, soapaction);\n\t\t\t\tsmart_str_append_const(&soap_headers,\"\\\"\");\n\t\t\t}\n\t\t\tsmart_str_append_const(&soap_headers,\"\\r\\n\");\n\t\t} else {\n\t\t\tsmart_str_append_const(&soap_headers,\"Content-Type: text/xml; charset=utf-8\\r\\n\");\n\t\t\tif (soapaction) {\n\t\t\t\tsmart_str_append_const(&soap_headers, \"SOAPAction: \\\"\");\n\t\t\t\tsmart_str_appends(&soap_headers, soapaction);\n\t\t\t\tsmart_str_append_const(&soap_headers, \"\\\"\\r\\n\");\n\t\t\t}\n\t\t}\n\t\tsmart_str_append_const(&soap_headers,\"Content-Length: \");\n\t\tsmart_str_append_long(&soap_headers, request->len);\n\t\tsmart_str_append_const(&soap_headers, \"\\r\\n\");\n\n\t\t/* HTTP Authentication */\n\t\tif ((login = zend_hash_str_find(Z_OBJPROP_P(this_ptr), \"_login\", sizeof(\"_login\")-1)) != NULL &&\n\t\t Z_TYPE_P(login) == IS_STRING) {\n\t\t\tzval *digest;\n\n\t\t\thas_authorization = 1;\n\t\t\tif ((digest = zend_hash_str_find(Z_OBJPROP_P(this_ptr), \"_digest\", sizeof(\"_digest\")-1)) != NULL) {\n\t\t\t\tif (Z_TYPE_P(digest) == IS_ARRAY) {\n\t\t\t\t\tchar HA1[33], HA2[33], response[33], cnonce[33], nc[9];\n\t\t\t\t\tPHP_MD5_CTX md5ctx;\n\t\t\t\t\tunsigned char hash[16];\n\n\t\t\t\t\tPHP_MD5Init(&md5ctx);\n\t\t\t\t\tsnprintf(cnonce, sizeof(cnonce), ZEND_LONG_FMT, php_rand());\n\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)cnonce, strlen(cnonce));\n\t\t\t\t\tPHP_MD5Final(hash, &md5ctx);\n\t\t\t\t\tmake_digest(cnonce, hash);\n\n\t\t\t\t\tif ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), \"nc\", sizeof(\"nc\")-1)) != NULL &&\n\t\t\t\t\t Z_TYPE_P(tmp) == IS_LONG) {\n\t\t\t\t\t\tZ_LVAL_P(tmp)++;\n\t\t\t\t\t\tsnprintf(nc, sizeof(nc), \"%08ld\", Z_LVAL_P(tmp));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tadd_assoc_long(digest, \"nc\", 1);\n\t\t\t\t\t\tstrcpy(nc, \"00000001\");\n\t\t\t\t\t}\n\n\t\t\t\t\tPHP_MD5Init(&md5ctx);\n\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_P(login), Z_STRLEN_P(login));\n\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\":\", 1);\n\t\t\t\t\tif ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), \"realm\", sizeof(\"realm\")-1)) != NULL &&\n\t\t\t\t\t Z_TYPE_P(tmp) == IS_STRING) {\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));\n\t\t\t\t\t}\n\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\":\", 1);\n\t\t\t\t\tif ((password = zend_hash_str_find(Z_OBJPROP_P(this_ptr), \"_password\", sizeof(\"_password\")-1)) != NULL &&\n\t\t\t\t\t Z_TYPE_P(password) == IS_STRING) {\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_P(password), Z_STRLEN_P(password));\n\t\t\t\t\t}\n\t\t\t\t\tPHP_MD5Final(hash, &md5ctx);\n\t\t\t\t\tmake_digest(HA1, hash);\n\t\t\t\t\tif ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), \"algorithm\", sizeof(\"algorithm\")-1)) != NULL &&\n\t\t\t\t\t Z_TYPE_P(tmp) == IS_STRING &&\n\t\t\t\t\t Z_STRLEN_P(tmp) == sizeof(\"md5-sess\")-1 &&\n\t\t\t\t\t stricmp(Z_STRVAL_P(tmp), \"md5-sess\") == 0) {\n\t\t\t\t\t\tPHP_MD5Init(&md5ctx);\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)HA1, 32);\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\":\", 1);\n\t\t\t\t\t\tif ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), \"nonce\", sizeof(\"nonce\")-1)) != NULL &&\n\t\t\t\t\t\t Z_TYPE_P(tmp) == IS_STRING) {\n\t\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\":\", 1);\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)cnonce, 8);\n\t\t\t\t\t\tPHP_MD5Final(hash, &md5ctx);\n\t\t\t\t\t\tmake_digest(HA1, hash);\n\t\t\t\t\t}\n\n\t\t\t\t\tPHP_MD5Init(&md5ctx);\n\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\"POST:\", sizeof(\"POST:\")-1);\n\t\t\t\t\tif (phpurl->path) {\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)phpurl->path, strlen(phpurl->path));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\"/\", 1);\n\t\t\t\t\t}\n\t\t\t\t\tif (phpurl->query) {\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\"?\", 1);\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)phpurl->query, strlen(phpurl->query));\n\t\t\t\t\t}\n\n\t\t\t\t\t/* TODO: Support for qop=\"auth-int\" */\n/*\n\t\t\t\t\tif (zend_hash_find(Z_ARRVAL_PP(digest), \"qop\", sizeof(\"qop\"), (void **)&tmp) == SUCCESS &&\n\t\t\t\t\t Z_TYPE_PP(tmp) == IS_STRING &&\n\t\t\t\t\t Z_STRLEN_PP(tmp) == sizeof(\"auth-int\")-1 &&\n\t\t\t\t\t stricmp(Z_STRVAL_PP(tmp), \"auth-int\") == 0) {\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, \":\", 1);\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, HEntity, HASHHEXLEN);\n\t\t\t\t\t}\n*/\n\t\t\t\t\tPHP_MD5Final(hash, &md5ctx);\n\t\t\t\t\tmake_digest(HA2, hash);\n\n\t\t\t\t\tPHP_MD5Init(&md5ctx);\n\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)HA1, 32);\n\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\":\", 1);\n\t\t\t\t\tif ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), \"nonce\", sizeof(\"nonce\")-1)) != NULL &&\n\t\t\t\t\t Z_TYPE_P(tmp) == IS_STRING) {\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));\n\t\t\t\t\t}\n\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\":\", 1);\n\t\t\t\t\tif ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), \"qop\", sizeof(\"qop\")-1)) != NULL &&\n\t\t\t\t\t Z_TYPE_P(tmp) == IS_STRING) {\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)nc, 8);\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\":\", 1);\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)cnonce, 8);\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\":\", 1);\n\t\t\t\t\t\t/* TODO: Support for qop=\"auth-int\" */\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\"auth\", sizeof(\"auth\")-1);\n\t\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)\":\", 1);\n\t\t\t\t\t}\n\t\t\t\t\tPHP_MD5Update(&md5ctx, (unsigned char*)HA2, 32);\n\t\t\t\t\tPHP_MD5Final(hash, &md5ctx);\n\t\t\t\t\tmake_digest(response, hash);\n\n\t\t\t\t\tsmart_str_append_const(&soap_headers, \"Authorization: Digest username=\\\"\");\n\t\t\t\t\tsmart_str_appendl(&soap_headers, Z_STRVAL_P(login), Z_STRLEN_P(login));\n\t\t\t\t\tif ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), \"realm\", sizeof(\"realm\")-1)) != NULL &&\n\t\t\t\t\t Z_TYPE_P(tmp) == IS_STRING) {\n\t\t\t\t\t\tsmart_str_append_const(&soap_headers, \"\\\", realm=\\\"\");\n\t\t\t\t\t\tsmart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));\n\t\t\t\t\t}\n\t\t\t\tif ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), \"nonce\", sizeof(\"nonce\")-1)) != NULL &&\n\t\t\t\t\t Z_TYPE_P(tmp) == IS_STRING) {\n\t\t\t\t\t\tsmart_str_append_const(&soap_headers, \"\\\", nonce=\\\"\");\n\t\t\t\t\t\tsmart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));\n\t\t\t\t\t}\n\t\t\t\t\tsmart_str_append_const(&soap_headers, \"\\\", uri=\\\"\");\n\t\t\t\t\tif (phpurl->path) {\n\t\t\t\t\t\tsmart_str_appends(&soap_headers, phpurl->path);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsmart_str_appendc(&soap_headers, '/');\n\t\t\t\t\t}\n\t\t\t\t\tif (phpurl->query) {\n\t\t\t\t\t\tsmart_str_appendc(&soap_headers, '?');\n\t\t\t\t\t\tsmart_str_appends(&soap_headers, phpurl->query);\n\t\t\t\t\t}\n\t\t\t\t\tif (phpurl->fragment) {\n\t\t\t\t\t\tsmart_str_appendc(&soap_headers, '#');\n\t\t\t\t\t\tsmart_str_appends(&soap_headers, phpurl->fragment);\n\t\t\t\t\t}\n\t\t\t\t\tif ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), \"qop\", sizeof(\"qop\")-1)) != NULL &&\n\t\t\t\t\t Z_TYPE_P(tmp) == IS_STRING) {\n\t\t\t\t\t/* TODO: Support for qop=\"auth-int\" */\n\t\t\t\t\t\tsmart_str_append_const(&soap_headers, \"\\\", qop=\\\"auth\");\n\t\t\t\t\t\tsmart_str_append_const(&soap_headers, \"\\\", nc=\\\"\");\n\t\t\t\t\t\tsmart_str_appendl(&soap_headers, nc, 8);\n\t\t\t\t\t\tsmart_str_append_const(&soap_headers, \"\\\", cnonce=\\\"\");\n\t\t\t\t\t\tsmart_str_appendl(&soap_headers, cnonce, 8);\n\t\t\t\t\t}\n\t\t\t\t\tsmart_str_append_const(&soap_headers, \"\\\", response=\\\"\");\n\t\t\t\t\tsmart_str_appendl(&soap_headers, response, 32);\n\t\t\t\t\tif ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), \"opaque\", sizeof(\"opaque\")-1)) != NULL &&\n\t\t\t\t\t Z_TYPE_P(tmp) == IS_STRING) {\n\t\t\t\t\t\tsmart_str_append_const(&soap_headers, \"\\\", opaque=\\\"\");\n\t\t\t\t\t\tsmart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));\n\t\t\t\t\t}\n\t\t\t\t\tif ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), \"algorithm\", sizeof(\"algorithm\")-1)) != NULL &&\n\t\t\t\t\t\tZ_TYPE_P(tmp) == IS_STRING) {\n\t\t\t\t\t\tsmart_str_append_const(&soap_headers, \"\\\", algorithm=\\\"\");\n\t\t\t\t\t\tsmart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));\n\t\t\t\t\t}\n\t\t\t\t\tsmart_str_append_const(&soap_headers, \"\\\"\\r\\n\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tzend_string *buf;\n\n\t\t\t\tsmart_str auth = {0};\n\t\t\t\tsmart_str_appendl(&auth, Z_STRVAL_P(login), Z_STRLEN_P(login));\n\t\t\t\tsmart_str_appendc(&auth, ':');\n\t\t\t\tif ((password = zend_hash_str_find(Z_OBJPROP_P(this_ptr), \"_password\", sizeof(\"_password\")-1)) != NULL &&\n\t\t\t\t Z_TYPE_P(password) == IS_STRING) {\n\t\t\t\t\tsmart_str_appendl(&auth, Z_STRVAL_P(password), Z_STRLEN_P(password));\n\t\t\t\t}\n\t\t\t\tsmart_str_0(&auth);\n\t\t\t\tbuf = php_base64_encode((unsigned char*)ZSTR_VAL(auth.s), ZSTR_LEN(auth.s));\n\t\t\t\tsmart_str_append_const(&soap_headers, \"Authorization: Basic \");\n\t\t\t\tsmart_str_appendl(&soap_headers, (char*)ZSTR_VAL(buf), ZSTR_LEN(buf));\n\t\t\t\tsmart_str_append_const(&soap_headers, \"\\r\\n\");\n\t\t\t\tzend_string_release(buf);\n\t\t\t\tsmart_str_free(&auth);\n\t\t\t}\n\t\t}\n\n\t\t/* Proxy HTTP Authentication */\n\t\tif (use_proxy && !use_ssl) {\n\t\t\thas_proxy_authorization = proxy_authentication(this_ptr, &soap_headers);\n\t\t}\n\n\t\t/* Send cookies along with request */\n\t\tif ((cookies = zend_hash_str_find(Z_OBJPROP_P(this_ptr), \"_cookies\", sizeof(\"_cookies\")-1)) != NULL &&\n\t\t Z_TYPE_P(cookies) == IS_ARRAY) {\n\t\t\tzval *data;\n\t\t\tzend_string *key;\n\t\t\tint i, n;\n\n\t\t\thas_cookies = 1;\n\t\t\tn = zend_hash_num_elements(Z_ARRVAL_P(cookies));\n\t\t\tif (n > 0) {\n\t\t\t\tzend_hash_internal_pointer_reset(Z_ARRVAL_P(cookies));\n\t\t\t\tsmart_str_append_const(&soap_headers, \"Cookie: \");\n\t\t\t\tfor (i = 0; i < n; i++) {\n\t\t\t\t\tzend_ulong numindx;\n\t\t\t\t\tint res = zend_hash_get_current_key(Z_ARRVAL_P(cookies), &key, &numindx);\n\t\t\t\t\tdata = zend_hash_get_current_data(Z_ARRVAL_P(cookies));\n\t\t\t\t\t\n\t\t\t\t\tif (res == HASH_KEY_IS_STRING && Z_TYPE_P(data) == IS_ARRAY) {\n\t\t\t\t\t zval *value;\n\n\t\t\t\t\t\tif ((value = zend_hash_index_find(Z_ARRVAL_P(data), 0)) != NULL &&\n\t\t\t\t\t\t Z_TYPE_P(value) == IS_STRING) {\n\t\t\t\t\t\t zval *tmp;\n\t\t\t\t\t\t if (((tmp = zend_hash_index_find(Z_ARRVAL_P(data), 1)) == NULL ||\n\t\t\t\t\t\t strncmp(phpurl->path?phpurl->path:\"/\",Z_STRVAL_P(tmp),Z_STRLEN_P(tmp)) == 0) &&\n\t\t\t\t\t\t ((tmp = zend_hash_index_find(Z_ARRVAL_P(data), 2)) == NULL ||\n\t\t\t\t\t\t in_domain(phpurl->host,Z_STRVAL_P(tmp))) &&\n\t\t\t\t\t\t (use_ssl || (tmp = zend_hash_index_find(Z_ARRVAL_P(data), 3)) == NULL)) {\n\t\t\t\t\t\t\t\tsmart_str_append(&soap_headers, key);\n\t\t\t\t\t\t\t\tsmart_str_appendc(&soap_headers, '=');\n\t\t\t\t\t\t\t\tsmart_str_append(&soap_headers, Z_STR_P(value));\n\t\t\t\t\t\t\t\tsmart_str_appendc(&soap_headers, ';');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tzend_hash_move_forward(Z_ARRVAL_P(cookies));\n\t\t\t\t}\n\t\t\t\tsmart_str_append_const(&soap_headers, \"\\r\\n\");\n\t\t\t}\n\t\t}\n\n\t\thttp_context_headers(context, has_authorization, has_proxy_authorization, has_cookies, &soap_headers);\n\n\t\tsmart_str_append_const(&soap_headers, \"\\r\\n\");\n\t\tsmart_str_0(&soap_headers);\n\t\tif ((trace = zend_hash_str_find(Z_OBJPROP_P(this_ptr), \"trace\", sizeof(\"trace\")-1)) != NULL &&\n\t\t (Z_TYPE_P(trace) == IS_TRUE || (Z_TYPE_P(trace) == IS_LONG && Z_LVAL_P(trace) != 0))) {\n\t\t\tadd_property_stringl(this_ptr, \"__last_request_headers\", ZSTR_VAL(soap_headers.s), ZSTR_LEN(soap_headers.s));\n\t\t}\n\t\tsmart_str_appendl(&soap_headers, request->val, request->len);\n\t\tsmart_str_0(&soap_headers);\n\n\t\terr = php_stream_write(stream, ZSTR_VAL(soap_headers.s), ZSTR_LEN(soap_headers.s));\n\t\tif (err != ZSTR_LEN(soap_headers.s)) {\n\t\t\tif (request != buf) {\n\t\t\t\tzend_string_release(request);\n\t\t\t}\n\t\t\tphp_stream_close(stream);\n\t\t\tzend_hash_str_del(Z_OBJPROP_P(this_ptr), \"httpurl\", sizeof(\"httpurl\")-1);\n\t\t\tzend_hash_str_del(Z_OBJPROP_P(this_ptr), \"httpsocket\", sizeof(\"httpsocket\")-1);\n\t\t\tzend_hash_str_del(Z_OBJPROP_P(this_ptr), \"_use_proxy\", sizeof(\"_use_proxy\")-1);\n\t\t\tadd_soap_fault(this_ptr, \"HTTP\", \"Failed Sending HTTP SOAP request\", NULL, NULL);\n\t\t\tsmart_str_free(&soap_headers_z);\n\t\t\treturn FALSE;\n\t\t}\n\t\tsmart_str_free(&soap_headers);\n\t} else {\n\t\tadd_soap_fault(this_ptr, \"HTTP\", \"Failed to create stream??\", NULL, NULL);\n\t\tsmart_str_free(&soap_headers_z);\n\t\treturn FALSE;\n\t}\n\n\tif (!return_value) {\n\t\tphp_stream_close(stream);\n\t\tzend_hash_str_del(Z_OBJPROP_P(this_ptr), \"httpsocket\", sizeof(\"httpsocket\")-1);\n\t\tzend_hash_str_del(Z_OBJPROP_P(this_ptr), \"_use_proxy\", sizeof(\"_use_proxy\")-1);\n\t\tsmart_str_free(&soap_headers_z);\n\t\treturn TRUE;\n\t}\n\n\tdo {\n\t\thttp_headers = get_http_headers(stream);\n\t\tif (!http_headers) {\n\t\t\tif (request != buf) {\n\t\t\t\tzend_string_release(request);\n\t\t\t}\n\t\t\tphp_stream_close(stream);\n\t\t\tzend_hash_str_del(Z_OBJPROP_P(this_ptr), \"httpsocket\", sizeof(\"httpsocket\")-1);\n\t\t\tzend_hash_str_del(Z_OBJPROP_P(this_ptr), \"_use_proxy\", sizeof(\"_use_proxy\")-1);\n\t\t\tadd_soap_fault(this_ptr, \"HTTP\", \"Error Fetching http headers\", NULL, NULL);\n\t\t\tsmart_str_free(&soap_headers_z);\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tif ((trace = zend_hash_str_find(Z_OBJPROP_P(this_ptr), \"trace\", sizeof(\"trace\")-1)) != NULL &&\n\t\t (Z_TYPE_P(trace) == IS_TRUE || (Z_TYPE_P(trace) == IS_LONG && Z_LVAL_P(trace) != 0))) {\n\t\t\tadd_property_str(this_ptr, \"__last_response_headers\", zend_string_copy(http_headers));\n\t\t}\n\n\t\t/* Check to see what HTTP status was sent */\n\t\thttp_1_1 = 0;\n\t\thttp_status = 0;\n\t\thttp_version = get_http_header_value(ZSTR_VAL(http_headers), \"HTTP/\");\n\t\tif (http_version) {\n\t\t\tchar *tmp;\n\n\t\t\tif (!strncmp(http_version,\"1.1\", 3)) {\n\t\t\t\thttp_1_1 = 1;\n\t\t\t}\n\n\t\t\ttmp = strstr(http_version,\" \");\n\t\t\tif (tmp != NULL) {\n\t\t\t\ttmp++;\n\t\t\t\thttp_status = atoi(tmp);\n\t\t\t}\n\t\t\ttmp = strstr(tmp,\" \");\n\t\t\tif (tmp != NULL) {\n\t\t\t\ttmp++;\n\t\t\t\tif (http_msg) {\n\t\t\t\t\tefree(http_msg);\n\t\t\t\t}\n\t\t\t\thttp_msg = estrdup(tmp);\n\t\t\t}\n\t\t\tefree(http_version);\n\n\t\t\t/* Try and get headers again */\n\t\t\tif (http_status == 100) {\n\t\t\t\tzend_string_release(http_headers);\n\t\t\t}\n\t\t}\n\t} while (http_status == 100);\n\n\t/* Grab and send back every cookie */\n\n\t/* Not going to worry about Path: because\n\t we shouldn't be changing urls so path dont\n\t matter too much\n\t*/\n\tcookie_itt = strstr(ZSTR_VAL(http_headers), \"Set-Cookie: \");\n\twhile (cookie_itt) {\n\t\tchar *cookie;\n\t\tchar *eqpos, *sempos;\n\t\tzval *cookies;\n\n\t\tif ((cookies = zend_hash_str_find(Z_OBJPROP_P(this_ptr), \"_cookies\", sizeof(\"_cookies\")-1)) == NULL ||\n\t\t Z_TYPE_P(cookies) != IS_ARRAY) {\n\t\t\tzval tmp_cookies;\n\t\t\tarray_init(&tmp_cookies);\n\t\t\tcookies = zend_hash_str_update(Z_OBJPROP_P(this_ptr), \"_cookies\", sizeof(\"_cookies\")-1, &tmp_cookies);\n\t\t}\n\n\t\tcookie = get_http_header_value(cookie_itt,\"Set-Cookie: \");\n\n\t\teqpos = strstr(cookie, \"=\");\n\t\tsempos = strstr(cookie, \";\");\n\t\tif (eqpos != NULL && (sempos == NULL || sempos > eqpos)) {\n\t\t\tsmart_str name = {0};\n\t\t\tint cookie_len;\n\t\t\tzval zcookie;\n\n\t\t\tif (sempos != NULL) {\n\t\t\t\tcookie_len = sempos-(eqpos+1);\n\t\t\t} else {\n\t\t\t\tcookie_len = strlen(cookie)-(eqpos-cookie)-1;\n\t\t\t}\n\n\t\t\tsmart_str_appendl(&name, cookie, eqpos - cookie);\n\t\t\tsmart_str_0(&name);\n\n\t\t\tarray_init(&zcookie);\n\t\t\tadd_index_stringl(&zcookie, 0, eqpos + 1, cookie_len);\n\n\t\t\tif (sempos != NULL) {\n\t\t\t\tchar *options = cookie + cookie_len+1;\n\t\t\t\twhile (*options) {\n\t\t\t\t\twhile (*options == ' ') {options++;}\n\t\t\t\t\tsempos = strstr(options, \";\");\n\t\t\t\t\tif (strstr(options,\"path=\") == options) {\n\t\t\t\t\t\teqpos = options + sizeof(\"path=\")-1;\n\t\t\t\t\t\tadd_index_stringl(&zcookie, 1, eqpos, sempos?(sempos-eqpos):strlen(eqpos));\n\t\t\t\t\t} else if (strstr(options,\"domain=\") == options) {\n\t\t\t\t\t\teqpos = options + sizeof(\"domain=\")-1;\n\t\t\t\t\t\tadd_index_stringl(&zcookie, 2, eqpos, sempos?(sempos-eqpos):strlen(eqpos));\n\t\t\t\t\t} else if (strstr(options,\"secure\") == options) {\n\t\t\t\t\t\tadd_index_bool(&zcookie, 3, 1);\n\t\t\t\t\t}\n\t\t\t\t\tif (sempos != NULL) {\n\t\t\t\t\t\toptions = sempos+1;\n\t\t\t\t\t} else {\n\t\t\t\t\t break;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!zend_hash_index_exists(Z_ARRVAL(zcookie), 1)) {\n\t\t\t\tchar *t = phpurl->path?phpurl->path:\"/\";\n\t\t\t\tchar *c = strrchr(t, '/');\n\t\t\t\tif (c) {\n\t\t\t\t\tadd_index_stringl(&zcookie, 1, t, c-t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!zend_hash_index_exists(Z_ARRVAL(zcookie), 2)) {\n\t\t\t\tadd_index_string(&zcookie, 2, phpurl->host);\n\t\t\t}\n\n\t\t\tzend_symtable_update(Z_ARRVAL_P(cookies), name.s, &zcookie);\n\t\t\tsmart_str_free(&name);\n\t\t}\n\n\t\tcookie_itt = strstr(cookie_itt + sizeof(\"Set-Cookie: \"), \"Set-Cookie: \");\n\t\tefree(cookie);\n\t}\n\n\t/* See if the server requested a close */\n\tif (http_1_1) {\n\t\thttp_close = FALSE;\n\t\tif (use_proxy && !use_ssl) {\n\t\t\tconnection = get_http_header_value(ZSTR_VAL(http_headers), \"Proxy-Connection: \");\n\t\t\tif (connection) {\n\t\t\t\tif (strncasecmp(connection, \"close\", sizeof(\"close\")-1) == 0) {\n\t\t\t\t\thttp_close = TRUE;\n\t\t\t\t}\n\t\t\t\tefree(connection);\n\t\t\t}\n\t\t}\n\t\tif (http_close == FALSE) {\n\t\t\tconnection = get_http_header_value(ZSTR_VAL(http_headers), \"Connection: \");\n\t\t\tif (connection) {\n\t\t\t\tif (strncasecmp(connection, \"close\", sizeof(\"close\")-1) == 0) {\n\t\t\t\t\thttp_close = TRUE;\n\t\t\t\t}\n\t\t\t\tefree(connection);\n\t\t\t}\n\t\t}\n\t} else {\n\t\thttp_close = TRUE;\n\t\tif (use_proxy && !use_ssl) {\n\t\t\tconnection = get_http_header_value(ZSTR_VAL(http_headers), \"Proxy-Connection: \");\n\t\t\tif (connection) {\n\t\t\t\tif (strncasecmp(connection, \"Keep-Alive\", sizeof(\"Keep-Alive\")-1) == 0) {\n\t\t\t\t\thttp_close = FALSE;\n\t\t\t\t}\n\t\t\t\tefree(connection);\n\t\t\t}\n\t\t}\n\t\tif (http_close == TRUE) {\n\t\t\tconnection = get_http_header_value(ZSTR_VAL(http_headers), \"Connection: \");\n\t\t\tif (connection) {\n\t\t\t\tif (strncasecmp(connection, \"Keep-Alive\", sizeof(\"Keep-Alive\")-1) == 0) {\n\t\t\t\t\thttp_close = FALSE;\n\t\t\t\t}\n\t\t\t\tefree(connection);\n\t\t\t}\n\t\t}\n\t}\n\n\n\thttp_body = get_http_body(stream, http_close, ZSTR_VAL(http_headers));\n\tif (!http_body) {\n\t\tif (request != buf) {\n\t\t\tzend_string_release(request);\n\t\t}\n\t\tphp_stream_close(stream);\n\t\tzend_string_release(http_headers);\n\t\tzend_hash_str_del(Z_OBJPROP_P(this_ptr), \"httpsocket\", sizeof(\"httpsocket\")-1);\n\t\tzend_hash_str_del(Z_OBJPROP_P(this_ptr), \"_use_proxy\", sizeof(\"_use_proxy\")-1);\n\t\tadd_soap_fault(this_ptr, \"HTTP\", \"Error Fetching http body, No Content-Length, connection closed or chunked data\", NULL, NULL);\n\t\tif (http_msg) {\n\t\t\tefree(http_msg);\n\t\t}\n\t\tsmart_str_free(&soap_headers_z);\n\t\treturn FALSE;\n\t}\n\n\tif (request != buf) {\n\t\tzend_string_release(request);\n\t}\n\n\tif (http_close) {\n\t\tphp_stream_close(stream);\n\t\tzend_hash_str_del(Z_OBJPROP_P(this_ptr), \"httpsocket\", sizeof(\"httpsocket\")-1);\n\t\tzend_hash_str_del(Z_OBJPROP_P(this_ptr), \"_use_proxy\", sizeof(\"_use_proxy\")-1);\n\t\tstream = NULL;\n\t}\n\n\t/* Process HTTP status codes */\n\tif (http_status >= 300 && http_status < 400) {\n\t\tchar *loc;\n\n\t\tif ((loc = get_http_header_value(ZSTR_VAL(http_headers), \"Location: \")) != NULL) {\n\t\t\tphp_url *new_url = php_url_parse(loc);\n\n\t\t\tif (new_url != NULL) {\n\t\t\t\tzend_string_release(http_headers);\n\t\t\t\tzend_string_release(http_body);\n\t\t\t\tefree(loc);\n\t\t\t\tif (new_url->scheme == NULL && new_url->path != NULL) {\n\t\t\t\t\tnew_url->scheme = phpurl->scheme ? estrdup(phpurl->scheme) : NULL;\n\t\t\t\t\tnew_url->host = phpurl->host ? estrdup(phpurl->host) : NULL;\n\t\t\t\t\tnew_url->port = phpurl->port;\n\t\t\t\t\tif (new_url->path && new_url->path[0] != '/') {\n\t\t\t\t\t\tif (phpurl->path) {\n\t\t\t\t\t\t\tchar *t = phpurl->path;\n\t\t\t\t\t\t\tchar *p = strrchr(t, '/');\n\t\t\t\t\t\t\tif (p) {\n\t\t\t\t\t\t\t\tchar *s = emalloc((p - t) + strlen(new_url->path) + 2);\n\t\t\t\t\t\t\t\tstrncpy(s, t, (p - t) + 1);\n\t\t\t\t\t\t\t\ts[(p - t) + 1] = 0;\n\t\t\t\t\t\t\t\tstrcat(s, new_url->path);\n\t\t\t\t\t\t\t\tefree(new_url->path);\n\t\t\t\t\t\t\t\tnew_url->path = s;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tchar *s = emalloc(strlen(new_url->path) + 2);\n\t\t\t\t\t\t\ts[0] = '/'; s[1] = 0;\n\t\t\t\t\t\t\tstrcat(s, new_url->path);\n\t\t\t\t\t\t\tefree(new_url->path);\n\t\t\t\t\t\t\tnew_url->path = s;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tphpurl = new_url;\n\n\t\t\t\tif (--redirect_max < 1) {\n\t\t\t\t\tadd_soap_fault(this_ptr, \"HTTP\", \"Redirection limit reached, aborting\", NULL, NULL);\n\t\t\t\t\tsmart_str_free(&soap_headers_z);\n\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\n\t\t\t\tgoto try_again;\n\t\t\t}\n\t\t}\n\t} else if (http_status == 401) {\n\t\t/* Digest authentication */\n\t\tzval *digest, *login, *password;\n\t\tchar *auth = get_http_header_value(ZSTR_VAL(http_headers), \"WWW-Authenticate: \");\n\n\t\tif (auth &&\n\t\t\t\tstrstr(auth, \"Digest\") == auth &&\n\t\t ((digest = zend_hash_str_find(Z_OBJPROP_P(this_ptr), \"_digest\", sizeof(\"_digest\")-1)) == NULL ||\n\t\t Z_TYPE_P(digest) != IS_ARRAY) &&\n\t\t (login = zend_hash_str_find(Z_OBJPROP_P(this_ptr), \"_login\", sizeof(\"_login\")-1)) != NULL &&\n\t\t Z_TYPE_P(login) == IS_STRING &&\n\t\t (password = zend_hash_str_find(Z_OBJPROP_P(this_ptr), \"_password\", sizeof(\"_password\")-1)) != NULL &&\n\t\t Z_TYPE_P(password) == IS_STRING) {\n\t\t\tchar *s;\n\t\t\tzval digest;\n\n\t\t\tZVAL_UNDEF(&digest);\n\t\t\ts = auth + sizeof(\"Digest\")-1;\n\t\t\twhile (*s != '\\0') {\n\t\t\t\tchar *name, *val;\n\t\t\t\twhile (*s == ' ') ++s;\n\t\t\t\tname = s;\n\t\t\t\twhile (*s != '\\0' && *s != '=') ++s;\n\t\t\t\tif (*s == '=') {\n\t\t\t\t\t*s = '\\0';\n\t\t\t\t\t++s;\n\t\t\t\t\tif (*s == '\"') {\n\t\t\t\t\t\t++s;\n\t\t\t\t\t\tval = s;\n\t\t\t\t\t\twhile (*s != '\\0' && *s != '\"') ++s;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tval = s;\n\t\t\t\t\t\twhile (*s != '\\0' && *s != ' ' && *s != ',') ++s;\n\t\t\t\t\t}\n\t\t\t\t\tif (*s != '\\0') {\n\t\t\t\t\t\tif (*s != ',') {\n\t\t\t\t\t\t\t*s = '\\0';\n\t\t\t\t\t\t\t++s;\n\t\t\t\t\t\t\twhile (*s != '\\0' && *s != ',') ++s;\n\t\t\t\t\t\t\tif (*s != '\\0') ++s;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t*s = '\\0';\n\t\t\t\t\t\t\t++s;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (Z_TYPE(digest) == IS_UNDEF) {\n\t\t\t\t\t\tarray_init(&digest);\n\t\t\t\t\t}\n\t\t\t\t\tadd_assoc_string(&digest, name, val);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (Z_TYPE(digest) != IS_UNDEF) {\n\t\t\t\tphp_url *new_url = emalloc(sizeof(php_url));\n\n\t\t\t\tZ_DELREF(digest);\n\t\t\t\tadd_property_zval_ex(this_ptr, \"_digest\", sizeof(\"_digest\")-1, &digest);\n\n\t\t\t\t*new_url = *phpurl;\n\t\t\t\tif (phpurl->scheme) phpurl->scheme = estrdup(phpurl->scheme);\n\t\t\t\tif (phpurl->user) phpurl->user = estrdup(phpurl->user);\n\t\t\t\tif (phpurl->pass) phpurl->pass = estrdup(phpurl->pass);\n\t\t\t\tif (phpurl->host) phpurl->host = estrdup(phpurl->host);\n\t\t\t\tif (phpurl->path) phpurl->path = estrdup(phpurl->path);\n\t\t\t\tif (phpurl->query) phpurl->query = estrdup(phpurl->query);\n\t\t\t\tif (phpurl->fragment) phpurl->fragment = estrdup(phpurl->fragment);\n\t\t\t\tphpurl = new_url;\n\n\t\t\t\tefree(auth);\n\t\t\t\tzend_string_release(http_headers);\n\t\t\t\tzend_string_release(http_body);\n\n\t\t\t\tgoto try_again;\n\t\t\t}\n\t\t}\n\t\tif (auth) efree(auth);\n\t}\n\tsmart_str_free(&soap_headers_z);\n\n\t/* Check and see if the server even sent a xml document */\n\tcontent_type = get_http_header_value(ZSTR_VAL(http_headers), \"Content-Type: \");\n\tif (content_type) {\n\t\tchar *pos = NULL;\n\t\tint cmplen;\n\t\tpos = strstr(content_type,\";\");\n\t\tif (pos != NULL) {\n\t\t\tcmplen = pos - content_type;\n\t\t} else {\n\t\t\tcmplen = strlen(content_type);\n\t\t}\n\t\tif (strncmp(content_type, \"text/xml\", cmplen) == 0 ||\n\t\t strncmp(content_type, \"application/soap+xml\", cmplen) == 0) {\n\t\t\tcontent_type_xml = 1;\n/*\n\t\t\tif (strncmp(http_body, \"val+10, http_body->len-10);\n\t\t} else if (strcmp(content_encoding,\"deflate\") == 0 &&\n\t\t zend_hash_str_exists(EG(function_table), \"gzuncompress\", sizeof(\"gzuncompress\")-1)) {\n\t\t\tZVAL_STRING(&func, \"gzuncompress\");\n\t\t\tZVAL_STR_COPY(¶ms[0], http_body);\n\t\t} else {\n\t\t\tefree(content_encoding);\n\t\t\tzend_string_release(http_headers);\n\t\t\tzend_string_release(http_body);\n\t\t\tif (http_msg) {\n\t\t\t\tefree(http_msg);\n\t\t\t}\n\t\t\tadd_soap_fault(this_ptr, \"HTTP\", \"Unknown Content-Encoding\", NULL, NULL);\n\t\t\treturn FALSE;\n\t\t}\n\t\tif (call_user_function(CG(function_table), (zval*)NULL, &func, &retval, 1, params) == SUCCESS &&\n\t\t Z_TYPE(retval) == IS_STRING) {\n\t\t\tzval_ptr_dtor(¶ms[0]);\n\t\t\tzval_ptr_dtor(&func);\n\t\t\tzend_string_release(http_body);\n\t\t\tZVAL_COPY_VALUE(return_value, &retval);\n\t\t} else {\n\t\t\tzval_ptr_dtor(¶ms[0]);\n\t\t\tzval_ptr_dtor(&func);\n\t\t\tefree(content_encoding);\n\t\t\tzend_string_release(http_headers);\n\t\t\tzend_string_release(http_body);\n\t\t\tadd_soap_fault(this_ptr, \"HTTP\", \"Can't uncompress compressed response\", NULL, NULL);\n\t\t\tif (http_msg) {\n\t\t\t\tefree(http_msg);\n\t\t\t}\n\t\t\treturn FALSE;\n\t\t}\n\t\tefree(content_encoding);\n\t} else {\n\t\tZVAL_STR(return_value, http_body);\n\t}\n\n\tzend_string_release(http_headers);\n\n\tif (http_status >= 400) {\n\t\tint error = 0;\n\n\t\tif (Z_STRLEN_P(return_value) == 0) {\n\t\t\terror = 1;\n\t\t} else if (Z_STRLEN_P(return_value) > 0) {\n\t\t\tif (!content_type_xml) {\n\t\t\t\tchar *s = Z_STRVAL_P(return_value);\n\n\t\t\t\twhile (*s != '\\0' && *s < ' ') {\n\t\t\t\t\ts++;\n\t\t\t\t}\n\t\t\t\tif (strncmp(s, \" \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #71610: Type Confusion Vulnerability - SOAP / make_http_soap_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: do_add_counters(struct net *net, const void __user *user, unsigned int len,\n\t\tint compat)\n{\n\tunsigned int i;\n\tstruct xt_counters_info tmp;\n\tstruct xt_counters *paddc;\n\tunsigned int num_counters;\n\tchar *name;\n\tint size;\n\tvoid *ptmp;\n\tstruct xt_table *t;\n\tconst struct xt_table_info *private;\n\tint ret = 0;\n\tstruct ip6t_entry *iter;\n\tunsigned int addend;\n#ifdef CONFIG_COMPAT\n\tstruct compat_xt_counters_info compat_tmp;\n\n\tif (compat) {\n\t\tptmp = &compat_tmp;\n\t\tsize = sizeof(struct compat_xt_counters_info);\n\t} else\n#endif\n\t{\n\t\tptmp = &tmp;\n\t\tsize = sizeof(struct xt_counters_info);\n\t}\n\n\tif (copy_from_user(ptmp, user, size) != 0)\n\t\treturn -EFAULT;\n\n#ifdef CONFIG_COMPAT\n\tif (compat) {\n\t\tnum_counters = compat_tmp.num_counters;\n\t\tname = compat_tmp.name;\n\t} else\n#endif\n\t{\n\t\tnum_counters = tmp.num_counters;\n\t\tname = tmp.name;\n\t}\n\n\tif (len != size + num_counters * sizeof(struct xt_counters))\n\t\treturn -EINVAL;\n\n\tpaddc = vmalloc(len - size);\n\tif (!paddc)\n\t\treturn -ENOMEM;\n\n\tif (copy_from_user(paddc, user + size, len - size) != 0) {\n\t\tret = -EFAULT;\n\t\tgoto free;\n\t}\n\n\tt = xt_find_table_lock(net, AF_INET6, name);\n\tif (IS_ERR_OR_NULL(t)) {\n\t\tret = t ? PTR_ERR(t) : -ENOENT;\n\t\tgoto free;\n\t}\n\n\tlocal_bh_disable();\n\tprivate = t->private;\n\tif (private->number != num_counters) {\n\t\tret = -EINVAL;\n\t\tgoto unlock_up_free;\n\t}\n\n\ti = 0;\n\taddend = xt_write_recseq_begin();\n\txt_entry_foreach(iter, private->entries, private->size) {\n\t\tstruct xt_counters *tmp;\n\n\t\ttmp = xt_get_this_cpu_counter(&iter->counters);\n\t\tADD_COUNTER(*tmp, paddc[i].bcnt, paddc[i].pcnt);\n\t\t++i;\n\t}\n\txt_write_recseq_end(addend);\n unlock_up_free:\n\tlocal_bh_enable();\n\txt_table_unlock(t);\n\tmodule_put(t->me);\n free:\n\tvfree(paddc);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'netfilter: x_tables: introduce and use xt_copy_counters_from_user\n\nThe three variants use same copy&pasted code, condense this into a\nhelper and use that.\n\nMake sure info.name is 0-terminated.\n\nSigned-off-by: Florian Westphal \nSigned-off-by: Pablo Neira Ayuso '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void __inet_del_ifa(struct in_device *in_dev, struct in_ifaddr **ifap,\n\t\t\t int destroy, struct nlmsghdr *nlh, u32 portid)\n{\n\tstruct in_ifaddr *promote = NULL;\n\tstruct in_ifaddr *ifa, *ifa1 = *ifap;\n\tstruct in_ifaddr *last_prim = in_dev->ifa_list;\n\tstruct in_ifaddr *prev_prom = NULL;\n\tint do_promote = IN_DEV_PROMOTE_SECONDARIES(in_dev);\n\n\tASSERT_RTNL();\n\n\t/* 1. Deleting primary ifaddr forces deletion all secondaries\n\t * unless alias promotion is set\n\t **/\n\n\tif (!(ifa1->ifa_flags & IFA_F_SECONDARY)) {\n\t\tstruct in_ifaddr **ifap1 = &ifa1->ifa_next;\n\n\t\twhile ((ifa = *ifap1) != NULL) {\n\t\t\tif (!(ifa->ifa_flags & IFA_F_SECONDARY) &&\n\t\t\t ifa1->ifa_scope <= ifa->ifa_scope)\n\t\t\t\tlast_prim = ifa;\n\n\t\t\tif (!(ifa->ifa_flags & IFA_F_SECONDARY) ||\n\t\t\t ifa1->ifa_mask != ifa->ifa_mask ||\n\t\t\t !inet_ifa_match(ifa1->ifa_address, ifa)) {\n\t\t\t\tifap1 = &ifa->ifa_next;\n\t\t\t\tprev_prom = ifa;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!do_promote) {\n\t\t\t\tinet_hash_remove(ifa);\n\t\t\t\t*ifap1 = ifa->ifa_next;\n\n\t\t\t\trtmsg_ifa(RTM_DELADDR, ifa, nlh, portid);\n\t\t\t\tblocking_notifier_call_chain(&inetaddr_chain,\n\t\t\t\t\t\tNETDEV_DOWN, ifa);\n\t\t\t\tinet_free_ifa(ifa);\n\t\t\t} else {\n\t\t\t\tpromote = ifa;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t/* On promotion all secondaries from subnet are changing\n\t * the primary IP, we must remove all their routes silently\n\t * and later to add them back with new prefsrc. Do this\n\t * while all addresses are on the device list.\n\t */\n\tfor (ifa = promote; ifa; ifa = ifa->ifa_next) {\n\t\tif (ifa1->ifa_mask == ifa->ifa_mask &&\n\t\t inet_ifa_match(ifa1->ifa_address, ifa))\n\t\t\tfib_del_ifaddr(ifa, ifa1);\n\t}\n\n\t/* 2. Unlink it */\n\n\t*ifap = ifa1->ifa_next;\n\tinet_hash_remove(ifa1);\n\n\t/* 3. Announce address deletion */\n\n\t/* Send message first, then call notifier.\n\t At first sight, FIB update triggered by notifier\n\t will refer to already deleted ifaddr, that could confuse\n\t netlink listeners. It is not true: look, gated sees\n\t that route deleted and if it still thinks that ifaddr\n\t is valid, it will try to restore deleted routes... Grr.\n\t So that, this order is correct.\n\t */\n\trtmsg_ifa(RTM_DELADDR, ifa1, nlh, portid);\n\tblocking_notifier_call_chain(&inetaddr_chain, NETDEV_DOWN, ifa1);\n\n\tif (promote) {\n\t\tstruct in_ifaddr *next_sec = promote->ifa_next;\n\n\t\tif (prev_prom) {\n\t\t\tprev_prom->ifa_next = promote->ifa_next;\n\t\t\tpromote->ifa_next = last_prim->ifa_next;\n\t\t\tlast_prim->ifa_next = promote;\n\t\t}\n\n\t\tpromote->ifa_flags &= ~IFA_F_SECONDARY;\n\t\trtmsg_ifa(RTM_NEWADDR, promote, nlh, portid);\n\t\tblocking_notifier_call_chain(&inetaddr_chain,\n\t\t\t\tNETDEV_UP, promote);\n\t\tfor (ifa = next_sec; ifa; ifa = ifa->ifa_next) {\n\t\t\tif (ifa1->ifa_mask != ifa->ifa_mask ||\n\t\t\t !inet_ifa_match(ifa1->ifa_address, ifa))\n\t\t\t\t\tcontinue;\n\t\t\tfib_add_ifaddr(ifa);\n\t\t}\n\n\t}\n\tif (destroy)\n\t\tinet_free_ifa(ifa1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'ipv4: Don't do expensive useless work during inetdev destroy.\n\nWhen an inetdev is destroyed, every address assigned to the interface\nis removed. And in this scenerio we do two pointless things which can\nbe very expensive if the number of assigned interfaces is large:\n\n1) Address promotion. We are deleting all addresses, so there is no\n point in doing this.\n\n2) A full nf conntrack table purge for every address. We only need to\n do this once, as is already caught by the existing\n masq_dev_notifier so masq_inet_event() can skip this.\n\nReported-by: Solar Designer \nSigned-off-by: David S. Miller \nTested-by: Cyrill Gorcunov '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: mbfl_buffer_converter_new2(\n\tconst mbfl_encoding *from,\n\tconst mbfl_encoding *to, \n int buf_initsz)\n{\n\tmbfl_buffer_converter *convd;\n\n\t/* allocate */\n\tconvd = (mbfl_buffer_converter*)mbfl_malloc(sizeof (mbfl_buffer_converter));\n\tif (convd == NULL) {\n\t\treturn NULL;\n\t}\n\n\t/* initialize */\n\tconvd->from = from;\n\tconvd->to = to;\n\n\t/* create convert filter */\n\tconvd->filter1 = NULL;\n\tconvd->filter2 = NULL;\n\tif (mbfl_convert_filter_get_vtbl(convd->from->no_encoding, convd->to->no_encoding) != NULL) {\n\t\tconvd->filter1 = mbfl_convert_filter_new(convd->from->no_encoding, convd->to->no_encoding, mbfl_memory_device_output, NULL, &convd->device);\n\t} else {\n\t\tconvd->filter2 = mbfl_convert_filter_new(mbfl_no_encoding_wchar, convd->to->no_encoding, mbfl_memory_device_output, NULL, &convd->device);\n\t\tif (convd->filter2 != NULL) {\n\t\t\tconvd->filter1 = mbfl_convert_filter_new(convd->from->no_encoding,\n\t\t\t\t\tmbfl_no_encoding_wchar,\n\t\t\t\t\t(int (*)(int, void*))convd->filter2->filter_function,\n\t\t\t\t\t(int (*)(void*))convd->filter2->filter_flush,\n\t\t\t\t\tconvd->filter2);\n\t\t\tif (convd->filter1 == NULL) {\n\t\t\t\tmbfl_convert_filter_delete(convd->filter2);\n\t\t\t}\n\t\t}\n\t}\n\tif (convd->filter1 == NULL) {\n\t\treturn NULL;\n\t}\n\n\tmbfl_memory_device_init(&convd->device, buf_initsz, buf_initsz/4);\n\n\treturn convd;\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, offsetGet)\n{\n\tchar *fname, *error;\n\tsize_t fname_len;\n\tzval zfname;\n\tphar_entry_info *entry;\n\tzend_string *sfname;\n\tPHAR_ARCHIVE_OBJECT();\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS(), \"s\", &fname, &fname_len) == FAILURE) {\n\t\treturn;\n\t}\n\n\t/* security is 0 here so that we can get a better error message than \"entry doesn't exist\" */\n\tif (!(entry = phar_get_entry_info_dir(phar_obj->archive, fname, fname_len, 1, &error, 0))) {\n\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \"Entry %s does not exist%s%s\", fname, error?\", \":\"\", error?error:\"\");\n\t} else {\n\t\tif (fname_len == sizeof(\".phar/stub.php\")-1 && !memcmp(fname, \".phar/stub.php\", sizeof(\".phar/stub.php\")-1)) {\n\t\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \"Cannot get stub \\\".phar/stub.php\\\" directly in phar \\\"%s\\\", use getStub\", phar_obj->archive->fname);\n\t\t\treturn;\n\t\t}\n\n\t\tif (fname_len == sizeof(\".phar/alias.txt\")-1 && !memcmp(fname, \".phar/alias.txt\", sizeof(\".phar/alias.txt\")-1)) {\n\t\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \"Cannot get alias \\\".phar/alias.txt\\\" directly in phar \\\"%s\\\", use getAlias\", phar_obj->archive->fname);\n\t\t\treturn;\n\t\t}\n\n\t\tif (fname_len >= sizeof(\".phar\")-1 && !memcmp(fname, \".phar\", sizeof(\".phar\")-1)) {\n\t\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \"Cannot directly get any files or directories in magic \\\".phar\\\" directory\", phar_obj->archive->fname);\n\t\t\treturn;\n\t\t}\n\n\t\tif (entry->is_temp_dir) {\n\t\t\tefree(entry->filename);\n\t\t\tefree(entry);\n\t\t}\n\n\t\tsfname = strpprintf(0, \"phar://%s/%s\", phar_obj->archive->fname, fname);\n\t\tZVAL_NEW_STR(&zfname, sfname);\n\t\tspl_instantiate_arg_ex1(phar_obj->spl.info_class, return_value, &zfname);\n\t\tzval_ptr_dtor(&zfname);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #71860: Require valid paths for phar filenames'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PHP_METHOD(Phar, unlinkArchive)\n{\n\tchar *fname, *error, *zname, *arch, *entry;\n\tsize_t fname_len;\n\tint zname_len, arch_len, entry_len;\n\tphar_archive_data *phar;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS(), \"s\", &fname, &fname_len) == FAILURE) {\n\t\tRETURN_FALSE;\n\t}\n\n\tif (!fname_len) {\n\t\tzend_throw_exception_ex(phar_ce_PharException, 0, \"Unknown phar archive \\\"\\\"\");\n\t\treturn;\n\t}\n\n\tif (FAILURE == phar_open_from_filename(fname, fname_len, NULL, 0, REPORT_ERRORS, &phar, &error)) {\n\t\tif (error) {\n\t\t\tzend_throw_exception_ex(phar_ce_PharException, 0, \"Unknown phar archive \\\"%s\\\": %s\", fname, error);\n\t\t\tefree(error);\n\t\t} else {\n\t\t\tzend_throw_exception_ex(phar_ce_PharException, 0, \"Unknown phar archive \\\"%s\\\"\", fname);\n\t\t}\n\t\treturn;\n\t}\n\n\tzname = (char*)zend_get_executed_filename();\n\tzname_len = strlen(zname);\n\n\tif (zname_len > 7 && !memcmp(zname, \"phar://\", 7) && SUCCESS == phar_split_fname(zname, zname_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) {\n\t\tif (arch_len == fname_len && !memcmp(arch, fname, arch_len)) {\n\t\t\tzend_throw_exception_ex(phar_ce_PharException, 0, \"phar archive \\\"%s\\\" cannot be unlinked from within itself\", fname);\n\t\t\tefree(arch);\n\t\t\tefree(entry);\n\t\t\treturn;\n\t\t}\n\t\tefree(arch);\n\t\tefree(entry);\n\t}\n\n\tif (phar->is_persistent) {\n\t\tzend_throw_exception_ex(phar_ce_PharException, 0, \"phar archive \\\"%s\\\" is in phar.cache_list, cannot unlinkArchive()\", fname);\n\t\treturn;\n\t}\n\n\tif (phar->refcount) {\n\t\tzend_throw_exception_ex(phar_ce_PharException, 0, \"phar archive \\\"%s\\\" has open file handles or objects. fclose() all file handles, and unset() all objects prior to calling unlinkArchive()\", fname);\n\t\treturn;\n\t}\n\n\tfname = estrndup(phar->fname, phar->fname_len);\n\n\t/* invalidate phar cache */\n\tPHAR_G(last_phar) = NULL;\n\tPHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;\n\n\tphar_archive_delref(phar);\n\tunlink(fname);\n\tefree(fname);\n\tRETURN_TRUE;\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: static inline void ext4_truncate_failed_write(struct inode *inode)\n{\n\ttruncate_inode_pages(inode->i_mapping, inode->i_size);\n\text4_truncate(inode);\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_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\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\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_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(srtp_ctx_t *ctx, void *rtp_hdr, int *pkt_octet_len) {\n srtp_hdr_t *hdr = (srtp_hdr_t *)rtp_hdr;\n uint32_t *enc_start; /* pointer to start of encrypted portion */\n uint32_t *auth_start; /* pointer to start of auth. 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 uint8_t *auth_tag = NULL; /* location of auth_tag within packet */\n err_status_t status; \n int tag_len;\n srtp_stream_ctx_t *stream;\n int prefix_len;\n\n debug_print(mod_srtp, \"function srtp_protect\", NULL);\n\n /* we assume the hdr is 32-bit aligned to start */\n\n /* Verify RTP header */\n status = srtp_validate_rtp_header(rtp_hdr, pkt_octet_len);\n if (status)\n return status;\n\n /* check the packet length - it must at least contain a full header */\n if (*pkt_octet_len < octets_in_rtp_header)\n return err_status_bad_param;\n\n /*\n * look up ssrc in srtp_stream list, and process the packet with\n * the appropriate stream. if we haven't seen this stream before,\n * there's a template key for this srtp_session, and the cipher\n * supports key-sharing, then we assume that a new stream using\n * that key has just started up\n */\n stream = srtp_get_stream(ctx, hdr->ssrc);\n if (stream == NULL) {\n if (ctx->stream_template != NULL) {\n srtp_stream_ctx_t *new_stream;\n\n /* allocate and initialize a new stream */\n status = srtp_stream_clone(ctx->stream_template, \n\t\t\t\t hdr->ssrc, &new_stream); \n if (status)\n\t return status;\n\n /* add new stream to the head of the stream_list */\n new_stream->next = ctx->stream_list;\n ctx->stream_list = new_stream;\n\n /* set direction to outbound */\n new_stream->direction = dir_srtp_sender;\n\n /* set stream (the pointer used in this function) */\n stream = new_stream;\n } else {\n /* no template stream, so we return an error */\n return err_status_no_ctx;\n } \n }\n\n /* \n * verify that stream is for sending traffic - this check will\n * detect SSRC collisions, since a stream that appears in both\n * srtp_protect() and srtp_unprotect() will fail this test in one of\n * those functions.\n */\n if (stream->direction != dir_srtp_sender) {\n if (stream->direction == dir_unknown) {\n stream->direction = dir_srtp_sender;\n } else {\n srtp_handle_event(ctx, stream, event_ssrc_collision);\n }\n }\n\n /*\n * Check if this is an AEAD stream (GCM mode). If so, then dispatch\n * the request to our AEAD handler.\n */\n if (stream->rtp_cipher->algorithm == AES_128_GCM ||\n stream->rtp_cipher->algorithm == AES_256_GCM) {\n return srtp_protect_aead(ctx, stream, rtp_hdr, (unsigned int*)pkt_octet_len);\n }\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_soft_limit: \n srtp_handle_event(ctx, stream, event_key_soft_limit);\n break; \n case key_event_hard_limit:\n srtp_handle_event(ctx, stream, event_key_hard_limit);\n\treturn err_status_key_expired;\n default:\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 * if we're not providing confidentiality, set enc_start to NULL\n */\n if (stream->rtp_services & sec_serv_conf) {\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 } else {\n enc_start = NULL;\n }\n\n /* \n * if we're providing authentication, set the auth_start and auth_tag\n * pointers to the proper locations; otherwise, set auth_start to NULL\n * to indicate that no authentication is needed\n */\n if (stream->rtp_services & sec_serv_auth) {\n auth_start = (uint32_t *)hdr;\n auth_tag = (uint8_t *)hdr + *pkt_octet_len;\n } else {\n auth_start = NULL;\n auth_tag = NULL;\n }\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 if (status != err_status_replay_fail || !stream->allow_repeat_tx)\n return status; /* we've been asked to reuse an index */\n }\n else\n rdbx_add_index(&stream->rtp_rdbx, delta);\n\n#ifdef NO_64BIT_MATH\n debug_print2(mod_srtp, \"estimated packet index: %08x%08x\", \n\t\thigh32(est),low32(est));\n#else\n debug_print(mod_srtp, \"estimated packet index: %016llx\", est);\n#endif\n\n /* \n * if we're using rindael counter mode, set nonce and seq \n */\n if (stream->rtp_cipher->type->id == AES_ICM ||\n stream->rtp_cipher->type->id == AES_256_ICM) {\n v128_t iv;\n\n iv.v32[0] = 0;\n iv.v32[1] = hdr->ssrc;\n#ifdef NO_64BIT_MATH\n iv.v64[1] = be64_to_cpu(make64((high32(est) << 16) | (low32(est) >> 16),\n\t\t\t\t\t\t\t\t low32(est) << 16));\n#else\n iv.v64[1] = be64_to_cpu(est << 16);\n#endif\n status = cipher_set_iv(stream->rtp_cipher, &iv, direction_encrypt);\n\n } else { \n v128_t iv;\n\n /* otherwise, set the index to est */ \n#ifdef NO_64BIT_MATH\n iv.v32[0] = 0;\n iv.v32[1] = 0;\n#else\n iv.v64[0] = 0;\n#endif\n iv.v64[1] = be64_to_cpu(est);\n status = cipher_set_iv(stream->rtp_cipher, &iv, direction_encrypt);\n }\n if (status)\n return err_status_cipher_fail;\n\n /* shift est, put into network byte order */\n#ifdef NO_64BIT_MATH\n est = be64_to_cpu(make64((high32(est) << 16) |\n\t\t\t\t\t\t (low32(est) >> 16),\n\t\t\t\t\t\t low32(est) << 16));\n#else\n est = be64_to_cpu(est << 16);\n#endif\n \n /* \n * if we're authenticating using a universal hash, put the keystream\n * prefix into the authentication tag\n */\n if (auth_start) {\n \n prefix_len = auth_get_prefix_length(stream->rtp_auth); \n if (prefix_len) {\n status = cipher_output(stream->rtp_cipher, auth_tag, prefix_len);\n if (status)\n\treturn err_status_cipher_fail;\n debug_print(mod_srtp, \"keystream prefix: %s\", \n\t\t octet_string_hex_string(auth_tag, prefix_len));\n }\n }\n\n /* if we're encrypting, exor keystream into the message */\n if (enc_start) {\n status = cipher_encrypt(stream->rtp_cipher, \n\t\t\t (uint8_t *)enc_start, (unsigned int*)&enc_octet_len);\n if (status)\n return err_status_cipher_fail;\n }\n\n /*\n * if we're authenticating, run authentication function and put result\n * into the auth_tag \n */\n if (auth_start) { \n\n /* initialize auth func context */\n status = auth_start(stream->rtp_auth);\n if (status) return status;\n\n /* run auth func over packet */\n status = auth_update(stream->rtp_auth, \n\t\t\t (uint8_t *)auth_start, *pkt_octet_len);\n if (status) return status;\n \n /* run auth func over ROC, put result into auth_tag */\n debug_print(mod_srtp, \"estimated packet index: %016llx\", est);\n status = auth_compute(stream->rtp_auth, (uint8_t *)&est, 4, auth_tag); \n debug_print(mod_srtp, \"srtp auth tag: %s\", \n\t\toctet_string_hex_string(auth_tag, tag_len));\n if (status)\n return err_status_auth_fail; \n\n }\n\n if (auth_tag) {\n\n /* increase the packet length by the length of the auth tag */\n *pkt_octet_len += tag_len;\n }\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 long restore_tm_sigcontexts(struct pt_regs *regs,\n\t\t\t\t struct sigcontext __user *sc,\n\t\t\t\t struct sigcontext __user *tm_sc)\n{\n#ifdef CONFIG_ALTIVEC\n\telf_vrreg_t __user *v_regs, *tm_v_regs;\n#endif\n\tunsigned long err = 0;\n\tunsigned long msr;\n#ifdef CONFIG_VSX\n\tint i;\n#endif\n\t/* copy the GPRs */\n\terr |= __copy_from_user(regs->gpr, tm_sc->gp_regs, sizeof(regs->gpr));\n\terr |= __copy_from_user(¤t->thread.ckpt_regs, sc->gp_regs,\n\t\t\t\tsizeof(regs->gpr));\n\n\t/*\n\t * TFHAR is restored from the checkpointed 'wound-back' ucontext's NIP.\n\t * TEXASR was set by the signal delivery reclaim, as was TFIAR.\n\t * Users doing anything abhorrent like thread-switching w/ signals for\n\t * TM-Suspended code will have to back TEXASR/TFIAR up themselves.\n\t * For the case of getting a signal and simply returning from it,\n\t * we don't need to re-copy them here.\n\t */\n\terr |= __get_user(regs->nip, &tm_sc->gp_regs[PT_NIP]);\n\terr |= __get_user(current->thread.tm_tfhar, &sc->gp_regs[PT_NIP]);\n\n\t/* get MSR separately, transfer the LE bit if doing signal return */\n\terr |= __get_user(msr, &sc->gp_regs[PT_MSR]);\n\t/* pull in MSR TM from user context */\n\tregs->msr = (regs->msr & ~MSR_TS_MASK) | (msr & MSR_TS_MASK);\n\n\t/* pull in MSR LE from user context */\n\tregs->msr = (regs->msr & ~MSR_LE) | (msr & MSR_LE);\n\n\t/* The following non-GPR non-FPR non-VR state is also checkpointed: */\n\terr |= __get_user(regs->ctr, &tm_sc->gp_regs[PT_CTR]);\n\terr |= __get_user(regs->link, &tm_sc->gp_regs[PT_LNK]);\n\terr |= __get_user(regs->xer, &tm_sc->gp_regs[PT_XER]);\n\terr |= __get_user(regs->ccr, &tm_sc->gp_regs[PT_CCR]);\n\terr |= __get_user(current->thread.ckpt_regs.ctr,\n\t\t\t &sc->gp_regs[PT_CTR]);\n\terr |= __get_user(current->thread.ckpt_regs.link,\n\t\t\t &sc->gp_regs[PT_LNK]);\n\terr |= __get_user(current->thread.ckpt_regs.xer,\n\t\t\t &sc->gp_regs[PT_XER]);\n\terr |= __get_user(current->thread.ckpt_regs.ccr,\n\t\t\t &sc->gp_regs[PT_CCR]);\n\n\t/* These regs are not checkpointed; they can go in 'regs'. */\n\terr |= __get_user(regs->trap, &sc->gp_regs[PT_TRAP]);\n\terr |= __get_user(regs->dar, &sc->gp_regs[PT_DAR]);\n\terr |= __get_user(regs->dsisr, &sc->gp_regs[PT_DSISR]);\n\terr |= __get_user(regs->result, &sc->gp_regs[PT_RESULT]);\n\n\t/*\n\t * Do this before updating the thread state in\n\t * current->thread.fpr/vr. That way, if we get preempted\n\t * and another task grabs the FPU/Altivec, it won't be\n\t * tempted to save the current CPU state into the thread_struct\n\t * and corrupt what we are writing there.\n\t */\n\tdiscard_lazy_cpu_state();\n\n\t/*\n\t * Force reload of FP/VEC.\n\t * This has to be done before copying stuff into current->thread.fpr/vr\n\t * for the reasons explained in the previous comment.\n\t */\n\tregs->msr &= ~(MSR_FP | MSR_FE0 | MSR_FE1 | MSR_VEC | MSR_VSX);\n\n#ifdef CONFIG_ALTIVEC\n\terr |= __get_user(v_regs, &sc->v_regs);\n\terr |= __get_user(tm_v_regs, &tm_sc->v_regs);\n\tif (err)\n\t\treturn err;\n\tif (v_regs && !access_ok(VERIFY_READ, v_regs, 34 * sizeof(vector128)))\n\t\treturn -EFAULT;\n\tif (tm_v_regs && !access_ok(VERIFY_READ,\n\t\t\t\t tm_v_regs, 34 * sizeof(vector128)))\n\t\treturn -EFAULT;\n\t/* Copy 33 vec registers (vr0..31 and vscr) from the stack */\n\tif (v_regs != NULL && tm_v_regs != NULL && (msr & MSR_VEC) != 0) {\n\t\terr |= __copy_from_user(¤t->thread.vr_state, v_regs,\n\t\t\t\t\t33 * sizeof(vector128));\n\t\terr |= __copy_from_user(¤t->thread.transact_vr, tm_v_regs,\n\t\t\t\t\t33 * sizeof(vector128));\n\t}\n\telse if (current->thread.used_vr) {\n\t\tmemset(¤t->thread.vr_state, 0, 33 * sizeof(vector128));\n\t\tmemset(¤t->thread.transact_vr, 0, 33 * sizeof(vector128));\n\t}\n\t/* Always get VRSAVE back */\n\tif (v_regs != NULL && tm_v_regs != NULL) {\n\t\terr |= __get_user(current->thread.vrsave,\n\t\t\t\t (u32 __user *)&v_regs[33]);\n\t\terr |= __get_user(current->thread.transact_vrsave,\n\t\t\t\t (u32 __user *)&tm_v_regs[33]);\n\t}\n\telse {\n\t\tcurrent->thread.vrsave = 0;\n\t\tcurrent->thread.transact_vrsave = 0;\n\t}\n\tif (cpu_has_feature(CPU_FTR_ALTIVEC))\n\t\tmtspr(SPRN_VRSAVE, current->thread.vrsave);\n#endif /* CONFIG_ALTIVEC */\n\t/* restore floating point */\n\terr |= copy_fpr_from_user(current, &sc->fp_regs);\n\terr |= copy_transact_fpr_from_user(current, &tm_sc->fp_regs);\n#ifdef CONFIG_VSX\n\t/*\n\t * Get additional VSX data. Update v_regs to point after the\n\t * VMX data. Copy VSX low doubleword from userspace to local\n\t * buffer for formatting, then into the taskstruct.\n\t */\n\tif (v_regs && ((msr & MSR_VSX) != 0)) {\n\t\tv_regs += ELF_NVRREG;\n\t\ttm_v_regs += ELF_NVRREG;\n\t\terr |= copy_vsx_from_user(current, v_regs);\n\t\terr |= copy_transact_vsx_from_user(current, tm_v_regs);\n\t} else {\n\t\tfor (i = 0; i < 32 ; i++) {\n\t\t\tcurrent->thread.fp_state.fpr[i][TS_VSRLOWOFFSET] = 0;\n\t\t\tcurrent->thread.transact_fp.fpr[i][TS_VSRLOWOFFSET] = 0;\n\t\t}\n\t}\n#endif\n\ttm_enable();\n\t/* Make sure the transaction is marked as failed */\n\tcurrent->thread.tm_texasr |= TEXASR_FS;\n\t/* This loads the checkpointed FP/VEC state, if used */\n\ttm_recheckpoint(¤t->thread, msr);\n\n\t/* This loads the speculative FP/VEC state, if used */\n\tif (msr & MSR_FP) {\n\t\tdo_load_up_transact_fpu(¤t->thread);\n\t\tregs->msr |= (MSR_FP | current->thread.fpexc_mode);\n\t}\n#ifdef CONFIG_ALTIVEC\n\tif (msr & MSR_VEC) {\n\t\tdo_load_up_transact_altivec(¤t->thread);\n\t\tregs->msr |= MSR_VEC;\n\t}\n#endif\n\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-284', 'CWE-369'], 'message': 'powerpc/tm: Block signal return setting invalid MSR state\n\nCurrently we allow both the MSR T and S bits to be set by userspace on\na signal return. Unfortunately this is a reserved configuration and\nwill cause a TM Bad Thing exception if attempted (via rfid).\n\nThis patch checks for this case in both the 32 and 64 bit signals\ncode. If both T and S are set, we mark the context as invalid.\n\nFound using a syscall fuzzer.\n\nFixes: 2b0a576d15e0 (\"powerpc: Add new transactional memory state to the signal context\")\nCc: stable@vger.kernel.org # v3.9+\nSigned-off-by: Michael Neuling \nSigned-off-by: Michael Ellerman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static pfunc check_literal(struct jv_parser* p) {\n if (p->tokenpos == 0) return 0;\n\n const char* pattern = 0;\n int plen;\n jv v;\n switch (p->tokenbuf[0]) {\n case 't': pattern = \"true\"; plen = 4; v = jv_true(); break;\n case 'f': pattern = \"false\"; plen = 5; v = jv_false(); break;\n case 'n': pattern = \"null\"; plen = 4; v = jv_null(); break;\n }\n if (pattern) {\n if (p->tokenpos != plen) return \"Invalid literal\";\n for (int i=0; itokenbuf[i] != pattern[i])\n return \"Invalid literal\";\n TRY(value(p, v));\n } else {\n // FIXME: better parser\n p->tokenbuf[p->tokenpos] = 0; // FIXME: invalid\n char* end = 0;\n double d = jvp_strtod(&p->dtoa, p->tokenbuf, &end);\n if (end == 0 || *end != 0)\n return \"Invalid numeric literal\";\n TRY(value(p, jv_number(d)));\n }\n p->tokenpos = 0;\n return 0;\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: BigInt inverse_mod(const BigInt& n, const BigInt& mod)\n {\n if(mod.is_zero())\n throw BigInt::DivideByZero();\n if(mod.is_negative() || n.is_negative())\n throw Invalid_Argument(\"inverse_mod: arguments must be non-negative\");\n\n if(n.is_zero() || (n.is_even() && mod.is_even()))\n return 0;\n\n BigInt x = mod, y = n, u = mod, v = n;\n BigInt A = 1, B = 0, C = 0, D = 1;\n\n while(u.is_nonzero())\n {\n size_t zero_bits = low_zero_bits(u);\n u >>= zero_bits;\n for(size_t i = 0; i != zero_bits; ++i)\n {\n if(A.is_odd() || B.is_odd())\n { A += y; B -= x; }\n A >>= 1; B >>= 1;\n }\n\n zero_bits = low_zero_bits(v);\n v >>= zero_bits;\n for(size_t i = 0; i != zero_bits; ++i)\n {\n if(C.is_odd() || D.is_odd())\n { C += y; D -= x; }\n C >>= 1; D >>= 1;\n }\n\n if(u >= v) { u -= v; A -= C; B -= D; }\n else { v -= u; C -= A; D -= B; }\n }\n\n if(v != 1)\n return 0;\n\n while(D.is_negative()) D += mod;\n while(D >= mod) D -= mod;\n\n return D;\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(bcsqrt)\n{\n\tchar *left;\n\tint left_len;\n\tlong scale_param = 0;\n\tbc_num result;\n\tint scale = BCG(bc_precision), argc = ZEND_NUM_ARGS();\n\n\tif (zend_parse_parameters(argc TSRMLS_CC, \"s|l\", &left, &left_len, &scale_param) == FAILURE) {\n\t\treturn;\n\t}\n\t\n\tif (argc == 2) {\n\t\tscale = (int) ((int)scale_param < 0) ? 0 : scale_param;\n\t}\n\n\tbc_init_num(&result TSRMLS_CC);\n\tphp_str2num(&result, left TSRMLS_CC);\n\t\n\tif (bc_sqrt (&result, scale TSRMLS_CC) != 0) {\n\t\tif (result->n_scale > scale) {\n\t\t\tresult->n_scale = scale;\n\t\t}\n\t\tZ_STRVAL_P(return_value) = bc_num2str(result);\n\t\tZ_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value));\n\t\tZ_TYPE_P(return_value) = IS_STRING;\n\t} else {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Square root of negative number\");\n\t}\n\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 int exif_process_IFD_TAG(image_info_type *ImageInfo, char *dir_entry, char *offset_base, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table TSRMLS_DC)\n{\n\tsize_t length;\n\tint tag, format, components;\n\tchar *value_ptr, tagname[64], cbuf[32], *outside=NULL;\n\tsize_t byte_count, offset_val, fpos, fgot;\n\tint64_t byte_count_signed;\n\txp_field_type *tmp_xp;\n#ifdef EXIF_DEBUG\n\tchar *dump_data;\n\tint dump_free;\n#endif /* EXIF_DEBUG */\n\n\t/* Protect against corrupt headers */\n\tif (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) {\n\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"corrupt EXIF header: maximum directory nesting level reached\");\n\t\treturn FALSE;\n\t}\n\tImageInfo->ifd_nesting_level++;\n\n\ttag = php_ifd_get16u(dir_entry, ImageInfo->motorola_intel);\n\tformat = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel);\n\tcomponents = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel);\n\n\tif (!format || format > NUM_FORMATS) {\n\t\t/* (-1) catches illegal zero case as unsigned underflows to positive large. */\n\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"Process tag(x%04X=%s): Illegal format code 0x%04X, suppose BYTE\", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), format);\n\t\tformat = TAG_FMT_BYTE;\n\t\t/*return TRUE;*/\n\t}\n\n\tif (components < 0) {\n\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"Process tag(x%04X=%s): Illegal components(%ld)\", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), components);\n\t\treturn FALSE;\n\t}\n\n\tbyte_count_signed = (int64_t)components * php_tiff_bytes_per_format[format];\n\n\tif (byte_count_signed < 0 || (byte_count_signed > INT32_MAX)) {\n\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"Process tag(x%04X=%s): Illegal byte_count\", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC));\n\t\treturn FALSE;\n\t}\n\n\tbyte_count = (size_t)byte_count_signed;\n\n\tif (byte_count > 4) {\n\t\toffset_val = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel);\n\t\t/* If its bigger than 4 bytes, the dir entry contains an offset. */\n\t\tvalue_ptr = offset_base+offset_val;\n /*\n dir_entry is ImageInfo->file.list[sn].data+2+i*12\n offset_base is ImageInfo->file.list[sn].data-dir_offset\n dir_entry - offset_base is dir_offset+2+i*12\n */\n\t\tif (byte_count > IFDlength || offset_val > IFDlength-byte_count || value_ptr < dir_entry || offset_val < (size_t)(dir_entry-offset_base)) {\n\t\t\t/* It is important to check for IMAGE_FILETYPE_TIFF\n\t\t\t * JPEG does not use absolute pointers instead its pointers are\n\t\t\t * relative to the start of the TIFF header in APP1 section. */\n\t\t\tif (byte_count > ImageInfo->FileSize || offset_val>ImageInfo->FileSize-byte_count || (ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_II && ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_MM && ImageInfo->FileType!=IMAGE_FILETYPE_JPEG)) {\n\t\t\t\tif (value_ptr < dir_entry) {\n\t\t\t\t\t/* we can read this if offset_val > 0 */\n\t\t\t\t\t/* some files have their values in other parts of the file */\n\t\t\t\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"Process tag(x%04X=%s): Illegal pointer offset(x%04X < x%04X)\", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val, dir_entry);\n\t\t\t\t} else {\n\t\t\t\t\t/* this is for sure not allowed */\n\t\t\t\t\t/* exception are IFD pointers */\n\t\t\t\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"Process tag(x%04X=%s): Illegal pointer offset(x%04X + x%04X = x%04X > x%04X)\", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val, byte_count, offset_val+byte_count, IFDlength);\n\t\t\t\t}\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\tif (byte_count>sizeof(cbuf)) {\n\t\t\t\t/* mark as outside range and get buffer */\n\t\t\t\tvalue_ptr = safe_emalloc(byte_count, 1, 0);\n\t\t\t\toutside = value_ptr;\n\t\t\t} else {\n\t\t\t\t/* In most cases we only access a small range so\n\t\t\t\t * it is faster to use a static buffer there\n\t\t\t\t * BUT it offers also the possibility to have\n\t\t\t\t * pointers read without the need to free them\n\t\t\t\t * explicitley before returning. */\n\t\t\t\tmemset(&cbuf, 0, sizeof(cbuf));\n\t\t\t\tvalue_ptr = cbuf;\n\t\t\t}\n\n\t\t\tfpos = php_stream_tell(ImageInfo->infile);\n\t\t\tphp_stream_seek(ImageInfo->infile, offset_val, SEEK_SET);\n\t\t\tfgot = php_stream_tell(ImageInfo->infile);\n\t\t\tif (fgot!=offset_val) {\n\t\t\t\tEFREE_IF(outside);\n\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, \"Wrong file pointer: 0x%08X != 0x%08X\", fgot, offset_val);\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\tfgot = php_stream_read(ImageInfo->infile, value_ptr, byte_count);\n\t\t\tphp_stream_seek(ImageInfo->infile, fpos, SEEK_SET);\n\t\t\tif (fgotsections_found |= FOUND_ANY_TAG;\n#ifdef EXIF_DEBUG\n\tdump_data = exif_dump_data(&dump_free, format, components, length, ImageInfo->motorola_intel, value_ptr TSRMLS_CC);\n\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Process tag(x%04X=%s,@x%04X + x%04X(=%d)): %s%s %s\", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val+displacement, byte_count, byte_count, (components>1)&&format!=TAG_FMT_UNDEFINED&&format!=TAG_FMT_STRING?\"ARRAY OF \":\"\", exif_get_tagformat(format), dump_data);\n\tif (dump_free) {\n\t\tefree(dump_data);\n\t}\n#endif\n\n\tif (section_index==SECTION_THUMBNAIL) {\n\t\tif (!ImageInfo->Thumbnail.data) {\n\t\t\tswitch(tag) {\n\t\t\t\tcase TAG_IMAGEWIDTH:\n\t\t\t\tcase TAG_COMP_IMAGE_WIDTH:\n\t\t\t\t\tImageInfo->Thumbnail.width = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase TAG_IMAGEHEIGHT:\n\t\t\t\tcase TAG_COMP_IMAGE_HEIGHT:\n\t\t\t\t\tImageInfo->Thumbnail.height = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase TAG_STRIP_OFFSETS:\n\t\t\t\tcase TAG_JPEG_INTERCHANGE_FORMAT:\n\t\t\t\t\t/* accept both formats */\n\t\t\t\t\tImageInfo->Thumbnail.offset = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase TAG_STRIP_BYTE_COUNTS:\n\t\t\t\t\tif (ImageInfo->FileType == IMAGE_FILETYPE_TIFF_II || ImageInfo->FileType == IMAGE_FILETYPE_TIFF_MM) {\n\t\t\t\t\t\tImageInfo->Thumbnail.filetype = ImageInfo->FileType;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t/* motorola is easier to read */\n\t\t\t\t\t\tImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_TIFF_MM;\n\t\t\t\t\t}\n\t\t\t\t\tImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase TAG_JPEG_INTERCHANGE_FORMAT_LEN:\n\t\t\t\t\tif (ImageInfo->Thumbnail.filetype == IMAGE_FILETYPE_UNKNOWN) {\n\t\t\t\t\t\tImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_JPEG;\n\t\t\t\t\t\tImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (section_index==SECTION_IFD0 || section_index==SECTION_EXIF)\n\t\tswitch(tag) {\n\t\t\tcase TAG_COPYRIGHT:\n\t\t\t\t/* check for \" NUL NUL\" */\n\t\t\t\tif (byte_count>1 && (length=php_strnlen(value_ptr, byte_count)) > 0) {\n\t\t\t\t\tif (lengthCopyrightPhotographer = estrdup(value_ptr);\n\t\t\t\t\t\tImageInfo->CopyrightEditor = estrndup(value_ptr+length+1, byte_count-length-1);\n\t\t\t\t\t\tspprintf(&ImageInfo->Copyright, 0, \"%s, %s\", value_ptr, value_ptr+length+1);\n\t\t\t\t\t\t/* format = TAG_FMT_UNDEFINED; this musn't be ASCII */\n\t\t\t\t\t\t/* but we are not supposed to change this */\n\t\t\t\t\t\t/* keep in mind that image_info does not store editor value */\n\t\t\t\t\t} else {\n\t\t\t\t\t\tImageInfo->Copyright = estrndup(value_ptr, byte_count);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_USERCOMMENT:\n\t\t\t\tImageInfo->UserCommentLength = exif_process_user_comment(ImageInfo, &(ImageInfo->UserComment), &(ImageInfo->UserCommentEncoding), value_ptr, byte_count TSRMLS_CC);\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_XP_TITLE:\n\t\t\tcase TAG_XP_COMMENTS:\n\t\t\tcase TAG_XP_AUTHOR:\n\t\t\tcase TAG_XP_KEYWORDS:\n\t\t\tcase TAG_XP_SUBJECT:\n\t\t\t\ttmp_xp = (xp_field_type*)safe_erealloc(ImageInfo->xp_fields.list, (ImageInfo->xp_fields.count+1), sizeof(xp_field_type), 0);\n\t\t\t\tImageInfo->sections_found |= FOUND_WINXP;\n\t\t\t\tImageInfo->xp_fields.list = tmp_xp;\n\t\t\t\tImageInfo->xp_fields.count++;\n\t\t\t\texif_process_unicode(ImageInfo, &(ImageInfo->xp_fields.list[ImageInfo->xp_fields.count-1]), tag, value_ptr, byte_count TSRMLS_CC);\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_FNUMBER:\n\t\t\t\t/* Simplest way of expressing aperture, so I trust it the most.\n\t\t\t\t (overwrite previously computed value if there is one) */\n\t\t\t\tImageInfo->ApertureFNumber = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_APERTURE:\n\t\t\tcase TAG_MAX_APERTURE:\n\t\t\t\t/* More relevant info always comes earlier, so only use this field if we don't\n\t\t\t\t have appropriate aperture information yet. */\n\t\t\t\tif (ImageInfo->ApertureFNumber == 0) {\n\t\t\t\t\tImageInfo->ApertureFNumber\n\t\t\t\t\t\t= (float)exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)*log(2)*0.5);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_SHUTTERSPEED:\n\t\t\t\t/* More complicated way of expressing exposure time, so only use\n\t\t\t\t this value if we don't already have it from somewhere else.\n\t\t\t\t SHUTTERSPEED comes after EXPOSURE TIME\n\t\t\t\t */\n\t\t\t\tif (ImageInfo->ExposureTime == 0) {\n\t\t\t\t\tImageInfo->ExposureTime\n\t\t\t\t\t\t= (float)(1/exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)*log(2)));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase TAG_EXPOSURETIME:\n\t\t\t\tImageInfo->ExposureTime = -1;\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_COMP_IMAGE_WIDTH:\n\t\t\t\tImageInfo->ExifImageWidth = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_FOCALPLANE_X_RES:\n\t\t\t\tImageInfo->FocalplaneXRes = exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_SUBJECT_DISTANCE:\n\t\t\t\t/* Inidcates the distacne the autofocus camera is focused to.\n\t\t\t\t Tends to be less accurate as distance increases. */\n\t\t\t\tImageInfo->Distance = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_FOCALPLANE_RESOLUTION_UNIT:\n\t\t\t\tswitch((int)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)) {\n\t\t\t\t\tcase 1: ImageInfo->FocalplaneUnits = 25.4; break; /* inch */\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\t/* According to the information I was using, 2 measn meters.\n\t\t\t\t\t\t But looking at the Cannon powershot's files, inches is the only\n\t\t\t\t\t\t sensible value. */\n\t\t\t\t\t\tImageInfo->FocalplaneUnits = 25.4;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 3: ImageInfo->FocalplaneUnits = 10; break; /* centimeter */\n\t\t\t\t\tcase 4: ImageInfo->FocalplaneUnits = 1; break; /* milimeter */\n\t\t\t\t\tcase 5: ImageInfo->FocalplaneUnits = .001; break; /* micrometer */\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_SUB_IFD:\n\t\t\t\tif (format==TAG_FMT_IFD) {\n\t\t\t\t\t/* If this is called we are either in a TIFFs thumbnail or a JPEG where we cannot handle it */\n\t\t\t\t\t/* TIFF thumbnail: our data structure cannot store a thumbnail of a thumbnail */\n\t\t\t\t\t/* JPEG do we have the data area and what to do with it */\n\t\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Skip SUB IFD\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_MAKE:\n\t\t\t\tImageInfo->make = estrndup(value_ptr, byte_count);\n\t\t\t\tbreak;\n\t\t\tcase TAG_MODEL:\n\t\t\t\tImageInfo->model = estrndup(value_ptr, byte_count);\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_MAKER_NOTE:\n\t\t\t\texif_process_IFD_in_MAKERNOTE(ImageInfo, value_ptr, byte_count, offset_base, IFDlength, displacement TSRMLS_CC);\n\t\t\t\tbreak;\n\n\t\t\tcase TAG_EXIF_IFD_POINTER:\n\t\t\tcase TAG_GPS_IFD_POINTER:\n\t\t\tcase TAG_INTEROP_IFD_POINTER:\n\t\t\t\tif (ReadNextIFD) {\n\t\t\t\t\tchar *Subdir_start;\n\t\t\t\t\tint sub_section_index = 0;\n\t\t\t\t\tswitch(tag) {\n\t\t\t\t\t\tcase TAG_EXIF_IFD_POINTER:\n#ifdef EXIF_DEBUG\n\t\t\t\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Found EXIF\");\n#endif\n\t\t\t\t\t\t\tImageInfo->sections_found |= FOUND_EXIF;\n\t\t\t\t\t\t\tsub_section_index = SECTION_EXIF;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase TAG_GPS_IFD_POINTER:\n#ifdef EXIF_DEBUG\n\t\t\t\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Found GPS\");\n#endif\n\t\t\t\t\t\t\tImageInfo->sections_found |= FOUND_GPS;\n\t\t\t\t\t\t\tsub_section_index = SECTION_GPS;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase TAG_INTEROP_IFD_POINTER:\n#ifdef EXIF_DEBUG\n\t\t\t\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Found INTEROPERABILITY\");\n#endif\n\t\t\t\t\t\t\tImageInfo->sections_found |= FOUND_INTEROP;\n\t\t\t\t\t\t\tsub_section_index = SECTION_INTEROP;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tSubdir_start = offset_base + php_ifd_get32u(value_ptr, ImageInfo->motorola_intel);\n\t\t\t\t\tif (Subdir_start < offset_base || Subdir_start > offset_base+IFDlength) {\n\t\t\t\t\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"Illegal IFD Pointer\");\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t\t}\n\t\t\t\t\tif (!exif_process_IFD_in_JPEG(ImageInfo, Subdir_start, offset_base, IFDlength, displacement, sub_section_index TSRMLS_CC)) {\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t\t}\n#ifdef EXIF_DEBUG\n\t\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Subsection %s done\", exif_get_sectionname(sub_section_index));\n#endif\n\t\t\t\t}\n\t\t}\n\t}\n\texif_iif_add_tag(ImageInfo, section_index, exif_get_tagname(tag, tagname, sizeof(tagname), tag_table TSRMLS_CC), tag, format, components, value_ptr TSRMLS_CC);\n\tEFREE_IF(outside);\n\treturn TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug #72094 - Out of bounds heap read access in exif header processing'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PHP_FUNCTION(xml_parse_into_struct)\n{\n\txml_parser *parser;\n\tzval *pind, **xdata, **info = NULL;\n\tchar *data;\n\tint data_len, ret;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"rsZ|Z\", &pind, &data, &data_len, &xdata, &info) == FAILURE) {\n\t\treturn;\n\t}\n\t\n\tif (info) {\t\n\t\tzval_dtor(*info);\n\t\tarray_init(*info);\n\t}\n\n\tZEND_FETCH_RESOURCE(parser,xml_parser *, &pind, -1, \"XML Parser\", le_xml_parser);\n\n\tzval_dtor(*xdata);\n\tarray_init(*xdata);\n\n\tparser->data = *xdata;\n\t\n\tif (info) {\n\t\tparser->info = *info;\n\t}\n\t\n\tparser->level = 0;\n\tparser->ltags = safe_emalloc(XML_MAXLEVEL, sizeof(char *), 0);\n\n\tXML_SetDefaultHandler(parser->parser, _xml_defaultHandler);\n\tXML_SetElementHandler(parser->parser, _xml_startElementHandler, _xml_endElementHandler);\n\tXML_SetCharacterDataHandler(parser->parser, _xml_characterDataHandler);\n\n\tparser->isparsing = 1;\n\tret = XML_Parse(parser->parser, data, data_len, 1);\n\tparser->isparsing = 0;\n\n\tRETVAL_LONG(ret);\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: SPL_METHOD(SplDoublyLinkedList, offsetSet)\n{\n\tzval *zindex, *value;\n\tspl_dllist_object *intern;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS(), \"zz\", &zindex, &value) == FAILURE) {\n\t\treturn;\n\t}\n\n\tintern = Z_SPLDLLIST_P(getThis());\n\n\tif (Z_TYPE_P(zindex) == IS_NULL) {\n\t\t/* $obj[] = ... */\n\t\tspl_ptr_llist_push(intern->llist, value);\n\t} else {\n\t\t/* $obj[$foo] = ... */\n\t\tzend_long index;\n\t\tspl_ptr_llist_element *element;\n\n\t\tindex = spl_offset_convert_to_long(zindex);\n\n\t\tif (index < 0 || index >= intern->llist->count) {\n\t\t\tzval_ptr_dtor(value);\n\t\t\tzend_throw_exception(spl_ce_OutOfRangeException, \"Offset invalid or out of range\", 0);\n\t\t\treturn;\n\t\t}\n\n\t\telement = spl_ptr_llist_offset(intern->llist, index, intern->flags & SPL_DLLIST_IT_LIFO);\n\n\t\tif (element != NULL) {\n\t\t\t/* call dtor on the old element as in spl_ptr_llist_pop */\n\t\t\tif (intern->llist->dtor) {\n\t\t\t\tintern->llist->dtor(element);\n\t\t\t}\n\n\t\t\t/* the element is replaced, delref the old one as in\n\t\t\t * SplDoublyLinkedList::pop() */\n\t\t\tzval_ptr_dtor(&element->data);\n\t\t\tZVAL_COPY_VALUE(&element->data, value);\n\n\t\t\t/* new element, call ctor as in spl_ptr_llist_push */\n\t\t\tif (intern->llist->ctor) {\n\t\t\t\tintern->llist->ctor(element);\n\t\t\t}\n\t\t} else {\n\t\t\tzval_ptr_dtor(value);\n\t\t\tzend_throw_exception(spl_ce_OutOfRangeException, \"Offset invalid\", 0);\n\t\t\treturn;\n\t\t}\n\t}\n} /* }}} */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'Fix bug #71735: Double-free in SplDoublyLinkedList::offsetSet'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void *bpf_any_get(void *raw, enum bpf_type type)\n{\n\tswitch (type) {\n\tcase BPF_TYPE_PROG:\n\t\tatomic_inc(&((struct bpf_prog *)raw)->aux->refcnt);\n\t\tbreak;\n\tcase BPF_TYPE_MAP:\n\t\tbpf_map_inc(raw, true);\n\t\tbreak;\n\tdefault:\n\t\tWARN_ON_ONCE(1);\n\t\tbreak;\n\t}\n\n\treturn raw;\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: polarssl_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 /* PolarSSL only supports SSLv3 and TLSv1 */\n if(data->set.ssl.version == CURL_SSLVERSION_SSLv2) {\n failf(data, \"PolarSSL 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\n if((ret = ctr_drbg_init(&connssl->ctr_drbg, entropy_func_mutex, &entropy,\n NULL, 0)) != 0) {\n#ifdef POLARSSL_ERROR_C\n error_strerror(ret, errorbuf, sizeof(errorbuf));\n#endif /* POLARSSL_ERROR_C */\n failf(data, \"Failed - PolarSSL: ctr_drbg_init returned (-0x%04X) %s\\n\",\n -ret, errorbuf);\n }\n#else\n entropy_init(&connssl->entropy);\n\n if((ret = ctr_drbg_init(&connssl->ctr_drbg, entropy_func, &connssl->entropy,\n NULL, 0)) != 0) {\n#ifdef POLARSSL_ERROR_C\n error_strerror(ret, errorbuf, sizeof(errorbuf));\n#endif /* POLARSSL_ERROR_C */\n failf(data, \"Failed - PolarSSL: ctr_drbg_init returned (-0x%04X) %s\\n\",\n -ret, errorbuf);\n }\n#endif /* THREADING_SUPPORT */\n\n /* Load the trusted CA */\n memset(&connssl->cacert, 0, sizeof(x509_crt));\n\n if(data->set.str[STRING_SSL_CAFILE]) {\n ret = x509_crt_parse_file(&connssl->cacert,\n data->set.str[STRING_SSL_CAFILE]);\n\n if(ret<0) {\n#ifdef POLARSSL_ERROR_C\n error_strerror(ret, errorbuf, sizeof(errorbuf));\n#endif /* POLARSSL_ERROR_C */\n failf(data, \"Error reading ca cert file %s - PolarSSL: (-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 = x509_crt_parse_path(&connssl->cacert,\n data->set.str[STRING_SSL_CAPATH]);\n\n if(ret<0) {\n#ifdef POLARSSL_ERROR_C\n error_strerror(ret, errorbuf, sizeof(errorbuf));\n#endif /* POLARSSL_ERROR_C */\n failf(data, \"Error reading ca cert path %s - PolarSSL: (-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 memset(&connssl->clicert, 0, sizeof(x509_crt));\n\n if(data->set.str[STRING_CERT]) {\n ret = x509_crt_parse_file(&connssl->clicert,\n data->set.str[STRING_CERT]);\n\n if(ret) {\n#ifdef POLARSSL_ERROR_C\n error_strerror(ret, errorbuf, sizeof(errorbuf));\n#endif /* POLARSSL_ERROR_C */\n failf(data, \"Error reading client cert file %s - PolarSSL: (-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 if(data->set.str[STRING_KEY]) {\n pk_context pk;\n pk_init(&pk);\n ret = pk_parse_keyfile(&pk, data->set.str[STRING_KEY],\n data->set.str[STRING_KEY_PASSWD]);\n if(ret == 0 && !pk_can_do(&pk, POLARSSL_PK_RSA))\n ret = POLARSSL_ERR_PK_TYPE_MISMATCH;\n if(ret == 0)\n rsa_copy(&connssl->rsa, pk_rsa(pk));\n else\n rsa_free(&connssl->rsa);\n pk_free(&pk);\n\n if(ret) {\n#ifdef POLARSSL_ERROR_C\n error_strerror(ret, errorbuf, sizeof(errorbuf));\n#endif /* POLARSSL_ERROR_C */\n failf(data, \"Error reading private key %s - PolarSSL: (-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 memset(&connssl->crl, 0, sizeof(x509_crl));\n\n if(data->set.str[STRING_SSL_CRLFILE]) {\n ret = x509_crl_parse_file(&connssl->crl,\n data->set.str[STRING_SSL_CRLFILE]);\n\n if(ret) {\n#ifdef POLARSSL_ERROR_C\n error_strerror(ret, errorbuf, sizeof(errorbuf));\n#endif /* POLARSSL_ERROR_C */\n failf(data, \"Error reading CRL file %s - PolarSSL: (-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, \"PolarSSL: Connecting to %s:%d\\n\",\n conn->host.name, conn->remote_port);\n\n if(ssl_init(&connssl->ssl)) {\n failf(data, \"PolarSSL: ssl_init failed\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n\n switch(data->set.ssl.version) {\n default:\n case CURL_SSLVERSION_DEFAULT:\n case CURL_SSLVERSION_TLSv1:\n ssl_set_min_version(&connssl->ssl, SSL_MAJOR_VERSION_3,\n SSL_MINOR_VERSION_1);\n break;\n case CURL_SSLVERSION_SSLv3:\n ssl_set_min_version(&connssl->ssl, SSL_MAJOR_VERSION_3,\n SSL_MINOR_VERSION_0);\n ssl_set_max_version(&connssl->ssl, SSL_MAJOR_VERSION_3,\n SSL_MINOR_VERSION_0);\n infof(data, \"PolarSSL: Forced min. SSL Version to be SSLv3\\n\");\n break;\n case CURL_SSLVERSION_TLSv1_0:\n ssl_set_min_version(&connssl->ssl, SSL_MAJOR_VERSION_3,\n SSL_MINOR_VERSION_1);\n ssl_set_max_version(&connssl->ssl, SSL_MAJOR_VERSION_3,\n SSL_MINOR_VERSION_1);\n infof(data, \"PolarSSL: Forced min. SSL Version to be TLS 1.0\\n\");\n break;\n case CURL_SSLVERSION_TLSv1_1:\n ssl_set_min_version(&connssl->ssl, SSL_MAJOR_VERSION_3,\n SSL_MINOR_VERSION_2);\n ssl_set_max_version(&connssl->ssl, SSL_MAJOR_VERSION_3,\n SSL_MINOR_VERSION_2);\n infof(data, \"PolarSSL: Forced min. SSL Version to be TLS 1.1\\n\");\n break;\n case CURL_SSLVERSION_TLSv1_2:\n ssl_set_min_version(&connssl->ssl, SSL_MAJOR_VERSION_3,\n SSL_MINOR_VERSION_3);\n ssl_set_max_version(&connssl->ssl, SSL_MAJOR_VERSION_3,\n SSL_MINOR_VERSION_3);\n infof(data, \"PolarSSL: Forced min. SSL Version to be TLS 1.2\\n\");\n break;\n }\n\n ssl_set_endpoint(&connssl->ssl, SSL_IS_CLIENT);\n ssl_set_authmode(&connssl->ssl, SSL_VERIFY_OPTIONAL);\n\n ssl_set_rng(&connssl->ssl, ctr_drbg_random,\n &connssl->ctr_drbg);\n ssl_set_bio(&connssl->ssl,\n net_recv, &conn->sock[sockindex],\n net_send, &conn->sock[sockindex]);\n\n ssl_set_ciphersuites(&connssl->ssl, ssl_list_ciphersuites());\n if(!Curl_ssl_getsessionid(conn, &old_session, NULL)) {\n ret = ssl_set_session(&connssl->ssl, old_session);\n if(ret) {\n failf(data, \"ssl_set_session returned -0x%x\", -ret);\n return CURLE_SSL_CONNECT_ERROR;\n }\n infof(data, \"PolarSSL re-using session\\n\");\n }\n\n ssl_set_ca_chain(&connssl->ssl,\n &connssl->cacert,\n &connssl->crl,\n conn->host.name);\n\n ssl_set_own_cert_rsa(&connssl->ssl,\n &connssl->clicert, &connssl->rsa);\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 && 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 static const char* protocols[3];\n int cur = 0;\n\n#ifdef USE_NGHTTP2\n if(data->set.httpversion >= CURL_HTTP_VERSION_2) {\n protocols[cur++] = NGHTTP2_PROTO_VERSION_ID;\n infof(data, \"ALPN, offering %s\\n\", NGHTTP2_PROTO_VERSION_ID);\n }\n#endif\n\n protocols[cur++] = ALPN_HTTP_1_1;\n infof(data, \"ALPN, offering %s\\n\", ALPN_HTTP_1_1);\n\n protocols[cur] = NULL;\n\n ssl_set_alpn_protocols(&connssl->ssl, protocols);\n }\n#endif\n\n#ifdef POLARSSL_DEBUG\n ssl_set_dbg(&connssl->ssl, polarssl_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: gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color)\n{\n int lastBorder;\n /* Seek left */\n int leftLimit, rightLimit;\n int i;\n leftLimit = (-1);\n if (border < 0)\n {\n /* Refuse to fill to a non-solid border */\n return;\n }\n for (i = x; (i >= 0); i--)\n {\n if (gdImageGetPixel (im, i, y) == border)\n\t{\n\t break;\n\t}\n gdImageSetPixel (im, i, y, color);\n leftLimit = i;\n }\n if (leftLimit == (-1))\n {\n return;\n }\n /* Seek right */\n rightLimit = x;\n for (i = (x + 1); (i < im->sx); i++)\n {\n if (gdImageGetPixel (im, i, y) == border)\n\t{\n\t break;\n\t}\n gdImageSetPixel (im, i, y, color);\n rightLimit = i;\n }\n /* Look at lines above and below and start paints */\n /* Above */\n if (y > 0)\n {\n lastBorder = 1;\n for (i = leftLimit; (i <= rightLimit); i++)\n\t{\n\t int c;\n\t c = gdImageGetPixel (im, i, y - 1);\n\t if (lastBorder)\n\t {\n\t if ((c != border) && (c != color))\n\t\t{\n\t\t gdImageFillToBorder (im, i, y - 1,\n\t\t\t\t border, color);\n\t\t lastBorder = 0;\n\t\t}\n\t }\n\t else if ((c == border) || (c == color))\n\t {\n\t lastBorder = 1;\n\t }\n\t}\n }\n /* Below */\n if (y < ((im->sy) - 1))\n {\n lastBorder = 1;\n for (i = leftLimit; (i <= rightLimit); i++)\n\t{\n\t int c;\n\t c = gdImageGetPixel (im, i, y + 1);\n\t if (lastBorder)\n\t {\n\t if ((c != border) && (c != color))\n\t\t{\n\t\t gdImageFillToBorder (im, i, y + 1,\n\t\t\t\t border, color);\n\t\t lastBorder = 0;\n\t\t}\n\t }\n\t else if ((c == border) || (c == color))\n\t {\n\t lastBorder = 1;\n\t }\n\t}\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fixed bug #22965 (Crash in gd lib's ImageFillToBorder()).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xmlFatalErr(xmlParserCtxtPtr ctxt, xmlParserErrors error, const char *info)\n{\n const char *errmsg;\n char errstr[129] = \"\";\n\n if ((ctxt != NULL) && (ctxt->disableSAX != 0) &&\n (ctxt->instate == XML_PARSER_EOF))\n\treturn;\n switch (error) {\n case XML_ERR_INVALID_HEX_CHARREF:\n errmsg = \"CharRef: invalid hexadecimal value\";\n break;\n case XML_ERR_INVALID_DEC_CHARREF:\n errmsg = \"CharRef: invalid decimal value\";\n break;\n case XML_ERR_INVALID_CHARREF:\n errmsg = \"CharRef: invalid value\";\n break;\n case XML_ERR_INTERNAL_ERROR:\n errmsg = \"internal error\";\n break;\n case XML_ERR_PEREF_AT_EOF:\n errmsg = \"PEReference at end of document\";\n break;\n case XML_ERR_PEREF_IN_PROLOG:\n errmsg = \"PEReference in prolog\";\n break;\n case XML_ERR_PEREF_IN_EPILOG:\n errmsg = \"PEReference in epilog\";\n break;\n case XML_ERR_PEREF_NO_NAME:\n errmsg = \"PEReference: no name\";\n break;\n case XML_ERR_PEREF_SEMICOL_MISSING:\n errmsg = \"PEReference: expecting ';'\";\n break;\n case XML_ERR_ENTITY_LOOP:\n errmsg = \"Detected an entity reference loop\";\n break;\n case XML_ERR_ENTITY_NOT_STARTED:\n errmsg = \"EntityValue: \\\" or ' expected\";\n break;\n case XML_ERR_ENTITY_PE_INTERNAL:\n errmsg = \"PEReferences forbidden in internal subset\";\n break;\n case XML_ERR_ENTITY_NOT_FINISHED:\n errmsg = \"EntityValue: \\\" or ' expected\";\n break;\n case XML_ERR_ATTRIBUTE_NOT_STARTED:\n errmsg = \"AttValue: \\\" or ' expected\";\n break;\n case XML_ERR_LT_IN_ATTRIBUTE:\n errmsg = \"Unescaped '<' not allowed in attributes values\";\n break;\n case XML_ERR_LITERAL_NOT_STARTED:\n errmsg = \"SystemLiteral \\\" or ' expected\";\n break;\n case XML_ERR_LITERAL_NOT_FINISHED:\n errmsg = \"Unfinished System or Public ID \\\" or ' expected\";\n break;\n case XML_ERR_MISPLACED_CDATA_END:\n errmsg = \"Sequence ']]>' not allowed in content\";\n break;\n case XML_ERR_URI_REQUIRED:\n errmsg = \"SYSTEM or PUBLIC, the URI is missing\";\n break;\n case XML_ERR_PUBID_REQUIRED:\n errmsg = \"PUBLIC, the Public Identifier is missing\";\n break;\n case XML_ERR_HYPHEN_IN_COMMENT:\n errmsg = \"Comment must not contain '--' (double-hyphen)\";\n break;\n case XML_ERR_PI_NOT_STARTED:\n errmsg = \"xmlParsePI : no target name\";\n break;\n case XML_ERR_RESERVED_XML_NAME:\n errmsg = \"Invalid PI name\";\n break;\n case XML_ERR_NOTATION_NOT_STARTED:\n errmsg = \"NOTATION: Name expected here\";\n break;\n case XML_ERR_NOTATION_NOT_FINISHED:\n errmsg = \"'>' required to close NOTATION declaration\";\n break;\n case XML_ERR_VALUE_REQUIRED:\n errmsg = \"Entity value required\";\n break;\n case XML_ERR_URI_FRAGMENT:\n errmsg = \"Fragment not allowed\";\n break;\n case XML_ERR_ATTLIST_NOT_STARTED:\n errmsg = \"'(' required to start ATTLIST enumeration\";\n break;\n case XML_ERR_NMTOKEN_REQUIRED:\n errmsg = \"NmToken expected in ATTLIST enumeration\";\n break;\n case XML_ERR_ATTLIST_NOT_FINISHED:\n errmsg = \"')' required to finish ATTLIST enumeration\";\n break;\n case XML_ERR_MIXED_NOT_STARTED:\n errmsg = \"MixedContentDecl : '|' or ')*' expected\";\n break;\n case XML_ERR_PCDATA_REQUIRED:\n errmsg = \"MixedContentDecl : '#PCDATA' expected\";\n break;\n case XML_ERR_ELEMCONTENT_NOT_STARTED:\n errmsg = \"ContentDecl : Name or '(' expected\";\n break;\n case XML_ERR_ELEMCONTENT_NOT_FINISHED:\n errmsg = \"ContentDecl : ',' '|' or ')' expected\";\n break;\n case XML_ERR_PEREF_IN_INT_SUBSET:\n errmsg =\n \"PEReference: forbidden within markup decl in internal subset\";\n break;\n case XML_ERR_GT_REQUIRED:\n errmsg = \"expected '>'\";\n break;\n case XML_ERR_CONDSEC_INVALID:\n errmsg = \"XML conditional section '[' expected\";\n break;\n case XML_ERR_EXT_SUBSET_NOT_FINISHED:\n errmsg = \"Content error in the external subset\";\n break;\n case XML_ERR_CONDSEC_INVALID_KEYWORD:\n errmsg =\n \"conditional section INCLUDE or IGNORE keyword expected\";\n break;\n case XML_ERR_CONDSEC_NOT_FINISHED:\n errmsg = \"XML conditional section not closed\";\n break;\n case XML_ERR_XMLDECL_NOT_STARTED:\n errmsg = \"Text declaration '' expected\";\n break;\n case XML_ERR_EXT_ENTITY_STANDALONE:\n errmsg = \"external parsed entities cannot be standalone\";\n break;\n case XML_ERR_ENTITYREF_SEMICOL_MISSING:\n errmsg = \"EntityRef: expecting ';'\";\n break;\n case XML_ERR_DOCTYPE_NOT_FINISHED:\n errmsg = \"DOCTYPE improperly terminated\";\n break;\n case XML_ERR_LTSLASH_REQUIRED:\n errmsg = \"EndTag: 'errNo = error;\n __xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_PARSER, error,\n XML_ERR_FATAL, NULL, 0, info, NULL, NULL, 0, 0, &errstr[0],\n info);\n if (ctxt != NULL) {\n\tctxt->wellFormed = 0;\n\tif (ctxt->recovery == 0)\n\t ctxt->disableSAX = 1;\n }\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: xmlSchemaFormatNodeForError(xmlChar ** msg,\n\t\t\t xmlSchemaAbstractCtxtPtr actxt,\n\t\t\t xmlNodePtr node)\n{\n xmlChar *str = NULL;\n\n *msg = NULL;\n if ((node != NULL) &&\n\t(node->type != XML_ELEMENT_NODE) &&\n\t(node->type != XML_ATTRIBUTE_NODE))\n {\n\t/*\n\t* Don't try to format other nodes than element and\n\t* attribute nodes.\n\t* Play save and return an empty string.\n\t*/\n\t*msg = xmlStrdup(BAD_CAST \"\");\n\treturn(*msg);\n }\n if (node != NULL) {\n\t/*\n\t* Work on tree nodes.\n\t*/\n\tif (node->type == XML_ATTRIBUTE_NODE) {\n\t xmlNodePtr elem = node->parent;\n\n\t *msg = xmlStrdup(BAD_CAST \"Element '\");\n\t if (elem->ns != NULL)\n\t\t*msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str,\n\t\t elem->ns->href, elem->name));\n\t else\n\t\t*msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str,\n\t\t NULL, elem->name));\n\t FREE_AND_NULL(str);\n\t *msg = xmlStrcat(*msg, BAD_CAST \"', \");\n\t *msg = xmlStrcat(*msg, BAD_CAST \"attribute '\");\n\t} else {\n\t *msg = xmlStrdup(BAD_CAST \"Element '\");\n\t}\n\tif (node->ns != NULL)\n\t *msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str,\n\t node->ns->href, node->name));\n\telse\n\t *msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str,\n\t NULL, node->name));\n\tFREE_AND_NULL(str);\n\t*msg = xmlStrcat(*msg, BAD_CAST \"': \");\n } else if (actxt->type == XML_SCHEMA_CTXT_VALIDATOR) {\n\txmlSchemaValidCtxtPtr vctxt = (xmlSchemaValidCtxtPtr) actxt;\n\t/*\n\t* Work on node infos.\n\t*/\n\tif (vctxt->inode->nodeType == XML_ATTRIBUTE_NODE) {\n\t xmlSchemaNodeInfoPtr ielem =\n\t\tvctxt->elemInfos[vctxt->depth];\n\n\t *msg = xmlStrdup(BAD_CAST \"Element '\");\n\t *msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str,\n\t\tielem->nsName, ielem->localName));\n\t FREE_AND_NULL(str);\n\t *msg = xmlStrcat(*msg, BAD_CAST \"', \");\n\t *msg = xmlStrcat(*msg, BAD_CAST \"attribute '\");\n\t} else {\n\t *msg = xmlStrdup(BAD_CAST \"Element '\");\n\t}\n\t*msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str,\n\t vctxt->inode->nsName, vctxt->inode->localName));\n\tFREE_AND_NULL(str);\n\t*msg = xmlStrcat(*msg, BAD_CAST \"': \");\n } else if (actxt->type == XML_SCHEMA_CTXT_PARSER) {\n\t/*\n\t* Hmm, no node while parsing?\n\t* Return an empty string, in case NULL will break something.\n\t*/\n\t*msg = xmlStrdup(BAD_CAST \"\");\n } else {\n\tTODO\n\treturn (NULL);\n }\n /*\n * VAL TODO: The output of the given schema component is currently\n * disabled.\n */\n#if 0\n if ((type != NULL) && (xmlSchemaIsGlobalItem(type))) {\n\t*msg = xmlStrcat(*msg, BAD_CAST \" [\");\n\t*msg = xmlStrcat(*msg, xmlSchemaFormatItemForReport(&str,\n\t NULL, type, NULL, 0));\n\tFREE_AND_NULL(str)\n\t*msg = xmlStrcat(*msg, BAD_CAST \"]\");\n }\n#endif\n return (*msg);\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: xmlStringLenDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int len,\n\t\t int what, xmlChar end, xmlChar end2, xmlChar end3) {\n xmlChar *buffer = NULL;\n size_t buffer_size = 0;\n size_t nbchars = 0;\n\n xmlChar *current = NULL;\n xmlChar *rep = NULL;\n const xmlChar *last;\n xmlEntityPtr ent;\n int c,l;\n\n if ((ctxt == NULL) || (str == NULL) || (len < 0))\n\treturn(NULL);\n last = str + len;\n\n if (((ctxt->depth > 40) &&\n ((ctxt->options & XML_PARSE_HUGE) == 0)) ||\n\t(ctxt->depth > 1024)) {\n\txmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);\n\treturn(NULL);\n }\n\n /*\n * allocate a translation buffer.\n */\n buffer_size = XML_PARSER_BIG_BUFFER_SIZE;\n buffer = (xmlChar *) xmlMallocAtomic(buffer_size);\n if (buffer == NULL) goto mem_error;\n\n /*\n * OK loop until we reach one of the ending char or a size limit.\n * we are operating on already parsed values.\n */\n if (str < last)\n\tc = CUR_SCHAR(str, l);\n else\n c = 0;\n while ((c != 0) && (c != end) && /* non input consuming loop */\n\t (c != end2) && (c != end3)) {\n\n\tif (c == 0) break;\n if ((c == '&') && (str[1] == '#')) {\n\t int val = xmlParseStringCharRef(ctxt, &str);\n\t if (val != 0) {\n\t\tCOPY_BUF(0,buffer,nbchars,val);\n\t }\n\t if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {\n\t growBuffer(buffer, XML_PARSER_BUFFER_SIZE);\n\t }\n\t} else if ((c == '&') && (what & XML_SUBSTITUTE_REF)) {\n\t if (xmlParserDebugEntities)\n\t\txmlGenericError(xmlGenericErrorContext,\n\t\t\t\"String decoding Entity Reference: %.30s\\n\",\n\t\t\tstr);\n\t ent = xmlParseStringEntityRef(ctxt, &str);\n\t if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) ||\n\t (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR))\n\t goto int_error;\n\t xmlParserEntityCheck(ctxt, 0, ent, 0);\n\t if (ent != NULL)\n\t ctxt->nbentities += ent->checked / 2;\n\t if ((ent != NULL) &&\n\t\t(ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) {\n\t\tif (ent->content != NULL) {\n\t\t COPY_BUF(0,buffer,nbchars,ent->content[0]);\n\t\t if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {\n\t\t\tgrowBuffer(buffer, XML_PARSER_BUFFER_SIZE);\n\t\t }\n\t\t} else {\n\t\t xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR,\n\t\t\t \"predefined entity has no content\\n\");\n\t\t}\n\t } else if ((ent != NULL) && (ent->content != NULL)) {\n\t\tctxt->depth++;\n\t\trep = xmlStringDecodeEntities(ctxt, ent->content, what,\n\t\t\t 0, 0, 0);\n\t\tctxt->depth--;\n\n\t\tif ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) ||\n\t\t (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR))\n\t\t goto int_error;\n\n\t\tif (rep != NULL) {\n\t\t current = rep;\n\t\t while (*current != 0) { /* non input consuming loop */\n\t\t\tbuffer[nbchars++] = *current++;\n\t\t\tif (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {\n\t\t\t if (xmlParserEntityCheck(ctxt, nbchars, ent, 0))\n\t\t\t\tgoto int_error;\n\t\t\t growBuffer(buffer, XML_PARSER_BUFFER_SIZE);\n\t\t\t}\n\t\t }\n\t\t xmlFree(rep);\n\t\t rep = NULL;\n\t\t}\n\t } else if (ent != NULL) {\n\t\tint i = xmlStrlen(ent->name);\n\t\tconst xmlChar *cur = ent->name;\n\n\t\tbuffer[nbchars++] = '&';\n\t\tif (nbchars + i + XML_PARSER_BUFFER_SIZE > buffer_size) {\n\t\t growBuffer(buffer, i + XML_PARSER_BUFFER_SIZE);\n\t\t}\n\t\tfor (;i > 0;i--)\n\t\t buffer[nbchars++] = *cur++;\n\t\tbuffer[nbchars++] = ';';\n\t }\n\t} else if (c == '%' && (what & XML_SUBSTITUTE_PEREF)) {\n\t if (xmlParserDebugEntities)\n\t\txmlGenericError(xmlGenericErrorContext,\n\t\t\t\"String decoding PE Reference: %.30s\\n\", str);\n\t ent = xmlParseStringPEReference(ctxt, &str);\n\t if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP)\n\t goto int_error;\n\t xmlParserEntityCheck(ctxt, 0, ent, 0);\n\t if (ent != NULL)\n\t ctxt->nbentities += ent->checked / 2;\n\t if (ent != NULL) {\n if (ent->content == NULL) {\n\t\t xmlLoadEntityContent(ctxt, ent);\n\t\t}\n\t\tctxt->depth++;\n\t\trep = xmlStringDecodeEntities(ctxt, ent->content, what,\n\t\t\t 0, 0, 0);\n\t\tctxt->depth--;\n\t\tif (rep != NULL) {\n\t\t current = rep;\n\t\t while (*current != 0) { /* non input consuming loop */\n\t\t\tbuffer[nbchars++] = *current++;\n\t\t\tif (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {\n\t\t\t if (xmlParserEntityCheck(ctxt, nbchars, ent, 0))\n\t\t\t goto int_error;\n\t\t\t growBuffer(buffer, XML_PARSER_BUFFER_SIZE);\n\t\t\t}\n\t\t }\n\t\t xmlFree(rep);\n\t\t rep = NULL;\n\t\t}\n\t }\n\t} else {\n\t COPY_BUF(l,buffer,nbchars,c);\n\t str += l;\n\t if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {\n\t growBuffer(buffer, XML_PARSER_BUFFER_SIZE);\n\t }\n\t}\n\tif (str < last)\n\t c = CUR_SCHAR(str, l);\n\telse\n\t c = 0;\n }\n buffer[nbchars] = 0;\n return(buffer);\n\nmem_error:\n xmlErrMemory(ctxt, NULL);\nint_error:\n if (rep != NULL)\n xmlFree(rep);\n if (buffer != NULL)\n xmlFree(buffer);\n return(NULL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix inappropriate fetch of entities content\n\nFor https://bugzilla.gnome.org/show_bug.cgi?id=761430\n\nlibfuzzer regression testing exposed another case where the parser would\nfetch content of an external entity while not in validating mode.\nPlug that hole'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int x25_negotiate_facilities(struct sk_buff *skb, struct sock *sk,\n\t\tstruct x25_facilities *new, struct x25_dte_facilities *dte)\n{\n\tstruct x25_sock *x25 = x25_sk(sk);\n\tstruct x25_facilities *ours = &x25->facilities;\n\tstruct x25_facilities theirs;\n\tint len;\n\n\tmemset(&theirs, 0, sizeof(theirs));\n\tmemcpy(new, ours, sizeof(*new));\n\n\tlen = x25_parse_facilities(skb, &theirs, dte, &x25->vc_facil_mask);\n\tif (len < 0)\n\t\treturn len;\n\n\t/*\n\t *\tThey want reverse charging, we won't accept it.\n\t */\n\tif ((theirs.reverse & 0x01 ) && (ours->reverse & 0x01)) {\n\t\tSOCK_DEBUG(sk, \"X.25: rejecting reverse charging request\\n\");\n\t\treturn -1;\n\t}\n\n\tnew->reverse = theirs.reverse;\n\n\tif (theirs.throughput) {\n\t\tint theirs_in = theirs.throughput & 0x0f;\n\t\tint theirs_out = theirs.throughput & 0xf0;\n\t\tint ours_in = ours->throughput & 0x0f;\n\t\tint ours_out = ours->throughput & 0xf0;\n\t\tif (!ours_in || theirs_in < ours_in) {\n\t\t\tSOCK_DEBUG(sk, \"X.25: inbound throughput negotiated\\n\");\n\t\t\tnew->throughput = (new->throughput & 0xf0) | theirs_in;\n\t\t}\n\t\tif (!ours_out || theirs_out < ours_out) {\n\t\t\tSOCK_DEBUG(sk,\n\t\t\t\t\"X.25: outbound throughput negotiated\\n\");\n\t\t\tnew->throughput = (new->throughput & 0x0f) | theirs_out;\n\t\t}\n\t}\n\n\tif (theirs.pacsize_in && theirs.pacsize_out) {\n\t\tif (theirs.pacsize_in < ours->pacsize_in) {\n\t\t\tSOCK_DEBUG(sk, \"X.25: packet size inwards negotiated down\\n\");\n\t\t\tnew->pacsize_in = theirs.pacsize_in;\n\t\t}\n\t\tif (theirs.pacsize_out < ours->pacsize_out) {\n\t\t\tSOCK_DEBUG(sk, \"X.25: packet size outwards negotiated down\\n\");\n\t\t\tnew->pacsize_out = theirs.pacsize_out;\n\t\t}\n\t}\n\n\tif (theirs.winsize_in && theirs.winsize_out) {\n\t\tif (theirs.winsize_in < ours->winsize_in) {\n\t\t\tSOCK_DEBUG(sk, \"X.25: window size inwards negotiated down\\n\");\n\t\t\tnew->winsize_in = theirs.winsize_in;\n\t\t}\n\t\tif (theirs.winsize_out < ours->winsize_out) {\n\t\t\tSOCK_DEBUG(sk, \"X.25: window size outwards negotiated down\\n\");\n\t\t\tnew->winsize_out = theirs.winsize_out;\n\t\t}\n\t}\n\n\treturn len;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'net: fix a kernel infoleak in x25 module\n\nStack object \"dte_facilities\" is allocated in x25_rx_call_request(),\nwhich is supposed to be initialized in x25_negotiate_facilities.\nHowever, 5 fields (8 bytes in total) are not initialized. This\nobject is then copied to userland via copy_to_user, thus infoleak\noccurs.\n\nSigned-off-by: Kangjie Lu \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int add_array_entry(const char* loc_name, zval* hash_arr, char* key_name TSRMLS_DC)\n{\n\tchar* key_value \t= NULL;\n\tchar* cur_key_name\t= NULL;\n\tchar* token \t= NULL;\n\tchar* last_ptr \t= NULL;\n\n\tint\tresult\t\t= 0;\n\tint \tcur_result \t= 0;\n\tint \tcnt \t\t= 0;\n\n\n\tif( strcmp(key_name , LOC_PRIVATE_TAG)==0 ){\n\t\tkey_value = get_private_subtags( loc_name );\n\t\tresult = 1;\n\t} else {\n\t\tkey_value = get_icu_value_internal( loc_name , key_name , &result,1 );\n\t}\n\tif( (strcmp(key_name , LOC_PRIVATE_TAG)==0) || \n\t\t( strcmp(key_name , LOC_VARIANT_TAG)==0) ){\n\t\tif( result > 0 && key_value){\n\t\t\t/* Tokenize on the \"_\" or \"-\" */\n\t\t\ttoken = php_strtok_r( key_value , DELIMITER ,&last_ptr);\t\n\t\t\tif( cur_key_name ){\n\t\t\t\tefree( cur_key_name);\n\t\t\t}\n\t\t\tcur_key_name = (char*)ecalloc( 25, 25);\n\t\t\tsprintf( cur_key_name , \"%s%d\", key_name , cnt++);\t\n\t\t\tadd_assoc_string( hash_arr, cur_key_name , token ,TRUE );\n\t\t\t/* tokenize on the \"_\" or \"-\" and stop at singleton if any */\n\t\t\twhile( (token = php_strtok_r(NULL , DELIMITER , &last_ptr)) && (strlen(token)>1) ){\n\t\t\t\tsprintf( cur_key_name , \"%s%d\", key_name , cnt++);\t\n\t\t\t\tadd_assoc_string( hash_arr, cur_key_name , token , TRUE );\n\t\t\t}\n/*\n\t\t\tif( strcmp(key_name, LOC_PRIVATE_TAG) == 0 ){\n\t\t\t}\n*/\n\t\t}\n\t} else {\n\t\tif( result == 1 ){\n\t\t\tadd_assoc_string( hash_arr, key_name , key_value , TRUE );\n\t\t\tcur_result = 1;\n\t\t}\n\t}\n\n\tif( cur_key_name ){\n\t\tefree( cur_key_name);\n\t}\n\t/*if( key_name != LOC_PRIVATE_TAG && key_value){*/\n\tif( key_value){\n\t\tefree(key_value);\t\n\t}\n\treturn cur_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: static int append_key_value(smart_str* loc_name, HashTable* hash_arr, char* key_name)\n{\n\tzval**\tele_value\t= NULL;\n\n\tif(zend_hash_find(hash_arr , key_name , strlen(key_name) + 1 ,(void **)&ele_value ) == SUCCESS ) {\n\t\tif(Z_TYPE_PP(ele_value)!= IS_STRING ){\n\t\t\t/* element value is not a string */\n\t\t\treturn FAILURE;\n\t\t}\n\t\tif(strcmp(key_name, LOC_LANG_TAG) != 0 && \n\t\t strcmp(key_name, LOC_GRANDFATHERED_LANG_TAG)!=0 ) {\n\t\t\t/* not lang or grandfathered tag */\n\t\t\tsmart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1);\n\t\t}\n\t\tsmart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value));\n\t\treturn SUCCESS;\n\t}\n\n\treturn LOC_NOT_FOUND;\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_language) \n{\n get_icu_disp_value_src_php( LOC_LANG_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: static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsigned int src_size, double scale_d, const interpolation_method pFilter)\n{\n\tdouble width_d;\n\tdouble scale_f_d = 1.0;\n\tconst double filter_width_d = DEFAULT_BOX_RADIUS;\n\tint windows_size;\n\tunsigned int u;\n\tLineContribType *res;\n\n\tif (scale_d < 1.0) {\n\t\twidth_d = filter_width_d / scale_d;\n\t\tscale_f_d = scale_d;\n\t} else {\n\t\twidth_d= filter_width_d;\n\t}\n\n\twindows_size = 2 * (int)ceil(width_d) + 1;\n\tres = _gdContributionsAlloc(line_size, windows_size);\n\n\tfor (u = 0; u < line_size; u++) {\n\t\tconst double dCenter = (double)u / scale_d;\n\t\t/* get the significant edge points affecting the pixel */\n\t\tregister int iLeft = MAX(0, (int)floor (dCenter - width_d));\n\t\tint iRight = MIN((int)ceil(dCenter + width_d), (int)src_size - 1);\n\t\tdouble dTotalWeight = 0.0;\n\t\tint iSrc;\n\n\t\tres->ContribRow[u].Left = iLeft;\n\t\tres->ContribRow[u].Right = iRight;\n\n\t\t/* Cut edge points to fit in filter window in case of spill-off */\n\t\tif (iRight - iLeft + 1 > windows_size) {\n\t\t\tif (iLeft < ((int)src_size - 1 / 2)) {\n\t\t\t\tiLeft++;\n\t\t\t} else {\n\t\t\t\tiRight--;\n\t\t\t}\n\t\t}\n\n\t\tfor (iSrc = iLeft; iSrc <= iRight; iSrc++) {\n\t\t\tdTotalWeight += (res->ContribRow[u].Weights[iSrc-iLeft] = scale_f_d * (*pFilter)(scale_f_d * (dCenter - (double)iSrc)));\n\t\t}\n\n\t\tif (dTotalWeight < 0.0) {\n\t\t\t_gdContributionsFree(res);\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (dTotalWeight > 0.0) {\n\t\t\tfor (iSrc = iLeft; iSrc <= iRight; iSrc++) {\n\t\t\t\tres->ContribRow[u].Weights[iSrc-iLeft] /= dTotalWeight;\n\t\t\t}\n\t\t}\n\t}\n\treturn res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed memory overrun bug in gdImageScaleTwoPass\n\n_gdContributionsCalc would compute a window size and then adjust\nthe left and right positions of the window to make a window within\nthat size. However, it was storing the values in the struct *before*\nit made the adjustment. This change fixes 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 inline unsigned char unimap_bsearch(const uni_to_enc *table, unsigned code_key_a, size_t num)\n{\n\tconst uni_to_enc *l = table,\n\t\t\t\t\t *h = &table[num-1],\n\t\t\t\t\t *m;\n\tunsigned short code_key;\n\n\t/* we have no mappings outside the BMP */\n\tif (code_key_a > 0xFFFFU)\n\t\treturn 0;\n\n\tcode_key = (unsigned short) code_key_a;\n\t\n\twhile (l <= h) {\n\t\tm = l + (h - l) / 2;\n\t\tif (code_key < m->un_code_point)\n\t\t\th = m - 1;\n\t\telse if (code_key > m->un_code_point)\n\t\t\tl = m + 1;\n\t\telse\n\t\t\treturn m->cs_code;\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72135 - don't create strings with lengths outside int range'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PHP_MINIT_FUNCTION(filter)\n{\n\tZEND_INIT_MODULE_GLOBALS(filter, php_filter_init_globals, NULL);\n\n\tREGISTER_INI_ENTRIES();\n\n\tREGISTER_LONG_CONSTANT(\"INPUT_POST\",\tPARSE_POST, \tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"INPUT_GET\",\t\tPARSE_GET,\t\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"INPUT_COOKIE\",\tPARSE_COOKIE, \tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"INPUT_ENV\",\t\tPARSE_ENV,\t\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"INPUT_SERVER\",\tPARSE_SERVER, \tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"INPUT_SESSION\", PARSE_SESSION, \tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"INPUT_REQUEST\", PARSE_REQUEST, \tCONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_NONE\", FILTER_FLAG_NONE, CONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"FILTER_REQUIRE_SCALAR\", FILTER_REQUIRE_SCALAR, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_REQUIRE_ARRAY\", FILTER_REQUIRE_ARRAY, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FORCE_ARRAY\", FILTER_FORCE_ARRAY, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_NULL_ON_FAILURE\", FILTER_NULL_ON_FAILURE, CONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"FILTER_VALIDATE_INT\", FILTER_VALIDATE_INT, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_VALIDATE_BOOLEAN\", FILTER_VALIDATE_BOOLEAN, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_VALIDATE_FLOAT\", FILTER_VALIDATE_FLOAT, CONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"FILTER_VALIDATE_REGEXP\", FILTER_VALIDATE_REGEXP, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_VALIDATE_URL\", FILTER_VALIDATE_URL, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_VALIDATE_EMAIL\", FILTER_VALIDATE_EMAIL, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_VALIDATE_IP\", FILTER_VALIDATE_IP, CONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"FILTER_DEFAULT\", FILTER_DEFAULT, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_UNSAFE_RAW\", FILTER_UNSAFE_RAW, CONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"FILTER_SANITIZE_STRING\", FILTER_SANITIZE_STRING, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_SANITIZE_STRIPPED\", FILTER_SANITIZE_STRING, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_SANITIZE_ENCODED\", FILTER_SANITIZE_ENCODED, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_SANITIZE_SPECIAL_CHARS\", FILTER_SANITIZE_SPECIAL_CHARS, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_SANITIZE_FULL_SPECIAL_CHARS\", FILTER_SANITIZE_SPECIAL_CHARS, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_SANITIZE_EMAIL\", FILTER_SANITIZE_EMAIL, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_SANITIZE_URL\", FILTER_SANITIZE_URL, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_SANITIZE_NUMBER_INT\", FILTER_SANITIZE_NUMBER_INT, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_SANITIZE_NUMBER_FLOAT\", FILTER_SANITIZE_NUMBER_FLOAT, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_SANITIZE_MAGIC_QUOTES\", FILTER_SANITIZE_MAGIC_QUOTES, CONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"FILTER_CALLBACK\", FILTER_CALLBACK, CONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_ALLOW_OCTAL\", FILTER_FLAG_ALLOW_OCTAL, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_ALLOW_HEX\", FILTER_FLAG_ALLOW_HEX, CONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_STRIP_LOW\", FILTER_FLAG_STRIP_LOW, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_STRIP_HIGH\", FILTER_FLAG_STRIP_HIGH, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_STRIP_BACKTICK\", FILTER_FLAG_STRIP_BACKTICK, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_ENCODE_LOW\", FILTER_FLAG_ENCODE_LOW, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_ENCODE_HIGH\", FILTER_FLAG_ENCODE_HIGH, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_ENCODE_AMP\", FILTER_FLAG_ENCODE_AMP, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_NO_ENCODE_QUOTES\", FILTER_FLAG_NO_ENCODE_QUOTES, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_EMPTY_STRING_NULL\", FILTER_FLAG_EMPTY_STRING_NULL, CONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_ALLOW_FRACTION\", FILTER_FLAG_ALLOW_FRACTION, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_ALLOW_THOUSAND\", FILTER_FLAG_ALLOW_THOUSAND, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_ALLOW_SCIENTIFIC\", FILTER_FLAG_ALLOW_SCIENTIFIC, CONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_SCHEME_REQUIRED\", FILTER_FLAG_SCHEME_REQUIRED, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_HOST_REQUIRED\", FILTER_FLAG_HOST_REQUIRED, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_PATH_REQUIRED\", FILTER_FLAG_PATH_REQUIRED, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_QUERY_REQUIRED\", FILTER_FLAG_QUERY_REQUIRED, CONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_IPV4\", FILTER_FLAG_IPV4, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_IPV6\", FILTER_FLAG_IPV6, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_NO_RES_RANGE\", FILTER_FLAG_NO_RES_RANGE, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"FILTER_FLAG_NO_PRIV_RANGE\", FILTER_FLAG_NO_PRIV_RANGE, CONST_CS | CONST_PERSISTENT);\n\n\tsapi_register_input_filter(php_sapi_filter, php_sapi_filter_init TSRMLS_CC);\n\n\treturn SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Wrong value for FILTER_SANITIZE_FULL_SPECIAL_CHARS in REGISTER_LONG_CONSTANT'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *draw_info,\n const PrimitiveInfo *primitive_info)\n{\n typedef struct _LineSegment\n {\n double\n p,\n q;\n } LineSegment;\n\n LineSegment\n dx,\n dy,\n inverse_slope,\n slope,\n theta;\n\n MagickBooleanType\n closed_path;\n\n double\n delta_theta,\n dot_product,\n mid,\n miterlimit;\n\n PointInfo\n box_p[5],\n box_q[5],\n center,\n offset,\n *path_p,\n *path_q;\n\n PrimitiveInfo\n *polygon_primitive,\n *stroke_polygon;\n\n register ssize_t\n i;\n\n size_t\n arc_segments,\n max_strokes,\n number_vertices;\n\n ssize_t\n j,\n n,\n p,\n q;\n\n /*\n Allocate paths.\n */\n number_vertices=primitive_info->coordinates;\n max_strokes=2*number_vertices+6*BezierQuantum+360;\n path_p=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes,\n sizeof(*path_p));\n path_q=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes,\n sizeof(*path_q));\n polygon_primitive=(PrimitiveInfo *) AcquireQuantumMemory((size_t)\n number_vertices+2UL,sizeof(*polygon_primitive));\n if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL) ||\n (polygon_primitive == (PrimitiveInfo *) NULL))\n return((PrimitiveInfo *) NULL);\n (void) CopyMagickMemory(polygon_primitive,primitive_info,(size_t)\n number_vertices*sizeof(*polygon_primitive));\n closed_path=\n (primitive_info[number_vertices-1].point.x == primitive_info[0].point.x) &&\n (primitive_info[number_vertices-1].point.y == primitive_info[0].point.y) ?\n MagickTrue : MagickFalse;\n if ((draw_info->linejoin == RoundJoin) ||\n ((draw_info->linejoin == MiterJoin) && (closed_path != MagickFalse)))\n {\n polygon_primitive[number_vertices]=primitive_info[1];\n number_vertices++;\n }\n polygon_primitive[number_vertices].primitive=UndefinedPrimitive;\n /*\n Compute the slope for the first line segment, p.\n */\n dx.p=0.0;\n dy.p=0.0;\n for (n=1; n < (ssize_t) number_vertices; n++)\n {\n dx.p=polygon_primitive[n].point.x-polygon_primitive[0].point.x;\n dy.p=polygon_primitive[n].point.y-polygon_primitive[0].point.y;\n if ((fabs(dx.p) >= MagickEpsilon) || (fabs(dy.p) >= MagickEpsilon))\n break;\n }\n if (n == (ssize_t) number_vertices)\n n=(ssize_t) number_vertices-1L;\n slope.p=DrawEpsilonReciprocal(dx.p)*dy.p;\n inverse_slope.p=(-1.0*DrawEpsilonReciprocal(slope.p));\n mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;\n miterlimit=(double) (draw_info->miterlimit*draw_info->miterlimit*\n mid*mid);\n if ((draw_info->linecap == SquareCap) && (closed_path == MagickFalse))\n TraceSquareLinecap(polygon_primitive,number_vertices,mid);\n offset.x=sqrt((double) (mid*mid/(inverse_slope.p*inverse_slope.p+1.0)));\n offset.y=(double) (offset.x*inverse_slope.p);\n if ((dy.p*offset.x-dx.p*offset.y) > 0.0)\n {\n box_p[0].x=polygon_primitive[0].point.x-offset.x;\n box_p[0].y=polygon_primitive[0].point.y-offset.x*inverse_slope.p;\n box_p[1].x=polygon_primitive[n].point.x-offset.x;\n box_p[1].y=polygon_primitive[n].point.y-offset.x*inverse_slope.p;\n box_q[0].x=polygon_primitive[0].point.x+offset.x;\n box_q[0].y=polygon_primitive[0].point.y+offset.x*inverse_slope.p;\n box_q[1].x=polygon_primitive[n].point.x+offset.x;\n box_q[1].y=polygon_primitive[n].point.y+offset.x*inverse_slope.p;\n }\n else\n {\n box_p[0].x=polygon_primitive[0].point.x+offset.x;\n box_p[0].y=polygon_primitive[0].point.y+offset.y;\n box_p[1].x=polygon_primitive[n].point.x+offset.x;\n box_p[1].y=polygon_primitive[n].point.y+offset.y;\n box_q[0].x=polygon_primitive[0].point.x-offset.x;\n box_q[0].y=polygon_primitive[0].point.y-offset.y;\n box_q[1].x=polygon_primitive[n].point.x-offset.x;\n box_q[1].y=polygon_primitive[n].point.y-offset.y;\n }\n /*\n Create strokes for the line join attribute: bevel, miter, round.\n */\n p=0;\n q=0;\n path_q[p++]=box_q[0];\n path_p[q++]=box_p[0];\n for (i=(ssize_t) n+1; i < (ssize_t) number_vertices; i++)\n {\n /*\n Compute the slope for this line segment, q.\n */\n dx.q=polygon_primitive[i].point.x-polygon_primitive[n].point.x;\n dy.q=polygon_primitive[i].point.y-polygon_primitive[n].point.y;\n dot_product=dx.q*dx.q+dy.q*dy.q;\n if (dot_product < 0.25)\n continue;\n slope.q=DrawEpsilonReciprocal(dx.q)*dy.q;\n inverse_slope.q=(-1.0*DrawEpsilonReciprocal(slope.q));\n offset.x=sqrt((double) (mid*mid/(inverse_slope.q*inverse_slope.q+1.0)));\n offset.y=(double) (offset.x*inverse_slope.q);\n dot_product=dy.q*offset.x-dx.q*offset.y;\n if (dot_product > 0.0)\n {\n box_p[2].x=polygon_primitive[n].point.x-offset.x;\n box_p[2].y=polygon_primitive[n].point.y-offset.y;\n box_p[3].x=polygon_primitive[i].point.x-offset.x;\n box_p[3].y=polygon_primitive[i].point.y-offset.y;\n box_q[2].x=polygon_primitive[n].point.x+offset.x;\n box_q[2].y=polygon_primitive[n].point.y+offset.y;\n box_q[3].x=polygon_primitive[i].point.x+offset.x;\n box_q[3].y=polygon_primitive[i].point.y+offset.y;\n }\n else\n {\n box_p[2].x=polygon_primitive[n].point.x+offset.x;\n box_p[2].y=polygon_primitive[n].point.y+offset.y;\n box_p[3].x=polygon_primitive[i].point.x+offset.x;\n box_p[3].y=polygon_primitive[i].point.y+offset.y;\n box_q[2].x=polygon_primitive[n].point.x-offset.x;\n box_q[2].y=polygon_primitive[n].point.y-offset.y;\n box_q[3].x=polygon_primitive[i].point.x-offset.x;\n box_q[3].y=polygon_primitive[i].point.y-offset.y;\n }\n if (fabs((double) (slope.p-slope.q)) < MagickEpsilon)\n {\n box_p[4]=box_p[1];\n box_q[4]=box_q[1];\n }\n else\n {\n box_p[4].x=(double) ((slope.p*box_p[0].x-box_p[0].y-slope.q*box_p[3].x+\n box_p[3].y)/(slope.p-slope.q));\n box_p[4].y=(double) (slope.p*(box_p[4].x-box_p[0].x)+box_p[0].y);\n box_q[4].x=(double) ((slope.p*box_q[0].x-box_q[0].y-slope.q*box_q[3].x+\n box_q[3].y)/(slope.p-slope.q));\n box_q[4].y=(double) (slope.p*(box_q[4].x-box_q[0].x)+box_q[0].y);\n }\n if (q >= (ssize_t) (max_strokes-6*BezierQuantum-360))\n {\n max_strokes+=6*BezierQuantum+360;\n path_p=(PointInfo *) ResizeQuantumMemory(path_p,(size_t) max_strokes,\n sizeof(*path_p));\n path_q=(PointInfo *) ResizeQuantumMemory(path_q,(size_t) max_strokes,\n sizeof(*path_q));\n if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL))\n {\n polygon_primitive=(PrimitiveInfo *)\n RelinquishMagickMemory(polygon_primitive);\n return((PrimitiveInfo *) NULL);\n }\n }\n dot_product=dx.q*dy.p-dx.p*dy.q;\n if (dot_product <= 0.0)\n switch (draw_info->linejoin)\n {\n case BevelJoin:\n {\n path_q[q++]=box_q[1];\n path_q[q++]=box_q[2];\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n path_p[p++]=box_p[4];\n else\n {\n path_p[p++]=box_p[1];\n path_p[p++]=box_p[2];\n }\n break;\n }\n case MiterJoin:\n {\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n {\n path_q[q++]=box_q[4];\n path_p[p++]=box_p[4];\n }\n else\n {\n path_q[q++]=box_q[1];\n path_q[q++]=box_q[2];\n path_p[p++]=box_p[1];\n path_p[p++]=box_p[2];\n }\n break;\n }\n case RoundJoin:\n {\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n path_p[p++]=box_p[4];\n else\n {\n path_p[p++]=box_p[1];\n path_p[p++]=box_p[2];\n }\n center=polygon_primitive[n].point;\n theta.p=atan2(box_q[1].y-center.y,box_q[1].x-center.x);\n theta.q=atan2(box_q[2].y-center.y,box_q[2].x-center.x);\n if (theta.q < theta.p)\n theta.q+=(double) (2.0*MagickPI);\n arc_segments=(size_t) ceil((double) ((theta.q-theta.p)/\n (2.0*sqrt((double) (1.0/mid)))));\n path_q[q].x=box_q[1].x;\n path_q[q].y=box_q[1].y;\n q++;\n for (j=1; j < (ssize_t) arc_segments; j++)\n {\n delta_theta=(double) (j*(theta.q-theta.p)/arc_segments);\n path_q[q].x=(double) (center.x+mid*cos(fmod((double)\n (theta.p+delta_theta),DegreesToRadians(360.0))));\n path_q[q].y=(double) (center.y+mid*sin(fmod((double)\n (theta.p+delta_theta),DegreesToRadians(360.0))));\n q++;\n }\n path_q[q++]=box_q[2];\n break;\n }\n default:\n break;\n }\n else\n switch (draw_info->linejoin)\n {\n case BevelJoin:\n {\n path_p[p++]=box_p[1];\n path_p[p++]=box_p[2];\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n path_q[q++]=box_q[4];\n else\n {\n path_q[q++]=box_q[1];\n path_q[q++]=box_q[2];\n }\n break;\n }\n case MiterJoin:\n {\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n {\n path_q[q++]=box_q[4];\n path_p[p++]=box_p[4];\n }\n else\n {\n path_q[q++]=box_q[1];\n path_q[q++]=box_q[2];\n path_p[p++]=box_p[1];\n path_p[p++]=box_p[2];\n }\n break;\n }\n case RoundJoin:\n {\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n path_q[q++]=box_q[4];\n else\n {\n path_q[q++]=box_q[1];\n path_q[q++]=box_q[2];\n }\n center=polygon_primitive[n].point;\n theta.p=atan2(box_p[1].y-center.y,box_p[1].x-center.x);\n theta.q=atan2(box_p[2].y-center.y,box_p[2].x-center.x);\n if (theta.p < theta.q)\n theta.p+=(double) (2.0*MagickPI);\n arc_segments=(size_t) ceil((double) ((theta.p-theta.q)/\n (2.0*sqrt((double) (1.0/mid)))));\n path_p[p++]=box_p[1];\n for (j=1; j < (ssize_t) arc_segments; j++)\n {\n delta_theta=(double) (j*(theta.q-theta.p)/arc_segments);\n path_p[p].x=(double) (center.x+mid*cos(fmod((double)\n (theta.p+delta_theta),DegreesToRadians(360.0))));\n path_p[p].y=(double) (center.y+mid*sin(fmod((double)\n (theta.p+delta_theta),DegreesToRadians(360.0))));\n p++;\n }\n path_p[p++]=box_p[2];\n break;\n }\n default:\n break;\n }\n slope.p=slope.q;\n inverse_slope.p=inverse_slope.q;\n box_p[0]=box_p[2];\n box_p[1]=box_p[3];\n box_q[0]=box_q[2];\n box_q[1]=box_q[3];\n dx.p=dx.q;\n dy.p=dy.q;\n n=i;\n }\n path_p[p++]=box_p[1];\n path_q[q++]=box_q[1];\n /*\n Trace stroked polygon.\n */\n stroke_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t)\n (p+q+2UL*closed_path+2UL),sizeof(*stroke_polygon));\n if (stroke_polygon != (PrimitiveInfo *) NULL)\n {\n for (i=0; i < (ssize_t) p; i++)\n {\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=path_p[i];\n }\n if (closed_path != MagickFalse)\n {\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=stroke_polygon[0].point;\n i++;\n }\n for ( ; i < (ssize_t) (p+q+closed_path); i++)\n {\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=path_q[p+q+closed_path-(i+1)];\n }\n if (closed_path != MagickFalse)\n {\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=stroke_polygon[p+closed_path].point;\n i++;\n }\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=stroke_polygon[0].point;\n i++;\n stroke_polygon[i].primitive=UndefinedPrimitive;\n stroke_polygon[0].coordinates=(size_t) (p+q+2*closed_path+1);\n }\n path_p=(PointInfo *) RelinquishMagickMemory(path_p);\n path_q=(PointInfo *) RelinquishMagickMemory(path_q);\n polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive);\n return(stroke_polygon);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-119'], 'message': 'Prevent buffer overflow in magick/draw.c'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: dissect_spoolss_keybuffer(tvbuff_t *tvb, int offset, packet_info *pinfo,\n\t\t\t proto_tree *tree, dcerpc_info *di, guint8 *drep)\n{\n\tguint32 size;\n\tint end_offset;\n\n\tif (di->conformant_run)\n\t\treturn offset;\n\n\t/* Dissect size and data */\n\n\toffset = dissect_ndr_uint32(tvb, offset, pinfo, tree, di, drep,\n\t\t\t\t hf_keybuffer_size, &size);\n\n\tend_offset = offset + (size*2);\n\tif (end_offset < offset) {\n\t\t/*\n\t\t * Overflow - make the end offset one past the end of\n\t\t * the packet data, so we throw an exception (as the\n\t\t * size is almost certainly too big).\n\t\t */\n\t\tend_offset = tvb_reported_length_remaining(tvb, offset) + 1;\n\t}\n\n\twhile (offset < end_offset)\n\t\toffset = dissect_spoolss_uint16uni(\n\t\t\ttvb, offset, pinfo, tree, drep, NULL, hf_keybuffer);\n\n\treturn offset;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'SPOOLSS: Try to avoid an infinite loop.\n\nUse tvb_reported_length_remaining in dissect_spoolss_uint16uni. Make\nsure our offset always increments in dissect_spoolss_keybuffer.\n\nChange-Id: I7017c9685bb2fa27161d80a03b8fca4ef630e793\nReviewed-on: https://code.wireshark.org/review/14687\nReviewed-by: Gerald Combs \nPetri-Dish: Gerald Combs \nTested-by: Petri Dish Buildbot \nReviewed-by: Michael Mann '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: parse_cosine_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,\n char *line, int *err, gchar **err_info)\n{\n\tunion wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;\n\tint\tnum_items_scanned;\n\tint\tyy, mm, dd, hr, min, sec, csec;\n\tguint\tpkt_len;\n\tint\tpro, off, pri, rm, error;\n\tguint\tcode1, code2;\n\tchar\tif_name[COSINE_MAX_IF_NAME_LEN] = \"\", direction[6] = \"\";\n\tstruct\ttm tm;\n\tguint8 *pd;\n\tint\ti, hex_lines, n, caplen = 0;\n\n\tif (sscanf(line, \"%4d-%2d-%2d,%2d:%2d:%2d.%9d:\",\n\t\t &yy, &mm, &dd, &hr, &min, &sec, &csec) == 7) {\n\t\t/* appears to be output to a control blade */\n\t\tnum_items_scanned = sscanf(line,\n\t\t \"%4d-%2d-%2d,%2d:%2d:%2d.%9d: %5s (%127[A-Za-z0-9/:]), Length:%9u, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]\",\n\t\t\t&yy, &mm, &dd, &hr, &min, &sec, &csec,\n\t\t\t\t direction, if_name, &pkt_len,\n\t\t\t\t &pro, &off, &pri, &rm, &error,\n\t\t\t\t &code1, &code2);\n\n\t\tif (num_items_scanned != 17) {\n\t\t\t*err = WTAP_ERR_BAD_FILE;\n\t\t\t*err_info = g_strdup(\"cosine: purported control blade line doesn't have code values\");\n\t\t\treturn FALSE;\n\t\t}\n\t} else {\n\t\t/* appears to be output to PE */\n\t\tnum_items_scanned = sscanf(line,\n\t\t \"%5s (%127[A-Za-z0-9/:]), Length:%9u, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]\",\n\t\t\t\t direction, if_name, &pkt_len,\n\t\t\t\t &pro, &off, &pri, &rm, &error,\n\t\t\t\t &code1, &code2);\n\n\t\tif (num_items_scanned != 10) {\n\t\t\t*err = WTAP_ERR_BAD_FILE;\n\t\t\t*err_info = g_strdup(\"cosine: header line is neither control blade nor PE output\");\n\t\t\treturn FALSE;\n\t\t}\n\t\tyy = mm = dd = hr = min = sec = csec = 0;\n\t}\n\tif (pkt_len > WTAP_MAX_PACKET_SIZE) {\n\t\t/*\n\t\t * Probably a corrupt capture file; don't blow up trying\n\t\t * to allocate space for an immensely-large packet.\n\t\t */\n\t\t*err = WTAP_ERR_BAD_FILE;\n\t\t*err_info = g_strdup_printf(\"cosine: File has %u-byte packet, bigger than maximum of %u\",\n\t\t pkt_len, WTAP_MAX_PACKET_SIZE);\n\t\treturn FALSE;\n\t}\n\n\tphdr->rec_type = REC_TYPE_PACKET;\n\tphdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;\n\ttm.tm_year = yy - 1900;\n\ttm.tm_mon = mm - 1;\n\ttm.tm_mday = dd;\n\ttm.tm_hour = hr;\n\ttm.tm_min = min;\n\ttm.tm_sec = sec;\n\ttm.tm_isdst = -1;\n\tphdr->ts.secs = mktime(&tm);\n\tphdr->ts.nsecs = csec * 10000000;\n\tphdr->len = pkt_len;\n\n\t/* XXX need to handle other encapsulations like Cisco HDLC,\n\t Frame Relay and ATM */\n\tif (strncmp(if_name, \"TEST:\", 5) == 0) {\n\t\tpseudo_header->cosine.encap = COSINE_ENCAP_TEST;\n\t} else if (strncmp(if_name, \"PPoATM:\", 7) == 0) {\n\t\tpseudo_header->cosine.encap = COSINE_ENCAP_PPoATM;\n\t} else if (strncmp(if_name, \"PPoFR:\", 6) == 0) {\n\t\tpseudo_header->cosine.encap = COSINE_ENCAP_PPoFR;\n\t} else if (strncmp(if_name, \"ATM:\", 4) == 0) {\n\t\tpseudo_header->cosine.encap = COSINE_ENCAP_ATM;\n\t} else if (strncmp(if_name, \"FR:\", 3) == 0) {\n\t\tpseudo_header->cosine.encap = COSINE_ENCAP_FR;\n\t} else if (strncmp(if_name, \"HDLC:\", 5) == 0) {\n\t\tpseudo_header->cosine.encap = COSINE_ENCAP_HDLC;\n\t} else if (strncmp(if_name, \"PPP:\", 4) == 0) {\n\t\tpseudo_header->cosine.encap = COSINE_ENCAP_PPP;\n\t} else if (strncmp(if_name, \"ETH:\", 4) == 0) {\n\t\tpseudo_header->cosine.encap = COSINE_ENCAP_ETH;\n\t} else {\n\t\tpseudo_header->cosine.encap = COSINE_ENCAP_UNKNOWN;\n\t}\n\tif (strncmp(direction, \"l2-tx\", 5) == 0) {\n\t\tpseudo_header->cosine.direction = COSINE_DIR_TX;\n\t} else if (strncmp(direction, \"l2-rx\", 5) == 0) {\n\t\tpseudo_header->cosine.direction = COSINE_DIR_RX;\n\t}\n\tg_strlcpy(pseudo_header->cosine.if_name, if_name,\n\t\tCOSINE_MAX_IF_NAME_LEN);\n\tpseudo_header->cosine.pro = pro;\n\tpseudo_header->cosine.off = off;\n\tpseudo_header->cosine.pri = pri;\n\tpseudo_header->cosine.rm = rm;\n\tpseudo_header->cosine.err = error;\n\n\t/* Make sure we have enough room for the packet */\n\tws_buffer_assure_space(buf, pkt_len);\n\tpd = ws_buffer_start_ptr(buf);\n\n\t/* Calculate the number of hex dump lines, each\n\t * containing 16 bytes of data */\n\thex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);\n\n\tfor (i = 0; i < hex_lines; i++) {\n\t\tif (file_gets(line, COSINE_LINE_LENGTH, fh) == NULL) {\n\t\t\t*err = file_error(fh, err_info);\n\t\t\tif (*err == 0) {\n\t\t\t\t*err = WTAP_ERR_SHORT_READ;\n\t\t\t}\n\t\t\treturn FALSE;\n\t\t}\n\t\tif (empty_line(line)) {\n\t\t\tbreak;\n\t\t}\n\t\tif ((n = parse_single_hex_dump_line(line, pd, i*16)) == -1) {\n\t\t\t*err = WTAP_ERR_BAD_FILE;\n\t\t\t*err_info = g_strdup(\"cosine: hex dump line doesn't have 16 numbers\");\n\t\t\treturn FALSE;\n\t\t}\n\t\tcaplen += n;\n\t}\n\tphdr->caplen = caplen;\n\treturn TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Don't treat the packet length as unsigned.\n\nThe scanf family of functions are as annoyingly bad at handling unsigned\nnumbers as strtoul() is - both of them are perfectly willing to accept a\nvalue beginning with a negative sign as an unsigned value. When using\nstrtoul(), you can compensate for this by explicitly checking for a '-'\nas the first character of the string, but you can't do that with\nsscanf().\n\nSo revert to having pkt_len be signed, and scanning it with %d, but\ncheck for a negative value and fail if we see a negative value.\n\nBug: 12395\nChange-Id: I43b458a73b0934e9a5c2c89d34eac5a8f21a7455\nReviewed-on: https://code.wireshark.org/review/15223\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_ppi(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)\n{\n proto_tree *ppi_tree = NULL, *ppi_flags_tree = NULL, *seg_tree = NULL, *ampdu_tree = NULL;\n proto_tree *agg_tree = NULL;\n proto_item *ti = NULL;\n tvbuff_t *next_tvb;\n int offset = 0;\n guint version, flags;\n gint tot_len, data_len;\n guint data_type;\n guint32 dlt;\n guint32 n_ext_flags = 0;\n guint32 ampdu_id = 0;\n fragment_head *fd_head = NULL;\n fragment_item *ft_fdh = NULL;\n gint mpdu_count = 0;\n gchar *mpdu_str;\n gboolean first_mpdu = TRUE;\n guint last_frame = 0;\n gint len_remain, /*pad_len = 0,*/ ampdu_len = 0;\n struct ieee_802_11_phdr phdr;\n\n col_set_str(pinfo->cinfo, COL_PROTOCOL, \"PPI\");\n col_clear(pinfo->cinfo, COL_INFO);\n\n version = tvb_get_guint8(tvb, offset);\n flags = tvb_get_guint8(tvb, offset + 1);\n\n tot_len = tvb_get_letohs(tvb, offset+2);\n dlt = tvb_get_letohl(tvb, offset+4);\n\n col_add_fstr(pinfo->cinfo, COL_INFO, \"PPI version %u, %u bytes\",\n version, tot_len);\n\n /* Dissect the packet */\n if (tree) {\n ti = proto_tree_add_protocol_format(tree, proto_ppi,\n tvb, 0, tot_len, \"PPI version %u, %u bytes\", version, tot_len);\n ppi_tree = proto_item_add_subtree(ti, ett_ppi_pph);\n proto_tree_add_item(ppi_tree, hf_ppi_head_version,\n tvb, offset, 1, ENC_LITTLE_ENDIAN);\n\n ti = proto_tree_add_item(ppi_tree, hf_ppi_head_flags,\n tvb, offset + 1, 1, ENC_LITTLE_ENDIAN);\n ppi_flags_tree = proto_item_add_subtree(ti, ett_ppi_flags);\n proto_tree_add_item(ppi_flags_tree, hf_ppi_head_flag_alignment,\n tvb, offset + 1, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(ppi_flags_tree, hf_ppi_head_flag_reserved,\n tvb, offset + 1, 1, ENC_LITTLE_ENDIAN);\n\n proto_tree_add_item(ppi_tree, hf_ppi_head_len,\n tvb, offset + 2, 2, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(ppi_tree, hf_ppi_head_dlt,\n tvb, offset + 4, 4, ENC_LITTLE_ENDIAN);\n }\n\n tot_len -= PPI_V0_HEADER_LEN;\n offset += 8;\n\n /* We don't have any 802.11 metadata yet. */\n memset(&phdr, 0, sizeof(phdr));\n phdr.fcs_len = -1;\n phdr.decrypted = FALSE;\n phdr.datapad = FALSE;\n phdr.phy = PHDR_802_11_PHY_UNKNOWN;\n phdr.presence_flags = 0;\n\n while (tot_len > 0) {\n data_type = tvb_get_letohs(tvb, offset);\n data_len = tvb_get_letohs(tvb, offset + 2) + 4;\n tot_len -= data_len;\n\n switch (data_type) {\n\n case PPI_80211_COMMON:\n dissect_80211_common(tvb, pinfo, ppi_tree, offset, data_len, &phdr);\n break;\n\n case PPI_80211N_MAC:\n dissect_80211n_mac(tvb, pinfo, ppi_tree, offset, data_len,\n TRUE, &n_ext_flags, &du_id, &phdr);\n break;\n\n case PPI_80211N_MAC_PHY:\n dissect_80211n_mac_phy(tvb, pinfo, ppi_tree, offset,\n data_len, &n_ext_flags, &du_id, &phdr);\n break;\n\n case PPI_SPECTRUM_MAP:\n ADD_BASIC_TAG(hf_spectrum_map);\n break;\n\n case PPI_PROCESS_INFO:\n ADD_BASIC_TAG(hf_process_info);\n break;\n\n case PPI_CAPTURE_INFO:\n ADD_BASIC_TAG(hf_capture_info);\n break;\n\n case PPI_AGGREGATION_EXTENSION:\n dissect_aggregation_extension(tvb, pinfo, ppi_tree, offset, data_len);\n break;\n\n case PPI_8023_EXTENSION:\n dissect_8023_extension(tvb, pinfo, ppi_tree, offset, data_len);\n break;\n\n case PPI_GPS_INFO:\n if (ppi_gps_handle == NULL)\n {\n proto_tree_add_item(ppi_tree, hf_ppi_gps, tvb, offset, data_len, ENC_NA);\n }\n else /* we found a suitable dissector */\n {\n /* skip over the ppi_fieldheader, and pass it off to the dedicated GPS dissetor */\n next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1);\n call_dissector(ppi_gps_handle, next_tvb, pinfo, ppi_tree);\n }\n break;\n\n case PPI_VECTOR_INFO:\n if (ppi_vector_handle == NULL)\n {\n proto_tree_add_item(ppi_tree, hf_ppi_vector, tvb, offset, data_len, ENC_NA);\n }\n else /* we found a suitable dissector */\n {\n /* skip over the ppi_fieldheader, and pass it off to the dedicated VECTOR dissetor */\n next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1);\n call_dissector(ppi_vector_handle, next_tvb, pinfo, ppi_tree);\n }\n break;\n\n case PPI_SENSOR_INFO:\n if (ppi_sensor_handle == NULL)\n {\n proto_tree_add_item(ppi_tree, hf_ppi_harris, tvb, offset, data_len, ENC_NA);\n }\n else /* we found a suitable dissector */\n {\n /* skip over the ppi_fieldheader, and pass it off to the dedicated SENSOR dissetor */\n next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1);\n call_dissector(ppi_sensor_handle, next_tvb, pinfo, ppi_tree);\n }\n break;\n\n case PPI_ANTENNA_INFO:\n if (ppi_antenna_handle == NULL)\n {\n proto_tree_add_item(ppi_tree, hf_ppi_antenna, tvb, offset, data_len, ENC_NA);\n }\n else /* we found a suitable dissector */\n {\n /* skip over the ppi_fieldheader, and pass it off to the dedicated ANTENNA dissetor */\n next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1);\n call_dissector(ppi_antenna_handle, next_tvb, pinfo, ppi_tree);\n }\n break;\n\n case FNET_PRIVATE:\n if (ppi_fnet_handle == NULL)\n {\n proto_tree_add_item(ppi_tree, hf_ppi_fnet, tvb, offset, data_len, ENC_NA);\n }\n else /* we found a suitable dissector */\n {\n /* skip over the ppi_fieldheader, and pass it off to the dedicated FNET dissetor */\n next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1);\n call_dissector(ppi_fnet_handle, next_tvb, pinfo, ppi_tree);\n }\n break;\n\n default:\n proto_tree_add_item(ppi_tree, hf_ppi_reserved, tvb, offset, data_len, ENC_NA);\n }\n\n offset += data_len;\n if (IS_PPI_FLAG_ALIGN(flags)){\n offset += PADDING4(offset);\n }\n }\n\n if (ppi_ampdu_reassemble && DOT11N_IS_AGGREGATE(n_ext_flags)) {\n len_remain = tvb_captured_length_remaining(tvb, offset);\n#if 0 /* XXX: pad_len never actually used ?? */\n if (DOT11N_MORE_AGGREGATES(n_ext_flags)) {\n pad_len = PADDING4(len_remain);\n }\n#endif\n pinfo->fragmented = TRUE;\n\n /* Make sure we aren't going to go past AGGREGATE_MAX\n * and caclulate our full A-MPDU length */\n fd_head = fragment_get(&du_reassembly_table, pinfo, ampdu_id, NULL);\n while (fd_head) {\n ampdu_len += fd_head->len + PADDING4(fd_head->len) + 4;\n fd_head = fd_head->next;\n }\n if (ampdu_len > AGGREGATE_MAX) {\n if (tree) {\n proto_tree_add_expert_format(ppi_tree, pinfo, &ei_ppi_invalid_length, tvb, offset, -1, \"Aggregate length greater than maximum (%u)\", AGGREGATE_MAX);\n THROW(ReportedBoundsError);\n } else {\n return;\n }\n }\n\n /*\n * Note that we never actually reassemble our A-MPDUs. Doing\n * so would require prepending each MPDU with an A-MPDU delimiter\n * and appending it with padding, only to hand it off to some\n * routine which would un-do the work we just did. We're using\n * the reassembly code to track MPDU sizes and frame numbers.\n */\n /*??fd_head = */fragment_add_seq_next(&du_reassembly_table,\n tvb, offset, pinfo, ampdu_id, NULL, len_remain, TRUE);\n pinfo->fragmented = TRUE;\n\n /* Do reassembly? */\n fd_head = fragment_get(&du_reassembly_table, pinfo, ampdu_id, NULL);\n\n /* Show our fragments */\n if (fd_head && tree) {\n ft_fdh = fd_head;\n /* List our fragments */\n seg_tree = proto_tree_add_subtree_format(ppi_tree, tvb, offset, -1,\n ett_ampdu_segments, &ti, \"A-MPDU (%u bytes w/hdrs):\", ampdu_len);\n PROTO_ITEM_SET_GENERATED(ti);\n\n while (ft_fdh) {\n if (ft_fdh->tvb_data && ft_fdh->len) {\n last_frame = ft_fdh->frame;\n if (!first_mpdu)\n proto_item_append_text(ti, \",\");\n first_mpdu = FALSE;\n proto_item_append_text(ti, \" #%u(%u)\",\n ft_fdh->frame, ft_fdh->len);\n proto_tree_add_uint_format(seg_tree, hf_ampdu_segment,\n tvb, 0, 0, last_frame,\n \"Frame: %u (%u byte%s)\",\n last_frame,\n ft_fdh->len,\n plurality(ft_fdh->len, \"\", \"s\"));\n }\n ft_fdh = ft_fdh->next;\n }\n if (last_frame && last_frame != pinfo->fd->num)\n proto_tree_add_uint(seg_tree, hf_ampdu_reassembled_in,\n tvb, 0, 0, last_frame);\n }\n\n if (fd_head && !DOT11N_MORE_AGGREGATES(n_ext_flags)) {\n if (tree) {\n ti = proto_tree_add_protocol_format(tree,\n proto_get_id_by_filter_name(\"wlan_aggregate\"),\n tvb, 0, tot_len, \"IEEE 802.11 Aggregate MPDU\");\n agg_tree = proto_item_add_subtree(ti, ett_ampdu);\n }\n\n while (fd_head) {\n if (fd_head->tvb_data && fd_head->len) {\n mpdu_count++;\n mpdu_str = wmem_strdup_printf(wmem_packet_scope(), \"MPDU #%d\", mpdu_count);\n\n next_tvb = tvb_new_chain(tvb, fd_head->tvb_data);\n add_new_data_source(pinfo, next_tvb, mpdu_str);\n\n ampdu_tree = proto_tree_add_subtree(agg_tree, next_tvb, 0, -1, ett_ampdu_segment, NULL, mpdu_str);\n call_dissector_with_data(ieee80211_radio_handle, next_tvb, pinfo, ampdu_tree, &phdr);\n }\n fd_head = fd_head->next;\n }\n proto_tree_add_uint(seg_tree, hf_ampdu_count, tvb, 0, 0, mpdu_count);\n pinfo->fragmented=FALSE;\n } else {\n next_tvb = tvb_new_subset_remaining(tvb, offset);\n col_set_str(pinfo->cinfo, COL_PROTOCOL, \"IEEE 802.11n\");\n col_set_str(pinfo->cinfo, COL_INFO, \"Unreassembled A-MPDU data\");\n call_dissector(data_handle, next_tvb, pinfo, tree);\n }\n return;\n }\n\n next_tvb = tvb_new_subset_remaining(tvb, offset);\n /*\n * You can't just call an arbitrary subdissector based on a\n * LINKTYPE_ value, because they may expect a particular\n * pseudo-header to be passed to them.\n *\n * So we look for LINKTYPE_IEEE802_11, which is 105, and, if\n * that's what the LINKTYPE_ value is, pass it a pointer\n * to a struct ieee_802_11_phdr; otherwise, we pass it\n * a null pointer - if it actually matters, we need to\n * construct the appropriate pseudo-header and pass that.\n */\n if (dlt == 105) {\n /* LINKTYPE_IEEE802_11 */\n call_dissector_with_data(ieee80211_radio_handle, next_tvb, pinfo, tree, &phdr);\n } else {\n /* Everything else. This will pass a NULL data argument. */\n dissector_try_uint(wtap_encap_dissector_table,\n wtap_pcap_encap_to_wtap_encap(dlt), next_tvb, pinfo, 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 Image *ReadTGAImage(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n Image\n *image;\n\n MagickBooleanType\n status;\n\n PixelInfo\n pixel;\n\n Quantum\n index;\n\n register Quantum\n *q;\n\n register ssize_t\n i,\n x;\n\n size_t\n base,\n flag,\n offset,\n real,\n skip;\n\n ssize_t\n count,\n y;\n\n TGAInfo\n tga_info;\n\n unsigned char\n j,\n k,\n pixels[4],\n runlength;\n\n unsigned int\n alpha_bits;\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 TGA header information.\n */\n count=ReadBlob(image,1,&tga_info.id_length);\n tga_info.colormap_type=(unsigned char) ReadBlobByte(image);\n tga_info.image_type=(TGAImageType) ReadBlobByte(image);\n if ((count != 1) ||\n ((tga_info.image_type != TGAColormap) &&\n (tga_info.image_type != TGARGB) &&\n (tga_info.image_type != TGAMonochrome) &&\n (tga_info.image_type != TGARLEColormap) &&\n (tga_info.image_type != TGARLERGB) &&\n (tga_info.image_type != TGARLEMonochrome)) ||\n (((tga_info.image_type == TGAColormap) ||\n (tga_info.image_type == TGARLEColormap)) &&\n (tga_info.colormap_type == 0)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n tga_info.colormap_index=ReadBlobLSBShort(image);\n tga_info.colormap_length=ReadBlobLSBShort(image);\n tga_info.colormap_size=(unsigned char) ReadBlobByte(image);\n tga_info.x_origin=ReadBlobLSBShort(image);\n tga_info.y_origin=ReadBlobLSBShort(image);\n tga_info.width=(unsigned short) ReadBlobLSBShort(image);\n tga_info.height=(unsigned short) ReadBlobLSBShort(image);\n tga_info.bits_per_pixel=(unsigned char) ReadBlobByte(image);\n tga_info.attributes=(unsigned char) ReadBlobByte(image);\n if (EOFBlob(image) != MagickFalse)\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n if ((((tga_info.bits_per_pixel <= 1) || (tga_info.bits_per_pixel >= 17)) &&\n (tga_info.bits_per_pixel != 24) && (tga_info.bits_per_pixel != 32)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n /*\n Initialize image structure.\n */\n image->columns=tga_info.width;\n image->rows=tga_info.height;\n alpha_bits=(tga_info.attributes & 0x0FU);\n image->alpha_trait=(alpha_bits > 0) || (tga_info.bits_per_pixel == 32) ||\n (tga_info.colormap_size == 32) ? BlendPixelTrait : UndefinedPixelTrait;\n if ((tga_info.image_type != TGAColormap) &&\n (tga_info.image_type != TGARLEColormap))\n image->depth=(size_t) ((tga_info.bits_per_pixel <= 8) ? 8 :\n (tga_info.bits_per_pixel <= 16) ? 5 :\n (tga_info.bits_per_pixel == 24) ? 8 :\n (tga_info.bits_per_pixel == 32) ? 8 : 8);\n else\n image->depth=(size_t) ((tga_info.colormap_size <= 8) ? 8 :\n (tga_info.colormap_size <= 16) ? 5 :\n (tga_info.colormap_size == 24) ? 8 :\n (tga_info.colormap_size == 32) ? 8 : 8);\n if ((tga_info.image_type == TGAColormap) ||\n (tga_info.image_type == TGAMonochrome) ||\n (tga_info.image_type == TGARLEColormap) ||\n (tga_info.image_type == TGARLEMonochrome))\n image->storage_class=PseudoClass;\n image->compression=NoCompression;\n if ((tga_info.image_type == TGARLEColormap) ||\n (tga_info.image_type == TGARLEMonochrome) ||\n (tga_info.image_type == TGARLERGB))\n image->compression=RLECompression;\n if (image->storage_class == PseudoClass)\n {\n if (tga_info.colormap_type != 0)\n image->colors=tga_info.colormap_index+tga_info.colormap_length;\n else\n {\n size_t\n one;\n\n one=1;\n image->colors=one << tga_info.bits_per_pixel;\n if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n }\n if (tga_info.id_length != 0)\n {\n char\n *comment;\n\n size_t\n length;\n\n /*\n TGA image comment.\n */\n length=(size_t) tga_info.id_length;\n comment=(char *) NULL;\n if (~length >= (MagickPathExtent-1))\n comment=(char *) AcquireQuantumMemory(length+MagickPathExtent,\n sizeof(*comment));\n if (comment == (char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n count=ReadBlob(image,tga_info.id_length,(unsigned char *) comment);\n comment[tga_info.id_length]='\\0';\n (void) SetImageProperty(image,\"comment\",comment,exception);\n comment=DestroyString(comment);\n }\n if (image_info->ping != MagickFalse)\n {\n (void) CloseBlob(image);\n return(image);\n }\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n (void) ResetMagickMemory(&pixel,0,sizeof(pixel));\n pixel.alpha=(MagickRealType) OpaqueAlpha;\n if (tga_info.colormap_type != 0)\n {\n /*\n Read TGA raster colormap.\n */\n if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n for (i=0; i < (ssize_t) tga_info.colormap_index; i++)\n image->colormap[i]=pixel;\n for ( ; i < (ssize_t) image->colors; i++)\n {\n switch (tga_info.colormap_size)\n {\n case 8:\n default:\n {\n /*\n Gray scale.\n */\n pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n pixel.green=pixel.red;\n pixel.blue=pixel.red;\n break;\n }\n case 15:\n case 16:\n {\n QuantumAny\n range;\n\n /*\n 5 bits each of red green and blue.\n */\n j=(unsigned char) ReadBlobByte(image);\n k=(unsigned char) ReadBlobByte(image);\n range=GetQuantumRange(5UL);\n pixel.red=(MagickRealType) ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2,\n range);\n pixel.green=(MagickRealType) ScaleAnyToQuantum((1UL*(k & 0x03)\n << 3)+(1UL*(j & 0xe0) >> 5),range);\n pixel.blue=(MagickRealType) ScaleAnyToQuantum(1UL*(j & 0x1f),range);\n break;\n }\n case 24:\n {\n /*\n 8 bits each of blue, green and red.\n */\n pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n break;\n }\n case 32:\n {\n /*\n 8 bits each of blue, green, red, and alpha.\n */\n pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n pixel.alpha=(MagickRealType) ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n break;\n }\n }\n image->colormap[i]=pixel;\n }\n }\n /*\n Convert TGA pixels to pixel packets.\n */\n base=0;\n flag=0;\n skip=MagickFalse;\n real=0;\n index=0;\n runlength=0;\n offset=0;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n real=offset;\n if (((unsigned char) (tga_info.attributes & 0x20) >> 5) == 0)\n real=image->rows-real-1;\n q=QueueAuthenticPixels(image,0,(ssize_t) real,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if ((tga_info.image_type == TGARLEColormap) ||\n (tga_info.image_type == TGARLERGB) ||\n (tga_info.image_type == TGARLEMonochrome))\n {\n if (runlength != 0)\n {\n runlength--;\n skip=flag != 0;\n }\n else\n {\n count=ReadBlob(image,1,&runlength);\n if (count != 1)\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n flag=runlength & 0x80;\n if (flag != 0)\n runlength-=128;\n skip=MagickFalse;\n }\n }\n if (skip == MagickFalse)\n switch (tga_info.bits_per_pixel)\n {\n case 8:\n default:\n {\n /*\n Gray scale.\n */\n index=(Quantum) ReadBlobByte(image);\n if (tga_info.colormap_type != 0)\n pixel=image->colormap[(ssize_t) ConstrainColormapIndex(image,\n (ssize_t) index,exception)];\n else\n {\n pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)\n index);\n pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char)\n index);\n pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char)\n index);\n }\n break;\n }\n case 15:\n case 16:\n {\n QuantumAny\n range;\n\n /*\n 5 bits each of RGB.\n */\n if (ReadBlob(image,2,pixels) != 2)\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n j=pixels[0];\n k=pixels[1];\n range=GetQuantumRange(5UL);\n pixel.red=(MagickRealType) ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2,\n range);\n pixel.green=(MagickRealType) ScaleAnyToQuantum((1UL*\n (k & 0x03) << 3)+(1UL*(j & 0xe0) >> 5),range);\n pixel.blue=(MagickRealType) ScaleAnyToQuantum(1UL*(j & 0x1f),range);\n if (image->alpha_trait != UndefinedPixelTrait)\n pixel.alpha=(MagickRealType) ((k & 0x80) == 0 ? (Quantum)\n TransparentAlpha : (Quantum) OpaqueAlpha);\n if (image->storage_class == PseudoClass)\n index=(Quantum) ConstrainColormapIndex(image,((ssize_t) (k << 8))+\n j,exception);\n break;\n }\n case 24:\n {\n /*\n BGR pixels.\n */\n if (ReadBlob(image,3,pixels) != 3)\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n pixel.blue=(MagickRealType) ScaleCharToQuantum(pixels[0]);\n pixel.green=(MagickRealType) ScaleCharToQuantum(pixels[1]);\n pixel.red=(MagickRealType) ScaleCharToQuantum(pixels[2]);\n break;\n }\n case 32:\n {\n /*\n BGRA pixels.\n */\n if (ReadBlob(image,4,pixels) != 4)\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n pixel.blue=(MagickRealType) ScaleCharToQuantum(pixels[0]);\n pixel.green=(MagickRealType) ScaleCharToQuantum(pixels[1]);\n pixel.red=(MagickRealType) ScaleCharToQuantum(pixels[2]);\n pixel.alpha=(MagickRealType) ScaleCharToQuantum(pixels[3]);\n break;\n }\n }\n if (status == MagickFalse)\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n if (image->storage_class == PseudoClass)\n SetPixelIndex(image,index,q);\n SetPixelRed(image,ClampToQuantum(pixel.red),q);\n SetPixelGreen(image,ClampToQuantum(pixel.green),q);\n SetPixelBlue(image,ClampToQuantum(pixel.blue),q);\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);\n q+=GetPixelChannels(image);\n }\n /*\n if (((unsigned char) (tga_info.attributes & 0xc0) >> 6) == 4)\n offset+=4;\n else\n */\n if (((unsigned char) (tga_info.attributes & 0xc0) >> 6) == 2)\n offset+=2;\n else\n offset++;\n if (offset >= image->rows)\n {\n base++;\n offset=base;\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 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-415'], 'message': 'https://bugs.launchpad.net/ubuntu/+source/imagemagick/+bug/1490362'" }, { "text": "[INST] Given the following code containing errors, provide Common 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_codes(struct archive_read *a)\n{\n int i, j, val, n, r;\n unsigned char bitlengths[MAX_SYMBOLS], zerocount, ppmd_flags;\n unsigned int maxorder;\n struct huffman_code precode;\n struct rar *rar = (struct rar *)(a->format->data);\n struct rar_br *br = &(rar->br);\n\n free_codes(a);\n\n /* Skip to the next byte */\n rar_br_consume_unalined_bits(br);\n\n /* PPMd block flag */\n if (!rar_br_read_ahead(a, br, 1))\n goto truncated_data;\n if ((rar->is_ppmd_block = rar_br_bits(br, 1)) != 0)\n {\n rar_br_consume(br, 1);\n if (!rar_br_read_ahead(a, br, 7))\n goto truncated_data;\n ppmd_flags = rar_br_bits(br, 7);\n rar_br_consume(br, 7);\n\n /* Memory is allocated in MB */\n if (ppmd_flags & 0x20)\n {\n if (!rar_br_read_ahead(a, br, 8))\n goto truncated_data;\n rar->dictionary_size = (rar_br_bits(br, 8) + 1) << 20;\n rar_br_consume(br, 8);\n }\n\n if (ppmd_flags & 0x40)\n {\n if (!rar_br_read_ahead(a, br, 8))\n goto truncated_data;\n rar->ppmd_escape = rar->ppmd7_context.InitEsc = rar_br_bits(br, 8);\n rar_br_consume(br, 8);\n }\n else\n rar->ppmd_escape = 2;\n\n if (ppmd_flags & 0x20)\n {\n maxorder = (ppmd_flags & 0x1F) + 1;\n if(maxorder > 16)\n maxorder = 16 + (maxorder - 16) * 3;\n\n if (maxorder == 1)\n {\n archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n \"Truncated RAR file data\");\n return (ARCHIVE_FATAL);\n }\n\n /* Make sure ppmd7_contest is freed before Ppmd7_Construct\n * because reading a broken file cause this abnormal sequence. */\n __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc);\n\n rar->bytein.a = a;\n rar->bytein.Read = &ppmd_read;\n __archive_ppmd7_functions.PpmdRAR_RangeDec_CreateVTable(&rar->range_dec);\n rar->range_dec.Stream = &rar->bytein;\n __archive_ppmd7_functions.Ppmd7_Construct(&rar->ppmd7_context);\n\n if (!__archive_ppmd7_functions.Ppmd7_Alloc(&rar->ppmd7_context,\n rar->dictionary_size, &g_szalloc))\n {\n archive_set_error(&a->archive, ENOMEM,\n \"Out of memory\");\n return (ARCHIVE_FATAL);\n }\n if (!__archive_ppmd7_functions.PpmdRAR_RangeDec_Init(&rar->range_dec))\n {\n archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n \"Unable to initialize PPMd range decoder\");\n return (ARCHIVE_FATAL);\n }\n __archive_ppmd7_functions.Ppmd7_Init(&rar->ppmd7_context, maxorder);\n rar->ppmd_valid = 1;\n }\n else\n {\n if (!rar->ppmd_valid) {\n archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n \"Invalid PPMd sequence\");\n return (ARCHIVE_FATAL);\n }\n if (!__archive_ppmd7_functions.PpmdRAR_RangeDec_Init(&rar->range_dec))\n {\n archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n \"Unable to initialize PPMd range decoder\");\n return (ARCHIVE_FATAL);\n }\n }\n }\n else\n {\n rar_br_consume(br, 1);\n\n /* Keep existing table flag */\n if (!rar_br_read_ahead(a, br, 1))\n goto truncated_data;\n if (!rar_br_bits(br, 1))\n memset(rar->lengthtable, 0, sizeof(rar->lengthtable));\n rar_br_consume(br, 1);\n\n memset(&bitlengths, 0, sizeof(bitlengths));\n for (i = 0; i < MAX_SYMBOLS;)\n {\n if (!rar_br_read_ahead(a, br, 4))\n goto truncated_data;\n bitlengths[i++] = rar_br_bits(br, 4);\n rar_br_consume(br, 4);\n if (bitlengths[i-1] == 0xF)\n {\n if (!rar_br_read_ahead(a, br, 4))\n goto truncated_data;\n zerocount = rar_br_bits(br, 4);\n rar_br_consume(br, 4);\n if (zerocount)\n {\n i--;\n for (j = 0; j < zerocount + 2 && i < MAX_SYMBOLS; j++)\n bitlengths[i++] = 0;\n }\n }\n }\n\n memset(&precode, 0, sizeof(precode));\n r = create_code(a, &precode, bitlengths, MAX_SYMBOLS, MAX_SYMBOL_LENGTH);\n if (r != ARCHIVE_OK) {\n free(precode.tree);\n free(precode.table);\n return (r);\n }\n\n for (i = 0; i < HUFFMAN_TABLE_SIZE;)\n {\n if ((val = read_next_symbol(a, &precode)) < 0) {\n free(precode.tree);\n free(precode.table);\n return (ARCHIVE_FATAL);\n }\n if (val < 16)\n {\n rar->lengthtable[i] = (rar->lengthtable[i] + val) & 0xF;\n i++;\n }\n else if (val < 18)\n {\n if (i == 0)\n {\n free(precode.tree);\n free(precode.table);\n archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n \"Internal error extracting RAR file.\");\n return (ARCHIVE_FATAL);\n }\n\n if(val == 16) {\n if (!rar_br_read_ahead(a, br, 3)) {\n free(precode.tree);\n free(precode.table);\n goto truncated_data;\n }\n n = rar_br_bits(br, 3) + 3;\n rar_br_consume(br, 3);\n } else {\n if (!rar_br_read_ahead(a, br, 7)) {\n free(precode.tree);\n free(precode.table);\n goto truncated_data;\n }\n n = rar_br_bits(br, 7) + 11;\n rar_br_consume(br, 7);\n }\n\n for (j = 0; j < n && i < HUFFMAN_TABLE_SIZE; j++)\n {\n rar->lengthtable[i] = rar->lengthtable[i-1];\n i++;\n }\n }\n else\n {\n if(val == 18) {\n if (!rar_br_read_ahead(a, br, 3)) {\n free(precode.tree);\n free(precode.table);\n goto truncated_data;\n }\n n = rar_br_bits(br, 3) + 3;\n rar_br_consume(br, 3);\n } else {\n if (!rar_br_read_ahead(a, br, 7)) {\n free(precode.tree);\n free(precode.table);\n goto truncated_data;\n }\n n = rar_br_bits(br, 7) + 11;\n rar_br_consume(br, 7);\n }\n\n for(j = 0; j < n && i < HUFFMAN_TABLE_SIZE; j++)\n rar->lengthtable[i++] = 0;\n }\n }\n free(precode.tree);\n free(precode.table);\n\n r = create_code(a, &rar->maincode, &rar->lengthtable[0], MAINCODE_SIZE,\n MAX_SYMBOL_LENGTH);\n if (r != ARCHIVE_OK)\n return (r);\n r = create_code(a, &rar->offsetcode, &rar->lengthtable[MAINCODE_SIZE],\n OFFSETCODE_SIZE, MAX_SYMBOL_LENGTH);\n if (r != ARCHIVE_OK)\n return (r);\n r = create_code(a, &rar->lowoffsetcode,\n &rar->lengthtable[MAINCODE_SIZE + OFFSETCODE_SIZE],\n LOWOFFSETCODE_SIZE, MAX_SYMBOL_LENGTH);\n if (r != ARCHIVE_OK)\n return (r);\n r = create_code(a, &rar->lengthcode,\n &rar->lengthtable[MAINCODE_SIZE + OFFSETCODE_SIZE +\n LOWOFFSETCODE_SIZE], LENGTHCODE_SIZE, MAX_SYMBOL_LENGTH);\n if (r != ARCHIVE_OK)\n return (r);\n }\n\n if (!rar->dictionary_size || !rar->lzss.window)\n {\n /* Seems as though dictionary sizes are not used. Even so, minimize\n * memory usage as much as possible.\n */\n void *new_window;\n unsigned int new_size;\n\n if (rar->unp_size >= DICTIONARY_MAX_SIZE)\n new_size = DICTIONARY_MAX_SIZE;\n else\n new_size = rar_fls((unsigned int)rar->unp_size) << 1;\n new_window = realloc(rar->lzss.window, new_size);\n if (new_window == NULL) {\n archive_set_error(&a->archive, ENOMEM,\n \"Unable to allocate memory for uncompressed data.\");\n return (ARCHIVE_FATAL);\n }\n rar->lzss.window = (unsigned char *)new_window;\n rar->dictionary_size = new_size;\n memset(rar->lzss.window, 0, rar->dictionary_size);\n rar->lzss.mask = rar->dictionary_size - 1;\n }\n\n rar->start_new_table = 0;\n return (ARCHIVE_OK);\ntruncated_data:\n archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n \"Truncated RAR file data\");\n rar->valid = 0;\n return (ARCHIVE_FATAL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Issue 719: Fix for TALOS-CAN-154\n\nA RAR file with an invalid zero dictionary size was not being\nrejected, leading to a zero-sized allocation for the dictionary\nstorage which was then overwritten during the dictionary initialization.\n\nThanks to the Open Source and Threat Intelligence project at Cisco for\nreporting 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: check_compat_entry_size_and_hooks(struct compat_ip6t_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_match *ematch;\n\tstruct xt_entry_target *t;\n\tstruct xt_target *target;\n\tunsigned int entry_offset;\n\tunsigned int j;\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_ip6t_entry) != 0 ||\n\t (unsigned char *)e + sizeof(struct compat_ip6t_entry) >= limit ||\n\t (unsigned char *)e + e->next_offset > 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_ip6t_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\tif (!ip6_checkentry(&e->ipv6))\n\t\treturn -EINVAL;\n\n\tret = xt_compat_check_entry_offsets(e,\n\t\t\t\t\t e->target_offset, e->next_offset);\n\tif (ret)\n\t\treturn ret;\n\n\toff = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry);\n\tentry_offset = (void *)e - (void *)base;\n\tj = 0;\n\txt_ematch_foreach(ematch, e) {\n\t\tret = compat_find_calc_match(ematch, name, &e->ipv6, &off);\n\t\tif (ret != 0)\n\t\t\tgoto release_matches;\n\t\t++j;\n\t}\n\n\tt = compat_ip6t_get_target(e);\n\ttarget = xt_request_find_target(NFPROTO_IPV6, 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 release_matches;\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(AF_INET6, entry_offset, off);\n\tif (ret)\n\t\tgoto out;\n\n\t/* Check hooks & underflows */\n\tfor (h = 0; h < NF_INET_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\nout:\n\tmodule_put(t->u.kernel.target->me);\nrelease_matches:\n\txt_ematch_foreach(ematch, e) {\n\t\tif (j-- == 0)\n\t\t\tbreak;\n\t\tmodule_put(ematch->u.kernel.match->me);\n\t}\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'netfilter: x_tables: check for bogus target offset\n\nWe're currently asserting that targetoff + targetsize <= nextoff.\n\nExtend it to also check that targetoff is >= sizeof(xt_entry).\nSince this is generic code, add an argument pointing to the start of the\nmatch/target, we can then derive the base structure size from the delta.\n\nWe also need the e->elems pointer in a followup change to validate matches.\n\nSigned-off-by: Florian Westphal \nSigned-off-by: Pablo Neira Ayuso '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static MagickBooleanType GetEXIFProperty(const Image *image,\n const char *property,ExceptionInfo *exception)\n{\n#define MaxDirectoryStack 16\n#define EXIF_DELIMITER \"\\n\"\n#define EXIF_NUM_FORMATS 12\n#define EXIF_FMT_BYTE 1\n#define EXIF_FMT_STRING 2\n#define EXIF_FMT_USHORT 3\n#define EXIF_FMT_ULONG 4\n#define EXIF_FMT_URATIONAL 5\n#define EXIF_FMT_SBYTE 6\n#define EXIF_FMT_UNDEFINED 7\n#define EXIF_FMT_SSHORT 8\n#define EXIF_FMT_SLONG 9\n#define EXIF_FMT_SRATIONAL 10\n#define EXIF_FMT_SINGLE 11\n#define EXIF_FMT_DOUBLE 12\n#define TAG_EXIF_OFFSET 0x8769\n#define TAG_GPS_OFFSET 0x8825\n#define TAG_INTEROP_OFFSET 0xa005\n\n#define EXIFMultipleValues(size,format,arg) \\\n{ \\\n ssize_t \\\n component; \\\n \\\n size_t \\\n length; \\\n \\\n unsigned char \\\n *p1; \\\n \\\n length=0; \\\n p1=p; \\\n for (component=0; component < components; component++) \\\n { \\\n length+=FormatLocaleString(buffer+length,MagickPathExtent-length, \\\n format\", \",arg); \\\n if (length >= (MagickPathExtent-1)) \\\n length=MagickPathExtent-1; \\\n p1+=size; \\\n } \\\n if (length > 1) \\\n buffer[length-2]='\\0'; \\\n value=AcquireString(buffer); \\\n}\n\n#define EXIFMultipleFractions(size,format,arg1,arg2) \\\n{ \\\n ssize_t \\\n component; \\\n \\\n size_t \\\n length; \\\n \\\n unsigned char \\\n *p1; \\\n \\\n length=0; \\\n p1=p; \\\n for (component=0; component < components; component++) \\\n { \\\n length+=FormatLocaleString(buffer+length,MagickPathExtent-length, \\\n format\", \",(arg1),(arg2)); \\\n if (length >= (MagickPathExtent-1)) \\\n length=MagickPathExtent-1; \\\n p1+=size; \\\n } \\\n if (length > 1) \\\n buffer[length-2]='\\0'; \\\n value=AcquireString(buffer); \\\n}\n\n typedef struct _DirectoryInfo\n {\n const unsigned char\n *directory;\n\n size_t\n entry;\n\n ssize_t\n offset;\n } DirectoryInfo;\n\n typedef struct _TagInfo\n {\n size_t\n tag;\n\n const char\n *description;\n } TagInfo;\n\n static TagInfo\n EXIFTag[] =\n {\n { 0x001, \"exif:InteroperabilityIndex\" },\n { 0x002, \"exif:InteroperabilityVersion\" },\n { 0x100, \"exif:ImageWidth\" },\n { 0x101, \"exif:ImageLength\" },\n { 0x102, \"exif:BitsPerSample\" },\n { 0x103, \"exif:Compression\" },\n { 0x106, \"exif:PhotometricInterpretation\" },\n { 0x10a, \"exif:FillOrder\" },\n { 0x10d, \"exif:DocumentName\" },\n { 0x10e, \"exif:ImageDescription\" },\n { 0x10f, \"exif:Make\" },\n { 0x110, \"exif:Model\" },\n { 0x111, \"exif:StripOffsets\" },\n { 0x112, \"exif:Orientation\" },\n { 0x115, \"exif:SamplesPerPixel\" },\n { 0x116, \"exif:RowsPerStrip\" },\n { 0x117, \"exif:StripByteCounts\" },\n { 0x11a, \"exif:XResolution\" },\n { 0x11b, \"exif:YResolution\" },\n { 0x11c, \"exif:PlanarConfiguration\" },\n { 0x11d, \"exif:PageName\" },\n { 0x11e, \"exif:XPosition\" },\n { 0x11f, \"exif:YPosition\" },\n { 0x118, \"exif:MinSampleValue\" },\n { 0x119, \"exif:MaxSampleValue\" },\n { 0x120, \"exif:FreeOffsets\" },\n { 0x121, \"exif:FreeByteCounts\" },\n { 0x122, \"exif:GrayResponseUnit\" },\n { 0x123, \"exif:GrayResponseCurve\" },\n { 0x124, \"exif:T4Options\" },\n { 0x125, \"exif:T6Options\" },\n { 0x128, \"exif:ResolutionUnit\" },\n { 0x12d, \"exif:TransferFunction\" },\n { 0x131, \"exif:Software\" },\n { 0x132, \"exif:DateTime\" },\n { 0x13b, \"exif:Artist\" },\n { 0x13e, \"exif:WhitePoint\" },\n { 0x13f, \"exif:PrimaryChromaticities\" },\n { 0x140, \"exif:ColorMap\" },\n { 0x141, \"exif:HalfToneHints\" },\n { 0x142, \"exif:TileWidth\" },\n { 0x143, \"exif:TileLength\" },\n { 0x144, \"exif:TileOffsets\" },\n { 0x145, \"exif:TileByteCounts\" },\n { 0x14a, \"exif:SubIFD\" },\n { 0x14c, \"exif:InkSet\" },\n { 0x14d, \"exif:InkNames\" },\n { 0x14e, \"exif:NumberOfInks\" },\n { 0x150, \"exif:DotRange\" },\n { 0x151, \"exif:TargetPrinter\" },\n { 0x152, \"exif:ExtraSample\" },\n { 0x153, \"exif:SampleFormat\" },\n { 0x154, \"exif:SMinSampleValue\" },\n { 0x155, \"exif:SMaxSampleValue\" },\n { 0x156, \"exif:TransferRange\" },\n { 0x157, \"exif:ClipPath\" },\n { 0x158, \"exif:XClipPathUnits\" },\n { 0x159, \"exif:YClipPathUnits\" },\n { 0x15a, \"exif:Indexed\" },\n { 0x15b, \"exif:JPEGTables\" },\n { 0x15f, \"exif:OPIProxy\" },\n { 0x200, \"exif:JPEGProc\" },\n { 0x201, \"exif:JPEGInterchangeFormat\" },\n { 0x202, \"exif:JPEGInterchangeFormatLength\" },\n { 0x203, \"exif:JPEGRestartInterval\" },\n { 0x205, \"exif:JPEGLosslessPredictors\" },\n { 0x206, \"exif:JPEGPointTransforms\" },\n { 0x207, \"exif:JPEGQTables\" },\n { 0x208, \"exif:JPEGDCTables\" },\n { 0x209, \"exif:JPEGACTables\" },\n { 0x211, \"exif:YCbCrCoefficients\" },\n { 0x212, \"exif:YCbCrSubSampling\" },\n { 0x213, \"exif:YCbCrPositioning\" },\n { 0x214, \"exif:ReferenceBlackWhite\" },\n { 0x2bc, \"exif:ExtensibleMetadataPlatform\" },\n { 0x301, \"exif:Gamma\" },\n { 0x302, \"exif:ICCProfileDescriptor\" },\n { 0x303, \"exif:SRGBRenderingIntent\" },\n { 0x320, \"exif:ImageTitle\" },\n { 0x5001, \"exif:ResolutionXUnit\" },\n { 0x5002, \"exif:ResolutionYUnit\" },\n { 0x5003, \"exif:ResolutionXLengthUnit\" },\n { 0x5004, \"exif:ResolutionYLengthUnit\" },\n { 0x5005, \"exif:PrintFlags\" },\n { 0x5006, \"exif:PrintFlagsVersion\" },\n { 0x5007, \"exif:PrintFlagsCrop\" },\n { 0x5008, \"exif:PrintFlagsBleedWidth\" },\n { 0x5009, \"exif:PrintFlagsBleedWidthScale\" },\n { 0x500A, \"exif:HalftoneLPI\" },\n { 0x500B, \"exif:HalftoneLPIUnit\" },\n { 0x500C, \"exif:HalftoneDegree\" },\n { 0x500D, \"exif:HalftoneShape\" },\n { 0x500E, \"exif:HalftoneMisc\" },\n { 0x500F, \"exif:HalftoneScreen\" },\n { 0x5010, \"exif:JPEGQuality\" },\n { 0x5011, \"exif:GridSize\" },\n { 0x5012, \"exif:ThumbnailFormat\" },\n { 0x5013, \"exif:ThumbnailWidth\" },\n { 0x5014, \"exif:ThumbnailHeight\" },\n { 0x5015, \"exif:ThumbnailColorDepth\" },\n { 0x5016, \"exif:ThumbnailPlanes\" },\n { 0x5017, \"exif:ThumbnailRawBytes\" },\n { 0x5018, \"exif:ThumbnailSize\" },\n { 0x5019, \"exif:ThumbnailCompressedSize\" },\n { 0x501a, \"exif:ColorTransferFunction\" },\n { 0x501b, \"exif:ThumbnailData\" },\n { 0x5020, \"exif:ThumbnailImageWidth\" },\n { 0x5021, \"exif:ThumbnailImageHeight\" },\n { 0x5022, \"exif:ThumbnailBitsPerSample\" },\n { 0x5023, \"exif:ThumbnailCompression\" },\n { 0x5024, \"exif:ThumbnailPhotometricInterp\" },\n { 0x5025, \"exif:ThumbnailImageDescription\" },\n { 0x5026, \"exif:ThumbnailEquipMake\" },\n { 0x5027, \"exif:ThumbnailEquipModel\" },\n { 0x5028, \"exif:ThumbnailStripOffsets\" },\n { 0x5029, \"exif:ThumbnailOrientation\" },\n { 0x502a, \"exif:ThumbnailSamplesPerPixel\" },\n { 0x502b, \"exif:ThumbnailRowsPerStrip\" },\n { 0x502c, \"exif:ThumbnailStripBytesCount\" },\n { 0x502d, \"exif:ThumbnailResolutionX\" },\n { 0x502e, \"exif:ThumbnailResolutionY\" },\n { 0x502f, \"exif:ThumbnailPlanarConfig\" },\n { 0x5030, \"exif:ThumbnailResolutionUnit\" },\n { 0x5031, \"exif:ThumbnailTransferFunction\" },\n { 0x5032, \"exif:ThumbnailSoftwareUsed\" },\n { 0x5033, \"exif:ThumbnailDateTime\" },\n { 0x5034, \"exif:ThumbnailArtist\" },\n { 0x5035, \"exif:ThumbnailWhitePoint\" },\n { 0x5036, \"exif:ThumbnailPrimaryChromaticities\" },\n { 0x5037, \"exif:ThumbnailYCbCrCoefficients\" },\n { 0x5038, \"exif:ThumbnailYCbCrSubsampling\" },\n { 0x5039, \"exif:ThumbnailYCbCrPositioning\" },\n { 0x503A, \"exif:ThumbnailRefBlackWhite\" },\n { 0x503B, \"exif:ThumbnailCopyRight\" },\n { 0x5090, \"exif:LuminanceTable\" },\n { 0x5091, \"exif:ChrominanceTable\" },\n { 0x5100, \"exif:FrameDelay\" },\n { 0x5101, \"exif:LoopCount\" },\n { 0x5110, \"exif:PixelUnit\" },\n { 0x5111, \"exif:PixelPerUnitX\" },\n { 0x5112, \"exif:PixelPerUnitY\" },\n { 0x5113, \"exif:PaletteHistogram\" },\n { 0x1000, \"exif:RelatedImageFileFormat\" },\n { 0x1001, \"exif:RelatedImageLength\" },\n { 0x1002, \"exif:RelatedImageWidth\" },\n { 0x800d, \"exif:ImageID\" },\n { 0x80e3, \"exif:Matteing\" },\n { 0x80e4, \"exif:DataType\" },\n { 0x80e5, \"exif:ImageDepth\" },\n { 0x80e6, \"exif:TileDepth\" },\n { 0x828d, \"exif:CFARepeatPatternDim\" },\n { 0x828e, \"exif:CFAPattern2\" },\n { 0x828f, \"exif:BatteryLevel\" },\n { 0x8298, \"exif:Copyright\" },\n { 0x829a, \"exif:ExposureTime\" },\n { 0x829d, \"exif:FNumber\" },\n { 0x83bb, \"exif:IPTC/NAA\" },\n { 0x84e3, \"exif:IT8RasterPadding\" },\n { 0x84e5, \"exif:IT8ColorTable\" },\n { 0x8649, \"exif:ImageResourceInformation\" },\n { 0x8769, \"exif:ExifOffset\" },\n { 0x8773, \"exif:InterColorProfile\" },\n { 0x8822, \"exif:ExposureProgram\" },\n { 0x8824, \"exif:SpectralSensitivity\" },\n { 0x8825, \"exif:GPSInfo\" },\n { 0x8827, \"exif:ISOSpeedRatings\" },\n { 0x8828, \"exif:OECF\" },\n { 0x8829, \"exif:Interlace\" },\n { 0x882a, \"exif:TimeZoneOffset\" },\n { 0x882b, \"exif:SelfTimerMode\" },\n { 0x9000, \"exif:ExifVersion\" },\n { 0x9003, \"exif:DateTimeOriginal\" },\n { 0x9004, \"exif:DateTimeDigitized\" },\n { 0x9101, \"exif:ComponentsConfiguration\" },\n { 0x9102, \"exif:CompressedBitsPerPixel\" },\n { 0x9201, \"exif:ShutterSpeedValue\" },\n { 0x9202, \"exif:ApertureValue\" },\n { 0x9203, \"exif:BrightnessValue\" },\n { 0x9204, \"exif:ExposureBiasValue\" },\n { 0x9205, \"exif:MaxApertureValue\" },\n { 0x9206, \"exif:SubjectDistance\" },\n { 0x9207, \"exif:MeteringMode\" },\n { 0x9208, \"exif:LightSource\" },\n { 0x9209, \"exif:Flash\" },\n { 0x920a, \"exif:FocalLength\" },\n { 0x920b, \"exif:FlashEnergy\" },\n { 0x920c, \"exif:SpatialFrequencyResponse\" },\n { 0x920d, \"exif:Noise\" },\n { 0x9211, \"exif:ImageNumber\" },\n { 0x9212, \"exif:SecurityClassification\" },\n { 0x9213, \"exif:ImageHistory\" },\n { 0x9214, \"exif:SubjectArea\" },\n { 0x9215, \"exif:ExposureIndex\" },\n { 0x9216, \"exif:TIFF-EPStandardID\" },\n { 0x927c, \"exif:MakerNote\" },\n { 0x9C9b, \"exif:WinXP-Title\" },\n { 0x9C9c, \"exif:WinXP-Comments\" },\n { 0x9C9d, \"exif:WinXP-Author\" },\n { 0x9C9e, \"exif:WinXP-Keywords\" },\n { 0x9C9f, \"exif:WinXP-Subject\" },\n { 0x9286, \"exif:UserComment\" },\n { 0x9290, \"exif:SubSecTime\" },\n { 0x9291, \"exif:SubSecTimeOriginal\" },\n { 0x9292, \"exif:SubSecTimeDigitized\" },\n { 0xa000, \"exif:FlashPixVersion\" },\n { 0xa001, \"exif:ColorSpace\" },\n { 0xa002, \"exif:ExifImageWidth\" },\n { 0xa003, \"exif:ExifImageLength\" },\n { 0xa004, \"exif:RelatedSoundFile\" },\n { 0xa005, \"exif:InteroperabilityOffset\" },\n { 0xa20b, \"exif:FlashEnergy\" },\n { 0xa20c, \"exif:SpatialFrequencyResponse\" },\n { 0xa20d, \"exif:Noise\" },\n { 0xa20e, \"exif:FocalPlaneXResolution\" },\n { 0xa20f, \"exif:FocalPlaneYResolution\" },\n { 0xa210, \"exif:FocalPlaneResolutionUnit\" },\n { 0xa214, \"exif:SubjectLocation\" },\n { 0xa215, \"exif:ExposureIndex\" },\n { 0xa216, \"exif:TIFF/EPStandardID\" },\n { 0xa217, \"exif:SensingMethod\" },\n { 0xa300, \"exif:FileSource\" },\n { 0xa301, \"exif:SceneType\" },\n { 0xa302, \"exif:CFAPattern\" },\n { 0xa401, \"exif:CustomRendered\" },\n { 0xa402, \"exif:ExposureMode\" },\n { 0xa403, \"exif:WhiteBalance\" },\n { 0xa404, \"exif:DigitalZoomRatio\" },\n { 0xa405, \"exif:FocalLengthIn35mmFilm\" },\n { 0xa406, \"exif:SceneCaptureType\" },\n { 0xa407, \"exif:GainControl\" },\n { 0xa408, \"exif:Contrast\" },\n { 0xa409, \"exif:Saturation\" },\n { 0xa40a, \"exif:Sharpness\" },\n { 0xa40b, \"exif:DeviceSettingDescription\" },\n { 0xa40c, \"exif:SubjectDistanceRange\" },\n { 0xa420, \"exif:ImageUniqueID\" },\n { 0xc4a5, \"exif:PrintImageMatching\" },\n { 0xa500, \"exif:Gamma\" },\n { 0xc640, \"exif:CR2Slice\" },\n { 0x10000, \"exif:GPSVersionID\" },\n { 0x10001, \"exif:GPSLatitudeRef\" },\n { 0x10002, \"exif:GPSLatitude\" },\n { 0x10003, \"exif:GPSLongitudeRef\" },\n { 0x10004, \"exif:GPSLongitude\" },\n { 0x10005, \"exif:GPSAltitudeRef\" },\n { 0x10006, \"exif:GPSAltitude\" },\n { 0x10007, \"exif:GPSTimeStamp\" },\n { 0x10008, \"exif:GPSSatellites\" },\n { 0x10009, \"exif:GPSStatus\" },\n { 0x1000a, \"exif:GPSMeasureMode\" },\n { 0x1000b, \"exif:GPSDop\" },\n { 0x1000c, \"exif:GPSSpeedRef\" },\n { 0x1000d, \"exif:GPSSpeed\" },\n { 0x1000e, \"exif:GPSTrackRef\" },\n { 0x1000f, \"exif:GPSTrack\" },\n { 0x10010, \"exif:GPSImgDirectionRef\" },\n { 0x10011, \"exif:GPSImgDirection\" },\n { 0x10012, \"exif:GPSMapDatum\" },\n { 0x10013, \"exif:GPSDestLatitudeRef\" },\n { 0x10014, \"exif:GPSDestLatitude\" },\n { 0x10015, \"exif:GPSDestLongitudeRef\" },\n { 0x10016, \"exif:GPSDestLongitude\" },\n { 0x10017, \"exif:GPSDestBearingRef\" },\n { 0x10018, \"exif:GPSDestBearing\" },\n { 0x10019, \"exif:GPSDestDistanceRef\" },\n { 0x1001a, \"exif:GPSDestDistance\" },\n { 0x1001b, \"exif:GPSProcessingMethod\" },\n { 0x1001c, \"exif:GPSAreaInformation\" },\n { 0x1001d, \"exif:GPSDateStamp\" },\n { 0x1001e, \"exif:GPSDifferential\" },\n { 0x00000, (const char *) NULL }\n };\n\n const StringInfo\n *profile;\n\n const unsigned char\n *directory,\n *exif;\n\n DirectoryInfo\n directory_stack[MaxDirectoryStack];\n\n EndianType\n endian;\n\n MagickBooleanType\n status;\n\n register ssize_t\n i;\n\n size_t\n entry,\n length,\n number_entries,\n tag,\n tag_value;\n\n SplayTreeInfo\n *exif_resources;\n\n ssize_t\n all,\n id,\n level,\n offset,\n tag_offset;\n\n static int\n tag_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8};\n\n /*\n If EXIF data exists, then try to parse the request for a tag.\n */\n profile=GetImageProfile(image,\"exif\");\n if (profile == (const StringInfo *) NULL)\n return(MagickFalse);\n if ((property == (const char *) NULL) || (*property == '\\0'))\n return(MagickFalse);\n while (isspace((int) ((unsigned char) *property)) != 0)\n property++;\n if (strlen(property) <= 5)\n return(MagickFalse);\n all=0;\n tag=(~0UL);\n switch (*(property+5))\n {\n case '*':\n {\n /*\n Caller has asked for all the tags in the EXIF data.\n */\n tag=0;\n all=1; /* return the data in description=value format */\n break;\n }\n case '!':\n {\n tag=0;\n all=2; /* return the data in tagid=value format */\n break;\n }\n case '#':\n case '@':\n {\n int\n c;\n\n size_t\n n;\n\n /*\n Check for a hex based tag specification first.\n */\n tag=(*(property+5) == '@') ? 1UL : 0UL;\n property+=6;\n n=strlen(property);\n if (n != 4)\n return(MagickFalse);\n /*\n Parse tag specification as a hex number.\n */\n n/=4;\n do\n {\n for (i=(ssize_t) n-1L; i >= 0; i--)\n {\n c=(*property++);\n tag<<=4;\n if ((c >= '0') && (c <= '9'))\n tag|=(c-'0');\n else\n if ((c >= 'A') && (c <= 'F'))\n tag|=(c-('A'-10));\n else\n if ((c >= 'a') && (c <= 'f'))\n tag|=(c-('a'-10));\n else\n return(MagickFalse);\n }\n } while (*property != '\\0');\n break;\n }\n default:\n {\n /*\n Try to match the text with a tag name instead.\n */\n for (i=0; ; i++)\n {\n if (EXIFTag[i].tag == 0)\n break;\n if (LocaleCompare(EXIFTag[i].description,property) == 0)\n {\n tag=(size_t) EXIFTag[i].tag;\n break;\n }\n }\n break;\n }\n }\n if (tag == (~0UL))\n return(MagickFalse);\n length=GetStringInfoLength(profile);\n exif=GetStringInfoDatum(profile);\n while (length != 0)\n {\n if (ReadPropertyByte(&exif,&length) != 0x45)\n continue;\n if (ReadPropertyByte(&exif,&length) != 0x78)\n continue;\n if (ReadPropertyByte(&exif,&length) != 0x69)\n continue;\n if (ReadPropertyByte(&exif,&length) != 0x66)\n continue;\n if (ReadPropertyByte(&exif,&length) != 0x00)\n continue;\n if (ReadPropertyByte(&exif,&length) != 0x00)\n continue;\n break;\n }\n if (length < 16)\n return(MagickFalse);\n id=(ssize_t) ReadPropertySignedShort(LSBEndian,exif);\n endian=LSBEndian;\n if (id == 0x4949)\n endian=LSBEndian;\n else\n if (id == 0x4D4D)\n endian=MSBEndian;\n else\n return(MagickFalse);\n if (ReadPropertyUnsignedShort(endian,exif+2) != 0x002a)\n return(MagickFalse);\n /*\n This the offset to the first IFD.\n */\n offset=(ssize_t) ReadPropertySignedLong(endian,exif+4);\n if ((offset < 0) || (size_t) offset >= length)\n return(MagickFalse);\n /*\n Set the pointer to the first IFD and follow it were it leads.\n */\n status=MagickFalse;\n directory=exif+offset;\n level=0;\n entry=0;\n tag_offset=0;\n exif_resources=NewSplayTree((int (*)(const void *,const void *)) NULL,\n (void *(*)(void *)) NULL,(void *(*)(void *)) NULL);\n do\n {\n /*\n If there is anything on the stack then pop it off.\n */\n if (level > 0)\n {\n level--;\n directory=directory_stack[level].directory;\n entry=directory_stack[level].entry;\n tag_offset=directory_stack[level].offset;\n }\n if ((directory < exif) || (directory > (exif+length-2)))\n break;\n /*\n Determine how many entries there are in the current IFD.\n */\n number_entries=(size_t) ReadPropertyUnsignedShort(endian,directory);\n for ( ; entry < number_entries; entry++)\n {\n register unsigned char\n *p,\n *q;\n\n size_t\n format;\n\n ssize_t\n number_bytes,\n components;\n\n q=(unsigned char *) (directory+(12*entry)+2);\n if (GetValueFromSplayTree(exif_resources,q) == q)\n break;\n (void) AddValueToSplayTree(exif_resources,q,q);\n tag_value=(size_t) ReadPropertyUnsignedShort(endian,q)+tag_offset;\n format=(size_t) ReadPropertyUnsignedShort(endian,q+2);\n if (format >= (sizeof(tag_bytes)/sizeof(*tag_bytes)))\n break;\n components=(ssize_t) ReadPropertySignedLong(endian,q+4);\n number_bytes=(size_t) components*tag_bytes[format];\n if (number_bytes < components)\n break; /* prevent overflow */\n if (number_bytes <= 4)\n p=q+8;\n else\n {\n ssize_t\n offset;\n\n /*\n The directory entry contains an offset.\n */\n offset=(ssize_t) ReadPropertySignedLong(endian,q+8);\n if ((offset < 0) || (size_t) offset >= length)\n continue;\n if ((ssize_t) (offset+number_bytes) < offset)\n continue; /* prevent overflow */\n if ((size_t) (offset+number_bytes) > length)\n continue;\n p=(unsigned char *) (exif+offset);\n }\n if ((all != 0) || (tag == (size_t) tag_value))\n {\n char\n buffer[MagickPathExtent],\n *value;\n\n value=(char *) NULL;\n *buffer='\\0';\n switch (format)\n {\n case EXIF_FMT_BYTE:\n case EXIF_FMT_UNDEFINED:\n {\n EXIFMultipleValues(1,\"%.20g\",(double) (*(unsigned char *) p1));\n break;\n }\n case EXIF_FMT_SBYTE:\n {\n EXIFMultipleValues(1,\"%.20g\",(double) (*(signed char *) p1));\n break;\n }\n case EXIF_FMT_SSHORT:\n {\n EXIFMultipleValues(2,\"%hd\",ReadPropertySignedShort(endian,p1));\n break;\n }\n case EXIF_FMT_USHORT:\n {\n EXIFMultipleValues(2,\"%hu\",ReadPropertyUnsignedShort(endian,p1));\n break;\n }\n case EXIF_FMT_ULONG:\n {\n EXIFMultipleValues(4,\"%.20g\",(double)\n ReadPropertyUnsignedLong(endian,p1));\n break;\n }\n case EXIF_FMT_SLONG:\n {\n EXIFMultipleValues(4,\"%.20g\",(double)\n ReadPropertySignedLong(endian,p1));\n break;\n }\n case EXIF_FMT_URATIONAL:\n {\n EXIFMultipleFractions(8,\"%.20g/%.20g\",(double)\n ReadPropertyUnsignedLong(endian,p1),(double)\n ReadPropertyUnsignedLong(endian,p1+4));\n break;\n }\n case EXIF_FMT_SRATIONAL:\n {\n EXIFMultipleFractions(8,\"%.20g/%.20g\",(double)\n ReadPropertySignedLong(endian,p1),(double)\n ReadPropertySignedLong(endian,p1+4));\n break;\n }\n case EXIF_FMT_SINGLE:\n {\n EXIFMultipleValues(4,\"%f\",(double) *(float *) p1);\n break;\n }\n case EXIF_FMT_DOUBLE:\n {\n EXIFMultipleValues(8,\"%f\",*(double *) p1);\n break;\n }\n default:\n case EXIF_FMT_STRING:\n {\n value=(char *) NULL;\n if (~((size_t) number_bytes) >= 1)\n value=(char *) AcquireQuantumMemory((size_t) number_bytes+1UL,\n sizeof(*value));\n if (value != (char *) NULL)\n {\n register ssize_t\n i;\n\n for (i=0; i < (ssize_t) number_bytes; i++)\n {\n value[i]='.';\n if ((isprint((int) p[i]) != 0) || (p[i] == '\\0'))\n value[i]=(char) p[i];\n }\n value[i]='\\0';\n }\n break;\n }\n }\n if (value != (char *) NULL)\n {\n char\n *key;\n\n register const char\n *p;\n\n key=AcquireString(property);\n switch (all)\n {\n case 1:\n {\n const char\n *description;\n\n register ssize_t\n i;\n\n description=\"unknown\";\n for (i=0; ; i++)\n {\n if (EXIFTag[i].tag == 0)\n break;\n if (EXIFTag[i].tag == tag_value)\n {\n description=EXIFTag[i].description;\n break;\n }\n }\n (void) FormatLocaleString(key,MagickPathExtent,\"%s\",\n description);\n if (level == 2)\n (void) SubstituteString(&key,\"exif:\",\"exif:thumbnail:\");\n break;\n }\n case 2:\n {\n if (tag_value < 0x10000)\n (void) FormatLocaleString(key,MagickPathExtent,\"#%04lx\",\n (unsigned long) tag_value);\n else\n if (tag_value < 0x20000)\n (void) FormatLocaleString(key,MagickPathExtent,\"@%04lx\",\n (unsigned long) (tag_value & 0xffff));\n else\n (void) FormatLocaleString(key,MagickPathExtent,\"unknown\");\n break;\n }\n default:\n {\n if (level == 2)\n (void) SubstituteString(&key,\"exif:\",\"exif:thumbnail:\");\n }\n }\n p=(const char *) NULL;\n if (image->properties != (void *) NULL)\n p=(const char *) GetValueFromSplayTree((SplayTreeInfo *)\n image->properties,key);\n if (p == (const char *) NULL)\n (void) SetImageProperty((Image *) image,key,value,exception);\n value=DestroyString(value);\n key=DestroyString(key);\n status=MagickTrue;\n }\n }\n if ((tag_value == TAG_EXIF_OFFSET) ||\n (tag_value == TAG_INTEROP_OFFSET) || (tag_value == TAG_GPS_OFFSET))\n {\n ssize_t\n offset;\n\n offset=(ssize_t) ReadPropertySignedLong(endian,p);\n if (((size_t) offset < length) && (level < (MaxDirectoryStack-2)))\n {\n ssize_t\n tag_offset1;\n\n tag_offset1=(ssize_t) ((tag_value == TAG_GPS_OFFSET) ? 0x10000 :\n 0);\n directory_stack[level].directory=directory;\n entry++;\n directory_stack[level].entry=entry;\n directory_stack[level].offset=tag_offset;\n level++;\n directory_stack[level].directory=exif+offset;\n directory_stack[level].offset=tag_offset1;\n directory_stack[level].entry=0;\n level++;\n if ((directory+2+(12*number_entries)) > (exif+length))\n break;\n offset=(ssize_t) ReadPropertySignedLong(endian,directory+2+(12*\n number_entries));\n if ((offset != 0) && ((size_t) offset < length) &&\n (level < (MaxDirectoryStack-2)))\n {\n directory_stack[level].directory=exif+offset;\n directory_stack[level].entry=0;\n directory_stack[level].offset=tag_offset1;\n level++;\n }\n }\n break;\n }\n }\n } while (level > 0);\n exif_resources=DestroySplayTree(exif_resources);\n return(status);\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 long vop_ioctl(struct file *f, unsigned int cmd, unsigned long arg)\n{\n\tstruct vop_vdev *vdev = f->private_data;\n\tstruct vop_info *vi = vdev->vi;\n\tvoid __user *argp = (void __user *)arg;\n\tint ret;\n\n\tswitch (cmd) {\n\tcase MIC_VIRTIO_ADD_DEVICE:\n\t{\n\t\tstruct mic_device_desc dd, *dd_config;\n\n\t\tif (copy_from_user(&dd, argp, sizeof(dd)))\n\t\t\treturn -EFAULT;\n\n\t\tif (mic_aligned_desc_size(&dd) > MIC_MAX_DESC_BLK_SIZE ||\n\t\t dd.num_vq > MIC_MAX_VRINGS)\n\t\t\treturn -EINVAL;\n\n\t\tdd_config = kzalloc(mic_desc_size(&dd), GFP_KERNEL);\n\t\tif (!dd_config)\n\t\t\treturn -ENOMEM;\n\t\tif (copy_from_user(dd_config, argp, mic_desc_size(&dd))) {\n\t\t\tret = -EFAULT;\n\t\t\tgoto free_ret;\n\t\t}\n\t\tmutex_lock(&vdev->vdev_mutex);\n\t\tmutex_lock(&vi->vop_mutex);\n\t\tret = vop_virtio_add_device(vdev, dd_config);\n\t\tif (ret)\n\t\t\tgoto unlock_ret;\n\t\tlist_add_tail(&vdev->list, &vi->vdev_list);\nunlock_ret:\n\t\tmutex_unlock(&vi->vop_mutex);\n\t\tmutex_unlock(&vdev->vdev_mutex);\nfree_ret:\n\t\tkfree(dd_config);\n\t\treturn ret;\n\t}\n\tcase MIC_VIRTIO_COPY_DESC:\n\t{\n\t\tstruct mic_copy_desc copy;\n\n\t\tmutex_lock(&vdev->vdev_mutex);\n\t\tret = vop_vdev_inited(vdev);\n\t\tif (ret)\n\t\t\tgoto _unlock_ret;\n\n\t\tif (copy_from_user(©, argp, sizeof(copy))) {\n\t\t\tret = -EFAULT;\n\t\t\tgoto _unlock_ret;\n\t\t}\n\n\t\tret = vop_virtio_copy_desc(vdev, ©);\n\t\tif (ret < 0)\n\t\t\tgoto _unlock_ret;\n\t\tif (copy_to_user(\n\t\t\t&((struct mic_copy_desc __user *)argp)->out_len,\n\t\t\t©.out_len, sizeof(copy.out_len)))\n\t\t\tret = -EFAULT;\n_unlock_ret:\n\t\tmutex_unlock(&vdev->vdev_mutex);\n\t\treturn ret;\n\t}\n\tcase MIC_VIRTIO_CONFIG_CHANGE:\n\t{\n\t\tvoid *buf;\n\n\t\tmutex_lock(&vdev->vdev_mutex);\n\t\tret = vop_vdev_inited(vdev);\n\t\tif (ret)\n\t\t\tgoto __unlock_ret;\n\t\tbuf = kzalloc(vdev->dd->config_len, GFP_KERNEL);\n\t\tif (!buf) {\n\t\t\tret = -ENOMEM;\n\t\t\tgoto __unlock_ret;\n\t\t}\n\t\tif (copy_from_user(buf, argp, vdev->dd->config_len)) {\n\t\t\tret = -EFAULT;\n\t\t\tgoto done;\n\t\t}\n\t\tret = vop_virtio_config_change(vdev, buf);\ndone:\n\t\tkfree(buf);\n__unlock_ret:\n\t\tmutex_unlock(&vdev->vdev_mutex);\n\t\treturn ret;\n\t}\n\tdefault:\n\t\treturn -ENOIOCTLCMD;\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': 'misc: mic: Fix for double fetch security bug in VOP driver\n\nThe MIC VOP driver does two successive reads from user space to read a\nvariable length data structure. Kernel memory corruption can result if\nthe data structure changes between the two reads. This patch disallows\nthe chance of this happening.\n\nBugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=116651\nReported by: Pengfei Wang \nReviewed-by: Sudeep Dutt \nSigned-off-by: Ashutosh Dixit \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 gdImageCopyResized (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH)\n{\n\tint c;\n\tint x, y;\n\tint tox, toy;\n\tint ydest;\n\tint i;\n\tint colorMap[gdMaxColors];\n\t/* Stretch vectors */\n\tint *stx, *sty;\n\t\n\tif (overflow2(sizeof(int), srcW)) {\n\t\treturn;\n\t}\n\tif (overflow2(sizeof(int), srcH)) {\n\t\treturn;\n\t}\n\n\tstx = (int *) gdMalloc (sizeof (int) * srcW);\n\tsty = (int *) gdMalloc (sizeof (int) * srcH);\n\n\t/* Fixed by Mao Morimoto 2.0.16 */\n\tfor (i = 0; (i < srcW); i++) {\n\t\tstx[i] = dstW * (i+1) / srcW - dstW * i / srcW ;\n\t}\n\tfor (i = 0; (i < srcH); i++) {\n\t\tsty[i] = dstH * (i+1) / srcH - dstH * i / srcH ;\n\t}\n\tfor (i = 0; (i < gdMaxColors); i++) {\n\t\tcolorMap[i] = (-1);\n\t}\n\ttoy = dstY;\n\tfor (y = srcY; (y < (srcY + srcH)); y++) {\n\t\tfor (ydest = 0; (ydest < sty[y - srcY]); ydest++) {\n\t\t\ttox = dstX;\n\t\t\tfor (x = srcX; (x < (srcX + srcW)); x++) {\n\t\t\t\tint nc = 0;\n\t\t\t\tint mapTo;\n\t\t\t\tif (!stx[x - srcX]) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (dst->trueColor) {\n\t\t\t\t\t/* 2.0.9: Thorben Kundinger: Maybe the source image is not a truecolor image */\n\t\t\t\t\tif (!src->trueColor) {\n\t\t\t\t\t \tint tmp = gdImageGetPixel (src, x, y);\n\t\t \t\t\t\tmapTo = gdImageGetTrueColorPixel (src, x, y);\n\t\t\t\t\t \tif (gdImageGetTransparent (src) == tmp) {\n\t\t\t\t\t\t\t/* 2.0.21, TK: not tox++ */\n\t\t\t\t\t\t\ttox += stx[x - srcX];\n\t\t\t\t\t \t\tcontinue;\n\t\t\t\t\t \t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t/* TK: old code follows */\n\t\t\t\t\t \tmapTo = gdImageGetTrueColorPixel (src, x, y);\n\t\t\t\t\t\t/* Added 7/24/95: support transparent copies */\n\t\t\t\t\t\tif (gdImageGetTransparent (src) == mapTo) {\n\t\t\t\t\t\t\t/* 2.0.21, TK: not tox++ */\n\t\t\t\t\t\t\ttox += stx[x - srcX];\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} else {\n\t\t\t\t\tc = gdImageGetPixel (src, x, y);\n\t\t\t\t\t/* Added 7/24/95: support transparent copies */\n\t\t\t\t\tif (gdImageGetTransparent (src) == c) {\n\t\t\t\t\t tox += stx[x - srcX];\n\t\t\t\t\t continue;\n\t\t\t\t\t}\n\t\t\t\t\tif (src->trueColor) {\n\t\t\t\t\t /* Remap to the palette available in the destination image. This is slow and works badly. */\n\t\t\t\t\t mapTo = gdImageColorResolveAlpha(dst, gdTrueColorGetRed(c),\n\t\t\t\t\t \t\t\t\t\t gdTrueColorGetGreen(c),\n\t\t\t\t\t \t\t\t\t\t gdTrueColorGetBlue(c),\n\t\t\t\t\t \t\t\t\t\t gdTrueColorGetAlpha (c));\n\t\t\t\t\t} else {\n\t\t\t\t\t\t/* Have we established a mapping for this color? */\n\t\t\t\t\t\tif (colorMap[c] == (-1)) {\n\t\t\t\t\t\t\t/* If it's the same image, mapping is trivial */\n\t\t\t\t\t\t\tif (dst == src) {\n\t\t\t\t\t\t\t\tnc = c;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t/* Find or create the best match */\n\t\t\t\t\t\t\t\t/* 2.0.5: can't use gdTrueColorGetRed, etc with palette */\n\t\t\t\t\t\t\t\tnc = gdImageColorResolveAlpha(dst, gdImageRed(src, c),\n\t\t\t\t\t\t\t\t\t\t\t\t gdImageGreen(src, c),\n\t\t\t\t\t\t\t\t\t\t\t\t gdImageBlue(src, c),\n\t\t\t\t\t\t\t\t\t\t\t\t gdImageAlpha(src, c));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcolorMap[c] = nc;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmapTo = colorMap[c];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (i = 0; (i < stx[x - srcX]); i++) {\n\t\t\t\t\tgdImageSetPixel (dst, tox, toy, mapTo);\n\t\t\t\t\ttox++;\n\t\t\t\t}\n\t\t\t}\n\t\t\ttoy++;\n\t\t}\n\t}\n\tgdFree (stx);\n\tgdFree (sty);\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: Get the IV size of cipher (Usually the same as the blocksize) */\nPHP_FUNCTION(mcrypt_get_iv_size)\n{\n\tchar *cipher;\n\tchar *module;\n\tint cipher_len, module_len; \n\tchar *cipher_dir_string;\n\tchar *module_dir_string;\n\tMCRYPT td;\n\n\tMCRYPT_GET_INI\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"ss\",\n\t\t&cipher, &cipher_len, &module, &module_len) == FAILURE) {\n\t\treturn;\n\t}\n\t\n\ttd = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string);\n\tif (td != MCRYPT_FAILED) {\n\t\tRETVAL_LONG(mcrypt_enc_get_iv_size(td));\n\t\tmcrypt_module_close(td);\n\t} else {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);\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: Get the key size of cipher */\nPHP_FUNCTION(mcrypt_get_key_size)\n{\n\tchar *cipher;\n\tchar *module;\n\tint cipher_len, module_len; \n\tchar *cipher_dir_string;\n\tchar *module_dir_string;\n\tMCRYPT td;\n\n\tMCRYPT_GET_INI\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"ss\",\n\t\t&cipher, &cipher_len, &module, &module_len) == FAILURE) {\n\t\treturn;\n\t}\n\t\n\ttd = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string);\n\tif (td != MCRYPT_FAILED) {\n\t\tRETVAL_LONG(mcrypt_enc_get_key_size(td));\n\t\tmcrypt_module_close(td);\n\t} else {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);\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: _php_mb_regex_init_options(const char *parg, int narg, OnigOptionType *option, OnigSyntaxType **syntax, int *eval) \n{\n\tint n;\n\tchar c;\n\tint optm = 0; \n\n\t*syntax = ONIG_SYNTAX_RUBY;\n\n\tif (parg != NULL) {\n\t\tn = 0;\n\t\twhile(n < narg) {\n\t\t\tc = parg[n++];\n\t\t\tswitch (c) {\n\t\t\t\tcase 'i':\n\t\t\t\t\toptm |= ONIG_OPTION_IGNORECASE;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'x':\n\t\t\t\t\toptm |= ONIG_OPTION_EXTEND;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'm':\n\t\t\t\t\toptm |= ONIG_OPTION_MULTILINE;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 's':\n\t\t\t\t\toptm |= ONIG_OPTION_SINGLELINE;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'p':\n\t\t\t\t\toptm |= ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'l':\n\t\t\t\t\toptm |= ONIG_OPTION_FIND_LONGEST;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'n':\n\t\t\t\t\toptm |= ONIG_OPTION_FIND_NOT_EMPTY;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'j':\n\t\t\t\t\t*syntax = ONIG_SYNTAX_JAVA;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'u':\n\t\t\t\t\t*syntax = ONIG_SYNTAX_GNU_REGEX;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'g':\n\t\t\t\t\t*syntax = ONIG_SYNTAX_GREP;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'c':\n\t\t\t\t\t*syntax = ONIG_SYNTAX_EMACS;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'r':\n\t\t\t\t\t*syntax = ONIG_SYNTAX_RUBY;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'z':\n\t\t\t\t\t*syntax = ONIG_SYNTAX_PERL;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'b':\n\t\t\t\t\t*syntax = ONIG_SYNTAX_POSIX_BASIC;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'd':\n\t\t\t\t\t*syntax = ONIG_SYNTAX_POSIX_EXTENDED;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'e':\n\t\t\t\t\tif (eval != NULL) *eval = 1; \n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (option != NULL) *option|=optm; \n\t}\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, fgetcsv)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\tchar delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape;\n\tchar *delim = NULL, *enclo = NULL, *esc = NULL;\n\tint d_len = 0, e_len = 0, esc_len = 0;\n\t\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"|sss\", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) {\n\t\tswitch(ZEND_NUM_ARGS())\n\t\t{\n\t\tcase 3:\n\t\t\tif (esc_len != 1) {\n\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"escape must be a character\");\n\t\t\t\tRETURN_FALSE;\n\t\t\t}\n\t\t\tescape = esc[0];\n\t\t\t/* no break */\n\t\tcase 2:\n\t\t\tif (e_len != 1) {\n\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"enclosure must be a character\");\n\t\t\t\tRETURN_FALSE;\n\t\t\t}\n\t\t\tenclosure = enclo[0];\n\t\t\t/* no break */\n\t\tcase 1:\n\t\t\tif (d_len != 1) {\n\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"delimiter must be a character\");\n\t\t\t\tRETURN_FALSE;\n\t\t\t}\n\t\t\tdelimiter = delim[0];\n\t\t\t/* no break */\n\t\tcase 0:\n\t\t\tbreak;\n\t\t}\n\t\tspl_filesystem_file_read_csv(intern, delimiter, enclosure, escape, return_value TSRMLS_CC);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72262 - do not overflow int'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: SPL_METHOD(RecursiveDirectoryIterator, getChildren)\n{\n\tzval *zpath, *zflags;\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\tspl_filesystem_object *subdir;\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\t\n\tspl_filesystem_object_get_file_name(intern TSRMLS_CC);\n\n\tMAKE_STD_ZVAL(zflags);\n\tMAKE_STD_ZVAL(zpath);\n\tZVAL_LONG(zflags, intern->flags);\n\tZVAL_STRINGL(zpath, intern->file_name, intern->file_name_len, 1);\n\tspl_instantiate_arg_ex2(Z_OBJCE_P(getThis()), &return_value, 0, zpath, zflags TSRMLS_CC);\n\tzval_ptr_dtor(&zpath);\n\tzval_ptr_dtor(&zflags);\n\n\tsubdir = (spl_filesystem_object*)zend_object_store_get_object(return_value TSRMLS_CC);\n\tif (subdir) {\n\t\tif (intern->u.dir.sub_path && intern->u.dir.sub_path[0]) {\n\t\t\tsubdir->u.dir.sub_path_len = spprintf(&subdir->u.dir.sub_path, 0, \"%s%c%s\", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name);\n\t\t} else {\n\t\t\tsubdir->u.dir.sub_path_len = strlen(intern->u.dir.entry.d_name);\n\t\t\tsubdir->u.dir.sub_path = estrndup(intern->u.dir.entry.d_name, subdir->u.dir.sub_path_len);\n\t\t}\n\t\tsubdir->info_class = intern->info_class;\n\t\tsubdir->file_class = intern->file_class;\n\t\tsubdir->oth = intern->oth;\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, ftruncate)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\tlong size;\n\t\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"l\", &size) == FAILURE) {\n\t\treturn;\n\t}\n\n\tif (!php_stream_truncate_supported(intern->u.file.stream)) {\n\t\tzend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, \"Can't truncate file %s\", intern->file_name);\n\t\tRETURN_FALSE;\n\t}\n\t\n\tRETURN_BOOL(0 == php_stream_truncate_set_size(intern->u.file.stream, size));\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, getLinkTarget)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\tint ret;\n\tchar buff[MAXPATHLEN];\n\tzend_error_handling error_handling;\n\t\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\n\tzend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);\n\n#if defined(PHP_WIN32) || HAVE_SYMLINK\n\tif (intern->file_name == NULL) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Empty filename\");\n\t\tRETURN_FALSE;\n\t} else if (!IS_ABSOLUTE_PATH(intern->file_name, intern->file_name_len)) {\n\t\tchar expanded_path[MAXPATHLEN];\n\t\tif (!expand_filepath_with_mode(intern->file_name, expanded_path, NULL, 0, CWD_EXPAND TSRMLS_CC)) {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"No such file or directory\");\n\t\t\tRETURN_FALSE;\n\t\t}\n\t\tret = php_sys_readlink(expanded_path, buff, MAXPATHLEN - 1);\n\t} else {\n\t\tret = php_sys_readlink(intern->file_name, buff, MAXPATHLEN-1);\n\t}\n#else\n\tret = -1; /* always fail if not implemented */\n#endif\n\n\tif (ret == -1) {\n\t\tzend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, \"Unable to read link %s, error: %s\", intern->file_name, strerror(errno));\n\t\tRETVAL_FALSE;\n\t} else {\n\t\t/* Append NULL to the end of the string */\n\t\tbuff[ret] = '\\0';\n\n\t\tRETVAL_STRINGL(buff, ret, 1);\n\t}\n\n\tzend_restore_error_handling(&error_handling 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: SPL_METHOD(FilesystemIterator, current)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\t\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\n\tif (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_PATHNAME)) {\n\t\tspl_filesystem_object_get_file_name(intern TSRMLS_CC);\n\t\tRETURN_STRINGL(intern->file_name, intern->file_name_len, 1);\n\t} else if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_FILEINFO)) {\n\t\tspl_filesystem_object_get_file_name(intern TSRMLS_CC);\n\t\tspl_filesystem_object_create_type(0, intern, SPL_FS_INFO, NULL, return_value TSRMLS_CC);\n\t} else {\n\t\tRETURN_ZVAL(getThis(), 1, 0);\n\t\t/*RETURN_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: SPL_METHOD(SplFileObject, rewind)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\t\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\n\tspl_filesystem_file_rewind(getThis(), intern 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: zend_function *spl_filesystem_object_get_method_check(zval **object_ptr, char *method, int method_len, const struct _zend_literal *key TSRMLS_DC) /* {{{ */\n{\n\tspl_filesystem_object *fsobj = zend_object_store_get_object(*object_ptr TSRMLS_CC);\n\t\n\tif (fsobj->u.dir.entry.d_name[0] == '\\0' && fsobj->orig_path == NULL) {\n\t\tmethod = \"_bad_state_ex\";\n\t\tmethod_len = sizeof(\"_bad_state_ex\") - 1;\n\t\tkey = NULL;\n\t}\n\t\n\treturn zend_get_std_object_handlers()->get_method(object_ptr, method, method_len, key 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 void cli_session_setup_gensec_remote_done(struct tevent_req *subreq)\n{\n\tstruct tevent_req *req =\n\t\ttevent_req_callback_data(subreq,\n\t\tstruct tevent_req);\n\tstruct cli_session_setup_gensec_state *state =\n\t\ttevent_req_data(req,\n\t\tstruct cli_session_setup_gensec_state);\n\tNTSTATUS status;\n\n\tTALLOC_FREE(state->inbuf);\n\tTALLOC_FREE(state->recv_iov);\n\n\tstatus = cli_sesssetup_blob_recv(subreq, state, &state->blob_in,\n\t\t\t\t\t &state->inbuf, &state->recv_iov);\n\tTALLOC_FREE(subreq);\n\tdata_blob_free(&state->blob_out);\n\tif (!NT_STATUS_IS_OK(status) &&\n\t !NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED))\n\t{\n\t\ttevent_req_nterror(req, status);\n\t\treturn;\n\t}\n\n\tif (NT_STATUS_IS_OK(status)) {\n\t\tstruct smbXcli_session *session = NULL;\n\t\tbool is_guest = false;\n\n\t\tif (smbXcli_conn_protocol(state->cli->conn) >= PROTOCOL_SMB2_02) {\n\t\t\tsession = state->cli->smb2.session;\n\t\t} else {\n\t\t\tsession = state->cli->smb1.session;\n\t\t}\n\n\t\tis_guest = smbXcli_session_is_guest(session);\n\t\tif (is_guest) {\n\t\t\t/*\n\t\t\t * We can't finish the gensec handshake, we don't\n\t\t\t * have a negotiated session key.\n\t\t\t *\n\t\t\t * So just pretend we are completely done.\n\t\t\t */\n\t\t\tstate->blob_in = data_blob_null;\n\t\t\tstate->local_ready = true;\n\t\t}\n\n\t\tstate->remote_ready = true;\n\t}\n\n\tif (state->local_ready && state->remote_ready) {\n\t\tcli_session_setup_gensec_ready(req);\n\t\treturn;\n\t}\n\n\tcli_session_setup_gensec_local_next(req);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-94'], 'message': 'CVE-2016-2019: s3:libsmb: add comment regarding smbXcli_session_is_guest() with mandatory signing\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=11860\n\nSigned-off-by: Stefan Metzmacher '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static zend_bool php_auto_globals_create_files(const char *name, uint name_len TSRMLS_DC)\n{\n\tzval *vars;\n\n\tif (PG(http_globals)[TRACK_VARS_FILES]) {\n\t\tvars = PG(http_globals)[TRACK_VARS_FILES];\n\t} else {\n\t\tALLOC_ZVAL(vars);\n\t\tarray_init(vars);\n\t\tINIT_PZVAL(vars);\n\t\tPG(http_globals)[TRACK_VARS_FILES] = vars;\n\t}\n\n\tzend_hash_update(&EG(symbol_table), name, name_len + 1, &vars, sizeof(zval *), NULL);\n\tZ_ADDREF_P(vars);\n\t\n\treturn 0; /* don't rearm */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-601'], 'message': 'Fix for HTTP_PROXY issue.\n\nThe following changes are made:\n- _SERVER/_ENV only has HTTP_PROXY if the local environment has it,\n and only one from the environment.\n- getenv('HTTP_PROXY') only returns one from the local environment\n- getenv has optional second parameter, telling it to only consider\n local environment'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static zend_bool php_auto_globals_create_cookie(const char *name, uint name_len TSRMLS_DC)\n{\n\tzval *vars;\n\n\tif (PG(variables_order) && (strchr(PG(variables_order),'C') || strchr(PG(variables_order),'c'))) {\n\t\tsapi_module.treat_data(PARSE_COOKIE, NULL, NULL TSRMLS_CC);\n\t\tvars = PG(http_globals)[TRACK_VARS_COOKIE];\n\t} else {\n\t\tALLOC_ZVAL(vars);\n\t\tarray_init(vars);\n\t\tINIT_PZVAL(vars);\n\t\tif (PG(http_globals)[TRACK_VARS_COOKIE]) {\n\t\t\tzval_ptr_dtor(&PG(http_globals)[TRACK_VARS_COOKIE]);\n\t\t}\n\t\tPG(http_globals)[TRACK_VARS_COOKIE] = vars;\n\t}\n\n\tzend_hash_update(&EG(symbol_table), name, name_len + 1, &vars, sizeof(zval *), NULL);\n\tZ_ADDREF_P(vars);\n\t\n\treturn 0; /* don't rearm */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-601'], 'message': 'Fix for HTTP_PROXY issue.\n\nThe following changes are made:\n- _SERVER/_ENV only has HTTP_PROXY if the local environment has it,\n and only one from the environment.\n- getenv('HTTP_PROXY') only returns one from the local environment\n- getenv has optional second parameter, telling it to only consider\n local environment'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void srpt_handle_tsk_mgmt(struct srpt_rdma_ch *ch,\n\t\t\t\t struct srpt_recv_ioctx *recv_ioctx,\n\t\t\t\t struct srpt_send_ioctx *send_ioctx)\n{\n\tstruct srp_tsk_mgmt *srp_tsk;\n\tstruct se_cmd *cmd;\n\tstruct se_session *sess = ch->sess;\n\tuint64_t unpacked_lun;\n\tuint32_t tag = 0;\n\tint tcm_tmr;\n\tint rc;\n\n\tBUG_ON(!send_ioctx);\n\n\tsrp_tsk = recv_ioctx->ioctx.buf;\n\tcmd = &send_ioctx->cmd;\n\n\tpr_debug(\"recv tsk_mgmt fn %d for task_tag %lld and cmd tag %lld\"\n\t\t \" cm_id %p sess %p\\n\", srp_tsk->tsk_mgmt_func,\n\t\t srp_tsk->task_tag, srp_tsk->tag, ch->cm_id, ch->sess);\n\n\tsrpt_set_cmd_state(send_ioctx, SRPT_STATE_MGMT);\n\tsend_ioctx->cmd.tag = srp_tsk->tag;\n\ttcm_tmr = srp_tmr_to_tcm(srp_tsk->tsk_mgmt_func);\n\tif (tcm_tmr < 0) {\n\t\tsend_ioctx->cmd.se_tmr_req->response =\n\t\t\tTMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED;\n\t\tgoto fail;\n\t}\n\tunpacked_lun = srpt_unpack_lun((uint8_t *)&srp_tsk->lun,\n\t\t\t\t sizeof(srp_tsk->lun));\n\n\tif (srp_tsk->tsk_mgmt_func == SRP_TSK_ABORT_TASK) {\n\t\trc = srpt_rx_mgmt_fn_tag(send_ioctx, srp_tsk->task_tag);\n\t\tif (rc < 0) {\n\t\t\tsend_ioctx->cmd.se_tmr_req->response =\n\t\t\t\t\tTMR_TASK_DOES_NOT_EXIST;\n\t\t\tgoto fail;\n\t\t}\n\t\ttag = srp_tsk->task_tag;\n\t}\n\trc = target_submit_tmr(&send_ioctx->cmd, sess, NULL, unpacked_lun,\n\t\t\t\tsrp_tsk, tcm_tmr, GFP_KERNEL, tag,\n\t\t\t\tTARGET_SCF_ACK_KREF);\n\tif (rc != 0) {\n\t\tsend_ioctx->cmd.se_tmr_req->response = TMR_FUNCTION_REJECTED;\n\t\tgoto fail;\n\t}\n\treturn;\nfail:\n\ttransport_send_check_condition_and_sense(cmd, 0, 0); // XXX:\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: isoent_gen_joliet_identifier(struct archive_write *a, struct isoent *isoent,\n struct idr *idr)\n{\n\tstruct iso9660 *iso9660;\n\tstruct isoent *np;\n\tunsigned char *p;\n\tsize_t l;\n\tint r;\n\tint ffmax, parent_len;\n\tstatic const struct archive_rb_tree_ops rb_ops = {\n\t\tisoent_cmp_node_joliet, isoent_cmp_key_joliet\n\t};\n\n\tif (isoent->children.cnt == 0)\n\t\treturn (0);\n\n\tiso9660 = a->format_data;\n\tif (iso9660->opt.joliet == OPT_JOLIET_LONGNAME)\n\t\tffmax = 206;\n\telse\n\t\tffmax = 128;\n\n\tr = idr_start(a, idr, isoent->children.cnt, ffmax, 6, 2, &rb_ops);\n\tif (r < 0)\n\t\treturn (r);\n\n\tparent_len = 1;\n\tfor (np = isoent; np->parent != np; np = np->parent)\n\t\tparent_len += np->mb_len + 1;\n\n\tfor (np = isoent->children.first; np != NULL; np = np->chnext) {\n\t\tunsigned char *dot;\n\t\tint ext_off, noff, weight;\n\t\tsize_t lt;\n\n\t\tif ((int)(l = np->file->basename_utf16.length) > ffmax)\n\t\t\tl = ffmax;\n\n\t\tp = malloc((l+1)*2);\n\t\tif (p == NULL) {\n\t\t\tarchive_set_error(&a->archive, ENOMEM,\n\t\t\t \"Can't allocate memory\");\n\t\t\treturn (ARCHIVE_FATAL);\n\t\t}\n\t\tmemcpy(p, np->file->basename_utf16.s, l);\n\t\tp[l] = 0;\n\t\tp[l+1] = 0;\n\n\t\tnp->identifier = (char *)p;\n\t\tlt = l;\n\t\tdot = p + l;\n\t\tweight = 0;\n\t\twhile (lt > 0) {\n\t\t\tif (!joliet_allowed_char(p[0], p[1]))\n\t\t\t\tarchive_be16enc(p, 0x005F); /* '_' */\n\t\t\telse if (p[0] == 0 && p[1] == 0x2E) /* '.' */\n\t\t\t\tdot = p;\n\t\t\tp += 2;\n\t\t\tlt -= 2;\n\t\t}\n\t\text_off = (int)(dot - (unsigned char *)np->identifier);\n\t\tnp->ext_off = ext_off;\n\t\tnp->ext_len = (int)l - ext_off;\n\t\tnp->id_len = (int)l;\n\n\t\t/*\n\t\t * Get a length of MBS of a full-pathname.\n\t\t */\n\t\tif ((int)np->file->basename_utf16.length > ffmax) {\n\t\t\tif (archive_strncpy_l(&iso9660->mbs,\n\t\t\t (const char *)np->identifier, l,\n\t\t\t\tiso9660->sconv_from_utf16be) != 0 &&\n\t\t\t errno == ENOMEM) {\n\t\t\t\tarchive_set_error(&a->archive, errno,\n\t\t\t\t \"No memory\");\n\t\t\t\treturn (ARCHIVE_FATAL);\n\t\t\t}\n\t\t\tnp->mb_len = (int)iso9660->mbs.length;\n\t\t\tif (np->mb_len != (int)np->file->basename.length)\n\t\t\t\tweight = np->mb_len;\n\t\t} else\n\t\t\tnp->mb_len = (int)np->file->basename.length;\n\n\t\t/* If a length of full-pathname is longer than 240 bytes,\n\t\t * it violates Joliet extensions regulation. */\n\t\tif (parent_len + np->mb_len > 240) {\n\t\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n\t\t\t \"The regulation of Joliet extensions;\"\n\t\t\t \" A length of a full-pathname of `%s' is \"\n\t\t\t \"longer than 240 bytes, (p=%d, b=%d)\",\n\t\t\t archive_entry_pathname(np->file->entry),\n\t\t\t (int)parent_len, (int)np->mb_len);\n\t\t\treturn (ARCHIVE_FATAL);\n\t\t}\n\n\t\t/* Make an offset of the number which is used to be set\n\t\t * hexadecimal number to avoid duplicate identifier. */\n\t\tif ((int)l == ffmax)\n\t\t\tnoff = ext_off - 6;\n\t\telse if ((int)l == ffmax-2)\n\t\t\tnoff = ext_off - 4;\n\t\telse if ((int)l == ffmax-4)\n\t\t\tnoff = ext_off - 2;\n\t\telse\n\t\t\tnoff = ext_off;\n\t\t/* Register entry to the identifier resolver. */\n\t\tidr_register(idr, np, weight, noff);\n\t}\n\n\t/* Resolve duplicate identifier with Joliet Volume. */\n\tidr_resolve(idr, idr_set_num_beutf16);\n\n\treturn (ARCHIVE_OK);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Issue 711: Be more careful about verifying filename lengths when writing ISO9660 archives\n\n* Don't cast size_t to int, since this can lead to overflow\n on machines where sizeof(int) < sizeof(size_t)\n* Check a + b > limit by writing it as\n a > limit || b > limit || a + b > limit\n to avoid problems when a + b wraps around.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (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_bz2iop_close(php_stream *stream, int close_handle TSRMLS_DC)\n{\n\tstruct php_bz2_stream_data_t *self = (struct php_bz2_stream_data_t *)stream->abstract;\n\tint ret = EOF;\n\t\n\tif (close_handle) {\n\t\tBZ2_bzclose(self->bz_file);\n\t}\n\n\tif (self->stream) {\n\t\tphp_stream_free(self->stream, PHP_STREAM_FREE_CLOSE | (close_handle == 0 ? PHP_STREAM_FREE_PRESERVE_HANDLE : 0));\n\t}\n\n\tefree(self);\n\n\treturn ret;\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: CWD_API void realpath_cache_del(const char *path, int path_len 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\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 (key == (*bucket)->key && path_len == (*bucket)->path_len &&\n\t\t\t\t\tmemcmp(path, (*bucket)->path, path_len) == 0) {\n\t\t\trealpath_cache_bucket *r = *bucket;\n\t\t\t*bucket = (*bucket)->next;\n\t\t \n\t\t\t/* if the pointers match then only subtract the length of the path */\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 \n\t\t\tfree(r);\n\t\t\treturn;\n\t\t} else {\n\t\t\tbucket = &(*bucket)->next;\n\t\t}\n\t}\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 int exif_process_user_comment(image_info_type *ImageInfo, char **pszInfoPtr, char **pszEncoding, char *szValuePtr, int ByteCount TSRMLS_DC)\n{\n\tint a;\n\tchar *decode;\n\tsize_t len;;\n\n\t*pszEncoding = NULL;\n\t/* Copy the comment */\n\tif (ByteCount>=8) {\n\t\tif (!memcmp(szValuePtr, \"UNICODE\\0\", 8)) {\n\t\t\t*pszEncoding = estrdup((const char*)szValuePtr);\n\t\t\tszValuePtr = szValuePtr+8;\n\t\t\tByteCount -= 8;\n\t\t\t/* First try to detect BOM: ZERO WIDTH NOBREAK SPACE (FEFF 16)\n\t\t\t * since we have no encoding support for the BOM yet we skip that.\n\t\t\t */\n\t\t\tif (!memcmp(szValuePtr, \"\\xFE\\xFF\", 2)) {\n\t\t\t\tdecode = \"UCS-2BE\";\n\t\t\t\tszValuePtr = szValuePtr+2;\n\t\t\t\tByteCount -= 2;\n\t\t\t} else if (!memcmp(szValuePtr, \"\\xFF\\xFE\", 2)) {\n\t\t\t\tdecode = \"UCS-2LE\";\n\t\t\t\tszValuePtr = szValuePtr+2;\n\t\t\t\tByteCount -= 2;\n\t\t\t} else if (ImageInfo->motorola_intel) {\n\t\t\t\tdecode = ImageInfo->decode_unicode_be;\n\t\t\t} else {\n\t\t\t\tdecode = ImageInfo->decode_unicode_le;\n\t\t\t}\n\t\t\t/* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX */\n\t\t\tif (zend_multibyte_encoding_converter(\n\t\t\t\t\t(unsigned char**)pszInfoPtr,\n\t\t\t\t\t&len,\n\t\t\t\t\t(unsigned char*)szValuePtr,\n\t\t\t\t\tByteCount,\n\t\t\t\t\tzend_multibyte_fetch_encoding(ImageInfo->encode_unicode TSRMLS_CC),\n\t\t\t\t\tzend_multibyte_fetch_encoding(decode TSRMLS_CC)\n\t\t\t\t\tTSRMLS_CC) == (size_t)-1) {\n\t\t\t\tlen = exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount);\n\t\t\t}\n\t\t\treturn len;\n\t\t} else if (!memcmp(szValuePtr, \"ASCII\\0\\0\\0\", 8)) {\n\t\t\t*pszEncoding = estrdup((const char*)szValuePtr);\n\t\t\tszValuePtr = szValuePtr+8;\n\t\t\tByteCount -= 8;\n\t\t} else if (!memcmp(szValuePtr, \"JIS\\0\\0\\0\\0\\0\", 8)) {\n\t\t\t/* JIS should be tanslated to MB or we leave it to the user - leave it to the user */\n\t\t\t*pszEncoding = estrdup((const char*)szValuePtr);\n\t\t\tszValuePtr = szValuePtr+8;\n\t\t\tByteCount -= 8;\n\t\t\t/* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX */\n\t\t\tif (zend_multibyte_encoding_converter(\n\t\t\t\t\t(unsigned char**)pszInfoPtr,\n\t\t\t\t\t&len,\n\t\t\t\t\t(unsigned char*)szValuePtr,\n\t\t\t\t\tByteCount,\n\t\t\t\t\tzend_multibyte_fetch_encoding(ImageInfo->encode_jis TSRMLS_CC),\n\t\t\t\t\tzend_multibyte_fetch_encoding(ImageInfo->motorola_intel ? ImageInfo->decode_jis_be : ImageInfo->decode_jis_le TSRMLS_CC)\n\t\t\t\t\tTSRMLS_CC) == (size_t)-1) {\n\t\t\t\tlen = exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount);\n\t\t\t}\n\t\t\treturn len;\n\t\t} else if (!memcmp(szValuePtr, \"\\0\\0\\0\\0\\0\\0\\0\\0\", 8)) {\n\t\t\t/* 8 NULL means undefined and should be ASCII... */\n\t\t\t*pszEncoding = estrdup(\"UNDEFINED\");\n\t\t\tszValuePtr = szValuePtr+8;\n\t\t\tByteCount -= 8;\n\t\t}\n\t}\n\n\t/* Olympus has this padded with trailing spaces. Remove these first. */\n\tif (ByteCount>0) {\n\t\tfor (a=ByteCount-1;a && szValuePtr[a]==' ';a--) {\n\t\t\t(szValuePtr)[a] = '\\0';\n\t\t}\n\t}\n\n\t/* normal text without encoding */\n\texif_process_string(pszInfoPtr, szValuePtr, ByteCount TSRMLS_CC);\n\treturn strlen(*pszInfoPtr);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix bug #72618: NULL Pointer Dereference in exif_process_user_comment'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PHP_FUNCTION(snmp_set_oid_output_format)\n{\n\tlong a1;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"l\", &a1) == FAILURE) {\n\t\tRETURN_FALSE;\n\t}\n\n\tswitch((int) a1) {\n\t\tcase NETSNMP_OID_OUTPUT_SUFFIX:\n\t\tcase NETSNMP_OID_OUTPUT_MODULE:\n\t\tcase NETSNMP_OID_OUTPUT_FULL:\n\t\tcase NETSNMP_OID_OUTPUT_NUMERIC:\n\t\tcase NETSNMP_OID_OUTPUT_UCD:\n\t\tcase NETSNMP_OID_OUTPUT_NONE:\n\t\t\tnetsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, a1);\n\t\t\tRETURN_TRUE;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Unknown SNMP output print format '%d'\", (int) a1);\n\t\t\tRETURN_FALSE;\n\t\t\tbreak;\n\t}\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: void simplestring_addn(simplestring* target, const char* source, int add_len) {\n if(target && source) {\n if(!target->str) {\n simplestring_init_str(target);\n }\n if(target->len + add_len + 1 > target->size) {\n /* newsize is current length + new length */\n int newsize = target->len + add_len + 1;\n int incr = target->size * 2;\n\n /* align to SIMPLESTRING_INCR increments */\n newsize = newsize - (newsize % incr) + incr;\n target->str = (char*)realloc(target->str, newsize);\n\n target->size = target->str ? newsize : 0;\n }\n\n if(target->str) {\n if(add_len) {\n memcpy(target->str + target->len, source, add_len);\n }\n target->len += add_len;\n target->str[target->len] = 0; /* null terminate */\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug #72606: heap-buffer-overflow (write) simplestring_addn simplestring.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 ext2_fill_super(struct super_block *sb, void *data, int silent)\n{\n\tstruct buffer_head * bh;\n\tstruct ext2_sb_info * sbi;\n\tstruct ext2_super_block * es;\n\tstruct inode *root;\n\tunsigned long block;\n\tunsigned long sb_block = get_sb_block(&data);\n\tunsigned long logic_sb_block;\n\tunsigned long offset = 0;\n\tunsigned long def_mount_opts;\n\tlong ret = -EINVAL;\n\tint blocksize = BLOCK_SIZE;\n\tint db_count;\n\tint i, j;\n\t__le32 features;\n\tint err;\n\n\terr = -ENOMEM;\n\tsbi = kzalloc(sizeof(*sbi), GFP_KERNEL);\n\tif (!sbi)\n\t\tgoto failed;\n\n\tsbi->s_blockgroup_lock =\n\t\tkzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL);\n\tif (!sbi->s_blockgroup_lock) {\n\t\tkfree(sbi);\n\t\tgoto failed;\n\t}\n\tsb->s_fs_info = sbi;\n\tsbi->s_sb_block = sb_block;\n\n\tspin_lock_init(&sbi->s_lock);\n\n\t/*\n\t * See what the current blocksize for the device is, and\n\t * use that as the blocksize. Otherwise (or if the blocksize\n\t * is smaller than the default) use the default.\n\t * This is important for devices that have a hardware\n\t * sectorsize that is larger than the default.\n\t */\n\tblocksize = sb_min_blocksize(sb, BLOCK_SIZE);\n\tif (!blocksize) {\n\t\text2_msg(sb, KERN_ERR, \"error: unable to set blocksize\");\n\t\tgoto failed_sbi;\n\t}\n\n\t/*\n\t * If the superblock doesn't start on a hardware sector boundary,\n\t * calculate the offset. \n\t */\n\tif (blocksize != BLOCK_SIZE) {\n\t\tlogic_sb_block = (sb_block*BLOCK_SIZE) / blocksize;\n\t\toffset = (sb_block*BLOCK_SIZE) % blocksize;\n\t} else {\n\t\tlogic_sb_block = sb_block;\n\t}\n\n\tif (!(bh = sb_bread(sb, logic_sb_block))) {\n\t\text2_msg(sb, KERN_ERR, \"error: unable to read superblock\");\n\t\tgoto failed_sbi;\n\t}\n\t/*\n\t * Note: s_es must be initialized as soon as possible because\n\t * some ext2 macro-instructions depend on its value\n\t */\n\tes = (struct ext2_super_block *) (((char *)bh->b_data) + offset);\n\tsbi->s_es = es;\n\tsb->s_magic = le16_to_cpu(es->s_magic);\n\n\tif (sb->s_magic != EXT2_SUPER_MAGIC)\n\t\tgoto cantfind_ext2;\n\n\t/* Set defaults before we parse the mount options */\n\tdef_mount_opts = le32_to_cpu(es->s_default_mount_opts);\n\tif (def_mount_opts & EXT2_DEFM_DEBUG)\n\t\tset_opt(sbi->s_mount_opt, DEBUG);\n\tif (def_mount_opts & EXT2_DEFM_BSDGROUPS)\n\t\tset_opt(sbi->s_mount_opt, GRPID);\n\tif (def_mount_opts & EXT2_DEFM_UID16)\n\t\tset_opt(sbi->s_mount_opt, NO_UID32);\n#ifdef CONFIG_EXT2_FS_XATTR\n\tif (def_mount_opts & EXT2_DEFM_XATTR_USER)\n\t\tset_opt(sbi->s_mount_opt, XATTR_USER);\n#endif\n#ifdef CONFIG_EXT2_FS_POSIX_ACL\n\tif (def_mount_opts & EXT2_DEFM_ACL)\n\t\tset_opt(sbi->s_mount_opt, POSIX_ACL);\n#endif\n\t\n\tif (le16_to_cpu(sbi->s_es->s_errors) == EXT2_ERRORS_PANIC)\n\t\tset_opt(sbi->s_mount_opt, ERRORS_PANIC);\n\telse if (le16_to_cpu(sbi->s_es->s_errors) == EXT2_ERRORS_CONTINUE)\n\t\tset_opt(sbi->s_mount_opt, ERRORS_CONT);\n\telse\n\t\tset_opt(sbi->s_mount_opt, ERRORS_RO);\n\n\tsbi->s_resuid = 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\t\n\tset_opt(sbi->s_mount_opt, RESERVATION);\n\n\tif (!parse_options((char *) data, sb))\n\t\tgoto failed_mount;\n\n\tsb->s_flags = (sb->s_flags & ~MS_POSIXACL) |\n\t\t((EXT2_SB(sb)->s_mount_opt & EXT2_MOUNT_POSIX_ACL) ?\n\t\t MS_POSIXACL : 0);\n\tsb->s_iflags |= SB_I_CGROUPWB;\n\n\tif (le32_to_cpu(es->s_rev_level) == EXT2_GOOD_OLD_REV &&\n\t (EXT2_HAS_COMPAT_FEATURE(sb, ~0U) ||\n\t EXT2_HAS_RO_COMPAT_FEATURE(sb, ~0U) ||\n\t EXT2_HAS_INCOMPAT_FEATURE(sb, ~0U)))\n\t\text2_msg(sb, KERN_WARNING,\n\t\t\t\"warning: feature flags set on rev 0 fs, \"\n\t\t\t\"running e2fsck is recommended\");\n\t/*\n\t * Check feature flags regardless of the revision level, since we\n\t * previously didn't change the revision level when setting the flags,\n\t * so there is a chance incompat flags are set on a rev 0 filesystem.\n\t */\n\tfeatures = EXT2_HAS_INCOMPAT_FEATURE(sb, ~EXT2_FEATURE_INCOMPAT_SUPP);\n\tif (features) {\n\t\text2_msg(sb, KERN_ERR,\t\"error: couldn't mount because of \"\n\t\t \"unsupported optional features (%x)\",\n\t\t\tle32_to_cpu(features));\n\t\tgoto failed_mount;\n\t}\n\tif (!(sb->s_flags & MS_RDONLY) &&\n\t (features = EXT2_HAS_RO_COMPAT_FEATURE(sb, ~EXT2_FEATURE_RO_COMPAT_SUPP))){\n\t\text2_msg(sb, KERN_ERR, \"error: couldn't mount RDWR because of \"\n\t\t \"unsupported optional features (%x)\",\n\t\t le32_to_cpu(features));\n\t\tgoto failed_mount;\n\t}\n\n\tblocksize = BLOCK_SIZE << le32_to_cpu(sbi->s_es->s_log_block_size);\n\n\tif (sbi->s_mount_opt & EXT2_MOUNT_DAX) {\n\t\tif (blocksize != PAGE_SIZE) {\n\t\t\text2_msg(sb, KERN_ERR,\n\t\t\t\t\t\"error: unsupported blocksize for dax\");\n\t\t\tgoto failed_mount;\n\t\t}\n\t\tif (!sb->s_bdev->bd_disk->fops->direct_access) {\n\t\t\text2_msg(sb, KERN_ERR,\n\t\t\t\t\t\"error: device does not support dax\");\n\t\t\tgoto failed_mount;\n\t\t}\n\t}\n\n\t/* If the blocksize doesn't match, re-read the thing.. */\n\tif (sb->s_blocksize != blocksize) {\n\t\tbrelse(bh);\n\n\t\tif (!sb_set_blocksize(sb, blocksize)) {\n\t\t\text2_msg(sb, KERN_ERR,\n\t\t\t\t\"error: bad blocksize %d\", blocksize);\n\t\t\tgoto failed_sbi;\n\t\t}\n\n\t\tlogic_sb_block = (sb_block*BLOCK_SIZE) / blocksize;\n\t\toffset = (sb_block*BLOCK_SIZE) % blocksize;\n\t\tbh = sb_bread(sb, logic_sb_block);\n\t\tif(!bh) {\n\t\t\text2_msg(sb, KERN_ERR, \"error: couldn't read\"\n\t\t\t\t\"superblock on 2nd try\");\n\t\t\tgoto failed_sbi;\n\t\t}\n\t\tes = (struct ext2_super_block *) (((char *)bh->b_data) + offset);\n\t\tsbi->s_es = es;\n\t\tif (es->s_magic != cpu_to_le16(EXT2_SUPER_MAGIC)) {\n\t\t\text2_msg(sb, KERN_ERR, \"error: magic mismatch\");\n\t\t\tgoto failed_mount;\n\t\t}\n\t}\n\n\tsb->s_maxbytes = ext2_max_size(sb->s_blocksize_bits);\n\tsb->s_max_links = EXT2_LINK_MAX;\n\n\tif (le32_to_cpu(es->s_rev_level) == EXT2_GOOD_OLD_REV) {\n\t\tsbi->s_inode_size = EXT2_GOOD_OLD_INODE_SIZE;\n\t\tsbi->s_first_ino = EXT2_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 < EXT2_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\text2_msg(sb, KERN_ERR,\n\t\t\t\t\"error: unsupported inode size: %d\",\n\t\t\t\tsbi->s_inode_size);\n\t\t\tgoto failed_mount;\n\t\t}\n\t}\n\n\tsbi->s_frag_size = EXT2_MIN_FRAG_SIZE <<\n\t\t\t\t le32_to_cpu(es->s_log_frag_size);\n\tif (sbi->s_frag_size == 0)\n\t\tgoto cantfind_ext2;\n\tsbi->s_frags_per_block = sb->s_blocksize / sbi->s_frag_size;\n\n\tsbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group);\n\tsbi->s_frags_per_group = le32_to_cpu(es->s_frags_per_group);\n\tsbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group);\n\n\tif (EXT2_INODE_SIZE(sb) == 0)\n\t\tgoto cantfind_ext2;\n\tsbi->s_inodes_per_block = sb->s_blocksize / EXT2_INODE_SIZE(sb);\n\tif (sbi->s_inodes_per_block == 0 || sbi->s_inodes_per_group == 0)\n\t\tgoto cantfind_ext2;\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 = sb->s_blocksize /\n\t\t\t\t\tsizeof (struct ext2_group_desc);\n\tsbi->s_sbh = bh;\n\tsbi->s_mount_state = le16_to_cpu(es->s_state);\n\tsbi->s_addr_per_block_bits =\n\t\tilog2 (EXT2_ADDR_PER_BLOCK(sb));\n\tsbi->s_desc_per_block_bits =\n\t\tilog2 (EXT2_DESC_PER_BLOCK(sb));\n\n\tif (sb->s_magic != EXT2_SUPER_MAGIC)\n\t\tgoto cantfind_ext2;\n\n\tif (sb->s_blocksize != bh->b_size) {\n\t\tif (!silent)\n\t\t\text2_msg(sb, KERN_ERR, \"error: unsupported blocksize\");\n\t\tgoto failed_mount;\n\t}\n\n\tif (sb->s_blocksize != sbi->s_frag_size) {\n\t\text2_msg(sb, KERN_ERR,\n\t\t\t\"error: fragsize %lu != blocksize %lu\"\n\t\t\t\"(not supported yet)\",\n\t\t\tsbi->s_frag_size, sb->s_blocksize);\n\t\tgoto failed_mount;\n\t}\n\n\tif (sbi->s_blocks_per_group > sb->s_blocksize * 8) {\n\t\text2_msg(sb, KERN_ERR,\n\t\t\t\"error: #blocks per group too big: %lu\",\n\t\t\tsbi->s_blocks_per_group);\n\t\tgoto failed_mount;\n\t}\n\tif (sbi->s_frags_per_group > sb->s_blocksize * 8) {\n\t\text2_msg(sb, KERN_ERR,\n\t\t\t\"error: #fragments per group too big: %lu\",\n\t\t\tsbi->s_frags_per_group);\n\t\tgoto failed_mount;\n\t}\n\tif (sbi->s_inodes_per_group > sb->s_blocksize * 8) {\n\t\text2_msg(sb, KERN_ERR,\n\t\t\t\"error: #inodes per group too big: %lu\",\n\t\t\tsbi->s_inodes_per_group);\n\t\tgoto failed_mount;\n\t}\n\n\tif (EXT2_BLOCKS_PER_GROUP(sb) == 0)\n\t\tgoto cantfind_ext2;\n \tsbi->s_groups_count = ((le32_to_cpu(es->s_blocks_count) -\n \t\t\t\tle32_to_cpu(es->s_first_data_block) - 1)\n \t\t\t\t\t/ EXT2_BLOCKS_PER_GROUP(sb)) + 1;\n\tdb_count = (sbi->s_groups_count + EXT2_DESC_PER_BLOCK(sb) - 1) /\n\t\t EXT2_DESC_PER_BLOCK(sb);\n\tsbi->s_group_desc = kmalloc (db_count * sizeof (struct buffer_head *), GFP_KERNEL);\n\tif (sbi->s_group_desc == NULL) {\n\t\text2_msg(sb, KERN_ERR, \"error: not enough memory\");\n\t\tgoto failed_mount;\n\t}\n\tbgl_lock_init(sbi->s_blockgroup_lock);\n\tsbi->s_debts = kcalloc(sbi->s_groups_count, sizeof(*sbi->s_debts), GFP_KERNEL);\n\tif (!sbi->s_debts) {\n\t\text2_msg(sb, KERN_ERR, \"error: not enough memory\");\n\t\tgoto failed_mount_group_desc;\n\t}\n\tfor (i = 0; i < db_count; i++) {\n\t\tblock = descriptor_loc(sb, logic_sb_block, i);\n\t\tsbi->s_group_desc[i] = sb_bread(sb, block);\n\t\tif (!sbi->s_group_desc[i]) {\n\t\t\tfor (j = 0; j < i; j++)\n\t\t\t\tbrelse (sbi->s_group_desc[j]);\n\t\t\text2_msg(sb, KERN_ERR,\n\t\t\t\t\"error: unable to read group descriptors\");\n\t\t\tgoto failed_mount_group_desc;\n\t\t}\n\t}\n\tif (!ext2_check_descriptors (sb)) {\n\t\text2_msg(sb, KERN_ERR, \"group descriptors corrupted\");\n\t\tgoto failed_mount2;\n\t}\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\t/* per fileystem reservation list head & lock */\n\tspin_lock_init(&sbi->s_rsv_window_lock);\n\tsbi->s_rsv_window_root = RB_ROOT;\n\t/*\n\t * Add a single, static dummy reservation to the start of the\n\t * reservation window list --- it gives us a placeholder for\n\t * append-at-start-of-list which makes the allocation logic\n\t * _much_ simpler.\n\t */\n\tsbi->s_rsv_window_head.rsv_start = EXT2_RESERVE_WINDOW_NOT_ALLOCATED;\n\tsbi->s_rsv_window_head.rsv_end = EXT2_RESERVE_WINDOW_NOT_ALLOCATED;\n\tsbi->s_rsv_window_head.rsv_alloc_hit = 0;\n\tsbi->s_rsv_window_head.rsv_goal_size = 0;\n\text2_rsv_window_add(sb, &sbi->s_rsv_window_head);\n\n\terr = percpu_counter_init(&sbi->s_freeblocks_counter,\n\t\t\t\text2_count_free_blocks(sb), GFP_KERNEL);\n\tif (!err) {\n\t\terr = percpu_counter_init(&sbi->s_freeinodes_counter,\n\t\t\t\text2_count_free_inodes(sb), GFP_KERNEL);\n\t}\n\tif (!err) {\n\t\terr = percpu_counter_init(&sbi->s_dirs_counter,\n\t\t\t\text2_count_dirs(sb), GFP_KERNEL);\n\t}\n\tif (err) {\n\t\text2_msg(sb, KERN_ERR, \"error: insufficient memory\");\n\t\tgoto failed_mount3;\n\t}\n\t/*\n\t * set up enough so that it can read an inode\n\t */\n\tsb->s_op = &ext2_sops;\n\tsb->s_export_op = &ext2_export_ops;\n\tsb->s_xattr = ext2_xattr_handlers;\n\n#ifdef CONFIG_QUOTA\n\tsb->dq_op = &dquot_operations;\n\tsb->s_qcop = &dquot_quotactl_ops;\n\tsb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP;\n#endif\n\n\troot = ext2_iget(sb, EXT2_ROOT_INO);\n\tif (IS_ERR(root)) {\n\t\tret = PTR_ERR(root);\n\t\tgoto failed_mount3;\n\t}\n\tif (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) {\n\t\tiput(root);\n\t\text2_msg(sb, KERN_ERR, \"error: corrupt root inode, run e2fsck\");\n\t\tgoto failed_mount3;\n\t}\n\n\tsb->s_root = d_make_root(root);\n\tif (!sb->s_root) {\n\t\text2_msg(sb, KERN_ERR, \"error: get root inode failed\");\n\t\tret = -ENOMEM;\n\t\tgoto failed_mount3;\n\t}\n\tif (EXT2_HAS_COMPAT_FEATURE(sb, EXT3_FEATURE_COMPAT_HAS_JOURNAL))\n\t\text2_msg(sb, KERN_WARNING,\n\t\t\t\"warning: mounting ext3 filesystem as ext2\");\n\tif (ext2_setup_super (sb, es, sb->s_flags & MS_RDONLY))\n\t\tsb->s_flags |= MS_RDONLY;\n\text2_write_super(sb);\n\treturn 0;\n\ncantfind_ext2:\n\tif (!silent)\n\t\text2_msg(sb, KERN_ERR,\n\t\t\t\"error: can't find an ext2 filesystem on dev %s.\",\n\t\t\tsb->s_id);\n\tgoto failed_mount;\nfailed_mount3:\n\tpercpu_counter_destroy(&sbi->s_freeblocks_counter);\n\tpercpu_counter_destroy(&sbi->s_freeinodes_counter);\n\tpercpu_counter_destroy(&sbi->s_dirs_counter);\nfailed_mount2:\n\tfor (i = 0; i < db_count; i++)\n\t\tbrelse(sbi->s_group_desc[i]);\nfailed_mount_group_desc:\n\tkfree(sbi->s_group_desc);\n\tkfree(sbi->s_debts);\nfailed_mount:\n\tbrelse(bh);\nfailed_sbi:\n\tsb->s_fs_info = NULL;\n\tkfree(sbi->s_blockgroup_lock);\n\tkfree(sbi);\nfailed:\n\treturn ret;\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_set2(struct inode *inode, struct buffer_head *old_bh,\n\t\tstruct ext2_xattr_header *header)\n{\n\tstruct super_block *sb = inode->i_sb;\n\tstruct buffer_head *new_bh = NULL;\n\tint error;\n\n\tif (header) {\n\t\tnew_bh = ext2_xattr_cache_find(inode, header);\n\t\tif (new_bh) {\n\t\t\t/* We found an identical block in the cache. */\n\t\t\tif (new_bh == old_bh) {\n\t\t\t\tea_bdebug(new_bh, \"keeping this block\");\n\t\t\t} else {\n\t\t\t\t/* The old block is released after updating\n\t\t\t\t the inode. */\n\t\t\t\tea_bdebug(new_bh, \"reusing block\");\n\n\t\t\t\terror = dquot_alloc_block(inode, 1);\n\t\t\t\tif (error) {\n\t\t\t\t\tunlock_buffer(new_bh);\n\t\t\t\t\tgoto cleanup;\n\t\t\t\t}\n\t\t\t\tle32_add_cpu(&HDR(new_bh)->h_refcount, 1);\n\t\t\t\tea_bdebug(new_bh, \"refcount now=%d\",\n\t\t\t\t\tle32_to_cpu(HDR(new_bh)->h_refcount));\n\t\t\t}\n\t\t\tunlock_buffer(new_bh);\n\t\t} else if (old_bh && header == HDR(old_bh)) {\n\t\t\t/* Keep this block. No need to lock the block as we\n\t\t\t don't need to change the reference count. */\n\t\t\tnew_bh = old_bh;\n\t\t\tget_bh(new_bh);\n\t\t\text2_xattr_cache_insert(new_bh);\n\t\t} else {\n\t\t\t/* We need to allocate a new block */\n\t\t\text2_fsblk_t goal = ext2_group_first_block_no(sb,\n\t\t\t\t\t\tEXT2_I(inode)->i_block_group);\n\t\t\tint block = ext2_new_block(inode, goal, &error);\n\t\t\tif (error)\n\t\t\t\tgoto cleanup;\n\t\t\tea_idebug(inode, \"creating block %d\", block);\n\n\t\t\tnew_bh = sb_getblk(sb, block);\n\t\t\tif (unlikely(!new_bh)) {\n\t\t\t\text2_free_blocks(inode, block, 1);\n\t\t\t\tmark_inode_dirty(inode);\n\t\t\t\terror = -ENOMEM;\n\t\t\t\tgoto cleanup;\n\t\t\t}\n\t\t\tlock_buffer(new_bh);\n\t\t\tmemcpy(new_bh->b_data, header, new_bh->b_size);\n\t\t\tset_buffer_uptodate(new_bh);\n\t\t\tunlock_buffer(new_bh);\n\t\t\text2_xattr_cache_insert(new_bh);\n\t\t\t\n\t\t\text2_xattr_update_super_block(sb);\n\t\t}\n\t\tmark_buffer_dirty(new_bh);\n\t\tif (IS_SYNC(inode)) {\n\t\t\tsync_dirty_buffer(new_bh);\n\t\t\terror = -EIO;\n\t\t\tif (buffer_req(new_bh) && !buffer_uptodate(new_bh))\n\t\t\t\tgoto cleanup;\n\t\t}\n\t}\n\n\t/* Update the inode. */\n\tEXT2_I(inode)->i_file_acl = new_bh ? new_bh->b_blocknr : 0;\n\tinode->i_ctime = CURRENT_TIME_SEC;\n\tif (IS_SYNC(inode)) {\n\t\terror = sync_inode_metadata(inode, 1);\n\t\t/* In case sync failed due to ENOSPC the inode was actually\n\t\t * written (only some dirty data were not) so we just proceed\n\t\t * as if nothing happened and cleanup the unused block */\n\t\tif (error && error != -ENOSPC) {\n\t\t\tif (new_bh && new_bh != old_bh) {\n\t\t\t\tdquot_free_block_nodirty(inode, 1);\n\t\t\t\tmark_inode_dirty(inode);\n\t\t\t}\n\t\t\tgoto cleanup;\n\t\t}\n\t} else\n\t\tmark_inode_dirty(inode);\n\n\terror = 0;\n\tif (old_bh && old_bh != new_bh) {\n\t\tstruct mb_cache_entry *ce;\n\n\t\t/*\n\t\t * If there was an old block and we are no longer using it,\n\t\t * release the old block.\n\t\t */\n\t\tce = mb_cache_entry_get(ext2_xattr_cache, old_bh->b_bdev,\n\t\t\t\t\told_bh->b_blocknr);\n\t\tlock_buffer(old_bh);\n\t\tif (HDR(old_bh)->h_refcount == cpu_to_le32(1)) {\n\t\t\t/* Free the old block. */\n\t\t\tif (ce)\n\t\t\t\tmb_cache_entry_free(ce);\n\t\t\tea_bdebug(old_bh, \"freeing\");\n\t\t\text2_free_blocks(inode, old_bh->b_blocknr, 1);\n\t\t\tmark_inode_dirty(inode);\n\t\t\t/* We let our caller release old_bh, so we\n\t\t\t * need to duplicate the buffer before. */\n\t\t\tget_bh(old_bh);\n\t\t\tbforget(old_bh);\n\t\t} else {\n\t\t\t/* Decrement the refcount only. */\n\t\t\tle32_add_cpu(&HDR(old_bh)->h_refcount, -1);\n\t\t\tif (ce)\n\t\t\t\tmb_cache_entry_release(ce);\n\t\t\tdquot_free_block_nodirty(inode, 1);\n\t\t\tmark_inode_dirty(inode);\n\t\t\tmark_buffer_dirty(old_bh);\n\t\t\tea_bdebug(old_bh, \"refcount now=%d\",\n\t\t\t\tle32_to_cpu(HDR(old_bh)->h_refcount));\n\t\t}\n\t\tunlock_buffer(old_bh);\n\t}\n\ncleanup:\n\tbrelse(new_bh);\n\n\treturn error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'ext2: convert to mbcache2\n\nThe conversion is generally straightforward. We convert filesystem from\na global cache to per-fs one. Similarly to ext4 the tricky part is that\nxattr block corresponding to found mbcache entry can get freed before we\nget buffer lock for that block. So we have to check whether the entry is\nstill valid after getting the buffer lock.\n\nSigned-off-by: Jan Kara \nSigned-off-by: Theodore Ts'o '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static MagickBooleanType Get8BIMProperty(const Image *image,const char *key,\n ExceptionInfo *exception)\n{\n char\n *attribute,\n format[MagickPathExtent],\n name[MagickPathExtent],\n *resource;\n\n const StringInfo\n *profile;\n\n const unsigned char\n *info;\n\n long\n start,\n stop;\n\n MagickBooleanType\n status;\n\n register ssize_t\n i;\n\n size_t\n length;\n\n ssize_t\n count,\n id,\n sub_number;\n\n /*\n There are no newlines in path names, so it's safe as terminator.\n */\n profile=GetImageProfile(image,\"8bim\");\n if (profile == (StringInfo *) NULL)\n return(MagickFalse);\n count=(ssize_t) sscanf(key,\"8BIM:%ld,%ld:%1024[^\\n]\\n%1024[^\\n]\",&start,&stop,\n name,format);\n if ((count != 2) && (count != 3) && (count != 4))\n return(MagickFalse);\n if (count < 4)\n (void) CopyMagickString(format,\"SVG\",MagickPathExtent);\n if (count < 3)\n *name='\\0';\n sub_number=1;\n if (*name == '#')\n sub_number=(ssize_t) StringToLong(&name[1]);\n sub_number=MagickMax(sub_number,1L);\n resource=(char *) NULL;\n status=MagickFalse;\n length=GetStringInfoLength(profile);\n info=GetStringInfoDatum(profile);\n while ((length > 0) && (status == MagickFalse))\n {\n if (ReadPropertyByte(&info,&length) != (unsigned char) '8')\n continue;\n if (ReadPropertyByte(&info,&length) != (unsigned char) 'B')\n continue;\n if (ReadPropertyByte(&info,&length) != (unsigned char) 'I')\n continue;\n if (ReadPropertyByte(&info,&length) != (unsigned char) 'M')\n continue;\n id=(ssize_t) ReadPropertyMSBShort(&info,&length);\n if (id < (ssize_t) start)\n continue;\n if (id > (ssize_t) stop)\n continue;\n if (resource != (char *) NULL)\n resource=DestroyString(resource);\n count=(ssize_t) ReadPropertyByte(&info,&length);\n if ((count != 0) && ((size_t) count <= length))\n {\n resource=(char *) NULL;\n if (~((size_t) count) >= (MagickPathExtent-1))\n resource=(char *) AcquireQuantumMemory((size_t) count+\n MagickPathExtent,sizeof(*resource));\n if (resource != (char *) NULL)\n {\n for (i=0; i < (ssize_t) count; i++)\n resource[i]=(char) ReadPropertyByte(&info,&length);\n resource[count]='\\0';\n }\n }\n if ((count & 0x01) == 0)\n (void) ReadPropertyByte(&info,&length);\n count=(ssize_t) ReadPropertyMSBLong(&info,&length);\n if ((*name != '\\0') && (*name != '#'))\n if ((resource == (char *) NULL) || (LocaleCompare(name,resource) != 0))\n {\n /*\n No name match, scroll forward and try next.\n */\n info+=count;\n length-=MagickMin(count,(ssize_t) length);\n continue;\n }\n if ((*name == '#') && (sub_number != 1))\n {\n /*\n No numbered match, scroll forward and try next.\n */\n sub_number--;\n info+=count;\n length-=MagickMin(count,(ssize_t) length);\n continue;\n }\n /*\n We have the resource of interest.\n */\n attribute=(char *) NULL;\n if (~((size_t) count) >= (MagickPathExtent-1))\n attribute=(char *) AcquireQuantumMemory((size_t) count+MagickPathExtent,\n sizeof(*attribute));\n if (attribute != (char *) NULL)\n {\n (void) CopyMagickMemory(attribute,(char *) info,(size_t) count);\n attribute[count]='\\0';\n info+=count;\n length-=MagickMin(count,(ssize_t) length);\n if ((id <= 1999) || (id >= 2999))\n (void) SetImageProperty((Image *) image,key,(const char *)\n attribute,exception);\n else\n {\n char\n *path;\n\n if (LocaleCompare(format,\"svg\") == 0)\n path=TraceSVGClippath((unsigned char *) attribute,(size_t) count,\n image->columns,image->rows);\n else\n path=TracePSClippath((unsigned char *) attribute,(size_t) count);\n (void) SetImageProperty((Image *) image,key,(const char *) path,\n exception);\n path=DestroyString(path);\n }\n attribute=DestroyString(attribute);\n status=MagickTrue;\n }\n }\n if (resource != (char *) NULL)\n resource=DestroyString(resource);\n return(status);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Prevent buffer 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: recv_and_process_client_pkt(void /*int fd*/)\n{\n\tssize_t size;\n\t//uint8_t version;\n\tlen_and_sockaddr *to;\n\tstruct sockaddr *from;\n\tmsg_t msg;\n\tuint8_t query_status;\n\tl_fixedpt_t query_xmttime;\n\n\tto = get_sock_lsa(G_listen_fd);\n\tfrom = xzalloc(to->len);\n\n\tsize = recv_from_to(G_listen_fd, &msg, sizeof(msg), MSG_DONTWAIT, from, &to->u.sa, to->len);\n\tif (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {\n\t\tchar *addr;\n\t\tif (size < 0) {\n\t\t\tif (errno == EAGAIN)\n\t\t\t\tgoto bail;\n\t\t\tbb_perror_msg_and_die(\"recv\");\n\t\t}\n\t\taddr = xmalloc_sockaddr2dotted_noport(from);\n\t\tbb_error_msg(\"malformed packet received from %s: size %u\", addr, (int)size);\n\t\tfree(addr);\n\t\tgoto bail;\n\t}\n\n\tquery_status = msg.m_status;\n\tquery_xmttime = msg.m_xmttime;\n\n\t/* Build a reply packet */\n\tmemset(&msg, 0, sizeof(msg));\n\tmsg.m_status = G.stratum < MAXSTRAT ? (G.ntp_status & LI_MASK) : LI_ALARM;\n\tmsg.m_status |= (query_status & VERSION_MASK);\n\tmsg.m_status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?\n\t\t\tMODE_SERVER : MODE_SYM_PAS;\n\tmsg.m_stratum = G.stratum;\n\tmsg.m_ppoll = G.poll_exp;\n\tmsg.m_precision_exp = G_precision_exp;\n\t/* this time was obtained between poll() and recv() */\n\tmsg.m_rectime = d_to_lfp(G.cur_time);\n\tmsg.m_xmttime = d_to_lfp(gettime1900d()); /* this instant */\n\tif (G.peer_cnt == 0) {\n\t\t/* we have no peers: \"stratum 1 server\" mode. reftime = our own time */\n\t\tG.reftime = G.cur_time;\n\t}\n\tmsg.m_reftime = d_to_lfp(G.reftime);\n\tmsg.m_orgtime = query_xmttime;\n\tmsg.m_rootdelay = d_to_sfp(G.rootdelay);\n//simple code does not do this, fix simple code!\n\tmsg.m_rootdisp = d_to_sfp(G.rootdisp);\n\t//version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */\n\tmsg.m_refid = G.refid; // (version > (3 << VERSION_SHIFT)) ? G.refid : G.refid3;\n\n\t/* We reply from the local address packet was sent to,\n\t * this makes to/from look swapped here: */\n\tdo_sendto(G_listen_fd,\n\t\t/*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,\n\t\t&msg, size);\n\n bail:\n\tfree(to);\n\tfree(from);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'ntpd: respond only to client and symmetric active packets\n\nThe busybox NTP implementation doesn't check the NTP mode of packets\nreceived on the server port and responds to any packet with the right\nsize. This includes responses from another NTP server. An attacker can\nsend a packet with a spoofed source address in order to create an\ninfinite loop of responses between two busybox NTP servers. Adding\nmore packets to the loop increases the traffic between the servers\nuntil one of them has a fully loaded CPU and/or network.\n\nSigned-off-by: Miroslav Lichvar \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: ipv6_dup_options(struct sock *sk, struct ipv6_txoptions *opt)\n{\n\tstruct ipv6_txoptions *opt2;\n\n\topt2 = sock_kmalloc(sk, opt->tot_len, GFP_ATOMIC);\n\tif (opt2) {\n\t\tlong dif = (char *)opt2 - (char *)opt;\n\t\tmemcpy(opt2, opt, opt->tot_len);\n\t\tif (opt2->hopopt)\n\t\t\t*((char **)&opt2->hopopt) += dif;\n\t\tif (opt2->dst0opt)\n\t\t\t*((char **)&opt2->dst0opt) += dif;\n\t\tif (opt2->dst1opt)\n\t\t\t*((char **)&opt2->dst1opt) += dif;\n\t\tif (opt2->srcrt)\n\t\t\t*((char **)&opt2->srcrt) += dif;\n\t}\n\treturn opt2;\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: static struct sock *dccp_v6_request_recv_sock(const struct sock *sk,\n\t\t\t\t\t struct sk_buff *skb,\n\t\t\t\t\t struct request_sock *req,\n\t\t\t\t\t struct dst_entry *dst,\n\t\t\t\t\t struct request_sock *req_unhash,\n\t\t\t\t\t bool *own_req)\n{\n\tstruct inet_request_sock *ireq = inet_rsk(req);\n\tstruct ipv6_pinfo *newnp;\n\tconst struct ipv6_pinfo *np = inet6_sk(sk);\n\tstruct inet_sock *newinet;\n\tstruct dccp6_sock *newdp6;\n\tstruct sock *newsk;\n\n\tif (skb->protocol == htons(ETH_P_IP)) {\n\t\t/*\n\t\t *\tv6 mapped\n\t\t */\n\t\tnewsk = dccp_v4_request_recv_sock(sk, skb, req, dst,\n\t\t\t\t\t\t req_unhash, own_req);\n\t\tif (newsk == NULL)\n\t\t\treturn NULL;\n\n\t\tnewdp6 = (struct dccp6_sock *)newsk;\n\t\tnewinet = inet_sk(newsk);\n\t\tnewinet->pinet6 = &newdp6->inet6;\n\t\tnewnp = inet6_sk(newsk);\n\n\t\tmemcpy(newnp, np, sizeof(struct ipv6_pinfo));\n\n\t\tnewnp->saddr = newsk->sk_v6_rcv_saddr;\n\n\t\tinet_csk(newsk)->icsk_af_ops = &dccp_ipv6_mapped;\n\t\tnewsk->sk_backlog_rcv = dccp_v4_do_rcv;\n\t\tnewnp->pktoptions = NULL;\n\t\tnewnp->opt\t = NULL;\n\t\tnewnp->mcast_oif = inet6_iif(skb);\n\t\tnewnp->mcast_hops = ipv6_hdr(skb)->hop_limit;\n\n\t\t/*\n\t\t * No need to charge this sock to the relevant IPv6 refcnt debug socks count\n\t\t * here, dccp_create_openreq_child now does this for us, see the comment in\n\t\t * that function for the gory details. -acme\n\t\t */\n\n\t\t/* It is tricky place. Until this moment IPv4 tcp\n\t\t worked with IPv6 icsk.icsk_af_ops.\n\t\t Sync it now.\n\t\t */\n\t\tdccp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie);\n\n\t\treturn newsk;\n\t}\n\n\n\tif (sk_acceptq_is_full(sk))\n\t\tgoto out_overflow;\n\n\tif (!dst) {\n\t\tstruct flowi6 fl6;\n\n\t\tdst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_DCCP);\n\t\tif (!dst)\n\t\t\tgoto out;\n\t}\n\n\tnewsk = dccp_create_openreq_child(sk, req, skb);\n\tif (newsk == NULL)\n\t\tgoto out_nonewsk;\n\n\t/*\n\t * No need to charge this sock to the relevant IPv6 refcnt debug socks\n\t * count here, dccp_create_openreq_child now does this for us, see the\n\t * comment in that function for the gory details. -acme\n\t */\n\n\t__ip6_dst_store(newsk, dst, NULL, NULL);\n\tnewsk->sk_route_caps = dst->dev->features & ~(NETIF_F_IP_CSUM |\n\t\t\t\t\t\t NETIF_F_TSO);\n\tnewdp6 = (struct dccp6_sock *)newsk;\n\tnewinet = inet_sk(newsk);\n\tnewinet->pinet6 = &newdp6->inet6;\n\tnewnp = inet6_sk(newsk);\n\n\tmemcpy(newnp, np, sizeof(struct ipv6_pinfo));\n\n\tnewsk->sk_v6_daddr\t= ireq->ir_v6_rmt_addr;\n\tnewnp->saddr\t\t= ireq->ir_v6_loc_addr;\n\tnewsk->sk_v6_rcv_saddr\t= ireq->ir_v6_loc_addr;\n\tnewsk->sk_bound_dev_if\t= ireq->ir_iif;\n\n\t/* Now IPv6 options...\n\n\t First: no IPv4 options.\n\t */\n\tnewinet->inet_opt = NULL;\n\n\t/* Clone RX bits */\n\tnewnp->rxopt.all = np->rxopt.all;\n\n\tnewnp->pktoptions = NULL;\n\tnewnp->opt\t = NULL;\n\tnewnp->mcast_oif = inet6_iif(skb);\n\tnewnp->mcast_hops = ipv6_hdr(skb)->hop_limit;\n\n\t/*\n\t * Clone native IPv6 options from listening socket (if any)\n\t *\n\t * Yes, keeping reference count would be much more clever, but we make\n\t * one more one thing there: reattach optmem to newsk.\n\t */\n\tif (np->opt != NULL)\n\t\tnewnp->opt = ipv6_dup_options(newsk, np->opt);\n\n\tinet_csk(newsk)->icsk_ext_hdr_len = 0;\n\tif (newnp->opt != NULL)\n\t\tinet_csk(newsk)->icsk_ext_hdr_len = (newnp->opt->opt_nflen +\n\t\t\t\t\t\t newnp->opt->opt_flen);\n\n\tdccp_sync_mss(newsk, dst_mtu(dst));\n\n\tnewinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6;\n\tnewinet->inet_rcv_saddr = LOOPBACK4_IPV6;\n\n\tif (__inet_inherit_port(sk, newsk) < 0) {\n\t\tinet_csk_prepare_forced_close(newsk);\n\t\tdccp_done(newsk);\n\t\tgoto out;\n\t}\n\t*own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash));\n\t/* Clone pktoptions received with SYN, if we own the req */\n\tif (*own_req && ireq->pktopts) {\n\t\tnewnp->pktoptions = skb_clone(ireq->pktopts, GFP_ATOMIC);\n\t\tconsume_skb(ireq->pktopts);\n\t\tireq->pktopts = NULL;\n\t\tif (newnp->pktoptions)\n\t\t\tskb_set_owner_r(newnp->pktoptions, newsk);\n\t}\n\n\treturn newsk;\n\nout_overflow:\n\tNET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);\nout_nonewsk:\n\tdst_release(dst);\nout:\n\tNET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS);\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-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: Curves16Data* CurvesAlloc(cmsContext ContextID, int nCurves, int nElements, cmsToneCurve** G)\n{\n int i, j;\n Curves16Data* c16;\n\n c16 = (Curves16Data*)_cmsMallocZero(ContextID, sizeof(Curves16Data));\n if (c16 == NULL) return NULL;\n\n c16 ->nCurves = nCurves;\n c16 ->nElements = nElements;\n\n c16->Curves = (cmsUInt16Number**) _cmsCalloc(ContextID, nCurves, sizeof(cmsUInt16Number*));\n if (c16 ->Curves == NULL) return NULL;\n\n for (i=0; i < nCurves; i++) {\n\n c16->Curves[i] = (cmsUInt16Number*) _cmsCalloc(ContextID, nElements, sizeof(cmsUInt16Number));\n\n if (c16->Curves[i] == NULL) {\n\n for (j=0; j < i; j++) {\n _cmsFree(ContextID, c16->Curves[j]);\n }\n _cmsFree(ContextID, c16->Curves);\n _cmsFree(ContextID, c16);\n return NULL;\n }\n\n if (nElements == 256) {\n\n for (j=0; j < nElements; j++) {\n\n c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], FROM_8_TO_16(j));\n }\n }\n else {\n\n for (j=0; j < nElements; j++) {\n c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], (cmsUInt16Number) j);\n }\n }\n }\n\n return c16;\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: __ext4_set_acl(handle_t *handle, struct inode *inode, int type,\n\t struct posix_acl *acl)\n{\n\tint name_index;\n\tvoid *value = NULL;\n\tsize_t size = 0;\n\tint error;\n\n\tswitch (type) {\n\tcase ACL_TYPE_ACCESS:\n\t\tname_index = EXT4_XATTR_INDEX_POSIX_ACL_ACCESS;\n\t\tif (acl) {\n\t\t\terror = posix_acl_equiv_mode(acl, &inode->i_mode);\n\t\t\tif (error < 0)\n\t\t\t\treturn error;\n\t\t\telse {\n\t\t\t\tinode->i_ctime = ext4_current_time(inode);\n\t\t\t\text4_mark_inode_dirty(handle, inode);\n\t\t\t\tif (error == 0)\n\t\t\t\t\tacl = NULL;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase ACL_TYPE_DEFAULT:\n\t\tname_index = EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT;\n\t\tif (!S_ISDIR(inode->i_mode))\n\t\t\treturn acl ? -EACCES : 0;\n\t\tbreak;\n\n\tdefault:\n\t\treturn -EINVAL;\n\t}\n\tif (acl) {\n\t\tvalue = ext4_acl_to_disk(acl, &size);\n\t\tif (IS_ERR(value))\n\t\t\treturn (int)PTR_ERR(value);\n\t}\n\n\terror = ext4_xattr_set_handle(handle, inode, name_index, \"\",\n\t\t\t\t value, size, 0);\n\n\tkfree(value);\n\tif (!error)\n\t\tset_cached_acl(inode, type, acl);\n\n\treturn error;\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: void net_tx_pkt_init(struct NetTxPkt **pkt, PCIDevice *pci_dev,\n uint32_t max_frags, bool has_virt_hdr)\n{\n struct NetTxPkt *p = g_malloc0(sizeof *p);\n\n p->pci_dev = pci_dev;\n\n p->vec = g_malloc((sizeof *p->vec) *\n (max_frags + NET_TX_PKT_PL_START_FRAG));\n\n p->raw = g_malloc((sizeof *p->raw) * max_frags);\n\n p->max_payload_frags = max_frags;\n p->max_raw_frags = max_frags;\n p->has_virt_hdr = has_virt_hdr;\n p->vec[NET_TX_PKT_VHDR_FRAG].iov_base = &p->virt_hdr;\n p->vec[NET_TX_PKT_VHDR_FRAG].iov_len =\n p->has_virt_hdr ? sizeof p->virt_hdr : 0;\n p->vec[NET_TX_PKT_L2HDR_FRAG].iov_base = &p->l2_hdr;\n p->vec[NET_TX_PKT_L3HDR_FRAG].iov_base = &p->l3_hdr;\n\n *pkt = p;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'net: vmxnet: use g_new for pkt initialisation\n\nWhen network transport abstraction layer initialises pkt, the maximum\nfragmentation count is not checked. This could lead to an integer\noverflow causing a NULL pointer dereference. Replace g_malloc() with\ng_new() to catch the multiplication overflow.\n\nReported-by: Li Qiang \nSigned-off-by: Prasad J Pandit \nAcked-by: Dmitry Fleytman \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: 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\tl_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16));\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-787'], 'message': 'Fix an integer overflow issue (#809)\n\nPrevent an integer overflow issue in function opj_pi_create_decode of\r\npi.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 puff(unsigned char *dest, /* pointer to destination pointer */\n boost::uint32_t *destlen, /* amount of output space */\n const unsigned char *source, /* pointer to source data pointer */\n boost::uint32_t *sourcelen) /* amount of input available */\n{\n struct state s; /* input/output state */\n int last, type; /* block information */\n int err; /* return value */\n\n /* initialize output state */\n s.out = dest;\n s.outlen = *destlen; /* ignored if dest is NIL */\n s.outcnt = 0;\n\n /* initialize input state */\n s.in = source;\n s.inlen = *sourcelen;\n s.incnt = 0;\n s.bitbuf = 0;\n s.bitcnt = 0;\n\n /* return if bits() or decode() tries to read past available input */\n if (setjmp(s.env) != 0) /* if came back here via longjmp() */\n err = 2; /* then skip do-loop, return error */\n else {\n /* process blocks until last block or error */\n do {\n last = bits(&s, 1); /* one if last block */\n type = bits(&s, 2); /* block type 0..3 */\n err = type == 0 ? stored(&s) :\n (type == 1 ? fixed(&s) :\n (type == 2 ? dynamic(&s) :\n -1)); /* type == 3, invalid */\n if (err != 0) break; /* return with error */\n } while (!last);\n }\n\n /* update the lengths and return */\n if (err <= 0) {\n *destlen = s.outcnt;\n *sourcelen = s.incnt;\n }\n return err;\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: string PacketReader::getLabel(unsigned int recurs)\n{\n string ret;\n ret.reserve(40);\n getLabelFromContent(d_content, d_pos, ret, recurs++);\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'Reject qname's wirelength > 255, `chopOff()` handle dot inside labels'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int arcmsr_iop_message_xfer(struct AdapterControlBlock *acb,\n\t\tstruct scsi_cmnd *cmd)\n{\n\tchar *buffer;\n\tunsigned short use_sg;\n\tint retvalue = 0, transfer_len = 0;\n\tunsigned long flags;\n\tstruct CMD_MESSAGE_FIELD *pcmdmessagefld;\n\tuint32_t controlcode = (uint32_t)cmd->cmnd[5] << 24 |\n\t\t(uint32_t)cmd->cmnd[6] << 16 |\n\t\t(uint32_t)cmd->cmnd[7] << 8 |\n\t\t(uint32_t)cmd->cmnd[8];\n\tstruct scatterlist *sg;\n\n\tuse_sg = scsi_sg_count(cmd);\n\tsg = scsi_sglist(cmd);\n\tbuffer = kmap_atomic(sg_page(sg)) + sg->offset;\n\tif (use_sg > 1) {\n\t\tretvalue = ARCMSR_MESSAGE_FAIL;\n\t\tgoto message_out;\n\t}\n\ttransfer_len += sg->length;\n\tif (transfer_len > sizeof(struct CMD_MESSAGE_FIELD)) {\n\t\tretvalue = ARCMSR_MESSAGE_FAIL;\n\t\tpr_info(\"%s: ARCMSR_MESSAGE_FAIL!\\n\", __func__);\n\t\tgoto message_out;\n\t}\n\tpcmdmessagefld = (struct CMD_MESSAGE_FIELD *)buffer;\n\tswitch (controlcode) {\n\tcase ARCMSR_MESSAGE_READ_RQBUFFER: {\n\t\tunsigned char *ver_addr;\n\t\tuint8_t *ptmpQbuffer;\n\t\tuint32_t allxfer_len = 0;\n\t\tver_addr = kmalloc(ARCMSR_API_DATA_BUFLEN, GFP_ATOMIC);\n\t\tif (!ver_addr) {\n\t\t\tretvalue = ARCMSR_MESSAGE_FAIL;\n\t\t\tpr_info(\"%s: memory not enough!\\n\", __func__);\n\t\t\tgoto message_out;\n\t\t}\n\t\tptmpQbuffer = ver_addr;\n\t\tspin_lock_irqsave(&acb->rqbuffer_lock, flags);\n\t\tif (acb->rqbuf_getIndex != acb->rqbuf_putIndex) {\n\t\t\tunsigned int tail = acb->rqbuf_getIndex;\n\t\t\tunsigned int head = acb->rqbuf_putIndex;\n\t\t\tunsigned int cnt_to_end = CIRC_CNT_TO_END(head, tail, ARCMSR_MAX_QBUFFER);\n\n\t\t\tallxfer_len = CIRC_CNT(head, tail, ARCMSR_MAX_QBUFFER);\n\t\t\tif (allxfer_len > ARCMSR_API_DATA_BUFLEN)\n\t\t\t\tallxfer_len = ARCMSR_API_DATA_BUFLEN;\n\n\t\t\tif (allxfer_len <= cnt_to_end)\n\t\t\t\tmemcpy(ptmpQbuffer, acb->rqbuffer + tail, allxfer_len);\n\t\t\telse {\n\t\t\t\tmemcpy(ptmpQbuffer, acb->rqbuffer + tail, cnt_to_end);\n\t\t\t\tmemcpy(ptmpQbuffer + cnt_to_end, acb->rqbuffer, allxfer_len - cnt_to_end);\n\t\t\t}\n\t\t\tacb->rqbuf_getIndex = (acb->rqbuf_getIndex + allxfer_len) % ARCMSR_MAX_QBUFFER;\n\t\t}\n\t\tmemcpy(pcmdmessagefld->messagedatabuffer, ver_addr,\n\t\t\tallxfer_len);\n\t\tif (acb->acb_flags & ACB_F_IOPDATA_OVERFLOW) {\n\t\t\tstruct QBUFFER __iomem *prbuffer;\n\t\t\tacb->acb_flags &= ~ACB_F_IOPDATA_OVERFLOW;\n\t\t\tprbuffer = arcmsr_get_iop_rqbuffer(acb);\n\t\t\tif (arcmsr_Read_iop_rqbuffer_data(acb, prbuffer) == 0)\n\t\t\t\tacb->acb_flags |= ACB_F_IOPDATA_OVERFLOW;\n\t\t}\n\t\tspin_unlock_irqrestore(&acb->rqbuffer_lock, flags);\n\t\tkfree(ver_addr);\n\t\tpcmdmessagefld->cmdmessage.Length = allxfer_len;\n\t\tif (acb->fw_flag == FW_DEADLOCK)\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;\n\t\telse\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_OK;\n\t\tbreak;\n\t}\n\tcase ARCMSR_MESSAGE_WRITE_WQBUFFER: {\n\t\tunsigned char *ver_addr;\n\t\tuint32_t user_len;\n\t\tint32_t cnt2end;\n\t\tuint8_t *pQbuffer, *ptmpuserbuffer;\n\t\tver_addr = kmalloc(ARCMSR_API_DATA_BUFLEN, GFP_ATOMIC);\n\t\tif (!ver_addr) {\n\t\t\tretvalue = ARCMSR_MESSAGE_FAIL;\n\t\t\tgoto message_out;\n\t\t}\n\t\tptmpuserbuffer = ver_addr;\n\t\tuser_len = pcmdmessagefld->cmdmessage.Length;\n\t\tif (user_len > ARCMSR_API_DATA_BUFLEN) {\n\t\t\tretvalue = ARCMSR_MESSAGE_FAIL;\n\t\t\tkfree(ver_addr);\n\t\t\tgoto message_out;\n\t\t}\n\t\tmemcpy(ptmpuserbuffer,\n\t\t\tpcmdmessagefld->messagedatabuffer, user_len);\n\t\tspin_lock_irqsave(&acb->wqbuffer_lock, flags);\n\t\tif (acb->wqbuf_putIndex != acb->wqbuf_getIndex) {\n\t\t\tstruct SENSE_DATA *sensebuffer =\n\t\t\t\t(struct SENSE_DATA *)cmd->sense_buffer;\n\t\t\tarcmsr_write_ioctldata2iop(acb);\n\t\t\t/* has error report sensedata */\n\t\t\tsensebuffer->ErrorCode = SCSI_SENSE_CURRENT_ERRORS;\n\t\t\tsensebuffer->SenseKey = ILLEGAL_REQUEST;\n\t\t\tsensebuffer->AdditionalSenseLength = 0x0A;\n\t\t\tsensebuffer->AdditionalSenseCode = 0x20;\n\t\t\tsensebuffer->Valid = 1;\n\t\t\tretvalue = ARCMSR_MESSAGE_FAIL;\n\t\t} else {\n\t\t\tpQbuffer = &acb->wqbuffer[acb->wqbuf_putIndex];\n\t\t\tcnt2end = ARCMSR_MAX_QBUFFER - acb->wqbuf_putIndex;\n\t\t\tif (user_len > cnt2end) {\n\t\t\t\tmemcpy(pQbuffer, ptmpuserbuffer, cnt2end);\n\t\t\t\tptmpuserbuffer += cnt2end;\n\t\t\t\tuser_len -= cnt2end;\n\t\t\t\tacb->wqbuf_putIndex = 0;\n\t\t\t\tpQbuffer = acb->wqbuffer;\n\t\t\t}\n\t\t\tmemcpy(pQbuffer, ptmpuserbuffer, user_len);\n\t\t\tacb->wqbuf_putIndex += user_len;\n\t\t\tacb->wqbuf_putIndex %= ARCMSR_MAX_QBUFFER;\n\t\t\tif (acb->acb_flags & ACB_F_MESSAGE_WQBUFFER_CLEARED) {\n\t\t\t\tacb->acb_flags &=\n\t\t\t\t\t\t~ACB_F_MESSAGE_WQBUFFER_CLEARED;\n\t\t\t\tarcmsr_write_ioctldata2iop(acb);\n\t\t\t}\n\t\t}\n\t\tspin_unlock_irqrestore(&acb->wqbuffer_lock, flags);\n\t\tkfree(ver_addr);\n\t\tif (acb->fw_flag == FW_DEADLOCK)\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;\n\t\telse\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_OK;\n\t\tbreak;\n\t}\n\tcase ARCMSR_MESSAGE_CLEAR_RQBUFFER: {\n\t\tuint8_t *pQbuffer = acb->rqbuffer;\n\n\t\tarcmsr_clear_iop2drv_rqueue_buffer(acb);\n\t\tspin_lock_irqsave(&acb->rqbuffer_lock, flags);\n\t\tacb->acb_flags |= ACB_F_MESSAGE_RQBUFFER_CLEARED;\n\t\tacb->rqbuf_getIndex = 0;\n\t\tacb->rqbuf_putIndex = 0;\n\t\tmemset(pQbuffer, 0, ARCMSR_MAX_QBUFFER);\n\t\tspin_unlock_irqrestore(&acb->rqbuffer_lock, flags);\n\t\tif (acb->fw_flag == FW_DEADLOCK)\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;\n\t\telse\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_OK;\n\t\tbreak;\n\t}\n\tcase ARCMSR_MESSAGE_CLEAR_WQBUFFER: {\n\t\tuint8_t *pQbuffer = acb->wqbuffer;\n\t\tspin_lock_irqsave(&acb->wqbuffer_lock, flags);\n\t\tacb->acb_flags |= (ACB_F_MESSAGE_WQBUFFER_CLEARED |\n\t\t\tACB_F_MESSAGE_WQBUFFER_READED);\n\t\tacb->wqbuf_getIndex = 0;\n\t\tacb->wqbuf_putIndex = 0;\n\t\tmemset(pQbuffer, 0, ARCMSR_MAX_QBUFFER);\n\t\tspin_unlock_irqrestore(&acb->wqbuffer_lock, flags);\n\t\tif (acb->fw_flag == FW_DEADLOCK)\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;\n\t\telse\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_OK;\n\t\tbreak;\n\t}\n\tcase ARCMSR_MESSAGE_CLEAR_ALLQBUFFER: {\n\t\tuint8_t *pQbuffer;\n\t\tarcmsr_clear_iop2drv_rqueue_buffer(acb);\n\t\tspin_lock_irqsave(&acb->rqbuffer_lock, flags);\n\t\tacb->acb_flags |= ACB_F_MESSAGE_RQBUFFER_CLEARED;\n\t\tacb->rqbuf_getIndex = 0;\n\t\tacb->rqbuf_putIndex = 0;\n\t\tpQbuffer = acb->rqbuffer;\n\t\tmemset(pQbuffer, 0, sizeof(struct QBUFFER));\n\t\tspin_unlock_irqrestore(&acb->rqbuffer_lock, flags);\n\t\tspin_lock_irqsave(&acb->wqbuffer_lock, flags);\n\t\tacb->acb_flags |= (ACB_F_MESSAGE_WQBUFFER_CLEARED |\n\t\t\tACB_F_MESSAGE_WQBUFFER_READED);\n\t\tacb->wqbuf_getIndex = 0;\n\t\tacb->wqbuf_putIndex = 0;\n\t\tpQbuffer = acb->wqbuffer;\n\t\tmemset(pQbuffer, 0, sizeof(struct QBUFFER));\n\t\tspin_unlock_irqrestore(&acb->wqbuffer_lock, flags);\n\t\tif (acb->fw_flag == FW_DEADLOCK)\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;\n\t\telse\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_OK;\n\t\tbreak;\n\t}\n\tcase ARCMSR_MESSAGE_RETURN_CODE_3F: {\n\t\tif (acb->fw_flag == FW_DEADLOCK)\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;\n\t\telse\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_3F;\n\t\tbreak;\n\t}\n\tcase ARCMSR_MESSAGE_SAY_HELLO: {\n\t\tint8_t *hello_string = \"Hello! I am ARCMSR\";\n\t\tif (acb->fw_flag == FW_DEADLOCK)\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;\n\t\telse\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_OK;\n\t\tmemcpy(pcmdmessagefld->messagedatabuffer,\n\t\t\thello_string, (int16_t)strlen(hello_string));\n\t\tbreak;\n\t}\n\tcase ARCMSR_MESSAGE_SAY_GOODBYE: {\n\t\tif (acb->fw_flag == FW_DEADLOCK)\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;\n\t\telse\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_OK;\n\t\tarcmsr_iop_parking(acb);\n\t\tbreak;\n\t}\n\tcase ARCMSR_MESSAGE_FLUSH_ADAPTER_CACHE: {\n\t\tif (acb->fw_flag == FW_DEADLOCK)\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;\n\t\telse\n\t\t\tpcmdmessagefld->cmdmessage.ReturnCode =\n\t\t\t\tARCMSR_MESSAGE_RETURNCODE_OK;\n\t\tarcmsr_flush_adapter_cache(acb);\n\t\tbreak;\n\t}\n\tdefault:\n\t\tretvalue = ARCMSR_MESSAGE_FAIL;\n\t\tpr_info(\"%s: unknown controlcode!\\n\", __func__);\n\t}\nmessage_out:\n\tif (use_sg) {\n\t\tstruct scatterlist *sg = scsi_sglist(cmd);\n\t\tkunmap_atomic(buffer - sg->offset);\n\t}\n\treturn retvalue;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'scsi: arcmsr: Simplify user_len checking\n\nDo the user_len check first and then the ver_addr allocation so that we\ncan save us the kfree() on the error path when user_len is >\nARCMSR_API_DATA_BUFLEN.\n\nSigned-off-by: Borislav Petkov \nCc: Marco Grassi \nCc: Dan Carpenter \nCc: Tomas Henzl \nCc: Martin K. Petersen \nCc: \nReviewed-by: Johannes Thumshirn \nReviewed-by: Tomas Henzl \nSigned-off-by: Martin K. Petersen '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static MagickBooleanType WriteImageChannels(const PSDInfo *psd_info,\n const ImageInfo *image_info,Image *image,Image *next_image,\n const MagickBooleanType separate,ExceptionInfo *exception)\n{\n size_t\n channels,\n packet_size;\n\n unsigned char\n *compact_pixels;\n\n /*\n Write uncompressed pixels as separate planes.\n */\n channels=1;\n packet_size=next_image->depth > 8UL ? 2UL : 1UL;\n compact_pixels=(unsigned char *) NULL;\n if (next_image->compression == RLECompression)\n {\n compact_pixels=(unsigned char *) AcquireQuantumMemory(2*channels*\n next_image->columns,packet_size*sizeof(*compact_pixels));\n if (compact_pixels == (unsigned char *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n if (IsImageGray(next_image) != MagickFalse)\n {\n if (next_image->compression == RLECompression)\n {\n /*\n Packbits compression.\n */\n (void) WriteBlobMSBShort(image,1);\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,GrayQuantum,exception);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,AlphaQuantum,exception);\n }\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n GrayQuantum,MagickTrue,exception);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n AlphaQuantum,separate,exception);\n (void) SetImageProgress(image,SaveImagesTag,0,1);\n }\n else\n if (next_image->storage_class == PseudoClass)\n {\n if (next_image->compression == RLECompression)\n {\n /*\n Packbits compression.\n */\n (void) WriteBlobMSBShort(image,1);\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,IndexQuantum,exception);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,AlphaQuantum,exception);\n }\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n IndexQuantum,MagickTrue,exception);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n AlphaQuantum,separate,exception);\n (void) SetImageProgress(image,SaveImagesTag,0,1);\n }\n else\n {\n if (next_image->colorspace == CMYKColorspace)\n (void) NegateCMYK(next_image,exception);\n if (next_image->compression == RLECompression)\n {\n /*\n Packbits compression.\n */\n (void) WriteBlobMSBShort(image,1);\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,RedQuantum,exception);\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,GreenQuantum,exception);\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,BlueQuantum,exception);\n if (next_image->colorspace == CMYKColorspace)\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,BlackQuantum,exception);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,AlphaQuantum,exception);\n }\n (void) SetImageProgress(image,SaveImagesTag,0,6);\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n RedQuantum,MagickTrue,exception);\n (void) SetImageProgress(image,SaveImagesTag,1,6);\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n GreenQuantum,separate,exception);\n (void) SetImageProgress(image,SaveImagesTag,2,6);\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n BlueQuantum,separate,exception);\n (void) SetImageProgress(image,SaveImagesTag,3,6);\n if (next_image->colorspace == CMYKColorspace)\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n BlackQuantum,separate,exception);\n (void) SetImageProgress(image,SaveImagesTag,4,6);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n AlphaQuantum,separate,exception);\n (void) SetImageProgress(image,SaveImagesTag,5,6);\n if (next_image->colorspace == CMYKColorspace)\n (void) NegateCMYK(next_image,exception);\n }\n if (next_image->compression == RLECompression)\n compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n return(MagickTrue);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed 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 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 height;\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 == 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 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->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 if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n switch (sun_info.maptype)\n {\n case RMT_NONE:\n break;\n case RMT_EQUAL_RGB:\n {\n unsigned char\n *sun_colormap;\n\n /*\n Read SUN raster colormap.\n */\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,\"ImproperImageHeader\");\n number_pixels=(MagickSizeType) (image->columns*image->rows);\n if ((sun_info.type != RT_ENCODED) && \n ((number_pixels*sun_info.depth) > (8UL*sun_info.length)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n bytes_per_line=sun_info.width*sun_info.depth;\n sun_data=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax(\n sun_info.length,bytes_per_line*sun_info.width),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 height=sun_info.height;\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,\"ImproperImageHeader\");\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,\"ImproperImageHeader\");\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 if (sun_info.type == RT_ENCODED)\n (void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line*\n height);\n else\n {\n if (sun_info.length > (height*bytes_per_line))\n ThrowReaderException(ResourceLimitError,\"ImproperImageHeader\");\n (void) CopyMagickMemory(sun_pixels,sun_data,sun_info.length);\n }\n sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);\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 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,ConstrainColormapIndex(image,*p,exception),q);\n p++;\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 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-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 WritePDBImage(const ImageInfo *image_info,Image *image,\n ExceptionInfo *exception)\n{\n const char\n *comment;\n\n int\n bits;\n\n MagickBooleanType\n status;\n\n PDBImage\n pdb_image;\n\n PDBInfo\n pdb_info;\n\n QuantumInfo\n *quantum_info;\n\n register const Quantum\n *p;\n\n register ssize_t\n x;\n\n register unsigned char\n *q;\n\n size_t\n bits_per_pixel,\n literal,\n packets,\n packet_size,\n repeat;\n\n ssize_t\n y;\n\n unsigned char\n *buffer,\n *runlength,\n *scanline;\n\n /*\n Open output image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(status);\n (void) TransformImageColorspace(image,sRGBColorspace,exception);\n if (SetImageMonochrome(image,exception) != MagickFalse) {\n bits_per_pixel=1;\n } else if (image->colors <= 4) {\n bits_per_pixel=2;\n } else if (image->colors <= 8) {\n bits_per_pixel=3;\n } else {\n bits_per_pixel=4;\n }\n (void) ResetMagickMemory(&pdb_info,0,sizeof(pdb_info));\n (void) CopyMagickString(pdb_info.name,image_info->filename,\n sizeof(pdb_info.name));\n pdb_info.attributes=0;\n pdb_info.version=0;\n pdb_info.create_time=time(NULL);\n pdb_info.modify_time=pdb_info.create_time;\n pdb_info.archive_time=0;\n pdb_info.modify_number=0;\n pdb_info.application_info=0;\n pdb_info.sort_info=0;\n (void) CopyMagickMemory(pdb_info.type,\"vIMG\",4);\n (void) CopyMagickMemory(pdb_info.id,\"View\",4);\n pdb_info.seed=0;\n pdb_info.next_record=0;\n comment=GetImageProperty(image,\"comment\",exception);\n pdb_info.number_records=(comment == (const char *) NULL ? 1 : 2);\n (void) WriteBlob(image,sizeof(pdb_info.name),(unsigned char *) pdb_info.name);\n (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.attributes);\n (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.version);\n (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.create_time);\n (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_time);\n (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.archive_time);\n (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_number);\n (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.application_info);\n (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.sort_info);\n (void) WriteBlob(image,4,(unsigned char *) pdb_info.type);\n (void) WriteBlob(image,4,(unsigned char *) pdb_info.id);\n (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.seed);\n (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.next_record);\n (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.number_records);\n (void) CopyMagickString(pdb_image.name,pdb_info.name,sizeof(pdb_image.name));\n pdb_image.version=1; /* RLE Compressed */\n switch (bits_per_pixel)\n {\n case 1: pdb_image.type=(unsigned char) 0xff; break; /* monochrome */\n case 2: pdb_image.type=(unsigned char) 0x00; break; /* 2 bit gray */\n default: pdb_image.type=(unsigned char) 0x02; /* 4 bit gray */\n }\n pdb_image.reserved_1=0;\n pdb_image.note=0;\n pdb_image.x_last=0;\n pdb_image.y_last=0;\n pdb_image.reserved_2=0;\n pdb_image.x_anchor=(unsigned short) 0xffff;\n pdb_image.y_anchor=(unsigned short) 0xffff;\n pdb_image.width=(short) image->columns;\n if (image->columns % 16)\n pdb_image.width=(short) (16*(image->columns/16+1));\n pdb_image.height=(short) image->rows;\n packets=((bits_per_pixel*image->columns+7)/8);\n runlength=(unsigned char *) AcquireQuantumMemory(4UL*packets,\n image->rows*sizeof(*runlength));\n if (runlength == (unsigned char *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n buffer=(unsigned char *) AcquireQuantumMemory(2*256,sizeof(*buffer));\n if (buffer == (unsigned char *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n packet_size=(size_t) (image->depth > 8 ? 2: 1);\n scanline=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*\n sizeof(*scanline));\n if (scanline == (unsigned char *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n (void) TransformImageColorspace(image,sRGBColorspace,exception);\n /*\n Convert to GRAY raster scanline.\n */\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n bits=8/(int) bits_per_pixel-1; /* start at most significant bits */\n literal=0;\n repeat=0;\n q=runlength;\n buffer[0]=0x00;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n (void) ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n GrayQuantum,scanline,exception);\n for (x=0; x < (ssize_t) pdb_image.width; x++)\n {\n if (x < (ssize_t) image->columns)\n buffer[literal+repeat]|=(0xff-scanline[x*packet_size]) >>\n (8-bits_per_pixel) << bits*bits_per_pixel;\n bits--;\n if (bits < 0)\n {\n if (((literal+repeat) > 0) &&\n (buffer[literal+repeat] == buffer[literal+repeat-1]))\n {\n if (repeat == 0)\n {\n literal--;\n repeat++;\n }\n repeat++;\n if (0x7f < repeat)\n {\n q=EncodeRLE(q,buffer,literal,repeat);\n literal=0;\n repeat=0;\n }\n }\n else\n {\n if (repeat >= 2)\n literal+=repeat;\n else\n {\n q=EncodeRLE(q,buffer,literal,repeat);\n buffer[0]=buffer[literal+repeat];\n literal=0;\n }\n literal++;\n repeat=0;\n if (0x7f < literal)\n {\n q=EncodeRLE(q,buffer,(literal < 0x80 ? literal : 0x80),0);\n (void) CopyMagickMemory(buffer,buffer+literal+repeat,0x80);\n literal-=0x80;\n }\n }\n bits=8/(int) bits_per_pixel-1;\n buffer[literal+repeat]=0x00;\n }\n }\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n q=EncodeRLE(q,buffer,literal,repeat);\n scanline=(unsigned char *) RelinquishMagickMemory(scanline);\n buffer=(unsigned char *) RelinquishMagickMemory(buffer);\n quantum_info=DestroyQuantumInfo(quantum_info);\n /*\n Write the Image record header.\n */\n (void) WriteBlobMSBLong(image,(unsigned int)\n (TellBlob(image)+8*pdb_info.number_records));\n (void) WriteBlobByte(image,0x40);\n (void) WriteBlobByte(image,0x6f);\n (void) WriteBlobByte(image,0x80);\n (void) WriteBlobByte(image,0);\n if (pdb_info.number_records > 1)\n {\n /*\n Write the comment record header.\n */\n (void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8+58+q-\n runlength));\n (void) WriteBlobByte(image,0x40);\n (void) WriteBlobByte(image,0x6f);\n (void) WriteBlobByte(image,0x80);\n (void) WriteBlobByte(image,1);\n }\n /*\n Write the Image data.\n */\n (void) WriteBlob(image,sizeof(pdb_image.name),(unsigned char *)\n pdb_image.name);\n (void) WriteBlobByte(image,(unsigned char) pdb_image.version);\n (void) WriteBlobByte(image,pdb_image.type);\n (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_1);\n (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.note);\n (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.x_last);\n (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.y_last);\n (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_2);\n (void) WriteBlobMSBShort(image,pdb_image.x_anchor);\n (void) WriteBlobMSBShort(image,pdb_image.y_anchor);\n (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.width);\n (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.height);\n (void) WriteBlob(image,(size_t) (q-runlength),runlength);\n runlength=(unsigned char *) RelinquishMagickMemory(runlength);\n if (pdb_info.number_records > 1)\n (void) WriteBlobString(image,comment);\n (void) CloseBlob(image);\n return(MagickTrue);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/121'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ha_myisam::repair(THD *thd, MI_CHECK ¶m, bool do_optimize)\n{\n int error=0;\n uint local_testflag=param.testflag;\n bool optimize_done= !do_optimize, statistics_done=0;\n const char *old_proc_info=thd->proc_info;\n char fixed_name[FN_REFLEN];\n MYISAM_SHARE* share = file->s;\n ha_rows rows= file->state->records;\n DBUG_ENTER(\"ha_myisam::repair\");\n\n param.db_name= table->s->db.str;\n param.table_name= table->alias;\n param.using_global_keycache = 1;\n param.thd= thd;\n param.tmpdir= &mysql_tmpdir_list;\n param.out_flag= 0;\n strmov(fixed_name,file->filename);\n\n // Release latches since this can take a long time\n ha_release_temporary_latches(thd);\n\n // Don't lock tables if we have used LOCK TABLE\n if (! thd->locked_tables_mode &&\n mi_lock_database(file, table->s->tmp_table ? F_EXTRA_LCK : F_WRLCK))\n {\n mi_check_print_error(¶m,ER(ER_CANT_LOCK),my_errno);\n DBUG_RETURN(HA_ADMIN_FAILED);\n }\n\n if (!do_optimize ||\n ((file->state->del || share->state.split != file->state->records) &&\n (!(param.testflag & T_QUICK) ||\n\t!(share->state.changed & STATE_NOT_OPTIMIZED_KEYS))))\n {\n ulonglong key_map= ((local_testflag & T_CREATE_MISSING_KEYS) ?\n\t\t\tmi_get_mask_all_keys_active(share->base.keys) :\n\t\t\tshare->state.key_map);\n uint testflag=param.testflag;\n#ifdef HAVE_MMAP\n bool remap= test(share->file_map);\n /*\n mi_repair*() functions family use file I/O even if memory\n mapping is available.\n\n Since mixing mmap I/O and file I/O may cause various artifacts,\n memory mapping must be disabled.\n */\n if (remap)\n mi_munmap_file(file);\n#endif\n if (mi_test_if_sort_rep(file,file->state->records,key_map,0) &&\n\t(local_testflag & T_REP_BY_SORT))\n {\n local_testflag|= T_STATISTICS;\n param.testflag|= T_STATISTICS;\t\t// We get this for free\n statistics_done=1;\n if (THDVAR(thd, repair_threads)>1)\n {\n char buf[40];\n /* TODO: respect myisam_repair_threads variable */\n my_snprintf(buf, 40, \"Repair with %d threads\", my_count_bits(key_map));\n thd_proc_info(thd, buf);\n error = mi_repair_parallel(¶m, file, fixed_name,\n param.testflag & T_QUICK);\n thd_proc_info(thd, \"Repair done\"); // to reset proc_info, as\n // it was pointing to local buffer\n }\n else\n {\n thd_proc_info(thd, \"Repair by sorting\");\n error = mi_repair_by_sort(¶m, file, fixed_name,\n param.testflag & T_QUICK);\n }\n }\n else\n {\n thd_proc_info(thd, \"Repair with keycache\");\n param.testflag &= ~T_REP_BY_SORT;\n error= mi_repair(¶m, file, fixed_name,\n\t\t\tparam.testflag & T_QUICK);\n }\n#ifdef HAVE_MMAP\n if (remap)\n mi_dynmap_file(file, file->state->data_file_length);\n#endif\n param.testflag=testflag;\n optimize_done=1;\n }\n if (!error)\n {\n if ((local_testflag & T_SORT_INDEX) &&\n\t(share->state.changed & STATE_NOT_SORTED_PAGES))\n {\n optimize_done=1;\n thd_proc_info(thd, \"Sorting index\");\n error=mi_sort_index(¶m,file,fixed_name);\n }\n if (!statistics_done && (local_testflag & T_STATISTICS))\n {\n if (share->state.changed & STATE_NOT_ANALYZED)\n {\n\toptimize_done=1;\n\tthd_proc_info(thd, \"Analyzing\");\n\terror = chk_key(¶m, file);\n }\n else\n\tlocal_testflag&= ~T_STATISTICS;\t\t// Don't update statistics\n }\n }\n thd_proc_info(thd, \"Saving state\");\n if (!error)\n {\n if ((share->state.changed & STATE_CHANGED) || mi_is_crashed(file))\n {\n share->state.changed&= ~(STATE_CHANGED | STATE_CRASHED |\n\t\t\t STATE_CRASHED_ON_REPAIR);\n file->update|=HA_STATE_CHANGED | HA_STATE_ROW_CHANGED;\n }\n /*\n the following 'if', thought conceptually wrong,\n is a useful optimization nevertheless.\n */\n if (file->state != &file->s->state.state)\n file->s->state.state = *file->state;\n if (file->s->base.auto_key)\n update_auto_increment_key(¶m, file, 1);\n if (optimize_done)\n error = update_state_info(¶m, file,\n\t\t\t\tUPDATE_TIME | UPDATE_OPEN_COUNT |\n\t\t\t\t(local_testflag &\n\t\t\t\t T_STATISTICS ? UPDATE_STAT : 0));\n info(HA_STATUS_NO_LOCK | HA_STATUS_TIME | HA_STATUS_VARIABLE |\n\t HA_STATUS_CONST);\n if (rows != file->state->records && ! (param.testflag & T_VERY_SILENT))\n {\n char llbuff[22],llbuff2[22];\n mi_check_print_warning(¶m,\"Number of rows changed from %s to %s\",\n\t\t\t llstr(rows,llbuff),\n\t\t\t llstr(file->state->records,llbuff2));\n }\n }\n else\n {\n mi_mark_crashed_on_repair(file);\n file->update |= HA_STATE_CHANGED | HA_STATE_ROW_CHANGED;\n update_state_info(¶m, file, 0);\n }\n thd_proc_info(thd, old_proc_info);\n if (! thd->locked_tables_mode)\n mi_lock_database(file,F_UNLCK);\n DBUG_RETURN(error ? HA_ADMIN_FAILED :\n\t !optimize_done ? HA_ADMIN_ALREADY_DONE : HA_ADMIN_OK);\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 (errno == EAGAIN || errno == EINTR)\n return 0;\n\n return -errno;\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 return log_oom();\n }\n }\n\n if (!ucred || ucred->pid <= 0) {\n log_warning(\"Received notify message without valid credentials. Ignoring.\");\n return 0;\n }\n\n if ((size_t) n >= sizeof(buf)) {\n log_warning(\"Received notify message exceeded maximum size. Ignoring.\");\n return 0;\n }\n\n buf[n] = 0;\n\n /* Notify every unit that might be interested, but try\n * to avoid notifying the same one multiple times. */\n u1 = manager_get_unit_by_pid_cgroup(m, ucred->pid);\n if (u1) {\n manager_invoke_notify_message(m, u1, ucred->pid, buf, n, fds);\n found = true;\n }\n\n u2 = hashmap_get(m->watch_pids1, PID_TO_PTR(ucred->pid));\n if (u2 && u2 != u1) {\n manager_invoke_notify_message(m, u2, ucred->pid, buf, n, fds);\n found = true;\n }\n\n u3 = hashmap_get(m->watch_pids2, PID_TO_PTR(ucred->pid));\n if (u3 && u3 != u2 && u3 != u1) {\n manager_invoke_notify_message(m, u3, ucred->pid, buf, n, fds);\n found = true;\n }\n\n if (!found)\n log_warning(\"Cannot find unit for notify message of PID \"PID_FMT\".\", ucred->pid);\n\n if (fdset_size(fds) > 0)\n log_warning(\"Got auxiliary fds with notification message, closing all.\");\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'pid1: don't return any error in manager_dispatch_notify_fd() (#4240)\n\nIf manager_dispatch_notify_fd() fails and returns an error then the handling of\r\nservice notifications will be disabled entirely leading to a compromised system.\r\n\r\nFor example pid1 won't be able to receive the WATCHDOG messages anymore and\r\nwill kill all services supposed to send such messages.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void loadServerConfigFromString(char *config) {\n char *err = NULL;\n int linenum = 0, totlines, i;\n int slaveof_linenum = 0;\n sds *lines;\n\n lines = sdssplitlen(config,strlen(config),\"\\n\",1,&totlines);\n\n for (i = 0; i < totlines; i++) {\n sds *argv;\n int argc;\n\n linenum = i+1;\n lines[i] = sdstrim(lines[i],\" \\t\\r\\n\");\n\n /* Skip comments and blank lines */\n if (lines[i][0] == '#' || lines[i][0] == '\\0') continue;\n\n /* Split into arguments */\n argv = sdssplitargs(lines[i],&argc);\n if (argv == NULL) {\n err = \"Unbalanced quotes in configuration line\";\n goto loaderr;\n }\n\n /* Skip this line if the resulting command vector is empty. */\n if (argc == 0) {\n sdsfreesplitres(argv,argc);\n continue;\n }\n sdstolower(argv[0]);\n\n /* Execute config directives */\n if (!strcasecmp(argv[0],\"timeout\") && argc == 2) {\n server.maxidletime = atoi(argv[1]);\n if (server.maxidletime < 0) {\n err = \"Invalid timeout value\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"tcp-keepalive\") && argc == 2) {\n server.tcpkeepalive = atoi(argv[1]);\n if (server.tcpkeepalive < 0) {\n err = \"Invalid tcp-keepalive value\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"protected-mode\") && argc == 2) {\n if ((server.protected_mode = yesnotoi(argv[1])) == -1) {\n err = \"argument must be 'yes' or 'no'\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"port\") && argc == 2) {\n server.port = atoi(argv[1]);\n if (server.port < 0 || server.port > 65535) {\n err = \"Invalid port\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"tcp-backlog\") && argc == 2) {\n server.tcp_backlog = atoi(argv[1]);\n if (server.tcp_backlog < 0) {\n err = \"Invalid backlog value\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"bind\") && argc >= 2) {\n int j, addresses = argc-1;\n\n if (addresses > CONFIG_BINDADDR_MAX) {\n err = \"Too many bind addresses specified\"; goto loaderr;\n }\n for (j = 0; j < addresses; j++)\n server.bindaddr[j] = zstrdup(argv[j+1]);\n server.bindaddr_count = addresses;\n } else if (!strcasecmp(argv[0],\"unixsocket\") && argc == 2) {\n server.unixsocket = zstrdup(argv[1]);\n } else if (!strcasecmp(argv[0],\"unixsocketperm\") && argc == 2) {\n errno = 0;\n server.unixsocketperm = (mode_t)strtol(argv[1], NULL, 8);\n if (errno || server.unixsocketperm > 0777) {\n err = \"Invalid socket file permissions\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"save\")) {\n if (argc == 3) {\n int seconds = atoi(argv[1]);\n int changes = atoi(argv[2]);\n if (seconds < 1 || changes < 0) {\n err = \"Invalid save parameters\"; goto loaderr;\n }\n appendServerSaveParams(seconds,changes);\n } else if (argc == 2 && !strcasecmp(argv[1],\"\")) {\n resetServerSaveParams();\n }\n } else if (!strcasecmp(argv[0],\"dir\") && argc == 2) {\n if (chdir(argv[1]) == -1) {\n serverLog(LL_WARNING,\"Can't chdir to '%s': %s\",\n argv[1], strerror(errno));\n exit(1);\n }\n } else if (!strcasecmp(argv[0],\"loglevel\") && argc == 2) {\n server.verbosity = configEnumGetValue(loglevel_enum,argv[1]);\n if (server.verbosity == INT_MIN) {\n err = \"Invalid log level. \"\n \"Must be one of debug, verbose, notice, warning\";\n goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"logfile\") && argc == 2) {\n FILE *logfp;\n\n zfree(server.logfile);\n server.logfile = zstrdup(argv[1]);\n if (server.logfile[0] != '\\0') {\n /* Test if we are able to open the file. The server will not\n * be able to abort just for this problem later... */\n logfp = fopen(server.logfile,\"a\");\n if (logfp == NULL) {\n err = sdscatprintf(sdsempty(),\n \"Can't open the log file: %s\", strerror(errno));\n goto loaderr;\n }\n fclose(logfp);\n }\n } else if (!strcasecmp(argv[0],\"syslog-enabled\") && argc == 2) {\n if ((server.syslog_enabled = yesnotoi(argv[1])) == -1) {\n err = \"argument must be 'yes' or 'no'\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"syslog-ident\") && argc == 2) {\n if (server.syslog_ident) zfree(server.syslog_ident);\n server.syslog_ident = zstrdup(argv[1]);\n } else if (!strcasecmp(argv[0],\"syslog-facility\") && argc == 2) {\n server.syslog_facility =\n configEnumGetValue(syslog_facility_enum,argv[1]);\n if (server.syslog_facility == INT_MIN) {\n err = \"Invalid log facility. Must be one of USER or between LOCAL0-LOCAL7\";\n goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"databases\") && argc == 2) {\n server.dbnum = atoi(argv[1]);\n if (server.dbnum < 1) {\n err = \"Invalid number of databases\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"include\") && argc == 2) {\n loadServerConfig(argv[1],NULL);\n } else if (!strcasecmp(argv[0],\"maxclients\") && argc == 2) {\n server.maxclients = atoi(argv[1]);\n if (server.maxclients < 1) {\n err = \"Invalid max clients limit\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"maxmemory\") && argc == 2) {\n server.maxmemory = memtoll(argv[1],NULL);\n } else if (!strcasecmp(argv[0],\"maxmemory-policy\") && argc == 2) {\n server.maxmemory_policy =\n configEnumGetValue(maxmemory_policy_enum,argv[1]);\n if (server.maxmemory_policy == INT_MIN) {\n err = \"Invalid maxmemory policy\";\n goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"maxmemory-samples\") && argc == 2) {\n server.maxmemory_samples = atoi(argv[1]);\n if (server.maxmemory_samples <= 0) {\n err = \"maxmemory-samples must be 1 or greater\";\n goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"lfu-log-factor\") && argc == 2) {\n server.lfu_log_factor = atoi(argv[1]);\n if (server.maxmemory_samples < 0) {\n err = \"lfu-log-factor must be 0 or greater\";\n goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"lfu-decay-time\") && argc == 2) {\n server.lfu_decay_time = atoi(argv[1]);\n if (server.maxmemory_samples < 1) {\n err = \"lfu-decay-time must be 0 or greater\";\n goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"slaveof\") && argc == 3) {\n slaveof_linenum = linenum;\n server.masterhost = sdsnew(argv[1]);\n server.masterport = atoi(argv[2]);\n server.repl_state = REPL_STATE_CONNECT;\n } else if (!strcasecmp(argv[0],\"repl-ping-slave-period\") && argc == 2) {\n server.repl_ping_slave_period = atoi(argv[1]);\n if (server.repl_ping_slave_period <= 0) {\n err = \"repl-ping-slave-period must be 1 or greater\";\n goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"repl-timeout\") && argc == 2) {\n server.repl_timeout = atoi(argv[1]);\n if (server.repl_timeout <= 0) {\n err = \"repl-timeout must be 1 or greater\";\n goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"repl-disable-tcp-nodelay\") && argc==2) {\n if ((server.repl_disable_tcp_nodelay = yesnotoi(argv[1])) == -1) {\n err = \"argument must be 'yes' or 'no'\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"repl-diskless-sync\") && argc==2) {\n if ((server.repl_diskless_sync = yesnotoi(argv[1])) == -1) {\n err = \"argument must be 'yes' or 'no'\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"repl-diskless-sync-delay\") && argc==2) {\n server.repl_diskless_sync_delay = atoi(argv[1]);\n if (server.repl_diskless_sync_delay < 0) {\n err = \"repl-diskless-sync-delay can't be negative\";\n goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"repl-backlog-size\") && argc == 2) {\n long long size = memtoll(argv[1],NULL);\n if (size <= 0) {\n err = \"repl-backlog-size must be 1 or greater.\";\n goto loaderr;\n }\n resizeReplicationBacklog(size);\n } else if (!strcasecmp(argv[0],\"repl-backlog-ttl\") && argc == 2) {\n server.repl_backlog_time_limit = atoi(argv[1]);\n if (server.repl_backlog_time_limit < 0) {\n err = \"repl-backlog-ttl can't be negative \";\n goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"masterauth\") && argc == 2) {\n zfree(server.masterauth);\n server.masterauth = zstrdup(argv[1]);\n } else if (!strcasecmp(argv[0],\"slave-serve-stale-data\") && argc == 2) {\n if ((server.repl_serve_stale_data = yesnotoi(argv[1])) == -1) {\n err = \"argument must be 'yes' or 'no'\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"slave-read-only\") && argc == 2) {\n if ((server.repl_slave_ro = yesnotoi(argv[1])) == -1) {\n err = \"argument must be 'yes' or 'no'\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"rdbcompression\") && argc == 2) {\n if ((server.rdb_compression = yesnotoi(argv[1])) == -1) {\n err = \"argument must be 'yes' or 'no'\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"rdbchecksum\") && argc == 2) {\n if ((server.rdb_checksum = yesnotoi(argv[1])) == -1) {\n err = \"argument must be 'yes' or 'no'\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"activerehashing\") && argc == 2) {\n if ((server.activerehashing = yesnotoi(argv[1])) == -1) {\n err = \"argument must be 'yes' or 'no'\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"lazyfree-lazy-eviction\") && argc == 2) {\n if ((server.lazyfree_lazy_eviction = yesnotoi(argv[1])) == -1) {\n err = \"argument must be 'yes' or 'no'\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"lazyfree-lazy-expire\") && argc == 2) {\n if ((server.lazyfree_lazy_expire = yesnotoi(argv[1])) == -1) {\n err = \"argument must be 'yes' or 'no'\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"lazyfree-lazy-server-del\") && argc == 2){\n if ((server.lazyfree_lazy_server_del = yesnotoi(argv[1])) == -1) {\n err = \"argument must be 'yes' or 'no'\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"slave-lazy-flush\") && argc == 2) {\n if ((server.repl_slave_lazy_flush = yesnotoi(argv[1])) == -1) {\n err = \"argument must be 'yes' or 'no'\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"daemonize\") && argc == 2) {\n if ((server.daemonize = yesnotoi(argv[1])) == -1) {\n err = \"argument must be 'yes' or 'no'\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"hz\") && argc == 2) {\n server.hz = atoi(argv[1]);\n if (server.hz < CONFIG_MIN_HZ) server.hz = CONFIG_MIN_HZ;\n if (server.hz > CONFIG_MAX_HZ) server.hz = CONFIG_MAX_HZ;\n } else if (!strcasecmp(argv[0],\"appendonly\") && argc == 2) {\n int yes;\n\n if ((yes = yesnotoi(argv[1])) == -1) {\n err = \"argument must be 'yes' or 'no'\"; goto loaderr;\n }\n server.aof_state = yes ? AOF_ON : AOF_OFF;\n } else if (!strcasecmp(argv[0],\"appendfilename\") && argc == 2) {\n if (!pathIsBaseName(argv[1])) {\n err = \"appendfilename can't be a path, just a filename\";\n goto loaderr;\n }\n zfree(server.aof_filename);\n server.aof_filename = zstrdup(argv[1]);\n } else if (!strcasecmp(argv[0],\"no-appendfsync-on-rewrite\")\n && argc == 2) {\n if ((server.aof_no_fsync_on_rewrite= yesnotoi(argv[1])) == -1) {\n err = \"argument must be 'yes' or 'no'\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"appendfsync\") && argc == 2) {\n server.aof_fsync = configEnumGetValue(aof_fsync_enum,argv[1]);\n if (server.aof_fsync == INT_MIN) {\n err = \"argument must be 'no', 'always' or 'everysec'\";\n goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"auto-aof-rewrite-percentage\") &&\n argc == 2)\n {\n server.aof_rewrite_perc = atoi(argv[1]);\n if (server.aof_rewrite_perc < 0) {\n err = \"Invalid negative percentage for AOF auto rewrite\";\n goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"auto-aof-rewrite-min-size\") &&\n argc == 2)\n {\n server.aof_rewrite_min_size = memtoll(argv[1],NULL);\n } else if (!strcasecmp(argv[0],\"aof-rewrite-incremental-fsync\") &&\n argc == 2)\n {\n if ((server.aof_rewrite_incremental_fsync =\n yesnotoi(argv[1])) == -1) {\n err = \"argument must be 'yes' or 'no'\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"aof-load-truncated\") && argc == 2) {\n if ((server.aof_load_truncated = yesnotoi(argv[1])) == -1) {\n err = \"argument must be 'yes' or 'no'\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"aof-use-rdb-preamble\") && argc == 2) {\n if ((server.aof_use_rdb_preamble = yesnotoi(argv[1])) == -1) {\n err = \"argument must be 'yes' or 'no'\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"requirepass\") && argc == 2) {\n if (strlen(argv[1]) > CONFIG_AUTHPASS_MAX_LEN) {\n err = \"Password is longer than CONFIG_AUTHPASS_MAX_LEN\";\n goto loaderr;\n }\n server.requirepass = zstrdup(argv[1]);\n } else if (!strcasecmp(argv[0],\"pidfile\") && argc == 2) {\n zfree(server.pidfile);\n server.pidfile = zstrdup(argv[1]);\n } else if (!strcasecmp(argv[0],\"dbfilename\") && argc == 2) {\n if (!pathIsBaseName(argv[1])) {\n err = \"dbfilename can't be a path, just a filename\";\n goto loaderr;\n }\n zfree(server.rdb_filename);\n server.rdb_filename = zstrdup(argv[1]);\n } else if (!strcasecmp(argv[0],\"hash-max-ziplist-entries\") && argc == 2) {\n server.hash_max_ziplist_entries = memtoll(argv[1], NULL);\n } else if (!strcasecmp(argv[0],\"hash-max-ziplist-value\") && argc == 2) {\n server.hash_max_ziplist_value = memtoll(argv[1], NULL);\n } else if (!strcasecmp(argv[0],\"list-max-ziplist-entries\") && argc == 2){\n /* DEAD OPTION */\n } else if (!strcasecmp(argv[0],\"list-max-ziplist-value\") && argc == 2) {\n /* DEAD OPTION */\n } else if (!strcasecmp(argv[0],\"list-max-ziplist-size\") && argc == 2) {\n server.list_max_ziplist_size = atoi(argv[1]);\n } else if (!strcasecmp(argv[0],\"list-compress-depth\") && argc == 2) {\n server.list_compress_depth = atoi(argv[1]);\n } else if (!strcasecmp(argv[0],\"set-max-intset-entries\") && argc == 2) {\n server.set_max_intset_entries = memtoll(argv[1], NULL);\n } else if (!strcasecmp(argv[0],\"zset-max-ziplist-entries\") && argc == 2) {\n server.zset_max_ziplist_entries = memtoll(argv[1], NULL);\n } else if (!strcasecmp(argv[0],\"zset-max-ziplist-value\") && argc == 2) {\n server.zset_max_ziplist_value = memtoll(argv[1], NULL);\n } else if (!strcasecmp(argv[0],\"hll-sparse-max-bytes\") && argc == 2) {\n server.hll_sparse_max_bytes = memtoll(argv[1], NULL);\n } else if (!strcasecmp(argv[0],\"rename-command\") && argc == 3) {\n struct redisCommand *cmd = lookupCommand(argv[1]);\n int retval;\n\n if (!cmd) {\n err = \"No such command in rename-command\";\n goto loaderr;\n }\n\n /* If the target command name is the empty string we just\n * remove it from the command table. */\n retval = dictDelete(server.commands, argv[1]);\n serverAssert(retval == DICT_OK);\n\n /* Otherwise we re-add the command under a different name. */\n if (sdslen(argv[2]) != 0) {\n sds copy = sdsdup(argv[2]);\n\n retval = dictAdd(server.commands, copy, cmd);\n if (retval != DICT_OK) {\n sdsfree(copy);\n err = \"Target command name already exists\"; goto loaderr;\n }\n }\n } else if (!strcasecmp(argv[0],\"cluster-enabled\") && argc == 2) {\n if ((server.cluster_enabled = yesnotoi(argv[1])) == -1) {\n err = \"argument must be 'yes' or 'no'\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"cluster-config-file\") && argc == 2) {\n zfree(server.cluster_configfile);\n server.cluster_configfile = zstrdup(argv[1]);\n } else if (!strcasecmp(argv[0],\"cluster-announce-ip\") && argc == 2) {\n zfree(server.cluster_announce_ip);\n server.cluster_announce_ip = zstrdup(argv[1]);\n } else if (!strcasecmp(argv[0],\"cluster-announce-port\") && argc == 2) {\n server.cluster_announce_port = atoi(argv[1]);\n if (server.cluster_announce_port < 0 ||\n server.cluster_announce_port > 65535)\n {\n err = \"Invalid port\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"cluster-announce-bus-port\") &&\n argc == 2)\n {\n server.cluster_announce_bus_port = atoi(argv[1]);\n if (server.cluster_announce_bus_port < 0 ||\n server.cluster_announce_bus_port > 65535)\n {\n err = \"Invalid port\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"cluster-require-full-coverage\") &&\n argc == 2)\n {\n if ((server.cluster_require_full_coverage = yesnotoi(argv[1])) == -1)\n {\n err = \"argument must be 'yes' or 'no'\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"cluster-node-timeout\") && argc == 2) {\n server.cluster_node_timeout = strtoll(argv[1],NULL,10);\n if (server.cluster_node_timeout <= 0) {\n err = \"cluster node timeout must be 1 or greater\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"cluster-migration-barrier\")\n && argc == 2)\n {\n server.cluster_migration_barrier = atoi(argv[1]);\n if (server.cluster_migration_barrier < 0) {\n err = \"cluster migration barrier must zero or positive\";\n goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"cluster-slave-validity-factor\")\n && argc == 2)\n {\n server.cluster_slave_validity_factor = atoi(argv[1]);\n if (server.cluster_slave_validity_factor < 0) {\n err = \"cluster slave validity factor must be zero or positive\";\n goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"lua-time-limit\") && argc == 2) {\n server.lua_time_limit = strtoll(argv[1],NULL,10);\n } else if (!strcasecmp(argv[0],\"slowlog-log-slower-than\") &&\n argc == 2)\n {\n server.slowlog_log_slower_than = strtoll(argv[1],NULL,10);\n } else if (!strcasecmp(argv[0],\"latency-monitor-threshold\") &&\n argc == 2)\n {\n server.latency_monitor_threshold = strtoll(argv[1],NULL,10);\n if (server.latency_monitor_threshold < 0) {\n err = \"The latency threshold can't be negative\";\n goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"slowlog-max-len\") && argc == 2) {\n server.slowlog_max_len = strtoll(argv[1],NULL,10);\n } else if (!strcasecmp(argv[0],\"client-output-buffer-limit\") &&\n argc == 5)\n {\n int class = getClientTypeByName(argv[1]);\n unsigned long long hard, soft;\n int soft_seconds;\n\n if (class == -1) {\n err = \"Unrecognized client limit class\";\n goto loaderr;\n }\n hard = memtoll(argv[2],NULL);\n soft = memtoll(argv[3],NULL);\n soft_seconds = atoi(argv[4]);\n if (soft_seconds < 0) {\n err = \"Negative number of seconds in soft limit is invalid\";\n goto loaderr;\n }\n server.client_obuf_limits[class].hard_limit_bytes = hard;\n server.client_obuf_limits[class].soft_limit_bytes = soft;\n server.client_obuf_limits[class].soft_limit_seconds = soft_seconds;\n } else if (!strcasecmp(argv[0],\"stop-writes-on-bgsave-error\") &&\n argc == 2) {\n if ((server.stop_writes_on_bgsave_err = yesnotoi(argv[1])) == -1) {\n err = \"argument must be 'yes' or 'no'\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"slave-priority\") && argc == 2) {\n server.slave_priority = atoi(argv[1]);\n } else if (!strcasecmp(argv[0],\"slave-announce-ip\") && argc == 2) {\n zfree(server.slave_announce_ip);\n server.slave_announce_ip = zstrdup(argv[1]);\n } else if (!strcasecmp(argv[0],\"slave-announce-port\") && argc == 2) {\n server.slave_announce_port = atoi(argv[1]);\n if (server.slave_announce_port < 0 ||\n server.slave_announce_port > 65535)\n {\n err = \"Invalid port\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"min-slaves-to-write\") && argc == 2) {\n server.repl_min_slaves_to_write = atoi(argv[1]);\n if (server.repl_min_slaves_to_write < 0) {\n err = \"Invalid value for min-slaves-to-write.\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"min-slaves-max-lag\") && argc == 2) {\n server.repl_min_slaves_max_lag = atoi(argv[1]);\n if (server.repl_min_slaves_max_lag < 0) {\n err = \"Invalid value for min-slaves-max-lag.\"; goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"notify-keyspace-events\") && argc == 2) {\n int flags = keyspaceEventsStringToFlags(argv[1]);\n\n if (flags == -1) {\n err = \"Invalid event class character. Use 'g$lshzxeA'.\";\n goto loaderr;\n }\n server.notify_keyspace_events = flags;\n } else if (!strcasecmp(argv[0],\"supervised\") && argc == 2) {\n server.supervised_mode =\n configEnumGetValue(supervised_mode_enum,argv[1]);\n\n if (server.supervised_mode == INT_MIN) {\n err = \"Invalid option for 'supervised'. \"\n \"Allowed values: 'upstart', 'systemd', 'auto', or 'no'\";\n goto loaderr;\n }\n } else if (!strcasecmp(argv[0],\"loadmodule\") && argc >= 2) {\n queueLoadModule(argv[1],&argv[2],argc-2);\n } else if (!strcasecmp(argv[0],\"sentinel\")) {\n /* argc == 1 is handled by main() as we need to enter the sentinel\n * mode ASAP. */\n if (argc != 1) {\n if (!server.sentinel_mode) {\n err = \"sentinel directive while not in sentinel mode\";\n goto loaderr;\n }\n err = sentinelHandleConfiguration(argv+1,argc-1);\n if (err) goto loaderr;\n }\n } else {\n err = \"Bad directive or wrong number of arguments\"; goto loaderr;\n }\n sdsfreesplitres(argv,argc);\n }\n\n /* Sanity checks. */\n if (server.cluster_enabled && server.masterhost) {\n linenum = slaveof_linenum;\n i = linenum-1;\n err = \"slaveof directive not allowed in cluster mode\";\n goto loaderr;\n }\n\n sdsfreesplitres(lines,totlines);\n return;\n\nloaderr:\n fprintf(stderr, \"\\n*** FATAL CONFIG FILE ERROR ***\\n\");\n fprintf(stderr, \"Reading the configuration file, at line %d\\n\", linenum);\n fprintf(stderr, \">>> '%s'\\n\", lines[i]);\n fprintf(stderr, \"%s\\n\", err);\n exit(1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Security: CONFIG SET client-output-buffer-limit overflow fixed.\n\nThis commit fixes a vunlerability reported by Cory Duplantis\nof Cisco Talos, see TALOS-2016-0206 for reference.\n\nCONFIG SET client-output-buffer-limit accepts as client class \"master\"\nwhich is actually only used to implement CLIENT KILL. The \"master\" class\nhas ID 3. What happens is that the global structure:\n\n server.client_obuf_limits[class]\n\nIs accessed with class = 3. However it is a 3 elements array, so writing\nthe 4th element means to write up to 24 bytes of memory *after* the end\nof the array, since the structure is defined as:\n\n typedef struct clientBufferLimitsConfig {\n unsigned long long hard_limit_bytes;\n unsigned long long soft_limit_bytes;\n time_t soft_limit_seconds;\n } clientBufferLimitsConfig;\n\nEVALUATION OF IMPACT:\n\nChecking what's past the boundaries of the array in the global\n'server' structure, we find AOF state fields:\n\n clientBufferLimitsConfig client_obuf_limits[CLIENT_TYPE_OBUF_COUNT];\n /* AOF persistence */\n int aof_state; /* AOF_(ON|OFF|WAIT_REWRITE) */\n int aof_fsync; /* Kind of fsync() policy */\n char *aof_filename; /* Name of the AOF file */\n int aof_no_fsync_on_rewrite; /* Don't fsync if a rewrite is in prog. */\n int aof_rewrite_perc; /* Rewrite AOF if % growth is > M and... */\n off_t aof_rewrite_min_size; /* the AOF file is at least N bytes. */\n off_t aof_rewrite_base_size; /* AOF size on latest startup or rewrite. */\n off_t aof_current_size; /* AOF current size. */\n\nWriting to most of these fields should be harmless and only cause problems in\nRedis persistence that should not escalate to security problems.\nHowever unfortunately writing to \"aof_filename\" could be potentially a\nsecurity issue depending on the access pattern.\n\nSearching for \"aof.filename\" accesses in the source code returns many different\nusages of the field, including using it as input for open(), logging to the\nRedis log file or syslog, and calling the rename() syscall.\n\nIt looks possible that attacks could lead at least to informations\ndisclosure of the state and data inside Redis. However note that the\nattacker must already have access to the server. But, worse than that,\nit looks possible that being able to change the AOF filename can be used\nto mount more powerful attacks: like overwriting random files with AOF\ndata (easily a potential security issue as demostrated here:\nhttp://antirez.com/news/96), or even more subtle attacks where the\nAOF filename is changed to a path were a malicious AOF file is loaded\nin order to exploit other potential issues when the AOF parser is fed\nwith untrusted input (no known issue known currently).\n\nThe fix checks the places where the 'master' class is specifiedf in\norder to access configuration data structures, and return an error in\nthis cases.\n\nWHO IS AT RISK?\n\nThe \"master\" client class was introduced in Redis in Jul 28 2015.\nEvery Redis instance released past this date is not vulnerable\nwhile all the releases after this date are. Notably:\n\n Redis 3.0.x is NOT vunlerable.\n Redis 3.2.x IS vulnerable.\n Redis unstable is vulnerable.\n\nIn order for the instance to be at risk, at least one of the following\nconditions must be true:\n\n 1. The attacker can access Redis remotely and is able to send\n the CONFIG SET command (often banned in managed Redis instances).\n\n 2. The attacker is able to control the \"redis.conf\" file and\n can wait or trigger a server restart.\n\nThe problem was fixed 26th September 2016 in all the releases 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 struct page *follow_page_pte(struct vm_area_struct *vma,\n\t\tunsigned long address, pmd_t *pmd, unsigned int flags)\n{\n\tstruct mm_struct *mm = vma->vm_mm;\n\tstruct dev_pagemap *pgmap = NULL;\n\tstruct page *page;\n\tspinlock_t *ptl;\n\tpte_t *ptep, pte;\n\nretry:\n\tif (unlikely(pmd_bad(*pmd)))\n\t\treturn no_page_table(vma, flags);\n\n\tptep = pte_offset_map_lock(mm, pmd, address, &ptl);\n\tpte = *ptep;\n\tif (!pte_present(pte)) {\n\t\tswp_entry_t entry;\n\t\t/*\n\t\t * KSM's break_ksm() relies upon recognizing a ksm page\n\t\t * even while it is being migrated, so for that case we\n\t\t * need migration_entry_wait().\n\t\t */\n\t\tif (likely(!(flags & FOLL_MIGRATION)))\n\t\t\tgoto no_page;\n\t\tif (pte_none(pte))\n\t\t\tgoto no_page;\n\t\tentry = pte_to_swp_entry(pte);\n\t\tif (!is_migration_entry(entry))\n\t\t\tgoto no_page;\n\t\tpte_unmap_unlock(ptep, ptl);\n\t\tmigration_entry_wait(mm, pmd, address);\n\t\tgoto retry;\n\t}\n\tif ((flags & FOLL_NUMA) && pte_protnone(pte))\n\t\tgoto no_page;\n\tif ((flags & FOLL_WRITE) && !pte_write(pte)) {\n\t\tpte_unmap_unlock(ptep, ptl);\n\t\treturn NULL;\n\t}\n\n\tpage = vm_normal_page(vma, address, pte);\n\tif (!page && pte_devmap(pte) && (flags & FOLL_GET)) {\n\t\t/*\n\t\t * Only return device mapping pages in the FOLL_GET case since\n\t\t * they are only valid while holding the pgmap reference.\n\t\t */\n\t\tpgmap = get_dev_pagemap(pte_pfn(pte), NULL);\n\t\tif (pgmap)\n\t\t\tpage = pte_page(pte);\n\t\telse\n\t\t\tgoto no_page;\n\t} else if (unlikely(!page)) {\n\t\tif (flags & FOLL_DUMP) {\n\t\t\t/* Avoid special (like zero) pages in core dumps */\n\t\t\tpage = ERR_PTR(-EFAULT);\n\t\t\tgoto out;\n\t\t}\n\n\t\tif (is_zero_pfn(pte_pfn(pte))) {\n\t\t\tpage = pte_page(pte);\n\t\t} else {\n\t\t\tint ret;\n\n\t\t\tret = follow_pfn_pte(vma, address, ptep, flags);\n\t\t\tpage = ERR_PTR(ret);\n\t\t\tgoto out;\n\t\t}\n\t}\n\n\tif (flags & FOLL_SPLIT && PageTransCompound(page)) {\n\t\tint ret;\n\t\tget_page(page);\n\t\tpte_unmap_unlock(ptep, ptl);\n\t\tlock_page(page);\n\t\tret = split_huge_page(page);\n\t\tunlock_page(page);\n\t\tput_page(page);\n\t\tif (ret)\n\t\t\treturn ERR_PTR(ret);\n\t\tgoto retry;\n\t}\n\n\tif (flags & FOLL_GET) {\n\t\tget_page(page);\n\n\t\t/* drop the pgmap reference now that we hold the page */\n\t\tif (pgmap) {\n\t\t\tput_dev_pagemap(pgmap);\n\t\t\tpgmap = NULL;\n\t\t}\n\t}\n\tif (flags & FOLL_TOUCH) {\n\t\tif ((flags & FOLL_WRITE) &&\n\t\t !pte_dirty(pte) && !PageDirty(page))\n\t\t\tset_page_dirty(page);\n\t\t/*\n\t\t * pte_mkyoung() would be more correct here, but atomic care\n\t\t * is needed to avoid losing the dirty bit: it is easier to use\n\t\t * mark_page_accessed().\n\t\t */\n\t\tmark_page_accessed(page);\n\t}\n\tif ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {\n\t\t/* Do not mlock pte-mapped THP */\n\t\tif (PageTransCompound(page))\n\t\t\tgoto out;\n\n\t\t/*\n\t\t * The preliminary mapping check is mainly to avoid the\n\t\t * pointless overhead of lock_page on the ZERO_PAGE\n\t\t * which might bounce very badly if there is contention.\n\t\t *\n\t\t * If the page is already locked, we don't need to\n\t\t * handle it now - vmscan will handle it later if and\n\t\t * when it attempts to reclaim the page.\n\t\t */\n\t\tif (page->mapping && trylock_page(page)) {\n\t\t\tlru_add_drain(); /* push cached pages to LRU */\n\t\t\t/*\n\t\t\t * Because we lock page here, and migration is\n\t\t\t * blocked by the pte's page reference, and we\n\t\t\t * know the page is still mapped, we don't even\n\t\t\t * need to check for file-cache page truncation.\n\t\t\t */\n\t\t\tmlock_vma_page(page);\n\t\t\tunlock_page(page);\n\t\t}\n\t}\nout:\n\tpte_unmap_unlock(ptep, ptl);\n\treturn page;\nno_page:\n\tpte_unmap_unlock(ptep, ptl);\n\tif (!pte_none(pte))\n\t\treturn NULL;\n\treturn no_page_table(vma, flags);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'mm: remove gup_flags FOLL_WRITE games from __get_user_pages()\n\nThis is an ancient bug that was actually attempted to be fixed once\n(badly) by me eleven years ago in commit 4ceb5db9757a (\"Fix\nget_user_pages() race for write access\") but that was then undone due to\nproblems on s390 by commit f33ea7f404e5 (\"fix get_user_pages bug\").\n\nIn the meantime, the s390 situation has long been fixed, and we can now\nfix it by checking the pte_dirty() bit properly (and do it better). The\ns390 dirty bit was implemented in abf09bed3cce (\"s390/mm: implement\nsoftware dirty bits\") which made it into v3.9. Earlier kernels will\nhave to look at the page state itself.\n\nAlso, the VM has become more scalable, and what used a purely\ntheoretical race back then has become easier to trigger.\n\nTo fix it, we introduce a new internal FOLL_COW flag to mark the \"yes,\nwe already did a COW\" rather than play racy games with FOLL_WRITE that\nis very fundamental, and then use the pte dirty flag to validate that\nthe FOLL_COW flag is still valid.\n\nReported-and-tested-by: Phil \"not Paul\" Oester \nAcked-by: Hugh Dickins \nReviewed-by: Michal Hocko \nCc: Andy Lutomirski \nCc: Kees Cook \nCc: Oleg Nesterov \nCc: Willy Tarreau \nCc: Nick Piggin \nCc: Greg Thelen \nCc: stable@vger.kernel.org\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xfs_iflush_abort(\n\txfs_inode_t\t\t*ip,\n\tbool\t\t\tstale)\n{\n\txfs_inode_log_item_t\t*iip = ip->i_itemp;\n\n\tif (iip) {\n\t\tif (iip->ili_item.li_flags & XFS_LI_IN_AIL) {\n\t\t\txfs_trans_ail_remove(&iip->ili_item,\n\t\t\t\t\t stale ? SHUTDOWN_LOG_IO_ERROR :\n\t\t\t\t\t\t SHUTDOWN_CORRUPT_INCORE);\n\t\t}\n\t\tiip->ili_logged = 0;\n\t\t/*\n\t\t * Clear the ili_last_fields bits now that we know that the\n\t\t * data corresponding to them is safely on disk.\n\t\t */\n\t\tiip->ili_last_fields = 0;\n\t\t/*\n\t\t * Clear the inode logging fields so no more flushes are\n\t\t * attempted.\n\t\t */\n\t\tiip->ili_fields = 0;\n\t}\n\t/*\n\t * Release the inode's flush lock since we're done with it.\n\t */\n\txfs_ifunlock(ip);\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: jas_image_t *bmp_decode(jas_stream_t *in, char *optstr)\n{\n\tjas_image_t *image;\n\tbmp_hdr_t hdr;\n\tbmp_info_t *info;\n\tuint_fast16_t cmptno;\n\tjas_image_cmptparm_t cmptparms[3];\n\tjas_image_cmptparm_t *cmptparm;\n\tuint_fast16_t numcmpts;\n\tlong n;\n\n\tif (optstr) {\n\t\tjas_eprintf(\"warning: ignoring BMP decoder options\\n\");\n\t}\n\n\tjas_eprintf(\n\t \"THE BMP FORMAT IS NOT FULLY SUPPORTED!\\n\"\n\t \"THAT IS, THE JASPER SOFTWARE CANNOT DECODE ALL TYPES OF BMP DATA.\\n\"\n\t \"IF YOU HAVE ANY PROBLEMS, PLEASE TRY CONVERTING YOUR IMAGE DATA\\n\"\n\t \"TO THE PNM FORMAT, AND USING THIS FORMAT INSTEAD.\\n\"\n\t );\n\n\t/* Read the bitmap header. */\n\tif (bmp_gethdr(in, &hdr)) {\n\t\tjas_eprintf(\"cannot get header\\n\");\n\t\treturn 0;\n\t}\n\n\t/* Read the bitmap information. */\n\tif (!(info = bmp_getinfo(in))) {\n\t\tjas_eprintf(\"cannot get info\\n\");\n\t\treturn 0;\n\t}\n\n\t/* Ensure that we support this type of BMP file. */\n\tif (!bmp_issupported(&hdr, info)) {\n\t\tjas_eprintf(\"error: unsupported BMP encoding\\n\");\n\t\tbmp_info_destroy(info);\n\t\treturn 0;\n\t}\n\n\t/* Skip over any useless data between the end of the palette\n\t and start of the bitmap data. */\n\tif ((n = hdr.off - (BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info))) < 0) {\n\t\tjas_eprintf(\"error: possibly bad bitmap offset?\\n\");\n\t\treturn 0;\n\t}\n\tif (n > 0) {\n\t\tjas_eprintf(\"skipping unknown data in BMP file\\n\");\n\t\tif (bmp_gobble(in, n)) {\n\t\t\tbmp_info_destroy(info);\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\t/* Get the number of components. */\n\tnumcmpts = bmp_numcmpts(info);\n\n\tfor (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,\n\t ++cmptparm) {\n\t\tcmptparm->tlx = 0;\n\t\tcmptparm->tly = 0;\n\t\tcmptparm->hstep = 1;\n\t\tcmptparm->vstep = 1;\n\t\tcmptparm->width = info->width;\n\t\tcmptparm->height = info->height;\n\t\tcmptparm->prec = 8;\n\t\tcmptparm->sgnd = false;\n\t}\n\n\t/* Create image object. */\n\tif (!(image = jas_image_create(numcmpts, cmptparms,\n\t JAS_CLRSPC_UNKNOWN))) {\n\t\tbmp_info_destroy(info);\n\t\treturn 0;\n\t}\n\n\tif (numcmpts == 3) {\n\t\tjas_image_setclrspc(image, JAS_CLRSPC_SRGB);\n\t\tjas_image_setcmpttype(image, 0,\n\t\t JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R));\n\t\tjas_image_setcmpttype(image, 1,\n\t\t JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G));\n\t\tjas_image_setcmpttype(image, 2,\n\t\t JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B));\n\t} else {\n\t\tjas_image_setclrspc(image, JAS_CLRSPC_SGRAY);\n\t\tjas_image_setcmpttype(image, 0,\n\t\t JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y));\n\t}\n\n\t/* Read the bitmap data. */\n\tif (bmp_getdata(in, info, image)) {\n\t\tbmp_info_destroy(info);\n\t\tjas_image_destroy(image);\n\t\treturn 0;\n\t}\n\n\tbmp_info_destroy(info);\n\n\treturn image;\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: rtadv_read (struct thread *thread)\n{\n int sock;\n int len;\n u_char buf[RTADV_MSG_SIZE];\n struct sockaddr_in6 from;\n ifindex_t ifindex = 0;\n int hoplimit = -1;\n struct zebra_vrf *zvrf = THREAD_ARG (thread);\n\n sock = THREAD_FD (thread);\n zvrf->rtadv.ra_read = NULL;\n\n /* Register myself. */\n rtadv_event (zvrf, RTADV_READ, sock);\n\n len = rtadv_recv_packet (sock, buf, BUFSIZ, &from, &ifindex, &hoplimit);\n\n if (len < 0) \n {\n zlog_warn (\"router solicitation recv failed: %s.\", safe_strerror (errno));\n return len;\n }\n\n rtadv_process_packet (buf, (unsigned)len, ifindex, hoplimit, zvrf->vrf_id);\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'zebra: stack overrun in IPv6 RA receive code (CVE-2016-1245)\n\nThe IPv6 RA code also receives ICMPv6 RS and RA messages.\nUnfortunately, by bad coding practice, the buffer size specified on\nreceiving such messages mixed up 2 constants that in fact have\ndifferent values.\n\nThe code itself has:\n #define RTADV_MSG_SIZE 4096\nWhile BUFSIZ is system-dependent, in my case (x86_64 glibc):\n /usr/include/_G_config.h:#define _G_BUFSIZ 8192\n /usr/include/libio.h:#define _IO_BUFSIZ _G_BUFSIZ\n /usr/include/stdio.h:# define BUFSIZ _IO_BUFSIZ\n\nFreeBSD, OpenBSD, NetBSD and Illumos are not affected, since all of them\nhave BUFSIZ == 1024.\n\nAs the latter is passed to the kernel on recvmsg(), it's possible to\noverwrite 4kB of stack -- with ICMPv6 packets that can be globally sent\nto any of the system's addresses (using fragmentation to get to 8k).\n\n(The socket has filters installed limiting this to RS and RA packets,\nbut does not have a filter for source address or TTL.)\n\nIssue discovered by trying to test other stuff, which randomly caused\nthe stack to be smaller than 8kB in that code location, which then\ncauses the kernel to report EFAULT (Bad address).\n\nSigned-off-by: David Lamparter \nReviewed-by: Donald Sharp '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void *jas_malloc(size_t size)\n{\n\tvoid *result;\n\tjas_mb_t *mb;\n\tsize_t ext_size;\n\tsize_t mem;\n\n\tJAS_DBGLOG(100, (\"jas_malloc(%zu)\\n\", size));\n#if defined(JAS_MALLOC_RETURN_NULL_PTR_FOR_ZERO_SIZE)\n\tif (!size) {\n\t\treturn 0;\n\t}\n#endif\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\tresult = 0;\n\t\tmb = 0;\n\t} else if (!jas_safe_size_add(jas_mem, size, &mem) || mem > jas_max_mem) {\n\t\tjas_eprintf(\"maximum memory limit would be exceeded\\n\");\n\t\tresult = 0;\n\t\tmb = 0;\n\t} else {\n\t\tJAS_DBGLOG(100, (\"jas_malloc: ext_size=%zu\\n\", ext_size));\n\t\tif ((mb = malloc(ext_size))) {\n\t\t\tresult = jas_mb_get_data(mb);\n\t\t\tmb->size = size;\n\t\t\tjas_mem = mem;\n\t\t} else {\n\t\t\tresult = 0;\n\t\t}\n\t}\n\tJAS_DBGLOG(99, (\"jas_malloc(%zu) -> %p (mb=%p)\\n\", size, result, 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: static jas_image_cmpt_t *jas_image_cmpt_create(uint_fast32_t tlx,\n uint_fast32_t tly, uint_fast32_t hstep, uint_fast32_t vstep,\n uint_fast32_t width, uint_fast32_t height, uint_fast16_t depth, bool sgnd,\n uint_fast32_t inmem)\n{\n\tjas_image_cmpt_t *cmpt;\n\tsize_t size;\n\n\tif (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) {\n\t\tgoto error;\n\t}\n\n\tcmpt->type_ = JAS_IMAGE_CT_UNKNOWN;\n\tcmpt->tlx_ = tlx;\n\tcmpt->tly_ = tly;\n\tcmpt->hstep_ = hstep;\n\tcmpt->vstep_ = vstep;\n\tcmpt->width_ = width;\n\tcmpt->height_ = height;\n\tcmpt->prec_ = depth;\n\tcmpt->sgnd_ = sgnd;\n\tcmpt->stream_ = 0;\n\tcmpt->cps_ = (depth + 7) / 8;\n\n\t// size = cmpt->width_ * cmpt->height_ * cmpt->cps_;\n\tif (!jas_safe_size_mul(cmpt->width_, cmpt->height_, &size) ||\n\t !jas_safe_size_mul(size, cmpt->cps_, &size)) {\n\t\tgoto error;\n\t}\n\tcmpt->stream_ = (inmem) ? jas_stream_memopen(0, size) :\n\t jas_stream_tmpfile();\n\tif (!cmpt->stream_) {\n\t\tgoto error;\n\t}\n\n\t/* Zero the component data. This isn't necessary, but it is\n\tconvenient for debugging purposes. */\n\t/* Note: conversion of size - 1 to long can overflow */\n\tif (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 ||\n\t jas_stream_putc(cmpt->stream_, 0) == EOF ||\n\t jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) {\n\t\tgoto error;\n\t}\n\n\treturn cmpt;\n\nerror:\n\tif (cmpt) {\n\t\tjas_image_cmpt_destroy(cmpt);\n\t}\n\treturn 0;\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: ZEND_METHOD(CURLFile, __wakeup)\n{\n\tzend_update_property_string(curl_CURLFile_class, getThis(), \"name\", sizeof(\"name\")-1, \"\" TSRMLS_CC);\n\tzend_throw_exception(NULL, \"Unserialization of CURLFile instances is not allowed\", 0 TSRMLS_CC);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Fix bug #73147: Use After Free in PHP7 unserialize()'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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 cstm(JF, js_Ast *stm)\n{\n\tjs_Ast *target;\n\tint loop, cont, then, end;\n\n\temitline(J, F, stm);\n\n\tswitch (stm->type) {\n\tcase AST_FUNDEC:\n\t\tbreak;\n\n\tcase STM_BLOCK:\n\t\tcstmlist(J, F, stm->a);\n\t\tbreak;\n\n\tcase STM_EMPTY:\n\t\tif (F->script) {\n\t\t\temit(J, F, OP_POP);\n\t\t\temit(J, F, OP_UNDEF);\n\t\t}\n\t\tbreak;\n\n\tcase STM_VAR:\n\t\tcvarinit(J, F, stm->a);\n\t\tbreak;\n\n\tcase STM_IF:\n\t\tif (stm->c) {\n\t\t\tcexp(J, F, stm->a);\n\t\t\tthen = emitjump(J, F, OP_JTRUE);\n\t\t\tcstm(J, F, stm->c);\n\t\t\tend = emitjump(J, F, OP_JUMP);\n\t\t\tlabel(J, F, then);\n\t\t\tcstm(J, F, stm->b);\n\t\t\tlabel(J, F, end);\n\t\t} else {\n\t\t\tcexp(J, F, stm->a);\n\t\t\tend = emitjump(J, F, OP_JFALSE);\n\t\t\tcstm(J, F, stm->b);\n\t\t\tlabel(J, F, end);\n\t\t}\n\t\tbreak;\n\n\tcase STM_DO:\n\t\tloop = here(J, F);\n\t\tcstm(J, F, stm->a);\n\t\tcont = here(J, F);\n\t\tcexp(J, F, stm->b);\n\t\temitjumpto(J, F, OP_JTRUE, loop);\n\t\tlabeljumps(J, F, stm->jumps, here(J,F), cont);\n\t\tbreak;\n\n\tcase STM_WHILE:\n\t\tloop = here(J, F);\n\t\tcexp(J, F, stm->a);\n\t\tend = emitjump(J, F, OP_JFALSE);\n\t\tcstm(J, F, stm->b);\n\t\temitjumpto(J, F, OP_JUMP, loop);\n\t\tlabel(J, F, end);\n\t\tlabeljumps(J, F, stm->jumps, here(J,F), loop);\n\t\tbreak;\n\n\tcase STM_FOR:\n\tcase STM_FOR_VAR:\n\t\tif (stm->type == STM_FOR_VAR) {\n\t\t\tcvarinit(J, F, stm->a);\n\t\t} else {\n\t\t\tif (stm->a) {\n\t\t\t\tcexp(J, F, stm->a);\n\t\t\t\temit(J, F, OP_POP);\n\t\t\t}\n\t\t}\n\t\tloop = here(J, F);\n\t\tif (stm->b) {\n\t\t\tcexp(J, F, stm->b);\n\t\t\tend = emitjump(J, F, OP_JFALSE);\n\t\t} else {\n\t\t\tend = 0;\n\t\t}\n\t\tcstm(J, F, stm->d);\n\t\tcont = here(J, F);\n\t\tif (stm->c) {\n\t\t\tcexp(J, F, stm->c);\n\t\t\temit(J, F, OP_POP);\n\t\t}\n\t\temitjumpto(J, F, OP_JUMP, loop);\n\t\tif (end)\n\t\t\tlabel(J, F, end);\n\t\tlabeljumps(J, F, stm->jumps, here(J,F), cont);\n\t\tbreak;\n\n\tcase STM_FOR_IN:\n\tcase STM_FOR_IN_VAR:\n\t\tcexp(J, F, stm->b);\n\t\temit(J, F, OP_ITERATOR);\n\t\tloop = here(J, F);\n\t\t{\n\t\t\temit(J, F, OP_NEXTITER);\n\t\t\tend = emitjump(J, F, OP_JFALSE);\n\t\t\tcassignforin(J, F, stm);\n\t\t\tif (F->script) {\n\t\t\t\temit(J, F, OP_ROT2);\n\t\t\t\tcstm(J, F, stm->c);\n\t\t\t\temit(J, F, OP_ROT2);\n\t\t\t} else {\n\t\t\t\tcstm(J, F, stm->c);\n\t\t\t}\n\t\t\temitjumpto(J, F, OP_JUMP, loop);\n\t\t}\n\t\tlabel(J, F, end);\n\t\tlabeljumps(J, F, stm->jumps, here(J,F), loop);\n\t\tbreak;\n\n\tcase STM_SWITCH:\n\t\tcswitch(J, F, stm->a, stm->b);\n\t\tlabeljumps(J, F, stm->jumps, here(J,F), 0);\n\t\tbreak;\n\n\tcase STM_LABEL:\n\t\tcstm(J, F, stm->b);\n\t\t/* skip consecutive labels */\n\t\twhile (stm->type == STM_LABEL)\n\t\t\tstm = stm->b;\n\t\t/* loops and switches have already been labelled */\n\t\tif (!isloop(stm->type) && stm->type != STM_SWITCH)\n\t\t\tlabeljumps(J, F, stm->jumps, here(J,F), 0);\n\t\tbreak;\n\n\tcase STM_BREAK:\n\t\tif (stm->a) {\n\t\t\ttarget = breaktarget(J, F, stm, stm->a->string);\n\t\t\tif (!target)\n\t\t\t\tjsC_error(J, stm, \"break label '%s' not found\", stm->a->string);\n\t\t} else {\n\t\t\ttarget = breaktarget(J, F, stm, NULL);\n\t\t\tif (!target)\n\t\t\t\tjsC_error(J, stm, \"unlabelled break must be inside loop or switch\");\n\t\t}\n\t\tcexit(J, F, STM_BREAK, stm, target);\n\t\taddjump(J, F, STM_BREAK, target, emitjump(J, F, OP_JUMP));\n\t\tbreak;\n\n\tcase STM_CONTINUE:\n\t\tif (stm->a) {\n\t\t\ttarget = continuetarget(J, F, stm, stm->a->string);\n\t\t\tif (!target)\n\t\t\t\tjsC_error(J, stm, \"continue label '%s' not found\", stm->a->string);\n\t\t} else {\n\t\t\ttarget = continuetarget(J, F, stm, NULL);\n\t\t\tif (!target)\n\t\t\t\tjsC_error(J, stm, \"continue must be inside loop\");\n\t\t}\n\t\tcexit(J, F, STM_CONTINUE, stm, target);\n\t\taddjump(J, F, STM_CONTINUE, target, emitjump(J, F, OP_JUMP));\n\t\tbreak;\n\n\tcase STM_RETURN:\n\t\tif (stm->a)\n\t\t\tcexp(J, F, stm->a);\n\t\telse\n\t\t\temit(J, F, OP_UNDEF);\n\t\ttarget = returntarget(J, F, stm);\n\t\tif (!target)\n\t\t\tjsC_error(J, stm, \"return not in function\");\n\t\tcexit(J, F, STM_RETURN, stm, target);\n\t\temit(J, F, OP_RETURN);\n\t\tbreak;\n\n\tcase STM_THROW:\n\t\tcexp(J, F, stm->a);\n\t\temit(J, F, OP_THROW);\n\t\tbreak;\n\n\tcase STM_WITH:\n\t\tcexp(J, F, stm->a);\n\t\temit(J, F, OP_WITH);\n\t\tcstm(J, F, stm->b);\n\t\temit(J, F, OP_ENDWITH);\n\t\tbreak;\n\n\tcase STM_TRY:\n\t\tif (stm->b && stm->c) {\n\t\t\tif (stm->d)\n\t\t\t\tctrycatchfinally(J, F, stm->a, stm->b, stm->c, stm->d);\n\t\t\telse\n\t\t\t\tctrycatch(J, F, stm->a, stm->b, stm->c);\n\t\t} else {\n\t\t\tctryfinally(J, F, stm->a, stm->d);\n\t\t}\n\t\tbreak;\n\n\tcase STM_DEBUGGER:\n\t\temit(J, F, OP_DEBUGGER);\n\t\tbreak;\n\n\tdefault:\n\t\tif (F->script) {\n\t\t\temit(J, F, OP_POP);\n\t\t\tcexp(J, F, stm);\n\t\t} else {\n\t\t\tcexp(J, F, stm);\n\t\t\temit(J, F, OP_POP);\n\t\t}\n\t\tbreak;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix 697172: degenerate labeled break/continue statement.\n\nA labeled break statement will look for a matching label through\nits chain of parent statements. We start looking at the break statement\nthough, so if the label is attached to the break, we'll return the break\nstatement itself as a break target.\n\nStart looking for targets one level up instead.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: jas_seq2d_t *jas_seq2d_copy(jas_seq2d_t *x)\n{\n\tjas_matrix_t *y;\n\tint i;\n\tint j;\n\ty = jas_seq2d_create(jas_seq2d_xstart(x), jas_seq2d_ystart(x),\n\t jas_seq2d_xend(x), jas_seq2d_yend(x));\n\tassert(y);\n\tfor (i = 0; i < x->numrows_; ++i) {\n\t\tfor (j = 0; j < x->numcols_; ++j) {\n\t\t\t*jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j);\n\t\t}\n\t}\n\treturn y;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'The generation of the configuration file jas_config.h has been completely\nreworked in order to avoid pollution of the global namespace.\n\nSome problematic types like uchar, ulong, and friends have been replaced\nwith names with a jas_ prefix.\n\nAn option max_samples has been added to the BMP and JPEG decoders to\nrestrict the maximum size of image that they can decode. This change\nwas made as a (possibly temporary) fix to address security concerns.\nA max_samples command-line option has also been added to imginfo.\n\nWhether an image component (for jas_image_t) is stored in memory or on\ndisk is now based on the component size (rather than the image size).\n\nSome debug log message were added.\n\nSome new integer overflow checks were added.\n\nSome new safe integer add/multiply functions were added.\n\nMore pre-C99 cruft was removed. JasPer has numerous \"hacks\" to\nhandle pre-C99 compilers. JasPer now assumes C99 support. So, this\npre-C99 cruft is unnecessary and can be removed.\n\nThe regression jasper-doublefree-mem_close.jpg has been re-enabled.\nTheoretically, it should work more predictably now.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int jpc_enc_encodemainhdr(jpc_enc_t *enc)\n{\n\tjpc_siz_t *siz;\n\tjpc_cod_t *cod;\n\tjpc_qcd_t *qcd;\n\tint i;\nlong startoff;\nlong mainhdrlen;\n\tjpc_enc_cp_t *cp;\n\tjpc_qcc_t *qcc;\n\tjpc_enc_tccp_t *tccp;\n\tuint_fast16_t cmptno;\n\tjpc_tsfb_band_t bandinfos[JPC_MAXBANDS];\n\tjpc_fix_t mctsynweight;\n\tjpc_enc_tcp_t *tcp;\n\tjpc_tsfb_t *tsfb;\n\tjpc_tsfb_band_t *bandinfo;\n\tuint_fast16_t numbands;\n\tuint_fast16_t bandno;\n\tuint_fast16_t rlvlno;\n\tuint_fast16_t analgain;\n\tjpc_fix_t absstepsize;\n\tchar buf[1024];\n\tjpc_com_t *com;\n\n\tcp = enc->cp;\n\nstartoff = jas_stream_getrwcount(enc->out);\n\n\t/* Write SOC marker segment. */\n\tif (!(enc->mrk = jpc_ms_create(JPC_MS_SOC))) {\n\t\treturn -1;\n\t}\n\tif (jpc_putms(enc->out, enc->cstate, enc->mrk)) {\n\t\tjas_eprintf(\"cannot write SOC marker\\n\");\n\t\treturn -1;\n\t}\n\tjpc_ms_destroy(enc->mrk);\n\tenc->mrk = 0;\n\n\t/* Write SIZ marker segment. */\n\tif (!(enc->mrk = jpc_ms_create(JPC_MS_SIZ))) {\n\t\treturn -1;\n\t}\n\tsiz = &enc->mrk->parms.siz;\n\tsiz->caps = 0;\n\tsiz->xoff = cp->imgareatlx;\n\tsiz->yoff = cp->imgareatly;\n\tsiz->width = cp->refgrdwidth;\n\tsiz->height = cp->refgrdheight;\n\tsiz->tilexoff = cp->tilegrdoffx;\n\tsiz->tileyoff = cp->tilegrdoffy;\n\tsiz->tilewidth = cp->tilewidth;\n\tsiz->tileheight = cp->tileheight;\n\tsiz->numcomps = cp->numcmpts;\n\tsiz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t));\n\tassert(siz->comps);\n\tfor (i = 0; i < JAS_CAST(int, cp->numcmpts); ++i) {\n\t\tsiz->comps[i].prec = cp->ccps[i].prec;\n\t\tsiz->comps[i].sgnd = cp->ccps[i].sgnd;\n\t\tsiz->comps[i].hsamp = cp->ccps[i].sampgrdstepx;\n\t\tsiz->comps[i].vsamp = cp->ccps[i].sampgrdstepy;\n\t}\n\tif (jpc_putms(enc->out, enc->cstate, enc->mrk)) {\n\t\tjas_eprintf(\"cannot write SIZ marker\\n\");\n\t\treturn -1;\n\t}\n\tjpc_ms_destroy(enc->mrk);\n\tenc->mrk = 0;\n\n\tif (!(enc->mrk = jpc_ms_create(JPC_MS_COM))) {\n\t\treturn -1;\n\t}\n\tsprintf(buf, \"Creator: JasPer Version %s\", jas_getversion());\n\tcom = &enc->mrk->parms.com;\n\tcom->len = JAS_CAST(uint_fast16_t, strlen(buf));\n\tcom->regid = JPC_COM_LATIN;\n\tif (!(com->data = JAS_CAST(uchar *, jas_strdup(buf)))) {\n\t\tabort();\n\t}\n\tif (jpc_putms(enc->out, enc->cstate, enc->mrk)) {\n\t\tjas_eprintf(\"cannot write COM marker\\n\");\n\t\treturn -1;\n\t}\n\tjpc_ms_destroy(enc->mrk);\n\tenc->mrk = 0;\n\n#if 0\n\tif (!(enc->mrk = jpc_ms_create(JPC_MS_CRG))) {\n\t\treturn -1;\n\t}\n\tcrg = &enc->mrk->parms.crg;\n\tcrg->comps = jas_alloc2(crg->numcomps, sizeof(jpc_crgcomp_t));\n\tif (jpc_putms(enc->out, enc->cstate, enc->mrk)) {\n\t\tjas_eprintf(\"cannot write CRG marker\\n\");\n\t\treturn -1;\n\t}\n\tjpc_ms_destroy(enc->mrk);\n\tenc->mrk = 0;\n#endif\n\n\ttcp = &cp->tcp;\n\ttccp = &cp->tccp;\n\tfor (cmptno = 0; cmptno < cp->numcmpts; ++cmptno) {\n\t\ttsfb = jpc_cod_gettsfb(tccp->qmfbid, tccp->maxrlvls - 1);\n\t\tjpc_tsfb_getbands(tsfb, 0, 0, 1 << tccp->maxrlvls, 1 << tccp->maxrlvls,\n\t\t bandinfos);\n\t\tjpc_tsfb_destroy(tsfb);\n\t\tmctsynweight = jpc_mct_getsynweight(tcp->mctid, cmptno);\n\t\tnumbands = 3 * tccp->maxrlvls - 2;\n\t\tfor (bandno = 0, bandinfo = bandinfos; bandno < numbands;\n\t\t ++bandno, ++bandinfo) {\n\t\t\trlvlno = (bandno) ? ((bandno - 1) / 3 + 1) : 0;\n\t\t\tanalgain = JPC_NOMINALGAIN(tccp->qmfbid, tccp->maxrlvls,\n\t\t\t rlvlno, bandinfo->orient);\n\t\t\tif (!tcp->intmode) {\n\t\t\t\tabsstepsize = jpc_fix_div(jpc_inttofix(1 <<\n\t\t\t\t (analgain + 1)), bandinfo->synenergywt);\n\t\t\t} else {\n\t\t\t\tabsstepsize = jpc_inttofix(1);\n\t\t\t}\t\n\t\t\tcp->ccps[cmptno].stepsizes[bandno] =\n\t\t\t jpc_abstorelstepsize(absstepsize,\n\t\t\t cp->ccps[cmptno].prec + analgain);\n\t\t}\n\t\tcp->ccps[cmptno].numstepsizes = numbands;\n\t}\n\n\tif (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) {\n\t\treturn -1;\n\t}\n\tcod = &enc->mrk->parms.cod;\n\tcod->csty = cp->tccp.csty | cp->tcp.csty;\n\tcod->compparms.csty = cp->tccp.csty | cp->tcp.csty;\n\tcod->compparms.numdlvls = cp->tccp.maxrlvls - 1;\n\tcod->compparms.numrlvls = cp->tccp.maxrlvls;\n\tcod->prg = cp->tcp.prg;\n\tcod->numlyrs = cp->tcp.numlyrs;\n\tcod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkwidthexpn);\n\tcod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkheightexpn);\n\tcod->compparms.cblksty = cp->tccp.cblksty;\n\tcod->compparms.qmfbid = cp->tccp.qmfbid;\n\tcod->mctrans = (cp->tcp.mctid != JPC_MCT_NONE);\n\tif (tccp->csty & JPC_COX_PRT) {\n\t\tfor (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) {\n\t\t\tcod->compparms.rlvls[rlvlno].parwidthval = tccp->prcwidthexpns[rlvlno];\n\t\t\tcod->compparms.rlvls[rlvlno].parheightval = tccp->prcheightexpns[rlvlno];\n\t\t}\n\t}\n\tif (jpc_putms(enc->out, enc->cstate, enc->mrk)) {\n\t\tjas_eprintf(\"cannot write COD marker\\n\");\n\t\treturn -1;\n\t}\n\tjpc_ms_destroy(enc->mrk);\n\tenc->mrk = 0;\n\n\tif (!(enc->mrk = jpc_ms_create(JPC_MS_QCD))) {\n\t\treturn -1;\n\t}\n\tqcd = &enc->mrk->parms.qcd;\n\tqcd->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ?\n\t JPC_QCX_SEQNT : JPC_QCX_NOQNT;\n\tqcd->compparms.numstepsizes = cp->ccps[0].numstepsizes;\n\tqcd->compparms.numguard = cp->tccp.numgbits;\n\tqcd->compparms.stepsizes = cp->ccps[0].stepsizes;\n\tif (jpc_putms(enc->out, enc->cstate, enc->mrk)) {\n\t\treturn -1;\n\t}\n\t/* We do not want the step size array to be freed! */\n\tqcd->compparms.stepsizes = 0;\n\tjpc_ms_destroy(enc->mrk);\n\tenc->mrk = 0;\n\n\ttccp = &cp->tccp;\n\tfor (cmptno = 1; cmptno < cp->numcmpts; ++cmptno) {\n\t\tif (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) {\n\t\t\treturn -1;\n\t\t}\n\t\tqcc = &enc->mrk->parms.qcc;\n\t\tqcc->compno = cmptno;\n\t\tqcc->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ?\n\t\t JPC_QCX_SEQNT : JPC_QCX_NOQNT;\n\t\tqcc->compparms.numstepsizes = cp->ccps[cmptno].numstepsizes;\n\t\tqcc->compparms.numguard = cp->tccp.numgbits;\n\t\tqcc->compparms.stepsizes = cp->ccps[cmptno].stepsizes;\n\t\tif (jpc_putms(enc->out, enc->cstate, enc->mrk)) {\n\t\t\treturn -1;\n\t\t}\n\t\t/* We do not want the step size array to be freed! */\n\t\tqcc->compparms.stepsizes = 0;\n\t\tjpc_ms_destroy(enc->mrk);\n\t\tenc->mrk = 0;\n\t}\n\n#define MAINTLRLEN\t2\n\tmainhdrlen = jas_stream_getrwcount(enc->out) - startoff;\n\tenc->len += mainhdrlen;\n\tif (enc->cp->totalsize != UINT_FAST32_MAX) {\n\t\tuint_fast32_t overhead;\n\t\toverhead = mainhdrlen + MAINTLRLEN;\n\t\tenc->mainbodysize = (enc->cp->totalsize >= overhead) ?\n\t\t (enc->cp->totalsize - overhead) : 0;\n\t} else {\n\t\tenc->mainbodysize = UINT_FAST32_MAX;\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'The generation of the configuration file jas_config.h has been completely\nreworked in order to avoid pollution of the global namespace.\n\nSome problematic types like uchar, ulong, and friends have been replaced\nwith names with a jas_ prefix.\n\nAn option max_samples has been added to the BMP and JPEG decoders to\nrestrict the maximum size of image that they can decode. This change\nwas made as a (possibly temporary) fix to address security concerns.\nA max_samples command-line option has also been added to imginfo.\n\nWhether an image component (for jas_image_t) is stored in memory or on\ndisk is now based on the component size (rather than the image size).\n\nSome debug log message were added.\n\nSome new integer overflow checks were added.\n\nSome new safe integer add/multiply functions were added.\n\nMore pre-C99 cruft was removed. JasPer has numerous \"hacks\" to\nhandle pre-C99 compilers. JasPer now assumes C99 support. So, this\npre-C99 cruft is unnecessary and can be removed.\n\nThe regression jasper-doublefree-mem_close.jpg has been re-enabled.\nTheoretically, it should work more predictably now.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ras_validate(jas_stream_t *in)\n{\n\tuchar buf[RAS_MAGICLEN];\n\tint i;\n\tint n;\n\tuint_fast32_t magic;\n\n\tassert(JAS_STREAM_MAXPUTBACK >= RAS_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, RAS_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 < RAS_MAGICLEN) {\n\t\treturn -1;\n\t}\n\n\tmagic = (JAS_CAST(uint_fast32_t, buf[0]) << 24) |\n\t (JAS_CAST(uint_fast32_t, buf[1]) << 16) |\n\t (JAS_CAST(uint_fast32_t, buf[2]) << 8) |\n\t buf[3];\n\n\t/* Is the signature correct for the Sun Rasterfile format? */\n\tif (magic != RAS_MAGIC) {\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-20', 'CWE-190'], 'message': 'The generation of the configuration file jas_config.h has been completely\nreworked in order to avoid pollution of the global namespace.\n\nSome problematic types like uchar, ulong, and friends have been replaced\nwith names with a jas_ prefix.\n\nAn option max_samples has been added to the BMP and JPEG decoders to\nrestrict the maximum size of image that they can decode. This change\nwas made as a (possibly temporary) fix to address security concerns.\nA max_samples command-line option has also been added to imginfo.\n\nWhether an image component (for jas_image_t) is stored in memory or on\ndisk is now based on the component size (rather than the image size).\n\nSome debug log message were added.\n\nSome new integer overflow checks were added.\n\nSome new safe integer add/multiply functions were added.\n\nMore pre-C99 cruft was removed. JasPer has numerous \"hacks\" to\nhandle pre-C99 compilers. JasPer now assumes C99 support. So, this\npre-C99 cruft is unnecessary and can be removed.\n\nThe regression jasper-doublefree-mem_close.jpg has been re-enabled.\nTheoretically, it should work more predictably now.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static mif_hdr_t *mif_hdr_get(jas_stream_t *in)\n{\n\tuchar magicbuf[MIF_MAGICLEN];\n\tchar buf[4096];\n\tmif_hdr_t *hdr;\n\tbool done;\n\tjas_tvparser_t *tvp;\n\tint id;\n\n\thdr = 0;\n\ttvp = 0;\n\n\tif (jas_stream_read(in, magicbuf, MIF_MAGICLEN) != MIF_MAGICLEN) {\n\t\tgoto error;\n\t}\n\tif (magicbuf[0] != (MIF_MAGIC >> 24) || magicbuf[1] != ((MIF_MAGIC >> 16) &\n\t 0xff) || magicbuf[2] != ((MIF_MAGIC >> 8) & 0xff) || magicbuf[3] !=\n\t (MIF_MAGIC & 0xff)) {\n\t\tjas_eprintf(\"error: bad signature\\n\");\n\t\tgoto error;\n\t}\n\n\tif (!(hdr = mif_hdr_create(0))) {\n\t\tgoto error;\n\t}\n\n\tdone = false;\n\tdo {\n\t\tif (!mif_getline(in, buf, sizeof(buf))) {\n\t\t\tjas_eprintf(\"mif_getline failed\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tif (buf[0] == '\\0') {\n\t\t\tcontinue;\n\t\t}\n\t\tJAS_DBGLOG(10, (\"header line: len=%d; %s\\n\", strlen(buf), buf));\n\t\tif (!(tvp = jas_tvparser_create(buf))) {\n\t\t\tjas_eprintf(\"jas_tvparser_create failed\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tif (jas_tvparser_next(tvp)) {\n\t\t\tjas_eprintf(\"cannot get record type\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tid = jas_taginfo_nonull(jas_taginfos_lookup(mif_tags2,\n\t\t jas_tvparser_gettag(tvp)))->id;\n\t\tjas_tvparser_destroy(tvp);\n\t\ttvp = 0;\n\t\tswitch (id) {\n\t\tcase MIF_CMPT:\n\t\t\tif (mif_process_cmpt(hdr, buf)) {\n\t\t\t\tjas_eprintf(\"cannot get component information\\n\");\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase MIF_END:\n\t\t\tdone = 1;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tjas_eprintf(\"invalid header information: %s\\n\", buf);\n\t\t\tgoto error;\n\t\t\tbreak;\n\t\t}\n\t} while (!done);\n\n\treturn hdr;\n\nerror:\n\tif (hdr) {\n\t\tmif_hdr_destroy(hdr);\n\t}\n\tif (tvp) {\n\t\tjas_tvparser_destroy(tvp);\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: jpc_ms_t *jpc_getms(jas_stream_t *in, jpc_cstate_t *cstate)\n{\n\tjpc_ms_t *ms;\n\tjpc_mstabent_t *mstabent;\n\tjas_stream_t *tmpstream;\n\n\tif (!(ms = jpc_ms_create(0))) {\n\t\treturn 0;\n\t}\n\n\t/* Get the marker type. */\n\tif (jpc_getuint16(in, &ms->id) || ms->id < JPC_MS_MIN ||\n\t ms->id > JPC_MS_MAX) {\n\t\tjpc_ms_destroy(ms);\n\t\treturn 0;\n\t}\n\n\tmstabent = jpc_mstab_lookup(ms->id);\n\tms->ops = &mstabent->ops;\n\n\t/* Get the marker segment length and parameters if present. */\n\t/* Note: It is tacitly assumed that a marker segment cannot have\n\t parameters unless it has a length field. That is, there cannot\n\t be a parameters field without a length field and vice versa. */\n\tif (JPC_MS_HASPARMS(ms->id)) {\n\t\t/* Get the length of the marker segment. */\n\t\tif (jpc_getuint16(in, &ms->len) || ms->len < 3) {\n\t\t\tjpc_ms_destroy(ms);\n\t\t\treturn 0;\n\t\t}\n\t\t/* Calculate the length of the marker segment parameters. */\n\t\tms->len -= 2;\n\t\t/* Create and prepare a temporary memory stream from which to\n\t\t read the marker segment parameters. */\n\t\t/* Note: This approach provides a simple way of ensuring that\n\t\t we never read beyond the end of the marker segment (even if\n\t\t the marker segment length is errantly set too small). */\n\t\tif (!(tmpstream = jas_stream_memopen(0, 0))) {\n\t\t\tjpc_ms_destroy(ms);\n\t\t\treturn 0;\n\t\t}\n\t\tif (jas_stream_copy(tmpstream, in, ms->len) ||\n\t\t jas_stream_seek(tmpstream, 0, SEEK_SET) < 0) {\n\t\t\tjas_stream_close(tmpstream);\n\t\t\tjpc_ms_destroy(ms);\n\t\t\treturn 0;\n\t\t}\n\t\t/* Get the marker segment parameters. */\n\t\tif ((*ms->ops->getparms)(ms, cstate, tmpstream)) {\n\t\t\tms->ops = 0;\n\t\t\tjpc_ms_destroy(ms);\n\t\t\tjas_stream_close(tmpstream);\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (jas_getdbglevel() > 0) {\n\t\t\tjpc_ms_dump(ms, stderr);\n\t\t}\n\n\t\tif (JAS_CAST(ulong, jas_stream_tell(tmpstream)) != ms->len) {\n\t\t\tjas_eprintf(\n\t\t\t \"warning: trailing garbage in marker segment (%ld bytes)\\n\",\n\t\t\t ms->len - jas_stream_tell(tmpstream));\n\t\t}\n\n\t\t/* Close the temporary stream. */\n\t\tjas_stream_close(tmpstream);\n\n\t} else {\n\t\t/* There are no marker segment parameters. */\n\t\tms->len = 0;\n\n\t\tif (jas_getdbglevel() > 0) {\n\t\t\tjpc_ms_dump(ms, stderr);\n\t\t}\n\t}\n\n\t/* Update the code stream state information based on the type of\n\t marker segment read. */\n\t/* Note: This is a bit of a hack, but I'm not going to define another\n\t type of virtual function for this one special case. */\n\tif (ms->id == JPC_MS_SIZ) {\n\t\tcstate->numcomps = ms->parms.siz.numcomps;\n\t}\n\n\treturn ms;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'The generation of the configuration file jas_config.h has been completely\nreworked in order to avoid pollution of the global namespace.\n\nSome problematic types like uchar, ulong, and friends have been replaced\nwith names with a jas_ prefix.\n\nAn option max_samples has been added to the BMP and JPEG decoders to\nrestrict the maximum size of image that they can decode. This change\nwas made as a (possibly temporary) fix to address security concerns.\nA max_samples command-line option has also been added to imginfo.\n\nWhether an image component (for jas_image_t) is stored in memory or on\ndisk is now based on the component size (rather than the image size).\n\nSome debug log message were added.\n\nSome new integer overflow checks were added.\n\nSome new safe integer add/multiply functions were added.\n\nMore pre-C99 cruft was removed. JasPer has numerous \"hacks\" to\nhandle pre-C99 compilers. JasPer now assumes C99 support. So, this\npre-C99 cruft is unnecessary and can be removed.\n\nThe regression jasper-doublefree-mem_close.jpg has been re-enabled.\nTheoretically, it should work more predictably now.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int calcstepsizes(uint_fast16_t refstepsize, int numrlvls,\n uint_fast16_t *stepsizes)\n{\n\tint bandno;\n\tint numbands;\n\tuint_fast16_t expn;\n\tuint_fast16_t mant;\n\texpn = JPC_QCX_GETEXPN(refstepsize);\n\tmant = JPC_QCX_GETMANT(refstepsize);\n\tnumbands = 3 * numrlvls - 2;\n\tfor (bandno = 0; bandno < numbands; ++bandno) {\n//jas_eprintf(\"DEBUG %d %d %d %d %d\\n\", bandno, expn, numrlvls, bandno, ((numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0)))));\n\t\tstepsizes[bandno] = JPC_QCX_MANT(mant) | JPC_QCX_EXPN(expn + (bandno + 2) / 3);\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'jpc_dec: check for JPC_QCX_EXPN() parameter overflow\n\nAvoid the assertion failure in the JPC_QCX_EXPN() function. While the\n\"expn\" variable cannot be bigger than 0x1f, adding something to it may\nexceed that limit.\n\nThis condition could be exploited with a malicious JP2 file, allowing\na denial of service attack on processes which parse JP2 files.\n\nFixes CVE-2016-9399 and CVE-2017-13751\n\nCloses https://github.com/jasper-maint/jasper/issues/1'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile)\n{\n\tjpc_dec_tcomp_t *tcomp;\n\tint compno;\n\tint rlvlno;\n\tjpc_dec_rlvl_t *rlvl;\n\tjpc_dec_band_t *band;\n\tjpc_dec_prc_t *prc;\n\tint bndno;\n\tjpc_tsfb_band_t *bnd;\n\tint bandno;\n\tjpc_dec_ccp_t *ccp;\n\tint prccnt;\n\tjpc_dec_cblk_t *cblk;\n\tint cblkcnt;\n\tuint_fast32_t tlprcxstart;\n\tuint_fast32_t tlprcystart;\n\tuint_fast32_t brprcxend;\n\tuint_fast32_t brprcyend;\n\tuint_fast32_t tlcbgxstart;\n\tuint_fast32_t tlcbgystart;\n\tuint_fast32_t brcbgxend;\n\tuint_fast32_t brcbgyend;\n\tuint_fast32_t cbgxstart;\n\tuint_fast32_t cbgystart;\n\tuint_fast32_t cbgxend;\n\tuint_fast32_t cbgyend;\n\tuint_fast32_t tlcblkxstart;\n\tuint_fast32_t tlcblkystart;\n\tuint_fast32_t brcblkxend;\n\tuint_fast32_t brcblkyend;\n\tuint_fast32_t cblkxstart;\n\tuint_fast32_t cblkystart;\n\tuint_fast32_t cblkxend;\n\tuint_fast32_t cblkyend;\n\tuint_fast32_t tmpxstart;\n\tuint_fast32_t tmpystart;\n\tuint_fast32_t tmpxend;\n\tuint_fast32_t tmpyend;\n\tjpc_dec_cp_t *cp;\n\tjpc_tsfb_band_t bnds[64];\n\tjpc_pchg_t *pchg;\n\tint pchgno;\n\tjpc_dec_cmpt_t *cmpt;\n\n\tcp = tile->cp;\n\ttile->realmode = 0;\n\tif (cp->mctid == JPC_MCT_ICT) {\n\t\ttile->realmode = 1;\n\t}\n\n\tfor (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <\n\t dec->numcomps; ++compno, ++tcomp, ++cmpt) {\n\t\tccp = &tile->cp->ccps[compno];\n\t\tif (ccp->qmfbid == JPC_COX_INS) {\n\t\t\ttile->realmode = 1;\n\t\t}\n\t\ttcomp->numrlvls = ccp->numrlvls;\n\t\tif (!(tcomp->rlvls = jas_alloc2(tcomp->numrlvls,\n\t\t sizeof(jpc_dec_rlvl_t)))) {\n\t\t\treturn -1;\n\t\t}\n\t\tif (!(tcomp->data = jas_seq2d_create(JPC_CEILDIV(tile->xstart,\n\t\t cmpt->hstep), JPC_CEILDIV(tile->ystart, cmpt->vstep),\n\t\t JPC_CEILDIV(tile->xend, cmpt->hstep), JPC_CEILDIV(tile->yend,\n\t\t cmpt->vstep)))) {\n\t\t\treturn -1;\n\t\t}\n\t\tif (!(tcomp->tsfb = jpc_cod_gettsfb(ccp->qmfbid,\n\t\t tcomp->numrlvls - 1))) {\n\t\t\treturn -1;\n\t\t}\n\t\t{\n\t\t\tjpc_tsfb_getbands(tcomp->tsfb, jas_seq2d_xstart(tcomp->data),\n\t\t\t jas_seq2d_ystart(tcomp->data), jas_seq2d_xend(tcomp->data),\n\t\t\t jas_seq2d_yend(tcomp->data), bnds);\n\t\t}\n\t\tfor (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls;\n\t\t ++rlvlno, ++rlvl) {\n\t\t\trlvl->bands = 0;\n\t\t\trlvl->xstart = JPC_CEILDIVPOW2(tcomp->xstart,\n\t\t\t tcomp->numrlvls - 1 - rlvlno);\n\t\t\trlvl->ystart = JPC_CEILDIVPOW2(tcomp->ystart,\n\t\t\t tcomp->numrlvls - 1 - rlvlno);\n\t\t\trlvl->xend = JPC_CEILDIVPOW2(tcomp->xend,\n\t\t\t tcomp->numrlvls - 1 - rlvlno);\n\t\t\trlvl->yend = JPC_CEILDIVPOW2(tcomp->yend,\n\t\t\t tcomp->numrlvls - 1 - rlvlno);\n\t\t\trlvl->prcwidthexpn = ccp->prcwidthexpns[rlvlno];\n\t\t\trlvl->prcheightexpn = ccp->prcheightexpns[rlvlno];\n\t\t\ttlprcxstart = JPC_FLOORDIVPOW2(rlvl->xstart,\n\t\t\t rlvl->prcwidthexpn) << rlvl->prcwidthexpn;\n\t\t\ttlprcystart = JPC_FLOORDIVPOW2(rlvl->ystart,\n\t\t\t rlvl->prcheightexpn) << rlvl->prcheightexpn;\n\t\t\tbrprcxend = JPC_CEILDIVPOW2(rlvl->xend,\n\t\t\t rlvl->prcwidthexpn) << rlvl->prcwidthexpn;\n\t\t\tbrprcyend = JPC_CEILDIVPOW2(rlvl->yend,\n\t\t\t rlvl->prcheightexpn) << rlvl->prcheightexpn;\n\t\t\trlvl->numhprcs = (brprcxend - tlprcxstart) >>\n\t\t\t rlvl->prcwidthexpn;\n\t\t\trlvl->numvprcs = (brprcyend - tlprcystart) >>\n\t\t\t rlvl->prcheightexpn;\n\t\t\trlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs;\n\n\t\t\tif (rlvl->xstart >= rlvl->xend || rlvl->ystart >= rlvl->yend) {\n\t\t\t\trlvl->bands = 0;\n\t\t\t\trlvl->numprcs = 0;\n\t\t\t\trlvl->numhprcs = 0;\n\t\t\t\trlvl->numvprcs = 0;\n\t\t\t\tcontinue;\n\t\t\t}\t\n\t\t\tif (!rlvlno) {\n\t\t\t\ttlcbgxstart = tlprcxstart;\n\t\t\t\ttlcbgystart = tlprcystart;\n\t\t\t\tbrcbgxend = brprcxend;\n\t\t\t\tbrcbgyend = brprcyend;\n\t\t\t\trlvl->cbgwidthexpn = rlvl->prcwidthexpn;\n\t\t\t\trlvl->cbgheightexpn = rlvl->prcheightexpn;\n\t\t\t} else {\n\t\t\t\ttlcbgxstart = JPC_CEILDIVPOW2(tlprcxstart, 1);\n\t\t\t\ttlcbgystart = JPC_CEILDIVPOW2(tlprcystart, 1);\n\t\t\t\tbrcbgxend = JPC_CEILDIVPOW2(brprcxend, 1);\n\t\t\t\tbrcbgyend = JPC_CEILDIVPOW2(brprcyend, 1);\n\t\t\t\trlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1;\n\t\t\t\trlvl->cbgheightexpn = rlvl->prcheightexpn - 1;\n\t\t\t}\n\t\t\trlvl->cblkwidthexpn = JAS_MIN(ccp->cblkwidthexpn,\n\t\t\t rlvl->cbgwidthexpn);\n\t\t\trlvl->cblkheightexpn = JAS_MIN(ccp->cblkheightexpn,\n\t\t\t rlvl->cbgheightexpn);\n\n\t\t\trlvl->numbands = (!rlvlno) ? 1 : 3;\n\t\t\tif (!(rlvl->bands = jas_alloc2(rlvl->numbands,\n\t\t\t sizeof(jpc_dec_band_t)))) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tfor (bandno = 0, band = rlvl->bands;\n\t\t\t bandno < rlvl->numbands; ++bandno, ++band) {\n\t\t\t\tbndno = (!rlvlno) ? 0 : (3 * (rlvlno - 1) +\n\t\t\t\t bandno + 1);\n\t\t\t\tbnd = &bnds[bndno];\n\n\t\t\t\tband->orient = bnd->orient;\n\t\t\t\tband->stepsize = ccp->stepsizes[bndno];\n\t\t\t\tband->analgain = JPC_NOMINALGAIN(ccp->qmfbid,\n\t\t\t\t tcomp->numrlvls - 1, rlvlno, band->orient);\n\t\t\t\tband->absstepsize = jpc_calcabsstepsize(band->stepsize,\n\t\t\t\t cmpt->prec + band->analgain);\n\t\t\t\tband->numbps = ccp->numguardbits +\n\t\t\t\t JPC_QCX_GETEXPN(band->stepsize) - 1;\n\t\t\t\tband->roishift = (ccp->roishift + band->numbps >= JPC_PREC) ?\n\t\t\t\t (JPC_PREC - 1 - band->numbps) : ccp->roishift;\n\t\t\t\tband->data = 0;\n\t\t\t\tband->prcs = 0;\n\t\t\t\tif (bnd->xstart == bnd->xend || bnd->ystart == bnd->yend) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!(band->data = jas_seq2d_create(0, 0, 0, 0))) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tjas_seq2d_bindsub(band->data, tcomp->data, bnd->locxstart,\n\t\t\t\t bnd->locystart, bnd->locxend, bnd->locyend);\n\t\t\t\tjas_seq2d_setshift(band->data, bnd->xstart, bnd->ystart);\n\n\t\t\t\tassert(rlvl->numprcs);\n\n\t\t\t\tif (!(band->prcs = jas_alloc2(rlvl->numprcs,\n\t\t\t\t sizeof(jpc_dec_prc_t)))) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\n/************************************************/\n\t\t\t\tcbgxstart = tlcbgxstart;\n\t\t\t\tcbgystart = tlcbgystart;\n\t\t\t\tfor (prccnt = rlvl->numprcs, prc = band->prcs;\n\t\t\t\t prccnt > 0; --prccnt, ++prc) {\n\t\t\t\t\tcbgxend = cbgxstart + (1 << rlvl->cbgwidthexpn);\n\t\t\t\t\tcbgyend = cbgystart + (1 << rlvl->cbgheightexpn);\n\t\t\t\t\tprc->xstart = JAS_MAX(cbgxstart, JAS_CAST(uint_fast32_t,\n\t\t\t\t\t jas_seq2d_xstart(band->data)));\n\t\t\t\t\tprc->ystart = JAS_MAX(cbgystart, JAS_CAST(uint_fast32_t,\n\t\t\t\t\t jas_seq2d_ystart(band->data)));\n\t\t\t\t\tprc->xend = JAS_MIN(cbgxend, JAS_CAST(uint_fast32_t,\n\t\t\t\t\t jas_seq2d_xend(band->data)));\n\t\t\t\t\tprc->yend = JAS_MIN(cbgyend, JAS_CAST(uint_fast32_t,\n\t\t\t\t\t jas_seq2d_yend(band->data)));\n\t\t\t\t\tif (prc->xend > prc->xstart && prc->yend > prc->ystart) {\n\t\t\t\t\t\ttlcblkxstart = JPC_FLOORDIVPOW2(prc->xstart,\n\t\t\t\t\t\t rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn;\n\t\t\t\t\t\ttlcblkystart = JPC_FLOORDIVPOW2(prc->ystart,\n\t\t\t\t\t\t rlvl->cblkheightexpn) << rlvl->cblkheightexpn;\n\t\t\t\t\t\tbrcblkxend = JPC_CEILDIVPOW2(prc->xend,\n\t\t\t\t\t\t rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn;\n\t\t\t\t\t\tbrcblkyend = JPC_CEILDIVPOW2(prc->yend,\n\t\t\t\t\t\t rlvl->cblkheightexpn) << rlvl->cblkheightexpn;\n\t\t\t\t\t\tprc->numhcblks = (brcblkxend - tlcblkxstart) >>\n\t\t\t\t\t\t rlvl->cblkwidthexpn;\n\t\t\t\t\t\tprc->numvcblks = (brcblkyend - tlcblkystart) >>\n\t\t\t\t\t\t rlvl->cblkheightexpn;\n\t\t\t\t\t\tprc->numcblks = prc->numhcblks * prc->numvcblks;\n\t\t\t\t\t\tassert(prc->numcblks > 0);\n\n\t\t\t\t\t\tif (!(prc->incltagtree = jpc_tagtree_create(\n\t\t\t\t\t\t prc->numhcblks, prc->numvcblks))) {\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!(prc->numimsbstagtree = jpc_tagtree_create(\n\t\t\t\t\t\t prc->numhcblks, prc->numvcblks))) {\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!(prc->cblks = jas_alloc2(prc->numcblks,\n\t\t\t\t\t\t sizeof(jpc_dec_cblk_t)))) {\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tcblkxstart = cbgxstart;\n\t\t\t\t\t\tcblkystart = cbgystart;\n\t\t\t\t\t\tfor (cblkcnt = prc->numcblks, cblk = prc->cblks;\n\t\t\t\t\t\t cblkcnt > 0;) {\n\t\t\t\t\t\t\tcblkxend = cblkxstart + (1 << rlvl->cblkwidthexpn);\n\t\t\t\t\t\t\tcblkyend = cblkystart + (1 << rlvl->cblkheightexpn);\n\t\t\t\t\t\t\ttmpxstart = JAS_MAX(cblkxstart, prc->xstart);\n\t\t\t\t\t\t\ttmpystart = JAS_MAX(cblkystart, prc->ystart);\n\t\t\t\t\t\t\ttmpxend = JAS_MIN(cblkxend, prc->xend);\n\t\t\t\t\t\t\ttmpyend = JAS_MIN(cblkyend, prc->yend);\n\t\t\t\t\t\t\tif (tmpxend > tmpxstart && tmpyend > tmpystart) {\n\t\t\t\t\t\t\t\tcblk->firstpassno = -1;\n\t\t\t\t\t\t\t\tcblk->mqdec = 0;\n\t\t\t\t\t\t\t\tcblk->nulldec = 0;\n\t\t\t\t\t\t\t\tcblk->flags = 0;\n\t\t\t\t\t\t\t\tcblk->numpasses = 0;\n\t\t\t\t\t\t\t\tcblk->segs.head = 0;\n\t\t\t\t\t\t\t\tcblk->segs.tail = 0;\n\t\t\t\t\t\t\t\tcblk->curseg = 0;\n\t\t\t\t\t\t\t\tcblk->numimsbs = 0;\n\t\t\t\t\t\t\t\tcblk->numlenbits = 3;\n\t\t\t\t\t\t\t\tcblk->flags = 0;\n\t\t\t\t\t\t\t\tif (!(cblk->data = jas_seq2d_create(0, 0, 0,\n\t\t\t\t\t\t\t\t 0))) {\n\t\t\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tjas_seq2d_bindsub(cblk->data, band->data,\n\t\t\t\t\t\t\t\t tmpxstart, tmpystart, tmpxend, tmpyend);\n\t\t\t\t\t\t\t\t++cblk;\n\t\t\t\t\t\t\t\t--cblkcnt;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcblkxstart += 1 << rlvl->cblkwidthexpn;\n\t\t\t\t\t\t\tif (cblkxstart >= cbgxend) {\n\t\t\t\t\t\t\t\tcblkxstart = cbgxstart;\n\t\t\t\t\t\t\t\tcblkystart += 1 << rlvl->cblkheightexpn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\tprc->cblks = 0;\n\t\t\t\t\t\tprc->incltagtree = 0;\n\t\t\t\t\t\tprc->numimsbstagtree = 0;\n\t\t\t\t\t}\n\t\t\t\t\tcbgxstart += 1 << rlvl->cbgwidthexpn;\n\t\t\t\t\tif (cbgxstart >= brcbgxend) {\n\t\t\t\t\t\tcbgxstart = tlcbgxstart;\n\t\t\t\t\t\tcbgystart += 1 << rlvl->cbgheightexpn;\n\t\t\t\t\t}\n\n\t\t\t\t}\n/********************************************/\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!(tile->pi = jpc_dec_pi_create(dec, tile))) {\n\t\treturn -1;\n\t}\n\n\tfor (pchgno = 0; pchgno < jpc_pchglist_numpchgs(tile->cp->pchglist);\n\t ++pchgno) {\n\t\tpchg = jpc_pchg_copy(jpc_pchglist_get(tile->cp->pchglist, pchgno));\n\t\tassert(pchg);\n\t\tjpc_pi_addpchg(tile->pi, pchg);\n\t}\n\tjpc_pi_init(tile->pi);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fixed an array overflow problem in 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: int fixup_exception(struct pt_regs *regs)\n{\n\tconst struct exception_table_entry *fixup;\n\tunsigned long new_ip;\n\n#ifdef CONFIG_PNPBIOS\n\tif (unlikely(SEGMENT_IS_PNP_CODE(regs->cs))) {\n\t\textern u32 pnp_bios_fault_eip, pnp_bios_fault_esp;\n\t\textern u32 pnp_bios_is_utter_crap;\n\t\tpnp_bios_is_utter_crap = 1;\n\t\tprintk(KERN_CRIT \"PNPBIOS fault.. attempting recovery.\\n\");\n\t\t__asm__ volatile(\n\t\t\t\"movl %0, %%esp\\n\\t\"\n\t\t\t\"jmp *%1\\n\\t\"\n\t\t\t: : \"g\" (pnp_bios_fault_esp), \"g\" (pnp_bios_fault_eip));\n\t\tpanic(\"do_trap: can't hit this\");\n\t}\n#endif\n\n\tfixup = search_exception_tables(regs->ip);\n\tif (fixup) {\n\t\tnew_ip = ex_fixup_addr(fixup);\n\n\t\tif (fixup->fixup - fixup->insn >= 0x7ffffff0 - 4) {\n\t\t\t/* Special hack for uaccess_err */\n\t\t\tcurrent_thread_info()->uaccess_err = 1;\n\t\t\tnew_ip -= 0x7ffffff0;\n\t\t}\n\t\tregs->ip = new_ip;\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-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: addMultirowsForm(Buffer *buf, AnchorList *al)\n{\n int i, j, k, col, ecol, pos;\n Anchor a_form, *a;\n Line *l, *ls;\n\n if (al == NULL || al->nanchor == 0)\n\treturn;\n for (i = 0; i < al->nanchor; i++) {\n\ta_form = al->anchors[i];\n\tal->anchors[i].rows = 1;\n\tif (a_form.hseq < 0 || a_form.rows <= 1)\n\t continue;\n\tfor (l = buf->firstLine; l != NULL; l = l->next) {\n\t if (l->linenumber == a_form.y)\n\t\tbreak;\n\t}\n\tif (!l)\n\t continue;\n\tif (a_form.y == a_form.start.line)\n\t ls = l;\n\telse {\n\t for (ls = l; ls != NULL;\n\t\t ls = (a_form.y < a_form.start.line) ? ls->next : ls->prev) {\n\t\tif (ls->linenumber == a_form.start.line)\n\t\t break;\n\t }\n\t if (!ls)\n\t\tcontinue;\n\t}\n\tcol = COLPOS(ls, a_form.start.pos);\n\tecol = COLPOS(ls, a_form.end.pos);\n\tfor (j = 0; l && j < a_form.rows; l = l->next, j++) {\n\t pos = columnPos(l, col);\n\t if (j == 0) {\n\t\tbuf->hmarklist->marks[a_form.hseq].line = l->linenumber;\n\t\tbuf->hmarklist->marks[a_form.hseq].pos = pos;\n\t }\n\t if (a_form.start.line == l->linenumber)\n\t\tcontinue;\n\t buf->formitem = putAnchor(buf->formitem, a_form.url,\n\t\t\t\t a_form.target, &a, NULL, NULL, '\\0',\n\t\t\t\t l->linenumber, pos);\n\t a->hseq = a_form.hseq;\n\t a->y = a_form.y;\n\t a->end.pos = pos + ecol - col;\n\t l->lineBuf[pos - 1] = '[';\n\t l->lineBuf[a->end.pos] = ']';\n\t for (k = pos; k < a->end.pos; k++)\n\t\tl->propBuf[k] |= PE_FORM;\n\t}\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Prevent segfault due to buffer overflows in addMultirowsForm\n\nBug-Debian: https://github.com/tats/w3m/issues/21\nBug-Debian: https://github.com/tats/w3m/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: ptr_t GC_unix_get_mem(word bytes)\n{\n# if defined(MMAP_SUPPORTED)\n /* By default, we try both sbrk and mmap, in that order. */\n static GC_bool sbrk_failed = FALSE;\n ptr_t result = 0;\n\n if (!sbrk_failed) result = GC_unix_sbrk_get_mem(bytes);\n if (0 == result) {\n sbrk_failed = TRUE;\n result = GC_unix_mmap_get_mem(bytes);\n }\n if (0 == result) {\n /* Try sbrk again, in case sbrk memory became available. */\n result = GC_unix_sbrk_get_mem(bytes);\n }\n return result;\n# else /* !MMAP_SUPPORTED */\n return GC_unix_sbrk_get_mem(bytes);\n# endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix malloc routines to prevent size value wrap-around\n\nSee issue #135 on Github.\n\n* allchblk.c (GC_allochblk, GC_allochblk_nth): Use\nOBJ_SZ_TO_BLOCKS_CHECKED instead of OBJ_SZ_TO_BLOCKS.\n* malloc.c (GC_alloc_large): Likewise.\n* alloc.c (GC_expand_hp_inner): Type of \"bytes\" local variable changed\nfrom word to size_t; cast ROUNDUP_PAGESIZE argument to size_t; prevent\noverflow when computing GC_heapsize+bytes > GC_max_heapsize.\n* dbg_mlc.c (GC_debug_malloc, GC_debug_malloc_ignore_off_page,\nGC_debug_malloc_atomic_ignore_off_page, GC_debug_generic_malloc,\nGC_debug_generic_malloc_inner,\nGC_debug_generic_malloc_inner_ignore_off_page,\nGC_debug_malloc_stubborn, GC_debug_malloc_atomic,\nGC_debug_malloc_uncollectable, GC_debug_malloc_atomic_uncollectable):\nUse SIZET_SAT_ADD (instead of \"+\" operator) to add extra bytes to lb\nvalue.\n* fnlz_mlc.c (GC_finalized_malloc): Likewise.\n* gcj_mlc.c (GC_debug_gcj_malloc): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, ROUNDUP_PAGESIZE): Likewise.\n* include/private/gcconfig.h (GET_MEM): Likewise.\n* mallocx.c (GC_malloc_many, GC_memalign): Likewise.\n* os_dep.c (GC_wince_get_mem, GC_win32_get_mem): Likewise.\n* typd_mlc.c (GC_malloc_explicitly_typed,\nGC_malloc_explicitly_typed_ignore_off_page,\nGC_calloc_explicitly_typed): Likewise.\n* headers.c (GC_scratch_alloc): Change type of bytes_to_get from word\nto size_t (because ROUNDUP_PAGESIZE_IF_MMAP result type changed).\n* include/private/gc_priv.h: Include limits.h (unless SIZE_MAX already\ndefined).\n* include/private/gc_priv.h (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Move from\nmalloc.c file.\n* include/private/gc_priv.h (SIZET_SAT_ADD): New macro (defined before\ninclude gcconfig.h).\n* include/private/gc_priv.h (EXTRA_BYTES, GC_page_size): Change type\nto size_t.\n* os_dep.c (GC_page_size): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, ROUNDUP_PAGESIZE): Add comment about the argument.\n* include/private/gcconfig.h (GET_MEM): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, OBJ_SZ_TO_BLOCKS, ROUNDUP_PAGESIZE,\nROUNDUP_PAGESIZE_IF_MMAP): Rename argument to \"lb\".\n* include/private/gc_priv.h (OBJ_SZ_TO_BLOCKS_CHECKED): New macro.\n* include/private/gcconfig.h (GC_win32_get_mem, GC_wince_get_mem,\nGC_unix_get_mem): Change argument type from word to int.\n* os_dep.c (GC_unix_mmap_get_mem, GC_unix_get_mem,\nGC_unix_sbrk_get_mem, GC_wince_get_mem, GC_win32_get_mem): Likewise.\n* malloc.c (GC_alloc_large_and_clear): Call OBJ_SZ_TO_BLOCKS only\nif no value wrap around is guaranteed.\n* malloc.c (GC_generic_malloc): Do not check for lb_rounded < lb case\n(because ROUNDED_UP_GRANULES and GRANULES_TO_BYTES guarantees no value\nwrap around).\n* mallocx.c (GC_generic_malloc_ignore_off_page): Likewise.\n* misc.c (GC_init_size_map): Change \"i\" local variable type from int\nto size_t.\n* os_dep.c (GC_write_fault_handler, catch_exception_raise): Likewise.\n* misc.c (GC_envfile_init): Cast len to size_t when passed to\nROUNDUP_PAGESIZE_IF_MMAP.\n* os_dep.c (GC_setpagesize): Cast GC_sysinfo.dwPageSize and\nGETPAGESIZE() to size_t (when setting GC_page_size).\n* os_dep.c (GC_unix_mmap_get_mem, GC_unmap_start, GC_remove_protection):\nExpand ROUNDUP_PAGESIZE macro but without value wrap-around checking\n(the argument is of word type).\n* os_dep.c (GC_unix_mmap_get_mem): Replace -GC_page_size with\n~GC_page_size+1 (because GC_page_size is unsigned); remove redundant\ncast to size_t.\n* os_dep.c (GC_unix_sbrk_get_mem): Add explicit cast of GC_page_size\nto SBRK_ARG_T.\n* os_dep.c (GC_wince_get_mem): Change type of res_bytes local variable\nto size_t.\n* typd_mlc.c: Do not include limits.h.\n* typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Remove (as defined in\ngc_priv.h now).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: GC_API GC_ATTR_MALLOC void * GC_CALL GC_generic_malloc(size_t lb, int k)\n{\n void * result;\n DCL_LOCK_STATE;\n\n GC_ASSERT(k < MAXOBJKINDS);\n if (EXPECT(GC_have_errors, FALSE))\n GC_print_all_errors();\n GC_INVOKE_FINALIZERS();\n GC_DBG_COLLECT_AT_MALLOC(lb);\n if (SMALL_OBJ(lb)) {\n LOCK();\n result = GC_generic_malloc_inner(lb, k);\n UNLOCK();\n } else {\n size_t lg;\n size_t lb_rounded;\n word n_blocks;\n GC_bool init;\n\n lg = ROUNDED_UP_GRANULES(lb);\n lb_rounded = GRANULES_TO_BYTES(lg);\n if (lb_rounded < lb)\n return((*GC_get_oom_fn())(lb));\n n_blocks = OBJ_SZ_TO_BLOCKS(lb_rounded);\n init = GC_obj_kinds[k].ok_init;\n LOCK();\n result = (ptr_t)GC_alloc_large(lb_rounded, k, 0);\n if (0 != result) {\n if (GC_debugging_started) {\n BZERO(result, n_blocks * HBLKSIZE);\n } else {\n# ifdef THREADS\n /* Clear any memory that might be used for GC descriptors */\n /* before we release the lock. */\n ((word *)result)[0] = 0;\n ((word *)result)[1] = 0;\n ((word *)result)[GRANULES_TO_WORDS(lg)-1] = 0;\n ((word *)result)[GRANULES_TO_WORDS(lg)-2] = 0;\n# endif\n }\n }\n GC_bytes_allocd += lb_rounded;\n UNLOCK();\n if (init && !GC_debugging_started && 0 != result) {\n BZERO(result, n_blocks * HBLKSIZE);\n }\n }\n if (0 == result) {\n return((*GC_get_oom_fn())(lb));\n } else {\n return(result);\n }\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_init_size_map(void)\n{\n int i;\n\n /* Map size 0 to something bigger. */\n /* This avoids problems at lower levels. */\n GC_size_map[0] = 1;\n for (i = 1; i <= GRANULES_TO_BYTES(TINY_FREELISTS-1) - EXTRA_BYTES; i++) {\n GC_size_map[i] = (unsigned)ROUNDED_UP_GRANULES(i);\n# ifndef _MSC_VER\n GC_ASSERT(GC_size_map[i] < TINY_FREELISTS);\n /* Seems to tickle bug in VC++ 2008 for AMD64 */\n# endif\n }\n /* We leave the rest of the array to be filled in on demand. */\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 ptr_t GC_unix_mmap_get_mem(word bytes)\n{\n void *result;\n static ptr_t last_addr = HEAP_START;\n\n# ifndef USE_MMAP_ANON\n static GC_bool initialized = FALSE;\n\n if (!EXPECT(initialized, TRUE)) {\n# ifdef SYMBIAN\n char* path = GC_get_private_path_and_zero_file();\n zero_fd = open(path, O_RDWR | O_CREAT, 0666);\n free(path);\n# else\n zero_fd = open(\"/dev/zero\", O_RDONLY);\n# endif\n if (zero_fd == -1)\n ABORT(\"Could not open /dev/zero\");\n if (fcntl(zero_fd, F_SETFD, FD_CLOEXEC) == -1)\n WARN(\"Could not set FD_CLOEXEC for /dev/zero\\n\", 0);\n\n initialized = TRUE;\n }\n# endif\n\n if (bytes & (GC_page_size - 1)) ABORT(\"Bad GET_MEM arg\");\n result = mmap(last_addr, bytes, (PROT_READ | PROT_WRITE)\n | (GC_pages_executable ? PROT_EXEC : 0),\n GC_MMAP_FLAGS | OPT_MAP_ANON, zero_fd, 0/* offset */);\n# undef IGNORE_PAGES_EXECUTABLE\n\n if (result == MAP_FAILED) return(0);\n last_addr = (ptr_t)ROUNDUP_PAGESIZE((word)result + bytes);\n# if !defined(LINUX)\n if (last_addr == 0) {\n /* Oops. We got the end of the address space. This isn't */\n /* usable by arbitrary C code, since one-past-end pointers */\n /* don't work, so we discard it and try again. */\n munmap(result, (size_t)(-GC_page_size) - (size_t)result);\n /* Leave last page mapped, so we can't repeat. */\n return GC_unix_mmap_get_mem(bytes);\n }\n# else\n GC_ASSERT(last_addr != 0);\n# endif\n if (((word)result % HBLKSIZE) != 0)\n ABORT(\n \"GC_unix_get_mem: Memory returned by mmap is not aligned to HBLKSIZE.\");\n return((ptr_t)result);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix malloc routines to prevent size value wrap-around\n\nSee issue #135 on Github.\n\n* allchblk.c (GC_allochblk, GC_allochblk_nth): Use\nOBJ_SZ_TO_BLOCKS_CHECKED instead of OBJ_SZ_TO_BLOCKS.\n* malloc.c (GC_alloc_large): Likewise.\n* alloc.c (GC_expand_hp_inner): Type of \"bytes\" local variable changed\nfrom word to size_t; cast ROUNDUP_PAGESIZE argument to size_t; prevent\noverflow when computing GC_heapsize+bytes > GC_max_heapsize.\n* dbg_mlc.c (GC_debug_malloc, GC_debug_malloc_ignore_off_page,\nGC_debug_malloc_atomic_ignore_off_page, GC_debug_generic_malloc,\nGC_debug_generic_malloc_inner,\nGC_debug_generic_malloc_inner_ignore_off_page,\nGC_debug_malloc_stubborn, GC_debug_malloc_atomic,\nGC_debug_malloc_uncollectable, GC_debug_malloc_atomic_uncollectable):\nUse SIZET_SAT_ADD (instead of \"+\" operator) to add extra bytes to lb\nvalue.\n* fnlz_mlc.c (GC_finalized_malloc): Likewise.\n* gcj_mlc.c (GC_debug_gcj_malloc): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, ROUNDUP_PAGESIZE): Likewise.\n* include/private/gcconfig.h (GET_MEM): Likewise.\n* mallocx.c (GC_malloc_many, GC_memalign): Likewise.\n* os_dep.c (GC_wince_get_mem, GC_win32_get_mem): Likewise.\n* typd_mlc.c (GC_malloc_explicitly_typed,\nGC_malloc_explicitly_typed_ignore_off_page,\nGC_calloc_explicitly_typed): Likewise.\n* headers.c (GC_scratch_alloc): Change type of bytes_to_get from word\nto size_t (because ROUNDUP_PAGESIZE_IF_MMAP result type changed).\n* include/private/gc_priv.h: Include limits.h (unless SIZE_MAX already\ndefined).\n* include/private/gc_priv.h (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Move from\nmalloc.c file.\n* include/private/gc_priv.h (SIZET_SAT_ADD): New macro (defined before\ninclude gcconfig.h).\n* include/private/gc_priv.h (EXTRA_BYTES, GC_page_size): Change type\nto size_t.\n* os_dep.c (GC_page_size): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, ROUNDUP_PAGESIZE): Add comment about the argument.\n* include/private/gcconfig.h (GET_MEM): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, OBJ_SZ_TO_BLOCKS, ROUNDUP_PAGESIZE,\nROUNDUP_PAGESIZE_IF_MMAP): Rename argument to \"lb\".\n* include/private/gc_priv.h (OBJ_SZ_TO_BLOCKS_CHECKED): New macro.\n* include/private/gcconfig.h (GC_win32_get_mem, GC_wince_get_mem,\nGC_unix_get_mem): Change argument type from word to int.\n* os_dep.c (GC_unix_mmap_get_mem, GC_unix_get_mem,\nGC_unix_sbrk_get_mem, GC_wince_get_mem, GC_win32_get_mem): Likewise.\n* malloc.c (GC_alloc_large_and_clear): Call OBJ_SZ_TO_BLOCKS only\nif no value wrap around is guaranteed.\n* malloc.c (GC_generic_malloc): Do not check for lb_rounded < lb case\n(because ROUNDED_UP_GRANULES and GRANULES_TO_BYTES guarantees no value\nwrap around).\n* mallocx.c (GC_generic_malloc_ignore_off_page): Likewise.\n* misc.c (GC_init_size_map): Change \"i\" local variable type from int\nto size_t.\n* os_dep.c (GC_write_fault_handler, catch_exception_raise): Likewise.\n* misc.c (GC_envfile_init): Cast len to size_t when passed to\nROUNDUP_PAGESIZE_IF_MMAP.\n* os_dep.c (GC_setpagesize): Cast GC_sysinfo.dwPageSize and\nGETPAGESIZE() to size_t (when setting GC_page_size).\n* os_dep.c (GC_unix_mmap_get_mem, GC_unmap_start, GC_remove_protection):\nExpand ROUNDUP_PAGESIZE macro but without value wrap-around checking\n(the argument is of word type).\n* os_dep.c (GC_unix_mmap_get_mem): Replace -GC_page_size with\n~GC_page_size+1 (because GC_page_size is unsigned); remove redundant\ncast to size_t.\n* os_dep.c (GC_unix_sbrk_get_mem): Add explicit cast of GC_page_size\nto SBRK_ARG_T.\n* os_dep.c (GC_wince_get_mem): Change type of res_bytes local variable\nto size_t.\n* typd_mlc.c: Do not include limits.h.\n* typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Remove (as defined in\ngc_priv.h now).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: HTMLtagproc1(struct parsed_tag *tag, struct html_feed_environ *h_env)\n{\n char *p, *q, *r;\n int i, w, x, y, z, count, width;\n struct readbuffer *obuf = h_env->obuf;\n struct environment *envs = h_env->envs;\n Str tmp;\n int hseq;\n int cmd;\n#ifdef ID_EXT\n char *id = NULL;\n#endif\t\t\t\t/* ID_EXT */\n\n cmd = tag->tagid;\n\n if (obuf->flag & RB_PRE) {\n\tswitch (cmd) {\n\tcase HTML_NOBR:\n\tcase HTML_N_NOBR:\n\tcase HTML_PRE_INT:\n\tcase HTML_N_PRE_INT:\n\t return 1;\n\t}\n }\n\n switch (cmd) {\n case HTML_B:\n\tobuf->in_bold++;\n\tif (obuf->in_bold > 1)\n\t return 1;\n\treturn 0;\n case HTML_N_B:\n\tif (obuf->in_bold == 1 && close_effect0(obuf, HTML_B))\n\t obuf->in_bold = 0;\n\tif (obuf->in_bold > 0) {\n\t obuf->in_bold--;\n\t if (obuf->in_bold == 0)\n\t\treturn 0;\n\t}\n\treturn 1;\n case HTML_I:\n\tobuf->in_italic++;\n\tif (obuf->in_italic > 1)\n\t return 1;\n\treturn 0;\n case HTML_N_I:\n\tif (obuf->in_italic == 1 && close_effect0(obuf, HTML_I))\n\t obuf->in_italic = 0;\n\tif (obuf->in_italic > 0) {\n\t obuf->in_italic--;\n\t if (obuf->in_italic == 0)\n\t\treturn 0;\n\t}\n\treturn 1;\n case HTML_U:\n\tobuf->in_under++;\n\tif (obuf->in_under > 1)\n\t return 1;\n\treturn 0;\n case HTML_N_U:\n\tif (obuf->in_under == 1 && close_effect0(obuf, HTML_U))\n\t obuf->in_under = 0;\n\tif (obuf->in_under > 0) {\n\t obuf->in_under--;\n\t if (obuf->in_under == 0)\n\t\treturn 0;\n\t}\n\treturn 1;\n case HTML_EM:\n\tHTMLlineproc1(\"\", h_env);\n\treturn 1;\n case HTML_N_EM:\n\tHTMLlineproc1(\"\", h_env);\n\treturn 1;\n case HTML_STRONG:\n\tHTMLlineproc1(\"\", h_env);\n\treturn 1;\n case HTML_N_STRONG:\n\tHTMLlineproc1(\"\", h_env);\n\treturn 1;\n case HTML_Q:\n\tHTMLlineproc1(\"`\", h_env);\n\treturn 1;\n case HTML_N_Q:\n\tHTMLlineproc1(\"'\", h_env);\n\treturn 1;\n case HTML_P:\n case HTML_N_P:\n\tCLOSE_A;\n\tif (!(obuf->flag & RB_IGNORE_P)) {\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 1, h_env->limit);\n\t do_blankline(h_env, obuf, envs[h_env->envc].indent, 0,\n\t\t\t h_env->limit);\n\t}\n\tobuf->flag |= RB_IGNORE_P;\n\tif (cmd == HTML_P) {\n\t set_alignment(obuf, tag);\n\t obuf->flag |= RB_P;\n\t}\n\treturn 1;\n case HTML_BR:\n\tflushline(h_env, obuf, envs[h_env->envc].indent, 1, h_env->limit);\n\th_env->blank_lines = 0;\n\treturn 1;\n case HTML_H:\n\tif (!(obuf->flag & (RB_PREMODE | RB_IGNORE_P))) {\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\t do_blankline(h_env, obuf, envs[h_env->envc].indent, 0,\n\t\t\t h_env->limit);\n\t}\n\tHTMLlineproc1(\"\", h_env);\n\tset_alignment(obuf, tag);\n\treturn 1;\n case HTML_N_H:\n\tHTMLlineproc1(\"\", h_env);\n\tif (!(obuf->flag & RB_PREMODE)) {\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\t}\n\tdo_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\tRB_RESTORE_FLAG(obuf);\n\tclose_anchor(h_env, obuf);\n\tobuf->flag |= RB_IGNORE_P;\n\treturn 1;\n case HTML_UL:\n case HTML_OL:\n case HTML_BLQ:\n\tCLOSE_A;\n\tif (!(obuf->flag & RB_IGNORE_P)) {\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\t if (!(obuf->flag & RB_PREMODE) &&\n\t\t(h_env->envc == 0 || cmd == HTML_BLQ))\n\t\tdo_blankline(h_env, obuf, envs[h_env->envc].indent, 0,\n\t\t\t h_env->limit);\n\t}\n\tPUSH_ENV(cmd);\n\tif (cmd == HTML_UL || cmd == HTML_OL) {\n\t if (parsedtag_get_value(tag, ATTR_START, &count)) {\n\t\tenvs[h_env->envc].count = count - 1;\n\t }\n\t}\n\tif (cmd == HTML_OL) {\n\t envs[h_env->envc].type = '1';\n\t if (parsedtag_get_value(tag, ATTR_TYPE, &p)) {\n\t\tenvs[h_env->envc].type = (int)*p;\n\t }\n\t}\n\tif (cmd == HTML_UL)\n\t envs[h_env->envc].type = ul_type(tag, 0);\n\tflushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\treturn 1;\n case HTML_N_UL:\n case HTML_N_OL:\n case HTML_N_DL:\n case HTML_N_BLQ:\n\tCLOSE_DT;\n\tCLOSE_A;\n\tif (h_env->envc > 0) {\n\t flushline(h_env, obuf, envs[h_env->envc - 1].indent, 0,\n\t\t h_env->limit);\n\t POP_ENV;\n\t if (!(obuf->flag & RB_PREMODE) &&\n\t\t(h_env->envc == 0 || cmd == HTML_N_DL || cmd == HTML_N_BLQ)) {\n\t\tdo_blankline(h_env, obuf,\n\t\t\t envs[h_env->envc].indent,\n\t\t\t INDENT_INCR, h_env->limit);\n\t\tobuf->flag |= RB_IGNORE_P;\n\t }\n\t}\n\tclose_anchor(h_env, obuf);\n\treturn 1;\n case HTML_DL:\n\tCLOSE_A;\n\tif (!(obuf->flag & RB_IGNORE_P)) {\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\t if (!(obuf->flag & RB_PREMODE))\n\t\tdo_blankline(h_env, obuf, envs[h_env->envc].indent, 0,\n\t\t\t h_env->limit);\n\t}\n\tPUSH_ENV(cmd);\n\tif (parsedtag_exists(tag, ATTR_COMPACT))\n\t envs[h_env->envc].env = HTML_DL_COMPACT;\n\tobuf->flag |= RB_IGNORE_P;\n\treturn 1;\n case HTML_LI:\n\tCLOSE_A;\n\tCLOSE_DT;\n\tif (h_env->envc > 0) {\n\t Str num;\n\t flushline(h_env, obuf,\n\t\t envs[h_env->envc - 1].indent, 0, h_env->limit);\n\t envs[h_env->envc].count++;\n\t if (parsedtag_get_value(tag, ATTR_VALUE, &p)) {\n\t\tcount = atoi(p);\n\t\tif (count > 0)\n\t\t envs[h_env->envc].count = count;\n\t\telse\n\t\t envs[h_env->envc].count = 0;\n\t }\n\t switch (envs[h_env->envc].env) {\n\t case HTML_UL:\n\t\tenvs[h_env->envc].type = ul_type(tag, envs[h_env->envc].type);\n\t\tfor (i = 0; i < INDENT_INCR - 3; i++)\n\t\t push_charp(obuf, 1, NBSP, PC_ASCII);\n\t\ttmp = Strnew();\n\t\tswitch (envs[h_env->envc].type) {\n\t\tcase 'd':\n\t\t push_symbol(tmp, UL_SYMBOL_DISC, symbol_width, 1);\n\t\t break;\n\t\tcase 'c':\n\t\t push_symbol(tmp, UL_SYMBOL_CIRCLE, symbol_width, 1);\n\t\t break;\n\t\tcase 's':\n\t\t push_symbol(tmp, UL_SYMBOL_SQUARE, symbol_width, 1);\n\t\t break;\n\t\tdefault:\n\t\t push_symbol(tmp,\n\t\t\t\tUL_SYMBOL((h_env->envc_real -\n\t\t\t\t\t 1) % MAX_UL_LEVEL), symbol_width,\n\t\t\t\t1);\n\t\t break;\n\t\t}\n\t\tif (symbol_width == 1)\n\t\t push_charp(obuf, 1, NBSP, PC_ASCII);\n\t\tpush_str(obuf, symbol_width, tmp, PC_ASCII);\n\t\tpush_charp(obuf, 1, NBSP, PC_ASCII);\n\t\tset_space_to_prevchar(obuf->prevchar);\n\t\tbreak;\n\t case HTML_OL:\n\t\tif (parsedtag_get_value(tag, ATTR_TYPE, &p))\n\t\t envs[h_env->envc].type = (int)*p;\n\t\tswitch ((envs[h_env->envc].count > 0)? envs[h_env->envc].type: '1') {\n\t\tcase 'i':\n\t\t num = romanNumeral(envs[h_env->envc].count);\n\t\t break;\n\t\tcase 'I':\n\t\t num = romanNumeral(envs[h_env->envc].count);\n\t\t Strupper(num);\n\t\t break;\n\t\tcase 'a':\n\t\t num = romanAlphabet(envs[h_env->envc].count);\n\t\t break;\n\t\tcase 'A':\n\t\t num = romanAlphabet(envs[h_env->envc].count);\n\t\t Strupper(num);\n\t\t break;\n\t\tdefault:\n\t\t num = Sprintf(\"%d\", envs[h_env->envc].count);\n\t\t break;\n\t\t}\n\t\tif (INDENT_INCR >= 4)\n\t\t Strcat_charp(num, \". \");\n\t\telse\n\t\t Strcat_char(num, '.');\n\t\tpush_spaces(obuf, 1, INDENT_INCR - num->length);\n\t\tpush_str(obuf, num->length, num, PC_ASCII);\n\t\tif (INDENT_INCR >= 4)\n\t\t set_space_to_prevchar(obuf->prevchar);\n\t\tbreak;\n\t default:\n\t\tpush_spaces(obuf, 1, INDENT_INCR);\n\t\tbreak;\n\t }\n\t}\n\telse {\n\t flushline(h_env, obuf, 0, 0, h_env->limit);\n\t}\n\tobuf->flag |= RB_IGNORE_P;\n\treturn 1;\n case HTML_DT:\n\tCLOSE_A;\n\tif (h_env->envc == 0 ||\n\t (h_env->envc_real < h_env->nenv &&\n\t envs[h_env->envc].env != HTML_DL &&\n\t envs[h_env->envc].env != HTML_DL_COMPACT)) {\n\t PUSH_ENV(HTML_DL);\n\t}\n\tif (h_env->envc > 0) {\n\t flushline(h_env, obuf,\n\t\t envs[h_env->envc - 1].indent, 0, h_env->limit);\n\t}\n\tif (!(obuf->flag & RB_IN_DT)) {\n\t HTMLlineproc1(\"\", h_env);\n\t obuf->flag |= RB_IN_DT;\n\t}\n\tobuf->flag |= RB_IGNORE_P;\n\treturn 1;\n case HTML_DD:\n\tCLOSE_A;\n\tCLOSE_DT;\n\tif (envs[h_env->envc].env == HTML_DL_COMPACT) {\n\t if (obuf->pos > envs[h_env->envc].indent)\n\t\tflushline(h_env, obuf, envs[h_env->envc].indent, 0,\n\t\t\t h_env->limit);\n\t else\n\t\tpush_spaces(obuf, 1, envs[h_env->envc].indent - obuf->pos);\n\t}\n\telse\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\t/* obuf->flag |= RB_IGNORE_P; */\n\treturn 1;\n case HTML_TITLE:\n\tclose_anchor(h_env, obuf);\n\tprocess_title(tag);\n\tobuf->flag |= RB_TITLE;\n\tobuf->end_tag = HTML_N_TITLE;\n\treturn 1;\n case HTML_N_TITLE:\n\tif (!(obuf->flag & RB_TITLE))\n\t return 1;\n\tobuf->flag &= ~RB_TITLE;\n\tobuf->end_tag = 0;\n\ttmp = process_n_title(tag);\n\tif (tmp)\n\t HTMLlineproc1(tmp->ptr, h_env);\n\treturn 1;\n case HTML_TITLE_ALT:\n\tif (parsedtag_get_value(tag, ATTR_TITLE, &p))\n\t h_env->title = html_unquote(p);\n\treturn 0;\n case HTML_FRAMESET:\n\tPUSH_ENV(cmd);\n\tpush_charp(obuf, 9, \"--FRAME--\", PC_ASCII);\n\tflushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\treturn 0;\n case HTML_N_FRAMESET:\n\tif (h_env->envc > 0) {\n\t POP_ENV;\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\t}\n\treturn 0;\n case HTML_NOFRAMES:\n\tCLOSE_A;\n\tflushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\tobuf->flag |= (RB_NOFRAMES | RB_IGNORE_P);\n\t/* istr = str; */\n\treturn 1;\n case HTML_N_NOFRAMES:\n\tCLOSE_A;\n\tflushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\tobuf->flag &= ~RB_NOFRAMES;\n\treturn 1;\n case HTML_FRAME:\n\tq = r = NULL;\n\tparsedtag_get_value(tag, ATTR_SRC, &q);\n\tparsedtag_get_value(tag, ATTR_NAME, &r);\n\tif (q) {\n\t q = html_quote(q);\n\t push_tag(obuf, Sprintf(\"\",\n\t\t\t\t cur_hseq++, q)->ptr, HTML_A);\n\t if (r)\n\t\tq = html_quote(r);\n\t push_charp(obuf, get_strwidth(q), q, PC_ASCII);\n\t push_tag(obuf, \"\", HTML_N_A);\n\t}\n\tflushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\treturn 0;\n case HTML_HR:\n\tclose_anchor(h_env, obuf);\n\ttmp = process_hr(tag, h_env->limit, envs[h_env->envc].indent);\n\tHTMLlineproc1(tmp->ptr, h_env);\n\tset_space_to_prevchar(obuf->prevchar);\n\treturn 1;\n case HTML_PRE:\n\tx = parsedtag_exists(tag, ATTR_FOR_TABLE);\n\tCLOSE_A;\n\tif (!(obuf->flag & RB_IGNORE_P)) {\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\t if (!x)\n\t\tdo_blankline(h_env, obuf, envs[h_env->envc].indent, 0,\n\t\t\t h_env->limit);\n\t}\n\telse\n\t fillline(obuf, envs[h_env->envc].indent);\n\tobuf->flag |= (RB_PRE | RB_IGNORE_P);\n\t/* istr = str; */\n\treturn 1;\n case HTML_N_PRE:\n\tflushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\tif (!(obuf->flag & RB_IGNORE_P)) {\n\t do_blankline(h_env, obuf, envs[h_env->envc].indent, 0,\n\t\t\t h_env->limit);\n\t obuf->flag |= RB_IGNORE_P;\n\t h_env->blank_lines++;\n\t}\n\tobuf->flag &= ~RB_PRE;\n\tclose_anchor(h_env, obuf);\n\treturn 1;\n case HTML_PRE_INT:\n\ti = obuf->line->length;\n\tappend_tags(obuf);\n\tif (!(obuf->flag & RB_SPECIAL)) {\n\t set_breakpoint(obuf, obuf->line->length - i);\n\t}\n\tobuf->flag |= RB_PRE_INT;\n\treturn 0;\n case HTML_N_PRE_INT:\n\tpush_tag(obuf, \"\", HTML_N_PRE_INT);\n\tobuf->flag &= ~RB_PRE_INT;\n\tif (!(obuf->flag & RB_SPECIAL) && obuf->pos > obuf->bp.pos) {\n\t set_prevchar(obuf->prevchar, \"\", 0);\n\t obuf->prev_ctype = PC_CTRL;\n\t}\n\treturn 1;\n case HTML_NOBR:\n\tobuf->flag |= RB_NOBR;\n\tobuf->nobr_level++;\n\treturn 0;\n case HTML_N_NOBR:\n\tif (obuf->nobr_level > 0)\n\t obuf->nobr_level--;\n\tif (obuf->nobr_level == 0)\n\t obuf->flag &= ~RB_NOBR;\n\treturn 0;\n case HTML_PRE_PLAIN:\n\tCLOSE_A;\n\tif (!(obuf->flag & RB_IGNORE_P)) {\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\t do_blankline(h_env, obuf, envs[h_env->envc].indent, 0,\n\t\t\t h_env->limit);\n\t}\n\tobuf->flag |= (RB_PRE | RB_IGNORE_P);\n\treturn 1;\n case HTML_N_PRE_PLAIN:\n\tCLOSE_A;\n\tif (!(obuf->flag & RB_IGNORE_P)) {\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\t do_blankline(h_env, obuf, envs[h_env->envc].indent, 0,\n\t\t\t h_env->limit);\n\t obuf->flag |= RB_IGNORE_P;\n\t}\n\tobuf->flag &= ~RB_PRE;\n\treturn 1;\n case HTML_LISTING:\n case HTML_XMP:\n case HTML_PLAINTEXT:\n\tCLOSE_A;\n\tif (!(obuf->flag & RB_IGNORE_P)) {\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\t do_blankline(h_env, obuf, envs[h_env->envc].indent, 0,\n\t\t\t h_env->limit);\n\t}\n\tobuf->flag |= (RB_PLAIN | RB_IGNORE_P);\n\tswitch (cmd) {\n\tcase HTML_LISTING:\n\t obuf->end_tag = HTML_N_LISTING;\n\t break;\n\tcase HTML_XMP:\n\t obuf->end_tag = HTML_N_XMP;\n\t break;\n\tcase HTML_PLAINTEXT:\n\t obuf->end_tag = MAX_HTMLTAG;\n\t break;\n\t}\n\treturn 1;\n case HTML_N_LISTING:\n case HTML_N_XMP:\n\tCLOSE_A;\n\tif (!(obuf->flag & RB_IGNORE_P)) {\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\t do_blankline(h_env, obuf, envs[h_env->envc].indent, 0,\n\t\t\t h_env->limit);\n\t obuf->flag |= RB_IGNORE_P;\n\t}\n\tobuf->flag &= ~RB_PLAIN;\n\tobuf->end_tag = 0;\n\treturn 1;\n case HTML_SCRIPT:\n\tobuf->flag |= RB_SCRIPT;\n\tobuf->end_tag = HTML_N_SCRIPT;\n\treturn 1;\n case HTML_STYLE:\n\tobuf->flag |= RB_STYLE;\n\tobuf->end_tag = HTML_N_STYLE;\n\treturn 1;\n case HTML_N_SCRIPT:\n\tobuf->flag &= ~RB_SCRIPT;\n\tobuf->end_tag = 0;\n\treturn 1;\n case HTML_N_STYLE:\n\tobuf->flag &= ~RB_STYLE;\n\tobuf->end_tag = 0;\n\treturn 1;\n case HTML_A:\n\tif (obuf->anchor.url)\n\t close_anchor(h_env, obuf);\n\n\thseq = 0;\n\n\tif (parsedtag_get_value(tag, ATTR_HREF, &p))\n\t obuf->anchor.url = Strnew_charp(p)->ptr;\n\tif (parsedtag_get_value(tag, ATTR_TARGET, &p))\n\t obuf->anchor.target = Strnew_charp(p)->ptr;\n\tif (parsedtag_get_value(tag, ATTR_REFERER, &p))\n\t obuf->anchor.referer = Strnew_charp(p)->ptr;\n\tif (parsedtag_get_value(tag, ATTR_TITLE, &p))\n\t obuf->anchor.title = Strnew_charp(p)->ptr;\n\tif (parsedtag_get_value(tag, ATTR_ACCESSKEY, &p))\n\t obuf->anchor.accesskey = (unsigned char)*p;\n\tif (parsedtag_get_value(tag, ATTR_HSEQ, &hseq))\n\t obuf->anchor.hseq = hseq;\n\n\tif (hseq == 0 && obuf->anchor.url) {\n\t obuf->anchor.hseq = cur_hseq;\n\t tmp = process_anchor(tag, h_env->tagbuf->ptr);\n\t push_tag(obuf, tmp->ptr, HTML_A);\n\t if (displayLinkNumber)\n\t\tHTMLlineproc1(getLinkNumberStr(-1)->ptr, h_env);\n\t return 1;\n\t}\n\treturn 0;\n case HTML_N_A:\n\tclose_anchor(h_env, obuf);\n\treturn 1;\n case HTML_IMG:\n\ttmp = process_img(tag, h_env->limit);\n\tHTMLlineproc1(tmp->ptr, h_env);\n\treturn 1;\n case HTML_IMG_ALT:\n\tif (parsedtag_get_value(tag, ATTR_SRC, &p))\n\t obuf->img_alt = Strnew_charp(p);\n#ifdef USE_IMAGE\n\ti = 0;\n\tif (parsedtag_get_value(tag, ATTR_TOP_MARGIN, &i)) {\n\t if (i > obuf->top_margin)\n\t\tobuf->top_margin = i;\n\t}\n\ti = 0;\n\tif (parsedtag_get_value(tag, ATTR_BOTTOM_MARGIN, &i)) {\n\t if (i > obuf->bottom_margin)\n\t\tobuf->bottom_margin = i;\n\t}\n#endif\n\treturn 0;\n case HTML_N_IMG_ALT:\n\tif (obuf->img_alt) {\n\t if (!close_effect0(obuf, HTML_IMG_ALT))\n\t\tpush_tag(obuf, \"\", HTML_N_IMG_ALT);\n\t obuf->img_alt = NULL;\n\t}\n\treturn 1;\n case HTML_INPUT_ALT:\n\ti = 0;\n\tif (parsedtag_get_value(tag, ATTR_TOP_MARGIN, &i)) {\n\t if (i > obuf->top_margin)\n\t\tobuf->top_margin = i;\n\t}\n\ti = 0;\n\tif (parsedtag_get_value(tag, ATTR_BOTTOM_MARGIN, &i)) {\n\t if (i > obuf->bottom_margin)\n\t\tobuf->bottom_margin = i;\n\t}\n\tif (parsedtag_get_value(tag, ATTR_HSEQ, &hseq)) {\n\t obuf->input_alt.hseq = hseq;\n\t}\n\tif (parsedtag_get_value(tag, ATTR_FID, &i)) {\n\t obuf->input_alt.fid = i;\n\t}\n\tif (parsedtag_get_value(tag, ATTR_TYPE, &p)) {\n\t obuf->input_alt.type = Strnew_charp(p);\n\t}\n\tif (parsedtag_get_value(tag, ATTR_VALUE, &p)) {\n\t obuf->input_alt.value = Strnew_charp(p);\n\t}\n\tif (parsedtag_get_value(tag, ATTR_NAME, &p)) {\n\t obuf->input_alt.name = Strnew_charp(p);\n\t}\n\tobuf->input_alt.in = 1;\n\treturn 0;\n case HTML_N_INPUT_ALT:\n\tif (obuf->input_alt.in) {\n\t if (!close_effect0(obuf, HTML_INPUT_ALT))\n\t\tpush_tag(obuf, \"\", HTML_N_INPUT_ALT);\n\t obuf->input_alt.hseq = 0;\n\t obuf->input_alt.fid = -1;\n\t obuf->input_alt.in = 0;\n\t obuf->input_alt.type = NULL;\n\t obuf->input_alt.name = NULL;\n\t obuf->input_alt.value = NULL;\n\t}\n\treturn 1;\n case HTML_TABLE:\n\tclose_anchor(h_env, obuf);\n\tobuf->table_level++;\n\tif (obuf->table_level >= MAX_TABLE)\n\t break;\n\tw = BORDER_NONE;\n\t/* x: cellspacing, y: cellpadding */\n\tx = 2;\n\ty = 1;\n\tz = 0;\n\twidth = 0;\n\tif (parsedtag_exists(tag, ATTR_BORDER)) {\n\t if (parsedtag_get_value(tag, ATTR_BORDER, &w)) {\n\t\tif (w > 2)\n\t\t w = BORDER_THICK;\n\t\telse if (w < 0) {\t/* weird */\n\t\t w = BORDER_THIN;\n\t\t}\n\t }\n\t else\n\t\tw = BORDER_THIN;\n\t}\n\tif (DisplayBorders && w == BORDER_NONE)\n\t w = BORDER_THIN;\n\tif (parsedtag_get_value(tag, ATTR_WIDTH, &i)) {\n\t if (obuf->table_level == 0)\n\t\twidth = REAL_WIDTH(i, h_env->limit - envs[h_env->envc].indent);\n\t else\n\t\twidth = RELATIVE_WIDTH(i);\n\t}\n\tif (parsedtag_exists(tag, ATTR_HBORDER))\n\t w = BORDER_NOWIN;\n#define MAX_CELLSPACING 1000\n#define MAX_CELLPADDING 1000\n#define MAX_VSPACE 1000\n\tparsedtag_get_value(tag, ATTR_CELLSPACING, &x);\n\tparsedtag_get_value(tag, ATTR_CELLPADDING, &y);\n\tparsedtag_get_value(tag, ATTR_VSPACE, &z);\n\tif (x > MAX_CELLSPACING)\n\t x = MAX_CELLSPACING;\n\tif (y > MAX_CELLPADDING)\n\t y = MAX_CELLPADDING;\n\tif (z > MAX_VSPACE)\n\t z = MAX_VSPACE;\n#ifdef ID_EXT\n\tparsedtag_get_value(tag, ATTR_ID, &id);\n#endif\t\t\t\t/* ID_EXT */\n\ttables[obuf->table_level] = begin_table(w, x, y, z);\n#ifdef ID_EXT\n\tif (id != NULL)\n\t tables[obuf->table_level]->id = Strnew_charp(id);\n#endif\t\t\t\t/* ID_EXT */\n\ttable_mode[obuf->table_level].pre_mode = 0;\n\ttable_mode[obuf->table_level].indent_level = 0;\n\ttable_mode[obuf->table_level].nobr_level = 0;\n\ttable_mode[obuf->table_level].caption = 0;\n\ttable_mode[obuf->table_level].end_tag = 0;\t/* HTML_UNKNOWN */\n#ifndef TABLE_EXPAND\n\ttables[obuf->table_level]->total_width = width;\n#else\n\ttables[obuf->table_level]->real_width = width;\n\ttables[obuf->table_level]->total_width = 0;\n#endif\n\treturn 1;\n case HTML_N_TABLE:\n\t/* should be processed in HTMLlineproc() */\n\treturn 1;\n case HTML_CENTER:\n\tCLOSE_A;\n\tif (!(obuf->flag & (RB_PREMODE | RB_IGNORE_P)))\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\tRB_SAVE_FLAG(obuf);\n\tRB_SET_ALIGN(obuf, RB_CENTER);\n\treturn 1;\n case HTML_N_CENTER:\n\tCLOSE_A;\n\tif (!(obuf->flag & RB_PREMODE))\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\tRB_RESTORE_FLAG(obuf);\n\treturn 1;\n case HTML_DIV:\n\tCLOSE_A;\n\tif (!(obuf->flag & RB_IGNORE_P))\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\tset_alignment(obuf, tag);\n\treturn 1;\n case HTML_N_DIV:\n\tCLOSE_A;\n\tflushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\tRB_RESTORE_FLAG(obuf);\n\treturn 1;\n case HTML_DIV_INT:\n\tCLOSE_P;\n\tif (!(obuf->flag & RB_IGNORE_P))\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\tset_alignment(obuf, tag);\n\treturn 1;\n case HTML_N_DIV_INT:\n\tCLOSE_P;\n\tflushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\tRB_RESTORE_FLAG(obuf);\n\treturn 1;\n case HTML_FORM:\n\tCLOSE_A;\n\tif (!(obuf->flag & RB_IGNORE_P))\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\ttmp = process_form(tag);\n\tif (tmp)\n\t HTMLlineproc1(tmp->ptr, h_env);\n\treturn 1;\n case HTML_N_FORM:\n\tCLOSE_A;\n\tflushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\tobuf->flag |= RB_IGNORE_P;\n\tprocess_n_form();\n\treturn 1;\n case HTML_INPUT:\n\tclose_anchor(h_env, obuf);\n\ttmp = process_input(tag);\n if (tmp)\n HTMLlineproc1(tmp->ptr, h_env);\n return 1;\n case HTML_BUTTON:\n tmp = process_button(tag);\n if (tmp)\n HTMLlineproc1(tmp->ptr, h_env);\n return 1;\n case HTML_N_BUTTON:\n tmp = process_n_button();\n\tif (tmp)\n\t HTMLlineproc1(tmp->ptr, h_env);\n\treturn 1;\n case HTML_SELECT:\n\tclose_anchor(h_env, obuf);\n\ttmp = process_select(tag);\n\tif (tmp)\n\t HTMLlineproc1(tmp->ptr, h_env);\n\tobuf->flag |= RB_INSELECT;\n\tobuf->end_tag = HTML_N_SELECT;\n\treturn 1;\n case HTML_N_SELECT:\n\tobuf->flag &= ~RB_INSELECT;\n\tobuf->end_tag = 0;\n\ttmp = process_n_select();\n\tif (tmp)\n\t HTMLlineproc1(tmp->ptr, h_env);\n\treturn 1;\n case HTML_OPTION:\n\t/* nothing */\n\treturn 1;\n case HTML_TEXTAREA:\n\tclose_anchor(h_env, obuf);\n\ttmp = process_textarea(tag, h_env->limit);\n\tif (tmp)\n\t HTMLlineproc1(tmp->ptr, h_env);\n\tobuf->flag |= RB_INTXTA;\n\tobuf->end_tag = HTML_N_TEXTAREA;\n\treturn 1;\n case HTML_N_TEXTAREA:\n\tobuf->flag &= ~RB_INTXTA;\n\tobuf->end_tag = 0;\n\ttmp = process_n_textarea();\n\tif (tmp)\n\t HTMLlineproc1(tmp->ptr, h_env);\n\treturn 1;\n case HTML_ISINDEX:\n\tp = \"\";\n\tq = \"!CURRENT_URL!\";\n\tparsedtag_get_value(tag, ATTR_PROMPT, &p);\n\tparsedtag_get_value(tag, ATTR_ACTION, &q);\n\ttmp = Strnew_m_charp(\"
\",\n\t\t\t html_quote(p),\n\t\t\t \"
\",\n\t\t\t NULL);\n\tHTMLlineproc1(tmp->ptr, h_env);\n\treturn 1;\n case HTML_META:\n\tp = q = r = NULL;\n\tparsedtag_get_value(tag, ATTR_HTTP_EQUIV, &p);\n\tparsedtag_get_value(tag, ATTR_CONTENT, &q);\n#ifdef USE_M17N\n\tparsedtag_get_value(tag, ATTR_CHARSET, &r);\n\tif (r) {\n\t /* */\n\t SKIP_BLANKS(r);\n\t meta_charset = wc_guess_charset(r, 0);\n\t}\n\telse\n\tif (p && q && !strcasecmp(p, \"Content-Type\") &&\n\t (q = strcasestr(q, \"charset\")) != NULL) {\n\t q += 7;\n\t SKIP_BLANKS(q);\n\t if (*q == '=') {\n\t\tq++;\n\t\tSKIP_BLANKS(q);\n\t\tmeta_charset = wc_guess_charset(q, 0);\n\t }\n\t}\n\telse\n#endif\n\tif (p && q && !strcasecmp(p, \"refresh\")) {\n\t int refresh_interval;\n\t tmp = NULL;\n\t refresh_interval = getMetaRefreshParam(q, &tmp);\n\t if (tmp) {\n\t\tq = html_quote(tmp->ptr);\n\t\ttmp = Sprintf(\"Refresh (%d sec) %s\",\n\t\t\t refresh_interval, q, q);\n\t }\n\t else if (refresh_interval > 0)\n\t\ttmp = Sprintf(\"Refresh (%d sec)\", refresh_interval);\n\t if (tmp) {\n\t\tHTMLlineproc1(tmp->ptr, h_env);\n\t\tdo_blankline(h_env, obuf, envs[h_env->envc].indent, 0,\n\t\t\t h_env->limit);\n\t\tif (!is_redisplay &&\n\t\t !((obuf->flag & RB_NOFRAMES) && RenderFrame)) {\n\t\t tag->need_reconstruct = TRUE;\n\t\t return 0;\n\t\t}\n\t }\n\t}\n\treturn 1;\n case HTML_BASE:\n#if defined(USE_M17N) || defined(USE_IMAGE)\n\tp = NULL;\n\tif (parsedtag_get_value(tag, ATTR_HREF, &p)) {\n\t cur_baseURL = New(ParsedURL);\n\t parseURL(p, cur_baseURL, NULL);\n\t}\n#endif\n case HTML_MAP:\n case HTML_N_MAP:\n case HTML_AREA:\n\treturn 0;\n case HTML_DEL:\n\tswitch (displayInsDel) {\n\tcase DISPLAY_INS_DEL_SIMPLE:\n\t obuf->flag |= RB_DEL;\n\t break;\n\tcase DISPLAY_INS_DEL_NORMAL:\n\t HTMLlineproc1(\"[DEL:\", h_env);\n\t break;\n\tcase DISPLAY_INS_DEL_FONTIFY:\n\t obuf->in_strike++;\n\t if (obuf->in_strike == 1) {\n\t\tpush_tag(obuf, \"\", HTML_S);\n\t }\n\t break;\n\t}\n\treturn 1;\n case HTML_N_DEL:\n\tswitch (displayInsDel) {\n\tcase DISPLAY_INS_DEL_SIMPLE:\n\t obuf->flag &= ~RB_DEL;\n\t break;\n\tcase DISPLAY_INS_DEL_NORMAL:\n\t HTMLlineproc1(\":DEL]\", h_env);\n\tcase DISPLAY_INS_DEL_FONTIFY:\n\t if (obuf->in_strike == 0)\n\t\treturn 1;\n\t if (obuf->in_strike == 1 && close_effect0(obuf, HTML_S))\n\t\tobuf->in_strike = 0;\n\t if (obuf->in_strike > 0) {\n\t\tobuf->in_strike--;\n\t\tif (obuf->in_strike == 0) {\n\t\t push_tag(obuf, \"\", HTML_N_S);\n\t\t}\n\t }\n\t break;\n\t}\n\treturn 1;\n case HTML_S:\n\tswitch (displayInsDel) {\n\tcase DISPLAY_INS_DEL_SIMPLE:\n\t obuf->flag |= RB_S;\n\t break;\n\tcase DISPLAY_INS_DEL_NORMAL:\n\t HTMLlineproc1(\"[S:\", h_env);\n\t break;\n\tcase DISPLAY_INS_DEL_FONTIFY:\n\t obuf->in_strike++;\n\t if (obuf->in_strike == 1) {\n\t\tpush_tag(obuf, \"\", HTML_S);\n\t }\n\t break;\n\t}\n\treturn 1;\n case HTML_N_S:\n\tswitch (displayInsDel) {\n\tcase DISPLAY_INS_DEL_SIMPLE:\n\t obuf->flag &= ~RB_S;\n\t break;\n\tcase DISPLAY_INS_DEL_NORMAL:\n\t HTMLlineproc1(\":S]\", h_env);\n\t break;\n\tcase DISPLAY_INS_DEL_FONTIFY:\n\t if (obuf->in_strike == 0)\n\t\treturn 1;\n\t if (obuf->in_strike == 1 && close_effect0(obuf, HTML_S))\n\t\tobuf->in_strike = 0;\n\t if (obuf->in_strike > 0) {\n\t\tobuf->in_strike--;\n\t\tif (obuf->in_strike == 0) {\n\t\t push_tag(obuf, \"\", HTML_N_S);\n\t\t}\n\t }\n\t}\n\treturn 1;\n case HTML_INS:\n\tswitch (displayInsDel) {\n\tcase DISPLAY_INS_DEL_SIMPLE:\n\t break;\n\tcase DISPLAY_INS_DEL_NORMAL:\n\t HTMLlineproc1(\"[INS:\", h_env);\n\t break;\n\tcase DISPLAY_INS_DEL_FONTIFY:\n\t obuf->in_ins++;\n\t if (obuf->in_ins == 1) {\n\t\tpush_tag(obuf, \"\", HTML_INS);\n\t }\n\t break;\n\t}\n\treturn 1;\n case HTML_N_INS:\n\tswitch (displayInsDel) {\n\tcase DISPLAY_INS_DEL_SIMPLE:\n\t break;\n\tcase DISPLAY_INS_DEL_NORMAL:\n\t HTMLlineproc1(\":INS]\", h_env);\n\t break;\n\tcase DISPLAY_INS_DEL_FONTIFY:\n\t if (obuf->in_ins == 0)\n\t\treturn 1;\n\t if (obuf->in_ins == 1 && close_effect0(obuf, HTML_INS))\n\t\tobuf->in_ins = 0;\n\t if (obuf->in_ins > 0) {\n\t\tobuf->in_ins--;\n\t\tif (obuf->in_ins == 0) {\n\t\t push_tag(obuf, \"\", HTML_N_INS);\n\t\t}\n\t }\n\t break;\n\t}\n\treturn 1;\n case HTML_SUP:\n\tif (!(obuf->flag & (RB_DEL | RB_S)))\n\t HTMLlineproc1(\"^\", h_env);\n\treturn 1;\n case HTML_N_SUP:\n\treturn 1;\n case HTML_SUB:\n\tif (!(obuf->flag & (RB_DEL | RB_S)))\n\t HTMLlineproc1(\"[\", h_env);\n\treturn 1;\n case HTML_N_SUB:\n\tif (!(obuf->flag & (RB_DEL | RB_S)))\n\t HTMLlineproc1(\"]\", h_env);\n\treturn 1;\n case HTML_FONT:\n case HTML_N_FONT:\n case HTML_NOP:\n\treturn 1;\n case HTML_BGSOUND:\n\tif (view_unseenobject) {\n\t if (parsedtag_get_value(tag, ATTR_SRC, &p)) {\n\t\tStr s;\n\t\tq = html_quote(p);\n\t\ts = Sprintf(\"bgsound(%s)\", q, q);\n\t\tHTMLlineproc1(s->ptr, h_env);\n\t }\n\t}\n\treturn 1;\n case HTML_EMBED:\n\tif (view_unseenobject) {\n\t if (parsedtag_get_value(tag, ATTR_SRC, &p)) {\n\t\tStr s;\n\t\tq = html_quote(p);\n\t\ts = Sprintf(\"embed(%s)\", q, q);\n\t\tHTMLlineproc1(s->ptr, h_env);\n\t }\n\t}\n\treturn 1;\n case HTML_APPLET:\n\tif (view_unseenobject) {\n\t if (parsedtag_get_value(tag, ATTR_ARCHIVE, &p)) {\n\t\tStr s;\n\t\tq = html_quote(p);\n\t\ts = Sprintf(\"applet archive(%s)\", q, q);\n\t\tHTMLlineproc1(s->ptr, h_env);\n\t }\n\t}\n\treturn 1;\n case HTML_BODY:\n\tif (view_unseenobject) {\n\t if (parsedtag_get_value(tag, ATTR_BACKGROUND, &p)) {\n\t\tStr s;\n\t\tq = html_quote(p);\n\t\ts = Sprintf(\"\\\"bg
\", q, q);\n\t\tHTMLlineproc1(s->ptr, h_env);\n\t }\n\t}\n case HTML_N_HEAD:\n\tif (obuf->flag & RB_TITLE)\n\t HTMLlineproc1(\"\", h_env);\n case HTML_HEAD:\n case HTML_N_BODY:\n\treturn 1;\n default:\n\t/* obuf->prevchar = '\\0'; */\n\treturn 0;\n }\n /* not reached */\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-476'], 'message': 'Fix uninitialised values for and
\n\nBug-Debian: https://github.com/tats/w3m/issues/16'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: HTMLtagproc1(struct parsed_tag *tag, struct html_feed_environ *h_env)\n{\n char *p, *q, *r;\n int i, w, x, y, z, count, width;\n struct readbuffer *obuf = h_env->obuf;\n struct environment *envs = h_env->envs;\n Str tmp;\n int hseq;\n int cmd;\n#ifdef ID_EXT\n char *id = NULL;\n#endif\t\t\t\t/* ID_EXT */\n\n cmd = tag->tagid;\n\n if (obuf->flag & RB_PRE) {\n\tswitch (cmd) {\n\tcase HTML_NOBR:\n\tcase HTML_N_NOBR:\n\tcase HTML_PRE_INT:\n\tcase HTML_N_PRE_INT:\n\t return 1;\n\t}\n }\n\n switch (cmd) {\n case HTML_B:\n\tobuf->in_bold++;\n\tif (obuf->in_bold > 1)\n\t return 1;\n\treturn 0;\n case HTML_N_B:\n\tif (obuf->in_bold == 1 && close_effect0(obuf, HTML_B))\n\t obuf->in_bold = 0;\n\tif (obuf->in_bold > 0) {\n\t obuf->in_bold--;\n\t if (obuf->in_bold == 0)\n\t\treturn 0;\n\t}\n\treturn 1;\n case HTML_I:\n\tobuf->in_italic++;\n\tif (obuf->in_italic > 1)\n\t return 1;\n\treturn 0;\n case HTML_N_I:\n\tif (obuf->in_italic == 1 && close_effect0(obuf, HTML_I))\n\t obuf->in_italic = 0;\n\tif (obuf->in_italic > 0) {\n\t obuf->in_italic--;\n\t if (obuf->in_italic == 0)\n\t\treturn 0;\n\t}\n\treturn 1;\n case HTML_U:\n\tobuf->in_under++;\n\tif (obuf->in_under > 1)\n\t return 1;\n\treturn 0;\n case HTML_N_U:\n\tif (obuf->in_under == 1 && close_effect0(obuf, HTML_U))\n\t obuf->in_under = 0;\n\tif (obuf->in_under > 0) {\n\t obuf->in_under--;\n\t if (obuf->in_under == 0)\n\t\treturn 0;\n\t}\n\treturn 1;\n case HTML_EM:\n\tHTMLlineproc1(\"\", h_env);\n\treturn 1;\n case HTML_N_EM:\n\tHTMLlineproc1(\"\", h_env);\n\treturn 1;\n case HTML_STRONG:\n\tHTMLlineproc1(\"\", h_env);\n\treturn 1;\n case HTML_N_STRONG:\n\tHTMLlineproc1(\"\", h_env);\n\treturn 1;\n case HTML_Q:\n\tHTMLlineproc1(\"`\", h_env);\n\treturn 1;\n case HTML_N_Q:\n\tHTMLlineproc1(\"'\", h_env);\n\treturn 1;\n case HTML_P:\n case HTML_N_P:\n\tCLOSE_A;\n\tif (!(obuf->flag & RB_IGNORE_P)) {\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 1, h_env->limit);\n\t do_blankline(h_env, obuf, envs[h_env->envc].indent, 0,\n\t\t\t h_env->limit);\n\t}\n\tobuf->flag |= RB_IGNORE_P;\n\tif (cmd == HTML_P) {\n\t set_alignment(obuf, tag);\n\t obuf->flag |= RB_P;\n\t}\n\treturn 1;\n case HTML_BR:\n\tflushline(h_env, obuf, envs[h_env->envc].indent, 1, h_env->limit);\n\th_env->blank_lines = 0;\n\treturn 1;\n case HTML_H:\n\tif (!(obuf->flag & (RB_PREMODE | RB_IGNORE_P))) {\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\t do_blankline(h_env, obuf, envs[h_env->envc].indent, 0,\n\t\t\t h_env->limit);\n\t}\n\tHTMLlineproc1(\"\", h_env);\n\tset_alignment(obuf, tag);\n\treturn 1;\n case HTML_N_H:\n\tHTMLlineproc1(\"\", h_env);\n\tif (!(obuf->flag & RB_PREMODE)) {\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\t}\n\tdo_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\tRB_RESTORE_FLAG(obuf);\n\tclose_anchor(h_env, obuf);\n\tobuf->flag |= RB_IGNORE_P;\n\treturn 1;\n case HTML_UL:\n case HTML_OL:\n case HTML_BLQ:\n\tCLOSE_A;\n\tif (!(obuf->flag & RB_IGNORE_P)) {\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\t if (!(obuf->flag & RB_PREMODE) &&\n\t\t(h_env->envc == 0 || cmd == HTML_BLQ))\n\t\tdo_blankline(h_env, obuf, envs[h_env->envc].indent, 0,\n\t\t\t h_env->limit);\n\t}\n\tPUSH_ENV(cmd);\n\tif (cmd == HTML_UL || cmd == HTML_OL) {\n\t if (parsedtag_get_value(tag, ATTR_START, &count)) {\n\t\tenvs[h_env->envc].count = count - 1;\n\t }\n\t}\n\tif (cmd == HTML_OL) {\n\t envs[h_env->envc].type = '1';\n\t if (parsedtag_get_value(tag, ATTR_TYPE, &p)) {\n\t\tenvs[h_env->envc].type = (int)*p;\n\t }\n\t}\n\tif (cmd == HTML_UL)\n\t envs[h_env->envc].type = ul_type(tag, 0);\n\tflushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\treturn 1;\n case HTML_N_UL:\n case HTML_N_OL:\n case HTML_N_DL:\n case HTML_N_BLQ:\n\tCLOSE_DT;\n\tCLOSE_A;\n\tif (h_env->envc > 0) {\n\t flushline(h_env, obuf, envs[h_env->envc - 1].indent, 0,\n\t\t h_env->limit);\n\t POP_ENV;\n\t if (!(obuf->flag & RB_PREMODE) &&\n\t\t(h_env->envc == 0 || cmd == HTML_N_DL || cmd == HTML_N_BLQ)) {\n\t\tdo_blankline(h_env, obuf,\n\t\t\t envs[h_env->envc].indent,\n\t\t\t INDENT_INCR, h_env->limit);\n\t\tobuf->flag |= RB_IGNORE_P;\n\t }\n\t}\n\tclose_anchor(h_env, obuf);\n\treturn 1;\n case HTML_DL:\n\tCLOSE_A;\n\tif (!(obuf->flag & RB_IGNORE_P)) {\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\t if (!(obuf->flag & RB_PREMODE))\n\t\tdo_blankline(h_env, obuf, envs[h_env->envc].indent, 0,\n\t\t\t h_env->limit);\n\t}\n\tPUSH_ENV(cmd);\n\tif (parsedtag_exists(tag, ATTR_COMPACT))\n\t envs[h_env->envc].env = HTML_DL_COMPACT;\n\tobuf->flag |= RB_IGNORE_P;\n\treturn 1;\n case HTML_LI:\n\tCLOSE_A;\n\tCLOSE_DT;\n\tif (h_env->envc > 0) {\n\t Str num;\n\t flushline(h_env, obuf,\n\t\t envs[h_env->envc - 1].indent, 0, h_env->limit);\n\t envs[h_env->envc].count++;\n\t if (parsedtag_get_value(tag, ATTR_VALUE, &p)) {\n\t\tcount = atoi(p);\n\t\tif (count > 0)\n\t\t envs[h_env->envc].count = count;\n\t\telse\n\t\t envs[h_env->envc].count = 0;\n\t }\n\t switch (envs[h_env->envc].env) {\n\t case HTML_UL:\n\t\tenvs[h_env->envc].type = ul_type(tag, envs[h_env->envc].type);\n\t\tfor (i = 0; i < INDENT_INCR - 3; i++)\n\t\t push_charp(obuf, 1, NBSP, PC_ASCII);\n\t\ttmp = Strnew();\n\t\tswitch (envs[h_env->envc].type) {\n\t\tcase 'd':\n\t\t push_symbol(tmp, UL_SYMBOL_DISC, symbol_width, 1);\n\t\t break;\n\t\tcase 'c':\n\t\t push_symbol(tmp, UL_SYMBOL_CIRCLE, symbol_width, 1);\n\t\t break;\n\t\tcase 's':\n\t\t push_symbol(tmp, UL_SYMBOL_SQUARE, symbol_width, 1);\n\t\t break;\n\t\tdefault:\n\t\t push_symbol(tmp,\n\t\t\t\tUL_SYMBOL((h_env->envc_real -\n\t\t\t\t\t 1) % MAX_UL_LEVEL), symbol_width,\n\t\t\t\t1);\n\t\t break;\n\t\t}\n\t\tif (symbol_width == 1)\n\t\t push_charp(obuf, 1, NBSP, PC_ASCII);\n\t\tpush_str(obuf, symbol_width, tmp, PC_ASCII);\n\t\tpush_charp(obuf, 1, NBSP, PC_ASCII);\n\t\tset_space_to_prevchar(obuf->prevchar);\n\t\tbreak;\n\t case HTML_OL:\n\t\tif (parsedtag_get_value(tag, ATTR_TYPE, &p))\n\t\t envs[h_env->envc].type = (int)*p;\n\t\tswitch ((envs[h_env->envc].count > 0)? envs[h_env->envc].type: '1') {\n\t\tcase 'i':\n\t\t num = romanNumeral(envs[h_env->envc].count);\n\t\t break;\n\t\tcase 'I':\n\t\t num = romanNumeral(envs[h_env->envc].count);\n\t\t Strupper(num);\n\t\t break;\n\t\tcase 'a':\n\t\t num = romanAlphabet(envs[h_env->envc].count);\n\t\t break;\n\t\tcase 'A':\n\t\t num = romanAlphabet(envs[h_env->envc].count);\n\t\t Strupper(num);\n\t\t break;\n\t\tdefault:\n\t\t num = Sprintf(\"%d\", envs[h_env->envc].count);\n\t\t break;\n\t\t}\n\t\tif (INDENT_INCR >= 4)\n\t\t Strcat_charp(num, \". \");\n\t\telse\n\t\t Strcat_char(num, '.');\n\t\tpush_spaces(obuf, 1, INDENT_INCR - num->length);\n\t\tpush_str(obuf, num->length, num, PC_ASCII);\n\t\tif (INDENT_INCR >= 4)\n\t\t set_space_to_prevchar(obuf->prevchar);\n\t\tbreak;\n\t default:\n\t\tpush_spaces(obuf, 1, INDENT_INCR);\n\t\tbreak;\n\t }\n\t}\n\telse {\n\t flushline(h_env, obuf, 0, 0, h_env->limit);\n\t}\n\tobuf->flag |= RB_IGNORE_P;\n\treturn 1;\n case HTML_DT:\n\tCLOSE_A;\n\tif (h_env->envc == 0 ||\n\t (h_env->envc_real < h_env->nenv &&\n\t envs[h_env->envc].env != HTML_DL &&\n\t envs[h_env->envc].env != HTML_DL_COMPACT)) {\n\t PUSH_ENV(HTML_DL);\n\t}\n\tif (h_env->envc > 0) {\n\t flushline(h_env, obuf,\n\t\t envs[h_env->envc - 1].indent, 0, h_env->limit);\n\t}\n\tif (!(obuf->flag & RB_IN_DT)) {\n\t HTMLlineproc1(\"\", h_env);\n\t obuf->flag |= RB_IN_DT;\n\t}\n\tobuf->flag |= RB_IGNORE_P;\n\treturn 1;\n case HTML_DD:\n\tCLOSE_A;\n\tCLOSE_DT;\n\tif (h_env->envc == 0 ||\n\t (h_env->envc_real < h_env->nenv &&\n\t envs[h_env->envc].env != HTML_DL &&\n\t envs[h_env->envc].env != HTML_DL_COMPACT)) {\n\t PUSH_ENV(HTML_DL);\n\t}\n\tif (envs[h_env->envc].env == HTML_DL_COMPACT) {\n\t if (obuf->pos > envs[h_env->envc].indent)\n\t\tflushline(h_env, obuf, envs[h_env->envc].indent, 0,\n\t\t\t h_env->limit);\n\t else\n\t\tpush_spaces(obuf, 1, envs[h_env->envc].indent - obuf->pos);\n\t}\n\telse\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\t/* obuf->flag |= RB_IGNORE_P; */\n\treturn 1;\n case HTML_TITLE:\n\tclose_anchor(h_env, obuf);\n\tprocess_title(tag);\n\tobuf->flag |= RB_TITLE;\n\tobuf->end_tag = HTML_N_TITLE;\n\treturn 1;\n case HTML_N_TITLE:\n\tif (!(obuf->flag & RB_TITLE))\n\t return 1;\n\tobuf->flag &= ~RB_TITLE;\n\tobuf->end_tag = 0;\n\ttmp = process_n_title(tag);\n\tif (tmp)\n\t HTMLlineproc1(tmp->ptr, h_env);\n\treturn 1;\n case HTML_TITLE_ALT:\n\tif (parsedtag_get_value(tag, ATTR_TITLE, &p))\n\t h_env->title = html_unquote(p);\n\treturn 0;\n case HTML_FRAMESET:\n\tPUSH_ENV(cmd);\n\tpush_charp(obuf, 9, \"--FRAME--\", PC_ASCII);\n\tflushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\treturn 0;\n case HTML_N_FRAMESET:\n\tif (h_env->envc > 0) {\n\t POP_ENV;\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\t}\n\treturn 0;\n case HTML_NOFRAMES:\n\tCLOSE_A;\n\tflushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\tobuf->flag |= (RB_NOFRAMES | RB_IGNORE_P);\n\t/* istr = str; */\n\treturn 1;\n case HTML_N_NOFRAMES:\n\tCLOSE_A;\n\tflushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\tobuf->flag &= ~RB_NOFRAMES;\n\treturn 1;\n case HTML_FRAME:\n\tq = r = NULL;\n\tparsedtag_get_value(tag, ATTR_SRC, &q);\n\tparsedtag_get_value(tag, ATTR_NAME, &r);\n\tif (q) {\n\t q = html_quote(q);\n\t push_tag(obuf, Sprintf(\"\",\n\t\t\t\t cur_hseq++, q)->ptr, HTML_A);\n\t if (r)\n\t\tq = html_quote(r);\n\t push_charp(obuf, get_strwidth(q), q, PC_ASCII);\n\t push_tag(obuf, \"\", HTML_N_A);\n\t}\n\tflushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\treturn 0;\n case HTML_HR:\n\tclose_anchor(h_env, obuf);\n\ttmp = process_hr(tag, h_env->limit, envs[h_env->envc].indent);\n\tHTMLlineproc1(tmp->ptr, h_env);\n\tset_space_to_prevchar(obuf->prevchar);\n\treturn 1;\n case HTML_PRE:\n\tx = parsedtag_exists(tag, ATTR_FOR_TABLE);\n\tCLOSE_A;\n\tif (!(obuf->flag & RB_IGNORE_P)) {\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\t if (!x)\n\t\tdo_blankline(h_env, obuf, envs[h_env->envc].indent, 0,\n\t\t\t h_env->limit);\n\t}\n\telse\n\t fillline(obuf, envs[h_env->envc].indent);\n\tobuf->flag |= (RB_PRE | RB_IGNORE_P);\n\t/* istr = str; */\n\treturn 1;\n case HTML_N_PRE:\n\tflushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\tif (!(obuf->flag & RB_IGNORE_P)) {\n\t do_blankline(h_env, obuf, envs[h_env->envc].indent, 0,\n\t\t\t h_env->limit);\n\t obuf->flag |= RB_IGNORE_P;\n\t h_env->blank_lines++;\n\t}\n\tobuf->flag &= ~RB_PRE;\n\tclose_anchor(h_env, obuf);\n\treturn 1;\n case HTML_PRE_INT:\n\ti = obuf->line->length;\n\tappend_tags(obuf);\n\tif (!(obuf->flag & RB_SPECIAL)) {\n\t set_breakpoint(obuf, obuf->line->length - i);\n\t}\n\tobuf->flag |= RB_PRE_INT;\n\treturn 0;\n case HTML_N_PRE_INT:\n\tpush_tag(obuf, \"\", HTML_N_PRE_INT);\n\tobuf->flag &= ~RB_PRE_INT;\n\tif (!(obuf->flag & RB_SPECIAL) && obuf->pos > obuf->bp.pos) {\n\t set_prevchar(obuf->prevchar, \"\", 0);\n\t obuf->prev_ctype = PC_CTRL;\n\t}\n\treturn 1;\n case HTML_NOBR:\n\tobuf->flag |= RB_NOBR;\n\tobuf->nobr_level++;\n\treturn 0;\n case HTML_N_NOBR:\n\tif (obuf->nobr_level > 0)\n\t obuf->nobr_level--;\n\tif (obuf->nobr_level == 0)\n\t obuf->flag &= ~RB_NOBR;\n\treturn 0;\n case HTML_PRE_PLAIN:\n\tCLOSE_A;\n\tif (!(obuf->flag & RB_IGNORE_P)) {\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\t do_blankline(h_env, obuf, envs[h_env->envc].indent, 0,\n\t\t\t h_env->limit);\n\t}\n\tobuf->flag |= (RB_PRE | RB_IGNORE_P);\n\treturn 1;\n case HTML_N_PRE_PLAIN:\n\tCLOSE_A;\n\tif (!(obuf->flag & RB_IGNORE_P)) {\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\t do_blankline(h_env, obuf, envs[h_env->envc].indent, 0,\n\t\t\t h_env->limit);\n\t obuf->flag |= RB_IGNORE_P;\n\t}\n\tobuf->flag &= ~RB_PRE;\n\treturn 1;\n case HTML_LISTING:\n case HTML_XMP:\n case HTML_PLAINTEXT:\n\tCLOSE_A;\n\tif (!(obuf->flag & RB_IGNORE_P)) {\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\t do_blankline(h_env, obuf, envs[h_env->envc].indent, 0,\n\t\t\t h_env->limit);\n\t}\n\tobuf->flag |= (RB_PLAIN | RB_IGNORE_P);\n\tswitch (cmd) {\n\tcase HTML_LISTING:\n\t obuf->end_tag = HTML_N_LISTING;\n\t break;\n\tcase HTML_XMP:\n\t obuf->end_tag = HTML_N_XMP;\n\t break;\n\tcase HTML_PLAINTEXT:\n\t obuf->end_tag = MAX_HTMLTAG;\n\t break;\n\t}\n\treturn 1;\n case HTML_N_LISTING:\n case HTML_N_XMP:\n\tCLOSE_A;\n\tif (!(obuf->flag & RB_IGNORE_P)) {\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\t do_blankline(h_env, obuf, envs[h_env->envc].indent, 0,\n\t\t\t h_env->limit);\n\t obuf->flag |= RB_IGNORE_P;\n\t}\n\tobuf->flag &= ~RB_PLAIN;\n\tobuf->end_tag = 0;\n\treturn 1;\n case HTML_SCRIPT:\n\tobuf->flag |= RB_SCRIPT;\n\tobuf->end_tag = HTML_N_SCRIPT;\n\treturn 1;\n case HTML_STYLE:\n\tobuf->flag |= RB_STYLE;\n\tobuf->end_tag = HTML_N_STYLE;\n\treturn 1;\n case HTML_N_SCRIPT:\n\tobuf->flag &= ~RB_SCRIPT;\n\tobuf->end_tag = 0;\n\treturn 1;\n case HTML_N_STYLE:\n\tobuf->flag &= ~RB_STYLE;\n\tobuf->end_tag = 0;\n\treturn 1;\n case HTML_A:\n\tif (obuf->anchor.url)\n\t close_anchor(h_env, obuf);\n\n\thseq = 0;\n\n\tif (parsedtag_get_value(tag, ATTR_HREF, &p))\n\t obuf->anchor.url = Strnew_charp(p)->ptr;\n\tif (parsedtag_get_value(tag, ATTR_TARGET, &p))\n\t obuf->anchor.target = Strnew_charp(p)->ptr;\n\tif (parsedtag_get_value(tag, ATTR_REFERER, &p))\n\t obuf->anchor.referer = Strnew_charp(p)->ptr;\n\tif (parsedtag_get_value(tag, ATTR_TITLE, &p))\n\t obuf->anchor.title = Strnew_charp(p)->ptr;\n\tif (parsedtag_get_value(tag, ATTR_ACCESSKEY, &p))\n\t obuf->anchor.accesskey = (unsigned char)*p;\n\tif (parsedtag_get_value(tag, ATTR_HSEQ, &hseq))\n\t obuf->anchor.hseq = hseq;\n\n\tif (hseq == 0 && obuf->anchor.url) {\n\t obuf->anchor.hseq = cur_hseq;\n\t tmp = process_anchor(tag, h_env->tagbuf->ptr);\n\t push_tag(obuf, tmp->ptr, HTML_A);\n\t if (displayLinkNumber)\n\t\tHTMLlineproc1(getLinkNumberStr(-1)->ptr, h_env);\n\t return 1;\n\t}\n\treturn 0;\n case HTML_N_A:\n\tclose_anchor(h_env, obuf);\n\treturn 1;\n case HTML_IMG:\n\ttmp = process_img(tag, h_env->limit);\n\tHTMLlineproc1(tmp->ptr, h_env);\n\treturn 1;\n case HTML_IMG_ALT:\n\tif (parsedtag_get_value(tag, ATTR_SRC, &p))\n\t obuf->img_alt = Strnew_charp(p);\n#ifdef USE_IMAGE\n\ti = 0;\n\tif (parsedtag_get_value(tag, ATTR_TOP_MARGIN, &i)) {\n\t if (i > obuf->top_margin)\n\t\tobuf->top_margin = i;\n\t}\n\ti = 0;\n\tif (parsedtag_get_value(tag, ATTR_BOTTOM_MARGIN, &i)) {\n\t if (i > obuf->bottom_margin)\n\t\tobuf->bottom_margin = i;\n\t}\n#endif\n\treturn 0;\n case HTML_N_IMG_ALT:\n\tif (obuf->img_alt) {\n\t if (!close_effect0(obuf, HTML_IMG_ALT))\n\t\tpush_tag(obuf, \"\", HTML_N_IMG_ALT);\n\t obuf->img_alt = NULL;\n\t}\n\treturn 1;\n case HTML_INPUT_ALT:\n\ti = 0;\n\tif (parsedtag_get_value(tag, ATTR_TOP_MARGIN, &i)) {\n\t if (i > obuf->top_margin)\n\t\tobuf->top_margin = i;\n\t}\n\ti = 0;\n\tif (parsedtag_get_value(tag, ATTR_BOTTOM_MARGIN, &i)) {\n\t if (i > obuf->bottom_margin)\n\t\tobuf->bottom_margin = i;\n\t}\n\tif (parsedtag_get_value(tag, ATTR_HSEQ, &hseq)) {\n\t obuf->input_alt.hseq = hseq;\n\t}\n\tif (parsedtag_get_value(tag, ATTR_FID, &i)) {\n\t obuf->input_alt.fid = i;\n\t}\n\tif (parsedtag_get_value(tag, ATTR_TYPE, &p)) {\n\t obuf->input_alt.type = Strnew_charp(p);\n\t}\n\tif (parsedtag_get_value(tag, ATTR_VALUE, &p)) {\n\t obuf->input_alt.value = Strnew_charp(p);\n\t}\n\tif (parsedtag_get_value(tag, ATTR_NAME, &p)) {\n\t obuf->input_alt.name = Strnew_charp(p);\n\t}\n\tobuf->input_alt.in = 1;\n\treturn 0;\n case HTML_N_INPUT_ALT:\n\tif (obuf->input_alt.in) {\n\t if (!close_effect0(obuf, HTML_INPUT_ALT))\n\t\tpush_tag(obuf, \"\", HTML_N_INPUT_ALT);\n\t obuf->input_alt.hseq = 0;\n\t obuf->input_alt.fid = -1;\n\t obuf->input_alt.in = 0;\n\t obuf->input_alt.type = NULL;\n\t obuf->input_alt.name = NULL;\n\t obuf->input_alt.value = NULL;\n\t}\n\treturn 1;\n case HTML_TABLE:\n\tclose_anchor(h_env, obuf);\n\tobuf->table_level++;\n\tif (obuf->table_level >= MAX_TABLE)\n\t break;\n\tw = BORDER_NONE;\n\t/* x: cellspacing, y: cellpadding */\n\tx = 2;\n\ty = 1;\n\tz = 0;\n\twidth = 0;\n\tif (parsedtag_exists(tag, ATTR_BORDER)) {\n\t if (parsedtag_get_value(tag, ATTR_BORDER, &w)) {\n\t\tif (w > 2)\n\t\t w = BORDER_THICK;\n\t\telse if (w < 0) {\t/* weird */\n\t\t w = BORDER_THIN;\n\t\t}\n\t }\n\t else\n\t\tw = BORDER_THIN;\n\t}\n\tif (DisplayBorders && w == BORDER_NONE)\n\t w = BORDER_THIN;\n\tif (parsedtag_get_value(tag, ATTR_WIDTH, &i)) {\n\t if (obuf->table_level == 0)\n\t\twidth = REAL_WIDTH(i, h_env->limit - envs[h_env->envc].indent);\n\t else\n\t\twidth = RELATIVE_WIDTH(i);\n\t}\n\tif (parsedtag_exists(tag, ATTR_HBORDER))\n\t w = BORDER_NOWIN;\n#define MAX_CELLSPACING 1000\n#define MAX_CELLPADDING 1000\n#define MAX_VSPACE 1000\n\tparsedtag_get_value(tag, ATTR_CELLSPACING, &x);\n\tparsedtag_get_value(tag, ATTR_CELLPADDING, &y);\n\tparsedtag_get_value(tag, ATTR_VSPACE, &z);\n\tif (x > MAX_CELLSPACING)\n\t x = MAX_CELLSPACING;\n\tif (y > MAX_CELLPADDING)\n\t y = MAX_CELLPADDING;\n\tif (z > MAX_VSPACE)\n\t z = MAX_VSPACE;\n#ifdef ID_EXT\n\tparsedtag_get_value(tag, ATTR_ID, &id);\n#endif\t\t\t\t/* ID_EXT */\n\ttables[obuf->table_level] = begin_table(w, x, y, z);\n#ifdef ID_EXT\n\tif (id != NULL)\n\t tables[obuf->table_level]->id = Strnew_charp(id);\n#endif\t\t\t\t/* ID_EXT */\n\ttable_mode[obuf->table_level].pre_mode = 0;\n\ttable_mode[obuf->table_level].indent_level = 0;\n\ttable_mode[obuf->table_level].nobr_level = 0;\n\ttable_mode[obuf->table_level].caption = 0;\n\ttable_mode[obuf->table_level].end_tag = 0;\t/* HTML_UNKNOWN */\n#ifndef TABLE_EXPAND\n\ttables[obuf->table_level]->total_width = width;\n#else\n\ttables[obuf->table_level]->real_width = width;\n\ttables[obuf->table_level]->total_width = 0;\n#endif\n\treturn 1;\n case HTML_N_TABLE:\n\t/* should be processed in HTMLlineproc() */\n\treturn 1;\n case HTML_CENTER:\n\tCLOSE_A;\n\tif (!(obuf->flag & (RB_PREMODE | RB_IGNORE_P)))\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\tRB_SAVE_FLAG(obuf);\n\tRB_SET_ALIGN(obuf, RB_CENTER);\n\treturn 1;\n case HTML_N_CENTER:\n\tCLOSE_A;\n\tif (!(obuf->flag & RB_PREMODE))\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\tRB_RESTORE_FLAG(obuf);\n\treturn 1;\n case HTML_DIV:\n\tCLOSE_A;\n\tif (!(obuf->flag & RB_IGNORE_P))\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\tset_alignment(obuf, tag);\n\treturn 1;\n case HTML_N_DIV:\n\tCLOSE_A;\n\tflushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\tRB_RESTORE_FLAG(obuf);\n\treturn 1;\n case HTML_DIV_INT:\n\tCLOSE_P;\n\tif (!(obuf->flag & RB_IGNORE_P))\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\tset_alignment(obuf, tag);\n\treturn 1;\n case HTML_N_DIV_INT:\n\tCLOSE_P;\n\tflushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\tRB_RESTORE_FLAG(obuf);\n\treturn 1;\n case HTML_FORM:\n\tCLOSE_A;\n\tif (!(obuf->flag & RB_IGNORE_P))\n\t flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\ttmp = process_form(tag);\n\tif (tmp)\n\t HTMLlineproc1(tmp->ptr, h_env);\n\treturn 1;\n case HTML_N_FORM:\n\tCLOSE_A;\n\tflushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit);\n\tobuf->flag |= RB_IGNORE_P;\n\tprocess_n_form();\n\treturn 1;\n case HTML_INPUT:\n\tclose_anchor(h_env, obuf);\n\ttmp = process_input(tag);\n if (tmp)\n HTMLlineproc1(tmp->ptr, h_env);\n return 1;\n case HTML_BUTTON:\n tmp = process_button(tag);\n if (tmp)\n HTMLlineproc1(tmp->ptr, h_env);\n return 1;\n case HTML_N_BUTTON:\n tmp = process_n_button();\n\tif (tmp)\n\t HTMLlineproc1(tmp->ptr, h_env);\n\treturn 1;\n case HTML_SELECT:\n\tclose_anchor(h_env, obuf);\n\ttmp = process_select(tag);\n\tif (tmp)\n\t HTMLlineproc1(tmp->ptr, h_env);\n\tobuf->flag |= RB_INSELECT;\n\tobuf->end_tag = HTML_N_SELECT;\n\treturn 1;\n case HTML_N_SELECT:\n\tobuf->flag &= ~RB_INSELECT;\n\tobuf->end_tag = 0;\n\ttmp = process_n_select();\n\tif (tmp)\n\t HTMLlineproc1(tmp->ptr, h_env);\n\treturn 1;\n case HTML_OPTION:\n\t/* nothing */\n\treturn 1;\n case HTML_TEXTAREA:\n\tclose_anchor(h_env, obuf);\n\ttmp = process_textarea(tag, h_env->limit);\n\tif (tmp)\n\t HTMLlineproc1(tmp->ptr, h_env);\n\tobuf->flag |= RB_INTXTA;\n\tobuf->end_tag = HTML_N_TEXTAREA;\n\treturn 1;\n case HTML_N_TEXTAREA:\n\tobuf->flag &= ~RB_INTXTA;\n\tobuf->end_tag = 0;\n\ttmp = process_n_textarea();\n\tif (tmp)\n\t HTMLlineproc1(tmp->ptr, h_env);\n\treturn 1;\n case HTML_ISINDEX:\n\tp = \"\";\n\tq = \"!CURRENT_URL!\";\n\tparsedtag_get_value(tag, ATTR_PROMPT, &p);\n\tparsedtag_get_value(tag, ATTR_ACTION, &q);\n\ttmp = Strnew_m_charp(\"
\",\n\t\t\t html_quote(p),\n\t\t\t \"
\",\n\t\t\t NULL);\n\tHTMLlineproc1(tmp->ptr, h_env);\n\treturn 1;\n case HTML_META:\n\tp = q = r = NULL;\n\tparsedtag_get_value(tag, ATTR_HTTP_EQUIV, &p);\n\tparsedtag_get_value(tag, ATTR_CONTENT, &q);\n#ifdef USE_M17N\n\tparsedtag_get_value(tag, ATTR_CHARSET, &r);\n\tif (r) {\n\t /* */\n\t SKIP_BLANKS(r);\n\t meta_charset = wc_guess_charset(r, 0);\n\t}\n\telse\n\tif (p && q && !strcasecmp(p, \"Content-Type\") &&\n\t (q = strcasestr(q, \"charset\")) != NULL) {\n\t q += 7;\n\t SKIP_BLANKS(q);\n\t if (*q == '=') {\n\t\tq++;\n\t\tSKIP_BLANKS(q);\n\t\tmeta_charset = wc_guess_charset(q, 0);\n\t }\n\t}\n\telse\n#endif\n\tif (p && q && !strcasecmp(p, \"refresh\")) {\n\t int refresh_interval;\n\t tmp = NULL;\n\t refresh_interval = getMetaRefreshParam(q, &tmp);\n\t if (tmp) {\n\t\tq = html_quote(tmp->ptr);\n\t\ttmp = Sprintf(\"Refresh (%d sec) %s\",\n\t\t\t refresh_interval, q, q);\n\t }\n\t else if (refresh_interval > 0)\n\t\ttmp = Sprintf(\"Refresh (%d sec)\", refresh_interval);\n\t if (tmp) {\n\t\tHTMLlineproc1(tmp->ptr, h_env);\n\t\tdo_blankline(h_env, obuf, envs[h_env->envc].indent, 0,\n\t\t\t h_env->limit);\n\t\tif (!is_redisplay &&\n\t\t !((obuf->flag & RB_NOFRAMES) && RenderFrame)) {\n\t\t tag->need_reconstruct = TRUE;\n\t\t return 0;\n\t\t}\n\t }\n\t}\n\treturn 1;\n case HTML_BASE:\n#if defined(USE_M17N) || defined(USE_IMAGE)\n\tp = NULL;\n\tif (parsedtag_get_value(tag, ATTR_HREF, &p)) {\n\t cur_baseURL = New(ParsedURL);\n\t parseURL(p, cur_baseURL, NULL);\n\t}\n#endif\n case HTML_MAP:\n case HTML_N_MAP:\n case HTML_AREA:\n\treturn 0;\n case HTML_DEL:\n\tswitch (displayInsDel) {\n\tcase DISPLAY_INS_DEL_SIMPLE:\n\t obuf->flag |= RB_DEL;\n\t break;\n\tcase DISPLAY_INS_DEL_NORMAL:\n\t HTMLlineproc1(\"[DEL:\", h_env);\n\t break;\n\tcase DISPLAY_INS_DEL_FONTIFY:\n\t obuf->in_strike++;\n\t if (obuf->in_strike == 1) {\n\t\tpush_tag(obuf, \"\", HTML_S);\n\t }\n\t break;\n\t}\n\treturn 1;\n case HTML_N_DEL:\n\tswitch (displayInsDel) {\n\tcase DISPLAY_INS_DEL_SIMPLE:\n\t obuf->flag &= ~RB_DEL;\n\t break;\n\tcase DISPLAY_INS_DEL_NORMAL:\n\t HTMLlineproc1(\":DEL]\", h_env);\n\tcase DISPLAY_INS_DEL_FONTIFY:\n\t if (obuf->in_strike == 0)\n\t\treturn 1;\n\t if (obuf->in_strike == 1 && close_effect0(obuf, HTML_S))\n\t\tobuf->in_strike = 0;\n\t if (obuf->in_strike > 0) {\n\t\tobuf->in_strike--;\n\t\tif (obuf->in_strike == 0) {\n\t\t push_tag(obuf, \"\", HTML_N_S);\n\t\t}\n\t }\n\t break;\n\t}\n\treturn 1;\n case HTML_S:\n\tswitch (displayInsDel) {\n\tcase DISPLAY_INS_DEL_SIMPLE:\n\t obuf->flag |= RB_S;\n\t break;\n\tcase DISPLAY_INS_DEL_NORMAL:\n\t HTMLlineproc1(\"[S:\", h_env);\n\t break;\n\tcase DISPLAY_INS_DEL_FONTIFY:\n\t obuf->in_strike++;\n\t if (obuf->in_strike == 1) {\n\t\tpush_tag(obuf, \"\", HTML_S);\n\t }\n\t break;\n\t}\n\treturn 1;\n case HTML_N_S:\n\tswitch (displayInsDel) {\n\tcase DISPLAY_INS_DEL_SIMPLE:\n\t obuf->flag &= ~RB_S;\n\t break;\n\tcase DISPLAY_INS_DEL_NORMAL:\n\t HTMLlineproc1(\":S]\", h_env);\n\t break;\n\tcase DISPLAY_INS_DEL_FONTIFY:\n\t if (obuf->in_strike == 0)\n\t\treturn 1;\n\t if (obuf->in_strike == 1 && close_effect0(obuf, HTML_S))\n\t\tobuf->in_strike = 0;\n\t if (obuf->in_strike > 0) {\n\t\tobuf->in_strike--;\n\t\tif (obuf->in_strike == 0) {\n\t\t push_tag(obuf, \"\", HTML_N_S);\n\t\t}\n\t }\n\t}\n\treturn 1;\n case HTML_INS:\n\tswitch (displayInsDel) {\n\tcase DISPLAY_INS_DEL_SIMPLE:\n\t break;\n\tcase DISPLAY_INS_DEL_NORMAL:\n\t HTMLlineproc1(\"[INS:\", h_env);\n\t break;\n\tcase DISPLAY_INS_DEL_FONTIFY:\n\t obuf->in_ins++;\n\t if (obuf->in_ins == 1) {\n\t\tpush_tag(obuf, \"\", HTML_INS);\n\t }\n\t break;\n\t}\n\treturn 1;\n case HTML_N_INS:\n\tswitch (displayInsDel) {\n\tcase DISPLAY_INS_DEL_SIMPLE:\n\t break;\n\tcase DISPLAY_INS_DEL_NORMAL:\n\t HTMLlineproc1(\":INS]\", h_env);\n\t break;\n\tcase DISPLAY_INS_DEL_FONTIFY:\n\t if (obuf->in_ins == 0)\n\t\treturn 1;\n\t if (obuf->in_ins == 1 && close_effect0(obuf, HTML_INS))\n\t\tobuf->in_ins = 0;\n\t if (obuf->in_ins > 0) {\n\t\tobuf->in_ins--;\n\t\tif (obuf->in_ins == 0) {\n\t\t push_tag(obuf, \"\", HTML_N_INS);\n\t\t}\n\t }\n\t break;\n\t}\n\treturn 1;\n case HTML_SUP:\n\tif (!(obuf->flag & (RB_DEL | RB_S)))\n\t HTMLlineproc1(\"^\", h_env);\n\treturn 1;\n case HTML_N_SUP:\n\treturn 1;\n case HTML_SUB:\n\tif (!(obuf->flag & (RB_DEL | RB_S)))\n\t HTMLlineproc1(\"[\", h_env);\n\treturn 1;\n case HTML_N_SUB:\n\tif (!(obuf->flag & (RB_DEL | RB_S)))\n\t HTMLlineproc1(\"]\", h_env);\n\treturn 1;\n case HTML_FONT:\n case HTML_N_FONT:\n case HTML_NOP:\n\treturn 1;\n case HTML_BGSOUND:\n\tif (view_unseenobject) {\n\t if (parsedtag_get_value(tag, ATTR_SRC, &p)) {\n\t\tStr s;\n\t\tq = html_quote(p);\n\t\ts = Sprintf(\"bgsound(%s)\", q, q);\n\t\tHTMLlineproc1(s->ptr, h_env);\n\t }\n\t}\n\treturn 1;\n case HTML_EMBED:\n\tif (view_unseenobject) {\n\t if (parsedtag_get_value(tag, ATTR_SRC, &p)) {\n\t\tStr s;\n\t\tq = html_quote(p);\n\t\ts = Sprintf(\"embed(%s)\", q, q);\n\t\tHTMLlineproc1(s->ptr, h_env);\n\t }\n\t}\n\treturn 1;\n case HTML_APPLET:\n\tif (view_unseenobject) {\n\t if (parsedtag_get_value(tag, ATTR_ARCHIVE, &p)) {\n\t\tStr s;\n\t\tq = html_quote(p);\n\t\ts = Sprintf(\"applet archive(%s)\", q, q);\n\t\tHTMLlineproc1(s->ptr, h_env);\n\t }\n\t}\n\treturn 1;\n case HTML_BODY:\n\tif (view_unseenobject) {\n\t if (parsedtag_get_value(tag, ATTR_BACKGROUND, &p)) {\n\t\tStr s;\n\t\tq = html_quote(p);\n\t\ts = Sprintf(\"\\\"bg
\", q, q);\n\t\tHTMLlineproc1(s->ptr, h_env);\n\t }\n\t}\n case HTML_N_HEAD:\n\tif (obuf->flag & RB_TITLE)\n\t HTMLlineproc1(\"\", h_env);\n case HTML_HEAD:\n case HTML_N_BODY:\n\treturn 1;\n default:\n\t/* obuf->prevchar = '\\0'; */\n\treturn 0;\n }\n /* not reached */\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Prevent crash after allocate string of negative size\n\nBug-Debian: https://github.com/tats/w3m/issues/33'
" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: parseURL(char *url, ParsedURL *p_url, ParsedURL *current)\n{\n char *p, *q, *qq;\n Str tmp;\n\n url = url_quote(url);\t/* quote 0x01-0x20, 0x7F-0xFF */\n\n p = url;\n copyParsedURL(p_url, NULL);\n p_url->scheme = SCM_MISSING;\n\n /* RFC1808: Relative Uniform Resource Locators\n * 4. Resolving Relative URLs\n */\n if (*url == '\\0' || *url == '#') {\n\tif (current)\n\t copyParsedURL(p_url, current);\n\tgoto do_label;\n }\n#if defined( __EMX__ ) || defined( __CYGWIN__ )\n if (!strncasecmp(url, \"file://localhost/\", 17)) {\n\tp_url->scheme = SCM_LOCAL;\n\tp += 17 - 1;\n\turl += 17 - 1;\n }\n#endif\n#ifdef SUPPORT_DOS_DRIVE_PREFIX\n if (IS_ALPHA(*p) && (p[1] == ':' || p[1] == '|')) {\n\tp_url->scheme = SCM_LOCAL;\n\tgoto analyze_file;\n }\n#endif\t\t\t\t/* SUPPORT_DOS_DRIVE_PREFIX */\n /* search for scheme */\n p_url->scheme = getURLScheme(&p);\n if (p_url->scheme == SCM_MISSING) {\n\t/* scheme part is not found in the url. This means either\n\t * (a) the url is relative to the current or (b) the url\n\t * denotes a filename (therefore the scheme is SCM_LOCAL).\n\t */\n\tif (current) {\n\t switch (current->scheme) {\n\t case SCM_LOCAL:\n\t case SCM_LOCAL_CGI:\n\t\tp_url->scheme = SCM_LOCAL;\n\t\tbreak;\n\t case SCM_FTP:\n\t case SCM_FTPDIR:\n\t\tp_url->scheme = SCM_FTP;\n\t\tbreak;\n#ifdef USE_NNTP\n\t case SCM_NNTP:\n\t case SCM_NNTP_GROUP:\n\t\tp_url->scheme = SCM_NNTP;\n\t\tbreak;\n\t case SCM_NEWS:\n\t case SCM_NEWS_GROUP:\n\t\tp_url->scheme = SCM_NEWS;\n\t\tbreak;\n#endif\n\t default:\n\t\tp_url->scheme = current->scheme;\n\t\tbreak;\n\t }\n\t}\n\telse\n\t p_url->scheme = SCM_LOCAL;\n\tp = url;\n\tif (!strncmp(p, \"//\", 2)) {\n\t /* URL begins with // */\n\t /* it means that 'scheme:' is abbreviated */\n\t p += 2;\n\t goto analyze_url;\n\t}\n\t/* the url doesn't begin with '//' */\n\tgoto analyze_file;\n }\n /* scheme part has been found */\n if (p_url->scheme == SCM_UNKNOWN) {\n\tp_url->file = allocStr(url, -1);\n\treturn;\n }\n /* get host and port */\n if (p[0] != '/' || p[1] != '/') {\t/* scheme:foo or scheme:/foo */\n\tp_url->host = NULL;\n\tif (p_url->scheme != SCM_UNKNOWN)\n\t p_url->port = DefaultPort[p_url->scheme];\n\telse\n\t p_url->port = 0;\n\tgoto analyze_file;\n }\n /* after here, p begins with // */\n if (p_url->scheme == SCM_LOCAL) {\t/* file://foo */\n#ifdef __EMX__\n\tp += 2;\n\tgoto analyze_file;\n#else\n\tif (p[2] == '/' || p[2] == '~'\n\t /* file:///foo or file://~user */\n#ifdef SUPPORT_DOS_DRIVE_PREFIX\n\t || (IS_ALPHA(p[2]) && (p[3] == ':' || p[3] == '|'))\n\t /* file://DRIVE/foo */\n#endif\t\t\t\t/* SUPPORT_DOS_DRIVE_PREFIX */\n\t ) {\n\t p += 2;\n\t goto analyze_file;\n\t}\n#endif\t\t\t\t/* __EMX__ */\n }\n p += 2;\t\t\t/* scheme://foo */\n /* ^p is here */\n analyze_url:\n q = p;\n#ifdef INET6\n if (*q == '[') {\t\t/* rfc2732,rfc2373 compliance */\n\tp++;\n\twhile (IS_XDIGIT(*p) || *p == ':' || *p == '.')\n\t p++;\n\tif (*p != ']' || (*(p + 1) && strchr(\":/?#\", *(p + 1)) == NULL))\n\t p = q;\n }\n#endif\n while (*p && strchr(\":/@?#\", *p) == NULL)\n\tp++;\n switch (*p) {\n case ':':\n\t/* scheme://user:pass@host or\n\t * scheme://host:port\n\t */\n\tqq = q;\n\tq = ++p;\n\twhile (*p && strchr(\"@/?#\", *p) == NULL)\n\t p++;\n\tif (*p == '@') {\n\t /* scheme://user:pass@... */\n\t p_url->user = copyPath(qq, q - 1 - qq, COPYPATH_SPC_IGNORE);\n\t p_url->pass = copyPath(q, p - q, COPYPATH_SPC_ALLOW);\n\t p++;\n\t goto analyze_url;\n\t}\n\t/* scheme://host:port/ */\n\tp_url->host = copyPath(qq, q - 1 - qq,\n\t\t\t COPYPATH_SPC_IGNORE | COPYPATH_LOWERCASE);\n\ttmp = Strnew_charp_n(q, p - q);\n\tp_url->port = atoi(tmp->ptr);\n\t/* *p is one of ['\\0', '/', '?', '#'] */\n\tbreak;\n case '@':\n\t/* scheme://user@... */\n\tp_url->user = copyPath(q, p - q, COPYPATH_SPC_IGNORE);\n\tp++;\n\tgoto analyze_url;\n case '\\0':\n\t/* scheme://host */\n case '/':\n case '?':\n case '#':\n\tp_url->host = copyPath(q, p - q,\n\t\t\t COPYPATH_SPC_IGNORE | COPYPATH_LOWERCASE);\n\tp_url->port = DefaultPort[p_url->scheme];\n\tbreak;\n }\n analyze_file:\n#ifndef SUPPORT_NETBIOS_SHARE\n if (p_url->scheme == SCM_LOCAL && p_url->user == NULL &&\n\tp_url->host != NULL && *p_url->host != '\\0' &&\n\tstrcmp(p_url->host, \"localhost\")) {\n\t/*\n\t * In the environments other than CYGWIN, a URL like \n\t * file://host/file is regarded as ftp://host/file.\n\t * On the other hand, file://host/file on CYGWIN is\n\t * regarded as local access to the file //host/file.\n\t * `host' is a netbios-hostname, drive, or any other\n\t * name; It is CYGWIN system call who interprets that.\n\t */\n\n\tp_url->scheme = SCM_FTP;\t/* ftp://host/... */\n\tif (p_url->port == 0)\n\t p_url->port = DefaultPort[SCM_FTP];\n }\n#endif\n if ((*p == '\\0' || *p == '#' || *p == '?') && p_url->host == NULL) {\n\tp_url->file = \"\";\n\tgoto do_query;\n }\n#ifdef SUPPORT_DOS_DRIVE_PREFIX\n if (p_url->scheme == SCM_LOCAL) {\n\tq = p;\n\tif (*q == '/')\n\t q++;\n\tif (IS_ALPHA(q[0]) && (q[1] == ':' || q[1] == '|')) {\n\t if (q[1] == '|') {\n\t\tp = allocStr(q, -1);\n\t\tp[1] = ':';\n\t }\n\t else\n\t\tp = q;\n\t}\n }\n#endif\n\n q = p;\n#ifdef USE_GOPHER\n if (p_url->scheme == SCM_GOPHER) {\n\tif (*q == '/')\n\t q++;\n\tif (*q && q[0] != '/' && q[1] != '/' && q[2] == '/')\n\t q++;\n }\n#endif\t\t\t\t/* USE_GOPHER */\n if (*p == '/')\n\tp++;\n if (*p == '\\0' || *p == '#' || *p == '?') {\t/* scheme://host[:port]/ */\n\tp_url->file = DefaultFile(p_url->scheme);\n\tgoto do_query;\n }\n#ifdef USE_GOPHER\n if (p_url->scheme == SCM_GOPHER && *p == 'R') {\n\tp++;\n\ttmp = Strnew();\n\tStrcat_char(tmp, *(p++));\n\twhile (*p && *p != '/')\n\t p++;\n\tStrcat_charp(tmp, p);\n\twhile (*p)\n\t p++;\n\tp_url->file = copyPath(tmp->ptr, -1, COPYPATH_SPC_IGNORE);\n }\n else\n#endif\t\t\t\t/* USE_GOPHER */\n {\n\tchar *cgi = strchr(p, '?');\n again:\n\twhile (*p && *p != '#' && p != cgi)\n\t p++;\n\tif (*p == '#' && p_url->scheme == SCM_LOCAL) {\n\t /* \n\t * According to RFC2396, # means the beginning of\n\t * URI-reference, and # should be escaped. But,\n\t * if the scheme is SCM_LOCAL, the special\n\t * treatment will apply to # for convinience.\n\t */\n\t if (p > q && *(p - 1) == '/' && (cgi == NULL || p < cgi)) {\n\t\t/* \n\t\t * # comes as the first character of the file name\n\t\t * that means, # is not a label but a part of the file\n\t\t * name.\n\t\t */\n\t\tp++;\n\t\tgoto again;\n\t }\n\t else if (*(p + 1) == '\\0') {\n\t\t/* \n\t\t * # comes as the last character of the file name that\n\t\t * means, # is not a label but a part of the file\n\t\t * name.\n\t\t */\n\t\tp++;\n\t }\n\t}\n\tif (p_url->scheme == SCM_LOCAL || p_url->scheme == SCM_MISSING)\n\t p_url->file = copyPath(q, p - q, COPYPATH_SPC_ALLOW);\n\telse\n\t p_url->file = copyPath(q, p - q, COPYPATH_SPC_IGNORE);\n }\n\n do_query:\n if (*p == '?') {\n\tq = ++p;\n\twhile (*p && *p != '#')\n\t p++;\n\tp_url->query = copyPath(q, p - q, COPYPATH_SPC_ALLOW);\n }\n do_label:\n if (p_url->scheme == SCM_MISSING) {\n\tp_url->scheme = SCM_LOCAL;\n\tp_url->file = allocStr(p, -1);\n\tp_url->label = NULL;\n }\n else if (*p == '#')\n\tp_url->label = allocStr(p + 1, -1);\n else\n\tp_url->label = NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Prevent global-buffer-overflow in parseURL()\n\nBug-Debian: https://github.com/tats/w3m/issues/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: gst_flxdec_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)\n{\n GstCaps *caps;\n guint avail;\n GstFlowReturn res = GST_FLOW_OK;\n\n GstFlxDec *flxdec;\n FlxHeader *flxh;\n\n g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);\n flxdec = (GstFlxDec *) parent;\n g_return_val_if_fail (flxdec != NULL, GST_FLOW_ERROR);\n\n gst_adapter_push (flxdec->adapter, buf);\n avail = gst_adapter_available (flxdec->adapter);\n\n if (flxdec->state == GST_FLXDEC_READ_HEADER) {\n if (avail >= FlxHeaderSize) {\n const guint8 *data = gst_adapter_map (flxdec->adapter, FlxHeaderSize);\n GstCaps *templ;\n\n memcpy ((gchar *) & flxdec->hdr, data, FlxHeaderSize);\n FLX_HDR_FIX_ENDIANNESS (&(flxdec->hdr));\n gst_adapter_unmap (flxdec->adapter);\n gst_adapter_flush (flxdec->adapter, FlxHeaderSize);\n\n flxh = &flxdec->hdr;\n\n /* check header */\n if (flxh->type != FLX_MAGICHDR_FLI &&\n flxh->type != FLX_MAGICHDR_FLC && flxh->type != FLX_MAGICHDR_FLX)\n goto wrong_type;\n\n GST_LOG (\"size : %d\", flxh->size);\n GST_LOG (\"frames : %d\", flxh->frames);\n GST_LOG (\"width : %d\", flxh->width);\n GST_LOG (\"height : %d\", flxh->height);\n GST_LOG (\"depth : %d\", flxh->depth);\n GST_LOG (\"speed : %d\", flxh->speed);\n\n flxdec->next_time = 0;\n\n if (flxh->type == FLX_MAGICHDR_FLI) {\n flxdec->frame_time = JIFFIE * flxh->speed;\n } else if (flxh->speed == 0) {\n flxdec->frame_time = GST_SECOND / 70;\n } else {\n flxdec->frame_time = flxh->speed * GST_MSECOND;\n }\n\n flxdec->duration = flxh->frames * flxdec->frame_time;\n GST_LOG (\"duration : %\" GST_TIME_FORMAT,\n GST_TIME_ARGS (flxdec->duration));\n\n templ = gst_pad_get_pad_template_caps (flxdec->srcpad);\n caps = gst_caps_copy (templ);\n gst_caps_unref (templ);\n gst_caps_set_simple (caps,\n \"width\", G_TYPE_INT, flxh->width,\n \"height\", G_TYPE_INT, flxh->height,\n \"framerate\", GST_TYPE_FRACTION, (gint) GST_MSECOND,\n (gint) flxdec->frame_time / 1000, NULL);\n\n gst_pad_set_caps (flxdec->srcpad, caps);\n gst_caps_unref (caps);\n\n if (flxh->depth <= 8)\n flxdec->converter =\n flx_colorspace_converter_new (flxh->width, flxh->height);\n\n if (flxh->type == FLX_MAGICHDR_FLC || flxh->type == FLX_MAGICHDR_FLX) {\n GST_LOG (\"(FLC) aspect_dx : %d\", flxh->aspect_dx);\n GST_LOG (\"(FLC) aspect_dy : %d\", flxh->aspect_dy);\n GST_LOG (\"(FLC) oframe1 : 0x%08x\", flxh->oframe1);\n GST_LOG (\"(FLC) oframe2 : 0x%08x\", flxh->oframe2);\n }\n\n flxdec->size = ((guint) flxh->width * (guint) flxh->height);\n\n /* create delta and output frame */\n flxdec->frame_data = g_malloc (flxdec->size);\n flxdec->delta_data = g_malloc (flxdec->size);\n\n flxdec->state = GST_FLXDEC_PLAYING;\n }\n } else if (flxdec->state == GST_FLXDEC_PLAYING) {\n GstBuffer *out;\n\n /* while we have enough data in the adapter */\n while (avail >= FlxFrameChunkSize && res == GST_FLOW_OK) {\n FlxFrameChunk flxfh;\n guchar *chunk;\n const guint8 *data;\n GstMapInfo map;\n\n chunk = NULL;\n data = gst_adapter_map (flxdec->adapter, FlxFrameChunkSize);\n memcpy (&flxfh, data, FlxFrameChunkSize);\n FLX_FRAME_CHUNK_FIX_ENDIANNESS (&flxfh);\n gst_adapter_unmap (flxdec->adapter);\n\n switch (flxfh.id) {\n case FLX_FRAME_TYPE:\n /* check if we have the complete frame */\n if (avail < flxfh.size)\n goto need_more_data;\n\n /* flush header */\n gst_adapter_flush (flxdec->adapter, FlxFrameChunkSize);\n\n chunk = gst_adapter_take (flxdec->adapter,\n flxfh.size - FlxFrameChunkSize);\n FLX_FRAME_TYPE_FIX_ENDIANNESS ((FlxFrameType *) chunk);\n if (((FlxFrameType *) chunk)->chunks == 0)\n break;\n\n /* create 32 bits output frame */\n// res = gst_pad_alloc_buffer_and_set_caps (flxdec->srcpad,\n// GST_BUFFER_OFFSET_NONE,\n// flxdec->size * 4, GST_PAD_CAPS (flxdec->srcpad), &out);\n// if (res != GST_FLOW_OK)\n// break;\n\n out = gst_buffer_new_and_alloc (flxdec->size * 4);\n\n /* decode chunks */\n if (!flx_decode_chunks (flxdec,\n ((FlxFrameType *) chunk)->chunks,\n chunk + FlxFrameTypeSize, flxdec->frame_data)) {\n GST_ELEMENT_ERROR (flxdec, STREAM, DECODE,\n (\"%s\", \"Could not decode chunk\"), NULL);\n return GST_FLOW_ERROR;\n }\n\n /* save copy of the current frame for possible delta. */\n memcpy (flxdec->delta_data, flxdec->frame_data, flxdec->size);\n\n gst_buffer_map (out, &map, GST_MAP_WRITE);\n /* convert current frame. */\n flx_colorspace_convert (flxdec->converter, flxdec->frame_data,\n map.data);\n gst_buffer_unmap (out, &map);\n\n GST_BUFFER_TIMESTAMP (out) = flxdec->next_time;\n flxdec->next_time += flxdec->frame_time;\n\n res = gst_pad_push (flxdec->srcpad, out);\n break;\n default:\n /* check if we have the complete frame */\n if (avail < flxfh.size)\n goto need_more_data;\n\n gst_adapter_flush (flxdec->adapter, flxfh.size);\n break;\n }\n\n g_free (chunk);\n\n avail = gst_adapter_available (flxdec->adapter);\n }\n }\nneed_more_data:\n return res;\n\n /* ERRORS */\nwrong_type:\n {\n GST_ELEMENT_ERROR (flxdec, STREAM, WRONG_TYPE, (NULL),\n (\"not a flx file (type %x)\", flxh->type));\n gst_object_unref (flxdec);\n return GST_FLOW_ERROR;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'flxdec: Don't unref() parent in the chain function\n\nWe don't own the reference here, it is owned by the caller and given to\nus for the scope of this function. Leftover mistake from 0.10 porting.\n\nhttps://bugzilla.gnome.org/show_bug.cgi?id=774897'" }, { "text": "[INST] Given the following code containing errors, provide Common 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 ZEXPORT inflateMark(strm)\nz_streamp strm;\n{\n struct inflate_state FAR *state;\n\n if (strm == Z_NULL || strm->state == Z_NULL) return -1L << 16;\n state = (struct inflate_state FAR *)strm->state;\n return ((long)(state->back) << 16) +\n (state->mode == COPY ? state->length :\n (state->mode == MATCH ? state->was - state->length : 0));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Avoid shifts of negative values inflateMark().\n\nThe C standard says that bit shifts of negative integers is\nundefined. This casts to unsigned values to assure a known\nresult.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void mux_chr_update_read_handler(CharDriverState *chr,\n GMainContext *context,\n int tag)\n{\n MuxDriver *d = chr->opaque;\n\n assert(tag >= 0);\n assert(tag < d->mux_cnt);\n\n d->ext_opaque[tag] = chr->handler_opaque;\n d->chr_can_read[tag] = chr->chr_can_read;\n d->chr_read[tag] = chr->chr_read;\n d->chr_event[tag] = chr->chr_event;\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: void kbd_put_keysym_console(QemuConsole *s, int keysym)\n{\n uint8_t buf[16], *q;\n int c;\n\n if (!s || (s->console_type == GRAPHIC_CONSOLE))\n return;\n\n switch(keysym) {\n case QEMU_KEY_CTRL_UP:\n console_scroll(s, -1);\n break;\n case QEMU_KEY_CTRL_DOWN:\n console_scroll(s, 1);\n break;\n case QEMU_KEY_CTRL_PAGEUP:\n console_scroll(s, -10);\n break;\n case QEMU_KEY_CTRL_PAGEDOWN:\n console_scroll(s, 10);\n break;\n default:\n /* convert the QEMU keysym to VT100 key string */\n q = buf;\n if (keysym >= 0xe100 && keysym <= 0xe11f) {\n *q++ = '\\033';\n *q++ = '[';\n c = keysym - 0xe100;\n if (c >= 10)\n *q++ = '0' + (c / 10);\n *q++ = '0' + (c % 10);\n *q++ = '~';\n } else if (keysym >= 0xe120 && keysym <= 0xe17f) {\n *q++ = '\\033';\n *q++ = '[';\n *q++ = keysym & 0xff;\n } else if (s->echo && (keysym == '\\r' || keysym == '\\n')) {\n console_puts(s->chr, (const uint8_t *) \"\\r\", 1);\n *q++ = '\\n';\n } else {\n *q++ = keysym;\n }\n if (s->echo) {\n console_puts(s->chr, buf, q - buf);\n }\n if (s->chr->chr_read) {\n qemu_fifo_write(&s->out_fifo, buf, q - buf);\n kbd_send_chars(s);\n }\n break;\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 CharDriverState *qemu_chr_open_mux(const char *id,\n ChardevBackend *backend,\n ChardevReturn *ret, Error **errp)\n{\n ChardevMux *mux = backend->u.mux.data;\n CharDriverState *chr, *drv;\n MuxDriver *d;\n ChardevCommon *common = qapi_ChardevMux_base(mux);\n\n drv = qemu_chr_find(mux->chardev);\n if (drv == NULL) {\n error_setg(errp, \"mux: base chardev %s not found\", mux->chardev);\n return NULL;\n }\n\n chr = qemu_chr_alloc(common, errp);\n if (!chr) {\n return NULL;\n }\n d = g_new0(MuxDriver, 1);\n\n chr->opaque = d;\n d->focus = -1;\n chr->chr_close = mux_chr_close;\n chr->chr_write = mux_chr_write;\n chr->chr_update_read_handler = mux_chr_update_read_handler;\n chr->chr_accept_input = mux_chr_accept_input;\n /* Frontend guest-open / -close notification is not support with muxes */\n chr->chr_set_fe_open = NULL;\n if (drv->chr_add_watch) {\n chr->chr_add_watch = mux_chr_add_watch;\n }\n /* only default to opened state if we've realized the initial\n * set of muxes\n */\n chr->explicit_be_open = muxes_realized ? 0 : 1;\n chr->is_mux = 1;\n if (!qemu_chr_fe_init(&d->chr, drv, errp)) {\n qemu_chr_free(chr);\n return NULL;\n }\n\n return chr;\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 perf_event_refresh(struct perf_event *event, int refresh)\n{\n\t/*\n\t * not supported on inherited events\n\t */\n\tif (event->attr.inherit || !is_sampling_event(event))\n\t\treturn -EINVAL;\n\n\tatomic_add(refresh, &event->event_limit);\n\tperf_event_enable(event);\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: SYSCALL_DEFINE5(perf_event_open,\n\t\tstruct perf_event_attr __user *, attr_uptr,\n\t\tpid_t, pid, int, cpu, int, group_fd, unsigned long, flags)\n{\n\tstruct perf_event *group_leader = NULL, *output_event = NULL;\n\tstruct perf_event *event, *sibling;\n\tstruct perf_event_attr attr;\n\tstruct perf_event_context *ctx;\n\tstruct file *event_file = NULL;\n\tstruct fd group = {NULL, 0};\n\tstruct task_struct *task = NULL;\n\tstruct pmu *pmu;\n\tint event_fd;\n\tint move_group = 0;\n\tint err;\n\tint f_flags = O_RDWR;\n\n\t/* for future expandability... */\n\tif (flags & ~PERF_FLAG_ALL)\n\t\treturn -EINVAL;\n\n\terr = perf_copy_attr(attr_uptr, &attr);\n\tif (err)\n\t\treturn err;\n\n\tif (!attr.exclude_kernel) {\n\t\tif (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))\n\t\t\treturn -EACCES;\n\t}\n\n\tif (attr.freq) {\n\t\tif (attr.sample_freq > sysctl_perf_event_sample_rate)\n\t\t\treturn -EINVAL;\n\t} else {\n\t\tif (attr.sample_period & (1ULL << 63))\n\t\t\treturn -EINVAL;\n\t}\n\n\t/*\n\t * In cgroup mode, the pid argument is used to pass the fd\n\t * opened to the cgroup directory in cgroupfs. The cpu argument\n\t * designates the cpu on which to monitor threads from that\n\t * cgroup.\n\t */\n\tif ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))\n\t\treturn -EINVAL;\n\n\tif (flags & PERF_FLAG_FD_CLOEXEC)\n\t\tf_flags |= O_CLOEXEC;\n\n\tevent_fd = get_unused_fd_flags(f_flags);\n\tif (event_fd < 0)\n\t\treturn event_fd;\n\n\tif (group_fd != -1) {\n\t\terr = perf_fget_light(group_fd, &group);\n\t\tif (err)\n\t\t\tgoto err_fd;\n\t\tgroup_leader = group.file->private_data;\n\t\tif (flags & PERF_FLAG_FD_OUTPUT)\n\t\t\toutput_event = group_leader;\n\t\tif (flags & PERF_FLAG_FD_NO_GROUP)\n\t\t\tgroup_leader = NULL;\n\t}\n\n\tif (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {\n\t\ttask = find_lively_task_by_vpid(pid);\n\t\tif (IS_ERR(task)) {\n\t\t\terr = PTR_ERR(task);\n\t\t\tgoto err_group_fd;\n\t\t}\n\t}\n\n\tif (task && group_leader &&\n\t group_leader->attr.inherit != attr.inherit) {\n\t\terr = -EINVAL;\n\t\tgoto err_task;\n\t}\n\n\tget_online_cpus();\n\n\tevent = perf_event_alloc(&attr, cpu, task, group_leader, NULL,\n\t\t\t\t NULL, NULL);\n\tif (IS_ERR(event)) {\n\t\terr = PTR_ERR(event);\n\t\tgoto err_cpus;\n\t}\n\n\tif (flags & PERF_FLAG_PID_CGROUP) {\n\t\terr = perf_cgroup_connect(pid, event, &attr, group_leader);\n\t\tif (err) {\n\t\t\t__free_event(event);\n\t\t\tgoto err_cpus;\n\t\t}\n\t}\n\n\tif (is_sampling_event(event)) {\n\t\tif (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {\n\t\t\terr = -ENOTSUPP;\n\t\t\tgoto err_alloc;\n\t\t}\n\t}\n\n\taccount_event(event);\n\n\t/*\n\t * Special case software events and allow them to be part of\n\t * any hardware group.\n\t */\n\tpmu = event->pmu;\n\n\tif (group_leader &&\n\t (is_software_event(event) != is_software_event(group_leader))) {\n\t\tif (is_software_event(event)) {\n\t\t\t/*\n\t\t\t * If event and group_leader are not both a software\n\t\t\t * event, and event is, then group leader is not.\n\t\t\t *\n\t\t\t * Allow the addition of software events to !software\n\t\t\t * groups, this is safe because software events never\n\t\t\t * fail to schedule.\n\t\t\t */\n\t\t\tpmu = group_leader->pmu;\n\t\t} else if (is_software_event(group_leader) &&\n\t\t\t (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {\n\t\t\t/*\n\t\t\t * In case the group is a pure software group, and we\n\t\t\t * try to add a hardware event, move the whole group to\n\t\t\t * the hardware context.\n\t\t\t */\n\t\t\tmove_group = 1;\n\t\t}\n\t}\n\n\t/*\n\t * Get the target context (task or percpu):\n\t */\n\tctx = find_get_context(pmu, task, event->cpu);\n\tif (IS_ERR(ctx)) {\n\t\terr = PTR_ERR(ctx);\n\t\tgoto err_alloc;\n\t}\n\n\tif (task) {\n\t\tput_task_struct(task);\n\t\ttask = NULL;\n\t}\n\n\t/*\n\t * Look up the group leader (we will attach this event to it):\n\t */\n\tif (group_leader) {\n\t\terr = -EINVAL;\n\n\t\t/*\n\t\t * Do not allow a recursive hierarchy (this new sibling\n\t\t * becoming part of another group-sibling):\n\t\t */\n\t\tif (group_leader->group_leader != group_leader)\n\t\t\tgoto err_context;\n\t\t/*\n\t\t * Do not allow to attach to a group in a different\n\t\t * task or CPU context:\n\t\t */\n\t\tif (move_group) {\n\t\t\t/*\n\t\t\t * Make sure we're both on the same task, or both\n\t\t\t * per-cpu events.\n\t\t\t */\n\t\t\tif (group_leader->ctx->task != ctx->task)\n\t\t\t\tgoto err_context;\n\n\t\t\t/*\n\t\t\t * Make sure we're both events for the same CPU;\n\t\t\t * grouping events for different CPUs is broken; since\n\t\t\t * you can never concurrently schedule them anyhow.\n\t\t\t */\n\t\t\tif (group_leader->cpu != event->cpu)\n\t\t\t\tgoto err_context;\n\t\t} else {\n\t\t\tif (group_leader->ctx != ctx)\n\t\t\t\tgoto err_context;\n\t\t}\n\n\t\t/*\n\t\t * Only a group leader can be exclusive or pinned\n\t\t */\n\t\tif (attr.exclusive || attr.pinned)\n\t\t\tgoto err_context;\n\t}\n\n\tif (output_event) {\n\t\terr = perf_event_set_output(event, output_event);\n\t\tif (err)\n\t\t\tgoto err_context;\n\t}\n\n\tevent_file = anon_inode_getfile(\"[perf_event]\", &perf_fops, event,\n\t\t\t\t\tf_flags);\n\tif (IS_ERR(event_file)) {\n\t\terr = PTR_ERR(event_file);\n\t\tgoto err_context;\n\t}\n\n\tif (move_group) {\n\t\tstruct perf_event_context *gctx = group_leader->ctx;\n\n\t\tmutex_lock(&gctx->mutex);\n\t\tperf_remove_from_context(group_leader, false);\n\n\t\t/*\n\t\t * Removing from the context ends up with disabled\n\t\t * event. What we want here is event in the initial\n\t\t * startup state, ready to be add into new context.\n\t\t */\n\t\tperf_event__state_init(group_leader);\n\t\tlist_for_each_entry(sibling, &group_leader->sibling_list,\n\t\t\t\t group_entry) {\n\t\t\tperf_remove_from_context(sibling, false);\n\t\t\tperf_event__state_init(sibling);\n\t\t\tput_ctx(gctx);\n\t\t}\n\t\tmutex_unlock(&gctx->mutex);\n\t\tput_ctx(gctx);\n\t}\n\n\tWARN_ON_ONCE(ctx->parent_ctx);\n\tmutex_lock(&ctx->mutex);\n\n\tif (move_group) {\n\t\tsynchronize_rcu();\n\t\tperf_install_in_context(ctx, group_leader, group_leader->cpu);\n\t\tget_ctx(ctx);\n\t\tlist_for_each_entry(sibling, &group_leader->sibling_list,\n\t\t\t\t group_entry) {\n\t\t\tperf_install_in_context(ctx, sibling, sibling->cpu);\n\t\t\tget_ctx(ctx);\n\t\t}\n\t}\n\n\tperf_install_in_context(ctx, event, event->cpu);\n\tperf_unpin_context(ctx);\n\tmutex_unlock(&ctx->mutex);\n\n\tput_online_cpus();\n\n\tevent->owner = current;\n\n\tmutex_lock(¤t->perf_event_mutex);\n\tlist_add_tail(&event->owner_entry, ¤t->perf_event_list);\n\tmutex_unlock(¤t->perf_event_mutex);\n\n\t/*\n\t * Precalculate sample_data sizes\n\t */\n\tperf_event__header_size(event);\n\tperf_event__id_header_size(event);\n\n\t/*\n\t * Drop the reference on the group_event after placing the\n\t * new event on the sibling_list. This ensures destruction\n\t * of the group leader will find the pointer to itself in\n\t * perf_group_detach().\n\t */\n\tfdput(group);\n\tfd_install(event_fd, event_file);\n\treturn event_fd;\n\nerr_context:\n\tperf_unpin_context(ctx);\n\tput_ctx(ctx);\nerr_alloc:\n\tfree_event(event);\nerr_cpus:\n\tput_online_cpus();\nerr_task:\n\tif (task)\n\t\tput_task_struct(task);\nerr_group_fd:\n\tfdput(group);\nerr_fd:\n\tput_unused_fd(event_fd);\n\treturn err;\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: \nvoid pdo_stmt_init(TSRMLS_D)\n{\n\tzend_class_entry ce;\n\n\tINIT_CLASS_ENTRY(ce, \"PDOStatement\", pdo_dbstmt_functions);\n\tpdo_dbstmt_ce = zend_register_internal_class(&ce TSRMLS_CC);\n\tpdo_dbstmt_ce->get_iterator = pdo_stmt_iter_get;\n\tpdo_dbstmt_ce->create_object = pdo_dbstmt_new;\n\tzend_class_implements(pdo_dbstmt_ce TSRMLS_CC, 1, zend_ce_traversable);\n\tzend_declare_property_null(pdo_dbstmt_ce, \"queryString\", sizeof(\"queryString\")-1, ZEND_ACC_PUBLIC TSRMLS_CC);\n\n\tmemcpy(&pdo_dbstmt_object_handlers, &std_object_handlers, sizeof(zend_object_handlers));\n\tpdo_dbstmt_object_handlers.write_property = dbstmt_prop_write;\n\tpdo_dbstmt_object_handlers.unset_property = dbstmt_prop_delete;\n\tpdo_dbstmt_object_handlers.get_method = dbstmt_method_get;\n\tpdo_dbstmt_object_handlers.compare_objects = dbstmt_compare;\n\tpdo_dbstmt_object_handlers.clone_obj = dbstmt_clone_obj;\n\n\tINIT_CLASS_ENTRY(ce, \"PDORow\", pdo_row_functions);\n\tpdo_row_ce = zend_register_internal_class(&ce TSRMLS_CC);\n\tpdo_row_ce->ce_flags |= ZEND_ACC_FINAL_CLASS; /* when removing this a lot of handlers need to be redone */\n\tpdo_row_ce->create_object = pdo_row_new;\n\tpdo_row_ce->serialize = pdo_row_serialize; ; 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: int jpc_dec_decodepkts(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in)\n{\n\tjpc_dec_tile_t *tile;\n\tjpc_pi_t *pi;\n\tint ret;\n\n\ttile = dec->curtile;\n\tpi = tile->pi;\n\tfor (;;) {\nif (!tile->pkthdrstream || jas_stream_peekc(tile->pkthdrstream) == EOF) {\n\t\tswitch (jpc_dec_lookahead(in)) {\n\t\tcase JPC_MS_EOC:\n\t\tcase JPC_MS_SOT:\n\t\t\treturn 0;\n\t\t\tbreak;\n\t\tcase JPC_MS_SOP:\n\t\tcase JPC_MS_EPH:\n\t\tcase 0:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn -1;\n\t\t\tbreak;\n\t\t}\n}\n\t\tif ((ret = jpc_pi_next(pi))) {\n\t\t\treturn ret;\n\t\t}\nif (dec->maxpkts >= 0 && dec->numpkts >= dec->maxpkts) {\n\tjas_eprintf(\"warning: stopping decode prematurely as requested\\n\");\n\treturn 0;\n}\n\t\tif (jas_getdbglevel() >= 1) {\n\t\t\tjas_eprintf(\"packet offset=%08ld prg=%d cmptno=%02d \"\n\t\t\t \"rlvlno=%02d prcno=%03d lyrno=%02d\\n\", (long)\n\t\t\t jas_stream_getrwcount(in), jpc_pi_prg(pi), jpc_pi_cmptno(pi),\n\t\t\t jpc_pi_rlvlno(pi), jpc_pi_prcno(pi), jpc_pi_lyrno(pi));\n\t\t}\n\t\tif (jpc_dec_decodepkt(dec, pkthdrstream, in, jpc_pi_cmptno(pi), jpc_pi_rlvlno(pi),\n\t\t jpc_pi_prcno(pi), jpc_pi_lyrno(pi))) {\n\t\t\treturn -1;\n\t\t}\n++dec->numpkts;\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed numerous integer overflow problems in the code for packet iterators\nin the JPC decoder.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void prc_destroy(jpc_enc_prc_t *prc)\n{\n\tjpc_enc_cblk_t *cblk;\n\tuint_fast32_t cblkno;\n\n\tif (prc->cblks) {\n\t\tfor (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;\n\t\t ++cblkno, ++cblk) {\n\t\t\tcblk_destroy(cblk);\n\t\t}\n\t\tjas_free(prc->cblks);\n\t}\n\tif (prc->incltree) {\n\t\tjpc_tagtree_destroy(prc->incltree);\n\t}\n\tif (prc->nlibtree) {\n\t\tjpc_tagtree_destroy(prc->nlibtree);\n\t}\n\tif (prc->savincltree) {\n\t\tjpc_tagtree_destroy(prc->savincltree);\n\t}\n\tif (prc->savnlibtree) {\n\t\tjpc_tagtree_destroy(prc->savnlibtree);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed some potential double-free problems in the JPC codec.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static MagickBooleanType ConcatenateImages(int argc,char **argv,\n ExceptionInfo *exception )\n{\n FILE\n *input,\n *output;\n\n int\n c;\n\n register ssize_t\n i;\n\n if (ExpandFilenames(&argc,&argv) == MagickFalse)\n ThrowFileException(exception,ResourceLimitError,\"MemoryAllocationFailed\",\n GetExceptionMessage(errno));\n\n output=fopen_utf8(argv[argc-1],\"wb\");\n if (output == (FILE *) NULL) {\n ThrowFileException(exception,FileOpenError,\"UnableToOpenFile\",argv[argc-1]);\n return(MagickFalse);\n }\n for (i=2; i < (ssize_t) (argc-1); i++) {\n#if 0\n fprintf(stderr, \"DEBUG: Concatenate Image: \\\"%s\\\"\\n\", argv[i]);\n#endif\n input=fopen_utf8(argv[i],\"rb\");\n if (input == (FILE *) NULL) {\n ThrowFileException(exception,FileOpenError,\"UnableToOpenFile\",argv[i]);\n continue;\n }\n for (c=fgetc(input); c != EOF; c=fgetc(input))\n (void) fputc((char) c,output);\n (void) fclose(input);\n (void) remove_utf8(argv[i]);\n }\n (void) fclose(output);\n return(MagickTrue);\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 inline void perf_event_exit_cpu(int cpu) { } ; 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\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-119', 'CWE-787'], 'message': 'smart_pkt: verify packet length exceeds PKT_LEN_SIZE\n\nEach packet line in the Git protocol is prefixed by a four-byte\nlength of how much data will follow, which we parse in\n`git_pkt_parse_line`. The transmitted length can either be equal\nto zero in case of a flush packet or has to be at least of length\nfour, as it also includes the encoded length itself. Not\nchecking this may result in a buffer overflow as we directly pass\nthe length to functions which accept a `size_t` length as\nparameter.\n\nFix the issue by verifying that non-flush packets have at least a\nlength of `PKT_LEN_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: u32 cdk_pk_get_keyid(cdk_pubkey_t pk, u32 * keyid)\n{\n\tu32 lowbits = 0;\n\tbyte buf[24];\n\n\tif (pk && (!pk->keyid[0] || !pk->keyid[1])) {\n\t\tif (pk->version < 4 && is_RSA(pk->pubkey_algo)) {\n\t\t\tbyte p[MAX_MPI_BYTES];\n\t\t\tsize_t n;\n\n\t\t\tn = MAX_MPI_BYTES;\n\t\t\t_gnutls_mpi_print(pk->mpi[0], p, &n);\n\t\t\tpk->keyid[0] =\n\t\t\t p[n - 8] << 24 | p[n - 7] << 16 | p[n -\n\t\t\t\t\t\t\t\t6] << 8 |\n\t\t\t p[n - 5];\n\t\t\tpk->keyid[1] =\n\t\t\t p[n - 4] << 24 | p[n - 3] << 16 | p[n -\n\t\t\t\t\t\t\t\t2] << 8 |\n\t\t\t p[n - 1];\n\t\t} else if (pk->version == 4) {\n\t\t\tcdk_pk_get_fingerprint(pk, buf);\n\t\t\tpk->keyid[0] = _cdk_buftou32(buf + 12);\n\t\t\tpk->keyid[1] = _cdk_buftou32(buf + 16);\n\t\t}\n\t}\n\tlowbits = pk ? pk->keyid[1] : 0;\n\tif (keyid && pk) {\n\t\tkeyid[0] = pk->keyid[0];\n\t\tkeyid[1] = pk->keyid[1];\n\t}\n\n\treturn lowbits;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'opencdk: cdk_pk_get_keyid: fix stack overflow\n\nIssue found using oss-fuzz:\n https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=340\n\nSigned-off-by: Nikos Mavrogiannopoulos '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static size_t WritePSDChannels(const PSDInfo *psd_info,\n const ImageInfo *image_info,Image *image,Image *next_image,\n MagickOffsetType size_offset,const MagickBooleanType separate,\n ExceptionInfo *exception)\n{\n Image\n *mask;\n\n MagickOffsetType\n rows_offset;\n\n size_t\n channels,\n count,\n length,\n offset_length;\n\n unsigned char\n *compact_pixels;\n\n count=0;\n offset_length=0;\n rows_offset=0;\n compact_pixels=(unsigned char *) NULL;\n if (next_image->compression == RLECompression)\n {\n compact_pixels=AcquireCompactPixels(image,exception);\n if (compact_pixels == (unsigned char *) NULL)\n return(0);\n }\n channels=1;\n if (separate == MagickFalse)\n {\n if (next_image->storage_class != PseudoClass)\n {\n if (IsImageGray(next_image) == MagickFalse)\n channels=next_image->colorspace == CMYKColorspace ? 4 : 3;\n if (next_image->alpha_trait != UndefinedPixelTrait)\n channels++;\n }\n rows_offset=TellBlob(image)+2;\n count+=WriteCompressionStart(psd_info,image,next_image,channels);\n offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4));\n }\n size_offset+=2;\n if (next_image->storage_class == PseudoClass)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n IndexQuantum,compact_pixels,rows_offset,separate,exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n else\n {\n if (IsImageGray(next_image) != MagickFalse)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n GrayQuantum,compact_pixels,rows_offset,separate,exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n else\n {\n if (next_image->colorspace == CMYKColorspace)\n (void) NegateCMYK(next_image,exception);\n\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n RedQuantum,compact_pixels,rows_offset,separate,exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n GreenQuantum,compact_pixels,rows_offset,separate,exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n BlueQuantum,compact_pixels,rows_offset,separate,exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n\n if (next_image->colorspace == CMYKColorspace)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n BlackQuantum,compact_pixels,rows_offset,separate,exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n }\n if (next_image->alpha_trait != UndefinedPixelTrait)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n AlphaQuantum,compact_pixels,rows_offset,separate,exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n }\n compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n if (next_image->colorspace == CMYKColorspace)\n (void) NegateCMYK(next_image,exception);\n if (separate != MagickFalse)\n {\n const char\n *property;\n\n property=GetImageArtifact(next_image,\"psd:opacity-mask\");\n if (property != (const char *) NULL)\n {\n mask=(Image *) GetImageRegistry(ImageRegistryType,property,\n exception);\n if (mask != (Image *) NULL)\n {\n if (mask->compression == RLECompression)\n {\n compact_pixels=AcquireCompactPixels(mask,exception);\n if (compact_pixels == (unsigned char *) NULL)\n return(0);\n }\n length=WritePSDChannel(psd_info,image_info,image,mask,\n RedQuantum,compact_pixels,rows_offset,MagickTrue,exception);\n (void) WritePSDSize(psd_info,image,length,size_offset);\n count+=length;\n compact_pixels=(unsigned char *) RelinquishMagickMemory(\n compact_pixels);\n }\n }\n }\n return(count);\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 main(int argc, char *argv[])\n{\n FILE *iplist = NULL;\n plist_t root_node = NULL;\n char *plist_out = NULL;\n uint32_t size = 0;\n int read_size = 0;\n char *plist_entire = NULL;\n struct stat filestats;\n options_t *options = parse_arguments(argc, argv);\n\n if (!options)\n {\n print_usage(argc, argv);\n return 0;\n }\n\n // read input file\n iplist = fopen(options->in_file, \"rb\");\n if (!iplist) {\n free(options);\n return 1;\n }\n\n stat(options->in_file, &filestats);\n plist_entire = (char *) malloc(sizeof(char) * (filestats.st_size + 1));\n read_size = fread(plist_entire, sizeof(char), filestats.st_size, iplist);\n fclose(iplist);\n\n // convert from binary to xml or vice-versa\n if (memcmp(plist_entire, \"bplist00\", 8) == 0)\n {\n plist_from_bin(plist_entire, read_size, &root_node);\n plist_to_xml(root_node, &plist_out, &size);\n }\n else\n {\n plist_from_xml(plist_entire, read_size, &root_node);\n plist_to_bin(root_node, &plist_out, &size);\n }\n plist_free(root_node);\n free(plist_entire);\n\n if (plist_out)\n {\n if (options->out_file != NULL)\n {\n FILE *oplist = fopen(options->out_file, \"wb\");\n if (!oplist) {\n free(options);\n return 1;\n }\n fwrite(plist_out, size, sizeof(char), oplist);\n fclose(oplist);\n }\n // if no output file specified, write to stdout\n else\n fwrite(plist_out, size, sizeof(char), stdout);\n\n free(plist_out);\n }\n else\n printf(\"ERROR: Failed to convert input file.\\n\");\n\n free(options);\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-125'], 'message': 'plistutil: Prevent OOB heap buffer read by checking input size\n\nAs pointed out in #87 plistutil would do a memcmp with a heap buffer\nwithout checking the size. If the size is less than 8 it would read\nbeyond the bounds of this heap buffer. This commit prevents 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: smbhash(unsigned char *out, const unsigned char *in, unsigned char *key)\n{\n\tint rc;\n\tunsigned char key2[8];\n\tstruct crypto_skcipher *tfm_des;\n\tstruct scatterlist sgin, sgout;\n\tstruct skcipher_request *req;\n\n\tstr_to_key(key, key2);\n\n\ttfm_des = crypto_alloc_skcipher(\"ecb(des)\", 0, CRYPTO_ALG_ASYNC);\n\tif (IS_ERR(tfm_des)) {\n\t\trc = PTR_ERR(tfm_des);\n\t\tcifs_dbg(VFS, \"could not allocate des crypto API\\n\");\n\t\tgoto smbhash_err;\n\t}\n\n\treq = skcipher_request_alloc(tfm_des, GFP_KERNEL);\n\tif (!req) {\n\t\trc = -ENOMEM;\n\t\tcifs_dbg(VFS, \"could not allocate des crypto API\\n\");\n\t\tgoto smbhash_free_skcipher;\n\t}\n\n\tcrypto_skcipher_setkey(tfm_des, key2, 8);\n\n\tsg_init_one(&sgin, in, 8);\n\tsg_init_one(&sgout, out, 8);\n\n\tskcipher_request_set_callback(req, 0, NULL, NULL);\n\tskcipher_request_set_crypt(req, &sgin, &sgout, 8, NULL);\n\n\trc = crypto_skcipher_encrypt(req);\n\tif (rc)\n\t\tcifs_dbg(VFS, \"could not encrypt crypt key rc: %d\\n\", rc);\n\n\tskcipher_request_free(req);\n\nsmbhash_free_skcipher:\n\tcrypto_free_skcipher(tfm_des);\nsmbhash_err:\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-703'], 'message': 'cifs: Fix smbencrypt() to stop pointing a scatterlist at the stack\n\nsmbencrypt() points a scatterlist to the stack, which is breaks if\nCONFIG_VMAP_STACK=y.\n\nFix it by switching to crypto_cipher_encrypt_one(). The new code\nshould be considerably faster as an added benefit.\n\nThis code is nearly identical to some code that Eric Biggers\nsuggested.\n\nCc: stable@vger.kernel.org # 4.9 only\nReported-by: Eric Biggers \nSigned-off-by: Andy Lutomirski \nAcked-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: int32_t FASTCALL get_word (WavpackStream *wps, int chan, int32_t *correction)\n{\n register struct entropy_data *c = wps->w.c + chan;\n uint32_t ones_count, low, mid, high;\n int32_t value;\n int sign;\n\n if (!wps->wvbits.ptr)\n return WORD_EOF;\n\n if (correction)\n *correction = 0;\n\n if (!(wps->w.c [0].median [0] & ~1) && !wps->w.holding_zero && !wps->w.holding_one && !(wps->w.c [1].median [0] & ~1)) {\n uint32_t mask;\n int cbits;\n\n if (wps->w.zeros_acc) {\n if (--wps->w.zeros_acc) {\n c->slow_level -= (c->slow_level + SLO) >> SLS;\n return 0;\n }\n }\n else {\n for (cbits = 0; cbits < 33 && getbit (&wps->wvbits); ++cbits);\n\n if (cbits == 33)\n return WORD_EOF;\n\n if (cbits < 2)\n wps->w.zeros_acc = cbits;\n else {\n for (mask = 1, wps->w.zeros_acc = 0; --cbits; mask <<= 1)\n if (getbit (&wps->wvbits))\n wps->w.zeros_acc |= mask;\n\n wps->w.zeros_acc |= mask;\n }\n\n if (wps->w.zeros_acc) {\n c->slow_level -= (c->slow_level + SLO) >> SLS;\n CLEAR (wps->w.c [0].median);\n CLEAR (wps->w.c [1].median);\n return 0;\n }\n }\n }\n\n if (wps->w.holding_zero)\n ones_count = wps->w.holding_zero = 0;\n else {\n#ifdef USE_CTZ_OPTIMIZATION\n while (wps->wvbits.bc < LIMIT_ONES) {\n if (++(wps->wvbits.ptr) == wps->wvbits.end)\n wps->wvbits.wrap (&wps->wvbits);\n\n wps->wvbits.sr |= *(wps->wvbits.ptr) << wps->wvbits.bc;\n wps->wvbits.bc += sizeof (*(wps->wvbits.ptr)) * 8;\n }\n\n#ifdef _WIN32\n _BitScanForward (&ones_count, ~wps->wvbits.sr);\n#else\n ones_count = __builtin_ctz (~wps->wvbits.sr);\n#endif\n\n if (ones_count >= LIMIT_ONES) {\n wps->wvbits.bc -= ones_count;\n wps->wvbits.sr >>= ones_count;\n\n for (; ones_count < (LIMIT_ONES + 1) && getbit (&wps->wvbits); ++ones_count);\n\n if (ones_count == (LIMIT_ONES + 1))\n return WORD_EOF;\n\n if (ones_count == LIMIT_ONES) {\n uint32_t mask;\n int cbits;\n\n for (cbits = 0; cbits < 33 && getbit (&wps->wvbits); ++cbits);\n\n if (cbits == 33)\n return WORD_EOF;\n\n if (cbits < 2)\n ones_count = cbits;\n else {\n for (mask = 1, ones_count = 0; --cbits; mask <<= 1)\n if (getbit (&wps->wvbits))\n ones_count |= mask;\n\n ones_count |= mask;\n }\n\n ones_count += LIMIT_ONES;\n }\n }\n else {\n wps->wvbits.bc -= ones_count + 1;\n wps->wvbits.sr >>= ones_count + 1;\n }\n#elif defined (USE_NEXT8_OPTIMIZATION)\n int next8;\n\n if (wps->wvbits.bc < 8) {\n if (++(wps->wvbits.ptr) == wps->wvbits.end)\n wps->wvbits.wrap (&wps->wvbits);\n\n next8 = (wps->wvbits.sr |= *(wps->wvbits.ptr) << wps->wvbits.bc) & 0xff;\n wps->wvbits.bc += sizeof (*(wps->wvbits.ptr)) * 8;\n }\n else\n next8 = wps->wvbits.sr & 0xff;\n\n if (next8 == 0xff) {\n wps->wvbits.bc -= 8;\n wps->wvbits.sr >>= 8;\n\n for (ones_count = 8; ones_count < (LIMIT_ONES + 1) && getbit (&wps->wvbits); ++ones_count);\n\n if (ones_count == (LIMIT_ONES + 1))\n return WORD_EOF;\n\n if (ones_count == LIMIT_ONES) {\n uint32_t mask;\n int cbits;\n\n for (cbits = 0; cbits < 33 && getbit (&wps->wvbits); ++cbits);\n\n if (cbits == 33)\n return WORD_EOF;\n\n if (cbits < 2)\n ones_count = cbits;\n else {\n for (mask = 1, ones_count = 0; --cbits; mask <<= 1)\n if (getbit (&wps->wvbits))\n ones_count |= mask;\n\n ones_count |= mask;\n }\n\n ones_count += LIMIT_ONES;\n }\n }\n else {\n wps->wvbits.bc -= (ones_count = ones_count_table [next8]) + 1;\n wps->wvbits.sr >>= ones_count + 1;\n }\n#else\n for (ones_count = 0; ones_count < (LIMIT_ONES + 1) && getbit (&wps->wvbits); ++ones_count);\n\n if (ones_count >= LIMIT_ONES) {\n uint32_t mask;\n int cbits;\n\n if (ones_count == (LIMIT_ONES + 1))\n return WORD_EOF;\n\n for (cbits = 0; cbits < 33 && getbit (&wps->wvbits); ++cbits);\n\n if (cbits == 33)\n return WORD_EOF;\n\n if (cbits < 2)\n ones_count = cbits;\n else {\n for (mask = 1, ones_count = 0; --cbits; mask <<= 1)\n if (getbit (&wps->wvbits))\n ones_count |= mask;\n\n ones_count |= mask;\n }\n\n ones_count += LIMIT_ONES;\n }\n#endif\n\n if (wps->w.holding_one) {\n wps->w.holding_one = ones_count & 1;\n ones_count = (ones_count >> 1) + 1;\n }\n else {\n wps->w.holding_one = ones_count & 1;\n ones_count >>= 1;\n }\n\n wps->w.holding_zero = ~wps->w.holding_one & 1;\n }\n\n if ((wps->wphdr.flags & HYBRID_FLAG) && !chan)\n update_error_limit (wps);\n\n if (ones_count == 0) {\n low = 0;\n high = GET_MED (0) - 1;\n DEC_MED0 ();\n }\n else {\n low = GET_MED (0);\n INC_MED0 ();\n\n if (ones_count == 1) {\n high = low + GET_MED (1) - 1;\n DEC_MED1 ();\n }\n else {\n low += GET_MED (1);\n INC_MED1 ();\n\n if (ones_count == 2) {\n high = low + GET_MED (2) - 1;\n DEC_MED2 ();\n }\n else {\n low += (ones_count - 2) * GET_MED (2);\n high = low + GET_MED (2) - 1;\n INC_MED2 ();\n }\n }\n }\n\n low &= 0x7fffffff;\n high &= 0x7fffffff;\n mid = (high + low + 1) >> 1;\n\n if (!c->error_limit)\n mid = read_code (&wps->wvbits, high - low) + low;\n else while (high - low > c->error_limit) {\n if (getbit (&wps->wvbits))\n mid = (high + (low = mid) + 1) >> 1;\n else\n mid = ((high = mid - 1) + low + 1) >> 1;\n }\n\n sign = getbit (&wps->wvbits);\n\n if (bs_is_open (&wps->wvcbits) && c->error_limit) {\n value = read_code (&wps->wvcbits, high - low) + low;\n\n if (correction)\n *correction = sign ? (mid - value) : (value - mid);\n }\n\n if (wps->wphdr.flags & HYBRID_BITRATE) {\n c->slow_level -= (c->slow_level + SLO) >> SLS;\n c->slow_level += wp_log2 (mid);\n }\n\n return sign ? ~mid : mid;\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_map_dcmd(MegasasState *s, MegasasCmd *cmd)\n{\n dma_addr_t iov_pa, iov_size;\n\n cmd->flags = le16_to_cpu(cmd->frame->header.flags);\n if (!cmd->frame->header.sge_count) {\n trace_megasas_dcmd_zero_sge(cmd->index);\n cmd->iov_size = 0;\n return 0;\n } else if (cmd->frame->header.sge_count > 1) {\n trace_megasas_dcmd_invalid_sge(cmd->index,\n cmd->frame->header.sge_count);\n cmd->iov_size = 0;\n return -1;\n }\n iov_pa = megasas_sgl_get_addr(cmd, &cmd->frame->dcmd.sgl);\n iov_size = megasas_sgl_get_len(cmd, &cmd->frame->dcmd.sgl);\n pci_dma_sglist_init(&cmd->qsg, PCI_DEVICE(s), 1);\n qemu_sglist_add(&cmd->qsg, iov_pa, iov_size);\n cmd->iov_size = iov_size;\n return cmd->iov_size;\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: gst_aac_parse_sink_setcaps (GstBaseParse * parse, GstCaps * caps)\n{\n GstAacParse *aacparse;\n GstStructure *structure;\n gchar *caps_str;\n const GValue *value;\n\n aacparse = GST_AAC_PARSE (parse);\n structure = gst_caps_get_structure (caps, 0);\n caps_str = gst_caps_to_string (caps);\n\n GST_DEBUG_OBJECT (aacparse, \"setcaps: %s\", caps_str);\n g_free (caps_str);\n\n /* This is needed at least in case of RTP\n * Parses the codec_data information to get ObjectType,\n * number of channels and samplerate */\n value = gst_structure_get_value (structure, \"codec_data\");\n if (value) {\n GstBuffer *buf = gst_value_get_buffer (value);\n\n if (buf) {\n GstMapInfo map;\n guint sr_idx;\n\n gst_buffer_map (buf, &map, GST_MAP_READ);\n\n sr_idx = ((map.data[0] & 0x07) << 1) | ((map.data[1] & 0x80) >> 7);\n aacparse->object_type = (map.data[0] & 0xf8) >> 3;\n aacparse->sample_rate =\n gst_codec_utils_aac_get_sample_rate_from_index (sr_idx);\n aacparse->channels = (map.data[1] & 0x78) >> 3;\n if (aacparse->channels == 7)\n aacparse->channels = 8;\n else if (aacparse->channels == 11)\n aacparse->channels = 7;\n else if (aacparse->channels == 12 || aacparse->channels == 14)\n aacparse->channels = 8;\n aacparse->header_type = DSPAAC_HEADER_NONE;\n aacparse->mpegversion = 4;\n aacparse->frame_samples = (map.data[1] & 4) ? 960 : 1024;\n gst_buffer_unmap (buf, &map);\n\n GST_DEBUG (\"codec_data: object_type=%d, sample_rate=%d, channels=%d, \"\n \"samples=%d\", aacparse->object_type, aacparse->sample_rate,\n aacparse->channels, aacparse->frame_samples);\n\n /* arrange for metadata and get out of the way */\n gst_aac_parse_set_src_caps (aacparse, caps);\n if (aacparse->header_type == aacparse->output_header_type)\n gst_base_parse_set_passthrough (parse, TRUE);\n } else {\n return FALSE;\n }\n\n /* caps info overrides */\n gst_structure_get_int (structure, \"rate\", &aacparse->sample_rate);\n gst_structure_get_int (structure, \"channels\", &aacparse->channels);\n } else {\n const gchar *stream_format =\n gst_structure_get_string (structure, \"stream-format\");\n\n if (g_strcmp0 (stream_format, \"raw\") == 0) {\n GST_ERROR_OBJECT (parse, \"Need codec_data for raw AAC\");\n return FALSE;\n } else {\n aacparse->sample_rate = 0;\n aacparse->channels = 0;\n aacparse->header_type = DSPAAC_HEADER_NOT_PARSED;\n gst_base_parse_set_passthrough (parse, FALSE);\n }\n }\n return TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'aacparse: Make sure we have enough data in the codec_data to be able to parse it\n\nAlso error out cleanly if mapping the buffer failed.\n\nhttps://bugzilla.gnome.org/show_bug.cgi?id=775450'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int sctp_wait_for_sndbuf(struct sctp_association *asoc, long *timeo_p,\n\t\t\t\tsize_t msg_len)\n{\n\tstruct sock *sk = asoc->base.sk;\n\tint err = 0;\n\tlong current_timeo = *timeo_p;\n\tDEFINE_WAIT(wait);\n\n\tpr_debug(\"%s: asoc:%p, timeo:%ld, msg_len:%zu\\n\", __func__, asoc,\n\t\t *timeo_p, msg_len);\n\n\t/* Increment the association's refcnt. */\n\tsctp_association_hold(asoc);\n\n\t/* Wait on the association specific sndbuf space. */\n\tfor (;;) {\n\t\tprepare_to_wait_exclusive(&asoc->wait, &wait,\n\t\t\t\t\t TASK_INTERRUPTIBLE);\n\t\tif (!*timeo_p)\n\t\t\tgoto do_nonblock;\n\t\tif (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING ||\n\t\t asoc->base.dead)\n\t\t\tgoto do_error;\n\t\tif (signal_pending(current))\n\t\t\tgoto do_interrupted;\n\t\tif (msg_len <= sctp_wspace(asoc))\n\t\t\tbreak;\n\n\t\t/* Let another process have a go. Since we are going\n\t\t * to sleep anyway.\n\t\t */\n\t\trelease_sock(sk);\n\t\tcurrent_timeo = schedule_timeout(current_timeo);\n\t\tBUG_ON(sk != asoc->base.sk);\n\t\tlock_sock(sk);\n\n\t\t*timeo_p = current_timeo;\n\t}\n\nout:\n\tfinish_wait(&asoc->wait, &wait);\n\n\t/* Release the association's refcnt. */\n\tsctp_association_put(asoc);\n\n\treturn err;\n\ndo_error:\n\terr = -EPIPE;\n\tgoto out;\n\ndo_interrupted:\n\terr = sock_intr_errno(*timeo_p);\n\tgoto out;\n\ndo_nonblock:\n\terr = -EAGAIN;\n\tgoto out;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617', 'CWE-362'], 'message': 'sctp: avoid BUG_ON on sctp_wait_for_sndbuf\n\nAlexander Popov reported that an application may trigger a BUG_ON in\nsctp_wait_for_sndbuf if the socket tx buffer is full, a thread is\nwaiting on it to queue more data and meanwhile another thread peels off\nthe association being used by the first thread.\n\nThis patch replaces the BUG_ON call with a proper error handling. It\nwill return -EPIPE to the original sendmsg call, similarly to what would\nhave been done if the association wasn't found in the first place.\n\nAcked-by: Alexander Popov \nSigned-off-by: Marcelo Ricardo Leitner \nReviewed-by: Xin Long \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 __init init_timer_stats(void)\n{\n\tint cpu;\n\n\tfor_each_possible_cpu(cpu)\n\t\traw_spin_lock_init(&per_cpu(tstats_lookup_lock, cpu));\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 tstats_show(struct seq_file *m, void *v)\n{\n\tstruct timespec64 period;\n\tstruct entry *entry;\n\tunsigned long ms;\n\tlong events = 0;\n\tktime_t time;\n\tint i;\n\n\tmutex_lock(&show_mutex);\n\t/*\n\t * If still active then calculate up to now:\n\t */\n\tif (timer_stats_active)\n\t\ttime_stop = ktime_get();\n\n\ttime = ktime_sub(time_stop, time_start);\n\n\tperiod = ktime_to_timespec64(time);\n\tms = period.tv_nsec / 1000000;\n\n\tseq_puts(m, \"Timer Stats Version: v0.3\\n\");\n\tseq_printf(m, \"Sample period: %ld.%03ld s\\n\", (long)period.tv_sec, ms);\n\tif (atomic_read(&overflow_count))\n\t\tseq_printf(m, \"Overflow: %d entries\\n\", atomic_read(&overflow_count));\n\tseq_printf(m, \"Collection: %s\\n\", timer_stats_active ? \"active\" : \"inactive\");\n\n\tfor (i = 0; i < nr_entries; i++) {\n\t\tentry = entries + i;\n\t\tif (entry->flags & TIMER_DEFERRABLE) {\n\t\t\tseq_printf(m, \"%4luD, %5d %-16s \",\n\t\t\t\tentry->count, entry->pid, entry->comm);\n\t\t} else {\n\t\t\tseq_printf(m, \" %4lu, %5d %-16s \",\n\t\t\t\tentry->count, entry->pid, entry->comm);\n\t\t}\n\n\t\tprint_name_offset(m, (unsigned long)entry->start_func);\n\t\tseq_puts(m, \" (\");\n\t\tprint_name_offset(m, (unsigned long)entry->expire_func);\n\t\tseq_puts(m, \")\\n\");\n\n\t\tevents += entry->count;\n\t}\n\n\tms += period.tv_sec * 1000;\n\tif (!ms)\n\t\tms = 1;\n\n\tif (events && period.tv_sec)\n\t\tseq_printf(m, \"%ld total events, %ld.%03ld events/sec\\n\",\n\t\t\t events, events * 1000 / ms,\n\t\t\t (events * 1000000 / ms) % 1000);\n\telse\n\t\tseq_printf(m, \"%ld total events\\n\", events);\n\n\tmutex_unlock(&show_mutex);\n\n\treturn 0;\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: void timer_stats_update_stats(void *timer, pid_t pid, void *startf,\n\t\t\t void *timerf, char *comm, u32 tflags)\n{\n\t/*\n\t * It doesn't matter which lock we take:\n\t */\n\traw_spinlock_t *lock;\n\tstruct entry *entry, input;\n\tunsigned long flags;\n\n\tif (likely(!timer_stats_active))\n\t\treturn;\n\n\tlock = &per_cpu(tstats_lookup_lock, raw_smp_processor_id());\n\n\tinput.timer = timer;\n\tinput.start_func = startf;\n\tinput.expire_func = timerf;\n\tinput.pid = pid;\n\tinput.flags = tflags;\n\n\traw_spin_lock_irqsave(lock, flags);\n\tif (!timer_stats_active)\n\t\tgoto out_unlock;\n\n\tentry = tstat_lookup(&input, comm);\n\tif (likely(entry))\n\t\tentry->count++;\n\telse\n\t\tatomic_inc(&overflow_count);\n\n out_unlock:\n\traw_spin_unlock_irqrestore(lock, flags);\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 print_name_offset(struct seq_file *m, unsigned long addr)\n{\n\tchar symname[KSYM_NAME_LEN];\n\n\tif (lookup_symbol_name(addr, symname) < 0)\n\t\tseq_printf(m, \"<%p>\", (void *)addr);\n\telse\n\t\tseq_printf(m, \"%s\", symname);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'time: Remove CONFIG_TIMER_STATS\n\nCurrently CONFIG_TIMER_STATS exposes process information across namespaces:\n\nkernel/time/timer_list.c print_timer():\n\n SEQ_printf(m, \", %s/%d\", tmp, timer->start_pid);\n\n/proc/timer_list:\n\n #11: <0000000000000000>, hrtimer_wakeup, S:01, do_nanosleep, cron/2570\n\nGiven that the tracer can give the same information, this patch entirely\nremoves CONFIG_TIMER_STATS.\n\nSuggested-by: Thomas Gleixner \nSigned-off-by: Kees Cook \nAcked-by: John Stultz \nCc: Nicolas Pitre \nCc: linux-doc@vger.kernel.org\nCc: Lai Jiangshan \nCc: Shuah Khan \nCc: Xing Gao \nCc: Jonathan Corbet \nCc: Jessica Frazelle \nCc: kernel-hardening@lists.openwall.com\nCc: Nicolas Iooss \nCc: \"Paul E. McKenney\" \nCc: Petr Mladek \nCc: Richard Cochran \nCc: Tejun Heo \nCc: Michal Marek \nCc: Josh Poimboeuf \nCc: Dmitry Vyukov \nCc: Oleg Nesterov \nCc: \"Eric W. Biederman\" \nCc: Olof Johansson \nCc: Andrew Morton \nCc: linux-api@vger.kernel.org\nCc: Arjan van de Ven \nLink: http://lkml.kernel.org/r/20170208192659.GA32582@beast\nSigned-off-by: Thomas Gleixner '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int oidc_handle_redirect_uri_request(request_rec *r, oidc_cfg *c,\n\t\toidc_session_t *session) {\n\n\tif (oidc_proto_is_redirect_authorization_response(r, c)) {\n\n\t\t/* this is an authorization response from the OP using the Basic Client profile or a Hybrid flow*/\n\t\treturn oidc_handle_redirect_authorization_response(r, c, session);\n\n\t} else if (oidc_proto_is_post_authorization_response(r, c)) {\n\n\t\t/* this is an authorization response using the fragment(+POST) response_mode with the Implicit Client profile */\n\t\treturn oidc_handle_post_authorization_response(r, c, session);\n\n\t} else if (oidc_is_discovery_response(r, c)) {\n\n\t\t/* this is response from the OP discovery page */\n\t\treturn oidc_handle_discovery_response(r, c);\n\n\t} else if (oidc_util_request_has_parameter(r, \"logout\")) {\n\n\t\t/* handle logout */\n\t\treturn oidc_handle_logout(r, c, session);\n\n\t} else if (oidc_util_request_has_parameter(r, \"jwks\")) {\n\n\t\t/* handle JWKs request */\n\t\treturn oidc_handle_jwks(r, c);\n\n\t} else if (oidc_util_request_has_parameter(r, \"session\")) {\n\n\t\t/* handle session management request */\n\t\treturn oidc_handle_session_management(r, c, session);\n\n\t} else if (oidc_util_request_has_parameter(r, \"refresh\")) {\n\n\t\t/* handle refresh token request */\n\t\treturn oidc_handle_refresh_token_request(r, c, session);\n\n\t} else if (oidc_util_request_has_parameter(r, \"request_uri\")) {\n\n\t\t/* handle request object by reference request */\n\t\treturn oidc_handle_request_uri(r, c);\n\n\t} else if (oidc_util_request_has_parameter(r, \"remove_at_cache\")) {\n\n\t\t/* handle request to invalidate access token cache */\n\t\treturn oidc_handle_remove_at_cache(r, c);\n\n\t} else if ((r->args == NULL) || (apr_strnatcmp(r->args, \"\") == 0)) {\n\n\t\t/* this is a \"bare\" request to the redirect URI, indicating implicit flow using the fragment response_mode */\n\t\treturn oidc_proto_javascript_implicit(r, c);\n\t}\n\n\t/* this is not an authorization response or logout request */\n\n\t/* check for \"error\" response */\n\tif (oidc_util_request_has_parameter(r, \"error\")) {\n\n//\t\tchar *error = NULL, *descr = NULL;\n//\t\toidc_util_get_request_parameter(r, \"error\", &error);\n//\t\toidc_util_get_request_parameter(r, \"error_description\", &descr);\n//\n//\t\t/* send user facing error to browser */\n//\t\treturn oidc_util_html_send_error(r, error, descr, DONE);\n\t\toidc_handle_redirect_authorization_response(r, c, session);\n\t}\n\n\t/* something went wrong */\n\treturn oidc_util_html_send_error(r, c->error_template, \"Invalid Request\",\n\t\t\tapr_psprintf(r->pool,\n\t\t\t\t\t\"The OpenID Connect callback URL received an invalid request: %s\",\n\t\t\t\t\tr->args), HTTP_INTERNAL_SERVER_ERROR);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'don't echo query params on invalid requests to redirect URI; closes #212\n\nthanks @LukasReschke; I'm sure there's some OWASP guideline that warns\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: static void write_png_palette(int idx, uint32_t pix, void *opaque)\n{\n struct palette_cb_priv *priv = opaque;\n VncState *vs = priv->vs;\n png_colorp color = &priv->png_palette[idx];\n\n if (vs->tight.pixel24)\n {\n color->red = (pix >> vs->clientds.pf.rshift) & vs->clientds.pf.rmax;\n color->green = (pix >> vs->clientds.pf.gshift) & vs->clientds.pf.gmax;\n color->blue = (pix >> vs->clientds.pf.bshift) & vs->clientds.pf.bmax;\n }\n else\n {\n int red, green, blue;\n\n red = (pix >> vs->clientds.pf.rshift) & vs->clientds.pf.rmax;\n green = (pix >> vs->clientds.pf.gshift) & vs->clientds.pf.gmax;\n blue = (pix >> vs->clientds.pf.bshift) & vs->clientds.pf.bmax;\n color->red = ((red * 255 + vs->clientds.pf.rmax / 2) /\n vs->clientds.pf.rmax);\n color->green = ((green * 255 + vs->clientds.pf.gmax / 2) /\n vs->clientds.pf.gmax);\n color->blue = ((blue * 255 + vs->clientds.pf.bmax / 2) /\n vs->clientds.pf.bmax);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'pixman/vnc: use pixman images in vnc.\n\nThe vnc code uses *three* DisplaySurfaces:\n\nFirst is the surface of the actual QemuConsole, usually the guest\nscreen, but could also be a text console (monitor/serial reachable via\nCtrl-Alt- keys). This is left as-is.\n\nSecond is the current server's view of the screen content. The vnc code\nuses this to figure which parts of the guest screen did _really_ change\nto reduce the amount of updates sent to the vnc clients. It is also\nused as data source when sending out the updates to the clients. This\nsurface gets replaced by a pixman image. The format changes too,\ninstead of using the guest screen format we'll use fixed 32bit rgb\nframebuffer and convert the pixels on the fly when comparing and\nupdating the server framebuffer.\n\nThird surface carries the format expected by the vnc client. That isn't\nused to store image data. This surface is switched to PixelFormat and a\nboolean for bigendian byte order.\n\nSigned-off-by: Gerd Hoffmann '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int vnc_refresh_server_surface(VncDisplay *vd)\n{\n int y;\n uint8_t *guest_row;\n uint8_t *server_row;\n int cmp_bytes;\n VncState *vs;\n int has_dirty = 0;\n\n struct timeval tv = { 0, 0 };\n\n if (!vd->non_adaptive) {\n gettimeofday(&tv, NULL);\n has_dirty = vnc_update_stats(vd, &tv);\n }\n\n /*\n * Walk through the guest dirty map.\n * Check and copy modified bits from guest to server surface.\n * Update server dirty map.\n */\n cmp_bytes = 16 * ds_get_bytes_per_pixel(vd->ds);\n if (cmp_bytes > vd->ds->surface->linesize) {\n cmp_bytes = vd->ds->surface->linesize;\n }\n guest_row = vd->guest.ds->data;\n server_row = vd->server->data;\n for (y = 0; y < vd->guest.ds->height; y++) {\n if (!bitmap_empty(vd->guest.dirty[y], VNC_DIRTY_BITS)) {\n int x;\n uint8_t *guest_ptr;\n uint8_t *server_ptr;\n\n guest_ptr = guest_row;\n server_ptr = server_row;\n\n for (x = 0; x + 15 < vd->guest.ds->width;\n x += 16, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {\n if (!test_and_clear_bit((x / 16), vd->guest.dirty[y]))\n continue;\n if (memcmp(server_ptr, guest_ptr, cmp_bytes) == 0)\n continue;\n memcpy(server_ptr, guest_ptr, cmp_bytes);\n if (!vd->non_adaptive)\n vnc_rect_updated(vd, x, y, &tv);\n QTAILQ_FOREACH(vs, &vd->clients, next) {\n set_bit((x / 16), vs->dirty[y]);\n }\n has_dirty++;\n }\n }\n guest_row += ds_get_linesize(vd->ds);\n server_row += ds_get_linesize(vd->ds);\n }\n return has_dirty;\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 void rgb_prepare_row(VncState *vs, uint8_t *dst, int x, int y,\n int count)\n{\n if (ds_get_bytes_per_pixel(vs->ds) == 4) {\n if (vs->ds->surface->pf.rmax == 0xFF &&\n vs->ds->surface->pf.gmax == 0xFF &&\n vs->ds->surface->pf.bmax == 0xFF) {\n rgb_prepare_row24(vs, dst, x, y, count);\n } else {\n rgb_prepare_row32(vs, dst, x, y, count);\n }\n } else {\n rgb_prepare_row16(vs, dst, x, y, count);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'pixman/vnc: use pixman images in vnc.\n\nThe vnc code uses *three* DisplaySurfaces:\n\nFirst is the surface of the actual QemuConsole, usually the guest\nscreen, but could also be a text console (monitor/serial reachable via\nCtrl-Alt- keys). This is left as-is.\n\nSecond is the current server's view of the screen content. The vnc code\nuses this to figure which parts of the guest screen did _really_ change\nto reduce the amount of updates sent to the vnc clients. It is also\nused as data source when sending out the updates to the clients. This\nsurface gets replaced by a pixman image. The format changes too,\ninstead of using the guest screen format we'll use fixed 32bit rgb\nframebuffer and convert the pixels on the fly when comparing and\nupdating the server framebuffer.\n\nThird surface carries the format expected by the vnc client. That isn't\nused to store image data. This surface is switched to PixelFormat and a\nboolean for bigendian byte order.\n\nSigned-off-by: Gerd Hoffmann '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int vnc_update_stats(VncDisplay *vd, struct timeval * tv)\n{\n int x, y;\n struct timeval res;\n int has_dirty = 0;\n\n for (y = 0; y < vd->guest.ds->height; y += VNC_STAT_RECT) {\n for (x = 0; x < vd->guest.ds->width; x += VNC_STAT_RECT) {\n VncRectStat *rect = vnc_stat_rect(vd, x, y);\n\n rect->updated = false;\n }\n }\n\n qemu_timersub(tv, &VNC_REFRESH_STATS, &res);\n\n if (timercmp(&vd->guest.last_freq_check, &res, >)) {\n return has_dirty;\n }\n vd->guest.last_freq_check = *tv;\n\n for (y = 0; y < vd->guest.ds->height; y += VNC_STAT_RECT) {\n for (x = 0; x < vd->guest.ds->width; x += VNC_STAT_RECT) {\n VncRectStat *rect= vnc_stat_rect(vd, x, y);\n int count = ARRAY_SIZE(rect->times);\n struct timeval min, max;\n\n if (!timerisset(&rect->times[count - 1])) {\n continue ;\n }\n\n max = rect->times[(rect->idx + count - 1) % count];\n qemu_timersub(tv, &max, &res);\n\n if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {\n rect->freq = 0;\n has_dirty += vnc_refresh_lossy_rect(vd, x, y);\n memset(rect->times, 0, sizeof (rect->times));\n continue ;\n }\n\n min = rect->times[rect->idx];\n max = rect->times[(rect->idx + count - 1) % count];\n qemu_timersub(&max, &min, &res);\n\n rect->freq = res.tv_sec + res.tv_usec / 1000000.;\n rect->freq /= count;\n rect->freq = 1. / rect->freq;\n }\n }\n return has_dirty;\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 void ip_cmsg_recv_checksum(struct msghdr *msg, struct sk_buff *skb,\n\t\t\t\t int tlen, int offset)\n{\n\t__wsum csum = skb->csum;\n\n\tif (skb->ip_summed != CHECKSUM_COMPLETE)\n\t\treturn;\n\n\tif (offset != 0)\n\t\tcsum = csum_sub(csum,\n\t\t\t\tcsum_partial(skb_transport_header(skb) + tlen,\n\t\t\t\t\t offset, 0));\n\n\tput_cmsg(msg, SOL_IP, IP_CHECKSUM, sizeof(__wsum), &csum);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'ip: fix IP_CHECKSUM handling\n\nThe skbs processed by ip_cmsg_recv() are not guaranteed to\nbe linear e.g. when sending UDP packets over loopback with\nMSGMORE.\nUsing csum_partial() on [potentially] the whole skb len\nis dangerous; instead be on the safe side and use skb_checksum().\n\nThanks to syzkaller team to detect the issue and provide the\nreproducer.\n\nv1 -> v2:\n - move the variable declaration in a tighter scope\n\nFixes: ad6f939ab193 (\"ip: Add offset parameter to ip_cmsg_recv\")\nReported-by: Andrey Konovalov \nSigned-off-by: Paolo Abeni \nAcked-by: Eric Dumazet \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: key_ref_t keyring_search(key_ref_t keyring,\n\t\t\t struct key_type *type,\n\t\t\t const char *description)\n{\n\tstruct keyring_search_context ctx = {\n\t\t.index_key.type\t\t= type,\n\t\t.index_key.description\t= description,\n\t\t.cred\t\t\t= current_cred(),\n\t\t.match_data.cmp\t\t= type->match,\n\t\t.match_data.raw_data\t= description,\n\t\t.match_data.lookup_type\t= KEYRING_SEARCH_LOOKUP_DIRECT,\n\t\t.flags\t\t\t= KEYRING_SEARCH_DO_STATE_CHECK,\n\t};\n\tkey_ref_t key;\n\tint ret;\n\n\tif (!ctx.match_data.cmp)\n\t\treturn ERR_PTR(-ENOKEY);\n\n\tif (type->match_preparse) {\n\t\tret = type->match_preparse(&ctx.match_data);\n\t\tif (ret < 0)\n\t\t\treturn ERR_PTR(ret);\n\t}\n\n\tkey = keyring_search_aux(keyring, &ctx);\n\n\tif (type->match_free)\n\t\ttype->match_free(&ctx.match_data);\n\treturn key;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'KEYS: Remove key_type::match in favour of overriding default by match_preparse\n\nA previous patch added a ->match_preparse() method to the key type. This is\nallowed to override the function called by the iteration algorithm.\nTherefore, we can just set a default that simply checks for an exact match of\nthe key description with the original criterion data and allow match_preparse\nto override it as needed.\n\nThe key_type::match op is then redundant and can be removed, as can the\nuser_match() function.\n\nSigned-off-by: David Howells \nAcked-by: Vivek Goyal '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void fanout_release(struct sock *sk)\n{\n\tstruct packet_sock *po = pkt_sk(sk);\n\tstruct packet_fanout *f;\n\n\tf = po->fanout;\n\tif (!f)\n\t\treturn;\n\n\tmutex_lock(&fanout_mutex);\n\tpo->fanout = NULL;\n\n\tif (atomic_dec_and_test(&f->sk_ref)) {\n\t\tlist_del(&f->list);\n\t\tdev_remove_pack(&f->prot_hook);\n\t\tfanout_release_data(f);\n\t\tkfree(f);\n\t}\n\tmutex_unlock(&fanout_mutex);\n\n\tif (po->rollover)\n\t\tkfree_rcu(po->rollover, rcu);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-362'], 'message': 'packet: fix races in fanout_add()\n\nMultiple threads can call fanout_add() at the same time.\n\nWe need to grab fanout_mutex earlier to avoid races that could\nlead to one thread freeing po->rollover that was set by another thread.\n\nDo the same in fanout_release(), for peace of mind, and to help us\nfinding lockdep issues earlier.\n\nFixes: dc99f600698d (\"packet: Add fanout support.\")\nFixes: 0648ab70afe6 (\"packet: rollover prepare: per-socket state\")\nSigned-off-by: Eric Dumazet \nCc: Willem de Bruijn \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void PropertiesWidget::loadTorrentInfos(BitTorrent::TorrentHandle *const torrent)\n{\n clear();\n m_torrent = torrent;\n downloaded_pieces->setTorrent(m_torrent);\n pieces_availability->setTorrent(m_torrent);\n if (!m_torrent) return;\n\n // Save path\n updateSavePath(m_torrent);\n // Hash\n hash_lbl->setText(m_torrent->hash());\n PropListModel->model()->clear();\n if (m_torrent->hasMetadata()) {\n // Creation date\n lbl_creationDate->setText(m_torrent->creationDate().toString(Qt::DefaultLocaleShortDate));\n\n label_total_size_val->setText(Utils::Misc::friendlyUnit(m_torrent->totalSize()));\n\n // Comment\n comment_text->setText(Utils::Misc::parseHtmlLinks(m_torrent->comment()));\n\n // URL seeds\n loadUrlSeeds();\n\n label_created_by_val->setText(m_torrent->creator());\n\n // List files in torrent\n PropListModel->model()->setupModelData(m_torrent->info());\n filesList->setExpanded(PropListModel->index(0, 0), true);\n\n // Load file priorities\n PropListModel->model()->updateFilesPriorities(m_torrent->filePriorities());\n }\n // Load dynamic data\n loadDynamicData();\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_get_request_session(request_rec *r)\n{\n const char *session_id;\n\n /* Get session id from cookie. */\n session_id = am_cookie_get(r);\n if(session_id == NULL) {\n /* Cookie is unset - we don't have a session. */\n return NULL;\n }\n\n return am_cache_lock(r->server, AM_CACHE_SESSION, session_id);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-79'], 'message': 'Fix Cross-Site Session Transfer vulnerability\n\nmod_auth_mellon did not verify that the site the session was created\nfor was the same site as the site the user accessed. This allows an\nattacker with access to one web site on a server to use the same\nsession to get access to a different site running on the same server.\n\nThis patch fixes this vulnerability by storing the cookie parameters\nused when creating the session in the session, and verifying those\nparameters when the session is loaded.\n\nThanks to Fran\u00e7ois Kooman for reporting this vulnerability.\n\nThis vulnerability has been assigned CVE-2017-6807.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: sql_real_connect(char *host,char *database,char *user,char *password,\n\t\t uint silent)\n{\n my_bool handle_expired= (opt_connect_expired_password || !status.batch) ?\n TRUE : FALSE;\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_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_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 {\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#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_set_character_set(&mysql, default_charset);\n#ifdef __WIN__\n uint cnv_errors;\n String converted_database, converted_user;\n if (!my_charset_same(&my_charset_utf8mb4_bin, mysql.charset))\n {\n /* Convert user and database from UTF8MB4 to connection character set */\n if (user)\n {\n converted_user.copy(user, strlen(user) + 1,\n &my_charset_utf8mb4_bin, mysql.charset,\n &cnv_errors);\n user= (char *) converted_user.ptr();\n }\n if (database)\n {\n converted_database.copy(database, strlen(database) + 1,\n &my_charset_utf8mb4_bin, mysql.charset,\n &cnv_errors);\n database= (char *) converted_database.ptr();\n }\n }\n#endif\n \n if (opt_plugin_dir && *opt_plugin_dir)\n mysql_options(&mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir);\n\n if (opt_default_auth && *opt_default_auth)\n mysql_options(&mysql, MYSQL_DEFAULT_AUTH, opt_default_auth);\n\n#if !defined(HAVE_YASSL)\n if (opt_server_public_key && *opt_server_public_key)\n mysql_options(&mysql, MYSQL_SERVER_PUBLIC_KEY, opt_server_public_key);\n#endif\n\n if (using_opt_enable_cleartext_plugin)\n mysql_options(&mysql, MYSQL_ENABLE_CLEARTEXT_PLUGIN, \n (char*) &opt_enable_cleartext_plugin);\n\n mysql_options(&mysql, MYSQL_OPT_CONNECT_ATTR_RESET, 0);\n mysql_options4(&mysql, MYSQL_OPT_CONNECT_ATTR_ADD, \n \"program_name\", \"mysql\");\n mysql_options(&mysql, MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS, &handle_expired);\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#ifdef __WIN__\n /* Convert --execute buffer from UTF8MB4 to connection character set */\n if (!execute_buffer_conversion_done++ &&\n status.line_buff &&\n !status.line_buff->file && /* Convert only -e buffer, not real file */\n status.line_buff->buffer < status.line_buff->end && /* Non-empty */\n !my_charset_same(&my_charset_utf8mb4_bin, mysql.charset))\n {\n String tmp;\n size_t len= status.line_buff->end - status.line_buff->buffer;\n uint dummy_errors;\n /*\n Don't convert trailing '\\n' character - it was appended during\n last batch_readline_command() call. \n Oherwise we'll get an extra line, which makes some tests fail.\n */\n if (status.line_buff->buffer[len - 1] == '\\n')\n len--;\n if (tmp.copy(status.line_buff->buffer, len,\n &my_charset_utf8mb4_bin, mysql.charset, &dummy_errors))\n return 1;\n\n /* Free the old line buffer */\n batch_readline_end(status.line_buff);\n\n /* Re-initialize line buffer from the converted string */\n if (!(status.line_buff= batch_readline_command(NULL, (char *) tmp.c_ptr_safe())))\n return 1;\n }\n#endif /* __WIN__ */\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 f91b941842d240b8a62645e507f5554e8be76aec)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int STDCALL\nmysql_options(MYSQL *mysql,enum mysql_option option, const void *arg)\n{\n DBUG_ENTER(\"mysql_option\");\n DBUG_PRINT(\"enter\",(\"option: %d\",(int) option));\n switch (option) {\n case MYSQL_OPT_CONNECT_TIMEOUT:\n mysql->options.connect_timeout= *(uint*) arg;\n break;\n case MYSQL_OPT_READ_TIMEOUT:\n mysql->options.read_timeout= *(uint*) arg;\n break;\n case MYSQL_OPT_WRITE_TIMEOUT:\n mysql->options.write_timeout= *(uint*) arg;\n break;\n case MYSQL_OPT_COMPRESS:\n mysql->options.compress= 1;\t\t\t/* Remember for connect */\n mysql->options.client_flag|= CLIENT_COMPRESS;\n break;\n case MYSQL_OPT_NAMED_PIPE:\t\t\t/* This option is depricated */\n mysql->options.protocol=MYSQL_PROTOCOL_PIPE; /* Force named pipe */\n break;\n case MYSQL_OPT_LOCAL_INFILE:\t\t\t/* Allow LOAD DATA LOCAL ?*/\n if (!arg || test(*(uint*) arg))\n mysql->options.client_flag|= CLIENT_LOCAL_FILES;\n else\n mysql->options.client_flag&= ~CLIENT_LOCAL_FILES;\n break;\n case MYSQL_INIT_COMMAND:\n add_init_command(&mysql->options,arg);\n break;\n case MYSQL_READ_DEFAULT_FILE:\n my_free(mysql->options.my_cnf_file);\n mysql->options.my_cnf_file=my_strdup(arg,MYF(MY_WME));\n break;\n case MYSQL_READ_DEFAULT_GROUP:\n my_free(mysql->options.my_cnf_group);\n mysql->options.my_cnf_group=my_strdup(arg,MYF(MY_WME));\n break;\n case MYSQL_SET_CHARSET_DIR:\n my_free(mysql->options.charset_dir);\n mysql->options.charset_dir=my_strdup(arg,MYF(MY_WME));\n break;\n case MYSQL_SET_CHARSET_NAME:\n my_free(mysql->options.charset_name);\n mysql->options.charset_name=my_strdup(arg,MYF(MY_WME));\n break;\n case MYSQL_OPT_PROTOCOL:\n mysql->options.protocol= *(uint*) arg;\n break;\n case MYSQL_SHARED_MEMORY_BASE_NAME:\n#ifdef HAVE_SMEM\n if (mysql->options.shared_memory_base_name != def_shared_memory_base_name)\n my_free(mysql->options.shared_memory_base_name);\n mysql->options.shared_memory_base_name=my_strdup(arg,MYF(MY_WME));\n#endif\n break;\n case MYSQL_OPT_USE_REMOTE_CONNECTION:\n case MYSQL_OPT_USE_EMBEDDED_CONNECTION:\n case MYSQL_OPT_GUESS_CONNECTION:\n mysql->options.methods_to_use= option;\n break;\n case MYSQL_SET_CLIENT_IP:\n my_free(mysql->options.client_ip);\n mysql->options.client_ip= my_strdup(arg, MYF(MY_WME));\n break;\n case MYSQL_SECURE_AUTH:\n mysql->options.secure_auth= *(my_bool *) arg;\n break;\n case MYSQL_REPORT_DATA_TRUNCATION:\n mysql->options.report_data_truncation= test(*(my_bool *) arg);\n break;\n case MYSQL_OPT_RECONNECT:\n mysql->reconnect= *(my_bool *) arg;\n break;\n case MYSQL_OPT_SSL_VERIFY_SERVER_CERT:\n if (*(my_bool*) arg)\n mysql->options.client_flag|= CLIENT_SSL_VERIFY_SERVER_CERT;\n else\n mysql->options.client_flag&= ~CLIENT_SSL_VERIFY_SERVER_CERT;\n break;\n case MYSQL_PLUGIN_DIR:\n EXTENSION_SET_STRING(&mysql->options, plugin_dir, arg);\n break;\n case MYSQL_DEFAULT_AUTH:\n EXTENSION_SET_STRING(&mysql->options, default_auth, arg);\n break;\n case MYSQL_ENABLE_CLEARTEXT_PLUGIN:\n ENSURE_EXTENSIONS_PRESENT(&mysql->options);\n mysql->options.extension->enable_cleartext_plugin= \n (*(my_bool*) arg) ? TRUE : FALSE;\n break;\n default:\n DBUG_RETURN(1);\n }\n DBUG_RETURN(0); ; 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: int main(int argc, char **argv)\n{\n int error;\n my_bool first_argument_uses_wildcards=0;\n char *wild;\n MYSQL mysql;\n MY_INIT(argv[0]);\n if (load_defaults(\"my\",load_default_groups,&argc,&argv))\n exit(1);\n\n get_options(&argc,&argv);\n\n wild=0;\n if (argc)\n {\n char *pos= argv[argc-1], *to;\n for (to= pos ; *pos ; pos++, to++)\n {\n switch (*pos) {\n case '*':\n\t*pos= '%';\n\tfirst_argument_uses_wildcards= 1;\n\tbreak;\n case '?':\n\t*pos= '_';\n\tfirst_argument_uses_wildcards= 1;\n\tbreak;\n case '%':\n case '_':\n\tfirst_argument_uses_wildcards= 1;\n\tbreak;\n case '\\\\':\n\tpos++;\n default: break;\n }\n *to= *pos;\n } \n *to= *pos; /* just to copy a '\\0' if '\\\\' was used */\n }\n if (first_argument_uses_wildcards)\n wild= argv[--argc];\n else if (argc == 3)\t\t\t/* We only want one field */\n wild= argv[--argc];\n\n if (argc > 2)\n {\n fprintf(stderr,\"%s: Too many arguments\\n\",my_progname);\n exit(1);\n }\n mysql_init(&mysql);\n if (opt_compress)\n mysql_options(&mysql,MYSQL_OPT_COMPRESS,NullS);\n#ifdef HAVE_OPENSSL\n if (opt_use_ssl)\n mysql_ssl_set(&mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,\n\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 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, opt_password,\n\t\t\t (first_argument_uses_wildcards) ? \"\" :\n argv[0], opt_mysql_port, opt_mysql_unix_port,\n\t\t\t 0, opt_ssl_required)))\n {\n fprintf(stderr,\"%s: %s\\n\",my_progname,mysql_error(&mysql));\n exit(1);\n }\n mysql.reconnect= 1;\n\n switch (argc) {\n case 0: error=list_dbs(&mysql,wild); break;\n case 1:\n if (opt_status)\n error=list_table_status(&mysql,argv[0],wild);\n else\n error=list_tables(&mysql,argv[0],wild);\n break;\n default:\n if (opt_status && ! wild)\n error=list_table_status(&mysql,argv[0],argv[1]);\n else\n error=list_fields(&mysql,argv[0],argv[1],wild);\n break;\n }\n mysql_close(&mysql);\t\t\t/* Close & free connection */\n my_free(opt_password);\n#ifdef HAVE_SMEM\n my_free(shared_memory_base_name);\n#endif\n my_end(my_end_arg);\n exit(error ? 1 : 0);\n return 0;\t\t\t\t/* No compiler warnings */\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: static plist_t parse_string_node(const char **bnode, uint64_t size)\n{\n plist_data_t data = plist_new_plist_data();\n\n data->type = PLIST_STRING;\n data->strval = (char *) malloc(sizeof(char) * (size + 1));\n memcpy(data->strval, *bnode, size);\n data->strval[size] = '\\0';\n data->length = strlen(data->strval);\n\n return node_create(NULL, data);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'bplist: Make sure to bail out if malloc() fails in parse_string_node()\n\nCredit to Wang Junjie (#93)'" }, { "text": "[INST] Given the following code containing errors, provide Common 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 IsOptionMember(const char *option,\n const char *options)\n{\n char\n **option_list,\n *string;\n\n int\n number_options;\n\n MagickBooleanType\n member;\n\n register ssize_t\n i;\n\n /*\n Is option a member of the options list?\n */\n if (options == (const char *) NULL)\n return(MagickFalse);\n string=ConstantString(options);\n (void) SubstituteString(&string,\",\",\" \");\n option_list=StringToArgv(string,&number_options);\n string=DestroyString(string);\n if (option_list == (char **) NULL)\n return(MagickFalse);\n member=MagickFalse;\n for (i=1; i < (ssize_t) number_options; i++)\n {\n if ((*option_list[i] == '!') &&\n (LocaleCompare(option,option_list[i]+1) == 0))\n break;\n if (GlobExpression(option,option_list[i],MagickTrue) != MagickFalse)\n {\n member=MagickTrue;\n break;\n }\n option_list[i]=DestroyString(option_list[i]);\n }\n for ( ; i < (ssize_t) number_options; i++)\n option_list[i]=DestroyString(option_list[i]);\n option_list=(char **) RelinquishMagickMemory(option_list);\n return(member);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'Fixed memory leak in IsOptionMember.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (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_putdata(jp2_box_t *box, jas_stream_t *out)\n{\n#if 0\n\tjp2_pclr_t *pclr = &box->data.pclr;\n#endif\n/* Eliminate warning about unused variable. */\nbox = 0;\nout = 0;\n\treturn -1;\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: \nvoid skb_complete_tx_timestamp(struct sk_buff *skb,\n\t\t\t struct skb_shared_hwtstamps *hwtstamps)\n{\n\tstruct sock *sk = skb->sk;\n\n\tif (!skb_may_tx_timestamp(sk, false))\n\t\treturn;\n\n\t/* Take a reference to prevent skb_orphan() from freeing the socket,\n\t * but only if the socket refcount is not zero.\n\t */\n\tif (likely(atomic_inc_not_zero(&sk->sk_refcnt))) {\n\t\t*skb_hwtstamps(skb) = *hwtstamps;\n\t\t__skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND);\n\t\tsock_put(sk);\n\t} ; 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 inline char *parse_ip_address_ex(const char *str, size_t str_len, int *portno, int get_err, zend_string **err)\n{\n\tchar *colon;\n\tchar *host = NULL;\n\n#ifdef HAVE_IPV6\n\tchar *p;\n\n\tif (*(str) == '[' && str_len > 1) {\n\t\t/* IPV6 notation to specify raw address with port (i.e. [fe80::1]:80) */\n\t\tp = memchr(str + 1, ']', str_len - 2);\n\t\tif (!p || *(p + 1) != ':') {\n\t\t\tif (get_err) {\n\t\t\t\t*err = strpprintf(0, \"Failed to parse IPv6 address \\\"%s\\\"\", str);\n\t\t\t}\n\t\t\treturn NULL;\n\t\t}\n\t\t*portno = atoi(p + 2);\n\t\treturn estrndup(str + 1, p - str - 1);\n\t}\n#endif\n\tif (str_len) {\n\t\tcolon = memchr(str, ':', str_len - 1);\n\t} else {\n\t\tcolon = NULL;\n\t}\n\tif (colon) {\n\t\t*portno = atoi(colon + 1);\n\t\thost = estrndup(str, colon - str);\n\t} else {\n\t\tif (get_err) {\n\t\t\t*err = strpprintf(0, \"Failed to parse address \\\"%s\\\"\", str);\n\t\t}\n\t\treturn NULL;\n\t}\n\n\treturn host;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-918'], 'message': 'Detect invalid port in xp_socket parse ip address\n\nFor historical reasons, fsockopen() accepts the port and hostname\nseparately: fsockopen('127.0.0.1', 80)\n\nHowever, with the introdcution of stream transports in PHP 4.3,\nit became possible to include the port in the hostname specifier:\n\nfsockopen('127.0.0.1:80')\nOr more formally: fsockopen('tcp://127.0.0.1:80')\n\nConfusing results when these two forms are combined, however.\nfsockopen('127.0.0.1:80', 443) results in fsockopen() attempting\nto connect to '127.0.0.1:80:443' which any reasonable stack would\nconsider invalid.\n\nUnfortunately, PHP parses the address looking for the first colon\n(with special handling for IPv6, don't worry) and calls atoi()\nfrom there. atoi() in turn, simply stops parsing at the first\nnon-numeric character and returns the value so far.\n\nThe end result is that the explicitly supplied port is treated\nas ignored garbage, rather than producing an error.\n\nThis diff replaces atoi() with strtol() and inspects the\nstop character. If additional \"garbage\" of any kind is found,\nit fails and returns 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: static int get_default_root(pool *p, int allow_symlinks, char **root) {\n config_rec *c = NULL;\n char *dir = NULL;\n int res;\n\n c = find_config(main_server->conf, CONF_PARAM, \"DefaultRoot\", FALSE);\n while (c) {\n pr_signals_handle();\n\n /* Check the groups acl */\n if (c->argc < 2) {\n dir = c->argv[0];\n break;\n }\n\n res = pr_expr_eval_group_and(((char **) c->argv)+1);\n if (res) {\n dir = c->argv[0];\n break;\n }\n\n c = find_config_next(c, c->next, CONF_PARAM, \"DefaultRoot\", FALSE);\n }\n\n if (dir) {\n char *new_dir;\n\n /* Check for any expandable variables. */\n new_dir = path_subst_uservar(p, &dir);\n if (new_dir != NULL) {\n dir = new_dir;\n }\n\n if (strncmp(dir, \"/\", 2) == 0) {\n dir = NULL;\n\n } else {\n char *realdir;\n int xerrno = 0;\n\n if (allow_symlinks == FALSE) {\n char *path, target_path[PR_TUNABLE_PATH_MAX + 1];\n struct stat st;\n size_t pathlen;\n\n /* First, deal with any possible interpolation. dir_realpath() will\n * do this for us, but dir_realpath() ALSO automatically follows\n * symlinks, which is what we do NOT want to do here.\n */\n\n path = dir;\n if (*path != '/') {\n if (*path == '~') {\n if (pr_fs_interpolate(dir, target_path,\n sizeof(target_path)-1) < 0) {\n return -1;\n }\n\n path = target_path;\n }\n }\n\n /* Note: lstat(2) is sensitive to the presence of a trailing slash on\n * the path, particularly in the case of a symlink to a directory.\n * Thus to get the correct test, we need to remove any trailing slash\n * that might be present. Subtle.\n */\n pathlen = strlen(path);\n if (pathlen > 1 &&\n path[pathlen-1] == '/') {\n path[pathlen-1] = '\\0';\n }\n\n pr_fs_clear_cache();\n res = pr_fsio_lstat(path, &st);\n if (res < 0) {\n xerrno = errno;\n\n pr_log_pri(PR_LOG_WARNING, \"error: unable to check %s: %s\", path,\n strerror(xerrno));\n\n errno = xerrno;\n return -1;\n }\n\n if (S_ISLNK(st.st_mode)) {\n pr_log_pri(PR_LOG_WARNING,\n \"error: DefaultRoot %s is a symlink (denied by AllowChrootSymlinks \"\n \"config)\", path);\n errno = EPERM;\n return -1;\n }\n }\n\n /* We need to be the final user here so that if the user has their home\n * directory with a mode the user proftpd is running (i.e. the User\n * directive) as can not traverse down, we can still have the default\n * root.\n */\n\n PRIVS_USER\n realdir = dir_realpath(p, dir);\n xerrno = errno;\n PRIVS_RELINQUISH\n\n if (realdir) {\n dir = realdir;\n\n } else {\n /* Try to provide a more informative message. */\n char interp_dir[PR_TUNABLE_PATH_MAX + 1];\n\n memset(interp_dir, '\\0', sizeof(interp_dir));\n (void) pr_fs_interpolate(dir, interp_dir, sizeof(interp_dir)-1); \n\n pr_log_pri(PR_LOG_NOTICE,\n \"notice: unable to use DefaultRoot '%s' [resolved to '%s']: %s\",\n dir, interp_dir, strerror(xerrno));\n\n errno = xerrno;\n }\n }\n }\n\n *root = dir;\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'Backporting recursive handling of DefaultRoot path, when AllowChrootSymlinks\nis off, to 1.3.5 branch.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: #else\n static int input (yyscan_t yyscanner)\n#endif\n\n{\n\tint c;\n struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;\n\n\t*yyg->yy_c_buf_p = yyg->yy_hold_char;\n\n\tif ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR )\n\t\t{\n\t\t/* yy_c_buf_p now points to the character we want to return.\n\t\t * If this occurs *before* the EOB characters, then it's a\n\t\t * valid NUL; if not, then we've hit the end of the buffer.\n\t\t */\n\t\tif ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )\n\t\t\t/* This was really a NUL. */\n\t\t\t*yyg->yy_c_buf_p = '\\0';\n\n\t\telse\n\t\t\t{ /* need more input */\n\t\t\tyy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr;\n\t\t\t++yyg->yy_c_buf_p;\n\n\t\t\tswitch ( yy_get_next_buffer( yyscanner ) )\n\t\t\t\t{\n\t\t\t\tcase EOB_ACT_LAST_MATCH:\n\t\t\t\t\t/* This happens because yy_g_n_b()\n\t\t\t\t\t * sees that we've accumulated a\n\t\t\t\t\t * token and flags that we need to\n\t\t\t\t\t * try matching the token before\n\t\t\t\t\t * proceeding. But for input(),\n\t\t\t\t\t * there's no matching to consider.\n\t\t\t\t\t * So convert the EOB_ACT_LAST_MATCH\n\t\t\t\t\t * to EOB_ACT_END_OF_FILE.\n\t\t\t\t\t */\n\n\t\t\t\t\t/* Reset buffer status. */\n\t\t\t\t\tre_yyrestart(yyin ,yyscanner);\n\n\t\t\t\t\t/*FALLTHROUGH*/\n\n\t\t\t\tcase EOB_ACT_END_OF_FILE:\n\t\t\t\t\t{\n\t\t\t\t\tif ( re_yywrap(yyscanner ) )\n\t\t\t\t\t\treturn EOF;\n\n\t\t\t\t\tif ( ! yyg->yy_did_buffer_switch_on_eof )\n\t\t\t\t\t\tYY_NEW_FILE;\n#ifdef __cplusplus\n\t\t\t\t\treturn yyinput(yyscanner);\n#else\n\t\t\t\t\treturn input(yyscanner);\n#endif\n\t\t\t\t\t}\n\n\t\t\t\tcase EOB_ACT_CONTINUE_SCAN:\n\t\t\t\t\tyyg->yy_c_buf_p = yyg->yytext_ptr + offset;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tc = *(unsigned char *) yyg->yy_c_buf_p;\t/* cast for 8-bit char's */\n\t*yyg->yy_c_buf_p = '\\0';\t/* preserve yytext */\n\tyyg->yy_hold_char = *++yyg->yy_c_buf_p;\n\n\tif ( c == '\\n' )\n\t\t \n do{ yylineno++;\n yycolumn=0;\n }while(0)\n;\n\n\treturn c; ; 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: header_put_le_8byte (SF_PRIVATE *psf, sf_count_t x)\n{\tif (psf->headindex < SIGNED_SIZEOF (psf->header) - 8)\n\t{\tpsf->header [psf->headindex++] = x ;\n\t\tpsf->header [psf->headindex++] = (x >> 8) ;\n\t\tpsf->header [psf->headindex++] = (x >> 16) ;\n\t\tpsf->header [psf->headindex++] = (x >> 24) ;\n\t\tpsf->header [psf->headindex++] = 0 ;\n\t\tpsf->header [psf->headindex++] = 0 ;\n\t\tpsf->header [psf->headindex++] = 0 ;\n\t\tpsf->header [psf->headindex++] = 0 ;\n\t\t} ;\n} /* header_put_le_8byte */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'src/ : Move to a variable length header buffer\n\nPreviously, the `psf->header` buffer was a fixed length specified by\n`SF_HEADER_LEN` which was set to `12292`. This was problematic for\ntwo reasons; this value was un-necessarily large for the majority\nof files and too small for some others.\n\nNow the size of the header buffer starts at 256 bytes and grows as\nnecessary up to a maximum of 100k.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: psf_close (SF_PRIVATE *psf)\n{\tuint32_t k ;\n\tint\terror = 0 ;\n\n\tif (psf->codec_close)\n\t{\terror = psf->codec_close (psf) ;\n\t\t/* To prevent it being called in psf->container_close(). */\n\t\tpsf->codec_close = NULL ;\n\t\t} ;\n\n\tif (psf->container_close)\n\t\terror = psf->container_close (psf) ;\n\n\terror = psf_fclose (psf) ;\n\tpsf_close_rsrc (psf) ;\n\n\t/* For an ISO C compliant implementation it is ok to free a NULL pointer. */\n\tfree (psf->container_data) ;\n\tfree (psf->codec_data) ;\n\tfree (psf->interleave) ;\n\tfree (psf->dither) ;\n\tfree (psf->peak_info) ;\n\tfree (psf->broadcast_16k) ;\n\tfree (psf->loop_info) ;\n\tfree (psf->instrument) ;\n\tfree (psf->cues) ;\n\tfree (psf->channel_map) ;\n\tfree (psf->format_desc) ;\n\tfree (psf->strings.storage) ;\n\n\tif (psf->wchunks.chunks)\n\t\tfor (k = 0 ; k < psf->wchunks.used ; k++)\n\t\t\tfree (psf->wchunks.chunks [k].data) ;\n\tfree (psf->rchunks.chunks) ;\n\tfree (psf->wchunks.chunks) ;\n\tfree (psf->iterator) ;\n\tfree (psf->cart_16k) ;\n\n\tmemset (psf, 0, sizeof (SF_PRIVATE)) ;\n\tfree (psf) ;\n\n\treturn error ;\n} /* psf_close */ ; 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: sf_open\t(const char *path, int mode, SF_INFO *sfinfo)\n{\tSF_PRIVATE \t*psf ;\n\n\t/* Ultimate sanity check. */\n\tassert (sizeof (sf_count_t) == 8) ;\n\n\tif ((psf = calloc (1, sizeof (SF_PRIVATE))) == NULL)\n\t{\tsf_errno = SFE_MALLOC_FAILED ;\n\t\treturn\tNULL ;\n\t\t} ;\n\n\tpsf_init_files (psf) ;\n\n\tpsf_log_printf (psf, \"File : %s\\n\", path) ;\n\n\tif (copy_filename (psf, path) != 0)\n\t{\tsf_errno = psf->error ;\n\t\treturn\tNULL ;\n\t\t} ;\n\n\tpsf->file.mode = mode ;\n\tif (strcmp (path, \"-\") == 0)\n\t\tpsf->error = psf_set_stdio (psf) ;\n\telse\n\t\tpsf->error = psf_fopen (psf) ;\n\n\treturn psf_open_file (psf, sfinfo) ;\n} /* sf_open */ ; 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_op_unaligned_finish(struct ahash_request *req, int err)\n{\n\tstruct ahash_request_priv *priv = req->priv;\n\n\tif (err == -EINPROGRESS)\n\t\treturn;\n\n\tif (!err)\n\t\tmemcpy(priv->result, req->result,\n\t\t crypto_ahash_digestsize(crypto_ahash_reqtfm(req)));\n\n\tahash_restore_req(req);\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 ModulateHWB(const double percent_hue,\n const double percent_whiteness,const double percent_blackness,double *red,\n double *green,double *blue)\n{\n double\n blackness,\n hue,\n whiteness;\n\n /*\n Increase or decrease color blackness, whiteness, or hue.\n */\n ConvertRGBToHWB(*red,*green,*blue,&hue,&whiteness,&blackness);\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 blackness*=0.01*percent_blackness;\n whiteness*=0.01*percent_whiteness;\n ConvertHWBToRGB(hue,whiteness,blackness,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 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 *pixels,\n *q;\n\n size_t\n extent,\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 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 (IsImageMonochrome(image) != 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+1) >= 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+1) >= 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 /*\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 /*\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 /*\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 /*\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 (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++,\n GetImageListLength(image));\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-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: static int local_name_to_path(FsContext *ctx, V9fsPath *dir_path,\n const char *name, V9fsPath *target)\n{\n if (dir_path) {\n v9fs_path_sprintf(target, \"%s/%s\", dir_path->data, name);\n } else {\n v9fs_path_sprintf(target, \"%s\", name);\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-732'], 'message': '9pfs: local: set the path of the export root to \".\"\n\nThe local backend was recently converted to using \"at*()\" syscalls in order\nto ensure all accesses happen below the shared directory. This requires that\nwe only pass relative paths, otherwise the dirfd argument to the \"at*()\"\nsyscalls is ignored and the path is treated as an absolute path in the host.\nThis is actually the case for paths in all fids, with the notable exception\nof the root fid, whose path is \"/\". This causes the following backend ops to\nact on the \"/\" directory of the host instead of the virtfs shared directory\nwhen the export root is involved:\n- lstat\n- chmod\n- chown\n- utimensat\n\nie, chmod /9p_mount_point in the guest will be converted to chmod / in the\nhost for example. This could cause security issues with a privileged QEMU.\n\nAll \"*at()\" syscalls are being passed an open file descriptor. In the case\nof the export root, this file descriptor points to the path in the host that\nwas passed to -fsdev.\n\nThe fix is thus as simple as changing the path of the export root fid to be\n\".\" instead of \"/\".\n\nThis is CVE-2017-7471.\n\nCc: qemu-stable@nongnu.org\nReported-by: L\u00e9o Gaspard \nSigned-off-by: Greg Kurz \nReviewed-by: Eric Blake \nSigned-off-by: Peter Maydell '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline void glue(rop_32_,ROP_NAME)(uint32_t *dst, uint32_t src)\n{\n *dst = ROP_FN(*dst, src);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around dst pointers in the blitter\n\nInstead pass around the address (aka offset into vga memory). Calculate\nthe pointer in the rop_* functions, after applying the mask to the\naddress, to make sure the address stays within the valid range.\n\nSigned-off-by: Gerd Hoffmann \nMessage-id: 1489574872-8679-1-git-send-email-kraxel@redhat.com'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: glue(cirrus_bitblt_rop_bkwd_, 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 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-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),_8)(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 uint8_t transp = s->vga.gr[0x34];\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++) {\n ROP_OP_TR(s, dstaddr, *src, transp);\n dstaddr++;\n src++;\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 colors[2];\n uint32_t addr;\n int x, y;\n unsigned bits;\n unsigned int col;\n unsigned bitmask;\n int srcskipleft = s->vga.gr[0x2f] & 0x07;\n int dstskipleft = srcskipleft * (DEPTH / 8);\n\n colors[0] = s->cirrus_blt_bgcol;\n colors[1] = s->cirrus_blt_fgcol;\n for(y = 0; y < bltheight; y++) {\n bitmask = 0x80 >> srcskipleft;\n bits = *src++;\n addr = dstaddr + dstskipleft;\n for (x = dstskipleft; x < bltwidth; x += (DEPTH / 8)) {\n if ((bitmask & 0xff) == 0) {\n bitmask = 0x80;\n bits = *src++;\n }\n col = colors[!!(bits & bitmask)];\n PUTPIXEL(s, addr, col);\n addr += (DEPTH / 8);\n bitmask >>= 1;\n }\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_encrypt(struct sk_buff *skb,\n\t\t\t\t struct net_device *dev)\n{\n\tint ret;\n\tstruct scatterlist *sg;\n\tunsigned char *iv;\n\tstruct ethhdr *eth;\n\tstruct macsec_eth_header *hh;\n\tsize_t unprotected_len;\n\tstruct aead_request *req;\n\tstruct macsec_secy *secy;\n\tstruct macsec_tx_sc *tx_sc;\n\tstruct macsec_tx_sa *tx_sa;\n\tstruct macsec_dev *macsec = macsec_priv(dev);\n\tbool sci_present;\n\tu32 pn;\n\n\tsecy = &macsec->secy;\n\ttx_sc = &secy->tx_sc;\n\n\t/* 10.5.1 TX SA assignment */\n\ttx_sa = macsec_txsa_get(tx_sc->sa[tx_sc->encoding_sa]);\n\tif (!tx_sa) {\n\t\tsecy->operational = false;\n\t\tkfree_skb(skb);\n\t\treturn ERR_PTR(-EINVAL);\n\t}\n\n\tif (unlikely(skb_headroom(skb) < MACSEC_NEEDED_HEADROOM ||\n\t\t skb_tailroom(skb) < MACSEC_NEEDED_TAILROOM)) {\n\t\tstruct sk_buff *nskb = skb_copy_expand(skb,\n\t\t\t\t\t\t MACSEC_NEEDED_HEADROOM,\n\t\t\t\t\t\t MACSEC_NEEDED_TAILROOM,\n\t\t\t\t\t\t GFP_ATOMIC);\n\t\tif (likely(nskb)) {\n\t\t\tconsume_skb(skb);\n\t\t\tskb = nskb;\n\t\t} else {\n\t\t\tmacsec_txsa_put(tx_sa);\n\t\t\tkfree_skb(skb);\n\t\t\treturn ERR_PTR(-ENOMEM);\n\t\t}\n\t} else {\n\t\tskb = skb_unshare(skb, GFP_ATOMIC);\n\t\tif (!skb) {\n\t\t\tmacsec_txsa_put(tx_sa);\n\t\t\treturn ERR_PTR(-ENOMEM);\n\t\t}\n\t}\n\n\tunprotected_len = skb->len;\n\teth = eth_hdr(skb);\n\tsci_present = send_sci(secy);\n\thh = (struct macsec_eth_header *)skb_push(skb, macsec_extra_len(sci_present));\n\tmemmove(hh, eth, 2 * ETH_ALEN);\n\n\tpn = tx_sa_update_pn(tx_sa, secy);\n\tif (pn == 0) {\n\t\tmacsec_txsa_put(tx_sa);\n\t\tkfree_skb(skb);\n\t\treturn ERR_PTR(-ENOLINK);\n\t}\n\tmacsec_fill_sectag(hh, secy, pn, sci_present);\n\tmacsec_set_shortlen(hh, unprotected_len - 2 * ETH_ALEN);\n\n\tskb_put(skb, secy->icv_len);\n\n\tif (skb->len - ETH_HLEN > macsec_priv(dev)->real_dev->mtu) {\n\t\tstruct pcpu_secy_stats *secy_stats = this_cpu_ptr(macsec->stats);\n\n\t\tu64_stats_update_begin(&secy_stats->syncp);\n\t\tsecy_stats->stats.OutPktsTooLong++;\n\t\tu64_stats_update_end(&secy_stats->syncp);\n\n\t\tmacsec_txsa_put(tx_sa);\n\t\tkfree_skb(skb);\n\t\treturn ERR_PTR(-EINVAL);\n\t}\n\n\treq = macsec_alloc_req(tx_sa->key.tfm, &iv, &sg);\n\tif (!req) {\n\t\tmacsec_txsa_put(tx_sa);\n\t\tkfree_skb(skb);\n\t\treturn ERR_PTR(-ENOMEM);\n\t}\n\n\tmacsec_fill_iv(iv, secy->sci, pn);\n\n\tsg_init_table(sg, MAX_SKB_FRAGS + 1);\n\tskb_to_sgvec(skb, sg, 0, skb->len);\n\n\tif (tx_sc->encrypt) {\n\t\tint len = skb->len - macsec_hdr_len(sci_present) -\n\t\t\t secy->icv_len;\n\t\taead_request_set_crypt(req, sg, sg, len, iv);\n\t\taead_request_set_ad(req, macsec_hdr_len(sci_present));\n\t} else {\n\t\taead_request_set_crypt(req, sg, sg, 0, iv);\n\t\taead_request_set_ad(req, skb->len - secy->icv_len);\n\t}\n\n\tmacsec_skb_cb(skb)->req = req;\n\tmacsec_skb_cb(skb)->tx_sa = tx_sa;\n\taead_request_set_callback(req, 0, macsec_encrypt_done, skb);\n\n\tdev_hold(skb->dev);\n\tret = crypto_aead_encrypt(req);\n\tif (ret == -EINPROGRESS) {\n\t\treturn ERR_PTR(ret);\n\t} else if (ret != 0) {\n\t\tdev_put(skb->dev);\n\t\tkfree_skb(skb);\n\t\taead_request_free(req);\n\t\tmacsec_txsa_put(tx_sa);\n\t\treturn ERR_PTR(-EINVAL);\n\t}\n\n\tdev_put(skb->dev);\n\taead_request_free(req);\n\tmacsec_txsa_put(tx_sa);\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_direction_output(struct gpio_chip *chip,\n\t\t\t\t\tunsigned offset, int value)\n{\n\tstruct cp2112_device *dev = gpiochip_get_data(chip);\n\tstruct hid_device *hdev = dev->hdev;\n\tu8 *buf = dev->in_out_buffer;\n\tunsigned long flags;\n\tint ret;\n\n\tspin_lock_irqsave(&dev->lock, flags);\n\n\tret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,\n\t\t\t\t CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,\n\t\t\t\t HID_REQ_GET_REPORT);\n\tif (ret != CP2112_GPIO_CONFIG_LENGTH) {\n\t\thid_err(hdev, \"error requesting GPIO config: %d\\n\", ret);\n\t\tgoto fail;\n\t}\n\n\tbuf[1] |= 1 << offset;\n\tbuf[2] = gpio_push_pull;\n\n\tret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,\n\t\t\t\t CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,\n\t\t\t\t HID_REQ_SET_REPORT);\n\tif (ret < 0) {\n\t\thid_err(hdev, \"error setting GPIO config: %d\\n\", ret);\n\t\tgoto fail;\n\t}\n\n\tspin_unlock_irqrestore(&dev->lock, flags);\n\n\t/*\n\t * Set gpio value when output direction is already set,\n\t * as specified in AN495, Rev. 0.2, cpt. 4.4\n\t */\n\tcp2112_gpio_set(chip, offset, value);\n\n\treturn 0;\n\nfail:\n\tspin_unlock_irqrestore(&dev->lock, flags);\n\treturn ret < 0 ? ret : -EIO;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-404', 'CWE-703'], 'message': 'HID: cp2112: fix sleep-while-atomic\n\nA recent commit fixing DMA-buffers on stack added a shared transfer\nbuffer protected by a spinlock. This is broken as the USB HID request\ncallbacks can sleep. Fix this up by replacing the spinlock with a mutex.\n\nFixes: 1ffb3c40ffb5 (\"HID: cp2112: make transfer buffers DMA capable\")\nCc: stable \t# 4.9\nSigned-off-by: Johan Hovold \nReviewed-by: Benjamin Tissoires \nSigned-off-by: Jiri Kosina '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int cxusb_ctrl_msg(struct dvb_usb_device *d,\n\t\t\t u8 cmd, u8 *wbuf, int wlen, u8 *rbuf, int rlen)\n{\n\tstruct cxusb_state *st = d->priv;\n\tint ret, wo;\n\n\tif (1 + wlen > MAX_XFER_SIZE) {\n\t\twarn(\"i2c wr: len=%d is too big!\\n\", wlen);\n\t\treturn -EOPNOTSUPP;\n\t}\n\n\two = (rbuf == NULL || rlen == 0); /* write-only */\n\n\tmutex_lock(&d->data_mutex);\n\tst->data[0] = cmd;\n\tmemcpy(&st->data[1], wbuf, wlen);\n\tif (wo)\n\t\tret = dvb_usb_generic_write(d, st->data, 1 + wlen);\n\telse\n\t\tret = dvb_usb_generic_rw(d, st->data, 1 + wlen,\n\t\t\t\t\t rbuf, rlen, 0);\n\n\tmutex_unlock(&d->data_mutex);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': '[media] cxusb: Use a dma capable buffer also for reading\n\nCommit 17ce039b4e54 (\"[media] cxusb: don't do DMA on stack\")\nadded a kmalloc'ed bounce buffer for writes, but missed to do the same\nfor reads. As the read only happens after the write is finished, we can\nreuse the same buffer.\n\nAs dvb_usb_generic_rw handles a read length of 0 by itself, avoid calling\nit using the dvb_usb_generic_read wrapper function.\n\nSigned-off-by: Stefan Br\u00fcns \nSigned-off-by: Mauro Carvalho Chehab '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PLIST_API void plist_from_bin(const char *plist_bin, uint32_t length, plist_t * plist)\n{\n bplist_trailer_t *trailer = NULL;\n uint8_t offset_size = 0;\n uint8_t ref_size = 0;\n uint64_t num_objects = 0;\n uint64_t root_object = 0;\n const char *offset_table = NULL;\n const char *start_data = NULL;\n const char *end_data = NULL;\n\n //first check we have enough data\n if (!(length >= BPLIST_MAGIC_SIZE + BPLIST_VERSION_SIZE + sizeof(bplist_trailer_t))) {\n PLIST_BIN_ERR(\"plist data is to small to hold a binary plist\\n\");\n return;\n }\n //check that plist_bin in actually a plist\n if (memcmp(plist_bin, BPLIST_MAGIC, BPLIST_MAGIC_SIZE) != 0) {\n PLIST_BIN_ERR(\"bplist magic mismatch\\n\");\n return;\n }\n //check for known version\n if (memcmp(plist_bin + BPLIST_MAGIC_SIZE, BPLIST_VERSION, BPLIST_VERSION_SIZE) != 0) {\n PLIST_BIN_ERR(\"unsupported binary plist version '%.2s\\n\", plist_bin+BPLIST_MAGIC_SIZE);\n return;\n }\n\n start_data = plist_bin + BPLIST_MAGIC_SIZE + BPLIST_VERSION_SIZE;\n end_data = plist_bin + length - sizeof(bplist_trailer_t);\n\n //now parse trailer\n trailer = (bplist_trailer_t*)end_data;\n\n offset_size = trailer->offset_size;\n ref_size = trailer->ref_size;\n num_objects = be64toh(trailer->num_objects);\n root_object = be64toh(trailer->root_object_index);\n offset_table = (char *)(plist_bin + be64toh(trailer->offset_table_offset));\n\n if (num_objects == 0) {\n PLIST_BIN_ERR(\"number of objects must be larger than 0\\n\");\n return;\n }\n\n if (offset_size == 0) {\n PLIST_BIN_ERR(\"offset size in trailer must be larger than 0\\n\");\n return;\n }\n\n if (ref_size == 0) {\n PLIST_BIN_ERR(\"object reference size in trailer must be larger than 0\\n\");\n return;\n }\n\n if (root_object >= num_objects) {\n PLIST_BIN_ERR(\"root object index (%\" PRIu64 \") must be smaller than number of objects (%\" PRIu64 \")\\n\", root_object, num_objects);\n return;\n }\n\n if (offset_table < start_data || offset_table >= end_data) {\n PLIST_BIN_ERR(\"offset table offset points outside of valid range\\n\");\n return;\n }\n\n if (num_objects * offset_size < num_objects) {\n PLIST_BIN_ERR(\"integer overflow when calculating offset table size (too many objects)\\n\");\n return;\n }\n\n if ((uint64_t)offset_table + num_objects * offset_size > (uint64_t)end_data) {\n PLIST_BIN_ERR(\"offset table points outside of valid range\\n\");\n return;\n }\n\n struct bplist_data bplist;\n bplist.data = plist_bin;\n bplist.size = length;\n bplist.num_objects = num_objects;\n bplist.ref_size = ref_size;\n bplist.offset_size = offset_size;\n bplist.offset_table = offset_table;\n bplist.level = 0;\n bplist.used_indexes = plist_new_array();\n\n if (!bplist.used_indexes) {\n PLIST_BIN_ERR(\"failed to create array to hold used node indexes. Out of memory?\\n\");\n return;\n }\n\n *plist = parse_bin_node_at_index(&bplist, root_object);\n\n plist_free(bplist.used_indexes);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'bplist: Fix integer overflow check (offset table 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 int rxrpc_krb5_decode_principal(struct krb5_principal *princ,\n\t\t\t\t const __be32 **_xdr,\n\t\t\t\t unsigned int *_toklen)\n{\n\tconst __be32 *xdr = *_xdr;\n\tunsigned int toklen = *_toklen, n_parts, loop, tmp;\n\n\t/* there must be at least one name, and at least #names+1 length\n\t * words */\n\tif (toklen <= 12)\n\t\treturn -EINVAL;\n\n\t_enter(\",{%x,%x,%x},%u\",\n\t ntohl(xdr[0]), ntohl(xdr[1]), ntohl(xdr[2]), toklen);\n\n\tn_parts = ntohl(*xdr++);\n\ttoklen -= 4;\n\tif (n_parts <= 0 || n_parts > AFSTOKEN_K5_COMPONENTS_MAX)\n\t\treturn -EINVAL;\n\tprinc->n_name_parts = n_parts;\n\n\tif (toklen <= (n_parts + 1) * 4)\n\t\treturn -EINVAL;\n\n\tprinc->name_parts = kcalloc(n_parts, sizeof(char *), GFP_KERNEL);\n\tif (!princ->name_parts)\n\t\treturn -ENOMEM;\n\n\tfor (loop = 0; loop < n_parts; loop++) {\n\t\tif (toklen < 4)\n\t\t\treturn -EINVAL;\n\t\ttmp = ntohl(*xdr++);\n\t\ttoklen -= 4;\n\t\tif (tmp <= 0 || tmp > AFSTOKEN_STRING_MAX)\n\t\t\treturn -EINVAL;\n\t\tif (tmp > toklen)\n\t\t\treturn -EINVAL;\n\t\tprinc->name_parts[loop] = kmalloc(tmp + 1, GFP_KERNEL);\n\t\tif (!princ->name_parts[loop])\n\t\t\treturn -ENOMEM;\n\t\tmemcpy(princ->name_parts[loop], xdr, tmp);\n\t\tprinc->name_parts[loop][tmp] = 0;\n\t\ttmp = (tmp + 3) & ~3;\n\t\ttoklen -= tmp;\n\t\txdr += tmp >> 2;\n\t}\n\n\tif (toklen < 4)\n\t\treturn -EINVAL;\n\ttmp = ntohl(*xdr++);\n\ttoklen -= 4;\n\tif (tmp <= 0 || tmp > AFSTOKEN_K5_REALM_MAX)\n\t\treturn -EINVAL;\n\tif (tmp > toklen)\n\t\treturn -EINVAL;\n\tprinc->realm = kmalloc(tmp + 1, GFP_KERNEL);\n\tif (!princ->realm)\n\t\treturn -ENOMEM;\n\tmemcpy(princ->realm, xdr, tmp);\n\tprinc->realm[tmp] = 0;\n\ttmp = (tmp + 3) & ~3;\n\ttoklen -= tmp;\n\txdr += tmp >> 2;\n\n\t_debug(\"%s/...@%s\", princ->name_parts[0], princ->realm);\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_smbfs\", 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_smbfs\");\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::SMBFS);\n \n // Compile the list of arguments.\n QStringList args_list;\n \n // Workgroup\n if (!share->workgroupName().isEmpty())\n {\n args_list << \"-W\";\n args_list << KShell::quoteArg(share->workgroupName());\n }\n else\n {\n // Do nothing\n }\n \n // Host IP\n if (!share->hostIP().isEmpty())\n {\n args_list << \"-I\";\n args_list << share->hostIP();\n }\n else\n {\n // Do nothing\n }\n \n // UID\n if (options)\n {\n args_list << \"-u\";\n args_list << QString(\"%1\").arg(options->uid());\n }\n else\n {\n args_list << \"-u\";\n args_list << QString(\"%1\").arg((K_UID)Smb4KMountSettings::userID().toInt());\n }\n \n // GID\n if (options)\n {\n args_list << \"-g\";\n args_list << QString(\"%1\").arg(options->gid());\n }\n else\n {\n args_list << \"-g\";\n args_list << QString(\"%1\").arg((K_GID)Smb4KMountSettings::groupID().toInt());\n }\n \n // Character sets for the client and server\n QString client_charset, server_charset;\n\n switch (Smb4KMountSettings::clientCharset())\n {\n case Smb4KMountSettings::EnumClientCharset::default_charset:\n {\n client_charset = global_options[\"unix charset\"].toLower(); // maybe empty\n break;\n }\n default:\n {\n client_charset = Smb4KMountSettings::self()->clientCharsetItem()->choices().value(Smb4KMountSettings::clientCharset()).label;\n break;\n }\n }\n\n switch (Smb4KMountSettings::serverCodepage())\n {\n case Smb4KMountSettings::EnumServerCodepage::default_codepage:\n {\n server_charset = global_options[\"dos charset\"].toLower(); // maybe empty\n break;\n }\n default:\n {\n server_charset = Smb4KMountSettings::self()->serverCodepageItem()->choices().value(Smb4KMountSettings::serverCodepage()).label;\n break;\n }\n }\n\n if (!client_charset.isEmpty() && !server_charset.isEmpty())\n {\n args_list << \"-E\";\n args_list << QString(\"%1:%2\").arg(client_charset, server_charset);\n }\n else\n {\n // Do nothing\n }\n \n // File mask\n if (!Smb4KMountSettings::fileMask().isEmpty())\n {\n args_list << \"-f\";\n args_list << QString(\"%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 << \"-d\";\n args_list << QString(\"%1\").arg(Smb4KMountSettings::directoryMask());\n }\n else\n {\n // Do nothing\n }\n \n // User name\n if (!share->login().isEmpty())\n {\n args_list << \"-U\";\n args_list << QString(\"%1\").arg(share->login());\n }\n else\n {\n args_list << \"-N\";\n }\n \n // Mount options\n map.insert(\"mh_options\", args_list);\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: struct sock *tcp_create_openreq_child(const struct sock *sk,\n\t\t\t\t struct request_sock *req,\n\t\t\t\t struct sk_buff *skb)\n{\n\tstruct sock *newsk = inet_csk_clone_lock(sk, req, GFP_ATOMIC);\n\n\tif (newsk) {\n\t\tconst struct inet_request_sock *ireq = inet_rsk(req);\n\t\tstruct tcp_request_sock *treq = tcp_rsk(req);\n\t\tstruct inet_connection_sock *newicsk = inet_csk(newsk);\n\t\tstruct tcp_sock *newtp = tcp_sk(newsk);\n\n\t\t/* Now setup tcp_sock */\n\t\tnewtp->pred_flags = 0;\n\n\t\tnewtp->rcv_wup = newtp->copied_seq =\n\t\tnewtp->rcv_nxt = treq->rcv_isn + 1;\n\t\tnewtp->segs_in = 1;\n\n\t\tnewtp->snd_sml = newtp->snd_una =\n\t\tnewtp->snd_nxt = newtp->snd_up = treq->snt_isn + 1;\n\n\t\ttcp_prequeue_init(newtp);\n\t\tINIT_LIST_HEAD(&newtp->tsq_node);\n\n\t\ttcp_init_wl(newtp, treq->rcv_isn);\n\n\t\tnewtp->srtt_us = 0;\n\t\tnewtp->mdev_us = jiffies_to_usecs(TCP_TIMEOUT_INIT);\n\t\tminmax_reset(&newtp->rtt_min, tcp_time_stamp, ~0U);\n\t\tnewicsk->icsk_rto = TCP_TIMEOUT_INIT;\n\t\tnewicsk->icsk_ack.lrcvtime = tcp_time_stamp;\n\n\t\tnewtp->packets_out = 0;\n\t\tnewtp->retrans_out = 0;\n\t\tnewtp->sacked_out = 0;\n\t\tnewtp->fackets_out = 0;\n\t\tnewtp->snd_ssthresh = TCP_INFINITE_SSTHRESH;\n\t\tnewtp->tlp_high_seq = 0;\n\t\tnewtp->lsndtime = treq->snt_synack.stamp_jiffies;\n\t\tnewsk->sk_txhash = treq->txhash;\n\t\tnewtp->last_oow_ack_time = 0;\n\t\tnewtp->total_retrans = req->num_retrans;\n\n\t\t/* So many TCP implementations out there (incorrectly) count the\n\t\t * initial SYN frame in their delayed-ACK and congestion control\n\t\t * algorithms that we must have the following bandaid to talk\n\t\t * efficiently to them. -DaveM\n\t\t */\n\t\tnewtp->snd_cwnd = TCP_INIT_CWND;\n\t\tnewtp->snd_cwnd_cnt = 0;\n\n\t\t/* There's a bubble in the pipe until at least the first ACK. */\n\t\tnewtp->app_limited = ~0U;\n\n\t\ttcp_init_xmit_timers(newsk);\n\t\tnewtp->write_seq = newtp->pushed_seq = treq->snt_isn + 1;\n\n\t\tnewtp->rx_opt.saw_tstamp = 0;\n\n\t\tnewtp->rx_opt.dsack = 0;\n\t\tnewtp->rx_opt.num_sacks = 0;\n\n\t\tnewtp->urg_data = 0;\n\n\t\tif (sock_flag(newsk, SOCK_KEEPOPEN))\n\t\t\tinet_csk_reset_keepalive_timer(newsk,\n\t\t\t\t\t\t keepalive_time_when(newtp));\n\n\t\tnewtp->rx_opt.tstamp_ok = ireq->tstamp_ok;\n\t\tif ((newtp->rx_opt.sack_ok = ireq->sack_ok) != 0) {\n\t\t\tif (sysctl_tcp_fack)\n\t\t\t\ttcp_enable_fack(newtp);\n\t\t}\n\t\tnewtp->window_clamp = req->rsk_window_clamp;\n\t\tnewtp->rcv_ssthresh = req->rsk_rcv_wnd;\n\t\tnewtp->rcv_wnd = req->rsk_rcv_wnd;\n\t\tnewtp->rx_opt.wscale_ok = ireq->wscale_ok;\n\t\tif (newtp->rx_opt.wscale_ok) {\n\t\t\tnewtp->rx_opt.snd_wscale = ireq->snd_wscale;\n\t\t\tnewtp->rx_opt.rcv_wscale = ireq->rcv_wscale;\n\t\t} else {\n\t\t\tnewtp->rx_opt.snd_wscale = newtp->rx_opt.rcv_wscale = 0;\n\t\t\tnewtp->window_clamp = min(newtp->window_clamp, 65535U);\n\t\t}\n\t\tnewtp->snd_wnd = (ntohs(tcp_hdr(skb)->window) <<\n\t\t\t\t newtp->rx_opt.snd_wscale);\n\t\tnewtp->max_window = newtp->snd_wnd;\n\n\t\tif (newtp->rx_opt.tstamp_ok) {\n\t\t\tnewtp->rx_opt.ts_recent = req->ts_recent;\n\t\t\tnewtp->rx_opt.ts_recent_stamp = get_seconds();\n\t\t\tnewtp->tcp_header_len = sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;\n\t\t} else {\n\t\t\tnewtp->rx_opt.ts_recent_stamp = 0;\n\t\t\tnewtp->tcp_header_len = sizeof(struct tcphdr);\n\t\t}\n\t\tnewtp->tsoffset = treq->ts_off;\n#ifdef CONFIG_TCP_MD5SIG\n\t\tnewtp->md5sig_info = NULL;\t/*XXX*/\n\t\tif (newtp->af_specific->md5_lookup(sk, newsk))\n\t\t\tnewtp->tcp_header_len += TCPOLEN_MD5SIG_ALIGNED;\n#endif\n\t\tif (skb->len >= TCP_MSS_DEFAULT + newtp->tcp_header_len)\n\t\t\tnewicsk->icsk_ack.last_seg_size = skb->len - newtp->tcp_header_len;\n\t\tnewtp->rx_opt.mss_clamp = req->mss;\n\t\ttcp_ecn_openreq_child(newtp, req);\n\t\tnewtp->fastopen_rsk = NULL;\n\t\tnewtp->syn_data_acked = 0;\n\t\tnewtp->rack.mstamp.v64 = 0;\n\t\tnewtp->rack.advanced = 0;\n\n\t\t__TCP_INC_STATS(sock_net(sk), TCP_MIB_PASSIVEOPENS);\n\t}\n\treturn newsk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'tcp: do not inherit fastopen_req from parent\n\nUnder fuzzer stress, it is possible that a child gets a non NULL\nfastopen_req pointer from its parent at accept() time, when/if parent\nmorphs from listener to active session.\n\nWe need to make sure this can not happen, by clearing the field after\nsocket cloning.\n\nBUG: Double free or freeing an invalid pointer\nUnexpected shadow byte: 0xFB\nCPU: 3 PID: 20933 Comm: syz-executor3 Not tainted 4.11.0+ #306\nHardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs\n01/01/2011\nCall Trace:\n \n __dump_stack lib/dump_stack.c:16 [inline]\n dump_stack+0x292/0x395 lib/dump_stack.c:52\n kasan_object_err+0x1c/0x70 mm/kasan/report.c:164\n kasan_report_double_free+0x5c/0x70 mm/kasan/report.c:185\n kasan_slab_free+0x9d/0xc0 mm/kasan/kasan.c:580\n slab_free_hook mm/slub.c:1357 [inline]\n slab_free_freelist_hook mm/slub.c:1379 [inline]\n slab_free mm/slub.c:2961 [inline]\n kfree+0xe8/0x2b0 mm/slub.c:3882\n tcp_free_fastopen_req net/ipv4/tcp.c:1077 [inline]\n tcp_disconnect+0xc15/0x13e0 net/ipv4/tcp.c:2328\n inet_child_forget+0xb8/0x600 net/ipv4/inet_connection_sock.c:898\n inet_csk_reqsk_queue_add+0x1e7/0x250\nnet/ipv4/inet_connection_sock.c:928\n tcp_get_cookie_sock+0x21a/0x510 net/ipv4/syncookies.c:217\n cookie_v4_check+0x1a19/0x28b0 net/ipv4/syncookies.c:384\n tcp_v4_cookie_check net/ipv4/tcp_ipv4.c:1384 [inline]\n tcp_v4_do_rcv+0x731/0x940 net/ipv4/tcp_ipv4.c:1421\n tcp_v4_rcv+0x2dc0/0x31c0 net/ipv4/tcp_ipv4.c:1715\n ip_local_deliver_finish+0x4cc/0xc20 net/ipv4/ip_input.c:216\n NF_HOOK include/linux/netfilter.h:257 [inline]\n ip_local_deliver+0x1ce/0x700 net/ipv4/ip_input.c:257\n dst_input include/net/dst.h:492 [inline]\n ip_rcv_finish+0xb1d/0x20b0 net/ipv4/ip_input.c:396\n NF_HOOK include/linux/netfilter.h:257 [inline]\n ip_rcv+0xd8c/0x19c0 net/ipv4/ip_input.c:487\n __netif_receive_skb_core+0x1ad1/0x3400 net/core/dev.c:4210\n __netif_receive_skb+0x2a/0x1a0 net/core/dev.c:4248\n process_backlog+0xe5/0x6c0 net/core/dev.c:4868\n napi_poll net/core/dev.c:5270 [inline]\n net_rx_action+0xe70/0x18e0 net/core/dev.c:5335\n __do_softirq+0x2fb/0xb99 kernel/softirq.c:284\n do_softirq_own_stack+0x1c/0x30 arch/x86/entry/entry_64.S:899\n \n do_softirq.part.17+0x1e8/0x230 kernel/softirq.c:328\n do_softirq kernel/softirq.c:176 [inline]\n __local_bh_enable_ip+0x1cf/0x1e0 kernel/softirq.c:181\n local_bh_enable include/linux/bottom_half.h:31 [inline]\n rcu_read_unlock_bh include/linux/rcupdate.h:931 [inline]\n ip_finish_output2+0x9ab/0x15e0 net/ipv4/ip_output.c:230\n ip_finish_output+0xa35/0xdf0 net/ipv4/ip_output.c:316\n NF_HOOK_COND include/linux/netfilter.h:246 [inline]\n ip_output+0x1f6/0x7b0 net/ipv4/ip_output.c:404\n dst_output include/net/dst.h:486 [inline]\n ip_local_out+0x95/0x160 net/ipv4/ip_output.c:124\n ip_queue_xmit+0x9a8/0x1a10 net/ipv4/ip_output.c:503\n tcp_transmit_skb+0x1ade/0x3470 net/ipv4/tcp_output.c:1057\n tcp_write_xmit+0x79e/0x55b0 net/ipv4/tcp_output.c:2265\n __tcp_push_pending_frames+0xfa/0x3a0 net/ipv4/tcp_output.c:2450\n tcp_push+0x4ee/0x780 net/ipv4/tcp.c:683\n tcp_sendmsg+0x128d/0x39b0 net/ipv4/tcp.c:1342\n inet_sendmsg+0x164/0x5b0 net/ipv4/af_inet.c:762\n sock_sendmsg_nosec net/socket.c:633 [inline]\n sock_sendmsg+0xca/0x110 net/socket.c:643\n SYSC_sendto+0x660/0x810 net/socket.c:1696\n SyS_sendto+0x40/0x50 net/socket.c:1664\n entry_SYSCALL_64_fastpath+0x1f/0xbe\nRIP: 0033:0x446059\nRSP: 002b:00007faa6761fb58 EFLAGS: 00000282 ORIG_RAX: 000000000000002c\nRAX: ffffffffffffffda RBX: 0000000000000017 RCX: 0000000000446059\nRDX: 0000000000000001 RSI: 0000000020ba3fcd RDI: 0000000000000017\nRBP: 00000000006e40a0 R08: 0000000020ba4ff0 R09: 0000000000000010\nR10: 0000000020000000 R11: 0000000000000282 R12: 0000000000708150\nR13: 0000000000000000 R14: 00007faa676209c0 R15: 00007faa67620700\nObject at ffff88003b5bbcb8, in cache kmalloc-64 size: 64\nAllocated:\nPID = 20909\n save_stack_trace+0x16/0x20 arch/x86/kernel/stacktrace.c:59\n save_stack+0x43/0xd0 mm/kasan/kasan.c:513\n set_track mm/kasan/kasan.c:525 [inline]\n kasan_kmalloc+0xad/0xe0 mm/kasan/kasan.c:616\n kmem_cache_alloc_trace+0x82/0x270 mm/slub.c:2745\n kmalloc include/linux/slab.h:490 [inline]\n kzalloc include/linux/slab.h:663 [inline]\n tcp_sendmsg_fastopen net/ipv4/tcp.c:1094 [inline]\n tcp_sendmsg+0x221a/0x39b0 net/ipv4/tcp.c:1139\n inet_sendmsg+0x164/0x5b0 net/ipv4/af_inet.c:762\n sock_sendmsg_nosec net/socket.c:633 [inline]\n sock_sendmsg+0xca/0x110 net/socket.c:643\n SYSC_sendto+0x660/0x810 net/socket.c:1696\n SyS_sendto+0x40/0x50 net/socket.c:1664\n entry_SYSCALL_64_fastpath+0x1f/0xbe\nFreed:\nPID = 20909\n save_stack_trace+0x16/0x20 arch/x86/kernel/stacktrace.c:59\n save_stack+0x43/0xd0 mm/kasan/kasan.c:513\n set_track mm/kasan/kasan.c:525 [inline]\n kasan_slab_free+0x73/0xc0 mm/kasan/kasan.c:589\n slab_free_hook mm/slub.c:1357 [inline]\n slab_free_freelist_hook mm/slub.c:1379 [inline]\n slab_free mm/slub.c:2961 [inline]\n kfree+0xe8/0x2b0 mm/slub.c:3882\n tcp_free_fastopen_req net/ipv4/tcp.c:1077 [inline]\n tcp_disconnect+0xc15/0x13e0 net/ipv4/tcp.c:2328\n __inet_stream_connect+0x20c/0xf90 net/ipv4/af_inet.c:593\n tcp_sendmsg_fastopen net/ipv4/tcp.c:1111 [inline]\n tcp_sendmsg+0x23a8/0x39b0 net/ipv4/tcp.c:1139\n inet_sendmsg+0x164/0x5b0 net/ipv4/af_inet.c:762\n sock_sendmsg_nosec net/socket.c:633 [inline]\n sock_sendmsg+0xca/0x110 net/socket.c:643\n SYSC_sendto+0x660/0x810 net/socket.c:1696\n SyS_sendto+0x40/0x50 net/socket.c:1664\n entry_SYSCALL_64_fastpath+0x1f/0xbe\n\nFixes: e994b2f0fb92 (\"tcp: do not lock listener to process SYN packets\")\nFixes: 7db92362d2fe (\"tcp: fix potential double free issue for fastopen_req\")\nSigned-off-by: Eric Dumazet \nReported-by: Andrey Konovalov \nAcked-by: Wei Wang \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void edge_bulk_in_callback(struct urb *urb)\n{\n\tstruct edgeport_port *edge_port = urb->context;\n\tstruct device *dev = &edge_port->port->dev;\n\tunsigned char *data = urb->transfer_buffer;\n\tint retval = 0;\n\tint port_number;\n\tint status = urb->status;\n\n\tswitch (status) {\n\tcase 0:\n\t\t/* success */\n\t\tbreak;\n\tcase -ECONNRESET:\n\tcase -ENOENT:\n\tcase -ESHUTDOWN:\n\t\t/* this urb is terminated, clean up */\n\t\tdev_dbg(&urb->dev->dev, \"%s - urb shutting down with status: %d\\n\", __func__, status);\n\t\treturn;\n\tdefault:\n\t\tdev_err(&urb->dev->dev, \"%s - nonzero read bulk status received: %d\\n\", __func__, status);\n\t}\n\n\tif (status == -EPIPE)\n\t\tgoto exit;\n\n\tif (status) {\n\t\tdev_err(&urb->dev->dev, \"%s - stopping read!\\n\", __func__);\n\t\treturn;\n\t}\n\n\tport_number = edge_port->port->port_number;\n\n\tif (edge_port->lsr_event) {\n\t\tedge_port->lsr_event = 0;\n\t\tdev_dbg(dev, \"%s ===== Port %u LSR Status = %02x, Data = %02x ======\\n\",\n\t\t\t__func__, port_number, edge_port->lsr_mask, *data);\n\t\thandle_new_lsr(edge_port, 1, edge_port->lsr_mask, *data);\n\t\t/* Adjust buffer length/pointer */\n\t\t--urb->actual_length;\n\t\t++data;\n\t}\n\n\tif (urb->actual_length) {\n\t\tusb_serial_debug_data(dev, __func__, urb->actual_length, data);\n\t\tif (edge_port->close_pending)\n\t\t\tdev_dbg(dev, \"%s - close pending, dropping data on the floor\\n\",\n\t\t\t\t\t\t\t\t__func__);\n\t\telse\n\t\t\tedge_tty_recv(edge_port->port, data,\n\t\t\t\t\turb->actual_length);\n\t\tedge_port->port->icount.rx += urb->actual_length;\n\t}\n\nexit:\n\t/* continue read unless stopped */\n\tspin_lock(&edge_port->ep_lock);\n\tif (edge_port->ep_read_urb_state == EDGE_READ_URB_RUNNING)\n\t\tretval = usb_submit_urb(urb, GFP_ATOMIC);\n\telse if (edge_port->ep_read_urb_state == EDGE_READ_URB_STOPPING)\n\t\tedge_port->ep_read_urb_state = EDGE_READ_URB_STOPPED;\n\n\tspin_unlock(&edge_port->ep_lock);\n\tif (retval)\n\t\tdev_err(dev, \"%s - usb_submit_urb failed with result %d\\n\", __func__, retval);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-191'], 'message': 'USB: serial: io_ti: fix information leak in completion handler\n\nAdd missing sanity check to the bulk-in completion handler to avoid an\ninteger underflow that can be triggered by a malicious device.\n\nThis avoids leaking 128 kB of memory content from after the URB transfer\nbuffer to user space.\n\nFixes: 8c209e6782ca (\"USB: make actual_length in struct urb field u32\")\nFixes: 1da177e4c3f4 (\"Linux-2.6.12-rc2\")\nCc: stable \t# 2.6.30\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 struct sock *sctp_v6_create_accept_sk(struct sock *sk,\n\t\t\t\t\t struct sctp_association *asoc,\n\t\t\t\t\t bool kern)\n{\n\tstruct sock *newsk;\n\tstruct ipv6_pinfo *newnp, *np = inet6_sk(sk);\n\tstruct sctp6_sock *newsctp6sk;\n\tstruct ipv6_txoptions *opt;\n\n\tnewsk = sk_alloc(sock_net(sk), PF_INET6, GFP_KERNEL, sk->sk_prot, kern);\n\tif (!newsk)\n\t\tgoto out;\n\n\tsock_init_data(NULL, newsk);\n\n\tsctp_copy_sock(newsk, sk, asoc);\n\tsock_reset_flag(sk, SOCK_ZAPPED);\n\n\tnewsctp6sk = (struct sctp6_sock *)newsk;\n\tinet_sk(newsk)->pinet6 = &newsctp6sk->inet6;\n\n\tsctp_sk(newsk)->v4mapped = sctp_sk(sk)->v4mapped;\n\n\tnewnp = inet6_sk(newsk);\n\n\tmemcpy(newnp, np, sizeof(struct ipv6_pinfo));\n\n\trcu_read_lock();\n\topt = rcu_dereference(np->opt);\n\tif (opt)\n\t\topt = ipv6_dup_options(newsk, opt);\n\tRCU_INIT_POINTER(newnp->opt, opt);\n\trcu_read_unlock();\n\n\t/* Initialize sk's sport, dport, rcv_saddr and daddr for getsockname()\n\t * and getpeername().\n\t */\n\tsctp_v6_to_sk_daddr(&asoc->peer.primary_addr, newsk);\n\n\tnewsk->sk_v6_rcv_saddr = sk->sk_v6_rcv_saddr;\n\n\tsk_refcnt_debug_inc(newsk);\n\n\tif (newsk->sk_prot->init(newsk)) {\n\t\tsk_common_release(newsk);\n\t\tnewsk = NULL;\n\t}\n\nout:\n\treturn newsk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-241'], 'message': 'sctp: do not inherit ipv6_{mc|ac|fl}_list from parent\n\nSCTP needs fixes similar to 83eaddab4378 (\"ipv6/dccp: do not inherit\nipv6_mc_list from parent\"), otherwise bad things can happen.\n\nSigned-off-by: Eric Dumazet \nReported-by: Andrey Konovalov \nTested-by: Andrey Konovalov \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: jbig2_decode_symbol_dict(Jbig2Ctx *ctx,\n Jbig2Segment *segment,\n const Jbig2SymbolDictParams *params, const byte *data, size_t size, Jbig2ArithCx *GB_stats, Jbig2ArithCx *GR_stats)\n{\n Jbig2SymbolDict *SDNEWSYMS = NULL;\n Jbig2SymbolDict *SDEXSYMS = NULL;\n uint32_t HCHEIGHT;\n uint32_t NSYMSDECODED;\n uint32_t SYMWIDTH, TOTWIDTH;\n uint32_t HCFIRSTSYM;\n uint32_t *SDNEWSYMWIDTHS = NULL;\n int SBSYMCODELEN = 0;\n Jbig2WordStream *ws = NULL;\n Jbig2HuffmanState *hs = NULL;\n Jbig2HuffmanTable *SDHUFFRDX = NULL;\n Jbig2HuffmanTable *SBHUFFRSIZE = NULL;\n Jbig2ArithState *as = NULL;\n Jbig2ArithIntCtx *IADH = NULL;\n Jbig2ArithIntCtx *IADW = NULL;\n Jbig2ArithIntCtx *IAEX = NULL;\n Jbig2ArithIntCtx *IAAI = NULL;\n Jbig2ArithIaidCtx *IAID = NULL;\n Jbig2ArithIntCtx *IARDX = NULL;\n Jbig2ArithIntCtx *IARDY = NULL;\n int code = 0;\n Jbig2SymbolDict **refagg_dicts = NULL;\n int n_refagg_dicts = 1;\n\n Jbig2TextRegionParams *tparams = NULL;\n\n /* 6.5.5 (3) */\n HCHEIGHT = 0;\n NSYMSDECODED = 0;\n\n ws = jbig2_word_stream_buf_new(ctx, data, size);\n if (ws == NULL) {\n jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, \"failed to allocate ws in jbig2_decode_symbol_dict\");\n return NULL;\n }\n\n as = jbig2_arith_new(ctx, ws);\n if (as == NULL) {\n jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, \"failed to allocate as in jbig2_decode_symbol_dict\");\n jbig2_word_stream_buf_free(ctx, ws);\n return NULL;\n }\n\n if (!params->SDHUFF) {\n IADH = jbig2_arith_int_ctx_new(ctx);\n IADW = jbig2_arith_int_ctx_new(ctx);\n IAEX = jbig2_arith_int_ctx_new(ctx);\n IAAI = jbig2_arith_int_ctx_new(ctx);\n if ((IADH == NULL) || (IADW == NULL) || (IAEX == NULL) || (IAAI == NULL)) {\n jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, \"failed to allocate storage for symbol bitmap\");\n goto cleanup1;\n }\n if (params->SDREFAGG) {\n int64_t tmp = params->SDNUMINSYMS + params->SDNUMNEWSYMS;\n\n for (SBSYMCODELEN = 0; ((int64_t) 1 << SBSYMCODELEN) < tmp; SBSYMCODELEN++);\n IAID = jbig2_arith_iaid_ctx_new(ctx, SBSYMCODELEN);\n IARDX = jbig2_arith_int_ctx_new(ctx);\n IARDY = jbig2_arith_int_ctx_new(ctx);\n if ((IAID == NULL) || (IARDX == NULL) || (IARDY == NULL)) {\n jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, \"failed to allocate storage for symbol bitmap\");\n goto cleanup2;\n }\n }\n } else {\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \"huffman coded symbol dictionary\");\n hs = jbig2_huffman_new(ctx, ws);\n SDHUFFRDX = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_O);\n SBHUFFRSIZE = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_A);\n if ((hs == NULL) || (SDHUFFRDX == NULL) || (SBHUFFRSIZE == NULL)) {\n jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, \"failed to allocate storage for symbol bitmap\");\n goto cleanup2;\n }\n if (!params->SDREFAGG) {\n SDNEWSYMWIDTHS = jbig2_new(ctx, uint32_t, params->SDNUMNEWSYMS);\n if (SDNEWSYMWIDTHS == NULL) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"could not allocate storage for (%u) symbol widths\", params->SDNUMNEWSYMS);\n goto cleanup2;\n }\n }\n }\n\n SDNEWSYMS = jbig2_sd_new(ctx, params->SDNUMNEWSYMS);\n if (SDNEWSYMS == NULL) {\n jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, \"could not allocate storage for (%u) new symbols\", params->SDNUMNEWSYMS);\n goto cleanup2;\n }\n\n /* 6.5.5 (4a) */\n while (NSYMSDECODED < params->SDNUMNEWSYMS) {\n int32_t HCDH, DW;\n\n /* 6.5.6 */\n if (params->SDHUFF) {\n HCDH = jbig2_huffman_get(hs, params->SDHUFFDH, &code);\n } else {\n code = jbig2_arith_int_decode(IADH, as, &HCDH);\n }\n\n if (code != 0) {\n jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, \"error or OOB decoding height class delta (%d)\\n\", code);\n }\n\n if (!params->SDHUFF && jbig2_arith_has_reached_marker(as)) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"prevent DOS while decoding height classes\");\n goto cleanup2;\n }\n\n /* 6.5.5 (4b) */\n HCHEIGHT = HCHEIGHT + HCDH;\n SYMWIDTH = 0;\n TOTWIDTH = 0;\n HCFIRSTSYM = NSYMSDECODED;\n\n if ((int32_t) HCHEIGHT < 0) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"Invalid HCHEIGHT value\");\n goto cleanup2;\n }\n#ifdef JBIG2_DEBUG\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \"HCHEIGHT = %d\", HCHEIGHT);\n#endif\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \"decoding height class %d with %d syms decoded\", HCHEIGHT, NSYMSDECODED);\n\n for (;;) {\n /* 6.5.7 */\n if (params->SDHUFF) {\n DW = jbig2_huffman_get(hs, params->SDHUFFDW, &code);\n } else {\n code = jbig2_arith_int_decode(IADW, as, &DW);\n }\n if (code < 0)\n goto cleanup4;\n\n /* 6.5.5 (4c.i) */\n if (code == 1) {\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \" OOB signals end of height class %d\", HCHEIGHT);\n break;\n }\n\n /* check for broken symbol table */\n if (NSYMSDECODED >= params->SDNUMNEWSYMS) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"No OOB signalling end of height class %d\", HCHEIGHT);\n goto cleanup4;\n }\n\n SYMWIDTH = SYMWIDTH + DW;\n TOTWIDTH = TOTWIDTH + SYMWIDTH;\n if ((int32_t) SYMWIDTH < 0) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"Invalid SYMWIDTH value (%d) at symbol %d\", SYMWIDTH, NSYMSDECODED + 1);\n goto cleanup4;\n }\n#ifdef JBIG2_DEBUG\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \"SYMWIDTH = %d TOTWIDTH = %d\", SYMWIDTH, TOTWIDTH);\n#endif\n /* 6.5.5 (4c.ii) */\n if (!params->SDHUFF || params->SDREFAGG) {\n#ifdef JBIG2_DEBUG\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \"SDHUFF = %d; SDREFAGG = %d\", params->SDHUFF, params->SDREFAGG);\n#endif\n /* 6.5.8 */\n if (!params->SDREFAGG) {\n Jbig2GenericRegionParams region_params;\n int sdat_bytes;\n Jbig2Image *image;\n\n /* Table 16 */\n region_params.MMR = 0;\n region_params.GBTEMPLATE = params->SDTEMPLATE;\n region_params.TPGDON = 0;\n region_params.USESKIP = 0;\n sdat_bytes = params->SDTEMPLATE == 0 ? 8 : 2;\n memcpy(region_params.gbat, params->sdat, sdat_bytes);\n\n image = jbig2_image_new(ctx, SYMWIDTH, HCHEIGHT);\n if (image == NULL) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"failed to allocate image in jbig2_decode_symbol_dict\");\n goto cleanup4;\n }\n\n code = jbig2_decode_generic_region(ctx, segment, ®ion_params, as, image, GB_stats);\n if (code < 0) {\n jbig2_image_release(ctx, image);\n goto cleanup4;\n }\n\n SDNEWSYMS->glyphs[NSYMSDECODED] = image;\n } else {\n /* 6.5.8.2 refinement/aggregate symbol */\n uint32_t REFAGGNINST;\n\n if (params->SDHUFF) {\n REFAGGNINST = jbig2_huffman_get(hs, params->SDHUFFAGGINST, &code);\n } else {\n code = jbig2_arith_int_decode(IAAI, as, (int32_t *) & REFAGGNINST);\n }\n if (code || (int32_t) REFAGGNINST <= 0) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"invalid number of symbols or OOB in aggregate glyph\");\n goto cleanup4;\n }\n\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \"aggregate symbol coding (%d instances)\", REFAGGNINST);\n\n if (REFAGGNINST > 1) {\n Jbig2Image *image;\n uint32_t i;\n\n if (tparams == NULL) {\n /* First time through, we need to initialise the */\n /* various tables for Huffman or adaptive encoding */\n /* as well as the text region parameters structure */\n refagg_dicts = jbig2_new(ctx, Jbig2SymbolDict *, n_refagg_dicts);\n if (refagg_dicts == NULL) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"Out of memory allocating dictionary array\");\n goto cleanup4;\n }\n refagg_dicts[0] = jbig2_sd_new(ctx, params->SDNUMINSYMS + params->SDNUMNEWSYMS);\n if (refagg_dicts[0] == NULL) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"Out of memory allocating symbol dictionary\");\n goto cleanup4;\n }\n for (i = 0; i < params->SDNUMINSYMS; i++) {\n refagg_dicts[0]->glyphs[i] = jbig2_image_clone(ctx, params->SDINSYMS->glyphs[i]);\n }\n\n tparams = jbig2_new(ctx, Jbig2TextRegionParams, 1);\n if (tparams == NULL) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"Out of memory creating text region params\");\n goto cleanup4;\n }\n if (!params->SDHUFF) {\n /* Values from Table 17, section 6.5.8.2 (2) */\n tparams->IADT = jbig2_arith_int_ctx_new(ctx);\n tparams->IAFS = jbig2_arith_int_ctx_new(ctx);\n tparams->IADS = jbig2_arith_int_ctx_new(ctx);\n tparams->IAIT = jbig2_arith_int_ctx_new(ctx);\n /* Table 31 */\n for (SBSYMCODELEN = 0; (1 << SBSYMCODELEN) < (int)(params->SDNUMINSYMS + params->SDNUMNEWSYMS); SBSYMCODELEN++);\n tparams->IAID = jbig2_arith_iaid_ctx_new(ctx, SBSYMCODELEN);\n tparams->IARI = jbig2_arith_int_ctx_new(ctx);\n tparams->IARDW = jbig2_arith_int_ctx_new(ctx);\n tparams->IARDH = jbig2_arith_int_ctx_new(ctx);\n tparams->IARDX = jbig2_arith_int_ctx_new(ctx);\n tparams->IARDY = jbig2_arith_int_ctx_new(ctx);\n } else {\n tparams->SBHUFFFS = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_F); /* Table B.6 */\n tparams->SBHUFFDS = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_H); /* Table B.8 */\n tparams->SBHUFFDT = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_K); /* Table B.11 */\n tparams->SBHUFFRDW = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_O); /* Table B.15 */\n tparams->SBHUFFRDH = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_O); /* Table B.15 */\n tparams->SBHUFFRDX = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_O); /* Table B.15 */\n tparams->SBHUFFRDY = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_O); /* Table B.15 */\n }\n tparams->SBHUFF = params->SDHUFF;\n tparams->SBREFINE = 1;\n tparams->SBSTRIPS = 1;\n tparams->SBDEFPIXEL = 0;\n tparams->SBCOMBOP = JBIG2_COMPOSE_OR;\n tparams->TRANSPOSED = 0;\n tparams->REFCORNER = JBIG2_CORNER_TOPLEFT;\n tparams->SBDSOFFSET = 0;\n tparams->SBRTEMPLATE = params->SDRTEMPLATE;\n }\n tparams->SBNUMINSTANCES = REFAGGNINST;\n\n image = jbig2_image_new(ctx, SYMWIDTH, HCHEIGHT);\n if (image == NULL) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"Out of memory creating symbol image\");\n goto cleanup4;\n }\n\n /* multiple symbols are handled as a text region */\n jbig2_decode_text_region(ctx, segment, tparams, (const Jbig2SymbolDict * const *)refagg_dicts,\n n_refagg_dicts, image, data, size, GR_stats, as, ws);\n\n SDNEWSYMS->glyphs[NSYMSDECODED] = image;\n refagg_dicts[0]->glyphs[params->SDNUMINSYMS + NSYMSDECODED] = jbig2_image_clone(ctx, SDNEWSYMS->glyphs[NSYMSDECODED]);\n } else {\n /* 6.5.8.2.2 */\n /* bool SBHUFF = params->SDHUFF; */\n Jbig2RefinementRegionParams rparams;\n Jbig2Image *image;\n uint32_t ID;\n int32_t RDX, RDY;\n int BMSIZE = 0;\n uint32_t ninsyms = params->SDNUMINSYMS;\n int code1 = 0;\n int code2 = 0;\n int code3 = 0;\n int code4 = 0;\n\n /* 6.5.8.2.2 (2, 3, 4, 5) */\n if (params->SDHUFF) {\n ID = jbig2_huffman_get_bits(hs, SBSYMCODELEN, &code4);\n RDX = jbig2_huffman_get(hs, SDHUFFRDX, &code1);\n RDY = jbig2_huffman_get(hs, SDHUFFRDX, &code2);\n BMSIZE = jbig2_huffman_get(hs, SBHUFFRSIZE, &code3);\n jbig2_huffman_skip(hs);\n } else {\n code1 = jbig2_arith_iaid_decode(IAID, as, (int32_t *) & ID);\n code2 = jbig2_arith_int_decode(IARDX, as, &RDX);\n code3 = jbig2_arith_int_decode(IARDY, as, &RDY);\n }\n\n if ((code1 < 0) || (code2 < 0) || (code3 < 0) || (code4 < 0)) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"failed to decode data\");\n goto cleanup4;\n }\n\n if (ID >= ninsyms + NSYMSDECODED) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"refinement references unknown symbol %d\", ID);\n goto cleanup4;\n }\n\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number,\n \"symbol is a refinement of id %d with the \" \"refinement applied at (%d,%d)\", ID, RDX, RDY);\n\n image = jbig2_image_new(ctx, SYMWIDTH, HCHEIGHT);\n if (image == NULL) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"Out of memory creating symbol image\");\n goto cleanup4;\n }\n\n /* Table 18 */\n rparams.GRTEMPLATE = params->SDRTEMPLATE;\n rparams.reference = (ID < ninsyms) ? params->SDINSYMS->glyphs[ID] : SDNEWSYMS->glyphs[ID - ninsyms];\n /* SumatraPDF: fail on missing glyphs */\n if (rparams.reference == NULL) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"missing glyph %d/%d!\", ID, ninsyms);\n jbig2_image_release(ctx, image);\n goto cleanup4;\n }\n rparams.DX = RDX;\n rparams.DY = RDY;\n rparams.TPGRON = 0;\n memcpy(rparams.grat, params->sdrat, 4);\n code = jbig2_decode_refinement_region(ctx, segment, &rparams, as, image, GR_stats);\n if (code < 0)\n goto cleanup4;\n\n SDNEWSYMS->glyphs[NSYMSDECODED] = image;\n\n /* 6.5.8.2.2 (7) */\n if (params->SDHUFF) {\n if (BMSIZE == 0)\n BMSIZE = image->height * image->stride;\n jbig2_huffman_advance(hs, BMSIZE);\n }\n }\n }\n\n#ifdef OUTPUT_PBM\n {\n char name[64];\n FILE *out;\n\n snprintf(name, 64, \"sd.%04d.%04d.pbm\", segment->number, NSYMSDECODED);\n out = fopen(name, \"wb\");\n jbig2_image_write_pbm(SDNEWSYMS->glyphs[NSYMSDECODED], out);\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \"writing out glyph as '%s' ...\", name);\n fclose(out);\n }\n#endif\n\n }\n\n /* 6.5.5 (4c.iii) */\n if (params->SDHUFF && !params->SDREFAGG) {\n SDNEWSYMWIDTHS[NSYMSDECODED] = SYMWIDTH;\n }\n\n /* 6.5.5 (4c.iv) */\n NSYMSDECODED = NSYMSDECODED + 1;\n\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \"decoded symbol %u of %u (%ux%u)\", NSYMSDECODED, params->SDNUMNEWSYMS, SYMWIDTH, HCHEIGHT);\n\n } /* end height class decode loop */\n\n /* 6.5.5 (4d) */\n if (params->SDHUFF && !params->SDREFAGG) {\n /* 6.5.9 */\n Jbig2Image *image;\n uint32_t BMSIZE = jbig2_huffman_get(hs, params->SDHUFFBMSIZE, &code);\n uint32_t j;\n int x;\n\n if (code) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"error decoding size of collective bitmap!\");\n goto cleanup4;\n }\n\n /* skip any bits before the next byte boundary */\n jbig2_huffman_skip(hs);\n\n image = jbig2_image_new(ctx, TOTWIDTH, HCHEIGHT);\n if (image == NULL) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"could not allocate collective bitmap image!\");\n goto cleanup4;\n }\n\n if (BMSIZE == 0) {\n /* if BMSIZE == 0 bitmap is uncompressed */\n const byte *src = data + jbig2_huffman_offset(hs);\n const int stride = (image->width >> 3) + ((image->width & 7) ? 1 : 0);\n byte *dst = image->data;\n\n /* SumatraPDF: prevent read access violation */\n if ((size - jbig2_huffman_offset(hs) < image->height * stride) || (size < jbig2_huffman_offset(hs))) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"not enough data for decoding (%d/%d)\", image->height * stride,\n size - jbig2_huffman_offset(hs));\n jbig2_image_release(ctx, image);\n goto cleanup4;\n }\n\n BMSIZE = image->height * stride;\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number,\n \"reading %dx%d uncompressed bitmap\" \" for %d symbols (%d bytes)\", image->width, image->height, NSYMSDECODED - HCFIRSTSYM, BMSIZE);\n\n for (j = 0; j < image->height; j++) {\n memcpy(dst, src, stride);\n dst += image->stride;\n src += stride;\n }\n } else {\n Jbig2GenericRegionParams rparams;\n\n /* SumatraPDF: prevent read access violation */\n if (size - jbig2_huffman_offset(hs) < BMSIZE) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"not enough data for decoding (%d/%d)\", BMSIZE, size - jbig2_huffman_offset(hs));\n jbig2_image_release(ctx, image);\n goto cleanup4;\n }\n\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number,\n \"reading %dx%d collective bitmap for %d symbols (%d bytes)\", image->width, image->height, NSYMSDECODED - HCFIRSTSYM, BMSIZE);\n\n rparams.MMR = 1;\n code = jbig2_decode_generic_mmr(ctx, segment, &rparams, data + jbig2_huffman_offset(hs), BMSIZE, image);\n if (code) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"error decoding MMR bitmap image!\");\n jbig2_image_release(ctx, image);\n goto cleanup4;\n }\n }\n\n /* advance past the data we've just read */\n jbig2_huffman_advance(hs, BMSIZE);\n\n /* copy the collective bitmap into the symbol dictionary */\n x = 0;\n for (j = HCFIRSTSYM; j < NSYMSDECODED; j++) {\n Jbig2Image *glyph;\n\n glyph = jbig2_image_new(ctx, SDNEWSYMWIDTHS[j], HCHEIGHT);\n if (glyph == NULL) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"failed to copy the collective bitmap into symbol dictionary\");\n jbig2_image_release(ctx, image);\n goto cleanup4;\n }\n jbig2_image_compose(ctx, glyph, image, -x, 0, JBIG2_COMPOSE_REPLACE);\n x += SDNEWSYMWIDTHS[j];\n SDNEWSYMS->glyphs[j] = glyph;\n }\n jbig2_image_release(ctx, image);\n }\n\n } /* end of symbol decode loop */\n\n /* 6.5.10 */\n SDEXSYMS = jbig2_sd_new(ctx, params->SDNUMEXSYMS);\n if (SDEXSYMS == NULL) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"failed to allocate symbols exported from symbols dictionary\");\n goto cleanup4;\n } else {\n uint32_t i = 0;\n uint32_t j = 0;\n uint32_t k;\n int exflag = 0;\n uint32_t limit = params->SDNUMINSYMS + params->SDNUMNEWSYMS;\n uint32_t exrunlength;\n int zerolength = 0;\n\n while (i < limit) {\n if (params->SDHUFF)\n exrunlength = jbig2_huffman_get(hs, SBHUFFRSIZE, &code);\n else\n code = jbig2_arith_int_decode(IAEX, as, (int32_t *)&exrunlength);\n /* prevent infinite loop */\n zerolength = exrunlength > 0 ? 0 : zerolength + 1;\n if (code || (exrunlength > limit - i) || (zerolength > 4) || (exflag && (exrunlength + j > params->SDNUMEXSYMS))) {\n if (code)\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"failed to decode exrunlength for exported symbols\");\n else if (exrunlength <= 0)\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"runlength too small in export symbol table (%d <= 0)\\n\", exrunlength);\n else\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number,\n \"runlength too large in export symbol table (%d > %d - %d)\\n\", exrunlength, params->SDNUMEXSYMS, j);\n /* skip to the cleanup code and return SDEXSYMS = NULL */\n jbig2_sd_release(ctx, SDEXSYMS);\n SDEXSYMS = NULL;\n break;\n }\n for (k = 0; k < exrunlength; k++) {\n if (exflag) {\n SDEXSYMS->glyphs[j++] = (i < params->SDNUMINSYMS) ?\n jbig2_image_clone(ctx, params->SDINSYMS->glyphs[i]) : jbig2_image_clone(ctx, SDNEWSYMS->glyphs[i - params->SDNUMINSYMS]);\n }\n i++;\n }\n exflag = !exflag;\n }\n }\n\ncleanup4:\n if (tparams != NULL) {\n if (!params->SDHUFF) {\n jbig2_arith_int_ctx_free(ctx, tparams->IADT);\n jbig2_arith_int_ctx_free(ctx, tparams->IAFS);\n jbig2_arith_int_ctx_free(ctx, tparams->IADS);\n jbig2_arith_int_ctx_free(ctx, tparams->IAIT);\n jbig2_arith_iaid_ctx_free(ctx, tparams->IAID);\n jbig2_arith_int_ctx_free(ctx, tparams->IARI);\n jbig2_arith_int_ctx_free(ctx, tparams->IARDW);\n jbig2_arith_int_ctx_free(ctx, tparams->IARDH);\n jbig2_arith_int_ctx_free(ctx, tparams->IARDX);\n jbig2_arith_int_ctx_free(ctx, tparams->IARDY);\n } else {\n jbig2_release_huffman_table(ctx, tparams->SBHUFFFS);\n jbig2_release_huffman_table(ctx, tparams->SBHUFFDS);\n jbig2_release_huffman_table(ctx, tparams->SBHUFFDT);\n jbig2_release_huffman_table(ctx, tparams->SBHUFFRDX);\n jbig2_release_huffman_table(ctx, tparams->SBHUFFRDY);\n jbig2_release_huffman_table(ctx, tparams->SBHUFFRDW);\n jbig2_release_huffman_table(ctx, tparams->SBHUFFRDH);\n }\n jbig2_free(ctx->allocator, tparams);\n }\n if (refagg_dicts != NULL) {\n if (refagg_dicts[0] != NULL)\n jbig2_sd_release(ctx, refagg_dicts[0]);\n jbig2_free(ctx->allocator, refagg_dicts);\n }\n\ncleanup2:\n jbig2_sd_release(ctx, SDNEWSYMS);\n if (params->SDHUFF && !params->SDREFAGG) {\n jbig2_free(ctx->allocator, SDNEWSYMWIDTHS);\n }\n jbig2_release_huffman_table(ctx, SDHUFFRDX);\n jbig2_release_huffman_table(ctx, SBHUFFRSIZE);\n jbig2_huffman_free(ctx, hs);\n jbig2_arith_iaid_ctx_free(ctx, IAID);\n jbig2_arith_int_ctx_free(ctx, IARDX);\n jbig2_arith_int_ctx_free(ctx, IARDY);\n\ncleanup1:\n jbig2_word_stream_buf_free(ctx, ws);\n jbig2_free(ctx->allocator, as);\n jbig2_arith_int_ctx_free(ctx, IADH);\n jbig2_arith_int_ctx_free(ctx, IADW);\n jbig2_arith_int_ctx_free(ctx, IAEX);\n jbig2_arith_int_ctx_free(ctx, IAAI);\n\n return SDEXSYMS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Bug 697934: Fix SEGV due to error code being ignored.\n\nThe return code from jbig2_decode_text_region was being ignored so the\ncode continued to try and parse the invalid file using incomplete/empty\nstructures.'" }, { "text": "[INST] Given the following code containing errors, provide Common 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 TestRandomPool()\r\n{\r\n\tstd::cout << \"\\nTesting RandomPool generator...\\n\\n\";\r\n\tbool pass=true, fail;\r\n\t{\r\n\t\tRandomPool prng;\r\n\t\tstatic const unsigned int ENTROPY_SIZE = 32;\r\n\r\n\t\tMeterFilter meter(new Redirector(TheBitBucket()));\r\n\t\tRandomNumberSource test(prng, 100000, true, new Deflator(new Redirector(meter)));\r\n\r\n\t\tfail = false;\r\n\t\tif (meter.GetTotalBytes() < 100000)\r\n\t\t\tfail = true;\r\n\r\n\t\tpass &= !fail;\r\n\t\tif (fail)\r\n\t\t\tstd::cout << \"FAILED:\";\r\n\t\telse\r\n\t\t\tstd::cout << \"passed:\";\r\n\t\tstd::cout << \" 100000 generated bytes compressed to \" << meter.GetTotalBytes() << \" bytes by DEFLATE\\n\";\r\n\r\n\t\ttry\r\n\t\t{\r\n\t\t\tfail = false;\r\n\t\t\tprng.DiscardBytes(100000);\r\n\t\t}\r\n\t\tcatch (const Exception&)\r\n\t\t{\r\n\t\t\tfail = true;\r\n\t\t}\r\n\r\n\t\tpass &= !fail;\r\n\t\tif (fail)\r\n\t\t\tstd::cout << \"FAILED:\";\r\n\t\telse\r\n\t\t\tstd::cout << \"passed:\";\r\n\t\tstd::cout << \" discarded 10000 bytes\" << std::endl;\r\n\r\n\t\ttry\r\n\t\t{\r\n\t\t\tfail = false;\r\n\t\t\tif(prng.CanIncorporateEntropy())\r\n\t\t\t{\r\n\t\t\t\tSecByteBlock entropy(ENTROPY_SIZE);\r\n\t\t\t\tGlobalRNG().GenerateBlock(entropy, entropy.SizeInBytes());\r\n\r\n\t\t\t\tprng.IncorporateEntropy(entropy, entropy.SizeInBytes());\r\n\t\t\t\tprng.IncorporateEntropy(entropy, entropy.SizeInBytes());\r\n\t\t\t\tprng.IncorporateEntropy(entropy, entropy.SizeInBytes());\r\n\t\t\t\tprng.IncorporateEntropy(entropy, entropy.SizeInBytes());\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (const Exception& /*ex*/)\r\n\t\t{\r\n\t\t\tfail = true;\r\n\t\t}\r\n\r\n\t\tpass &= !fail;\r\n\t\tif (fail)\r\n\t\t\tstd::cout << \"FAILED:\";\r\n\t\telse\r\n\t\t\tstd::cout << \"passed:\";\r\n\t\tstd::cout << \" IncorporateEntropy with \" << 4*ENTROPY_SIZE << \" bytes\\n\";\r\n\r\n\t\ttry\r\n\t\t{\r\n\t\t\t// Miscellaneous for code coverage\r\n\t\t\t(void)prng.AlgorithmName(); // \"unknown\"\r\n\t\t\tword32 result = prng.GenerateWord32();\r\n\t\t\tresult = prng.GenerateWord32((result & 0xff), 0xffffffff - (result & 0xff));\r\n\t\t\tprng.GenerateBlock(reinterpret_cast(&result), 4);\r\n\t\t\tprng.GenerateBlock(reinterpret_cast(&result), 3);\r\n\t\t\tprng.GenerateBlock(reinterpret_cast(&result), 2);\r\n\t\t\tprng.GenerateBlock(reinterpret_cast(&result), 1);\r\n\t\t}\r\n\t\tcatch (const Exception&)\r\n\t\t{\r\n\t\t\tfail = true;\r\n\t\t}\r\n\r\n\t\tpass &= !fail;\r\n\t\tif (fail)\r\n\t\t\tstd::cout << \"FAILED:\";\r\n\t\telse\r\n\t\t\tstd::cout << \"passed:\";\r\n\t\tstd::cout << \" GenerateWord32 and Crop\\n\";\t\r\n\t}\r\n\r\n#if !defined(NO_OS_DEPENDENCE)\r\n\tstd::cout << \"\\nTesting AutoSeeded RandomPool generator...\\n\\n\";\r\n\t{\r\n\t\tAutoSeededRandomPool prng;\r\n\t\tstatic const unsigned int ENTROPY_SIZE = 32;\r\n\r\n\t\tMeterFilter meter(new Redirector(TheBitBucket()));\r\n\t\tRandomNumberSource test(prng, 100000, true, new Deflator(new Redirector(meter)));\r\n\r\n\t\tfail = false;\r\n\t\tif (meter.GetTotalBytes() < 100000)\r\n\t\t\tfail = true;\r\n\r\n\t\tpass &= !fail;\r\n\t\tif (fail)\r\n\t\t\tstd::cout << \"FAILED:\";\r\n\t\telse\r\n\t\t\tstd::cout << \"passed:\";\r\n\t\tstd::cout << \" 100000 generated bytes compressed to \" << meter.GetTotalBytes() << \" bytes by DEFLATE\\n\";\r\n\r\n\t\ttry\r\n\t\t{\r\n\t\t\tfail = false;\r\n\t\t\tprng.DiscardBytes(100000);\r\n\t\t}\r\n\t\tcatch (const Exception&)\r\n\t\t{\r\n\t\t\tfail = true;\r\n\t\t}\r\n\r\n\t\tpass &= !fail;\r\n\t\tif (fail)\r\n\t\t\tstd::cout << \"FAILED:\";\r\n\t\telse\r\n\t\t\tstd::cout << \"passed:\";\r\n\t\tstd::cout << \" discarded 10000 bytes\" << std::endl;\r\n\r\n\t\ttry\r\n\t\t{\r\n\t\t\tfail = false;\r\n\t\t\tif(prng.CanIncorporateEntropy())\r\n\t\t\t{\r\n\t\t\t\tSecByteBlock entropy(ENTROPY_SIZE);\r\n\t\t\t\tGlobalRNG().GenerateBlock(entropy, entropy.SizeInBytes());\r\n\r\n\t\t\t\tprng.IncorporateEntropy(entropy, entropy.SizeInBytes());\r\n\t\t\t\tprng.IncorporateEntropy(entropy, entropy.SizeInBytes());\r\n\t\t\t\tprng.IncorporateEntropy(entropy, entropy.SizeInBytes());\r\n\t\t\t\tprng.IncorporateEntropy(entropy, entropy.SizeInBytes());\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (const Exception& /*ex*/)\r\n\t\t{\r\n\t\t\tfail = true;\r\n\t\t}\r\n\r\n\t\tpass &= !fail;\r\n\t\tif (fail)\r\n\t\t\tstd::cout << \"FAILED:\";\r\n\t\telse\r\n\t\t\tstd::cout << \"passed:\";\r\n\t\tstd::cout << \" IncorporateEntropy with \" << 4*ENTROPY_SIZE << \" bytes\\n\";\r\n\r\n\t\ttry\r\n\t\t{\r\n\t\t\t// Miscellaneous for code coverage\r\n\t\t\tfail = false;\r\n\t\t\t(void)prng.AlgorithmName(); // \"unknown\"\r\n\t\t\tword32 result = prng.GenerateWord32();\r\n\t\t\tresult = prng.GenerateWord32((result & 0xff), 0xffffffff - (result & 0xff));\r\n\t\t\tprng.GenerateBlock(reinterpret_cast(&result), 4);\r\n\t\t\tprng.GenerateBlock(reinterpret_cast(&result), 3);\r\n\t\t\tprng.GenerateBlock(reinterpret_cast(&result), 2);\r\n\t\t\tprng.GenerateBlock(reinterpret_cast(&result), 1);\r\n\t\t}\r\n\t\tcatch (const Exception&)\r\n\t\t{\r\n\t\t\tfail = true;\r\n\t\t}\r\n\r\n\t\tpass &= !fail;\r\n\t\tif (fail)\r\n\t\t\tstd::cout << \"FAILED:\";\r\n\t\telse\r\n\t\t\tstd::cout << \"passed:\";\r\n\t\tstd::cout << \" GenerateWord32 and Crop\\n\";\t\r\n\t}\r\n#endif\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: connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,\n edge_connection_t *conn,\n crypt_path_t *layer_hint)\n{\n static int num_seen=0;\n relay_header_t rh;\n unsigned domain = layer_hint?LD_APP:LD_EXIT;\n int reason;\n int optimistic_data = 0; /* Set to 1 if we receive data on a stream\n * that's in the EXIT_CONN_STATE_RESOLVING\n * or EXIT_CONN_STATE_CONNECTING states. */\n\n tor_assert(cell);\n tor_assert(circ);\n\n relay_header_unpack(&rh, cell->payload);\n// log_fn(LOG_DEBUG,\"command %d stream %d\", rh.command, rh.stream_id);\n num_seen++;\n log_debug(domain, \"Now seen %d relay cells here (command %d, stream %d).\",\n num_seen, rh.command, rh.stream_id);\n\n if (rh.length > RELAY_PAYLOAD_SIZE) {\n log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,\n \"Relay cell length field too long. Closing circuit.\");\n return - END_CIRC_REASON_TORPROTOCOL;\n }\n\n if (rh.stream_id == 0) {\n switch (rh.command) {\n case RELAY_COMMAND_BEGIN:\n case RELAY_COMMAND_CONNECTED:\n case RELAY_COMMAND_DATA:\n case RELAY_COMMAND_END:\n case RELAY_COMMAND_RESOLVE:\n case RELAY_COMMAND_RESOLVED:\n case RELAY_COMMAND_BEGIN_DIR:\n log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \"Relay command %d with zero \"\n \"stream_id. Dropping.\", (int)rh.command);\n return 0;\n default:\n ;\n }\n }\n\n /* either conn is NULL, in which case we've got a control cell, or else\n * conn points to the recognized stream. */\n\n if (conn && !connection_state_is_open(TO_CONN(conn))) {\n if (conn->base_.type == CONN_TYPE_EXIT &&\n (conn->base_.state == EXIT_CONN_STATE_CONNECTING ||\n conn->base_.state == EXIT_CONN_STATE_RESOLVING) &&\n rh.command == RELAY_COMMAND_DATA) {\n /* Allow DATA cells to be delivered to an exit node in state\n * EXIT_CONN_STATE_CONNECTING or EXIT_CONN_STATE_RESOLVING.\n * This speeds up HTTP, for example. */\n optimistic_data = 1;\n } else {\n return connection_edge_process_relay_cell_not_open(\n &rh, cell, circ, conn, layer_hint);\n }\n }\n\n switch (rh.command) {\n case RELAY_COMMAND_DROP:\n// log_info(domain,\"Got a relay-level padding cell. Dropping.\");\n return 0;\n case RELAY_COMMAND_BEGIN:\n case RELAY_COMMAND_BEGIN_DIR:\n if (layer_hint &&\n circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {\n log_fn(LOG_PROTOCOL_WARN, LD_APP,\n \"Relay begin request unsupported at AP. Dropping.\");\n return 0;\n }\n if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED &&\n layer_hint != TO_ORIGIN_CIRCUIT(circ)->cpath->prev) {\n log_fn(LOG_PROTOCOL_WARN, LD_APP,\n \"Relay begin request to Hidden Service \"\n \"from intermediary node. Dropping.\");\n return 0;\n }\n if (conn) {\n log_fn(LOG_PROTOCOL_WARN, domain,\n \"Begin cell for known stream. Dropping.\");\n return 0;\n }\n if (rh.command == RELAY_COMMAND_BEGIN_DIR) {\n /* Assign this circuit and its app-ward OR connection a unique ID,\n * so that we can measure download times. The local edge and dir\n * connection will be assigned the same ID when they are created\n * and linked. */\n static uint64_t next_id = 0;\n circ->dirreq_id = ++next_id;\n TO_OR_CIRCUIT(circ)->p_chan->dirreq_id = circ->dirreq_id;\n }\n\n return connection_exit_begin_conn(cell, circ);\n case RELAY_COMMAND_DATA:\n ++stats_n_data_cells_received;\n if (( layer_hint && --layer_hint->deliver_window < 0) ||\n (!layer_hint && --circ->deliver_window < 0)) {\n log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,\n \"(relay data) circ deliver_window below 0. Killing.\");\n if (conn) {\n /* XXXX Do we actually need to do this? Will killing the circuit\n * not send an END and mark the stream for close as appropriate? */\n connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);\n connection_mark_for_close(TO_CONN(conn));\n }\n return -END_CIRC_REASON_TORPROTOCOL;\n }\n log_debug(domain,\"circ deliver_window now %d.\", layer_hint ?\n layer_hint->deliver_window : circ->deliver_window);\n\n circuit_consider_sending_sendme(circ, layer_hint);\n\n if (!conn) {\n log_info(domain,\"data cell dropped, unknown stream (streamid %d).\",\n rh.stream_id);\n return 0;\n }\n\n if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */\n log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,\n \"(relay data) conn deliver_window below 0. Killing.\");\n return -END_CIRC_REASON_TORPROTOCOL;\n }\n\n stats_n_data_bytes_received += rh.length;\n connection_write_to_buf((char*)(cell->payload + RELAY_HEADER_SIZE),\n rh.length, TO_CONN(conn));\n\n if (!optimistic_data) {\n /* Only send a SENDME if we're not getting optimistic data; otherwise\n * a SENDME could arrive before the CONNECTED.\n */\n connection_edge_consider_sending_sendme(conn);\n }\n\n return 0;\n case RELAY_COMMAND_END:\n reason = rh.length > 0 ?\n get_uint8(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;\n if (!conn) {\n log_info(domain,\"end cell (%s) dropped, unknown stream.\",\n stream_end_reason_to_string(reason));\n return 0;\n }\n/* XXX add to this log_fn the exit node's nickname? */\n log_info(domain,TOR_SOCKET_T_FORMAT\": end cell (%s) for stream %d. \"\n \"Removing stream.\",\n conn->base_.s,\n stream_end_reason_to_string(reason),\n conn->stream_id);\n if (conn->base_.type == CONN_TYPE_AP) {\n entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);\n if (entry_conn->socks_request &&\n !entry_conn->socks_request->has_finished)\n log_warn(LD_BUG,\n \"open stream hasn't sent socks answer yet? Closing.\");\n }\n /* We just *got* an end; no reason to send one. */\n conn->edge_has_sent_end = 1;\n if (!conn->end_reason)\n conn->end_reason = reason | END_STREAM_REASON_FLAG_REMOTE;\n if (!conn->base_.marked_for_close) {\n /* only mark it if not already marked. it's possible to\n * get the 'end' right around when the client hangs up on us. */\n connection_mark_and_flush(TO_CONN(conn));\n }\n return 0;\n case RELAY_COMMAND_EXTEND:\n case RELAY_COMMAND_EXTEND2: {\n static uint64_t total_n_extend=0, total_nonearly=0;\n total_n_extend++;\n if (rh.stream_id) {\n log_fn(LOG_PROTOCOL_WARN, domain,\n \"'extend' cell received for non-zero stream. Dropping.\");\n return 0;\n }\n if (cell->command != CELL_RELAY_EARLY &&\n !networkstatus_get_param(NULL,\"AllowNonearlyExtend\",0,0,1)) {\n#define EARLY_WARNING_INTERVAL 3600\n static ratelim_t early_warning_limit =\n RATELIM_INIT(EARLY_WARNING_INTERVAL);\n char *m;\n if (cell->command == CELL_RELAY) {\n ++total_nonearly;\n if ((m = rate_limit_log(&early_warning_limit, approx_time()))) {\n double percentage = ((double)total_nonearly)/total_n_extend;\n percentage *= 100;\n log_fn(LOG_PROTOCOL_WARN, domain, \"EXTEND cell received, \"\n \"but not via RELAY_EARLY. Dropping.%s\", m);\n log_fn(LOG_PROTOCOL_WARN, domain, \" (We have dropped %.02f%% of \"\n \"all EXTEND cells for this reason)\", percentage);\n tor_free(m);\n }\n } else {\n log_fn(LOG_WARN, domain,\n \"EXTEND cell received, in a cell with type %d! Dropping.\",\n cell->command);\n }\n return 0;\n }\n return circuit_extend(cell, circ);\n }\n case RELAY_COMMAND_EXTENDED:\n case RELAY_COMMAND_EXTENDED2:\n if (!layer_hint) {\n log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,\n \"'extended' unsupported at non-origin. Dropping.\");\n return 0;\n }\n log_debug(domain,\"Got an extended cell! Yay.\");\n {\n extended_cell_t extended_cell;\n if (extended_cell_parse(&extended_cell, rh.command,\n (const uint8_t*)cell->payload+RELAY_HEADER_SIZE,\n rh.length)<0) {\n log_warn(LD_PROTOCOL,\n \"Can't parse EXTENDED cell; killing circuit.\");\n return -END_CIRC_REASON_TORPROTOCOL;\n }\n if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ),\n &extended_cell.created_cell)) < 0) {\n log_warn(domain,\"circuit_finish_handshake failed.\");\n return reason;\n }\n }\n if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) {\n log_info(domain,\"circuit_send_next_onion_skin() failed.\");\n return reason;\n }\n return 0;\n case RELAY_COMMAND_TRUNCATE:\n if (layer_hint) {\n log_fn(LOG_PROTOCOL_WARN, LD_APP,\n \"'truncate' unsupported at origin. Dropping.\");\n return 0;\n }\n if (circ->n_hop) {\n if (circ->n_chan)\n log_warn(LD_BUG, \"n_chan and n_hop set on the same circuit!\");\n extend_info_free(circ->n_hop);\n circ->n_hop = NULL;\n tor_free(circ->n_chan_create_cell);\n circuit_set_state(circ, CIRCUIT_STATE_OPEN);\n }\n if (circ->n_chan) {\n uint8_t trunc_reason = get_uint8(cell->payload + RELAY_HEADER_SIZE);\n circuit_clear_cell_queue(circ, circ->n_chan);\n channel_send_destroy(circ->n_circ_id, circ->n_chan,\n trunc_reason);\n circuit_set_n_circid_chan(circ, 0, NULL);\n }\n log_debug(LD_EXIT, \"Processed 'truncate', replying.\");\n {\n char payload[1];\n payload[0] = (char)END_CIRC_REASON_REQUESTED;\n relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,\n payload, sizeof(payload), NULL);\n }\n return 0;\n case RELAY_COMMAND_TRUNCATED:\n if (!layer_hint) {\n log_fn(LOG_PROTOCOL_WARN, LD_EXIT,\n \"'truncated' unsupported at non-origin. Dropping.\");\n return 0;\n }\n circuit_truncated(TO_ORIGIN_CIRCUIT(circ), layer_hint,\n get_uint8(cell->payload + RELAY_HEADER_SIZE));\n return 0;\n case RELAY_COMMAND_CONNECTED:\n if (conn) {\n log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,\n \"'connected' unsupported while open. Closing circ.\");\n return -END_CIRC_REASON_TORPROTOCOL;\n }\n log_info(domain,\n \"'connected' received, no conn attached anymore. Ignoring.\");\n return 0;\n case RELAY_COMMAND_SENDME:\n if (!rh.stream_id) {\n if (layer_hint) {\n if (layer_hint->package_window + CIRCWINDOW_INCREMENT >\n CIRCWINDOW_START_MAX) {\n log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,\n \"Unexpected sendme cell from exit relay. \"\n \"Closing circ.\");\n return -END_CIRC_REASON_TORPROTOCOL;\n }\n layer_hint->package_window += CIRCWINDOW_INCREMENT;\n log_debug(LD_APP,\"circ-level sendme at origin, packagewindow %d.\",\n layer_hint->package_window);\n circuit_resume_edge_reading(circ, layer_hint);\n } else {\n if (circ->package_window + CIRCWINDOW_INCREMENT >\n CIRCWINDOW_START_MAX) {\n log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,\n \"Unexpected sendme cell from client. \"\n \"Closing circ (window %d).\",\n circ->package_window);\n return -END_CIRC_REASON_TORPROTOCOL;\n }\n circ->package_window += CIRCWINDOW_INCREMENT;\n log_debug(LD_APP,\n \"circ-level sendme at non-origin, packagewindow %d.\",\n circ->package_window);\n circuit_resume_edge_reading(circ, layer_hint);\n }\n return 0;\n }\n if (!conn) {\n log_info(domain,\"sendme cell dropped, unknown stream (streamid %d).\",\n rh.stream_id);\n return 0;\n }\n conn->package_window += STREAMWINDOW_INCREMENT;\n log_debug(domain,\"stream-level sendme, packagewindow now %d.\",\n conn->package_window);\n if (circuit_queue_streams_are_blocked(circ)) {\n /* Still waiting for queue to flush; don't touch conn */\n return 0;\n }\n connection_start_reading(TO_CONN(conn));\n /* handle whatever might still be on the inbuf */\n if (connection_edge_package_raw_inbuf(conn, 1, NULL) < 0) {\n /* (We already sent an end cell if possible) */\n connection_mark_for_close(TO_CONN(conn));\n return 0;\n }\n return 0;\n case RELAY_COMMAND_RESOLVE:\n if (layer_hint) {\n log_fn(LOG_PROTOCOL_WARN, LD_APP,\n \"resolve request unsupported at AP; dropping.\");\n return 0;\n } else if (conn) {\n log_fn(LOG_PROTOCOL_WARN, domain,\n \"resolve request for known stream; dropping.\");\n return 0;\n } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {\n log_fn(LOG_PROTOCOL_WARN, domain,\n \"resolve request on circ with purpose %d; dropping\",\n circ->purpose);\n return 0;\n }\n connection_exit_begin_resolve(cell, TO_OR_CIRCUIT(circ));\n return 0;\n case RELAY_COMMAND_RESOLVED:\n if (conn) {\n log_fn(LOG_PROTOCOL_WARN, domain,\n \"'resolved' unsupported while open. Closing circ.\");\n return -END_CIRC_REASON_TORPROTOCOL;\n }\n log_info(domain,\n \"'resolved' received, no conn attached anymore. Ignoring.\");\n return 0;\n case RELAY_COMMAND_ESTABLISH_INTRO:\n case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:\n case RELAY_COMMAND_INTRODUCE1:\n case RELAY_COMMAND_INTRODUCE2:\n case RELAY_COMMAND_INTRODUCE_ACK:\n case RELAY_COMMAND_RENDEZVOUS1:\n case RELAY_COMMAND_RENDEZVOUS2:\n case RELAY_COMMAND_INTRO_ESTABLISHED:\n case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:\n rend_process_relay_cell(circ, layer_hint,\n rh.command, rh.length,\n cell->payload+RELAY_HEADER_SIZE);\n return 0;\n }\n log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,\n \"Received unknown relay command %d. Perhaps the other side is using \"\n \"a newer version of Tor? Dropping.\",\n rh.command);\n return 0; /* for forward compatibility, don't kill the circuit */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-617'], 'message': 'TROVE-2017-005: Fix assertion failure in connection_edge_process_relay_cell\n\nOn an hidden service rendezvous circuit, a BEGIN_DIR could be sent\n(maliciously) which would trigger a tor_assert() because\nconnection_edge_process_relay_cell() thought that the circuit is an\nor_circuit_t but is an origin circuit in reality.\n\nFixes #22494\n\nReported-by: Roger Dingledine \nSigned-off-by: David Goulet '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline int vma_growsdown(struct vm_area_struct *vma, unsigned long addr)\n{\n\treturn vma && (vma->vm_end == addr) && (vma->vm_flags & VM_GROWSDOWN);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'mm: larger stack guard gap, between vmas\n\nStack guard page is a useful feature to reduce a risk of stack smashing\ninto a different mapping. We have been using a single page gap which\nis sufficient to prevent having stack adjacent to a different mapping.\nBut this seems to be insufficient in the light of the stack usage in\nuserspace. E.g. glibc uses as large as 64kB alloca() in many commonly\nused functions. Others use constructs liks gid_t buffer[NGROUPS_MAX]\nwhich is 256kB or stack strings with MAX_ARG_STRLEN.\n\nThis will become especially dangerous for suid binaries and the default\nno limit for the stack size limit because those applications can be\ntricked to consume a large portion of the stack and a single glibc call\ncould jump over the guard page. These attacks are not theoretical,\nunfortunatelly.\n\nMake those attacks less probable by increasing the stack guard gap\nto 1MB (on systems with 4k pages; but make it depend on the page size\nbecause systems with larger base pages might cap stack allocations in\nthe PAGE_SIZE units) which should cover larger alloca() and VLA stack\nallocations. It is obviously not a full fix because the problem is\nsomehow inherent, but it should reduce attack space a lot.\n\nOne could argue that the gap size should be configurable from userspace,\nbut that can be done later when somebody finds that the new 1MB is wrong\nfor some special case applications. For now, add a kernel command line\noption (stack_guard_gap) to specify the stack gap size (in page units).\n\nImplementation wise, first delete all the old code for stack guard page:\nbecause although we could get away with accounting one extra page in a\nstack vma, accounting a larger gap can break userspace - case in point,\na program run with \"ulimit -S -v 20000\" failed when the 1MB gap was\ncounted for RLIMIT_AS; similar problems could come with RLIMIT_MLOCK\nand strict non-overcommit mode.\n\nInstead of keeping gap inside the stack vma, maintain the stack guard\ngap as a gap between vmas: using vm_start_gap() in place of vm_start\n(or vm_end_gap() in place of vm_end if VM_GROWSUP) in just those few\nplaces which need to respect the gap - mainly arch_get_unmapped_area(),\nand and the vma tree's subtree_gap support for that.\n\nOriginal-patch-by: Oleg Nesterov \nOriginal-patch-by: Michal Hocko \nSigned-off-by: Hugh Dickins \nAcked-by: Michal Hocko \nTested-by: Helge Deller # parisc\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: radix__hugetlb_get_unmapped_area(struct file *file, unsigned long addr,\n\t\t\t\tunsigned long len, unsigned long pgoff,\n\t\t\t\tunsigned long flags)\n{\n\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *vma;\n\tstruct hstate *h = hstate_file(file);\n\tstruct vm_unmapped_area_info info;\n\n\tif (unlikely(addr > mm->context.addr_limit && addr < TASK_SIZE))\n\t\tmm->context.addr_limit = TASK_SIZE;\n\n\tif (len & ~huge_page_mask(h))\n\t\treturn -EINVAL;\n\tif (len > mm->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 (mm->task_size - len >= addr &&\n\t\t (!vma || addr + len <= vma->vm_start))\n\t\t\treturn addr;\n\t}\n\t/*\n\t * We are always doing an topdown search here. Slice code\n\t * does that too.\n\t */\n\tinfo.flags = VM_UNMAPPED_AREA_TOPDOWN;\n\tinfo.length = len;\n\tinfo.low_limit = PAGE_SIZE;\n\tinfo.high_limit = current->mm->mmap_base;\n\tinfo.align_mask = PAGE_MASK & ~huge_page_mask(h);\n\tinfo.align_offset = 0;\n\n\tif (addr > DEFAULT_MAP_WINDOW)\n\t\tinfo.high_limit += mm->context.addr_limit - DEFAULT_MAP_WINDOW;\n\n\treturn vm_unmapped_area(&info);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'mm: larger stack guard gap, between vmas\n\nStack guard page is a useful feature to reduce a risk of stack smashing\ninto a different mapping. We have been using a single page gap which\nis sufficient to prevent having stack adjacent to a different mapping.\nBut this seems to be insufficient in the light of the stack usage in\nuserspace. E.g. glibc uses as large as 64kB alloca() in many commonly\nused functions. Others use constructs liks gid_t buffer[NGROUPS_MAX]\nwhich is 256kB or stack strings with MAX_ARG_STRLEN.\n\nThis will become especially dangerous for suid binaries and the default\nno limit for the stack size limit because those applications can be\ntricked to consume a large portion of the stack and a single glibc call\ncould jump over the guard page. These attacks are not theoretical,\nunfortunatelly.\n\nMake those attacks less probable by increasing the stack guard gap\nto 1MB (on systems with 4k pages; but make it depend on the page size\nbecause systems with larger base pages might cap stack allocations in\nthe PAGE_SIZE units) which should cover larger alloca() and VLA stack\nallocations. It is obviously not a full fix because the problem is\nsomehow inherent, but it should reduce attack space a lot.\n\nOne could argue that the gap size should be configurable from userspace,\nbut that can be done later when somebody finds that the new 1MB is wrong\nfor some special case applications. For now, add a kernel command line\noption (stack_guard_gap) to specify the stack gap size (in page units).\n\nImplementation wise, first delete all the old code for stack guard page:\nbecause although we could get away with accounting one extra page in a\nstack vma, accounting a larger gap can break userspace - case in point,\na program run with \"ulimit -S -v 20000\" failed when the 1MB gap was\ncounted for RLIMIT_AS; similar problems could come with RLIMIT_MLOCK\nand strict non-overcommit mode.\n\nInstead of keeping gap inside the stack vma, maintain the stack guard\ngap as a gap between vmas: using vm_start_gap() in place of vm_start\n(or vm_end_gap() in place of vm_end if VM_GROWSUP) in just those few\nplaces which need to respect the gap - mainly arch_get_unmapped_area(),\nand and the vma tree's subtree_gap support for that.\n\nOriginal-patch-by: Oleg Nesterov \nOriginal-patch-by: Michal Hocko \nSigned-off-by: Hugh Dickins \nAcked-by: Michal Hocko \nTested-by: Helge Deller # parisc\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int expand_stack(struct vm_area_struct *vma, unsigned long address)\n{\n\tstruct vm_area_struct *next;\n\n\taddress &= PAGE_MASK;\n\tnext = vma->vm_next;\n\tif (next && next->vm_start == address + PAGE_SIZE) {\n\t\tif (!(next->vm_flags & VM_GROWSUP))\n\t\t\treturn -ENOMEM;\n\t}\n\treturn expand_upwards(vma, address);\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, unsigned long pgoff, unsigned long flags)\n{\n\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct * vma;\n\tunsigned long task_size = TASK_SIZE;\n\tint do_color_align;\n\tstruct vm_unmapped_area_info info;\n\n\tif (flags & MAP_FIXED) {\n\t\t/* We do not accept a shared mapping if it would violate\n\t\t * cache aliasing constraints.\n\t\t */\n\t\tif ((flags & MAP_SHARED) &&\n\t\t ((addr - (pgoff << PAGE_SHIFT)) & (SHMLBA - 1)))\n\t\t\treturn -EINVAL;\n\t\treturn addr;\n\t}\n\n\tif (test_thread_flag(TIF_32BIT))\n\t\ttask_size = STACK_TOP32;\n\tif (unlikely(len > task_size || len >= VA_EXCLUDE_START))\n\t\treturn -ENOMEM;\n\n\tdo_color_align = 0;\n\tif (filp || (flags & MAP_SHARED))\n\t\tdo_color_align = 1;\n\n\tif (addr) {\n\t\tif (do_color_align)\n\t\t\taddr = COLOR_ALIGN(addr, pgoff);\n\t\telse\n\t\t\taddr = PAGE_ALIGN(addr);\n\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\n\tinfo.flags = 0;\n\tinfo.length = len;\n\tinfo.low_limit = TASK_UNMAPPED_BASE;\n\tinfo.high_limit = min(task_size, VA_EXCLUDE_START);\n\tinfo.align_mask = do_color_align ? (PAGE_MASK & (SHMLBA - 1)) : 0;\n\tinfo.align_offset = pgoff << PAGE_SHIFT;\n\taddr = vm_unmapped_area(&info);\n\n\tif ((addr & ~PAGE_MASK) && task_size > VA_EXCLUDE_END) {\n\t\tVM_BUG_ON(addr != -ENOMEM);\n\t\tinfo.low_limit = VA_EXCLUDE_END;\n\t\tinfo.high_limit = task_size;\n\t\taddr = vm_unmapped_area(&info);\n\t}\n\n\treturn addr;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'mm: larger stack guard gap, between vmas\n\nStack guard page is a useful feature to reduce a risk of stack smashing\ninto a different mapping. We have been using a single page gap which\nis sufficient to prevent having stack adjacent to a different mapping.\nBut this seems to be insufficient in the light of the stack usage in\nuserspace. E.g. glibc uses as large as 64kB alloca() in many commonly\nused functions. Others use constructs liks gid_t buffer[NGROUPS_MAX]\nwhich is 256kB or stack strings with MAX_ARG_STRLEN.\n\nThis will become especially dangerous for suid binaries and the default\nno limit for the stack size limit because those applications can be\ntricked to consume a large portion of the stack and a single glibc call\ncould jump over the guard page. These attacks are not theoretical,\nunfortunatelly.\n\nMake those attacks less probable by increasing the stack guard gap\nto 1MB (on systems with 4k pages; but make it depend on the page size\nbecause systems with larger base pages might cap stack allocations in\nthe PAGE_SIZE units) which should cover larger alloca() and VLA stack\nallocations. It is obviously not a full fix because the problem is\nsomehow inherent, but it should reduce attack space a lot.\n\nOne could argue that the gap size should be configurable from userspace,\nbut that can be done later when somebody finds that the new 1MB is wrong\nfor some special case applications. For now, add a kernel command line\noption (stack_guard_gap) to specify the stack gap size (in page units).\n\nImplementation wise, first delete all the old code for stack guard page:\nbecause although we could get away with accounting one extra page in a\nstack vma, accounting a larger gap can break userspace - case in point,\na program run with \"ulimit -S -v 20000\" failed when the 1MB gap was\ncounted for RLIMIT_AS; similar problems could come with RLIMIT_MLOCK\nand strict non-overcommit mode.\n\nInstead of keeping gap inside the stack vma, maintain the stack guard\ngap as a gap between vmas: using vm_start_gap() in place of vm_start\n(or vm_end_gap() in place of vm_end if VM_GROWSUP) in just those few\nplaces which need to respect the gap - mainly arch_get_unmapped_area(),\nand and the vma tree's subtree_gap support for that.\n\nOriginal-patch-by: Oleg Nesterov \nOriginal-patch-by: Michal Hocko \nSigned-off-by: Hugh Dickins \nAcked-by: Michal Hocko \nTested-by: Helge Deller # parisc\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadMIFFImage(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n#define BZipMaxExtent(x) ((x)+((x)/100)+600)\n#define LZMAMaxExtent(x) ((x)+((x)/3)+128)\n#define ZipMaxExtent(x) ((x)+(((x)+7) >> 3)+(((x)+63) >> 6)+11)\n\n#if defined(MAGICKCORE_BZLIB_DELEGATE)\n bz_stream\n bzip_info;\n#endif\n\n char\n id[MagickPathExtent],\n keyword[MagickPathExtent],\n *options;\n\n const unsigned char\n *p;\n\n double\n version;\n\n GeometryInfo\n geometry_info;\n\n Image\n *image;\n\n int\n c;\n\n LinkedListInfo\n *profiles;\n\n#if defined(MAGICKCORE_LZMA_DELEGATE)\n lzma_stream\n initialize_lzma = LZMA_STREAM_INIT,\n lzma_info;\n\n lzma_allocator\n allocator;\n#endif\n\n MagickBooleanType\n status;\n\n PixelInfo\n pixel;\n\n MagickStatusType\n flags;\n\n QuantumFormatType\n quantum_format;\n\n QuantumInfo\n *quantum_info;\n\n QuantumType\n quantum_type;\n\n register ssize_t\n i;\n\n size_t\n compress_extent,\n length,\n packet_size;\n\n ssize_t\n count;\n\n unsigned char\n *compress_pixels,\n *pixels;\n\n size_t\n colors;\n\n ssize_t\n y;\n\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n z_stream\n zip_info;\n#endif\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Decode image header; header terminates one character beyond a ':'.\n */\n c=ReadBlobByte(image);\n if (c == EOF)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n *id='\\0';\n (void) ResetMagickMemory(keyword,0,sizeof(keyword));\n version=0.0;\n (void) version;\n do\n {\n /*\n Decode image header; header terminates one character beyond a ':'.\n */\n length=MagickPathExtent;\n options=AcquireString((char *) NULL);\n quantum_format=UndefinedQuantumFormat;\n profiles=(LinkedListInfo *) NULL;\n colors=0;\n image->depth=8UL;\n image->compression=NoCompression;\n while ((isgraph(c) != MagickFalse) && (c != (int) ':'))\n {\n register char\n *p;\n\n if (c == (int) '{')\n {\n char\n *comment;\n\n /*\n Read comment-- any text between { }.\n */\n length=MagickPathExtent;\n comment=AcquireString((char *) NULL);\n for (p=comment; comment != (char *) NULL; p++)\n {\n c=ReadBlobByte(image);\n if (c == (int) '\\\\')\n c=ReadBlobByte(image);\n else\n if ((c == EOF) || (c == (int) '}'))\n break;\n if ((size_t) (p-comment+1) >= length)\n {\n *p='\\0';\n length<<=1;\n comment=(char *) ResizeQuantumMemory(comment,length+\n MagickPathExtent,sizeof(*comment));\n if (comment == (char *) NULL)\n break;\n p=comment+strlen(comment);\n }\n *p=(char) c;\n }\n if (comment == (char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n *p='\\0';\n (void) SetImageProperty(image,\"comment\",comment,exception);\n comment=DestroyString(comment);\n c=ReadBlobByte(image);\n }\n else\n if (isalnum(c) != MagickFalse)\n {\n /*\n Get the keyword.\n */\n length=MagickPathExtent;\n p=keyword;\n do\n {\n if (c == (int) '=')\n break;\n if ((size_t) (p-keyword) < (MagickPathExtent-1))\n *p++=(char) c;\n c=ReadBlobByte(image);\n } while (c != EOF);\n *p='\\0';\n p=options;\n while ((isspace((int) ((unsigned char) c)) != 0) && (c != EOF))\n c=ReadBlobByte(image);\n if (c == (int) '=')\n {\n /*\n Get the keyword value.\n */\n c=ReadBlobByte(image);\n while ((c != (int) '}') && (c != EOF))\n {\n if ((size_t) (p-options+1) >= length)\n {\n *p='\\0';\n length<<=1;\n options=(char *) ResizeQuantumMemory(options,length+\n MagickPathExtent,sizeof(*options));\n if (options == (char *) NULL)\n break;\n p=options+strlen(options);\n }\n *p++=(char) c;\n c=ReadBlobByte(image);\n if (c == '\\\\')\n {\n c=ReadBlobByte(image);\n if (c == (int) '}')\n {\n *p++=(char) c;\n c=ReadBlobByte(image);\n }\n }\n if (*options != '{')\n if (isspace((int) ((unsigned char) c)) != 0)\n break;\n }\n if (options == (char *) NULL)\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n *p='\\0';\n if (*options == '{')\n (void) CopyMagickString(options,options+1,strlen(options));\n /*\n Assign a value to the specified keyword.\n */\n switch (*keyword)\n {\n case 'a':\n case 'A':\n {\n if (LocaleCompare(keyword,\"alpha-trait\") == 0)\n {\n ssize_t\n alpha_trait;\n\n alpha_trait=ParseCommandOption(MagickPixelTraitOptions,\n MagickFalse,options);\n if (alpha_trait < 0)\n break;\n image->alpha_trait=(PixelTrait) alpha_trait;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'b':\n case 'B':\n {\n if (LocaleCompare(keyword,\"background-color\") == 0)\n {\n (void) QueryColorCompliance(options,AllCompliance,\n &image->background_color,exception);\n break;\n }\n if (LocaleCompare(keyword,\"blue-primary\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->chromaticity.blue_primary.x=geometry_info.rho;\n image->chromaticity.blue_primary.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->chromaticity.blue_primary.y=\n image->chromaticity.blue_primary.x;\n break;\n }\n if (LocaleCompare(keyword,\"border-color\") == 0)\n {\n (void) QueryColorCompliance(options,AllCompliance,\n &image->border_color,exception);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'c':\n case 'C':\n {\n if (LocaleCompare(keyword,\"class\") == 0)\n {\n ssize_t\n storage_class;\n\n storage_class=ParseCommandOption(MagickClassOptions,\n MagickFalse,options);\n if (storage_class < 0)\n break;\n image->storage_class=(ClassType) storage_class;\n break;\n }\n if (LocaleCompare(keyword,\"colors\") == 0)\n {\n colors=StringToUnsignedLong(options);\n break;\n }\n if (LocaleCompare(keyword,\"colorspace\") == 0)\n {\n ssize_t\n colorspace;\n\n colorspace=ParseCommandOption(MagickColorspaceOptions,\n MagickFalse,options);\n if (colorspace < 0)\n break;\n image->colorspace=(ColorspaceType) colorspace;\n break;\n }\n if (LocaleCompare(keyword,\"compression\") == 0)\n {\n ssize_t\n compression;\n\n compression=ParseCommandOption(MagickCompressOptions,\n MagickFalse,options);\n if (compression < 0)\n break;\n image->compression=(CompressionType) compression;\n break;\n }\n if (LocaleCompare(keyword,\"columns\") == 0)\n {\n image->columns=StringToUnsignedLong(options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'd':\n case 'D':\n {\n if (LocaleCompare(keyword,\"delay\") == 0)\n {\n image->delay=StringToUnsignedLong(options);\n break;\n }\n if (LocaleCompare(keyword,\"depth\") == 0)\n {\n image->depth=StringToUnsignedLong(options);\n break;\n }\n if (LocaleCompare(keyword,\"dispose\") == 0)\n {\n ssize_t\n dispose;\n\n dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse,\n options);\n if (dispose < 0)\n break;\n image->dispose=(DisposeType) dispose;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'e':\n case 'E':\n {\n if (LocaleCompare(keyword,\"endian\") == 0)\n {\n ssize_t\n endian;\n\n endian=ParseCommandOption(MagickEndianOptions,MagickFalse,\n options);\n if (endian < 0)\n break;\n image->endian=(EndianType) endian;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'g':\n case 'G':\n {\n if (LocaleCompare(keyword,\"gamma\") == 0)\n {\n image->gamma=StringToDouble(options,(char **) NULL);\n break;\n }\n if (LocaleCompare(keyword,\"gravity\") == 0)\n {\n ssize_t\n gravity;\n\n gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,\n options);\n if (gravity < 0)\n break;\n image->gravity=(GravityType) gravity;\n break;\n }\n if (LocaleCompare(keyword,\"green-primary\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->chromaticity.green_primary.x=geometry_info.rho;\n image->chromaticity.green_primary.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->chromaticity.green_primary.y=\n image->chromaticity.green_primary.x;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'i':\n case 'I':\n {\n if (LocaleCompare(keyword,\"id\") == 0)\n {\n (void) CopyMagickString(id,options,MagickPathExtent);\n break;\n }\n if (LocaleCompare(keyword,\"iterations\") == 0)\n {\n image->iterations=StringToUnsignedLong(options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'm':\n case 'M':\n {\n if (LocaleCompare(keyword,\"matte\") == 0)\n {\n ssize_t\n matte;\n\n matte=ParseCommandOption(MagickBooleanOptions,MagickFalse,\n options);\n if (matte < 0)\n break;\n image->alpha_trait=matte == 0 ? UndefinedPixelTrait :\n BlendPixelTrait;\n break;\n }\n if (LocaleCompare(keyword,\"mattecolor\") == 0)\n {\n (void) QueryColorCompliance(options,AllCompliance,\n &image->matte_color,exception);\n break;\n }\n if (LocaleCompare(keyword,\"montage\") == 0)\n {\n (void) CloneString(&image->montage,options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'o':\n case 'O':\n {\n if (LocaleCompare(keyword,\"orientation\") == 0)\n {\n ssize_t\n orientation;\n\n orientation=ParseCommandOption(MagickOrientationOptions,\n MagickFalse,options);\n if (orientation < 0)\n break;\n image->orientation=(OrientationType) orientation;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'p':\n case 'P':\n {\n if (LocaleCompare(keyword,\"page\") == 0)\n {\n char\n *geometry;\n\n geometry=GetPageGeometry(options);\n (void) ParseAbsoluteGeometry(geometry,&image->page);\n geometry=DestroyString(geometry);\n break;\n }\n if (LocaleCompare(keyword,\"pixel-intensity\") == 0)\n {\n ssize_t\n intensity;\n\n intensity=ParseCommandOption(MagickPixelIntensityOptions,\n MagickFalse,options);\n if (intensity < 0)\n break;\n image->intensity=(PixelIntensityMethod) intensity;\n break;\n }\n if ((LocaleNCompare(keyword,\"profile:\",8) == 0) ||\n (LocaleNCompare(keyword,\"profile-\",8) == 0))\n {\n StringInfo\n *profile;\n\n if (profiles == (LinkedListInfo *) NULL)\n profiles=NewLinkedList(0);\n (void) AppendValueToLinkedList(profiles,\n AcquireString(keyword+8));\n profile=BlobToStringInfo((const void *) NULL,(size_t)\n StringToLong(options));\n if (profile == (StringInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n (void) SetImageProfile(image,keyword+8,profile,exception);\n profile=DestroyStringInfo(profile);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'q':\n case 'Q':\n {\n if (LocaleCompare(keyword,\"quality\") == 0)\n {\n image->quality=StringToUnsignedLong(options);\n break;\n }\n if ((LocaleCompare(keyword,\"quantum-format\") == 0) ||\n (LocaleCompare(keyword,\"quantum:format\") == 0))\n {\n ssize_t\n format;\n\n format=ParseCommandOption(MagickQuantumFormatOptions,\n MagickFalse,options);\n if (format < 0)\n break;\n quantum_format=(QuantumFormatType) format;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'r':\n case 'R':\n {\n if (LocaleCompare(keyword,\"red-primary\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->chromaticity.red_primary.x=geometry_info.rho;\n image->chromaticity.red_primary.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->chromaticity.red_primary.y=\n image->chromaticity.red_primary.x;\n break;\n }\n if (LocaleCompare(keyword,\"rendering-intent\") == 0)\n {\n ssize_t\n rendering_intent;\n\n rendering_intent=ParseCommandOption(MagickIntentOptions,\n MagickFalse,options);\n if (rendering_intent < 0)\n break;\n image->rendering_intent=(RenderingIntent) rendering_intent;\n break;\n }\n if (LocaleCompare(keyword,\"resolution\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->resolution.x=geometry_info.rho;\n image->resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->resolution.y=image->resolution.x;\n break;\n }\n if (LocaleCompare(keyword,\"rows\") == 0)\n {\n image->rows=StringToUnsignedLong(options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 's':\n case 'S':\n {\n if (LocaleCompare(keyword,\"scene\") == 0)\n {\n image->scene=StringToUnsignedLong(options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 't':\n case 'T':\n {\n if (LocaleCompare(keyword,\"ticks-per-second\") == 0)\n {\n image->ticks_per_second=(ssize_t) StringToLong(options);\n break;\n }\n if (LocaleCompare(keyword,\"tile-offset\") == 0)\n {\n char\n *geometry;\n\n geometry=GetPageGeometry(options);\n (void) ParseAbsoluteGeometry(geometry,&image->tile_offset);\n geometry=DestroyString(geometry);\n break;\n }\n if (LocaleCompare(keyword,\"type\") == 0)\n {\n ssize_t\n type;\n\n type=ParseCommandOption(MagickTypeOptions,MagickFalse,\n options);\n if (type < 0)\n break;\n image->type=(ImageType) type;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'u':\n case 'U':\n {\n if (LocaleCompare(keyword,\"units\") == 0)\n {\n ssize_t\n units;\n\n units=ParseCommandOption(MagickResolutionOptions,\n MagickFalse,options);\n if (units < 0)\n break;\n image->units=(ResolutionType) units;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'v':\n case 'V':\n {\n if (LocaleCompare(keyword,\"version\") == 0)\n {\n version=StringToDouble(options,(char **) NULL);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'w':\n case 'W':\n {\n if (LocaleCompare(keyword,\"white-point\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->chromaticity.white_point.x=geometry_info.rho;\n image->chromaticity.white_point.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->chromaticity.white_point.y=\n image->chromaticity.white_point.x;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n default:\n {\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n }\n }\n else\n c=ReadBlobByte(image);\n while (isspace((int) ((unsigned char) c)) != 0)\n c=ReadBlobByte(image);\n }\n options=DestroyString(options);\n (void) ReadBlobByte(image);\n /*\n Verify that required image information is defined.\n */\n if ((LocaleCompare(id,\"ImageMagick\") != 0) ||\n (image->storage_class == UndefinedClass) ||\n (image->compression == UndefinedCompression) ||\n (image->colorspace == UndefinedColorspace) ||\n (image->columns == 0) || (image->rows == 0))\n {\n if (image->previous == (Image *) NULL)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n (void) ThrowMagickException(exception,GetMagickModule(),\n CorruptImageError,\"ImproperImageHeader\",\"`%s'\",image->filename);\n break;\n }\n if (image->montage != (char *) NULL)\n {\n register char\n *p;\n\n /*\n Image directory.\n */\n length=MagickPathExtent;\n image->directory=AcquireString((char *) NULL);\n p=image->directory;\n do\n {\n *p='\\0';\n if ((strlen(image->directory)+MagickPathExtent) >= length)\n {\n /*\n Allocate more memory for the image directory.\n */\n length<<=1;\n image->directory=(char *) ResizeQuantumMemory(image->directory,\n length+MagickPathExtent,sizeof(*image->directory));\n if (image->directory == (char *) NULL)\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n p=image->directory+strlen(image->directory);\n }\n c=ReadBlobByte(image);\n *p++=(char) c;\n } while (c != (int) '\\0');\n }\n if (profiles != (LinkedListInfo *) NULL)\n {\n const char\n *name;\n\n const StringInfo\n *profile;\n\n /*\n Read image profiles.\n */\n ResetLinkedListIterator(profiles);\n name=(const char *) GetNextValueInLinkedList(profiles);\n while (name != (const char *) NULL)\n {\n profile=GetImageProfile(image,name);\n if (profile != (StringInfo *) NULL)\n {\n register unsigned char\n *p;\n\n p=GetStringInfoDatum(profile);\n count=ReadBlob(image,GetStringInfoLength(profile),p);\n (void) count;\n }\n name=(const char *) GetNextValueInLinkedList(profiles);\n }\n profiles=DestroyLinkedList(profiles,RelinquishMagickMemory);\n }\n image->depth=GetImageQuantumDepth(image,MagickFalse);\n if (image->storage_class == PseudoClass)\n {\n /*\n Create image colormap.\n */\n status=AcquireImageColormap(image,colors != 0 ? colors : 256,exception);\n if (status == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (colors != 0)\n {\n size_t\n packet_size;\n\n unsigned char\n *colormap;\n\n /*\n Read image colormap from file.\n */\n packet_size=(size_t) (3UL*image->depth/8UL);\n colormap=(unsigned char *) AcquireQuantumMemory(image->colors,\n packet_size*sizeof(*colormap));\n if (colormap == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n count=ReadBlob(image,packet_size*image->colors,colormap);\n p=colormap;\n switch (image->depth)\n {\n default:\n ThrowReaderException(CorruptImageError,\n \"ImageDepthNotSupported\");\n case 8:\n {\n unsigned char\n pixel;\n\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n p=PushCharPixel(p,&pixel);\n image->colormap[i].red=ScaleCharToQuantum(pixel);\n p=PushCharPixel(p,&pixel);\n image->colormap[i].green=ScaleCharToQuantum(pixel);\n p=PushCharPixel(p,&pixel);\n image->colormap[i].blue=ScaleCharToQuantum(pixel);\n }\n break;\n }\n case 16:\n {\n unsigned short\n pixel;\n\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n p=PushShortPixel(MSBEndian,p,&pixel);\n image->colormap[i].red=ScaleShortToQuantum(pixel);\n p=PushShortPixel(MSBEndian,p,&pixel);\n image->colormap[i].green=ScaleShortToQuantum(pixel);\n p=PushShortPixel(MSBEndian,p,&pixel);\n image->colormap[i].blue=ScaleShortToQuantum(pixel);\n }\n break;\n }\n case 32:\n {\n unsigned int\n pixel;\n\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n p=PushLongPixel(MSBEndian,p,&pixel);\n image->colormap[i].red=ScaleLongToQuantum(pixel);\n p=PushLongPixel(MSBEndian,p,&pixel);\n image->colormap[i].green=ScaleLongToQuantum(pixel);\n p=PushLongPixel(MSBEndian,p,&pixel);\n image->colormap[i].blue=ScaleLongToQuantum(pixel);\n }\n break;\n }\n }\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n }\n }\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n /*\n Allocate image pixels.\n */\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (quantum_format != UndefinedQuantumFormat)\n {\n status=SetQuantumFormat(image,quantum_info,quantum_format);\n if (status == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n packet_size=(size_t) (quantum_info->depth/8);\n if (image->storage_class == DirectClass)\n packet_size=(size_t) (3*quantum_info->depth/8);\n if (IsGrayColorspace(image->colorspace) != MagickFalse)\n packet_size=quantum_info->depth/8;\n if (image->alpha_trait != UndefinedPixelTrait)\n packet_size+=quantum_info->depth/8;\n if (image->colorspace == CMYKColorspace)\n packet_size+=quantum_info->depth/8;\n if (image->compression == RLECompression)\n packet_size++;\n compress_extent=MagickMax(MagickMax(BZipMaxExtent(packet_size*\n image->columns),LZMAMaxExtent(packet_size*image->columns)),\n ZipMaxExtent(packet_size*image->columns));\n compress_pixels=(unsigned char *) AcquireQuantumMemory(compress_extent,\n sizeof(*compress_pixels));\n if (compress_pixels == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n /*\n Read image pixels.\n */\n quantum_type=RGBQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n quantum_type=RGBAQuantum;\n if (image->colorspace == CMYKColorspace)\n {\n quantum_type=CMYKQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n quantum_type=CMYKAQuantum;\n }\n if (IsGrayColorspace(image->colorspace) != MagickFalse)\n {\n quantum_type=GrayQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n quantum_type=GrayAlphaQuantum;\n }\n if (image->storage_class == PseudoClass)\n {\n quantum_type=IndexQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n quantum_type=IndexAlphaQuantum;\n }\n status=MagickTrue;\n GetPixelInfo(image,&pixel);\n#if defined(MAGICKCORE_BZLIB_DELEGATE)\n (void) ResetMagickMemory(&bzip_info,0,sizeof(bzip_info));\n#endif\n#if defined(MAGICKCORE_LZMA_DELEGATE)\n (void) ResetMagickMemory(&allocator,0,sizeof(allocator));\n#endif\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n (void) ResetMagickMemory(&zip_info,0,sizeof(zip_info));\n#endif\n switch (image->compression)\n {\n#if defined(MAGICKCORE_BZLIB_DELEGATE)\n case BZipCompression:\n {\n int\n code;\n\n bzip_info.bzalloc=AcquireBZIPMemory;\n bzip_info.bzfree=RelinquishBZIPMemory;\n bzip_info.opaque=(void *) NULL;\n code=BZ2_bzDecompressInit(&bzip_info,(int) image_info->verbose,\n MagickFalse);\n if (code != BZ_OK)\n status=MagickFalse;\n break;\n }\n#endif\n#if defined(MAGICKCORE_LZMA_DELEGATE)\n case LZMACompression:\n {\n int\n code;\n\n allocator.alloc=AcquireLZMAMemory;\n allocator.free=RelinquishLZMAMemory;\n lzma_info=initialize_lzma;\n lzma_info.allocator=(&allocator);\n code=lzma_auto_decoder(&lzma_info,-1,0);\n if (code != LZMA_OK)\n status=MagickFalse;\n break;\n }\n#endif\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n case LZWCompression:\n case ZipCompression:\n {\n int\n code;\n\n zip_info.zalloc=AcquireZIPMemory;\n zip_info.zfree=RelinquishZIPMemory;\n zip_info.opaque=(voidpf) NULL;\n code=inflateInit(&zip_info);\n if (code != Z_OK)\n status=MagickFalse;\n break;\n }\n#endif\n case RLECompression:\n break;\n default:\n break;\n }\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n length=0;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register ssize_t\n x;\n\n register Quantum\n *magick_restrict q;\n\n if (status == MagickFalse)\n break;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n switch (image->compression)\n {\n#if defined(MAGICKCORE_BZLIB_DELEGATE)\n case BZipCompression:\n {\n bzip_info.next_out=(char *) pixels;\n bzip_info.avail_out=(unsigned int) (packet_size*image->columns);\n do\n {\n int\n code;\n\n if (bzip_info.avail_in == 0)\n {\n bzip_info.next_in=(char *) compress_pixels;\n length=(size_t) BZipMaxExtent(packet_size*image->columns);\n if (version != 0.0)\n length=(size_t) ReadBlobMSBLong(image);\n if (length > compress_extent)\n {\n (void) BZ2_bzDecompressEnd(&bzip_info);\n ThrowReaderException(CorruptImageError,\n \"UnableToReadImageData\");\n }\n bzip_info.avail_in=(unsigned int) ReadBlob(image,length,\n (unsigned char *) bzip_info.next_in);\n }\n code=BZ2_bzDecompress(&bzip_info);\n if (code < 0)\n {\n status=MagickFalse;\n break;\n }\n if (code == BZ_STREAM_END)\n break;\n } while (bzip_info.avail_out != 0);\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n break;\n }\n#endif\n#if defined(MAGICKCORE_LZMA_DELEGATE)\n case LZMACompression:\n {\n lzma_info.next_out=pixels;\n lzma_info.avail_out=packet_size*image->columns;\n do\n {\n int\n code;\n\n if (lzma_info.avail_in == 0)\n {\n lzma_info.next_in=compress_pixels;\n length=(size_t) ReadBlobMSBLong(image);\n if (length > compress_extent)\n {\n lzma_end(&lzma_info);\n ThrowReaderException(CorruptImageError,\n \"UnableToReadImageData\");\n }\n lzma_info.avail_in=(unsigned int) ReadBlob(image,length,\n (unsigned char *) lzma_info.next_in);\n }\n code=lzma_code(&lzma_info,LZMA_RUN);\n if (code < 0)\n {\n status=MagickFalse;\n break;\n }\n if (code == LZMA_STREAM_END)\n break;\n } while (lzma_info.avail_out != 0);\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n break;\n }\n#endif\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n case LZWCompression:\n case ZipCompression:\n {\n zip_info.next_out=pixels;\n zip_info.avail_out=(uInt) (packet_size*image->columns);\n do\n {\n int\n code;\n\n if (zip_info.avail_in == 0)\n {\n zip_info.next_in=compress_pixels;\n length=(size_t) ZipMaxExtent(packet_size*image->columns);\n if (version != 0.0)\n length=(size_t) ReadBlobMSBLong(image);\n if (length > compress_extent)\n {\n (void) inflateEnd(&zip_info);\n ThrowReaderException(CorruptImageError,\n \"UnableToReadImageData\");\n }\n zip_info.avail_in=(unsigned int) ReadBlob(image,length,\n zip_info.next_in);\n }\n code=inflate(&zip_info,Z_SYNC_FLUSH);\n if (code < 0)\n {\n status=MagickFalse;\n break;\n }\n if (code == Z_STREAM_END)\n break;\n } while (zip_info.avail_out != 0);\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n break;\n }\n#endif\n case RLECompression:\n {\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (length == 0)\n {\n count=ReadBlob(image,packet_size,pixels);\n PushRunlengthPacket(image,pixels,&length,&pixel,exception);\n }\n length--;\n if (image->storage_class == PseudoClass)\n SetPixelIndex(image,ClampToQuantum(pixel.index),q);\n else\n {\n SetPixelRed(image,ClampToQuantum(pixel.red),q);\n SetPixelGreen(image,ClampToQuantum(pixel.green),q);\n SetPixelBlue(image,ClampToQuantum(pixel.blue),q);\n if (image->colorspace == CMYKColorspace)\n SetPixelBlack(image,ClampToQuantum(pixel.black),q);\n }\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);\n q+=GetPixelChannels(image);\n }\n break;\n }\n default:\n {\n count=ReadBlob(image,packet_size*image->columns,pixels);\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n break;\n }\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n SetQuantumImageType(image,quantum_type);\n switch (image->compression)\n {\n#if defined(MAGICKCORE_BZLIB_DELEGATE)\n case BZipCompression:\n {\n int\n code;\n\n if (version == 0.0)\n {\n MagickOffsetType\n offset;\n\n offset=SeekBlob(image,-((MagickOffsetType)\n bzip_info.avail_in),SEEK_CUR);\n if (offset < 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n code=BZ2_bzDecompressEnd(&bzip_info);\n if (code != BZ_OK)\n status=MagickFalse;\n break;\n }\n#endif\n#if defined(MAGICKCORE_LZMA_DELEGATE)\n case LZMACompression:\n {\n int\n code;\n\n code=lzma_code(&lzma_info,LZMA_FINISH);\n if ((code != LZMA_STREAM_END) && (code != LZMA_OK))\n status=MagickFalse;\n lzma_end(&lzma_info);\n break;\n }\n#endif\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n case LZWCompression:\n case ZipCompression:\n {\n int\n code;\n\n if (version == 0.0)\n {\n MagickOffsetType\n offset;\n\n offset=SeekBlob(image,-((MagickOffsetType) zip_info.avail_in),\n SEEK_CUR);\n if (offset < 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n code=inflateEnd(&zip_info);\n if (code != LZMA_OK)\n status=MagickFalse;\n break;\n }\n#endif\n default:\n break;\n }\n quantum_info=DestroyQuantumInfo(quantum_info);\n compress_pixels=(unsigned char *) RelinquishMagickMemory(compress_pixels);\n if (((y != (ssize_t) image->rows)) || (status == MagickFalse))\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n do\n {\n c=ReadBlobByte(image);\n } while ((isgraph(c) == MagickFalse) && (c != EOF));\n if (c != EOF)\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n } while (c != EOF);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/500'" }, { "text": "[INST] Given the following code containing errors, provide Common 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 uint32_t skip_virt(TType type) { return ::apache::thrift::protocol::skip(*this, type); } ; 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_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock)\n{\n struct grub_ext2_data *data = node->data;\n struct grub_ext2_inode *inode = &node->inode;\n grub_disk_addr_t blknr = -1;\n unsigned int blksz = EXT2_BLOCK_SIZE (data);\n int log2_blksz = LOG2_EXT2_BLOCK_SIZE (data);\n\n if (inode->flags & grub_cpu_to_le32_compile_time (EXT4_EXTENTS_FLAG))\n {\n GRUB_PROPERLY_ALIGNED_ARRAY (buf, EXT2_BLOCK_SIZE(data));\n struct grub_ext4_extent_header *leaf;\n struct grub_ext4_extent *ext;\n int i;\n\n leaf = grub_ext4_find_leaf (data, buf,\n (struct grub_ext4_extent_header *) inode->blocks.dir_blocks,\n fileblock);\n if (! leaf)\n {\n grub_error (GRUB_ERR_BAD_FS, \"invalid extent\");\n return -1;\n }\n\n ext = (struct grub_ext4_extent *) (leaf + 1);\n for (i = 0; i < grub_le_to_cpu16 (leaf->entries); i++)\n {\n if (fileblock < grub_le_to_cpu32 (ext[i].block))\n break;\n }\n\n if (--i >= 0)\n {\n fileblock -= grub_le_to_cpu32 (ext[i].block);\n if (fileblock >= grub_le_to_cpu16 (ext[i].len))\n return 0;\n else\n {\n grub_disk_addr_t start;\n\n start = grub_le_to_cpu16 (ext[i].start_hi);\n start = (start << 32) + grub_le_to_cpu32 (ext[i].start);\n\n return fileblock + start;\n }\n }\n else\n {\n grub_error (GRUB_ERR_BAD_FS, \"something wrong with extent\");\n return -1;\n }\n }\n /* Direct blocks. */\n if (fileblock < INDIRECT_BLOCKS)\n blknr = grub_le_to_cpu32 (inode->blocks.dir_blocks[fileblock]);\n /* Indirect. */\n else if (fileblock < INDIRECT_BLOCKS + blksz / 4)\n {\n grub_uint32_t indir[blksz / 4];\n\n if (grub_disk_read (data->disk,\n\t\t\t ((grub_disk_addr_t)\n\t\t\t grub_le_to_cpu32 (inode->blocks.indir_block))\n\t\t\t << log2_blksz,\n\t\t\t 0, blksz, indir))\n\treturn grub_errno;\n\n blknr = grub_le_to_cpu32 (indir[fileblock - INDIRECT_BLOCKS]);\n }\n /* Double indirect. */\n else if (fileblock < INDIRECT_BLOCKS\n\t + blksz / 4 * ((grub_disk_addr_t) blksz / 4 + 1))\n {\n int log_perblock = log2_blksz + 9 - 2;\n grub_disk_addr_t rblock = fileblock - (INDIRECT_BLOCKS\n\t\t\t\t\t + blksz / 4);\n grub_uint32_t indir[blksz / 4];\n\n if (grub_disk_read (data->disk,\n\t\t\t ((grub_disk_addr_t)\n\t\t\t grub_le_to_cpu32 (inode->blocks.double_indir_block))\n\t\t\t << log2_blksz,\n\t\t\t 0, blksz, indir))\n\treturn grub_errno;\n\n if (grub_disk_read (data->disk,\n\t\t\t ((grub_disk_addr_t)\n\t\t\t grub_le_to_cpu32 (indir[rblock >> log_perblock]))\n\t\t\t << log2_blksz,\n\t\t\t 0, blksz, indir))\n\treturn grub_errno;\n\n\n blknr = grub_le_to_cpu32 (indir[rblock & ((1 << log_perblock) - 1)]);\n }\n /* triple indirect. */\n else if (fileblock < INDIRECT_BLOCKS + blksz / 4 * ((grub_disk_addr_t) blksz / 4 + 1)\n\t + ((grub_disk_addr_t) blksz / 4) * ((grub_disk_addr_t) blksz / 4)\n\t * ((grub_disk_addr_t) blksz / 4 + 1))\n {\n int log_perblock = log2_blksz + 9 - 2;\n grub_disk_addr_t rblock = fileblock - (INDIRECT_BLOCKS + blksz / 4\n\t\t\t\t\t * (blksz / 4 + 1));\n grub_uint32_t indir[blksz / 4];\n\n if (grub_disk_read (data->disk,\n\t\t\t ((grub_disk_addr_t)\n\t\t\t grub_le_to_cpu32 (inode->blocks.triple_indir_block))\n\t\t\t << log2_blksz,\n\t\t\t 0, blksz, indir))\n\treturn grub_errno;\n\n if (grub_disk_read (data->disk,\n\t\t\t ((grub_disk_addr_t)\n\t\t\t grub_le_to_cpu32 (indir[(rblock >> log_perblock) >> log_perblock]))\n\t\t\t << log2_blksz,\n\t\t\t 0, blksz, indir))\n\treturn grub_errno;\n\n if (grub_disk_read (data->disk,\n\t\t\t ((grub_disk_addr_t)\n\t\t\t grub_le_to_cpu32 (indir[(rblock >> log_perblock) & ((1 << log_perblock) - 1)]))\n\t\t\t << log2_blksz,\n\t\t\t 0, blksz, indir))\n\treturn grub_errno;\n\n blknr = grub_le_to_cpu32 (indir[rblock & ((1 << log_perblock) - 1)]);\n }\n else\n {\n grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,\n\t\t \"ext2fs doesn't support quadruple indirect blocks\");\n }\n\n return blknr;\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: _gcry_mpi_powm (gcry_mpi_t res,\n gcry_mpi_t base, gcry_mpi_t expo, gcry_mpi_t mod)\n{\n /* Pointer to the limbs of the arguments, their size and signs. */\n mpi_ptr_t rp, ep, mp, bp;\n mpi_size_t esize, msize, bsize, rsize;\n int msign, bsign, rsign;\n /* Flags telling the secure allocation status of the arguments. */\n int esec, msec, bsec;\n /* Size of the result including space for temporary values. */\n mpi_size_t size;\n /* Helper. */\n int mod_shift_cnt;\n int negative_result;\n mpi_ptr_t mp_marker = NULL;\n mpi_ptr_t bp_marker = NULL;\n mpi_ptr_t ep_marker = NULL;\n mpi_ptr_t xp_marker = NULL;\n unsigned int mp_nlimbs = 0;\n unsigned int bp_nlimbs = 0;\n unsigned int ep_nlimbs = 0;\n unsigned int xp_nlimbs = 0;\n mpi_ptr_t precomp[SIZE_PRECOMP]; /* Pre-computed array: BASE^1, ^3, ^5, ... */\n mpi_size_t precomp_size[SIZE_PRECOMP];\n mpi_size_t W;\n mpi_ptr_t base_u;\n mpi_size_t base_u_size;\n mpi_size_t max_u_size;\n\n esize = expo->nlimbs;\n msize = mod->nlimbs;\n size = 2 * msize;\n msign = mod->sign;\n\n ep = expo->d;\n MPN_NORMALIZE(ep, esize);\n\n if (esize * BITS_PER_MPI_LIMB > 512)\n W = 5;\n else if (esize * BITS_PER_MPI_LIMB > 256)\n W = 4;\n else if (esize * BITS_PER_MPI_LIMB > 128)\n W = 3;\n else if (esize * BITS_PER_MPI_LIMB > 64)\n W = 2;\n else\n W = 1;\n\n esec = mpi_is_secure(expo);\n msec = mpi_is_secure(mod);\n bsec = mpi_is_secure(base);\n\n rp = res->d;\n\n if (!msize)\n _gcry_divide_by_zero();\n\n if (!esize)\n {\n /* Exponent is zero, result is 1 mod MOD, i.e., 1 or 0 depending\n on if MOD equals 1. */\n res->nlimbs = (msize == 1 && mod->d[0] == 1) ? 0 : 1;\n if (res->nlimbs)\n {\n RESIZE_IF_NEEDED (res, 1);\n rp = res->d;\n rp[0] = 1;\n }\n res->sign = 0;\n goto leave;\n }\n\n /* Normalize MOD (i.e. make its most significant bit set) as\n required by mpn_divrem. This will make the intermediate values\n in the calculation slightly larger, but the correct result is\n obtained after a final reduction using the original MOD value. */\n mp_nlimbs = msec? msize:0;\n mp = mp_marker = mpi_alloc_limb_space(msize, msec);\n count_leading_zeros (mod_shift_cnt, mod->d[msize-1]);\n if (mod_shift_cnt)\n _gcry_mpih_lshift (mp, mod->d, msize, mod_shift_cnt);\n else\n MPN_COPY( mp, mod->d, msize );\n\n bsize = base->nlimbs;\n bsign = base->sign;\n if (bsize > msize)\n {\n /* The base is larger than the module. Reduce it.\n\n Allocate (BSIZE + 1) with space for remainder and quotient.\n (The quotient is (bsize - msize + 1) limbs.) */\n bp_nlimbs = bsec ? (bsize + 1):0;\n bp = bp_marker = mpi_alloc_limb_space( bsize + 1, bsec );\n MPN_COPY ( bp, base->d, bsize );\n /* We don't care about the quotient, store it above the\n * remainder, at BP + MSIZE. */\n _gcry_mpih_divrem( bp + msize, 0, bp, bsize, mp, msize );\n bsize = msize;\n /* Canonicalize the base, since we are going to multiply with it\n quite a few times. */\n MPN_NORMALIZE( bp, bsize );\n }\n else\n bp = base->d;\n\n if (!bsize)\n {\n res->nlimbs = 0;\n res->sign = 0;\n goto leave;\n }\n\n\n /* Make BASE, EXPO not overlap with RES. We don't need to check MOD\n because that has already been copied to the MP var. */\n if ( rp == bp )\n {\n /* RES and BASE are identical. Allocate temp. space for BASE. */\n gcry_assert (!bp_marker);\n bp_nlimbs = bsec? bsize:0;\n bp = bp_marker = mpi_alloc_limb_space( bsize, bsec );\n MPN_COPY(bp, rp, bsize);\n }\n if ( rp == ep )\n {\n /* RES and EXPO are identical. Allocate temp. space for EXPO. */\n ep_nlimbs = esec? esize:0;\n ep = ep_marker = mpi_alloc_limb_space( esize, esec );\n MPN_COPY(ep, rp, esize);\n }\n\n /* Copy base to the result. */\n if (res->alloced < size)\n {\n mpi_resize (res, size);\n rp = res->d;\n }\n\n /* Main processing. */\n {\n mpi_size_t i, j, k;\n mpi_ptr_t xp;\n mpi_size_t xsize;\n int c;\n mpi_limb_t e;\n mpi_limb_t carry_limb;\n struct karatsuba_ctx karactx;\n mpi_ptr_t tp;\n\n xp_nlimbs = msec? (2 * (msize + 1)):0;\n xp = xp_marker = mpi_alloc_limb_space( 2 * (msize + 1), msec );\n\n memset( &karactx, 0, sizeof karactx );\n negative_result = (ep[0] & 1) && bsign;\n\n /* Precompute PRECOMP[], BASE^(2 * i + 1), BASE^1, ^3, ^5, ... */\n if (W > 1) /* X := BASE^2 */\n mul_mod (xp, &xsize, bp, bsize, bp, bsize, mp, msize, &karactx);\n base_u = precomp[0] = mpi_alloc_limb_space (bsize, esec);\n base_u_size = max_u_size = precomp_size[0] = bsize;\n MPN_COPY (precomp[0], bp, bsize);\n for (i = 1; i < (1 << (W - 1)); i++)\n { /* PRECOMP[i] = BASE^(2 * i + 1) */\n if (xsize >= base_u_size)\n mul_mod (rp, &rsize, xp, xsize, base_u, base_u_size,\n mp, msize, &karactx);\n else\n mul_mod (rp, &rsize, base_u, base_u_size, xp, xsize,\n mp, msize, &karactx);\n base_u = precomp[i] = mpi_alloc_limb_space (rsize, esec);\n base_u_size = precomp_size[i] = rsize;\n if (max_u_size < base_u_size)\n max_u_size = base_u_size;\n MPN_COPY (precomp[i], rp, rsize);\n }\n\n base_u = mpi_alloc_limb_space (max_u_size, esec);\n MPN_ZERO (base_u, max_u_size);\n\n i = esize - 1;\n\n /* Main loop.\n\n Make the result be pointed to alternately by XP and RP. This\n helps us avoid block copying, which would otherwise be\n necessary with the overlap restrictions of\n _gcry_mpih_divmod. With 50% probability the result after this\n loop will be in the area originally pointed by RP (==RES->d),\n and with 50% probability in the area originally pointed to by XP. */\n rsign = 0;\n if (W == 1)\n {\n rsize = bsize;\n }\n else\n {\n rsize = msize;\n MPN_ZERO (rp, rsize);\n }\n MPN_COPY ( rp, bp, bsize );\n\n e = ep[i];\n count_leading_zeros (c, e);\n e = (e << c) << 1;\n c = BITS_PER_MPI_LIMB - 1 - c;\n\n j = 0;\n\n for (;;)\n if (e == 0)\n {\n j += c;\n if ( --i < 0 )\n break;\n\n e = ep[i];\n c = BITS_PER_MPI_LIMB;\n }\n else\n {\n int c0;\n mpi_limb_t e0;\n\n count_leading_zeros (c0, e);\n e = (e << c0);\n c -= c0;\n j += c0;\n\n e0 = (e >> (BITS_PER_MPI_LIMB - W));\n if (c >= W)\n c0 = 0;\n else\n {\n if ( --i < 0 )\n {\n e0 = (e >> (BITS_PER_MPI_LIMB - c));\n j += c - W;\n goto last_step;\n }\n else\n {\n c0 = c;\n e = ep[i];\n c = BITS_PER_MPI_LIMB;\n e0 |= (e >> (BITS_PER_MPI_LIMB - (W - c0)));\n }\n }\n\n e = e << (W - c0);\n c -= (W - c0);\n\n last_step:\n count_trailing_zeros (c0, e0);\n e0 = (e0 >> c0) >> 1;\n\n /*\n * base_u <= precomp[e0]\n * base_u_size <= precomp_size[e0]\n */\n base_u_size = 0;\n for (k = 0; k < (1<< (W - 1)); k++)\n {\n struct gcry_mpi w, u;\n w.alloced = w.nlimbs = precomp_size[k];\n u.alloced = u.nlimbs = precomp_size[k];\n w.sign = u.sign = 0;\n w.flags = u.flags = 0;\n w.d = base_u;\n u.d = precomp[k];\n\n mpi_set_cond (&w, &u, k == e0);\n base_u_size |= ( precomp_size[k] & ((mpi_size_t)0 - (k == e0)) );\n }\n\n for (j += W - c0; j >= 0; j--)\n {\n mul_mod (xp, &xsize, rp, rsize,\n j == 0 ? base_u : rp, j == 0 ? base_u_size : rsize,\n mp, msize, &karactx);\n tp = rp; rp = xp; xp = tp;\n rsize = xsize;\n }\n\n j = c0;\n if ( i < 0 )\n break;\n }\n\n while (j--)\n {\n mul_mod (xp, &xsize, rp, rsize, rp, rsize, mp, msize, &karactx);\n tp = rp; rp = xp; xp = tp;\n rsize = xsize;\n }\n\n /* We shifted MOD, the modulo reduction argument, left\n MOD_SHIFT_CNT steps. Adjust the result by reducing it with the\n original MOD.\n\n Also make sure the result is put in RES->d (where it already\n might be, see above). */\n if ( mod_shift_cnt )\n {\n carry_limb = _gcry_mpih_lshift( res->d, rp, rsize, mod_shift_cnt);\n rp = res->d;\n if ( carry_limb )\n {\n rp[rsize] = carry_limb;\n rsize++;\n }\n }\n else if (res->d != rp)\n {\n MPN_COPY (res->d, rp, rsize);\n rp = res->d;\n }\n\n if ( rsize >= msize )\n {\n _gcry_mpih_divrem(rp + msize, 0, rp, rsize, mp, msize);\n rsize = msize;\n }\n\n /* Remove any leading zero words from the result. */\n if ( mod_shift_cnt )\n _gcry_mpih_rshift( rp, rp, rsize, mod_shift_cnt);\n MPN_NORMALIZE (rp, rsize);\n\n _gcry_mpih_release_karatsuba_ctx (&karactx );\n for (i = 0; i < (1 << (W - 1)); i++)\n _gcry_mpi_free_limb_space( precomp[i], esec ? precomp_size[i] : 0 );\n _gcry_mpi_free_limb_space (base_u, esec ? max_u_size : 0);\n }\n\n /* Fixup for negative results. */\n if ( negative_result && rsize )\n {\n if ( mod_shift_cnt )\n _gcry_mpih_rshift( mp, mp, msize, mod_shift_cnt);\n _gcry_mpih_sub( rp, mp, msize, rp, rsize);\n rsize = msize;\n rsign = msign;\n MPN_NORMALIZE(rp, rsize);\n }\n gcry_assert (res->d == rp);\n res->nlimbs = rsize;\n res->sign = rsign;\n\n leave:\n if (mp_marker)\n _gcry_mpi_free_limb_space( mp_marker, mp_nlimbs );\n if (bp_marker)\n _gcry_mpi_free_limb_space( bp_marker, bp_nlimbs );\n if (ep_marker)\n _gcry_mpi_free_limb_space( ep_marker, ep_nlimbs );\n if (xp_marker)\n _gcry_mpi_free_limb_space( xp_marker, xp_nlimbs );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Same computation for square and multiply.\n\n* mpi/mpi-pow.c (_gcry_mpi_powm): Compare msize for max_u_size. Move\nthe assignment to base_u into the loop. Copy content refered by RP to\nBASE_U except the last of the loop.\n\n--\n\nSigned-off-by: NIIBE Yutaka '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: fetch_token(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\t 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_BOUND;\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_NOT_WORD_BOUND;\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 '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 'x':\n if (PEND) break;\n\n prev = p;\n if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) {\n PINC;\n num = scan_unsigned_hexadecimal_number(&p, end, 8, enc);\n if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE;\n if (!PEND) {\n if (ONIGENC_IS_CODE_XDIGIT(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, 2, enc);\n if (num < 0) return ONIGERR_TOO_BIG_NUMBER;\n if (p == prev) { /* can't read nothing. */\n num = 0; /* but, it's not error */\n }\n tok->type = TK_RAW_BYTE;\n tok->base = 16;\n tok->u.c = num;\n }\n break;\n\n case 'u':\n if (PEND) break;\n\n prev = p;\n if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) {\n num = scan_unsigned_hexadecimal_number(&p, end, 4, enc);\n if (num < 0) return ONIGERR_TOO_BIG_NUMBER;\n if (p == prev) { /* can't read nothing. */\n num = 0; /* but, it's not error */\n }\n tok->type = TK_CODE_POINT;\n tok->base = 16;\n tok->u.code = (OnigCodePoint )num;\n }\n break;\n\n case '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_MEM_NODES(env)[num]))\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) 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#ifdef USE_NAMED_GROUP\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\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);\n if (r == 1) tok->u.backref.exist_level = 1;\n else tok->u.backref.exist_level = 0;\n#else\n r = fetch_name(&p, end, &name_end, env, &back_num, 1);\n#endif\n if (r < 0) return r;\n\n if (back_num != 0) {\n if (back_num < 0) {\n back_num = BACKREF_REL_TO_ABS(back_num, env);\n if (back_num <= 0)\n return ONIGERR_INVALID_BACKREF;\n }\n\n if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) {\n if (back_num > env->num_mem ||\n IS_NULL(SCANENV_MEM_NODES(env)[back_num]))\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_MEM_NODES(env)[backs[i]]))\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#endif\n\n#ifdef USE_SUBEXP_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\n prev = p;\n r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &gnum, 1);\n if (r < 0) return r;\n\n tok->type = TK_CALL;\n tok->u.call.name = prev;\n tok->u.call.name_end = name_end;\n tok->u.call.gnum = gnum;\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\t}\n }\n break;\n }\n }\n else {\n tok->u.c = c;\n tok->escaped = 0;\n\n#ifdef USE_VARIABLE_META_CHARS\n if ((c != ONIG_INEFFECTIVE_META_CHAR) &&\n 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 && PPEEK_IS('#')) {\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 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->option)\n\t\t\t? ANCHOR_BEGIN_BUF : ANCHOR_BEGIN_LINE);\n break;\n\n case '$':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break;\n tok->type = TK_ANCHOR;\n tok->u.subtype = (IS_SINGLELINE(env->option)\n\t\t\t? ANCHOR_SEMI_END_BUF : ANCHOR_END_LINE);\n break;\n\n case '[':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACKET_CC)) break;\n tok->type = TK_CC_OPEN;\n break;\n\n case ']':\n if (*src > env->pattern) /* /].../ is allowed. */\n CLOSE_BRACKET_WITHOUT_ESC_WARN(env, (UChar* )\"]\");\n break;\n\n case '#':\n if (IS_EXTEND(env->option)) {\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->option))\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-787'], 'message': 'fix #55 : Byte value expressed in octal must be smaller than 256'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline void fsnotify_oldname_free(const unsigned char *old_name)\n{\n\tkfree(old_name);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362', 'CWE-399'], 'message': 'dentry name snapshots\n\ntake_dentry_name_snapshot() takes a safe snapshot of dentry name;\nif the name is a short one, it gets copied into caller-supplied\nstructure, otherwise an extra reference to external name is grabbed\n(those are never modified). In either case the pointer to stable\nstring is stored into the same structure.\n\ndentry must be held by the caller of take_dentry_name_snapshot(),\nbut may be freely dropped afterwards - the snapshot will stay\nuntil destroyed by release_dentry_name_snapshot().\n\nIntended use:\n\tstruct name_snapshot s;\n\n\ttake_dentry_name_snapshot(&s, dentry);\n\t...\n\taccess s.name\n\t...\n\trelease_dentry_name_snapshot(&s);\n\nReplaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name\nto pass down with event.\n\nSigned-off-by: Al Viro '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: accept_xsmp_connection (SmsConn sms_conn,\n GsmXsmpServer *server,\n unsigned long *mask_ret,\n SmsCallbacks *callbacks_ret,\n char **failure_reason_ret)\n{\n IceConn ice_conn;\n GsmXSMPClient *client;\n\n /* FIXME: what about during shutdown but before gsm_xsmp_shutdown? */\n if (server->priv->xsmp_sockets == NULL) {\n g_debug (\"GsmXsmpServer: In shutdown, rejecting new client\");\n\n *failure_reason_ret = strdup (_(\"Refusing new client connection because the session is currently being shut down\\n\"));\n return FALSE;\n }\n\n ice_conn = SmsGetIceConnection (sms_conn);\n client = ice_conn->context;\n\n g_return_val_if_fail (client != NULL, TRUE);\n\n gsm_xsmp_client_connect (client, sms_conn, mask_ret, callbacks_ret);\n\n return TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-835'], 'message': '[gsm] Delay the creation of the GsmXSMPClient until it really exists\n\nWe used to create the GsmXSMPClient before the XSMP connection is really\naccepted. This can lead to some issues, though. An example is:\nhttps://bugzilla.gnome.org/show_bug.cgi?id=598211#c19. Quoting:\n\n \"What is happening is that a new client (probably metacity in your\n case) is opening an ICE connection in the GSM_MANAGER_PHASE_END_SESSION\n phase, which causes a new GsmXSMPClient to be added to the client\n store. The GSM_MANAGER_PHASE_EXIT phase then begins before the client\n has had a chance to establish a xsmp connection, which means that\n client->priv->conn will not be initialized at the point that xsmp_stop\n is called on the new unregistered client.\"\n\nThe fix is to create the GsmXSMPClient object when there's a real XSMP\nconnection. This implies moving the timeout that makes sure we don't\nhave an empty client to the XSMP server.\n\nhttps://bugzilla.gnome.org/show_bug.cgi?id=598211'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void acpi_ns_terminate(void)\n{\n\tacpi_status status;\n\n\tACPI_FUNCTION_TRACE(ns_terminate);\n\n#ifdef ACPI_EXEC_APP\n\t{\n\t\tunion acpi_operand_object *prev;\n\t\tunion acpi_operand_object *next;\n\n\t\t/* Delete any module-level code blocks */\n\n\t\tnext = acpi_gbl_module_code_list;\n\t\twhile (next) {\n\t\t\tprev = next;\n\t\t\tnext = next->method.mutex;\n\t\t\tprev->method.mutex = NULL;\t/* Clear the Mutex (cheated) field */\n\t\t\tacpi_ut_remove_reference(prev);\n\t\t}\n\t}\n#endif\n\n\t/*\n\t * Free the entire namespace -- all nodes and all objects\n\t * attached to the nodes\n\t */\n\tacpi_ns_delete_namespace_subtree(acpi_gbl_root_node);\n\n\t/* Delete any objects attached to the root node */\n\n\tstatus = acpi_ut_acquire_mutex(ACPI_MTX_NAMESPACE);\n\tif (ACPI_FAILURE(status)) {\n\t\treturn_VOID;\n\t}\n\n\tacpi_ns_delete_node(acpi_gbl_root_node);\n\t(void)acpi_ut_release_mutex(ACPI_MTX_NAMESPACE);\n\n\tACPI_DEBUG_PRINT((ACPI_DB_INFO, \"Namespace freed\\n\"));\n\treturn_VOID;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-755'], 'message': 'ACPICA: Namespace: fix operand cache leak\n\nACPICA commit a23325b2e583556eae88ed3f764e457786bf4df6\n\nI found some ACPI operand cache leaks in ACPI early abort cases.\n\nBoot log of ACPI operand cache leak is as follows:\n>[ 0.174332] ACPI: Added _OSI(Module Device)\n>[ 0.175504] ACPI: Added _OSI(Processor Device)\n>[ 0.176010] ACPI: Added _OSI(3.0 _SCP Extensions)\n>[ 0.177032] ACPI: Added _OSI(Processor Aggregator Device)\n>[ 0.178284] ACPI: SCI (IRQ16705) allocation failed\n>[ 0.179352] ACPI Exception: AE_NOT_ACQUIRED, Unable to install\nSystem Control Interrupt handler (20160930/evevent-131)\n>[ 0.180008] ACPI: Unable to start the ACPI Interpreter\n>[ 0.181125] ACPI Error: Could not remove SCI handler\n(20160930/evmisc-281)\n>[ 0.184068] kmem_cache_destroy Acpi-Operand: Slab cache still has\nobjects\n>[ 0.185358] CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.10.0-rc3 #2\n>[ 0.186820] Hardware name: innotek gmb_h virtual_box/virtual_box, BIOS\nvirtual_box 12/01/2006\n>[ 0.188000] Call Trace:\n>[ 0.188000] ? dump_stack+0x5c/0x7d\n>[ 0.188000] ? kmem_cache_destroy+0x224/0x230\n>[ 0.188000] ? acpi_sleep_proc_init+0x22/0x22\n>[ 0.188000] ? acpi_os_delete_cache+0xa/0xd\n>[ 0.188000] ? acpi_ut_delete_caches+0x3f/0x7b\n>[ 0.188000] ? acpi_terminate+0x5/0xf\n>[ 0.188000] ? acpi_init+0x288/0x32e\n>[ 0.188000] ? __class_create+0x4c/0x80\n>[ 0.188000] ? video_setup+0x7a/0x7a\n>[ 0.188000] ? do_one_initcall+0x4e/0x1b0\n>[ 0.188000] ? kernel_init_freeable+0x194/0x21a\n>[ 0.188000] ? rest_init+0x80/0x80\n>[ 0.188000] ? kernel_init+0xa/0x100\n>[ 0.188000] ? ret_from_fork+0x25/0x30\n\nWhen early abort is occurred due to invalid ACPI information, Linux kernel\nterminates ACPI by calling acpi_terminate() function. The function calls\nacpi_ns_terminate() function to delete namespace data and ACPI operand cache\n(acpi_gbl_module_code_list).\n\nBut the deletion code in acpi_ns_terminate() function is wrapped in\nACPI_EXEC_APP definition, therefore the code is only executed when the\ndefinition exists. If the define doesn't exist, ACPI operand cache\n(acpi_gbl_module_code_list) is leaked, and stack dump is shown in kernel log.\n\nThis causes a security threat because the old kernel (<= 4.9) shows memory\nlocations of kernel functions in stack dump, therefore kernel ASLR can be\nneutralized.\n\nTo fix ACPI operand leak for enhancing security, I made a patch which\nremoves the ACPI_EXEC_APP define in acpi_ns_terminate() function for\nexecuting the deletion code unconditionally.\n\nLink: https://github.com/acpica/acpica/commit/a23325b2\nSigned-off-by: Seunghun Han \nSigned-off-by: Lv Zheng \nSigned-off-by: Bob Moore \nSigned-off-by: Rafael J. Wysocki '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (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_write(QIOChannel *ioc, const 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_OUT,\n nbd_negotiate_continue,\n qemu_coroutine_self(),\n NULL);\n ret = nbd_write(ioc, buffer, size, NULL);\n g_source_remove(watch);\n return ret;\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: ModuleExport size_t RegisterRLEImage(void)\n{\n MagickInfo\n *entry;\n\n entry=AcquireMagickInfo(\"RLE\",\"RLE\",\"Utah Run length encoded image\");\n entry->decoder=(DecodeImageHandler *) ReadRLEImage;\n entry->magick=(IsImageFormatHandler *) IsRLE;\n entry->flags^=CoderAdjoinFlag;\n (void) RegisterMagickInfo(entry);\n return(MagickImageCoderSignature);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-834'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/518'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: QPDF::resolve(int objid, int generation)\n{\n // Check object cache before checking xref table. This allows us\n // to insert things into the object cache that don't actually\n // exist in the file.\n QPDFObjGen og(objid, generation);\n if (! this->obj_cache.count(og))\n {\n\tif (! this->xref_table.count(og))\n\t{\n\t // PDF spec says unknown objects resolve to the null object.\n\t return new QPDF_Null;\n\t}\n\n\tQPDFXRefEntry const& entry = this->xref_table[og];\n\tswitch (entry.getType())\n\t{\n\t case 1:\n\t {\n\t\tqpdf_offset_t offset = entry.getOffset();\n\t\t// Object stored in cache by readObjectAtOffset\n\t\tint aobjid;\n\t\tint ageneration;\n\t\tQPDFObjectHandle oh =\n\t\t readObjectAtOffset(true, offset, \"\", objid, generation,\n\t\t\t\t aobjid, ageneration);\n\t }\n\t break;\n\n\t case 2:\n\t resolveObjectsInStream(entry.getObjStreamNumber());\n\t break;\n\n\t default:\n\t throw QPDFExc(qpdf_e_damaged_pdf, this->file->getName(), \"\", 0,\n\t\t\t \"object \" +\n\t\t\t QUtil::int_to_string(objid) + \"/\" +\n\t\t\t QUtil::int_to_string(generation) +\n\t\t\t \" has unexpected xref entry type\");\n\t}\n }\n\n return this->obj_cache[og].object;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-835'], 'message': 'Detect recursion loops resolving objects (fixes #51)\n\nDuring parsing of an object, sometimes parts of the object have to be\nresolved. An example is stream lengths. If such an object directly or\nindirectly points to the object being parsed, it can cause an infinite\nloop. Guard against all cases of re-entrant resolution of 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: xps_load_sfnt_name(xps_font_t *font, char *namep)\n{\n byte *namedata;\n int offset, length;\n /*int format;*/\n int count, stringoffset;\n int found;\n int i, k;\n\n found = 0;\n strcpy(namep, \"Unknown\");\n\n offset = xps_find_sfnt_table(font, \"name\", &length);\n if (offset < 0 || length < 6)\n {\n gs_warn(\"cannot find name table\");\n return;\n }\n\n /* validate the offset, and the data for the two\n * values we're about to read\n */\n if (offset + 6 > font->length)\n {\n gs_warn(\"name table byte offset invalid\");\n return;\n }\n namedata = font->data + offset;\n\n /*format = u16(namedata + 0);*/\n count = u16(namedata + 2);\n stringoffset = u16(namedata + 4);\n\n if (stringoffset + offset > font->length\n || offset + 6 + count * 12 > font->length)\n {\n gs_warn(\"name table invalid\");\n return;\n }\n\n if (length < 6 + (count * 12))\n {\n gs_warn(\"name table too short\");\n return;\n }\n\n for (i = 0; i < count; i++)\n {\n byte *record = namedata + 6 + i * 12;\n int pid = u16(record + 0);\n int eid = u16(record + 2);\n int langid = u16(record + 4);\n int nameid = u16(record + 6);\n length = u16(record + 8);\n offset = u16(record + 10);\n\n /* Full font name or postscript name */\n if (nameid == 4 || nameid == 6)\n {\n if (pid == 1 && eid == 0 && langid == 0) /* mac roman, english */\n {\n if (found < 3)\n {\n memcpy(namep, namedata + stringoffset + offset, length);\n namep[length] = 0;\n found = 3;\n }\n }\n\n if (pid == 3 && eid == 1 && langid == 0x409) /* windows unicode ucs-2, US */\n {\n if (found < 2)\n {\n unsigned char *s = namedata + stringoffset + offset;\n int n = length / 2;\n for (k = 0; k < n; k ++)\n {\n int c = u16(s + k * 2);\n namep[k] = isprint(c) ? c : '?';\n }\n namep[k] = 0;\n found = 2;\n }\n }\n\n if (pid == 3 && eid == 10 && langid == 0x409) /* windows unicode ucs-4, US */\n {\n if (found < 1)\n {\n unsigned char *s = namedata + stringoffset + offset;\n int n = length / 4;\n for (k = 0; k < n; k ++)\n {\n int c = u32(s + k * 4);\n namep[k] = isprint(c) ? c : '?';\n }\n namep[k] = 0;\n found = 1;\n }\n }\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Bug 698044: restrict font name length to the buffer size.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: i_alloc_struct_array(gs_memory_t * mem, uint num_elements,\n gs_memory_type_ptr_t pstype, client_name_t cname)\n{\n gs_ref_memory_t * const imem = (gs_ref_memory_t *)mem;\n obj_header_t *obj;\n\n#ifdef MEMENTO\n if (Memento_failThisEvent())\n return NULL;\n#endif\n\n ALLOC_CHECK_SIZE(mem,pstype);\n#ifdef DEBUG\n if (pstype->enum_ptrs == basic_enum_ptrs) {\n dmprintf2(mem, \" i_alloc_struct_array: called with incorrect structure type (not element), struct='%s', client='%s'\\n\",\n pstype->sname, cname);\n return NULL;\t\t/* fail */\n }\n#endif\n obj = alloc_obj(imem,\n (ulong) num_elements * pstype->ssize,\n pstype, ALLOC_DIRECT, cname);\n if_debug7m('A', mem, \"[a%d:+<.]%s %s*(%lu=%u*%u) = 0x%lx\\n\",\n alloc_trace_space(imem), client_name_string(cname),\n struct_type_name_string(pstype),\n (ulong) num_elements * pstype->ssize,\n num_elements, pstype->ssize, (ulong) obj);\n return (char *)obj;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Bug 697985: bounds check the array allocations methods\n\nThe clump allocator has four allocation functions that use 'number of elements'\nand 'size of elements' parameters (rather than a simple 'number of bytes').\n\nThose need specific bounds checking.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Huff_offsetReceive (node_t *node, int *ch, byte *fin, int *offset) {\n\tbloc = *offset;\n\twhile (node && node->symbol == INTERNAL_NODE) {\n\t\tif (get_bit(fin)) {\n\t\t\tnode = node->right;\n\t\t} else {\n\t\t\tnode = node->left;\n\t\t}\n\t}\n\tif (!node) {\n\t\t*ch = 0;\n\t\treturn;\n//\t\tCom_Error(ERR_DROP, \"Illegal tree!\");\n\t}\n\t*ch = node->symbol;\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: SYSCALL_DEFINE2(timerfd_create, int, clockid, int, flags)\n{\n\tint ufd;\n\tstruct timerfd_ctx *ctx;\n\n\t/* Check the TFD_* constants for consistency. */\n\tBUILD_BUG_ON(TFD_CLOEXEC != O_CLOEXEC);\n\tBUILD_BUG_ON(TFD_NONBLOCK != O_NONBLOCK);\n\n\tif ((flags & ~TFD_CREATE_FLAGS) ||\n\t (clockid != CLOCK_MONOTONIC &&\n\t clockid != CLOCK_REALTIME &&\n\t clockid != CLOCK_REALTIME_ALARM &&\n\t clockid != CLOCK_BOOTTIME &&\n\t clockid != CLOCK_BOOTTIME_ALARM))\n\t\treturn -EINVAL;\n\n\tif (!capable(CAP_WAKE_ALARM) &&\n\t (clockid == CLOCK_REALTIME_ALARM ||\n\t clockid == CLOCK_BOOTTIME_ALARM))\n\t\treturn -EPERM;\n\n\tctx = kzalloc(sizeof(*ctx), GFP_KERNEL);\n\tif (!ctx)\n\t\treturn -ENOMEM;\n\n\tinit_waitqueue_head(&ctx->wqh);\n\tctx->clockid = clockid;\n\n\tif (isalarm(ctx))\n\t\talarm_init(&ctx->t.alarm,\n\t\t\t ctx->clockid == CLOCK_REALTIME_ALARM ?\n\t\t\t ALARM_REALTIME : ALARM_BOOTTIME,\n\t\t\t timerfd_alarmproc);\n\telse\n\t\thrtimer_init(&ctx->t.tmr, clockid, HRTIMER_MODE_ABS);\n\n\tctx->moffs = ktime_mono_to_real(0);\n\n\tufd = anon_inode_getfd(\"[timerfd]\", &timerfd_fops, ctx,\n\t\t\t O_RDWR | (flags & TFD_SHARED_FCNTL_FLAGS));\n\tif (ufd < 0)\n\t\tkfree(ctx);\n\n\treturn ufd;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'timerfd: Protect the might cancel mechanism proper\n\nThe handling of the might_cancel queueing is not properly protected, so\nparallel operations on the file descriptor can race with each other and\nlead to list corruptions or use after free.\n\nProtect the context for these operations with a seperate lock.\n\nThe wait queue lock cannot be reused for this because that would create a\nlock inversion scenario vs. the cancel lock. Replacing might_cancel with an\natomic (atomic_t or atomic bit) does not help either because it still can\nrace vs. the actual list operation.\n\nReported-by: Dmitry Vyukov \nSigned-off-by: Thomas Gleixner \nCc: \"linux-fsdevel@vger.kernel.org\"\nCc: syzkaller \nCc: Al Viro \nCc: linux-fsdevel@vger.kernel.org\nLink: http://lkml.kernel.org/r/alpine.DEB.2.20.1701311521430.3457@nanos\nSigned-off-by: Thomas Gleixner '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n char\n cache_filename[MagickPathExtent],\n id[MagickPathExtent],\n keyword[MagickPathExtent],\n *options;\n\n const unsigned char\n *p;\n\n GeometryInfo\n geometry_info;\n\n Image\n *image;\n\n int\n c;\n\n LinkedListInfo\n *profiles;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n offset;\n\n MagickStatusType\n flags;\n\n register ssize_t\n i;\n\n size_t\n depth,\n length;\n\n ssize_t\n count;\n\n StringInfo\n *profile;\n\n unsigned int\n signature;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n (void) CopyMagickString(cache_filename,image->filename,MagickPathExtent);\n AppendImageFormat(\"cache\",cache_filename);\n c=ReadBlobByte(image);\n if (c == EOF)\n {\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n *id='\\0';\n (void) ResetMagickMemory(keyword,0,sizeof(keyword));\n offset=0;\n do\n {\n /*\n Decode image header; header terminates one character beyond a ':'.\n */\n profiles=(LinkedListInfo *) NULL;\n length=MagickPathExtent;\n options=AcquireString((char *) NULL);\n signature=GetMagickSignature((const StringInfo *) NULL);\n image->depth=8;\n image->compression=NoCompression;\n while ((isgraph(c) != MagickFalse) && (c != (int) ':'))\n {\n register char\n *p;\n\n if (c == (int) '{')\n {\n char\n *comment;\n\n /*\n Read comment-- any text between { }.\n */\n length=MagickPathExtent;\n comment=AcquireString((char *) NULL);\n for (p=comment; comment != (char *) NULL; p++)\n {\n c=ReadBlobByte(image);\n if (c == (int) '\\\\')\n c=ReadBlobByte(image);\n else\n if ((c == EOF) || (c == (int) '}'))\n break;\n if ((size_t) (p-comment+1) >= length)\n {\n *p='\\0';\n length<<=1;\n comment=(char *) ResizeQuantumMemory(comment,length+\n MagickPathExtent,sizeof(*comment));\n if (comment == (char *) NULL)\n break;\n p=comment+strlen(comment);\n }\n *p=(char) c;\n }\n if (comment == (char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n *p='\\0';\n (void) SetImageProperty(image,\"comment\",comment,exception);\n comment=DestroyString(comment);\n c=ReadBlobByte(image);\n }\n else\n if (isalnum(c) != MagickFalse)\n {\n /*\n Get the keyword.\n */\n length=MagickPathExtent;\n p=keyword;\n do\n {\n if (c == (int) '=')\n break;\n if ((size_t) (p-keyword) < (MagickPathExtent-1))\n *p++=(char) c;\n c=ReadBlobByte(image);\n } while (c != EOF);\n *p='\\0';\n p=options;\n while (isspace((int) ((unsigned char) c)) != 0)\n c=ReadBlobByte(image);\n if (c == (int) '=')\n {\n /*\n Get the keyword value.\n */\n c=ReadBlobByte(image);\n while ((c != (int) '}') && (c != EOF))\n {\n if ((size_t) (p-options+1) >= length)\n {\n *p='\\0';\n length<<=1;\n options=(char *) ResizeQuantumMemory(options,length+\n MagickPathExtent,sizeof(*options));\n if (options == (char *) NULL)\n break;\n p=options+strlen(options);\n }\n *p++=(char) c;\n c=ReadBlobByte(image);\n if (c == '\\\\')\n {\n c=ReadBlobByte(image);\n if (c == (int) '}')\n {\n *p++=(char) c;\n c=ReadBlobByte(image);\n }\n }\n if (*options != '{')\n if (isspace((int) ((unsigned char) c)) != 0)\n break;\n }\n if (options == (char *) NULL)\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n *p='\\0';\n if (*options == '{')\n (void) CopyMagickString(options,options+1,strlen(options));\n /*\n Assign a value to the specified keyword.\n */\n switch (*keyword)\n {\n case 'a':\n case 'A':\n {\n if (LocaleCompare(keyword,\"alpha-trait\") == 0)\n {\n ssize_t\n alpha_trait;\n\n alpha_trait=ParseCommandOption(MagickPixelTraitOptions,\n MagickFalse,options);\n if (alpha_trait < 0)\n break;\n image->alpha_trait=(PixelTrait) alpha_trait;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'b':\n case 'B':\n {\n if (LocaleCompare(keyword,\"background-color\") == 0)\n {\n (void) QueryColorCompliance(options,AllCompliance,\n &image->background_color,exception);\n break;\n }\n if (LocaleCompare(keyword,\"blue-primary\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->chromaticity.blue_primary.x=geometry_info.rho;\n image->chromaticity.blue_primary.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->chromaticity.blue_primary.y=\n image->chromaticity.blue_primary.x;\n break;\n }\n if (LocaleCompare(keyword,\"border-color\") == 0)\n {\n (void) QueryColorCompliance(options,AllCompliance,\n &image->border_color,exception);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'c':\n case 'C':\n {\n if (LocaleCompare(keyword,\"class\") == 0)\n {\n ssize_t\n storage_class;\n\n storage_class=ParseCommandOption(MagickClassOptions,\n MagickFalse,options);\n if (storage_class < 0)\n break;\n image->storage_class=(ClassType) storage_class;\n break;\n }\n if (LocaleCompare(keyword,\"colors\") == 0)\n {\n image->colors=StringToUnsignedLong(options);\n break;\n }\n if (LocaleCompare(keyword,\"colorspace\") == 0)\n {\n ssize_t\n colorspace;\n\n colorspace=ParseCommandOption(MagickColorspaceOptions,\n MagickFalse,options);\n if (colorspace < 0)\n break;\n image->colorspace=(ColorspaceType) colorspace;\n break;\n }\n if (LocaleCompare(keyword,\"compression\") == 0)\n {\n ssize_t\n compression;\n\n compression=ParseCommandOption(MagickCompressOptions,\n MagickFalse,options);\n if (compression < 0)\n break;\n image->compression=(CompressionType) compression;\n break;\n }\n if (LocaleCompare(keyword,\"columns\") == 0)\n {\n image->columns=StringToUnsignedLong(options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'd':\n case 'D':\n {\n if (LocaleCompare(keyword,\"delay\") == 0)\n {\n image->delay=StringToUnsignedLong(options);\n break;\n }\n if (LocaleCompare(keyword,\"depth\") == 0)\n {\n image->depth=StringToUnsignedLong(options);\n break;\n }\n if (LocaleCompare(keyword,\"dispose\") == 0)\n {\n ssize_t\n dispose;\n\n dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse,\n options);\n if (dispose < 0)\n break;\n image->dispose=(DisposeType) dispose;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'e':\n case 'E':\n {\n if (LocaleCompare(keyword,\"endian\") == 0)\n {\n ssize_t\n endian;\n\n endian=ParseCommandOption(MagickEndianOptions,MagickFalse,\n options);\n if (endian < 0)\n break;\n image->endian=(EndianType) endian;\n break;\n }\n if (LocaleCompare(keyword,\"error\") == 0)\n {\n image->error.mean_error_per_pixel=StringToDouble(options,\n (char **) NULL);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'g':\n case 'G':\n {\n if (LocaleCompare(keyword,\"gamma\") == 0)\n {\n image->gamma=StringToDouble(options,(char **) NULL);\n break;\n }\n if (LocaleCompare(keyword,\"green-primary\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->chromaticity.green_primary.x=geometry_info.rho;\n image->chromaticity.green_primary.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->chromaticity.green_primary.y=\n image->chromaticity.green_primary.x;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'i':\n case 'I':\n {\n if (LocaleCompare(keyword,\"id\") == 0)\n {\n (void) CopyMagickString(id,options,MagickPathExtent);\n break;\n }\n if (LocaleCompare(keyword,\"iterations\") == 0)\n {\n image->iterations=StringToUnsignedLong(options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'm':\n case 'M':\n {\n if (LocaleCompare(keyword,\"magick-signature\") == 0)\n {\n signature=(unsigned int) StringToUnsignedLong(options);\n break;\n }\n if (LocaleCompare(keyword,\"mattecolor\") == 0)\n {\n (void) QueryColorCompliance(options,AllCompliance,\n &image->matte_color,exception);\n break;\n }\n if (LocaleCompare(keyword,\"maximum-error\") == 0)\n {\n image->error.normalized_maximum_error=StringToDouble(\n options,(char **) NULL);\n break;\n }\n if (LocaleCompare(keyword,\"mean-error\") == 0)\n {\n image->error.normalized_mean_error=StringToDouble(options,\n (char **) NULL);\n break;\n }\n if (LocaleCompare(keyword,\"montage\") == 0)\n {\n (void) CloneString(&image->montage,options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'n':\n case 'N':\n {\n if (LocaleCompare(keyword,\"number-channels\") == 0)\n {\n image->number_channels=StringToUnsignedLong(options);\n break;\n }\n if (LocaleCompare(keyword,\"number-meta-channels\") == 0)\n {\n image->number_meta_channels=StringToUnsignedLong(options);\n if (image->number_meta_channels > MaxPixelChannels)\n ThrowReaderException(CorruptImageError,\n \"ImproperImageHeader\");\n break;\n }\n break;\n }\n case 'o':\n case 'O':\n {\n if (LocaleCompare(keyword,\"orientation\") == 0)\n {\n ssize_t\n orientation;\n\n orientation=ParseCommandOption(MagickOrientationOptions,\n MagickFalse,options);\n if (orientation < 0)\n break;\n image->orientation=(OrientationType) orientation;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'p':\n case 'P':\n {\n if (LocaleCompare(keyword,\"page\") == 0)\n {\n char\n *geometry;\n\n geometry=GetPageGeometry(options);\n (void) ParseAbsoluteGeometry(geometry,&image->page);\n geometry=DestroyString(geometry);\n break;\n }\n if (LocaleCompare(keyword,\"pixel-intensity\") == 0)\n {\n ssize_t\n intensity;\n\n intensity=ParseCommandOption(MagickPixelIntensityOptions,\n MagickFalse,options);\n if (intensity < 0)\n break;\n image->intensity=(PixelIntensityMethod) intensity;\n break;\n }\n if ((LocaleNCompare(keyword,\"profile:\",8) == 0) ||\n (LocaleNCompare(keyword,\"profile-\",8) == 0))\n {\n if (profiles == (LinkedListInfo *) NULL)\n profiles=NewLinkedList(0);\n (void) AppendValueToLinkedList(profiles,\n AcquireString(keyword+8));\n profile=BlobToStringInfo((const void *) NULL,(size_t)\n StringToLong(options));\n if (profile == (StringInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n (void) SetImageProfile(image,keyword+8,profile,exception);\n profile=DestroyStringInfo(profile);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'q':\n case 'Q':\n {\n if (LocaleCompare(keyword,\"quality\") == 0)\n {\n image->quality=StringToUnsignedLong(options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'r':\n case 'R':\n {\n if (LocaleCompare(keyword,\"red-primary\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->chromaticity.red_primary.x=geometry_info.rho;\n if ((flags & SigmaValue) != 0)\n image->chromaticity.red_primary.y=geometry_info.sigma;\n break;\n }\n if (LocaleCompare(keyword,\"rendering-intent\") == 0)\n {\n ssize_t\n rendering_intent;\n\n rendering_intent=ParseCommandOption(MagickIntentOptions,\n MagickFalse,options);\n if (rendering_intent < 0)\n break;\n image->rendering_intent=(RenderingIntent) rendering_intent;\n break;\n }\n if (LocaleCompare(keyword,\"resolution\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->resolution.x=geometry_info.rho;\n image->resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->resolution.y=image->resolution.x;\n break;\n }\n if (LocaleCompare(keyword,\"rows\") == 0)\n {\n image->rows=StringToUnsignedLong(options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 's':\n case 'S':\n {\n if (LocaleCompare(keyword,\"scene\") == 0)\n {\n image->scene=StringToUnsignedLong(options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 't':\n case 'T':\n {\n if (LocaleCompare(keyword,\"ticks-per-second\") == 0)\n {\n image->ticks_per_second=(ssize_t) StringToLong(options);\n break;\n }\n if (LocaleCompare(keyword,\"tile-offset\") == 0)\n {\n char\n *geometry;\n\n geometry=GetPageGeometry(options);\n (void) ParseAbsoluteGeometry(geometry,&image->tile_offset);\n geometry=DestroyString(geometry);\n }\n if (LocaleCompare(keyword,\"type\") == 0)\n {\n ssize_t\n type;\n\n type=ParseCommandOption(MagickTypeOptions,MagickFalse,\n options);\n if (type < 0)\n break;\n image->type=(ImageType) type;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'u':\n case 'U':\n {\n if (LocaleCompare(keyword,\"units\") == 0)\n {\n ssize_t\n units;\n\n units=ParseCommandOption(MagickResolutionOptions,\n MagickFalse,options);\n if (units < 0)\n break;\n image->units=(ResolutionType) units;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'w':\n case 'W':\n {\n if (LocaleCompare(keyword,\"white-point\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->chromaticity.white_point.x=geometry_info.rho;\n image->chromaticity.white_point.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->chromaticity.white_point.y=\n image->chromaticity.white_point.x;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n default:\n {\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n }\n }\n else\n c=ReadBlobByte(image);\n while (isspace((int) ((unsigned char) c)) != 0)\n c=ReadBlobByte(image);\n }\n options=DestroyString(options);\n (void) ReadBlobByte(image);\n /*\n Verify that required image information is defined.\n */\n if ((LocaleCompare(id,\"MagickCache\") != 0) ||\n (image->storage_class == UndefinedClass) ||\n (image->compression == UndefinedCompression) || (image->columns == 0) ||\n (image->rows == 0))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (signature != GetMagickSignature((const StringInfo *) NULL))\n ThrowReaderException(CacheError,\"IncompatibleAPI\");\n if (image->montage != (char *) NULL)\n {\n register char\n *p;\n\n /*\n Image directory.\n */\n length=MagickPathExtent;\n image->directory=AcquireString((char *) NULL);\n p=image->directory;\n do\n {\n *p='\\0';\n if ((strlen(image->directory)+MagickPathExtent) >= length)\n {\n /*\n Allocate more memory for the image directory.\n */\n length<<=1;\n image->directory=(char *) ResizeQuantumMemory(image->directory,\n length+MagickPathExtent,sizeof(*image->directory));\n if (image->directory == (char *) NULL)\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n p=image->directory+strlen(image->directory);\n }\n c=ReadBlobByte(image);\n *p++=(char) c;\n } while (c != (int) '\\0');\n }\n if (profiles != (LinkedListInfo *) NULL)\n {\n const char\n *name;\n\n const StringInfo\n *profile;\n\n register unsigned char\n *p;\n\n /*\n Read image profiles.\n */\n ResetLinkedListIterator(profiles);\n name=(const char *) GetNextValueInLinkedList(profiles);\n while (name != (const char *) NULL)\n {\n profile=GetImageProfile(image,name);\n if (profile != (StringInfo *) NULL)\n {\n p=GetStringInfoDatum(profile);\n count=ReadBlob(image,GetStringInfoLength(profile),p);\n }\n name=(const char *) GetNextValueInLinkedList(profiles);\n }\n profiles=DestroyLinkedList(profiles,RelinquishMagickMemory);\n }\n depth=GetImageQuantumDepth(image,MagickFalse);\n if (image->storage_class == PseudoClass)\n {\n /*\n Create image colormap.\n */\n image->colormap=(PixelInfo *) AcquireQuantumMemory(image->colors+1,\n sizeof(*image->colormap));\n if (image->colormap == (PixelInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (image->colors != 0)\n {\n size_t\n packet_size;\n\n unsigned char\n *colormap;\n\n /*\n Read image colormap from file.\n */\n packet_size=(size_t) (3UL*depth/8UL);\n colormap=(unsigned char *) AcquireQuantumMemory(image->colors,\n packet_size*sizeof(*colormap));\n if (colormap == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n count=ReadBlob(image,packet_size*image->colors,colormap);\n if (count != (ssize_t) (packet_size*image->colors))\n {\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n ThrowReaderException(CorruptImageError,\n \"InsufficientImageDataInFile\");\n }\n p=colormap;\n switch (depth)\n {\n default:\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n ThrowReaderException(CorruptImageError,\n \"ImageDepthNotSupported\");\n case 8:\n {\n unsigned char\n pixel;\n\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n p=PushCharPixel(p,&pixel);\n image->colormap[i].red=ScaleCharToQuantum(pixel);\n p=PushCharPixel(p,&pixel);\n image->colormap[i].green=ScaleCharToQuantum(pixel);\n p=PushCharPixel(p,&pixel);\n image->colormap[i].blue=ScaleCharToQuantum(pixel);\n }\n break;\n }\n case 16:\n {\n unsigned short\n pixel;\n\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n p=PushShortPixel(MSBEndian,p,&pixel);\n image->colormap[i].red=ScaleShortToQuantum(pixel);\n p=PushShortPixel(MSBEndian,p,&pixel);\n image->colormap[i].green=ScaleShortToQuantum(pixel);\n p=PushShortPixel(MSBEndian,p,&pixel);\n image->colormap[i].blue=ScaleShortToQuantum(pixel);\n }\n break;\n }\n case 32:\n {\n unsigned int\n pixel;\n\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n p=PushLongPixel(MSBEndian,p,&pixel);\n image->colormap[i].red=ScaleLongToQuantum(pixel);\n p=PushLongPixel(MSBEndian,p,&pixel);\n image->colormap[i].green=ScaleLongToQuantum(pixel);\n p=PushLongPixel(MSBEndian,p,&pixel);\n image->colormap[i].blue=ScaleLongToQuantum(pixel);\n }\n break;\n }\n }\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n }\n }\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) ||\n (AcquireMagickResource(HeightResource,image->rows) == MagickFalse))\n ThrowReaderException(ImageError,\"WidthOrHeightExceedsLimit\");\n /*\n Attach persistent pixel cache.\n */\n status=PersistPixelCache(image,cache_filename,MagickTrue,&offset,exception);\n if (status == MagickFalse)\n ThrowReaderException(CacheError,\"UnableToPersistPixelCache\");\n /*\n Proceed to next image.\n */\n do\n {\n c=ReadBlobByte(image);\n } while ((isgraph(c) == MagickFalse) && (c != EOF));\n if (c != EOF)\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n } while (c != EOF);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-770'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/546'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: setup_arch (char **cmdline_p)\n{\n\tunw_init();\n\n\tia64_patch_vtop((u64) __start___vtop_patchlist, (u64) __end___vtop_patchlist);\n\n\t*cmdline_p = __va(ia64_boot_param->command_line);\n\tstrlcpy(boot_command_line, *cmdline_p, COMMAND_LINE_SIZE);\n\n\tefi_init();\n\tio_port_init();\n\n#ifdef CONFIG_IA64_GENERIC\n\t/* machvec needs to be parsed from the command line\n\t * before parse_early_param() is called to ensure\n\t * that ia64_mv is initialised before any command line\n\t * settings may cause console setup to occur\n\t */\n\tmachvec_init_from_cmdline(*cmdline_p);\n#endif\n\n\tparse_early_param();\n\n\tif (early_console_setup(*cmdline_p) == 0)\n\t\tmark_bsp_online();\n\n#ifdef CONFIG_ACPI\n\t/* Initialize the ACPI boot-time table parser */\n\tacpi_table_init();\n# ifdef CONFIG_ACPI_NUMA\n\tacpi_numa_init();\n\tper_cpu_scan_finalize((cpus_weight(early_cpu_possible_map) == 0 ?\n\t\t32 : cpus_weight(early_cpu_possible_map)), additional_cpus);\n# endif\n#else\n# ifdef CONFIG_SMP\n\tsmp_build_cpu_map();\t/* happens, e.g., with the Ski simulator */\n# endif\n#endif /* CONFIG_APCI_BOOT */\n\n\tfind_memory();\n\n\t/* process SAL system table: */\n\tia64_sal_init(__va(efi.sal_systab));\n\n#ifdef CONFIG_SMP\n\tcpu_physical_id(0) = hard_smp_processor_id();\n#endif\n\n\tcpu_init();\t/* initialize the bootstrap CPU */\n\tmmu_context_init();\t/* initialize context_id bitmap */\n\n\tcheck_sal_cache_flush();\n\n#ifdef CONFIG_ACPI\n\tacpi_boot_init();\n#endif\n\n#ifdef CONFIG_VT\n\tif (!conswitchp) {\n# if defined(CONFIG_DUMMY_CONSOLE)\n\t\tconswitchp = &dummy_con;\n# endif\n# if defined(CONFIG_VGA_CONSOLE)\n\t\t/*\n\t\t * Non-legacy systems may route legacy VGA MMIO range to system\n\t\t * memory. vga_con probes the MMIO hole, so memory looks like\n\t\t * a VGA device to it. The EFI memory map can tell us if it's\n\t\t * memory so we can avoid this problem.\n\t\t */\n\t\tif (efi_mem_type(0xA0000) != EFI_CONVENTIONAL_MEMORY)\n\t\t\tconswitchp = &vga_con;\n# endif\n\t}\n#endif\n\n\t/* enable IA-64 Machine Check Abort Handling unless disabled */\n\tif (!nomca)\n\t\tia64_mca_init();\n\n\tplatform_setup(cmdline_p);\n\tpaging_init();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': '[IA64] Workaround for RSE issue\n\nProblem: An application violating the architectural rules regarding\noperation dependencies and having specific Register Stack Engine (RSE)\nstate at the time of the violation, may result in an illegal operation\nfault and invalid RSE state. Such faults may initiate a cascade of\nrepeated illegal operation faults within OS interruption handlers.\nThe specific behavior is OS dependent.\n\nImplication: An application causing an illegal operation fault with\nspecific RSE state may result in a series of illegal operation faults\nand an eventual OS stack overflow condition.\n\nWorkaround: OS interruption handlers that switch to kernel backing\nstore implement a check for invalid RSE state to avoid the series\nof illegal operation faults.\n\nThe core of the workaround is the RSE_WORKAROUND code sequence\ninserted into each invocation of the SAVE_MIN_WITH_COVER and\nSAVE_MIN_WITH_COVER_R19 macros. This sequence includes hard-coded\nconstants that depend on the number of stacked physical registers\nbeing 96. The rest of this patch consists of code to disable this\nworkaround should this not be the case (with the presumption that\nif a future Itanium processor increases the number of registers, it\nwould also remove the need for this patch).\n\nMove the start of the RBS up to a mod32 boundary to avoid some\ncorner cases.\n\nThe dispatch_illegal_op_fault code outgrew the spot it was\nsquatting in when built with this patch and CONFIG_VIRT_CPU_ACCOUNTING=y\nMove it out to the end of the ivt.\n\nSigned-off-by: Tony Luck '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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_always_inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, zend_long elements, int objprops)\n{\n\twhile (elements-- > 0) {\n\t\tzval key, *data, d, *old_data;\n\t\tzend_ulong idx;\n\n\t\tZVAL_UNDEF(&key);\n\n\t\tif (!php_var_unserialize_internal(&key, p, max, NULL, classes)) {\n\t\t\tzval_dtor(&key);\n\t\t\treturn 0;\n\t\t}\n\n\t\tdata = NULL;\n\t\tZVAL_UNDEF(&d);\n\n\t\tif (!objprops) {\n\t\t\tif (Z_TYPE(key) == IS_LONG) {\n\t\t\t\tidx = Z_LVAL(key);\nnumeric_key:\n\t\t\t\tif (UNEXPECTED((old_data = zend_hash_index_find(ht, idx)) != NULL)) {\n\t\t\t\t\t//??? update hash\n\t\t\t\t\tvar_push_dtor(var_hash, old_data);\n\t\t\t\t\tdata = zend_hash_index_update(ht, idx, &d);\n\t\t\t\t} else {\n\t\t\t\t\tdata = zend_hash_index_add_new(ht, idx, &d);\n\t\t\t\t}\n\t\t\t} else if (Z_TYPE(key) == IS_STRING) {\n\t\t\t\tif (UNEXPECTED(ZEND_HANDLE_NUMERIC(Z_STR(key), idx))) {\n\t\t\t\t\tgoto numeric_key;\n\t\t\t\t}\n\t\t\t\tif (UNEXPECTED((old_data = zend_hash_find(ht, Z_STR(key))) != NULL)) {\n\t\t\t\t\t//??? update hash\n\t\t\t\t\tvar_push_dtor(var_hash, old_data);\n\t\t\t\t\tdata = zend_hash_update(ht, Z_STR(key), &d);\n\t\t\t\t} else {\n\t\t\t\t\tdata = zend_hash_add_new(ht, Z_STR(key), &d);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tzval_dtor(&key);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t} else {\n\t\t\tif (EXPECTED(Z_TYPE(key) == IS_STRING)) {\nstring_key:\n\t\t\t\tif ((old_data = zend_hash_find(ht, Z_STR(key))) != NULL) {\n\t\t\t\t\tif (Z_TYPE_P(old_data) == IS_INDIRECT) {\n\t\t\t\t\t\told_data = Z_INDIRECT_P(old_data);\n\t\t\t\t\t}\n\t\t\t\t\tvar_push_dtor(var_hash, old_data);\n\t\t\t\t\tdata = zend_hash_update_ind(ht, Z_STR(key), &d);\n\t\t\t\t} else {\n\t\t\t\t\tdata = zend_hash_add_new(ht, Z_STR(key), &d);\n\t\t\t\t}\n\t\t\t} else if (Z_TYPE(key) == IS_LONG) {\n\t\t\t\t/* object properties should include no integers */\n\t\t\t\tconvert_to_string(&key);\n\t\t\t\tgoto string_key;\n\t\t\t} else {\n\t\t\t\tzval_dtor(&key);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\n\t\tif (!php_var_unserialize_internal(data, p, max, var_hash, classes)) {\n\t\t\tzval_dtor(&key);\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (UNEXPECTED(Z_ISUNDEF_P(data))) {\n\t\t\tif (Z_TYPE(key) == IS_LONG) {\n\t\t\t\tzend_hash_index_del(ht, Z_LVAL(key));\n\t\t\t} else {\n\t\t\t\tzend_hash_del_ind(ht, Z_STR(key));\n\t\t\t}\n\t\t} else {\n\t\t\tvar_push_dtor(var_hash, data);\n\t\t}\n\n\t\tzval_dtor(&key);\n\n\t\tif (elements && *(*p-1) != ';' && *(*p-1) != '}') {\n\t\t\t(*p)--;\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\treturn 1;\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: on_unregister_handler(TCMUService1HandlerManager1 *interface,\n\t\t GDBusMethodInvocation *invocation,\n\t\t gchar *subtype,\n\t\t gpointer user_data)\n{\n\tstruct tcmur_handler *handler = find_handler_by_subtype(subtype);\n\tstruct dbus_info *info = handler->opaque;\n\n\tif (!handler) {\n\t\tg_dbus_method_invocation_return_value(invocation,\n\t\t\tg_variant_new(\"(bs)\", FALSE,\n\t\t\t\t \"unknown subtype\"));\n\t\treturn TRUE;\n\t}\n\tdbus_unexport_handler(handler);\n\ttcmur_unregister_handler(handler);\n\tg_bus_unwatch_name(info->watcher_id);\n\tg_free(info);\n\tg_free(handler);\n\tg_dbus_method_invocation_return_value(invocation,\n\t\tg_variant_new(\"(bs)\", TRUE, \"succeeded\"));\n\treturn TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'fixed local DoS when UnregisterHandler was called for a not existing handler\n\nAny user with DBUS access could cause a SEGFAULT in tcmu-runner by\nrunning something like this:\n\ndbus-send --system --print-reply --dest=org.kernel.TCMUService1 /org/kernel/TCMUService1/HandlerManager1 org.kernel.TCMUService1.HandlerManager1.UnregisterHandler string:123'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int tcp_disconnect(struct sock *sk, int flags)\n{\n\tstruct inet_sock *inet = inet_sk(sk);\n\tstruct inet_connection_sock *icsk = inet_csk(sk);\n\tstruct tcp_sock *tp = tcp_sk(sk);\n\tint err = 0;\n\tint old_state = sk->sk_state;\n\n\tif (old_state != TCP_CLOSE)\n\t\ttcp_set_state(sk, TCP_CLOSE);\n\n\t/* ABORT function of RFC793 */\n\tif (old_state == TCP_LISTEN) {\n\t\tinet_csk_listen_stop(sk);\n\t} else if (unlikely(tp->repair)) {\n\t\tsk->sk_err = ECONNABORTED;\n\t} else if (tcp_need_reset(old_state) ||\n\t\t (tp->snd_nxt != tp->write_seq &&\n\t\t (1 << old_state) & (TCPF_CLOSING | TCPF_LAST_ACK))) {\n\t\t/* The last check adjusts for discrepancy of Linux wrt. RFC\n\t\t * states\n\t\t */\n\t\ttcp_send_active_reset(sk, gfp_any());\n\t\tsk->sk_err = ECONNRESET;\n\t} else if (old_state == TCP_SYN_SENT)\n\t\tsk->sk_err = ECONNRESET;\n\n\ttcp_clear_xmit_timers(sk);\n\t__skb_queue_purge(&sk->sk_receive_queue);\n\ttcp_write_queue_purge(sk);\n\ttcp_fastopen_active_disable_ofo_check(sk);\n\tskb_rbtree_purge(&tp->out_of_order_queue);\n\n\tinet->inet_dport = 0;\n\n\tif (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))\n\t\tinet_reset_saddr(sk);\n\n\tsk->sk_shutdown = 0;\n\tsock_reset_flag(sk, SOCK_DONE);\n\ttp->srtt_us = 0;\n\ttp->write_seq += tp->max_window + 2;\n\tif (tp->write_seq == 0)\n\t\ttp->write_seq = 1;\n\ticsk->icsk_backoff = 0;\n\ttp->snd_cwnd = 2;\n\ticsk->icsk_probes_out = 0;\n\ttp->packets_out = 0;\n\ttp->snd_ssthresh = TCP_INFINITE_SSTHRESH;\n\ttp->snd_cwnd_cnt = 0;\n\ttp->window_clamp = 0;\n\ttcp_set_ca_state(sk, TCP_CA_Open);\n\ttcp_clear_retrans(tp);\n\tinet_csk_delack_init(sk);\n\ttcp_init_send_head(sk);\n\tmemset(&tp->rx_opt, 0, sizeof(tp->rx_opt));\n\t__sk_dst_reset(sk);\n\ttcp_saved_syn_free(tp);\n\n\t/* Clean up fastopen related fields */\n\ttcp_free_fastopen_req(tp);\n\tinet->defer_connect = 0;\n\n\tWARN_ON(inet->inet_num && !icsk->icsk_bind_hash);\n\n\tsk->sk_error_report(sk);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'tcp: initialize rcv_mss to TCP_MIN_MSS instead of 0\n\nWhen tcp_disconnect() is called, inet_csk_delack_init() sets\nicsk->icsk_ack.rcv_mss to 0.\nThis could potentially cause tcp_recvmsg() => tcp_cleanup_rbuf() =>\n__tcp_select_window() call path to have division by 0 issue.\nSo this patch initializes rcv_mss to TCP_MIN_MSS instead of 0.\n\nReported-by: Andrey Konovalov \nSigned-off-by: Wei Wang \nSigned-off-by: Eric Dumazet \nSigned-off-by: Neal Cardwell \nSigned-off-by: Yuchung Cheng \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 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 /* The +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */\n l_data_size = 1 + (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-119', 'CWE-787'], 'message': 'Encoder: grow buffer size in opj_tcd_code_block_enc_allocate_data() to avoid write heap buffer overflow in opj_mqc_flush (#982)'" }, { "text": "[INST] Given the following code containing errors, provide Common 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_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,\n int swap __attribute__((__unused__)), uint32_t namesz, uint32_t descsz,\n size_t noff, size_t doff, int *flags)\n{\n\tif (namesz == 4 && strcmp((char *)&nbuf[noff], \"GNU\") == 0 &&\n\t type == NT_GNU_BUILD_ID && (descsz >= 4 || descsz <= 20)) {\n\t\tuint8_t desc[20];\n\t\tconst char *btype;\n\t\tuint32_t i;\n\t\t*flags |= FLAGS_DID_BUILD_ID;\n\t\tswitch (descsz) {\n\t\tcase 8:\n\t\t btype = \"xxHash\";\n\t\t break;\n\t\tcase 16:\n\t\t btype = \"md5/uuid\";\n\t\t break;\n\t\tcase 20:\n\t\t btype = \"sha1\";\n\t\t break;\n\t\tdefault:\n\t\t btype = \"unknown\";\n\t\t break;\n\t\t}\n\t\tif (file_printf(ms, \", BuildID[%s]=\", btype) == -1)\n\t\t\treturn 1;\n\t\t(void)memcpy(desc, &nbuf[doff], descsz);\n\t\tfor (i = 0; i < descsz; i++)\n\t\t if (file_printf(ms, \"%02x\", desc[i]) == -1)\n\t\t\treturn 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-119'], 'message': 'Fix always true condition (Thomas Jarosch)'" }, { "text": "[INST] Given the following code containing errors, provide Common 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_process_context_token (minor_status,\n context_handle,\n token_buffer)\n\nOM_uint32 *\t\tminor_status;\ngss_ctx_id_t\t\tcontext_handle;\ngss_buffer_t\t\ttoken_buffer;\n\n{\n OM_uint32\t\tstatus;\n gss_union_ctx_id_t\tctx;\n gss_mechanism\tmech;\n\n if (minor_status == NULL)\n\treturn (GSS_S_CALL_INACCESSIBLE_WRITE);\n *minor_status = 0;\n\n if (context_handle == GSS_C_NO_CONTEXT)\n\treturn (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT);\n\n if (token_buffer == GSS_C_NO_BUFFER)\n\treturn (GSS_S_CALL_INACCESSIBLE_READ);\n\n if (GSS_EMPTY_BUFFER(token_buffer))\n\treturn (GSS_S_CALL_INACCESSIBLE_READ);\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\n\tif (mech->gss_process_context_token) {\n\t status = mech->gss_process_context_token(\n\t\t\t\t\t\t minor_status,\n\t\t\t\t\t\t ctx->internal_ctx_id,\n\t\t\t\t\t\t token_buffer);\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\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_wrap_size_limit(OM_uint32 *minor_status,\n gss_ctx_id_t context_handle,\n int conf_req_flag,\n gss_qop_t qop_req, OM_uint32 req_output_size, OM_uint32 *max_input_size)\n{\n gss_union_ctx_id_t ctx;\n gss_mechanism mech;\n OM_uint32 major_status;\n\n if (minor_status == NULL)\n return (GSS_S_CALL_INACCESSIBLE_WRITE);\n *minor_status = 0;\n\n if (context_handle == GSS_C_NO_CONTEXT)\n return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT);\n\n if (max_input_size == NULL)\n return (GSS_S_CALL_INACCESSIBLE_WRITE);\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 return (GSS_S_BAD_MECH);\n\n if (mech->gss_wrap_size_limit)\n major_status = mech->gss_wrap_size_limit(minor_status,\n ctx->internal_ctx_id,\n conf_req_flag, qop_req,\n req_output_size, max_input_size);\n else if (mech->gss_wrap_iov_length)\n major_status = gssint_wrap_size_limit_iov_shim(mech, minor_status,\n ctx->internal_ctx_id,\n conf_req_flag, qop_req,\n req_output_size, max_input_size);\n else\n major_status = GSS_S_UNAVAILABLE;\n if (major_status != GSS_S_COMPLETE)\n map_error(minor_status, mech);\n return major_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: static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms)\n{\n\tjpc_siz_t *siz = &ms->parms.siz;\n\tint compno;\n\tint tileno;\n\tjpc_dec_tile_t *tile;\n\tjpc_dec_tcomp_t *tcomp;\n\tint htileno;\n\tint vtileno;\n\tjpc_dec_cmpt_t *cmpt;\n\tsize_t size;\n\tsize_t num_samples;\n\tsize_t num_samples_delta;\n\n\tdec->xstart = siz->xoff;\n\tdec->ystart = siz->yoff;\n\tdec->xend = siz->width;\n\tdec->yend = siz->height;\n\tdec->tilewidth = siz->tilewidth;\n\tdec->tileheight = siz->tileheight;\n\tdec->tilexoff = siz->tilexoff;\n\tdec->tileyoff = siz->tileyoff;\n\tdec->numcomps = siz->numcomps;\n\n\tif (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) {\n\t\treturn -1;\n\t}\n\n\tif (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) {\n\t\treturn -1;\n\t}\n\n\tnum_samples = 0;\n\tfor (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno,\n\t ++cmpt) {\n\t\tcmpt->prec = siz->comps[compno].prec;\n\t\tcmpt->sgnd = siz->comps[compno].sgnd;\n\t\tcmpt->hstep = siz->comps[compno].hsamp;\n\t\tcmpt->vstep = siz->comps[compno].vsamp;\n\t\tcmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) -\n\t\t JPC_CEILDIV(dec->xstart, cmpt->hstep);\n\t\tcmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) -\n\t\t JPC_CEILDIV(dec->ystart, cmpt->vstep);\n\t\tcmpt->hsubstep = 0;\n\t\tcmpt->vsubstep = 0;\n\n\t\tif (!jas_safe_size_mul(cmpt->width, cmpt->height, &num_samples_delta)) {\n\t\t\tjas_eprintf(\"image too large\\n\");\n\t\t\treturn -1;\n\t\t}\n\t\tif (!jas_safe_size_add(num_samples, num_samples_delta, &num_samples)) {\n\t\t\tjas_eprintf(\"image too large\\n\");\n\t\t}\n\t}\n\n\tif (dec->max_samples > 0 && num_samples > dec->max_samples) {\n\t\tjas_eprintf(\"maximum number of samples exceeded (%zu > %zu)\\n\",\n\t\t num_samples, dec->max_samples);\n\t\treturn -1;\n\t}\n\n\tdec->image = 0;\n\n\tdec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth);\n\tdec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight);\n\tassert(dec->numhtiles >= 0);\n\tassert(dec->numvtiles >= 0);\n\tif (!jas_safe_size_mul(dec->numhtiles, dec->numvtiles, &size) ||\n\t size > INT_MAX) {\n\t\treturn -1;\n\t}\n\tdec->numtiles = size;\n\tJAS_DBGLOG(10, (\"numtiles = %d; numhtiles = %d; numvtiles = %d;\\n\",\n\t dec->numtiles, dec->numhtiles, dec->numvtiles));\n\tif (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) {\n\t\treturn -1;\n\t}\n\n\tfor (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,\n\t ++tile) {\n\t\thtileno = tileno % dec->numhtiles;\n\t\tvtileno = tileno / dec->numhtiles;\n\t\ttile->realmode = 0;\n\t\ttile->state = JPC_TILE_INIT;\n\t\ttile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth,\n\t\t dec->xstart);\n\t\ttile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight,\n\t\t dec->ystart);\n\t\ttile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) *\n\t\t dec->tilewidth, dec->xend);\n\t\ttile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) *\n\t\t dec->tileheight, dec->yend);\n\t\ttile->numparts = 0;\n\t\ttile->partno = 0;\n\t\ttile->pkthdrstream = 0;\n\t\ttile->pkthdrstreampos = 0;\n\t\ttile->pptstab = 0;\n\t\ttile->cp = 0;\n\t\ttile->pi = 0;\n\t\tif (!(tile->tcomps = jas_alloc2(dec->numcomps,\n\t\t sizeof(jpc_dec_tcomp_t)))) {\n\t\t\treturn -1;\n\t\t}\n\t\tfor (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps;\n\t\t compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) {\n\t\t\ttcomp->rlvls = 0;\n\t\t\ttcomp->numrlvls = 0;\n\t\t\ttcomp->data = 0;\n\t\t\ttcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep);\n\t\t\ttcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep);\n\t\t\ttcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep);\n\t\t\ttcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep);\n\t\t\ttcomp->tsfb = 0;\n\t\t}\n\t}\n\n\tdec->pkthdrstreams = 0;\n\n\t/* We should expect to encounter other main header marker segments\n\t or an SOT marker segment next. */\n\tdec->state = JPC_MH;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772'], 'message': 'jpc_dec: fix tile memory leak after decoder failure\n\nThe function jpc_dec_tilefini() is only called for tiles which have\ncompleted successfully. If there is one decoder error, all unfinished\ntiles leak lots of memory.\n\nThis change adds jpc_dec_tilefini() calls to jpc_dec_destroy() for\neach tile which is not marked \"done\" (state!=JPC_TILE_DONE). This\nhowever crashes when the tile initialization loop in\njpc_dec_process_siz() fails, because the rest of the array has not yet\nbeen initialized; to work around this, I added a loop which\ninitializes all states with JPC_TILE_DONE before doing the real\ninitialization.\n\nFixes CVE-2017-13748\n\nCloses https://github.com/mdadams/jasper/issues/168'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void l2cap_conn_start(struct l2cap_conn *conn)\n{\n\tstruct l2cap_chan *chan, *tmp;\n\n\tBT_DBG(\"conn %p\", conn);\n\n\tmutex_lock(&conn->chan_lock);\n\n\tlist_for_each_entry_safe(chan, tmp, &conn->chan_l, list) {\n\t\tl2cap_chan_lock(chan);\n\n\t\tif (chan->chan_type != L2CAP_CHAN_CONN_ORIENTED) {\n\t\t\tl2cap_chan_ready(chan);\n\t\t\tl2cap_chan_unlock(chan);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (chan->state == BT_CONNECT) {\n\t\t\tif (!l2cap_chan_check_security(chan, true) ||\n\t\t\t !__l2cap_no_conn_pending(chan)) {\n\t\t\t\tl2cap_chan_unlock(chan);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!l2cap_mode_supported(chan->mode, conn->feat_mask)\n\t\t\t && test_bit(CONF_STATE2_DEVICE,\n\t\t\t\t\t&chan->conf_state)) {\n\t\t\t\tl2cap_chan_close(chan, ECONNRESET);\n\t\t\t\tl2cap_chan_unlock(chan);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tl2cap_start_connection(chan);\n\n\t\t} else if (chan->state == BT_CONNECT2) {\n\t\t\tstruct l2cap_conn_rsp rsp;\n\t\t\tchar buf[128];\n\t\t\trsp.scid = cpu_to_le16(chan->dcid);\n\t\t\trsp.dcid = cpu_to_le16(chan->scid);\n\n\t\t\tif (l2cap_chan_check_security(chan, false)) {\n\t\t\t\tif (test_bit(FLAG_DEFER_SETUP, &chan->flags)) {\n\t\t\t\t\trsp.result = cpu_to_le16(L2CAP_CR_PEND);\n\t\t\t\t\trsp.status = cpu_to_le16(L2CAP_CS_AUTHOR_PEND);\n\t\t\t\t\tchan->ops->defer(chan);\n\n\t\t\t\t} else {\n\t\t\t\t\tl2cap_state_change(chan, BT_CONFIG);\n\t\t\t\t\trsp.result = cpu_to_le16(L2CAP_CR_SUCCESS);\n\t\t\t\t\trsp.status = cpu_to_le16(L2CAP_CS_NO_INFO);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trsp.result = cpu_to_le16(L2CAP_CR_PEND);\n\t\t\t\trsp.status = cpu_to_le16(L2CAP_CS_AUTHEN_PEND);\n\t\t\t}\n\n\t\t\tl2cap_send_cmd(conn, chan->ident, L2CAP_CONN_RSP,\n\t\t\t\t sizeof(rsp), &rsp);\n\n\t\t\tif (test_bit(CONF_REQ_SENT, &chan->conf_state) ||\n\t\t\t rsp.result != L2CAP_CR_SUCCESS) {\n\t\t\t\tl2cap_chan_unlock(chan);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tset_bit(CONF_REQ_SENT, &chan->conf_state);\n\t\t\tl2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ,\n\t\t\t\t l2cap_build_conf_req(chan, buf), buf);\n\t\t\tchan->num_conf_req++;\n\t\t}\n\n\t\tl2cap_chan_unlock(chan);\n\t}\n\n\tmutex_unlock(&conn->chan_lock);\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 inline int l2cap_config_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_conf_rsp *rsp = (struct l2cap_conf_rsp *)data;\n\tu16 scid, flags, result;\n\tstruct l2cap_chan *chan;\n\tint len = cmd_len - sizeof(*rsp);\n\tint err = 0;\n\n\tif (cmd_len < sizeof(*rsp))\n\t\treturn -EPROTO;\n\n\tscid = __le16_to_cpu(rsp->scid);\n\tflags = __le16_to_cpu(rsp->flags);\n\tresult = __le16_to_cpu(rsp->result);\n\n\tBT_DBG(\"scid 0x%4.4x flags 0x%2.2x result 0x%2.2x len %d\", scid, flags,\n\t result, len);\n\n\tchan = l2cap_get_chan_by_scid(conn, scid);\n\tif (!chan)\n\t\treturn 0;\n\n\tswitch (result) {\n\tcase L2CAP_CONF_SUCCESS:\n\t\tl2cap_conf_rfc_get(chan, rsp->data, len);\n\t\tclear_bit(CONF_REM_CONF_PEND, &chan->conf_state);\n\t\tbreak;\n\n\tcase L2CAP_CONF_PENDING:\n\t\tset_bit(CONF_REM_CONF_PEND, &chan->conf_state);\n\n\t\tif (test_bit(CONF_LOC_CONF_PEND, &chan->conf_state)) {\n\t\t\tchar buf[64];\n\n\t\t\tlen = l2cap_parse_conf_rsp(chan, rsp->data, len,\n\t\t\t\t\t\t buf, &result);\n\t\t\tif (len < 0) {\n\t\t\t\tl2cap_send_disconn_req(chan, ECONNRESET);\n\t\t\t\tgoto done;\n\t\t\t}\n\n\t\t\tif (!chan->hs_hcon) {\n\t\t\t\tl2cap_send_efs_conf_rsp(chan, buf, cmd->ident,\n\t\t\t\t\t\t\t0);\n\t\t\t} else {\n\t\t\t\tif (l2cap_check_efs(chan)) {\n\t\t\t\t\tamp_create_logical_link(chan);\n\t\t\t\t\tchan->ident = cmd->ident;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tgoto done;\n\n\tcase L2CAP_CONF_UNACCEPT:\n\t\tif (chan->num_conf_rsp <= L2CAP_CONF_MAX_CONF_RSP) {\n\t\t\tchar req[64];\n\n\t\t\tif (len > sizeof(req) - sizeof(struct l2cap_conf_req)) {\n\t\t\t\tl2cap_send_disconn_req(chan, ECONNRESET);\n\t\t\t\tgoto done;\n\t\t\t}\n\n\t\t\t/* throw out any old stored conf requests */\n\t\t\tresult = L2CAP_CONF_SUCCESS;\n\t\t\tlen = l2cap_parse_conf_rsp(chan, rsp->data, len,\n\t\t\t\t\t\t req, &result);\n\t\t\tif (len < 0) {\n\t\t\t\tl2cap_send_disconn_req(chan, ECONNRESET);\n\t\t\t\tgoto done;\n\t\t\t}\n\n\t\t\tl2cap_send_cmd(conn, l2cap_get_ident(conn),\n\t\t\t\t L2CAP_CONF_REQ, len, req);\n\t\t\tchan->num_conf_req++;\n\t\t\tif (result != L2CAP_CONF_SUCCESS)\n\t\t\t\tgoto done;\n\t\t\tbreak;\n\t\t}\n\n\tdefault:\n\t\tl2cap_chan_set_err(chan, ECONNRESET);\n\n\t\t__set_chan_timer(chan, L2CAP_DISC_REJ_TIMEOUT);\n\t\tl2cap_send_disconn_req(chan, ECONNRESET);\n\t\tgoto done;\n\t}\n\n\tif (flags & L2CAP_CONF_FLAG_CONTINUATION)\n\t\tgoto done;\n\n\tset_bit(CONF_INPUT_DONE, &chan->conf_state);\n\n\tif (test_bit(CONF_OUTPUT_DONE, &chan->conf_state)) {\n\t\tset_default_fcs(chan);\n\n\t\tif (chan->mode == L2CAP_MODE_ERTM ||\n\t\t chan->mode == L2CAP_MODE_STREAMING)\n\t\t\terr = l2cap_ertm_init(chan);\n\n\t\tif (err < 0)\n\t\t\tl2cap_send_disconn_req(chan, -err);\n\t\telse\n\t\t\tl2cap_chan_ready(chan);\n\t}\n\ndone:\n\tl2cap_chan_unlock(chan);\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: MagickExport Image *SampleImage(const Image *image,const size_t columns,\n const size_t rows,ExceptionInfo *exception)\n{\n#define SampleImageTag \"Sample/Image\"\n\n CacheView\n *image_view,\n *sample_view;\n\n Image\n *sample_image;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n progress;\n\n register ssize_t\n x1;\n\n ssize_t\n *x_offset,\n y;\n\n PointInfo\n sample_offset;\n\n /*\n Initialize sampled image attributes.\n */\n assert(image != (const Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n if ((columns == 0) || (rows == 0))\n ThrowImageException(ImageError,\"NegativeOrZeroImageSize\");\n if ((columns == image->columns) && (rows == image->rows))\n return(CloneImage(image,0,0,MagickTrue,exception));\n sample_image=CloneImage(image,columns,rows,MagickTrue,exception);\n if (sample_image == (Image *) NULL)\n return((Image *) NULL);\n /*\n Set the sampling offset, default is in the mid-point of sample regions.\n */\n sample_offset.x=sample_offset.y=0.5-MagickEpsilon;\n {\n const char\n *value;\n\n value=GetImageArtifact(image,\"sample:offset\");\n if (value != (char *) NULL)\n {\n GeometryInfo\n geometry_info;\n\n MagickStatusType\n flags;\n\n (void) ParseGeometry(value,&geometry_info);\n flags=ParseGeometry(value,&geometry_info);\n sample_offset.x=sample_offset.y=geometry_info.rho/100.0-MagickEpsilon;\n if ((flags & SigmaValue) != 0)\n sample_offset.y=geometry_info.sigma/100.0-MagickEpsilon;\n }\n }\n /*\n Allocate scan line buffer and column offset buffers.\n */\n x_offset=(ssize_t *) AcquireQuantumMemory((size_t) sample_image->columns,\n sizeof(*x_offset));\n if (x_offset == (ssize_t *) NULL)\n {\n sample_image=DestroyImage(sample_image);\n ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n for (x1=0; x1 < (ssize_t) sample_image->columns; x1++)\n x_offset[x1]=(ssize_t) ((((double) x1+sample_offset.x)*image->columns)/\n sample_image->columns);\n /*\n Sample each row.\n */\n status=MagickTrue;\n progress=0;\n image_view=AcquireVirtualCacheView(image,exception);\n sample_view=AcquireAuthenticCacheView(sample_image,exception);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static,4) shared(status) \\\n magick_threads(image,sample_image,1,1)\n#endif\n for (y=0; y < (ssize_t) sample_image->rows; y++)\n {\n register const Quantum\n *magick_restrict p;\n\n register Quantum\n *magick_restrict q;\n\n register ssize_t\n x;\n\n ssize_t\n y_offset;\n\n if (status == MagickFalse)\n continue;\n y_offset=(ssize_t) ((((double) y+sample_offset.y)*image->rows)/\n sample_image->rows);\n p=GetCacheViewVirtualPixels(image_view,0,y_offset,image->columns,1,\n exception);\n q=QueueCacheViewAuthenticPixels(sample_view,0,y,sample_image->columns,1,\n exception);\n if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))\n {\n status=MagickFalse;\n continue;\n }\n /*\n Sample each column.\n */\n for (x=0; x < (ssize_t) sample_image->columns; x++)\n {\n register ssize_t\n i;\n\n if (GetPixelWriteMask(sample_image,q) <= (QuantumRange/2))\n {\n q+=GetPixelChannels(sample_image);\n continue;\n }\n for (i=0; i < (ssize_t) GetPixelChannels(sample_image); i++)\n {\n PixelChannel\n channel;\n\n PixelTrait\n sample_traits,\n traits;\n\n channel=GetPixelChannelChannel(image,i);\n traits=GetPixelChannelTraits(image,channel);\n sample_traits=GetPixelChannelTraits(sample_image,channel);\n if ((traits == UndefinedPixelTrait) ||\n (sample_traits == UndefinedPixelTrait))\n continue;\n SetPixelChannel(sample_image,channel,p[x_offset[x]*GetPixelChannels(\n image)+i],q);\n }\n q+=GetPixelChannels(sample_image);\n }\n if (SyncCacheViewAuthenticPixels(sample_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_SampleImage)\n#endif\n proceed=SetImageProgress(image,SampleImageTag,progress++,image->rows);\n if (proceed == MagickFalse)\n status=MagickFalse;\n }\n }\n image_view=DestroyCacheView(image_view);\n sample_view=DestroyCacheView(sample_view);\n x_offset=(ssize_t *) RelinquishMagickMemory(x_offset);\n sample_image->type=image->type;\n if (status == MagickFalse)\n sample_image=DestroyImage(sample_image);\n return(sample_image);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/717'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer)\n{\n /*placeholder */\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: 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 (\"test44.bson\",\n BSON_VALIDATE_NONE,\n 24,\n BSON_VALIDATE_NONE,\n \"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 (\"test48.bson\",\n BSON_VALIDATE_NONE,\n 14,\n BSON_VALIDATE_NONE,\n \"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': '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: WandExport double *DrawGetStrokeDashArray(const DrawingWand *wand,\n size_t *number_elements)\n{\n double\n *dasharray;\n\n register const double\n *p;\n\n register double\n *q;\n\n register ssize_t\n i;\n\n size_t\n n;\n\n assert(wand != (const DrawingWand *) NULL);\n assert(wand->signature == MagickWandSignature);\n if (wand->debug != MagickFalse)\n (void) LogMagickEvent(WandEvent,GetMagickModule(),\"%s\",wand->name);\n assert(number_elements != (size_t *) NULL);\n n=0;\n p=CurrentContext->dash_pattern;\n if (p != (const double *) NULL)\n while (fabs(*p++) >= MagickEpsilon)\n n++;\n *number_elements=n;\n dasharray=(double *) NULL;\n if (n != 0)\n {\n dasharray=(double *) AcquireQuantumMemory((size_t) n+1UL,\n sizeof(*dasharray));\n p=CurrentContext->dash_pattern;\n q=dasharray;\n for (i=0; i < (ssize_t) n; i++)\n *q++=(*p++);\n *q=0.0;\n }\n return(dasharray);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/716'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ofputil_decode_ofp15_group_desc_reply(struct ofputil_group_desc *gd,\n struct ofpbuf *msg,\n enum ofp_version version)\n{\n struct ofp15_group_desc_stats *ogds;\n uint16_t length, bucket_list_len;\n int error;\n\n if (!msg->header) {\n ofpraw_pull_assert(msg);\n }\n\n if (!msg->size) {\n return EOF;\n }\n\n ogds = ofpbuf_try_pull(msg, sizeof *ogds);\n if (!ogds) {\n VLOG_WARN_RL(&bad_ofmsg_rl, \"OFPST11_GROUP_DESC reply has %\"PRIu32\" \"\n \"leftover bytes at end\", msg->size);\n return OFPERR_OFPBRC_BAD_LEN;\n }\n gd->type = ogds->type;\n gd->group_id = ntohl(ogds->group_id);\n\n length = ntohs(ogds->length);\n if (length < sizeof *ogds || length - sizeof *ogds > msg->size) {\n VLOG_WARN_RL(&bad_ofmsg_rl, \"OFPST11_GROUP_DESC reply claims invalid \"\n \"length %u\", length);\n return OFPERR_OFPBRC_BAD_LEN;\n }\n\n bucket_list_len = ntohs(ogds->bucket_list_len);\n if (length < bucket_list_len + sizeof *ogds) {\n VLOG_WARN_RL(&bad_ofmsg_rl, \"OFPST11_GROUP_DESC reply claims invalid \"\n \"bucket list length %u\", bucket_list_len);\n return OFPERR_OFPBRC_BAD_LEN;\n }\n error = ofputil_pull_ofp15_buckets(msg, bucket_list_len, version, gd->type,\n &gd->buckets);\n if (error) {\n return error;\n }\n\n /* By definition group desc messages don't have a group mod command.\n * However, parse_group_prop_ntr_selection_method() checks to make sure\n * that the command is OFPGC15_ADD or OFPGC15_DELETE to guard\n * against group mod messages with other commands supplying\n * a NTR selection method group experimenter property.\n * Such properties are valid for group desc replies so\n * claim that the group mod command is OFPGC15_ADD to\n * satisfy the check in parse_group_prop_ntr_selection_method() */\n return parse_ofp15_group_properties(msg, gd->type, OFPGC15_ADD, &gd->props,\n length - sizeof *ogds - bucket_list_len);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772'], 'message': 'ofp-util: Fix memory leaks when parsing OF1.5 group properties.\n\nFound by libFuzzer.\n\nReported-by: Bhargava Shastry \nSigned-off-by: Ben Pfaff \nAcked-by: Justin Pettit '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: logger_get_mask_expanded (struct t_gui_buffer *buffer, const char *mask)\n{\n char *mask2, *mask_decoded, *mask_decoded2, *mask_decoded3, *mask_decoded4;\n char *mask_decoded5;\n const char *dir_separator;\n int length;\n time_t seconds;\n struct tm *date_tmp;\n\n mask2 = NULL;\n mask_decoded = NULL;\n mask_decoded2 = NULL;\n mask_decoded3 = NULL;\n mask_decoded4 = NULL;\n mask_decoded5 = NULL;\n\n dir_separator = weechat_info_get (\"dir_separator\", \"\");\n if (!dir_separator)\n return NULL;\n\n /*\n * we first replace directory separator (commonly '/') by \\01 because\n * buffer mask can contain this char, and will be replaced by replacement\n * char ('_' by default)\n */\n mask2 = weechat_string_replace (mask, dir_separator, \"\\01\");\n if (!mask2)\n goto end;\n\n mask_decoded = weechat_buffer_string_replace_local_var (buffer, mask2);\n if (!mask_decoded)\n goto end;\n\n mask_decoded2 = weechat_string_replace (mask_decoded,\n dir_separator,\n weechat_config_string (logger_config_file_replacement_char));\n if (!mask_decoded2)\n goto end;\n\n#ifdef __CYGWIN__\n mask_decoded3 = weechat_string_replace (mask_decoded2, \"\\\\\",\n weechat_config_string (logger_config_file_replacement_char));\n#else\n mask_decoded3 = strdup (mask_decoded2);\n#endif /* __CYGWIN__ */\n if (!mask_decoded3)\n goto end;\n\n /* restore directory separator */\n mask_decoded4 = weechat_string_replace (mask_decoded3,\n \"\\01\", dir_separator);\n if (!mask_decoded4)\n goto end;\n\n /* replace date/time specifiers in mask */\n length = strlen (mask_decoded4) + 256 + 1;\n mask_decoded5 = malloc (length);\n if (!mask_decoded5)\n goto end;\n seconds = time (NULL);\n date_tmp = localtime (&seconds);\n mask_decoded5[0] = '\\0';\n strftime (mask_decoded5, length - 1, mask_decoded4, date_tmp);\n\n /* convert to lower case? */\n if (weechat_config_boolean (logger_config_file_name_lower_case))\n weechat_string_tolower (mask_decoded5);\n\n if (weechat_logger_plugin->debug)\n {\n weechat_printf_date_tags (NULL, 0, \"no_log\",\n \"%s: buffer = \\\"%s\\\", mask = \\\"%s\\\", \"\n \"decoded mask = \\\"%s\\\"\",\n LOGGER_PLUGIN_NAME,\n weechat_buffer_get_string (buffer, \"name\"),\n mask, mask_decoded5);\n }\n\nend:\n if (mask2)\n free (mask2);\n if (mask_decoded)\n free (mask_decoded);\n if (mask_decoded2)\n free (mask_decoded2);\n if (mask_decoded3)\n free (mask_decoded3);\n if (mask_decoded4)\n free (mask_decoded4);\n\n return mask_decoded5;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'logger: call strftime before replacing buffer local variables'" }, { "text": "[INST] Given the following code containing errors, provide Common 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 e_phoff = get_te64(&ehdri.e_phoff);\n e_shoff = get_te64(&ehdri.e_shoff);\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 const *)(e_shoff + file_image); // do not free() !!\n sec_dynsym = elf_find_section_type(Elf64_Shdr::SHT_DYNSYM);\n if (sec_dynsym)\n sec_dynstr = get_te64(&sec_dynsym->sh_link) + shdri;\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 *)(get_te64(&phdr->p_offset) + file_image);\n break;\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 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;\n }\n }\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: static bool add_line(String &buffer,char *line,char *in_string,\n bool *ml_comment, bool truncated)\n{\n uchar inchar;\n char buff[80], *pos, *out;\n COMMANDS *com;\n bool need_space= 0;\n bool ss_comment= 0;\n DBUG_ENTER(\"add_line\");\n\n if (!line[0] && buffer.is_empty())\n DBUG_RETURN(0);\n#ifdef HAVE_READLINE\n if (status.add_to_history && line[0] && not_in_history(line))\n add_history(line);\n#endif\n char *end_of_line=line+(uint) strlen(line);\n\n for (pos=out=line ; (inchar= (uchar) *pos) ; pos++)\n {\n if (!preserve_comments)\n {\n // Skip spaces at the beginning of a statement\n if (my_isspace(charset_info,inchar) && (out == line) &&\n buffer.is_empty())\n continue;\n }\n \n#ifdef USE_MB\n // Accept multi-byte characters as-is\n int length;\n if (use_mb(charset_info) &&\n (length= my_ismbchar(charset_info, pos, end_of_line)))\n {\n if (!*ml_comment || preserve_comments)\n {\n while (length--)\n *out++ = *pos++;\n pos--;\n }\n else\n pos+= length - 1;\n continue;\n }\n#endif\n if (!*ml_comment && inchar == '\\\\' &&\n !(*in_string && \n (mysql.server_status & SERVER_STATUS_NO_BACKSLASH_ESCAPES)))\n {\n // Found possbile one character command like \\c\n\n if (!(inchar = (uchar) *++pos))\n\tbreak;\t\t\t\t// readline adds one '\\'\n if (*in_string || inchar == 'N')\t// \\N is short for NULL\n {\t\t\t\t\t// Don't allow commands in string\n\t*out++='\\\\';\n\t*out++= (char) inchar;\n\tcontinue;\n }\n if ((com=find_command(NullS,(char) inchar)))\n {\n // Flush previously accepted characters\n if (out != line)\n {\n buffer.append(line, (uint) (out-line));\n out= line;\n }\n \n if ((*com->func)(&buffer,pos-1) > 0)\n DBUG_RETURN(1); // Quit\n if (com->takes_params)\n {\n if (ss_comment)\n {\n /*\n If a client-side macro appears inside a server-side comment,\n discard all characters in the comment after the macro (that is,\n until the end of the comment rather than the next delimiter)\n */\n for (pos++; *pos && (*pos != '*' || *(pos + 1) != '/'); pos++)\n ;\n pos--;\n }\n else\n {\n for (pos++ ;\n *pos && (*pos != *delimiter ||\n !is_prefix(pos + 1, delimiter + 1)) ; pos++)\n ;\t// Remove parameters\n if (!*pos)\n pos--;\n else \n pos+= delimiter_length - 1; // Point at last delim char\n }\n }\n }\n else\n {\n\tsprintf(buff,\"Unknown command '\\\\%c'.\",inchar);\n\tif (put_info(buff,INFO_ERROR) > 0)\n\t DBUG_RETURN(1);\n\t*out++='\\\\';\n\t*out++=(char) inchar;\n\tcontinue;\n }\n }\n else if (!*ml_comment && !*in_string && is_prefix(pos, delimiter))\n {\n // Found a statement. Continue parsing after the delimiter\n pos+= delimiter_length;\n\n if (preserve_comments)\n {\n while (my_isspace(charset_info, *pos))\n *out++= *pos++;\n }\n // Flush previously accepted characters\n if (out != line)\n {\n buffer.append(line, (uint32) (out-line));\n out= line;\n }\n\n if (preserve_comments && ((*pos == '#') ||\n ((*pos == '-') &&\n (pos[1] == '-') &&\n my_isspace(charset_info, pos[2]))))\n {\n // Add trailing single line comments to this statement\n buffer.append(pos);\n pos+= strlen(pos);\n }\n\n pos--;\n\n if ((com= find_command(buffer.c_ptr(), 0)))\n {\n \n if ((*com->func)(&buffer, buffer.c_ptr()) > 0)\n DBUG_RETURN(1); // Quit \n }\n else\n {\n if (com_go(&buffer, 0) > 0) // < 0 is not fatal\n DBUG_RETURN(1);\n }\n buffer.length(0);\n }\n else if (!*ml_comment && (!*in_string && (inchar == '#' ||\n (inchar == '-' && pos[1] == '-' &&\n /*\n The third byte is either whitespace or is the\n end of the line -- which would occur only\n because of the user sending newline -- which is\n itself whitespace and should also match.\n */\n\t\t\t (my_isspace(charset_info,pos[2]) ||\n !pos[2])))))\n {\n // Flush previously accepted characters\n if (out != line)\n {\n buffer.append(line, (uint32) (out - line));\n out= line;\n }\n\n // comment to end of line\n if (preserve_comments)\n {\n bool started_with_nothing= !buffer.length();\n\n buffer.append(pos);\n\n /*\n A single-line comment by itself gets sent immediately so that\n client commands (delimiter, status, etc) will be interpreted on\n the next line.\n */\n if (started_with_nothing)\n {\n if (com_go(&buffer, 0) > 0) // < 0 is not fatal\n DBUG_RETURN(1);\n buffer.length(0);\n }\n }\n\n break;\n }\n else if (!*in_string && inchar == '/' && *(pos+1) == '*' &&\n\t *(pos+2) != '!')\n {\n if (preserve_comments)\n {\n *out++= *pos++; // copy '/'\n *out++= *pos; // copy '*'\n }\n else\n pos++;\n *ml_comment= 1;\n if (out != line)\n {\n buffer.append(line,(uint) (out-line));\n out=line;\n }\n }\n else if (*ml_comment && !ss_comment && inchar == '*' && *(pos + 1) == '/')\n {\n if (preserve_comments)\n {\n *out++= *pos++; // copy '*'\n *out++= *pos; // copy '/'\n }\n else\n pos++;\n *ml_comment= 0;\n if (out != line)\n {\n buffer.append(line, (uint32) (out - line));\n out= line;\n }\n // Consumed a 2 chars or more, and will add 1 at most,\n // so using the 'line' buffer to edit data in place is ok.\n need_space= 1;\n } \n else\n {\t\t\t\t\t\t// Add found char to buffer\n if (!*in_string && inchar == '/' && *(pos + 1) == '*' &&\n *(pos + 2) == '!')\n ss_comment= 1;\n else if (!*in_string && ss_comment && inchar == '*' && *(pos + 1) == '/')\n ss_comment= 0;\n if (inchar == *in_string)\n\t*in_string= 0;\n else if (!*ml_comment && !*in_string &&\n\t (inchar == '\\'' || inchar == '\"' || inchar == '`'))\n\t*in_string= (char) inchar;\n if (!*ml_comment || preserve_comments)\n {\n if (need_space && !my_isspace(charset_info, (char)inchar))\n *out++= ' ';\n need_space= 0;\n *out++= (char) inchar;\n }\n }\n }\n if (out != line || !buffer.is_empty())\n {\n uint length=(uint) (out-line);\n\n if (!truncated && (length < 9 ||\n my_strnncoll (charset_info, (uchar *)line, 9,\n (const uchar *) \"delimiter\", 9) ||\n (*in_string || *ml_comment)))\n {\n /* \n Don't add a new line in case there's a DELIMITER command to be \n added to the glob buffer (e.g. on processing a line like \n \";DELIMITER \") : similar to how a new line is \n not added in the case when the DELIMITER is the first command \n entered with an empty glob buffer. However, if the delimiter is\n part of a string or a comment, the new line should be added. (e.g.\n SELECT '\\ndelimiter\\n';\\n)\n */\n *out++='\\n';\n length++;\n }\n if (buffer.length() + length >= buffer.alloced_length())\n buffer.realloc(buffer.length()+length+IO_SIZE);\n if ((!*ml_comment || preserve_comments) && buffer.append(line, length))\n DBUG_RETURN(1);\n }\n DBUG_RETURN(0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-863'], 'message': 'Bug#26372491 - RCE THROUGH THE MISHANDLE OF BACKSLASH\n\nDESCRIPTION:\n===========\nThe bug is related to incorrect parsing of SQL queries\nwhen typed in on the CLI. The incorrect parsing can\nresult in unexpected results.\n\nANALYSIS:\n========\nThe scenarios mainly happens for identifier names\nwith a typical combination of backslashes and backticks.\nThe incorrect parsing can either result in executing\nadditional queries or can result in query truncation.\nThis can impact mysqldump as well.\n\nFIX:\n===\nThe fix makes sure that such identifier names are\ncorrectly parsed and a proper query is sent to the\nserver for execution.\n\n(cherry picked from commit 31a372aa1c2b93dc75267d1f05a7f7fca6080dc0)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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_state_fetch_resp(struct connectdata *conn, int imapcode,\n imapstate instate)\n{\n CURLcode result = CURLE_OK;\n struct Curl_easy *data = conn->data;\n struct imap_conn *imapc = &conn->proto.imapc;\n struct pingpong *pp = &imapc->pp;\n const char *ptr = data->state.buffer;\n bool parsed = FALSE;\n curl_off_t size = 0;\n\n (void)instate; /* no use for this yet */\n\n if(imapcode != '*') {\n Curl_pgrsSetDownloadSize(data, -1);\n state(conn, IMAP_STOP);\n return CURLE_REMOTE_FILE_NOT_FOUND; /* TODO: Fix error code */\n }\n\n /* Something like this is received \"* 1 FETCH (BODY[TEXT] {2021}\\r\" so parse\n the continuation data contained within the curly brackets */\n while(*ptr && (*ptr != '{'))\n ptr++;\n\n if(*ptr == '{') {\n char *endptr;\n if(!curlx_strtoofft(ptr + 1, &endptr, 10, &size)) {\n if(endptr - ptr > 1 && endptr[0] == '}' &&\n endptr[1] == '\\r' && endptr[2] == '\\0')\n parsed = TRUE;\n }\n }\n\n if(parsed) {\n infof(data, \"Found %\" CURL_FORMAT_CURL_OFF_TU \" bytes to download\\n\",\n size);\n Curl_pgrsSetDownloadSize(data, size);\n\n if(pp->cache) {\n /* At this point there is a bunch of data in the header \"cache\" that is\n actually body content, send it as body and then skip it. Do note\n that there may even be additional \"headers\" after the body. */\n size_t chunk = pp->cache_size;\n\n if(chunk > (size_t)size)\n /* The conversion from curl_off_t to size_t is always fine here */\n chunk = (size_t)size;\n\n result = Curl_client_write(conn, CLIENTWRITE_BODY, pp->cache, chunk);\n if(result)\n return result;\n\n data->req.bytecount += chunk;\n\n infof(data, \"Written %\" CURL_FORMAT_CURL_OFF_TU\n \" bytes, %\" CURL_FORMAT_CURL_OFF_TU\n \" bytes are left for transfer\\n\", (curl_off_t)chunk,\n size - chunk);\n\n /* Have we used the entire cache or just part of it?*/\n if(pp->cache_size > chunk) {\n /* Only part of it so shrink the cache to fit the trailing data */\n memmove(pp->cache, pp->cache + chunk, pp->cache_size - chunk);\n pp->cache_size -= chunk;\n }\n else {\n /* Free the cache */\n Curl_safefree(pp->cache);\n\n /* Reset the cache size */\n pp->cache_size = 0;\n }\n }\n\n if(data->req.bytecount == size)\n /* The entire data is already transferred! */\n Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);\n else {\n /* IMAP download */\n data->req.maxdownload = size;\n Curl_setup_transfer(conn, FIRSTSOCKET, size, FALSE, NULL, -1, NULL);\n }\n }\n else {\n /* We don't know how to parse this line */\n failf(pp->conn->data, \"Failed to parse FETCH response.\");\n result = CURLE_WEIRD_SERVER_REPLY;\n }\n\n /* End of DO phase */\n state(conn, IMAP_STOP);\n\n return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'imap: if a FETCH response has no size, don't call write callback\n\nCVE-2017-1000257\n\nReported-by: Brian Carpenter and 0xd34db347\nAlso detected by OSS-Fuzz: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=3586'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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 __fanout_unlink(struct sock *sk, struct packet_sock *po)\n{\n\tstruct packet_fanout *f = po->fanout;\n\tint i;\n\n\tspin_lock(&f->lock);\n\tfor (i = 0; i < f->num_members; i++) {\n\t\tif (f->arr[i] == sk)\n\t\t\tbreak;\n\t}\n\tBUG_ON(i >= f->num_members);\n\tf->arr[i] = f->arr[f->num_members - 1];\n\tf->num_members--;\n\tspin_unlock(&f->lock);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'packet: Do not call fanout_release from atomic contexts\n\nCommit 6664498280cf (\"packet: call fanout_release, while UNREGISTERING a\nnetdev\"), unfortunately, introduced the following issues.\n\n1. calling mutex_lock(&fanout_mutex) (fanout_release()) from inside\nrcu_read-side critical section. rcu_read_lock disables preemption, most often,\nwhich prohibits calling sleeping functions.\n\n[ ] include/linux/rcupdate.h:560 Illegal context switch in RCU read-side critical section!\n[ ]\n[ ] rcu_scheduler_active = 1, debug_locks = 0\n[ ] 4 locks held by ovs-vswitchd/1969:\n[ ] #0: (cb_lock){++++++}, at: [] genl_rcv+0x19/0x40\n[ ] #1: (ovs_mutex){+.+.+.}, at: [] ovs_vport_cmd_del+0x4a/0x100 [openvswitch]\n[ ] #2: (rtnl_mutex){+.+.+.}, at: [] rtnl_lock+0x17/0x20\n[ ] #3: (rcu_read_lock){......}, at: [] packet_notifier+0x5/0x3f0\n[ ]\n[ ] Call Trace:\n[ ] [] dump_stack+0x85/0xc4\n[ ] [] lockdep_rcu_suspicious+0x107/0x110\n[ ] [] ___might_sleep+0x57/0x210\n[ ] [] __might_sleep+0x70/0x90\n[ ] [] mutex_lock_nested+0x3c/0x3a0\n[ ] [] ? vprintk_default+0x1f/0x30\n[ ] [] ? printk+0x4d/0x4f\n[ ] [] fanout_release+0x1d/0xe0\n[ ] [] packet_notifier+0x2f9/0x3f0\n\n2. calling mutex_lock(&fanout_mutex) inside spin_lock(&po->bind_lock).\n\"sleeping function called from invalid context\"\n\n[ ] BUG: sleeping function called from invalid context at kernel/locking/mutex.c:620\n[ ] in_atomic(): 1, irqs_disabled(): 0, pid: 1969, name: ovs-vswitchd\n[ ] INFO: lockdep is turned off.\n[ ] Call Trace:\n[ ] [] dump_stack+0x85/0xc4\n[ ] [] ___might_sleep+0x202/0x210\n[ ] [] __might_sleep+0x70/0x90\n[ ] [] mutex_lock_nested+0x3c/0x3a0\n[ ] [] fanout_release+0x1d/0xe0\n[ ] [] packet_notifier+0x2f9/0x3f0\n\n3. calling dev_remove_pack(&fanout->prot_hook), from inside\nspin_lock(&po->bind_lock) or rcu_read-side critical-section. dev_remove_pack()\n-> synchronize_net(), which might sleep.\n\n[ ] BUG: scheduling while atomic: ovs-vswitchd/1969/0x00000002\n[ ] INFO: lockdep is turned off.\n[ ] Call Trace:\n[ ] [] dump_stack+0x85/0xc4\n[ ] [] __schedule_bug+0x64/0x73\n[ ] [] __schedule+0x6b/0xd10\n[ ] [] schedule+0x6b/0x80\n[ ] [] schedule_timeout+0x38d/0x410\n[ ] [] synchronize_sched_expedited+0x53d/0x810\n[ ] [] synchronize_rcu_expedited+0xe/0x10\n[ ] [] synchronize_net+0x35/0x50\n[ ] [] dev_remove_pack+0x13/0x20\n[ ] [] fanout_release+0xbe/0xe0\n[ ] [] packet_notifier+0x2f9/0x3f0\n\n4. fanout_release() races with calls from different CPU.\n\nTo fix the above problems, remove the call to fanout_release() under\nrcu_read_lock(). Instead, call __dev_remove_pack(&fanout->prot_hook) and\nnetdev_run_todo will be happy that &dev->ptype_specific list is empty. In order\nto achieve this, I moved dev_{add,remove}_pack() out of fanout_{add,release} to\n__fanout_{link,unlink}. So, call to {,__}unregister_prot_hook() will make sure\nfanout->prot_hook is removed as well.\n\nFixes: 6664498280cf (\"packet: call fanout_release, while UNREGISTERING a netdev\")\nReported-by: Eric Dumazet \nSigned-off-by: Anoob Soman \nAcked-by: Eric Dumazet \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static noinline void key_gc_unused_keys(struct list_head *keys)\n{\n\twhile (!list_empty(keys)) {\n\t\tstruct key *key =\n\t\t\tlist_entry(keys->next, struct key, graveyard_link);\n\t\tlist_del(&key->graveyard_link);\n\n\t\tkdebug(\"- %u\", key->serial);\n\t\tkey_check(key);\n\n\t\t/* Throw away the key data if the key is instantiated */\n\t\tif (test_bit(KEY_FLAG_INSTANTIATED, &key->flags) &&\n\t\t !test_bit(KEY_FLAG_NEGATIVE, &key->flags) &&\n\t\t key->type->destroy)\n\t\t\tkey->type->destroy(key);\n\n\t\tsecurity_key_free(key);\n\n\t\t/* deal with the user's key tracking and quota */\n\t\tif (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {\n\t\t\tspin_lock(&key->user->lock);\n\t\t\tkey->user->qnkeys--;\n\t\t\tkey->user->qnbytes -= key->quotalen;\n\t\t\tspin_unlock(&key->user->lock);\n\t\t}\n\n\t\tatomic_dec(&key->user->nkeys);\n\t\tif (test_bit(KEY_FLAG_INSTANTIATED, &key->flags))\n\t\t\tatomic_dec(&key->user->nikeys);\n\n\t\tkey_user_put(key->user);\n\n\t\tkfree(key->description);\n\n\t\tmemzero_explicit(key, sizeof(*key));\n\t\tkmem_cache_free(key_jar, key);\n\t}\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: long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen)\n{\n\tstruct key *key;\n\tkey_ref_t key_ref;\n\tlong ret;\n\n\t/* find the key first */\n\tkey_ref = lookup_user_key(keyid, 0, 0);\n\tif (IS_ERR(key_ref)) {\n\t\tret = -ENOKEY;\n\t\tgoto error;\n\t}\n\n\tkey = key_ref_to_ptr(key_ref);\n\n\tif (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) {\n\t\tret = -ENOKEY;\n\t\tgoto error2;\n\t}\n\n\t/* see if we can read it directly */\n\tret = key_permission(key_ref, KEY_NEED_READ);\n\tif (ret == 0)\n\t\tgoto can_read_key;\n\tif (ret != -EACCES)\n\t\tgoto error2;\n\n\t/* we can't; see if it's searchable from this process's keyrings\n\t * - we automatically take account of the fact that it may be\n\t * dangling off an instantiation key\n\t */\n\tif (!is_key_possessed(key_ref)) {\n\t\tret = -EACCES;\n\t\tgoto error2;\n\t}\n\n\t/* the key is probably readable - now try to read it */\ncan_read_key:\n\tret = -EOPNOTSUPP;\n\tif (key->type->read) {\n\t\t/* Read the data with the semaphore held (since we might sleep)\n\t\t * to protect against the key being updated or revoked.\n\t\t */\n\t\tdown_read(&key->sem);\n\t\tret = key_validate(key);\n\t\tif (ret == 0)\n\t\t\tret = key->type->read(key, buffer, buflen);\n\t\tup_read(&key->sem);\n\t}\n\nerror2:\n\tkey_put(key);\nerror:\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'KEYS: Fix race between updating and finding a negative key\n\nConsolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection\nerror into one field such that:\n\n (1) The instantiation state can be modified/read atomically.\n\n (2) The error can be accessed atomically with the state.\n\n (3) The error isn't stored unioned with the payload pointers.\n\nThis deals with the problem that the state is spread over three different\nobjects (two bits and a separate variable) and reading or updating them\natomically isn't practical, given that not only can uninstantiated keys\nchange into instantiated or rejected keys, but rejected keys can also turn\ninto instantiated keys - and someone accessing the key might not be using\nany locking.\n\nThe main side effect of this problem is that what was held in the payload\nmay change, depending on the state. For instance, you might observe the\nkey to be in the rejected state. You then read the cached error, but if\nthe key semaphore wasn't locked, the key might've become instantiated\nbetween the two reads - and you might now have something in hand that isn't\nactually an error code.\n\nThe state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error\ncode if the key is negatively instantiated. The key_is_instantiated()\nfunction is replaced with key_is_positive() to avoid confusion as negative\nkeys are also 'instantiated'.\n\nAdditionally, barriering is included:\n\n (1) Order payload-set before state-set during instantiation.\n\n (2) Order state-read before payload-read when using the key.\n\nFurther separate barriering is necessary if RCU is being used to access the\npayload content after reading the payload pointers.\n\nFixes: 146aa8b1453b (\"KEYS: Merge the type-specific data with the payload data\")\nCc: stable@vger.kernel.org # v4.4+\nReported-by: Eric Biggers \nSigned-off-by: David Howells \nReviewed-by: Eric Biggers '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int usb_get_bos_descriptor(struct usb_device *dev)\n{\n\tstruct device *ddev = &dev->dev;\n\tstruct usb_bos_descriptor *bos;\n\tstruct usb_dev_cap_header *cap;\n\tunsigned char *buffer;\n\tint length, total_len, num, i;\n\tint ret;\n\n\tbos = kzalloc(sizeof(struct usb_bos_descriptor), GFP_KERNEL);\n\tif (!bos)\n\t\treturn -ENOMEM;\n\n\t/* Get BOS descriptor */\n\tret = usb_get_descriptor(dev, USB_DT_BOS, 0, bos, USB_DT_BOS_SIZE);\n\tif (ret < USB_DT_BOS_SIZE) {\n\t\tdev_err(ddev, \"unable to get BOS descriptor\\n\");\n\t\tif (ret >= 0)\n\t\t\tret = -ENOMSG;\n\t\tkfree(bos);\n\t\treturn ret;\n\t}\n\n\tlength = bos->bLength;\n\ttotal_len = le16_to_cpu(bos->wTotalLength);\n\tnum = bos->bNumDeviceCaps;\n\tkfree(bos);\n\tif (total_len < length)\n\t\treturn -EINVAL;\n\n\tdev->bos = kzalloc(sizeof(struct usb_host_bos), GFP_KERNEL);\n\tif (!dev->bos)\n\t\treturn -ENOMEM;\n\n\t/* Now let's get the whole BOS descriptor set */\n\tbuffer = kzalloc(total_len, GFP_KERNEL);\n\tif (!buffer) {\n\t\tret = -ENOMEM;\n\t\tgoto err;\n\t}\n\tdev->bos->desc = (struct usb_bos_descriptor *)buffer;\n\n\tret = usb_get_descriptor(dev, USB_DT_BOS, 0, buffer, total_len);\n\tif (ret < total_len) {\n\t\tdev_err(ddev, \"unable to get BOS descriptor set\\n\");\n\t\tif (ret >= 0)\n\t\t\tret = -ENOMSG;\n\t\tgoto err;\n\t}\n\ttotal_len -= length;\n\n\tfor (i = 0; i < num; i++) {\n\t\tbuffer += length;\n\t\tcap = (struct usb_dev_cap_header *)buffer;\n\t\tlength = cap->bLength;\n\n\t\tif (total_len < length)\n\t\t\tbreak;\n\t\ttotal_len -= length;\n\n\t\tif (cap->bDescriptorType != USB_DT_DEVICE_CAPABILITY) {\n\t\t\tdev_warn(ddev, \"descriptor type invalid, skip\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tswitch (cap->bDevCapabilityType) {\n\t\tcase USB_CAP_TYPE_WIRELESS_USB:\n\t\t\t/* Wireless USB cap descriptor is handled by wusb */\n\t\t\tbreak;\n\t\tcase USB_CAP_TYPE_EXT:\n\t\t\tdev->bos->ext_cap =\n\t\t\t\t(struct usb_ext_cap_descriptor *)buffer;\n\t\t\tbreak;\n\t\tcase USB_SS_CAP_TYPE:\n\t\t\tdev->bos->ss_cap =\n\t\t\t\t(struct usb_ss_cap_descriptor *)buffer;\n\t\t\tbreak;\n\t\tcase USB_SSP_CAP_TYPE:\n\t\t\tdev->bos->ssp_cap =\n\t\t\t\t(struct usb_ssp_cap_descriptor *)buffer;\n\t\t\tbreak;\n\t\tcase CONTAINER_ID_TYPE:\n\t\t\tdev->bos->ss_id =\n\t\t\t\t(struct usb_ss_container_id_descriptor *)buffer;\n\t\t\tbreak;\n\t\tcase USB_PTM_CAP_TYPE:\n\t\t\tdev->bos->ptm_cap =\n\t\t\t\t(struct usb_ptm_cap_descriptor *)buffer;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn 0;\n\nerr:\n\tusb_release_bos_descriptor(dev);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'USB: core: fix out-of-bounds access bug in usb_get_bos_descriptor()\n\nAndrey used the syzkaller fuzzer to find an out-of-bounds memory\naccess in usb_get_bos_descriptor(). The code wasn't checking that the\nnext usb_dev_cap_header structure could fit into the remaining buffer\nspace.\n\nThis patch fixes the error and also reduces the bNumDeviceCaps field\nin the header to match the actual number of capabilities found, in\ncases where there are fewer than expected.\n\nReported-by: Andrey Konovalov \nSigned-off-by: Alan Stern \nTested-by: Andrey Konovalov \nCC: \nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int usb_parse_configuration(struct usb_device *dev, int cfgidx,\n struct usb_host_config *config, unsigned char *buffer, int size)\n{\n\tstruct device *ddev = &dev->dev;\n\tunsigned char *buffer0 = buffer;\n\tint cfgno;\n\tint nintf, nintf_orig;\n\tint i, j, n;\n\tstruct usb_interface_cache *intfc;\n\tunsigned char *buffer2;\n\tint size2;\n\tstruct usb_descriptor_header *header;\n\tint len, retval;\n\tu8 inums[USB_MAXINTERFACES], nalts[USB_MAXINTERFACES];\n\tunsigned iad_num = 0;\n\n\tmemcpy(&config->desc, buffer, USB_DT_CONFIG_SIZE);\n\tif (config->desc.bDescriptorType != USB_DT_CONFIG ||\n\t config->desc.bLength < USB_DT_CONFIG_SIZE ||\n\t config->desc.bLength > size) {\n\t\tdev_err(ddev, \"invalid descriptor for config index %d: \"\n\t\t \"type = 0x%X, length = %d\\n\", cfgidx,\n\t\t config->desc.bDescriptorType, config->desc.bLength);\n\t\treturn -EINVAL;\n\t}\n\tcfgno = config->desc.bConfigurationValue;\n\n\tbuffer += config->desc.bLength;\n\tsize -= config->desc.bLength;\n\n\tnintf = nintf_orig = config->desc.bNumInterfaces;\n\tif (nintf > USB_MAXINTERFACES) {\n\t\tdev_warn(ddev, \"config %d has too many interfaces: %d, \"\n\t\t \"using maximum allowed: %d\\n\",\n\t\t cfgno, nintf, USB_MAXINTERFACES);\n\t\tnintf = USB_MAXINTERFACES;\n\t}\n\n\t/* Go through the descriptors, checking their length and counting the\n\t * number of altsettings for each interface */\n\tn = 0;\n\tfor ((buffer2 = buffer, size2 = size);\n\t size2 > 0;\n\t (buffer2 += header->bLength, size2 -= header->bLength)) {\n\n\t\tif (size2 < sizeof(struct usb_descriptor_header)) {\n\t\t\tdev_warn(ddev, \"config %d descriptor has %d excess \"\n\t\t\t \"byte%s, ignoring\\n\",\n\t\t\t cfgno, size2, plural(size2));\n\t\t\tbreak;\n\t\t}\n\n\t\theader = (struct usb_descriptor_header *) buffer2;\n\t\tif ((header->bLength > size2) || (header->bLength < 2)) {\n\t\t\tdev_warn(ddev, \"config %d has an invalid descriptor \"\n\t\t\t \"of length %d, skipping remainder of the config\\n\",\n\t\t\t cfgno, header->bLength);\n\t\t\tbreak;\n\t\t}\n\n\t\tif (header->bDescriptorType == USB_DT_INTERFACE) {\n\t\t\tstruct usb_interface_descriptor *d;\n\t\t\tint inum;\n\n\t\t\td = (struct usb_interface_descriptor *) header;\n\t\t\tif (d->bLength < USB_DT_INTERFACE_SIZE) {\n\t\t\t\tdev_warn(ddev, \"config %d has an invalid \"\n\t\t\t\t \"interface descriptor of length %d, \"\n\t\t\t\t \"skipping\\n\", cfgno, d->bLength);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tinum = d->bInterfaceNumber;\n\n\t\t\tif ((dev->quirks & USB_QUIRK_HONOR_BNUMINTERFACES) &&\n\t\t\t n >= nintf_orig) {\n\t\t\t\tdev_warn(ddev, \"config %d has more interface \"\n\t\t\t\t \"descriptors, than it declares in \"\n\t\t\t\t \"bNumInterfaces, ignoring interface \"\n\t\t\t\t \"number: %d\\n\", cfgno, inum);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (inum >= nintf_orig)\n\t\t\t\tdev_warn(ddev, \"config %d has an invalid \"\n\t\t\t\t \"interface number: %d but max is %d\\n\",\n\t\t\t\t cfgno, inum, nintf_orig - 1);\n\n\t\t\t/* Have we already encountered this interface?\n\t\t\t * Count its altsettings */\n\t\t\tfor (i = 0; i < n; ++i) {\n\t\t\t\tif (inums[i] == inum)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (i < n) {\n\t\t\t\tif (nalts[i] < 255)\n\t\t\t\t\t++nalts[i];\n\t\t\t} else if (n < USB_MAXINTERFACES) {\n\t\t\t\tinums[n] = inum;\n\t\t\t\tnalts[n] = 1;\n\t\t\t\t++n;\n\t\t\t}\n\n\t\t} else if (header->bDescriptorType ==\n\t\t\t\tUSB_DT_INTERFACE_ASSOCIATION) {\n\t\t\tif (iad_num == USB_MAXIADS) {\n\t\t\t\tdev_warn(ddev, \"found more Interface \"\n\t\t\t\t\t \"Association Descriptors \"\n\t\t\t\t\t \"than allocated for in \"\n\t\t\t\t\t \"configuration %d\\n\", cfgno);\n\t\t\t} else {\n\t\t\t\tconfig->intf_assoc[iad_num] =\n\t\t\t\t\t(struct usb_interface_assoc_descriptor\n\t\t\t\t\t*)header;\n\t\t\t\tiad_num++;\n\t\t\t}\n\n\t\t} else if (header->bDescriptorType == USB_DT_DEVICE ||\n\t\t\t header->bDescriptorType == USB_DT_CONFIG)\n\t\t\tdev_warn(ddev, \"config %d contains an unexpected \"\n\t\t\t \"descriptor of type 0x%X, skipping\\n\",\n\t\t\t cfgno, header->bDescriptorType);\n\n\t}\t/* for ((buffer2 = buffer, size2 = size); ...) */\n\tsize = buffer2 - buffer;\n\tconfig->desc.wTotalLength = cpu_to_le16(buffer2 - buffer0);\n\n\tif (n != nintf)\n\t\tdev_warn(ddev, \"config %d has %d interface%s, different from \"\n\t\t \"the descriptor's value: %d\\n\",\n\t\t cfgno, n, plural(n), nintf_orig);\n\telse if (n == 0)\n\t\tdev_warn(ddev, \"config %d has no interfaces?\\n\", cfgno);\n\tconfig->desc.bNumInterfaces = nintf = n;\n\n\t/* Check for missing interface numbers */\n\tfor (i = 0; i < nintf; ++i) {\n\t\tfor (j = 0; j < nintf; ++j) {\n\t\t\tif (inums[j] == i)\n\t\t\t\tbreak;\n\t\t}\n\t\tif (j >= nintf)\n\t\t\tdev_warn(ddev, \"config %d has no interface number \"\n\t\t\t \"%d\\n\", cfgno, i);\n\t}\n\n\t/* Allocate the usb_interface_caches and altsetting arrays */\n\tfor (i = 0; i < nintf; ++i) {\n\t\tj = nalts[i];\n\t\tif (j > USB_MAXALTSETTING) {\n\t\t\tdev_warn(ddev, \"too many alternate settings for \"\n\t\t\t \"config %d interface %d: %d, \"\n\t\t\t \"using maximum allowed: %d\\n\",\n\t\t\t cfgno, inums[i], j, USB_MAXALTSETTING);\n\t\t\tnalts[i] = j = USB_MAXALTSETTING;\n\t\t}\n\n\t\tlen = sizeof(*intfc) + sizeof(struct usb_host_interface) * j;\n\t\tconfig->intf_cache[i] = intfc = kzalloc(len, GFP_KERNEL);\n\t\tif (!intfc)\n\t\t\treturn -ENOMEM;\n\t\tkref_init(&intfc->ref);\n\t}\n\n\t/* FIXME: parse the BOS descriptor */\n\n\t/* Skip over any Class Specific or Vendor Specific descriptors;\n\t * find the first interface descriptor */\n\tconfig->extra = buffer;\n\ti = find_next_descriptor(buffer, size, USB_DT_INTERFACE,\n\t USB_DT_INTERFACE, &n);\n\tconfig->extralen = i;\n\tif (n > 0)\n\t\tdev_dbg(ddev, \"skipped %d descriptor%s after %s\\n\",\n\t\t n, plural(n), \"configuration\");\n\tbuffer += i;\n\tsize -= i;\n\n\t/* Parse all the interface/altsetting descriptors */\n\twhile (size > 0) {\n\t\tretval = usb_parse_interface(ddev, cfgno, config,\n\t\t buffer, size, inums, nalts);\n\t\tif (retval < 0)\n\t\t\treturn retval;\n\n\t\tbuffer += retval;\n\t\tsize -= retval;\n\t}\n\n\t/* Check for missing altsettings */\n\tfor (i = 0; i < nintf; ++i) {\n\t\tintfc = config->intf_cache[i];\n\t\tfor (j = 0; j < intfc->num_altsetting; ++j) {\n\t\t\tfor (n = 0; n < intfc->num_altsetting; ++n) {\n\t\t\t\tif (intfc->altsetting[n].desc.\n\t\t\t\t bAlternateSetting == j)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (n >= intfc->num_altsetting)\n\t\t\t\tdev_warn(ddev, \"config %d interface %d has no \"\n\t\t\t\t \"altsetting %d\\n\", cfgno, inums[i], j);\n\t\t}\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'USB: fix out-of-bounds in usb_set_configuration\n\nAndrey Konovalov reported a possible out-of-bounds problem for a USB interface\nassociation descriptor. He writes:\n\tIt seems there's no proper size check of a USB_DT_INTERFACE_ASSOCIATION\n\tdescriptor. It's only checked that the size is >= 2 in\n\tusb_parse_configuration(), so find_iad() might do out-of-bounds access\n\tto intf_assoc->bInterfaceCount.\n\nAnd he's right, we don't check for crazy descriptors of this type very well, so\nresolve this problem. Yet another issue found by syzkaller...\n\nReported-by: Andrey Konovalov \nTested-by: Andrey Konovalov \nCc: stable \nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void ctcp_msg_dcc_chat(IRC_SERVER_REC *server, const char *data,\n\t\t\t const char *nick, const char *addr,\n\t\t\t const char *target, CHAT_DCC_REC *chat)\n{\n CHAT_DCC_REC *dcc;\n\tchar **params;\n\tint paramcount;\n int passive, autoallow = FALSE;\n\n /* CHAT
*/\n\t/* CHAT
0 (DCC CHAT passive protocol) */\n\tparams = g_strsplit(data, \" \", -1);\n\tparamcount = g_strv_length(params);\n\n\tif (paramcount < 3) {\n\t\tg_strfreev(params);\n\t\treturn;\n\t}\n\tpassive = paramcount == 4 && g_strcmp0(params[2], \"0\") == 0;\n\n\tdcc = DCC_CHAT(dcc_find_request(DCC_CHAT_TYPE, nick, NULL));\n\tif (dcc != NULL) {\n\t\tif (dcc_is_listening(dcc)) {\n\t\t\t/* we requested dcc chat, they requested\n\t\t\t dcc chat from us .. allow it. */\n\t\t\tdcc_destroy(DCC(dcc));\n\t\t\tautoallow = TRUE;\n\t\t} else if (!dcc_is_passive(dcc)) {\n\t\t\t/* we already have one dcc chat request\n\t\t\t from this nick, remove it. */\n\t\t\tdcc_destroy(DCC(dcc));\n\t\t} else if (passive) {\n\t\t\tif (dcc->pasv_id != atoi(params[3])) {\n\t\t\t\t/* IDs don't match! */\n\t\t\t\tdcc_destroy(DCC(dcc));\n\t\t\t} else {\n\t\t\t\t/* IDs are ok! Update address and port and\n\t\t\t\t connect! */\n\t\t\t\tdcc->target = g_strdup(target);\n\t\t\t\tdcc->port = atoi(params[2]);\n\t\t\t\tdcc_str2ip(params[1], &dcc->addr);\n\t\t\t\tnet_ip2host(&dcc->addr, dcc->addrstr);\n\n\t\t\t\tdcc_chat_connect(dcc);\n\t\t\t\tg_strfreev(params);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tdcc = dcc_chat_create(server, chat, nick, params[0]);\n\tdcc->target = g_strdup(target);\n\tdcc->port = atoi(params[2]);\n\n\tif (passive)\n\t\tdcc->pasv_id = atoi(params[3]);\n\n\tdcc_str2ip(params[1], &dcc->addr);\n\tnet_ip2host(&dcc->addr, dcc->addrstr);\n\n\tsignal_emit(\"dcc request\", 2, dcc, addr);\n\n\tif (autoallow || DCC_CHAT_AUTOACCEPT(dcc, server, nick, addr)) {\n\t\tif (passive) {\n\t\t\t/* Passive DCC... let's set up a listening socket\n\t\t\t and send reply back */\n\t\t\tdcc_chat_passive(dcc);\n\t\t} else {\n\t\t\tdcc_chat_connect(dcc);\n\t\t}\n\t}\n\tg_strfreev(params);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Merge branch 'security' into 'master'\n\nSecurity\n\nCloses GL#12, GL#13, GL#14, GL#15, GL#16\n\nSee merge request irssi/irssi!23'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ldns_rr_new_frm_str_internal(ldns_rr **newrr, const char *str,\n uint32_t default_ttl, ldns_rdf *origin,\n\t\t ldns_rdf **prev, bool question)\n{\n\tldns_rr *new;\n\tconst ldns_rr_descriptor *desc;\n\tldns_rr_type rr_type;\n\tldns_buffer *rr_buf = NULL;\n\tldns_buffer *rd_buf = NULL;\n\tuint32_t ttl_val;\n\tchar *owner = NULL;\n\tchar *ttl = NULL;\n\tldns_rr_class clas_val;\n\tchar *clas = NULL;\n\tchar *type = NULL;\n\tchar *rdata = NULL;\n\tchar *rd = NULL;\n\tchar *\tb64 = NULL;\n\tsize_t rd_strlen;\n\tconst char *delimiters;\n\tssize_t c;\n\tldns_rdf *owner_dname;\n const char* endptr;\n int was_unknown_rr_format = 0;\n\tldns_status status = LDNS_STATUS_OK;\n\n\t/* used for types with unknown number of rdatas */\n\tbool done;\n\tbool quoted;\n\n\tldns_rdf *r = NULL;\n\tuint16_t r_cnt;\n\tuint16_t r_min;\n\tuint16_t r_max;\n size_t pre_data_pos;\n\n\tnew = ldns_rr_new();\n\n\towner = LDNS_XMALLOC(char, LDNS_MAX_DOMAINLEN + 1);\n\tttl = LDNS_XMALLOC(char, LDNS_TTL_DATALEN);\n\tclas = LDNS_XMALLOC(char, LDNS_SYNTAX_DATALEN);\n\trdata = LDNS_XMALLOC(char, LDNS_MAX_PACKETLEN + 1);\n\trr_buf = LDNS_MALLOC(ldns_buffer);\n\trd_buf = LDNS_MALLOC(ldns_buffer);\n\trd = LDNS_XMALLOC(char, LDNS_MAX_RDFLEN);\n\tb64 = LDNS_XMALLOC(char, LDNS_MAX_RDFLEN);\n\tif (!new || !owner || !ttl || !clas || !rdata || !rr_buf || !rd_buf || !rd || !b64 ) {\n\t\tstatus = LDNS_STATUS_MEM_ERR;\n\t\tLDNS_FREE(rr_buf);\n\t\tgoto ldnserror;\n\t}\n\n\tldns_buffer_new_frm_data(rr_buf, (char*)str, strlen(str));\n\n\t/* split the rr in its parts -1 signals trouble */\n\tif (ldns_bget_token(rr_buf, owner, \"\\t\\n \", LDNS_MAX_DOMAINLEN) == -1) {\n\t\tstatus = LDNS_STATUS_SYNTAX_ERR;\n\t\tldns_buffer_free(rr_buf);\n\t\tgoto ldnserror;\n\t}\n\n\tif (ldns_bget_token(rr_buf, ttl, \"\\t\\n \", LDNS_TTL_DATALEN) == -1) {\n\t\tstatus = LDNS_STATUS_SYNTAX_TTL_ERR;\n\t\tldns_buffer_free(rr_buf);\n\t\tgoto ldnserror;\n\t}\n\tttl_val = (uint32_t) ldns_str2period(ttl, &endptr);\n\n\tif (strlen(ttl) > 0 && !isdigit((int) ttl[0])) {\n\t\t/* ah, it's not there or something */\n\t\tif (default_ttl == 0) {\n\t\t\tttl_val = LDNS_DEFAULT_TTL;\n\t\t} else {\n\t\t\tttl_val = default_ttl;\n\t\t}\n\t\t/* we not ASSUMING the TTL is missing and that\n\t\t * the rest of the RR is still there. That is\n\t\t * CLASS TYPE RDATA\n\t\t * so ttl value we read is actually the class\n\t\t */\n\t\tclas_val = ldns_get_rr_class_by_name(ttl);\n\t\t/* class can be left out too, assume IN, current\n\t\t * token must be type\n\t\t */\n\t\tif (clas_val == 0) {\n\t\t\tclas_val = LDNS_RR_CLASS_IN;\n\t\t\ttype = LDNS_XMALLOC(char, strlen(ttl) + 1);\n\t\t\tif(!type) {\n\t\t\t\tstatus = LDNS_STATUS_MEM_ERR;\n\t\t\t\tldns_buffer_free(rr_buf);\n\t\t\t\tgoto ldnserror;\n\t\t\t}\n\t\t\tstrncpy(type, ttl, strlen(ttl) + 1);\n\t\t}\n\t} else {\n\t\tif (ldns_bget_token(rr_buf, clas, \"\\t\\n \", LDNS_SYNTAX_DATALEN) == -1) {\n\t\t\tstatus = LDNS_STATUS_SYNTAX_CLASS_ERR;\n\t\t\tldns_buffer_free(rr_buf);\n\t\t\tgoto ldnserror;\n\t\t}\n\t\tclas_val = ldns_get_rr_class_by_name(clas);\n\t\t/* class can be left out too, assume IN, current\n\t\t * token must be type\n\t\t */\n\t\tif (clas_val == 0) {\n\t\t\tclas_val = LDNS_RR_CLASS_IN;\n\t\t\ttype = LDNS_XMALLOC(char, strlen(clas) + 1);\n\t\t\tif(!type) {\n\t\t\t\tstatus = LDNS_STATUS_MEM_ERR;\n\t\t\t\tldns_buffer_free(rr_buf);\n\t\t\t\tgoto ldnserror;\n\t\t\t}\n\t\t\tstrncpy(type, clas, strlen(clas) + 1);\n\t\t}\n\t}\n\t/* the rest should still be waiting for us */\n\n\tif (!type) {\n\t\ttype = LDNS_XMALLOC(char, LDNS_SYNTAX_DATALEN);\n\t\tif(!type) {\n\t\t\tstatus = LDNS_STATUS_MEM_ERR;\n\t\t\tldns_buffer_free(rr_buf);\n\t\t\tgoto ldnserror;\n\t\t}\n\t\tif (ldns_bget_token(rr_buf, type, \"\\t\\n \", LDNS_SYNTAX_DATALEN) == -1) {\n\t\t\tstatus = LDNS_STATUS_SYNTAX_TYPE_ERR;\n\t\t\tldns_buffer_free(rr_buf);\n\t\t\tgoto ldnserror;\n\t\t}\n\t}\n\n\tif (ldns_bget_token(rr_buf, rdata, \"\\0\", LDNS_MAX_PACKETLEN) == -1) {\n\t\t/* apparently we are done, and it's only a question RR\n\t\t * so do not set status and go to ldnserror here\n\t\t*/\n\t}\n\n\tldns_buffer_new_frm_data(rd_buf, rdata, strlen(rdata));\n\n\tif (strlen(owner) <= 1 && strncmp(owner, \"@\", 1) == 0) {\n\t\tif (origin) {\n\t\t\tldns_rr_set_owner(new, ldns_rdf_clone(origin));\n\t\t} else if (prev && *prev) {\n\t\t\tldns_rr_set_owner(new, ldns_rdf_clone(*prev));\n\t\t} else {\n\t\t\t/* default to root */\n\t\t\tldns_rr_set_owner(new, ldns_dname_new_frm_str(\".\"));\n\t\t}\n\n\t\t/* @ also overrides prev */\n\t\tif (prev) {\n\t\t\tldns_rdf_deep_free(*prev);\n\t\t\t*prev = ldns_rdf_clone(ldns_rr_owner(new));\n\t\t\tif (!*prev) {\n\t\t\t\tstatus = LDNS_STATUS_MEM_ERR;\n\t\t\t\tldns_buffer_free(rr_buf);\n\t\t\t\tgoto ldnserror;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (strlen(owner) == 0) {\n\t\t\t/* no ownername was given, try prev, if that fails\n\t\t\t * origin, else default to root */\n\t\t\tif (prev && *prev) {\n\t\t\t\tldns_rr_set_owner(new, ldns_rdf_clone(*prev));\n\t\t\t} else if (origin) {\n\t\t\t\tldns_rr_set_owner(new, ldns_rdf_clone(origin));\n\t\t\t} else {\n\t\t\t\tldns_rr_set_owner(new, ldns_dname_new_frm_str(\".\"));\n\t\t\t}\n\t\t\tif(!ldns_rr_owner(new)) {\n\t\t\t\tstatus = LDNS_STATUS_MEM_ERR;\n\t\t\t\tldns_buffer_free(rr_buf);\n\t\t\t\tgoto ldnserror;\n\t\t\t}\n\t\t} else {\n\t\t\towner_dname = ldns_dname_new_frm_str(owner);\n\t\t\tif (!owner_dname) {\n\t\t\t\tstatus = LDNS_STATUS_SYNTAX_ERR;\n\t\t\t\tldns_buffer_free(rr_buf);\n\t\t\t\tgoto ldnserror;\n\t\t\t}\n\n\t\t\tldns_rr_set_owner(new, owner_dname);\n\t\t\tif (!ldns_dname_str_absolute(owner) && origin) {\n\t\t\t\tif(ldns_dname_cat(ldns_rr_owner(new),\n\t\t\t\t\t\t\torigin) != LDNS_STATUS_OK) {\n\t\t\t\t\tstatus = LDNS_STATUS_SYNTAX_ERR;\n\t\t\t\t\tldns_buffer_free(rr_buf);\n\t\t\t\t\tgoto ldnserror;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (prev) {\n\t\t\t\tldns_rdf_deep_free(*prev);\n\t\t\t\t*prev = ldns_rdf_clone(ldns_rr_owner(new));\n\t\t\t\tif(!*prev) {\n\t\t\t\t\tstatus = LDNS_STATUS_MEM_ERR;\n\t\t\t\t\tldns_buffer_free(rr_buf);\n\t\t\t\t\tgoto ldnserror;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tLDNS_FREE(owner);\n\towner = NULL;\n\n\tldns_rr_set_question(new, question);\n\n\tldns_rr_set_ttl(new, ttl_val);\n\tLDNS_FREE(ttl);\n\tttl = NULL;\n\n\tldns_rr_set_class(new, clas_val);\n\tLDNS_FREE(clas);\n\tclas = NULL;\n\n\trr_type = ldns_get_rr_type_by_name(type);\n\tLDNS_FREE(type);\n\ttype = NULL;\n\n\tdesc = ldns_rr_descript((uint16_t)rr_type);\n\tldns_rr_set_type(new, rr_type);\n\tif (desc) {\n\t\t/* only the rdata remains */\n\t\tr_max = ldns_rr_descriptor_maximum(desc);\n\t\tr_min = ldns_rr_descriptor_minimum(desc);\n\t} else {\n\t\tr_min = 0;\n\t\tr_max = 1;\n\t}\n\n\t/* depending on the rr_type we need to extract\n\t * the rdata differently, e.g. NSEC/NSEC3 */\n\tswitch(rr_type) {\n\t\tdefault:\n\t\t\tdone = false;\n\n\t\t\tfor (r_cnt = 0; !done && r_cnt < r_max; r_cnt++) {\n\t\t\t\tquoted = false;\n\t\t\t\t/* if type = B64, the field may contain spaces */\n\t\t\t\tif (ldns_rr_descriptor_field_type(desc,\n\t\t\t\t\t r_cnt) == LDNS_RDF_TYPE_B64 ||\n\t\t\t\t ldns_rr_descriptor_field_type(desc,\n\t\t\t\t\t r_cnt) == LDNS_RDF_TYPE_HEX ||\n\t\t\t\t ldns_rr_descriptor_field_type(desc,\n\t\t\t\t\t r_cnt) == LDNS_RDF_TYPE_LOC ||\n\t\t\t\t ldns_rr_descriptor_field_type(desc,\n\t\t\t\t\t r_cnt) == LDNS_RDF_TYPE_WKS ||\n\t\t\t\t ldns_rr_descriptor_field_type(desc,\n\t\t\t\t\t r_cnt) == LDNS_RDF_TYPE_IPSECKEY ||\n\t\t\t\t ldns_rr_descriptor_field_type(desc,\n\t\t\t\t\t r_cnt) == LDNS_RDF_TYPE_NSEC) {\n\t\t\t\t\tdelimiters = \"\\n\\t\";\n\t\t\t\t} else {\n\t\t\t\t\tdelimiters = \"\\n\\t \";\n\t\t\t\t}\n\n\t\t\t\tif (ldns_rr_descriptor_field_type(desc,\n\t\t\t\t\t\t\tr_cnt) == LDNS_RDF_TYPE_STR &&\n\t\t\t\t\t\t\tldns_buffer_remaining(rd_buf) > 0) {\n\t\t\t\t\t/* skip spaces */\n\t\t\t\t\twhile (*(ldns_buffer_current(rd_buf)) == ' ') {\n\t\t\t\t\t\tldns_buffer_skip(rd_buf, 1);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (*(ldns_buffer_current(rd_buf)) == '\\\"') {\n\t\t\t\t\t\tdelimiters = \"\\\"\\0\";\n\t\t\t\t\t\tldns_buffer_skip(rd_buf, 1);\n\t\t\t\t\t\tquoted = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/* because number of fields can be variable, we can't\n\t\t\t\t rely on _maximum() only */\n\t\t\t\t/* skip spaces */\n\t\t\t\twhile (ldns_buffer_position(rd_buf) < ldns_buffer_limit(rd_buf) &&\n\t\t\t\t\t*(ldns_buffer_current(rd_buf)) == ' ' && !quoted\n\t\t\t\t ) {\n\t\t\t\t\tldns_buffer_skip(rd_buf, 1);\n\t\t\t\t}\n\n\t\t\t\tpre_data_pos = ldns_buffer_position(rd_buf);\n\t\t\t\tif ((c = ldns_bget_token(rd_buf, rd, delimiters,\n\t\t\t\t\t\t\tLDNS_MAX_RDFLEN)) != -1) {\n\t\t\t\t\t/* hmmz, rfc3597 specifies that any type can be represented with\n\t\t\t\t\t * \\# method, which can contain spaces...\n\t\t\t\t\t * it does specify size though...\n\t\t\t\t\t */\n\t\t\t\t\trd_strlen = strlen(rd);\n\n\t\t\t\t\t/* unknown RR data */\n\t\t\t\t\tif (strncmp(rd, \"\\\\#\", 2) == 0 && !quoted && (rd_strlen == 2 || rd[2]==' ')) {\n \tuint16_t hex_data_size;\n char *hex_data_str;\n uint16_t cur_hex_data_size;\n\n was_unknown_rr_format = 1;\n /* go back to before \\# and skip it while setting delimiters better */\n ldns_buffer_set_position(rd_buf, pre_data_pos);\n\t\t\t\t\t delimiters = \"\\n\\t \";\n (void)ldns_bget_token(rd_buf, rd, delimiters, LDNS_MAX_RDFLEN);\n /* read rdata octet length */\n\t\t\t\t\t\tc = ldns_bget_token(rd_buf, rd, delimiters, LDNS_MAX_RDFLEN);\n\t\t\t\t\t\tif (c == -1) {\n\t\t\t\t\t\t\t/* something goes very wrong here */\n LDNS_FREE(rd);\n LDNS_FREE(b64);\n ldns_buffer_free(rd_buf);\n ldns_buffer_free(rr_buf);\n LDNS_FREE(rdata);\n ldns_rr_free(new);\n\t\t\t\t\t\t\treturn LDNS_STATUS_SYNTAX_RDATA_ERR;\n\t\t\t\t\t\t}\n\t\t\t\t\t\thex_data_size = (uint16_t) atoi(rd);\n\t\t\t\t\t\t/* copy the hex chars into hex str (which is 2 chars per byte) */\n\t\t\t\t\t\thex_data_str = LDNS_XMALLOC(char, 2 * hex_data_size + 1);\n\t\t\t\t\t\tif (!hex_data_str) {\n\t\t\t\t\t\t\t/* malloc error */\n LDNS_FREE(rd);\n LDNS_FREE(b64);\n ldns_buffer_free(rd_buf);\n ldns_buffer_free(rr_buf);\n LDNS_FREE(rdata);\n ldns_rr_free(new);\n\t\t\t\t\t\t\treturn LDNS_STATUS_SYNTAX_RDATA_ERR;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcur_hex_data_size = 0;\n\t\t\t\t\t\twhile(cur_hex_data_size < 2 * hex_data_size) {\n\t\t\t\t\t\t\tc = ldns_bget_token(rd_buf, rd, delimiters, LDNS_MAX_RDFLEN);\n\t\t\t\t\t\t\tif (c != -1) {\n\t\t\t\t\t\t\t\trd_strlen = strlen(rd);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (c == -1 || (size_t)cur_hex_data_size + rd_strlen > 2 * (size_t)hex_data_size) {\n\t\t\t\t\t\t\t\tLDNS_FREE(hex_data_str);\n\t\t\t\t\t\t\t\tLDNS_FREE(rd);\n\t\t\t\t\t\t\t\tLDNS_FREE(b64);\n\t\t\t\t\t\t\t\tldns_buffer_free(rd_buf);\n\t\t\t\t\t\t\t\tldns_buffer_free(rr_buf);\n\t\t\t\t\t\t\t\tLDNS_FREE(rdata);\n\t\t\t\t\t\t\t\tldns_rr_free(new);\n\t\t\t\t\t\t\t\treturn LDNS_STATUS_SYNTAX_RDATA_ERR;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tstrncpy(hex_data_str + cur_hex_data_size, rd, rd_strlen);\n\t\t\t\t\t\t\tcur_hex_data_size += rd_strlen;\n\t\t\t\t\t\t}\n\t\t\t\t\t\thex_data_str[cur_hex_data_size] = '\\0';\n\n\t\t\t\t\t\t/* correct the rdf type */\n\t\t\t\t\t\t/* if *we* know the type, interpret it as wireformat */\n\t\t\t\t\t\tif (desc) {\n\t\t\t\t\t\t\tsize_t hex_pos = 0;\n\t\t\t\t\t\t\tuint8_t *hex_data = LDNS_XMALLOC(uint8_t, hex_data_size + 2);\n ldns_status s;\n if(!hex_data) {\n LDNS_FREE(hex_data_str);\n LDNS_FREE(rd);\n LDNS_FREE(b64);\n ldns_buffer_free(rd_buf);\n ldns_buffer_free(rr_buf);\n LDNS_FREE(rdata);\n ldns_rr_free(new);\n return LDNS_STATUS_MEM_ERR;\n }\n\t\t\t\t\t\t\tldns_write_uint16(hex_data, hex_data_size);\n\t\t\t\t\t\t\tldns_hexstring_to_data(hex_data + 2, hex_data_str);\n\t\t\t\t\t\t\ts = ldns_wire2rdf(new, hex_data,\n\t\t\t\t\t\t\t hex_data_size+2, &hex_pos);\n if(s != LDNS_STATUS_OK) {\n LDNS_FREE(hex_data_str);\n LDNS_FREE(rd);\n LDNS_FREE(b64);\n ldns_buffer_free(rd_buf);\n ldns_buffer_free(rr_buf);\n LDNS_FREE(rdata);\n ldns_rr_free(new);\n\t\t\t\t\t\t\t\tLDNS_FREE(hex_data);\n return s;\n }\n\t\t\t\t\t\t\tLDNS_FREE(hex_data);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tr = ldns_rdf_new_frm_str(LDNS_RDF_TYPE_HEX, hex_data_str);\n if(!r) {\n LDNS_FREE(hex_data_str);\n LDNS_FREE(rd);\n LDNS_FREE(b64);\n ldns_buffer_free(rd_buf);\n ldns_buffer_free(rr_buf);\n LDNS_FREE(rdata);\n ldns_rr_free(new);\n return LDNS_STATUS_MEM_ERR;\n }\n\t\t\t\t\t\t\tldns_rdf_set_type(r, LDNS_RDF_TYPE_UNKNOWN);\n\t\t\t\t\t\t\tif(!ldns_rr_push_rdf(new, r)) {\n LDNS_FREE(hex_data_str);\n LDNS_FREE(rd);\n LDNS_FREE(b64);\n ldns_buffer_free(rd_buf);\n ldns_buffer_free(rr_buf);\n LDNS_FREE(rdata);\n ldns_rr_free(new);\n return LDNS_STATUS_MEM_ERR;\n }\n\t\t\t\t\t\t}\n\t\t\t\t\t\tLDNS_FREE(hex_data_str);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t/* Normal RR */\n\t\t\t\t\t\tswitch(ldns_rr_descriptor_field_type(desc, r_cnt)) {\n\t\t\t\t\t\tcase LDNS_RDF_TYPE_HEX:\n\t\t\t\t\t\tcase LDNS_RDF_TYPE_B64:\n\t\t\t\t\t\t\t/* can have spaces, and will always be the last\n\t\t\t\t\t\t\t * record of the rrdata. Read in the rest */\n\t\t\t\t\t\t\tif ((c = ldns_bget_token(rd_buf,\n\t\t\t\t\t\t\t\t\t\t\t\tb64,\n\t\t\t\t\t\t\t\t\t\t\t\t\"\\n\",\n\t\t\t\t\t\t\t\t\t\t\t\tLDNS_MAX_RDFLEN))\n\t\t\t\t\t\t\t != -1) {\n\t\t\t\t\t\t\t\trd = strncat(rd,\n\t\t\t\t\t\t\t\t\t\t b64,\n\t\t\t\t\t\t\t\t\t\t LDNS_MAX_RDFLEN\n\t\t\t\t\t\t\t\t\t\t - strlen(rd) - 1);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tr = ldns_rdf_new_frm_str(\n\t\t\t\t\t\t\t\t\tldns_rr_descriptor_field_type(desc, r_cnt),\n\t\t\t\t\t\t\t\t\trd);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase LDNS_RDF_TYPE_DNAME:\n\t\t\t\t\t\t\tr = ldns_rdf_new_frm_str(\n\t\t\t\t\t\t\t\t\tldns_rr_descriptor_field_type(desc, r_cnt),\n\t\t\t\t\t\t\t\t\trd);\n\n\t\t\t\t\t\t\t/* check if the origin should be used or concatenated */\n\t\t\t\t\t\t\tif (r && ldns_rdf_size(r) > 1 && ldns_rdf_data(r)[0] == 1\n\t\t\t\t\t\t\t\t&& ldns_rdf_data(r)[1] == '@') {\n\t\t\t\t\t\t\t\tldns_rdf_deep_free(r);\n\t\t\t\t\t\t\t\tif (origin) {\n\t\t\t\t\t\t\t\t\tr = ldns_rdf_clone(origin);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t /* if this is the SOA, use its own owner name */\n\t\t\t\t\t\t\t\t\tif (rr_type == LDNS_RR_TYPE_SOA) {\n\t\t\t\t\t\t\t\t\t\tr = ldns_rdf_clone(ldns_rr_owner(new));\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tr = ldns_rdf_new_frm_str(LDNS_RDF_TYPE_DNAME, \".\");\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} else if (r && rd_strlen >= 1 && !ldns_dname_str_absolute(rd) && origin) {\n\t\t\t\t\t\t\t\tif (ldns_dname_cat(r, origin) != LDNS_STATUS_OK) {\n\t\t\t\t\t\t\t LDNS_FREE(rd);\n\t\t\t\t\t\t\t LDNS_FREE(b64);\n\t\t\t\t\t\t\t ldns_buffer_free(rd_buf);\n\t\t\t\t\t\t\t ldns_buffer_free(rr_buf);\n\t\t\t\t\t\t\t LDNS_FREE(rdata);\n\t\t\t\t\t\t\t ldns_rr_free(new);\n\t\t\t\t\t\t\t\t\treturn LDNS_STATUS_ERR;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tr = ldns_rdf_new_frm_str(\n\t\t\t\t\t\t\t\t\tldns_rr_descriptor_field_type(desc, r_cnt),\n\t\t\t\t\t\t\t\t\trd);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (r) {\n\t\t\t\t\t\t\tldns_rr_push_rdf(new, r);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tLDNS_FREE(rd);\n\t\t\t\t\t\t\tLDNS_FREE(b64);\n\t\t\t\t\t\t\tldns_buffer_free(rd_buf);\n\t\t\t\t\t\t\tldns_buffer_free(rr_buf);\n\t\t\t\t\t\t\tLDNS_FREE(rdata);\n\t\t\t\t\t\t\tldns_rr_free(new);\n\t\t\t\t\t\t\treturn LDNS_STATUS_SYNTAX_RDATA_ERR;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (quoted) {\n\t\t\t\t\t\tif (ldns_buffer_available(rd_buf, 1)) {\n\t\t\t\t\t\t\tldns_buffer_skip(rd_buf, 1);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdone = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tdone = true;\n\t\t\t\t}\n\t\t\t}\n\t}\n\tLDNS_FREE(rd);\n\tLDNS_FREE(b64);\n\tldns_buffer_free(rd_buf);\n\tldns_buffer_free(rr_buf);\n\tLDNS_FREE(rdata);\n\n\tif (!question && desc && !was_unknown_rr_format && ldns_rr_rd_count(new) < r_min) {\n\t\tldns_rr_free(new);\n\t\treturn LDNS_STATUS_SYNTAX_MISSING_VALUE_ERR;\n\t}\n\n\tif (newrr) {\n\t\t*newrr = new;\n\t} else {\n\t\t/* Maybe the caller just wanted to see if it would parse? */\n\t\tldns_rr_free(new);\n\t}\n\treturn LDNS_STATUS_OK;\n\nldnserror:\n\tLDNS_FREE(type);\n\tLDNS_FREE(owner);\n\tLDNS_FREE(ttl);\n\tLDNS_FREE(clas);\n\tLDNS_FREE(rdata);\n\tLDNS_FREE(rd);\n\tLDNS_FREE(rd_buf);\n\tLDNS_FREE(b64);\n\tldns_rr_free(new);\n return status;\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 int __init drbg_init(void)\n{\n\tunsigned int i = 0; /* pointer to drbg_algs */\n\tunsigned int j = 0; /* pointer to drbg_cores */\n\tint ret = -EFAULT;\n\n\tret = drbg_healthcheck_sanity();\n\tif (ret)\n\t\treturn ret;\n\n\tif (ARRAY_SIZE(drbg_cores) * 2 > ARRAY_SIZE(drbg_algs)) {\n\t\tpr_info(\"DRBG: Cannot register all DRBG types\"\n\t\t\t\"(slots needed: %zu, slots available: %zu)\\n\",\n\t\t\tARRAY_SIZE(drbg_cores) * 2, ARRAY_SIZE(drbg_algs));\n\t\treturn ret;\n\t}\n\n\t/*\n\t * each DRBG definition can be used with PR and without PR, thus\n\t * we instantiate each DRBG in drbg_cores[] twice.\n\t *\n\t * As the order of placing them into the drbg_algs array matters\n\t * (the later DRBGs receive a higher cra_priority) we register the\n\t * prediction resistance DRBGs first as the should not be too\n\t * interesting.\n\t */\n\tfor (j = 0; ARRAY_SIZE(drbg_cores) > j; j++, i++)\n\t\tdrbg_fill_array(&drbg_algs[i], &drbg_cores[j], 1);\n\tfor (j = 0; ARRAY_SIZE(drbg_cores) > j; j++, i++)\n\t\tdrbg_fill_array(&drbg_algs[i], &drbg_cores[j], 0);\n\treturn crypto_register_algs(drbg_algs, (ARRAY_SIZE(drbg_cores) * 2));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'crypto: drbg - Convert to new rng interface\n\nThis patch converts the DRBG implementation to the new low-level\nrng interface.\n\nThis allows us to get rid of struct drbg_gen by using the new RNG\nAPI instead.\n\nSigned-off-by: Herbert Xu \nAcked-by: Stephan Mueller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void file_checksum(const char *fname, const STRUCT_STAT *st_p, char *sum)\n{\n\tstruct map_struct *buf;\n\tOFF_T i, len = st_p->st_size;\n\tmd_context m;\n\tint32 remainder;\n\tint fd;\n\n\tmemset(sum, 0, MAX_DIGEST_LEN);\n\n\tfd = do_open(fname, O_RDONLY, 0);\n\tif (fd == -1)\n\t\treturn;\n\n\tbuf = map_file(fd, len, MAX_MAP_SIZE, CSUM_CHUNK);\n\n\tswitch (checksum_type) {\n\t case CSUM_MD5:\n\t\tmd5_begin(&m);\n\n\t\tfor (i = 0; i + CSUM_CHUNK <= len; i += CSUM_CHUNK) {\n\t\t\tmd5_update(&m, (uchar *)map_ptr(buf, i, CSUM_CHUNK),\n\t\t\t\t CSUM_CHUNK);\n\t\t}\n\n\t\tremainder = (int32)(len - i);\n\t\tif (remainder > 0)\n\t\t\tmd5_update(&m, (uchar *)map_ptr(buf, i, remainder), remainder);\n\n\t\tmd5_result(&m, (uchar *)sum);\n\t\tbreak;\n\t case CSUM_MD4:\n\t case CSUM_MD4_OLD:\n\t case CSUM_MD4_BUSTED:\n\t\tmdfour_begin(&m);\n\n\t\tfor (i = 0; i + CSUM_CHUNK <= len; i += CSUM_CHUNK) {\n\t\t\tmdfour_update(&m, (uchar *)map_ptr(buf, i, CSUM_CHUNK),\n\t\t\t\t CSUM_CHUNK);\n\t\t}\n\n\t\t/* Prior to version 27 an incorrect MD4 checksum was computed\n\t\t * by failing to call mdfour_tail() for block sizes that\n\t\t * are multiples of 64. This is fixed by calling mdfour_update()\n\t\t * even when there are no more bytes. */\n\t\tremainder = (int32)(len - i);\n\t\tif (remainder > 0 || checksum_type != CSUM_MD4_BUSTED)\n\t\t\tmdfour_update(&m, (uchar *)map_ptr(buf, i, remainder), remainder);\n\n\t\tmdfour_result(&m, (uchar *)sum);\n\t\tbreak;\n\t default:\n\t\trprintf(FERROR, \"invalid checksum-choice for the --checksum option (%d)\\n\", checksum_type);\n\t\texit_cleanup(RERR_UNSUPPORTED);\n\t}\n\n\tclose(fd);\n\tunmap_file(buf);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-354'], 'message': 'Handle archaic checksums properly.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool ParseState::do_string(CephContext* cct, const char* s, size_t l) {\n auto k = pp->tokens.lookup(s, l);\n Policy& p = pp->policy;\n bool is_action = false;\n bool is_validaction = false;\n Statement* t = p.statements.empty() ? nullptr : &(p.statements.back());\n\n // Top level!\n if ((w->id == TokenID::Version) && k &&\n k->kind == TokenKind::version_key) {\n p.version = static_cast(k->specific);\n } else if (w->id == TokenID::Id) {\n p.id = string(s, l);\n\n // Statement\n\n } else if (w->id == TokenID::Sid) {\n t->sid.emplace(s, l);\n } else if ((w->id == TokenID::Effect) &&\n\t k->kind == TokenKind::effect_key) {\n t->effect = static_cast(k->specific);\n } else if (w->id == TokenID::Principal && s && *s == '*') {\n t->princ.emplace(Principal::wildcard());\n } else if (w->id == TokenID::NotPrincipal && s && *s == '*') {\n t->noprinc.emplace(Principal::wildcard());\n } else if ((w->id == TokenID::Action) ||\n\t (w->id == TokenID::NotAction)) {\n is_action = true;\n for (auto& p : actpairs) {\n if (match_policy({s, l}, p.name, MATCH_POLICY_ACTION)) {\n is_validaction = true;\n\t(w->id == TokenID::Action ? t->action : t->notaction) |= p.bit;\n }\n }\n } else if (w->id == TokenID::Resource || w->id == TokenID::NotResource) {\n auto a = ARN::parse({s, l}, true);\n // You can't specify resources for someone ELSE'S account.\n if (a && (a->account.empty() || a->account == pp->tenant ||\n\t a->account == \"*\")) {\n if (a->account.empty() || a->account == \"*\")\n\ta->account = pp->tenant;\n (w->id == TokenID::Resource ? t->resource : t->notresource)\n\t.emplace(std::move(*a));\n }\n else\n ldout(cct, 0) << \"Supplied resource is discarded: \" << string(s, l)\n\t\t << dendl;\n } else if (w->kind == TokenKind::cond_key) {\n auto& t = pp->policy.statements.back();\n t.conditions.back().vals.emplace_back(s, l);\n\n // Principals\n\n } else if (w->kind == TokenKind::princ_type) {\n ceph_assert(pp->s.size() > 1);\n auto& pri = pp->s[pp->s.size() - 2].w->id == TokenID::Principal ?\n t->princ : t->noprinc;\n\n auto o = parse_principal(pp->cct, w->id, string(s, l));\n if (o)\n pri.emplace(std::move(*o));\n\n // Failure\n\n } else {\n return false;\n }\n\n if (!arraying) {\n pp->s.pop_back();\n }\n\n if (is_action && !is_validaction){\n return false;\n }\n\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'rgw: Remove assertions in IAM Policy\n\nA couple of them could be triggered by user input.\n\nSigned-off-by: Adam C. Emerson '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static 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\treturn;\n\n\tkfree(fepriv);\n\tfe->frontend_priv = NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'dvb_frontend: don't use-after-free the frontend struct\n\ndvb_frontend_invoke_release() may free the frontend struct.\nSo, the free logic can't update it anymore after calling it.\n\nThat's OK, as __dvb_frontend_free() is called only when the\nkrefs are zeroed, so nobody is using it anymore.\n\nThat should fix the following KASAN error:\n\nThe KASAN report looks like this (running on kernel 3e0cc09a3a2c40ec1ffb6b4e12da86e98feccb11 (4.14-rc5+)):\n==================================================================\nBUG: KASAN: use-after-free in __dvb_frontend_free+0x113/0x120\nWrite of size 8 at addr ffff880067d45a00 by task kworker/0:1/24\n\nCPU: 0 PID: 24 Comm: kworker/0:1 Not tainted 4.14.0-rc5-43687-g06ab8a23e0e6 #545\nHardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011\nWorkqueue: usb_hub_wq hub_event\nCall Trace:\n __dump_stack lib/dump_stack.c:16\n dump_stack+0x292/0x395 lib/dump_stack.c:52\n print_address_description+0x78/0x280 mm/kasan/report.c:252\n kasan_report_error mm/kasan/report.c:351\n kasan_report+0x23d/0x350 mm/kasan/report.c:409\n __asan_report_store8_noabort+0x1c/0x20 mm/kasan/report.c:435\n __dvb_frontend_free+0x113/0x120 drivers/media/dvb-core/dvb_frontend.c:156\n dvb_frontend_put+0x59/0x70 drivers/media/dvb-core/dvb_frontend.c:176\n dvb_frontend_detach+0x120/0x150 drivers/media/dvb-core/dvb_frontend.c:2803\n dvb_usb_adapter_frontend_exit+0xd6/0x160 drivers/media/usb/dvb-usb/dvb-usb-dvb.c:340\n dvb_usb_adapter_exit drivers/media/usb/dvb-usb/dvb-usb-init.c:116\n dvb_usb_exit+0x9b/0x200 drivers/media/usb/dvb-usb/dvb-usb-init.c:132\n dvb_usb_device_exit+0xa5/0xf0 drivers/media/usb/dvb-usb/dvb-usb-init.c:295\n usb_unbind_interface+0x21c/0xa90 drivers/usb/core/driver.c:423\n __device_release_driver drivers/base/dd.c:861\n device_release_driver_internal+0x4f1/0x5c0 drivers/base/dd.c:893\n device_release_driver+0x1e/0x30 drivers/base/dd.c:918\n bus_remove_device+0x2f4/0x4b0 drivers/base/bus.c:565\n device_del+0x5c4/0xab0 drivers/base/core.c:1985\n usb_disable_device+0x1e9/0x680 drivers/usb/core/message.c:1170\n usb_disconnect+0x260/0x7a0 drivers/usb/core/hub.c:2124\n hub_port_connect drivers/usb/core/hub.c:4754\n hub_port_connect_change drivers/usb/core/hub.c:5009\n port_event drivers/usb/core/hub.c:5115\n hub_event+0x1318/0x3740 drivers/usb/core/hub.c:5195\n process_one_work+0xc73/0x1d90 kernel/workqueue.c:2119\n worker_thread+0x221/0x1850 kernel/workqueue.c:2253\n kthread+0x363/0x440 kernel/kthread.c:231\n ret_from_fork+0x2a/0x40 arch/x86/entry/entry_64.S:431\n\nAllocated by task 24:\n save_stack_trace+0x1b/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\n kasan_kmalloc+0xad/0xe0 mm/kasan/kasan.c:551\n kmem_cache_alloc_trace+0x11e/0x2d0 mm/slub.c:2772\n kmalloc ./include/linux/slab.h:493\n kzalloc ./include/linux/slab.h:666\n dtt200u_fe_attach+0x4c/0x110 drivers/media/usb/dvb-usb/dtt200u-fe.c:212\n dtt200u_frontend_attach+0x35/0x80 drivers/media/usb/dvb-usb/dtt200u.c:136\n dvb_usb_adapter_frontend_init+0x32b/0x660 drivers/media/usb/dvb-usb/dvb-usb-dvb.c:286\n dvb_usb_adapter_init drivers/media/usb/dvb-usb/dvb-usb-init.c:86\n dvb_usb_init drivers/media/usb/dvb-usb/dvb-usb-init.c:162\n dvb_usb_device_init+0xf73/0x17f0 drivers/media/usb/dvb-usb/dvb-usb-init.c:277\n dtt200u_usb_probe+0xa1/0xe0 drivers/media/usb/dvb-usb/dtt200u.c:155\n usb_probe_interface+0x35d/0x8e0 drivers/usb/core/driver.c:361\n really_probe drivers/base/dd.c:413\n driver_probe_device+0x610/0xa00 drivers/base/dd.c:557\n __device_attach_driver+0x230/0x290 drivers/base/dd.c:653\n bus_for_each_drv+0x161/0x210 drivers/base/bus.c:463\n __device_attach+0x26b/0x3c0 drivers/base/dd.c:710\n device_initial_probe+0x1f/0x30 drivers/base/dd.c:757\n bus_probe_device+0x1eb/0x290 drivers/base/bus.c:523\n device_add+0xd0b/0x1660 drivers/base/core.c:1835\n usb_set_configuration+0x104e/0x1870 drivers/usb/core/message.c:1932\n generic_probe+0x73/0xe0 drivers/usb/core/generic.c:174\n usb_probe_device+0xaf/0xe0 drivers/usb/core/driver.c:266\n really_probe drivers/base/dd.c:413\n driver_probe_device+0x610/0xa00 drivers/base/dd.c:557\n __device_attach_driver+0x230/0x290 drivers/base/dd.c:653\n bus_for_each_drv+0x161/0x210 drivers/base/bus.c:463\n __device_attach+0x26b/0x3c0 drivers/base/dd.c:710\n device_initial_probe+0x1f/0x30 drivers/base/dd.c:757\n bus_probe_device+0x1eb/0x290 drivers/base/bus.c:523\n device_add+0xd0b/0x1660 drivers/base/core.c:1835\n usb_new_device+0x7b8/0x1020 drivers/usb/core/hub.c:2457\n hub_port_connect drivers/usb/core/hub.c:4903\n hub_port_connect_change drivers/usb/core/hub.c:5009\n port_event drivers/usb/core/hub.c:5115\n hub_event+0x194d/0x3740 drivers/usb/core/hub.c:5195\n process_one_work+0xc73/0x1d90 kernel/workqueue.c:2119\n worker_thread+0x221/0x1850 kernel/workqueue.c:2253\n kthread+0x363/0x440 kernel/kthread.c:231\n ret_from_fork+0x2a/0x40 arch/x86/entry/entry_64.S:431\n\nFreed by task 24:\n save_stack_trace+0x1b/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\n kasan_slab_free+0x72/0xc0 mm/kasan/kasan.c:524\n slab_free_hook mm/slub.c:1390\n slab_free_freelist_hook mm/slub.c:1412\n slab_free mm/slub.c:2988\n kfree+0xf6/0x2f0 mm/slub.c:3919\n dtt200u_fe_release+0x3c/0x50 drivers/media/usb/dvb-usb/dtt200u-fe.c:202\n dvb_frontend_invoke_release.part.13+0x1c/0x30 drivers/media/dvb-core/dvb_frontend.c:2790\n dvb_frontend_invoke_release drivers/media/dvb-core/dvb_frontend.c:2789\n __dvb_frontend_free+0xad/0x120 drivers/media/dvb-core/dvb_frontend.c:153\n dvb_frontend_put+0x59/0x70 drivers/media/dvb-core/dvb_frontend.c:176\n dvb_frontend_detach+0x120/0x150 drivers/media/dvb-core/dvb_frontend.c:2803\n dvb_usb_adapter_frontend_exit+0xd6/0x160 drivers/media/usb/dvb-usb/dvb-usb-dvb.c:340\n dvb_usb_adapter_exit drivers/media/usb/dvb-usb/dvb-usb-init.c:116\n dvb_usb_exit+0x9b/0x200 drivers/media/usb/dvb-usb/dvb-usb-init.c:132\n dvb_usb_device_exit+0xa5/0xf0 drivers/media/usb/dvb-usb/dvb-usb-init.c:295\n usb_unbind_interface+0x21c/0xa90 drivers/usb/core/driver.c:423\n __device_release_driver drivers/base/dd.c:861\n device_release_driver_internal+0x4f1/0x5c0 drivers/base/dd.c:893\n device_release_driver+0x1e/0x30 drivers/base/dd.c:918\n bus_remove_device+0x2f4/0x4b0 drivers/base/bus.c:565\n device_del+0x5c4/0xab0 drivers/base/core.c:1985\n usb_disable_device+0x1e9/0x680 drivers/usb/core/message.c:1170\n usb_disconnect+0x260/0x7a0 drivers/usb/core/hub.c:2124\n hub_port_connect drivers/usb/core/hub.c:4754\n hub_port_connect_change drivers/usb/core/hub.c:5009\n port_event drivers/usb/core/hub.c:5115\n hub_event+0x1318/0x3740 drivers/usb/core/hub.c:5195\n process_one_work+0xc73/0x1d90 kernel/workqueue.c:2119\n worker_thread+0x221/0x1850 kernel/workqueue.c:2253\n kthread+0x363/0x440 kernel/kthread.c:231\n ret_from_fork+0x2a/0x40 arch/x86/entry/entry_64.S:431\n\nThe buggy address belongs to the object at ffff880067d45500\n which belongs to the cache kmalloc-2048 of size 2048\nThe buggy address is located 1280 bytes inside of\n 2048-byte region [ffff880067d45500, ffff880067d45d00)\nThe buggy address belongs to the page:\npage:ffffea00019f5000 count:1 mapcount:0 mapping: (null)\nindex:0x0 compound_mapcount: 0\nflags: 0x100000000008100(slab|head)\nraw: 0100000000008100 0000000000000000 0000000000000000 00000001000f000f\nraw: dead000000000100 dead000000000200 ffff88006c002d80 0000000000000000\npage dumped because: kasan: bad access detected\n\nMemory state around the buggy address:\n ffff880067d45900: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n ffff880067d45980: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n ffff880067d45a00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n ^\n ffff880067d45a80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n ffff880067d45b00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n==================================================================\n\nFixes: ead666000a5f (\"media: dvb_frontend: only use kref after initialized\")\n\nReported-by: Andrey Konovalov \nSuggested-by: Matthias Schwarzott \nTested-by: Andrey Konovalov \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 mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,\n\tstruct user_namespace *user_ns)\n{\n\tmm->mmap = NULL;\n\tmm->mm_rb = RB_ROOT;\n\tmm->vmacache_seqnum = 0;\n\tatomic_set(&mm->mm_users, 1);\n\tatomic_set(&mm->mm_count, 1);\n\tinit_rwsem(&mm->mmap_sem);\n\tINIT_LIST_HEAD(&mm->mmlist);\n\tmm->core_state = NULL;\n\tatomic_long_set(&mm->nr_ptes, 0);\n\tmm_nr_pmds_init(mm);\n\tmm->map_count = 0;\n\tmm->locked_vm = 0;\n\tmm->pinned_vm = 0;\n\tmemset(&mm->rss_stat, 0, sizeof(mm->rss_stat));\n\tspin_lock_init(&mm->page_table_lock);\n\tmm_init_cpumask(mm);\n\tmm_init_aio(mm);\n\tmm_init_owner(mm, p);\n\tRCU_INIT_POINTER(mm->exe_file, NULL);\n\tmmu_notifier_mm_init(mm);\n\tinit_tlb_flush_pending(mm);\n#if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS\n\tmm->pmd_huge_pte = NULL;\n#endif\n\n\tif (current->mm) {\n\t\tmm->flags = current->mm->flags & MMF_INIT_MASK;\n\t\tmm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;\n\t} else {\n\t\tmm->flags = default_dump_filter;\n\t\tmm->def_flags = 0;\n\t}\n\n\tif (mm_alloc_pgd(mm))\n\t\tgoto fail_nopgd;\n\n\tif (init_new_context(p, mm))\n\t\tgoto fail_nocontext;\n\n\tmm->user_ns = get_user_ns(user_ns);\n\treturn mm;\n\nfail_nocontext:\n\tmm_free_pgd(mm);\nfail_nopgd:\n\tfree_mm(mm);\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'mm, uprobes: fix multiple free of ->uprobes_state.xol_area\n\nCommit 7c051267931a (\"mm, fork: make dup_mmap wait for mmap_sem for\nwrite killable\") made it possible to kill a forking task while it is\nwaiting to acquire its ->mmap_sem for write, in dup_mmap().\n\nHowever, it was overlooked that this introduced an new error path before\nthe new mm_struct's ->uprobes_state.xol_area has been set to NULL after\nbeing copied from the old mm_struct by the memcpy in dup_mm(). For a\ntask that has previously hit a uprobe tracepoint, this resulted in the\n'struct xol_area' being freed multiple times if the task was killed at\njust the right time while forking.\n\nFix it by setting ->uprobes_state.xol_area to NULL in mm_init() rather\nthan in uprobe_dup_mmap().\n\nWith CONFIG_UPROBE_EVENTS=y, the bug can be reproduced by the same C\nprogram given by commit 2b7e8665b4ff (\"fork: fix incorrect fput of\n->exe_file causing use-after-free\"), provided that a uprobe tracepoint\nhas been set on the fork_thread() function. For example:\n\n $ gcc reproducer.c -o reproducer -lpthread\n $ nm reproducer | grep fork_thread\n 0000000000400719 t fork_thread\n $ echo \"p $PWD/reproducer:0x719\" > /sys/kernel/debug/tracing/uprobe_events\n $ echo 1 > /sys/kernel/debug/tracing/events/uprobes/enable\n $ ./reproducer\n\nHere is the use-after-free reported by KASAN:\n\n BUG: KASAN: use-after-free in uprobe_clear_state+0x1c4/0x200\n Read of size 8 at addr ffff8800320a8b88 by task reproducer/198\n\n CPU: 1 PID: 198 Comm: reproducer Not tainted 4.13.0-rc7-00015-g36fde05f3fb5 #255\n Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-20170228_101828-anatol 04/01/2014\n Call Trace:\n dump_stack+0xdb/0x185\n print_address_description+0x7e/0x290\n kasan_report+0x23b/0x350\n __asan_report_load8_noabort+0x19/0x20\n uprobe_clear_state+0x1c4/0x200\n mmput+0xd6/0x360\n do_exit+0x740/0x1670\n do_group_exit+0x13f/0x380\n get_signal+0x597/0x17d0\n do_signal+0x99/0x1df0\n exit_to_usermode_loop+0x166/0x1e0\n syscall_return_slowpath+0x258/0x2c0\n entry_SYSCALL_64_fastpath+0xbc/0xbe\n\n ...\n\n Allocated by task 199:\n save_stack_trace+0x1b/0x20\n kasan_kmalloc+0xfc/0x180\n kmem_cache_alloc_trace+0xf3/0x330\n __create_xol_area+0x10f/0x780\n uprobe_notify_resume+0x1674/0x2210\n exit_to_usermode_loop+0x150/0x1e0\n prepare_exit_to_usermode+0x14b/0x180\n retint_user+0x8/0x20\n\n Freed by task 199:\n save_stack_trace+0x1b/0x20\n kasan_slab_free+0xa8/0x1a0\n kfree+0xba/0x210\n uprobe_clear_state+0x151/0x200\n mmput+0xd6/0x360\n copy_process.part.8+0x605f/0x65d0\n _do_fork+0x1a5/0xbd0\n SyS_clone+0x19/0x20\n do_syscall_64+0x22f/0x660\n return_from_SYSCALL_64+0x0/0x7a\n\nNote: without KASAN, you may instead see a \"Bad page state\" message, or\nsimply a general protection fault.\n\nLink: http://lkml.kernel.org/r/20170830033303.17927-1-ebiggers3@gmail.com\nFixes: 7c051267931a (\"mm, fork: make dup_mmap wait for mmap_sem for write killable\")\nSigned-off-by: Eric Biggers \nReported-by: Oleg Nesterov \nAcked-by: Oleg Nesterov \nCc: Alexander Shishkin \nCc: Arnaldo Carvalho de Melo \nCc: Dmitry Vyukov \nCc: Ingo Molnar \nCc: Konstantin Khlebnikov \nCc: Mark Rutland \nCc: Michal Hocko \nCc: Peter Zijlstra \nCc: Vlastimil Babka \nCc: [4.7+]\nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: readfile(\n char_u\t*fname,\n char_u\t*sfname,\n linenr_T\tfrom,\n linenr_T\tlines_to_skip,\n linenr_T\tlines_to_read,\n exarg_T\t*eap,\t\t\t/* can be NULL! */\n int\t\tflags)\n{\n int\t\tfd = 0;\n int\t\tnewfile = (flags & READ_NEW);\n int\t\tcheck_readonly;\n int\t\tfiltering = (flags & READ_FILTER);\n int\t\tread_stdin = (flags & READ_STDIN);\n int\t\tread_buffer = (flags & READ_BUFFER);\n int\t\tread_fifo = (flags & READ_FIFO);\n int\t\tset_options = newfile || read_buffer\n\t\t\t\t\t || (eap != NULL && eap->read_edit);\n linenr_T\tread_buf_lnum = 1;\t/* next line to read from curbuf */\n colnr_T\tread_buf_col = 0;\t/* next char to read from this line */\n char_u\tc;\n linenr_T\tlnum = from;\n char_u\t*ptr = NULL;\t\t/* pointer into read buffer */\n char_u\t*buffer = NULL;\t\t/* read buffer */\n char_u\t*new_buffer = NULL;\t/* init to shut up gcc */\n char_u\t*line_start = NULL;\t/* init to shut up gcc */\n int\t\twasempty;\t\t/* buffer was empty before reading */\n colnr_T\tlen;\n long\tsize = 0;\n char_u\t*p;\n off_T\tfilesize = 0;\n int\t\tskip_read = FALSE;\n#ifdef FEAT_CRYPT\n char_u\t*cryptkey = NULL;\n int\t\tdid_ask_for_key = FALSE;\n#endif\n#ifdef FEAT_PERSISTENT_UNDO\n context_sha256_T sha_ctx;\n int\t\tread_undo_file = FALSE;\n#endif\n int\t\tsplit = 0;\t\t/* number of split lines */\n#define UNKNOWN\t 0x0fffffff\t\t/* file size is unknown */\n linenr_T\tlinecnt;\n int\t\terror = FALSE;\t\t/* errors encountered */\n int\t\tff_error = EOL_UNKNOWN; /* file format with errors */\n long\tlinerest = 0;\t\t/* remaining chars in line */\n#ifdef UNIX\n int\t\tperm = 0;\n int\t\tswap_mode = -1;\t\t/* protection bits for swap file */\n#else\n int\t\tperm;\n#endif\n int\t\tfileformat = 0;\t\t/* end-of-line format */\n int\t\tkeep_fileformat = FALSE;\n stat_T\tst;\n int\t\tfile_readonly;\n linenr_T\tskip_count = 0;\n linenr_T\tread_count = 0;\n int\t\tmsg_save = msg_scroll;\n linenr_T\tread_no_eol_lnum = 0; /* non-zero lnum when last line of\n\t\t\t\t\t * last read was missing the eol */\n int\t\ttry_mac;\n int\t\ttry_dos;\n int\t\ttry_unix;\n int\t\tfile_rewind = FALSE;\n#ifdef FEAT_MBYTE\n int\t\tcan_retry;\n linenr_T\tconv_error = 0;\t\t/* line nr with conversion error */\n linenr_T\tillegal_byte = 0;\t/* line nr with illegal byte */\n int\t\tkeep_dest_enc = FALSE;\t/* don't retry when char doesn't fit\n\t\t\t\t\t in destination encoding */\n int\t\tbad_char_behavior = BAD_REPLACE;\n\t\t\t\t\t/* BAD_KEEP, BAD_DROP or character to\n\t\t\t\t\t * replace with */\n char_u\t*tmpname = NULL;\t/* name of 'charconvert' output file */\n int\t\tfio_flags = 0;\n char_u\t*fenc;\t\t\t/* fileencoding to use */\n int\t\tfenc_alloced;\t\t/* fenc_next is in allocated memory */\n char_u\t*fenc_next = NULL;\t/* next item in 'fencs' or NULL */\n int\t\tadvance_fenc = FALSE;\n long\treal_size = 0;\n# ifdef USE_ICONV\n iconv_t\ticonv_fd = (iconv_t)-1;\t/* descriptor for iconv() or -1 */\n# ifdef FEAT_EVAL\n int\t\tdid_iconv = FALSE;\t/* TRUE when iconv() failed and trying\n\t\t\t\t\t 'charconvert' next */\n# endif\n# endif\n int\t\tconverted = FALSE;\t/* TRUE if conversion done */\n int\t\tnotconverted = FALSE;\t/* TRUE if conversion wanted but it\n\t\t\t\t\t wasn't possible */\n char_u\tconv_rest[CONV_RESTLEN];\n int\t\tconv_restlen = 0;\t/* nr of bytes in conv_rest[] */\n#endif\n#ifdef FEAT_AUTOCMD\n buf_T\t*old_curbuf;\n char_u\t*old_b_ffname;\n char_u\t*old_b_fname;\n int\t\tusing_b_ffname;\n int\t\tusing_b_fname;\n#endif\n\n#ifdef FEAT_AUTOCMD\n au_did_filetype = FALSE; /* reset before triggering any autocommands */\n#endif\n\n curbuf->b_no_eol_lnum = 0;\t/* in case it was set by the previous read */\n\n /*\n * If there is no file name yet, use the one for the read file.\n * BF_NOTEDITED is set to reflect this.\n * Don't do this for a read from a filter.\n * Only do this when 'cpoptions' contains the 'f' flag.\n */\n if (curbuf->b_ffname == NULL\n\t && !filtering\n\t && fname != NULL\n\t && vim_strchr(p_cpo, CPO_FNAMER) != NULL\n\t && !(flags & READ_DUMMY))\n {\n\tif (set_rw_fname(fname, sfname) == FAIL)\n\t return FAIL;\n }\n\n#ifdef FEAT_AUTOCMD\n /* Remember the initial values of curbuf, curbuf->b_ffname and\n * curbuf->b_fname to detect whether they are altered as a result of\n * executing nasty autocommands. Also check if \"fname\" and \"sfname\"\n * point to one of these values. */\n old_curbuf = curbuf;\n old_b_ffname = curbuf->b_ffname;\n old_b_fname = curbuf->b_fname;\n using_b_ffname = (fname == curbuf->b_ffname)\n\t\t\t\t\t || (sfname == curbuf->b_ffname);\n using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);\n#endif\n\n /* After reading a file the cursor line changes but we don't want to\n * display the line. */\n ex_no_reprint = TRUE;\n\n /* don't display the file info for another buffer now */\n need_fileinfo = FALSE;\n\n /*\n * For Unix: Use the short file name whenever possible.\n * Avoids problems with networks and when directory names are changed.\n * Don't do this for MS-DOS, a \"cd\" in a sub-shell may have moved us to\n * another directory, which we don't detect.\n */\n if (sfname == NULL)\n\tsfname = fname;\n#if defined(UNIX)\n fname = sfname;\n#endif\n\n#ifdef FEAT_AUTOCMD\n /*\n * The BufReadCmd and FileReadCmd events intercept the reading process by\n * executing the associated commands instead.\n */\n if (!filtering && !read_stdin && !read_buffer)\n {\n\tpos_T\t pos;\n\n\tpos = curbuf->b_op_start;\n\n\t/* Set '[ mark to the line above where the lines go (line 1 if zero). */\n\tcurbuf->b_op_start.lnum = ((from == 0) ? 1 : from);\n\tcurbuf->b_op_start.col = 0;\n\n\tif (newfile)\n\t{\n\t if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,\n\t\t\t\t\t\t\t FALSE, curbuf, eap))\n#ifdef FEAT_EVAL\n\t\treturn aborting() ? FAIL : OK;\n#else\n\t\treturn OK;\n#endif\n\t}\n\telse if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,\n\t\t\t\t\t\t\t FALSE, NULL, eap))\n#ifdef FEAT_EVAL\n\t return aborting() ? FAIL : OK;\n#else\n\t return OK;\n#endif\n\n\tcurbuf->b_op_start = pos;\n }\n#endif\n\n if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)\n\tmsg_scroll = FALSE;\t/* overwrite previous file message */\n else\n\tmsg_scroll = TRUE;\t/* don't overwrite previous file message */\n\n /*\n * If the name ends in a path separator, we can't open it. Check here,\n * because reading the file may actually work, but then creating the swap\n * file may destroy it! Reported on MS-DOS and Win 95.\n * If the name is too long we might crash further on, quit here.\n */\n if (fname != NULL && *fname != NUL)\n {\n\tp = fname + STRLEN(fname);\n\tif (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)\n\t{\n\t filemess(curbuf, fname, (char_u *)_(\"Illegal file name\"), 0);\n\t msg_end();\n\t msg_scroll = msg_save;\n\t return FAIL;\n\t}\n }\n\n if (!read_stdin && !read_buffer && !read_fifo)\n {\n#ifdef UNIX\n\t/*\n\t * On Unix it is possible to read a directory, so we have to\n\t * check for it before the mch_open().\n\t */\n\tperm = mch_getperm(fname);\n\tif (perm >= 0 && !S_ISREG(perm)\t\t /* not a regular file ... */\n# ifdef S_ISFIFO\n\t\t && !S_ISFIFO(perm)\t /* ... or fifo */\n# endif\n# ifdef S_ISSOCK\n\t\t && !S_ISSOCK(perm)\t /* ... or socket */\n# endif\n# ifdef OPEN_CHR_FILES\n\t\t && !(S_ISCHR(perm) && is_dev_fd_file(fname))\n\t\t\t/* ... or a character special file named /dev/fd/ */\n# endif\n\t\t\t\t\t\t)\n\t{\n\t int retval = FAIL;\n\n\t if (S_ISDIR(perm))\n\t {\n\t\tfilemess(curbuf, fname, (char_u *)_(\"is a directory\"), 0);\n\t\tretval = NOTDONE;\n\t }\n\t else\n\t\tfilemess(curbuf, fname, (char_u *)_(\"is not a file\"), 0);\n\t msg_end();\n\t msg_scroll = msg_save;\n\t return retval;\n\t}\n#endif\n#if defined(MSWIN)\n\t/*\n\t * MS-Windows allows opening a device, but we will probably get stuck\n\t * trying to read it.\n\t */\n\tif (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)\n\t{\n\t filemess(curbuf, fname, (char_u *)_(\"is a device (disabled with 'opendevice' option)\"), 0);\n\t msg_end();\n\t msg_scroll = msg_save;\n\t return FAIL;\n\t}\n#endif\n }\n\n /* Set default or forced 'fileformat' and 'binary'. */\n set_file_options(set_options, eap);\n\n /*\n * When opening a new file we take the readonly flag from the file.\n * Default is r/w, can be set to r/o below.\n * Don't reset it when in readonly mode\n * Only set/reset b_p_ro when BF_CHECK_RO is set.\n */\n check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));\n if (check_readonly && !readonlymode)\n\tcurbuf->b_p_ro = FALSE;\n\n if (newfile && !read_stdin && !read_buffer && !read_fifo)\n {\n\t/* Remember time of file. */\n\tif (mch_stat((char *)fname, &st) >= 0)\n\t{\n\t buf_store_time(curbuf, &st, fname);\n\t curbuf->b_mtime_read = curbuf->b_mtime;\n#ifdef UNIX\n\t /*\n\t * Use the protection bits of the original file for the swap file.\n\t * This makes it possible for others to read the name of the\n\t * edited file from the swapfile, but only if they can read the\n\t * edited file.\n\t * Remove the \"write\" and \"execute\" bits for group and others\n\t * (they must not write the swapfile).\n\t * Add the \"read\" and \"write\" bits for the user, otherwise we may\n\t * not be able to write to the file ourselves.\n\t * Setting the bits is done below, after creating the swap file.\n\t */\n\t swap_mode = (st.st_mode & 0644) | 0600;\n#endif\n#ifdef FEAT_CW_EDITOR\n\t /* Get the FSSpec on MacOS\n\t * TODO: Update it properly when the buffer name changes\n\t */\n\t (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);\n#endif\n#ifdef VMS\n\t curbuf->b_fab_rfm = st.st_fab_rfm;\n\t curbuf->b_fab_rat = st.st_fab_rat;\n\t curbuf->b_fab_mrs = st.st_fab_mrs;\n#endif\n\t}\n\telse\n\t{\n\t curbuf->b_mtime = 0;\n\t curbuf->b_mtime_read = 0;\n\t curbuf->b_orig_size = 0;\n\t curbuf->b_orig_mode = 0;\n\t}\n\n\t/* Reset the \"new file\" flag. It will be set again below when the\n\t * file doesn't exist. */\n\tcurbuf->b_flags &= ~(BF_NEW | BF_NEW_W);\n }\n\n/*\n * for UNIX: check readonly with perm and mch_access()\n * for Amiga: check readonly by trying to open the file for writing\n */\n file_readonly = FALSE;\n if (read_stdin)\n {\n#if defined(MSWIN)\n\t/* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */\n\tsetmode(0, O_BINARY);\n#endif\n }\n else if (!read_buffer)\n {\n#ifdef USE_MCH_ACCESS\n\tif (\n# ifdef UNIX\n\t !(perm & 0222) ||\n# endif\n\t\t\t\tmch_access((char *)fname, W_OK))\n\t file_readonly = TRUE;\n\tfd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);\n#else\n\tif (!newfile\n\t\t|| readonlymode\n\t\t|| (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)\n\t{\n\t file_readonly = TRUE;\n\t /* try to open ro */\n\t fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);\n\t}\n#endif\n }\n\n if (fd < 0)\t\t\t /* cannot open at all */\n {\n#ifndef UNIX\n\tint\tisdir_f;\n#endif\n\tmsg_scroll = msg_save;\n#ifndef UNIX\n\t/*\n\t * On Amiga we can't open a directory, check here.\n\t */\n\tisdir_f = (mch_isdir(fname));\n\tperm = mch_getperm(fname); /* check if the file exists */\n\tif (isdir_f)\n\t{\n\t filemess(curbuf, sfname, (char_u *)_(\"is a directory\"), 0);\n\t curbuf->b_p_ro = TRUE;\t/* must use \"w!\" now */\n\t}\n\telse\n#endif\n\t if (newfile)\n\t {\n\t\tif (perm < 0\n#ifdef ENOENT\n\t\t\t&& errno == ENOENT\n#endif\n\t\t )\n\t\t{\n\t\t /*\n\t\t * Set the 'new-file' flag, so that when the file has\n\t\t * been created by someone else, a \":w\" will complain.\n\t\t */\n\t\t curbuf->b_flags |= BF_NEW;\n\n\t\t /* Create a swap file now, so that other Vims are warned\n\t\t * that we are editing this file. Don't do this for a\n\t\t * \"nofile\" or \"nowrite\" buffer type. */\n#ifdef FEAT_QUICKFIX\n\t\t if (!bt_dontwrite(curbuf))\n#endif\n\t\t {\n\t\t\tcheck_need_swap(newfile);\n#ifdef FEAT_AUTOCMD\n\t\t\t/* SwapExists autocommand may mess things up */\n\t\t\tif (curbuf != old_curbuf\n\t\t\t\t|| (using_b_ffname\n\t\t\t\t\t&& (old_b_ffname != curbuf->b_ffname))\n\t\t\t\t|| (using_b_fname\n\t\t\t\t\t && (old_b_fname != curbuf->b_fname)))\n\t\t\t{\n\t\t\t EMSG(_(e_auchangedbuf));\n\t\t\t return FAIL;\n\t\t\t}\n#endif\n\t\t }\n\t\t if (dir_of_file_exists(fname))\n\t\t\tfilemess(curbuf, sfname, (char_u *)_(\"[New File]\"), 0);\n\t\t else\n\t\t\tfilemess(curbuf, sfname,\n\t\t\t\t\t (char_u *)_(\"[New DIRECTORY]\"), 0);\n#ifdef FEAT_VIMINFO\n\t\t /* Even though this is a new file, it might have been\n\t\t * edited before and deleted. Get the old marks. */\n\t\t check_marks_read();\n#endif\n#ifdef FEAT_MBYTE\n\t\t /* Set forced 'fileencoding'. */\n\t\t if (eap != NULL)\n\t\t\tset_forced_fenc(eap);\n#endif\n#ifdef FEAT_AUTOCMD\n\t\t apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,\n\t\t\t\t\t\t\t FALSE, curbuf, eap);\n#endif\n\t\t /* remember the current fileformat */\n\t\t save_file_ff(curbuf);\n\n#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)\n\t\t if (aborting()) /* autocmds may abort script processing */\n\t\t\treturn FAIL;\n#endif\n\t\t return OK;\t /* a new file is not an error */\n\t\t}\n\t\telse\n\t\t{\n\t\t filemess(curbuf, sfname, (char_u *)(\n# ifdef EFBIG\n\t\t\t (errno == EFBIG) ? _(\"[File too big]\") :\n# endif\n# ifdef EOVERFLOW\n\t\t\t (errno == EOVERFLOW) ? _(\"[File too big]\") :\n# endif\n\t\t\t\t\t\t_(\"[Permission Denied]\")), 0);\n\t\t curbuf->b_p_ro = TRUE;\t/* must use \"w!\" now */\n\t\t}\n\t }\n\n\treturn FAIL;\n }\n\n /*\n * Only set the 'ro' flag for readonly files the first time they are\n * loaded.\tHelp files always get readonly mode\n */\n if ((check_readonly && file_readonly) || curbuf->b_help)\n\tcurbuf->b_p_ro = TRUE;\n\n if (set_options)\n {\n\t/* Don't change 'eol' if reading from buffer as it will already be\n\t * correctly set when reading stdin. */\n\tif (!read_buffer)\n\t{\n\t curbuf->b_p_eol = TRUE;\n\t curbuf->b_start_eol = TRUE;\n\t}\n#ifdef FEAT_MBYTE\n\tcurbuf->b_p_bomb = FALSE;\n\tcurbuf->b_start_bomb = FALSE;\n#endif\n }\n\n /* Create a swap file now, so that other Vims are warned that we are\n * editing this file.\n * Don't do this for a \"nofile\" or \"nowrite\" buffer type. */\n#ifdef FEAT_QUICKFIX\n if (!bt_dontwrite(curbuf))\n#endif\n {\n\tcheck_need_swap(newfile);\n#ifdef FEAT_AUTOCMD\n\tif (!read_stdin && (curbuf != old_curbuf\n\t\t|| (using_b_ffname && (old_b_ffname != curbuf->b_ffname))\n\t\t|| (using_b_fname && (old_b_fname != curbuf->b_fname))))\n\t{\n\t EMSG(_(e_auchangedbuf));\n\t if (!read_buffer)\n\t\tclose(fd);\n\t return FAIL;\n\t}\n#endif\n#ifdef UNIX\n\t/* Set swap file protection bits after creating it. */\n\tif (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL\n\t\t\t && curbuf->b_ml.ml_mfp->mf_fname != NULL)\n\t (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);\n#endif\n }\n\n#if defined(HAS_SWAP_EXISTS_ACTION)\n /* If \"Quit\" selected at ATTENTION dialog, don't load the file */\n if (swap_exists_action == SEA_QUIT)\n {\n\tif (!read_buffer && !read_stdin)\n\t close(fd);\n\treturn FAIL;\n }\n#endif\n\n ++no_wait_return;\t /* don't wait for return yet */\n\n /*\n * Set '[ mark to the line above where the lines go (line 1 if zero).\n */\n curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);\n curbuf->b_op_start.col = 0;\n\n try_mac = (vim_strchr(p_ffs, 'm') != NULL);\n try_dos = (vim_strchr(p_ffs, 'd') != NULL);\n try_unix = (vim_strchr(p_ffs, 'x') != NULL);\n\n#ifdef FEAT_AUTOCMD\n if (!read_buffer)\n {\n\tint\tm = msg_scroll;\n\tint\tn = msg_scrolled;\n\n\t/*\n\t * The file must be closed again, the autocommands may want to change\n\t * the file before reading it.\n\t */\n\tif (!read_stdin)\n\t close(fd);\t\t/* ignore errors */\n\n\t/*\n\t * The output from the autocommands should not overwrite anything and\n\t * should not be overwritten: Set msg_scroll, restore its value if no\n\t * output was done.\n\t */\n\tmsg_scroll = TRUE;\n\tif (filtering)\n\t apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,\n\t\t\t\t\t\t\t FALSE, curbuf, eap);\n\telse if (read_stdin)\n\t apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,\n\t\t\t\t\t\t\t FALSE, curbuf, eap);\n\telse if (newfile)\n\t apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,\n\t\t\t\t\t\t\t FALSE, curbuf, eap);\n\telse\n\t apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,\n\t\t\t\t\t\t\t FALSE, NULL, eap);\n\t/* autocommands may have changed it */\n\ttry_mac = (vim_strchr(p_ffs, 'm') != NULL);\n\ttry_dos = (vim_strchr(p_ffs, 'd') != NULL);\n\ttry_unix = (vim_strchr(p_ffs, 'x') != NULL);\n\n\tif (msg_scrolled == n)\n\t msg_scroll = m;\n\n#ifdef FEAT_EVAL\n\tif (aborting())\t /* autocmds may abort script processing */\n\t{\n\t --no_wait_return;\n\t msg_scroll = msg_save;\n\t curbuf->b_p_ro = TRUE;\t/* must use \"w!\" now */\n\t return FAIL;\n\t}\n#endif\n\t/*\n\t * Don't allow the autocommands to change the current buffer.\n\t * Try to re-open the file.\n\t *\n\t * Don't allow the autocommands to change the buffer name either\n\t * (cd for example) if it invalidates fname or sfname.\n\t */\n\tif (!read_stdin && (curbuf != old_curbuf\n\t\t|| (using_b_ffname && (old_b_ffname != curbuf->b_ffname))\n\t\t|| (using_b_fname && (old_b_fname != curbuf->b_fname))\n\t\t|| (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))\n\t{\n\t --no_wait_return;\n\t msg_scroll = msg_save;\n\t if (fd < 0)\n\t\tEMSG(_(\"E200: *ReadPre autocommands made the file unreadable\"));\n\t else\n\t\tEMSG(_(\"E201: *ReadPre autocommands must not change current buffer\"));\n\t curbuf->b_p_ro = TRUE;\t/* must use \"w!\" now */\n\t return FAIL;\n\t}\n }\n#endif /* FEAT_AUTOCMD */\n\n /* Autocommands may add lines to the file, need to check if it is empty */\n wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);\n\n if (!recoverymode && !filtering && !(flags & READ_DUMMY))\n {\n\t/*\n\t * Show the user that we are busy reading the input. Sometimes this\n\t * may take a while. When reading from stdin another program may\n\t * still be running, don't move the cursor to the last line, unless\n\t * always using the GUI.\n\t */\n\tif (read_stdin)\n\t{\n#ifndef ALWAYS_USE_GUI\n\t mch_msg(_(\"Vim: Reading from stdin...\\n\"));\n#endif\n#ifdef FEAT_GUI\n\t /* Also write a message in the GUI window, if there is one. */\n\t if (gui.in_use && !gui.dying && !gui.starting)\n\t {\n\t\tp = (char_u *)_(\"Reading from stdin...\");\n\t\tgui_write(p, (int)STRLEN(p));\n\t }\n#endif\n\t}\n\telse if (!read_buffer)\n\t filemess(curbuf, sfname, (char_u *)\"\", 0);\n }\n\n msg_scroll = FALSE;\t\t\t/* overwrite the file message */\n\n /*\n * Set linecnt now, before the \"retry\" caused by a wrong guess for\n * fileformat, and after the autocommands, which may change them.\n */\n linecnt = curbuf->b_ml.ml_line_count;\n\n#ifdef FEAT_MBYTE\n /* \"++bad=\" argument. */\n if (eap != NULL && eap->bad_char != 0)\n {\n\tbad_char_behavior = eap->bad_char;\n\tif (set_options)\n\t curbuf->b_bad_char = eap->bad_char;\n }\n else\n\tcurbuf->b_bad_char = 0;\n\n /*\n * Decide which 'encoding' to use or use first.\n */\n if (eap != NULL && eap->force_enc != 0)\n {\n\tfenc = enc_canonize(eap->cmd + eap->force_enc);\n\tfenc_alloced = TRUE;\n\tkeep_dest_enc = TRUE;\n }\n else if (curbuf->b_p_bin)\n {\n\tfenc = (char_u *)\"\";\t\t/* binary: don't convert */\n\tfenc_alloced = FALSE;\n }\n else if (curbuf->b_help)\n {\n\tchar_u\t firstline[80];\n\tint\t fc;\n\n\t/* Help files are either utf-8 or latin1. Try utf-8 first, if this\n\t * fails it must be latin1.\n\t * Always do this when 'encoding' is \"utf-8\". Otherwise only do\n\t * this when needed to avoid [converted] remarks all the time.\n\t * It is needed when the first line contains non-ASCII characters.\n\t * That is only in *.??x files. */\n\tfenc = (char_u *)\"latin1\";\n\tc = enc_utf8;\n\tif (!c && !read_stdin)\n\t{\n\t fc = fname[STRLEN(fname) - 1];\n\t if (TOLOWER_ASC(fc) == 'x')\n\t {\n\t\t/* Read the first line (and a bit more). Immediately rewind to\n\t\t * the start of the file. If the read() fails \"len\" is -1. */\n\t\tlen = read_eintr(fd, firstline, 80);\n\t\tvim_lseek(fd, (off_T)0L, SEEK_SET);\n\t\tfor (p = firstline; p < firstline + len; ++p)\n\t\t if (*p >= 0x80)\n\t\t {\n\t\t\tc = TRUE;\n\t\t\tbreak;\n\t\t }\n\t }\n\t}\n\n\tif (c)\n\t{\n\t fenc_next = fenc;\n\t fenc = (char_u *)\"utf-8\";\n\n\t /* When the file is utf-8 but a character doesn't fit in\n\t * 'encoding' don't retry. In help text editing utf-8 bytes\n\t * doesn't make sense. */\n\t if (!enc_utf8)\n\t\tkeep_dest_enc = TRUE;\n\t}\n\tfenc_alloced = FALSE;\n }\n else if (*p_fencs == NUL)\n {\n\tfenc = curbuf->b_p_fenc;\t/* use format from buffer */\n\tfenc_alloced = FALSE;\n }\n else\n {\n\tfenc_next = p_fencs;\t\t/* try items in 'fileencodings' */\n\tfenc = next_fenc(&fenc_next);\n\tfenc_alloced = TRUE;\n }\n#endif\n\n /*\n * Jump back here to retry reading the file in different ways.\n * Reasons to retry:\n * - encoding conversion failed: try another one from \"fenc_next\"\n * - BOM detected and fenc was set, need to setup conversion\n * - \"fileformat\" check failed: try another\n *\n * Variables set for special retry actions:\n * \"file_rewind\"\tRewind the file to start reading it again.\n * \"advance_fenc\"\tAdvance \"fenc\" using \"fenc_next\".\n * \"skip_read\"\tRe-use already read bytes (BOM detected).\n * \"did_iconv\"\ticonv() conversion failed, try 'charconvert'.\n * \"keep_fileformat\" Don't reset \"fileformat\".\n *\n * Other status indicators:\n * \"tmpname\"\tWhen != NULL did conversion with 'charconvert'.\n *\t\t\tOutput file has to be deleted afterwards.\n * \"iconv_fd\"\tWhen != -1 did conversion with iconv().\n */\nretry:\n\n if (file_rewind)\n {\n\tif (read_buffer)\n\t{\n\t read_buf_lnum = 1;\n\t read_buf_col = 0;\n\t}\n\telse if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0)\n\t{\n\t /* Can't rewind the file, give up. */\n\t error = TRUE;\n\t goto failed;\n\t}\n\t/* Delete the previously read lines. */\n\twhile (lnum > from)\n\t ml_delete(lnum--, FALSE);\n\tfile_rewind = FALSE;\n#ifdef FEAT_MBYTE\n\tif (set_options)\n\t{\n\t curbuf->b_p_bomb = FALSE;\n\t curbuf->b_start_bomb = FALSE;\n\t}\n\tconv_error = 0;\n#endif\n }\n\n /*\n * When retrying with another \"fenc\" and the first time \"fileformat\"\n * will be reset.\n */\n if (keep_fileformat)\n\tkeep_fileformat = FALSE;\n else\n {\n\tif (eap != NULL && eap->force_ff != 0)\n\t{\n\t fileformat = get_fileformat_force(curbuf, eap);\n\t try_unix = try_dos = try_mac = FALSE;\n\t}\n\telse if (curbuf->b_p_bin)\n\t fileformat = EOL_UNIX;\t\t/* binary: use Unix format */\n\telse if (*p_ffs == NUL)\n\t fileformat = get_fileformat(curbuf);/* use format from buffer */\n\telse\n\t fileformat = EOL_UNKNOWN;\t\t/* detect from file */\n }\n\n#ifdef FEAT_MBYTE\n# ifdef USE_ICONV\n if (iconv_fd != (iconv_t)-1)\n {\n\t/* aborted conversion with iconv(), close the descriptor */\n\ticonv_close(iconv_fd);\n\ticonv_fd = (iconv_t)-1;\n }\n# endif\n\n if (advance_fenc)\n {\n\t/*\n\t * Try the next entry in 'fileencodings'.\n\t */\n\tadvance_fenc = FALSE;\n\n\tif (eap != NULL && eap->force_enc != 0)\n\t{\n\t /* Conversion given with \"++cc=\" wasn't possible, read\n\t * without conversion. */\n\t notconverted = TRUE;\n\t conv_error = 0;\n\t if (fenc_alloced)\n\t\tvim_free(fenc);\n\t fenc = (char_u *)\"\";\n\t fenc_alloced = FALSE;\n\t}\n\telse\n\t{\n\t if (fenc_alloced)\n\t\tvim_free(fenc);\n\t if (fenc_next != NULL)\n\t {\n\t\tfenc = next_fenc(&fenc_next);\n\t\tfenc_alloced = (fenc_next != NULL);\n\t }\n\t else\n\t {\n\t\tfenc = (char_u *)\"\";\n\t\tfenc_alloced = FALSE;\n\t }\n\t}\n\tif (tmpname != NULL)\n\t{\n\t mch_remove(tmpname);\t\t/* delete converted file */\n\t vim_free(tmpname);\n\t tmpname = NULL;\n\t}\n }\n\n /*\n * Conversion may be required when the encoding of the file is different\n * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.\n */\n fio_flags = 0;\n converted = need_conversion(fenc);\n if (converted)\n {\n\n\t/* \"ucs-bom\" means we need to check the first bytes of the file\n\t * for a BOM. */\n\tif (STRCMP(fenc, ENC_UCSBOM) == 0)\n\t fio_flags = FIO_UCSBOM;\n\n\t/*\n\t * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be\n\t * done. This is handled below after read(). Prepare the\n\t * fio_flags to avoid having to parse the string each time.\n\t * Also check for Unicode to Latin1 conversion, because iconv()\n\t * appears not to handle this correctly. This works just like\n\t * conversion to UTF-8 except how the resulting character is put in\n\t * the buffer.\n\t */\n\telse if (enc_utf8 || STRCMP(p_enc, \"latin1\") == 0)\n\t fio_flags = get_fio_flags(fenc);\n\n# ifdef WIN3264\n\t/*\n\t * Conversion from an MS-Windows codepage to UTF-8 or another codepage\n\t * is handled with MultiByteToWideChar().\n\t */\n\tif (fio_flags == 0)\n\t fio_flags = get_win_fio_flags(fenc);\n# endif\n\n# ifdef MACOS_CONVERT\n\t/* Conversion from Apple MacRoman to latin1 or UTF-8 */\n\tif (fio_flags == 0)\n\t fio_flags = get_mac_fio_flags(fenc);\n# endif\n\n# ifdef USE_ICONV\n\t/*\n\t * Try using iconv() if we can't convert internally.\n\t */\n\tif (fio_flags == 0\n# ifdef FEAT_EVAL\n\t\t&& !did_iconv\n# endif\n\t\t)\n\t iconv_fd = (iconv_t)my_iconv_open(\n\t\t\t\t enc_utf8 ? (char_u *)\"utf-8\" : p_enc, fenc);\n# endif\n\n# ifdef FEAT_EVAL\n\t/*\n\t * Use the 'charconvert' expression when conversion is required\n\t * and we can't do it internally or with iconv().\n\t */\n\tif (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL\n\t\t\t\t\t\t && !read_fifo\n# ifdef USE_ICONV\n\t\t\t\t\t\t && iconv_fd == (iconv_t)-1\n# endif\n\t\t)\n\t{\n# ifdef USE_ICONV\n\t did_iconv = FALSE;\n# endif\n\t /* Skip conversion when it's already done (retry for wrong\n\t * \"fileformat\"). */\n\t if (tmpname == NULL)\n\t {\n\t\ttmpname = readfile_charconvert(fname, fenc, &fd);\n\t\tif (tmpname == NULL)\n\t\t{\n\t\t /* Conversion failed. Try another one. */\n\t\t advance_fenc = TRUE;\n\t\t if (fd < 0)\n\t\t {\n\t\t\t/* Re-opening the original file failed! */\n\t\t\tEMSG(_(\"E202: Conversion made file unreadable!\"));\n\t\t\terror = TRUE;\n\t\t\tgoto failed;\n\t\t }\n\t\t goto retry;\n\t\t}\n\t }\n\t}\n\telse\n# endif\n\t{\n\t if (fio_flags == 0\n# ifdef USE_ICONV\n\t\t && iconv_fd == (iconv_t)-1\n# endif\n\t )\n\t {\n\t\t/* Conversion wanted but we can't.\n\t\t * Try the next conversion in 'fileencodings' */\n\t\tadvance_fenc = TRUE;\n\t\tgoto retry;\n\t }\n\t}\n }\n\n /* Set \"can_retry\" when it's possible to rewind the file and try with\n * another \"fenc\" value. It's FALSE when no other \"fenc\" to try, reading\n * stdin or fixed at a specific encoding. */\n can_retry = (*fenc != NUL && !read_stdin && !read_fifo && !keep_dest_enc);\n#endif\n\n if (!skip_read)\n {\n\tlinerest = 0;\n\tfilesize = 0;\n\tskip_count = lines_to_skip;\n\tread_count = lines_to_read;\n#ifdef FEAT_MBYTE\n\tconv_restlen = 0;\n#endif\n#ifdef FEAT_PERSISTENT_UNDO\n\tread_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0\n\t\t\t\t && curbuf->b_ffname != NULL\n\t\t\t\t && curbuf->b_p_udf\n\t\t\t\t && !filtering\n\t\t\t\t && !read_fifo\n\t\t\t\t && !read_stdin\n\t\t\t\t && !read_buffer);\n\tif (read_undo_file)\n\t sha256_start(&sha_ctx);\n#endif\n#ifdef FEAT_CRYPT\n\tif (curbuf->b_cryptstate != NULL)\n\t{\n\t /* Need to free the state, but keep the key, don't want to ask for\n\t * it again. */\n\t crypt_free_state(curbuf->b_cryptstate);\n\t curbuf->b_cryptstate = NULL;\n\t}\n#endif\n }\n\n while (!error && !got_int)\n {\n\t/*\n\t * We allocate as much space for the file as we can get, plus\n\t * space for the old line plus room for one terminating NUL.\n\t * The amount is limited by the fact that read() only can read\n\t * upto max_unsigned characters (and other things).\n\t */\n#if VIM_SIZEOF_INT <= 2\n\tif (linerest >= 0x7ff0)\n\t{\n\t ++split;\n\t *ptr = NL;\t\t /* split line by inserting a NL */\n\t size = 1;\n\t}\n\telse\n#endif\n\t{\n\t if (!skip_read)\n\t {\n#if VIM_SIZEOF_INT > 2\n# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)\n\t\tsize = SSIZE_MAX;\t\t /* use max I/O size, 52K */\n# else\n\t\tsize = 0x10000L;\t\t /* use buffer >= 64K */\n# endif\n#else\n\t\tsize = 0x7ff0L - linerest;\t /* limit buffer to 32K */\n#endif\n\n\t\tfor ( ; size >= 10; size = (long)((long_u)size >> 1))\n\t\t{\n\t\t if ((new_buffer = lalloc((long_u)(size + linerest + 1),\n\t\t\t\t\t\t\t FALSE)) != NULL)\n\t\t\tbreak;\n\t\t}\n\t\tif (new_buffer == NULL)\n\t\t{\n\t\t do_outofmem_msg((long_u)(size * 2 + linerest + 1));\n\t\t error = TRUE;\n\t\t break;\n\t\t}\n\t\tif (linerest)\t/* copy characters from the previous buffer */\n\t\t mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);\n\t\tvim_free(buffer);\n\t\tbuffer = new_buffer;\n\t\tptr = buffer + linerest;\n\t\tline_start = buffer;\n\n#ifdef FEAT_MBYTE\n\t\t/* May need room to translate into.\n\t\t * For iconv() we don't really know the required space, use a\n\t\t * factor ICONV_MULT.\n\t\t * latin1 to utf-8: 1 byte becomes up to 2 bytes\n\t\t * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes\n\t\t * become up to 4 bytes, size must be multiple of 2\n\t\t * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be\n\t\t * multiple of 2\n\t\t * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be\n\t\t * multiple of 4 */\n\t\treal_size = (int)size;\n# ifdef USE_ICONV\n\t\tif (iconv_fd != (iconv_t)-1)\n\t\t size = size / ICONV_MULT;\n\t\telse\n# endif\n\t\t if (fio_flags & FIO_LATIN1)\n\t\t size = size / 2;\n\t\telse if (fio_flags & (FIO_UCS2 | FIO_UTF16))\n\t\t size = (size * 2 / 3) & ~1;\n\t\telse if (fio_flags & FIO_UCS4)\n\t\t size = (size * 2 / 3) & ~3;\n\t\telse if (fio_flags == FIO_UCSBOM)\n\t\t size = size / ICONV_MULT;\t/* worst case */\n# ifdef WIN3264\n\t\telse if (fio_flags & FIO_CODEPAGE)\n\t\t size = size / ICONV_MULT;\t/* also worst case */\n# endif\n# ifdef MACOS_CONVERT\n\t\telse if (fio_flags & FIO_MACROMAN)\n\t\t size = size / ICONV_MULT;\t/* also worst case */\n# endif\n#endif\n\n#ifdef FEAT_MBYTE\n\t\tif (conv_restlen > 0)\n\t\t{\n\t\t /* Insert unconverted bytes from previous line. */\n\t\t mch_memmove(ptr, conv_rest, conv_restlen);\n\t\t ptr += conv_restlen;\n\t\t size -= conv_restlen;\n\t\t}\n#endif\n\n\t\tif (read_buffer)\n\t\t{\n\t\t /*\n\t\t * Read bytes from curbuf. Used for converting text read\n\t\t * from stdin.\n\t\t */\n\t\t if (read_buf_lnum > from)\n\t\t\tsize = 0;\n\t\t else\n\t\t {\n\t\t\tint\tn, ni;\n\t\t\tlong\ttlen;\n\n\t\t\ttlen = 0;\n\t\t\tfor (;;)\n\t\t\t{\n\t\t\t p = ml_get(read_buf_lnum) + read_buf_col;\n\t\t\t n = (int)STRLEN(p);\n\t\t\t if ((int)tlen + n + 1 > size)\n\t\t\t {\n\t\t\t\t/* Filled up to \"size\", append partial line.\n\t\t\t\t * Change NL to NUL to reverse the effect done\n\t\t\t\t * below. */\n\t\t\t\tn = (int)(size - tlen);\n\t\t\t\tfor (ni = 0; ni < n; ++ni)\n\t\t\t\t{\n\t\t\t\t if (p[ni] == NL)\n\t\t\t\t\tptr[tlen++] = NUL;\n\t\t\t\t else\n\t\t\t\t\tptr[tlen++] = p[ni];\n\t\t\t\t}\n\t\t\t\tread_buf_col += n;\n\t\t\t\tbreak;\n\t\t\t }\n\t\t\t else\n\t\t\t {\n\t\t\t\t/* Append whole line and new-line. Change NL\n\t\t\t\t * to NUL to reverse the effect done below. */\n\t\t\t\tfor (ni = 0; ni < n; ++ni)\n\t\t\t\t{\n\t\t\t\t if (p[ni] == NL)\n\t\t\t\t\tptr[tlen++] = NUL;\n\t\t\t\t else\n\t\t\t\t\tptr[tlen++] = p[ni];\n\t\t\t\t}\n\t\t\t\tptr[tlen++] = NL;\n\t\t\t\tread_buf_col = 0;\n\t\t\t\tif (++read_buf_lnum > from)\n\t\t\t\t{\n\t\t\t\t /* When the last line didn't have an\n\t\t\t\t * end-of-line don't add it now either. */\n\t\t\t\t if (!curbuf->b_p_eol)\n\t\t\t\t\t--tlen;\n\t\t\t\t size = tlen;\n\t\t\t\t break;\n\t\t\t\t}\n\t\t\t }\n\t\t\t}\n\t\t }\n\t\t}\n\t\telse\n\t\t{\n\t\t /*\n\t\t * Read bytes from the file.\n\t\t */\n\t\t size = read_eintr(fd, ptr, size);\n\t\t}\n\n#ifdef FEAT_CRYPT\n\t\t/*\n\t\t * At start of file: Check for magic number of encryption.\n\t\t */\n\t\tif (filesize == 0 && size > 0)\n\t\t cryptkey = check_for_cryptkey(cryptkey, ptr, &size,\n\t\t\t\t\t\t &filesize, newfile, sfname,\n\t\t\t\t\t\t &did_ask_for_key);\n\t\t/*\n\t\t * Decrypt the read bytes. This is done before checking for\n\t\t * EOF because the crypt layer may be buffering.\n\t\t */\n\t\tif (cryptkey != NULL && curbuf->b_cryptstate != NULL\n\t\t\t\t\t\t\t\t && size > 0)\n\t\t{\n\t\t if (crypt_works_inplace(curbuf->b_cryptstate))\n\t\t {\n\t\t\tcrypt_decode_inplace(curbuf->b_cryptstate, ptr, size);\n\t\t }\n\t\t else\n\t\t {\n\t\t\tchar_u\t*newptr = NULL;\n\t\t\tint\tdecrypted_size;\n\n\t\t\tdecrypted_size = crypt_decode_alloc(\n\t\t\t\t curbuf->b_cryptstate, ptr, size, &newptr);\n\n\t\t\t/* If the crypt layer is buffering, not producing\n\t\t\t * anything yet, need to read more. */\n\t\t\tif (size > 0 && decrypted_size == 0)\n\t\t\t continue;\n\n\t\t\tif (linerest == 0)\n\t\t\t{\n\t\t\t /* Simple case: reuse returned buffer (may be\n\t\t\t * NULL, checked later). */\n\t\t\t new_buffer = newptr;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t long_u\tnew_size;\n\n\t\t\t /* Need new buffer to add bytes carried over. */\n\t\t\t new_size = (long_u)(decrypted_size + linerest + 1);\n\t\t\t new_buffer = lalloc(new_size, FALSE);\n\t\t\t if (new_buffer == NULL)\n\t\t\t {\n\t\t\t\tdo_outofmem_msg(new_size);\n\t\t\t\terror = TRUE;\n\t\t\t\tbreak;\n\t\t\t }\n\n\t\t\t mch_memmove(new_buffer, buffer, linerest);\n\t\t\t if (newptr != NULL)\n\t\t\t\tmch_memmove(new_buffer + linerest, newptr,\n\t\t\t\t\t\t\t decrypted_size);\n\t\t\t}\n\n\t\t\tif (new_buffer != NULL)\n\t\t\t{\n\t\t\t vim_free(buffer);\n\t\t\t buffer = new_buffer;\n\t\t\t new_buffer = NULL;\n\t\t\t line_start = buffer;\n\t\t\t ptr = buffer + linerest;\n\t\t\t}\n\t\t\tsize = decrypted_size;\n\t\t }\n\t\t}\n#endif\n\n\t\tif (size <= 0)\n\t\t{\n\t\t if (size < 0)\t\t /* read error */\n\t\t\terror = TRUE;\n#ifdef FEAT_MBYTE\n\t\t else if (conv_restlen > 0)\n\t\t {\n\t\t\t/*\n\t\t\t * Reached end-of-file but some trailing bytes could\n\t\t\t * not be converted. Truncated file?\n\t\t\t */\n\n\t\t\t/* When we did a conversion report an error. */\n\t\t\tif (fio_flags != 0\n# ifdef USE_ICONV\n\t\t\t\t|| iconv_fd != (iconv_t)-1\n# endif\n\t\t\t )\n\t\t\t{\n\t\t\t if (can_retry)\n\t\t\t\tgoto rewind_retry;\n\t\t\t if (conv_error == 0)\n\t\t\t\tconv_error = curbuf->b_ml.ml_line_count\n\t\t\t\t\t\t\t\t- linecnt + 1;\n\t\t\t}\n\t\t\t/* Remember the first linenr with an illegal byte */\n\t\t\telse if (illegal_byte == 0)\n\t\t\t illegal_byte = curbuf->b_ml.ml_line_count\n\t\t\t\t\t\t\t\t- linecnt + 1;\n\t\t\tif (bad_char_behavior == BAD_DROP)\n\t\t\t{\n\t\t\t *(ptr - conv_restlen) = NUL;\n\t\t\t conv_restlen = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t /* Replace the trailing bytes with the replacement\n\t\t\t * character if we were converting; if we weren't,\n\t\t\t * leave the UTF8 checking code to do it, as it\n\t\t\t * works slightly differently. */\n\t\t\t if (bad_char_behavior != BAD_KEEP && (fio_flags != 0\n# ifdef USE_ICONV\n\t\t\t\t || iconv_fd != (iconv_t)-1\n# endif\n\t\t\t ))\n\t\t\t {\n\t\t\t\twhile (conv_restlen > 0)\n\t\t\t\t{\n\t\t\t\t *(--ptr) = bad_char_behavior;\n\t\t\t\t --conv_restlen;\n\t\t\t\t}\n\t\t\t }\n\t\t\t fio_flags = 0;\t/* don't convert this */\n# ifdef USE_ICONV\n\t\t\t if (iconv_fd != (iconv_t)-1)\n\t\t\t {\n\t\t\t\ticonv_close(iconv_fd);\n\t\t\t\ticonv_fd = (iconv_t)-1;\n\t\t\t }\n# endif\n\t\t\t}\n\t\t }\n#endif\n\t\t}\n\t }\n\t skip_read = FALSE;\n\n#ifdef FEAT_MBYTE\n\t /*\n\t * At start of file (or after crypt magic number): Check for BOM.\n\t * Also check for a BOM for other Unicode encodings, but not after\n\t * converting with 'charconvert' or when a BOM has already been\n\t * found.\n\t */\n\t if ((filesize == 0\n# ifdef FEAT_CRYPT\n\t\t || (cryptkey != NULL\n\t\t\t&& filesize == crypt_get_header_len(\n\t\t\t\t\t\t crypt_get_method_nr(curbuf)))\n# endif\n\t\t )\n\t\t && (fio_flags == FIO_UCSBOM\n\t\t\t|| (!curbuf->b_p_bomb\n\t\t\t && tmpname == NULL\n\t\t\t && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))\n\t {\n\t\tchar_u\t*ccname;\n\t\tint\tblen;\n\n\t\t/* no BOM detection in a short file or in binary mode */\n\t\tif (size < 2 || curbuf->b_p_bin)\n\t\t ccname = NULL;\n\t\telse\n\t\t ccname = check_for_bom(ptr, size, &blen,\n\t\t fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));\n\t\tif (ccname != NULL)\n\t\t{\n\t\t /* Remove BOM from the text */\n\t\t filesize += blen;\n\t\t size -= blen;\n\t\t mch_memmove(ptr, ptr + blen, (size_t)size);\n\t\t if (set_options)\n\t\t {\n\t\t\tcurbuf->b_p_bomb = TRUE;\n\t\t\tcurbuf->b_start_bomb = TRUE;\n\t\t }\n\t\t}\n\n\t\tif (fio_flags == FIO_UCSBOM)\n\t\t{\n\t\t if (ccname == NULL)\n\t\t {\n\t\t\t/* No BOM detected: retry with next encoding. */\n\t\t\tadvance_fenc = TRUE;\n\t\t }\n\t\t else\n\t\t {\n\t\t\t/* BOM detected: set \"fenc\" and jump back */\n\t\t\tif (fenc_alloced)\n\t\t\t vim_free(fenc);\n\t\t\tfenc = ccname;\n\t\t\tfenc_alloced = FALSE;\n\t\t }\n\t\t /* retry reading without getting new bytes or rewinding */\n\t\t skip_read = TRUE;\n\t\t goto retry;\n\t\t}\n\t }\n\n\t /* Include not converted bytes. */\n\t ptr -= conv_restlen;\n\t size += conv_restlen;\n\t conv_restlen = 0;\n#endif\n\t /*\n\t * Break here for a read error or end-of-file.\n\t */\n\t if (size <= 0)\n\t\tbreak;\n\n#ifdef FEAT_MBYTE\n\n# ifdef USE_ICONV\n\t if (iconv_fd != (iconv_t)-1)\n\t {\n\t\t/*\n\t\t * Attempt conversion of the read bytes to 'encoding' using\n\t\t * iconv().\n\t\t */\n\t\tconst char\t*fromp;\n\t\tchar\t\t*top;\n\t\tsize_t\t\tfrom_size;\n\t\tsize_t\t\tto_size;\n\n\t\tfromp = (char *)ptr;\n\t\tfrom_size = size;\n\t\tptr += size;\n\t\ttop = (char *)ptr;\n\t\tto_size = real_size - size;\n\n\t\t/*\n\t\t * If there is conversion error or not enough room try using\n\t\t * another conversion. Except for when there is no\n\t\t * alternative (help files).\n\t\t */\n\t\twhile ((iconv(iconv_fd, (void *)&fromp, &from_size,\n\t\t\t\t\t\t\t &top, &to_size)\n\t\t\t == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)\n\t\t\t\t\t\t || from_size > CONV_RESTLEN)\n\t\t{\n\t\t if (can_retry)\n\t\t\tgoto rewind_retry;\n\t\t if (conv_error == 0)\n\t\t\tconv_error = readfile_linenr(linecnt,\n\t\t\t\t\t\t\t ptr, (char_u *)top);\n\n\t\t /* Deal with a bad byte and continue with the next. */\n\t\t ++fromp;\n\t\t --from_size;\n\t\t if (bad_char_behavior == BAD_KEEP)\n\t\t {\n\t\t\t*top++ = *(fromp - 1);\n\t\t\t--to_size;\n\t\t }\n\t\t else if (bad_char_behavior != BAD_DROP)\n\t\t {\n\t\t\t*top++ = bad_char_behavior;\n\t\t\t--to_size;\n\t\t }\n\t\t}\n\n\t\tif (from_size > 0)\n\t\t{\n\t\t /* Some remaining characters, keep them for the next\n\t\t * round. */\n\t\t mch_memmove(conv_rest, (char_u *)fromp, from_size);\n\t\t conv_restlen = (int)from_size;\n\t\t}\n\n\t\t/* move the linerest to before the converted characters */\n\t\tline_start = ptr - linerest;\n\t\tmch_memmove(line_start, buffer, (size_t)linerest);\n\t\tsize = (long)((char_u *)top - ptr);\n\t }\n# endif\n\n# ifdef WIN3264\n\t if (fio_flags & FIO_CODEPAGE)\n\t {\n\t\tchar_u\t*src, *dst;\n\t\tWCHAR\tucs2buf[3];\n\t\tint\tucs2len;\n\t\tint\tcodepage = FIO_GET_CP(fio_flags);\n\t\tint\tbytelen;\n\t\tint\tfound_bad;\n\t\tchar\treplstr[2];\n\n\t\t/*\n\t\t * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or\n\t\t * a codepage, using standard MS-Windows functions. This\n\t\t * requires two steps:\n\t\t * 1. convert from 'fileencoding' to ucs-2\n\t\t * 2. convert from ucs-2 to 'encoding'\n\t\t *\n\t\t * Because there may be illegal bytes AND an incomplete byte\n\t\t * sequence at the end, we may have to do the conversion one\n\t\t * character at a time to get it right.\n\t\t */\n\n\t\t/* Replacement string for WideCharToMultiByte(). */\n\t\tif (bad_char_behavior > 0)\n\t\t replstr[0] = bad_char_behavior;\n\t\telse\n\t\t replstr[0] = '?';\n\t\treplstr[1] = NUL;\n\n\t\t/*\n\t\t * Move the bytes to the end of the buffer, so that we have\n\t\t * room to put the result at the start.\n\t\t */\n\t\tsrc = ptr + real_size - size;\n\t\tmch_memmove(src, ptr, size);\n\n\t\t/*\n\t\t * Do the conversion.\n\t\t */\n\t\tdst = ptr;\n\t\tsize = size;\n\t\twhile (size > 0)\n\t\t{\n\t\t found_bad = FALSE;\n\n# ifdef CP_UTF8\t/* VC 4.1 doesn't define CP_UTF8 */\n\t\t if (codepage == CP_UTF8)\n\t\t {\n\t\t\t/* Handle CP_UTF8 input ourselves to be able to handle\n\t\t\t * trailing bytes properly.\n\t\t\t * Get one UTF-8 character from src. */\n\t\t\tbytelen = (int)utf_ptr2len_len(src, size);\n\t\t\tif (bytelen > size)\n\t\t\t{\n\t\t\t /* Only got some bytes of a character. Normally\n\t\t\t * it's put in \"conv_rest\", but if it's too long\n\t\t\t * deal with it as if they were illegal bytes. */\n\t\t\t if (bytelen <= CONV_RESTLEN)\n\t\t\t\tbreak;\n\n\t\t\t /* weird overlong byte sequence */\n\t\t\t bytelen = size;\n\t\t\t found_bad = TRUE;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t int\t u8c = utf_ptr2char(src);\n\n\t\t\t if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))\n\t\t\t\tfound_bad = TRUE;\n\t\t\t ucs2buf[0] = u8c;\n\t\t\t ucs2len = 1;\n\t\t\t}\n\t\t }\n\t\t else\n# endif\n\t\t {\n\t\t\t/* We don't know how long the byte sequence is, try\n\t\t\t * from one to three bytes. */\n\t\t\tfor (bytelen = 1; bytelen <= size && bytelen <= 3;\n\t\t\t\t\t\t\t\t ++bytelen)\n\t\t\t{\n\t\t\t ucs2len = MultiByteToWideChar(codepage,\n\t\t\t\t\t\t\t MB_ERR_INVALID_CHARS,\n\t\t\t\t\t\t\t (LPCSTR)src, bytelen,\n\t\t\t\t\t\t\t\t ucs2buf, 3);\n\t\t\t if (ucs2len > 0)\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (ucs2len == 0)\n\t\t\t{\n\t\t\t /* If we have only one byte then it's probably an\n\t\t\t * incomplete byte sequence. Otherwise discard\n\t\t\t * one byte as a bad character. */\n\t\t\t if (size == 1)\n\t\t\t\tbreak;\n\t\t\t found_bad = TRUE;\n\t\t\t bytelen = 1;\n\t\t\t}\n\t\t }\n\n\t\t if (!found_bad)\n\t\t {\n\t\t\tint\ti;\n\n\t\t\t/* Convert \"ucs2buf[ucs2len]\" to 'enc' in \"dst\". */\n\t\t\tif (enc_utf8)\n\t\t\t{\n\t\t\t /* From UCS-2 to UTF-8. Cannot fail. */\n\t\t\t for (i = 0; i < ucs2len; ++i)\n\t\t\t\tdst += utf_char2bytes(ucs2buf[i], dst);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t BOOL\tbad = FALSE;\n\t\t\t int\t\tdstlen;\n\n\t\t\t /* From UCS-2 to \"enc_codepage\". If the\n\t\t\t * conversion uses the default character \"?\",\n\t\t\t * the data doesn't fit in this encoding. */\n\t\t\t dstlen = WideCharToMultiByte(enc_codepage, 0,\n\t\t\t\t (LPCWSTR)ucs2buf, ucs2len,\n\t\t\t\t (LPSTR)dst, (int)(src - dst),\n\t\t\t\t replstr, &bad);\n\t\t\t if (bad)\n\t\t\t\tfound_bad = TRUE;\n\t\t\t else\n\t\t\t\tdst += dstlen;\n\t\t\t}\n\t\t }\n\n\t\t if (found_bad)\n\t\t {\n\t\t\t/* Deal with bytes we can't convert. */\n\t\t\tif (can_retry)\n\t\t\t goto rewind_retry;\n\t\t\tif (conv_error == 0)\n\t\t\t conv_error = readfile_linenr(linecnt, ptr, dst);\n\t\t\tif (bad_char_behavior != BAD_DROP)\n\t\t\t{\n\t\t\t if (bad_char_behavior == BAD_KEEP)\n\t\t\t {\n\t\t\t\tmch_memmove(dst, src, bytelen);\n\t\t\t\tdst += bytelen;\n\t\t\t }\n\t\t\t else\n\t\t\t\t*dst++ = bad_char_behavior;\n\t\t\t}\n\t\t }\n\n\t\t src += bytelen;\n\t\t size -= bytelen;\n\t\t}\n\n\t\tif (size > 0)\n\t\t{\n\t\t /* An incomplete byte sequence remaining. */\n\t\t mch_memmove(conv_rest, src, size);\n\t\t conv_restlen = size;\n\t\t}\n\n\t\t/* The new size is equal to how much \"dst\" was advanced. */\n\t\tsize = (long)(dst - ptr);\n\t }\n\t else\n# endif\n# ifdef MACOS_CONVERT\n\t if (fio_flags & FIO_MACROMAN)\n\t {\n\t\t/*\n\t\t * Conversion from Apple MacRoman char encoding to UTF-8 or\n\t\t * latin1. This is in os_mac_conv.c.\n\t\t */\n\t\tif (macroman2enc(ptr, &size, real_size) == FAIL)\n\t\t goto rewind_retry;\n\t }\n\t else\n# endif\n\t if (fio_flags != 0)\n\t {\n\t\tint\tu8c;\n\t\tchar_u\t*dest;\n\t\tchar_u\t*tail = NULL;\n\n\t\t/*\n\t\t * \"enc_utf8\" set: Convert Unicode or Latin1 to UTF-8.\n\t\t * \"enc_utf8\" not set: Convert Unicode to Latin1.\n\t\t * Go from end to start through the buffer, because the number\n\t\t * of bytes may increase.\n\t\t * \"dest\" points to after where the UTF-8 bytes go, \"p\" points\n\t\t * to after the next character to convert.\n\t\t */\n\t\tdest = ptr + real_size;\n\t\tif (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)\n\t\t{\n\t\t p = ptr + size;\n\t\t if (fio_flags == FIO_UTF8)\n\t\t {\n\t\t\t/* Check for a trailing incomplete UTF-8 sequence */\n\t\t\ttail = ptr + size - 1;\n\t\t\twhile (tail > ptr && (*tail & 0xc0) == 0x80)\n\t\t\t --tail;\n\t\t\tif (tail + utf_byte2len(*tail) <= ptr + size)\n\t\t\t tail = NULL;\n\t\t\telse\n\t\t\t p = tail;\n\t\t }\n\t\t}\n\t\telse if (fio_flags & (FIO_UCS2 | FIO_UTF16))\n\t\t{\n\t\t /* Check for a trailing byte */\n\t\t p = ptr + (size & ~1);\n\t\t if (size & 1)\n\t\t\ttail = p;\n\t\t if ((fio_flags & FIO_UTF16) && p > ptr)\n\t\t {\n\t\t\t/* Check for a trailing leading word */\n\t\t\tif (fio_flags & FIO_ENDIAN_L)\n\t\t\t{\n\t\t\t u8c = (*--p << 8);\n\t\t\t u8c += *--p;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t u8c = *--p;\n\t\t\t u8c += (*--p << 8);\n\t\t\t}\n\t\t\tif (u8c >= 0xd800 && u8c <= 0xdbff)\n\t\t\t tail = p;\n\t\t\telse\n\t\t\t p += 2;\n\t\t }\n\t\t}\n\t\telse /* FIO_UCS4 */\n\t\t{\n\t\t /* Check for trailing 1, 2 or 3 bytes */\n\t\t p = ptr + (size & ~3);\n\t\t if (size & 3)\n\t\t\ttail = p;\n\t\t}\n\n\t\t/* If there is a trailing incomplete sequence move it to\n\t\t * conv_rest[]. */\n\t\tif (tail != NULL)\n\t\t{\n\t\t conv_restlen = (int)((ptr + size) - tail);\n\t\t mch_memmove(conv_rest, (char_u *)tail, conv_restlen);\n\t\t size -= conv_restlen;\n\t\t}\n\n\n\t\twhile (p > ptr)\n\t\t{\n\t\t if (fio_flags & FIO_LATIN1)\n\t\t\tu8c = *--p;\n\t\t else if (fio_flags & (FIO_UCS2 | FIO_UTF16))\n\t\t {\n\t\t\tif (fio_flags & FIO_ENDIAN_L)\n\t\t\t{\n\t\t\t u8c = (*--p << 8);\n\t\t\t u8c += *--p;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t u8c = *--p;\n\t\t\t u8c += (*--p << 8);\n\t\t\t}\n\t\t\tif ((fio_flags & FIO_UTF16)\n\t\t\t\t\t && u8c >= 0xdc00 && u8c <= 0xdfff)\n\t\t\t{\n\t\t\t int u16c;\n\n\t\t\t if (p == ptr)\n\t\t\t {\n\t\t\t\t/* Missing leading word. */\n\t\t\t\tif (can_retry)\n\t\t\t\t goto rewind_retry;\n\t\t\t\tif (conv_error == 0)\n\t\t\t\t conv_error = readfile_linenr(linecnt,\n\t\t\t\t\t\t\t\t ptr, p);\n\t\t\t\tif (bad_char_behavior == BAD_DROP)\n\t\t\t\t continue;\n\t\t\t\tif (bad_char_behavior != BAD_KEEP)\n\t\t\t\t u8c = bad_char_behavior;\n\t\t\t }\n\n\t\t\t /* found second word of double-word, get the first\n\t\t\t * word and compute the resulting character */\n\t\t\t if (fio_flags & FIO_ENDIAN_L)\n\t\t\t {\n\t\t\t\tu16c = (*--p << 8);\n\t\t\t\tu16c += *--p;\n\t\t\t }\n\t\t\t else\n\t\t\t {\n\t\t\t\tu16c = *--p;\n\t\t\t\tu16c += (*--p << 8);\n\t\t\t }\n\t\t\t u8c = 0x10000 + ((u16c & 0x3ff) << 10)\n\t\t\t\t\t\t\t + (u8c & 0x3ff);\n\n\t\t\t /* Check if the word is indeed a leading word. */\n\t\t\t if (u16c < 0xd800 || u16c > 0xdbff)\n\t\t\t {\n\t\t\t\tif (can_retry)\n\t\t\t\t goto rewind_retry;\n\t\t\t\tif (conv_error == 0)\n\t\t\t\t conv_error = readfile_linenr(linecnt,\n\t\t\t\t\t\t\t\t ptr, p);\n\t\t\t\tif (bad_char_behavior == BAD_DROP)\n\t\t\t\t continue;\n\t\t\t\tif (bad_char_behavior != BAD_KEEP)\n\t\t\t\t u8c = bad_char_behavior;\n\t\t\t }\n\t\t\t}\n\t\t }\n\t\t else if (fio_flags & FIO_UCS4)\n\t\t {\n\t\t\tif (fio_flags & FIO_ENDIAN_L)\n\t\t\t{\n\t\t\t u8c = (unsigned)*--p << 24;\n\t\t\t u8c += (unsigned)*--p << 16;\n\t\t\t u8c += (unsigned)*--p << 8;\n\t\t\t u8c += *--p;\n\t\t\t}\n\t\t\telse\t/* big endian */\n\t\t\t{\n\t\t\t u8c = *--p;\n\t\t\t u8c += (unsigned)*--p << 8;\n\t\t\t u8c += (unsigned)*--p << 16;\n\t\t\t u8c += (unsigned)*--p << 24;\n\t\t\t}\n\t\t }\n\t\t else /* UTF-8 */\n\t\t {\n\t\t\tif (*--p < 0x80)\n\t\t\t u8c = *p;\n\t\t\telse\n\t\t\t{\n\t\t\t len = utf_head_off(ptr, p);\n\t\t\t p -= len;\n\t\t\t u8c = utf_ptr2char(p);\n\t\t\t if (len == 0)\n\t\t\t {\n\t\t\t\t/* Not a valid UTF-8 character, retry with\n\t\t\t\t * another fenc when possible, otherwise just\n\t\t\t\t * report the error. */\n\t\t\t\tif (can_retry)\n\t\t\t\t goto rewind_retry;\n\t\t\t\tif (conv_error == 0)\n\t\t\t\t conv_error = readfile_linenr(linecnt,\n\t\t\t\t\t\t\t\t ptr, p);\n\t\t\t\tif (bad_char_behavior == BAD_DROP)\n\t\t\t\t continue;\n\t\t\t\tif (bad_char_behavior != BAD_KEEP)\n\t\t\t\t u8c = bad_char_behavior;\n\t\t\t }\n\t\t\t}\n\t\t }\n\t\t if (enc_utf8)\t/* produce UTF-8 */\n\t\t {\n\t\t\tdest -= utf_char2len(u8c);\n\t\t\t(void)utf_char2bytes(u8c, dest);\n\t\t }\n\t\t else\t\t/* produce Latin1 */\n\t\t {\n\t\t\t--dest;\n\t\t\tif (u8c >= 0x100)\n\t\t\t{\n\t\t\t /* character doesn't fit in latin1, retry with\n\t\t\t * another fenc when possible, otherwise just\n\t\t\t * report the error. */\n\t\t\t if (can_retry)\n\t\t\t\tgoto rewind_retry;\n\t\t\t if (conv_error == 0)\n\t\t\t\tconv_error = readfile_linenr(linecnt, ptr, p);\n\t\t\t if (bad_char_behavior == BAD_DROP)\n\t\t\t\t++dest;\n\t\t\t else if (bad_char_behavior == BAD_KEEP)\n\t\t\t\t*dest = u8c;\n\t\t\t else if (eap != NULL && eap->bad_char != 0)\n\t\t\t\t*dest = bad_char_behavior;\n\t\t\t else\n\t\t\t\t*dest = 0xBF;\n\t\t\t}\n\t\t\telse\n\t\t\t *dest = u8c;\n\t\t }\n\t\t}\n\n\t\t/* move the linerest to before the converted characters */\n\t\tline_start = dest - linerest;\n\t\tmch_memmove(line_start, buffer, (size_t)linerest);\n\t\tsize = (long)((ptr + real_size) - dest);\n\t\tptr = dest;\n\t }\n\t else if (enc_utf8 && !curbuf->b_p_bin)\n\t {\n\t\tint incomplete_tail = FALSE;\n\n\t\t/* Reading UTF-8: Check if the bytes are valid UTF-8. */\n\t\tfor (p = ptr; ; ++p)\n\t\t{\n\t\t int\t todo = (int)((ptr + size) - p);\n\t\t int\t l;\n\n\t\t if (todo <= 0)\n\t\t\tbreak;\n\t\t if (*p >= 0x80)\n\t\t {\n\t\t\t/* A length of 1 means it's an illegal byte. Accept\n\t\t\t * an incomplete character at the end though, the next\n\t\t\t * read() will get the next bytes, we'll check it\n\t\t\t * then. */\n\t\t\tl = utf_ptr2len_len(p, todo);\n\t\t\tif (l > todo && !incomplete_tail)\n\t\t\t{\n\t\t\t /* Avoid retrying with a different encoding when\n\t\t\t * a truncated file is more likely, or attempting\n\t\t\t * to read the rest of an incomplete sequence when\n\t\t\t * we have already done so. */\n\t\t\t if (p > ptr || filesize > 0)\n\t\t\t\tincomplete_tail = TRUE;\n\t\t\t /* Incomplete byte sequence, move it to conv_rest[]\n\t\t\t * and try to read the rest of it, unless we've\n\t\t\t * already done so. */\n\t\t\t if (p > ptr)\n\t\t\t {\n\t\t\t\tconv_restlen = todo;\n\t\t\t\tmch_memmove(conv_rest, p, conv_restlen);\n\t\t\t\tsize -= conv_restlen;\n\t\t\t\tbreak;\n\t\t\t }\n\t\t\t}\n\t\t\tif (l == 1 || l > todo)\n\t\t\t{\n\t\t\t /* Illegal byte. If we can try another encoding\n\t\t\t * do that, unless at EOF where a truncated\n\t\t\t * file is more likely than a conversion error. */\n\t\t\t if (can_retry && !incomplete_tail)\n\t\t\t\tbreak;\n# ifdef USE_ICONV\n\t\t\t /* When we did a conversion report an error. */\n\t\t\t if (iconv_fd != (iconv_t)-1 && conv_error == 0)\n\t\t\t\tconv_error = readfile_linenr(linecnt, ptr, p);\n# endif\n\t\t\t /* Remember the first linenr with an illegal byte */\n\t\t\t if (conv_error == 0 && illegal_byte == 0)\n\t\t\t\tillegal_byte = readfile_linenr(linecnt, ptr, p);\n\n\t\t\t /* Drop, keep or replace the bad byte. */\n\t\t\t if (bad_char_behavior == BAD_DROP)\n\t\t\t {\n\t\t\t\tmch_memmove(p, p + 1, todo - 1);\n\t\t\t\t--p;\n\t\t\t\t--size;\n\t\t\t }\n\t\t\t else if (bad_char_behavior != BAD_KEEP)\n\t\t\t\t*p = bad_char_behavior;\n\t\t\t}\n\t\t\telse\n\t\t\t p += l - 1;\n\t\t }\n\t\t}\n\t\tif (p < ptr + size && !incomplete_tail)\n\t\t{\n\t\t /* Detected a UTF-8 error. */\nrewind_retry:\n\t\t /* Retry reading with another conversion. */\n# if defined(FEAT_EVAL) && defined(USE_ICONV)\n\t\t if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)\n\t\t\t/* iconv() failed, try 'charconvert' */\n\t\t\tdid_iconv = TRUE;\n\t\t else\n# endif\n\t\t\t/* use next item from 'fileencodings' */\n\t\t\tadvance_fenc = TRUE;\n\t\t file_rewind = TRUE;\n\t\t goto retry;\n\t\t}\n\t }\n#endif\n\n\t /* count the number of characters (after conversion!) */\n\t filesize += size;\n\n\t /*\n\t * when reading the first part of a file: guess EOL type\n\t */\n\t if (fileformat == EOL_UNKNOWN)\n\t {\n\t\t/* First try finding a NL, for Dos and Unix */\n\t\tif (try_dos || try_unix)\n\t\t{\n\t\t /* Reset the carriage return counter. */\n\t\t if (try_mac)\n\t\t\ttry_mac = 1;\n\n\t\t for (p = ptr; p < ptr + size; ++p)\n\t\t {\n\t\t\tif (*p == NL)\n\t\t\t{\n\t\t\t if (!try_unix\n\t\t\t\t || (try_dos && p > ptr && p[-1] == CAR))\n\t\t\t\tfileformat = EOL_DOS;\n\t\t\t else\n\t\t\t\tfileformat = EOL_UNIX;\n\t\t\t break;\n\t\t\t}\n\t\t\telse if (*p == CAR && try_mac)\n\t\t\t try_mac++;\n\t\t }\n\n\t\t /* Don't give in to EOL_UNIX if EOL_MAC is more likely */\n\t\t if (fileformat == EOL_UNIX && try_mac)\n\t\t {\n\t\t\t/* Need to reset the counters when retrying fenc. */\n\t\t\ttry_mac = 1;\n\t\t\ttry_unix = 1;\n\t\t\tfor (; p >= ptr && *p != CAR; p--)\n\t\t\t ;\n\t\t\tif (p >= ptr)\n\t\t\t{\n\t\t\t for (p = ptr; p < ptr + size; ++p)\n\t\t\t {\n\t\t\t\tif (*p == NL)\n\t\t\t\t try_unix++;\n\t\t\t\telse if (*p == CAR)\n\t\t\t\t try_mac++;\n\t\t\t }\n\t\t\t if (try_mac > try_unix)\n\t\t\t\tfileformat = EOL_MAC;\n\t\t\t}\n\t\t }\n\t\t else if (fileformat == EOL_UNKNOWN && try_mac == 1)\n\t\t\t/* Looking for CR but found no end-of-line markers at\n\t\t\t * all: use the default format. */\n\t\t\tfileformat = default_fileformat();\n\t\t}\n\n\t\t/* No NL found: may use Mac format */\n\t\tif (fileformat == EOL_UNKNOWN && try_mac)\n\t\t fileformat = EOL_MAC;\n\n\t\t/* Still nothing found? Use first format in 'ffs' */\n\t\tif (fileformat == EOL_UNKNOWN)\n\t\t fileformat = default_fileformat();\n\n\t\t/* if editing a new file: may set p_tx and p_ff */\n\t\tif (set_options)\n\t\t set_fileformat(fileformat, OPT_LOCAL);\n\t }\n\t}\n\n\t/*\n\t * This loop is executed once for every character read.\n\t * Keep it fast!\n\t */\n\tif (fileformat == EOL_MAC)\n\t{\n\t --ptr;\n\t while (++ptr, --size >= 0)\n\t {\n\t\t/* catch most common case first */\n\t\tif ((c = *ptr) != NUL && c != CAR && c != NL)\n\t\t continue;\n\t\tif (c == NUL)\n\t\t *ptr = NL;\t/* NULs are replaced by newlines! */\n\t\telse if (c == NL)\n\t\t *ptr = CAR;\t/* NLs are replaced by CRs! */\n\t\telse\n\t\t{\n\t\t if (skip_count == 0)\n\t\t {\n\t\t\t*ptr = NUL;\t /* end of line */\n\t\t\tlen = (colnr_T) (ptr - line_start + 1);\n\t\t\tif (ml_append(lnum, line_start, len, newfile) == FAIL)\n\t\t\t{\n\t\t\t error = TRUE;\n\t\t\t break;\n\t\t\t}\n#ifdef FEAT_PERSISTENT_UNDO\n\t\t\tif (read_undo_file)\n\t\t\t sha256_update(&sha_ctx, line_start, len);\n#endif\n\t\t\t++lnum;\n\t\t\tif (--read_count == 0)\n\t\t\t{\n\t\t\t error = TRUE;\t/* break loop */\n\t\t\t line_start = ptr;\t/* nothing left to write */\n\t\t\t break;\n\t\t\t}\n\t\t }\n\t\t else\n\t\t\t--skip_count;\n\t\t line_start = ptr + 1;\n\t\t}\n\t }\n\t}\n\telse\n\t{\n\t --ptr;\n\t while (++ptr, --size >= 0)\n\t {\n\t\tif ((c = *ptr) != NUL && c != NL) /* catch most common case */\n\t\t continue;\n\t\tif (c == NUL)\n\t\t *ptr = NL;\t/* NULs are replaced by newlines! */\n\t\telse\n\t\t{\n\t\t if (skip_count == 0)\n\t\t {\n\t\t\t*ptr = NUL;\t\t/* end of line */\n\t\t\tlen = (colnr_T)(ptr - line_start + 1);\n\t\t\tif (fileformat == EOL_DOS)\n\t\t\t{\n\t\t\t if (ptr > line_start && ptr[-1] == CAR)\n\t\t\t {\n\t\t\t\t/* remove CR before NL */\n\t\t\t\tptr[-1] = NUL;\n\t\t\t\t--len;\n\t\t\t }\n\t\t\t /*\n\t\t\t * Reading in Dos format, but no CR-LF found!\n\t\t\t * When 'fileformats' includes \"unix\", delete all\n\t\t\t * the lines read so far and start all over again.\n\t\t\t * Otherwise give an error message later.\n\t\t\t */\n\t\t\t else if (ff_error != EOL_DOS)\n\t\t\t {\n\t\t\t\tif ( try_unix\n\t\t\t\t && !read_stdin\n\t\t\t\t && (read_buffer\n\t\t\t\t\t|| vim_lseek(fd, (off_T)0L, SEEK_SET)\n\t\t\t\t\t\t\t\t\t == 0))\n\t\t\t\t{\n\t\t\t\t fileformat = EOL_UNIX;\n\t\t\t\t if (set_options)\n\t\t\t\t\tset_fileformat(EOL_UNIX, OPT_LOCAL);\n\t\t\t\t file_rewind = TRUE;\n\t\t\t\t keep_fileformat = TRUE;\n\t\t\t\t goto retry;\n\t\t\t\t}\n\t\t\t\tff_error = EOL_DOS;\n\t\t\t }\n\t\t\t}\n\t\t\tif (ml_append(lnum, line_start, len, newfile) == FAIL)\n\t\t\t{\n\t\t\t error = TRUE;\n\t\t\t break;\n\t\t\t}\n#ifdef FEAT_PERSISTENT_UNDO\n\t\t\tif (read_undo_file)\n\t\t\t sha256_update(&sha_ctx, line_start, len);\n#endif\n\t\t\t++lnum;\n\t\t\tif (--read_count == 0)\n\t\t\t{\n\t\t\t error = TRUE;\t /* break loop */\n\t\t\t line_start = ptr;\t/* nothing left to write */\n\t\t\t break;\n\t\t\t}\n\t\t }\n\t\t else\n\t\t\t--skip_count;\n\t\t line_start = ptr + 1;\n\t\t}\n\t }\n\t}\n\tlinerest = (long)(ptr - line_start);\n\tui_breakcheck();\n }\n\nfailed:\n /* not an error, max. number of lines reached */\n if (error && read_count == 0)\n\terror = FALSE;\n\n /*\n * If we get EOF in the middle of a line, note the fact and\n * complete the line ourselves.\n * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.\n */\n if (!error\n\t && !got_int\n\t && linerest != 0\n\t && !(!curbuf->b_p_bin\n\t\t&& fileformat == EOL_DOS\n\t\t&& *line_start == Ctrl_Z\n\t\t&& ptr == line_start + 1))\n {\n\t/* remember for when writing */\n\tif (set_options)\n\t curbuf->b_p_eol = FALSE;\n\t*ptr = NUL;\n\tlen = (colnr_T)(ptr - line_start + 1);\n\tif (ml_append(lnum, line_start, len, newfile) == FAIL)\n\t error = TRUE;\n\telse\n\t{\n#ifdef FEAT_PERSISTENT_UNDO\n\t if (read_undo_file)\n\t\tsha256_update(&sha_ctx, line_start, len);\n#endif\n\t read_no_eol_lnum = ++lnum;\n\t}\n }\n\n if (set_options)\n\tsave_file_ff(curbuf);\t\t/* remember the current file format */\n\n#ifdef FEAT_CRYPT\n if (curbuf->b_cryptstate != NULL)\n {\n\tcrypt_free_state(curbuf->b_cryptstate);\n\tcurbuf->b_cryptstate = NULL;\n }\n if (cryptkey != NULL && cryptkey != curbuf->b_p_key)\n\tcrypt_free_key(cryptkey);\n /* Don't set cryptkey to NULL, it's used below as a flag that\n * encryption was used. */\n#endif\n\n#ifdef FEAT_MBYTE\n /* If editing a new file: set 'fenc' for the current buffer.\n * Also for \":read ++edit file\". */\n if (set_options)\n\tset_string_option_direct((char_u *)\"fenc\", -1, fenc,\n\t\t\t\t\t\t OPT_FREE|OPT_LOCAL, 0);\n if (fenc_alloced)\n\tvim_free(fenc);\n# ifdef USE_ICONV\n if (iconv_fd != (iconv_t)-1)\n {\n\ticonv_close(iconv_fd);\n\ticonv_fd = (iconv_t)-1;\n }\n# endif\n#endif\n\n if (!read_buffer && !read_stdin)\n\tclose(fd);\t\t\t\t/* errors are ignored */\n#ifdef HAVE_FD_CLOEXEC\n else\n {\n\tint fdflags = fcntl(fd, F_GETFD);\n\tif (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)\n\t (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);\n }\n#endif\n vim_free(buffer);\n\n#ifdef HAVE_DUP\n if (read_stdin)\n {\n\t/* Use stderr for stdin, makes shell commands work. */\n\tclose(0);\n\tignored = dup(2);\n }\n#endif\n\n#ifdef FEAT_MBYTE\n if (tmpname != NULL)\n {\n\tmch_remove(tmpname);\t\t/* delete converted file */\n\tvim_free(tmpname);\n }\n#endif\n --no_wait_return;\t\t\t/* may wait for return now */\n\n /*\n * In recovery mode everything but autocommands is skipped.\n */\n if (!recoverymode)\n {\n\t/* need to delete the last line, which comes from the empty buffer */\n\tif (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))\n\t{\n#ifdef FEAT_NETBEANS_INTG\n\t netbeansFireChanges = 0;\n#endif\n\t ml_delete(curbuf->b_ml.ml_line_count, FALSE);\n#ifdef FEAT_NETBEANS_INTG\n\t netbeansFireChanges = 1;\n#endif\n\t --linecnt;\n\t}\n\tlinecnt = curbuf->b_ml.ml_line_count - linecnt;\n\tif (filesize == 0)\n\t linecnt = 0;\n\tif (newfile || read_buffer)\n\t{\n\t redraw_curbuf_later(NOT_VALID);\n#ifdef FEAT_DIFF\n\t /* After reading the text into the buffer the diff info needs to\n\t * be updated. */\n\t diff_invalidate(curbuf);\n#endif\n#ifdef FEAT_FOLDING\n\t /* All folds in the window are invalid now. Mark them for update\n\t * before triggering autocommands. */\n\t foldUpdateAll(curwin);\n#endif\n\t}\n\telse if (linecnt)\t\t/* appended at least one line */\n\t appended_lines_mark(from, linecnt);\n\n#ifndef ALWAYS_USE_GUI\n\t/*\n\t * If we were reading from the same terminal as where messages go,\n\t * the screen will have been messed up.\n\t * Switch on raw mode now and clear the screen.\n\t */\n\tif (read_stdin)\n\t{\n\t settmode(TMODE_RAW);\t/* set to raw mode */\n\t starttermcap();\n\t screenclear();\n\t}\n#endif\n\n\tif (got_int)\n\t{\n\t if (!(flags & READ_DUMMY))\n\t {\n\t\tfilemess(curbuf, sfname, (char_u *)_(e_interr), 0);\n\t\tif (newfile)\n\t\t curbuf->b_p_ro = TRUE;\t/* must use \"w!\" now */\n\t }\n\t msg_scroll = msg_save;\n#ifdef FEAT_VIMINFO\n\t check_marks_read();\n#endif\n\t return OK;\t\t/* an interrupt isn't really an error */\n\t}\n\n\tif (!filtering && !(flags & READ_DUMMY))\n\t{\n\t msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */\n\t c = FALSE;\n\n#ifdef UNIX\n# ifdef S_ISFIFO\n\t if (S_ISFIFO(perm))\t\t\t /* fifo or socket */\n\t {\n\t\tSTRCAT(IObuff, _(\"[fifo/socket]\"));\n\t\tc = TRUE;\n\t }\n# else\n# ifdef S_IFIFO\n\t if ((perm & S_IFMT) == S_IFIFO)\t /* fifo */\n\t {\n\t\tSTRCAT(IObuff, _(\"[fifo]\"));\n\t\tc = TRUE;\n\t }\n# endif\n# ifdef S_IFSOCK\n\t if ((perm & S_IFMT) == S_IFSOCK)\t /* or socket */\n\t {\n\t\tSTRCAT(IObuff, _(\"[socket]\"));\n\t\tc = TRUE;\n\t }\n# endif\n# endif\n# ifdef OPEN_CHR_FILES\n\t if (S_ISCHR(perm))\t\t\t /* or character special */\n\t {\n\t\tSTRCAT(IObuff, _(\"[character special]\"));\n\t\tc = TRUE;\n\t }\n# endif\n#endif\n\t if (curbuf->b_p_ro)\n\t {\n\t\tSTRCAT(IObuff, shortmess(SHM_RO) ? _(\"[RO]\") : _(\"[readonly]\"));\n\t\tc = TRUE;\n\t }\n\t if (read_no_eol_lnum)\n\t {\n\t\tmsg_add_eol();\n\t\tc = TRUE;\n\t }\n\t if (ff_error == EOL_DOS)\n\t {\n\t\tSTRCAT(IObuff, _(\"[CR missing]\"));\n\t\tc = TRUE;\n\t }\n\t if (split)\n\t {\n\t\tSTRCAT(IObuff, _(\"[long lines split]\"));\n\t\tc = TRUE;\n\t }\n#ifdef FEAT_MBYTE\n\t if (notconverted)\n\t {\n\t\tSTRCAT(IObuff, _(\"[NOT converted]\"));\n\t\tc = TRUE;\n\t }\n\t else if (converted)\n\t {\n\t\tSTRCAT(IObuff, _(\"[converted]\"));\n\t\tc = TRUE;\n\t }\n#endif\n#ifdef FEAT_CRYPT\n\t if (cryptkey != NULL)\n\t {\n\t\tcrypt_append_msg(curbuf);\n\t\tc = TRUE;\n\t }\n#endif\n#ifdef FEAT_MBYTE\n\t if (conv_error != 0)\n\t {\n\t\tsprintf((char *)IObuff + STRLEN(IObuff),\n\t\t _(\"[CONVERSION ERROR in line %ld]\"), (long)conv_error);\n\t\tc = TRUE;\n\t }\n\t else if (illegal_byte > 0)\n\t {\n\t\tsprintf((char *)IObuff + STRLEN(IObuff),\n\t\t\t _(\"[ILLEGAL BYTE in line %ld]\"), (long)illegal_byte);\n\t\tc = TRUE;\n\t }\n\t else\n#endif\n\t\tif (error)\n\t {\n\t\tSTRCAT(IObuff, _(\"[READ ERRORS]\"));\n\t\tc = TRUE;\n\t }\n\t if (msg_add_fileformat(fileformat))\n\t\tc = TRUE;\n#ifdef FEAT_CRYPT\n\t if (cryptkey != NULL)\n\t\tmsg_add_lines(c, (long)linecnt, filesize\n\t\t\t - crypt_get_header_len(crypt_get_method_nr(curbuf)));\n\t else\n#endif\n\t\tmsg_add_lines(c, (long)linecnt, filesize);\n\n\t vim_free(keep_msg);\n\t keep_msg = NULL;\n\t msg_scrolled_ign = TRUE;\n#ifdef ALWAYS_USE_GUI\n\t /* Don't show the message when reading stdin, it would end up in a\n\t * message box (which might be shown when exiting!) */\n\t if (read_stdin || read_buffer)\n\t\tp = msg_may_trunc(FALSE, IObuff);\n\t else\n#endif\n\t\tp = msg_trunc_attr(IObuff, FALSE, 0);\n\t if (read_stdin || read_buffer || restart_edit != 0\n\t\t || (msg_scrolled != 0 && !need_wait_return))\n\t\t/* Need to repeat the message after redrawing when:\n\t\t * - When reading from stdin (the screen will be cleared next).\n\t\t * - When restart_edit is set (otherwise there will be a delay\n\t\t * before redrawing).\n\t\t * - When the screen was scrolled but there is no wait-return\n\t\t * prompt. */\n\t\tset_keep_msg(p, 0);\n\t msg_scrolled_ign = FALSE;\n\t}\n\n\t/* with errors writing the file requires \":w!\" */\n\tif (newfile && (error\n#ifdef FEAT_MBYTE\n\t\t || conv_error != 0\n\t\t || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)\n#endif\n\t\t ))\n\t curbuf->b_p_ro = TRUE;\n\n\tu_clearline();\t /* cannot use \"U\" command after adding lines */\n\n\t/*\n\t * In Ex mode: cursor at last new line.\n\t * Otherwise: cursor at first new line.\n\t */\n\tif (exmode_active)\n\t curwin->w_cursor.lnum = from + linecnt;\n\telse\n\t curwin->w_cursor.lnum = from + 1;\n\tcheck_cursor_lnum();\n\tbeginline(BL_WHITE | BL_FIX);\t /* on first non-blank */\n\n\t/*\n\t * Set '[ and '] marks to the newly read lines.\n\t */\n\tcurbuf->b_op_start.lnum = from + 1;\n\tcurbuf->b_op_start.col = 0;\n\tcurbuf->b_op_end.lnum = from + linecnt;\n\tcurbuf->b_op_end.col = 0;\n\n#ifdef WIN32\n\t/*\n\t * Work around a weird problem: When a file has two links (only\n\t * possible on NTFS) and we write through one link, then stat() it\n\t * through the other link, the timestamp information may be wrong.\n\t * It's correct again after reading the file, thus reset the timestamp\n\t * here.\n\t */\n\tif (newfile && !read_stdin && !read_buffer\n\t\t\t\t\t && mch_stat((char *)fname, &st) >= 0)\n\t{\n\t buf_store_time(curbuf, &st, fname);\n\t curbuf->b_mtime_read = curbuf->b_mtime;\n\t}\n#endif\n }\n msg_scroll = msg_save;\n\n#ifdef FEAT_VIMINFO\n /*\n * Get the marks before executing autocommands, so they can be used there.\n */\n check_marks_read();\n#endif\n\n /*\n * We remember if the last line of the read didn't have\n * an eol even when 'binary' is off, to support turning 'fixeol' off,\n * or writing the read again with 'binary' on. The latter is required\n * for \":autocmd FileReadPost *.gz set bin|'[,']!gunzip\" to work.\n */\n curbuf->b_no_eol_lnum = read_no_eol_lnum;\n\n /* When reloading a buffer put the cursor at the first line that is\n * different. */\n if (flags & READ_KEEP_UNDO)\n\tu_find_first_changed();\n\n#ifdef FEAT_PERSISTENT_UNDO\n /*\n * When opening a new file locate undo info and read it.\n */\n if (read_undo_file)\n {\n\tchar_u\thash[UNDO_HASH_SIZE];\n\n\tsha256_finish(&sha_ctx, hash);\n\tu_read_undo(NULL, hash, fname);\n }\n#endif\n\n#ifdef FEAT_AUTOCMD\n if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL))\n {\n\tint m = msg_scroll;\n\tint n = msg_scrolled;\n\n\t/* Save the fileformat now, otherwise the buffer will be considered\n\t * modified if the format/encoding was automatically detected. */\n\tif (set_options)\n\t save_file_ff(curbuf);\n\n\t/*\n\t * The output from the autocommands should not overwrite anything and\n\t * should not be overwritten: Set msg_scroll, restore its value if no\n\t * output was done.\n\t */\n\tmsg_scroll = TRUE;\n\tif (filtering)\n\t apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,\n\t\t\t\t\t\t\t FALSE, curbuf, eap);\n\telse if (newfile || (read_buffer && sfname != NULL))\n\t{\n\t apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,\n\t\t\t\t\t\t\t FALSE, curbuf, eap);\n\t if (!au_did_filetype && *curbuf->b_p_ft != NUL)\n\t\t/*\n\t\t * EVENT_FILETYPE was not triggered but the buffer already has a\n\t\t * filetype. Trigger EVENT_FILETYPE using the existing filetype.\n\t\t */\n\t\tapply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,\n\t\t\tTRUE, curbuf);\n\t}\n\telse\n\t apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,\n\t\t\t\t\t\t\t FALSE, NULL, eap);\n\tif (msg_scrolled == n)\n\t msg_scroll = m;\n# ifdef FEAT_EVAL\n\tif (aborting())\t /* autocmds may abort script processing */\n\t return FAIL;\n# endif\n }\n#endif\n\n if (recoverymode && error)\n\treturn FAIL;\n return OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-668'], 'message': 'patch 8.0.1263: others can read the swap file if a user is careless\n\nProblem: Others can read the swap file if a user is careless with his\n primary group.\nSolution: If the group permission allows for reading but the world\n permissions doesn't, make sure the group is right.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int nfnl_cthelper_new(struct net *net, struct sock *nfnl,\n\t\t\t struct sk_buff *skb, const struct nlmsghdr *nlh,\n\t\t\t const struct nlattr * const tb[],\n\t\t\t struct netlink_ext_ack *extack)\n{\n\tconst char *helper_name;\n\tstruct nf_conntrack_helper *cur, *helper = NULL;\n\tstruct nf_conntrack_tuple tuple;\n\tstruct nfnl_cthelper *nlcth;\n\tint ret = 0;\n\n\tif (!tb[NFCTH_NAME] || !tb[NFCTH_TUPLE])\n\t\treturn -EINVAL;\n\n\thelper_name = nla_data(tb[NFCTH_NAME]);\n\n\tret = nfnl_cthelper_parse_tuple(&tuple, tb[NFCTH_TUPLE]);\n\tif (ret < 0)\n\t\treturn ret;\n\n\tlist_for_each_entry(nlcth, &nfnl_cthelper_list, list) {\n\t\tcur = &nlcth->helper;\n\n\t\tif (strncmp(cur->name, helper_name, NF_CT_HELPER_NAME_LEN))\n\t\t\tcontinue;\n\n\t\tif ((tuple.src.l3num != cur->tuple.src.l3num ||\n\t\t tuple.dst.protonum != cur->tuple.dst.protonum))\n\t\t\tcontinue;\n\n\t\tif (nlh->nlmsg_flags & NLM_F_EXCL)\n\t\t\treturn -EEXIST;\n\n\t\thelper = cur;\n\t\tbreak;\n\t}\n\n\tif (helper == NULL)\n\t\tret = nfnl_cthelper_create(tb, &tuple);\n\telse\n\t\tret = nfnl_cthelper_update(tb, helper);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-862'], 'message': 'netfilter: nfnetlink_cthelper: Add missing permission checks\n\nThe capability check in nfnetlink_rcv() verifies that the caller\nhas CAP_NET_ADMIN in the namespace that \"owns\" the netlink socket.\nHowever, nfnl_cthelper_list is shared by all net namespaces on the\nsystem. An unprivileged user can create user and net namespaces\nin which he holds CAP_NET_ADMIN to bypass the netlink_net_capable()\ncheck:\n\n $ nfct helper list\n nfct v1.4.4: netlink error: Operation not permitted\n $ vpnns -- nfct helper list\n {\n .name = ftp,\n .queuenum = 0,\n .l3protonum = 2,\n .l4protonum = 6,\n .priv_data_len = 24,\n .status = enabled,\n };\n\nAdd capable() checks in nfnetlink_cthelper, as this is cleaner than\ntrying to generalize the solution.\n\nSigned-off-by: Kevin Cernekee \nSigned-off-by: Pablo Neira Ayuso '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int 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.src.virt.addr,\n\t\t\t\t walk.dst.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.src.virt.addr,\n\t\t\t\t walk.dst.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.src.virt.addr,\n\t\t\t\t walk.dst.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 __attribute__((unused))cdate = 0;\n guint32 __attribute__((unused))mdate = 0;\n guint32 __attribute__((unused))appid;\n guint32 __attribute__((unused))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.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void fli_read_lc_2(FILE *f, s_fli_header *fli_header, unsigned char *old_framebuf, unsigned char *framebuf)\n{\n\tunsigned short yc, lc, numline;\n\tunsigned char *pos;\n\tmemcpy(framebuf, old_framebuf, fli_header->width * fli_header->height);\n\tyc=0;\n\tnumline = fli_read_short(f);\n\tfor (lc=0; lc < numline; lc++) {\n\t\tunsigned short xc, pc, pcnt, lpf, lpn;\n\t\tpc=fli_read_short(f);\n\t\tlpf=0; lpn=0;\n\t\twhile (pc & 0x8000) {\n\t\t\tif (pc & 0x4000) {\n\t\t\t\tyc+=-(signed short)pc;\n\t\t\t} else {\n\t\t\t\tlpf=1;lpn=pc&0xFF;\n\t\t\t}\n\t\t\tpc=fli_read_short(f);\n\t\t}\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,skip;\n\t\t\tskip=fli_read_char(f);\n\t\t\tps=fli_read_char(f);\n\t\t\txc+=skip;\n\t\t\tif (ps & 0x80) {\n\t\t\t\tunsigned char v1,v2;\n\t\t\t\tps=-(signed char)ps;\n\t\t\t\tv1=fli_read_char(f);\n\t\t\t\tv2=fli_read_char(f);\n\t\t\t\twhile (ps>0) {\n\t\t\t\t\tpos[xc++]=v1;\n\t\t\t\t\tpos[xc++]=v2;\n\t\t\t\t\tps--;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfread(&(pos[xc]), ps, 2, f);\n\t\t\t\txc+=ps << 1;\n\t\t\t}\n\t\t}\n\t\tif (lpf) pos[xc]=lpn;\n\t\tyc++;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Bug 739133 - (CVE-2017-17785) Heap overflow while parsing FLI files.\n\nIt is possible to trigger a heap overflow while parsing FLI files. The\nRLE decoder is vulnerable to out of boundary writes due to lack of\nboundary checks.\n\nThe variable \"framebuf\" points to a memory area which was allocated\nwith fli_header->width * fli_header->height bytes. The RLE decoder\ntherefore must never write beyond that limit.\n\nIf an illegal frame is detected, the parser won't stop, which means\nthat the next valid sequence is properly parsed again. This should\nallow GIMP to parse FLI files as good as possible even if they are\nbroken by an attacker or by accident.\n\nWhile at it, I changed the variable xc to be of type size_t, because\nthe multiplication of width and height could overflow a 16 bit type.\n\nSigned-off-by: Tobias Stoeckmann '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info,\n const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception)\n{\n char\n im_vers[32],\n libpng_runv[32],\n libpng_vers[32],\n zlib_runv[32],\n zlib_vers[32];\n\n Image\n *image;\n\n ImageInfo\n *image_info;\n\n char\n s[2];\n\n const char\n *name,\n *property,\n *value;\n\n const StringInfo\n *profile;\n\n int\n num_passes,\n pass,\n ping_wrote_caNv;\n\n png_byte\n ping_trans_alpha[256];\n\n png_color\n palette[257];\n\n png_color_16\n ping_background,\n ping_trans_color;\n\n png_info\n *ping_info;\n\n png_struct\n *ping;\n\n png_uint_32\n ping_height,\n ping_width;\n\n ssize_t\n y;\n\n MagickBooleanType\n image_matte,\n logging,\n matte,\n\n ping_have_blob,\n ping_have_cheap_transparency,\n ping_have_color,\n ping_have_non_bw,\n ping_have_PLTE,\n ping_have_bKGD,\n ping_have_eXIf,\n ping_have_iCCP,\n ping_have_pHYs,\n ping_have_sRGB,\n ping_have_tRNS,\n\n ping_exclude_bKGD,\n ping_exclude_cHRM,\n ping_exclude_date,\n /* ping_exclude_EXIF, */\n ping_exclude_eXIf,\n ping_exclude_gAMA,\n ping_exclude_iCCP,\n /* ping_exclude_iTXt, */\n ping_exclude_oFFs,\n ping_exclude_pHYs,\n ping_exclude_sRGB,\n ping_exclude_tEXt,\n ping_exclude_tIME,\n /* ping_exclude_tRNS, */\n ping_exclude_caNv,\n ping_exclude_zCCP, /* hex-encoded iCCP */\n ping_exclude_zTXt,\n\n ping_preserve_colormap,\n ping_preserve_iCCP,\n ping_need_colortype_warning,\n\n status,\n tried_332,\n tried_333,\n tried_444;\n\n MemoryInfo\n *volatile pixel_info;\n\n QuantumInfo\n *quantum_info;\n\n PNGErrorInfo\n error_info;\n\n register ssize_t\n i,\n x;\n\n unsigned char\n *ping_pixels;\n\n volatile int\n image_colors,\n ping_bit_depth,\n ping_color_type,\n ping_interlace_method,\n ping_compression_method,\n ping_filter_method,\n ping_num_trans;\n\n volatile size_t\n image_depth,\n old_bit_depth;\n\n size_t\n quality,\n rowbytes,\n save_image_depth;\n\n int\n j,\n number_colors,\n number_opaque,\n number_semitransparent,\n number_transparent,\n ping_pHYs_unit_type;\n\n png_uint_32\n ping_pHYs_x_resolution,\n ping_pHYs_y_resolution;\n\n logging=LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Enter WriteOnePNGImage()\");\n\n image = CloneImage(IMimage,0,0,MagickFalse,exception);\n if (image == (Image *) NULL)\n return(MagickFalse);\n image_info=(ImageInfo *) CloneImageInfo(IMimage_info);\n\n /* Define these outside of the following \"if logging()\" block so they will\n * show in debuggers.\n */\n *im_vers='\\0';\n (void) ConcatenateMagickString(im_vers,\n MagickLibVersionText,MagickPathExtent);\n (void) ConcatenateMagickString(im_vers,\n MagickLibAddendum,MagickPathExtent);\n\n *libpng_vers='\\0';\n (void) ConcatenateMagickString(libpng_vers,\n PNG_LIBPNG_VER_STRING,32);\n *libpng_runv='\\0';\n (void) ConcatenateMagickString(libpng_runv,\n png_get_libpng_ver(NULL),32);\n\n *zlib_vers='\\0';\n (void) ConcatenateMagickString(zlib_vers,\n ZLIB_VERSION,32);\n *zlib_runv='\\0';\n (void) ConcatenateMagickString(zlib_runv,\n zlib_version,32);\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" IM version = %s\", im_vers);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Libpng version = %s\", libpng_vers);\n if (LocaleCompare(libpng_vers,libpng_runv) != 0)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" running with %s\", libpng_runv);\n }\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Zlib version = %s\", zlib_vers);\n if (LocaleCompare(zlib_vers,zlib_runv) != 0)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" running with %s\", zlib_runv);\n }\n }\n\n /* Initialize some stuff */\n ping_bit_depth=0,\n ping_color_type=0,\n ping_interlace_method=0,\n ping_compression_method=0,\n ping_filter_method=0,\n ping_num_trans = 0;\n\n ping_background.red = 0;\n ping_background.green = 0;\n ping_background.blue = 0;\n ping_background.gray = 0;\n ping_background.index = 0;\n\n ping_trans_color.red=0;\n ping_trans_color.green=0;\n ping_trans_color.blue=0;\n ping_trans_color.gray=0;\n\n ping_pHYs_unit_type = 0;\n ping_pHYs_x_resolution = 0;\n ping_pHYs_y_resolution = 0;\n\n ping_have_blob=MagickFalse;\n ping_have_cheap_transparency=MagickFalse;\n ping_have_color=MagickTrue;\n ping_have_non_bw=MagickTrue;\n ping_have_PLTE=MagickFalse;\n ping_have_bKGD=MagickFalse;\n ping_have_eXIf=MagickTrue;\n ping_have_iCCP=MagickFalse;\n ping_have_pHYs=MagickFalse;\n ping_have_sRGB=MagickFalse;\n ping_have_tRNS=MagickFalse;\n\n ping_exclude_bKGD=mng_info->ping_exclude_bKGD;\n ping_exclude_caNv=mng_info->ping_exclude_caNv;\n ping_exclude_cHRM=mng_info->ping_exclude_cHRM;\n ping_exclude_date=mng_info->ping_exclude_date;\n ping_exclude_eXIf=mng_info->ping_exclude_eXIf;\n ping_exclude_gAMA=mng_info->ping_exclude_gAMA;\n ping_exclude_iCCP=mng_info->ping_exclude_iCCP;\n /* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */\n ping_exclude_oFFs=mng_info->ping_exclude_oFFs;\n ping_exclude_pHYs=mng_info->ping_exclude_pHYs;\n ping_exclude_sRGB=mng_info->ping_exclude_sRGB;\n ping_exclude_tEXt=mng_info->ping_exclude_tEXt;\n ping_exclude_tIME=mng_info->ping_exclude_tIME;\n /* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */\n ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */\n ping_exclude_zTXt=mng_info->ping_exclude_zTXt;\n\n ping_preserve_colormap = mng_info->ping_preserve_colormap;\n ping_preserve_iCCP = mng_info->ping_preserve_iCCP;\n ping_need_colortype_warning = MagickFalse;\n\n /* Recognize the ICC sRGB profile and convert it to the sRGB chunk,\n * i.e., eliminate the ICC profile and set image->rendering_intent.\n * Note that this will not involve any changes to the actual pixels\n * but merely passes information to applications that read the resulting\n * PNG image.\n *\n * To do: recognize other variants of the sRGB profile, using the CRC to\n * verify all recognized variants including the 7 already known.\n *\n * Work around libpng16+ rejecting some \"known invalid sRGB profiles\".\n *\n * Use something other than image->rendering_intent to record the fact\n * that the sRGB profile was found.\n *\n * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC\n * profile. Record the Blackpoint Compensation, if any.\n */\n if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse)\n {\n char\n *name;\n\n const StringInfo\n *profile;\n\n ResetImageProfileIterator(image);\n for (name=GetNextImageProfile(image); name != (const char *) NULL; )\n {\n profile=GetImageProfile(image,name);\n\n if (profile != (StringInfo *) NULL)\n {\n if ((LocaleCompare(name,\"ICC\") == 0) ||\n (LocaleCompare(name,\"ICM\") == 0))\n\n {\n int\n icheck,\n got_crc=0;\n\n\n png_uint_32\n length,\n profile_crc=0;\n\n unsigned char\n *data;\n\n length=(png_uint_32) GetStringInfoLength(profile);\n\n for (icheck=0; sRGB_info[icheck].len > 0; icheck++)\n {\n if (length == sRGB_info[icheck].len)\n {\n if (got_crc == 0)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Got a %lu-byte ICC profile (potentially sRGB)\",\n (unsigned long) length);\n\n data=GetStringInfoDatum(profile);\n profile_crc=crc32(0,data,length);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" with crc=%8x\",(unsigned int) profile_crc);\n got_crc++;\n }\n\n if (profile_crc == sRGB_info[icheck].crc)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" It is sRGB with rendering intent = %s\",\n Magick_RenderingIntentString_from_PNG_RenderingIntent(\n sRGB_info[icheck].intent));\n if (image->rendering_intent==UndefinedIntent)\n {\n image->rendering_intent=\n Magick_RenderingIntent_from_PNG_RenderingIntent(\n sRGB_info[icheck].intent);\n }\n ping_exclude_iCCP = MagickTrue;\n ping_exclude_zCCP = MagickTrue;\n ping_have_sRGB = MagickTrue;\n break;\n }\n }\n }\n if (sRGB_info[icheck].len == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Got %lu-byte ICC profile not recognized as sRGB\",\n (unsigned long) length);\n }\n }\n name=GetNextImageProfile(image);\n }\n }\n\n number_opaque = 0;\n number_semitransparent = 0;\n number_transparent = 0;\n\n if (logging != MagickFalse)\n {\n if (image->storage_class == UndefinedClass)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->storage_class=UndefinedClass\");\n if (image->storage_class == DirectClass)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->storage_class=DirectClass\");\n if (image->storage_class == PseudoClass)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->storage_class=PseudoClass\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ?\n \" image->taint=MagickTrue\":\n \" image->taint=MagickFalse\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->gamma=%g\", image->gamma);\n }\n\n if (image->storage_class == PseudoClass &&\n (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 ||\n mng_info->write_png48 || mng_info->write_png64 ||\n (mng_info->write_png_colortype != 1 &&\n mng_info->write_png_colortype != 5)))\n {\n (void) SyncImage(image,exception);\n image->storage_class = DirectClass;\n }\n\n if (ping_preserve_colormap == MagickFalse)\n {\n if (image->storage_class != PseudoClass && image->colormap != NULL)\n {\n /* Free the bogus colormap; it can cause trouble later */\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Freeing bogus colormap\");\n (void) RelinquishMagickMemory(image->colormap);\n image->colormap=NULL;\n }\n }\n\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n (void) TransformImageColorspace(image,sRGBColorspace,exception);\n\n /*\n Sometimes we get PseudoClass images whose RGB values don't match\n the colors in the colormap. This code syncs the RGB values.\n */\n if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass)\n (void) SyncImage(image,exception);\n\n#if (MAGICKCORE_QUANTUM_DEPTH == 8)\n if (image->depth > 8)\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reducing PNG bit depth to 8 since this is a Q8 build.\");\n\n image->depth=8;\n }\n#endif\n\n /* Respect the -depth option */\n if (image->depth < 4)\n {\n register Quantum\n *r;\n\n if (image->depth > 2)\n {\n /* Scale to 4-bit */\n LBR04PacketRGBO(image->background_color);\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n r=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (r == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n LBR04PixelRGBA(r);\n r+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n\n if (image->storage_class == PseudoClass && image->colormap != NULL)\n {\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n LBR04PacketRGBO(image->colormap[i]);\n }\n }\n }\n else if (image->depth > 1)\n {\n /* Scale to 2-bit */\n LBR02PacketRGBO(image->background_color);\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n r=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (r == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n LBR02PixelRGBA(r);\n r+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n\n if (image->storage_class == PseudoClass && image->colormap != NULL)\n {\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n LBR02PacketRGBO(image->colormap[i]);\n }\n }\n }\n else\n {\n /* Scale to 1-bit */\n LBR01PacketRGBO(image->background_color);\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n r=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (r == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n LBR01PixelRGBA(r);\n r+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n\n if (image->storage_class == PseudoClass && image->colormap != NULL)\n {\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n LBR01PacketRGBO(image->colormap[i]);\n }\n }\n }\n }\n\n /* To do: set to next higher multiple of 8 */\n if (image->depth < 8)\n image->depth=8;\n\n#if (MAGICKCORE_QUANTUM_DEPTH > 16)\n /* PNG does not handle depths greater than 16 so reduce it even\n * if lossy\n */\n if (image->depth > 8)\n image->depth=16;\n#endif\n\n#if (MAGICKCORE_QUANTUM_DEPTH > 8)\n if (image->depth > 8)\n {\n /* To do: fill low byte properly */\n image->depth=16;\n }\n\n if (image->depth == 16 && mng_info->write_png_depth != 16)\n if (mng_info->write_png8 ||\n LosslessReduceDepthOK(image,exception) != MagickFalse)\n image->depth = 8;\n#endif\n\n image_colors = (int) image->colors;\n number_opaque = (int) image->colors;\n number_transparent = 0;\n number_semitransparent = 0;\n\n if (mng_info->write_png_colortype &&\n (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 &&\n mng_info->write_png_colortype < 4 &&\n image->alpha_trait == UndefinedPixelTrait)))\n {\n /* Avoid the expensive BUILD_PALETTE operation if we're sure that we\n * are not going to need the result.\n */\n if (mng_info->write_png_colortype == 1 ||\n mng_info->write_png_colortype == 5)\n ping_have_color=MagickFalse;\n\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n number_transparent = 2;\n number_semitransparent = 1;\n }\n }\n\n if (mng_info->write_png_colortype < 7)\n {\n /* BUILD_PALETTE\n *\n * Normally we run this just once, but in the case of writing PNG8\n * we reduce the transparency to binary and run again, then if there\n * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1\n * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA\n * palette. Then (To do) we take care of a final reduction that is only\n * needed if there are still 256 colors present and one of them has both\n * transparent and opaque instances.\n */\n\n tried_332 = MagickFalse;\n tried_333 = MagickFalse;\n tried_444 = MagickFalse;\n\n for (j=0; j<6; j++)\n {\n /*\n * Sometimes we get DirectClass images that have 256 colors or fewer.\n * This code will build a colormap.\n *\n * Also, sometimes we get PseudoClass images with an out-of-date\n * colormap. This code will replace the colormap with a new one.\n * Sometimes we get PseudoClass images that have more than 256 colors.\n * This code will delete the colormap and change the image to\n * DirectClass.\n *\n * If image->alpha_trait is MagickFalse, we ignore the alpha channel\n * even though it sometimes contains left-over non-opaque values.\n *\n * Also we gather some information (number of opaque, transparent,\n * and semitransparent pixels, and whether the image has any non-gray\n * pixels or only black-and-white pixels) that we might need later.\n *\n * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6)\n * we need to check for bogus non-opaque values, at least.\n */\n\n int\n n;\n\n PixelInfo\n opaque[260],\n semitransparent[260],\n transparent[260];\n\n register const Quantum\n *s;\n\n register Quantum\n *q,\n *r;\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Enter BUILD_PALETTE:\");\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->columns=%.20g\",(double) image->columns);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->rows=%.20g\",(double) image->rows);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->alpha_trait=%.20g\",(double) image->alpha_trait);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->depth=%.20g\",(double) image->depth);\n\n if (image->storage_class == PseudoClass && image->colormap != NULL)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Original colormap:\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" i (red,green,blue,alpha)\");\n\n for (i=0; i < 256; i++)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" %d (%d,%d,%d,%d)\",\n (int) i,\n (int) image->colormap[i].red,\n (int) image->colormap[i].green,\n (int) image->colormap[i].blue,\n (int) image->colormap[i].alpha);\n }\n\n for (i=image->colors - 10; i < (ssize_t) image->colors; i++)\n {\n if (i > 255)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" %d (%d,%d,%d,%d)\",\n (int) i,\n (int) image->colormap[i].red,\n (int) image->colormap[i].green,\n (int) image->colormap[i].blue,\n (int) image->colormap[i].alpha);\n }\n }\n }\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->colors=%d\",(int) image->colors);\n\n if (image->colors == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" (zero means unknown)\");\n\n if (ping_preserve_colormap == MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Regenerate the colormap\");\n }\n\n image_colors=0;\n number_opaque = 0;\n number_semitransparent = 0;\n number_transparent = 0;\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (q == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (image->alpha_trait == UndefinedPixelTrait ||\n GetPixelAlpha(image,q) == OpaqueAlpha)\n {\n if (number_opaque < 259)\n {\n if (number_opaque == 0)\n {\n GetPixelInfoPixel(image, q, opaque);\n opaque[0].alpha=OpaqueAlpha;\n number_opaque=1;\n }\n\n for (i=0; i< (ssize_t) number_opaque; i++)\n {\n if (Magick_png_color_equal(image,q,opaque+i))\n break;\n }\n\n if (i == (ssize_t) number_opaque && number_opaque < 259)\n {\n number_opaque++;\n GetPixelInfoPixel(image, q, opaque+i);\n opaque[i].alpha=OpaqueAlpha;\n }\n }\n }\n else if (GetPixelAlpha(image,q) == TransparentAlpha)\n {\n if (number_transparent < 259)\n {\n if (number_transparent == 0)\n {\n GetPixelInfoPixel(image, q, transparent);\n ping_trans_color.red=(unsigned short)\n GetPixelRed(image,q);\n ping_trans_color.green=(unsigned short)\n GetPixelGreen(image,q);\n ping_trans_color.blue=(unsigned short)\n GetPixelBlue(image,q);\n ping_trans_color.gray=(unsigned short)\n GetPixelGray(image,q);\n number_transparent = 1;\n }\n\n for (i=0; i< (ssize_t) number_transparent; i++)\n {\n if (Magick_png_color_equal(image,q,transparent+i))\n break;\n }\n\n if (i == (ssize_t) number_transparent &&\n number_transparent < 259)\n {\n number_transparent++;\n GetPixelInfoPixel(image,q,transparent+i);\n }\n }\n }\n else\n {\n if (number_semitransparent < 259)\n {\n if (number_semitransparent == 0)\n {\n GetPixelInfoPixel(image,q,semitransparent);\n number_semitransparent = 1;\n }\n\n for (i=0; i< (ssize_t) number_semitransparent; i++)\n {\n if (Magick_png_color_equal(image,q,semitransparent+i)\n && GetPixelAlpha(image,q) ==\n semitransparent[i].alpha)\n break;\n }\n\n if (i == (ssize_t) number_semitransparent &&\n number_semitransparent < 259)\n {\n number_semitransparent++;\n GetPixelInfoPixel(image, q, semitransparent+i);\n }\n }\n }\n q+=GetPixelChannels(image);\n }\n }\n\n if (mng_info->write_png8 == MagickFalse &&\n ping_exclude_bKGD == MagickFalse)\n {\n /* Add the background color to the palette, if it\n * isn't already there.\n */\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Check colormap for background (%d,%d,%d)\",\n (int) image->background_color.red,\n (int) image->background_color.green,\n (int) image->background_color.blue);\n }\n for (i=0; ibackground_color.red &&\n opaque[i].green == image->background_color.green &&\n opaque[i].blue == image->background_color.blue)\n break;\n }\n if (number_opaque < 259 && i == number_opaque)\n {\n opaque[i] = image->background_color;\n ping_background.index = i;\n number_opaque++;\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" background_color index is %d\",(int) i);\n }\n\n }\n else if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" No room in the colormap to add background color\");\n }\n\n image_colors=number_opaque+number_transparent+number_semitransparent;\n\n if (logging != MagickFalse)\n {\n if (image_colors > 256)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image has more than 256 colors\");\n\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image has %d colors\",image_colors);\n }\n\n if (ping_preserve_colormap != MagickFalse)\n break;\n\n if (mng_info->write_png_colortype != 7) /* We won't need this info */\n {\n ping_have_color=MagickFalse;\n ping_have_non_bw=MagickFalse;\n\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"incompatible colorspace\");\n ping_have_color=MagickTrue;\n ping_have_non_bw=MagickTrue;\n }\n\n if(image_colors > 256)\n {\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (q == (Quantum *) NULL)\n break;\n\n s=q;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (GetPixelRed(image,s) != GetPixelGreen(image,s) ||\n GetPixelRed(image,s) != GetPixelBlue(image,s))\n {\n ping_have_color=MagickTrue;\n ping_have_non_bw=MagickTrue;\n break;\n }\n s+=GetPixelChannels(image);\n }\n\n if (ping_have_color != MagickFalse)\n break;\n\n /* Worst case is black-and-white; we are looking at every\n * pixel twice.\n */\n\n if (ping_have_non_bw == MagickFalse)\n {\n s=q;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (GetPixelRed(image,s) != 0 &&\n GetPixelRed(image,s) != QuantumRange)\n {\n ping_have_non_bw=MagickTrue;\n break;\n }\n s+=GetPixelChannels(image);\n }\n }\n }\n }\n }\n\n if (image_colors < 257)\n {\n PixelInfo\n colormap[260];\n\n /*\n * Initialize image colormap.\n */\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Sort the new colormap\");\n\n /* Sort palette, transparent first */;\n\n n = 0;\n\n for (i=0; iping_exclude_tRNS == MagickFalse ||\n (number_transparent == 0 && number_semitransparent == 0)) &&\n (((mng_info->write_png_colortype-1) ==\n PNG_COLOR_TYPE_PALETTE) ||\n (mng_info->write_png_colortype == 0)))\n {\n if (logging != MagickFalse)\n {\n if (n != (ssize_t) image_colors)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image_colors (%d) and n (%d) don't match\",\n image_colors, n);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" AcquireImageColormap\");\n }\n\n image->colors = image_colors;\n\n if (AcquireImageColormap(image,image_colors,exception) ==\n MagickFalse)\n ThrowWriterException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n\n for (i=0; i< (ssize_t) image_colors; i++)\n image->colormap[i] = colormap[i];\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->colors=%d (%d)\",\n (int) image->colors, image_colors);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Update the pixel indexes\");\n }\n\n /* Sync the pixel indices with the new colormap */\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (q == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n for (i=0; i< (ssize_t) image_colors; i++)\n {\n if ((image->alpha_trait == UndefinedPixelTrait ||\n image->colormap[i].alpha == GetPixelAlpha(image,q)) &&\n image->colormap[i].red == GetPixelRed(image,q) &&\n image->colormap[i].green == GetPixelGreen(image,q) &&\n image->colormap[i].blue == GetPixelBlue(image,q))\n {\n SetPixelIndex(image,i,q);\n break;\n }\n }\n q+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n }\n }\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->colors=%d\", (int) image->colors);\n\n if (image->colormap != NULL)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" i (red,green,blue,alpha)\");\n\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n if (i < 300 || i >= (ssize_t) image->colors - 10)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" %d (%d,%d,%d,%d)\",\n (int) i,\n (int) image->colormap[i].red,\n (int) image->colormap[i].green,\n (int) image->colormap[i].blue,\n (int) image->colormap[i].alpha);\n }\n }\n }\n\n if (number_transparent < 257)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" number_transparent = %d\",\n number_transparent);\n else\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" number_transparent > 256\");\n\n if (number_opaque < 257)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" number_opaque = %d\",\n number_opaque);\n\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" number_opaque > 256\");\n\n if (number_semitransparent < 257)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" number_semitransparent = %d\",\n number_semitransparent);\n\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" number_semitransparent > 256\");\n\n if (ping_have_non_bw == MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" All pixels and the background are black or white\");\n\n else if (ping_have_color == MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" All pixels and the background are gray\");\n\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" At least one pixel or the background is non-gray\");\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Exit BUILD_PALETTE:\");\n }\n\n if (mng_info->write_png8 == MagickFalse)\n break;\n\n /* Make any reductions necessary for the PNG8 format */\n if (image_colors <= 256 &&\n image_colors != 0 && image->colormap != NULL &&\n number_semitransparent == 0 &&\n number_transparent <= 1)\n break;\n\n /* PNG8 can't have semitransparent colors so we threshold the\n * opacity to 0 or OpaqueOpacity, and PNG8 can only have one\n * transparent color so if more than one is transparent we merge\n * them into image->background_color.\n */\n if (number_semitransparent != 0 || number_transparent > 1)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Thresholding the alpha channel to binary\");\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n r=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (r == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (GetPixelAlpha(image,r) < OpaqueAlpha/2)\n {\n SetPixelViaPixelInfo(image,&image->background_color,r);\n SetPixelAlpha(image,TransparentAlpha,r);\n }\n else\n SetPixelAlpha(image,OpaqueAlpha,r);\n r+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n\n if (image_colors != 0 && image_colors <= 256 &&\n image->colormap != NULL)\n for (i=0; icolormap[i].alpha =\n (image->colormap[i].alpha > TransparentAlpha/2 ?\n TransparentAlpha : OpaqueAlpha);\n }\n continue;\n }\n\n /* PNG8 can't have more than 256 colors so we quantize the pixels and\n * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the\n * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256\n * colors or less.\n */\n if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256))\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the background color to 4-4-4\");\n\n tried_444 = MagickTrue;\n\n LBR04PacketRGB(image->background_color);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the pixel colors to 4-4-4\");\n\n if (image->colormap == NULL)\n {\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n r=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (r == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (GetPixelAlpha(image,r) == OpaqueAlpha)\n LBR04PixelRGB(r);\n r+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n }\n\n else /* Should not reach this; colormap already exists and\n must be <= 256 */\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the colormap to 4-4-4\");\n\n for (i=0; icolormap[i]);\n }\n }\n continue;\n }\n\n if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256))\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the background color to 3-3-3\");\n\n tried_333 = MagickTrue;\n\n LBR03PacketRGB(image->background_color);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the pixel colors to 3-3-3-1\");\n\n if (image->colormap == NULL)\n {\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n r=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (r == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (GetPixelAlpha(image,r) == OpaqueAlpha)\n LBR03RGB(r);\n r+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n }\n\n else /* Should not reach this; colormap already exists and\n must be <= 256 */\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the colormap to 3-3-3-1\");\n for (i=0; icolormap[i]);\n }\n }\n continue;\n }\n\n if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256))\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the background color to 3-3-2\");\n\n tried_332 = MagickTrue;\n\n /* Red and green were already done so we only quantize the blue\n * channel\n */\n\n LBR02PacketBlue(image->background_color);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the pixel colors to 3-3-2-1\");\n\n if (image->colormap == NULL)\n {\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n r=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (r == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (GetPixelAlpha(image,r) == OpaqueAlpha)\n LBR02PixelBlue(r);\n r+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n }\n\n else /* Should not reach this; colormap already exists and\n must be <= 256 */\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Quantizing the colormap to 3-3-2-1\");\n for (i=0; icolormap[i]);\n }\n }\n continue;\n }\n\n if (image_colors == 0 || image_colors > 256)\n {\n /* Take care of special case with 256 opaque colors + 1 transparent\n * color. We don't need to quantize to 2-3-2-1; we only need to\n * eliminate one color, so we'll merge the two darkest red\n * colors (0x49, 0, 0) -> (0x24, 0, 0).\n */\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Merging two dark red background colors to 3-3-2-1\");\n\n if (ScaleQuantumToChar(image->background_color.red) == 0x49 &&\n ScaleQuantumToChar(image->background_color.green) == 0x00 &&\n ScaleQuantumToChar(image->background_color.blue) == 0x00)\n {\n image->background_color.red=ScaleCharToQuantum(0x24);\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Merging two dark red pixel colors to 3-3-2-1\");\n\n if (image->colormap == NULL)\n {\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n r=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (r == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (ScaleQuantumToChar(GetPixelRed(image,r)) == 0x49 &&\n ScaleQuantumToChar(GetPixelGreen(image,r)) == 0x00 &&\n ScaleQuantumToChar(GetPixelBlue(image,r)) == 0x00 &&\n GetPixelAlpha(image,r) == OpaqueAlpha)\n {\n SetPixelRed(image,ScaleCharToQuantum(0x24),r);\n }\n r+=GetPixelChannels(image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n\n }\n }\n\n else\n {\n for (i=0; icolormap[i].red) == 0x49 &&\n ScaleQuantumToChar(image->colormap[i].green) == 0x00 &&\n ScaleQuantumToChar(image->colormap[i].blue) == 0x00)\n {\n image->colormap[i].red=ScaleCharToQuantum(0x24);\n }\n }\n }\n }\n }\n }\n /* END OF BUILD_PALETTE */\n\n /* If we are excluding the tRNS chunk and there is transparency,\n * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6)\n * PNG.\n */\n if (mng_info->ping_exclude_tRNS != MagickFalse &&\n (number_transparent != 0 || number_semitransparent != 0))\n {\n unsigned int colortype=mng_info->write_png_colortype;\n\n if (ping_have_color == MagickFalse)\n mng_info->write_png_colortype = 5;\n\n else\n mng_info->write_png_colortype = 7;\n\n if (colortype != 0 &&\n mng_info->write_png_colortype != colortype)\n ping_need_colortype_warning=MagickTrue;\n\n }\n\n /* See if cheap transparency is possible. It is only possible\n * when there is a single transparent color, no semitransparent\n * color, and no opaque color that has the same RGB components\n * as the transparent color. We only need this information if\n * we are writing a PNG with colortype 0 or 2, and we have not\n * excluded the tRNS chunk.\n */\n if (number_transparent == 1 &&\n mng_info->write_png_colortype < 4)\n {\n ping_have_cheap_transparency = MagickTrue;\n\n if (number_semitransparent != 0)\n ping_have_cheap_transparency = MagickFalse;\n\n else if (image_colors == 0 || image_colors > 256 ||\n image->colormap == NULL)\n {\n register const Quantum\n *q;\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=GetVirtualPixels(image,0,y,image->columns,1, exception);\n\n if (q == (Quantum *) NULL)\n break;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (GetPixelAlpha(image,q) != TransparentAlpha &&\n (unsigned short) GetPixelRed(image,q) ==\n ping_trans_color.red &&\n (unsigned short) GetPixelGreen(image,q) ==\n ping_trans_color.green &&\n (unsigned short) GetPixelBlue(image,q) ==\n ping_trans_color.blue)\n {\n ping_have_cheap_transparency = MagickFalse;\n break;\n }\n\n q+=GetPixelChannels(image);\n }\n\n if (ping_have_cheap_transparency == MagickFalse)\n break;\n }\n }\n else\n {\n /* Assuming that image->colormap[0] is the one transparent color\n * and that all others are opaque.\n */\n if (image_colors > 1)\n for (i=1; icolormap[i].red == image->colormap[0].red &&\n image->colormap[i].green == image->colormap[0].green &&\n image->colormap[i].blue == image->colormap[0].blue)\n {\n ping_have_cheap_transparency = MagickFalse;\n break;\n }\n }\n\n if (logging != MagickFalse)\n {\n if (ping_have_cheap_transparency == MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Cheap transparency is not possible.\");\n\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Cheap transparency is possible.\");\n }\n }\n else\n ping_have_cheap_transparency = MagickFalse;\n\n image_depth=image->depth;\n\n quantum_info = (QuantumInfo *) NULL;\n number_colors=0;\n image_colors=(int) image->colors;\n image_matte=image->alpha_trait !=\n UndefinedPixelTrait ? MagickTrue : MagickFalse;\n\n if (mng_info->write_png_colortype < 5)\n mng_info->IsPalette=image->storage_class == PseudoClass &&\n image_colors <= 256 && image->colormap != NULL;\n else\n mng_info->IsPalette = MagickFalse;\n\n if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) &&\n (image->colors == 0 || image->colormap == NULL))\n {\n image_info=DestroyImageInfo(image_info);\n image=DestroyImage(image);\n (void) ThrowMagickException(exception,GetMagickModule(),CoderError,\n \"Cannot write PNG8 or color-type 3; colormap is NULL\",\n \"`%s'\",IMimage->filename);\n return(MagickFalse);\n }\n\n /*\n Allocate the PNG structures\n */\n#ifdef PNG_USER_MEM_SUPPORTED\n error_info.image=image;\n error_info.exception=exception;\n ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info,\n MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL,\n (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free);\n\n#else\n ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info,\n MagickPNGErrorHandler,MagickPNGWarningHandler);\n\n#endif\n if (ping == (png_struct *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n ping_info=png_create_info_struct(ping);\n\n if (ping_info == (png_info *) NULL)\n {\n png_destroy_write_struct(&ping,(png_info **) NULL);\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n\n png_set_write_fn(ping,image,png_put_data,png_flush_data);\n pixel_info=(MemoryInfo *) NULL;\n\n if (setjmp(png_jmpbuf(ping)))\n {\n /*\n PNG write failed.\n */\n#ifdef PNG_DEBUG\n if (image_info->verbose)\n (void) printf(\"PNG write has failed.\\n\");\n#endif\n png_destroy_write_struct(&ping,&ping_info);\n#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE\n UnlockSemaphoreInfo(ping_semaphore);\n#endif\n\n if (pixel_info != (MemoryInfo *) NULL)\n pixel_info=RelinquishVirtualMemory(pixel_info);\n\n if (quantum_info != (QuantumInfo *) NULL)\n quantum_info=DestroyQuantumInfo(quantum_info);\n\n if (ping_have_blob != MagickFalse)\n (void) CloseBlob(image);\n image_info=DestroyImageInfo(image_info);\n image=DestroyImage(image);\n return(MagickFalse);\n }\n\n /* { For navigation to end of SETJMP-protected block. Within this\n * block, use png_error() instead of Throwing an Exception, to ensure\n * that libpng is able to clean up, and that the semaphore is unlocked.\n */\n\n#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE\n LockSemaphoreInfo(ping_semaphore);\n#endif\n\n#ifdef PNG_BENIGN_ERRORS_SUPPORTED\n /* Allow benign errors */\n png_set_benign_errors(ping, 1);\n#endif\n\n#ifdef PNG_SET_USER_LIMITS_SUPPORTED\n /* Reject images with too many rows or columns */\n png_set_user_limits(ping,\n (png_uint_32) MagickMin(0x7fffffffL,\n GetMagickResourceLimit(WidthResource)),\n (png_uint_32) MagickMin(0x7fffffffL,\n GetMagickResourceLimit(HeightResource)));\n#endif /* PNG_SET_USER_LIMITS_SUPPORTED */\n\n /*\n Prepare PNG for writing.\n */\n\n#if defined(PNG_MNG_FEATURES_SUPPORTED)\n if (mng_info->write_mng)\n {\n (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES);\n# ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED\n /* Disable new libpng-1.5.10 feature when writing a MNG because\n * zero-length PLTE is OK\n */\n png_set_check_for_invalid_index (ping, 0);\n# endif\n }\n\n#else\n# ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED\n if (mng_info->write_mng)\n png_permit_empty_plte(ping,MagickTrue);\n\n# endif\n#endif\n\n x=0;\n\n ping_width=(png_uint_32) image->columns;\n ping_height=(png_uint_32) image->rows;\n\n if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32)\n image_depth=8;\n\n if (mng_info->write_png48 || mng_info->write_png64)\n image_depth=16;\n\n if (mng_info->write_png_depth != 0)\n image_depth=mng_info->write_png_depth;\n\n /* Adjust requested depth to next higher valid depth if necessary */\n if (image_depth > 8)\n image_depth=16;\n\n if ((image_depth > 4) && (image_depth < 8))\n image_depth=8;\n\n if (image_depth == 3)\n image_depth=4;\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" width=%.20g\",(double) ping_width);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" height=%.20g\",(double) ping_height);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image_matte=%.20g\",(double) image->alpha_trait);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->depth=%.20g\",(double) image->depth);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Tentative ping_bit_depth=%.20g\",(double) image_depth);\n }\n\n save_image_depth=image_depth;\n ping_bit_depth=(png_byte) save_image_depth;\n\n\n#if defined(PNG_pHYs_SUPPORTED)\n if (ping_exclude_pHYs == MagickFalse)\n {\n if ((image->resolution.x != 0) && (image->resolution.y != 0) &&\n (!mng_info->write_mng || !mng_info->equal_physs))\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up pHYs chunk\");\n\n if (image->units == PixelsPerInchResolution)\n {\n ping_pHYs_unit_type=PNG_RESOLUTION_METER;\n ping_pHYs_x_resolution=\n (png_uint_32) ((100.0*image->resolution.x+0.5)/2.54);\n ping_pHYs_y_resolution=\n (png_uint_32) ((100.0*image->resolution.y+0.5)/2.54);\n }\n\n else if (image->units == PixelsPerCentimeterResolution)\n {\n ping_pHYs_unit_type=PNG_RESOLUTION_METER;\n ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5);\n ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5);\n }\n\n else\n {\n ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN;\n ping_pHYs_x_resolution=(png_uint_32) image->resolution.x;\n ping_pHYs_y_resolution=(png_uint_32) image->resolution.y;\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.\",\n (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution,\n (int) ping_pHYs_unit_type);\n ping_have_pHYs = MagickTrue;\n }\n }\n#endif\n\n if (ping_exclude_bKGD == MagickFalse)\n {\n if ((!mng_info->adjoin || !mng_info->equal_backgrounds))\n {\n unsigned int\n mask;\n\n mask=0xffff;\n if (ping_bit_depth == 8)\n mask=0x00ff;\n\n if (ping_bit_depth == 4)\n mask=0x000f;\n\n if (ping_bit_depth == 2)\n mask=0x0003;\n\n if (ping_bit_depth == 1)\n mask=0x0001;\n\n ping_background.red=(png_uint_16)\n (ScaleQuantumToShort(image->background_color.red) & mask);\n\n ping_background.green=(png_uint_16)\n (ScaleQuantumToShort(image->background_color.green) & mask);\n\n ping_background.blue=(png_uint_16)\n (ScaleQuantumToShort(image->background_color.blue) & mask);\n\n ping_background.gray=(png_uint_16) ping_background.green;\n }\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up bKGD chunk (1)\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" background_color index is %d\",\n (int) ping_background.index);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" ping_bit_depth=%d\",ping_bit_depth);\n }\n\n ping_have_bKGD = MagickTrue;\n }\n\n /*\n Select the color type.\n */\n matte=image_matte;\n old_bit_depth=0;\n\n if (mng_info->IsPalette && mng_info->write_png8)\n {\n /* To do: make this a function cause it's used twice, except\n for reducing the sample depth from 8. */\n\n number_colors=image_colors;\n\n ping_have_tRNS=MagickFalse;\n\n /*\n Set image palette.\n */\n ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up PLTE chunk with %d colors (%d)\",\n number_colors, image_colors);\n\n for (i=0; i < (ssize_t) number_colors; i++)\n {\n palette[i].red=ScaleQuantumToChar(image->colormap[i].red);\n palette[i].green=ScaleQuantumToChar(image->colormap[i].green);\n palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue);\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n#if MAGICKCORE_QUANTUM_DEPTH == 8\n \" %3ld (%3d,%3d,%3d)\",\n#else\n \" %5ld (%5d,%5d,%5d)\",\n#endif\n (long) i,palette[i].red,palette[i].green,palette[i].blue);\n\n }\n\n ping_have_PLTE=MagickTrue;\n image_depth=ping_bit_depth;\n ping_num_trans=0;\n\n if (matte != MagickFalse)\n {\n /*\n Identify which colormap entry is transparent.\n */\n assert(number_colors <= 256);\n assert(image->colormap != NULL);\n\n for (i=0; i < (ssize_t) number_transparent; i++)\n ping_trans_alpha[i]=0;\n\n\n ping_num_trans=(unsigned short) (number_transparent +\n number_semitransparent);\n\n if (ping_num_trans == 0)\n ping_have_tRNS=MagickFalse;\n\n else\n ping_have_tRNS=MagickTrue;\n }\n\n if (ping_exclude_bKGD == MagickFalse)\n {\n /*\n * Identify which colormap entry is the background color.\n */\n\n for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++)\n if (IsPNGColorEqual(ping_background,image->colormap[i]))\n break;\n\n ping_background.index=(png_byte) i;\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" background_color index is %d\",\n (int) ping_background.index);\n }\n }\n } /* end of write_png8 */\n\n else if (mng_info->write_png_colortype == 1)\n {\n image_matte=MagickFalse;\n ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY;\n }\n\n else if (mng_info->write_png24 || mng_info->write_png48 ||\n mng_info->write_png_colortype == 3)\n {\n image_matte=MagickFalse;\n ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;\n }\n\n else if (mng_info->write_png32 || mng_info->write_png64 ||\n mng_info->write_png_colortype == 7)\n {\n image_matte=MagickTrue;\n ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA;\n }\n\n else /* mng_info->write_pngNN not specified */\n {\n image_depth=ping_bit_depth;\n\n if (mng_info->write_png_colortype != 0)\n {\n ping_color_type=(png_byte) mng_info->write_png_colortype-1;\n\n if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||\n ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)\n image_matte=MagickTrue;\n\n else\n image_matte=MagickFalse;\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" PNG colortype %d was specified:\",(int) ping_color_type);\n }\n\n else /* write_png_colortype not specified */\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Selecting PNG colortype:\");\n\n ping_color_type=(png_byte) ((matte != MagickFalse)?\n PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB);\n\n if (image_info->type == TrueColorType)\n {\n ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;\n image_matte=MagickFalse;\n }\n\n if (image_info->type == TrueColorAlphaType)\n {\n ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA;\n image_matte=MagickTrue;\n }\n\n if (image_info->type == PaletteType ||\n image_info->type == PaletteAlphaType)\n ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;\n\n if (mng_info->write_png_colortype == 0 &&\n image_info->type == UndefinedType)\n {\n if (ping_have_color == MagickFalse)\n {\n if (image_matte == MagickFalse)\n {\n ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY;\n image_matte=MagickFalse;\n }\n\n else\n {\n ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA;\n image_matte=MagickTrue;\n }\n }\n else\n {\n if (image_matte == MagickFalse)\n {\n ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;\n image_matte=MagickFalse;\n }\n\n else\n {\n ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA;\n image_matte=MagickTrue;\n }\n }\n }\n\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Selected PNG colortype=%d\",ping_color_type);\n\n if (ping_bit_depth < 8)\n {\n if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||\n ping_color_type == PNG_COLOR_TYPE_RGB ||\n ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)\n ping_bit_depth=8;\n }\n\n old_bit_depth=ping_bit_depth;\n\n if (ping_color_type == PNG_COLOR_TYPE_GRAY)\n {\n if (image->alpha_trait == UndefinedPixelTrait &&\n ping_have_non_bw == MagickFalse)\n ping_bit_depth=1;\n }\n\n if (ping_color_type == PNG_COLOR_TYPE_PALETTE)\n {\n size_t one = 1;\n ping_bit_depth=1;\n\n if (image->colors == 0)\n {\n /* DO SOMETHING */\n png_error(ping,\"image has 0 colors\");\n }\n\n while ((int) (one << ping_bit_depth) < (ssize_t) image_colors)\n ping_bit_depth <<= 1;\n }\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Number of colors: %.20g\",(double) image_colors);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Tentative PNG bit depth: %d\",ping_bit_depth);\n }\n\n if (ping_bit_depth < (int) mng_info->write_png_depth)\n ping_bit_depth = mng_info->write_png_depth;\n }\n\n image_depth=ping_bit_depth;\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Tentative PNG color type: %s (%.20g)\",\n PngColorTypeToString(ping_color_type),\n (double) ping_color_type);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image_info->type: %.20g\",(double) image_info->type);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image_depth: %.20g\",(double) image_depth);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n\n \" image->depth: %.20g\",(double) image->depth);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" ping_bit_depth: %.20g\",(double) ping_bit_depth);\n }\n\n if (matte != MagickFalse)\n {\n if (mng_info->IsPalette)\n {\n if (mng_info->write_png_colortype == 0)\n {\n ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA;\n\n if (ping_have_color != MagickFalse)\n ping_color_type=PNG_COLOR_TYPE_RGBA;\n }\n\n /*\n * Determine if there is any transparent color.\n */\n if (number_transparent + number_semitransparent == 0)\n {\n /*\n No transparent pixels are present. Change 4 or 6 to 0 or 2.\n */\n\n image_matte=MagickFalse;\n\n if (mng_info->write_png_colortype == 0)\n ping_color_type&=0x03;\n }\n\n else\n {\n unsigned int\n mask;\n\n mask=0xffff;\n\n if (ping_bit_depth == 8)\n mask=0x00ff;\n\n if (ping_bit_depth == 4)\n mask=0x000f;\n\n if (ping_bit_depth == 2)\n mask=0x0003;\n\n if (ping_bit_depth == 1)\n mask=0x0001;\n\n ping_trans_color.red=(png_uint_16)\n (ScaleQuantumToShort(image->colormap[0].red) & mask);\n\n ping_trans_color.green=(png_uint_16)\n (ScaleQuantumToShort(image->colormap[0].green) & mask);\n\n ping_trans_color.blue=(png_uint_16)\n (ScaleQuantumToShort(image->colormap[0].blue) & mask);\n\n ping_trans_color.gray=(png_uint_16)\n (ScaleQuantumToShort(GetPixelInfoIntensity(image,\n image->colormap)) & mask);\n\n ping_trans_color.index=(png_byte) 0;\n\n ping_have_tRNS=MagickTrue;\n }\n\n if (ping_have_tRNS != MagickFalse)\n {\n /*\n * Determine if there is one and only one transparent color\n * and if so if it is fully transparent.\n */\n if (ping_have_cheap_transparency == MagickFalse)\n ping_have_tRNS=MagickFalse;\n }\n\n if (ping_have_tRNS != MagickFalse)\n {\n if (mng_info->write_png_colortype == 0)\n ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */\n\n if (image_depth == 8)\n {\n ping_trans_color.red&=0xff;\n ping_trans_color.green&=0xff;\n ping_trans_color.blue&=0xff;\n ping_trans_color.gray&=0xff;\n }\n }\n }\n else\n {\n if (image_depth == 8)\n {\n ping_trans_color.red&=0xff;\n ping_trans_color.green&=0xff;\n ping_trans_color.blue&=0xff;\n ping_trans_color.gray&=0xff;\n }\n }\n }\n\n matte=image_matte;\n\n if (ping_have_tRNS != MagickFalse)\n image_matte=MagickFalse;\n\n if ((mng_info->IsPalette) &&\n mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE &&\n ping_have_color == MagickFalse &&\n (image_matte == MagickFalse || image_depth >= 8))\n {\n size_t one=1;\n\n if (image_matte != MagickFalse)\n ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA;\n\n else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA)\n {\n ping_color_type=PNG_COLOR_TYPE_GRAY;\n\n if (save_image_depth == 16 && image_depth == 8)\n {\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Scaling ping_trans_color (0)\");\n }\n ping_trans_color.gray*=0x0101;\n }\n }\n\n if (image_depth > MAGICKCORE_QUANTUM_DEPTH)\n image_depth=MAGICKCORE_QUANTUM_DEPTH;\n\n if ((image_colors == 0) ||\n ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize))\n image_colors=(int) (one << image_depth);\n\n if (image_depth > 8)\n ping_bit_depth=16;\n\n else\n {\n ping_bit_depth=8;\n if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)\n {\n if(!mng_info->write_png_depth)\n {\n ping_bit_depth=1;\n\n while ((int) (one << ping_bit_depth)\n < (ssize_t) image_colors)\n ping_bit_depth <<= 1;\n }\n }\n\n else if (ping_color_type ==\n PNG_COLOR_TYPE_GRAY && image_colors < 17 &&\n mng_info->IsPalette)\n {\n /* Check if grayscale is reducible */\n\n int\n depth_4_ok=MagickTrue,\n depth_2_ok=MagickTrue,\n depth_1_ok=MagickTrue;\n\n for (i=0; i < (ssize_t) image_colors; i++)\n {\n unsigned char\n intensity;\n\n intensity=ScaleQuantumToChar(image->colormap[i].red);\n\n if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4))\n depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse;\n else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2))\n depth_2_ok=depth_1_ok=MagickFalse;\n else if ((intensity & 0x01) != ((intensity & 0x02) >> 1))\n depth_1_ok=MagickFalse;\n }\n\n if (depth_1_ok && mng_info->write_png_depth <= 1)\n ping_bit_depth=1;\n\n else if (depth_2_ok && mng_info->write_png_depth <= 2)\n ping_bit_depth=2;\n\n else if (depth_4_ok && mng_info->write_png_depth <= 4)\n ping_bit_depth=4;\n }\n }\n\n image_depth=ping_bit_depth;\n }\n\n else\n\n if (mng_info->IsPalette)\n {\n number_colors=image_colors;\n\n if (image_depth <= 8)\n {\n /*\n Set image palette.\n */\n ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;\n\n if (!(mng_info->have_write_global_plte && matte == MagickFalse))\n {\n for (i=0; i < (ssize_t) number_colors; i++)\n {\n palette[i].red=ScaleQuantumToChar(image->colormap[i].red);\n palette[i].green=\n ScaleQuantumToChar(image->colormap[i].green);\n palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue);\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up PLTE chunk with %d colors\",\n number_colors);\n\n ping_have_PLTE=MagickTrue;\n }\n\n /* color_type is PNG_COLOR_TYPE_PALETTE */\n if (mng_info->write_png_depth == 0)\n {\n size_t\n one;\n\n ping_bit_depth=1;\n one=1;\n\n while ((one << ping_bit_depth) < (size_t) number_colors)\n ping_bit_depth <<= 1;\n }\n\n ping_num_trans=0;\n\n if (matte != MagickFalse)\n {\n /*\n * Set up trans_colors array.\n */\n assert(number_colors <= 256);\n\n ping_num_trans=(unsigned short) (number_transparent +\n number_semitransparent);\n\n if (ping_num_trans == 0)\n ping_have_tRNS=MagickFalse;\n\n else\n {\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Scaling ping_trans_color (1)\");\n }\n ping_have_tRNS=MagickTrue;\n\n for (i=0; i < ping_num_trans; i++)\n {\n ping_trans_alpha[i]= (png_byte)\n ScaleQuantumToChar(image->colormap[i].alpha);\n }\n }\n }\n }\n }\n\n else\n {\n\n if (image_depth < 8)\n image_depth=8;\n\n if ((save_image_depth == 16) && (image_depth == 8))\n {\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Scaling ping_trans_color from (%d,%d,%d)\",\n (int) ping_trans_color.red,\n (int) ping_trans_color.green,\n (int) ping_trans_color.blue);\n }\n\n ping_trans_color.red*=0x0101;\n ping_trans_color.green*=0x0101;\n ping_trans_color.blue*=0x0101;\n ping_trans_color.gray*=0x0101;\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" to (%d,%d,%d)\",\n (int) ping_trans_color.red,\n (int) ping_trans_color.green,\n (int) ping_trans_color.blue);\n }\n }\n }\n\n if (ping_bit_depth < (ssize_t) mng_info->write_png_depth)\n ping_bit_depth = (ssize_t) mng_info->write_png_depth;\n\n /*\n Adjust background and transparency samples in sub-8-bit grayscale files.\n */\n if (ping_bit_depth < 8 && ping_color_type ==\n PNG_COLOR_TYPE_GRAY)\n {\n png_uint_16\n maxval;\n\n size_t\n one=1;\n\n maxval=(png_uint_16) ((one << ping_bit_depth)-1);\n\n if (ping_exclude_bKGD == MagickFalse)\n {\n\n ping_background.gray=(png_uint_16) ((maxval/65535.)*\n (ScaleQuantumToShort(((GetPixelInfoIntensity(image,\n &image->background_color))) +.5)));\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up bKGD chunk (2)\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" background_color index is %d\",\n (int) ping_background.index);\n\n ping_have_bKGD = MagickTrue;\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Scaling ping_trans_color.gray from %d\",\n (int)ping_trans_color.gray);\n\n ping_trans_color.gray=(png_uint_16) ((maxval/255.)*(\n ping_trans_color.gray)+.5);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" to %d\", (int)ping_trans_color.gray);\n }\n\n if (ping_exclude_bKGD == MagickFalse)\n {\n if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE)\n {\n /*\n Identify which colormap entry is the background color.\n */\n\n number_colors=image_colors;\n\n for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++)\n if (IsPNGColorEqual(image->background_color,image->colormap[i]))\n break;\n\n ping_background.index=(png_byte) i;\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up bKGD chunk with index=%d\",(int) i);\n }\n\n if (i < (ssize_t) number_colors)\n {\n ping_have_bKGD = MagickTrue;\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" background =(%d,%d,%d)\",\n (int) ping_background.red,\n (int) ping_background.green,\n (int) ping_background.blue);\n }\n }\n\n else /* Can't happen */\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" No room in PLTE to add bKGD color\");\n ping_have_bKGD = MagickFalse;\n }\n }\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" PNG color type: %s (%d)\", PngColorTypeToString(ping_color_type),\n ping_color_type);\n /*\n Initialize compression level and filtering.\n */\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up deflate compression\");\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression buffer size: 32768\");\n }\n\n png_set_compression_buffer_size(ping,32768L);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression mem level: 9\");\n\n png_set_compression_mem_level(ping, 9);\n\n /* Untangle the \"-quality\" setting:\n\n Undefined is 0; the default is used.\n Default is 75\n\n 10's digit:\n\n 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the\n zlib default compression level\n\n 1-9: the zlib compression level\n\n 1's digit:\n\n 0-4: the PNG filter method\n\n 5: libpng adaptive filtering if compression level > 5\n libpng filter type \"none\" if compression level <= 5\n or if image is grayscale or palette\n\n 6: libpng adaptive filtering\n\n 7: \"LOCO\" filtering (intrapixel differing) if writing\n a MNG, otherwise \"none\". Did not work in IM-6.7.0-9\n and earlier because of a missing \"else\".\n\n 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive\n filtering. Unused prior to IM-6.7.0-10, was same as 6\n\n 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters\n Unused prior to IM-6.7.0-10, was same as 6\n\n Note that using the -quality option, not all combinations of\n PNG filter type, zlib compression level, and zlib compression\n strategy are possible. This will be addressed soon in a\n release that accomodates \"-define png:compression-strategy\", etc.\n\n */\n\n quality=image_info->quality == UndefinedCompressionQuality ? 75UL :\n image_info->quality;\n\n if (quality <= 9)\n {\n if (mng_info->write_png_compression_strategy == 0)\n mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1;\n }\n\n else if (mng_info->write_png_compression_level == 0)\n {\n int\n level;\n\n level=(int) MagickMin((ssize_t) quality/10,9);\n\n mng_info->write_png_compression_level = level+1;\n }\n\n if (mng_info->write_png_compression_strategy == 0)\n {\n if ((quality %10) == 8 || (quality %10) == 9)\n#ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */\n mng_info->write_png_compression_strategy=Z_RLE+1;\n#else\n mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1;\n#endif\n }\n\n if (mng_info->write_png_compression_filter == 0)\n mng_info->write_png_compression_filter=((int) quality % 10) + 1;\n\n if (logging != MagickFalse)\n {\n if (mng_info->write_png_compression_level)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression level: %d\",\n (int) mng_info->write_png_compression_level-1);\n\n if (mng_info->write_png_compression_strategy)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression strategy: %d\",\n (int) mng_info->write_png_compression_strategy-1);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up filtering\");\n\n if (mng_info->write_png_compression_filter == 6)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Base filter method: ADAPTIVE\");\n else if (mng_info->write_png_compression_filter == 0 ||\n mng_info->write_png_compression_filter == 1)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Base filter method: NONE\");\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Base filter method: %d\",\n (int) mng_info->write_png_compression_filter-1);\n }\n\n if (mng_info->write_png_compression_level != 0)\n png_set_compression_level(ping,mng_info->write_png_compression_level-1);\n\n if (mng_info->write_png_compression_filter == 6)\n {\n if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) ||\n ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) ||\n (quality < 50))\n png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);\n else\n png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS);\n }\n else if (mng_info->write_png_compression_filter == 7 ||\n mng_info->write_png_compression_filter == 10)\n png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS);\n\n else if (mng_info->write_png_compression_filter == 8)\n {\n#if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING)\n if (mng_info->write_mng)\n {\n if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) ||\n ((int) ping_color_type == PNG_COLOR_TYPE_RGBA))\n ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING;\n }\n#endif\n png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);\n }\n\n else if (mng_info->write_png_compression_filter == 9)\n png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);\n\n else if (mng_info->write_png_compression_filter != 0)\n png_set_filter(ping,PNG_FILTER_TYPE_BASE,\n mng_info->write_png_compression_filter-1);\n\n if (mng_info->write_png_compression_strategy != 0)\n png_set_compression_strategy(ping,\n mng_info->write_png_compression_strategy-1);\n\n ping_interlace_method=image_info->interlace != NoInterlace;\n\n if (mng_info->write_mng)\n png_set_sig_bytes(ping,8);\n\n /* Bail out if cannot meet defined png:bit-depth or png:color-type */\n\n if (mng_info->write_png_colortype != 0)\n {\n if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY)\n if (ping_have_color != MagickFalse)\n {\n ping_color_type = PNG_COLOR_TYPE_RGB;\n\n if (ping_bit_depth < 8)\n ping_bit_depth=8;\n }\n\n if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA)\n if (ping_have_color != MagickFalse)\n ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA;\n }\n\n if (ping_need_colortype_warning != MagickFalse ||\n ((mng_info->write_png_depth &&\n (int) mng_info->write_png_depth != ping_bit_depth) ||\n (mng_info->write_png_colortype &&\n ((int) mng_info->write_png_colortype-1 != ping_color_type &&\n mng_info->write_png_colortype != 7 &&\n !(mng_info->write_png_colortype == 5 && ping_color_type == 0)))))\n {\n if (logging != MagickFalse)\n {\n if (ping_need_colortype_warning != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Image has transparency but tRNS chunk was excluded\");\n }\n\n if (mng_info->write_png_depth)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Defined png:bit-depth=%u, Computed depth=%u\",\n mng_info->write_png_depth,\n ping_bit_depth);\n }\n\n if (mng_info->write_png_colortype)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Defined png:color-type=%u, Computed color type=%u\",\n mng_info->write_png_colortype-1,\n ping_color_type);\n }\n }\n\n png_warning(ping,\n \"Cannot write image with defined png:bit-depth or png:color-type.\");\n }\n\n if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait)\n {\n /* Add an opaque matte channel */\n image->alpha_trait = BlendPixelTrait;\n (void) SetImageAlpha(image,OpaqueAlpha,exception);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Added an opaque matte channel\");\n }\n\n if (number_transparent != 0 || number_semitransparent != 0)\n {\n if (ping_color_type < 4)\n {\n ping_have_tRNS=MagickTrue;\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting ping_have_tRNS=MagickTrue.\");\n }\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing PNG header chunks\");\n\n png_set_IHDR(ping,ping_info,ping_width,ping_height,\n ping_bit_depth,ping_color_type,\n ping_interlace_method,ping_compression_method,\n ping_filter_method);\n\n if (ping_color_type == 3 && ping_have_PLTE != MagickFalse)\n {\n png_set_PLTE(ping,ping_info,palette,number_colors);\n\n if (logging != MagickFalse)\n {\n for (i=0; i< (ssize_t) number_colors; i++)\n {\n if (i < ping_num_trans)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)\",\n (int) i,\n (int) palette[i].red,\n (int) palette[i].green,\n (int) palette[i].blue,\n (int) i,\n (int) ping_trans_alpha[i]);\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" PLTE[%d] = (%d,%d,%d)\",\n (int) i,\n (int) palette[i].red,\n (int) palette[i].green,\n (int) palette[i].blue);\n }\n }\n }\n\n /* Only write the iCCP chunk if we are not writing the sRGB chunk. */\n if (ping_exclude_sRGB != MagickFalse ||\n (!png_get_valid(ping,ping_info,PNG_INFO_sRGB)))\n {\n if ((ping_exclude_tEXt == MagickFalse ||\n ping_exclude_zTXt == MagickFalse) &&\n (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse))\n {\n ResetImageProfileIterator(image);\n for (name=GetNextImageProfile(image); name != (const char *) NULL; )\n {\n profile=GetImageProfile(image,name);\n\n if (profile != (StringInfo *) NULL)\n {\n#ifdef PNG_WRITE_iCCP_SUPPORTED\n if ((LocaleCompare(name,\"ICC\") == 0) ||\n (LocaleCompare(name,\"ICM\") == 0))\n {\n ping_have_iCCP = MagickTrue;\n if (ping_exclude_iCCP == MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up iCCP chunk\");\n\n png_set_iCCP(ping,ping_info,(png_charp) name,0,\n#if (PNG_LIBPNG_VER < 10500)\n (png_charp) GetStringInfoDatum(profile),\n#else\n (const png_byte *) GetStringInfoDatum(profile),\n#endif\n (png_uint_32) GetStringInfoLength(profile));\n }\n else\n {\n /* Do not write hex-encoded ICC chunk */\n name=GetNextImageProfile(image);\n continue;\n }\n }\n#endif /* WRITE_iCCP */\n\n if (LocaleCompare(name,\"exif\") == 0)\n {\n /* Do not write hex-encoded ICC chunk; we will\n write it later as an eXIf chunk */\n name=GetNextImageProfile(image);\n continue;\n }\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up zTXt chunk with uuencoded %s profile\",\n name);\n Magick_png_write_raw_profile(image_info,ping,ping_info,\n (unsigned char *) name,(unsigned char *) name,\n GetStringInfoDatum(profile),\n (png_uint_32) GetStringInfoLength(profile));\n }\n name=GetNextImageProfile(image);\n }\n }\n }\n\n#if defined(PNG_WRITE_sRGB_SUPPORTED)\n if ((mng_info->have_write_global_srgb == 0) &&\n ping_have_iCCP != MagickTrue &&\n (ping_have_sRGB != MagickFalse ||\n png_get_valid(ping,ping_info,PNG_INFO_sRGB)))\n {\n if (ping_exclude_sRGB == MagickFalse)\n {\n /*\n Note image rendering intent.\n */\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up sRGB chunk\");\n\n (void) png_set_sRGB(ping,ping_info,(\n Magick_RenderingIntent_to_PNG_RenderingIntent(\n image->rendering_intent)));\n\n ping_have_sRGB = MagickTrue;\n }\n }\n\n if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB)))\n#endif\n {\n if (ping_exclude_gAMA == MagickFalse &&\n ping_have_iCCP == MagickFalse &&\n ping_have_sRGB == MagickFalse &&\n (ping_exclude_sRGB == MagickFalse ||\n (image->gamma < .45 || image->gamma > .46)))\n {\n if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0))\n {\n /*\n Note image gamma.\n To do: check for cHRM+gAMA == sRGB, and write sRGB instead.\n */\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up gAMA chunk\");\n\n png_set_gAMA(ping,ping_info,image->gamma);\n }\n }\n\n if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse)\n {\n if ((mng_info->have_write_global_chrm == 0) &&\n (image->chromaticity.red_primary.x != 0.0))\n {\n /*\n Note image chromaticity.\n Note: if cHRM+gAMA == sRGB write sRGB instead.\n */\n PrimaryInfo\n bp,\n gp,\n rp,\n wp;\n\n wp=image->chromaticity.white_point;\n rp=image->chromaticity.red_primary;\n gp=image->chromaticity.green_primary;\n bp=image->chromaticity.blue_primary;\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up cHRM chunk\");\n\n png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y,\n bp.x,bp.y);\n }\n }\n }\n\n if (ping_exclude_bKGD == MagickFalse)\n {\n if (ping_have_bKGD != MagickFalse)\n {\n png_set_bKGD(ping,ping_info,&ping_background);\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up bKGD chunk\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" background color = (%d,%d,%d)\",\n (int) ping_background.red,\n (int) ping_background.green,\n (int) ping_background.blue);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" index = %d, gray=%d\",\n (int) ping_background.index,\n (int) ping_background.gray);\n }\n }\n }\n\n if (ping_exclude_pHYs == MagickFalse)\n {\n if (ping_have_pHYs != MagickFalse)\n {\n png_set_pHYs(ping,ping_info,\n ping_pHYs_x_resolution,\n ping_pHYs_y_resolution,\n ping_pHYs_unit_type);\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up pHYs chunk\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" x_resolution=%lu\",\n (unsigned long) ping_pHYs_x_resolution);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" y_resolution=%lu\",\n (unsigned long) ping_pHYs_y_resolution);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" unit_type=%lu\",\n (unsigned long) ping_pHYs_unit_type);\n }\n }\n }\n\n#if defined(PNG_tIME_SUPPORTED)\n if (ping_exclude_tIME == MagickFalse)\n {\n const char\n *timestamp;\n\n if (image->taint == MagickFalse)\n {\n timestamp=GetImageOption(image_info,\"png:tIME\");\n\n if (timestamp == (const char *) NULL)\n timestamp=GetImageProperty(image,\"png:tIME\",exception);\n }\n\n else\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reset tIME in tainted image\");\n\n timestamp=GetImageProperty(image,\"date:modify\",exception);\n }\n\n if (timestamp != (const char *) NULL)\n write_tIME_chunk(image,ping,ping_info,timestamp,exception);\n }\n#endif\n\n if (mng_info->need_blob != MagickFalse)\n {\n if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) ==\n MagickFalse)\n png_error(ping,\"WriteBlob Failed\");\n\n ping_have_blob=MagickTrue;\n }\n\n png_write_info_before_PLTE(ping, ping_info);\n\n if (ping_have_tRNS != MagickFalse && ping_color_type < 4)\n {\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Calling png_set_tRNS with num_trans=%d\",ping_num_trans);\n }\n\n if (ping_color_type == 3)\n (void) png_set_tRNS(ping, ping_info,\n ping_trans_alpha,\n ping_num_trans,\n NULL);\n\n else\n {\n (void) png_set_tRNS(ping, ping_info,\n NULL,\n 0,\n &ping_trans_color);\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" tRNS color =(%d,%d,%d)\",\n (int) ping_trans_color.red,\n (int) ping_trans_color.green,\n (int) ping_trans_color.blue);\n }\n }\n }\n\n png_write_info(ping,ping_info);\n\n /* write orNT if image->orientation is defined */\n if (image->orientation != UndefinedOrientation)\n {\n unsigned char\n chunk[6];\n (void) WriteBlobMSBULong(image,1L); /* data length=1 */\n PNGType(chunk,mng_orNT);\n LogPNGChunk(logging,mng_orNT,1L);\n /* PNG uses Exif orientation values */\n chunk[4]=Magick_Orientation_to_Exif_Orientation(image->orientation);\n (void) WriteBlob(image,5,chunk);\n (void) WriteBlobMSBULong(image,crc32(0,chunk,5));\n }\n\n ping_wrote_caNv = MagickFalse;\n\n /* write caNv chunk */\n if (ping_exclude_caNv == MagickFalse)\n {\n if ((image->page.width != 0 && image->page.width != image->columns) ||\n (image->page.height != 0 && image->page.height != image->rows) ||\n image->page.x != 0 || image->page.y != 0)\n {\n unsigned char\n chunk[20];\n\n (void) WriteBlobMSBULong(image,16L); /* data length=8 */\n PNGType(chunk,mng_caNv);\n LogPNGChunk(logging,mng_caNv,16L);\n PNGLong(chunk+4,(png_uint_32) image->page.width);\n PNGLong(chunk+8,(png_uint_32) image->page.height);\n PNGsLong(chunk+12,(png_int_32) image->page.x);\n PNGsLong(chunk+16,(png_int_32) image->page.y);\n (void) WriteBlob(image,20,chunk);\n (void) WriteBlobMSBULong(image,crc32(0,chunk,20));\n ping_wrote_caNv = MagickTrue;\n }\n }\n\n#if defined(PNG_oFFs_SUPPORTED)\n if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse)\n {\n if (image->page.x || image->page.y)\n {\n png_set_oFFs(ping,ping_info,(png_int_32) image->page.x,\n (png_int_32) image->page.y, 0);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up oFFs chunk with x=%d, y=%d, units=0\",\n (int) image->page.x, (int) image->page.y);\n }\n }\n#endif\n\n#if (PNG_LIBPNG_VER == 10206)\n /* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */\n#define PNG_HAVE_IDAT 0x04\n ping->mode |= PNG_HAVE_IDAT;\n#undef PNG_HAVE_IDAT\n#endif\n\n png_set_packing(ping);\n /*\n Allocate memory.\n */\n rowbytes=image->columns;\n if (image_depth > 8)\n rowbytes*=2;\n switch (ping_color_type)\n {\n case PNG_COLOR_TYPE_RGB:\n rowbytes*=3;\n break;\n\n case PNG_COLOR_TYPE_GRAY_ALPHA:\n rowbytes*=2;\n break;\n\n case PNG_COLOR_TYPE_RGBA:\n rowbytes*=4;\n break;\n\n default:\n break;\n }\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing PNG image data\");\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Allocating %.20g bytes of memory for pixels\",(double) rowbytes);\n }\n pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n png_error(ping,\"Allocation of memory for pixels failed\");\n ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n\n /*\n Initialize image scanlines.\n */\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n png_error(ping,\"Memory allocation for quantum_info failed\");\n quantum_info->format=UndefinedQuantumFormat;\n SetQuantumDepth(image,quantum_info,image_depth);\n (void) SetQuantumEndian(image,quantum_info,MSBEndian);\n num_passes=png_set_interlace_handling(ping);\n\n if ((!mng_info->write_png8 && !mng_info->write_png24 &&\n !mng_info->write_png48 && !mng_info->write_png64 &&\n !mng_info->write_png32) &&\n (mng_info->IsPalette ||\n (image_info->type == BilevelType)) &&\n image_matte == MagickFalse &&\n ping_have_non_bw == MagickFalse)\n {\n /* Palette, Bilevel, or Opaque Monochrome */\n register const Quantum\n *p;\n\n SetQuantumDepth(image,quantum_info,8);\n for (pass=0; pass < num_passes; pass++)\n {\n /*\n Convert PseudoClass image to a PNG monochrome image.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing row of pixels (0)\");\n\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n\n if (p == (const Quantum *) NULL)\n break;\n\n if (mng_info->IsPalette)\n {\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,GrayQuantum,ping_pixels,exception);\n if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE &&\n mng_info->write_png_depth &&\n mng_info->write_png_depth != old_bit_depth)\n {\n /* Undo pixel scaling */\n for (i=0; i < (ssize_t) image->columns; i++)\n *(ping_pixels+i)=(unsigned char) (*(ping_pixels+i)\n >> (8-old_bit_depth));\n }\n }\n\n else\n {\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,RedQuantum,ping_pixels,exception);\n }\n\n if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE)\n for (i=0; i < (ssize_t) image->columns; i++)\n *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ?\n 255 : 0);\n\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing row of pixels (1)\");\n\n png_write_row(ping,ping_pixels);\n\n status=SetImageProgress(image,SaveImageTag,\n (MagickOffsetType) (pass * image->rows + y),\n num_passes * image->rows);\n\n if (status == MagickFalse)\n break;\n }\n }\n }\n\n else /* Not Palette, Bilevel, or Opaque Monochrome */\n {\n if ((!mng_info->write_png8 && !mng_info->write_png24 &&\n !mng_info->write_png48 && !mng_info->write_png64 &&\n !mng_info->write_png32) && (image_matte != MagickFalse ||\n (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) &&\n (mng_info->IsPalette) && ping_have_color == MagickFalse)\n {\n register const Quantum\n *p;\n\n for (pass=0; pass < num_passes; pass++)\n {\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n\n if (p == (const Quantum *) NULL)\n break;\n\n if (ping_color_type == PNG_COLOR_TYPE_GRAY)\n {\n if (mng_info->IsPalette)\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,GrayQuantum,ping_pixels,exception);\n\n else\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,RedQuantum,ping_pixels,exception);\n\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing GRAY PNG pixels (2)\");\n }\n\n else /* PNG_COLOR_TYPE_GRAY_ALPHA */\n {\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing GRAY_ALPHA PNG pixels (2)\");\n\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,GrayAlphaQuantum,ping_pixels,exception);\n }\n\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing row of pixels (2)\");\n\n png_write_row(ping,ping_pixels);\n\n status=SetImageProgress(image,SaveImageTag,\n (MagickOffsetType) (pass * image->rows + y),\n num_passes * image->rows);\n\n if (status == MagickFalse)\n break;\n }\n }\n }\n\n else\n {\n register const Quantum\n *p;\n\n for (pass=0; pass < num_passes; pass++)\n {\n if ((image_depth > 8) ||\n mng_info->write_png24 ||\n mng_info->write_png32 ||\n mng_info->write_png48 ||\n mng_info->write_png64 ||\n (!mng_info->write_png8 && !mng_info->IsPalette))\n {\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1, exception);\n\n if (p == (const Quantum *) NULL)\n break;\n\n if (ping_color_type == PNG_COLOR_TYPE_GRAY)\n {\n if (image->storage_class == DirectClass)\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,RedQuantum,ping_pixels,exception);\n\n else\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,GrayQuantum,ping_pixels,exception);\n }\n\n else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)\n {\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,GrayAlphaQuantum,ping_pixels,\n exception);\n\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing GRAY_ALPHA PNG pixels (3)\");\n }\n\n else if (image_matte != MagickFalse)\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,RGBAQuantum,ping_pixels,exception);\n\n else\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,RGBQuantum,ping_pixels,exception);\n\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing row of pixels (3)\");\n\n png_write_row(ping,ping_pixels);\n\n status=SetImageProgress(image,SaveImageTag,\n (MagickOffsetType) (pass * image->rows + y),\n num_passes * image->rows);\n\n if (status == MagickFalse)\n break;\n }\n }\n\n else\n /* not ((image_depth > 8) ||\n mng_info->write_png24 || mng_info->write_png32 ||\n mng_info->write_png48 || mng_info->write_png64 ||\n (!mng_info->write_png8 && !mng_info->IsPalette))\n */\n {\n if ((ping_color_type != PNG_COLOR_TYPE_GRAY) &&\n (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA))\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" pass %d, Image Is not GRAY or GRAY_ALPHA\",pass);\n\n SetQuantumDepth(image,quantum_info,8);\n image_depth=8;\n }\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA\",\n pass);\n\n p=GetVirtualPixels(image,0,y,image->columns,1, exception);\n\n if (p == (const Quantum *) NULL)\n break;\n\n if (ping_color_type == PNG_COLOR_TYPE_GRAY)\n {\n SetQuantumDepth(image,quantum_info,image->depth);\n\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,GrayQuantum,ping_pixels,exception);\n }\n\n else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)\n {\n if (logging != MagickFalse && y == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing GRAY_ALPHA PNG pixels (4)\");\n\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,GrayAlphaQuantum,ping_pixels,\n exception);\n }\n\n else\n {\n (void) ExportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,IndexQuantum,ping_pixels,exception);\n\n if (logging != MagickFalse && y <= 2)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing row of non-gray pixels (4)\");\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" ping_pixels[0]=%d,ping_pixels[1]=%d\",\n (int)ping_pixels[0],(int)ping_pixels[1]);\n }\n }\n png_write_row(ping,ping_pixels);\n\n status=SetImageProgress(image,SaveImageTag,\n (MagickOffsetType) (pass * image->rows + y),\n num_passes * image->rows);\n\n if (status == MagickFalse)\n break;\n }\n }\n }\n }\n }\n\n if (quantum_info != (QuantumInfo *) NULL)\n quantum_info=DestroyQuantumInfo(quantum_info);\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Wrote PNG image data\");\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Width: %.20g\",(double) ping_width);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Height: %.20g\",(double) ping_height);\n\n if (mng_info->write_png_depth)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Defined png:bit-depth: %d\",mng_info->write_png_depth);\n }\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" PNG bit-depth written: %d\",ping_bit_depth);\n\n if (mng_info->write_png_colortype)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Defined png:color-type: %d\",mng_info->write_png_colortype-1);\n }\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" PNG color-type written: %d\",ping_color_type);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" PNG Interlace method: %d\",ping_interlace_method);\n }\n /*\n Generate text chunks after IDAT.\n */\n if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse)\n {\n ResetImagePropertyIterator(image);\n property=GetNextImageProperty(image);\n while (property != (const char *) NULL)\n {\n png_textp\n text;\n\n value=GetImageProperty(image,property,exception);\n\n /* Don't write any \"png:\" or \"jpeg:\" properties; those are just for\n * \"identify\" or for passing through to another JPEG\n */\n if ((LocaleNCompare(property,\"png:\",4) != 0 &&\n LocaleNCompare(property,\"jpeg:\",5) != 0) &&\n\n\n /* Suppress density and units if we wrote a pHYs chunk */\n (ping_exclude_pHYs != MagickFalse ||\n LocaleCompare(property,\"density\") != 0 ||\n LocaleCompare(property,\"units\") != 0) &&\n\n /* Suppress the IM-generated Date:create and Date:modify */\n (ping_exclude_date == MagickFalse ||\n LocaleNCompare(property, \"Date:\",5) != 0))\n {\n if (value != (const char *) NULL)\n {\n\n#if PNG_LIBPNG_VER >= 10400\n text=(png_textp) png_malloc(ping,\n (png_alloc_size_t) sizeof(png_text));\n#else\n text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text));\n#endif\n text[0].key=(char *) property;\n text[0].text=(char *) value;\n text[0].text_length=strlen(value);\n\n if (ping_exclude_tEXt != MagickFalse)\n text[0].compression=PNG_TEXT_COMPRESSION_zTXt;\n\n else if (ping_exclude_zTXt != MagickFalse)\n text[0].compression=PNG_TEXT_COMPRESSION_NONE;\n\n else\n {\n text[0].compression=image_info->compression == NoCompression ||\n (image_info->compression == UndefinedCompression &&\n text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE :\n PNG_TEXT_COMPRESSION_zTXt ;\n }\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Setting up text chunk\");\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" keyword: '%s'\",text[0].key);\n }\n\n png_set_text(ping,ping_info,text,1);\n png_free(ping,text);\n }\n }\n property=GetNextImageProperty(image);\n }\n }\n\n /* write eXIf profile */\n if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse)\n {\n char\n *name;\n\n ResetImageProfileIterator(image);\n\n for (name=GetNextImageProfile(image); name != (const char *) NULL; )\n {\n if (LocaleCompare(name,\"exif\") == 0)\n {\n const StringInfo\n *profile;\n\n profile=GetImageProfile(image,name);\n\n if (profile != (StringInfo *) NULL)\n {\n png_uint_32\n length;\n\n unsigned char\n chunk[4],\n *data;\n\n StringInfo\n *ping_profile;\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Have eXIf profile\");\n\n ping_profile=CloneStringInfo(profile);\n data=GetStringInfoDatum(ping_profile),\n length=(png_uint_32) GetStringInfoLength(ping_profile);\n\n PNGType(chunk,mng_eXIf);\n if (length < 7)\n {\n ping_profile=DestroyStringInfo(ping_profile);\n break; /* otherwise crashes */\n }\n\n if (*data == 'E' && *(data+1) == 'x' && *(data+2) == 'i' &&\n *(data+3) == 'f' && *(data+4) == '\\0' && *(data+5) == '\\0')\n {\n /* skip the \"Exif\\0\\0\" JFIF Exif Header ID */\n length -= 6;\n data += 6;\n }\n\n LogPNGChunk(logging,chunk,length);\n (void) WriteBlobMSBULong(image,length);\n (void) WriteBlob(image,4,chunk);\n (void) WriteBlob(image,length,data);\n (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data,\n (uInt) length));\n ping_profile=DestroyStringInfo(ping_profile);\n break;\n }\n }\n name=GetNextImageProfile(image);\n }\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing PNG end info\");\n\n png_write_end(ping,ping_info);\n\n if (mng_info->need_fram && (int) image->dispose == BackgroundDispose)\n {\n if (mng_info->page.x || mng_info->page.y ||\n (ping_width != mng_info->page.width) ||\n (ping_height != mng_info->page.height))\n {\n unsigned char\n chunk[32];\n\n /*\n Write FRAM 4 with clipping boundaries followed by FRAM 1.\n */\n (void) WriteBlobMSBULong(image,27L); /* data length=27 */\n PNGType(chunk,mng_FRAM);\n LogPNGChunk(logging,mng_FRAM,27L);\n chunk[4]=4;\n chunk[5]=0; /* frame name separator (no name) */\n chunk[6]=1; /* flag for changing delay, for next frame only */\n chunk[7]=0; /* flag for changing frame timeout */\n chunk[8]=1; /* flag for changing frame clipping for next frame */\n chunk[9]=0; /* flag for changing frame sync_id */\n PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */\n chunk[14]=0; /* clipping boundaries delta type */\n PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */\n PNGLong(chunk+19,\n (png_uint_32) (mng_info->page.x + ping_width));\n PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */\n PNGLong(chunk+27,\n (png_uint_32) (mng_info->page.y + ping_height));\n (void) WriteBlob(image,31,chunk);\n (void) WriteBlobMSBULong(image,crc32(0,chunk,31));\n mng_info->old_framing_mode=4;\n mng_info->framing_mode=1;\n }\n\n else\n mng_info->framing_mode=3;\n }\n if (mng_info->write_mng && !mng_info->need_fram &&\n ((int) image->dispose == 3))\n png_error(ping, \"Cannot convert GIF with disposal method 3 to MNG-LC\");\n\n /*\n Free PNG resources.\n */\n\n png_destroy_write_struct(&ping,&ping_info);\n\n pixel_info=RelinquishVirtualMemory(pixel_info);\n\n if (ping_have_blob != MagickFalse)\n (void) CloseBlob(image);\n\n image_info=DestroyImageInfo(image_info);\n image=DestroyImage(image);\n\n /* Store bit depth actually written */\n s[0]=(char) ping_bit_depth;\n s[1]='\\0';\n\n (void) SetImageProperty(IMimage,\"png:bit-depth-written\",s,exception);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" exit WriteOnePNGImage()\");\n\n#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE\n UnlockSemaphoreInfo(ping_semaphore);\n#endif\n\n /* } for navigation to beginning of SETJMP-protected block. Revert to\n * Throwing an Exception when an error occurs.\n */\n\n return(MagickTrue);\n/* End write one PNG image */\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/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: TIFFPrintDirectory(TIFF* tif, FILE* fd, long flags)\n{\n\tTIFFDirectory *td = &tif->tif_dir;\n\tchar *sep;\n\tlong l, n;\n\n#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))\n\tfprintf(fd, \"TIFF Directory at offset 0x%I64x (%I64u)\\n\",\n\t\t(unsigned __int64) tif->tif_diroff,\n\t\t(unsigned __int64) tif->tif_diroff);\n#else\n\tfprintf(fd, \"TIFF Directory at offset 0x%llx (%llu)\\n\",\n\t\t(unsigned long long) tif->tif_diroff,\n\t\t(unsigned long long) tif->tif_diroff);\n#endif\n\tif (TIFFFieldSet(tif,FIELD_SUBFILETYPE)) {\n\t\tfprintf(fd, \" Subfile Type:\");\n\t\tsep = \" \";\n\t\tif (td->td_subfiletype & FILETYPE_REDUCEDIMAGE) {\n\t\t\tfprintf(fd, \"%sreduced-resolution image\", sep);\n\t\t\tsep = \"/\";\n\t\t}\n\t\tif (td->td_subfiletype & FILETYPE_PAGE) {\n\t\t\tfprintf(fd, \"%smulti-page document\", sep);\n\t\t\tsep = \"/\";\n\t\t}\n\t\tif (td->td_subfiletype & FILETYPE_MASK)\n\t\t\tfprintf(fd, \"%stransparency mask\", sep);\n\t\tfprintf(fd, \" (%lu = 0x%lx)\\n\",\n\t\t (unsigned long) td->td_subfiletype, (long) td->td_subfiletype);\n\t}\n\tif (TIFFFieldSet(tif,FIELD_IMAGEDIMENSIONS)) {\n\t\tfprintf(fd, \" Image Width: %lu Image Length: %lu\",\n\t\t (unsigned long) td->td_imagewidth, (unsigned long) td->td_imagelength);\n\t\tif (TIFFFieldSet(tif,FIELD_IMAGEDEPTH))\n\t\t\tfprintf(fd, \" Image Depth: %lu\",\n\t\t\t (unsigned long) td->td_imagedepth);\n\t\tfprintf(fd, \"\\n\");\n\t}\n\tif (TIFFFieldSet(tif,FIELD_TILEDIMENSIONS)) {\n\t\tfprintf(fd, \" Tile Width: %lu Tile Length: %lu\",\n\t\t (unsigned long) td->td_tilewidth, (unsigned long) td->td_tilelength);\n\t\tif (TIFFFieldSet(tif,FIELD_TILEDEPTH))\n\t\t\tfprintf(fd, \" Tile Depth: %lu\",\n\t\t\t (unsigned long) td->td_tiledepth);\n\t\tfprintf(fd, \"\\n\");\n\t}\n\tif (TIFFFieldSet(tif,FIELD_RESOLUTION)) {\n\t\tfprintf(fd, \" Resolution: %g, %g\",\n\t\t td->td_xresolution, td->td_yresolution);\n\t\tif (TIFFFieldSet(tif,FIELD_RESOLUTIONUNIT)) {\n\t\t\tswitch (td->td_resolutionunit) {\n\t\t\tcase RESUNIT_NONE:\n\t\t\t\tfprintf(fd, \" (unitless)\");\n\t\t\t\tbreak;\n\t\t\tcase RESUNIT_INCH:\n\t\t\t\tfprintf(fd, \" pixels/inch\");\n\t\t\t\tbreak;\n\t\t\tcase RESUNIT_CENTIMETER:\n\t\t\t\tfprintf(fd, \" pixels/cm\");\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tfprintf(fd, \" (unit %u = 0x%x)\",\n\t\t\t\t td->td_resolutionunit,\n\t\t\t\t td->td_resolutionunit);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tfprintf(fd, \"\\n\");\n\t}\n\tif (TIFFFieldSet(tif,FIELD_POSITION))\n\t\tfprintf(fd, \" Position: %g, %g\\n\",\n\t\t td->td_xposition, td->td_yposition);\n\tif (TIFFFieldSet(tif,FIELD_BITSPERSAMPLE))\n\t\tfprintf(fd, \" Bits/Sample: %u\\n\", td->td_bitspersample);\n\tif (TIFFFieldSet(tif,FIELD_SAMPLEFORMAT)) {\n\t\tfprintf(fd, \" Sample Format: \");\n\t\tswitch (td->td_sampleformat) {\n\t\tcase SAMPLEFORMAT_VOID:\n\t\t\tfprintf(fd, \"void\\n\");\n\t\t\tbreak;\n\t\tcase SAMPLEFORMAT_INT:\n\t\t\tfprintf(fd, \"signed integer\\n\");\n\t\t\tbreak;\n\t\tcase SAMPLEFORMAT_UINT:\n\t\t\tfprintf(fd, \"unsigned integer\\n\");\n\t\t\tbreak;\n\t\tcase SAMPLEFORMAT_IEEEFP:\n\t\t\tfprintf(fd, \"IEEE floating point\\n\");\n\t\t\tbreak;\n\t\tcase SAMPLEFORMAT_COMPLEXINT:\n\t\t\tfprintf(fd, \"complex signed integer\\n\");\n\t\t\tbreak;\n\t\tcase SAMPLEFORMAT_COMPLEXIEEEFP:\n\t\t\tfprintf(fd, \"complex IEEE floating point\\n\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tfprintf(fd, \"%u (0x%x)\\n\",\n\t\t\t td->td_sampleformat, td->td_sampleformat);\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (TIFFFieldSet(tif,FIELD_COMPRESSION)) {\n\t\tconst TIFFCodec* c = TIFFFindCODEC(td->td_compression);\n\t\tfprintf(fd, \" Compression Scheme: \");\n\t\tif (c)\n\t\t\tfprintf(fd, \"%s\\n\", c->name);\n\t\telse\n\t\t\tfprintf(fd, \"%u (0x%x)\\n\",\n\t\t\t td->td_compression, td->td_compression);\n\t}\n\tif (TIFFFieldSet(tif,FIELD_PHOTOMETRIC)) {\n\t\tfprintf(fd, \" Photometric Interpretation: \");\n\t\tif (td->td_photometric < NPHOTONAMES)\n\t\t\tfprintf(fd, \"%s\\n\", photoNames[td->td_photometric]);\n\t\telse {\n\t\t\tswitch (td->td_photometric) {\n\t\t\tcase PHOTOMETRIC_LOGL:\n\t\t\t\tfprintf(fd, \"CIE Log2(L)\\n\");\n\t\t\t\tbreak;\n\t\t\tcase PHOTOMETRIC_LOGLUV:\n\t\t\t\tfprintf(fd, \"CIE Log2(L) (u',v')\\n\");\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tfprintf(fd, \"%u (0x%x)\\n\",\n\t\t\t\t td->td_photometric, td->td_photometric);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tif (TIFFFieldSet(tif,FIELD_EXTRASAMPLES) && td->td_extrasamples) {\n\t\tuint16 i;\n\t\tfprintf(fd, \" Extra Samples: %u<\", td->td_extrasamples);\n\t\tsep = \"\";\n\t\tfor (i = 0; i < td->td_extrasamples; i++) {\n\t\t\tswitch (td->td_sampleinfo[i]) {\n\t\t\tcase EXTRASAMPLE_UNSPECIFIED:\n\t\t\t\tfprintf(fd, \"%sunspecified\", sep);\n\t\t\t\tbreak;\n\t\t\tcase EXTRASAMPLE_ASSOCALPHA:\n\t\t\t\tfprintf(fd, \"%sassoc-alpha\", sep);\n\t\t\t\tbreak;\n\t\t\tcase EXTRASAMPLE_UNASSALPHA:\n\t\t\t\tfprintf(fd, \"%sunassoc-alpha\", sep);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tfprintf(fd, \"%s%u (0x%x)\", sep,\n\t\t\t\t td->td_sampleinfo[i], td->td_sampleinfo[i]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tsep = \", \";\n\t\t}\n\t\tfprintf(fd, \">\\n\");\n\t}\n\tif (TIFFFieldSet(tif,FIELD_INKNAMES)) {\n\t\tchar* cp;\n\t\tuint16 i;\n\t\tfprintf(fd, \" Ink Names: \");\n\t\ti = td->td_samplesperpixel;\n\t\tsep = \"\";\n\t\tfor (cp = td->td_inknames; \n\t\t i > 0 && cp < td->td_inknames + td->td_inknameslen; \n\t\t cp = strchr(cp,'\\0')+1, i--) {\n\t\t\tsize_t max_chars = \n\t\t\t\ttd->td_inknameslen - (cp - td->td_inknames);\n\t\t\tfputs(sep, fd);\n\t\t\t_TIFFprintAsciiBounded(fd, cp, max_chars);\n\t\t\tsep = \", \";\n\t\t}\n fputs(\"\\n\", fd);\n\t}\n\tif (TIFFFieldSet(tif,FIELD_THRESHHOLDING)) {\n\t\tfprintf(fd, \" Thresholding: \");\n\t\tswitch (td->td_threshholding) {\n\t\tcase THRESHHOLD_BILEVEL:\n\t\t\tfprintf(fd, \"bilevel art scan\\n\");\n\t\t\tbreak;\n\t\tcase THRESHHOLD_HALFTONE:\n\t\t\tfprintf(fd, \"halftone or dithered scan\\n\");\n\t\t\tbreak;\n\t\tcase THRESHHOLD_ERRORDIFFUSE:\n\t\t\tfprintf(fd, \"error diffused\\n\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tfprintf(fd, \"%u (0x%x)\\n\",\n\t\t\t td->td_threshholding, td->td_threshholding);\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (TIFFFieldSet(tif,FIELD_FILLORDER)) {\n\t\tfprintf(fd, \" FillOrder: \");\n\t\tswitch (td->td_fillorder) {\n\t\tcase FILLORDER_MSB2LSB:\n\t\t\tfprintf(fd, \"msb-to-lsb\\n\");\n\t\t\tbreak;\n\t\tcase FILLORDER_LSB2MSB:\n\t\t\tfprintf(fd, \"lsb-to-msb\\n\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tfprintf(fd, \"%u (0x%x)\\n\",\n\t\t\t td->td_fillorder, td->td_fillorder);\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (TIFFFieldSet(tif,FIELD_YCBCRSUBSAMPLING))\n {\n\t\tfprintf(fd, \" YCbCr Subsampling: %u, %u\\n\",\n\t\t\ttd->td_ycbcrsubsampling[0], td->td_ycbcrsubsampling[1] );\n\t}\n\tif (TIFFFieldSet(tif,FIELD_YCBCRPOSITIONING)) {\n\t\tfprintf(fd, \" YCbCr Positioning: \");\n\t\tswitch (td->td_ycbcrpositioning) {\n\t\tcase YCBCRPOSITION_CENTERED:\n\t\t\tfprintf(fd, \"centered\\n\");\n\t\t\tbreak;\n\t\tcase YCBCRPOSITION_COSITED:\n\t\t\tfprintf(fd, \"cosited\\n\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tfprintf(fd, \"%u (0x%x)\\n\",\n\t\t\t td->td_ycbcrpositioning, td->td_ycbcrpositioning);\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (TIFFFieldSet(tif,FIELD_HALFTONEHINTS))\n\t\tfprintf(fd, \" Halftone Hints: light %u dark %u\\n\",\n\t\t td->td_halftonehints[0], td->td_halftonehints[1]);\n\tif (TIFFFieldSet(tif,FIELD_ORIENTATION)) {\n\t\tfprintf(fd, \" Orientation: \");\n\t\tif (td->td_orientation < NORIENTNAMES)\n\t\t\tfprintf(fd, \"%s\\n\", orientNames[td->td_orientation]);\n\t\telse\n\t\t\tfprintf(fd, \"%u (0x%x)\\n\",\n\t\t\t td->td_orientation, td->td_orientation);\n\t}\n\tif (TIFFFieldSet(tif,FIELD_SAMPLESPERPIXEL))\n\t\tfprintf(fd, \" Samples/Pixel: %u\\n\", td->td_samplesperpixel);\n\tif (TIFFFieldSet(tif,FIELD_ROWSPERSTRIP)) {\n\t\tfprintf(fd, \" Rows/Strip: \");\n\t\tif (td->td_rowsperstrip == (uint32) -1)\n\t\t\tfprintf(fd, \"(infinite)\\n\");\n\t\telse\n\t\t\tfprintf(fd, \"%lu\\n\", (unsigned long) td->td_rowsperstrip);\n\t}\n\tif (TIFFFieldSet(tif,FIELD_MINSAMPLEVALUE))\n\t\tfprintf(fd, \" Min Sample Value: %u\\n\", td->td_minsamplevalue);\n\tif (TIFFFieldSet(tif,FIELD_MAXSAMPLEVALUE))\n\t\tfprintf(fd, \" Max Sample Value: %u\\n\", td->td_maxsamplevalue);\n\tif (TIFFFieldSet(tif,FIELD_SMINSAMPLEVALUE)) {\n\t\tint i;\n\t\tint count = (tif->tif_flags & TIFF_PERSAMPLE) ? td->td_samplesperpixel : 1;\n\t\tfprintf(fd, \" SMin Sample Value:\");\n\t\tfor (i = 0; i < count; ++i)\n\t\t\tfprintf(fd, \" %g\", td->td_sminsamplevalue[i]);\n\t\tfprintf(fd, \"\\n\");\n\t}\n\tif (TIFFFieldSet(tif,FIELD_SMAXSAMPLEVALUE)) {\n\t\tint i;\n\t\tint count = (tif->tif_flags & TIFF_PERSAMPLE) ? td->td_samplesperpixel : 1;\n\t\tfprintf(fd, \" SMax Sample Value:\");\n\t\tfor (i = 0; i < count; ++i)\n\t\t\tfprintf(fd, \" %g\", td->td_smaxsamplevalue[i]);\n\t\tfprintf(fd, \"\\n\");\n\t}\n\tif (TIFFFieldSet(tif,FIELD_PLANARCONFIG)) {\n\t\tfprintf(fd, \" Planar Configuration: \");\n\t\tswitch (td->td_planarconfig) {\n\t\tcase PLANARCONFIG_CONTIG:\n\t\t\tfprintf(fd, \"single image plane\\n\");\n\t\t\tbreak;\n\t\tcase PLANARCONFIG_SEPARATE:\n\t\t\tfprintf(fd, \"separate image planes\\n\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tfprintf(fd, \"%u (0x%x)\\n\",\n\t\t\t td->td_planarconfig, td->td_planarconfig);\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (TIFFFieldSet(tif,FIELD_PAGENUMBER))\n\t\tfprintf(fd, \" Page Number: %u-%u\\n\",\n\t\t td->td_pagenumber[0], td->td_pagenumber[1]);\n\tif (TIFFFieldSet(tif,FIELD_COLORMAP)) {\n\t\tfprintf(fd, \" Color Map: \");\n\t\tif (flags & TIFFPRINT_COLORMAP) {\n\t\t\tfprintf(fd, \"\\n\");\n\t\t\tn = 1L<td_bitspersample;\n\t\t\tfor (l = 0; l < n; l++)\n\t\t\t\tfprintf(fd, \" %5ld: %5u %5u %5u\\n\",\n\t\t\t\t l,\n\t\t\t\t td->td_colormap[0][l],\n\t\t\t\t td->td_colormap[1][l],\n\t\t\t\t td->td_colormap[2][l]);\n\t\t} else\n\t\t\tfprintf(fd, \"(present)\\n\");\n\t}\n\tif (TIFFFieldSet(tif,FIELD_REFBLACKWHITE)) {\n\t\tint i;\n\t\tfprintf(fd, \" Reference Black/White:\\n\");\n\t\tfor (i = 0; i < 3; i++)\n\t\tfprintf(fd, \" %2d: %5g %5g\\n\", i,\n\t\t\ttd->td_refblackwhite[2*i+0],\n\t\t\ttd->td_refblackwhite[2*i+1]);\n\t}\n\tif (TIFFFieldSet(tif,FIELD_TRANSFERFUNCTION)) {\n\t\tfprintf(fd, \" Transfer Function: \");\n\t\tif (flags & TIFFPRINT_CURVES) {\n\t\t\tfprintf(fd, \"\\n\");\n\t\t\tn = 1L<td_bitspersample;\n\t\t\tfor (l = 0; l < n; l++) {\n\t\t\t\tuint16 i;\n\t\t\t\tfprintf(fd, \" %2ld: %5u\",\n\t\t\t\t l, td->td_transferfunction[0][l]);\n\t\t\t\tfor (i = 1; i < td->td_samplesperpixel; i++)\n\t\t\t\t\tfprintf(fd, \" %5u\",\n\t\t\t\t\t td->td_transferfunction[i][l]);\n\t\t\t\tfputc('\\n', fd);\n\t\t\t}\n\t\t} else\n\t\t\tfprintf(fd, \"(present)\\n\");\n\t}\n\tif (TIFFFieldSet(tif, FIELD_SUBIFD) && (td->td_subifd)) {\n\t\tuint16 i;\n\t\tfprintf(fd, \" SubIFD Offsets:\");\n\t\tfor (i = 0; i < td->td_nsubifd; i++)\n#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))\n\t\t\tfprintf(fd, \" %5I64u\",\n\t\t\t\t(unsigned __int64) td->td_subifd[i]);\n#else\n\t\t\tfprintf(fd, \" %5llu\",\n\t\t\t\t(unsigned long long) td->td_subifd[i]);\n#endif\n\t\tfputc('\\n', fd);\n\t}\n\n\t/*\n\t** Custom tag support.\n\t*/\n\t{\n\t\tint i;\n\t\tshort count;\n\n\t\tcount = (short) TIFFGetTagListCount(tif);\n\t\tfor(i = 0; i < count; i++) {\n\t\t\tuint32 tag = TIFFGetTagListEntry(tif, i);\n\t\t\tconst TIFFField *fip;\n\t\t\tuint32 value_count;\n\t\t\tint mem_alloc = 0;\n\t\t\tvoid *raw_data;\n\n\t\t\tfip = TIFFFieldWithTag(tif, tag);\n\t\t\tif(fip == NULL)\n\t\t\t\tcontinue;\n\n\t\t\tif(fip->field_passcount) {\n\t\t\t\tif (fip->field_readcount == TIFF_VARIABLE2 ) {\n\t\t\t\t\tif(TIFFGetField(tif, tag, &value_count, &raw_data) != 1)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t} else if (fip->field_readcount == TIFF_VARIABLE ) {\n\t\t\t\t\tuint16 small_value_count;\n\t\t\t\t\tif(TIFFGetField(tif, tag, &small_value_count, &raw_data) != 1)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tvalue_count = small_value_count;\n\t\t\t\t} else {\n\t\t\t\t\tassert (fip->field_readcount == TIFF_VARIABLE\n\t\t\t\t\t\t|| fip->field_readcount == TIFF_VARIABLE2);\n\t\t\t\t\tcontinue;\n\t\t\t\t} \n\t\t\t} else {\n\t\t\t\tif (fip->field_readcount == TIFF_VARIABLE\n\t\t\t\t || fip->field_readcount == TIFF_VARIABLE2)\n\t\t\t\t\tvalue_count = 1;\n\t\t\t\telse if (fip->field_readcount == TIFF_SPP)\n\t\t\t\t\tvalue_count = td->td_samplesperpixel;\n\t\t\t\telse\n\t\t\t\t\tvalue_count = fip->field_readcount;\n\t\t\t\tif (fip->field_tag == TIFFTAG_DOTRANGE\n\t\t\t\t && strcmp(fip->field_name,\"DotRange\") == 0) {\n\t\t\t\t\t/* TODO: This is an evil exception and should not have been\n\t\t\t\t\t handled this way ... likely best if we move it into\n\t\t\t\t\t the directory structure with an explicit field in \n\t\t\t\t\t libtiff 4.1 and assign it a FIELD_ value */\n\t\t\t\t\tstatic uint16 dotrange[2];\n\t\t\t\t\traw_data = dotrange;\n\t\t\t\t\tTIFFGetField(tif, tag, dotrange+0, dotrange+1);\n\t\t\t\t} else if (fip->field_type == TIFF_ASCII\n\t\t\t\t\t || fip->field_readcount == TIFF_VARIABLE\n\t\t\t\t\t || fip->field_readcount == TIFF_VARIABLE2\n\t\t\t\t\t || fip->field_readcount == TIFF_SPP\n\t\t\t\t\t || value_count > 1) {\n\t\t\t\t\tif(TIFFGetField(tif, tag, &raw_data) != 1)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t} else {\n\t\t\t\t\traw_data = _TIFFmalloc(\n\t\t\t\t\t _TIFFDataSize(fip->field_type)\n\t\t\t\t\t * value_count);\n\t\t\t\t\tmem_alloc = 1;\n\t\t\t\t\tif(TIFFGetField(tif, tag, raw_data) != 1) {\n\t\t\t\t\t\t_TIFFfree(raw_data);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Catch the tags which needs to be specially handled\n\t\t\t * and pretty print them. If tag not handled in\n\t\t\t * _TIFFPrettyPrintField() fall down and print it as\n\t\t\t * any other tag.\n\t\t\t */\n\t\t\tif (!_TIFFPrettyPrintField(tif, fip, fd, tag, value_count, raw_data))\n\t\t\t\t_TIFFPrintField(fd, fip, value_count, raw_data);\n\n\t\t\tif(mem_alloc)\n\t\t\t\t_TIFFfree(raw_data);\n\t\t}\n\t}\n \n\tif (tif->tif_tagmethods.printdir)\n\t\t(*tif->tif_tagmethods.printdir)(tif, fd, flags);\n\n _TIFFFillStriles( tif );\n \n\tif ((flags & TIFFPRINT_STRIPS) &&\n\t TIFFFieldSet(tif,FIELD_STRIPOFFSETS)) {\n\t\tuint32 s;\n\n\t\tfprintf(fd, \" %lu %s:\\n\",\n\t\t (unsigned long) td->td_nstrips,\n\t\t isTiled(tif) ? \"Tiles\" : \"Strips\");\n\t\tfor (s = 0; s < td->td_nstrips; s++)\n#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))\n\t\t\tfprintf(fd, \" %3lu: [%8I64u, %8I64u]\\n\",\n\t\t\t (unsigned long) s,\n\t\t\t (unsigned __int64) td->td_stripoffset[s],\n\t\t\t (unsigned __int64) td->td_stripbytecount[s]);\n#else\n\t\t\tfprintf(fd, \" %3lu: [%8llu, %8llu]\\n\",\n\t\t\t (unsigned long) s,\n\t\t\t (unsigned long long) td->td_stripoffset[s],\n\t\t\t (unsigned long long) td->td_stripbytecount[s]);\n#endif\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'libtiff/tif_print.c: TIFFPrintDirectory(): fix null pointer dereference on corrupted file. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2770'" }, { "text": "[INST] Given the following code containing errors, provide Common 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 Decompress::handleZipEntry(std::istream& zipStream, const ZipLocalFileHeader& hdr)\n{\n\tif (hdr.isDirectory())\n\t{\n\t\t// directory have 0 size, nth to read\n\t\tif (!_flattenDirs)\n\t\t{\n\t\t\tstd::string dirName = hdr.getFileName();\n\t\t\tif (!ZipCommon::isValidPath(dirName))\n\t\t\t\tthrow ZipException(\"Illegal entry name \" + dirName + \" containing parent directory reference\");\n\t\t\tPoco::Path dir(_outDir, dirName);\n\t\t\tdir.makeDirectory();\n\t\t\tPoco::File aFile(dir);\n\t\t\taFile.createDirectories();\n\t\t}\n\t\treturn true;\n\t}\n\ttry\n\t{\n\t\tstd::string fileName = hdr.getFileName();\n\t\tif (_flattenDirs)\n\t\t{\n\t\t\t// remove path info\n\t\t\tPoco::Path p(fileName);\n\t\t\tp.makeFile();\n\t\t\tfileName = p.getFileName();\n\t\t}\n\n\t\tif (!ZipCommon::isValidPath(fileName))\n\t\t\tthrow ZipException(\"Illegal entry name \" + fileName + \" containing parent directory reference\");\n\n\t\tPoco::Path file(fileName);\n\t\tfile.makeFile();\n\t\tPoco::Path dest(_outDir, file);\n\t\tdest.makeFile();\n\t\tif (dest.depth() > 0)\n\t\t{\n\t\t\tPoco::File aFile(dest.parent());\n\t\t\taFile.createDirectories();\n\t\t}\n\t\tPoco::FileOutputStream out(dest.toString());\n\t\tZipInputStream inp(zipStream, hdr, false);\n\t\tPoco::StreamCopier::copyStream(inp, out);\n\t\tout.close();\n\t\tPoco::File aFile(dest.toString());\n\t\tif (!aFile.exists() || !aFile.isFile())\n\t\t{\n\t\t\tstd::pair tmp = std::make_pair(hdr, \"Failed to create output stream \" + dest.toString());\n\t\t\tEError.notify(this, tmp);\n\t\t\treturn false;\n\t\t}\n\n\t\tif (!inp.crcValid())\n\t\t{\n\t\t\tif (!_keepIncompleteFiles)\n\t\t\t\taFile.remove();\n\t\t\tstd::pair tmp = std::make_pair(hdr, \"CRC mismatch. Corrupt file: \" + dest.toString());\n\t\t\tEError.notify(this, tmp);\n\t\t\treturn false;\n\t\t}\n\n\t\t// cannot check against hdr.getUnCompressedSize if CRC and size are not set in hdr but in a ZipDataInfo\n\t\t// crc is typically enough to detect errors\n\t\tif (aFile.getSize() != hdr.getUncompressedSize() && !hdr.searchCRCAndSizesAfterData())\n\t\t{\n\t\t\tif (!_keepIncompleteFiles)\n\t\t\t\taFile.remove();\n\t\t\tstd::pair tmp = std::make_pair(hdr, \"Filesizes do not match. Corrupt file: \" + dest.toString());\n\t\t\tEError.notify(this, tmp);\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::pair tmp = std::make_pair(hdr, file);\n\t\tEOk.notify(this, tmp);\n\t}\n\tcatch (Poco::Exception& e)\n\t{\n\t\tstd::pair tmp = std::make_pair(hdr, std::string(\"Exception: \" + e.displayText()));\n\t\tEError.notify(this, tmp);\n\t\treturn false;\n\t}\n\tcatch (...)\n\t{\n\t\tstd::pair tmp = std::make_pair(hdr, std::string(\"Unknown Exception\"));\n\t\tEError.notify(this, tmp);\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-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::testSetZipComment()\n{\n\tstd::string comment(\"Testing...123...\");\n\tstd::ofstream out(\"comment.zip\", std::ios::binary);\n\tPoco::Path theFile(ZipTest::getTestFile(\"data\", \"test.zip\"));\n\tCompress c(out, true);\n\tc.addFile(theFile, theFile.getFileName());\n\tc.setZipComment(comment);\n\tZipArchive a(c.close());\n\tassert(a.getZipComment() == comment);\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 long snd_seq_ioctl(struct file *file, unsigned int cmd,\n\t\t\t unsigned long arg)\n{\n\tstruct snd_seq_client *client = file->private_data;\n\t/* To use kernel stack for ioctl data. */\n\tunion {\n\t\tint pversion;\n\t\tint client_id;\n\t\tstruct snd_seq_system_info\tsystem_info;\n\t\tstruct snd_seq_running_info\trunning_info;\n\t\tstruct snd_seq_client_info\tclient_info;\n\t\tstruct snd_seq_port_info\tport_info;\n\t\tstruct snd_seq_port_subscribe\tport_subscribe;\n\t\tstruct snd_seq_queue_info\tqueue_info;\n\t\tstruct snd_seq_queue_status\tqueue_status;\n\t\tstruct snd_seq_queue_tempo\ttempo;\n\t\tstruct snd_seq_queue_timer\tqueue_timer;\n\t\tstruct snd_seq_queue_client\tqueue_client;\n\t\tstruct snd_seq_client_pool\tclient_pool;\n\t\tstruct snd_seq_remove_events\tremove_events;\n\t\tstruct snd_seq_query_subs\tquery_subs;\n\t} buf;\n\tconst struct ioctl_handler *handler;\n\tunsigned long size;\n\tint err;\n\n\tif (snd_BUG_ON(!client))\n\t\treturn -ENXIO;\n\n\tfor (handler = ioctl_handlers; handler->cmd > 0; ++handler) {\n\t\tif (handler->cmd == cmd)\n\t\t\tbreak;\n\t}\n\tif (handler->cmd == 0)\n\t\treturn -ENOTTY;\n\n\tmemset(&buf, 0, sizeof(buf));\n\n\t/*\n\t * All of ioctl commands for ALSA sequencer get an argument of size\n\t * within 13 bits. We can safely pick up the size from the command.\n\t */\n\tsize = _IOC_SIZE(handler->cmd);\n\tif (handler->cmd & IOC_IN) {\n\t\tif (copy_from_user(&buf, (const void __user *)arg, size))\n\t\t\treturn -EFAULT;\n\t}\n\n\terr = handler->func(client, &buf);\n\tif (err >= 0) {\n\t\t/* Some commands includes a bug in 'dir' field. */\n\t\tif (handler->cmd == SNDRV_SEQ_IOCTL_SET_QUEUE_CLIENT ||\n\t\t handler->cmd == SNDRV_SEQ_IOCTL_SET_CLIENT_POOL ||\n\t\t (handler->cmd & IOC_OUT))\n\t\t\tif (copy_to_user((void __user *)arg, &buf, size))\n\t\t\t\treturn -EFAULT;\n\t}\n\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'ALSA: seq: Make ioctls race-free\n\nThe ALSA sequencer ioctls have no protection against racy calls while\nthe concurrent operations may lead to interfere with each other. As\nreported recently, for example, the concurrent calls of setting client\npool with a combination of write calls may lead to either the\nunkillable dead-lock or UAF.\n\nAs a slightly big hammer solution, this patch introduces the mutex to\nmake each ioctl exclusive. Although this may reduce performance via\nparallel ioctl calls, usually it's not demanded for sequencer usages,\nhence it should be negligible.\n\nReported-by: Luo Quan \nReviewed-by: Kees Cook \nReviewed-by: Greg Kroah-Hartman \nCc: \nSigned-off-by: Takashi Iwai '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: GetCode_(gdIOCtx *fd, CODE_STATIC_DATA *scd, int code_size, int flag, int *ZeroDataBlockP)\n{\n\tint i, j, ret;\n\tunsigned char count;\n\n\tif (flag) {\n\t\tscd->curbit = 0;\n\t\tscd->lastbit = 0;\n\t\tscd->last_byte = 0;\n\t\tscd->done = FALSE;\n\t\treturn 0;\n\t}\n\n\tif ( (scd->curbit + code_size) >= scd->lastbit) {\n\t\tif (scd->done) {\n\t\t\tif (scd->curbit >= scd->lastbit) {\n\t\t\t\t/* Oh well */\n\t\t\t}\n\t\t\treturn -1;\n\t\t}\n\t\tscd->buf[0] = scd->buf[scd->last_byte-2];\n\t\tscd->buf[1] = scd->buf[scd->last_byte-1];\n\n if ((count = GetDataBlock(fd, &scd->buf[2], ZeroDataBlockP)) <= 0)\n\t\t\tscd->done = TRUE;\n\n\t\tscd->last_byte = 2 + count;\n\t\tscd->curbit = (scd->curbit - scd->lastbit) + 16;\n\t\tscd->lastbit = (2+count)*8 ;\n\t}\n\n\tif ((scd->curbit + code_size - 1) >= (CSD_BUF_SIZE * 8)) {\n\t\tret = -1;\n\t} else {\n\t\tret = 0;\n\t\tfor (i = scd->curbit, j = 0; j < code_size; ++i, ++j) {\n\t\t\tret |= ((scd->buf[i / 8] & (1 << (i % 8))) != 0) << j;\n\t\t}\n\t}\n\n\tscd->curbit += code_size;\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-681'], 'message': 'Fixed bug #75571: Potential infinite loop in gdImageCreateFromGifCtx\n\nDue to a signedness confusion in `GetCode_` a corrupt GIF file can\ntrigger an infinite loop. Furthermore we make sure that a GIF without\nany palette entries is treated as invalid *after* open palette entries\nhave been removed.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: feed_table_block_tag(struct table *tbl,\n\t\t char *line, struct table_mode *mode, int indent, int cmd)\n{\n int offset;\n if (mode->indent_level <= 0 && indent == -1)\n\treturn;\n if (mode->indent_level >= CHAR_MAX && indent == 1)\n\treturn;\n setwidth(tbl, mode);\n feed_table_inline_tag(tbl, line, mode, -1);\n clearcontentssize(tbl, mode);\n if (indent == 1) {\n\tmode->indent_level++;\n\tif (mode->indent_level <= MAX_INDENT_LEVEL)\n\t tbl->indent += INDENT_INCR;\n }\n else if (indent == -1) {\n\tmode->indent_level--;\n\tif (mode->indent_level < MAX_INDENT_LEVEL)\n\t tbl->indent -= INDENT_INCR;\n }\n offset = tbl->indent;\n if (cmd == HTML_DT) {\n\tif (mode->indent_level > 0 && mode->indent_level <= MAX_INDENT_LEVEL)\n\t offset -= INDENT_INCR;\n }\n if (tbl->indent > 0) {\n\tcheck_minimum0(tbl, 0);\n\taddcontentssize(tbl, offset);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-835'], 'message': 'Prevent negative indent value in feed_table_block_tag()\n\nBug-Debian: https://github.com/tats/w3m/issues/88'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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 *callexp(js_State *J)\n{\n\tjs_Ast *a = newexp(J);\nloop:\n\tif (jsP_accept(J, '.')) { a = EXP2(MEMBER, a, identifiername(J)); goto loop; }\n\tif (jsP_accept(J, '[')) { a = EXP2(INDEX, a, expression(J, 0)); jsP_expect(J, ']'); goto loop; }\n\tif (jsP_accept(J, '(')) { a = EXP2(CALL, a, arguments(J)); jsP_expect(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 void i8042_stop(struct serio *serio)\n{\n\tstruct i8042_port *port = serio->port_data;\n\n\tport->exists = false;\n\n\t/*\n\t * We synchronize with both AUX and KBD IRQs because there is\n\t * a (very unlikely) chance that AUX IRQ is raised for KBD port\n\t * and vice versa.\n\t */\n\tsynchronize_irq(I8042_AUX_IRQ);\n\tsynchronize_irq(I8042_KBD_IRQ);\n\tport->serio = NULL;\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: */\nbool skb_gso_validate_mtu(const struct sk_buff *skb, unsigned int mtu)\n{\n\tconst struct skb_shared_info *shinfo = skb_shinfo(skb);\n\tconst struct sk_buff *iter;\n\tunsigned int hlen;\n\n\thlen = skb_gso_network_seglen(skb);\n\n\tif (shinfo->gso_size != GSO_BY_FRAGS)\n\t\treturn hlen <= mtu;\n\n\t/* Undo this so we can re-use header sizes */\n\thlen -= GSO_BY_FRAGS;\n\n\tskb_walk_frags(skb, iter) {\n\t\tif (hlen + skb_headlen(iter) > mtu)\n\t\t\treturn false;\n\t}\n\n\treturn true; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'net: create skb_gso_validate_mac_len()\n\nIf you take a GSO skb, and split it into packets, will the MAC\nlength (L2 + L3 + L4 headers + payload) of those packets be small\nenough to fit within a given length?\n\nMove skb_gso_mac_seglen() to skbuff.h with other related functions\nlike skb_gso_network_seglen() so we can use it, and then create\nskb_gso_validate_mac_len to do the full calculation.\n\nSigned-off-by: Daniel Axtens \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: side_in_cb (GSocket *socket, GIOCondition condition, gpointer user_data)\n{\n ProxySide *side = user_data;\n FlatpakProxyClient *client = side->client;\n GError *error = NULL;\n Buffer *buffer;\n gboolean retval = G_SOURCE_CONTINUE;\n\n g_object_ref (client);\n\n while (!side->closed)\n {\n if (!side->got_first_byte)\n buffer = buffer_new (1, NULL);\n else if (!client->authenticated)\n buffer = buffer_new (64, NULL);\n else\n buffer = side->current_read_buffer;\n\n if (!buffer_read (side, buffer, socket))\n {\n if (buffer != side->current_read_buffer)\n buffer_unref (buffer);\n break;\n }\n\n if (!client->authenticated)\n {\n if (buffer->pos > 0)\n {\n gboolean found_auth_end = FALSE;\n gsize extra_data;\n\n buffer->size = buffer->pos;\n if (!side->got_first_byte)\n {\n buffer->send_credentials = TRUE;\n side->got_first_byte = TRUE;\n }\n /* Look for end of authentication mechanism */\n else if (side == &client->client_side)\n {\n gssize auth_end = find_auth_end (client, buffer);\n\n if (auth_end >= 0)\n {\n found_auth_end = TRUE;\n buffer->size = auth_end;\n extra_data = buffer->pos - buffer->size;\n\n /* We may have gotten some extra data which is not part of\n the auth handshake, keep it for the next iteration. */\n if (extra_data > 0)\n side->extra_input_data = g_bytes_new (buffer->data + buffer->size, extra_data);\n }\n }\n\n got_buffer_from_side (side, buffer);\n\n if (found_auth_end)\n client->authenticated = TRUE;\n }\n else\n {\n buffer_unref (buffer);\n }\n }\n else if (buffer->pos == buffer->size)\n {\n if (buffer == &side->header_buffer)\n {\n gssize required;\n required = g_dbus_message_bytes_needed (buffer->data, buffer->size, &error);\n if (required < 0)\n {\n g_warning (\"Invalid message header read\");\n side_closed (side);\n }\n else\n {\n side->current_read_buffer = buffer_new (required, buffer);\n }\n }\n else\n {\n got_buffer_from_side (side, buffer);\n side->header_buffer.pos = 0;\n side->current_read_buffer = &side->header_buffer;\n }\n }\n }\n\n if (side->closed)\n {\n side->in_source = NULL;\n retval = G_SOURCE_REMOVE;\n }\n\n g_object_unref (client);\n\n return retval;\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 amd_gpio_probe(struct platform_device *pdev)\n{\n\tint ret = 0;\n\tint irq_base;\n\tstruct resource *res;\n\tstruct amd_gpio *gpio_dev;\n\n\tgpio_dev = devm_kzalloc(&pdev->dev,\n\t\t\t\tsizeof(struct amd_gpio), GFP_KERNEL);\n\tif (!gpio_dev)\n\t\treturn -ENOMEM;\n\n\tspin_lock_init(&gpio_dev->lock);\n\n\tres = platform_get_resource(pdev, IORESOURCE_MEM, 0);\n\tif (!res) {\n\t\tdev_err(&pdev->dev, \"Failed to get gpio io resource.\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\tgpio_dev->base = devm_ioremap_nocache(&pdev->dev, res->start,\n\t\t\t\t\t\tresource_size(res));\n\tif (!gpio_dev->base)\n\t\treturn -ENOMEM;\n\n\tirq_base = platform_get_irq(pdev, 0);\n\tif (irq_base < 0) {\n\t\tdev_err(&pdev->dev, \"Failed to get gpio IRQ.\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\tgpio_dev->pdev = pdev;\n\tgpio_dev->gc.direction_input\t= amd_gpio_direction_input;\n\tgpio_dev->gc.direction_output\t= amd_gpio_direction_output;\n\tgpio_dev->gc.get\t\t\t= amd_gpio_get_value;\n\tgpio_dev->gc.set\t\t\t= amd_gpio_set_value;\n\tgpio_dev->gc.set_debounce\t= amd_gpio_set_debounce;\n\tgpio_dev->gc.dbg_show\t\t= amd_gpio_dbg_show;\n\n\tgpio_dev->gc.base\t\t\t= 0;\n\tgpio_dev->gc.label\t\t\t= pdev->name;\n\tgpio_dev->gc.owner\t\t\t= THIS_MODULE;\n\tgpio_dev->gc.parent\t\t\t= &pdev->dev;\n\tgpio_dev->gc.ngpio\t\t\t= TOTAL_NUMBER_OF_PINS;\n#if defined(CONFIG_OF_GPIO)\n\tgpio_dev->gc.of_node\t\t\t= pdev->dev.of_node;\n#endif\n\n\tgpio_dev->groups = kerncz_groups;\n\tgpio_dev->ngroups = ARRAY_SIZE(kerncz_groups);\n\n\tamd_pinctrl_desc.name = dev_name(&pdev->dev);\n\tgpio_dev->pctrl = pinctrl_register(&amd_pinctrl_desc,\n\t\t\t\t\t&pdev->dev, gpio_dev);\n\tif (IS_ERR(gpio_dev->pctrl)) {\n\t\tdev_err(&pdev->dev, \"Couldn't register pinctrl driver\\n\");\n\t\treturn PTR_ERR(gpio_dev->pctrl);\n\t}\n\n\tret = gpiochip_add_data(&gpio_dev->gc, gpio_dev);\n\tif (ret)\n\t\tgoto out1;\n\n\tret = gpiochip_add_pin_range(&gpio_dev->gc, dev_name(&pdev->dev),\n\t\t\t\t0, 0, TOTAL_NUMBER_OF_PINS);\n\tif (ret) {\n\t\tdev_err(&pdev->dev, \"Failed to add pin range\\n\");\n\t\tgoto out2;\n\t}\n\n\tret = gpiochip_irqchip_add(&gpio_dev->gc,\n\t\t\t\t&amd_gpio_irqchip,\n\t\t\t\t0,\n\t\t\t\thandle_simple_irq,\n\t\t\t\tIRQ_TYPE_NONE);\n\tif (ret) {\n\t\tdev_err(&pdev->dev, \"could not add irqchip\\n\");\n\t\tret = -ENODEV;\n\t\tgoto out2;\n\t}\n\n\tgpiochip_set_chained_irqchip(&gpio_dev->gc,\n\t\t\t\t &amd_gpio_irqchip,\n\t\t\t\t irq_base,\n\t\t\t\t amd_gpio_irq_handler);\n\n\tplatform_set_drvdata(pdev, gpio_dev);\n\n\tdev_dbg(&pdev->dev, \"amd gpio driver loaded\\n\");\n\treturn ret;\n\nout2:\n\tgpiochip_remove(&gpio_dev->gc);\n\nout1:\n\tpinctrl_unregister(gpio_dev->pctrl);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'pinctrl: amd: Use devm_pinctrl_register() for pinctrl registration\n\nUse devm_pinctrl_register() for pin control registration and clean\nerror path.\n\nSigned-off-by: Laxman Dewangan \nSigned-off-by: Linus Walleij '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: intuit_diff_type (bool need_header, mode_t *p_file_type)\n{\n file_offset this_line = 0;\n file_offset first_command_line = -1;\n char first_ed_command_letter = 0;\n lin fcl_line = 0; /* Pacify 'gcc -W'. */\n bool this_is_a_command = false;\n bool stars_this_line = false;\n bool extended_headers = false;\n enum nametype i;\n struct stat st[3];\n int stat_errno[3];\n int version_controlled[3];\n enum diff retval;\n mode_t file_type;\n size_t indent = 0;\n\n for (i = OLD; i <= INDEX; i++)\n if (p_name[i]) {\n\t free (p_name[i]);\n\t p_name[i] = 0;\n }\n for (i = 0; i < ARRAY_SIZE (invalid_names); i++)\n\tinvalid_names[i] = NULL;\n for (i = OLD; i <= NEW; i++)\n if (p_timestr[i])\n\t{\n\t free(p_timestr[i]);\n\t p_timestr[i] = 0;\n\t}\n for (i = OLD; i <= NEW; i++)\n if (p_sha1[i])\n\t{\n\t free (p_sha1[i]);\n\t p_sha1[i] = 0;\n\t}\n p_git_diff = false;\n for (i = OLD; i <= NEW; i++)\n {\n\tp_mode[i] = 0;\n\tp_copy[i] = false;\n\tp_rename[i] = false;\n }\n\n /* Ed and normal format patches don't have filename headers. */\n if (diff_type == ED_DIFF || diff_type == NORMAL_DIFF)\n need_header = false;\n\n version_controlled[OLD] = -1;\n version_controlled[NEW] = -1;\n version_controlled[INDEX] = -1;\n p_rfc934_nesting = 0;\n p_timestamp[OLD].tv_sec = p_timestamp[NEW].tv_sec = -1;\n p_says_nonexistent[OLD] = p_says_nonexistent[NEW] = 0;\n Fseek (pfp, p_base, SEEK_SET);\n p_input_line = p_bline - 1;\n for (;;) {\n\tchar *s;\n\tchar *t;\n\tfile_offset previous_line = this_line;\n\tbool last_line_was_command = this_is_a_command;\n\tbool stars_last_line = stars_this_line;\n\tsize_t indent_last_line = indent;\n\tchar ed_command_letter;\n\tbool strip_trailing_cr;\n\tsize_t chars_read;\n\n\tindent = 0;\n\tthis_line = file_tell (pfp);\n\tchars_read = pget_line (0, 0, false, false);\n\tif (chars_read == (size_t) -1)\n\t xalloc_die ();\n\tif (! chars_read) {\n\t if (first_ed_command_letter) {\n\t\t\t\t\t/* nothing but deletes!? */\n\t\tp_start = first_command_line;\n\t\tp_sline = fcl_line;\n\t\tretval = ED_DIFF;\n\t\tgoto scan_exit;\n\t }\n\t else {\n\t\tp_start = this_line;\n\t\tp_sline = p_input_line;\n\t\tif (extended_headers)\n\t\t {\n\t\t /* Patch contains no hunks; any diff type will do. */\n\t\t retval = UNI_DIFF;\n\t\t goto scan_exit;\n\t\t }\n\t\treturn NO_DIFF;\n\t }\n\t}\n\tstrip_trailing_cr = 2 <= chars_read && buf[chars_read - 2] == '\\r';\n\tfor (s = buf; *s == ' ' || *s == '\\t' || *s == 'X'; s++) {\n\t if (*s == '\\t')\n\t\tindent = (indent + 8) & ~7;\n\t else\n\t\tindent++;\n\t}\n\tif (ISDIGIT (*s))\n\t {\n\t for (t = s + 1; ISDIGIT (*t) || *t == ','; t++)\n\t /* do nothing */ ;\n\t if (*t == 'd' || *t == 'c' || *t == 'a')\n\t {\n\t\tfor (t++; ISDIGIT (*t) || *t == ','; t++)\n\t\t /* do nothing */ ;\n\t\tfor (; *t == ' ' || *t == '\\t'; t++)\n\t\t /* do nothing */ ;\n\t\tif (*t == '\\r')\n\t\t t++;\n\t\tthis_is_a_command = (*t == '\\n');\n\t }\n\t }\n\tif (! need_header\n\t && first_command_line < 0\n\t && ((ed_command_letter = get_ed_command_letter (s))\n\t\t|| this_is_a_command)) {\n\t first_command_line = this_line;\n\t first_ed_command_letter = ed_command_letter;\n\t fcl_line = p_input_line;\n\t p_indent = indent;\t\t/* assume this for now */\n\t p_strip_trailing_cr = strip_trailing_cr;\n\t}\n\tif (!stars_last_line && strnEQ(s, \"*** \", 4))\n\t {\n\t fetchname (s+4, strippath, &p_name[OLD], &p_timestr[OLD],\n\t\t &p_timestamp[OLD]);\n\t need_header = false;\n\t }\n\telse if (strnEQ(s, \"+++ \", 4))\n\t {\n\t /* Swap with NEW below. */\n\t fetchname (s+4, strippath, &p_name[OLD], &p_timestr[OLD],\n\t\t &p_timestamp[OLD]);\n\t need_header = false;\n\t p_strip_trailing_cr = strip_trailing_cr;\n\t }\n\telse if (strnEQ(s, \"Index:\", 6))\n\t {\n\t fetchname (s+6, strippath, &p_name[INDEX], (char **) 0, NULL);\n\t need_header = false;\n\t p_strip_trailing_cr = strip_trailing_cr;\n\t }\n\telse if (strnEQ(s, \"Prereq:\", 7))\n\t {\n\t for (t = s + 7; ISSPACE ((unsigned char) *t); t++)\n\t /* do nothing */ ;\n\t revision = t;\n\t for (t = revision; *t; t++)\n\t if (ISSPACE ((unsigned char) *t))\n\t\t{\n\t\t char const *u;\n\t\t for (u = t + 1; ISSPACE ((unsigned char) *u); u++)\n\t\t /* do nothing */ ;\n\t\t if (*u)\n\t\t {\n\t\t char numbuf[LINENUM_LENGTH_BOUND + 1];\n\t\t say (\"Prereq: with multiple words at line %s of patch\\n\",\n\t\t\t format_linenum (numbuf, this_line));\n\t\t }\n\t\t break;\n\t\t}\n\t if (t == revision)\n\t\trevision = 0;\n\t else {\n\t\tchar oldc = *t;\n\t\t*t = '\\0';\n\t\trevision = xstrdup (revision);\n\t\t*t = oldc;\n\t }\n\t }\n\telse if (strnEQ (s, \"diff --git \", 11))\n\t {\n\t char const *u;\n\n\t if (extended_headers)\n\t {\n\t\tp_start = this_line;\n\t\tp_sline = p_input_line;\n\t\t/* Patch contains no hunks; any diff type will do. */\n\t\tretval = UNI_DIFF;\n\t\tgoto scan_exit;\n\t }\n\n\t for (i = OLD; i <= NEW; i++)\n\t {\n\t\tfree (p_name[i]);\n\t\tp_name[i] = 0;\n\t }\n\t if (! ((p_name[OLD] = parse_name (s + 11, strippath, &u))\n\t\t && ISSPACE ((unsigned char) *u)\n\t\t && (p_name[NEW] = parse_name (u, strippath, &u))\n\t\t && (u = skip_spaces (u), ! *u)))\n\t for (i = OLD; i <= NEW; i++)\n\t\t{\n\t\t free (p_name[i]);\n\t\t p_name[i] = 0;\n\t\t}\n\t p_git_diff = true;\n\t need_header = false;\n\t }\n\telse if (p_git_diff && strnEQ (s, \"index \", 6))\n\t {\n\t char const *u, *v;\n\t if ((u = skip_hex_digits (s + 6))\n\t\t&& u[0] == '.' && u[1] == '.'\n\t\t&& (v = skip_hex_digits (u + 2))\n\t\t&& (! *v || ISSPACE ((unsigned char) *v)))\n\t {\n\t\tget_sha1(&p_sha1[OLD], s + 6, u);\n\t\tget_sha1(&p_sha1[NEW], u + 2, v);\n\t\tp_says_nonexistent[OLD] = sha1_says_nonexistent (p_sha1[OLD]);\n\t\tp_says_nonexistent[NEW] = sha1_says_nonexistent (p_sha1[NEW]);\n\t\tif (*(v = skip_spaces (v)))\n\t\t p_mode[OLD] = p_mode[NEW] = fetchmode (v);\n\t\textended_headers = true;\n\t }\n\t }\n\telse if (p_git_diff && strnEQ (s, \"old mode \", 9))\n\t {\n\t p_mode[OLD] = fetchmode (s + 9);\n\t extended_headers = true;\n\t }\n\telse if (p_git_diff && strnEQ (s, \"new mode \", 9))\n\t {\n\t p_mode[NEW] = fetchmode (s + 9);\n\t extended_headers = true;\n\t }\n\telse if (p_git_diff && strnEQ (s, \"deleted file mode \", 18))\n\t {\n\t p_mode[OLD] = fetchmode (s + 18);\n\t p_says_nonexistent[NEW] = 2;\n\t extended_headers = true;\n\t }\n\telse if (p_git_diff && strnEQ (s, \"new file mode \", 14))\n\t {\n\t p_mode[NEW] = fetchmode (s + 14);\n\t p_says_nonexistent[OLD] = 2;\n\t extended_headers = true;\n\t }\n\telse if (p_git_diff && strnEQ (s, \"rename from \", 12))\n\t {\n\t /* Git leaves out the prefix in the file name in this header,\n\t so we can only ignore the file name. */\n\t p_rename[OLD] = true;\n\t extended_headers = true;\n\t }\n\telse if (p_git_diff && strnEQ (s, \"rename to \", 10))\n\t {\n\t /* Git leaves out the prefix in the file name in this header,\n\t so we can only ignore the file name. */\n\t p_rename[NEW] = true;\n\t extended_headers = true;\n\t }\n\telse if (p_git_diff && strnEQ (s, \"copy from \", 10))\n\t {\n\t /* Git leaves out the prefix in the file name in this header,\n\t so we can only ignore the file name. */\n\t p_copy[OLD] = true;\n\t extended_headers = true;\n\t }\n\telse if (p_git_diff && strnEQ (s, \"copy to \", 8))\n\t {\n\t /* Git leaves out the prefix in the file name in this header,\n\t so we can only ignore the file name. */\n\t p_copy[NEW] = true;\n\t extended_headers = true;\n\t }\n\telse if (p_git_diff && strnEQ (s, \"GIT binary patch\", 16))\n\t {\n\t p_start = this_line;\n\t p_sline = p_input_line;\n\t retval = GIT_BINARY_DIFF;\n\t goto scan_exit;\n\t }\n\telse\n\t {\n\t for (t = s; t[0] == '-' && t[1] == ' '; t += 2)\n\t /* do nothing */ ;\n\t if (strnEQ(t, \"--- \", 4))\n\t {\n\t\tstruct timespec timestamp;\n\t\ttimestamp.tv_sec = -1;\n\t\tfetchname (t+4, strippath, &p_name[NEW], &p_timestr[NEW],\n\t\t\t ×tamp);\n\t\tneed_header = false;\n\t\tif (timestamp.tv_sec != -1)\n\t\t {\n\t\t p_timestamp[NEW] = timestamp;\n\t\t p_rfc934_nesting = (t - s) >> 1;\n\t\t }\n\t\tp_strip_trailing_cr = strip_trailing_cr;\n\t }\n\t }\n\tif (need_header)\n\t continue;\n\tif ((diff_type == NO_DIFF || diff_type == ED_DIFF) &&\n\t first_command_line >= 0 &&\n\t strEQ(s, \".\\n\") ) {\n\t p_start = first_command_line;\n\t p_sline = fcl_line;\n\t retval = ED_DIFF;\n\t goto scan_exit;\n\t}\n\tif ((diff_type == NO_DIFF || diff_type == UNI_DIFF)\n\t && strnEQ(s, \"@@ -\", 4)) {\n\n\t /* 'p_name', 'p_timestr', and 'p_timestamp' are backwards;\n\t swap them. */\n\t struct timespec ti = p_timestamp[OLD];\n\t p_timestamp[OLD] = p_timestamp[NEW];\n\t p_timestamp[NEW] = ti;\n\t t = p_name[OLD];\n\t p_name[OLD] = p_name[NEW];\n\t p_name[NEW] = t;\n\t t = p_timestr[OLD];\n\t p_timestr[OLD] = p_timestr[NEW];\n\t p_timestr[NEW] = t;\n\n\t s += 4;\n\t if (s[0] == '0' && !ISDIGIT (s[1]))\n\t p_says_nonexistent[OLD] = 1 + ! p_timestamp[OLD].tv_sec;\n\t while (*s != ' ' && *s != '\\n')\n\t s++;\n\t while (*s == ' ')\n\t s++;\n\t if (s[0] == '+' && s[1] == '0' && !ISDIGIT (s[2]))\n\t p_says_nonexistent[NEW] = 1 + ! p_timestamp[NEW].tv_sec;\n\t p_indent = indent;\n\t p_start = this_line;\n\t p_sline = p_input_line;\n\t retval = UNI_DIFF;\n\t if (! ((p_name[OLD] || ! p_timestamp[OLD].tv_sec)\n\t\t && (p_name[NEW] || ! p_timestamp[NEW].tv_sec))\n\t\t&& ! p_name[INDEX] && need_header)\n\t {\n\t\tchar numbuf[LINENUM_LENGTH_BOUND + 1];\n\t\tsay (\"missing header for unified diff at line %s of patch\\n\",\n\t\t format_linenum (numbuf, p_sline));\n\t }\n\t goto scan_exit;\n\t}\n\tstars_this_line = strnEQ(s, \"********\", 8);\n\tif ((diff_type == NO_DIFF\n\t || diff_type == CONTEXT_DIFF\n\t || diff_type == NEW_CONTEXT_DIFF)\n\t && stars_last_line && indent_last_line == indent\n\t && strnEQ (s, \"*** \", 4)) {\n\t s += 4;\n\t if (s[0] == '0' && !ISDIGIT (s[1]))\n\t p_says_nonexistent[OLD] = 1 + ! p_timestamp[OLD].tv_sec;\n\t /* if this is a new context diff the character just before */\n\t /* the newline is a '*'. */\n\t while (*s != '\\n')\n\t\ts++;\n\t p_indent = indent;\n\t p_strip_trailing_cr = strip_trailing_cr;\n\t p_start = previous_line;\n\t p_sline = p_input_line - 1;\n\t retval = (*(s-1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);\n\n\t {\n\t /* Scan the first hunk to see whether the file contents\n\t\t appear to have been deleted. */\n\t file_offset saved_p_base = p_base;\n\t lin saved_p_bline = p_bline;\n\t Fseek (pfp, previous_line, SEEK_SET);\n\t p_input_line -= 2;\n\t if (another_hunk (retval, false)\n\t\t && ! p_repl_lines && p_newfirst == 1)\n\t\tp_says_nonexistent[NEW] = 1 + ! p_timestamp[NEW].tv_sec;\n\t next_intuit_at (saved_p_base, saved_p_bline);\n\t }\n\n\t if (! ((p_name[OLD] || ! p_timestamp[OLD].tv_sec)\n\t\t && (p_name[NEW] || ! p_timestamp[NEW].tv_sec))\n\t\t&& ! p_name[INDEX] && need_header)\n\t {\n\t\tchar numbuf[LINENUM_LENGTH_BOUND + 1];\n\t\tsay (\"missing header for context diff at line %s of patch\\n\",\n\t\t format_linenum (numbuf, p_sline));\n\t }\n\t goto scan_exit;\n\t}\n\tif ((diff_type == NO_DIFF || diff_type == NORMAL_DIFF) &&\n\t last_line_was_command &&\n\t (strnEQ(s, \"< \", 2) || strnEQ(s, \"> \", 2)) ) {\n\t p_start = previous_line;\n\t p_sline = p_input_line - 1;\n\t p_indent = indent;\n\t retval = NORMAL_DIFF;\n\t goto scan_exit;\n\t}\n }\n\n scan_exit:\n\n /* The old, new, or old and new file types may be defined. When both\n file types are defined, make sure they are the same, or else assume\n we do not know the file type. */\n file_type = p_mode[OLD] & S_IFMT;\n if (file_type)\n {\n\tmode_t new_file_type = p_mode[NEW] & S_IFMT;\n\tif (new_file_type && file_type != new_file_type)\n\t file_type = 0;\n }\n else\n {\n\tfile_type = p_mode[NEW] & S_IFMT;\n\tif (! file_type)\n\t file_type = S_IFREG;\n }\n *p_file_type = file_type;\n\n /* To intuit 'inname', the name of the file to patch,\n use the algorithm specified by POSIX 1003.1-2001 XCU lines 25680-26599\n (with some modifications if posixly_correct is zero):\n\n - Take the old and new names from the context header if present,\n\t and take the index name from the 'Index:' line if present and\n\t if either the old and new names are both absent\n\t or posixly_correct is nonzero.\n\t Consider the file names to be in the order (old, new, index).\n - If some named files exist, use the first one if posixly_correct\n\t is nonzero, the best one otherwise.\n - If patch_get is nonzero, and no named files exist,\n\t but an RCS or SCCS master file exists,\n\t use the first named file with an RCS or SCCS master.\n - If no named files exist, no RCS or SCCS master was found,\n\t some names are given, posixly_correct is zero,\n\t and the patch appears to create a file, then use the best name\n\t requiring the creation of the fewest directories.\n - Otherwise, report failure by setting 'inname' to 0;\n\t this causes our invoker to ask the user for a file name. */\n\n i = NONE;\n\n if (!inname)\n {\n\tenum nametype i0 = NONE;\n\n\tif (! posixly_correct && (p_name[OLD] || p_name[NEW]) && p_name[INDEX])\n\t {\n\t free (p_name[INDEX]);\n\t p_name[INDEX] = 0;\n\t }\n\n\tfor (i = OLD; i <= INDEX; i++)\n\t if (p_name[i])\n\t {\n\t if (i0 != NONE && strcmp (p_name[i0], p_name[i]) == 0)\n\t\t{\n\t\t /* It's the same name as before; reuse stat results. */\n\t\t stat_errno[i] = stat_errno[i0];\n\t\t if (! stat_errno[i])\n\t\t st[i] = st[i0];\n\t\t}\n\t else\n\t\t{\n\t\t stat_errno[i] = stat_file (p_name[i], &st[i]);\n\t\t if (! stat_errno[i])\n\t\t {\n\t\t if (lookup_file_id (&st[i]) == DELETE_LATER)\n\t\t\tstat_errno[i] = ENOENT;\n\t\t else if (posixly_correct && name_is_valid (p_name[i]))\n\t\t\tbreak;\n\t\t }\n\t\t}\n\t i0 = i;\n\t }\n\n\tif (! posixly_correct)\n\t {\n\t /* The best of all existing files. */\n\t i = best_name (p_name, stat_errno);\n\n\t if (i == NONE && patch_get)\n\t {\n\t\tenum nametype nope = NONE;\n\n\t\tfor (i = OLD; i <= INDEX; i++)\n\t\t if (p_name[i])\n\t\t {\n\t\t char const *cs;\n\t\t char *getbuf;\n\t\t char *diffbuf;\n\t\t bool readonly = (outfile\n\t\t\t\t && strcmp (outfile, p_name[i]) != 0);\n\n\t\t if (nope == NONE || strcmp (p_name[nope], p_name[i]) != 0)\n\t\t\t{\n\t\t\t cs = (version_controller\n\t\t\t (p_name[i], readonly, (struct stat *) 0,\n\t\t\t\t &getbuf, &diffbuf));\n\t\t\t version_controlled[i] = !! cs;\n\t\t\t if (cs)\n\t\t\t {\n\t\t\t if (version_get (p_name[i], cs, false, readonly,\n\t\t\t\t\t getbuf, &st[i]))\n\t\t\t\tstat_errno[i] = 0;\n\t\t\t else\n\t\t\t\tversion_controlled[i] = 0;\n\n\t\t\t free (getbuf);\n\t\t\t free (diffbuf);\n\n\t\t\t if (! stat_errno[i])\n\t\t\t\tbreak;\n\t\t\t }\n\t\t\t}\n\n\t\t nope = i;\n\t\t }\n\t }\n\n\t if (i0 != NONE\n\t\t&& (i == NONE || (st[i].st_mode & S_IFMT) == file_type)\n\t\t&& maybe_reverse (p_name[i == NONE ? i0 : i], i == NONE,\n\t\t\t\t i == NONE || st[i].st_size == 0)\n\t\t&& i == NONE)\n\t i = i0;\n\n\t if (i == NONE && p_says_nonexistent[reverse])\n\t {\n\t\tint newdirs[3];\n\t\tint newdirs_min = INT_MAX;\n\t\tint distance_from_minimum[3];\n\n\t\tfor (i = OLD; i <= INDEX; i++)\n\t\t if (p_name[i])\n\t\t {\n\t\t newdirs[i] = (prefix_components (p_name[i], false)\n\t\t\t\t - prefix_components (p_name[i], true));\n\t\t if (newdirs[i] < newdirs_min)\n\t\t\tnewdirs_min = newdirs[i];\n\t\t }\n\n\t\tfor (i = OLD; i <= INDEX; i++)\n\t\t if (p_name[i])\n\t\t distance_from_minimum[i] = newdirs[i] - newdirs_min;\n\n\t\t/* The best of the filenames which create the fewest directories. */\n\t\ti = best_name (p_name, distance_from_minimum);\n\t }\n\t }\n }\n\n if ((pch_rename () || pch_copy ())\n\t&& ! inname\n\t&& ! ((i == OLD || i == NEW) &&\n\t p_name[! reverse] &&\n\t name_is_valid (p_name[! reverse])))\n {\n\tsay (\"Cannot %s file without two valid file names\\n\", pch_rename () ? \"rename\" : \"copy\");\n\tskip_rest_of_patch = true;\n }\n\n if (i == NONE)\n {\n\tif (inname)\n\t {\n\t inerrno = stat_file (inname, &instat);\n\t if (inerrno || (instat.st_mode & S_IFMT) == file_type)\n\t maybe_reverse (inname, inerrno, inerrno || instat.st_size == 0);\n\t }\n\telse\n inerrno = -1;\n }\n else\n {\n\tinname = xstrdup (p_name[i]);\n\tinerrno = stat_errno[i];\n\tinvc = version_controlled[i];\n\tinstat = st[i];\n }\n\n return retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix segfault with mangled rename patch\n\nhttp://savannah.gnu.org/bugs/?53132\n* src/pch.c (intuit_diff_type): Ensure that two filenames are specified\nfor renames and copies (fix the existing 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: check_owner_password_V4(std::string& user_password,\n std::string const& owner_password,\n QPDF::EncryptionData const& data)\n{\n // Algorithm 3.7 from the PDF 1.7 Reference Manual\n\n unsigned char key[OU_key_bytes_V4];\n compute_O_rc4_key(user_password, owner_password, data, key);\n unsigned char O_data[key_bytes];\n memcpy(O_data, QUtil::unsigned_char_pointer(data.getO()), key_bytes);\n iterate_rc4(O_data, key_bytes, key, data.getLengthBytes(),\n (data.getR() >= 3) ? 20 : 1, true);\n std::string new_user_password =\n std::string(reinterpret_cast(O_data), key_bytes);\n bool result = false;\n if (check_user_password(new_user_password, data))\n {\n result = true;\n user_password = new_user_password;\n }\n return result;\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: static void parse_version(std::string const& full_version_string,\n std::string& version, int& extension_level)\n{\n PointerHolder vp(true, QUtil::copy_string(full_version_string));\n char* v = vp.getPointer();\n char* p1 = strchr(v, '.');\n char* p2 = (p1 ? strchr(1 + p1, '.') : 0);\n if (p2 && *(p2 + 1))\n {\n *p2++ = '\\0';\n extension_level = atoi(p2);\n }\n version = v;\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: gplotAddPlot(GPLOT *gplot,\n NUMA *nax,\n NUMA *nay,\n l_int32 plotstyle,\n const char *plottitle)\n{\nchar buf[L_BUF_SIZE];\nchar emptystring[] = \"\";\nchar *datastr, *title;\nl_int32 n, i;\nl_float32 valx, valy, startx, delx;\nSARRAY *sa;\n\n PROCNAME(\"gplotAddPlot\");\n\n if (!gplot)\n return ERROR_INT(\"gplot not defined\", procName, 1);\n if (!nay)\n return ERROR_INT(\"nay not defined\", procName, 1);\n if (plotstyle < 0 || plotstyle >= NUM_GPLOT_STYLES)\n return ERROR_INT(\"invalid plotstyle\", procName, 1);\n\n if ((n = numaGetCount(nay)) == 0)\n return ERROR_INT(\"no points to plot\", procName, 1);\n if (nax && (n != numaGetCount(nax)))\n return ERROR_INT(\"nax and nay sizes differ\", procName, 1);\n if (n == 1 && plotstyle == GPLOT_LINES) {\n L_INFO(\"only 1 pt; changing style to points\\n\", procName);\n plotstyle = GPLOT_POINTS;\n }\n\n /* Save plotstyle and plottitle */\n numaGetParameters(nay, &startx, &delx);\n numaAddNumber(gplot->plotstyles, plotstyle);\n if (plottitle) {\n title = stringNew(plottitle);\n sarrayAddString(gplot->plottitles, title, L_INSERT);\n } else {\n sarrayAddString(gplot->plottitles, emptystring, L_COPY);\n }\n\n /* Generate and save data filename */\n gplot->nplots++;\n snprintf(buf, L_BUF_SIZE, \"%s.data.%d\", gplot->rootname, gplot->nplots);\n sarrayAddString(gplot->datanames, buf, L_COPY);\n\n /* Generate data and save as a string */\n sa = sarrayCreate(n);\n for (i = 0; i < n; i++) {\n if (nax)\n numaGetFValue(nax, i, &valx);\n else\n valx = startx + i * delx;\n numaGetFValue(nay, i, &valy);\n snprintf(buf, L_BUF_SIZE, \"%f %f\\n\", valx, valy);\n sarrayAddString(sa, buf, L_COPY);\n }\n datastr = sarrayToString(sa, 0);\n sarrayAddString(gplot->plotdata, datastr, L_INSERT);\n sarrayDestroy(&sa);\n\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 sig_chatnet_read(IRC_CHATNET_REC *rec, CONFIG_NODE *node)\n{\n\tif (!IS_IRC_CHATNET(rec))\n\t\treturn;\n\n\trec->usermode = g_strdup(config_node_get_str(node, \"usermode\", NULL));\n\n\trec->max_cmds_at_once = config_node_get_int(node, \"cmdmax\", 0);\n\trec->cmd_queue_speed = config_node_get_int(node, \"cmdspeed\", 0);\n\trec->max_query_chans = config_node_get_int(node, \"max_query_chans\", 0);\n\n\trec->max_kicks = config_node_get_int(node, \"max_kicks\", 0);\n\trec->max_msgs = config_node_get_int(node, \"max_msgs\", 0);\n\trec->max_modes = config_node_get_int(node, \"max_modes\", 0);\n\trec->max_whois = config_node_get_int(node, \"max_whois\", 0);\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_success(IRC_SERVER_REC *server, const char *data, const char *from)\n{\n\tif (server->sasl_timeout != 0) {\n\t\tg_source_remove(server->sasl_timeout);\n\t\tserver->sasl_timeout = 0;\n\t}\n\n\tserver->sasl_success = TRUE;\n\n\tsignal_emit(\"server sasl success\", 1, server);\n\n\t/* The authentication succeeded, time to finish the CAP negotiation */\n\tcap_finish_negotiation(server);\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: valid_host(cupsd_client_t *con)\t\t/* I - Client connection */\n{\n cupsd_alias_t\t*a;\t\t\t/* Current alias */\n cupsd_netif_t\t*netif;\t\t\t/* Current network interface */\n const char\t*end;\t\t\t/* End character */\n char\t\t*ptr;\t\t\t/* Pointer into host value */\n\n\n /*\n * Copy the Host: header for later use...\n */\n\n strlcpy(con->clientname, httpGetField(con->http, HTTP_FIELD_HOST),\n sizeof(con->clientname));\n if ((ptr = strrchr(con->clientname, ':')) != NULL && !strchr(ptr, ']'))\n {\n *ptr++ = '\\0';\n con->clientport = atoi(ptr);\n }\n else\n con->clientport = con->serverport;\n\n /*\n * Then validate...\n */\n\n if (httpAddrLocalhost(httpGetAddress(con->http)))\n {\n /*\n * Only allow \"localhost\" or the equivalent IPv4 or IPv6 numerical\n * addresses when accessing CUPS via the loopback interface...\n */\n\n return (!_cups_strcasecmp(con->clientname, \"localhost\") ||\n\t !_cups_strcasecmp(con->clientname, \"localhost.\") ||\n#ifdef __linux\n\t !_cups_strcasecmp(con->clientname, \"localhost.localdomain\") ||\n#endif /* __linux */\n !strcmp(con->clientname, \"127.0.0.1\") ||\n\t !strcmp(con->clientname, \"[::1]\"));\n }\n\n#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)\n /*\n * Check if the hostname is something.local (Bonjour); if so, allow it.\n */\n\n if ((end = strrchr(con->clientname, '.')) != NULL && end > con->clientname &&\n !end[1])\n {\n /*\n * \".\" on end, work back to second-to-last \".\"...\n */\n\n for (end --; end > con->clientname && *end != '.'; end --);\n }\n\n if (end && (!_cups_strcasecmp(end, \".local\") ||\n\t !_cups_strcasecmp(end, \".local.\")))\n return (1);\n#endif /* HAVE_DNSSD || HAVE_AVAHI */\n\n /*\n * Check if the hostname is an IP address...\n */\n\n if (isdigit(con->clientname[0] & 255) || con->clientname[0] == '[')\n {\n /*\n * Possible IPv4/IPv6 address...\n */\n\n http_addrlist_t *addrlist;\t\t/* List of addresses */\n\n\n if ((addrlist = httpAddrGetList(con->clientname, AF_UNSPEC, NULL)) != NULL)\n {\n /*\n * Good IPv4/IPv6 address...\n */\n\n httpAddrFreeList(addrlist);\n return (1);\n }\n }\n\n /*\n * Check for (alias) name matches...\n */\n\n for (a = (cupsd_alias_t *)cupsArrayFirst(ServerAlias);\n a;\n a = (cupsd_alias_t *)cupsArrayNext(ServerAlias))\n {\n /*\n * \"ServerAlias *\" allows all host values through...\n */\n\n if (!strcmp(a->name, \"*\"))\n return (1);\n\n if (!_cups_strncasecmp(con->clientname, a->name, a->namelen))\n {\n /*\n * Prefix matches; check the character at the end - it must be \".\" or nul.\n */\n\n end = con->clientname + a->namelen;\n\n if (!*end || (*end == '.' && !end[1]))\n return (1);\n }\n }\n\n#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)\n for (a = (cupsd_alias_t *)cupsArrayFirst(DNSSDAlias);\n a;\n a = (cupsd_alias_t *)cupsArrayNext(DNSSDAlias))\n {\n /*\n * \"ServerAlias *\" allows all host values through...\n */\n\n if (!strcmp(a->name, \"*\"))\n return (1);\n\n if (!_cups_strncasecmp(con->clientname, a->name, a->namelen))\n {\n /*\n * Prefix matches; check the character at the end - it must be \".\" or nul.\n */\n\n end = con->clientname + a->namelen;\n\n if (!*end || (*end == '.' && !end[1]))\n return (1);\n }\n }\n#endif /* HAVE_DNSSD || HAVE_AVAHI */\n\n /*\n * Check for interface hostname matches...\n */\n\n for (netif = (cupsd_netif_t *)cupsArrayFirst(NetIFList);\n netif;\n netif = (cupsd_netif_t *)cupsArrayNext(NetIFList))\n {\n if (!_cups_strncasecmp(con->clientname, netif->hostname, netif->hostlen))\n {\n /*\n * Prefix matches; check the character at the end - it must be \".\" or nul.\n */\n\n end = con->clientname + netif->hostlen;\n\n if (!*end || (*end == '.' && !end[1]))\n return (1);\n }\n }\n\n return (0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-290'], 'message': 'Don't treat \"localhost.localdomain\" as an allowed replacement for localhost, since it isn'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: static int get_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\tunsigned int n;\n\tcompat_caddr_t p;\n\n\tif (!access_ok(VERIFY_READ, up, sizeof(*up)) ||\n\t get_user(kp->which, &up->which) ||\n\t get_user(kp->count, &up->count) ||\n\t get_user(kp->error_idx, &up->error_idx) ||\n\t copy_from_user(kp->reserved, up->reserved, sizeof(kp->reserved)))\n\t\treturn -EFAULT;\n\tif (kp->count == 0) {\n\t\tkp->controls = NULL;\n\t\treturn 0;\n\t} else if (kp->count > V4L2_CID_MAX_CTRLS) {\n\t\treturn -EINVAL;\n\t}\n\tif (get_user(p, &up->controls))\n\t\treturn -EFAULT;\n\tucontrols = compat_ptr(p);\n\tif (!access_ok(VERIFY_READ, ucontrols, kp->count * sizeof(*ucontrols)))\n\t\treturn -EFAULT;\n\tkcontrols = compat_alloc_user_space(kp->count * sizeof(*kcontrols));\n\tkp->controls = (__force struct v4l2_ext_control *)kcontrols;\n\tfor (n = 0; n < kp->count; n++) {\n\t\tu32 id;\n\n\t\tif (copy_in_user(kcontrols, ucontrols, sizeof(*ucontrols)))\n\t\t\treturn -EFAULT;\n\t\tif (get_user(id, &kcontrols->id))\n\t\t\treturn -EFAULT;\n\t\tif (ctrl_is_pointer(file, id)) {\n\t\t\tvoid __user *s;\n\n\t\t\tif (get_user(p, &ucontrols->string))\n\t\t\t\treturn -EFAULT;\n\t\t\ts = compat_ptr(p);\n\t\t\tif (put_user(s, &kcontrols->string))\n\t\t\t\treturn -EFAULT;\n\t\t}\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_buffer32(struct v4l2_buffer *kp, struct v4l2_buffer32 __user *up)\n{\n\tstruct v4l2_plane32 __user *uplane32;\n\tstruct v4l2_plane __user *uplane;\n\tcompat_caddr_t p;\n\tint ret;\n\n\tif (!access_ok(VERIFY_READ, up, sizeof(*up)) ||\n\t get_user(kp->index, &up->index) ||\n\t get_user(kp->type, &up->type) ||\n\t get_user(kp->flags, &up->flags) ||\n\t get_user(kp->memory, &up->memory) ||\n\t get_user(kp->length, &up->length))\n\t\treturn -EFAULT;\n\n\tif (V4L2_TYPE_IS_OUTPUT(kp->type))\n\t\tif (get_user(kp->bytesused, &up->bytesused) ||\n\t\t get_user(kp->field, &up->field) ||\n\t\t get_user(kp->timestamp.tv_sec, &up->timestamp.tv_sec) ||\n\t\t get_user(kp->timestamp.tv_usec, &up->timestamp.tv_usec))\n\t\t\treturn -EFAULT;\n\n\tif (V4L2_TYPE_IS_MULTIPLANAR(kp->type)) {\n\t\tunsigned int num_planes;\n\n\t\tif (kp->length == 0) {\n\t\t\tkp->m.planes = NULL;\n\t\t\t/* num_planes == 0 is legal, e.g. when userspace doesn't\n\t\t\t * need planes array on DQBUF*/\n\t\t\treturn 0;\n\t\t} else if (kp->length > VIDEO_MAX_PLANES) {\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tif (get_user(p, &up->m.planes))\n\t\t\treturn -EFAULT;\n\n\t\tuplane32 = compat_ptr(p);\n\t\tif (!access_ok(VERIFY_READ, uplane32,\n\t\t\t kp->length * sizeof(*uplane32)))\n\t\t\treturn -EFAULT;\n\n\t\t/* We don't really care if userspace decides to kill itself\n\t\t * by passing a very big num_planes value */\n\t\tuplane = compat_alloc_user_space(kp->length * sizeof(*uplane));\n\t\tkp->m.planes = (__force struct v4l2_plane *)uplane;\n\n\t\tfor (num_planes = 0; num_planes < kp->length; num_planes++) {\n\t\t\tret = get_v4l2_plane32(uplane, uplane32, kp->memory);\n\t\t\tif (ret)\n\t\t\t\treturn ret;\n\t\t\t++uplane;\n\t\t\t++uplane32;\n\t\t}\n\t} else {\n\t\tswitch (kp->memory) {\n\t\tcase V4L2_MEMORY_MMAP:\n\t\tcase V4L2_MEMORY_OVERLAY:\n\t\t\tif (get_user(kp->m.offset, &up->m.offset))\n\t\t\t\treturn -EFAULT;\n\t\t\tbreak;\n\t\tcase V4L2_MEMORY_USERPTR:\n\t\t\t{\n\t\t\t\tcompat_long_t tmp;\n\n\t\t\t\tif (get_user(tmp, &up->m.userptr))\n\t\t\t\t\treturn -EFAULT;\n\n\t\t\t\tkp->m.userptr = (unsigned long)compat_ptr(tmp);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase V4L2_MEMORY_DMABUF:\n\t\t\tif (get_user(kp->m.fd, &up->m.fd))\n\t\t\t\treturn -EFAULT;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': '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_create32(struct v4l2_create_buffers *kp, struct v4l2_create_buffers32 __user *up)\n{\n\tif (!access_ok(VERIFY_READ, up, sizeof(*up)) ||\n\t copy_from_user(kp, up, offsetof(struct v4l2_create_buffers32, format)))\n\t\treturn -EFAULT;\n\treturn __get_v4l2_format32(&kp->format, &up->format);\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 blkcg_init_queue(struct request_queue *q)\n{\n\tstruct blkcg_gq *new_blkg, *blkg;\n\tbool preloaded;\n\tint ret;\n\n\tnew_blkg = blkg_alloc(&blkcg_root, q, GFP_KERNEL);\n\tif (!new_blkg)\n\t\treturn -ENOMEM;\n\n\tpreloaded = !radix_tree_preload(GFP_KERNEL);\n\n\t/*\n\t * Make sure the root blkg exists and count the existing blkgs. As\n\t * @q is bypassing at this point, blkg_lookup_create() can't be\n\t * used. Open code insertion.\n\t */\n\trcu_read_lock();\n\tspin_lock_irq(q->queue_lock);\n\tblkg = blkg_create(&blkcg_root, q, new_blkg);\n\tspin_unlock_irq(q->queue_lock);\n\trcu_read_unlock();\n\n\tif (preloaded)\n\t\tradix_tree_preload_end();\n\n\tif (IS_ERR(blkg)) {\n\t\tblkg_free(new_blkg);\n\t\treturn PTR_ERR(blkg);\n\t}\n\n\tq->root_blkg = blkg;\n\tq->root_rl.blkg = blkg;\n\n\tret = blk_throtl_init(q);\n\tif (ret) {\n\t\tspin_lock_irq(q->queue_lock);\n\t\tblkg_destroy_all(q);\n\t\tspin_unlock_irq(q->queue_lock);\n\t}\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'blkcg: fix double free of new_blkg in blkcg_init_queue\n\nIf blkg_create fails, new_blkg passed as an argument will\nbe freed by blkg_create, so there is no need to free it again.\n\nSigned-off-by: Hou Tao \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: php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper, \n\t\tconst char *path, const char *mode, int options, char **opened_path, \n\t\tphp_stream_context *context, int redirect_max, int flags STREAMS_DC TSRMLS_DC) /* {{{ */\n{\n\tphp_stream *stream = NULL;\n\tphp_url *resource = NULL;\n\tint use_ssl;\n\tint use_proxy = 0;\n\tchar *scratch = NULL;\n\tchar *tmp = NULL;\n\tchar *ua_str = NULL;\n\tzval **ua_zval = NULL, **tmpzval = NULL, *ssl_proxy_peer_name = NULL;\n\tint scratch_len = 0;\n\tint body = 0;\n\tchar location[HTTP_HEADER_BLOCK_SIZE];\n\tzval *response_header = NULL;\n\tint reqok = 0;\n\tchar *http_header_line = NULL;\n\tchar tmp_line[128];\n\tsize_t chunk_size = 0, file_size = 0;\n\tint eol_detect = 0;\n\tchar *transport_string, *errstr = NULL;\n\tint transport_len, have_header = 0, request_fulluri = 0, ignore_errors = 0;\n\tchar *protocol_version = NULL;\n\tint protocol_version_len = 3; /* Default: \"1.0\" */\n\tstruct timeval timeout;\n\tchar *user_headers = NULL;\n\tint header_init = ((flags & HTTP_WRAPPER_HEADER_INIT) != 0);\n\tint redirected = ((flags & HTTP_WRAPPER_REDIRECTED) != 0);\n\tint follow_location = 1;\n\tphp_stream_filter *transfer_encoding = NULL;\n\tint response_code;\n\n\ttmp_line[0] = '\\0';\n\n\tif (redirect_max < 1) {\n\t\tphp_stream_wrapper_log_error(wrapper, options TSRMLS_CC, \"Redirection limit reached, aborting\");\n\t\treturn NULL;\n\t}\n\n\tresource = php_url_parse(path);\n\tif (resource == NULL) {\n\t\treturn NULL;\n\t}\n\n\tif (strncasecmp(resource->scheme, \"http\", sizeof(\"http\")) && strncasecmp(resource->scheme, \"https\", sizeof(\"https\"))) {\n\t\tif (!context ||\n\t\t\tphp_stream_context_get_option(context, wrapper->wops->label, \"proxy\", &tmpzval) == FAILURE ||\n\t\t\tZ_TYPE_PP(tmpzval) != IS_STRING ||\n\t\t\tZ_STRLEN_PP(tmpzval) <= 0) {\n\t\t\tphp_url_free(resource);\n\t\t\treturn php_stream_open_wrapper_ex(path, mode, REPORT_ERRORS, NULL, context);\n\t\t}\n\t\t/* Called from a non-http wrapper with http proxying requested (i.e. ftp) */\n\t\trequest_fulluri = 1;\n\t\tuse_ssl = 0;\n\t\tuse_proxy = 1;\n\n\t\ttransport_len = Z_STRLEN_PP(tmpzval);\n\t\ttransport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval));\n\t} else {\n\t\t/* Normal http request (possibly with proxy) */\n\n\t\tif (strpbrk(mode, \"awx+\")) {\n\t\t\tphp_stream_wrapper_log_error(wrapper, options TSRMLS_CC, \"HTTP wrapper does not support writeable connections\");\n\t\t\tphp_url_free(resource);\n\t\t\treturn NULL;\n\t\t}\n\n\t\tuse_ssl = resource->scheme && (strlen(resource->scheme) > 4) && resource->scheme[4] == 's';\n\t\t/* choose default ports */\n\t\tif (use_ssl && resource->port == 0)\n\t\t\tresource->port = 443;\n\t\telse if (resource->port == 0)\n\t\t\tresource->port = 80;\n\n\t\tif (context &&\n\t\t\tphp_stream_context_get_option(context, wrapper->wops->label, \"proxy\", &tmpzval) == SUCCESS &&\n\t\t\tZ_TYPE_PP(tmpzval) == IS_STRING &&\n\t\t\tZ_STRLEN_PP(tmpzval) > 0) {\n\t\t\tuse_proxy = 1;\n\t\t\ttransport_len = Z_STRLEN_PP(tmpzval);\n\t\t\ttransport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval));\n\t\t} else {\n\t\t\ttransport_len = spprintf(&transport_string, 0, \"%s://%s:%d\", use_ssl ? \"ssl\" : \"tcp\", resource->host, resource->port);\n\t\t}\n\t}\n\n\tif (context && php_stream_context_get_option(context, wrapper->wops->label, \"timeout\", &tmpzval) == SUCCESS) {\n\t\tSEPARATE_ZVAL(tmpzval);\n\t\tconvert_to_double_ex(tmpzval);\n\t\ttimeout.tv_sec = (time_t) Z_DVAL_PP(tmpzval);\n\t\ttimeout.tv_usec = (size_t) ((Z_DVAL_PP(tmpzval) - timeout.tv_sec) * 1000000);\n\t} else {\n\t\ttimeout.tv_sec = FG(default_socket_timeout);\n\t\ttimeout.tv_usec = 0;\n\t}\n\n\tstream = php_stream_xport_create(transport_string, transport_len, options,\n\t\t\tSTREAM_XPORT_CLIENT | STREAM_XPORT_CONNECT,\n\t\t\tNULL, &timeout, context, &errstr, NULL);\n\n\tif (stream) {\n\t\tphp_stream_set_option(stream, PHP_STREAM_OPTION_READ_TIMEOUT, 0, &timeout);\n\t}\n\n\tif (errstr) {\n\t\tphp_stream_wrapper_log_error(wrapper, options TSRMLS_CC, \"%s\", errstr);\n\t\tefree(errstr);\n\t\terrstr = NULL;\n\t}\n\n\tefree(transport_string);\n\n\tif (stream && use_proxy && use_ssl) {\n\t\tsmart_str header = {0};\n\n\t\t/* Set peer_name or name verification will try to use the proxy server name */\n\t\tif (!context || php_stream_context_get_option(context, \"ssl\", \"peer_name\", &tmpzval) == FAILURE) {\n\t\t\tMAKE_STD_ZVAL(ssl_proxy_peer_name);\n\t\t\tZVAL_STRING(ssl_proxy_peer_name, resource->host, 1);\n\t\t\tphp_stream_context_set_option(stream->context, \"ssl\", \"peer_name\", ssl_proxy_peer_name);\n\t\t}\n\n\t\tsmart_str_appendl(&header, \"CONNECT \", sizeof(\"CONNECT \")-1);\n\t\tsmart_str_appends(&header, resource->host);\n\t\tsmart_str_appendc(&header, ':');\n\t\tsmart_str_append_unsigned(&header, resource->port);\n\t\tsmart_str_appendl(&header, \" HTTP/1.0\\r\\n\", sizeof(\" HTTP/1.0\\r\\n\")-1);\n\n\t /* check if we have Proxy-Authorization header */\n\t\tif (context && php_stream_context_get_option(context, \"http\", \"header\", &tmpzval) == SUCCESS) {\n\t\t\tchar *s, *p;\n\n\t\t\tif (Z_TYPE_PP(tmpzval) == IS_ARRAY) {\n\t\t\t\tHashPosition pos;\n\t\t\t\tzval **tmpheader = NULL;\n\n\t\t\t\tfor (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(tmpzval), &pos);\n\t\t\t\t\tSUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(tmpzval), (void *)&tmpheader, &pos);\n\t\t\t\t\tzend_hash_move_forward_ex(Z_ARRVAL_PP(tmpzval), &pos)) {\n\t\t\t\t\tif (Z_TYPE_PP(tmpheader) == IS_STRING) {\n\t\t\t\t\t\ts = Z_STRVAL_PP(tmpheader);\n\t\t\t\t\t\tdo {\n\t\t\t\t\t\t\twhile (*s == ' ' || *s == '\\t') s++;\n\t\t\t\t\t\t\tp = s;\n\t\t\t\t\t\t\twhile (*p != 0 && *p != ':' && *p != '\\r' && *p !='\\n') p++;\n\t\t\t\t\t\t\tif (*p == ':') {\n\t\t\t\t\t\t\t\tp++;\n\t\t\t\t\t\t\t\tif (p - s == sizeof(\"Proxy-Authorization:\") - 1 &&\n\t\t\t\t\t\t\t\t zend_binary_strcasecmp(s, sizeof(\"Proxy-Authorization:\") - 1,\n\t\t\t\t\t\t\t\t \"Proxy-Authorization:\", sizeof(\"Proxy-Authorization:\") - 1) == 0) {\n\t\t\t\t\t\t\t\t\twhile (*p != 0 && *p != '\\r' && *p !='\\n') p++;\n\t\t\t\t\t\t\t\t\tsmart_str_appendl(&header, s, p - s);\n\t\t\t\t\t\t\t\t\tsmart_str_appendl(&header, \"\\r\\n\", sizeof(\"\\r\\n\")-1);\n\t\t\t\t\t\t\t\t\tgoto finish;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\twhile (*p != 0 && *p != '\\r' && *p !='\\n') p++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ts = p;\n\t\t\t\t\t\t\twhile (*s == '\\r' || *s == '\\n') s++;\n\t\t\t\t\t\t} while (*s != 0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval)) {\n\t\t\t\ts = Z_STRVAL_PP(tmpzval);\n\t\t\t\tdo {\n\t\t\t\t\twhile (*s == ' ' || *s == '\\t') s++;\n\t\t\t\t\tp = s;\n\t\t\t\t\twhile (*p != 0 && *p != ':' && *p != '\\r' && *p !='\\n') p++;\n\t\t\t\t\tif (*p == ':') {\n\t\t\t\t\t\tp++;\n\t\t\t\t\t\tif (p - s == sizeof(\"Proxy-Authorization:\") - 1 &&\n\t\t\t\t\t\t zend_binary_strcasecmp(s, sizeof(\"Proxy-Authorization:\") - 1,\n\t\t\t\t\t\t \"Proxy-Authorization:\", sizeof(\"Proxy-Authorization:\") - 1) == 0) {\n\t\t\t\t\t\t\twhile (*p != 0 && *p != '\\r' && *p !='\\n') p++;\n\t\t\t\t\t\t\tsmart_str_appendl(&header, s, p - s);\n\t\t\t\t\t\t\tsmart_str_appendl(&header, \"\\r\\n\", sizeof(\"\\r\\n\")-1);\n\t\t\t\t\t\t\tgoto finish;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\twhile (*p != 0 && *p != '\\r' && *p !='\\n') p++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ts = p;\n\t\t\t\t\twhile (*s == '\\r' || *s == '\\n') s++;\n\t\t\t\t} while (*s != 0);\n\t\t\t}\n\t\t}\nfinish:\n\t\tsmart_str_appendl(&header, \"\\r\\n\", sizeof(\"\\r\\n\")-1);\n\n\t\tif (php_stream_write(stream, header.c, header.len) != header.len) {\n\t\t\tphp_stream_wrapper_log_error(wrapper, options TSRMLS_CC, \"Cannot connect to HTTPS server through proxy\");\n\t\t\tphp_stream_close(stream);\n\t\t\tstream = NULL;\n\t\t}\n \t \tsmart_str_free(&header);\n\n \t \tif (stream) {\n \t \t\tchar header_line[HTTP_HEADER_BLOCK_SIZE];\n\n\t\t\t/* get response header */\n\t\t\twhile (php_stream_gets(stream, header_line, HTTP_HEADER_BLOCK_SIZE-1) != NULL) {\n\t\t\t\tif (header_line[0] == '\\n' ||\n\t\t\t\t header_line[0] == '\\r' ||\n\t\t\t\t header_line[0] == '\\0') {\n\t\t\t\t break;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/* enable SSL transport layer */\n\t\tif (stream) {\n\t\t\tif (php_stream_xport_crypto_setup(stream, STREAM_CRYPTO_METHOD_SSLv23_CLIENT, NULL TSRMLS_CC) < 0 ||\n\t\t\t php_stream_xport_crypto_enable(stream, 1 TSRMLS_CC) < 0) {\n\t\t\t\tphp_stream_wrapper_log_error(wrapper, options TSRMLS_CC, \"Cannot connect to HTTPS server through proxy\");\n\t\t\t\tphp_stream_close(stream);\n\t\t\t\tstream = NULL;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (stream == NULL)\n\t\tgoto out;\n\n\t/* avoid buffering issues while reading header */\n\tif (options & STREAM_WILL_CAST)\n\t\tchunk_size = php_stream_set_chunk_size(stream, 1);\n\n\t/* avoid problems with auto-detecting when reading the headers -> the headers\n\t * are always in canonical \\r\\n format */\n\teol_detect = stream->flags & (PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC);\n\tstream->flags &= ~(PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC);\n\n\tphp_stream_context_set(stream, context);\n\n\tphp_stream_notify_info(context, PHP_STREAM_NOTIFY_CONNECT, NULL, 0);\n\n\tif (header_init && context && php_stream_context_get_option(context, \"http\", \"max_redirects\", &tmpzval) == SUCCESS) {\n\t\tSEPARATE_ZVAL(tmpzval);\n\t\tconvert_to_long_ex(tmpzval);\n\t\tredirect_max = Z_LVAL_PP(tmpzval);\n\t}\n\n\tif (context && php_stream_context_get_option(context, \"http\", \"method\", &tmpzval) == SUCCESS) {\n\t\tif (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) {\n\t\t\t/* As per the RFC, automatically redirected requests MUST NOT use other methods than\n\t\t\t * GET and HEAD unless it can be confirmed by the user */\n\t\t\tif (!redirected\n\t\t\t\t|| (Z_STRLEN_PP(tmpzval) == 3 && memcmp(\"GET\", Z_STRVAL_PP(tmpzval), 3) == 0)\n\t\t\t\t|| (Z_STRLEN_PP(tmpzval) == 4 && memcmp(\"HEAD\",Z_STRVAL_PP(tmpzval), 4) == 0)\n\t\t\t) {\n\t\t\t\tscratch_len = strlen(path) + 29 + Z_STRLEN_PP(tmpzval);\n\t\t\t\tscratch = emalloc(scratch_len);\n\t\t\t\tstrlcpy(scratch, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval) + 1);\n\t\t\t\tstrncat(scratch, \" \", 1);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (context && php_stream_context_get_option(context, \"http\", \"protocol_version\", &tmpzval) == SUCCESS) {\n\t\tSEPARATE_ZVAL(tmpzval);\n\t\tconvert_to_double_ex(tmpzval);\n\t\tprotocol_version_len = spprintf(&protocol_version, 0, \"%.1F\", Z_DVAL_PP(tmpzval));\n\t}\n\n\tif (!scratch) {\n\t\tscratch_len = strlen(path) + 29 + protocol_version_len;\n\t\tscratch = emalloc(scratch_len);\n\t\tstrncpy(scratch, \"GET \", scratch_len);\n\t}\n\n\t/* Should we send the entire path in the request line, default to no. */\n\tif (!request_fulluri &&\n\t\tcontext &&\n\t\tphp_stream_context_get_option(context, \"http\", \"request_fulluri\", &tmpzval) == SUCCESS) {\n\t\tzval ztmp = **tmpzval;\n\n\t\tzval_copy_ctor(&ztmp);\n\t\tconvert_to_boolean(&ztmp);\n\t\trequest_fulluri = Z_BVAL(ztmp) ? 1 : 0;\n\t\tzval_dtor(&ztmp);\n\t}\n\n\tif (request_fulluri) {\n\t\t/* Ask for everything */\n\t\tstrcat(scratch, path);\n\t} else {\n\t\t/* Send the traditional /path/to/file?query_string */\n\n\t\t/* file */\n\t\tif (resource->path && *resource->path) {\n\t\t\tstrlcat(scratch, resource->path, scratch_len);\n\t\t} else {\n\t\t\tstrlcat(scratch, \"/\", scratch_len);\n\t\t}\n\n\t\t/* query string */\n\t\tif (resource->query) {\n\t\t\tstrlcat(scratch, \"?\", scratch_len);\n\t\t\tstrlcat(scratch, resource->query, scratch_len);\n\t\t}\n\t}\n\n\t/* protocol version we are speaking */\n\tif (protocol_version) {\n\t\tstrlcat(scratch, \" HTTP/\", scratch_len);\n\t\tstrlcat(scratch, protocol_version, scratch_len);\n\t\tstrlcat(scratch, \"\\r\\n\", scratch_len);\n\t} else {\n\t\tstrlcat(scratch, \" HTTP/1.0\\r\\n\", scratch_len);\n\t}\n\n\t/* send it */\n\tphp_stream_write(stream, scratch, strlen(scratch));\n\n\tif (context && php_stream_context_get_option(context, \"http\", \"header\", &tmpzval) == SUCCESS) {\n\t\ttmp = NULL;\n\n\t\tif (Z_TYPE_PP(tmpzval) == IS_ARRAY) {\n\t\t\tHashPosition pos;\n\t\t\tzval **tmpheader = NULL;\n\t\t\tsmart_str tmpstr = {0};\n\n\t\t\tfor (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(tmpzval), &pos);\n\t\t\t\tSUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(tmpzval), (void *)&tmpheader, &pos);\n\t\t\t\tzend_hash_move_forward_ex(Z_ARRVAL_PP(tmpzval), &pos)\n\t\t\t) {\n\t\t\t\tif (Z_TYPE_PP(tmpheader) == IS_STRING) {\n\t\t\t\t\tsmart_str_appendl(&tmpstr, Z_STRVAL_PP(tmpheader), Z_STRLEN_PP(tmpheader));\n\t\t\t\t\tsmart_str_appendl(&tmpstr, \"\\r\\n\", sizeof(\"\\r\\n\") - 1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tsmart_str_0(&tmpstr);\n\t\t\t/* Remove newlines and spaces from start and end. there's at least one extra \\r\\n at the end that needs to go. */\n\t\t\tif (tmpstr.c) {\n\t\t\t\ttmp = php_trim(tmpstr.c, strlen(tmpstr.c), NULL, 0, NULL, 3 TSRMLS_CC);\n\t\t\t\tsmart_str_free(&tmpstr);\n\t\t\t}\n\t\t}\n\t\tif (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval)) {\n\t\t\t/* Remove newlines and spaces from start and end php_trim will estrndup() */\n\t\t\ttmp = php_trim(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval), NULL, 0, NULL, 3 TSRMLS_CC);\n\t\t}\n\t\tif (tmp && strlen(tmp) > 0) {\n\t\t\tchar *s;\n\n\t\t\tuser_headers = estrdup(tmp);\n\n\t\t\t/* Make lowercase for easy comparison against 'standard' headers */\n\t\t\tphp_strtolower(tmp, strlen(tmp));\n\n\t\t\tif (!header_init) {\n\t\t\t\t/* strip POST headers on redirect */\n\t\t\t\tstrip_header(user_headers, tmp, \"content-length:\");\n\t\t\t\tstrip_header(user_headers, tmp, \"content-type:\");\n\t\t\t}\n\n\t\t\tif ((s = strstr(tmp, \"user-agent:\")) &&\n\t\t\t (s == tmp || *(s-1) == '\\r' || *(s-1) == '\\n' ||\n\t\t\t *(s-1) == '\\t' || *(s-1) == ' ')) {\n\t\t\t\t have_header |= HTTP_HEADER_USER_AGENT;\n\t\t\t}\n\t\t\tif ((s = strstr(tmp, \"host:\")) &&\n\t\t\t (s == tmp || *(s-1) == '\\r' || *(s-1) == '\\n' ||\n\t\t\t *(s-1) == '\\t' || *(s-1) == ' ')) {\n\t\t\t\t have_header |= HTTP_HEADER_HOST;\n\t\t\t}\n\t\t\tif ((s = strstr(tmp, \"from:\")) &&\n\t\t\t (s == tmp || *(s-1) == '\\r' || *(s-1) == '\\n' ||\n\t\t\t *(s-1) == '\\t' || *(s-1) == ' ')) {\n\t\t\t\t have_header |= HTTP_HEADER_FROM;\n\t\t\t\t}\n\t\t\tif ((s = strstr(tmp, \"authorization:\")) &&\n\t\t\t (s == tmp || *(s-1) == '\\r' || *(s-1) == '\\n' ||\n\t\t\t *(s-1) == '\\t' || *(s-1) == ' ')) {\n\t\t\t\t have_header |= HTTP_HEADER_AUTH;\n\t\t\t}\n\t\t\tif ((s = strstr(tmp, \"content-length:\")) &&\n\t\t\t (s == tmp || *(s-1) == '\\r' || *(s-1) == '\\n' ||\n\t\t\t *(s-1) == '\\t' || *(s-1) == ' ')) {\n\t\t\t\t have_header |= HTTP_HEADER_CONTENT_LENGTH;\n\t\t\t}\n\t\t\tif ((s = strstr(tmp, \"content-type:\")) &&\n\t\t\t (s == tmp || *(s-1) == '\\r' || *(s-1) == '\\n' ||\n\t\t\t *(s-1) == '\\t' || *(s-1) == ' ')) {\n\t\t\t\t have_header |= HTTP_HEADER_TYPE;\n\t\t\t}\n\t\t\tif ((s = strstr(tmp, \"connection:\")) &&\n\t\t\t (s == tmp || *(s-1) == '\\r' || *(s-1) == '\\n' || \n\t\t\t *(s-1) == '\\t' || *(s-1) == ' ')) {\n\t\t\t\t have_header |= HTTP_HEADER_CONNECTION;\n\t\t\t}\n\t\t\t/* remove Proxy-Authorization header */\n\t\t\tif (use_proxy && use_ssl && (s = strstr(tmp, \"proxy-authorization:\")) &&\n\t\t\t (s == tmp || *(s-1) == '\\r' || *(s-1) == '\\n' ||\n\t\t\t *(s-1) == '\\t' || *(s-1) == ' ')) {\n\t\t\t\tchar *p = s + sizeof(\"proxy-authorization:\") - 1;\n\n\t\t\t\twhile (s > tmp && (*(s-1) == ' ' || *(s-1) == '\\t')) s--;\n\t\t\t\twhile (*p != 0 && *p != '\\r' && *p != '\\n') p++;\n\t\t\t\twhile (*p == '\\r' || *p == '\\n') p++;\n\t\t\t\tif (*p == 0) {\n\t\t\t\t\tif (s == tmp) {\n\t\t\t\t\t\tefree(user_headers);\n\t\t\t\t\t\tuser_headers = NULL;\n\t\t\t\t\t} else {\n\t\t\t\t\t\twhile (s > tmp && (*(s-1) == '\\r' || *(s-1) == '\\n')) s--;\n\t\t\t\t\t\tuser_headers[s - tmp] = 0;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tmemmove(user_headers + (s - tmp), user_headers + (p - tmp), strlen(p) + 1);\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\tif (tmp) {\n\t\t\tefree(tmp);\n\t\t}\n\t}\n\n\t/* auth header if it was specified */\n\tif (((have_header & HTTP_HEADER_AUTH) == 0) && resource->user) {\n\t\t/* decode the strings first */\n\t\tphp_url_decode(resource->user, strlen(resource->user));\n\n\t\t/* scratch is large enough, since it was made large enough for the whole URL */\n\t\tstrcpy(scratch, resource->user);\n\t\tstrcat(scratch, \":\");\n\n\t\t/* Note: password is optional! */\n\t\tif (resource->pass) {\n\t\t\tphp_url_decode(resource->pass, strlen(resource->pass));\n\t\t\tstrcat(scratch, resource->pass);\n\t\t}\n\n\t\ttmp = (char*)php_base64_encode((unsigned char*)scratch, strlen(scratch), NULL);\n\n\t\tif (snprintf(scratch, scratch_len, \"Authorization: Basic %s\\r\\n\", tmp) > 0) {\n\t\t\tphp_stream_write(stream, scratch, strlen(scratch));\n\t\t\tphp_stream_notify_info(context, PHP_STREAM_NOTIFY_AUTH_REQUIRED, NULL, 0);\n\t\t}\n\n\t\tefree(tmp);\n\t\ttmp = NULL;\n\t}\n\n\t/* if the user has configured who they are, send a From: line */\n\tif (((have_header & HTTP_HEADER_FROM) == 0) && FG(from_address)) {\n\t\tif (snprintf(scratch, scratch_len, \"From: %s\\r\\n\", FG(from_address)) > 0)\n\t\t\tphp_stream_write(stream, scratch, strlen(scratch));\n\t}\n\n\t/* Send Host: header so name-based virtual hosts work */\n\tif ((have_header & HTTP_HEADER_HOST) == 0) {\n\t\tif ((use_ssl && resource->port != 443 && resource->port != 0) ||\n\t\t\t(!use_ssl && resource->port != 80 && resource->port != 0)) {\n\t\t\tif (snprintf(scratch, scratch_len, \"Host: %s:%i\\r\\n\", resource->host, resource->port) > 0)\n\t\t\t\tphp_stream_write(stream, scratch, strlen(scratch));\n\t\t} else {\n\t\t\tif (snprintf(scratch, scratch_len, \"Host: %s\\r\\n\", resource->host) > 0) {\n\t\t\t\tphp_stream_write(stream, scratch, strlen(scratch));\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Send a Connection: close header to avoid hanging when the server\n\t * interprets the RFC literally and establishes a keep-alive connection,\n\t * unless the user specifically requests something else by specifying a\n\t * Connection header in the context options. Send that header even for\n\t * HTTP/1.0 to avoid issues when the server respond with a HTTP/1.1\n\t * keep-alive response, which is the preferred response type. */\n\tif ((have_header & HTTP_HEADER_CONNECTION) == 0) {\n\t\tphp_stream_write_string(stream, \"Connection: close\\r\\n\");\n\t}\n\n\tif (context &&\n\t php_stream_context_get_option(context, \"http\", \"user_agent\", &ua_zval) == SUCCESS &&\n\t\tZ_TYPE_PP(ua_zval) == IS_STRING) {\n\t\tua_str = Z_STRVAL_PP(ua_zval);\n\t} else if (FG(user_agent)) {\n\t\tua_str = FG(user_agent);\n\t}\n\n\tif (((have_header & HTTP_HEADER_USER_AGENT) == 0) && ua_str) {\n#define _UA_HEADER \"User-Agent: %s\\r\\n\"\n\t\tchar *ua;\n\t\tsize_t ua_len;\n\n\t\tua_len = sizeof(_UA_HEADER) + strlen(ua_str);\n\n\t\t/* ensure the header is only sent if user_agent is not blank */\n\t\tif (ua_len > sizeof(_UA_HEADER)) {\n\t\t\tua = emalloc(ua_len + 1);\n\t\t\tif ((ua_len = slprintf(ua, ua_len, _UA_HEADER, ua_str)) > 0) {\n\t\t\t\tua[ua_len] = 0;\n\t\t\t\tphp_stream_write(stream, ua, ua_len);\n\t\t\t} else {\n\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Cannot construct User-agent header\");\n\t\t\t}\n\n\t\t\tif (ua) {\n\t\t\t\tefree(ua);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (user_headers) {\n\t\t/* A bit weird, but some servers require that Content-Length be sent prior to Content-Type for POST\n\t\t * see bug #44603 for details. Since Content-Type maybe part of user's headers we need to do this check first.\n\t\t */\n\t\tif (\n\t\t\t\theader_init &&\n\t\t\t\tcontext &&\n\t\t\t\t!(have_header & HTTP_HEADER_CONTENT_LENGTH) &&\n\t\t\t\tphp_stream_context_get_option(context, \"http\", \"content\", &tmpzval) == SUCCESS &&\n\t\t\t\tZ_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0\n\t\t) {\n\t\t\tscratch_len = slprintf(scratch, scratch_len, \"Content-Length: %d\\r\\n\", Z_STRLEN_PP(tmpzval));\n\t\t\tphp_stream_write(stream, scratch, scratch_len);\n\t\t\thave_header |= HTTP_HEADER_CONTENT_LENGTH;\n\t\t}\n\n\t\tphp_stream_write(stream, user_headers, strlen(user_headers));\n\t\tphp_stream_write(stream, \"\\r\\n\", sizeof(\"\\r\\n\")-1);\n\t\tefree(user_headers);\n\t}\n\n\t/* Request content, such as for POST requests */\n\tif (header_init && context &&\n\t\tphp_stream_context_get_option(context, \"http\", \"content\", &tmpzval) == SUCCESS &&\n\t\tZ_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) {\n\t\tif (!(have_header & HTTP_HEADER_CONTENT_LENGTH)) {\n\t\t\tscratch_len = slprintf(scratch, scratch_len, \"Content-Length: %d\\r\\n\", Z_STRLEN_PP(tmpzval));\n\t\t\tphp_stream_write(stream, scratch, scratch_len);\n\t\t}\n\t\tif (!(have_header & HTTP_HEADER_TYPE)) {\n\t\t\tphp_stream_write(stream, \"Content-Type: application/x-www-form-urlencoded\\r\\n\",\n\t\t\t\tsizeof(\"Content-Type: application/x-www-form-urlencoded\\r\\n\") - 1);\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_NOTICE, \"Content-type not specified assuming application/x-www-form-urlencoded\");\n\t\t}\n\t\tphp_stream_write(stream, \"\\r\\n\", sizeof(\"\\r\\n\")-1);\n\t\tphp_stream_write(stream, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval));\n\t} else {\n\t\tphp_stream_write(stream, \"\\r\\n\", sizeof(\"\\r\\n\")-1);\n\t}\n\n\tlocation[0] = '\\0';\n\n\tif (!EG(active_symbol_table)) {\n\t\tzend_rebuild_symbol_table(TSRMLS_C);\n\t}\n\n\tif (header_init) {\n\t\tzval *ztmp;\n\t\tMAKE_STD_ZVAL(ztmp);\n\t\tarray_init(ztmp);\n\t\tZEND_SET_SYMBOL(EG(active_symbol_table), \"http_response_header\", ztmp);\n\t}\n\n\t{\n\t\tzval **rh;\n\t\tif(zend_hash_find(EG(active_symbol_table), \"http_response_header\", sizeof(\"http_response_header\"), (void **) &rh) != SUCCESS || Z_TYPE_PP(rh) != IS_ARRAY) {\n\t\t\tphp_stream_wrapper_log_error(wrapper, options TSRMLS_CC, \"HTTP request failed, http_response_header overwritten\");\n\t\t\tgoto out;\n\t\t}\n\t\tresponse_header = *rh;\n\t\tZ_ADDREF_P(response_header);\n\t}\n\n\tif (!php_stream_eof(stream)) {\n\t\tsize_t tmp_line_len;\n\t\t/* get response header */\n\n\t\tif (php_stream_get_line(stream, tmp_line, sizeof(tmp_line) - 1, &tmp_line_len) != NULL) {\n\t\t\tzval *http_response;\n\n\t\t\tif (tmp_line_len > 9) {\n\t\t\t\tresponse_code = atoi(tmp_line + 9);\n\t\t\t} else {\n\t\t\t\tresponse_code = 0;\n\t\t\t}\n\t\t\tif (context && SUCCESS==php_stream_context_get_option(context, \"http\", \"ignore_errors\", &tmpzval)) {\n\t\t\t\tignore_errors = zend_is_true(*tmpzval);\n\t\t\t}\n\t\t\t/* when we request only the header, don't fail even on error codes */\n\t\t\tif ((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) {\n\t\t\t\treqok = 1;\n\t\t\t}\n\n\t\t\t/* status codes of 1xx are \"informational\", and will be followed by a real response\n\t\t\t * e.g \"100 Continue\". RFC 7231 states that unexpected 1xx status MUST be parsed,\n\t\t\t * and MAY be ignored. As such, we need to skip ahead to the \"real\" status*/\n\t\t\tif (response_code >= 100 && response_code < 200) {\n\t\t\t\t/* consume lines until we find a line starting 'HTTP/1' */\n\t\t\t\twhile (\n\t\t\t\t\t!php_stream_eof(stream)\n\t\t\t\t\t&& php_stream_get_line(stream, tmp_line, sizeof(tmp_line) - 1, &tmp_line_len) != NULL\n\t\t\t\t\t&& ( tmp_line_len < sizeof(\"HTTP/1\") - 1 || strncasecmp(tmp_line, \"HTTP/1\", sizeof(\"HTTP/1\") - 1) )\n\t\t\t\t);\n\n\t\t\t\tif (tmp_line_len > 9) {\n\t\t\t\t\tresponse_code = atoi(tmp_line + 9);\n\t\t\t\t} else {\n\t\t\t\t\tresponse_code = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\t/* all status codes in the 2xx range are defined by the specification as successful;\n\t\t\t * all status codes in the 3xx range are for redirection, and so also should never\n\t\t\t * fail */\n\t\t\tif (response_code >= 200 && response_code < 400) {\n\t\t\t\treqok = 1;\n\t\t\t} else {\n\t\t\t\tswitch(response_code) {\n\t\t\t\t\tcase 403:\n\t\t\t\t\t\tphp_stream_notify_error(context, PHP_STREAM_NOTIFY_AUTH_RESULT,\n\t\t\t\t\t\t\t\ttmp_line, response_code);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t/* safety net in the event tmp_line == NULL */\n\t\t\t\t\t\tif (!tmp_line_len) {\n\t\t\t\t\t\t\ttmp_line[0] = '\\0';\n\t\t\t\t\t\t}\n\t\t\t\t\t\tphp_stream_notify_error(context, PHP_STREAM_NOTIFY_FAILURE,\n\t\t\t\t\t\t\t\ttmp_line, response_code);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (tmp_line[tmp_line_len - 1] == '\\n') {\n\t\t\t\t--tmp_line_len;\n\t\t\t\tif (tmp_line[tmp_line_len - 1] == '\\r') {\n\t\t\t\t\t--tmp_line_len;\n\t\t\t\t}\n\t\t\t}\n\t\t\tMAKE_STD_ZVAL(http_response);\n\t\t\tZVAL_STRINGL(http_response, tmp_line, tmp_line_len, 1);\n\t\t\tzend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_response, sizeof(zval *), NULL);\n\t\t}\n\t} else {\n\t\tphp_stream_wrapper_log_error(wrapper, options TSRMLS_CC, \"HTTP request failed, unexpected end of socket!\");\n\t\tgoto out;\n\t}\n\n\t/* read past HTTP headers */\n\n\thttp_header_line = emalloc(HTTP_HEADER_BLOCK_SIZE);\n\n\twhile (!body && !php_stream_eof(stream)) {\n\t\tsize_t http_header_line_length;\n\t\tif (php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length) && *http_header_line != '\\n' && *http_header_line != '\\r') {\n\t\t\tchar *e = http_header_line + http_header_line_length - 1;\n\t\t\tif (*e != '\\n') {\n\t\t\t\tdo { /* partial header */\n\t\t\t\t\tif (php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length) == NULL) {\n\t\t\t\t\t\tphp_stream_wrapper_log_error(wrapper, options TSRMLS_CC, \"Failed to read HTTP headers\");\n\t\t\t\t\t\tgoto out;\n\t\t\t\t\t}\n\t\t\t\t\te = http_header_line + http_header_line_length - 1;\n\t\t\t\t} while (*e != '\\n');\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\twhile (*e == '\\n' || *e == '\\r') {\n\t\t\t\te--;\n\t\t\t}\n\t\t\thttp_header_line_length = e - http_header_line + 1;\n\t\t\thttp_header_line[http_header_line_length] = '\\0';\n\n\t\t\tif (!strncasecmp(http_header_line, \"Location: \", 10)) {\n\t\t\t\tif (context && php_stream_context_get_option(context, \"http\", \"follow_location\", &tmpzval) == SUCCESS) {\n\t\t\t\t\tSEPARATE_ZVAL(tmpzval);\n\t\t\t\t\tconvert_to_long_ex(tmpzval);\n\t\t\t\t\tfollow_location = Z_LVAL_PP(tmpzval);\n\t\t\t\t} else if (!(response_code >= 300 && response_code < 304 || 307 == response_code || 308 == response_code)) {\n\t\t\t\t\t/* we shouldn't redirect automatically\n\t\t\t\t\tif follow_location isn't set and response_code not in (300, 301, 302, 303 and 307)\n\t\t\t\t\tsee http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.1\n\t\t\t\t\tRFC 7238 defines 308: http://tools.ietf.org/html/rfc7238 */\n\t\t\t\t\tfollow_location = 0;\n\t\t\t\t}\n\t\t\t\tstrlcpy(location, http_header_line + 10, sizeof(location));\n\t\t\t} else if (!strncasecmp(http_header_line, \"Content-Type: \", 14)) {\n\t\t\t\tphp_stream_notify_info(context, PHP_STREAM_NOTIFY_MIME_TYPE_IS, http_header_line + 14, 0);\n\t\t\t} else if (!strncasecmp(http_header_line, \"Content-Length: \", 16)) {\n\t\t\t\tfile_size = atoi(http_header_line + 16);\n\t\t\t\tphp_stream_notify_file_size(context, file_size, http_header_line, 0);\n\t\t\t} else if (!strncasecmp(http_header_line, \"Transfer-Encoding: chunked\", sizeof(\"Transfer-Encoding: chunked\"))) {\n\n\t\t\t\t/* create filter to decode response body */\n\t\t\t\tif (!(options & STREAM_ONLY_GET_HEADERS)) {\n\t\t\t\t\tlong decode = 1;\n\n\t\t\t\t\tif (context && php_stream_context_get_option(context, \"http\", \"auto_decode\", &tmpzval) == SUCCESS) {\n\t\t\t\t\t\tSEPARATE_ZVAL(tmpzval);\n\t\t\t\t\t\tconvert_to_boolean(*tmpzval);\n\t\t\t\t\t\tdecode = Z_LVAL_PP(tmpzval);\n\t\t\t\t\t}\n\t\t\t\t\tif (decode) {\n\t\t\t\t\t\ttransfer_encoding = php_stream_filter_create(\"dechunk\", NULL, php_stream_is_persistent(stream) TSRMLS_CC);\n\t\t\t\t\t\tif (transfer_encoding) {\n\t\t\t\t\t\t\t/* don't store transfer-encodeing header */\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\n\t\t\tif (http_header_line[0] == '\\0') {\n\t\t\t\tbody = 1;\n\t\t\t} else {\n\t\t\t\tzval *http_header;\n\n\t\t\t\tMAKE_STD_ZVAL(http_header);\n\n\t\t\t\tZVAL_STRINGL(http_header, http_header_line, http_header_line_length, 1);\n\n\t\t\t\tzend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_header, sizeof(zval *), NULL);\n\t\t\t}\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (!reqok || (location[0] != '\\0' && follow_location)) {\n\t\tif (!follow_location || (((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) && redirect_max <= 1)) {\n\t\t\tgoto out;\n\t\t}\n\n\t\tif (location[0] != '\\0')\n\t\t\tphp_stream_notify_info(context, PHP_STREAM_NOTIFY_REDIRECTED, location, 0);\n\n\t\tphp_stream_close(stream);\n\t\tstream = NULL;\n\n\t\tif (location[0] != '\\0') {\n\n\t\t\tchar new_path[HTTP_HEADER_BLOCK_SIZE];\n\t\t\tchar loc_path[HTTP_HEADER_BLOCK_SIZE];\n\n\t\t\t*new_path='\\0';\n\t\t\tif (strlen(location)<8 || (strncasecmp(location, \"http://\", sizeof(\"http://\")-1) &&\n\t\t\t\t\t\t\tstrncasecmp(location, \"https://\", sizeof(\"https://\")-1) &&\n\t\t\t\t\t\t\tstrncasecmp(location, \"ftp://\", sizeof(\"ftp://\")-1) &&\n\t\t\t\t\t\t\tstrncasecmp(location, \"ftps://\", sizeof(\"ftps://\")-1)))\n\t\t\t{\n\t\t\t\tif (*location != '/') {\n\t\t\t\t\tif (*(location+1) != '\\0' && resource->path) {\n\t\t\t\t\t\tchar *s = strrchr(resource->path, '/');\n\t\t\t\t\t\tif (!s) {\n\t\t\t\t\t\t\ts = resource->path;\n\t\t\t\t\t\t\tif (!s[0]) {\n\t\t\t\t\t\t\t\tefree(s);\n\t\t\t\t\t\t\t\ts = resource->path = estrdup(\"/\");\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t*s = '/';\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\ts[1] = '\\0';\n\t\t\t\t\t\tif (resource->path && *(resource->path) == '/' && *(resource->path + 1) == '\\0') {\n\t\t\t\t\t\t\tsnprintf(loc_path, sizeof(loc_path) - 1, \"%s%s\", resource->path, location);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tsnprintf(loc_path, sizeof(loc_path) - 1, \"%s/%s\", resource->path, location);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsnprintf(loc_path, sizeof(loc_path) - 1, \"/%s\", location);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tstrlcpy(loc_path, location, sizeof(loc_path));\n\t\t\t\t}\n\t\t\t\tif ((use_ssl && resource->port != 443) || (!use_ssl && resource->port != 80)) {\n\t\t\t\t\tsnprintf(new_path, sizeof(new_path) - 1, \"%s://%s:%d%s\", resource->scheme, resource->host, resource->port, loc_path);\n\t\t\t\t} else {\n\t\t\t\t\tsnprintf(new_path, sizeof(new_path) - 1, \"%s://%s%s\", resource->scheme, resource->host, loc_path);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstrlcpy(new_path, location, sizeof(new_path));\n\t\t\t}\n\n\t\t\tphp_url_free(resource);\n\t\t\t/* check for invalid redirection URLs */\n\t\t\tif ((resource = php_url_parse(new_path)) == NULL) {\n\t\t\t\tphp_stream_wrapper_log_error(wrapper, options TSRMLS_CC, \"Invalid redirect URL! %s\", new_path);\n\t\t\t\tgoto out;\n\t\t\t}\n\n#define CHECK_FOR_CNTRL_CHARS(val) { \\\n\tif (val) { \\\n\t\tunsigned char *s, *e; \\\n\t\tint l; \\\n\t\tl = php_url_decode(val, strlen(val)); \\\n\t\ts = (unsigned char*)val; e = s + l; \\\n\t\twhile (s < e) { \\\n\t\t\tif (iscntrl(*s)) { \\\n\t\t\t\tphp_stream_wrapper_log_error(wrapper, options TSRMLS_CC, \"Invalid redirect URL! %s\", new_path); \\\n\t\t\t\tgoto out; \\\n\t\t\t} \\\n\t\t\ts++; \\\n\t\t} \\\n\t} \\\n}\n\t\t\t/* check for control characters in login, password & path */\n\t\t\tif (strncasecmp(new_path, \"http://\", sizeof(\"http://\") - 1) || strncasecmp(new_path, \"https://\", sizeof(\"https://\") - 1)) {\n\t\t\t\tCHECK_FOR_CNTRL_CHARS(resource->user)\n\t\t\t\tCHECK_FOR_CNTRL_CHARS(resource->pass)\n\t\t\t\tCHECK_FOR_CNTRL_CHARS(resource->path)\n\t\t\t}\n\t\t\tstream = php_stream_url_wrap_http_ex(wrapper, new_path, mode, options, opened_path, context, --redirect_max, HTTP_WRAPPER_REDIRECTED STREAMS_CC TSRMLS_CC);\n\t\t} else {\n\t\t\tphp_stream_wrapper_log_error(wrapper, options TSRMLS_CC, \"HTTP request failed! %s\", tmp_line);\n\t\t}\n\t}\nout:\n\tif (protocol_version) {\n\t\tefree(protocol_version);\n\t}\n\n\tif (http_header_line) {\n\t\tefree(http_header_line);\n\t}\n\n\tif (scratch) {\n\t\tefree(scratch);\n\t}\n\n\tif (resource) {\n\t\tphp_url_free(resource);\n\t}\n\n\tif (stream) {\n\t\tif (header_init) {\n\t\t\tstream->wrapperdata = response_header;\n\t\t} else {\n\t\t\tif(response_header) {\n\t\t\t\tZ_DELREF_P(response_header);\n\t\t\t}\n\t\t}\n\t\tphp_stream_notify_progress_init(context, 0, file_size);\n\n\t\t/* Restore original chunk size now that we're done with headers */\n\t\tif (options & STREAM_WILL_CAST)\n\t\t\tphp_stream_set_chunk_size(stream, chunk_size);\n\n\t\t/* restore the users auto-detect-line-endings setting */\n\t\tstream->flags |= eol_detect;\n\n\t\t/* as far as streams are concerned, we are now at the start of\n\t\t * the stream */\n\t\tstream->position = 0;\n\n\t\t/* restore mode */\n\t\tstrlcpy(stream->mode, mode, sizeof(stream->mode));\n\n\t\tif (transfer_encoding) {\n\t\t\tphp_stream_filter_append(&stream->readfilters, transfer_encoding);\n\t\t}\n\t} else {\n\t\tif(response_header) {\n\t\t\tZ_DELREF_P(response_header);\n\t\t}\n\t\tif (transfer_encoding) {\n\t\t\tphp_stream_filter_free(transfer_encoding TSRMLS_CC);\n\t\t}\n\t}\n\n\treturn stream;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix bug #75981: prevent reading beyond buffer start'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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_num_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\tint ret = 0;\n\n\ttmp = simple_strtoul(p, &p, 0);\n\tif (!p || (*p && (*p != '\\n')))\n\t\treturn -EINVAL;\n\n\tif (tmp >= O2NM_MAX_NODES)\n\t\treturn -ERANGE;\n\n\t/* once we're in the cl_nodes tree networking can look us up by\n\t * node number and try to use our address and port attributes\n\t * to connect to this node.. make sure that they've been set\n\t * before writing the node attribute? */\n\tif (!test_bit(O2NM_NODE_ATTR_ADDRESS, &node->nd_set_attributes) ||\n\t !test_bit(O2NM_NODE_ATTR_PORT, &node->nd_set_attributes))\n\t\treturn -EINVAL; /* XXX */\n\n\twrite_lock(&cluster->cl_nodes_lock);\n\tif (cluster->cl_nodes[tmp])\n\t\tret = -EEXIST;\n\telse if (test_and_set_bit(O2NM_NODE_ATTR_NUM,\n\t\t\t&node->nd_set_attributes))\n\t\tret = -EBUSY;\n\telse {\n\t\tcluster->cl_nodes[tmp] = node;\n\t\tnode->nd_num = tmp;\n\t\tset_bit(tmp, cluster->cl_nodes_bitmap);\n\t}\n\twrite_unlock(&cluster->cl_nodes_lock);\n\tif (ret)\n\t\treturn ret;\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: \n CImg& _load_bmp(std::FILE *const file, const char *const filename) {\n if (!file && !filename)\n throw CImgArgumentException(_cimg_instance\n \"load_bmp(): Specified filename is (null).\",\n cimg_instance);\n\n std::FILE *const nfile = file?file:cimg::fopen(filename,\"rb\");\n CImg header(54);\n cimg::fread(header._data,54,nfile);\n if (*header!='B' || header[1]!='M') {\n if (!file) cimg::fclose(nfile);\n throw CImgIOException(_cimg_instance\n \"load_bmp(): Invalid BMP file '%s'.\",\n cimg_instance,\n filename?filename:\"(FILE*)\");\n }\n\n // Read header and pixel buffer\n int\n file_size = header[0x02] + (header[0x03]<<8) + (header[0x04]<<16) + (header[0x05]<<24),\n offset = header[0x0A] + (header[0x0B]<<8) + (header[0x0C]<<16) + (header[0x0D]<<24),\n header_size = header[0x0E] + (header[0x0F]<<8) + (header[0x10]<<16) + (header[0x11]<<24),\n dx = header[0x12] + (header[0x13]<<8) + (header[0x14]<<16) + (header[0x15]<<24),\n dy = header[0x16] + (header[0x17]<<8) + (header[0x18]<<16) + (header[0x19]<<24),\n compression = header[0x1E] + (header[0x1F]<<8) + (header[0x20]<<16) + (header[0x21]<<24),\n nb_colors = header[0x2E] + (header[0x2F]<<8) + (header[0x30]<<16) + (header[0x31]<<24),\n bpp = header[0x1C] + (header[0x1D]<<8);\n\n if (!file_size || file_size==offset) {\n cimg::fseek(nfile,0,SEEK_END);\n file_size = (int)cimg::ftell(nfile);\n cimg::fseek(nfile,54,SEEK_SET);\n }\n if (header_size>40) cimg::fseek(nfile,header_size - 40,SEEK_CUR);\n\n const int\n dx_bytes = (bpp==1)?(dx/8 + (dx%8?1:0)):((bpp==4)?(dx/2 + (dx%2)):(dx*bpp/8)),\n align_bytes = (4 - dx_bytes%4)%4;\n const ulongT\n cimg_iobuffer = (ulongT)24*1024*1024,\n buf_size = std::min((ulongT)cimg::abs(dy)*(dx_bytes + align_bytes),(ulongT)file_size - offset);\n\n CImg colormap;\n if (bpp<16) { if (!nb_colors) nb_colors = 1<0) cimg::fseek(nfile,xoffset,SEEK_CUR);\n\n CImg buffer;\n if (buf_size=0; --y) {\n if (buf_size>=cimg_iobuffer) {\n if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break;\n cimg::fseek(nfile,align_bytes,SEEK_CUR);\n }\n unsigned char mask = 0x80, val = 0;\n cimg_forX(*this,x) {\n if (mask==0x80) val = *(ptrs++);\n const unsigned char *col = (unsigned char*)(colormap._data + (val&mask?1:0));\n (*this)(x,y,2) = (T)*(col++);\n (*this)(x,y,1) = (T)*(col++);\n (*this)(x,y,0) = (T)*(col++);\n mask = cimg::ror(mask);\n }\n ptrs+=align_bytes;\n }\n } break;\n case 4 : { // 16 colors\n for (int y = height() - 1; y>=0; --y) {\n if (buf_size>=cimg_iobuffer) {\n if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break;\n cimg::fseek(nfile,align_bytes,SEEK_CUR);\n }\n unsigned char mask = 0xF0, val = 0;\n cimg_forX(*this,x) {\n if (mask==0xF0) val = *(ptrs++);\n const unsigned char color = (unsigned char)((mask<16)?(val&mask):((val&mask)>>4));\n const unsigned char *col = (unsigned char*)(colormap._data + color);\n (*this)(x,y,2) = (T)*(col++);\n (*this)(x,y,1) = (T)*(col++);\n (*this)(x,y,0) = (T)*(col++);\n mask = cimg::ror(mask,4);\n }\n ptrs+=align_bytes;\n }\n } break;\n case 8 : { // 256 colors\n for (int y = height() - 1; y>=0; --y) {\n if (buf_size>=cimg_iobuffer) {\n if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break;\n cimg::fseek(nfile,align_bytes,SEEK_CUR);\n }\n cimg_forX(*this,x) {\n const unsigned char *col = (unsigned char*)(colormap._data + *(ptrs++));\n (*this)(x,y,2) = (T)*(col++);\n (*this)(x,y,1) = (T)*(col++);\n (*this)(x,y,0) = (T)*(col++);\n }\n ptrs+=align_bytes;\n }\n } break;\n case 16 : { // 16 bits colors\n for (int y = height() - 1; y>=0; --y) {\n if (buf_size>=cimg_iobuffer) {\n if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break;\n cimg::fseek(nfile,align_bytes,SEEK_CUR);\n }\n cimg_forX(*this,x) {\n const unsigned char c1 = *(ptrs++), c2 = *(ptrs++);\n const unsigned short col = (unsigned short)(c1|(c2<<8));\n (*this)(x,y,2) = (T)(col&0x1F);\n (*this)(x,y,1) = (T)((col>>5)&0x1F);\n (*this)(x,y,0) = (T)((col>>10)&0x1F);\n }\n ptrs+=align_bytes;\n }\n } break;\n case 24 : { // 24 bits colors\n for (int y = height() - 1; y>=0; --y) {\n if (buf_size>=cimg_iobuffer) {\n if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break;\n cimg::fseek(nfile,align_bytes,SEEK_CUR);\n }\n cimg_forX(*this,x) {\n (*this)(x,y,2) = (T)*(ptrs++);\n (*this)(x,y,1) = (T)*(ptrs++);\n (*this)(x,y,0) = (T)*(ptrs++);\n }\n ptrs+=align_bytes;\n }\n } break;\n case 32 : { // 32 bits colors\n for (int y = height() - 1; y>=0; --y) {\n if (buf_size>=cimg_iobuffer) {\n if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break;\n cimg::fseek(nfile,align_bytes,SEEK_CUR);\n }\n cimg_forX(*this,x) {\n (*this)(x,y,2) = (T)*(ptrs++);\n (*this)(x,y,1) = (T)*(ptrs++);\n (*this)(x,y,0) = (T)*(ptrs++);\n ++ptrs;\n }\n ptrs+=align_bytes;\n }\n } break;\n }\n if (dy<0) mirror('y');\n if (!file) cimg::fclose(nfile);\n return *this; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix other issues in 'CImg::load_bmp()'.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (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, last_len, prefix_len, suffix_len, path_len;\n\t\tuintmax_t strip_len;\n\n\t\tstrip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len);\n\t\tlast_len = strlen(last);\n\n\t\tif (varint_len == 0 || last_len < strip_len)\n\t\t\treturn index_error_invalid(\"incorrect prefix length\");\n\n\t\tprefix_len = last_len - strip_len;\n\t\tsuffix_len = strlen(path_ptr + varint_len);\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: error out on unreasonable prefix-compressed path lengths\n\nWhen computing the complete path length from the encoded\nprefix-compressed path, we end up just allocating the complete path\nwithout ever checking what the encoded path length actually is. This can\neasily lead to a denial of service by just encoding an unreasonable long\npath name inside of the index. Git already enforces a maximum path\nlength of 4096 bytes. As we also have that enforcement ready in some\nplaces, just make sure that the resulting path is smaller than\nGIT_PATH_MAX.\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_disk_entry_fopen(ZZIP_DISK * disk, ZZIP_DISK_ENTRY * entry)\n{\n /* keep this in sync with zzip_mem_entry_fopen */\n struct zzip_file_header *header =\n zzip_disk_entry_to_file_header(disk, entry);\n if (! header)\n return 0; /* EBADMSG */\n ___ ZZIP_DISK_FILE *file = malloc(sizeof(ZZIP_DISK_FILE));\n if (! file)\n return 0; /* ENOMEM */\n file->buffer = disk->buffer;\n file->endbuf = disk->endbuf;\n file->avail = zzip_file_header_usize(header);\n\n if (! file->avail || zzip_file_header_data_stored(header))\n { \n file->stored = zzip_file_header_to_data (header);\n DBG2(\"stored size %i\", (int) file->avail);\n if (file->stored + file->avail >= disk->endbuf)\n goto error;\n return file; \n }\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_file_header_csize(header);\n file->zlib.next_in = zzip_file_header_to_data(header);\n\n DBG2(\"compressed size %i\", (int) file->zlib.avail_in);\n if (file->zlib.next_in + file->zlib.avail_in >= disk->endbuf)\n goto error;\n\n if (! zzip_file_header_data_deflated(header))\n goto error;\n if (inflateInit2(&file->zlib, -MAX_WBITS) != Z_OK)\n goto error;\n\n return file;\nerror:\n free (file);\n errno = EBADMSG;\n return 0; \n ____;\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_entry_to_data(ZZIP_MEM_DISK* dir, ZZIP_DISK_ENTRY* entry) {\n return zzip_disk_entry_to_data(dir->disk, entry); } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'memdisk\n (.)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: zzip_mem_disk_fread (void* ptr, _zzip_size_t size, _zzip_size_t nmemb,\n ZZIP_DISK_FILE* file) {\n return zzip_disk_fread(ptr, size, nmemb, file); } ; 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: static int ocfs2_dio_get_block(struct inode *inode, sector_t iblock,\n\t\t\t struct buffer_head *bh_result, int create)\n{\n\tstruct ocfs2_super *osb = OCFS2_SB(inode->i_sb);\n\tstruct ocfs2_inode_info *oi = OCFS2_I(inode);\n\tstruct ocfs2_write_ctxt *wc;\n\tstruct ocfs2_write_cluster_desc *desc = NULL;\n\tstruct ocfs2_dio_write_ctxt *dwc = NULL;\n\tstruct buffer_head *di_bh = NULL;\n\tu64 p_blkno;\n\tloff_t pos = iblock << inode->i_sb->s_blocksize_bits;\n\tunsigned len, total_len = bh_result->b_size;\n\tint ret = 0, first_get_block = 0;\n\n\tlen = osb->s_clustersize - (pos & (osb->s_clustersize - 1));\n\tlen = min(total_len, len);\n\n\tmlog(0, \"get block of %lu at %llu:%u req %u\\n\",\n\t\t\tinode->i_ino, pos, len, total_len);\n\n\t/*\n\t * Because we need to change file size in ocfs2_dio_end_io_write(), or\n\t * we may need to add it to orphan dir. So can not fall to fast path\n\t * while file size will be changed.\n\t */\n\tif (pos + total_len <= i_size_read(inode)) {\n\t\tdown_read(&oi->ip_alloc_sem);\n\t\t/* This is the fast path for re-write. */\n\t\tret = ocfs2_get_block(inode, iblock, bh_result, create);\n\n\t\tup_read(&oi->ip_alloc_sem);\n\n\t\tif (buffer_mapped(bh_result) &&\n\t\t !buffer_new(bh_result) &&\n\t\t ret == 0)\n\t\t\tgoto out;\n\n\t\t/* Clear state set by ocfs2_get_block. */\n\t\tbh_result->b_state = 0;\n\t}\n\n\tdwc = ocfs2_dio_alloc_write_ctx(bh_result, &first_get_block);\n\tif (unlikely(dwc == NULL)) {\n\t\tret = -ENOMEM;\n\t\tmlog_errno(ret);\n\t\tgoto out;\n\t}\n\n\tif (ocfs2_clusters_for_bytes(inode->i_sb, pos + total_len) >\n\t ocfs2_clusters_for_bytes(inode->i_sb, i_size_read(inode)) &&\n\t !dwc->dw_orphaned) {\n\t\t/*\n\t\t * when we are going to alloc extents beyond file size, add the\n\t\t * inode to orphan dir, so we can recall those spaces when\n\t\t * system crashed during write.\n\t\t */\n\t\tret = ocfs2_add_inode_to_orphan(osb, inode);\n\t\tif (ret < 0) {\n\t\t\tmlog_errno(ret);\n\t\t\tgoto out;\n\t\t}\n\t\tdwc->dw_orphaned = 1;\n\t}\n\n\tret = ocfs2_inode_lock(inode, &di_bh, 1);\n\tif (ret) {\n\t\tmlog_errno(ret);\n\t\tgoto out;\n\t}\n\n\tdown_write(&oi->ip_alloc_sem);\n\n\tif (first_get_block) {\n\t\tif (ocfs2_sparse_alloc(OCFS2_SB(inode->i_sb)))\n\t\t\tret = ocfs2_zero_tail(inode, di_bh, pos);\n\t\telse\n\t\t\tret = ocfs2_expand_nonsparse_inode(inode, di_bh, pos,\n\t\t\t\t\t\t\t total_len, NULL);\n\t\tif (ret < 0) {\n\t\t\tmlog_errno(ret);\n\t\t\tgoto unlock;\n\t\t}\n\t}\n\n\tret = ocfs2_write_begin_nolock(inode->i_mapping, pos, len,\n\t\t\t\t OCFS2_WRITE_DIRECT, NULL,\n\t\t\t\t (void **)&wc, di_bh, NULL);\n\tif (ret) {\n\t\tmlog_errno(ret);\n\t\tgoto unlock;\n\t}\n\n\tdesc = &wc->w_desc[0];\n\n\tp_blkno = ocfs2_clusters_to_blocks(inode->i_sb, desc->c_phys);\n\tBUG_ON(p_blkno == 0);\n\tp_blkno += iblock & (u64)(ocfs2_clusters_to_blocks(inode->i_sb, 1) - 1);\n\n\tmap_bh(bh_result, inode->i_sb, p_blkno);\n\tbh_result->b_size = len;\n\tif (desc->c_needs_zero)\n\t\tset_buffer_new(bh_result);\n\n\t/* May sleep in end_io. It should not happen in a irq context. So defer\n\t * it to dio work queue. */\n\tset_buffer_defer_completion(bh_result);\n\n\tif (!list_empty(&wc->w_unwritten_list)) {\n\t\tstruct ocfs2_unwritten_extent *ue = NULL;\n\n\t\tue = list_first_entry(&wc->w_unwritten_list,\n\t\t\t\t struct ocfs2_unwritten_extent,\n\t\t\t\t ue_node);\n\t\tBUG_ON(ue->ue_cpos != desc->c_cpos);\n\t\t/* The physical address may be 0, fill it. */\n\t\tue->ue_phys = desc->c_phys;\n\n\t\tlist_splice_tail_init(&wc->w_unwritten_list, &dwc->dw_zero_list);\n\t\tdwc->dw_zero_count++;\n\t}\n\n\tret = ocfs2_write_end_nolock(inode->i_mapping, pos, len, len, wc);\n\tBUG_ON(ret != len);\n\tret = 0;\nunlock:\n\tup_write(&oi->ip_alloc_sem);\n\tocfs2_inode_unlock(inode, 1);\n\tbrelse(di_bh);\nout:\n\tif (ret < 0)\n\t\tret = -EIO;\n\treturn ret;\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_discover_domain(struct work_struct *work)\n{\n\tstruct domain_device *dev;\n\tint error = 0;\n\tstruct sas_discovery_event *ev = to_sas_discovery_event(work);\n\tstruct asd_sas_port *port = ev->port;\n\n\tclear_bit(DISCE_DISCOVER_DOMAIN, &port->disc.pending);\n\n\tif (port->port_dev)\n\t\treturn;\n\n\terror = sas_get_port_device(port);\n\tif (error)\n\t\treturn;\n\tdev = port->port_dev;\n\n\tSAS_DPRINTK(\"DOING DISCOVERY on port %d, pid:%d\\n\", port->id,\n\t\t task_pid_nr(current));\n\n\tswitch (dev->dev_type) {\n\tcase SAS_END_DEVICE:\n\t\terror = sas_discover_end_dev(dev);\n\t\tbreak;\n\tcase SAS_EDGE_EXPANDER_DEVICE:\n\tcase SAS_FANOUT_EXPANDER_DEVICE:\n\t\terror = sas_discover_root_expander(dev);\n\t\tbreak;\n\tcase SAS_SATA_DEV:\n\tcase SAS_SATA_PM:\n#ifdef CONFIG_SCSI_SAS_ATA\n\t\terror = sas_discover_sata(dev);\n\t\tbreak;\n#else\n\t\tSAS_DPRINTK(\"ATA device seen but CONFIG_SCSI_SAS_ATA=N so cannot attach\\n\");\n\t\t/* Fall through */\n#endif\n\tdefault:\n\t\terror = -ENXIO;\n\t\tSAS_DPRINTK(\"unhandled device %d\\n\", dev->dev_type);\n\t\tbreak;\n\t}\n\n\tif (error) {\n\t\tsas_rphy_free(dev->rphy);\n\t\tlist_del_init(&dev->disco_list_node);\n\t\tspin_lock_irq(&port->dev_list_lock);\n\t\tlist_del_init(&dev->dev_list_node);\n\t\tspin_unlock_irq(&port->dev_list_lock);\n\n\t\tsas_put_device(dev);\n\t\tport->port_dev = NULL;\n\t}\n\n\tSAS_DPRINTK(\"DONE DISCOVERY on port %d, pid:%d, result:%d\\n\", port->id,\n\t\t task_pid_nr(current), error);\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: LZWDecodeCompat(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)\n{\n\tstatic const char module[] = \"LZWDecodeCompat\";\n\tLZWCodecState *sp = DecoderState(tif);\n\tchar *op = (char*) op0;\n\tlong occ = (long) occ0;\n\tchar *tp;\n\tunsigned char *bp;\n\tint code, nbits;\n\tlong nextbits, nextdata, nbitsmask;\n\tcode_t *codep, *free_entp, *maxcodep, *oldcodep;\n\n\t(void) s;\n\tassert(sp != NULL);\n\n\t/*\n\t Fail if value does not fit in long.\n\t*/\n\tif ((tmsize_t) occ != occ0)\n\t return (0);\n\n\t/*\n\t * Restart interrupted output operation.\n\t */\n\tif (sp->dec_restart) {\n\t\tlong residue;\n\n\t\tcodep = sp->dec_codep;\n\t\tresidue = codep->length - sp->dec_restart;\n\t\tif (residue > occ) {\n\t\t\t/*\n\t\t\t * Residue from previous decode is sufficient\n\t\t\t * to satisfy decode request. Skip to the\n\t\t\t * start of the decoded string, place decoded\n\t\t\t * values in the output buffer, and return.\n\t\t\t */\n\t\t\tsp->dec_restart += occ;\n\t\t\tdo {\n\t\t\t\tcodep = codep->next;\n\t\t\t} while (--residue > occ);\n\t\t\ttp = op + occ;\n\t\t\tdo {\n\t\t\t\t*--tp = codep->value;\n\t\t\t\tcodep = codep->next;\n\t\t\t} while (--occ);\n\t\t\treturn (1);\n\t\t}\n\t\t/*\n\t\t * Residue satisfies only part of the decode request.\n\t\t */\n\t\top += residue;\n\t\tocc -= residue;\n\t\ttp = op;\n\t\tdo {\n\t\t\t*--tp = codep->value;\n\t\t\tcodep = codep->next;\n\t\t} while (--residue);\n\t\tsp->dec_restart = 0;\n\t}\n\n\tbp = (unsigned char *)tif->tif_rawcp;\n#ifdef LZW_CHECKEOS\n\tsp->dec_bitsleft = (((uint64)tif->tif_rawcc) << 3);\n#endif\n\tnbits = sp->lzw_nbits;\n\tnextdata = sp->lzw_nextdata;\n\tnextbits = sp->lzw_nextbits;\n\tnbitsmask = sp->dec_nbitsmask;\n\toldcodep = sp->dec_oldcodep;\n\tfree_entp = sp->dec_free_entp;\n\tmaxcodep = sp->dec_maxcodep;\n\n\twhile (occ > 0) {\n\t\tNextCode(tif, sp, bp, code, GetNextCodeCompat);\n\t\tif (code == CODE_EOI)\n\t\t\tbreak;\n\t\tif (code == CODE_CLEAR) {\n\t\t\tdo {\n\t\t\t\tfree_entp = sp->dec_codetab + CODE_FIRST;\n\t\t\t\t_TIFFmemset(free_entp, 0,\n\t\t\t\t\t (CSIZE - CODE_FIRST) * sizeof (code_t));\n\t\t\t\tnbits = BITS_MIN;\n\t\t\t\tnbitsmask = MAXCODE(BITS_MIN);\n\t\t\t\tmaxcodep = sp->dec_codetab + nbitsmask;\n\t\t\t\tNextCode(tif, sp, bp, code, GetNextCodeCompat);\n\t\t\t} while (code == CODE_CLEAR);\t/* consecutive CODE_CLEAR codes */\n\t\t\tif (code == CODE_EOI)\n\t\t\t\tbreak;\n\t\t\tif (code > CODE_CLEAR) {\n\t\t\t\tTIFFErrorExt(tif->tif_clientdata, tif->tif_name,\n\t\t\t\t\"LZWDecode: Corrupted LZW table at scanline %d\",\n\t\t\t\t\t tif->tif_row);\n\t\t\t\treturn (0);\n\t\t\t}\n\t\t\t*op++ = (char)code;\n\t\t\tocc--;\n\t\t\toldcodep = sp->dec_codetab + code;\n\t\t\tcontinue;\n\t\t}\n\t\tcodep = sp->dec_codetab + code;\n\n\t\t/*\n\t\t * Add the new entry to the code table.\n\t\t */\n\t\tif (free_entp < &sp->dec_codetab[0] ||\n\t\t free_entp >= &sp->dec_codetab[CSIZE]) {\n\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t \"Corrupted LZW table at scanline %d\", tif->tif_row);\n\t\t\treturn (0);\n\t\t}\n\n\t\tfree_entp->next = oldcodep;\n\t\tif (free_entp->next < &sp->dec_codetab[0] ||\n\t\t free_entp->next >= &sp->dec_codetab[CSIZE]) {\n\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t \"Corrupted LZW table at scanline %d\", tif->tif_row);\n\t\t\treturn (0);\n\t\t}\n\t\tfree_entp->firstchar = free_entp->next->firstchar;\n\t\tfree_entp->length = free_entp->next->length+1;\n\t\tfree_entp->value = (codep < free_entp) ?\n\t\t codep->firstchar : free_entp->firstchar;\n\t\tif (++free_entp > maxcodep) {\n\t\t\tif (++nbits > BITS_MAX)\t\t/* should not happen */\n\t\t\t\tnbits = BITS_MAX;\n\t\t\tnbitsmask = MAXCODE(nbits);\n\t\t\tmaxcodep = sp->dec_codetab + nbitsmask;\n\t\t}\n\t\toldcodep = codep;\n\t\tif (code >= 256) {\n\t\t\t/*\n\t\t\t * Code maps to a string, copy string\n\t\t\t * value to output (written in reverse).\n\t\t\t */\n\t\t\tif(codep->length == 0) {\n\t\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t\t \"Wrong length of decoded \"\n\t\t\t\t \"string: data probably corrupted at scanline %d\",\n\t\t\t\t tif->tif_row);\n\t\t\t\treturn (0);\n\t\t\t}\n\t\t\tif (codep->length > occ) {\n\t\t\t\t/*\n\t\t\t\t * String is too long for decode buffer,\n\t\t\t\t * locate portion that will fit, copy to\n\t\t\t\t * the decode buffer, and setup restart\n\t\t\t\t * logic for the next decoding call.\n\t\t\t\t */\n\t\t\t\tsp->dec_codep = codep;\n\t\t\t\tdo {\n\t\t\t\t\tcodep = codep->next;\n\t\t\t\t} while (codep->length > occ);\n\t\t\t\tsp->dec_restart = occ;\n\t\t\t\ttp = op + occ;\n\t\t\t\tdo {\n\t\t\t\t\t*--tp = codep->value;\n\t\t\t\t\tcodep = codep->next;\n\t\t\t\t} while (--occ);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tassert(occ >= codep->length);\n\t\t\top += codep->length;\n\t\t\tocc -= codep->length;\n\t\t\ttp = op;\n\t\t\tdo {\n\t\t\t\t*--tp = codep->value;\n\t\t\t} while( (codep = codep->next) != NULL );\n\t\t} else {\n\t\t\t*op++ = (char)code;\n\t\t\tocc--;\n\t\t}\n\t}\n\n\ttif->tif_rawcc -= (tmsize_t)( (uint8*) bp - tif->tif_rawcp );\n\ttif->tif_rawcp = (uint8*) bp;\n\tsp->lzw_nbits = (unsigned short)nbits;\n\tsp->lzw_nextdata = nextdata;\n\tsp->lzw_nextbits = nextbits;\n\tsp->dec_nbitsmask = nbitsmask;\n\tsp->dec_oldcodep = oldcodep;\n\tsp->dec_free_entp = free_entp;\n\tsp->dec_maxcodep = maxcodep;\n\n\tif (occ > 0) {\n#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))\n\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t\"Not enough data at scanline %d (short %I64d bytes)\",\n\t\t\t tif->tif_row, (unsigned __int64) occ);\n#else\n\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t\"Not enough data at scanline %d (short %llu bytes)\",\n\t\t\t tif->tif_row, (unsigned long long) occ);\n#endif\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-787'], 'message': 'LZWDecodeCompat(): fix potential index-out-of-bounds write. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2780 / CVE-2018-8905\n\nThe fix consists in using the similar code LZWDecode() to validate we\ndon't write outside of the output 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 int jpc_enc_encodemainbody(jpc_enc_t *enc)\n{\n\tint tileno;\n\tint tilex;\n\tint tiley;\n\tint i;\n\tjpc_sot_t *sot;\n\tjpc_enc_tcmpt_t *comp;\n\tjpc_enc_tcmpt_t *endcomps;\n\tjpc_enc_band_t *band;\n\tjpc_enc_band_t *endbands;\n\tjpc_enc_rlvl_t *lvl;\n\tint rlvlno;\n\tjpc_qcc_t *qcc;\n\tjpc_cod_t *cod;\n\tint adjust;\n\tint j;\n\tint absbandno;\n\tlong numbytes;\n\tlong tilehdrlen;\n\tlong tilelen;\n\tjpc_enc_tile_t *tile;\n\tjpc_enc_cp_t *cp;\n\tdouble rho;\n\tint lyrno;\n\tint cmptno;\n\tint samestepsizes;\n\tjpc_enc_ccp_t *ccps;\n\tjpc_enc_tccp_t *tccp;\n\tint bandno;\n\tuint_fast32_t x;\n\tuint_fast32_t y;\n\tint mingbits;\n\tint actualnumbps;\n\tjpc_fix_t mxmag;\n\tjpc_fix_t mag;\n\tint numgbits;\n\n\tcp = enc->cp;\n\n\t/* Avoid compile warnings. */\n\tnumbytes = 0;\n\n\tfor (tileno = 0; tileno < JAS_CAST(int, cp->numtiles); ++tileno) {\n\t\ttilex = tileno % cp->numhtiles;\n\t\ttiley = tileno / cp->numhtiles;\n\n\t\tif (!(enc->curtile = jpc_enc_tile_create(enc->cp, enc->image,\n\t\t tileno))) {\n\t\t\tjas_eprintf(\"cannot create tile\\n\");\n\t\t\treturn -1;\n\t\t}\n\n\t\ttile = enc->curtile;\n\n\t\tif (jas_getdbglevel() >= 10) {\n\t\t\tjpc_enc_dump(enc);\n\t\t}\n\n\t\tendcomps = &tile->tcmpts[tile->numtcmpts];\n\t\tfor (cmptno = 0, comp = tile->tcmpts; cmptno < tile->numtcmpts; ++cmptno, ++comp) {\n\t\t\tif (!cp->ccps[cmptno].sgnd) {\n\t\t\t\tadjust = 1 << (cp->ccps[cmptno].prec - 1);\n\t\t\t\tfor (i = 0; i < jas_matrix_numrows(comp->data); ++i) {\n\t\t\t\t\tfor (j = 0; j < jas_matrix_numcols(comp->data); ++j) {\n\t\t\t\t\t\t*jas_matrix_getref(comp->data, i, j) -= adjust;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!tile->intmode) {\n\t\t\t\tendcomps = &tile->tcmpts[tile->numtcmpts];\n\t\t\t\tfor (comp = tile->tcmpts; comp != endcomps; ++comp) {\n\t\t\t\t\tjas_matrix_asl(comp->data, JPC_FIX_FRACBITS);\n\t\t\t\t}\n\t\t}\n\n\t\tswitch (tile->mctid) {\n\t\tcase JPC_MCT_RCT:\nassert(jas_image_numcmpts(enc->image) == 3);\n\t\t\tjpc_rct(tile->tcmpts[0].data, tile->tcmpts[1].data,\n\t\t\t tile->tcmpts[2].data);\n\t\t\tbreak;\n\t\tcase JPC_MCT_ICT:\nassert(jas_image_numcmpts(enc->image) == 3);\n\t\t\tjpc_ict(tile->tcmpts[0].data, tile->tcmpts[1].data,\n\t\t\t tile->tcmpts[2].data);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\tfor (i = 0; i < jas_image_numcmpts(enc->image); ++i) {\n\t\t\tcomp = &tile->tcmpts[i];\n\t\t\tjpc_tsfb_analyze(comp->tsfb, comp->data);\n\n\t\t}\n\n\n\t\tendcomps = &tile->tcmpts[tile->numtcmpts];\n\t\tfor (cmptno = 0, comp = tile->tcmpts; comp != endcomps; ++cmptno, ++comp) {\n\t\t\tmingbits = 0;\n\t\t\tabsbandno = 0;\n\t\t\t/* All bands must have a corresponding quantizer step size,\n\t\t\t even if they contain no samples and are never coded. */\n\t\t\t/* Some bands may not be hit by the loop below, so we must\n\t\t\t initialize all of the step sizes to a sane value. */\n\t\t\tmemset(comp->stepsizes, 0, sizeof(comp->stepsizes));\n\t\t\tfor (rlvlno = 0, lvl = comp->rlvls; rlvlno < comp->numrlvls; ++rlvlno, ++lvl) {\n\t\t\t\tif (!lvl->bands) {\n\t\t\t\t\tabsbandno += rlvlno ? 3 : 1;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tendbands = &lvl->bands[lvl->numbands];\n\t\t\t\tfor (band = lvl->bands; band != endbands; ++band) {\n\t\t\t\t\tif (!band->data) {\n\t\t\t\t\t\t++absbandno;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tactualnumbps = 0;\n\t\t\t\t\tmxmag = 0;\n\t\t\t\t\tfor (y = 0; y < JAS_CAST(uint_fast32_t, jas_matrix_numrows(band->data)); ++y) {\n\t\t\t\t\t\tfor (x = 0; x < JAS_CAST(uint_fast32_t, jas_matrix_numcols(band->data)); ++x) {\n\t\t\t\t\t\t\tmag = JAS_ABS(jas_matrix_get(band->data, y, x));\n\t\t\t\t\t\t\tif (mag > mxmag) {\n\t\t\t\t\t\t\t\tmxmag = mag;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (tile->intmode) {\n\t\t\t\t\t\tactualnumbps = jpc_firstone(mxmag) + 1;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tactualnumbps = jpc_firstone(mxmag) + 1 - JPC_FIX_FRACBITS;\n\t\t\t\t\t}\n\t\t\t\t\tnumgbits = actualnumbps - (cp->ccps[cmptno].prec - 1 +\n\t\t\t\t\t band->analgain);\n#if 0\njas_eprintf(\"%d %d mag=%d actual=%d numgbits=%d\\n\", cp->ccps[cmptno].prec, band->analgain, mxmag, actualnumbps, numgbits);\n#endif\n\t\t\t\t\tif (numgbits > mingbits) {\n\t\t\t\t\t\tmingbits = numgbits;\n\t\t\t\t\t}\n\t\t\t\t\tif (!tile->intmode) {\n\t\t\t\t\t\tband->absstepsize = jpc_fix_div(jpc_inttofix(1\n\t\t\t\t\t\t << (band->analgain + 1)),\n\t\t\t\t\t\t band->synweight);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tband->absstepsize = jpc_inttofix(1);\n\t\t\t\t\t}\n\t\t\t\t\tband->stepsize = jpc_abstorelstepsize(\n\t\t\t\t\t band->absstepsize, cp->ccps[cmptno].prec +\n\t\t\t\t\t band->analgain);\n\t\t\t\t\tband->numbps = cp->tccp.numgbits +\n\t\t\t\t\t JPC_QCX_GETEXPN(band->stepsize) - 1;\n\n\t\t\t\t\tif ((!tile->intmode) && band->data) {\n\t\t\t\t\t\tjpc_quantize(band->data, band->absstepsize);\n\t\t\t\t\t}\n\n\t\t\t\t\tcomp->stepsizes[absbandno] = band->stepsize;\n\t\t\t\t\t++absbandno;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tassert(JPC_FIX_FRACBITS >= JPC_NUMEXTRABITS);\n\t\t\tif (!tile->intmode) {\n\t\t\t\tjas_matrix_divpow2(comp->data, JPC_FIX_FRACBITS - JPC_NUMEXTRABITS);\n\t\t\t} else {\n\t\t\t\tjas_matrix_asl(comp->data, JPC_NUMEXTRABITS);\n\t\t\t}\n\n#if 0\njas_eprintf(\"mingbits %d\\n\", mingbits);\n#endif\n\t\t\tif (mingbits > cp->tccp.numgbits) {\n\t\t\t\tjas_eprintf(\"error: too few guard bits (need at least %d)\\n\",\n\t\t\t\t mingbits);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\n\t\tif (!(enc->tmpstream = jas_stream_memopen(0, 0))) {\n\t\t\tjas_eprintf(\"cannot open tmp file\\n\");\n\t\t\treturn -1;\n\t\t}\n\n\t\t/* Write the tile header. */\n\t\tif (!(enc->mrk = jpc_ms_create(JPC_MS_SOT))) {\n\t\t\treturn -1;\n\t\t}\n\t\tsot = &enc->mrk->parms.sot;\n\t\tsot->len = 0;\n\t\tsot->tileno = tileno;\n\t\tsot->partno = 0;\n\t\tsot->numparts = 1;\n\t\tif (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {\n\t\t\tjas_eprintf(\"cannot write SOT marker\\n\");\n\t\t\treturn -1;\n\t\t}\n\t\tjpc_ms_destroy(enc->mrk);\n\t\tenc->mrk = 0;\n\n/************************************************************************/\n/************************************************************************/\n/************************************************************************/\n\n\t\ttccp = &cp->tccp;\n\t\tfor (cmptno = 0; cmptno < JAS_CAST(int, cp->numcmpts); ++cmptno) {\n\t\t\tcomp = &tile->tcmpts[cmptno];\n\t\t\tif (comp->numrlvls != tccp->maxrlvls) {\n\t\t\t\tif (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n/* XXX = this is not really correct. we are using comp #0's precint sizes\nand other characteristics */\n\t\t\t\tcomp = &tile->tcmpts[0];\n\t\t\t\tcod = &enc->mrk->parms.cod;\n\t\t\t\tcod->compparms.csty = 0;\n\t\t\t\tcod->compparms.numdlvls = comp->numrlvls - 1;\n\t\t\t\tcod->prg = tile->prg;\n\t\t\t\tcod->numlyrs = tile->numlyrs;\n\t\t\t\tcod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(comp->cblkwidthexpn);\n\t\t\t\tcod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(comp->cblkheightexpn);\n\t\t\t\tcod->compparms.cblksty = comp->cblksty;\n\t\t\t\tcod->compparms.qmfbid = comp->qmfbid;\n\t\t\t\tcod->mctrans = (tile->mctid != JPC_MCT_NONE);\n\t\t\t\tfor (i = 0; i < comp->numrlvls; ++i) {\n\t\t\t\t\tcod->compparms.rlvls[i].parwidthval = comp->rlvls[i].prcwidthexpn;\n\t\t\t\t\tcod->compparms.rlvls[i].parheightval = comp->rlvls[i].prcheightexpn;\n\t\t\t\t}\n\t\t\t\tif (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tjpc_ms_destroy(enc->mrk);\n\t\t\t\tenc->mrk = 0;\n\t\t\t}\n\t\t}\n\n\t\tfor (cmptno = 0, comp = tile->tcmpts; cmptno < JAS_CAST(int,\n\t\t cp->numcmpts); ++cmptno, ++comp) {\n\t\t\tccps = &cp->ccps[cmptno];\n\t\t\tif (JAS_CAST(int, ccps->numstepsizes) == comp->numstepsizes) {\n\t\t\t\tsamestepsizes = 1;\n\t\t\t\tfor (bandno = 0; bandno < JAS_CAST(int, ccps->numstepsizes);\n\t\t\t\t ++bandno) {\n\t\t\t\t\tif (ccps->stepsizes[bandno] != comp->stepsizes[bandno]) {\n\t\t\t\t\t\tsamestepsizes = 0;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsamestepsizes = 0;\n\t\t\t}\n\t\t\tif (!samestepsizes) {\n\t\t\t\tif (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tqcc = &enc->mrk->parms.qcc;\n\t\t\t\tqcc->compno = cmptno;\n\t\t\t\tqcc->compparms.numguard = cp->tccp.numgbits;\n\t\t\t\tqcc->compparms.qntsty = (comp->qmfbid == JPC_COX_INS) ?\n\t\t\t\t JPC_QCX_SEQNT : JPC_QCX_NOQNT;\n\t\t\t\tqcc->compparms.numstepsizes = comp->numstepsizes;\n\t\t\t\tqcc->compparms.stepsizes = comp->stepsizes;\n\t\t\t\tif (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tqcc->compparms.stepsizes = 0;\n\t\t\t\tjpc_ms_destroy(enc->mrk);\n\t\t\t\tenc->mrk = 0;\n\t\t\t}\n\t\t}\n\n\t\t/* Write a SOD marker to indicate the end of the tile header. */\n\t\tif (!(enc->mrk = jpc_ms_create(JPC_MS_SOD))) {\n\t\t\treturn -1;\n\t\t}\n\t\tif (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {\n\t\t\tjas_eprintf(\"cannot write SOD marker\\n\");\n\t\t\treturn -1;\n\t\t}\n\t\tjpc_ms_destroy(enc->mrk);\n\t\tenc->mrk = 0;\n\t\ttilehdrlen = jas_stream_getrwcount(enc->tmpstream);\n\t\tassert(tilehdrlen >= 0);\n\n/************************************************************************/\n/************************************************************************/\n/************************************************************************/\n\n\t\tif (jpc_enc_enccblks(enc)) {\n\t\t\tabort();\n\t\t\treturn -1;\n\t\t}\n\n\t\tcp = enc->cp;\n\t\trho = (double) (tile->brx - tile->tlx) * (tile->bry - tile->tly) /\n\t\t ((cp->refgrdwidth - cp->imgareatlx) * (cp->refgrdheight -\n\t\t cp->imgareatly));\n\t\ttile->rawsize = cp->rawsize * rho;\n\n\t\tfor (lyrno = 0; lyrno < tile->numlyrs - 1; ++lyrno) {\n\t\t\ttile->lyrsizes[lyrno] = tile->rawsize * jpc_fixtodbl(\n\t\t\t cp->tcp.ilyrrates[lyrno]);\n\t\t}\n#if !defined(__clang__)\n\t\t// WARNING:\n\t\t// Some versions of Clang (e.g., 3.7.1 and 3.8.1) appear to generate\n\t\t// incorrect code for the following line.\n\t\ttile->lyrsizes[tile->numlyrs - 1] =\n\t\t (cp->totalsize != UINT_FAST32_MAX) ?\n\t\t (rho * enc->mainbodysize) : UINT_FAST32_MAX;\n#else\n\t\tif (cp->totalsize != UINT_FAST32_MAX) {\n\t\t\ttile->lyrsizes[tile->numlyrs - 1] = (rho * enc->mainbodysize);\n\t\t} else {\n\t\t\ttile->lyrsizes[tile->numlyrs - 1] = UINT_FAST32_MAX;\n\t\t}\n#endif\n//jas_eprintf(\"TESTING %ld %ld\\n\", cp->totalsize != UINT_FAST32_MAX, tile->lyrsizes[0]);\n\t\tfor (lyrno = 0; lyrno < tile->numlyrs; ++lyrno) {\n\t\t\tif (tile->lyrsizes[lyrno] != UINT_FAST32_MAX) {\n\t\t\t\tif (JAS_CAST(uint_fast32_t, tilehdrlen) <= tile->lyrsizes[lyrno]) {\n\t\t\t\t\ttile->lyrsizes[lyrno] -= tilehdrlen;\n\t\t\t\t} else {\n\t\t\t\t\ttile->lyrsizes[lyrno] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (rateallocate(enc, tile->numlyrs, tile->lyrsizes)) {\n\t\t\treturn -1;\n\t\t}\n\n#if 0\njas_eprintf(\"ENCODE TILE DATA\\n\");\n#endif\n\t\tif (jpc_enc_encodetiledata(enc)) {\n\t\t\tjas_eprintf(\"dotile failed\\n\");\n\t\t\treturn -1;\n\t\t}\n\n/************************************************************************/\n/************************************************************************/\n/************************************************************************/\n\n/************************************************************************/\n/************************************************************************/\n/************************************************************************/\n\n\t\ttilelen = jas_stream_tell(enc->tmpstream);\n\n\t\tif (jas_stream_seek(enc->tmpstream, 6, SEEK_SET) < 0) {\n\t\t\treturn -1;\n\t\t}\n\t\tjpc_putuint32(enc->tmpstream, tilelen);\n\n\t\tif (jas_stream_seek(enc->tmpstream, 0, SEEK_SET) < 0) {\n\t\t\treturn -1;\n\t\t}\n\t\tif (jpc_putdata(enc->out, enc->tmpstream, -1)) {\n\t\t\treturn -1;\n\t\t}\n\t\tenc->len += tilelen;\n\n\t\tjas_stream_close(enc->tmpstream);\n\t\tenc->tmpstream = 0;\n\n\t\tjpc_enc_tile_destroy(enc->curtile);\n\t\tenc->curtile = 0;\n\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'jpc_math: split jpc_firstone() in int/jpc_fix_t overloads\n\nFixes CVE-2018-9055 (denial of service via a reachable assertion due\nto integer overflow).\n\nBased on a patch from Fridrich Strba . Instead of\nswitching to `int_fast32_t`, this patch splits jpc_firstone() into two\noverloads, one for `int` and one for `jpc_fix_t`. This is safer\nagainst future changes on `jpc_fix_t`. To avoid the overhead of 64\nbit integer math on 32 bit CPUs, this leaves the `int` overload\naround.\n\nCloses https://github.com/jasper-maint/jasper/issues/9'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: rb_push_glob(VALUE str, VALUE base, int flags) /* '\\0' is delimiter */\n{\n long offset = 0;\n VALUE ary;\n\n GlobPathValue(str, TRUE);\n ary = rb_ary_new();\n\n while (offset < RSTRING_LEN(str)) {\n\tchar *p, *pend;\n\tint status;\n\tp = RSTRING_PTR(str) + offset;\n\tstatus = push_glob(ary, rb_enc_str_new(p, strlen(p), rb_enc_get(str)),\n\t\t\t base, flags);\n\tif (status) GLOB_JUMP_TAG(status);\n\tif (offset >= RSTRING_LEN(str)) break;\n\tp += strlen(p) + 1;\n\tpend = RSTRING_PTR(str) + RSTRING_LEN(str);\n\twhile (p < pend && !*p)\n\t p++;\n\toffset = p - RSTRING_PTR(str);\n }\n\n return ary;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'dir.c: check NUL bytes\n\n* dir.c (GlobPathValue): should be used in rb_push_glob only.\n other methods should use FilePathValue.\n https://hackerone.com/reports/302338\n\n* dir.c (rb_push_glob): expand GlobPathValue\n\ngit-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@62989 b2dd03c8-39d4-4d8f-98ff-823fe69b080e'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int sanity_check_raw_super(struct super_block *sb,\n\t\t\tstruct f2fs_super_block *raw_super)\n{\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_CACHE_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_CACHE_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/* 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\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'f2fs: do more integrity verification for superblock\n\nDo more sanity check for superblock during ->mount.\n\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 int __get_data_block(struct inode *inode, sector_t iblock,\n\t\t\tstruct buffer_head *bh, int create, int flag,\n\t\t\tpgoff_t *next_pgofs)\n{\n\tstruct f2fs_map_blocks map;\n\tint err;\n\n\tmap.m_lblk = iblock;\n\tmap.m_len = bh->b_size >> inode->i_blkbits;\n\tmap.m_next_pgofs = next_pgofs;\n\n\terr = f2fs_map_blocks(inode, &map, create, flag);\n\tif (!err) {\n\t\tmap_bh(bh, inode->i_sb, map.m_pblk);\n\t\tbh->b_state = (bh->b_state & ~F2FS_MAP_FLAGS) | map.m_flags;\n\t\tbh->b_size = map.m_len << inode->i_blkbits;\n\t}\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'f2fs: fix a dead loop in f2fs_fiemap()\n\nA dead loop can be triggered in f2fs_fiemap() using the test case\nas below:\n\n\t...\n\tfd = open();\n\tfallocate(fd, 0, 0, 4294967296);\n\tioctl(fd, FS_IOC_FIEMAP, fiemap_buf);\n\t...\n\nIt's caused by an overflow in __get_data_block():\n\t...\n\tbh->b_size = map.m_len << inode->i_blkbits;\n\t...\nmap.m_len is an unsigned int, and bh->b_size is a size_t which is 64 bits\non 64 bits archtecture, type conversion from an unsigned int to a size_t\nwill result in an overflow.\n\nIn the above-mentioned case, bh->b_size will be zero, and f2fs_fiemap()\nwill call get_data_block() at block 0 again an again.\n\nFix this by adding a force conversion before left shift.\n\nSigned-off-by: Wei Fang \nAcked-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: xz_head(xz_statep state)\n{\n lzma_stream *strm = &(state->strm);\n lzma_stream init = LZMA_STREAM_INIT;\n int flags;\n unsigned len;\n\n /* allocate read buffers and inflate memory */\n if (state->size == 0) {\n /* allocate buffers */\n state->in = xmlMalloc(state->want);\n state->out = xmlMalloc(state->want << 1);\n if (state->in == NULL || state->out == NULL) {\n if (state->out != NULL)\n xmlFree(state->out);\n if (state->in != NULL)\n xmlFree(state->in);\n xz_error(state, LZMA_MEM_ERROR, \"out of memory\");\n return -1;\n }\n state->size = state->want;\n\n /* allocate decoder memory */\n state->strm = init;\n state->strm.avail_in = 0;\n state->strm.next_in = NULL;\n if (lzma_auto_decoder(&state->strm, UINT64_MAX, 0) != LZMA_OK) {\n xmlFree(state->out);\n xmlFree(state->in);\n state->size = 0;\n xz_error(state, LZMA_MEM_ERROR, \"out of memory\");\n return -1;\n }\n#ifdef HAVE_ZLIB_H\n /* allocate inflate memory */\n state->zstrm.zalloc = Z_NULL;\n state->zstrm.zfree = Z_NULL;\n state->zstrm.opaque = Z_NULL;\n state->zstrm.avail_in = 0;\n state->zstrm.next_in = Z_NULL;\n if (state->init == 0) {\n if (inflateInit2(&(state->zstrm), -15) != Z_OK) {/* raw inflate */\n xmlFree(state->out);\n xmlFree(state->in);\n state->size = 0;\n xz_error(state, LZMA_MEM_ERROR, \"out of memory\");\n return -1;\n }\n state->init = 1;\n }\n#endif\n }\n\n /* get some data in the input buffer */\n if (strm->avail_in == 0) {\n if (xz_avail(state) == -1)\n return -1;\n if (strm->avail_in == 0)\n return 0;\n }\n\n /* look for the xz magic header bytes */\n if (is_format_xz(state) || is_format_lzma(state)) {\n state->how = LZMA;\n state->direct = 0;\n return 0;\n }\n#ifdef HAVE_ZLIB_H\n /* look for the gzip magic header bytes 31 and 139 */\n if (strm->next_in[0] == 31) {\n strm->avail_in--;\n strm->next_in++;\n if (strm->avail_in == 0 && xz_avail(state) == -1)\n return -1;\n if (strm->avail_in && strm->next_in[0] == 139) {\n /* we have a gzip header, woo hoo! */\n strm->avail_in--;\n strm->next_in++;\n\n /* skip rest of header */\n if (NEXT() != 8) { /* compression method */\n xz_error(state, LZMA_DATA_ERROR,\n \"unknown compression method\");\n return -1;\n }\n flags = NEXT();\n if (flags & 0xe0) { /* reserved flag bits */\n xz_error(state, LZMA_DATA_ERROR,\n \"unknown header flags set\");\n return -1;\n }\n NEXT(); /* modification time */\n NEXT();\n NEXT();\n NEXT();\n NEXT(); /* extra flags */\n NEXT(); /* operating system */\n if (flags & 4) { /* extra field */\n len = (unsigned) NEXT();\n len += (unsigned) NEXT() << 8;\n while (len--)\n if (NEXT() < 0)\n break;\n }\n if (flags & 8) /* file name */\n while (NEXT() > 0) ;\n if (flags & 16) /* comment */\n while (NEXT() > 0) ;\n if (flags & 2) { /* header crc */\n NEXT();\n NEXT();\n }\n /* an unexpected end of file is not checked for here -- it will be\n * noticed on the first request for uncompressed data */\n\n /* set up for decompression */\n inflateReset(&state->zstrm);\n state->zstrm.adler = crc32(0L, Z_NULL, 0);\n state->how = GZIP;\n state->direct = 0;\n return 0;\n } else {\n /* not a gzip file -- save first byte (31) and fall to raw i/o */\n state->out[0] = 31;\n state->have = 1;\n }\n }\n#endif\n\n /* doing raw i/o, save start of raw data for seeking, copy any leftover\n * input to output -- this assumes that the output buffer is larger than\n * the input buffer, which also assures space for gzungetc() */\n state->raw = state->pos;\n state->next = state->out;\n if (strm->avail_in) {\n memcpy(state->next + state->have, strm->next_in, strm->avail_in);\n state->have += strm->avail_in;\n strm->avail_in = 0;\n }\n state->how = COPY;\n state->direct = 1;\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-770'], 'message': 'Set memory limit for LZMA decompression\n\nOtherwise malicious LZMA compressed files could consume large amounts\nof memory when decompressed.\n\nAccording to the xz man page, files compressed with `xz -9` currently\nrequire 65 MB to decompress, so set the limit to 100 MB.\n\nShould fix bug 786696.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ParseWave64HeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config)\n{\n int64_t total_samples = 0, infilesize;\n Wave64ChunkHeader chunk_header;\n Wave64FileHeader filehdr;\n WaveHeader WaveHeader;\n uint32_t bcount;\n\n infilesize = DoGetFileSize (infile);\n memcpy (&filehdr, fourcc, 4);\n\n if (!DoReadFile (infile, ((char *) &filehdr) + 4, sizeof (Wave64FileHeader) - 4, &bcount) ||\n bcount != sizeof (Wave64FileHeader) - 4 || memcmp (filehdr.ckID, riff_guid, sizeof (riff_guid)) ||\n memcmp (filehdr.formType, wave_guid, sizeof (wave_guid))) {\n error_line (\"%s is not a valid .W64 file!\", infilename);\n return WAVPACK_SOFT_ERROR;\n }\n else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&\n !WavpackAddWrapper (wpc, &filehdr, sizeof (filehdr))) {\n error_line (\"%s\", WavpackGetErrorMessage (wpc));\n return WAVPACK_SOFT_ERROR;\n }\n\n#if 1 // this might be a little too picky...\n WavpackLittleEndianToNative (&filehdr, Wave64ChunkHeaderFormat);\n\n if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) &&\n filehdr.ckSize && filehdr.ckSize + 1 && filehdr.ckSize != infilesize) {\n error_line (\"%s is not a valid .W64 file!\", infilename);\n return WAVPACK_SOFT_ERROR;\n }\n#endif\n\n // loop through all elements of the wave64 header\n // (until the data chuck) and copy them to the output file\n\n while (1) {\n if (!DoReadFile (infile, &chunk_header, sizeof (Wave64ChunkHeader), &bcount) ||\n bcount != sizeof (Wave64ChunkHeader)) {\n error_line (\"%s is not a valid .W64 file!\", infilename);\n return WAVPACK_SOFT_ERROR;\n }\n else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&\n !WavpackAddWrapper (wpc, &chunk_header, sizeof (Wave64ChunkHeader))) {\n error_line (\"%s\", WavpackGetErrorMessage (wpc));\n return WAVPACK_SOFT_ERROR;\n }\n\n WavpackLittleEndianToNative (&chunk_header, Wave64ChunkHeaderFormat);\n chunk_header.ckSize -= sizeof (chunk_header);\n\n // if it's the format chunk, we want to get some info out of there and\n // make sure it's a .wav file we can handle\n\n if (!memcmp (chunk_header.ckID, fmt_guid, sizeof (fmt_guid))) {\n int supported = TRUE, format;\n\n chunk_header.ckSize = (chunk_header.ckSize + 7) & ~7L;\n\n if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) ||\n !DoReadFile (infile, &WaveHeader, (uint32_t) chunk_header.ckSize, &bcount) ||\n bcount != chunk_header.ckSize) {\n error_line (\"%s is not a valid .W64 file!\", infilename);\n return WAVPACK_SOFT_ERROR;\n }\n else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&\n !WavpackAddWrapper (wpc, &WaveHeader, (uint32_t) 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 .W64 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 W64 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\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 (!memcmp (chunk_header.ckID, data_guid, sizeof (data_guid))) { // on the data chunk, get size and exit loop\n\n if (!WaveHeader.NumChannels) { // make sure we saw \"fmt\" chunk\n error_line (\"%s is not a valid .W64 file!\", infilename);\n return WAVPACK_SOFT_ERROR;\n }\n\n if ((config->qmode & QMODE_IGNORE_LENGTH) || chunk_header.ckSize <= 0) {\n config->qmode |= QMODE_IGNORE_LENGTH;\n\n if (infilesize && DoGetFilePosition (infile) != -1)\n total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign;\n else\n total_samples = -1;\n }\n else {\n if (infilesize && infilesize - chunk_header.ckSize > 16777216) {\n error_line (\"this .W64 file has over 16 MB of extra RIFF data, probably is corrupt!\");\n return WAVPACK_SOFT_ERROR;\n }\n\n total_samples = chunk_header.ckSize / WaveHeader.BlockAlign;\n\n if (!total_samples) {\n error_line (\"this .W64 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 int bytes_to_copy = (chunk_header.ckSize + 7) & ~7L;\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: bool DaemonServer::ms_verify_authorizer(Connection *con,\n int peer_type,\n int protocol,\n ceph::bufferlist& authorizer_data,\n ceph::bufferlist& authorizer_reply,\n bool& is_valid,\n CryptoKey& session_key)\n{\n AuthAuthorizeHandler *handler = nullptr;\n if (peer_type == CEPH_ENTITY_TYPE_OSD ||\n peer_type == CEPH_ENTITY_TYPE_MON ||\n peer_type == CEPH_ENTITY_TYPE_MDS ||\n peer_type == CEPH_ENTITY_TYPE_MGR) {\n handler = auth_cluster_registry.get_handler(protocol);\n } else {\n handler = auth_service_registry.get_handler(protocol);\n }\n if (!handler) {\n dout(0) << \"No AuthAuthorizeHandler found for protocol \" << protocol << dendl;\n is_valid = false;\n return true;\n }\n\n MgrSessionRef s(new MgrSession(cct));\n s->inst.addr = con->get_peer_addr();\n AuthCapsInfo caps_info;\n\n RotatingKeyRing *keys = monc->rotating_secrets.get();\n if (keys) {\n is_valid = handler->verify_authorizer(\n cct, keys,\n authorizer_data,\n authorizer_reply, s->entity_name,\n s->global_id, caps_info,\n session_key);\n } else {\n dout(10) << __func__ << \" no rotating_keys (yet), denied\" << dendl;\n is_valid = false;\n }\n\n if (is_valid) {\n if (caps_info.allow_all) {\n dout(10) << \" session \" << s << \" \" << s->entity_name\n\t << \" allow_all\" << dendl;\n s->caps.set_allow_all();\n }\n if (caps_info.caps.length() > 0) {\n bufferlist::iterator p = caps_info.caps.begin();\n string str;\n try {\n\t::decode(str, p);\n }\n catch (buffer::error& e) {\n }\n bool success = s->caps.parse(str);\n if (success) {\n\tdout(10) << \" session \" << s << \" \" << s->entity_name\n\t\t << \" has caps \" << s->caps << \" '\" << str << \"'\" << dendl;\n } else {\n\tdout(10) << \" session \" << s << \" \" << s->entity_name\n\t\t << \" failed to parse caps '\" << str << \"'\" << dendl;\n\tis_valid = false;\n }\n }\n con->set_priv(s->get());\n\n if (peer_type == CEPH_ENTITY_TYPE_OSD) {\n Mutex::Locker l(lock);\n s->osd_id = atoi(s->entity_name.get_id().c_str());\n dout(10) << \"registering osd.\" << s->osd_id << \" session \"\n\t << s << \" con \" << con << dendl;\n osd_cons[s->osd_id].insert(con);\n }\n }\n\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge\n\nAllow the accepting side of a connection to reject an initial authorizer\nwith a random challenge. The connecting side then has to respond with an\nupdated authorizer proving they are able to decrypt the service's challenge\nand that the new authorizer was produced for this specific connection\ninstance.\n\nThe accepting side requires this challenge and response unconditionally\nif the client side advertises they have the feature bit. Servers wishing\nto require this improved level of authentication simply have to require\nthe appropriate feature.\n\nSigned-off-by: Sage Weil \n(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)\n\n# Conflicts:\n#\tsrc/auth/Auth.h\n#\tsrc/auth/cephx/CephxProtocol.cc\n#\tsrc/auth/cephx/CephxProtocol.h\n#\tsrc/auth/none/AuthNoneProtocol.h\n#\tsrc/msg/Dispatcher.h\n#\tsrc/msg/async/AsyncConnection.cc\n\n- const_iterator\n- ::decode vs decode\n- AsyncConnection ctor arg noise\n- get_random_bytes(), not cct->random()'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool ms_verify_authorizer(Connection *con, int peer_type,\n\t\t\t int protocol, bufferlist& authorizer_data, bufferlist& authorizer_reply,\n\t\t\t bool& isvalid, CryptoKey& session_key) override {\n isvalid = true;\n return true;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge\n\nAllow the accepting side of a connection to reject an initial authorizer\nwith a random challenge. The connecting side then has to respond with an\nupdated authorizer proving they are able to decrypt the service's challenge\nand that the new authorizer was produced for this specific connection\ninstance.\n\nThe accepting side requires this challenge and response unconditionally\nif the client side advertises they have the feature bit. Servers wishing\nto require this improved level of authentication simply have to require\nthe appropriate feature.\n\nSigned-off-by: Sage Weil \n(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)\n\n# Conflicts:\n#\tsrc/auth/Auth.h\n#\tsrc/auth/cephx/CephxProtocol.cc\n#\tsrc/auth/cephx/CephxProtocol.h\n#\tsrc/auth/none/AuthNoneProtocol.h\n#\tsrc/msg/Dispatcher.h\n#\tsrc/msg/async/AsyncConnection.cc\n\n- const_iterator\n- ::decode vs decode\n- AsyncConnection ctor arg noise\n- get_random_bytes(), not cct->random()'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool cephx_verify_authorizer(CephContext *cct, KeyStore *keys,\n\t\t\t bufferlist::iterator& indata,\n\t\t\t CephXServiceTicketInfo& ticket_info, bufferlist& reply_bl)\n{\n __u8 authorizer_v;\n uint32_t service_id;\n uint64_t global_id;\n CryptoKey service_secret;\n // ticket blob\n CephXTicketBlob ticket;\n\n\n try {\n ::decode(authorizer_v, indata);\n ::decode(global_id, indata);\n ::decode(service_id, indata);\n ::decode(ticket, indata);\n } catch (buffer::end_of_buffer &e) {\n // Unable to decode!\n return false;\n }\n ldout(cct, 10) << \"verify_authorizer decrypted service \"\n\t << ceph_entity_type_name(service_id)\n\t << \" secret_id=\" << ticket.secret_id << dendl;\n\n if (ticket.secret_id == (uint64_t)-1) {\n EntityName name;\n name.set_type(service_id);\n if (!keys->get_secret(name, service_secret)) {\n ldout(cct, 0) << \"verify_authorizer could not get general service secret for service \"\n\t << ceph_entity_type_name(service_id) << \" secret_id=\" << ticket.secret_id << dendl;\n return false;\n }\n } else {\n if (!keys->get_service_secret(service_id, ticket.secret_id, service_secret)) {\n ldout(cct, 0) << \"verify_authorizer could not get service secret for service \"\n\t << ceph_entity_type_name(service_id) << \" secret_id=\" << ticket.secret_id << dendl;\n if (cct->_conf->auth_debug && ticket.secret_id == 0)\n\tassert(0 == \"got secret_id=0\");\n return false;\n }\n }\n std::string error;\n if (!service_secret.get_secret().length())\n error = \"invalid key\"; // Bad key?\n else\n decode_decrypt_enc_bl(cct, ticket_info, service_secret, ticket.blob, error);\n if (!error.empty()) {\n ldout(cct, 0) << \"verify_authorizer could not decrypt ticket info: error: \"\n << error << dendl;\n return false;\n }\n\n if (ticket_info.ticket.global_id != global_id) {\n ldout(cct, 0) << \"verify_authorizer global_id mismatch: declared id=\" << global_id\n\t << \" ticket_id=\" << ticket_info.ticket.global_id << dendl;\n return false;\n }\n\n ldout(cct, 10) << \"verify_authorizer global_id=\" << global_id << dendl;\n\n // CephXAuthorize\n CephXAuthorize auth_msg;\n if (decode_decrypt(cct, auth_msg, ticket_info.session_key, indata, error)) {\n ldout(cct, 0) << \"verify_authorizercould not decrypt authorize request with error: \"\n << error << dendl;\n return false;\n }\n\n /*\n * Reply authorizer:\n * {timestamp + 1}^session_key\n */\n CephXAuthorizeReply reply;\n // reply.trans_id = auth_msg.trans_id;\n reply.nonce_plus_one = auth_msg.nonce + 1;\n if (encode_encrypt(cct, reply, ticket_info.session_key, reply_bl, error)) {\n ldout(cct, 10) << \"verify_authorizer: encode_encrypt error: \" << error << dendl;\n return false;\n }\n\n ldout(cct, 10) << \"verify_authorizer ok nonce \" << hex << auth_msg.nonce << dec\n\t << \" reply_bl.length()=\" << reply_bl.length() << dendl;\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge\n\nAllow the accepting side of a connection to reject an initial authorizer\nwith a random challenge. The connecting side then has to respond with an\nupdated authorizer proving they are able to decrypt the service's challenge\nand that the new authorizer was produced for this specific connection\ninstance.\n\nThe accepting side requires this challenge and response unconditionally\nif the client side advertises they have the feature bit. Servers wishing\nto require this improved level of authentication simply have to require\nthe appropriate feature.\n\nSigned-off-by: Sage Weil \n(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)\n\n# Conflicts:\n#\tsrc/auth/Auth.h\n#\tsrc/auth/cephx/CephxProtocol.cc\n#\tsrc/auth/cephx/CephxProtocol.h\n#\tsrc/auth/none/AuthNoneProtocol.h\n#\tsrc/msg/Dispatcher.h\n#\tsrc/msg/async/AsyncConnection.cc\n\n- const_iterator\n- ::decode vs decode\n- AsyncConnection ctor arg noise\n- get_random_bytes(), not cct->random()'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TIFFWriteDirectorySec(TIFF* tif, int isimage, int imagedone, uint64* pdiroff)\n{\n\tstatic const char module[] = \"TIFFWriteDirectorySec\";\n\tuint32 ndir;\n\tTIFFDirEntry* dir;\n\tuint32 dirsize;\n\tvoid* dirmem;\n\tuint32 m;\n\tif (tif->tif_mode == O_RDONLY)\n\t\treturn (1);\n\n _TIFFFillStriles( tif );\n \n\t/*\n\t * Clear write state so that subsequent images with\n\t * different characteristics get the right buffers\n\t * setup for them.\n\t */\n\tif (imagedone)\n\t{\n\t\tif (tif->tif_flags & TIFF_POSTENCODE)\n\t\t{\n\t\t\ttif->tif_flags &= ~TIFF_POSTENCODE;\n\t\t\tif (!(*tif->tif_postencode)(tif))\n\t\t\t{\n\t\t\t\tTIFFErrorExt(tif->tif_clientdata,module,\n\t\t\t\t \"Error post-encoding before directory write\");\n\t\t\t\treturn (0);\n\t\t\t}\n\t\t}\n\t\t(*tif->tif_close)(tif); /* shutdown encoder */\n\t\t/*\n\t\t * Flush any data that might have been written\n\t\t * by the compression close+cleanup routines. But\n * be careful not to write stuff if we didn't add data\n * in the previous steps as the \"rawcc\" data may well be\n * a previously read tile/strip in mixed read/write mode.\n\t\t */\n\t\tif (tif->tif_rawcc > 0 \n\t\t && (tif->tif_flags & TIFF_BEENWRITING) != 0 )\n\t\t{\n\t\t if( !TIFFFlushData1(tif) )\n {\n\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t \"Error flushing data before directory write\");\n\t\t\treturn (0);\n }\n\t\t}\n\t\tif ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata)\n\t\t{\n\t\t\t_TIFFfree(tif->tif_rawdata);\n\t\t\ttif->tif_rawdata = NULL;\n\t\t\ttif->tif_rawcc = 0;\n\t\t\ttif->tif_rawdatasize = 0;\n tif->tif_rawdataoff = 0;\n tif->tif_rawdataloaded = 0;\n\t\t}\n\t\ttif->tif_flags &= ~(TIFF_BEENWRITING|TIFF_BUFFERSETUP);\n\t}\n\tdir=NULL;\n\tdirmem=NULL;\n\tdirsize=0;\n\twhile (1)\n\t{\n\t\tndir=0;\n\t\tif (isimage)\n\t\t{\n\t\t\tif (TIFFFieldSet(tif,FIELD_IMAGEDIMENSIONS))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagShortLong(tif,&ndir,dir,TIFFTAG_IMAGEWIDTH,tif->tif_dir.td_imagewidth))\n\t\t\t\t\tgoto bad;\n\t\t\t\tif (!TIFFWriteDirectoryTagShortLong(tif,&ndir,dir,TIFFTAG_IMAGELENGTH,tif->tif_dir.td_imagelength))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_TILEDIMENSIONS))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagShortLong(tif,&ndir,dir,TIFFTAG_TILEWIDTH,tif->tif_dir.td_tilewidth))\n\t\t\t\t\tgoto bad;\n\t\t\t\tif (!TIFFWriteDirectoryTagShortLong(tif,&ndir,dir,TIFFTAG_TILELENGTH,tif->tif_dir.td_tilelength))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_RESOLUTION))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagRational(tif,&ndir,dir,TIFFTAG_XRESOLUTION,tif->tif_dir.td_xresolution))\n\t\t\t\t\tgoto bad;\n\t\t\t\tif (!TIFFWriteDirectoryTagRational(tif,&ndir,dir,TIFFTAG_YRESOLUTION,tif->tif_dir.td_yresolution))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_POSITION))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagRational(tif,&ndir,dir,TIFFTAG_XPOSITION,tif->tif_dir.td_xposition))\n\t\t\t\t\tgoto bad;\n\t\t\t\tif (!TIFFWriteDirectoryTagRational(tif,&ndir,dir,TIFFTAG_YPOSITION,tif->tif_dir.td_yposition))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_SUBFILETYPE))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagLong(tif,&ndir,dir,TIFFTAG_SUBFILETYPE,tif->tif_dir.td_subfiletype))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_BITSPERSAMPLE))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagShortPerSample(tif,&ndir,dir,TIFFTAG_BITSPERSAMPLE,tif->tif_dir.td_bitspersample))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_COMPRESSION))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_COMPRESSION,tif->tif_dir.td_compression))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_PHOTOMETRIC))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_PHOTOMETRIC,tif->tif_dir.td_photometric))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_THRESHHOLDING))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_THRESHHOLDING,tif->tif_dir.td_threshholding))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_FILLORDER))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_FILLORDER,tif->tif_dir.td_fillorder))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_ORIENTATION))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_ORIENTATION,tif->tif_dir.td_orientation))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_SAMPLESPERPIXEL))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_SAMPLESPERPIXEL,tif->tif_dir.td_samplesperpixel))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_ROWSPERSTRIP))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagShortLong(tif,&ndir,dir,TIFFTAG_ROWSPERSTRIP,tif->tif_dir.td_rowsperstrip))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_MINSAMPLEVALUE))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagShortPerSample(tif,&ndir,dir,TIFFTAG_MINSAMPLEVALUE,tif->tif_dir.td_minsamplevalue))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_MAXSAMPLEVALUE))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagShortPerSample(tif,&ndir,dir,TIFFTAG_MAXSAMPLEVALUE,tif->tif_dir.td_maxsamplevalue))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_PLANARCONFIG))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_PLANARCONFIG,tif->tif_dir.td_planarconfig))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_RESOLUTIONUNIT))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_RESOLUTIONUNIT,tif->tif_dir.td_resolutionunit))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_PAGENUMBER))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagShortArray(tif,&ndir,dir,TIFFTAG_PAGENUMBER,2,&tif->tif_dir.td_pagenumber[0]))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_STRIPBYTECOUNTS))\n\t\t\t{\n\t\t\t\tif (!isTiled(tif))\n\t\t\t\t{\n\t\t\t\t\tif (!TIFFWriteDirectoryTagLongLong8Array(tif,&ndir,dir,TIFFTAG_STRIPBYTECOUNTS,tif->tif_dir.td_nstrips,tif->tif_dir.td_stripbytecount))\n\t\t\t\t\t\tgoto bad;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (!TIFFWriteDirectoryTagLongLong8Array(tif,&ndir,dir,TIFFTAG_TILEBYTECOUNTS,tif->tif_dir.td_nstrips,tif->tif_dir.td_stripbytecount))\n\t\t\t\t\t\tgoto bad;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_STRIPOFFSETS))\n\t\t\t{\n\t\t\t\tif (!isTiled(tif))\n\t\t\t\t{\n /* td_stripoffset might be NULL in an odd OJPEG case. See\n * tif_dirread.c around line 3634.\n * XXX: OJPEG hack.\n * If a) compression is OJPEG, b) it's not a tiled TIFF,\n * and c) the number of strips is 1,\n * then we tolerate the absence of stripoffsets tag,\n * because, presumably, all required data is in the\n * JpegInterchangeFormat stream.\n * We can get here when using tiffset on such a file.\n * See http://bugzilla.maptools.org/show_bug.cgi?id=2500\n */\n if (tif->tif_dir.td_stripoffset != NULL &&\n !TIFFWriteDirectoryTagLongLong8Array(tif,&ndir,dir,TIFFTAG_STRIPOFFSETS,tif->tif_dir.td_nstrips,tif->tif_dir.td_stripoffset))\n goto bad;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (!TIFFWriteDirectoryTagLongLong8Array(tif,&ndir,dir,TIFFTAG_TILEOFFSETS,tif->tif_dir.td_nstrips,tif->tif_dir.td_stripoffset))\n\t\t\t\t\t\tgoto bad;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_COLORMAP))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagColormap(tif,&ndir,dir))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_EXTRASAMPLES))\n\t\t\t{\n\t\t\t\tif (tif->tif_dir.td_extrasamples)\n\t\t\t\t{\n\t\t\t\t\tuint16 na;\n\t\t\t\t\tuint16* nb;\n\t\t\t\t\tTIFFGetFieldDefaulted(tif,TIFFTAG_EXTRASAMPLES,&na,&nb);\n\t\t\t\t\tif (!TIFFWriteDirectoryTagShortArray(tif,&ndir,dir,TIFFTAG_EXTRASAMPLES,na,nb))\n\t\t\t\t\t\tgoto bad;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_SAMPLEFORMAT))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagShortPerSample(tif,&ndir,dir,TIFFTAG_SAMPLEFORMAT,tif->tif_dir.td_sampleformat))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_SMINSAMPLEVALUE))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagSampleformatArray(tif,&ndir,dir,TIFFTAG_SMINSAMPLEVALUE,tif->tif_dir.td_samplesperpixel,tif->tif_dir.td_sminsamplevalue))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_SMAXSAMPLEVALUE))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagSampleformatArray(tif,&ndir,dir,TIFFTAG_SMAXSAMPLEVALUE,tif->tif_dir.td_samplesperpixel,tif->tif_dir.td_smaxsamplevalue))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_IMAGEDEPTH))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagLong(tif,&ndir,dir,TIFFTAG_IMAGEDEPTH,tif->tif_dir.td_imagedepth))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_TILEDEPTH))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagLong(tif,&ndir,dir,TIFFTAG_TILEDEPTH,tif->tif_dir.td_tiledepth))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_HALFTONEHINTS))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagShortArray(tif,&ndir,dir,TIFFTAG_HALFTONEHINTS,2,&tif->tif_dir.td_halftonehints[0]))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_YCBCRSUBSAMPLING))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagShortArray(tif,&ndir,dir,TIFFTAG_YCBCRSUBSAMPLING,2,&tif->tif_dir.td_ycbcrsubsampling[0]))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_YCBCRPOSITIONING))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_YCBCRPOSITIONING,tif->tif_dir.td_ycbcrpositioning))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_REFBLACKWHITE))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagRationalArray(tif,&ndir,dir,TIFFTAG_REFERENCEBLACKWHITE,6,tif->tif_dir.td_refblackwhite))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_TRANSFERFUNCTION))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagTransferfunction(tif,&ndir,dir))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_INKNAMES))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagAscii(tif,&ndir,dir,TIFFTAG_INKNAMES,tif->tif_dir.td_inknameslen,tif->tif_dir.td_inknames))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tif (TIFFFieldSet(tif,FIELD_SUBIFD))\n\t\t\t{\n\t\t\t\tif (!TIFFWriteDirectoryTagSubifd(tif,&ndir,dir))\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\t{\n\t\t\t\tuint32 n;\n\t\t\t\tfor (n=0; ntif_nfields; n++) {\n\t\t\t\t\tconst TIFFField* o;\n\t\t\t\t\to = tif->tif_fields[n];\n\t\t\t\t\tif ((o->field_bit>=FIELD_CODEC)&&(TIFFFieldSet(tif,o->field_bit)))\n\t\t\t\t\t{\n\t\t\t\t\t\tswitch (o->get_field_type)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcase TIFF_SETGET_ASCII:\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tuint32 pa;\n\t\t\t\t\t\t\t\t\tchar* pb;\n\t\t\t\t\t\t\t\t\tassert(o->field_type==TIFF_ASCII);\n\t\t\t\t\t\t\t\t\tassert(o->field_readcount==TIFF_VARIABLE);\n\t\t\t\t\t\t\t\t\tassert(o->field_passcount==0);\n\t\t\t\t\t\t\t\t\tTIFFGetField(tif,o->field_tag,&pb);\n\t\t\t\t\t\t\t\t\tpa=(uint32)(strlen(pb));\n\t\t\t\t\t\t\t\t\tif (!TIFFWriteDirectoryTagAscii(tif,&ndir,dir,(uint16)o->field_tag,pa,pb))\n\t\t\t\t\t\t\t\t\t\tgoto bad;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase TIFF_SETGET_UINT16:\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tuint16 p;\n\t\t\t\t\t\t\t\t\tassert(o->field_type==TIFF_SHORT);\n\t\t\t\t\t\t\t\t\tassert(o->field_readcount==1);\n\t\t\t\t\t\t\t\t\tassert(o->field_passcount==0);\n\t\t\t\t\t\t\t\t\tTIFFGetField(tif,o->field_tag,&p);\n\t\t\t\t\t\t\t\t\tif (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,(uint16)o->field_tag,p))\n\t\t\t\t\t\t\t\t\t\tgoto bad;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase TIFF_SETGET_UINT32:\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tuint32 p;\n\t\t\t\t\t\t\t\t\tassert(o->field_type==TIFF_LONG);\n\t\t\t\t\t\t\t\t\tassert(o->field_readcount==1);\n\t\t\t\t\t\t\t\t\tassert(o->field_passcount==0);\n\t\t\t\t\t\t\t\t\tTIFFGetField(tif,o->field_tag,&p);\n\t\t\t\t\t\t\t\t\tif (!TIFFWriteDirectoryTagLong(tif,&ndir,dir,(uint16)o->field_tag,p))\n\t\t\t\t\t\t\t\t\t\tgoto bad;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase TIFF_SETGET_C32_UINT8:\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tuint32 pa;\n\t\t\t\t\t\t\t\t\tvoid* pb;\n\t\t\t\t\t\t\t\t\tassert(o->field_type==TIFF_UNDEFINED);\n\t\t\t\t\t\t\t\t\tassert(o->field_readcount==TIFF_VARIABLE2);\n\t\t\t\t\t\t\t\t\tassert(o->field_passcount==1);\n\t\t\t\t\t\t\t\t\tTIFFGetField(tif,o->field_tag,&pa,&pb);\n\t\t\t\t\t\t\t\t\tif (!TIFFWriteDirectoryTagUndefinedArray(tif,&ndir,dir,(uint16)o->field_tag,pa,pb))\n\t\t\t\t\t\t\t\t\t\tgoto bad;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\tassert(0); /* we should never get here */\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (m=0; m<(uint32)(tif->tif_dir.td_customValueCount); m++)\n\t\t{\n uint16 tag = (uint16)tif->tif_dir.td_customValues[m].info->field_tag;\n uint32 count = tif->tif_dir.td_customValues[m].count;\n\t\t\tswitch (tif->tif_dir.td_customValues[m].info->field_type)\n\t\t\t{\n\t\t\t\tcase TIFF_ASCII:\n\t\t\t\t\tif (!TIFFWriteDirectoryTagAscii(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))\n\t\t\t\t\t\tgoto bad;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TIFF_UNDEFINED:\n\t\t\t\t\tif (!TIFFWriteDirectoryTagUndefinedArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))\n\t\t\t\t\t\tgoto bad;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TIFF_BYTE:\n\t\t\t\t\tif (!TIFFWriteDirectoryTagByteArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))\n\t\t\t\t\t\tgoto bad;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TIFF_SBYTE:\n\t\t\t\t\tif (!TIFFWriteDirectoryTagSbyteArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))\n\t\t\t\t\t\tgoto bad;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TIFF_SHORT:\n\t\t\t\t\tif (!TIFFWriteDirectoryTagShortArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))\n\t\t\t\t\t\tgoto bad;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TIFF_SSHORT:\n\t\t\t\t\tif (!TIFFWriteDirectoryTagSshortArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))\n\t\t\t\t\t\tgoto bad;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TIFF_LONG:\n\t\t\t\t\tif (!TIFFWriteDirectoryTagLongArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))\n\t\t\t\t\t\tgoto bad;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TIFF_SLONG:\n\t\t\t\t\tif (!TIFFWriteDirectoryTagSlongArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))\n\t\t\t\t\t\tgoto bad;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TIFF_LONG8:\n\t\t\t\t\tif (!TIFFWriteDirectoryTagLong8Array(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))\n\t\t\t\t\t\tgoto bad;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TIFF_SLONG8:\n\t\t\t\t\tif (!TIFFWriteDirectoryTagSlong8Array(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))\n\t\t\t\t\t\tgoto bad;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TIFF_RATIONAL:\n\t\t\t\t\tif (!TIFFWriteDirectoryTagRationalArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))\n\t\t\t\t\t\tgoto bad;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TIFF_SRATIONAL:\n\t\t\t\t\tif (!TIFFWriteDirectoryTagSrationalArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))\n\t\t\t\t\t\tgoto bad;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TIFF_FLOAT:\n\t\t\t\t\tif (!TIFFWriteDirectoryTagFloatArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))\n\t\t\t\t\t\tgoto bad;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TIFF_DOUBLE:\n\t\t\t\t\tif (!TIFFWriteDirectoryTagDoubleArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))\n\t\t\t\t\t\tgoto bad;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TIFF_IFD:\n\t\t\t\t\tif (!TIFFWriteDirectoryTagIfdArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))\n\t\t\t\t\t\tgoto bad;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TIFF_IFD8:\n\t\t\t\t\tif (!TIFFWriteDirectoryTagIfdIfd8Array(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))\n\t\t\t\t\t\tgoto bad;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tassert(0); /* we should never get here */\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (dir!=NULL)\n\t\t\tbreak;\n\t\tdir=_TIFFmalloc(ndir*sizeof(TIFFDirEntry));\n\t\tif (dir==NULL)\n\t\t{\n\t\t\tTIFFErrorExt(tif->tif_clientdata,module,\"Out of memory\");\n\t\t\tgoto bad;\n\t\t}\n\t\tif (isimage)\n\t\t{\n\t\t\tif ((tif->tif_diroff==0)&&(!TIFFLinkDirectory(tif)))\n\t\t\t\tgoto bad;\n\t\t}\n\t\telse\n\t\t\ttif->tif_diroff=(TIFFSeekFile(tif,0,SEEK_END)+1)&(~((toff_t)1));\n\t\tif (pdiroff!=NULL)\n\t\t\t*pdiroff=tif->tif_diroff;\n\t\tif (!(tif->tif_flags&TIFF_BIGTIFF))\n\t\t\tdirsize=2+ndir*12+4;\n\t\telse\n\t\t\tdirsize=8+ndir*20+8;\n\t\ttif->tif_dataoff=tif->tif_diroff+dirsize;\n\t\tif (!(tif->tif_flags&TIFF_BIGTIFF))\n\t\t\ttif->tif_dataoff=(uint32)tif->tif_dataoff;\n\t\tif ((tif->tif_dataofftif_diroff)||(tif->tif_dataoff<(uint64)dirsize))\n\t\t{\n\t\t\tTIFFErrorExt(tif->tif_clientdata,module,\"Maximum TIFF file size exceeded\");\n\t\t\tgoto bad;\n\t\t}\n\t\tif (tif->tif_dataoff&1)\n\t\t\ttif->tif_dataoff++;\n\t\tif (isimage)\n\t\t\ttif->tif_curdir++;\n\t}\n\tif (isimage)\n\t{\n\t\tif (TIFFFieldSet(tif,FIELD_SUBIFD)&&(tif->tif_subifdoff==0))\n\t\t{\n\t\t\tuint32 na;\n\t\t\tTIFFDirEntry* nb;\n\t\t\tfor (na=0, nb=dir; ; na++, nb++)\n\t\t\t{\n\t\t\t\tif( na == ndir )\n {\n TIFFErrorExt(tif->tif_clientdata,module,\n \"Cannot find SubIFD tag\");\n goto bad;\n }\n\t\t\t\tif (nb->tdir_tag==TIFFTAG_SUBIFD)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!(tif->tif_flags&TIFF_BIGTIFF))\n\t\t\t\ttif->tif_subifdoff=tif->tif_diroff+2+na*12+8;\n\t\t\telse\n\t\t\t\ttif->tif_subifdoff=tif->tif_diroff+8+na*20+12;\n\t\t}\n\t}\n\tdirmem=_TIFFmalloc(dirsize);\n\tif (dirmem==NULL)\n\t{\n\t\tTIFFErrorExt(tif->tif_clientdata,module,\"Out of memory\");\n\t\tgoto bad;\n\t}\n\tif (!(tif->tif_flags&TIFF_BIGTIFF))\n\t{\n\t\tuint8* n;\n\t\tuint32 nTmp;\n\t\tTIFFDirEntry* o;\n\t\tn=dirmem;\n\t\t*(uint16*)n=(uint16)ndir;\n\t\tif (tif->tif_flags&TIFF_SWAB)\n\t\t\tTIFFSwabShort((uint16*)n);\n\t\tn+=2;\n\t\to=dir;\n\t\tfor (m=0; mtdir_tag;\n\t\t\tif (tif->tif_flags&TIFF_SWAB)\n\t\t\t\tTIFFSwabShort((uint16*)n);\n\t\t\tn+=2;\n\t\t\t*(uint16*)n=o->tdir_type;\n\t\t\tif (tif->tif_flags&TIFF_SWAB)\n\t\t\t\tTIFFSwabShort((uint16*)n);\n\t\t\tn+=2;\n\t\t\tnTmp = (uint32)o->tdir_count;\n\t\t\t_TIFFmemcpy(n,&nTmp,4);\n\t\t\tif (tif->tif_flags&TIFF_SWAB)\n\t\t\t\tTIFFSwabLong((uint32*)n);\n\t\t\tn+=4;\n\t\t\t/* This is correct. The data has been */\n\t\t\t/* swabbed previously in TIFFWriteDirectoryTagData */\n\t\t\t_TIFFmemcpy(n,&o->tdir_offset,4);\n\t\t\tn+=4;\n\t\t\to++;\n\t\t}\n\t\tnTmp = (uint32)tif->tif_nextdiroff;\n\t\tif (tif->tif_flags&TIFF_SWAB)\n\t\t\tTIFFSwabLong(&nTmp);\n\t\t_TIFFmemcpy(n,&nTmp,4);\n\t}\n\telse\n\t{\n\t\tuint8* n;\n\t\tTIFFDirEntry* o;\n\t\tn=dirmem;\n\t\t*(uint64*)n=ndir;\n\t\tif (tif->tif_flags&TIFF_SWAB)\n\t\t\tTIFFSwabLong8((uint64*)n);\n\t\tn+=8;\n\t\to=dir;\n\t\tfor (m=0; mtdir_tag;\n\t\t\tif (tif->tif_flags&TIFF_SWAB)\n\t\t\t\tTIFFSwabShort((uint16*)n);\n\t\t\tn+=2;\n\t\t\t*(uint16*)n=o->tdir_type;\n\t\t\tif (tif->tif_flags&TIFF_SWAB)\n\t\t\t\tTIFFSwabShort((uint16*)n);\n\t\t\tn+=2;\n\t\t\t_TIFFmemcpy(n,&o->tdir_count,8);\n\t\t\tif (tif->tif_flags&TIFF_SWAB)\n\t\t\t\tTIFFSwabLong8((uint64*)n);\n\t\t\tn+=8;\n\t\t\t_TIFFmemcpy(n,&o->tdir_offset,8);\n\t\t\tn+=8;\n\t\t\to++;\n\t\t}\n\t\t_TIFFmemcpy(n,&tif->tif_nextdiroff,8);\n\t\tif (tif->tif_flags&TIFF_SWAB)\n\t\t\tTIFFSwabLong8((uint64*)n);\n\t}\n\t_TIFFfree(dir);\n\tdir=NULL;\n\tif (!SeekOK(tif,tif->tif_diroff))\n\t{\n\t\tTIFFErrorExt(tif->tif_clientdata,module,\"IO error writing directory\");\n\t\tgoto bad;\n\t}\n\tif (!WriteOK(tif,dirmem,(tmsize_t)dirsize))\n\t{\n\t\tTIFFErrorExt(tif->tif_clientdata,module,\"IO error writing directory\");\n\t\tgoto bad;\n\t}\n\t_TIFFfree(dirmem);\n\tif (imagedone)\n\t{\n\t\tTIFFFreeDirectory(tif);\n\t\ttif->tif_flags &= ~TIFF_DIRTYDIRECT;\n\t\ttif->tif_flags &= ~TIFF_DIRTYSTRIP;\n\t\t(*tif->tif_cleanup)(tif);\n\t\t/*\n\t\t* Reset directory-related state for subsequent\n\t\t* directories.\n\t\t*/\n\t\tTIFFCreateDirectory(tif);\n\t}\n\treturn(1);\nbad:\n\tif (dir!=NULL)\n\t\t_TIFFfree(dir);\n\tif (dirmem!=NULL)\n\t\t_TIFFfree(dirmem);\n\treturn(0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'TIFFWriteDirectorySec: avoid assertion. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2795. CVE-2018-10963'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (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_kv_add_internal(struct ldb_module *module,\n\t\t\t struct ldb_kv_private *ldb_kv,\n\t\t\t const struct ldb_message *msg,\n\t\t\t bool check_single_value)\n{\n\tstruct ldb_context *ldb = ldb_module_get_ctx(module);\n\tint ret = LDB_SUCCESS;\n\tunsigned int i;\n\n\tfor (i=0;inum_elements;i++) {\n\t\tstruct ldb_message_element *el = &msg->elements[i];\n\t\tconst struct ldb_schema_attribute *a = ldb_schema_attribute_by_name(ldb, el->name);\n\n\t\tif (el->num_values == 0) {\n\t\t\tldb_asprintf_errstring(ldb, \"attribute '%s' on '%s' specified, but with 0 values (illegal)\",\n\t\t\t\t\t el->name, ldb_dn_get_linearized(msg->dn));\n\t\t\treturn LDB_ERR_CONSTRAINT_VIOLATION;\n\t\t}\n\t\tif (check_single_value && el->num_values > 1 &&\n\t\t ldb_kv_single_valued(a, el)) {\n\t\t\tldb_asprintf_errstring(ldb, \"SINGLE-VALUE attribute %s on %s specified more than once\",\n\t\t\t\t\t el->name, ldb_dn_get_linearized(msg->dn));\n\t\t\treturn LDB_ERR_CONSTRAINT_VIOLATION;\n\t\t}\n\n\t\t/* Do not check \"@ATTRIBUTES\" for duplicated values */\n\t\tif (ldb_dn_is_special(msg->dn) &&\n\t\t ldb_dn_check_special(msg->dn, LDB_KV_ATTRIBUTES)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (check_single_value &&\n\t\t !(el->flags &\n\t\t LDB_FLAG_INTERNAL_DISABLE_SINGLE_VALUE_CHECK)) {\n\t\t\tstruct ldb_val *duplicate = NULL;\n\n\t\t\tret = ldb_msg_find_duplicate_val(ldb, discard_const(msg),\n\t\t\t\t\t\t\t el, &duplicate, 0);\n\t\t\tif (ret != LDB_SUCCESS) {\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\tif (duplicate != NULL) {\n\t\t\t\tldb_asprintf_errstring(\n\t\t\t\t\tldb,\n\t\t\t\t\t\"attribute '%s': value '%.*s' on '%s' \"\n\t\t\t\t\t\"provided more than once in ADD object\",\n\t\t\t\t\tel->name,\n\t\t\t\t\t(int)duplicate->length,\n\t\t\t\t\tduplicate->data,\n\t\t\t\t\tldb_dn_get_linearized(msg->dn));\n\t\t\t\treturn LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS;\n\t\t\t}\n\t\t}\n\t}\n\n\tret = ldb_kv_store(module, msg, TDB_INSERT);\n\tif (ret != LDB_SUCCESS) {\n\t\t/*\n\t\t * Try really hard to get the right error code for\n\t\t * a re-add situation, as this can matter!\n\t\t */\n\t\tif (ret == LDB_ERR_CONSTRAINT_VIOLATION) {\n\t\t\tint ret2;\n\t\t\tstruct ldb_dn *dn2 = NULL;\n\t\t\tTALLOC_CTX *mem_ctx = talloc_new(module);\n\t\t\tif (mem_ctx == NULL) {\n\t\t\t\treturn ldb_module_operr(module);\n\t\t\t}\n\t\t\tret2 =\n\t\t\t ldb_kv_search_base(module, mem_ctx, msg->dn, &dn2);\n\t\t\tTALLOC_FREE(mem_ctx);\n\t\t\tif (ret2 == LDB_SUCCESS) {\n\t\t\t\tret = LDB_ERR_ENTRY_ALREADY_EXISTS;\n\t\t\t}\n\t\t}\n\t\tif (ret == LDB_ERR_ENTRY_ALREADY_EXISTS) {\n\t\t\tldb_asprintf_errstring(ldb,\n\t\t\t\t\t \"Entry %s already exists\",\n\t\t\t\t\t ldb_dn_get_linearized(msg->dn));\n\t\t}\n\t\treturn ret;\n\t}\n\n\tret = ldb_kv_index_add_new(module, ldb_kv, msg);\n\tif (ret != LDB_SUCCESS) {\n\t\t/*\n\t\t * If we failed to index, delete the message again.\n\t\t *\n\t\t * This is particularly important for the GUID index\n\t\t * case, which will only fail for a duplicate DN\n\t\t * in the index add.\n\t\t *\n\t\t * Note that the caller may not cancel the transation\n\t\t * and this means the above add might really show up!\n\t\t */\n\t\tldb_kv_delete_noindex(module, msg);\n\t\treturn ret;\n\t}\n\n\tret = ldb_kv_modified(module, msg->dn);\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::calls_crt1(Elf32_Rel const *rel, int sz)\n{\n for (; 0 < sz; (sz -= sizeof(Elf32_Rel)), ++rel) {\n unsigned const symnum = get_te32(&rel->r_info) >> 8;\n char const *const symnam = get_te32(&dynsym[symnum].st_name) + dynstr;\n if (0==strcmp(symnam, \"__libc_start_main\") // glibc\n || 0==strcmp(symnam, \"__libc_init\") // Android\n || 0==strcmp(symnam, \"__uClibc_main\")\n || 0==strcmp(symnam, \"__uClibc_start_main\"))\n return true;\n }\n return false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-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 sr_do_ioctl(Scsi_CD *cd, struct packet_command *cgc)\n{\n\tstruct scsi_device *SDev;\n\tstruct scsi_sense_hdr sshdr;\n\tint result, err = 0, retries = 0;\n\n\tSDev = cd->device;\n\n retry:\n\tif (!scsi_block_when_processing_errors(SDev)) {\n\t\terr = -ENODEV;\n\t\tgoto out;\n\t}\n\n\tresult = scsi_execute(SDev, cgc->cmd, cgc->data_direction,\n\t\t\t cgc->buffer, cgc->buflen,\n\t\t\t (unsigned char *)cgc->sense, &sshdr,\n\t\t\t cgc->timeout, IOCTL_RETRIES, 0, 0, NULL);\n\n\t/* Minimal error checking. Ignore cases we know about, and report the rest. */\n\tif (driver_byte(result) != 0) {\n\t\tswitch (sshdr.sense_key) {\n\t\tcase UNIT_ATTENTION:\n\t\t\tSDev->changed = 1;\n\t\t\tif (!cgc->quiet)\n\t\t\t\tsr_printk(KERN_INFO, cd,\n\t\t\t\t\t \"disc change detected.\\n\");\n\t\t\tif (retries++ < 10)\n\t\t\t\tgoto retry;\n\t\t\terr = -ENOMEDIUM;\n\t\t\tbreak;\n\t\tcase NOT_READY:\t/* This happens if there is no disc in drive */\n\t\t\tif (sshdr.asc == 0x04 &&\n\t\t\t sshdr.ascq == 0x01) {\n\t\t\t\t/* sense: Logical unit is in process of becoming ready */\n\t\t\t\tif (!cgc->quiet)\n\t\t\t\t\tsr_printk(KERN_INFO, cd,\n\t\t\t\t\t\t \"CDROM not ready yet.\\n\");\n\t\t\t\tif (retries++ < 10) {\n\t\t\t\t\t/* sleep 2 sec and try again */\n\t\t\t\t\tssleep(2);\n\t\t\t\t\tgoto retry;\n\t\t\t\t} else {\n\t\t\t\t\t/* 20 secs are enough? */\n\t\t\t\t\terr = -ENOMEDIUM;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!cgc->quiet)\n\t\t\t\tsr_printk(KERN_INFO, cd,\n\t\t\t\t\t \"CDROM not ready. Make sure there \"\n\t\t\t\t\t \"is a disc in the drive.\\n\");\n\t\t\terr = -ENOMEDIUM;\n\t\t\tbreak;\n\t\tcase ILLEGAL_REQUEST:\n\t\t\terr = -EIO;\n\t\t\tif (sshdr.asc == 0x20 &&\n\t\t\t sshdr.ascq == 0x00)\n\t\t\t\t/* sense: Invalid command operation code */\n\t\t\t\terr = -EDRIVE_CANT_DO_THIS;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\terr = -EIO;\n\t\t}\n\t}\n\n\t/* Wake up a process waiting for device */\n out:\n\tcgc->stat = err;\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'sr: pass down correctly sized SCSI sense buffer\n\nWe're casting the CDROM layer request_sense to the SCSI sense\nbuffer, but the former is 64 bytes and the latter is 96 bytes.\nAs we generally allocate these on the stack, we end up blowing\nup the stack.\n\nFix this by wrapping the scsi_execute() call with a properly\nsized sense buffer, and copying back the bits for the CDROM\nlayer.\n\nCc: stable@vger.kernel.org\nReported-by: Piotr Gabriel Kosinski \nReported-by: Daniel Shapira \nTested-by: Kees Cook \nFixes: 82ed4db499b8 (\"block: split scsi_request out of struct request\")\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 void _slurm_rpc_allocate_resources(slurm_msg_t * msg)\n{\n\tstatic int active_rpc_cnt = 0;\n\tint error_code = SLURM_SUCCESS;\n\tslurm_msg_t response_msg;\n\tDEF_TIMERS;\n\tjob_desc_msg_t *job_desc_msg = (job_desc_msg_t *) msg->data;\n\tresource_allocation_response_msg_t alloc_msg;\n\t/* Locks: Read config, read job, read node, read partition */\n\tslurmctld_lock_t job_read_lock = {\n\t\tREAD_LOCK, READ_LOCK, READ_LOCK, READ_LOCK, READ_LOCK };\n\t/* Locks: Read config, write job, write node, read partition */\n\tslurmctld_lock_t job_write_lock = {\n\t\tREAD_LOCK, WRITE_LOCK, WRITE_LOCK, READ_LOCK, READ_LOCK };\n\tuid_t uid = g_slurm_auth_get_uid(msg->auth_cred,\n\t\t\t\t\t slurmctld_config.auth_info);\n\tint immediate = job_desc_msg->immediate;\n\tbool do_unlock = false;\n\tbool reject_job = false;\n\tstruct job_record *job_ptr = NULL;\n\tuint16_t port;\t/* dummy value */\n\tslurm_addr_t resp_addr;\n\tchar *err_msg = NULL, *job_submit_user_msg = NULL;\n\n\tSTART_TIMER;\n\n\tif (slurmctld_config.submissions_disabled) {\n\t\tinfo(\"Submissions disabled on system\");\n\t\terror_code = ESLURM_SUBMISSIONS_DISABLED;\n\t\treject_job = true;\n\t\tgoto send_msg;\n\t}\n\n\tif ((uid != job_desc_msg->user_id) && (!validate_slurm_user(uid))) {\n\t\terror_code = ESLURM_USER_ID_MISSING;\n\t\terror(\"Security violation, RESOURCE_ALLOCATE from uid=%d\",\n\t\t uid);\n\t}\n\tdebug2(\"sched: Processing RPC: REQUEST_RESOURCE_ALLOCATION from uid=%d\",\n\t uid);\n\n\t/* do RPC call */\n\tif ((job_desc_msg->alloc_node == NULL) ||\n\t (job_desc_msg->alloc_node[0] == '\\0')) {\n\t\terror_code = ESLURM_INVALID_NODE_NAME;\n\t\terror(\"REQUEST_RESOURCE_ALLOCATE lacks alloc_node from uid=%d\",\n\t\t uid);\n\t}\n\n\tif (error_code == SLURM_SUCCESS) {\n\t\t/* Locks are for job_submit plugin use */\n\t\tlock_slurmctld(job_read_lock);\n\t\tjob_desc_msg->pack_job_offset = NO_VAL;\n\t\terror_code = validate_job_create_req(job_desc_msg,uid,&err_msg);\n\t\tunlock_slurmctld(job_read_lock);\n\t}\n\n\t/*\n\t * In validate_job_create_req(), err_msg is currently only modified in\n\t * the call to job_submit_plugin_submit. We save the err_msg in a temp\n\t * char *job_submit_user_msg because err_msg can be overwritten later\n\t * in the calls to fed_mgr_job_allocate and/or job_allocate, and we\n\t * need the job submit plugin value to build the resource allocation\n\t * response in the call to _build_alloc_msg.\n\t */\n\tif (err_msg)\n\t\tjob_submit_user_msg = xstrdup(err_msg);\n\n#if HAVE_ALPS_CRAY\n\t/*\n\t * Catch attempts to nest salloc sessions. It is not possible to use an\n\t * ALPS session which has the same alloc_sid, it fails even if PAGG\n\t * container IDs are used.\n\t */\n\tif (allocated_session_in_use(job_desc_msg)) {\n\t\terror_code = ESLURM_RESERVATION_BUSY;\n\t\terror(\"attempt to nest ALPS allocation on %s:%d by uid=%d\",\n\t\t\tjob_desc_msg->alloc_node, job_desc_msg->alloc_sid, uid);\n\t}\n#endif\n\tif (error_code) {\n\t\treject_job = true;\n\t} else if (!slurm_get_peer_addr(msg->conn_fd, &resp_addr)) {\n\t\t/* resp_host could already be set from a federated cluster */\n\t\tif (!job_desc_msg->resp_host) {\n\t\t\tjob_desc_msg->resp_host = xmalloc(16);\n\t\t\tslurm_get_ip_str(&resp_addr, &port,\n\t\t\t\t\t job_desc_msg->resp_host, 16);\n\t\t}\n\t\tdump_job_desc(job_desc_msg);\n\t\tdo_unlock = true;\n\t\t_throttle_start(&active_rpc_cnt);\n\n\t\tlock_slurmctld(job_write_lock);\n\t\tif (fed_mgr_fed_rec) {\n\t\t\tuint32_t job_id;\n\t\t\tif (fed_mgr_job_allocate(msg, job_desc_msg, true, uid,\n\t\t\t\t\t\t msg->protocol_version, &job_id,\n\t\t\t\t\t\t &error_code, &err_msg)) {\n\t\t\t\treject_job = true;\n\t\t\t} else if (!(job_ptr = find_job_record(job_id))) {\n\t\t\t\terror(\"%s: can't find fed job that was just created. this should never happen\",\n\t\t\t\t __func__);\n\t\t\t\treject_job = true;\n\t\t\t\terror_code = SLURM_ERROR;\n\t\t\t}\n\t\t} else {\n\t\t\tjob_desc_msg->pack_job_offset = NO_VAL;\n\t\t\terror_code = job_allocate(job_desc_msg, immediate,\n\t\t\t\t\t\t false, NULL, true, uid,\n\t\t\t\t\t\t &job_ptr, &err_msg,\n\t\t\t\t\t\t msg->protocol_version);\n\t\t\t/* unlock after finished using the job structure\n\t\t\t * data */\n\n\t\t\t/* return result */\n\t\t\tif (!job_ptr ||\n\t\t\t (error_code && job_ptr->job_state == JOB_FAILED))\n\t\t\t\treject_job = true;\n\t\t}\n\t\tEND_TIMER2(\"_slurm_rpc_allocate_resources\");\n\t} else {\n\t\treject_job = true;\n\t\tif (errno)\n\t\t\terror_code = errno;\n\t\telse\n\t\t\terror_code = SLURM_ERROR;\n\t}\n\nsend_msg:\n\n\tif (!reject_job) {\n\t\txassert(job_ptr);\n\t\tinfo(\"sched: %s JobId=%u NodeList=%s %s\", __func__,\n\t\t job_ptr->job_id, job_ptr->nodes, TIME_STR);\n\n\t\t_build_alloc_msg(job_ptr, &alloc_msg, error_code,\n\t\t\t\t job_submit_user_msg);\n\n\t\t/*\n\t\t * This check really isn't needed, but just doing it\n\t\t * to be more complete.\n\t\t */\n\t\tif (do_unlock) {\n\t\t\tunlock_slurmctld(job_write_lock);\n\t\t\t_throttle_fini(&active_rpc_cnt);\n\t\t}\n\n\t\tslurm_msg_t_init(&response_msg);\n\t\tresponse_msg.conn = msg->conn;\n\t\tresponse_msg.flags = msg->flags;\n\t\tresponse_msg.protocol_version = msg->protocol_version;\n\t\tresponse_msg.msg_type = RESPONSE_RESOURCE_ALLOCATION;\n\t\tresponse_msg.data = &alloc_msg;\n\n\t\tif (slurm_send_node_msg(msg->conn_fd, &response_msg) < 0)\n\t\t\t_kill_job_on_msg_fail(job_ptr->job_id);\n\n\t\tschedule_job_save();\t/* has own locks */\n\t\tschedule_node_save();\t/* has own locks */\n\n\t\tif (!alloc_msg.node_cnt) /* didn't get an allocation */\n\t\t\tqueue_job_scheduler();\n\n\t\t/* NULL out working_cluster_rec since it's pointing to global\n\t\t * memory */\n\t\talloc_msg.working_cluster_rec = NULL;\n\t\tslurm_free_resource_allocation_response_msg_members(&alloc_msg);\n\t} else {\t/* allocate error */\n\t\tif (do_unlock) {\n\t\t\tunlock_slurmctld(job_write_lock);\n\t\t\t_throttle_fini(&active_rpc_cnt);\n\t\t}\n\t\tinfo(\"%s: %s \", __func__, slurm_strerror(error_code));\n\t\tif (err_msg)\n\t\t\tslurm_send_rc_err_msg(msg, error_code, err_msg);\n\t\telse\n\t\t\tslurm_send_rc_msg(msg, error_code);\n\t}\n\txfree(err_msg);\n\txfree(job_submit_user_msg);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix insecure handling of job requested gid.\n\nOnly trust MUNGE signed values, unless the RPC was signed by\nSlurmUser or root.\n\nCVE-2018-10995.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: z_check_file_permissions(gs_memory_t *mem, const char *fname, const int len, const char *permission)\n{\n i_ctx_t *i_ctx_p = get_minst_from_memory(mem)->i_ctx_p;\n gs_parsed_file_name_t pname;\n const char *permitgroup = permission[0] == 'r' ? \"PermitFileReading\" : \"PermitFileWriting\";\n int code = gs_parse_file_name(&pname, fname, len, imemory);\n if (code < 0)\n return code;\n\n if (pname.iodev && i_ctx_p->LockFilePermissions && strcmp(pname.iodev->dname, \"%pipe%\") == 0)\n return gs_error_invalidfileaccess;\n \n code = check_file_permissions(i_ctx_p, fname, len, permitgroup);\n return code;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Bug 697193: status operator honour SAFER option'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int add_match_busid(char *busid)\n{\n\tint i;\n\tint ret = -1;\n\n\tspin_lock(&busid_table_lock);\n\t/* already registered? */\n\tif (get_busid_idx(busid) >= 0) {\n\t\tret = 0;\n\t\tgoto out;\n\t}\n\n\tfor (i = 0; i < MAX_BUSID; i++)\n\t\tif (!busid_table[i].name[0]) {\n\t\t\tstrlcpy(busid_table[i].name, busid, BUSID_SIZE);\n\t\t\tif ((busid_table[i].status != STUB_BUSID_ALLOC) &&\n\t\t\t (busid_table[i].status != STUB_BUSID_REMOV))\n\t\t\t\tbusid_table[i].status = STUB_BUSID_ADDED;\n\t\t\tret = 0;\n\t\t\tbreak;\n\t\t}\n\nout:\n\tspin_unlock(&busid_table_lock);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'usbip: usbip_host: fix NULL-ptr deref and use-after-free errors\n\nusbip_host updates device status without holding lock from stub probe,\ndisconnect and rebind code paths. When multiple requests to import a\ndevice are received, these unprotected code paths step all over each\nother and drive fails with NULL-ptr deref and use-after-free errors.\n\nThe driver uses a table lock to protect the busid array for adding and\ndeleting busids to the table. However, the probe, disconnect and rebind\npaths get the busid table entry and update the status without holding\nthe busid table lock. Add a new finer grain lock to protect the busid\nentry. This new lock will be held to search and update the busid entry\nfields from get_busid_idx(), add_match_busid() and del_match_busid().\n\nmatch_busid_show() does the same to access the busid entry fields.\n\nget_busid_priv() changed to return the pointer to the busid entry holding\nthe busid lock. stub_probe(), stub_disconnect() and stub_device_rebind()\ncall put_busid_priv() to release the busid lock before returning. This\nchanges fixes the unprotected code paths eliminating the race conditions\nin updating the busid entries.\n\nReported-by: Jakub Jirasek\nSigned-off-by: Shuah Khan (Samsung OSG) \nCc: stable \nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Statement_Ptr Expand::operator()(Declaration_Ptr d)\n {\n Block_Obj ab = d->block();\n String_Obj old_p = d->property();\n Expression_Obj prop = old_p->perform(&eval);\n String_Obj new_p = Cast(prop);\n // we might get a color back\n if (!new_p) {\n std::string str(prop->to_string(ctx.c_options));\n new_p = SASS_MEMORY_NEW(String_Constant, old_p->pstate(), str);\n }\n Expression_Obj value = d->value()->perform(&eval);\n Block_Obj bb = ab ? operator()(ab) : NULL;\n if (!bb) {\n if (!value || (value->is_invisible() && !d->is_important())) return 0;\n }\n Declaration_Ptr decl = SASS_MEMORY_NEW(Declaration,\n d->pstate(),\n new_p,\n value,\n d->is_important(),\n d->is_custom_property(),\n bb);\n decl->tabs(d->tabs());\n return decl;\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 int getnum (lua_State *L, const char **fmt, int df) {\n if (!isdigit(**fmt)) /* no number? */\n return df; /* return default value */\n else {\n int a = 0;\n do {\n if (a > (INT_MAX / 10) || a * 10 > (INT_MAX - (**fmt - '0')))\n luaL_error(L, \"integral size overflow\");\n a = a*10 + *((*fmt)++) - '0';\n } while (isdigit(**fmt));\n return a;\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: static int sock_close(struct inode *inode, struct file *filp)\n{\n\tsock_release(SOCKET_I(inode));\n\treturn 0;\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: start_watchdog(ngx_cycle_t *cycle) {\n ngx_core_conf_t *core_conf;\n ngx_int_t ret, result;\n ngx_uint_t i;\n AfterForkData after_fork_data;\n ngx_keyval_t *ctl = NULL;\n ngx_str_t str;\n PsgJsonValue *w_config = NULL;\n PsgJsonValue *j_log_target;\n u_char filename[NGX_MAX_PATH], *last;\n char *passenger_root = NULL;\n char *error_message = NULL;\n passenger_autogenerated_main_conf_t *autogenerated_main_conf =\n &passenger_main_conf.autogenerated;\n\n core_conf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module);\n result = NGX_OK;\n w_config = psg_json_value_new_with_type(PSG_JSON_VALUE_TYPE_OBJECT);\n j_log_target = psg_json_value_new_with_type(PSG_JSON_VALUE_TYPE_OBJECT);\n after_fork_data.cycle = cycle;\n after_fork_data.log_fd = -1;\n passenger_root = ngx_str_null_terminate(&autogenerated_main_conf->root_dir);\n if (passenger_root == NULL) {\n goto error_enomem;\n }\n\n if (autogenerated_main_conf->stat_throttle_rate != NGX_CONF_UNSET_UINT) {\n pp_app_type_detector_set_throttle_rate(pp_app_type_detector,\n autogenerated_main_conf->stat_throttle_rate);\n }\n\n /* Note: WatchdogLauncher::start() sets a number of default values. */\n psg_json_value_set_str_ne (w_config, \"web_server_module_version\", PASSENGER_VERSION, strlen(PASSENGER_VERSION));\n psg_json_value_set_str_ne (w_config, \"web_server_version\", NGINX_VERSION, strlen(NGINX_VERSION));\n psg_json_value_set_str_ne (w_config, \"server_software\", NGINX_VER, strlen(NGINX_VER));\n psg_json_value_set_bool (w_config, \"multi_app\", 1);\n psg_json_value_set_bool (w_config, \"default_load_shell_envvars\", 1);\n psg_json_value_set_value (w_config, \"config_manifest\", -1, passenger_main_conf.manifest);\n psg_json_value_set_ngx_uint (w_config, \"log_level\", autogenerated_main_conf->log_level);\n psg_json_value_set_ngx_str_ne(w_config, \"file_descriptor_log_target\", &autogenerated_main_conf->file_descriptor_log_file);\n psg_json_value_set_ngx_uint (w_config, \"core_file_descriptor_ulimit\", autogenerated_main_conf->core_file_descriptor_ulimit);\n psg_json_value_set_ngx_uint (w_config, \"controller_socket_backlog\", autogenerated_main_conf->socket_backlog);\n psg_json_value_set_ngx_str_ne(w_config, \"controller_file_buffered_channel_buffer_dir\", &autogenerated_main_conf->data_buffer_dir);\n psg_json_value_set_ngx_str_ne(w_config, \"instance_registry_dir\", &autogenerated_main_conf->instance_registry_dir);\n psg_json_value_set_ngx_flag (w_config, \"security_update_checker_disabled\", autogenerated_main_conf->disable_security_update_check);\n psg_json_value_set_ngx_str_ne(w_config, \"security_update_checker_proxy_url\", &autogenerated_main_conf->security_update_check_proxy);\n psg_json_value_set_ngx_flag (w_config, \"user_switching\", autogenerated_main_conf->user_switching);\n psg_json_value_set_ngx_flag (w_config, \"show_version_in_header\", autogenerated_main_conf->show_version_in_header);\n psg_json_value_set_ngx_flag (w_config, \"turbocaching\", autogenerated_main_conf->turbocaching);\n psg_json_value_set_ngx_str_ne(w_config, \"default_user\", &autogenerated_main_conf->default_user);\n psg_json_value_set_ngx_str_ne(w_config, \"default_group\", &autogenerated_main_conf->default_group);\n psg_json_value_set_ngx_str_ne(w_config, \"default_ruby\", &passenger_main_conf.default_ruby);\n psg_json_value_set_ngx_uint (w_config, \"max_pool_size\", autogenerated_main_conf->max_pool_size);\n psg_json_value_set_ngx_uint (w_config, \"pool_idle_time\", autogenerated_main_conf->pool_idle_time);\n psg_json_value_set_ngx_uint (w_config, \"max_instances_per_app\", autogenerated_main_conf->max_instances_per_app);\n psg_json_value_set_ngx_uint (w_config, \"response_buffer_high_watermark\", autogenerated_main_conf->response_buffer_high_watermark);\n psg_json_value_set_ngx_uint (w_config, \"stat_throttle_rate\", autogenerated_main_conf->stat_throttle_rate);\n psg_json_value_set_ngx_str_ne(w_config, \"admin_panel_url\", &autogenerated_main_conf->admin_panel_url);\n psg_json_value_set_ngx_str_ne(w_config, \"admin_panel_auth_type\", &autogenerated_main_conf->admin_panel_auth_type);\n psg_json_value_set_ngx_str_ne(w_config, \"admin_panel_username\", &autogenerated_main_conf->admin_panel_username);\n psg_json_value_set_ngx_str_ne(w_config, \"admin_panel_password\", &autogenerated_main_conf->admin_panel_password);\n\n if (autogenerated_main_conf->prestart_uris != NGX_CONF_UNSET_PTR) {\n psg_json_value_set_strset(w_config, \"prestart_urls\", (ngx_str_t *) autogenerated_main_conf->prestart_uris->elts,\n autogenerated_main_conf->prestart_uris->nelts);\n }\n\n if (autogenerated_main_conf->log_file.len > 0) {\n psg_json_value_set_ngx_str_ne(j_log_target, \"path\", &autogenerated_main_conf->log_file);\n } else if (cycle->new_log.file == NULL) {\n ngx_log_error(NGX_LOG_EMERG, cycle->log, 0, \"Cannot initialize \" PROGRAM_NAME\n \" because Nginx is not configured with an error log file.\"\n \" Please either configure Nginx with an error log file, or configure \"\n PROGRAM_NAME \" with a `passenger_log_file`\");\n result = NGX_ERROR;\n goto cleanup;\n } else if (cycle->new_log.file->name.len > 0) {\n psg_json_value_set_ngx_str_ne(j_log_target, \"path\", &cycle->new_log.file->name);\n } else if (cycle->log->file->name.len > 0) {\n psg_json_value_set_ngx_str_ne(j_log_target, \"path\", &cycle->log->file->name);\n }\n\n if (autogenerated_main_conf->ctl != NULL) {\n ctl = (ngx_keyval_t *) autogenerated_main_conf->ctl->elts;\n for (i = 0; i < autogenerated_main_conf->ctl->nelts; i++) {\n psg_json_value_set_with_autodetected_data_type(w_config,\n (const char *) ctl[i].key.data, ctl[i].key.len,\n (const char *) ctl[i].value.data, ctl[i].value.len,\n &error_message);\n if (error_message != NULL) {\n str.data = ctl[i].key.data;\n str.len = ctl[i].key.len - 1;\n ngx_log_error(NGX_LOG_EMERG, cycle->log, 0,\n \"Error parsing ctl %V as JSON data: %s\",\n &str, error_message);\n result = NGX_ERROR;\n goto cleanup;\n }\n }\n }\n\n open_log_file_for_after_forking(&after_fork_data, j_log_target);\n if (after_fork_data.stderr_equals_log_file) {\n psg_json_value_set_bool(j_log_target, \"stderr\", 1);\n }\n if (!psg_json_value_empty(j_log_target)) {\n psg_json_value_set_value(w_config, \"log_target\", -1, j_log_target);\n }\n\n ret = psg_watchdog_launcher_start(psg_watchdog_launcher,\n passenger_root,\n w_config,\n starting_watchdog_after_fork,\n &after_fork_data,\n &error_message);\n if (!ret) {\n ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno, \"%s\", error_message);\n result = NGX_ERROR;\n goto cleanup;\n }\n\n /* Create the file instance_dir + \"/web_server_info/control_process.pid\"\n * and make it writable by the worker processes. This is because\n * save_master_process_pid is run after Nginx has lowered privileges.\n */\n last = ngx_snprintf(filename, sizeof(filename) - 1,\n \"%s/web_server_info/control_process.pid\",\n psg_watchdog_launcher_get_instance_dir(psg_watchdog_launcher, NULL));\n *last = (u_char) '\\0';\n if (create_file(cycle, filename, (const u_char *) \"\", 0) != NGX_OK) {\n result = NGX_ERROR;\n goto cleanup;\n }\n do {\n ret = chown((const char *) filename, (uid_t) core_conf->user, (gid_t) -1);\n } while (ret == -1 && errno == EINTR);\n if (ret == -1) {\n result = NGX_ERROR;\n goto cleanup;\n }\n\ncleanup:\n psg_json_value_free(w_config);\n psg_json_value_free(j_log_target);\n free(passenger_root);\n free(error_message);\n\n if (after_fork_data.log_fd != -1) {\n close(after_fork_data.log_fd);\n }\n\n if (result == NGX_ERROR && autogenerated_main_conf->abort_on_startup_error) {\n exit(1);\n }\n\n return result;\n\nerror_enomem:\n ngx_log_error(NGX_LOG_ALERT, cycle->log, ENOMEM, \"Cannot allocate memory\");\n result = NGX_ERROR;\n goto cleanup;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'Fix privilege escalation in the Nginx module\n\nThe vulnerability is exploitable with a non-standard\npassenger_instance_registry_dir, via a race condition where after a file\nwas created, it was chowned via the path not the file descriptor.\n\nThe chown entered the code in 2010, so Passenger 4 + 5 all affected.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static MagickBooleanType WriteBMPImage(const ImageInfo *image_info,Image *image)\n{\n BMPInfo\n bmp_info;\n\n BMPSubtype\n bmp_subtype;\n\n const char\n *option;\n\n const StringInfo\n *profile;\n\n MagickBooleanType\n have_color_info,\n status;\n\n MemoryInfo\n *pixel_info;\n\n MagickOffsetType\n scene;\n\n register const IndexPacket\n *indexes;\n\n register const PixelPacket\n *p;\n\n register ssize_t\n i,\n x;\n\n register unsigned char\n *q;\n\n size_t\n bytes_per_line,\n imageListLength,\n type;\n\n ssize_t\n y;\n\n unsigned char\n *bmp_data,\n *pixels;\n\n /*\n Open output image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);\n if (status == MagickFalse)\n return(status);\n type=4;\n if (LocaleCompare(image_info->magick,\"BMP2\") == 0)\n type=2;\n else\n if (LocaleCompare(image_info->magick,\"BMP3\") == 0)\n type=3;\n\n option=GetImageOption(image_info,\"bmp:format\");\n if (option != (char *) NULL)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Format=%s\",option);\n\n if (LocaleCompare(option,\"bmp2\") == 0)\n type=2;\n if (LocaleCompare(option,\"bmp3\") == 0)\n type=3;\n if (LocaleCompare(option,\"bmp4\") == 0)\n type=4;\n }\n scene=0;\n imageListLength=GetImageListLength(image);\n do\n {\n /*\n Initialize BMP raster file header.\n */\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n (void) TransformImageColorspace(image,sRGBColorspace);\n (void) memset(&bmp_info,0,sizeof(bmp_info));\n bmp_info.file_size=14+12;\n if (type > 2)\n bmp_info.file_size+=28;\n bmp_info.offset_bits=bmp_info.file_size;\n bmp_info.compression=BI_RGB;\n bmp_info.red_mask=0x00ff0000U;\n bmp_info.green_mask=0x0000ff00U;\n bmp_info.blue_mask=0x000000ffU;\n bmp_info.alpha_mask=0xff000000U;\n bmp_subtype=UndefinedSubtype;\n if ((image->storage_class == PseudoClass) && (image->colors > 256))\n (void) SetImageStorageClass(image,DirectClass);\n if (image->storage_class != DirectClass)\n {\n /*\n Colormapped BMP raster.\n */\n bmp_info.bits_per_pixel=8;\n if (image->colors <= 2)\n bmp_info.bits_per_pixel=1;\n else\n if (image->colors <= 16)\n bmp_info.bits_per_pixel=4;\n else\n if (image->colors <= 256)\n bmp_info.bits_per_pixel=8;\n if (image_info->compression == RLECompression)\n bmp_info.bits_per_pixel=8;\n bmp_info.number_colors=1U << bmp_info.bits_per_pixel;\n if (image->matte != MagickFalse)\n (void) SetImageStorageClass(image,DirectClass);\n else\n if ((size_t) bmp_info.number_colors < image->colors)\n (void) SetImageStorageClass(image,DirectClass);\n else\n {\n bmp_info.file_size+=3*(1UL << bmp_info.bits_per_pixel);\n bmp_info.offset_bits+=3*(1UL << bmp_info.bits_per_pixel);\n if (type > 2)\n {\n bmp_info.file_size+=(1UL << bmp_info.bits_per_pixel);\n bmp_info.offset_bits+=(1UL << bmp_info.bits_per_pixel);\n }\n }\n }\n if (image->storage_class == DirectClass)\n {\n /*\n Full color BMP raster.\n */\n bmp_info.number_colors=0;\n option=GetImageOption(image_info,\"bmp:subtype\");\n if (option != (const char *) NULL)\n {\n if (image->matte != MagickFalse)\n {\n if (LocaleNCompare(option,\"ARGB4444\",8) == 0)\n {\n bmp_subtype=ARGB4444;\n bmp_info.red_mask=0x00000f00U;\n bmp_info.green_mask=0x000000f0U;\n bmp_info.blue_mask=0x0000000fU;\n bmp_info.alpha_mask=0x0000f000U;\n }\n else if (LocaleNCompare(option,\"ARGB1555\",8) == 0)\n {\n bmp_subtype=ARGB1555;\n bmp_info.red_mask=0x00007c00U;\n bmp_info.green_mask=0x000003e0U;\n bmp_info.blue_mask=0x0000001fU;\n bmp_info.alpha_mask=0x00008000U;\n }\n }\n else\n {\n if (LocaleNCompare(option,\"RGB555\",6) == 0)\n {\n bmp_subtype=RGB555;\n bmp_info.red_mask=0x00007c00U;\n bmp_info.green_mask=0x000003e0U;\n bmp_info.blue_mask=0x0000001fU;\n bmp_info.alpha_mask=0U;\n }\n else if (LocaleNCompare(option,\"RGB565\",6) == 0)\n {\n bmp_subtype=RGB565;\n bmp_info.red_mask=0x0000f800U;\n bmp_info.green_mask=0x000007e0U;\n bmp_info.blue_mask=0x0000001fU;\n bmp_info.alpha_mask=0U;\n }\n }\n }\n if (bmp_subtype != UndefinedSubtype)\n {\n bmp_info.bits_per_pixel=16;\n bmp_info.compression=BI_BITFIELDS;\n }\n else\n {\n bmp_info.bits_per_pixel=(unsigned short)\n ((type > 3) && (image->matte != MagickFalse) ? 32 : 24);\n bmp_info.compression=(unsigned int) ((type > 3) &&\n (image->matte != MagickFalse) ? BI_BITFIELDS : BI_RGB);\n if ((type == 3) && (image->matte != MagickFalse))\n {\n option=GetImageOption(image_info,\"bmp3:alpha\");\n if (IsStringTrue(option))\n bmp_info.bits_per_pixel=32;\n }\n }\n }\n bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32);\n bmp_info.ba_offset=0;\n profile=GetImageProfile(image,\"icc\");\n have_color_info=(image->rendering_intent != UndefinedIntent) ||\n (profile != (StringInfo *) NULL) || (image->gamma != 0.0) ? MagickTrue :\n MagickFalse;\n if (type == 2)\n bmp_info.size=12;\n else\n if ((type == 3) || ((image->matte == MagickFalse) &&\n (have_color_info == MagickFalse)))\n {\n type=3;\n bmp_info.size=40;\n }\n else\n {\n int\n extra_size;\n\n bmp_info.size=108;\n extra_size=68;\n if ((image->rendering_intent != UndefinedIntent) ||\n (profile != (StringInfo *) NULL))\n {\n bmp_info.size=124;\n extra_size+=16;\n }\n bmp_info.file_size+=extra_size;\n bmp_info.offset_bits+=extra_size;\n }\n if (((ssize_t) image->columns != (ssize_t) ((signed int) image->columns)) ||\n ((ssize_t) image->rows != (ssize_t) ((signed int) image->rows)))\n ThrowWriterException(ImageError,\"WidthOrHeightExceedsLimit\");\n bmp_info.width=(ssize_t) image->columns;\n bmp_info.height=(ssize_t) image->rows;\n bmp_info.planes=1;\n bmp_info.image_size=(unsigned int) (bytes_per_line*image->rows);\n bmp_info.file_size+=bmp_info.image_size;\n bmp_info.x_pixels=75*39;\n bmp_info.y_pixels=75*39;\n switch (image->units)\n {\n case UndefinedResolution:\n case PixelsPerInchResolution:\n {\n bmp_info.x_pixels=(unsigned int) (100.0*image->x_resolution/2.54);\n bmp_info.y_pixels=(unsigned int) (100.0*image->y_resolution/2.54);\n break;\n }\n case PixelsPerCentimeterResolution:\n {\n bmp_info.x_pixels=(unsigned int) (100.0*image->x_resolution);\n bmp_info.y_pixels=(unsigned int) (100.0*image->y_resolution);\n break;\n }\n }\n bmp_info.colors_important=bmp_info.number_colors;\n /*\n Convert MIFF to BMP raster pixels.\n */\n pixel_info=AcquireVirtualMemory((size_t) bmp_info.image_size,\n sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n (void) memset(pixels,0,(size_t) bmp_info.image_size);\n switch (bmp_info.bits_per_pixel)\n {\n case 1:\n {\n size_t\n bit,\n byte;\n\n /*\n Convert PseudoClass image to a BMP monochrome image.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);\n if (p == (const PixelPacket *) NULL)\n break;\n indexes=GetVirtualIndexQueue(image);\n q=pixels+(image->rows-y-1)*bytes_per_line;\n bit=0;\n byte=0;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n byte<<=1;\n byte|=GetPixelIndex(indexes+x) != 0 ? 0x01 : 0x00;\n bit++;\n if (bit == 8)\n {\n *q++=(unsigned char) byte;\n bit=0;\n byte=0;\n }\n }\n if (bit != 0)\n {\n *q++=(unsigned char) (byte << (8-bit));\n x++;\n }\n for (x=(ssize_t) (image->columns+7)/8; x < (ssize_t) bytes_per_line; x++)\n *q++=0x00;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case 4:\n {\n size_t\n nibble,\n byte;\n\n /*\n Convert PseudoClass image to a BMP monochrome image.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);\n if (p == (const PixelPacket *) NULL)\n break;\n indexes=GetVirtualIndexQueue(image);\n q=pixels+(image->rows-y-1)*bytes_per_line;\n nibble=0;\n byte=0;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n byte<<=4;\n byte|=((size_t) GetPixelIndex(indexes+x) & 0x0f);\n nibble++;\n if (nibble == 2)\n {\n *q++=(unsigned char) byte;\n nibble=0;\n byte=0;\n }\n }\n if (nibble != 0)\n {\n *q++=(unsigned char) (byte << 4);\n x++;\n }\n for (x=(ssize_t) (image->columns+1)/2; x < (ssize_t) bytes_per_line; x++)\n *q++=0x00;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case 8:\n {\n /*\n Convert PseudoClass packet to BMP pixel.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);\n if (p == (const PixelPacket *) NULL)\n break;\n indexes=GetVirtualIndexQueue(image);\n q=pixels+(image->rows-y-1)*bytes_per_line;\n for (x=0; x < (ssize_t) image->columns; x++)\n *q++=(unsigned char) GetPixelIndex(indexes+x);\n for ( ; x < (ssize_t) bytes_per_line; x++)\n *q++=0x00;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case 16:\n {\n /*\n Convert DirectClass packet to BMP BGR888.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);\n if (p == (const PixelPacket *) NULL)\n break;\n q=(pixels+(image->rows-y-1)*bytes_per_line);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n unsigned short\n pixel;\n\n pixel=0;\n if (bmp_subtype == ARGB4444)\n {\n pixel=(unsigned short) (ScaleQuantumToAny(\n GetPixelAlpha(p),15) << 12);\n pixel|=(unsigned short) (ScaleQuantumToAny(\n GetPixelRed(p),15) << 8);\n pixel|=(unsigned short) (ScaleQuantumToAny(\n GetPixelGreen(p),15) << 4);\n pixel|=(unsigned short) (ScaleQuantumToAny(\n GetPixelBlue(p),15));\n }\n else if (bmp_subtype == RGB565)\n {\n pixel=(unsigned short) (ScaleQuantumToAny(\n GetPixelRed(p),31) << 11);\n pixel|=(unsigned short) (ScaleQuantumToAny(\n GetPixelGreen(p),63) << 5);\n pixel|=(unsigned short) (ScaleQuantumToAny(\n GetPixelBlue(p),31));\n }\n else\n {\n if (bmp_subtype == ARGB1555)\n pixel=(unsigned short) (ScaleQuantumToAny(\n GetPixelAlpha(p),1) << 15);\n pixel|=(unsigned short) (ScaleQuantumToAny(\n GetPixelRed(p),31) << 10);\n pixel|=(unsigned short) (ScaleQuantumToAny(\n GetPixelGreen(p),31) << 5);\n pixel|=(unsigned short) (ScaleQuantumToAny(\n GetPixelBlue(p),31));\n }\n *((unsigned short *) q)=pixel;\n q+=2;\n p++;\n }\n for (x=2L*(ssize_t) image->columns; x < (ssize_t) bytes_per_line; x++)\n *q++=0x00;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case 24:\n {\n /*\n Convert DirectClass packet to BMP BGR888.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);\n if (p == (const PixelPacket *) NULL)\n break;\n q=pixels+(image->rows-y-1)*bytes_per_line;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n *q++=ScaleQuantumToChar(GetPixelBlue(p));\n *q++=ScaleQuantumToChar(GetPixelGreen(p));\n *q++=ScaleQuantumToChar(GetPixelRed(p));\n p++;\n }\n for (x=3L*(ssize_t) image->columns; x < (ssize_t) bytes_per_line; x++)\n *q++=0x00;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case 32:\n {\n /*\n Convert DirectClass packet to ARGB8888 pixel.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);\n if (p == (const PixelPacket *) NULL)\n break;\n q=pixels+(image->rows-y-1)*bytes_per_line;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n *q++=ScaleQuantumToChar(GetPixelBlue(p));\n *q++=ScaleQuantumToChar(GetPixelGreen(p));\n *q++=ScaleQuantumToChar(GetPixelRed(p));\n *q++=ScaleQuantumToChar(GetPixelAlpha(p));\n p++;\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n }\n if ((type > 2) && (bmp_info.bits_per_pixel == 8))\n if (image_info->compression != NoCompression)\n {\n MemoryInfo\n *rle_info;\n\n /*\n Convert run-length encoded raster pixels.\n */\n rle_info=AcquireVirtualMemory((size_t) (2*(bytes_per_line+2)+2),\n (image->rows+2)*sizeof(*pixels));\n if (rle_info == (MemoryInfo *) NULL)\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n bmp_data=(unsigned char *) GetVirtualMemoryBlob(rle_info);\n bmp_info.file_size-=bmp_info.image_size;\n bmp_info.image_size=(unsigned int) EncodeImage(image,bytes_per_line,\n pixels,bmp_data);\n bmp_info.file_size+=bmp_info.image_size;\n pixel_info=RelinquishVirtualMemory(pixel_info);\n pixel_info=rle_info;\n pixels=bmp_data;\n bmp_info.compression=BI_RLE8;\n }\n /*\n Write BMP for Windows, all versions, 14-byte header.\n */\n if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing BMP version %.20g datastream\",(double) type);\n if (image->storage_class == DirectClass)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Storage class=DirectClass\");\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Storage class=PseudoClass\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Image depth=%.20g\",(double) image->depth);\n if (image->matte != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Matte=True\");\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Matte=MagickFalse\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" BMP bits_per_pixel=%.20g\",(double) bmp_info.bits_per_pixel);\n switch ((int) bmp_info.compression)\n {\n case BI_RGB:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression=BI_RGB\");\n break;\n }\n case BI_RLE8:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression=BI_RLE8\");\n break;\n }\n case BI_BITFIELDS:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression=BI_BITFIELDS\");\n break;\n }\n default:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression=UNKNOWN (%u)\",bmp_info.compression);\n break;\n }\n }\n if (bmp_info.number_colors == 0)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Number_colors=unspecified\");\n else\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Number_colors=%u\",bmp_info.number_colors);\n }\n (void) WriteBlob(image,2,(unsigned char *) \"BM\");\n (void) WriteBlobLSBLong(image,bmp_info.file_size);\n (void) WriteBlobLSBLong(image,bmp_info.ba_offset); /* always 0 */\n (void) WriteBlobLSBLong(image,bmp_info.offset_bits);\n if (type == 2)\n {\n /*\n Write 12-byte version 2 bitmap header.\n */\n (void) WriteBlobLSBLong(image,bmp_info.size);\n (void) WriteBlobLSBSignedShort(image,(signed short) bmp_info.width);\n (void) WriteBlobLSBSignedShort(image,(signed short) bmp_info.height);\n (void) WriteBlobLSBShort(image,bmp_info.planes);\n (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel);\n }\n else\n {\n /*\n Write 40-byte version 3+ bitmap header.\n */\n (void) WriteBlobLSBLong(image,bmp_info.size);\n (void) WriteBlobLSBSignedLong(image,(signed long) bmp_info.width);\n (void) WriteBlobLSBSignedLong(image,(signed long) bmp_info.height);\n (void) WriteBlobLSBShort(image,bmp_info.planes);\n (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel);\n (void) WriteBlobLSBLong(image,bmp_info.compression);\n (void) WriteBlobLSBLong(image,bmp_info.image_size);\n (void) WriteBlobLSBLong(image,bmp_info.x_pixels);\n (void) WriteBlobLSBLong(image,bmp_info.y_pixels);\n (void) WriteBlobLSBLong(image,bmp_info.number_colors);\n (void) WriteBlobLSBLong(image,bmp_info.colors_important);\n }\n if ((type > 3) && ((image->matte != MagickFalse) ||\n (have_color_info != MagickFalse)))\n {\n /*\n Write the rest of the 108-byte BMP Version 4 header.\n */\n (void) WriteBlobLSBLong(image,bmp_info.red_mask);\n (void) WriteBlobLSBLong(image,bmp_info.green_mask);\n (void) WriteBlobLSBLong(image,bmp_info.blue_mask);\n (void) WriteBlobLSBLong(image,bmp_info.alpha_mask);\n (void) WriteBlobLSBLong(image,0x73524742U); /* sRGB */\n (void) WriteBlobLSBLong(image,(unsigned int)\n (image->chromaticity.red_primary.x*0x40000000));\n (void) WriteBlobLSBLong(image,(unsigned int)\n (image->chromaticity.red_primary.y*0x40000000));\n (void) WriteBlobLSBLong(image,(unsigned int)\n ((1.000f-(image->chromaticity.red_primary.x+\n image->chromaticity.red_primary.y))*0x40000000));\n (void) WriteBlobLSBLong(image,(unsigned int)\n (image->chromaticity.green_primary.x*0x40000000));\n (void) WriteBlobLSBLong(image,(unsigned int)\n (image->chromaticity.green_primary.y*0x40000000));\n (void) WriteBlobLSBLong(image,(unsigned int)\n ((1.000f-(image->chromaticity.green_primary.x+\n image->chromaticity.green_primary.y))*0x40000000));\n (void) WriteBlobLSBLong(image,(unsigned int)\n (image->chromaticity.blue_primary.x*0x40000000));\n (void) WriteBlobLSBLong(image,(unsigned int)\n (image->chromaticity.blue_primary.y*0x40000000));\n (void) WriteBlobLSBLong(image,(unsigned int)\n ((1.000f-(image->chromaticity.blue_primary.x+\n image->chromaticity.blue_primary.y))*0x40000000));\n (void) WriteBlobLSBLong(image,(unsigned int)\n (bmp_info.gamma_scale.x*0x10000));\n (void) WriteBlobLSBLong(image,(unsigned int)\n (bmp_info.gamma_scale.y*0x10000));\n (void) WriteBlobLSBLong(image,(unsigned int)\n (bmp_info.gamma_scale.z*0x10000));\n if ((image->rendering_intent != UndefinedIntent) ||\n (profile != (StringInfo *) NULL))\n {\n ssize_t\n intent;\n\n switch ((int) image->rendering_intent)\n {\n case SaturationIntent:\n {\n intent=LCS_GM_BUSINESS;\n break;\n }\n case RelativeIntent:\n {\n intent=LCS_GM_GRAPHICS;\n break;\n }\n case PerceptualIntent:\n {\n intent=LCS_GM_IMAGES;\n break;\n }\n case AbsoluteIntent:\n {\n intent=LCS_GM_ABS_COLORIMETRIC;\n break;\n }\n default:\n {\n intent=0;\n break;\n }\n }\n (void) WriteBlobLSBLong(image,(unsigned int) intent);\n (void) WriteBlobLSBLong(image,0x00); /* dummy profile data */\n (void) WriteBlobLSBLong(image,0x00); /* dummy profile length */\n (void) WriteBlobLSBLong(image,0x00); /* reserved */\n }\n }\n if (image->storage_class == PseudoClass)\n {\n unsigned char\n *bmp_colormap;\n\n /*\n Dump colormap to file.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Colormap: %.20g entries\",(double) image->colors);\n bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) (1UL <<\n bmp_info.bits_per_pixel),4*sizeof(*bmp_colormap));\n if (bmp_colormap == (unsigned char *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n q=bmp_colormap;\n for (i=0; i < (ssize_t) MagickMin((ssize_t) image->colors,(ssize_t) bmp_info.number_colors); i++)\n {\n *q++=ScaleQuantumToChar(image->colormap[i].blue);\n *q++=ScaleQuantumToChar(image->colormap[i].green);\n *q++=ScaleQuantumToChar(image->colormap[i].red);\n if (type > 2)\n *q++=(unsigned char) 0x0;\n }\n for ( ; i < (ssize_t) (1UL << bmp_info.bits_per_pixel); i++)\n {\n *q++=(unsigned char) 0x00;\n *q++=(unsigned char) 0x00;\n *q++=(unsigned char) 0x00;\n if (type > 2)\n *q++=(unsigned char) 0x00;\n }\n if (type <= 2)\n (void) WriteBlob(image,(size_t) (3*(1L << bmp_info.bits_per_pixel)),\n bmp_colormap);\n else\n (void) WriteBlob(image,(size_t) (4*(1L << bmp_info.bits_per_pixel)),\n bmp_colormap);\n bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Pixels: %u bytes\",bmp_info.image_size);\n (void) WriteBlob(image,(size_t) bmp_info.image_size,pixels);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (GetNextImageInList(image) == (Image *) NULL)\n break;\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);\n if (status == MagickFalse)\n break;\n } while (image_info->adjoin != MagickFalse);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" File_size: %u bytes\",bmp_info.file_size);\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/1177'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int handle_vmon(struct kvm_vcpu *vcpu)\n{\n\tint ret;\n\tgpa_t vmptr;\n\tstruct page *page;\n\tstruct vcpu_vmx *vmx = to_vmx(vcpu);\n\tconst u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED\n\t\t| FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;\n\n\t/*\n\t * The Intel VMX Instruction Reference lists a bunch of bits that are\n\t * prerequisite to running VMXON, most notably cr4.VMXE must be set to\n\t * 1 (see vmx_set_cr4() for when we allow the guest to set this).\n\t * Otherwise, we should fail with #UD. But most faulting conditions\n\t * have already been checked by hardware, prior to the VM-exit for\n\t * VMXON. We do test guest cr4.VMXE because processor CR4 always has\n\t * that bit set to 1 in non-root mode.\n\t */\n\tif (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE)) {\n\t\tkvm_queue_exception(vcpu, UD_VECTOR);\n\t\treturn 1;\n\t}\n\n\tif (vmx->nested.vmxon) {\n\t\tnested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION);\n\t\treturn kvm_skip_emulated_instruction(vcpu);\n\t}\n\n\tif ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)\n\t\t\t!= VMXON_NEEDED_FEATURES) {\n\t\tkvm_inject_gp(vcpu, 0);\n\t\treturn 1;\n\t}\n\n\tif (nested_vmx_get_vmptr(vcpu, &vmptr))\n\t\treturn 1;\n\n\t/*\n\t * SDM 3: 24.11.5\n\t * The first 4 bytes of VMXON region contain the supported\n\t * VMCS revision identifier\n\t *\n\t * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case;\n\t * which replaces physical address width with 32\n\t */\n\tif (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {\n\t\tnested_vmx_failInvalid(vcpu);\n\t\treturn kvm_skip_emulated_instruction(vcpu);\n\t}\n\n\tpage = kvm_vcpu_gpa_to_page(vcpu, vmptr);\n\tif (is_error_page(page)) {\n\t\tnested_vmx_failInvalid(vcpu);\n\t\treturn kvm_skip_emulated_instruction(vcpu);\n\t}\n\tif (*(u32 *)kmap(page) != VMCS12_REVISION) {\n\t\tkunmap(page);\n\t\tkvm_release_page_clean(page);\n\t\tnested_vmx_failInvalid(vcpu);\n\t\treturn kvm_skip_emulated_instruction(vcpu);\n\t}\n\tkunmap(page);\n\tkvm_release_page_clean(page);\n\n\tvmx->nested.vmxon_ptr = vmptr;\n\tret = enter_vmx_operation(vcpu);\n\tif (ret)\n\t\treturn ret;\n\n\tnested_vmx_succeed(vcpu);\n\treturn kvm_skip_emulated_instruction(vcpu);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284'], 'message': 'kvm: nVMX: Enforce cpl=0 for VMX instructions\n\nVMX instructions executed inside a L1 VM will always trigger a VM exit\neven when executed with cpl 3. This means we must perform the\nprivilege check in software.\n\nFixes: 70f3aac964ae(\"kvm: nVMX: Remove superfluous VMX instruction fault checks\")\nCc: stable@vger.kernel.org\nSigned-off-by: Felix Wilhelm \nSigned-off-by: Paolo Bonzini '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void RemoteFsDevice::mount()\n{\n if (details.isLocalFile()) {\n return;\n }\n if (isConnected() || proc) {\n return;\n }\n\n if (messageSent) {\n return;\n }\n if (constSambaAvahiProtocol==details.url.scheme()) {\n Details det=details;\n AvahiService *srv=Avahi::self()->getService(det.serviceName);\n if (!srv || srv->getHost().isEmpty() || 0==srv->getPort()) {\n emit error(tr(\"Failed to resolve connection details for %1\").arg(details.name));\n return;\n }\n if (constPromptPassword==det.url.password()) {\n bool ok=false;\n QString passwd=InputDialog::getPassword(QString(), &ok, QApplication::activeWindow());\n if (!ok) {\n return;\n }\n det.url.setPassword(passwd);\n }\n det.url.setScheme(constSambaProtocol);\n det.url.setHost(srv->getHost());\n det.url.setPort(srv->getPort());\n mounter()->mount(det.url.toString(), mountPoint(details, true), getuid(), getgid(), getpid());\n setStatusMessage(tr(\"Connecting...\"));\n messageSent=true;\n return;\n }\n if (constSambaProtocol==details.url.scheme()) {\n Details det=details;\n if (constPromptPassword==det.url.password()) {\n bool ok=false;\n QString passwd=InputDialog::getPassword(QString(), &ok, QApplication::activeWindow());\n if (!ok) {\n return;\n }\n det.url.setPassword(passwd);\n }\n mounter()->mount(det.url.toString(), mountPoint(details, true), getuid(), getgid(), getpid());\n setStatusMessage(tr(\"Connecting...\"));\n messageSent=true;\n return;\n }\n\n QString cmd;\n QStringList args;\n QString askPass;\n if (!details.isLocalFile() && !details.isEmpty()) {\n // If user has added 'IdentityFile' to extra options, then no password prompting is required...\n bool needAskPass=!details.extraOptions.contains(\"IdentityFile=\");\n\n if (needAskPass) {\n QStringList askPassList;\n if (Utils::KDE==Utils::currentDe()) {\n askPassList << QLatin1String(\"ksshaskpass\") << QLatin1String(\"ssh-askpass\") << QLatin1String(\"ssh-askpass-gnome\");\n } else {\n askPassList << QLatin1String(\"ssh-askpass-gnome\") << QLatin1String(\"ssh-askpass\") << QLatin1String(\"ksshaskpass\");\n }\n\n for (const QString &ap: askPassList) {\n askPass=Utils::findExe(ap);\n if (!askPass.isEmpty()) {\n break;\n }\n }\n\n if (askPass.isEmpty()) {\n emit error(tr(\"No suitable ssh-askpass application installed! This is required for entering passwords.\"));\n return;\n }\n }\n QString sshfs=Utils::findExe(\"sshfs\");\n if (sshfs.isEmpty()) {\n emit error(tr(\"\\\"sshfs\\\" is not installed!\"));\n return;\n }\n cmd=Utils::findExe(\"setsid\");\n if (!cmd.isEmpty()) {\n QString mp=mountPoint(details, true);\n if (mp.isEmpty()) {\n emit error(\"Failed to determine mount point\"); // TODO: 2.4 make translatable. For now, error should never happen!\n }\n if (!QDir(mp).entryList(QDir::NoDot|QDir::NoDotDot|QDir::AllEntries|QDir::Hidden).isEmpty()) {\n emit error(tr(\"Mount point (\\\"%1\\\") is not empty!\").arg(mp));\n return;\n }\n\n args << sshfs << details.url.userName()+QChar('@')+details.url.host()+QChar(':')+details.url.path()<< QLatin1String(\"-p\")\n << QString::number(details.url.port()) << mountPoint(details, true)\n << QLatin1String(\"-o\") << QLatin1String(\"ServerAliveInterval=15\");\n //<< QLatin1String(\"-o\") << QLatin1String(\"Ciphers=arcfour\");\n if (!details.extraOptions.isEmpty()) {\n args << details.extraOptions.split(' ', QString::SkipEmptyParts);\n }\n } else {\n emit error(tr(\"\\\"sshfs\\\" is not installed!\").replace(\"sshfs\", \"setsid\")); // TODO: 2.4 use correct string!\n }\n }\n\n if (!cmd.isEmpty()) {\n setStatusMessage(tr(\"Connecting...\"));\n proc=new QProcess(this);\n proc->setProperty(\"mount\", true);\n\n if (!askPass.isEmpty()) {\n QProcessEnvironment env = QProcessEnvironment::systemEnvironment();\n env.insert(\"SSH_ASKPASS\", askPass);\n proc->setProcessEnvironment(env);\n }\n connect(proc, SIGNAL(finished(int)), SLOT(procFinished(int)));\n proc->start(cmd, args, QIODevice::ReadOnly);\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: MpdCantataMounterInterface * RemoteFsDevice::mounter()\n{\n if (!mounterIface) {\n if (!QDBusConnection::systemBus().interface()->isServiceRegistered(MpdCantataMounterInterface::staticInterfaceName())) {\n QDBusConnection::systemBus().interface()->startService(MpdCantataMounterInterface::staticInterfaceName());\n }\n mounterIface=new MpdCantataMounterInterface(MpdCantataMounterInterface::staticInterfaceName(),\n \"/Mounter\", QDBusConnection::systemBus(), this);\n connect(mounterIface, SIGNAL(mountStatus(const QString &, int, int)), SLOT(mountStatus(const QString &, int, int)));\n connect(mounterIface, SIGNAL(umountStatus(const QString &, int, int)), SLOT(umountStatus(const QString &, int, int)));\n }\n return mounterIface;\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: AvahiService::~AvahiService()\n{\n stop();\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: Avahi * Avahi::self()\n{\n #ifdef ENABLE_KDE_SUPPORT\n return instance;\n #else\n static Avahi *instance=0;\n if(!instance) {\n instance=new Avahi;\n }\n return instance;\n #endif\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: int main(int argc G_GNUC_UNUSED, char **argv G_GNUC_UNUSED)\n{\n SpiceMarshaller *marshaller;\n SpiceMsgMainShortDataSubMarshall *msg;\n size_t len, msg_len;\n int free_res;\n uint8_t *data;\n message_destructor_t free_message;\n\n msg = g_new0(SpiceMsgMainShortDataSubMarshall, 1);\n msg->data = g_new(uint64_t, 2);\n msg->dummy_byte = 123;\n msg->data_size = 2;\n msg->data[0] = 0x1234567890abcdef;\n msg->data[1] = 0xfedcba0987654321;\n\n marshaller = spice_marshaller_new();\n spice_marshall_msg_main_ShortDataSubMarshall(marshaller, msg);\n spice_marshaller_flush(marshaller);\n data = spice_marshaller_linearize(marshaller, 0, &len, &free_res);\n g_assert_cmpint(len, ==, G_N_ELEMENTS(expected_data));\n g_assert_true(memcmp(data, expected_data, len) == 0);\n\n g_free(msg->data);\n g_free(msg);\n\n // test demarshaller\n msg = (SpiceMsgMainShortDataSubMarshall *)\n spice_parse_msg(data, data + len, SPICE_CHANNEL_MAIN, SPICE_MSG_MAIN_SHORTDATASUBMARSHALL,\n 0, &msg_len, &free_message);\n\n g_assert_nonnull(msg);\n g_assert_cmpint(msg->dummy_byte, ==, 123);\n g_assert_cmpint(msg->data_size, ==, 2);\n g_assert_nonnull(msg->data);\n g_assert_cmpint(msg->data[0], ==, 0x1234567890abcdef);\n g_assert_cmpint(msg->data[1], ==, 0xfedcba0987654321);\n\n free_message((uint8_t *) msg);\n\n if (free_res) {\n free(data);\n }\n spice_marshaller_reset(marshaller);\n\n SpiceMsgMainZeroes msg_zeroes = { 0x0102 };\n\n spice_marshall_msg_main_Zeroes(marshaller, &msg_zeroes);\n spice_marshaller_flush(marshaller);\n data = spice_marshaller_linearize(marshaller, 0, &len, &free_res);\n g_assert_cmpint(len, ==, 7);\n g_assert_true(memcmp(data, \"\\x00\\x02\\x01\\x00\\x00\\x00\\x00\", 7) == 0);\n if (free_res) {\n free(data);\n }\n\n test_overflow(marshaller);\n\n spice_marshaller_destroy(marshaller);\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix flexible array buffer overflow\n\nThis is kind of a DoS, possibly flexible array in the protocol\ncauses the network size check to be ignored due to integer overflows.\n\nThe size of flexible array is computed as (message_end - position),\nthen this size is added to the number of bytes before the array and\nthis number is used to check if we overflow initial message.\n\nAn example is:\n\n message {\n uint32 dummy[2];\n uint8 data[] @end;\n } LenMessage;\n\nwhich generated this (simplified remove useless code) code:\n\n { /* data */\n data__nelements = message_end - (start + 8);\n\n data__nw_size = data__nelements;\n }\n\n nw_size = 8 + data__nw_size;\n\n /* Check if message fits in reported side */\n if (nw_size > (uintptr_t) (message_end - start)) {\n return NULL;\n }\n\nFollowing code:\n- data__nelements == message_end - (start + 8)\n- data__nw_size == data__nelements == message_end - (start + 8)\n- nw_size == 8 + data__nw_size == 8 + message_end - (start + 8) ==\n 8 + message_end - start - 8 == message_end -start\n- the check for overflow is (nw_size > (message_end - start)) but\n nw_size == message_end - start so the check is doing\n ((message_end - start) > (message_end - start)) which is always false.\n\nIf message_end - start < 8 then data__nelements (number of element\non the array above) computation generate an integer underflow that\nlater create a buffer overflow.\n\nAdd a check to make sure that the array starts before the message ends\nto avoid the overflow.\n\nDifference is:\n diff -u save/generated_client_demarshallers1.c common/generated_client_demarshallers1.c\n --- save/generated_client_demarshallers1.c\t2018-06-22 22:13:48.626793919 +0100\n +++ common/generated_client_demarshallers1.c\t2018-06-22 22:14:03.408163291 +0100\n @@ -225,6 +225,9 @@\n uint64_t data__nelements;\n\n { /* data */\n + if (SPICE_UNLIKELY((start + 0) > message_end)) {\n + goto error;\n + }\n data__nelements = message_end - (start + 0);\n\n data__nw_size = data__nelements;\n @@ -243,6 +246,9 @@\n *free_message = nofree;\n return data;\n\n + error:\n + free(data);\n + return NULL;\n }\n\n static uint8_t * parse_msg_set_ack(uint8_t *message_start, uint8_t *message_end, SPICE_GNUC_UNUSED int minor, size_t *size, message_destructor_t *free_message)\n @@ -301,6 +307,9 @@\n SpiceMsgPing *out;\n\n { /* data */\n + if (SPICE_UNLIKELY((start + 12) > message_end)) {\n + goto error;\n + }\n data__nelements = message_end - (start + 12);\n\n data__nw_size = data__nelements;\n @@ -5226,6 +5235,9 @@\n uint64_t cursor_data__nw_size;\n uint64_t cursor_data__nelements;\n { /* data */\n + if (SPICE_UNLIKELY((start2 + 22) > message_end)) {\n + goto error;\n + }\n cursor_data__nelements = message_end - (start2 + 22);\n\n cursor_data__nw_size = cursor_data__nelements;\n @@ -5305,6 +5317,9 @@\n uint64_t cursor_data__nw_size;\n uint64_t cursor_data__nelements;\n { /* data */\n + if (SPICE_UNLIKELY((start2 + 22) > message_end)) {\n + goto error;\n + }\n cursor_data__nelements = message_end - (start2 + 22);\n\n cursor_data__nw_size = cursor_data__nelements;\n @@ -5540,6 +5555,9 @@\n SpiceMsgPlaybackPacket *out;\n\n { /* data */\n + if (SPICE_UNLIKELY((start + 4) > message_end)) {\n + goto error;\n + }\n data__nelements = message_end - (start + 4);\n\n data__nw_size = data__nelements;\n @@ -5594,6 +5612,9 @@\n SpiceMsgPlaybackMode *out;\n\n { /* data */\n + if (SPICE_UNLIKELY((start + 8) > message_end)) {\n + goto error;\n + }\n data__nelements = message_end - (start + 8);\n\n data__nw_size = data__nelements;\n diff -u save/generated_client_demarshallers.c common/generated_client_demarshallers.c\n --- save/generated_client_demarshallers.c\t2018-06-22 22:13:48.626793919 +0100\n +++ common/generated_client_demarshallers.c\t2018-06-22 22:14:03.004153195 +0100\n @@ -225,6 +225,9 @@\n uint64_t data__nelements;\n\n { /* data */\n + if (SPICE_UNLIKELY((start + 0) > message_end)) {\n + goto error;\n + }\n data__nelements = message_end - (start + 0);\n\n data__nw_size = data__nelements;\n @@ -243,6 +246,9 @@\n *free_message = nofree;\n return data;\n\n + error:\n + free(data);\n + return NULL;\n }\n\n static uint8_t * parse_msg_set_ack(uint8_t *message_start, uint8_t *message_end, SPICE_GNUC_UNUSED int minor, size_t *size, message_destructor_t *free_message)\n @@ -301,6 +307,9 @@\n SpiceMsgPing *out;\n\n { /* data */\n + if (SPICE_UNLIKELY((start + 12) > message_end)) {\n + goto error;\n + }\n data__nelements = message_end - (start + 12);\n\n data__nw_size = data__nelements;\n @@ -6574,6 +6583,9 @@\n }\n\n { /* data */\n + if (SPICE_UNLIKELY((start2 + 2 + cursor_u__nw_size) > message_end)) {\n + goto error;\n + }\n cursor_data__nelements = message_end - (start2 + 2 + cursor_u__nw_size);\n\n cursor_data__nw_size = cursor_data__nelements;\n @@ -6670,6 +6682,9 @@\n }\n\n { /* data */\n + if (SPICE_UNLIKELY((start2 + 2 + cursor_u__nw_size) > message_end)) {\n + goto error;\n + }\n cursor_data__nelements = message_end - (start2 + 2 + cursor_u__nw_size);\n\n cursor_data__nw_size = cursor_data__nelements;\n @@ -6907,6 +6922,9 @@\n SpiceMsgPlaybackPacket *out;\n\n { /* data */\n + if (SPICE_UNLIKELY((start + 4) > message_end)) {\n + goto error;\n + }\n data__nelements = message_end - (start + 4);\n\n data__nw_size = data__nelements;\n @@ -6961,6 +6979,9 @@\n SpiceMsgPlaybackMode *out;\n\n { /* data */\n + if (SPICE_UNLIKELY((start + 6) > message_end)) {\n + goto error;\n + }\n data__nelements = message_end - (start + 6);\n\n data__nw_size = data__nelements;\n @@ -7559,6 +7580,9 @@\n SpiceMsgTunnelSocketData *out;\n\n { /* data */\n + if (SPICE_UNLIKELY((start + 2) > message_end)) {\n + goto error;\n + }\n data__nelements = message_end - (start + 2);\n\n data__nw_size = data__nelements;\n @@ -7840,6 +7864,9 @@\n }\n\n { /* compressed_data */\n + if (SPICE_UNLIKELY((start + 1 + u__nw_size) > message_end)) {\n + goto error;\n + }\n compressed_data__nelements = message_end - (start + 1 + u__nw_size);\n\n compressed_data__nw_size = compressed_data__nelements;\n diff -u save/generated_server_demarshallers.c common/generated_server_demarshallers.c\n --- save/generated_server_demarshallers.c\t2018-06-22 22:13:48.627793944 +0100\n +++ common/generated_server_demarshallers.c\t2018-06-22 22:14:05.231208847 +0100\n @@ -306,6 +306,9 @@\n uint64_t data__nelements;\n\n { /* data */\n + if (SPICE_UNLIKELY((start + 0) > message_end)) {\n + goto error;\n + }\n data__nelements = message_end - (start + 0);\n\n data__nw_size = data__nelements;\n @@ -324,6 +327,9 @@\n *free_message = nofree;\n return data;\n\n + error:\n + free(data);\n + return NULL;\n }\n\n static uint8_t * parse_msgc_disconnecting(uint8_t *message_start, uint8_t *message_end, SPICE_GNUC_UNUSED int minor, size_t *size, message_destructor_t *free_message)\n @@ -1259,6 +1265,9 @@\n SpiceMsgcRecordPacket *out;\n\n { /* data */\n + if (SPICE_UNLIKELY((start + 4) > message_end)) {\n + goto error;\n + }\n data__nelements = message_end - (start + 4);\n\n data__nw_size = data__nelements;\n @@ -1313,6 +1322,9 @@\n SpiceMsgcRecordMode *out;\n\n { /* data */\n + if (SPICE_UNLIKELY((start + 6) > message_end)) {\n + goto error;\n + }\n data__nelements = message_end - (start + 6);\n\n data__nw_size = data__nelements;\n @@ -1841,6 +1853,9 @@\n SpiceMsgcTunnelSocketData *out;\n\n { /* data */\n + if (SPICE_UNLIKELY((start + 2) > message_end)) {\n + goto error;\n + }\n data__nelements = message_end - (start + 2);\n\n data__nw_size = data__nelements;\n @@ -2057,6 +2072,9 @@\n }\n\n { /* compressed_data */\n + if (SPICE_UNLIKELY((start + 1 + u__nw_size) > message_end)) {\n + goto error;\n + }\n compressed_data__nelements = message_end - (start + 1 + u__nw_size);\n\n compressed_data__nw_size = compressed_data__nelements;\n\nSigned-off-by: Frediano Ziglio \nSigned-off-by: Christophe Fergeau '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (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_xattr_set_entry(struct ext4_xattr_info *i,\n\t\t\t\tstruct ext4_xattr_search *s,\n\t\t\t\thandle_t *handle, struct inode *inode,\n\t\t\t\tbool is_block)\n{\n\tstruct ext4_xattr_entry *last;\n\tstruct ext4_xattr_entry *here = s->here;\n\tsize_t min_offs = s->end - s->base, name_len = strlen(i->name);\n\tint in_inode = i->in_inode;\n\tstruct inode *old_ea_inode = NULL;\n\tstruct inode *new_ea_inode = NULL;\n\tsize_t old_size, new_size;\n\tint ret;\n\n\t/* Space used by old and new values. */\n\told_size = (!s->not_found && !here->e_value_inum) ?\n\t\t\tEXT4_XATTR_SIZE(le32_to_cpu(here->e_value_size)) : 0;\n\tnew_size = (i->value && !in_inode) ? EXT4_XATTR_SIZE(i->value_len) : 0;\n\n\t/*\n\t * Optimization for the simple case when old and new values have the\n\t * same padded sizes. Not applicable if external inodes are involved.\n\t */\n\tif (new_size && new_size == old_size) {\n\t\tsize_t offs = le16_to_cpu(here->e_value_offs);\n\t\tvoid *val = s->base + offs;\n\n\t\there->e_value_size = cpu_to_le32(i->value_len);\n\t\tif (i->value == EXT4_ZERO_XATTR_VALUE) {\n\t\t\tmemset(val, 0, new_size);\n\t\t} else {\n\t\t\tmemcpy(val, i->value, i->value_len);\n\t\t\t/* Clear padding bytes. */\n\t\t\tmemset(val + i->value_len, 0, new_size - i->value_len);\n\t\t}\n\t\tgoto update_hash;\n\t}\n\n\t/* Compute min_offs and last. */\n\tlast = s->first;\n\tfor (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {\n\t\tif (!last->e_value_inum && last->e_value_size) {\n\t\t\tsize_t offs = le16_to_cpu(last->e_value_offs);\n\t\t\tif (offs < min_offs)\n\t\t\t\tmin_offs = offs;\n\t\t}\n\t}\n\n\t/* Check whether we have enough space. */\n\tif (i->value) {\n\t\tsize_t free;\n\n\t\tfree = min_offs - ((void *)last - s->base) - sizeof(__u32);\n\t\tif (!s->not_found)\n\t\t\tfree += EXT4_XATTR_LEN(name_len) + old_size;\n\n\t\tif (free < EXT4_XATTR_LEN(name_len) + new_size) {\n\t\t\tret = -ENOSPC;\n\t\t\tgoto out;\n\t\t}\n\n\t\t/*\n\t\t * If storing the value in an external inode is an option,\n\t\t * reserve space for xattr entries/names in the external\n\t\t * attribute block so that a long value does not occupy the\n\t\t * whole space and prevent futher entries being added.\n\t\t */\n\t\tif (ext4_has_feature_ea_inode(inode->i_sb) &&\n\t\t new_size && is_block &&\n\t\t (min_offs + old_size - new_size) <\n\t\t\t\t\tEXT4_XATTR_BLOCK_RESERVE(inode)) {\n\t\t\tret = -ENOSPC;\n\t\t\tgoto out;\n\t\t}\n\t}\n\n\t/*\n\t * Getting access to old and new ea inodes is subject to failures.\n\t * Finish that work before doing any modifications to the xattr data.\n\t */\n\tif (!s->not_found && here->e_value_inum) {\n\t\tret = ext4_xattr_inode_iget(inode,\n\t\t\t\t\t le32_to_cpu(here->e_value_inum),\n\t\t\t\t\t le32_to_cpu(here->e_hash),\n\t\t\t\t\t &old_ea_inode);\n\t\tif (ret) {\n\t\t\told_ea_inode = NULL;\n\t\t\tgoto out;\n\t\t}\n\t}\n\tif (i->value && in_inode) {\n\t\tWARN_ON_ONCE(!i->value_len);\n\n\t\tret = ext4_xattr_inode_alloc_quota(inode, i->value_len);\n\t\tif (ret)\n\t\t\tgoto out;\n\n\t\tret = ext4_xattr_inode_lookup_create(handle, inode, i->value,\n\t\t\t\t\t\t i->value_len,\n\t\t\t\t\t\t &new_ea_inode);\n\t\tif (ret) {\n\t\t\tnew_ea_inode = NULL;\n\t\t\text4_xattr_inode_free_quota(inode, NULL, i->value_len);\n\t\t\tgoto out;\n\t\t}\n\t}\n\n\tif (old_ea_inode) {\n\t\t/* We are ready to release ref count on the old_ea_inode. */\n\t\tret = ext4_xattr_inode_dec_ref(handle, old_ea_inode);\n\t\tif (ret) {\n\t\t\t/* Release newly required ref count on new_ea_inode. */\n\t\t\tif (new_ea_inode) {\n\t\t\t\tint err;\n\n\t\t\t\terr = ext4_xattr_inode_dec_ref(handle,\n\t\t\t\t\t\t\t new_ea_inode);\n\t\t\t\tif (err)\n\t\t\t\t\text4_warning_inode(new_ea_inode,\n\t\t\t\t\t\t \"dec ref new_ea_inode err=%d\",\n\t\t\t\t\t\t err);\n\t\t\t\text4_xattr_inode_free_quota(inode, new_ea_inode,\n\t\t\t\t\t\t\t i->value_len);\n\t\t\t}\n\t\t\tgoto out;\n\t\t}\n\n\t\text4_xattr_inode_free_quota(inode, old_ea_inode,\n\t\t\t\t\t le32_to_cpu(here->e_value_size));\n\t}\n\n\t/* No failures allowed past this point. */\n\n\tif (!s->not_found && here->e_value_size && here->e_value_offs) {\n\t\t/* Remove the old value. */\n\t\tvoid *first_val = s->base + min_offs;\n\t\tsize_t offs = le16_to_cpu(here->e_value_offs);\n\t\tvoid *val = s->base + offs;\n\n\t\tmemmove(first_val + old_size, first_val, val - first_val);\n\t\tmemset(first_val, 0, old_size);\n\t\tmin_offs += old_size;\n\n\t\t/* Adjust all value offsets. */\n\t\tlast = s->first;\n\t\twhile (!IS_LAST_ENTRY(last)) {\n\t\t\tsize_t o = le16_to_cpu(last->e_value_offs);\n\n\t\t\tif (!last->e_value_inum &&\n\t\t\t last->e_value_size && o < offs)\n\t\t\t\tlast->e_value_offs = cpu_to_le16(o + old_size);\n\t\t\tlast = EXT4_XATTR_NEXT(last);\n\t\t}\n\t}\n\n\tif (!i->value) {\n\t\t/* Remove old name. */\n\t\tsize_t size = EXT4_XATTR_LEN(name_len);\n\n\t\tlast = ENTRY((void *)last - size);\n\t\tmemmove(here, (void *)here + size,\n\t\t\t(void *)last - (void *)here + sizeof(__u32));\n\t\tmemset(last, 0, size);\n\t} else if (s->not_found) {\n\t\t/* Insert new name. */\n\t\tsize_t size = EXT4_XATTR_LEN(name_len);\n\t\tsize_t rest = (void *)last - (void *)here + sizeof(__u32);\n\n\t\tmemmove((void *)here + size, here, rest);\n\t\tmemset(here, 0, size);\n\t\there->e_name_index = i->name_index;\n\t\there->e_name_len = name_len;\n\t\tmemcpy(here->e_name, i->name, name_len);\n\t} else {\n\t\t/* This is an update, reset value info. */\n\t\there->e_value_inum = 0;\n\t\there->e_value_offs = 0;\n\t\there->e_value_size = 0;\n\t}\n\n\tif (i->value) {\n\t\t/* Insert new value. */\n\t\tif (in_inode) {\n\t\t\there->e_value_inum = cpu_to_le32(new_ea_inode->i_ino);\n\t\t} else if (i->value_len) {\n\t\t\tvoid *val = s->base + min_offs - new_size;\n\n\t\t\there->e_value_offs = cpu_to_le16(min_offs - new_size);\n\t\t\tif (i->value == EXT4_ZERO_XATTR_VALUE) {\n\t\t\t\tmemset(val, 0, new_size);\n\t\t\t} else {\n\t\t\t\tmemcpy(val, i->value, i->value_len);\n\t\t\t\t/* Clear padding bytes. */\n\t\t\t\tmemset(val + i->value_len, 0,\n\t\t\t\t new_size - i->value_len);\n\t\t\t}\n\t\t}\n\t\there->e_value_size = cpu_to_le32(i->value_len);\n\t}\n\nupdate_hash:\n\tif (i->value) {\n\t\t__le32 hash = 0;\n\n\t\t/* Entry hash calculation. */\n\t\tif (in_inode) {\n\t\t\t__le32 crc32c_hash;\n\n\t\t\t/*\n\t\t\t * Feed crc32c hash instead of the raw value for entry\n\t\t\t * hash calculation. This is to avoid walking\n\t\t\t * potentially long value buffer again.\n\t\t\t */\n\t\t\tcrc32c_hash = cpu_to_le32(\n\t\t\t\t ext4_xattr_inode_get_hash(new_ea_inode));\n\t\t\thash = ext4_xattr_hash_entry(here->e_name,\n\t\t\t\t\t\t here->e_name_len,\n\t\t\t\t\t\t &crc32c_hash, 1);\n\t\t} else if (is_block) {\n\t\t\t__le32 *value = s->base + le16_to_cpu(\n\t\t\t\t\t\t\there->e_value_offs);\n\n\t\t\thash = ext4_xattr_hash_entry(here->e_name,\n\t\t\t\t\t\t here->e_name_len, value,\n\t\t\t\t\t\t new_size >> 2);\n\t\t}\n\t\there->e_hash = hash;\n\t}\n\n\tif (is_block)\n\t\text4_xattr_rehash((struct ext4_xattr_header *)s->base);\n\n\tret = 0;\nout:\n\tiput(old_ea_inode);\n\tiput(new_ea_inode);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'ext4: add corruption check in ext4_xattr_set_entry()\n\nIn theory this should have been caught earlier when the xattr list was\nverified, but in case it got missed, it's simple enough to add check\nto make sure we don't overrun the xattr buffer.\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: int jbd2_journal_dirty_metadata(handle_t *handle, struct buffer_head *bh)\n{\n\ttransaction_t *transaction = handle->h_transaction;\n\tjournal_t *journal;\n\tstruct journal_head *jh;\n\tint ret = 0;\n\n\tif (is_handle_aborted(handle))\n\t\treturn -EROFS;\n\tif (!buffer_jbd(bh)) {\n\t\tret = -EUCLEAN;\n\t\tgoto out;\n\t}\n\t/*\n\t * We don't grab jh reference here since the buffer must be part\n\t * of the running transaction.\n\t */\n\tjh = bh2jh(bh);\n\t/*\n\t * This and the following assertions are unreliable since we may see jh\n\t * in inconsistent state unless we grab bh_state lock. But this is\n\t * crucial to catch bugs so let's do a reliable check until the\n\t * lockless handling is fully proven.\n\t */\n\tif (jh->b_transaction != transaction &&\n\t jh->b_next_transaction != transaction) {\n\t\tjbd_lock_bh_state(bh);\n\t\tJ_ASSERT_JH(jh, jh->b_transaction == transaction ||\n\t\t\t\tjh->b_next_transaction == transaction);\n\t\tjbd_unlock_bh_state(bh);\n\t}\n\tif (jh->b_modified == 1) {\n\t\t/* If it's in our transaction it must be in BJ_Metadata list. */\n\t\tif (jh->b_transaction == transaction &&\n\t\t jh->b_jlist != BJ_Metadata) {\n\t\t\tjbd_lock_bh_state(bh);\n\t\t\tJ_ASSERT_JH(jh, jh->b_transaction != transaction ||\n\t\t\t\t\tjh->b_jlist == BJ_Metadata);\n\t\t\tjbd_unlock_bh_state(bh);\n\t\t}\n\t\tgoto out;\n\t}\n\n\tjournal = transaction->t_journal;\n\tjbd_debug(5, \"journal_head %p\\n\", jh);\n\tJBUFFER_TRACE(jh, \"entry\");\n\n\tjbd_lock_bh_state(bh);\n\n\tif (jh->b_modified == 0) {\n\t\t/*\n\t\t * This buffer's got modified and becoming part\n\t\t * of the transaction. This needs to be done\n\t\t * once a transaction -bzzz\n\t\t */\n\t\tjh->b_modified = 1;\n\t\tif (handle->h_buffer_credits <= 0) {\n\t\t\tret = -ENOSPC;\n\t\t\tgoto out_unlock_bh;\n\t\t}\n\t\thandle->h_buffer_credits--;\n\t}\n\n\t/*\n\t * fastpath, to avoid expensive locking. If this buffer is already\n\t * on the running transaction's metadata list there is nothing to do.\n\t * Nobody can take it off again because there is a handle open.\n\t * I _think_ we're OK here with SMP barriers - a mistaken decision will\n\t * result in this test being false, so we go in and take the locks.\n\t */\n\tif (jh->b_transaction == transaction && jh->b_jlist == BJ_Metadata) {\n\t\tJBUFFER_TRACE(jh, \"fastpath\");\n\t\tif (unlikely(jh->b_transaction !=\n\t\t\t journal->j_running_transaction)) {\n\t\t\tprintk(KERN_ERR \"JBD2: %s: \"\n\t\t\t \"jh->b_transaction (%llu, %p, %u) != \"\n\t\t\t \"journal->j_running_transaction (%p, %u)\\n\",\n\t\t\t journal->j_devname,\n\t\t\t (unsigned long long) bh->b_blocknr,\n\t\t\t jh->b_transaction,\n\t\t\t jh->b_transaction ? jh->b_transaction->t_tid : 0,\n\t\t\t journal->j_running_transaction,\n\t\t\t journal->j_running_transaction ?\n\t\t\t journal->j_running_transaction->t_tid : 0);\n\t\t\tret = -EINVAL;\n\t\t}\n\t\tgoto out_unlock_bh;\n\t}\n\n\tset_buffer_jbddirty(bh);\n\n\t/*\n\t * Metadata already on the current transaction list doesn't\n\t * need to be filed. Metadata on another transaction's list must\n\t * be committing, and will be refiled once the commit completes:\n\t * leave it alone for now.\n\t */\n\tif (jh->b_transaction != transaction) {\n\t\tJBUFFER_TRACE(jh, \"already on other transaction\");\n\t\tif (unlikely(((jh->b_transaction !=\n\t\t\t journal->j_committing_transaction)) ||\n\t\t\t (jh->b_next_transaction != transaction))) {\n\t\t\tprintk(KERN_ERR \"jbd2_journal_dirty_metadata: %s: \"\n\t\t\t \"bad jh for block %llu: \"\n\t\t\t \"transaction (%p, %u), \"\n\t\t\t \"jh->b_transaction (%p, %u), \"\n\t\t\t \"jh->b_next_transaction (%p, %u), jlist %u\\n\",\n\t\t\t journal->j_devname,\n\t\t\t (unsigned long long) bh->b_blocknr,\n\t\t\t transaction, transaction->t_tid,\n\t\t\t jh->b_transaction,\n\t\t\t jh->b_transaction ?\n\t\t\t jh->b_transaction->t_tid : 0,\n\t\t\t jh->b_next_transaction,\n\t\t\t jh->b_next_transaction ?\n\t\t\t jh->b_next_transaction->t_tid : 0,\n\t\t\t jh->b_jlist);\n\t\t\tWARN_ON(1);\n\t\t\tret = -EINVAL;\n\t\t}\n\t\t/* And this case is illegal: we can't reuse another\n\t\t * transaction's data buffer, ever. */\n\t\tgoto out_unlock_bh;\n\t}\n\n\t/* That test should have eliminated the following case: */\n\tJ_ASSERT_JH(jh, jh->b_frozen_data == NULL);\n\n\tJBUFFER_TRACE(jh, \"file as BJ_Metadata\");\n\tspin_lock(&journal->j_list_lock);\n\t__jbd2_journal_file_buffer(jh, transaction, BJ_Metadata);\n\tspin_unlock(&journal->j_list_lock);\nout_unlock_bh:\n\tjbd_unlock_bh_state(bh);\nout:\n\tJBUFFER_TRACE(jh, \"exit\");\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'jbd2: don't mark block as modified if the handle is out of credits\n\nDo not set the b_modified flag in block's journal head should not\nuntil after we're sure that jbd2_journal_dirty_metadat() will not\nabort with an error due to there not being enough space reserved in\nthe jbd2 handle.\n\nOtherwise, future attempts to modify the buffer may lead a large\nnumber of spurious errors and warnings.\n\nThis addresses CVE-2018-10883.\n\nhttps://bugzilla.kernel.org/show_bug.cgi?id=200071\n\nSigned-off-by: Theodore Ts'o \nCc: stable@kernel.org'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xfs_iget_cache_miss(\n\tstruct xfs_mount\t*mp,\n\tstruct xfs_perag\t*pag,\n\txfs_trans_t\t\t*tp,\n\txfs_ino_t\t\tino,\n\tstruct xfs_inode\t**ipp,\n\tint\t\t\tflags,\n\tint\t\t\tlock_flags)\n{\n\tstruct xfs_inode\t*ip;\n\tint\t\t\terror;\n\txfs_agino_t\t\tagino = XFS_INO_TO_AGINO(mp, ino);\n\tint\t\t\tiflags;\n\n\tip = xfs_inode_alloc(mp, ino);\n\tif (!ip)\n\t\treturn -ENOMEM;\n\n\terror = xfs_iread(mp, tp, ip, flags);\n\tif (error)\n\t\tgoto out_destroy;\n\n\tif (!xfs_inode_verify_forks(ip)) {\n\t\terror = -EFSCORRUPTED;\n\t\tgoto out_destroy;\n\t}\n\n\ttrace_xfs_iget_miss(ip);\n\n\n\t/*\n\t * If we are allocating a new inode, then check what was returned is\n\t * actually a free, empty inode. If we are not allocating an inode,\n\t * the check we didn't find a free inode.\n\t */\n\tif (flags & XFS_IGET_CREATE) {\n\t\tif (VFS_I(ip)->i_mode != 0) {\n\t\t\txfs_warn(mp,\n\"Corruption detected! Free inode 0x%llx not marked free on disk\",\n\t\t\t\tino);\n\t\t\terror = -EFSCORRUPTED;\n\t\t\tgoto out_destroy;\n\t\t}\n\t\tif (ip->i_d.di_nblocks != 0) {\n\t\t\txfs_warn(mp,\n\"Corruption detected! Free inode 0x%llx has blocks allocated!\",\n\t\t\t\tino);\n\t\t\terror = -EFSCORRUPTED;\n\t\t\tgoto out_destroy;\n\t\t}\n\t} else if (VFS_I(ip)->i_mode == 0) {\n\t\terror = -ENOENT;\n\t\tgoto out_destroy;\n\t}\n\n\t/*\n\t * Preload the radix tree so we can insert safely under the\n\t * write spinlock. Note that we cannot sleep inside the preload\n\t * region. Since we can be called from transaction context, don't\n\t * recurse into the file system.\n\t */\n\tif (radix_tree_preload(GFP_NOFS)) {\n\t\terror = -EAGAIN;\n\t\tgoto out_destroy;\n\t}\n\n\t/*\n\t * Because the inode hasn't been added to the radix-tree yet it can't\n\t * be found by another thread, so we can do the non-sleeping lock here.\n\t */\n\tif (lock_flags) {\n\t\tif (!xfs_ilock_nowait(ip, lock_flags))\n\t\t\tBUG();\n\t}\n\n\t/*\n\t * These values must be set before inserting the inode into the radix\n\t * tree as the moment it is inserted a concurrent lookup (allowed by the\n\t * RCU locking mechanism) can find it and that lookup must see that this\n\t * is an inode currently under construction (i.e. that XFS_INEW is set).\n\t * The ip->i_flags_lock that protects the XFS_INEW flag forms the\n\t * memory barrier that ensures this detection works correctly at lookup\n\t * time.\n\t */\n\tiflags = XFS_INEW;\n\tif (flags & XFS_IGET_DONTCACHE)\n\t\tiflags |= XFS_IDONTCACHE;\n\tip->i_udquot = NULL;\n\tip->i_gdquot = NULL;\n\tip->i_pdquot = NULL;\n\txfs_iflags_set(ip, iflags);\n\n\t/* insert the new inode */\n\tspin_lock(&pag->pag_ici_lock);\n\terror = radix_tree_insert(&pag->pag_ici_root, agino, ip);\n\tif (unlikely(error)) {\n\t\tWARN_ON(error != -EEXIST);\n\t\tXFS_STATS_INC(mp, xs_ig_dup);\n\t\terror = -EAGAIN;\n\t\tgoto out_preload_end;\n\t}\n\tspin_unlock(&pag->pag_ici_lock);\n\tradix_tree_preload_end();\n\n\t*ipp = ip;\n\treturn 0;\n\nout_preload_end:\n\tspin_unlock(&pag->pag_ici_lock);\n\tradix_tree_preload_end();\n\tif (lock_flags)\n\t\txfs_iunlock(ip, lock_flags);\nout_destroy:\n\t__destroy_inode(VFS_I(ip));\n\txfs_inode_free(ip);\n\treturn error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'xfs: validate cached inodes are free when allocated\n\nA recent fuzzed filesystem image cached random dcache corruption\nwhen the reproducer was run. This often showed up as panics in\nlookup_slow() on a null inode->i_ops pointer when doing pathwalks.\n\nBUG: unable to handle kernel NULL pointer dereference at 0000000000000000\n....\nCall Trace:\n lookup_slow+0x44/0x60\n walk_component+0x3dd/0x9f0\n link_path_walk+0x4a7/0x830\n path_lookupat+0xc1/0x470\n filename_lookup+0x129/0x270\n user_path_at_empty+0x36/0x40\n path_listxattr+0x98/0x110\n SyS_listxattr+0x13/0x20\n do_syscall_64+0xf5/0x280\n entry_SYSCALL_64_after_hwframe+0x42/0xb7\n\nbut had many different failure modes including deadlocks trying to\nlock the inode that was just allocated or KASAN reports of\nuse-after-free violations.\n\nThe cause of the problem was a corrupt INOBT on a v4 fs where the\nroot inode was marked as free in the inobt record. Hence when we\nallocated an inode, it chose the root inode to allocate, found it in\nthe cache and re-initialised it.\n\nWe recently fixed a similar inode allocation issue caused by inobt\nrecord corruption problem in xfs_iget_cache_miss() in commit\nee457001ed6c (\"xfs: catch inode allocation state mismatch\ncorruption\"). This change adds similar checks to the cache-hit path\nto catch it, and turns the reproducer into a corruption shutdown\nsituation.\n\nReported-by: Wen Xu \nSigned-Off-By: Dave Chinner \nReviewed-by: Christoph Hellwig \nReviewed-by: Carlos Maiolino \nReviewed-by: Darrick J. Wong \n[darrick: fix typos in comment]\nSigned-off-by: Darrick J. Wong '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *XMagickCommand(Display *display,XResourceInfo *resource_info,\n XWindows *windows,const CommandType command_type,Image **image,\n MagickStatusType *state,ExceptionInfo *exception)\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 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[MagickPathExtent] = \"*\";\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 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],MagickPathExtent);\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 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[MagickPathExtent];\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,MagickPathExtent,\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,exception);\n (void) CopyMagickString(windows->image.name,title,MagickPathExtent);\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,exception);\n if (status == MagickFalse)\n {\n char\n message[MagickPathExtent];\n\n (void) FormatLocaleString(message,MagickPathExtent,\"%s:%s\",\n exception->reason != (char *) NULL ? exception->reason : \"\",\n exception->description != (char *) NULL ? exception->description :\n \"\");\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 exception);\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[MagickPathExtent],\n *url;\n\n /*\n Display documentation using Netscape remote control.\n */\n url=GetMagickHomeURL();\n (void) FormatLocaleString(command,MagickPathExtent,\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,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 RateTransposer::setChannels(int nChannels)\r\n{\r\n assert(nChannels > 0);\r\n\r\n if (pTransposer->numChannels == nChannels) return;\r\n pTransposer->setChannels(nChannels);\r\n\r\n inputBuffer.setChannels(nChannels);\r\n midBuffer.setChannels(nChannels);\r\n outputBuffer.setChannels(nChannels);\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_sync_mailbox (CONTEXT *ctx, int *index_hint)\n{\n int i, j, ret = 0;\n char buf[LONG_STRING];\n POP_DATA *pop_data = (POP_DATA *)ctx->data;\n progress_t progress;\n#ifdef USE_HCACHE\n header_cache_t *hc = NULL;\n#endif\n\n pop_data->check_time = 0;\n\n FOREVER\n {\n if (pop_reconnect (ctx) < 0)\n return -1;\n\n mutt_progress_init (&progress, _(\"Marking messages deleted...\"),\n\t\t\tMUTT_PROGRESS_MSG, WriteInc, ctx->deleted);\n\n#if 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\tj++;\n\tif (!ctx->quiet)\n\t mutt_progress_update (&progress, j, -1);\n\tsnprintf (buf, sizeof (buf), \"DELE %d\\r\\n\", ctx->hdrs[i]->refno);\n\tif ((ret = pop_query (pop_data, buf, sizeof (buf))) == 0)\n\t{\n\t mutt_bcache_del (pop_data->bcache, ctx->hdrs[i]->data);\n#if USE_HCACHE\n\t mutt_hcache_delete (hc, ctx->hdrs[i]->data, strlen);\n#endif\n\t}\n }\n\n#if USE_HCACHE\n if (ctx->hdrs[i]->changed)\n {\n\tmutt_hcache_store (hc, ctx->hdrs[i]->data, ctx->hdrs[i], 0, strlen, MUTT_GENERATE_UIDVALIDITY);\n }\n#endif\n\n }\n\n#if USE_HCACHE\n mutt_hcache_close (hc);\n#endif\n\n if (ret == 0)\n {\n 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 = 1;\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 mutt_sleep (2);\n return -1;\n }\n }\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: static void cmd_parse_lsub(struct ImapData *idata, char *s)\n{\n char buf[STRING];\n char errstr[STRING];\n struct Buffer err, token;\n struct Url url;\n struct ImapList list;\n\n if (idata->cmddata && idata->cmdtype == IMAP_CT_LIST)\n {\n /* caller will handle response itself */\n cmd_parse_list(idata, s);\n return;\n }\n\n if (!ImapCheckSubscribed)\n return;\n\n idata->cmdtype = IMAP_CT_LIST;\n idata->cmddata = &list;\n cmd_parse_list(idata, s);\n idata->cmddata = NULL;\n /* noselect is for a gmail quirk (#3445) */\n if (!list.name || list.noselect)\n return;\n\n mutt_debug(3, \"Subscribing to %s\\n\", list.name);\n\n mutt_str_strfcpy(buf, \"mailboxes \\\"\", sizeof(buf));\n mutt_account_tourl(&idata->conn->account, &url);\n /* escape \\ and \" */\n imap_quote_string(errstr, sizeof(errstr), list.name);\n url.path = errstr + 1;\n url.path[strlen(url.path) - 1] = '\\0';\n if (mutt_str_strcmp(url.user, ImapUser) == 0)\n url.user = NULL;\n url_tostring(&url, buf + 11, sizeof(buf) - 11, 0);\n mutt_str_strcat(buf, sizeof(buf), \"\\\"\");\n mutt_buffer_init(&token);\n mutt_buffer_init(&err);\n err.data = errstr;\n err.dsize = sizeof(errstr);\n if (mutt_parse_rc_line(buf, &token, &err))\n mutt_debug(1, \"Error adding subscribed mailbox: %s\\n\", errstr);\n FREE(&token.data);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-78', 'CWE-77'], 'message': 'quote imap strings more carefully\n\nCo-authored-by: JerikoOne '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int fetch_uidl (char *line, void *data)\n{\n int i, index;\n CONTEXT *ctx = (CONTEXT *)data;\n POP_DATA *pop_data = (POP_DATA *)ctx->data;\n char *endp;\n\n errno = 0;\n index = strtol(line, &endp, 10);\n if (errno)\n return -1;\n while (*endp == ' ')\n endp++;\n memmove(line, endp, strlen(endp) + 1);\n\n for (i = 0; i < ctx->msgcount; i++)\n if (!mutt_strcmp (line, ctx->hdrs[i]->data))\n break;\n\n if (i == ctx->msgcount)\n {\n dprint (1, (debugfile, \"pop_fetch_headers: new header %d %s\\n\", index, line));\n\n if (i >= ctx->hdrmax)\n mx_alloc_memory(ctx);\n\n ctx->msgcount++;\n ctx->hdrs[i] = mutt_new_header ();\n ctx->hdrs[i]->data = safe_strdup (line);\n }\n else if (ctx->hdrs[i]->index != index - 1)\n pop_data->clear_cache = 1;\n\n ctx->hdrs[i]->refno = index;\n ctx->hdrs[i]->index = index - 1;\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-824'], 'message': 'Ensure UID in fetch_uidl.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int md_require_https_maybe(request_rec *r)\n{\n const md_srv_conf_t *sc;\n apr_uri_t uri;\n const char *s;\n int status;\n \n if (opt_ssl_is_https \n && strncmp(WELL_KNOWN_PREFIX, r->parsed_uri.path, sizeof(WELL_KNOWN_PREFIX)-1)) {\n \n sc = ap_get_module_config(r->server->module_config, &md_module);\n if (sc && sc->assigned && sc->assigned->require_https > MD_REQUIRE_OFF) {\n if (opt_ssl_is_https(r->connection)) {\n /* Using https:\n * if 'permanent' and no one else set a HSTS header already, do it */\n if (sc->assigned->require_https == MD_REQUIRE_PERMANENT \n && sc->mc->hsts_header && !apr_table_get(r->headers_out, MD_HSTS_HEADER)) {\n apr_table_setn(r->headers_out, MD_HSTS_HEADER, sc->mc->hsts_header);\n }\n }\n else {\n /* Not using https:, but require it. Redirect. */\n if (r->method_number == M_GET) {\n /* safe to use the old-fashioned codes */\n status = ((MD_REQUIRE_PERMANENT == sc->assigned->require_https)? \n HTTP_MOVED_PERMANENTLY : HTTP_MOVED_TEMPORARILY);\n }\n else {\n /* these should keep the method unchanged on retry */\n status = ((MD_REQUIRE_PERMANENT == sc->assigned->require_https)? \n HTTP_PERMANENT_REDIRECT : HTTP_TEMPORARY_REDIRECT);\n }\n \n s = ap_construct_url(r->pool, r->uri, r);\n if (APR_SUCCESS == apr_uri_parse(r->pool, s, &uri)) {\n uri.scheme = (char*)\"https\";\n uri.port = 443;\n uri.port_str = (char*)\"443\";\n uri.query = r->parsed_uri.query;\n uri.fragment = r->parsed_uri.fragment;\n s = apr_uri_unparse(r->pool, &uri, APR_URI_UNP_OMITUSERINFO);\n if (s && *s) {\n apr_table_setn(r->headers_out, \"Location\", s);\n return status;\n }\n }\n }\n }\n }\n return DECLINED;\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); // int format_len;\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 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': 'Added minimum size check for WAV header block lengh values'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadMIFFImage(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n#define BZipMaxExtent(x) ((x)+((x)/100)+600)\n#define LZMAMaxExtent(x) ((x)+((x)/3)+128)\n#define ThrowMIFFException(exception,message) \\\n{ \\\n if (quantum_info != (QuantumInfo *) NULL) \\\n quantum_info=DestroyQuantumInfo(quantum_info); \\\n if (compress_pixels != (unsigned char *) NULL) \\\n compress_pixels=(unsigned char *) RelinquishMagickMemory(compress_pixels); \\\n ThrowReaderException((exception),(message)); \\\n}\n#define ZipMaxExtent(x) ((x)+(((x)+7) >> 3)+(((x)+63) >> 6)+11)\n\n#if defined(MAGICKCORE_BZLIB_DELEGATE)\n bz_stream\n bzip_info;\n#endif\n\n char\n id[MagickPathExtent],\n keyword[MagickPathExtent],\n *options;\n\n double\n version;\n\n GeometryInfo\n geometry_info;\n\n Image\n *image;\n\n int\n c;\n\n LinkedListInfo\n *profiles;\n\n#if defined(MAGICKCORE_LZMA_DELEGATE)\n lzma_stream\n initialize_lzma = LZMA_STREAM_INIT,\n lzma_info;\n\n lzma_allocator\n allocator;\n#endif\n\n MagickBooleanType\n status;\n\n PixelInfo\n pixel;\n\n MagickStatusType\n flags;\n\n QuantumFormatType\n quantum_format;\n\n QuantumInfo\n *quantum_info;\n\n QuantumType\n quantum_type;\n\n register ssize_t\n i;\n\n size_t\n compress_extent,\n length,\n packet_size;\n\n ssize_t\n count;\n\n unsigned char\n *compress_pixels,\n *pixels;\n\n size_t\n colors;\n\n ssize_t\n y;\n\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n z_stream\n zip_info;\n#endif\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Decode image header; header terminates one character beyond a ':'.\n */\n c=ReadBlobByte(image);\n if (c == EOF)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n *id='\\0';\n compress_pixels=(unsigned char *) NULL;\n quantum_info=(QuantumInfo *) NULL;\n (void) memset(keyword,0,sizeof(keyword));\n version=0.0;\n (void) version;\n do\n {\n /*\n Decode image header; header terminates one character beyond a ':'.\n */\n SetGeometryInfo(&geometry_info);\n length=MagickPathExtent;\n options=AcquireString((char *) NULL);\n quantum_format=UndefinedQuantumFormat;\n profiles=(LinkedListInfo *) NULL;\n colors=0;\n image->depth=8UL;\n image->compression=NoCompression;\n while ((isgraph(c) != MagickFalse) && (c != (int) ':'))\n {\n register char\n *p;\n\n if (c == (int) '{')\n {\n char\n *comment;\n\n /*\n Read comment-- any text between { }.\n */\n length=MagickPathExtent;\n comment=AcquireString((char *) NULL);\n for (p=comment; comment != (char *) NULL; p++)\n {\n c=ReadBlobByte(image);\n if (c == (int) '\\\\')\n c=ReadBlobByte(image);\n else\n if ((c == EOF) || (c == (int) '}'))\n break;\n if ((size_t) (p-comment+1) >= length)\n {\n *p='\\0';\n length<<=1;\n comment=(char *) ResizeQuantumMemory(comment,length+\n MagickPathExtent,sizeof(*comment));\n if (comment == (char *) NULL)\n break;\n p=comment+strlen(comment);\n }\n *p=(char) c;\n }\n if (comment == (char *) NULL)\n {\n options=DestroyString(options);\n ThrowMIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n *p='\\0';\n (void) SetImageProperty(image,\"comment\",comment,exception);\n comment=DestroyString(comment);\n c=ReadBlobByte(image);\n }\n else\n if (isalnum(c) != MagickFalse)\n {\n /*\n Get the keyword.\n */\n length=MagickPathExtent-1;\n p=keyword;\n do\n {\n if (c == (int) '=')\n break;\n if ((size_t) (p-keyword) < (MagickPathExtent-1))\n *p++=(char) c;\n c=ReadBlobByte(image);\n } while (c != EOF);\n *p='\\0';\n p=options;\n while ((isspace((int) ((unsigned char) c)) != 0) && (c != EOF))\n c=ReadBlobByte(image);\n if (c == (int) '=')\n {\n /*\n Get the keyword value.\n */\n c=ReadBlobByte(image);\n while ((c != (int) '}') && (c != EOF))\n {\n if ((size_t) (p-options+1) >= length)\n {\n *p='\\0';\n length<<=1;\n options=(char *) ResizeQuantumMemory(options,length+\n MagickPathExtent,sizeof(*options));\n if (options == (char *) NULL)\n break;\n p=options+strlen(options);\n }\n *p++=(char) c;\n c=ReadBlobByte(image);\n if (c == '\\\\')\n {\n c=ReadBlobByte(image);\n if (c == (int) '}')\n {\n *p++=(char) c;\n c=ReadBlobByte(image);\n }\n }\n if (*options != '{')\n if (isspace((int) ((unsigned char) c)) != 0)\n break;\n }\n if (options == (char *) NULL)\n ThrowMIFFException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n *p='\\0';\n if (*options == '{')\n (void) CopyMagickString(options,options+1,strlen(options));\n /*\n Assign a value to the specified keyword.\n */\n switch (*keyword)\n {\n case 'a':\n case 'A':\n {\n if (LocaleCompare(keyword,\"alpha-trait\") == 0)\n {\n ssize_t\n alpha_trait;\n\n alpha_trait=ParseCommandOption(MagickPixelTraitOptions,\n MagickFalse,options);\n if (alpha_trait < 0)\n break;\n image->alpha_trait=(PixelTrait) alpha_trait;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'b':\n case 'B':\n {\n if (LocaleCompare(keyword,\"background-color\") == 0)\n {\n (void) QueryColorCompliance(options,AllCompliance,\n &image->background_color,exception);\n break;\n }\n if (LocaleCompare(keyword,\"blue-primary\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->chromaticity.blue_primary.x=geometry_info.rho;\n image->chromaticity.blue_primary.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->chromaticity.blue_primary.y=\n image->chromaticity.blue_primary.x;\n break;\n }\n if (LocaleCompare(keyword,\"border-color\") == 0)\n {\n (void) QueryColorCompliance(options,AllCompliance,\n &image->border_color,exception);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'c':\n case 'C':\n {\n if (LocaleCompare(keyword,\"class\") == 0)\n {\n ssize_t\n storage_class;\n\n storage_class=ParseCommandOption(MagickClassOptions,\n MagickFalse,options);\n if (storage_class < 0)\n break;\n image->storage_class=(ClassType) storage_class;\n break;\n }\n if (LocaleCompare(keyword,\"colors\") == 0)\n {\n colors=StringToUnsignedLong(options);\n break;\n }\n if (LocaleCompare(keyword,\"colorspace\") == 0)\n {\n ssize_t\n colorspace;\n\n colorspace=ParseCommandOption(MagickColorspaceOptions,\n MagickFalse,options);\n if (colorspace < 0)\n break;\n image->colorspace=(ColorspaceType) colorspace;\n break;\n }\n if (LocaleCompare(keyword,\"compression\") == 0)\n {\n ssize_t\n compression;\n\n compression=ParseCommandOption(MagickCompressOptions,\n MagickFalse,options);\n if (compression < 0)\n break;\n image->compression=(CompressionType) compression;\n break;\n }\n if (LocaleCompare(keyword,\"columns\") == 0)\n {\n image->columns=StringToUnsignedLong(options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'd':\n case 'D':\n {\n if (LocaleCompare(keyword,\"delay\") == 0)\n {\n image->delay=StringToUnsignedLong(options);\n break;\n }\n if (LocaleCompare(keyword,\"depth\") == 0)\n {\n image->depth=StringToUnsignedLong(options);\n break;\n }\n if (LocaleCompare(keyword,\"dispose\") == 0)\n {\n ssize_t\n dispose;\n\n dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse,\n options);\n if (dispose < 0)\n break;\n image->dispose=(DisposeType) dispose;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'e':\n case 'E':\n {\n if (LocaleCompare(keyword,\"endian\") == 0)\n {\n ssize_t\n endian;\n\n endian=ParseCommandOption(MagickEndianOptions,MagickFalse,\n options);\n if (endian < 0)\n break;\n image->endian=(EndianType) endian;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'g':\n case 'G':\n {\n if (LocaleCompare(keyword,\"gamma\") == 0)\n {\n image->gamma=StringToDouble(options,(char **) NULL);\n break;\n }\n if (LocaleCompare(keyword,\"gravity\") == 0)\n {\n ssize_t\n gravity;\n\n gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,\n options);\n if (gravity < 0)\n break;\n image->gravity=(GravityType) gravity;\n break;\n }\n if (LocaleCompare(keyword,\"green-primary\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->chromaticity.green_primary.x=geometry_info.rho;\n image->chromaticity.green_primary.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->chromaticity.green_primary.y=\n image->chromaticity.green_primary.x;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'i':\n case 'I':\n {\n if (LocaleCompare(keyword,\"id\") == 0)\n {\n (void) CopyMagickString(id,options,MagickPathExtent);\n break;\n }\n if (LocaleCompare(keyword,\"iterations\") == 0)\n {\n image->iterations=StringToUnsignedLong(options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'm':\n case 'M':\n {\n if (LocaleCompare(keyword,\"matte\") == 0)\n {\n ssize_t\n matte;\n\n matte=ParseCommandOption(MagickBooleanOptions,MagickFalse,\n options);\n if (matte < 0)\n break;\n image->alpha_trait=matte == 0 ? UndefinedPixelTrait :\n BlendPixelTrait;\n break;\n }\n if (LocaleCompare(keyword,\"mattecolor\") == 0)\n {\n (void) QueryColorCompliance(options,AllCompliance,\n &image->matte_color,exception);\n break;\n }\n if (LocaleCompare(keyword,\"montage\") == 0)\n {\n (void) CloneString(&image->montage,options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'o':\n case 'O':\n {\n if (LocaleCompare(keyword,\"orientation\") == 0)\n {\n ssize_t\n orientation;\n\n orientation=ParseCommandOption(MagickOrientationOptions,\n MagickFalse,options);\n if (orientation < 0)\n break;\n image->orientation=(OrientationType) orientation;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'p':\n case 'P':\n {\n if (LocaleCompare(keyword,\"page\") == 0)\n {\n char\n *geometry;\n\n geometry=GetPageGeometry(options);\n (void) ParseAbsoluteGeometry(geometry,&image->page);\n geometry=DestroyString(geometry);\n break;\n }\n if (LocaleCompare(keyword,\"pixel-intensity\") == 0)\n {\n ssize_t\n intensity;\n\n intensity=ParseCommandOption(MagickPixelIntensityOptions,\n MagickFalse,options);\n if (intensity < 0)\n break;\n image->intensity=(PixelIntensityMethod) intensity;\n break;\n }\n if (LocaleCompare(keyword,\"profile\") == 0)\n {\n if (profiles == (LinkedListInfo *) NULL)\n profiles=NewLinkedList(0);\n (void) AppendValueToLinkedList(profiles,\n AcquireString(options));\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'q':\n case 'Q':\n {\n if (LocaleCompare(keyword,\"quality\") == 0)\n {\n image->quality=StringToUnsignedLong(options);\n break;\n }\n if ((LocaleCompare(keyword,\"quantum-format\") == 0) ||\n (LocaleCompare(keyword,\"quantum:format\") == 0))\n {\n ssize_t\n format;\n\n format=ParseCommandOption(MagickQuantumFormatOptions,\n MagickFalse,options);\n if (format < 0)\n break;\n quantum_format=(QuantumFormatType) format;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'r':\n case 'R':\n {\n if (LocaleCompare(keyword,\"red-primary\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->chromaticity.red_primary.x=geometry_info.rho;\n image->chromaticity.red_primary.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->chromaticity.red_primary.y=\n image->chromaticity.red_primary.x;\n break;\n }\n if (LocaleCompare(keyword,\"rendering-intent\") == 0)\n {\n ssize_t\n rendering_intent;\n\n rendering_intent=ParseCommandOption(MagickIntentOptions,\n MagickFalse,options);\n if (rendering_intent < 0)\n break;\n image->rendering_intent=(RenderingIntent) rendering_intent;\n break;\n }\n if (LocaleCompare(keyword,\"resolution\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->resolution.x=geometry_info.rho;\n image->resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->resolution.y=image->resolution.x;\n break;\n }\n if (LocaleCompare(keyword,\"rows\") == 0)\n {\n image->rows=StringToUnsignedLong(options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 's':\n case 'S':\n {\n if (LocaleCompare(keyword,\"scene\") == 0)\n {\n image->scene=StringToUnsignedLong(options);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 't':\n case 'T':\n {\n if (LocaleCompare(keyword,\"ticks-per-second\") == 0)\n {\n image->ticks_per_second=(ssize_t) StringToLong(options);\n break;\n }\n if (LocaleCompare(keyword,\"tile-offset\") == 0)\n {\n char\n *geometry;\n\n geometry=GetPageGeometry(options);\n (void) ParseAbsoluteGeometry(geometry,&image->tile_offset);\n geometry=DestroyString(geometry);\n break;\n }\n if (LocaleCompare(keyword,\"type\") == 0)\n {\n ssize_t\n type;\n\n type=ParseCommandOption(MagickTypeOptions,MagickFalse,\n options);\n if (type < 0)\n break;\n image->type=(ImageType) type;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'u':\n case 'U':\n {\n if (LocaleCompare(keyword,\"units\") == 0)\n {\n ssize_t\n units;\n\n units=ParseCommandOption(MagickResolutionOptions,\n MagickFalse,options);\n if (units < 0)\n break;\n image->units=(ResolutionType) units;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'v':\n case 'V':\n {\n if (LocaleCompare(keyword,\"version\") == 0)\n {\n version=StringToDouble(options,(char **) NULL);\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n case 'w':\n case 'W':\n {\n if (LocaleCompare(keyword,\"white-point\") == 0)\n {\n flags=ParseGeometry(options,&geometry_info);\n image->chromaticity.white_point.x=geometry_info.rho;\n image->chromaticity.white_point.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->chromaticity.white_point.y=\n image->chromaticity.white_point.x;\n break;\n }\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n default:\n {\n (void) SetImageProperty(image,keyword,options,exception);\n break;\n }\n }\n }\n else\n c=ReadBlobByte(image);\n while (isspace((int) ((unsigned char) c)) != 0)\n c=ReadBlobByte(image);\n }\n options=DestroyString(options);\n (void) ReadBlobByte(image);\n /*\n Verify that required image information is defined.\n */\n if ((LocaleCompare(id,\"ImageMagick\") != 0) || (image->depth > 64) ||\n (image->storage_class == UndefinedClass) ||\n (image->compression == UndefinedCompression) ||\n (image->colorspace == UndefinedColorspace) ||\n (image->columns == 0) || (image->rows == 0))\n {\n if (profiles != (LinkedListInfo *) NULL)\n profiles=DestroyLinkedList(profiles,RelinquishMagickMemory);\n if (image->previous == (Image *) NULL)\n ThrowMIFFException(CorruptImageError,\"ImproperImageHeader\");\n DeleteImageFromList(&image);\n (void) ThrowMagickException(exception,GetMagickModule(),\n CorruptImageError,\"ImproperImageHeader\",\"`%s'\",image->filename);\n break;\n }\n if (image->montage != (char *) NULL)\n {\n register char\n *p;\n\n /*\n Image directory.\n */\n length=MagickPathExtent;\n image->directory=AcquireString((char *) NULL);\n p=image->directory;\n do\n {\n *p='\\0';\n if ((strlen(image->directory)+MagickPathExtent) >= length)\n {\n /*\n Allocate more memory for the image directory.\n */\n length<<=1;\n image->directory=(char *) ResizeQuantumMemory(image->directory,\n length+MagickPathExtent,sizeof(*image->directory));\n if (image->directory == (char *) NULL)\n ThrowMIFFException(CorruptImageError,\"UnableToReadImageData\");\n p=image->directory+strlen(image->directory);\n }\n c=ReadBlobByte(image);\n if (c == EOF)\n break;\n *p++=(char) c;\n } while (c != (int) '\\0');\n }\n if (profiles != (LinkedListInfo *) NULL)\n {\n const char\n *name;\n\n StringInfo\n *profile;\n\n /*\n Read image profiles.\n */\n ResetLinkedListIterator(profiles);\n name=(const char *) GetNextValueInLinkedList(profiles);\n while (name != (const char *) NULL)\n {\n length=ReadBlobMSBLong(image);\n if ((MagickSizeType) length > GetBlobSize(image))\n break;\n profile=AcquireStringInfo(length);\n if (profile == (StringInfo *) NULL)\n break;\n count=ReadBlob(image,length,GetStringInfoDatum(profile));\n if (count != (ssize_t) length)\n {\n profile=DestroyStringInfo(profile);\n break;\n }\n status=SetImageProfile(image,name,profile,exception);\n profile=DestroyStringInfo(profile);\n if (status == MagickFalse)\n break;\n name=(const char *) GetNextValueInLinkedList(profiles);\n }\n profiles=DestroyLinkedList(profiles,RelinquishMagickMemory);\n }\n image->depth=GetImageQuantumDepth(image,MagickFalse);\n if (image->storage_class == PseudoClass)\n {\n unsigned char\n *colormap;\n\n /*\n Create image colormap.\n */\n packet_size=(size_t) (3UL*image->depth/8UL);\n if ((MagickSizeType) colors > GetBlobSize(image))\n ThrowMIFFException(CorruptImageError,\"InsufficientImageDataInFile\");\n if (((MagickSizeType) packet_size*colors) > GetBlobSize(image))\n ThrowMIFFException(CorruptImageError,\"InsufficientImageDataInFile\");\n status=AcquireImageColormap(image,colors != 0 ? colors : 256,exception);\n if (status == MagickFalse)\n ThrowMIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (colors != 0)\n {\n const unsigned char\n *p;\n\n /*\n Read image colormap from file.\n */\n colormap=(unsigned char *) AcquireQuantumMemory(image->colors,\n packet_size*sizeof(*colormap));\n if (colormap == (unsigned char *) NULL)\n ThrowMIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n count=ReadBlob(image,packet_size*image->colors,colormap);\n p=colormap;\n switch (image->depth)\n {\n default:\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n ThrowMIFFException(CorruptImageError,\"ImageDepthNotSupported\");\n case 8:\n {\n unsigned char\n char_pixel;\n\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n p=PushCharPixel(p,&char_pixel);\n image->colormap[i].red=(MagickRealType)\n ScaleCharToQuantum(char_pixel);\n p=PushCharPixel(p,&char_pixel);\n image->colormap[i].green=(MagickRealType)\n ScaleCharToQuantum(char_pixel);\n p=PushCharPixel(p,&char_pixel);\n image->colormap[i].blue=(MagickRealType)\n ScaleCharToQuantum(char_pixel);\n }\n break;\n }\n case 16:\n {\n unsigned short\n short_pixel;\n\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n p=PushShortPixel(MSBEndian,p,&short_pixel);\n image->colormap[i].red=(MagickRealType)\n ScaleShortToQuantum(short_pixel);\n p=PushShortPixel(MSBEndian,p,&short_pixel);\n image->colormap[i].green=(MagickRealType)\n ScaleShortToQuantum(short_pixel);\n p=PushShortPixel(MSBEndian,p,&short_pixel);\n image->colormap[i].blue=(MagickRealType)\n ScaleShortToQuantum(short_pixel);\n }\n break;\n }\n case 32:\n {\n unsigned int\n long_pixel;\n\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n p=PushLongPixel(MSBEndian,p,&long_pixel);\n image->colormap[i].red=(MagickRealType)\n ScaleLongToQuantum(long_pixel);\n p=PushLongPixel(MSBEndian,p,&long_pixel);\n image->colormap[i].green=(MagickRealType)\n ScaleLongToQuantum(long_pixel);\n p=PushLongPixel(MSBEndian,p,&long_pixel);\n image->colormap[i].blue=(MagickRealType)\n ScaleLongToQuantum(long_pixel);\n }\n break;\n }\n }\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n }\n }\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n status=ResetImagePixels(image,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n /*\n Allocate image pixels.\n */\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowMIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (quantum_format != UndefinedQuantumFormat)\n {\n status=SetQuantumFormat(image,quantum_info,quantum_format);\n if (status == MagickFalse)\n ThrowMIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n packet_size=(size_t) (quantum_info->depth/8);\n if (image->storage_class == DirectClass)\n packet_size=(size_t) (3*quantum_info->depth/8);\n if (IsGrayColorspace(image->colorspace) != MagickFalse)\n packet_size=quantum_info->depth/8;\n if (image->alpha_trait != UndefinedPixelTrait)\n packet_size+=quantum_info->depth/8;\n if (image->colorspace == CMYKColorspace)\n packet_size+=quantum_info->depth/8;\n if (image->compression == RLECompression)\n packet_size++;\n compress_extent=MagickMax(MagickMax(BZipMaxExtent(packet_size*\n image->columns),LZMAMaxExtent(packet_size*image->columns)),\n ZipMaxExtent(packet_size*image->columns));\n compress_pixels=(unsigned char *) AcquireQuantumMemory(compress_extent,\n sizeof(*compress_pixels));\n if (compress_pixels == (unsigned char *) NULL)\n ThrowMIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n /*\n Read image pixels.\n */\n quantum_type=RGBQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n quantum_type=RGBAQuantum;\n if (image->colorspace == CMYKColorspace)\n {\n quantum_type=CMYKQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n quantum_type=CMYKAQuantum;\n }\n if (IsGrayColorspace(image->colorspace) != MagickFalse)\n {\n quantum_type=GrayQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n quantum_type=GrayAlphaQuantum;\n }\n if (image->storage_class == PseudoClass)\n {\n quantum_type=IndexQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n quantum_type=IndexAlphaQuantum;\n }\n status=MagickTrue;\n GetPixelInfo(image,&pixel);\n#if defined(MAGICKCORE_BZLIB_DELEGATE)\n (void) memset(&bzip_info,0,sizeof(bzip_info));\n#endif\n#if defined(MAGICKCORE_LZMA_DELEGATE)\n (void) memset(&allocator,0,sizeof(allocator));\n#endif\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n (void) memset(&zip_info,0,sizeof(zip_info));\n#endif\n switch (image->compression)\n {\n#if defined(MAGICKCORE_BZLIB_DELEGATE)\n case BZipCompression:\n {\n int\n code;\n\n bzip_info.bzalloc=AcquireBZIPMemory;\n bzip_info.bzfree=RelinquishBZIPMemory;\n bzip_info.opaque=(void *) image;\n code=BZ2_bzDecompressInit(&bzip_info,(int) image_info->verbose,\n MagickFalse);\n if (code != BZ_OK)\n status=MagickFalse;\n break;\n }\n#endif\n#if defined(MAGICKCORE_LZMA_DELEGATE)\n case LZMACompression:\n {\n int\n code;\n\n allocator.alloc=AcquireLZMAMemory;\n allocator.free=RelinquishLZMAMemory;\n allocator.opaque=(void *) image;\n lzma_info=initialize_lzma;\n lzma_info.allocator=(&allocator);\n code=lzma_auto_decoder(&lzma_info,(uint64_t) -1,0);\n if (code != LZMA_OK)\n status=MagickFalse;\n break;\n }\n#endif\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n case LZWCompression:\n case ZipCompression:\n {\n int\n code;\n\n zip_info.zalloc=AcquireZIPMemory;\n zip_info.zfree=RelinquishZIPMemory;\n zip_info.opaque=(voidpf) image;\n code=inflateInit(&zip_info);\n if (code != Z_OK)\n status=MagickFalse;\n break;\n }\n#endif\n case RLECompression:\n break;\n default:\n break;\n }\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n length=0;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register ssize_t\n x;\n\n register Quantum\n *magick_restrict q;\n\n if (status == MagickFalse)\n break;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n switch (image->compression)\n {\n#if defined(MAGICKCORE_BZLIB_DELEGATE)\n case BZipCompression:\n {\n bzip_info.next_out=(char *) pixels;\n bzip_info.avail_out=(unsigned int) (packet_size*image->columns);\n do\n {\n int\n code;\n\n if (bzip_info.avail_in == 0)\n {\n bzip_info.next_in=(char *) compress_pixels;\n length=(size_t) BZipMaxExtent(packet_size*image->columns);\n if (version != 0.0)\n length=(size_t) ReadBlobMSBLong(image);\n if (length <= compress_extent)\n bzip_info.avail_in=(unsigned int) ReadBlob(image,length,\n (unsigned char *) bzip_info.next_in);\n if ((length > compress_extent) ||\n ((size_t) bzip_info.avail_in != length))\n {\n (void) BZ2_bzDecompressEnd(&bzip_info);\n ThrowMIFFException(CorruptImageError,\n \"UnableToReadImageData\");\n }\n }\n code=BZ2_bzDecompress(&bzip_info);\n if ((code != BZ_OK) && (code != BZ_STREAM_END))\n {\n status=MagickFalse;\n break;\n }\n if (code == BZ_STREAM_END)\n break;\n } while (bzip_info.avail_out != 0);\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n break;\n }\n#endif\n#if defined(MAGICKCORE_LZMA_DELEGATE)\n case LZMACompression:\n {\n lzma_info.next_out=pixels;\n lzma_info.avail_out=packet_size*image->columns;\n do\n {\n int\n code;\n\n if (lzma_info.avail_in == 0)\n {\n lzma_info.next_in=compress_pixels;\n length=(size_t) ReadBlobMSBLong(image);\n if (length <= compress_extent)\n lzma_info.avail_in=(unsigned int) ReadBlob(image,length,\n (unsigned char *) lzma_info.next_in);\n if ((length > compress_extent) ||\n (lzma_info.avail_in != length))\n {\n lzma_end(&lzma_info);\n ThrowMIFFException(CorruptImageError,\n \"UnableToReadImageData\");\n }\n }\n code=lzma_code(&lzma_info,LZMA_RUN);\n if ((code != LZMA_OK) && (code != LZMA_STREAM_END))\n {\n status=MagickFalse;\n break;\n }\n if (code == LZMA_STREAM_END)\n break;\n } while (lzma_info.avail_out != 0);\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n break;\n }\n#endif\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n case LZWCompression:\n case ZipCompression:\n {\n zip_info.next_out=pixels;\n zip_info.avail_out=(uInt) (packet_size*image->columns);\n do\n {\n int\n code;\n\n if (zip_info.avail_in == 0)\n {\n zip_info.next_in=compress_pixels;\n length=(size_t) ZipMaxExtent(packet_size*image->columns);\n if (version != 0.0)\n length=(size_t) ReadBlobMSBLong(image);\n if (length <= compress_extent)\n zip_info.avail_in=(unsigned int) ReadBlob(image,length,\n zip_info.next_in);\n if ((length > compress_extent) ||\n ((size_t) zip_info.avail_in != length))\n {\n (void) inflateEnd(&zip_info);\n ThrowMIFFException(CorruptImageError,\n \"UnableToReadImageData\");\n }\n }\n code=inflate(&zip_info,Z_SYNC_FLUSH);\n if ((code != Z_OK) && (code != Z_STREAM_END))\n {\n status=MagickFalse;\n break;\n }\n if (code == Z_STREAM_END)\n break;\n } while (zip_info.avail_out != 0);\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n break;\n }\n#endif\n case RLECompression:\n {\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (length == 0)\n {\n count=ReadBlob(image,packet_size,pixels);\n if (count != (ssize_t) packet_size)\n ThrowMIFFException(CorruptImageError,\"UnableToReadImageData\");\n PushRunlengthPacket(image,pixels,&length,&pixel,exception);\n }\n length--;\n if (image->storage_class == PseudoClass)\n SetPixelIndex(image,ClampToQuantum(pixel.index),q);\n else\n {\n SetPixelRed(image,ClampToQuantum(pixel.red),q);\n SetPixelGreen(image,ClampToQuantum(pixel.green),q);\n SetPixelBlue(image,ClampToQuantum(pixel.blue),q);\n if (image->colorspace == CMYKColorspace)\n SetPixelBlack(image,ClampToQuantum(pixel.black),q);\n }\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);\n q+=GetPixelChannels(image);\n }\n break;\n }\n default:\n {\n count=ReadBlob(image,packet_size*image->columns,pixels);\n if (count != (ssize_t) (packet_size*image->columns))\n ThrowMIFFException(CorruptImageError,\"UnableToReadImageData\");\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n break;\n }\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n SetQuantumImageType(image,quantum_type);\n switch (image->compression)\n {\n#if defined(MAGICKCORE_BZLIB_DELEGATE)\n case BZipCompression:\n {\n int\n code;\n\n if (version == 0.0)\n {\n MagickOffsetType\n offset;\n\n offset=SeekBlob(image,-((MagickOffsetType) bzip_info.avail_in),\n SEEK_CUR);\n if (offset < 0)\n {\n (void) BZ2_bzDecompressEnd(&bzip_info);\n ThrowMIFFException(CorruptImageError,\"ImproperImageHeader\");\n }\n }\n code=BZ2_bzDecompressEnd(&bzip_info);\n if (code != BZ_OK)\n status=MagickFalse;\n break;\n }\n#endif\n#if defined(MAGICKCORE_LZMA_DELEGATE)\n case LZMACompression:\n {\n int\n code;\n\n code=lzma_code(&lzma_info,LZMA_FINISH);\n if ((code != LZMA_STREAM_END) && (code != LZMA_OK))\n status=MagickFalse;\n lzma_end(&lzma_info);\n break;\n }\n#endif\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n case LZWCompression:\n case ZipCompression:\n {\n int\n code;\n\n if (version == 0.0)\n {\n MagickOffsetType\n offset;\n\n offset=SeekBlob(image,-((MagickOffsetType) zip_info.avail_in),\n SEEK_CUR);\n if (offset < 0)\n {\n (void) inflateEnd(&zip_info);\n ThrowMIFFException(CorruptImageError,\"ImproperImageHeader\");\n }\n }\n code=inflateEnd(&zip_info);\n if (code != Z_OK)\n status=MagickFalse;\n break;\n }\n#endif\n default:\n break;\n }\n quantum_info=DestroyQuantumInfo(quantum_info);\n compress_pixels=(unsigned char *) RelinquishMagickMemory(compress_pixels);\n if (((y != (ssize_t) image->rows)) || (status == MagickFalse))\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n do\n {\n c=ReadBlobByte(image);\n } while ((isgraph(c) == MagickFalse) && (c != EOF));\n if (c != EOF)\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n 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 (c != EOF);\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-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1191'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int kwajd_read_headers(struct mspack_system *sys,\n\t\t\t struct mspack_file *fh,\n\t\t\t struct mskwajd_header *hdr)\n{\n unsigned char buf[16];\n int i;\n\n /* read in the header */\n if (sys->read(fh, &buf[0], kwajh_SIZEOF) != kwajh_SIZEOF) {\n\treturn MSPACK_ERR_READ;\n }\n\n /* check for \"KWAJ\" signature */\n if (((unsigned int) EndGetI32(&buf[kwajh_Signature1]) != 0x4A41574B) ||\n\t((unsigned int) EndGetI32(&buf[kwajh_Signature2]) != 0xD127F088))\n {\n\treturn MSPACK_ERR_SIGNATURE;\n }\n\n /* basic header fields */\n hdr->comp_type = EndGetI16(&buf[kwajh_CompMethod]);\n hdr->data_offset = EndGetI16(&buf[kwajh_DataOffset]);\n hdr->headers = EndGetI16(&buf[kwajh_Flags]);\n hdr->length = 0;\n hdr->filename = NULL;\n hdr->extra = NULL;\n hdr->extra_length = 0;\n\n /* optional headers */\n\n /* 4 bytes: length of unpacked file */\n if (hdr->headers & MSKWAJ_HDR_HASLENGTH) {\n\tif (sys->read(fh, &buf[0], 4) != 4) return MSPACK_ERR_READ;\n\thdr->length = EndGetI32(&buf[0]);\n }\n\n /* 2 bytes: unknown purpose */\n if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN1) {\n\tif (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ;\n }\n\n /* 2 bytes: length of section, then [length] bytes: unknown purpose */\n if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN2) {\n\tif (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ;\n\ti = EndGetI16(&buf[0]);\n\tif (sys->seek(fh, (off_t)i, MSPACK_SYS_SEEK_CUR)) return MSPACK_ERR_SEEK;\n }\n\n /* filename and extension */\n if (hdr->headers & (MSKWAJ_HDR_HASFILENAME | MSKWAJ_HDR_HASFILEEXT)) {\n\toff_t pos = sys->tell(fh);\n\tchar *fn = (char *) sys->alloc(sys, (size_t) 13);\n\n\t/* allocate memory for maximum length filename */\n\tif (! fn) return MSPACK_ERR_NOMEMORY;\n\thdr->filename = fn;\n\n\t/* copy filename if present */\n\tif (hdr->headers & MSKWAJ_HDR_HASFILENAME) {\n\t if (sys->read(fh, &buf[0], 9) != 9) return MSPACK_ERR_READ;\n\t for (i = 0; i < 9; i++, fn++) if (!(*fn = buf[i])) break;\n\t pos += (i < 9) ? i+1 : 9;\n\t if (sys->seek(fh, pos, MSPACK_SYS_SEEK_START))\n\t\treturn MSPACK_ERR_SEEK;\n\t}\n\n\t/* copy extension if present */\n\tif (hdr->headers & MSKWAJ_HDR_HASFILEEXT) {\n\t *fn++ = '.';\n\t if (sys->read(fh, &buf[0], 4) != 4) return MSPACK_ERR_READ;\n\t for (i = 0; i < 4; i++, fn++) if (!(*fn = buf[i])) break;\n\t pos += (i < 4) ? i+1 : 4;\n\t if (sys->seek(fh, pos, MSPACK_SYS_SEEK_START))\n\t\treturn MSPACK_ERR_SEEK;\n\t}\n\t*fn = '\\0';\n }\n\n /* 2 bytes: extra text length then [length] bytes of extra text data */\n if (hdr->headers & MSKWAJ_HDR_HASEXTRATEXT) {\n\tif (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ;\n\ti = EndGetI16(&buf[0]);\n\thdr->extra = (char *) sys->alloc(sys, (size_t)i+1);\n\tif (! hdr->extra) return MSPACK_ERR_NOMEMORY;\n\tif (sys->read(fh, hdr->extra, i) != i) return MSPACK_ERR_READ;\n\thdr->extra[i] = '\\0';\n\thdr->extra_length = i;\n }\n return MSPACK_ERR_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310', 'CWE-787'], 'message': 'kwaj_read_headers(): fix handling of non-terminated strings'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: plain(void)\n{\n\ttest(PTR1_ZEROES PTR1_STR \" \" PTR2_STR, \"%p %p\", PTR1, PTR2);\n\t/*\n\t * The field width is overloaded for some %p extensions to\n\t * pass another piece of information. For plain pointers, the\n\t * behaviour is slightly odd: One cannot pass either the 0\n\t * flag nor a precision to %p without gcc complaining, and if\n\t * one explicitly gives a field width, the number is no longer\n\t * zero-padded.\n\t */\n\ttest(\"|\" PTR1_STR PTR1_SPACES \" | \" PTR1_SPACES PTR1_STR \"|\",\n\t \"|%-*p|%*p|\", PTR_WIDTH+2, PTR1, PTR_WIDTH+2, PTR1);\n\ttest(\"|\" PTR2_STR \" | \" PTR2_STR \"|\",\n\t \"|%-*p|%*p|\", PTR_WIDTH+2, PTR2, PTR_WIDTH+2, PTR2);\n\n\t/*\n\t * Unrecognized %p extensions are treated as plain %p, but the\n\t * alphanumeric suffix is ignored (that is, does not occur in\n\t * the output.)\n\t */\n\ttest(\"|\"PTR1_ZEROES PTR1_STR\"|\", \"|%p0y|\", PTR1);\n\ttest(\"|\"PTR2_STR\"|\", \"|%p0y|\", PTR2);\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: CompileKeymap(XkbFile *file, struct xkb_keymap *keymap, enum merge_mode merge)\n{\n bool ok;\n XkbFile *files[LAST_KEYMAP_FILE_TYPE + 1] = { NULL };\n enum xkb_file_type type;\n struct xkb_context *ctx = keymap->ctx;\n\n /* Collect section files and check for duplicates. */\n for (file = (XkbFile *) file->defs; file;\n file = (XkbFile *) file->common.next) {\n if (file->file_type < FIRST_KEYMAP_FILE_TYPE ||\n file->file_type > LAST_KEYMAP_FILE_TYPE) {\n log_err(ctx, \"Cannot define %s in a keymap file\\n\",\n xkb_file_type_to_string(file->file_type));\n continue;\n }\n\n if (files[file->file_type]) {\n log_err(ctx,\n \"More than one %s section in keymap file; \"\n \"All sections after the first ignored\\n\",\n xkb_file_type_to_string(file->file_type));\n continue;\n }\n\n files[file->file_type] = file;\n }\n\n /*\n * Check that all required section were provided.\n * Report everything before failing.\n */\n ok = true;\n for (type = FIRST_KEYMAP_FILE_TYPE;\n type <= LAST_KEYMAP_FILE_TYPE;\n type++) {\n if (files[type] == NULL) {\n log_err(ctx, \"Required section %s missing from keymap\\n\",\n xkb_file_type_to_string(type));\n ok = false;\n }\n }\n if (!ok)\n return false;\n\n /* Compile sections. */\n for (type = FIRST_KEYMAP_FILE_TYPE;\n type <= LAST_KEYMAP_FILE_TYPE;\n type++) {\n log_dbg(ctx, \"Compiling %s \\\"%s\\\"\\n\",\n xkb_file_type_to_string(type), files[type]->name);\n\n ok = compile_file_fns[type](files[type], keymap, merge);\n if (!ok) {\n log_err(ctx, \"Failed to compile %s\\n\",\n xkb_file_type_to_string(type));\n return false;\n }\n }\n\n return UpdateDerivedKeymapFields(keymap);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'xkbcomp: fix crash when parsing an xkb_geometry section\n\nxkb_geometry sections are ignored; previously the had done so by\nreturning NULL for the section's XkbFile, however some sections of the\ncode do not expect this. Instead, create an XkbFile for it, it will\nnever be processes and discarded later.\n\nCaught with the afl fuzzer.\n\nSigned-off-by: Ran Benita '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline void CheckEventLogging()\n{\n /*\n Are we logging events?\n */\n if (IsLinkedListEmpty(log_cache) != MagickFalse)\n event_logging=MagickFalse;\n else\n {\n LogInfo\n *p;\n\n ResetLinkedListIterator(log_cache);\n p=(LogInfo *) GetNextValueInLinkedList(log_cache);\n event_logging=p->event_mask != NoEvents ? MagickTrue: MagickFalse;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1224'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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=(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 if (length > GetBlobSize(image))\n {\n DestroyJNG(NULL,&color_image,&color_image_info,\n &alpha_image,&alpha_image_info);\n ThrowReaderException(CorruptImageError,\n \"InsufficientImageDataInFile\");\n }\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,\n \"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 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,exception);\n\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 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 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,exception);\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 status=OpenBlob(alpha_image_info,alpha_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 (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->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 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 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 if (color_image != (Image *) NULL)\n color_image=DestroyImageList(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,MagickPathExtent,\n \"jpeg:%s\",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 {\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\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 {\n DestroyJNG(NULL,&color_image,&color_image_info,&alpha_image,\n &alpha_image_info);\n jng_image=DestroyImageList(jng_image);\n return(DestroyImageList(image));\n }\n if ((image->columns != jng_image->columns) ||\n (image->rows != jng_image->rows))\n {\n DestroyJNG(NULL,&color_image,&color_image_info,&alpha_image,\n &alpha_image_info);\n jng_image=DestroyImageList(jng_image);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\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 Quantum *) NULL) || (q == (Quantum *) NULL))\n break;\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) && (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,exception);\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n if ((s == (const Quantum *) NULL) || (q == (Quantum *) NULL))\n break;\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 /* 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-399', '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 *ReadPWPImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n char\n filename[MaxTextExtent];\n\n FILE\n *file;\n\n Image\n *image,\n *next_image,\n *pwp_image;\n\n ImageInfo\n *read_info;\n\n int\n c,\n unique_file;\n\n MagickBooleanType\n status;\n\n register Image\n *p;\n\n register ssize_t\n i;\n\n size_t\n filesize,\n length;\n\n ssize_t\n count;\n\n unsigned char\n magick[MaxTextExtent];\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=DestroyImage(image);\n return((Image *) NULL);\n }\n pwp_image=image;\n memset(magick,0,sizeof(magick));\n count=ReadBlob(pwp_image,5,magick);\n if ((count != 5) || (LocaleNCompare((char *) magick,\"SFW95\",5) != 0))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n read_info=CloneImageInfo(image_info);\n (void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL,\n (void *) NULL);\n SetImageInfoBlob(read_info,(void *) NULL,0);\n unique_file=AcquireUniqueFileResource(filename);\n (void) FormatLocaleString(read_info->filename,MagickPathExtent,\"sfw:%s\",\n filename);\n for ( ; ; )\n {\n (void) memset(magick,0,sizeof(magick));\n for (c=ReadBlobByte(pwp_image); c != EOF; c=ReadBlobByte(pwp_image))\n {\n for (i=0; i < 17; i++)\n magick[i]=magick[i+1];\n magick[17]=(unsigned char) c;\n if (LocaleNCompare((char *) (magick+12),\"SFW94A\",6) == 0)\n break;\n }\n if (c == EOF)\n {\n (void) RelinquishUniqueFileResource(filename);\n read_info=DestroyImageInfo(read_info);\n ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\");\n }\n if (LocaleNCompare((char *) (magick+12),\"SFW94A\",6) != 0)\n {\n (void) RelinquishUniqueFileResource(filename);\n read_info=DestroyImageInfo(read_info);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n /*\n Dump SFW image to a temporary file.\n */\n file=(FILE *) NULL;\n if (unique_file != -1)\n file=fdopen(unique_file,\"wb\");\n if ((unique_file == -1) || (file == (FILE *) NULL))\n {\n (void) RelinquishUniqueFileResource(filename);\n read_info=DestroyImageInfo(read_info);\n ThrowFileException(exception,FileOpenError,\"UnableToWriteFile\",\n image->filename);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n length=fwrite(\"SFW94A\",1,6,file);\n (void) length;\n filesize=65535UL*magick[2]+256L*magick[1]+magick[0];\n for (i=0; i < (ssize_t) filesize; i++)\n {\n c=ReadBlobByte(pwp_image);\n if (c == EOF)\n break;\n (void) fputc(c,file);\n }\n (void) fclose(file);\n if (c == EOF)\n {\n (void) RelinquishUniqueFileResource(filename);\n read_info=DestroyImageInfo(read_info);\n ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\");\n }\n next_image=ReadImage(read_info,exception);\n if (next_image == (Image *) NULL)\n break;\n (void) FormatLocaleString(next_image->filename,MaxTextExtent,\n \"slide_%02ld.sfw\",(long) next_image->scene);\n if (image == (Image *) NULL)\n image=next_image;\n else\n {\n /*\n Link image into image list.\n */\n for (p=image; p->next != (Image *) NULL; p=GetNextImageInList(p)) ;\n next_image->previous=p;\n next_image->scene=p->scene+1;\n p->next=next_image;\n }\n if (image_info->number_scenes != 0)\n if (next_image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=SetImageProgress(image,LoadImagesTag,TellBlob(pwp_image),\n GetBlobSize(pwp_image));\n if (status == MagickFalse)\n break;\n }\n if (unique_file != -1)\n (void) close(unique_file);\n (void) RelinquishUniqueFileResource(filename);\n read_info=DestroyImageInfo(read_info);\n if (image != (Image *) NULL)\n {\n if (EOFBlob(image) != MagickFalse)\n {\n char\n *message;\n\n message=GetExceptionMessage(errno);\n (void) ThrowMagickException(exception,GetMagickModule(),\n CorruptImageError,\"UnexpectedEndOfFile\",\"`%s': %s\",image->filename,\n message);\n message=DestroyString(message);\n }\n (void) CloseBlob(image);\n }\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-252'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1199'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int formatIPTC(Image *ifile, Image *ofile)\n{\n char\n temp[MaxTextExtent];\n\n unsigned int\n foundiptc,\n tagsfound;\n\n unsigned char\n recnum,\n dataset;\n\n unsigned char\n *readable,\n *str;\n\n ssize_t\n tagindx,\n taglen;\n\n int\n i,\n tagcount = (int) (sizeof(tags) / sizeof(tag_spec));\n\n int\n c;\n\n foundiptc = 0; /* found the IPTC-Header */\n tagsfound = 0; /* number of tags found */\n\n c = ReadBlobByte(ifile);\n while (c != EOF)\n {\n if (c == 0x1c)\n foundiptc=1;\n else\n {\n if (foundiptc)\n return(-1);\n else\n {\n c=0;\n continue;\n }\n }\n\n /* we found the 0x1c tag and now grab the dataset and record number tags */\n c = ReadBlobByte(ifile);\n if (c == EOF)\n return(-1);\n dataset = (unsigned char) c;\n c = ReadBlobByte(ifile);\n if (c == EOF)\n return(-1);\n recnum = (unsigned char) c;\n /* try to match this record to one of the ones in our named table */\n for (i=0; i< tagcount; i++)\n {\n if (tags[i].id == (short) recnum)\n break;\n }\n if (i < tagcount)\n readable = (unsigned char *) tags[i].name;\n else\n readable = (unsigned char *) \"\";\n /*\n We decode the length of the block that follows - ssize_t or short fmt.\n */\n c=ReadBlobByte(ifile);\n if (c == EOF)\n return(-1);\n if (c & (unsigned char) 0x80)\n return(0);\n else\n {\n int\n c0;\n\n c0=ReadBlobByte(ifile);\n if (c0 == EOF)\n return(-1);\n taglen = (c << 8) | c0;\n }\n if (taglen < 0)\n return(-1);\n /* make a buffer to hold the tag datand snag it from the input stream */\n str=(unsigned char *) AcquireQuantumMemory((size_t) (taglen+MaxTextExtent),\n sizeof(*str));\n if (str == (unsigned char *) NULL)\n return(0);\n for (tagindx=0; tagindx 0)\n (void) FormatLocaleString(temp,MaxTextExtent,\"%d#%d#%s=\",\n (unsigned int) dataset, (unsigned int) recnum, readable);\n else\n (void) FormatLocaleString(temp,MaxTextExtent,\"%d#%d=\",\n (unsigned int) dataset,(unsigned int) recnum);\n (void) WriteBlobString(ofile,temp);\n formatString( ofile, (char *)str, taglen );\n str=(unsigned char *) RelinquishMagickMemory(str);\n\n tagsfound++;\n\n c=ReadBlobByte(ifile);\n }\n return((int) tagsfound);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1118'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int read_private_key(RSA *rsa)\n{\n\tint r;\n\tsc_path_t path;\n\tsc_file_t *file;\n\tconst sc_acl_entry_t *e;\n\n\tu8 buf[2048], *p = buf;\n\tsize_t bufsize, keysize;\n\n\tr = select_app_df();\n\tif (r)\n\t\treturn 1;\n\tsc_format_path(\"I0012\", &path);\n\tr = sc_select_file(card, &path, &file);\n\tif (r) {\n\t\tfprintf(stderr, \"Unable to select private key file: %s\\n\", sc_strerror(r));\n\t\treturn 2;\n\t}\n\te = sc_file_get_acl_entry(file, SC_AC_OP_READ);\n\tif (e == NULL || e->method == SC_AC_NEVER)\n\t\treturn 10;\n\tbufsize = file->size;\n\tsc_file_free(file);\n\tr = sc_read_binary(card, 0, buf, bufsize, 0);\n\tif (r < 0) {\n\t\tfprintf(stderr, \"Unable to read private key file: %s\\n\", sc_strerror(r));\n\t\treturn 2;\n\t}\n\tbufsize = r;\n\tdo {\n\t\tif (bufsize < 4)\n\t\t\treturn 3;\n\t\tkeysize = (p[0] << 8) | p[1];\n\t\tif (keysize == 0)\n\t\t\tbreak;\n\t\tif (keysize < 3)\n\t\t\treturn 3;\n\t\tif (p[2] == opt_key_num)\n\t\t\tbreak;\n\t\tp += keysize;\n\t\tbufsize -= keysize;\n\t} while (1);\n\tif (keysize == 0) {\n\t\tprintf(\"Key number %d not found.\\n\", opt_key_num);\n\t\treturn 2;\n\t}\n\treturn parse_private_key(p, keysize, rsa);\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 muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)\n{\n\tmuscle_private_t* priv = MUSCLE_DATA(card);\n\tmscfs_t *fs = priv->fs;\n\tint x;\n\tint count = 0;\n\n\tmscfs_check_cache(priv->fs);\n\n\tfor(x = 0; x < fs->cache.size; x++) {\n\t\tu8* oid= fs->cache.array[x].objectId.id;\n\t\tsc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,\n\t\t\t\"FILE: %02X%02X%02X%02X\\n\",\n\t\t\toid[0],oid[1],oid[2],oid[3]);\n\t\tif(0 == memcmp(fs->currentPath, oid, 2)) {\n\t\t\tbuf[0] = oid[2];\n\t\t\tbuf[1] = oid[3];\n\t\t\tif(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */\n\t\t\tbuf += 2;\n\t\t\tcount+=2;\n\t\t}\n\t}\n\treturn count;\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: show_signal_msg(struct pt_regs *regs, unsigned long error_code,\n\t\tunsigned long address, struct task_struct *tsk)\n{\n\tconst char *loglvl = task_pid_nr(tsk) > 1 ? KERN_INFO : KERN_EMERG;\n\n\tif (!unhandled_signal(tsk, SIGSEGV))\n\t\treturn;\n\n\tif (!printk_ratelimit())\n\t\treturn;\n\n\tprintk(\"%s%s[%d]: segfault at %lx ip %px sp %px error %lx\",\n\t\tloglvl, tsk->comm, task_pid_nr(tsk), address,\n\t\t(void *)regs->ip, (void *)regs->sp, error_code);\n\n\tprint_vma_addr(KERN_CONT \" in \", regs->ip);\n\n\tprintk(KERN_CONT \"\\n\");\n\n\tshow_opcodes((u8 *)regs->ip, loglvl);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'x86/dumpstack: Don't dump kernel memory based on usermode RIP\n\n\nshow_opcodes() is used both for dumping kernel instructions and for dumping\nuser instructions. If userspace causes #PF by jumping to a kernel address,\nshow_opcodes() can be reached with regs->ip controlled by the user,\npointing to kernel code. Make sure that userspace can't trick us into\ndumping kernel memory into dmesg.\n\nFixes: 7cccf0725cf7 (\"x86/dumpstack: Add a show_ip() function\")\nSigned-off-by: Jann Horn \nSigned-off-by: Thomas Gleixner \nReviewed-by: Kees Cook \nReviewed-by: Borislav Petkov \nCc: \"H. Peter Anvin\" \nCc: Andy Lutomirski \nCc: security@kernel.org\nCc: stable@vger.kernel.org\nLink: https://lkml.kernel.org/r/20180828154901.112726-1-jannh@google.com'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void WavOutFile::write(const short *buffer, int numElems)\r\n{\r\n int res;\r\n\r\n // 16 bit samples\r\n if (numElems < 1) return; // nothing to do\r\n\r\n switch (header.format.bits_per_sample)\r\n {\r\n case 8:\r\n {\r\n int i;\r\n unsigned char *temp = (unsigned char *)getConvBuffer(numElems);\r\n // convert from 16bit format to 8bit format\r\n for (i = 0; i < numElems; i ++)\r\n {\r\n temp[i] = (unsigned char)(buffer[i] / 256 + 128);\r\n }\r\n // write in 8bit format\r\n write(temp, numElems);\r\n break;\r\n }\r\n\r\n case 16:\r\n {\r\n // 16bit format\r\n\r\n // use temp buffer to swap byte order if necessary\r\n short *pTemp = (short *)getConvBuffer(numElems * sizeof(short));\r\n memcpy(pTemp, buffer, numElems * 2);\r\n _swap16Buffer(pTemp, numElems);\r\n\r\n res = (int)fwrite(pTemp, 2, numElems, fptr);\r\n\r\n if (res != numElems) \r\n {\r\n ST_THROW_RT_ERROR(\"Error while writing to a wav file.\");\r\n }\r\n bytesWritten += 2 * numElems;\r\n break;\r\n }\r\n\r\n default:\r\n {\r\n stringstream ss;\r\n ss << \"\\nOnly 8/16 bit sample WAV files supported in integer compilation. Can't open WAV file with \";\r\n ss << (int)header.format.bits_per_sample;\r\n ss << \" bit sample format. \";\r\n ST_THROW_RT_ERROR(ss.str().c_str());\r\n }\r\n }\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: struct posix_acl *ovl_get_acl(struct inode *inode, int type)\n{\n\tstruct inode *realinode = ovl_inode_real(inode);\n\n\tif (!realinode)\n\t\treturn ERR_PTR(-ENOENT);\n\n\tif (!IS_POSIXACL(realinode))\n\t\treturn NULL;\n\n\tif (!realinode->i_op->get_acl)\n\t\treturn NULL;\n\n\treturn realinode->i_op->get_acl(realinode, type);\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: udisks_log (UDisksLogLevel level,\n const gchar *function,\n const gchar *location,\n const gchar *format,\n ...)\n{\n va_list var_args;\n gchar *message;\n\n va_start (var_args, format);\n message = g_strdup_vprintf (format, var_args);\n va_end (var_args);\n\n#if GLIB_CHECK_VERSION(2, 50, 0)\n g_log_structured (\"udisks\", (GLogLevelFlags) level,\n \"MESSAGE\", message, \"THREAD_ID\", \"%d\", (gint) syscall (SYS_gettid),\n \"CODE_FUNC\", function, \"CODE_FILE\", location);\n#else\n g_log (\"udisks\", level, \"[%d]: %s [%s, %s()]\", (gint) syscall (SYS_gettid), message, location, function);\n#endif\n\n g_free (message);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-134'], 'message': 'Fix string format vulnerability\n\nIf the message in g_log_structured itself\ncontained format sequences like %d or %n they\nwere applied again, leading to leaked stack contents\nand possibly memory corruption. It can be triggered\ne.g. by a volume label containing format sequences.\n\nPrint the message argument itself into a \"%s\" string\nto avoid intepreting format sequences.\n\nhttps://github.com/storaged-project/udisks/issues/578'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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 WriteSGIImage(const ImageInfo *image_info,Image *image,\n ExceptionInfo *exception)\n{\n CompressionType\n compression;\n\n const char\n *value;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n scene;\n\n MagickSizeType\n number_pixels;\n\n MemoryInfo\n *pixel_info;\n\n SGIInfo\n iris_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 ssize_t\n y,\n z;\n\n unsigned char\n *pixels,\n *packets;\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 if ((image->columns > 65535UL) || (image->rows > 65535UL))\n ThrowWriterException(ImageError,\"WidthOrHeightExceedsLimit\");\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 do\n {\n /*\n Initialize SGI raster file header.\n */\n (void) TransformImageColorspace(image,sRGBColorspace,exception);\n (void) memset(&iris_info,0,sizeof(iris_info));\n iris_info.magic=0x01DA;\n compression=image->compression;\n if (image_info->compression != UndefinedCompression)\n compression=image_info->compression;\n if (image->depth > 8)\n compression=NoCompression;\n if (compression == NoCompression)\n iris_info.storage=(unsigned char) 0x00;\n else\n iris_info.storage=(unsigned char) 0x01;\n iris_info.bytes_per_pixel=(unsigned char) (image->depth > 8 ? 2 : 1);\n iris_info.dimension=3;\n iris_info.columns=(unsigned short) image->columns;\n iris_info.rows=(unsigned short) image->rows;\n if (image->alpha_trait != UndefinedPixelTrait)\n iris_info.depth=4;\n else\n {\n if ((image_info->type != TrueColorType) &&\n (SetImageGray(image,exception) != MagickFalse))\n {\n iris_info.dimension=2;\n iris_info.depth=1;\n }\n else\n iris_info.depth=3;\n }\n iris_info.minimum_value=0;\n iris_info.maximum_value=(size_t) (image->depth <= 8 ?\n 1UL*ScaleQuantumToChar(QuantumRange) :\n 1UL*ScaleQuantumToShort(QuantumRange));\n /*\n Write SGI header.\n */\n (void) WriteBlobMSBShort(image,iris_info.magic);\n (void) WriteBlobByte(image,iris_info.storage);\n (void) WriteBlobByte(image,iris_info.bytes_per_pixel);\n (void) WriteBlobMSBShort(image,iris_info.dimension);\n (void) WriteBlobMSBShort(image,iris_info.columns);\n (void) WriteBlobMSBShort(image,iris_info.rows);\n (void) WriteBlobMSBShort(image,iris_info.depth);\n (void) WriteBlobMSBLong(image,(unsigned int) iris_info.minimum_value);\n (void) WriteBlobMSBLong(image,(unsigned int) iris_info.maximum_value);\n (void) WriteBlobMSBLong(image,(unsigned int) iris_info.sans);\n value=GetImageProperty(image,\"label\",exception);\n if (value != (const char *) NULL)\n (void) CopyMagickString(iris_info.name,value,sizeof(iris_info.name));\n (void) WriteBlob(image,sizeof(iris_info.name),(unsigned char *)\n iris_info.name);\n (void) WriteBlobMSBLong(image,(unsigned int) iris_info.pixel_format);\n (void) WriteBlob(image,sizeof(iris_info.filler),iris_info.filler);\n /*\n Allocate SGI pixels.\n */\n number_pixels=(MagickSizeType) image->columns*image->rows;\n if ((4*iris_info.bytes_per_pixel*number_pixels) !=\n ((MagickSizeType) (size_t) (4*iris_info.bytes_per_pixel*number_pixels)))\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixel_info=AcquireVirtualMemory((size_t) number_pixels,4*\n iris_info.bytes_per_pixel*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Convert image pixels to uncompressed SGI pixels.\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 if (image->depth <= 8)\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n register unsigned char\n *q;\n\n q=(unsigned char *) pixels;\n q+=((iris_info.rows-1)-y)*(4*iris_info.columns)+4*x;\n *q++=ScaleQuantumToChar(GetPixelRed(image,p));\n *q++=ScaleQuantumToChar(GetPixelGreen(image,p));\n *q++=ScaleQuantumToChar(GetPixelBlue(image,p));\n *q++=ScaleQuantumToChar(GetPixelAlpha(image,p));\n p+=GetPixelChannels(image);\n }\n else\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n register unsigned short\n *q;\n\n q=(unsigned short *) pixels;\n q+=((iris_info.rows-1)-y)*(4*iris_info.columns)+4*x;\n *q++=ScaleQuantumToShort(GetPixelRed(image,p));\n *q++=ScaleQuantumToShort(GetPixelGreen(image,p));\n *q++=ScaleQuantumToShort(GetPixelBlue(image,p));\n *q++=ScaleQuantumToShort(GetPixelAlpha(image,p));\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n switch (compression)\n {\n case NoCompression:\n {\n /*\n Write uncompressed SGI pixels.\n */\n for (z=0; z < (ssize_t) iris_info.depth; z++)\n {\n for (y=0; y < (ssize_t) iris_info.rows; y++)\n {\n if (image->depth <= 8)\n for (x=0; x < (ssize_t) iris_info.columns; x++)\n {\n register unsigned char\n *q;\n\n q=(unsigned char *) pixels;\n q+=y*(4*iris_info.columns)+4*x+z;\n (void) WriteBlobByte(image,*q);\n }\n else\n for (x=0; x < (ssize_t) iris_info.columns; x++)\n {\n register unsigned short\n *q;\n\n q=(unsigned short *) pixels;\n q+=y*(4*iris_info.columns)+4*x+z;\n (void) WriteBlobMSBShort(image,*q);\n }\n }\n }\n break;\n }\n default:\n {\n MemoryInfo\n *packet_info;\n\n size_t\n length,\n number_packets,\n *runlength;\n\n ssize_t\n offset,\n *offsets;\n\n /*\n Convert SGI uncompressed pixels.\n */\n offsets=(ssize_t *) AcquireQuantumMemory(iris_info.rows,\n iris_info.depth*sizeof(*offsets));\n runlength=(size_t *) AcquireQuantumMemory(iris_info.rows,\n iris_info.depth*sizeof(*runlength));\n packet_info=AcquireVirtualMemory((2*(size_t) iris_info.columns+10)*\n image->rows,4*sizeof(*packets));\n if ((offsets == (ssize_t *) NULL) ||\n (runlength == (size_t *) NULL) ||\n (packet_info == (MemoryInfo *) NULL))\n {\n if (offsets != (ssize_t *) NULL)\n offsets=(ssize_t *) RelinquishMagickMemory(offsets);\n if (runlength != (size_t *) NULL)\n runlength=(size_t *) RelinquishMagickMemory(runlength);\n if (packet_info != (MemoryInfo *) NULL)\n packet_info=RelinquishVirtualMemory(packet_info);\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n packets=(unsigned char *) GetVirtualMemoryBlob(packet_info);\n offset=512+4*2*((ssize_t) iris_info.rows*iris_info.depth);\n number_packets=0;\n q=pixels;\n for (y=0; y < (ssize_t) iris_info.rows; y++)\n {\n for (z=0; z < (ssize_t) iris_info.depth; z++)\n {\n length=SGIEncode(q+z,(size_t) iris_info.columns,packets+\n number_packets);\n number_packets+=length;\n offsets[y+z*iris_info.rows]=offset;\n runlength[y+z*iris_info.rows]=(size_t) length;\n offset+=(ssize_t) length;\n }\n q+=(iris_info.columns*4);\n }\n /*\n Write out line start and length tables and runlength-encoded pixels.\n */\n for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)\n (void) WriteBlobMSBLong(image,(unsigned int) offsets[i]);\n for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)\n (void) WriteBlobMSBLong(image,(unsigned int) runlength[i]);\n (void) WriteBlob(image,number_packets,packets);\n /*\n Relinquish resources.\n */\n offsets=(ssize_t *) RelinquishMagickMemory(offsets);\n runlength=(size_t *) RelinquishMagickMemory(runlength);\n packet_info=RelinquishVirtualMemory(packet_info);\n break;\n }\n }\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (GetNextImageInList(image) == (Image *) NULL)\n break;\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,SaveImagesTag,scene++,\n GetImageListLength(image));\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-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1052'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n BMPInfo\n bmp_info;\n\n Image\n *image;\n\n IndexPacket\n index;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n offset,\n start_position;\n\n MemoryInfo\n *pixel_info;\n\n register IndexPacket\n *indexes;\n\n register PixelPacket\n *q;\n\n register ssize_t\n i,\n x;\n\n register unsigned char\n *p;\n\n size_t\n bit,\n bytes_per_line,\n length;\n\n ssize_t\n count,\n y;\n\n unsigned char\n magick[12],\n *pixels;\n\n unsigned int\n blue,\n green,\n offset_bits,\n red;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Determine if this a BMP file.\n */\n (void) memset(&bmp_info,0,sizeof(bmp_info));\n bmp_info.ba_offset=0;\n start_position=0;\n offset_bits=0;\n count=ReadBlob(image,2,magick);\n if (count != 2)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n do\n {\n LongPixelPacket\n shift;\n\n PixelPacket\n quantum_bits;\n\n /*\n Verify BMP identifier.\n */\n if (bmp_info.ba_offset == 0)\n start_position=TellBlob(image)-2;\n bmp_info.ba_offset=0;\n while (LocaleNCompare((char *) magick,\"BA\",2) == 0)\n {\n bmp_info.file_size=ReadBlobLSBLong(image);\n bmp_info.ba_offset=ReadBlobLSBLong(image);\n bmp_info.offset_bits=ReadBlobLSBLong(image);\n count=ReadBlob(image,2,magick);\n if (count != 2)\n break;\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Magick: %c%c\",\n magick[0],magick[1]);\n if ((count != 2) || ((LocaleNCompare((char *) magick,\"BM\",2) != 0) &&\n (LocaleNCompare((char *) magick,\"CI\",2) != 0)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n bmp_info.file_size=ReadBlobLSBLong(image);\n (void) ReadBlobLSBLong(image);\n\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" File_size in header: %u bytes\",bmp_info.file_size);\n\n bmp_info.offset_bits=ReadBlobLSBLong(image);\n bmp_info.size=ReadBlobLSBLong(image);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" BMP size: %u\",\n bmp_info.size);\n if (bmp_info.size == 12)\n {\n /*\n OS/2 BMP image file.\n */\n (void) CopyMagickString(image->magick,\"BMP2\",MaxTextExtent);\n bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image));\n bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image));\n bmp_info.planes=ReadBlobLSBShort(image);\n bmp_info.bits_per_pixel=ReadBlobLSBShort(image);\n bmp_info.x_pixels=0;\n bmp_info.y_pixels=0;\n bmp_info.number_colors=0;\n bmp_info.compression=BI_RGB;\n bmp_info.image_size=0;\n bmp_info.alpha_mask=0;\n if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Format: OS/2 Bitmap\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Geometry: %.20gx%.20g\",(double) bmp_info.width,(double)\n bmp_info.height);\n }\n }\n else\n {\n /*\n Microsoft Windows BMP image file.\n */\n if (bmp_info.size < 40)\n ThrowReaderException(CorruptImageError,\"NonOS2HeaderSizeError\");\n bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image);\n bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image);\n bmp_info.planes=ReadBlobLSBShort(image);\n bmp_info.bits_per_pixel=ReadBlobLSBShort(image);\n bmp_info.compression=ReadBlobLSBLong(image);\n bmp_info.image_size=ReadBlobLSBLong(image);\n bmp_info.x_pixels=ReadBlobLSBLong(image);\n bmp_info.y_pixels=ReadBlobLSBLong(image);\n bmp_info.number_colors=ReadBlobLSBLong(image);\n if (bmp_info.number_colors > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n bmp_info.colors_important=ReadBlobLSBLong(image);\n if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Format: MS Windows bitmap\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Geometry: %.20gx%.20g\",(double) bmp_info.width,(double)\n bmp_info.height);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Bits per pixel: %.20g\",(double) bmp_info.bits_per_pixel);\n switch (bmp_info.compression)\n {\n case BI_RGB:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_RGB\");\n break;\n }\n case BI_RLE4:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_RLE4\");\n break;\n }\n case BI_RLE8:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_RLE8\");\n break;\n }\n case BI_BITFIELDS:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_BITFIELDS\");\n break;\n }\n case BI_PNG:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_PNG\");\n break;\n }\n case BI_JPEG:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_JPEG\");\n break;\n }\n default:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: UNKNOWN (%u)\",bmp_info.compression);\n }\n }\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Number of colors: %u\",bmp_info.number_colors);\n }\n bmp_info.red_mask=ReadBlobLSBLong(image);\n bmp_info.green_mask=ReadBlobLSBLong(image);\n bmp_info.blue_mask=ReadBlobLSBLong(image);\n if (bmp_info.size > 40)\n {\n double\n gamma;\n\n /*\n Read color management information.\n */\n bmp_info.alpha_mask=ReadBlobLSBLong(image);\n bmp_info.colorspace=ReadBlobLSBSignedLong(image);\n /*\n Decode 2^30 fixed point formatted CIE primaries.\n */\n# define BMP_DENOM ((double) 0x40000000)\n bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n\n gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+\n bmp_info.red_primary.z;\n gamma=PerceptibleReciprocal(gamma);\n bmp_info.red_primary.x*=gamma;\n bmp_info.red_primary.y*=gamma;\n image->chromaticity.red_primary.x=bmp_info.red_primary.x;\n image->chromaticity.red_primary.y=bmp_info.red_primary.y;\n\n gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+\n bmp_info.green_primary.z;\n gamma=PerceptibleReciprocal(gamma);\n bmp_info.green_primary.x*=gamma;\n bmp_info.green_primary.y*=gamma;\n image->chromaticity.green_primary.x=bmp_info.green_primary.x;\n image->chromaticity.green_primary.y=bmp_info.green_primary.y;\n\n gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+\n bmp_info.blue_primary.z;\n gamma=PerceptibleReciprocal(gamma);\n bmp_info.blue_primary.x*=gamma;\n bmp_info.blue_primary.y*=gamma;\n image->chromaticity.blue_primary.x=bmp_info.blue_primary.x;\n image->chromaticity.blue_primary.y=bmp_info.blue_primary.y;\n\n /*\n Decode 16^16 fixed point formatted gamma_scales.\n */\n bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000;\n bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000;\n bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000;\n /*\n Compute a single gamma from the BMP 3-channel gamma.\n */\n image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+\n bmp_info.gamma_scale.z)/3.0;\n }\n else\n (void) CopyMagickString(image->magick,\"BMP3\",MaxTextExtent);\n\n if (bmp_info.size > 108)\n {\n size_t\n intent;\n\n /*\n Read BMP Version 5 color management information.\n */\n intent=ReadBlobLSBLong(image);\n switch ((int) intent)\n {\n case LCS_GM_BUSINESS:\n {\n image->rendering_intent=SaturationIntent;\n break;\n }\n case LCS_GM_GRAPHICS:\n {\n image->rendering_intent=RelativeIntent;\n break;\n }\n case LCS_GM_IMAGES:\n {\n image->rendering_intent=PerceptualIntent;\n break;\n }\n case LCS_GM_ABS_COLORIMETRIC:\n {\n image->rendering_intent=AbsoluteIntent;\n break;\n }\n }\n (void) ReadBlobLSBLong(image); /* Profile data */\n (void) ReadBlobLSBLong(image); /* Profile size */\n (void) ReadBlobLSBLong(image); /* Reserved byte */\n }\n }\n if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image))\n (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,\n \"LengthAndFilesizeDoNotMatch\",\"`%s'\",image->filename);\n else\n if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image))\n (void) ThrowMagickException(exception,GetMagickModule(),\n CorruptImageWarning,\"LengthAndFilesizeDoNotMatch\",\"`%s'\",\n image->filename);\n if (bmp_info.width <= 0)\n ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\");\n if (bmp_info.height == 0)\n ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\");\n if (bmp_info.planes != 1)\n ThrowReaderException(CorruptImageError,\"StaticPlanesValueNotEqualToOne\");\n if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) &&\n (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) &&\n (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32))\n ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n if (bmp_info.bits_per_pixel < 16 &&\n bmp_info.number_colors > (1U << bmp_info.bits_per_pixel))\n ThrowReaderException(CorruptImageError,\"UnrecognizedNumberOfColors\");\n if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8))\n ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4))\n ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16))\n ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n switch (bmp_info.compression)\n {\n case BI_RGB:\n image->compression=NoCompression;\n break;\n case BI_RLE8:\n case BI_RLE4:\n image->compression=RLECompression;\n break;\n case BI_BITFIELDS:\n break;\n case BI_JPEG:\n ThrowReaderException(CoderError,\"JPEGCompressNotSupported\");\n case BI_PNG:\n ThrowReaderException(CoderError,\"PNGCompressNotSupported\");\n default:\n ThrowReaderException(CorruptImageError,\"UnrecognizedImageCompression\");\n }\n image->columns=(size_t) MagickAbsoluteValue(bmp_info.width);\n image->rows=(size_t) MagickAbsoluteValue(bmp_info.height);\n image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8;\n image->matte=((bmp_info.alpha_mask != 0) &&\n (bmp_info.compression == BI_BITFIELDS)) ? MagickTrue : MagickFalse;\n if (bmp_info.bits_per_pixel < 16)\n {\n size_t\n one;\n\n image->storage_class=PseudoClass;\n image->colors=bmp_info.number_colors;\n one=1;\n if (image->colors == 0)\n image->colors=one << bmp_info.bits_per_pixel;\n }\n image->x_resolution=(double) bmp_info.x_pixels/100.0;\n image->y_resolution=(double) bmp_info.y_pixels/100.0;\n image->units=PixelsPerCentimeterResolution;\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n InheritException(exception,&image->exception);\n return(DestroyImageList(image));\n }\n if (image->storage_class == PseudoClass)\n {\n unsigned char\n *bmp_colormap;\n\n size_t\n packet_size;\n\n /*\n Read BMP raster colormap.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reading colormap of %.20g colors\",(double) image->colors);\n if (AcquireImageColormap(image,image->colors) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t)\n image->colors,4*sizeof(*bmp_colormap));\n if (bmp_colormap == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if ((bmp_info.size == 12) || (bmp_info.size == 64))\n packet_size=3;\n else\n packet_size=4;\n offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET);\n if (offset < 0)\n {\n bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n count=ReadBlob(image,packet_size*image->colors,bmp_colormap);\n if (count != (ssize_t) (packet_size*image->colors))\n {\n bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n ThrowReaderException(CorruptImageError,\n \"InsufficientImageDataInFile\");\n }\n p=bmp_colormap;\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n image->colormap[i].blue=ScaleCharToQuantum(*p++);\n image->colormap[i].green=ScaleCharToQuantum(*p++);\n image->colormap[i].red=ScaleCharToQuantum(*p++);\n if (packet_size == 4)\n p++;\n }\n bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n }\n /*\n Read image data.\n */\n if (bmp_info.offset_bits == offset_bits)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n offset_bits=bmp_info.offset_bits;\n offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET);\n if (offset < 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (bmp_info.compression == BI_RLE4)\n bmp_info.bits_per_pixel<<=1;\n bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32);\n length=(size_t) bytes_per_line*image->rows;\n if (((MagickSizeType) length/8) > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n if ((bmp_info.compression == BI_RGB) ||\n (bmp_info.compression == BI_BITFIELDS))\n {\n pixel_info=AcquireVirtualMemory(image->rows,MagickMax(bytes_per_line,\n image->columns+256UL)*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reading pixels (%.20g bytes)\",(double) length);\n count=ReadBlob(image,length,pixels);\n if (count != (ssize_t) length)\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"InsufficientImageDataInFile\");\n }\n }\n else\n {\n /*\n Convert run-length encoded raster pixels.\n */\n pixel_info=AcquireVirtualMemory(image->rows,MagickMax(bytes_per_line,\n image->columns+256UL)*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n status=DecodeImage(image,bmp_info.compression,pixels,\n image->columns*image->rows);\n if (status == MagickFalse)\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"UnableToRunlengthDecodeImage\");\n }\n }\n /*\n Convert BMP raster image to pixel packets.\n */\n if (bmp_info.compression == BI_RGB)\n {\n /*\n We should ignore the alpha value in BMP3 files but there have been\n reports about 32 bit files with alpha. We do a quick check to see if\n the alpha channel contains a value that is not zero (default value).\n If we find a non zero value we asume the program that wrote the file\n wants to use the alpha channel.\n */\n if ((image->matte == MagickFalse) && (bmp_info.size == 40) &&\n (bmp_info.bits_per_pixel == 32))\n {\n bytes_per_line=4*(image->columns);\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (*(p+3) != 0)\n {\n image->matte=MagickTrue;\n y=-1;\n break;\n }\n p+=4;\n }\n }\n }\n bmp_info.alpha_mask=image->matte != MagickFalse ? 0xff000000U : 0U;\n bmp_info.red_mask=0x00ff0000U;\n bmp_info.green_mask=0x0000ff00U;\n bmp_info.blue_mask=0x000000ffU;\n if (bmp_info.bits_per_pixel == 16)\n {\n /*\n RGB555.\n */\n bmp_info.red_mask=0x00007c00U;\n bmp_info.green_mask=0x000003e0U;\n bmp_info.blue_mask=0x0000001fU;\n }\n }\n (void) memset(&shift,0,sizeof(shift));\n (void) memset(&quantum_bits,0,sizeof(quantum_bits));\n if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32))\n {\n register size_t\n sample;\n\n /*\n Get shift and quantum bits info from bitfield masks.\n */\n if (bmp_info.red_mask != 0)\n while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0)\n {\n shift.red++;\n if (shift.red > 32U)\n break;\n }\n if (bmp_info.green_mask != 0)\n while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0)\n {\n shift.green++;\n if (shift.green > 32U)\n break;\n }\n if (bmp_info.blue_mask != 0)\n while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0)\n {\n shift.blue++;\n if (shift.blue > 32U)\n break;\n }\n if (bmp_info.alpha_mask != 0)\n while (((bmp_info.alpha_mask << shift.opacity) & 0x80000000UL) == 0)\n {\n shift.opacity++;\n if (shift.opacity > 32U)\n break;\n }\n sample=shift.red;\n while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0)\n {\n sample++;\n if (sample > 32U)\n break;\n }\n quantum_bits.red=ClampToQuantum((MagickRealType) sample-shift.red);\n sample=shift.green;\n while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0)\n {\n sample++;\n if (sample > 32U)\n break;\n }\n quantum_bits.green=ClampToQuantum((MagickRealType) sample-shift.green);\n sample=shift.blue;\n while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0)\n {\n sample++;\n if (sample > 32U)\n break;\n }\n quantum_bits.blue=ClampToQuantum((MagickRealType) sample-shift.blue);\n sample=shift.opacity;\n while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0)\n {\n sample++;\n if (sample > 32U)\n break;\n }\n quantum_bits.opacity=ClampToQuantum((MagickRealType) sample-\n shift.opacity);\n }\n switch (bmp_info.bits_per_pixel)\n {\n case 1:\n {\n /*\n Convert bitmap scanline.\n */\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=0; x < ((ssize_t) image->columns-7); x+=8)\n {\n for (bit=0; bit < 8; bit++)\n {\n index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);\n SetPixelIndex(indexes+x+bit,index);\n q++;\n }\n p++;\n }\n if ((image->columns % 8) != 0)\n {\n for (bit=0; bit < (image->columns % 8); bit++)\n {\n index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);\n SetPixelIndex(indexes+x+bit,index);\n }\n p++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n (void) SyncImage(image);\n break;\n }\n case 4:\n {\n /*\n Convert PseudoColor scanline.\n */\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=0; x < ((ssize_t) image->columns-1); x+=2)\n {\n (void) IsValidColormapIndex(image,(ssize_t) ((*p >> 4) & 0x0f),\n &index,exception);\n SetPixelIndex(indexes+x,index);\n (void) IsValidColormapIndex(image,(ssize_t) (*p & 0x0f),&index,\n exception);\n SetPixelIndex(indexes+x+1,index);\n p++;\n }\n if ((image->columns % 2) != 0)\n {\n (void) IsValidColormapIndex(image,(ssize_t) ((*p >> 4) & 0xf),\n &index,exception);\n SetPixelIndex(indexes+(x++),index);\n p++;\n }\n if (x < (ssize_t) image->columns)\n break;\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n (void) SyncImage(image);\n break;\n }\n case 8:\n {\n /*\n Convert PseudoColor scanline.\n */\n if ((bmp_info.compression == BI_RLE8) ||\n (bmp_info.compression == BI_RLE4))\n bytes_per_line=image->columns;\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=(ssize_t) image->columns; x != 0; --x)\n {\n (void) IsValidColormapIndex(image,(ssize_t) *p,&index,exception);\n SetPixelIndex(indexes,index);\n indexes++;\n p++;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n offset=(MagickOffsetType) (image->rows-y-1);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n (void) SyncImage(image);\n break;\n }\n case 16:\n {\n unsigned int\n alpha,\n pixel;\n\n /*\n Convert bitfield encoded 16-bit PseudoColor scanline.\n */\n if (bmp_info.compression != BI_RGB &&\n bmp_info.compression != BI_BITFIELDS)\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"UnrecognizedImageCompression\");\n }\n bytes_per_line=2*(image->columns+image->columns % 2);\n image->storage_class=DirectClass;\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=(unsigned int) (*p++);\n pixel|=(*p++) << 8;\n red=((pixel & bmp_info.red_mask) << shift.red) >> 16;\n if (quantum_bits.red == 5)\n red|=((red & 0xe000) >> 5);\n if (quantum_bits.red <= 8)\n red|=((red & 0xff00) >> 8);\n green=((pixel & bmp_info.green_mask) << shift.green) >> 16;\n if (quantum_bits.green == 5)\n green|=((green & 0xe000) >> 5);\n if (quantum_bits.green == 6)\n green|=((green & 0xc000) >> 6);\n if (quantum_bits.green <= 8)\n green|=((green & 0xff00) >> 8);\n blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;\n if (quantum_bits.blue == 5)\n blue|=((blue & 0xe000) >> 5);\n if (quantum_bits.blue <= 8)\n blue|=((blue & 0xff00) >> 8);\n SetPixelRed(q,ScaleShortToQuantum((unsigned short) red));\n SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green));\n SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue));\n SetPixelOpacity(q,OpaqueOpacity);\n if (image->matte != MagickFalse)\n {\n alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16;\n if (quantum_bits.opacity <= 8)\n alpha|=((alpha & 0xff00) >> 8);\n SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha));\n }\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n offset=(MagickOffsetType) (image->rows-y-1);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case 24:\n {\n /*\n Convert DirectColor scanline.\n */\n bytes_per_line=4*((image->columns*24+31)/32);\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelBlue(q,ScaleCharToQuantum(*p++));\n SetPixelGreen(q,ScaleCharToQuantum(*p++));\n SetPixelRed(q,ScaleCharToQuantum(*p++));\n SetPixelOpacity(q,OpaqueOpacity);\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n offset=(MagickOffsetType) (image->rows-y-1);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case 32:\n {\n /*\n Convert bitfield encoded DirectColor scanline.\n */\n if ((bmp_info.compression != BI_RGB) &&\n (bmp_info.compression != BI_BITFIELDS))\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"UnrecognizedImageCompression\");\n }\n bytes_per_line=4*(image->columns);\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n unsigned int\n alpha,\n pixel;\n\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=(unsigned int) (*p++);\n pixel|=((unsigned int) *p++ << 8);\n pixel|=((unsigned int) *p++ << 16);\n pixel|=((unsigned int) *p++ << 24);\n red=((pixel & bmp_info.red_mask) << shift.red) >> 16;\n if (quantum_bits.red == 8)\n red|=(red >> 8);\n green=((pixel & bmp_info.green_mask) << shift.green) >> 16;\n if (quantum_bits.green == 8)\n green|=(green >> 8);\n blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;\n if (quantum_bits.blue == 8)\n blue|=(blue >> 8);\n SetPixelRed(q,ScaleShortToQuantum((unsigned short) red));\n SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green));\n SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue));\n SetPixelAlpha(q,OpaqueOpacity);\n if (image->matte != MagickFalse)\n {\n alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16;\n if (quantum_bits.opacity == 8)\n alpha|=(alpha >> 8);\n SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha));\n }\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n offset=(MagickOffsetType) (image->rows-y-1);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n default:\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n }\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (y > 0)\n break;\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n if (bmp_info.height < 0)\n {\n Image\n *flipped_image;\n\n /*\n Correct image orientation.\n */\n flipped_image=FlipImage(image,exception);\n if (flipped_image != (Image *) NULL)\n {\n DuplicateBlob(flipped_image,image);\n ReplaceImageInList(&image, flipped_image);\n image=flipped_image;\n }\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n *magick='\\0';\n if (bmp_info.ba_offset != 0)\n {\n offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET);\n if (offset < 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n count=ReadBlob(image,2,magick);\n if ((count == 2) && (IsBMP(magick,2) != MagickFalse))\n {\n /*\n Acquire next image structure.\n */\n AcquireNextImage(image_info,image);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n 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 (IsBMP(magick,2) != MagickFalse);\n (void) CloseBlob(image);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1337'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int link_stop_clients(Link *link) {\n int r = 0, k;\n\n assert(link);\n assert(link->manager);\n assert(link->manager->event);\n\n if (!link->network)\n return 0;\n\n if (link->dhcp_client) {\n k = sd_dhcp_client_stop(link->dhcp_client);\n if (k < 0)\n r = log_link_warning_errno(link, r, \"Could not stop DHCPv4 client: %m\");\n }\n\n if (link->ipv4ll) {\n k = sd_ipv4ll_stop(link->ipv4ll);\n if (k < 0)\n r = log_link_warning_errno(link, r, \"Could not stop IPv4 link-local: %m\");\n }\n\n if(link->ndisc_router_discovery) {\n if (link->dhcp6_client) {\n k = sd_dhcp6_client_stop(link->dhcp6_client);\n if (k < 0)\n r = log_link_warning_errno(link, r, \"Could not stop DHCPv6 client: %m\");\n }\n\n k = sd_ndisc_stop(link->ndisc_router_discovery);\n if (k < 0)\n r = log_link_warning_errno(link, r, \"Could not stop IPv6 Router Discovery: %m\");\n }\n\n if (link->lldp) {\n k = sd_lldp_stop(link->lldp);\n if (k < 0)\n r = log_link_warning_errno(link, r, \"Could not stop LLDP: %m\");\n }\n\n return r;\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: do_execstack(i_ctx_t *i_ctx_p, bool include_marks, os_ptr op1)\n{\n os_ptr op = osp;\n ref *arefs = op1->value.refs;\n uint asize = r_size(op1);\n uint i;\n ref *rq;\n\n /*\n * Copy elements from the stack to the array,\n * optionally skipping executable nulls.\n * Clear the executable bit in any internal operators, and\n * convert t_structs and t_astructs (which can only appear\n * in connection with stack marks, which means that they will\n * probably be freed when unwinding) to something harmless.\n */\n for (i = 0, rq = arefs + asize; rq != arefs; ++i) {\n const ref *rp = ref_stack_index(&e_stack, (long)i);\n\n if (r_has_type_attrs(rp, t_null, a_executable) && !include_marks)\n continue;\n --rq;\n ref_assign_old(op1, rq, rp, \"execstack\");\n switch (r_type(rq)) {\n case t_operator: {\n uint opidx = op_index(rq);\n\n if (opidx == 0 || op_def_is_internal(op_index_def(opidx)))\n r_clear_attrs(rq, a_executable);\n break;\n }\n case t_struct:\n case t_astruct: {\n const char *tname = rq->value.pstruct ?\n gs_struct_type_name_string(\n gs_object_type(imemory, rq->value.pstruct))\n : \"NULL\";\n\n make_const_string(rq, a_readonly | avm_foreign,\n strlen(tname), (const byte *)tname);\n break;\n }\n default:\n ;\n }\n }\n pop(op - op1);\n return 0;\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;\n\n print_buffer = curlx_mvaprintf(fmt, ap);\n if(!print_buffer)\n return;\n len = strlen(print_buffer);\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 curl_free(print_buffer);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-125'], 'message': 'voutf: fix bad arethmetic when outputting warnings to stderr\n\nCVE-2018-16842\nReported-by: Brian Carpenter\nBug: https://curl.haxx.se/docs/CVE-2018-16842.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: int RGWListMultipart_ObjStore::get_params()\n{\n upload_id = s->info.args.get(\"uploadId\");\n\n if (upload_id.empty()) {\n op_ret = -ENOTSUP;\n }\n string marker_str = s->info.args.get(\"part-number-marker\");\n\n if (!marker_str.empty()) {\n string err;\n marker = strict_strtol(marker_str.c_str(), 10, &err);\n if (!err.empty()) {\n ldout(s->cct, 20) << \"bad marker: \" << marker << dendl;\n op_ret = -EINVAL;\n return op_ret;\n }\n }\n \n string str = s->info.args.get(\"max-parts\");\n op_ret = parse_value_and_bound(str, &max_parts, 0, g_conf()->rgw_max_listing_results, max_parts);\n\n return op_ret;\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: void Image::printIFDStructure(BasicIo& io, std::ostream& out, Exiv2::PrintStructureOption option,uint32_t start,bool bSwap,char c,int depth)\n {\n depth++;\n bool bFirst = true ;\n\n // buffer\n const size_t dirSize = 32;\n DataBuf dir(dirSize);\n bool bPrint = option == kpsBasic || option == kpsRecursive;\n\n do {\n // Read top of directory\n io.seek(start,BasicIo::beg);\n io.read(dir.pData_, 2);\n uint16_t dirLength = byteSwap2(dir,0,bSwap);\n\n bool tooBig = dirLength > 500;\n if ( tooBig ) throw Error(kerTiffDirectoryTooLarge);\n\n if ( bFirst && bPrint ) {\n out << Internal::indent(depth) << Internal::stringFormat(\"STRUCTURE OF TIFF FILE (%c%c): \",c,c) << io.path() << std::endl;\n if ( tooBig ) out << Internal::indent(depth) << \"dirLength = \" << dirLength << std::endl;\n }\n\n // Read the dictionary\n for ( int i = 0 ; i < dirLength ; i ++ ) {\n if ( bFirst && bPrint ) {\n out << Internal::indent(depth)\n << \" address | tag | \"\n << \" type | count | offset | value\\n\";\n }\n bFirst = false;\n\n io.read(dir.pData_, 12);\n uint16_t tag = byteSwap2(dir,0,bSwap);\n uint16_t type = byteSwap2(dir,2,bSwap);\n uint32_t count = byteSwap4(dir,4,bSwap);\n uint32_t offset = byteSwap4(dir,8,bSwap);\n\n // Break for unknown tag types else we may segfault.\n if ( !typeValid(type) ) {\n std::cerr << \"invalid type value detected in Image::printIFDStructure: \" << type << std::endl;\n start = 0; // break from do loop\n throw Error(kerInvalidTypeValue);\n }\n\n std::string sp = \"\" ; // output spacer\n\n //prepare to print the value\n uint32_t kount = isPrintXMP(tag,option) ? count // haul in all the data\n : isPrintICC(tag,option) ? count // ditto\n : isStringType(type) ? (count > 32 ? 32 : count) // restrict long arrays\n : count > 5 ? 5\n : count\n ;\n uint32_t pad = isStringType(type) ? 1 : 0;\n uint32_t size = isStringType(type) ? 1\n : is2ByteType(type) ? 2\n : is4ByteType(type) ? 4\n : is8ByteType(type) ? 8\n : 1\n ;\n\n // if ( offset > io.size() ) offset = 0; // Denial of service?\n\n // #55 and #56 memory allocation crash test/data/POC8\n long long allocate = (long long) size*count + pad+20;\n if ( allocate > (long long) io.size() ) {\n throw Error(kerInvalidMalloc);\n }\n DataBuf buf((long)allocate); // allocate a buffer\n std::memset(buf.pData_, 0, buf.size_);\n std::memcpy(buf.pData_,dir.pData_+8,4); // copy dir[8:11] into buffer (short strings)\n const bool bOffsetIsPointer = count*size > 4;\n\n if ( bOffsetIsPointer ) { // read into buffer\n size_t restore = io.tell(); // save\n io.seek(offset,BasicIo::beg); // position\n io.read(buf.pData_,count*size);// read\n io.seek(restore,BasicIo::beg); // restore\n }\n\n if ( bPrint ) {\n const uint32_t address = start + 2 + i*12 ;\n const std::string offsetString = bOffsetIsPointer?\n Internal::stringFormat(\"%10u\", offset):\n \"\";\n\n out << Internal::indent(depth)\n << Internal::stringFormat(\"%8u | %#06x %-28s |%10s |%9u |%10s | \"\n ,address,tag,tagName(tag).c_str(),typeName(type),count,offsetString.c_str());\n if ( isShortType(type) ){\n for ( size_t k = 0 ; k < kount ; k++ ) {\n out << sp << byteSwap2(buf,k*size,bSwap);\n sp = \" \";\n }\n } else if ( isLongType(type) ){\n for ( size_t k = 0 ; k < kount ; k++ ) {\n out << sp << byteSwap4(buf,k*size,bSwap);\n sp = \" \";\n }\n\n } else if ( isRationalType(type) ){\n for ( size_t k = 0 ; k < kount ; k++ ) {\n uint32_t a = byteSwap4(buf,k*size+0,bSwap);\n uint32_t b = byteSwap4(buf,k*size+4,bSwap);\n out << sp << a << \"/\" << b;\n sp = \" \";\n }\n } else if ( isStringType(type) ) {\n out << sp << Internal::binaryToString(makeSlice(buf, 0, kount));\n }\n\n sp = kount == count ? \"\" : \" ...\";\n out << sp << std::endl;\n\n if ( option == kpsRecursive && (tag == 0x8769 /* ExifTag */ || tag == 0x014a/*SubIFDs*/ || type == tiffIfd) ) {\n for ( size_t k = 0 ; k < count ; k++ ) {\n size_t restore = io.tell();\n uint32_t offset = byteSwap4(buf,k*size,bSwap);\n printIFDStructure(io,out,option,offset,bSwap,c,depth);\n io.seek(restore,BasicIo::beg);\n }\n } else if ( option == kpsRecursive && tag == 0x83bb /* IPTCNAA */ ) {\n\n if (static_cast(Safe::add(count, offset)) > io.size()) {\n throw Error(kerCorruptedMetadata);\n }\n\n const size_t restore = io.tell();\n io.seek(offset, BasicIo::beg); // position\n std::vector bytes(count) ; // allocate memory\n // TODO: once we have C++11 use bytes.data()\n const long read_bytes = io.read(&bytes[0], count);\n io.seek(restore, BasicIo::beg);\n // TODO: once we have C++11 use bytes.data()\n IptcData::printStructure(out, makeSliceUntil(&bytes[0], read_bytes), depth);\n\n } else if ( option == kpsRecursive && tag == 0x927c /* MakerNote */ && count > 10) {\n size_t restore = io.tell(); // save\n\n uint32_t jump= 10 ;\n byte bytes[20] ;\n const char* chars = (const char*) &bytes[0] ;\n io.seek(offset,BasicIo::beg); // position\n io.read(bytes,jump ) ; // read\n bytes[jump]=0 ;\n if ( ::strcmp(\"Nikon\",chars) == 0 ) {\n // tag is an embedded tiff\n byte* bytes=new byte[count-jump] ; // allocate memory\n io.read(bytes,count-jump) ; // read\n MemIo memIo(bytes,count-jump) ; // create a file\n printTiffStructure(memIo,out,option,depth);\n delete[] bytes ; // free\n } else {\n // tag is an IFD\n io.seek(0,BasicIo::beg); // position\n printIFDStructure(io,out,option,offset,bSwap,c,depth);\n }\n\n io.seek(restore,BasicIo::beg); // restore\n }\n }\n\n if ( isPrintXMP(tag,option) ) {\n buf.pData_[count]=0;\n out << (char*) buf.pData_;\n }\n if ( isPrintICC(tag,option) ) {\n out.write((const char*)buf.pData_,count);\n }\n }\n if ( start ) {\n io.read(dir.pData_, 4);\n start = tooBig ? 0 : byteSwap4(dir,0,bSwap);\n }\n } while (start) ;\n\n if ( bPrint ) {\n out << Internal::indent(depth) << \"END \" << io.path() << std::endl;\n }\n out.flush();\n depth--;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'Check in Image::printIFDStructure if seek and reads are OK'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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 handle_returned_header (void *ptr, size_t size, size_t nmemb, void *stream)\n{\n auth_client *auth_user = stream;\n size_t bytes = size * nmemb;\n client_t *client = auth_user->client;\n\n if (client)\n {\n auth_t *auth = client->auth;\n auth_url *url = auth->state;\n if (strncasecmp (ptr, url->auth_header, url->auth_header_len) == 0)\n client->authenticated = 1;\n if (strncasecmp (ptr, url->timelimit_header, url->timelimit_header_len) == 0)\n {\n unsigned int limit = 0;\n sscanf ((char *)ptr+url->timelimit_header_len, \"%u\\r\\n\", &limit);\n client->con->discon_time = time(NULL) + limit;\n }\n if (strncasecmp (ptr, \"icecast-auth-message: \", 22) == 0)\n {\n char *eol;\n snprintf (url->errormsg, sizeof (url->errormsg), \"%s\", (char*)ptr+22);\n eol = strchr (url->errormsg, '\\r');\n if (eol == NULL)\n eol = strchr (url->errormsg, '\\n');\n if (eol)\n *eol = '\\0';\n }\n }\n\n return bytes;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix: Worked around buffer overflows in URL auth's cURL interface\n\nThis is only a workaround that keeps compatibility with 2.4.x mainline.\nA real fix has been implemented in 2.5.x (master).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ambsdtar_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 = NULL;\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 = NULL;\n char *file_include = NULL;\n GString *strbuf;\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 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 goto common_error;\n\t return;\n\t}\n\n\tif (bsdtar_directory) {\n\t dirname = bsdtar_directory;\n\t} else {\n\t dirname = argument->dle.device;\n\t}\n\tambsdtar_build_exinclude(&argument->dle, 1,\n\t\t\t\t &nb_exclude, &file_exclude,\n\t\t\t\t &nb_include, &file_include);\n\n\trun_calcsize(argument->config, \"BSDTAR\", 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\t}\n\tamfree(file_exclude);\n\tamfree(file_include);\n\tamfree(qdisk);\n\treturn;\n }\n\n if (!bsdtar_path) {\n\terrmsg = g_strdup(_(\"BSDTAR-PATH not defined\"));\n\tgoto common_error;\n }\n\n if (!check_exec_for_suid(bsdtar_path, FALSE)) {\n\terrmsg = g_strdup_printf(\"'%s' binary is not secure\", bsdtar_path);\n\tgoto common_error;\n }\n\n if (!state_dir) {\n\terrmsg = g_strdup(_(\"STATE-DIR not defined\"));\n\tgoto common_error;\n }\n\n qdisk = quote_string(argument->dle.disk);\n for (levels = argument->level; levels != NULL; levels = levels->next) {\n\tchar *timestamps;\n\tlevel = GPOINTER_TO_INT(levels->data);\n\ttimestamps = ambsdtar_get_timestamps(argument, level, stdout, CMD_ESTIMATE);\n\tcmd = g_strdup(bsdtar_path);\n\targv_ptr = ambsdtar_build_argv(argument, timestamps, &file_exclude,\n\t\t\t\t &file_include, CMD_ESTIMATE);\n\tamfree(timestamps);\n\n\tstart_time = curclock();\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_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 (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 g_debug(\"%s\", 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\toff_t blocksize = gblocksize;\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\tif (!blocksize) {\n\t\t\t blocksize = 20;\n\t\t\t}\n\t\t\tblocksize /= 2;\n\t\t\tsize = (size+blocksize-1) / blocksize;\n\t\t\tsize *= blocksize;\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 g_debug(\"%s\", line);\n\t}\n\n\tg_debug(\".....\");\n\tg_debug(_(\"estimate time for %s level %d: %s\"),\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\"), cmd);\n\t g_debug(_(\"%s for %s\"), errmsg, qdisk);\n\t g_debug(\".....\");\n\t} else if(size == (off_t)0 && argument->level == 0) {\n\t g_debug(_(\"possible %s problem -- is \\\"%s\\\" really empty?\"),\n\t\t cmd, argument->dle.disk);\n\t g_debug(\".....\");\n\t}\n\tg_debug(_(\"estimate size for %s level %d: %lld KB\"),\n\t\t qdisk,\n\t\t level,\n\t\t (long long)size);\n\n\t(void)kill(-tarpid, SIGTERM);\n\n\tg_debug(_(\"waiting for %s \\\"%s\\\" child\"), cmd, qdisk);\n\twaitpid(tarpid, &wait_status, 0);\n\tif (WIFSIGNALED(wait_status)) {\n\t strbuf = g_string_new(errmsg);\n\t g_string_append_printf(strbuf, \"%s terminated with signal %d: see %s\",\n cmd, WTERMSIG(wait_status), dbfn());\n\t g_free(errmsg);\n errmsg = g_string_free(strbuf, FALSE);\n\t exit_status = 1;\n\t} else if (WIFEXITED(wait_status)) {\n\t if (exit_value[WEXITSTATUS(wait_status)] == 1) {\n strbuf = g_string_new(errmsg);\n g_string_append_printf(strbuf, \"%s exited with status %d: see %s\",\n cmd, WEXITSTATUS(wait_status), dbfn());\n\t\tg_free(errmsg);\n errmsg = g_string_free(strbuf, FALSE);\n\t\texit_status = 1;\n\t } else {\n\t\t/* Normal exit */\n\t }\n\t} else {\n\t errmsg = g_strdup_printf(_(\"%s got bad exit: see %s\"),\n\t\t\t\tcmd, dbfn());\n\t exit_status = 1;\n\t}\n\tg_debug(_(\"after %s %s wait\"), cmd, qdisk);\n\ncommon_exit:\n\tif (errmsg) {\n\t g_debug(\"%s\", errmsg);\n\t fprintf(stdout, \"ERROR %s\\n\", errmsg);\n\t amfree(errmsg);\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\tamfree(incrname);\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(file_exclude);\n amfree(file_include);\n amfree(errmsg);\n amfree(qerrmsg);\n amfree(incrname);\n return;\n\ncommon_error:\n qerrmsg = quote_string(errmsg);\n amfree(qdisk);\n g_debug(\"%s\", errmsg);\n fprintf(stdout, \"ERROR %s\\n\", qerrmsg);\n exit_status = 1;\n amfree(file_exclude);\n amfree(file_include);\n amfree(errmsg);\n amfree(qerrmsg);\n amfree(incrname);\n return;\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: amgtar_restore(\n application_argument_t *argument)\n{\n char *cmd;\n GPtrArray *argv_ptr = g_ptr_array_new();\n char **env;\n int j;\n char *e;\n char *include_filename = NULL;\n char *exclude_filename = NULL;\n\n if (!gnutar_path) {\n\terror(_(\"GNUTAR-PATH not defined\"));\n }\n\n if (!check_exec_for_suid(gnutar_path, FALSE)) {\n error(\"'%s' binary is not secure\", gnutar_path);\n }\n\n cmd = stralloc(gnutar_path);\n g_ptr_array_add(argv_ptr, stralloc(gnutar_path));\n g_ptr_array_add(argv_ptr, stralloc(\"--numeric-owner\"));\n if (gnutar_no_unquote)\n\tg_ptr_array_add(argv_ptr, stralloc(\"--no-unquote\"));\n if (gnutar_acls)\n\tg_ptr_array_add(argv_ptr, stralloc(\"--acls\"));\n if (gnutar_selinux)\n\tg_ptr_array_add(argv_ptr, stralloc(\"--selinux\"));\n if (gnutar_xattrs)\n\tg_ptr_array_add(argv_ptr, stralloc(\"--xattrs\"));\n /* ignore trailing zero blocks on input (this was the default until tar-1.21) */\n if (argument->ignore_zeros) {\n\tg_ptr_array_add(argv_ptr, stralloc(\"--ignore-zeros\"));\n }\n if (argument->tar_blocksize) {\n\tg_ptr_array_add(argv_ptr, stralloc(\"--blocking-factor\"));\n\tg_ptr_array_add(argv_ptr, stralloc(argument->tar_blocksize));\n }\n g_ptr_array_add(argv_ptr, stralloc(\"-xpGvf\"));\n g_ptr_array_add(argv_ptr, stralloc(\"-\"));\n if (gnutar_directory) {\n\tstruct stat stat_buf;\n\tif(stat(gnutar_directory, &stat_buf) != 0) {\n\t fprintf(stderr,\"can not stat directory %s: %s\\n\", gnutar_directory, strerror(errno));\n\t exit(1);\n\t}\n\tif (!S_ISDIR(stat_buf.st_mode)) {\n\t fprintf(stderr,\"%s is not a directory\\n\", gnutar_directory);\n\t exit(1);\n\t}\n\tif (access(gnutar_directory, W_OK) != 0) {\n\t fprintf(stderr, \"Can't write to %s: %s\\n\", gnutar_directory, strerror(errno));\n\t exit(1);\n\t}\n\tg_ptr_array_add(argv_ptr, stralloc(\"--directory\"));\n\tg_ptr_array_add(argv_ptr, stralloc(gnutar_directory));\n }\n\n g_ptr_array_add(argv_ptr, stralloc(\"--wildcards\"));\n if (argument->dle.exclude_list &&\n\targument->dle.exclude_list->nb_element == 1) {\n\tFILE *exclude;\n\tchar *sdisk;\n\tint in_argv;\n\tint entry_in_exclude = 0;\n\tchar line[2*PATH_MAX];\n\tFILE *exclude_list;\n\n\tif (argument->dle.disk) {\n\t sdisk = sanitise_filename(argument->dle.disk);\n\t} else {\n\t sdisk = g_strdup_printf(\"no_dle-%d\", (int)getpid());\n\t}\n\texclude_filename= vstralloc(AMANDA_TMPDIR, \"/\", \"exclude-\", sdisk, NULL);\n\texclude_list = fopen(argument->dle.exclude_list->first->name, \"r\");\n\n\texclude = fopen(exclude_filename, \"w\");\n\twhile (fgets(line, 2*PATH_MAX, exclude_list)) {\n\t char *escaped;\n\t line[strlen(line)-1] = '\\0'; /* remove '\\n' */\n\t escaped = escape_tar_glob(line, &in_argv);\n\t if (in_argv) {\n\t\tg_ptr_array_add(argv_ptr, \"--exclude\");\n\t\tg_ptr_array_add(argv_ptr, escaped);\n\t } else {\n\t\tfprintf(exclude,\"%s\\n\", escaped);\n\t\tentry_in_exclude++;\n\t\tamfree(escaped);\n\t }\n\t}\n\tfclose(exclude);\n\tg_ptr_array_add(argv_ptr, stralloc(\"--exclude-from\"));\n\tg_ptr_array_add(argv_ptr, exclude_filename);\n }\n\n if (argument->exclude_list_glob) {\n\tg_ptr_array_add(argv_ptr, stralloc(\"--exclude-from\"));\n\tg_ptr_array_add(argv_ptr, stralloc(argument->exclude_list_glob));\n }\n\n {\n\tGPtrArray *argv_include = g_ptr_array_new();\n\tFILE *include;\n\tchar *sdisk;\n\tint in_argv;\n\tguint i;\n\tint entry_in_include = 0;\n\n\tif (argument->dle.disk) {\n\t sdisk = sanitise_filename(argument->dle.disk);\n\t} else {\n\t sdisk = g_strdup_printf(\"no_dle-%d\", (int)getpid());\n\t}\n\tinclude_filename = vstralloc(AMANDA_TMPDIR, \"/\", \"include-\", sdisk, NULL);\n\tinclude = fopen(include_filename, \"w\");\n\tif (argument->dle.include_list &&\n\t argument->dle.include_list->nb_element == 1) {\n\t char line[2*PATH_MAX];\n\t FILE *include_list = fopen(argument->dle.include_list->first->name, \"r\");\n\t while (fgets(line, 2*PATH_MAX, include_list)) {\n\t\tchar *escaped;\n\t\tline[strlen(line)-1] = '\\0'; /* remove '\\n' */\n\t\tescaped = escape_tar_glob(line, &in_argv);\n\t\tif (in_argv) {\n\t\t g_ptr_array_add(argv_include, escaped);\n\t\t} else {\n\t\t fprintf(include,\"%s\\n\", escaped);\n\t\t entry_in_include++;\n\t\t amfree(escaped);\n\t\t}\n\t }\n\t}\n\n\tfor (j=1; j< argument->argc; j++) {\n\t char *escaped = escape_tar_glob(argument->argv[j], &in_argv);\n\t if (in_argv) {\n\t\tg_ptr_array_add(argv_include, escaped);\n\t } else {\n\t\tfprintf(include,\"%s\\n\", escaped);\n\t\tentry_in_include++;\n\t\tamfree(escaped);\n\t }\n\t}\n\tfclose(include);\n\n\tif (entry_in_include) {\n\t g_ptr_array_add(argv_ptr, stralloc(\"--files-from\"));\n\t g_ptr_array_add(argv_ptr, include_filename);\n\t}\n\n\tif (argument->include_list_glob) {\n\t g_ptr_array_add(argv_ptr, stralloc(\"--files-from\"));\n\t g_ptr_array_add(argv_ptr, stralloc(argument->include_list_glob));\n\t}\n\n\tfor (i = 0; i < argv_include->len; i++) {\n\t g_ptr_array_add(argv_ptr, (char *)g_ptr_array_index(argv_include,i));\n\t}\n }\n g_ptr_array_add(argv_ptr, NULL);\n\n debug_executing(argv_ptr);\n\n env = safe_env();\n become_root();\n execve(cmd, (char **)argv_ptr->pdata, env);\n e = strerror(errno);\n error(_(\"error [exec %s: %s]\"), cmd, e);\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: main(\n int\t\targc,\n char **\targv)\n{\n#ifdef GNUTAR\n int i;\n char *e;\n char *dbf;\n char *cmdline;\n#endif\n int good_option;\n\n if (argc > 1 && argv && argv[1] && g_str_equal(argv[1], \"--version\")) {\n\tprintf(\"runtar-%s\\n\", VERSION);\n\treturn (0);\n }\n\n /*\n * Configure program for internationalization:\n * 1) Only set the message locale for now.\n * 2) Set textdomain for all amanda related programs to \"amanda\"\n * We don't want to be forced to support dozens of message catalogs.\n */ \n setlocale(LC_MESSAGES, \"C\");\n textdomain(\"amanda\"); \n\n safe_fd(-1, 0);\n safe_cd();\n\n set_pname(\"runtar\");\n\n /* Don't die when child closes pipe */\n signal(SIGPIPE, SIG_IGN);\n\n dbopen(DBG_SUBDIR_CLIENT);\n config_init(CONFIG_INIT_CLIENT, NULL);\n\n if (argc < 3) {\n\terror(_(\"Need at least 3 arguments\\n\"));\n\t/*NOTREACHED*/\n }\n\n dbprintf(_(\"version %s\\n\"), VERSION);\n\n if (strcmp(argv[3], \"--create\") != 0) {\n\terror(_(\"Can only be used to create tar archives\\n\"));\n\t/*NOTREACHED*/\n }\n\n#ifndef GNUTAR\n\n g_fprintf(stderr,_(\"gnutar not available on this system.\\n\"));\n dbprintf(_(\"%s: gnutar not available on this system.\\n\"), argv[0]);\n dbclose();\n return 1;\n\n#else\n\n /*\n * Print out version information for tar.\n */\n do {\n\tFILE *\tversion_file;\n\tchar\tversion_buf[80];\n\n\tif ((version_file = popen(GNUTAR \" --version 2>&1\", \"r\")) != NULL) {\n\t if (fgets(version_buf, (int)sizeof(version_buf), version_file) != NULL) {\n\t\tdbprintf(_(GNUTAR \" version: %s\\n\"), version_buf);\n\t } else {\n\t\tif (ferror(version_file)) {\n\t\t dbprintf(_(GNUTAR \" version: Read failure: %s\\n\"), strerror(errno));\n\t\t} else {\n\t\t dbprintf(_(GNUTAR \" version: Read failure; EOF\\n\"));\n\t\t}\n\t }\n\t} else {\n\t dbprintf(_(GNUTAR \" version: unavailable: %s\\n\"), strerror(errno));\n\t}\n } while(0);\n\n#ifdef WANT_SETUID_CLIENT\n check_running_as(RUNNING_AS_CLIENT_LOGIN | RUNNING_AS_UID_ONLY);\n if (!become_root()) {\n\terror(_(\"error [%s could not become root (is the setuid bit set?)]\\n\"), get_pname());\n\t/*NOTREACHED*/\n }\n#else\n check_running_as(RUNNING_AS_CLIENT_LOGIN);\n#endif\n\n /* skip argv[0] */\n argc--;\n argv++;\n\n dbprintf(_(\"config: %s\\n\"), argv[0]);\n if (strcmp(argv[0], \"NOCONFIG\") != 0)\n\tdbrename(argv[0], DBG_SUBDIR_CLIENT);\n argc--;\n argv++;\n\n if (!check_exec_for_suid(GNUTAR, TRUE)) {\n\tdbclose();\n\texit(1);\n }\n\n cmdline = stralloc(GNUTAR);\n good_option = 0;\n for (i = 1; argv[i]; i++) {\n\tchar *quoted;\n\n\tif (good_option <= 0) {\n\t if (g_str_has_prefix(argv[i],\"--rsh-command\") ||\n\t\tg_str_has_prefix(argv[i],\"--to-command\") ||\n\t\tg_str_has_prefix(argv[i],\"--info-script\") ||\n\t\tg_str_has_prefix(argv[i],\"--new-volume-script\") ||\n\t\tg_str_has_prefix(argv[i],\"--rmt-command\") ||\n\t\tg_str_has_prefix(argv[i],\"--use-compress-program\")) {\n\t\t/* Filter potential malicious option */\n\t\tgood_option = 0;\n\t } else if (g_str_has_prefix(argv[i],\"--create\") ||\n\t\tg_str_has_prefix(argv[i],\"--totals\") ||\n\t\tg_str_has_prefix(argv[i],\"--dereference\") ||\n\t\tg_str_has_prefix(argv[i],\"--no-recursion\") ||\n\t\tg_str_has_prefix(argv[i],\"--one-file-system\") ||\n\t\tg_str_has_prefix(argv[i],\"--incremental\") ||\n\t\tg_str_has_prefix(argv[i],\"--atime-preserve\") ||\n\t\tg_str_has_prefix(argv[i],\"--sparse\") ||\n\t\tg_str_has_prefix(argv[i],\"--ignore-failed-read\") ||\n\t\tg_str_has_prefix(argv[i],\"--numeric-owner\")) {\n\t\t/* Accept theses options */\n\t\tgood_option++;\n\t } else if (g_str_has_prefix(argv[i],\"--blocking-factor\") ||\n\t\tg_str_has_prefix(argv[i],\"--file\") ||\n\t\tg_str_has_prefix(argv[i],\"--directory\") ||\n\t\tg_str_has_prefix(argv[i],\"--exclude\") ||\n\t\tg_str_has_prefix(argv[i],\"--transform\") ||\n\t\tg_str_has_prefix(argv[i],\"--listed-incremental\") ||\n\t\tg_str_has_prefix(argv[i],\"--newer\") ||\n\t\tg_str_has_prefix(argv[i],\"--exclude-from\") ||\n\t\tg_str_has_prefix(argv[i],\"--files-from\")) {\n\t\t/* Accept theses options with the following argument */\n\t\tgood_option += 2;\n\t } else if (argv[i][0] != '-') {\n\t\tgood_option++;\n\t }\n\t}\n\tif (good_option <= 0) {\n\t error(\"error [%s invalid option: %s]\", get_pname(), argv[i]);\n\t}\n\tgood_option--;\n\n\tquoted = quote_string(argv[i]);\n\tcmdline = vstrextend(&cmdline, \" \", quoted, NULL);\n\tamfree(quoted);\n }\n dbprintf(_(\"running: %s\\n\"), cmdline);\n amfree(cmdline);\n\n dbf = dbfn();\n if (dbf) {\n\tdbf = stralloc(dbf);\n }\n dbclose();\n\n execve(GNUTAR, argv, safe_env());\n\n e = strerror(errno);\n dbreopen(dbf, \"more\");\n amfree(dbf);\n dbprintf(_(\"execve of %s failed (%s)\\n\"), GNUTAR, e);\n dbclose();\n\n g_fprintf(stderr, _(\"runtar: could not exec %s: %s\\n\"), GNUTAR, e);\n return 1;\n#endif\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: int main(int argc, char *argv[]) {\n GooString *fileName;\n UnicodeMap *uMap;\n GooString *ownerPW, *userPW;\n PDFDoc *doc;\n char uBuf[8];\n char path[1024];\n char *p;\n bool ok;\n int exitCode;\n GooList *embeddedFiles = nullptr;\n int nFiles, nPages, n, i, j;\n FileSpec *fileSpec;\n Page *page;\n Annots *annots;\n Annot *annot;\n const GooString *s1;\n Unicode u;\n bool isUnicode;\n\n Win32Console win32Console(&argc, &argv);\n exitCode = 99;\n\n // parse args\n ok = parseArgs(argDesc, &argc, argv);\n if ((doList ? 1 : 0) +\n ((saveNum != 0) ? 1 : 0) +\n (saveAll ? 1 : 0) != 1) {\n ok = false;\n }\n if (!ok || argc != 2 || printVersion || printHelp) {\n fprintf(stderr, \"pdfdetach version %s\\n\", PACKAGE_VERSION);\n fprintf(stderr, \"%s\\n\", popplerCopyright);\n fprintf(stderr, \"%s\\n\", xpdfCopyright);\n if (!printVersion) {\n printUsage(\"pdfdetach\", \"\", argDesc);\n }\n goto err0;\n }\n fileName = new GooString(argv[1]);\n\n // read config file\n globalParams = new GlobalParams();\n if (textEncName[0]) {\n globalParams->setTextEncoding(textEncName);\n }\n\n // get mapping to output encoding\n if (!(uMap = globalParams->getTextEncoding())) {\n error(errConfig, -1, \"Couldn't get text encoding\");\n delete fileName;\n goto err1;\n }\n\n // open PDF file\n if (ownerPassword[0] != '\\001') {\n ownerPW = new GooString(ownerPassword);\n } else {\n ownerPW = nullptr;\n }\n if (userPassword[0] != '\\001') {\n userPW = new GooString(userPassword);\n } else {\n userPW = nullptr;\n }\n\n doc = PDFDocFactory().createPDFDoc(*fileName, ownerPW, userPW);\n\n if (userPW) {\n delete userPW;\n }\n if (ownerPW) {\n delete ownerPW;\n }\n if (!doc->isOk()) {\n exitCode = 1;\n goto err2;\n }\n\n embeddedFiles = new GooList();\n for (i = 0; i < doc->getCatalog()->numEmbeddedFiles(); ++i)\n embeddedFiles->push_back(doc->getCatalog()->embeddedFile(i));\n\n nPages = doc->getCatalog()->getNumPages();\n for (i = 0; i < nPages; ++i) {\n page = doc->getCatalog()->getPage(i + 1);\n if (!page)\n continue;\n annots = page->getAnnots();\n if (!annots)\n break;\n\n for (j = 0; j < annots->getNumAnnots(); ++j) {\n annot = annots->getAnnot(j);\n if (annot->getType() != Annot::typeFileAttachment)\n continue;\n embeddedFiles->push_back(new FileSpec(static_cast(annot)->getFile()));\n }\n }\n\n nFiles = embeddedFiles->getLength();\n\n // list embedded files\n if (doList) {\n printf(\"%d embedded files\\n\", nFiles);\n for (i = 0; i < nFiles; ++i) {\n fileSpec = static_cast(embeddedFiles->get(i));\n printf(\"%d: \", i+1);\n s1 = fileSpec->getFileName();\n if ((s1->getChar(0) & 0xff) == 0xfe && (s1->getChar(1) & 0xff) == 0xff) {\n isUnicode = true;\n j = 2;\n } else {\n isUnicode = false;\n j = 0;\n }\n while (j < fileSpec->getFileName()->getLength()) {\n if (isUnicode) {\n u = ((s1->getChar(j) & 0xff) << 8) | (s1->getChar(j+1) & 0xff);\n j += 2;\n } else {\n u = pdfDocEncoding[s1->getChar(j) & 0xff];\n ++j;\n }\n n = uMap->mapUnicode(u, uBuf, sizeof(uBuf));\n fwrite(uBuf, 1, n, stdout);\n }\n fputc('\\n', stdout);\n }\n\n // save all embedded files\n } else if (saveAll) {\n for (i = 0; i < nFiles; ++i) {\n fileSpec = static_cast(embeddedFiles->get(i));\n if (savePath[0]) {\n\tn = strlen(savePath);\n\tif (n > (int)sizeof(path) - 2) {\n\t n = sizeof(path) - 2;\n\t}\n\tmemcpy(path, savePath, n);\n\tpath[n] = '/';\n\tp = path + n + 1;\n } else {\n\tp = path;\n }\n s1 = fileSpec->getFileName();\n if ((s1->getChar(0) & 0xff) == 0xfe && (s1->getChar(1) & 0xff) == 0xff) {\n isUnicode = true;\n j = 2;\n } else {\n isUnicode = false;\n j = 0;\n }\n while (j < fileSpec->getFileName()->getLength()) {\n if (isUnicode) {\n u = ((s1->getChar(j) & 0xff) << 8) | (s1->getChar(j+1) & 0xff);\n j += 2;\n } else {\n u = pdfDocEncoding[s1->getChar(j) & 0xff];\n ++j;\n }\n n = uMap->mapUnicode(u, uBuf, sizeof(uBuf));\n if (p + n >= path + sizeof(path))\n break;\n memcpy(p, uBuf, n);\n p += n;\n }\n *p = '\\0';\n\n auto *embFile = fileSpec->getEmbeddedFile();\n if (!embFile || !embFile->isOk()) {\n\texitCode = 3;\n\tgoto err2;\n }\n if (!embFile->save(path)) {\n\terror(errIO, -1, \"Error saving embedded file as '{0:s}'\", p);\n\texitCode = 2;\n\tgoto err2;\n }\n }\n\n // save an embedded file\n } else {\n if (saveNum < 1 || saveNum > nFiles) {\n error(errCommandLine, -1, \"Invalid file number\");\n goto err2;\n }\n\n fileSpec = static_cast(embeddedFiles->get(saveNum - 1));\n if (savePath[0]) {\n p = savePath;\n } else {\n p = path;\n s1 = fileSpec->getFileName();\n if ((s1->getChar(0) & 0xff) == 0xfe && (s1->getChar(1) & 0xff) == 0xff) {\n isUnicode = true;\n j = 2;\n } else {\n isUnicode = false;\n j = 0;\n }\n while (j < fileSpec->getFileName()->getLength()) {\n if (isUnicode) {\n u = ((s1->getChar(j) & 0xff) << 8) | (s1->getChar(j+1) & 0xff);\n j += 2;\n } else {\n u = pdfDocEncoding[s1->getChar(j) & 0xff];\n ++j;\n }\n n = uMap->mapUnicode(u, uBuf, sizeof(uBuf));\n if (p + n >= path + sizeof(path))\n break;\n memcpy(p, uBuf, n);\n p += n;\n }\n *p = '\\0';\n p = path;\n }\n\n auto *embFile = fileSpec->getEmbeddedFile();\n if (!embFile || !embFile->isOk()) {\n exitCode = 3;\n goto err2;\n }\n if (!embFile->save(p)) {\n error(errIO, -1, \"Error saving embedded file as '{0:s}'\", p);\n exitCode = 2;\n goto err2;\n }\n }\n\n exitCode = 0;\n\n // clean up\n err2:\n if (embeddedFiles)\n deleteGooList(embeddedFiles);\n uMap->decRefCnt();\n delete doc;\n err1:\n delete globalParams;\n err0:\n\n return exitCode;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'pdfdetach: Check for valid file name of embedded file before using it to determine save path.\n\nCloses #660'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: vrrp_print_json(void)\n{\n\tFILE *file;\n\telement e;\n\tstruct json_object *array;\n\n\tif (LIST_ISEMPTY(vrrp_data->vrrp))\n\t\treturn;\n\n\tfile = fopen (\"/tmp/keepalived.json\",\"w\");\n\tif (!file) {\n\t\tlog_message(LOG_INFO, \"Can't open /tmp/keepalived.json (%d: %s)\",\n\t\t\terrno, strerror(errno));\n\t\treturn;\n\t}\n\n\tarray = json_object_new_array();\n\n\tfor (e = LIST_HEAD(vrrp_data->vrrp); e; ELEMENT_NEXT(e)) {\n\t\tstruct json_object *instance_json, *json_stats, *json_data,\n\t\t\t*vips, *evips, *track_ifp, *track_script;\n#ifdef _HAVE_FIB_ROUTING_\n\t\tstruct json_object *vroutes, *vrules;\n#endif\n\t\telement f;\n\n\t\tvrrp_t *vrrp = ELEMENT_DATA(e);\n\t\tinstance_json = json_object_new_object();\n\t\tjson_stats = json_object_new_object();\n\t\tjson_data = json_object_new_object();\n\t\tvips = json_object_new_array();\n\t\tevips = json_object_new_array();\n\t\ttrack_ifp = json_object_new_array();\n\t\ttrack_script = json_object_new_array();\n#ifdef _HAVE_FIB_ROUTING_\n\t\tvroutes = json_object_new_array();\n\t\tvrules = json_object_new_array();\n#endif\n\n\t\t// Dump data to json\n\t\tjson_object_object_add(json_data, \"iname\",\n\t\t\tjson_object_new_string(vrrp->iname));\n\t\tjson_object_object_add(json_data, \"dont_track_primary\",\n\t\t\tjson_object_new_int(vrrp->dont_track_primary));\n\t\tjson_object_object_add(json_data, \"skip_check_adv_addr\",\n\t\t\tjson_object_new_int(vrrp->skip_check_adv_addr));\n\t\tjson_object_object_add(json_data, \"strict_mode\",\n\t\t\tjson_object_new_int((int)vrrp->strict_mode));\n#ifdef _HAVE_VRRP_VMAC_\n\t\tjson_object_object_add(json_data, \"vmac_ifname\",\n\t\t\tjson_object_new_string(vrrp->vmac_ifname));\n#endif\n\t\t// Tracked interfaces are stored in a list\n\t\tif (!LIST_ISEMPTY(vrrp->track_ifp)) {\n\t\t\tfor (f = LIST_HEAD(vrrp->track_ifp); f; ELEMENT_NEXT(f)) {\n\t\t\t\tinterface_t *ifp = ELEMENT_DATA(f);\n\t\t\t\tjson_object_array_add(track_ifp,\n\t\t\t\t\tjson_object_new_string(ifp->ifname));\n\t\t\t}\n\t\t}\n\t\tjson_object_object_add(json_data, \"track_ifp\", track_ifp);\n\n\t\t// Tracked scripts also\n\t\tif (!LIST_ISEMPTY(vrrp->track_script)) {\n\t\t\tfor (f = LIST_HEAD(vrrp->track_script); f; ELEMENT_NEXT(f)) {\n\t\t\t\ttracked_sc_t *tsc = ELEMENT_DATA(f);\n\t\t\t\tvrrp_script_t *vscript = tsc->scr;\n\t\t\t\tjson_object_array_add(track_script,\n\t\t\t\t\tjson_object_new_string(cmd_str(&vscript->script)));\n\t\t\t}\n\t\t}\n\t\tjson_object_object_add(json_data, \"track_script\", track_script);\n\n\t\tjson_object_object_add(json_data, \"ifp_ifname\",\n\t\t\tjson_object_new_string(vrrp->ifp->ifname));\n\t\tjson_object_object_add(json_data, \"master_priority\",\n\t\t\tjson_object_new_int(vrrp->master_priority));\n\t\tjson_object_object_add(json_data, \"last_transition\",\n\t\t\tjson_object_new_double(timeval_to_double(&vrrp->last_transition)));\n\t\tjson_object_object_add(json_data, \"garp_delay\",\n\t\t\tjson_object_new_double(vrrp->garp_delay / TIMER_HZ_FLOAT));\n\t\tjson_object_object_add(json_data, \"garp_refresh\",\n\t\t\tjson_object_new_int((int)vrrp->garp_refresh.tv_sec));\n\t\tjson_object_object_add(json_data, \"garp_rep\",\n\t\t\tjson_object_new_int((int)vrrp->garp_rep));\n\t\tjson_object_object_add(json_data, \"garp_refresh_rep\",\n\t\t\tjson_object_new_int((int)vrrp->garp_refresh_rep));\n\t\tjson_object_object_add(json_data, \"garp_lower_prio_delay\",\n\t\t\tjson_object_new_int((int)(vrrp->garp_lower_prio_delay / TIMER_HZ)));\n\t\tjson_object_object_add(json_data, \"garp_lower_prio_rep\",\n\t\t\tjson_object_new_int((int)vrrp->garp_lower_prio_rep));\n\t\tjson_object_object_add(json_data, \"lower_prio_no_advert\",\n\t\t\tjson_object_new_int((int)vrrp->lower_prio_no_advert));\n\t\tjson_object_object_add(json_data, \"higher_prio_send_advert\",\n\t\t\tjson_object_new_int((int)vrrp->higher_prio_send_advert));\n\t\tjson_object_object_add(json_data, \"vrid\",\n\t\t\tjson_object_new_int(vrrp->vrid));\n\t\tjson_object_object_add(json_data, \"base_priority\",\n\t\t\tjson_object_new_int(vrrp->base_priority));\n\t\tjson_object_object_add(json_data, \"effective_priority\",\n\t\t\tjson_object_new_int(vrrp->effective_priority));\n\t\tjson_object_object_add(json_data, \"vipset\",\n\t\t\tjson_object_new_boolean(vrrp->vipset));\n\n\t\t//Virtual IPs are stored in a list\n\t\tif (!LIST_ISEMPTY(vrrp->vip)) {\n\t\t\tfor (f = LIST_HEAD(vrrp->vip); f; ELEMENT_NEXT(f)) {\n\t\t\t\tip_address_t *vip = ELEMENT_DATA(f);\n\t\t\t\tchar ipaddr[INET6_ADDRSTRLEN];\n\t\t\t\tinet_ntop(vrrp->family, &(vip->u.sin.sin_addr.s_addr),\n\t\t\t\t\tipaddr, INET6_ADDRSTRLEN);\n\t\t\t\tjson_object_array_add(vips,\n\t\t\t\t\tjson_object_new_string(ipaddr));\n\t\t\t}\n\t\t}\n\t\tjson_object_object_add(json_data, \"vips\", vips);\n\n\t\t//External VIPs are also stored in a list\n\t\tif (!LIST_ISEMPTY(vrrp->evip)) {\n\t\t\tfor (f = LIST_HEAD(vrrp->evip); f; ELEMENT_NEXT(f)) {\n\t\t\t\tip_address_t *evip = ELEMENT_DATA(f);\n\t\t\t\tchar ipaddr[INET6_ADDRSTRLEN];\n\t\t\t\tinet_ntop(vrrp->family, &(evip->u.sin.sin_addr.s_addr),\n\t\t\t\t\tipaddr, INET6_ADDRSTRLEN);\n\t\t\t\tjson_object_array_add(evips,\n\t\t\t\t\tjson_object_new_string(ipaddr));\n\t\t\t}\n\t\t}\n\t\tjson_object_object_add(json_data, \"evips\", evips);\n\n\t\tjson_object_object_add(json_data, \"promote_secondaries\",\n\t\t\tjson_object_new_boolean(vrrp->promote_secondaries));\n\n#ifdef _HAVE_FIB_ROUTING_\n\t\t// Dump vroutes\n\t\tif (!LIST_ISEMPTY(vrrp->vroutes)) {\n\t\t\tfor (f = LIST_HEAD(vrrp->vroutes); f; ELEMENT_NEXT(f)) {\n\t\t\t\tip_route_t *route = ELEMENT_DATA(f);\n\t\t\t\tchar *buf = MALLOC(ROUTE_BUF_SIZE);\n\t\t\t\tformat_iproute(route, buf, ROUTE_BUF_SIZE);\n\t\t\t\tjson_object_array_add(vroutes,\n\t\t\t\t\tjson_object_new_string(buf));\n\t\t\t}\n\t\t}\n\t\tjson_object_object_add(json_data, \"vroutes\", vroutes);\n\n\t\t// Dump vrules\n\t\tif (!LIST_ISEMPTY(vrrp->vrules)) {\n\t\t\tfor (f = LIST_HEAD(vrrp->vrules); f; ELEMENT_NEXT(f)) {\n\t\t\t\tip_rule_t *rule = ELEMENT_DATA(f);\n\t\t\t\tchar *buf = MALLOC(RULE_BUF_SIZE);\n\t\t\t\tformat_iprule(rule, buf, RULE_BUF_SIZE);\n\t\t\t\tjson_object_array_add(vrules,\n\t\t\t\t\tjson_object_new_string(buf));\n\t\t\t}\n\t\t}\n\t\tjson_object_object_add(json_data, \"vrules\", vrules);\n#endif\n\n\t\tjson_object_object_add(json_data, \"adver_int\",\n\t\t\tjson_object_new_double(vrrp->adver_int / TIMER_HZ_FLOAT));\n\t\tjson_object_object_add(json_data, \"master_adver_int\",\n\t\t\tjson_object_new_double(vrrp->master_adver_int / TIMER_HZ_FLOAT));\n\t\tjson_object_object_add(json_data, \"accept\",\n\t\t\tjson_object_new_int((int)vrrp->accept));\n\t\tjson_object_object_add(json_data, \"nopreempt\",\n\t\t\tjson_object_new_boolean(vrrp->nopreempt));\n\t\tjson_object_object_add(json_data, \"preempt_delay\",\n\t\t\tjson_object_new_int((int)(vrrp->preempt_delay / TIMER_HZ)));\n\t\tjson_object_object_add(json_data, \"state\",\n\t\t\tjson_object_new_int(vrrp->state));\n\t\tjson_object_object_add(json_data, \"wantstate\",\n\t\t\tjson_object_new_int(vrrp->wantstate));\n\t\tjson_object_object_add(json_data, \"version\",\n\t\t\tjson_object_new_int(vrrp->version));\n\t\tif (vrrp->script_backup)\n\t\t\tjson_object_object_add(json_data, \"script_backup\",\n\t\t\t\tjson_object_new_string(cmd_str(vrrp->script_backup)));\n\t\tif (vrrp->script_master)\n\t\t\tjson_object_object_add(json_data, \"script_master\",\n\t\t\t\tjson_object_new_string(cmd_str(vrrp->script_master)));\n\t\tif (vrrp->script_fault)\n\t\t\tjson_object_object_add(json_data, \"script_fault\",\n\t\t\t\tjson_object_new_string(cmd_str(vrrp->script_fault)));\n\t\tif (vrrp->script_stop)\n\t\t\tjson_object_object_add(json_data, \"script_stop\",\n\t\t\t\tjson_object_new_string(cmd_str(vrrp->script_stop)));\n\t\tif (vrrp->script)\n\t\t\tjson_object_object_add(json_data, \"script\",\n\t\t\t\tjson_object_new_string(cmd_str(vrrp->script)));\n\t\tif (vrrp->script_master_rx_lower_pri)\n\t\t\tjson_object_object_add(json_data, \"script_master_rx_lower_pri\",\n\t\t\t\tjson_object_new_string(cmd_str(vrrp->script_master_rx_lower_pri)));\n\t\tjson_object_object_add(json_data, \"smtp_alert\",\n\t\t\tjson_object_new_boolean(vrrp->smtp_alert));\n#ifdef _WITH_VRRP_AUTH_\n\t\tif (vrrp->auth_type) {\n\t\t\tjson_object_object_add(json_data, \"auth_type\",\n\t\t\t\tjson_object_new_int(vrrp->auth_type));\n\n\t\t\tif (vrrp->auth_type != VRRP_AUTH_AH) {\n\t\t\t\tchar auth_data[sizeof(vrrp->auth_data) + 1];\n\t\t\t\tmemcpy(auth_data, vrrp->auth_data, sizeof(vrrp->auth_data));\n\t\t\t\tauth_data[sizeof(vrrp->auth_data)] = '\\0';\n\t\t\t\tjson_object_object_add(json_data, \"auth_data\",\n\t\t\t\t\tjson_object_new_string(auth_data));\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tjson_object_object_add(json_data, \"auth_type\",\n\t\t\t\tjson_object_new_int(0));\n#endif\n\n\t\t// Dump stats to json\n\t\tjson_object_object_add(json_stats, \"advert_rcvd\",\n\t\t\tjson_object_new_int64((int64_t)vrrp->stats->advert_rcvd));\n\t\tjson_object_object_add(json_stats, \"advert_sent\",\n\t\t\tjson_object_new_int64(vrrp->stats->advert_sent));\n\t\tjson_object_object_add(json_stats, \"become_master\",\n\t\t\tjson_object_new_int64(vrrp->stats->become_master));\n\t\tjson_object_object_add(json_stats, \"release_master\",\n\t\t\tjson_object_new_int64(vrrp->stats->release_master));\n\t\tjson_object_object_add(json_stats, \"packet_len_err\",\n\t\t\tjson_object_new_int64((int64_t)vrrp->stats->packet_len_err));\n\t\tjson_object_object_add(json_stats, \"advert_interval_err\",\n\t\t\tjson_object_new_int64((int64_t)vrrp->stats->advert_interval_err));\n\t\tjson_object_object_add(json_stats, \"ip_ttl_err\",\n\t\t\tjson_object_new_int64((int64_t)vrrp->stats->ip_ttl_err));\n\t\tjson_object_object_add(json_stats, \"invalid_type_rcvd\",\n\t\t\tjson_object_new_int64((int64_t)vrrp->stats->invalid_type_rcvd));\n\t\tjson_object_object_add(json_stats, \"addr_list_err\",\n\t\t\tjson_object_new_int64((int64_t)vrrp->stats->addr_list_err));\n\t\tjson_object_object_add(json_stats, \"invalid_authtype\",\n\t\t\tjson_object_new_int64(vrrp->stats->invalid_authtype));\n#ifdef _WITH_VRRP_AUTH_\n\t\tjson_object_object_add(json_stats, \"authtype_mismatch\",\n\t\t\tjson_object_new_int64(vrrp->stats->authtype_mismatch));\n\t\tjson_object_object_add(json_stats, \"auth_failure\",\n\t\t\tjson_object_new_int64(vrrp->stats->auth_failure));\n#endif\n\t\tjson_object_object_add(json_stats, \"pri_zero_rcvd\",\n\t\t\tjson_object_new_int64((int64_t)vrrp->stats->pri_zero_rcvd));\n\t\tjson_object_object_add(json_stats, \"pri_zero_sent\",\n\t\t\tjson_object_new_int64((int64_t)vrrp->stats->pri_zero_sent));\n\n\t\t// Add both json_data and json_stats to main instance_json\n\t\tjson_object_object_add(instance_json, \"data\", json_data);\n\t\tjson_object_object_add(instance_json, \"stats\", json_stats);\n\n\t\t// Add instance_json to main array\n\t\tjson_object_array_add(array, instance_json);\n\n\t}\n\tfprintf(file, \"%s\", json_object_to_json_string(array));\n\tfclose(file);\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: set_umask(const char *optarg)\n{\n\tlong umask_long;\n\tmode_t umask_val;\n\tchar *endptr;\n\n\tumask_long = strtoll(optarg, &endptr, 0);\n\n\tif (*endptr || umask_long < 0 || umask_long & ~0777L) {\n\t\tfprintf(stderr, \"Invalid --umask option %s\", optarg);\n\t\treturn;\n\t}\n\n\tumask_val = umask_long & 0777;\n\tumask(umask_val);\n\n\tumask_cmdline = true;\n\n\treturn umask_val;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Fix compile warning introduced in commit c6247a9\n\nCommit c6247a9 - \"Add command line and configuration option to set umask\"\nintroduced a compile warning, although the code would have worked OK.\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\tint exit_code = KEEPALIVED_EXIT_OK;\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/* Set default file creation mask */\n\tumask(022);\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\texit_code = KEEPALIVED_EXIT_NO_CONFIG;\n\t\tgoto end;\n\t}\n\n\tglobal_data = alloc_global_data();\n\tglobal_data->umask = umask_val;\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#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(exit_code);\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: start_bfd_child(void)\n{\n#ifndef _DEBUG_\n\tpid_t pid;\n\tint ret;\n\tchar *syslog_ident;\n\n\t/* Initialize child process */\n\tif (log_file_name)\n\t\tflush_log_file();\n\n\tpid = fork();\n\n\tif (pid < 0) {\n\t\tlog_message(LOG_INFO, \"BFD child process: fork error(%m)\");\n\t\treturn -1;\n\t} else if (pid) {\n\t\tbfd_child = pid;\n\t\tlog_message(LOG_INFO, \"Starting BFD child process, pid=%d\",\n\t\t\t pid);\n\n\t\t/* Start respawning thread */\n\t\tthread_add_child(master, bfd_respawn_thread, NULL,\n\t\t\t\t pid, TIMER_NEVER);\n\t\treturn 0;\n\t}\n\tprctl(PR_SET_PDEATHSIG, SIGTERM);\n\n\tprog_type = PROG_TYPE_BFD;\n\n\t/* Close the read end of the event notification pipes */\n#ifdef _WITH_VRRP_\n\tclose(bfd_vrrp_event_pipe[0]);\n#endif\n#ifdef _WITH_LVS_\n\tclose(bfd_checker_event_pipe[0]);\n#endif\n\n\tinitialise_debug_options();\n\n\tif ((global_data->instance_name\n#if HAVE_DECL_CLONE_NEWNET\n\t\t\t || global_data->network_namespace\n#endif\n\t\t\t\t\t ) &&\n\t (bfd_syslog_ident = make_syslog_ident(PROG_BFD)))\n\t\tsyslog_ident = bfd_syslog_ident;\n\telse\n\t\tsyslog_ident = PROG_BFD;\n\n\t/* Opening local BFD syslog channel */\n\tif (!__test_bit(NO_SYSLOG_BIT, &debug))\n\t\topenlog(syslog_ident, LOG_PID | ((__test_bit(LOG_CONSOLE_BIT, &debug)) ? LOG_CONS : 0)\n\t\t\t\t , (log_facility==LOG_DAEMON) ? LOG_LOCAL2 : log_facility);\n\n\tif (log_file_name)\n\t\topen_log_file(log_file_name,\n\t\t\t\t\"bfd\",\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\n#ifdef _MEM_CHECK_\n\tmem_log_init(PROG_BFD, \"BFD child process\");\n#endif\n\n\tfree_parent_mallocs_startup(true);\n\n\t/* Clear any child finder functions set in parent */\n\tset_child_finder_name(NULL);\n\n\t/* Child process part, write pidfile */\n\tif (!pidfile_write(bfd_pidfile, getpid())) {\n\t\t/* Fatal error */\n\t\tlog_message(LOG_INFO,\n\t\t\t \"BFD child process: cannot write pidfile\");\n\t\texit(0);\n\t}\n\n\t/* Create the new master thread */\n\tthread_destroy_master(master);\n\tmaster = thread_make_master();\n\n\t/* change to / dir */\n\tret = chdir(\"/\");\n\tif (ret < 0) {\n\t\tlog_message(LOG_INFO, \"BFD child process: error chdir\");\n\t}\n\n\t/* Set mask */\n\tumask(0);\n#endif\n\n\t/* If last process died during a reload, we can get there and we\n\t * don't want to loop again, because we're not reloading anymore.\n\t */\n\tUNSET_RELOAD;\n\n#ifndef _DEBUG_\n\t/* Signal handling initialization */\n\tbfd_signal_init();\n#endif\n\n\t/* Start BFD daemon */\n\tstart_bfd(NULL);\n\n#ifdef _DEBUG_\n\treturn 0;\n#else\n\n#ifdef THREAD_DUMP\n\tregister_bfd_thread_addresses();\n#endif\n\n\t/* Launch the scheduling I/O multiplexer */\n\tlaunch_thread_scheduler(master);\n\n#ifdef THREAD_DUMP\n\tderegister_thread_addresses();\n#endif\n\n\t/* Finish BFD daemon process */\n\tstop_bfd(EXIT_SUCCESS);\n\n\t/* unreachable */\n\texit(EXIT_SUCCESS);\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: rf64_read_header (SF_PRIVATE *psf, int *blockalign, int *framesperblock)\n{\tWAVLIKE_PRIVATE\t*wpriv ;\n\tWAV_FMT\t\t*wav_fmt ;\n\tsf_count_t riff_size = 0, frame_count = 0, ds64_datalength = 0 ;\n\tuint32_t marks [2], marker, chunk_size, parsestage = 0 ;\n\tint error, done = 0, format = 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, \"pmmm\", 0, &marker, marks, marks + 1) ;\n\tif (marker != RF64_MARKER || marks [1] != WAVE_MARKER)\n\t\treturn SFE_RF64_NOT_RF64 ;\n\n\tif (marks [0] == FFFF_MARKER)\n\t\tpsf_log_printf (psf, \"%M\\n %M\\n\", RF64_MARKER, WAVE_MARKER) ;\n\telse\n\t\tpsf_log_printf (psf, \"%M : 0x%x (should be 0xFFFFFFFF)\\n %M\\n\", RF64_MARKER, WAVE_MARKER) ;\n\n\twhile (NOT (done))\n\t{\n\t\tmarker = chunk_size = 0 ;\n\t\tpsf_binheader_readf (psf, \"em4\", &marker, &chunk_size) ;\n\n\t\tif (marker == 0)\n\t\t{\tsf_count_t pos = psf_ftell (psf) ;\n\t\t\tpsf_log_printf (psf, \"Have 0 marker at position %D (0x%x).\\n\", pos, pos) ;\n\t\t\tbreak ;\n\t\t\t} ;\n\n\t\tpsf_store_read_chunk_u32 (&psf->rchunks, marker, psf_ftell (psf), chunk_size) ;\n\n\t\tswitch (marker)\n\t\t{\tcase ds64_MARKER :\n\t\t\t\tif (parsestage & HAVE_ds64)\n\t\t\t\t{\tpsf_log_printf (psf, \"*** Second 'ds64' chunk?\\n\") ;\n\t\t\t\t\tbreak ;\n\t\t\t\t\t} ;\n\n\t\t\t\t{\tunsigned int table_len, bytesread ;\n\n\t\t\t\t\t/* Read ds64 sizes (3 8-byte words). */\n\t\t\t\t\tbytesread = psf_binheader_readf (psf, \"888\", &riff_size, &ds64_datalength, &frame_count) ;\n\n\t\t\t\t\t/* Read table length. */\n\t\t\t\t\tbytesread += psf_binheader_readf (psf, \"4\", &table_len) ;\n\t\t\t\t\t/* Skip table for now. (this was \"table_len + 4\", why?) */\n\t\t\t\t\tbytesread += psf_binheader_readf (psf, \"j\", table_len) ;\n\n\t\t\t\t\tif (chunk_size == bytesread)\n\t\t\t\t\t\tpsf_log_printf (psf, \"%M : %u\\n\", marker, chunk_size) ;\n\t\t\t\t\telse if (chunk_size >= bytesread + 4)\n\t\t\t\t\t{\tunsigned int next ;\n\t\t\t\t\t\tpsf_binheader_readf (psf, \"m\", &next) ;\n\t\t\t\t\t\tif (next == fmt_MARKER)\n\t\t\t\t\t\t{\tpsf_log_printf (psf, \"%M : %u (should be %u)\\n\", marker, chunk_size, bytesread) ;\n\t\t\t\t\t\t\tpsf_binheader_readf (psf, \"j\", -4) ;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\tpsf_log_printf (psf, \"%M : %u\\n\", marker, chunk_size) ;\n\t\t\t\t\t\t\tpsf_binheader_readf (psf, \"j\", chunk_size - bytesread - 4) ;\n\t\t\t\t\t\t\t} ;\n\t\t\t\t\t\t} ;\n\n\t\t\t\t\tif (psf->filelength != riff_size + 8)\n\t\t\t\t\t\tpsf_log_printf (psf, \" Riff size : %D (should be %D)\\n\", riff_size, psf->filelength - 8) ;\n\t\t\t\t\telse\n\t\t\t\t\t\tpsf_log_printf (psf, \" Riff size : %D\\n\", riff_size) ;\n\n\t\t\t\t\tpsf_log_printf (psf, \" Data size : %D\\n\", ds64_datalength) ;\n\n\t\t\t\t\tpsf_log_printf (psf, \" Frames : %D\\n\", frame_count) ;\n\t\t\t\t\tpsf_log_printf (psf, \" Table length : %u\\n\", table_len) ;\n\n\t\t\t\t\t} ;\n\t\t\t\tparsestage |= HAVE_ds64 ;\n\t\t\t\tbreak ;\n\n\t\t\tcase fmt_MARKER:\n\t\t\t\t\tpsf_log_printf (psf, \"%M : %u\\n\", marker, chunk_size) ;\n\t\t\t\t\tif ((error = wavlike_read_fmt_chunk (psf, chunk_size)) != 0)\n\t\t\t\t\t\treturn error ;\n\t\t\t\t\tformat = wav_fmt->format ;\n\t\t\t\t\tparsestage |= HAVE_fmt ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase bext_MARKER :\n\t\t\t\t\tif ((error = wavlike_read_bext_chunk (psf, chunk_size)) != 0)\n\t\t\t\t\t\treturn error ;\n\t\t\t\t\tparsestage |= HAVE_bext ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase cart_MARKER :\n\t\t\t\t\tif ((error = wavlike_read_cart_chunk (psf, chunk_size)) != 0)\n\t\t\t\t\t\treturn error ;\n\t\t\t\t\tparsestage |= HAVE_cart ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase INFO_MARKER :\n\t\t\tcase LIST_MARKER :\n\t\t\t\t\tif ((error = wavlike_subchunk_parse (psf, marker, chunk_size)) != 0)\n\t\t\t\t\t\treturn error ;\n\t\t\t\t\tparsestage |= HAVE_other ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase PEAK_MARKER :\n\t\t\t\t\tif ((parsestage & (HAVE_ds64 | HAVE_fmt)) != (HAVE_ds64 | HAVE_fmt))\n\t\t\t\t\t\treturn SFE_RF64_PEAK_B4_FMT ;\n\n\t\t\t\t\tparsestage |= HAVE_PEAK ;\n\n\t\t\t\t\tpsf_log_printf (psf, \"%M : %u\\n\", marker, chunk_size) ;\n\t\t\t\t\tif ((error = wavlike_read_peak_chunk (psf, chunk_size)) != 0)\n\t\t\t\t\t\treturn error ;\n\t\t\t\t\tpsf->peak_info->peak_loc = ((parsestage & HAVE_data) == 0) ? SF_PEAK_START : SF_PEAK_END ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase data_MARKER :\n\t\t\t\t/* see wav for more sophisticated parsing -> implement state machine with parsestage */\n\n\t\t\t\tif (HAVE_CHUNK (HAVE_ds64))\n\t\t\t\t{\tif (chunk_size == 0xffffffff)\n\t\t\t\t\t\tpsf_log_printf (psf, \"%M : 0x%x\\n\", marker, chunk_size) ;\n\t\t\t\t\telse\n\t\t\t\t\t\tpsf_log_printf (psf, \"%M : 0x%x (should be 0xffffffff\\n\", marker, chunk_size) ;\n\t\t\t\t\tpsf->datalength = ds64_datalength ;\n\t\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\tif (chunk_size == 0xffffffff)\n\t\t\t\t\t{\tpsf_log_printf (psf, \"%M : 0x%x\\n\", marker, chunk_size) ;\n\t\t\t\t\t\tpsf_log_printf (psf, \" *** Data length not specified no 'ds64' chunk.\\n\") ;\n\t\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\tpsf_log_printf (psf, \"%M : 0x%x\\n**** Weird, RF64 file without a 'ds64' chunk and no valid 'data' size.\\n\", marker, chunk_size) ;\n\t\t\t\t\t\tpsf->datalength = chunk_size ;\n\t\t\t\t\t\t} ;\n\t\t\t\t\t} ;\n\n\t\t\t\tpsf->dataoffset = psf_ftell (psf) ;\n\n\t\t\t\tif (psf->dataoffset > 0)\n\t\t\t\t{\tif (chunk_size == 0 && riff_size == 8 && psf->filelength > 44)\n\t\t\t\t\t{\tpsf_log_printf (psf, \" *** Looks like a WAV file which wasn't closed properly. Fixing it.\\n\") ;\n\t\t\t\t\t\tpsf->datalength = psf->filelength - psf->dataoffset ;\n\t\t\t\t\t\t} ;\n\n\t\t\t\t\t/* Only set dataend if there really is data at the end. */\n\t\t\t\t\tif (psf->datalength + psf->dataoffset < psf->filelength)\n\t\t\t\t\t\tpsf->dataend = psf->datalength + psf->dataoffset ;\n\n\t\t\t\t\tif (NOT (psf->sf.seekable) || psf->dataoffset < 0)\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, psf->datalength, SEEK_CUR) ;\n\n\t\t\t\t\tif (psf_ftell (psf) != psf->datalength + psf->dataoffset)\n\t\t\t\t\t\tpsf_log_printf (psf, \" *** psf_fseek past end error ***\\n\") ;\n\t\t\t\t\t} ;\n\t\t\t\tbreak ;\n\n\t\t\tcase JUNK_MARKER :\n\t\t\tcase PAD_MARKER :\n\t\t\t\tpsf_log_printf (psf, \"%M : %d\\n\", marker, chunk_size) ;\n\t\t\t\tpsf_binheader_readf (psf, \"j\", chunk_size) ;\n\t\t\t\tbreak ;\n\n\t\t\tdefault :\n\t\t\t\t\tif (chunk_size >= 0xffff0000)\n\t\t\t\t\t{\tpsf_log_printf (psf, \"*** Unknown chunk marker (%X) at position %D with length %u. Exiting parser.\\n\", marker, psf_ftell (psf) - 8, chunk_size) ;\n\t\t\t\t\t\tdone = SF_TRUE ;\n\t\t\t\t\t\tbreak ;\n\t\t\t\t\t\t} ;\n\n\t\t\t\t\tif (isprint ((marker >> 24) & 0xFF) && isprint ((marker >> 16) & 0xFF)\n\t\t\t\t\t\t&& isprint ((marker >> 8) & 0xFF) && isprint (marker & 0xFF))\n\t\t\t\t\t{\tpsf_log_printf (psf, \"*** %M : %d (unknown marker)\\n\", marker, chunk_size) ;\n\t\t\t\t\t\tpsf_binheader_readf (psf, \"j\", chunk_size) ;\n\t\t\t\t\t\tbreak ;\n\t\t\t\t\t\t} ;\n\t\t\t\t\tif (psf_ftell (psf) & 0x03)\n\t\t\t\t\t{\tpsf_log_printf (psf, \" Unknown chunk marker at position 0x%x. Resynching.\\n\", chunk_size - 4) ;\n\t\t\t\t\t\tpsf_binheader_readf (psf, \"j\", -3) ;\n\t\t\t\t\t\tbreak ;\n\t\t\t\t\t\t} ;\n\t\t\t\t\tpsf_log_printf (psf, \"*** Unknown chunk marker (0x%X) at position 0x%X. Exiting parser.\\n\", marker, psf_ftell (psf) - 4) ;\n\t\t\t\t\tdone = SF_TRUE ;\n\t\t\t\t\tbreak ;\n\t\t\t} ;\t/* switch (marker) */\n\n\t\t/* The 'data' chunk, a chunk size of 0xffffffff means that the 'data' chunk size\n\t\t** is actually given by the ds64_datalength field.\n\t\t*/\n\t\tif (marker != data_MARKER && 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_ftell (psf) >= psf->filelength - SIGNED_SIZEOF (marker))\n\t\t{\tpsf_log_printf (psf, \"End\\n\") ;\n\t\t\tbreak ;\n\t\t\t} ;\n\t\t} ;\n\n\tif (psf->dataoffset <= 0)\n\t\treturn SFE_RF64_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\t/* WAVs can be little or big endian */\n\tpsf->endian = psf->rwf_endian ;\n\n\tpsf_fseek (psf, psf->dataoffset, SEEK_SET) ;\n\n\tif (psf->is_pipe == 0)\n\t{\t/*\n\t\t** Check for 'wvpk' at the start of the DATA section. Not able to\n\t\t** handle this.\n\t\t*/\n\t\tpsf_binheader_readf (psf, \"4\", &marker) ;\n\t\tif (marker == wvpk_MARKER || marker == OggS_MARKER)\n\t\t\treturn SFE_WAV_WVPK_DATA ;\n\t\t} ;\n\n\t/* Seek to start of DATA section. */\n\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\tif (frame_count != psf->sf.frames)\n\t\tpsf_log_printf (psf, \"*** Calculated frame count %d does not match value from 'ds64' chunk of %d.\\n\", psf->sf.frames, frame_count) ;\n\n\tswitch (format)\n\t{\n\t\tcase WAVE_FORMAT_EXTENSIBLE :\n\n\t\t\t/* with WAVE_FORMAT_EXTENSIBLE the psf->sf.format field is already set. We just have to set the major to rf64 */\n\t\t\tpsf->sf.format = (psf->sf.format & ~SF_FORMAT_TYPEMASK) | SF_FORMAT_RF64 ;\n\n\t\t\tif (psf->sf.format == (SF_FORMAT_WAVEX | SF_FORMAT_MS_ADPCM))\n\t\t\t{\t*blockalign = wav_fmt->msadpcm.blockalign ;\n\t\t\t\t*framesperblock = wav_fmt->msadpcm.samplesperblock ;\n\t\t\t\t} ;\n\t\t\tbreak ;\n\n\t\tcase WAVE_FORMAT_PCM :\n\t\t\t\t\tpsf->sf.format = SF_FORMAT_RF64 | u_bitwidth_to_subformat (psf->bytewidth * 8) ;\n\t\t\t\t\tbreak ;\n\n\t\tcase WAVE_FORMAT_MULAW :\n\t\tcase IBM_FORMAT_MULAW :\n\t\t\t\t\tpsf->sf.format = (SF_FORMAT_RF64 | SF_FORMAT_ULAW) ;\n\t\t\t\t\tbreak ;\n\n\t\tcase WAVE_FORMAT_ALAW :\n\t\tcase IBM_FORMAT_ALAW :\n\t\t\t\t\tpsf->sf.format = (SF_FORMAT_RF64 | 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_RF64 | 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_RF64 | 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_RF64 | 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_RF64 ;\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\tcase WAVE_FORMAT_G721_ADPCM :\n\t\t\t\t\tpsf->sf.format = SF_FORMAT_RF64 | SF_FORMAT_G721_32 ;\n\t\t\t\t\tbreak ;\n\n\t\tdefault : return SFE_UNIMPLEMENTED ;\n\t\t} ;\n\n\tif (wpriv->fmt_is_broken)\n\t\twavlike_analyze (psf) ;\n\n\t/* Only set the format endian-ness if its non-standard big-endian. */\n\tif (psf->endian == SF_ENDIAN_BIG)\n\t\tpsf->sf.format |= SF_ENDIAN_BIG ;\n\n\treturn 0 ;\n} /* rf64_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_record_hdr(int ifd, void *buffer, struct record_header *record_hdr,\n\t\t struct file_header *file_hdr, int arch_64, int endian_mismatch,\n\t\t int oneof)\n{\n\tint rc;\n\n\tif ((rc = sa_fread(ifd, buffer, (size_t) file_hdr->rec_size, SOFT_SIZE, oneof)) != 0)\n\t\t/* End of sa data file */\n\t\treturn rc;\n\n\t/* Remap record header structure to that expected by current version */\n\tremap_struct(rec_types_nr, file_hdr->rec_types_nr, buffer,\n\t\t file_hdr->rec_size, RECORD_HEADER_SIZE);\n\tmemcpy(record_hdr, buffer, RECORD_HEADER_SIZE);\n\n\t/* Normalize endianness */\n\tif (endian_mismatch) {\n\t\tswap_struct(rec_types_nr, record_hdr, arch_64);\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 int gather_pid_metadata(\n char* context[_CONTEXT_MAX],\n char **comm_fallback,\n struct iovec *iovec, size_t *n_iovec) {\n\n /* We need 27 empty slots in iovec!\n *\n * Note that if we fail on oom later on, we do not roll-back changes to the iovec structure. (It remains valid,\n * with the first n_iovec fields initialized.) */\n\n uid_t owner_uid;\n pid_t pid;\n char *t;\n const char *p;\n int r, signo;\n\n r = parse_pid(context[CONTEXT_PID], &pid);\n if (r < 0)\n return log_error_errno(r, \"Failed to parse PID \\\"%s\\\": %m\", context[CONTEXT_PID]);\n\n r = get_process_comm(pid, &context[CONTEXT_COMM]);\n if (r < 0) {\n log_warning_errno(r, \"Failed to get COMM, falling back to the command line: %m\");\n context[CONTEXT_COMM] = strv_join(comm_fallback, \" \");\n if (!context[CONTEXT_COMM])\n return log_oom();\n }\n\n r = get_process_exe(pid, &context[CONTEXT_EXE]);\n if (r < 0)\n log_warning_errno(r, \"Failed to get EXE, ignoring: %m\");\n\n if (cg_pid_get_unit(pid, &context[CONTEXT_UNIT]) >= 0) {\n if (!is_journald_crash((const char**) context)) {\n /* OK, now we know it's not the journal, hence we can make use of it now. */\n log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);\n log_open();\n }\n\n /* If this is PID 1 disable coredump collection, we'll unlikely be able to process it later on. */\n if (is_pid1_crash((const char**) context)) {\n log_notice(\"Due to PID 1 having crashed coredump collection will now be turned off.\");\n disable_coredumps();\n }\n\n set_iovec_field(iovec, n_iovec, \"COREDUMP_UNIT=\", context[CONTEXT_UNIT]);\n }\n\n if (cg_pid_get_user_unit(pid, &t) >= 0)\n set_iovec_field_free(iovec, n_iovec, \"COREDUMP_USER_UNIT=\", t);\n\n /* The next few are mandatory */\n if (!set_iovec_field(iovec, n_iovec, \"COREDUMP_PID=\", context[CONTEXT_PID]))\n return log_oom();\n\n if (!set_iovec_field(iovec, n_iovec, \"COREDUMP_UID=\", context[CONTEXT_UID]))\n return log_oom();\n\n if (!set_iovec_field(iovec, n_iovec, \"COREDUMP_GID=\", context[CONTEXT_GID]))\n return log_oom();\n\n if (!set_iovec_field(iovec, n_iovec, \"COREDUMP_SIGNAL=\", context[CONTEXT_SIGNAL]))\n return log_oom();\n\n if (!set_iovec_field(iovec, n_iovec, \"COREDUMP_RLIMIT=\", context[CONTEXT_RLIMIT]))\n return log_oom();\n\n if (!set_iovec_field(iovec, n_iovec, \"COREDUMP_HOSTNAME=\", context[CONTEXT_HOSTNAME]))\n return log_oom();\n\n if (!set_iovec_field(iovec, n_iovec, \"COREDUMP_COMM=\", context[CONTEXT_COMM]))\n return log_oom();\n\n if (context[CONTEXT_EXE] &&\n !set_iovec_field(iovec, n_iovec, \"COREDUMP_EXE=\", context[CONTEXT_EXE]))\n return log_oom();\n\n if (sd_pid_get_session(pid, &t) >= 0)\n set_iovec_field_free(iovec, n_iovec, \"COREDUMP_SESSION=\", t);\n\n if (sd_pid_get_owner_uid(pid, &owner_uid) >= 0) {\n r = asprintf(&t, \"COREDUMP_OWNER_UID=\" UID_FMT, owner_uid);\n if (r > 0)\n iovec[(*n_iovec)++] = IOVEC_MAKE_STRING(t);\n }\n\n if (sd_pid_get_slice(pid, &t) >= 0)\n set_iovec_field_free(iovec, n_iovec, \"COREDUMP_SLICE=\", t);\n\n if (get_process_cmdline(pid, 0, false, &t) >= 0)\n set_iovec_field_free(iovec, n_iovec, \"COREDUMP_CMDLINE=\", t);\n\n if (cg_pid_get_path_shifted(pid, NULL, &t) >= 0)\n set_iovec_field_free(iovec, n_iovec, \"COREDUMP_CGROUP=\", t);\n\n if (compose_open_fds(pid, &t) >= 0)\n set_iovec_field_free(iovec, n_iovec, \"COREDUMP_OPEN_FDS=\", t);\n\n p = procfs_file_alloca(pid, \"status\");\n if (read_full_file(p, &t, NULL) >= 0)\n set_iovec_field_free(iovec, n_iovec, \"COREDUMP_PROC_STATUS=\", t);\n\n p = procfs_file_alloca(pid, \"maps\");\n if (read_full_file(p, &t, NULL) >= 0)\n set_iovec_field_free(iovec, n_iovec, \"COREDUMP_PROC_MAPS=\", t);\n\n p = procfs_file_alloca(pid, \"limits\");\n if (read_full_file(p, &t, NULL) >= 0)\n set_iovec_field_free(iovec, n_iovec, \"COREDUMP_PROC_LIMITS=\", t);\n\n p = procfs_file_alloca(pid, \"cgroup\");\n if (read_full_file(p, &t, NULL) >=0)\n set_iovec_field_free(iovec, n_iovec, \"COREDUMP_PROC_CGROUP=\", t);\n\n p = procfs_file_alloca(pid, \"mountinfo\");\n if (read_full_file(p, &t, NULL) >=0)\n set_iovec_field_free(iovec, n_iovec, \"COREDUMP_PROC_MOUNTINFO=\", t);\n\n if (get_process_cwd(pid, &t) >= 0)\n set_iovec_field_free(iovec, n_iovec, \"COREDUMP_CWD=\", t);\n\n if (get_process_root(pid, &t) >= 0) {\n bool proc_self_root_is_slash;\n\n proc_self_root_is_slash = strcmp(t, \"/\") == 0;\n\n set_iovec_field_free(iovec, n_iovec, \"COREDUMP_ROOT=\", t);\n\n /* If the process' root is \"/\", then there is a chance it has\n * mounted own root and hence being containerized. */\n if (proc_self_root_is_slash && get_process_container_parent_cmdline(pid, &t) > 0)\n set_iovec_field_free(iovec, n_iovec, \"COREDUMP_CONTAINER_CMDLINE=\", t);\n }\n\n if (get_process_environ(pid, &t) >= 0)\n set_iovec_field_free(iovec, n_iovec, \"COREDUMP_ENVIRON=\", t);\n\n t = strjoin(\"COREDUMP_TIMESTAMP=\", context[CONTEXT_TIMESTAMP], \"000000\");\n if (t)\n iovec[(*n_iovec)++] = IOVEC_MAKE_STRING(t);\n\n if (safe_atoi(context[CONTEXT_SIGNAL], &signo) >= 0 && SIGNAL_VALID(signo))\n set_iovec_field(iovec, n_iovec, \"COREDUMP_SIGNAL_NAME=SIG\", signal_to_string(signo));\n\n return 0; /* we successfully acquired all metadata */\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: static void test_syslog_parse_identifier(const char* str,\n const char *ident, const char*pid, int ret) {\n const char *buf = str;\n _cleanup_free_ char *ident2 = NULL, *pid2 = NULL;\n int ret2;\n\n ret2 = syslog_parse_identifier(&buf, &ident2, &pid2);\n\n assert_se(ret == ret2);\n assert_se(ident == ident2 || streq_ptr(ident, ident2));\n assert_se(pid == pid2 || streq_ptr(pid, pid2));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'journal: fix syslog_parse_identifier()\n\nFixes #9829.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int iccompareproc(i_ctx_t *i_ctx_p, ref *space, ref *testspace)\n{\n int code1, code2;\n ref ICCdict1, ICCdict2, *tempref1, *tempref2;\n int buff_size;\n\n code1 = array_get(imemory, space, 1, &ICCdict1);\n if (code1 < 0)\n return 0;\n code2 = array_get(imemory, testspace, 1, &ICCdict2);\n if (code2 < 0)\n return 0;\n\n /* As a quick check see if current is same as new */\n if (ICCdict1.value.bytes == ICCdict2.value.bytes)\n return 1;\n\n /* Need to check all the various parts */\n code1 = dict_find_string(&ICCdict1, \"N\", &tempref1);\n code2 = dict_find_string(&ICCdict2, \"N\", &tempref2);\n if (code1 != code2)\n return 0;\n if (tempref1->value.intval != tempref2->value.intval)\n return 0;\n\n if (!comparedictkey(i_ctx_p, &ICCdict1, &ICCdict2, (char *)\"Range\"))\n return 0;\n\n code1 = dict_find_string(&ICCdict1, \"DataSource\", &tempref1);\n if (code1 <= 0)\n return 0;\n code2 = dict_find_string(&ICCdict2, \"DataSource\", &tempref2);\n if (code2 <= 0)\n return 0;\n if (r_size(tempref1) != r_size(tempref2))\n return 0;\n\n buff_size = r_size(tempref1);\n if (memcmp(tempref1->value.const_bytes, tempref2->value.const_bytes, buff_size) == 0)\n return 1;\n else\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: z_jpx_decode(i_ctx_t * i_ctx_p)\n{\n os_ptr op = osp;\n ref *sop = NULL;\n ref *csname = NULL;\n stream_jpxd_state state;\n\n /* it's our responsibility to call set_defaults() */\n state.memory = imemory->non_gc_memory;\n if (s_jpxd_template.set_defaults)\n (*s_jpxd_template.set_defaults)((stream_state *)&state);\n if (r_has_type(op, t_dictionary)) {\n check_dict_read(*op);\n if ( dict_find_string(op, \"Alpha\", &sop) > 0) {\n check_type(*sop, t_boolean);\n if (sop->value.boolval)\n state.alpha = true;\n }\n if ( dict_find_string(op, \"ColorSpace\", &sop) > 0) {\n /* parse the value */\n if (r_is_array(sop)) {\n /* assume it's the first array element */\n csname = sop->value.refs;\n } else if (r_has_type(sop,t_name)) {\n /* use the name directly */\n csname = sop;\n } else {\n dmprintf(imemory, \"warning: JPX ColorSpace value is an unhandled type!\\n\");\n }\n if (csname != NULL) {\n ref sref;\n /* get a reference to the name's string value */\n name_string_ref(imemory, csname, &sref);\n /* request raw index values if the colorspace is /Indexed */\n if (!ISTRCMP(&sref, \"Indexed\"))\n state.colorspace = gs_jpx_cs_indexed;\n /* tell the filter what output we want for other spaces */\n else if (!ISTRCMP(&sref, \"DeviceGray\"))\n state.colorspace = gs_jpx_cs_gray;\n else if (!ISTRCMP(&sref, \"DeviceRGB\"))\n state.colorspace = gs_jpx_cs_rgb;\n else if (!ISTRCMP(&sref, \"DeviceCMYK\"))\n state.colorspace = gs_jpx_cs_cmyk;\n else if (!ISTRCMP(&sref, \"ICCBased\")) {\n /* The second array element should be the profile's\n stream dict */\n ref *csdict = sop->value.refs + 1;\n ref *nref;\n ref altname;\n if (r_is_array(sop) && (r_size(sop) > 1) &&\n r_has_type(csdict, t_dictionary)) {\n check_dict_read(*csdict);\n /* try to look up the alternate space */\n if (dict_find_string(csdict, \"Alternate\", &nref) > 0) {\n name_string_ref(imemory, csname, &altname);\n if (!ISTRCMP(&altname, \"DeviceGray\"))\n state.colorspace = gs_jpx_cs_gray;\n else if (!ISTRCMP(&altname, \"DeviceRGB\"))\n state.colorspace = gs_jpx_cs_rgb;\n else if (!ISTRCMP(&altname, \"DeviceCMYK\"))\n state.colorspace = gs_jpx_cs_cmyk;\n }\n /* else guess based on the number of components */\n if (state.colorspace == gs_jpx_cs_unset &&\n dict_find_string(csdict, \"N\", &nref) > 0) {\n if_debug1m('w', imemory, \"[w] JPX image has an external %\"PRIpsint\n \" channel colorspace\\n\", nref->value.intval);\n switch (nref->value.intval) {\n case 1: state.colorspace = gs_jpx_cs_gray;\n break;\n case 3: state.colorspace = gs_jpx_cs_rgb;\n break;\n case 4: state.colorspace = gs_jpx_cs_cmyk;\n break;\n }\n }\n }\n }\n } else {\n if_debug0m('w', imemory, \"[w] Couldn't read JPX ColorSpace key!\\n\");\n }\n }\n }\n\n /* we pass npop=0, since we've no arguments left to consume */\n /* we pass 0 instead of the usual rspace(sop) which will allocate storage\n for filter state from the same memory pool as the stream it's coding.\n this causes no trouble because we maintain no pointers */\n return filter_read(i_ctx_p, 0, &s_jpxd_template,\n (stream_state *) & state, 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: gs_pattern2_set_color(const gs_client_color * pcc, gs_gstate * pgs)\n{\n gs_pattern2_instance_t * pinst = (gs_pattern2_instance_t *)pcc->pattern;\n gs_color_space * pcs = pinst->templat.Shading->params.ColorSpace;\n int code;\n uchar k, num_comps;\n\n pinst->saved->overprint_mode = pgs->overprint_mode;\n pinst->saved->overprint = pgs->overprint;\n \n num_comps = pgs->device->color_info.num_components;\n for (k = 0; k < num_comps; k++) {\n pgs->color_component_map.color_map[k] = \n pinst->saved->color_component_map.color_map[k];\n }\n code = pcs->type->set_overprint(pcs, pgs);\n return code;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-704'], 'message': 'PS interpreter - check the Implementation of a Pattern before use\n\nBug #700141 \"Type confusion in setpattern\"\n\nAs the bug thread says, we were not checking that the Implementation\nof a pattern dictionary was a structure type, leading to a crash when\nwe tried to treat it as one.\n\nHere we make the st_pattern1_instance and st_pattern2_instance\nstructures public definitions and in zsetcolor we check the object\nstored under the Implementation key in the supplied dictionary to see if\nits a t_struct or t_astruct type, and if it is that its a\nst_pattern1_instance or st_pattern2_instance structure.\n\nIf either check fails we throw a typecheck error.\n\nWe need to make the st_pattern1_instance and st_pattern2_instance\ndefinitions public as they are defined in the graphics library and we\nneed to check in the interpreter.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int crypto_report_akcipher(struct sk_buff *skb, struct crypto_alg *alg)\n{\n\tstruct crypto_report_akcipher rakcipher;\n\n\tstrlcpy(rakcipher.type, \"akcipher\", sizeof(rakcipher.type));\n\n\tif (nla_put(skb, CRYPTOCFGA_REPORT_AKCIPHER,\n\t\t sizeof(struct crypto_report_akcipher), &rakcipher))\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: sg_read(struct file *filp, char __user *buf, size_t count, loff_t * ppos)\n{\n\tSg_device *sdp;\n\tSg_fd *sfp;\n\tSg_request *srp;\n\tint req_pack_id = -1;\n\tsg_io_hdr_t *hp;\n\tstruct sg_header *old_hdr = NULL;\n\tint retval = 0;\n\n\tif ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))\n\t\treturn -ENXIO;\n\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,\n\t\t\t\t \"sg_read: count=%d\\n\", (int) count));\n\n\tif (!access_ok(VERIFY_WRITE, buf, count))\n\t\treturn -EFAULT;\n\tif (sfp->force_packid && (count >= SZ_SG_HEADER)) {\n\t\told_hdr = kmalloc(SZ_SG_HEADER, GFP_KERNEL);\n\t\tif (!old_hdr)\n\t\t\treturn -ENOMEM;\n\t\tif (__copy_from_user(old_hdr, buf, SZ_SG_HEADER)) {\n\t\t\tretval = -EFAULT;\n\t\t\tgoto free_old_hdr;\n\t\t}\n\t\tif (old_hdr->reply_len < 0) {\n\t\t\tif (count >= SZ_SG_IO_HDR) {\n\t\t\t\tsg_io_hdr_t *new_hdr;\n\t\t\t\tnew_hdr = kmalloc(SZ_SG_IO_HDR, GFP_KERNEL);\n\t\t\t\tif (!new_hdr) {\n\t\t\t\t\tretval = -ENOMEM;\n\t\t\t\t\tgoto free_old_hdr;\n\t\t\t\t}\n\t\t\t\tretval =__copy_from_user\n\t\t\t\t (new_hdr, buf, SZ_SG_IO_HDR);\n\t\t\t\treq_pack_id = new_hdr->pack_id;\n\t\t\t\tkfree(new_hdr);\n\t\t\t\tif (retval) {\n\t\t\t\t\tretval = -EFAULT;\n\t\t\t\t\tgoto free_old_hdr;\n\t\t\t\t}\n\t\t\t}\n\t\t} else\n\t\t\treq_pack_id = old_hdr->pack_id;\n\t}\n\tsrp = sg_get_rq_mark(sfp, req_pack_id);\n\tif (!srp) {\t\t/* now wait on packet to arrive */\n\t\tif (atomic_read(&sdp->detaching)) {\n\t\t\tretval = -ENODEV;\n\t\t\tgoto free_old_hdr;\n\t\t}\n\t\tif (filp->f_flags & O_NONBLOCK) {\n\t\t\tretval = -EAGAIN;\n\t\t\tgoto free_old_hdr;\n\t\t}\n\t\tretval = wait_event_interruptible(sfp->read_wait,\n\t\t\t(atomic_read(&sdp->detaching) ||\n\t\t\t(srp = sg_get_rq_mark(sfp, req_pack_id))));\n\t\tif (atomic_read(&sdp->detaching)) {\n\t\t\tretval = -ENODEV;\n\t\t\tgoto free_old_hdr;\n\t\t}\n\t\tif (retval) {\n\t\t\t/* -ERESTARTSYS as signal hit process */\n\t\t\tgoto free_old_hdr;\n\t\t}\n\t}\n\tif (srp->header.interface_id != '\\0') {\n\t\tretval = sg_new_read(sfp, buf, count, srp);\n\t\tgoto free_old_hdr;\n\t}\n\n\thp = &srp->header;\n\tif (old_hdr == NULL) {\n\t\told_hdr = kmalloc(SZ_SG_HEADER, GFP_KERNEL);\n\t\tif (! old_hdr) {\n\t\t\tretval = -ENOMEM;\n\t\t\tgoto free_old_hdr;\n\t\t}\n\t}\n\tmemset(old_hdr, 0, SZ_SG_HEADER);\n\told_hdr->reply_len = (int) hp->timeout;\n\told_hdr->pack_len = old_hdr->reply_len; /* old, strange behaviour */\n\told_hdr->pack_id = hp->pack_id;\n\told_hdr->twelve_byte =\n\t ((srp->data.cmd_opcode >= 0xc0) && (12 == hp->cmd_len)) ? 1 : 0;\n\told_hdr->target_status = hp->masked_status;\n\told_hdr->host_status = hp->host_status;\n\told_hdr->driver_status = hp->driver_status;\n\tif ((CHECK_CONDITION & hp->masked_status) ||\n\t (DRIVER_SENSE & hp->driver_status))\n\t\tmemcpy(old_hdr->sense_buffer, srp->sense_b,\n\t\t sizeof (old_hdr->sense_buffer));\n\tswitch (hp->host_status) {\n\t/* This setup of 'result' is for backward compatibility and is best\n\t ignored by the user who should use target, host + driver status */\n\tcase DID_OK:\n\tcase DID_PASSTHROUGH:\n\tcase DID_SOFT_ERROR:\n\t\told_hdr->result = 0;\n\t\tbreak;\n\tcase DID_NO_CONNECT:\n\tcase DID_BUS_BUSY:\n\tcase DID_TIME_OUT:\n\t\told_hdr->result = EBUSY;\n\t\tbreak;\n\tcase DID_BAD_TARGET:\n\tcase DID_ABORT:\n\tcase DID_PARITY:\n\tcase DID_RESET:\n\tcase DID_BAD_INTR:\n\t\told_hdr->result = EIO;\n\t\tbreak;\n\tcase DID_ERROR:\n\t\told_hdr->result = (srp->sense_b[0] == 0 && \n\t\t\t\t hp->masked_status == GOOD) ? 0 : EIO;\n\t\tbreak;\n\tdefault:\n\t\told_hdr->result = EIO;\n\t\tbreak;\n\t}\n\n\t/* Now copy the result back to the user buffer. */\n\tif (count >= SZ_SG_HEADER) {\n\t\tif (__copy_to_user(buf, old_hdr, SZ_SG_HEADER)) {\n\t\t\tretval = -EFAULT;\n\t\t\tgoto free_old_hdr;\n\t\t}\n\t\tbuf += SZ_SG_HEADER;\n\t\tif (count > old_hdr->reply_len)\n\t\t\tcount = old_hdr->reply_len;\n\t\tif (count > SZ_SG_HEADER) {\n\t\t\tif (sg_read_oxfer(srp, buf, count - SZ_SG_HEADER)) {\n\t\t\t\tretval = -EFAULT;\n\t\t\t\tgoto free_old_hdr;\n\t\t\t}\n\t\t}\n\t} else\n\t\tcount = (old_hdr->result == 0) ? 0 : -EIO;\n\tsg_finish_rem_req(srp);\n\tsg_remove_request(sfp, srp);\n\tretval = count;\nfree_old_hdr:\n\tkfree(old_hdr);\n\treturn retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-732'], 'message': 'scsi: sg: mitigate read/write abuse\n\nAs Al Viro noted in commit 128394eff343 (\"sg_write()/bsg_write() is not fit\nto be called under KERNEL_DS\"), sg improperly accesses userspace memory\noutside the provided buffer, permitting kernel memory corruption via\nsplice(). But it doesn't just do it on ->write(), also on ->read().\n\nAs a band-aid, make sure that the ->read() and ->write() handlers can not\nbe called in weird contexts (kernel context or credentials different from\nfile opener), like for ib_safe_file_access().\n\nIf someone needs to use these interfaces from different security contexts,\na new interface should be written that goes through the ->ioctl() handler.\n\nI've mostly copypasted ib_safe_file_access() over as sg_safe_file_access()\nbecause I couldn't find a good common header - please tell me if you know a\nbetter way.\n\n[mkp: s/_safe_/_check_/]\n\nFixes: 1da177e4c3f4 (\"Linux-2.6.12-rc2\")\nCc: \nSigned-off-by: Jann Horn \nAcked-by: Douglas Gilbert \nSigned-off-by: Martin K. Petersen '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: CloseUndoneFileDownload(rfbClientPtr cl, rfbTightClientPtr rtcp)\n{\n\tif(cl == NULL)\n\t\treturn;\n\t\n\tif(rtcp->rcft.rcfd.downloadInProgress == TRUE) {\n\t\trtcp->rcft.rcfd.downloadInProgress = FALSE;\n\n\t\tif(rtcp->rcft.rcfd.downloadFD != -1) {\t\t\t\n\t\t\tclose(rtcp->rcft.rcfd.downloadFD);\n\t\t\trtcp->rcft.rcfd.downloadFD = -1;\n\t\t}\n\t\tmemset(rtcp->rcft.rcfd.fName, 0 , PATH_MAX);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'tightvnc-filetransfer: wait for download thread end in CloseUndoneFileDownload()\n\n...and use it when deregistering the file transfer extension.\n\nCloses #242'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int main(int argc,char** argv)\n{\n char *repeaterHost;\n int repeaterPort, sock;\n char id[250];\n rfbClientPtr cl;\n\n int i,j;\n uint16_t* f;\n\n /* Parse command-line arguments */\n if (argc < 3) {\n fprintf(stderr,\n \"Usage: %s []\\n\", argv[0]);\n exit(1);\n }\n snprintf(id, sizeof(id) - 1, \"ID:%s\", argv[1]);\n repeaterHost = argv[2];\n repeaterPort = argc < 4 ? 5500 : atoi(argv[3]);\n\n /* The initialization is identical to simple15.c */\n rfbScreenInfoPtr server=rfbGetScreen(&argc,argv,400,300,5,3,2);\n if(!server)\n return 0;\n server->frameBuffer=(char*)malloc(400*300*2);\n f=(uint16_t*)server->frameBuffer;\n for(j=0;j<300;j++)\n for(i=0;i<400;i++)\n f[j*400+i]=/* red */ ((j*32/300) << 10) |\n\t\t /* green */ (((j+400-i)*32/700) << 5) |\n\t\t /* blue */ ((i*32/400));\n\n /* Now for the repeater-specific part: */\n server->port = -1; /* do not listen on any port */\n server->ipv6port = -1; /* do not listen on any port */\n\n sock = rfbConnectToTcpAddr(repeaterHost, repeaterPort);\n if (sock < 0) {\n perror(\"connect to repeater\");\n return 1;\n }\n if (write(sock, id, sizeof(id)) != sizeof(id)) {\n perror(\"writing id\");\n return 1;\n }\n cl = rfbNewClient(server, sock);\n if (!cl) {\n perror(\"new client\");\n return 1;\n }\n cl->reverseConnection = 0;\n cl->clientGoneHook = clientGone;\n\n /* Run the server */\n rfbInitServer(server);\n rfbRunEventLoop(server,-1,FALSE);\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-665'], 'message': 'When connecting to a repeater, only send initialised string\n\nCloses #253'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void CLASS nikon_coolscan_load_raw()\n{\n int bufsize = width*3*tiff_bps/8;\n if(tiff_bps <= 8)\n gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,255);\n else\n gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,65535);\n fseek (ifp, data_offset, SEEK_SET);\n unsigned char *buf = (unsigned char*)malloc(bufsize);\n unsigned short *ubuf = (unsigned short *)buf;\n for(int row = 0; row < raw_height; row++)\n {\n int red = fread (buf, 1, bufsize, ifp);\n unsigned short (*ip)[4] = (unsigned short (*)[4]) image + row*width;\n if(tiff_bps <= 8)\n for(int col=0; col \"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: print_help (void)\n{\n#ifndef TESTING\n /* We split the help text this way to ease translation of individual\n entries. */\n static const char *help[] = {\n \"\\n\",\n N_(\"\\\nMandatory arguments to long options are mandatory for short options too.\\n\\n\"),\n N_(\"\\\nStartup:\\n\"),\n N_(\"\\\n -V, --version display the version of Wget and exit\\n\"),\n N_(\"\\\n -h, --help print this help\\n\"),\n N_(\"\\\n -b, --background go to background after startup\\n\"),\n N_(\"\\\n -e, --execute=COMMAND execute a `.wgetrc'-style command\\n\"),\n \"\\n\",\n\n N_(\"\\\nLogging and input file:\\n\"),\n N_(\"\\\n -o, --output-file=FILE log messages to FILE\\n\"),\n N_(\"\\\n -a, --append-output=FILE append messages to FILE\\n\"),\n#ifdef ENABLE_DEBUG\n N_(\"\\\n -d, --debug print lots of debugging information\\n\"),\n#endif\n#ifdef USE_WATT32\n N_(\"\\\n --wdebug print Watt-32 debug output\\n\"),\n#endif\n N_(\"\\\n -q, --quiet quiet (no output)\\n\"),\n N_(\"\\\n -v, --verbose be verbose (this is the default)\\n\"),\n N_(\"\\\n -nv, --no-verbose turn off verboseness, without being quiet\\n\"),\n N_(\"\\\n --report-speed=TYPE output bandwidth as TYPE. TYPE can be bits\\n\"),\n N_(\"\\\n -i, --input-file=FILE download URLs found in local or external FILE\\n\"),\n#ifdef HAVE_METALINK\n N_(\"\\\n --input-metalink=FILE download files covered in local Metalink FILE\\n\"),\n#endif\n N_(\"\\\n -F, --force-html treat input file as HTML\\n\"),\n N_(\"\\\n -B, --base=URL resolves HTML input-file links (-i -F)\\n\\\n relative to URL\\n\"),\n N_(\"\\\n --config=FILE specify config file to use\\n\"),\n N_(\"\\\n --no-config do not read any config file\\n\"),\n N_(\"\\\n --rejected-log=FILE log reasons for URL rejection to FILE\\n\"),\n \"\\n\",\n\n N_(\"\\\nDownload:\\n\"),\n N_(\"\\\n -t, --tries=NUMBER set number of retries to NUMBER (0 unlimits)\\n\"),\n N_(\"\\\n --retry-connrefused retry even if connection is refused\\n\"),\n N_(\"\\\n --retry-on-http-error=ERRORS comma-separated list of HTTP errors to retry\\n\"),\n N_(\"\\\n -O, --output-document=FILE write documents to FILE\\n\"),\n N_(\"\\\n -nc, --no-clobber skip downloads that would download to\\n\\\n existing files (overwriting them)\\n\"),\n N_(\"\\\n --no-netrc don't try to obtain credentials from .netrc\\n\"),\n N_(\"\\\n -c, --continue resume getting a partially-downloaded file\\n\"),\n N_(\"\\\n --start-pos=OFFSET start downloading from zero-based position OFFSET\\n\"),\n N_(\"\\\n --progress=TYPE select progress gauge type\\n\"),\n N_(\"\\\n --show-progress display the progress bar in any verbosity mode\\n\"),\n N_(\"\\\n -N, --timestamping don't re-retrieve files unless newer than\\n\\\n local\\n\"),\n N_(\"\\\n --no-if-modified-since don't use conditional if-modified-since get\\n\\\n requests in timestamping mode\\n\"),\n N_(\"\\\n --no-use-server-timestamps don't set the local file's timestamp by\\n\\\n the one on the server\\n\"),\n N_(\"\\\n -S, --server-response print server response\\n\"),\n N_(\"\\\n --spider don't download anything\\n\"),\n N_(\"\\\n -T, --timeout=SECONDS set all timeout values to SECONDS\\n\"),\n#ifdef HAVE_LIBCARES\n N_(\"\\\n --dns-servers=ADDRESSES list of DNS servers to query (comma separated)\\n\"),\n N_(\"\\\n --bind-dns-address=ADDRESS bind DNS resolver to ADDRESS (hostname or IP) on local host\\n\"),\n#endif\n N_(\"\\\n --dns-timeout=SECS set the DNS lookup timeout to SECS\\n\"),\n N_(\"\\\n --connect-timeout=SECS set the connect timeout to SECS\\n\"),\n N_(\"\\\n --read-timeout=SECS set the read timeout to SECS\\n\"),\n N_(\"\\\n -w, --wait=SECONDS wait SECONDS between retrievals\\n\"),\n N_(\"\\\n --waitretry=SECONDS wait 1..SECONDS between retries of a retrieval\\n\"),\n N_(\"\\\n --random-wait wait from 0.5*WAIT...1.5*WAIT secs between retrievals\\n\"),\n N_(\"\\\n --no-proxy explicitly turn off proxy\\n\"),\n N_(\"\\\n -Q, --quota=NUMBER set retrieval quota to NUMBER\\n\"),\n N_(\"\\\n --bind-address=ADDRESS bind to ADDRESS (hostname or IP) on local host\\n\"),\n N_(\"\\\n --limit-rate=RATE limit download rate to RATE\\n\"),\n N_(\"\\\n --no-dns-cache disable caching DNS lookups\\n\"),\n N_(\"\\\n --restrict-file-names=OS restrict chars in file names to ones OS allows\\n\"),\n N_(\"\\\n --ignore-case ignore case when matching files/directories\\n\"),\n#ifdef ENABLE_IPV6\n N_(\"\\\n -4, --inet4-only connect only to IPv4 addresses\\n\"),\n N_(\"\\\n -6, --inet6-only connect only to IPv6 addresses\\n\"),\n N_(\"\\\n --prefer-family=FAMILY connect first to addresses of specified family,\\n\\\n one of IPv6, IPv4, or none\\n\"),\n#endif\n N_(\"\\\n --user=USER set both ftp and http user to USER\\n\"),\n N_(\"\\\n --password=PASS set both ftp and http password to PASS\\n\"),\n N_(\"\\\n --ask-password prompt for passwords\\n\"),\n N_(\"\\\n --use-askpass=COMMAND specify credential handler for requesting \\n\\\n username and password. If no COMMAND is \\n\\\n specified the WGET_ASKPASS or the SSH_ASKPASS \\n\\\n environment variable is used.\\n\"),\n N_(\"\\\n --no-iri turn off IRI support\\n\"),\n N_(\"\\\n --local-encoding=ENC use ENC as the local encoding for IRIs\\n\"),\n N_(\"\\\n --remote-encoding=ENC use ENC as the default remote encoding\\n\"),\n N_(\"\\\n --unlink remove file before clobber\\n\"),\n#ifdef HAVE_METALINK\n N_(\"\\\n --keep-badhash keep files with checksum mismatch (append .badhash)\\n\"),\n N_(\"\\\n --metalink-index=NUMBER Metalink application/metalink4+xml metaurl ordinal NUMBER\\n\"),\n N_(\"\\\n --metalink-over-http use Metalink metadata from HTTP response headers\\n\"),\n N_(\"\\\n --preferred-location preferred location for Metalink resources\\n\"),\n#endif\n#ifdef ENABLE_XATTR\n N_(\"\\\n --no-xattr turn off storage of metadata in extended file attributes\\n\"),\n#endif\n \"\\n\",\n\n N_(\"\\\nDirectories:\\n\"),\n N_(\"\\\n -nd, --no-directories don't create directories\\n\"),\n N_(\"\\\n -x, --force-directories force creation of directories\\n\"),\n N_(\"\\\n -nH, --no-host-directories don't create host directories\\n\"),\n N_(\"\\\n --protocol-directories use protocol name in directories\\n\"),\n N_(\"\\\n -P, --directory-prefix=PREFIX save files to PREFIX/..\\n\"),\n N_(\"\\\n --cut-dirs=NUMBER ignore NUMBER remote directory components\\n\"),\n \"\\n\",\n\n N_(\"\\\nHTTP options:\\n\"),\n N_(\"\\\n --http-user=USER set http user to USER\\n\"),\n N_(\"\\\n --http-password=PASS set http password to PASS\\n\"),\n N_(\"\\\n --no-cache disallow server-cached data\\n\"),\n N_ (\"\\\n --default-page=NAME change the default page name (normally\\n\\\n this is 'index.html'.)\\n\"),\n N_(\"\\\n -E, --adjust-extension save HTML/CSS documents with proper extensions\\n\"),\n N_(\"\\\n --ignore-length ignore 'Content-Length' header field\\n\"),\n N_(\"\\\n --header=STRING insert STRING among the headers\\n\"),\n#ifdef HAVE_LIBZ\n N_(\"\\\n --compression=TYPE choose compression, one of auto, gzip and none. (default: none)\\n\"),\n#endif\n N_(\"\\\n --max-redirect maximum redirections allowed per page\\n\"),\n N_(\"\\\n --proxy-user=USER set USER as proxy username\\n\"),\n N_(\"\\\n --proxy-password=PASS set PASS as proxy password\\n\"),\n N_(\"\\\n --referer=URL include 'Referer: URL' header in HTTP request\\n\"),\n N_(\"\\\n --save-headers save the HTTP headers to file\\n\"),\n N_(\"\\\n -U, --user-agent=AGENT identify as AGENT instead of Wget/VERSION\\n\"),\n N_(\"\\\n --no-http-keep-alive disable HTTP keep-alive (persistent connections)\\n\"),\n N_(\"\\\n --no-cookies don't use cookies\\n\"),\n N_(\"\\\n --load-cookies=FILE load cookies from FILE before session\\n\"),\n N_(\"\\\n --save-cookies=FILE save cookies to FILE after session\\n\"),\n N_(\"\\\n --keep-session-cookies load and save session (non-permanent) cookies\\n\"),\n N_(\"\\\n --post-data=STRING use the POST method; send STRING as the data\\n\"),\n N_(\"\\\n --post-file=FILE use the POST method; send contents of FILE\\n\"),\n N_(\"\\\n --method=HTTPMethod use method \\\"HTTPMethod\\\" in the request\\n\"),\n N_(\"\\\n --body-data=STRING send STRING as data. --method MUST be set\\n\"),\n N_(\"\\\n --body-file=FILE send contents of FILE. --method MUST be set\\n\"),\n N_(\"\\\n --content-disposition honor the Content-Disposition header when\\n\\\n choosing local file names (EXPERIMENTAL)\\n\"),\n N_(\"\\\n --content-on-error output the received content on server errors\\n\"),\n N_(\"\\\n --auth-no-challenge send Basic HTTP authentication information\\n\\\n without first waiting for the server's\\n\\\n challenge\\n\"),\n \"\\n\",\n\n#ifdef HAVE_SSL\n N_(\"\\\nHTTPS (SSL/TLS) options:\\n\"),\n N_(\"\\\n --secure-protocol=PR choose secure protocol, one of auto, SSLv2,\\n\\\n SSLv3, TLSv1, TLSv1_1, TLSv1_2 and PFS\\n\"),\n N_(\"\\\n --https-only only follow secure HTTPS links\\n\"),\n N_(\"\\\n --no-check-certificate don't validate the server's certificate\\n\"),\n N_(\"\\\n --certificate=FILE client certificate file\\n\"),\n N_(\"\\\n --certificate-type=TYPE client certificate type, PEM or DER\\n\"),\n N_(\"\\\n --private-key=FILE private key file\\n\"),\n N_(\"\\\n --private-key-type=TYPE private key type, PEM or DER\\n\"),\n N_(\"\\\n --ca-certificate=FILE file with the bundle of CAs\\n\"),\n N_(\"\\\n --ca-directory=DIR directory where hash list of CAs is stored\\n\"),\n N_(\"\\\n --crl-file=FILE file with bundle of CRLs\\n\"),\n N_(\"\\\n --pinnedpubkey=FILE/HASHES Public key (PEM/DER) file, or any number\\n\\\n of base64 encoded sha256 hashes preceded by\\n\\\n \\'sha256//\\' and separated by \\';\\', to verify\\n\\\n peer against\\n\"),\n#if defined(HAVE_LIBSSL) || defined(HAVE_LIBSSL32)\n N_(\"\\\n --random-file=FILE file with random data for seeding the SSL PRNG\\n\"),\n#endif\n#if (defined(HAVE_LIBSSL) || defined(HAVE_LIBSSL32)) && defined(HAVE_RAND_EGD)\n N_(\"\\\n --egd-file=FILE file naming the EGD socket with random data\\n\"),\n#endif\n \"\\n\",\n N_(\"\\\n --ciphers=STR Set the priority string (GnuTLS) or cipher list string (OpenSSL) directly.\\n\\\n Use with care. This option overrides --secure-protocol.\\n\\\n The format and syntax of this string depend on the specific SSL/TLS engine.\\n\"),\n#endif /* HAVE_SSL */\n\n#ifdef HAVE_HSTS\n N_(\"\\\nHSTS options:\\n\"),\n N_(\"\\\n --no-hsts disable HSTS\\n\"),\n N_(\"\\\n --hsts-file path of HSTS database (will override default)\\n\"),\n \"\\n\",\n#endif\n\n N_(\"\\\nFTP options:\\n\"),\n#ifdef __VMS\n N_(\"\\\n --ftp-stmlf use Stream_LF format for all binary FTP files\\n\"),\n#endif /* def __VMS */\n N_(\"\\\n --ftp-user=USER set ftp user to USER\\n\"),\n N_(\"\\\n --ftp-password=PASS set ftp password to PASS\\n\"),\n N_(\"\\\n --no-remove-listing don't remove '.listing' files\\n\"),\n N_(\"\\\n --no-glob turn off FTP file name globbing\\n\"),\n N_(\"\\\n --no-passive-ftp disable the \\\"passive\\\" transfer mode\\n\"),\n N_(\"\\\n --preserve-permissions preserve remote file permissions\\n\"),\n N_(\"\\\n --retr-symlinks when recursing, get linked-to files (not dir)\\n\"),\n \"\\n\",\n\n#ifdef HAVE_SSL\n N_(\"\\\nFTPS options:\\n\"),\n N_(\"\\\n --ftps-implicit use implicit FTPS (default port is 990)\\n\"),\n N_(\"\\\n --ftps-resume-ssl resume the SSL/TLS session started in the control connection when\\n\"\n \" opening a data connection\\n\"),\n N_(\"\\\n --ftps-clear-data-connection cipher the control channel only; all the data will be in plaintext\\n\"),\n N_(\"\\\n --ftps-fallback-to-ftp fall back to FTP if FTPS is not supported in the target server\\n\"),\n#endif\n\n N_(\"\\\nWARC options:\\n\"),\n N_(\"\\\n --warc-file=FILENAME save request/response data to a .warc.gz file\\n\"),\n N_(\"\\\n --warc-header=STRING insert STRING into the warcinfo record\\n\"),\n N_(\"\\\n --warc-max-size=NUMBER set maximum size of WARC files to NUMBER\\n\"),\n N_(\"\\\n --warc-cdx write CDX index files\\n\"),\n N_(\"\\\n --warc-dedup=FILENAME do not store records listed in this CDX file\\n\"),\n#ifdef HAVE_LIBZ\n N_(\"\\\n --no-warc-compression do not compress WARC files with GZIP\\n\"),\n#endif\n N_(\"\\\n --no-warc-digests do not calculate SHA1 digests\\n\"),\n N_(\"\\\n --no-warc-keep-log do not store the log file in a WARC record\\n\"),\n N_(\"\\\n --warc-tempdir=DIRECTORY location for temporary files created by the\\n\\\n WARC writer\\n\"),\n \"\\n\",\n\n N_(\"\\\nRecursive download:\\n\"),\n N_(\"\\\n -r, --recursive specify recursive download\\n\"),\n N_(\"\\\n -l, --level=NUMBER maximum recursion depth (inf or 0 for infinite)\\n\"),\n N_(\"\\\n --delete-after delete files locally after downloading them\\n\"),\n N_(\"\\\n -k, --convert-links make links in downloaded HTML or CSS point to\\n\\\n local files\\n\"),\n N_(\"\\\n --convert-file-only convert the file part of the URLs only (usually known as the basename)\\n\"),\n N_(\"\\\n --backups=N before writing file X, rotate up to N backup files\\n\"),\n\n#ifdef __VMS\n N_(\"\\\n -K, --backup-converted before converting file X, back up as X_orig\\n\"),\n#else /* def __VMS */\n N_(\"\\\n -K, --backup-converted before converting file X, back up as X.orig\\n\"),\n#endif /* def __VMS [else] */\n N_(\"\\\n -m, --mirror shortcut for -N -r -l inf --no-remove-listing\\n\"),\n N_(\"\\\n -p, --page-requisites get all images, etc. needed to display HTML page\\n\"),\n N_(\"\\\n --strict-comments turn on strict (SGML) handling of HTML comments\\n\"),\n \"\\n\",\n\n N_(\"\\\nRecursive accept/reject:\\n\"),\n N_(\"\\\n -A, --accept=LIST comma-separated list of accepted extensions\\n\"),\n N_(\"\\\n -R, --reject=LIST comma-separated list of rejected extensions\\n\"),\n N_(\"\\\n --accept-regex=REGEX regex matching accepted URLs\\n\"),\n N_(\"\\\n --reject-regex=REGEX regex matching rejected URLs\\n\"),\n#if defined HAVE_LIBPCRE || defined HAVE_LIBPCRE2\n N_(\"\\\n --regex-type=TYPE regex type (posix|pcre)\\n\"),\n#else\n N_(\"\\\n --regex-type=TYPE regex type (posix)\\n\"),\n#endif\n N_(\"\\\n -D, --domains=LIST comma-separated list of accepted domains\\n\"),\n N_(\"\\\n --exclude-domains=LIST comma-separated list of rejected domains\\n\"),\n N_(\"\\\n --follow-ftp follow FTP links from HTML documents\\n\"),\n N_(\"\\\n --follow-tags=LIST comma-separated list of followed HTML tags\\n\"),\n N_(\"\\\n --ignore-tags=LIST comma-separated list of ignored HTML tags\\n\"),\n N_(\"\\\n -H, --span-hosts go to foreign hosts when recursive\\n\"),\n N_(\"\\\n -L, --relative follow relative links only\\n\"),\n N_(\"\\\n -I, --include-directories=LIST list of allowed directories\\n\"),\n N_(\"\\\n --trust-server-names use the name specified by the redirection\\n\\\n URL's last component\\n\"),\n N_(\"\\\n -X, --exclude-directories=LIST list of excluded directories\\n\"),\n N_(\"\\\n -np, --no-parent don't ascend to the parent directory\\n\"),\n \"\\n\",\n N_(\"Email bug reports, questions, discussions to \\n\"),\n N_(\"and/or open issues at https://savannah.gnu.org/bugs/?func=additem&group=wget.\\n\")\n };\n\n size_t i;\n\n if (printf (_(\"GNU Wget %s, a non-interactive network retriever.\\n\"),\n version_string) < 0)\n exit (WGET_EXIT_IO_FAIL);\n if (print_usage (0) < 0)\n exit (WGET_EXIT_IO_FAIL);\n\n for (i = 0; i < countof (help); i++)\n if (fputs (_(help[i]), stdout) < 0)\n exit (WGET_EXIT_IO_FAIL);\n#endif /* TESTING */\n exit (WGET_EXIT_SUCCESS);\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 h2c_decode_headers(struct h2c *h2c, struct buffer *rxbuf, uint32_t *flags)\n{\n\tconst uint8_t *hdrs = (uint8_t *)b_head(&h2c->dbuf);\n\tstruct buffer *tmp = get_trash_chunk();\n\tstruct http_hdr list[MAX_HTTP_HDR * 2];\n\tstruct buffer *copy = NULL;\n\tunsigned int msgf;\n\tstruct htx *htx = NULL;\n\tint flen; // header frame len\n\tint hole = 0;\n\tint ret = 0;\n\tint outlen;\n\tint wrap;\n\tint try = 0;\n\nnext_frame:\n\tif (b_data(&h2c->dbuf) - hole < h2c->dfl)\n\t\tgoto leave; // incomplete input frame\n\n\t/* No END_HEADERS means there's one or more CONTINUATION frames. In\n\t * this case, we'll try to paste it immediately after the initial\n\t * HEADERS frame payload and kill any possible padding. The initial\n\t * frame's length will be increased to represent the concatenation\n\t * of the two frames. The next frame is read from position \n\t * and written at position (minus padding if some is present).\n\t */\n\tif (unlikely(!(h2c->dff & H2_F_HEADERS_END_HEADERS))) {\n\t\tstruct h2_fh hdr;\n\t\tint clen; // CONTINUATION frame's payload length\n\n\t\tif (!h2_peek_frame_hdr(&h2c->dbuf, h2c->dfl + hole, &hdr)) {\n\t\t\t/* no more data, the buffer may be full, either due to\n\t\t\t * too large a frame or because of too large a hole that\n\t\t\t * we're going to compact at the end.\n\t\t\t */\n\t\t\tgoto leave;\n\t\t}\n\n\t\tif (hdr.ft != H2_FT_CONTINUATION) {\n\t\t\t/* RFC7540#6.10: frame of unexpected type */\n\t\t\th2c_error(h2c, H2_ERR_PROTOCOL_ERROR);\n\t\t\tgoto fail;\n\t\t}\n\n\t\tif (hdr.sid != h2c->dsi) {\n\t\t\t/* RFC7540#6.10: frame of different stream */\n\t\t\th2c_error(h2c, H2_ERR_PROTOCOL_ERROR);\n\t\t\tgoto fail;\n\t\t}\n\n\t\tif ((unsigned)hdr.len > (unsigned)global.tune.bufsize) {\n\t\t\t/* RFC7540#4.2: invalid frame length */\n\t\t\th2c_error(h2c, H2_ERR_FRAME_SIZE_ERROR);\n\t\t\tgoto fail;\n\t\t}\n\n\t\t/* detect when we must stop aggragating frames */\n\t\th2c->dff |= hdr.ff & H2_F_HEADERS_END_HEADERS;\n\n\t\t/* Take as much as we can of the CONTINUATION frame's payload */\n\t\tclen = b_data(&h2c->dbuf) - (h2c->dfl + hole + 9);\n\t\tif (clen > hdr.len)\n\t\t\tclen = hdr.len;\n\n\t\t/* Move the frame's payload over the padding, hole and frame\n\t\t * header. At least one of hole or dpl is null (see diagrams\n\t\t * above). The hole moves after the new aggragated frame.\n\t\t */\n\t\tb_move(&h2c->dbuf, b_peek_ofs(&h2c->dbuf, h2c->dfl + hole + 9), clen, -(h2c->dpl + hole + 9));\n\t\th2c->dfl += clen - h2c->dpl;\n\t\thole += h2c->dpl + 9;\n\t\th2c->dpl = 0;\n\t\tgoto next_frame;\n\t}\n\n\tflen = h2c->dfl - h2c->dpl;\n\n\t/* if the input buffer wraps, take a temporary copy of it (rare) */\n\twrap = b_wrap(&h2c->dbuf) - b_head(&h2c->dbuf);\n\tif (wrap < h2c->dfl) {\n\t\tcopy = alloc_trash_chunk();\n\t\tif (!copy) {\n\t\t\th2c_error(h2c, H2_ERR_INTERNAL_ERROR);\n\t\t\tgoto fail;\n\t\t}\n\t\tmemcpy(copy->area, b_head(&h2c->dbuf), wrap);\n\t\tmemcpy(copy->area + wrap, b_orig(&h2c->dbuf), h2c->dfl - wrap);\n\t\thdrs = (uint8_t *) copy->area;\n\t}\n\n\t/* Skip StreamDep and weight for now (we don't support PRIORITY) */\n\tif (h2c->dff & H2_F_HEADERS_PRIORITY) {\n\t\tif (read_n32(hdrs) == h2c->dsi) {\n\t\t\t/* RFC7540#5.3.1 : stream dep may not depend on itself */\n\t\t\th2c_error(h2c, H2_ERR_PROTOCOL_ERROR);\n\t\t\tgoto fail;\n\t\t}\n\n\t\thdrs += 5; // stream dep = 4, weight = 1\n\t\tflen -= 5;\n\t}\n\n\tif (!h2_get_buf(h2c, rxbuf)) {\n\t\th2c->flags |= H2_CF_DEM_SALLOC;\n\t\tgoto leave;\n\t}\n\n\t/* we can't retry a failed decompression operation so we must be very\n\t * careful not to take any risks. In practice the output buffer is\n\t * always empty except maybe for trailers, in which case we simply have\n\t * to wait for the upper layer to finish consuming what is available.\n\t */\n\n\tif (h2c->proxy->options2 & PR_O2_USE_HTX) {\n\t\thtx = htx_from_buf(rxbuf);\n\t\tif (!htx_is_empty(htx)) {\n\t\t\th2c->flags |= H2_CF_DEM_SFULL;\n\t\t\tgoto leave;\n\t\t}\n\t} else {\n\t\tif (b_data(rxbuf)) {\n\t\t\th2c->flags |= H2_CF_DEM_SFULL;\n\t\t\tgoto leave;\n\t\t}\n\n\t\trxbuf->head = 0;\n\t\ttry = b_size(rxbuf);\n\t}\n\n\t/* past this point we cannot roll back in case of error */\n\toutlen = hpack_decode_frame(h2c->ddht, hdrs, flen, list,\n\t sizeof(list)/sizeof(list[0]), tmp);\n\tif (outlen < 0) {\n\t\th2c_error(h2c, H2_ERR_COMPRESSION_ERROR);\n\t\tgoto fail;\n\t}\n\n\t/* The PACK decompressor was updated, let's update the input buffer and\n\t * the parser's state to commit these changes and allow us to later\n\t * fail solely on the stream if needed.\n\t */\n\tb_del(&h2c->dbuf, h2c->dfl + hole);\n\th2c->dfl = hole = 0;\n\th2c->st0 = H2_CS_FRAME_H;\n\n\t/* OK now we have our header list in */\n\tmsgf = (h2c->dff & H2_F_HEADERS_END_STREAM) ? 0 : H2_MSGF_BODY;\n\n\tif (*flags & H2_SF_HEADERS_RCVD)\n\t\tgoto trailers;\n\n\t/* This is the first HEADERS frame so it's a headers block */\n\tif (htx) {\n\t\t/* HTX mode */\n\t\tif (h2c->flags & H2_CF_IS_BACK)\n\t\t\toutlen = h2_make_htx_response(list, htx, &msgf);\n\t\telse\n\t\t\toutlen = h2_make_htx_request(list, htx, &msgf);\n\t} else {\n\t\t/* HTTP/1 mode */\n\t\toutlen = h2_make_h1_request(list, b_tail(rxbuf), try, &msgf);\n\t\tif (outlen > 0)\n\t\t\tb_add(rxbuf, outlen);\n\t}\n\n\tif (outlen < 0) {\n\t\t/* too large headers? this is a stream error only */\n\t\tgoto fail;\n\t}\n\n\tif (msgf & H2_MSGF_BODY) {\n\t\t/* a payload is present */\n\t\tif (msgf & H2_MSGF_BODY_CL)\n\t\t\t*flags |= H2_SF_DATA_CLEN;\n\t\telse if (!(msgf & H2_MSGF_BODY_TUNNEL) && !htx)\n\t\t\t*flags |= H2_SF_DATA_CHNK;\n\t}\n\n done:\n\t/* indicate that a HEADERS frame was received for this stream */\n\t*flags |= H2_SF_HEADERS_RCVD;\n\n\tif (h2c->dff & H2_F_HEADERS_END_STREAM) {\n\t\t/* Mark the end of message, either using EOM in HTX or with the\n\t\t * trailing CRLF after the end of trailers. Note that DATA_CHNK\n\t\t * is not set during headers with END_STREAM.\n\t\t */\n\t\tif (htx) {\n\t\t\tif (!htx_add_endof(htx, HTX_BLK_EOM))\n\t\t\t\tgoto fail;\n\t\t}\n\t\telse if (*flags & H2_SF_DATA_CHNK) {\n\t\t\tif (!b_putblk(rxbuf, \"\\r\\n\", 2))\n\t\t\t\tgoto fail;\n\t\t}\n\t}\n\n\t/* success */\n\tret = 1;\n\n leave:\n\t/* If there is a hole left and it's not at the end, we are forced to\n\t * move the remaining data over it.\n\t */\n\tif (hole) {\n\t\tif (b_data(&h2c->dbuf) > h2c->dfl + hole)\n\t\t\tb_move(&h2c->dbuf, b_peek_ofs(&h2c->dbuf, h2c->dfl + hole),\n\t\t\t b_data(&h2c->dbuf) - (h2c->dfl + hole), -hole);\n\t\tb_sub(&h2c->dbuf, hole);\n\t}\n\n\tif (b_full(&h2c->dbuf) && h2c->dfl > b_data(&h2c->dbuf)) {\n\t\t/* too large frames */\n\t\th2c_error(h2c, H2_ERR_INTERNAL_ERROR);\n\t\tret = -1;\n\t}\n\n\tif (htx)\n\t\thtx_to_buf(htx, rxbuf);\n\tfree_trash_chunk(copy);\n\treturn ret;\n\n fail:\n\tret = -1;\n\tgoto leave;\n\n trailers:\n\t/* This is the last HEADERS frame hence a trailer */\n\n\tif (!(h2c->dff & H2_F_HEADERS_END_STREAM)) {\n\t\t/* It's a trailer but it's missing ES flag */\n\t\th2c_error(h2c, H2_ERR_PROTOCOL_ERROR);\n\t\tgoto fail;\n\t}\n\n\t/* Trailers terminate a DATA sequence. In HTX we have to emit an EOD\n\t * block, and when using chunks we must send the 0 CRLF marker. For\n\t * other modes, the trailers are silently dropped.\n\t */\n\tif (htx) {\n\t\tif (!htx_add_endof(htx, HTX_BLK_EOD))\n\t\t\tgoto fail;\n\t\tif (h2_make_htx_trailers(list, htx) <= 0)\n\t\t\tgoto fail;\n\t}\n\telse if (*flags & H2_SF_DATA_CHNK) {\n\t\t/* Legacy mode with chunked encoding : we must finalize the\n\t\t * data block message emit the trailing CRLF */\n\t\tif (!b_putblk(rxbuf, \"0\\r\\n\", 3))\n\t\t\tgoto fail;\n\n\t\toutlen = h2_make_h1_trailers(list, b_tail(rxbuf), try);\n\t\tif (outlen > 0)\n\t\t\tb_add(rxbuf, outlen);\n\t\telse\n\t\t\tgoto fail;\n\t}\n\n\tgoto done;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'BUG/CRITICAL: mux-h2: re-check the frame length when PRIORITY is used\n\nTim D\ufffdsterhus reported a possible crash in the H2 HEADERS frame decoder\nwhen the PRIORITY flag is present. A check is missing to ensure the 5\nextra bytes needed with this flag are actually part of the frame. As per\nRFC7540#4.2, let's return a connection error with code FRAME_SIZE_ERROR.\n\nMany thanks to Tim for responsibly reporting this issue with a working\nconfig and reproducer. This issue was assigned CVE-2018-20615.\n\nThis fix must be backported to 1.9 and 1.8.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ks_http_fetch (ctrl_t ctrl, const char *url, unsigned int flags,\n estream_t *r_fp)\n{\n gpg_error_t err;\n http_session_t session = NULL;\n unsigned int session_flags;\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, is_https;\n\n err = http_parse_uri (&uri, url, 0);\n if (err)\n goto leave;\n is_onion = uri->onion;\n is_https = uri->use_tls;\n\n /* By default we only use the system provided certificates with this\n * fetch command. */\n session_flags = HTTP_FLAG_TRUST_SYS;\n if ((flags & KS_HTTP_FETCH_NO_CRL) || ctrl->http_no_crl)\n session_flags |= HTTP_FLAG_NO_CRL;\n if ((flags & KS_HTTP_FETCH_TRUST_CFG))\n session_flags |= HTTP_FLAG_TRUST_CFG;\n\n once_more:\n err = http_session_new (&session, NULL, session_flags,\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 *r_fp = NULL;\n err = http_open (&http,\n HTTP_REQ_GET,\n url,\n /* httphost */ NULL,\n /* fixme: AUTH */ NULL,\n ((opt.honor_http_proxy? HTTP_FLAG_TRY_PROXY:0)\n | (DBG_LOOKUP? HTTP_FLAG_LOG_RESP: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 if ((flags & KS_HTTP_FETCH_NOCACHE))\n es_fputs (\"Pragma: no-cache\\r\\n\"\n \"Cache-Control: no-cache\\r\\n\", fp);\n http_start_data (http);\n if (es_ferror (fp))\n err = gpg_error_from_syserror ();\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 url, 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 url, gpg_strerror (err));\n goto leave;\n }\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 url, s?s:\"[none]\", http_get_status_code (http));\n if (s && *s && redirects_left-- )\n {\n if (is_onion || is_https)\n {\n /* Make sure that an onion address only redirects to\n * another onion address, or that a https address\n * only redirects to a https 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 (is_onion && !uri->onion)\n {\n err = gpg_error (GPG_ERR_FORBIDDEN);\n goto leave;\n }\n if (!(flags & KS_HTTP_FETCH_ALLOW_DOWNGRADE)\n && is_https && !uri->use_tls)\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 url = request_buffer;\n http_close (http, 0);\n http = NULL;\n http_session_release (session);\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 default:\n log_error (_(\"error accessing '%s': http status %u\\n\"),\n url, http_get_status_code (http));\n err = gpg_error (GPG_ERR_NO_DATA);\n goto leave;\n }\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: PyMemoTable_Copy(PyMemoTable *self)\n{\n Py_ssize_t i;\n PyMemoTable *new = PyMemoTable_New();\n if (new == NULL)\n return NULL;\n\n new->mt_used = self->mt_used;\n new->mt_allocated = self->mt_allocated;\n new->mt_mask = self->mt_mask;\n /* The table we get from _New() is probably smaller than we wanted.\n Free it and allocate one that's the right size. */\n PyMem_FREE(new->mt_table);\n new->mt_table = PyMem_NEW(PyMemoEntry, self->mt_allocated);\n if (new->mt_table == NULL) {\n PyMem_FREE(new);\n PyErr_NoMemory();\n return NULL;\n }\n for (i = 0; i < self->mt_allocated; i++) {\n Py_XINCREF(self->mt_table[i].me_key);\n }\n memcpy(new->mt_table, self->mt_table,\n sizeof(PyMemoEntry) * self->mt_allocated);\n\n return new;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-369'], 'message': 'closes bpo-34656: Avoid relying on signed overflow in _pickle memos. (GH-9261)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n BMPInfo\n bmp_info;\n\n Image\n *image;\n\n IndexPacket\n index;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n offset,\n start_position;\n\n MemoryInfo\n *pixel_info;\n\n register IndexPacket\n *indexes;\n\n register PixelPacket\n *q;\n\n register ssize_t\n i,\n x;\n\n register unsigned char\n *p;\n\n size_t\n bit,\n bytes_per_line,\n length;\n\n ssize_t\n count,\n y;\n\n unsigned char\n magick[12],\n *pixels;\n\n unsigned int\n blue,\n green,\n offset_bits,\n red;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Determine if this a BMP file.\n */\n (void) memset(&bmp_info,0,sizeof(bmp_info));\n bmp_info.ba_offset=0;\n start_position=0;\n offset_bits=0;\n count=ReadBlob(image,2,magick);\n if (count != 2)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n do\n {\n LongPixelPacket\n shift;\n\n PixelPacket\n quantum_bits;\n\n /*\n Verify BMP identifier.\n */\n start_position=TellBlob(image)-2;\n bmp_info.ba_offset=0;\n while (LocaleNCompare((char *) magick,\"BA\",2) == 0)\n {\n bmp_info.file_size=ReadBlobLSBLong(image);\n bmp_info.ba_offset=ReadBlobLSBLong(image);\n bmp_info.offset_bits=ReadBlobLSBLong(image);\n count=ReadBlob(image,2,magick);\n if (count != 2)\n break;\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Magick: %c%c\",\n magick[0],magick[1]);\n if ((count != 2) || ((LocaleNCompare((char *) magick,\"BM\",2) != 0) &&\n (LocaleNCompare((char *) magick,\"CI\",2) != 0)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n bmp_info.file_size=ReadBlobLSBLong(image);\n (void) ReadBlobLSBLong(image);\n\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" File_size in header: %u bytes\",bmp_info.file_size);\n\n bmp_info.offset_bits=ReadBlobLSBLong(image);\n bmp_info.size=ReadBlobLSBLong(image);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" BMP size: %u\",\n bmp_info.size);\n if (bmp_info.size == 12)\n {\n /*\n OS/2 BMP image file.\n */\n (void) CopyMagickString(image->magick,\"BMP2\",MaxTextExtent);\n bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image));\n bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image));\n bmp_info.planes=ReadBlobLSBShort(image);\n bmp_info.bits_per_pixel=ReadBlobLSBShort(image);\n bmp_info.x_pixels=0;\n bmp_info.y_pixels=0;\n bmp_info.number_colors=0;\n bmp_info.compression=BI_RGB;\n bmp_info.image_size=0;\n bmp_info.alpha_mask=0;\n if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Format: OS/2 Bitmap\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Geometry: %.20gx%.20g\",(double) bmp_info.width,(double)\n bmp_info.height);\n }\n }\n else\n {\n /*\n Microsoft Windows BMP image file.\n */\n if (bmp_info.size < 40)\n ThrowReaderException(CorruptImageError,\"NonOS2HeaderSizeError\");\n bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image);\n bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image);\n bmp_info.planes=ReadBlobLSBShort(image);\n bmp_info.bits_per_pixel=ReadBlobLSBShort(image);\n bmp_info.compression=ReadBlobLSBLong(image);\n bmp_info.image_size=ReadBlobLSBLong(image);\n bmp_info.x_pixels=ReadBlobLSBLong(image);\n bmp_info.y_pixels=ReadBlobLSBLong(image);\n bmp_info.number_colors=ReadBlobLSBLong(image);\n if (bmp_info.number_colors > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n bmp_info.colors_important=ReadBlobLSBLong(image);\n if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Format: MS Windows bitmap\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Geometry: %.20gx%.20g\",(double) bmp_info.width,(double)\n bmp_info.height);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Bits per pixel: %.20g\",(double) bmp_info.bits_per_pixel);\n switch (bmp_info.compression)\n {\n case BI_RGB:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_RGB\");\n break;\n }\n case BI_RLE4:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_RLE4\");\n break;\n }\n case BI_RLE8:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_RLE8\");\n break;\n }\n case BI_BITFIELDS:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_BITFIELDS\");\n break;\n }\n case BI_PNG:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_PNG\");\n break;\n }\n case BI_JPEG:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_JPEG\");\n break;\n }\n default:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: UNKNOWN (%u)\",bmp_info.compression);\n }\n }\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Number of colors: %u\",bmp_info.number_colors);\n }\n bmp_info.red_mask=ReadBlobLSBLong(image);\n bmp_info.green_mask=ReadBlobLSBLong(image);\n bmp_info.blue_mask=ReadBlobLSBLong(image);\n if (bmp_info.size > 40)\n {\n double\n gamma;\n\n /*\n Read color management information.\n */\n bmp_info.alpha_mask=ReadBlobLSBLong(image);\n bmp_info.colorspace=ReadBlobLSBSignedLong(image);\n /*\n Decode 2^30 fixed point formatted CIE primaries.\n */\n# define BMP_DENOM ((double) 0x40000000)\n bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n\n gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+\n bmp_info.red_primary.z;\n gamma=PerceptibleReciprocal(gamma);\n bmp_info.red_primary.x*=gamma;\n bmp_info.red_primary.y*=gamma;\n image->chromaticity.red_primary.x=bmp_info.red_primary.x;\n image->chromaticity.red_primary.y=bmp_info.red_primary.y;\n\n gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+\n bmp_info.green_primary.z;\n gamma=PerceptibleReciprocal(gamma);\n bmp_info.green_primary.x*=gamma;\n bmp_info.green_primary.y*=gamma;\n image->chromaticity.green_primary.x=bmp_info.green_primary.x;\n image->chromaticity.green_primary.y=bmp_info.green_primary.y;\n\n gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+\n bmp_info.blue_primary.z;\n gamma=PerceptibleReciprocal(gamma);\n bmp_info.blue_primary.x*=gamma;\n bmp_info.blue_primary.y*=gamma;\n image->chromaticity.blue_primary.x=bmp_info.blue_primary.x;\n image->chromaticity.blue_primary.y=bmp_info.blue_primary.y;\n\n /*\n Decode 16^16 fixed point formatted gamma_scales.\n */\n bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000;\n bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000;\n bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000;\n /*\n Compute a single gamma from the BMP 3-channel gamma.\n */\n image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+\n bmp_info.gamma_scale.z)/3.0;\n }\n else\n (void) CopyMagickString(image->magick,\"BMP3\",MaxTextExtent);\n\n if (bmp_info.size > 108)\n {\n size_t\n intent;\n\n /*\n Read BMP Version 5 color management information.\n */\n intent=ReadBlobLSBLong(image);\n switch ((int) intent)\n {\n case LCS_GM_BUSINESS:\n {\n image->rendering_intent=SaturationIntent;\n break;\n }\n case LCS_GM_GRAPHICS:\n {\n image->rendering_intent=RelativeIntent;\n break;\n }\n case LCS_GM_IMAGES:\n {\n image->rendering_intent=PerceptualIntent;\n break;\n }\n case LCS_GM_ABS_COLORIMETRIC:\n {\n image->rendering_intent=AbsoluteIntent;\n break;\n }\n }\n (void) ReadBlobLSBLong(image); /* Profile data */\n (void) ReadBlobLSBLong(image); /* Profile size */\n (void) ReadBlobLSBLong(image); /* Reserved byte */\n }\n }\n if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image))\n (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,\n \"LengthAndFilesizeDoNotMatch\",\"`%s'\",image->filename);\n else\n if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image))\n (void) ThrowMagickException(exception,GetMagickModule(),\n CorruptImageWarning,\"LengthAndFilesizeDoNotMatch\",\"`%s'\",\n image->filename);\n if (bmp_info.width <= 0)\n ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\");\n if (bmp_info.height == 0)\n ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\");\n if (bmp_info.planes != 1)\n ThrowReaderException(CorruptImageError,\"StaticPlanesValueNotEqualToOne\");\n if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) &&\n (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) &&\n (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32))\n ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n if (bmp_info.bits_per_pixel < 16 &&\n bmp_info.number_colors > (1U << bmp_info.bits_per_pixel))\n ThrowReaderException(CorruptImageError,\"UnrecognizedNumberOfColors\");\n if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8))\n ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4))\n ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16))\n ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n switch (bmp_info.compression)\n {\n case BI_RGB:\n image->compression=NoCompression;\n break;\n case BI_RLE8:\n case BI_RLE4:\n image->compression=RLECompression;\n break;\n case BI_BITFIELDS:\n break;\n case BI_JPEG:\n ThrowReaderException(CoderError,\"JPEGCompressNotSupported\");\n case BI_PNG:\n ThrowReaderException(CoderError,\"PNGCompressNotSupported\");\n default:\n ThrowReaderException(CorruptImageError,\"UnrecognizedImageCompression\");\n }\n image->columns=(size_t) MagickAbsoluteValue(bmp_info.width);\n image->rows=(size_t) MagickAbsoluteValue(bmp_info.height);\n image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8;\n image->matte=((bmp_info.alpha_mask != 0) &&\n (bmp_info.compression == BI_BITFIELDS)) ? MagickTrue : MagickFalse;\n if (bmp_info.bits_per_pixel < 16)\n {\n size_t\n one;\n\n image->storage_class=PseudoClass;\n image->colors=bmp_info.number_colors;\n one=1;\n if (image->colors == 0)\n image->colors=one << bmp_info.bits_per_pixel;\n }\n image->x_resolution=(double) bmp_info.x_pixels/100.0;\n image->y_resolution=(double) bmp_info.y_pixels/100.0;\n image->units=PixelsPerCentimeterResolution;\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n InheritException(exception,&image->exception);\n return(DestroyImageList(image));\n }\n if (image->storage_class == PseudoClass)\n {\n unsigned char\n *bmp_colormap;\n\n size_t\n packet_size;\n\n /*\n Read BMP raster colormap.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reading colormap of %.20g colors\",(double) image->colors);\n if (AcquireImageColormap(image,image->colors) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t)\n image->colors,4*sizeof(*bmp_colormap));\n if (bmp_colormap == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if ((bmp_info.size == 12) || (bmp_info.size == 64))\n packet_size=3;\n else\n packet_size=4;\n offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET);\n if (offset < 0)\n {\n bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n count=ReadBlob(image,packet_size*image->colors,bmp_colormap);\n if (count != (ssize_t) (packet_size*image->colors))\n {\n bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n ThrowReaderException(CorruptImageError,\n \"InsufficientImageDataInFile\");\n }\n p=bmp_colormap;\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n image->colormap[i].blue=ScaleCharToQuantum(*p++);\n image->colormap[i].green=ScaleCharToQuantum(*p++);\n image->colormap[i].red=ScaleCharToQuantum(*p++);\n if (packet_size == 4)\n p++;\n }\n bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n }\n /*\n Read image data.\n */\n if (bmp_info.offset_bits == offset_bits)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n offset_bits=bmp_info.offset_bits;\n offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET);\n if (offset < 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (bmp_info.compression == BI_RLE4)\n bmp_info.bits_per_pixel<<=1;\n bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32);\n length=(size_t) bytes_per_line*image->rows;\n if ((bmp_info.compression == BI_RGB) ||\n (bmp_info.compression == BI_BITFIELDS))\n {\n if ((MagickSizeType) length > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n pixel_info=AcquireVirtualMemory(image->rows,MagickMax(bytes_per_line,\n image->columns+256UL)*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reading pixels (%.20g bytes)\",(double) length);\n count=ReadBlob(image,length,pixels);\n if (count != (ssize_t) length)\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"InsufficientImageDataInFile\");\n }\n }\n else\n {\n /*\n Convert run-length encoded raster pixels.\n */\n pixel_info=AcquireVirtualMemory(image->rows,MagickMax(bytes_per_line,\n image->columns+256UL)*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n status=DecodeImage(image,bmp_info.compression,pixels,\n image->columns*image->rows);\n if (status == MagickFalse)\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"UnableToRunlengthDecodeImage\");\n }\n }\n /*\n Convert BMP raster image to pixel packets.\n */\n if (bmp_info.compression == BI_RGB)\n {\n /*\n We should ignore the alpha value in BMP3 files but there have been\n reports about 32 bit files with alpha. We do a quick check to see if\n the alpha channel contains a value that is not zero (default value).\n If we find a non zero value we asume the program that wrote the file\n wants to use the alpha channel.\n */\n if ((image->matte == MagickFalse) && (bmp_info.size == 40) &&\n (bmp_info.bits_per_pixel == 32))\n {\n bytes_per_line=4*(image->columns);\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (*(p+3) != 0)\n {\n image->matte=MagickTrue;\n y=-1;\n break;\n }\n p+=4;\n }\n }\n }\n bmp_info.alpha_mask=image->matte != MagickFalse ? 0xff000000U : 0U;\n bmp_info.red_mask=0x00ff0000U;\n bmp_info.green_mask=0x0000ff00U;\n bmp_info.blue_mask=0x000000ffU;\n if (bmp_info.bits_per_pixel == 16)\n {\n /*\n RGB555.\n */\n bmp_info.red_mask=0x00007c00U;\n bmp_info.green_mask=0x000003e0U;\n bmp_info.blue_mask=0x0000001fU;\n }\n }\n (void) memset(&shift,0,sizeof(shift));\n (void) memset(&quantum_bits,0,sizeof(quantum_bits));\n if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32))\n {\n register size_t\n sample;\n\n /*\n Get shift and quantum bits info from bitfield masks.\n */\n if (bmp_info.red_mask != 0)\n while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0)\n {\n shift.red++;\n if (shift.red > 32U)\n break;\n }\n if (bmp_info.green_mask != 0)\n while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0)\n {\n shift.green++;\n if (shift.green > 32U)\n break;\n }\n if (bmp_info.blue_mask != 0)\n while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0)\n {\n shift.blue++;\n if (shift.blue > 32U)\n break;\n }\n if (bmp_info.alpha_mask != 0)\n while (((bmp_info.alpha_mask << shift.opacity) & 0x80000000UL) == 0)\n {\n shift.opacity++;\n if (shift.opacity > 32U)\n break;\n }\n sample=shift.red;\n while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0)\n {\n sample++;\n if (sample > 32U)\n break;\n }\n quantum_bits.red=ClampToQuantum((MagickRealType) sample-shift.red);\n sample=shift.green;\n while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0)\n {\n sample++;\n if (sample > 32U)\n break;\n }\n quantum_bits.green=ClampToQuantum((MagickRealType) sample-shift.green);\n sample=shift.blue;\n while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0)\n {\n sample++;\n if (sample > 32U)\n break;\n }\n quantum_bits.blue=ClampToQuantum((MagickRealType) sample-shift.blue);\n sample=shift.opacity;\n while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0)\n {\n sample++;\n if (sample > 32U)\n break;\n }\n quantum_bits.opacity=ClampToQuantum((MagickRealType) sample-\n shift.opacity);\n }\n switch (bmp_info.bits_per_pixel)\n {\n case 1:\n {\n /*\n Convert bitmap scanline.\n */\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=0; x < ((ssize_t) image->columns-7); x+=8)\n {\n for (bit=0; bit < 8; bit++)\n {\n index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);\n SetPixelIndex(indexes+x+bit,index);\n q++;\n }\n p++;\n }\n if ((image->columns % 8) != 0)\n {\n for (bit=0; bit < (image->columns % 8); bit++)\n {\n index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);\n SetPixelIndex(indexes+x+bit,index);\n }\n p++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n (void) SyncImage(image);\n break;\n }\n case 4:\n {\n /*\n Convert PseudoColor scanline.\n */\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=0; x < ((ssize_t) image->columns-1); x+=2)\n {\n (void) IsValidColormapIndex(image,(ssize_t) ((*p >> 4) & 0x0f),\n &index,exception);\n SetPixelIndex(indexes+x,index);\n (void) IsValidColormapIndex(image,(ssize_t) (*p & 0x0f),&index,\n exception);\n SetPixelIndex(indexes+x+1,index);\n p++;\n }\n if ((image->columns % 2) != 0)\n {\n (void) IsValidColormapIndex(image,(ssize_t) ((*p >> 4) & 0xf),\n &index,exception);\n SetPixelIndex(indexes+(x++),index);\n p++;\n }\n if (x < (ssize_t) image->columns)\n break;\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n (void) SyncImage(image);\n break;\n }\n case 8:\n {\n /*\n Convert PseudoColor scanline.\n */\n if ((bmp_info.compression == BI_RLE8) ||\n (bmp_info.compression == BI_RLE4))\n bytes_per_line=image->columns;\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=(ssize_t) image->columns; x != 0; --x)\n {\n (void) IsValidColormapIndex(image,(ssize_t) *p,&index,exception);\n SetPixelIndex(indexes,index);\n indexes++;\n p++;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n offset=(MagickOffsetType) (image->rows-y-1);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n (void) SyncImage(image);\n break;\n }\n case 16:\n {\n unsigned int\n alpha,\n pixel;\n\n /*\n Convert bitfield encoded 16-bit PseudoColor scanline.\n */\n if (bmp_info.compression != BI_RGB &&\n bmp_info.compression != BI_BITFIELDS)\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"UnrecognizedImageCompression\");\n }\n bytes_per_line=2*(image->columns+image->columns % 2);\n image->storage_class=DirectClass;\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=(unsigned int) (*p++);\n pixel|=(*p++) << 8;\n red=((pixel & bmp_info.red_mask) << shift.red) >> 16;\n if (quantum_bits.red == 5)\n red|=((red & 0xe000) >> 5);\n if (quantum_bits.red <= 8)\n red|=((red & 0xff00) >> 8);\n green=((pixel & bmp_info.green_mask) << shift.green) >> 16;\n if (quantum_bits.green == 5)\n green|=((green & 0xe000) >> 5);\n if (quantum_bits.green == 6)\n green|=((green & 0xc000) >> 6);\n if (quantum_bits.green <= 8)\n green|=((green & 0xff00) >> 8);\n blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;\n if (quantum_bits.blue == 5)\n blue|=((blue & 0xe000) >> 5);\n if (quantum_bits.blue <= 8)\n blue|=((blue & 0xff00) >> 8);\n SetPixelRed(q,ScaleShortToQuantum((unsigned short) red));\n SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green));\n SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue));\n SetPixelOpacity(q,OpaqueOpacity);\n if (image->matte != MagickFalse)\n {\n alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16;\n if (quantum_bits.opacity <= 8)\n alpha|=((alpha & 0xff00) >> 8);\n SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha));\n }\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n offset=(MagickOffsetType) (image->rows-y-1);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case 24:\n {\n /*\n Convert DirectColor scanline.\n */\n bytes_per_line=4*((image->columns*24+31)/32);\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelBlue(q,ScaleCharToQuantum(*p++));\n SetPixelGreen(q,ScaleCharToQuantum(*p++));\n SetPixelRed(q,ScaleCharToQuantum(*p++));\n SetPixelOpacity(q,OpaqueOpacity);\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n offset=(MagickOffsetType) (image->rows-y-1);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case 32:\n {\n /*\n Convert bitfield encoded DirectColor scanline.\n */\n if ((bmp_info.compression != BI_RGB) &&\n (bmp_info.compression != BI_BITFIELDS))\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"UnrecognizedImageCompression\");\n }\n bytes_per_line=4*(image->columns);\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n unsigned int\n alpha,\n pixel;\n\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=(unsigned int) (*p++);\n pixel|=((unsigned int) *p++ << 8);\n pixel|=((unsigned int) *p++ << 16);\n pixel|=((unsigned int) *p++ << 24);\n red=((pixel & bmp_info.red_mask) << shift.red) >> 16;\n if (quantum_bits.red == 8)\n red|=(red >> 8);\n green=((pixel & bmp_info.green_mask) << shift.green) >> 16;\n if (quantum_bits.green == 8)\n green|=(green >> 8);\n blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;\n if (quantum_bits.blue == 8)\n blue|=(blue >> 8);\n SetPixelRed(q,ScaleShortToQuantum((unsigned short) red));\n SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green));\n SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue));\n SetPixelAlpha(q,OpaqueOpacity);\n if (image->matte != MagickFalse)\n {\n alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16;\n if (quantum_bits.opacity == 8)\n alpha|=(alpha >> 8);\n SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha));\n }\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n offset=(MagickOffsetType) (image->rows-y-1);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n default:\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n }\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (y > 0)\n break;\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n if (bmp_info.height < 0)\n {\n Image\n *flipped_image;\n\n /*\n Correct image orientation.\n */\n flipped_image=FlipImage(image,exception);\n if (flipped_image != (Image *) NULL)\n {\n DuplicateBlob(flipped_image,image);\n ReplaceImageInList(&image, flipped_image);\n image=flipped_image;\n }\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n *magick='\\0';\n if (bmp_info.ba_offset != 0)\n {\n offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET);\n if (offset < 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n count=ReadBlob(image,2,magick);\n if ((count == 2) && (IsBMP(magick,2) != MagickFalse))\n {\n /*\n Acquire next image structure.\n */\n AcquireNextImage(image_info,image);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n 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 (IsBMP(magick,2) != MagickFalse);\n (void) CloseBlob(image);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'Prevent infinite loop'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool PDFDoc::setup(const GooString *ownerPassword, const GooString *userPassword) {\n pdfdocLocker();\n\n if (str->getLength() <= 0)\n {\n error(errSyntaxError, -1, \"Document stream is empty\");\n return false;\n }\n\n str->setPos(0, -1);\n if (str->getPos() < 0)\n {\n error(errSyntaxError, -1, \"Document base stream is not seekable\");\n return false;\n }\n\n str->reset();\n\n // check footer\n // Adobe does not seem to enforce %%EOF, so we do the same\n// if (!checkFooter()) return false;\n \n // check header\n checkHeader();\n\n bool wasReconstructed = false;\n\n // read xref table\n xref = new XRef(str, getStartXRef(), getMainXRefEntriesOffset(), &wasReconstructed);\n if (!xref->isOk()) {\n if (wasReconstructed) {\n delete xref;\n startXRefPos = -1;\n xref = new XRef(str, getStartXRef(true), getMainXRefEntriesOffset(true), &wasReconstructed);\n }\n if (!xref->isOk()) {\n error(errSyntaxError, -1, \"Couldn't read xref table\");\n errCode = xref->getErrorCode();\n return false;\n }\n }\n\n // check for encryption\n if (!checkEncryption(ownerPassword, userPassword)) {\n errCode = errEncrypted;\n return false;\n }\n\n // read catalog\n catalog = new Catalog(this);\n if (catalog && !catalog->isOk()) {\n if (!wasReconstructed)\n {\n // try one more time to construct the Catalog, maybe the problem is damaged XRef\n delete catalog;\n delete xref;\n xref = new XRef(str, 0, 0, nullptr, true);\n catalog = new Catalog(this);\n }\n\n if (catalog && !catalog->isOk()) {\n error(errSyntaxError, -1, \"Couldn't read page catalog\");\n errCode = errBadCatalog;\n return false;\n }\n }\n\n // Extract PDF Subtype information\n extractPDFSubtype();\n\n // done\n return xref->isOk();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Revert 9fd5ec0e6e5f763b190f2a55ceb5427cfe851d5f\n\nIt was causing regressions for some half-broken files\n\nRationale:\n\nEven if xref::constructXRef is returning false, that only means \"i\ndin't find a new xref root\", but constructXRef is also quite stubborn in\nwhich it basically parses the whole file and stores the positions of all\nthe objects it finds, so for some half broken pdf files this is good\nenough and we will be able to render those files just fine'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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 URI_CHAR * URI_FUNC(ParseIPv6address2)(\n\t\tURI_TYPE(ParserState) * state,\n\t\tconst URI_CHAR * first, const URI_CHAR * afterLast,\n\t\tUriMemoryManager * memory) {\n\tint zipperEver = 0;\n\tint quadsDone = 0;\n\tint digitCount = 0;\n\tunsigned char digitHistory[4];\n\tint ip4OctetsDone = 0;\n\n\tunsigned char quadsAfterZipper[14];\n\tint quadsAfterZipperCount = 0;\n\n\n\tfor (;;) {\n\t\tif (first >= afterLast) {\n\t\t\tURI_FUNC(StopSyntax)(state, first, memory);\n\t\t\treturn NULL;\n\t\t}\n\n\t\t/* Inside IPv4 part? */\n\t\tif (ip4OctetsDone > 0) {\n\t\t\t/* Eat rest of IPv4 address */\n\t\t\tfor (;;) {\n\t\t\t\tswitch (*first) {\n\t\t\t\tcase URI_SET_DIGIT:\n\t\t\t\t\tif (digitCount == 4) {\n\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first, memory);\n\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t}\n\t\t\t\t\tdigitHistory[digitCount++] = (unsigned char)(9 + *first - _UT('9'));\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase _UT('.'):\n\t\t\t\t\tif ((ip4OctetsDone == 4) /* NOTE! */\n\t\t\t\t\t\t\t|| (digitCount == 0)\n\t\t\t\t\t\t\t|| (digitCount == 4)) {\n\t\t\t\t\t\t/* Invalid digit or octet count */\n\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first, memory);\n\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t} else if ((digitCount > 1)\n\t\t\t\t\t\t\t&& (digitHistory[0] == 0)) {\n\t\t\t\t\t\t/* Leading zero */\n\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first - digitCount, memory);\n\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t} else if ((digitCount > 2)\n\t\t\t\t\t\t\t&& (digitHistory[1] == 0)) {\n\t\t\t\t\t\t/* Leading zero */\n\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first - digitCount + 1, memory);\n\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t} else if ((digitCount == 3)\n\t\t\t\t\t\t\t&& (100 * digitHistory[0]\n\t\t\t\t\t\t\t\t+ 10 * digitHistory[1]\n\t\t\t\t\t\t\t\t+ digitHistory[2] > 255)) {\n\t\t\t\t\t\t/* Octet value too large */\n\t\t\t\t\t\tif (digitHistory[0] > 2) {\n\t\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first - 3, memory);\n\t\t\t\t\t\t} else if (digitHistory[1] > 5) {\n\t\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first - 2, memory);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first - 1, memory);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t}\n\n\t\t\t\t\t/* Copy IPv4 octet */\n\t\t\t\t\tstate->uri->hostData.ip6->data[16 - 4 + ip4OctetsDone] = uriGetOctetValue(digitHistory, digitCount);\n\t\t\t\t\tdigitCount = 0;\n\t\t\t\t\tip4OctetsDone++;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase _UT(']'):\n\t\t\t\t\tif ((ip4OctetsDone != 3) /* NOTE! */\n\t\t\t\t\t\t\t|| (digitCount == 0)\n\t\t\t\t\t\t\t|| (digitCount == 4)) {\n\t\t\t\t\t\t/* Invalid digit or octet count */\n\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first, memory);\n\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t} else if ((digitCount > 1)\n\t\t\t\t\t\t\t&& (digitHistory[0] == 0)) {\n\t\t\t\t\t\t/* Leading zero */\n\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first - digitCount, memory);\n\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t} else if ((digitCount > 2)\n\t\t\t\t\t\t\t&& (digitHistory[1] == 0)) {\n\t\t\t\t\t\t/* Leading zero */\n\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first - digitCount + 1, memory);\n\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t} else if ((digitCount == 3)\n\t\t\t\t\t\t\t&& (100 * digitHistory[0]\n\t\t\t\t\t\t\t\t+ 10 * digitHistory[1]\n\t\t\t\t\t\t\t\t+ digitHistory[2] > 255)) {\n\t\t\t\t\t\t/* Octet value too large */\n\t\t\t\t\t\tif (digitHistory[0] > 2) {\n\t\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first - 3, memory);\n\t\t\t\t\t\t} else if (digitHistory[1] > 5) {\n\t\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first - 2, memory);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first - 1, memory);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t}\n\n\t\t\t\t\tstate->uri->hostText.afterLast = first; /* HOST END */\n\n\t\t\t\t\t/* Copy missing quads right before IPv4 */\n\t\t\t\t\tmemcpy(state->uri->hostData.ip6->data + 16 - 4 - 2 * quadsAfterZipperCount,\n\t\t\t\t\t\t\t\tquadsAfterZipper, 2 * quadsAfterZipperCount);\n\n\t\t\t\t\t/* Copy last IPv4 octet */\n\t\t\t\t\tstate->uri->hostData.ip6->data[16 - 4 + 3] = uriGetOctetValue(digitHistory, digitCount);\n\n\t\t\t\t\treturn first + 1;\n\n\t\t\t\tdefault:\n\t\t\t\t\tURI_FUNC(StopSyntax)(state, first, memory);\n\t\t\t\t\treturn NULL;\n\t\t\t\t}\n\t\t\t\tfirst++;\n\t\t\t}\n\t\t} else {\n\t\t\t/* Eat while no dot in sight */\n\t\t\tint letterAmong = 0;\n\t\t\tint walking = 1;\n\t\t\tdo {\n\t\t\t\tswitch (*first) {\n\t\t\t\tcase URI_SET_HEX_LETTER_LOWER:\n\t\t\t\t\tletterAmong = 1;\n\t\t\t\t\tif (digitCount == 4) {\n\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first, memory);\n\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t}\n\t\t\t\t\tdigitHistory[digitCount] = (unsigned char)(15 + *first - _UT('f'));\n\t\t\t\t\tdigitCount++;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase URI_SET_HEX_LETTER_UPPER:\n\t\t\t\t\tletterAmong = 1;\n\t\t\t\t\tif (digitCount == 4) {\n\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first, memory);\n\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t}\n\t\t\t\t\tdigitHistory[digitCount] = (unsigned char)(15 + *first - _UT('F'));\n\t\t\t\t\tdigitCount++;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase URI_SET_DIGIT:\n\t\t\t\t\tif (digitCount == 4) {\n\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first, memory);\n\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t}\n\t\t\t\t\tdigitHistory[digitCount] = (unsigned char)(9 + *first - _UT('9'));\n\t\t\t\t\tdigitCount++;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase _UT(':'):\n\t\t\t\t\t{\n\t\t\t\t\t\tint setZipper = 0;\n\n\t\t\t\t\t\tif (digitCount > 0) {\n\t\t\t\t\t\t\tif (zipperEver) {\n\t\t\t\t\t\t\t\turiWriteQuadToDoubleByte(digitHistory, digitCount, quadsAfterZipper + 2 * quadsAfterZipperCount);\n\t\t\t\t\t\t\t\tquadsAfterZipperCount++;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\turiWriteQuadToDoubleByte(digitHistory, digitCount, state->uri->hostData.ip6->data + 2 * quadsDone);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tquadsDone++;\n\t\t\t\t\t\t\tdigitCount = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tletterAmong = 0;\n\n\t\t\t\t\t\t/* Too many quads? */\n\t\t\t\t\t\tif (quadsDone >= 8 - zipperEver) {\n\t\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first, memory);\n\t\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t/* \"::\"? */\n\t\t\t\t\t\tif (first + 1 >= afterLast) {\n\t\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first + 1, memory);\n\t\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (first[1] == _UT(':')) {\n\t\t\t\t\t\t\tconst int resetOffset = 2 * (quadsDone + (digitCount > 0));\n\n\t\t\t\t\t\t\tfirst++;\n\t\t\t\t\t\t\tif (zipperEver) {\n\t\t\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first, memory);\n\t\t\t\t\t\t\t\treturn NULL; /* \"::.+::\" */\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t/* Zero everything after zipper */\n\t\t\t\t\t\t\tmemset(state->uri->hostData.ip6->data + resetOffset, 0, 16 - resetOffset);\n\t\t\t\t\t\t\tsetZipper = 1;\n\n\t\t\t\t\t\t\t/* \":::+\"? */\n\t\t\t\t\t\t\tif (first + 1 >= afterLast) {\n\t\t\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first + 1, memory);\n\t\t\t\t\t\t\t\treturn NULL; /* No ']' yet */\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (first[1] == _UT(':')) {\n\t\t\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first + 1, memory);\n\t\t\t\t\t\t\t\treturn NULL; /* \":::+ \"*/\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (setZipper) {\n\t\t\t\t\t\t\tzipperEver = 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase _UT('.'):\n\t\t\t\t\tif ((quadsDone > 6) /* NOTE */\n\t\t\t\t\t\t\t|| (!zipperEver && (quadsDone < 6))\n\t\t\t\t\t\t\t|| letterAmong\n\t\t\t\t\t\t\t|| (digitCount == 0)\n\t\t\t\t\t\t\t|| (digitCount == 4)) {\n\t\t\t\t\t\t/* Invalid octet before */\n\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first, memory);\n\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t} else if ((digitCount > 1)\n\t\t\t\t\t\t\t&& (digitHistory[0] == 0)) {\n\t\t\t\t\t\t/* Leading zero */\n\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first - digitCount, memory);\n\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t} else if ((digitCount > 2)\n\t\t\t\t\t\t\t&& (digitHistory[1] == 0)) {\n\t\t\t\t\t\t/* Leading zero */\n\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first - digitCount + 1, memory);\n\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t} else if ((digitCount == 3)\n\t\t\t\t\t\t\t&& (100 * digitHistory[0]\n\t\t\t\t\t\t\t\t+ 10 * digitHistory[1]\n\t\t\t\t\t\t\t\t+ digitHistory[2] > 255)) {\n\t\t\t\t\t\t/* Octet value too large */\n\t\t\t\t\t\tif (digitHistory[0] > 2) {\n\t\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first - 3, memory);\n\t\t\t\t\t\t} else if (digitHistory[1] > 5) {\n\t\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first - 2, memory);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first - 1, memory);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t}\n\n\t\t\t\t\t/* Copy first IPv4 octet */\n\t\t\t\t\tstate->uri->hostData.ip6->data[16 - 4] = uriGetOctetValue(digitHistory, digitCount);\n\t\t\t\t\tdigitCount = 0;\n\n\t\t\t\t\t/* Switch over to IPv4 loop */\n\t\t\t\t\tip4OctetsDone = 1;\n\t\t\t\t\twalking = 0;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase _UT(']'):\n\t\t\t\t\t/* Too little quads? */\n\t\t\t\t\tif (!zipperEver && !((quadsDone == 7) && (digitCount > 0))) {\n\t\t\t\t\t\tURI_FUNC(StopSyntax)(state, first, memory);\n\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (digitCount > 0) {\n\t\t\t\t\t\tif (zipperEver) {\n\t\t\t\t\t\t\turiWriteQuadToDoubleByte(digitHistory, digitCount, quadsAfterZipper + 2 * quadsAfterZipperCount);\n\t\t\t\t\t\t\tquadsAfterZipperCount++;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\turiWriteQuadToDoubleByte(digitHistory, digitCount, state->uri->hostData.ip6->data + 2 * quadsDone);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t/*\n\t\t\t\t\t\tquadsDone++;\n\t\t\t\t\t\tdigitCount = 0;\n\t\t\t\t\t\t*/\n\t\t\t\t\t}\n\n\t\t\t\t\t/* Copy missing quads to the end */\n\t\t\t\t\tmemcpy(state->uri->hostData.ip6->data + 16 - 2 * quadsAfterZipperCount,\n\t\t\t\t\t\t\t\tquadsAfterZipper, 2 * quadsAfterZipperCount);\n\n\t\t\t\t\tstate->uri->hostText.afterLast = first; /* HOST END */\n\t\t\t\t\treturn first + 1; /* Fine */\n\n\t\t\t\tdefault:\n\t\t\t\t\tURI_FUNC(StopSyntax)(state, first, memory);\n\t\t\t\t\treturn NULL;\n\t\t\t\t}\n\t\t\t\tfirst++;\n\n\t\t\t\tif (first >= afterLast) {\n\t\t\t\t\tURI_FUNC(StopSyntax)(state, first, memory);\n\t\t\t\t\treturn NULL; /* No ']' yet */\n\t\t\t\t}\n\t\t\t} while (walking);\n\t\t}\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix uriParse*Ex* out-of-bounds read'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static char **fill_envp(struct dhcp_packet *packet)\n{\n\tint envc;\n\tint i;\n\tchar **envp, **curr;\n\tconst char *opt_name;\n\tuint8_t *temp;\n\tuint8_t overload = 0;\n\n#define BITMAP unsigned\n#define BBITS (sizeof(BITMAP) * 8)\n#define BMASK(i) (1 << (i & (sizeof(BITMAP) * 8 - 1)))\n#define FOUND_OPTS(i) (found_opts[(unsigned)i / BBITS])\n\tBITMAP found_opts[256 / BBITS];\n\n\tmemset(found_opts, 0, sizeof(found_opts));\n\n\t/* We need 6 elements for:\n\t * \"interface=IFACE\"\n\t * \"ip=N.N.N.N\" from packet->yiaddr\n\t * \"siaddr=IP\" from packet->siaddr_nip (unless 0)\n\t * \"boot_file=FILE\" from packet->file (unless overloaded)\n\t * \"sname=SERVER_HOSTNAME\" from packet->sname (unless overloaded)\n\t * terminating NULL\n\t */\n\tenvc = 6;\n\t/* +1 element for each option, +2 for subnet option: */\n\tif (packet) {\n\t\t/* note: do not search for \"pad\" (0) and \"end\" (255) options */\n//TODO: change logic to scan packet _once_\n\t\tfor (i = 1; i < 255; i++) {\n\t\t\ttemp = udhcp_get_option(packet, i);\n\t\t\tif (temp) {\n\t\t\t\tif (i == DHCP_OPTION_OVERLOAD)\n\t\t\t\t\toverload |= *temp;\n\t\t\t\telse if (i == DHCP_SUBNET)\n\t\t\t\t\tenvc++; /* for $mask */\n\t\t\t\tenvc++;\n\t\t\t\t/*if (i != DHCP_MESSAGE_TYPE)*/\n\t\t\t\tFOUND_OPTS(i) |= BMASK(i);\n\t\t\t}\n\t\t}\n\t}\n\tcurr = envp = xzalloc(sizeof(envp[0]) * envc);\n\n\t*curr = xasprintf(\"interface=%s\", client_config.interface);\n\tputenv(*curr++);\n\n\tif (!packet)\n\t\treturn envp;\n\n\t/* Export BOOTP fields. Fields we don't (yet?) export:\n\t * uint8_t op; // always BOOTREPLY\n\t * uint8_t htype; // hardware address type. 1 = 10mb ethernet\n\t * uint8_t hlen; // hardware address length\n\t * uint8_t hops; // used by relay agents only\n\t * uint32_t xid;\n\t * uint16_t secs; // elapsed since client began acquisition/renewal\n\t * uint16_t flags; // only one flag so far: bcast. Never set by server\n\t * uint32_t ciaddr; // client IP (usually == yiaddr. can it be different\n\t * // if during renew server wants to give us different IP?)\n\t * uint32_t gateway_nip; // relay agent IP address\n\t * uint8_t chaddr[16]; // link-layer client hardware address (MAC)\n\t * TODO: export gateway_nip as $giaddr?\n\t */\n\t/* Most important one: yiaddr as $ip */\n\t*curr = xmalloc(sizeof(\"ip=255.255.255.255\"));\n\tsprint_nip(*curr, \"ip=\", (uint8_t *) &packet->yiaddr);\n\tputenv(*curr++);\n\tif (packet->siaddr_nip) {\n\t\t/* IP address of next server to use in bootstrap */\n\t\t*curr = xmalloc(sizeof(\"siaddr=255.255.255.255\"));\n\t\tsprint_nip(*curr, \"siaddr=\", (uint8_t *) &packet->siaddr_nip);\n\t\tputenv(*curr++);\n\t}\n\tif (!(overload & FILE_FIELD) && packet->file[0]) {\n\t\t/* watch out for invalid packets */\n\t\t*curr = xasprintf(\"boot_file=%.\"DHCP_PKT_FILE_LEN_STR\"s\", packet->file);\n\t\tputenv(*curr++);\n\t}\n\tif (!(overload & SNAME_FIELD) && packet->sname[0]) {\n\t\t/* watch out for invalid packets */\n\t\t*curr = xasprintf(\"sname=%.\"DHCP_PKT_SNAME_LEN_STR\"s\", packet->sname);\n\t\tputenv(*curr++);\n\t}\n\n\t/* Export known DHCP options */\n\topt_name = dhcp_option_strings;\n\ti = 0;\n\twhile (*opt_name) {\n\t\tuint8_t code = dhcp_optflags[i].code;\n\t\tBITMAP *found_ptr = &FOUND_OPTS(code);\n\t\tBITMAP found_mask = BMASK(code);\n\t\tif (!(*found_ptr & found_mask))\n\t\t\tgoto next;\n\t\t*found_ptr &= ~found_mask; /* leave only unknown options */\n\t\ttemp = udhcp_get_option(packet, code);\n\t\t*curr = xmalloc_optname_optval(temp, &dhcp_optflags[i], opt_name);\n\t\tputenv(*curr++);\n\t\tif (code == DHCP_SUBNET) {\n\t\t\t/* Subnet option: make things like \"$ip/$mask\" possible */\n\t\t\tuint32_t subnet;\n\t\t\tmove_from_unaligned32(subnet, temp);\n\t\t\t*curr = xasprintf(\"mask=%u\", mton(subnet));\n\t\t\tputenv(*curr++);\n\t\t}\n next:\n\t\topt_name += strlen(opt_name) + 1;\n\t\ti++;\n\t}\n\t/* Export unknown options */\n\tfor (i = 0; i < 256;) {\n\t\tBITMAP bitmap = FOUND_OPTS(i);\n\t\tif (!bitmap) {\n\t\t\ti += BBITS;\n\t\t\tcontinue;\n\t\t}\n\t\tif (bitmap & BMASK(i)) {\n\t\t\tunsigned len, ofs;\n\n\t\t\ttemp = udhcp_get_option(packet, i);\n\t\t\t/* udhcp_get_option returns ptr to data portion,\n\t\t\t * need to go back to get len\n\t\t\t */\n\t\t\tlen = temp[-OPT_DATA + OPT_LEN];\n\t\t\t*curr = xmalloc(sizeof(\"optNNN=\") + 1 + len*2);\n\t\t\tofs = sprintf(*curr, \"opt%u=\", i);\n\t\t\t*bin2hex(*curr + ofs, (void*) temp, len) = '\\0';\n\t\t\tputenv(*curr++);\n\t\t}\n\t\ti++;\n\t}\n\n\treturn envp;\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 strncpy_from_user(char *dst, const char __user *src, 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)src;\n\tif (likely(src_addr < max_addr)) {\n\t\tunsigned long max = max_addr - src_addr;\n\t\tlong retval;\n\n\t\tkasan_check_write(dst, count);\n\t\tcheck_object_size(dst, count, false);\n\t\tuser_access_begin();\n\t\tretval = do_strncpy_from_user(dst, src, count, max);\n\t\tuser_access_end();\n\t\treturn retval;\n\t}\n\treturn -EFAULT;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'make 'user_access_begin()' do 'access_ok()'\n\nOriginally, the rule used to be that you'd have to do access_ok()\nseparately, and then user_access_begin() before actually doing the\ndirect (optimized) user access.\n\nBut experience has shown that people then decide not to do access_ok()\nat all, and instead rely on it being implied by other operations or\nsimilar. Which makes it very hard to verify that the access has\nactually been range-checked.\n\nIf you use the unsafe direct user accesses, hardware features (either\nSMAP - Supervisor Mode Access Protection - on x86, or PAN - Privileged\nAccess Never - on ARM) do force you to use user_access_begin(). But\nnothing really forces the range check.\n\nBy putting the range check into user_access_begin(), we actually force\npeople to do the right thing (tm), and the range check vill be visible\nnear the actual accesses. We have way too long a history of people\ntrying to avoid them.\n\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ssize_t hid_debug_events_read(struct file *file, char __user *buffer,\n\t\tsize_t count, loff_t *ppos)\n{\n\tstruct hid_debug_list *list = file->private_data;\n\tint ret = 0, len;\n\tDECLARE_WAITQUEUE(wait, current);\n\n\tmutex_lock(&list->read_mutex);\n\twhile (ret == 0) {\n\t\tif (list->head == list->tail) {\n\t\t\tadd_wait_queue(&list->hdev->debug_wait, &wait);\n\t\t\tset_current_state(TASK_INTERRUPTIBLE);\n\n\t\t\twhile (list->head == list->tail) {\n\t\t\t\tif (file->f_flags & O_NONBLOCK) {\n\t\t\t\t\tret = -EAGAIN;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (signal_pending(current)) {\n\t\t\t\t\tret = -ERESTARTSYS;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (!list->hdev || !list->hdev->debug) {\n\t\t\t\t\tret = -EIO;\n\t\t\t\t\tset_current_state(TASK_RUNNING);\n\t\t\t\t\tgoto out;\n\t\t\t\t}\n\n\t\t\t\t/* allow O_NONBLOCK from other threads */\n\t\t\t\tmutex_unlock(&list->read_mutex);\n\t\t\t\tschedule();\n\t\t\t\tmutex_lock(&list->read_mutex);\n\t\t\t\tset_current_state(TASK_INTERRUPTIBLE);\n\t\t\t}\n\n\t\t\tset_current_state(TASK_RUNNING);\n\t\t\tremove_wait_queue(&list->hdev->debug_wait, &wait);\n\t\t}\n\n\t\tif (ret)\n\t\t\tgoto out;\n\n\t\t/* pass the ringbuffer contents to userspace */\ncopy_rest:\n\t\tif (list->tail == list->head)\n\t\t\tgoto out;\n\t\tif (list->tail > list->head) {\n\t\t\tlen = list->tail - list->head;\n\t\t\tif (len > count)\n\t\t\t\tlen = count;\n\n\t\t\tif (copy_to_user(buffer + ret, &list->hid_debug_buf[list->head], len)) {\n\t\t\t\tret = -EFAULT;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tret += len;\n\t\t\tlist->head += len;\n\t\t} else {\n\t\t\tlen = HID_DEBUG_BUFSIZE - list->head;\n\t\t\tif (len > count)\n\t\t\t\tlen = count;\n\n\t\t\tif (copy_to_user(buffer, &list->hid_debug_buf[list->head], len)) {\n\t\t\t\tret = -EFAULT;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tlist->head = 0;\n\t\t\tret += len;\n\t\t\tcount -= len;\n\t\t\tif (count > 0)\n\t\t\t\tgoto copy_rest;\n\t\t}\n\n\t}\nout:\n\tmutex_unlock(&list->read_mutex);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'HID: debug: fix the ring buffer implementation\n\nRing buffer implementation in hid_debug_event() and hid_debug_events_read()\nis strange allowing lost or corrupted data. After commit 717adfdaf147\n(\"HID: debug: check length before copy_to_user()\") it is possible to enter\nan infinite loop in hid_debug_events_read() by providing 0 as count, this\nlocks up a system. Fix this by rewriting the ring buffer implementation\nwith kfifo and simplify the code.\n\nThis fixes CVE-2019-3819.\n\nv2: fix an execution logic and add a comment\nv3: use __set_current_state() instead of set_current_state()\n\nLink: https://bugzilla.redhat.com/show_bug.cgi?id=1669187\nCc: stable@vger.kernel.org # v4.18+\nFixes: cd667ce24796 (\"HID: use debugfs for events/reports dumping\")\nFixes: 717adfdaf147 (\"HID: debug: check length before copy_to_user()\")\nSigned-off-by: Vladis Dronov \nReviewed-by: Oleg Nesterov \nSigned-off-by: Benjamin Tissoires '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: mcs_recv_connect_response(STREAM mcs_data)\n{\n\tuint8 result;\n\tint length;\n\tSTREAM s;\n\n\ts = iso_recv(NULL);\n\tif (s == NULL)\n\t\treturn False;\n\n\tber_parse_header(s, MCS_CONNECT_RESPONSE, &length);\n\n\tber_parse_header(s, BER_TAG_RESULT, &length);\n\tin_uint8(s, result);\n\tif (result != 0)\n\t{\n\t\terror(\"MCS connect: %d\\n\", result);\n\t\treturn False;\n\t}\n\n\tber_parse_header(s, BER_TAG_INTEGER, &length);\n\tin_uint8s(s, length);\t/* connect id */\n\tmcs_parse_domain_params(s);\n\n\tber_parse_header(s, BER_TAG_OCTET_STRING, &length);\n\n\tsec_process_mcs_data(s);\n\t/*\n\t if (length > mcs_data->size)\n\t {\n\t error(\"MCS data length %d, expected %d\\n\", length,\n\t mcs_data->size);\n\t length = mcs_data->size;\n\t }\n\n\t in_uint8a(s, mcs_data->data, length);\n\t mcs_data->p = mcs_data->data;\n\t mcs_data->end = mcs_data->data + length;\n\t */\n\treturn s_check_end(s);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n* Add rdp_protocol_error function that is used in several fixes\n* Refactor of process_bitmap_updates\n* Fix possible integer overflow in s_check_rem() on 32bit arch\n* Fix memory corruption in process_bitmap_data - CVE-2018-8794\n* Fix remote code execution in process_bitmap_data - CVE-2018-8795\n* Fix remote code execution in process_plane - CVE-2018-8797\n* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n* Fix Denial of Service in sec_recv - CVE-2018-20176\n* Fix minor information leak in rdpdr_process - CVE-2018-8791\n* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n* Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n* Fix Denial of Service in process_secondary_order - CVE-2018-8799\n* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n* Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n* Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n* Fix Denial of Service in process_demand_active - CVE-2018-20178\n* Fix remote code execution in lspci_process - CVE-2018-20179\n* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n* Fix remote code execution in seamless_process - CVE-2018-20181\n* Fix remote code execution in seamless_process_line - CVE-2018-20182'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: seamless_process_line(const char *line, void *data)\n{\n\tchar *p, *l;\n\tchar *tok1, *tok2, *tok3, *tok4, *tok5, *tok6, *tok7, *tok8;\n\tunsigned long id, flags;\n\tchar *endptr;\n\n\tl = xstrdup(line);\n\tp = l;\n\n\tDEBUG_SEAMLESS((\"seamlessrdp got:%s\\n\", p));\n\n\ttok1 = seamless_get_token(&p);\n\ttok2 = seamless_get_token(&p);\n\ttok3 = seamless_get_token(&p);\n\ttok4 = seamless_get_token(&p);\n\ttok5 = seamless_get_token(&p);\n\ttok6 = seamless_get_token(&p);\n\ttok7 = seamless_get_token(&p);\n\ttok8 = seamless_get_token(&p);\n\n\tif (!strcmp(\"CREATE\", tok1))\n\t{\n\t\tunsigned long group, parent;\n\t\tif (!tok6)\n\t\t\treturn False;\n\n\t\tid = strtoul(tok3, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tgroup = strtoul(tok4, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tparent = strtoul(tok5, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tflags = strtoul(tok6, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tui_seamless_create_window(id, group, parent, flags);\n\t}\n\telse if (!strcmp(\"DESTROY\", tok1))\n\t{\n\t\tif (!tok4)\n\t\t\treturn False;\n\n\t\tid = strtoul(tok3, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tflags = strtoul(tok4, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tui_seamless_destroy_window(id, flags);\n\n\t}\n\telse if (!strcmp(\"DESTROYGRP\", tok1))\n\t{\n\t\tif (!tok4)\n\t\t\treturn False;\n\n\t\tid = strtoul(tok3, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tflags = strtoul(tok4, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tui_seamless_destroy_group(id, flags);\n\t}\n\telse if (!strcmp(\"SETICON\", tok1))\n\t{\n\t\tint chunk, width, height, len;\n\t\tchar byte[3];\n\n\t\tif (!tok8)\n\t\t\treturn False;\n\n\t\tid = strtoul(tok3, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tchunk = strtoul(tok4, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\twidth = strtoul(tok6, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\theight = strtoul(tok7, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tbyte[2] = '\\0';\n\t\tlen = 0;\n\t\twhile (*tok8 != '\\0')\n\t\t{\n\t\t\tbyte[0] = *tok8;\n\t\t\ttok8++;\n\t\t\tif (*tok8 == '\\0')\n\t\t\t\treturn False;\n\t\t\tbyte[1] = *tok8;\n\t\t\ttok8++;\n\n\t\t\ticon_buf[len] = strtol(byte, NULL, 16);\n\t\t\tlen++;\n\t\t}\n\n\t\tui_seamless_seticon(id, tok5, width, height, chunk, icon_buf, len);\n\t}\n\telse if (!strcmp(\"DELICON\", tok1))\n\t{\n\t\tint width, height;\n\n\t\tif (!tok6)\n\t\t\treturn False;\n\n\t\tid = strtoul(tok3, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\twidth = strtoul(tok5, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\theight = strtoul(tok6, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tui_seamless_delicon(id, tok4, width, height);\n\t}\n\telse if (!strcmp(\"POSITION\", tok1))\n\t{\n\t\tint x, y, width, height;\n\n\t\tif (!tok8)\n\t\t\treturn False;\n\n\t\tid = strtoul(tok3, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tx = strtol(tok4, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\t\ty = strtol(tok5, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\twidth = strtol(tok6, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\t\theight = strtol(tok7, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tflags = strtoul(tok8, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tui_seamless_move_window(id, x, y, width, height, flags);\n\t}\n\telse if (!strcmp(\"ZCHANGE\", tok1))\n\t{\n\t\tunsigned long behind;\n\n\t\tid = strtoul(tok3, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tbehind = strtoul(tok4, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tflags = strtoul(tok5, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tui_seamless_restack_window(id, behind, flags);\n\t}\n\telse if (!strcmp(\"TITLE\", tok1))\n\t{\n\t\tif (!tok5)\n\t\t\treturn False;\n\n\t\tid = strtoul(tok3, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tflags = strtoul(tok5, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tui_seamless_settitle(id, tok4, flags);\n\t}\n\telse if (!strcmp(\"STATE\", tok1))\n\t{\n\t\tunsigned int state;\n\n\t\tif (!tok5)\n\t\t\treturn False;\n\n\t\tid = strtoul(tok3, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tstate = strtoul(tok4, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tflags = strtoul(tok5, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tui_seamless_setstate(id, state, flags);\n\t}\n\telse if (!strcmp(\"DEBUG\", tok1))\n\t{\n\t\tDEBUG_SEAMLESS((\"SeamlessRDP:%s\\n\", line));\n\t}\n\telse if (!strcmp(\"SYNCBEGIN\", tok1))\n\t{\n\t\tif (!tok3)\n\t\t\treturn False;\n\n\t\tflags = strtoul(tok3, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tui_seamless_syncbegin(flags);\n\t}\n\telse if (!strcmp(\"SYNCEND\", tok1))\n\t{\n\t\tif (!tok3)\n\t\t\treturn False;\n\n\t\tflags = strtoul(tok3, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\t/* do nothing, currently */\n\t}\n\telse if (!strcmp(\"HELLO\", tok1))\n\t{\n\t\tif (!tok3)\n\t\t\treturn False;\n\n\t\tflags = strtoul(tok3, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tui_seamless_begin(! !(flags & SEAMLESSRDP_HELLO_HIDDEN));\n\t}\n\telse if (!strcmp(\"ACK\", tok1))\n\t{\n\t\tunsigned int serial;\n\n\t\tserial = strtoul(tok3, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tui_seamless_ack(serial);\n\t}\n\telse if (!strcmp(\"HIDE\", tok1))\n\t{\n\t\tif (!tok3)\n\t\t\treturn False;\n\n\t\tflags = strtoul(tok3, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tui_seamless_hide_desktop();\n\t}\n\telse if (!strcmp(\"UNHIDE\", tok1))\n\t{\n\t\tif (!tok3)\n\t\t\treturn False;\n\n\t\tflags = strtoul(tok3, &endptr, 0);\n\t\tif (*endptr)\n\t\t\treturn False;\n\n\t\tui_seamless_unhide_desktop();\n\t}\n\n\n\txfree(l);\n\treturn True;\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: BOOL nsc_process_message(NSC_CONTEXT* context, UINT16 bpp,\n UINT32 width, UINT32 height,\n const BYTE* data, UINT32 length,\n BYTE* pDstData, UINT32 DstFormat,\n UINT32 nDstStride,\n UINT32 nXDst, UINT32 nYDst, UINT32 nWidth,\n UINT32 nHeight, UINT32 flip)\n{\n\twStream* s;\n\tBOOL ret;\n\ts = Stream_New((BYTE*)data, length);\n\n\tif (!s)\n\t\treturn FALSE;\n\n\tif (nDstStride == 0)\n\t\tnDstStride = nWidth * GetBytesPerPixel(DstFormat);\n\n\tswitch (bpp)\n\t{\n\t\tcase 32:\n\t\t\tcontext->format = PIXEL_FORMAT_BGRA32;\n\t\t\tbreak;\n\n\t\tcase 24:\n\t\t\tcontext->format = PIXEL_FORMAT_BGR24;\n\t\t\tbreak;\n\n\t\tcase 16:\n\t\t\tcontext->format = PIXEL_FORMAT_BGR16;\n\t\t\tbreak;\n\n\t\tcase 8:\n\t\t\tcontext->format = PIXEL_FORMAT_RGB8;\n\t\t\tbreak;\n\n\t\tcase 4:\n\t\t\tcontext->format = PIXEL_FORMAT_A4;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tStream_Free(s, TRUE);\n\t\t\treturn FALSE;\n\t}\n\n\tcontext->width = width;\n\tcontext->height = height;\n\tret = nsc_context_initialize(context, s);\n\tStream_Free(s, FALSE);\n\n\tif (!ret)\n\t\treturn FALSE;\n\n\t/* RLE decode */\n\tPROFILER_ENTER(context->priv->prof_nsc_rle_decompress_data)\n\tnsc_rle_decompress_data(context);\n\tPROFILER_EXIT(context->priv->prof_nsc_rle_decompress_data)\n\t/* Colorloss recover, Chroma supersample and AYCoCg to ARGB Conversion in one step */\n\tPROFILER_ENTER(context->priv->prof_nsc_decode)\n\tcontext->decode(context);\n\tPROFILER_EXIT(context->priv->prof_nsc_decode)\n\n\tif (!freerdp_image_copy(pDstData, DstFormat, nDstStride, nXDst, nYDst,\n\t width, height, context->BitmapData,\n\t PIXEL_FORMAT_BGRA32, 0, 0, 0, NULL, flip))\n\t\treturn FALSE;\n\n\treturn TRUE;\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(wStream* s, NTLM_MESSAGE_FIELDS* fields)\n{\n\tif (Stream_GetRemainingLength(s) < 8)\n\t\treturn -1;\n\n\tStream_Read_UINT16(s, fields->Len); /* Len (2 bytes) */\n\tStream_Read_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */\n\tStream_Read_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */\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 *) gdImageWBMPPtr(gdImagePtr im, int *size, int fg)\n{\n\tvoid *rv;\n\tgdIOCtx *out = gdNewDynamicCtx(2048, NULL);\n\tif (out == NULL) return NULL;\n\tgdImageWBMPCtx(im, fg, out);\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': 'Fix #492: Potential double-free in gdImage*Ptr()\n\nWhenever `gdImage*Ptr()` calls `gdImage*Ctx()` and the latter fails, we\nmust not call `gdDPExtractData()`; otherwise a double-free would\nhappen. Since `gdImage*Ctx()` are void functions, and we can't change\nthat for BC reasons, we're introducing static helpers which are used\ninternally.\n\nWe're adding a regression test for `gdImageJpegPtr()`, but not for\n`gdImageGifPtr()` and `gdImageWbmpPtr()` since we don't know how to\ntrigger failure of the respective `gdImage*Ctx()` calls.\n\nThis potential security issue has been reported by Solmaz Salimi (aka.\nRooney).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void 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\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\t}\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': 'Sync with upstream\n\nEven though libgd/libgd#492 is not a relevant bug fix for PHP, since\nthe binding doesn't use the `gdImage*Ptr()` functions at all, we're\nporting the fix to stay in sync here.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static struct ldb_parse_tree *ldb_parse_simple(TALLOC_CTX *mem_ctx, const char **s)\n{\n\tchar *attr, *value;\n\tstruct ldb_parse_tree *ret;\n\tenum ldb_parse_op filtertype;\n\n\tret = talloc(mem_ctx, struct ldb_parse_tree);\n\tif (!ret) {\n\t\terrno = ENOMEM;\n\t\treturn NULL;\n\t}\n\n\tfiltertype = ldb_parse_filtertype(ret, &attr, &value, s);\n\tif (!filtertype) {\n\t\ttalloc_free(ret);\n\t\treturn NULL;\n\t}\n\n\tswitch (filtertype) {\n\n\t\tcase LDB_OP_PRESENT:\n\t\t\tret->operation = LDB_OP_PRESENT;\n\t\t\tret->u.present.attr = attr;\n\t\t\tbreak;\n\n\t\tcase LDB_OP_EQUALITY:\n\n\t\t\tif (strcmp(value, \"*\") == 0) {\n\t\t\t\tret->operation = LDB_OP_PRESENT;\n\t\t\t\tret->u.present.attr = attr;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (ldb_parse_find_wildcard(value) != NULL) {\n\t\t\t\tret->operation = LDB_OP_SUBSTRING;\n\t\t\t\tret->u.substring.attr = attr;\n\t\t\t\tret->u.substring.start_with_wildcard = 0;\n\t\t\t\tret->u.substring.end_with_wildcard = 0;\n\t\t\t\tret->u.substring.chunks = ldb_wildcard_decode(ret, value);\n\t\t\t\tif (ret->u.substring.chunks == NULL){\n\t\t\t\t\ttalloc_free(ret);\n\t\t\t\t\treturn NULL;\n\t\t\t\t}\n\t\t\t\tif (value[0] == '*')\n\t\t\t\t\tret->u.substring.start_with_wildcard = 1;\n\t\t\t\tif (value[strlen(value) - 1] == '*')\n\t\t\t\t\tret->u.substring.end_with_wildcard = 1;\n\t\t\t\ttalloc_free(value);\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tret->operation = LDB_OP_EQUALITY;\n\t\t\tret->u.equality.attr = attr;\n\t\t\tret->u.equality.value = ldb_binary_decode(ret, value);\n\t\t\tif (ret->u.equality.value.data == NULL) {\n\t\t\t\ttalloc_free(ret);\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\ttalloc_free(value);\n\t\t\tbreak;\n\n\t\tcase LDB_OP_GREATER:\n\t\t\tret->operation = LDB_OP_GREATER;\n\t\t\tret->u.comparison.attr = attr;\n\t\t\tret->u.comparison.value = ldb_binary_decode(ret, value);\n\t\t\tif (ret->u.comparison.value.data == NULL) {\n\t\t\t\ttalloc_free(ret);\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\ttalloc_free(value);\n\t\t\tbreak;\n\n\t\tcase LDB_OP_LESS:\n\t\t\tret->operation = LDB_OP_LESS;\n\t\t\tret->u.comparison.attr = attr;\n\t\t\tret->u.comparison.value = ldb_binary_decode(ret, value);\n\t\t\tif (ret->u.comparison.value.data == NULL) {\n\t\t\t\ttalloc_free(ret);\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\ttalloc_free(value);\n\t\t\tbreak;\n\n\t\tcase LDB_OP_APPROX:\n\t\t\tret->operation = LDB_OP_APPROX;\n\t\t\tret->u.comparison.attr = attr;\n\t\t\tret->u.comparison.value = ldb_binary_decode(ret, value);\n\t\t\tif (ret->u.comparison.value.data == NULL) {\n\t\t\t\ttalloc_free(ret);\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\ttalloc_free(value);\n\t\t\tbreak;\n\n\t\tcase LDB_OP_EXTENDED:\n\n\t\t\tret = ldb_parse_extended(ret, attr, value);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\ttalloc_free(ret);\n\t\t\treturn NULL;\n\t}\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'CVE-2019-3824 ldb: ldb_parse_tree use talloc_zero\n\nInitialise the created ldb_parse_tree with talloc_zero, this ensures\nthat it is correctly initialised if inadvertently passed to a function\nexpecting a different operation type.\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=13773\n\nSigned-off-by: Gary Lockyer \nReviewed-by: Andrew Bartlett '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,\n\t\t\t\t struct bpf_insn *insn,\n\t\t\t\t const struct bpf_reg_state *ptr_reg,\n\t\t\t\t const struct bpf_reg_state *off_reg)\n{\n\tstruct bpf_verifier_state *vstate = env->cur_state;\n\tstruct bpf_func_state *state = vstate->frame[vstate->curframe];\n\tstruct bpf_reg_state *regs = state->regs, *dst_reg;\n\tbool known = tnum_is_const(off_reg->var_off);\n\ts64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,\n\t smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;\n\tu64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,\n\t umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;\n\tu32 dst = insn->dst_reg, src = insn->src_reg;\n\tu8 opcode = BPF_OP(insn->code);\n\n\tdst_reg = ®s[dst];\n\n\tif ((known && (smin_val != smax_val || umin_val != umax_val)) ||\n\t smin_val > smax_val || umin_val > umax_val) {\n\t\t/* Taint dst register if offset had invalid bounds derived from\n\t\t * e.g. dead branches.\n\t\t */\n\t\t__mark_reg_unknown(dst_reg);\n\t\treturn 0;\n\t}\n\n\tif (BPF_CLASS(insn->code) != BPF_ALU64) {\n\t\t/* 32-bit ALU ops on pointers produce (meaningless) scalars */\n\t\tverbose(env,\n\t\t\t\"R%d 32-bit pointer arithmetic prohibited\\n\",\n\t\t\tdst);\n\t\treturn -EACCES;\n\t}\n\n\tswitch (ptr_reg->type) {\n\tcase PTR_TO_MAP_VALUE_OR_NULL:\n\t\tverbose(env, \"R%d pointer arithmetic on %s prohibited, null-check it first\\n\",\n\t\t\tdst, reg_type_str[ptr_reg->type]);\n\t\treturn -EACCES;\n\tcase CONST_PTR_TO_MAP:\n\tcase PTR_TO_PACKET_END:\n\tcase PTR_TO_SOCKET:\n\tcase PTR_TO_SOCKET_OR_NULL:\n\t\tverbose(env, \"R%d pointer arithmetic on %s prohibited\\n\",\n\t\t\tdst, reg_type_str[ptr_reg->type]);\n\t\treturn -EACCES;\n\tcase PTR_TO_MAP_VALUE:\n\t\tif (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {\n\t\t\tverbose(env, \"R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\\n\",\n\t\t\t\toff_reg == dst_reg ? dst : src);\n\t\t\treturn -EACCES;\n\t\t}\n\t\t/* fall-through */\n\tdefault:\n\t\tbreak;\n\t}\n\n\t/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.\n\t * The id may be overwritten later if we create a new variable offset.\n\t */\n\tdst_reg->type = ptr_reg->type;\n\tdst_reg->id = ptr_reg->id;\n\n\tif (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||\n\t !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))\n\t\treturn -EINVAL;\n\n\tswitch (opcode) {\n\tcase BPF_ADD:\n\t\t/* We can take a fixed offset as long as it doesn't overflow\n\t\t * the s32 'off' field\n\t\t */\n\t\tif (known && (ptr_reg->off + smin_val ==\n\t\t\t (s64)(s32)(ptr_reg->off + smin_val))) {\n\t\t\t/* pointer += K. Accumulate it into fixed offset */\n\t\t\tdst_reg->smin_value = smin_ptr;\n\t\t\tdst_reg->smax_value = smax_ptr;\n\t\t\tdst_reg->umin_value = umin_ptr;\n\t\t\tdst_reg->umax_value = umax_ptr;\n\t\t\tdst_reg->var_off = ptr_reg->var_off;\n\t\t\tdst_reg->off = ptr_reg->off + smin_val;\n\t\t\tdst_reg->raw = ptr_reg->raw;\n\t\t\tbreak;\n\t\t}\n\t\t/* A new variable offset is created. Note that off_reg->off\n\t\t * == 0, since it's a scalar.\n\t\t * dst_reg gets the pointer type and since some positive\n\t\t * integer value was added to the pointer, give it a new 'id'\n\t\t * if it's a PTR_TO_PACKET.\n\t\t * this creates a new 'base' pointer, off_reg (variable) gets\n\t\t * added into the variable offset, and we copy the fixed offset\n\t\t * from ptr_reg.\n\t\t */\n\t\tif (signed_add_overflows(smin_ptr, smin_val) ||\n\t\t signed_add_overflows(smax_ptr, smax_val)) {\n\t\t\tdst_reg->smin_value = S64_MIN;\n\t\t\tdst_reg->smax_value = S64_MAX;\n\t\t} else {\n\t\t\tdst_reg->smin_value = smin_ptr + smin_val;\n\t\t\tdst_reg->smax_value = smax_ptr + smax_val;\n\t\t}\n\t\tif (umin_ptr + umin_val < umin_ptr ||\n\t\t umax_ptr + umax_val < umax_ptr) {\n\t\t\tdst_reg->umin_value = 0;\n\t\t\tdst_reg->umax_value = U64_MAX;\n\t\t} else {\n\t\t\tdst_reg->umin_value = umin_ptr + umin_val;\n\t\t\tdst_reg->umax_value = umax_ptr + umax_val;\n\t\t}\n\t\tdst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);\n\t\tdst_reg->off = ptr_reg->off;\n\t\tdst_reg->raw = ptr_reg->raw;\n\t\tif (reg_is_pkt_pointer(ptr_reg)) {\n\t\t\tdst_reg->id = ++env->id_gen;\n\t\t\t/* something was added to pkt_ptr, set range to zero */\n\t\t\tdst_reg->raw = 0;\n\t\t}\n\t\tbreak;\n\tcase BPF_SUB:\n\t\tif (dst_reg == off_reg) {\n\t\t\t/* scalar -= pointer. Creates an unknown scalar */\n\t\t\tverbose(env, \"R%d tried to subtract pointer from scalar\\n\",\n\t\t\t\tdst);\n\t\t\treturn -EACCES;\n\t\t}\n\t\t/* We don't allow subtraction from FP, because (according to\n\t\t * test_verifier.c test \"invalid fp arithmetic\", JITs might not\n\t\t * be able to deal with it.\n\t\t */\n\t\tif (ptr_reg->type == PTR_TO_STACK) {\n\t\t\tverbose(env, \"R%d subtraction from stack pointer prohibited\\n\",\n\t\t\t\tdst);\n\t\t\treturn -EACCES;\n\t\t}\n\t\tif (known && (ptr_reg->off - smin_val ==\n\t\t\t (s64)(s32)(ptr_reg->off - smin_val))) {\n\t\t\t/* pointer -= K. Subtract it from fixed offset */\n\t\t\tdst_reg->smin_value = smin_ptr;\n\t\t\tdst_reg->smax_value = smax_ptr;\n\t\t\tdst_reg->umin_value = umin_ptr;\n\t\t\tdst_reg->umax_value = umax_ptr;\n\t\t\tdst_reg->var_off = ptr_reg->var_off;\n\t\t\tdst_reg->id = ptr_reg->id;\n\t\t\tdst_reg->off = ptr_reg->off - smin_val;\n\t\t\tdst_reg->raw = ptr_reg->raw;\n\t\t\tbreak;\n\t\t}\n\t\t/* A new variable offset is created. If the subtrahend is known\n\t\t * nonnegative, then any reg->range we had before is still good.\n\t\t */\n\t\tif (signed_sub_overflows(smin_ptr, smax_val) ||\n\t\t signed_sub_overflows(smax_ptr, smin_val)) {\n\t\t\t/* Overflow possible, we know nothing */\n\t\t\tdst_reg->smin_value = S64_MIN;\n\t\t\tdst_reg->smax_value = S64_MAX;\n\t\t} else {\n\t\t\tdst_reg->smin_value = smin_ptr - smax_val;\n\t\t\tdst_reg->smax_value = smax_ptr - smin_val;\n\t\t}\n\t\tif (umin_ptr < umax_val) {\n\t\t\t/* Overflow possible, we know nothing */\n\t\t\tdst_reg->umin_value = 0;\n\t\t\tdst_reg->umax_value = U64_MAX;\n\t\t} else {\n\t\t\t/* Cannot overflow (as long as bounds are consistent) */\n\t\t\tdst_reg->umin_value = umin_ptr - umax_val;\n\t\t\tdst_reg->umax_value = umax_ptr - umin_val;\n\t\t}\n\t\tdst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);\n\t\tdst_reg->off = ptr_reg->off;\n\t\tdst_reg->raw = ptr_reg->raw;\n\t\tif (reg_is_pkt_pointer(ptr_reg)) {\n\t\t\tdst_reg->id = ++env->id_gen;\n\t\t\t/* something was added to pkt_ptr, set range to zero */\n\t\t\tif (smin_val < 0)\n\t\t\t\tdst_reg->raw = 0;\n\t\t}\n\t\tbreak;\n\tcase BPF_AND:\n\tcase BPF_OR:\n\tcase BPF_XOR:\n\t\t/* bitwise ops on pointers are troublesome, prohibit. */\n\t\tverbose(env, \"R%d bitwise operator %s on pointer prohibited\\n\",\n\t\t\tdst, bpf_alu_string[opcode >> 4]);\n\t\treturn -EACCES;\n\tdefault:\n\t\t/* other operators (e.g. MUL,LSH) produce non-pointer results */\n\t\tverbose(env, \"R%d pointer arithmetic with %s operator prohibited\\n\",\n\t\t\tdst, bpf_alu_string[opcode >> 4]);\n\t\treturn -EACCES;\n\t}\n\n\tif (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))\n\t\treturn -EINVAL;\n\n\t__update_reg_bounds(dst_reg);\n\t__reg_deduce_bounds(dst_reg);\n\t__reg_bound_offset(dst_reg);\n\n\t/* For unprivileged we require that resulting offset must be in bounds\n\t * in order to be able to sanitize access later on.\n\t */\n\tif (!env->allow_ptr_leaks) {\n\t\tif (dst_reg->type == PTR_TO_MAP_VALUE &&\n\t\t check_map_access(env, dst, dst_reg->off, 1, false)) {\n\t\t\tverbose(env, \"R%d pointer arithmetic of map value goes out of range, \"\n\t\t\t\t\"prohibited for !root\\n\", dst);\n\t\t\treturn -EACCES;\n\t\t} else if (dst_reg->type == PTR_TO_STACK &&\n\t\t\t check_stack_access(env, dst_reg, dst_reg->off +\n\t\t\t\t\t dst_reg->var_off.value, 1)) {\n\t\t\tverbose(env, \"R%d stack pointer arithmetic goes out of range, \"\n\t\t\t\t\"prohibited for !root\\n\", dst);\n\t\t\treturn -EACCES;\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', 'CWE-189'], 'message': 'bpf: prevent out of bounds speculation on pointer arithmetic\n\nJann reported that the original commit back in b2157399cc98\n(\"bpf: prevent out-of-bounds speculation\") was not sufficient\nto stop CPU from speculating out of bounds memory access:\nWhile b2157399cc98 only focussed on masking array map access\nfor unprivileged users for tail calls and data access such\nthat the user provided index gets sanitized from BPF program\nand syscall side, there is still a more generic form affected\nfrom BPF programs that applies to most maps that hold user\ndata in relation to dynamic map access when dealing with\nunknown scalars or \"slow\" known scalars as access offset, for\nexample:\n\n - Load a map value pointer into R6\n - Load an index into R7\n - Do a slow computation (e.g. with a memory dependency) that\n loads a limit into R8 (e.g. load the limit from a map for\n high latency, then mask it to make the verifier happy)\n - Exit if R7 >= R8 (mispredicted branch)\n - Load R0 = R6[R7]\n - Load R0 = R6[R0]\n\nFor unknown scalars there are two options in the BPF verifier\nwhere we could derive knowledge from in order to guarantee\nsafe access to the memory: i) While /<=/>= variants won't\nallow to derive any lower or upper bounds from the unknown\nscalar where it would be safe to add it to the map value\npointer, it is possible through ==/!= test however. ii) another\noption is to transform the unknown scalar into a known scalar,\nfor example, through ALU ops combination such as R &= \nfollowed by R |= or any similar combination where the\noriginal information from the unknown scalar would be destroyed\nentirely leaving R with a constant. The initial slow load still\nprecedes the latter ALU ops on that register, so the CPU\nexecutes speculatively from that point. Once we have the known\nscalar, any compare operation would work then. A third option\nonly involving registers with known scalars could be crafted\nas described in [0] where a CPU port (e.g. Slow Int unit)\nwould be filled with many dependent computations such that\nthe subsequent condition depending on its outcome has to wait\nfor evaluation on its execution port and thereby executing\nspeculatively if the speculated code can be scheduled on a\ndifferent execution port, or any other form of mistraining\nas described in [1], for example. Given this is not limited\nto only unknown scalars, not only map but also stack access\nis affected since both is accessible for unprivileged users\nand could potentially be used for out of bounds access under\nspeculation.\n\nIn order to prevent any of these cases, the verifier is now\nsanitizing pointer arithmetic on the offset such that any\nout of bounds speculation would be masked in a way where the\npointer arithmetic result in the destination register will\nstay unchanged, meaning offset masked into zero similar as\nin array_index_nospec() case. With regards to implementation,\nthere are three options that were considered: i) new insn\nfor sanitation, ii) push/pop insn and sanitation as inlined\nBPF, iii) reuse of ax register and sanitation as inlined BPF.\n\nOption i) has the downside that we end up using from reserved\nbits in the opcode space, but also that we would require\neach JIT to emit masking as native arch opcodes meaning\nmitigation would have slow adoption till everyone implements\nit eventually which is counter-productive. Option ii) and iii)\nhave both in common that a temporary register is needed in\norder to implement the sanitation as inlined BPF since we\nare not allowed to modify the source register. While a push /\npop insn in ii) would be useful to have in any case, it\nrequires once again that every JIT needs to implement it\nfirst. While possible, amount of changes needed would also\nbe unsuitable for a -stable patch. Therefore, the path which\nhas fewer changes, less BPF instructions for the mitigation\nand does not require anything to be changed in the JITs is\noption iii) which this work is pursuing. The ax register is\nalready mapped to a register in all JITs (modulo arm32 where\nit's mapped to stack as various other BPF registers there)\nand used in constant blinding for JITs-only so far. It can\nbe reused for verifier rewrites under certain constraints.\nThe interpreter's tmp \"register\" has therefore been remapped\ninto extending the register set with hidden ax register and\nreusing that for a number of instructions that needed the\nprior temporary variable internally (e.g. div, mod). This\nallows for zero increase in stack space usage in the interpreter,\nand enables (restricted) generic use in rewrites otherwise as\nlong as such a patchlet does not make use of these instructions.\nThe sanitation mask is dynamic and relative to the offset the\nmap value or stack pointer currently holds.\n\nThere are various cases that need to be taken under consideration\nfor the masking, e.g. such operation could look as follows:\nptr += val or val += ptr or ptr -= val. Thus, the value to be\nsanitized could reside either in source or in destination\nregister, and the limit is different depending on whether\nthe ALU op is addition or subtraction and depending on the\ncurrent known and bounded offset. The limit is derived as\nfollows: limit := max_value_size - (smin_value + off). For\nsubtraction: limit := umax_value + off. This holds because\nwe do not allow any pointer arithmetic that would\ntemporarily go out of bounds or would have an unknown\nvalue with mixed signed bounds where it is unclear at\nverification time whether the actual runtime value would\nbe either negative or positive. For example, we have a\nderived map pointer value with constant offset and bounded\none, so limit based on smin_value works because the verifier\nrequires that statically analyzed arithmetic on the pointer\nmust be in bounds, and thus it checks if resulting\nsmin_value + off and umax_value + off is still within map\nvalue bounds at time of arithmetic in addition to time of\naccess. Similarly, for the case of stack access we derive\nthe limit as follows: MAX_BPF_STACK + off for subtraction\nand -off for the case of addition where off := ptr_reg->off +\nptr_reg->var_off.value. Subtraction is a special case for\nthe masking which can be in form of ptr += -val, ptr -= -val,\nor ptr -= val. In the first two cases where we know that\nthe value is negative, we need to temporarily negate the\nvalue in order to do the sanitation on a positive value\nwhere we later swap the ALU op, and restore original source\nregister if the value was in source.\n\nThe sanitation of pointer arithmetic alone is still not fully\nsufficient as is, since a scenario like the following could\nhappen ...\n\n PTR += 0x1000 (e.g. K-based imm)\n PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON\n PTR += 0x1000\n PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON\n [...]\n\n... which under speculation could end up as ...\n\n PTR += 0x1000\n PTR -= 0 [ truncated by mitigation ]\n PTR += 0x1000\n PTR -= 0 [ truncated by mitigation ]\n [...]\n\n... and therefore still access out of bounds. To prevent such\ncase, the verifier is also analyzing safety for potential out\nof bounds access under speculative execution. Meaning, it is\nalso simulating pointer access under truncation. We therefore\n\"branch off\" and push the current verification state after the\nALU operation with known 0 to the verification stack for later\nanalysis. Given the current path analysis succeeded it is\nlikely that the one under speculation can be pruned. In any\ncase, it is also subject to existing complexity limits and\ntherefore anything beyond this point will be rejected. In\nterms of pruning, it needs to be ensured that the verification\nstate from speculative execution simulation must never prune\na non-speculative execution path, therefore, we mark verifier\nstate accordingly at the time of push_stack(). If verifier\ndetects out of bounds access under speculative execution from\none of the possible paths that includes a truncation, it will\nreject such program.\n\nGiven we mask every reg-based pointer arithmetic for\nunprivileged programs, we've been looking into how it could\naffect real-world programs in terms of size increase. As the\nmajority of programs are targeted for privileged-only use\ncase, we've unconditionally enabled masking (with its alu\nrestrictions on top of it) for privileged programs for the\nsake of testing in order to check i) whether they get rejected\nin its current form, and ii) by how much the number of\ninstructions and size will increase. We've tested this by\nusing Katran, Cilium and test_l4lb from the kernel selftests.\nFor Katran we've evaluated balancer_kern.o, Cilium bpf_lxc.o\nand an older test object bpf_lxc_opt_-DUNKNOWN.o and l4lb\nwe've used test_l4lb.o as well as test_l4lb_noinline.o. We\nfound that none of the programs got rejected by the verifier\nwith this change, and that impact is rather minimal to none.\nbalancer_kern.o had 13,904 bytes (1,738 insns) xlated and\n7,797 bytes JITed before and after the change. Most complex\nprogram in bpf_lxc.o had 30,544 bytes (3,817 insns) xlated\nand 18,538 bytes JITed before and after and none of the other\ntail call programs in bpf_lxc.o had any changes either. For\nthe older bpf_lxc_opt_-DUNKNOWN.o object we found a small\nincrease from 20,616 bytes (2,576 insns) and 12,536 bytes JITed\nbefore to 20,664 bytes (2,582 insns) and 12,558 bytes JITed\nafter the change. Other programs from that object file had\nsimilar small increase. Both test_l4lb.o had no change and\nremained at 6,544 bytes (817 insns) xlated and 3,401 bytes\nJITed and for test_l4lb_noinline.o constant at 5,080 bytes\n(634 insns) xlated and 3,313 bytes JITed. This can be explained\nin that LLVM typically optimizes stack based pointer arithmetic\nby using K-based operations and that use of dynamic map access\nis not overly frequent. However, in future we may decide to\noptimize the algorithm further under known guarantees from\nbranch and value speculation. Latter seems also unclear in\nterms of prediction heuristics that today's CPUs apply as well\nas whether there could be collisions in e.g. the predictor's\nValue History/Pattern Table for triggering out of bounds access,\nthus masking is performed unconditionally at this point but could\nbe subject to relaxation later on. We were generally also\nbrainstorming various other approaches for mitigation, but the\nblocker was always lack of available registers at runtime and/or\noverhead for runtime tracking of limits belonging to a specific\npointer. Thus, we found this to be minimally intrusive under\ngiven constraints.\n\nWith that in place, a simple example with sanitized access on\nunprivileged load at post-verification time looks as follows:\n\n # bpftool prog dump xlated id 282\n [...]\n 28: (79) r1 = *(u64 *)(r7 +0)\n 29: (79) r2 = *(u64 *)(r7 +8)\n 30: (57) r1 &= 15\n 31: (79) r3 = *(u64 *)(r0 +4608)\n 32: (57) r3 &= 1\n 33: (47) r3 |= 1\n 34: (2d) if r2 > r3 goto pc+19\n 35: (b4) (u32) r11 = (u32) 20479 |\n 36: (1f) r11 -= r2 | Dynamic sanitation for pointer\n 37: (4f) r11 |= r2 | arithmetic with registers\n 38: (87) r11 = -r11 | containing bounded or known\n 39: (c7) r11 s>>= 63 | scalars in order to prevent\n 40: (5f) r11 &= r2 | out of bounds speculation.\n 41: (0f) r4 += r11 |\n 42: (71) r4 = *(u8 *)(r4 +0)\n 43: (6f) r4 <<= r1\n [...]\n\nFor the case where the scalar sits in the destination register\nas opposed to the source register, the following code is emitted\nfor the above example:\n\n [...]\n 16: (b4) (u32) r11 = (u32) 20479\n 17: (1f) r11 -= r2\n 18: (4f) r11 |= r2\n 19: (87) r11 = -r11\n 20: (c7) r11 s>>= 63\n 21: (5f) r2 &= r11\n 22: (0f) r2 += r0\n 23: (61) r0 = *(u32 *)(r2 +0)\n [...]\n\nJIT blinding example with non-conflicting use of r10:\n\n [...]\n d5:\tje 0x0000000000000106 _\n d7:\tmov 0x0(%rax),%edi |\n da:\tmov $0xf153246,%r10d | Index load from map value and\n e0:\txor $0xf153259,%r10 | (const blinded) mask with 0x1f.\n e7:\tand %r10,%rdi |_\n ea:\tmov $0x2f,%r10d |\n f0:\tsub %rdi,%r10 | Sanitized addition. Both use r10\n f3:\tor %rdi,%r10 | but do not interfere with each\n f6:\tneg %r10 | other. (Neither do these instructions\n f9:\tsar $0x3f,%r10 | interfere with the use of ax as temp\n fd:\tand %r10,%rdi | in interpreter.)\n 100:\tadd %rax,%rdi |_\n 103:\tmov 0x0(%rdi),%eax\n [...]\n\nTested that it fixes Jann's reproducer, and also checked that test_verifier\nand test_progs suite with interpreter, JIT and JIT with hardening enabled\non x86-64 and arm64 runs successfully.\n\n [0] Speculose: Analyzing the Security Implications of Speculative\n Execution in CPUs, Giorgi Maisuradze and Christian Rossow,\n https://arxiv.org/pdf/1801.04084.pdf\n\n [1] A Systematic Evaluation of Transient Execution Attacks and\n Defenses, Claudio Canella, Jo Van Bulck, Michael Schwarz,\n Moritz Lipp, Benjamin von Berg, Philipp Ortner, Frank Piessens,\n Dmitry Evtyushkin, Daniel Gruss,\n https://arxiv.org/pdf/1811.05441.pdf\n\nFixes: b2157399cc98 (\"bpf: prevent out-of-bounds speculation\")\nReported-by: Jann Horn \nSigned-off-by: Daniel Borkmann \nAcked-by: Alexei Starovoitov \nSigned-off-by: Alexei Starovoitov '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static size_t WritePSDChannel(const PSDInfo *psd_info,\n const ImageInfo *image_info,Image *image,Image *next_image,\n const QuantumType quantum_type, unsigned char *compact_pixels,\n MagickOffsetType size_offset,const MagickBooleanType separate,\n const CompressionType compression,ExceptionInfo *exception)\n{\n MagickBooleanType\n monochrome;\n\n QuantumInfo\n *quantum_info;\n\n register const Quantum\n *p;\n\n register ssize_t\n i;\n\n size_t\n count,\n length;\n\n ssize_t\n y;\n\n unsigned char\n *pixels;\n\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n\n#define CHUNK 16384\n\n int\n flush,\n level;\n\n unsigned char\n *compressed_pixels;\n\n z_stream\n stream;\n\n compressed_pixels=(unsigned char *) NULL;\n flush=Z_NO_FLUSH;\n#endif\n count=0;\n if (separate != MagickFalse)\n {\n size_offset=TellBlob(image)+2;\n count+=WriteCompressionStart(psd_info,image,next_image,compression,1);\n }\n if (next_image->depth > 8)\n next_image->depth=16;\n monochrome=IsImageMonochrome(image) && (image->depth == 1) ?\n MagickTrue : MagickFalse;\n quantum_info=AcquireQuantumInfo(image_info,next_image);\n if (quantum_info == (QuantumInfo *) NULL)\n return(0);\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n if (compression == ZipCompression)\n {\n compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK,\n sizeof(*compressed_pixels));\n if (compressed_pixels == (unsigned char *) NULL)\n {\n quantum_info=DestroyQuantumInfo(quantum_info);\n return(0);\n }\n memset(&stream,0,sizeof(stream));\n stream.data_type=Z_BINARY;\n level=Z_DEFAULT_COMPRESSION;\n if ((image_info->quality > 0 && image_info->quality < 10))\n level=(int) image_info->quality;\n if (deflateInit(&stream,level) != Z_OK)\n {\n quantum_info=DestroyQuantumInfo(quantum_info);\n return(0);\n }\n }\n#endif\n for (y=0; y < (ssize_t) next_image->rows; y++)\n {\n p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n if (monochrome != MagickFalse)\n for (i=0; i < (ssize_t) length; i++)\n pixels[i]=(~pixels[i]);\n if (compression == RLECompression)\n {\n length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,\n exception);\n count+=WriteBlob(image,length,compact_pixels);\n size_offset+=WritePSDOffset(psd_info,image,length,size_offset);\n }\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n else if (compression == ZipCompression)\n {\n stream.avail_in=(uInt) length;\n stream.next_in=(Bytef *) pixels;\n if (y == (ssize_t) next_image->rows-1)\n flush=Z_FINISH;\n do {\n stream.avail_out=(uInt) CHUNK;\n stream.next_out=(Bytef *) compressed_pixels;\n if (deflate(&stream,flush) == Z_STREAM_ERROR)\n break;\n length=(size_t) CHUNK-stream.avail_out;\n if (length > 0)\n count+=WriteBlob(image,length,compressed_pixels);\n } while (stream.avail_out == 0);\n }\n#endif\n else\n count+=WriteBlob(image,length,pixels);\n }\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n if (compression == ZipCompression)\n {\n (void) deflateEnd(&stream);\n compressed_pixels=(unsigned char *) RelinquishMagickMemory(\n compressed_pixels);\n }\n#endif\n quantum_info=DestroyQuantumInfo(quantum_info);\n return(count);\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/1451'" }, { "text": "[INST] Given the following code containing errors, provide Common 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_mp_signed_parse (EMailParserExtension *extension,\n EMailParser *parser,\n CamelMimePart *part,\n GString *part_id,\n GCancellable *cancellable,\n GQueue *out_mail_parts)\n{\n\tCamelMimePart *cpart = NULL;\n\tCamelMultipart *multipart;\n\tCamelCipherContext *cipher = NULL;\n\tCamelContentType *content_type;\n\tCamelSession *session;\n\tguint32 validity_type;\n\tCamelCipherValidity *valid;\n\tconst gchar *protocol = NULL;\n\tGError *local_error = NULL;\n\tgint i, nparts, len;\n\tgboolean secured;\n\n\t/* If the part is application/pgp-signature sub-part then skip it. */\n\tif (!CAMEL_IS_MULTIPART (part)) {\n\t\tcontent_type = camel_mime_part_get_content_type (part);\n\t\tif (camel_content_type_is (\n\t\t\tcontent_type, \"application\", \"pgp-signature\")) {\n\t\t\treturn TRUE;\n\t\t}\n\t}\n\n\tmultipart = (CamelMultipart *) camel_medium_get_content ((CamelMedium *) part);\n\tif (CAMEL_IS_MULTIPART_SIGNED (multipart)) {\n\t\tcpart = camel_multipart_get_part (\n\t\t\tmultipart, CAMEL_MULTIPART_SIGNED_CONTENT);\n\t}\n\n\tif (cpart == NULL) {\n\t\te_mail_parser_error (\n\t\t\tparser, out_mail_parts,\n\t\t\t_(\"Could not parse MIME message. \"\n\t\t\t\"Displaying as source.\"));\n\t\te_mail_parser_parse_part_as (\n\t\t\tparser, part, part_id,\n\t\t\t\"application/vnd.evolution.source\",\n\t\t\tcancellable, out_mail_parts);\n\n\t\treturn TRUE;\n\t}\n\n\tcontent_type = camel_data_wrapper_get_mime_type_field (\n\t\tCAMEL_DATA_WRAPPER (multipart));\n\tif (content_type != NULL)\n\t\tprotocol = camel_content_type_param (content_type, \"protocol\");\n\n\tsession = e_mail_parser_get_session (parser);\n\t/* FIXME: Should be done via a plugin interface */\n\t/* FIXME: duplicated in em-format-html-display.c */\n\tif (protocol != NULL) {\n#ifdef ENABLE_SMIME\n\t\tif (g_ascii_strcasecmp (\"application/x-pkcs7-signature\", protocol) == 0\n\t\t || g_ascii_strcasecmp (\"application/pkcs7-signature\", protocol) == 0) {\n\t\t\tcipher = camel_smime_context_new (session);\n\t\t\tvalidity_type = E_MAIL_PART_VALIDITY_SMIME;\n\t\t} else {\n#endif\n\t\t\tif (g_ascii_strcasecmp (\"application/pgp-signature\", protocol) == 0) {\n\t\t\t\tcipher = camel_gpg_context_new (session);\n\t\t\t\tvalidity_type = E_MAIL_PART_VALIDITY_PGP;\n\t\t\t}\n#ifdef ENABLE_SMIME\n\t\t}\n#endif\n\t}\n\n\tif (cipher == NULL) {\n\t\te_mail_parser_error (\n\t\t\tparser, out_mail_parts,\n\t\t\t_(\"Unsupported signature format\"));\n\t\te_mail_parser_parse_part_as (\n\t\t\tparser, part, part_id, \"multipart/mixed\",\n\t\t\tcancellable, out_mail_parts);\n\n\t\treturn TRUE;\n\t}\n\n\tvalid = camel_cipher_context_verify_sync (\n\t\tcipher, part, 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_(\"Error verifying signature: %s\"),\n\t\t\tlocal_error->message);\n\t\te_mail_parser_parse_part_as (\n\t\t\tparser, part, part_id, \"multipart/mixed\",\n\t\t\tcancellable, out_mail_parts);\n\n\t\tg_object_unref (cipher);\n\t\tg_error_free (local_error);\n\n\t\treturn TRUE;\n\t}\n\n\tnparts = camel_multipart_get_number (multipart);\n\tsecured = FALSE;\n\tlen = part_id->len;\n\tfor (i = 0; i < nparts; i++) {\n\t\tGQueue work_queue = G_QUEUE_INIT;\n\t\tGList *head, *link;\n\t\tCamelMimePart *subpart;\n\n\t\tsubpart = camel_multipart_get_part (multipart, i);\n\n\t\tg_string_append_printf (part_id, \".signed.%d\", i);\n\n\t\tg_warn_if_fail (e_mail_parser_parse_part (\n\t\t\tparser, subpart, part_id, cancellable, &work_queue));\n\n\t\tg_string_truncate (part_id, len);\n\n\t\tif (!secured)\n\t\t\tsecured = e_mail_part_is_secured (subpart);\n\n\t\thead = g_queue_peek_head_link (&work_queue);\n\n\t\tfor (link = head; link != NULL; link = g_list_next (link)) {\n\t\t\tEMailPart *mail_part = link->data;\n\n\t\t\te_mail_part_update_validity (\n\t\t\t\tmail_part, valid,\n\t\t\t\tvalidity_type | E_MAIL_PART_VALIDITY_SIGNED);\n\t\t}\n\n\t\te_queue_transfer (&work_queue, out_mail_parts);\n\t}\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 (!secured) {\n\t\tGQueue work_queue = G_QUEUE_INIT;\n\t\tEMailPart *mail_part;\n\n\t\tg_string_append (part_id, \".signed.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\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\tvalidity_type | E_MAIL_PART_VALIDITY_SIGNED);\n\n\t\te_queue_transfer (&work_queue, out_mail_parts);\n\n\t\tg_string_truncate (part_id, len);\n\t}\n\n\tcamel_cipher_validity_free (valid);\n\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_backend_authenticate_sync (EBackend *backend,\n\t\t\t const ENamedParameters *credentials,\n\t\t\t gchar **out_certificate_pem,\n\t\t\t GTlsCertificateFlags *out_certificate_errors,\n\t\t\t GCancellable *cancellable,\n\t\t\t GError **error)\n{\n\tEEwsBackend *ews_backend;\n\tEEwsConnection *connection;\n\tCamelEwsSettings *ews_settings;\n\tESourceAuthenticationResult result = E_SOURCE_AUTHENTICATION_ERROR;\n\n\tg_return_val_if_fail (E_IS_EWS_BACKEND (backend), E_SOURCE_AUTHENTICATION_ERROR);\n\n\tews_backend = E_EWS_BACKEND (backend);\n\tews_settings = ews_backend_get_settings (ews_backend);\n\tg_return_val_if_fail (ews_settings != NULL, E_SOURCE_AUTHENTICATION_ERROR);\n\n\tg_mutex_lock (&ews_backend->priv->connection_lock);\n\tg_clear_object (&ews_backend->priv->connection);\n\te_named_parameters_free (ews_backend->priv->credentials);\n\tews_backend->priv->credentials = e_named_parameters_new_clone (credentials);\n\tg_mutex_unlock (&ews_backend->priv->connection_lock);\n\n\tconnection = e_ews_backend_ref_connection_sync (ews_backend, &result, cancellable, error);\n\tg_clear_object (&connection);\n\n\tif (result == E_SOURCE_AUTHENTICATION_ACCEPTED) {\n\t\te_collection_backend_authenticate_children (E_COLLECTION_BACKEND (backend), credentials);\n\n\t\te_ews_backend_sync_folders (ews_backend, NULL, ews_backend_folders_synced_cb, NULL);\n\t} else if (e_ews_connection_utils_get_without_password (ews_settings) &&\n\t\t result == E_SOURCE_AUTHENTICATION_REJECTED &&\n\t\t !e_named_parameters_exists (credentials, E_SOURCE_CREDENTIAL_PASSWORD)) {\n\t\te_ews_connection_utils_force_off_ntlm_auth_check ();\n\t\tresult = E_SOURCE_AUTHENTICATION_REQUIRED;\n\t}\n\n\treturn result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated\n\nThis depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too.\n\nCloses https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: oal_response_cb (SoupSession *soup_session,\n SoupMessage *soup_message,\n gpointer user_data)\n{\n\tGSimpleAsyncResult *simple;\n\tstruct _oal_req_data *data;\n\tconst gchar *etag;\n\txmlDoc *doc;\n\txmlNode *node;\n\n\tsimple = G_SIMPLE_ASYNC_RESULT (user_data);\n\tdata = g_simple_async_result_get_op_res_gpointer (simple);\n\n\tif (ews_connection_credentials_failed (data->cnc, soup_message, simple)) {\n\t\tgoto exit;\n\t} else if (soup_message->status_code != 200) {\n\t\tif (soup_message->status_code == SOUP_STATUS_UNAUTHORIZED &&\n\t\t soup_message->response_headers) {\n\t\t\tconst gchar *diagnostics;\n\n\t\t\tdiagnostics = soup_message_headers_get_list (soup_message->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\tsimple,\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\tsimple,\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\t\tg_simple_async_result_set_error (\n\t\t\tsimple, SOUP_HTTP_ERROR,\n\t\t\tsoup_message->status_code,\n\t\t\t\"%d %s\",\n\t\t\tsoup_message->status_code,\n\t\t\tsoup_message->reason_phrase);\n\t\tgoto exit;\n\t}\n\n\tetag = soup_message_headers_get_one(soup_message->response_headers,\n\t\t\t\t\t \"ETag\");\n\tif (etag)\n\t\tdata->etag = g_strdup(etag);\n\n\te_ews_debug_dump_raw_soup_response (soup_message);\n\n\tdoc = xmlReadMemory (\n\t\tsoup_message->response_body->data,\n\t\tsoup_message->response_body->length,\n\t\t\"oab.xml\", NULL, 0);\n\tif (doc == NULL) {\n\t\tg_simple_async_result_set_error (\n\t\t\tsimple, EWS_CONNECTION_ERROR, -1,\n\t\t\t\"%s\", _(\"Failed to parse oab XML\"));\n\t\tgoto exit;\n\t}\n\n\tnode = xmlDocGetRootElement (doc);\n\tif (strcmp ((gchar *) node->name, \"OAB\") != 0) {\n\t\tg_simple_async_result_set_error (\n\t\t\tsimple, EWS_CONNECTION_ERROR, -1,\n\t\t\t\"%s\", _(\"Failed to find element\\n\"));\n\t\tgoto exit_doc;\n\t}\n\n\tfor (node = node->children; node; node = node->next) {\n\t\tif (node->type == XML_ELEMENT_NODE && strcmp ((gchar *) node->name, \"OAL\") == 0) {\n\t\t\tif (data->oal_id == NULL) {\n\t\t\t\tEwsOAL *oal = g_new0 (EwsOAL, 1);\n\n\t\t\t\toal->id = get_property (node, \"id\");\n\t\t\t\toal->dn = get_property (node, \"dn\");\n\t\t\t\toal->name = get_property (node, \"name\");\n\n\t\t\t\tdata->oals = g_slist_prepend (data->oals, oal);\n\t\t\t} else {\n\t\t\t\tgchar *id = get_property (node, \"id\");\n\n\t\t\t\tif (strcmp (id, data->oal_id) == 0) {\n\t\t\t\t\t/* parse details of full_details file */\n\t\t\t\t\tdata->elements = parse_oal_full_details (node, data->oal_element);\n\n\t\t\t\t\tg_free (id);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tg_free (id);\n\t\t\t}\n\t\t}\n\t}\n\n\tdata->oals = g_slist_reverse (data->oals);\n\n exit_doc:\n\txmlFreeDoc (doc);\n exit:\n\tg_simple_async_result_complete_in_idle (simple);\n\t/* This is run in cnc->priv->soup_thread, and the cnc is held by simple, thus\n\t * for cases when the complete_in_idle is finished before the unref call, when\n\t * the cnc will be left with the last reference and thus cannot join the soup_thread\n\t * while still in it, the unref is done in a dedicated thread. */\n\te_ews_connection_utils_unref_in_thread (simple);\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: mail_config_ews_autodiscover_run_cb (GObject *source_object,\n GAsyncResult *result,\n gpointer user_data)\n{\n\tAsyncContext *async_context = user_data;\n\tEMailConfigEwsAutodiscover *autodiscover;\n\tEAlertSink *alert_sink;\n\tGError *error = NULL;\n\tEMailConfigServiceBackend *backend;\n\tCamelSettings *settings;\n\n\tautodiscover = async_context->autodiscover;\n\talert_sink = e_activity_get_alert_sink (async_context->activity);\n\n\tmail_config_ews_autodiscover_finish (E_MAIL_CONFIG_EWS_AUTODISCOVER (source_object), result, &error);\n\n\tbackend = e_mail_config_ews_autodiscover_get_backend (autodiscover);\n\tsettings = e_mail_config_service_backend_get_settings (backend);\n\t/*\n\t * And unstop since we are back to the main thread.\n\t */\n\tg_object_thaw_notify (G_OBJECT (settings));\n\n\tif (e_activity_handle_cancellation (async_context->activity, error)) {\n\t\tg_error_free (error);\n\n\t} else if (error != NULL) {\n\t\te_alert_submit (\n\t\t\talert_sink,\n\t\t\t\"ews:autodiscovery-error\",\n\t\t\terror->message, NULL);\n\t\tg_error_free (error);\n\t}\n\n\tgtk_widget_set_sensitive (GTK_WIDGET (autodiscover), 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: compute_tag(dns_name_t *name, dns_rdata_dnskey_t *dnskey, isc_mem_t *mctx,\n\t dns_keytag_t *tag)\n{\n\tisc_result_t result;\n\tdns_rdata_t rdata = DNS_RDATA_INIT;\n\tunsigned char data[4096];\n\tisc_buffer_t buffer;\n\tdst_key_t *dstkey = NULL;\n\n\tisc_buffer_init(&buffer, data, sizeof(data));\n\tdns_rdata_fromstruct(&rdata, dnskey->common.rdclass,\n\t\t\t dns_rdatatype_dnskey, dnskey, &buffer);\n\n\tresult = dns_dnssec_keyfromrdata(name, &rdata, mctx, &dstkey);\n\tif (result == ISC_R_SUCCESS)\n\t\t*tag = dst_key_id(dstkey);\n\tdst_key_free(&dstkey);\n\n\treturn (result);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-327'], 'message': 'Don't free key in compute_tag in case of failure\n\nIf `dns_dnssec_keyfromrdata` failed we don't need to call\n`dst_key_free` because no `dstkey` was created. Doing so\nnevertheless will result in an assertion failure.\n\nThis can happen if the key uses an unsupported algorithm.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)\n{\n\tif (cfs_rq->load.weight)\n\t\treturn false;\n\n\tif (cfs_rq->avg.load_sum)\n\t\treturn false;\n\n\tif (cfs_rq->avg.util_sum)\n\t\treturn false;\n\n\tif (cfs_rq->avg.runnable_load_sum)\n\t\treturn false;\n\n\treturn true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703', 'CWE-835'], 'message': 'sched/fair: Fix infinite loop in update_blocked_averages() by reverting a9e7f6544b9c\n\nZhipeng Xie, Xie XiuQi and Sargun Dhillon reported lockups in the\nscheduler under high loads, starting at around the v4.18 time frame,\nand Zhipeng Xie tracked it down to bugs in the rq->leaf_cfs_rq_list\nmanipulation.\n\nDo a (manual) revert of:\n\n a9e7f6544b9c (\"sched/fair: Fix O(nr_cgroups) in load balance path\")\n\nIt turns out that the list_del_leaf_cfs_rq() introduced by this commit\nis a surprising property that was not considered in followup commits\nsuch as:\n\n 9c2791f936ef (\"sched/fair: Fix hierarchical order in rq->leaf_cfs_rq_list\")\n\nAs Vincent Guittot explains:\n\n \"I think that there is a bigger problem with commit a9e7f6544b9c and\n cfs_rq throttling:\n\n Let take the example of the following topology TG2 --> TG1 --> root:\n\n 1) The 1st time a task is enqueued, we will add TG2 cfs_rq then TG1\n cfs_rq to leaf_cfs_rq_list and we are sure to do the whole branch in\n one path because it has never been used and can't be throttled so\n tmp_alone_branch will point to leaf_cfs_rq_list at the end.\n\n 2) Then TG1 is throttled\n\n 3) and we add TG3 as a new child of TG1.\n\n 4) The 1st enqueue of a task on TG3 will add TG3 cfs_rq just before TG1\n cfs_rq and tmp_alone_branch will stay on rq->leaf_cfs_rq_list.\n\n With commit a9e7f6544b9c, we can del a cfs_rq from rq->leaf_cfs_rq_list.\n So if the load of TG1 cfs_rq becomes NULL before step 2) above, TG1\n cfs_rq is removed from the list.\n Then at step 4), TG3 cfs_rq is added at the beginning of rq->leaf_cfs_rq_list\n but tmp_alone_branch still points to TG3 cfs_rq because its throttled\n parent can't be enqueued when the lock is released.\n tmp_alone_branch doesn't point to rq->leaf_cfs_rq_list whereas it should.\n\n So if TG3 cfs_rq is removed or destroyed before tmp_alone_branch\n points on another TG cfs_rq, the next TG cfs_rq that will be added,\n will be linked outside rq->leaf_cfs_rq_list - which is bad.\n\n In addition, we can break the ordering of the cfs_rq in\n rq->leaf_cfs_rq_list but this ordering is used to update and\n propagate the update from leaf down to root.\"\n\nInstead of trying to work through all these cases and trying to reproduce\nthe very high loads that produced the lockup to begin with, simplify\nthe code temporarily by reverting a9e7f6544b9c - which change was clearly\nnot thought through completely.\n\nThis (hopefully) gives us a kernel that doesn't lock up so people\ncan continue to enjoy their holidays without worrying about regressions. ;-)\n\n[ mingo: Wrote changelog, fixed weird spelling in code comment while at it. ]\n\nAnalyzed-by: Xie XiuQi \nAnalyzed-by: Vincent Guittot \nReported-by: Zhipeng Xie \nReported-by: Sargun Dhillon \nReported-by: Xie XiuQi \nTested-by: Zhipeng Xie \nTested-by: Sargun Dhillon \nSigned-off-by: Linus Torvalds \nAcked-by: Vincent Guittot \nCc: # v4.13+\nCc: Bin Li \nCc: Mike Galbraith \nCc: Peter Zijlstra \nCc: Tejun Heo \nCc: Thomas Gleixner \nFixes: a9e7f6544b9c (\"sched/fair: Fix O(nr_cgroups) in load balance path\")\nLink: http://lkml.kernel.org/r/1545879866-27809-1-git-send-email-xiexiuqi@huawei.com\nSigned-off-by: Ingo Molnar '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: INTERNAL void vterm_screen_free(VTermScreen *screen)\n{\n vterm_allocator_free(screen->vt, screen->buffers[0]);\n if(screen->buffers[1])\n vterm_allocator_free(screen->vt, screen->buffers[1]);\n\n vterm_allocator_free(screen->vt, screen->sb_buffer);\n\n vterm_allocator_free(screen->vt, screen);\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 int bus_append_execute_property(sd_bus_message *m, const char *field, const char *eq) {\n const char *suffix;\n int r;\n\n if (STR_IN_SET(field,\n \"User\", \"Group\",\n \"UtmpIdentifier\", \"UtmpMode\", \"PAMName\", \"TTYPath\",\n \"WorkingDirectory\", \"RootDirectory\", \"SyslogIdentifier\",\n \"ProtectSystem\", \"ProtectHome\", \"SELinuxContext\", \"RootImage\",\n \"RuntimeDirectoryPreserve\", \"Personality\", \"KeyringMode\", \"NetworkNamespacePath\"))\n\n return bus_append_string(m, field, eq);\n\n if (STR_IN_SET(field,\n \"IgnoreSIGPIPE\", \"TTYVHangup\", \"TTYReset\", \"TTYVTDisallocate\",\n \"PrivateTmp\", \"PrivateDevices\", \"PrivateNetwork\", \"PrivateUsers\",\n \"PrivateMounts\", \"NoNewPrivileges\", \"SyslogLevelPrefix\",\n \"MemoryDenyWriteExecute\", \"RestrictRealtime\", \"DynamicUser\", \"RemoveIPC\",\n \"ProtectKernelTunables\", \"ProtectKernelModules\", \"ProtectControlGroups\",\n \"MountAPIVFS\", \"CPUSchedulingResetOnFork\", \"LockPersonality\", \"ProtectHostname\"))\n\n return bus_append_parse_boolean(m, field, eq);\n\n if (STR_IN_SET(field,\n \"ReadWriteDirectories\", \"ReadOnlyDirectories\", \"InaccessibleDirectories\",\n \"ReadWritePaths\", \"ReadOnlyPaths\", \"InaccessiblePaths\",\n \"RuntimeDirectory\", \"StateDirectory\", \"CacheDirectory\", \"LogsDirectory\", \"ConfigurationDirectory\",\n \"SupplementaryGroups\", \"SystemCallArchitectures\"))\n\n return bus_append_strv(m, field, eq, EXTRACT_QUOTES);\n\n if (STR_IN_SET(field, \"SyslogLevel\", \"LogLevelMax\"))\n\n return bus_append_log_level_from_string(m, field, eq);\n\n if (streq(field, \"SyslogFacility\"))\n\n return bus_append_log_facility_unshifted_from_string(m, field, eq);\n\n if (streq(field, \"SecureBits\"))\n\n return bus_append_secure_bits_from_string(m, field, eq);\n\n if (streq(field, \"CPUSchedulingPolicy\"))\n\n return bus_append_sched_policy_from_string(m, field, eq);\n\n if (STR_IN_SET(field, \"CPUSchedulingPriority\", \"OOMScoreAdjust\"))\n\n return bus_append_safe_atoi(m, field, eq);\n\n if (streq(field, \"Nice\"))\n\n return bus_append_parse_nice(m, field, eq);\n\n if (streq(field, \"SystemCallErrorNumber\"))\n\n return bus_append_parse_errno(m, field, eq);\n\n if (streq(field, \"IOSchedulingClass\"))\n\n return bus_append_ioprio_class_from_string(m, field, eq);\n\n if (streq(field, \"IOSchedulingPriority\"))\n\n return bus_append_ioprio_parse_priority(m, field, eq);\n\n if (STR_IN_SET(field,\n \"RuntimeDirectoryMode\", \"StateDirectoryMode\", \"CacheDirectoryMode\",\n \"LogsDirectoryMode\", \"ConfigurationDirectoryMode\", \"UMask\"))\n\n return bus_append_parse_mode(m, field, eq);\n\n if (streq(field, \"TimerSlackNSec\"))\n\n return bus_append_parse_nsec(m, field, eq);\n\n if (streq(field, \"LogRateLimitIntervalSec\"))\n\n return bus_append_parse_sec_rename(m, field, eq);\n\n if (streq(field, \"LogRateLimitBurst\"))\n\n return bus_append_safe_atou(m, field, eq);\n\n if (streq(field, \"MountFlags\"))\n\n return bus_append_mount_propagation_flags_from_string(m, field, eq);\n\n if (STR_IN_SET(field, \"Environment\", \"UnsetEnvironment\", \"PassEnvironment\"))\n\n return bus_append_strv(m, field, eq, EXTRACT_QUOTES|EXTRACT_CUNESCAPE);\n\n if (streq(field, \"EnvironmentFile\")) {\n\n if (isempty(eq))\n r = sd_bus_message_append(m, \"(sv)\", \"EnvironmentFiles\", \"a(sb)\", 0);\n else\n r = sd_bus_message_append(m, \"(sv)\", \"EnvironmentFiles\", \"a(sb)\", 1,\n eq[0] == '-' ? eq + 1 : eq,\n eq[0] == '-');\n if (r < 0)\n return bus_log_create_error(r);\n\n return 1;\n }\n\n if (streq(field, \"LogExtraFields\")) {\n\n r = sd_bus_message_open_container(m, 'r', \"sv\");\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_append_basic(m, 's', \"LogExtraFields\");\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_open_container(m, 'v', \"aay\");\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_open_container(m, 'a', \"ay\");\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_append_array(m, 'y', eq, strlen(eq));\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_close_container(m);\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_close_container(m);\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_close_container(m);\n if (r < 0)\n return bus_log_create_error(r);\n\n return 1;\n }\n\n if (STR_IN_SET(field, \"StandardInput\", \"StandardOutput\", \"StandardError\")) {\n const char *n, *appended;\n\n if ((n = startswith(eq, \"fd:\"))) {\n appended = strjoina(field, \"FileDescriptorName\");\n r = sd_bus_message_append(m, \"(sv)\", appended, \"s\", n);\n } else if ((n = startswith(eq, \"file:\"))) {\n appended = strjoina(field, \"File\");\n r = sd_bus_message_append(m, \"(sv)\", appended, \"s\", n);\n } else if ((n = startswith(eq, \"append:\"))) {\n appended = strjoina(field, \"FileToAppend\");\n r = sd_bus_message_append(m, \"(sv)\", appended, \"s\", n);\n } else\n r = sd_bus_message_append(m, \"(sv)\", field, \"s\", eq);\n if (r < 0)\n return bus_log_create_error(r);\n\n return 1;\n }\n\n if (streq(field, \"StandardInputText\")) {\n _cleanup_free_ char *unescaped = NULL;\n\n r = cunescape(eq, 0, &unescaped);\n if (r < 0)\n return log_error_errno(r, \"Failed to unescape text '%s': %m\", eq);\n\n if (!strextend(&unescaped, \"\\n\", NULL))\n return log_oom();\n\n /* Note that we don't expand specifiers here, but that should be OK, as this is a programmatic\n * interface anyway */\n\n return bus_append_byte_array(m, field, unescaped, strlen(unescaped));\n }\n\n if (streq(field, \"StandardInputData\")) {\n _cleanup_free_ void *decoded = NULL;\n size_t sz;\n\n r = unbase64mem(eq, (size_t) -1, &decoded, &sz);\n if (r < 0)\n return log_error_errno(r, \"Failed to decode base64 data '%s': %m\", eq);\n\n return bus_append_byte_array(m, field, decoded, sz);\n }\n\n if ((suffix = startswith(field, \"Limit\"))) {\n int rl;\n\n rl = rlimit_from_string(suffix);\n if (rl >= 0) {\n const char *sn;\n struct rlimit l;\n\n r = rlimit_parse(rl, eq, &l);\n if (r < 0)\n return log_error_errno(r, \"Failed to parse resource limit: %s\", eq);\n\n r = sd_bus_message_append(m, \"(sv)\", field, \"t\", l.rlim_max);\n if (r < 0)\n return bus_log_create_error(r);\n\n sn = strjoina(field, \"Soft\");\n r = sd_bus_message_append(m, \"(sv)\", sn, \"t\", l.rlim_cur);\n if (r < 0)\n return bus_log_create_error(r);\n\n return 1;\n }\n }\n\n if (STR_IN_SET(field, \"AppArmorProfile\", \"SmackProcessLabel\")) {\n int ignore = 0;\n const char *s = eq;\n\n if (eq[0] == '-') {\n ignore = 1;\n s = eq + 1;\n }\n\n r = sd_bus_message_append(m, \"(sv)\", field, \"(bs)\", ignore, s);\n if (r < 0)\n return bus_log_create_error(r);\n\n return 1;\n }\n\n if (STR_IN_SET(field, \"CapabilityBoundingSet\", \"AmbientCapabilities\")) {\n uint64_t sum = 0;\n bool invert = false;\n const char *p = eq;\n\n if (*p == '~') {\n invert = true;\n p++;\n }\n\n r = capability_set_from_string(p, &sum);\n if (r < 0)\n return log_error_errno(r, \"Failed to parse %s value %s: %m\", field, eq);\n\n sum = invert ? ~sum : sum;\n\n r = sd_bus_message_append(m, \"(sv)\", field, \"t\", sum);\n if (r < 0)\n return bus_log_create_error(r);\n\n return 1;\n }\n\n if (streq(field, \"CPUAffinity\")) {\n _cleanup_cpu_free_ cpu_set_t *cpuset = NULL;\n\n r = parse_cpu_set(eq, &cpuset);\n if (r < 0)\n return log_error_errno(r, \"Failed to parse %s value: %s\", field, eq);\n\n return bus_append_byte_array(m, field, cpuset, CPU_ALLOC_SIZE(r));\n }\n\n if (STR_IN_SET(field, \"RestrictAddressFamilies\", \"SystemCallFilter\")) {\n int whitelist = 1;\n const char *p = eq;\n\n if (*p == '~') {\n whitelist = 0;\n p++;\n }\n\n r = sd_bus_message_open_container(m, SD_BUS_TYPE_STRUCT, \"sv\");\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_append_basic(m, SD_BUS_TYPE_STRING, field);\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_open_container(m, 'v', \"(bas)\");\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_open_container(m, 'r', \"bas\");\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_append_basic(m, 'b', &whitelist);\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_open_container(m, 'a', \"s\");\n if (r < 0)\n return bus_log_create_error(r);\n\n for (;;) {\n _cleanup_free_ char *word = NULL;\n\n r = extract_first_word(&p, &word, NULL, EXTRACT_QUOTES);\n if (r == 0)\n break;\n if (r == -ENOMEM)\n return log_oom();\n if (r < 0)\n return log_error_errno(r, \"Invalid syntax: %s\", eq);\n\n r = sd_bus_message_append_basic(m, 's', word);\n if (r < 0)\n return bus_log_create_error(r);\n }\n\n r = sd_bus_message_close_container(m);\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_close_container(m);\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_close_container(m);\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_close_container(m);\n if (r < 0)\n return bus_log_create_error(r);\n\n return 1;\n }\n\n if (streq(field, \"RestrictNamespaces\")) {\n bool invert = false;\n unsigned long flags;\n\n r = parse_boolean(eq);\n if (r > 0)\n flags = 0;\n else if (r == 0)\n flags = NAMESPACE_FLAGS_ALL;\n else {\n if (eq[0] == '~') {\n invert = true;\n eq++;\n }\n\n r = namespace_flags_from_string(eq, &flags);\n if (r < 0)\n return log_error_errno(r, \"Failed to parse %s value %s.\", field, eq);\n }\n\n if (invert)\n flags = (~flags) & NAMESPACE_FLAGS_ALL;\n\n r = sd_bus_message_append(m, \"(sv)\", field, \"t\", (uint64_t) flags);\n if (r < 0)\n return bus_log_create_error(r);\n\n return 1;\n }\n\n if (STR_IN_SET(field, \"BindPaths\", \"BindReadOnlyPaths\")) {\n const char *p = eq;\n\n r = sd_bus_message_open_container(m, SD_BUS_TYPE_STRUCT, \"sv\");\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_append_basic(m, SD_BUS_TYPE_STRING, field);\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_open_container(m, 'v', \"a(ssbt)\");\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_open_container(m, 'a', \"(ssbt)\");\n if (r < 0)\n return bus_log_create_error(r);\n\n for (;;) {\n _cleanup_free_ char *source = NULL, *destination = NULL;\n char *s = NULL, *d = NULL;\n bool ignore_enoent = false;\n uint64_t flags = MS_REC;\n\n r = extract_first_word(&p, &source, \":\" WHITESPACE, EXTRACT_QUOTES|EXTRACT_DONT_COALESCE_SEPARATORS);\n if (r < 0)\n return log_error_errno(r, \"Failed to parse argument: %m\");\n if (r == 0)\n break;\n\n s = source;\n if (s[0] == '-') {\n ignore_enoent = true;\n s++;\n }\n\n if (p && p[-1] == ':') {\n r = extract_first_word(&p, &destination, \":\" WHITESPACE, EXTRACT_QUOTES|EXTRACT_DONT_COALESCE_SEPARATORS);\n if (r < 0)\n return log_error_errno(r, \"Failed to parse argument: %m\");\n if (r == 0)\n return log_error_errno(SYNTHETIC_ERRNO(EINVAL),\n \"Missing argument after ':': %s\",\n eq);\n\n d = destination;\n\n if (p && p[-1] == ':') {\n _cleanup_free_ char *options = NULL;\n\n r = extract_first_word(&p, &options, NULL, EXTRACT_QUOTES);\n if (r < 0)\n return log_error_errno(r, \"Failed to parse argument: %m\");\n\n if (isempty(options) || streq(options, \"rbind\"))\n flags = MS_REC;\n else if (streq(options, \"norbind\"))\n flags = 0;\n else\n return log_error_errno(SYNTHETIC_ERRNO(EINVAL),\n \"Unknown options: %s\",\n eq);\n }\n } else\n d = s;\n\n r = sd_bus_message_append(m, \"(ssbt)\", s, d, ignore_enoent, flags);\n if (r < 0)\n return bus_log_create_error(r);\n }\n\n r = sd_bus_message_close_container(m);\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_close_container(m);\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_close_container(m);\n if (r < 0)\n return bus_log_create_error(r);\n\n return 1;\n }\n\n if (streq(field, \"TemporaryFileSystem\")) {\n const char *p = eq;\n\n r = sd_bus_message_open_container(m, SD_BUS_TYPE_STRUCT, \"sv\");\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_append_basic(m, SD_BUS_TYPE_STRING, field);\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_open_container(m, 'v', \"a(ss)\");\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_open_container(m, 'a', \"(ss)\");\n if (r < 0)\n return bus_log_create_error(r);\n\n for (;;) {\n _cleanup_free_ char *word = NULL, *path = NULL;\n const char *w;\n\n r = extract_first_word(&p, &word, NULL, EXTRACT_QUOTES);\n if (r < 0)\n return log_error_errno(r, \"Failed to parse argument: %m\");\n if (r == 0)\n break;\n\n w = word;\n r = extract_first_word(&w, &path, \":\", EXTRACT_DONT_COALESCE_SEPARATORS);\n if (r < 0)\n return log_error_errno(r, \"Failed to parse argument: %m\");\n if (r == 0)\n return log_error_errno(SYNTHETIC_ERRNO(EINVAL),\n \"Failed to parse argument: %s\",\n p);\n\n r = sd_bus_message_append(m, \"(ss)\", path, w);\n if (r < 0)\n return bus_log_create_error(r);\n }\n\n r = sd_bus_message_close_container(m);\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_close_container(m);\n if (r < 0)\n return bus_log_create_error(r);\n\n r = sd_bus_message_close_container(m);\n if (r < 0)\n return bus_log_create_error(r);\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-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: static void xml_element_serialize(xml_element *el, int (*fptr)(void *data, const char *text, int size), void *data, XML_ELEM_OUTPUT_OPTIONS options, int depth)\n{\n int i;\n static STRUCT_XML_ELEM_OUTPUT_OPTIONS default_opts = {xml_elem_pretty, xml_elem_markup_escaping | xml_elem_non_print_escaping, XML_DECL_ENCODING_DEFAULT};\n static char whitespace[] = \" \"\n \" \"\n \" \";\n depth++;\n\n if(!el) {\n fprintf(stderr, \"Nothing to write\\n\");\n return;\n }\n if(!options) {\n options = &default_opts;\n }\n\n /* print xml declaration if at root level */\n if(depth == 1) {\n xml_elem_writefunc(fptr, XML_DECL_START, data, XML_DECL_START_LEN);\n xml_elem_writefunc(fptr, WHITESPACE, data, WHITESPACE_LEN);\n xml_elem_writefunc(fptr, XML_DECL_VERSION, data, XML_DECL_VERSION_LEN);\n if(options->encoding && *options->encoding) {\n xml_elem_writefunc(fptr, WHITESPACE, data, WHITESPACE_LEN);\n xml_elem_writefunc(fptr, XML_DECL_ENCODING_ATTR, data, XML_DECL_ENCODING_ATTR_LEN);\n xml_elem_writefunc(fptr, EQUALS, data, EQUALS_LEN);\n xml_elem_writefunc(fptr, ATTR_DELIMITER, data, ATTR_DELIMITER_LEN);\n xml_elem_writefunc(fptr, options->encoding, data, 0);\n xml_elem_writefunc(fptr, ATTR_DELIMITER, data, ATTR_DELIMITER_LEN);\n }\n xml_elem_writefunc(fptr, XML_DECL_END, data, XML_DECL_END_LEN);\n if(options->verbosity != xml_elem_no_white_space) {\n xml_elem_writefunc(fptr, NEWLINE, data, NEWLINE_LEN);\n }\n }\n\n if(options->verbosity == xml_elem_pretty && depth > 2) {\n xml_elem_writefunc(fptr, whitespace, data, depth - 2);\n }\n /* begin element */\n xml_elem_writefunc(fptr,START_TOKEN_BEGIN, data, START_TOKEN_BEGIN_LEN);\n if(el->name) {\n xml_elem_writefunc(fptr, el->name, data, 0);\n\n /* write attrs, if any */\n if(Q_Size(&el->attrs)) {\n xml_element_attr* iter = Q_Head(&el->attrs);\n while( iter ) {\n xml_elem_writefunc(fptr, WHITESPACE, data, WHITESPACE_LEN);\n xml_elem_writefunc(fptr, iter->key, data, 0);\n xml_elem_writefunc(fptr, EQUALS, data, EQUALS_LEN);\n xml_elem_writefunc(fptr, ATTR_DELIMITER, data, ATTR_DELIMITER_LEN);\n xml_elem_writefunc(fptr, iter->val, data, 0);\n xml_elem_writefunc(fptr, ATTR_DELIMITER, data, ATTR_DELIMITER_LEN);\n\n iter = Q_Next(&el->attrs);\n }\n }\n }\n else {\n xml_elem_writefunc(fptr, \"None\", data, 0);\n }\n /* if no text and no children, use abbreviated form, eg: */\n if(!el->text.len && !Q_Size(&el->children)) {\n xml_elem_writefunc(fptr, EMPTY_START_TOKEN_END, data, EMPTY_START_TOKEN_END_LEN);\n }\n /* otherwise, print element contents */\n else {\n xml_elem_writefunc(fptr, START_TOKEN_END, data, START_TOKEN_END_LEN);\n\n /* print text, if any */\n if(el->text.len) {\n char* escaped_str = el->text.str;\n int buflen = el->text.len;\n\n if(options->escaping && options->escaping != xml_elem_cdata_escaping) {\n escaped_str = xml_elem_entity_escape(el->text.str, buflen, &buflen, options->escaping );\n if(!escaped_str) {\n escaped_str = el->text.str;\n }\n }\n\n if(options->escaping & xml_elem_cdata_escaping) {\n xml_elem_writefunc(fptr, CDATA_BEGIN, data, CDATA_BEGIN_LEN);\n }\n\n xml_elem_writefunc(fptr, escaped_str, data, buflen);\n\n if(escaped_str != el->text.str) {\n my_free(escaped_str);\n }\n\n if(options->escaping & xml_elem_cdata_escaping) {\n xml_elem_writefunc(fptr, CDATA_END, data, CDATA_END_LEN);\n }\n }\n /* no text, so print child elems */\n else {\n xml_element *kids = Q_Head(&el->children);\n i = 0;\n while( kids ) {\n if(i++ == 0) {\n if(options->verbosity != xml_elem_no_white_space) {\n xml_elem_writefunc(fptr, NEWLINE, data, NEWLINE_LEN);\n }\n }\n xml_element_serialize(kids, fptr, data, options, depth);\n kids = Q_Next(&el->children);\n }\n if(i) {\n if(options->verbosity == xml_elem_pretty && depth > 2) {\n xml_elem_writefunc(fptr, whitespace, data, depth - 2);\n }\n }\n }\n\n xml_elem_writefunc(fptr, END_TOKEN_BEGIN, data, END_TOKEN_BEGIN_LEN);\n xml_elem_writefunc(fptr,el->name ? el->name : \"None\", data, 0);\n xml_elem_writefunc(fptr, END_TOKEN_END, data, END_TOKEN_END_LEN);\n }\n if(options->verbosity != xml_elem_no_white_space) {\n xml_elem_writefunc(fptr, NEWLINE, data, NEWLINE_LEN);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'MFH: Fixed bug #46746 (xmlrpc_decode_request outputs non-suppressable error\nwhen given bad data).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static u_char *php_parserr(u_char *cp, u_char *end, querybuf *answer, int type_to_fetch, int store, int raw, zval *subarray)\n{\n\tu_short type, class, dlen;\n\tu_long ttl;\n\tlong n, i;\n\tu_short s;\n\tu_char *tp, *p;\n\tchar name[MAXHOSTNAMELEN];\n\tint have_v6_break = 0, in_v6_break = 0;\n\n\tZVAL_UNDEF(subarray);\n\n\tn = dn_expand(answer->qb2, end, cp, name, sizeof(name) - 2);\n\tif (n < 0) {\n\t\treturn NULL;\n\t}\n\tcp += n;\n\n\tCHECKCP(10);\n\tGETSHORT(type, cp);\n\tGETSHORT(class, cp);\n\tGETLONG(ttl, cp);\n\tGETSHORT(dlen, cp);\n\tCHECKCP(dlen);\n\tif (type_to_fetch != T_ANY && type != type_to_fetch) {\n\t\tcp += dlen;\n\t\treturn cp;\n\t}\n\n\tif (!store) {\n\t\tcp += dlen;\n\t\treturn cp;\n\t}\n\n\tarray_init(subarray);\n\n\tadd_assoc_string(subarray, \"host\", name);\n\tadd_assoc_string(subarray, \"class\", \"IN\");\n\tadd_assoc_long(subarray, \"ttl\", ttl);\n\t(void) class;\n\n\tif (raw) {\n\t\tadd_assoc_long(subarray, \"type\", type);\n\t\tadd_assoc_stringl(subarray, \"data\", (char*) cp, (uint) dlen);\n\t\tcp += dlen;\n\t\treturn cp;\n\t}\n\n\tswitch (type) {\n\t\tcase DNS_T_A:\n\t\t\tCHECKCP(4);\n\t\t\tadd_assoc_string(subarray, \"type\", \"A\");\n\t\t\tsnprintf(name, sizeof(name), \"%d.%d.%d.%d\", cp[0], cp[1], cp[2], cp[3]);\n\t\t\tadd_assoc_string(subarray, \"ip\", name);\n\t\t\tcp += dlen;\n\t\t\tbreak;\n\t\tcase DNS_T_MX:\n\t\t\tCHECKCP(2);\n\t\t\tadd_assoc_string(subarray, \"type\", \"MX\");\n\t\t\tGETSHORT(n, cp);\n\t\t\tadd_assoc_long(subarray, \"pri\", n);\n\t\t\t/* no break; */\n\t\tcase DNS_T_CNAME:\n\t\t\tif (type == DNS_T_CNAME) {\n\t\t\t\tadd_assoc_string(subarray, \"type\", \"CNAME\");\n\t\t\t}\n\t\t\t/* no break; */\n\t\tcase DNS_T_NS:\n\t\t\tif (type == DNS_T_NS) {\n\t\t\t\tadd_assoc_string(subarray, \"type\", \"NS\");\n\t\t\t}\n\t\t\t/* no break; */\n\t\tcase DNS_T_PTR:\n\t\t\tif (type == DNS_T_PTR) {\n\t\t\t\tadd_assoc_string(subarray, \"type\", \"PTR\");\n\t\t\t}\n\t\t\tn = dn_expand(answer->qb2, end, cp, name, (sizeof name) - 2);\n\t\t\tif (n < 0) {\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tcp += n;\n\t\t\tadd_assoc_string(subarray, \"target\", name);\n\t\t\tbreak;\n\t\tcase DNS_T_HINFO:\n\t\t\t/* See RFC 1010 for values */\n\t\t\tadd_assoc_string(subarray, \"type\", \"HINFO\");\n\t\t\tCHECKCP(1);\n\t\t\tn = *cp & 0xFF;\n\t\t\tcp++;\n\t\t\tCHECKCP(n);\n\t\t\tadd_assoc_stringl(subarray, \"cpu\", (char*)cp, n);\n\t\t\tcp += n;\n\t\t\tCHECKCP(1);\n\t\t\tn = *cp & 0xFF;\n\t\t\tcp++;\n\t\t\tCHECKCP(n);\n\t\t\tadd_assoc_stringl(subarray, \"os\", (char*)cp, n);\n\t\t\tcp += n;\n\t\t\tbreak;\n\t\tcase DNS_T_CAA:\n\t\t\t/* See RFC 6844 for values https://tools.ietf.org/html/rfc6844 */\n\t\t\tadd_assoc_string(subarray, \"type\", \"CAA\");\n\t\t\t// 1 flag byte\n\t\t\tCHECKCP(1);\n\t\t\tn = *cp & 0xFF;\n\t\t\tadd_assoc_long(subarray, \"flags\", n);\n\t\t\tcp++;\n\t\t\t// Tag length (1 byte)\n\t\t\tCHECKCP(1);\n\t\t\tn = *cp & 0xFF;\n\t\t\tcp++;\n\t\t\tCHECKCP(n);\n\t\t\tadd_assoc_stringl(subarray, \"tag\", (char*)cp, n);\n\t\t\tcp += n;\n\t\t\tn = dlen - n - 2;\n\t\t\tCHECKCP(n);\n\t\t\tadd_assoc_stringl(subarray, \"value\", (char*)cp, n);\n\t\t\tcp += n;\n\t\t\tbreak;\n\t\tcase DNS_T_TXT:\n\t\t\t{\n\t\t\t\tint l1 = 0, l2 = 0;\n\t\t\t\tzval entries;\n\t\t\t\tzend_string *tp;\n\n\t\t\t\tadd_assoc_string(subarray, \"type\", \"TXT\");\n\t\t\t\ttp = zend_string_alloc(dlen, 0);\n\n\t\t\t\tarray_init(&entries);\n\n\t\t\t\twhile (l1 < dlen) {\n\t\t\t\t\tn = cp[l1];\n\t\t\t\t\tif ((l1 + n) >= dlen) {\n\t\t\t\t\t\t// Invalid chunk length, truncate\n\t\t\t\t\t\tn = dlen - (l1 + 1);\n\t\t\t\t\t}\n\t\t\t\t\tif (n) {\n\t\t\t\t\t\tmemcpy(ZSTR_VAL(tp) + l2 , cp + l1 + 1, n);\n\t\t\t\t\t\tadd_next_index_stringl(&entries, (char *) cp + l1 + 1, n);\n\t\t\t\t\t}\n\t\t\t\t\tl1 = l1 + n + 1;\n\t\t\t\t\tl2 = l2 + n;\n\t\t\t\t}\n\t\t\t\tZSTR_VAL(tp)[l2] = '\\0';\n\t\t\t\tZSTR_LEN(tp) = l2;\n\t\t\t\tcp += dlen;\n\n\t\t\t\tadd_assoc_str(subarray, \"txt\", tp);\n\t\t\t\tadd_assoc_zval(subarray, \"entries\", &entries);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase DNS_T_SOA:\n\t\t\tadd_assoc_string(subarray, \"type\", \"SOA\");\n\t\t\tn = dn_expand(answer->qb2, end, cp, name, (sizeof name) -2);\n\t\t\tif (n < 0) {\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tcp += n;\n\t\t\tadd_assoc_string(subarray, \"mname\", name);\n\t\t\tn = dn_expand(answer->qb2, end, cp, name, (sizeof name) -2);\n\t\t\tif (n < 0) {\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tcp += n;\n\t\t\tadd_assoc_string(subarray, \"rname\", name);\n\t\t\tCHECKCP(5*4);\n\t\t\tGETLONG(n, cp);\n\t\t\tadd_assoc_long(subarray, \"serial\", n);\n\t\t\tGETLONG(n, cp);\n\t\t\tadd_assoc_long(subarray, \"refresh\", n);\n\t\t\tGETLONG(n, cp);\n\t\t\tadd_assoc_long(subarray, \"retry\", n);\n\t\t\tGETLONG(n, cp);\n\t\t\tadd_assoc_long(subarray, \"expire\", n);\n\t\t\tGETLONG(n, cp);\n\t\t\tadd_assoc_long(subarray, \"minimum-ttl\", n);\n\t\t\tbreak;\n\t\tcase DNS_T_AAAA:\n\t\t\ttp = (u_char*)name;\n\t\t\tCHECKCP(8*2);\n\t\t\tfor(i=0; i < 8; i++) {\n\t\t\t\tGETSHORT(s, cp);\n\t\t\t\tif (s != 0) {\n\t\t\t\t\tif (tp > (u_char *)name) {\n\t\t\t\t\t\tin_v6_break = 0;\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t}\n\t\t\t\t\ttp += sprintf((char*)tp,\"%x\",s);\n\t\t\t\t} else {\n\t\t\t\t\tif (!have_v6_break) {\n\t\t\t\t\t\thave_v6_break = 1;\n\t\t\t\t\t\tin_v6_break = 1;\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t} else if (!in_v6_break) {\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t\ttp[0] = '0';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (have_v6_break && in_v6_break) {\n\t\t\t\ttp[0] = ':';\n\t\t\t\ttp++;\n\t\t\t}\n\t\t\ttp[0] = '\\0';\n\t\t\tadd_assoc_string(subarray, \"type\", \"AAAA\");\n\t\t\tadd_assoc_string(subarray, \"ipv6\", name);\n\t\t\tbreak;\n\t\tcase DNS_T_A6:\n\t\t\tp = cp;\n\t\t\tadd_assoc_string(subarray, \"type\", \"A6\");\n\t\t\tCHECKCP(1);\n\t\t\tn = ((int)cp[0]) & 0xFF;\n\t\t\tcp++;\n\t\t\tadd_assoc_long(subarray, \"masklen\", n);\n\t\t\ttp = (u_char*)name;\n\t\t\tif (n > 15) {\n\t\t\t\thave_v6_break = 1;\n\t\t\t\tin_v6_break = 1;\n\t\t\t\ttp[0] = ':';\n\t\t\t\ttp++;\n\t\t\t}\n\t\t\tif (n % 16 > 8) {\n\t\t\t\t/* Partial short */\n\t\t\t\tif (cp[0] != 0) {\n\t\t\t\t\tif (tp > (u_char *)name) {\n\t\t\t\t\t\tin_v6_break = 0;\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t}\n\t\t\t\t\tsprintf((char*)tp, \"%x\", cp[0] & 0xFF);\n\t\t\t\t} else {\n\t\t\t\t\tif (!have_v6_break) {\n\t\t\t\t\t\thave_v6_break = 1;\n\t\t\t\t\t\tin_v6_break = 1;\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t} else if (!in_v6_break) {\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t\ttp[0] = '0';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcp++;\n\t\t\t}\n\t\t\tfor (i = (n + 8) / 16; i < 8; i++) {\n\t\t\t\tCHECKCP(2);\n\t\t\t\tGETSHORT(s, cp);\n\t\t\t\tif (s != 0) {\n\t\t\t\t\tif (tp > (u_char *)name) {\n\t\t\t\t\t\tin_v6_break = 0;\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t}\n\t\t\t\t\ttp += sprintf((char*)tp,\"%x\",s);\n\t\t\t\t} else {\n\t\t\t\t\tif (!have_v6_break) {\n\t\t\t\t\t\thave_v6_break = 1;\n\t\t\t\t\t\tin_v6_break = 1;\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t} else if (!in_v6_break) {\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t\ttp[0] = '0';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (have_v6_break && in_v6_break) {\n\t\t\t\ttp[0] = ':';\n\t\t\t\ttp++;\n\t\t\t}\n\t\t\ttp[0] = '\\0';\n\t\t\tadd_assoc_string(subarray, \"ipv6\", name);\n\t\t\tif (cp < p + dlen) {\n\t\t\t\tn = dn_expand(answer->qb2, end, cp, name, (sizeof name) - 2);\n\t\t\t\tif (n < 0) {\n\t\t\t\t\treturn NULL;\n\t\t\t\t}\n\t\t\t\tcp += n;\n\t\t\t\tadd_assoc_string(subarray, \"chain\", name);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase DNS_T_SRV:\n\t\t\tCHECKCP(3*2);\n\t\t\tadd_assoc_string(subarray, \"type\", \"SRV\");\n\t\t\tGETSHORT(n, cp);\n\t\t\tadd_assoc_long(subarray, \"pri\", n);\n\t\t\tGETSHORT(n, cp);\n\t\t\tadd_assoc_long(subarray, \"weight\", n);\n\t\t\tGETSHORT(n, cp);\n\t\t\tadd_assoc_long(subarray, \"port\", n);\n\t\t\tn = dn_expand(answer->qb2, end, cp, name, (sizeof name) - 2);\n\t\t\tif (n < 0) {\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tcp += n;\n\t\t\tadd_assoc_string(subarray, \"target\", name);\n\t\t\tbreak;\n\t\tcase DNS_T_NAPTR:\n\t\t\tCHECKCP(2*2);\n\t\t\tadd_assoc_string(subarray, \"type\", \"NAPTR\");\n\t\t\tGETSHORT(n, cp);\n\t\t\tadd_assoc_long(subarray, \"order\", n);\n\t\t\tGETSHORT(n, cp);\n\t\t\tadd_assoc_long(subarray, \"pref\", n);\n\n\t\t\tCHECKCP(1);\n\t\t\tn = (cp[0] & 0xFF);\n\t\t\tcp++;\n\t\t\tCHECKCP(n);\n\t\t\tadd_assoc_stringl(subarray, \"flags\", (char*)cp, n);\n\t\t\tcp += n;\n\n\t\t\tCHECKCP(1);\n\t\t\tn = (cp[0] & 0xFF);\n\t\t\tcp++;\n\t\t\tCHECKCP(n);\n\t\t\tadd_assoc_stringl(subarray, \"services\", (char*)cp, n);\n\t\t\tcp += n;\n\n\t\t\tCHECKCP(1);\n\t\t\tn = (cp[0] & 0xFF);\n\t\t\tcp++;\n\t\t\tCHECKCP(n);\n\t\t\tadd_assoc_stringl(subarray, \"regex\", (char*)cp, n);\n\t\t\tcp += n;\n\n\t\t\tn = dn_expand(answer->qb2, end, cp, name, (sizeof name) - 2);\n\t\t\tif (n < 0) {\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tcp += n;\n\t\t\tadd_assoc_string(subarray, \"replacement\", name);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tzval_ptr_dtor(subarray);\n\t\t\tZVAL_UNDEF(subarray);\n\t\t\tcp += dlen;\n\t\t\tbreak;\n\t}\n\n\treturn cp;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix #77369 - memcpy with negative length via crafted DNS 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: Output4bitPixel (\r\n IN OUT EFI_IMAGE_INPUT *Image,\r\n IN UINT8 *Data,\r\n IN EFI_HII_IMAGE_PALETTE_INFO *PaletteInfo\r\n )\r\n{\r\n UINT16 Xpos;\r\n UINT16 Ypos;\r\n UINTN OffsetY;\r\n EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BitMapPtr;\r\n EFI_GRAPHICS_OUTPUT_BLT_PIXEL PaletteValue[16];\r\n EFI_HII_IMAGE_PALETTE_INFO *Palette;\r\n UINTN PaletteSize;\r\n UINT16 PaletteNum;\r\n UINT8 Byte;\r\n\r\n ASSERT (Image != NULL && Data != NULL && PaletteInfo != NULL);\r\n\r\n BitMapPtr = Image->Bitmap;\r\n\r\n //\r\n // The bitmap should allocate each color index starting from 0.\r\n //\r\n PaletteSize = 0;\r\n CopyMem (&PaletteSize, PaletteInfo, sizeof (UINT16));\r\n PaletteSize += sizeof (UINT16);\r\n Palette = AllocateZeroPool (PaletteSize);\r\n ASSERT (Palette != NULL);\r\n if (Palette == NULL) {\r\n return;\r\n }\r\n CopyMem (Palette, PaletteInfo, PaletteSize);\r\n PaletteNum = (UINT16)(Palette->PaletteSize / sizeof (EFI_HII_RGB_PIXEL));\r\n\r\n ZeroMem (PaletteValue, sizeof (PaletteValue));\r\n CopyRgbToGopPixel (PaletteValue, Palette->PaletteValue, PaletteNum);\r\n FreePool (Palette);\r\n\r\n //\r\n // Convert the pixel from 4 bit to corresponding color.\r\n //\r\n for (Ypos = 0; Ypos < Image->Height; Ypos++) {\r\n OffsetY = BITMAP_LEN_4_BIT (Image->Width, Ypos);\r\n //\r\n // All bits in these bytes are meaningful\r\n //\r\n for (Xpos = 0; Xpos < Image->Width / 2; Xpos++) {\r\n Byte = *(Data + OffsetY + Xpos);\r\n BitMapPtr[Ypos * Image->Width + Xpos * 2] = PaletteValue[Byte >> 4];\r\n BitMapPtr[Ypos * Image->Width + Xpos * 2 + 1] = PaletteValue[Byte & 0x0F];\r\n }\r\n\r\n if (Image->Width % 2 != 0) {\r\n //\r\n // Padding bits in this byte should be ignored.\r\n //\r\n Byte = *(Data + OffsetY + Xpos);\r\n BitMapPtr[Ypos * Image->Width + Xpos * 2] = PaletteValue[Byte >> 4];\r\n }\r\n }\r\n}\r ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'MdeModulePkg/HiiImage: Fix stack overflow when corrupted BMP is parsed (CVE-2018-12181)\n\nREF: https://bugzilla.tianocore.org/show_bug.cgi?id=1135\n\nFor 4bit BMP, there are only 2^4 = 16 colors in the palette.\nBut when a corrupted BMP contains more than 16 colors in the palette,\ntoday's implementation wrongly copies all colors to the local\nPaletteValue[16] array which causes stack overflow.\n\nThe similar issue also exists in the logic to handle 8bit BMP.\n\nThe patch fixes the issue by only copies the first 16 or 256 colors\nin the palette depending on the BMP type.\n\nContributed-under: TianoCore Contribution Agreement 1.1\nSigned-off-by: Ray Ni \nCc: Liming Gao \nCc: Jiewen Yao \nReviewed-by: Jian J Wang '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int channel_request_pty(LIBSSH2_CHANNEL *channel,\n const char *term, unsigned int term_len,\n const char *modes, unsigned int modes_len,\n int width, int height,\n int width_px, int height_px)\n{\n LIBSSH2_SESSION *session = channel->session;\n unsigned char *s;\n static const unsigned char reply_codes[3] =\n { SSH_MSG_CHANNEL_SUCCESS, SSH_MSG_CHANNEL_FAILURE, 0 };\n int rc;\n\n if(channel->reqPTY_state == libssh2_NB_state_idle) {\n /* 41 = packet_type(1) + channel(4) + pty_req_len(4) + \"pty_req\"(7) +\n * want_reply(1) + term_len(4) + width(4) + height(4) + width_px(4) +\n * height_px(4) + modes_len(4) */\n if(term_len + modes_len > 256) {\n return _libssh2_error(session, LIBSSH2_ERROR_INVAL,\n \"term + mode lengths too large\");\n }\n\n channel->reqPTY_packet_len = term_len + modes_len + 41;\n\n /* Zero the whole thing out */\n memset(&channel->reqPTY_packet_requirev_state, 0,\n sizeof(channel->reqPTY_packet_requirev_state));\n\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"Allocating tty on channel %lu/%lu\", channel->local.id,\n channel->remote.id);\n\n s = channel->reqPTY_packet;\n\n *(s++) = SSH_MSG_CHANNEL_REQUEST;\n _libssh2_store_u32(&s, channel->remote.id);\n _libssh2_store_str(&s, (char *)\"pty-req\", sizeof(\"pty-req\") - 1);\n\n *(s++) = 0x01;\n\n _libssh2_store_str(&s, term, term_len);\n _libssh2_store_u32(&s, width);\n _libssh2_store_u32(&s, height);\n _libssh2_store_u32(&s, width_px);\n _libssh2_store_u32(&s, height_px);\n _libssh2_store_str(&s, modes, modes_len);\n\n channel->reqPTY_state = libssh2_NB_state_created;\n }\n\n if(channel->reqPTY_state == libssh2_NB_state_created) {\n rc = _libssh2_transport_send(session, channel->reqPTY_packet,\n channel->reqPTY_packet_len,\n NULL, 0);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n _libssh2_error(session, rc,\n \"Would block sending pty request\");\n return rc;\n }\n else if(rc) {\n channel->reqPTY_state = libssh2_NB_state_idle;\n return _libssh2_error(session, rc,\n \"Unable to send pty-request packet\");\n }\n _libssh2_htonu32(channel->reqPTY_local_channel, channel->local.id);\n\n channel->reqPTY_state = libssh2_NB_state_sent;\n }\n\n if(channel->reqPTY_state == libssh2_NB_state_sent) {\n unsigned char *data;\n size_t data_len;\n unsigned char code;\n rc = _libssh2_packet_requirev(session, reply_codes, &data, &data_len,\n 1, channel->reqPTY_local_channel, 4,\n &channel->reqPTY_packet_requirev_state);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n return rc;\n }\n else if(rc) {\n channel->reqPTY_state = libssh2_NB_state_idle;\n return _libssh2_error(session, LIBSSH2_ERROR_PROTO,\n \"Failed to require the PTY package\");\n }\n\n code = data[0];\n\n LIBSSH2_FREE(session, data);\n channel->reqPTY_state = libssh2_NB_state_idle;\n\n if(code == SSH_MSG_CHANNEL_SUCCESS)\n return 0;\n }\n\n return _libssh2_error(session, LIBSSH2_ERROR_CHANNEL_REQUEST_DENIED,\n \"Unable to complete request for channel request-pty\");\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: _libssh2_channel_process_startup(LIBSSH2_CHANNEL *channel,\n const char *request, size_t request_len,\n const char *message, size_t message_len)\n{\n LIBSSH2_SESSION *session = channel->session;\n unsigned char *s;\n static const unsigned char reply_codes[3] =\n { SSH_MSG_CHANNEL_SUCCESS, SSH_MSG_CHANNEL_FAILURE, 0 };\n int rc;\n\n if(channel->process_state == libssh2_NB_state_end) {\n return _libssh2_error(session, LIBSSH2_ERROR_BAD_USE,\n \"Channel can not be reused\");\n }\n\n if(channel->process_state == libssh2_NB_state_idle) {\n /* 10 = packet_type(1) + channel(4) + request_len(4) + want_reply(1) */\n channel->process_packet_len = request_len + 10;\n\n /* Zero the whole thing out */\n memset(&channel->process_packet_requirev_state, 0,\n sizeof(channel->process_packet_requirev_state));\n\n if(message)\n channel->process_packet_len += + 4;\n\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"starting request(%s) on channel %lu/%lu, message=%s\",\n request, channel->local.id, channel->remote.id,\n message ? message : \"\");\n s = channel->process_packet =\n LIBSSH2_ALLOC(session, channel->process_packet_len);\n if(!channel->process_packet)\n return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate memory \"\n \"for channel-process request\");\n\n *(s++) = SSH_MSG_CHANNEL_REQUEST;\n _libssh2_store_u32(&s, channel->remote.id);\n _libssh2_store_str(&s, request, request_len);\n *(s++) = 0x01;\n\n if(message)\n _libssh2_store_u32(&s, message_len);\n\n channel->process_state = libssh2_NB_state_created;\n }\n\n if(channel->process_state == libssh2_NB_state_created) {\n rc = _libssh2_transport_send(session,\n channel->process_packet,\n channel->process_packet_len,\n (unsigned char *)message, message_len);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n _libssh2_error(session, rc,\n \"Would block sending channel request\");\n return rc;\n }\n else if(rc) {\n LIBSSH2_FREE(session, channel->process_packet);\n channel->process_packet = NULL;\n channel->process_state = libssh2_NB_state_end;\n return _libssh2_error(session, rc,\n \"Unable to send channel request\");\n }\n LIBSSH2_FREE(session, channel->process_packet);\n channel->process_packet = NULL;\n\n _libssh2_htonu32(channel->process_local_channel, channel->local.id);\n\n channel->process_state = libssh2_NB_state_sent;\n }\n\n if(channel->process_state == libssh2_NB_state_sent) {\n unsigned char *data;\n size_t data_len;\n unsigned char code;\n rc = _libssh2_packet_requirev(session, reply_codes, &data, &data_len,\n 1, channel->process_local_channel, 4,\n &channel->process_packet_requirev_state);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n return rc;\n }\n else if(rc) {\n channel->process_state = libssh2_NB_state_end;\n return _libssh2_error(session, rc,\n \"Failed waiting for channel success\");\n }\n\n code = data[0];\n LIBSSH2_FREE(session, data);\n channel->process_state = libssh2_NB_state_end;\n\n if(code == SSH_MSG_CHANNEL_SUCCESS)\n return 0;\n }\n\n return _libssh2_error(session, LIBSSH2_ERROR_CHANNEL_REQUEST_DENIED,\n \"Unable to complete request for \"\n \"channel-process-startup\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315)\n\n* Bounds checks\r\n\r\nFixes for CVEs\r\nhttps://www.libssh2.org/CVE-2019-3863.html\r\nhttps://www.libssh2.org/CVE-2019-3856.html\r\n\r\n* Packet length bounds check\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3855.html\r\n\r\n* Response length check\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3859.html\r\n\r\n* Bounds check\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3857.html\r\n\r\n* Bounds checking\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3859.html\r\n\r\nand additional data validation\r\n\r\n* Check bounds before reading into buffers\r\n\r\n* Bounds checking\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3859.html\r\n\r\n* declare SIZE_MAX and UINT_MAX if needed'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: hostkey_method_ssh_ed25519_init(LIBSSH2_SESSION * session,\n const unsigned char *hostkey_data,\n size_t hostkey_data_len,\n void **abstract)\n{\n const unsigned char *s;\n unsigned long len, key_len;\n libssh2_ed25519_ctx *ctx = NULL;\n\n if(*abstract) {\n hostkey_method_ssh_ed25519_dtor(session, abstract);\n *abstract = NULL;\n }\n\n if(hostkey_data_len < 15) {\n return -1;\n }\n\n s = hostkey_data;\n len = _libssh2_ntohu32(s);\n s += 4;\n\n if(len != 11 || strncmp((char *) s, \"ssh-ed25519\", 11) != 0) {\n return -1;\n }\n\n s += 11;\n\n //public key\n key_len = _libssh2_ntohu32(s);\n s += 4;\n\n if(_libssh2_ed25519_new_public(&ctx, session, s, key_len) != 0) {\n return -1;\n }\n\n *abstract = ctx;\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315)\n\n* Bounds checks\r\n\r\nFixes for CVEs\r\nhttps://www.libssh2.org/CVE-2019-3863.html\r\nhttps://www.libssh2.org/CVE-2019-3856.html\r\n\r\n* Packet length bounds check\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3855.html\r\n\r\n* Response length check\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3859.html\r\n\r\n* Bounds check\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3857.html\r\n\r\n* Bounds checking\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3859.html\r\n\r\nand additional data validation\r\n\r\n* Check bounds before reading into buffers\r\n\r\n* Bounds checking\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3859.html\r\n\r\n* declare SIZE_MAX and UINT_MAX if needed'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int replace_cmd(void) {\n\tchar n[MAX_FNAME], envstr[MAX_ENVSTR];\n\tFILE *tmp;\n\tint ch, eof, fd;\n\tint error = 0;\n\tentry *e;\n\tuid_t file_owner;\n\tchar **envp;\n\tchar *safename;\n\n\n\tsafename = host_specific_filename(\"#tmp\", \"XXXXXXXXXX\");\n\tif (!safename || !glue_strings(TempFilename, sizeof TempFilename, SPOOL_DIR,\n\t\t\tsafename, '/')) {\n\t\tTempFilename[0] = '\\0';\n\t\tfprintf(stderr, \"path too long\\n\");\n\t\treturn (-2);\n\t}\n\tif ((fd = mkstemp(TempFilename)) == -1 || !(tmp = fdopen(fd, \"w+\"))) {\n\t\tperror(TempFilename);\n\t\tif (fd != -1) {\n\t\t\tclose(fd);\n\t\t\tunlink(TempFilename);\n\t\t}\n\t\tTempFilename[0] = '\\0';\n\t\treturn (-2);\n\t}\n\n\t(void) signal(SIGHUP, die);\n\t(void) signal(SIGINT, die);\n\t(void) signal(SIGQUIT, die);\n\n\t/* write a signature at the top of the file.\n\t *\n\t * VERY IMPORTANT: make sure NHEADER_LINES agrees with this code.\n\t */\n\t/*fprintf(tmp, \"# DO NOT EDIT THIS FILE - edit the master and reinstall.\\n\");\n\t *fprintf(tmp, \"# (%s installed on %-24.24s)\\n\", Filename, ctime(&now));\n\t *fprintf(tmp, \"# (Cron version %s)\\n\", CRON_VERSION);\n\t */\n#ifdef WITH_SELINUX\n\tif (selinux_context)\n\t\tfprintf(tmp, \"SELINUX_ROLE_TYPE=%s\\n\", selinux_context);\n#endif\n\n\t/* copy the crontab to the tmp\n\t */\n\trewind(NewCrontab);\n\tSet_LineNum(1)\n\t\twhile (EOF != (ch = get_char(NewCrontab)))\n\t\tputc(ch, tmp);\n\tif (ftruncate(fileno(tmp), ftell(tmp)) == -1) {\n\t\tfprintf(stderr, \"%s: error while writing new crontab to %s\\n\",\n\t\t\tProgramName, TempFilename);\n\t\tfclose(tmp);\n\t\terror = -2;\n\t\tgoto done;\n\t}\n\tfflush(tmp);\n\trewind(tmp);\n\tif (ferror(tmp)) {\n\t\tfprintf(stderr, \"%s: error while writing new crontab to %s\\n\",\n\t\t\tProgramName, TempFilename);\n\t\tfclose(tmp);\n\t\terror = -2;\n\t\tgoto done;\n\t}\n\n\t/* check the syntax of the file being installed.\n\t */\n\n\t/* BUG: was reporting errors after the EOF if there were any errors\n\t * in the file proper -- kludged it by stopping after first error.\n\t * vix 31mar87\n\t */\n\tSet_LineNum(1 - NHEADER_LINES)\n\t\tCheckErrorCount = 0;\n\teof = FALSE;\n\n\tenvp = env_init();\n\tif (envp == NULL) {\n\t\tfprintf(stderr, \"%s: Cannot allocate memory.\\n\", ProgramName);\n\t\tfclose(tmp);\n\t\terror = -2;\n\t\tgoto done;\n\t}\n\n\twhile (!CheckErrorCount && !eof) {\n\t\tswitch (load_env(envstr, tmp)) {\n\t\tcase ERR:\n\t\t\t/* check for data before the EOF */\n\t\t\tif (envstr[0] != '\\0') {\n\t\t\t\tSet_LineNum(LineNumber + 1);\n\t\t\t\tcheck_error(\"premature EOF\");\n\t\t\t}\n\t\t\teof = TRUE;\n\t\t\tbreak;\n\t\tcase FALSE:\n\t\t\te = load_entry(tmp, check_error, pw, envp);\n\t\t\tif (e)\n\t\t\t\tfree_entry(e);\n\t\t\tbreak;\n\t\tcase TRUE:\n\t\t\tbreak;\n\t\t}\n\t}\n\tenv_free(envp);\n\n\tif (CheckErrorCount != 0) {\n\t\tfprintf(stderr, \"errors in crontab file, can't install.\\n\");\n\t\tfclose(tmp);\n\t\terror = -1;\n\t\tgoto done;\n\t}\n\n\tfile_owner = (getgid() == geteuid() && getgid() == getegid()) ? ROOT_UID : pw->pw_uid;\n\n#ifdef HAVE_FCHOWN\n\tif (fchown(fileno(tmp), file_owner, (gid_t)-1) < OK) {\n\t\tperror(\"fchown\");\n\t\tfclose(tmp);\n\t\terror = -2;\n\t\tgoto done;\n\t}\n#else\n\tif (chown(TempFilename, file_owner, (gid_t)-1) < OK) {\n\t\tperror(\"chown\");\n\t\tfclose(tmp);\n\t\terror = -2;\n\t\tgoto done;\n\t}\n#endif\n\n\tif (fclose(tmp) == EOF) {\n\t\tperror(\"fclose\");\n\t\terror = -2;\n\t\tgoto done;\n\t}\n\n\tif (!glue_strings(n, sizeof n, SPOOL_DIR, User, '/')) {\n\t\tfprintf(stderr, \"path too long\\n\");\n\t\terror = -2;\n\t\tgoto done;\n\t}\n\tif (rename(TempFilename, n)) {\n\t\tfprintf(stderr, \"%s: error renaming %s to %s\\n\",\n\t\t\tProgramName, TempFilename, n);\n\t\tperror(\"rename\");\n\t\terror = -2;\n\t\tgoto done;\n\t}\n\tTempFilename[0] = '\\0';\n\tlog_it(RealUser, Pid, \"REPLACE\", User, 0);\n\n\tpoke_daemon();\n\n done:\n\t(void) signal(SIGHUP, SIG_DFL);\n\t(void) signal(SIGINT, SIG_DFL);\n\t(void) signal(SIGQUIT, SIG_DFL);\n\tif (TempFilename[0]) {\n\t\t(void) unlink(TempFilename);\n\t\tTempFilename[0] = '\\0';\n\t}\n\treturn (error);\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_tls_handshake_callback (GObject *object,\n\t\t\t\t\tGAsyncResult *result,\n\t\t\t\t\tgpointer user_data)\n{\n GSocketClientAsyncConnectData *data = user_data;\n\n if (g_tls_connection_handshake_finish (G_TLS_CONNECTION (object),\n\t\t\t\t\t result,\n\t\t\t\t\t &data->last_error))\n {\n g_object_unref (data->connection);\n data->connection = G_IO_STREAM (object);\n\n g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_TLS_HANDSHAKED, data->connectable, data->connection);\n g_socket_client_async_connect_complete (data);\n }\n else\n {\n g_object_unref (object);\n enumerator_next_async (data);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-754'], 'message': 'gsocketclient: Fix criticals\n\nThis ensures the parent GTask is kept alive as long as an enumeration\nis running and trying to connect.\n\nCloses #1646\nCloses #1649'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int exif_process_IFD_in_TIFF(image_info_type *ImageInfo, size_t dir_offset, int section_index)\n{\n\tint i, sn, num_entries, sub_section_index = 0;\n\tunsigned char *dir_entry;\n\tchar tagname[64];\n\tsize_t ifd_size, dir_size, entry_offset, next_offset, entry_length, entry_value=0, fgot;\n\tint entry_tag , entry_type;\n\ttag_table_type tag_table = exif_get_tag_table(section_index);\n\n\tif (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) {\n return FALSE;\n }\n\n\tif (ImageInfo->FileSize >= dir_offset+2) {\n\t\tsn = exif_file_sections_add(ImageInfo, M_PSEUDO, 2, NULL);\n#ifdef EXIF_DEBUG\n\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Read from TIFF: filesize(x%04X), IFD dir(x%04X + x%04X)\", ImageInfo->FileSize, dir_offset, 2);\n#endif\n\t\tphp_stream_seek(ImageInfo->infile, dir_offset, SEEK_SET); /* we do not know the order of sections */\n\t\tphp_stream_read(ImageInfo->infile, (char*)ImageInfo->file.list[sn].data, 2);\n\t\tnum_entries = php_ifd_get16u(ImageInfo->file.list[sn].data, ImageInfo->motorola_intel);\n\t\tdir_size = 2/*num dir entries*/ +12/*length of entry*/*num_entries +4/* offset to next ifd (points to thumbnail or NULL)*/;\n\t\tif (ImageInfo->FileSize >= dir_offset+dir_size) {\n#ifdef EXIF_DEBUG\n\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Read from TIFF: filesize(x%04X), IFD dir(x%04X + x%04X), IFD entries(%d)\", ImageInfo->FileSize, dir_offset+2, dir_size-2, num_entries);\n#endif\n\t\t\tif (exif_file_sections_realloc(ImageInfo, sn, dir_size)) {\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\tphp_stream_read(ImageInfo->infile, (char*)(ImageInfo->file.list[sn].data+2), dir_size-2);\n\t\t\t/*exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Dump: %s\", exif_char_dump(ImageInfo->file.list[sn].data, dir_size, 0));*/\n\t\t\tnext_offset = php_ifd_get32u(ImageInfo->file.list[sn].data + dir_size - 4, ImageInfo->motorola_intel);\n#ifdef EXIF_DEBUG\n\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Read from TIFF done, next offset x%04X\", next_offset);\n#endif\n\t\t\t/* now we have the directory we can look how long it should be */\n\t\t\tifd_size = dir_size;\n\t\t\tfor(i=0;ifile.list[sn].data+2+i*12;\n\t\t\t\tentry_tag = php_ifd_get16u(dir_entry+0, ImageInfo->motorola_intel);\n\t\t\t\tentry_type = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel);\n\t\t\t\tif (entry_type > NUM_FORMATS) {\n\t\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Read from TIFF: tag(0x%04X,%12s): Illegal format code 0x%04X, switching to BYTE\", entry_tag, exif_get_tagname(entry_tag, tagname, -12, tag_table), entry_type);\n\t\t\t\t\t/* Since this is repeated in exif_process_IFD_TAG make it a notice here */\n\t\t\t\t\t/* and make it a warning in the exif_process_IFD_TAG which is called */\n\t\t\t\t\t/* elsewhere. */\n\t\t\t\t\tentry_type = TAG_FMT_BYTE;\n\t\t\t\t\t/*The next line would break the image on writeback: */\n\t\t\t\t\t/* php_ifd_set16u(dir_entry+2, entry_type, ImageInfo->motorola_intel);*/\n\t\t\t\t}\n\t\t\t\tentry_length = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel) * php_tiff_bytes_per_format[entry_type];\n\t\t\t\tif (entry_length <= 4) {\n\t\t\t\t\tswitch(entry_type) {\n\t\t\t\t\t\tcase TAG_FMT_USHORT:\n\t\t\t\t\t\t\tentry_value = php_ifd_get16u(dir_entry+8, ImageInfo->motorola_intel);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase TAG_FMT_SSHORT:\n\t\t\t\t\t\t\tentry_value = php_ifd_get16s(dir_entry+8, ImageInfo->motorola_intel);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase TAG_FMT_ULONG:\n\t\t\t\t\t\t\tentry_value = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase TAG_FMT_SLONG:\n\t\t\t\t\t\t\tentry_value = php_ifd_get32s(dir_entry+8, ImageInfo->motorola_intel);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tswitch(entry_tag) {\n\t\t\t\t\t\tcase TAG_IMAGEWIDTH:\n\t\t\t\t\t\tcase TAG_COMP_IMAGE_WIDTH:\n\t\t\t\t\t\t\tImageInfo->Width = entry_value;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase TAG_IMAGEHEIGHT:\n\t\t\t\t\t\tcase TAG_COMP_IMAGE_HEIGHT:\n\t\t\t\t\t\t\tImageInfo->Height = entry_value;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase TAG_PHOTOMETRIC_INTERPRETATION:\n\t\t\t\t\t\t\tswitch (entry_value) {\n\t\t\t\t\t\t\t\tcase PMI_BLACK_IS_ZERO:\n\t\t\t\t\t\t\t\tcase PMI_WHITE_IS_ZERO:\n\t\t\t\t\t\t\t\tcase PMI_TRANSPARENCY_MASK:\n\t\t\t\t\t\t\t\t\tImageInfo->IsColor = 0;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase PMI_RGB:\n\t\t\t\t\t\t\t\tcase PMI_PALETTE_COLOR:\n\t\t\t\t\t\t\t\tcase PMI_SEPARATED:\n\t\t\t\t\t\t\t\tcase PMI_YCBCR:\n\t\t\t\t\t\t\t\tcase PMI_CIELAB:\n\t\t\t\t\t\t\t\t\tImageInfo->IsColor = 1;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tentry_offset = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel);\n\t\t\t\t\t/* if entry needs expading ifd cache and entry is at end of current ifd cache. */\n\t\t\t\t\t/* otherwise there may be huge holes between two entries */\n\t\t\t\t\tif (entry_offset + entry_length > dir_offset + ifd_size\n\t\t\t\t\t && entry_offset == dir_offset + ifd_size) {\n\t\t\t\t\t\tifd_size = entry_offset + entry_length - dir_offset;\n#ifdef EXIF_DEBUG\n\t\t\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Resize struct: x%04X + x%04X - x%04X = x%04X\", entry_offset, entry_length, dir_offset, ifd_size);\n#endif\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (ImageInfo->FileSize >= dir_offset + ImageInfo->file.list[sn].size) {\n\t\t\t\tif (ifd_size > dir_size) {\n\t\t\t\t\tif (dir_offset + ifd_size > ImageInfo->FileSize) {\n\t\t\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, \"Error in TIFF: filesize(x%04X) less than size of IFD(x%04X + x%04X)\", ImageInfo->FileSize, dir_offset, ifd_size);\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t\t}\n\t\t\t\t\tif (exif_file_sections_realloc(ImageInfo, sn, ifd_size)) {\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t\t}\n\t\t\t\t\t/* read values not stored in directory itself */\n#ifdef EXIF_DEBUG\n\t\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Read from TIFF: filesize(x%04X), IFD(x%04X + x%04X)\", ImageInfo->FileSize, dir_offset, ifd_size);\n#endif\n\t\t\t\t\tphp_stream_read(ImageInfo->infile, (char*)(ImageInfo->file.list[sn].data+dir_size), ifd_size-dir_size);\n#ifdef EXIF_DEBUG\n\t\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Read from TIFF, done\");\n#endif\n\t\t\t\t}\n\t\t\t\t/* now process the tags */\n\t\t\t\tfor(i=0;ifile.list[sn].data+2+i*12;\n\t\t\t\t\tentry_tag = php_ifd_get16u(dir_entry+0, ImageInfo->motorola_intel);\n\t\t\t\t\tentry_type = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel);\n\t\t\t\t\t/*entry_length = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel);*/\n\t\t\t\t\tif (entry_tag == TAG_EXIF_IFD_POINTER ||\n\t\t\t\t\t\tentry_tag == TAG_INTEROP_IFD_POINTER ||\n\t\t\t\t\t\tentry_tag == TAG_GPS_IFD_POINTER ||\n\t\t\t\t\t\tentry_tag == TAG_SUB_IFD\n\t\t\t\t\t) {\n\t\t\t\t\t\tswitch(entry_tag) {\n\t\t\t\t\t\t\tcase TAG_EXIF_IFD_POINTER:\n\t\t\t\t\t\t\t\tImageInfo->sections_found |= FOUND_EXIF;\n\t\t\t\t\t\t\t\tsub_section_index = SECTION_EXIF;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase TAG_GPS_IFD_POINTER:\n\t\t\t\t\t\t\t\tImageInfo->sections_found |= FOUND_GPS;\n\t\t\t\t\t\t\t\tsub_section_index = SECTION_GPS;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase TAG_INTEROP_IFD_POINTER:\n\t\t\t\t\t\t\t\tImageInfo->sections_found |= FOUND_INTEROP;\n\t\t\t\t\t\t\t\tsub_section_index = SECTION_INTEROP;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase TAG_SUB_IFD:\n\t\t\t\t\t\t\t\tImageInfo->sections_found |= FOUND_THUMBNAIL;\n\t\t\t\t\t\t\t\tsub_section_index = SECTION_THUMBNAIL;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tentry_offset = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel);\n#ifdef EXIF_DEBUG\n\t\t\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Next IFD: %s @x%04X\", exif_get_sectionname(sub_section_index), entry_offset);\n#endif\n\t\t\t\t\t\tImageInfo->ifd_nesting_level++;\n\t\t\t\t\t\texif_process_IFD_in_TIFF(ImageInfo, entry_offset, sub_section_index);\n\t\t\t\t\t\tif (section_index!=SECTION_THUMBNAIL && entry_tag==TAG_SUB_IFD) {\n\t\t\t\t\t\t\tif (ImageInfo->Thumbnail.filetype != IMAGE_FILETYPE_UNKNOWN\n\t\t\t\t\t\t\t&& ImageInfo->Thumbnail.size\n\t\t\t\t\t\t\t&& ImageInfo->Thumbnail.offset\n\t\t\t\t\t\t\t&& ImageInfo->read_thumbnail\n\t\t\t\t\t\t\t) {\n#ifdef EXIF_DEBUG\n\t\t\t\t\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"%s THUMBNAIL @0x%04X + 0x%04X\", ImageInfo->Thumbnail.data ? \"Ignore\" : \"Read\", ImageInfo->Thumbnail.offset, ImageInfo->Thumbnail.size);\n#endif\n\t\t\t\t\t\t\t\tif (!ImageInfo->Thumbnail.data) {\n\t\t\t\t\t\t\t\t\tImageInfo->Thumbnail.data = safe_emalloc(ImageInfo->Thumbnail.size, 1, 0);\n\t\t\t\t\t\t\t\t\tphp_stream_seek(ImageInfo->infile, ImageInfo->Thumbnail.offset, SEEK_SET);\n\t\t\t\t\t\t\t\t\tfgot = php_stream_read(ImageInfo->infile, ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size);\n\t\t\t\t\t\t\t\t\tif (fgot < ImageInfo->Thumbnail.size) {\n\t\t\t\t\t\t\t\t\t\tEXIF_ERRLOG_THUMBEOF(ImageInfo)\n\t\t\t\t\t\t\t\t\t\tefree(ImageInfo->Thumbnail.data);\n\n\t\t\t\t\t\t\t\t\t\tImageInfo->Thumbnail.data = NULL;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\texif_thumbnail_build(ImageInfo);\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}\n\t\t\t\t\t\t}\n#ifdef EXIF_DEBUG\n\t\t\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Next IFD: %s done\", exif_get_sectionname(sub_section_index));\n#endif\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (!exif_process_IFD_TAG(ImageInfo, (char*)dir_entry,\n\t\t\t\t\t\t\t\t\t\t\t\t (char*)(ImageInfo->file.list[sn].data-dir_offset),\n\t\t\t\t\t\t\t\t\t\t\t\t ifd_size, 0, section_index, 0, tag_table)) {\n\t\t\t\t\t\t\treturn FALSE;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t/* If we had a thumbnail in a SUB_IFD we have ANOTHER image in NEXT IFD */\n\t\t\t\tif (next_offset && section_index != SECTION_THUMBNAIL) {\n\t\t\t\t\t/* this should be a thumbnail IFD */\n\t\t\t\t\t/* the thumbnail itself is stored at Tag=StripOffsets */\n#ifdef EXIF_DEBUG\n\t\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Read next IFD (THUMBNAIL) at x%04X\", next_offset);\n#endif\n\t\t\t\t\tImageInfo->ifd_nesting_level++;\n\t\t\t\t\texif_process_IFD_in_TIFF(ImageInfo, next_offset, SECTION_THUMBNAIL);\n#ifdef EXIF_DEBUG\n\t\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"%s THUMBNAIL @0x%04X + 0x%04X\", ImageInfo->Thumbnail.data ? \"Ignore\" : \"Read\", ImageInfo->Thumbnail.offset, ImageInfo->Thumbnail.size);\n#endif\n\t\t\t\t\tif (!ImageInfo->Thumbnail.data && ImageInfo->Thumbnail.offset && ImageInfo->Thumbnail.size && ImageInfo->read_thumbnail) {\n\t\t\t\t\t\tImageInfo->Thumbnail.data = safe_emalloc(ImageInfo->Thumbnail.size, 1, 0);\n\t\t\t\t\t\tphp_stream_seek(ImageInfo->infile, ImageInfo->Thumbnail.offset, SEEK_SET);\n\t\t\t\t\t\tfgot = php_stream_read(ImageInfo->infile, ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size);\n\t\t\t\t\t\tif (fgot < ImageInfo->Thumbnail.size) {\n\t\t\t\t\t\t\tEXIF_ERRLOG_THUMBEOF(ImageInfo)\n\t\t\t\t\t\t\tefree(ImageInfo->Thumbnail.data);\n\t\t\t\t\t\t\tImageInfo->Thumbnail.data = NULL;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\texif_thumbnail_build(ImageInfo);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n#ifdef EXIF_DEBUG\n\t\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Read next IFD (THUMBNAIL) done\");\n#endif\n\t\t\t\t}\n\t\t\t\treturn TRUE;\n\t\t\t} else {\n\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, \"Error in TIFF: filesize(x%04X) less than size of IFD(x%04X)\", ImageInfo->FileSize, dir_offset+ImageInfo->file.list[sn].size);\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t} else {\n\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, \"Error in TIFF: filesize(x%04X) less than size of IFD dir(x%04X)\", ImageInfo->FileSize, dir_offset+dir_size);\n\t\t\treturn FALSE;\n\t\t}\n\t} else {\n\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, \"Error in TIFF: filesize(x%04X) less than start of IFD dir(x%04X)\", ImageInfo->FileSize, dir_offset+2);\n\t\treturn FALSE;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-908'], 'message': 'Fix integer overflows on 32-bits'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: pax_decode_header (struct tar_sparse_file *file)\n{\n if (file->stat_info->sparse_major > 0)\n {\n uintmax_t u;\n char nbuf[UINTMAX_STRSIZE_BOUND];\n union block *blk;\n char *p;\n size_t i;\n off_t start;\n \n#define COPY_BUF(b,buf,src) do \\\n { \\\n char *endp = b->buffer + BLOCKSIZE; \\\n char *dst = buf; \\\n do \\\n { \\\n if (dst == buf + UINTMAX_STRSIZE_BOUND -1) \\\n { \\\n ERROR ((0, 0, _(\"%s: numeric overflow in sparse archive member\"), \\\n\t file->stat_info->orig_file_name)); \\\n return false; \\\n } \\\n if (src == endp) \\\n\t { \\\n\t set_next_block_after (b); \\\n b = find_next_block (); \\\n src = b->buffer; \\\n\t endp = b->buffer + BLOCKSIZE; \\\n\t } \\\n *dst = *src++; \\\n } \\\n while (*dst++ != '\\n'); \\\n dst[-1] = 0; \\\n } while (0)\n\n start = current_block_ordinal ();\n set_next_block_after (current_header);\n blk = find_next_block ();\n p = blk->buffer;\n COPY_BUF (blk,nbuf,p);\n if (!decode_num (&u, nbuf, TYPE_MAXIMUM (size_t)))\n\t{\n\t ERROR ((0, 0, _(\"%s: malformed sparse archive member\"),\n\t\t file->stat_info->orig_file_name));\n\t return false;\n\t}\n file->stat_info->sparse_map_size = u;\n file->stat_info->sparse_map = xcalloc (file->stat_info->sparse_map_size,\n\t\t\t\t\t sizeof (*file->stat_info->sparse_map));\n file->stat_info->sparse_map_avail = 0;\n for (i = 0; i < file->stat_info->sparse_map_size; i++)\n\t{\n\t struct sp_array sp;\n\n\t COPY_BUF (blk,nbuf,p);\n\t if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t)))\n\t {\n\t ERROR ((0, 0, _(\"%s: malformed sparse archive member\"),\n\t\t file->stat_info->orig_file_name));\n\t return false;\n\t }\n\t sp.offset = u;\n\t COPY_BUF (blk,nbuf,p);\n\t if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t)))\n\t {\n\t ERROR ((0, 0, _(\"%s: malformed sparse archive member\"),\n\t\t file->stat_info->orig_file_name));\n\t return false;\n\t }\n\t sp.numbytes = u;\n\t sparse_add_map (file->stat_info, &sp);\n\t}\n set_next_block_after (blk);\n\n file->dumped_size += BLOCKSIZE * (current_block_ordinal () - start);\n }\n\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix possible NULL dereference (savannah bug #55369)\n\n* src/sparse.c (pax_decode_header): Check return from find_next_block.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void *load_device_tree(const char *filename_path, int *sizep)\n{\n int dt_size;\n int dt_file_load_size;\n int ret;\n void *fdt = NULL;\n\n *sizep = 0;\n dt_size = get_image_size(filename_path);\n if (dt_size < 0) {\n error_report(\"Unable to get size of device tree file '%s'\",\n filename_path);\n goto fail;\n }\n\n /* Expand to 2x size to give enough room for manipulation. */\n dt_size += 10000;\n dt_size *= 2;\n /* First allocate space in qemu for device tree */\n fdt = g_malloc0(dt_size);\n\n dt_file_load_size = load_image_size(filename_path, fdt, dt_size);\n if (dt_file_load_size < 0) {\n error_report(\"Unable to open device tree file '%s'\",\n filename_path);\n goto fail;\n }\n\n ret = fdt_open_into(fdt, fdt, dt_size);\n if (ret) {\n error_report(\"Unable to copy device tree in memory\");\n goto fail;\n }\n\n /* Check sanity of device tree */\n if (fdt_check_header(fdt)) {\n error_report(\"Device tree file loaded into memory is invalid: %s\",\n filename_path);\n goto fail;\n }\n *sizep = dt_size;\n return fdt;\n\nfail:\n g_free(fdt);\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'device_tree: Fix integer overflowing in load_device_tree()\n\nIf the value of get_image_size() exceeds INT_MAX / 2 - 10000, the\ncomputation of @dt_size overflows to a negative number, which then\ngets converted to a very large size_t for g_malloc0() and\nload_image_size(). In the (fortunately improbable) case g_malloc0()\nsucceeds and load_image_size() survives, we'd assign the negative\nnumber to *sizep. What that would do to the callers I can't say, but\nit's unlikely to be good.\n\nFix by rejecting images whose size would overflow.\n\nReported-by: Kurtis Miller \nSigned-off-by: Markus Armbruster \nReviewed-by: Philippe Mathieu-Daud\u00e9 \nSigned-off-by: Alistair Francis \nMessage-Id: <20190409174018.25798-1-armbru@redhat.com>'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int inotify_update_existing_watch(struct fsnotify_group *group,\n\t\t\t\t\t struct inode *inode,\n\t\t\t\t\t u32 arg)\n{\n\tstruct fsnotify_mark *fsn_mark;\n\tstruct inotify_inode_mark *i_mark;\n\t__u32 old_mask, new_mask;\n\t__u32 mask;\n\tint add = (arg & IN_MASK_ADD);\n\tint create = (arg & IN_MASK_CREATE);\n\tint ret;\n\n\tmask = inotify_arg_to_mask(arg);\n\n\tfsn_mark = fsnotify_find_mark(&inode->i_fsnotify_marks, group);\n\tif (!fsn_mark)\n\t\treturn -ENOENT;\n\telse if (create)\n\t\treturn -EEXIST;\n\n\ti_mark = container_of(fsn_mark, struct inotify_inode_mark, fsn_mark);\n\n\tspin_lock(&fsn_mark->lock);\n\told_mask = fsn_mark->mask;\n\tif (add)\n\t\tfsn_mark->mask |= mask;\n\telse\n\t\tfsn_mark->mask = mask;\n\tnew_mask = fsn_mark->mask;\n\tspin_unlock(&fsn_mark->lock);\n\n\tif (old_mask != new_mask) {\n\t\t/* more bits in old than in new? */\n\t\tint dropped = (old_mask & ~new_mask);\n\t\t/* more bits in this fsn_mark than the inode's mask? */\n\t\tint do_inode = (new_mask & ~inode->i_fsnotify_mask);\n\n\t\t/* update the inode with this new fsn_mark */\n\t\tif (dropped || do_inode)\n\t\t\tfsnotify_recalc_mask(inode->i_fsnotify_marks);\n\n\t}\n\n\t/* return the wd */\n\tret = i_mark->wd;\n\n\t/* match the get from fsnotify_find_mark() */\n\tfsnotify_put_mark(fsn_mark);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'inotify: Fix fsnotify_mark refcount leak in inotify_update_existing_watch()\n\nCommit 4d97f7d53da7dc83 (\"inotify: Add flag IN_MASK_CREATE for\ninotify_add_watch()\") forgot to call fsnotify_put_mark() with\nIN_MASK_CREATE after fsnotify_find_mark()\n\nFixes: 4d97f7d53da7dc83 (\"inotify: Add flag IN_MASK_CREATE for inotify_add_watch()\")\nSigned-off-by: ZhangXiaoxu \nSigned-off-by: Jan Kara '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int aio_prep_rw(struct kiocb *req, const struct iocb *iocb)\n{\n\tint ret;\n\n\treq->ki_filp = fget(iocb->aio_fildes);\n\tif (unlikely(!req->ki_filp))\n\t\treturn -EBADF;\n\treq->ki_complete = aio_complete_rw;\n\treq->private = NULL;\n\treq->ki_pos = iocb->aio_offset;\n\treq->ki_flags = iocb_flags(req->ki_filp);\n\tif (iocb->aio_flags & IOCB_FLAG_RESFD)\n\t\treq->ki_flags |= IOCB_EVENTFD;\n\treq->ki_hint = ki_hint_validate(file_write_hint(req->ki_filp));\n\tif (iocb->aio_flags & IOCB_FLAG_IOPRIO) {\n\t\t/*\n\t\t * If the IOCB_FLAG_IOPRIO flag of aio_flags is set, then\n\t\t * aio_reqprio is interpreted as an I/O scheduling\n\t\t * class and priority.\n\t\t */\n\t\tret = ioprio_check_cap(iocb->aio_reqprio);\n\t\tif (ret) {\n\t\t\tpr_debug(\"aio ioprio check cap error: %d\\n\", ret);\n\t\t\tgoto out_fput;\n\t\t}\n\n\t\treq->ki_ioprio = iocb->aio_reqprio;\n\t} else\n\t\treq->ki_ioprio = get_current_ioprio();\n\n\tret = kiocb_set_rw_flags(req, iocb->aio_rw_flags);\n\tif (unlikely(ret))\n\t\tgoto out_fput;\n\n\treq->ki_flags &= ~IOCB_HIPRI; /* no one is going to poll for this I/O */\n\treturn 0;\n\nout_fput:\n\tfput(req->ki_filp);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'aio: simplify - and fix - fget/fput for io_submit()\n\nAl Viro root-caused a race where the IOCB_CMD_POLL handling of\nfget/fput() could cause us to access the file pointer after it had\nalready been freed:\n\n \"In more details - normally IOCB_CMD_POLL handling looks so:\n\n 1) io_submit(2) allocates aio_kiocb instance and passes it to\n aio_poll()\n\n 2) aio_poll() resolves the descriptor to struct file by req->file =\n fget(iocb->aio_fildes)\n\n 3) aio_poll() sets ->woken to false and raises ->ki_refcnt of that\n aio_kiocb to 2 (bumps by 1, that is).\n\n 4) aio_poll() calls vfs_poll(). After sanity checks (basically,\n \"poll_wait() had been called and only once\") it locks the queue.\n That's what the extra reference to iocb had been for - we know we\n can safely access it.\n\n 5) With queue locked, we check if ->woken has already been set to\n true (by aio_poll_wake()) and, if it had been, we unlock the\n queue, drop a reference to aio_kiocb and bugger off - at that\n point it's a responsibility to aio_poll_wake() and the stuff\n called/scheduled by it. That code will drop the reference to file\n in req->file, along with the other reference to our aio_kiocb.\n\n 6) otherwise, we see whether we need to wait. If we do, we unlock the\n queue, drop one reference to aio_kiocb and go away - eventual\n wakeup (or cancel) will deal with the reference to file and with\n the other reference to aio_kiocb\n\n 7) otherwise we remove ourselves from waitqueue (still under the\n queue lock), so that wakeup won't get us. No async activity will\n be happening, so we can safely drop req->file and iocb ourselves.\n\n If wakeup happens while we are in vfs_poll(), we are fine - aio_kiocb\n won't get freed under us, so we can do all the checks and locking\n safely. And we don't touch ->file if we detect that case.\n\n However, vfs_poll() most certainly *does* touch the file it had been\n given. So wakeup coming while we are still in ->poll() might end up\n doing fput() on that file. That case is not too rare, and usually we\n are saved by the still present reference from descriptor table - that\n fput() is not the final one.\n\n But if another thread closes that descriptor right after our fget()\n and wakeup does happen before ->poll() returns, we are in trouble -\n final fput() done while we are in the middle of a method:\n\nAl also wrote a patch to take an extra reference to the file descriptor\nto fix this, but I instead suggested we just streamline the whole file\npointer handling by submit_io() so that the generic aio submission code\nsimply keeps the file pointer around until the aio has completed.\n\nFixes: bfe4037e722e (\"aio: implement IOCB_CMD_POLL\")\nAcked-by: Al Viro \nReported-by: syzbot+503d4cc169fcec1cb18c@syzkaller.appspotmail.com\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: do_conversion (const char *tocode, const char *fromcode, char const *in_org, size_t inlen, char **out)\n{\n iconv_t cd;\n /* sXXXav : hummm hard to guess... */\n size_t len, done, outlen;\n int invalid = 0, tooshort = 0;\n char *s, *in, *in_save;\n\n cd = iconv_open (tocode, fromcode);\n if (cd == (iconv_t)(-1))\n {\n logprintf (LOG_VERBOSE, _(\"Conversion from %s to %s isn't supported\\n\"),\n quote (fromcode), quote (tocode));\n *out = NULL;\n return false;\n }\n\n /* iconv() has to work on an unescaped string */\n in_save = in = xstrndup (in_org, inlen);\n url_unescape_except_reserved (in);\n inlen = strlen(in);\n\n len = outlen = inlen * 2;\n *out = s = xmalloc (outlen + 1);\n done = 0;\n\n DEBUGP ((\"iconv %s -> %s\\n\", tocode, fromcode));\n\n for (;;)\n {\n DEBUGP ((\"iconv outlen=%d inlen=%d\\n\", outlen, inlen));\n if (iconv (cd, (ICONV_CONST char **) &in, &inlen, out, &outlen) != (size_t)(-1) &&\n iconv (cd, NULL, NULL, out, &outlen) != (size_t)(-1))\n {\n *out = s;\n *(s + len - outlen - done) = '\\0';\n xfree(in_save);\n iconv_close(cd);\n IF_DEBUG\n {\n /* not not print out embedded passwords, in_org might be an URL */\n if (!strchr(in_org, '@') && !strchr(*out, '@'))\n debug_logprintf (\"converted '%s' (%s) -> '%s' (%s)\\n\", in_org, fromcode, *out, tocode);\n else\n debug_logprintf (\"logging suppressed, strings may contain password\\n\");\n }\n return true;\n }\n\n /* Incomplete or invalid multibyte sequence */\n if (errno == EINVAL || errno == EILSEQ)\n {\n if (!invalid)\n logprintf (LOG_VERBOSE,\n _(\"Incomplete or invalid multibyte sequence encountered\\n\"));\n\n invalid++;\n **out = *in;\n in++;\n inlen--;\n (*out)++;\n outlen--;\n }\n else if (errno == E2BIG) /* Output buffer full */\n {\n logprintf (LOG_VERBOSE,\n _(\"Reallocate output buffer len=%d outlen=%d inlen=%d\\n\"), len, outlen, inlen);\n tooshort++;\n done = len;\n len = done + inlen * 2;\n s = xrealloc (s, len + 1);\n *out = s + done - outlen;\n outlen += inlen * 2;\n }\n else /* Weird, we got an unspecified error */\n {\n logprintf (LOG_VERBOSE, _(\"Unhandled errno %d\\n\"), errno);\n break;\n }\n }\n\n xfree(in_save);\n iconv_close(cd);\n IF_DEBUG\n {\n /* not not print out embedded passwords, in_org might be an URL */\n if (!strchr(in_org, '@') && !strchr(*out, '@'))\n debug_logprintf (\"converted '%s' (%s) -> '%s' (%s)\\n\", in_org, fromcode, *out, tocode);\n else\n debug_logprintf (\"logging suppressed, strings may contain password\\n\");\n }\n return false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': '* src/iri.c (do_conversion): Remove unneeded debug lines'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: qb_ipcs_create(const char *name,\n\t int32_t service_id,\n\t enum qb_ipc_type type, struct qb_ipcs_service_handlers *handlers)\n{\n\tstruct qb_ipcs_service *s;\n\tint fd;\n\tunsigned int seed;\n\n\ts = calloc(1, sizeof(struct qb_ipcs_service));\n\tif (s == NULL) {\n\t\treturn NULL;\n\t}\n\tif (type == QB_IPC_NATIVE) {\n#ifdef DISABLE_IPC_SHM\n\t\ts->type = QB_IPC_SOCKET;\n#else\n\t\ts->type = QB_IPC_SHM;\n#endif /* DISABLE_IPC_SHM */\n\t} else {\n\t\ts->type = type;\n\t}\n\n\ts->pid = getpid();\n\ts->needs_sock_for_poll = QB_FALSE;\n\ts->poll_priority = QB_LOOP_MED;\n\n\t/* Initial alloc ref */\n\tqb_ipcs_ref(s);\n\n\ts->service_id = service_id;\n\t(void)strlcpy(s->name, name, NAME_MAX);\n\n\ts->serv_fns.connection_accept = handlers->connection_accept;\n\ts->serv_fns.connection_created = handlers->connection_created;\n\ts->serv_fns.msg_process = handlers->msg_process;\n\ts->serv_fns.connection_closed = handlers->connection_closed;\n\ts->serv_fns.connection_destroyed = handlers->connection_destroyed;\n\n\tqb_list_init(&s->connections);\n\tqb_list_init(&s->list);\n\tqb_list_add(&s->list, &qb_ipc_services);\n\n\t/* Randomise socket names */\n\tfd = open(\"/dev/urandom\", O_RDONLY);\n\tif (fd == -1) {\n\t\tseed = (time_t)time(NULL);\n\t} else {\n\t\tif (read(fd, &seed, sizeof(seed)) != 4) {\n\t\t\tseed = (time_t)time(NULL);\n\t\t}\n\t\tclose(fd);\n\t}\n\tsrand(seed);\n\n\treturn s;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59'], 'message': 'ipc: fixes\n\nUse O_EXCL on IPC files'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: SYSCALL_DEFINE5(perf_event_open,\n\t\tstruct perf_event_attr __user *, attr_uptr,\n\t\tpid_t, pid, int, cpu, int, group_fd, unsigned long, flags)\n{\n\tstruct perf_event *group_leader = NULL, *output_event = NULL;\n\tstruct perf_event *event, *sibling;\n\tstruct perf_event_attr attr;\n\tstruct perf_event_context *ctx, *uninitialized_var(gctx);\n\tstruct file *event_file = NULL;\n\tstruct fd group = {NULL, 0};\n\tstruct task_struct *task = NULL;\n\tstruct pmu *pmu;\n\tint event_fd;\n\tint move_group = 0;\n\tint err;\n\tint f_flags = O_RDWR;\n\tint cgroup_fd = -1;\n\n\t/* for future expandability... */\n\tif (flags & ~PERF_FLAG_ALL)\n\t\treturn -EINVAL;\n\n\terr = perf_copy_attr(attr_uptr, &attr);\n\tif (err)\n\t\treturn err;\n\n\tif (!attr.exclude_kernel) {\n\t\tif (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))\n\t\t\treturn -EACCES;\n\t}\n\n\tif (attr.freq) {\n\t\tif (attr.sample_freq > sysctl_perf_event_sample_rate)\n\t\t\treturn -EINVAL;\n\t} else {\n\t\tif (attr.sample_period & (1ULL << 63))\n\t\t\treturn -EINVAL;\n\t}\n\n\t/*\n\t * In cgroup mode, the pid argument is used to pass the fd\n\t * opened to the cgroup directory in cgroupfs. The cpu argument\n\t * designates the cpu on which to monitor threads from that\n\t * cgroup.\n\t */\n\tif ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))\n\t\treturn -EINVAL;\n\n\tif (flags & PERF_FLAG_FD_CLOEXEC)\n\t\tf_flags |= O_CLOEXEC;\n\n\tevent_fd = get_unused_fd_flags(f_flags);\n\tif (event_fd < 0)\n\t\treturn event_fd;\n\n\tif (group_fd != -1) {\n\t\terr = perf_fget_light(group_fd, &group);\n\t\tif (err)\n\t\t\tgoto err_fd;\n\t\tgroup_leader = group.file->private_data;\n\t\tif (flags & PERF_FLAG_FD_OUTPUT)\n\t\t\toutput_event = group_leader;\n\t\tif (flags & PERF_FLAG_FD_NO_GROUP)\n\t\t\tgroup_leader = NULL;\n\t}\n\n\tif (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {\n\t\ttask = find_lively_task_by_vpid(pid);\n\t\tif (IS_ERR(task)) {\n\t\t\terr = PTR_ERR(task);\n\t\t\tgoto err_group_fd;\n\t\t}\n\t}\n\n\tif (task && group_leader &&\n\t group_leader->attr.inherit != attr.inherit) {\n\t\terr = -EINVAL;\n\t\tgoto err_task;\n\t}\n\n\tget_online_cpus();\n\n\tif (flags & PERF_FLAG_PID_CGROUP)\n\t\tcgroup_fd = pid;\n\n\tevent = perf_event_alloc(&attr, cpu, task, group_leader, NULL,\n\t\t\t\t NULL, NULL, cgroup_fd);\n\tif (IS_ERR(event)) {\n\t\terr = PTR_ERR(event);\n\t\tgoto err_cpus;\n\t}\n\n\tif (is_sampling_event(event)) {\n\t\tif (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {\n\t\t\terr = -ENOTSUPP;\n\t\t\tgoto err_alloc;\n\t\t}\n\t}\n\n\t/*\n\t * Special case software events and allow them to be part of\n\t * any hardware group.\n\t */\n\tpmu = event->pmu;\n\n\tif (attr.use_clockid) {\n\t\terr = perf_event_set_clock(event, attr.clockid);\n\t\tif (err)\n\t\t\tgoto err_alloc;\n\t}\n\n\tif (group_leader &&\n\t (is_software_event(event) != is_software_event(group_leader))) {\n\t\tif (is_software_event(event)) {\n\t\t\t/*\n\t\t\t * If event and group_leader are not both a software\n\t\t\t * event, and event is, then group leader is not.\n\t\t\t *\n\t\t\t * Allow the addition of software events to !software\n\t\t\t * groups, this is safe because software events never\n\t\t\t * fail to schedule.\n\t\t\t */\n\t\t\tpmu = group_leader->pmu;\n\t\t} else if (is_software_event(group_leader) &&\n\t\t\t (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {\n\t\t\t/*\n\t\t\t * In case the group is a pure software group, and we\n\t\t\t * try to add a hardware event, move the whole group to\n\t\t\t * the hardware context.\n\t\t\t */\n\t\t\tmove_group = 1;\n\t\t}\n\t}\n\n\t/*\n\t * Get the target context (task or percpu):\n\t */\n\tctx = find_get_context(pmu, task, event);\n\tif (IS_ERR(ctx)) {\n\t\terr = PTR_ERR(ctx);\n\t\tgoto err_alloc;\n\t}\n\n\tif ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) {\n\t\terr = -EBUSY;\n\t\tgoto err_context;\n\t}\n\n\tif (task) {\n\t\tput_task_struct(task);\n\t\ttask = NULL;\n\t}\n\n\t/*\n\t * Look up the group leader (we will attach this event to it):\n\t */\n\tif (group_leader) {\n\t\terr = -EINVAL;\n\n\t\t/*\n\t\t * Do not allow a recursive hierarchy (this new sibling\n\t\t * becoming part of another group-sibling):\n\t\t */\n\t\tif (group_leader->group_leader != group_leader)\n\t\t\tgoto err_context;\n\n\t\t/* All events in a group should have the same clock */\n\t\tif (group_leader->clock != event->clock)\n\t\t\tgoto err_context;\n\n\t\t/*\n\t\t * Do not allow to attach to a group in a different\n\t\t * task or CPU context:\n\t\t */\n\t\tif (move_group) {\n\t\t\t/*\n\t\t\t * Make sure we're both on the same task, or both\n\t\t\t * per-cpu events.\n\t\t\t */\n\t\t\tif (group_leader->ctx->task != ctx->task)\n\t\t\t\tgoto err_context;\n\n\t\t\t/*\n\t\t\t * Make sure we're both events for the same CPU;\n\t\t\t * grouping events for different CPUs is broken; since\n\t\t\t * you can never concurrently schedule them anyhow.\n\t\t\t */\n\t\t\tif (group_leader->cpu != event->cpu)\n\t\t\t\tgoto err_context;\n\t\t} else {\n\t\t\tif (group_leader->ctx != ctx)\n\t\t\t\tgoto err_context;\n\t\t}\n\n\t\t/*\n\t\t * Only a group leader can be exclusive or pinned\n\t\t */\n\t\tif (attr.exclusive || attr.pinned)\n\t\t\tgoto err_context;\n\t}\n\n\tif (output_event) {\n\t\terr = perf_event_set_output(event, output_event);\n\t\tif (err)\n\t\t\tgoto err_context;\n\t}\n\n\tevent_file = anon_inode_getfile(\"[perf_event]\", &perf_fops, event,\n\t\t\t\t\tf_flags);\n\tif (IS_ERR(event_file)) {\n\t\terr = PTR_ERR(event_file);\n\t\tevent_file = NULL;\n\t\tgoto err_context;\n\t}\n\n\tif (move_group) {\n\t\tgctx = group_leader->ctx;\n\t\tmutex_lock_double(&gctx->mutex, &ctx->mutex);\n\t\tif (gctx->task == TASK_TOMBSTONE) {\n\t\t\terr = -ESRCH;\n\t\t\tgoto err_locked;\n\t\t}\n\t} else {\n\t\tmutex_lock(&ctx->mutex);\n\t}\n\n\tif (ctx->task == TASK_TOMBSTONE) {\n\t\terr = -ESRCH;\n\t\tgoto err_locked;\n\t}\n\n\tif (!perf_event_validate_size(event)) {\n\t\terr = -E2BIG;\n\t\tgoto err_locked;\n\t}\n\n\t/*\n\t * Must be under the same ctx::mutex as perf_install_in_context(),\n\t * because we need to serialize with concurrent event creation.\n\t */\n\tif (!exclusive_event_installable(event, ctx)) {\n\t\t/* exclusive and group stuff are assumed mutually exclusive */\n\t\tWARN_ON_ONCE(move_group);\n\n\t\terr = -EBUSY;\n\t\tgoto err_locked;\n\t}\n\n\tWARN_ON_ONCE(ctx->parent_ctx);\n\n\tif (move_group) {\n\t\t/*\n\t\t * See perf_event_ctx_lock() for comments on the details\n\t\t * of swizzling perf_event::ctx.\n\t\t */\n\t\tperf_remove_from_context(group_leader, 0);\n\n\t\tlist_for_each_entry(sibling, &group_leader->sibling_list,\n\t\t\t\t group_entry) {\n\t\t\tperf_remove_from_context(sibling, 0);\n\t\t\tput_ctx(gctx);\n\t\t}\n\n\t\t/*\n\t\t * Wait for everybody to stop referencing the events through\n\t\t * the old lists, before installing it on new lists.\n\t\t */\n\t\tsynchronize_rcu();\n\n\t\t/*\n\t\t * Install the group siblings before the group leader.\n\t\t *\n\t\t * Because a group leader will try and install the entire group\n\t\t * (through the sibling list, which is still in-tact), we can\n\t\t * end up with siblings installed in the wrong context.\n\t\t *\n\t\t * By installing siblings first we NO-OP because they're not\n\t\t * reachable through the group lists.\n\t\t */\n\t\tlist_for_each_entry(sibling, &group_leader->sibling_list,\n\t\t\t\t group_entry) {\n\t\t\tperf_event__state_init(sibling);\n\t\t\tperf_install_in_context(ctx, sibling, sibling->cpu);\n\t\t\tget_ctx(ctx);\n\t\t}\n\n\t\t/*\n\t\t * Removing from the context ends up with disabled\n\t\t * event. What we want here is event in the initial\n\t\t * startup state, ready to be add into new context.\n\t\t */\n\t\tperf_event__state_init(group_leader);\n\t\tperf_install_in_context(ctx, group_leader, group_leader->cpu);\n\t\tget_ctx(ctx);\n\n\t\t/*\n\t\t * Now that all events are installed in @ctx, nothing\n\t\t * references @gctx anymore, so drop the last reference we have\n\t\t * on it.\n\t\t */\n\t\tput_ctx(gctx);\n\t}\n\n\t/*\n\t * Precalculate sample_data sizes; do while holding ctx::mutex such\n\t * that we're serialized against further additions and before\n\t * perf_install_in_context() which is the point the event is active and\n\t * can use these values.\n\t */\n\tperf_event__header_size(event);\n\tperf_event__id_header_size(event);\n\n\tevent->owner = current;\n\n\tperf_install_in_context(ctx, event, event->cpu);\n\tperf_unpin_context(ctx);\n\n\tif (move_group)\n\t\tmutex_unlock(&gctx->mutex);\n\tmutex_unlock(&ctx->mutex);\n\n\tput_online_cpus();\n\n\tmutex_lock(¤t->perf_event_mutex);\n\tlist_add_tail(&event->owner_entry, ¤t->perf_event_list);\n\tmutex_unlock(¤t->perf_event_mutex);\n\n\t/*\n\t * Drop the reference on the group_event after placing the\n\t * new event on the sibling_list. This ensures destruction\n\t * of the group leader will find the pointer to itself in\n\t * perf_group_detach().\n\t */\n\tfdput(group);\n\tfd_install(event_fd, event_file);\n\treturn event_fd;\n\nerr_locked:\n\tif (move_group)\n\t\tmutex_unlock(&gctx->mutex);\n\tmutex_unlock(&ctx->mutex);\n/* err_file: */\n\tfput(event_file);\nerr_context:\n\tperf_unpin_context(ctx);\n\tput_ctx(ctx);\nerr_alloc:\n\t/*\n\t * If event_file is set, the fput() above will have called ->release()\n\t * and that will take care of freeing the event.\n\t */\n\tif (!event_file)\n\t\tfree_event(event);\nerr_cpus:\n\tput_online_cpus();\nerr_task:\n\tif (task)\n\t\tput_task_struct(task);\nerr_group_fd:\n\tfdput(group);\nerr_fd:\n\tput_unused_fd(event_fd);\n\treturn err;\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: PHP_FUNCTION(exif_read_data)\n{\n\tchar *p_name, *p_sections_needed = NULL;\n\tsize_t p_name_len, p_sections_needed_len = 0;\n\tzend_bool sub_arrays=0, read_thumbnail=0, read_all=0;\n\n\tint i, ret, sections_needed=0;\n\timage_info_type ImageInfo;\n\tchar tmp[64], *sections_str, *s;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS(), \"p|sbb\", &p_name, &p_name_len, &p_sections_needed, &p_sections_needed_len, &sub_arrays, &read_thumbnail) == FAILURE) {\n\t\treturn;\n\t}\n\n\tmemset(&ImageInfo, 0, sizeof(ImageInfo));\n\n\tif (p_sections_needed) {\n\t\tspprintf(§ions_str, 0, \",%s,\", p_sections_needed);\n\t\t/* sections_str DOES start with , and SPACES are NOT allowed in names */\n\t\ts = sections_str;\n\t\twhile (*++s) {\n\t\t\tif (*s == ' ') {\n\t\t\t\t*s = ',';\n\t\t\t}\n\t\t}\n\n\t\tfor (i = 0; i < SECTION_COUNT; i++) {\n\t\t\tsnprintf(tmp, sizeof(tmp), \",%s,\", exif_get_sectionname(i));\n\t\t\tif (strstr(sections_str, tmp)) {\n\t\t\t\tsections_needed |= 1<0 && ImageInfo.Height>0) {\n\t\texif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, \"html\" , \"width=\\\"%d\\\" height=\\\"%d\\\"\", ImageInfo.Width, ImageInfo.Height);\n\t\texif_iif_add_int(&ImageInfo, SECTION_COMPUTED, \"Height\", ImageInfo.Height);\n\t\texif_iif_add_int(&ImageInfo, SECTION_COMPUTED, \"Width\", ImageInfo.Width);\n\t}\n\texif_iif_add_int(&ImageInfo, SECTION_COMPUTED, \"IsColor\", ImageInfo.IsColor);\n\tif (ImageInfo.motorola_intel != -1) {\n\t\texif_iif_add_int(&ImageInfo, SECTION_COMPUTED, \"ByteOrderMotorola\", ImageInfo.motorola_intel);\n\t}\n\tif (ImageInfo.FocalLength) {\n\t\texif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, \"FocalLength\", \"%4.1Fmm\", ImageInfo.FocalLength);\n\t\tif(ImageInfo.CCDWidth) {\n\t\t\texif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, \"35mmFocalLength\", \"%dmm\", (int)(ImageInfo.FocalLength/ImageInfo.CCDWidth*35+0.5));\n\t\t}\n\t}\n\tif(ImageInfo.CCDWidth) {\n\t\texif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, \"CCDWidth\", \"%dmm\", (int)ImageInfo.CCDWidth);\n\t}\n\tif(ImageInfo.ExposureTime>0) {\n\t\tif(ImageInfo.ExposureTime <= 0.5) {\n\t\t\texif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, \"ExposureTime\", \"%0.3F s (1/%d)\", ImageInfo.ExposureTime, (int)(0.5 + 1/ImageInfo.ExposureTime));\n\t\t} else {\n\t\t\texif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, \"ExposureTime\", \"%0.3F s\", ImageInfo.ExposureTime);\n\t\t}\n\t}\n\tif(ImageInfo.ApertureFNumber) {\n\t\texif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, \"ApertureFNumber\", \"f/%.1F\", ImageInfo.ApertureFNumber);\n\t}\n\tif(ImageInfo.Distance) {\n\t\tif(ImageInfo.Distance<0) {\n\t\t\texif_iif_add_str(&ImageInfo, SECTION_COMPUTED, \"FocusDistance\", \"Infinite\");\n\t\t} else {\n\t\t\texif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, \"FocusDistance\", \"%0.2Fm\", ImageInfo.Distance);\n\t\t}\n\t}\n\tif (ImageInfo.UserComment) {\n\t\texif_iif_add_buffer(&ImageInfo, SECTION_COMPUTED, \"UserComment\", ImageInfo.UserCommentLength, ImageInfo.UserComment);\n\t\tif (ImageInfo.UserCommentEncoding && strlen(ImageInfo.UserCommentEncoding)) {\n\t\t\texif_iif_add_str(&ImageInfo, SECTION_COMPUTED, \"UserCommentEncoding\", ImageInfo.UserCommentEncoding);\n\t\t}\n\t}\n\n\texif_iif_add_str(&ImageInfo, SECTION_COMPUTED, \"Copyright\", ImageInfo.Copyright);\n\texif_iif_add_str(&ImageInfo, SECTION_COMPUTED, \"Copyright.Photographer\", ImageInfo.CopyrightPhotographer);\n\texif_iif_add_str(&ImageInfo, SECTION_COMPUTED, \"Copyright.Editor\", ImageInfo.CopyrightEditor);\n\n\tfor (i=0; i \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed bug #77831 - Heap-buffer-overflow in exif_iif_add_value in EXIF'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int format8BIM(Image *ifile, Image *ofile)\n{\n char\n temp[MaxTextExtent];\n\n unsigned int\n foundOSType;\n\n int\n ID,\n resCount,\n i,\n c;\n\n ssize_t\n count;\n\n unsigned char\n *PString,\n *str;\n\n resCount=0;\n foundOSType=0; /* found the OSType */\n (void) foundOSType;\n c=ReadBlobByte(ifile);\n while (c != EOF)\n {\n if (c == '8')\n {\n unsigned char\n buffer[5];\n\n buffer[0]=(unsigned char) c;\n for (i=1; i<4; i++)\n {\n c=ReadBlobByte(ifile);\n if (c == EOF)\n return(-1);\n buffer[i] = (unsigned char) c;\n }\n buffer[4]=0;\n if (strcmp((const char *)buffer, \"8BIM\") == 0)\n foundOSType=1;\n else\n continue;\n }\n else\n {\n c=ReadBlobByte(ifile);\n continue;\n }\n /*\n We found the OSType (8BIM) and now grab the ID, PString, and Size fields.\n */\n ID=ReadBlobMSBSignedShort(ifile);\n if (ID < 0)\n return(-1);\n {\n unsigned char\n plen;\n\n c=ReadBlobByte(ifile);\n if (c == EOF)\n return(-1);\n plen = (unsigned char) c;\n PString=(unsigned char *) AcquireQuantumMemory((size_t) (plen+\n MaxTextExtent),sizeof(*PString));\n if (PString == (unsigned char *) NULL)\n return 0;\n for (i=0; i GetBlobSize(ifile)))\n {\n PString=(unsigned char *) RelinquishMagickMemory(PString);\n return(-1);\n }\n /* make a buffer to hold the data and snag it from the input stream */\n str=(unsigned char *) AcquireQuantumMemory((size_t) count,sizeof(*str));\n if (str == (unsigned char *) NULL)\n {\n PString=(unsigned char *) RelinquishMagickMemory(PString);\n return 0;\n }\n for (i=0; i < (ssize_t) count; i++)\n {\n c=ReadBlobByte(ifile);\n if (c == EOF)\n {\n str=(unsigned char *) RelinquishMagickMemory(str);\n PString=(unsigned char *) RelinquishMagickMemory(PString);\n return(-1);\n }\n str[i]=(unsigned char) c;\n }\n\n /* we currently skip thumbnails, since it does not make\n * any sense preserving them in a real world application\n */\n if (ID != THUMBNAIL_ID)\n {\n /* now finish up by formatting this binary data into\n * ASCII equivalent\n */\n if (strlen((const char *)PString) > 0)\n (void) FormatLocaleString(temp,MaxTextExtent,\"8BIM#%d#%s=\",ID,\n PString);\n else\n (void) FormatLocaleString(temp,MaxTextExtent,\"8BIM#%d=\",ID);\n (void) WriteBlobString(ofile,temp);\n if (ID == IPTC_ID)\n {\n formatString(ofile, \"IPTC\", 4);\n formatIPTCfromBuffer(ofile, (char *)str, (ssize_t) count);\n }\n else\n formatString(ofile, (char *)str, (ssize_t) count);\n }\n str=(unsigned char *) RelinquishMagickMemory(str);\n PString=(unsigned char *) RelinquishMagickMemory(PString);\n resCount++;\n c=ReadBlobByte(ifile);\n }\n return resCount;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-193'], 'message': '...'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void uverbs_user_mmap_disassociate(struct ib_uverbs_file *ufile)\n{\n\tstruct rdma_umap_priv *priv, *next_priv;\n\n\tlockdep_assert_held(&ufile->hw_destroy_rwsem);\n\n\twhile (1) {\n\t\tstruct mm_struct *mm = NULL;\n\n\t\t/* Get an arbitrary mm pointer that hasn't been cleaned yet */\n\t\tmutex_lock(&ufile->umap_lock);\n\t\twhile (!list_empty(&ufile->umaps)) {\n\t\t\tint ret;\n\n\t\t\tpriv = list_first_entry(&ufile->umaps,\n\t\t\t\t\t\tstruct rdma_umap_priv, list);\n\t\t\tmm = priv->vma->vm_mm;\n\t\t\tret = mmget_not_zero(mm);\n\t\t\tif (!ret) {\n\t\t\t\tlist_del_init(&priv->list);\n\t\t\t\tmm = NULL;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tmutex_unlock(&ufile->umap_lock);\n\t\tif (!mm)\n\t\t\treturn;\n\n\t\t/*\n\t\t * The umap_lock is nested under mmap_sem since it used within\n\t\t * the vma_ops callbacks, so we have to clean the list one mm\n\t\t * at a time to get the lock ordering right. Typically there\n\t\t * will only be one mm, so no big deal.\n\t\t */\n\t\tdown_write(&mm->mmap_sem);\n\t\tmutex_lock(&ufile->umap_lock);\n\t\tlist_for_each_entry_safe (priv, next_priv, &ufile->umaps,\n\t\t\t\t\t list) {\n\t\t\tstruct vm_area_struct *vma = priv->vma;\n\n\t\t\tif (vma->vm_mm != mm)\n\t\t\t\tcontinue;\n\t\t\tlist_del_init(&priv->list);\n\n\t\t\tzap_vma_ptes(vma, vma->vm_start,\n\t\t\t\t vma->vm_end - vma->vm_start);\n\t\t\tvma->vm_flags &= ~(VM_SHARED | VM_MAYSHARE);\n\t\t}\n\t\tmutex_unlock(&ufile->umap_lock);\n\t\tup_write(&mm->mmap_sem);\n\t\tmmput(mm);\n\t}\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 struct sk_buff *udp_gro_receive_segment(struct list_head *head,\n\t\t\t\t\t struct sk_buff *skb)\n{\n\tstruct udphdr *uh = udp_hdr(skb);\n\tstruct sk_buff *pp = NULL;\n\tstruct udphdr *uh2;\n\tstruct sk_buff *p;\n\n\t/* requires non zero csum, for symmetry with GSO */\n\tif (!uh->check) {\n\t\tNAPI_GRO_CB(skb)->flush = 1;\n\t\treturn NULL;\n\t}\n\n\t/* pull encapsulating udp header */\n\tskb_gro_pull(skb, sizeof(struct udphdr));\n\tskb_gro_postpull_rcsum(skb, uh, sizeof(struct udphdr));\n\n\tlist_for_each_entry(p, head, list) {\n\t\tif (!NAPI_GRO_CB(p)->same_flow)\n\t\t\tcontinue;\n\n\t\tuh2 = udp_hdr(p);\n\n\t\t/* Match ports only, as csum is always non zero */\n\t\tif ((*(u32 *)&uh->source != *(u32 *)&uh2->source)) {\n\t\t\tNAPI_GRO_CB(p)->same_flow = 0;\n\t\t\tcontinue;\n\t\t}\n\n\t\t/* Terminate the flow on len mismatch or if it grow \"too much\".\n\t\t * Under small packet flood GRO count could elsewhere grow a lot\n\t\t * leading to execessive truesize values.\n\t\t * On len mismatch merge the first packet shorter than gso_size,\n\t\t * otherwise complete the GRO packet.\n\t\t */\n\t\tif (uh->len > uh2->len || skb_gro_receive(p, skb) ||\n\t\t uh->len != uh2->len ||\n\t\t NAPI_GRO_CB(p)->count >= UDP_GRO_CNT_MAX)\n\t\t\tpp = p;\n\n\t\treturn pp;\n\t}\n\n\t/* mismatch, but we never need to flush */\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'udp: fix GRO packet of death\n\nsyzbot was able to crash host by sending UDP packets with a 0 payload.\n\nTCP does not have this issue since we do not aggregate packets without\npayload.\n\nSince dev_gro_receive() sets gso_size based on skb_gro_len(skb)\nit seems not worth trying to cope with padded packets.\n\nBUG: KASAN: slab-out-of-bounds in skb_gro_receive+0xf5f/0x10e0 net/core/skbuff.c:3826\nRead of size 16 at addr ffff88808893fff0 by task syz-executor612/7889\n\nCPU: 0 PID: 7889 Comm: syz-executor612 Not tainted 5.1.0-rc7+ #96\nHardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 01/01/2011\nCall Trace:\n __dump_stack lib/dump_stack.c:77 [inline]\n dump_stack+0x172/0x1f0 lib/dump_stack.c:113\n print_address_description.cold+0x7c/0x20d mm/kasan/report.c:187\n kasan_report.cold+0x1b/0x40 mm/kasan/report.c:317\n __asan_report_load16_noabort+0x14/0x20 mm/kasan/generic_report.c:133\n skb_gro_receive+0xf5f/0x10e0 net/core/skbuff.c:3826\n udp_gro_receive_segment net/ipv4/udp_offload.c:382 [inline]\n call_gro_receive include/linux/netdevice.h:2349 [inline]\n udp_gro_receive+0xb61/0xfd0 net/ipv4/udp_offload.c:414\n udp4_gro_receive+0x763/0xeb0 net/ipv4/udp_offload.c:478\n inet_gro_receive+0xe72/0x1110 net/ipv4/af_inet.c:1510\n dev_gro_receive+0x1cd0/0x23c0 net/core/dev.c:5581\n napi_gro_frags+0x36b/0xd10 net/core/dev.c:5843\n tun_get_user+0x2f24/0x3fb0 drivers/net/tun.c:1981\n tun_chr_write_iter+0xbd/0x156 drivers/net/tun.c:2027\n call_write_iter include/linux/fs.h:1866 [inline]\n do_iter_readv_writev+0x5e1/0x8e0 fs/read_write.c:681\n do_iter_write fs/read_write.c:957 [inline]\n do_iter_write+0x184/0x610 fs/read_write.c:938\n vfs_writev+0x1b3/0x2f0 fs/read_write.c:1002\n do_writev+0x15e/0x370 fs/read_write.c:1037\n __do_sys_writev fs/read_write.c:1110 [inline]\n __se_sys_writev fs/read_write.c:1107 [inline]\n __x64_sys_writev+0x75/0xb0 fs/read_write.c:1107\n do_syscall_64+0x103/0x610 arch/x86/entry/common.c:290\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\nRIP: 0033:0x441cc0\nCode: 05 48 3d 01 f0 ff ff 0f 83 9d 09 fc ff c3 66 2e 0f 1f 84 00 00 00 00 00 66 90 83 3d 51 93 29 00 00 75 14 b8 14 00 00 00 0f 05 <48> 3d 01 f0 ff ff 0f 83 74 09 fc ff c3 48 83 ec 08 e8 ba 2b 00 00\nRSP: 002b:00007ffe8c716118 EFLAGS: 00000246 ORIG_RAX: 0000000000000014\nRAX: ffffffffffffffda RBX: 00007ffe8c716150 RCX: 0000000000441cc0\nRDX: 0000000000000001 RSI: 00007ffe8c716170 RDI: 00000000000000f0\nRBP: 0000000000000000 R08: 000000000000ffff R09: 0000000000a64668\nR10: 0000000020000040 R11: 0000000000000246 R12: 000000000000c2d9\nR13: 0000000000402b50 R14: 0000000000000000 R15: 0000000000000000\n\nAllocated by task 5143:\n save_stack+0x45/0xd0 mm/kasan/common.c:75\n set_track mm/kasan/common.c:87 [inline]\n __kasan_kmalloc mm/kasan/common.c:497 [inline]\n __kasan_kmalloc.constprop.0+0xcf/0xe0 mm/kasan/common.c:470\n kasan_slab_alloc+0xf/0x20 mm/kasan/common.c:505\n slab_post_alloc_hook mm/slab.h:437 [inline]\n slab_alloc mm/slab.c:3393 [inline]\n kmem_cache_alloc+0x11a/0x6f0 mm/slab.c:3555\n mm_alloc+0x1d/0xd0 kernel/fork.c:1030\n bprm_mm_init fs/exec.c:363 [inline]\n __do_execve_file.isra.0+0xaa3/0x23f0 fs/exec.c:1791\n do_execveat_common fs/exec.c:1865 [inline]\n do_execve fs/exec.c:1882 [inline]\n __do_sys_execve fs/exec.c:1958 [inline]\n __se_sys_execve fs/exec.c:1953 [inline]\n __x64_sys_execve+0x8f/0xc0 fs/exec.c:1953\n do_syscall_64+0x103/0x610 arch/x86/entry/common.c:290\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\n\nFreed by task 5351:\n save_stack+0x45/0xd0 mm/kasan/common.c:75\n set_track mm/kasan/common.c:87 [inline]\n __kasan_slab_free+0x102/0x150 mm/kasan/common.c:459\n kasan_slab_free+0xe/0x10 mm/kasan/common.c:467\n __cache_free mm/slab.c:3499 [inline]\n kmem_cache_free+0x86/0x260 mm/slab.c:3765\n __mmdrop+0x238/0x320 kernel/fork.c:677\n mmdrop include/linux/sched/mm.h:49 [inline]\n finish_task_switch+0x47b/0x780 kernel/sched/core.c:2746\n context_switch kernel/sched/core.c:2880 [inline]\n __schedule+0x81b/0x1cc0 kernel/sched/core.c:3518\n preempt_schedule_irq+0xb5/0x140 kernel/sched/core.c:3745\n retint_kernel+0x1b/0x2d\n arch_local_irq_restore arch/x86/include/asm/paravirt.h:767 [inline]\n kmem_cache_free+0xab/0x260 mm/slab.c:3766\n anon_vma_chain_free mm/rmap.c:134 [inline]\n unlink_anon_vmas+0x2ba/0x870 mm/rmap.c:401\n free_pgtables+0x1af/0x2f0 mm/memory.c:394\n exit_mmap+0x2d1/0x530 mm/mmap.c:3144\n __mmput kernel/fork.c:1046 [inline]\n mmput+0x15f/0x4c0 kernel/fork.c:1067\n exec_mmap fs/exec.c:1046 [inline]\n flush_old_exec+0x8d9/0x1c20 fs/exec.c:1279\n load_elf_binary+0x9bc/0x53f0 fs/binfmt_elf.c:864\n search_binary_handler fs/exec.c:1656 [inline]\n search_binary_handler+0x17f/0x570 fs/exec.c:1634\n exec_binprm fs/exec.c:1698 [inline]\n __do_execve_file.isra.0+0x1394/0x23f0 fs/exec.c:1818\n do_execveat_common fs/exec.c:1865 [inline]\n do_execve fs/exec.c:1882 [inline]\n __do_sys_execve fs/exec.c:1958 [inline]\n __se_sys_execve fs/exec.c:1953 [inline]\n __x64_sys_execve+0x8f/0xc0 fs/exec.c:1953\n do_syscall_64+0x103/0x610 arch/x86/entry/common.c:290\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\n\nThe buggy address belongs to the object at ffff88808893f7c0\n which belongs to the cache mm_struct of size 1496\nThe buggy address is located 600 bytes to the right of\n 1496-byte region [ffff88808893f7c0, ffff88808893fd98)\nThe buggy address belongs to the page:\npage:ffffea0002224f80 count:1 mapcount:0 mapping:ffff88821bc40ac0 index:0xffff88808893f7c0 compound_mapcount: 0\nflags: 0x1fffc0000010200(slab|head)\nraw: 01fffc0000010200 ffffea00025b4f08 ffffea00027b9d08 ffff88821bc40ac0\nraw: ffff88808893f7c0 ffff88808893e440 0000000100000001 0000000000000000\npage dumped because: kasan: bad access detected\n\nMemory state around the buggy address:\n ffff88808893fe80: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc\n ffff88808893ff00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc\n>ffff88808893ff80: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc\n ^\n ffff888088940000: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n ffff888088940080: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n\nFixes: e20cf8d3f1f7 (\"udp: implement GRO for plain UDP sockets.\")\nSigned-off-by: Eric Dumazet \nCc: Paolo Abeni \nReported-by: syzbot \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int format8BIM(Image *ifile, Image *ofile)\n{\n char\n temp[MaxTextExtent];\n\n unsigned int\n foundOSType;\n\n int\n ID,\n resCount,\n i,\n c;\n\n ssize_t\n count;\n\n unsigned char\n *PString,\n *str;\n\n resCount=0;\n foundOSType=0; /* found the OSType */\n (void) foundOSType;\n c=ReadBlobByte(ifile);\n while (c != EOF)\n {\n if (c == '8')\n {\n unsigned char\n buffer[5];\n\n buffer[0]=(unsigned char) c;\n for (i=1; i<4; i++)\n {\n c=ReadBlobByte(ifile);\n if (c == EOF)\n return(-1);\n buffer[i] = (unsigned char) c;\n }\n buffer[4]=0;\n if (strcmp((const char *)buffer, \"8BIM\") == 0)\n foundOSType=1;\n else\n continue;\n }\n else\n {\n c=ReadBlobByte(ifile);\n continue;\n }\n /*\n We found the OSType (8BIM) and now grab the ID, PString, and Size fields.\n */\n ID=ReadBlobMSBSignedShort(ifile);\n if (ID < 0)\n return(-1);\n {\n unsigned char\n plen;\n\n c=ReadBlobByte(ifile);\n if (c == EOF)\n return(-1);\n plen = (unsigned char) c;\n PString=(unsigned char *) AcquireQuantumMemory((size_t) (plen+\n MaxTextExtent),sizeof(*PString));\n if (PString == (unsigned char *) NULL)\n {\n printf(\"MemoryAllocationFailed\");\n return 0;\n }\n for (i=0; i 0)\n (void) FormatLocaleString(temp,MaxTextExtent,\"8BIM#%d#%s=\",ID,\n PString);\n else\n (void) FormatLocaleString(temp,MaxTextExtent,\"8BIM#%d=\",ID);\n (void) WriteBlobString(ofile,temp);\n if (ID == IPTC_ID)\n {\n formatString(ofile, \"IPTC\", 4);\n formatIPTCfromBuffer(ofile, (char *)str, (ssize_t) count);\n }\n else\n formatString(ofile, (char *)str, (ssize_t) count);\n }\n str=(unsigned char *) RelinquishMagickMemory(str);\n PString=(unsigned char *) RelinquishMagickMemory(PString);\n resCount++;\n c=ReadBlobByte(ifile);\n }\n return resCount;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/660'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ipmi_si_mem_setup(struct si_sm_io *io)\n{\n\tunsigned long addr = io->addr_data;\n\tint mapsize, idx;\n\n\tif (!addr)\n\t\treturn -ENODEV;\n\n\tio->io_cleanup = mem_cleanup;\n\n\t/*\n\t * Figure out the actual readb/readw/readl/etc routine to use based\n\t * upon the register size.\n\t */\n\tswitch (io->regsize) {\n\tcase 1:\n\t\tio->inputb = intf_mem_inb;\n\t\tio->outputb = intf_mem_outb;\n\t\tbreak;\n\tcase 2:\n\t\tio->inputb = intf_mem_inw;\n\t\tio->outputb = intf_mem_outw;\n\t\tbreak;\n\tcase 4:\n\t\tio->inputb = intf_mem_inl;\n\t\tio->outputb = intf_mem_outl;\n\t\tbreak;\n#ifdef readq\n\tcase 8:\n\t\tio->inputb = mem_inq;\n\t\tio->outputb = mem_outq;\n\t\tbreak;\n#endif\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 memory regions in their ACPI\n\t * tables. This causes problems when trying to request the\n\t * entire region. Therefore we must request each register\n\t * separately.\n\t */\n\tfor (idx = 0; idx < io->io_size; idx++) {\n\t\tif (request_mem_region(addr + idx * io->regspacing,\n\t\t\t\t io->regsize, DEVICE_NAME) == NULL) {\n\t\t\t/* Undo allocations */\n\t\t\tmem_region_cleanup(io, idx);\n\t\t\treturn -EIO;\n\t\t}\n\t}\n\n\t/*\n\t * Calculate the total amount of memory to claim. This is an\n\t * unusual looking calculation, but it avoids claiming any\n\t * more memory than it has to. It will claim everything\n\t * between the first address to the end of the last full\n\t * register.\n\t */\n\tmapsize = ((io->io_size * io->regspacing)\n\t\t - (io->regspacing - io->regsize));\n\tio->addr = ioremap(addr, mapsize);\n\tif (io->addr == NULL) {\n\t\tmem_region_cleanup(io, io->io_size);\n\t\treturn -EIO;\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: krb5_init_creds_step(krb5_context context,\n\t\t krb5_init_creds_context ctx,\n\t\t krb5_data *in,\n\t\t krb5_data *out,\n\t\t krb5_krbhst_info *hostinfo,\n\t\t unsigned int *flags)\n{\n krb5_error_code ret;\n size_t len = 0;\n size_t size;\n AS_REQ req2;\n\n krb5_data_zero(out);\n\n if (ctx->as_req.req_body.cname == NULL) {\n\tret = init_as_req(context, ctx->flags, &ctx->cred,\n\t\t\t ctx->addrs, ctx->etypes, &ctx->as_req);\n\tif (ret) {\n\t free_init_creds_ctx(context, ctx);\n\t return ret;\n\t}\n }\n\n#define MAX_PA_COUNTER 10\n if (ctx->pa_counter > MAX_PA_COUNTER) {\n\tkrb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP,\n\t\t\t N_(\"Looping %d times while getting \"\n\t\t\t\t \"initial credentials\", \"\"),\n\t\t\t ctx->pa_counter);\n\treturn KRB5_GET_IN_TKT_LOOP;\n }\n ctx->pa_counter++;\n\n _krb5_debug(context, 5, \"krb5_get_init_creds: loop %d\", ctx->pa_counter);\n\n /* Lets process the input packet */\n if (in && in->length) {\n\tkrb5_kdc_rep rep;\n\n\tmemset(&rep, 0, sizeof(rep));\n\n\t_krb5_debug(context, 5, \"krb5_get_init_creds: processing input\");\n\n\tret = decode_AS_REP(in->data, in->length, &rep.kdc_rep, &size);\n\tif (ret == 0) {\n\t unsigned eflags = EXTRACT_TICKET_AS_REQ | EXTRACT_TICKET_TIMESYNC;\n\t krb5_data data;\n\n\t /*\n\t * Unwrap AS-REP\n\t */\n\t ASN1_MALLOC_ENCODE(Ticket, data.data, data.length,\n\t\t\t &rep.kdc_rep.ticket, &size, ret);\n\t if (ret)\n\t\tgoto out;\n\t heim_assert(data.length == size, \"ASN.1 internal error\");\n\n\t ret = fast_unwrap_as_rep(context, ctx->nonce, &data,\n\t\t\t\t &ctx->fast_state, &rep.kdc_rep);\n\t krb5_data_free(&data);\n\t if (ret)\n\t\tgoto out;\n\n\t /*\n\t * Now check and extract the ticket\n\t */\n\n\t if (ctx->flags.canonicalize) {\n\t\teflags |= EXTRACT_TICKET_ALLOW_SERVER_MISMATCH;\n\t\teflags |= EXTRACT_TICKET_MATCH_REALM;\n\t }\n\t if (ctx->ic_flags & KRB5_INIT_CREDS_NO_C_CANON_CHECK)\n\t\teflags |= EXTRACT_TICKET_ALLOW_CNAME_MISMATCH;\n\n\t ret = process_pa_data_to_key(context, ctx, &ctx->cred,\n\t\t\t\t\t &ctx->as_req, &rep.kdc_rep,\n\t\t\t\t\t hostinfo, &ctx->fast_state.reply_key);\n\t if (ret) {\n\t\tfree_AS_REP(&rep.kdc_rep);\n\t\tgoto out;\n\t }\n\n\t _krb5_debug(context, 5, \"krb5_get_init_creds: extracting ticket\");\n\n\t ret = _krb5_extract_ticket(context,\n\t\t\t\t &rep,\n\t\t\t\t &ctx->cred,\n\t\t\t\t ctx->fast_state.reply_key,\n\t\t\t\t NULL,\n\t\t\t\t KRB5_KU_AS_REP_ENC_PART,\n\t\t\t\t NULL,\n\t\t\t\t ctx->nonce,\n\t\t\t\t eflags,\n\t\t\t\t &ctx->req_buffer,\n\t\t\t\t NULL,\n\t\t\t\t NULL);\n\t if (ret == 0)\n\t\tret = copy_EncKDCRepPart(&rep.enc_part, &ctx->enc_part);\n\n\t krb5_free_keyblock(context, ctx->fast_state.reply_key);\n\t ctx->fast_state.reply_key = NULL;\n\t *flags = 0;\n\n\t free_AS_REP(&rep.kdc_rep);\n\t free_EncASRepPart(&rep.enc_part);\n\n\t return ret;\n\n\t} else {\n\t /* let's try to parse it as a KRB-ERROR */\n\n\t _krb5_debug(context, 5, \"krb5_get_init_creds: got an error\");\n\n\t free_KRB_ERROR(&ctx->error);\n\n\t ret = krb5_rd_error(context, in, &ctx->error);\n\t if(ret && in->length && ((char*)in->data)[0] == 4)\n\t\tret = KRB5KRB_AP_ERR_V4_REPLY;\n\t if (ret) {\n\t\t_krb5_debug(context, 5, \"krb5_get_init_creds: failed to read error\");\n\t\tgoto out;\n\t }\n\n\t /*\n\t * Unwrap KRB-ERROR\n\t */\n\t ret = fast_unwrap_error(context, &ctx->fast_state, &ctx->error);\n\t if (ret)\n\t\tgoto out;\n\n\t /*\n\t *\n\t */\n\n\t ret = krb5_error_from_rd_error(context, &ctx->error, &ctx->cred);\n\n\t _krb5_debug(context, 5, \"krb5_get_init_creds: KRB-ERROR %d\", ret);\n\n\t /*\n\t * If no preauth was set and KDC requires it, give it one\n\t * more try.\n\t */\n\n\t if (ret == KRB5KDC_ERR_PREAUTH_REQUIRED) {\n\n\t free_METHOD_DATA(&ctx->md);\n\t memset(&ctx->md, 0, sizeof(ctx->md));\n\n\t\tif (ctx->error.e_data) {\n\t\t ret = decode_METHOD_DATA(ctx->error.e_data->data,\n\t\t\t\t\t ctx->error.e_data->length,\n\t\t\t\t\t &ctx->md,\n\t\t\t\t\t NULL);\n\t\t if (ret)\n\t\t\tkrb5_set_error_message(context, ret,\n\t\t\t\t\t N_(\"Failed to decode METHOD-DATA\", \"\"));\n\t\t} else {\n\t\t krb5_set_error_message(context, ret,\n\t\t\t\t\t N_(\"Preauth required but no preauth \"\n\t\t\t\t\t \"options send by KDC\", \"\"));\n\t\t}\n\t } else if (ret == KRB5KRB_AP_ERR_SKEW && context->kdc_sec_offset == 0) {\n\t\t/*\n\t\t * Try adapt to timeskrew when we are using pre-auth, and\n\t\t * if there was a time skew, try again.\n\t\t */\n\t\tkrb5_set_real_time(context, ctx->error.stime, -1);\n\t\tif (context->kdc_sec_offset)\n\t\t ret = 0;\n\n\t\t_krb5_debug(context, 10, \"init_creds: err skew updateing kdc offset to %d\",\n\t\t\t context->kdc_sec_offset);\n\n\t\tctx->used_pa_types = 0;\n\n\t } else if (ret == KRB5_KDC_ERR_WRONG_REALM && ctx->flags.canonicalize) {\n\t /* client referal to a new realm */\n\n\t\tif (ctx->error.crealm == NULL) {\n\t\t krb5_set_error_message(context, ret,\n\t\t\t\t\t N_(\"Got a client referral, not but no realm\", \"\"));\n\t\t goto out;\n\t\t}\n\t\t_krb5_debug(context, 5,\n\t\t\t \"krb5_get_init_creds: got referal to realm %s\",\n\t\t\t *ctx->error.crealm);\n\n\t\tret = krb5_principal_set_realm(context,\n\t\t\t\t\t ctx->cred.client,\n\t\t\t\t\t *ctx->error.crealm);\n\t\tif (ret)\n\t\t goto out;\n\n\t\tif (krb5_principal_is_krbtgt(context, ctx->cred.server)) {\n\t\t ret = krb5_init_creds_set_service(context, ctx, NULL);\n\t\t if (ret)\n\t\t\tgoto out;\n\t\t}\n\n\t\tfree_AS_REQ(&ctx->as_req);\n\t\tmemset(&ctx->as_req, 0, sizeof(ctx->as_req));\n\n\t\tctx->used_pa_types = 0;\n\t } else if (ret == KRB5KDC_ERR_KEY_EXP && ctx->runflags.change_password == 0 && ctx->prompter) {\n\t\tchar buf2[1024];\n\n\t\tctx->runflags.change_password = 1;\n\n\t\tctx->prompter(context, ctx->prompter_data, NULL, N_(\"Password has expired\", \"\"), 0, NULL);\n\n\n\t\t/* try to avoid recursion */\n\t\tif (ctx->in_tkt_service != NULL && strcmp(ctx->in_tkt_service, \"kadmin/changepw\") == 0)\n\t\t goto out;\n\n /* don't try to change password where then where none */\n if (ctx->prompter == NULL)\n goto out;\n\n\t\tret = change_password(context,\n\t\t\t\t ctx->cred.client,\n\t\t\t\t ctx->password,\n\t\t\t\t buf2,\n\t\t\t\t sizeof(buf2),\n\t\t\t\t ctx->prompter,\n\t\t\t\t ctx->prompter_data,\n\t\t\t\t NULL);\n\t\tif (ret)\n\t\t goto out;\n\n\t\tkrb5_init_creds_set_password(context, ctx, buf2);\n\n \t\tctx->used_pa_types = 0;\n\t\tret = 0;\n\n \t } else if (ret == KRB5KDC_ERR_PREAUTH_FAILED) {\n \n \t\tif (ctx->fast_state.flags & KRB5_FAST_DISABLED)\n \t\t goto out;\n \t\tif (ctx->fast_state.flags & (KRB5_FAST_REQUIRED | KRB5_FAST_EXPECTED))\n \t\t goto out;\n \n \t\t_krb5_debug(context, 10, \"preauth failed with FAST, \"\n\t\t\t \"and told by KD or user, trying w/o FAST\");\n \n \t\tctx->fast_state.flags |= KRB5_FAST_DISABLED;\n \t\tctx->used_pa_types = 0;\n\t\tret = 0;\n\t }\n\t if (ret)\n\t\tgoto out;\n\t}\n }\n\n if (ctx->as_req.req_body.cname == NULL) {\n\tret = init_as_req(context, ctx->flags, &ctx->cred,\n\t\t\t ctx->addrs, ctx->etypes, &ctx->as_req);\n\tif (ret) {\n\t free_init_creds_ctx(context, ctx);\n\t return ret;\n\t}\n }\n\n if (ctx->as_req.padata) {\n\tfree_METHOD_DATA(ctx->as_req.padata);\n\tfree(ctx->as_req.padata);\n\tctx->as_req.padata = NULL;\n }\n\n /* Set a new nonce. */\n ctx->as_req.req_body.nonce = ctx->nonce;\n\n /* fill_in_md_data */\n ret = process_pa_data_to_md(context, &ctx->cred, &ctx->as_req, ctx,\n\t\t\t\t&ctx->md, &ctx->as_req.padata,\n\t\t\t\tctx->prompter, ctx->prompter_data);\n if (ret)\n\tgoto out;\n\n /*\n * Wrap with FAST\n */\n copy_AS_REQ(&ctx->as_req, &req2);\n\n ret = fast_wrap_req(context, &ctx->fast_state, &req2);\n if (ret) {\n\tfree_AS_REQ(&req2);\n\tgoto out;\n }\n\n krb5_data_free(&ctx->req_buffer);\n\n ASN1_MALLOC_ENCODE(AS_REQ,\n\t\t ctx->req_buffer.data, ctx->req_buffer.length,\n\t\t &req2, &len, ret);\n free_AS_REQ(&req2);\n if (ret)\n\tgoto out;\n if(len != ctx->req_buffer.length)\n\tkrb5_abortx(context, \"internal error in ASN.1 encoder\");\n\n out->data = ctx->req_buffer.data;\n out->length = ctx->req_buffer.length;\n\n *flags = KRB5_INIT_CREDS_STEP_FLAG_CONTINUE;\n\n return 0;\n out:\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-320'], 'message': 'CVE-2019-12098: krb5: always confirm PA-PKINIT-KX for anon PKINIT\n\nRFC8062 Section 7 requires verification of the PA-PKINIT-KX key excahnge\nwhen anonymous PKINIT is used. Failure to do so can permit an active\nattacker to become a man-in-the-middle.\n\nIntroduced by a1ef548600c5bb51cf52a9a9ea12676506ede19f. First tagged\nrelease Heimdal 1.4.0.\n\nCVSS:3.0/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:L/A:N (4.8)\n\nChange-Id: I6cc1c0c24985936468af08693839ac6c3edda133\nSigned-off-by: Jeffrey Altman \nApproved-by: Jeffrey Altman \n(cherry picked from commit 38c797e1ae9b9c8f99ae4aa2e73957679031fd2b)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: exsltSaxonLineNumberFunction(xmlXPathParserContextPtr ctxt, int nargs) {\n xmlNodePtr cur = NULL;\n\n if (nargs == 0) {\n\tcur = ctxt->context->node;\n } else if (nargs == 1) {\n\txmlXPathObjectPtr obj;\n\txmlNodeSetPtr nodelist;\n\tint i;\n\n\tif ((ctxt->value == NULL) || (ctxt->value->type != XPATH_NODESET)) {\n\t xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL,\n\t\t\"saxon:line-number() : invalid arg expecting a node-set\\n\");\n\t ctxt->error = XPATH_INVALID_TYPE;\n\t return;\n\t}\n\n\tobj = valuePop(ctxt);\n\tnodelist = obj->nodesetval;\n\tif ((nodelist == NULL) || (nodelist->nodeNr <= 0)) {\n\t xmlXPathFreeObject(obj);\n\t valuePush(ctxt, xmlXPathNewFloat(-1));\n\t return;\n\t}\n\tcur = nodelist->nodeTab[0];\n\tfor (i = 1;i < nodelist->nodeNr;i++) {\n\t int ret = xmlXPathCmpNodes(cur, nodelist->nodeTab[i]);\n\t if (ret == -1)\n\t\tcur = nodelist->nodeTab[i];\n\t}\n\txmlXPathFreeObject(obj);\n } else {\n\txsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL,\n\t\t\"saxon:line-number() : invalid number of args %d\\n\",\n\t\tnargs);\n\tctxt->error = XPATH_INVALID_ARITY;\n\treturn;\n }\n\n valuePush(ctxt, xmlXPathNewFloat(xmlGetLineNo(cur)));\n return;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix saxon:line-number with namespace nodes\n\nexsltSaxonLineNumberFunction must make sure not to pass namespace\n\"nodes\" to xmlGetLineNo. Otherwise, an OOB heap read results which\ntypically leads to 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: int ip6_ra_control(struct sock *sk, int sel)\n{\n\tstruct ip6_ra_chain *ra, *new_ra, **rap;\n\n\t/* RA packet may be delivered ONLY to IPPROTO_RAW socket */\n\tif (sk->sk_type != SOCK_RAW || inet_sk(sk)->inet_num != IPPROTO_RAW)\n\t\treturn -ENOPROTOOPT;\n\n\tnew_ra = (sel >= 0) ? kmalloc(sizeof(*new_ra), GFP_KERNEL) : NULL;\n\n\twrite_lock_bh(&ip6_ra_lock);\n\tfor (rap = &ip6_ra_chain; (ra = *rap) != NULL; rap = &ra->next) {\n\t\tif (ra->sk == sk) {\n\t\t\tif (sel >= 0) {\n\t\t\t\twrite_unlock_bh(&ip6_ra_lock);\n\t\t\t\tkfree(new_ra);\n\t\t\t\treturn -EADDRINUSE;\n\t\t\t}\n\n\t\t\t*rap = ra->next;\n\t\t\twrite_unlock_bh(&ip6_ra_lock);\n\n\t\t\tsock_put(sk);\n\t\t\tkfree(ra);\n\t\t\treturn 0;\n\t\t}\n\t}\n\tif (!new_ra) {\n\t\twrite_unlock_bh(&ip6_ra_lock);\n\t\treturn -ENOBUFS;\n\t}\n\tnew_ra->sk = sk;\n\tnew_ra->sel = sel;\n\tnew_ra->next = ra;\n\t*rap = new_ra;\n\tsock_hold(sk);\n\twrite_unlock_bh(&ip6_ra_lock);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'ipv6_sockglue: Fix a missing-check bug in ip6_ra_control()\n\nIn function ip6_ra_control(), the pointer new_ra is allocated a memory\nspace via kmalloc(). And it is used in the following codes. However,\nwhen there is a memory allocation error, kmalloc() fails. Thus null\npointer dereference may happen. And it will cause the kernel to crash.\nTherefore, we should check the return value and handle the error.\n\nSigned-off-by: Gen Zhang \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 tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)\n{\n\tstruct tun_struct *tun;\n\tstruct tun_file *tfile = file->private_data;\n\tstruct net_device *dev;\n\tint err;\n\n\tif (tfile->detached)\n\t\treturn -EINVAL;\n\n\tdev = __dev_get_by_name(net, ifr->ifr_name);\n\tif (dev) {\n\t\tif (ifr->ifr_flags & IFF_TUN_EXCL)\n\t\t\treturn -EBUSY;\n\t\tif ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)\n\t\t\ttun = netdev_priv(dev);\n\t\telse if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)\n\t\t\ttun = netdev_priv(dev);\n\t\telse\n\t\t\treturn -EINVAL;\n\n\t\tif (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=\n\t\t !!(tun->flags & IFF_MULTI_QUEUE))\n\t\t\treturn -EINVAL;\n\n\t\tif (tun_not_capable(tun))\n\t\t\treturn -EPERM;\n\t\terr = security_tun_dev_open(tun->security);\n\t\tif (err < 0)\n\t\t\treturn err;\n\n\t\terr = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER);\n\t\tif (err < 0)\n\t\t\treturn err;\n\n\t\tif (tun->flags & IFF_MULTI_QUEUE &&\n\t\t (tun->numqueues + tun->numdisabled > 1)) {\n\t\t\t/* One or more queue has already been attached, no need\n\t\t\t * to initialize the device again.\n\t\t\t */\n\t\t\treturn 0;\n\t\t}\n\t}\n\telse {\n\t\tchar *name;\n\t\tunsigned long flags = 0;\n\t\tint queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?\n\t\t\t MAX_TAP_QUEUES : 1;\n\n\t\tif (!ns_capable(net->user_ns, CAP_NET_ADMIN))\n\t\t\treturn -EPERM;\n\t\terr = security_tun_dev_create();\n\t\tif (err < 0)\n\t\t\treturn err;\n\n\t\t/* Set dev type */\n\t\tif (ifr->ifr_flags & IFF_TUN) {\n\t\t\t/* TUN device */\n\t\t\tflags |= IFF_TUN;\n\t\t\tname = \"tun%d\";\n\t\t} else if (ifr->ifr_flags & IFF_TAP) {\n\t\t\t/* TAP device */\n\t\t\tflags |= IFF_TAP;\n\t\t\tname = \"tap%d\";\n\t\t} else\n\t\t\treturn -EINVAL;\n\n\t\tif (*ifr->ifr_name)\n\t\t\tname = ifr->ifr_name;\n\n\t\tdev = alloc_netdev_mqs(sizeof(struct tun_struct), name,\n\t\t\t\t NET_NAME_UNKNOWN, tun_setup, queues,\n\t\t\t\t queues);\n\n\t\tif (!dev)\n\t\t\treturn -ENOMEM;\n\t\terr = dev_get_valid_name(net, dev, name);\n\t\tif (err)\n\t\t\tgoto err_free_dev;\n\n\t\tdev_net_set(dev, net);\n\t\tdev->rtnl_link_ops = &tun_link_ops;\n\t\tdev->ifindex = tfile->ifindex;\n\t\tdev->sysfs_groups[0] = &tun_attr_group;\n\n\t\ttun = netdev_priv(dev);\n\t\ttun->dev = dev;\n\t\ttun->flags = flags;\n\t\ttun->txflt.count = 0;\n\t\ttun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);\n\n\t\ttun->align = NET_SKB_PAD;\n\t\ttun->filter_attached = false;\n\t\ttun->sndbuf = tfile->socket.sk->sk_sndbuf;\n\t\ttun->rx_batched = 0;\n\n\t\ttun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats);\n\t\tif (!tun->pcpu_stats) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto err_free_dev;\n\t\t}\n\n\t\tspin_lock_init(&tun->lock);\n\n\t\terr = security_tun_dev_alloc_security(&tun->security);\n\t\tif (err < 0)\n\t\t\tgoto err_free_stat;\n\n\t\ttun_net_init(dev);\n\t\ttun_flow_init(tun);\n\n\t\tdev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |\n\t\t\t\t TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX |\n\t\t\t\t NETIF_F_HW_VLAN_STAG_TX;\n\t\tdev->features = dev->hw_features | NETIF_F_LLTX;\n\t\tdev->vlan_features = dev->features &\n\t\t\t\t ~(NETIF_F_HW_VLAN_CTAG_TX |\n\t\t\t\t NETIF_F_HW_VLAN_STAG_TX);\n\n\t\tINIT_LIST_HEAD(&tun->disabled);\n\t\terr = tun_attach(tun, file, false);\n\t\tif (err < 0)\n\t\t\tgoto err_free_flow;\n\n\t\terr = register_netdevice(tun->dev);\n\t\tif (err < 0)\n\t\t\tgoto err_detach;\n\t}\n\n\tnetif_carrier_on(tun->dev);\n\n\ttun_debug(KERN_INFO, tun, \"tun_set_iff\\n\");\n\n\ttun->flags = (tun->flags & ~TUN_FEATURES) |\n\t\t(ifr->ifr_flags & TUN_FEATURES);\n\n\t/* Make sure persistent devices do not get stuck in\n\t * xoff state.\n\t */\n\tif (netif_running(tun->dev))\n\t\tnetif_tx_wake_all_queues(tun->dev);\n\n\tstrcpy(ifr->ifr_name, tun->dev->name);\n\treturn 0;\n\nerr_detach:\n\ttun_detach_all(dev);\n\t/* register_netdevice() already called tun_free_netdev() */\n\tgoto err_free_dev;\n\nerr_free_flow:\n\ttun_flow_uninit(tun);\n\tsecurity_tun_dev_free_security(tun->security);\nerr_free_stat:\n\tfree_percpu(tun->pcpu_stats);\nerr_free_dev:\n\tfree_netdev(dev);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'tun: allow positive return values on dev_get_valid_name() call\n\nIf the name argument of dev_get_valid_name() contains \"%d\", it will try\nto assign it a unit number in __dev__alloc_name() and return either the\nunit number (>= 0) or an error code (< 0).\nConsidering positive values as error values prevent tun device creations\nrelying this mechanism, therefor we should only consider negative values\nas errors here.\n\nSigned-off-by: Julien Gomes \nAcked-by: Cong Wang \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int get_devices_from_authfile(const char *authfile, const char *username,\n unsigned max_devs, int verbose, FILE *debug_file,\n device_t *devices, unsigned *n_devs) {\n\n char *buf = NULL;\n char *s_user, *s_token;\n int retval = 0;\n int fd = -1;\n struct stat st;\n struct passwd *pw = NULL, pw_s;\n char buffer[BUFSIZE];\n int gpu_ret;\n FILE *opwfile = NULL;\n unsigned i, j;\n\n /* Ensure we never return uninitialized count. */\n *n_devs = 0;\n\n fd = open(authfile, O_RDONLY, 0);\n if (fd < 0) {\n if (verbose)\n D(debug_file, \"Cannot open file: %s (%s)\", authfile, strerror(errno));\n goto err;\n }\n\n if (fstat(fd, &st) < 0) {\n if (verbose)\n D(debug_file, \"Cannot stat file: %s (%s)\", authfile, strerror(errno));\n goto err;\n }\n\n if (!S_ISREG(st.st_mode)) {\n if (verbose)\n D(debug_file, \"%s is not a regular file\", authfile);\n goto err;\n }\n\n if (st.st_size == 0) {\n if (verbose)\n D(debug_file, \"File %s is empty\", authfile);\n goto err;\n }\n\n gpu_ret = getpwuid_r(st.st_uid, &pw_s, buffer, sizeof(buffer), &pw);\n if (gpu_ret != 0 || pw == NULL) {\n D(debug_file, \"Unable to retrieve credentials for uid %u, (%s)\", st.st_uid,\n strerror(errno));\n goto err;\n }\n\n if (strcmp(pw->pw_name, username) != 0 && strcmp(pw->pw_name, \"root\") != 0) {\n if (strcmp(username, \"root\") != 0) {\n D(debug_file, \"The owner of the authentication file is neither %s nor root\",\n username);\n } else {\n D(debug_file, \"The owner of the authentication file is not root\");\n }\n goto err;\n }\n\n opwfile = fdopen(fd, \"r\");\n if (opwfile == NULL) {\n if (verbose)\n D(debug_file, \"fdopen: %s\", strerror(errno));\n goto err;\n }\n\n buf = malloc(sizeof(char) * (DEVSIZE * max_devs));\n if (!buf) {\n if (verbose)\n D(debug_file, \"Unable to allocate memory\");\n goto err;\n }\n\n retval = -2;\n while (fgets(buf, (int)(DEVSIZE * (max_devs - 1)), opwfile)) {\n char *saveptr = NULL;\n if (buf[strlen(buf) - 1] == '\\n')\n buf[strlen(buf) - 1] = '\\0';\n\n if (verbose)\n D(debug_file, \"Authorization line: %s\", buf);\n\n s_user = strtok_r(buf, \":\", &saveptr);\n if (s_user && strcmp(username, s_user) == 0) {\n if (verbose)\n D(debug_file, \"Matched user: %s\", s_user);\n\n retval = -1; // We found at least one line for the user\n\n // only keep last line for this user\n for (i = 0; i < *n_devs; i++) {\n free(devices[i].keyHandle);\n free(devices[i].publicKey);\n devices[i].keyHandle = NULL;\n devices[i].publicKey = NULL;\n }\n *n_devs = 0;\n\n i = 0;\n while ((s_token = strtok_r(NULL, \",\", &saveptr))) {\n devices[i].keyHandle = NULL;\n devices[i].publicKey = NULL;\n\n if ((*n_devs)++ > MAX_DEVS - 1) {\n *n_devs = MAX_DEVS;\n if (verbose)\n D(debug_file, \"Found more than %d devices, ignoring the remaining ones\",\n MAX_DEVS);\n break;\n }\n\n if (verbose)\n D(debug_file, \"KeyHandle for device number %d: %s\", i + 1, s_token);\n\n devices[i].keyHandle = strdup(s_token);\n\n if (!devices[i].keyHandle) {\n if (verbose)\n D(debug_file, \"Unable to allocate memory for keyHandle number %d\", i);\n goto err;\n }\n\n s_token = strtok_r(NULL, \":\", &saveptr);\n\n if (!s_token) {\n if (verbose)\n D(debug_file, \"Unable to retrieve publicKey number %d\", i + 1);\n goto err;\n }\n\n if (verbose)\n D(debug_file, \"publicKey for device number %d: %s\", i + 1, s_token);\n\n if (strlen(s_token) % 2 != 0) {\n if (verbose)\n D(debug_file, \"Length of key number %d not even\", i + 1);\n goto err;\n }\n\n devices[i].key_len = strlen(s_token) / 2;\n\n if (verbose)\n D(debug_file, \"Length of key number %d is %zu\", i + 1, devices[i].key_len);\n\n devices[i].publicKey =\n malloc((sizeof(unsigned char) * devices[i].key_len));\n\n if (!devices[i].publicKey) {\n if (verbose)\n D(debug_file, \"Unable to allocate memory for publicKey number %d\", i);\n goto err;\n }\n\n for (j = 0; j < devices[i].key_len; j++) {\n unsigned int x;\n if (sscanf(&s_token[2 * j], \"%2x\", &x) != 1) {\n if (verbose)\n D(debug_file, \"Invalid hex number in key\");\n goto err;\n }\n devices[i].publicKey[j] = (unsigned char)x;\n }\n\n i++;\n }\n }\n }\n\n if (verbose)\n D(debug_file, \"Found %d device(s) for user %s\", *n_devs, username);\n\n retval = 1;\n goto out;\n\nerr:\n for (i = 0; i < *n_devs; i++) {\n free(devices[i].keyHandle);\n free(devices[i].publicKey);\n devices[i].keyHandle = NULL;\n devices[i].publicKey = NULL;\n }\n\n *n_devs = 0;\n\nout:\n if (buf) {\n free(buf);\n buf = NULL;\n }\n\n if (opwfile)\n fclose(opwfile);\n else if (fd >= 0)\n close(fd);\n return retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Do not leak file descriptor when doing exec\n\nWhen opening a custom debug file, the descriptor would stay\nopen when calling exec and leak to the child process.\n\nMake sure all files are opened with close-on-exec.\n\nThis fixes CVE-2019-12210.\n\nThanks to Matthias Gerstner of the SUSE Security Team for reporting\nthe issue.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static bool tcp_shifted_skb(struct sock *sk, struct sk_buff *prev,\n\t\t\t struct sk_buff *skb,\n\t\t\t struct tcp_sacktag_state *state,\n\t\t\t unsigned int pcount, int shifted, int mss,\n\t\t\t bool dup_sack)\n{\n\tstruct tcp_sock *tp = tcp_sk(sk);\n\tu32 start_seq = TCP_SKB_CB(skb)->seq;\t/* start of newly-SACKed */\n\tu32 end_seq = start_seq + shifted;\t/* end of newly-SACKed */\n\n\tBUG_ON(!pcount);\n\n\t/* Adjust counters and hints for the newly sacked sequence\n\t * range but discard the return value since prev is already\n\t * marked. We must tag the range first because the seq\n\t * advancement below implicitly advances\n\t * tcp_highest_sack_seq() when skb is highest_sack.\n\t */\n\ttcp_sacktag_one(sk, state, TCP_SKB_CB(skb)->sacked,\n\t\t\tstart_seq, end_seq, dup_sack, pcount,\n\t\t\ttcp_skb_timestamp_us(skb));\n\ttcp_rate_skb_delivered(sk, skb, state->rate);\n\n\tif (skb == tp->lost_skb_hint)\n\t\ttp->lost_cnt_hint += pcount;\n\n\tTCP_SKB_CB(prev)->end_seq += shifted;\n\tTCP_SKB_CB(skb)->seq += shifted;\n\n\ttcp_skb_pcount_add(prev, pcount);\n\tBUG_ON(tcp_skb_pcount(skb) < pcount);\n\ttcp_skb_pcount_add(skb, -pcount);\n\n\t/* When we're adding to gso_segs == 1, gso_size will be zero,\n\t * in theory this shouldn't be necessary but as long as DSACK\n\t * code can come after this skb later on it's better to keep\n\t * setting gso_size to something.\n\t */\n\tif (!TCP_SKB_CB(prev)->tcp_gso_size)\n\t\tTCP_SKB_CB(prev)->tcp_gso_size = mss;\n\n\t/* CHECKME: To clear or not to clear? Mimics normal skb currently */\n\tif (tcp_skb_pcount(skb) <= 1)\n\t\tTCP_SKB_CB(skb)->tcp_gso_size = 0;\n\n\t/* Difference in this won't matter, both ACKed by the same cumul. ACK */\n\tTCP_SKB_CB(prev)->sacked |= (TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS);\n\n\tif (skb->len > 0) {\n\t\tBUG_ON(!tcp_skb_pcount(skb));\n\t\tNET_INC_STATS(sock_net(sk), LINUX_MIB_SACKSHIFTED);\n\t\treturn false;\n\t}\n\n\t/* Whole SKB was eaten :-) */\n\n\tif (skb == tp->retransmit_skb_hint)\n\t\ttp->retransmit_skb_hint = prev;\n\tif (skb == tp->lost_skb_hint) {\n\t\ttp->lost_skb_hint = prev;\n\t\ttp->lost_cnt_hint -= tcp_skb_pcount(prev);\n\t}\n\n\tTCP_SKB_CB(prev)->tcp_flags |= TCP_SKB_CB(skb)->tcp_flags;\n\tTCP_SKB_CB(prev)->eor = TCP_SKB_CB(skb)->eor;\n\tif (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)\n\t\tTCP_SKB_CB(prev)->end_seq++;\n\n\tif (skb == tcp_highest_sack(sk))\n\t\ttcp_advance_highest_sack(sk, skb);\n\n\ttcp_skb_collapse_tstamp(prev, skb);\n\tif (unlikely(TCP_SKB_CB(prev)->tx.delivered_mstamp))\n\t\tTCP_SKB_CB(prev)->tx.delivered_mstamp = 0;\n\n\ttcp_rtx_queue_unlink_and_free(skb, sk);\n\n\tNET_INC_STATS(sock_net(sk), LINUX_MIB_SACKMERGED);\n\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: int __mdiobus_register(struct mii_bus *bus, struct module *owner)\n{\n\tstruct mdio_device *mdiodev;\n\tint i, err;\n\tstruct gpio_desc *gpiod;\n\n\tif (NULL == bus || NULL == bus->name ||\n\t NULL == bus->read || NULL == bus->write)\n\t\treturn -EINVAL;\n\n\tBUG_ON(bus->state != MDIOBUS_ALLOCATED &&\n\t bus->state != MDIOBUS_UNREGISTERED);\n\n\tbus->owner = owner;\n\tbus->dev.parent = bus->parent;\n\tbus->dev.class = &mdio_bus_class;\n\tbus->dev.groups = NULL;\n\tdev_set_name(&bus->dev, \"%s\", bus->id);\n\n\terr = device_register(&bus->dev);\n\tif (err) {\n\t\tpr_err(\"mii_bus %s failed to register\\n\", bus->id);\n\t\tput_device(&bus->dev);\n\t\treturn -EINVAL;\n\t}\n\n\tmutex_init(&bus->mdio_lock);\n\n\t/* de-assert bus level PHY GPIO reset */\n\tgpiod = devm_gpiod_get_optional(&bus->dev, \"reset\", GPIOD_OUT_LOW);\n\tif (IS_ERR(gpiod)) {\n\t\tdev_err(&bus->dev, \"mii_bus %s couldn't get reset GPIO\\n\",\n\t\t\tbus->id);\n\t\tdevice_del(&bus->dev);\n\t\treturn PTR_ERR(gpiod);\n\t} else\tif (gpiod) {\n\t\tbus->reset_gpiod = gpiod;\n\n\t\tgpiod_set_value_cansleep(gpiod, 1);\n\t\tudelay(bus->reset_delay_us);\n\t\tgpiod_set_value_cansleep(gpiod, 0);\n\t}\n\n\tif (bus->reset)\n\t\tbus->reset(bus);\n\n\tfor (i = 0; i < PHY_MAX_ADDR; i++) {\n\t\tif ((bus->phy_mask & (1 << i)) == 0) {\n\t\t\tstruct phy_device *phydev;\n\n\t\t\tphydev = mdiobus_scan(bus, i);\n\t\t\tif (IS_ERR(phydev) && (PTR_ERR(phydev) != -ENODEV)) {\n\t\t\t\terr = PTR_ERR(phydev);\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t}\n\t}\n\n\tmdiobus_setup_mdiodev_from_board_info(bus, mdiobus_create_device);\n\n\tbus->state = MDIOBUS_REGISTERED;\n\tpr_info(\"%s: probed\\n\", bus->name);\n\treturn 0;\n\nerror:\n\twhile (--i >= 0) {\n\t\tmdiodev = bus->mdio_map[i];\n\t\tif (!mdiodev)\n\t\t\tcontinue;\n\n\t\tmdiodev->device_remove(mdiodev);\n\t\tmdiodev->device_free(mdiodev);\n\t}\n\n\t/* Put PHYs in RESET to save power */\n\tif (bus->reset_gpiod)\n\t\tgpiod_set_value_cansleep(bus->reset_gpiod, 1);\n\n\tdevice_del(&bus->dev);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'mdio_bus: Fix use-after-free on device_register fails\n\nKASAN has found use-after-free in fixed_mdio_bus_init,\ncommit 0c692d07842a (\"drivers/net/phy/mdio_bus.c: call\nput_device on device_register() failure\") call put_device()\nwhile device_register() fails,give up the last reference\nto the device and allow mdiobus_release to be executed\n,kfreeing the bus. However in most drives, mdiobus_free\nbe called to free the bus while mdiobus_register fails.\nuse-after-free occurs when access bus again, this patch\nrevert it to let mdiobus_free free the bus.\n\nKASAN report details as below:\n\nBUG: KASAN: use-after-free in mdiobus_free+0x85/0x90 drivers/net/phy/mdio_bus.c:482\nRead of size 4 at addr ffff8881dc824d78 by task syz-executor.0/3524\n\nCPU: 1 PID: 3524 Comm: syz-executor.0 Not tainted 5.0.0-rc7+ #45\nHardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014\nCall Trace:\n __dump_stack lib/dump_stack.c:77 [inline]\n dump_stack+0xfa/0x1ce lib/dump_stack.c:113\n print_address_description+0x65/0x270 mm/kasan/report.c:187\n kasan_report+0x149/0x18d mm/kasan/report.c:317\n mdiobus_free+0x85/0x90 drivers/net/phy/mdio_bus.c:482\n fixed_mdio_bus_init+0x283/0x1000 [fixed_phy]\n ? 0xffffffffc0e40000\n ? 0xffffffffc0e40000\n ? 0xffffffffc0e40000\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:00007f6215c19c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139\nRAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99\nRDX: 0000000000000000 RSI: 0000000020000080 RDI: 0000000000000003\nRBP: 00007f6215c19c70 R08: 0000000000000000 R09: 0000000000000000\nR10: 0000000000000000 R11: 0000000000000246 R12: 00007f6215c1a6bc\nR13: 00000000004bcefb R14: 00000000006f7030 R15: 0000000000000004\n\nAllocated by task 3524:\n set_track mm/kasan/common.c:85 [inline]\n __kasan_kmalloc.constprop.3+0xa0/0xd0 mm/kasan/common.c:496\n kmalloc include/linux/slab.h:545 [inline]\n kzalloc include/linux/slab.h:740 [inline]\n mdiobus_alloc_size+0x54/0x1b0 drivers/net/phy/mdio_bus.c:143\n fixed_mdio_bus_init+0x163/0x1000 [fixed_phy]\n do_one_initcall+0xfa/0x5ca init/main.c:887\n do_init_module+0x204/0x5f6 kernel/module.c:3460\n load_module+0x66b2/0x8570 kernel/module.c:3808\n __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902\n do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\n\nFreed by task 3524:\n set_track mm/kasan/common.c:85 [inline]\n __kasan_slab_free+0x130/0x180 mm/kasan/common.c:458\n slab_free_hook mm/slub.c:1409 [inline]\n slab_free_freelist_hook mm/slub.c:1436 [inline]\n slab_free mm/slub.c:2986 [inline]\n kfree+0xe1/0x270 mm/slub.c:3938\n device_release+0x78/0x200 drivers/base/core.c:919\n kobject_cleanup lib/kobject.c:662 [inline]\n kobject_release lib/kobject.c:691 [inline]\n kref_put include/linux/kref.h:67 [inline]\n kobject_put+0x146/0x240 lib/kobject.c:708\n put_device+0x1c/0x30 drivers/base/core.c:2060\n __mdiobus_register+0x483/0x560 drivers/net/phy/mdio_bus.c:382\n fixed_mdio_bus_init+0x26b/0x1000 [fixed_phy]\n do_one_initcall+0xfa/0x5ca init/main.c:887\n do_init_module+0x204/0x5f6 kernel/module.c:3460\n load_module+0x66b2/0x8570 kernel/module.c:3808\n __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902\n do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\n\nThe buggy address belongs to the object at ffff8881dc824c80\n which belongs to the cache kmalloc-2k of size 2048\nThe buggy address is located 248 bytes inside of\n 2048-byte region [ffff8881dc824c80, ffff8881dc825480)\nThe buggy address belongs to the page:\npage:ffffea0007720800 count:1 mapcount:0 mapping:ffff8881f6c02800 index:0x0 compound_mapcount: 0\nflags: 0x2fffc0000010200(slab|head)\nraw: 02fffc0000010200 0000000000000000 0000000500000001 ffff8881f6c02800\nraw: 0000000000000000 00000000800f000f 00000001ffffffff 0000000000000000\npage dumped because: kasan: bad access detected\n\nMemory state around the buggy address:\n ffff8881dc824c00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc\n ffff8881dc824c80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n>ffff8881dc824d00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n ^\n ffff8881dc824d80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n ffff8881dc824e00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n\nFixes: 0c692d07842a (\"drivers/net/phy/mdio_bus.c: call put_device on device_register() failure\")\nSigned-off-by: YueHaibing \nReviewed-by: Andrew Lunn \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 hllMerge(uint8_t *max, robj *hll) {\n struct hllhdr *hdr = hll->ptr;\n int i;\n\n if (hdr->encoding == HLL_DENSE) {\n uint8_t val;\n\n for (i = 0; i < HLL_REGISTERS; i++) {\n HLL_DENSE_GET_REGISTER(val,hdr->registers,i);\n if (val > max[i]) max[i] = val;\n }\n } else {\n uint8_t *p = hll->ptr, *end = p + sdslen(hll->ptr);\n long runlen, regval;\n\n p += HLL_HDR_SIZE;\n i = 0;\n while(p < end) {\n if (HLL_SPARSE_IS_ZERO(p)) {\n runlen = HLL_SPARSE_ZERO_LEN(p);\n i += runlen;\n p++;\n } else if (HLL_SPARSE_IS_XZERO(p)) {\n runlen = HLL_SPARSE_XZERO_LEN(p);\n i += runlen;\n p += 2;\n } else {\n runlen = HLL_SPARSE_VAL_LEN(p);\n regval = HLL_SPARSE_VAL_VALUE(p);\n while(runlen--) {\n if (regval > max[i]) max[i] = regval;\n i++;\n }\n p++;\n }\n }\n if (i != HLL_REGISTERS) return C_ERR;\n }\n return C_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix hyperloglog corruption'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: inline int web_client_api_request_v1_data(RRDHOST *host, struct web_client *w, char *url) {\n debug(D_WEB_CLIENT, \"%llu: API v1 data with URL '%s'\", w->id, url);\n\n int ret = 400;\n BUFFER *dimensions = NULL;\n\n buffer_flush(w->response.data);\n\n char *google_version = \"0.6\",\n *google_reqId = \"0\",\n *google_sig = \"0\",\n *google_out = \"json\",\n *responseHandler = NULL,\n *outFileName = NULL;\n\n time_t last_timestamp_in_data = 0, google_timestamp = 0;\n\n char *chart = NULL\n , *before_str = NULL\n , *after_str = NULL\n , *group_time_str = NULL\n , *points_str = NULL;\n\n int group = RRDR_GROUPING_AVERAGE;\n uint32_t format = DATASOURCE_JSON;\n uint32_t options = 0x00000000;\n\n while(url) {\n char *value = mystrsep(&url, \"?&\");\n if(!value || !*value) continue;\n\n char *name = mystrsep(&value, \"=\");\n if(!name || !*name) continue;\n if(!value || !*value) continue;\n\n debug(D_WEB_CLIENT, \"%llu: API v1 data query param '%s' with value '%s'\", w->id, name, value);\n\n // name and value are now the parameters\n // they are not null and not empty\n\n if(!strcmp(name, \"chart\")) chart = value;\n else if(!strcmp(name, \"dimension\") || !strcmp(name, \"dim\") || !strcmp(name, \"dimensions\") || !strcmp(name, \"dims\")) {\n if(!dimensions) dimensions = buffer_create(100);\n buffer_strcat(dimensions, \"|\");\n buffer_strcat(dimensions, value);\n }\n else if(!strcmp(name, \"after\")) after_str = value;\n else if(!strcmp(name, \"before\")) before_str = value;\n else if(!strcmp(name, \"points\")) points_str = value;\n else if(!strcmp(name, \"gtime\")) group_time_str = value;\n else if(!strcmp(name, \"group\")) {\n group = web_client_api_request_v1_data_group(value, RRDR_GROUPING_AVERAGE);\n }\n else if(!strcmp(name, \"format\")) {\n format = web_client_api_request_v1_data_format(value);\n }\n else if(!strcmp(name, \"options\")) {\n options |= web_client_api_request_v1_data_options(value);\n }\n else if(!strcmp(name, \"callback\")) {\n responseHandler = value;\n }\n else if(!strcmp(name, \"filename\")) {\n outFileName = value;\n }\n else if(!strcmp(name, \"tqx\")) {\n // parse Google Visualization API options\n // https://developers.google.com/chart/interactive/docs/dev/implementing_data_source\n char *tqx_name, *tqx_value;\n\n while(value) {\n tqx_value = mystrsep(&value, \";\");\n if(!tqx_value || !*tqx_value) continue;\n\n tqx_name = mystrsep(&tqx_value, \":\");\n if(!tqx_name || !*tqx_name) continue;\n if(!tqx_value || !*tqx_value) continue;\n\n if(!strcmp(tqx_name, \"version\"))\n google_version = tqx_value;\n else if(!strcmp(tqx_name, \"reqId\"))\n google_reqId = tqx_value;\n else if(!strcmp(tqx_name, \"sig\")) {\n google_sig = tqx_value;\n google_timestamp = strtoul(google_sig, NULL, 0);\n }\n else if(!strcmp(tqx_name, \"out\")) {\n google_out = tqx_value;\n format = web_client_api_request_v1_data_google_format(google_out);\n }\n else if(!strcmp(tqx_name, \"responseHandler\"))\n responseHandler = tqx_value;\n else if(!strcmp(tqx_name, \"outFileName\"))\n outFileName = tqx_value;\n }\n }\n }\n\n if(!chart || !*chart) {\n buffer_sprintf(w->response.data, \"No chart id is given at the request.\");\n goto cleanup;\n }\n\n RRDSET *st = rrdset_find(host, chart);\n if(!st) st = rrdset_find_byname(host, chart);\n if(!st) {\n buffer_strcat(w->response.data, \"Chart is not found: \");\n buffer_strcat_htmlescape(w->response.data, chart);\n ret = 404;\n goto cleanup;\n }\n st->last_accessed_time = now_realtime_sec();\n\n long long before = (before_str && *before_str)?str2l(before_str):0;\n long long after = (after_str && *after_str) ?str2l(after_str):0;\n int points = (points_str && *points_str)?str2i(points_str):0;\n long group_time = (group_time_str && *group_time_str)?str2l(group_time_str):0;\n\n debug(D_WEB_CLIENT, \"%llu: API command 'data' for chart '%s', dimensions '%s', after '%lld', before '%lld', points '%d', group '%d', format '%u', options '0x%08x'\"\n , w->id\n , chart\n , (dimensions)?buffer_tostring(dimensions):\"\"\n , after\n , before\n , points\n , group\n , format\n , options\n );\n\n if(outFileName && *outFileName) {\n buffer_sprintf(w->response.header, \"Content-Disposition: attachment; filename=\\\"%s\\\"\\r\\n\", outFileName);\n debug(D_WEB_CLIENT, \"%llu: generating outfilename header: '%s'\", w->id, outFileName);\n }\n\n if(format == DATASOURCE_DATATABLE_JSONP) {\n if(responseHandler == NULL)\n responseHandler = \"google.visualization.Query.setResponse\";\n\n debug(D_WEB_CLIENT_ACCESS, \"%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'\",\n w->id, google_version, google_reqId, google_sig, google_out, responseHandler, outFileName\n );\n\n buffer_sprintf(w->response.data,\n \"%s({version:'%s',reqId:'%s',status:'ok',sig:'%ld',table:\",\n responseHandler, google_version, google_reqId, st->last_updated.tv_sec);\n }\n else if(format == DATASOURCE_JSONP) {\n if(responseHandler == NULL)\n responseHandler = \"callback\";\n\n buffer_strcat(w->response.data, responseHandler);\n buffer_strcat(w->response.data, \"(\");\n }\n\n ret = rrdset2anything_api_v1(st, w->response.data, dimensions, format, points, after, before, group, group_time\n , options, &last_timestamp_in_data);\n\n if(format == DATASOURCE_DATATABLE_JSONP) {\n if(google_timestamp < last_timestamp_in_data)\n buffer_strcat(w->response.data, \"});\");\n\n else {\n // the client already has the latest data\n buffer_flush(w->response.data);\n buffer_sprintf(w->response.data,\n \"%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});\",\n responseHandler, google_version, google_reqId);\n }\n }\n else if(format == DATASOURCE_JSONP)\n buffer_strcat(w->response.data, \");\");\n\n cleanup:\n buffer_free(dimensions);\n return ret;\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 *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 profile_data,\n profile_size,\n start_position;\n\n MemoryInfo\n *pixel_info;\n\n Quantum\n index;\n\n register Quantum\n *q;\n\n register ssize_t\n i,\n x;\n\n register unsigned char\n *p;\n\n size_t\n bit,\n bytes_per_line,\n length;\n\n ssize_t\n count,\n y;\n\n unsigned char\n magick[12],\n *pixels;\n\n unsigned int\n blue,\n green,\n offset_bits,\n red;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Determine if this a BMP file.\n */\n (void) memset(&bmp_info,0,sizeof(bmp_info));\n bmp_info.ba_offset=0;\n start_position=0;\n offset_bits=0;\n count=ReadBlob(image,2,magick);\n if (count != 2)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n do\n {\n PixelInfo\n quantum_bits;\n\n PixelPacket\n shift;\n\n /*\n Verify BMP identifier.\n */\n start_position=TellBlob(image)-2;\n bmp_info.ba_offset=0;\n while (LocaleNCompare((char *) magick,\"BA\",2) == 0)\n {\n bmp_info.file_size=ReadBlobLSBLong(image);\n bmp_info.ba_offset=ReadBlobLSBLong(image);\n bmp_info.offset_bits=ReadBlobLSBLong(image);\n count=ReadBlob(image,2,magick);\n if (count != 2)\n break;\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Magick: %c%c\",\n magick[0],magick[1]);\n if ((count != 2) || ((LocaleNCompare((char *) magick,\"BM\",2) != 0) &&\n (LocaleNCompare((char *) magick,\"CI\",2) != 0)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n bmp_info.file_size=ReadBlobLSBLong(image);\n (void) ReadBlobLSBLong(image);\n bmp_info.offset_bits=ReadBlobLSBLong(image);\n bmp_info.size=ReadBlobLSBLong(image);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" BMP size: %u\",\n bmp_info.size);\n profile_data=0;\n profile_size=0;\n if (bmp_info.size == 12)\n {\n /*\n OS/2 BMP image file.\n */\n (void) CopyMagickString(image->magick,\"BMP2\",MagickPathExtent);\n bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image));\n bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image));\n bmp_info.planes=ReadBlobLSBShort(image);\n bmp_info.bits_per_pixel=ReadBlobLSBShort(image);\n bmp_info.x_pixels=0;\n bmp_info.y_pixels=0;\n bmp_info.number_colors=0;\n bmp_info.compression=BI_RGB;\n bmp_info.image_size=0;\n bmp_info.alpha_mask=0;\n if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Format: OS/2 Bitmap\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Geometry: %.20gx%.20g\",(double) bmp_info.width,(double)\n bmp_info.height);\n }\n }\n else\n {\n /*\n Microsoft Windows BMP image file.\n */\n if (bmp_info.size < 40)\n ThrowReaderException(CorruptImageError,\"NonOS2HeaderSizeError\");\n bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image);\n bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image);\n bmp_info.planes=ReadBlobLSBShort(image);\n bmp_info.bits_per_pixel=ReadBlobLSBShort(image);\n bmp_info.compression=ReadBlobLSBLong(image);\n bmp_info.image_size=ReadBlobLSBLong(image);\n bmp_info.x_pixels=ReadBlobLSBLong(image);\n bmp_info.y_pixels=ReadBlobLSBLong(image);\n bmp_info.number_colors=ReadBlobLSBLong(image);\n if ((MagickSizeType) bmp_info.number_colors > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n bmp_info.colors_important=ReadBlobLSBLong(image);\n if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Format: MS Windows bitmap\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Geometry: %.20gx%.20g\",(double) bmp_info.width,(double)\n bmp_info.height);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Bits per pixel: %.20g\",(double) bmp_info.bits_per_pixel);\n switch (bmp_info.compression)\n {\n case BI_RGB:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_RGB\");\n break;\n }\n case BI_RLE4:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_RLE4\");\n break;\n }\n case BI_RLE8:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_RLE8\");\n break;\n }\n case BI_BITFIELDS:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_BITFIELDS\");\n break;\n }\n case BI_PNG:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_PNG\");\n break;\n }\n case BI_JPEG:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_JPEG\");\n break;\n }\n default:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: UNKNOWN (%u)\",bmp_info.compression);\n }\n }\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Number of colors: %u\",bmp_info.number_colors);\n }\n bmp_info.red_mask=ReadBlobLSBLong(image);\n bmp_info.green_mask=ReadBlobLSBLong(image);\n bmp_info.blue_mask=ReadBlobLSBLong(image);\n if (bmp_info.size > 40)\n {\n double\n gamma;\n\n /*\n Read color management information.\n */\n bmp_info.alpha_mask=ReadBlobLSBLong(image);\n bmp_info.colorspace=ReadBlobLSBSignedLong(image);\n /*\n Decode 2^30 fixed point formatted CIE primaries.\n */\n# define BMP_DENOM ((double) 0x40000000)\n bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n\n gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+\n bmp_info.red_primary.z;\n gamma=PerceptibleReciprocal(gamma);\n bmp_info.red_primary.x*=gamma;\n bmp_info.red_primary.y*=gamma;\n image->chromaticity.red_primary.x=bmp_info.red_primary.x;\n image->chromaticity.red_primary.y=bmp_info.red_primary.y;\n\n gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+\n bmp_info.green_primary.z;\n gamma=PerceptibleReciprocal(gamma);\n bmp_info.green_primary.x*=gamma;\n bmp_info.green_primary.y*=gamma;\n image->chromaticity.green_primary.x=bmp_info.green_primary.x;\n image->chromaticity.green_primary.y=bmp_info.green_primary.y;\n\n gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+\n bmp_info.blue_primary.z;\n gamma=PerceptibleReciprocal(gamma);\n bmp_info.blue_primary.x*=gamma;\n bmp_info.blue_primary.y*=gamma;\n image->chromaticity.blue_primary.x=bmp_info.blue_primary.x;\n image->chromaticity.blue_primary.y=bmp_info.blue_primary.y;\n\n /*\n Decode 16^16 fixed point formatted gamma_scales.\n */\n bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000;\n bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000;\n bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000;\n /*\n Compute a single gamma from the BMP 3-channel gamma.\n */\n image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+\n bmp_info.gamma_scale.z)/3.0;\n }\n else\n (void) CopyMagickString(image->magick,\"BMP3\",MagickPathExtent);\n\n if (bmp_info.size > 108)\n {\n size_t\n intent;\n\n /*\n Read BMP Version 5 color management information.\n */\n intent=ReadBlobLSBLong(image);\n switch ((int) intent)\n {\n case LCS_GM_BUSINESS:\n {\n image->rendering_intent=SaturationIntent;\n break;\n }\n case LCS_GM_GRAPHICS:\n {\n image->rendering_intent=RelativeIntent;\n break;\n }\n case LCS_GM_IMAGES:\n {\n image->rendering_intent=PerceptualIntent;\n break;\n }\n case LCS_GM_ABS_COLORIMETRIC:\n {\n image->rendering_intent=AbsoluteIntent;\n break;\n }\n }\n profile_data=(MagickOffsetType)ReadBlobLSBLong(image);\n profile_size=(MagickOffsetType)ReadBlobLSBLong(image);\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,\"UnsupportedBitsPerPixel\");\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,\"UnsupportedBitsPerPixel\");\n if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4))\n ThrowReaderException(CorruptImageError,\"UnsupportedBitsPerPixel\");\n if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16))\n ThrowReaderException(CorruptImageError,\"UnsupportedBitsPerPixel\");\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/256) > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n if ((bmp_info.compression == BI_RGB) ||\n (bmp_info.compression == BI_BITFIELDS))\n {\n pixel_info=AcquireVirtualMemory(image->rows,\n MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reading pixels (%.20g bytes)\",(double) length);\n count=ReadBlob(image,length,pixels);\n if (count != (ssize_t) length)\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"InsufficientImageDataInFile\");\n }\n }\n else\n {\n /*\n Convert run-length encoded raster pixels.\n */\n pixel_info=AcquireVirtualMemory(image->rows,\n MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n status=DecodeImage(image,bmp_info.compression,pixels,\n image->columns*image->rows);\n if (status == MagickFalse)\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"UnableToRunlengthDecodeImage\");\n }\n }\n /*\n Convert BMP raster image to pixel packets.\n */\n if (bmp_info.compression == BI_RGB)\n {\n /*\n We should ignore the alpha value in BMP3 files but there have been\n reports about 32 bit files with alpha. We do a quick check to see if\n the alpha channel contains a value that is not zero (default value).\n If we find a non zero value we asume the program that wrote the file\n wants to use the alpha channel.\n */\n if ((image->alpha_trait == UndefinedPixelTrait) &&\n (bmp_info.size == 40) && (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 Read embeded ICC profile\n */\n if ((bmp_info.colorspace == 0x4D424544L) && (profile_data > 0) &&\n (profile_size > 0))\n {\n StringInfo\n *profile;\n\n unsigned char\n *datum;\n\n offset=start_position+14+profile_data;\n if ((offset < TellBlob(image)) ||\n (SeekBlob(image,offset,SEEK_SET) != offset) ||\n (GetBlobSize(image) < (MagickSizeType) (offset+profile_size)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n profile=AcquireStringInfo((size_t) profile_size);\n if (profile == (StringInfo *) NULL)\n ThrowReaderException(CorruptImageError,\"MemoryAllocationFailed\");\n datum=GetStringInfoDatum(profile);\n if (ReadBlob(image,(size_t) profile_size,datum) == (ssize_t) profile_size)\n {\n MagickOffsetType\n profile_size_orig;\n\n /*\n Trimming padded bytes.\n */\n profile_size_orig=(MagickOffsetType) datum[0] << 24;\n profile_size_orig|=(MagickOffsetType) datum[1] << 16;\n profile_size_orig|=(MagickOffsetType) datum[2] << 8;\n profile_size_orig|=(MagickOffsetType) datum[3];\n if (profile_size_orig < profile_size)\n SetStringInfoLength(profile,(size_t) profile_size_orig);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Profile: ICC, %u bytes\",(unsigned int) profile_size_orig);\n (void) SetImageProfile(image,\"icc\",profile,exception);\n }\n profile=DestroyStringInfo(profile);\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 offset=(MagickOffsetType) bmp_info.ba_offset;\n if (offset != 0)\n if ((offset < TellBlob(image)) ||\n (SeekBlob(image,offset,SEEK_SET) != offset))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n *magick='\\0';\n count=ReadBlob(image,2,magick);\n if ((count == 2) && (IsBMP(magick,2) != MagickFalse))\n {\n /*\n Acquire next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n status=MagickFalse;\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n } while (IsBMP(magick,2) != MagickFalse);\n (void) CloseBlob(image);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-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 *ReadFLIFImage(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n FLIF_DECODER\n *flifdec;\n\n FLIF_IMAGE\n *flifimage;\n\n Image\n *image;\n\n MagickBooleanType\n status;\n\n register PixelPacket\n *q;\n\n register ssize_t\n x;\n\n register unsigned short\n *p;\n\n size_t\n count,\n image_count,\n length;\n\n ssize_t\n y;\n\n unsigned char\n *stream;\n\n unsigned short\n *pixels;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n length=(size_t) GetBlobSize(image);\n stream=(unsigned char *) AcquireQuantumMemory(length,sizeof(*stream));\n if (stream == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n count=ReadBlob(image,length,stream);\n if (count != length)\n {\n stream=(unsigned char *) RelinquishMagickMemory(stream);\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n }\n flifdec=flif_create_decoder();\n if (image_info->quality != UndefinedCompressionQuality)\n flif_decoder_set_quality(flifdec,image_info->quality);\n if (!flif_decoder_decode_memory(flifdec,stream,length))\n {\n flif_destroy_decoder(flifdec);\n ThrowReaderException(CorruptImageError,\"CorruptImage\");\n }\n image_count=flif_decoder_num_images(flifdec);\n flifimage=flif_decoder_get_image(flifdec,0);\n length=sizeof(unsigned short)*4*flif_image_get_width(flifimage);\n pixels=(unsigned short *) AcquireMagickMemory(length);\n if (pixels == (unsigned short *) NULL)\n {\n flif_destroy_decoder(flifdec);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n\n for (count=0; count < image_count; count++)\n {\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 flif_destroy_decoder(flifdec);\n pixels=(unsigned short *) RelinquishMagickMemory(pixels);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n }\n flifimage=flif_decoder_get_image(flifdec,count);\n image->columns=(size_t) flif_image_get_width(flifimage);\n image->rows=(size_t) flif_image_get_height(flifimage);\n image->depth=flif_image_get_depth(flifimage);\n image->matte=(flif_image_get_nb_channels(flifimage) > 3 ?\n MagickTrue : MagickFalse);\n image->delay=flif_image_get_frame_delay(flifimage);\n image->ticks_per_second=1000;\n image->scene=count;\n image->dispose=BackgroundDispose;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n flif_image_read_row_RGBA16(flifimage,y,pixels,length);\n p=pixels;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(q,ScaleShortToQuantum(*p++));\n SetPixelGreen(q,ScaleShortToQuantum(*p++));\n SetPixelBlue(q,ScaleShortToQuantum(*p++));\n SetPixelAlpha(q,ScaleShortToQuantum(*p++));\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 }\n flif_destroy_decoder(flifdec);\n pixels=(unsigned short *) RelinquishMagickMemory(pixels);\n return(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 *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n#define ThrowPNMException(exception,message) \\\n{ \\\n if (comment_info.comment != (char *) NULL) \\\n comment_info.comment=DestroyString(comment_info.comment); \\\n ThrowReaderException((exception),(message)); \\\n}\n\n char\n format;\n\n CommentInfo\n comment_info;\n\n double\n quantum_scale;\n\n Image\n *image;\n\n MagickBooleanType\n status;\n\n QuantumAny\n max_value;\n\n QuantumInfo\n *quantum_info;\n\n QuantumType\n quantum_type;\n\n size_t\n depth,\n extent,\n packet_size;\n\n ssize_t\n count,\n row,\n y;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read PNM image.\n */\n count=ReadBlob(image,1,(unsigned char *) &format);\n do\n {\n /*\n Initialize image structure.\n */\n comment_info.comment=AcquireString(NULL);\n comment_info.extent=MagickPathExtent;\n if ((count != 1) || (format != 'P'))\n ThrowPNMException(CorruptImageError,\"ImproperImageHeader\");\n max_value=1;\n quantum_type=RGBQuantum;\n quantum_scale=1.0;\n format=(char) ReadBlobByte(image);\n if (format != '7')\n {\n /*\n PBM, PGM, PPM, and PNM.\n */\n image->columns=PNMInteger(image,&comment_info,10);\n image->rows=PNMInteger(image,&comment_info,10);\n if ((format == 'f') || (format == 'F'))\n {\n char\n scale[MaxTextExtent];\n\n if (ReadBlobString(image,scale) != (char *) NULL)\n quantum_scale=StringToDouble(scale,(char **) NULL);\n }\n else\n {\n if ((format == '1') || (format == '4'))\n max_value=1; /* bitmap */\n else\n max_value=PNMInteger(image,&comment_info,10);\n }\n }\n else\n {\n char\n keyword[MaxTextExtent],\n value[MaxTextExtent];\n\n int\n c;\n\n register char\n *p;\n\n /*\n PAM.\n */\n for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))\n {\n while (isspace((int) ((unsigned char) c)) != 0)\n c=ReadBlobByte(image);\n if (c == '#')\n {\n /*\n Comment.\n */\n c=PNMComment(image,&comment_info);\n c=ReadBlobByte(image);\n while (isspace((int) ((unsigned char) c)) != 0)\n c=ReadBlobByte(image);\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));\n *p='\\0';\n if (LocaleCompare(keyword,\"endhdr\") == 0)\n break;\n while (isspace((int) ((unsigned char) c)) != 0)\n c=ReadBlobByte(image);\n p=value;\n while (isalnum(c) || (c == '_'))\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 if (LocaleCompare(keyword,\"depth\") == 0)\n packet_size=StringToUnsignedLong(value);\n (void) packet_size;\n if (LocaleCompare(keyword,\"height\") == 0)\n image->rows=StringToUnsignedLong(value);\n if (LocaleCompare(keyword,\"maxval\") == 0)\n max_value=StringToUnsignedLong(value);\n if (LocaleCompare(keyword,\"TUPLTYPE\") == 0)\n {\n if (LocaleCompare(value,\"BLACKANDWHITE\") == 0)\n {\n (void) SetImageColorspace(image,GRAYColorspace);\n quantum_type=GrayQuantum;\n }\n if (LocaleCompare(value,\"BLACKANDWHITE_ALPHA\") == 0)\n {\n (void) SetImageColorspace(image,GRAYColorspace);\n image->matte=MagickTrue;\n quantum_type=GrayAlphaQuantum;\n }\n if (LocaleCompare(value,\"GRAYSCALE\") == 0)\n {\n (void) SetImageColorspace(image,GRAYColorspace);\n quantum_type=GrayQuantum;\n }\n if (LocaleCompare(value,\"GRAYSCALE_ALPHA\") == 0)\n {\n (void) SetImageColorspace(image,GRAYColorspace);\n image->matte=MagickTrue;\n quantum_type=GrayAlphaQuantum;\n }\n if (LocaleCompare(value,\"RGB_ALPHA\") == 0)\n {\n quantum_type=RGBAQuantum;\n image->matte=MagickTrue;\n }\n if (LocaleCompare(value,\"CMYK\") == 0)\n {\n (void) SetImageColorspace(image,CMYKColorspace);\n quantum_type=CMYKQuantum;\n }\n if (LocaleCompare(value,\"CMYK_ALPHA\") == 0)\n {\n (void) SetImageColorspace(image,CMYKColorspace);\n image->matte=MagickTrue;\n quantum_type=CMYKAQuantum;\n }\n }\n if (LocaleCompare(keyword,\"width\") == 0)\n image->columns=StringToUnsignedLong(value);\n }\n }\n if ((image->columns == 0) || (image->rows == 0))\n ThrowPNMException(CorruptImageError,\"NegativeOrZeroImageSize\");\n if ((max_value == 0) || (max_value > 4294967295U))\n ThrowPNMException(CorruptImageError,\"ImproperImageHeader\");\n for (depth=1; GetQuantumRange(depth) < max_value; depth++) ;\n image->depth=depth;\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n InheritException(exception,&image->exception);\n return(DestroyImageList(image));\n }\n (void) SetImageBackgroundColor(image);\n /*\n Convert PNM pixels.\n */\n row=0;\n switch (format)\n {\n case '1':\n {\n /*\n Convert PBM image to pixel packets.\n */\n (void) SetImageColorspace(image,GRAYColorspace);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register ssize_t\n x;\n\n register PixelPacket\n *magick_restrict q;\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 SetPixelRed(q,PNMInteger(image,&comment_info,2) == 0 ?\n QuantumRange : 0);\n if (EOFBlob(image) != MagickFalse)\n break;\n SetPixelGreen(q,GetPixelRed(q));\n SetPixelBlue(q,GetPixelRed(q));\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n if (EOFBlob(image) != MagickFalse)\n break;\n }\n image->type=BilevelType;\n break;\n }\n case '2':\n {\n size_t\n intensity;\n\n /*\n Convert PGM image to pixel packets.\n */\n (void) SetImageColorspace(image,GRAYColorspace);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register ssize_t\n x;\n\n register PixelPacket\n *magick_restrict q;\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 intensity=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10),\n max_value);\n if (EOFBlob(image) != MagickFalse)\n break;\n SetPixelRed(q,intensity);\n SetPixelGreen(q,GetPixelRed(q));\n SetPixelBlue(q,GetPixelRed(q));\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n if (EOFBlob(image) != MagickFalse)\n break;\n }\n image->type=GrayscaleType;\n break;\n }\n case '3':\n {\n /*\n Convert PNM image to pixel packets.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register ssize_t\n x;\n\n register PixelPacket\n *magick_restrict q;\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 QuantumAny\n pixel;\n\n pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10),\n max_value);\n if (EOFBlob(image) != MagickFalse)\n break;\n SetPixelRed(q,pixel);\n pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10),\n max_value);\n SetPixelGreen(q,pixel);\n pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10),\n max_value);\n SetPixelBlue(q,pixel);\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n if (EOFBlob(image) != MagickFalse)\n break;\n }\n break;\n }\n case '4':\n {\n /*\n Convert PBM raw image to pixel packets.\n */\n (void) SetImageColorspace(image,GRAYColorspace);\n quantum_type=GrayQuantum;\n if (image->storage_class == PseudoClass)\n quantum_type=IndexQuantum;\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowPNMException(ResourceLimitError,\"MemoryAllocationFailed\");\n SetQuantumMinIsWhite(quantum_info,MagickTrue);\n extent=GetQuantumExtent(image,quantum_info,quantum_type);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n const unsigned char\n *pixels;\n\n MagickBooleanType\n sync;\n\n register PixelPacket\n *magick_restrict q;\n\n ssize_t\n count,\n offset;\n\n size_t\n length;\n\n pixels=(unsigned char *) ReadBlobStream(image,extent,\n GetQuantumPixels(quantum_info),&count);\n if (count != (ssize_t) extent)\n break;\n if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&\n (image->previous == (Image *) NULL))\n {\n MagickBooleanType\n proceed;\n\n proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n row,image->rows);\n if (proceed == MagickFalse)\n break;\n }\n offset=row++;\n q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n if (length != extent)\n break;\n sync=SyncAuthenticPixels(image,exception);\n if (sync == MagickFalse)\n break;\n }\n quantum_info=DestroyQuantumInfo(quantum_info);\n SetQuantumImageType(image,quantum_type);\n break;\n }\n case '5':\n {\n /*\n Convert PGM raw image to pixel packets.\n */\n (void) SetImageColorspace(image,GRAYColorspace);\n quantum_type=GrayQuantum;\n extent=(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)*\n image->columns;\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowPNMException(ResourceLimitError,\"MemoryAllocationFailed\");\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n const unsigned char\n *pixels;\n\n MagickBooleanType\n sync;\n\n register const unsigned char\n *magick_restrict p;\n\n register PixelPacket\n *magick_restrict q;\n\n register ssize_t\n x;\n\n ssize_t\n count,\n offset;\n\n pixels=(unsigned char *) ReadBlobStream(image,extent,\n GetQuantumPixels(quantum_info),&count);\n if (count != (ssize_t) extent)\n break;\n if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&\n (image->previous == (Image *) NULL))\n {\n MagickBooleanType\n proceed;\n\n proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n row,image->rows);\n if (proceed == MagickFalse)\n break;\n }\n offset=row++;\n q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n p=pixels;\n switch (image->depth)\n {\n case 8:\n case 16:\n case 32:\n {\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n break;\n }\n default:\n {\n unsigned int\n pixel;\n\n if (image->depth <= 8)\n {\n unsigned char\n pixel;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n p=PushCharPixel(p,&pixel);\n SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));\n SetPixelGreen(q,GetPixelRed(q));\n SetPixelBlue(q,GetPixelRed(q));\n q++;\n }\n break;\n }\n if (image->depth <= 16)\n {\n unsigned short\n pixel;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n p=PushShortPixel(MSBEndian,p,&pixel);\n SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));\n SetPixelGreen(q,GetPixelRed(q));\n SetPixelBlue(q,GetPixelRed(q));\n q++;\n }\n break;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n p=PushLongPixel(MSBEndian,p,&pixel);\n SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));\n SetPixelGreen(q,GetPixelRed(q));\n SetPixelBlue(q,GetPixelRed(q));\n q++;\n }\n break;\n }\n }\n sync=SyncAuthenticPixels(image,exception);\n if (sync == MagickFalse)\n break;\n }\n quantum_info=DestroyQuantumInfo(quantum_info);\n SetQuantumImageType(image,quantum_type);\n break;\n }\n case '6':\n {\n /*\n Convert PNM raster image to pixel packets.\n */\n quantum_type=RGBQuantum;\n extent=3*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)*\n image->columns;\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowPNMException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) SetQuantumEndian(image,quantum_info,MSBEndian);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n const unsigned char\n *pixels;\n\n MagickBooleanType\n sync;\n\n register const unsigned char\n *magick_restrict p;\n\n register PixelPacket\n *magick_restrict q;\n\n register ssize_t\n x;\n\n ssize_t\n count,\n offset;\n\n pixels=(unsigned char *) ReadBlobStream(image,extent,\n GetQuantumPixels(quantum_info),&count);\n if (count != (ssize_t) extent)\n break;\n if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&\n (image->previous == (Image *) NULL))\n {\n MagickBooleanType\n proceed;\n\n proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n row,image->rows);\n if (proceed == MagickFalse)\n break;\n }\n offset=row++;\n q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n p=pixels;\n switch (image->depth)\n {\n case 8:\n {\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(q,ScaleCharToQuantum(*p++));\n SetPixelGreen(q,ScaleCharToQuantum(*p++));\n SetPixelBlue(q,ScaleCharToQuantum(*p++));\n q->opacity=OpaqueOpacity;\n q++;\n }\n break;\n }\n case 16:\n {\n unsigned short\n pixel;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n p=PushShortPixel(MSBEndian,p,&pixel);\n SetPixelRed(q,ScaleShortToQuantum(pixel));\n p=PushShortPixel(MSBEndian,p,&pixel);\n SetPixelGreen(q,ScaleShortToQuantum(pixel));\n p=PushShortPixel(MSBEndian,p,&pixel);\n SetPixelBlue(q,ScaleShortToQuantum(pixel));\n SetPixelOpacity(q,OpaqueOpacity);\n q++;\n }\n break;\n }\n case 32:\n {\n unsigned int\n pixel;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n p=PushLongPixel(MSBEndian,p,&pixel);\n SetPixelRed(q,ScaleLongToQuantum(pixel));\n p=PushLongPixel(MSBEndian,p,&pixel);\n SetPixelGreen(q,ScaleLongToQuantum(pixel));\n p=PushLongPixel(MSBEndian,p,&pixel);\n SetPixelBlue(q,ScaleLongToQuantum(pixel));\n SetPixelOpacity(q,OpaqueOpacity);\n q++;\n }\n break;\n }\n default:\n {\n unsigned int\n pixel;\n\n if (image->depth <= 8)\n {\n unsigned char\n pixel;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n p=PushCharPixel(p,&pixel);\n SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));\n p=PushCharPixel(p,&pixel);\n SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));\n p=PushCharPixel(p,&pixel);\n SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));\n SetPixelOpacity(q,OpaqueOpacity);\n q++;\n }\n break;\n }\n if (image->depth <= 16)\n {\n unsigned short\n pixel;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n p=PushShortPixel(MSBEndian,p,&pixel);\n SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));\n p=PushShortPixel(MSBEndian,p,&pixel);\n SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));\n p=PushShortPixel(MSBEndian,p,&pixel);\n SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));\n SetPixelOpacity(q,OpaqueOpacity);\n q++;\n }\n break;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n p=PushLongPixel(MSBEndian,p,&pixel);\n SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));\n p=PushLongPixel(MSBEndian,p,&pixel);\n SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));\n p=PushLongPixel(MSBEndian,p,&pixel);\n SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));\n SetPixelOpacity(q,OpaqueOpacity);\n q++;\n }\n break;\n }\n break;\n }\n sync=SyncAuthenticPixels(image,exception);\n if (sync == MagickFalse)\n break;\n }\n quantum_info=DestroyQuantumInfo(quantum_info);\n break;\n }\n case '7':\n {\n register IndexPacket\n *indexes;\n\n size_t\n channels;\n\n /*\n Convert PAM raster image to pixel packets.\n */\n switch (quantum_type)\n {\n case GrayQuantum:\n case GrayAlphaQuantum:\n {\n channels=1;\n break;\n }\n case CMYKQuantum:\n case CMYKAQuantum:\n {\n channels=4;\n break;\n }\n default:\n {\n channels=3;\n break;\n }\n }\n if (image->matte != MagickFalse)\n channels++;\n extent=channels*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)*\n image->columns;\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowPNMException(ResourceLimitError,\"MemoryAllocationFailed\");\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n const unsigned char\n *pixels;\n\n MagickBooleanType\n sync;\n\n register const unsigned char\n *magick_restrict p;\n\n register ssize_t\n x;\n\n register PixelPacket\n *magick_restrict q;\n\n ssize_t\n count,\n offset;\n\n pixels=(unsigned char *) ReadBlobStream(image,extent,\n GetQuantumPixels(quantum_info),&count);\n if (count != (ssize_t) extent)\n break;\n if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&\n (image->previous == (Image *) NULL))\n {\n MagickBooleanType\n proceed;\n\n proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n row,image->rows);\n if (proceed == MagickFalse)\n break;\n }\n offset=row++;\n q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n p=pixels;\n switch (image->depth)\n {\n case 8:\n case 16:\n case 32:\n {\n (void) ImportQuantumPixels(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 unsigned int\n pixel;\n\n if (image->depth <= 8)\n {\n unsigned char\n pixel;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n p=PushCharPixel(p,&pixel);\n SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));\n SetPixelGreen(q,GetPixelRed(q));\n SetPixelBlue(q,GetPixelRed(q));\n SetPixelOpacity(q,OpaqueOpacity);\n if (image->matte != MagickFalse)\n {\n p=PushCharPixel(p,&pixel);\n if (image->depth != 1)\n SetPixelOpacity(q,ScaleAnyToQuantum(pixel,\n max_value));\n else\n SetPixelOpacity(q,QuantumRange-ScaleAnyToQuantum(\n pixel,max_value));\n }\n q++;\n }\n break;\n }\n if (image->depth <= 16)\n {\n unsigned short\n pixel;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n p=PushShortPixel(MSBEndian,p,&pixel);\n SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));\n SetPixelGreen(q,GetPixelRed(q));\n SetPixelBlue(q,GetPixelRed(q));\n SetPixelOpacity(q,OpaqueOpacity);\n if (image->matte != MagickFalse)\n {\n p=PushShortPixel(MSBEndian,p,&pixel);\n SetPixelOpacity(q,ScaleAnyToQuantum(pixel,\n max_value));\n }\n q++;\n }\n break;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n p=PushLongPixel(MSBEndian,p,&pixel);\n SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));\n SetPixelGreen(q,GetPixelRed(q));\n SetPixelBlue(q,GetPixelRed(q));\n SetPixelOpacity(q,OpaqueOpacity);\n if (image->matte != MagickFalse)\n {\n p=PushLongPixel(MSBEndian,p,&pixel);\n SetPixelOpacity(q,ScaleAnyToQuantum(pixel,max_value));\n }\n q++;\n }\n break;\n }\n case CMYKQuantum:\n case CMYKAQuantum:\n {\n unsigned int\n pixel;\n\n if (image->depth <= 8)\n {\n unsigned char\n pixel;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n p=PushCharPixel(p,&pixel);\n SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));\n p=PushCharPixel(p,&pixel);\n SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));\n p=PushCharPixel(p,&pixel);\n SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));\n p=PushCharPixel(p,&pixel);\n SetPixelIndex(indexes+x,ScaleAnyToQuantum(pixel,\n max_value));\n SetPixelOpacity(q,OpaqueOpacity);\n if (image->matte != MagickFalse)\n {\n p=PushCharPixel(p,&pixel);\n SetPixelOpacity(q,ScaleAnyToQuantum(pixel,\n max_value));\n }\n q++;\n }\n break;\n }\n if (image->depth <= 16)\n {\n unsigned short\n pixel;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n p=PushShortPixel(MSBEndian,p,&pixel);\n SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));\n p=PushShortPixel(MSBEndian,p,&pixel);\n SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));\n p=PushShortPixel(MSBEndian,p,&pixel);\n SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));\n p=PushShortPixel(MSBEndian,p,&pixel);\n SetPixelIndex(indexes+x,ScaleAnyToQuantum(pixel,\n max_value));\n SetPixelOpacity(q,OpaqueOpacity);\n if (image->matte != MagickFalse)\n {\n p=PushShortPixel(MSBEndian,p,&pixel);\n SetPixelOpacity(q,ScaleAnyToQuantum(pixel,\n max_value));\n }\n q++;\n }\n break;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n p=PushLongPixel(MSBEndian,p,&pixel);\n SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));\n p=PushLongPixel(MSBEndian,p,&pixel);\n SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));\n p=PushLongPixel(MSBEndian,p,&pixel);\n SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));\n p=PushLongPixel(MSBEndian,p,&pixel);\n SetPixelIndex(indexes+x,ScaleAnyToQuantum(pixel,max_value));\n SetPixelOpacity(q,OpaqueOpacity);\n if (image->matte != MagickFalse)\n {\n p=PushLongPixel(MSBEndian,p,&pixel);\n SetPixelOpacity(q,ScaleAnyToQuantum(pixel,max_value));\n }\n q++;\n }\n break;\n }\n default:\n {\n unsigned int\n pixel;\n\n if (image->depth <= 8)\n {\n unsigned char\n pixel;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n p=PushCharPixel(p,&pixel);\n SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));\n p=PushCharPixel(p,&pixel);\n SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));\n p=PushCharPixel(p,&pixel);\n SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));\n SetPixelOpacity(q,OpaqueOpacity);\n if (image->matte != MagickFalse)\n {\n p=PushCharPixel(p,&pixel);\n SetPixelOpacity(q,ScaleAnyToQuantum(pixel,\n max_value));\n }\n q++;\n }\n break;\n }\n if (image->depth <= 16)\n {\n unsigned short\n pixel;\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n p=PushShortPixel(MSBEndian,p,&pixel);\n SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));\n p=PushShortPixel(MSBEndian,p,&pixel);\n SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));\n p=PushShortPixel(MSBEndian,p,&pixel);\n SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));\n SetPixelOpacity(q,OpaqueOpacity);\n if (image->matte != MagickFalse)\n {\n p=PushShortPixel(MSBEndian,p,&pixel);\n SetPixelOpacity(q,ScaleAnyToQuantum(pixel,\n max_value));\n }\n q++;\n }\n break;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n p=PushLongPixel(MSBEndian,p,&pixel);\n SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));\n p=PushLongPixel(MSBEndian,p,&pixel);\n SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));\n p=PushLongPixel(MSBEndian,p,&pixel);\n SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));\n SetPixelOpacity(q,OpaqueOpacity);\n if (image->matte != MagickFalse)\n {\n p=PushLongPixel(MSBEndian,p,&pixel);\n SetPixelOpacity(q,ScaleAnyToQuantum(pixel,max_value));\n }\n q++;\n }\n break;\n }\n }\n break;\n }\n }\n sync=SyncAuthenticPixels(image,exception);\n if (sync == MagickFalse)\n break;\n }\n quantum_info=DestroyQuantumInfo(quantum_info);\n SetQuantumImageType(image,quantum_type);\n break;\n }\n case 'F':\n case 'f':\n {\n /*\n Convert PFM raster image to pixel packets.\n */\n if (format == 'f')\n (void) SetImageColorspace(image,GRAYColorspace);\n quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;\n image->endian=quantum_scale < 0.0 ? LSBEndian : MSBEndian;\n image->depth=32;\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowPNMException(ResourceLimitError,\"MemoryAllocationFailed\");\n status=SetQuantumDepth(image,quantum_info,32);\n if (status == MagickFalse)\n ThrowPNMException(ResourceLimitError,\"MemoryAllocationFailed\");\n status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);\n if (status == MagickFalse)\n ThrowPNMException(ResourceLimitError,\"MemoryAllocationFailed\");\n SetQuantumScale(quantum_info,(MagickRealType) QuantumRange*\n fabs(quantum_scale));\n extent=GetQuantumExtent(image,quantum_info,quantum_type);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n const unsigned char\n *pixels;\n\n MagickBooleanType\n sync;\n\n register PixelPacket\n *magick_restrict q;\n\n ssize_t\n count,\n offset;\n\n size_t\n length;\n\n pixels=(unsigned char *) ReadBlobStream(image,extent,\n GetQuantumPixels(quantum_info),&count);\n if ((size_t) count != extent)\n break;\n if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&\n (image->previous == (Image *) NULL))\n {\n MagickBooleanType\n proceed;\n\n proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n row,image->rows);\n if (proceed == MagickFalse)\n break;\n }\n offset=row++;\n q=QueueAuthenticPixels(image,0,(ssize_t) (image->rows-offset-1),\n image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n if (length != extent)\n break;\n sync=SyncAuthenticPixels(image,exception);\n if (sync == MagickFalse)\n break;\n }\n quantum_info=DestroyQuantumInfo(quantum_info);\n SetQuantumImageType(image,quantum_type);\n break;\n }\n default:\n ThrowPNMException(CorruptImageError,\"ImproperImageHeader\");\n }\n if (*comment_info.comment != '\\0')\n (void) SetImageProperty(image,\"comment\",comment_info.comment);\n comment_info.comment=DestroyString(comment_info.comment);\n if (y < (ssize_t) image->rows)\n ThrowPNMException(CorruptImageError,\"UnableToReadImageData\");\n if (EOFBlob(image) != MagickFalse)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n CorruptImageError,\"UnexpectedEndOfFile\",\"`%s'\",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 ((format == '1') || (format == '2') || (format == '3'))\n do\n {\n /*\n Skip to end of line.\n */\n count=ReadBlob(image,1,(unsigned char *) &format);\n if (count != 1)\n break;\n if (format == 'P')\n break;\n } while (format != '\\n');\n count=ReadBlob(image,1,(unsigned char *) &format);\n if ((count == 1) && (format == 'P'))\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 == 1) && (format == 'P'));\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *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 (void) SeekBlob(image,0,SEEK_SET);\n while (EOFBlob(image) == MagickFalse)\n {\n /*\n Object parser.\n */\n ldblk=ReadBlobLSBLong(image);\n if (EOFBlob(image) != MagickFalse)\n break;\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);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n (void) SetImageBackgroundColor(image);\n (void) SetImageColorspace(image,GRAYColorspace);\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 PixelPacket\n *magick_restrict q;\n\n count=ReadBlob(image,depth/8*image->columns,(unsigned 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 == (PixelPacket *) 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(q,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,(unsigned char *) pixels);\n if (count == -1)\n break;\n if (HDR.Type[1] == 0)\n InsertComplexDoubleRow((double *) pixels,y,image,0,0);\n else\n InsertComplexFloatRow((float *) pixels,y,image,0,0);\n }\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);\n if (GetNextImageInList(image) == (Image *) NULL)\n return(DestroyImageList(image));\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 return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: g_vfs_daemon_finalize (GObject *object)\n{\n GVfsDaemon *daemon;\n\n daemon = G_VFS_DAEMON (object);\n\n /* There may be some jobs outstanding if we've been force unmounted. */\n if (daemon->jobs)\n g_warning (\"daemon->jobs != NULL when finalizing daemon!\");\n\n if (daemon->name_watcher)\n g_bus_unwatch_name (daemon->name_watcher);\n \n if (daemon->daemon_skeleton != NULL)\n {\n g_dbus_interface_skeleton_unexport (G_DBUS_INTERFACE_SKELETON (daemon->daemon_skeleton));\n g_object_unref (daemon->daemon_skeleton);\n }\n if (daemon->mountable_skeleton != NULL)\n {\n g_dbus_interface_skeleton_unexport (G_DBUS_INTERFACE_SKELETON (daemon->mountable_skeleton));\n g_object_unref (daemon->mountable_skeleton);\n }\n if (daemon->conn != NULL)\n g_object_unref (daemon->conn);\n \n g_hash_table_destroy (daemon->registered_paths);\n g_hash_table_destroy (daemon->client_connections);\n g_mutex_clear (&daemon->lock);\n\n if (G_OBJECT_CLASS (g_vfs_daemon_parent_class)->finalize)\n (*G_OBJECT_CLASS (g_vfs_daemon_parent_class)->finalize) (object);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-276'], 'message': 'gvfsdaemon: Check that the connecting client is the same user\n\nOtherwise, an attacker who learns the abstract socket address from\nnetstat(8) or similar could connect to it and issue D-Bus method\ncalls.\n\nSigned-off-by: Simon McVittie '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void undefer_input(__G)\n __GDEF\n{\n if (G.incnt > 0)\n G.csize += G.incnt;\n if (G.incnt_leftover > 0) {\n /* We know that \"(G.csize < MAXINT)\" so we can cast G.csize to int:\n * This condition was checked when G.incnt_leftover was set > 0 in\n * defer_leftover_input(), and it is NOT allowed to touch G.csize\n * before calling undefer_input() when (G.incnt_leftover > 0)\n * (single exception: see read_byte()'s \"G.csize <= 0\" handling) !!\n */\n G.incnt = G.incnt_leftover + (int)G.csize;\n G.inptr = G.inptr_leftover - (int)G.csize;\n G.incnt_leftover = 0;\n } else if (G.incnt < 0)\n G.incnt = 0;\n} /* end function undefer_input() */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'Fix bug in undefer_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_security_cfm(struct hci_conn *hcon, u8 status, u8 encrypt)\n{\n\tstruct l2cap_conn *conn = hcon->l2cap_data;\n\tstruct l2cap_chan *chan;\n\n\tif (!conn)\n\t\treturn;\n\n\tBT_DBG(\"conn %p status 0x%2.2x encrypt %u\", conn, status, encrypt);\n\n\tmutex_lock(&conn->chan_lock);\n\n\tlist_for_each_entry(chan, &conn->chan_l, list) {\n\t\tl2cap_chan_lock(chan);\n\n\t\tBT_DBG(\"chan %p scid 0x%4.4x state %s\", chan, chan->scid,\n\t\t state_to_string(chan->state));\n\n\t\tif (chan->scid == L2CAP_CID_A2MP) {\n\t\t\tl2cap_chan_unlock(chan);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!status && encrypt)\n\t\t\tchan->sec_level = hcon->sec_level;\n\n\t\tif (!__l2cap_no_conn_pending(chan)) {\n\t\t\tl2cap_chan_unlock(chan);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!status && (chan->state == BT_CONNECTED ||\n\t\t\t\tchan->state == BT_CONFIG)) {\n\t\t\tchan->ops->resume(chan);\n\t\t\tl2cap_check_encryption(chan, encrypt);\n\t\t\tl2cap_chan_unlock(chan);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (chan->state == BT_CONNECT) {\n\t\t\tif (!status)\n\t\t\t\tl2cap_start_connection(chan);\n\t\t\telse\n\t\t\t\t__set_chan_timer(chan, L2CAP_DISC_TIMEOUT);\n\t\t} else if (chan->state == BT_CONNECT2 &&\n\t\t\t chan->mode != L2CAP_MODE_LE_FLOWCTL) {\n\t\t\tstruct l2cap_conn_rsp rsp;\n\t\t\t__u16 res, stat;\n\n\t\t\tif (!status) {\n\t\t\t\tif (test_bit(FLAG_DEFER_SETUP, &chan->flags)) {\n\t\t\t\t\tres = L2CAP_CR_PEND;\n\t\t\t\t\tstat = L2CAP_CS_AUTHOR_PEND;\n\t\t\t\t\tchan->ops->defer(chan);\n\t\t\t\t} else {\n\t\t\t\t\tl2cap_state_change(chan, BT_CONFIG);\n\t\t\t\t\tres = L2CAP_CR_SUCCESS;\n\t\t\t\t\tstat = L2CAP_CS_NO_INFO;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tl2cap_state_change(chan, BT_DISCONN);\n\t\t\t\t__set_chan_timer(chan, L2CAP_DISC_TIMEOUT);\n\t\t\t\tres = L2CAP_CR_SEC_BLOCK;\n\t\t\t\tstat = L2CAP_CS_NO_INFO;\n\t\t\t}\n\n\t\t\trsp.scid = cpu_to_le16(chan->dcid);\n\t\t\trsp.dcid = cpu_to_le16(chan->scid);\n\t\t\trsp.result = cpu_to_le16(res);\n\t\t\trsp.status = cpu_to_le16(stat);\n\t\t\tl2cap_send_cmd(conn, chan->ident, L2CAP_CONN_RSP,\n\t\t\t\t sizeof(rsp), &rsp);\n\n\t\t\tif (!test_bit(CONF_REQ_SENT, &chan->conf_state) &&\n\t\t\t res == L2CAP_CR_SUCCESS) {\n\t\t\t\tchar buf[128];\n\t\t\t\tset_bit(CONF_REQ_SENT, &chan->conf_state);\n\t\t\t\tl2cap_send_cmd(conn, l2cap_get_ident(conn),\n\t\t\t\t\t L2CAP_CONF_REQ,\n\t\t\t\t\t l2cap_build_conf_req(chan, buf, sizeof(buf)),\n\t\t\t\t\t buf);\n\t\t\t\tchan->num_conf_req++;\n\t\t\t}\n\t\t}\n\n\t\tl2cap_chan_unlock(chan);\n\t}\n\n\tmutex_unlock(&conn->chan_lock);\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::UniquePtr m;\n switch (CiffComponent::typeId(tag)) {\n case directory: m = CiffComponent::UniquePtr(new CiffDirectory); break;\n default: m = CiffComponent::UniquePtr(new CiffEntry); break;\n }\n m->setDir(this->tag());\n m->read(pData, size, o, byteOrder);\n add(std::move(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.\n\n(cherry picked from commit c0ecc2ae36f34462be98623deb85ba1747ae2175)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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_pcrl(opj_pi_iterator_t * pi)\n{\n opj_pi_comp_t *comp = NULL;\n opj_pi_resolution_t *res = NULL;\n long index = 0;\n\n if (!pi->first) {\n comp = &pi->comps[pi->compno];\n goto LABEL_SKIP;\n } else {\n 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->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 comp = &pi->comps[pi->compno];\n for (pi->resno = pi->poc.resno0;\n pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {\n int levelno;\n int trx0, try0;\n int trx1, try1;\n int rpx, rpy;\n int prci, prcj;\n res = &comp->resolutions[pi->resno];\n levelno = comp->numresolutions - 1 - pi->resno;\n trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);\n try0 = int_ceildiv(pi->ty0, comp->dy << levelno);\n trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);\n try1 = int_ceildiv(pi->ty1, comp->dy << levelno);\n rpx = res->pdx + levelno;\n rpy = res->pdy + levelno;\n 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: 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\n /* To avoid divisions by zero / undefined behaviour on shift */\n if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx ||\n rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) {\n continue;\n }\n\n if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&\n ((try0 << levelno) % (1 << rpy))))) {\n continue;\n }\n if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&\n ((trx0 << levelno) % (1 << rpx))))) {\n continue;\n }\n\n if ((res->pw == 0) || (res->ph == 0)) {\n continue;\n }\n\n if ((trx0 == trx1) || (try0 == try1)) {\n continue;\n }\n\n prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)\n - int_floordivpow2(trx0, res->pdx);\n prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)\n - int_floordivpow2(try0, res->pdy);\n pi->precno = prci + prcj * res->pw;\n for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {\n index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *\n pi->step_c + pi->precno * pi->step_p;\n /* Avoids index out of bounds access with include*/\n if (index >= pi->include_size) {\n opj_pi_emit_error(pi, \"Invalid access to pi->include\");\n return OPJ_FALSE;\n }\n if (!pi->include[index]) {\n pi->include[index] = 1;\n return OPJ_TRUE;\n }\nLABEL_SKIP:\n ;\n }\n }\n }\n }\n }\n\n return OPJ_FALSE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Revert \"[MJ2] Avoid index out of bounds access to pi->include[]\"\n\nThis reverts commit c277159986c80142180fbe5efb256bbf3bdf3edc.\n\nThe commit didn't compile. include_size is not defined in openmj2'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env)\n{\n int r, len;\n\n switch (node->type) {\n case BAG_MEMORY:\n r = compile_bag_memory_node(node, reg, env);\n break;\n\n case BAG_OPTION:\n r = compile_option_node(node, reg, env);\n break;\n\n case BAG_STOP_BACKTRACK:\n if (NODE_IS_STOP_BT_SIMPLE_REPEAT(node)) {\n QuantNode* qn = QUANT_(NODE_BAG_BODY(node));\n r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env);\n if (r != 0) return r;\n\n len = compile_length_tree(NODE_QUANT_BODY(qn), reg);\n if (len < 0) return len;\n\n r = add_op(reg, OP_PUSH);\n if (r != 0) return r;\n COP(reg)->push.addr = SIZE_INC_OP + len + SIZE_OP_POP_OUT + SIZE_OP_JUMP;\n\n r = compile_tree(NODE_QUANT_BODY(qn), reg, env);\n if (r != 0) return r;\n r = add_op(reg, OP_POP_OUT);\n if (r != 0) return r;\n\n r = add_op(reg, OP_JUMP);\n if (r != 0) return r;\n COP(reg)->jump.addr = -((int )SIZE_OP_PUSH + len + (int )SIZE_OP_POP_OUT);\n }\n else {\n r = add_op(reg, OP_ATOMIC_START);\n if (r != 0) return r;\n r = compile_tree(NODE_BAG_BODY(node), reg, env);\n if (r != 0) return r;\n r = add_op(reg, OP_ATOMIC_END);\n }\n break;\n\n case BAG_IF_ELSE:\n {\n int cond_len, then_len, jump_len;\n Node* cond = NODE_BAG_BODY(node);\n Node* Then = node->te.Then;\n Node* Else = node->te.Else;\n\n r = add_op(reg, OP_ATOMIC_START);\n if (r != 0) return r;\n\n cond_len = compile_length_tree(cond, reg);\n if (cond_len < 0) return cond_len;\n if (IS_NOT_NULL(Then)) {\n then_len = compile_length_tree(Then, reg);\n if (then_len < 0) return then_len;\n }\n else\n then_len = 0;\n\n jump_len = cond_len + then_len + SIZE_OP_ATOMIC_END;\n if (IS_NOT_NULL(Else)) jump_len += SIZE_OP_JUMP;\n\n r = add_op(reg, OP_PUSH);\n if (r != 0) return r;\n COP(reg)->push.addr = SIZE_INC_OP + jump_len;\n\n r = compile_tree(cond, reg, env);\n if (r != 0) return r;\n r = add_op(reg, OP_ATOMIC_END);\n if (r != 0) return r;\n\n if (IS_NOT_NULL(Then)) {\n r = compile_tree(Then, reg, env);\n if (r != 0) return r;\n }\n\n if (IS_NOT_NULL(Else)) {\n int else_len = compile_length_tree(Else, reg);\n r = add_op(reg, OP_JUMP);\n if (r != 0) return r;\n COP(reg)->jump.addr = else_len + SIZE_INC_OP;\n\n r = compile_tree(Else, reg, env);\n }\n }\n break;\n }\n\n return r;\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: WandPrivate MagickBooleanType CLIListOperatorImages(MagickCLI *cli_wand,\n const char *option,const char *arg1n,const char *arg2n)\n{\n const char /* percent escaped versions of the args */\n *arg1,\n *arg2;\n\n Image\n *new_images;\n\n MagickStatusType\n status;\n\n ssize_t\n parse;\n\n#define _image_info (cli_wand->wand.image_info)\n#define _images (cli_wand->wand.images)\n#define _exception (cli_wand->wand.exception)\n#define _draw_info (cli_wand->draw_info)\n#define _quantize_info (cli_wand->quantize_info)\n#define _process_flags (cli_wand->process_flags)\n#define _option_type ((CommandOptionFlags) cli_wand->command->flags)\n#define IfNormalOp (*option=='-')\n#define IfPlusOp (*option!='-')\n#define IsNormalOp IfNormalOp ? MagickTrue : MagickFalse\n\n assert(cli_wand != (MagickCLI *) NULL);\n assert(cli_wand->signature == MagickWandSignature);\n assert(cli_wand->wand.signature == MagickWandSignature);\n assert(_images != (Image *) NULL); /* _images must be present */\n\n if (cli_wand->wand.debug != MagickFalse)\n (void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(),\n \"- List Operator: %s \\\"%s\\\" \\\"%s\\\"\", option,\n arg1n == (const char *) NULL ? \"null\" : arg1n,\n arg2n == (const char *) NULL ? \"null\" : arg2n);\n\n arg1 = arg1n;\n arg2 = arg2n;\n\n /* Interpret Percent Escapes in Arguments - using first image */\n if ( (((_process_flags & ProcessInterpretProperities) != 0 )\n || ((_option_type & AlwaysInterpretArgsFlag) != 0)\n ) && ((_option_type & NeverInterpretArgsFlag) == 0) ) {\n /* Interpret Percent escapes in argument 1 */\n if (arg1n != (char *) NULL) {\n arg1=InterpretImageProperties(_image_info,_images,arg1n,_exception);\n if (arg1 == (char *) NULL) {\n CLIWandException(OptionWarning,\"InterpretPropertyFailure\",option);\n arg1=arg1n; /* use the given argument as is */\n }\n }\n if (arg2n != (char *) NULL) {\n arg2=InterpretImageProperties(_image_info,_images,arg2n,_exception);\n if (arg2 == (char *) NULL) {\n CLIWandException(OptionWarning,\"InterpretPropertyFailure\",option);\n arg2=arg2n; /* use the given argument as is */\n }\n }\n }\n#undef _process_flags\n#undef _option_type\n\n status=MagickTrue;\n new_images=NewImageList();\n\n switch (*(option+1))\n {\n case 'a':\n {\n if (LocaleCompare(\"append\",option+1) == 0)\n {\n new_images=AppendImages(_images,IsNormalOp,_exception);\n break;\n }\n if (LocaleCompare(\"average\",option+1) == 0)\n {\n CLIWandWarnReplaced(\"-evaluate-sequence Mean\");\n (void) CLIListOperatorImages(cli_wand,\"-evaluate-sequence\",\"Mean\",\n NULL);\n break;\n }\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n case 'c':\n {\n if (LocaleCompare(\"channel-fx\",option+1) == 0)\n {\n new_images=ChannelFxImage(_images,arg1,_exception);\n break;\n }\n if (LocaleCompare(\"clut\",option+1) == 0)\n {\n Image\n *clut_image;\n\n /* FUTURE - make this a compose option, and thus can be used\n with layers compose or even compose last image over all other\n _images.\n */\n new_images=RemoveFirstImageFromList(&_images);\n clut_image=RemoveLastImageFromList(&_images);\n /* FUTURE - produce Exception, rather than silent fail */\n if (clut_image == (Image *) NULL)\n break;\n (void) ClutImage(new_images,clut_image,new_images->interpolate,\n _exception);\n clut_image=DestroyImage(clut_image);\n break;\n }\n if (LocaleCompare(\"coalesce\",option+1) == 0)\n {\n new_images=CoalesceImages(_images,_exception);\n break;\n }\n if (LocaleCompare(\"combine\",option+1) == 0)\n {\n parse=(ssize_t) _images->colorspace;\n if (_images->number_channels < GetImageListLength(_images))\n parse=sRGBColorspace;\n if ( IfPlusOp )\n parse=ParseCommandOption(MagickColorspaceOptions,MagickFalse,arg1);\n if (parse < 0)\n CLIWandExceptArgBreak(OptionError,\"UnrecognizedColorspace\",option,\n arg1);\n new_images=CombineImages(_images,(ColorspaceType) parse,_exception);\n break;\n }\n if (LocaleCompare(\"compare\",option+1) == 0)\n {\n double\n distortion;\n\n 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 image=RemoveFirstImageFromList(&_images);\n reconstruct_image=RemoveFirstImageFromList(&_images);\n /* FUTURE - produce Exception, rather than silent fail */\n if (reconstruct_image == (Image *) NULL)\n { \n image=DestroyImage(image);\n break;\n }\n metric=UndefinedErrorMetric;\n option=GetImageOption(_image_info,\"metric\");\n if (option != (const char *) NULL)\n metric=(MetricType) ParseCommandOption(MagickMetricOptions,\n MagickFalse,option);\n new_images=CompareImages(image,reconstruct_image,metric,&distortion,\n _exception);\n (void) distortion;\n reconstruct_image=DestroyImage(reconstruct_image);\n image=DestroyImage(image);\n break;\n }\n if (LocaleCompare(\"complex\",option+1) == 0)\n {\n parse=ParseCommandOption(MagickComplexOptions,MagickFalse,arg1);\n if (parse < 0)\n CLIWandExceptArgBreak(OptionError,\"UnrecognizedEvaluateOperator\",\n option,arg1);\n new_images=ComplexImages(_images,(ComplexOperator) parse,_exception);\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 *source_image;\n\n RectangleInfo\n geometry;\n\n /* Compose value from \"-compose\" option only */\n value=GetImageOption(_image_info,\"compose\");\n if (value == (const char *) NULL)\n compose=OverCompositeOp; /* use Over not source_image->compose */\n else\n compose=(CompositeOperator) ParseCommandOption(MagickComposeOptions,\n MagickFalse,value);\n\n /* Get \"clip-to-self\" expert setting (false is normal) */\n clip_to_self=GetCompositeClipToSelf(compose);\n value=GetImageOption(_image_info,\"compose:clip-to-self\");\n if (value != (const char *) NULL)\n clip_to_self=IsStringTrue(value);\n value=GetImageOption(_image_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,clip_to_self,\n 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,OverCompositeOp,\n 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 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 if (IsGeometry(arg1) == MagickFalse)\n CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1);\n if (IsGeometry(arg2) == MagickFalse)\n CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1);\n (void) ParsePageGeometry(_images,arg2,&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,arg1,&geometry,_exception);\n (void) CopyImagePixels(_images,source_image,&geometry,&offset,\n _exception);\n break;\n }\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n case 'd':\n {\n if (LocaleCompare(\"deconstruct\",option+1) == 0)\n {\n CLIWandWarnReplaced(\"-layer CompareAny\");\n (void) CLIListOperatorImages(cli_wand,\"-layer\",\"CompareAny\",NULL);\n break;\n }\n if (LocaleCompare(\"delete\",option+1) == 0)\n {\n if (IfNormalOp)\n DeleteImages(&_images,arg1,_exception);\n else\n DeleteImages(&_images,\"-1\",_exception);\n break;\n }\n if (LocaleCompare(\"duplicate\",option+1) == 0)\n {\n if (IfNormalOp)\n {\n const char\n *p;\n\n size_t\n number_duplicates;\n\n if (IsGeometry(arg1) == MagickFalse)\n CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,\n arg1);\n number_duplicates=(size_t) StringToLong(arg1);\n p=strchr(arg1,',');\n if (p == (const char *) NULL)\n new_images=DuplicateImages(_images,number_duplicates,\"-1\",\n _exception);\n else\n new_images=DuplicateImages(_images,number_duplicates,p,\n _exception);\n }\n else\n new_images=DuplicateImages(_images,1,\"-1\",_exception);\n AppendImageToList(&_images, new_images);\n new_images=(Image *) NULL;\n break;\n }\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n case 'e':\n {\n if (LocaleCompare(\"evaluate-sequence\",option+1) == 0)\n {\n parse=ParseCommandOption(MagickEvaluateOptions,MagickFalse,arg1);\n if (parse < 0)\n CLIWandExceptArgBreak(OptionError,\"UnrecognizedEvaluateOperator\",\n option,arg1);\n new_images=EvaluateImages(_images,(MagickEvaluateOperator) parse,\n _exception);\n break;\n }\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n case 'f':\n {\n if (LocaleCompare(\"fft\",option+1) == 0)\n {\n new_images=ForwardFourierTransformImage(_images,IsNormalOp,\n _exception);\n break;\n }\n if (LocaleCompare(\"flatten\",option+1) == 0)\n {\n /* REDIRECTED to use -layers flatten instead */\n (void) CLIListOperatorImages(cli_wand,\"-layers\",option+1,NULL);\n break;\n }\n if (LocaleCompare(\"fx\",option+1) == 0)\n {\n new_images=FxImage(_images,arg1,_exception);\n break;\n }\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n case 'h':\n {\n if (LocaleCompare(\"hald-clut\",option+1) == 0)\n {\n /* FUTURE - make this a compose option (and thus layers compose )\n or perhaps compose last image over all other _images.\n */\n Image\n *hald_image;\n\n new_images=RemoveFirstImageFromList(&_images);\n hald_image=RemoveLastImageFromList(&_images);\n if (hald_image == (Image *) NULL)\n break;\n (void) HaldClutImage(new_images,hald_image,_exception);\n hald_image=DestroyImage(hald_image);\n break;\n }\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n case 'i':\n {\n if (LocaleCompare(\"ift\",option+1) == 0)\n {\n Image\n *magnitude_image,\n *phase_image;\n\n magnitude_image=RemoveFirstImageFromList(&_images);\n phase_image=RemoveFirstImageFromList(&_images);\n /* FUTURE - produce Exception, rather than silent fail */\n if (phase_image == (Image *) NULL)\n break;\n new_images=InverseFourierTransformImage(magnitude_image,phase_image,\n IsNormalOp,_exception);\n magnitude_image=DestroyImage(magnitude_image);\n phase_image=DestroyImage(phase_image);\n break;\n }\n if (LocaleCompare(\"insert\",option+1) == 0)\n {\n Image\n *insert_image,\n *index_image;\n\n ssize_t\n index;\n\n if (IfNormalOp && (IsGeometry(arg1) == MagickFalse))\n CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1);\n index=0;\n insert_image=RemoveLastImageFromList(&_images);\n if (IfNormalOp)\n index=(ssize_t) StringToLong(arg1);\n index_image=insert_image;\n if (index == 0)\n PrependImageToList(&_images,insert_image);\n else if (index == (ssize_t) GetImageListLength(_images))\n AppendImageToList(&_images,insert_image);\n else\n {\n index_image=GetImageFromList(_images,index-1);\n if (index_image == (Image *) NULL)\n CLIWandExceptArgBreak(OptionError,\"NoSuchImage\",option,arg1);\n InsertImageInList(&index_image,insert_image);\n }\n _images=GetFirstImageInList(index_image);\n break;\n }\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n case 'l':\n {\n if (LocaleCompare(\"layers\",option+1) == 0)\n {\n parse=ParseCommandOption(MagickLayerOptions,MagickFalse,arg1);\n if ( parse < 0 )\n CLIWandExceptArgBreak(OptionError,\"UnrecognizedLayerMethod\",\n option,arg1);\n switch ((LayerMethod) parse)\n {\n case CoalesceLayer:\n {\n new_images=CoalesceImages(_images,_exception);\n break;\n }\n case CompareAnyLayer:\n case CompareClearLayer:\n case CompareOverlayLayer:\n default:\n {\n new_images=CompareImagesLayers(_images,(LayerMethod) parse,\n _exception);\n break;\n }\n case MergeLayer:\n case FlattenLayer:\n case MosaicLayer:\n case TrimBoundsLayer:\n {\n new_images=MergeImageLayers(_images,(LayerMethod) parse,\n _exception);\n break;\n }\n case DisposeLayer:\n {\n new_images=DisposeImages(_images,_exception);\n break;\n }\n case OptimizeImageLayer:\n {\n new_images=OptimizeImageLayers(_images,_exception);\n break;\n }\n case OptimizePlusLayer:\n {\n new_images=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 { /* General Purpose, GIF Animation Optimizer. */\n new_images=CoalesceImages(_images,_exception);\n if (new_images == (Image *) NULL)\n break;\n _images=DestroyImageList(_images);\n _images=OptimizeImageLayers(new_images,_exception);\n if (_images == (Image *) NULL)\n break;\n new_images=DestroyImageList(new_images);\n OptimizeImageTransparency(_images,_exception);\n (void) RemapImages(_quantize_info,_images,(Image *) NULL,\n _exception);\n break;\n }\n case CompositeLayer:\n {\n Image\n *source;\n\n RectangleInfo\n geometry;\n\n CompositeOperator\n compose;\n\n const char*\n value;\n\n value=GetImageOption(_image_info,\"compose\");\n compose=OverCompositeOp; /* Default to Over */\n if (value != (const char *) NULL)\n compose=(CompositeOperator) ParseCommandOption(\n MagickComposeOptions,MagickFalse,value);\n\n /* Split image sequence at the first 'NULL:' image. */\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 { /* Separate the two lists, junk the null: image. */\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 break;\n }\n /* Adjust offset with gravity and virtual canvas. */\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\n /* Compose the two image sequences together */\n CompositeLayers(_images,compose,source,geometry.x,geometry.y,\n _exception);\n source=DestroyImageList(source);\n break;\n }\n }\n break;\n }\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n case 'm':\n {\n if (LocaleCompare(\"map\",option+1) == 0)\n {\n CLIWandWarnReplaced(\"+remap\");\n (void) RemapImages(_quantize_info,_images,(Image *) NULL,_exception);\n break;\n }\n if (LocaleCompare(\"metric\",option+1) == 0)\n {\n (void) SetImageOption(_image_info,option+1,arg1);\n break;\n }\n if (LocaleCompare(\"morph\",option+1) == 0)\n {\n Image\n *morph_image;\n\n if (IsGeometry(arg1) == MagickFalse)\n CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1);\n morph_image=MorphImages(_images,StringToUnsignedLong(arg1),\n _exception);\n if (morph_image == (Image *) NULL)\n break;\n _images=DestroyImageList(_images);\n _images=morph_image;\n break;\n }\n if (LocaleCompare(\"mosaic\",option+1) == 0)\n {\n /* REDIRECTED to use -layers mosaic instead */\n (void) CLIListOperatorImages(cli_wand,\"-layers\",option+1,NULL);\n break;\n }\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n case 'p':\n {\n if (LocaleCompare(\"poly\",option+1) == 0)\n {\n double\n *args;\n\n ssize_t\n count;\n\n /* convert argument string into an array of doubles */\n args = StringToArrayOfDoubles(arg1,&count,_exception);\n if (args == (double *) NULL )\n CLIWandExceptArgBreak(OptionError,\"InvalidNumberList\",option,arg1);\n new_images=PolynomialImage(_images,(size_t) (count >> 1),args,\n _exception);\n args=(double *) RelinquishMagickMemory(args);\n break;\n }\n if (LocaleCompare(\"process\",option+1) == 0)\n {\n /* FUTURE: better parsing using ScriptToken() from string ??? */\n char\n **arguments;\n\n int\n j,\n number_arguments;\n\n arguments=StringToArgv(arg1,&number_arguments);\n if (arguments == (char **) NULL)\n break;\n if (strchr(arguments[1],'=') != (char *) NULL)\n {\n char\n breaker,\n quote,\n *token;\n\n const char\n *arguments;\n\n int\n next,\n status;\n\n size_t\n length;\n\n TokenInfo\n *token_info;\n\n /*\n Support old style syntax, filter=\"-option arg1\".\n */\n assert(arg1 != (const char *) NULL);\n length=strlen(arg1);\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 arguments=arg1;\n token_info=AcquireTokenInfo();\n status=Tokenizer(token_info,0,token,length,arguments,\"\",\"=\",\n \"\\\"\",'\\0',&breaker,&next,"e);\n token_info=DestroyTokenInfo(token_info);\n if (status == 0)\n {\n const char\n *argv;\n\n argv=(&(arguments[next]));\n (void) InvokeDynamicImageFilter(token,&_images,1,&argv,\n _exception);\n }\n token=DestroyString(token);\n break;\n }\n (void) SubstituteString(&arguments[1],\"-\",\"\");\n (void) InvokeDynamicImageFilter(arguments[1],&_images,\n number_arguments-2,(const char **) arguments+2,_exception);\n for (j=0; j < number_arguments; j++)\n arguments[j]=DestroyString(arguments[j]);\n arguments=(char **) RelinquishMagickMemory(arguments);\n break;\n }\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n case 'r':\n {\n if (LocaleCompare(\"remap\",option+1) == 0)\n {\n (void) RemapImages(_quantize_info,_images,(Image *) NULL,_exception);\n break;\n }\n if (LocaleCompare(\"reverse\",option+1) == 0)\n {\n ReverseImageList(&_images);\n break;\n }\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n case 's':\n {\n if (LocaleCompare(\"smush\",option+1) == 0)\n {\n /* FUTURE: this option needs more work to make better */\n ssize_t\n offset;\n\n if (IsGeometry(arg1) == MagickFalse)\n CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1);\n offset=(ssize_t) StringToLong(arg1);\n new_images=SmushImages(_images,IsNormalOp,offset,_exception);\n break;\n }\n if (LocaleCompare(\"subimage\",option+1) == 0)\n {\n Image\n *base_image,\n *compare_image;\n\n const char\n *value;\n\n MetricType\n metric;\n\n double\n similarity;\n\n RectangleInfo\n offset;\n\n base_image=GetImageFromList(_images,0);\n compare_image=GetImageFromList(_images,1);\n\n /* Comparision Metric */\n metric=UndefinedErrorMetric;\n value=GetImageOption(_image_info,\"metric\");\n if (value != (const char *) NULL)\n metric=(MetricType) ParseCommandOption(MagickMetricOptions,\n MagickFalse,value);\n\n new_images=SimilarityImage(base_image,compare_image,metric,0.0,\n &offset,&similarity,_exception);\n\n if (new_images != (Image *) NULL)\n {\n char\n result[MagickPathExtent];\n\n (void) FormatLocaleString(result,MagickPathExtent,\"%lf\",\n similarity);\n (void) SetImageProperty(new_images,\"subimage:similarity\",result,\n _exception);\n (void) FormatLocaleString(result,MagickPathExtent,\"%+ld\",(long)\n offset.x);\n (void) SetImageProperty(new_images,\"subimage:x\",result,\n _exception);\n (void) FormatLocaleString(result,MagickPathExtent,\"%+ld\",(long)\n offset.y);\n (void) SetImageProperty(new_images,\"subimage:y\",result,\n _exception);\n (void) FormatLocaleString(result,MagickPathExtent,\n \"%lux%lu%+ld%+ld\",(unsigned long) offset.width,(unsigned long)\n offset.height,(long) offset.x,(long) offset.y);\n (void) SetImageProperty(new_images,\"subimage:offset\",result,\n _exception);\n }\n break;\n }\n if (LocaleCompare(\"swap\",option+1) == 0)\n {\n Image\n *p,\n *q,\n *swap;\n\n ssize_t\n index,\n swap_index;\n\n index=(-1);\n swap_index=(-2);\n if (IfNormalOp) {\n GeometryInfo\n geometry_info;\n\n MagickStatusType\n flags;\n\n swap_index=(-1);\n flags=ParseGeometry(arg1,&geometry_info);\n if ((flags & RhoValue) == 0)\n CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1);\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 if (IfNormalOp)\n CLIWandExceptArgBreak(OptionError,\"InvalidImageIndex\",option,arg1)\n else\n CLIWandExceptionBreak(OptionError,\"TwoOrMoreImagesRequired\",option);\n }\n if (p == q)\n CLIWandExceptArgBreak(OptionError,\"InvalidImageIndex\",option,arg1);\n swap=CloneImage(p,0,0,MagickTrue,_exception);\n if (swap == (Image *) NULL)\n CLIWandExceptArgBreak(ResourceLimitError,\"MemoryAllocationFailed\",\n option,GetExceptionMessage(errno));\n ReplaceImageInList(&p,CloneImage(q,0,0,MagickTrue,_exception));\n ReplaceImageInList(&q,swap);\n _images=GetFirstImageInList(q);\n break;\n }\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n default:\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n\n /* clean up percent escape interpreted strings */\n if (arg1 != arg1n )\n arg1=DestroyString((char *)arg1);\n if (arg2 != arg2n )\n arg2=DestroyString((char *)arg2);\n\n /* if new image list generated, replace existing image list */\n if (new_images == (Image *) NULL)\n return(status == 0 ? MagickFalse : MagickTrue);\n _images=DestroyImageList(_images);\n _images=GetFirstImageInList(new_images);\n return(status == 0 ? MagickFalse : MagickTrue);\n\n#undef _image_info\n#undef _images\n#undef _exception\n#undef _draw_info\n#undef _quantize_info\n#undef IfNormalOp\n#undef IfPlusOp\n#undef IsNormalOp\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+1) >= 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+1) >= 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/1612'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static MagickPixelPacket **AcquirePixelThreadSet(const Image *image)\n{\n MagickPixelPacket\n **pixels;\n\n register ssize_t\n i,\n j;\n\n size_t\n number_threads;\n\n number_threads=(size_t) GetMagickResourceLimit(ThreadResource);\n pixels=(MagickPixelPacket **) AcquireQuantumMemory(number_threads,\n sizeof(*pixels));\n if (pixels == (MagickPixelPacket **) NULL)\n return((MagickPixelPacket **) NULL);\n (void) memset(pixels,0,number_threads*sizeof(*pixels));\n for (i=0; i < (ssize_t) number_threads; i++)\n {\n pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(image->columns,\n sizeof(**pixels));\n if (pixels[i] == (MagickPixelPacket *) NULL)\n return(DestroyPixelThreadSet(pixels));\n for (j=0; j < (ssize_t) image->columns; j++)\n GetMagickPixelPacket(image,&pixels[i][j]);\n }\n return(pixels);\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/1586'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: WandPrivate MagickBooleanType CLIListOperatorImages(MagickCLI *cli_wand,\n const char *option,const char *arg1n,const char *arg2n)\n{\n const char /* percent escaped versions of the args */\n *arg1,\n *arg2;\n\n Image\n *new_images;\n\n MagickStatusType\n status;\n\n ssize_t\n parse;\n\n#define _image_info (cli_wand->wand.image_info)\n#define _images (cli_wand->wand.images)\n#define _exception (cli_wand->wand.exception)\n#define _draw_info (cli_wand->draw_info)\n#define _quantize_info (cli_wand->quantize_info)\n#define _process_flags (cli_wand->process_flags)\n#define _option_type ((CommandOptionFlags) cli_wand->command->flags)\n#define IfNormalOp (*option=='-')\n#define IfPlusOp (*option!='-')\n#define IsNormalOp IfNormalOp ? MagickTrue : MagickFalse\n\n assert(cli_wand != (MagickCLI *) NULL);\n assert(cli_wand->signature == MagickWandSignature);\n assert(cli_wand->wand.signature == MagickWandSignature);\n assert(_images != (Image *) NULL); /* _images must be present */\n\n if (cli_wand->wand.debug != MagickFalse)\n (void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(),\n \"- List Operator: %s \\\"%s\\\" \\\"%s\\\"\", option,\n arg1n == (const char *) NULL ? \"null\" : arg1n,\n arg2n == (const char *) NULL ? \"null\" : arg2n);\n\n arg1 = arg1n;\n arg2 = arg2n;\n\n /* Interpret Percent Escapes in Arguments - using first image */\n if ( (((_process_flags & ProcessInterpretProperities) != 0 )\n || ((_option_type & AlwaysInterpretArgsFlag) != 0)\n ) && ((_option_type & NeverInterpretArgsFlag) == 0) ) {\n /* Interpret Percent escapes in argument 1 */\n if (arg1n != (char *) NULL) {\n arg1=InterpretImageProperties(_image_info,_images,arg1n,_exception);\n if (arg1 == (char *) NULL) {\n CLIWandException(OptionWarning,\"InterpretPropertyFailure\",option);\n arg1=arg1n; /* use the given argument as is */\n }\n }\n if (arg2n != (char *) NULL) {\n arg2=InterpretImageProperties(_image_info,_images,arg2n,_exception);\n if (arg2 == (char *) NULL) {\n CLIWandException(OptionWarning,\"InterpretPropertyFailure\",option);\n arg2=arg2n; /* use the given argument as is */\n }\n }\n }\n#undef _process_flags\n#undef _option_type\n\n status=MagickTrue;\n new_images=NewImageList();\n\n switch (*(option+1))\n {\n case 'a':\n {\n if (LocaleCompare(\"append\",option+1) == 0)\n {\n new_images=AppendImages(_images,IsNormalOp,_exception);\n break;\n }\n if (LocaleCompare(\"average\",option+1) == 0)\n {\n CLIWandWarnReplaced(\"-evaluate-sequence Mean\");\n (void) CLIListOperatorImages(cli_wand,\"-evaluate-sequence\",\"Mean\",\n NULL);\n break;\n }\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n case 'c':\n {\n if (LocaleCompare(\"channel-fx\",option+1) == 0)\n {\n new_images=ChannelFxImage(_images,arg1,_exception);\n break;\n }\n if (LocaleCompare(\"clut\",option+1) == 0)\n {\n Image\n *clut_image;\n\n /* FUTURE - make this a compose option, and thus can be used\n with layers compose or even compose last image over all other\n _images.\n */\n new_images=RemoveFirstImageFromList(&_images);\n clut_image=RemoveLastImageFromList(&_images);\n /* FUTURE - produce Exception, rather than silent fail */\n if (clut_image == (Image *) NULL)\n break;\n (void) ClutImage(new_images,clut_image,new_images->interpolate,\n _exception);\n clut_image=DestroyImage(clut_image);\n break;\n }\n if (LocaleCompare(\"coalesce\",option+1) == 0)\n {\n new_images=CoalesceImages(_images,_exception);\n break;\n }\n if (LocaleCompare(\"combine\",option+1) == 0)\n {\n parse=(ssize_t) _images->colorspace;\n if (_images->number_channels < GetImageListLength(_images))\n parse=sRGBColorspace;\n if ( IfPlusOp )\n parse=ParseCommandOption(MagickColorspaceOptions,MagickFalse,arg1);\n if (parse < 0)\n CLIWandExceptArgBreak(OptionError,\"UnrecognizedColorspace\",option,\n arg1);\n new_images=CombineImages(_images,(ColorspaceType) parse,_exception);\n break;\n }\n if (LocaleCompare(\"compare\",option+1) == 0)\n {\n double\n distortion;\n\n 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 image=RemoveFirstImageFromList(&_images);\n reconstruct_image=RemoveFirstImageFromList(&_images);\n /* FUTURE - produce Exception, rather than silent fail */\n if (reconstruct_image == (Image *) NULL)\n break;\n metric=UndefinedErrorMetric;\n option=GetImageOption(_image_info,\"metric\");\n if (option != (const char *) NULL)\n metric=(MetricType) ParseCommandOption(MagickMetricOptions,\n MagickFalse,option);\n new_images=CompareImages(image,reconstruct_image,metric,&distortion,\n _exception);\n (void) distortion;\n reconstruct_image=DestroyImage(reconstruct_image);\n image=DestroyImage(image);\n break;\n }\n if (LocaleCompare(\"complex\",option+1) == 0)\n {\n parse=ParseCommandOption(MagickComplexOptions,MagickFalse,arg1);\n if (parse < 0)\n CLIWandExceptArgBreak(OptionError,\"UnrecognizedEvaluateOperator\",\n option,arg1);\n new_images=ComplexImages(_images,(ComplexOperator) parse,_exception);\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 *source_image;\n\n RectangleInfo\n geometry;\n\n /* Compose value from \"-compose\" option only */\n value=GetImageOption(_image_info,\"compose\");\n if (value == (const char *) NULL)\n compose=OverCompositeOp; /* use Over not source_image->compose */\n else\n compose=(CompositeOperator) ParseCommandOption(MagickComposeOptions,\n MagickFalse,value);\n\n /* Get \"clip-to-self\" expert setting (false is normal) */\n clip_to_self=GetCompositeClipToSelf(compose);\n value=GetImageOption(_image_info,\"compose:clip-to-self\");\n if (value != (const char *) NULL)\n clip_to_self=IsStringTrue(value);\n value=GetImageOption(_image_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,clip_to_self,\n 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,OverCompositeOp,\n clip_to_self,0,0,_exception);\n new_images=DestroyImage(new_images);\n new_images=clone_image;\n }\n mask_image=DestroyImage(mask_image);\n }\n source_image=DestroyImage(source_image);\n break;\n }\n if (LocaleCompare(\"copy\",option+1) == 0)\n {\n Image\n *source_image;\n\n OffsetInfo\n offset;\n\n RectangleInfo\n geometry;\n\n /*\n Copy image pixels.\n */\n if (IsGeometry(arg1) == MagickFalse)\n CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1);\n if (IsGeometry(arg2) == MagickFalse)\n CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1);\n (void) ParsePageGeometry(_images,arg2,&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,arg1,&geometry,_exception);\n (void) CopyImagePixels(_images,source_image,&geometry,&offset,\n _exception);\n break;\n }\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n case 'd':\n {\n if (LocaleCompare(\"deconstruct\",option+1) == 0)\n {\n CLIWandWarnReplaced(\"-layer CompareAny\");\n (void) CLIListOperatorImages(cli_wand,\"-layer\",\"CompareAny\",NULL);\n break;\n }\n if (LocaleCompare(\"delete\",option+1) == 0)\n {\n if (IfNormalOp)\n DeleteImages(&_images,arg1,_exception);\n else\n DeleteImages(&_images,\"-1\",_exception);\n break;\n }\n if (LocaleCompare(\"duplicate\",option+1) == 0)\n {\n if (IfNormalOp)\n {\n const char\n *p;\n\n size_t\n number_duplicates;\n\n if (IsGeometry(arg1) == MagickFalse)\n CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,\n arg1);\n number_duplicates=(size_t) StringToLong(arg1);\n p=strchr(arg1,',');\n if (p == (const char *) NULL)\n new_images=DuplicateImages(_images,number_duplicates,\"-1\",\n _exception);\n else\n new_images=DuplicateImages(_images,number_duplicates,p,\n _exception);\n }\n else\n new_images=DuplicateImages(_images,1,\"-1\",_exception);\n AppendImageToList(&_images, new_images);\n new_images=(Image *) NULL;\n break;\n }\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n case 'e':\n {\n if (LocaleCompare(\"evaluate-sequence\",option+1) == 0)\n {\n parse=ParseCommandOption(MagickEvaluateOptions,MagickFalse,arg1);\n if (parse < 0)\n CLIWandExceptArgBreak(OptionError,\"UnrecognizedEvaluateOperator\",\n option,arg1);\n new_images=EvaluateImages(_images,(MagickEvaluateOperator) parse,\n _exception);\n break;\n }\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n case 'f':\n {\n if (LocaleCompare(\"fft\",option+1) == 0)\n {\n new_images=ForwardFourierTransformImage(_images,IsNormalOp,\n _exception);\n break;\n }\n if (LocaleCompare(\"flatten\",option+1) == 0)\n {\n /* REDIRECTED to use -layers flatten instead */\n (void) CLIListOperatorImages(cli_wand,\"-layers\",option+1,NULL);\n break;\n }\n if (LocaleCompare(\"fx\",option+1) == 0)\n {\n new_images=FxImage(_images,arg1,_exception);\n break;\n }\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n case 'h':\n {\n if (LocaleCompare(\"hald-clut\",option+1) == 0)\n {\n /* FUTURE - make this a compose option (and thus layers compose )\n or perhaps compose last image over all other _images.\n */\n Image\n *hald_image;\n\n new_images=RemoveFirstImageFromList(&_images);\n hald_image=RemoveLastImageFromList(&_images);\n if (hald_image == (Image *) NULL)\n break;\n (void) HaldClutImage(new_images,hald_image,_exception);\n hald_image=DestroyImage(hald_image);\n break;\n }\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n case 'i':\n {\n if (LocaleCompare(\"ift\",option+1) == 0)\n {\n Image\n *magnitude_image,\n *phase_image;\n\n magnitude_image=RemoveFirstImageFromList(&_images);\n phase_image=RemoveFirstImageFromList(&_images);\n /* FUTURE - produce Exception, rather than silent fail */\n if (phase_image == (Image *) NULL)\n break;\n new_images=InverseFourierTransformImage(magnitude_image,phase_image,\n IsNormalOp,_exception);\n magnitude_image=DestroyImage(magnitude_image);\n phase_image=DestroyImage(phase_image);\n break;\n }\n if (LocaleCompare(\"insert\",option+1) == 0)\n {\n Image\n *insert_image,\n *index_image;\n\n ssize_t\n index;\n\n if (IfNormalOp && (IsGeometry(arg1) == MagickFalse))\n CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1);\n index=0;\n insert_image=RemoveLastImageFromList(&_images);\n if (IfNormalOp)\n index=(ssize_t) StringToLong(arg1);\n index_image=insert_image;\n if (index == 0)\n PrependImageToList(&_images,insert_image);\n else if (index == (ssize_t) GetImageListLength(_images))\n AppendImageToList(&_images,insert_image);\n else\n {\n index_image=GetImageFromList(_images,index-1);\n if (index_image == (Image *) NULL)\n CLIWandExceptArgBreak(OptionError,\"NoSuchImage\",option,arg1);\n InsertImageInList(&index_image,insert_image);\n }\n _images=GetFirstImageInList(index_image);\n break;\n }\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n case 'l':\n {\n if (LocaleCompare(\"layers\",option+1) == 0)\n {\n parse=ParseCommandOption(MagickLayerOptions,MagickFalse,arg1);\n if ( parse < 0 )\n CLIWandExceptArgBreak(OptionError,\"UnrecognizedLayerMethod\",\n option,arg1);\n switch ((LayerMethod) parse)\n {\n case CoalesceLayer:\n {\n new_images=CoalesceImages(_images,_exception);\n break;\n }\n case CompareAnyLayer:\n case CompareClearLayer:\n case CompareOverlayLayer:\n default:\n {\n new_images=CompareImagesLayers(_images,(LayerMethod) parse,\n _exception);\n break;\n }\n case MergeLayer:\n case FlattenLayer:\n case MosaicLayer:\n case TrimBoundsLayer:\n {\n new_images=MergeImageLayers(_images,(LayerMethod) parse,\n _exception);\n break;\n }\n case DisposeLayer:\n {\n new_images=DisposeImages(_images,_exception);\n break;\n }\n case OptimizeImageLayer:\n {\n new_images=OptimizeImageLayers(_images,_exception);\n break;\n }\n case OptimizePlusLayer:\n {\n new_images=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 { /* General Purpose, GIF Animation Optimizer. */\n new_images=CoalesceImages(_images,_exception);\n if (new_images == (Image *) NULL)\n break;\n _images=DestroyImageList(_images);\n _images=OptimizeImageLayers(new_images,_exception);\n if (_images == (Image *) NULL)\n break;\n new_images=DestroyImageList(new_images);\n OptimizeImageTransparency(_images,_exception);\n (void) RemapImages(_quantize_info,_images,(Image *) NULL,\n _exception);\n break;\n }\n case CompositeLayer:\n {\n Image\n *source;\n\n RectangleInfo\n geometry;\n\n CompositeOperator\n compose;\n\n const char*\n value;\n\n value=GetImageOption(_image_info,\"compose\");\n compose=OverCompositeOp; /* Default to Over */\n if (value != (const char *) NULL)\n compose=(CompositeOperator) ParseCommandOption(\n MagickComposeOptions,MagickFalse,value);\n\n /* Split image sequence at the first 'NULL:' image. */\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 { /* Separate the two lists, junk the null: image. */\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 break;\n }\n /* Adjust offset with gravity and virtual canvas. */\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\n /* Compose the two image sequences together */\n CompositeLayers(_images,compose,source,geometry.x,geometry.y,\n _exception);\n source=DestroyImageList(source);\n break;\n }\n }\n break;\n }\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n case 'm':\n {\n if (LocaleCompare(\"map\",option+1) == 0)\n {\n CLIWandWarnReplaced(\"+remap\");\n (void) RemapImages(_quantize_info,_images,(Image *) NULL,_exception);\n break;\n }\n if (LocaleCompare(\"metric\",option+1) == 0)\n {\n (void) SetImageOption(_image_info,option+1,arg1);\n break;\n }\n if (LocaleCompare(\"morph\",option+1) == 0)\n {\n Image\n *morph_image;\n\n if (IsGeometry(arg1) == MagickFalse)\n CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1);\n morph_image=MorphImages(_images,StringToUnsignedLong(arg1),\n _exception);\n if (morph_image == (Image *) NULL)\n break;\n _images=DestroyImageList(_images);\n _images=morph_image;\n break;\n }\n if (LocaleCompare(\"mosaic\",option+1) == 0)\n {\n /* REDIRECTED to use -layers mosaic instead */\n (void) CLIListOperatorImages(cli_wand,\"-layers\",option+1,NULL);\n break;\n }\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n case 'p':\n {\n if (LocaleCompare(\"poly\",option+1) == 0)\n {\n double\n *args;\n\n ssize_t\n count;\n\n /* convert argument string into an array of doubles */\n args = StringToArrayOfDoubles(arg1,&count,_exception);\n if (args == (double *) NULL )\n CLIWandExceptArgBreak(OptionError,\"InvalidNumberList\",option,arg1);\n new_images=PolynomialImage(_images,(size_t) (count >> 1),args,\n _exception);\n args=(double *) RelinquishMagickMemory(args);\n break;\n }\n if (LocaleCompare(\"process\",option+1) == 0)\n {\n /* FUTURE: better parsing using ScriptToken() from string ??? */\n char\n **arguments;\n\n int\n j,\n number_arguments;\n\n arguments=StringToArgv(arg1,&number_arguments);\n if (arguments == (char **) NULL)\n break;\n if (strchr(arguments[1],'=') != (char *) NULL)\n {\n char\n breaker,\n quote,\n *token;\n\n const char\n *arguments;\n\n int\n next,\n status;\n\n size_t\n length;\n\n TokenInfo\n *token_info;\n\n /*\n Support old style syntax, filter=\"-option arg1\".\n */\n assert(arg1 != (const char *) NULL);\n length=strlen(arg1);\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 arguments=arg1;\n token_info=AcquireTokenInfo();\n status=Tokenizer(token_info,0,token,length,arguments,\"\",\"=\",\n \"\\\"\",'\\0',&breaker,&next,"e);\n token_info=DestroyTokenInfo(token_info);\n if (status == 0)\n {\n const char\n *argv;\n\n argv=(&(arguments[next]));\n (void) InvokeDynamicImageFilter(token,&_images,1,&argv,\n _exception);\n }\n token=DestroyString(token);\n break;\n }\n (void) SubstituteString(&arguments[1],\"-\",\"\");\n (void) InvokeDynamicImageFilter(arguments[1],&_images,\n number_arguments-2,(const char **) arguments+2,_exception);\n for (j=0; j < number_arguments; j++)\n arguments[j]=DestroyString(arguments[j]);\n arguments=(char **) RelinquishMagickMemory(arguments);\n break;\n }\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n case 'r':\n {\n if (LocaleCompare(\"remap\",option+1) == 0)\n {\n (void) RemapImages(_quantize_info,_images,(Image *) NULL,_exception);\n break;\n }\n if (LocaleCompare(\"reverse\",option+1) == 0)\n {\n ReverseImageList(&_images);\n break;\n }\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n case 's':\n {\n if (LocaleCompare(\"smush\",option+1) == 0)\n {\n /* FUTURE: this option needs more work to make better */\n ssize_t\n offset;\n\n if (IsGeometry(arg1) == MagickFalse)\n CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1);\n offset=(ssize_t) StringToLong(arg1);\n new_images=SmushImages(_images,IsNormalOp,offset,_exception);\n break;\n }\n if (LocaleCompare(\"subimage\",option+1) == 0)\n {\n Image\n *base_image,\n *compare_image;\n\n const char\n *value;\n\n MetricType\n metric;\n\n double\n similarity;\n\n RectangleInfo\n offset;\n\n base_image=GetImageFromList(_images,0);\n compare_image=GetImageFromList(_images,1);\n\n /* Comparision Metric */\n metric=UndefinedErrorMetric;\n value=GetImageOption(_image_info,\"metric\");\n if (value != (const char *) NULL)\n metric=(MetricType) ParseCommandOption(MagickMetricOptions,\n MagickFalse,value);\n\n new_images=SimilarityImage(base_image,compare_image,metric,0.0,\n &offset,&similarity,_exception);\n\n if (new_images != (Image *) NULL)\n {\n char\n result[MagickPathExtent];\n\n (void) FormatLocaleString(result,MagickPathExtent,\"%lf\",\n similarity);\n (void) SetImageProperty(new_images,\"subimage:similarity\",result,\n _exception);\n (void) FormatLocaleString(result,MagickPathExtent,\"%+ld\",(long)\n offset.x);\n (void) SetImageProperty(new_images,\"subimage:x\",result,\n _exception);\n (void) FormatLocaleString(result,MagickPathExtent,\"%+ld\",(long)\n offset.y);\n (void) SetImageProperty(new_images,\"subimage:y\",result,\n _exception);\n (void) FormatLocaleString(result,MagickPathExtent,\n \"%lux%lu%+ld%+ld\",(unsigned long) offset.width,(unsigned long)\n offset.height,(long) offset.x,(long) offset.y);\n (void) SetImageProperty(new_images,\"subimage:offset\",result,\n _exception);\n }\n break;\n }\n if (LocaleCompare(\"swap\",option+1) == 0)\n {\n Image\n *p,\n *q,\n *swap;\n\n ssize_t\n index,\n swap_index;\n\n index=(-1);\n swap_index=(-2);\n if (IfNormalOp) {\n GeometryInfo\n geometry_info;\n\n MagickStatusType\n flags;\n\n swap_index=(-1);\n flags=ParseGeometry(arg1,&geometry_info);\n if ((flags & RhoValue) == 0)\n CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1);\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 if (IfNormalOp)\n CLIWandExceptArgBreak(OptionError,\"InvalidImageIndex\",option,arg1)\n else\n CLIWandExceptionBreak(OptionError,\"TwoOrMoreImagesRequired\",option);\n }\n if (p == q)\n CLIWandExceptArgBreak(OptionError,\"InvalidImageIndex\",option,arg1);\n swap=CloneImage(p,0,0,MagickTrue,_exception);\n if (swap == (Image *) NULL)\n CLIWandExceptArgBreak(ResourceLimitError,\"MemoryAllocationFailed\",\n option,GetExceptionMessage(errno));\n ReplaceImageInList(&p,CloneImage(q,0,0,MagickTrue,_exception));\n ReplaceImageInList(&q,swap);\n _images=GetFirstImageInList(q);\n break;\n }\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n default:\n CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option);\n }\n\n /* clean up percent escape interpreted strings */\n if (arg1 != arg1n )\n arg1=DestroyString((char *)arg1);\n if (arg2 != arg2n )\n arg2=DestroyString((char *)arg2);\n\n /* if new image list generated, replace existing image list */\n if (new_images == (Image *) NULL)\n return(status == 0 ? MagickFalse : MagickTrue);\n _images=DestroyImageList(_images);\n _images=GetFirstImageInList(new_images);\n return(status == 0 ? MagickFalse : MagickTrue);\n\n#undef _image_info\n#undef _images\n#undef _exception\n#undef _draw_info\n#undef _quantize_info\n#undef IfNormalOp\n#undef IfPlusOp\n#undef IsNormalOp\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/1604'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static MagickBooleanType WriteDPXImage(const ImageInfo *image_info,Image *image,\n ExceptionInfo *exception)\n{\n const char\n *value;\n\n const StringInfo\n *profile;\n\n DPXInfo\n dpx;\n\n GeometryInfo\n geometry_info;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n offset;\n\n MagickStatusType\n flags;\n\n QuantumInfo\n *quantum_info;\n\n QuantumType\n quantum_type;\n\n register const Quantum\n *p;\n\n register ssize_t\n i;\n\n size_t\n channels,\n extent;\n\n ssize_t\n count,\n horizontal_factor,\n vertical_factor,\n y;\n\n time_t\n seconds;\n\n unsigned char\n *pixels;\n\n /*\n Open output image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n horizontal_factor=4;\n vertical_factor=4;\n if (image_info->sampling_factor != (char *) NULL)\n {\n flags=ParseGeometry(image_info->sampling_factor,&geometry_info);\n horizontal_factor=(ssize_t) geometry_info.rho;\n vertical_factor=(ssize_t) geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n vertical_factor=horizontal_factor;\n if ((horizontal_factor != 1) && (horizontal_factor != 2) &&\n (horizontal_factor != 4) && (vertical_factor != 1) &&\n (vertical_factor != 2) && (vertical_factor != 4))\n ThrowWriterException(CorruptImageError,\"UnexpectedSamplingFactor\");\n }\n if ((image->colorspace == YCbCrColorspace) &&\n ((horizontal_factor == 2) || (vertical_factor == 2)))\n if ((image->columns % 2) != 0)\n image->columns++;\n 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 Write file header.\n */\n (void) memset(&dpx,0,sizeof(dpx));\n offset=0;\n dpx.file.magic=0x53445058U;\n offset+=WriteBlobLong(image,dpx.file.magic);\n dpx.file.image_offset=0x2000U;\n profile=GetImageProfile(image,\"dpx:user-data\");\n if (profile != (StringInfo *) NULL)\n {\n if (GetStringInfoLength(profile) > 1048576)\n ThrowWriterException(ImageError,\"WidthOrHeightExceedsLimit\");\n dpx.file.image_offset+=(unsigned int) GetStringInfoLength(profile);\n dpx.file.image_offset=(((dpx.file.image_offset+0x2000-1)/0x2000)*0x2000);\n }\n offset+=WriteBlobLong(image,dpx.file.image_offset);\n (void) strncpy(dpx.file.version,\"V2.0\",sizeof(dpx.file.version)-1);\n offset+=WriteBlob(image,8,(unsigned char *) &dpx.file.version);\n channels=1;\n if (IsImageGray(image) == MagickFalse)\n channels=3;\n if (image->alpha_trait != UndefinedPixelTrait)\n channels++;\n dpx.file.file_size=(unsigned int) (channels*image->columns*image->rows+\n dpx.file.image_offset);\n offset+=WriteBlobLong(image,dpx.file.file_size);\n dpx.file.ditto_key=1U; /* new frame */\n offset+=WriteBlobLong(image,dpx.file.ditto_key);\n dpx.file.generic_size=0x00000680U;\n offset+=WriteBlobLong(image,dpx.file.generic_size);\n dpx.file.industry_size=0x00000180U;\n offset+=WriteBlobLong(image,dpx.file.industry_size);\n dpx.file.user_size=0;\n if (profile != (StringInfo *) NULL)\n {\n dpx.file.user_size+=(unsigned int) GetStringInfoLength(profile);\n dpx.file.user_size=(((dpx.file.user_size+0x2000-1)/0x2000)*0x2000);\n }\n offset+=WriteBlobLong(image,dpx.file.user_size);\n value=GetDPXProperty(image,\"dpx:file.filename\",exception);\n if (value != (const char *) NULL)\n (void) strncpy(dpx.file.filename,value,sizeof(dpx.file.filename)-1);\n offset+=WriteBlob(image,sizeof(dpx.file.filename),(unsigned char *)\n dpx.file.filename);\n seconds=time((time_t *) NULL);\n (void) FormatMagickTime(seconds,sizeof(dpx.file.timestamp),\n dpx.file.timestamp);\n offset+=WriteBlob(image,sizeof(dpx.file.timestamp),(unsigned char *)\n dpx.file.timestamp);\n (void) strncpy(dpx.file.creator,MagickAuthoritativeURL,\n sizeof(dpx.file.creator)-1);\n value=GetDPXProperty(image,\"dpx:file.creator\",exception);\n if (value != (const char *) NULL)\n (void) strncpy(dpx.file.creator,value,sizeof(dpx.file.creator)-1);\n offset+=WriteBlob(image,sizeof(dpx.file.creator),(unsigned char *)\n dpx.file.creator);\n value=GetDPXProperty(image,\"dpx:file.project\",exception);\n if (value != (const char *) NULL)\n (void) strncpy(dpx.file.project,value,sizeof(dpx.file.project)-1);\n offset+=WriteBlob(image,sizeof(dpx.file.project),(unsigned char *)\n dpx.file.project);\n value=GetDPXProperty(image,\"dpx:file.copyright\",exception);\n if (value != (const char *) NULL)\n (void) strncpy(dpx.file.copyright,value,sizeof(dpx.file.copyright)-1);\n offset+=WriteBlob(image,sizeof(dpx.file.copyright),(unsigned char *)\n dpx.file.copyright);\n dpx.file.encrypt_key=(~0U);\n offset+=WriteBlobLong(image,dpx.file.encrypt_key);\n offset+=WriteBlob(image,sizeof(dpx.file.reserve),(unsigned char *)\n dpx.file.reserve);\n /*\n Write image header.\n */\n switch (image->orientation)\n {\n default:\n case TopLeftOrientation: dpx.image.orientation=0; break;\n case TopRightOrientation: dpx.image.orientation=1; break;\n case BottomLeftOrientation: dpx.image.orientation=2; break;\n case BottomRightOrientation: dpx.image.orientation=3; break;\n case LeftTopOrientation: dpx.image.orientation=4; break;\n case RightTopOrientation: dpx.image.orientation=5; break;\n case LeftBottomOrientation: dpx.image.orientation=6; break;\n case RightBottomOrientation: dpx.image.orientation=7; break;\n }\n offset+=WriteBlobShort(image,dpx.image.orientation);\n dpx.image.number_elements=1;\n offset+=WriteBlobShort(image,dpx.image.number_elements);\n if ((image->columns != (unsigned int) image->columns) ||\n (image->rows != (unsigned int) image->rows))\n ThrowWriterException(ImageError,\"WidthOrHeightExceedsLimit\");\n offset+=WriteBlobLong(image,(unsigned int) image->columns);\n offset+=WriteBlobLong(image,(unsigned int) image->rows);\n for (i=0; i < 8; i++)\n {\n dpx.image.image_element[i].data_sign=0U;\n offset+=WriteBlobLong(image,dpx.image.image_element[i].data_sign);\n dpx.image.image_element[i].low_data=0U;\n offset+=WriteBlobLong(image,dpx.image.image_element[i].low_data);\n dpx.image.image_element[i].low_quantity=0.0f;\n offset+=WriteBlobFloat(image,dpx.image.image_element[i].low_quantity);\n dpx.image.image_element[i].high_data=0U;\n offset+=WriteBlobLong(image,dpx.image.image_element[i].high_data);\n dpx.image.image_element[i].high_quantity=0.0f;\n offset+=WriteBlobFloat(image,dpx.image.image_element[i].high_quantity);\n dpx.image.image_element[i].descriptor=0;\n if (i == 0)\n switch (image->colorspace)\n {\n case Rec601YCbCrColorspace:\n case Rec709YCbCrColorspace:\n case YCbCrColorspace:\n {\n dpx.image.image_element[i].descriptor=CbYCr444ComponentType;\n if (image->alpha_trait != UndefinedPixelTrait)\n dpx.image.image_element[i].descriptor=CbYCrA4444ComponentType;\n break;\n }\n default:\n {\n dpx.image.image_element[i].descriptor=RGBComponentType;\n if (image->alpha_trait != UndefinedPixelTrait)\n dpx.image.image_element[i].descriptor=RGBAComponentType;\n if ((image_info->type != TrueColorType) &&\n (image->alpha_trait == UndefinedPixelTrait) &&\n (SetImageGray(image,exception) != MagickFalse))\n dpx.image.image_element[i].descriptor=LumaComponentType;\n break;\n }\n }\n offset+=WriteBlobByte(image,dpx.image.image_element[i].descriptor);\n dpx.image.image_element[i].transfer_characteristic=0;\n if (image->colorspace == LogColorspace)\n dpx.image.image_element[0].transfer_characteristic=\n PrintingDensityColorimetric;\n offset+=WriteBlobByte(image,\n dpx.image.image_element[i].transfer_characteristic);\n dpx.image.image_element[i].colorimetric=0;\n offset+=WriteBlobByte(image,dpx.image.image_element[i].colorimetric);\n dpx.image.image_element[i].bit_size=0;\n if (i == 0)\n dpx.image.image_element[i].bit_size=(unsigned char) image->depth;\n offset+=WriteBlobByte(image,dpx.image.image_element[i].bit_size);\n dpx.image.image_element[i].packing=0;\n if ((image->depth == 10) || (image->depth == 12))\n dpx.image.image_element[i].packing=1;\n offset+=WriteBlobShort(image,dpx.image.image_element[i].packing);\n dpx.image.image_element[i].encoding=0;\n offset+=WriteBlobShort(image,dpx.image.image_element[i].encoding);\n dpx.image.image_element[i].data_offset=0U;\n if (i == 0)\n dpx.image.image_element[i].data_offset=dpx.file.image_offset;\n offset+=WriteBlobLong(image,dpx.image.image_element[i].data_offset);\n dpx.image.image_element[i].end_of_line_padding=0U;\n offset+=WriteBlobLong(image,dpx.image.image_element[i].end_of_line_padding);\n offset+=WriteBlobLong(image,\n dpx.image.image_element[i].end_of_image_padding);\n offset+=WriteBlob(image,sizeof(dpx.image.image_element[i].description),\n (unsigned char *) dpx.image.image_element[i].description);\n }\n offset+=WriteBlob(image,sizeof(dpx.image.reserve),(unsigned char *)\n dpx.image.reserve);\n /*\n Write orientation header.\n */\n if ((image->rows != image->magick_rows) ||\n (image->columns != image->magick_columns))\n {\n /*\n These properties are not valid if image size changed.\n */\n (void) DeleteImageProperty(image,\"dpx:orientation.x_offset\");\n (void) DeleteImageProperty(image,\"dpx:orientation.y_offset\");\n (void) DeleteImageProperty(image,\"dpx:orientation.x_center\");\n (void) DeleteImageProperty(image,\"dpx:orientation.y_center\");\n (void) DeleteImageProperty(image,\"dpx:orientation.x_size\");\n (void) DeleteImageProperty(image,\"dpx:orientation.y_size\");\n }\n dpx.orientation.x_offset=0U;\n value=GetDPXProperty(image,\"dpx:orientation.x_offset\",exception);\n if (value != (const char *) NULL)\n dpx.orientation.x_offset=(unsigned int) StringToUnsignedLong(value);\n offset+=WriteBlobLong(image,dpx.orientation.x_offset);\n dpx.orientation.y_offset=0U;\n value=GetDPXProperty(image,\"dpx:orientation.y_offset\",exception);\n if (value != (const char *) NULL)\n dpx.orientation.y_offset=(unsigned int) StringToUnsignedLong(value);\n offset+=WriteBlobLong(image,dpx.orientation.y_offset);\n dpx.orientation.x_center=0.0f;\n value=GetDPXProperty(image,\"dpx:orientation.x_center\",exception);\n if (value != (const char *) NULL)\n dpx.orientation.x_center=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.orientation.x_center);\n dpx.orientation.y_center=0.0f;\n value=GetDPXProperty(image,\"dpx:orientation.y_center\",exception);\n if (value != (const char *) NULL)\n dpx.orientation.y_center=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.orientation.y_center);\n dpx.orientation.x_size=0U;\n value=GetDPXProperty(image,\"dpx:orientation.x_size\",exception);\n if (value != (const char *) NULL)\n dpx.orientation.x_size=(unsigned int) StringToUnsignedLong(value);\n offset+=WriteBlobLong(image,dpx.orientation.x_size);\n dpx.orientation.y_size=0U;\n value=GetDPXProperty(image,\"dpx:orientation.y_size\",exception);\n if (value != (const char *) NULL)\n dpx.orientation.y_size=(unsigned int) StringToUnsignedLong(value);\n offset+=WriteBlobLong(image,dpx.orientation.y_size);\n value=GetDPXProperty(image,\"dpx:orientation.filename\",exception);\n if (value != (const char *) NULL)\n (void) strncpy(dpx.orientation.filename,value,\n sizeof(dpx.orientation.filename)-1);\n offset+=WriteBlob(image,sizeof(dpx.orientation.filename),(unsigned char *)\n dpx.orientation.filename);\n offset+=WriteBlob(image,sizeof(dpx.orientation.timestamp),(unsigned char *)\n dpx.orientation.timestamp);\n value=GetDPXProperty(image,\"dpx:orientation.device\",exception);\n if (value != (const char *) NULL)\n (void) strncpy(dpx.orientation.device,value,\n sizeof(dpx.orientation.device)-1);\n offset+=WriteBlob(image,sizeof(dpx.orientation.device),(unsigned char *)\n dpx.orientation.device);\n value=GetDPXProperty(image,\"dpx:orientation.serial\",exception);\n if (value != (const char *) NULL)\n (void) strncpy(dpx.orientation.serial,value,\n sizeof(dpx.orientation.serial)-1);\n offset+=WriteBlob(image,sizeof(dpx.orientation.serial),(unsigned char *)\n dpx.orientation.serial);\n for (i=0; i < 4; i++)\n dpx.orientation.border[i]=0;\n value=GetDPXProperty(image,\"dpx:orientation.border\",exception);\n if (value != (const char *) NULL)\n {\n flags=ParseGeometry(value,&geometry_info);\n if ((flags & SigmaValue) == 0)\n geometry_info.sigma=geometry_info.rho;\n dpx.orientation.border[0]=(unsigned short) (geometry_info.rho+0.5);\n dpx.orientation.border[1]=(unsigned short) (geometry_info.sigma+0.5);\n dpx.orientation.border[2]=(unsigned short) (geometry_info.xi+0.5);\n dpx.orientation.border[3]=(unsigned short) (geometry_info.psi+0.5);\n }\n for (i=0; i < 4; i++)\n offset+=WriteBlobShort(image,dpx.orientation.border[i]);\n for (i=0; i < 2; i++)\n dpx.orientation.aspect_ratio[i]=0U;\n value=GetDPXProperty(image,\"dpx:orientation.aspect_ratio\",exception);\n if (value != (const char *) NULL)\n {\n flags=ParseGeometry(value,&geometry_info);\n if ((flags & SigmaValue) == 0)\n geometry_info.sigma=geometry_info.rho;\n dpx.orientation.aspect_ratio[0]=(unsigned int) (geometry_info.rho+0.5);\n dpx.orientation.aspect_ratio[1]=(unsigned int) (geometry_info.sigma+0.5);\n }\n for (i=0; i < 2; i++)\n offset+=WriteBlobLong(image,dpx.orientation.aspect_ratio[i]);\n offset+=WriteBlob(image,sizeof(dpx.orientation.reserve),(unsigned char *)\n dpx.orientation.reserve);\n /*\n Write film header.\n */\n (void) memset(dpx.film.id,0,sizeof(dpx.film.id));\n value=GetDPXProperty(image,\"dpx:film.id\",exception);\n if (value != (const char *) NULL)\n (void) strncpy(dpx.film.id,value,sizeof(dpx.film.id)-1);\n offset+=WriteBlob(image,sizeof(dpx.film.id),(unsigned char *) dpx.film.id);\n (void) memset(dpx.film.type,0,sizeof(dpx.film.type));\n value=GetDPXProperty(image,\"dpx:film.type\",exception);\n if (value != (const char *) NULL)\n (void) strncpy(dpx.film.type,value,sizeof(dpx.film.type)-1);\n offset+=WriteBlob(image,sizeof(dpx.film.type),(unsigned char *)\n dpx.film.type);\n (void) memset(dpx.film.offset,0,sizeof(dpx.film.offset));\n value=GetDPXProperty(image,\"dpx:film.offset\",exception);\n if (value != (const char *) NULL)\n (void) strncpy(dpx.film.offset,value,sizeof(dpx.film.offset)-1);\n offset+=WriteBlob(image,sizeof(dpx.film.offset),(unsigned char *)\n dpx.film.offset);\n (void) memset(dpx.film.prefix,0,sizeof(dpx.film.prefix));\n value=GetDPXProperty(image,\"dpx:film.prefix\",exception);\n if (value != (const char *) NULL)\n (void) strncpy(dpx.film.prefix,value,sizeof(dpx.film.prefix)-1);\n offset+=WriteBlob(image,sizeof(dpx.film.prefix),(unsigned char *)\n dpx.film.prefix);\n (void) memset(dpx.film.count,0,sizeof(dpx.film.count));\n value=GetDPXProperty(image,\"dpx:film.count\",exception);\n if (value != (const char *) NULL)\n (void) strncpy(dpx.film.count,value,sizeof(dpx.film.count)-1);\n offset+=WriteBlob(image,sizeof(dpx.film.count),(unsigned char *)\n dpx.film.count);\n (void) memset(dpx.film.format,0,sizeof(dpx.film.format));\n value=GetDPXProperty(image,\"dpx:film.format\",exception);\n if (value != (const char *) NULL)\n (void) strncpy(dpx.film.format,value,sizeof(dpx.film.format)-1);\n offset+=WriteBlob(image,sizeof(dpx.film.format),(unsigned char *)\n dpx.film.format);\n dpx.film.frame_position=0U;\n value=GetDPXProperty(image,\"dpx:film.frame_position\",exception);\n if (value != (const char *) NULL)\n dpx.film.frame_position=(unsigned int) StringToUnsignedLong(value);\n offset+=WriteBlobLong(image,dpx.film.frame_position);\n dpx.film.sequence_extent=0U;\n value=GetDPXProperty(image,\"dpx:film.sequence_extent\",exception);\n if (value != (const char *) NULL)\n dpx.film.sequence_extent=(unsigned int) StringToUnsignedLong(value);\n offset+=WriteBlobLong(image,dpx.film.sequence_extent);\n dpx.film.held_count=0U;\n value=GetDPXProperty(image,\"dpx:film.held_count\",exception);\n if (value != (const char *) NULL)\n dpx.film.held_count=(unsigned int) StringToUnsignedLong(value);\n offset+=WriteBlobLong(image,dpx.film.held_count);\n dpx.film.frame_rate=0.0f;\n value=GetDPXProperty(image,\"dpx:film.frame_rate\",exception);\n if (value != (const char *) NULL)\n dpx.film.frame_rate=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.film.frame_rate);\n dpx.film.shutter_angle=0.0f;\n value=GetDPXProperty(image,\"dpx:film.shutter_angle\",exception);\n if (value != (const char *) NULL)\n dpx.film.shutter_angle=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.film.shutter_angle);\n (void) memset(dpx.film.frame_id,0,sizeof(dpx.film.frame_id));\n value=GetDPXProperty(image,\"dpx:film.frame_id\",exception);\n if (value != (const char *) NULL)\n (void) strncpy(dpx.film.frame_id,value,sizeof(dpx.film.frame_id)-1);\n offset+=WriteBlob(image,sizeof(dpx.film.frame_id),(unsigned char *)\n dpx.film.frame_id);\n value=GetDPXProperty(image,\"dpx:film.slate\",exception);\n if (value != (const char *) NULL)\n (void) strncpy(dpx.film.slate,value,sizeof(dpx.film.slate)-1);\n offset+=WriteBlob(image,sizeof(dpx.film.slate),(unsigned char *)\n dpx.film.slate);\n offset+=WriteBlob(image,sizeof(dpx.film.reserve),(unsigned char *)\n dpx.film.reserve);\n /*\n Write television header.\n */\n value=GetDPXProperty(image,\"dpx:television.time.code\",exception);\n if (value != (const char *) NULL)\n dpx.television.time_code=StringToTimeCode(value);\n offset+=WriteBlobLong(image,dpx.television.time_code);\n value=GetDPXProperty(image,\"dpx:television.user.bits\",exception);\n if (value != (const char *) NULL)\n dpx.television.user_bits=StringToTimeCode(value);\n offset+=WriteBlobLong(image,dpx.television.user_bits);\n value=GetDPXProperty(image,\"dpx:television.interlace\",exception);\n if (value != (const char *) NULL)\n dpx.television.interlace=(unsigned char) StringToLong(value);\n offset+=WriteBlobByte(image,dpx.television.interlace);\n value=GetDPXProperty(image,\"dpx:television.field_number\",exception);\n if (value != (const char *) NULL)\n dpx.television.field_number=(unsigned char) StringToLong(value);\n offset+=WriteBlobByte(image,dpx.television.field_number);\n dpx.television.video_signal=0;\n value=GetDPXProperty(image,\"dpx:television.video_signal\",exception);\n if (value != (const char *) NULL)\n dpx.television.video_signal=(unsigned char) StringToLong(value);\n offset+=WriteBlobByte(image,dpx.television.video_signal);\n dpx.television.padding=0;\n value=GetDPXProperty(image,\"dpx:television.padding\",exception);\n if (value != (const char *) NULL)\n dpx.television.padding=(unsigned char) StringToLong(value);\n offset+=WriteBlobByte(image,dpx.television.padding);\n dpx.television.horizontal_sample_rate=0.0f;\n value=GetDPXProperty(image,\"dpx:television.horizontal_sample_rate\",\n exception);\n if (value != (const char *) NULL)\n dpx.television.horizontal_sample_rate=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.television.horizontal_sample_rate);\n dpx.television.vertical_sample_rate=0.0f;\n value=GetDPXProperty(image,\"dpx:television.vertical_sample_rate\",exception);\n if (value != (const char *) NULL)\n dpx.television.vertical_sample_rate=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.television.vertical_sample_rate);\n dpx.television.frame_rate=0.0f;\n value=GetDPXProperty(image,\"dpx:television.frame_rate\",exception);\n if (value != (const char *) NULL)\n dpx.television.frame_rate=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.television.frame_rate);\n dpx.television.time_offset=0.0f;\n value=GetDPXProperty(image,\"dpx:television.time_offset\",exception);\n if (value != (const char *) NULL)\n dpx.television.time_offset=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.television.time_offset);\n dpx.television.gamma=0.0f;\n value=GetDPXProperty(image,\"dpx:television.gamma\",exception);\n if (value != (const char *) NULL)\n dpx.television.gamma=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.television.gamma);\n dpx.television.black_level=0.0f;\n value=GetDPXProperty(image,\"dpx:television.black_level\",exception);\n if (value != (const char *) NULL)\n dpx.television.black_level=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.television.black_level);\n dpx.television.black_gain=0.0f;\n value=GetDPXProperty(image,\"dpx:television.black_gain\",exception);\n if (value != (const char *) NULL)\n dpx.television.black_gain=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.television.black_gain);\n dpx.television.break_point=0.0f;\n value=GetDPXProperty(image,\"dpx:television.break_point\",exception);\n if (value != (const char *) NULL)\n dpx.television.break_point=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.television.break_point);\n dpx.television.white_level=0.0f;\n value=GetDPXProperty(image,\"dpx:television.white_level\",exception);\n if (value != (const char *) NULL)\n dpx.television.white_level=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.television.white_level);\n dpx.television.integration_times=0.0f;\n value=GetDPXProperty(image,\"dpx:television.integration_times\",exception);\n if (value != (const char *) NULL)\n dpx.television.integration_times=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,dpx.television.integration_times);\n offset+=WriteBlob(image,sizeof(dpx.television.reserve),(unsigned char *)\n dpx.television.reserve);\n /*\n Write user header.\n */\n value=GetDPXProperty(image,\"dpx:user.id\",exception);\n if (value != (const char *) NULL)\n (void) strncpy(dpx.user.id,value,sizeof(dpx.user.id)-1);\n offset+=WriteBlob(image,sizeof(dpx.user.id),(unsigned char *) dpx.user.id);\n if (profile != (StringInfo *) NULL)\n offset+=WriteBlob(image,GetStringInfoLength(profile),\n GetStringInfoDatum(profile));\n while (offset < (MagickOffsetType) dpx.image.image_element[0].data_offset)\n {\n count=WriteBlobByte(image,0x00);\n if (count != 1)\n {\n ThrowFileException(exception,FileOpenError,\"UnableToWriteFile\",\n image->filename);\n break;\n }\n offset+=count;\n }\n /*\n Convert pixel packets to DPX raster image.\n */\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n SetQuantumQuantum(quantum_info,32);\n SetQuantumPack(quantum_info,dpx.image.image_element[0].packing == 0 ?\n MagickTrue : MagickFalse);\n quantum_type=RGBQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n quantum_type=RGBAQuantum;\n if (image->colorspace == YCbCrColorspace)\n {\n quantum_type=CbYCrQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n quantum_type=CbYCrAQuantum;\n if ((horizontal_factor == 2) || (vertical_factor == 2))\n quantum_type=CbYCrYQuantum;\n }\n extent=GetBytesPerRow(image->columns,\n image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL,image->depth,\n dpx.image.image_element[0].packing == 0 ? MagickFalse : MagickTrue);\n if ((image_info->type != TrueColorType) &&\n (image->alpha_trait == UndefinedPixelTrait) &&\n (SetImageGray(image,exception) != MagickFalse))\n {\n quantum_type=GrayQuantum;\n extent=GetBytesPerRow(image->columns,1UL,image->depth,\n dpx.image.image_element[0].packing == 0 ? MagickFalse : MagickTrue);\n }\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n size_t\n length;\n\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n count=WriteBlob(image,extent,pixels);\n if (count != (ssize_t) length)\n break;\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n quantum_info=DestroyQuantumInfo(quantum_info);\n if (y < (ssize_t) image->rows)\n ThrowWriterException(CorruptImageError,\"UnableToWriteImageData\");\n (void) CloseBlob(image);\n return(status);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1517'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: plan_a (char const *filename)\n{\n char const *s;\n char const *lim;\n char const **ptr;\n char *buffer;\n lin iline;\n size_t size = instat.st_size;\n\n /* Fail if the file size doesn't fit in a size_t,\n or if storage isn't available. */\n if (! (size == instat.st_size\n\t && (buffer = malloc (size ? size : (size_t) 1))))\n return false;\n\n /* Read the input file, but don't bother reading it if it's empty.\n When creating files, the files do not actually exist. */\n if (size)\n {\n if (S_ISREG (instat.st_mode))\n {\n\t int ifd = safe_open (filename, O_RDONLY|binary_transput, 0);\n\t size_t buffered = 0, n;\n\t if (ifd < 0)\n\t pfatal (\"can't open file %s\", quotearg (filename));\n\n\t while (size - buffered != 0)\n\t {\n\t n = read (ifd, buffer + buffered, size - buffered);\n\t if (n == 0)\n\t\t{\n\t\t /* Some non-POSIX hosts exaggerate st_size in text mode;\n\t\t or the file may have shrunk! */\n\t\t size = buffered;\n\t\t break;\n\t\t}\n\t if (n == (size_t) -1)\n\t\t{\n\t\t /* Perhaps size is too large for this host. */\n\t\t close (ifd);\n\t\t free (buffer);\n\t\t return false;\n\t\t}\n\t buffered += n;\n\t }\n\n\t if (close (ifd) != 0)\n\t read_fatal ();\n\t}\n else if (S_ISLNK (instat.st_mode))\n\t{\n\t ssize_t n;\n\t n = safe_readlink (filename, buffer, size);\n\t if (n < 0)\n\t pfatal (\"can't read %s %s\", \"symbolic link\", quotearg (filename));\n\t size = n;\n\t}\n else\n\t{\n\t free (buffer);\n\t return false;\n\t}\n }\n\n /* Scan the buffer and build array of pointers to lines. */\n lim = buffer + size;\n iline = 3; /* 1 unused, 1 for SOF, 1 for EOF if last line is incomplete */\n for (s = buffer; (s = (char *) memchr (s, '\\n', lim - s)); s++)\n if (++iline < 0)\n too_many_lines (filename);\n if (! (iline == (size_t) iline\n\t && (size_t) iline * sizeof *ptr / sizeof *ptr == (size_t) iline\n\t && (ptr = (char const **) malloc ((size_t) iline * sizeof *ptr))))\n {\n free (buffer);\n return false;\n }\n iline = 0;\n for (s = buffer; ; s++)\n {\n ptr[++iline] = s;\n if (! (s = (char *) memchr (s, '\\n', lim - s)))\n\tbreak;\n }\n if (size && lim[-1] != '\\n')\n ptr[++iline] = lim;\n input_lines = iline - 1;\n\n if (revision)\n {\n char const *rev = revision;\n int rev0 = rev[0];\n bool found_revision = false;\n size_t revlen = strlen (rev);\n\n if (revlen <= size)\n\t{\n\t char const *limrev = lim - revlen;\n\n\t for (s = buffer; (s = (char *) memchr (s, rev0, limrev - s)); s++)\n\t if (memcmp (s, rev, revlen) == 0\n\t\t&& (s == buffer || ISSPACE ((unsigned char) s[-1]))\n\t\t&& (s + 1 == limrev || ISSPACE ((unsigned char) s[revlen])))\n\t {\n\t\tfound_revision = true;\n\t\tbreak;\n\t }\n\t}\n\n report_revision (found_revision);\n }\n\n /* Plan A will work. */\n i_buffer = buffer;\n i_ptr = ptr;\n return true;\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 void setup_format_params(int track)\n{\n\tint n;\n\tint il;\n\tint count;\n\tint head_shift;\n\tint track_shift;\n\tstruct fparm {\n\t\tunsigned char track, head, sect, size;\n\t} *here = (struct fparm *)floppy_track_buffer;\n\n\traw_cmd = &default_raw_cmd;\n\traw_cmd->track = track;\n\n\traw_cmd->flags = (FD_RAW_WRITE | FD_RAW_INTR | FD_RAW_SPIN |\n\t\t\t FD_RAW_NEED_DISK | FD_RAW_NEED_SEEK);\n\traw_cmd->rate = _floppy->rate & 0x43;\n\traw_cmd->cmd_count = NR_F;\n\tCOMMAND = FM_MODE(_floppy, FD_FORMAT);\n\tDR_SELECT = UNIT(current_drive) + PH_HEAD(_floppy, format_req.head);\n\tF_SIZECODE = FD_SIZECODE(_floppy);\n\tF_SECT_PER_TRACK = _floppy->sect << 2 >> F_SIZECODE;\n\tF_GAP = _floppy->fmt_gap;\n\tF_FILL = FD_FILL_BYTE;\n\n\traw_cmd->kernel_data = floppy_track_buffer;\n\traw_cmd->length = 4 * F_SECT_PER_TRACK;\n\n\t/* allow for about 30ms for data transport per track */\n\thead_shift = (F_SECT_PER_TRACK + 5) / 6;\n\n\t/* a ``cylinder'' is two tracks plus a little stepping time */\n\ttrack_shift = 2 * head_shift + 3;\n\n\t/* position of logical sector 1 on this track */\n\tn = (track_shift * format_req.track + head_shift * format_req.head)\n\t % F_SECT_PER_TRACK;\n\n\t/* determine interleave */\n\til = 1;\n\tif (_floppy->fmt_gap < 0x22)\n\t\til++;\n\n\t/* initialize field */\n\tfor (count = 0; count < F_SECT_PER_TRACK; ++count) {\n\t\there[count].track = format_req.track;\n\t\there[count].head = format_req.head;\n\t\there[count].sect = 0;\n\t\there[count].size = F_SIZECODE;\n\t}\n\t/* place logical sectors */\n\tfor (count = 1; count <= F_SECT_PER_TRACK; ++count) {\n\t\there[n].sect = count;\n\t\tn = (n + il) % F_SECT_PER_TRACK;\n\t\tif (here[n].sect) {\t/* sector busy, find next free sector */\n\t\t\t++n;\n\t\t\tif (n >= F_SECT_PER_TRACK) {\n\t\t\t\tn -= F_SECT_PER_TRACK;\n\t\t\t\twhile (here[n].sect)\n\t\t\t\t\t++n;\n\t\t\t}\n\t\t}\n\t}\n\tif (_floppy->stretch & FD_SECTBASEMASK) {\n\t\tfor (count = 0; count < F_SECT_PER_TRACK; count++)\n\t\t\there[count].sect += FD_SECTBASE(_floppy) - 1;\n\t}\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: \n CImg& _load_bmp(std::FILE *const file, const char *const filename) {\n if (!file && !filename)\n throw CImgArgumentException(_cimg_instance\n \"load_bmp(): Specified filename is (null).\",\n cimg_instance);\n\n std::FILE *const nfile = file?file:cimg::fopen(filename,\"rb\");\n CImg header(54);\n cimg::fread(header._data,54,nfile);\n if (*header!='B' || header[1]!='M') {\n if (!file) cimg::fclose(nfile);\n throw CImgIOException(_cimg_instance\n \"load_bmp(): Invalid BMP file '%s'.\",\n cimg_instance,\n filename?filename:\"(FILE*)\");\n }\n\n // Read header and pixel buffer\n int\n file_size = header[0x02] + (header[0x03]<<8) + (header[0x04]<<16) + (header[0x05]<<24),\n offset = header[0x0A] + (header[0x0B]<<8) + (header[0x0C]<<16) + (header[0x0D]<<24),\n header_size = header[0x0E] + (header[0x0F]<<8) + (header[0x10]<<16) + (header[0x11]<<24),\n dx = header[0x12] + (header[0x13]<<8) + (header[0x14]<<16) + (header[0x15]<<24),\n dy = header[0x16] + (header[0x17]<<8) + (header[0x18]<<16) + (header[0x19]<<24),\n compression = header[0x1E] + (header[0x1F]<<8) + (header[0x20]<<16) + (header[0x21]<<24),\n nb_colors = header[0x2E] + (header[0x2F]<<8) + (header[0x30]<<16) + (header[0x31]<<24),\n bpp = header[0x1C] + (header[0x1D]<<8);\n\n if (!file_size || file_size==offset) {\n cimg::fseek(nfile,0,SEEK_END);\n file_size = (int)cimg::ftell(nfile);\n cimg::fseek(nfile,54,SEEK_SET);\n }\n if (header_size>40) cimg::fseek(nfile,header_size - 40,SEEK_CUR);\n\n const int\n dx_bytes = (bpp==1)?(dx/8 + (dx%8?1:0)):((bpp==4)?(dx/2 + (dx%2)):(int)((longT)dx*bpp/8)),\n align_bytes = (4 - dx_bytes%4)%4;\n const ulongT\n cimg_iobuffer = (ulongT)24*1024*1024,\n buf_size = std::min((ulongT)cimg::abs(dy)*(dx_bytes + align_bytes),(ulongT)file_size - offset);\n\n CImg colormap;\n if (bpp<16) { if (!nb_colors) nb_colors = 1<0) cimg::fseek(nfile,xoffset,SEEK_CUR);\n\n CImg buffer;\n if (buf_size=2) for (int y = height() - 1; y>=0; --y) {\n if (buf_size>=cimg_iobuffer) {\n if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break;\n cimg::fseek(nfile,align_bytes,SEEK_CUR);\n }\n unsigned char mask = 0x80, val = 0;\n cimg_forX(*this,x) {\n if (mask==0x80) val = *(ptrs++);\n const unsigned char *col = (unsigned char*)(colormap._data + (val&mask?1:0));\n (*this)(x,y,2) = (T)*(col++);\n (*this)(x,y,1) = (T)*(col++);\n (*this)(x,y,0) = (T)*(col++);\n mask = cimg::ror(mask);\n }\n ptrs+=align_bytes;\n }\n } break;\n case 4 : { // 16 colors\n if (colormap._width>=16) for (int y = height() - 1; y>=0; --y) {\n if (buf_size>=cimg_iobuffer) {\n if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break;\n cimg::fseek(nfile,align_bytes,SEEK_CUR);\n }\n unsigned char mask = 0xF0, val = 0;\n cimg_forX(*this,x) {\n if (mask==0xF0) val = *(ptrs++);\n const unsigned char color = (unsigned char)((mask<16)?(val&mask):((val&mask)>>4));\n const unsigned char *col = (unsigned char*)(colormap._data + color);\n (*this)(x,y,2) = (T)*(col++);\n (*this)(x,y,1) = (T)*(col++);\n (*this)(x,y,0) = (T)*(col++);\n mask = cimg::ror(mask,4);\n }\n ptrs+=align_bytes;\n }\n } break;\n case 8 : { // 256 colors\n if (colormap._width>=256) for (int y = height() - 1; y>=0; --y) {\n if (buf_size>=cimg_iobuffer) {\n if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break;\n cimg::fseek(nfile,align_bytes,SEEK_CUR);\n }\n cimg_forX(*this,x) {\n const unsigned char *col = (unsigned char*)(colormap._data + *(ptrs++));\n (*this)(x,y,2) = (T)*(col++);\n (*this)(x,y,1) = (T)*(col++);\n (*this)(x,y,0) = (T)*(col++);\n }\n ptrs+=align_bytes;\n }\n } break;\n case 16 : { // 16 bits colors\n for (int y = height() - 1; y>=0; --y) {\n if (buf_size>=cimg_iobuffer) {\n if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break;\n cimg::fseek(nfile,align_bytes,SEEK_CUR);\n }\n cimg_forX(*this,x) {\n const unsigned char c1 = *(ptrs++), c2 = *(ptrs++);\n const unsigned short col = (unsigned short)(c1|(c2<<8));\n (*this)(x,y,2) = (T)(col&0x1F);\n (*this)(x,y,1) = (T)((col>>5)&0x1F);\n (*this)(x,y,0) = (T)((col>>10)&0x1F);\n }\n ptrs+=align_bytes;\n }\n } break;\n case 24 : { // 24 bits colors\n for (int y = height() - 1; y>=0; --y) {\n if (buf_size>=cimg_iobuffer) {\n if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break;\n cimg::fseek(nfile,align_bytes,SEEK_CUR);\n }\n cimg_forX(*this,x) {\n (*this)(x,y,2) = (T)*(ptrs++);\n (*this)(x,y,1) = (T)*(ptrs++);\n (*this)(x,y,0) = (T)*(ptrs++);\n }\n ptrs+=align_bytes;\n }\n } break;\n case 32 : { // 32 bits colors\n for (int y = height() - 1; y>=0; --y) {\n if (buf_size>=cimg_iobuffer) {\n if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break;\n cimg::fseek(nfile,align_bytes,SEEK_CUR);\n }\n cimg_forX(*this,x) {\n (*this)(x,y,2) = (T)*(ptrs++);\n (*this)(x,y,1) = (T)*(ptrs++);\n (*this)(x,y,0) = (T)*(ptrs++);\n ++ptrs;\n }\n ptrs+=align_bytes;\n }\n } break;\n }\n if (dy<0) mirror('y');\n if (!file) cimg::fclose(nfile);\n return *this; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], '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: cupsdReadClient(cupsd_client_t *con)\t/* I - Client to read from */\n{\n char\t\t\tline[32768],\t/* Line from client... */\n\t\t\tlocale[64],\t/* Locale */\n\t\t\t*ptr;\t\t/* Pointer into strings */\n http_status_t\t\tstatus;\t\t/* Transfer status */\n ipp_state_t\t\tipp_state;\t/* State of IPP transfer */\n int\t\t\tbytes;\t\t/* Number of bytes to POST */\n char\t\t\t*filename;\t/* Name of file for GET/HEAD */\n char\t\t\tbuf[1024];\t/* Buffer for real filename */\n struct stat\t\tfilestats;\t/* File information */\n mime_type_t\t\t*type;\t\t/* MIME type of file */\n cupsd_printer_t\t*p;\t\t/* Printer */\n static unsigned\trequest_id = 0;\t/* Request ID for temp files */\n\n\n status = HTTP_STATUS_CONTINUE;\n\n cupsdLogClient(con, CUPSD_LOG_DEBUG2, \"cupsdReadClient: error=%d, used=%d, state=%s, data_encoding=HTTP_ENCODING_%s, data_remaining=\" CUPS_LLFMT \", request=%p(%s), file=%d\", httpError(con->http), (int)httpGetReady(con->http), httpStateString(httpGetState(con->http)), httpIsChunked(con->http) ? \"CHUNKED\" : \"LENGTH\", CUPS_LLCAST httpGetRemaining(con->http), con->request, con->request ? ippStateString(ippGetState(con->request)) : \"\", con->file);\n\n if (httpGetState(con->http) == HTTP_STATE_GET_SEND ||\n httpGetState(con->http) == HTTP_STATE_POST_SEND ||\n httpGetState(con->http) == HTTP_STATE_STATUS)\n {\n /*\n * If we get called in the wrong state, then something went wrong with the\n * connection and we need to shut it down...\n */\n\n if (!httpGetReady(con->http) && recv(httpGetFd(con->http), buf, 1, MSG_PEEK) < 1)\n {\n /*\n * Connection closed...\n */\n\n cupsdLogClient(con, CUPSD_LOG_DEBUG, \"Closing on EOF.\");\n cupsdCloseClient(con);\n return;\n }\n\n cupsdLogClient(con, CUPSD_LOG_DEBUG, \"Closing on unexpected HTTP read state %s.\", httpStateString(httpGetState(con->http)));\n cupsdCloseClient(con);\n return;\n }\n\n#ifdef HAVE_SSL\n if (con->auto_ssl)\n {\n /*\n * Automatically check for a SSL/TLS handshake...\n */\n\n con->auto_ssl = 0;\n\n if (recv(httpGetFd(con->http), buf, 1, MSG_PEEK) == 1 &&\n (!buf[0] || !strchr(\"DGHOPT\", buf[0])))\n {\n /*\n * Encrypt this connection...\n */\n\n cupsdLogClient(con, CUPSD_LOG_DEBUG2, \"Saw first byte %02X, auto-negotiating SSL/TLS session.\", buf[0] & 255);\n\n if (cupsd_start_tls(con, HTTP_ENCRYPTION_ALWAYS))\n cupsdCloseClient(con);\n\n return;\n }\n }\n#endif /* HAVE_SSL */\n\n switch (httpGetState(con->http))\n {\n case HTTP_STATE_WAITING :\n /*\n * See if we've received a request line...\n\t*/\n\n con->operation = httpReadRequest(con->http, con->uri, sizeof(con->uri));\n if (con->operation == HTTP_STATE_ERROR ||\n\t con->operation == HTTP_STATE_UNKNOWN_METHOD ||\n\t con->operation == HTTP_STATE_UNKNOWN_VERSION)\n\t{\n\t if (httpError(con->http))\n\t cupsdLogClient(con, CUPSD_LOG_DEBUG,\n\t\t\t \"HTTP_STATE_WAITING Closing for error %d (%s)\",\n\t\t\t httpError(con->http), strerror(httpError(con->http)));\n\t else\n\t cupsdLogClient(con, CUPSD_LOG_DEBUG,\n\t \"HTTP_STATE_WAITING Closing on error: %s\",\n\t\t\t cupsLastErrorString());\n\n\t cupsdCloseClient(con);\n\t return;\n\t}\n\n /*\n * Ignore blank request lines...\n\t*/\n\n if (con->operation == HTTP_STATE_WAITING)\n\t break;\n\n /*\n * Clear other state variables...\n\t*/\n\n\tcon->bytes = 0;\n\tcon->file = -1;\n\tcon->file_ready = 0;\n\tcon->pipe_pid = 0;\n\tcon->username[0] = '\\0';\n\tcon->password[0] = '\\0';\n\n\tcupsdClearString(&con->command);\n\tcupsdClearString(&con->options);\n\tcupsdClearString(&con->query_string);\n\n\tif (con->request)\n\t{\n\t ippDelete(con->request);\n\t con->request = NULL;\n\t}\n\n\tif (con->response)\n\t{\n\t ippDelete(con->response);\n\t con->response = NULL;\n\t}\n\n\tif (con->language)\n\t{\n\t cupsLangFree(con->language);\n\t con->language = NULL;\n\t}\n\n#ifdef HAVE_GSSAPI\n con->have_gss = 0;\n\tcon->gss_uid = 0;\n#endif /* HAVE_GSSAPI */\n\n /*\n * Handle full URLs in the request line...\n\t*/\n\n if (strcmp(con->uri, \"*\"))\n\t{\n\t char\tscheme[HTTP_MAX_URI],\t/* Method/scheme */\n\t\tuserpass[HTTP_MAX_URI],\t/* Username:password */\n\t\thostname[HTTP_MAX_URI],\t/* Hostname */\n\t\tresource[HTTP_MAX_URI];\t/* Resource path */\n int\tport;\t\t\t/* Port number */\n\n /*\n\t * Separate the URI into its components...\n\t */\n\n if (httpSeparateURI(HTTP_URI_CODING_MOST, con->uri,\n\t scheme, sizeof(scheme),\n\t userpass, sizeof(userpass),\n\t\t\t hostname, sizeof(hostname), &port,\n\t\t\t resource, sizeof(resource)) < HTTP_URI_STATUS_OK)\n {\n\t cupsdLogClient(con, CUPSD_LOG_ERROR, \"Bad URI \\\"%s\\\" in request.\",\n con->uri);\n\t cupsdSendError(con, HTTP_STATUS_METHOD_NOT_ALLOWED, CUPSD_AUTH_NONE);\n\t cupsdCloseClient(con);\n\t return;\n\t }\n\n\t /*\n\t * Only allow URIs with the servername, localhost, or an IP\n\t * address...\n\t */\n\n\t if (strcmp(scheme, \"file\") &&\n\t _cups_strcasecmp(hostname, ServerName) &&\n\t _cups_strcasecmp(hostname, \"localhost\") &&\n\t !cupsArrayFind(ServerAlias, hostname) &&\n\t !isdigit(hostname[0]) && hostname[0] != '[')\n\t {\n\t /*\n\t * Nope, we don't do proxies...\n\t */\n\n\t cupsdLogClient(con, CUPSD_LOG_ERROR, \"Bad URI \\\"%s\\\" in request.\",\n con->uri);\n\t cupsdSendError(con, HTTP_STATUS_METHOD_NOT_ALLOWED, CUPSD_AUTH_NONE);\n\t cupsdCloseClient(con);\n\t return;\n\t }\n\n /*\n\t * Copy the resource portion back into the URI; both resource and\n\t * con->uri are HTTP_MAX_URI bytes in size...\n\t */\n\n strlcpy(con->uri, resource, sizeof(con->uri));\n\t}\n\n /*\n * Process the request...\n\t*/\n\n gettimeofday(&(con->start), NULL);\n\n cupsdLogClient(con, CUPSD_LOG_DEBUG, \"%s %s HTTP/%d.%d\",\n\t httpStateString(con->operation) + 11, con->uri,\n\t\t httpGetVersion(con->http) / 100,\n httpGetVersion(con->http) % 100);\n\n if (!cupsArrayFind(ActiveClients, con))\n\t{\n\t cupsArrayAdd(ActiveClients, con);\n cupsdSetBusyState(0);\n }\n\n case HTTP_STATE_OPTIONS :\n case HTTP_STATE_DELETE :\n case HTTP_STATE_GET :\n case HTTP_STATE_HEAD :\n case HTTP_STATE_POST :\n case HTTP_STATE_PUT :\n case HTTP_STATE_TRACE :\n /*\n * Parse incoming parameters until the status changes...\n\t*/\n\n while ((status = httpUpdate(con->http)) == HTTP_STATUS_CONTINUE)\n\t if (!httpGetReady(con->http))\n\t break;\n\n\tif (status != HTTP_STATUS_OK && status != HTTP_STATUS_CONTINUE)\n\t{\n\t if (httpError(con->http) && httpError(con->http) != EPIPE)\n\t cupsdLogClient(con, CUPSD_LOG_DEBUG,\n \"Closing for error %d (%s) while reading headers.\",\n httpError(con->http), strerror(httpError(con->http)));\n\t else\n\t cupsdLogClient(con, CUPSD_LOG_DEBUG,\n\t \"Closing on EOF while reading headers.\");\n\n\t cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE);\n\t cupsdCloseClient(con);\n\t return;\n\t}\n\tbreak;\n\n default :\n if (!httpGetReady(con->http) && recv(httpGetFd(con->http), buf, 1, MSG_PEEK) < 1)\n\t{\n\t /*\n\t * Connection closed...\n\t */\n\n\t cupsdLogClient(con, CUPSD_LOG_DEBUG, \"Closing on EOF.\");\n cupsdCloseClient(con);\n\t return;\n\t}\n break; /* Anti-compiler-warning-code */\n }\n\n /*\n * Handle new transfers...\n */\n\n cupsdLogClient(con, CUPSD_LOG_DEBUG, \"Read: status=%d, state=%d\", status, httpGetState(con->http));\n\n if (status == HTTP_STATUS_OK)\n {\n /*\n * Record whether the client is a web browser. \"Mozilla\" was the original\n * and it seems that every web browser in existence now uses that as the\n * prefix with additional information identifying *which* browser.\n *\n * Chrome (at least) has problems with multiple WWW-Authenticate values in\n * a single header, so we only report Basic or Negotiate to web browsers and\n * leave the multiple choices to the native CUPS client...\n */\n\n con->is_browser = !strncmp(httpGetField(con->http, HTTP_FIELD_USER_AGENT), \"Mozilla/\", 8);\n\n if (httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE)[0])\n {\n /*\n * Figure out the locale from the Accept-Language and Content-Type\n * fields...\n */\n\n if ((ptr = strchr(httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE),\n ',')) != NULL)\n *ptr = '\\0';\n\n if ((ptr = strchr(httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE),\n ';')) != NULL)\n *ptr = '\\0';\n\n if ((ptr = strstr(httpGetField(con->http, HTTP_FIELD_CONTENT_TYPE),\n \"charset=\")) != NULL)\n {\n /*\n * Combine language and charset, and trim any extra params in the\n\t* content-type.\n\t*/\n\n snprintf(locale, sizeof(locale), \"%s.%s\",\n\t httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE), ptr + 8);\n\n\tif ((ptr = strchr(locale, ',')) != NULL)\n\t *ptr = '\\0';\n }\n else\n snprintf(locale, sizeof(locale), \"%s.UTF-8\",\n\t httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE));\n\n con->language = cupsLangGet(locale);\n }\n else\n con->language = cupsLangGet(DefaultLocale);\n\n cupsdAuthorize(con);\n\n if (!_cups_strncasecmp(httpGetField(con->http, HTTP_FIELD_CONNECTION),\n \"Keep-Alive\", 10) && KeepAlive)\n httpSetKeepAlive(con->http, HTTP_KEEPALIVE_ON);\n else if (!_cups_strncasecmp(httpGetField(con->http, HTTP_FIELD_CONNECTION),\n \"close\", 5))\n httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);\n\n if (!httpGetField(con->http, HTTP_FIELD_HOST)[0] &&\n httpGetVersion(con->http) >= HTTP_VERSION_1_1)\n {\n /*\n * HTTP/1.1 and higher require the \"Host:\" field...\n */\n\n if (!cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE))\n {\n cupsdLogClient(con, CUPSD_LOG_ERROR, \"Missing Host: field in request.\");\n\tcupsdCloseClient(con);\n\treturn;\n }\n }\n else if (!valid_host(con))\n {\n /*\n * Access to localhost must use \"localhost\" or the corresponding IPv4\n * or IPv6 values in the Host: field.\n */\n\n cupsdLogClient(con, CUPSD_LOG_ERROR,\n \"Request from \\\"%s\\\" using invalid Host: field \\\"%s\\\".\",\n httpGetHostname(con->http, NULL, 0), httpGetField(con->http, HTTP_FIELD_HOST));\n\n if (!cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE))\n {\n\tcupsdCloseClient(con);\n\treturn;\n }\n }\n else if (con->operation == HTTP_STATE_OPTIONS)\n {\n /*\n * Do OPTIONS command...\n */\n\n if (con->best && con->best->type != CUPSD_AUTH_NONE)\n {\n httpClearFields(con->http);\n\n\tif (!cupsdSendHeader(con, HTTP_STATUS_UNAUTHORIZED, NULL, CUPSD_AUTH_NONE))\n\t{\n\t cupsdCloseClient(con);\n\t return;\n\t}\n }\n\n if (!_cups_strcasecmp(httpGetField(con->http, HTTP_FIELD_CONNECTION), \"Upgrade\") && strstr(httpGetField(con->http, HTTP_FIELD_UPGRADE), \"TLS/\") != NULL && !httpIsEncrypted(con->http))\n {\n#ifdef HAVE_SSL\n /*\n * Do encryption stuff...\n\t*/\n\n httpClearFields(con->http);\n\n\tif (!cupsdSendHeader(con, HTTP_STATUS_SWITCHING_PROTOCOLS, NULL, CUPSD_AUTH_NONE))\n\t{\n\t cupsdCloseClient(con);\n\t return;\n\t}\n\n if (cupsd_start_tls(con, HTTP_ENCRYPTION_REQUIRED))\n {\n\t cupsdCloseClient(con);\n\t return;\n\t}\n#else\n\tif (!cupsdSendError(con, HTTP_STATUS_NOT_IMPLEMENTED, CUPSD_AUTH_NONE))\n\t{\n\t cupsdCloseClient(con);\n\t return;\n\t}\n#endif /* HAVE_SSL */\n }\n\n httpClearFields(con->http);\n httpSetField(con->http, HTTP_FIELD_ALLOW,\n\t\t \"GET, HEAD, OPTIONS, POST, PUT\");\n httpSetField(con->http, HTTP_FIELD_CONTENT_LENGTH, \"0\");\n\n if (!cupsdSendHeader(con, HTTP_STATUS_OK, NULL, CUPSD_AUTH_NONE))\n {\n\tcupsdCloseClient(con);\n\treturn;\n }\n }\n else if (!is_path_absolute(con->uri))\n {\n /*\n * Protect against malicious users!\n */\n\n cupsdLogClient(con, CUPSD_LOG_ERROR,\n \"Request for non-absolute resource \\\"%s\\\".\", con->uri);\n\n if (!cupsdSendError(con, HTTP_STATUS_FORBIDDEN, CUPSD_AUTH_NONE))\n {\n\tcupsdCloseClient(con);\n\treturn;\n }\n }\n else\n {\n if (!_cups_strcasecmp(httpGetField(con->http, HTTP_FIELD_CONNECTION),\n \"Upgrade\") && !httpIsEncrypted(con->http))\n {\n#ifdef HAVE_SSL\n /*\n * Do encryption stuff...\n\t*/\n\n httpClearFields(con->http);\n\n\tif (!cupsdSendHeader(con, HTTP_STATUS_SWITCHING_PROTOCOLS, NULL,\n\t CUPSD_AUTH_NONE))\n\t{\n\t cupsdCloseClient(con);\n\t return;\n\t}\n\n if (cupsd_start_tls(con, HTTP_ENCRYPTION_REQUIRED))\n {\n\t cupsdCloseClient(con);\n\t return;\n\t}\n#else\n\tif (!cupsdSendError(con, HTTP_STATUS_NOT_IMPLEMENTED, CUPSD_AUTH_NONE))\n\t{\n\t cupsdCloseClient(con);\n\t return;\n\t}\n#endif /* HAVE_SSL */\n }\n\n if ((status = cupsdIsAuthorized(con, NULL)) != HTTP_STATUS_OK)\n {\n\tcupsdSendError(con, status, CUPSD_AUTH_NONE);\n\tcupsdCloseClient(con);\n\treturn;\n }\n\n if (httpGetExpect(con->http) &&\n (con->operation == HTTP_STATE_POST || con->operation == HTTP_STATE_PUT))\n {\n if (httpGetExpect(con->http) == HTTP_STATUS_CONTINUE)\n\t{\n\t /*\n\t * Send 100-continue header...\n\t */\n\n if (httpWriteResponse(con->http, HTTP_STATUS_CONTINUE))\n\t {\n\t cupsdCloseClient(con);\n\t return;\n\t }\n\t}\n\telse\n\t{\n\t /*\n\t * Send 417-expectation-failed header...\n\t */\n\n httpClearFields(con->http);\n\t httpSetField(con->http, HTTP_FIELD_CONTENT_LENGTH, \"0\");\n\n\t cupsdSendError(con, HTTP_STATUS_EXPECTATION_FAILED, CUPSD_AUTH_NONE);\n cupsdCloseClient(con);\n return;\n\t}\n }\n\n switch (httpGetState(con->http))\n {\n\tcase HTTP_STATE_GET_SEND :\n cupsdLogClient(con, CUPSD_LOG_DEBUG, \"Processing GET %s\", con->uri);\n\n if ((!strncmp(con->uri, \"/ppd/\", 5) ||\n\t\t !strncmp(con->uri, \"/printers/\", 10) ||\n\t\t !strncmp(con->uri, \"/classes/\", 9)) &&\n\t\t!strcmp(con->uri + strlen(con->uri) - 4, \".ppd\"))\n\t {\n\t /*\n\t * Send PPD file - get the real printer name since printer\n\t * names are not case sensitive but filenames can be...\n\t */\n\n con->uri[strlen(con->uri) - 4] = '\\0';\t/* Drop \".ppd\" */\n\n\t if (!strncmp(con->uri, \"/ppd/\", 5))\n\t\tp = cupsdFindPrinter(con->uri + 5);\n\t else if (!strncmp(con->uri, \"/printers/\", 10))\n\t\tp = cupsdFindPrinter(con->uri + 10);\n\t else\n\t {\n\t\tp = cupsdFindClass(con->uri + 9);\n\n\t\tif (p)\n\t\t{\n\t\t int i;\t\t/* Looping var */\n\n\t\t for (i = 0; i < p->num_printers; i ++)\n\t\t {\n\t\t if (!(p->printers[i]->type & CUPS_PRINTER_CLASS))\n\t\t {\n\t\t char ppdname[1024];/* PPD filename */\n\n\t\t snprintf(ppdname, sizeof(ppdname), \"%s/ppd/%s.ppd\",\n\t\t ServerRoot, p->printers[i]->name);\n\t\t if (!access(ppdname, 0))\n\t\t {\n\t\t p = p->printers[i];\n\t\t break;\n\t\t }\n\t\t }\n\t\t }\n\n if (i >= p->num_printers)\n p = NULL;\n\t\t}\n\t }\n\n\t if (p)\n\t {\n\t\tsnprintf(con->uri, sizeof(con->uri), \"/ppd/%s.ppd\", p->name);\n\t }\n\t else\n\t {\n\t\tif (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))\n\t\t{\n\t\t cupsdCloseClient(con);\n\t\t return;\n\t\t}\n\n\t\tbreak;\n\t }\n\t }\n else if ((!strncmp(con->uri, \"/icons/\", 7) ||\n\t\t !strncmp(con->uri, \"/printers/\", 10) ||\n\t\t !strncmp(con->uri, \"/classes/\", 9)) &&\n\t\t !strcmp(con->uri + strlen(con->uri) - 4, \".png\"))\n\t {\n\t /*\n\t * Send icon file - get the real queue name since queue names are\n\t * not case sensitive but filenames can be...\n\t */\n\n\t con->uri[strlen(con->uri) - 4] = '\\0';\t/* Drop \".png\" */\n\n if (!strncmp(con->uri, \"/icons/\", 7))\n p = cupsdFindPrinter(con->uri + 7);\n else if (!strncmp(con->uri, \"/printers/\", 10))\n p = cupsdFindPrinter(con->uri + 10);\n else\n {\n\t\tp = cupsdFindClass(con->uri + 9);\n\n\t\tif (p)\n\t\t{\n\t\t int i;\t\t/* Looping var */\n\n\t\t for (i = 0; i < p->num_printers; i ++)\n\t\t {\n\t\t if (!(p->printers[i]->type & CUPS_PRINTER_CLASS))\n\t\t {\n\t\t char ppdname[1024];/* PPD filename */\n\n\t\t snprintf(ppdname, sizeof(ppdname), \"%s/ppd/%s.ppd\",\n\t\t ServerRoot, p->printers[i]->name);\n\t\t if (!access(ppdname, 0))\n\t\t {\n\t\t p = p->printers[i];\n\t\t break;\n\t\t }\n\t\t }\n\t\t }\n\n if (i >= p->num_printers)\n p = NULL;\n\t\t}\n\t }\n\n if (p)\n\t\tsnprintf(con->uri, sizeof(con->uri), \"/icons/%s.png\", p->name);\n\t else\n\t {\n\t\tif (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))\n\t\t{\n\t\t cupsdCloseClient(con);\n\t\t return;\n\t\t}\n\n\t\tbreak;\n\t }\n\t }\n\n\t if ((!strncmp(con->uri, \"/admin\", 6) && strcmp(con->uri, \"/admin/conf/cupsd.conf\") && strncmp(con->uri, \"/admin/log/\", 11)) ||\n\t\t !strncmp(con->uri, \"/printers\", 9) ||\n\t\t !strncmp(con->uri, \"/classes\", 8) ||\n\t\t !strncmp(con->uri, \"/help\", 5) ||\n\t\t !strncmp(con->uri, \"/jobs\", 5))\n\t {\n\t if (!WebInterface)\n\t {\n\t /*\n\t\t* Web interface is disabled. Show an appropriate message...\n\t\t*/\n\n\t\tif (!cupsdSendError(con, HTTP_STATUS_CUPS_WEBIF_DISABLED, CUPSD_AUTH_NONE))\n\t\t{\n\t\t cupsdCloseClient(con);\n\t\t return;\n\t\t}\n\n\t\tbreak;\n\t }\n\n\t /*\n\t * Send CGI output...\n\t */\n\n if (!strncmp(con->uri, \"/admin\", 6))\n\t {\n\t\tcupsdSetStringf(&con->command, \"%s/cgi-bin/admin.cgi\",\n\t\t ServerBin);\n\n\t\tcupsdSetString(&con->options, strchr(con->uri + 6, '?'));\n\t }\n else if (!strncmp(con->uri, \"/printers\", 9))\n\t {\n\t\tcupsdSetStringf(&con->command, \"%s/cgi-bin/printers.cgi\",\n\t\t ServerBin);\n\n if (con->uri[9] && con->uri[10])\n\t\t cupsdSetString(&con->options, con->uri + 9);\n\t\telse\n\t\t cupsdSetString(&con->options, NULL);\n\t }\n\t else if (!strncmp(con->uri, \"/classes\", 8))\n\t {\n\t\tcupsdSetStringf(&con->command, \"%s/cgi-bin/classes.cgi\",\n\t\t ServerBin);\n\n if (con->uri[8] && con->uri[9])\n\t\t cupsdSetString(&con->options, con->uri + 8);\n\t\telse\n\t\t cupsdSetString(&con->options, NULL);\n\t }\n\t else if (!strncmp(con->uri, \"/jobs\", 5))\n\t {\n\t\tcupsdSetStringf(&con->command, \"%s/cgi-bin/jobs.cgi\",\n\t\t ServerBin);\n\n if (con->uri[5] && con->uri[6])\n\t\t cupsdSetString(&con->options, con->uri + 5);\n\t\telse\n\t\t cupsdSetString(&con->options, NULL);\n\t }\n\t else\n\t {\n\t\tcupsdSetStringf(&con->command, \"%s/cgi-bin/help.cgi\",\n\t\t ServerBin);\n\n if (con->uri[5] && con->uri[6])\n\t\t cupsdSetString(&con->options, con->uri + 5);\n\t\telse\n\t\t cupsdSetString(&con->options, NULL);\n\t }\n\n if (!cupsdSendCommand(con, con->command, con->options, 0))\n\t {\n\t\tif (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))\n\t\t{\n\t\t cupsdCloseClient(con);\n\t\t return;\n\t\t}\n }\n\t else\n \tcupsdLogRequest(con, HTTP_STATUS_OK);\n\n\t if (httpGetVersion(con->http) <= HTTP_VERSION_1_0)\n\t\thttpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);\n\t }\n else if (!strncmp(con->uri, \"/admin/log/\", 11) && (strchr(con->uri + 11, '/') || strlen(con->uri) == 11))\n\t {\n\t /*\n\t * GET can only be done to configuration files directly under\n\t * /admin/conf...\n\t */\n\n\t cupsdLogClient(con, CUPSD_LOG_ERROR, \"Request for subdirectory \\\"%s\\\".\", con->uri);\n\n\t if (!cupsdSendError(con, HTTP_STATUS_FORBIDDEN, CUPSD_AUTH_NONE))\n\t {\n\t\tcupsdCloseClient(con);\n\t\treturn;\n\t }\n\n\t break;\n\t }\n\t else\n\t {\n\t /*\n\t * Serve a file...\n\t */\n\n if ((filename = get_file(con, &filestats, buf,\n\t sizeof(buf))) == NULL)\n\t {\n\t\tif (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))\n\t\t{\n\t\t cupsdCloseClient(con);\n\t\t return;\n\t\t}\n\n\t\tbreak;\n\t }\n\n\t type = mimeFileType(MimeDatabase, filename, NULL, NULL);\n\n cupsdLogClient(con, CUPSD_LOG_DEBUG, \"filename=\\\"%s\\\", type=%s/%s\", filename, type ? type->super : \"\", type ? type->type : \"\");\n\n if (is_cgi(con, filename, &filestats, type))\n\t {\n\t /*\n\t * Note: con->command and con->options were set by\n\t\t* is_cgi()...\n\t\t*/\n\n \tif (!cupsdSendCommand(con, con->command, con->options, 0))\n\t\t{\n\t\t if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))\n\t\t {\n\t\t cupsdCloseClient(con);\n\t\t return;\n\t\t }\n \t}\n\t\telse\n \t cupsdLogRequest(con, HTTP_STATUS_OK);\n\n\t\tif (httpGetVersion(con->http) <= HTTP_VERSION_1_0)\n\t\t httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);\n\t break;\n\t }\n\n\t if (!check_if_modified(con, &filestats))\n {\n \tif (!cupsdSendError(con, HTTP_STATUS_NOT_MODIFIED, CUPSD_AUTH_NONE))\n\t\t{\n\t\t cupsdCloseClient(con);\n\t\t return;\n\t\t}\n\t }\n\t else\n {\n\t\tif (type == NULL)\n\t strlcpy(line, \"text/plain\", sizeof(line));\n\t\telse\n\t snprintf(line, sizeof(line), \"%s/%s\", type->super, type->type);\n\n \tif (!write_file(con, HTTP_STATUS_OK, filename, line, &filestats))\n\t\t{\n\t\t cupsdCloseClient(con);\n\t\t return;\n\t\t}\n\t }\n\t }\n break;\n\n\tcase HTTP_STATE_POST_RECV :\n /*\n\t * See if the POST request includes a Content-Length field, and if\n\t * so check the length against any limits that are set...\n\t */\n\n if (httpGetField(con->http, HTTP_FIELD_CONTENT_LENGTH)[0] &&\n\t\tMaxRequestSize > 0 &&\n\t\thttpGetLength2(con->http) > MaxRequestSize)\n\t {\n\t /*\n\t * Request too large...\n\t */\n\n if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))\n\t {\n\t\tcupsdCloseClient(con);\n\t\treturn;\n\t }\n\n\t break;\n }\n\t else if (httpGetLength2(con->http) < 0)\n\t {\n\t /*\n\t * Negative content lengths are invalid!\n\t */\n\n if (!cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE))\n\t {\n\t\tcupsdCloseClient(con);\n\t\treturn;\n\t }\n\n\t break;\n\t }\n\n /*\n\t * See what kind of POST request this is; for IPP requests the\n\t * content-type field will be \"application/ipp\"...\n\t */\n\n\t if (!strcmp(httpGetField(con->http, HTTP_FIELD_CONTENT_TYPE),\n\t \"application/ipp\"))\n con->request = ippNew();\n else if (!WebInterface)\n\t {\n\t /*\n\t * Web interface is disabled. Show an appropriate message...\n\t */\n\n\t if (!cupsdSendError(con, HTTP_STATUS_CUPS_WEBIF_DISABLED, CUPSD_AUTH_NONE))\n\t {\n\t\tcupsdCloseClient(con);\n\t\treturn;\n\t }\n\n\t break;\n\t }\n\t else if ((!strncmp(con->uri, \"/admin\", 6) && strncmp(con->uri, \"/admin/log/\", 11)) ||\n\t !strncmp(con->uri, \"/printers\", 9) ||\n\t !strncmp(con->uri, \"/classes\", 8) ||\n\t !strncmp(con->uri, \"/help\", 5) ||\n\t !strncmp(con->uri, \"/jobs\", 5))\n\t {\n\t /*\n\t * CGI request...\n\t */\n\n if (!strncmp(con->uri, \"/admin\", 6))\n\t {\n\t\tcupsdSetStringf(&con->command, \"%s/cgi-bin/admin.cgi\",\n\t\t ServerBin);\n\n\t\tcupsdSetString(&con->options, strchr(con->uri + 6, '?'));\n\t }\n else if (!strncmp(con->uri, \"/printers\", 9))\n\t {\n\t\tcupsdSetStringf(&con->command, \"%s/cgi-bin/printers.cgi\",\n\t\t ServerBin);\n\n if (con->uri[9] && con->uri[10])\n\t\t cupsdSetString(&con->options, con->uri + 9);\n\t\telse\n\t\t cupsdSetString(&con->options, NULL);\n\t }\n\t else if (!strncmp(con->uri, \"/classes\", 8))\n\t {\n\t\tcupsdSetStringf(&con->command, \"%s/cgi-bin/classes.cgi\",\n\t\t ServerBin);\n\n if (con->uri[8] && con->uri[9])\n\t\t cupsdSetString(&con->options, con->uri + 8);\n\t\telse\n\t\t cupsdSetString(&con->options, NULL);\n\t }\n\t else if (!strncmp(con->uri, \"/jobs\", 5))\n\t {\n\t\tcupsdSetStringf(&con->command, \"%s/cgi-bin/jobs.cgi\",\n\t\t ServerBin);\n\n if (con->uri[5] && con->uri[6])\n\t\t cupsdSetString(&con->options, con->uri + 5);\n\t\telse\n\t\t cupsdSetString(&con->options, NULL);\n\t }\n\t else\n\t {\n\t\tcupsdSetStringf(&con->command, \"%s/cgi-bin/help.cgi\",\n\t\t ServerBin);\n\n if (con->uri[5] && con->uri[6])\n\t\t cupsdSetString(&con->options, con->uri + 5);\n\t\telse\n\t\t cupsdSetString(&con->options, NULL);\n\t }\n\n\t if (httpGetVersion(con->http) <= HTTP_VERSION_1_0)\n\t\thttpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);\n\t }\n\t else\n\t {\n\t /*\n\t * POST to a file...\n\t */\n\n if ((filename = get_file(con, &filestats, buf,\n\t sizeof(buf))) == NULL)\n\t {\n\t\tif (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))\n\t\t{\n\t\t cupsdCloseClient(con);\n\t\t return;\n\t\t}\n\n\t\tbreak;\n\t }\n\n\t type = mimeFileType(MimeDatabase, filename, NULL, NULL);\n\n if (!is_cgi(con, filename, &filestats, type))\n\t {\n\t /*\n\t * Only POST to CGI's...\n\t\t*/\n\n\t\tif (!cupsdSendError(con, HTTP_STATUS_UNAUTHORIZED, CUPSD_AUTH_NONE))\n\t\t{\n\t\t cupsdCloseClient(con);\n\t\t return;\n\t\t}\n\t }\n\t }\n\t break;\n\n\tcase HTTP_STATE_PUT_RECV :\n\t /*\n\t * Validate the resource name...\n\t */\n\n if (strcmp(con->uri, \"/admin/conf/cupsd.conf\"))\n\t {\n\t /*\n\t * PUT can only be done to the cupsd.conf file...\n\t */\n\n\t cupsdLogClient(con, CUPSD_LOG_ERROR,\n\t\t\t \"Disallowed PUT request for \\\"%s\\\".\", con->uri);\n\n\t if (!cupsdSendError(con, HTTP_STATUS_FORBIDDEN, CUPSD_AUTH_NONE))\n\t {\n\t\tcupsdCloseClient(con);\n\t\treturn;\n\t }\n\n\t break;\n\t }\n\n /*\n\t * See if the PUT request includes a Content-Length field, and if\n\t * so check the length against any limits that are set...\n\t */\n\n if (httpGetField(con->http, HTTP_FIELD_CONTENT_LENGTH)[0] &&\n\t\tMaxRequestSize > 0 &&\n\t\thttpGetLength2(con->http) > MaxRequestSize)\n\t {\n\t /*\n\t * Request too large...\n\t */\n\n if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))\n\t {\n\t\tcupsdCloseClient(con);\n\t\treturn;\n\t }\n\n\t break;\n }\n\t else if (httpGetLength2(con->http) < 0)\n\t {\n\t /*\n\t * Negative content lengths are invalid!\n\t */\n\n if (!cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE))\n\t {\n\t\tcupsdCloseClient(con);\n\t\treturn;\n\t }\n\n\t break;\n\t }\n\n /*\n\t * Open a temporary file to hold the request...\n\t */\n\n cupsdSetStringf(&con->filename, \"%s/%08x\", RequestRoot,\n\t request_id ++);\n\t con->file = open(con->filename, O_WRONLY | O_CREAT | O_TRUNC, 0640);\n\n\t if (con->file < 0)\n\t {\n\t cupsdLogClient(con, CUPSD_LOG_ERROR,\n\t \"Unable to create request file \\\"%s\\\": %s\",\n con->filename, strerror(errno));\n\n\t if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))\n\t {\n\t\tcupsdCloseClient(con);\n\t\treturn;\n\t }\n\t }\n\n\t fchmod(con->file, 0640);\n\t fchown(con->file, RunUser, Group);\n\t fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);\n\t break;\n\n\tcase HTTP_STATE_DELETE :\n\tcase HTTP_STATE_TRACE :\n cupsdSendError(con, HTTP_STATUS_NOT_IMPLEMENTED, CUPSD_AUTH_NONE);\n\t cupsdCloseClient(con);\n\t return;\n\n\tcase HTTP_STATE_HEAD :\n if (!strncmp(con->uri, \"/printers/\", 10) &&\n\t\t!strcmp(con->uri + strlen(con->uri) - 4, \".ppd\"))\n\t {\n\t /*\n\t * Send PPD file - get the real printer name since printer\n\t * names are not case sensitive but filenames can be...\n\t */\n\n con->uri[strlen(con->uri) - 4] = '\\0';\t/* Drop \".ppd\" */\n\n if ((p = cupsdFindPrinter(con->uri + 10)) != NULL)\n\t\tsnprintf(con->uri, sizeof(con->uri), \"/ppd/%s.ppd\", p->name);\n\t else\n\t {\n\t\tif (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))\n\t\t{\n\t\t cupsdCloseClient(con);\n\t\t return;\n\t\t}\n\n\t\tcupsdLogRequest(con, HTTP_STATUS_NOT_FOUND);\n\t\tbreak;\n\t }\n\t }\n else if (!strncmp(con->uri, \"/printers/\", 10) &&\n\t\t !strcmp(con->uri + strlen(con->uri) - 4, \".png\"))\n\t {\n\t /*\n\t * Send PNG file - get the real printer name since printer\n\t * names are not case sensitive but filenames can be...\n\t */\n\n con->uri[strlen(con->uri) - 4] = '\\0';\t/* Drop \".ppd\" */\n\n if ((p = cupsdFindPrinter(con->uri + 10)) != NULL)\n\t\tsnprintf(con->uri, sizeof(con->uri), \"/icons/%s.png\", p->name);\n\t else\n\t {\n\t\tif (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))\n\t\t{\n\t\t cupsdCloseClient(con);\n\t\t return;\n\t\t}\n\n\t\tcupsdLogRequest(con, HTTP_STATUS_NOT_FOUND);\n\t\tbreak;\n\t }\n\t }\n\t else if (!WebInterface)\n\t {\n httpClearFields(con->http);\n\n if (!cupsdSendHeader(con, HTTP_STATUS_OK, NULL, CUPSD_AUTH_NONE))\n\t {\n\t\tcupsdCloseClient(con);\n\t\treturn;\n\t }\n\n cupsdLogRequest(con, HTTP_STATUS_OK);\n\t break;\n\t }\n\n\t if ((!strncmp(con->uri, \"/admin\", 6) && strcmp(con->uri, \"/admin/conf/cupsd.conf\") && strncmp(con->uri, \"/admin/log/\", 11)) ||\n\t\t!strncmp(con->uri, \"/printers\", 9) ||\n\t\t!strncmp(con->uri, \"/classes\", 8) ||\n\t\t!strncmp(con->uri, \"/help\", 5) ||\n\t\t!strncmp(con->uri, \"/jobs\", 5))\n\t {\n\t /*\n\t * CGI output...\n\t */\n\n httpClearFields(con->http);\n\n if (!cupsdSendHeader(con, HTTP_STATUS_OK, \"text/html\", CUPSD_AUTH_NONE))\n\t {\n\t\tcupsdCloseClient(con);\n\t\treturn;\n\t }\n\n cupsdLogRequest(con, HTTP_STATUS_OK);\n\t }\n else if (!strncmp(con->uri, \"/admin/log/\", 11) && (strchr(con->uri + 11, '/') || strlen(con->uri) == 11))\n\t {\n\t /*\n\t * HEAD can only be done to configuration files under\n\t * /admin/conf...\n\t */\n\n\t cupsdLogClient(con, CUPSD_LOG_ERROR,\n\t\t\t \"Request for subdirectory \\\"%s\\\".\", con->uri);\n\n\t if (!cupsdSendError(con, HTTP_STATUS_FORBIDDEN, CUPSD_AUTH_NONE))\n\t {\n\t\tcupsdCloseClient(con);\n\t\treturn;\n\t }\n\n cupsdLogRequest(con, HTTP_STATUS_FORBIDDEN);\n\t break;\n\t }\n\t else if ((filename = get_file(con, &filestats, buf,\n\t sizeof(buf))) == NULL)\n\t {\n httpClearFields(con->http);\n\n\t if (!cupsdSendHeader(con, HTTP_STATUS_NOT_FOUND, \"text/html\",\n\t CUPSD_AUTH_NONE))\n\t {\n\t\tcupsdCloseClient(con);\n\t\treturn;\n\t }\n\n cupsdLogRequest(con, HTTP_STATUS_NOT_FOUND);\n\t }\n\t else if (!check_if_modified(con, &filestats))\n {\n if (!cupsdSendError(con, HTTP_STATUS_NOT_MODIFIED, CUPSD_AUTH_NONE))\n\t {\n\t\tcupsdCloseClient(con);\n\t\treturn;\n\t }\n\n cupsdLogRequest(con, HTTP_STATUS_NOT_MODIFIED);\n\t }\n\t else\n\t {\n\t /*\n\t * Serve a file...\n\t */\n\n\t type = mimeFileType(MimeDatabase, filename, NULL, NULL);\n\t if (type == NULL)\n\t\tstrlcpy(line, \"text/plain\", sizeof(line));\n\t else\n\t\tsnprintf(line, sizeof(line), \"%s/%s\", type->super, type->type);\n\n httpClearFields(con->http);\n\n\t httpSetField(con->http, HTTP_FIELD_LAST_MODIFIED,\n\t\t\t httpGetDateString(filestats.st_mtime));\n\t httpSetLength(con->http, (size_t)filestats.st_size);\n\n if (!cupsdSendHeader(con, HTTP_STATUS_OK, line, CUPSD_AUTH_NONE))\n\t {\n\t\tcupsdCloseClient(con);\n\t\treturn;\n\t }\n\n cupsdLogRequest(con, HTTP_STATUS_OK);\n\t }\n break;\n\n\tdefault :\n break; /* Anti-compiler-warning-code */\n }\n }\n }\n\n /*\n * Handle any incoming data...\n */\n\n switch (httpGetState(con->http))\n {\n case HTTP_STATE_PUT_RECV :\n do\n\t{\n if ((bytes = httpRead2(con->http, line, sizeof(line))) < 0)\n\t {\n\t if (httpError(con->http) && httpError(con->http) != EPIPE)\n\t cupsdLogClient(con, CUPSD_LOG_DEBUG,\n \"HTTP_STATE_PUT_RECV Closing for error %d (%s)\",\n httpError(con->http), strerror(httpError(con->http)));\n\t else\n\t cupsdLogClient(con, CUPSD_LOG_DEBUG,\n\t\t\t \"HTTP_STATE_PUT_RECV Closing on EOF.\");\n\n\t cupsdCloseClient(con);\n\t return;\n\t }\n\t else if (bytes > 0)\n\t {\n\t con->bytes += bytes;\n\n if (MaxRequestSize > 0 && con->bytes > MaxRequestSize)\n {\n\t close(con->file);\n\t con->file = -1;\n\t unlink(con->filename);\n\t cupsdClearString(&con->filename);\n\n if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))\n\t {\n\t\tcupsdCloseClient(con);\n\t\treturn;\n\t }\n }\n\n if (write(con->file, line, (size_t)bytes) < bytes)\n\t {\n cupsdLogClient(con, CUPSD_LOG_ERROR,\n\t \"Unable to write %d bytes to \\\"%s\\\": %s\", bytes,\n con->filename, strerror(errno));\n\n\t close(con->file);\n\t con->file = -1;\n\t unlink(con->filename);\n\t cupsdClearString(&con->filename);\n\n if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))\n\t {\n\t\tcupsdCloseClient(con);\n\t\treturn;\n\t }\n\t }\n\t }\n else if (httpGetState(con->http) == HTTP_STATE_PUT_RECV)\n {\n cupsdCloseClient(con);\n return;\n }\n }\n\twhile (httpGetState(con->http) == HTTP_STATE_PUT_RECV && httpGetReady(con->http));\n\n if (httpGetState(con->http) == HTTP_STATE_STATUS)\n\t{\n\t /*\n\t * End of file, see how big it is...\n\t */\n\n\t fstat(con->file, &filestats);\n\n\t close(con->file);\n\t con->file = -1;\n\n if (filestats.st_size > MaxRequestSize &&\n\t MaxRequestSize > 0)\n\t {\n\t /*\n\t * Request is too big; remove it and send an error...\n\t */\n\n\t unlink(con->filename);\n\t cupsdClearString(&con->filename);\n\n if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))\n\t {\n\t cupsdCloseClient(con);\n\t return;\n\t }\n\t }\n\n /*\n\t * Install the configuration file...\n\t */\n\n status = install_cupsd_conf(con);\n\n /*\n\t * Return the status to the client...\n\t */\n\n if (!cupsdSendError(con, status, CUPSD_AUTH_NONE))\n\t {\n\t cupsdCloseClient(con);\n\t return;\n\t }\n\t}\n break;\n\n case HTTP_STATE_POST_RECV :\n do\n\t{\n if (con->request && con->file < 0)\n\t {\n\t /*\n\t * Grab any request data from the connection...\n\t */\n\n\t if (!httpWait(con->http, 0))\n\t return;\n\n\t if ((ipp_state = ippRead(con->http, con->request)) == IPP_STATE_ERROR)\n\t {\n cupsdLogClient(con, CUPSD_LOG_ERROR, \"IPP read error: %s\",\n cupsLastErrorString());\n\n\t cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE);\n\t cupsdCloseClient(con);\n\t return;\n\t }\n\t else if (ipp_state != IPP_STATE_DATA)\n\t {\n if (httpGetState(con->http) == HTTP_STATE_POST_SEND)\n\t {\n\t\tcupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE);\n\t\tcupsdCloseClient(con);\n\t\treturn;\n\t }\n\n\t if (httpGetReady(con->http))\n\t continue;\n\t break;\n }\n\t else\n\t {\n\t cupsdLogClient(con, CUPSD_LOG_DEBUG, \"%d.%d %s %d\",\n\t\t\t con->request->request.op.version[0],\n\t\t\t con->request->request.op.version[1],\n\t\t\t ippOpString(con->request->request.op.operation_id),\n\t\t\t con->request->request.op.request_id);\n\t con->bytes += (off_t)ippLength(con->request);\n\t }\n\t }\n\n if (con->file < 0 && httpGetState(con->http) != HTTP_STATE_POST_SEND)\n\t {\n /*\n\t * Create a file as needed for the request data...\n\t */\n\n cupsdSetStringf(&con->filename, \"%s/%08x\", RequestRoot,\n\t request_id ++);\n\t con->file = open(con->filename, O_WRONLY | O_CREAT | O_TRUNC, 0640);\n\n\t if (con->file < 0)\n\t {\n\t cupsdLogClient(con, CUPSD_LOG_ERROR,\n\t \"Unable to create request file \\\"%s\\\": %s\",\n con->filename, strerror(errno));\n\n\t if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))\n\t {\n\t\tcupsdCloseClient(con);\n\t\treturn;\n\t }\n\t }\n\n\t fchmod(con->file, 0640);\n\t fchown(con->file, RunUser, Group);\n fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);\n\t }\n\n\t if (httpGetState(con->http) != HTTP_STATE_POST_SEND)\n\t {\n\t if (!httpWait(con->http, 0))\n\t return;\n else if ((bytes = httpRead2(con->http, line, sizeof(line))) < 0)\n\t {\n\t if (httpError(con->http) && httpError(con->http) != EPIPE)\n\t\tcupsdLogClient(con, CUPSD_LOG_DEBUG,\n\t\t\t \"HTTP_STATE_POST_SEND Closing for error %d (%s)\",\n httpError(con->http), strerror(httpError(con->http)));\n\t else\n\t\tcupsdLogClient(con, CUPSD_LOG_DEBUG,\n\t\t\t \"HTTP_STATE_POST_SEND Closing on EOF.\");\n\n\t cupsdCloseClient(con);\n\t return;\n\t }\n\t else if (bytes > 0)\n\t {\n\t con->bytes += bytes;\n\n if (MaxRequestSize > 0 && con->bytes > MaxRequestSize)\n {\n close(con->file);\n con->file = -1;\n unlink(con->filename);\n cupsdClearString(&con->filename);\n\n if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))\n {\n cupsdCloseClient(con);\n return;\n }\n }\n\n if (write(con->file, line, (size_t)bytes) < bytes)\n\t {\n \tcupsdLogClient(con, CUPSD_LOG_ERROR,\n\t \"Unable to write %d bytes to \\\"%s\\\": %s\",\n bytes, con->filename, strerror(errno));\n\n\t\tclose(con->file);\n\t\tcon->file = -1;\n\t\tunlink(con->filename);\n\t\tcupsdClearString(&con->filename);\n\n \tif (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE,\n\t\t CUPSD_AUTH_NONE))\n\t\t{\n\t\t cupsdCloseClient(con);\n\t\t return;\n\t\t}\n\t }\n\t }\n\t else if (httpGetState(con->http) == HTTP_STATE_POST_RECV)\n return;\n\t else if (httpGetState(con->http) != HTTP_STATE_POST_SEND)\n\t {\n\t cupsdLogClient(con, CUPSD_LOG_DEBUG,\n\t \"Closing on unexpected state %s.\",\n\t\t\t httpStateString(httpGetState(con->http)));\n\t cupsdCloseClient(con);\n\t return;\n\t }\n\t }\n }\n\twhile (httpGetState(con->http) == HTTP_STATE_POST_RECV && httpGetReady(con->http));\n\n\tif (httpGetState(con->http) == HTTP_STATE_POST_SEND)\n\t{\n\t if (con->file >= 0)\n\t {\n\t fstat(con->file, &filestats);\n\n\t close(con->file);\n\t con->file = -1;\n\n if (filestats.st_size > MaxRequestSize &&\n\t MaxRequestSize > 0)\n\t {\n\t /*\n\t * Request is too big; remove it and send an error...\n\t */\n\n\t unlink(con->filename);\n\t cupsdClearString(&con->filename);\n\n\t if (con->request)\n\t {\n\t /*\n\t * Delete any IPP request data...\n\t\t*/\n\n\t ippDelete(con->request);\n\t\tcon->request = NULL;\n }\n\n if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))\n\t {\n\t\tcupsdCloseClient(con);\n\t\treturn;\n\t }\n\t }\n\t else if (filestats.st_size == 0)\n\t {\n\t /*\n\t * Don't allow empty file...\n\t */\n\n\t unlink(con->filename);\n\t cupsdClearString(&con->filename);\n\t }\n\n\t if (con->command)\n\t {\n\t if (!cupsdSendCommand(con, con->command, con->options, 0))\n\t {\n\t\tif (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))\n\t\t{\n\t\t cupsdCloseClient(con);\n\t\t return;\n\t\t}\n }\n\t else\n \tcupsdLogRequest(con, HTTP_STATUS_OK);\n }\n\t }\n\n if (con->request)\n\t {\n\t cupsdProcessIPPRequest(con);\n\n\t if (con->filename)\n\t {\n\t unlink(con->filename);\n\t cupsdClearString(&con->filename);\n\t }\n\n\t return;\n\t }\n\t}\n break;\n\n default :\n break; /* Anti-compiler-warning-code */\n }\n\n if (httpGetState(con->http) == HTTP_STATE_WAITING)\n {\n if (!httpGetKeepAlive(con->http))\n {\n cupsdLogClient(con, CUPSD_LOG_DEBUG,\n \"Closing because Keep-Alive is disabled.\");\n cupsdCloseClient(con);\n }\n else\n {\n cupsArrayRemove(ActiveClients, con);\n cupsdSetBusyState(0);\n }\n }\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 struct phy *serdes_simple_xlate(struct device *dev,\n\t\t\t\t struct of_phandle_args *args)\n{\n\tstruct serdes_ctrl *ctrl = dev_get_drvdata(dev);\n\tunsigned int port, idx, i;\n\n\tif (args->args_count != 2)\n\t\treturn ERR_PTR(-EINVAL);\n\n\tport = args->args[0];\n\tidx = args->args[1];\n\n\tfor (i = 0; i <= SERDES_MAX; i++) {\n\t\tstruct serdes_macro *macro = phy_get_drvdata(ctrl->phys[i]);\n\n\t\tif (idx != macro->idx)\n\t\t\tcontinue;\n\n\t\t/* SERDES6G(0) is the only SerDes capable of QSGMII */\n\t\tif (idx != SERDES6G(0) && macro->port >= 0)\n\t\t\treturn ERR_PTR(-EBUSY);\n\n\t\tmacro->port = port;\n\t\treturn ctrl->phys[i];\n\t}\n\n\treturn ERR_PTR(-ENODEV);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'phy: ocelot-serdes: fix out-of-bounds read\n\nCurrently, there is an out-of-bounds read on array ctrl->phys,\nonce variable i reaches the maximum array size of SERDES_MAX\nin the for loop.\n\nFix this by changing the condition in the for loop from\ni <= SERDES_MAX to i < SERDES_MAX.\n\nAddresses-Coverity-ID: 1473966 (\"Out-of-bounds read\")\nAddresses-Coverity-ID: 1473959 (\"Out-of-bounds read\")\nFixes: 51f6b410fc22 (\"phy: add driver for Microsemi Ocelot SerDes muxing\")\nReviewed-by: Quentin Schulz \nSigned-off-by: Gustavo A. R. Silva \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void stream_joined(h2_mplx *m, h2_stream *stream)\n{\n ap_assert(!stream->task || stream->task->worker_done);\n \n h2_ihash_remove(m->shold, stream->id);\n h2_ihash_add(m->spurge, 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: void h2_task_redo(h2_task *task)\n{\n task->rst_error = 0;\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 void load_xref_from_plaintext(FILE *fp, xref_t *xref)\n{\n int i, buf_idx, obj_id, added_entries;\n char c, buf[32] = {0};\n long start, pos;\n\n start = ftell(fp);\n\n /* Get number of entries */\n pos = xref->end;\n fseek(fp, pos, SEEK_SET);\n while (ftell(fp) != 0)\n if (SAFE_F(fp, (fgetc(fp) == '/' && fgetc(fp) == 'S')))\n break;\n else\n SAFE_E(fseek(fp, --pos, SEEK_SET), 0, \"Failed seek to xref /Size.\\n\");\n\n SAFE_E(fread(buf, 1, 21, fp), 21, \"Failed to load entry Size string.\\n\");\n xref->n_entries = atoi(buf + strlen(\"ize \"));\n xref->entries = calloc(1, xref->n_entries * sizeof(struct _xref_entry));\n\n /* Load entry data */\n obj_id = 0;\n fseek(fp, xref->start + strlen(\"xref\"), SEEK_SET);\n added_entries = 0;\n for (i=0; in_entries; i++)\n {\n /* Advance past newlines. */\n c = fgetc(fp);\n while (c == '\\n' || c == '\\r')\n c = fgetc(fp);\n\n /* Collect data up until the following newline. */\n buf_idx = 0;\n while (c != '\\n' && c != '\\r' && !feof(fp) &&\n !ferror(fp) && buf_idx < sizeof(buf))\n {\n buf[buf_idx++] = c;\n c = fgetc(fp);\n }\n if (buf_idx >= sizeof(buf))\n {\n ERR(\"Failed to locate newline character. \"\n \"This might be a corrupt PDF.\\n\");\n exit(EXIT_FAILURE);\n }\n buf[buf_idx] = '\\0';\n\n /* Went to far and hit start of trailer */\n if (strchr(buf, 't'))\n break;\n\n /* Entry or object id */\n if (strlen(buf) > 17)\n {\n xref->entries[i].obj_id = obj_id++;\n xref->entries[i].offset = atol(strtok(buf, \" \"));\n xref->entries[i].gen_num = atoi(strtok(NULL, \" \"));\n xref->entries[i].f_or_n = buf[17];\n ++added_entries;\n }\n else\n {\n obj_id = atoi(buf);\n --i;\n }\n }\n\n xref->n_entries = added_entries;\n fseek(fp, start, SEEK_SET);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Zero and sanity check all dynamic allocs.\n\nThis addresses the memory issues in Issue #6 expressed in\ncalloc_some.pdf and malloc_some.pdf'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline void free_ep_req(struct usb_ep *ep, struct usb_request *req)\n{\n\tkfree(req->buf);\n\tusb_ep_free_request(ep, req);\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: qedi_dbg_notice(struct qedi_dbg_ctx *qedi, const char *func, u32 line,\n\t\tconst char *fmt, ...)\n{\n\tva_list va;\n\tstruct va_format vaf;\n\tchar nfunc[32];\n\n\tmemset(nfunc, 0, sizeof(nfunc));\n\tmemcpy(nfunc, func, sizeof(nfunc) - 1);\n\n\tva_start(va, fmt);\n\n\tvaf.fmt = fmt;\n\tvaf.va = &va;\n\n\tif (!(qedi_dbg_log & QEDI_LOG_NOTICE))\n\t\tgoto ret;\n\n\tif (likely(qedi) && likely(qedi->pdev))\n\t\tpr_notice(\"[%s]:[%s:%d]:%d: %pV\",\n\t\t\t dev_name(&qedi->pdev->dev), nfunc, line,\n\t\t\t qedi->host_no, &vaf);\n\telse\n\t\tpr_notice(\"[0000:00:00.0]:[%s:%d]: %pV\", nfunc, line, &vaf);\n\nret:\n\tva_end(va);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'scsi: qedi: remove memset/memcpy to nfunc and use func instead\n\nKASAN reports this:\n\nBUG: KASAN: global-out-of-bounds in qedi_dbg_err+0xda/0x330 [qedi]\nRead of size 31 at addr ffffffffc12b0ae0 by task syz-executor.0/2429\n\nCPU: 0 PID: 2429 Comm: syz-executor.0 Not tainted 5.0.0-rc7+ #45\nHardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014\nCall Trace:\n __dump_stack lib/dump_stack.c:77 [inline]\n dump_stack+0xfa/0x1ce lib/dump_stack.c:113\n print_address_description+0x1c4/0x270 mm/kasan/report.c:187\n kasan_report+0x149/0x18d mm/kasan/report.c:317\n memcpy+0x1f/0x50 mm/kasan/common.c:130\n qedi_dbg_err+0xda/0x330 [qedi]\n ? 0xffffffffc12d0000\n qedi_init+0x118/0x1000 [qedi]\n ? 0xffffffffc12d0000\n ? 0xffffffffc12d0000\n ? 0xffffffffc12d0000\n do_one_initcall+0xfa/0x5ca init/main.c:887\n do_init_module+0x204/0x5f6 kernel/module.c:3460\n load_module+0x66b2/0x8570 kernel/module.c:3808\n __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902\n do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\nRIP: 0033:0x462e99\nCode: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48\nRSP: 002b:00007f2d57e55c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139\nRAX: ffffffffffffffda RBX: 000000000073bfa0 RCX: 0000000000462e99\nRDX: 0000000000000000 RSI: 00000000200003c0 RDI: 0000000000000003\nRBP: 00007f2d57e55c70 R08: 0000000000000000 R09: 0000000000000000\nR10: 0000000000000000 R11: 0000000000000246 R12: 00007f2d57e566bc\nR13: 00000000004bcefb R14: 00000000006f7030 R15: 0000000000000004\n\nThe buggy address belongs to the variable:\n __func__.67584+0x0/0xffffffffffffd520 [qedi]\n\nMemory state around the buggy address:\n ffffffffc12b0980: fa fa fa fa 00 04 fa fa fa fa fa fa 00 00 05 fa\n ffffffffc12b0a00: fa fa fa fa 00 00 04 fa fa fa fa fa 00 05 fa fa\n> ffffffffc12b0a80: fa fa fa fa 00 06 fa fa fa fa fa fa 00 02 fa fa\n ^\n ffffffffc12b0b00: fa fa fa fa 00 00 04 fa fa fa fa fa 00 00 03 fa\n ffffffffc12b0b80: fa fa fa fa 00 00 02 fa fa fa fa fa 00 00 04 fa\n\nCurrently the qedi_dbg_* family of functions can overrun the end of the\nsource string if it is less than the destination buffer length because of\nthe use of a fixed sized memcpy. Remove the memset/memcpy calls to nfunc\nand just use func instead as it is always a null terminated string.\n\nReported-by: Hulk Robot \nFixes: ace7f46ba5fd (\"scsi: qedi: Add QLogic FastLinQ offload iSCSI driver framework.\")\nSigned-off-by: YueHaibing \nReviewed-by: Dan Carpenter \nSigned-off-by: Martin K. Petersen '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void ath10k_usb_free_urb_to_pipe(struct ath10k_usb_pipe *pipe,\n\t\t\t\t\tstruct ath10k_urb_context *urb_context)\n{\n\tunsigned long flags;\n\n\tspin_lock_irqsave(&pipe->ar_usb->cs_lock, flags);\n\n\tpipe->urb_cnt++;\n\tlist_add(&urb_context->link, &pipe->urb_list_head);\n\n\tspin_unlock_irqrestore(&pipe->ar_usb->cs_lock, flags);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'ath10k: Fix a NULL-ptr-deref bug in ath10k_usb_alloc_urb_from_pipe\n\nThe `ar_usb` field of `ath10k_usb_pipe_usb_pipe` objects\nare initialized to point to the containing `ath10k_usb` object\naccording to endpoint descriptors read from the device side, as shown\nbelow in `ath10k_usb_setup_pipe_resources`:\n\nfor (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {\n endpoint = &iface_desc->endpoint[i].desc;\n\n // get the address from endpoint descriptor\n pipe_num = ath10k_usb_get_logical_pipe_num(ar_usb,\n endpoint->bEndpointAddress,\n &urbcount);\n ......\n // select the pipe object\n pipe = &ar_usb->pipes[pipe_num];\n\n // initialize the ar_usb field\n pipe->ar_usb = ar_usb;\n}\n\nThe driver assumes that the addresses reported in endpoint\ndescriptors from device side to be complete. If a device is\nmalicious and does not report complete addresses, it may trigger\nNULL-ptr-deref `ath10k_usb_alloc_urb_from_pipe` and\n`ath10k_usb_free_urb_to_pipe`.\n\nThis patch fixes the bug by preventing potential NULL-ptr-deref.\n\nSigned-off-by: Hui Peng \nReported-by: Hui Peng \nReported-by: Mathias Payer \nReviewed-by: Greg Kroah-Hartman \n[groeck: Add driver tag to subject, fix build warning]\nSigned-off-by: Guenter Roeck \nSigned-off-by: Kalle Valo '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int mwifiex_update_vs_ie(const u8 *ies, int ies_len,\n\t\t\t\tstruct mwifiex_ie **ie_ptr, u16 mask,\n\t\t\t\tunsigned int oui, u8 oui_type)\n{\n\tstruct ieee_types_header *vs_ie;\n\tstruct mwifiex_ie *ie = *ie_ptr;\n\tconst u8 *vendor_ie;\n\n\tvendor_ie = cfg80211_find_vendor_ie(oui, oui_type, ies, ies_len);\n\tif (vendor_ie) {\n\t\tif (!*ie_ptr) {\n\t\t\t*ie_ptr = kzalloc(sizeof(struct mwifiex_ie),\n\t\t\t\t\t GFP_KERNEL);\n\t\t\tif (!*ie_ptr)\n\t\t\t\treturn -ENOMEM;\n\t\t\tie = *ie_ptr;\n\t\t}\n\n\t\tvs_ie = (struct ieee_types_header *)vendor_ie;\n\t\tmemcpy(ie->ie_buffer + le16_to_cpu(ie->ie_length),\n\t\t vs_ie, vs_ie->len + 2);\n\t\tle16_unaligned_add_cpu(&ie->ie_length, vs_ie->len + 2);\n\t\tie->mgmt_subtype_mask = cpu_to_le16(mask);\n\t\tie->ie_index = cpu_to_le16(MWIFIEX_AUTO_IDX_MASK);\n\t}\n\n\t*ie_ptr = ie;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'mwifiex: Fix three heap overflow at parsing element in cfg80211_ap_settings\n\nmwifiex_update_vs_ie(),mwifiex_set_uap_rates() and\nmwifiex_set_wmm_params() call memcpy() without checking\nthe destination size.Since the source is given from\nuser-space, this may trigger a heap buffer overflow.\n\nFix them by putting the length check before performing memcpy().\n\nThis fix addresses CVE-2019-14814,CVE-2019-14815,CVE-2019-14816.\n\nSigned-off-by: Wen Huang \nAcked-by: Ganapathi Bhat \nSigned-off-by: Kalle Valo '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: const std::array uuid() const {\n int len = 0;\n const char* data = nullptr;\n if (type() == BinData && binDataType() == BinDataType::newUUID)\n data = binData(len);\n uassert(ErrorCodes::InvalidUUID,\n \"uuid must be a 16-byte binary field with UUID (4) subtype\",\n 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 AuthorizationManager::_initializeUserFromPrivilegeDocument(User* user,\n const BSONObj& privDoc) {\n V2UserDocumentParser parser;\n std::string userName = parser.extractUserNameFromUserDocument(privDoc);\n if (userName != user->getName().getUser()) {\n return Status(ErrorCodes::BadValue,\n mongoutils::str::stream() << \"User name from privilege document \\\"\"\n << userName\n << \"\\\" doesn't match name of provided User \\\"\"\n << user->getName().getUser()\n << \"\\\"\",\n 0);\n }\n\n Status status = parser.initializeUserCredentialsFromUserDocument(user, privDoc);\n if (!status.isOK()) {\n return status;\n }\n status = parser.initializeUserRolesFromUserDocument(privDoc, user);\n if (!status.isOK()) {\n return status;\n }\n status = parser.initializeUserIndirectRolesFromUserDocument(privDoc, user);\n if (!status.isOK()) {\n return status;\n }\n status = parser.initializeUserPrivilegesFromUserDocument(privDoc, user);\n if (!status.isOK()) {\n return status;\n }\n\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: xfs_setattr_nonsize(\n\tstruct xfs_inode\t*ip,\n\tstruct iattr\t\t*iattr,\n\tint\t\t\tflags)\n{\n\txfs_mount_t\t\t*mp = ip->i_mount;\n\tstruct inode\t\t*inode = VFS_I(ip);\n\tint\t\t\tmask = iattr->ia_valid;\n\txfs_trans_t\t\t*tp;\n\tint\t\t\terror;\n\tkuid_t\t\t\tuid = GLOBAL_ROOT_UID, iuid = GLOBAL_ROOT_UID;\n\tkgid_t\t\t\tgid = GLOBAL_ROOT_GID, igid = GLOBAL_ROOT_GID;\n\tstruct xfs_dquot\t*udqp = NULL, *gdqp = NULL;\n\tstruct xfs_dquot\t*olddquot1 = NULL, *olddquot2 = NULL;\n\n\tASSERT((mask & ATTR_SIZE) == 0);\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 & (ATTR_UID|ATTR_GID))) {\n\t\tuint\tqflags = 0;\n\n\t\tif ((mask & ATTR_UID) && XFS_IS_UQUOTA_ON(mp)) {\n\t\t\tuid = iattr->ia_uid;\n\t\t\tqflags |= XFS_QMOPT_UQUOTA;\n\t\t} else {\n\t\t\tuid = inode->i_uid;\n\t\t}\n\t\tif ((mask & ATTR_GID) && XFS_IS_GQUOTA_ON(mp)) {\n\t\t\tgid = iattr->ia_gid;\n\t\t\tqflags |= XFS_QMOPT_GQUOTA;\n\t\t} else {\n\t\t\tgid = inode->i_gid;\n\t\t}\n\n\t\t/*\n\t\t * We take a reference when we initialize udqp and gdqp,\n\t\t * so it is important that we never blindly double trip on\n\t\t * the same variable. See xfs_create() for an example.\n\t\t */\n\t\tASSERT(udqp == NULL);\n\t\tASSERT(gdqp == NULL);\n\t\terror = xfs_qm_vop_dqalloc(ip, xfs_kuid_to_uid(uid),\n\t\t\t\t\t xfs_kgid_to_gid(gid),\n\t\t\t\t\t xfs_get_projid(ip),\n\t\t\t\t\t qflags, &udqp, &gdqp, NULL);\n\t\tif (error)\n\t\t\treturn error;\n\t}\n\n\terror = xfs_trans_alloc(mp, &M_RES(mp)->tr_ichange, 0, 0, 0, &tp);\n\tif (error)\n\t\tgoto out_dqrele;\n\n\txfs_ilock(ip, XFS_ILOCK_EXCL);\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 & (ATTR_UID|ATTR_GID)) {\n\t\t/*\n\t\t * These IDs could have changed since we last looked at them.\n\t\t * But, we're assured that if the ownership did change\n\t\t * while we didn't have the inode locked, inode's dquot(s)\n\t\t * would have changed also.\n\t\t */\n\t\tiuid = inode->i_uid;\n\t\tigid = inode->i_gid;\n\t\tgid = (mask & ATTR_GID) ? iattr->ia_gid : igid;\n\t\tuid = (mask & ATTR_UID) ? iattr->ia_uid : iuid;\n\n\t\t/*\n\t\t * Do a quota reservation only if uid/gid is actually\n\t\t * going to change.\n\t\t */\n\t\tif (XFS_IS_QUOTA_RUNNING(mp) &&\n\t\t ((XFS_IS_UQUOTA_ON(mp) && !uid_eq(iuid, uid)) ||\n\t\t (XFS_IS_GQUOTA_ON(mp) && !gid_eq(igid, gid)))) {\n\t\t\tASSERT(tp);\n\t\t\terror = xfs_qm_vop_chown_reserve(tp, ip, udqp, gdqp,\n\t\t\t\t\t\tNULL, capable(CAP_FOWNER) ?\n\t\t\t\t\t\tXFS_QMOPT_FORCE_RES : 0);\n\t\t\tif (error)\t/* out of quota */\n\t\t\t\tgoto out_cancel;\n\t\t}\n\t}\n\n\t/*\n\t * Change file ownership. Must be the owner or privileged.\n\t */\n\tif (mask & (ATTR_UID|ATTR_GID)) {\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 ((inode->i_mode & (S_ISUID|S_ISGID)) &&\n\t\t !capable(CAP_FSETID))\n\t\t\tinode->i_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 (!uid_eq(iuid, uid)) {\n\t\t\tif (XFS_IS_QUOTA_RUNNING(mp) && XFS_IS_UQUOTA_ON(mp)) {\n\t\t\t\tASSERT(mask & ATTR_UID);\n\t\t\t\tASSERT(udqp);\n\t\t\t\tolddquot1 = xfs_qm_vop_chown(tp, ip,\n\t\t\t\t\t\t\t&ip->i_udquot, udqp);\n\t\t\t}\n\t\t\tip->i_d.di_uid = xfs_kuid_to_uid(uid);\n\t\t\tinode->i_uid = uid;\n\t\t}\n\t\tif (!gid_eq(igid, gid)) {\n\t\t\tif (XFS_IS_QUOTA_RUNNING(mp) && XFS_IS_GQUOTA_ON(mp)) {\n\t\t\t\tASSERT(xfs_sb_version_has_pquotino(&mp->m_sb) ||\n\t\t\t\t !XFS_IS_PQUOTA_ON(mp));\n\t\t\t\tASSERT(mask & ATTR_GID);\n\t\t\t\tASSERT(gdqp);\n\t\t\t\tolddquot2 = xfs_qm_vop_chown(tp, ip,\n\t\t\t\t\t\t\t&ip->i_gdquot, gdqp);\n\t\t\t}\n\t\t\tip->i_d.di_gid = xfs_kgid_to_gid(gid);\n\t\t\tinode->i_gid = gid;\n\t\t}\n\t}\n\n\tif (mask & ATTR_MODE)\n\t\txfs_setattr_mode(ip, iattr);\n\tif (mask & (ATTR_ATIME|ATTR_CTIME|ATTR_MTIME))\n\t\txfs_setattr_time(ip, iattr);\n\n\txfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);\n\n\tXFS_STATS_INC(mp, xs_ig_attrchg);\n\n\tif (mp->m_flags & XFS_MOUNT_WSYNC)\n\t\txfs_trans_set_sync(tp);\n\terror = xfs_trans_commit(tp);\n\n\txfs_iunlock(ip, XFS_ILOCK_EXCL);\n\n\t/*\n\t * Release any dquot(s) the inode had kept before chown.\n\t */\n\txfs_qm_dqrele(olddquot1);\n\txfs_qm_dqrele(olddquot2);\n\txfs_qm_dqrele(udqp);\n\txfs_qm_dqrele(gdqp);\n\n\tif (error)\n\t\treturn error;\n\n\t/*\n\t * XXX(hch): Updating the ACL entries is not atomic vs the i_mode\n\t * \t update. We could avoid this with linked transactions\n\t * \t and passing down the transaction pointer all the way\n\t *\t to attr_set. No previous user of the generic\n\t * \t Posix ACL code seems to care about this issue either.\n\t */\n\tif ((mask & ATTR_MODE) && !(flags & XFS_ATTR_NOACL)) {\n\t\terror = posix_acl_chmod(inode, inode->i_mode);\n\t\tif (error)\n\t\t\treturn error;\n\t}\n\n\treturn 0;\n\nout_cancel:\n\txfs_trans_cancel(tp);\nout_dqrele:\n\txfs_qm_dqrele(udqp);\n\txfs_qm_dqrele(gdqp);\n\treturn error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-399', 'CWE-703'], 'message': 'xfs: fix missing ILOCK unlock when xfs_setattr_nonsize fails due to EDQUOT\n\nBenjamin Moody reported to Debian that XFS partially wedges when a chgrp\nfails on account of being out of disk quota. I ran his reproducer\nscript:\n\n# adduser dummy\n# adduser dummy plugdev\n\n# dd if=/dev/zero bs=1M count=100 of=test.img\n# mkfs.xfs test.img\n# mount -t xfs -o gquota test.img /mnt\n# mkdir -p /mnt/dummy\n# chown -c dummy /mnt/dummy\n# xfs_quota -xc 'limit -g bsoft=100k bhard=100k plugdev' /mnt\n\n(and then as user dummy)\n\n$ dd if=/dev/urandom bs=1M count=50 of=/mnt/dummy/foo\n$ chgrp plugdev /mnt/dummy/foo\n\nand saw:\n\n================================================\nWARNING: lock held when returning to user space!\n5.3.0-rc5 #rc5 Tainted: G W\n------------------------------------------------\nchgrp/47006 is leaving the kernel with locks still held!\n1 lock held by chgrp/47006:\n #0: 000000006664ea2d (&xfs_nondir_ilock_class){++++}, at: xfs_ilock+0xd2/0x290 [xfs]\n\n...which is clearly caused by xfs_setattr_nonsize failing to unlock the\nILOCK after the xfs_qm_vop_chown_reserve call fails. Add the missing\nunlock.\n\nReported-by: benjamin.moody@gmail.com\nFixes: 253f4911f297 (\"xfs: better xfs_trans_alloc interface\")\nSigned-off-by: Darrick J. Wong \nReviewed-by: Dave Chinner \nTested-by: Salvatore Bonaccorso '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (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_load_firmware(struct ieee80211_hw *dev,\n\t\t\t struct usb_interface *intf)\n{\n\tstruct usb_device *udev = interface_to_usbdev(intf);\n\tstruct p54u_priv *priv = dev->priv;\n\tstruct device *device = &udev->dev;\n\tint err, i;\n\n\tBUILD_BUG_ON(ARRAY_SIZE(p54u_fwlist) != __NUM_P54U_HWTYPES);\n\n\tinit_completion(&priv->fw_wait_load);\n\ti = p54_find_type(priv);\n\tif (i < 0)\n\t\treturn i;\n\n\tdev_info(&priv->udev->dev, \"Loading firmware file %s\\n\",\n\t p54u_fwlist[i].fw);\n\n\tusb_get_dev(udev);\n\terr = request_firmware_nowait(THIS_MODULE, 1, p54u_fwlist[i].fw,\n\t\t\t\t device, GFP_KERNEL, priv,\n\t\t\t\t p54u_load_firmware_cb);\n\tif (err) {\n\t\tdev_err(&priv->udev->dev, \"(p54usb) cannot load firmware %s \"\n\t\t\t\t\t \"(%d)!\\n\", p54u_fwlist[i].fw, err);\n\t\tusb_put_dev(udev);\n\t}\n\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: int line6_probe(struct usb_interface *interface,\n\t\tconst struct usb_device_id *id,\n\t\tconst char *driver_name,\n\t\tconst struct line6_properties *properties,\n\t\tint (*private_init)(struct usb_line6 *, const struct usb_device_id *id),\n\t\tsize_t data_size)\n{\n\tstruct usb_device *usbdev = interface_to_usbdev(interface);\n\tstruct snd_card *card;\n\tstruct usb_line6 *line6;\n\tint interface_number;\n\tint ret;\n\n\tif (WARN_ON(data_size < sizeof(*line6)))\n\t\treturn -EINVAL;\n\n\t/* we don't handle multiple configurations */\n\tif (usbdev->descriptor.bNumConfigurations != 1)\n\t\treturn -ENODEV;\n\n\tret = snd_card_new(&interface->dev,\n\t\t\t SNDRV_DEFAULT_IDX1, SNDRV_DEFAULT_STR1,\n\t\t\t THIS_MODULE, data_size, &card);\n\tif (ret < 0)\n\t\treturn ret;\n\n\t/* store basic data: */\n\tline6 = card->private_data;\n\tline6->card = card;\n\tline6->properties = properties;\n\tline6->usbdev = usbdev;\n\tline6->ifcdev = &interface->dev;\n\n\tstrcpy(card->id, properties->id);\n\tstrcpy(card->driver, driver_name);\n\tstrcpy(card->shortname, properties->name);\n\tsprintf(card->longname, \"Line 6 %s at USB %s\", properties->name,\n\t\tdev_name(line6->ifcdev));\n\tcard->private_free = line6_destruct;\n\n\tusb_set_intfdata(interface, line6);\n\n\t/* increment reference counters: */\n\tusb_get_dev(usbdev);\n\n\t/* initialize device info: */\n\tdev_info(&interface->dev, \"Line 6 %s found\\n\", properties->name);\n\n\t/* query interface number */\n\tinterface_number = interface->cur_altsetting->desc.bInterfaceNumber;\n\n\t/* TODO reserves the bus bandwidth even without actual transfer */\n\tret = usb_set_interface(usbdev, interface_number,\n\t\t\t\tproperties->altsetting);\n\tif (ret < 0) {\n\t\tdev_err(&interface->dev, \"set_interface failed\\n\");\n\t\tgoto error;\n\t}\n\n\tline6_get_usb_properties(line6);\n\n\tif (properties->capabilities & LINE6_CAP_CONTROL) {\n\t\tret = line6_init_cap_control(line6);\n\t\tif (ret < 0)\n\t\t\tgoto error;\n\t}\n\n\t/* initialize device data based on device: */\n\tret = private_init(line6, id);\n\tif (ret < 0)\n\t\tgoto error;\n\n\t/* creation of additional special files should go here */\n\n\tdev_info(&interface->dev, \"Line 6 %s now attached\\n\",\n\t\t properties->name);\n\n\treturn 0;\n\n error:\n\t/* we can call disconnect callback here because no close-sync is\n\t * needed yet at this point\n\t */\n\tline6_disconnect(interface);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'ALSA: line6: Assure canceling delayed work at disconnection\n\nThe current code performs the cancel of a delayed work at the late\nstage of disconnection procedure, which may lead to the access to the\nalready cleared state.\n\nThis patch assures to call cancel_delayed_work_sync() at the beginning\nof the disconnection procedure for avoiding that race. The delayed\nwork object is now assigned in the common line6 object instead of its\nderivative, so that we can call cancel_delayed_work_sync().\n\nAlong with the change, the startup function is called via the new\ncallback instead. This will make it easier to port other LINE6\ndrivers to use the delayed work for startup in later patches.\n\nReported-by: syzbot+5255458d5e0a2b10bbb9@syzkaller.appspotmail.com\nFixes: 7f84ff68be05 (\"ALSA: line6: toneport: Fix broken usage of timer for delayed execution\")\nCc: \nSigned-off-by: Takashi Iwai '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bgp_log_error(struct bgp_proto *p, u8 class, char *msg, uint code, uint subcode, byte *data, uint len)\n{\n byte argbuf[256], *t = argbuf;\n uint i;\n\n /* Don't report Cease messages generated by myself */\n if (code == 6 && class == BE_BGP_TX)\n return;\n\n /* Reset shutdown message */\n if ((code == 6) && ((subcode == 2) || (subcode == 4)))\n proto_set_message(&p->p, NULL, 0);\n\n if (len)\n {\n /* Bad peer AS - we would like to print the AS */\n if ((code == 2) && (subcode == 2) && ((len == 2) || (len == 4)))\n\t{\n\t t += bsprintf(t, \": %u\", (len == 2) ? get_u16(data) : get_u32(data));\n\t goto done;\n\t}\n\n /* RFC 8203 - shutdown communication */\n if (((code == 6) && ((subcode == 2) || (subcode == 4))))\n\tif (bgp_handle_message(p, data, len, &t))\n\t goto done;\n\n *t++ = ':';\n *t++ = ' ';\n if (len > 16)\n\tlen = 16;\n for (i=0; ip.name, msg, dsc, argbuf);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'BGP: Fix bugs in handling of shutdown messages\n\nThere is an improper check for valid message size, which may lead to\nstack overflow and buffer leaks to log when a large message is received.\n\nThanks to Daniel McCarney for bugreport and analysis.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end,\n int tok, const char *next, const char **nextPtr, XML_Bool haveMore) {\n#ifdef XML_DTD\n static const XML_Char externalSubsetName[] = {ASCII_HASH, '\\0'};\n#endif /* XML_DTD */\n static const XML_Char atypeCDATA[]\n = {ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\\0'};\n static const XML_Char atypeID[] = {ASCII_I, ASCII_D, '\\0'};\n static const XML_Char atypeIDREF[]\n = {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, '\\0'};\n static const XML_Char atypeIDREFS[]\n = {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, ASCII_S, '\\0'};\n static const XML_Char atypeENTITY[]\n = {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_Y, '\\0'};\n static const XML_Char atypeENTITIES[]\n = {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T,\n ASCII_I, ASCII_E, ASCII_S, '\\0'};\n static const XML_Char atypeNMTOKEN[]\n = {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, '\\0'};\n static const XML_Char atypeNMTOKENS[]\n = {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K,\n ASCII_E, ASCII_N, ASCII_S, '\\0'};\n static const XML_Char notationPrefix[]\n = {ASCII_N, ASCII_O, ASCII_T, ASCII_A, ASCII_T,\n ASCII_I, ASCII_O, ASCII_N, ASCII_LPAREN, '\\0'};\n static const XML_Char enumValueSep[] = {ASCII_PIPE, '\\0'};\n static const XML_Char enumValueStart[] = {ASCII_LPAREN, '\\0'};\n\n /* save one level of indirection */\n DTD *const dtd = parser->m_dtd;\n\n const char **eventPP;\n const char **eventEndPP;\n enum XML_Content_Quant quant;\n\n if (enc == parser->m_encoding) {\n eventPP = &parser->m_eventPtr;\n eventEndPP = &parser->m_eventEndPtr;\n } else {\n eventPP = &(parser->m_openInternalEntities->internalEventPtr);\n eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);\n }\n\n for (;;) {\n int role;\n XML_Bool handleDefault = XML_TRUE;\n *eventPP = s;\n *eventEndPP = next;\n if (tok <= 0) {\n if (haveMore && tok != XML_TOK_INVALID) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n switch (tok) {\n case XML_TOK_INVALID:\n *eventPP = next;\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_PARTIAL:\n return XML_ERROR_UNCLOSED_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n return XML_ERROR_PARTIAL_CHAR;\n case -XML_TOK_PROLOG_S:\n tok = -tok;\n break;\n case XML_TOK_NONE:\n#ifdef XML_DTD\n /* for internal PE NOT referenced between declarations */\n if (enc != parser->m_encoding\n && ! parser->m_openInternalEntities->betweenDecl) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n /* WFC: PE Between Declarations - must check that PE contains\n complete markup, not only for external PEs, but also for\n internal PEs if the reference occurs between declarations.\n */\n if (parser->m_isParamEntity || enc != parser->m_encoding) {\n if (XmlTokenRole(&parser->m_prologState, XML_TOK_NONE, end, end, enc)\n == XML_ROLE_ERROR)\n return XML_ERROR_INCOMPLETE_PE;\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n#endif /* XML_DTD */\n return XML_ERROR_NO_ELEMENTS;\n default:\n tok = -tok;\n next = end;\n break;\n }\n }\n role = XmlTokenRole(&parser->m_prologState, tok, s, next, enc);\n switch (role) {\n case XML_ROLE_XML_DECL: {\n enum XML_Error result = processXmlDecl(parser, 0, s, next);\n if (result != XML_ERROR_NONE)\n return result;\n enc = parser->m_encoding;\n handleDefault = XML_FALSE;\n } break;\n case XML_ROLE_DOCTYPE_NAME:\n if (parser->m_startDoctypeDeclHandler) {\n parser->m_doctypeName\n = poolStoreString(&parser->m_tempPool, enc, s, next);\n if (! parser->m_doctypeName)\n return XML_ERROR_NO_MEMORY;\n poolFinish(&parser->m_tempPool);\n parser->m_doctypePubid = NULL;\n handleDefault = XML_FALSE;\n }\n parser->m_doctypeSysid = NULL; /* always initialize to NULL */\n break;\n case XML_ROLE_DOCTYPE_INTERNAL_SUBSET:\n if (parser->m_startDoctypeDeclHandler) {\n parser->m_startDoctypeDeclHandler(\n parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,\n parser->m_doctypePubid, 1);\n parser->m_doctypeName = NULL;\n poolClear(&parser->m_tempPool);\n handleDefault = XML_FALSE;\n }\n break;\n#ifdef XML_DTD\n case XML_ROLE_TEXT_DECL: {\n enum XML_Error result = processXmlDecl(parser, 1, s, next);\n if (result != XML_ERROR_NONE)\n return result;\n enc = parser->m_encoding;\n handleDefault = XML_FALSE;\n } break;\n#endif /* XML_DTD */\n case XML_ROLE_DOCTYPE_PUBLIC_ID:\n#ifdef XML_DTD\n parser->m_useForeignDTD = XML_FALSE;\n parser->m_declEntity = (ENTITY *)lookup(\n parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY));\n if (! parser->m_declEntity)\n return XML_ERROR_NO_MEMORY;\n#endif /* XML_DTD */\n dtd->hasParamEntityRefs = XML_TRUE;\n if (parser->m_startDoctypeDeclHandler) {\n XML_Char *pubId;\n if (! XmlIsPublicId(enc, s, next, eventPP))\n return XML_ERROR_PUBLICID;\n pubId = poolStoreString(&parser->m_tempPool, enc,\n s + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (! pubId)\n return XML_ERROR_NO_MEMORY;\n normalizePublicId(pubId);\n poolFinish(&parser->m_tempPool);\n parser->m_doctypePubid = pubId;\n handleDefault = XML_FALSE;\n goto alreadyChecked;\n }\n /* fall through */\n case XML_ROLE_ENTITY_PUBLIC_ID:\n if (! XmlIsPublicId(enc, s, next, eventPP))\n return XML_ERROR_PUBLICID;\n alreadyChecked:\n if (dtd->keepProcessing && parser->m_declEntity) {\n XML_Char *tem\n = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (! tem)\n return XML_ERROR_NO_MEMORY;\n normalizePublicId(tem);\n parser->m_declEntity->publicId = tem;\n poolFinish(&dtd->pool);\n /* Don't suppress the default handler if we fell through from\n * the XML_ROLE_DOCTYPE_PUBLIC_ID case.\n */\n if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_PUBLIC_ID)\n handleDefault = XML_FALSE;\n }\n break;\n case XML_ROLE_DOCTYPE_CLOSE:\n if (parser->m_doctypeName) {\n parser->m_startDoctypeDeclHandler(\n parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,\n parser->m_doctypePubid, 0);\n poolClear(&parser->m_tempPool);\n handleDefault = XML_FALSE;\n }\n /* parser->m_doctypeSysid will be non-NULL in the case of a previous\n XML_ROLE_DOCTYPE_SYSTEM_ID, even if parser->m_startDoctypeDeclHandler\n was not set, indicating an external subset\n */\n#ifdef XML_DTD\n if (parser->m_doctypeSysid || parser->m_useForeignDTD) {\n XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;\n dtd->hasParamEntityRefs = XML_TRUE;\n if (parser->m_paramEntityParsing\n && parser->m_externalEntityRefHandler) {\n ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,\n externalSubsetName, sizeof(ENTITY));\n if (! entity) {\n /* The external subset name \"#\" will have already been\n * inserted into the hash table at the start of the\n * external entity parsing, so no allocation will happen\n * and lookup() cannot fail.\n */\n return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */\n }\n if (parser->m_useForeignDTD)\n entity->base = parser->m_curBase;\n dtd->paramEntityRead = XML_FALSE;\n if (! parser->m_externalEntityRefHandler(\n parser->m_externalEntityRefHandlerArg, 0, entity->base,\n entity->systemId, entity->publicId))\n return XML_ERROR_EXTERNAL_ENTITY_HANDLING;\n if (dtd->paramEntityRead) {\n if (! dtd->standalone && parser->m_notStandaloneHandler\n && ! parser->m_notStandaloneHandler(parser->m_handlerArg))\n return XML_ERROR_NOT_STANDALONE;\n }\n /* if we didn't read the foreign DTD then this means that there\n is no external subset and we must reset dtd->hasParamEntityRefs\n */\n else if (! parser->m_doctypeSysid)\n dtd->hasParamEntityRefs = hadParamEntityRefs;\n /* end of DTD - no need to update dtd->keepProcessing */\n }\n parser->m_useForeignDTD = XML_FALSE;\n }\n#endif /* XML_DTD */\n if (parser->m_endDoctypeDeclHandler) {\n parser->m_endDoctypeDeclHandler(parser->m_handlerArg);\n handleDefault = XML_FALSE;\n }\n break;\n case XML_ROLE_INSTANCE_START:\n#ifdef XML_DTD\n /* if there is no DOCTYPE declaration then now is the\n last chance to read the foreign DTD\n */\n if (parser->m_useForeignDTD) {\n XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;\n dtd->hasParamEntityRefs = XML_TRUE;\n if (parser->m_paramEntityParsing\n && parser->m_externalEntityRefHandler) {\n ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,\n externalSubsetName, sizeof(ENTITY));\n if (! entity)\n return XML_ERROR_NO_MEMORY;\n entity->base = parser->m_curBase;\n dtd->paramEntityRead = XML_FALSE;\n if (! parser->m_externalEntityRefHandler(\n parser->m_externalEntityRefHandlerArg, 0, entity->base,\n entity->systemId, entity->publicId))\n return XML_ERROR_EXTERNAL_ENTITY_HANDLING;\n if (dtd->paramEntityRead) {\n if (! dtd->standalone && parser->m_notStandaloneHandler\n && ! parser->m_notStandaloneHandler(parser->m_handlerArg))\n return XML_ERROR_NOT_STANDALONE;\n }\n /* if we didn't read the foreign DTD then this means that there\n is no external subset and we must reset dtd->hasParamEntityRefs\n */\n else\n dtd->hasParamEntityRefs = hadParamEntityRefs;\n /* end of DTD - no need to update dtd->keepProcessing */\n }\n }\n#endif /* XML_DTD */\n parser->m_processor = contentProcessor;\n return contentProcessor(parser, s, end, nextPtr);\n case XML_ROLE_ATTLIST_ELEMENT_NAME:\n parser->m_declElementType = getElementType(parser, enc, s, next);\n if (! parser->m_declElementType)\n return XML_ERROR_NO_MEMORY;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_NAME:\n parser->m_declAttributeId = getAttributeId(parser, enc, s, next);\n if (! parser->m_declAttributeId)\n return XML_ERROR_NO_MEMORY;\n parser->m_declAttributeIsCdata = XML_FALSE;\n parser->m_declAttributeType = NULL;\n parser->m_declAttributeIsId = XML_FALSE;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_TYPE_CDATA:\n parser->m_declAttributeIsCdata = XML_TRUE;\n parser->m_declAttributeType = atypeCDATA;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_TYPE_ID:\n parser->m_declAttributeIsId = XML_TRUE;\n parser->m_declAttributeType = atypeID;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_TYPE_IDREF:\n parser->m_declAttributeType = atypeIDREF;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_TYPE_IDREFS:\n parser->m_declAttributeType = atypeIDREFS;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_TYPE_ENTITY:\n parser->m_declAttributeType = atypeENTITY;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_TYPE_ENTITIES:\n parser->m_declAttributeType = atypeENTITIES;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN:\n parser->m_declAttributeType = atypeNMTOKEN;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS:\n parser->m_declAttributeType = atypeNMTOKENS;\n checkAttListDeclHandler:\n if (dtd->keepProcessing && parser->m_attlistDeclHandler)\n handleDefault = XML_FALSE;\n break;\n case XML_ROLE_ATTRIBUTE_ENUM_VALUE:\n case XML_ROLE_ATTRIBUTE_NOTATION_VALUE:\n if (dtd->keepProcessing && parser->m_attlistDeclHandler) {\n const XML_Char *prefix;\n if (parser->m_declAttributeType) {\n prefix = enumValueSep;\n } else {\n prefix = (role == XML_ROLE_ATTRIBUTE_NOTATION_VALUE ? notationPrefix\n : enumValueStart);\n }\n if (! poolAppendString(&parser->m_tempPool, prefix))\n return XML_ERROR_NO_MEMORY;\n if (! poolAppend(&parser->m_tempPool, enc, s, next))\n return XML_ERROR_NO_MEMORY;\n parser->m_declAttributeType = parser->m_tempPool.start;\n handleDefault = XML_FALSE;\n }\n break;\n case XML_ROLE_IMPLIED_ATTRIBUTE_VALUE:\n case XML_ROLE_REQUIRED_ATTRIBUTE_VALUE:\n if (dtd->keepProcessing) {\n if (! defineAttribute(parser->m_declElementType,\n parser->m_declAttributeId,\n parser->m_declAttributeIsCdata,\n parser->m_declAttributeIsId, 0, parser))\n return XML_ERROR_NO_MEMORY;\n if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {\n if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)\n || (*parser->m_declAttributeType == XML_T(ASCII_N)\n && parser->m_declAttributeType[1] == XML_T(ASCII_O))) {\n /* Enumerated or Notation type */\n if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))\n || ! poolAppendChar(&parser->m_tempPool, XML_T('\\0')))\n return XML_ERROR_NO_MEMORY;\n parser->m_declAttributeType = parser->m_tempPool.start;\n poolFinish(&parser->m_tempPool);\n }\n *eventEndPP = s;\n parser->m_attlistDeclHandler(\n parser->m_handlerArg, parser->m_declElementType->name,\n parser->m_declAttributeId->name, parser->m_declAttributeType, 0,\n role == XML_ROLE_REQUIRED_ATTRIBUTE_VALUE);\n poolClear(&parser->m_tempPool);\n handleDefault = XML_FALSE;\n }\n }\n break;\n case XML_ROLE_DEFAULT_ATTRIBUTE_VALUE:\n case XML_ROLE_FIXED_ATTRIBUTE_VALUE:\n if (dtd->keepProcessing) {\n const XML_Char *attVal;\n enum XML_Error result = storeAttributeValue(\n parser, enc, parser->m_declAttributeIsCdata,\n s + enc->minBytesPerChar, next - enc->minBytesPerChar, &dtd->pool);\n if (result)\n return result;\n attVal = poolStart(&dtd->pool);\n poolFinish(&dtd->pool);\n /* ID attributes aren't allowed to have a default */\n if (! defineAttribute(\n parser->m_declElementType, parser->m_declAttributeId,\n parser->m_declAttributeIsCdata, XML_FALSE, attVal, parser))\n return XML_ERROR_NO_MEMORY;\n if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {\n if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)\n || (*parser->m_declAttributeType == XML_T(ASCII_N)\n && parser->m_declAttributeType[1] == XML_T(ASCII_O))) {\n /* Enumerated or Notation type */\n if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))\n || ! poolAppendChar(&parser->m_tempPool, XML_T('\\0')))\n return XML_ERROR_NO_MEMORY;\n parser->m_declAttributeType = parser->m_tempPool.start;\n poolFinish(&parser->m_tempPool);\n }\n *eventEndPP = s;\n parser->m_attlistDeclHandler(\n parser->m_handlerArg, parser->m_declElementType->name,\n parser->m_declAttributeId->name, parser->m_declAttributeType,\n attVal, role == XML_ROLE_FIXED_ATTRIBUTE_VALUE);\n poolClear(&parser->m_tempPool);\n handleDefault = XML_FALSE;\n }\n }\n break;\n case XML_ROLE_ENTITY_VALUE:\n if (dtd->keepProcessing) {\n enum XML_Error result = storeEntityValue(\n parser, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar);\n if (parser->m_declEntity) {\n parser->m_declEntity->textPtr = poolStart(&dtd->entityValuePool);\n parser->m_declEntity->textLen\n = (int)(poolLength(&dtd->entityValuePool));\n poolFinish(&dtd->entityValuePool);\n if (parser->m_entityDeclHandler) {\n *eventEndPP = s;\n parser->m_entityDeclHandler(\n parser->m_handlerArg, parser->m_declEntity->name,\n parser->m_declEntity->is_param, parser->m_declEntity->textPtr,\n parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0);\n handleDefault = XML_FALSE;\n }\n } else\n poolDiscard(&dtd->entityValuePool);\n if (result != XML_ERROR_NONE)\n return result;\n }\n break;\n case XML_ROLE_DOCTYPE_SYSTEM_ID:\n#ifdef XML_DTD\n parser->m_useForeignDTD = XML_FALSE;\n#endif /* XML_DTD */\n dtd->hasParamEntityRefs = XML_TRUE;\n if (parser->m_startDoctypeDeclHandler) {\n parser->m_doctypeSysid = poolStoreString(&parser->m_tempPool, enc,\n s + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (parser->m_doctypeSysid == NULL)\n return XML_ERROR_NO_MEMORY;\n poolFinish(&parser->m_tempPool);\n handleDefault = XML_FALSE;\n }\n#ifdef XML_DTD\n else\n /* use externalSubsetName to make parser->m_doctypeSysid non-NULL\n for the case where no parser->m_startDoctypeDeclHandler is set */\n parser->m_doctypeSysid = externalSubsetName;\n#endif /* XML_DTD */\n if (! dtd->standalone\n#ifdef XML_DTD\n && ! parser->m_paramEntityParsing\n#endif /* XML_DTD */\n && parser->m_notStandaloneHandler\n && ! parser->m_notStandaloneHandler(parser->m_handlerArg))\n return XML_ERROR_NOT_STANDALONE;\n#ifndef XML_DTD\n break;\n#else /* XML_DTD */\n if (! parser->m_declEntity) {\n parser->m_declEntity = (ENTITY *)lookup(\n parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY));\n if (! parser->m_declEntity)\n return XML_ERROR_NO_MEMORY;\n parser->m_declEntity->publicId = NULL;\n }\n#endif /* XML_DTD */\n /* fall through */\n case XML_ROLE_ENTITY_SYSTEM_ID:\n if (dtd->keepProcessing && parser->m_declEntity) {\n parser->m_declEntity->systemId\n = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (! parser->m_declEntity->systemId)\n return XML_ERROR_NO_MEMORY;\n parser->m_declEntity->base = parser->m_curBase;\n poolFinish(&dtd->pool);\n /* Don't suppress the default handler if we fell through from\n * the XML_ROLE_DOCTYPE_SYSTEM_ID case.\n */\n if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_SYSTEM_ID)\n handleDefault = XML_FALSE;\n }\n break;\n case XML_ROLE_ENTITY_COMPLETE:\n if (dtd->keepProcessing && parser->m_declEntity\n && parser->m_entityDeclHandler) {\n *eventEndPP = s;\n parser->m_entityDeclHandler(\n parser->m_handlerArg, parser->m_declEntity->name,\n parser->m_declEntity->is_param, 0, 0, parser->m_declEntity->base,\n parser->m_declEntity->systemId, parser->m_declEntity->publicId, 0);\n handleDefault = XML_FALSE;\n }\n break;\n case XML_ROLE_ENTITY_NOTATION_NAME:\n if (dtd->keepProcessing && parser->m_declEntity) {\n parser->m_declEntity->notation\n = poolStoreString(&dtd->pool, enc, s, next);\n if (! parser->m_declEntity->notation)\n return XML_ERROR_NO_MEMORY;\n poolFinish(&dtd->pool);\n if (parser->m_unparsedEntityDeclHandler) {\n *eventEndPP = s;\n parser->m_unparsedEntityDeclHandler(\n parser->m_handlerArg, parser->m_declEntity->name,\n parser->m_declEntity->base, parser->m_declEntity->systemId,\n parser->m_declEntity->publicId, parser->m_declEntity->notation);\n handleDefault = XML_FALSE;\n } else if (parser->m_entityDeclHandler) {\n *eventEndPP = s;\n parser->m_entityDeclHandler(\n parser->m_handlerArg, parser->m_declEntity->name, 0, 0, 0,\n parser->m_declEntity->base, parser->m_declEntity->systemId,\n parser->m_declEntity->publicId, parser->m_declEntity->notation);\n handleDefault = XML_FALSE;\n }\n }\n break;\n case XML_ROLE_GENERAL_ENTITY_NAME: {\n if (XmlPredefinedEntityName(enc, s, next)) {\n parser->m_declEntity = NULL;\n break;\n }\n if (dtd->keepProcessing) {\n const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);\n if (! name)\n return XML_ERROR_NO_MEMORY;\n parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->generalEntities,\n name, sizeof(ENTITY));\n if (! parser->m_declEntity)\n return XML_ERROR_NO_MEMORY;\n if (parser->m_declEntity->name != name) {\n poolDiscard(&dtd->pool);\n parser->m_declEntity = NULL;\n } else {\n poolFinish(&dtd->pool);\n parser->m_declEntity->publicId = NULL;\n parser->m_declEntity->is_param = XML_FALSE;\n /* if we have a parent parser or are reading an internal parameter\n entity, then the entity declaration is not considered \"internal\"\n */\n parser->m_declEntity->is_internal\n = ! (parser->m_parentParser || parser->m_openInternalEntities);\n if (parser->m_entityDeclHandler)\n handleDefault = XML_FALSE;\n }\n } else {\n poolDiscard(&dtd->pool);\n parser->m_declEntity = NULL;\n }\n } break;\n case XML_ROLE_PARAM_ENTITY_NAME:\n#ifdef XML_DTD\n if (dtd->keepProcessing) {\n const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);\n if (! name)\n return XML_ERROR_NO_MEMORY;\n parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->paramEntities,\n name, sizeof(ENTITY));\n if (! parser->m_declEntity)\n return XML_ERROR_NO_MEMORY;\n if (parser->m_declEntity->name != name) {\n poolDiscard(&dtd->pool);\n parser->m_declEntity = NULL;\n } else {\n poolFinish(&dtd->pool);\n parser->m_declEntity->publicId = NULL;\n parser->m_declEntity->is_param = XML_TRUE;\n /* if we have a parent parser or are reading an internal parameter\n entity, then the entity declaration is not considered \"internal\"\n */\n parser->m_declEntity->is_internal\n = ! (parser->m_parentParser || parser->m_openInternalEntities);\n if (parser->m_entityDeclHandler)\n handleDefault = XML_FALSE;\n }\n } else {\n poolDiscard(&dtd->pool);\n parser->m_declEntity = NULL;\n }\n#else /* not XML_DTD */\n parser->m_declEntity = NULL;\n#endif /* XML_DTD */\n break;\n case XML_ROLE_NOTATION_NAME:\n parser->m_declNotationPublicId = NULL;\n parser->m_declNotationName = NULL;\n if (parser->m_notationDeclHandler) {\n parser->m_declNotationName\n = poolStoreString(&parser->m_tempPool, enc, s, next);\n if (! parser->m_declNotationName)\n return XML_ERROR_NO_MEMORY;\n poolFinish(&parser->m_tempPool);\n handleDefault = XML_FALSE;\n }\n break;\n case XML_ROLE_NOTATION_PUBLIC_ID:\n if (! XmlIsPublicId(enc, s, next, eventPP))\n return XML_ERROR_PUBLICID;\n if (parser\n ->m_declNotationName) { /* means m_notationDeclHandler != NULL */\n XML_Char *tem = poolStoreString(&parser->m_tempPool, enc,\n s + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (! tem)\n return XML_ERROR_NO_MEMORY;\n normalizePublicId(tem);\n parser->m_declNotationPublicId = tem;\n poolFinish(&parser->m_tempPool);\n handleDefault = XML_FALSE;\n }\n break;\n case XML_ROLE_NOTATION_SYSTEM_ID:\n if (parser->m_declNotationName && parser->m_notationDeclHandler) {\n const XML_Char *systemId = poolStoreString(&parser->m_tempPool, enc,\n s + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (! systemId)\n return XML_ERROR_NO_MEMORY;\n *eventEndPP = s;\n parser->m_notationDeclHandler(\n parser->m_handlerArg, parser->m_declNotationName, parser->m_curBase,\n systemId, parser->m_declNotationPublicId);\n handleDefault = XML_FALSE;\n }\n poolClear(&parser->m_tempPool);\n break;\n case XML_ROLE_NOTATION_NO_SYSTEM_ID:\n if (parser->m_declNotationPublicId && parser->m_notationDeclHandler) {\n *eventEndPP = s;\n parser->m_notationDeclHandler(\n parser->m_handlerArg, parser->m_declNotationName, parser->m_curBase,\n 0, parser->m_declNotationPublicId);\n handleDefault = XML_FALSE;\n }\n poolClear(&parser->m_tempPool);\n break;\n case XML_ROLE_ERROR:\n switch (tok) {\n case XML_TOK_PARAM_ENTITY_REF:\n /* PE references in internal subset are\n not allowed within declarations. */\n return XML_ERROR_PARAM_ENTITY_REF;\n case XML_TOK_XML_DECL:\n return XML_ERROR_MISPLACED_XML_PI;\n default:\n return XML_ERROR_SYNTAX;\n }\n#ifdef XML_DTD\n case XML_ROLE_IGNORE_SECT: {\n enum XML_Error result;\n if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n handleDefault = XML_FALSE;\n result = doIgnoreSection(parser, enc, &next, end, nextPtr, haveMore);\n if (result != XML_ERROR_NONE)\n return result;\n else if (! next) {\n parser->m_processor = ignoreSectionProcessor;\n return result;\n }\n } break;\n#endif /* XML_DTD */\n case XML_ROLE_GROUP_OPEN:\n if (parser->m_prologState.level >= parser->m_groupSize) {\n if (parser->m_groupSize) {\n {\n char *const new_connector = (char *)REALLOC(\n parser, parser->m_groupConnector, parser->m_groupSize *= 2);\n if (new_connector == NULL) {\n parser->m_groupSize /= 2;\n return XML_ERROR_NO_MEMORY;\n }\n parser->m_groupConnector = new_connector;\n }\n\n if (dtd->scaffIndex) {\n int *const new_scaff_index = (int *)REALLOC(\n parser, dtd->scaffIndex, parser->m_groupSize * sizeof(int));\n if (new_scaff_index == NULL)\n return XML_ERROR_NO_MEMORY;\n dtd->scaffIndex = new_scaff_index;\n }\n } else {\n parser->m_groupConnector\n = (char *)MALLOC(parser, parser->m_groupSize = 32);\n if (! parser->m_groupConnector) {\n parser->m_groupSize = 0;\n return XML_ERROR_NO_MEMORY;\n }\n }\n }\n parser->m_groupConnector[parser->m_prologState.level] = 0;\n if (dtd->in_eldecl) {\n int myindex = nextScaffoldPart(parser);\n if (myindex < 0)\n return XML_ERROR_NO_MEMORY;\n assert(dtd->scaffIndex != NULL);\n dtd->scaffIndex[dtd->scaffLevel] = myindex;\n dtd->scaffLevel++;\n dtd->scaffold[myindex].type = XML_CTYPE_SEQ;\n if (parser->m_elementDeclHandler)\n handleDefault = XML_FALSE;\n }\n break;\n case XML_ROLE_GROUP_SEQUENCE:\n if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_PIPE)\n return XML_ERROR_SYNTAX;\n parser->m_groupConnector[parser->m_prologState.level] = ASCII_COMMA;\n if (dtd->in_eldecl && parser->m_elementDeclHandler)\n handleDefault = XML_FALSE;\n break;\n case XML_ROLE_GROUP_CHOICE:\n if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_COMMA)\n return XML_ERROR_SYNTAX;\n if (dtd->in_eldecl\n && ! parser->m_groupConnector[parser->m_prologState.level]\n && (dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type\n != XML_CTYPE_MIXED)) {\n dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type\n = XML_CTYPE_CHOICE;\n if (parser->m_elementDeclHandler)\n handleDefault = XML_FALSE;\n }\n parser->m_groupConnector[parser->m_prologState.level] = ASCII_PIPE;\n break;\n case XML_ROLE_PARAM_ENTITY_REF:\n#ifdef XML_DTD\n case XML_ROLE_INNER_PARAM_ENTITY_REF:\n dtd->hasParamEntityRefs = XML_TRUE;\n if (! parser->m_paramEntityParsing)\n dtd->keepProcessing = dtd->standalone;\n else {\n const XML_Char *name;\n ENTITY *entity;\n name = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (! name)\n return XML_ERROR_NO_MEMORY;\n entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0);\n poolDiscard(&dtd->pool);\n /* first, determine if a check for an existing declaration is needed;\n if yes, check that the entity exists, and that it is internal,\n otherwise call the skipped entity handler\n */\n if (parser->m_prologState.documentEntity\n && (dtd->standalone ? ! parser->m_openInternalEntities\n : ! dtd->hasParamEntityRefs)) {\n if (! entity)\n return XML_ERROR_UNDEFINED_ENTITY;\n else if (! entity->is_internal) {\n /* It's hard to exhaustively search the code to be sure,\n * but there doesn't seem to be a way of executing the\n * following line. There are two cases:\n *\n * If 'standalone' is false, the DTD must have no\n * parameter entities or we wouldn't have passed the outer\n * 'if' statement. That measn the only entity in the hash\n * table is the external subset name \"#\" which cannot be\n * given as a parameter entity name in XML syntax, so the\n * lookup must have returned NULL and we don't even reach\n * the test for an internal entity.\n *\n * If 'standalone' is true, it does not seem to be\n * possible to create entities taking this code path that\n * are not internal entities, so fail the test above.\n *\n * Because this analysis is very uncertain, the code is\n * being left in place and merely removed from the\n * coverage test statistics.\n */\n return XML_ERROR_ENTITY_DECLARED_IN_PE; /* LCOV_EXCL_LINE */\n }\n } else if (! entity) {\n dtd->keepProcessing = dtd->standalone;\n /* cannot report skipped entities in declarations */\n if ((role == XML_ROLE_PARAM_ENTITY_REF)\n && parser->m_skippedEntityHandler) {\n parser->m_skippedEntityHandler(parser->m_handlerArg, name, 1);\n handleDefault = XML_FALSE;\n }\n break;\n }\n if (entity->open)\n return XML_ERROR_RECURSIVE_ENTITY_REF;\n if (entity->textPtr) {\n enum XML_Error result;\n XML_Bool betweenDecl\n = (role == XML_ROLE_PARAM_ENTITY_REF ? XML_TRUE : XML_FALSE);\n result = processInternalEntity(parser, entity, betweenDecl);\n if (result != XML_ERROR_NONE)\n return result;\n handleDefault = XML_FALSE;\n break;\n }\n if (parser->m_externalEntityRefHandler) {\n dtd->paramEntityRead = XML_FALSE;\n entity->open = XML_TRUE;\n if (! parser->m_externalEntityRefHandler(\n parser->m_externalEntityRefHandlerArg, 0, entity->base,\n entity->systemId, entity->publicId)) {\n entity->open = XML_FALSE;\n return XML_ERROR_EXTERNAL_ENTITY_HANDLING;\n }\n entity->open = XML_FALSE;\n handleDefault = XML_FALSE;\n if (! dtd->paramEntityRead) {\n dtd->keepProcessing = dtd->standalone;\n break;\n }\n } else {\n dtd->keepProcessing = dtd->standalone;\n break;\n }\n }\n#endif /* XML_DTD */\n if (! dtd->standalone && parser->m_notStandaloneHandler\n && ! parser->m_notStandaloneHandler(parser->m_handlerArg))\n return XML_ERROR_NOT_STANDALONE;\n break;\n\n /* Element declaration stuff */\n\n case XML_ROLE_ELEMENT_NAME:\n if (parser->m_elementDeclHandler) {\n parser->m_declElementType = getElementType(parser, enc, s, next);\n if (! parser->m_declElementType)\n return XML_ERROR_NO_MEMORY;\n dtd->scaffLevel = 0;\n dtd->scaffCount = 0;\n dtd->in_eldecl = XML_TRUE;\n handleDefault = XML_FALSE;\n }\n break;\n\n case XML_ROLE_CONTENT_ANY:\n case XML_ROLE_CONTENT_EMPTY:\n if (dtd->in_eldecl) {\n if (parser->m_elementDeclHandler) {\n XML_Content *content\n = (XML_Content *)MALLOC(parser, sizeof(XML_Content));\n if (! content)\n return XML_ERROR_NO_MEMORY;\n content->quant = XML_CQUANT_NONE;\n content->name = NULL;\n content->numchildren = 0;\n content->children = NULL;\n content->type = ((role == XML_ROLE_CONTENT_ANY) ? XML_CTYPE_ANY\n : XML_CTYPE_EMPTY);\n *eventEndPP = s;\n parser->m_elementDeclHandler(\n parser->m_handlerArg, parser->m_declElementType->name, content);\n handleDefault = XML_FALSE;\n }\n dtd->in_eldecl = XML_FALSE;\n }\n break;\n\n case XML_ROLE_CONTENT_PCDATA:\n if (dtd->in_eldecl) {\n dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type\n = XML_CTYPE_MIXED;\n if (parser->m_elementDeclHandler)\n handleDefault = XML_FALSE;\n }\n break;\n\n case XML_ROLE_CONTENT_ELEMENT:\n quant = XML_CQUANT_NONE;\n goto elementContent;\n case XML_ROLE_CONTENT_ELEMENT_OPT:\n quant = XML_CQUANT_OPT;\n goto elementContent;\n case XML_ROLE_CONTENT_ELEMENT_REP:\n quant = XML_CQUANT_REP;\n goto elementContent;\n case XML_ROLE_CONTENT_ELEMENT_PLUS:\n quant = XML_CQUANT_PLUS;\n elementContent:\n if (dtd->in_eldecl) {\n ELEMENT_TYPE *el;\n const XML_Char *name;\n int nameLen;\n const char *nxt\n = (quant == XML_CQUANT_NONE ? next : next - enc->minBytesPerChar);\n int myindex = nextScaffoldPart(parser);\n if (myindex < 0)\n return XML_ERROR_NO_MEMORY;\n dtd->scaffold[myindex].type = XML_CTYPE_NAME;\n dtd->scaffold[myindex].quant = quant;\n el = getElementType(parser, enc, s, nxt);\n if (! el)\n return XML_ERROR_NO_MEMORY;\n name = el->name;\n dtd->scaffold[myindex].name = name;\n nameLen = 0;\n for (; name[nameLen++];)\n ;\n dtd->contentStringLen += nameLen;\n if (parser->m_elementDeclHandler)\n handleDefault = XML_FALSE;\n }\n break;\n\n case XML_ROLE_GROUP_CLOSE:\n quant = XML_CQUANT_NONE;\n goto closeGroup;\n case XML_ROLE_GROUP_CLOSE_OPT:\n quant = XML_CQUANT_OPT;\n goto closeGroup;\n case XML_ROLE_GROUP_CLOSE_REP:\n quant = XML_CQUANT_REP;\n goto closeGroup;\n case XML_ROLE_GROUP_CLOSE_PLUS:\n quant = XML_CQUANT_PLUS;\n closeGroup:\n if (dtd->in_eldecl) {\n if (parser->m_elementDeclHandler)\n handleDefault = XML_FALSE;\n dtd->scaffLevel--;\n dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel]].quant = quant;\n if (dtd->scaffLevel == 0) {\n if (! handleDefault) {\n XML_Content *model = build_model(parser);\n if (! model)\n return XML_ERROR_NO_MEMORY;\n *eventEndPP = s;\n parser->m_elementDeclHandler(\n parser->m_handlerArg, parser->m_declElementType->name, model);\n }\n dtd->in_eldecl = XML_FALSE;\n dtd->contentStringLen = 0;\n }\n }\n break;\n /* End element declaration stuff */\n\n case XML_ROLE_PI:\n if (! reportProcessingInstruction(parser, enc, s, next))\n return XML_ERROR_NO_MEMORY;\n handleDefault = XML_FALSE;\n break;\n case XML_ROLE_COMMENT:\n if (! reportComment(parser, enc, s, next))\n return XML_ERROR_NO_MEMORY;\n handleDefault = XML_FALSE;\n break;\n case XML_ROLE_NONE:\n switch (tok) {\n case XML_TOK_BOM:\n handleDefault = XML_FALSE;\n break;\n }\n break;\n case XML_ROLE_DOCTYPE_NONE:\n if (parser->m_startDoctypeDeclHandler)\n handleDefault = XML_FALSE;\n break;\n case XML_ROLE_ENTITY_NONE:\n if (dtd->keepProcessing && parser->m_entityDeclHandler)\n handleDefault = XML_FALSE;\n break;\n case XML_ROLE_NOTATION_NONE:\n if (parser->m_notationDeclHandler)\n handleDefault = XML_FALSE;\n break;\n case XML_ROLE_ATTLIST_NONE:\n if (dtd->keepProcessing && parser->m_attlistDeclHandler)\n handleDefault = XML_FALSE;\n break;\n case XML_ROLE_ELEMENT_NONE:\n if (parser->m_elementDeclHandler)\n handleDefault = XML_FALSE;\n break;\n } /* end of big switch */\n\n if (handleDefault && parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n\n switch (parser->m_parsingStatus.parsing) {\n case XML_SUSPENDED:\n *nextPtr = next;\n return XML_ERROR_NONE;\n case XML_FINISHED:\n return XML_ERROR_ABORTED;\n default:\n s = next;\n tok = XmlPrologTok(enc, s, end, &next);\n }\n }\n /* not reached */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-611', 'CWE-776', 'CWE-415', 'CWE-125'], 'message': 'xmlparse.c: Deny internal entities closing the doctype'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TEST(HeaderMapImplTest, InlineInsert) {\n HeaderMapImpl headers;\n EXPECT_TRUE(headers.empty());\n EXPECT_EQ(0, headers.size());\n EXPECT_EQ(nullptr, headers.Host());\n headers.insertHost().value(std::string(\"hello\"));\n EXPECT_FALSE(headers.empty());\n EXPECT_EQ(1, headers.size());\n EXPECT_EQ(\":authority\", headers.Host()->key().getStringView());\n EXPECT_EQ(\"hello\", headers.Host()->value().getStringView());\n EXPECT_EQ(\"hello\", headers.get(Headers::get().Host)->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: HttpIntegrationTest::waitForNextUpstreamRequest(const std::vector& upstream_indices) {\n uint64_t upstream_with_request;\n // If there is no upstream connection, wait for it to be established.\n if (!fake_upstream_connection_) {\n\n AssertionResult result = AssertionFailure();\n for (auto upstream_index : upstream_indices) {\n result = fake_upstreams_[upstream_index]->waitForHttpConnection(\n *dispatcher_, fake_upstream_connection_, TestUtility::DefaultTimeout,\n max_request_headers_kb_);\n if (result) {\n upstream_with_request = upstream_index;\n break;\n }\n }\n RELEASE_ASSERT(result, result.message());\n }\n // Wait for the next stream on the upstream connection.\n AssertionResult result =\n fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_);\n RELEASE_ASSERT(result, result.message());\n // Wait for the stream to be completely received.\n result = upstream_request_->waitForEndStream(*dispatcher_);\n RELEASE_ASSERT(result, result.message());\n\n return upstream_with_request;\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, PseudoHeaderOrder) {\n using MockCb = testing::MockFunction;\n MockCb cb;\n\n {\n LowerCaseString foo(\"hello\");\n Http::TestHeaderMapImpl headers{};\n EXPECT_EQ(0UL, headers.size());\n EXPECT_TRUE(headers.empty());\n\n headers.addReferenceKey(foo, \"world\");\n EXPECT_EQ(1UL, headers.size());\n EXPECT_FALSE(headers.empty());\n\n headers.setReferenceKey(Headers::get().ContentType, \"text/html\");\n EXPECT_EQ(2UL, headers.size());\n EXPECT_FALSE(headers.empty());\n\n // Pseudo header gets inserted before non-pseudo headers\n headers.setReferenceKey(Headers::get().Method, \"PUT\");\n EXPECT_EQ(3UL, headers.size());\n EXPECT_FALSE(headers.empty());\n\n InSequence seq;\n EXPECT_CALL(cb, Call(\":method\", \"PUT\"));\n EXPECT_CALL(cb, Call(\"hello\", \"world\"));\n EXPECT_CALL(cb, Call(\"content-type\", \"text/html\"));\n\n headers.iterate(\n [](const Http::HeaderEntry& header, void* cb_v) -> HeaderMap::Iterate {\n static_cast(cb_v)->Call(std::string(header.key().getStringView()),\n std::string(header.value().getStringView()));\n return HeaderMap::Iterate::Continue;\n },\n &cb);\n\n // Removal of the header before which pseudo-headers are inserted\n headers.remove(foo);\n EXPECT_EQ(2UL, headers.size());\n EXPECT_FALSE(headers.empty());\n\n EXPECT_CALL(cb, Call(\":method\", \"PUT\"));\n EXPECT_CALL(cb, Call(\"content-type\", \"text/html\"));\n\n headers.iterate(\n [](const Http::HeaderEntry& header, void* cb_v) -> HeaderMap::Iterate {\n static_cast(cb_v)->Call(std::string(header.key().getStringView()),\n std::string(header.value().getStringView()));\n return HeaderMap::Iterate::Continue;\n },\n &cb);\n\n // Next pseudo-header goes after other pseudo-headers, but before normal headers\n headers.setReferenceKey(Headers::get().Path, \"/test\");\n EXPECT_EQ(3UL, headers.size());\n EXPECT_FALSE(headers.empty());\n\n EXPECT_CALL(cb, Call(\":method\", \"PUT\"));\n EXPECT_CALL(cb, Call(\":path\", \"/test\"));\n EXPECT_CALL(cb, Call(\"content-type\", \"text/html\"));\n\n headers.iterate(\n [](const Http::HeaderEntry& header, void* cb_v) -> HeaderMap::Iterate {\n static_cast(cb_v)->Call(std::string(header.key().getStringView()),\n std::string(header.value().getStringView()));\n return HeaderMap::Iterate::Continue;\n },\n &cb);\n\n // Removing the last normal header\n headers.remove(Headers::get().ContentType);\n EXPECT_EQ(2UL, headers.size());\n EXPECT_FALSE(headers.empty());\n\n EXPECT_CALL(cb, Call(\":method\", \"PUT\"));\n EXPECT_CALL(cb, Call(\":path\", \"/test\"));\n\n headers.iterate(\n [](const Http::HeaderEntry& header, void* cb_v) -> HeaderMap::Iterate {\n static_cast(cb_v)->Call(std::string(header.key().getStringView()),\n std::string(header.value().getStringView()));\n return HeaderMap::Iterate::Continue;\n },\n &cb);\n\n // Adding a new pseudo-header after removing the last normal header\n headers.setReferenceKey(Headers::get().Host, \"host\");\n EXPECT_EQ(3UL, headers.size());\n EXPECT_FALSE(headers.empty());\n\n EXPECT_CALL(cb, Call(\":method\", \"PUT\"));\n EXPECT_CALL(cb, Call(\":path\", \"/test\"));\n EXPECT_CALL(cb, Call(\":authority\", \"host\"));\n\n headers.iterate(\n [](const Http::HeaderEntry& header, void* cb_v) -> HeaderMap::Iterate {\n static_cast(cb_v)->Call(std::string(header.key().getStringView()),\n std::string(header.value().getStringView()));\n return HeaderMap::Iterate::Continue;\n },\n &cb);\n\n // Adding the first normal header\n headers.setReferenceKey(Headers::get().ContentType, \"text/html\");\n EXPECT_EQ(4UL, headers.size());\n EXPECT_FALSE(headers.empty());\n\n EXPECT_CALL(cb, Call(\":method\", \"PUT\"));\n EXPECT_CALL(cb, Call(\":path\", \"/test\"));\n EXPECT_CALL(cb, Call(\":authority\", \"host\"));\n EXPECT_CALL(cb, Call(\"content-type\", \"text/html\"));\n\n headers.iterate(\n [](const Http::HeaderEntry& header, void* cb_v) -> HeaderMap::Iterate {\n static_cast(cb_v)->Call(std::string(header.key().getStringView()),\n std::string(header.value().getStringView()));\n return HeaderMap::Iterate::Continue;\n },\n &cb);\n\n // Removing all pseudo-headers\n headers.remove(Headers::get().Path);\n headers.remove(Headers::get().Method);\n headers.remove(Headers::get().Host);\n EXPECT_EQ(1UL, headers.size());\n EXPECT_FALSE(headers.empty());\n\n EXPECT_CALL(cb, Call(\"content-type\", \"text/html\"));\n\n headers.iterate(\n [](const Http::HeaderEntry& header, void* cb_v) -> HeaderMap::Iterate {\n static_cast(cb_v)->Call(std::string(header.key().getStringView()),\n std::string(header.value().getStringView()));\n return HeaderMap::Iterate::Continue;\n },\n &cb);\n\n // Removing all headers\n headers.remove(Headers::get().ContentType);\n EXPECT_EQ(0UL, headers.size());\n EXPECT_TRUE(headers.empty());\n\n // Adding a lone pseudo-header\n headers.setReferenceKey(Headers::get().Status, \"200\");\n EXPECT_EQ(1UL, headers.size());\n EXPECT_FALSE(headers.empty());\n\n EXPECT_CALL(cb, Call(\":status\", \"200\"));\n\n headers.iterate(\n [](const Http::HeaderEntry& header, void* cb_v) -> HeaderMap::Iterate {\n static_cast(cb_v)->Call(std::string(header.key().getStringView()),\n std::string(header.value().getStringView()));\n return HeaderMap::Iterate::Continue;\n },\n &cb);\n }\n\n // Starting with a normal header\n {\n Http::TestHeaderMapImpl headers{{\"content-type\", \"text/plain\"},\n {\":method\", \"GET\"},\n {\":path\", \"/\"},\n {\"hello\", \"world\"},\n {\":authority\", \"host\"}};\n\n InSequence seq;\n EXPECT_CALL(cb, Call(\":method\", \"GET\"));\n EXPECT_CALL(cb, Call(\":path\", \"/\"));\n EXPECT_CALL(cb, Call(\":authority\", \"host\"));\n EXPECT_CALL(cb, Call(\"content-type\", \"text/plain\"));\n EXPECT_CALL(cb, Call(\"hello\", \"world\"));\n\n headers.iterate(\n [](const Http::HeaderEntry& header, void* cb_v) -> HeaderMap::Iterate {\n static_cast(cb_v)->Call(std::string(header.key().getStringView()),\n std::string(header.value().getStringView()));\n return HeaderMap::Iterate::Continue;\n },\n &cb);\n }\n\n // Starting with a pseudo-header\n {\n Http::TestHeaderMapImpl headers{{\":path\", \"/\"},\n {\"content-type\", \"text/plain\"},\n {\":method\", \"GET\"},\n {\"hello\", \"world\"},\n {\":authority\", \"host\"}};\n\n InSequence seq;\n EXPECT_CALL(cb, Call(\":path\", \"/\"));\n EXPECT_CALL(cb, Call(\":method\", \"GET\"));\n EXPECT_CALL(cb, Call(\":authority\", \"host\"));\n EXPECT_CALL(cb, Call(\"content-type\", \"text/plain\"));\n EXPECT_CALL(cb, Call(\"hello\", \"world\"));\n\n headers.iterate(\n [](const Http::HeaderEntry& header, void* cb_v) -> HeaderMap::Iterate {\n static_cast(cb_v)->Call(std::string(header.key().getStringView()),\n std::string(header.value().getStringView()));\n return HeaderMap::Iterate::Continue;\n },\n &cb);\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: TEST(HeaderMapImplTest, AddReferenceKey) {\n HeaderMapImpl headers;\n LowerCaseString foo(\"hello\");\n headers.addReferenceKey(foo, \"world\");\n EXPECT_NE(\"world\", headers.get(foo)->value().getStringView().data());\n EXPECT_EQ(\"world\", headers.get(foo)->value().getStringView());\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.\n\nIntroduces a cached byte size updated internally in HeaderMap. The value\nis stored as an optional, and is cleared whenever a non-const pointer or\nreference to a HeaderEntry is accessed. The cached value can be set with\nrefreshByteSize() which performs an iteration over the HeaderMap to sum\nthe size of each key and value in the HeaderMap.\n\nSigned-off-by: Asra Ali '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: string_vformat(gstring * g, BOOL extend, const char *format, va_list ap)\n{\nenum ltypes { L_NORMAL=1, L_SHORT=2, L_LONG=3, L_LONGLONG=4, L_LONGDOUBLE=5, L_SIZE=6 };\n\nint width, precision, off, lim;\nconst char * fp = format;\t/* Deliberately not unsigned */\n\nstring_datestamp_offset = -1;\t/* Datestamp not inserted */\nstring_datestamp_length = 0;\t/* Datestamp not inserted */\nstring_datestamp_type = 0;\t/* Datestamp not inserted */\n\n#ifdef COMPILE_UTILITY\nassert(!extend);\nassert(g);\n#else\n\n/* Ensure we have a string, to save on checking later */\nif (!g) g = string_get(16);\n#endif\t/*!COMPILE_UTILITY*/\n\nlim = g->size - 1;\t/* leave one for a nul */\noff = g->ptr;\t\t/* remember initial offset in gstring */\n\n/* Scan the format and handle the insertions */\n\nwhile (*fp)\n {\n int length = L_NORMAL;\n int *nptr;\n int slen;\n const char *null = \"NULL\";\t\t/* ) These variables */\n const char *item_start, *s;\t\t/* ) are deliberately */\n char newformat[16];\t\t\t/* ) not unsigned */\n char * gp = CS g->s + g->ptr;\t\t/* ) */\n\n /* Non-% characters just get copied verbatim */\n\n if (*fp != '%')\n {\n /* Avoid string_copyn() due to COMPILE_UTILITY */\n if (g->ptr >= lim - 1)\n {\n if (!extend) return NULL;\n gstring_grow(g, g->ptr, 1);\n lim = g->size - 1;\n }\n g->s[g->ptr++] = (uschar) *fp++;\n continue;\n }\n\n /* Deal with % characters. Pick off the width and precision, for checking\n strings, skipping over the flag and modifier characters. */\n\n item_start = fp;\n width = precision = -1;\n\n if (strchr(\"-+ #0\", *(++fp)) != NULL)\n {\n if (*fp == '#') null = \"\";\n fp++;\n }\n\n if (isdigit((uschar)*fp))\n {\n width = *fp++ - '0';\n while (isdigit((uschar)*fp)) width = width * 10 + *fp++ - '0';\n }\n else if (*fp == '*')\n {\n width = va_arg(ap, int);\n fp++;\n }\n\n if (*fp == '.')\n if (*(++fp) == '*')\n {\n precision = va_arg(ap, int);\n fp++;\n }\n else\n for (precision = 0; isdigit((uschar)*fp); fp++)\n precision = precision*10 + *fp - '0';\n\n /* Skip over 'h', 'L', 'l', 'll' and 'z', remembering the item length */\n\n if (*fp == 'h')\n { fp++; length = L_SHORT; }\n else if (*fp == 'L')\n { fp++; length = L_LONGDOUBLE; }\n else if (*fp == 'l')\n if (fp[1] == 'l')\n { fp += 2; length = L_LONGLONG; }\n else\n { fp++; length = L_LONG; }\n else if (*fp == 'z')\n { fp++; length = L_SIZE; }\n\n /* Handle each specific format type. */\n\n switch (*fp++)\n {\n case 'n':\n nptr = va_arg(ap, int *);\n *nptr = g->ptr - off;\n break;\n\n case 'd':\n case 'o':\n case 'u':\n case 'x':\n case 'X':\n width = length > L_LONG ? 24 : 12;\n if (g->ptr >= lim - width)\n\t{\n\tif (!extend) return NULL;\n\tgstring_grow(g, g->ptr, width);\n\tlim = g->size - 1;\n\tgp = CS g->s + g->ptr;\n\t}\n strncpy(newformat, item_start, fp - item_start);\n newformat[fp - item_start] = 0;\n\n /* Short int is promoted to int when passing through ..., so we must use\n int for va_arg(). */\n\n switch(length)\n\t{\n\tcase L_SHORT:\n\tcase L_NORMAL:\n\t g->ptr += sprintf(gp, newformat, va_arg(ap, int)); break;\n\tcase L_LONG:\n\t g->ptr += sprintf(gp, newformat, va_arg(ap, long int)); break;\n\tcase L_LONGLONG:\n\t g->ptr += sprintf(gp, newformat, va_arg(ap, LONGLONG_T)); break;\n\tcase L_SIZE:\n\t g->ptr += sprintf(gp, newformat, va_arg(ap, size_t)); break;\n\t}\n break;\n\n case 'p':\n {\n void * ptr;\n if (g->ptr >= lim - 24)\n\t{\n\tif (!extend) return NULL;\n\tgstring_grow(g, g->ptr, 24);\n\tlim = g->size - 1;\n\tgp = CS g->s + g->ptr;\n\t}\n /* sprintf() saying \"(nil)\" for a null pointer seems unreliable.\n Handle it explicitly. */\n if ((ptr = va_arg(ap, void *)))\n\t{\n\tstrncpy(newformat, item_start, fp - item_start);\n\tnewformat[fp - item_start] = 0;\n\tg->ptr += sprintf(gp, newformat, ptr);\n\t}\n else\n\tg->ptr += sprintf(gp, \"(nil)\");\n }\n break;\n\n /* %f format is inherently insecure if the numbers that it may be\n handed are unknown (e.g. 1e300). However, in Exim, %f is used for\n printing load averages, and these are actually stored as integers\n (load average * 1000) so the size of the numbers is constrained.\n It is also used for formatting sending rates, where the simplicity\n of the format prevents overflow. */\n\n case 'f':\n case 'e':\n case 'E':\n case 'g':\n case 'G':\n if (precision < 0) precision = 6;\n if (g->ptr >= lim - precision - 8)\n\t{\n\tif (!extend) return NULL;\n\tgstring_grow(g, g->ptr, precision+8);\n\tlim = g->size - 1;\n\tgp = CS g->s + g->ptr;\n\t}\n strncpy(newformat, item_start, fp - item_start);\n newformat[fp-item_start] = 0;\n if (length == L_LONGDOUBLE)\n\tg->ptr += sprintf(gp, newformat, va_arg(ap, long double));\n else\n\tg->ptr += sprintf(gp, newformat, va_arg(ap, double));\n break;\n\n /* String types */\n\n case '%':\n if (g->ptr >= lim - 1)\n\t{\n\tif (!extend) return NULL;\n\tgstring_grow(g, g->ptr, 1);\n\tlim = g->size - 1;\n\t}\n g->s[g->ptr++] = (uschar) '%';\n break;\n\n case 'c':\n if (g->ptr >= lim - 1)\n\t{\n\tif (!extend) return NULL;\n\tgstring_grow(g, g->ptr, 1);\n\tlim = g->size - 1;\n\t}\n g->s[g->ptr++] = (uschar) va_arg(ap, int);\n break;\n\n case 'D': /* Insert daily datestamp for log file names */\n s = CS tod_stamp(tod_log_datestamp_daily);\n string_datestamp_offset = g->ptr;\t\t/* Passed back via global */\n string_datestamp_length = Ustrlen(s);\t/* Passed back via global */\n string_datestamp_type = tod_log_datestamp_daily;\n slen = string_datestamp_length;\n goto INSERT_STRING;\n\n case 'M': /* Insert monthly datestamp for log file names */\n s = CS tod_stamp(tod_log_datestamp_monthly);\n string_datestamp_offset = g->ptr;\t\t/* Passed back via global */\n string_datestamp_length = Ustrlen(s);\t/* Passed back via global */\n string_datestamp_type = tod_log_datestamp_monthly;\n slen = string_datestamp_length;\n goto INSERT_STRING;\n\n case 's':\n case 'S': /* Forces *lower* case */\n case 'T': /* Forces *upper* case */\n s = va_arg(ap, char *);\n\n if (!s) s = null;\n slen = Ustrlen(s);\n\n INSERT_STRING: /* Come to from %D or %M above */\n\n {\n BOOL truncated = FALSE;\n\n /* If the width is specified, check that there is a precision\n set; if not, set it to the width to prevent overruns of long\n strings. */\n\n if (width >= 0)\n\t{\n\tif (precision < 0) precision = width;\n\t}\n\n /* If a width is not specified and the precision is specified, set\n the width to the precision, or the string length if shorted. */\n\n else if (precision >= 0)\n\twidth = precision < slen ? precision : slen;\n\n /* If neither are specified, set them both to the string length. */\n\n else\n\twidth = precision = slen;\n\n if (!extend)\n\t{\n\tif (g->ptr == lim) return NULL;\n\tif (g->ptr >= lim - width)\n\t {\n\t truncated = TRUE;\n\t width = precision = lim - g->ptr - 1;\n\t if (width < 0) width = 0;\n\t if (precision < 0) precision = 0;\n\t }\n\t}\n else if (g->ptr >= lim - width)\n\t{\n\tgstring_grow(g, g->ptr, width - (lim - g->ptr));\n\tlim = g->size - 1;\n\tgp = CS g->s + g->ptr;\n\t}\n\n g->ptr += sprintf(gp, \"%*.*s\", width, precision, s);\n if (fp[-1] == 'S')\n\twhile (*gp) { *gp = tolower(*gp); gp++; }\n else if (fp[-1] == 'T')\n\twhile (*gp) { *gp = toupper(*gp); gp++; }\n\n if (truncated) return NULL;\n break;\n }\n\n /* Some things are never used in Exim; also catches junk. */\n\n default:\n strncpy(newformat, item_start, fp - item_start);\n newformat[fp-item_start] = 0;\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"string_format: unsupported type \"\n\t\"in \\\"%s\\\" in \\\"%s\\\"\", newformat, format);\n break;\n }\n }\n\nreturn g;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix buffer overflow in string_vformat. Bug 2449'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: backend_set_handle (struct backend *b, struct connection *conn, void *handle)\n{\n assert (b->i < conn->nr_handles);\n conn->handles[b->i].handle = handle;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-406'], 'message': 'server: Fix regression for NBD_OPT_INFO before NBD_OPT_GO\n\nMost known NBD clients do not bother with NBD_OPT_INFO (except for\nclients like 'qemu-nbd --list' that don't ever intend to connect), but\ngo straight to NBD_OPT_GO. However, it's not too hard to hack up qemu\nto add in an extra client step (whether info on the same name, or more\ninterestingly, info on a different name), as a patch against qemu\ncommit 6f214b30445:\n\n| diff --git i/nbd/client.c w/nbd/client.c\n| index f6733962b49b..425292ac5ea9 100644\n| --- i/nbd/client.c\n| +++ w/nbd/client.c\n| @@ -1038,6 +1038,14 @@ int nbd_receive_negotiate(AioContext *aio_context, QIOChannel *ioc,\n| * TLS). If it is not available, fall back to\n| * NBD_OPT_LIST for nicer error messages about a missing\n| * export, then use NBD_OPT_EXPORT_NAME. */\n| + if (getenv (\"HACK\"))\n| + info->name[0]++;\n| + result = nbd_opt_info_or_go(ioc, NBD_OPT_INFO, info, errp);\n| + if (getenv (\"HACK\"))\n| + info->name[0]--;\n| + if (result < 0) {\n| + return -EINVAL;\n| + }\n| result = nbd_opt_info_or_go(ioc, NBD_OPT_GO, info, errp);\n| if (result < 0) {\n| return -EINVAL;\n\nThis works just fine in 1.14.0, where we call .open only once (so the\nINFO and GO repeat calls into the same plugin handle), but in 1.14.1\nit regressed into causing an assertion failure: we are now calling\n.open a second time on a connection that is already opened:\n\n$ nbdkit -rfv null &\n$ hacked-qemu-io -f raw -r nbd://localhost -c quit\n...\nnbdkit: null[1]: debug: null: open readonly=1\nnbdkit: backend.c:179: backend_open: Assertion `h->handle == NULL' failed.\n\nWorse, on the mainline development, we have recently made it possible\nfor plugins to actively report different information for different\nexport names; for example, a plugin may choose to report different\nanswers for .can_write on export A than for export B; but if we share\ncached handles, then an NBD_OPT_INFO on one export prevents correct\nanswers for NBD_OPT_GO on the second export name. (The HACK envvar in\nmy qemu modifications can be used to demonstrate cross-name requests,\nwhich are even less likely in a real client).\n\nThe solution is to call .close after NBD_OPT_INFO, coupled with enough\nglue logic to reset cached connection handles back to the state\nexpected by .open. This in turn means factoring out another backend_*\nfunction, but also gives us an opportunity to change\nbackend_set_handle to no longer accept NULL.\n\nThe assertion failure is, to some extent, a possible denial of service\nattack (one client can force nbdkit to exit by merely sending OPT_INFO\nbefore OPT_GO, preventing the next client from connecting), although\nthis is mitigated by using TLS to weed out untrusted clients. Still,\nthe fact that we introduced a potential DoS attack while trying to fix\na traffic amplification security bug is not very nice.\n\nSadly, as there are no known clients that easily trigger this mode of\noperation (OPT_INFO before OPT_GO), there is no easy way to cover this\nvia a testsuite addition. I may end up hacking something into libnbd.\n\nFixes: c05686f957\nSigned-off-by: Eric Blake '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: v9fs_file_write_iter(struct kiocb *iocb, struct iov_iter *from)\n{\n\tstruct file *file = iocb->ki_filp;\n\tssize_t retval;\n\tloff_t origin;\n\tint err = 0;\n\n\tretval = generic_write_checks(iocb, from);\n\tif (retval <= 0)\n\t\treturn retval;\n\n\torigin = iocb->ki_pos;\n\tretval = p9_client_write(file->private_data, iocb->ki_pos, from, &err);\n\tif (retval > 0) {\n\t\tstruct inode *inode = file_inode(file);\n\t\tloff_t i_size;\n\t\tunsigned long pg_start, pg_end;\n\t\tpg_start = origin >> PAGE_SHIFT;\n\t\tpg_end = (origin + retval - 1) >> PAGE_SHIFT;\n\t\tif (inode->i_mapping && inode->i_mapping->nrpages)\n\t\t\tinvalidate_inode_pages2_range(inode->i_mapping,\n\t\t\t\t\t\t pg_start, pg_end);\n\t\tiocb->ki_pos += retval;\n\t\ti_size = i_size_read(inode);\n\t\tif (iocb->ki_pos > i_size) {\n\t\t\tinode_add_bytes(inode, iocb->ki_pos - i_size);\n\t\t\ti_size_write(inode, iocb->ki_pos);\n\t\t}\n\t\treturn retval;\n\t}\n\treturn err;\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: Sfdouble_t sh_strnum(Shell_t *shp, const char *str, char **ptr, int mode) {\n Sfdouble_t d;\n char *last;\n\n if (*str == 0) {\n if (ptr) *ptr = (char *)str;\n return 0;\n }\n errno = 0;\n d = number(str, &last, shp->inarith ? 0 : 10, NULL);\n if (*last) {\n if (*last != '.' || last[1] != '.') {\n d = strval(shp, str, &last, arith, mode);\n Varsubscript = true;\n }\n if (!ptr && *last && mode > 0) errormsg(SH_DICT, ERROR_exit(1), e_lexbadchar, *last, str);\n } else if (!d && *str == '-') {\n d = -0.0;\n }\n if (ptr) *ptr = last;\n return d;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-77', 'CWE-74'], 'message': 'Harden env var imports'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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 arc_emac_tx_clean(struct net_device *ndev)\n{\n\tstruct arc_emac_priv *priv = netdev_priv(ndev);\n\tstruct net_device_stats *stats = &ndev->stats;\n\tunsigned int i;\n\n\tfor (i = 0; i < TX_BD_NUM; i++) {\n\t\tunsigned int *txbd_dirty = &priv->txbd_dirty;\n\t\tstruct arc_emac_bd *txbd = &priv->txbd[*txbd_dirty];\n\t\tstruct buffer_state *tx_buff = &priv->tx_buff[*txbd_dirty];\n\t\tstruct sk_buff *skb = tx_buff->skb;\n\t\tunsigned int info = le32_to_cpu(txbd->info);\n\n\t\tif ((info & FOR_EMAC) || !txbd->data)\n\t\t\tbreak;\n\n\t\tif (unlikely(info & (DROP | DEFR | LTCL | UFLO))) {\n\t\t\tstats->tx_errors++;\n\t\t\tstats->tx_dropped++;\n\n\t\t\tif (info & DEFR)\n\t\t\t\tstats->tx_carrier_errors++;\n\n\t\t\tif (info & LTCL)\n\t\t\t\tstats->collisions++;\n\n\t\t\tif (info & UFLO)\n\t\t\t\tstats->tx_fifo_errors++;\n\t\t} else if (likely(info & FIRST_OR_LAST_MASK)) {\n\t\t\tstats->tx_packets++;\n\t\t\tstats->tx_bytes += skb->len;\n\t\t}\n\n\t\tdma_unmap_single(&ndev->dev, dma_unmap_addr(tx_buff, addr),\n\t\t\t\t dma_unmap_len(tx_buff, len), DMA_TO_DEVICE);\n\n\t\t/* return the sk_buff to system */\n\t\tdev_kfree_skb_irq(skb);\n\n\t\ttxbd->data = 0;\n\t\ttxbd->info = 0;\n\n\t\t*txbd_dirty = (*txbd_dirty + 1) % TX_BD_NUM;\n\t}\n\n\t/* Ensure that txbd_dirty is visible to tx() before checking\n\t * for queue stopped.\n\t */\n\tsmp_mb();\n\n\tif (netif_queue_stopped(ndev) && arc_emac_tx_avail(priv))\n\t\tnetif_wake_queue(ndev);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'net: arc_emac: fix koops caused by sk_buff free\n\nThere is a race between arc_emac_tx() and arc_emac_tx_clean().\nsk_buff got freed by arc_emac_tx_clean() while arc_emac_tx()\nsubmitting sk_buff.\n\nIn order to free sk_buff arc_emac_tx_clean() checks:\n if ((info & FOR_EMAC) || !txbd->data)\n break;\n ...\n dev_kfree_skb_irq(skb);\n\nIf condition false, arc_emac_tx_clean() free sk_buff.\n\nIn order to submit txbd, arc_emac_tx() do:\n priv->tx_buff[*txbd_curr].skb = skb;\n ...\n priv->txbd[*txbd_curr].data = cpu_to_le32(addr);\n ...\n ... <== arc_emac_tx_clean() check condition here\n ... <== (info & FOR_EMAC) is false\n ... <== !txbd->data is false\n ...\n *info = cpu_to_le32(FOR_EMAC | FIRST_OR_LAST_MASK | len);\n\nIn order to reproduce the situation,\nrun device:\n # iperf -s\nrun on host:\n # iperf -t 600 -c \n\n[ 28.396284] ------------[ cut here ]------------\n[ 28.400912] kernel BUG at .../net/core/skbuff.c:1355!\n[ 28.414019] Internal error: Oops - BUG: 0 [#1] SMP ARM\n[ 28.419150] Modules linked in:\n[ 28.422219] CPU: 0 PID: 0 Comm: swapper/0 Tainted: G B 4.4.0+ #120\n[ 28.429516] Hardware name: Rockchip (Device Tree)\n[ 28.434216] task: c0665070 ti: c0660000 task.ti: c0660000\n[ 28.439622] PC is at skb_put+0x10/0x54\n[ 28.443381] LR is at arc_emac_poll+0x260/0x474\n[ 28.447821] pc : [] lr : [] psr: a0070113\n[ 28.447821] sp : c0661e58 ip : eea68502 fp : ef377000\n[ 28.459280] r10: 0000012c r9 : f08b2000 r8 : eeb57100\n[ 28.464498] r7 : 00000000 r6 : ef376594 r5 : 00000077 r4 : ef376000\n[ 28.471015] r3 : 0030488b r2 : ef13e880 r1 : 000005ee r0 : eeb57100\n[ 28.477534] Flags: NzCv IRQs on FIQs on Mode SVC_32 ISA ARM Segment none\n[ 28.484658] Control: 10c5387d Table: 8eaf004a DAC: 00000051\n[ 28.490396] Process swapper/0 (pid: 0, stack limit = 0xc0660210)\n[ 28.496393] Stack: (0xc0661e58 to 0xc0662000)\n[ 28.500745] 1e40: 00000002 00000000\n[ 28.508913] 1e60: 00000000 ef376520 00000028 f08b23b8 00000000 ef376520 ef7b6900 c028fc64\n[ 28.517082] 1e80: 2f158000 c0661ea8 c0661eb0 0000012c c065e900 c03bdeac ffff95e9 c0662100\n[ 28.525250] 1ea0: c0663924 00000028 c0661ea8 c0661ea8 c0661eb0 c0661eb0 0000001e c0660000\n[ 28.533417] 1ec0: 40000003 00000008 c0695a00 0000000a c066208c 00000100 c0661ee0 c0027410\n[ 28.541584] 1ee0: ef0fb700 2f158000 00200000 ffff95e8 00000004 c0662100 c0662080 00000003\n[ 28.549751] 1f00: 00000000 00000000 00000000 c065b45c 0000001e ef005000 c0647a30 00000000\n[ 28.557919] 1f20: 00000000 c0027798 00000000 c005cf40 f0802100 c0662ffc c0661f60 f0803100\n[ 28.566088] 1f40: c0661fb8 c00093bc c000ffb4 60070013 ffffffff c0661f94 c0661fb8 c00137d4\n[ 28.574267] 1f60: 00000001 00000000 00000000 c001ffa0 00000000 c0660000 00000000 c065a364\n[ 28.582441] 1f80: c0661fb8 c0647a30 00000000 00000000 00000000 c0661fb0 c000ffb0 c000ffb4\n[ 28.590608] 1fa0: 60070013 ffffffff 00000051 00000000 00000000 c005496c c0662400 c061bc40\n[ 28.598776] 1fc0: ffffffff ffffffff 00000000 c061b680 00000000 c0647a30 00000000 c0695294\n[ 28.606943] 1fe0: c0662488 c0647a2c c066619c 6000406a 413fc090 6000807c 00000000 00000000\n[ 28.615127] [] (skb_put) from [] (0xef376520)\n[ 28.621218] Code: e5902054 e590c090 e3520000 0a000000 (e7f001f2)\n[ 28.627307] ---[ end trace 4824734e2243fdb6 ]---\n\n[ 34.377068] Internal error: Oops: 17 [#1] SMP ARM\n[ 34.382854] Modules linked in:\n[ 34.385947] CPU: 0 PID: 3 Comm: ksoftirqd/0 Not tainted 4.4.0+ #120\n[ 34.392219] Hardware name: Rockchip (Device Tree)\n[ 34.396937] task: ef02d040 ti: ef05c000 task.ti: ef05c000\n[ 34.402376] PC is at __dev_kfree_skb_irq+0x4/0x80\n[ 34.407121] LR is at arc_emac_poll+0x130/0x474\n[ 34.411583] pc : [] lr : [] psr: 60030013\n[ 34.411583] sp : ef05de68 ip : 0008e83c fp : ef377000\n[ 34.423062] r10: c001bec4 r9 : 00000000 r8 : f08b24c8\n[ 34.428296] r7 : f08b2400 r6 : 00000075 r5 : 00000019 r4 : ef376000\n[ 34.434827] r3 : 00060000 r2 : 00000042 r1 : 00000001 r0 : 00000000\n[ 34.441365] Flags: nZCv IRQs on FIQs on Mode SVC_32 ISA ARM Segment none\n[ 34.448507] Control: 10c5387d Table: 8f25c04a DAC: 00000051\n[ 34.454262] Process ksoftirqd/0 (pid: 3, stack limit = 0xef05c210)\n[ 34.460449] Stack: (0xef05de68 to 0xef05e000)\n[ 34.464827] de60: ef376000 c028fd94 00000000 c0669480 c0669480 ef376520\n[ 34.473022] de80: 00000028 00000001 00002ae4 ef376520 ef7b6900 c028fc64 2f158000 ef05dec0\n[ 34.481215] dea0: ef05dec8 0000012c c065e900 c03bdeac ffff983f c0662100 c0663924 00000028\n[ 34.489409] dec0: ef05dec0 ef05dec0 ef05dec8 ef05dec8 ef7b6000 ef05c000 40000003 00000008\n[ 34.497600] dee0: c0695a00 0000000a c066208c 00000100 ef05def8 c0027410 ef7b6000 40000000\n[ 34.505795] df00: 04208040 ffff983e 00000004 c0662100 c0662080 00000003 ef05c000 ef027340\n[ 34.513985] df20: ef05c000 c0666c2c 00000000 00000001 00000002 00000000 00000000 c0027568\n[ 34.522176] df40: ef027340 c003ef48 ef027300 00000000 ef027340 c003edd4 00000000 00000000\n[ 34.530367] df60: 00000000 c003c37c ffffff7f 00000001 00000000 ef027340 00000000 00030003\n[ 34.538559] df80: ef05df80 ef05df80 00000000 00000000 ef05df90 ef05df90 ef05dfac ef027300\n[ 34.546750] dfa0: c003c2a4 00000000 00000000 c000f578 00000000 00000000 00000000 00000000\n[ 34.554939] dfc0: 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000\n[ 34.563129] dfe0: 00000000 00000000 00000000 00000000 00000013 00000000 ffffffff dfff7fff\n[ 34.571360] [] (__dev_kfree_skb_irq) from [] (arc_emac_poll+0x130/0x474)\n[ 34.579840] [] (arc_emac_poll) from [] (net_rx_action+0xdc/0x28c)\n[ 34.587712] [] (net_rx_action) from [] (__do_softirq+0xcc/0x1f8)\n[ 34.595482] [] (__do_softirq) from [] (run_ksoftirqd+0x2c/0x50)\n[ 34.603168] [] (run_ksoftirqd) from [] (smpboot_thread_fn+0x174/0x18c)\n[ 34.611466] [] (smpboot_thread_fn) from [] (kthread+0xd8/0xec)\n[ 34.619075] [] (kthread) from [] (ret_from_fork+0x14/0x3c)\n[ 34.626317] Code: e8bd8010 e3a00000 e12fff1e e92d4010 (e59030a4)\n[ 34.632572] ---[ end trace cca5a3d86a82249a ]---\n\nSigned-off-by: Alexander Kochetkov \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int llcp_sock_create(struct net *net, struct socket *sock,\n\t\t\t const struct nfc_protocol *nfc_proto, int kern)\n{\n\tstruct sock *sk;\n\n\tpr_debug(\"%p\\n\", sock);\n\n\tif (sock->type != SOCK_STREAM &&\n\t sock->type != SOCK_DGRAM &&\n\t sock->type != SOCK_RAW)\n\t\treturn -ESOCKTNOSUPPORT;\n\n\tif (sock->type == SOCK_RAW)\n\t\tsock->ops = &llcp_rawsock_ops;\n\telse\n\t\tsock->ops = &llcp_sock_ops;\n\n\tsk = nfc_llcp_sock_alloc(sock, sock->type, GFP_ATOMIC, kern);\n\tif (sk == NULL)\n\t\treturn -ENOMEM;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-276'], 'message': 'nfc: enforce CAP_NET_RAW for raw sockets\n\nWhen creating a raw AF_NFC socket, CAP_NET_RAW needs to be checked\nfirst.\n\nSigned-off-by: Ori Nimron \nSigned-off-by: Greg Kroah-Hartman \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int hclge_tm_schd_mode_vnet_base_cfg(struct hclge_vport *vport)\n{\n\tstruct hnae3_knic_private_info *kinfo = &vport->nic.kinfo;\n\tstruct hclge_dev *hdev = vport->back;\n\tint ret;\n\tu8 i;\n\n\tret = hclge_tm_pri_schd_mode_cfg(hdev, vport->vport_id);\n\tif (ret)\n\t\treturn ret;\n\n\tfor (i = 0; i < kinfo->num_tc; i++) {\n\t\tu8 sch_mode = hdev->tm_info.tc_info[i].tc_sch_mode;\n\n\t\tret = hclge_tm_qs_schd_mode_cfg(hdev, vport->qs_offset + i,\n\t\t\t\t\t\tsch_mode);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'net: hns3: add some error checking in hclge_tm module\n\nWhen hdev->tx_sch_mode is HCLGE_FLAG_VNET_BASE_SCH_MODE, the\nhclge_tm_schd_mode_vnet_base_cfg calls hclge_tm_pri_schd_mode_cfg\nwith vport->vport_id as pri_id, which is used as index for\nhdev->tm_info.tc_info, it will cause out of bound access issue\nif vport_id is equal to or larger than HNAE3_MAX_TC.\n\nAlso hardware only support maximum speed of HCLGE_ETHER_MAX_RATE.\n\nSo this patch adds two checks for above cases.\n\nFixes: 848440544b41 (\"net: hns3: Add support of TX Scheduler & Shaper to HNS3 driver\")\nSigned-off-by: Yunsheng Lin \nSigned-off-by: Peng Li \nSigned-off-by: Huazhong Tan \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int restore_fp(struct task_struct *tsk) { return 0; } ; 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: rpl_dao_print(netdissect_options *ndo,\n const u_char *bp, u_int length)\n{\n const struct nd_rpl_dao *dao = (const struct nd_rpl_dao *)bp;\n const char *dagid_str = \"\";\n\n ND_TCHECK(*dao);\n if (length < ND_RPL_DAO_MIN_LEN)\n \tgoto tooshort;\n\n bp += ND_RPL_DAO_MIN_LEN;\n length -= ND_RPL_DAO_MIN_LEN;\n if(RPL_DAO_D(dao->rpl_flags)) {\n ND_TCHECK2(dao->rpl_dagid, DAGID_LEN);\n if (length < DAGID_LEN)\n \tgoto tooshort;\n dagid_str = ip6addr_string (ndo, dao->rpl_dagid);\n bp += DAGID_LEN;\n length -= DAGID_LEN;\n }\n\n ND_PRINT((ndo, \" [dagid:%s,seq:%u,instance:%u%s%s,%02x]\",\n dagid_str,\n dao->rpl_daoseq,\n dao->rpl_instanceid,\n RPL_DAO_K(dao->rpl_flags) ? \",acK\":\"\",\n RPL_DAO_D(dao->rpl_flags) ? \",Dagid\":\"\",\n dao->rpl_flags));\n\n if(ndo->ndo_vflag > 1) {\n const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp;\n rpl_dio_printopt(ndo, opt, length);\n }\n\treturn;\n\ntrunc:\n\tND_PRINT((ndo,\" [|truncated]\"));\n\treturn;\n\ntooshort:\n\tND_PRINT((ndo,\" [|length too short]\"));\n\treturn;\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: rsvp_obj_print(netdissect_options *ndo,\n const u_char *pptr, u_int plen, const u_char *tptr,\n const char *ident, u_int tlen,\n const struct rsvp_common_header *rsvp_com_header)\n{\n const struct rsvp_object_header *rsvp_obj_header;\n const u_char *obj_tptr;\n union {\n const struct rsvp_obj_integrity_t *rsvp_obj_integrity;\n const struct rsvp_obj_frr_t *rsvp_obj_frr;\n } obj_ptr;\n\n u_short rsvp_obj_len,rsvp_obj_ctype,obj_tlen,intserv_serv_tlen;\n int hexdump,processed,padbytes,error_code,error_value,i,sigcheck;\n union {\n\tfloat f;\n\tuint32_t i;\n } bw;\n uint8_t namelen;\n\n u_int action, subchannel;\n\n while(tlen>=sizeof(struct rsvp_object_header)) {\n /* did we capture enough for fully decoding the object header ? */\n ND_TCHECK2(*tptr, sizeof(struct rsvp_object_header));\n\n rsvp_obj_header = (const struct rsvp_object_header *)tptr;\n rsvp_obj_len=EXTRACT_16BITS(rsvp_obj_header->length);\n rsvp_obj_ctype=rsvp_obj_header->ctype;\n\n if(rsvp_obj_len % 4) {\n ND_PRINT((ndo, \"%sERROR: object header size %u not a multiple of 4\", ident, rsvp_obj_len));\n return -1;\n }\n if(rsvp_obj_len < sizeof(struct rsvp_object_header)) {\n ND_PRINT((ndo, \"%sERROR: object header too short %u < %lu\", ident, rsvp_obj_len,\n (unsigned long)sizeof(const struct rsvp_object_header)));\n return -1;\n }\n\n ND_PRINT((ndo, \"%s%s Object (%u) Flags: [%s\",\n ident,\n tok2str(rsvp_obj_values,\n \"Unknown\",\n rsvp_obj_header->class_num),\n rsvp_obj_header->class_num,\n ((rsvp_obj_header->class_num) & 0x80) ? \"ignore\" : \"reject\"));\n\n if (rsvp_obj_header->class_num > 128)\n ND_PRINT((ndo, \" %s\",\n ((rsvp_obj_header->class_num) & 0x40) ? \"and forward\" : \"silently\"));\n\n ND_PRINT((ndo, \" if unknown], Class-Type: %s (%u), length: %u\",\n tok2str(rsvp_ctype_values,\n \"Unknown\",\n ((rsvp_obj_header->class_num)<<8)+rsvp_obj_ctype),\n rsvp_obj_ctype,\n rsvp_obj_len));\n\n if(tlen < rsvp_obj_len) {\n ND_PRINT((ndo, \"%sERROR: object goes past end of objects TLV\", ident));\n return -1;\n }\n\n obj_tptr=tptr+sizeof(struct rsvp_object_header);\n obj_tlen=rsvp_obj_len-sizeof(struct rsvp_object_header);\n\n /* did we capture enough for fully decoding the object ? */\n if (!ND_TTEST2(*tptr, rsvp_obj_len))\n return -1;\n hexdump=FALSE;\n\n switch(rsvp_obj_header->class_num) {\n case RSVP_OBJ_SESSION:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_IPV4:\n if (obj_tlen < 8)\n return -1;\n ND_PRINT((ndo, \"%s IPv4 DestAddress: %s, Protocol ID: 0x%02x\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n *(obj_tptr + sizeof(struct in_addr))));\n ND_PRINT((ndo, \"%s Flags: [0x%02x], DestPort %u\",\n ident,\n *(obj_tptr+5),\n EXTRACT_16BITS(obj_tptr + 6)));\n obj_tlen-=8;\n obj_tptr+=8;\n break;\n case RSVP_CTYPE_IPV6:\n if (obj_tlen < 20)\n return -1;\n ND_PRINT((ndo, \"%s IPv6 DestAddress: %s, Protocol ID: 0x%02x\",\n ident,\n ip6addr_string(ndo, obj_tptr),\n *(obj_tptr + sizeof(struct in6_addr))));\n ND_PRINT((ndo, \"%s Flags: [0x%02x], DestPort %u\",\n ident,\n *(obj_tptr+sizeof(struct in6_addr)+1),\n EXTRACT_16BITS(obj_tptr + sizeof(struct in6_addr) + 2)));\n obj_tlen-=20;\n obj_tptr+=20;\n break;\n\n case RSVP_CTYPE_TUNNEL_IPV6:\n if (obj_tlen < 36)\n return -1;\n ND_PRINT((ndo, \"%s IPv6 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s\",\n ident,\n ip6addr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr+18),\n ip6addr_string(ndo, obj_tptr + 20)));\n obj_tlen-=36;\n obj_tptr+=36;\n break;\n\n case RSVP_CTYPE_14: /* IPv6 p2mp LSP Tunnel */\n if (obj_tlen < 26)\n return -1;\n ND_PRINT((ndo, \"%s IPv6 P2MP LSP ID: 0x%08x, Tunnel ID: 0x%04x, Extended Tunnel ID: %s\",\n ident,\n EXTRACT_32BITS(obj_tptr),\n EXTRACT_16BITS(obj_tptr+6),\n ip6addr_string(ndo, obj_tptr + 8)));\n obj_tlen-=26;\n obj_tptr+=26;\n break;\n case RSVP_CTYPE_13: /* IPv4 p2mp LSP Tunnel */\n if (obj_tlen < 12)\n return -1;\n ND_PRINT((ndo, \"%s IPv4 P2MP LSP ID: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr+6),\n ipaddr_string(ndo, obj_tptr + 8)));\n obj_tlen-=12;\n obj_tptr+=12;\n break;\n case RSVP_CTYPE_TUNNEL_IPV4:\n case RSVP_CTYPE_UNI_IPV4:\n if (obj_tlen < 12)\n return -1;\n ND_PRINT((ndo, \"%s IPv4 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr+6),\n ipaddr_string(ndo, obj_tptr + 8)));\n obj_tlen-=12;\n obj_tptr+=12;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_CONFIRM:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_IPV4:\n if (obj_tlen < sizeof(struct in_addr))\n return -1;\n ND_PRINT((ndo, \"%s IPv4 Receiver Address: %s\",\n ident,\n ipaddr_string(ndo, obj_tptr)));\n obj_tlen-=sizeof(struct in_addr);\n obj_tptr+=sizeof(struct in_addr);\n break;\n case RSVP_CTYPE_IPV6:\n if (obj_tlen < sizeof(struct in6_addr))\n return -1;\n ND_PRINT((ndo, \"%s IPv6 Receiver Address: %s\",\n ident,\n ip6addr_string(ndo, obj_tptr)));\n obj_tlen-=sizeof(struct in6_addr);\n obj_tptr+=sizeof(struct in6_addr);\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_NOTIFY_REQ:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_IPV4:\n if (obj_tlen < sizeof(struct in_addr))\n return -1;\n ND_PRINT((ndo, \"%s IPv4 Notify Node Address: %s\",\n ident,\n ipaddr_string(ndo, obj_tptr)));\n obj_tlen-=sizeof(struct in_addr);\n obj_tptr+=sizeof(struct in_addr);\n break;\n case RSVP_CTYPE_IPV6:\n if (obj_tlen < sizeof(struct in6_addr))\n return-1;\n ND_PRINT((ndo, \"%s IPv6 Notify Node Address: %s\",\n ident,\n ip6addr_string(ndo, obj_tptr)));\n obj_tlen-=sizeof(struct in6_addr);\n obj_tptr+=sizeof(struct in6_addr);\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_SUGGESTED_LABEL: /* fall through */\n case RSVP_OBJ_UPSTREAM_LABEL: /* fall through */\n case RSVP_OBJ_RECOVERY_LABEL: /* fall through */\n case RSVP_OBJ_LABEL:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1:\n while(obj_tlen >= 4 ) {\n ND_PRINT((ndo, \"%s Label: %u\", ident, EXTRACT_32BITS(obj_tptr)));\n obj_tlen-=4;\n obj_tptr+=4;\n }\n break;\n case RSVP_CTYPE_2:\n if (obj_tlen < 4)\n return-1;\n ND_PRINT((ndo, \"%s Generalized Label: %u\",\n ident,\n EXTRACT_32BITS(obj_tptr)));\n obj_tlen-=4;\n obj_tptr+=4;\n break;\n case RSVP_CTYPE_3:\n if (obj_tlen < 12)\n return-1;\n ND_PRINT((ndo, \"%s Waveband ID: %u%s Start Label: %u, Stop Label: %u\",\n ident,\n EXTRACT_32BITS(obj_tptr),\n ident,\n EXTRACT_32BITS(obj_tptr+4),\n EXTRACT_32BITS(obj_tptr + 8)));\n obj_tlen-=12;\n obj_tptr+=12;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_STYLE:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1:\n if (obj_tlen < 4)\n return-1;\n ND_PRINT((ndo, \"%s Reservation Style: %s, Flags: [0x%02x]\",\n ident,\n tok2str(rsvp_resstyle_values,\n \"Unknown\",\n EXTRACT_24BITS(obj_tptr+1)),\n *(obj_tptr)));\n obj_tlen-=4;\n obj_tptr+=4;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_SENDER_TEMPLATE:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_IPV4:\n if (obj_tlen < 8)\n return-1;\n ND_PRINT((ndo, \"%s Source Address: %s, Source Port: %u\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr + 6)));\n obj_tlen-=8;\n obj_tptr+=8;\n break;\n case RSVP_CTYPE_IPV6:\n if (obj_tlen < 20)\n return-1;\n ND_PRINT((ndo, \"%s Source Address: %s, Source Port: %u\",\n ident,\n ip6addr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr + 18)));\n obj_tlen-=20;\n obj_tptr+=20;\n break;\n case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */\n if (obj_tlen < 40)\n return-1;\n ND_PRINT((ndo, \"%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x\"\n \"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x\",\n ident,\n ip6addr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr+18),\n ident,\n ip6addr_string(ndo, obj_tptr+20),\n EXTRACT_16BITS(obj_tptr + 38)));\n obj_tlen-=40;\n obj_tptr+=40;\n break;\n case RSVP_CTYPE_TUNNEL_IPV4:\n if (obj_tlen < 8)\n return-1;\n ND_PRINT((ndo, \"%s IPv4 Tunnel Sender Address: %s, LSP-ID: 0x%04x\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr + 6)));\n obj_tlen-=8;\n obj_tptr+=8;\n break;\n case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */\n if (obj_tlen < 16)\n return-1;\n ND_PRINT((ndo, \"%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x\"\n \"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr+6),\n ident,\n ipaddr_string(ndo, obj_tptr+8),\n EXTRACT_16BITS(obj_tptr + 12)));\n obj_tlen-=16;\n obj_tptr+=16;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_LABEL_REQ:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1:\n while(obj_tlen >= 4 ) {\n ND_PRINT((ndo, \"%s L3 Protocol ID: %s\",\n ident,\n tok2str(ethertype_values,\n \"Unknown Protocol (0x%04x)\",\n EXTRACT_16BITS(obj_tptr + 2))));\n obj_tlen-=4;\n obj_tptr+=4;\n }\n break;\n case RSVP_CTYPE_2:\n if (obj_tlen < 12)\n return-1;\n ND_PRINT((ndo, \"%s L3 Protocol ID: %s\",\n ident,\n tok2str(ethertype_values,\n \"Unknown Protocol (0x%04x)\",\n EXTRACT_16BITS(obj_tptr + 2))));\n ND_PRINT((ndo, \",%s merge capability\",((*(obj_tptr + 4)) & 0x80) ? \"no\" : \"\" ));\n ND_PRINT((ndo, \"%s Minimum VPI/VCI: %u/%u\",\n ident,\n (EXTRACT_16BITS(obj_tptr+4))&0xfff,\n (EXTRACT_16BITS(obj_tptr + 6)) & 0xfff));\n ND_PRINT((ndo, \"%s Maximum VPI/VCI: %u/%u\",\n ident,\n (EXTRACT_16BITS(obj_tptr+8))&0xfff,\n (EXTRACT_16BITS(obj_tptr + 10)) & 0xfff));\n obj_tlen-=12;\n obj_tptr+=12;\n break;\n case RSVP_CTYPE_3:\n if (obj_tlen < 12)\n return-1;\n ND_PRINT((ndo, \"%s L3 Protocol ID: %s\",\n ident,\n tok2str(ethertype_values,\n \"Unknown Protocol (0x%04x)\",\n EXTRACT_16BITS(obj_tptr + 2))));\n ND_PRINT((ndo, \"%s Minimum/Maximum DLCI: %u/%u, %s%s bit DLCI\",\n ident,\n (EXTRACT_32BITS(obj_tptr+4))&0x7fffff,\n (EXTRACT_32BITS(obj_tptr+8))&0x7fffff,\n (((EXTRACT_16BITS(obj_tptr+4)>>7)&3) == 0 ) ? \"10\" : \"\",\n (((EXTRACT_16BITS(obj_tptr + 4) >> 7) & 3) == 2 ) ? \"23\" : \"\"));\n obj_tlen-=12;\n obj_tptr+=12;\n break;\n case RSVP_CTYPE_4:\n if (obj_tlen < 4)\n return-1;\n ND_PRINT((ndo, \"%s LSP Encoding Type: %s (%u)\",\n ident,\n tok2str(gmpls_encoding_values,\n \"Unknown\",\n *obj_tptr),\n\t\t *obj_tptr));\n ND_PRINT((ndo, \"%s Switching Type: %s (%u), Payload ID: %s (0x%04x)\",\n ident,\n tok2str(gmpls_switch_cap_values,\n \"Unknown\",\n *(obj_tptr+1)),\n\t\t *(obj_tptr+1),\n tok2str(gmpls_payload_values,\n \"Unknown\",\n EXTRACT_16BITS(obj_tptr+2)),\n\t\t EXTRACT_16BITS(obj_tptr + 2)));\n obj_tlen-=4;\n obj_tptr+=4;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_RRO:\n case RSVP_OBJ_ERO:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_IPV4:\n while(obj_tlen >= 4 ) {\n\t\t u_char length;\n\n\t\t ND_TCHECK2(*obj_tptr, 4);\n\t\t length = *(obj_tptr + 1);\n ND_PRINT((ndo, \"%s Subobject Type: %s, length %u\",\n ident,\n tok2str(rsvp_obj_xro_values,\n \"Unknown %u\",\n RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)),\n length));\n\n if (length == 0) { /* prevent infinite loops */\n ND_PRINT((ndo, \"%s ERROR: zero length ERO subtype\", ident));\n break;\n }\n\n switch(RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)) {\n\t\t u_char prefix_length;\n\n case RSVP_OBJ_XRO_IPV4:\n\t\t\tif (length != 8) {\n\t\t\t\tND_PRINT((ndo, \" ERROR: length != 8\"));\n\t\t\t\tgoto invalid;\n\t\t\t}\n\t\t\tND_TCHECK2(*obj_tptr, 8);\n\t\t\tprefix_length = *(obj_tptr+6);\n\t\t\tif (prefix_length != 32) {\n\t\t\t\tND_PRINT((ndo, \" ERROR: Prefix length %u != 32\",\n\t\t\t\t\t prefix_length));\n\t\t\t\tgoto invalid;\n\t\t\t}\n ND_PRINT((ndo, \", %s, %s/%u, Flags: [%s]\",\n RSVP_OBJ_XRO_MASK_LOOSE(*obj_tptr) ? \"Loose\" : \"Strict\",\n ipaddr_string(ndo, obj_tptr+2),\n *(obj_tptr+6),\n bittok2str(rsvp_obj_rro_flag_values,\n \"none\",\n *(obj_tptr + 7)))); /* rfc3209 says that this field is rsvd. */\n break;\n case RSVP_OBJ_XRO_LABEL:\n\t\t\tif (length != 8) {\n\t\t\t\tND_PRINT((ndo, \" ERROR: length != 8\"));\n\t\t\t\tgoto invalid;\n\t\t\t}\n\t\t\tND_TCHECK2(*obj_tptr, 8);\n ND_PRINT((ndo, \", Flags: [%s] (%#x), Class-Type: %s (%u), %u\",\n bittok2str(rsvp_obj_rro_label_flag_values,\n \"none\",\n *(obj_tptr+2)),\n *(obj_tptr+2),\n tok2str(rsvp_ctype_values,\n \"Unknown\",\n *(obj_tptr+3) + 256*RSVP_OBJ_RRO),\n *(obj_tptr+3),\n EXTRACT_32BITS(obj_tptr + 4)));\n }\n obj_tlen-=*(obj_tptr+1);\n obj_tptr+=*(obj_tptr+1);\n }\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_HELLO:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1:\n case RSVP_CTYPE_2:\n if (obj_tlen < 8)\n return-1;\n ND_PRINT((ndo, \"%s Source Instance: 0x%08x, Destination Instance: 0x%08x\",\n ident,\n EXTRACT_32BITS(obj_tptr),\n EXTRACT_32BITS(obj_tptr + 4)));\n obj_tlen-=8;\n obj_tptr+=8;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_RESTART_CAPABILITY:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1:\n if (obj_tlen < 8)\n return-1;\n ND_PRINT((ndo, \"%s Restart Time: %ums, Recovery Time: %ums\",\n ident,\n EXTRACT_32BITS(obj_tptr),\n EXTRACT_32BITS(obj_tptr + 4)));\n obj_tlen-=8;\n obj_tptr+=8;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_SESSION_ATTRIBUTE:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_TUNNEL_IPV4:\n if (obj_tlen < 4)\n return-1;\n namelen = *(obj_tptr+3);\n if (obj_tlen < 4+namelen)\n return-1;\n ND_PRINT((ndo, \"%s Session Name: \", ident));\n for (i = 0; i < namelen; i++)\n safeputchar(ndo, *(obj_tptr + 4 + i));\n ND_PRINT((ndo, \"%s Setup Priority: %u, Holding Priority: %u, Flags: [%s] (%#x)\",\n ident,\n (int)*obj_tptr,\n (int)*(obj_tptr+1),\n bittok2str(rsvp_session_attribute_flag_values,\n \"none\",\n *(obj_tptr+2)),\n *(obj_tptr + 2)));\n obj_tlen-=4+*(obj_tptr+3);\n obj_tptr+=4+*(obj_tptr+3);\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n\tcase RSVP_OBJ_GENERALIZED_UNI:\n switch(rsvp_obj_ctype) {\n\t\tint subobj_type,af,subobj_len,total_subobj_len;\n\n case RSVP_CTYPE_1:\n\n if (obj_tlen < 4)\n return-1;\n\n\t\t/* read variable length subobjects */\n\t\ttotal_subobj_len = obj_tlen;\n while(total_subobj_len > 0) {\n /* If RFC 3476 Section 3.1 defined that a sub-object of the\n * GENERALIZED_UNI RSVP object must have the Length field as\n * a multiple of 4, instead of the check below it would be\n * better to test total_subobj_len only once before the loop.\n * So long as it does not define it and this while loop does\n * not implement such a requirement, let's accept that within\n * each iteration subobj_len may happen to be a multiple of 1\n * and test it and total_subobj_len respectively.\n */\n if (total_subobj_len < 4)\n goto invalid;\n subobj_len = EXTRACT_16BITS(obj_tptr);\n subobj_type = (EXTRACT_16BITS(obj_tptr+2))>>8;\n af = (EXTRACT_16BITS(obj_tptr+2))&0x00FF;\n\n ND_PRINT((ndo, \"%s Subobject Type: %s (%u), AF: %s (%u), length: %u\",\n ident,\n tok2str(rsvp_obj_generalized_uni_values, \"Unknown\", subobj_type),\n subobj_type,\n tok2str(af_values, \"Unknown\", af), af,\n subobj_len));\n\n /* In addition to what is explained above, the same spec does not\n * explicitly say that the same Length field includes the 4-octet\n * sub-object header, but as long as this while loop implements it\n * as it does include, let's keep the check below consistent with\n * the rest of the code.\n */\n if(subobj_len < 4 || subobj_len > total_subobj_len)\n goto invalid;\n\n switch(subobj_type) {\n case RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS:\n case RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS:\n\n switch(af) {\n case AFNUM_INET:\n if (subobj_len < 8)\n return -1;\n ND_PRINT((ndo, \"%s UNI IPv4 TNA address: %s\",\n ident, ipaddr_string(ndo, obj_tptr + 4)));\n break;\n case AFNUM_INET6:\n if (subobj_len < 20)\n return -1;\n ND_PRINT((ndo, \"%s UNI IPv6 TNA address: %s\",\n ident, ip6addr_string(ndo, obj_tptr + 4)));\n break;\n case AFNUM_NSAP:\n if (subobj_len) {\n /* unless we have a TLV parser lets just hexdump */\n hexdump=TRUE;\n }\n break;\n }\n break;\n\n case RSVP_GEN_UNI_SUBOBJ_DIVERSITY:\n if (subobj_len) {\n /* unless we have a TLV parser lets just hexdump */\n hexdump=TRUE;\n }\n break;\n\n case RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL:\n if (subobj_len < 16) {\n return -1;\n }\n\n ND_PRINT((ndo, \"%s U-bit: %x, Label type: %u, Logical port id: %u, Label: %u\",\n ident,\n ((EXTRACT_32BITS(obj_tptr+4))>>31),\n ((EXTRACT_32BITS(obj_tptr+4))&0xFF),\n EXTRACT_32BITS(obj_tptr+8),\n EXTRACT_32BITS(obj_tptr + 12)));\n break;\n\n case RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL:\n if (subobj_len < 8) {\n return -1;\n }\n\n ND_PRINT((ndo, \"%s Service level: %u\",\n ident, (EXTRACT_32BITS(obj_tptr + 4)) >> 24));\n break;\n\n default:\n hexdump=TRUE;\n break;\n }\n total_subobj_len-=subobj_len;\n obj_tptr+=subobj_len;\n obj_tlen+=subobj_len;\n\t\t}\n\n if (total_subobj_len) {\n /* unless we have a TLV parser lets just hexdump */\n hexdump=TRUE;\n }\n break;\n\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_RSVP_HOP:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */\n case RSVP_CTYPE_IPV4:\n if (obj_tlen < 8)\n return-1;\n ND_PRINT((ndo, \"%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n EXTRACT_32BITS(obj_tptr + 4)));\n obj_tlen-=8;\n obj_tptr+=8;\n if (obj_tlen)\n hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */\n break;\n case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */\n case RSVP_CTYPE_IPV6:\n if (obj_tlen < 20)\n return-1;\n ND_PRINT((ndo, \"%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x\",\n ident,\n ip6addr_string(ndo, obj_tptr),\n EXTRACT_32BITS(obj_tptr + 16)));\n obj_tlen-=20;\n obj_tptr+=20;\n hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_TIME_VALUES:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1:\n if (obj_tlen < 4)\n return-1;\n ND_PRINT((ndo, \"%s Refresh Period: %ums\",\n ident,\n EXTRACT_32BITS(obj_tptr)));\n obj_tlen-=4;\n obj_tptr+=4;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n /* those three objects do share the same semantics */\n case RSVP_OBJ_SENDER_TSPEC:\n case RSVP_OBJ_ADSPEC:\n case RSVP_OBJ_FLOWSPEC:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_2:\n if (obj_tlen < 4)\n return-1;\n ND_PRINT((ndo, \"%s Msg-Version: %u, length: %u\",\n ident,\n (*obj_tptr & 0xf0) >> 4,\n EXTRACT_16BITS(obj_tptr + 2) << 2));\n obj_tptr+=4; /* get to the start of the service header */\n obj_tlen-=4;\n\n while (obj_tlen >= 4) {\n intserv_serv_tlen=EXTRACT_16BITS(obj_tptr+2)<<2;\n ND_PRINT((ndo, \"%s Service Type: %s (%u), break bit %s set, Service length: %u\",\n ident,\n tok2str(rsvp_intserv_service_type_values,\"unknown\",*(obj_tptr)),\n *(obj_tptr),\n (*(obj_tptr+1)&0x80) ? \"\" : \"not\",\n intserv_serv_tlen));\n\n obj_tptr+=4; /* get to the start of the parameter list */\n obj_tlen-=4;\n\n while (intserv_serv_tlen>=4) {\n processed = rsvp_intserv_print(ndo, obj_tptr, obj_tlen);\n if (processed == 0)\n break;\n obj_tlen-=processed;\n intserv_serv_tlen-=processed;\n obj_tptr+=processed;\n }\n }\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_FILTERSPEC:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_IPV4:\n if (obj_tlen < 8)\n return-1;\n ND_PRINT((ndo, \"%s Source Address: %s, Source Port: %u\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr + 6)));\n obj_tlen-=8;\n obj_tptr+=8;\n break;\n case RSVP_CTYPE_IPV6:\n if (obj_tlen < 20)\n return-1;\n ND_PRINT((ndo, \"%s Source Address: %s, Source Port: %u\",\n ident,\n ip6addr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr + 18)));\n obj_tlen-=20;\n obj_tptr+=20;\n break;\n case RSVP_CTYPE_3:\n if (obj_tlen < 20)\n return-1;\n ND_PRINT((ndo, \"%s Source Address: %s, Flow Label: %u\",\n ident,\n ip6addr_string(ndo, obj_tptr),\n EXTRACT_24BITS(obj_tptr + 17)));\n obj_tlen-=20;\n obj_tptr+=20;\n break;\n case RSVP_CTYPE_TUNNEL_IPV6:\n if (obj_tlen < 20)\n return-1;\n ND_PRINT((ndo, \"%s Source Address: %s, LSP-ID: 0x%04x\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr + 18)));\n obj_tlen-=20;\n obj_tptr+=20;\n break;\n case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */\n if (obj_tlen < 40)\n return-1;\n ND_PRINT((ndo, \"%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x\"\n \"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x\",\n ident,\n ip6addr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr+18),\n ident,\n ip6addr_string(ndo, obj_tptr+20),\n EXTRACT_16BITS(obj_tptr + 38)));\n obj_tlen-=40;\n obj_tptr+=40;\n break;\n case RSVP_CTYPE_TUNNEL_IPV4:\n if (obj_tlen < 8)\n return-1;\n ND_PRINT((ndo, \"%s Source Address: %s, LSP-ID: 0x%04x\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr + 6)));\n obj_tlen-=8;\n obj_tptr+=8;\n break;\n case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */\n if (obj_tlen < 16)\n return-1;\n ND_PRINT((ndo, \"%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x\"\n \"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr+6),\n ident,\n ipaddr_string(ndo, obj_tptr+8),\n EXTRACT_16BITS(obj_tptr + 12)));\n obj_tlen-=16;\n obj_tptr+=16;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_FASTREROUTE:\n /* the differences between c-type 1 and 7 are minor */\n obj_ptr.rsvp_obj_frr = (const struct rsvp_obj_frr_t *)obj_tptr;\n\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1: /* new style */\n if (obj_tlen < sizeof(struct rsvp_obj_frr_t))\n return-1;\n bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);\n ND_PRINT((ndo, \"%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps\",\n ident,\n (int)obj_ptr.rsvp_obj_frr->setup_prio,\n (int)obj_ptr.rsvp_obj_frr->hold_prio,\n (int)obj_ptr.rsvp_obj_frr->hop_limit,\n bw.f * 8 / 1000000));\n ND_PRINT((ndo, \"%s Include-any: 0x%08x, Exclude-any: 0x%08x, Include-all: 0x%08x\",\n ident,\n EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any),\n EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any),\n EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_all)));\n obj_tlen-=sizeof(struct rsvp_obj_frr_t);\n obj_tptr+=sizeof(struct rsvp_obj_frr_t);\n break;\n\n case RSVP_CTYPE_TUNNEL_IPV4: /* old style */\n if (obj_tlen < 16)\n return-1;\n bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);\n ND_PRINT((ndo, \"%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps\",\n ident,\n (int)obj_ptr.rsvp_obj_frr->setup_prio,\n (int)obj_ptr.rsvp_obj_frr->hold_prio,\n (int)obj_ptr.rsvp_obj_frr->hop_limit,\n bw.f * 8 / 1000000));\n ND_PRINT((ndo, \"%s Include Colors: 0x%08x, Exclude Colors: 0x%08x\",\n ident,\n EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any),\n EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any)));\n obj_tlen-=16;\n obj_tptr+=16;\n break;\n\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_DETOUR:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_TUNNEL_IPV4:\n while(obj_tlen >= 8) {\n ND_PRINT((ndo, \"%s PLR-ID: %s, Avoid-Node-ID: %s\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n ipaddr_string(ndo, obj_tptr + 4)));\n obj_tlen-=8;\n obj_tptr+=8;\n }\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_CLASSTYPE:\n case RSVP_OBJ_CLASSTYPE_OLD: /* fall through */\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1:\n ND_PRINT((ndo, \"%s CT: %u\",\n ident,\n EXTRACT_32BITS(obj_tptr) & 0x7));\n obj_tlen-=4;\n obj_tptr+=4;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_ERROR_SPEC:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */\n case RSVP_CTYPE_IPV4:\n if (obj_tlen < 8)\n return-1;\n error_code=*(obj_tptr+5);\n error_value=EXTRACT_16BITS(obj_tptr+6);\n ND_PRINT((ndo, \"%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n *(obj_tptr+4),\n ident,\n tok2str(rsvp_obj_error_code_values,\"unknown\",error_code),\n error_code));\n switch (error_code) {\n case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING:\n ND_PRINT((ndo, \", Error Value: %s (%u)\",\n tok2str(rsvp_obj_error_code_routing_values,\"unknown\",error_value),\n error_value));\n break;\n case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE: /* fall through */\n case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD:\n ND_PRINT((ndo, \", Error Value: %s (%u)\",\n tok2str(rsvp_obj_error_code_diffserv_te_values,\"unknown\",error_value),\n error_value));\n break;\n default:\n ND_PRINT((ndo, \", Unknown Error Value (%u)\", error_value));\n break;\n }\n obj_tlen-=8;\n obj_tptr+=8;\n break;\n case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */\n case RSVP_CTYPE_IPV6:\n if (obj_tlen < 20)\n return-1;\n error_code=*(obj_tptr+17);\n error_value=EXTRACT_16BITS(obj_tptr+18);\n ND_PRINT((ndo, \"%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)\",\n ident,\n ip6addr_string(ndo, obj_tptr),\n *(obj_tptr+16),\n ident,\n tok2str(rsvp_obj_error_code_values,\"unknown\",error_code),\n error_code));\n\n switch (error_code) {\n case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING:\n ND_PRINT((ndo, \", Error Value: %s (%u)\",\n tok2str(rsvp_obj_error_code_routing_values,\"unknown\",error_value),\n\t\t\t error_value));\n break;\n default:\n break;\n }\n obj_tlen-=20;\n obj_tptr+=20;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_PROPERTIES:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1:\n if (obj_tlen < 4)\n return-1;\n padbytes = EXTRACT_16BITS(obj_tptr+2);\n ND_PRINT((ndo, \"%s TLV count: %u, padding bytes: %u\",\n ident,\n EXTRACT_16BITS(obj_tptr),\n padbytes));\n obj_tlen-=4;\n obj_tptr+=4;\n /* loop through as long there is anything longer than the TLV header (2) */\n while(obj_tlen >= 2 + padbytes) {\n ND_PRINT((ndo, \"%s %s TLV (0x%02x), length: %u\", /* length includes header */\n ident,\n tok2str(rsvp_obj_prop_tlv_values,\"unknown\",*obj_tptr),\n *obj_tptr,\n *(obj_tptr + 1)));\n if (obj_tlen < *(obj_tptr+1))\n return-1;\n if (*(obj_tptr+1) < 2)\n return -1;\n print_unknown_data(ndo, obj_tptr + 2, \"\\n\\t\\t\", *(obj_tptr + 1) - 2);\n obj_tlen-=*(obj_tptr+1);\n obj_tptr+=*(obj_tptr+1);\n }\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_MESSAGE_ID: /* fall through */\n case RSVP_OBJ_MESSAGE_ID_ACK: /* fall through */\n case RSVP_OBJ_MESSAGE_ID_LIST:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1:\n case RSVP_CTYPE_2:\n if (obj_tlen < 8)\n return-1;\n ND_PRINT((ndo, \"%s Flags [0x%02x], epoch: %u\",\n ident,\n *obj_tptr,\n EXTRACT_24BITS(obj_tptr + 1)));\n obj_tlen-=4;\n obj_tptr+=4;\n /* loop through as long there are no messages left */\n while(obj_tlen >= 4) {\n ND_PRINT((ndo, \"%s Message-ID 0x%08x (%u)\",\n ident,\n EXTRACT_32BITS(obj_tptr),\n EXTRACT_32BITS(obj_tptr)));\n obj_tlen-=4;\n obj_tptr+=4;\n }\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_INTEGRITY:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1:\n if (obj_tlen < sizeof(struct rsvp_obj_integrity_t))\n return-1;\n obj_ptr.rsvp_obj_integrity = (const struct rsvp_obj_integrity_t *)obj_tptr;\n ND_PRINT((ndo, \"%s Key-ID 0x%04x%08x, Sequence 0x%08x%08x, Flags [%s]\",\n ident,\n EXTRACT_16BITS(obj_ptr.rsvp_obj_integrity->key_id),\n EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->key_id+2),\n EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence),\n EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence+4),\n bittok2str(rsvp_obj_integrity_flag_values,\n \"none\",\n obj_ptr.rsvp_obj_integrity->flags)));\n ND_PRINT((ndo, \"%s MD5-sum 0x%08x%08x%08x%08x \",\n ident,\n EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest),\n EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+4),\n EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+8),\n EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest + 12)));\n\n sigcheck = signature_verify(ndo, pptr, plen,\n obj_ptr.rsvp_obj_integrity->digest,\n rsvp_clear_checksum,\n rsvp_com_header);\n ND_PRINT((ndo, \" (%s)\", tok2str(signature_check_values, \"Unknown\", sigcheck)));\n\n obj_tlen+=sizeof(struct rsvp_obj_integrity_t);\n obj_tptr+=sizeof(struct rsvp_obj_integrity_t);\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_ADMIN_STATUS:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1:\n if (obj_tlen < 4)\n return-1;\n ND_PRINT((ndo, \"%s Flags [%s]\", ident,\n bittok2str(rsvp_obj_admin_status_flag_values, \"none\",\n EXTRACT_32BITS(obj_tptr))));\n obj_tlen-=4;\n obj_tptr+=4;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_LABEL_SET:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1:\n if (obj_tlen < 4)\n return-1;\n action = (EXTRACT_16BITS(obj_tptr)>>8);\n\n ND_PRINT((ndo, \"%s Action: %s (%u), Label type: %u\", ident,\n tok2str(rsvp_obj_label_set_action_values, \"Unknown\", action),\n action, ((EXTRACT_32BITS(obj_tptr) & 0x7F))));\n\n switch (action) {\n case LABEL_SET_INCLUSIVE_RANGE:\n case LABEL_SET_EXCLUSIVE_RANGE: /* fall through */\n\n\t\t /* only a couple of subchannels are expected */\n\t\t if (obj_tlen < 12)\n\t\t\treturn -1;\n\t\t ND_PRINT((ndo, \"%s Start range: %u, End range: %u\", ident,\n EXTRACT_32BITS(obj_tptr+4),\n EXTRACT_32BITS(obj_tptr + 8)));\n\t\t obj_tlen-=12;\n\t\t obj_tptr+=12;\n break;\n\n default:\n obj_tlen-=4;\n obj_tptr+=4;\n subchannel = 1;\n while(obj_tlen >= 4 ) {\n ND_PRINT((ndo, \"%s Subchannel #%u: %u\", ident, subchannel,\n EXTRACT_32BITS(obj_tptr)));\n obj_tptr+=4;\n obj_tlen-=4;\n subchannel++;\n }\n break;\n }\n break;\n default:\n hexdump=TRUE;\n }\n\n case RSVP_OBJ_S2L:\n switch (rsvp_obj_ctype) {\n case RSVP_CTYPE_IPV4:\n if (obj_tlen < 4)\n return-1;\n ND_PRINT((ndo, \"%s Sub-LSP destination address: %s\",\n ident, ipaddr_string(ndo, obj_tptr)));\n\n obj_tlen-=4;\n obj_tptr+=4;\n break;\n case RSVP_CTYPE_IPV6:\n if (obj_tlen < 16)\n return-1;\n ND_PRINT((ndo, \"%s Sub-LSP destination address: %s\",\n ident, ip6addr_string(ndo, obj_tptr)));\n\n obj_tlen-=16;\n obj_tptr+=16;\n break;\n default:\n hexdump=TRUE;\n }\n\n /*\n * FIXME those are the defined objects that lack a decoder\n * you are welcome to contribute code ;-)\n */\n\n case RSVP_OBJ_SCOPE:\n case RSVP_OBJ_POLICY_DATA:\n case RSVP_OBJ_ACCEPT_LABEL_SET:\n case RSVP_OBJ_PROTECTION:\n default:\n if (ndo->ndo_vflag <= 1)\n print_unknown_data(ndo, obj_tptr, \"\\n\\t \", obj_tlen); /* FIXME indentation */\n break;\n }\n /* do we also want to see a hex dump ? */\n if (ndo->ndo_vflag > 1 || hexdump == TRUE)\n print_unknown_data(ndo, tptr + sizeof(struct rsvp_object_header), \"\\n\\t \", /* FIXME indentation */\n rsvp_obj_len - sizeof(struct rsvp_object_header));\n\n tptr+=rsvp_obj_len;\n tlen-=rsvp_obj_len;\n }\n return 0;\ninvalid:\n ND_PRINT((ndo, \"%s\", istr));\n return -1;\ntrunc:\n ND_PRINT((ndo, \"\\n\\t\\t\"));\n ND_PRINT((ndo, \"%s\", tstr));\n return -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-14465/RSVP: Add a missing bounds check\n\nIn rsvp_obj_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: ldp_tlv_print(netdissect_options *ndo,\n register const u_char *tptr,\n u_short msg_tlen)\n{\n struct ldp_tlv_header {\n uint8_t type[2];\n uint8_t length[2];\n };\n\n const struct ldp_tlv_header *ldp_tlv_header;\n u_short tlv_type,tlv_len,tlv_tlen,af,ft_flags;\n u_char fec_type;\n u_int ui,vc_info_len, vc_info_tlv_type, vc_info_tlv_len,idx;\n char buf[100];\n int i;\n\n ldp_tlv_header = (const struct ldp_tlv_header *)tptr;\n ND_TCHECK(*ldp_tlv_header);\n tlv_len=EXTRACT_16BITS(ldp_tlv_header->length);\n if (tlv_len + 4 > msg_tlen) {\n ND_PRINT((ndo, \"\\n\\t\\t TLV contents go past end of message\"));\n return 0;\n }\n tlv_tlen=tlv_len;\n tlv_type=LDP_MASK_TLV_TYPE(EXTRACT_16BITS(ldp_tlv_header->type));\n\n /* FIXME vendor private / experimental check */\n ND_PRINT((ndo, \"\\n\\t %s TLV (0x%04x), length: %u, Flags: [%s and %s forward if unknown]\",\n tok2str(ldp_tlv_values,\n \"Unknown\",\n tlv_type),\n tlv_type,\n tlv_len,\n LDP_MASK_U_BIT(EXTRACT_16BITS(&ldp_tlv_header->type)) ? \"continue processing\" : \"ignore\",\n LDP_MASK_F_BIT(EXTRACT_16BITS(&ldp_tlv_header->type)) ? \"do\" : \"don't\"));\n\n tptr+=sizeof(struct ldp_tlv_header);\n\n switch(tlv_type) {\n\n case LDP_TLV_COMMON_HELLO:\n TLV_TCHECK(4);\n ND_PRINT((ndo, \"\\n\\t Hold Time: %us, Flags: [%s Hello%s]\",\n EXTRACT_16BITS(tptr),\n (EXTRACT_16BITS(tptr+2)&0x8000) ? \"Targeted\" : \"Link\",\n (EXTRACT_16BITS(tptr+2)&0x4000) ? \", Request for targeted Hellos\" : \"\"));\n break;\n\n case LDP_TLV_IPV4_TRANSPORT_ADDR:\n TLV_TCHECK(4);\n ND_PRINT((ndo, \"\\n\\t IPv4 Transport Address: %s\", ipaddr_string(ndo, tptr)));\n break;\n case LDP_TLV_IPV6_TRANSPORT_ADDR:\n TLV_TCHECK(16);\n ND_PRINT((ndo, \"\\n\\t IPv6 Transport Address: %s\", ip6addr_string(ndo, tptr)));\n break;\n case LDP_TLV_CONFIG_SEQ_NUMBER:\n TLV_TCHECK(4);\n ND_PRINT((ndo, \"\\n\\t Sequence Number: %u\", EXTRACT_32BITS(tptr)));\n break;\n\n case LDP_TLV_ADDRESS_LIST:\n TLV_TCHECK(LDP_TLV_ADDRESS_LIST_AFNUM_LEN);\n\taf = EXTRACT_16BITS(tptr);\n\ttptr+=LDP_TLV_ADDRESS_LIST_AFNUM_LEN;\n tlv_tlen -= LDP_TLV_ADDRESS_LIST_AFNUM_LEN;\n\tND_PRINT((ndo, \"\\n\\t Address Family: %s, addresses\",\n tok2str(af_values, \"Unknown (%u)\", af)));\n switch (af) {\n case AFNUM_INET:\n\t while(tlv_tlen >= sizeof(struct in_addr)) {\n\t\tND_TCHECK2(*tptr, sizeof(struct in_addr));\n\t\tND_PRINT((ndo, \" %s\", ipaddr_string(ndo, tptr)));\n\t\ttlv_tlen-=sizeof(struct in_addr);\n\t\ttptr+=sizeof(struct in_addr);\n\t }\n break;\n case AFNUM_INET6:\n\t while(tlv_tlen >= sizeof(struct in6_addr)) {\n\t\tND_TCHECK2(*tptr, sizeof(struct in6_addr));\n\t\tND_PRINT((ndo, \" %s\", ip6addr_string(ndo, tptr)));\n\t\ttlv_tlen-=sizeof(struct in6_addr);\n\t\ttptr+=sizeof(struct in6_addr);\n\t }\n break;\n default:\n /* unknown AF */\n break;\n }\n\tbreak;\n\n case LDP_TLV_COMMON_SESSION:\n\tTLV_TCHECK(8);\n\tND_PRINT((ndo, \"\\n\\t Version: %u, Keepalive: %us, Flags: [Downstream %s, Loop Detection %s]\",\n\t EXTRACT_16BITS(tptr), EXTRACT_16BITS(tptr+2),\n\t (EXTRACT_16BITS(tptr+6)&0x8000) ? \"On Demand\" : \"Unsolicited\",\n\t (EXTRACT_16BITS(tptr+6)&0x4000) ? \"Enabled\" : \"Disabled\"\n\t ));\n\tbreak;\n\n case LDP_TLV_FEC:\n TLV_TCHECK(1);\n fec_type = *tptr;\n\tND_PRINT((ndo, \"\\n\\t %s FEC (0x%02x)\",\n\t tok2str(ldp_fec_values, \"Unknown\", fec_type),\n\t fec_type));\n\n\ttptr+=1;\n\ttlv_tlen-=1;\n\tswitch(fec_type) {\n\n\tcase LDP_FEC_WILDCARD:\n\t break;\n\tcase LDP_FEC_PREFIX:\n\t TLV_TCHECK(2);\n\t af = EXTRACT_16BITS(tptr);\n\t tptr+=LDP_TLV_ADDRESS_LIST_AFNUM_LEN;\n\t tlv_tlen-=LDP_TLV_ADDRESS_LIST_AFNUM_LEN;\n\t if (af == AFNUM_INET) {\n\t\ti=decode_prefix4(ndo, tptr, tlv_tlen, buf, sizeof(buf));\n\t\tif (i == -2)\n\t\t goto trunc;\n\t\tif (i == -3)\n\t\t ND_PRINT((ndo, \": IPv4 prefix (goes past end of TLV)\"));\n\t\telse if (i == -1)\n\t\t ND_PRINT((ndo, \": IPv4 prefix (invalid length)\"));\n\t\telse\n\t\t ND_PRINT((ndo, \": IPv4 prefix %s\", buf));\n\t }\n\t else if (af == AFNUM_INET6) {\n\t\ti=decode_prefix6(ndo, tptr, tlv_tlen, buf, sizeof(buf));\n\t\tif (i == -2)\n\t\t goto trunc;\n\t\tif (i == -3)\n\t\t ND_PRINT((ndo, \": IPv4 prefix (goes past end of TLV)\"));\n\t\telse if (i == -1)\n\t\t ND_PRINT((ndo, \": IPv6 prefix (invalid length)\"));\n\t\telse\n\t\t ND_PRINT((ndo, \": IPv6 prefix %s\", buf));\n\t }\n\t else\n\t\tND_PRINT((ndo, \": Address family %u prefix\", af));\n\t break;\n\tcase LDP_FEC_HOSTADDRESS:\n\t break;\n\tcase LDP_FEC_MARTINI_VC:\n /*\n * We assume the type was supposed to be one of the MPLS\n * Pseudowire Types.\n */\n TLV_TCHECK(7);\n vc_info_len = *(tptr+2);\n\n /*\n\t * According to RFC 4908, the VC info Length field can be zero,\n\t * in which case not only are there no interface parameters,\n\t * there's no VC ID.\n\t */\n if (vc_info_len == 0) {\n ND_PRINT((ndo, \": %s, %scontrol word, group-ID %u, VC-info-length: %u\",\n tok2str(mpls_pw_types_values, \"Unknown\", EXTRACT_16BITS(tptr)&0x7fff),\n EXTRACT_16BITS(tptr)&0x8000 ? \"\" : \"no \",\n EXTRACT_32BITS(tptr+3),\n vc_info_len));\n break;\n }\n\n /* Make sure we have the VC ID as well */\n TLV_TCHECK(11);\n\t ND_PRINT((ndo, \": %s, %scontrol word, group-ID %u, VC-ID %u, VC-info-length: %u\",\n\t\t tok2str(mpls_pw_types_values, \"Unknown\", EXTRACT_16BITS(tptr)&0x7fff),\n\t\t EXTRACT_16BITS(tptr)&0x8000 ? \"\" : \"no \",\n EXTRACT_32BITS(tptr+3),\n\t\t EXTRACT_32BITS(tptr+7),\n vc_info_len));\n if (vc_info_len < 4) {\n /* minimum 4, for the VC ID */\n ND_PRINT((ndo, \" (invalid, < 4\"));\n return(tlv_len+4); /* Type & Length fields not included */\n\t }\n vc_info_len -= 4; /* subtract out the VC ID, giving the length of the interface parameters */\n\n /* Skip past the fixed information and the VC ID */\n tptr+=11;\n tlv_tlen-=11;\n TLV_TCHECK(vc_info_len);\n\n while (vc_info_len > 2) {\n vc_info_tlv_type = *tptr;\n vc_info_tlv_len = *(tptr+1);\n if (vc_info_tlv_len < 2)\n break;\n if (vc_info_len < vc_info_tlv_len)\n break;\n\n ND_PRINT((ndo, \"\\n\\t\\tInterface Parameter: %s (0x%02x), len %u\",\n tok2str(ldp_fec_martini_ifparm_values,\"Unknown\",vc_info_tlv_type),\n vc_info_tlv_type,\n vc_info_tlv_len));\n\n switch(vc_info_tlv_type) {\n case LDP_FEC_MARTINI_IFPARM_MTU:\n ND_PRINT((ndo, \": %u\", EXTRACT_16BITS(tptr+2)));\n break;\n\n case LDP_FEC_MARTINI_IFPARM_DESC:\n ND_PRINT((ndo, \": \"));\n for (idx = 2; idx < vc_info_tlv_len; idx++)\n safeputchar(ndo, *(tptr + idx));\n break;\n\n case LDP_FEC_MARTINI_IFPARM_VCCV:\n ND_PRINT((ndo, \"\\n\\t\\t Control Channels (0x%02x) = [%s]\",\n *(tptr+2),\n bittok2str(ldp_fec_martini_ifparm_vccv_cc_values, \"none\", *(tptr+2))));\n ND_PRINT((ndo, \"\\n\\t\\t CV Types (0x%02x) = [%s]\",\n *(tptr+3),\n bittok2str(ldp_fec_martini_ifparm_vccv_cv_values, \"none\", *(tptr+3))));\n break;\n\n default:\n print_unknown_data(ndo, tptr+2, \"\\n\\t\\t \", vc_info_tlv_len-2);\n break;\n }\n\n vc_info_len -= vc_info_tlv_len;\n tptr += vc_info_tlv_len;\n }\n\t break;\n\t}\n\n\tbreak;\n\n case LDP_TLV_GENERIC_LABEL:\n\tTLV_TCHECK(4);\n\tND_PRINT((ndo, \"\\n\\t Label: %u\", EXTRACT_32BITS(tptr) & 0xfffff));\n\tbreak;\n\n case LDP_TLV_STATUS:\n\tTLV_TCHECK(8);\n\tui = EXTRACT_32BITS(tptr);\n\ttptr+=4;\n\tND_PRINT((ndo, \"\\n\\t Status: 0x%02x, Flags: [%s and %s forward]\",\n\t ui&0x3fffffff,\n\t ui&0x80000000 ? \"Fatal error\" : \"Advisory Notification\",\n\t ui&0x40000000 ? \"do\" : \"don't\"));\n\tui = EXTRACT_32BITS(tptr);\n\ttptr+=4;\n\tif (ui)\n\t ND_PRINT((ndo, \", causing Message ID: 0x%08x\", ui));\n\tbreak;\n\n case LDP_TLV_FT_SESSION:\n\tTLV_TCHECK(8);\n\tft_flags = EXTRACT_16BITS(tptr);\n\tND_PRINT((ndo, \"\\n\\t Flags: [%sReconnect, %sSave State, %sAll-Label Protection, %s Checkpoint, %sRe-Learn State]\",\n\t ft_flags&0x8000 ? \"\" : \"No \",\n\t ft_flags&0x8 ? \"\" : \"Don't \",\n\t ft_flags&0x4 ? \"\" : \"No \",\n\t ft_flags&0x2 ? \"Sequence Numbered Label\" : \"All Labels\",\n\t ft_flags&0x1 ? \"\" : \"Don't \"));\n\ttptr+=4;\n\tui = EXTRACT_32BITS(tptr);\n\tif (ui)\n\t ND_PRINT((ndo, \", Reconnect Timeout: %ums\", ui));\n\ttptr+=4;\n\tui = EXTRACT_32BITS(tptr);\n\tif (ui)\n\t ND_PRINT((ndo, \", Recovery Time: %ums\", ui));\n\tbreak;\n\n case LDP_TLV_MTU:\n\tTLV_TCHECK(2);\n\tND_PRINT((ndo, \"\\n\\t MTU: %u\", EXTRACT_16BITS(tptr)));\n\tbreak;\n\n\n /*\n * FIXME those are the defined TLVs that lack a decoder\n * you are welcome to contribute code ;-)\n */\n\n case LDP_TLV_HOP_COUNT:\n case LDP_TLV_PATH_VECTOR:\n case LDP_TLV_ATM_LABEL:\n case LDP_TLV_FR_LABEL:\n case LDP_TLV_EXTD_STATUS:\n case LDP_TLV_RETURNED_PDU:\n case LDP_TLV_RETURNED_MSG:\n case LDP_TLV_ATM_SESSION_PARM:\n case LDP_TLV_FR_SESSION_PARM:\n case LDP_TLV_LABEL_REQUEST_MSG_ID:\n\n default:\n if (ndo->ndo_vflag <= 1)\n print_unknown_data(ndo, tptr, \"\\n\\t \", tlv_tlen);\n break;\n }\n return(tlv_len+4); /* Type & Length fields not included */\n\ntrunc:\n ND_PRINT((ndo, \"\\n\\t\\t packet exceeded snapshot\"));\n return 0;\n\nbadtlv:\n ND_PRINT((ndo, \"\\n\\t\\t TLV contents go past end of TLV\"));\n return(tlv_len+4); /* Type & Length fields not included */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-14461/LDP: Fix a bounds check\n\nIn ldp_tlv_print(), the FT Session TLV length must be 12, not 8 (RFC3479)\n\nThis fixes a buffer over-read discovered by Konrad Rieck and\nBhargava Shastry.\n\nAdd a test using the capture file supplied by the reporter(s).\n\nMoreover:\nAdd and use tstr[].\nAdd a comment.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: smb_fdata(netdissect_options *ndo,\n const u_char *buf, const char *fmt, const u_char *maxbuf,\n int unicodestr)\n{\n static int depth = 0;\n char s[128];\n char *p;\n\n while (*fmt) {\n\tswitch (*fmt) {\n\tcase '*':\n\t fmt++;\n\t while (buf < maxbuf) {\n\t\tconst u_char *buf2;\n\t\tdepth++;\n\t\tbuf2 = smb_fdata(ndo, buf, fmt, maxbuf, unicodestr);\n\t\tdepth--;\n\t\tif (buf2 == NULL)\n\t\t return(NULL);\n\t\tif (buf2 == buf)\n\t\t return(buf);\n\t\tbuf = buf2;\n\t }\n\t return(buf);\n\n\tcase '|':\n\t fmt++;\n\t if (buf >= maxbuf)\n\t\treturn(buf);\n\t break;\n\n\tcase '%':\n\t fmt++;\n\t buf = maxbuf;\n\t break;\n\n\tcase '#':\n\t fmt++;\n\t return(buf);\n\t break;\n\n\tcase '[':\n\t fmt++;\n\t if (buf >= maxbuf)\n\t\treturn(buf);\n\t memset(s, 0, sizeof(s));\n\t p = strchr(fmt, ']');\n\t if ((size_t)(p - fmt + 1) > sizeof(s)) {\n\t\t/* overrun */\n\t\treturn(buf);\n\t }\n\t strncpy(s, fmt, p - fmt);\n\t s[p - fmt] = '\\0';\n\t fmt = p + 1;\n\t buf = smb_fdata1(ndo, buf, s, maxbuf, unicodestr);\n\t if (buf == NULL)\n\t\treturn(NULL);\n\t break;\n\n\tdefault:\n\t ND_PRINT((ndo, \"%c\", *fmt));\n\t fmt++;\n\t break;\n\t}\n }\n if (!depth && buf < maxbuf) {\n\tsize_t len = PTR_DIFF(maxbuf, buf);\n\tND_PRINT((ndo, \"Data: (%lu bytes)\\n\", (unsigned long)len));\n\tsmb_print_data(ndo, buf, len);\n\treturn(buf + len);\n }\n return(buf);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-674', 'CWE-787'], 'message': '(for 4.9.3) CVE-2018-16452/SMB: prevent stack exhaustion\n\nEnforce a limit on how many times smb_fdata() can recurse.\n\nThis fixes a stack exhaustion discovered by Include Security working\nunder the Mozilla SOS program in 2018 by means of code audit.'" }, { "text": "[INST] Given the following code containing errors, provide Common 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\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\tif (strcmp(user_password, (char *) crypt(password, user_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-476'], 'message': 'Don't crash if crypt() fails.\n\nIt can fail, so make sure it doesn't before comparing its result with\nthe password.\n\nThis addresses Include Security issue F12: [libpcap] Remote Packet\nCapture Daemon Null Pointer Dereference 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 int __init pf_init(void)\n{\t\t\t\t/* preliminary initialisation */\n\tstruct pf_unit *pf;\n\tint unit;\n\n\tif (disable)\n\t\treturn -EINVAL;\n\n\tpf_init_units();\n\n\tif (pf_detect())\n\t\treturn -ENODEV;\n\tpf_busy = 0;\n\n\tif (register_blkdev(major, name)) {\n\t\tfor (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++)\n\t\t\tput_disk(pf->disk);\n\t\treturn -EBUSY;\n\t}\n\n\tfor (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++) {\n\t\tstruct gendisk *disk = pf->disk;\n\n\t\tif (!pf->present)\n\t\t\tcontinue;\n\t\tdisk->private_data = pf;\n\t\tadd_disk(disk);\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': '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: sign (gcry_mpi_t r, gcry_mpi_t s, gcry_mpi_t input, DSA_secret_key *skey,\n int flags, int hashalgo)\n{\n gpg_err_code_t rc;\n gcry_mpi_t hash;\n gcry_mpi_t k;\n gcry_mpi_t kinv;\n gcry_mpi_t tmp;\n const void *abuf;\n unsigned int abits, qbits;\n int extraloops = 0;\n\n qbits = mpi_get_nbits (skey->q);\n\n /* Convert the INPUT into an MPI. */\n rc = _gcry_dsa_normalize_hash (input, &hash, qbits);\n if (rc)\n return rc;\n\n again:\n /* Create the K value. */\n if ((flags & PUBKEY_FLAG_RFC6979) && hashalgo)\n {\n /* Use Pornin's method for deterministic DSA. If this flag is\n set, it is expected that HASH is an opaque MPI with the to be\n signed hash. That hash is also 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->q, skey->x,\n abuf, (abits+7)/8, hashalgo, extraloops);\n if (rc)\n goto leave;\n }\n else\n {\n /* Select a random k with 0 < k < q */\n k = _gcry_dsa_gen_k (skey->q, GCRY_STRONG_RANDOM);\n }\n\n /* r = (a^k mod p) mod q */\n mpi_powm( r, skey->g, k, skey->p );\n mpi_fdiv_r( r, r, skey->q );\n\n /* kinv = k^(-1) mod q */\n kinv = mpi_alloc( mpi_get_nlimbs(k) );\n mpi_invm(kinv, k, skey->q );\n\n /* s = (kinv * ( hash + x * r)) mod q */\n tmp = mpi_alloc( mpi_get_nlimbs(skey->p) );\n mpi_mul( tmp, skey->x, r );\n mpi_add( tmp, tmp, hash );\n mpi_mulm( s , kinv, tmp, skey->q );\n\n mpi_free(k);\n mpi_free(kinv);\n mpi_free(tmp);\n\n if (!mpi_cmp_ui (r, 0))\n {\n /* This is a highly unlikely code path. */\n extraloops++;\n goto again;\n }\n\n rc = 0;\n\n leave:\n if (hash != input)\n mpi_free (hash);\n\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-203'], 'message': 'dsa,ecdsa: Fix use of nonce, use larger one.\n\n* cipher/dsa-common.c (_gcry_dsa_modify_k): New.\n* cipher/pubkey-internal.h (_gcry_dsa_modify_k): New.\n* cipher/dsa.c (sign): Use _gcry_dsa_modify_k.\n* cipher/ecc-ecdsa.c (_gcry_ecc_ecdsa_sign): Likewise.\n* cipher/ecc-gost.c (_gcry_ecc_gost_sign): Likewise.\n\nCVE-id: CVE-2019-13627\nGnuPG-bug-id: 4626\nSigned-off-by: NIIBE Yutaka '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: idn2_strerror (int rc)\n{\n bindtextdomain (PACKAGE, LOCALEDIR);\n\n switch (rc)\n {\n case IDN2_OK: return _(\"success\");\n case IDN2_MALLOC: return _(\"out of memory\");\n case IDN2_NO_CODESET: return _(\"could not determine locale encoding format\");\n case IDN2_ICONV_FAIL: return _(\"could not convert string to UTF-8\");\n case IDN2_ENCODING_ERROR: return _(\"string encoding error\");\n case IDN2_NFC: return _(\"string could not be NFC normalized\");\n case IDN2_PUNYCODE_BAD_INPUT: return _(\"string contains invalid punycode data\");\n case IDN2_PUNYCODE_BIG_OUTPUT: return _(\"punycode encoded data will be too large\");\n case IDN2_PUNYCODE_OVERFLOW: return _(\"punycode conversion resulted in overflow\");\n case IDN2_TOO_BIG_DOMAIN: return _(\"domain name longer than 255 characters\");\n case IDN2_TOO_BIG_LABEL: return _(\"domain label longer than 63 characters\");\n case IDN2_INVALID_ALABEL: return _(\"input A-label is not valid\");\n case IDN2_UALABEL_MISMATCH: return _(\"input A-label and U-label does not match\");\n case IDN2_NOT_NFC: return _(\"string is not in Unicode NFC format\");\n case IDN2_2HYPHEN: return _(\"string contains forbidden two hyphens pattern\");\n case IDN2_HYPHEN_STARTEND: return _(\"string start/ends with forbidden hyphen\");\n case IDN2_LEADING_COMBINING: return _(\"string contains a forbidden leading combining character\");\n case IDN2_DISALLOWED: return _(\"string contains a disallowed character\");\n case IDN2_CONTEXTJ: return _(\"string contains a forbidden context-j character\");\n case IDN2_CONTEXTJ_NO_RULE: return _(\"string contains a context-j character with null rule\");\n case IDN2_CONTEXTO: return _(\"string contains a forbidden context-o character\");\n case IDN2_CONTEXTO_NO_RULE: return _(\"string contains a context-o character with null rule\");\n case IDN2_UNASSIGNED: return _(\"string contains unassigned code point\");\n case IDN2_BIDI: return _(\"string has forbidden bi-directional properties\");\n case IDN2_DOT_IN_LABEL: return _(\"domain label has forbidden dot (TR46)\");\n case IDN2_INVALID_TRANSITIONAL: return _(\"domain label has character forbidden in transitional mode (TR46)\");\n case IDN2_INVALID_NONTRANSITIONAL: return _(\"domain label has character forbidden in non-transitional mode (TR46)\");\n default: return _(\"Unknown error\");\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Perform A-Label roundtrip for lookup functions by default\n\nThis adds another check to avoid unexpected results.\nIt was a longstanding FIXME.\n\nThanks to Jonathan Birch of Microsoft Corporation,\nFlorian Weimer (GNU glibc) and Nikos Mavrogiannopoulos (GnuTLS)\nfor investigation, discussion and testing.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int vrend_renderer_resource_create(struct vrend_renderer_resource_create_args *args, struct iovec *iov, uint32_t num_iovs, void *image_oes)\n{\n struct vrend_resource *gr;\n int ret;\n\n ret = check_resource_valid(args);\n if (ret)\n return EINVAL;\n\n gr = (struct vrend_resource *)CALLOC_STRUCT(vrend_texture);\n if (!gr)\n return ENOMEM;\n\n vrend_renderer_resource_copy_args(args, gr);\n gr->iov = iov;\n gr->num_iovs = num_iovs;\n\n if (args->flags & VIRGL_RESOURCE_Y_0_TOP)\n gr->y_0_top = true;\n\n pipe_reference_init(&gr->base.reference, 1);\n\n if (args->bind == VIRGL_BIND_CUSTOM) {\n assert(args->target == PIPE_BUFFER);\n /* use iovec directly when attached */\n gr->storage = VREND_RESOURCE_STORAGE_GUEST_ELSE_SYSTEM;\n gr->ptr = malloc(args->width);\n if (!gr->ptr) {\n FREE(gr);\n return ENOMEM;\n }\n } else if (args->bind == VIRGL_BIND_STAGING) {\n /* Staging buffers use only guest memory. */\n gr->storage = VREND_RESOURCE_STORAGE_GUEST;\n } else if (args->bind == VIRGL_BIND_INDEX_BUFFER) {\n gr->target = GL_ELEMENT_ARRAY_BUFFER_ARB;\n vrend_create_buffer(gr, args->width);\n } else if (args->bind == VIRGL_BIND_STREAM_OUTPUT) {\n gr->target = GL_TRANSFORM_FEEDBACK_BUFFER;\n vrend_create_buffer(gr, args->width);\n } else if (args->bind == VIRGL_BIND_VERTEX_BUFFER) {\n gr->target = GL_ARRAY_BUFFER_ARB;\n vrend_create_buffer(gr, args->width);\n } else if (args->bind == VIRGL_BIND_CONSTANT_BUFFER) {\n gr->target = GL_UNIFORM_BUFFER;\n vrend_create_buffer(gr, args->width);\n } else if (args->bind == VIRGL_BIND_QUERY_BUFFER) {\n gr->target = GL_QUERY_BUFFER;\n vrend_create_buffer(gr, args->width);\n } else if (args->bind == VIRGL_BIND_COMMAND_ARGS) {\n gr->target = GL_DRAW_INDIRECT_BUFFER;\n vrend_create_buffer(gr, args->width);\n } else if (args->target == PIPE_BUFFER && (args->bind == 0 || args->bind == VIRGL_BIND_SHADER_BUFFER)) {\n gr->target = GL_ARRAY_BUFFER_ARB;\n vrend_create_buffer(gr, args->width);\n } else if (args->target == PIPE_BUFFER && (args->bind & VIRGL_BIND_SAMPLER_VIEW)) {\n /*\n * On Desktop we use GL_ARB_texture_buffer_object on GLES we use\n * GL_EXT_texture_buffer (it is in the ANDRIOD extension pack).\n */\n#if GL_TEXTURE_BUFFER != GL_TEXTURE_BUFFER_EXT\n#error \"GL_TEXTURE_BUFFER enums differ, they shouldn't.\"\n#endif\n\n /* need to check GL version here */\n if (has_feature(feat_arb_or_gles_ext_texture_buffer)) {\n gr->target = GL_TEXTURE_BUFFER;\n } else {\n gr->target = GL_PIXEL_PACK_BUFFER_ARB;\n }\n vrend_create_buffer(gr, args->width);\n } else {\n int r = vrend_renderer_resource_allocate_texture(gr, image_oes);\n if (r)\n return r;\n }\n\n ret = vrend_resource_insert(gr, args->handle);\n if (ret == 0) {\n vrend_renderer_resource_destroy(gr);\n return ENOMEM;\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: unsigned find_file(const StringList & sl, String & filename)\n {\n StringListEnumeration els = sl.elements_obj();\n const char * dir;\n String path;\n while ( (dir = els.next()) != 0 ) \n {\n path = dir;\n if (path.back() != '/') path += '/';\n unsigned dir_len = path.size();\n path += filename;\n if (file_exists(path)) {\n filename.swap(path);\n return dir_len;\n }\n }\n return 0;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix various bugs found by OSS-Fuze.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static boolean ReadIPTCProfile(j_decompress_ptr jpeg_info)\n{\n char\n magick[MagickPathExtent];\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 *iptc_profile,\n *profile;\n\n /*\n Determine length of binary data stored here.\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 /*\n Validate that this was written as a Photoshop resource format slug.\n */\n for (i=0; i < 10; i++)\n magick[i]=(char) GetCharacter(jpeg_info);\n magick[10]='\\0';\n length-=10;\n if (length <= 10)\n return(TRUE);\n if (LocaleCompare(magick,\"Photoshop \") != 0)\n {\n /*\n Not a IPTC profile, return.\n */\n for (i=0; i < (ssize_t) length; i++)\n if (GetCharacter(jpeg_info) == EOF)\n break;\n return(TRUE);\n }\n /*\n Remove the version number.\n */\n for (i=0; i < 4; i++)\n if (GetCharacter(jpeg_info) == EOF)\n break;\n if (length <= 11)\n return(TRUE);\n length-=4;\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 error_manager->profile=NULL;\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 /* The IPTC profile is actually an 8bim */\n iptc_profile=(StringInfo *) GetImageProfile(image,\"8bim\");\n if (iptc_profile != (StringInfo *) NULL)\n {\n ConcatenateStringInfo(iptc_profile,profile);\n profile=DestroyStringInfo(profile);\n }\n else\n {\n status=SetImageProfile(image,\"8bim\",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: iptc, %.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: ModuleExport size_t RegisterXWDImage(void)\n{\n MagickInfo\n *entry;\n\n entry=SetMagickInfo(\"XWD\");\n#if defined(MAGICKCORE_X11_DELEGATE)\n entry->decoder=(DecodeImageHandler *) ReadXWDImage;\n entry->encoder=(EncodeImageHandler *) WriteXWDImage;\n#endif\n entry->magick=(IsImageFormatHandler *) IsXWD;\n entry->adjoin=MagickFalse;\n entry->description=ConstantString(\"X Windows system window dump (color)\");\n entry->module=ConstantString(\"XWD\");\n (void) RegisterMagickInfo(entry);\n return(MagickImageCoderSignature);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1553'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int qtree_scan_dquots(struct quota_handle *h,\n\t\t int (*process_dquot) (struct dquot *, void *),\n\t\t void *data)\n{\n\tchar *bitmap;\n\tstruct v2_mem_dqinfo *v2info = &h->qh_info.u.v2_mdqi;\n\tstruct qtree_mem_dqinfo *info = &v2info->dqi_qtree;\n\tstruct dquot *dquot = get_empty_dquot();\n\n\tif (!dquot)\n\t\treturn -1;\n\n\tdquot->dq_h = h;\n\tif (ext2fs_get_memzero((info->dqi_blocks + 7) >> 3, &bitmap)) {\n\t\text2fs_free_mem(&dquot);\n\t\treturn -1;\n\t}\n\tv2info->dqi_used_entries = report_tree(dquot, QT_TREEOFF, 0, bitmap,\n\t\t\t\t\t process_dquot, data);\n\tv2info->dqi_data_blocks = find_set_bits(bitmap, info->dqi_blocks);\n\text2fs_free_mem(&bitmap);\n\text2fs_free_mem(&dquot);\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: onig_compile(regex_t* reg, const UChar* pattern, const UChar* pattern_end,\n OnigErrorInfo* einfo)\n{\n#define COMPILE_INIT_SIZE 20\n\n int r, init_size;\n Node* root;\n ScanEnv scan_env;\n#ifdef USE_CALL\n UnsetAddrList uslist;\n#endif\n\n root = 0;\n if (IS_NOT_NULL(einfo)) einfo->par = (UChar* )NULL;\n\n#ifdef ONIG_DEBUG\n print_enc_string(stderr, reg->enc, pattern, pattern_end);\n#endif\n\n if (reg->alloc == 0) {\n init_size = (int )(pattern_end - pattern) * 2;\n if (init_size <= 0) init_size = COMPILE_INIT_SIZE;\n r = BB_INIT(reg, init_size);\n if (r != 0) goto end;\n }\n else\n reg->used = 0;\n\n reg->num_mem = 0;\n reg->num_repeat = 0;\n reg->num_null_check = 0;\n reg->repeat_range_alloc = 0;\n reg->repeat_range = (OnigRepeatRange* )NULL;\n\n r = onig_parse_tree(&root, pattern, pattern_end, reg, &scan_env);\n if (r != 0) goto err;\n\n /* mixed use named group and no-named group */\n if (scan_env.num_named > 0 &&\n IS_SYNTAX_BV(scan_env.syntax, ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP) &&\n ! ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_CAPTURE_GROUP)) {\n if (scan_env.num_named != scan_env.num_mem)\n r = disable_noname_group_capture(&root, reg, &scan_env);\n else\n r = numbered_ref_check(root);\n\n if (r != 0) goto err;\n }\n\n r = check_backrefs(root, &scan_env);\n if (r != 0) goto err;\n\n#ifdef USE_CALL\n if (scan_env.num_call > 0) {\n r = unset_addr_list_init(&uslist, scan_env.num_call);\n if (r != 0) goto err;\n scan_env.unset_addr_list = &uslist;\n r = setup_call(root, &scan_env, 0);\n if (r != 0) goto err_unset;\n r = setup_call2(root);\n if (r != 0) goto err_unset;\n r = recursive_call_check_trav(root, &scan_env, 0);\n if (r < 0) goto err_unset;\n r = infinite_recursive_call_check_trav(root, &scan_env);\n if (r != 0) goto err_unset;\n\n setup_called_state(root, 0);\n }\n\n reg->num_call = scan_env.num_call;\n#endif\n\n r = setup_tree(root, reg, 0, &scan_env);\n if (r != 0) goto err_unset;\n\n#ifdef ONIG_DEBUG_PARSE\n print_tree(stderr, root);\n#endif\n\n reg->capture_history = scan_env.capture_history;\n reg->bt_mem_start = scan_env.bt_mem_start;\n reg->bt_mem_start |= reg->capture_history;\n if (IS_FIND_CONDITION(reg->options))\n MEM_STATUS_ON_ALL(reg->bt_mem_end);\n else {\n reg->bt_mem_end = scan_env.bt_mem_end;\n reg->bt_mem_end |= reg->capture_history;\n }\n reg->bt_mem_start |= reg->bt_mem_end;\n\n clear_optimize_info(reg);\n#ifndef ONIG_DONT_OPTIMIZE\n r = set_optimize_info_from_tree(root, reg, &scan_env);\n if (r != 0) goto err_unset;\n#endif\n\n if (IS_NOT_NULL(scan_env.mem_env_dynamic)) {\n xfree(scan_env.mem_env_dynamic);\n scan_env.mem_env_dynamic = (MemEnv* )NULL;\n }\n\n r = compile_tree(root, reg, &scan_env);\n if (r == 0) {\n if (scan_env.keep_num > 0) {\n r = add_opcode(reg, OP_UPDATE_VAR);\n if (r != 0) goto err;\n r = add_update_var_type(reg, UPDATE_VAR_KEEP_FROM_STACK_LAST);\n if (r != 0) goto err;\n r = add_mem_num(reg, 0 /* not used */);\n if (r != 0) goto err;\n }\n\n r = add_opcode(reg, OP_END);\n#ifdef USE_CALL\n if (scan_env.num_call > 0) {\n r = fix_unset_addr_list(&uslist, reg);\n unset_addr_list_end(&uslist);\n if (r != 0) goto err;\n }\n#endif\n\n if ((reg->num_repeat != 0) || (reg->bt_mem_end != 0)\n#ifdef USE_CALLOUT\n || (IS_NOT_NULL(REG_EXTP(reg)) && REG_EXTP(reg)->callout_num != 0)\n#endif\n )\n reg->stack_pop_level = STACK_POP_LEVEL_ALL;\n else {\n if (reg->bt_mem_start != 0)\n reg->stack_pop_level = STACK_POP_LEVEL_MEM_START;\n else\n reg->stack_pop_level = STACK_POP_LEVEL_FREE;\n }\n }\n#ifdef USE_CALL\n else if (scan_env.num_call > 0) {\n unset_addr_list_end(&uslist);\n }\n#endif\n onig_node_free(root);\n\n#ifdef ONIG_DEBUG_COMPILE\n onig_print_names(stderr, reg);\n onig_print_compiled_byte_code_list(stderr, reg);\n#endif\n\n end:\n return r;\n\n err_unset:\n#ifdef USE_CALL\n if (scan_env.num_call > 0) {\n unset_addr_list_end(&uslist);\n }\n#endif\n err:\n if (IS_NOT_NULL(scan_env.error)) {\n if (IS_NOT_NULL(einfo)) {\n einfo->enc = scan_env.enc;\n einfo->par = scan_env.error;\n einfo->par_end = scan_env.error_end;\n }\n }\n\n onig_node_free(root);\n if (IS_NOT_NULL(scan_env.mem_env_dynamic))\n xfree(scan_env.mem_env_dynamic);\n return r;\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, ListenerFilterReportError) {\n InSequence s;\n\n TestListener* test_listener = addListener(1, true, false, \"test_listener\");\n Network::MockListener* listener = new Network::MockListener();\n Network::ListenerCallbacks* listener_callbacks;\n EXPECT_CALL(dispatcher_, createListener_(_, _, _))\n .WillOnce(\n Invoke([&](Network::Socket&, Network::ListenerCallbacks& cb, bool) -> Network::Listener* {\n listener_callbacks = &cb;\n return listener;\n }));\n EXPECT_CALL(test_listener->socket_, localAddress());\n handler_->addListener(*test_listener);\n\n Network::MockListenerFilter* first_filter = new Network::MockListenerFilter();\n Network::MockListenerFilter* last_filter = new Network::MockListenerFilter();\n\n EXPECT_CALL(factory_, createListenerFilterChain(_))\n .WillRepeatedly(Invoke([&](Network::ListenerFilterManager& manager) -> bool {\n manager.addAcceptFilter(Network::ListenerFilterPtr{first_filter});\n manager.addAcceptFilter(Network::ListenerFilterPtr{last_filter});\n return true;\n }));\n // The first filter close the socket\n EXPECT_CALL(*first_filter, onAccept(_))\n .WillOnce(Invoke([&](Network::ListenerFilterCallbacks& cb) -> Network::FilterStatus {\n cb.socket().close();\n return Network::FilterStatus::StopIteration;\n }));\n // The last filter won't be invoked\n EXPECT_CALL(*last_filter, onAccept(_)).Times(0);\n Network::MockConnectionSocket* accepted_socket = new NiceMock();\n listener_callbacks->onAccept(Network::ConnectionSocketPtr{accepted_socket});\n\n dispatcher_.clearDeferredDeleteList();\n // Make sure the error leads to no listener timer created.\n EXPECT_CALL(dispatcher_, createTimer_(_)).Times(0);\n // Make sure we never try to match the filer chain since listener filter doesn't complete.\n EXPECT_CALL(manager_, findFilterChain(_)).Times(0);\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 *__filterQuotedShell(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 '\\r':\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 unsigned long tjPlaneSizeYUV(int componentID, int width, int stride,\n int height, int subsamp)\n{\n unsigned long retval = 0;\n int pw, ph;\n\n if (width < 1 || height < 1 || subsamp < 0 || subsamp >= NUMSUBOPT)\n THROWG(\"tjPlaneSizeYUV(): Invalid argument\");\n\n pw = tjPlaneWidth(componentID, width, subsamp);\n ph = tjPlaneHeight(componentID, height, subsamp);\n if (pw < 0 || ph < 0) return -1;\n\n if (stride == 0) stride = pw;\n else stride = abs(stride);\n\n retval = stride * (ph - 1) + pw;\n\nbailout:\n return retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'TurboJPEG: Properly handle gigapixel images\n\nPrevent several integer overflow issues and subsequent segfaults that\noccurred when attempting to compress or decompress gigapixel images with\nthe TurboJPEG API:\n\n- Modify tjBufSize(), tjBufSizeYUV2(), and tjPlaneSizeYUV() to avoid\n integer overflow when computing the return values and to return an\n error if such an overflow is unavoidable.\n- Modify tjunittest to validate the above.\n- Modify tjCompress2(), tjEncodeYUVPlanes(), tjDecompress2(), and\n tjDecodeYUVPlanes() to avoid integer overflow when computing the row\n pointers in the 64-bit TurboJPEG C API.\n- Modify TJBench (both C and Java versions) to avoid overflowing the\n size argument to malloc()/new and to fail gracefully if such an\n overflow is unavoidable.\n\nIn general, this allows gigapixel images to be accommodated by the\n64-bit TurboJPEG C API when using automatic JPEG buffer (re)allocation.\nSuch images cannot currently be accommodated without automatic JPEG\nbuffer (re)allocation, due to the fact that tjAlloc() accepts a 32-bit\ninteger argument (oops.) Such images cannot be accommodated in the\nTurboJPEG Java API due to the fact that Java always uses a signed 32-bit\ninteger as an array index.\n\nFixes #361'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: soup_auth_ntlm_update_connection (SoupConnectionAuth *auth, SoupMessage *msg,\n\t\t\t\t const char *auth_header, gpointer state)\n{\n\tSoupAuthNTLM *auth_ntlm = SOUP_AUTH_NTLM (auth);\n\tSoupAuthNTLMPrivate *priv = soup_auth_ntlm_get_instance_private (auth_ntlm);\n\tSoupNTLMConnectionState *conn = state;\n\tgboolean success = TRUE;\n\n\t/* Note that we only return FALSE if some sort of parsing error\n\t * occurs. Otherwise, the SoupAuth is still reusable (though it may\n\t * no longer be _ready or _authenticated).\n\t */\n\n\tif (!g_str_has_prefix (auth_header, \"NTLM\"))\n\t\treturn FALSE;\n\n\tif (conn->state > SOUP_NTLM_SENT_REQUEST) {\n\t\tif (priv->password_state == SOUP_NTLM_PASSWORD_ACCEPTED) {\n\t\t\t/* We know our password is correct, so a 401\n\t\t\t * means \"permission denied\". The code can't deal\n\t\t\t * with re-authenticating correctly, so make sure\n\t\t\t * we don't try.\n\t\t\t */\n\t\t\tconn->state = SOUP_NTLM_FAILED;\n\t\t\tif (soup_message_is_keepalive (msg)) {\n\t\t\t\tsoup_message_headers_append (msg->response_headers,\n\t\t\t\t\t\t\t \"Connection\", \"close\");\n\t\t\t}\n\t\t\treturn TRUE;\n\t\t}\n\n#ifdef USE_NTLM_AUTH\n\t\tif (priv->sso_available) {\n\t\t\tconn->state = SOUP_NTLM_SSO_FAILED;\n\t\t\tpriv->password_state = SOUP_NTLM_PASSWORD_NONE;\n\t\t} else {\n#endif\n\t\t\tconn->state = SOUP_NTLM_FAILED;\n\t\t\tpriv->password_state = SOUP_NTLM_PASSWORD_REJECTED;\n#ifdef USE_NTLM_AUTH\n\t\t}\n#endif\n\t\treturn TRUE;\n\t}\n\n\tif (conn->state == SOUP_NTLM_NEW && !auth_header[4])\n\t\treturn TRUE;\n\n\tif (!auth_header[4] || !auth_header[5]) {\n\t\tconn->state = SOUP_NTLM_FAILED;\n\t\treturn FALSE;\n\t}\n\n\tif (!soup_ntlm_parse_challenge (auth_header + 5, &conn->nonce,\n\t\t\t\t\tpriv->domain ? NULL : &priv->domain,\n\t\t\t\t\t&conn->ntlmv2_session)) {\n\t\tconn->state = SOUP_NTLM_FAILED;\n\t\treturn FALSE;\n\t}\n\n#ifdef USE_NTLM_AUTH\n\tif (priv->sso_available && conn->state == SOUP_NTLM_SENT_REQUEST) {\n\t\tchar *input, *response;\n\n\t\t/* Re-Initiate ntlm_auth process in case it was closed/killed abnormally */\n\t\tif (!sso_ntlm_initiate (priv)) {\n\t\t\tconn->state = SOUP_NTLM_SSO_FAILED;\n\t\t\tsuccess = FALSE;\n\t\t\tgoto out;\n\t\t}\n\n\t\tinput = g_strdup_printf (\"TT %s\\n\", auth_header + 5);\n\t\tresponse = sso_ntlm_response (priv, input, conn->state);\n\t\tsso_ntlm_close (priv);\n\t\tg_free (input);\n\n\t\tif (!response) {\n\t\t\tconn->state = SOUP_NTLM_SSO_FAILED;\n\t\t\tsuccess = FALSE;\n\t\t} else if (!g_ascii_strcasecmp (response, \"PW\")) {\n\t\t\tconn->state = SOUP_NTLM_SSO_FAILED;\n\t\t\tpriv->sso_available = FALSE;\n\t\t\tg_free (response);\n\t\t} else {\n\t\t\tconn->response_header = response;\n\t\t\tif (priv->password_state != SOUP_NTLM_PASSWORD_ACCEPTED)\n\t\t\t\tpriv->password_state = SOUP_NTLM_PASSWORD_PROVIDED;\n\t\t}\n\t}\n out:\n#endif\n\n\tif (conn->state == SOUP_NTLM_SENT_REQUEST)\n\t\tconn->state = SOUP_NTLM_RECEIVED_CHALLENGE;\n\n\tg_object_set (G_OBJECT (auth),\n\t\t SOUP_AUTH_REALM, priv->domain,\n\t\t SOUP_AUTH_HOST, soup_message_get_uri (msg)->host,\n\t\t NULL);\n\treturn success;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'NTLMv2 responses support'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: psutil_per_cpu_times(PyObject *self, PyObject *args) {\n natural_t cpu_count;\n natural_t i;\n processor_info_array_t info_array;\n mach_msg_type_number_t info_count;\n kern_return_t error;\n processor_cpu_load_info_data_t *cpu_load_info = NULL;\n int ret;\n PyObject *py_retlist = PyList_New(0);\n PyObject *py_cputime = NULL;\n\n if (py_retlist == NULL)\n return NULL;\n\n mach_port_t host_port = mach_host_self();\n error = host_processor_info(host_port, PROCESSOR_CPU_LOAD_INFO,\n &cpu_count, &info_array, &info_count);\n if (error != KERN_SUCCESS) {\n PyErr_Format(\n PyExc_RuntimeError,\n \"host_processor_info(PROCESSOR_CPU_LOAD_INFO) syscall failed: %s\",\n mach_error_string(error));\n goto error;\n }\n mach_port_deallocate(mach_task_self(), host_port);\n\n cpu_load_info = (processor_cpu_load_info_data_t *) info_array;\n\n for (i = 0; i < cpu_count; i++) {\n py_cputime = Py_BuildValue(\n \"(dddd)\",\n (double)cpu_load_info[i].cpu_ticks[CPU_STATE_USER] / CLK_TCK,\n (double)cpu_load_info[i].cpu_ticks[CPU_STATE_NICE] / CLK_TCK,\n (double)cpu_load_info[i].cpu_ticks[CPU_STATE_SYSTEM] / CLK_TCK,\n (double)cpu_load_info[i].cpu_ticks[CPU_STATE_IDLE] / CLK_TCK\n );\n if (!py_cputime)\n goto error;\n if (PyList_Append(py_retlist, py_cputime))\n goto error;\n Py_DECREF(py_cputime);\n }\n\n ret = vm_deallocate(mach_task_self(), (vm_address_t)info_array,\n info_count * sizeof(int));\n if (ret != KERN_SUCCESS)\n PyErr_WarnEx(PyExc_RuntimeWarning, \"vm_deallocate() failed\", 2);\n return py_retlist;\n\nerror:\n Py_XDECREF(py_cputime);\n Py_DECREF(py_retlist);\n if (cpu_load_info != NULL) {\n ret = vm_deallocate(mach_task_self(), (vm_address_t)info_array,\n info_count * sizeof(int));\n if (ret != KERN_SUCCESS)\n PyErr_WarnEx(PyExc_RuntimeWarning, \"vm_deallocate() failed\", 2);\n }\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_net_if_addrs(PyObject *self, PyObject *args) {\n unsigned int i = 0;\n ULONG family;\n PCTSTR intRet;\n PCTSTR netmaskIntRet;\n char *ptr;\n char buff_addr[1024];\n char buff_macaddr[1024];\n char buff_netmask[1024];\n DWORD dwRetVal = 0;\n#if (_WIN32_WINNT >= 0x0600) // Windows Vista and above\n ULONG converted_netmask;\n UINT netmask_bits;\n struct in_addr in_netmask;\n#endif\n PIP_ADAPTER_ADDRESSES pAddresses = NULL;\n PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL;\n PIP_ADAPTER_UNICAST_ADDRESS pUnicast = NULL;\n\n PyObject *py_retlist = PyList_New(0);\n PyObject *py_tuple = NULL;\n PyObject *py_address = NULL;\n PyObject *py_mac_address = NULL;\n PyObject *py_nic_name = NULL;\n PyObject *py_netmask = NULL;\n\n if (py_retlist == NULL)\n return NULL;\n\n pAddresses = psutil_get_nic_addresses();\n if (pAddresses == NULL)\n goto error;\n pCurrAddresses = pAddresses;\n\n while (pCurrAddresses) {\n pUnicast = pCurrAddresses->FirstUnicastAddress;\n\n netmaskIntRet = NULL;\n py_nic_name = NULL;\n py_nic_name = PyUnicode_FromWideChar(\n pCurrAddresses->FriendlyName,\n wcslen(pCurrAddresses->FriendlyName));\n if (py_nic_name == NULL)\n goto error;\n\n // MAC address\n if (pCurrAddresses->PhysicalAddressLength != 0) {\n ptr = buff_macaddr;\n *ptr = '\\0';\n for (i = 0; i < (int) pCurrAddresses->PhysicalAddressLength; i++) {\n if (i == (pCurrAddresses->PhysicalAddressLength - 1)) {\n sprintf_s(ptr, _countof(buff_macaddr), \"%.2X\\n\",\n (int)pCurrAddresses->PhysicalAddress[i]);\n }\n else {\n sprintf_s(ptr, _countof(buff_macaddr), \"%.2X-\",\n (int)pCurrAddresses->PhysicalAddress[i]);\n }\n ptr += 3;\n }\n *--ptr = '\\0';\n\n py_mac_address = Py_BuildValue(\"s\", buff_macaddr);\n if (py_mac_address == NULL)\n goto error;\n\n Py_INCREF(Py_None);\n Py_INCREF(Py_None);\n Py_INCREF(Py_None);\n py_tuple = Py_BuildValue(\n \"(OiOOOO)\",\n py_nic_name,\n -1, // this will be converted later to AF_LINK\n py_mac_address,\n Py_None, // netmask (not supported)\n Py_None, // broadcast (not supported)\n Py_None // ptp (not supported on Windows)\n );\n if (! py_tuple)\n goto error;\n if (PyList_Append(py_retlist, py_tuple))\n goto error;\n Py_DECREF(py_tuple);\n Py_DECREF(py_mac_address);\n }\n\n // find out the IP address associated with the NIC\n if (pUnicast != NULL) {\n for (i = 0; pUnicast != NULL; i++) {\n family = pUnicast->Address.lpSockaddr->sa_family;\n if (family == AF_INET) {\n struct sockaddr_in *sa_in = (struct sockaddr_in *)\n pUnicast->Address.lpSockaddr;\n intRet = inet_ntop(AF_INET, &(sa_in->sin_addr), buff_addr,\n sizeof(buff_addr));\n if (!intRet)\n goto error;\n#if (_WIN32_WINNT >= 0x0600) // Windows Vista and above\n netmask_bits = pUnicast->OnLinkPrefixLength;\n dwRetVal = ConvertLengthToIpv4Mask(netmask_bits, &converted_netmask);\n if (dwRetVal == NO_ERROR) {\n in_netmask.s_addr = converted_netmask;\n netmaskIntRet = inet_ntop(\n AF_INET, &in_netmask, buff_netmask,\n sizeof(buff_netmask));\n if (!netmaskIntRet)\n goto error;\n }\n#endif\n }\n else if (family == AF_INET6) {\n struct sockaddr_in6 *sa_in6 = (struct sockaddr_in6 *)\n pUnicast->Address.lpSockaddr;\n intRet = inet_ntop(AF_INET6, &(sa_in6->sin6_addr),\n buff_addr, sizeof(buff_addr));\n if (!intRet)\n goto error;\n }\n else {\n // we should never get here\n pUnicast = pUnicast->Next;\n continue;\n }\n\n#if PY_MAJOR_VERSION >= 3\n py_address = PyUnicode_FromString(buff_addr);\n#else\n py_address = PyString_FromString(buff_addr);\n#endif\n if (py_address == NULL)\n goto error;\n\n if (netmaskIntRet != NULL) {\n#if PY_MAJOR_VERSION >= 3\n py_netmask = PyUnicode_FromString(buff_netmask);\n#else\n py_netmask = PyString_FromString(buff_netmask);\n#endif\n } else {\n Py_INCREF(Py_None);\n py_netmask = Py_None;\n }\n\n Py_INCREF(Py_None);\n Py_INCREF(Py_None);\n py_tuple = Py_BuildValue(\n \"(OiOOOO)\",\n py_nic_name,\n family,\n py_address,\n py_netmask,\n Py_None, // broadcast (not supported)\n Py_None // ptp (not supported on Windows)\n );\n\n if (! py_tuple)\n goto error;\n if (PyList_Append(py_retlist, py_tuple))\n goto error;\n Py_DECREF(py_tuple);\n Py_DECREF(py_address);\n Py_DECREF(py_netmask);\n\n pUnicast = pUnicast->Next;\n }\n }\n Py_DECREF(py_nic_name);\n pCurrAddresses = pCurrAddresses->Next;\n }\n\n free(pAddresses);\n return py_retlist;\n\nerror:\n if (pAddresses)\n free(pAddresses);\n Py_DECREF(py_retlist);\n Py_XDECREF(py_tuple);\n Py_XDECREF(py_address);\n Py_XDECREF(py_nic_name);\n Py_XDECREF(py_netmask);\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_net_connections(PyObject *self, PyObject *args) {\n static long null_address[4] = { 0, 0, 0, 0 };\n unsigned long pid;\n int pid_return;\n PVOID table = NULL;\n DWORD tableSize;\n DWORD error;\n PMIB_TCPTABLE_OWNER_PID tcp4Table;\n PMIB_UDPTABLE_OWNER_PID udp4Table;\n PMIB_TCP6TABLE_OWNER_PID tcp6Table;\n PMIB_UDP6TABLE_OWNER_PID udp6Table;\n ULONG i;\n CHAR addressBufferLocal[65];\n CHAR addressBufferRemote[65];\n\n PyObject *py_retlist;\n PyObject *py_conn_tuple = NULL;\n PyObject *py_af_filter = NULL;\n PyObject *py_type_filter = NULL;\n PyObject *py_addr_tuple_local = NULL;\n PyObject *py_addr_tuple_remote = NULL;\n PyObject *_AF_INET = PyLong_FromLong((long)AF_INET);\n PyObject *_AF_INET6 = PyLong_FromLong((long)AF_INET6);\n PyObject *_SOCK_STREAM = PyLong_FromLong((long)SOCK_STREAM);\n PyObject *_SOCK_DGRAM = PyLong_FromLong((long)SOCK_DGRAM);\n\n // Import some functions.\n if (! PyArg_ParseTuple(args, \"lOO\", &pid, &py_af_filter, &py_type_filter))\n goto error;\n\n if (!PySequence_Check(py_af_filter) || !PySequence_Check(py_type_filter)) {\n psutil_conn_decref_objs();\n PyErr_SetString(PyExc_TypeError, \"arg 2 or 3 is not a sequence\");\n return NULL;\n }\n\n if (pid != -1) {\n pid_return = psutil_pid_is_running(pid);\n if (pid_return == 0) {\n psutil_conn_decref_objs();\n return NoSuchProcess(\"\");\n }\n else if (pid_return == -1) {\n psutil_conn_decref_objs();\n return NULL;\n }\n }\n\n py_retlist = PyList_New(0);\n if (py_retlist == NULL) {\n psutil_conn_decref_objs();\n return NULL;\n }\n\n // TCP IPv4\n\n if ((PySequence_Contains(py_af_filter, _AF_INET) == 1) &&\n (PySequence_Contains(py_type_filter, _SOCK_STREAM) == 1))\n {\n table = NULL;\n py_conn_tuple = NULL;\n py_addr_tuple_local = NULL;\n py_addr_tuple_remote = NULL;\n tableSize = 0;\n\n error = __GetExtendedTcpTable(psutil_GetExtendedTcpTable,\n AF_INET, &table, &tableSize);\n if (error != 0)\n goto error;\n tcp4Table = table;\n for (i = 0; i < tcp4Table->dwNumEntries; i++) {\n if (pid != -1) {\n if (tcp4Table->table[i].dwOwningPid != pid) {\n continue;\n }\n }\n\n if (tcp4Table->table[i].dwLocalAddr != 0 ||\n tcp4Table->table[i].dwLocalPort != 0)\n {\n struct in_addr addr;\n\n addr.S_un.S_addr = tcp4Table->table[i].dwLocalAddr;\n psutil_rtlIpv4AddressToStringA(&addr, addressBufferLocal);\n py_addr_tuple_local = Py_BuildValue(\n \"(si)\",\n addressBufferLocal,\n BYTESWAP_USHORT(tcp4Table->table[i].dwLocalPort));\n }\n else {\n py_addr_tuple_local = PyTuple_New(0);\n }\n\n if (py_addr_tuple_local == NULL)\n goto error;\n\n // On Windows <= XP, remote addr is filled even if socket\n // is in LISTEN mode in which case we just ignore it.\n if ((tcp4Table->table[i].dwRemoteAddr != 0 ||\n tcp4Table->table[i].dwRemotePort != 0) &&\n (tcp4Table->table[i].dwState != MIB_TCP_STATE_LISTEN))\n {\n struct in_addr addr;\n\n addr.S_un.S_addr = tcp4Table->table[i].dwRemoteAddr;\n psutil_rtlIpv4AddressToStringA(&addr, addressBufferRemote);\n py_addr_tuple_remote = Py_BuildValue(\n \"(si)\",\n addressBufferRemote,\n BYTESWAP_USHORT(tcp4Table->table[i].dwRemotePort));\n }\n else\n {\n py_addr_tuple_remote = PyTuple_New(0);\n }\n\n if (py_addr_tuple_remote == NULL)\n goto error;\n\n py_conn_tuple = Py_BuildValue(\n \"(iiiNNiI)\",\n -1,\n AF_INET,\n SOCK_STREAM,\n py_addr_tuple_local,\n py_addr_tuple_remote,\n tcp4Table->table[i].dwState,\n tcp4Table->table[i].dwOwningPid);\n if (!py_conn_tuple)\n goto error;\n if (PyList_Append(py_retlist, py_conn_tuple))\n goto error;\n Py_DECREF(py_conn_tuple);\n }\n\n free(table);\n table = NULL;\n tableSize = 0;\n }\n\n // TCP IPv6\n if ((PySequence_Contains(py_af_filter, _AF_INET6) == 1) &&\n (PySequence_Contains(py_type_filter, _SOCK_STREAM) == 1) &&\n (psutil_rtlIpv6AddressToStringA != NULL))\n {\n table = NULL;\n py_conn_tuple = NULL;\n py_addr_tuple_local = NULL;\n py_addr_tuple_remote = NULL;\n tableSize = 0;\n\n error = __GetExtendedTcpTable(psutil_GetExtendedTcpTable,\n AF_INET6, &table, &tableSize);\n if (error != 0)\n goto error;\n tcp6Table = table;\n for (i = 0; i < tcp6Table->dwNumEntries; i++)\n {\n if (pid != -1) {\n if (tcp6Table->table[i].dwOwningPid != pid) {\n continue;\n }\n }\n\n if (memcmp(tcp6Table->table[i].ucLocalAddr, null_address, 16)\n != 0 || tcp6Table->table[i].dwLocalPort != 0)\n {\n struct in6_addr addr;\n\n memcpy(&addr, tcp6Table->table[i].ucLocalAddr, 16);\n psutil_rtlIpv6AddressToStringA(&addr, addressBufferLocal);\n py_addr_tuple_local = Py_BuildValue(\n \"(si)\",\n addressBufferLocal,\n BYTESWAP_USHORT(tcp6Table->table[i].dwLocalPort));\n }\n else {\n py_addr_tuple_local = PyTuple_New(0);\n }\n\n if (py_addr_tuple_local == NULL)\n goto error;\n\n // On Windows <= XP, remote addr is filled even if socket\n // is in LISTEN mode in which case we just ignore it.\n if ((memcmp(tcp6Table->table[i].ucRemoteAddr, null_address, 16)\n != 0 ||\n tcp6Table->table[i].dwRemotePort != 0) &&\n (tcp6Table->table[i].dwState != MIB_TCP_STATE_LISTEN))\n {\n struct in6_addr addr;\n\n memcpy(&addr, tcp6Table->table[i].ucRemoteAddr, 16);\n psutil_rtlIpv6AddressToStringA(&addr, addressBufferRemote);\n py_addr_tuple_remote = Py_BuildValue(\n \"(si)\",\n addressBufferRemote,\n BYTESWAP_USHORT(tcp6Table->table[i].dwRemotePort));\n }\n else {\n py_addr_tuple_remote = PyTuple_New(0);\n }\n\n if (py_addr_tuple_remote == NULL)\n goto error;\n\n py_conn_tuple = Py_BuildValue(\n \"(iiiNNiI)\",\n -1,\n AF_INET6,\n SOCK_STREAM,\n py_addr_tuple_local,\n py_addr_tuple_remote,\n tcp6Table->table[i].dwState,\n tcp6Table->table[i].dwOwningPid);\n if (!py_conn_tuple)\n goto error;\n if (PyList_Append(py_retlist, py_conn_tuple))\n goto error;\n Py_DECREF(py_conn_tuple);\n }\n\n free(table);\n table = NULL;\n tableSize = 0;\n }\n\n // UDP IPv4\n\n if ((PySequence_Contains(py_af_filter, _AF_INET) == 1) &&\n (PySequence_Contains(py_type_filter, _SOCK_DGRAM) == 1))\n {\n table = NULL;\n py_conn_tuple = NULL;\n py_addr_tuple_local = NULL;\n py_addr_tuple_remote = NULL;\n tableSize = 0;\n error = __GetExtendedUdpTable(psutil_GetExtendedUdpTable,\n AF_INET, &table, &tableSize);\n if (error != 0)\n goto error;\n udp4Table = table;\n for (i = 0; i < udp4Table->dwNumEntries; i++)\n {\n if (pid != -1) {\n if (udp4Table->table[i].dwOwningPid != pid) {\n continue;\n }\n }\n\n if (udp4Table->table[i].dwLocalAddr != 0 ||\n udp4Table->table[i].dwLocalPort != 0)\n {\n struct in_addr addr;\n\n addr.S_un.S_addr = udp4Table->table[i].dwLocalAddr;\n psutil_rtlIpv4AddressToStringA(&addr, addressBufferLocal);\n py_addr_tuple_local = Py_BuildValue(\n \"(si)\",\n addressBufferLocal,\n BYTESWAP_USHORT(udp4Table->table[i].dwLocalPort));\n }\n else {\n py_addr_tuple_local = PyTuple_New(0);\n }\n\n if (py_addr_tuple_local == NULL)\n goto error;\n\n py_conn_tuple = Py_BuildValue(\n \"(iiiNNiI)\",\n -1,\n AF_INET,\n SOCK_DGRAM,\n py_addr_tuple_local,\n PyTuple_New(0),\n PSUTIL_CONN_NONE,\n udp4Table->table[i].dwOwningPid);\n if (!py_conn_tuple)\n goto error;\n if (PyList_Append(py_retlist, py_conn_tuple))\n goto error;\n Py_DECREF(py_conn_tuple);\n }\n\n free(table);\n table = NULL;\n tableSize = 0;\n }\n\n // UDP IPv6\n\n if ((PySequence_Contains(py_af_filter, _AF_INET6) == 1) &&\n (PySequence_Contains(py_type_filter, _SOCK_DGRAM) == 1) &&\n (psutil_rtlIpv6AddressToStringA != NULL))\n {\n table = NULL;\n py_conn_tuple = NULL;\n py_addr_tuple_local = NULL;\n py_addr_tuple_remote = NULL;\n tableSize = 0;\n error = __GetExtendedUdpTable(psutil_GetExtendedUdpTable,\n AF_INET6, &table, &tableSize);\n if (error != 0)\n goto error;\n udp6Table = table;\n for (i = 0; i < udp6Table->dwNumEntries; i++) {\n if (pid != -1) {\n if (udp6Table->table[i].dwOwningPid != pid) {\n continue;\n }\n }\n\n if (memcmp(udp6Table->table[i].ucLocalAddr, null_address, 16)\n != 0 || udp6Table->table[i].dwLocalPort != 0)\n {\n struct in6_addr addr;\n\n memcpy(&addr, udp6Table->table[i].ucLocalAddr, 16);\n psutil_rtlIpv6AddressToStringA(&addr, addressBufferLocal);\n py_addr_tuple_local = Py_BuildValue(\n \"(si)\",\n addressBufferLocal,\n BYTESWAP_USHORT(udp6Table->table[i].dwLocalPort));\n }\n else {\n py_addr_tuple_local = PyTuple_New(0);\n }\n\n if (py_addr_tuple_local == NULL)\n goto error;\n\n py_conn_tuple = Py_BuildValue(\n \"(iiiNNiI)\",\n -1,\n AF_INET6,\n SOCK_DGRAM,\n py_addr_tuple_local,\n PyTuple_New(0),\n PSUTIL_CONN_NONE,\n udp6Table->table[i].dwOwningPid);\n if (!py_conn_tuple)\n goto error;\n if (PyList_Append(py_retlist, py_conn_tuple))\n goto error;\n Py_DECREF(py_conn_tuple);\n }\n\n free(table);\n table = NULL;\n tableSize = 0;\n }\n\n psutil_conn_decref_objs();\n return py_retlist;\n\nerror:\n psutil_conn_decref_objs();\n Py_XDECREF(py_conn_tuple);\n Py_XDECREF(py_addr_tuple_local);\n Py_XDECREF(py_addr_tuple_remote);\n Py_DECREF(py_retlist);\n if (table != NULL)\n free(table);\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_ppid_map(PyObject *self, PyObject *args) {\n PyObject *py_pid = NULL;\n PyObject *py_ppid = NULL;\n PyObject *py_retdict = PyDict_New();\n HANDLE handle = NULL;\n PROCESSENTRY32 pe = {0};\n pe.dwSize = sizeof(PROCESSENTRY32);\n\n if (py_retdict == NULL)\n return NULL;\n handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);\n if (handle == INVALID_HANDLE_VALUE) {\n PyErr_SetFromWindowsErr(0);\n Py_DECREF(py_retdict);\n return NULL;\n }\n\n if (Process32First(handle, &pe)) {\n do {\n py_pid = Py_BuildValue(\"I\", pe.th32ProcessID);\n if (py_pid == NULL)\n goto error;\n py_ppid = Py_BuildValue(\"I\", pe.th32ParentProcessID);\n if (py_ppid == NULL)\n goto error;\n if (PyDict_SetItem(py_retdict, py_pid, py_ppid))\n goto error;\n Py_DECREF(py_pid);\n Py_DECREF(py_ppid);\n } while (Process32Next(handle, &pe));\n }\n\n CloseHandle(handle);\n return py_retdict;\n\nerror:\n Py_XDECREF(py_pid);\n Py_XDECREF(py_ppid);\n Py_DECREF(py_retdict);\n CloseHandle(handle);\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: int ath9k_wmi_cmd(struct wmi *wmi, enum wmi_cmd_id cmd_id,\n\t\t u8 *cmd_buf, u32 cmd_len,\n\t\t u8 *rsp_buf, u32 rsp_len,\n\t\t u32 timeout)\n{\n\tstruct ath_hw *ah = wmi->drv_priv->ah;\n\tstruct ath_common *common = ath9k_hw_common(ah);\n\tu16 headroom = sizeof(struct htc_frame_hdr) +\n\t\t sizeof(struct wmi_cmd_hdr);\n\tstruct sk_buff *skb;\n\tunsigned long time_left;\n\tint ret = 0;\n\n\tif (ah->ah_flags & AH_UNPLUGGED)\n\t\treturn 0;\n\n\tskb = alloc_skb(headroom + cmd_len, GFP_ATOMIC);\n\tif (!skb)\n\t\treturn -ENOMEM;\n\n\tskb_reserve(skb, headroom);\n\n\tif (cmd_len != 0 && cmd_buf != NULL) {\n\t\tskb_put_data(skb, cmd_buf, cmd_len);\n\t}\n\n\tmutex_lock(&wmi->op_mutex);\n\n\t/* check if wmi stopped flag is set */\n\tif (unlikely(wmi->stopped)) {\n\t\tret = -EPROTO;\n\t\tgoto out;\n\t}\n\n\t/* record the rsp buffer and length */\n\twmi->cmd_rsp_buf = rsp_buf;\n\twmi->cmd_rsp_len = rsp_len;\n\n\tret = ath9k_wmi_cmd_issue(wmi, skb, cmd_id, cmd_len);\n\tif (ret)\n\t\tgoto out;\n\n\ttime_left = wait_for_completion_timeout(&wmi->cmd_wait, timeout);\n\tif (!time_left) {\n\t\tath_dbg(common, WMI, \"Timeout waiting for WMI command: %s\\n\",\n\t\t\twmi_cmd_to_name(cmd_id));\n\t\tmutex_unlock(&wmi->op_mutex);\n\t\treturn -ETIMEDOUT;\n\t}\n\n\tmutex_unlock(&wmi->op_mutex);\n\n\treturn 0;\n\nout:\n\tath_dbg(common, WMI, \"WMI failure for: %s\\n\", wmi_cmd_to_name(cmd_id));\n\tmutex_unlock(&wmi->op_mutex);\n\tkfree_skb(skb);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'ath9k: release allocated buffer if timed out\n\nIn ath9k_wmi_cmd, the allocated network buffer needs to be released\nif timeout happens. Otherwise memory will be leaked.\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: static int i40e_setup_macvlans(struct i40e_vsi *vsi, u16 macvlan_cnt, u16 qcnt,\n\t\t\t struct net_device *vdev)\n{\n\tstruct i40e_pf *pf = vsi->back;\n\tstruct i40e_hw *hw = &pf->hw;\n\tstruct i40e_vsi_context ctxt;\n\tu16 sections, qmap, num_qps;\n\tstruct i40e_channel *ch;\n\tint i, pow, ret = 0;\n\tu8 offset = 0;\n\n\tif (vsi->type != I40E_VSI_MAIN || !macvlan_cnt)\n\t\treturn -EINVAL;\n\n\tnum_qps = vsi->num_queue_pairs - (macvlan_cnt * qcnt);\n\n\t/* find the next higher power-of-2 of num queue pairs */\n\tpow = fls(roundup_pow_of_two(num_qps) - 1);\n\n\tqmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |\n\t\t(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);\n\n\t/* Setup context bits for the main VSI */\n\tsections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;\n\tsections |= I40E_AQ_VSI_PROP_SCHED_VALID;\n\tmemset(&ctxt, 0, sizeof(ctxt));\n\tctxt.seid = vsi->seid;\n\tctxt.pf_num = vsi->back->hw.pf_id;\n\tctxt.vf_num = 0;\n\tctxt.uplink_seid = vsi->uplink_seid;\n\tctxt.info = vsi->info;\n\tctxt.info.tc_mapping[0] = cpu_to_le16(qmap);\n\tctxt.info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);\n\tctxt.info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);\n\tctxt.info.valid_sections |= cpu_to_le16(sections);\n\n\t/* Reconfigure RSS for main VSI with new max queue count */\n\tvsi->rss_size = max_t(u16, num_qps, qcnt);\n\tret = i40e_vsi_config_rss(vsi);\n\tif (ret) {\n\t\tdev_info(&pf->pdev->dev,\n\t\t\t \"Failed to reconfig RSS for num_queues (%u)\\n\",\n\t\t\t vsi->rss_size);\n\t\treturn ret;\n\t}\n\tvsi->reconfig_rss = true;\n\tdev_dbg(&vsi->back->pdev->dev,\n\t\t\"Reconfigured RSS with num_queues (%u)\\n\", vsi->rss_size);\n\tvsi->next_base_queue = num_qps;\n\tvsi->cnt_q_avail = vsi->num_queue_pairs - num_qps;\n\n\t/* Update the VSI after updating the VSI queue-mapping\n\t * information\n\t */\n\tret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);\n\tif (ret) {\n\t\tdev_info(&pf->pdev->dev,\n\t\t\t \"Update vsi tc config failed, err %s aq_err %s\\n\",\n\t\t\t i40e_stat_str(hw, ret),\n\t\t\t i40e_aq_str(hw, hw->aq.asq_last_status));\n\t\treturn ret;\n\t}\n\t/* update the local VSI info with updated queue map */\n\ti40e_vsi_update_queue_map(vsi, &ctxt);\n\tvsi->info.valid_sections = 0;\n\n\t/* Create channels for macvlans */\n\tINIT_LIST_HEAD(&vsi->macvlan_list);\n\tfor (i = 0; i < macvlan_cnt; i++) {\n\t\tch = kzalloc(sizeof(*ch), GFP_KERNEL);\n\t\tif (!ch) {\n\t\t\tret = -ENOMEM;\n\t\t\tgoto err_free;\n\t\t}\n\t\tINIT_LIST_HEAD(&ch->list);\n\t\tch->num_queue_pairs = qcnt;\n\t\tif (!i40e_setup_channel(pf, vsi, ch)) {\n\t\t\tret = -EINVAL;\n\t\t\tgoto err_free;\n\t\t}\n\t\tch->parent_vsi = vsi;\n\t\tvsi->cnt_q_avail -= ch->num_queue_pairs;\n\t\tvsi->macvlan_cnt++;\n\t\tlist_add_tail(&ch->list, &vsi->macvlan_list);\n\t}\n\n\treturn ret;\n\nerr_free:\n\tdev_info(&pf->pdev->dev, \"Failed to setup macvlans\\n\");\n\ti40e_free_macvlan_channels(vsi);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'i40e: prevent memory leak in i40e_setup_macvlans\n\nIn i40e_setup_macvlans if i40e_setup_channel fails the allocated memory\nfor ch should be released.\n\nSigned-off-by: Navid Emamdoost \nTested-by: Andrew Bowers \nSigned-off-by: Jeff Kirsher '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int i2400m_op_rfkill_sw_toggle(struct wimax_dev *wimax_dev,\n\t\t\t enum wimax_rf_state state)\n{\n\tint result;\n\tstruct i2400m *i2400m = wimax_dev_to_i2400m(wimax_dev);\n\tstruct device *dev = i2400m_dev(i2400m);\n\tstruct sk_buff *ack_skb;\n\tstruct {\n\t\tstruct i2400m_l3l4_hdr hdr;\n\t\tstruct i2400m_tlv_rf_operation sw_rf;\n\t} __packed *cmd;\n\tchar strerr[32];\n\n\td_fnstart(4, dev, \"(wimax_dev %p state %d)\\n\", wimax_dev, state);\n\n\tresult = -ENOMEM;\n\tcmd = kzalloc(sizeof(*cmd), GFP_KERNEL);\n\tif (cmd == NULL)\n\t\tgoto error_alloc;\n\tcmd->hdr.type = cpu_to_le16(I2400M_MT_CMD_RF_CONTROL);\n\tcmd->hdr.length = sizeof(cmd->sw_rf);\n\tcmd->hdr.version = cpu_to_le16(I2400M_L3L4_VERSION);\n\tcmd->sw_rf.hdr.type = cpu_to_le16(I2400M_TLV_RF_OPERATION);\n\tcmd->sw_rf.hdr.length = cpu_to_le16(sizeof(cmd->sw_rf.status));\n\tswitch (state) {\n\tcase WIMAX_RF_OFF:\t/* RFKILL ON, radio OFF */\n\t\tcmd->sw_rf.status = cpu_to_le32(2);\n\t\tbreak;\n\tcase WIMAX_RF_ON:\t/* RFKILL OFF, radio ON */\n\t\tcmd->sw_rf.status = cpu_to_le32(1);\n\t\tbreak;\n\tdefault:\n\t\tBUG();\n\t}\n\n\tack_skb = i2400m_msg_to_dev(i2400m, cmd, sizeof(*cmd));\n\tresult = PTR_ERR(ack_skb);\n\tif (IS_ERR(ack_skb)) {\n\t\tdev_err(dev, \"Failed to issue 'RF Control' command: %d\\n\",\n\t\t\tresult);\n\t\tgoto error_msg_to_dev;\n\t}\n\tresult = i2400m_msg_check_status(wimax_msg_data(ack_skb),\n\t\t\t\t\t strerr, sizeof(strerr));\n\tif (result < 0) {\n\t\tdev_err(dev, \"'RF Control' (0x%04x) command failed: %d - %s\\n\",\n\t\t\tI2400M_MT_CMD_RF_CONTROL, result, strerr);\n\t\tgoto error_cmd;\n\t}\n\n\t/* Now we wait for the state to change to RADIO_OFF or RADIO_ON */\n\tresult = wait_event_timeout(\n\t\ti2400m->state_wq, i2400m_radio_is(i2400m, state),\n\t\t5 * HZ);\n\tif (result == 0)\n\t\tresult = -ETIMEDOUT;\n\tif (result < 0)\n\t\tdev_err(dev, \"Error waiting for device to toggle RF state: \"\n\t\t\t\"%d\\n\", result);\n\tresult = 0;\nerror_cmd:\n\tkfree(cmd);\n\tkfree_skb(ack_skb);\nerror_msg_to_dev:\nerror_alloc:\n\td_fnend(4, dev, \"(wimax_dev %p state %d) = %d\\n\",\n\t\twimax_dev, state, result);\n\treturn result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'wimax: i2400: Fix memory leak in i2400m_op_rfkill_sw_toggle\n\nIn the implementation of i2400m_op_rfkill_sw_toggle() the allocated\nbuffer for cmd should be released before returning. The\ndocumentation for i2400m_msg_to_dev() says when it returns the buffer\ncan be reused. Meaning cmd should be released in either case. Move\nkfree(cmd) before return to be reached by all execution paths.\n\nFixes: 2507e6ab7a9a (\"wimax: i2400: fix memory leak\")\nSigned-off-by: Navid Emamdoost \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 rpmsg_eptdev_write_iter(struct kiocb *iocb,\n\t\t\t\t struct iov_iter *from)\n{\n\tstruct file *filp = iocb->ki_filp;\n\tstruct rpmsg_eptdev *eptdev = filp->private_data;\n\tsize_t len = iov_iter_count(from);\n\tvoid *kbuf;\n\tint ret;\n\n\tkbuf = kzalloc(len, GFP_KERNEL);\n\tif (!kbuf)\n\t\treturn -ENOMEM;\n\n\tif (!copy_from_iter_full(kbuf, len, from))\n\t\treturn -EFAULT;\n\n\tif (mutex_lock_interruptible(&eptdev->ept_lock)) {\n\t\tret = -ERESTARTSYS;\n\t\tgoto free_kbuf;\n\t}\n\n\tif (!eptdev->ept) {\n\t\tret = -EPIPE;\n\t\tgoto unlock_eptdev;\n\t}\n\n\tif (filp->f_flags & O_NONBLOCK)\n\t\tret = rpmsg_trysend(eptdev->ept, kbuf, len);\n\telse\n\t\tret = rpmsg_send(eptdev->ept, kbuf, len);\n\nunlock_eptdev:\n\tmutex_unlock(&eptdev->ept_lock);\n\nfree_kbuf:\n\tkfree(kbuf);\n\treturn ret < 0 ? ret : len;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'rpmsg: char: release allocated memory\n\nIn rpmsg_eptdev_write_iter, if copy_from_iter_full fails the allocated\nbuffer needs to be released.\n\nSigned-off-by: Navid Emamdoost \nSigned-off-by: Bjorn Andersson '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int btrfs_scrub_progress(struct btrfs_fs_info *fs_info, u64 devid,\n\t\t\t struct btrfs_scrub_progress *progress)\n{\n\tstruct btrfs_device *dev;\n\tstruct scrub_ctx *sctx = NULL;\n\n\tmutex_lock(&fs_info->fs_devices->device_list_mutex);\n\tdev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL);\n\tif (dev)\n\t\tsctx = dev->scrub_ctx;\n\tif (sctx)\n\t\tmemcpy(progress, &sctx->stat, sizeof(*progress));\n\tmutex_unlock(&fs_info->fs_devices->device_list_mutex);\n\n\treturn dev ? (sctx ? 0 : -ENOTCONN) : -ENODEV;\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: int btrfs_init_dev_replace(struct btrfs_fs_info *fs_info)\n{\n\tstruct btrfs_key key;\n\tstruct btrfs_root *dev_root = fs_info->dev_root;\n\tstruct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;\n\tstruct extent_buffer *eb;\n\tint slot;\n\tint ret = 0;\n\tstruct btrfs_path *path = NULL;\n\tint item_size;\n\tstruct btrfs_dev_replace_item *ptr;\n\tu64 src_devid;\n\n\tpath = btrfs_alloc_path();\n\tif (!path) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}\n\n\tkey.objectid = 0;\n\tkey.type = BTRFS_DEV_REPLACE_KEY;\n\tkey.offset = 0;\n\tret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);\n\tif (ret) {\nno_valid_dev_replace_entry_found:\n\t\tret = 0;\n\t\tdev_replace->replace_state =\n\t\t\tBTRFS_DEV_REPLACE_ITEM_STATE_NEVER_STARTED;\n\t\tdev_replace->cont_reading_from_srcdev_mode =\n\t\t BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_ALWAYS;\n\t\tdev_replace->time_started = 0;\n\t\tdev_replace->time_stopped = 0;\n\t\tatomic64_set(&dev_replace->num_write_errors, 0);\n\t\tatomic64_set(&dev_replace->num_uncorrectable_read_errors, 0);\n\t\tdev_replace->cursor_left = 0;\n\t\tdev_replace->committed_cursor_left = 0;\n\t\tdev_replace->cursor_left_last_write_of_item = 0;\n\t\tdev_replace->cursor_right = 0;\n\t\tdev_replace->srcdev = NULL;\n\t\tdev_replace->tgtdev = NULL;\n\t\tdev_replace->is_valid = 0;\n\t\tdev_replace->item_needs_writeback = 0;\n\t\tgoto out;\n\t}\n\tslot = path->slots[0];\n\teb = path->nodes[0];\n\titem_size = btrfs_item_size_nr(eb, slot);\n\tptr = btrfs_item_ptr(eb, slot, struct btrfs_dev_replace_item);\n\n\tif (item_size != sizeof(struct btrfs_dev_replace_item)) {\n\t\tbtrfs_warn(fs_info,\n\t\t\t\"dev_replace entry found has unexpected size, ignore entry\");\n\t\tgoto no_valid_dev_replace_entry_found;\n\t}\n\n\tsrc_devid = btrfs_dev_replace_src_devid(eb, ptr);\n\tdev_replace->cont_reading_from_srcdev_mode =\n\t\tbtrfs_dev_replace_cont_reading_from_srcdev_mode(eb, ptr);\n\tdev_replace->replace_state = btrfs_dev_replace_replace_state(eb, ptr);\n\tdev_replace->time_started = btrfs_dev_replace_time_started(eb, ptr);\n\tdev_replace->time_stopped =\n\t\tbtrfs_dev_replace_time_stopped(eb, ptr);\n\tatomic64_set(&dev_replace->num_write_errors,\n\t\t btrfs_dev_replace_num_write_errors(eb, ptr));\n\tatomic64_set(&dev_replace->num_uncorrectable_read_errors,\n\t\t btrfs_dev_replace_num_uncorrectable_read_errors(eb, ptr));\n\tdev_replace->cursor_left = btrfs_dev_replace_cursor_left(eb, ptr);\n\tdev_replace->committed_cursor_left = dev_replace->cursor_left;\n\tdev_replace->cursor_left_last_write_of_item = dev_replace->cursor_left;\n\tdev_replace->cursor_right = btrfs_dev_replace_cursor_right(eb, ptr);\n\tdev_replace->is_valid = 1;\n\n\tdev_replace->item_needs_writeback = 0;\n\tswitch (dev_replace->replace_state) {\n\tcase BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:\n\tcase BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:\n\tcase BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:\n\t\tdev_replace->srcdev = NULL;\n\t\tdev_replace->tgtdev = NULL;\n\t\tbreak;\n\tcase BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:\n\tcase BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:\n\t\tdev_replace->srcdev = btrfs_find_device(fs_info->fs_devices,\n\t\t\t\t\t\t\tsrc_devid, NULL, NULL);\n\t\tdev_replace->tgtdev = btrfs_find_device(fs_info->fs_devices,\n\t\t\t\t\t\t\tBTRFS_DEV_REPLACE_DEVID,\n\t\t\t\t\t\t\tNULL, NULL);\n\t\t/*\n\t\t * allow 'btrfs dev replace_cancel' if src/tgt device is\n\t\t * missing\n\t\t */\n\t\tif (!dev_replace->srcdev &&\n\t\t !btrfs_test_opt(fs_info, DEGRADED)) {\n\t\t\tret = -EIO;\n\t\t\tbtrfs_warn(fs_info,\n\t\t\t \"cannot mount because device replace operation is ongoing and\");\n\t\t\tbtrfs_warn(fs_info,\n\t\t\t \"srcdev (devid %llu) is missing, need to run 'btrfs dev scan'?\",\n\t\t\t src_devid);\n\t\t}\n\t\tif (!dev_replace->tgtdev &&\n\t\t !btrfs_test_opt(fs_info, DEGRADED)) {\n\t\t\tret = -EIO;\n\t\t\tbtrfs_warn(fs_info,\n\t\t\t \"cannot mount because device replace operation is ongoing and\");\n\t\t\tbtrfs_warn(fs_info,\n\t\t\t \"tgtdev (devid %llu) is missing, need to run 'btrfs dev scan'?\",\n\t\t\t\tBTRFS_DEV_REPLACE_DEVID);\n\t\t}\n\t\tif (dev_replace->tgtdev) {\n\t\t\tif (dev_replace->srcdev) {\n\t\t\t\tdev_replace->tgtdev->total_bytes =\n\t\t\t\t\tdev_replace->srcdev->total_bytes;\n\t\t\t\tdev_replace->tgtdev->disk_total_bytes =\n\t\t\t\t\tdev_replace->srcdev->disk_total_bytes;\n\t\t\t\tdev_replace->tgtdev->commit_total_bytes =\n\t\t\t\t\tdev_replace->srcdev->commit_total_bytes;\n\t\t\t\tdev_replace->tgtdev->bytes_used =\n\t\t\t\t\tdev_replace->srcdev->bytes_used;\n\t\t\t\tdev_replace->tgtdev->commit_bytes_used =\n\t\t\t\t\tdev_replace->srcdev->commit_bytes_used;\n\t\t\t}\n\t\t\tset_bit(BTRFS_DEV_STATE_REPLACE_TGT,\n\t\t\t\t&dev_replace->tgtdev->dev_state);\n\n\t\t\tWARN_ON(fs_info->fs_devices->rw_devices == 0);\n\t\t\tdev_replace->tgtdev->io_width = fs_info->sectorsize;\n\t\t\tdev_replace->tgtdev->io_align = fs_info->sectorsize;\n\t\t\tdev_replace->tgtdev->sector_size = fs_info->sectorsize;\n\t\t\tdev_replace->tgtdev->fs_info = fs_info;\n\t\t\tset_bit(BTRFS_DEV_STATE_IN_FS_METADATA,\n\t\t\t\t&dev_replace->tgtdev->dev_state);\n\t\t}\n\t\tbreak;\n\t}\n\nout:\n\tbtrfs_free_path(path);\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 *dce100_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: struct clock_source *dce110_clock_source_create(\n\tstruct dc_context *ctx,\n\tstruct dc_bios *bios,\n\tenum clock_source_id id,\n\tconst struct dce110_clk_src_regs *regs,\n\tbool dp_clk_src)\n{\n\tstruct dce110_clk_src *clk_src =\n\t\tkzalloc(sizeof(struct dce110_clk_src), GFP_KERNEL);\n\n\tif (!clk_src)\n\t\treturn NULL;\n\n\tif (dce110_clk_src_construct(clk_src, ctx, bios, id,\n\t\t\tregs, &cs_shift, &cs_mask)) {\n\t\tclk_src->base.dp_clk_src = dp_clk_src;\n\t\treturn &clk_src->base;\n\t}\n\n\tBREAK_TO_DEBUGGER();\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703', 'CWE-401'], 'message': 'drm/amd/display: memory leak\n\nIn dcn*_clock_source_create when dcn20_clk_src_construct fails allocated\nclk_src needs release.\n\nSigned-off-by: Navid Emamdoost \nSigned-off-by: Alex Deucher '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int dwc3_pci_probe(struct pci_dev *pci, const struct pci_device_id *id)\n{\n\tstruct property_entry *p = (struct property_entry *)id->driver_data;\n\tstruct dwc3_pci\t\t*dwc;\n\tstruct resource\t\tres[2];\n\tint\t\t\tret;\n\tstruct device\t\t*dev = &pci->dev;\n\n\tret = pcim_enable_device(pci);\n\tif (ret) {\n\t\tdev_err(dev, \"failed to enable pci device\\n\");\n\t\treturn -ENODEV;\n\t}\n\n\tpci_set_master(pci);\n\n\tdwc = devm_kzalloc(dev, sizeof(*dwc), GFP_KERNEL);\n\tif (!dwc)\n\t\treturn -ENOMEM;\n\n\tdwc->dwc3 = platform_device_alloc(\"dwc3\", PLATFORM_DEVID_AUTO);\n\tif (!dwc->dwc3)\n\t\treturn -ENOMEM;\n\n\tmemset(res, 0x00, sizeof(struct resource) * ARRAY_SIZE(res));\n\n\tres[0].start\t= pci_resource_start(pci, 0);\n\tres[0].end\t= pci_resource_end(pci, 0);\n\tres[0].name\t= \"dwc_usb3\";\n\tres[0].flags\t= IORESOURCE_MEM;\n\n\tres[1].start\t= pci->irq;\n\tres[1].name\t= \"dwc_usb3\";\n\tres[1].flags\t= IORESOURCE_IRQ;\n\n\tret = platform_device_add_resources(dwc->dwc3, res, ARRAY_SIZE(res));\n\tif (ret) {\n\t\tdev_err(dev, \"couldn't add resources to dwc3 device\\n\");\n\t\tgoto err;\n\t}\n\n\tdwc->pci = pci;\n\tdwc->dwc3->dev.parent = dev;\n\tACPI_COMPANION_SET(&dwc->dwc3->dev, ACPI_COMPANION(dev));\n\n\tret = platform_device_add_properties(dwc->dwc3, p);\n\tif (ret < 0)\n\t\treturn ret;\n\n\tret = dwc3_pci_quirks(dwc);\n\tif (ret)\n\t\tgoto err;\n\n\tret = platform_device_add(dwc->dwc3);\n\tif (ret) {\n\t\tdev_err(dev, \"failed to register dwc3 device\\n\");\n\t\tgoto err;\n\t}\n\n\tdevice_init_wakeup(dev, true);\n\tpci_set_drvdata(pci, dwc);\n\tpm_runtime_put(dev);\n#ifdef CONFIG_PM\n\tINIT_WORK(&dwc->wakeup_work, dwc3_pci_resume_work);\n#endif\n\n\treturn 0;\nerr:\n\tplatform_device_put(dwc->dwc3);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'usb: dwc3: pci: prevent memory leak in dwc3_pci_probe\n\nIn dwc3_pci_probe a call to platform_device_alloc allocates a device\nwhich is correctly put in case of error except one case: when the call to\nplatform_device_add_properties fails it directly returns instead of\ngoing to error handling. This commit replaces return with the goto.\n\nFixes: 1a7b12f69a94 (\"usb: dwc3: pci: Supply device properties via driver data\")\nSigned-off-by: Navid Emamdoost \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: sushi_get_font_name (FT_Face face,\n gboolean short_form)\n{\n if (short_form && g_strcmp0 (face->style_name, \"Regular\") == 0)\n return g_strdup (face->family_name);\n\n return g_strconcat (face->family_name, \", \", face->style_name, NULL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fallback to basename when no family name (CVE-2019-19308)\n\nInstead of possibly returning an empty string, which will cause\nissues later on.\n\nWe store the GFile that was loaded to create the FT_Face into its\ngeneric client data structure, and load the basename from it when\nwe don't have a family name.\n\nhttps://gitlab.gnome.org/GNOME/gnome-font-viewer/issues/17'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int module_clone(int argc, const char **argv, const char *prefix)\n{\n\tconst char *name = NULL, *url = NULL, *depth = NULL;\n\tint quiet = 0;\n\tint progress = 0;\n\tchar *p, *path = NULL, *sm_gitdir;\n\tstruct strbuf sb = STRBUF_INIT;\n\tstruct string_list reference = STRING_LIST_INIT_NODUP;\n\tchar *sm_alternate = NULL, *error_strategy = NULL;\n\n\tstruct option module_clone_options[] = {\n\t\tOPT_STRING(0, \"prefix\", &prefix,\n\t\t\t N_(\"path\"),\n\t\t\t N_(\"alternative anchor for relative paths\")),\n\t\tOPT_STRING(0, \"path\", &path,\n\t\t\t N_(\"path\"),\n\t\t\t N_(\"where the new submodule will be cloned to\")),\n\t\tOPT_STRING(0, \"name\", &name,\n\t\t\t N_(\"string\"),\n\t\t\t N_(\"name of the new submodule\")),\n\t\tOPT_STRING(0, \"url\", &url,\n\t\t\t N_(\"string\"),\n\t\t\t N_(\"url where to clone the submodule from\")),\n\t\tOPT_STRING_LIST(0, \"reference\", &reference,\n\t\t\t N_(\"repo\"),\n\t\t\t N_(\"reference repository\")),\n\t\tOPT_STRING(0, \"depth\", &depth,\n\t\t\t N_(\"string\"),\n\t\t\t N_(\"depth for shallow clones\")),\n\t\tOPT__QUIET(&quiet, \"Suppress output for cloning a submodule\"),\n\t\tOPT_BOOL(0, \"progress\", &progress,\n\t\t\t N_(\"force cloning progress\")),\n\t\tOPT_END()\n\t};\n\n\tconst char *const git_submodule_helper_usage[] = {\n\t\tN_(\"git submodule--helper clone [--prefix=] [--quiet] \"\n\t\t \"[--reference ] [--name ] [--depth ] \"\n\t\t \"--url --path \"),\n\t\tNULL\n\t};\n\n\targc = parse_options(argc, argv, prefix, module_clone_options,\n\t\t\t git_submodule_helper_usage, 0);\n\n\tif (argc || !url || !path || !*path)\n\t\tusage_with_options(git_submodule_helper_usage,\n\t\t\t\t module_clone_options);\n\n\tstrbuf_addf(&sb, \"%s/modules/%s\", get_git_dir(), name);\n\tsm_gitdir = absolute_pathdup(sb.buf);\n\tstrbuf_reset(&sb);\n\n\tif (!is_absolute_path(path)) {\n\t\tstrbuf_addf(&sb, \"%s/%s\", get_git_work_tree(), path);\n\t\tpath = strbuf_detach(&sb, NULL);\n\t} else\n\t\tpath = xstrdup(path);\n\n\tif (!file_exists(sm_gitdir)) {\n\t\tif (safe_create_leading_directories_const(sm_gitdir) < 0)\n\t\t\tdie(_(\"could not create directory '%s'\"), sm_gitdir);\n\n\t\tprepare_possible_alternates(name, &reference);\n\n\t\tif (clone_submodule(path, sm_gitdir, url, depth, &reference,\n\t\t\t\t quiet, progress))\n\t\t\tdie(_(\"clone of '%s' into submodule path '%s' failed\"),\n\t\t\t url, path);\n\t} else {\n\t\tif (safe_create_leading_directories_const(path) < 0)\n\t\t\tdie(_(\"could not create directory '%s'\"), path);\n\t\tstrbuf_addf(&sb, \"%s/index\", sm_gitdir);\n\t\tunlink_or_warn(sb.buf);\n\t\tstrbuf_reset(&sb);\n\t}\n\n\t/* Connect module worktree and git dir */\n\tconnect_work_tree_and_git_dir(path, sm_gitdir);\n\n\tp = git_pathdup_submodule(path, \"config\");\n\tif (!p)\n\t\tdie(_(\"could not get submodule directory for '%s'\"), path);\n\n\t/* setup alternateLocation and alternateErrorStrategy in the cloned submodule if needed */\n\tgit_config_get_string(\"submodule.alternateLocation\", &sm_alternate);\n\tif (sm_alternate)\n\t\tgit_config_set_in_file(p, \"submodule.alternateLocation\",\n\t\t\t\t\t sm_alternate);\n\tgit_config_get_string(\"submodule.alternateErrorStrategy\", &error_strategy);\n\tif (error_strategy)\n\t\tgit_config_set_in_file(p, \"submodule.alternateErrorStrategy\",\n\t\t\t\t\t error_strategy);\n\n\tfree(sm_alternate);\n\tfree(error_strategy);\n\n\tstrbuf_release(&sb);\n\tfree(sm_gitdir);\n\tfree(path);\n\tfree(p);\n\treturn 0;\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 lg3ff_init(struct hid_device *hid)\n{\n\tstruct hid_input *hidinput = list_entry(hid->inputs.next, struct hid_input, list);\n\tstruct input_dev *dev = hidinput->input;\n\tconst signed short *ff_bits = ff3_joystick_ac;\n\tint error;\n\tint i;\n\n\t/* Check that the report looks ok */\n\tif (!hid_validate_values(hid, HID_OUTPUT_REPORT, 0, 0, 35))\n\t\treturn -ENODEV;\n\n\t/* Assume single fixed device G940 */\n\tfor (i = 0; ff_bits[i] >= 0; i++)\n\t\tset_bit(ff_bits[i], dev->ffbit);\n\n\terror = input_ff_create_memless(dev, NULL, hid_lg3ff_play);\n\tif (error)\n\t\treturn error;\n\n\tif (test_bit(FF_AUTOCENTER, dev->ffbit))\n\t\tdev->ff->set_autocenter = hid_lg3ff_set_autocenter;\n\n\thid_info(hid, \"Force feedback for Logitech Flight System G940 by Gary Stein \\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 axff_init(struct hid_device *hid)\n{\n\tstruct axff_device *axff;\n\tstruct hid_report *report;\n\tstruct hid_input *hidinput = list_first_entry(&hid->inputs, struct hid_input, list);\n\tstruct list_head *report_list =&hid->report_enum[HID_OUTPUT_REPORT].report_list;\n\tstruct input_dev *dev = hidinput->input;\n\tint field_count = 0;\n\tint i, j;\n\tint error;\n\n\tif (list_empty(report_list)) {\n\t\thid_err(hid, \"no output reports found\\n\");\n\t\treturn -ENODEV;\n\t}\n\n\treport = list_first_entry(report_list, struct hid_report, list);\n\tfor (i = 0; i < report->maxfield; i++) {\n\t\tfor (j = 0; j < report->field[i]->report_count; j++) {\n\t\t\treport->field[i]->value[j] = 0x00;\n\t\t\tfield_count++;\n\t\t}\n\t}\n\n\tif (field_count < 4 && hid->product != 0xf705) {\n\t\thid_err(hid, \"not enough fields in the report: %d\\n\",\n\t\t\tfield_count);\n\t\treturn -ENODEV;\n\t}\n\n\taxff = kzalloc(sizeof(struct axff_device), GFP_KERNEL);\n\tif (!axff)\n\t\treturn -ENOMEM;\n\n\tset_bit(FF_RUMBLE, dev->ffbit);\n\n\terror = input_ff_create_memless(dev, axff, axff_play);\n\tif (error)\n\t\tgoto err_free_mem;\n\n\taxff->report = report;\n\thid_hw_request(hid, axff->report, HID_REQ_SET_REPORT);\n\n\thid_info(hid, \"Force Feedback for ACRUX game controllers by Sergei Kolzun \\n\");\n\n\treturn 0;\n\nerr_free_mem:\n\tkfree(axff);\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 fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){\n int rc = SQLITE_ERROR; /* Return Code */\n const char *zVal = (const char *)sqlite3_value_text(pVal);\n int nVal = sqlite3_value_bytes(pVal);\n\n if( !zVal ){\n return SQLITE_NOMEM;\n }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, \"optimize\", 8) ){\n rc = fts3DoOptimize(p, 0);\n }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, \"rebuild\", 7) ){\n rc = fts3DoRebuild(p);\n }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, \"integrity-check\", 15) ){\n rc = fts3DoIntegrityCheck(p);\n }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, \"merge=\", 6) ){\n rc = fts3DoIncrmerge(p, &zVal[6]);\n }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, \"automerge=\", 10) ){\n rc = fts3DoAutoincrmerge(p, &zVal[10]);\n#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)\n }else{\n int v;\n if( nVal>9 && 0==sqlite3_strnicmp(zVal, \"nodesize=\", 9) ){\n v = atoi(&zVal[9]);\n if( v>=24 && v<=p->nPgsz-35 ) p->nNodeSize = v;\n rc = SQLITE_OK;\n }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, \"maxpending=\", 9) ){\n v = atoi(&zVal[11]);\n if( v>=64 && v<=FTS3_MAX_PENDING_DATA ) p->nMaxPendingData = v;\n rc = SQLITE_OK;\n }else if( nVal>21 && 0==sqlite3_strnicmp(zVal,\"test-no-incr-doclist=\",21) ){\n p->bNoIncrDoclist = atoi(&zVal[21]);\n rc = SQLITE_OK;\n }\n#endif\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 fts3MsrBufferData(\n Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */\n char *pList,\n int nList\n){\n if( nList>pMsr->nBuffer ){\n char *pNew;\n pMsr->nBuffer = nList*2;\n pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);\n if( !pNew ) return SQLITE_NOMEM;\n pMsr->aBuffer = pNew;\n }\n\n memcpy(pMsr->aBuffer, pList, nList);\n return SQLITE_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Improved detection of corrupt shadow tables in FTS3. Enable the debugging\nspecial-inserts for FTS3 for both SQLITE_DEBUG and SQLITE_TEST.\n\nFossilOrigin-Name: 04b2873be5aedeb1c4325cf36c4b5d180f929a641caf1e3829c03778adb29c8e'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int renameColumnSelectCb(Walker *pWalker, Select *p){\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 iowarrior_disconnect(struct usb_interface *interface)\n{\n\tstruct iowarrior *dev;\n\tint minor;\n\n\tdev = usb_get_intfdata(interface);\n\tmutex_lock(&iowarrior_open_disc_lock);\n\tusb_set_intfdata(interface, NULL);\n\n\tminor = dev->minor;\n\n\t/* give back our minor */\n\tusb_deregister_dev(interface, &iowarrior_class);\n\n\tmutex_lock(&dev->mutex);\n\n\t/* prevent device read, write and ioctl */\n\tdev->present = 0;\n\n\tmutex_unlock(&dev->mutex);\n\tmutex_unlock(&iowarrior_open_disc_lock);\n\n\tif (dev->opened) {\n\t\t/* There is a process that holds a filedescriptor to the device ,\n\t\t so we only shutdown read-/write-ops going on.\n\t\t Deleting the device is postponed until close() was called.\n\t\t */\n\t\tusb_kill_urb(dev->int_in_urb);\n\t\twake_up_interruptible(&dev->read_wait);\n\t\twake_up_interruptible(&dev->write_wait);\n\t} else {\n\t\t/* no process is using the device, cleanup now */\n\t\tiowarrior_delete(dev);\n\t}\n\n\tdev_info(&interface->dev, \"I/O-Warror #%d now disconnected\\n\",\n\t\t minor - IOWARRIOR_MINOR_BASE);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'usb: iowarrior: fix deadlock on disconnect\n\nWe have to drop the mutex before we close() upon disconnect()\nas close() needs the lock. This is safe to do by dropping the\nmutex as intfdata is already set to NULL, so open() will fail.\n\nFixes: 03f36e885fc26 (\"USB: open disconnect race in iowarrior\")\nReported-by: syzbot+a64a382964bf6c71a9c0@syzkaller.appspotmail.com\nCc: stable \nSigned-off-by: Oliver Neukum \nLink: https://lore.kernel.org/r/20190808092728.23417-1-oneukum@suse.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 int lookupName(\n Parse *pParse, /* The parsing context */\n const char *zDb, /* Name of the database containing table, or NULL */\n const char *zTab, /* Name of table containing column, or NULL */\n const char *zCol, /* Name of the column. */\n NameContext *pNC, /* The name context used to resolve the name */\n Expr *pExpr /* Make this EXPR node point to the selected column */\n){\n int i, j; /* Loop counters */\n int cnt = 0; /* Number of matching column names */\n int cntTab = 0; /* Number of matching table names */\n int nSubquery = 0; /* How many levels of subquery */\n sqlite3 *db = pParse->db; /* The database connection */\n struct SrcList_item *pItem; /* Use for looping over pSrcList items */\n struct SrcList_item *pMatch = 0; /* The matching pSrcList item */\n NameContext *pTopNC = pNC; /* First namecontext in the list */\n Schema *pSchema = 0; /* Schema of the expression */\n int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */\n Table *pTab = 0; /* Table hold the row */\n Column *pCol; /* A column of pTab */\n\n assert( pNC ); /* the name context cannot be NULL. */\n assert( zCol ); /* The Z in X.Y.Z cannot be NULL */\n assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );\n\n /* Initialize the node to no-match */\n pExpr->iTable = -1;\n ExprSetVVAProperty(pExpr, EP_NoReduce);\n\n /* Translate the schema name in zDb into a pointer to the corresponding\n ** schema. If not found, pSchema will remain NULL and nothing will match\n ** resulting in an appropriate error message toward the end of this routine\n */\n if( zDb ){\n testcase( pNC->ncFlags & NC_PartIdx );\n testcase( pNC->ncFlags & NC_IsCheck );\n if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){\n /* Silently ignore database qualifiers inside CHECK constraints and\n ** partial indices. Do not raise errors because that might break\n ** legacy and because it does not hurt anything to just ignore the\n ** database name. */\n zDb = 0;\n }else{\n for(i=0; inDb; i++){\n assert( db->aDb[i].zDbSName );\n if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){\n pSchema = db->aDb[i].pSchema;\n break;\n }\n }\n }\n }\n\n /* Start at the inner-most context and move outward until a match is found */\n assert( pNC && cnt==0 );\n do{\n ExprList *pEList;\n SrcList *pSrcList = pNC->pSrcList;\n\n if( pSrcList ){\n for(i=0, pItem=pSrcList->a; inSrc; i++, pItem++){\n pTab = pItem->pTab;\n assert( pTab!=0 && pTab->zName!=0 );\n assert( pTab->nCol>0 );\n if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){\n int hit = 0;\n pEList = pItem->pSelect->pEList;\n for(j=0; jnExpr; j++){\n if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){\n cnt++;\n cntTab = 2;\n pMatch = pItem;\n pExpr->iColumn = j;\n hit = 1;\n }\n }\n if( hit || zTab==0 ) continue;\n }\n if( zDb && pTab->pSchema!=pSchema ){\n continue;\n }\n if( zTab ){\n const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;\n assert( zTabName!=0 );\n if( sqlite3StrICmp(zTabName, zTab)!=0 ){\n continue;\n }\n if( IN_RENAME_OBJECT && pItem->zAlias ){\n sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);\n }\n }\n if( 0==(cntTab++) ){\n pMatch = pItem;\n }\n for(j=0, pCol=pTab->aCol; jnCol; j++, pCol++){\n if( sqlite3StrICmp(pCol->zName, zCol)==0 ){\n /* If there has been exactly one prior match and this match\n ** is for the right-hand table of a NATURAL JOIN or is in a \n ** USING clause, then skip this match.\n */\n if( cnt==1 ){\n if( pItem->fg.jointype & JT_NATURAL ) continue;\n if( nameInUsingClause(pItem->pUsing, zCol) ) continue;\n }\n cnt++;\n pMatch = pItem;\n /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */\n pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;\n break;\n }\n }\n }\n if( pMatch ){\n pExpr->iTable = pMatch->iCursor;\n pExpr->y.pTab = pMatch->pTab;\n /* RIGHT JOIN not (yet) supported */\n assert( (pMatch->fg.jointype & JT_RIGHT)==0 );\n if( (pMatch->fg.jointype & JT_LEFT)!=0 ){\n ExprSetProperty(pExpr, EP_CanBeNull);\n }\n pSchema = pExpr->y.pTab->pSchema;\n }\n } /* if( pSrcList ) */\n\n#if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)\n /* If we have not already resolved the name, then maybe \n ** it is a new.* or old.* trigger argument reference. Or\n ** maybe it is an excluded.* from an upsert.\n */\n if( zDb==0 && zTab!=0 && cntTab==0 ){\n pTab = 0;\n#ifndef SQLITE_OMIT_TRIGGER\n if( pParse->pTriggerTab!=0 ){\n int op = pParse->eTriggerOp;\n assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );\n if( op!=TK_DELETE && sqlite3StrICmp(\"new\",zTab) == 0 ){\n pExpr->iTable = 1;\n pTab = pParse->pTriggerTab;\n }else if( op!=TK_INSERT && sqlite3StrICmp(\"old\",zTab)==0 ){\n pExpr->iTable = 0;\n pTab = pParse->pTriggerTab;\n }\n }\n#endif /* SQLITE_OMIT_TRIGGER */\n#ifndef SQLITE_OMIT_UPSERT\n if( (pNC->ncFlags & NC_UUpsert)!=0 ){\n Upsert *pUpsert = pNC->uNC.pUpsert;\n if( pUpsert && sqlite3StrICmp(\"excluded\",zTab)==0 ){\n pTab = pUpsert->pUpsertSrc->a[0].pTab;\n pExpr->iTable = 2;\n }\n }\n#endif /* SQLITE_OMIT_UPSERT */\n\n if( pTab ){ \n int iCol;\n pSchema = pTab->pSchema;\n cntTab++;\n for(iCol=0, pCol=pTab->aCol; iColnCol; iCol++, pCol++){\n if( sqlite3StrICmp(pCol->zName, zCol)==0 ){\n if( iCol==pTab->iPKey ){\n iCol = -1;\n }\n break;\n }\n }\n if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){\n /* IMP: R-51414-32910 */\n iCol = -1;\n }\n if( iColnCol ){\n cnt++;\n#ifndef SQLITE_OMIT_UPSERT\n if( pExpr->iTable==2 ){\n testcase( iCol==(-1) );\n if( IN_RENAME_OBJECT ){\n pExpr->iColumn = iCol;\n pExpr->y.pTab = pTab;\n eNewExprOp = TK_COLUMN;\n }else{\n pExpr->iTable = pNC->uNC.pUpsert->regData + iCol;\n eNewExprOp = TK_REGISTER;\n ExprSetProperty(pExpr, EP_Alias);\n }\n }else\n#endif /* SQLITE_OMIT_UPSERT */\n {\n#ifndef SQLITE_OMIT_TRIGGER\n if( iCol<0 ){\n pExpr->affExpr = SQLITE_AFF_INTEGER;\n }else if( pExpr->iTable==0 ){\n testcase( iCol==31 );\n testcase( iCol==32 );\n pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<y.pTab = pTab;\n pExpr->iColumn = (i16)iCol;\n eNewExprOp = TK_TRIGGER;\n#endif /* SQLITE_OMIT_TRIGGER */\n }\n }\n }\n }\n#endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */\n\n /*\n ** Perhaps the name is a reference to the ROWID\n */\n if( cnt==0\n && cntTab==1\n && pMatch\n && (pNC->ncFlags & (NC_IdxExpr|NC_GenCol))==0\n && sqlite3IsRowid(zCol)\n && VisibleRowid(pMatch->pTab)\n ){\n cnt = 1;\n pExpr->iColumn = -1;\n pExpr->affExpr = SQLITE_AFF_INTEGER;\n }\n\n /*\n ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z\n ** might refer to an result-set alias. This happens, for example, when\n ** we are resolving names in the WHERE clause of the following command:\n **\n ** SELECT a+b AS x FROM table WHERE x<10;\n **\n ** In cases like this, replace pExpr with a copy of the expression that\n ** forms the result set entry (\"a+b\" in the example) and return immediately.\n ** Note that the expression in the result set should have already been\n ** resolved by the time the WHERE clause is resolved.\n **\n ** The ability to use an output result-set column in the WHERE, GROUP BY,\n ** or HAVING clauses, or as part of a larger expression in the ORDER BY\n ** clause is not standard SQL. This is a (goofy) SQLite extension, that\n ** is supported for backwards compatibility only. Hence, we issue a warning\n ** on sqlite3_log() whenever the capability is used.\n */\n if( (pNC->ncFlags & NC_UEList)!=0\n && cnt==0\n && zTab==0\n ){\n pEList = pNC->uNC.pEList;\n assert( pEList!=0 );\n for(j=0; jnExpr; j++){\n char *zAs = pEList->a[j].zName;\n if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){\n Expr *pOrig;\n assert( pExpr->pLeft==0 && pExpr->pRight==0 );\n assert( pExpr->x.pList==0 );\n assert( pExpr->x.pSelect==0 );\n pOrig = pEList->a[j].pExpr;\n if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){\n sqlite3ErrorMsg(pParse, \"misuse of aliased aggregate %s\", zAs);\n return WRC_Abort;\n }\n if( (pNC->ncFlags&NC_AllowWin)==0 && ExprHasProperty(pOrig, EP_Win) ){\n sqlite3ErrorMsg(pParse, \"misuse of aliased window function %s\",zAs);\n return WRC_Abort;\n }\n if( sqlite3ExprVectorSize(pOrig)!=1 ){\n sqlite3ErrorMsg(pParse, \"row value misused\");\n return WRC_Abort;\n }\n resolveAlias(pParse, pEList, j, pExpr, \"\", nSubquery);\n cnt = 1;\n pMatch = 0;\n assert( zTab==0 && zDb==0 );\n if( IN_RENAME_OBJECT ){\n sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);\n }\n goto lookupname_end;\n }\n } \n }\n\n /* Advance to the next name context. The loop will exit when either\n ** we have a match (cnt>0) or when we run out of name contexts.\n */\n if( cnt ) break;\n pNC = pNC->pNext;\n nSubquery++;\n }while( pNC );\n\n\n /*\n ** If X and Y are NULL (in other words if only the column name Z is\n ** supplied) and the value of Z is enclosed in double-quotes, then\n ** Z is a string literal if it doesn't match any column names. In that\n ** case, we need to return right away and not make any changes to\n ** pExpr.\n **\n ** Because no reference was made to outer contexts, the pNC->nRef\n ** fields are not changed in any context.\n */\n if( cnt==0 && zTab==0 ){\n assert( pExpr->op==TK_ID );\n if( ExprHasProperty(pExpr,EP_DblQuoted)\n && areDoubleQuotedStringsEnabled(db, pTopNC)\n ){\n /* If a double-quoted identifier does not match any known column name,\n ** then treat it as a string.\n **\n ** This hack was added in the early days of SQLite in a misguided attempt\n ** to be compatible with MySQL 3.x, which used double-quotes for strings.\n ** I now sorely regret putting in this hack. The effect of this hack is\n ** that misspelled identifier names are silently converted into strings\n ** rather than causing an error, to the frustration of countless\n ** programmers. To all those frustrated programmers, my apologies.\n **\n ** Someday, I hope to get rid of this hack. Unfortunately there is\n ** a huge amount of legacy SQL that uses it. So for now, we just\n ** issue a warning.\n */\n sqlite3_log(SQLITE_WARNING,\n \"double-quoted string literal: \\\"%w\\\"\", zCol);\n#ifdef SQLITE_ENABLE_NORMALIZE\n sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol);\n#endif\n pExpr->op = TK_STRING;\n pExpr->y.pTab = 0;\n return WRC_Prune;\n }\n if( sqlite3ExprIdToTrueFalse(pExpr) ){\n return WRC_Prune;\n }\n }\n\n /*\n ** cnt==0 means there was not match. cnt>1 means there were two or\n ** more matches. Either way, we have an error.\n */\n if( cnt!=1 ){\n const char *zErr;\n zErr = cnt==0 ? \"no such column\" : \"ambiguous column name\";\n if( zDb ){\n sqlite3ErrorMsg(pParse, \"%s: %s.%s.%s\", zErr, zDb, zTab, zCol);\n }else if( zTab ){\n sqlite3ErrorMsg(pParse, \"%s: %s.%s\", zErr, zTab, zCol);\n }else{\n sqlite3ErrorMsg(pParse, \"%s: %s\", zErr, zCol);\n }\n pParse->checkSchema = 1;\n pTopNC->nErr++;\n }\n\n /* If a column from a table in pSrcList is referenced, then record\n ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes\n ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the\n ** column number is greater than the number of bits in the bitmask\n ** then set the high-order bit of the bitmask.\n */\n if( pExpr->iColumn>=0 && pMatch!=0 ){\n int n = pExpr->iColumn;\n testcase( n==BMS-1 );\n if( n>=BMS ){\n n = BMS-1;\n }\n assert( pMatch->iCursor==pExpr->iTable );\n pMatch->colUsed |= ((Bitmask)1)<pLeft);\n pExpr->pLeft = 0;\n sqlite3ExprDelete(db, pExpr->pRight);\n pExpr->pRight = 0;\n pExpr->op = eNewExprOp;\n ExprSetProperty(pExpr, EP_Leaf);\nlookupname_end:\n if( cnt==1 ){\n assert( pNC!=0 );\n if( !ExprHasProperty(pExpr, EP_Alias) ){\n sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);\n }\n /* Increment the nRef value on all name contexts from TopNC up to\n ** the point where the name matched. */\n for(;;){\n assert( pTopNC!=0 );\n pTopNC->nRef++;\n if( pTopNC==pNC ) break;\n pTopNC = pTopNC->pNext;\n }\n return WRC_Prune;\n } else {\n return WRC_Abort;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-703', 'CWE-681'], 'message': 'Whenever a generated column is used, assume that all columns are used.\n\nFossilOrigin-Name: 6601da58032d18ae00b466c0f2077fb2b1ecd84225b56e1787724bea478eedc9'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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_curve(int c) {\n spiro_cp spiro[16];\n int nextknot[17];\n double d[5];\n spiro_seg *segs = NULL;\n bezctx *bc;\n rs_check_vals *rsp;\n int i,j,done;\n\n /* Load sample data so that we can see if library is callable */\n load_test_curve(spiro,nextknot,c);\n\n d[0] = 1.; d[1] = d[1] = 0.;\n#if defined(DO_CALL_TEST20)\n /* check if spiro values are reversed correctly on input path */\n printf(\"---\\ntesting spiroreverse() using data=path%d[].\\n\",c);\n if ( (spiroreverse(spiro,cl[c])) ) {\n\tfprintf(stderr,\"error with spiroreverse() using data=path%d[].\\n\",c);\n\treturn -1;\n }\n /* just do a visual check to verify types and points look ok. */\n /* NOTE: spiro[] is NOT replaced if unable to reverse values. */\n for (i=0; i < cl[c]; i++) {\n\tprintf(\" reversed %d: ty=%c, x=%g, y=%g\\n\", i,spiro[i].ty,spiro[i].x,spiro[i].y);\n }\n#else\n#if defined(DO_CALL_TEST14) || defined(DO_CALL_TEST15) || defined(DO_CALL_TEST16) || defined(DO_CALL_TEST17) || defined(DO_CALL_TEST18) || defined(DO_CALL_TEST19)\n#if defined(DO_CALL_TEST16) || defined(DO_CALL_TEST17) || defined(DO_CALL_TEST18) || defined(DO_CALL_TEST19)\n /* run_spiro0 with various paths to test a simple arc output. */\n d[0] = -1.;\n printf(\"---\\ntesting run_spiro0(q) using data=path%d[].\\n\",c);\n if ( (segs=run_spiro0(spiro,d,SPIRO_ARC_MAYBE,cl[c]))==0 ) {\n\tfprintf(stderr,\"error with run_spiro0(q) using data=path%d[].\\n\",c);\n\treturn -1;\n }\n#else\n /* Do run_spiro0 instead (these tests are far from -0.5..+0.5 */\n d[0] = -1.;\n printf(\"---\\ntesting run_spiro0() using data=path%d[].\\n\",c);\n if ( (segs=run_spiro0(spiro,d,0,cl[c]))==0 ) {\n\tfprintf(stderr,\"error with run_spiro0() using data=path%d[].\\n\",c);\n\treturn -1;\n }\n#endif\n#else\n /* Check if run_spiro works okay (try backwards compatiblity) */\n printf(\"---\\ntesting run_spiro() using data=path%d[].\\n\",c);\n if ( (segs=run_spiro(spiro,cl[c]))==0 ) {\n\tfprintf(stderr,\"error with run_spiro() using data=path%d[].\\n\",c);\n\treturn -1;\n }\n#endif\n\n /* Load pointer to verification data to ensure it works right */\n if ( c==0 )\t rsp = verify_rs0;\n else if ( c==1 ) rsp = verify_rs1;\n else if ( c==2 ) rsp = verify_rs2;\n /* else if ( c==3 ) rsp = NULL; expecting failure to converge */\n else if ( c==4 ) rsp = verify_rs4;\n else if ( c==5 ) rsp = verify_rs5;\n else if ( c==6 ) rsp = verify_rs5; /* same angles used for #6 */\n else if ( c==7 ) rsp = verify_rs7; /* stop curve with ah code */\n else if ( c==8 ) rsp = verify_rs8;\n else if ( c==9 ) rsp = verify_rs9;\n else if ( c==10 ) rsp = verify_rs10; /* start curve using ah. */\n else if ( c==11 ) rsp = verify_rs11;\n else if ( c==12 ) rsp = verify_rs7; /* test #12 uses path7[]. */\n else if ( c==13 ) rsp = verify_rs13; /* almost same as path11 */\n else if ( c==14 ) rsp = verify_rs14; /* very large path9 copy */\n else if ( c==15 ) rsp = verify_rs15; /* sub-atomic path9 copy */\n else if ( c==16 ) rsp = verify_rs4; /* path4 arc curve output */\n else if ( c==17 ) rsp = verify_rs4; /* path4 arc curve closed */\n else if ( c==18 ) rsp = verify_rs2; /* trying many iterations */\n else\t rsp = verify_rs0; /* long list, arc output. */\n\n /* Quick visual check shows X,Y knots match with each pathN[] */\n for (i=j=0; i < cl[c]-1; i++,j++) {\n\tif ( spiro[i].ty == 'h' ) {\n\t --j;\n\t printf(\"curve %d ctrl %d t=%c x=%f y=%f (handle)\\n\", \\\n\t c,j,segs[i].ty,spiro[i].x,spiro[i].y);\n\t}\n\tprintf(\"curve %d line %d t=%c x=%f y=%f bend=%f ch=%f th=%f \",c,j, \\\n\t segs[i].ty,segs[i].x,segs[i].y,segs[i].bend_th,segs[i].seg_ch,segs[i].seg_th);\n\t/* Let computer verify that run_spiro() data is PASS/FAIL */\n\t/* Tests including ah data more complicated to verify xy, */\n\t/* therefore, skip testing xy for call_tests shown below. */\n\tif ( (segs[i].ty != spiro[i].ty) ||\n#if defined(DO_CALL_TEST14) || defined(DO_CALL_TEST15) || defined(DO_CALL_TEST16) || defined(DO_CALL_TEST17) || defined(DO_CALL_TEST18) || defined(DO_CALL_TEST19)\n#if defined(DO_CALL_TEST14) || defined(DO_CALL_TEST16) || defined(DO_CALL_TEST17) || defined(DO_CALL_TEST18) || defined(DO_CALL_TEST19)\n\t (fabs((segs[i].x * d[0] + d[1]) - spiro[i].x) > 1e5) ||\n\t (fabs((segs[i].y * d[0] + d[2]) - spiro[i].y) > 1e5) ||\n\t (fabs(segs[i].seg_ch * d[0] - rsp[i].ch) > 1e5) ||\n#else\n\t (fabs((segs[i].x * d[0] + d[1]) - spiro[i].x) > 1e-47) ||\n\t (fabs((segs[i].y * d[0] + d[2]) - spiro[i].y) > 1e-47) ||\n\t (fabs(segs[i].seg_ch * d[0] - rsp[i].ch) > 1e-47) ||\n#endif\n#else\n#if !defined(DO_CALL_TEST6) && !defined(DO_CALL_TEST7) && !defined(DO_CALL_TEST8) && !defined(DO_CALL_TEST10) && !defined(DO_CALL_TEST11) && !defined(DO_CALL_TEST12) && !defined(DO_CALL_TEST13)\n\t (fabs(segs[i].x - spiro[i].x) > 1e-5) ||\n\t (fabs(segs[i].y - spiro[i].y) > 1e-5) ||\n#endif\n\t (fabs(segs[i].seg_ch - rsp[i].ch) > 1e-5) ||\n#endif\n\t (fabs(segs[i].bend_th - rsp[i].b) > 1e-5) ||\n\t (fabs(segs[i].seg_th - rsp[i].th) > 1e-5) ) {\n\t printf(\"FAIL\\n\");\n\t fprintf(stderr,\"Error found with run_spiro() data. Results are not the same.\\n\");\n\t fprintf(stderr,\"expected line %d t=%c x=%f y=%f bend=%f ch=%f th=%f\\n\", j, \\\n\t spiro[i].ty,spiro[i].x,spiro[i].y,rsp[i].b,rsp[i].ch,rsp[i].th);\n\t free(segs);\n\t return -2;\n\t} else\n\t printf(\"PASS\\n\");\n }\n printf(\"curve %d \",c);\n if ( spiro[i].ty == '}' || spiro[i].ty == 'z' )\n\tprintf(\"stop %d t=%c x=%f y=%f\\n\",j,segs[i].ty,segs[i].x,segs[i].y);\n else\n\tprintf(\"line %d t=%c x=%f y=%f bend=%f ch=%f th=%f\\n\", j,segs[i].ty, \\\n\t segs[i].x,segs[i].y,segs[i].bend_th,segs[i].seg_ch,segs[i].seg_th);\n\n /* Quick visual check shows X,Y knots match with each pathN[] */\n printf(\"---\\ntesting spiro_to_bpath() using data from run_spiro(data=path%d[],len=%d).\\n\",c,cl[c]);\n bc = new_bezctx_test();\n#if defined(DO_CALL_TEST14) || defined(DO_CALL_TEST15) || defined(DO_CALL_TEST16) || defined(DO_CALL_TEST17) || defined(DO_CALL_TEST18) || defined(DO_CALL_TEST19)\n#if defined(DO_CALL_TEST16) || defined(DO_CALL_TEST17) || defined(DO_CALL_TEST18) || defined(DO_CALL_TEST19)\n spiro_to_bpath0(spiro,segs,d,SPIRO_ARC_MAYBE,cl[c],bc);\n#else\n spiro_to_bpath0(spiro,segs,d,0,cl[c],bc);\n#endif\n#else\n spiro_to_bpath(segs,cl[c],bc);\n#endif\n free(segs);\n#endif\n\n#if !defined(DO_CALL_TEST20)\n#if defined(DO_CALL_TEST14) || defined(DO_CALL_TEST15) || defined(DO_CALL_TEST16) || defined(DO_CALL_TEST17) || defined(DO_CALL_TEST18) || defined(DO_CALL_TEST19)\n#if defined(DO_CALL_TEST14) || defined(DO_CALL_TEST15) || defined(DO_CALL_TEST16) || defined(DO_CALL_TEST17)\n /* Now verify we also have simple arc output too */\n printf(\"---\\ntesting SpiroCPsToBezier2() using data=path%d[].\\n\",c);\n if ( SpiroCPsToBezier2(spiro,cl[c],SPIRO_ARC_MAYBE,co[c],bc)!=1 ) {\n\tfprintf(stderr,\"error with SpiroCPsToBezier2() using data=path%d[].\\n\",c);\n\treturn -7;\n }\n#endif\n#if defined(DO_CALL_TEST18) || defined(DO_CALL_TEST19)\n printf(\"---\\ntesting TaggedSpiroCPsToBezier2() using data=path%d[].\\n\",c);\n if ( TaggedSpiroCPsToBezier2(spiro,SPIRO_ARC_MAYBE,bc)!=1 ) {\n\tfprintf(stderr,\"error with TaggedSpiroCPsToBezier2() using data=path%d[].\\n\",c);\n\treturn -8;\n }\n#endif\n#else\n#if !defined(DO_CALL_TEST4) && !defined(DO_CALL_TEST6) && !defined(DO_CALL_TEST7) && !defined(DO_CALL_TEST8) && !defined(DO_CALL_TEST9) && !defined(DO_CALL_TEST10) && !defined(DO_CALL_TEST11)\n /* Check if TaggedSpiroCPsToBezier0() works okay */\n printf(\"---\\ntesting TaggedSpiroCPsToBezier0() using data=path%d[].\\n\",c);\n if ( TaggedSpiroCPsToBezier0(spiro,bc)!=1 ) {\n\tfprintf(stderr,\"error with TaggedSpiroCPsToBezier0() using data=path%d[].\\n\",c);\n\treturn -3;\n }\n#endif\n\n#if !defined(DO_CALL_TEST12)\n /* Check if SpiroCPsToBezier0() works okay */\n printf(\"---\\ntesting SpiroCPsToBezier0() using data=path%d[].\\n\",c);\n if ( SpiroCPsToBezier0(spiro,cl[c],co[c],bc)!=1 ) {\n\tfprintf(stderr,\"error with SpiroCPsToBezier0() using data=path%d[].\\n\",c);\n\treturn -4;\n }\n#endif\n\n#if !defined(DO_CALL_TEST4) && !defined(DO_CALL_TEST6) && !defined(DO_CALL_TEST7) && !defined(DO_CALL_TEST8) && !defined(DO_CALL_TEST9) && !defined(DO_CALL_TEST10) && !defined(DO_CALL_TEST11)\n /* Check if TaggedSpiroCPsToBezier1() works okay */\n printf(\"---\\ntesting TaggedSpiroCPsToBezier1() using data=path%d[].\\n\",c);\n TaggedSpiroCPsToBezier1(spiro,bc,&done);\n if ( done!=1 ) {\n\tfprintf(stderr,\"error with TaggedSpiroCPsToBezier1() using data=path%d[].\\n\",c);\n\treturn -5;\n }\n#endif\n\n#if !defined(DO_CALL_TEST12)\n /* Check if SpiroCPsToBezier1() works okay */\n printf(\"---\\ntesting SpiroCPsToBezier1() using data=path%d[].\\n\",c);\n SpiroCPsToBezier1(spiro,cl[c],co[c],bc,&done);\n if ( done!=1 ) {\n\tfprintf(stderr,\"error with SpiroCPsToBezier1() using data=path%d[].\\n\",c);\n\treturn -6;\n }\n#endif\n#endif\n\n#else\n /* We already visually checked output for spiroreverse above. */\n /* Some reversed paths (above) will fail (like path20), so we */\n /* reverse the reversed spiro path so we can use current test */\n /* functions & values (so that this actually tests something) */\n if (c == 20 || c == 21) {\n\t/* Check if SpiroCPsToBezier2() works okay */\n\tprintf(\"---\\ntesting SpiroCPsToBezier2(reverse) using data=path%d[].\\n\",c);\n\tif ( SpiroCPsToBezier2(spiro,cl[c],SPIRO_REVERSE_SRC,co[c],bc)!=1 ) {\n\t fprintf(stderr,\"error with SpiroCPsToBezier2(reverse) using data=path%d[].\\n\",c);\n\t return -9;\n\t}\n } else { /* c==22 || c==23 || c==24 */\n\t/* Check if TaggedSpiroCPsToBezier2() works okay */\n\tprintf(\"---\\ntesting TaggedSpiroCPsToBezier2(reverse) using data=path%d[].\\n\",c);\n\tif ( TaggedSpiroCPsToBezier2(spiro,SPIRO_REVERSE_SRC,bc)!=1 ) {\n\t fprintf(stderr,\"error with TaggedSpiroCPsToBezier2(reverse) using data=path%d[].\\n\",c);\n\t return -10;\n\t}\n }\n#endif\n\n free(bc);\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2019-19847, Stack-based buffer overflow in the spiro_to_bpath0()\n\nFrederic Cambus (@fcambus) discovered a bug in call-test.c using:\n./configure CFLAGS=\"-fsanitize=address\"\nmake\n./tests/call-test[14,15,16,17,18,19]\nFredrick Brennan (@ctrlcctrlv) provided bugfix. See issue #21'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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 vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){\n assert( p->nOp>0 || p->aOp==0 );\n assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );\n if( p->nOp ){\n assert( p->aOp );\n sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);\n p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);\n }\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: TEST(DecodeAPI, Vp9PeekSI) {\n const vpx_codec_iface_t *const codec = &vpx_codec_vp9_dx_algo;\n // The first 9 bytes are valid and the rest of the bytes are made up. Until\n // size 10, this should return VPX_CODEC_UNSUP_BITSTREAM and after that it\n // should return VPX_CODEC_CORRUPT_FRAME.\n const uint8_t data[32] = {\n 0x85, 0xa4, 0xc1, 0xa1, 0x38, 0x81, 0xa3, 0x49, 0x83, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n };\n\n for (uint32_t data_sz = 1; data_sz <= 32; ++data_sz) {\n // Verify behavior of vpx_codec_decode. vpx_codec_decode doesn't even get\n // to decoder_peek_si_internal on frames of size < 8.\n if (data_sz >= 8) {\n vpx_codec_ctx_t dec;\n EXPECT_EQ(VPX_CODEC_OK, vpx_codec_dec_init(&dec, codec, NULL, 0));\n EXPECT_EQ(\n (data_sz < 10) ? VPX_CODEC_UNSUP_BITSTREAM : VPX_CODEC_CORRUPT_FRAME,\n vpx_codec_decode(&dec, data, data_sz, NULL, 0));\n vpx_codec_iter_t iter = NULL;\n EXPECT_EQ(NULL, vpx_codec_get_frame(&dec, &iter));\n EXPECT_EQ(VPX_CODEC_OK, vpx_codec_destroy(&dec));\n }\n\n // Verify behavior of vpx_codec_peek_stream_info.\n vpx_codec_stream_info_t si;\n si.sz = sizeof(si);\n EXPECT_EQ((data_sz < 10) ? VPX_CODEC_UNSUP_BITSTREAM : VPX_CODEC_OK,\n vpx_codec_peek_stream_info(codec, data, data_sz, &si));\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'vp9: fix OOB read in decoder_peek_si_internal\n\nProfile 1 or 3 bitstreams may require 11 bytes for the header in the\nintra-only case.\n\nAdditionally add a check on the bit reader's error handler callback to\nensure it's non-NULL before calling to avoid future regressions.\n\nThis has existed since at least (pre-1.4.0):\n09bf1d61c Changes hdr for profiles > 1 for intraonly frames\n\nBUG=webm:1543\n\nChange-Id: I23901e6e3a219170e8ea9efecc42af0be2e5c378'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int MkvReader::Read(long long offset, long len, unsigned char* buffer) {\n if (m_file == NULL)\n return -1;\n\n if (offset < 0)\n return -1;\n\n if (len < 0)\n return -1;\n\n if (len == 0)\n return 0;\n\n if (offset >= m_length)\n return -1;\n\n#ifdef _MSC_VER\n const int status = _fseeki64(m_file, offset, SEEK_SET);\n\n if (status)\n return -1; // error\n#else\n fseeko(m_file, static_cast(offset), SEEK_SET);\n#endif\n\n const size_t size = fread(buffer, 1, len, m_file);\n\n if (size < size_t(len))\n return -1; // error\n\n return 0; // success\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'update libwebm to libwebm-1.0.0.27-352-g6ab9fcf\n\nhttps://chromium.googlesource.com/webm/libwebm/+log/af81f26..6ab9fcf\n\nChange-Id: I9d56e1fbaba9b96404b4fbabefddc1a85b79c25d'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: exif_data_load_data (ExifData *data, const unsigned char *d_orig,\n\t\t unsigned int ds)\n{\n\tunsigned int l;\n\tExifLong offset;\n\tExifShort n;\n\tconst unsigned char *d = d_orig;\n\tunsigned int len, fullds;\n\n\tif (!data || !data->priv || !d || !ds)\n\t\treturn;\n\n\texif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \"ExifData\",\n\t\t \"Parsing %i byte(s) EXIF data...\\n\", ds);\n\n\t/*\n\t * It can be that the data starts with the EXIF header. If it does\n\t * not, search the EXIF marker.\n\t */\n\tif (ds < 6) {\n\t\tLOG_TOO_SMALL;\n\t\treturn;\n\t}\n\tif (!memcmp (d, ExifHeader, 6)) {\n\t\texif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \"ExifData\",\n\t\t\t \"Found EXIF header at start.\");\n\t} else {\n\t\twhile (ds >= 3) {\n\t\t\twhile (ds && (d[0] == 0xff)) {\n\t\t\t\td++;\n\t\t\t\tds--;\n\t\t\t}\n\n\t\t\t/* JPEG_MARKER_SOI */\n\t\t\tif (ds && d[0] == JPEG_MARKER_SOI) {\n\t\t\t\td++;\n\t\t\t\tds--;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/* JPEG_MARKER_APP1 */\n\t\t\tif (ds && d[0] == JPEG_MARKER_APP1)\n\t\t\t\tbreak;\n\n\t\t\t/* Skip irrelevant APP markers. The branch for APP1 must come before this,\n\t\t\t otherwise this code block will cause APP1 to be skipped. This code path\n\t\t\t is only relevant for files that are nonconformant to the EXIF\n\t\t\t specification. For conformant files, the APP1 code path above will be\n\t\t\t taken. */\n\t\t\tif (ds >= 3 && d[0] >= 0xe0 && d[0] <= 0xef) { /* JPEG_MARKER_APPn */\n\t\t\t\td++;\n\t\t\t\tds--;\n\t\t\t\tl = (d[0] << 8) | d[1];\n\t\t\t\tif (l > ds)\n\t\t\t\t\treturn;\n\t\t\t\td += l;\n\t\t\t\tds -= l;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/* Unknown marker or data. Give up. */\n\t\t\texif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t\t \"ExifData\", _(\"EXIF marker not found.\"));\n\t\t\treturn;\n\t\t}\n\t\tif (ds < 3) {\n\t\t\tLOG_TOO_SMALL;\n\t\t\treturn;\n\t\t}\n\t\td++;\n\t\tds--;\n\t\tlen = (d[0] << 8) | d[1];\n\t\texif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \"ExifData\",\n\t\t\t \"We have to deal with %i byte(s) of EXIF data.\",\n\t\t\t len);\n\t\td += 2;\n\t\tds -= 2;\n\t}\n\n\t/*\n\t * Verify the exif header\n\t * (offset 2, length 6).\n\t */\n\tif (ds < 6) {\n\t\tLOG_TOO_SMALL;\n\t\treturn;\n\t}\n\tif (memcmp (d, ExifHeader, 6)) {\n\t\texif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t \"ExifData\", _(\"EXIF header not found.\"));\n\t\treturn;\n\t}\n\n\texif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \"ExifData\",\n\t\t \"Found EXIF header.\");\n\n\t/* Sanity check the data length */\n\tif (ds < 14)\n\t\treturn;\n\n\t/* The JPEG APP1 section can be no longer than 64 KiB (including a\n\t 16-bit length), so cap the data length to protect against overflow\n\t in future offset calculations */\n\tfullds = ds;\n\tif (ds > 0xfffe)\n\t\tds = 0xfffe;\n\n\t/* Byte order (offset 6, length 2) */\n\tif (!memcmp (d + 6, \"II\", 2))\n\t\tdata->priv->order = EXIF_BYTE_ORDER_INTEL;\n\telse if (!memcmp (d + 6, \"MM\", 2))\n\t\tdata->priv->order = EXIF_BYTE_ORDER_MOTOROLA;\n\telse {\n\t\texif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t \"ExifData\", _(\"Unknown encoding.\"));\n\t\treturn;\n\t}\n\n\t/* Fixed value */\n\tif (exif_get_short (d + 8, data->priv->order) != 0x002a)\n\t\treturn;\n\n\t/* IFD 0 offset */\n\toffset = exif_get_long (d + 10, data->priv->order);\n\texif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \"ExifData\", \n\t\t \"IFD 0 at %i.\", (int) offset);\n\n\t/* Sanity check the offset, being careful about overflow */\n\tif (offset > ds || offset + 6 + 2 > ds)\n\t\treturn;\n\n\t/* Parse the actual exif data (usually offset 14 from start) */\n\texif_data_load_data_content (data, EXIF_IFD_0, d + 6, ds - 6, offset, 0);\n\n\t/* IFD 1 offset */\n\tn = exif_get_short (d + 6 + offset, data->priv->order);\n\tif (offset + 6 + 2 + 12 * n + 4 > ds)\n\t\treturn;\n\n\toffset = exif_get_long (d + 6 + offset + 2 + 12 * n, data->priv->order);\n\tif (offset) {\n\t\texif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \"ExifData\",\n\t\t\t \"IFD 1 at %i.\", (int) offset);\n\n\t\t/* Sanity check. */\n\t\tif (offset > ds || offset + 6 > ds) {\n\t\t\texif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t\t \"ExifData\", \"Bogus offset of IFD1.\");\n\t\t} else {\n\t\t exif_data_load_data_content (data, EXIF_IFD_1, d + 6, ds - 6, offset, 0);\n\t\t}\n\t}\n\n\t/*\n\t * If we got an EXIF_TAG_MAKER_NOTE, try to interpret it. Some\n\t * cameras use pointers in the maker note tag that point to the\n\t * space between IFDs. Here is the only place where we have access\n\t * to that data.\n\t */\n\tinterpret_maker_note(data, d, fullds);\n\n\t/* Fixup tags if requested */\n\tif (data->priv->options & EXIF_DATA_OPTION_FOLLOW_SPECIFICATION)\n\t\texif_data_fix (data);\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: ImagingSgiRleDecode(Imaging im, ImagingCodecState state,\n\t\t UINT8* buf, Py_ssize_t bytes)\n{\n UINT8 *ptr;\n SGISTATE *c;\n int err = 0;\n\n /* Get all data from File descriptor */\n c = (SGISTATE*)state->context;\n _imaging_seek_pyFd(state->fd, 0L, SEEK_END);\n c->bufsize = _imaging_tell_pyFd(state->fd);\n c->bufsize -= SGI_HEADER_SIZE;\n ptr = malloc(sizeof(UINT8) * c->bufsize);\n if (!ptr) {\n return IMAGING_CODEC_MEMORY;\n }\n _imaging_seek_pyFd(state->fd, SGI_HEADER_SIZE, SEEK_SET);\n _imaging_read_pyFd(state->fd, (char*)ptr, c->bufsize);\n\n\n /* decoder initialization */\n state->count = 0;\n state->y = 0;\n if (state->ystep < 0) {\n state->y = im->ysize - 1;\n } else {\n state->ystep = 1;\n }\n\n if (im->xsize > INT_MAX / im->bands ||\n im->ysize > INT_MAX / im->bands) {\n err = IMAGING_CODEC_MEMORY;\n goto sgi_finish_decode;\n }\n\n /* Allocate memory for RLE tables and rows */\n free(state->buffer);\n state->buffer = NULL;\n /* malloc overflow check above */\n state->buffer = calloc(im->xsize * im->bands, sizeof(UINT8) * 2);\n c->tablen = im->bands * im->ysize;\n c->starttab = calloc(c->tablen, sizeof(UINT32));\n c->lengthtab = calloc(c->tablen, sizeof(UINT32));\n if (!state->buffer ||\n !c->starttab ||\n !c->lengthtab) {\n err = IMAGING_CODEC_MEMORY;\n goto sgi_finish_decode;\n }\n /* populate offsets table */\n for (c->tabindex = 0, c->bufindex = 0; c->tabindex < c->tablen; c->tabindex++, c->bufindex+=4)\n read4B(&c->starttab[c->tabindex], &ptr[c->bufindex]);\n /* populate lengths table */\n for (c->tabindex = 0, c->bufindex = c->tablen * sizeof(UINT32); c->tabindex < c->tablen; c->tabindex++, c->bufindex+=4)\n read4B(&c->lengthtab[c->tabindex], &ptr[c->bufindex]);\n\n state->count += c->tablen * sizeof(UINT32) * 2;\n\n /* read compressed rows */\n for (c->rowno = 0; c->rowno < im->ysize; c->rowno++, state->y += state->ystep)\n {\n for (c->channo = 0; c->channo < im->bands; c->channo++)\n {\n c->rleoffset = c->starttab[c->rowno + c->channo * im->ysize];\n c->rlelength = c->lengthtab[c->rowno + c->channo * im->ysize];\n c->rleoffset -= SGI_HEADER_SIZE;\n\n if (c->rleoffset + c->rlelength > c->bufsize) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n\n /* row decompression */\n if (c->bpc ==1) {\n if(expandrow(&state->buffer[c->channo], &ptr[c->rleoffset], c->rlelength, im->bands))\n goto sgi_finish_decode;\n }\n else {\n if(expandrow2(&state->buffer[c->channo * 2], &ptr[c->rleoffset], c->rlelength, im->bands))\n goto sgi_finish_decode;\n }\n\n state->count += c->rlelength;\n }\n\n /* store decompressed data in image */\n state->shuffle((UINT8*)im->image[state->y], state->buffer, im->xsize);\n\n }\n\n c->bufsize++;\n\nsgi_finish_decode: ;\n\n free(c->starttab);\n free(c->lengthtab);\n free(ptr);\n if (err != 0){\n return err;\n }\n return state->count - c->bufsize;\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 int ieee80211_change_station(struct wiphy *wiphy,\n\t\t\t\t struct net_device *dev, const u8 *mac,\n\t\t\t\t struct station_parameters *params)\n{\n\tstruct ieee80211_sub_if_data *sdata = IEEE80211_DEV_TO_SUB_IF(dev);\n\tstruct ieee80211_local *local = wiphy_priv(wiphy);\n\tstruct sta_info *sta;\n\tstruct ieee80211_sub_if_data *vlansdata;\n\tenum cfg80211_station_type statype;\n\tint err;\n\n\tmutex_lock(&local->sta_mtx);\n\n\tsta = sta_info_get_bss(sdata, mac);\n\tif (!sta) {\n\t\terr = -ENOENT;\n\t\tgoto out_err;\n\t}\n\n\tswitch (sdata->vif.type) {\n\tcase NL80211_IFTYPE_MESH_POINT:\n\t\tif (sdata->u.mesh.user_mpm)\n\t\t\tstatype = CFG80211_STA_MESH_PEER_USER;\n\t\telse\n\t\t\tstatype = CFG80211_STA_MESH_PEER_KERNEL;\n\t\tbreak;\n\tcase NL80211_IFTYPE_ADHOC:\n\t\tstatype = CFG80211_STA_IBSS;\n\t\tbreak;\n\tcase NL80211_IFTYPE_STATION:\n\t\tif (!test_sta_flag(sta, WLAN_STA_TDLS_PEER)) {\n\t\t\tstatype = CFG80211_STA_AP_STA;\n\t\t\tbreak;\n\t\t}\n\t\tif (test_sta_flag(sta, WLAN_STA_AUTHORIZED))\n\t\t\tstatype = CFG80211_STA_TDLS_PEER_ACTIVE;\n\t\telse\n\t\t\tstatype = CFG80211_STA_TDLS_PEER_SETUP;\n\t\tbreak;\n\tcase NL80211_IFTYPE_AP:\n\tcase NL80211_IFTYPE_AP_VLAN:\n\t\tif (test_sta_flag(sta, WLAN_STA_ASSOC))\n\t\t\tstatype = CFG80211_STA_AP_CLIENT;\n\t\telse\n\t\t\tstatype = CFG80211_STA_AP_CLIENT_UNASSOC;\n\t\tbreak;\n\tdefault:\n\t\terr = -EOPNOTSUPP;\n\t\tgoto out_err;\n\t}\n\n\terr = cfg80211_check_station_change(wiphy, params, statype);\n\tif (err)\n\t\tgoto out_err;\n\n\tif (params->vlan && params->vlan != sta->sdata->dev) {\n\t\tvlansdata = IEEE80211_DEV_TO_SUB_IF(params->vlan);\n\n\t\tif (params->vlan->ieee80211_ptr->use_4addr) {\n\t\t\tif (vlansdata->u.vlan.sta) {\n\t\t\t\terr = -EBUSY;\n\t\t\t\tgoto out_err;\n\t\t\t}\n\n\t\t\trcu_assign_pointer(vlansdata->u.vlan.sta, sta);\n\t\t\t__ieee80211_check_fast_rx_iface(vlansdata);\n\t\t}\n\n\t\tif (sta->sdata->vif.type == NL80211_IFTYPE_AP_VLAN &&\n\t\t sta->sdata->u.vlan.sta)\n\t\t\tRCU_INIT_POINTER(sta->sdata->u.vlan.sta, NULL);\n\n\t\tif (test_sta_flag(sta, WLAN_STA_AUTHORIZED))\n\t\t\tieee80211_vif_dec_num_mcast(sta->sdata);\n\n\t\tsta->sdata = vlansdata;\n\t\tieee80211_check_fast_xmit(sta);\n\n\t\tif (test_sta_flag(sta, WLAN_STA_AUTHORIZED))\n\t\t\tieee80211_vif_inc_num_mcast(sta->sdata);\n\n\t\tcfg80211_send_layer2_update(sta->sdata->dev, sta->sta.addr);\n\t}\n\n\terr = sta_apply_parameters(local, sta, params);\n\tif (err)\n\t\tgoto out_err;\n\n\tmutex_unlock(&local->sta_mtx);\n\n\tif ((sdata->vif.type == NL80211_IFTYPE_AP ||\n\t sdata->vif.type == NL80211_IFTYPE_AP_VLAN) &&\n\t sta->known_smps_mode != sta->sdata->bss->req_smps &&\n\t test_sta_flag(sta, WLAN_STA_AUTHORIZED) &&\n\t sta_info_tx_streams(sta) != 1) {\n\t\tht_dbg(sta->sdata,\n\t\t \"%pM just authorized and MIMO capable - update SMPS\\n\",\n\t\t sta->sta.addr);\n\t\tieee80211_send_smps_action(sta->sdata,\n\t\t\tsta->sdata->bss->req_smps,\n\t\t\tsta->sta.addr,\n\t\t\tsta->sdata->vif.bss_conf.bssid);\n\t}\n\n\tif (sdata->vif.type == NL80211_IFTYPE_STATION &&\n\t params->sta_flags_mask & BIT(NL80211_STA_FLAG_AUTHORIZED)) {\n\t\tieee80211_recalc_ps(local);\n\t\tieee80211_recalc_ps_vif(sdata);\n\t}\n\n\treturn 0;\nout_err:\n\tmutex_unlock(&local->sta_mtx);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287'], 'message': 'mac80211: Do not send Layer 2 Update frame before authorization\n\nThe Layer 2 Update frame is used to update bridges when a station roams\nto another AP even if that STA does not transmit any frames after the\nreassociation. This behavior was described in IEEE Std 802.11F-2003 as\nsomething that would happen based on MLME-ASSOCIATE.indication, i.e.,\nbefore completing 4-way handshake. However, this IEEE trial-use\nrecommended practice document was published before RSN (IEEE Std\n802.11i-2004) and as such, did not consider RSN use cases. Furthermore,\nIEEE Std 802.11F-2003 was withdrawn in 2006 and as such, has not been\nmaintained amd should not be used anymore.\n\nSending out the Layer 2 Update frame immediately after association is\nfine for open networks (and also when using SAE, FT protocol, or FILS\nauthentication when the station is actually authenticated by the time\nassociation completes). However, it is not appropriate for cases where\nRSN is used with PSK or EAP authentication since the station is actually\nfully authenticated only once the 4-way handshake completes after\nauthentication and attackers might be able to use the unauthenticated\ntriggering of Layer 2 Update frame transmission to disrupt bridge\nbehavior.\n\nFix this by postponing transmission of the Layer 2 Update frame from\nstation entry addition to the point when the station entry is marked\nauthorized. Similarly, send out the VLAN binding update only if the STA\nentry has already been authorized.\n\nSigned-off-by: Jouni Malinen \nReviewed-by: Johannes Berg \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void delete_file(e2fsck_t ctx, ext2_ino_t ino,\n\t\t\tstruct dup_inode *dp, char* block_buf)\n{\n\text2_filsys fs = ctx->fs;\n\tstruct process_block_struct pb;\n\tstruct problem_context\tpctx;\n\tunsigned int\t\tcount;\n\n\tclear_problem_context(&pctx);\n\tpctx.ino = pb.ino = ino;\n\tpb.dup_blocks = 0;\n\tpb.ctx = ctx;\n\tpctx.str = \"delete_file\";\n\tpb.cur_cluster = ~0;\n\n\tif (ext2fs_inode_has_valid_blocks2(fs, EXT2_INODE(&dp->inode)))\n\t\tpctx.errcode = ext2fs_block_iterate3(fs, ino,\n\t\t\t\t\t\t BLOCK_FLAG_READ_ONLY,\n\t\t\t\t\t\t block_buf,\n\t\t\t\t\t\t delete_file_block, &pb);\n\tif (pctx.errcode)\n\t\tfix_problem(ctx, PR_1B_BLOCK_ITERATE, &pctx);\n\tif (ctx->inode_bad_map)\n\t\text2fs_unmark_inode_bitmap2(ctx->inode_bad_map, ino);\n\text2fs_inode_alloc_stats2(fs, ino, -1, LINUX_S_ISDIR(dp->inode.i_mode));\n\tquota_data_sub(ctx->qctx, &dp->inode, ino,\n\t\t pb.dup_blocks * fs->blocksize);\n\tquota_data_inodes(ctx->qctx, &dp->inode, ino, -1);\n\n\t/* Inode may have changed by block_iterate, so reread it */\n\te2fsck_read_inode_full(ctx, ino, EXT2_INODE(&dp->inode),\n\t\t\t sizeof(dp->inode), \"delete_file\");\n\te2fsck_clear_inode(ctx, ino, EXT2_INODE(&dp->inode), 0, \"delete_file\");\n\tif (ext2fs_file_acl_block(fs, EXT2_INODE(&dp->inode)) &&\n\t ext2fs_has_feature_xattr(fs->super)) {\n\t\tblk64_t file_acl_block = ext2fs_file_acl_block(fs,\n\t\t\t\t\t\tEXT2_INODE(&dp->inode));\n\n\t\tcount = 1;\n\t\tpctx.errcode = ext2fs_adjust_ea_refcount3(fs, file_acl_block,\n\t\t\t\t\tblock_buf, -1, &count, ino);\n\t\tif (pctx.errcode == EXT2_ET_BAD_EA_BLOCK_NUM) {\n\t\t\tpctx.errcode = 0;\n\t\t\tcount = 1;\n\t\t}\n\t\tif (pctx.errcode) {\n\t\t\tpctx.blk = file_acl_block;\n\t\t\tfix_problem(ctx, PR_1B_ADJ_EA_REFCOUNT, &pctx);\n\t\t}\n\t\t/*\n\t\t * If the count is zero, then arrange to have the\n\t\t * block deleted. If the block is in the block_dup_map,\n\t\t * also call delete_file_block since it will take care\n\t\t * of keeping the accounting straight.\n\t\t */\n\t\tif ((count == 0) ||\n\t\t ext2fs_test_block_bitmap2(ctx->block_dup_map,\n\t\t\t\t\t file_acl_block)) {\n\t\t\tdelete_file_block(fs, &file_acl_block,\n\t\t\t\t\t BLOCK_COUNT_EXTATTR, 0, 0, &pb);\n\t\t\text2fs_file_acl_block_set(fs, EXT2_INODE(&dp->inode),\n\t\t\t\t\t\t file_acl_block);\n\t\t\tquota_data_sub(ctx->qctx, &dp->inode, ino,\n\t\t\t\t fs->blocksize);\n\t\t}\n\t}\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: int overrun(int itemSize, int nItems) {\n int len = ptr - start + itemSize * nItems;\n if (len < (end - start) * 2)\n len = (end - start) * 2;\n\n U8* newStart = new U8[len];\n memcpy(newStart, start, ptr - start);\n ptr = newStart + (ptr - start);\n delete [] start;\n start = newStart;\n end = newStart + len;\n\n return nItems;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'Use size_t for lengths in stream objects\n\nProvides safety against them accidentally becoming negative because\nof bugs in the calculations.\n\nAlso does the same to CharArray and friends as they were strongly\nconnection to the stream objects.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: MemInStream(const void* data, int len, bool deleteWhenDone_=false)\n : start((const U8*)data), deleteWhenDone(deleteWhenDone_)\n {\n ptr = start;\n end = start + len;\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 int __feat_register_sp(struct list_head *fn, u8 feat, u8 is_local,\n\t\t\t u8 mandatory, u8 const *sp_val, u8 sp_len)\n{\n\tdccp_feat_val fval;\n\n\tif (dccp_feat_type(feat) != FEAT_SP ||\n\t !dccp_feat_sp_list_ok(feat, sp_val, sp_len))\n\t\treturn -EINVAL;\n\n\t/* Avoid negotiating alien CCIDs by only advertising supported ones */\n\tif (feat == DCCPF_CCID && !ccid_support_check(sp_val, sp_len))\n\t\treturn -EOPNOTSUPP;\n\n\tif (dccp_feat_clone_sp_val(&fval, sp_val, sp_len))\n\t\treturn -ENOMEM;\n\n\treturn dccp_feat_push_change(fn, feat, is_local, mandatory, &fval);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'dccp: Fix memleak in __feat_register_sp\n\nIf dccp_feat_push_change fails, we forget free the mem\nwhich is alloced by kmemdup in dccp_feat_clone_sp_val.\n\nReported-by: Hulk Robot \nFixes: e8ef967a54f4 (\"dccp: Registration routines for changing feature values\")\nReviewed-by: Mukesh Ojha \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: static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)\n{\n\tstruct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);\n\ts64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;\n\n\tif (slack_runtime <= 0)\n\t\treturn;\n\n\traw_spin_lock(&cfs_b->lock);\n\tif (cfs_b->quota != RUNTIME_INF &&\n\t cfs_rq->runtime_expires == cfs_b->runtime_expires) {\n\t\tcfs_b->runtime += slack_runtime;\n\n\t\t/* we are under rq->lock, defer unthrottling using a timer */\n\t\tif (cfs_b->runtime > sched_cfs_bandwidth_slice() &&\n\t\t !list_empty(&cfs_b->throttled_cfs_rq))\n\t\t\tstart_cfs_slack_bandwidth(cfs_b);\n\t}\n\traw_spin_unlock(&cfs_b->lock);\n\n\t/* even if it's not valid for return we don't want to try again */\n\tcfs_rq->runtime_remaining -= slack_runtime;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'sched/fair: Fix low cpu usage with high throttling by removing expiration of cpu-local slices\n\nIt has been observed, that highly-threaded, non-cpu-bound applications\nrunning under cpu.cfs_quota_us constraints can hit a high percentage of\nperiods throttled while simultaneously not consuming the allocated\namount of quota. This use case is typical of user-interactive non-cpu\nbound applications, such as those running in kubernetes or mesos when\nrun on multiple cpu cores.\n\nThis has been root caused to cpu-local run queue being allocated per cpu\nbandwidth slices, and then not fully using that slice within the period.\nAt which point the slice and quota expires. This expiration of unused\nslice results in applications not being able to utilize the quota for\nwhich they are allocated.\n\nThe non-expiration of per-cpu slices was recently fixed by\n'commit 512ac999d275 (\"sched/fair: Fix bandwidth timer clock drift\ncondition\")'. Prior to that it appears that this had been broken since\nat least 'commit 51f2176d74ac (\"sched/fair: Fix unlocked reads of some\ncfs_b->quota/period\")' which was introduced in v3.16-rc1 in 2014. That\nadded the following conditional which resulted in slices never being\nexpired.\n\nif (cfs_rq->runtime_expires != cfs_b->runtime_expires) {\n\t/* extend local deadline, drift is bounded above by 2 ticks */\n\tcfs_rq->runtime_expires += TICK_NSEC;\n\nBecause this was broken for nearly 5 years, and has recently been fixed\nand is now being noticed by many users running kubernetes\n(https://github.com/kubernetes/kubernetes/issues/67577) it is my opinion\nthat the mechanisms around expiring runtime should be removed\naltogether.\n\nThis allows quota already allocated to per-cpu run-queues to live longer\nthan the period boundary. This allows threads on runqueues that do not\nuse much CPU to continue to use their remaining slice over a longer\nperiod of time than cpu.cfs_period_us. However, this helps prevent the\nabove condition of hitting throttling while also not fully utilizing\nyour cpu quota.\n\nThis theoretically allows a machine to use slightly more than its\nallotted quota in some periods. This overflow would be bounded by the\nremaining quota left on each per-cpu runqueueu. This is typically no\nmore than min_cfs_rq_runtime=1ms per cpu. For CPU bound tasks this will\nchange nothing, as they should theoretically fully utilize all of their\nquota in each period. For user-interactive tasks as described above this\nprovides a much better user/application experience as their cpu\nutilization will more closely match the amount they requested when they\nhit throttling. This means that cpu limits no longer strictly apply per\nperiod for non-cpu bound applications, but that they are still accurate\nover longer timeframes.\n\nThis greatly improves performance of high-thread-count, non-cpu bound\napplications with low cfs_quota_us allocation on high-core-count\nmachines. In the case of an artificial testcase (10ms/100ms of quota on\n80 CPU machine), this commit resulted in almost 30x performance\nimprovement, while still maintaining correct cpu quota restrictions.\nThat testcase is available at https://github.com/indeedeng/fibtest.\n\nFixes: 512ac999d275 (\"sched/fair: Fix bandwidth timer clock drift condition\")\nSigned-off-by: Dave Chiluk \nSigned-off-by: Peter Zijlstra (Intel) \nReviewed-by: Phil Auld \nReviewed-by: Ben Segall \nCc: Ingo Molnar \nCc: John Hammond \nCc: Jonathan Corbet \nCc: Kyle Anderson \nCc: Gabriel Munos \nCc: Peter Oskolkov \nCc: Cong Wang \nCc: Brendan Gregg \nLink: https://lkml.kernel.org/r/1563900266-19734-2-git-send-email-chiluk+linux@indeed.com'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: lyd_new_anydata(struct lyd_node *parent, const struct lys_module *module, const char *name,\n void *value, LYD_ANYDATA_VALUETYPE value_type)\n{\n const struct lys_node *siblings, *snode;\n\n if ((!parent && !module) || !name) {\n LOGARG;\n return NULL;\n }\n\n siblings = lyd_new_find_schema(parent, module, 0);\n if (!siblings) {\n LOGARG;\n return NULL;\n }\n\n if (lys_getnext_data(module, lys_parent(siblings), name, strlen(name), LYS_ANYDATA, &snode) || !snode) {\n LOGERR(siblings->module->ctx, LY_EINVAL, \"Failed to find \\\"%s\\\" as a sibling to \\\"%s:%s\\\".\",\n name, lys_node_module(siblings)->name, siblings->name);\n return NULL;\n }\n\n return lyd_create_anydata(parent, snode, value, value_type);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'schema tree BUGFIX do not check features while still resolving schema\n\nFixes #723'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int\nyyparse (void *scanner, struct yang_parameter *param)\n{\n/* The lookahead symbol. */\nint yychar;\nchar *s = NULL, *tmp_s = NULL, *ext_name = NULL;\nstruct lys_module *trg = NULL;\nstruct lys_node *tpdf_parent = NULL, *data_node = NULL;\nstruct lys_ext_instance_complex *ext_instance = NULL;\nint is_ext_instance;\nvoid *actual = NULL;\nenum yytokentype backup_type, actual_type = MODULE_KEYWORD;\nint64_t cnt_val = 0;\nint is_value = 0;\nvoid *yang_type = NULL;\n\n\n/* The semantic value of the lookahead symbol. */\n/* Default value used for initialization, for pacifying older GCCs\n or non-GCC compilers. */\nYY_INITIAL_VALUE (static YYSTYPE yyval_default;)\nYYSTYPE yylval YY_INITIAL_VALUE (= yyval_default);\n\n/* Location data for the lookahead symbol. */\nstatic YYLTYPE yyloc_default\n# if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL\n = { 1, 1, 1, 1 }\n# endif\n;\nYYLTYPE yylloc = yyloc_default;\n\n /* Number of syntax errors so far. */\n int yynerrs;\n\n int yystate;\n /* Number of tokens to shift before error messages enabled. */\n int yyerrstatus;\n\n /* The stacks and their tools:\n 'yyss': related to states.\n 'yyvs': related to semantic values.\n 'yyls': related to locations.\n\n Refer to the stacks through separate pointers, to allow yyoverflow\n to reallocate them elsewhere. */\n\n /* The state stack. */\n yytype_int16 yyssa[YYINITDEPTH];\n yytype_int16 *yyss;\n yytype_int16 *yyssp;\n\n /* The semantic value stack. */\n YYSTYPE yyvsa[YYINITDEPTH];\n YYSTYPE *yyvs;\n YYSTYPE *yyvsp;\n\n /* The location stack. */\n YYLTYPE yylsa[YYINITDEPTH];\n YYLTYPE *yyls;\n YYLTYPE *yylsp;\n\n /* The locations where the error started and ended. */\n YYLTYPE yyerror_range[3];\n\n YYSIZE_T yystacksize;\n\n int yyn;\n int yyresult;\n /* Lookahead token as an internal (translated) token number. */\n int yytoken = 0;\n /* The variables used to return semantic value and location from the\n action routines. */\n YYSTYPE yyval;\n YYLTYPE yyloc;\n\n#if YYERROR_VERBOSE\n /* Buffer for error messages, and its allocated size. */\n char yymsgbuf[128];\n char *yymsg = yymsgbuf;\n YYSIZE_T yymsg_alloc = sizeof yymsgbuf;\n#endif\n\n#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N), yylsp -= (N))\n\n /* The number of symbols on the RHS of the reduced rule.\n Keep to zero when no symbol should be popped. */\n int yylen = 0;\n\n yyssp = yyss = yyssa;\n yyvsp = yyvs = yyvsa;\n yylsp = yyls = yylsa;\n yystacksize = YYINITDEPTH;\n\n YYDPRINTF ((stderr, \"Starting parse\\n\"));\n\n yystate = 0;\n yyerrstatus = 0;\n yynerrs = 0;\n yychar = YYEMPTY; /* Cause a token to be read. */\n\n/* User initialization code. */\n\n{ yylloc.last_column = 0;\n if (param->flags & EXT_INSTANCE_SUBSTMT) {\n is_ext_instance = 1;\n ext_instance = (struct lys_ext_instance_complex *)param->actual_node;\n ext_name = (char *)param->data_node;\n } else {\n is_ext_instance = 0;\n }\n yylloc.last_line = is_ext_instance; /* HACK for flex - return SUBMODULE_KEYWORD or SUBMODULE_EXT_KEYWORD */\n param->value = &s;\n param->data_node = (void **)&data_node;\n param->actual_node = &actual;\n backup_type = NODE;\n trg = (param->submodule) ? (struct lys_module *)param->submodule : param->module;\n }\n\n\n yylsp[0] = yylloc;\n goto yysetstate;\n\n/*------------------------------------------------------------.\n| yynewstate -- Push a new state, which is found in yystate. |\n`------------------------------------------------------------*/\n yynewstate:\n /* In all cases, when you get here, the value and location stacks\n have just been pushed. So pushing a state here evens the stacks. */\n yyssp++;\n\n yysetstate:\n *yyssp = (yytype_int16) yystate;\n\n if (yyss + yystacksize - 1 <= yyssp)\n {\n /* Get the current used size of the three stacks, in elements. */\n YYSIZE_T yysize = (YYSIZE_T) (yyssp - yyss + 1);\n\n#ifdef yyoverflow\n {\n /* Give user a chance to reallocate the stack. Use copies of\n these so that the &'s don't force the real ones into\n memory. */\n YYSTYPE *yyvs1 = yyvs;\n yytype_int16 *yyss1 = yyss;\n YYLTYPE *yyls1 = yyls;\n\n /* Each stack pointer address is followed by the size of the\n data in use in that stack, in bytes. This used to be a\n conditional around just the two extra args, but that might\n be undefined if yyoverflow is a macro. */\n yyoverflow (YY_(\"memory exhausted\"),\n &yyss1, yysize * sizeof (*yyssp),\n &yyvs1, yysize * sizeof (*yyvsp),\n &yyls1, yysize * sizeof (*yylsp),\n &yystacksize);\n yyss = yyss1;\n yyvs = yyvs1;\n yyls = yyls1;\n }\n#else /* no yyoverflow */\n# ifndef YYSTACK_RELOCATE\n goto yyexhaustedlab;\n# else\n /* Extend the stack our own way. */\n if (YYMAXDEPTH <= yystacksize)\n goto yyexhaustedlab;\n yystacksize *= 2;\n if (YYMAXDEPTH < yystacksize)\n yystacksize = YYMAXDEPTH;\n\n {\n yytype_int16 *yyss1 = yyss;\n union yyalloc *yyptr =\n (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));\n if (! yyptr)\n goto yyexhaustedlab;\n YYSTACK_RELOCATE (yyss_alloc, yyss);\n YYSTACK_RELOCATE (yyvs_alloc, yyvs);\n YYSTACK_RELOCATE (yyls_alloc, yyls);\n# undef YYSTACK_RELOCATE\n if (yyss1 != yyssa)\n YYSTACK_FREE (yyss1);\n }\n# endif\n#endif /* no yyoverflow */\n\n yyssp = yyss + yysize - 1;\n yyvsp = yyvs + yysize - 1;\n yylsp = yyls + yysize - 1;\n\n YYDPRINTF ((stderr, \"Stack size increased to %lu\\n\",\n (unsigned long) yystacksize));\n\n if (yyss + yystacksize - 1 <= yyssp)\n YYABORT;\n }\n\n YYDPRINTF ((stderr, \"Entering state %d\\n\", yystate));\n\n if (yystate == YYFINAL)\n YYACCEPT;\n\n goto yybackup;\n\n/*-----------.\n| yybackup. |\n`-----------*/\nyybackup:\n\n /* Do appropriate processing given the current state. Read a\n lookahead token if we need one and don't already have one. */\n\n /* First try to decide what to do without reference to lookahead token. */\n yyn = yypact[yystate];\n if (yypact_value_is_default (yyn))\n goto yydefault;\n\n /* Not known => get a lookahead token if don't already have one. */\n\n /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */\n if (yychar == YYEMPTY)\n {\n YYDPRINTF ((stderr, \"Reading a token: \"));\n yychar = yylex (&yylval, &yylloc, scanner);\n }\n\n if (yychar <= YYEOF)\n {\n yychar = yytoken = YYEOF;\n YYDPRINTF ((stderr, \"Now at end of input.\\n\"));\n }\n else\n {\n yytoken = YYTRANSLATE (yychar);\n YY_SYMBOL_PRINT (\"Next token is\", yytoken, &yylval, &yylloc);\n }\n\n /* If the proper action on seeing token YYTOKEN is to reduce or to\n detect an error, take that action. */\n yyn += yytoken;\n if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)\n goto yydefault;\n yyn = yytable[yyn];\n if (yyn <= 0)\n {\n if (yytable_value_is_error (yyn))\n goto yyerrlab;\n yyn = -yyn;\n goto yyreduce;\n }\n\n /* Count tokens shifted since error; after three, turn off error\n status. */\n if (yyerrstatus)\n yyerrstatus--;\n\n /* Shift the lookahead token. */\n YY_SYMBOL_PRINT (\"Shifting\", yytoken, &yylval, &yylloc);\n\n /* Discard the shifted token. */\n yychar = YYEMPTY;\n\n yystate = yyn;\n YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN\n *++yyvsp = yylval;\n YY_IGNORE_MAYBE_UNINITIALIZED_END\n *++yylsp = yylloc;\n goto yynewstate;\n\n\n/*-----------------------------------------------------------.\n| yydefault -- do the default action for the current state. |\n`-----------------------------------------------------------*/\nyydefault:\n yyn = yydefact[yystate];\n if (yyn == 0)\n goto yyerrlab;\n goto yyreduce;\n\n\n/*-----------------------------.\n| yyreduce -- Do a reduction. |\n`-----------------------------*/\nyyreduce:\n /* yyn is the number of a rule to reduce with. */\n yylen = yyr2[yyn];\n\n /* If YYLEN is nonzero, implement the default value of the action:\n '$$ = $1'.\n\n Otherwise, the following line sets YYVAL to garbage.\n This behavior is undocumented and Bison\n users should not rely upon it. Assigning to YYVAL\n unconditionally makes the parser a bit smaller, and it avoids a\n GCC warning that YYVAL may be used uninitialized. */\n yyval = yyvsp[1-yylen];\n\n /* Default location. */\n YYLLOC_DEFAULT (yyloc, (yylsp - yylen), yylen);\n yyerror_range[1] = yyloc;\n YY_REDUCE_PRINT (yyn);\n switch (yyn)\n {\n case 5:\n\n { if (yyget_text(scanner)[0] == '\"') {\n char *tmp;\n\n s = malloc(yyget_leng(scanner) - 1 + 7 * yylval.i);\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n if (!(tmp = yang_read_string(trg->ctx, yyget_text(scanner) + 1, s, yyget_leng(scanner) - 2, 0, yylloc.first_column))) {\n YYABORT;\n }\n s = tmp;\n } else {\n s = calloc(1, yyget_leng(scanner) - 1);\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n memcpy(s, yyget_text(scanner) + 1, yyget_leng(scanner) - 2);\n }\n (yyval.p_str) = &s;\n }\n\n break;\n\n case 8:\n\n { if (yyget_leng(scanner) > 2) {\n int length_s = strlen(s), length_tmp = yyget_leng(scanner);\n char *tmp;\n\n tmp = realloc(s, length_s + length_tmp - 1);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n s = tmp;\n if (yyget_text(scanner)[0] == '\"') {\n if (!(tmp = yang_read_string(trg->ctx, yyget_text(scanner) + 1, s, length_tmp - 2, length_s, yylloc.first_column))) {\n YYABORT;\n }\n s = tmp;\n } else {\n memcpy(s + length_s, yyget_text(scanner) + 1, length_tmp - 2);\n s[length_s + length_tmp - 2] = '\\0';\n }\n }\n }\n\n break;\n\n case 10:\n\n { if (param->submodule) {\n free(s);\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, \"module\");\n YYABORT;\n }\n trg = param->module;\n yang_read_common(trg,s,MODULE_KEYWORD);\n s = NULL;\n actual_type = MODULE_KEYWORD;\n }\n\n break;\n\n case 12:\n\n { if (!param->module->ns) {\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"namespace\", \"module\");\n YYABORT;\n }\n if (!param->module->prefix) {\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"prefix\", \"module\");\n YYABORT;\n }\n }\n\n break;\n\n case 13:\n\n { (yyval.i) = 0; }\n\n break;\n\n case 14:\n\n { if (yang_check_version(param->module, param->submodule, s, (yyvsp[-1].i))) {\n YYABORT;\n }\n (yyval.i) = 1;\n s = NULL;\n }\n\n break;\n\n case 15:\n\n { if (yang_read_common(param->module, s, NAMESPACE_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 16:\n\n { if (yang_read_prefix(trg, NULL, s)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 17:\n\n { if (!param->submodule) {\n free(s);\n LOGVAL(trg->ctx, LYE_SUBMODULE, LY_VLOG_NONE, NULL);\n YYABORT;\n }\n trg = (struct lys_module *)param->submodule;\n yang_read_common(trg,s,MODULE_KEYWORD);\n s = NULL;\n actual_type = SUBMODULE_KEYWORD;\n }\n\n break;\n\n case 19:\n\n { if (!param->submodule->prefix) {\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"belongs-to\", \"submodule\");\n YYABORT;\n }\n if (!(yyvsp[0].i)) {\n /* check version compatibility with the main module */\n if (param->module->version > 1) {\n LOGVAL(trg->ctx, LYE_INVER, LY_VLOG_NONE, NULL);\n YYABORT;\n }\n }\n }\n\n break;\n\n case 20:\n\n { (yyval.i) = 0; }\n\n break;\n\n case 21:\n\n { if (yang_check_version(param->module, param->submodule, s, (yyvsp[-1].i))) {\n YYABORT;\n }\n (yyval.i) = 1;\n s = NULL;\n }\n\n break;\n\n case 23:\n\n { backup_type = actual_type;\n actual_type = YANG_VERSION_KEYWORD;\n }\n\n break;\n\n case 25:\n\n { backup_type = actual_type;\n actual_type = NAMESPACE_KEYWORD;\n }\n\n break;\n\n case 30:\n\n { actual_type = (yyvsp[-4].token);\n backup_type = NODE;\n actual = NULL;\n }\n\n break;\n\n case 31:\n\n { YANG_ADDELEM(trg->imp, trg->imp_size, \"imports\");\n /* HACK for unres */\n ((struct lys_import *)actual)->module = (struct lys_module *)s;\n s = NULL;\n (yyval.token) = actual_type;\n actual_type = IMPORT_KEYWORD;\n }\n\n break;\n\n case 32:\n\n { (yyval.i) = 0; }\n\n break;\n\n case 33:\n\n { if (yang_read_prefix(trg, actual, s)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 34:\n\n { if (trg->version != 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, \"description\");\n free(s);\n YYABORT;\n }\n if (yang_read_description(trg, actual, s, \"import\", IMPORT_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n (yyval.i) = (yyvsp[-1].i);\n }\n\n break;\n\n case 35:\n\n { if (trg->version != 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, \"reference\");\n free(s);\n YYABORT;\n }\n if (yang_read_reference(trg, actual, s, \"import\", IMPORT_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n (yyval.i) = (yyvsp[-1].i);\n }\n\n break;\n\n case 36:\n\n { if ((yyvsp[-1].i)) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"revision-date\", \"import\");\n free(s);\n YYABORT;\n }\n memcpy(((struct lys_import *)actual)->rev, s, LY_REV_SIZE-1);\n free(s);\n s = NULL;\n (yyval.i) = 1;\n }\n\n break;\n\n case 37:\n\n { YANG_ADDELEM(trg->inc, trg->inc_size, \"includes\");\n /* HACK for unres */\n ((struct lys_include *)actual)->submodule = (struct lys_submodule *)s;\n s = NULL;\n (yyval.token) = actual_type;\n actual_type = INCLUDE_KEYWORD;\n }\n\n break;\n\n case 38:\n\n { actual_type = (yyvsp[-1].token);\n backup_type = NODE;\n actual = NULL;\n }\n\n break;\n\n case 41:\n\n { (yyval.i) = 0; }\n\n break;\n\n case 42:\n\n { if (trg->version != 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, \"description\");\n free(s);\n YYABORT;\n }\n if (yang_read_description(trg, actual, s, \"include\", INCLUDE_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n (yyval.i) = (yyvsp[-1].i);\n }\n\n break;\n\n case 43:\n\n { if (trg->version != 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, \"reference\");\n free(s);\n YYABORT;\n }\n if (yang_read_reference(trg, actual, s, \"include\", INCLUDE_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n (yyval.i) = (yyvsp[-1].i);\n }\n\n break;\n\n case 44:\n\n { if ((yyvsp[-1].i)) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"revision-date\", \"include\");\n free(s);\n YYABORT;\n }\n memcpy(((struct lys_include *)actual)->rev, s, LY_REV_SIZE-1);\n free(s);\n s = NULL;\n (yyval.i) = 1;\n }\n\n break;\n\n case 45:\n\n { backup_type = actual_type;\n actual_type = REVISION_DATE_KEYWORD;\n }\n\n break;\n\n case 47:\n\n { (yyval.token) = actual_type;\n if (is_ext_instance) {\n if (yang_read_extcomplex_str(trg, ext_instance, \"belongs-to\", ext_name, s,\n 0, LY_STMT_BELONGSTO)) {\n YYABORT;\n }\n } else {\n if (param->submodule->prefix) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"belongs-to\", \"submodule\");\n free(s);\n YYABORT;\n }\n if (!ly_strequal(s, param->submodule->belongsto->name, 0)) {\n LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, \"belongs-to\");\n free(s);\n YYABORT;\n }\n free(s);\n }\n s = NULL;\n actual_type = BELONGS_TO_KEYWORD;\n }\n\n break;\n\n case 48:\n\n { if (is_ext_instance) {\n if (yang_read_extcomplex_str(trg, ext_instance, \"prefix\", \"belongs-to\", s,\n LY_STMT_BELONGSTO, LY_STMT_PREFIX)) {\n YYABORT;\n }\n } else {\n if (yang_read_prefix(trg, NULL, s)) {\n YYABORT;\n }\n }\n s = NULL;\n actual_type = (yyvsp[-4].token);\n }\n\n break;\n\n case 49:\n\n { backup_type = actual_type;\n actual_type = PREFIX_KEYWORD;\n }\n\n break;\n\n case 52:\n\n { if (yang_read_common(trg, s, ORGANIZATION_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 53:\n\n { if (yang_read_common(trg, s, CONTACT_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 54:\n\n { if (yang_read_description(trg, NULL, s, NULL, MODULE_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 55:\n\n { if (yang_read_reference(trg, NULL, s, NULL, MODULE_KEYWORD)) {\n YYABORT;\n }\n s=NULL;\n }\n\n break;\n\n case 56:\n\n { backup_type = actual_type;\n actual_type = ORGANIZATION_KEYWORD;\n }\n\n break;\n\n case 58:\n\n { backup_type = actual_type;\n actual_type = CONTACT_KEYWORD;\n }\n\n break;\n\n case 60:\n\n { backup_type = actual_type;\n actual_type = DESCRIPTION_KEYWORD;\n }\n\n break;\n\n case 62:\n\n { backup_type = actual_type;\n actual_type = REFERENCE_KEYWORD;\n }\n\n break;\n\n case 64:\n\n { if (trg->rev_size) {\n struct lys_revision *tmp;\n\n tmp = realloc(trg->rev, trg->rev_size * sizeof *trg->rev);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n trg->rev = tmp;\n }\n }\n\n break;\n\n case 65:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!is_ext_instance) {\n YANG_ADDELEM(trg->rev, trg->rev_size, \"revisions\");\n }\n memcpy(((struct lys_revision *)actual)->date, s, LY_REV_SIZE);\n free(s);\n s = NULL;\n actual_type = REVISION_KEYWORD;\n }\n\n break;\n\n case 67:\n\n { int i;\n\n /* check uniqueness of the revision date - not required by RFC */\n for (i = 0; i < (trg->rev_size - 1); i++) {\n if (!strcmp(trg->rev[i].date, trg->rev[trg->rev_size - 1].date)) {\n LOGWRN(trg->ctx, \"Module's revisions are not unique (%s).\",\n trg->rev[trg->rev_size - 1].date);\n break;\n }\n }\n }\n\n break;\n\n case 68:\n\n { actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 72:\n\n { if (yang_read_description(trg, actual, s, \"revision\",REVISION_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 73:\n\n { if (yang_read_reference(trg, actual, s, \"revision\", REVISION_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 74:\n\n { s = strdup(yyget_text(scanner));\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n if (lyp_check_date(trg->ctx, s)) {\n free(s);\n YYABORT;\n }\n }\n\n break;\n\n case 76:\n\n { if (lyp_check_date(trg->ctx, s)) {\n free(s);\n YYABORT;\n }\n }\n\n break;\n\n case 77:\n\n { void *tmp;\n\n if (trg->tpdf_size) {\n tmp = realloc(trg->tpdf, trg->tpdf_size * sizeof *trg->tpdf);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n trg->tpdf = tmp;\n }\n\n if (trg->features_size) {\n tmp = realloc(trg->features, trg->features_size * sizeof *trg->features);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n trg->features = tmp;\n }\n\n if (trg->ident_size) {\n tmp = realloc(trg->ident, trg->ident_size * sizeof *trg->ident);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n trg->ident = tmp;\n }\n\n if (trg->augment_size) {\n tmp = realloc(trg->augment, trg->augment_size * sizeof *trg->augment);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n trg->augment = tmp;\n }\n\n if (trg->extensions_size) {\n tmp = realloc(trg->extensions, trg->extensions_size * sizeof *trg->extensions);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n trg->extensions = tmp;\n }\n }\n\n break;\n\n case 78:\n\n { /* check the module with respect to the context now */\n if (!param->submodule) {\n switch (lyp_ctx_check_module(trg)) {\n case -1:\n YYABORT;\n case 0:\n break;\n case 1:\n /* it's already there */\n param->flags |= YANG_EXIST_MODULE;\n YYABORT;\n }\n }\n param->flags &= (~YANG_REMOVE_IMPORT);\n if (yang_check_imports(trg, param->unres)) {\n YYABORT;\n }\n actual = NULL;\n }\n\n break;\n\n case 79:\n\n { actual = NULL; }\n\n break;\n\n case 90:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n YANG_ADDELEM(trg->extensions, trg->extensions_size, \"extensions\");\n trg->extensions_size--;\n ((struct lys_ext *)actual)->name = lydict_insert_zc(param->module->ctx, s);\n ((struct lys_ext *)actual)->module = trg;\n if (lyp_check_identifier(trg->ctx, ((struct lys_ext *)actual)->name, LY_IDENT_EXTENSION, trg, NULL)) {\n trg->extensions_size++;\n YYABORT;\n }\n trg->extensions_size++;\n s = NULL;\n actual_type = EXTENSION_KEYWORD;\n }\n\n break;\n\n case 91:\n\n { struct lys_ext *ext = actual;\n ext->plugin = ext_get_plugin(ext->name, ext->module->name, ext->module->rev ? ext->module->rev[0].date : NULL);\n actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 96:\n\n { if (((struct lys_ext *)actual)->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"status\", \"extension\");\n YYABORT;\n }\n ((struct lys_ext *)actual)->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 97:\n\n { if (yang_read_description(trg, actual, s, \"extension\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 98:\n\n { if (yang_read_reference(trg, actual, s, \"extension\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 99:\n\n { (yyval.token) = actual_type;\n if (is_ext_instance) {\n if (yang_read_extcomplex_str(trg, ext_instance, \"argument\", ext_name, s,\n 0, LY_STMT_ARGUMENT)) {\n YYABORT;\n }\n } else {\n if (((struct lys_ext *)actual)->argument) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"argument\", \"extension\");\n free(s);\n YYABORT;\n }\n ((struct lys_ext *)actual)->argument = lydict_insert_zc(param->module->ctx, s);\n }\n s = NULL;\n actual_type = ARGUMENT_KEYWORD;\n }\n\n break;\n\n case 100:\n\n { actual_type = (yyvsp[-1].token); }\n\n break;\n\n case 103:\n\n { (yyval.uint) = (yyvsp[0].uint);\n backup_type = actual_type;\n actual_type = YIN_ELEMENT_KEYWORD;\n }\n\n break;\n\n case 105:\n\n { if (is_ext_instance) {\n int c;\n const char ***p;\n uint8_t *val;\n struct lyext_substmt *info;\n\n c = 0;\n p = lys_ext_complex_get_substmt(LY_STMT_ARGUMENT, ext_instance, &info);\n if (info->cardinality >= LY_STMT_CARD_SOME) {\n /* get the index in the array to add new item */\n for (c = 0; p[0][c + 1]; c++);\n val = (uint8_t *)p[1];\n } else {\n val = (uint8_t *)(p + 1);\n }\n val[c] = ((yyvsp[-1].uint) == LYS_YINELEM) ? 1 : 2;\n } else {\n ((struct lys_ext *)actual)->flags |= (yyvsp[-1].uint);\n }\n }\n\n break;\n\n case 106:\n\n { (yyval.uint) = LYS_YINELEM; }\n\n break;\n\n case 107:\n\n { (yyval.uint) = 0; }\n\n break;\n\n case 108:\n\n { if (!strcmp(s, \"true\")) {\n (yyval.uint) = LYS_YINELEM;\n } else if (!strcmp(s, \"false\")) {\n (yyval.uint) = 0;\n } else {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, s);\n free(s);\n YYABORT;\n }\n free(s);\n s = NULL;\n }\n\n break;\n\n case 109:\n\n { (yyval.i) = (yyvsp[0].i);\n backup_type = actual_type;\n actual_type = STATUS_KEYWORD;\n }\n\n break;\n\n case 110:\n\n { (yyval.i) = (yyvsp[-1].i); }\n\n break;\n\n case 111:\n\n { (yyval.i) = LYS_STATUS_CURR; }\n\n break;\n\n case 112:\n\n { (yyval.i) = LYS_STATUS_OBSLT; }\n\n break;\n\n case 113:\n\n { (yyval.i) = LYS_STATUS_DEPRC; }\n\n break;\n\n case 114:\n\n { if (!strcmp(s, \"current\")) {\n (yyval.i) = LYS_STATUS_CURR;\n } else if (!strcmp(s, \"obsolete\")) {\n (yyval.i) = LYS_STATUS_OBSLT;\n } else if (!strcmp(s, \"deprecated\")) {\n (yyval.i) = LYS_STATUS_DEPRC;\n } else {\n LOGVAL(trg->ctx,LYE_INSTMT, LY_VLOG_NONE, NULL, s);\n free(s);\n YYABORT;\n }\n free(s);\n s = NULL;\n }\n\n break;\n\n case 115:\n\n { /* check uniqueness of feature's names */\n if (lyp_check_identifier(trg->ctx, s, LY_IDENT_FEATURE, trg, NULL)) {\n free(s);\n YYABORT;\n }\n (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n YANG_ADDELEM(trg->features, trg->features_size, \"features\");\n ((struct lys_feature *)actual)->name = lydict_insert_zc(trg->ctx, s);\n ((struct lys_feature *)actual)->module = trg;\n s = NULL;\n actual_type = FEATURE_KEYWORD;\n }\n\n break;\n\n case 116:\n\n { actual = (yyvsp[-1].backup_token).actual;\n actual_type = (yyvsp[-1].backup_token).token;\n }\n\n break;\n\n case 118:\n\n { struct lys_iffeature *tmp;\n\n if (((struct lys_feature *)actual)->iffeature_size) {\n tmp = realloc(((struct lys_feature *)actual)->iffeature,\n ((struct lys_feature *)actual)->iffeature_size * sizeof *tmp);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct lys_feature *)actual)->iffeature = tmp;\n }\n }\n\n break;\n\n case 121:\n\n { if (((struct lys_feature *)actual)->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"status\", \"feature\");\n YYABORT;\n }\n ((struct lys_feature *)actual)->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 122:\n\n { if (yang_read_description(trg, actual, s, \"feature\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 123:\n\n { if (yang_read_reference(trg, actual, s, \"feature\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 124:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n switch (actual_type) {\n case FEATURE_KEYWORD:\n YANG_ADDELEM(((struct lys_feature *)actual)->iffeature,\n ((struct lys_feature *)actual)->iffeature_size, \"if-features\");\n break;\n case IDENTITY_KEYWORD:\n if (trg->version < 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, \"if-feature\", \"identity\");\n free(s);\n YYABORT;\n }\n YANG_ADDELEM(((struct lys_ident *)actual)->iffeature,\n ((struct lys_ident *)actual)->iffeature_size, \"if-features\");\n break;\n case ENUM_KEYWORD:\n if (trg->version < 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, \"if-feature\");\n free(s);\n YYABORT;\n }\n YANG_ADDELEM(((struct lys_type_enum *)actual)->iffeature,\n ((struct lys_type_enum *)actual)->iffeature_size, \"if-features\");\n break;\n case BIT_KEYWORD:\n if (trg->version < 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, \"if-feature\", \"bit\");\n free(s);\n YYABORT;\n }\n YANG_ADDELEM(((struct lys_type_bit *)actual)->iffeature,\n ((struct lys_type_bit *)actual)->iffeature_size, \"if-features\");\n break;\n case REFINE_KEYWORD:\n if (trg->version < 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, \"if-feature\");\n free(s);\n YYABORT;\n }\n YANG_ADDELEM(((struct lys_refine *)actual)->iffeature,\n ((struct lys_refine *)actual)->iffeature_size, \"if-features\");\n break;\n case EXTENSION_INSTANCE:\n /* nothing change */\n break;\n default:\n /* lys_node_* */\n YANG_ADDELEM(((struct lys_node *)actual)->iffeature,\n ((struct lys_node *)actual)->iffeature_size, \"if-features\");\n break;\n }\n ((struct lys_iffeature *)actual)->features = (struct lys_feature **)s;\n s = NULL;\n actual_type = IF_FEATURE_KEYWORD;\n }\n\n break;\n\n case 125:\n\n { actual = (yyvsp[-1].backup_token).actual;\n actual_type = (yyvsp[-1].backup_token).token;\n }\n\n break;\n\n case 128:\n\n { const char *tmp;\n\n tmp = lydict_insert_zc(trg->ctx, s);\n s = NULL;\n if (dup_identities_check(tmp, trg)) {\n lydict_remove(trg->ctx, tmp);\n YYABORT;\n }\n (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n YANG_ADDELEM(trg->ident, trg->ident_size, \"identities\");\n ((struct lys_ident *)actual)->name = tmp;\n ((struct lys_ident *)actual)->module = trg;\n actual_type = IDENTITY_KEYWORD;\n }\n\n break;\n\n case 129:\n\n { actual = (yyvsp[-1].backup_token).actual;\n actual_type = (yyvsp[-1].backup_token).token;\n }\n\n break;\n\n case 131:\n\n { void *tmp;\n\n if (((struct lys_ident *)actual)->base_size) {\n tmp = realloc(((struct lys_ident *)actual)->base,\n ((struct lys_ident *)actual)->base_size * sizeof *((struct lys_ident *)actual)->base);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct lys_ident *)actual)->base = tmp;\n }\n\n if (((struct lys_ident *)actual)->iffeature_size) {\n tmp = realloc(((struct lys_ident *)actual)->iffeature,\n ((struct lys_ident *)actual)->iffeature_size * sizeof *((struct lys_ident *)actual)->iffeature);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct lys_ident *)actual)->iffeature = tmp;\n }\n }\n\n break;\n\n case 133:\n\n { void *identity;\n\n if ((trg->version < 2) && ((struct lys_ident *)actual)->base_size) {\n free(s);\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"base\", \"identity\");\n YYABORT;\n }\n identity = actual;\n YANG_ADDELEM(((struct lys_ident *)actual)->base,\n ((struct lys_ident *)actual)->base_size, \"bases\");\n *((struct lys_ident **)actual) = (struct lys_ident *)s;\n s = NULL;\n actual = identity;\n }\n\n break;\n\n case 135:\n\n { if (((struct lys_ident *)actual)->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"status\", \"identity\");\n YYABORT;\n }\n ((struct lys_ident *)actual)->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 136:\n\n { if (yang_read_description(trg, actual, s, \"identity\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 137:\n\n { if (yang_read_reference(trg, actual, s, \"identity\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 138:\n\n { backup_type = actual_type;\n actual_type = BASE_KEYWORD;\n }\n\n break;\n\n case 140:\n\n { tpdf_parent = (actual_type == EXTENSION_INSTANCE) ? ext_instance : actual;\n (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (lyp_check_identifier(trg->ctx, s, LY_IDENT_TYPE, trg, tpdf_parent)) {\n free(s);\n YYABORT;\n }\n switch (actual_type) {\n case MODULE_KEYWORD:\n case SUBMODULE_KEYWORD:\n YANG_ADDELEM(trg->tpdf, trg->tpdf_size, \"typedefs\");\n break;\n case GROUPING_KEYWORD:\n YANG_ADDELEM(((struct lys_node_grp *)tpdf_parent)->tpdf,\n ((struct lys_node_grp *)tpdf_parent)->tpdf_size, \"typedefs\");\n break;\n case CONTAINER_KEYWORD:\n YANG_ADDELEM(((struct lys_node_container *)tpdf_parent)->tpdf,\n ((struct lys_node_container *)tpdf_parent)->tpdf_size, \"typedefs\");\n break;\n case LIST_KEYWORD:\n YANG_ADDELEM(((struct lys_node_list *)tpdf_parent)->tpdf,\n ((struct lys_node_list *)tpdf_parent)->tpdf_size, \"typedefs\");\n break;\n case RPC_KEYWORD:\n case ACTION_KEYWORD:\n YANG_ADDELEM(((struct lys_node_rpc_action *)tpdf_parent)->tpdf,\n ((struct lys_node_rpc_action *)tpdf_parent)->tpdf_size, \"typedefs\");\n break;\n case INPUT_KEYWORD:\n case OUTPUT_KEYWORD:\n YANG_ADDELEM(((struct lys_node_inout *)tpdf_parent)->tpdf,\n ((struct lys_node_inout *)tpdf_parent)->tpdf_size, \"typedefs\");\n break;\n case NOTIFICATION_KEYWORD:\n YANG_ADDELEM(((struct lys_node_notif *)tpdf_parent)->tpdf,\n ((struct lys_node_notif *)tpdf_parent)->tpdf_size, \"typedefs\");\n break;\n case EXTENSION_INSTANCE:\n /* typedef is already allocated */\n break;\n default:\n /* another type of nodetype is error*/\n LOGINT(trg->ctx);\n free(s);\n YYABORT;\n }\n ((struct lys_tpdf *)actual)->name = lydict_insert_zc(param->module->ctx, s);\n ((struct lys_tpdf *)actual)->module = trg;\n s = NULL;\n actual_type = TYPEDEF_KEYWORD;\n }\n\n break;\n\n case 141:\n\n { if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) {\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"type\", \"typedef\");\n YYABORT;\n }\n actual_type = (yyvsp[-4].backup_token).token;\n actual = (yyvsp[-4].backup_token).actual;\n }\n\n break;\n\n case 142:\n\n { (yyval.nodes).node.ptr_tpdf = actual;\n (yyval.nodes).node.flag = 0;\n }\n\n break;\n\n case 143:\n\n { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF;\n (yyval.nodes) = (yyvsp[-2].nodes);\n }\n\n break;\n\n case 144:\n\n { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, TYPEDEF_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 145:\n\n { if (yang_read_default(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, TYPEDEF_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 146:\n\n { if ((yyvsp[-1].nodes).node.ptr_tpdf->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"status\", \"typedef\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_tpdf->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 147:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, \"typedef\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 148:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, \"typedef\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 149:\n\n { actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 150:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_type(trg->ctx, actual, s, actual_type))) {\n YYABORT;\n }\n s = NULL;\n actual_type = TYPE_KEYWORD;\n }\n\n break;\n\n case 153:\n\n { if (((struct yang_type *)actual)->base == LY_TYPE_STRING &&\n ((struct yang_type *)actual)->type->info.str.pat_count) {\n void *tmp;\n\n tmp = realloc(((struct yang_type *)actual)->type->info.str.patterns,\n ((struct yang_type *)actual)->type->info.str.pat_count * sizeof *((struct yang_type *)actual)->type->info.str.patterns);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct yang_type *)actual)->type->info.str.patterns = tmp;\n\n#ifdef LY_ENABLED_CACHE\n if (!(trg->ctx->models.flags & LY_CTX_TRUSTED) && ((struct yang_type *)actual)->type->info.str.patterns_pcre) {\n tmp = realloc(((struct yang_type *)actual)->type->info.str.patterns_pcre,\n 2 * ((struct yang_type *)actual)->type->info.str.pat_count * sizeof *((struct yang_type *)actual)->type->info.str.patterns_pcre);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct yang_type *)actual)->type->info.str.patterns_pcre = tmp;\n }\n#endif\n }\n if (((struct yang_type *)actual)->base == LY_TYPE_UNION) {\n struct lys_type *tmp;\n\n tmp = realloc(((struct yang_type *)actual)->type->info.uni.types,\n ((struct yang_type *)actual)->type->info.uni.count * sizeof *tmp);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct yang_type *)actual)->type->info.uni.types = tmp;\n }\n if (((struct yang_type *)actual)->base == LY_TYPE_IDENT) {\n struct lys_ident **tmp;\n\n tmp = realloc(((struct yang_type *)actual)->type->info.ident.ref,\n ((struct yang_type *)actual)->type->info.ident.count* sizeof *tmp);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct yang_type *)actual)->type->info.ident.ref = tmp;\n }\n }\n\n break;\n\n case 157:\n\n { if (yang_read_require_instance(trg->ctx, actual, (yyvsp[0].i))) {\n YYABORT;\n }\n }\n\n break;\n\n case 158:\n\n { /* leafref_specification */\n if (yang_read_leafref_path(trg, actual, s)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 159:\n\n { /* identityref_specification */\n if (((struct yang_type *)actual)->base && ((struct yang_type *)actual)->base != LY_TYPE_IDENT) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, \"base\");\n return EXIT_FAILURE;\n }\n ((struct yang_type *)actual)->base = LY_TYPE_IDENT;\n yang_type = actual;\n YANG_ADDELEM(((struct yang_type *)actual)->type->info.ident.ref,\n ((struct yang_type *)actual)->type->info.ident.count, \"identity refs\");\n *((struct lys_ident **)actual) = (struct lys_ident *)s;\n actual = yang_type;\n s = NULL;\n }\n\n break;\n\n case 162:\n\n { if (yang_read_fraction(trg->ctx, actual, (yyvsp[0].uint))) {\n YYABORT;\n }\n }\n\n break;\n\n case 165:\n\n { actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 166:\n\n { struct yang_type *stype = (struct yang_type *)actual;\n\n (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (stype->base != 0 && stype->base != LY_TYPE_UNION) {\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Unexpected type statement.\");\n YYABORT;\n }\n stype->base = LY_TYPE_UNION;\n if (strcmp(stype->name, \"union\")) {\n /* type can be a substatement only in \"union\" type, not in derived types */\n LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, \"type\", \"derived type\");\n YYABORT;\n }\n YANG_ADDELEM(stype->type->info.uni.types, stype->type->info.uni.count, \"union types\")\n actual_type = UNION_KEYWORD;\n }\n\n break;\n\n case 167:\n\n { (yyval.uint) = (yyvsp[0].uint);\n backup_type = actual_type;\n actual_type = FRACTION_DIGITS_KEYWORD;\n }\n\n break;\n\n case 168:\n\n { (yyval.uint) = (yyvsp[-1].uint); }\n\n break;\n\n case 169:\n\n { (yyval.uint) = (yyvsp[-1].uint); }\n\n break;\n\n case 170:\n\n { char *endptr = NULL;\n unsigned long val;\n errno = 0;\n\n val = strtoul(s, &endptr, 10);\n if (*endptr || s[0] == '-' || errno || val == 0 || val > UINT32_MAX) {\n LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, \"fraction-digits\");\n free(s);\n s = NULL;\n YYABORT;\n }\n (yyval.uint) = (uint32_t) val;\n free(s);\n s =NULL;\n }\n\n break;\n\n case 171:\n\n { actual = (yyvsp[-1].backup_token).actual;\n actual_type = (yyvsp[-1].backup_token).token;\n }\n\n break;\n\n case 172:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_length(trg->ctx, actual, s, is_ext_instance))) {\n YYABORT;\n }\n actual_type = LENGTH_KEYWORD;\n s = NULL;\n }\n\n break;\n\n case 175:\n\n { switch (actual_type) {\n case MUST_KEYWORD:\n (yyval.str) = \"must\";\n break;\n case LENGTH_KEYWORD:\n (yyval.str) = \"length\";\n break;\n case RANGE_KEYWORD:\n (yyval.str) = \"range\";\n break;\n default:\n LOGINT(trg->ctx);\n YYABORT;\n break;\n }\n }\n\n break;\n\n case 176:\n\n { if (yang_read_message(trg, actual, s, (yyvsp[-1].str), ERROR_MESSAGE_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 177:\n\n { if (yang_read_message(trg, actual, s, (yyvsp[-1].str), ERROR_APP_TAG_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 178:\n\n { if (yang_read_description(trg, actual, s, (yyvsp[-1].str), NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 179:\n\n { if (yang_read_reference(trg, actual, s, (yyvsp[-1].str), NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 180:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n }\n\n break;\n\n case 181:\n\n {struct lys_restr *pattern = actual;\n actual = NULL;\n#ifdef LY_ENABLED_CACHE\n if ((yyvsp[-2].backup_token).token != EXTENSION_INSTANCE &&\n !(data_node && data_node->nodetype != LYS_GROUPING && lys_ingrouping(data_node))) {\n unsigned int c = 2 * (((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.pat_count - 1);\n YANG_ADDELEM(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre, c, \"patterns\");\n ++c;\n YANG_ADDELEM(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre, c, \"patterns\");\n actual = &(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre)[2 * (((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.pat_count - 1)];\n }\n#endif\n if (yang_read_pattern(trg->ctx, pattern, actual, (yyvsp[-1].str), (yyvsp[0].ch))) {\n YYABORT;\n }\n actual_type = (yyvsp[-2].backup_token).token;\n actual = (yyvsp[-2].backup_token).actual;\n }\n\n break;\n\n case 182:\n\n { if (actual_type != EXTENSION_INSTANCE) {\n if (((struct yang_type *)actual)->base != 0 && ((struct yang_type *)actual)->base != LY_TYPE_STRING) {\n free(s);\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Unexpected pattern statement.\");\n YYABORT;\n }\n ((struct yang_type *)actual)->base = LY_TYPE_STRING;\n YANG_ADDELEM(((struct yang_type *)actual)->type->info.str.patterns,\n ((struct yang_type *)actual)->type->info.str.pat_count, \"patterns\");\n }\n (yyval.str) = s;\n s = NULL;\n actual_type = PATTERN_KEYWORD;\n }\n\n break;\n\n case 183:\n\n { (yyval.ch) = 0x06; }\n\n break;\n\n case 184:\n\n { (yyval.ch) = (yyvsp[-1].ch); }\n\n break;\n\n case 185:\n\n { (yyval.ch) = 0x06; /* ACK */ }\n\n break;\n\n case 186:\n\n { if (trg->version < 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, \"modifier\");\n YYABORT;\n }\n if ((yyvsp[-1].ch) != 0x06) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"modifier\", \"pattern\");\n YYABORT;\n }\n (yyval.ch) = (yyvsp[0].ch);\n }\n\n break;\n\n case 187:\n\n { if (yang_read_message(trg, actual, s, \"pattern\", ERROR_MESSAGE_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 188:\n\n { if (yang_read_message(trg, actual, s, \"pattern\", ERROR_APP_TAG_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 189:\n\n { if (yang_read_description(trg, actual, s, \"pattern\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 190:\n\n { if (yang_read_reference(trg, actual, s, \"pattern\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 191:\n\n { backup_type = actual_type;\n actual_type = MODIFIER_KEYWORD;\n }\n\n break;\n\n case 192:\n\n { if (!strcmp(s, \"invert-match\")) {\n (yyval.ch) = 0x15;\n free(s);\n s = NULL;\n } else {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, s);\n free(s);\n YYABORT;\n }\n }\n\n break;\n\n case 193:\n\n { struct lys_type_enum * tmp;\n\n cnt_val = 0;\n tmp = realloc(((struct yang_type *)actual)->type->info.enums.enm,\n ((struct yang_type *)actual)->type->info.enums.count * sizeof *tmp);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct yang_type *)actual)->type->info.enums.enm = tmp;\n }\n\n break;\n\n case 196:\n\n { if (yang_check_enum(trg->ctx, yang_type, actual, &cnt_val, is_value)) {\n YYABORT;\n }\n actual = (yyvsp[-1].backup_token).actual;\n actual_type = (yyvsp[-1].backup_token).token;\n }\n\n break;\n\n case 197:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = yang_type = actual;\n YANG_ADDELEM(((struct yang_type *)actual)->type->info.enums.enm, ((struct yang_type *)actual)->type->info.enums.count, \"enums\");\n if (yang_read_enum(trg->ctx, yang_type, actual, s)) {\n YYABORT;\n }\n s = NULL;\n is_value = 0;\n actual_type = ENUM_KEYWORD;\n }\n\n break;\n\n case 199:\n\n { if (((struct lys_type_enum *)actual)->iffeature_size) {\n struct lys_iffeature *tmp;\n\n tmp = realloc(((struct lys_type_enum *)actual)->iffeature,\n ((struct lys_type_enum *)actual)->iffeature_size * sizeof *tmp);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct lys_type_enum *)actual)->iffeature = tmp;\n }\n }\n\n break;\n\n case 202:\n\n { if (is_value) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"value\", \"enum\");\n YYABORT;\n }\n ((struct lys_type_enum *)actual)->value = (yyvsp[0].i);\n\n /* keep the highest enum value for automatic increment */\n if ((yyvsp[0].i) >= cnt_val) {\n cnt_val = (yyvsp[0].i) + 1;\n }\n is_value = 1;\n }\n\n break;\n\n case 203:\n\n { if (((struct lys_type_enum *)actual)->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"status\", \"enum\");\n YYABORT;\n }\n ((struct lys_type_enum *)actual)->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 204:\n\n { if (yang_read_description(trg, actual, s, \"enum\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 205:\n\n { if (yang_read_reference(trg, actual, s, \"enum\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 206:\n\n { (yyval.i) = (yyvsp[0].i);\n backup_type = actual_type;\n actual_type = VALUE_KEYWORD;\n }\n\n break;\n\n case 207:\n\n { (yyval.i) = (yyvsp[-1].i); }\n\n break;\n\n case 208:\n\n { (yyval.i) = (yyvsp[-1].i); }\n\n break;\n\n case 209:\n\n { /* convert it to int32_t */\n int64_t val;\n char *endptr;\n\n val = strtoll(s, &endptr, 10);\n if (val < INT32_MIN || val > INT32_MAX || *endptr) {\n LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, \"value\");\n free(s);\n YYABORT;\n }\n free(s);\n s = NULL;\n (yyval.i) = (int32_t) val;\n }\n\n break;\n\n case 210:\n\n { actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 213:\n\n { backup_type = actual_type;\n actual_type = PATH_KEYWORD;\n }\n\n break;\n\n case 215:\n\n { (yyval.i) = (yyvsp[0].i);\n backup_type = actual_type;\n actual_type = REQUIRE_INSTANCE_KEYWORD;\n }\n\n break;\n\n case 216:\n\n { (yyval.i) = (yyvsp[-1].i); }\n\n break;\n\n case 217:\n\n { (yyval.i) = 1; }\n\n break;\n\n case 218:\n\n { (yyval.i) = -1; }\n\n break;\n\n case 219:\n\n { if (!strcmp(s,\"true\")) {\n (yyval.i) = 1;\n } else if (!strcmp(s,\"false\")) {\n (yyval.i) = -1;\n } else {\n LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, \"require-instance\");\n free(s);\n YYABORT;\n }\n free(s);\n s = NULL;\n }\n\n break;\n\n case 220:\n\n { struct lys_type_bit * tmp;\n\n cnt_val = 0;\n tmp = realloc(((struct yang_type *)actual)->type->info.bits.bit,\n ((struct yang_type *)actual)->type->info.bits.count * sizeof *tmp);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct yang_type *)actual)->type->info.bits.bit = tmp;\n }\n\n break;\n\n case 223:\n\n { if (yang_check_bit(trg->ctx, yang_type, actual, &cnt_val, is_value)) {\n YYABORT;\n }\n actual = (yyvsp[-2].backup_token).actual;\n actual_type = (yyvsp[-2].backup_token).token;\n }\n\n break;\n\n case 224:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = yang_type = actual;\n YANG_ADDELEM(((struct yang_type *)actual)->type->info.bits.bit,\n ((struct yang_type *)actual)->type->info.bits.count, \"bits\");\n if (yang_read_bit(trg->ctx, yang_type, actual, s)) {\n YYABORT;\n }\n s = NULL;\n is_value = 0;\n actual_type = BIT_KEYWORD;\n }\n\n break;\n\n case 226:\n\n { if (((struct lys_type_bit *)actual)->iffeature_size) {\n struct lys_iffeature *tmp;\n\n tmp = realloc(((struct lys_type_bit *)actual)->iffeature,\n ((struct lys_type_bit *)actual)->iffeature_size * sizeof *tmp);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct lys_type_bit *)actual)->iffeature = tmp;\n }\n }\n\n break;\n\n case 229:\n\n { if (is_value) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"position\", \"bit\");\n YYABORT;\n }\n ((struct lys_type_bit *)actual)->pos = (yyvsp[0].uint);\n\n /* keep the highest position value for automatic increment */\n if ((yyvsp[0].uint) >= cnt_val) {\n cnt_val = (yyvsp[0].uint) + 1;\n }\n is_value = 1;\n }\n\n break;\n\n case 230:\n\n { if (((struct lys_type_bit *)actual)->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"status\", \"bit\");\n YYABORT;\n }\n ((struct lys_type_bit *)actual)->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 231:\n\n { if (yang_read_description(trg, actual, s, \"bit\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 232:\n\n { if (yang_read_reference(trg, actual, s, \"bit\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 233:\n\n { (yyval.uint) = (yyvsp[0].uint);\n backup_type = actual_type;\n actual_type = POSITION_KEYWORD;\n }\n\n break;\n\n case 234:\n\n { (yyval.uint) = (yyvsp[-1].uint); }\n\n break;\n\n case 235:\n\n { (yyval.uint) = (yyvsp[-1].uint); }\n\n break;\n\n case 236:\n\n { /* convert it to uint32_t */\n unsigned long val;\n char *endptr = NULL;\n errno = 0;\n\n val = strtoul(s, &endptr, 10);\n if (s[0] == '-' || *endptr || errno || val > UINT32_MAX) {\n LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, \"position\");\n free(s);\n YYABORT;\n }\n free(s);\n s = NULL;\n (yyval.uint) = (uint32_t) val;\n }\n\n break;\n\n case 237:\n\n { backup_type = actual_type;\n actual_type = ERROR_MESSAGE_KEYWORD;\n }\n\n break;\n\n case 239:\n\n { backup_type = actual_type;\n actual_type = ERROR_APP_TAG_KEYWORD;\n }\n\n break;\n\n case 241:\n\n { backup_type = actual_type;\n actual_type = UNITS_KEYWORD;\n }\n\n break;\n\n case 243:\n\n { backup_type = actual_type;\n actual_type = DEFAULT_KEYWORD;\n }\n\n break;\n\n case 245:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_GROUPING, sizeof(struct lys_node_grp)))) {\n YYABORT;\n }\n s = NULL;\n data_node = actual;\n actual_type = GROUPING_KEYWORD;\n }\n\n break;\n\n case 246:\n\n { LOGDBG(LY_LDGYANG, \"finished parsing grouping statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n data_node = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 249:\n\n { (yyval.nodes).grouping = actual; }\n\n break;\n\n case 250:\n\n { if ((yyvsp[-1].nodes).grouping->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).grouping, \"status\", \"grouping\");\n YYABORT;\n }\n (yyvsp[-1].nodes).grouping->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 251:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).grouping, s, \"grouping\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 252:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).grouping, s, \"grouping\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 257:\n\n { if (trg->version < 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).grouping, \"notification\");\n YYABORT;\n }\n }\n\n break;\n\n case 266:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CONTAINER, sizeof(struct lys_node_container)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = CONTAINER_KEYWORD;\n }\n\n break;\n\n case 267:\n\n { LOGDBG(LY_LDGYANG, \"finished parsing container statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n data_node = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 269:\n\n { void *tmp;\n\n if ((yyvsp[-1].nodes).container->iffeature_size) {\n tmp = realloc((yyvsp[-1].nodes).container->iffeature, (yyvsp[-1].nodes).container->iffeature_size * sizeof *(yyvsp[-1].nodes).container->iffeature);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).container->iffeature = tmp;\n }\n\n if ((yyvsp[-1].nodes).container->must_size) {\n tmp = realloc((yyvsp[-1].nodes).container->must, (yyvsp[-1].nodes).container->must_size * sizeof *(yyvsp[-1].nodes).container->must);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).container->must = tmp;\n }\n }\n\n break;\n\n case 270:\n\n { (yyval.nodes).container = actual; }\n\n break;\n\n case 274:\n\n { if (yang_read_presence(trg, (yyvsp[-1].nodes).container, s)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 275:\n\n { if ((yyvsp[-1].nodes).container->flags & LYS_CONFIG_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).container, \"config\", \"container\");\n YYABORT;\n }\n (yyvsp[-1].nodes).container->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 276:\n\n { if ((yyvsp[-1].nodes).container->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).container, \"status\", \"container\");\n YYABORT;\n }\n (yyvsp[-1].nodes).container->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 277:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).container, s, \"container\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 278:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).container, s, \"container\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 281:\n\n { if (trg->version < 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).container, \"notification\");\n YYABORT;\n }\n }\n\n break;\n\n case 284:\n\n { void *tmp;\n\n if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) {\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, \"type\", \"leaf\");\n YYABORT;\n }\n if ((yyvsp[-1].nodes).node.ptr_leaf->dflt && ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_MAND_TRUE)) {\n /* RFC 6020, 7.6.4 - default statement must not with mandatory true */\n LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, \"mandatory\", \"leaf\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, \"The \\\"mandatory\\\" statement is forbidden on leaf with \\\"default\\\".\");\n YYABORT;\n }\n\n if ((yyvsp[-1].nodes).node.ptr_leaf->iffeature_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_leaf->iffeature, (yyvsp[-1].nodes).node.ptr_leaf->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaf->iffeature);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_leaf->iffeature = tmp;\n }\n\n if ((yyvsp[-1].nodes).node.ptr_leaf->must_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_leaf->must, (yyvsp[-1].nodes).node.ptr_leaf->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaf->must);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_leaf->must = tmp;\n }\n\n LOGDBG(LY_LDGYANG, \"finished parsing leaf statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-4].backup_token).token;\n actual = (yyvsp[-4].backup_token).actual;\n data_node = (yyvsp[-4].backup_token).actual;\n }\n\n break;\n\n case 285:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LEAF, sizeof(struct lys_node_leaf)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = LEAF_KEYWORD;\n }\n\n break;\n\n case 286:\n\n { (yyval.nodes).node.ptr_leaf = actual;\n (yyval.nodes).node.flag = 0;\n }\n\n break;\n\n case 289:\n\n { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF;\n (yyval.nodes) = (yyvsp[-2].nodes);\n }\n\n break;\n\n case 290:\n\n { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, LEAF_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 292:\n\n { if (yang_read_default(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, LEAF_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 293:\n\n { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_CONFIG_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, \"config\", \"leaf\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 294:\n\n { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_MAND_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, \"mandatory\", \"leaf\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 295:\n\n { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, \"status\", \"leaf\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 296:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, \"leaf\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 297:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, \"leaf\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 298:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LEAFLIST, sizeof(struct lys_node_leaflist)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = LEAF_LIST_KEYWORD;\n }\n\n break;\n\n case 299:\n\n { void *tmp;\n\n if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_CONFIG_R) {\n /* RFC 6020, 7.7.5 - ignore ordering when the list represents state data\n * ignore oredering MASK - 0x7F\n */\n (yyvsp[-1].nodes).node.ptr_leaflist->flags &= 0x7F;\n }\n if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) {\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, \"type\", \"leaf-list\");\n YYABORT;\n }\n if ((yyvsp[-1].nodes).node.ptr_leaflist->dflt_size && (yyvsp[-1].nodes).node.ptr_leaflist->min) {\n LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, \"min-elements\", \"leaf-list\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist,\n \"The \\\"min-elements\\\" statement with non-zero value is forbidden on leaf-lists with the \\\"default\\\" statement.\");\n YYABORT;\n }\n\n if ((yyvsp[-1].nodes).node.ptr_leaflist->iffeature_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->iffeature, (yyvsp[-1].nodes).node.ptr_leaflist->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->iffeature);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_leaflist->iffeature = tmp;\n }\n\n if ((yyvsp[-1].nodes).node.ptr_leaflist->must_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->must, (yyvsp[-1].nodes).node.ptr_leaflist->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->must);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_leaflist->must = tmp;\n }\n\n if ((yyvsp[-1].nodes).node.ptr_leaflist->dflt_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->dflt, (yyvsp[-1].nodes).node.ptr_leaflist->dflt_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->dflt);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_leaflist->dflt = tmp;\n }\n\n LOGDBG(LY_LDGYANG, \"finished parsing leaf-list statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-4].backup_token).token;\n actual = (yyvsp[-4].backup_token).actual;\n data_node = (yyvsp[-4].backup_token).actual;\n }\n\n break;\n\n case 300:\n\n { (yyval.nodes).node.ptr_leaflist = actual;\n (yyval.nodes).node.flag = 0;\n }\n\n break;\n\n case 303:\n\n { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF;\n (yyval.nodes) = (yyvsp[-2].nodes);\n }\n\n break;\n\n case 304:\n\n { if (trg->version < 2) {\n free(s);\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, \"default\");\n YYABORT;\n }\n YANG_ADDELEM((yyvsp[-1].nodes).node.ptr_leaflist->dflt,\n (yyvsp[-1].nodes).node.ptr_leaflist->dflt_size, \"defaults\");\n (*(const char **)actual) = lydict_insert_zc(param->module->ctx, s);\n s = NULL;\n actual = (yyvsp[-1].nodes).node.ptr_leaflist;\n }\n\n break;\n\n case 305:\n\n { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, LEAF_LIST_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 307:\n\n { if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_CONFIG_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, \"config\", \"leaf-list\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_leaflist->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 308:\n\n { if ((yyvsp[-1].nodes).node.flag & LYS_MIN_ELEMENTS) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, \"min-elements\", \"leaf-list\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_leaflist->min = (yyvsp[0].uint);\n (yyvsp[-1].nodes).node.flag |= LYS_MIN_ELEMENTS;\n (yyval.nodes) = (yyvsp[-1].nodes);\n if ((yyvsp[-1].nodes).node.ptr_leaflist->max && ((yyvsp[-1].nodes).node.ptr_leaflist->min > (yyvsp[-1].nodes).node.ptr_leaflist->max)) {\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, \"Invalid value \\\"%d\\\" of \\\"%s\\\".\", (yyvsp[0].uint), \"min-elements\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, \"\\\"min-elements\\\" is bigger than \\\"max-elements\\\".\");\n YYABORT;\n }\n }\n\n break;\n\n case 309:\n\n { if ((yyvsp[-1].nodes).node.flag & LYS_MAX_ELEMENTS) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, \"max-elements\", \"leaf-list\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_leaflist->max = (yyvsp[0].uint);\n (yyvsp[-1].nodes).node.flag |= LYS_MAX_ELEMENTS;\n (yyval.nodes) = (yyvsp[-1].nodes);\n if ((yyvsp[-1].nodes).node.ptr_leaflist->min > (yyvsp[-1].nodes).node.ptr_leaflist->max) {\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, \"Invalid value \\\"%d\\\" of \\\"%s\\\".\", (yyvsp[0].uint), \"max-elements\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, \"\\\"max-elements\\\" is smaller than \\\"min-elements\\\".\");\n YYABORT;\n }\n }\n\n break;\n\n case 310:\n\n { if ((yyvsp[-1].nodes).node.flag & LYS_ORDERED_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, \"ordered by\", \"leaf-list\");\n YYABORT;\n }\n if ((yyvsp[0].i) & LYS_USERORDERED) {\n (yyvsp[-1].nodes).node.ptr_leaflist->flags |= LYS_USERORDERED;\n }\n (yyvsp[-1].nodes).node.flag |= (yyvsp[0].i);\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 311:\n\n { if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, \"status\", \"leaf-list\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_leaflist->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 312:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, \"leaf-list\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 313:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, \"leaf-list\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 314:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LIST, sizeof(struct lys_node_list)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = LIST_KEYWORD;\n }\n\n break;\n\n case 315:\n\n { void *tmp;\n\n if ((yyvsp[-1].nodes).node.ptr_list->iffeature_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_list->iffeature, (yyvsp[-1].nodes).node.ptr_list->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->iffeature);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_list->iffeature = tmp;\n }\n\n if ((yyvsp[-1].nodes).node.ptr_list->must_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_list->must, (yyvsp[-1].nodes).node.ptr_list->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->must);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_list->must = tmp;\n }\n\n if ((yyvsp[-1].nodes).node.ptr_list->tpdf_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_list->tpdf, (yyvsp[-1].nodes).node.ptr_list->tpdf_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->tpdf);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_list->tpdf = tmp;\n }\n\n if ((yyvsp[-1].nodes).node.ptr_list->unique_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_list->unique, (yyvsp[-1].nodes).node.ptr_list->unique_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->unique);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_list->unique = tmp;\n }\n\n LOGDBG(LY_LDGYANG, \"finished parsing list statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-4].backup_token).token;\n actual = (yyvsp[-4].backup_token).actual;\n data_node = (yyvsp[-4].backup_token).actual;\n }\n\n break;\n\n case 316:\n\n { (yyval.nodes).node.ptr_list = actual;\n (yyval.nodes).node.flag = 0;\n }\n\n break;\n\n case 320:\n\n { if ((yyvsp[-1].nodes).node.ptr_list->keys) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, \"key\", \"list\");\n free(s);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_list->keys = (struct lys_node_leaf **)s;\n (yyval.nodes) = (yyvsp[-1].nodes);\n s = NULL;\n }\n\n break;\n\n case 321:\n\n { YANG_ADDELEM((yyvsp[-1].nodes).node.ptr_list->unique, (yyvsp[-1].nodes).node.ptr_list->unique_size, \"uniques\");\n ((struct lys_unique *)actual)->expr = (const char **)s;\n (yyval.nodes) = (yyvsp[-1].nodes);\n s = NULL;\n actual = (yyvsp[-1].nodes).node.ptr_list;\n }\n\n break;\n\n case 322:\n\n { if ((yyvsp[-1].nodes).node.ptr_list->flags & LYS_CONFIG_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, \"config\", \"list\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_list->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 323:\n\n { if ((yyvsp[-1].nodes).node.flag & LYS_MIN_ELEMENTS) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, \"min-elements\", \"list\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_list->min = (yyvsp[0].uint);\n (yyvsp[-1].nodes).node.flag |= LYS_MIN_ELEMENTS;\n (yyval.nodes) = (yyvsp[-1].nodes);\n if ((yyvsp[-1].nodes).node.ptr_list->max && ((yyvsp[-1].nodes).node.ptr_list->min > (yyvsp[-1].nodes).node.ptr_list->max)) {\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, \"Invalid value \\\"%d\\\" of \\\"%s\\\".\", (yyvsp[0].uint), \"min-elements\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, \"\\\"min-elements\\\" is bigger than \\\"max-elements\\\".\");\n YYABORT;\n }\n }\n\n break;\n\n case 324:\n\n { if ((yyvsp[-1].nodes).node.flag & LYS_MAX_ELEMENTS) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, \"max-elements\", \"list\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_list->max = (yyvsp[0].uint);\n (yyvsp[-1].nodes).node.flag |= LYS_MAX_ELEMENTS;\n (yyval.nodes) = (yyvsp[-1].nodes);\n if ((yyvsp[-1].nodes).node.ptr_list->min > (yyvsp[-1].nodes).node.ptr_list->max) {\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, \"Invalid value \\\"%d\\\" of \\\"%s\\\".\", (yyvsp[0].uint), \"min-elements\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, \"\\\"max-elements\\\" is smaller than \\\"min-elements\\\".\");\n YYABORT;\n }\n }\n\n break;\n\n case 325:\n\n { if ((yyvsp[-1].nodes).node.flag & LYS_ORDERED_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, \"ordered by\", \"list\");\n YYABORT;\n }\n if ((yyvsp[0].i) & LYS_USERORDERED) {\n (yyvsp[-1].nodes).node.ptr_list->flags |= LYS_USERORDERED;\n }\n (yyvsp[-1].nodes).node.flag |= (yyvsp[0].i);\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 326:\n\n { if ((yyvsp[-1].nodes).node.ptr_list->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, \"status\", \"list\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_list->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 327:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_list, s, \"list\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 328:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_list, s, \"list\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 332:\n\n { if (trg->version < 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_list, \"notification\");\n YYABORT;\n }\n }\n\n break;\n\n case 334:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CHOICE, sizeof(struct lys_node_choice)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = CHOICE_KEYWORD;\n }\n\n break;\n\n case 335:\n\n { LOGDBG(LY_LDGYANG, \"finished parsing choice statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n data_node = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 337:\n\n { struct lys_iffeature *tmp;\n\n if (((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_MAND_TRUE) && (yyvsp[-1].nodes).node.ptr_choice->dflt) {\n LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, \"default\", \"choice\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, \"The \\\"default\\\" statement is forbidden on choices with \\\"mandatory\\\".\");\n YYABORT;\n }\n\n if ((yyvsp[-1].nodes).node.ptr_choice->iffeature_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_choice->iffeature, (yyvsp[-1].nodes).node.ptr_choice->iffeature_size * sizeof *tmp);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_choice->iffeature = tmp;\n }\n }\n\n break;\n\n case 338:\n\n { (yyval.nodes).node.ptr_choice = actual;\n (yyval.nodes).node.flag = 0;\n }\n\n break;\n\n case 341:\n\n { if ((yyvsp[-1].nodes).node.flag & LYS_CHOICE_DEFAULT) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, \"default\", \"choice\");\n free(s);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_choice->dflt = (struct lys_node *) s;\n s = NULL;\n (yyval.nodes) = (yyvsp[-1].nodes);\n (yyval.nodes).node.flag |= LYS_CHOICE_DEFAULT;\n }\n\n break;\n\n case 342:\n\n { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_CONFIG_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, \"config\", \"choice\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i);\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 343:\n\n { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_MAND_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, \"mandatory\", \"choice\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i);\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 344:\n\n { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, \"status\", \"choice\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i);\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 345:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_choice, s, \"choice\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 346:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_choice, s, \"choice\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 356:\n\n { if (trg->version < 2 ) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, \"choice\");\n YYABORT;\n }\n }\n\n break;\n\n case 357:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CASE, sizeof(struct lys_node_case)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = CASE_KEYWORD;\n }\n\n break;\n\n case 358:\n\n { LOGDBG(LY_LDGYANG, \"finished parsing case statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n data_node = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 360:\n\n { struct lys_iffeature *tmp;\n\n if ((yyvsp[-1].nodes).cs->iffeature_size) {\n tmp = realloc((yyvsp[-1].nodes).cs->iffeature, (yyvsp[-1].nodes).cs->iffeature_size * sizeof *tmp);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).cs->iffeature = tmp;\n }\n }\n\n break;\n\n case 361:\n\n { (yyval.nodes).cs = actual; }\n\n break;\n\n case 364:\n\n { if ((yyvsp[-1].nodes).cs->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).cs, \"status\", \"case\");\n YYABORT;\n }\n (yyvsp[-1].nodes).cs->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 365:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).cs, s, \"case\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 366:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).cs, s, \"case\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 368:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ANYXML, sizeof(struct lys_node_anydata)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = ANYXML_KEYWORD;\n }\n\n break;\n\n case 369:\n\n { LOGDBG(LY_LDGYANG, \"finished parsing anyxml statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n data_node = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 370:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ANYDATA, sizeof(struct lys_node_anydata)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = ANYDATA_KEYWORD;\n }\n\n break;\n\n case 371:\n\n { LOGDBG(LY_LDGYANG, \"finished parsing anydata statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n data_node = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 373:\n\n { void *tmp;\n\n if ((yyvsp[-1].nodes).node.ptr_anydata->iffeature_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_anydata->iffeature, (yyvsp[-1].nodes).node.ptr_anydata->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_anydata->iffeature);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_anydata->iffeature = tmp;\n }\n\n if ((yyvsp[-1].nodes).node.ptr_anydata->must_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_anydata->must, (yyvsp[-1].nodes).node.ptr_anydata->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_anydata->must);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_anydata->must = tmp;\n }\n }\n\n break;\n\n case 374:\n\n { (yyval.nodes).node.ptr_anydata = actual;\n (yyval.nodes).node.flag = actual_type;\n }\n\n break;\n\n case 378:\n\n { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_CONFIG_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, \"config\",\n ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? \"anyxml\" : \"anydata\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 379:\n\n { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_MAND_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, \"mandatory\",\n ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? \"anyxml\" : \"anydata\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 380:\n\n { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, \"status\",\n ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? \"anyxml\" : \"anydata\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 381:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_anydata, s, ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? \"anyxml\" : \"anydata\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 382:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_anydata, s, ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? \"anyxml\" : \"anydata\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 383:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_USES, sizeof(struct lys_node_uses)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = USES_KEYWORD;\n }\n\n break;\n\n case 384:\n\n { LOGDBG(LY_LDGYANG, \"finished parsing uses statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n data_node = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 386:\n\n { void *tmp;\n\n if ((yyvsp[-1].nodes).uses->iffeature_size) {\n tmp = realloc((yyvsp[-1].nodes).uses->iffeature, (yyvsp[-1].nodes).uses->iffeature_size * sizeof *(yyvsp[-1].nodes).uses->iffeature);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).uses->iffeature = tmp;\n }\n\n if ((yyvsp[-1].nodes).uses->refine_size) {\n tmp = realloc((yyvsp[-1].nodes).uses->refine, (yyvsp[-1].nodes).uses->refine_size * sizeof *(yyvsp[-1].nodes).uses->refine);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).uses->refine = tmp;\n }\n\n if ((yyvsp[-1].nodes).uses->augment_size) {\n tmp = realloc((yyvsp[-1].nodes).uses->augment, (yyvsp[-1].nodes).uses->augment_size * sizeof *(yyvsp[-1].nodes).uses->augment);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).uses->augment = tmp;\n }\n }\n\n break;\n\n case 387:\n\n { (yyval.nodes).uses = actual; }\n\n break;\n\n case 390:\n\n { if ((yyvsp[-1].nodes).uses->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).uses, \"status\", \"uses\");\n YYABORT;\n }\n (yyvsp[-1].nodes).uses->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 391:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).uses, s, \"uses\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 392:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).uses, s, \"uses\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 397:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n YANG_ADDELEM(((struct lys_node_uses *)actual)->refine,\n ((struct lys_node_uses *)actual)->refine_size, \"refines\");\n ((struct lys_refine *)actual)->target_name = transform_schema2json(trg, s);\n free(s);\n s = NULL;\n if (!((struct lys_refine *)actual)->target_name) {\n YYABORT;\n }\n actual_type = REFINE_KEYWORD;\n }\n\n break;\n\n case 398:\n\n { actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 400:\n\n { void *tmp;\n\n if ((yyvsp[-1].nodes).refine->iffeature_size) {\n tmp = realloc((yyvsp[-1].nodes).refine->iffeature, (yyvsp[-1].nodes).refine->iffeature_size * sizeof *(yyvsp[-1].nodes).refine->iffeature);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).refine->iffeature = tmp;\n }\n\n if ((yyvsp[-1].nodes).refine->must_size) {\n tmp = realloc((yyvsp[-1].nodes).refine->must, (yyvsp[-1].nodes).refine->must_size * sizeof *(yyvsp[-1].nodes).refine->must);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).refine->must = tmp;\n }\n\n if ((yyvsp[-1].nodes).refine->dflt_size) {\n tmp = realloc((yyvsp[-1].nodes).refine->dflt, (yyvsp[-1].nodes).refine->dflt_size * sizeof *(yyvsp[-1].nodes).refine->dflt);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).refine->dflt = tmp;\n }\n }\n\n break;\n\n case 401:\n\n { (yyval.nodes).refine = actual;\n actual_type = REFINE_KEYWORD;\n }\n\n break;\n\n case 402:\n\n { actual = (yyvsp[-2].nodes).refine;\n actual_type = REFINE_KEYWORD;\n if ((yyvsp[-2].nodes).refine->target_type) {\n if ((yyvsp[-2].nodes).refine->target_type & (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML)) {\n (yyvsp[-2].nodes).refine->target_type &= (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML);\n } else {\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"must\", \"refine\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Invalid refine target nodetype for the substatements.\");\n YYABORT;\n }\n } else {\n (yyvsp[-2].nodes).refine->target_type = LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML;\n }\n }\n\n break;\n\n case 403:\n\n { /* leaf, leaf-list, list, container or anyxml */\n /* check possibility of statements combination */\n if ((yyvsp[-2].nodes).refine->target_type) {\n if ((yyvsp[-2].nodes).refine->target_type & (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA)) {\n (yyvsp[-2].nodes).refine->target_type &= (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA);\n } else {\n free(s);\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"if-feature\", \"refine\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Invalid refine target nodetype for the substatements.\");\n YYABORT;\n }\n } else {\n (yyvsp[-2].nodes).refine->target_type = LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA;\n }\n }\n\n break;\n\n case 404:\n\n { if ((yyvsp[-1].nodes).refine->target_type) {\n if ((yyvsp[-1].nodes).refine->target_type & LYS_CONTAINER) {\n if ((yyvsp[-1].nodes).refine->mod.presence) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"presence\", \"refine\");\n free(s);\n YYABORT;\n }\n (yyvsp[-1].nodes).refine->target_type = LYS_CONTAINER;\n (yyvsp[-1].nodes).refine->mod.presence = lydict_insert_zc(trg->ctx, s);\n } else {\n free(s);\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"presence\", \"refine\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Invalid refine target nodetype for the substatements.\");\n YYABORT;\n }\n } else {\n (yyvsp[-1].nodes).refine->target_type = LYS_CONTAINER;\n (yyvsp[-1].nodes).refine->mod.presence = lydict_insert_zc(trg->ctx, s);\n }\n s = NULL;\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 405:\n\n { int i;\n\n if ((yyvsp[-1].nodes).refine->dflt_size) {\n if (trg->version < 2) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"default\", \"refine\");\n YYABORT;\n }\n if ((yyvsp[-1].nodes).refine->target_type & LYS_LEAFLIST) {\n (yyvsp[-1].nodes).refine->target_type = LYS_LEAFLIST;\n } else {\n free(s);\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"default\", \"refine\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Invalid refine target nodetype for the substatements.\");\n YYABORT;\n }\n } else {\n if ((yyvsp[-1].nodes).refine->target_type) {\n if (trg->version < 2 && ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE))) {\n (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE);\n } if (trg->version > 1 && ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE))) {\n /* YANG 1.1 */\n (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE);\n } else {\n free(s);\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"default\", \"refine\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Invalid refine target nodetype for the substatements.\");\n YYABORT;\n }\n } else {\n if (trg->version < 2) {\n (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE;\n } else {\n /* YANG 1.1 */\n (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE;\n }\n }\n }\n /* check for duplicity */\n for (i = 0; i < (yyvsp[-1].nodes).refine->dflt_size; ++i) {\n if (ly_strequal((yyvsp[-1].nodes).refine->dflt[i], s, 0)) {\n LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, \"default\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Duplicated default value \\\"%s\\\".\", s);\n YYABORT;\n }\n }\n YANG_ADDELEM((yyvsp[-1].nodes).refine->dflt, (yyvsp[-1].nodes).refine->dflt_size, \"defaults\");\n *((const char **)actual) = lydict_insert_zc(trg->ctx, s);\n actual = (yyvsp[-1].nodes).refine;\n s = NULL;\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 406:\n\n { if ((yyvsp[-1].nodes).refine->target_type) {\n if ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST)) {\n (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST);\n if ((yyvsp[-1].nodes).refine->flags & LYS_CONFIG_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"config\", \"refine\");\n YYABORT;\n }\n (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i);\n } else {\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"config\", \"refine\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Invalid refine target nodetype for the substatements.\");\n YYABORT;\n }\n } else {\n (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST;\n (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i);\n }\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 407:\n\n { if ((yyvsp[-1].nodes).refine->target_type) {\n if ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE | LYS_ANYXML)) {\n (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE | LYS_ANYXML);\n if ((yyvsp[-1].nodes).refine->flags & LYS_MAND_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"mandatory\", \"refine\");\n YYABORT;\n }\n (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i);\n } else {\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"mandatory\", \"refine\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Invalid refine target nodetype for the substatements.\");\n YYABORT;\n }\n } else {\n (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE | LYS_ANYXML;\n (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i);\n }\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 408:\n\n { if ((yyvsp[-1].nodes).refine->target_type) {\n if ((yyvsp[-1].nodes).refine->target_type & (LYS_LIST | LYS_LEAFLIST)) {\n (yyvsp[-1].nodes).refine->target_type &= (LYS_LIST | LYS_LEAFLIST);\n if ((yyvsp[-1].nodes).refine->flags & LYS_RFN_MINSET) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"min-elements\", \"refine\");\n YYABORT;\n }\n (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MINSET;\n (yyvsp[-1].nodes).refine->mod.list.min = (yyvsp[0].uint);\n } else {\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"min-elements\", \"refine\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Invalid refine target nodetype for the substatements.\");\n YYABORT;\n }\n } else {\n (yyvsp[-1].nodes).refine->target_type = LYS_LIST | LYS_LEAFLIST;\n (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MINSET;\n (yyvsp[-1].nodes).refine->mod.list.min = (yyvsp[0].uint);\n }\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 409:\n\n { if ((yyvsp[-1].nodes).refine->target_type) {\n if ((yyvsp[-1].nodes).refine->target_type & (LYS_LIST | LYS_LEAFLIST)) {\n (yyvsp[-1].nodes).refine->target_type &= (LYS_LIST | LYS_LEAFLIST);\n if ((yyvsp[-1].nodes).refine->flags & LYS_RFN_MAXSET) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"max-elements\", \"refine\");\n YYABORT;\n }\n (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MAXSET;\n (yyvsp[-1].nodes).refine->mod.list.max = (yyvsp[0].uint);\n } else {\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"max-elements\", \"refine\");\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Invalid refine target nodetype for the substatements.\");\n YYABORT;\n }\n } else {\n (yyvsp[-1].nodes).refine->target_type = LYS_LIST | LYS_LEAFLIST;\n (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MAXSET;\n (yyvsp[-1].nodes).refine->mod.list.max = (yyvsp[0].uint);\n }\n (yyval.nodes) = (yyvsp[-1].nodes);\n }\n\n break;\n\n case 410:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).refine, s, \"refine\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 411:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).refine, s, \"refine\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 414:\n\n { void *parent;\n\n (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n parent = actual;\n YANG_ADDELEM(((struct lys_node_uses *)actual)->augment,\n ((struct lys_node_uses *)actual)->augment_size, \"augments\");\n if (yang_read_augment(trg, parent, actual, s)) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = AUGMENT_KEYWORD;\n }\n\n break;\n\n case 415:\n\n { LOGDBG(LY_LDGYANG, \"finished parsing augment statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-4].backup_token).token;\n actual = (yyvsp[-4].backup_token).actual;\n data_node = (yyvsp[-4].backup_token).actual;\n }\n\n break;\n\n case 418:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n YANG_ADDELEM(trg->augment, trg->augment_size, \"augments\");\n if (yang_read_augment(trg, NULL, actual, s)) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = AUGMENT_KEYWORD;\n }\n\n break;\n\n case 419:\n\n { LOGDBG(LY_LDGYANG, \"finished parsing augment statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-4].backup_token).token;\n actual = (yyvsp[-4].backup_token).actual;\n data_node = (yyvsp[-4].backup_token).actual;\n }\n\n break;\n\n case 420:\n\n { (yyval.nodes).augment = actual; }\n\n break;\n\n case 423:\n\n { if ((yyvsp[-1].nodes).augment->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).augment, \"status\", \"augment\");\n YYABORT;\n }\n (yyvsp[-1].nodes).augment->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 424:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).augment, s, \"augment\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 425:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).augment, s, \"augment\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 428:\n\n { if (trg->version < 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).augment, \"notification\");\n YYABORT;\n }\n }\n\n break;\n\n case 430:\n\n { if (param->module->version != 2) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, \"action\");\n free(s);\n YYABORT;\n }\n (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ACTION, sizeof(struct lys_node_rpc_action)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = ACTION_KEYWORD;\n }\n\n break;\n\n case 431:\n\n { LOGDBG(LY_LDGYANG, \"finished parsing action statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n data_node = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 432:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, NULL, param->node, s, LYS_RPC, sizeof(struct lys_node_rpc_action)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = RPC_KEYWORD;\n }\n\n break;\n\n case 433:\n\n { LOGDBG(LY_LDGYANG, \"finished parsing rpc statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n data_node = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 435:\n\n { void *tmp;\n\n if ((yyvsp[-1].nodes).node.ptr_rpc->iffeature_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_rpc->iffeature, (yyvsp[-1].nodes).node.ptr_rpc->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_rpc->iffeature);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_rpc->iffeature = tmp;\n }\n\n if ((yyvsp[-1].nodes).node.ptr_rpc->tpdf_size) {\n tmp = realloc((yyvsp[-1].nodes).node.ptr_rpc->tpdf, (yyvsp[-1].nodes).node.ptr_rpc->tpdf_size * sizeof *(yyvsp[-1].nodes).node.ptr_rpc->tpdf);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_rpc->tpdf = tmp;\n }\n }\n\n break;\n\n case 436:\n\n { (yyval.nodes).node.ptr_rpc = actual;\n (yyval.nodes).node.flag = 0;\n }\n\n break;\n\n case 438:\n\n { if ((yyvsp[-1].nodes).node.ptr_rpc->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_rpc, \"status\", \"rpc\");\n YYABORT;\n }\n (yyvsp[-1].nodes).node.ptr_rpc->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 439:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_rpc, s, \"rpc\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 440:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_rpc, s, \"rpc\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 443:\n\n { if ((yyvsp[-2].nodes).node.flag & LYS_RPC_INPUT) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_rpc, \"input\", \"rpc\");\n YYABORT;\n }\n (yyvsp[-2].nodes).node.flag |= LYS_RPC_INPUT;\n (yyval.nodes) = (yyvsp[-2].nodes);\n }\n\n break;\n\n case 444:\n\n { if ((yyvsp[-2].nodes).node.flag & LYS_RPC_OUTPUT) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_rpc, \"output\", \"rpc\");\n YYABORT;\n }\n (yyvsp[-2].nodes).node.flag |= LYS_RPC_OUTPUT;\n (yyval.nodes) = (yyvsp[-2].nodes);\n }\n\n break;\n\n case 445:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n s = strdup(\"input\");\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_INPUT, sizeof(struct lys_node_inout)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = INPUT_KEYWORD;\n }\n\n break;\n\n case 446:\n\n { void *tmp;\n struct lys_node_inout *input = actual;\n\n if (input->must_size) {\n tmp = realloc(input->must, input->must_size * sizeof *input->must);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n input->must = tmp;\n }\n\n if (input->tpdf_size) {\n tmp = realloc(input->tpdf, input->tpdf_size * sizeof *input->tpdf);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n input->tpdf = tmp;\n }\n\n LOGDBG(LY_LDGYANG, \"finished parsing input statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-4].backup_token).token;\n actual = (yyvsp[-4].backup_token).actual;\n data_node = (yyvsp[-4].backup_token).actual;\n }\n\n break;\n\n case 452:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n s = strdup(\"output\");\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_OUTPUT, sizeof(struct lys_node_inout)))) {\n YYABORT;\n }\n data_node = actual;\n s = NULL;\n actual_type = OUTPUT_KEYWORD;\n }\n\n break;\n\n case 453:\n\n { void *tmp;\n struct lys_node_inout *output = actual;\n\n if (output->must_size) {\n tmp = realloc(output->must, output->must_size * sizeof *output->must);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n output->must = tmp;\n }\n\n if (output->tpdf_size) {\n tmp = realloc(output->tpdf, output->tpdf_size * sizeof *output->tpdf);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n output->tpdf = tmp;\n }\n\n LOGDBG(LY_LDGYANG, \"finished parsing output statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-4].backup_token).token;\n actual = (yyvsp[-4].backup_token).actual;\n data_node = (yyvsp[-4].backup_token).actual;\n }\n\n break;\n\n case 454:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_NOTIF, sizeof(struct lys_node_notif)))) {\n YYABORT;\n }\n data_node = actual;\n actual_type = NOTIFICATION_KEYWORD;\n }\n\n break;\n\n case 455:\n\n { LOGDBG(LY_LDGYANG, \"finished parsing notification statement \\\"%s\\\"\", data_node->name);\n actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n data_node = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 457:\n\n { void *tmp;\n\n if ((yyvsp[-1].nodes).notif->must_size) {\n tmp = realloc((yyvsp[-1].nodes).notif->must, (yyvsp[-1].nodes).notif->must_size * sizeof *(yyvsp[-1].nodes).notif->must);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).notif->must = tmp;\n }\n\n if ((yyvsp[-1].nodes).notif->iffeature_size) {\n tmp = realloc((yyvsp[-1].nodes).notif->iffeature, (yyvsp[-1].nodes).notif->iffeature_size * sizeof *(yyvsp[-1].nodes).notif->iffeature);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).notif->iffeature = tmp;\n }\n\n if ((yyvsp[-1].nodes).notif->tpdf_size) {\n tmp = realloc((yyvsp[-1].nodes).notif->tpdf, (yyvsp[-1].nodes).notif->tpdf_size * sizeof *(yyvsp[-1].nodes).notif->tpdf);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].nodes).notif->tpdf = tmp;\n }\n }\n\n break;\n\n case 458:\n\n { (yyval.nodes).notif = actual; }\n\n break;\n\n case 461:\n\n { if ((yyvsp[-1].nodes).notif->flags & LYS_STATUS_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).notif, \"status\", \"notification\");\n YYABORT;\n }\n (yyvsp[-1].nodes).notif->flags |= (yyvsp[0].i);\n }\n\n break;\n\n case 462:\n\n { if (yang_read_description(trg, (yyvsp[-1].nodes).notif, s, \"notification\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 463:\n\n { if (yang_read_reference(trg, (yyvsp[-1].nodes).notif, s, \"notification\", NODE_PRINT)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 467:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n YANG_ADDELEM(trg->deviation, trg->deviation_size, \"deviations\");\n ((struct lys_deviation *)actual)->target_name = transform_schema2json(trg, s);\n free(s);\n if (!((struct lys_deviation *)actual)->target_name) {\n YYABORT;\n }\n s = NULL;\n actual_type = DEVIATION_KEYWORD;\n }\n\n break;\n\n case 468:\n\n { void *tmp;\n\n if ((yyvsp[-1].dev)->deviate_size) {\n tmp = realloc((yyvsp[-1].dev)->deviate, (yyvsp[-1].dev)->deviate_size * sizeof *(yyvsp[-1].dev)->deviate);\n if (!tmp) {\n LOGINT(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].dev)->deviate = tmp;\n } else {\n LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, \"deviate\", \"deviation\");\n YYABORT;\n }\n actual_type = (yyvsp[-4].backup_token).token;\n actual = (yyvsp[-4].backup_token).actual;\n }\n\n break;\n\n case 469:\n\n { (yyval.dev) = actual; }\n\n break;\n\n case 470:\n\n { if (yang_read_description(trg, (yyvsp[-1].dev), s, \"deviation\", NODE)) {\n YYABORT;\n }\n s = NULL;\n (yyval.dev) = (yyvsp[-1].dev);\n }\n\n break;\n\n case 471:\n\n { if (yang_read_reference(trg, (yyvsp[-1].dev), s, \"deviation\", NODE)) {\n YYABORT;\n }\n s = NULL;\n (yyval.dev) = (yyvsp[-1].dev);\n }\n\n break;\n\n case 477:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_deviate_unsupported(trg->ctx, actual))) {\n YYABORT;\n }\n actual_type = NOT_SUPPORTED_KEYWORD;\n }\n\n break;\n\n case 478:\n\n { actual_type = (yyvsp[-2].backup_token).token;\n actual = (yyvsp[-2].backup_token).actual;\n }\n\n break;\n\n case 484:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_ADD))) {\n YYABORT;\n }\n actual_type = ADD_KEYWORD;\n }\n\n break;\n\n case 485:\n\n { actual_type = (yyvsp[-2].backup_token).token;\n actual = (yyvsp[-2].backup_token).actual;\n }\n\n break;\n\n case 487:\n\n { void *tmp;\n\n if ((yyvsp[-1].deviate)->must_size) {\n tmp = realloc((yyvsp[-1].deviate)->must, (yyvsp[-1].deviate)->must_size * sizeof *(yyvsp[-1].deviate)->must);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].deviate)->must = tmp;\n }\n\n if ((yyvsp[-1].deviate)->unique_size) {\n tmp = realloc((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size * sizeof *(yyvsp[-1].deviate)->unique);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].deviate)->unique = tmp;\n }\n\n if ((yyvsp[-1].deviate)->dflt_size) {\n tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].deviate)->dflt = tmp;\n }\n }\n\n break;\n\n case 488:\n\n { (yyval.deviate) = actual; }\n\n break;\n\n case 489:\n\n { if (yang_read_units(trg, actual, s, ADD_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 491:\n\n { YANG_ADDELEM((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size, \"uniques\");\n ((struct lys_unique *)actual)->expr = (const char **)s;\n s = NULL;\n actual = (yyvsp[-1].deviate);\n (yyval.deviate)= (yyvsp[-1].deviate);\n }\n\n break;\n\n case 492:\n\n { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, \"defaults\");\n *((const char **)actual) = lydict_insert_zc(trg->ctx, s);\n s = NULL;\n actual = (yyvsp[-1].deviate);\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 493:\n\n { if ((yyvsp[-1].deviate)->flags & LYS_CONFIG_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"config\", \"deviate\");\n YYABORT;\n }\n (yyvsp[-1].deviate)->flags = (yyvsp[0].i);\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 494:\n\n { if ((yyvsp[-1].deviate)->flags & LYS_MAND_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"mandatory\", \"deviate\");\n YYABORT;\n }\n (yyvsp[-1].deviate)->flags = (yyvsp[0].i);\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 495:\n\n { if ((yyvsp[-1].deviate)->min_set) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"min-elements\", \"deviation\");\n YYABORT;\n }\n (yyvsp[-1].deviate)->min = (yyvsp[0].uint);\n (yyvsp[-1].deviate)->min_set = 1;\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 496:\n\n { if ((yyvsp[-1].deviate)->max_set) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"max-elements\", \"deviation\");\n YYABORT;\n }\n (yyvsp[-1].deviate)->max = (yyvsp[0].uint);\n (yyvsp[-1].deviate)->max_set = 1;\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 497:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_DEL))) {\n YYABORT;\n }\n actual_type = DELETE_KEYWORD;\n }\n\n break;\n\n case 498:\n\n { actual_type = (yyvsp[-2].backup_token).token;\n actual = (yyvsp[-2].backup_token).actual;\n }\n\n break;\n\n case 500:\n\n { void *tmp;\n\n if ((yyvsp[-1].deviate)->must_size) {\n tmp = realloc((yyvsp[-1].deviate)->must, (yyvsp[-1].deviate)->must_size * sizeof *(yyvsp[-1].deviate)->must);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].deviate)->must = tmp;\n }\n\n if ((yyvsp[-1].deviate)->unique_size) {\n tmp = realloc((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size * sizeof *(yyvsp[-1].deviate)->unique);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].deviate)->unique = tmp;\n }\n\n if ((yyvsp[-1].deviate)->dflt_size) {\n tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].deviate)->dflt = tmp;\n }\n }\n\n break;\n\n case 501:\n\n { (yyval.deviate) = actual; }\n\n break;\n\n case 502:\n\n { if (yang_read_units(trg, actual, s, DELETE_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 504:\n\n { YANG_ADDELEM((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size, \"uniques\");\n ((struct lys_unique *)actual)->expr = (const char **)s;\n s = NULL;\n actual = (yyvsp[-1].deviate);\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 505:\n\n { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, \"defaults\");\n *((const char **)actual) = lydict_insert_zc(trg->ctx, s);\n s = NULL;\n actual = (yyvsp[-1].deviate);\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 506:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_RPL))) {\n YYABORT;\n }\n actual_type = REPLACE_KEYWORD;\n }\n\n break;\n\n case 507:\n\n { actual_type = (yyvsp[-2].backup_token).token;\n actual = (yyvsp[-2].backup_token).actual;\n }\n\n break;\n\n case 509:\n\n { void *tmp;\n\n if ((yyvsp[-1].deviate)->dflt_size) {\n tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt);\n if (!tmp) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyvsp[-1].deviate)->dflt = tmp;\n }\n }\n\n break;\n\n case 510:\n\n { (yyval.deviate) = actual; }\n\n break;\n\n case 512:\n\n { if (yang_read_units(trg, actual, s, DELETE_KEYWORD)) {\n YYABORT;\n }\n s = NULL;\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 513:\n\n { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, \"defaults\");\n *((const char **)actual) = lydict_insert_zc(trg->ctx, s);\n s = NULL;\n actual = (yyvsp[-1].deviate);\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 514:\n\n { if ((yyvsp[-1].deviate)->flags & LYS_CONFIG_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"config\", \"deviate\");\n YYABORT;\n }\n (yyvsp[-1].deviate)->flags = (yyvsp[0].i);\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 515:\n\n { if ((yyvsp[-1].deviate)->flags & LYS_MAND_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"mandatory\", \"deviate\");\n YYABORT;\n }\n (yyvsp[-1].deviate)->flags = (yyvsp[0].i);\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 516:\n\n { if ((yyvsp[-1].deviate)->min_set) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"min-elements\", \"deviation\");\n YYABORT;\n }\n (yyvsp[-1].deviate)->min = (yyvsp[0].uint);\n (yyvsp[-1].deviate)->min_set = 1;\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 517:\n\n { if ((yyvsp[-1].deviate)->max_set) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"max-elements\", \"deviation\");\n YYABORT;\n }\n (yyvsp[-1].deviate)->max = (yyvsp[0].uint);\n (yyvsp[-1].deviate)->max_set = 1;\n (yyval.deviate) = (yyvsp[-1].deviate);\n }\n\n break;\n\n case 518:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_when(trg, actual, actual_type, s))) {\n YYABORT;\n }\n s = NULL;\n actual_type = WHEN_KEYWORD;\n }\n\n break;\n\n case 519:\n\n { actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 523:\n\n { if (yang_read_description(trg, actual, s, \"when\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 524:\n\n { if (yang_read_reference(trg, actual, s, \"when\", NODE)) {\n YYABORT;\n }\n s = NULL;\n }\n\n break;\n\n case 525:\n\n { (yyval.i) = (yyvsp[0].i);\n backup_type = actual_type;\n actual_type = CONFIG_KEYWORD;\n }\n\n break;\n\n case 526:\n\n { (yyval.i) = (yyvsp[-1].i); }\n\n break;\n\n case 527:\n\n { (yyval.i) = LYS_CONFIG_W | LYS_CONFIG_SET; }\n\n break;\n\n case 528:\n\n { (yyval.i) = LYS_CONFIG_R | LYS_CONFIG_SET; }\n\n break;\n\n case 529:\n\n { if (!strcmp(s, \"true\")) {\n (yyval.i) = LYS_CONFIG_W | LYS_CONFIG_SET;\n } else if (!strcmp(s, \"false\")) {\n (yyval.i) = LYS_CONFIG_R | LYS_CONFIG_SET;\n } else {\n LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, \"config\");\n free(s);\n YYABORT;\n }\n free(s);\n s = NULL;\n }\n\n break;\n\n case 530:\n\n { (yyval.i) = (yyvsp[0].i);\n backup_type = actual_type;\n actual_type = MANDATORY_KEYWORD;\n }\n\n break;\n\n case 531:\n\n { (yyval.i) = (yyvsp[-1].i); }\n\n break;\n\n case 532:\n\n { (yyval.i) = LYS_MAND_TRUE; }\n\n break;\n\n case 533:\n\n { (yyval.i) = LYS_MAND_FALSE; }\n\n break;\n\n case 534:\n\n { if (!strcmp(s, \"true\")) {\n (yyval.i) = LYS_MAND_TRUE;\n } else if (!strcmp(s, \"false\")) {\n (yyval.i) = LYS_MAND_FALSE;\n } else {\n LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, \"mandatory\");\n free(s);\n YYABORT;\n }\n free(s);\n s = NULL;\n }\n\n break;\n\n case 535:\n\n { backup_type = actual_type;\n actual_type = PRESENCE_KEYWORD;\n }\n\n break;\n\n case 537:\n\n { (yyval.uint) = (yyvsp[0].uint);\n backup_type = actual_type;\n actual_type = MIN_ELEMENTS_KEYWORD;\n }\n\n break;\n\n case 538:\n\n { (yyval.uint) = (yyvsp[-1].uint); }\n\n break;\n\n case 539:\n\n { (yyval.uint) = (yyvsp[-1].uint); }\n\n break;\n\n case 540:\n\n { if (strlen(s) == 1 && s[0] == '0') {\n (yyval.uint) = 0;\n } else {\n /* convert it to uint32_t */\n uint64_t val;\n char *endptr = NULL;\n errno = 0;\n\n val = strtoul(s, &endptr, 10);\n if (*endptr || s[0] == '-' || errno || val > UINT32_MAX) {\n LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, \"min-elements\");\n free(s);\n YYABORT;\n }\n (yyval.uint) = (uint32_t) val;\n }\n free(s);\n s = NULL;\n }\n\n break;\n\n case 541:\n\n { (yyval.uint) = (yyvsp[0].uint);\n backup_type = actual_type;\n actual_type = MAX_ELEMENTS_KEYWORD;\n }\n\n break;\n\n case 542:\n\n { (yyval.uint) = (yyvsp[-1].uint); }\n\n break;\n\n case 543:\n\n { (yyval.uint) = 0; }\n\n break;\n\n case 544:\n\n { (yyval.uint) = (yyvsp[-1].uint); }\n\n break;\n\n case 545:\n\n { if (!strcmp(s, \"unbounded\")) {\n (yyval.uint) = 0;\n } else {\n /* convert it to uint32_t */\n uint64_t val;\n char *endptr = NULL;\n errno = 0;\n\n val = strtoul(s, &endptr, 10);\n if (*endptr || s[0] == '-' || errno || val == 0 || val > UINT32_MAX) {\n LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, \"max-elements\");\n free(s);\n YYABORT;\n }\n (yyval.uint) = (uint32_t) val;\n }\n free(s);\n s = NULL;\n }\n\n break;\n\n case 546:\n\n { (yyval.i) = (yyvsp[0].i);\n backup_type = actual_type;\n actual_type = ORDERED_BY_KEYWORD;\n }\n\n break;\n\n case 547:\n\n { (yyval.i) = (yyvsp[-1].i); }\n\n break;\n\n case 548:\n\n { (yyval.i) = LYS_USERORDERED; }\n\n break;\n\n case 549:\n\n { (yyval.i) = LYS_SYSTEMORDERED; }\n\n break;\n\n case 550:\n\n { if (!strcmp(s, \"user\")) {\n (yyval.i) = LYS_USERORDERED;\n } else if (!strcmp(s, \"system\")) {\n (yyval.i) = LYS_SYSTEMORDERED;\n } else {\n free(s);\n YYABORT;\n }\n free(s);\n s=NULL;\n }\n\n break;\n\n case 551:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n switch (actual_type) {\n case CONTAINER_KEYWORD:\n YANG_ADDELEM(((struct lys_node_container *)actual)->must,\n ((struct lys_node_container *)actual)->must_size, \"musts\");\n break;\n case ANYDATA_KEYWORD:\n case ANYXML_KEYWORD:\n YANG_ADDELEM(((struct lys_node_anydata *)actual)->must,\n ((struct lys_node_anydata *)actual)->must_size, \"musts\");\n break;\n case LEAF_KEYWORD:\n YANG_ADDELEM(((struct lys_node_leaf *)actual)->must,\n ((struct lys_node_leaf *)actual)->must_size, \"musts\");\n break;\n case LEAF_LIST_KEYWORD:\n YANG_ADDELEM(((struct lys_node_leaflist *)actual)->must,\n ((struct lys_node_leaflist *)actual)->must_size, \"musts\");\n break;\n case LIST_KEYWORD:\n YANG_ADDELEM(((struct lys_node_list *)actual)->must,\n ((struct lys_node_list *)actual)->must_size, \"musts\");\n break;\n case REFINE_KEYWORD:\n YANG_ADDELEM(((struct lys_refine *)actual)->must,\n ((struct lys_refine *)actual)->must_size, \"musts\");\n break;\n case ADD_KEYWORD:\n case DELETE_KEYWORD:\n YANG_ADDELEM(((struct lys_deviate *)actual)->must,\n ((struct lys_deviate *)actual)->must_size, \"musts\");\n break;\n case NOTIFICATION_KEYWORD:\n if (trg->version < 2) {\n free(s);\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, \"must\");\n YYABORT;\n }\n YANG_ADDELEM(((struct lys_node_notif *)actual)->must,\n ((struct lys_node_notif *)actual)->must_size, \"musts\");\n break;\n case INPUT_KEYWORD:\n case OUTPUT_KEYWORD:\n if (trg->version < 2) {\n free(s);\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, \"must\");\n YYABORT;\n }\n YANG_ADDELEM(((struct lys_node_inout *)actual)->must,\n ((struct lys_node_inout *)actual)->must_size, \"musts\");\n break;\n case EXTENSION_INSTANCE:\n /* must is already allocated */\n break;\n default:\n free(s);\n LOGINT(trg->ctx);\n YYABORT;\n }\n ((struct lys_restr *)actual)->expr = transform_schema2json(trg, s);\n free(s);\n if (!((struct lys_restr *)actual)->expr) {\n YYABORT;\n }\n s = NULL;\n actual_type = MUST_KEYWORD;\n }\n\n break;\n\n case 552:\n\n { actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 555:\n\n { backup_type = actual_type;\n actual_type = UNIQUE_KEYWORD;\n }\n\n break;\n\n case 559:\n\n { backup_type = actual_type;\n actual_type = KEY_KEYWORD;\n }\n\n break;\n\n case 561:\n\n { s = strdup(yyget_text(scanner));\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n }\n\n break;\n\n case 564:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_range(trg->ctx, actual, s, is_ext_instance))) {\n YYABORT;\n }\n actual_type = RANGE_KEYWORD;\n s = NULL;\n }\n\n break;\n\n case 565:\n\n { if (s) {\n s = ly_realloc(s,strlen(s) + yyget_leng(scanner) + 2);\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n strcat(s,\"/\");\n strcat(s, yyget_text(scanner));\n } else {\n s = malloc(yyget_leng(scanner) + 2);\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n s[0]='/';\n memcpy(s + 1, yyget_text(scanner), yyget_leng(scanner) + 1);\n }\n }\n\n break;\n\n case 569:\n\n { if (s) {\n s = ly_realloc(s,strlen(s) + yyget_leng(scanner) + 1);\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n strcat(s, yyget_text(scanner));\n } else {\n s = strdup(yyget_text(scanner));\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n }\n }\n\n break;\n\n case 571:\n\n { tmp_s = yyget_text(scanner); }\n\n break;\n\n case 572:\n\n { s = strdup(tmp_s);\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n s[strlen(s) - 1] = '\\0';\n }\n\n break;\n\n case 573:\n\n { tmp_s = yyget_text(scanner); }\n\n break;\n\n case 574:\n\n { s = strdup(tmp_s);\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n s[strlen(s) - 1] = '\\0';\n }\n\n break;\n\n case 598:\n\n { /* convert it to uint32_t */\n unsigned long val;\n\n val = strtoul(yyget_text(scanner), NULL, 10);\n if (val > UINT32_MAX) {\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Converted number is very long.\");\n YYABORT;\n }\n (yyval.uint) = (uint32_t) val;\n }\n\n break;\n\n case 599:\n\n { (yyval.uint) = 0; }\n\n break;\n\n case 600:\n\n { (yyval.uint) = (yyvsp[0].uint); }\n\n break;\n\n case 601:\n\n { (yyval.i) = 0; }\n\n break;\n\n case 602:\n\n { /* convert it to int32_t */\n int64_t val;\n\n val = strtoll(yyget_text(scanner), NULL, 10);\n if (val < INT32_MIN || val > INT32_MAX) {\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL,\n \"The number is not in the correct range (INT32_MIN..INT32_MAX): \\\"%d\\\"\",val);\n YYABORT;\n }\n (yyval.i) = (int32_t) val;\n }\n\n break;\n\n case 608:\n\n { if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) {\n free(s);\n YYABORT;\n }\n }\n\n break;\n\n case 613:\n\n { char *tmp;\n\n if ((tmp = strchr(s, ':'))) {\n *tmp = '\\0';\n /* check prefix */\n if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) {\n free(s);\n YYABORT;\n }\n /* check identifier */\n if (lyp_check_identifier(trg->ctx, tmp + 1, LY_IDENT_SIMPLE, trg, NULL)) {\n free(s);\n YYABORT;\n }\n *tmp = ':';\n } else {\n /* check identifier */\n if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) {\n free(s);\n YYABORT;\n }\n }\n }\n\n break;\n\n case 614:\n\n { s = (yyvsp[-1].str); }\n\n break;\n\n case 615:\n\n { s = (yyvsp[-3].str); }\n\n break;\n\n case 616:\n\n { actual_type = backup_type;\n backup_type = NODE;\n (yyval.str) = s;\n s = NULL;\n }\n\n break;\n\n case 617:\n\n { actual_type = backup_type;\n backup_type = NODE;\n }\n\n break;\n\n case 618:\n\n { (yyval.str) = s;\n s = NULL;\n }\n\n break;\n\n case 622:\n\n { actual_type = (yyvsp[-1].backup_token).token;\n actual = (yyvsp[-1].backup_token).actual;\n }\n\n break;\n\n case 623:\n\n { (yyval.backup_token).token = actual_type;\n (yyval.backup_token).actual = actual;\n if (!(actual = yang_read_ext(trg, (actual) ? actual : trg, (yyvsp[-1].str), s,\n actual_type, backup_type, is_ext_instance))) {\n YYABORT;\n }\n s = NULL;\n actual_type = EXTENSION_INSTANCE;\n }\n\n break;\n\n case 624:\n\n { (yyval.str) = s; s = NULL; }\n\n break;\n\n case 639:\n\n { struct yang_ext_substmt *substmt = ((struct lys_ext_instance *)actual)->parent;\n int32_t length = 0, old_length = 0;\n char *tmp_value;\n\n if (!substmt) {\n substmt = calloc(1, sizeof *substmt);\n if (!substmt) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct lys_ext_instance *)actual)->parent = substmt;\n }\n length = strlen((yyvsp[-2].str));\n old_length = (substmt->ext_substmt) ? strlen(substmt->ext_substmt) + 2 : 2;\n tmp_value = realloc(substmt->ext_substmt, old_length + length + 1);\n if (!tmp_value) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n substmt->ext_substmt = tmp_value;\n tmp_value += old_length - 2;\n memcpy(tmp_value, (yyvsp[-2].str), length);\n tmp_value[length] = ' ';\n tmp_value[length + 1] = '\\0';\n tmp_value[length + 2] = '\\0';\n }\n\n break;\n\n case 640:\n\n { struct yang_ext_substmt *substmt = ((struct lys_ext_instance *)actual)->parent;\n int32_t length;\n char *tmp_value, **array;\n int i = 0;\n\n if (!substmt) {\n substmt = calloc(1, sizeof *substmt);\n if (!substmt) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n ((struct lys_ext_instance *)actual)->parent = substmt;\n }\n length = strlen((yyvsp[-2].str));\n if (!substmt->ext_modules) {\n array = malloc(2 * sizeof *substmt->ext_modules);\n } else {\n for (i = 0; substmt->ext_modules[i]; ++i);\n array = realloc(substmt->ext_modules, (i + 2) * sizeof *substmt->ext_modules);\n }\n if (!array) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n substmt->ext_modules = array;\n array[i + 1] = NULL;\n tmp_value = malloc(length + 2);\n if (!tmp_value) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n array[i] = tmp_value;\n memcpy(tmp_value, (yyvsp[-2].str), length);\n tmp_value[length] = '\\0';\n tmp_value[length + 1] = '\\0';\n }\n\n break;\n\n case 643:\n\n { (yyval.str) = yyget_text(scanner); }\n\n break;\n\n case 644:\n\n { (yyval.str) = yyget_text(scanner); }\n\n break;\n\n case 656:\n\n { s = strdup(yyget_text(scanner));\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n }\n\n break;\n\n case 749:\n\n { s = strdup(yyget_text(scanner));\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n }\n\n break;\n\n case 750:\n\n { s = strdup(yyget_text(scanner));\n if (!s) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n }\n\n break;\n\n case 751:\n\n { struct lys_type **type;\n\n type = (struct lys_type **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name,\n \"type\", LY_STMT_TYPE);\n if (!type) {\n YYABORT;\n }\n /* allocate type structure */\n (*type) = calloc(1, sizeof **type);\n if (!*type) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n\n /* HACK for unres */\n (*type)->parent = (struct lys_tpdf *)ext_instance;\n (yyval.v) = actual = *type;\n is_ext_instance = 0;\n }\n\n break;\n\n case 752:\n\n { struct lys_tpdf **tpdf;\n\n tpdf = (struct lys_tpdf **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name,\n \"typedef\", LY_STMT_TYPEDEF);\n if (!tpdf) {\n YYABORT;\n }\n /* allocate typedef structure */\n (*tpdf) = calloc(1, sizeof **tpdf);\n if (!*tpdf) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n\n (yyval.v) = actual = *tpdf;\n is_ext_instance = 0;\n }\n\n break;\n\n case 753:\n\n { struct lys_iffeature **iffeature;\n\n iffeature = (struct lys_iffeature **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name,\n \"if-feature\", LY_STMT_IFFEATURE);\n if (!iffeature) {\n YYABORT;\n }\n /* allocate typedef structure */\n (*iffeature) = calloc(1, sizeof **iffeature);\n if (!*iffeature) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyval.v) = actual = *iffeature;\n }\n\n break;\n\n case 754:\n\n { struct lys_restr **restr;\n LY_STMT stmt;\n\n s = yyget_text(scanner);\n if (!strcmp(s, \"must\")) {\n stmt = LY_STMT_MUST;\n } else if (!strcmp(s, \"pattern\")) {\n stmt = LY_STMT_PATTERN;\n } else if (!strcmp(s, \"range\")) {\n stmt = LY_STMT_RANGE;\n } else {\n stmt = LY_STMT_LENGTH;\n }\n restr = (struct lys_restr **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, s, stmt);\n if (!restr) {\n YYABORT;\n }\n /* allocate structure for must */\n (*restr) = calloc(1, sizeof(struct lys_restr));\n if (!*restr) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n (yyval.v) = actual = *restr;\n s = NULL;\n }\n\n break;\n\n case 755:\n\n { actual = yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, \"when\", LY_STMT_WHEN);\n if (!actual) {\n YYABORT;\n }\n (yyval.v) = actual;\n }\n\n break;\n\n case 756:\n\n { struct lys_revision **rev;\n int i;\n\n rev = (struct lys_revision **)yang_getplace_for_extcomplex_struct(ext_instance, &i, ext_name,\n \"revision\", LY_STMT_REVISION);\n if (!rev) {\n YYABORT;\n }\n rev[i] = calloc(1, sizeof **rev);\n if (!rev[i]) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n actual = rev[i];\n (yyval.revisions).revision = rev;\n (yyval.revisions).index = i;\n }\n\n break;\n\n case 757:\n\n { LY_STMT stmt;\n\n s = yyget_text(scanner);\n if (!strcmp(s, \"action\")) {\n stmt = LY_STMT_ACTION;\n } else if (!strcmp(s, \"anydata\")) {\n stmt = LY_STMT_ANYDATA;\n } else if (!strcmp(s, \"anyxml\")) {\n stmt = LY_STMT_ANYXML;\n } else if (!strcmp(s, \"case\")) {\n stmt = LY_STMT_CASE;\n } else if (!strcmp(s, \"choice\")) {\n stmt = LY_STMT_CHOICE;\n } else if (!strcmp(s, \"container\")) {\n stmt = LY_STMT_CONTAINER;\n } else if (!strcmp(s, \"grouping\")) {\n stmt = LY_STMT_GROUPING;\n } else if (!strcmp(s, \"input\")) {\n stmt = LY_STMT_INPUT;\n } else if (!strcmp(s, \"leaf\")) {\n stmt = LY_STMT_LEAF;\n } else if (!strcmp(s, \"leaf-list\")) {\n stmt = LY_STMT_LEAFLIST;\n } else if (!strcmp(s, \"list\")) {\n stmt = LY_STMT_LIST;\n } else if (!strcmp(s, \"notification\")) {\n stmt = LY_STMT_NOTIFICATION;\n } else if (!strcmp(s, \"output\")) {\n stmt = LY_STMT_OUTPUT;\n } else {\n stmt = LY_STMT_USES;\n }\n if (yang_extcomplex_node(ext_instance, ext_name, s, *param->node, stmt)) {\n YYABORT;\n }\n actual = NULL;\n s = NULL;\n is_ext_instance = 0;\n }\n\n break;\n\n case 758:\n\n { LOGERR(trg->ctx, ly_errno, \"Extension's substatement \\\"%s\\\" not supported.\", yyget_text(scanner)); }\n\n break;\n\n case 790:\n\n { actual_type = EXTENSION_INSTANCE;\n actual = ext_instance;\n if (!is_ext_instance) {\n LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, yyget_text(scanner));\n YYABORT;\n }\n (yyval.i) = 0;\n }\n\n break;\n\n case 792:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"prefix\", ext_name, s,\n 0, LY_STMT_PREFIX)) {\n YYABORT;\n }\n }\n\n break;\n\n case 793:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"description\", ext_name, s,\n 0, LY_STMT_DESCRIPTION)) {\n YYABORT;\n }\n }\n\n break;\n\n case 794:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"reference\", ext_name, s,\n 0, LY_STMT_REFERENCE)) {\n YYABORT;\n }\n }\n\n break;\n\n case 795:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"units\", ext_name, s,\n 0, LY_STMT_UNITS)) {\n YYABORT;\n }\n }\n\n break;\n\n case 796:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"base\", ext_name, s,\n 0, LY_STMT_BASE)) {\n YYABORT;\n }\n }\n\n break;\n\n case 797:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"contact\", ext_name, s,\n 0, LY_STMT_CONTACT)) {\n YYABORT;\n }\n }\n\n break;\n\n case 798:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"default\", ext_name, s,\n 0, LY_STMT_DEFAULT)) {\n YYABORT;\n }\n }\n\n break;\n\n case 799:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"error-message\", ext_name, s,\n 0, LY_STMT_ERRMSG)) {\n YYABORT;\n }\n }\n\n break;\n\n case 800:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"error-app-tag\", ext_name, s,\n 0, LY_STMT_ERRTAG)) {\n YYABORT;\n }\n }\n\n break;\n\n case 801:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"key\", ext_name, s,\n 0, LY_STMT_KEY)) {\n YYABORT;\n }\n }\n\n break;\n\n case 802:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"namespace\", ext_name, s,\n 0, LY_STMT_NAMESPACE)) {\n YYABORT;\n }\n }\n\n break;\n\n case 803:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"organization\", ext_name, s,\n 0, LY_STMT_ORGANIZATION)) {\n YYABORT;\n }\n }\n\n break;\n\n case 804:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"path\", ext_name, s,\n 0, LY_STMT_PATH)) {\n YYABORT;\n }\n }\n\n break;\n\n case 805:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"presence\", ext_name, s,\n 0, LY_STMT_PRESENCE)) {\n YYABORT;\n }\n }\n\n break;\n\n case 806:\n\n { if (yang_read_extcomplex_str(trg, ext_instance, \"revision-date\", ext_name, s,\n 0, LY_STMT_REVISIONDATE)) {\n YYABORT;\n }\n }\n\n break;\n\n case 807:\n\n { struct lys_type *type = (yyvsp[-2].v);\n\n if (yang_fill_type(trg, type, (struct yang_type *)type->der, ext_instance, param->unres)) {\n yang_type_free(trg->ctx, type);\n YYABORT;\n }\n if (unres_schema_add_node(trg, param->unres, type, UNRES_TYPE_DER_EXT, NULL) == -1) {\n yang_type_free(trg->ctx, type);\n YYABORT;\n }\n actual = ext_instance;\n is_ext_instance = 1;\n }\n\n break;\n\n case 808:\n\n { struct lys_tpdf *tpdf = (yyvsp[-2].v);\n\n if (yang_fill_type(trg, &tpdf->type, (struct yang_type *)tpdf->type.der, tpdf, param->unres)) {\n yang_type_free(trg->ctx, &tpdf->type);\n }\n if (yang_check_ext_instance(trg, &tpdf->ext, tpdf->ext_size, tpdf, param->unres)) {\n YYABORT;\n }\n if (unres_schema_add_node(trg, param->unres, &tpdf->type, UNRES_TYPE_DER_TPDF, (struct lys_node *)ext_instance) == -1) {\n yang_type_free(trg->ctx, &tpdf->type);\n YYABORT;\n }\n /* check default value*/\n if (unres_schema_add_node(trg, param->unres, &tpdf->type, UNRES_TYPE_DFLT, (struct lys_node *)(&tpdf->dflt)) == -1) {\n YYABORT;\n }\n actual = ext_instance;\n is_ext_instance = 1;\n }\n\n break;\n\n case 809:\n\n { if (yang_fill_extcomplex_flags(ext_instance, ext_name, \"status\", LY_STMT_STATUS,\n (yyvsp[0].i), LYS_STATUS_MASK)) {\n YYABORT;\n }\n }\n\n break;\n\n case 810:\n\n { if (yang_fill_extcomplex_flags(ext_instance, ext_name, \"config\", LY_STMT_CONFIG,\n (yyvsp[0].i), LYS_CONFIG_MASK)) {\n YYABORT;\n }\n }\n\n break;\n\n case 811:\n\n { if (yang_fill_extcomplex_flags(ext_instance, ext_name, \"mandatory\", LY_STMT_MANDATORY,\n (yyvsp[0].i), LYS_MAND_MASK)) {\n YYABORT;\n }\n }\n\n break;\n\n case 812:\n\n { if ((yyvsp[-1].i) & LYS_ORDERED_MASK) {\n LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, \"ordered by\", ext_name);\n YYABORT;\n }\n if ((yyvsp[0].i) & LYS_USERORDERED) {\n if (yang_fill_extcomplex_flags(ext_instance, ext_name, \"ordered-by\", LY_STMT_ORDEREDBY,\n (yyvsp[0].i), LYS_USERORDERED)) {\n YYABORT;\n }\n }\n (yyvsp[-1].i) |= (yyvsp[0].i);\n (yyval.i) = (yyvsp[-1].i);\n }\n\n break;\n\n case 813:\n\n { if (yang_fill_extcomplex_uint8(ext_instance, ext_name, \"require-instance\",\n LY_STMT_REQINSTANCE, (yyvsp[0].i))) {\n YYABORT;\n }\n }\n\n break;\n\n case 814:\n\n { if (yang_fill_extcomplex_uint8(ext_instance, ext_name, \"modifier\", LY_STMT_MODIFIER, 0)) {\n YYABORT;\n }\n }\n\n break;\n\n case 815:\n\n { /* range check */\n if ((yyvsp[0].uint) < 1 || (yyvsp[0].uint) > 18) {\n LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, \"Invalid value \\\"%d\\\" of \\\"%s\\\".\", (yyvsp[0].uint), \"fraction-digits\");\n YYABORT;\n }\n if (yang_fill_extcomplex_uint8(ext_instance, ext_name, \"fraction-digits\", LY_STMT_DIGITS, (yyvsp[0].uint))) {\n YYABORT;\n }\n }\n\n break;\n\n case 816:\n\n { uint32_t **val;\n\n val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name,\n \"min-elements\", LY_STMT_MIN);\n if (!val) {\n YYABORT;\n }\n /* store the value */\n *val = malloc(sizeof(uint32_t));\n if (!*val) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n **val = (yyvsp[0].uint);\n }\n\n break;\n\n case 817:\n\n { uint32_t **val;\n\n val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name,\n \"max-elements\", LY_STMT_MAX);\n if (!val) {\n YYABORT;\n }\n /* store the value */\n *val = malloc(sizeof(uint32_t));\n if (!*val) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n **val = (yyvsp[0].uint);\n }\n\n break;\n\n case 818:\n\n { uint32_t **val;\n\n val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name,\n \"position\", LY_STMT_POSITION);\n if (!val) {\n YYABORT;\n }\n /* store the value */\n *val = malloc(sizeof(uint32_t));\n if (!*val) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n **val = (yyvsp[0].uint);\n }\n\n break;\n\n case 819:\n\n { int32_t **val;\n\n val = (int32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name,\n \"value\", LY_STMT_VALUE);\n if (!val) {\n YYABORT;\n }\n /* store the value */\n *val = malloc(sizeof(int32_t));\n if (!*val) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n **val = (yyvsp[0].i);\n }\n\n break;\n\n case 820:\n\n { struct lys_unique **unique;\n int rc;\n\n unique = (struct lys_unique **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name,\n \"unique\", LY_STMT_UNIQUE);\n if (!unique) {\n YYABORT;\n }\n *unique = calloc(1, sizeof(struct lys_unique));\n if (!*unique) {\n LOGMEM(trg->ctx);\n YYABORT;\n }\n rc = yang_fill_unique(trg, (struct lys_node_list *)ext_instance, *unique, s, param->unres);\n free(s);\n s = NULL;\n if (rc) {\n YYABORT;\n }\n }\n\n break;\n\n case 821:\n\n { struct lys_iffeature *iffeature;\n\n iffeature = (yyvsp[-2].v);\n s = (char *)iffeature->features;\n iffeature->features = NULL;\n if (yang_fill_iffeature(trg, iffeature, ext_instance, s, param->unres, 0)) {\n YYABORT;\n }\n if (yang_check_ext_instance(trg, &iffeature->ext, iffeature->ext_size, iffeature, param->unres)) {\n YYABORT;\n }\n s = NULL;\n actual = ext_instance;\n }\n\n break;\n\n case 823:\n\n { if (yang_check_ext_instance(trg, &((struct lys_restr *)(yyvsp[-2].v))->ext, ((struct lys_restr *)(yyvsp[-2].v))->ext_size, (yyvsp[-2].v), param->unres)) {\n YYABORT;\n }\n actual = ext_instance;\n }\n\n break;\n\n case 824:\n\n { if (yang_check_ext_instance(trg, &(*(struct lys_when **)(yyvsp[-2].v))->ext, (*(struct lys_when **)(yyvsp[-2].v))->ext_size,\n *(struct lys_when **)(yyvsp[-2].v), param->unres)) {\n YYABORT;\n }\n actual = ext_instance;\n }\n\n break;\n\n case 825:\n\n { int i;\n\n for (i = 0; i < (yyvsp[-2].revisions).index; ++i) {\n if (!strcmp((yyvsp[-2].revisions).revision[i]->date, (yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->date)) {\n LOGWRN(trg->ctx, \"Module's revisions are not unique (%s).\", (yyvsp[-2].revisions).revision[i]->date);\n break;\n }\n }\n if (yang_check_ext_instance(trg, &(yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->ext, (yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->ext_size,\n &(yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index], param->unres)) {\n YYABORT;\n }\n actual = ext_instance;\n }\n\n break;\n\n case 826:\n\n { actual = ext_instance;\n is_ext_instance = 1;\n }\n\n break;\n\n\n\n default: break;\n }\n /* User semantic actions sometimes alter yychar, and that requires\n that yytoken be updated with the new translation. We take the\n approach of translating immediately before every use of yytoken.\n One alternative is translating here after every semantic action,\n but that translation would be missed if the semantic action invokes\n YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or\n if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an\n incorrect destructor might then be invoked immediately. In the\n case of YYERROR or YYBACKUP, subsequent parser actions might lead\n to an incorrect destructor call or verbose syntax error message\n before the lookahead is translated. */\n YY_SYMBOL_PRINT (\"-> $$ =\", yyr1[yyn], &yyval, &yyloc);\n\n YYPOPSTACK (yylen);\n yylen = 0;\n YY_STACK_PRINT (yyss, yyssp);\n\n *++yyvsp = yyval;\n *++yylsp = yyloc;\n\n /* Now 'shift' the result of the reduction. Determine what state\n that goes to, based on the state we popped back to and the rule\n number reduced by. */\n {\n const int yylhs = yyr1[yyn] - YYNTOKENS;\n const int yyi = yypgoto[yylhs] + *yyssp;\n yystate = (0 <= yyi && yyi <= YYLAST && yycheck[yyi] == *yyssp\n ? yytable[yyi]\n : yydefgoto[yylhs]);\n }\n\n goto yynewstate;\n\n\n/*--------------------------------------.\n| yyerrlab -- here on detecting error. |\n`--------------------------------------*/\nyyerrlab:\n /* Make sure we have latest lookahead translation. See comments at\n user semantic actions for why this is necessary. */\n yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar);\n\n /* If not already recovering from an error, report this error. */\n if (!yyerrstatus)\n {\n ++yynerrs;\n#if ! YYERROR_VERBOSE\n yyerror (&yylloc, scanner, param, YY_(\"syntax error\"));\n#else\n# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \\\n yyssp, yytoken)\n {\n char const *yymsgp = YY_(\"syntax error\");\n int yysyntax_error_status;\n yysyntax_error_status = YYSYNTAX_ERROR;\n if (yysyntax_error_status == 0)\n yymsgp = yymsg;\n else if (yysyntax_error_status == 1)\n {\n if (yymsg != yymsgbuf)\n YYSTACK_FREE (yymsg);\n yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc);\n if (!yymsg)\n {\n yymsg = yymsgbuf;\n yymsg_alloc = sizeof yymsgbuf;\n yysyntax_error_status = 2;\n }\n else\n {\n yysyntax_error_status = YYSYNTAX_ERROR;\n yymsgp = yymsg;\n }\n }\n yyerror (&yylloc, scanner, param, yymsgp);\n if (yysyntax_error_status == 2)\n goto yyexhaustedlab;\n }\n# undef YYSYNTAX_ERROR\n#endif\n }\n\n yyerror_range[1] = yylloc;\n\n if (yyerrstatus == 3)\n {\n /* If just tried and failed to reuse lookahead token after an\n error, discard it. */\n\n if (yychar <= YYEOF)\n {\n /* Return failure if at end of input. */\n if (yychar == YYEOF)\n YYABORT;\n }\n else\n {\n yydestruct (\"Error: discarding\",\n yytoken, &yylval, &yylloc, scanner, param);\n yychar = YYEMPTY;\n }\n }\n\n /* Else will try to reuse lookahead token after shifting the error\n token. */\n goto yyerrlab1;\n\n\n/*---------------------------------------------------.\n| yyerrorlab -- error raised explicitly by YYERROR. |\n`---------------------------------------------------*/\nyyerrorlab:\n\n /* Pacify compilers like GCC when the user code never invokes\n YYERROR and the label yyerrorlab therefore never appears in user\n code. */\n if (/*CONSTCOND*/ 0)\n goto yyerrorlab;\n\n /* Do not reclaim the symbols of the rule whose action triggered\n this YYERROR. */\n YYPOPSTACK (yylen);\n yylen = 0;\n YY_STACK_PRINT (yyss, yyssp);\n yystate = *yyssp;\n goto yyerrlab1;\n\n\n/*-------------------------------------------------------------.\n| yyerrlab1 -- common code for both syntax error and YYERROR. |\n`-------------------------------------------------------------*/\nyyerrlab1:\n yyerrstatus = 3; /* Each real token shifted decrements this. */\n\n for (;;)\n {\n yyn = yypact[yystate];\n if (!yypact_value_is_default (yyn))\n {\n yyn += YYTERROR;\n if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)\n {\n yyn = yytable[yyn];\n if (0 < yyn)\n break;\n }\n }\n\n /* Pop the current state because it cannot handle the error token. */\n if (yyssp == yyss)\n YYABORT;\n\n yyerror_range[1] = *yylsp;\n yydestruct (\"Error: popping\",\n yystos[yystate], yyvsp, yylsp, scanner, param);\n YYPOPSTACK (1);\n yystate = *yyssp;\n YY_STACK_PRINT (yyss, yyssp);\n }\n\n YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN\n *++yyvsp = yylval;\n YY_IGNORE_MAYBE_UNINITIALIZED_END\n\n yyerror_range[2] = yylloc;\n /* Using YYLLOC is tempting, but would change the location of\n the lookahead. YYLOC is available though. */\n YYLLOC_DEFAULT (yyloc, yyerror_range, 2);\n *++yylsp = yyloc;\n\n /* Shift the error token. */\n YY_SYMBOL_PRINT (\"Shifting\", yystos[yyn], yyvsp, yylsp);\n\n yystate = yyn;\n goto yynewstate;\n\n\n/*-------------------------------------.\n| yyacceptlab -- YYACCEPT comes here. |\n`-------------------------------------*/\nyyacceptlab:\n yyresult = 0;\n goto yyreturn;\n\n/*-----------------------------------.\n| yyabortlab -- YYABORT comes here. |\n`-----------------------------------*/\nyyabortlab:\n yyresult = 1;\n goto yyreturn;\n\n#if !defined yyoverflow || YYERROR_VERBOSE\n/*-------------------------------------------------.\n| yyexhaustedlab -- memory exhaustion comes here. |\n`-------------------------------------------------*/\nyyexhaustedlab:\n yyerror (&yylloc, scanner, param, YY_(\"memory exhausted\"));\n yyresult = 2;\n /* Fall through. */\n#endif\n\nyyreturn:\n if (yychar != YYEMPTY)\n {\n /* Make sure we have latest lookahead translation. See comments at\n user semantic actions for why this is necessary. */\n yytoken = YYTRANSLATE (yychar);\n yydestruct (\"Cleanup: discarding lookahead\",\n yytoken, &yylval, &yylloc, scanner, param);\n }\n /* Do not reclaim the symbols of the rule whose action triggered\n this YYABORT or YYACCEPT. */\n YYPOPSTACK (yylen);\n YY_STACK_PRINT (yyss, yyssp);\n while (yyssp != yyss)\n {\n yydestruct (\"Cleanup: popping\",\n yystos[*yyssp], yyvsp, yylsp, scanner, param);\n YYPOPSTACK (1);\n }\n#ifndef yyoverflow\n if (yyss != yyssa)\n YYSTACK_FREE (yyss);\n#endif\n#if YYERROR_VERBOSE\n if (yymsg != yymsgbuf)\n YYSTACK_FREE (yymsg);\n#endif\n return yyresult; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-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 int sas_get_port_device(struct asd_sas_port *port)\n{\n\tstruct asd_sas_phy *phy;\n\tstruct sas_rphy *rphy;\n\tstruct domain_device *dev;\n\tint rc = -ENODEV;\n\n\tdev = sas_alloc_device();\n\tif (!dev)\n\t\treturn -ENOMEM;\n\n\tspin_lock_irq(&port->phy_list_lock);\n\tif (list_empty(&port->phy_list)) {\n\t\tspin_unlock_irq(&port->phy_list_lock);\n\t\tsas_put_device(dev);\n\t\treturn -ENODEV;\n\t}\n\tphy = container_of(port->phy_list.next, struct asd_sas_phy, port_phy_el);\n\tspin_lock(&phy->frame_rcvd_lock);\n\tmemcpy(dev->frame_rcvd, phy->frame_rcvd, min(sizeof(dev->frame_rcvd),\n\t\t\t\t\t (size_t)phy->frame_rcvd_size));\n\tspin_unlock(&phy->frame_rcvd_lock);\n\tspin_unlock_irq(&port->phy_list_lock);\n\n\tif (dev->frame_rcvd[0] == 0x34 && port->oob_mode == SATA_OOB_MODE) {\n\t\tstruct dev_to_host_fis *fis =\n\t\t\t(struct dev_to_host_fis *) dev->frame_rcvd;\n\t\tif (fis->interrupt_reason == 1 && fis->lbal == 1 &&\n\t\t fis->byte_count_low==0x69 && fis->byte_count_high == 0x96\n\t\t && (fis->device & ~0x10) == 0)\n\t\t\tdev->dev_type = SAS_SATA_PM;\n\t\telse\n\t\t\tdev->dev_type = SAS_SATA_DEV;\n\t\tdev->tproto = SAS_PROTOCOL_SATA;\n\t} else {\n\t\tstruct sas_identify_frame *id =\n\t\t\t(struct sas_identify_frame *) dev->frame_rcvd;\n\t\tdev->dev_type = id->dev_type;\n\t\tdev->iproto = id->initiator_bits;\n\t\tdev->tproto = id->target_bits;\n\t}\n\n\tsas_init_dev(dev);\n\n\tdev->port = port;\n\tswitch (dev->dev_type) {\n\tcase SAS_SATA_DEV:\n\t\trc = sas_ata_init(dev);\n\t\tif (rc) {\n\t\t\trphy = NULL;\n\t\t\tbreak;\n\t\t}\n\t\t/* fall through */\n\tcase SAS_END_DEVICE:\n\t\trphy = sas_end_device_alloc(port->port);\n\t\tbreak;\n\tcase SAS_EDGE_EXPANDER_DEVICE:\n\t\trphy = sas_expander_alloc(port->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(port->port,\n\t\t\t\t\t SAS_FANOUT_EXPANDER_DEVICE);\n\t\tbreak;\n\tdefault:\n\t\tpr_warn(\"ERROR: Unidentified device type %d\\n\", dev->dev_type);\n\t\trphy = NULL;\n\t\tbreak;\n\t}\n\n\tif (!rphy) {\n\t\tsas_put_device(dev);\n\t\treturn rc;\n\t}\n\n\trphy->identify.phy_identifier = phy->phy->identify.phy_identifier;\n\tmemcpy(dev->sas_addr, port->attached_sas_addr, SAS_ADDR_SIZE);\n\tsas_fill_in_rphy(dev, rphy);\n\tsas_hash_addr(dev->hashed_sas_addr, dev->sas_addr);\n\tport->port_dev = dev;\n\tdev->linkrate = port->linkrate;\n\tdev->min_linkrate = port->linkrate;\n\tdev->max_linkrate = port->linkrate;\n\tdev->pathways = port->num_phys;\n\tmemset(port->disc.fanout_sas_addr, 0, SAS_ADDR_SIZE);\n\tmemset(port->disc.eeds_a, 0, SAS_ADDR_SIZE);\n\tmemset(port->disc.eeds_b, 0, SAS_ADDR_SIZE);\n\tport->disc.max_level = 0;\n\tsas_device_set_phy(dev, port->port);\n\n\tdev->rphy = rphy;\n\tget_device(&dev->rphy->dev);\n\n\tif (dev_is_sata(dev) || dev->dev_type == SAS_END_DEVICE)\n\t\tlist_add_tail(&dev->disco_list_node, &port->disco_list);\n\telse {\n\t\tspin_lock_irq(&port->dev_list_lock);\n\t\tlist_add_tail(&dev->dev_list_node, &port->dev_list);\n\t\tspin_unlock_irq(&port->dev_list_lock);\n\t}\n\n\tspin_lock_irq(&port->phy_list_lock);\n\tlist_for_each_entry(phy, &port->phy_list, port_phy_el)\n\t\tsas_phy_set_target(phy, dev);\n\tspin_unlock_irq(&port->phy_list_lock);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'scsi: libsas: stop discovering if oob mode is disconnected\n\nThe discovering of sas port is driven by workqueue in libsas. When libsas\nis processing port events or phy events in workqueue, new events may rise\nup and change the state of some structures such as asd_sas_phy. This may\ncause some problems such as follows:\n\n==>thread 1 ==>thread 2\n\n ==>phy up\n ==>phy_up_v3_hw()\n ==>oob_mode = SATA_OOB_MODE;\n ==>phy down quickly\n ==>hisi_sas_phy_down()\n ==>sas_ha->notify_phy_event()\n ==>sas_phy_disconnected()\n ==>oob_mode = OOB_NOT_CONNECTED\n==>workqueue wakeup\n==>sas_form_port()\n ==>sas_discover_domain()\n ==>sas_get_port_device()\n ==>oob_mode is OOB_NOT_CONNECTED and device\n is wrongly taken as expander\n\nThis at last lead to the panic when libsas trying to issue a command to\ndiscover the device.\n\n[183047.614035] Unable to handle kernel NULL pointer dereference at\nvirtual address 0000000000000058\n[183047.622896] Mem abort info:\n[183047.625762] ESR = 0x96000004\n[183047.628893] Exception class = DABT (current EL), IL = 32 bits\n[183047.634888] SET = 0, FnV = 0\n[183047.638015] EA = 0, S1PTW = 0\n[183047.641232] Data abort info:\n[183047.644189] ISV = 0, ISS = 0x00000004\n[183047.648100] CM = 0, WnR = 0\n[183047.651145] user pgtable: 4k pages, 48-bit VAs, pgdp =\n00000000b7df67be\n[183047.657834] [0000000000000058] pgd=0000000000000000\n[183047.662789] Internal error: Oops: 96000004 [#1] SMP\n[183047.667740] Process kworker/u16:2 (pid: 31291, stack limit =\n0x00000000417c4974)\n[183047.675208] CPU: 0 PID: 3291 Comm: kworker/u16:2 Tainted: G\nW OE 4.19.36-vhulk1907.1.0.h410.eulerosv2r8.aarch64 #1\n[183047.687015] Hardware name: N/A N/A/Kunpeng Desktop Board D920S10,\nBIOS 0.15 10/22/2019\n[183047.695007] Workqueue: 0000:74:02.0_disco_q sas_discover_domain\n[183047.700999] pstate: 20c00009 (nzCv daif +PAN +UAO)\n[183047.705864] pc : prep_ata_v3_hw+0xf8/0x230 [hisi_sas_v3_hw]\n[183047.711510] lr : prep_ata_v3_hw+0xb0/0x230 [hisi_sas_v3_hw]\n[183047.717153] sp : ffff00000f28ba60\n[183047.720541] x29: ffff00000f28ba60 x28: ffff8026852d7228\n[183047.725925] x27: ffff8027dba3e0a8 x26: ffff8027c05fc200\n[183047.731310] x25: 0000000000000000 x24: ffff8026bafa8dc0\n[183047.736695] x23: ffff8027c05fc218 x22: ffff8026852d7228\n[183047.742079] x21: ffff80007c2f2940 x20: ffff8027c05fc200\n[183047.747464] x19: 0000000000f80800 x18: 0000000000000010\n[183047.752848] x17: 0000000000000000 x16: 0000000000000000\n[183047.758232] x15: ffff000089a5a4ff x14: 0000000000000005\n[183047.763617] x13: ffff000009a5a50e x12: ffff8026bafa1e20\n[183047.769001] x11: ffff0000087453b8 x10: ffff00000f28b870\n[183047.774385] x9 : 0000000000000000 x8 : ffff80007e58f9b0\n[183047.779770] x7 : 0000000000000000 x6 : 000000000000003f\n[183047.785154] x5 : 0000000000000040 x4 : ffffffffffffffe0\n[183047.790538] x3 : 00000000000000f8 x2 : 0000000002000007\n[183047.795922] x1 : 0000000000000008 x0 : 0000000000000000\n[183047.801307] Call trace:\n[183047.803827] prep_ata_v3_hw+0xf8/0x230 [hisi_sas_v3_hw]\n[183047.809127] hisi_sas_task_prep+0x750/0x888 [hisi_sas_main]\n[183047.814773] hisi_sas_task_exec.isra.7+0x88/0x1f0 [hisi_sas_main]\n[183047.820939] hisi_sas_queue_command+0x28/0x38 [hisi_sas_main]\n[183047.826757] smp_execute_task_sg+0xec/0x218\n[183047.831013] smp_execute_task+0x74/0xa0\n[183047.834921] sas_discover_expander.part.7+0x9c/0x5f8\n[183047.839959] sas_discover_root_expander+0x90/0x160\n[183047.844822] sas_discover_domain+0x1b8/0x1e8\n[183047.849164] process_one_work+0x1b4/0x3f8\n[183047.853246] worker_thread+0x54/0x470\n[183047.856981] kthread+0x134/0x138\n[183047.860283] ret_from_fork+0x10/0x18\n[183047.863931] Code: f9407a80 528000e2 39409281 72a04002 (b9405800)\n[183047.870097] kernel fault(0x1) notification starting on CPU 0\n[183047.875828] kernel fault(0x1) notification finished on CPU 0\n[183047.881559] Modules linked in: unibsp(OE) hns3(OE) hclge(OE)\nhnae3(OE) mem_drv(OE) hisi_sas_v3_hw(OE) hisi_sas_main(OE)\n[183047.892418] ---[ end trace 4cc26083fc11b783 ]---\n[183047.897107] Kernel panic - not syncing: Fatal exception\n[183047.902403] kernel fault(0x5) notification starting on CPU 0\n[183047.908134] kernel fault(0x5) notification finished on CPU 0\n[183047.913865] SMP: stopping secondary CPUs\n[183047.917861] Kernel Offset: disabled\n[183047.921422] CPU features: 0x2,a2a00a38\n[183047.925243] Memory Limit: none\n[183047.928372] kernel reboot(0x2) notification starting on CPU 0\n[183047.934190] kernel reboot(0x2) notification finished on CPU 0\n[183047.940008] ---[ end Kernel panic - not syncing: Fatal exception\n]---\n\nFixes: 2908d778ab3e (\"[SCSI] aic94xx: new driver\")\nLink: https://lore.kernel.org/r/20191206011118.46909-1-yanaijie@huawei.com\nReported-by: Gao Chuan \nReviewed-by: John Garry \nSigned-off-by: Jason Yan \nSigned-off-by: Martin K. Petersen '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int i915_gem_context_create_ioctl(struct drm_device *dev, void *data,\n\t\t\t\t struct drm_file *file)\n{\n\tstruct drm_i915_private *i915 = to_i915(dev);\n\tstruct drm_i915_gem_context_create *args = data;\n\tstruct drm_i915_file_private *file_priv = file->driver_priv;\n\tstruct i915_gem_context *ctx;\n\tint ret;\n\n\tif (!DRIVER_CAPS(i915)->has_logical_contexts)\n\t\treturn -ENODEV;\n\n\tif (args->pad != 0)\n\t\treturn -EINVAL;\n\n\tret = i915_terminally_wedged(i915);\n\tif (ret)\n\t\treturn ret;\n\n\tif (client_is_banned(file_priv)) {\n\t\tDRM_DEBUG(\"client %s[%d] banned from creating ctx\\n\",\n\t\t\t current->comm,\n\t\t\t pid_nr(get_task_pid(current, PIDTYPE_PID)));\n\n\t\treturn -EIO;\n\t}\n\n\tret = i915_mutex_lock_interruptible(dev);\n\tif (ret)\n\t\treturn ret;\n\n\tctx = i915_gem_create_context(i915);\n\tif (IS_ERR(ctx)) {\n\t\tret = PTR_ERR(ctx);\n\t\tgoto err_unlock;\n\t}\n\n\tret = gem_context_register(ctx, file_priv);\n\tif (ret)\n\t\tgoto err_ctx;\n\n\tmutex_unlock(&dev->struct_mutex);\n\n\targs->ctx_id = ctx->user_handle;\n\tDRM_DEBUG(\"HW context %d created\\n\", args->ctx_id);\n\n\treturn 0;\n\nerr_ctx:\n\tcontext_close(ctx);\nerr_unlock:\n\tmutex_unlock(&dev->struct_mutex);\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: u32 __skb_get_hash_symmetric(const struct sk_buff *skb)\n{\n\tstruct flow_keys keys;\n\n\t__flow_hash_secret_init();\n\n\tmemset(&keys, 0, sizeof(keys));\n\t__skb_flow_dissect(NULL, skb, &flow_keys_dissector_symmetric,\n\t\t\t &keys, NULL, 0, 0, 0,\n\t\t\t FLOW_DISSECTOR_F_STOP_AT_FLOW_LABEL);\n\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: static int sfb_enqueue(struct sk_buff *skb, struct Qdisc *sch,\n\t\t struct sk_buff **to_free)\n{\n\n\tstruct sfb_sched_data *q = qdisc_priv(sch);\n\tstruct Qdisc *child = q->qdisc;\n\tstruct tcf_proto *fl;\n\tint i;\n\tu32 p_min = ~0;\n\tu32 minqlen = ~0;\n\tu32 r, sfbhash;\n\tu32 slot = q->slot;\n\tint ret = NET_XMIT_SUCCESS | __NET_XMIT_BYPASS;\n\n\tif (unlikely(sch->q.qlen >= q->limit)) {\n\t\tqdisc_qstats_overlimit(sch);\n\t\tq->stats.queuedrop++;\n\t\tgoto drop;\n\t}\n\n\tif (q->rehash_interval > 0) {\n\t\tunsigned long limit = q->rehash_time + q->rehash_interval;\n\n\t\tif (unlikely(time_after(jiffies, limit))) {\n\t\t\tsfb_swap_slot(q);\n\t\t\tq->rehash_time = jiffies;\n\t\t} else if (unlikely(!q->double_buffering && q->warmup_time > 0 &&\n\t\t\t\t time_after(jiffies, limit - q->warmup_time))) {\n\t\t\tq->double_buffering = true;\n\t\t}\n\t}\n\n\tfl = rcu_dereference_bh(q->filter_list);\n\tif (fl) {\n\t\tu32 salt;\n\n\t\t/* If using external classifiers, get result and record it. */\n\t\tif (!sfb_classify(skb, fl, &ret, &salt))\n\t\t\tgoto other_drop;\n\t\tsfbhash = jhash_1word(salt, q->bins[slot].perturbation);\n\t} else {\n\t\tsfbhash = skb_get_hash_perturb(skb, q->bins[slot].perturbation);\n\t}\n\n\n\tif (!sfbhash)\n\t\tsfbhash = 1;\n\tsfb_skb_cb(skb)->hashes[slot] = sfbhash;\n\n\tfor (i = 0; i < SFB_LEVELS; i++) {\n\t\tu32 hash = sfbhash & SFB_BUCKET_MASK;\n\t\tstruct sfb_bucket *b = &q->bins[slot].bins[i][hash];\n\n\t\tsfbhash >>= SFB_BUCKET_SHIFT;\n\t\tif (b->qlen == 0)\n\t\t\tdecrement_prob(b, q);\n\t\telse if (b->qlen >= q->bin_size)\n\t\t\tincrement_prob(b, q);\n\t\tif (minqlen > b->qlen)\n\t\t\tminqlen = b->qlen;\n\t\tif (p_min > b->p_mark)\n\t\t\tp_min = b->p_mark;\n\t}\n\n\tslot ^= 1;\n\tsfb_skb_cb(skb)->hashes[slot] = 0;\n\n\tif (unlikely(minqlen >= q->max)) {\n\t\tqdisc_qstats_overlimit(sch);\n\t\tq->stats.bucketdrop++;\n\t\tgoto drop;\n\t}\n\n\tif (unlikely(p_min >= SFB_MAX_PROB)) {\n\t\t/* Inelastic flow */\n\t\tif (q->double_buffering) {\n\t\t\tsfbhash = skb_get_hash_perturb(skb,\n\t\t\t q->bins[slot].perturbation);\n\t\t\tif (!sfbhash)\n\t\t\t\tsfbhash = 1;\n\t\t\tsfb_skb_cb(skb)->hashes[slot] = sfbhash;\n\n\t\t\tfor (i = 0; i < SFB_LEVELS; i++) {\n\t\t\t\tu32 hash = sfbhash & SFB_BUCKET_MASK;\n\t\t\t\tstruct sfb_bucket *b = &q->bins[slot].bins[i][hash];\n\n\t\t\t\tsfbhash >>= SFB_BUCKET_SHIFT;\n\t\t\t\tif (b->qlen == 0)\n\t\t\t\t\tdecrement_prob(b, q);\n\t\t\t\telse if (b->qlen >= q->bin_size)\n\t\t\t\t\tincrement_prob(b, q);\n\t\t\t}\n\t\t}\n\t\tif (sfb_rate_limit(skb, q)) {\n\t\t\tqdisc_qstats_overlimit(sch);\n\t\t\tq->stats.penaltydrop++;\n\t\t\tgoto drop;\n\t\t}\n\t\tgoto enqueue;\n\t}\n\n\tr = prandom_u32() & SFB_MAX_PROB;\n\n\tif (unlikely(r < p_min)) {\n\t\tif (unlikely(p_min > SFB_MAX_PROB / 2)) {\n\t\t\t/* If we're marking that many packets, then either\n\t\t\t * this flow is unresponsive, or we're badly congested.\n\t\t\t * In either case, we want to start dropping packets.\n\t\t\t */\n\t\t\tif (r < (p_min - SFB_MAX_PROB / 2) * 2) {\n\t\t\t\tq->stats.earlydrop++;\n\t\t\t\tgoto drop;\n\t\t\t}\n\t\t}\n\t\tif (INET_ECN_set_ce(skb)) {\n\t\t\tq->stats.marked++;\n\t\t} else {\n\t\t\tq->stats.earlydrop++;\n\t\t\tgoto drop;\n\t\t}\n\t}\n\nenqueue:\n\tret = qdisc_enqueue(skb, child, to_free);\n\tif (likely(ret == NET_XMIT_SUCCESS)) {\n\t\tqdisc_qstats_backlog_inc(sch, skb);\n\t\tsch->q.qlen++;\n\t\tincrement_qlen(skb, q);\n\t} else if (net_xmit_drop_count(ret)) {\n\t\tq->stats.childdrop++;\n\t\tqdisc_qstats_drop(sch);\n\t}\n\treturn ret;\n\ndrop:\n\tqdisc_drop(skb, sch, to_free);\n\treturn NET_XMIT_CN;\nother_drop:\n\tif (ret & __NET_XMIT_BYPASS)\n\t\tqdisc_qstats_drop(sch);\n\tkfree_skb(skb);\n\treturn ret;\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* parseValue( char* ptr, FileNode& node, int min_indent, bool is_parent_flow )\n {\n char* endptr = 0;\n char c = ptr[0], d = ptr[1];\n int value_type = FileNode::NONE;\n int len;\n bool is_binary_string = false;\n bool is_user = false;\n\n if( c == '!' ) // handle explicit type specification\n {\n if( d == '!' || d == '^' )\n {\n ptr++;\n is_user = true;\n //value_type |= FileNode::USER;\n }\n if ( d == '<') //support of full type heading from YAML 1.2\n {\n const char* yamlTypeHeading = \"' && (size_t)(typeEndPtr - ptr) > headingLenght )\n {\n if ( memcmp(ptr, yamlTypeHeading, headingLenght) == 0 )\n {\n *typeEndPtr = ' ';\n ptr += headingLenght - 1;\n is_user = true;\n //value_type |= FileNode::USER;\n }\n }\n }\n\n endptr = ptr++;\n do d = *++endptr;\n while( cv_isprint(d) && d != ' ' );\n len = (int)(endptr - ptr);\n if( len == 0 )\n CV_PARSE_ERROR_CPP( \"Empty type name\" );\n d = *endptr;\n *endptr = '\\0';\n\n if( len == 3 && !is_user )\n {\n if( memcmp( ptr, \"str\", 3 ) == 0 )\n value_type = FileNode::STRING;\n else if( memcmp( ptr, \"int\", 3 ) == 0 )\n value_type = FileNode::INT;\n else if( memcmp( ptr, \"seq\", 3 ) == 0 )\n value_type = FileNode::SEQ;\n else if( memcmp( ptr, \"map\", 3 ) == 0 )\n value_type = FileNode::MAP;\n }\n else if( len == 5 && !is_user )\n {\n if( memcmp( ptr, \"float\", 5 ) == 0 )\n value_type = FileNode::REAL;\n }\n else if (len == 6 && is_user)\n {\n if( memcmp( ptr, \"binary\", 6 ) == 0 ) {\n value_type = FileNode::SEQ;\n is_binary_string = true;\n\n /* for ignore '|' */\n\n /**** operation with endptr ****/\n *endptr = d;\n\n do {\n d = *++endptr;\n if (d == '|')\n break;\n } while (d == ' ');\n\n d = *++endptr;\n *endptr = '\\0';\n }\n }\n\n *endptr = d;\n ptr = skipSpaces( endptr, min_indent, INT_MAX );\n\n c = *ptr;\n\n if( !is_user )\n {\n if (value_type == FileNode::STRING && c != '\\'' && c != '\\\"')\n goto force_string;\n if( value_type == FileNode::INT )\n goto force_int;\n if( value_type == FileNode::REAL )\n goto force_real;\n }\n }\n\n if (is_binary_string)\n {\n int indent = static_cast(ptr - fs->bufferStart());\n ptr = fs->parseBase64(ptr, indent, node);\n }\n else if( cv_isdigit(c) ||\n ((c == '-' || c == '+') && (cv_isdigit(d) || d == '.')) ||\n (c == '.' && cv_isalnum(d))) // a number\n {\n endptr = ptr + (c == '-' || c == '+');\n while( cv_isdigit(*endptr) )\n endptr++;\n if( *endptr == '.' || *endptr == 'e' )\n {\n force_real:\n double fval = fs->strtod( ptr, &endptr );\n node.setValue(FileNode::REAL, &fval);\n }\n else\n {\n force_int:\n int ival = (int)strtol( ptr, &endptr, 0 );\n node.setValue(FileNode::INT, &ival);\n }\n\n if( !endptr || endptr == ptr )\n CV_PARSE_ERROR_CPP( \"Invalid numeric value (inconsistent explicit type specification?)\" );\n\n ptr = endptr;\n CV_PERSISTENCE_CHECK_END_OF_BUFFER_BUG_CPP();\n }\n else if( c == '\\'' || c == '\\\"' ) // an explicit string\n {\n if( c == '\\'' )\n for( len = 0; len < CV_FS_MAX_LEN; )\n {\n c = *++ptr;\n if( cv_isalnum(c) || (c != '\\'' && cv_isprint(c)))\n buf[len++] = c;\n else if( c == '\\'' )\n {\n c = *++ptr;\n if( c != '\\'' )\n break;\n buf[len++] = c;\n }\n else\n CV_PARSE_ERROR_CPP( \"Invalid character\" );\n }\n else\n for( len = 0; len < CV_FS_MAX_LEN; )\n {\n c = *++ptr;\n if( cv_isalnum(c) || (c != '\\\\' && c != '\\\"' && cv_isprint(c)))\n buf[len++] = c;\n else if( c == '\\\"' )\n {\n ++ptr;\n break;\n }\n else if( c == '\\\\' )\n {\n d = *++ptr;\n if( d == '\\'' )\n buf[len++] = d;\n else if( d == '\\\"' || d == '\\\\' || d == '\\'' )\n buf[len++] = d;\n else if( d == 'n' )\n buf[len++] = '\\n';\n else if( d == 'r' )\n buf[len++] = '\\r';\n else if( d == 't' )\n buf[len++] = '\\t';\n else if( d == 'x' || (cv_isdigit(d) && d < '8') )\n {\n int val, is_hex = d == 'x';\n c = ptr[3];\n ptr[3] = '\\0';\n val = (int)strtol( ptr + is_hex, &endptr, is_hex ? 8 : 16 );\n ptr[3] = c;\n if( endptr == ptr + is_hex )\n buf[len++] = 'x';\n else\n {\n buf[len++] = (char)val;\n ptr = endptr;\n }\n }\n }\n else\n CV_PARSE_ERROR_CPP( \"Invalid character\" );\n }\n\n if( len >= CV_FS_MAX_LEN )\n CV_PARSE_ERROR_CPP( \"Too long string literal\" );\n\n node.setValue(FileNode::STRING, buf, len);\n }\n else if( c == '[' || c == '{' ) // collection as a flow\n {\n int new_min_indent = min_indent + !is_parent_flow;\n int struct_type = c == '{' ? FileNode::MAP : FileNode::SEQ;\n int nelems = 0;\n\n fs->convertToCollection(struct_type, node);\n d = c == '[' ? ']' : '}';\n\n for( ++ptr ;; nelems++ )\n {\n FileNode elem;\n\n ptr = skipSpaces( ptr, new_min_indent, INT_MAX );\n if( *ptr == '}' || *ptr == ']' )\n {\n if( *ptr != d )\n CV_PARSE_ERROR_CPP( \"The wrong closing bracket\" );\n ptr++;\n break;\n }\n\n if( nelems != 0 )\n {\n if( *ptr != ',' )\n CV_PARSE_ERROR_CPP( \"Missing , between the elements\" );\n ptr = skipSpaces( ptr + 1, new_min_indent, INT_MAX );\n }\n\n if( struct_type == FileNode::MAP )\n {\n ptr = parseKey( ptr, node, elem );\n ptr = skipSpaces( ptr, new_min_indent, INT_MAX );\n }\n else\n {\n if( *ptr == ']' )\n break;\n elem = fs->addNode(node, std::string(), FileNode::NONE);\n }\n ptr = parseValue( ptr, elem, new_min_indent, true );\n }\n fs->finalizeCollection(node);\n }\n else\n {\n int indent, struct_type;\n\n if( is_parent_flow || c != '-' )\n {\n // implicit (one-line) string or nested block-style collection\n if( !is_parent_flow )\n {\n if( c == '?' )\n CV_PARSE_ERROR_CPP( \"Complex keys are not supported\" );\n if( c == '|' || c == '>' )\n CV_PARSE_ERROR_CPP( \"Multi-line text literals are not supported\" );\n }\n\n force_string:\n endptr = ptr - 1;\n\n do c = *++endptr;\n while( cv_isprint(c) &&\n (!is_parent_flow || (c != ',' && c != '}' && c != ']')) &&\n (is_parent_flow || c != ':' || value_type == FileNode::STRING));\n\n if( endptr == ptr )\n CV_PARSE_ERROR_CPP( \"Invalid character\" );\n\n if( is_parent_flow || c != ':' )\n {\n char* str_end = endptr;\n // strip spaces in the end of string\n do c = *--str_end;\n while( str_end > ptr && c == ' ' );\n str_end++;\n node.setValue(FileNode::STRING, ptr, (int)(str_end - ptr));\n ptr = endptr;\n return ptr;\n }\n struct_type = FileNode::MAP;\n }\n else\n struct_type = FileNode::SEQ;\n\n fs->convertToCollection( struct_type, node );\n indent = (int)(ptr - fs->bufferStart());\n\n for(;;)\n {\n FileNode elem;\n\n if( struct_type == FileNode::MAP )\n {\n ptr = parseKey( ptr, node, elem );\n }\n else\n {\n c = *ptr++;\n if( c != '-' )\n CV_PARSE_ERROR_CPP( \"Block sequence elements must be preceded with \\'-\\'\" );\n\n elem = fs->addNode(node, std::string(), FileNode::NONE);\n }\n ptr = skipSpaces( ptr, indent + 1, INT_MAX );\n ptr = parseValue( ptr, elem, indent + 1, false );\n ptr = skipSpaces( ptr, 0, INT_MAX );\n if( ptr - fs->bufferStart() != indent )\n {\n if( ptr - fs->bufferStart() < indent )\n break;\n else\n CV_PARSE_ERROR_CPP( \"Incorrect indentation\" );\n }\n if( memcmp( ptr, \"...\", 3 ) == 0 )\n break;\n }\n fs->finalizeCollection(node);\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: char* parseKey( char* ptr, FileNode& collection, FileNode& value_placeholder )\n {\n if( *ptr != '\"' )\n CV_PARSE_ERROR_CPP( \"Key must start with \\'\\\"\\'\" );\n\n char * beg = ptr + 1;\n\n do {\n ++ptr;\n CV_PERSISTENCE_CHECK_END_OF_BUFFER_BUG_CPP();\n } while( cv_isprint(*ptr) && *ptr != '\"' );\n\n if( *ptr != '\"' )\n CV_PARSE_ERROR_CPP( \"Key must end with \\'\\\"\\'\" );\n\n const char * end = ptr;\n ptr++;\n ptr = skipSpaces( ptr );\n if( !ptr || !*ptr )\n return 0;\n\n if( *ptr != ':' )\n CV_PARSE_ERROR_CPP( \"Missing \\':\\' between key and value\" );\n\n /* [beg, end) */\n if( end <= beg )\n CV_PARSE_ERROR_CPP( \"Key is empty\" );\n\n value_placeholder = fs->addNode(collection, std::string(beg, (size_t)(end - beg)), FileNode::NONE);\n return ++ptr;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'core(persistence): added null ptr checks'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ipmi_sdr_print_sensor_generic_locator(struct sdr_record_generic_locator *dev)\n{\n\tchar desc[17];\n\n\tmemset(desc, 0, sizeof (desc));\n\tsnprintf(desc, (dev->id_code & 0x1f) + 1, \"%s\", dev->id_string);\n\n\tif (!verbose) {\n\t\tif (csv_output)\n\t\t\tprintf(\"%s,00h,ns,%d.%d\\n\",\n\t\t\t dev->id_code ? desc : \"\",\n\t\t\t dev->entity.id, dev->entity.instance);\n\t\telse if (sdr_extended)\n\t\t\tprintf\n\t\t\t (\"%-16s | 00h | ns | %2d.%1d | Generic Device @%02Xh:%02Xh.%1d\\n\",\n\t\t\t dev->id_code ? desc : \"\", dev->entity.id,\n\t\t\t dev->entity.instance, dev->dev_access_addr,\n\t\t\t dev->dev_slave_addr, dev->oem);\n\t\telse\n\t\t\tprintf(\"%-16s | Generic @%02X:%02X.%-2d | ok\\n\",\n\t\t\t dev->id_code ? desc : \"\",\n\t\t\t dev->dev_access_addr,\n\t\t\t dev->dev_slave_addr, dev->oem);\n\n\t\treturn 0;\n\t}\n\n\tprintf(\"Device ID : %s\\n\", dev->id_string);\n\tprintf(\"Entity ID : %d.%d (%s)\\n\",\n\t dev->entity.id, dev->entity.instance,\n\t val2str(dev->entity.id, entity_id_vals));\n\n\tprintf(\"Device Access Address : %02Xh\\n\", dev->dev_access_addr);\n\tprintf(\"Device Slave Address : %02Xh\\n\", dev->dev_slave_addr);\n\tprintf(\"Address Span : %02Xh\\n\", dev->addr_span);\n\tprintf(\"Channel Number : %01Xh\\n\", dev->channel_num);\n\tprintf(\"LUN.Bus : %01Xh.%01Xh\\n\", dev->lun, dev->bus);\n\tprintf(\"Device Type.Modifier : %01Xh.%01Xh (%s)\\n\",\n\t dev->dev_type, dev->dev_type_modifier,\n\t val2str(dev->dev_type << 8 | dev->dev_type_modifier,\n\t\t entity_device_type_vals));\n\tprintf(\"OEM : %02Xh\\n\", dev->oem);\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: static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){\n int i;\n WhereConst *pConst;\n if( pExpr->op!=TK_COLUMN ) return WRC_Continue;\n if( ExprHasProperty(pExpr, EP_FixedCol) ) return WRC_Continue;\n pConst = pWalker->u.pConst;\n for(i=0; inConst; i++){\n Expr *pColumn = pConst->apExpr[i*2];\n if( pColumn==pExpr ) continue;\n if( pColumn->iTable!=pExpr->iTable ) continue;\n if( pColumn->iColumn!=pExpr->iColumn ) continue;\n /* A match is found. Add the EP_FixedCol property */\n pConst->nChng++;\n ExprClearProperty(pExpr, EP_Leaf);\n ExprSetProperty(pExpr, EP_FixedCol);\n assert( pExpr->pLeft==0 );\n pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);\n break;\n }\n return WRC_Prune;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Do not allow the constant-propagation optimization to apple to ON/USING clause\nterms as it does not help and it might cause downstream problems.\n\nFossilOrigin-Name: 1bc783da63d58b05c690468b569cb2787846357b63c1100d11777666c5787bf4'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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[MagickPathExtent];\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,exception);\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\",MagickPathExtent);\n (void) AcquireUniqueFilename(read_info->filename);\n (void) FormatLocaleString(command,MagickPathExtent,\"-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: backward_search(regex_t* reg, const UChar* str, const UChar* end, UChar* s,\n const UChar* range, UChar* adjrange, UChar** low, UChar** high)\n{\n UChar *p;\n\n p = s;\n\n retry:\n switch (reg->optimize) {\n case OPTIMIZE_STR:\n exact_method:\n p = slow_search_backward(reg->enc, reg->exact, reg->exact_end,\n range, adjrange, end, p);\n break;\n\n case OPTIMIZE_STR_CASE_FOLD:\n p = slow_search_backward_ic(reg->enc, reg->case_fold_flag,\n reg->exact, reg->exact_end,\n range, adjrange, end, p);\n break;\n\n case OPTIMIZE_STR_FAST:\n case OPTIMIZE_STR_FAST_STEP_FORWARD:\n goto exact_method;\n break;\n\n case OPTIMIZE_MAP:\n p = map_search_backward(reg->enc, reg->map, range, adjrange, p);\n break;\n }\n\n if (p) {\n if (reg->sub_anchor) {\n UChar* prev;\n\n switch (reg->sub_anchor) {\n case ANCR_BEGIN_LINE:\n if (!ON_STR_BEGIN(p)) {\n prev = onigenc_get_prev_char_head(reg->enc, str, p);\n if (IS_NOT_NULL(prev) && !ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) {\n p = prev;\n goto retry;\n }\n }\n break;\n\n case ANCR_END_LINE:\n if (ON_STR_END(p)) {\n#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE\n prev = onigenc_get_prev_char_head(reg->enc, adjrange, p);\n if (IS_NULL(prev)) goto fail;\n if (ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) {\n p = prev;\n goto retry;\n }\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 p = onigenc_get_prev_char_head(reg->enc, adjrange, p);\n if (IS_NULL(p)) goto fail;\n goto retry;\n }\n break;\n }\n }\n\n if (reg->dist_max != INFINITE_LEN) {\n if ((ptrdiff_t )(p - str) < (ptrdiff_t )reg->dist_max)\n *low = (UChar* )str;\n else\n *low = p - reg->dist_max;\n\n if (reg->dist_min != 0) {\n if ((ptrdiff_t )(p - str) < (ptrdiff_t )reg->dist_min)\n *high = (UChar* )str;\n else\n *high = p - reg->dist_min;\n }\n else {\n *high = p;\n }\n\n *high = onigenc_get_right_adjust_char_head(reg->enc, adjrange, *high);\n }\n\n#ifdef ONIG_DEBUG_SEARCH\n fprintf(stderr, \"backward_search: low: %d, high: %d\\n\",\n (int )(*low - str), (int )(*high - str));\n#endif\n return 1; /* success */\n }\n\n fail:\n#ifdef ONIG_DEBUG_SEARCH\n fprintf(stderr, \"backward_search: fail.\\n\");\n#endif\n return 0; /* fail */\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: UnicodeString::doAppend(const UChar *srcChars, int32_t srcStart, int32_t srcLength) {\n if(!isWritable() || srcLength == 0 || srcChars == NULL) {\n return *this;\n }\n\n // Perform all remaining operations relative to srcChars + srcStart.\n // From this point forward, do not use srcStart.\n srcChars += srcStart;\n\n if(srcLength < 0) {\n // get the srcLength if necessary\n if((srcLength = u_strlen(srcChars)) == 0) {\n return *this;\n }\n }\n\n int32_t oldLength = length();\n int32_t newLength = oldLength + srcLength;\n\n // Check for append onto ourself\n const UChar* oldArray = getArrayStart();\n if (isBufferWritable() &&\n oldArray < srcChars + srcLength &&\n srcChars < oldArray + oldLength) {\n // Copy into a new UnicodeString and start over\n UnicodeString copy(srcChars, srcLength);\n if (copy.isBogus()) {\n setToBogus();\n return *this;\n }\n return doAppend(copy.getArrayStart(), 0, srcLength);\n }\n\n // optimize append() onto a large-enough, owned string\n if((newLength <= getCapacity() && isBufferWritable()) ||\n cloneArrayIfNeeded(newLength, getGrowCapacity(newLength))) {\n UChar *newArray = getArrayStart();\n // Do not copy characters when\n // UChar *buffer=str.getAppendBuffer(...);\n // is followed by\n // str.append(buffer, length);\n // or\n // str.appendString(buffer, length)\n // or similar.\n if(srcChars != newArray + oldLength) {\n us_arrayCopy(srcChars, 0, newArray, oldLength, srcLength);\n }\n setLength(newLength);\n }\n return *this;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-787'], 'message': 'ICU-20958 Prevent SEGV_MAPERR in append\n\nSee #971'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void ati_2d_blt(ATIVGAState *s)\n{\n /* FIXME it is probably more complex than this and may need to be */\n /* rewritten but for now as a start just to get some output: */\n DisplaySurface *ds = qemu_console_surface(s->vga.con);\n DPRINTF(\"%p %u ds: %p %d %d rop: %x\\n\", s->vga.vram_ptr,\n s->vga.vbe_start_addr, surface_data(ds), surface_stride(ds),\n surface_bits_per_pixel(ds),\n (s->regs.dp_mix & GMC_ROP3_MASK) >> 16);\n int dst_x = (s->regs.dp_cntl & DST_X_LEFT_TO_RIGHT ?\n s->regs.dst_x : s->regs.dst_x + 1 - s->regs.dst_width);\n int dst_y = (s->regs.dp_cntl & DST_Y_TOP_TO_BOTTOM ?\n s->regs.dst_y : s->regs.dst_y + 1 - s->regs.dst_height);\n int bpp = ati_bpp_from_datatype(s);\n int dst_stride = DEFAULT_CNTL ? s->regs.dst_pitch : s->regs.default_pitch;\n uint8_t *dst_bits = s->vga.vram_ptr + (DEFAULT_CNTL ?\n s->regs.dst_offset : s->regs.default_offset);\n\n if (s->dev_id == PCI_DEVICE_ID_ATI_RAGE128_PF) {\n dst_bits += s->regs.crtc_offset & 0x07ffffff;\n dst_stride *= bpp;\n }\n uint8_t *end = s->vga.vram_ptr + s->vga.vram_size;\n if (dst_bits >= end || dst_bits + dst_x + (dst_y + s->regs.dst_height) *\n dst_stride >= end) {\n qemu_log_mask(LOG_UNIMP, \"blt outside vram not implemented\\n\");\n return;\n }\n DPRINTF(\"%d %d %d, %d %d %d, (%d,%d) -> (%d,%d) %dx%d %c %c\\n\",\n s->regs.src_offset, s->regs.dst_offset, s->regs.default_offset,\n s->regs.src_pitch, s->regs.dst_pitch, s->regs.default_pitch,\n s->regs.src_x, s->regs.src_y, s->regs.dst_x, s->regs.dst_y,\n s->regs.dst_width, s->regs.dst_height,\n (s->regs.dp_cntl & DST_X_LEFT_TO_RIGHT ? '>' : '<'),\n (s->regs.dp_cntl & DST_Y_TOP_TO_BOTTOM ? 'v' : '^'));\n switch (s->regs.dp_mix & GMC_ROP3_MASK) {\n case ROP3_SRCCOPY:\n {\n int src_x = (s->regs.dp_cntl & DST_X_LEFT_TO_RIGHT ?\n s->regs.src_x : s->regs.src_x + 1 - s->regs.dst_width);\n int src_y = (s->regs.dp_cntl & DST_Y_TOP_TO_BOTTOM ?\n s->regs.src_y : s->regs.src_y + 1 - s->regs.dst_height);\n int src_stride = DEFAULT_CNTL ?\n s->regs.src_pitch : s->regs.default_pitch;\n uint8_t *src_bits = s->vga.vram_ptr + (DEFAULT_CNTL ?\n s->regs.src_offset : s->regs.default_offset);\n\n if (s->dev_id == PCI_DEVICE_ID_ATI_RAGE128_PF) {\n src_bits += s->regs.crtc_offset & 0x07ffffff;\n src_stride *= bpp;\n }\n if (src_bits >= end || src_bits + src_x +\n (src_y + s->regs.dst_height) * src_stride >= end) {\n qemu_log_mask(LOG_UNIMP, \"blt outside vram not implemented\\n\");\n return;\n }\n\n src_stride /= sizeof(uint32_t);\n dst_stride /= sizeof(uint32_t);\n DPRINTF(\"pixman_blt(%p, %p, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d)\\n\",\n src_bits, dst_bits, src_stride, dst_stride, bpp, bpp,\n src_x, src_y, dst_x, dst_y,\n s->regs.dst_width, s->regs.dst_height);\n if (s->regs.dp_cntl & DST_X_LEFT_TO_RIGHT &&\n s->regs.dp_cntl & DST_Y_TOP_TO_BOTTOM) {\n pixman_blt((uint32_t *)src_bits, (uint32_t *)dst_bits,\n src_stride, dst_stride, bpp, bpp,\n src_x, src_y, dst_x, dst_y,\n s->regs.dst_width, s->regs.dst_height);\n } else {\n /* FIXME: We only really need a temporary if src and dst overlap */\n int llb = s->regs.dst_width * (bpp / 8);\n int tmp_stride = DIV_ROUND_UP(llb, sizeof(uint32_t));\n uint32_t *tmp = g_malloc(tmp_stride * sizeof(uint32_t) *\n s->regs.dst_height);\n pixman_blt((uint32_t *)src_bits, tmp,\n src_stride, tmp_stride, bpp, bpp,\n src_x, src_y, 0, 0,\n s->regs.dst_width, s->regs.dst_height);\n pixman_blt(tmp, (uint32_t *)dst_bits,\n tmp_stride, dst_stride, bpp, bpp,\n 0, 0, dst_x, dst_y,\n s->regs.dst_width, s->regs.dst_height);\n g_free(tmp);\n }\n if (dst_bits >= s->vga.vram_ptr + s->vga.vbe_start_addr &&\n dst_bits < s->vga.vram_ptr + s->vga.vbe_start_addr +\n s->vga.vbe_regs[VBE_DISPI_INDEX_YRES] * s->vga.vbe_line_offset) {\n memory_region_set_dirty(&s->vga.vram, s->vga.vbe_start_addr +\n s->regs.dst_offset +\n dst_y * surface_stride(ds),\n s->regs.dst_height * surface_stride(ds));\n }\n s->regs.dst_x += s->regs.dst_width;\n s->regs.dst_y += s->regs.dst_height;\n break;\n }\n case ROP3_PATCOPY:\n case ROP3_BLACKNESS:\n case ROP3_WHITENESS:\n {\n uint32_t filler = 0;\n\n switch (s->regs.dp_mix & GMC_ROP3_MASK) {\n case ROP3_PATCOPY:\n filler = s->regs.dp_brush_frgd_clr;\n break;\n case ROP3_BLACKNESS:\n filler = 0xffUL << 24 | rgb_to_pixel32(s->vga.palette[0],\n s->vga.palette[1], s->vga.palette[2]);\n break;\n case ROP3_WHITENESS:\n filler = 0xffUL << 24 | rgb_to_pixel32(s->vga.palette[3],\n s->vga.palette[4], s->vga.palette[5]);\n break;\n }\n\n dst_stride /= sizeof(uint32_t);\n DPRINTF(\"pixman_fill(%p, %d, %d, %d, %d, %d, %d, %x)\\n\",\n dst_bits, dst_stride, bpp,\n s->regs.dst_x, s->regs.dst_y,\n s->regs.dst_width, s->regs.dst_height,\n filler);\n pixman_fill((uint32_t *)dst_bits, dst_stride, bpp,\n s->regs.dst_x, s->regs.dst_y,\n s->regs.dst_width, s->regs.dst_height,\n filler);\n if (dst_bits >= s->vga.vram_ptr + s->vga.vbe_start_addr &&\n dst_bits < s->vga.vram_ptr + s->vga.vbe_start_addr +\n s->vga.vbe_regs[VBE_DISPI_INDEX_YRES] * s->vga.vbe_line_offset) {\n memory_region_set_dirty(&s->vga.vram, s->vga.vbe_start_addr +\n s->regs.dst_offset +\n dst_y * surface_stride(ds),\n s->regs.dst_height * surface_stride(ds));\n }\n s->regs.dst_y += s->regs.dst_height;\n break;\n }\n default:\n qemu_log_mask(LOG_UNIMP, \"Unimplemented ati_2d blt op %x\\n\",\n (s->regs.dp_mix & GMC_ROP3_MASK) >> 16);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'ati-vga: Fix checks in ati_2d_blt() to avoid crash\n\nIn some corner cases (that never happen during normal operation but a\nmalicious guest could program wrong values) pixman functions were\ncalled with parameters that result in a crash. Fix this and add more\nchecks to disallow such cases.\n\nReported-by: Ziming Zhang \nSigned-off-by: BALATON Zoltan \nMessage-id: 20200406204029.19559747D5D@zero.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 void png_write_data(png_structp png_ptr, png_bytep data,\n png_size_t length)\n{\n VncState *vs = png_get_io_ptr(png_ptr);\n\n buffer_reserve(&vs->tight.png, vs->tight.png.offset + length);\n memcpy(vs->tight.png.buffer + vs->tight.png.offset, data, length);\n\n vs->tight.png.offset += length;\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: tight_filter_gradient24(VncState *vs, uint8_t *buf, int w, int h)\n{\n uint32_t *buf32;\n uint32_t pix32;\n int shift[3];\n int *prev;\n int here[3], upper[3], left[3], upperleft[3];\n int prediction;\n int x, y, c;\n\n buf32 = (uint32_t *)buf;\n memset(vs->tight.gradient.buffer, 0, w * 3 * sizeof(int));\n\n if (1 /* FIXME */) {\n shift[0] = vs->client_pf.rshift;\n shift[1] = vs->client_pf.gshift;\n shift[2] = vs->client_pf.bshift;\n } else {\n shift[0] = 24 - vs->client_pf.rshift;\n shift[1] = 24 - vs->client_pf.gshift;\n shift[2] = 24 - vs->client_pf.bshift;\n }\n\n for (y = 0; y < h; y++) {\n for (c = 0; c < 3; c++) {\n upper[c] = 0;\n here[c] = 0;\n }\n prev = (int *)vs->tight.gradient.buffer;\n for (x = 0; x < w; x++) {\n pix32 = *buf32++;\n for (c = 0; c < 3; c++) {\n upperleft[c] = upper[c];\n left[c] = here[c];\n upper[c] = *prev;\n here[c] = (int)(pix32 >> shift[c] & 0xFF);\n *prev++ = here[c];\n\n prediction = left[c] + upper[c] - upperleft[c];\n if (prediction < 0) {\n prediction = 0;\n } else if (prediction > 0xFF) {\n prediction = 0xFF;\n }\n *buf++ = (char)(here[c] - prediction);\n }\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-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_solid_rect(VncState *vs)\n{\n size_t bytes;\n\n vnc_write_u8(vs, VNC_TIGHT_FILL << 4); /* no flushing, no filter */\n\n if (vs->tight.pixel24) {\n tight_pack24(vs, vs->tight.tight.buffer, 1, &vs->tight.tight.offset);\n bytes = 3;\n } else {\n bytes = vs->client_pf.bytes_per_pixel;\n }\n\n vnc_write(vs, vs->tight.tight.buffer, bytes);\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: static int send_jpeg_rect(VncState *vs, int x, int y, int w, int h, int quality)\n{\n struct jpeg_compress_struct cinfo;\n struct jpeg_error_mgr jerr;\n struct jpeg_destination_mgr manager;\n pixman_image_t *linebuf;\n JSAMPROW row[1];\n uint8_t *buf;\n int dy;\n\n if (surface_bytes_per_pixel(vs->vd->ds) == 1) {\n return send_full_color_rect(vs, x, y, w, h);\n }\n\n buffer_reserve(&vs->tight.jpeg, 2048);\n\n cinfo.err = jpeg_std_error(&jerr);\n jpeg_create_compress(&cinfo);\n\n cinfo.client_data = vs;\n cinfo.image_width = w;\n cinfo.image_height = h;\n cinfo.input_components = 3;\n cinfo.in_color_space = JCS_RGB;\n\n jpeg_set_defaults(&cinfo);\n jpeg_set_quality(&cinfo, quality, true);\n\n manager.init_destination = jpeg_init_destination;\n manager.empty_output_buffer = jpeg_empty_output_buffer;\n manager.term_destination = jpeg_term_destination;\n cinfo.dest = &manager;\n\n jpeg_start_compress(&cinfo, true);\n\n linebuf = qemu_pixman_linebuf_create(PIXMAN_BE_r8g8b8, w);\n buf = (uint8_t *)pixman_image_get_data(linebuf);\n row[0] = buf;\n for (dy = 0; dy < h; dy++) {\n qemu_pixman_linebuf_fill(linebuf, vs->vd->server, w, x, y + dy);\n jpeg_write_scanlines(&cinfo, row, 1);\n }\n qemu_pixman_image_unref(linebuf);\n\n jpeg_finish_compress(&cinfo);\n jpeg_destroy_compress(&cinfo);\n\n vnc_write_u8(vs, VNC_TIGHT_JPEG << 4);\n\n tight_send_compact_size(vs, vs->tight.jpeg.offset);\n vnc_write(vs, vs->tight.jpeg.buffer, vs->tight.jpeg.offset);\n buffer_reset(&vs->tight.jpeg);\n\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: PyParser_AddToken(parser_state *ps, int type, char *str,\n int lineno, int col_offset,\n int end_lineno, int end_col_offset,\n int *expected_ret)\n{\n int ilabel;\n int err;\n\n D(printf(\"Token %s/'%s' ... \", _PyParser_TokenNames[type], str));\n\n /* Find out which label this token is */\n ilabel = classify(ps, type, str);\n if (ilabel < 0)\n return E_SYNTAX;\n\n /* Loop until the token is shifted or an error occurred */\n for (;;) {\n /* Fetch the current dfa and state */\n dfa *d = ps->p_stack.s_top->s_dfa;\n state *s = &d->d_state[ps->p_stack.s_top->s_state];\n\n D(printf(\" DFA '%s', state %d:\",\n d->d_name, ps->p_stack.s_top->s_state));\n\n /* Check accelerator */\n if (s->s_lower <= ilabel && ilabel < s->s_upper) {\n int x = s->s_accel[ilabel - s->s_lower];\n if (x != -1) {\n if (x & (1<<7)) {\n /* Push non-terminal */\n int nt = (x >> 8) + NT_OFFSET;\n int arrow = x & ((1<<7)-1);\n dfa *d1 = PyGrammar_FindDFA(\n ps->p_grammar, nt);\n if ((err = push(&ps->p_stack, nt, d1,\n arrow, lineno, col_offset,\n end_lineno, end_col_offset)) > 0) {\n D(printf(\" MemError: push\\n\"));\n return err;\n }\n D(printf(\" Push ...\\n\"));\n continue;\n }\n\n /* Shift the token */\n if ((err = shift(&ps->p_stack, type, str,\n x, lineno, col_offset,\n end_lineno, end_col_offset)) > 0) {\n D(printf(\" MemError: shift.\\n\"));\n return err;\n }\n D(printf(\" Shift.\\n\"));\n /* Pop while we are in an accept-only state */\n while (s = &d->d_state\n [ps->p_stack.s_top->s_state],\n s->s_accept && s->s_narcs == 1) {\n D(printf(\" DFA '%s', state %d: \"\n \"Direct pop.\\n\",\n d->d_name,\n ps->p_stack.s_top->s_state));\n#ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD\n#if 0\n if (d->d_name[0] == 'i' &&\n strcmp(d->d_name,\n \"import_stmt\") == 0)\n future_hack(ps);\n#endif\n#endif\n s_pop(&ps->p_stack);\n if (s_empty(&ps->p_stack)) {\n D(printf(\" ACCEPT.\\n\"));\n return E_DONE;\n }\n d = ps->p_stack.s_top->s_dfa;\n }\n return E_OK;\n }\n }\n\n if (s->s_accept) {\n#ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD\n#if 0\n if (d->d_name[0] == 'i' &&\n strcmp(d->d_name, \"import_stmt\") == 0)\n future_hack(ps);\n#endif\n#endif\n /* Pop this dfa and try again */\n s_pop(&ps->p_stack);\n D(printf(\" Pop ...\\n\"));\n if (s_empty(&ps->p_stack)) {\n D(printf(\" Error: bottom of stack.\\n\"));\n return E_SYNTAX;\n }\n continue;\n }\n\n /* Stuck, report syntax error */\n D(printf(\" Error.\\n\"));\n if (expected_ret) {\n if (s->s_lower == s->s_upper - 1) {\n /* Only one possible expected token */\n *expected_ret = ps->p_grammar->\n g_ll.ll_label[s->s_lower].lb_type;\n }\n else\n *expected_ret = -1;\n }\n return E_SYNTAX;\n }\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: Module(asdl_seq * body, PyArena *arena)\n{\n mod_ty p;\n p = (mod_ty)PyArena_Malloc(arena, sizeof(*p));\n if (!p)\n return NULL;\n p->kind = Module_kind;\n p->v.Module.body = body;\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: AsyncWith(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 = AsyncWith_kind;\n p->v.AsyncWith.items = items;\n p->v.AsyncWith.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: Assign(asdl_seq * targets, expr_ty value, int lineno, int col_offset, int\n end_lineno, int end_col_offset, PyArena *arena)\n{\n stmt_ty p;\n if (!value) {\n PyErr_SetString(PyExc_ValueError,\n \"field value is required for Assign\");\n return NULL;\n }\n p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));\n if (!p)\n return NULL;\n p->kind = Assign_kind;\n p->v.Assign.targets = targets;\n p->v.Assign.value = value;\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::handle_keepalive2(ceph::bufferlist &payload)\n{\n ldout(cct, 20) << __func__\n\t\t << \" payload.length()=\" << payload.length() << dendl;\n\n if (state != READY) {\n lderr(cct) << __func__ << \" not in ready state!\" << dendl;\n return _fault();\n }\n\n auto keepalive_frame = KeepAliveFrame::Decode(payload);\n\n ldout(cct, 30) << __func__ << \" got KEEPALIVE2 tag ...\" << dendl;\n\n connection->write_lock.lock();\n append_keepalive_ack(keepalive_frame.timestamp());\n connection->write_lock.unlock();\n\n ldout(cct, 20) << __func__ << \" got KEEPALIVE2 \"\n << keepalive_frame.timestamp() << dendl;\n connection->set_last_keepalive(ceph_clock_now());\n\n if (is_connected()) {\n connection->center->dispatch_event_external(connection->write_handler);\n }\n\n return CONTINUE(read_frame);\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 AES128GCM_OnWireRxHandler::reset_rx_handler()\n{\n if(1 != EVP_DecryptInit_ex(ectx.get(), nullptr, nullptr, nullptr,\n\treinterpret_cast(&nonce))) {\n throw std::runtime_error(\"EVP_DecryptInit_ex failed\");\n }\n ++nonce.random_seq;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-323'], 'message': 'msg/async/crypto_onwire: fix endianness of nonce_t\n\nAs a AES-GCM IV, nonce_t is implicitly shared between server and\nclient. Currently, if their endianness doesn't match, they are unable\nto communicate in secure mode because each gets its own idea of what\nthe next nonce should be after the counter is incremented.\n\nSeveral RFCs state that the nonce counter should be BE, but since we\nuse LE for everything on-disk and on-wire, make it LE.\n\nSigned-off-by: Ilya Dryomov \nReviewed-by: Radoslaw Zarzynski \nReviewed-by: Sage Weil '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int RGWGetObj_ObjStore_S3::send_response_data(bufferlist& bl, off_t bl_ofs,\n\t\t\t\t\t off_t bl_len)\n{\n const char *content_type = NULL;\n string content_type_str;\n map response_attrs;\n map::iterator riter;\n bufferlist metadata_bl;\n\n if (sent_header)\n goto send_data;\n\n if (custom_http_ret) {\n set_req_state_err(s, 0);\n dump_errno(s, custom_http_ret);\n } else {\n set_req_state_err(s, (partial_content && !op_ret) ? STATUS_PARTIAL_CONTENT\n : op_ret);\n dump_errno(s);\n }\n\n if (op_ret)\n goto done;\n\n if (range_str)\n dump_range(s, start, end, s->obj_size);\n\n if (s->system_request &&\n s->info.args.exists(RGW_SYS_PARAM_PREFIX \"prepend-metadata\")) {\n\n dump_header(s, \"Rgwx-Object-Size\", (long long)total_len);\n\n if (rgwx_stat) {\n /*\n * in this case, we're not returning the object's content, only the prepended\n * extra metadata\n */\n total_len = 0;\n }\n\n /* JSON encode object metadata */\n JSONFormatter jf;\n jf.open_object_section(\"obj_metadata\");\n encode_json(\"attrs\", attrs, &jf);\n utime_t ut(lastmod);\n encode_json(\"mtime\", ut, &jf);\n jf.close_section();\n stringstream ss;\n jf.flush(ss);\n metadata_bl.append(ss.str());\n dump_header(s, \"Rgwx-Embedded-Metadata-Len\", metadata_bl.length());\n total_len += metadata_bl.length();\n }\n\n if (s->system_request && !real_clock::is_zero(lastmod)) {\n /* we end up dumping mtime in two different methods, a bit redundant */\n dump_epoch_header(s, \"Rgwx-Mtime\", lastmod);\n uint64_t pg_ver = 0;\n int r = decode_attr_bl_single_value(attrs, RGW_ATTR_PG_VER, &pg_ver, (uint64_t)0);\n if (r < 0) {\n ldout(s->cct, 0) << \"ERROR: failed to decode pg ver attr, ignoring\" << dendl;\n }\n dump_header(s, \"Rgwx-Obj-PG-Ver\", pg_ver);\n\n uint32_t source_zone_short_id = 0;\n r = decode_attr_bl_single_value(attrs, RGW_ATTR_SOURCE_ZONE, &source_zone_short_id, (uint32_t)0);\n if (r < 0) {\n ldout(s->cct, 0) << \"ERROR: failed to decode pg ver attr, ignoring\" << dendl;\n }\n if (source_zone_short_id != 0) {\n dump_header(s, \"Rgwx-Source-Zone-Short-Id\", source_zone_short_id);\n }\n }\n\n for (auto &it : crypt_http_responses)\n dump_header(s, it.first, it.second);\n\n dump_content_length(s, total_len);\n dump_last_modified(s, lastmod);\n dump_header_if_nonempty(s, \"x-amz-version-id\", version_id);\n if (attrs.find(RGW_ATTR_APPEND_PART_NUM) != attrs.end()) {\n dump_header(s, \"x-rgw-object-type\", \"Appendable\");\n dump_header(s, \"x-rgw-next-append-position\", s->obj_size);\n } else {\n dump_header(s, \"x-rgw-object-type\", \"Normal\");\n }\n\n if (! op_ret) {\n if (! lo_etag.empty()) {\n /* Handle etag of Swift API's large objects (DLO/SLO). It's entirerly\n * legit to perform GET on them through S3 API. In such situation,\n * a client should receive the composited content with corresponding\n * etag value. */\n dump_etag(s, lo_etag);\n } else {\n auto iter = attrs.find(RGW_ATTR_ETAG);\n if (iter != attrs.end()) {\n dump_etag(s, iter->second.to_str());\n }\n }\n\n for (struct response_attr_param *p = resp_attr_params; p->param; p++) {\n bool exists;\n string val = s->info.args.get(p->param, &exists);\n if (exists) {\n\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 -EPERM;\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: EPERM to ERR_INVALID_REQUEST\n\nAs per Robin's comments and S3 spec\n\nSigned-off-by: Abhishek Lekshmanan '" }, { "text": "[INST] Given the following code containing errors, provide Common 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_DEFINE1(brk, unsigned long, brk)\n{\n\tunsigned long retval;\n\tunsigned long newbrk, oldbrk, origbrk;\n\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *next;\n\tunsigned long min_brk;\n\tbool populate;\n\tbool downgraded = false;\n\tLIST_HEAD(uf);\n\n\tbrk = untagged_addr(brk);\n\n\tif (down_write_killable(&mm->mmap_sem))\n\t\treturn -EINTR;\n\n\torigbrk = mm->brk;\n\n#ifdef CONFIG_COMPAT_BRK\n\t/*\n\t * CONFIG_COMPAT_BRK can still be overridden by setting\n\t * randomize_va_space to 2, which will still cause mm->start_brk\n\t * to be arbitrarily shifted\n\t */\n\tif (current->brk_randomized)\n\t\tmin_brk = mm->start_brk;\n\telse\n\t\tmin_brk = mm->end_data;\n#else\n\tmin_brk = mm->start_brk;\n#endif\n\tif (brk < min_brk)\n\t\tgoto out;\n\n\t/*\n\t * Check against rlimit here. If this check is done later after the test\n\t * of oldbrk with newbrk then it can escape the test and let the data\n\t * segment grow beyond its set limit the in case where the limit is\n\t * not page aligned -Ram Gupta\n\t */\n\tif (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,\n\t\t\t mm->end_data, mm->start_data))\n\t\tgoto out;\n\n\tnewbrk = PAGE_ALIGN(brk);\n\toldbrk = PAGE_ALIGN(mm->brk);\n\tif (oldbrk == newbrk) {\n\t\tmm->brk = brk;\n\t\tgoto success;\n\t}\n\n\t/*\n\t * Always allow shrinking brk.\n\t * __do_munmap() may downgrade mmap_sem to read.\n\t */\n\tif (brk <= mm->brk) {\n\t\tint ret;\n\n\t\t/*\n\t\t * mm->brk must to be protected by write mmap_sem so update it\n\t\t * before downgrading mmap_sem. When __do_munmap() fails,\n\t\t * mm->brk will be restored from origbrk.\n\t\t */\n\t\tmm->brk = brk;\n\t\tret = __do_munmap(mm, newbrk, oldbrk-newbrk, &uf, true);\n\t\tif (ret < 0) {\n\t\t\tmm->brk = origbrk;\n\t\t\tgoto out;\n\t\t} else if (ret == 1) {\n\t\t\tdowngraded = true;\n\t\t}\n\t\tgoto success;\n\t}\n\n\t/* Check against existing mmap mappings. */\n\tnext = find_vma(mm, oldbrk);\n\tif (next && newbrk + PAGE_SIZE > vm_start_gap(next))\n\t\tgoto out;\n\n\t/* Ok, looks good - let it rip. */\n\tif (do_brk_flags(oldbrk, newbrk-oldbrk, 0, &uf) < 0)\n\t\tgoto out;\n\tmm->brk = brk;\n\nsuccess:\n\tpopulate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;\n\tif (downgraded)\n\t\tup_read(&mm->mmap_sem);\n\telse\n\t\tup_write(&mm->mmap_sem);\n\tuserfaultfd_unmap_complete(mm, &uf);\n\tif (populate)\n\t\tmm_populate(oldbrk, newbrk - oldbrk);\n\treturn brk;\n\nout:\n\tretval = origbrk;\n\tup_write(&mm->mmap_sem);\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_instantiate (CONF_SECTION *cs, void **instance)\n{\n\teap_pwd_t *inst;\n\n\t*instance = inst = talloc_zero(cs, eap_pwd_t);\n\tif (!inst) return -1;\n\n\tif (cf_section_parse(cs, inst, pwd_module_config) < 0) {\n\t\treturn -1;\n\t}\n\n\tif (inst->fragment_size < 100) {\n\t\tcf_log_err_cs(cs, \"Fragment size is too small\");\n\t\treturn -1;\n\t}\n\n\tif ((inst->bnctx = BN_CTX_new()) == NULL) {\n\t\tcf_log_err_cs(cs, \"Failed to get BN context\");\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-662'], 'message': 'EAP-pwd: fix DoS due to multithreaded BN_CTX access\n\nThe EAP-pwd module created one global OpenSSL BN_CTX instance, and\nused this instance in all incoming requests. This means that different\nthreads used the same BN_CTX instance, which can result in a crash.\nAn adversary can trigger these crashes by concurrently initiating\nmultiple EAP-pwd handshakes from different clients.\n\nFix this bug by creating a separate BN_CTX instance for each request.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ssize_t mon_text_read_u(struct file *file, char __user *buf,\n\t\t\t\tsize_t nbytes, loff_t *ppos)\n{\n\tstruct mon_reader_text *rp = file->private_data;\n\tstruct mon_event_text *ep;\n\tstruct mon_text_ptr ptr;\n\n\tep = mon_text_read_wait(rp, file);\n\tif (IS_ERR(ep))\n\t\treturn PTR_ERR(ep);\n\tmutex_lock(&rp->printf_lock);\n\tptr.cnt = 0;\n\tptr.pbuf = rp->printf_buf;\n\tptr.limit = rp->printf_size;\n\n\tmon_text_read_head_u(rp, &ptr, ep);\n\tif (ep->type == 'E') {\n\t\tmon_text_read_statset(rp, &ptr, ep);\n\t} else if (ep->xfertype == USB_ENDPOINT_XFER_ISOC) {\n\t\tmon_text_read_isostat(rp, &ptr, ep);\n\t\tmon_text_read_isodesc(rp, &ptr, ep);\n\t} else if (ep->xfertype == USB_ENDPOINT_XFER_INT) {\n\t\tmon_text_read_intstat(rp, &ptr, ep);\n\t} else {\n\t\tmon_text_read_statset(rp, &ptr, ep);\n\t}\n\tptr.cnt += snprintf(ptr.pbuf + ptr.cnt, ptr.limit - ptr.cnt,\n\t \" %d\", ep->length);\n\tmon_text_read_data(rp, &ptr, ep);\n\n\tif (copy_to_user(buf, rp->printf_buf, ptr.cnt))\n\t\tptr.cnt = -EFAULT;\n\tmutex_unlock(&rp->printf_lock);\n\tkmem_cache_free(rp->e_slab, ep);\n\treturn ptr.cnt;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'usb: usbmon: Read text within supplied buffer size\n\nThis change fixes buffer overflows and silent data corruption with the\nusbmon device driver text file read operations.\n\nSigned-off-by: Fredrik Noring \nSigned-off-by: Pete Zaitcev \nCc: stable \nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void tulip_xmit_list_update(TULIPState *s)\n{\n struct tulip_descriptor desc;\n\n if (tulip_ts(s) != CSR5_TS_SUSPENDED) {\n return;\n }\n\n for (;;) {\n tulip_desc_read(s, s->current_tx_desc, &desc);\n tulip_dump_tx_descriptor(s, &desc);\n\n if (!(desc.status & TDES0_OWN)) {\n tulip_update_ts(s, CSR5_TS_SUSPENDED);\n s->csr[5] |= CSR5_TU;\n tulip_update_int(s);\n return;\n }\n\n if (desc.control & TDES1_SET) {\n tulip_setup_frame(s, &desc);\n } else {\n if (desc.control & TDES1_FS) {\n s->tx_frame_len = 0;\n }\n\n tulip_copy_tx_buffers(s, &desc);\n\n if (desc.control & TDES1_LS) {\n tulip_tx(s, &desc);\n }\n }\n tulip_desc_write(s, s->current_tx_desc, &desc);\n tulip_next_tx_descriptor(s, &desc);\n }\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: int mpol_parse_str(char *str, struct mempolicy **mpol)\n{\n\tstruct mempolicy *new = NULL;\n\tunsigned short mode_flags;\n\tnodemask_t nodes;\n\tchar *nodelist = strchr(str, ':');\n\tchar *flags = strchr(str, '=');\n\tint err = 1, mode;\n\n\tif (flags)\n\t\t*flags++ = '\\0';\t/* terminate mode string */\n\n\tif (nodelist) {\n\t\t/* NUL-terminate mode or flags string */\n\t\t*nodelist++ = '\\0';\n\t\tif (nodelist_parse(nodelist, nodes))\n\t\t\tgoto out;\n\t\tif (!nodes_subset(nodes, node_states[N_MEMORY]))\n\t\t\tgoto out;\n\t} else\n\t\tnodes_clear(nodes);\n\n\tmode = match_string(policy_modes, MPOL_MAX, str);\n\tif (mode < 0)\n\t\tgoto out;\n\n\tswitch (mode) {\n\tcase MPOL_PREFERRED:\n\t\t/*\n\t\t * Insist on a nodelist of one node only\n\t\t */\n\t\tif (nodelist) {\n\t\t\tchar *rest = nodelist;\n\t\t\twhile (isdigit(*rest))\n\t\t\t\trest++;\n\t\t\tif (*rest)\n\t\t\t\tgoto out;\n\t\t}\n\t\tbreak;\n\tcase MPOL_INTERLEAVE:\n\t\t/*\n\t\t * Default to online nodes with memory if no nodelist\n\t\t */\n\t\tif (!nodelist)\n\t\t\tnodes = node_states[N_MEMORY];\n\t\tbreak;\n\tcase MPOL_LOCAL:\n\t\t/*\n\t\t * Don't allow a nodelist; mpol_new() checks flags\n\t\t */\n\t\tif (nodelist)\n\t\t\tgoto out;\n\t\tmode = MPOL_PREFERRED;\n\t\tbreak;\n\tcase MPOL_DEFAULT:\n\t\t/*\n\t\t * Insist on a empty nodelist\n\t\t */\n\t\tif (!nodelist)\n\t\t\terr = 0;\n\t\tgoto out;\n\tcase MPOL_BIND:\n\t\t/*\n\t\t * Insist on a nodelist\n\t\t */\n\t\tif (!nodelist)\n\t\t\tgoto out;\n\t}\n\n\tmode_flags = 0;\n\tif (flags) {\n\t\t/*\n\t\t * Currently, we only support two mutually exclusive\n\t\t * mode flags.\n\t\t */\n\t\tif (!strcmp(flags, \"static\"))\n\t\t\tmode_flags |= MPOL_F_STATIC_NODES;\n\t\telse if (!strcmp(flags, \"relative\"))\n\t\t\tmode_flags |= MPOL_F_RELATIVE_NODES;\n\t\telse\n\t\t\tgoto out;\n\t}\n\n\tnew = mpol_new(mode, mode_flags, &nodes);\n\tif (IS_ERR(new))\n\t\tgoto out;\n\n\t/*\n\t * Save nodes for mpol_to_str() to show the tmpfs mount options\n\t * for /proc/mounts, /proc/pid/mounts and /proc/pid/mountinfo.\n\t */\n\tif (mode != MPOL_PREFERRED)\n\t\tnew->v.nodes = nodes;\n\telse if (nodelist)\n\t\tnew->v.preferred_node = first_node(nodes);\n\telse\n\t\tnew->flags |= MPOL_F_LOCAL;\n\n\t/*\n\t * Save nodes for contextualization: this will be used to \"clone\"\n\t * the mempolicy in a specific context [cpuset] at a later time.\n\t */\n\tnew->w.user_nodemask = nodes;\n\n\terr = 0;\n\nout:\n\t/* Restore string for error message */\n\tif (nodelist)\n\t\t*--nodelist = ':';\n\tif (flags)\n\t\t*--flags = '=';\n\tif (!err)\n\t\t*mpol = new;\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'mm: mempolicy: require at least one nodeid for MPOL_PREFERRED\n\nUsing an empty (malformed) nodelist that is not caught during mount option\nparsing leads to a stack-out-of-bounds access.\n\nThe option string that was used was: \"mpol=prefer:,\". However,\nMPOL_PREFERRED requires a single node number, which is not being provided\nhere.\n\nAdd a check that 'nodes' is not empty after parsing for MPOL_PREFERRED's\nnodeid.\n\nFixes: 095f1fc4ebf3 (\"mempolicy: rework shmem mpol parsing and display\")\nReported-by: Entropy Moe <3ntr0py1337@gmail.com>\nReported-by: syzbot+b055b1a6b2b958707a21@syzkaller.appspotmail.com\nSigned-off-by: Randy Dunlap \nSigned-off-by: Andrew Morton \nTested-by: syzbot+b055b1a6b2b958707a21@syzkaller.appspotmail.com\nCc: Lee Schermerhorn \nLink: http://lkml.kernel.org/r/89526377-7eb6-b662-e1d8-4430928abde9@infradead.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: transform_chain_param(struct rte_crypto_sym_xform *xforms,\n\t\tVhostUserCryptoSessionParam *param)\n{\n\tstruct rte_crypto_sym_xform *xform_cipher, *xform_auth;\n\tint ret;\n\n\tswitch (param->chaining_dir) {\n\tcase VIRTIO_CRYPTO_SYM_ALG_CHAIN_ORDER_HASH_THEN_CIPHER:\n\t\txform_auth = xforms;\n\t\txform_cipher = xforms->next;\n\t\txform_cipher->cipher.op = RTE_CRYPTO_CIPHER_OP_DECRYPT;\n\t\txform_auth->auth.op = RTE_CRYPTO_AUTH_OP_VERIFY;\n\t\tbreak;\n\tcase VIRTIO_CRYPTO_SYM_ALG_CHAIN_ORDER_CIPHER_THEN_HASH:\n\t\txform_cipher = xforms;\n\t\txform_auth = xforms->next;\n\t\txform_cipher->cipher.op = RTE_CRYPTO_CIPHER_OP_ENCRYPT;\n\t\txform_auth->auth.op = RTE_CRYPTO_AUTH_OP_GENERATE;\n\t\tbreak;\n\tdefault:\n\t\treturn -VIRTIO_CRYPTO_BADMSG;\n\t}\n\n\t/* cipher */\n\tret = cipher_algo_transform(param->cipher_algo,\n\t\t\t&xform_cipher->cipher.algo);\n\tif (unlikely(ret < 0))\n\t\treturn ret;\n\txform_cipher->type = RTE_CRYPTO_SYM_XFORM_CIPHER;\n\txform_cipher->cipher.key.length = param->cipher_key_len;\n\txform_cipher->cipher.key.data = param->cipher_key_buf;\n\tret = get_iv_len(xform_cipher->cipher.algo);\n\tif (unlikely(ret < 0))\n\t\treturn ret;\n\txform_cipher->cipher.iv.length = (uint16_t)ret;\n\txform_cipher->cipher.iv.offset = IV_OFFSET;\n\n\t/* auth */\n\txform_auth->type = RTE_CRYPTO_SYM_XFORM_AUTH;\n\tret = auth_algo_transform(param->hash_algo, &xform_auth->auth.algo);\n\tif (unlikely(ret < 0))\n\t\treturn ret;\n\txform_auth->auth.digest_length = param->digest_len;\n\txform_auth->auth.key.length = param->auth_key_len;\n\txform_auth->auth.key.data = param->auth_key_buf;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'vhost/crypto: validate keys lengths\n\ntransform_cipher_param() and transform_chain_param() handle\nthe payload data for the VHOST_USER_CRYPTO_CREATE_SESS\nmessage. These payloads have to be validated, since it\ncould come from untrusted sources.\n\nTwo buffers and their lengths are defined in this payload,\none the the auth key and one for the cipher key. But above\nfunctions do not validate the key length inputs, which could\nlead to read out of bounds, as buffers have static sizes of\n64 bytes for the cipher key and 512 bytes for the auth key.\n\nThis patch adds necessary checks on the key length field\nbefore being used.\n\nCVE-2020-10724\nFixes: e80a98708166 (\"vhost/crypto: add session message handler\")\nCc: stable@dpdk.org\n\nReported-by: Ilja Van Sprundel \nSigned-off-by: Maxime Coquelin \nReviewed-by: Xiaolong Ye \nReviewed-by: Ilja Van Sprundel '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: DeepScanLineInputFile::DeepScanLineInputFile\n (const char fileName[], int numThreads)\n:\n _data (new Data (numThreads))\n{\n _data->_streamData = new InputStreamMutex();\n _data->_deleteStream = true;\n OPENEXR_IMF_INTERNAL_NAMESPACE::IStream* is = 0;\n\n try\n {\n is = new StdIFStream (fileName);\n readMagicNumberAndVersionField(*is, _data->version);\n //\n // Backward compatibility to read multpart file.\n //\n if (isMultiPart(_data->version))\n {\n compatibilityInitialize(*is);\n return;\n }\n _data->_streamData->is = is;\n _data->memoryMapped = is->isMemoryMapped();\n _data->header.readFrom (*_data->_streamData->is, _data->version);\n _data->header.sanityCheck (isTiled (_data->version));\n\n initialize(_data->header);\n\n readLineOffsets (*_data->_streamData->is,\n _data->lineOrder,\n _data->lineOffsets,\n _data->fileIsComplete);\n }\n catch (IEX_NAMESPACE::BaseExc &e)\n {\n if (is) delete is;\n if (_data && _data->_streamData) delete _data->_streamData;\n if (_data) delete _data;\n\n REPLACE_EXC (e, \"Cannot read image file \"\n \"\\\"\" << fileName << \"\\\". \" << e.what());\n throw;\n }\n catch (...)\n {\n if (is) delete is;\n if (_data && _data->_streamData) delete _data->_streamData;\n if (_data) delete _data;\n\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: generateRandomFile (int partCount, const std::string & fn)\n{\n //\n // Init data.\n //\n Array2D halfData;\n Array2D floatData;\n Array2D uintData;\n fillPixels(uintData, width, height);\n fillPixels(halfData, width, height);\n fillPixels(floatData, width, height);\n\n Array2D< Array2D< half > >* tiledHalfData = new Array2D< Array2D< half > >[partCount];\n Array2D< Array2D< float > >* tiledFloatData = new Array2D< Array2D< float > >[partCount];\n Array2D< Array2D< unsigned int > >* tiledUintData = new Array2D< Array2D< unsigned int > >[partCount];\n\n vector outputfiles;\n vector taskList;\n\n pixelTypes.resize(partCount);\n partTypes.resize(partCount);\n levelModes.resize(partCount);\n\n //\n // Generate headers and data.\n //\n cout << \"Generating headers and data \" << flush;\n generateRandomHeaders(partCount, headers, taskList);\n\n //\n // Shuffle tasks.\n //\n cout << \"Shuffling \" << taskList.size() << \" tasks \" << flush;\n int taskListSize = taskList.size();\n for (int i = 0; i < taskListSize; i++)\n {\n int a, b;\n a = random_int(taskListSize);\n b = random_int(taskListSize);\n swap(taskList[a], taskList[b]);\n }\n\n remove(fn.c_str());\n MultiPartOutputFile file(fn.c_str(), &headers[0],headers.size());\n\n //\n // Writing tasks.\n //\n cout << \"Writing tasks \" << flush;\n\n //\n // Pre-generating frameBuffers.\n //\n vector parts;\n vector frameBuffers(partCount);\n Array >tiledFrameBuffers(partCount);\n for (int i = 0; i < partCount; i++)\n {\n if (partTypes[i] == 0)\n {\n OutputPart* part = new OutputPart(file, i);\n parts.push_back((void*) part);\n\n FrameBuffer& frameBuffer = frameBuffers[i];\n\n setOutputFrameBuffer(frameBuffer, pixelTypes[i], uintData, floatData, halfData, width);\n\n part->setFrameBuffer(frameBuffer);\n }\n else\n {\n TiledOutputPart* part = new TiledOutputPart(file, i);\n parts.push_back((void*) part);\n\n int numXLevels = part->numXLevels();\n int numYLevels = part->numYLevels();\n\n // Allocating space.\n switch (pixelTypes[i])\n {\n case 0:\n tiledUintData[i].resizeErase(numYLevels, numXLevels);\n break;\n case 1:\n tiledFloatData[i].resizeErase(numYLevels, numXLevels);\n break;\n case 2:\n tiledHalfData[i].resizeErase(numYLevels, numXLevels);\n break;\n }\n\n tiledFrameBuffers[i].resizeErase(numYLevels, numXLevels);\n\n for (int xLevel = 0; xLevel < numXLevels; xLevel++)\n for (int yLevel = 0; yLevel < numYLevels; yLevel++)\n {\n if (!part->isValidLevel(xLevel, yLevel))\n continue;\n\n int w = part->levelWidth(xLevel);\n int h = part->levelHeight(yLevel);\n\n FrameBuffer& frameBuffer = tiledFrameBuffers[i][yLevel][xLevel];\n\n switch (pixelTypes[i])\n {\n case 0:\n fillPixels(tiledUintData[i][yLevel][xLevel], w, h);\n break;\n case 1:\n fillPixels(tiledFloatData[i][yLevel][xLevel], w, h);\n break;\n case 2:\n fillPixels(tiledHalfData[i][yLevel][xLevel], w, h);\n break;\n }\n setOutputFrameBuffer(frameBuffer, pixelTypes[i],\n tiledUintData[i][yLevel][xLevel],\n tiledFloatData[i][yLevel][xLevel],\n tiledHalfData[i][yLevel][xLevel],\n w);\n }\n }\n }\n\n //\n // Writing tasks.\n //\n TaskGroup taskGroup;\n ThreadPool* threadPool = new ThreadPool(32);\n vector list;\n for (int i = 0; i < taskListSize; i++)\n {\n list.push_back(&taskList[i]);\n if (i % 10 == 0 || i == taskListSize - 1)\n {\n threadPool->addTask(\n (new WritingTask (&taskGroup, &file, list, tiledFrameBuffers)));\n list.clear();\n }\n }\n\n delete threadPool;\n\n delete[] tiledHalfData;\n delete[] tiledUintData;\n delete[] tiledFloatData;\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: DeepScanLineInputFile::~DeepScanLineInputFile ()\n{\n if (_data->_deleteStream)\n delete _data->_streamData->is;\n\n if (_data)\n {\n if (!_data->memoryMapped)\n for (size_t i = 0; i < _data->lineBuffers.size(); i++)\n delete [] _data->lineBuffers[i]->buffer;\n\n //\n // Unless this file was opened via the multipart API, delete the streamdata\n // object too.\n // (TODO) it should be \"isMultiPart(data->version)\", but when there is only\n // single part,\n // (see the above constructor) the version field is not set.\n //\n // (TODO) we should have a way to tell if the stream data is owned by this\n // file or by a parent multipart file.\n //\n\n if (_data->partNumber == -1 && _data->_streamData)\n delete _data->_streamData;\n\n delete _data;\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: generateRandomFile (int partCount, const std::string & fn)\n{\n //\n // Init data.\n //\n Array2D halfData;\n Array2D floatData;\n Array2D uintData;\n fillPixels(uintData, width, height);\n fillPixels(halfData, width, height);\n fillPixels(floatData, width, height);\n\n Array2D< Array2D< half > >* tiledHalfData = new Array2D< Array2D< half > >[partCount];\n Array2D< Array2D< float > >* tiledFloatData = new Array2D< Array2D< float > >[partCount];\n Array2D< Array2D< unsigned int > >* tiledUintData = new Array2D< Array2D< unsigned int > >[partCount];\n\n vector outputfiles;\n vector taskList;\n\n pixelTypes.resize(partCount);\n partTypes.resize(partCount);\n levelModes.resize(partCount);\n\n //\n // Generate headers and data.\n //\n cout << \"Generating headers and data \" << flush;\n generateRandomHeaders(partCount, headers, taskList);\n\n //\n // Shuffle tasks.\n //\n cout << \"Shuffling \" << taskList.size() << \" tasks \" << flush;\n int taskListSize = taskList.size();\n for (int i = 0; i < taskListSize; i++)\n {\n int a, b;\n a = random_int(taskListSize);\n b = random_int(taskListSize);\n swap(taskList[a], taskList[b]);\n }\n\n remove(fn.c_str());\n MultiPartOutputFile file(fn.c_str(), &headers[0],headers.size());\n\n //\n // Writing tasks.\n //\n cout << \"Writing tasks \" << flush;\n\n //\n // Pre-generating frameBuffers.\n //\n vector parts;\n vector frameBuffers(partCount);\n Array > tiledFrameBuffers(partCount);\n for (int i = 0; i < partCount; i++)\n {\n if (partTypes[i] == 0)\n {\n OutputPart* part = new OutputPart(file, i);\n parts.push_back((void*) part);\n\n FrameBuffer& frameBuffer = frameBuffers[i];\n\n setOutputFrameBuffer(frameBuffer, pixelTypes[i], uintData, floatData, halfData, width);\n\n part->setFrameBuffer(frameBuffer);\n }\n else\n {\n TiledOutputPart* part = new TiledOutputPart(file, i);\n parts.push_back((void*) part);\n\n int numXLevels = part->numXLevels();\n int numYLevels = part->numYLevels();\n\n // Allocating space.\n switch (pixelTypes[i])\n {\n case 0:\n tiledUintData[i].resizeErase(numYLevels, numXLevels);\n break;\n case 1:\n tiledFloatData[i].resizeErase(numYLevels, numXLevels);\n break;\n case 2:\n tiledHalfData[i].resizeErase(numYLevels, numXLevels);\n break;\n }\n\n tiledFrameBuffers[i].resizeErase(numYLevels, numXLevels);\n\n for (int xLevel = 0; xLevel < numXLevels; xLevel++)\n for (int yLevel = 0; yLevel < numYLevels; yLevel++)\n {\n if (!part->isValidLevel(xLevel, yLevel))\n continue;\n\n int w = part->levelWidth(xLevel);\n int h = part->levelHeight(yLevel);\n\n FrameBuffer& frameBuffer = tiledFrameBuffers[i][yLevel][xLevel];\n\n switch (pixelTypes[i])\n {\n case 0:\n fillPixels(tiledUintData[i][yLevel][xLevel], w, h);\n break;\n case 1:\n fillPixels(tiledFloatData[i][yLevel][xLevel], w, h);\n break;\n case 2:\n fillPixels(tiledHalfData[i][yLevel][xLevel], w, h);\n break;\n }\n setOutputFrameBuffer(frameBuffer, pixelTypes[i],\n tiledUintData[i][yLevel][xLevel],\n tiledFloatData[i][yLevel][xLevel],\n tiledHalfData[i][yLevel][xLevel],\n w);\n }\n }\n }\n\n //\n // Writing tasks.\n //\n for (int i = 0; i < taskListSize; i++)\n {\n int partNumber = taskList[i].partNumber;\n int partType = partTypes[partNumber];\n\n if (partType == 0)\n {\n OutputPart* part = (OutputPart*) parts[partNumber];\n part->writePixels();\n }\n else\n {\n int tx = taskList[i].tx;\n int ty = taskList[i].ty;\n int lx = taskList[i].lx;\n int ly = taskList[i].ly;\n TiledOutputPart* part = (TiledOutputPart*) parts[partNumber];\n part->setFrameBuffer(tiledFrameBuffers[partNumber][ly][lx]);\n part->writeTile(tx, ty, lx, ly);\n }\n }\n\n delete[] tiledHalfData;\n delete[] tiledUintData;\n delete[] tiledFloatData;\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: static int cbs_jpeg_split_fragment(CodedBitstreamContext *ctx,\n CodedBitstreamFragment *frag,\n int header)\n{\n AVBufferRef *data_ref;\n uint8_t *data;\n size_t data_size;\n int unit, start, end, marker, next_start, next_marker;\n int err, i, j, length;\n\n if (frag->data_size < 4) {\n // Definitely too short to be meaningful.\n return AVERROR_INVALIDDATA;\n }\n\n for (i = 0; i + 1 < frag->data_size && frag->data[i] != 0xff; i++);\n if (i > 0) {\n av_log(ctx->log_ctx, AV_LOG_WARNING, \"Discarding %d bytes at \"\n \"beginning of image.\\n\", i);\n }\n for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size && frag->data[i]) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"no SOI marker found.\\n\");\n return AVERROR_INVALIDDATA;\n }\n marker = frag->data[i];\n if (marker != JPEG_MARKER_SOI) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: first \"\n \"marker is %02x, should be SOI.\\n\", marker);\n return AVERROR_INVALIDDATA;\n }\n for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"no image content found.\\n\");\n return AVERROR_INVALIDDATA;\n }\n marker = frag->data[i];\n start = i + 1;\n\n for (unit = 0;; unit++) {\n if (marker == JPEG_MARKER_EOI) {\n break;\n } else if (marker == JPEG_MARKER_SOS) {\n for (i = start; i + 1 < frag->data_size; i++) {\n if (frag->data[i] != 0xff)\n continue;\n end = i;\n for (++i; i + 1 < frag->data_size &&\n frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size) {\n next_marker = -1;\n } else {\n if (frag->data[i] == 0x00)\n continue;\n next_marker = frag->data[i];\n next_start = i + 1;\n }\n break;\n }\n } else {\n i = start;\n if (i + 2 > frag->data_size) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"truncated at %02x marker.\\n\", marker);\n return AVERROR_INVALIDDATA;\n }\n length = AV_RB16(frag->data + i);\n if (i + length > frag->data_size) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"truncated at %02x marker segment.\\n\", marker);\n return AVERROR_INVALIDDATA;\n }\n end = start + length;\n\n i = end;\n if (frag->data[i] != 0xff) {\n next_marker = -1;\n } else {\n for (++i; i + 1 < frag->data_size &&\n frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size) {\n next_marker = -1;\n } else {\n next_marker = frag->data[i];\n next_start = i + 1;\n }\n }\n }\n\n if (marker == JPEG_MARKER_SOS) {\n length = AV_RB16(frag->data + start);\n\n data_ref = NULL;\n data = av_malloc(end - start +\n AV_INPUT_BUFFER_PADDING_SIZE);\n if (!data)\n return AVERROR(ENOMEM);\n\n memcpy(data, frag->data + start, length);\n for (i = start + length, j = length; i < end; i++, j++) {\n if (frag->data[i] == 0xff) {\n while (frag->data[i] == 0xff)\n ++i;\n data[j] = 0xff;\n } else {\n data[j] = frag->data[i];\n }\n }\n data_size = j;\n\n memset(data + data_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);\n\n } else {\n data = frag->data + start;\n data_size = end - start;\n data_ref = frag->data_ref;\n }\n\n err = ff_cbs_insert_unit_data(ctx, frag, unit, marker,\n data, data_size, data_ref);\n if (err < 0)\n return err;\n\n if (next_marker == -1)\n break;\n marker = next_marker;\n start = next_start;\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'avcodec/cbs_jpeg: Check length for SOS\n\nFixes: out of array access\nFixes: 19734/clusterfuzz-testcase-minimized-ffmpeg_BSF_TRACE_HEADERS_fuzzer-5673507031875584\nFixes: 19353/clusterfuzz-testcase-minimized-ffmpeg_BSF_TRACE_HEADERS_fuzzer-5703944462663680\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: mptctl_hp_hostinfo(unsigned long arg, unsigned int data_size)\n{\n\thp_host_info_t\t__user *uarg = (void __user *) arg;\n\tMPT_ADAPTER\t\t*ioc;\n\tstruct pci_dev\t\t*pdev;\n\tchar *pbuf=NULL;\n\tdma_addr_t\t\tbuf_dma;\n\thp_host_info_t\t\tkarg;\n\tCONFIGPARMS\t\tcfg;\n\tConfigPageHeader_t\thdr;\n\tint\t\t\tiocnum;\n\tint\t\t\trc, cim_rev;\n\tToolboxIstwiReadWriteRequest_t\t*IstwiRWRequest;\n\tMPT_FRAME_HDR\t\t*mf = NULL;\n\tunsigned long\t\ttimeleft;\n\tint\t\t\tretval;\n\tu32\t\t\tmsgcontext;\n\n\t/* Reset long to int. Should affect IA64 and SPARC only\n\t */\n\tif (data_size == sizeof(hp_host_info_t))\n\t\tcim_rev = 1;\n\telse if (data_size == sizeof(hp_host_info_rev0_t))\n\t\tcim_rev = 0;\t/* obsolete */\n\telse\n\t\treturn -EFAULT;\n\n\tif (copy_from_user(&karg, uarg, sizeof(hp_host_info_t))) {\n\t\tprintk(KERN_ERR MYNAM \"%s@%d::mptctl_hp_host_info - \"\n\t\t\t\"Unable to read in hp_host_info 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_hp_hostinfo() @%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_hp_hostinfo called.\\n\",\n\t ioc->name));\n\n\t/* Fill in the data and return the structure to the calling\n\t * program\n\t */\n\tpdev = (struct pci_dev *) ioc->pcidev;\n\n\tkarg.vendor = pdev->vendor;\n\tkarg.device = pdev->device;\n\tkarg.subsystem_id = pdev->subsystem_device;\n\tkarg.subsystem_vendor = pdev->subsystem_vendor;\n\tkarg.devfn = pdev->devfn;\n\tkarg.bus = pdev->bus->number;\n\n\t/* Save the SCSI host no. if\n\t * SCSI driver loaded\n\t */\n\tif (ioc->sh != NULL)\n\t\tkarg.host_no = ioc->sh->host_no;\n\telse\n\t\tkarg.host_no = -1;\n\n\t/* Reformat the fw_version into a string */\n\tsnprintf(karg.fw_version, sizeof(karg.fw_version),\n\t\t \"%.2hhu.%.2hhu.%.2hhu.%.2hhu\",\n\t\t ioc->facts.FWVersion.Struct.Major,\n\t\t ioc->facts.FWVersion.Struct.Minor,\n\t\t ioc->facts.FWVersion.Struct.Unit,\n\t\t ioc->facts.FWVersion.Struct.Dev);\n\n\t/* Issue a config request to get the device serial number\n\t */\n\thdr.PageVersion = 0;\n\thdr.PageLength = 0;\n\thdr.PageNumber = 0;\n\thdr.PageType = MPI_CONFIG_PAGETYPE_MANUFACTURING;\n\tcfg.cfghdr.hdr = &hdr;\n\tcfg.physAddr = -1;\n\tcfg.pageAddr = 0;\n\tcfg.action = MPI_CONFIG_ACTION_PAGE_HEADER;\n\tcfg.dir = 0;\t/* read */\n\tcfg.timeout = 10;\n\n\tstrncpy(karg.serial_number, \" \", 24);\n\tif (mpt_config(ioc, &cfg) == 0) {\n\t\tif (cfg.cfghdr.hdr->PageLength > 0) {\n\t\t\t/* Issue the second config page request */\n\t\t\tcfg.action = MPI_CONFIG_ACTION_PAGE_READ_CURRENT;\n\n\t\t\tpbuf = pci_alloc_consistent(ioc->pcidev, hdr.PageLength * 4, &buf_dma);\n\t\t\tif (pbuf) {\n\t\t\t\tcfg.physAddr = buf_dma;\n\t\t\t\tif (mpt_config(ioc, &cfg) == 0) {\n\t\t\t\t\tManufacturingPage0_t *pdata = (ManufacturingPage0_t *) pbuf;\n\t\t\t\t\tif (strlen(pdata->BoardTracerNumber) > 1) {\n\t\t\t\t\t\tstrlcpy(karg.serial_number,\n\t\t\t\t\t\t\tpdata->BoardTracerNumber, 24);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tpci_free_consistent(ioc->pcidev, hdr.PageLength * 4, pbuf, buf_dma);\n\t\t\t\tpbuf = NULL;\n\t\t\t}\n\t\t}\n\t}\n\trc = mpt_GetIocState(ioc, 1);\n\tswitch (rc) {\n\tcase MPI_IOC_STATE_OPERATIONAL:\n\t\tkarg.ioc_status = HP_STATUS_OK;\n\t\tbreak;\n\n\tcase MPI_IOC_STATE_FAULT:\n\t\tkarg.ioc_status = HP_STATUS_FAILED;\n\t\tbreak;\n\n\tcase MPI_IOC_STATE_RESET:\n\tcase MPI_IOC_STATE_READY:\n\tdefault:\n\t\tkarg.ioc_status = HP_STATUS_OTHER;\n\t\tbreak;\n\t}\n\n\tkarg.base_io_addr = pci_resource_start(pdev, 0);\n\n\tif ((ioc->bus_type == SAS) || (ioc->bus_type == FC))\n\t\tkarg.bus_phys_width = HP_BUS_WIDTH_UNK;\n\telse\n\t\tkarg.bus_phys_width = HP_BUS_WIDTH_16;\n\n\tkarg.hard_resets = 0;\n\tkarg.soft_resets = 0;\n\tkarg.timeouts = 0;\n\tif (ioc->sh != NULL) {\n\t\tMPT_SCSI_HOST *hd = shost_priv(ioc->sh);\n\n\t\tif (hd && (cim_rev == 1)) {\n\t\t\tkarg.hard_resets = ioc->hard_resets;\n\t\t\tkarg.soft_resets = ioc->soft_resets;\n\t\t\tkarg.timeouts = ioc->timeouts;\n\t\t}\n\t}\n\n\t/* \n\t * Gather ISTWI(Industry Standard Two Wire Interface) Data\n\t */\n\tif ((mf = mpt_get_msg_frame(mptctl_id, ioc)) == NULL) {\n\t\tdfailprintk(ioc, printk(MYIOC_s_WARN_FMT\n\t\t\t\"%s, no msg frames!!\\n\", ioc->name, __func__));\n\t\tgoto out;\n\t}\n\n\tIstwiRWRequest = (ToolboxIstwiReadWriteRequest_t *)mf;\n\tmsgcontext = IstwiRWRequest->MsgContext;\n\tmemset(IstwiRWRequest,0,sizeof(ToolboxIstwiReadWriteRequest_t));\n\tIstwiRWRequest->MsgContext = msgcontext;\n\tIstwiRWRequest->Function = MPI_FUNCTION_TOOLBOX;\n\tIstwiRWRequest->Tool = MPI_TOOLBOX_ISTWI_READ_WRITE_TOOL;\n\tIstwiRWRequest->Flags = MPI_TB_ISTWI_FLAGS_READ;\n\tIstwiRWRequest->NumAddressBytes = 0x01;\n\tIstwiRWRequest->DataLength = cpu_to_le16(0x04);\n\tif (pdev->devfn & 1)\n\t\tIstwiRWRequest->DeviceAddr = 0xB2;\n\telse\n\t\tIstwiRWRequest->DeviceAddr = 0xB0;\n\n\tpbuf = pci_alloc_consistent(ioc->pcidev, 4, &buf_dma);\n\tif (!pbuf)\n\t\tgoto out;\n\tioc->add_sge((char *)&IstwiRWRequest->SGL,\n\t (MPT_SGE_FLAGS_SSIMPLE_READ|4), buf_dma);\n\n\tretval = 0;\n\tSET_MGMT_MSG_CONTEXT(ioc->ioctl_cmds.msg_context,\n\t\t\t\tIstwiRWRequest->MsgContext);\n\tINITIALIZE_MGMT_STATUS(ioc->ioctl_cmds.status)\n\tmpt_put_msg_frame(mptctl_id, ioc, mf);\n\nretry_wait:\n\ttimeleft = wait_for_completion_timeout(&ioc->ioctl_cmds.done,\n\t\t\tHZ*MPT_IOCTL_DEFAULT_TIMEOUT);\n\tif (!(ioc->ioctl_cmds.status & MPT_MGMT_STATUS_COMMAND_GOOD)) {\n\t\tretval = -ETIME;\n\t\tprintk(MYIOC_s_WARN_FMT \"%s: failed\\n\", ioc->name, __func__);\n\t\tif (ioc->ioctl_cmds.status & MPT_MGMT_STATUS_DID_IOCRESET) {\n\t\t\tmpt_free_msg_frame(ioc, mf);\n\t\t\tgoto out;\n\t\t}\n\t\tif (!timeleft) {\n\t\t\tprintk(MYIOC_s_WARN_FMT\n\t\t\t \"HOST INFO command timeout, doorbell=0x%08x\\n\",\n\t\t\t ioc->name, mpt_GetIocState(ioc, 0));\n\t\t\tmptctl_timeout_expired(ioc, mf);\n\t\t} else\n\t\t\tgoto retry_wait;\n\t\tgoto out;\n\t}\n\n\t/*\n\t *ISTWI Data Definition\n\t * pbuf[0] = FW_VERSION = 0x4\n\t * pbuf[1] = Bay Count = 6 or 4 or 2, depending on\n\t * the config, you should be seeing one out of these three values\n\t * pbuf[2] = Drive Installed Map = bit pattern depend on which\n\t * bays have drives in them\n\t * pbuf[3] = Checksum (0x100 = (byte0 + byte2 + byte3)\n\t */\n\tif (ioc->ioctl_cmds.status & MPT_MGMT_STATUS_RF_VALID)\n\t\tkarg.rsvd = *(u32 *)pbuf;\n\n out:\n\tCLEAR_MGMT_STATUS(ioc->ioctl_cmds.status)\n\tSET_MGMT_MSG_CONTEXT(ioc->ioctl_cmds.msg_context, 0);\n\n\tif (pbuf)\n\t\tpci_free_consistent(ioc->pcidev, 4, pbuf, buf_dma);\n\n\t/* Copy the data from kernel memory to user memory\n\t */\n\tif (copy_to_user((char __user *)arg, &karg, sizeof(hp_host_info_t))) {\n\t\tprintk(MYIOC_s_ERR_FMT \"%s@%d::mptctl_hpgethostinfo - \"\n\t\t\t\"Unable to write out hp_host_info @ %p\\n\",\n\t\t\tioc->name, __FILE__, __LINE__, uarg);\n\t\treturn -EFAULT;\n\t}\n\n\treturn 0;\n\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_eventquery (unsigned long arg)\n{\n\tstruct mpt_ioctl_eventquery __user *uarg = (void __user *) arg;\n\tstruct mpt_ioctl_eventquery\t karg;\n\tMPT_ADAPTER *ioc;\n\tint iocnum;\n\n\tif (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventquery))) {\n\t\tprintk(KERN_ERR MYNAM \"%s@%d::mptctl_eventquery - \"\n\t\t\t\"Unable to read in mpt_ioctl_eventquery 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_eventquery() @%d - ioc%d not found!\\n\",\n\t\t\t\t__FILE__, __LINE__, iocnum);\n\t\treturn -ENODEV;\n\t}\n\n\tdctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT \"mptctl_eventquery called.\\n\",\n\t ioc->name));\n\tkarg.eventEntries = MPTCTL_EVENT_LOG_SIZE;\n\tkarg.eventTypes = ioc->eventTypes;\n\n\t/* Copy the data from kernel memory to user memory\n\t */\n\tif (copy_to_user((char __user *)arg, &karg, sizeof(struct mpt_ioctl_eventquery))) {\n\t\tprintk(MYIOC_s_ERR_FMT \"%s@%d::mptctl_eventquery - \"\n\t\t\t\"Unable to write out mpt_ioctl_eventquery struct @ %p\\n\",\n\t\t\tioc->name, __FILE__, __LINE__, uarg);\n\t\treturn -EFAULT;\n\t}\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: xfs_agf_verify(\n\tstruct xfs_buf\t\t*bp)\n{\n\tstruct xfs_mount\t*mp = bp->b_mount;\n\tstruct xfs_agf\t\t*agf = XFS_BUF_TO_AGF(bp);\n\n\tif (xfs_sb_version_hascrc(&mp->m_sb)) {\n\t\tif (!uuid_equal(&agf->agf_uuid, &mp->m_sb.sb_meta_uuid))\n\t\t\treturn __this_address;\n\t\tif (!xfs_log_check_lsn(mp,\n\t\t\t\tbe64_to_cpu(XFS_BUF_TO_AGF(bp)->agf_lsn)))\n\t\t\treturn __this_address;\n\t}\n\n\tif (!xfs_verify_magic(bp, agf->agf_magicnum))\n\t\treturn __this_address;\n\n\tif (!(XFS_AGF_GOOD_VERSION(be32_to_cpu(agf->agf_versionnum)) &&\n\t be32_to_cpu(agf->agf_freeblks) <= be32_to_cpu(agf->agf_length) &&\n\t be32_to_cpu(agf->agf_flfirst) < xfs_agfl_size(mp) &&\n\t be32_to_cpu(agf->agf_fllast) < xfs_agfl_size(mp) &&\n\t be32_to_cpu(agf->agf_flcount) <= xfs_agfl_size(mp)))\n\t\treturn __this_address;\n\n\tif (be32_to_cpu(agf->agf_levels[XFS_BTNUM_BNO]) < 1 ||\n\t be32_to_cpu(agf->agf_levels[XFS_BTNUM_CNT]) < 1 ||\n\t be32_to_cpu(agf->agf_levels[XFS_BTNUM_BNO]) > XFS_BTREE_MAXLEVELS ||\n\t be32_to_cpu(agf->agf_levels[XFS_BTNUM_CNT]) > XFS_BTREE_MAXLEVELS)\n\t\treturn __this_address;\n\n\tif (xfs_sb_version_hasrmapbt(&mp->m_sb) &&\n\t (be32_to_cpu(agf->agf_levels[XFS_BTNUM_RMAP]) < 1 ||\n\t be32_to_cpu(agf->agf_levels[XFS_BTNUM_RMAP]) > XFS_BTREE_MAXLEVELS))\n\t\treturn __this_address;\n\n\t/*\n\t * during growfs operations, the perag is not fully initialised,\n\t * so we can't use it for any useful checking. growfs ensures we can't\n\t * use it by using uncached buffers that don't have the perag attached\n\t * so we can detect and avoid this problem.\n\t */\n\tif (bp->b_pag && be32_to_cpu(agf->agf_seqno) != bp->b_pag->pag_agno)\n\t\treturn __this_address;\n\n\tif (xfs_sb_version_haslazysbcount(&mp->m_sb) &&\n\t be32_to_cpu(agf->agf_btreeblks) > be32_to_cpu(agf->agf_length))\n\t\treturn __this_address;\n\n\tif (xfs_sb_version_hasreflink(&mp->m_sb) &&\n\t (be32_to_cpu(agf->agf_refcount_level) < 1 ||\n\t be32_to_cpu(agf->agf_refcount_level) > XFS_BTREE_MAXLEVELS))\n\t\treturn __this_address;\n\n\treturn NULL;\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703', 'CWE-835'], 'message': 'xfs: add agf freeblocks verify in xfs_agf_verify\n\nWe recently used fuzz(hydra) to test XFS and automatically generate\ntmp.img(XFS v5 format, but some metadata is wrong)\n\nxfs_repair information(just one AG):\nagf_freeblks 0, counted 3224 in ag 0\nagf_longest 536874136, counted 3224 in ag 0\nsb_fdblocks 613, counted 3228\n\nTest as follows:\nmount tmp.img tmpdir\ncp file1M tmpdir\nsync\n\nIn 4.19-stable, sync will stuck, the reason is:\nxfs_mountfs\n xfs_check_summary_counts\n if ((!xfs_sb_version_haslazysbcount(&mp->m_sb) ||\n XFS_LAST_UNMOUNT_WAS_CLEAN(mp)) &&\n !xfs_fs_has_sickness(mp, XFS_SICK_FS_COUNTERS))\n\treturn 0; -->just return, incore sb_fdblocks still be 613\n xfs_initialize_perag_data\n\ncp file1M tmpdir -->ok(write file to pagecache)\nsync -->stuck(write pagecache to disk)\nxfs_map_blocks\n xfs_iomap_write_allocate\n while (count_fsb != 0) {\n nimaps = 0;\n while (nimaps == 0) { --> endless loop\n nimaps = 1;\n xfs_bmapi_write(..., &nimaps) --> nimaps becomes 0 again\nxfs_bmapi_write\n xfs_bmap_alloc\n xfs_bmap_btalloc\n xfs_alloc_vextent\n xfs_alloc_fix_freelist\n xfs_alloc_space_available -->fail(agf_freeblks is 0)\n\nIn linux-next, sync not stuck, cause commit c2b3164320b5 (\"xfs:\nuse the latest extent at writeback delalloc conversion time\") remove\nthe above while, dmesg is as follows:\n[ 55.250114] XFS (loop0): page discard on page ffffea0008bc7380, inode 0x1b0c, offset 0.\n\nUsers do not know why this page is discard, the better soultion is:\n1. Like xfs_repair, make sure sb_fdblocks is equal to counted\n(xfs_initialize_perag_data did this, who is not called at this mount)\n2. Add agf verify, if fail, will tell users to repair\n\nThis patch use the second soultion.\n\nSigned-off-by: Zheng Bin \nSigned-off-by: Ren Xudong \nReviewed-by: Darrick J. Wong \nSigned-off-by: Darrick J. Wong '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int stv06xx_isoc_init(struct gspca_dev *gspca_dev)\n{\n\tstruct usb_host_interface *alt;\n\tstruct sd *sd = (struct sd *) gspca_dev;\n\n\t/* Start isoc bandwidth \"negotiation\" at max isoc bandwidth */\n\talt = &gspca_dev->dev->actconfig->intf_cache[0]->altsetting[1];\n\talt->endpoint[0].desc.wMaxPacketSize =\n\t\tcpu_to_le16(sd->sensor->max_packet_size[gspca_dev->curr_mode]);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'media: stv06xx: add missing descriptor sanity checks\n\nMake sure to check that we have two alternate settings and at least one\nendpoint before accessing the second altsetting structure and\ndereferencing the endpoint arrays.\n\nThis specifically avoids dereferencing NULL-pointers or corrupting\nmemory when a device does not have the expected descriptors.\n\nNote that the sanity checks in stv06xx_start() and pb0100_start() are\nnot redundant as the driver is mixing looking up altsettings by index\nand by number, which may not coincide.\n\nFixes: 8668d504d72c (\"V4L/DVB (12082): gspca_stv06xx: Add support for st6422 bridge and sensor\")\nFixes: c0b33bdc5b8d (\"[media] gspca-stv06xx: support bandwidth changing\")\nCc: stable # 2.6.31\nCc: Hans de Goede \nSigned-off-by: Johan Hovold \nSigned-off-by: Hans Verkuil \nSigned-off-by: Mauro Carvalho Chehab '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static CACHE_BITMAP_V3_ORDER* update_read_cache_bitmap_v3_order(rdpUpdate* update, wStream* s,\n UINT16 flags)\n{\n\tBYTE bitsPerPixelId;\n\tBITMAP_DATA_EX* bitmapData;\n\tUINT32 new_len;\n\tBYTE* new_data;\n\tCACHE_BITMAP_V3_ORDER* cache_bitmap_v3;\n\n\tif (!update || !s)\n\t\treturn NULL;\n\n\tcache_bitmap_v3 = calloc(1, sizeof(CACHE_BITMAP_V3_ORDER));\n\n\tif (!cache_bitmap_v3)\n\t\tgoto fail;\n\n\tcache_bitmap_v3->cacheId = flags & 0x00000003;\n\tcache_bitmap_v3->flags = (flags & 0x0000FF80) >> 7;\n\tbitsPerPixelId = (flags & 0x00000078) >> 3;\n\tcache_bitmap_v3->bpp = CBR23_BPP[bitsPerPixelId];\n\n\tif (Stream_GetRemainingLength(s) < 21)\n\t\tgoto fail;\n\n\tStream_Read_UINT16(s, cache_bitmap_v3->cacheIndex); /* cacheIndex (2 bytes) */\n\tStream_Read_UINT32(s, cache_bitmap_v3->key1); /* key1 (4 bytes) */\n\tStream_Read_UINT32(s, cache_bitmap_v3->key2); /* key2 (4 bytes) */\n\tbitmapData = &cache_bitmap_v3->bitmapData;\n\tStream_Read_UINT8(s, bitmapData->bpp);\n\n\tif ((bitmapData->bpp < 1) || (bitmapData->bpp > 32))\n\t{\n\t\tWLog_Print(update->log, WLOG_ERROR, \"invalid bpp value %\" PRIu32 \"\", bitmapData->bpp);\n\t\tgoto fail;\n\t}\n\n\tStream_Seek_UINT8(s); /* reserved1 (1 byte) */\n\tStream_Seek_UINT8(s); /* reserved2 (1 byte) */\n\tStream_Read_UINT8(s, bitmapData->codecID); /* codecID (1 byte) */\n\tStream_Read_UINT16(s, bitmapData->width); /* width (2 bytes) */\n\tStream_Read_UINT16(s, bitmapData->height); /* height (2 bytes) */\n\tStream_Read_UINT32(s, new_len); /* length (4 bytes) */\n\n\tif (Stream_GetRemainingLength(s) < new_len)\n\t\tgoto fail;\n\n\tnew_data = (BYTE*)realloc(bitmapData->data, new_len);\n\n\tif (!new_data)\n\t\tgoto fail;\n\n\tbitmapData->data = new_data;\n\tbitmapData->length = new_len;\n\tStream_Read(s, bitmapData->data, bitmapData->length);\n\treturn cache_bitmap_v3;\nfail:\n\tfree_cache_bitmap_v3_order(update->context, cache_bitmap_v3);\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'Fixed #6013: Check new length is > 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: static INLINE INT32 planar_skip_plane_rle(const BYTE* pSrcData, UINT32 SrcSize, UINT32 nWidth,\n UINT32 nHeight)\n{\n\tUINT32 x, y;\n\tBYTE controlByte;\n\tconst BYTE* pRLE = pSrcData;\n\tconst BYTE* pEnd = &pSrcData[SrcSize];\n\n\tfor (y = 0; y < nHeight; y++)\n\t{\n\t\tfor (x = 0; x < nWidth;)\n\t\t{\n\t\t\tint cRawBytes;\n\t\t\tint nRunLength;\n\n\t\t\tif (pRLE >= pEnd)\n\t\t\t\treturn -1;\n\n\t\t\tcontrolByte = *pRLE++;\n\t\t\tnRunLength = PLANAR_CONTROL_BYTE_RUN_LENGTH(controlByte);\n\t\t\tcRawBytes = PLANAR_CONTROL_BYTE_RAW_BYTES(controlByte);\n\n\t\t\tif (nRunLength == 1)\n\t\t\t{\n\t\t\t\tnRunLength = cRawBytes + 16;\n\t\t\t\tcRawBytes = 0;\n\t\t\t}\n\t\t\telse if (nRunLength == 2)\n\t\t\t{\n\t\t\t\tnRunLength = cRawBytes + 32;\n\t\t\t\tcRawBytes = 0;\n\t\t\t}\n\n\t\t\tpRLE += cRawBytes;\n\t\t\tx += cRawBytes;\n\t\t\tx += nRunLength;\n\n\t\t\tif (x > nWidth)\n\t\t\t\treturn -1;\n\n\t\t\tif (pRLE > pEnd)\n\t\t\t\treturn -1;\n\t\t}\n\t}\n\n\treturn (INT32)(pRLE - pSrcData);\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: INLINE void gdi_RectToCRgn(const HGDI_RECT rect, INT32* x, INT32* y, INT32* w, INT32* h)\n{\n\t*x = rect->left;\n\t*y = rect->top;\n\t*w = rect->right - rect->left + 1;\n\t*h = rect->bottom - rect->top + 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix CVE-2020-11523: clamp invalid rectangles to size 0\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 nodeDestruct(struct SaveNode* node)\n{\n if (node->v == &node->sorted)\n {\n tr_free(node->sorted.val.l.vals);\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: processLastResort(struct module_qstate* qstate, struct iter_qstate* iq,\n\tstruct iter_env* ie, int id)\n{\n\tstruct delegpt_ns* ns;\n\tint query_count = 0;\n\tverbose(VERB_ALGO, \"No more query targets, attempting last resort\");\n\tlog_assert(iq->dp);\n\n\tif(!can_have_last_resort(qstate->env, iq->dp->name, iq->dp->namelen,\n\t\tiq->qchase.qclass, NULL)) {\n\t\t/* fail -- no more targets, no more hope of targets, no hope \n\t\t * of a response. */\n\t\terrinf(qstate, \"all the configured stub or forward servers failed,\");\n\t\terrinf_dname(qstate, \"at zone\", iq->dp->name);\n\t\tverbose(VERB_QUERY, \"configured stub or forward servers failed -- returning SERVFAIL\");\n\t\treturn error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);\n\t}\n\tif(!iq->dp->has_parent_side_NS && dname_is_root(iq->dp->name)) {\n\t\tstruct delegpt* p = hints_lookup_root(qstate->env->hints,\n\t\t\tiq->qchase.qclass);\n\t\tif(p) {\n\t\t\tstruct delegpt_addr* a;\n\t\t\tiq->chase_flags &= ~BIT_RD; /* go to authorities */\n\t\t\tfor(ns = p->nslist; ns; ns=ns->next) {\n\t\t\t\t(void)delegpt_add_ns(iq->dp, qstate->region,\n\t\t\t\t\tns->name, ns->lame);\n\t\t\t}\n\t\t\tfor(a = p->target_list; a; a=a->next_target) {\n\t\t\t\t(void)delegpt_add_addr(iq->dp, qstate->region,\n\t\t\t\t\t&a->addr, a->addrlen, a->bogus,\n\t\t\t\t\ta->lame, a->tls_auth_name);\n\t\t\t}\n\t\t}\n\t\tiq->dp->has_parent_side_NS = 1;\n\t} else if(!iq->dp->has_parent_side_NS) {\n\t\tif(!iter_lookup_parent_NS_from_cache(qstate->env, iq->dp,\n\t\t\tqstate->region, &qstate->qinfo) \n\t\t\t|| !iq->dp->has_parent_side_NS) {\n\t\t\t/* if: malloc failure in lookup go up to try */\n\t\t\t/* if: no parent NS in cache - go up one level */\n\t\t\tverbose(VERB_ALGO, \"try to grab parent NS\");\n\t\t\tiq->store_parent_NS = iq->dp;\n\t\t\tiq->chase_flags &= ~BIT_RD; /* go to authorities */\n\t\t\tiq->deleg_msg = NULL;\n\t\t\tiq->refetch_glue = 1;\n\t\t\tiq->query_restart_count++;\n\t\t\tiq->sent_count = 0;\n\t\t\tif(qstate->env->cfg->qname_minimisation)\n\t\t\t\tiq->minimisation_state = INIT_MINIMISE_STATE;\n\t\t\treturn next_state(iq, INIT_REQUEST_STATE);\n\t\t}\n\t}\n\t/* see if that makes new names available */\n\tif(!cache_fill_missing(qstate->env, iq->qchase.qclass, \n\t\tqstate->region, iq->dp))\n\t\tlog_err(\"out of memory in cache_fill_missing\");\n\tif(iq->dp->usable_list) {\n\t\tverbose(VERB_ALGO, \"try parent-side-name, w. glue from cache\");\n\t\treturn next_state(iq, QUERYTARGETS_STATE);\n\t}\n\t/* try to fill out parent glue from cache */\n\tif(iter_lookup_parent_glue_from_cache(qstate->env, iq->dp,\n\t\tqstate->region, &qstate->qinfo)) {\n\t\t/* got parent stuff from cache, see if we can continue */\n\t\tverbose(VERB_ALGO, \"try parent-side glue from cache\");\n\t\treturn next_state(iq, QUERYTARGETS_STATE);\n\t}\n\t/* query for an extra name added by the parent-NS record */\n\tif(delegpt_count_missing_targets(iq->dp) > 0) {\n\t\tint qs = 0;\n\t\tverbose(VERB_ALGO, \"try parent-side target name\");\n\t\tif(!query_for_targets(qstate, iq, ie, id, 1, &qs)) {\n\t\t\terrinf(qstate, \"could not fetch nameserver\");\n\t\t\terrinf_dname(qstate, \"at zone\", iq->dp->name);\n\t\t\treturn error_response(qstate, id, LDNS_RCODE_SERVFAIL);\n\t\t}\n\t\tiq->num_target_queries += qs;\n\t\ttarget_count_increase(iq, qs);\n\t\tif(qs != 0) {\n\t\t\tqstate->ext_state[id] = module_wait_subquery;\n\t\t\treturn 0; /* and wait for them */\n\t\t}\n\t}\n\tif(iq->depth == ie->max_dependency_depth) {\n\t\tverbose(VERB_QUERY, \"maxdepth and need more nameservers, fail\");\n\t\terrinf(qstate, \"cannot fetch more nameservers because at max dependency depth\");\n\t\treturn error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);\n\t}\n\tif(iq->depth > 0 && iq->target_count &&\n\t\tiq->target_count[1] > MAX_TARGET_COUNT) {\n\t\tchar s[LDNS_MAX_DOMAINLEN+1];\n\t\tdname_str(qstate->qinfo.qname, s);\n\t\tverbose(VERB_QUERY, \"request %s has exceeded the maximum \"\n\t\t\t\"number of glue fetches %d\", s, iq->target_count[1]);\n\t\terrinf(qstate, \"exceeded the maximum number of glue fetches\");\n\t\treturn error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);\n\t}\n\t/* mark cycle targets for parent-side lookups */\n\titer_mark_pside_cycle_targets(qstate, iq->dp);\n\t/* see if we can issue queries to get nameserver addresses */\n\t/* this lookup is not randomized, but sequential. */\n\tfor(ns = iq->dp->nslist; ns; ns = ns->next) {\n\t\t/* if this nameserver is at a delegation point, but that\n\t\t * delegation point is a stub and we cannot go higher, skip*/\n\t\tif( ((ie->supports_ipv6 && !ns->done_pside6) ||\n\t\t (ie->supports_ipv4 && !ns->done_pside4)) &&\n\t\t !can_have_last_resort(qstate->env, ns->name, ns->namelen,\n\t\t\tiq->qchase.qclass, NULL)) {\n\t\t\tlog_nametypeclass(VERB_ALGO, \"cannot pside lookup ns \"\n\t\t\t\t\"because it is also a stub/forward,\",\n\t\t\t\tns->name, LDNS_RR_TYPE_NS, iq->qchase.qclass);\n\t\t\tif(ie->supports_ipv6) ns->done_pside6 = 1;\n\t\t\tif(ie->supports_ipv4) ns->done_pside4 = 1;\n\t\t\tcontinue;\n\t\t}\n\t\t/* query for parent-side A and AAAA for nameservers */\n\t\tif(ie->supports_ipv6 && !ns->done_pside6) {\n\t\t\t/* Send the AAAA request. */\n\t\t\tif(!generate_parentside_target_query(qstate, iq, id, \n\t\t\t\tns->name, ns->namelen,\n\t\t\t\tLDNS_RR_TYPE_AAAA, iq->qchase.qclass)) {\n\t\t\t\terrinf_dname(qstate, \"could not generate nameserver AAAA lookup for\", ns->name);\n\t\t\t\treturn error_response(qstate, id,\n\t\t\t\t\tLDNS_RCODE_SERVFAIL);\n\t\t\t}\n\t\t\tns->done_pside6 = 1;\n\t\t\tquery_count++;\n\t\t}\n\t\tif(ie->supports_ipv4 && !ns->done_pside4) {\n\t\t\t/* Send the A request. */\n\t\t\tif(!generate_parentside_target_query(qstate, iq, id, \n\t\t\t\tns->name, ns->namelen, \n\t\t\t\tLDNS_RR_TYPE_A, iq->qchase.qclass)) {\n\t\t\t\terrinf_dname(qstate, \"could not generate nameserver A lookup for\", ns->name);\n\t\t\t\treturn error_response(qstate, id,\n\t\t\t\t\tLDNS_RCODE_SERVFAIL);\n\t\t\t}\n\t\t\tns->done_pside4 = 1;\n\t\t\tquery_count++;\n\t\t}\n\t\tif(query_count != 0) { /* suspend to await results */\n\t\t\tverbose(VERB_ALGO, \"try parent-side glue lookup\");\n\t\t\tiq->num_target_queries += query_count;\n\t\t\ttarget_count_increase(iq, query_count);\n\t\t\tqstate->ext_state[id] = module_wait_subquery;\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\t/* if this was a parent-side glue query itself, then store that\n\t * failure in cache. */\n\tif(!qstate->no_cache_store && iq->query_for_pside_glue\n\t\t&& !iq->pside_glue)\n\t\t\titer_store_parentside_neg(qstate->env, &qstate->qinfo,\n\t\t\t\tiq->deleg_msg?iq->deleg_msg->rep:\n\t\t\t\t(iq->response?iq->response->rep:NULL));\n\n\terrinf(qstate, \"all servers for this domain failed,\");\n\terrinf_dname(qstate, \"at zone\", iq->dp->name);\n\tverbose(VERB_QUERY, \"out of query targets -- returning SERVFAIL\");\n\t/* fail -- no more targets, no more hope of targets, no hope \n\t * of a response. */\n\treturn error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming\n query into a large number of queries directed to a target.\n- CVE-2020-12663 Malformed answers from upstream name servers can be\n used to make Unbound unresponsive.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: generate_ns_check(struct module_qstate* qstate, struct iter_qstate* iq, int id)\n{\n\tstruct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];\n\tstruct module_qstate* subq;\n\tlog_assert(iq->dp);\n\n\tif(iq->depth == ie->max_dependency_depth)\n\t\treturn;\n\tif(!can_have_last_resort(qstate->env, iq->dp->name, iq->dp->namelen,\n\t\tiq->qchase.qclass, NULL))\n\t\treturn;\n\t/* is this query the same as the nscheck? */\n\tif(qstate->qinfo.qtype == LDNS_RR_TYPE_NS &&\n\t\tquery_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 &&\n\t\t(qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){\n\t\t/* spawn off A, AAAA queries for in-zone glue to check */\n\t\tgenerate_a_aaaa_check(qstate, iq, id);\n\t\treturn;\n\t}\n\t/* no need to get the NS record for DS, it is above the zonecut */\n\tif(qstate->qinfo.qtype == LDNS_RR_TYPE_DS)\n\t\treturn;\n\n\tlog_nametypeclass(VERB_ALGO, \"schedule ns fetch\", \n\t\tiq->dp->name, LDNS_RR_TYPE_NS, iq->qchase.qclass);\n\tif(!generate_sub_request(iq->dp->name, iq->dp->namelen, \n\t\tLDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq,\n\t\tINIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {\n\t\tverbose(VERB_ALGO, \"could not generate ns check\");\n\t\treturn;\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/* make copy to avoid use of stub dp by different qs/threads */\n\t\t/* refetch glue to start higher up the tree */\n\t\tsubiq->refetch_glue = 1;\n\t\tsubiq->dp = delegpt_copy(iq->dp, subq->region);\n\t\tif(!subiq->dp) {\n\t\t\tlog_err(\"out of memory generating ns check, 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\treturn;\n\t\t}\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming\n query into a large number of queries directed to a target.\n- CVE-2020-12663 Malformed answers from upstream name servers can be\n used to make Unbound unresponsive.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: generate_dnskey_prefetch(struct module_qstate* qstate, \n\tstruct iter_qstate* iq, int id)\n{\n\tstruct module_qstate* subq;\n\tlog_assert(iq->dp);\n\n\t/* is this query the same as the prefetch? */\n\tif(qstate->qinfo.qtype == LDNS_RR_TYPE_DNSKEY &&\n\t\tquery_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 &&\n\t\t(qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){\n\t\treturn;\n\t}\n\n\t/* if the DNSKEY is in the cache this lookup will stop quickly */\n\tlog_nametypeclass(VERB_ALGO, \"schedule dnskey prefetch\", \n\t\tiq->dp->name, LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass);\n\tif(!generate_sub_request(iq->dp->name, iq->dp->namelen, \n\t\tLDNS_RR_TYPE_DNSKEY, iq->qchase.qclass, qstate, id, iq,\n\t\tINIT_REQUEST_STATE, FINISHED_STATE, &subq, 0)) {\n\t\t/* we'll be slower, but it'll work */\n\t\tverbose(VERB_ALGO, \"could not generate dnskey prefetch\");\n\t\treturn;\n\t}\n\tif(subq) {\n\t\tstruct iter_qstate* subiq = \n\t\t\t(struct iter_qstate*)subq->minfo[id];\n\t\t/* this qstate has the right delegation for the dnskey lookup*/\n\t\t/* make copy to avoid use of stub dp by different qs/threads */\n\t\tsubiq->dp = delegpt_copy(iq->dp, subq->region);\n\t\t/* if !subiq->dp, it'll start from the cache, no problem */\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming\n query into a large number of queries directed to a target.\n- CVE-2020-12663 Malformed answers from upstream name servers can be\n used to make Unbound unresponsive.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: prime_root(struct module_qstate* qstate, struct iter_qstate* iq, int id,\n\tuint16_t qclass)\n{\n\tstruct delegpt* dp;\n\tstruct module_qstate* subq;\n\tverbose(VERB_DETAIL, \"priming . %s NS\", \n\t\tsldns_lookup_by_id(sldns_rr_classes, (int)qclass)?\n\t\tsldns_lookup_by_id(sldns_rr_classes, (int)qclass)->name:\"??\");\n\tdp = hints_lookup_root(qstate->env->hints, qclass);\n\tif(!dp) {\n\t\tverbose(VERB_ALGO, \"Cannot prime due to lack of hints\");\n\t\treturn 0;\n\t}\n\t/* Priming requests start at the QUERYTARGETS state, skipping \n\t * the normal INIT state logic (which would cause an infloop). */\n\tif(!generate_sub_request((uint8_t*)\"\\000\", 1, LDNS_RR_TYPE_NS, \n\t\tqclass, qstate, id, iq, QUERYTARGETS_STATE, PRIME_RESP_STATE,\n\t\t&subq, 0)) {\n\t\tverbose(VERB_ALGO, \"could not prime root\");\n\t\treturn 0;\n\t}\n\tif(subq) {\n\t\tstruct iter_qstate* subiq = \n\t\t\t(struct iter_qstate*)subq->minfo[id];\n\t\t/* Set the initial delegation point to the hint.\n\t\t * copy dp, it is now part of the root prime query. \n\t\t * dp was part of in the fixed hints structure. */\n\t\tsubiq->dp = delegpt_copy(dp, subq->region);\n\t\tif(!subiq->dp) {\n\t\t\tlog_err(\"out of memory priming root, 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\treturn 0;\n\t\t}\n\t\t/* there should not be any target queries. */\n\t\tsubiq->num_target_queries = 0; \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: STATIC SSize_t\nS_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,\n SSize_t *minlenp, SSize_t *deltap,\n\t\t\tregnode *last,\n\t\t\tscan_data_t *data,\n\t\t\tI32 stopparen,\n U32 recursed_depth,\n\t\t\tregnode_ssc *and_withp,\n\t\t\tU32 flags, U32 depth)\n\t\t\t/* scanp: Start here (read-write). */\n\t\t\t/* deltap: Write maxlen-minlen here. */\n\t\t\t/* last: Stop before this one. */\n\t\t\t/* data: string data about the pattern */\n\t\t\t/* stopparen: treat close N as END */\n\t\t\t/* recursed: which subroutines have we recursed into */\n\t\t\t/* and_withp: Valid if flags & SCF_DO_STCLASS_OR */\n{\n dVAR;\n /* There must be at least this number of characters to match */\n SSize_t min = 0;\n I32 pars = 0, code;\n regnode *scan = *scanp, *next;\n SSize_t delta = 0;\n int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);\n int is_inf_internal = 0;\t\t/* The studied chunk is infinite */\n I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;\n scan_data_t data_fake;\n SV *re_trie_maxbuff = NULL;\n regnode *first_non_open = scan;\n SSize_t stopmin = SSize_t_MAX;\n scan_frame *frame = NULL;\n GET_RE_DEBUG_FLAGS_DECL;\n\n PERL_ARGS_ASSERT_STUDY_CHUNK;\n RExC_study_started= 1;\n\n Zero(&data_fake, 1, scan_data_t);\n\n if ( depth == 0 ) {\n while (first_non_open && OP(first_non_open) == OPEN)\n first_non_open=regnext(first_non_open);\n }\n\n\n fake_study_recurse:\n DEBUG_r(\n RExC_study_chunk_recursed_count++;\n );\n DEBUG_OPTIMISE_MORE_r(\n {\n Perl_re_indentf( aTHX_ \"study_chunk stopparen=%ld recursed_count=%lu depth=%lu recursed_depth=%lu scan=%p last=%p\",\n depth, (long)stopparen,\n (unsigned long)RExC_study_chunk_recursed_count,\n (unsigned long)depth, (unsigned long)recursed_depth,\n scan,\n last);\n if (recursed_depth) {\n U32 i;\n U32 j;\n for ( j = 0 ; j < recursed_depth ; j++ ) {\n for ( i = 0 ; i < (U32)RExC_total_parens ; i++ ) {\n if (\n PAREN_TEST(RExC_study_chunk_recursed +\n ( j * RExC_study_chunk_recursed_bytes), i )\n && (\n !j ||\n !PAREN_TEST(RExC_study_chunk_recursed +\n (( j - 1 ) * RExC_study_chunk_recursed_bytes), i)\n )\n ) {\n Perl_re_printf( aTHX_ \" %d\",(int)i);\n break;\n }\n }\n if ( j + 1 < recursed_depth ) {\n Perl_re_printf( aTHX_ \",\");\n }\n }\n }\n Perl_re_printf( aTHX_ \"\\n\");\n }\n );\n while ( scan && OP(scan) != END && scan < last ){\n UV min_subtract = 0; /* How mmany chars to subtract from the minimum\n node length to get a real minimum (because\n the folded version may be shorter) */\n\tbool unfolded_multi_char = FALSE;\n\t/* Peephole optimizer: */\n DEBUG_STUDYDATA(\"Peep\", data, depth, is_inf);\n DEBUG_PEEP(\"Peep\", scan, depth, flags);\n\n\n /* The reason we do this here is that we need to deal with things like\n * /(?:f)(?:o)(?:o)/ which cant be dealt with by the normal EXACT\n * parsing code, as each (?:..) is handled by a different invocation of\n * reg() -- Yves\n */\n JOIN_EXACT(scan,&min_subtract, &unfolded_multi_char, 0);\n\n /* Follow the next-chain of the current node and optimize\n away all the NOTHINGs from it.\n */\n rck_elide_nothing(scan);\n\n\t/* The principal pseudo-switch. Cannot be a switch, since we\n\t look into several different things. */\n if ( OP(scan) == DEFINEP ) {\n SSize_t minlen = 0;\n SSize_t deltanext = 0;\n SSize_t fake_last_close = 0;\n I32 f = SCF_IN_DEFINE;\n\n StructCopy(&zero_scan_data, &data_fake, scan_data_t);\n scan = regnext(scan);\n assert( OP(scan) == IFTHEN );\n DEBUG_PEEP(\"expect IFTHEN\", scan, depth, flags);\n\n data_fake.last_closep= &fake_last_close;\n minlen = *minlenp;\n next = regnext(scan);\n scan = NEXTOPER(NEXTOPER(scan));\n DEBUG_PEEP(\"scan\", scan, depth, flags);\n DEBUG_PEEP(\"next\", next, depth, flags);\n\n /* we suppose the run is continuous, last=next...\n * NOTE we dont use the return here! */\n /* DEFINEP study_chunk() recursion */\n (void)study_chunk(pRExC_state, &scan, &minlen,\n &deltanext, next, &data_fake, stopparen,\n recursed_depth, NULL, f, depth+1);\n\n scan = next;\n } else\n if (\n OP(scan) == BRANCH ||\n OP(scan) == BRANCHJ ||\n OP(scan) == IFTHEN\n ) {\n\t next = regnext(scan);\n\t code = OP(scan);\n\n /* The op(next)==code check below is to see if we\n * have \"BRANCH-BRANCH\", \"BRANCHJ-BRANCHJ\", \"IFTHEN-IFTHEN\"\n * IFTHEN is special as it might not appear in pairs.\n * Not sure whether BRANCH-BRANCHJ is possible, regardless\n * we dont handle it cleanly. */\n\t if (OP(next) == code || code == IFTHEN) {\n /* NOTE - There is similar code to this block below for\n * handling TRIE nodes on a re-study. If you change stuff here\n * check there too. */\n\t\tSSize_t max1 = 0, min1 = SSize_t_MAX, num = 0;\n\t\tregnode_ssc accum;\n\t\tregnode * const startbranch=scan;\n\n if (flags & SCF_DO_SUBSTR) {\n /* Cannot merge strings after this. */\n scan_commit(pRExC_state, data, minlenp, is_inf);\n }\n\n if (flags & SCF_DO_STCLASS)\n\t\t ssc_init_zero(pRExC_state, &accum);\n\n\t\twhile (OP(scan) == code) {\n\t\t SSize_t deltanext, minnext, fake;\n\t\t I32 f = 0;\n\t\t regnode_ssc this_class;\n\n DEBUG_PEEP(\"Branch\", scan, depth, flags);\n\n\t\t num++;\n StructCopy(&zero_scan_data, &data_fake, scan_data_t);\n\t\t if (data) {\n\t\t\tdata_fake.whilem_c = data->whilem_c;\n\t\t\tdata_fake.last_closep = data->last_closep;\n\t\t }\n\t\t else\n\t\t\tdata_fake.last_closep = &fake;\n\n\t\t data_fake.pos_delta = delta;\n\t\t next = regnext(scan);\n\n scan = NEXTOPER(scan); /* everything */\n if (code != BRANCH) /* everything but BRANCH */\n\t\t\tscan = NEXTOPER(scan);\n\n\t\t if (flags & SCF_DO_STCLASS) {\n\t\t\tssc_init(pRExC_state, &this_class);\n\t\t\tdata_fake.start_class = &this_class;\n\t\t\tf = SCF_DO_STCLASS_AND;\n\t\t }\n\t\t if (flags & SCF_WHILEM_VISITED_POS)\n\t\t\tf |= SCF_WHILEM_VISITED_POS;\n\n\t\t /* we suppose the run is continuous, last=next...*/\n /* recurse study_chunk() for each BRANCH in an alternation */\n\t\t minnext = study_chunk(pRExC_state, &scan, minlenp,\n &deltanext, next, &data_fake, stopparen,\n recursed_depth, NULL, f, depth+1);\n\n\t\t if (min1 > minnext)\n\t\t\tmin1 = minnext;\n\t\t if (deltanext == SSize_t_MAX) {\n\t\t\tis_inf = is_inf_internal = 1;\n\t\t\tmax1 = SSize_t_MAX;\n\t\t } else if (max1 < minnext + deltanext)\n\t\t\tmax1 = minnext + deltanext;\n\t\t scan = next;\n\t\t if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))\n\t\t\tpars++;\n\t if (data_fake.flags & SCF_SEEN_ACCEPT) {\n\t if ( stopmin > minnext)\n\t stopmin = min + min1;\n\t flags &= ~SCF_DO_SUBSTR;\n\t if (data)\n\t data->flags |= SCF_SEEN_ACCEPT;\n\t }\n\t\t if (data) {\n\t\t\tif (data_fake.flags & SF_HAS_EVAL)\n\t\t\t data->flags |= SF_HAS_EVAL;\n\t\t\tdata->whilem_c = data_fake.whilem_c;\n\t\t }\n\t\t if (flags & SCF_DO_STCLASS)\n\t\t\tssc_or(pRExC_state, &accum, (regnode_charclass*)&this_class);\n\t\t}\n\t\tif (code == IFTHEN && num < 2) /* Empty ELSE branch */\n\t\t min1 = 0;\n\t\tif (flags & SCF_DO_SUBSTR) {\n\t\t data->pos_min += min1;\n\t\t if (data->pos_delta >= SSize_t_MAX - (max1 - min1))\n\t\t data->pos_delta = SSize_t_MAX;\n\t\t else\n\t\t data->pos_delta += max1 - min1;\n\t\t if (max1 != min1 || is_inf)\n\t\t\tdata->cur_is_floating = 1;\n\t\t}\n\t\tmin += min1;\n\t\tif (delta == SSize_t_MAX\n\t\t || SSize_t_MAX - delta - (max1 - min1) < 0)\n\t\t delta = SSize_t_MAX;\n\t\telse\n\t\t delta += max1 - min1;\n\t\tif (flags & SCF_DO_STCLASS_OR) {\n\t\t ssc_or(pRExC_state, data->start_class, (regnode_charclass*) &accum);\n\t\t if (min1) {\n\t\t\tssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);\n\t\t\tflags &= ~SCF_DO_STCLASS;\n\t\t }\n\t\t}\n\t\telse if (flags & SCF_DO_STCLASS_AND) {\n\t\t if (min1) {\n\t\t\tssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);\n\t\t\tflags &= ~SCF_DO_STCLASS;\n\t\t }\n\t\t else {\n\t\t\t/* Switch to OR mode: cache the old value of\n\t\t\t * data->start_class */\n\t\t\tINIT_AND_WITHP;\n\t\t\tStructCopy(data->start_class, and_withp, regnode_ssc);\n\t\t\tflags &= ~SCF_DO_STCLASS_AND;\n\t\t\tStructCopy(&accum, data->start_class, regnode_ssc);\n\t\t\tflags |= SCF_DO_STCLASS_OR;\n\t\t }\n\t\t}\n\n if (PERL_ENABLE_TRIE_OPTIMISATION &&\n OP( startbranch ) == BRANCH )\n {\n\t\t/* demq.\n\n Assuming this was/is a branch we are dealing with: 'scan'\n now points at the item that follows the branch sequence,\n whatever it is. We now start at the beginning of the\n sequence and look for subsequences of\n\n\t\t BRANCH->EXACT=>x1\n\t\t BRANCH->EXACT=>x2\n\t\t tail\n\n which would be constructed from a pattern like\n /A|LIST|OF|WORDS/\n\n\t\t If we can find such a subsequence we need to turn the first\n\t\t element into a trie and then add the subsequent branch exact\n\t\t strings to the trie.\n\n\t\t We have two cases\n\n 1. patterns where the whole set of branches can be\n converted.\n\n\t\t 2. patterns where only a subset can be converted.\n\n\t\t In case 1 we can replace the whole set with a single regop\n\t\t for the trie. In case 2 we need to keep the start and end\n\t\t branches so\n\n\t\t 'BRANCH EXACT; BRANCH EXACT; BRANCH X'\n\t\t becomes BRANCH TRIE; BRANCH X;\n\n\t\t There is an additional case, that being where there is a\n\t\t common prefix, which gets split out into an EXACT like node\n\t\t preceding the TRIE node.\n\n\t\t If x(1..n)==tail then we can do a simple trie, if not we make\n\t\t a \"jump\" trie, such that when we match the appropriate word\n\t\t we \"jump\" to the appropriate tail node. Essentially we turn\n\t\t a nested if into a case structure of sorts.\n\n\t\t*/\n\n\t\t int made=0;\n\t\t if (!re_trie_maxbuff) {\n\t\t\tre_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);\n\t\t\tif (!SvIOK(re_trie_maxbuff))\n\t\t\t sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);\n\t\t }\n if ( SvIV(re_trie_maxbuff)>=0 ) {\n regnode *cur;\n regnode *first = (regnode *)NULL;\n regnode *last = (regnode *)NULL;\n regnode *tail = scan;\n U8 trietype = 0;\n U32 count=0;\n\n /* var tail is used because there may be a TAIL\n regop in the way. Ie, the exacts will point to the\n thing following the TAIL, but the last branch will\n point at the TAIL. So we advance tail. If we\n have nested (?:) we may have to move through several\n tails.\n */\n\n while ( OP( tail ) == TAIL ) {\n /* this is the TAIL generated by (?:) */\n tail = regnext( tail );\n }\n\n\n DEBUG_TRIE_COMPILE_r({\n regprop(RExC_rx, RExC_mysv, tail, NULL, pRExC_state);\n Perl_re_indentf( aTHX_ \"%s %\" UVuf \":%s\\n\",\n depth+1,\n \"Looking for TRIE'able sequences. Tail node is \",\n (UV) REGNODE_OFFSET(tail),\n SvPV_nolen_const( RExC_mysv )\n );\n });\n\n /*\n\n Step through the branches\n cur represents each branch,\n noper is the first thing to be matched as part\n of that branch\n noper_next is the regnext() of that node.\n\n We normally handle a case like this\n /FOO[xyz]|BAR[pqr]/ via a \"jump trie\" but we also\n support building with NOJUMPTRIE, which restricts\n the trie logic to structures like /FOO|BAR/.\n\n If noper is a trieable nodetype then the branch is\n a possible optimization target. If we are building\n under NOJUMPTRIE then we require that noper_next is\n the same as scan (our current position in the regex\n program).\n\n Once we have two or more consecutive such branches\n we can create a trie of the EXACT's contents and\n stitch it in place into the program.\n\n If the sequence represents all of the branches in\n the alternation we replace the entire thing with a\n single TRIE node.\n\n Otherwise when it is a subsequence we need to\n stitch it in place and replace only the relevant\n branches. This means the first branch has to remain\n as it is used by the alternation logic, and its\n next pointer, and needs to be repointed at the item\n on the branch chain following the last branch we\n have optimized away.\n\n This could be either a BRANCH, in which case the\n subsequence is internal, or it could be the item\n following the branch sequence in which case the\n subsequence is at the end (which does not\n necessarily mean the first node is the start of the\n alternation).\n\n TRIE_TYPE(X) is a define which maps the optype to a\n trietype.\n\n optype | trietype\n ----------------+-----------\n NOTHING | NOTHING\n EXACT | EXACT\n EXACT_ONLY8 | EXACT\n EXACTFU | EXACTFU\n EXACTFU_ONLY8 | EXACTFU\n EXACTFUP | EXACTFU\n EXACTFAA | EXACTFAA\n EXACTL | EXACTL\n EXACTFLU8 | EXACTFLU8\n\n\n */\n#define TRIE_TYPE(X) ( ( NOTHING == (X) ) \\\n ? NOTHING \\\n : ( EXACT == (X) || EXACT_ONLY8 == (X) ) \\\n ? EXACT \\\n : ( EXACTFU == (X) \\\n || EXACTFU_ONLY8 == (X) \\\n || EXACTFUP == (X) ) \\\n ? EXACTFU \\\n : ( EXACTFAA == (X) ) \\\n ? EXACTFAA \\\n : ( EXACTL == (X) ) \\\n ? EXACTL \\\n : ( EXACTFLU8 == (X) ) \\\n ? EXACTFLU8 \\\n : 0 )\n\n /* dont use tail as the end marker for this traverse */\n for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {\n regnode * const noper = NEXTOPER( cur );\n U8 noper_type = OP( noper );\n U8 noper_trietype = TRIE_TYPE( noper_type );\n#if defined(DEBUGGING) || defined(NOJUMPTRIE)\n regnode * const noper_next = regnext( noper );\n U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;\n U8 noper_next_trietype = (noper_next && noper_next < tail) ? TRIE_TYPE( noper_next_type ) :0;\n#endif\n\n DEBUG_TRIE_COMPILE_r({\n regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);\n Perl_re_indentf( aTHX_ \"- %d:%s (%d)\",\n depth+1,\n REG_NODE_NUM(cur), SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur) );\n\n regprop(RExC_rx, RExC_mysv, noper, NULL, pRExC_state);\n Perl_re_printf( aTHX_ \" -> %d:%s\",\n REG_NODE_NUM(noper), SvPV_nolen_const(RExC_mysv));\n\n if ( noper_next ) {\n regprop(RExC_rx, RExC_mysv, noper_next, NULL, pRExC_state);\n Perl_re_printf( aTHX_ \"\\t=> %d:%s\\t\",\n REG_NODE_NUM(noper_next), SvPV_nolen_const(RExC_mysv));\n }\n Perl_re_printf( aTHX_ \"(First==%d,Last==%d,Cur==%d,tt==%s,ntt==%s,nntt==%s)\\n\",\n REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur),\n\t\t\t\t PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype]\n\t\t\t\t);\n });\n\n /* Is noper a trieable nodetype that can be merged\n * with the current trie (if there is one)? */\n if ( noper_trietype\n &&\n (\n ( noper_trietype == NOTHING )\n || ( trietype == NOTHING )\n || ( trietype == noper_trietype )\n )\n#ifdef NOJUMPTRIE\n && noper_next >= tail\n#endif\n && count < U16_MAX)\n {\n /* Handle mergable triable node Either we are\n * the first node in a new trieable sequence,\n * in which case we do some bookkeeping,\n * otherwise we update the end pointer. */\n if ( !first ) {\n first = cur;\n\t\t\t\t if ( noper_trietype == NOTHING ) {\n#if !defined(DEBUGGING) && !defined(NOJUMPTRIE)\n\t\t\t\t\tregnode * const noper_next = regnext( noper );\n U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;\n\t\t\t\t\tU8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0;\n#endif\n\n if ( noper_next_trietype ) {\n\t\t\t\t\t trietype = noper_next_trietype;\n } else if (noper_next_type) {\n /* a NOTHING regop is 1 regop wide.\n * We need at least two for a trie\n * so we can't merge this in */\n first = NULL;\n }\n } else {\n trietype = noper_trietype;\n }\n } else {\n if ( trietype == NOTHING )\n trietype = noper_trietype;\n last = cur;\n }\n\t\t\t\tif (first)\n\t\t\t\t count++;\n } /* end handle mergable triable node */\n else {\n /* handle unmergable node -\n * noper may either be a triable node which can\n * not be tried together with the current trie,\n * or a non triable node */\n if ( last ) {\n /* If last is set and trietype is not\n * NOTHING then we have found at least two\n * triable branch sequences in a row of a\n * similar trietype so we can turn them\n * into a trie. If/when we allow NOTHING to\n * start a trie sequence this condition\n * will be required, and it isn't expensive\n * so we leave it in for now. */\n if ( trietype && trietype != NOTHING )\n make_trie( pRExC_state,\n startbranch, first, cur, tail,\n count, trietype, depth+1 );\n last = NULL; /* note: we clear/update\n first, trietype etc below,\n so we dont do it here */\n }\n if ( noper_trietype\n#ifdef NOJUMPTRIE\n && noper_next >= tail\n#endif\n ){\n /* noper is triable, so we can start a new\n * trie sequence */\n count = 1;\n first = cur;\n trietype = noper_trietype;\n } else if (first) {\n /* if we already saw a first but the\n * current node is not triable then we have\n * to reset the first information. */\n count = 0;\n first = NULL;\n trietype = 0;\n }\n } /* end handle unmergable node */\n } /* loop over branches */\n DEBUG_TRIE_COMPILE_r({\n regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);\n Perl_re_indentf( aTHX_ \"- %s (%d) \",\n depth+1, SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));\n Perl_re_printf( aTHX_ \"(First==%d, Last==%d, Cur==%d, tt==%s)\\n\",\n REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur),\n PL_reg_name[trietype]\n );\n\n });\n if ( last && trietype ) {\n if ( trietype != NOTHING ) {\n /* the last branch of the sequence was part of\n * a trie, so we have to construct it here\n * outside of the loop */\n made= make_trie( pRExC_state, startbranch,\n first, scan, tail, count,\n trietype, depth+1 );\n#ifdef TRIE_STUDY_OPT\n if ( ((made == MADE_EXACT_TRIE &&\n startbranch == first)\n || ( first_non_open == first )) &&\n depth==0 ) {\n flags |= SCF_TRIE_RESTUDY;\n if ( startbranch == first\n && scan >= tail )\n {\n RExC_seen &=~REG_TOP_LEVEL_BRANCHES_SEEN;\n }\n }\n#endif\n } else {\n /* at this point we know whatever we have is a\n * NOTHING sequence/branch AND if 'startbranch'\n * is 'first' then we can turn the whole thing\n * into a NOTHING\n */\n if ( startbranch == first ) {\n regnode *opt;\n /* the entire thing is a NOTHING sequence,\n * something like this: (?:|) So we can\n * turn it into a plain NOTHING op. */\n DEBUG_TRIE_COMPILE_r({\n regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);\n Perl_re_indentf( aTHX_ \"- %s (%d) \\n\",\n depth+1,\n SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));\n\n });\n OP(startbranch)= NOTHING;\n NEXT_OFF(startbranch)= tail - startbranch;\n for ( opt= startbranch + 1; opt < tail ; opt++ )\n OP(opt)= OPTIMIZED;\n }\n }\n } /* end if ( last) */\n } /* TRIE_MAXBUF is non zero */\n\n } /* do trie */\n\n\t }\n\t else if ( code == BRANCHJ ) { /* single branch is optimized. */\n\t\tscan = NEXTOPER(NEXTOPER(scan));\n\t } else\t\t\t/* single branch is optimized. */\n\t\tscan = NEXTOPER(scan);\n\t continue;\n } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB) {\n I32 paren = 0;\n regnode *start = NULL;\n regnode *end = NULL;\n U32 my_recursed_depth= recursed_depth;\n\n if (OP(scan) != SUSPEND) { /* GOSUB */\n /* Do setup, note this code has side effects beyond\n * the rest of this block. Specifically setting\n * RExC_recurse[] must happen at least once during\n * study_chunk(). */\n paren = ARG(scan);\n RExC_recurse[ARG2L(scan)] = scan;\n start = REGNODE_p(RExC_open_parens[paren]);\n end = REGNODE_p(RExC_close_parens[paren]);\n\n /* NOTE we MUST always execute the above code, even\n * if we do nothing with a GOSUB */\n if (\n ( flags & SCF_IN_DEFINE )\n ||\n (\n (is_inf_internal || is_inf || (data && data->flags & SF_IS_INF))\n &&\n ( (flags & (SCF_DO_STCLASS | SCF_DO_SUBSTR)) == 0 )\n )\n ) {\n /* no need to do anything here if we are in a define. */\n /* or we are after some kind of infinite construct\n * so we can skip recursing into this item.\n * Since it is infinite we will not change the maxlen\n * or delta, and if we miss something that might raise\n * the minlen it will merely pessimise a little.\n *\n * Iow /(?(DEFINE)(?foo|food))a+(?&foo)/\n * might result in a minlen of 1 and not of 4,\n * but this doesn't make us mismatch, just try a bit\n * harder than we should.\n * */\n scan= regnext(scan);\n continue;\n }\n\n if (\n !recursed_depth\n ||\n !PAREN_TEST(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), paren)\n ) {\n /* it is quite possible that there are more efficient ways\n * to do this. We maintain a bitmap per level of recursion\n * of which patterns we have entered so we can detect if a\n * pattern creates a possible infinite loop. When we\n * recurse down a level we copy the previous levels bitmap\n * down. When we are at recursion level 0 we zero the top\n * level bitmap. It would be nice to implement a different\n * more efficient way of doing this. In particular the top\n * level bitmap may be unnecessary.\n */\n if (!recursed_depth) {\n Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes, U8);\n } else {\n Copy(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes),\n RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes),\n RExC_study_chunk_recursed_bytes, U8);\n }\n /* we havent recursed into this paren yet, so recurse into it */\n DEBUG_STUDYDATA(\"gosub-set\", data, depth, is_inf);\n PAREN_SET(RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), paren);\n my_recursed_depth= recursed_depth + 1;\n } else {\n DEBUG_STUDYDATA(\"gosub-inf\", data, depth, is_inf);\n /* some form of infinite recursion, assume infinite length\n * */\n if (flags & SCF_DO_SUBSTR) {\n scan_commit(pRExC_state, data, minlenp, is_inf);\n data->cur_is_floating = 1;\n }\n is_inf = is_inf_internal = 1;\n if (flags & SCF_DO_STCLASS_OR) /* Allow everything */\n ssc_anything(data->start_class);\n flags &= ~SCF_DO_STCLASS;\n\n start= NULL; /* reset start so we dont recurse later on. */\n\t }\n } else {\n\t paren = stopparen;\n start = scan + 2;\n\t end = regnext(scan);\n\t }\n if (start) {\n scan_frame *newframe;\n assert(end);\n if (!RExC_frame_last) {\n Newxz(newframe, 1, scan_frame);\n SAVEDESTRUCTOR_X(S_unwind_scan_frames, newframe);\n RExC_frame_head= newframe;\n RExC_frame_count++;\n } else if (!RExC_frame_last->next_frame) {\n Newxz(newframe, 1, scan_frame);\n RExC_frame_last->next_frame= newframe;\n newframe->prev_frame= RExC_frame_last;\n RExC_frame_count++;\n } else {\n newframe= RExC_frame_last->next_frame;\n }\n RExC_frame_last= newframe;\n\n newframe->next_regnode = regnext(scan);\n newframe->last_regnode = last;\n newframe->stopparen = stopparen;\n newframe->prev_recursed_depth = recursed_depth;\n newframe->this_prev_frame= frame;\n\n DEBUG_STUDYDATA(\"frame-new\", data, depth, is_inf);\n DEBUG_PEEP(\"fnew\", scan, depth, flags);\n\n\t frame = newframe;\n\t scan = start;\n\t stopparen = paren;\n\t last = end;\n depth = depth + 1;\n recursed_depth= my_recursed_depth;\n\n\t continue;\n\t }\n\t}\n\telse if ( OP(scan) == EXACT\n || OP(scan) == EXACT_ONLY8\n || OP(scan) == EXACTL)\n {\n\t SSize_t l = STR_LEN(scan);\n\t UV uc;\n assert(l);\n\t if (UTF) {\n\t\tconst U8 * const s = (U8*)STRING(scan);\n\t\tuc = utf8_to_uvchr_buf(s, s + l, NULL);\n\t\tl = utf8_length(s, s + l);\n\t } else {\n\t\tuc = *((U8*)STRING(scan));\n\t }\n\t min += l;\n\t if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */\n\t\t/* The code below prefers earlier match for fixed\n\t\t offset, later match for variable offset. */\n\t\tif (data->last_end == -1) { /* Update the start info. */\n\t\t data->last_start_min = data->pos_min;\n \t\t data->last_start_max = is_inf\n \t\t\t? SSize_t_MAX : data->pos_min + data->pos_delta;\n\t\t}\n\t\tsv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));\n\t\tif (UTF)\n\t\t SvUTF8_on(data->last_found);\n\t\t{\n\t\t SV * const sv = data->last_found;\n\t\t MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?\n\t\t\tmg_find(sv, PERL_MAGIC_utf8) : NULL;\n\t\t if (mg && mg->mg_len >= 0)\n\t\t\tmg->mg_len += utf8_length((U8*)STRING(scan),\n (U8*)STRING(scan)+STR_LEN(scan));\n\t\t}\n\t\tdata->last_end = data->pos_min + l;\n\t\tdata->pos_min += l; /* As in the first entry. */\n\t\tdata->flags &= ~SF_BEFORE_EOL;\n\t }\n\n /* ANDing the code point leaves at most it, and not in locale, and\n * can't match null string */\n\t if (flags & SCF_DO_STCLASS_AND) {\n ssc_cp_and(data->start_class, uc);\n ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;\n ssc_clear_locale(data->start_class);\n\t }\n\t else if (flags & SCF_DO_STCLASS_OR) {\n ssc_add_cp(data->start_class, uc);\n\t\tssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);\n\n /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */\n ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;\n\t }\n\t flags &= ~SCF_DO_STCLASS;\n\t}\n else if (PL_regkind[OP(scan)] == EXACT) {\n /* But OP != EXACT!, so is EXACTFish */\n\t SSize_t l = STR_LEN(scan);\n const U8 * s = (U8*)STRING(scan);\n\n\t /* Search for fixed substrings supports EXACT only. */\n\t if (flags & SCF_DO_SUBSTR) {\n\t\tassert(data);\n scan_commit(pRExC_state, data, minlenp, is_inf);\n\t }\n\t if (UTF) {\n\t\tl = utf8_length(s, s + l);\n\t }\n\t if (unfolded_multi_char) {\n RExC_seen |= REG_UNFOLDED_MULTI_SEEN;\n\t }\n\t min += l - min_subtract;\n assert (min >= 0);\n delta += min_subtract;\n\t if (flags & SCF_DO_SUBSTR) {\n\t\tdata->pos_min += l - min_subtract;\n\t\tif (data->pos_min < 0) {\n data->pos_min = 0;\n }\n data->pos_delta += min_subtract;\n\t\tif (min_subtract) {\n\t\t data->cur_is_floating = 1; /* float */\n\t\t}\n\t }\n\n if (flags & SCF_DO_STCLASS) {\n SV* EXACTF_invlist = _make_exactf_invlist(pRExC_state, scan);\n\n assert(EXACTF_invlist);\n if (flags & SCF_DO_STCLASS_AND) {\n if (OP(scan) != EXACTFL)\n ssc_clear_locale(data->start_class);\n ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;\n ANYOF_POSIXL_ZERO(data->start_class);\n ssc_intersection(data->start_class, EXACTF_invlist, FALSE);\n }\n else { /* SCF_DO_STCLASS_OR */\n ssc_union(data->start_class, EXACTF_invlist, FALSE);\n ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);\n\n /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */\n ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;\n }\n flags &= ~SCF_DO_STCLASS;\n SvREFCNT_dec(EXACTF_invlist);\n }\n\t}\n\telse if (REGNODE_VARIES(OP(scan))) {\n\t SSize_t mincount, maxcount, minnext, deltanext, pos_before = 0;\n\t I32 fl = 0, f = flags;\n\t regnode * const oscan = scan;\n\t regnode_ssc this_class;\n\t regnode_ssc *oclass = NULL;\n\t I32 next_is_eval = 0;\n\n\t switch (PL_regkind[OP(scan)]) {\n\t case WHILEM:\t\t/* End of (?:...)* . */\n\t\tscan = NEXTOPER(scan);\n\t\tgoto finish;\n\t case PLUS:\n\t\tif (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {\n\t\t next = NEXTOPER(scan);\n\t\t if ( OP(next) == EXACT\n || OP(next) == EXACT_ONLY8\n || OP(next) == EXACTL\n || (flags & SCF_DO_STCLASS))\n {\n\t\t\tmincount = 1;\n\t\t\tmaxcount = REG_INFTY;\n\t\t\tnext = regnext(scan);\n\t\t\tscan = NEXTOPER(scan);\n\t\t\tgoto do_curly;\n\t\t }\n\t\t}\n\t\tif (flags & SCF_DO_SUBSTR)\n\t\t data->pos_min++;\n\t\tmin++;\n\t\t/* FALLTHROUGH */\n\t case STAR:\n next = NEXTOPER(scan);\n\n /* This temporary node can now be turned into EXACTFU, and\n * must, as regexec.c doesn't handle it */\n if (OP(next) == EXACTFU_S_EDGE) {\n OP(next) = EXACTFU;\n }\n\n if ( STR_LEN(next) == 1\n && isALPHA_A(* STRING(next))\n && ( OP(next) == EXACTFAA\n || ( OP(next) == EXACTFU\n && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(next)))))\n {\n /* These differ in just one bit */\n U8 mask = ~ ('A' ^ 'a');\n\n assert(isALPHA_A(* STRING(next)));\n\n /* Then replace it by an ANYOFM node, with\n * the mask set to the complement of the\n * bit that differs between upper and lower\n * case, and the lowest code point of the\n * pair (which the '&' forces) */\n OP(next) = ANYOFM;\n ARG_SET(next, *STRING(next) & mask);\n FLAGS(next) = mask;\n }\n\n\t\tif (flags & SCF_DO_STCLASS) {\n\t\t mincount = 0;\n\t\t maxcount = REG_INFTY;\n\t\t next = regnext(scan);\n\t\t scan = NEXTOPER(scan);\n\t\t goto do_curly;\n\t\t}\n\t\tif (flags & SCF_DO_SUBSTR) {\n scan_commit(pRExC_state, data, minlenp, is_inf);\n /* Cannot extend fixed substrings */\n\t\t data->cur_is_floating = 1; /* float */\n\t\t}\n is_inf = is_inf_internal = 1;\n scan = regnext(scan);\n\t\tgoto optimize_curly_tail;\n\t case CURLY:\n\t if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)\n\t && (scan->flags == stopparen))\n\t\t{\n\t\t mincount = 1;\n\t\t maxcount = 1;\n\t\t} else {\n\t\t mincount = ARG1(scan);\n\t\t maxcount = ARG2(scan);\n\t\t}\n\t\tnext = regnext(scan);\n\t\tif (OP(scan) == CURLYX) {\n\t\t I32 lp = (data ? *(data->last_closep) : 0);\n\t\t scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);\n\t\t}\n\t\tscan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;\n\t\tnext_is_eval = (OP(scan) == EVAL);\n\t do_curly:\n\t\tif (flags & SCF_DO_SUBSTR) {\n if (mincount == 0)\n scan_commit(pRExC_state, data, minlenp, is_inf);\n /* Cannot extend fixed substrings */\n\t\t pos_before = data->pos_min;\n\t\t}\n\t\tif (data) {\n\t\t fl = data->flags;\n\t\t data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);\n\t\t if (is_inf)\n\t\t\tdata->flags |= SF_IS_INF;\n\t\t}\n\t\tif (flags & SCF_DO_STCLASS) {\n\t\t ssc_init(pRExC_state, &this_class);\n\t\t oclass = data->start_class;\n\t\t data->start_class = &this_class;\n\t\t f |= SCF_DO_STCLASS_AND;\n\t\t f &= ~SCF_DO_STCLASS_OR;\n\t\t}\n\t /* Exclude from super-linear cache processing any {n,m}\n\t\t regops for which the combination of input pos and regex\n\t\t pos is not enough information to determine if a match\n\t\t will be possible.\n\n\t\t For example, in the regex /foo(bar\\s*){4,8}baz/ with the\n\t\t regex pos at the \\s*, the prospects for a match depend not\n\t\t only on the input position but also on how many (bar\\s*)\n\t\t repeats into the {4,8} we are. */\n if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY))\n\t\t f &= ~SCF_WHILEM_VISITED_POS;\n\n\t\t/* This will finish on WHILEM, setting scan, or on NULL: */\n /* recurse study_chunk() on loop bodies */\n\t\tminnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,\n last, data, stopparen, recursed_depth, NULL,\n (mincount == 0\n ? (f & ~SCF_DO_SUBSTR)\n : f)\n ,depth+1);\n\n\t\tif (flags & SCF_DO_STCLASS)\n\t\t data->start_class = oclass;\n\t\tif (mincount == 0 || minnext == 0) {\n\t\t if (flags & SCF_DO_STCLASS_OR) {\n\t\t\tssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);\n\t\t }\n\t\t else if (flags & SCF_DO_STCLASS_AND) {\n\t\t\t/* Switch to OR mode: cache the old value of\n\t\t\t * data->start_class */\n\t\t\tINIT_AND_WITHP;\n\t\t\tStructCopy(data->start_class, and_withp, regnode_ssc);\n\t\t\tflags &= ~SCF_DO_STCLASS_AND;\n\t\t\tStructCopy(&this_class, data->start_class, regnode_ssc);\n\t\t\tflags |= SCF_DO_STCLASS_OR;\n ANYOF_FLAGS(data->start_class)\n |= SSC_MATCHES_EMPTY_STRING;\n\t\t }\n\t\t} else {\t\t/* Non-zero len */\n\t\t if (flags & SCF_DO_STCLASS_OR) {\n\t\t\tssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);\n\t\t\tssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);\n\t\t }\n\t\t else if (flags & SCF_DO_STCLASS_AND)\n\t\t\tssc_and(pRExC_state, data->start_class, (regnode_charclass *) &this_class);\n\t\t flags &= ~SCF_DO_STCLASS;\n\t\t}\n\t\tif (!scan) \t\t/* It was not CURLYX, but CURLY. */\n\t\t scan = next;\n\t\tif (((flags & (SCF_TRIE_DOING_RESTUDY|SCF_DO_SUBSTR))==SCF_DO_SUBSTR)\n\t\t /* ? quantifier ok, except for (?{ ... }) */\n\t\t && (next_is_eval || !(mincount == 0 && maxcount == 1))\n\t\t && (minnext == 0) && (deltanext == 0)\n\t\t && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))\n && maxcount <= REG_INFTY/3) /* Complement check for big\n count */\n\t\t{\n\t\t _WARN_HELPER(RExC_precomp_end, packWARN(WARN_REGEXP),\n Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),\n \"Quantifier unexpected on zero-length expression \"\n \"in regex m/%\" UTF8f \"/\",\n\t\t\t UTF8fARG(UTF, RExC_precomp_end - RExC_precomp,\n\t\t\t\t RExC_precomp)));\n }\n\n if ( ( minnext > 0 && mincount >= SSize_t_MAX / minnext )\n || min >= SSize_t_MAX - minnext * mincount )\n {\n FAIL(\"Regexp out of space\");\n }\n\n\t\tmin += minnext * mincount;\n\t\tis_inf_internal |= deltanext == SSize_t_MAX\n || (maxcount == REG_INFTY && minnext + deltanext > 0);\n\t\tis_inf |= is_inf_internal;\n if (is_inf) {\n\t\t delta = SSize_t_MAX;\n } else {\n\t\t delta += (minnext + deltanext) * maxcount\n - minnext * mincount;\n }\n\t\t/* Try powerful optimization CURLYX => CURLYN. */\n\t\tif ( OP(oscan) == CURLYX && data\n\t\t && data->flags & SF_IN_PAR\n\t\t && !(data->flags & SF_HAS_EVAL)\n\t\t && !deltanext && minnext == 1 ) {\n\t\t /* Try to optimize to CURLYN. */\n\t\t regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;\n\t\t regnode * const nxt1 = nxt;\n#ifdef DEBUGGING\n\t\t regnode *nxt2;\n#endif\n\n\t\t /* Skip open. */\n\t\t nxt = regnext(nxt);\n\t\t if (!REGNODE_SIMPLE(OP(nxt))\n\t\t\t&& !(PL_regkind[OP(nxt)] == EXACT\n\t\t\t && STR_LEN(nxt) == 1))\n\t\t\tgoto nogo;\n#ifdef DEBUGGING\n\t\t nxt2 = nxt;\n#endif\n\t\t nxt = regnext(nxt);\n\t\t if (OP(nxt) != CLOSE)\n\t\t\tgoto nogo;\n\t\t if (RExC_open_parens) {\n\n /*open->CURLYM*/\n RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);\n\n /*close->while*/\n RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt) + 2;\n\t\t }\n\t\t /* Now we know that nxt2 is the only contents: */\n\t\t oscan->flags = (U8)ARG(nxt);\n\t\t OP(oscan) = CURLYN;\n\t\t OP(nxt1) = NOTHING;\t/* was OPEN. */\n\n#ifdef DEBUGGING\n\t\t OP(nxt1 + 1) = OPTIMIZED; /* was count. */\n\t\t NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */\n\t\t NEXT_OFF(nxt2) = 0;\t/* just for consistency with CURLY. */\n\t\t OP(nxt) = OPTIMIZED;\t/* was CLOSE. */\n\t\t OP(nxt + 1) = OPTIMIZED; /* was count. */\n\t\t NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */\n#endif\n\t\t}\n\t nogo:\n\n\t\t/* Try optimization CURLYX => CURLYM. */\n\t\tif ( OP(oscan) == CURLYX && data\n\t\t && !(data->flags & SF_HAS_PAR)\n\t\t && !(data->flags & SF_HAS_EVAL)\n\t\t && !deltanext\t/* atom is fixed width */\n\t\t && minnext != 0\t/* CURLYM can't handle zero width */\n\n /* Nor characters whose fold at run-time may be\n * multi-character */\n && ! (RExC_seen & REG_UNFOLDED_MULTI_SEEN)\n\t\t) {\n\t\t /* XXXX How to optimize if data == 0? */\n\t\t /* Optimize to a simpler form. */\n\t\t regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */\n\t\t regnode *nxt2;\n\n\t\t OP(oscan) = CURLYM;\n\t\t while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/\n\t\t\t && (OP(nxt2) != WHILEM))\n\t\t\tnxt = nxt2;\n\t\t OP(nxt2) = SUCCEED; /* Whas WHILEM */\n\t\t /* Need to optimize away parenths. */\n\t\t if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {\n\t\t\t/* Set the parenth number. */\n\t\t\tregnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/\n\n\t\t\toscan->flags = (U8)ARG(nxt);\n\t\t\tif (RExC_open_parens) {\n /*open->CURLYM*/\n RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);\n\n /*close->NOTHING*/\n RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt2)\n + 1;\n\t\t\t}\n\t\t\tOP(nxt1) = OPTIMIZED;\t/* was OPEN. */\n\t\t\tOP(nxt) = OPTIMIZED;\t/* was CLOSE. */\n\n#ifdef DEBUGGING\n\t\t\tOP(nxt1 + 1) = OPTIMIZED; /* was count. */\n\t\t\tOP(nxt + 1) = OPTIMIZED; /* was count. */\n\t\t\tNEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */\n\t\t\tNEXT_OFF(nxt + 1) = 0; /* just for consistency. */\n#endif\n#if 0\n\t\t\twhile ( nxt1 && (OP(nxt1) != WHILEM)) {\n\t\t\t regnode *nnxt = regnext(nxt1);\n\t\t\t if (nnxt == nxt) {\n\t\t\t\tif (reg_off_by_arg[OP(nxt1)])\n\t\t\t\t ARG_SET(nxt1, nxt2 - nxt1);\n\t\t\t\telse if (nxt2 - nxt1 < U16_MAX)\n\t\t\t\t NEXT_OFF(nxt1) = nxt2 - nxt1;\n\t\t\t\telse\n\t\t\t\t OP(nxt) = NOTHING;\t/* Cannot beautify */\n\t\t\t }\n\t\t\t nxt1 = nnxt;\n\t\t\t}\n#endif\n\t\t\t/* Optimize again: */\n /* recurse study_chunk() on optimised CURLYX => CURLYM */\n\t\t\tstudy_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,\n NULL, stopparen, recursed_depth, NULL, 0,\n depth+1);\n\t\t }\n\t\t else\n\t\t\toscan->flags = 0;\n\t\t}\n\t\telse if ((OP(oscan) == CURLYX)\n\t\t\t && (flags & SCF_WHILEM_VISITED_POS)\n\t\t\t /* See the comment on a similar expression above.\n\t\t\t However, this time it's not a subexpression\n\t\t\t we care about, but the expression itself. */\n\t\t\t && (maxcount == REG_INFTY)\n\t\t\t && data) {\n\t\t /* This stays as CURLYX, we can put the count/of pair. */\n\t\t /* Find WHILEM (as in regexec.c) */\n\t\t regnode *nxt = oscan + NEXT_OFF(oscan);\n\n\t\t if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */\n\t\t\tnxt += ARG(nxt);\n nxt = PREVOPER(nxt);\n if (nxt->flags & 0xf) {\n /* we've already set whilem count on this node */\n } else if (++data->whilem_c < 16) {\n assert(data->whilem_c <= RExC_whilem_seen);\n nxt->flags = (U8)(data->whilem_c\n | (RExC_whilem_seen << 4)); /* On WHILEM */\n }\n\t\t}\n\t\tif (data && fl & (SF_HAS_PAR|SF_IN_PAR))\n\t\t pars++;\n\t\tif (flags & SCF_DO_SUBSTR) {\n\t\t SV *last_str = NULL;\n STRLEN last_chrs = 0;\n\t\t int counted = mincount != 0;\n\n if (data->last_end > 0 && mincount != 0) { /* Ends with a\n string. */\n\t\t\tSSize_t b = pos_before >= data->last_start_min\n\t\t\t ? pos_before : data->last_start_min;\n\t\t\tSTRLEN l;\n\t\t\tconst char * const s = SvPV_const(data->last_found, l);\n\t\t\tSSize_t old = b - data->last_start_min;\n assert(old >= 0);\n\n\t\t\tif (UTF)\n\t\t\t old = utf8_hop_forward((U8*)s, old,\n (U8 *) SvEND(data->last_found))\n - (U8*)s;\n\t\t\tl -= old;\n\t\t\t/* Get the added string: */\n\t\t\tlast_str = newSVpvn_utf8(s + old, l, UTF);\n last_chrs = UTF ? utf8_length((U8*)(s + old),\n (U8*)(s + old + l)) : l;\n\t\t\tif (deltanext == 0 && pos_before == b) {\n\t\t\t /* What was added is a constant string */\n\t\t\t if (mincount > 1) {\n\n\t\t\t\tSvGROW(last_str, (mincount * l) + 1);\n\t\t\t\trepeatcpy(SvPVX(last_str) + l,\n\t\t\t\t\t SvPVX_const(last_str), l,\n mincount - 1);\n\t\t\t\tSvCUR_set(last_str, SvCUR(last_str) * mincount);\n\t\t\t\t/* Add additional parts. */\n\t\t\t\tSvCUR_set(data->last_found,\n\t\t\t\t\t SvCUR(data->last_found) - l);\n\t\t\t\tsv_catsv(data->last_found, last_str);\n\t\t\t\t{\n\t\t\t\t SV * sv = data->last_found;\n\t\t\t\t MAGIC *mg =\n\t\t\t\t\tSvUTF8(sv) && SvMAGICAL(sv) ?\n\t\t\t\t\tmg_find(sv, PERL_MAGIC_utf8) : NULL;\n\t\t\t\t if (mg && mg->mg_len >= 0)\n\t\t\t\t\tmg->mg_len += last_chrs * (mincount-1);\n\t\t\t\t}\n last_chrs *= mincount;\n\t\t\t\tdata->last_end += l * (mincount - 1);\n\t\t\t }\n\t\t\t} else {\n\t\t\t /* start offset must point into the last copy */\n\t\t\t data->last_start_min += minnext * (mincount - 1);\n\t\t\t data->last_start_max =\n is_inf\n ? SSize_t_MAX\n\t\t\t : data->last_start_max +\n (maxcount - 1) * (minnext + data->pos_delta);\n\t\t\t}\n\t\t }\n\t\t /* It is counted once already... */\n\t\t data->pos_min += minnext * (mincount - counted);\n#if 0\nPerl_re_printf( aTHX_ \"counted=%\" UVuf \" deltanext=%\" UVuf\n \" SSize_t_MAX=%\" UVuf \" minnext=%\" UVuf\n \" maxcount=%\" UVuf \" mincount=%\" UVuf \"\\n\",\n (UV)counted, (UV)deltanext, (UV)SSize_t_MAX, (UV)minnext, (UV)maxcount,\n (UV)mincount);\nif (deltanext != SSize_t_MAX)\nPerl_re_printf( aTHX_ \"LHS=%\" UVuf \" RHS=%\" UVuf \"\\n\",\n (UV)(-counted * deltanext + (minnext + deltanext) * maxcount\n - minnext * mincount), (UV)(SSize_t_MAX - data->pos_delta));\n#endif\n\t\t if (deltanext == SSize_t_MAX\n || -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount >= SSize_t_MAX - data->pos_delta)\n\t\t data->pos_delta = SSize_t_MAX;\n\t\t else\n\t\t data->pos_delta += - counted * deltanext +\n\t\t\t(minnext + deltanext) * maxcount - minnext * mincount;\n\t\t if (mincount != maxcount) {\n\t\t\t /* Cannot extend fixed substrings found inside\n\t\t\t the group. */\n scan_commit(pRExC_state, data, minlenp, is_inf);\n\t\t\tif (mincount && last_str) {\n\t\t\t SV * const sv = data->last_found;\n\t\t\t MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?\n\t\t\t\tmg_find(sv, PERL_MAGIC_utf8) : NULL;\n\n\t\t\t if (mg)\n\t\t\t\tmg->mg_len = -1;\n\t\t\t sv_setsv(sv, last_str);\n\t\t\t data->last_end = data->pos_min;\n\t\t\t data->last_start_min = data->pos_min - last_chrs;\n\t\t\t data->last_start_max = is_inf\n\t\t\t\t? SSize_t_MAX\n\t\t\t\t: data->pos_min + data->pos_delta - last_chrs;\n\t\t\t}\n\t\t\tdata->cur_is_floating = 1; /* float */\n\t\t }\n\t\t SvREFCNT_dec(last_str);\n\t\t}\n\t\tif (data && (fl & SF_HAS_EVAL))\n\t\t data->flags |= SF_HAS_EVAL;\n\t optimize_curly_tail:\n\t\trck_elide_nothing(oscan);\n\t\tcontinue;\n\n\t default:\n#ifdef DEBUGGING\n Perl_croak(aTHX_ \"panic: unexpected varying REx opcode %d\",\n OP(scan));\n#endif\n case REF:\n case CLUMP:\n\t\tif (flags & SCF_DO_SUBSTR) {\n /* Cannot expect anything... */\n scan_commit(pRExC_state, data, minlenp, is_inf);\n\t\t data->cur_is_floating = 1; /* float */\n\t\t}\n\t\tis_inf = is_inf_internal = 1;\n\t\tif (flags & SCF_DO_STCLASS_OR) {\n if (OP(scan) == CLUMP) {\n /* Actually is any start char, but very few code points\n * aren't start characters */\n ssc_match_all_cp(data->start_class);\n }\n else {\n ssc_anything(data->start_class);\n }\n }\n\t\tflags &= ~SCF_DO_STCLASS;\n\t\tbreak;\n\t }\n\t}\n\telse if (OP(scan) == LNBREAK) {\n\t if (flags & SCF_DO_STCLASS) {\n \t if (flags & SCF_DO_STCLASS_AND) {\n ssc_intersection(data->start_class,\n PL_XPosix_ptrs[_CC_VERTSPACE], FALSE);\n ssc_clear_locale(data->start_class);\n ANYOF_FLAGS(data->start_class)\n &= ~SSC_MATCHES_EMPTY_STRING;\n }\n else if (flags & SCF_DO_STCLASS_OR) {\n ssc_union(data->start_class,\n PL_XPosix_ptrs[_CC_VERTSPACE],\n FALSE);\n\t\t ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);\n\n /* See commit msg for\n * 749e076fceedeb708a624933726e7989f2302f6a */\n ANYOF_FLAGS(data->start_class)\n &= ~SSC_MATCHES_EMPTY_STRING;\n }\n\t\tflags &= ~SCF_DO_STCLASS;\n }\n\t min++;\n if (delta != SSize_t_MAX)\n delta++; /* Because of the 2 char string cr-lf */\n if (flags & SCF_DO_SUBSTR) {\n /* Cannot expect anything... */\n scan_commit(pRExC_state, data, minlenp, is_inf);\n \t data->pos_min += 1;\n if (data->pos_delta != SSize_t_MAX) {\n data->pos_delta += 1;\n }\n\t\tdata->cur_is_floating = 1; /* float */\n \t }\n\t}\n\telse if (REGNODE_SIMPLE(OP(scan))) {\n\n\t if (flags & SCF_DO_SUBSTR) {\n scan_commit(pRExC_state, data, minlenp, is_inf);\n\t\tdata->pos_min++;\n\t }\n\t min++;\n\t if (flags & SCF_DO_STCLASS) {\n bool invert = 0;\n SV* my_invlist = NULL;\n U8 namedclass;\n\n /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */\n ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;\n\n\t\t/* Some of the logic below assumes that switching\n\t\t locale on will only add false positives. */\n\t\tswitch (OP(scan)) {\n\n\t\tdefault:\n#ifdef DEBUGGING\n Perl_croak(aTHX_ \"panic: unexpected simple REx opcode %d\",\n OP(scan));\n#endif\n\t\tcase SANY:\n\t\t if (flags & SCF_DO_STCLASS_OR) /* Allow everything */\n\t\t\tssc_match_all_cp(data->start_class);\n\t\t break;\n\n\t\tcase REG_ANY:\n {\n SV* REG_ANY_invlist = _new_invlist(2);\n REG_ANY_invlist = add_cp_to_invlist(REG_ANY_invlist,\n '\\n');\n if (flags & SCF_DO_STCLASS_OR) {\n ssc_union(data->start_class,\n REG_ANY_invlist,\n TRUE /* TRUE => invert, hence all but \\n\n */\n );\n }\n else if (flags & SCF_DO_STCLASS_AND) {\n ssc_intersection(data->start_class,\n REG_ANY_invlist,\n TRUE /* TRUE => invert */\n );\n ssc_clear_locale(data->start_class);\n }\n SvREFCNT_dec_NN(REG_ANY_invlist);\n\t\t }\n\t\t break;\n\n case ANYOFD:\n case ANYOFL:\n case ANYOFPOSIXL:\n case ANYOFH:\n case ANYOF:\n\t\t if (flags & SCF_DO_STCLASS_AND)\n\t\t\tssc_and(pRExC_state, data->start_class,\n (regnode_charclass *) scan);\n\t\t else\n\t\t\tssc_or(pRExC_state, data->start_class,\n (regnode_charclass *) scan);\n\t\t break;\n\n case NANYOFM:\n case ANYOFM:\n {\n SV* cp_list = get_ANYOFM_contents(scan);\n\n if (flags & SCF_DO_STCLASS_OR) {\n ssc_union(data->start_class, cp_list, invert);\n }\n else if (flags & SCF_DO_STCLASS_AND) {\n ssc_intersection(data->start_class, cp_list, invert);\n }\n\n SvREFCNT_dec_NN(cp_list);\n break;\n }\n\n\t\tcase NPOSIXL:\n invert = 1;\n /* FALLTHROUGH */\n\n\t\tcase POSIXL:\n namedclass = classnum_to_namedclass(FLAGS(scan)) + invert;\n if (flags & SCF_DO_STCLASS_AND) {\n bool was_there = cBOOL(\n ANYOF_POSIXL_TEST(data->start_class,\n namedclass));\n ANYOF_POSIXL_ZERO(data->start_class);\n if (was_there) { /* Do an AND */\n ANYOF_POSIXL_SET(data->start_class, namedclass);\n }\n /* No individual code points can now match */\n data->start_class->invlist\n = sv_2mortal(_new_invlist(0));\n }\n else {\n int complement = namedclass + ((invert) ? -1 : 1);\n\n assert(flags & SCF_DO_STCLASS_OR);\n\n /* If the complement of this class was already there,\n * the result is that they match all code points,\n * (\\d + \\D == everything). Remove the classes from\n * future consideration. Locale is not relevant in\n * this case */\n if (ANYOF_POSIXL_TEST(data->start_class, complement)) {\n ssc_match_all_cp(data->start_class);\n ANYOF_POSIXL_CLEAR(data->start_class, namedclass);\n ANYOF_POSIXL_CLEAR(data->start_class, complement);\n }\n else { /* The usual case; just add this class to the\n existing set */\n ANYOF_POSIXL_SET(data->start_class, namedclass);\n }\n }\n break;\n\n case NPOSIXA: /* For these, we always know the exact set of\n what's matched */\n invert = 1;\n /* FALLTHROUGH */\n\t\tcase POSIXA:\n my_invlist = invlist_clone(PL_Posix_ptrs[FLAGS(scan)], NULL);\n goto join_posix_and_ascii;\n\n\t\tcase NPOSIXD:\n\t\tcase NPOSIXU:\n invert = 1;\n /* FALLTHROUGH */\n\t\tcase POSIXD:\n\t\tcase POSIXU:\n my_invlist = invlist_clone(PL_XPosix_ptrs[FLAGS(scan)], NULL);\n\n /* NPOSIXD matches all upper Latin1 code points unless the\n * target string being matched is UTF-8, which is\n * unknowable until match time. Since we are going to\n * invert, we want to get rid of all of them so that the\n * inversion will match all */\n if (OP(scan) == NPOSIXD) {\n _invlist_subtract(my_invlist, PL_UpperLatin1,\n &my_invlist);\n }\n\n join_posix_and_ascii:\n\n if (flags & SCF_DO_STCLASS_AND) {\n ssc_intersection(data->start_class, my_invlist, invert);\n ssc_clear_locale(data->start_class);\n }\n else {\n assert(flags & SCF_DO_STCLASS_OR);\n ssc_union(data->start_class, my_invlist, invert);\n }\n SvREFCNT_dec(my_invlist);\n\t\t}\n\t\tif (flags & SCF_DO_STCLASS_OR)\n\t\t ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);\n\t\tflags &= ~SCF_DO_STCLASS;\n\t }\n\t}\n\telse if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {\n\t data->flags |= (OP(scan) == MEOL\n\t\t\t ? SF_BEFORE_MEOL\n\t\t\t : SF_BEFORE_SEOL);\n scan_commit(pRExC_state, data, minlenp, is_inf);\n\n\t}\n\telse if ( PL_regkind[OP(scan)] == BRANCHJ\n\t\t /* Lookbehind, or need to calculate parens/evals/stclass: */\n\t\t && (scan->flags || data || (flags & SCF_DO_STCLASS))\n\t\t && (OP(scan) == IFMATCH || OP(scan) == UNLESSM))\n {\n if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY\n || OP(scan) == UNLESSM )\n {\n /* Negative Lookahead/lookbehind\n In this case we can't do fixed string optimisation.\n */\n\n SSize_t deltanext, minnext, fake = 0;\n regnode *nscan;\n regnode_ssc intrnl;\n int f = 0;\n\n StructCopy(&zero_scan_data, &data_fake, scan_data_t);\n if (data) {\n data_fake.whilem_c = data->whilem_c;\n data_fake.last_closep = data->last_closep;\n\t\t}\n else\n data_fake.last_closep = &fake;\n\t\tdata_fake.pos_delta = delta;\n if ( flags & SCF_DO_STCLASS && !scan->flags\n && OP(scan) == IFMATCH ) { /* Lookahead */\n ssc_init(pRExC_state, &intrnl);\n data_fake.start_class = &intrnl;\n f |= SCF_DO_STCLASS_AND;\n\t\t}\n if (flags & SCF_WHILEM_VISITED_POS)\n f |= SCF_WHILEM_VISITED_POS;\n next = regnext(scan);\n nscan = NEXTOPER(NEXTOPER(scan));\n\n /* recurse study_chunk() for lookahead body */\n minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,\n last, &data_fake, stopparen,\n recursed_depth, NULL, f, depth+1);\n if (scan->flags) {\n if ( deltanext < 0\n || deltanext > (I32) U8_MAX\n || minnext > (I32)U8_MAX\n || minnext + deltanext > (I32)U8_MAX)\n {\n\t\t\tFAIL2(\"Lookbehind longer than %\" UVuf \" not implemented\",\n (UV)U8_MAX);\n }\n\n /* The 'next_off' field has been repurposed to count the\n * additional starting positions to try beyond the initial\n * one. (This leaves it at 0 for non-variable length\n * matches to avoid breakage for those not using this\n * extension) */\n if (deltanext) {\n scan->next_off = deltanext;\n ckWARNexperimental(RExC_parse,\n WARN_EXPERIMENTAL__VLB,\n \"Variable length lookbehind is experimental\");\n }\n scan->flags = (U8)minnext + deltanext;\n }\n if (data) {\n if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))\n pars++;\n if (data_fake.flags & SF_HAS_EVAL)\n data->flags |= SF_HAS_EVAL;\n data->whilem_c = data_fake.whilem_c;\n }\n if (f & SCF_DO_STCLASS_AND) {\n\t\t if (flags & SCF_DO_STCLASS_OR) {\n\t\t\t/* OR before, AND after: ideally we would recurse with\n\t\t\t * data_fake to get the AND applied by study of the\n\t\t\t * remainder of the pattern, and then derecurse;\n\t\t\t * *** HACK *** for now just treat as \"no information\".\n\t\t\t * See [perl #56690].\n\t\t\t */\n\t\t\tssc_init(pRExC_state, data->start_class);\n\t\t } else {\n /* AND before and after: combine and continue. These\n * assertions are zero-length, so can match an EMPTY\n * string */\n\t\t\tssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);\n ANYOF_FLAGS(data->start_class)\n |= SSC_MATCHES_EMPTY_STRING;\n\t\t }\n }\n\t }\n#if PERL_ENABLE_POSITIVE_ASSERTION_STUDY\n else {\n /* Positive Lookahead/lookbehind\n In this case we can do fixed string optimisation,\n but we must be careful about it. Note in the case of\n lookbehind the positions will be offset by the minimum\n length of the pattern, something we won't know about\n until after the recurse.\n */\n SSize_t deltanext, fake = 0;\n regnode *nscan;\n regnode_ssc intrnl;\n int f = 0;\n /* We use SAVEFREEPV so that when the full compile\n is finished perl will clean up the allocated\n minlens when it's all done. This way we don't\n have to worry about freeing them when we know\n they wont be used, which would be a pain.\n */\n SSize_t *minnextp;\n Newx( minnextp, 1, SSize_t );\n SAVEFREEPV(minnextp);\n\n if (data) {\n StructCopy(data, &data_fake, scan_data_t);\n if ((flags & SCF_DO_SUBSTR) && data->last_found) {\n f |= SCF_DO_SUBSTR;\n if (scan->flags)\n scan_commit(pRExC_state, &data_fake, minlenp, is_inf);\n data_fake.last_found=newSVsv(data->last_found);\n }\n }\n else\n data_fake.last_closep = &fake;\n data_fake.flags = 0;\n data_fake.substrs[0].flags = 0;\n data_fake.substrs[1].flags = 0;\n\t\tdata_fake.pos_delta = delta;\n if (is_inf)\n\t data_fake.flags |= SF_IS_INF;\n if ( flags & SCF_DO_STCLASS && !scan->flags\n && OP(scan) == IFMATCH ) { /* Lookahead */\n ssc_init(pRExC_state, &intrnl);\n data_fake.start_class = &intrnl;\n f |= SCF_DO_STCLASS_AND;\n }\n if (flags & SCF_WHILEM_VISITED_POS)\n f |= SCF_WHILEM_VISITED_POS;\n next = regnext(scan);\n nscan = NEXTOPER(NEXTOPER(scan));\n\n /* positive lookahead study_chunk() recursion */\n *minnextp = study_chunk(pRExC_state, &nscan, minnextp,\n &deltanext, last, &data_fake,\n stopparen, recursed_depth, NULL,\n f, depth+1);\n if (scan->flags) {\n assert(0); /* This code has never been tested since this\n is normally not compiled */\n if ( deltanext < 0\n || deltanext > (I32) U8_MAX\n || *minnextp > (I32)U8_MAX\n || *minnextp + deltanext > (I32)U8_MAX)\n {\n\t\t\tFAIL2(\"Lookbehind longer than %\" UVuf \" not implemented\",\n (UV)U8_MAX);\n }\n\n if (deltanext) {\n scan->next_off = deltanext;\n }\n scan->flags = (U8)*minnextp + deltanext;\n }\n\n *minnextp += min;\n\n if (f & SCF_DO_STCLASS_AND) {\n ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);\n ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING;\n }\n if (data) {\n if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))\n pars++;\n if (data_fake.flags & SF_HAS_EVAL)\n data->flags |= SF_HAS_EVAL;\n data->whilem_c = data_fake.whilem_c;\n if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {\n int i;\n if (RExC_rx->minlen<*minnextp)\n RExC_rx->minlen=*minnextp;\n scan_commit(pRExC_state, &data_fake, minnextp, is_inf);\n SvREFCNT_dec_NN(data_fake.last_found);\n\n for (i = 0; i < 2; i++) {\n if (data_fake.substrs[i].minlenp != minlenp) {\n data->substrs[i].min_offset =\n data_fake.substrs[i].min_offset;\n data->substrs[i].max_offset =\n data_fake.substrs[i].max_offset;\n data->substrs[i].minlenp =\n data_fake.substrs[i].minlenp;\n data->substrs[i].lookbehind += scan->flags;\n }\n }\n }\n }\n\t }\n#endif\n\t}\n\n\telse if (OP(scan) == OPEN) {\n\t if (stopparen != (I32)ARG(scan))\n\t pars++;\n\t}\n\telse if (OP(scan) == CLOSE) {\n\t if (stopparen == (I32)ARG(scan)) {\n\t break;\n\t }\n\t if ((I32)ARG(scan) == is_par) {\n\t\tnext = regnext(scan);\n\n\t\tif ( next && (OP(next) != WHILEM) && next < last)\n\t\t is_par = 0;\t\t/* Disable optimization */\n\t }\n\t if (data)\n\t\t*(data->last_closep) = ARG(scan);\n\t}\n\telse if (OP(scan) == EVAL) {\n\t\tif (data)\n\t\t data->flags |= SF_HAS_EVAL;\n\t}\n\telse if ( PL_regkind[OP(scan)] == ENDLIKE ) {\n\t if (flags & SCF_DO_SUBSTR) {\n scan_commit(pRExC_state, data, minlenp, is_inf);\n\t\tflags &= ~SCF_DO_SUBSTR;\n\t }\n\t if (data && OP(scan)==ACCEPT) {\n\t data->flags |= SCF_SEEN_ACCEPT;\n\t if (stopmin > min)\n\t stopmin = min;\n\t }\n\t}\n\telse if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */\n\t{\n\t\tif (flags & SCF_DO_SUBSTR) {\n scan_commit(pRExC_state, data, minlenp, is_inf);\n\t\t data->cur_is_floating = 1; /* float */\n\t\t}\n\t\tis_inf = is_inf_internal = 1;\n\t\tif (flags & SCF_DO_STCLASS_OR) /* Allow everything */\n\t\t ssc_anything(data->start_class);\n\t\tflags &= ~SCF_DO_STCLASS;\n\t}\n\telse if (OP(scan) == GPOS) {\n if (!(RExC_rx->intflags & PREGf_GPOS_FLOAT) &&\n\t !(delta || is_inf || (data && data->pos_delta)))\n\t {\n if (!(RExC_rx->intflags & PREGf_ANCH) && (flags & SCF_DO_SUBSTR))\n RExC_rx->intflags |= PREGf_ANCH_GPOS;\n\t if (RExC_rx->gofs < (STRLEN)min)\n\t\t RExC_rx->gofs = min;\n } else {\n RExC_rx->intflags |= PREGf_GPOS_FLOAT;\n RExC_rx->gofs = 0;\n }\n\t}\n#ifdef TRIE_STUDY_OPT\n#ifdef FULL_TRIE_STUDY\n else if (PL_regkind[OP(scan)] == TRIE) {\n /* NOTE - There is similar code to this block above for handling\n BRANCH nodes on the initial study. If you change stuff here\n check there too. */\n regnode *trie_node= scan;\n regnode *tail= regnext(scan);\n reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];\n SSize_t max1 = 0, min1 = SSize_t_MAX;\n regnode_ssc accum;\n\n if (flags & SCF_DO_SUBSTR) { /* XXXX Add !SUSPEND? */\n /* Cannot merge strings after this. */\n scan_commit(pRExC_state, data, minlenp, is_inf);\n }\n if (flags & SCF_DO_STCLASS)\n ssc_init_zero(pRExC_state, &accum);\n\n if (!trie->jump) {\n min1= trie->minlen;\n max1= trie->maxlen;\n } else {\n const regnode *nextbranch= NULL;\n U32 word;\n\n for ( word=1 ; word <= trie->wordcount ; word++)\n {\n SSize_t deltanext=0, minnext=0, f = 0, fake;\n regnode_ssc this_class;\n\n StructCopy(&zero_scan_data, &data_fake, scan_data_t);\n if (data) {\n data_fake.whilem_c = data->whilem_c;\n data_fake.last_closep = data->last_closep;\n }\n else\n data_fake.last_closep = &fake;\n\t\t data_fake.pos_delta = delta;\n if (flags & SCF_DO_STCLASS) {\n ssc_init(pRExC_state, &this_class);\n data_fake.start_class = &this_class;\n f = SCF_DO_STCLASS_AND;\n }\n if (flags & SCF_WHILEM_VISITED_POS)\n f |= SCF_WHILEM_VISITED_POS;\n\n if (trie->jump[word]) {\n if (!nextbranch)\n nextbranch = trie_node + trie->jump[0];\n scan= trie_node + trie->jump[word];\n /* We go from the jump point to the branch that follows\n it. Note this means we need the vestigal unused\n branches even though they arent otherwise used. */\n /* optimise study_chunk() for TRIE */\n minnext = study_chunk(pRExC_state, &scan, minlenp,\n &deltanext, (regnode *)nextbranch, &data_fake,\n stopparen, recursed_depth, NULL, f, depth+1);\n }\n if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)\n nextbranch= regnext((regnode*)nextbranch);\n\n if (min1 > (SSize_t)(minnext + trie->minlen))\n min1 = minnext + trie->minlen;\n if (deltanext == SSize_t_MAX) {\n is_inf = is_inf_internal = 1;\n max1 = SSize_t_MAX;\n } else if (max1 < (SSize_t)(minnext + deltanext + trie->maxlen))\n max1 = minnext + deltanext + trie->maxlen;\n\n if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))\n pars++;\n if (data_fake.flags & SCF_SEEN_ACCEPT) {\n if ( stopmin > min + min1)\n\t stopmin = min + min1;\n\t flags &= ~SCF_DO_SUBSTR;\n\t if (data)\n\t data->flags |= SCF_SEEN_ACCEPT;\n\t }\n if (data) {\n if (data_fake.flags & SF_HAS_EVAL)\n data->flags |= SF_HAS_EVAL;\n data->whilem_c = data_fake.whilem_c;\n }\n if (flags & SCF_DO_STCLASS)\n ssc_or(pRExC_state, &accum, (regnode_charclass *) &this_class);\n }\n }\n if (flags & SCF_DO_SUBSTR) {\n data->pos_min += min1;\n data->pos_delta += max1 - min1;\n if (max1 != min1 || is_inf)\n data->cur_is_floating = 1; /* float */\n }\n min += min1;\n if (delta != SSize_t_MAX) {\n if (SSize_t_MAX - (max1 - min1) >= delta)\n delta += max1 - min1;\n else\n delta = SSize_t_MAX;\n }\n if (flags & SCF_DO_STCLASS_OR) {\n ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &accum);\n if (min1) {\n ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);\n flags &= ~SCF_DO_STCLASS;\n }\n }\n else if (flags & SCF_DO_STCLASS_AND) {\n if (min1) {\n ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);\n flags &= ~SCF_DO_STCLASS;\n }\n else {\n /* Switch to OR mode: cache the old value of\n * data->start_class */\n\t\t INIT_AND_WITHP;\n StructCopy(data->start_class, and_withp, regnode_ssc);\n flags &= ~SCF_DO_STCLASS_AND;\n StructCopy(&accum, data->start_class, regnode_ssc);\n flags |= SCF_DO_STCLASS_OR;\n }\n }\n scan= tail;\n continue;\n }\n#else\n\telse if (PL_regkind[OP(scan)] == TRIE) {\n\t reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];\n\t U8*bang=NULL;\n\n\t min += trie->minlen;\n\t delta += (trie->maxlen - trie->minlen);\n\t flags &= ~SCF_DO_STCLASS; /* xxx */\n if (flags & SCF_DO_SUBSTR) {\n /* Cannot expect anything... */\n scan_commit(pRExC_state, data, minlenp, is_inf);\n \t data->pos_min += trie->minlen;\n \t data->pos_delta += (trie->maxlen - trie->minlen);\n\t\tif (trie->maxlen != trie->minlen)\n\t\t data->cur_is_floating = 1; /* float */\n \t }\n \t if (trie->jump) /* no more substrings -- for now /grr*/\n flags &= ~SCF_DO_SUBSTR;\n\t}\n#endif /* old or new */\n#endif /* TRIE_STUDY_OPT */\n\n\t/* Else: zero-length, ignore. */\n\tscan = regnext(scan);\n }\n\n finish:\n if (frame) {\n /* we need to unwind recursion. */\n depth = depth - 1;\n\n DEBUG_STUDYDATA(\"frame-end\", data, depth, is_inf);\n DEBUG_PEEP(\"fend\", scan, depth, flags);\n\n /* restore previous context */\n last = frame->last_regnode;\n scan = frame->next_regnode;\n stopparen = frame->stopparen;\n recursed_depth = frame->prev_recursed_depth;\n\n RExC_frame_last = frame->prev_frame;\n frame = frame->this_prev_frame;\n goto fake_study_recurse;\n }\n\n assert(!frame);\n DEBUG_STUDYDATA(\"pre-fin\", data, depth, is_inf);\n\n *scanp = scan;\n *deltap = is_inf_internal ? SSize_t_MAX : delta;\n\n if (flags & SCF_DO_SUBSTR && is_inf)\n\tdata->pos_delta = SSize_t_MAX - data->pos_min;\n if (is_par > (I32)U8_MAX)\n\tis_par = 0;\n if (is_par && pars==1 && data) {\n\tdata->flags |= SF_IN_PAR;\n\tdata->flags &= ~SF_HAS_PAR;\n }\n else if (pars && data) {\n\tdata->flags |= SF_HAS_PAR;\n\tdata->flags &= ~SF_IN_PAR;\n }\n if (flags & SCF_DO_STCLASS_OR)\n\tssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);\n if (flags & SCF_TRIE_RESTUDY)\n data->flags |= \tSCF_TRIE_RESTUDY;\n\n DEBUG_STUDYDATA(\"post-fin\", data, depth, is_inf);\n\n {\n SSize_t final_minlen= min < stopmin ? min : stopmin;\n\n if (!(RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)) {\n if (final_minlen > SSize_t_MAX - delta)\n RExC_maxlen = SSize_t_MAX;\n else if (RExC_maxlen < final_minlen + delta)\n RExC_maxlen = final_minlen + delta;\n }\n return final_minlen;\n }\n NOT_REACHED; /* NOTREACHED */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'study_chunk: avoid mutating regexp program within GOSUB\n\ngh16947 and gh17743: studying GOSUB may restudy in an inner call\n(via a mix of recursion and enframing) something that an outer call\nis in the middle of looking at. Let the outer frame deal with it.\n\n(CVE-2020-12723)\n\n(cherry picked from commit c4033e740bd18d9fbe3456a9db2ec2053cdc5271)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: exif_mnote_data_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\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-416', 'CWE-908'], 'message': 'Ensure the MakerNote data pointers are initialized with NULL.\n\nThis ensures that an uninitialized pointer isn't dereferenced later in\nthe case where the number of components (and therefore size) is 0.\n\nThis fixes the second issue reported at\nhttps://sourceforge.net/p/libexif/bugs/125/\n\nCVE-2020-13113'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: verify_peer_certificate (GTlsConnectionBase *tls,\n GTlsCertificate *peer_certificate)\n{\n GTlsConnectionBaseClass *tls_class = G_TLS_CONNECTION_BASE_GET_CLASS (tls);\n GSocketConnectable *peer_identity;\n GTlsDatabase *database;\n GTlsCertificateFlags errors;\n gboolean is_client;\n\n is_client = G_IS_TLS_CLIENT_CONNECTION (tls);\n\n if (!is_client)\n peer_identity = NULL;\n else if (!g_tls_connection_base_is_dtls (tls))\n peer_identity = g_tls_client_connection_get_server_identity (G_TLS_CLIENT_CONNECTION (tls));\n else\n peer_identity = g_dtls_client_connection_get_server_identity (G_DTLS_CLIENT_CONNECTION (tls));\n\n errors = 0;\n\n database = g_tls_connection_get_database (G_TLS_CONNECTION (tls));\n if (!database)\n {\n errors |= G_TLS_CERTIFICATE_UNKNOWN_CA;\n errors |= g_tls_certificate_verify (peer_certificate, peer_identity, NULL);\n }\n else\n {\n GError *error = NULL;\n\n errors |= g_tls_database_verify_chain (database, peer_certificate,\n is_client ?\n G_TLS_DATABASE_PURPOSE_AUTHENTICATE_SERVER :\n G_TLS_DATABASE_PURPOSE_AUTHENTICATE_CLIENT,\n peer_identity,\n g_tls_connection_get_interaction (G_TLS_CONNECTION (tls)),\n G_TLS_DATABASE_VERIFY_NONE,\n NULL, &error);\n if (error)\n {\n g_warning (\"failure verifying certificate chain: %s\",\n error->message);\n g_assert (errors != 0);\n g_clear_error (&error);\n }\n }\n\n if (tls_class->verify_peer_certificate)\n errors |= tls_class->verify_peer_certificate (tls, peer_certificate, errors);\n\n return errors;\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: check_restricted(void)\n{\n if (restricted)\n {\n\temsg(_(\"E145: Shell commands not allowed in rvim\"));\n\treturn TRUE;\n }\n return FALSE;\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: BOOL nego_read_request(rdpNego* nego, wStream* s)\n{\n\tBYTE li;\n\tBYTE type;\n\tUINT16 length;\n\n\tif (!tpkt_read_header(s, &length))\n\t\treturn FALSE;\n\n\tif (!tpdu_read_connection_request(s, &li, length))\n\t\treturn FALSE;\n\n\tif (li != Stream_GetRemainingLength(s) + 6)\n\t{\n\t\tWLog_ERR(TAG, \"Incorrect TPDU length indicator.\");\n\t\treturn FALSE;\n\t}\n\n\tif (!nego_read_request_token_or_cookie(nego, s))\n\t{\n\t\tWLog_ERR(TAG, \"Failed to parse routing token or cookie.\");\n\t\treturn FALSE;\n\t}\n\n\tif (Stream_GetRemainingLength(s) >= 8)\n\t{\n\t\t/* rdpNegData (optional) */\n\t\tStream_Read_UINT8(s, type); /* Type */\n\n\t\tif (type != TYPE_RDP_NEG_REQ)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"Incorrect negotiation request type %\" PRIu8 \"\", type);\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tnego_process_negotiation_request(nego, s);\n\t}\n\n\treturn tpkt_ensure_stream_consumed(s, length);\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 serial_process_irp_write(SERIAL_DEVICE* serial, IRP* irp)\n{\n\tUINT32 Length;\n\tUINT64 Offset;\n\tDWORD nbWritten = 0;\n\n\tif (Stream_GetRemainingLength(irp->input) < 32)\n\t\treturn ERROR_INVALID_DATA;\n\n\tStream_Read_UINT32(irp->input, Length); /* Length (4 bytes) */\n\tStream_Read_UINT64(irp->input, Offset); /* Offset (8 bytes) */\n\tStream_Seek(irp->input, 20); /* Padding (20 bytes) */\n\t/* MS-RDPESP 3.2.5.1.5: The Offset field is ignored\n\t * assert(Offset == 0);\n\t *\n\t * Using a serial printer, noticed though this field could be\n\t * set.\n\t */\n\tWLog_Print(serial->log, WLOG_DEBUG, \"writing %\" PRIu32 \" bytes to %s\", Length,\n\t serial->device.name);\n\n\t/* FIXME: CommWriteFile to be replaced by WriteFile */\n\tif (CommWriteFile(serial->hComm, Stream_Pointer(irp->input), Length, &nbWritten, NULL))\n\t{\n\t\tirp->IoStatus = STATUS_SUCCESS;\n\t}\n\telse\n\t{\n\t\tWLog_Print(serial->log, WLOG_DEBUG,\n\t\t \"write failure to %s, nbWritten=%\" PRIu32 \", last-error: 0x%08\" PRIX32 \"\",\n\t\t serial->device.name, nbWritten, GetLastError());\n\t\tirp->IoStatus = _GetLastErrorToIoStatus(serial);\n\t}\n\n\tWLog_Print(serial->log, WLOG_DEBUG, \"%\" PRIu32 \" bytes written to %s\", nbWritten,\n\t serial->device.name);\n\tStream_Write_UINT32(irp->output, nbWritten); /* Length (4 bytes) */\n\tStream_Write_UINT8(irp->output, 0); /* Padding (1 byte) */\n\treturn CHANNEL_RC_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed oob read in irp_write and similar'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TEST_P(QuicHttpIntegrationTest, StopAcceptingConnectionsWhenOverloaded) {\n initialize();\n fake_upstreams_[0]->set_allow_unexpected_disconnects(true);\n\n // Put envoy in overloaded state and check that it doesn't accept the new client connection.\n updateResource(0.9);\n test_server_->waitForGaugeEq(\"overload.envoy.overload_actions.stop_accepting_connections.active\",\n 1);\n codec_client_ = makeRawHttpConnection(makeClientConnection((lookupPort(\"http\"))));\n EXPECT_TRUE(codec_client_->disconnected());\n\n // Reduce load a little to allow the connection to be accepted connection.\n updateResource(0.8);\n test_server_->waitForGaugeEq(\"overload.envoy.overload_actions.stop_accepting_connections.active\",\n 0);\n codec_client_ = makeHttpConnection(makeClientConnection((lookupPort(\"http\"))));\n auto response = codec_client_->makeHeaderOnlyRequest(default_request_headers_);\n waitForNextUpstreamRequest(0);\n // Send response headers, but hold response body for now.\n upstream_request_->encodeHeaders(default_response_headers_, /*end_stream=*/false);\n\n updateResource(0.95);\n test_server_->waitForGaugeEq(\"overload.envoy.overload_actions.stop_accepting_requests.active\", 1);\n // Existing request should be able to finish.\n upstream_request_->encodeData(10, true);\n response->waitForEndStream();\n EXPECT_TRUE(response->complete());\n EXPECT_EQ(\"200\", response->headers().getStatusValue());\n\n // New request should be rejected.\n auto response2 = codec_client_->makeHeaderOnlyRequest(default_request_headers_);\n response2->waitForEndStream();\n EXPECT_EQ(\"503\", response2->headers().getStatusValue());\n EXPECT_EQ(\"envoy overloaded\", response2->body());\n codec_client_->close();\n\n EXPECT_TRUE(makeRawHttpConnection(makeClientConnection((lookupPort(\"http\"))))->disconnected());\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, ResponseDataFlood) {\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 int frame_count = 0;\n Buffer::OwnedImpl buffer;\n ON_CALL(server_connection_, write(_, _))\n .WillByDefault(Invoke([&buffer, &frame_count](Buffer::Instance& frame, bool) {\n ++frame_count;\n buffer.move(frame);\n }));\n\n TestResponseHeaderMapImpl response_headers{{\":status\", \"200\"}};\n response_encoder_->encodeHeaders(response_headers, false);\n // Account for the single HEADERS frame above\n for (uint32_t i = 0; i < CommonUtility::OptionsLimits::DEFAULT_MAX_OUTBOUND_FRAMES; ++i) {\n Buffer::OwnedImpl data(\"0\");\n EXPECT_NO_THROW(response_encoder_->encodeData(data, false));\n }\n // Presently flood mitigation is done only when processing downstream data\n // So we need to send stream from downstream client to trigger mitigation\n EXPECT_EQ(0, nghttp2_submit_ping(client_->session(), NGHTTP2_FLAG_NONE, nullptr));\n EXPECT_THROW(client_->sendPendingFrames(), ServerCodecError);\n\n EXPECT_EQ(frame_count, CommonUtility::OptionsLimits::DEFAULT_MAX_OUTBOUND_FRAMES + 1);\n EXPECT_EQ(1, stats_store_.counter(\"http2.outbound_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: ConnectionImpl::~ConnectionImpl() { nghttp2_session_del(session_); } ; 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 Http2UpstreamIntegrationTest::manySimultaneousRequests(uint32_t request_bytes, uint32_t) {\n TestRandomGenerator rand;\n const uint32_t num_requests = 50;\n std::vector encoders;\n std::vector responses;\n std::vector response_bytes;\n autonomous_upstream_ = true;\n initialize();\n\n codec_client_ = makeHttpConnection(lookupPort(\"http\"));\n for (uint32_t i = 0; i < num_requests; ++i) {\n response_bytes.push_back(rand.random() % (1024 * 2));\n auto headers = Http::TestRequestHeaderMapImpl{\n {\":method\", \"POST\"},\n {\":path\", \"/test/long/url\"},\n {\":scheme\", \"http\"},\n {\":authority\", \"host\"},\n {AutonomousStream::RESPONSE_SIZE_BYTES, std::to_string(response_bytes[i])},\n {AutonomousStream::EXPECT_REQUEST_SIZE_BYTES, std::to_string(request_bytes)}};\n if (i % 2 == 0) {\n headers.addCopy(AutonomousStream::RESET_AFTER_REQUEST, \"yes\");\n }\n auto encoder_decoder = codec_client_->startRequest(headers);\n encoders.push_back(&encoder_decoder.first);\n responses.push_back(std::move(encoder_decoder.second));\n codec_client_->sendData(*encoders[i], request_bytes, true);\n }\n\n for (uint32_t i = 0; i < num_requests; ++i) {\n responses[i]->waitForEndStream();\n if (i % 2 != 0) {\n EXPECT_TRUE(responses[i]->complete());\n EXPECT_EQ(\"200\", responses[i]->headers().getStatusValue());\n EXPECT_EQ(response_bytes[i], responses[i]->body().length());\n } else {\n // Upstream stream reset.\n EXPECT_EQ(\"503\", responses[i]->headers().getStatusValue());\n }\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: void ServerConnectionImpl::onUrl(const char* data, size_t length) {\n if (active_request_.has_value()) {\n active_request_.value().request_url_.append(data, length);\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: TEST_P(ClusterMemoryTestRunner, MemoryLargeClusterSizeWithFakeSymbolTable) {\n symbol_table_creator_test_peer_.setUseFakeSymbolTables(true);\n\n // A unique instance of ClusterMemoryTest allows for multiple runs of Envoy with\n // differing configuration. This is necessary for measuring the memory consumption\n // between the different instances within the same test.\n const size_t m100 = ClusterMemoryTestHelper::computeMemoryDelta(1, 0, 101, 0, true);\n const size_t m_per_cluster = (m100) / 100;\n\n // Note: if you are increasing this golden value because you are adding a\n // stat, please confirm that this will be generally useful to most Envoy\n // users. Otherwise you are adding to the per-cluster memory overhead, which\n // will be significant for Envoy installations that are massively\n // multi-tenant.\n //\n // History of golden values:\n //\n // Date PR Bytes Per Cluster Notes\n // exact upper-bound\n // ---------- ----- ----------------- -----\n // 2019/03/20 6329 59015 Initial version\n // 2019/04/12 6477 59576 Implementing Endpoint lease...\n // 2019/04/23 6659 59512 Reintroduce dispatcher stats...\n // 2019/04/24 6161 49415 Pack tags and tag extracted names\n // 2019/05/07 6794 49957 Stats for excluded hosts in cluster\n // 2019/04/27 6733 50213 Use SymbolTable API for HTTP codes\n // 2019/05/31 6866 50157 libstdc++ upgrade in CI\n // 2019/06/03 7199 49393 absl update\n // 2019/06/06 7208 49650 make memory targets approximate\n // 2019/06/17 7243 49412 49700 macros for exact/upper-bound memory checks\n // 2019/06/29 7364 45685 46000 combine 2 levels of stat ref-counting into 1\n // 2019/06/30 7428 42742 43000 remove stats multiple inheritance, inline HeapStatData\n // 2019/07/06 7477 42742 43000 fork gauge representation to drop pending_increment_\n // 2019/07/15 7555 42806 43000 static link libstdc++ in tests\n // 2019/07/24 7503 43030 44000 add upstream filters to clusters\n // 2019/08/13 7877 42838 44000 skip EdfScheduler creation if all host weights equal\n // 2019/09/02 8118 42830 43000 Share symbol-tables in cluster/host stats.\n // 2019/09/16 8100 42894 43000 Add transport socket matcher in cluster.\n // 2019/09/25 8226 43022 44000 dns: enable dns failure refresh rate configuration\n // 2019/09/30 8354 43310 44000 Implement transport socket match.\n // 2019/10/17 8537 43308 44000 add new enum value HTTP3\n // 2019/10/17 8484 43340 44000 stats: add unit support to histogram\n // 2019/11/01 8859 43563 44000 build: switch to libc++ by default\n // 2019/11/15 9040 43371 44000 build: update protobuf to 3.10.1\n // 2019/11/15 9031 43403 44000 upstream: track whether cluster is local\n // 2019/12/10 8779 42919 43500 use var-length coding for name length\n // 2020/01/07 9069 43413 44000 upstream: Implement retry concurrency budgets\n // 2020/01/07 9564 43445 44000 use RefcountPtr for CentralCache.\n // 2020/01/09 8889 43509 44000 api: add UpstreamHttpProtocolOptions message\n // 2020/01/09 9227 43637 44000 router: per-cluster histograms w/ timeout budget\n // 2020/01/12 9633 43797 44104 config: support recovery of original message when\n // upgrading.\n // 2020/02/13 10042 43797 44136 Metadata: Metadata are shared across different\n // clusters and hosts.\n // 2020/03/16 9964 44085 44600 http2: support custom SETTINGS parameters.\n // 2020/03/24 10501 44261 44600 upstream: upstream_rq_retry_limit_exceeded.\n // 2020/04/02 10624 43356 44000 Use 100 clusters rather than 1000 to avoid timeouts\n // 2020/04/07 10661 43349 44000 fix clang tidy on master\n // 2020/04/23 10531 44169 44600 http: max stream duration upstream support.\n // 2020/05/05 10908 44233 44600 router: add InternalRedirectPolicy and predicate\n // 2020/05/13 10531 44425 44600 Refactor resource manager\n // 2020/05/20 11223 44491 44600 Add primary clusters tracking to cluster manager.\n // 2020/06/10 11561 44491 44811 Make upstreams pluggable\n\n // Note: when adjusting this value: EXPECT_MEMORY_EQ is active only in CI\n // 'release' builds, where we control the platform and tool-chain. So you\n // will need to find the correct value only after failing CI and looking\n // at the logs.\n //\n // On a local clang8/libstdc++/linux flow, the memory usage was observed in\n // June 2019 to be 64 bytes higher than it is in CI/release. Your mileage may\n // vary.\n //\n // If you encounter a failure here, please see\n // https://github.com/envoyproxy/envoy/blob/master/source/docs/stats.md#stats-memory-tests\n // for details on how to fix.\n EXPECT_MEMORY_EQ(m_per_cluster, 44491);\n EXPECT_MEMORY_LE(m_per_cluster, 46000); // Round up to allow platform variations.\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'listener: Add configurable accepted connection limits (#153)\n\nAdd support for per-listener limits on accepted connections.\n\nSigned-off-by: Tony Allen '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void ListenerImpl::listenCallback(evconnlistener*, evutil_socket_t fd, sockaddr* remote_addr,\n int remote_addr_len, void* arg) {\n ListenerImpl* listener = static_cast(arg);\n\n // Wrap raw socket fd in IoHandle.\n IoHandlePtr io_handle = SocketInterfaceSingleton::get().socket(fd);\n\n // Get the local address from the new socket if the listener is listening on IP ANY\n // (e.g., 0.0.0.0 for IPv4) (local_address_ is nullptr in this case).\n const Address::InstanceConstSharedPtr& local_address =\n listener->local_address_ ? listener->local_address_ : io_handle->localAddress();\n\n // The accept() call that filled in remote_addr doesn't fill in more than the sa_family field\n // for Unix domain sockets; apparently there isn't a mechanism in the kernel to get the\n // `sockaddr_un` associated with the client socket when starting from the server socket.\n // We work around this by using our own name for the socket in this case.\n // Pass the 'v6only' parameter as true if the local_address is an IPv6 address. This has no effect\n // if the socket is a v4 socket, but for v6 sockets this will create an IPv4 remote address if an\n // IPv4 local_address was created from an IPv6 mapped IPv4 address.\n const Address::InstanceConstSharedPtr& remote_address =\n (remote_addr->sa_family == AF_UNIX)\n ? io_handle->peerAddress()\n : Address::addressFromSockAddr(*reinterpret_cast(remote_addr),\n remote_addr_len,\n local_address->ip()->version() == Address::IpVersion::v6);\n listener->cb_.onAccept(\n std::make_unique(std::move(io_handle), local_address, remote_address));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'overload: Runtime configurable global connection limits (#147)\n\nSigned-off-by: Tony Allen '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ConnectionImpl::ConnectionImpl(Network::Connection& connection, CodecStats& stats,\n const envoy::config::core::v3::Http2ProtocolOptions& http2_options,\n const uint32_t max_headers_kb, const uint32_t max_headers_count)\n : stats_(stats), connection_(connection), max_headers_kb_(max_headers_kb),\n max_headers_count_(max_headers_count),\n per_stream_buffer_limit_(http2_options.initial_stream_window_size().value()),\n stream_error_on_invalid_http_messaging_(\n http2_options.stream_error_on_invalid_http_messaging()),\n flood_detected_(false), max_outbound_frames_(http2_options.max_outbound_frames().value()),\n frame_buffer_releasor_([this](const Buffer::OwnedBufferFragmentImpl* fragment) {\n releaseOutboundFrame(fragment);\n }),\n max_outbound_control_frames_(http2_options.max_outbound_control_frames().value()),\n control_frame_buffer_releasor_([this](const Buffer::OwnedBufferFragmentImpl* fragment) {\n releaseOutboundControlFrame(fragment);\n }),\n max_consecutive_inbound_frames_with_empty_payload_(\n http2_options.max_consecutive_inbound_frames_with_empty_payload().value()),\n max_inbound_priority_frames_per_stream_(\n http2_options.max_inbound_priority_frames_per_stream().value()),\n max_inbound_window_update_frames_per_data_frame_sent_(\n http2_options.max_inbound_window_update_frames_per_data_frame_sent().value()),\n dispatching_(false), raised_goaway_(false), pending_deferred_reset_(false) {} ; 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::coalesceOrAddSlice(SlicePtr&& other_slice) {\n const uint64_t slice_size = other_slice->dataSize();\n // The `other_slice` content can be coalesced into the existing slice IFF:\n // 1. The `other_slice` can be coalesced. Objects of type UnownedSlice can not be coalesced. See\n // comment in the UnownedSlice class definition;\n // 2. There are existing slices;\n // 3. The `other_slice` content length is under the CopyThreshold;\n // 4. There is enough unused space in the existing slice to accommodate the `other_slice` content.\n if (other_slice->canCoalesce() && !slices_.empty() && slice_size < CopyThreshold &&\n slices_.back()->reservableSize() >= slice_size) {\n // Copy content of the `other_slice`. The `move` methods which call this method effectively\n // drain the source buffer.\n addImpl(other_slice->data(), slice_size);\n } else {\n // Take ownership of the slice.\n slices_.emplace_back(std::move(other_slice));\n length_ += slice_size;\n }\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 MSUSB_PIPE_DESCRIPTOR** msusb_mspipes_read(wStream* s, UINT32 NumberOfPipes)\n{\n\tUINT32 pnum;\n\tMSUSB_PIPE_DESCRIPTOR** MsPipes;\n\n\tif (Stream_GetRemainingCapacity(s) < 12 * NumberOfPipes)\n\t\treturn NULL;\n\n\tMsPipes = (MSUSB_PIPE_DESCRIPTOR**)calloc(NumberOfPipes, sizeof(MSUSB_PIPE_DESCRIPTOR*));\n\n\tif (!MsPipes)\n\t\treturn NULL;\n\n\tfor (pnum = 0; pnum < NumberOfPipes; pnum++)\n\t{\n\t\tMSUSB_PIPE_DESCRIPTOR* MsPipe = msusb_mspipe_new();\n\n\t\tif (!MsPipe)\n\t\t\tgoto out_error;\n\n\t\tStream_Read_UINT16(s, MsPipe->MaximumPacketSize);\n\t\tStream_Seek(s, 2);\n\t\tStream_Read_UINT32(s, MsPipe->MaximumTransferSize);\n\t\tStream_Read_UINT32(s, MsPipe->PipeFlags);\n\t\t/* Already set to zero by memset\n\t\t MsPipe->PipeHandle\t = 0;\n\t\t MsPipe->bEndpointAddress = 0;\n\t\t MsPipe->bInterval\t\t= 0;\n\t\t MsPipe->PipeType\t\t = 0;\n\t\t MsPipe->InitCompleted\t= 0;\n\t\t*/\n\t\tMsPipes[pnum] = MsPipe;\n\t}\n\n\treturn MsPipes;\nout_error:\n\n\tfor (pnum = 0; pnum < NumberOfPipes; pnum++)\n\t\tfree(MsPipes[pnum]);\n\n\tfree(MsPipes);\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fixed int overflow in msusb_mspipes_read\n\nThanks to hac425'" }, { "text": "[INST] Given the following code containing errors, provide Common 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(RoleParsingTest, BuildRoleBSON) {\n RoleGraph graph;\n RoleName roleA(\"roleA\", \"dbA\");\n RoleName roleB(\"roleB\", \"dbB\");\n RoleName roleC(\"roleC\", \"dbC\");\n ActionSet actions;\n actions.addAction(ActionType::find);\n actions.addAction(ActionType::insert);\n\n ASSERT_OK(graph.createRole(roleA));\n ASSERT_OK(graph.createRole(roleB));\n ASSERT_OK(graph.createRole(roleC));\n\n ASSERT_OK(graph.addRoleToRole(roleA, roleC));\n ASSERT_OK(graph.addRoleToRole(roleA, roleB));\n ASSERT_OK(graph.addRoleToRole(roleB, roleC));\n\n ASSERT_OK(graph.addPrivilegeToRole(\n roleA, Privilege(ResourcePattern::forAnyNormalResource(), actions)));\n ASSERT_OK(graph.addPrivilegeToRole(\n roleB, Privilege(ResourcePattern::forExactNamespace(NamespaceString(\"dbB.foo\")), actions)));\n ASSERT_OK(\n graph.addPrivilegeToRole(roleC, Privilege(ResourcePattern::forClusterResource(), actions)));\n ASSERT_OK(graph.recomputePrivilegeData());\n\n\n // Role A\n mutablebson::Document doc;\n ASSERT_OK(RoleGraph::getBSONForRole(&graph, roleA, doc.root()));\n BSONObj roleDoc = doc.getObject();\n\n ASSERT_EQUALS(\"dbA.roleA\", roleDoc[\"_id\"].String());\n ASSERT_EQUALS(\"roleA\", roleDoc[\"role\"].String());\n ASSERT_EQUALS(\"dbA\", roleDoc[\"db\"].String());\n\n std::vector privs = roleDoc[\"privileges\"].Array();\n ASSERT_EQUALS(1U, privs.size());\n ASSERT_EQUALS(\"\", privs[0].Obj()[\"resource\"].Obj()[\"db\"].String());\n ASSERT_EQUALS(\"\", privs[0].Obj()[\"resource\"].Obj()[\"collection\"].String());\n ASSERT(privs[0].Obj()[\"resource\"].Obj()[\"cluster\"].eoo());\n std::vector actionElements = privs[0].Obj()[\"actions\"].Array();\n ASSERT_EQUALS(2U, actionElements.size());\n ASSERT_EQUALS(\"find\", actionElements[0].String());\n ASSERT_EQUALS(\"insert\", actionElements[1].String());\n\n std::vector roles = roleDoc[\"roles\"].Array();\n ASSERT_EQUALS(2U, roles.size());\n ASSERT_EQUALS(\"roleC\", roles[0].Obj()[\"role\"].String());\n ASSERT_EQUALS(\"dbC\", roles[0].Obj()[\"db\"].String());\n ASSERT_EQUALS(\"roleB\", roles[1].Obj()[\"role\"].String());\n ASSERT_EQUALS(\"dbB\", roles[1].Obj()[\"db\"].String());\n\n // Role B\n doc.reset();\n ASSERT_OK(RoleGraph::getBSONForRole(&graph, roleB, doc.root()));\n roleDoc = doc.getObject();\n\n ASSERT_EQUALS(\"dbB.roleB\", roleDoc[\"_id\"].String());\n ASSERT_EQUALS(\"roleB\", roleDoc[\"role\"].String());\n ASSERT_EQUALS(\"dbB\", roleDoc[\"db\"].String());\n\n privs = roleDoc[\"privileges\"].Array();\n ASSERT_EQUALS(1U, privs.size());\n ASSERT_EQUALS(\"dbB\", privs[0].Obj()[\"resource\"].Obj()[\"db\"].String());\n ASSERT_EQUALS(\"foo\", privs[0].Obj()[\"resource\"].Obj()[\"collection\"].String());\n ASSERT(privs[0].Obj()[\"resource\"].Obj()[\"cluster\"].eoo());\n actionElements = privs[0].Obj()[\"actions\"].Array();\n ASSERT_EQUALS(2U, actionElements.size());\n ASSERT_EQUALS(\"find\", actionElements[0].String());\n ASSERT_EQUALS(\"insert\", actionElements[1].String());\n\n roles = roleDoc[\"roles\"].Array();\n ASSERT_EQUALS(1U, roles.size());\n ASSERT_EQUALS(\"roleC\", roles[0].Obj()[\"role\"].String());\n ASSERT_EQUALS(\"dbC\", roles[0].Obj()[\"db\"].String());\n\n // Role C\n doc.reset();\n ASSERT_OK(RoleGraph::getBSONForRole(&graph, roleC, doc.root()));\n roleDoc = doc.getObject();\n\n ASSERT_EQUALS(\"dbC.roleC\", roleDoc[\"_id\"].String());\n ASSERT_EQUALS(\"roleC\", roleDoc[\"role\"].String());\n ASSERT_EQUALS(\"dbC\", roleDoc[\"db\"].String());\n\n privs = roleDoc[\"privileges\"].Array();\n ASSERT_EQUALS(1U, privs.size());\n ASSERT(privs[0].Obj()[\"resource\"].Obj()[\"cluster\"].Bool());\n ASSERT(privs[0].Obj()[\"resource\"].Obj()[\"db\"].eoo());\n ASSERT(privs[0].Obj()[\"resource\"].Obj()[\"collection\"].eoo());\n actionElements = privs[0].Obj()[\"actions\"].Array();\n ASSERT_EQUALS(2U, actionElements.size());\n ASSERT_EQUALS(\"find\", actionElements[0].String());\n ASSERT_EQUALS(\"insert\", actionElements[1].String());\n\n roles = roleDoc[\"roles\"].Array();\n ASSERT_EQUALS(0U, roles.size());\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-863'], 'message': 'SERVER-45472 Ensure RoleGraph can serialize authentication restrictions to BSON'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool PackLinuxElf32::calls_crt1(Elf32_Rel const *rel, int sz)\n{\n if (!dynsym || !dynstr) {\n return false;\n }\n for (unsigned relnum= 0; 0 < sz; (sz -= sizeof(Elf32_Rel)), ++rel, ++relnum) {\n unsigned const symnum = get_te32(&rel->r_info) >> 8;\n char const *const symnam = get_dynsym_name(symnum, relnum);\n if (0==strcmp(symnam, \"__libc_start_main\") // glibc\n || 0==strcmp(symnam, \"__libc_init\") // Android\n || 0==strcmp(symnam, \"__uClibc_main\")\n || 0==strcmp(symnam, \"__uClibc_start_main\"))\n return true;\n }\n return false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-190'], 'message': 'Avoid bogus values in PT_DYNAMIC segment.\n\nDetect duplicate DT_*.\nDetect out-of-bounds hashtab and gashtab.\nDetect missing DT_REL, DT_RELA.\nDetect out-of-bounds d_val.\nhttps://github.com/upx/upx/issues/317\n\tmodified: p_lx_elf.cpp'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: vlv_copy_down_controls(TALLOC_CTX *mem_ctx, 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\tbreak;\n\t\t}\n\t\t/*\n\t\t * Do not re-use VLV, nor the server-sort, both are\n\t\t * already handled here.\n\t\t */\n\t\tif (strcmp(control->oid, LDB_CONTROL_VLV_REQ_OID) == 0 ||\n\t\t strcmp(control->oid, LDB_CONTROL_SERVER_SORT_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 nntp_open_connection(struct NntpAccountData *adata)\n{\n struct Connection *conn = adata->conn;\n char buf[256];\n int cap;\n bool posting = false, auth = true;\n\n if (adata->status == NNTP_OK)\n return 0;\n if (adata->status == NNTP_BYE)\n return -1;\n adata->status = NNTP_NONE;\n\n if (mutt_socket_open(conn) < 0)\n return -1;\n\n if (mutt_socket_readln(buf, sizeof(buf), conn) < 0)\n return nntp_connect_error(adata);\n\n if (mutt_str_startswith(buf, \"200\", CASE_MATCH))\n posting = true;\n else if (!mutt_str_startswith(buf, \"201\", CASE_MATCH))\n {\n mutt_socket_close(conn);\n mutt_str_remove_trailing_ws(buf);\n mutt_error(\"%s\", buf);\n return -1;\n }\n\n /* get initial capabilities */\n cap = nntp_capabilities(adata);\n if (cap < 0)\n return -1;\n\n /* tell news server to switch to mode reader if it isn't so */\n if (cap > 0)\n {\n if ((mutt_socket_send(conn, \"MODE READER\\r\\n\") < 0) ||\n (mutt_socket_readln(buf, sizeof(buf), conn) < 0))\n {\n return nntp_connect_error(adata);\n }\n\n if (mutt_str_startswith(buf, \"200\", CASE_MATCH))\n posting = true;\n else if (mutt_str_startswith(buf, \"201\", CASE_MATCH))\n posting = false;\n /* error if has capabilities, ignore result if no capabilities */\n else if (adata->hasCAPABILITIES)\n {\n mutt_socket_close(conn);\n mutt_error(_(\"Could not switch to reader mode\"));\n return -1;\n }\n\n /* recheck capabilities after MODE READER */\n if (adata->hasCAPABILITIES)\n {\n cap = nntp_capabilities(adata);\n if (cap < 0)\n return -1;\n }\n }\n\n mutt_message(_(\"Connected to %s. %s\"), conn->account.host,\n posting ? _(\"Posting is ok\") : _(\"Posting is NOT ok\"));\n mutt_sleep(1);\n\n#ifdef USE_SSL\n /* Attempt STARTTLS if available and desired. */\n if ((adata->use_tls != 1) && (adata->hasSTARTTLS || C_SslForceTls))\n {\n if (adata->use_tls == 0)\n {\n adata->use_tls =\n C_SslForceTls || query_quadoption(C_SslStarttls,\n _(\"Secure connection with TLS?\")) == MUTT_YES ?\n 2 :\n 1;\n }\n if (adata->use_tls == 2)\n {\n if ((mutt_socket_send(conn, \"STARTTLS\\r\\n\") < 0) ||\n (mutt_socket_readln(buf, sizeof(buf), conn) < 0))\n {\n return nntp_connect_error(adata);\n }\n if (!mutt_str_startswith(buf, \"382\", CASE_MATCH))\n {\n adata->use_tls = 0;\n mutt_error(\"STARTTLS: %s\", buf);\n }\n else if (mutt_ssl_starttls(conn))\n {\n adata->use_tls = 0;\n adata->status = NNTP_NONE;\n mutt_socket_close(adata->conn);\n mutt_error(_(\"Could not negotiate TLS connection\"));\n return -1;\n }\n else\n {\n /* recheck capabilities after STARTTLS */\n cap = nntp_capabilities(adata);\n if (cap < 0)\n return -1;\n }\n }\n }\n#endif\n\n /* authentication required? */\n if (conn->account.flags & MUTT_ACCT_USER)\n {\n if (!conn->account.user[0])\n auth = false;\n }\n else\n {\n if ((mutt_socket_send(conn, \"STAT\\r\\n\") < 0) ||\n (mutt_socket_readln(buf, sizeof(buf), conn) < 0))\n {\n return nntp_connect_error(adata);\n }\n if (!mutt_str_startswith(buf, \"480\", CASE_MATCH))\n auth = false;\n }\n\n /* authenticate */\n if (auth && (nntp_auth(adata) < 0))\n return -1;\n\n /* get final capabilities after authentication */\n if (adata->hasCAPABILITIES && (auth || (cap > 0)))\n {\n cap = nntp_capabilities(adata);\n if (cap < 0)\n return -1;\n if (cap > 0)\n {\n mutt_socket_close(conn);\n mutt_error(_(\"Could not switch to reader mode\"));\n return -1;\n }\n }\n\n /* attempt features */\n if (nntp_attempt_features(adata) < 0)\n return -1;\n\n adata->status = NNTP_OK;\n return 0;\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: init_usm(void)\n{\n struct snmp_secmod_def *def;\n char *type;\n\n DEBUGMSGTL((\"init_usm\", \"unit_usm: %\" NETSNMP_PRIo \"u %\" NETSNMP_PRIo \"u\\n\",\n usmNoPrivProtocol[0], usmNoPrivProtocol[1]));\n\n sc_init(); /* initalize scapi code */\n\n /*\n * register ourselves as a security service\n */\n def = SNMP_MALLOC_STRUCT(snmp_secmod_def);\n if (def == NULL)\n return;\n /*\n * XXX: def->init_sess_secmod move stuff from snmp_api.c\n */\n def->encode_reverse = usm_secmod_rgenerate_out_msg;\n def->encode_forward = usm_secmod_generate_out_msg;\n def->decode = usm_secmod_process_in_msg;\n def->pdu_free_state_ref = usm_free_usmStateReference;\n def->session_setup = usm_session_init;\n def->handle_report = usm_handle_report;\n def->probe_engineid = usm_discover_engineid;\n def->post_probe_engineid = usm_create_user_from_session_hook;\n if (register_sec_mod(USM_SEC_MODEL_NUMBER, \"usm\", def) != SNMPERR_SUCCESS) {\n SNMP_FREE(def);\n snmp_log(LOG_ERR, \"could not register usm sec mod\\n\");\n return;\n }\n\n snmp_register_callback(SNMP_CALLBACK_LIBRARY,\n SNMP_CALLBACK_POST_PREMIB_READ_CONFIG,\n init_usm_post_config, NULL);\n\n snmp_register_callback(SNMP_CALLBACK_LIBRARY,\n SNMP_CALLBACK_SHUTDOWN,\n deinit_usm_post_config, NULL);\n\n snmp_register_callback(SNMP_CALLBACK_LIBRARY,\n SNMP_CALLBACK_SHUTDOWN,\n free_engineID, NULL);\n\n register_config_handler(\"snmp\", \"defAuthType\", snmpv3_authtype_conf,\n NULL, \"MD5|SHA|SHA-512|SHA-384|SHA-256|SHA-224\");\n register_config_handler(\"snmp\", \"defPrivType\", snmpv3_privtype_conf,\n NULL,\n \"DES\"\n#ifdef HAVE_AES\n \"|AES|AES-128\"\n#ifdef NETSNMP_DRAFT_BLUMENTHAL_AES_04\n \"|AES-192|AES-256\"\n#endif /* NETSNMP_DRAFT_BLUMENTHAL_AES_04 */\n#else\n \" (AES support not available)\"\n#endif\n );\n\n /*\n * Free stuff at shutdown time\n */\n snmp_register_callback(SNMP_CALLBACK_LIBRARY,\n SNMP_CALLBACK_SHUTDOWN,\n free_enginetime_on_shutdown, NULL);\n\n\n type = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_APPTYPE);\n\n register_config_handler(type, \"userSetAuthPass\", usm_set_password,\n NULL, NULL);\n register_config_handler(type, \"userSetPrivPass\", usm_set_password,\n NULL, NULL);\n register_config_handler(type, \"userSetAuthKey\", usm_set_password, NULL,\n NULL);\n register_config_handler(type, \"userSetPrivKey\", usm_set_password, NULL,\n NULL);\n register_config_handler(type, \"userSetAuthLocalKey\", usm_set_password,\n NULL, NULL);\n register_config_handler(type, \"userSetPrivLocalKey\", usm_set_password,\n NULL, NULL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'libsnmp, USM: Introduce a reference count in struct usmStateReference\n\nThis patch fixes https://sourceforge.net/p/net-snmp/bugs/2956/.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: webSocketsHandshake(rfbClientPtr cl, char *scheme)\n{\n char *buf, *response, *line;\n int n, linestart = 0, len = 0, llen, base64 = TRUE;\n char prefix[5], trailer[17];\n char *path = NULL, *host = NULL, *origin = NULL, *protocol = NULL;\n char *key1 = NULL, *key2 = NULL, *key3 = NULL;\n char *sec_ws_origin = NULL;\n char *sec_ws_key = NULL;\n char sec_ws_version = 0;\n ws_ctx_t *wsctx = NULL;\n\n buf = (char *) malloc(WEBSOCKETS_MAX_HANDSHAKE_LEN);\n if (!buf) {\n rfbLogPerror(\"webSocketsHandshake: malloc\");\n return FALSE;\n }\n response = (char *) malloc(WEBSOCKETS_MAX_HANDSHAKE_LEN);\n if (!response) {\n free(buf);\n rfbLogPerror(\"webSocketsHandshake: malloc\");\n return FALSE;\n }\n\n while (len < WEBSOCKETS_MAX_HANDSHAKE_LEN-1) {\n if ((n = rfbReadExactTimeout(cl, buf+len, 1,\n WEBSOCKETS_CLIENT_SEND_WAIT_MS)) <= 0) {\n if ((n < 0) && (errno == ETIMEDOUT)) {\n break;\n }\n if (n == 0)\n rfbLog(\"webSocketsHandshake: client gone\\n\");\n else\n rfbLogPerror(\"webSocketsHandshake: read\");\n free(response);\n free(buf);\n return FALSE;\n }\n\n len += 1;\n llen = len - linestart;\n if (((llen >= 2)) && (buf[len-1] == '\\n')) {\n line = buf+linestart;\n if ((llen == 2) && (strncmp(\"\\r\\n\", line, 2) == 0)) {\n if (key1 && key2) {\n if ((n = rfbReadExact(cl, buf+len, 8)) <= 0) {\n if ((n < 0) && (errno == ETIMEDOUT)) {\n break;\n }\n if (n == 0)\n rfbLog(\"webSocketsHandshake: client gone\\n\");\n else\n rfbLogPerror(\"webSocketsHandshake: read\");\n free(response);\n free(buf);\n return FALSE;\n }\n rfbLog(\"Got key3\\n\");\n key3 = buf+len;\n len += 8;\n } else {\n buf[len] = '\\0';\n }\n break;\n } else if ((llen >= 16) && ((strncmp(\"GET \", line, min(llen,4))) == 0)) {\n /* 16 = 4 (\"GET \") + 1 (\"/.*\") + 11 (\" HTTP/1.1\\r\\n\") */\n path = line+4;\n buf[len-11] = '\\0'; /* Trim trailing \" HTTP/1.1\\r\\n\" */\n cl->wspath = strdup(path);\n /* rfbLog(\"Got path: %s\\n\", path); */\n } else if ((strncasecmp(\"host: \", line, min(llen,6))) == 0) {\n host = line+6;\n buf[len-2] = '\\0';\n /* rfbLog(\"Got host: %s\\n\", host); */\n } else if ((strncasecmp(\"origin: \", line, min(llen,8))) == 0) {\n origin = line+8;\n buf[len-2] = '\\0';\n /* rfbLog(\"Got origin: %s\\n\", origin); */\n } else if ((strncasecmp(\"sec-websocket-key1: \", line, min(llen,20))) == 0) {\n key1 = line+20;\n buf[len-2] = '\\0';\n /* rfbLog(\"Got key1: %s\\n\", key1); */\n } else if ((strncasecmp(\"sec-websocket-key2: \", line, min(llen,20))) == 0) {\n key2 = line+20;\n buf[len-2] = '\\0';\n /* rfbLog(\"Got key2: %s\\n\", key2); */\n /* HyBI */\n\n\t } else if ((strncasecmp(\"sec-websocket-protocol: \", line, min(llen,24))) == 0) {\n protocol = line+24;\n buf[len-2] = '\\0';\n rfbLog(\"Got protocol: %s\\n\", protocol);\n } else if ((strncasecmp(\"sec-websocket-origin: \", line, min(llen,22))) == 0) {\n\t\tsec_ws_origin = line+22;\n buf[len-2] = '\\0';\n } else if ((strncasecmp(\"sec-websocket-key: \", line, min(llen,19))) == 0) {\n\t\tsec_ws_key = line+19;\n buf[len-2] = '\\0';\n } else if ((strncasecmp(\"sec-websocket-version: \", line, min(llen,23))) == 0) {\n\t\tsec_ws_version = strtol(line+23, NULL, 10);\n buf[len-2] = '\\0';\n\t }\n\n linestart = len;\n }\n }\n\n if (!(path && host && (origin || sec_ws_origin))) {\n rfbErr(\"webSocketsHandshake: incomplete client handshake\\n\");\n free(response);\n free(buf);\n return FALSE;\n }\n\n if ((protocol) && (strstr(protocol, \"binary\"))) {\n if (! sec_ws_version) {\n rfbErr(\"webSocketsHandshake: 'binary' protocol not supported with Hixie\\n\");\n free(response);\n free(buf);\n return FALSE;\n }\n rfbLog(\" - webSocketsHandshake: using binary/raw encoding\\n\");\n base64 = FALSE;\n protocol = \"binary\";\n } else {\n rfbLog(\" - webSocketsHandshake: using base64 encoding\\n\");\n base64 = TRUE;\n if ((protocol) && (strstr(protocol, \"base64\"))) {\n protocol = \"base64\";\n } else {\n protocol = \"\";\n }\n }\n\n /*\n * Generate the WebSockets server response based on the the headers sent\n * by the client.\n */\n\n if (sec_ws_version) {\n\tchar accept[B64LEN(SHA1_HASH_SIZE) + 1];\n\trfbLog(\" - WebSockets client version hybi-%02d\\n\", sec_ws_version);\n\twebSocketsGenSha1Key(accept, sizeof(accept), sec_ws_key);\n if(strlen(protocol) > 0)\n len = snprintf(response, WEBSOCKETS_MAX_HANDSHAKE_LEN,\n\t SERVER_HANDSHAKE_HYBI, accept, protocol);\n else\n len = snprintf(response, WEBSOCKETS_MAX_HANDSHAKE_LEN,\n SERVER_HANDSHAKE_HYBI_NO_PROTOCOL, accept);\n } else {\n\t/* older hixie handshake, this could be removed if\n\t * a final standard is established */\n\tif (!(key1 && key2 && key3)) {\n\t rfbLog(\" - WebSockets client version hixie-75\\n\");\n\t prefix[0] = '\\0';\n\t trailer[0] = '\\0';\n\t} else {\n\t rfbLog(\" - WebSockets client version hixie-76\\n\");\n\t snprintf(prefix, 5, \"Sec-\");\n\t webSocketsGenMd5(trailer, key1, key2, key3);\n\t}\n\tlen = snprintf(response, WEBSOCKETS_MAX_HANDSHAKE_LEN,\n\t\t SERVER_HANDSHAKE_HIXIE, prefix, origin, prefix, scheme,\n\t\t host, path, prefix, protocol, trailer);\n }\n\n if (rfbWriteExact(cl, response, len) < 0) {\n rfbErr(\"webSocketsHandshake: failed sending WebSockets response\\n\");\n free(response);\n free(buf);\n return FALSE;\n }\n /* rfbLog(\"webSocketsHandshake: %s\\n\", response); */\n free(response);\n free(buf);\n\n\n wsctx = calloc(1, sizeof(ws_ctx_t));\n if (sec_ws_version) {\n\twsctx->version = WEBSOCKETS_VERSION_HYBI;\n\twsctx->encode = webSocketsEncodeHybi;\n\twsctx->decode = webSocketsDecodeHybi;\n } else {\n\twsctx->version = WEBSOCKETS_VERSION_HIXIE;\n\twsctx->encode = webSocketsEncodeHixie;\n\twsctx->decode = webSocketsDecodeHixie;\n }\n wsctx->base64 = base64;\n cl->wsctx = (wsCtx *)wsctx;\n return TRUE;\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 void xgmac_enet_send(XgmacState *s)\n{\n struct desc bd;\n int frame_size;\n int len;\n uint8_t frame[8192];\n uint8_t *ptr;\n\n ptr = frame;\n frame_size = 0;\n while (1) {\n xgmac_read_desc(s, &bd, 0);\n if ((bd.ctl_stat & 0x80000000) == 0) {\n /* Run out of descriptors to transmit. */\n break;\n }\n len = (bd.buffer1_size & 0xfff) + (bd.buffer2_size & 0xfff);\n\n if ((bd.buffer1_size & 0xfff) > 2048) {\n DEBUGF_BRK(\"qemu:%s:ERROR...ERROR...ERROR... -- \"\n \"xgmac buffer 1 len on send > 2048 (0x%x)\\n\",\n __func__, bd.buffer1_size & 0xfff);\n }\n if ((bd.buffer2_size & 0xfff) != 0) {\n DEBUGF_BRK(\"qemu:%s:ERROR...ERROR...ERROR... -- \"\n \"xgmac buffer 2 len on send != 0 (0x%x)\\n\",\n __func__, bd.buffer2_size & 0xfff);\n }\n if (len >= sizeof(frame)) {\n DEBUGF_BRK(\"qemu:%s: buffer overflow %d read into %zu \"\n \"buffer\\n\" , __func__, len, sizeof(frame));\n DEBUGF_BRK(\"qemu:%s: buffer1.size=%d; buffer2.size=%d\\n\",\n __func__, bd.buffer1_size, bd.buffer2_size);\n }\n\n cpu_physical_memory_read(bd.buffer1_addr, ptr, len);\n ptr += len;\n frame_size += len;\n if (bd.ctl_stat & 0x20000000) {\n /* Last buffer in frame. */\n qemu_send_packet(qemu_get_queue(s->nic), frame, len);\n ptr = frame;\n frame_size = 0;\n s->regs[DMA_STATUS] |= DMA_STATUS_TI | DMA_STATUS_NIS;\n }\n bd.ctl_stat &= ~0x80000000;\n /* Write back the modified descriptor. */\n xgmac_write_desc(s, &bd, 0);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'hw/net/xgmac: Fix buffer overflow in xgmac_enet_send()\n\nA buffer overflow issue was reported by Mr. Ziming Zhang, CC'd here. It\noccurs while sending an Ethernet frame due to missing break statements\nand improper checking of the buffer size.\n\nReported-by: Ziming Zhang \nSigned-off-by: Mauro Matteo Cascella \nReviewed-by: Peter Maydell \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 INLINE BOOL update_read_brush(wStream* s, rdpBrush* brush, BYTE fieldFlags)\n{\n\tif (fieldFlags & ORDER_FIELD_01)\n\t{\n\t\tif (Stream_GetRemainingLength(s) < 1)\n\t\t\treturn FALSE;\n\n\t\tStream_Read_UINT8(s, brush->x);\n\t}\n\n\tif (fieldFlags & ORDER_FIELD_02)\n\t{\n\t\tif (Stream_GetRemainingLength(s) < 1)\n\t\t\treturn FALSE;\n\n\t\tStream_Read_UINT8(s, brush->y);\n\t}\n\n\tif (fieldFlags & ORDER_FIELD_03)\n\t{\n\t\tif (Stream_GetRemainingLength(s) < 1)\n\t\t\treturn FALSE;\n\n\t\tStream_Read_UINT8(s, brush->style);\n\t}\n\n\tif (fieldFlags & ORDER_FIELD_04)\n\t{\n\t\tif (Stream_GetRemainingLength(s) < 1)\n\t\t\treturn FALSE;\n\n\t\tStream_Read_UINT8(s, brush->hatch);\n\t}\n\n\tif (brush->style & CACHED_BRUSH)\n\t{\n\t\tbrush->index = brush->hatch;\n\t\tbrush->bpp = BMF_BPP[brush->style & 0x07];\n\n\t\tif (brush->bpp == 0)\n\t\t\tbrush->bpp = 1;\n\t}\n\n\tif (fieldFlags & ORDER_FIELD_05)\n\t{\n\t\tif (Stream_GetRemainingLength(s) < 7)\n\t\t\treturn FALSE;\n\n\t\tbrush->data = (BYTE*)brush->p8x8;\n\t\tStream_Read_UINT8(s, brush->data[7]);\n\t\tStream_Read_UINT8(s, brush->data[6]);\n\t\tStream_Read_UINT8(s, brush->data[5]);\n\t\tStream_Read_UINT8(s, brush->data[4]);\n\t\tStream_Read_UINT8(s, brush->data[3]);\n\t\tStream_Read_UINT8(s, brush->data[2]);\n\t\tStream_Read_UINT8(s, brush->data[1]);\n\t\tbrush->data[0] = brush->hatch;\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 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 trio_pointer_t trio_register TRIO_ARGS2((callback, name), trio_callback_t callback,\n TRIO_CONST char* name)\n{\n\ttrio_userdef_t* def;\n\ttrio_userdef_t* prev = NULL;\n\n\tif (callback == NULL)\n\t\treturn NULL;\n\n\tif (name)\n\t{\n\t\t/* Handle built-in namespaces */\n\t\tif (name[0] == ':')\n\t\t{\n\t\t\tif (trio_equal(name, \":enter\"))\n\t\t\t{\n\t\t\t\tinternalEnterCriticalRegion = callback;\n\t\t\t}\n\t\t\telse if (trio_equal(name, \":leave\"))\n\t\t\t{\n\t\t\t\tinternalLeaveCriticalRegion = callback;\n\t\t\t}\n\t\t\treturn NULL;\n\t\t}\n\n\t\t/* Bail out if namespace is too long */\n\t\tif (trio_length(name) >= MAX_USER_NAME)\n\t\t\treturn NULL;\n\n\t\t/* Bail out if namespace already is registered */\n\t\tdef = TrioFindNamespace(name, &prev);\n\t\tif (def)\n\t\t\treturn NULL;\n\t}\n\n\tdef = (trio_userdef_t*)TRIO_MALLOC(sizeof(trio_userdef_t));\n\tif (def)\n\t{\n\t\tif (internalEnterCriticalRegion)\n\t\t\t(void)internalEnterCriticalRegion(NULL);\n\n\t\tif (name)\n\t\t{\n\t\t\t/* Link into internal list */\n\t\t\tif (prev == NULL)\n\t\t\t\tinternalUserDef = def;\n\t\t\telse\n\t\t\t\tprev->next = def;\n\t\t}\n\t\t/* Initialize */\n\t\tdef->callback = callback;\n\t\tdef->name = (name == NULL) ? NULL : trio_duplicate(name);\n\t\tdef->next = NULL;\n\n\t\tif (internalLeaveCriticalRegion)\n\t\t\t(void)internalLeaveCriticalRegion(NULL);\n\t}\n\treturn (trio_pointer_t)def;\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 INLINE UINT16 ntlm_av_pair_get_id(const NTLM_AV_PAIR* pAvPair)\n{\n\tUINT16 AvId;\n\n\tData_Read_UINT16(&pAvPair->AvId, AvId);\n\n\treturn AvId;\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_SurfaceToSurface(RdpgfxClientContext* context,\n const RDPGFX_SURFACE_TO_SURFACE_PDU* surfaceToSurface)\n{\n\tUINT status = ERROR_INTERNAL_ERROR;\n\tUINT16 index;\n\tBOOL sameSurface;\n\tUINT32 nWidth, nHeight;\n\tconst RECTANGLE_16* rectSrc;\n\tRDPGFX_POINT16* destPt;\n\tRECTANGLE_16 invalidRect;\n\tgdiGfxSurface* surfaceSrc;\n\tgdiGfxSurface* surfaceDst;\n\trdpGdi* gdi = (rdpGdi*)context->custom;\n\tEnterCriticalSection(&context->mux);\n\trectSrc = &(surfaceToSurface->rectSrc);\n\tsurfaceSrc = (gdiGfxSurface*)context->GetSurfaceData(context, surfaceToSurface->surfaceIdSrc);\n\tsameSurface =\n\t (surfaceToSurface->surfaceIdSrc == surfaceToSurface->surfaceIdDest) ? TRUE : FALSE;\n\n\tif (!sameSurface)\n\t\tsurfaceDst =\n\t\t (gdiGfxSurface*)context->GetSurfaceData(context, surfaceToSurface->surfaceIdDest);\n\telse\n\t\tsurfaceDst = surfaceSrc;\n\n\tif (!surfaceSrc || !surfaceDst)\n\t\tgoto fail;\n\n\tnWidth = rectSrc->right - rectSrc->left;\n\tnHeight = rectSrc->bottom - rectSrc->top;\n\n\tfor (index = 0; index < surfaceToSurface->destPtsCount; index++)\n\t{\n\t\tdestPt = &surfaceToSurface->destPts[index];\n\n\t\tif (!freerdp_image_copy(surfaceDst->data, surfaceDst->format, surfaceDst->scanline,\n\t\t destPt->x, destPt->y, nWidth, nHeight, surfaceSrc->data,\n\t\t surfaceSrc->format, surfaceSrc->scanline, rectSrc->left,\n\t\t rectSrc->top, NULL, 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 + rectSrc->right;\n\t\tinvalidRect.bottom = destPt->y + rectSrc->bottom;\n\t\tregion16_union_rect(&surfaceDst->invalidRegion, &surfaceDst->invalidRegion, &invalidRect);\n\t\tstatus = IFCALLRESULT(CHANNEL_RC_OK, context->UpdateSurfaceArea, context,\n\t\t surfaceDst->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\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 luaT_adjustvarargs (lua_State *L, int nfixparams, CallInfo *ci,\n const Proto *p) {\n int i;\n int actual = cast_int(L->top - ci->func) - 1; /* number of arguments */\n int nextra = actual - nfixparams; /* number of extra arguments */\n ci->u.l.nextraargs = nextra;\n checkstackGC(L, p->maxstacksize + 1);\n /* copy function to the top of the stack */\n setobjs2s(L, L->top++, ci->func);\n /* move fixed parameters to the top of the stack */\n for (i = 1; i <= nfixparams; i++) {\n setobjs2s(L, L->top++, ci->func + i);\n setnilvalue(s2v(ci->func + i)); /* erase original parameter (for GC) */\n }\n ci->func += actual + 1;\n ci->top += actual + 1;\n lua_assert(L->top <= ci->top && ci->top <= L->stack_last);\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: rfbClientIteratorNext(rfbClientIteratorPtr i)\n{\n if(i->next == 0) {\n LOCK(rfbClientListMutex);\n i->next = i->screen->clientHead;\n UNLOCK(rfbClientListMutex);\n } else {\n rfbClientPtr cl = i->next;\n i->next = i->next->next;\n rfbDecrClientRef(cl);\n }\n\n#if defined(LIBVNCSERVER_HAVE_LIBPTHREAD) || defined(LIBVNCSERVER_HAVE_WIN32THREADS)\n if(!i->closedToo)\n while(i->next && i->next->sock<0)\n i->next = i->next->next;\n if(i->next)\n rfbIncrClientRef(i->next);\n#endif\n\n return i->next;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'libvncserver: add missing NULL pointer checks'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: LUA_API void lua_sethook (lua_State *L, lua_Hook func, int mask, int count) {\n if (func == NULL || mask == 0) { /* turn off hooks? */\n mask = 0;\n func = NULL;\n }\n if (isLua(L->ci))\n L->oldpc = L->ci->u.l.savedpc;\n L->hook = func;\n L->basehookcount = count;\n resethookcount(L);\n L->hookmask = cast_byte(mask);\n if (mask)\n settraps(L->ci); /* to trace inside 'luaV_execute' */\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: _XimAttributeToValue(\n Xic\t\t\t ic,\n XIMResourceList\t res,\n CARD16\t\t *data,\n INT16\t\t data_len,\n XPointer\t\t value,\n BITMASK32\t\t mode)\n{\n switch (res->resource_size) {\n case XimType_SeparatorOfNestedList:\n case XimType_NEST:\n\tbreak;\n\n case XimType_CARD8:\n case XimType_CARD16:\n case XimType_CARD32:\n case XimType_Window:\n case XimType_XIMHotKeyState:\n\t_XCopyToArg((XPointer)data, (XPointer *)&value, data_len);\n\tbreak;\n\n case XimType_STRING8:\n\t{\n\t char\t*str;\n\n\t if (!(value))\n\t\treturn False;\n\n\t if (!(str = Xmalloc(data_len + 1)))\n\t\treturn False;\n\n\t (void)memcpy(str, (char *)data, data_len);\n\t str[data_len] = '\\0';\n\n\t *((char **)value) = str;\n\t break;\n\t}\n\n case XimType_XIMStyles:\n\t{\n\t CARD16\t\t num = data[0];\n\t register CARD32\t*style_list = (CARD32 *)&data[2];\n\t XIMStyle\t\t*style;\n\t XIMStyles\t\t*rep;\n\t register int\t i;\n\t char\t\t*p;\n\t unsigned int alloc_len;\n\n\t if (!(value))\n\t\treturn False;\n\n\t if (num > (USHRT_MAX / sizeof(XIMStyle)))\n\t\treturn False;\n\t if ((sizeof(num) + (num * sizeof(XIMStyle))) > data_len)\n\t\treturn False;\n\t alloc_len = sizeof(XIMStyles) + sizeof(XIMStyle) * num;\n\t if (alloc_len < sizeof(XIMStyles))\n\t\treturn False;\n\t if (!(p = Xmalloc(alloc_len)))\n\t\treturn False;\n\n\t rep = (XIMStyles *)p;\n\t style = (XIMStyle *)(p + sizeof(XIMStyles));\n\n\t for (i = 0; i < num; i++)\n\t\tstyle[i] = (XIMStyle)style_list[i];\n\n\t rep->count_styles = (unsigned short)num;\n\t rep->supported_styles = style;\n\t *((XIMStyles **)value) = rep;\n\t break;\n\t}\n\n case XimType_XRectangle:\n\t{\n\t XRectangle\t*rep;\n\n\t if (!(value))\n\t\treturn False;\n\n\t if (!(rep = Xmalloc(sizeof(XRectangle))))\n\t\treturn False;\n\n\t rep->x = data[0];\n\t rep->y = data[1];\n\t rep->width = data[2];\n\t rep->height = data[3];\n\t *((XRectangle **)value) = rep;\n\t break;\n\t}\n\n case XimType_XPoint:\n\t{\n\t XPoint\t*rep;\n\n\t if (!(value))\n\t\treturn False;\n\n\t if (!(rep = Xmalloc(sizeof(XPoint))))\n\t\treturn False;\n\n\t rep->x = data[0];\n\t rep->y = data[1];\n\t *((XPoint **)value) = rep;\n\t break;\n\t}\n\n case XimType_XFontSet:\n\t{\n\t CARD16\t len = data[0];\n\t char\t*base_name;\n\t XFontSet\t rep = (XFontSet)NULL;\n\t char\t**missing_list = NULL;\n\t int\t\t missing_count;\n\t char\t*def_string;\n\n\t if (!(value))\n\t\treturn False;\n\t if (!ic)\n\t\treturn False;\n\t if (len > data_len)\n\t\treturn False;\n\t if (!(base_name = Xmalloc(len + 1)))\n\t\treturn False;\n\n\t (void)strncpy(base_name, (char *)&data[1], (size_t)len);\n\t base_name[len] = '\\0';\n\n\t if (mode & XIM_PREEDIT_ATTR) {\n\t\tif (!strcmp(base_name, ic->private.proto.preedit_font)) {\n\t\t rep = ic->core.preedit_attr.fontset;\n\t\t} else if (!ic->private.proto.preedit_font_length) {\n\t\t rep = XCreateFontSet(ic->core.im->core.display,\n\t\t\t\t\tbase_name, &missing_list,\n\t\t\t\t\t&missing_count, &def_string);\n\t\t}\n\t } else if (mode & XIM_STATUS_ATTR) {\n\t\tif (!strcmp(base_name, ic->private.proto.status_font)) {\n\t\t rep = ic->core.status_attr.fontset;\n\t\t} else if (!ic->private.proto.status_font_length) {\n\t\t rep = XCreateFontSet(ic->core.im->core.display,\n\t\t\t\t\tbase_name, &missing_list,\n\t\t\t\t\t&missing_count, &def_string);\n\t\t}\n\t }\n\n\t Xfree(base_name);\n\t Xfree(missing_list);\n\t *((XFontSet *)value) = rep;\n\t break;\n\t}\n\n case XimType_XIMHotKeyTriggers:\n\t{\n\t CARD32\t\t\t num = *((CARD32 *)data);\n\t register CARD32\t\t*key_list = (CARD32 *)&data[2];\n\t XIMHotKeyTrigger\t\t*key;\n\t XIMHotKeyTriggers\t\t*rep;\n\t register int\t\t i;\n\t char\t\t\t*p;\n\t unsigned int\t\t alloc_len;\n\n\t if (!(value))\n\t\treturn False;\n\n\t if (num > (UINT_MAX / sizeof(XIMHotKeyTrigger)))\n\t\treturn False;\n\t if ((sizeof(num) + (num * sizeof(XIMHotKeyTrigger))) > data_len)\n\t\treturn False;\n\t alloc_len = sizeof(XIMHotKeyTriggers)\n\t\t + sizeof(XIMHotKeyTrigger) * num;\n\t if (alloc_len < sizeof(XIMHotKeyTriggers))\n\t\treturn False;\n\t if (!(p = Xmalloc(alloc_len)))\n\t\treturn False;\n\n\t rep = (XIMHotKeyTriggers *)p;\n\t key = (XIMHotKeyTrigger *)(p + sizeof(XIMHotKeyTriggers));\n\n\t for (i = 0; i < num; i++, key_list += 3) {\n\t\tkey[i].keysym = (KeySym)key_list[0]; /* keysym */\n\t\tkey[i].modifier = (int)key_list[1]; /* modifier */\n\t\tkey[i].modifier_mask = (int)key_list[2]; /* modifier_mask */\n\t }\n\n\t rep->num_hot_key = (int)num;\n\t rep->key = key;\n\t *((XIMHotKeyTriggers **)value) = rep;\n\t break;\n\t}\n\n case XimType_XIMStringConversion:\n\t{\n\t break;\n\t}\n\n default:\n\treturn False;\n }\n return True;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Change the data_len parameter of _XimAttributeToValue() to CARD16\n\nIt's coming from a length in the protocol (unsigned) and passed\nto functions that expect unsigned int parameters (_XCopyToArg()\nand memcpy()).\n\nSigned-off-by: Matthieu Herrb \nReviewed-by: Todd Carson '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _XimGetAttributeID(\n Xim\t\t\t im,\n CARD16\t\t *buf)\n{\n unsigned int\t n;\n XIMResourceList\t res;\n char\t\t *names;\n int\t\t\t names_len;\n XPointer\t\t tmp;\n XIMValuesList\t *values_list;\n char\t\t**values;\n int\t\t\t values_len;\n register int\t i;\n INT16\t\t len;\n INT16\t\t min_len = sizeof(CARD16) /* sizeof attribute ID */\n\t\t\t\t + sizeof(CARD16) /* sizeof type of value */\n\t\t\t\t + sizeof(INT16); /* sizeof length of attr */\n /*\n * IM attribute ID\n */\n\n if (!(n = _XimCountNumberOfAttr(buf[0], &buf[1], &names_len)))\n\treturn False;\n\n if (!(res = Xcalloc(n, sizeof(XIMResource))))\n\treturn False;\n\n values_len = sizeof(XIMValuesList) + (sizeof(char **) * n) + names_len;\n if (!(tmp = Xcalloc(1, values_len))) {\n\tXfree(res);\n\treturn False;\n }\n\n values_list = (XIMValuesList *)tmp;\n values = (char **)((char *)tmp + sizeof(XIMValuesList));\n names = (char *)((char *)values + (sizeof(char **) * n));\n\n values_list->count_values = n;\n values_list->supported_values = values;\n\n buf++;\n for (i = 0; i < n; i++) {\n\tlen = buf[2];\n\t(void)memcpy(names, (char *)&buf[3], len);\n\tvalues[i] = names;\n\tnames[len] = '\\0';\n\tres[i].resource_name = names;\n\tres[i].resource_size = buf[1];\n\tres[i].id\t = buf[0];\n\tnames += (len + 1);\n\tlen += (min_len + XIM_PAD(len + 2));\n\tbuf = (CARD16 *)((char *)buf + len);\n }\n _XIMCompileResourceList(res, n);\n\n Xfree(im->core.im_resources);\n Xfree(im->core.im_values_list);\n\n im->core.im_resources = res;\n im->core.im_num_resources = n;\n im->core.im_values_list = values_list;\n\n /*\n * IC attribute ID\n */\n\n if (!(n = _XimCountNumberOfAttr(buf[0], &buf[2], &names_len)))\n\treturn False;\n\n if (!(res = Xcalloc(n, sizeof(XIMResource))))\n\treturn False;\n\n values_len = sizeof(XIMValuesList) + (sizeof(char **) * n) + names_len;\n if (!(tmp = Xcalloc(1, values_len))) {\n\tXfree(res);\n\treturn False;\n }\n\n values_list = (XIMValuesList *)tmp;\n values = (char **)((char *)tmp + sizeof(XIMValuesList));\n names = (char *)((char *)values + (sizeof(char **) * n));\n\n values_list->count_values = n;\n values_list->supported_values = values;\n\n buf += 2;\n for (i = 0; i < n; i++) {\n\tlen = buf[2];\n\t(void)memcpy(names, (char *)&buf[3], len);\n\tvalues[i] = names;\n\tnames[len] = '\\0';\n\tres[i].resource_name = names;\n\tres[i].resource_size = buf[1];\n\tres[i].id\t = buf[0];\n\tnames += (len + 1);\n\tlen += (min_len + XIM_PAD(len + 2));\n\tbuf = (CARD16 *)((char *)buf + len);\n }\n _XIMCompileResourceList(res, n);\n\n\n Xfree(im->core.ic_resources);\n Xfree(im->core.ic_values_list);\n\n im->core.ic_resources = res;\n im->core.ic_num_resources = n;\n im->core.ic_values_list = values_list;\n\n return True;\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: netsnmp_mibindex_lookup( const char *dirname )\n{\n int i;\n static char tmpbuf[300];\n\n for (i=0; i<_mibindex; i++) {\n if ( _mibindexes[i] &&\n strcmp( _mibindexes[i], dirname ) == 0) {\n snprintf(tmpbuf, sizeof(tmpbuf), \"%s/mib_indexes/%d\",\n get_persistent_directory(), i);\n tmpbuf[sizeof(tmpbuf)-1] = 0;\n DEBUGMSGTL((\"mibindex\", \"lookup: %s (%d) %s\\n\", dirname, i, tmpbuf ));\n return tmpbuf;\n }\n }\n DEBUGMSGTL((\"mibindex\", \"lookup: (none)\\n\"));\n return NULL;\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 void h2_push_diary_append(h2_push_diary *diary, h2_push_diary_entry *e)\n{\n h2_push_diary_entry *ne;\n \n if (diary->entries->nelts < diary->N) {\n /* append a new diary entry at the end */\n APR_ARRAY_PUSH(diary->entries, h2_push_diary_entry) = *e;\n ne = &APR_ARRAY_IDX(diary->entries, diary->entries->nelts-1, h2_push_diary_entry);\n }\n else {\n /* replace content with new digest. keeps memory usage constant once diary is full */\n ne = move_to_last(diary, 0);\n *ne = *e;\n }\n /* Intentional no APLOGNO */\n ap_log_perror(APLOG_MARK, GCSLOG_LEVEL, 0, diary->entries->pool,\n \"push_diary_append: %\"APR_UINT64_T_HEX_FMT, ne->hash);\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: SProcRecordRegisterClients(ClientPtr client)\n{\n REQUEST(xRecordRegisterClientsReq);\n int status;\n\n swaps(&stuff->length);\n REQUEST_AT_LEAST_SIZE(xRecordRegisterClientsReq);\n if ((status = SwapCreateRegister((void *) stuff)) != Success)\n return status;\n return ProcRecordRegisterClients(client);\n} /* SProcRecordRegisterClients */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-191'], 'message': 'Fix XRecordRegisterClients() Integer underflow\n\nCVE-2020-14362 ZDI-CAN-11574\n\nThis vulnerability was discovered by:\nJan-Niklas Sohn working with Trend Micro Zero Day Initiative\n\nSigned-off-by: Matthieu Herrb '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: pkcs11dh_fromdns(dst_key_t *key, isc_buffer_t *data) {\n\tpk11_object_t *dh = NULL;\n\tisc_region_t r;\n\tuint16_t plen, glen, plen_, glen_, publen;\n\tCK_BYTE *prime = NULL, *base = NULL, *pub = NULL;\n\tCK_ATTRIBUTE *attr;\n\tint special = 0;\n\tisc_result_t result;\n\n\tisc_buffer_remainingregion(data, &r);\n\tif (r.length == 0) {\n\t\tresult = ISC_R_SUCCESS;\n\t\tgoto cleanup;\n\t}\n\n\tdh = (pk11_object_t *) isc_mem_get(key->mctx, sizeof(*dh));\n\tif (dh == NULL) {\n\t\tresult = ISC_R_NOMEMORY;\n\t\tgoto cleanup;\n\t}\n\n\tmemset(dh, 0, sizeof(*dh));\n\tresult = DST_R_INVALIDPUBLICKEY;\n\n\t/*\n\t * Read the prime length. 1 & 2 are table entries, > 16 means a\n\t * prime follows, otherwise an error.\n\t */\n\tif (r.length < 2)\n\t\tgoto cleanup;\n\n\tplen = uint16_fromregion(&r);\n\tif (plen < 16 && plen != 1 && plen != 2)\n\t\tgoto cleanup;\n\n\tif (r.length < plen)\n\t\tgoto cleanup;\n\n\tplen_ = plen;\n\tif (plen == 1 || plen == 2) {\n\t\tif (plen == 1) {\n\t\t\tspecial = *r.base;\n\t\t\tisc_region_consume(&r, 1);\n\t\t} else {\n\t\t\tspecial = uint16_fromregion(&r);\n\t\t}\n\t\tswitch (special) {\n\t\t\tcase 1:\n\t\t\t\tprime = pk11_dh_bn768;\n\t\t\t\tplen_ = sizeof(pk11_dh_bn768);\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tprime = pk11_dh_bn1024;\n\t\t\t\tplen_ = sizeof(pk11_dh_bn1024);\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tprime = pk11_dh_bn1536;\n\t\t\t\tplen_ = sizeof(pk11_dh_bn1536);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tgoto cleanup;\n\t\t}\n\t}\n\telse {\n\t\tprime = r.base;\n\t\tisc_region_consume(&r, plen);\n\t}\n\n\t/*\n\t * Read the generator length. This should be 0 if the prime was\n\t * special, but it might not be. If it's 0 and the prime is not\n\t * special, we have a problem.\n\t */\n\tif (r.length < 2)\n\t\tgoto cleanup;\n\n\tglen = uint16_fromregion(&r);\n\tif (r.length < glen)\n\t\tgoto cleanup;\n\n\tglen_ = glen;\n\tif (special != 0) {\n\t\tif (glen == 0) {\n\t\t\tbase = pk11_dh_bn2;\n\t\t\tglen_ = sizeof(pk11_dh_bn2);\n\t\t}\n\t\telse {\n\t\t\tbase = r.base;\n\t\t\tif (!isc_safe_memequal(base, pk11_dh_bn2, glen))\n\t\t\t\tgoto cleanup;\n\t\t\tbase = pk11_dh_bn2;\n\t\t\tglen_ = sizeof(pk11_dh_bn2);\n\t\t}\n\t}\n\telse {\n\t\tif (glen == 0)\n\t\t\tgoto cleanup;\n\t\tbase = r.base;\n\t}\n\tisc_region_consume(&r, glen);\n\n\tif (r.length < 2)\n\t\tgoto cleanup;\n\n\tpublen = uint16_fromregion(&r);\n\tif (r.length < publen)\n\t\tgoto cleanup;\n\n\tpub = r.base;\n\tisc_region_consume(&r, publen);\n\n\tkey->key_size = pk11_numbits(prime, plen_);\n\n\tdh->repr = (CK_ATTRIBUTE *) isc_mem_get(key->mctx, sizeof(*attr) * 3);\n\tif (dh->repr == NULL)\n\t\tgoto nomemory;\n\tmemset(dh->repr, 0, sizeof(*attr) * 3);\n\tdh->attrcnt = 3;\n\n\tattr = dh->repr;\n\tattr[0].type = CKA_PRIME;\n\tattr[0].pValue = isc_mem_get(key->mctx, plen_);\n\tif (attr[0].pValue == NULL)\n\t\tgoto nomemory;\n\tmemmove(attr[0].pValue, prime, plen_);\n\tattr[0].ulValueLen = (CK_ULONG) plen_;\n\n\tattr[1].type = CKA_BASE;\n\tattr[1].pValue = isc_mem_get(key->mctx, glen_);\n\tif (attr[1].pValue == NULL)\n\t\tgoto nomemory;\n\tmemmove(attr[1].pValue, base, glen_);\n\tattr[1].ulValueLen = (CK_ULONG) glen_;\n\n\tattr[2].type = CKA_VALUE;\n\tattr[2].pValue = isc_mem_get(key->mctx, publen);\n\tif (attr[2].pValue == NULL)\n\t\tgoto nomemory;\n\tmemmove(attr[2].pValue, pub, publen);\n\tattr[2].ulValueLen = (CK_ULONG) publen;\n\n\tisc_buffer_forward(data, plen + glen + publen + 6);\n\n\tkey->keydata.pkey = dh;\n\n\treturn (ISC_R_SUCCESS);\n\n nomemory:\n\tfor (attr = pk11_attribute_first(dh);\n\t attr != NULL;\n\t attr = pk11_attribute_next(dh, attr))\n\t\tswitch (attr->type) {\n\t\tcase CKA_VALUE:\n\t\tcase CKA_PRIME:\n\t\tcase CKA_BASE:\n\t\t\tif (attr->pValue != NULL) {\n\t\t\t\tisc_safe_memwipe(attr->pValue,\n\t\t\t\t\t\t attr->ulValueLen);\n\t\t\t\tisc_mem_put(key->mctx,\n\t\t\t\t\t attr->pValue,\n\t\t\t\t\t attr->ulValueLen);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\tif (dh->repr != NULL) {\n\t\tisc_safe_memwipe(dh->repr, dh->attrcnt * sizeof(*attr));\n\t\tisc_mem_put(key->mctx, dh->repr, dh->attrcnt * sizeof(*attr));\n\t}\n\n\tresult = ISC_R_NOMEMORY;\n\n cleanup:\n\tif (dh != NULL) {\n\t\tisc_safe_memwipe(dh, sizeof(*dh));\n\t\tisc_mem_put(key->mctx, dh, sizeof(*dh));\n\t}\n\treturn (result);\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: tiffsep1_print_page(gx_device_printer * pdev, gp_file * file)\n{\n tiffsep1_device * const tfdev = (tiffsep1_device *)pdev;\n int num_std_colorants = tfdev->devn_params.num_std_colorant_names;\n int num_order = tfdev->devn_params.num_separation_order_names;\n int num_spot = tfdev->devn_params.separations.num_separations;\n int num_comp, comp_num, code = 0, code1 = 0;\n short map_comp_to_sep[GX_DEVICE_COLOR_MAX_COMPONENTS];\n char *name = NULL;\n int save_depth = pdev->color_info.depth;\n int save_numcomps = pdev->color_info.num_components;\n const char *fmt;\n gs_parsed_file_name_t parsed;\n int non_encodable_count = 0;\n\n if (tfdev->thresholds[0].dstart == NULL)\n return_error(gs_error_rangecheck);\n\n name = (char *)gs_alloc_bytes(pdev->memory, gp_file_name_sizeof, \"tiffsep1_print_page(name)\");\n if (!name)\n return_error(gs_error_VMerror);\n\n build_comp_to_sep_map((tiffsep_device *)tfdev, map_comp_to_sep);\n\n /*\n * Since different pages may have different spot colors, if this is for a\n * page after Page 1, we require that each output file is unique with a \"fmt\"\n * (i.e. %d) as part of the filename. We create individual separation files\n * for each page of the input.\n * Since the TIFF lib requires seeakable files, /dev/null or nul: are\n * not allowed (as they are with the psdcmyk devices).\n */\n code = gx_parse_output_file_name(&parsed, &fmt, tfdev->fname,\n strlen(tfdev->fname), pdev->memory);\n if (code < 0 || (fmt == NULL && tfdev->PageCount > 0)) {\n emprintf(tfdev->memory,\n \"\\nUse of the %%d format is required to output more than one page to tiffsep1.\\n\"\n \"See doc/Devices.htm#TIFF for details.\\n\\n\");\n code = gs_note_error(gs_error_ioerror);\n }\n /* If the output file is on disk and the name contains a page #, */\n /* then delete the previous file. */\n if (pdev->file != NULL && parsed.iodev == iodev_default(pdev->memory) && fmt) {\n long count1 = pdev->PageCount;\n char *compname = (char *)gs_alloc_bytes(pdev->memory, gp_file_name_sizeof, \"tiffsep1_print_page(compname)\");\n if (!compname) {\n code = gs_note_error(gs_error_VMerror);\n goto done;\n }\n\n gx_device_close_output_file((gx_device *)pdev, pdev->fname, pdev->file);\n pdev->file = NULL;\n\n while (*fmt != 'l' && *fmt != '%')\n --fmt;\n if (*fmt == 'l')\n gs_sprintf(compname, parsed.fname, count1);\n else\n gs_sprintf(compname, parsed.fname, (int)count1);\n parsed.iodev->procs.delete_file(parsed.iodev, compname);\n /* we always need an open printer (it will get deleted in tiffsep1_prn_close */\n code = gdev_prn_open_printer((gx_device *)pdev, 1);\n\n gs_free_object(pdev->memory, compname, \"tiffsep_print_page(compname)\");\n if (code < 0) {\n goto done;\n }\n }\n\n /* Set up the separation output files */\n num_comp = number_output_separations( tfdev->color_info.num_components,\n num_std_colorants, num_order, num_spot);\n for (comp_num = 0; comp_num < num_comp; comp_num++ ) {\n int sep_num = map_comp_to_sep[comp_num];\n\n code = create_separation_file_name((tiffsep_device *)tfdev, name,\n gp_file_name_sizeof, sep_num, true);\n if (code < 0) {\n goto done;\n }\n\n /* Open the separation file, if not already open */\n if (tfdev->sep_file[comp_num] == NULL) {\n code = gs_add_outputfile_control_path(tfdev->memory, name);\n if (code < 0) {\n goto done;\n }\n code = gx_device_open_output_file((gx_device *)pdev, name,\n true, true, &(tfdev->sep_file[comp_num]));\n if (code < 0) {\n goto done;\n }\n tfdev->tiff[comp_num] = tiff_from_filep(pdev, name,\n tfdev->sep_file[comp_num],\n tfdev->BigEndian, tfdev->UseBigTIFF);\n if (!tfdev->tiff[comp_num]) {\n code = gs_note_error(gs_error_ioerror);\n goto done;\n }\n }\n\n pdev->color_info.depth = 8; /* Create files for 8 bit gray */\n pdev->color_info.num_components = 1;\n code = tiff_set_fields_for_printer(pdev, tfdev->tiff[comp_num], 1, 0, tfdev->write_datetime);\n tiff_set_gray_fields(pdev, tfdev->tiff[comp_num], 1, tfdev->Compression, tfdev->MaxStripSize);\n pdev->color_info.depth = save_depth;\n pdev->color_info.num_components = save_numcomps;\n if (code < 0) {\n goto done;\n }\n\n } /* end initialization of separation files */\n\n\n { /* Get the expanded contone line, halftone and write out the dithered separations */\n byte *planes[GS_CLIENT_COLOR_MAX_COMPONENTS];\n int width = tfdev->width;\n int raster_plane = bitmap_raster(width * 8);\n int dithered_raster = ((7 + width) / 8) + ARCH_SIZEOF_LONG;\n int pixel, y;\n gs_get_bits_params_t params;\n gs_int_rect rect;\n /* the dithered_line is assumed to be 32-bit aligned by the alloc */\n uint32_t *dithered_line = (uint32_t *)gs_alloc_bytes(pdev->memory, dithered_raster,\n \"tiffsep1_print_page\");\n\n memset(planes, 0, sizeof(*planes) * GS_CLIENT_COLOR_MAX_COMPONENTS);\n\n /* Return planar data */\n params.options = (GB_RETURN_POINTER | GB_RETURN_COPY |\n GB_ALIGN_STANDARD | GB_OFFSET_0 | GB_RASTER_STANDARD |\n GB_PACKING_PLANAR | GB_COLORS_NATIVE | GB_ALPHA_NONE);\n params.x_offset = 0;\n params.raster = bitmap_raster(width * pdev->color_info.depth);\n\n code = 0;\n for (comp_num = 0; comp_num < num_comp; comp_num++) {\n planes[comp_num] = gs_alloc_bytes(pdev->memory, raster_plane,\n \"tiffsep1_print_page\");\n if (planes[comp_num] == NULL) {\n code = gs_error_VMerror;\n break;\n }\n }\n\n if (code < 0 || dithered_line == NULL) {\n code = gs_note_error(gs_error_VMerror);\n goto cleanup;\n }\n\n for (comp_num = 0; comp_num < num_comp; comp_num++ )\n TIFFCheckpointDirectory(tfdev->tiff[comp_num]);\n\n rect.p.x = 0;\n rect.q.x = pdev->width;\n /* Loop for the lines */\n for (y = 0; y < pdev->height; ++y) {\n rect.p.y = y;\n rect.q.y = y + 1;\n /* We have to reset the pointers since get_bits_rect will have moved them */\n for (comp_num = 0; comp_num < num_comp; comp_num++)\n params.data[comp_num] = planes[comp_num];\n code = (*dev_proc(pdev, get_bits_rectangle))((gx_device *)pdev, &rect, ¶ms, NULL);\n if (code < 0)\n break;\n\n /* Dither the separation and write it out */\n for (comp_num = 0; comp_num < num_comp; comp_num++ ) {\n\n/***** #define SKIP_HALFTONING_FOR_TIMING *****/ /* uncomment for timing test */\n#ifndef SKIP_HALFTONING_FOR_TIMING\n\n /*\n * Define 32-bit writes by default. Testing shows that while this is more\n * complex code, it runs measurably and consistently faster than the more\n * obvious 8-bit code. The 8-bit code is kept to help future optimization\n * efforts determine what affects tight loop optimization. Subtracting the\n * time when halftoning is skipped shows that the 32-bit halftoning is\n * 27% faster.\n */\n#define USE_32_BIT_WRITES\n byte *thresh_line_base = tfdev->thresholds[comp_num].dstart +\n ((y % tfdev->thresholds[comp_num].dheight) *\n tfdev->thresholds[comp_num].dwidth) ;\n byte *thresh_ptr = thresh_line_base;\n byte *thresh_limit = thresh_ptr + tfdev->thresholds[comp_num].dwidth;\n byte *src = params.data[comp_num];\n#ifdef USE_32_BIT_WRITES\n uint32_t *dest = dithered_line;\n uint32_t val = 0;\n const uint32_t *mask = &bit_order[0];\n#else /* example 8-bit code */\n byte *dest = dithered_line;\n byte val = 0;\n byte mask = 0x80;\n#endif /* USE_32_BIT_WRITES */\n\n for (pixel = 0; pixel < width; pixel++, src++) {\n#ifdef USE_32_BIT_WRITES\n if (*src < *thresh_ptr++)\n val |= *mask;\n if (++mask == &(bit_order[32])) {\n *dest++ = val;\n val = 0;\n mask = &bit_order[0];\n }\n#else /* example 8-bit code */\n if (*src < *thresh_ptr++)\n val |= mask;\n mask >>= 1;\n if (mask == 0) {\n *dest++ = val;\n val = 0;\n mask = 0x80;\n }\n#endif /* USE_32_BIT_WRITES */\n if (thresh_ptr >= thresh_limit)\n thresh_ptr = thresh_line_base;\n } /* end src pixel loop - collect last bits if any */\n /* the following relies on their being enough 'pad' in dithered_line */\n#ifdef USE_32_BIT_WRITES\n if (mask != &bit_order[0]) {\n *dest = val;\n }\n#else /* example 8-bit code */\n if (mask != 0x80) {\n *dest = val;\n }\n#endif /* USE_32_BIT_WRITES */\n#endif /* SKIP_HALFTONING_FOR_TIMING */\n TIFFWriteScanline(tfdev->tiff[comp_num], (tdata_t)dithered_line, y, 0);\n } /* end component loop */\n }\n /* Update the strip data */\n for (comp_num = 0; comp_num < num_comp; comp_num++ ) {\n TIFFWriteDirectory(tfdev->tiff[comp_num]);\n if (fmt) {\n int sep_num = map_comp_to_sep[comp_num];\n\n code = create_separation_file_name((tiffsep_device *)tfdev, name, gp_file_name_sizeof, sep_num, false);\n if (code < 0) {\n code1 = code;\n continue;\n }\n code = tiffsep_close_sep_file((tiffsep_device *)tfdev, name, comp_num);\n if (code >= 0)\n code = gs_remove_outputfile_control_path(tfdev->memory, name);\n if (code < 0) {\n code1 = code;\n }\n }\n }\n code = code1;\n\n /* free any allocations and exit with code */\ncleanup:\n gs_free_object(pdev->memory, dithered_line, \"tiffsep1_print_page\");\n for (comp_num = 0; comp_num < num_comp; comp_num++) {\n gs_free_object(pdev->memory, planes[comp_num], \"tiffsep1_print_page\");\n }\n }\n /*\n * If we have any non encodable pixels then signal an error.\n */\n if (non_encodable_count) {\n dmlprintf1(pdev->memory, \"WARNING: Non encodable pixels = %d\\n\", non_encodable_count);\n code = gs_note_error(gs_error_rangecheck);\n }\n\ndone:\n if (name)\n gs_free_object(pdev->memory, name, \"tiffsep1_print_page(name)\");\n return code;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Tiffsep and Tiffsep1 - abort on multi-page input wtithout %d OutputFile\n\nBug #701821 \"Segmentation fault at tiff//libtiff/tif_dirinfo.c:513 in TIFFFindField\"\n\nThe tiffsep and tiffsep1 only set 'code' to an error when an attempt is\nmade to write a second output file without using %d in the OutputFile\nspecification.\n\nThis causes problems later when attempting to process the files. The\ndevices should exit without trying to further process the pages under\nthese conditions and this commit returns immediately on error.\n\nThe other devices like this already return immediately on error, it\nlooks like the code here was copied between devices without realising\nthat the tiffsep and tiffsep1 devices didn't exit when the error\ncondition was set.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int changedline (const Proto *p, int oldpc, int newpc) {\n while (oldpc++ < newpc) {\n if (p->lineinfo[oldpc] != 0)\n return (luaG_getfuncline(p, oldpc - 1) != luaG_getfuncline(p, newpc));\n }\n return 0; /* no line changes in the way */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-787'], 'message': 'Fixed bug: line hooks in stripped functions\n\nLine-hook handling was accessing debug info. without checking whether\nit was 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: image_render_color_thresh(gx_image_enum *penum_orig, const byte *buffer, int data_x,\n uint w, int h, gx_device * dev)\n{\n gx_image_enum *penum = penum_orig; /* const within proc */\n image_posture posture = penum->posture;\n int vdi; /* amounts to replicate */\n fixed xrun = 0;\n byte *thresh_align;\n byte *devc_contone[GX_DEVICE_COLOR_MAX_COMPONENTS];\n byte *psrc_plane[GX_DEVICE_COLOR_MAX_COMPONENTS];\n byte *devc_contone_gray;\n const byte *psrc = buffer + data_x;\n int dest_width, dest_height, data_length;\n int spp_out = dev->color_info.num_components;\n int position, i, j, k;\n int offset_bits = penum->ht_offset_bits;\n int contone_stride = 0; /* Not used in landscape case */\n fixed offset;\n int src_size;\n bool flush_buff = false;\n byte *psrc_temp;\n int offset_contone[GX_DEVICE_COLOR_MAX_COMPONENTS]; /* to ensure 128 bit boundary */\n int offset_threshold; /* to ensure 128 bit boundary */\n gx_dda_fixed dda_ht;\n int xn, xr;\t\t/* destination position (pixel, not contone buffer offset) */\n int code = 0;\n int spp_cm = 0;\n byte *psrc_cm = NULL, *psrc_cm_start = NULL;\n byte *bufend = NULL;\n int psrc_planestride = w/penum->spp;\n\n if (h != 0 && penum->line_size != 0) { /* line_size == 0, nothing to do */\n /* Get the buffer into the device color space */\n code = image_color_icc_prep(penum, psrc, w, dev, &spp_cm, &psrc_cm,\n &psrc_cm_start, &bufend, true);\n if (code < 0)\n return code;\n } else {\n if (penum->ht_landscape.count == 0 || posture == image_portrait) {\n return 0;\n } else {\n /* Need to flush the buffer */\n offset_bits = penum->ht_landscape.count;\n penum->ht_offset_bits = offset_bits;\n penum->ht_landscape.offset_set = true;\n flush_buff = true;\n }\n }\n /* Data is now in the proper destination color space. Now we want\n to go ahead and get the data into the proper spatial setting and then\n threshold. First get the data spatially sampled correctly */\n src_size = penum->rect.w;\n\n /* Set up the dda. We could move this out but the cost is pretty small */\n dda_ht = (posture == image_portrait) ? penum->dda.pixel0.x : penum->dda.pixel0.y;\n if (penum->dxx > 0)\n dda_translate(dda_ht, -fixed_epsilon); /* to match rounding in non-fast code */\n\n switch (posture) {\n case image_portrait:\n /* Figure out our offset in the contone and threshold data\n buffers so that we ensure that we are on the 128bit\n memory boundaries when we get offset_bits into the data. */\n /* Can't do this earlier, as GC might move the buffers. */\n xrun = dda_current(dda_ht);\n dest_width = gxht_dda_length(&dda_ht, src_size);\n if (penum->x_extent.x < 0)\n xrun += penum->x_extent.x;\n vdi = penum->hci;\n contone_stride = penum->line_size;\n offset_threshold = (- (((long)(penum->thresh_buffer)) +\n penum->ht_offset_bits)) & 15;\n for (k = 0; k < spp_out; k ++) {\n offset_contone[k] = (- (((long)(penum->line)) +\n contone_stride * k +\n penum->ht_offset_bits)) & 15;\n }\n data_length = dest_width;\n dest_height = fixed2int_var_rounded(any_abs(penum->y_extent.y));\n#ifdef DEBUG\n /* Help in spotting problems */\n memset(penum->ht_buffer, 0x00, penum->ht_stride * vdi * spp_out);\n#endif\n break;\n case image_landscape:\n default:\n /* Figure out our offset in the contone and threshold data buffers\n so that we ensure that we are on the 128bit memory boundaries.\n Can't do this earlier as GC may move the buffers.\n */\n vdi = penum->wci;\n contone_stride = penum->line_size;\n dest_width = fixed2int_var_rounded(any_abs(penum->y_extent.x));\n /* match height in gxht_thresh.c dev_width calculation */\n xrun = dda_current(dda_ht); /* really yrun, but just used here for landscape */\n dest_height = gxht_dda_length(&dda_ht, src_size);\n data_length = dest_height;\n offset_threshold = (-(long)(penum->thresh_buffer)) & 15;\n for (k = 0; k < spp_out; k ++) {\n offset_contone[k] = (- ((long)(penum->line) +\n contone_stride * k)) & 15;\n }\n /* In the landscaped case, we want to accumulate multiple columns\n of data before sending to the device. We want to have a full\n byte of HT data in one write. This may not be possible at the\n left or right and for those and for those we have so send partial\n chunks */\n /* Initialize our xstart and compute our partial bit chunk so\n that we get in sync with the 1 bit mem device 16 bit positions\n for the rest of the chunks */\n if (penum->ht_landscape.count == 0) {\n /* In the landscape case, the size depends upon\n if we are moving left to right or right to left with\n the image data. This offset is to ensure that we get\n aligned in our chunks along 16 bit boundaries */\n penum->ht_landscape.offset_set = true;\n if (penum->ht_landscape.index < 0) {\n penum->ht_landscape.xstart = penum->xci + vdi - 1;\n offset_bits = (penum->ht_landscape.xstart % 16) + 1;\n /* xci can be negative, so allow for that */\n if (offset_bits <= 0) offset_bits += 16;\n } else {\n penum->ht_landscape.xstart = penum->xci;\n /* xci can be negative, see Bug 692569. */\n offset_bits = 16 - penum->xci % 16;\n if (offset_bits >= 16) offset_bits -= 16;\n }\n if (offset_bits == 0 || offset_bits == 16) {\n penum->ht_landscape.offset_set = false;\n penum->ht_offset_bits = 0;\n } else {\n penum->ht_offset_bits = offset_bits;\n }\n }\n break;\n }\n if (flush_buff)\n goto flush; /* All done */\n\n /* Get the pointers to our buffers */\n for (k = 0; k < spp_out; k++) {\n if (posture == image_portrait) {\n devc_contone[k] = penum->line + contone_stride * k +\n offset_contone[k];\n } else {\n devc_contone[k] = penum->line + offset_contone[k] +\n LAND_BITS * k * contone_stride;\n }\n psrc_plane[k] = psrc_cm + psrc_planestride * k;\n }\n xr = fixed2int_var_rounded(dda_current(dda_ht));\t/* indexes in the destination (contone) */\n\n /* Do conversion to device resolution in quick small loops. */\n /* For now we have 3 cases. A CMYK (4 channel), gray, or other case\n the latter of which is not yet implemented */\n switch (spp_out)\n {\n /* Monochrome output case */\n case 1:\n devc_contone_gray = devc_contone[0];\n switch (posture) {\n /* Monochrome portrait */\n case image_portrait:\n if (penum->dst_width > 0) {\n if (src_size == dest_width) {\n memcpy(devc_contone_gray, psrc_cm, data_length);\n } else if (src_size * 2 == dest_width) {\n psrc_temp = psrc_cm;\n for (k = 0; k < data_length; k+=2,\n devc_contone_gray+=2, psrc_temp++) {\n *devc_contone_gray =\n *(devc_contone_gray+1) = *psrc_temp;\n }\n } else {\n /* Mono case, forward */\n psrc_temp = psrc_cm;\n for (k=0; k= xr */\n psrc_temp++;\n }\n }\n } else {\n /* Mono case, backwards */\n devc_contone_gray += (data_length - 1);\n psrc_temp = psrc_cm;\n for (k=0; k xn) {\n *devc_contone_gray-- = *psrc_temp;\n xr--;\n } /* at loop exit xn will be >= xr */\n psrc_temp++;\n }\n }\n break;\n /* Monochrome landscape */\n case image_landscape:\n /* We store the data at this point into a column. Depending\n upon our landscape direction we may be going left to right\n or right to left. */\n if (penum->ht_landscape.flipy) {\n position = penum->ht_landscape.curr_pos +\n LAND_BITS * (data_length - 1);\n psrc_temp = psrc_cm;\n for (k=0; k xn) {\n devc_contone_gray[position] = *psrc_temp;\n position -= LAND_BITS;\n xr--;\n } /* at loop exit xn will be <= xr */\n psrc_temp++;\n }\n } else {\n position = penum->ht_landscape.curr_pos;\n /* Code up special cases for when we have no scaling\n and 2x scaling which we will run into in 300 and\n 600dpi devices and content */\n if (src_size == dest_height) {\n for (k = 0; k < data_length; k++) {\n devc_contone_gray[position] = psrc_cm[k];\n position += LAND_BITS;\n }\n } else if (src_size*2 == dest_height) {\n for (k = 0; k < data_length; k+=2) {\n offset = fixed2int_var_rounded(fixed_half * k);\n devc_contone_gray[position] =\n devc_contone_gray[position + LAND_BITS] =\n psrc_cm[offset];\n position += 2*LAND_BITS;\n }\n } else {\n /* use dda */\n psrc_temp = psrc_cm;\n for (k=0; k= xr */\n psrc_temp++;\n }\n }\n }\n /* Store the width information and update our counts */\n penum->ht_landscape.count += vdi;\n penum->ht_landscape.widths[penum->ht_landscape.curr_pos] = vdi;\n penum->ht_landscape.curr_pos += penum->ht_landscape.index;\n penum->ht_landscape.num_contones++;\n break;\n default:\n /* error not allowed */\n break;\n }\n break;\n\n /* CMYK case */\n case 4:\n switch (posture) {\n /* CMYK portrait */\n case image_portrait:\n if (penum->dst_width > 0) {\n if (src_size == dest_width) {\n memcpy(devc_contone[0], psrc_plane[0], data_length);\n memcpy(devc_contone[1], psrc_plane[1], data_length);\n memcpy(devc_contone[2], psrc_plane[2], data_length);\n memcpy(devc_contone[3], psrc_plane[3], data_length);\n } else if (src_size * 2 == dest_width) {\n for (k = 0; k < data_length; k+=2) {\n *(devc_contone[0]) = *(devc_contone[0]+1) =\n *psrc_plane[0]++;\n *(devc_contone[1]) = *(devc_contone[1]+1) =\n *psrc_plane[1]++;\n *(devc_contone[2]) = *(devc_contone[2]+1) =\n *psrc_plane[2]++;\n *(devc_contone[3]) = *(devc_contone[3]+1) =\n *psrc_plane[3]++;\n devc_contone[0] += 2;\n devc_contone[1] += 2;\n devc_contone[2] += 2;\n devc_contone[3] += 2;\n }\n } else {\n /* CMYK case, forward */\n for (k=0, j=0; k= xr */\n j++;\n }\n }\n } else {\n /* CMYK case, backwards */\n /* Move to the other end and we will decrement */\n devc_contone[0] += (data_length - 1);\n devc_contone[1] += (data_length - 1);\n devc_contone[2] += (data_length - 1);\n devc_contone[3] += (data_length - 1);\n for (k=0, j=0; k xn) {\n *(devc_contone[0])-- = (psrc_plane[0])[j];\n *(devc_contone[1])-- = (psrc_plane[1])[j];\n *(devc_contone[2])-- = (psrc_plane[2])[j];\n *(devc_contone[3])-- = (psrc_plane[3])[j];\n xr--;\n } /* at loop exit xn will be <= xr */\n j++;\n }\n }\n break;\n /* CMYK landscape */\n case image_landscape:\n /* Data is already color managed. */\n /* We store the data at this point into columns in\n seperate planes. Depending upon our landscape direction\n we may be going left to right or right to left. */\n if (penum->ht_landscape.flipy) {\n position = penum->ht_landscape.curr_pos +\n LAND_BITS * (data_length - 1);\n /* use dda */\n for (k=0, i=0; k xn) {\n for (j = 0; j < spp_out; j++) {\n *(devc_contone[j] + position) = (psrc_plane[j])[i];\n position -= LAND_BITS;\n }\n xr--;\n } /* at loop exit xn will be <= xr */\n i++;\n }\n } else {\n position = penum->ht_landscape.curr_pos;\n /* Code up special cases for when we have no scaling\n and 2x scaling which we will run into in 300 and\n 600dpi devices and content */\n /* Apply initial offset */\n for (k = 0; k < spp_out; k++) {\n devc_contone[k] = devc_contone[k] + position;\n }\n if (src_size == dest_height) {\n for (k = 0; k < data_length; k++) {\n /* Is it better to unwind this? We know it is 4 */\n for (j = 0; j < spp_out; j++) {\n *(devc_contone[j]) = (psrc_plane[j])[k];\n devc_contone[j] += LAND_BITS;\n }\n }\n } else if (src_size*2 == dest_height) {\n for (k = 0; k < data_length; k+=2) {\n offset = fixed2int_var_rounded(fixed_half * k);\n /* Is it better to unwind this? We know it is 4 */\n for (j = 0; j < spp_out; j++) {\n *(devc_contone[j]) =\n *(devc_contone[j] + LAND_BITS) =\n (psrc_plane[j])[offset];\n devc_contone[j] += 2 * LAND_BITS;\n }\n }\n } else {\n /* use dda */\n for (k=0, i=0; k xn) {\n for (j = 0; j < spp_out; j++) {\n *(devc_contone[j] + position) = (psrc_plane[j])[i];\n position -= LAND_BITS;\n }\n xr--;\n } /* at loop exit xn will be <= xr */\n i++;\n }\n }\n }\n /* Store the width information and update our counts */\n penum->ht_landscape.count += vdi;\n penum->ht_landscape.widths[penum->ht_landscape.curr_pos] = vdi;\n penum->ht_landscape.curr_pos += penum->ht_landscape.index;\n penum->ht_landscape.num_contones++;\n break;\n default:\n /* error not allowed */\n break;\n }\n break;\n default:\n /* Not yet handled (e.g. CMY case) */\n break;\n }\n /* Apply threshold array to image data. It may be neccessary to invert\n depnding upon the polarity of the device */\nflush:\n thresh_align = penum->thresh_buffer + offset_threshold;\n code = gxht_thresh_planes(penum, xrun, dest_width, dest_height,\n thresh_align, dev, offset_contone,\n contone_stride);\n /* Free cm buffer, if it was used */\n if (psrc_cm_start != NULL) {\n gs_free_object(penum->pgs->memory, (byte *)psrc_cm_start,\n \"image_render_color_thresh\");\n }\n return code;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Bug 701842: Fix misindexing in gxicolor.c\n\nWe were incorrectly decrementing position per-component, rather\nthan per-pixel (in 2 places).\n\nAlso, take care of some whitespace oddities.'" }, { "text": "[INST] Given the following code containing errors, provide Common 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_pidfile(void)\n{\n const char *pidfile = CNF_GetPidFile();\n FILE *out;\n\n if (!pidfile[0])\n return;\n\n out = fopen(pidfile, \"w\");\n if (!out) {\n LOG_FATAL(\"Could not open %s : %s\", pidfile, strerror(errno));\n } else {\n fprintf(out, \"%d\\n\", (int)getpid());\n fclose(out);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59'], 'message': 'switch to new util file functions\n\nReplace all fopen(), rename(), and unlink() calls with the new util\nfunctions.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: REF_Initialise(void)\n{\n FILE *in;\n double file_freq_ppm, file_skew_ppm;\n double our_frequency_ppm;\n int tai_offset;\n\n mode = REF_ModeNormal;\n are_we_synchronised = 0;\n our_leap_status = LEAP_Unsynchronised;\n our_leap_sec = 0;\n our_tai_offset = 0;\n initialised = 1;\n our_root_dispersion = 1.0;\n our_root_delay = 1.0;\n our_frequency_ppm = 0.0;\n our_skew = 1.0; /* i.e. rather bad */\n our_residual_freq = 0.0;\n drift_file_age = 0.0;\n\n /* Now see if we can get the drift file opened */\n drift_file = CNF_GetDriftFile();\n if (drift_file) {\n in = fopen(drift_file, \"r\");\n if (in) {\n if (fscanf(in, \"%lf%lf\", &file_freq_ppm, &file_skew_ppm) == 2) {\n /* We have read valid data */\n our_frequency_ppm = file_freq_ppm;\n our_skew = 1.0e-6 * file_skew_ppm;\n if (our_skew < MIN_SKEW)\n our_skew = MIN_SKEW;\n LOG(LOGS_INFO, \"Frequency %.3f +/- %.3f ppm read from %s\",\n file_freq_ppm, file_skew_ppm, drift_file);\n LCL_SetAbsoluteFrequency(our_frequency_ppm);\n } else {\n LOG(LOGS_WARN, \"Could not read valid frequency and skew from driftfile %s\",\n drift_file);\n }\n fclose(in);\n }\n }\n \n if (our_frequency_ppm == 0.0) {\n our_frequency_ppm = LCL_ReadAbsoluteFrequency();\n if (our_frequency_ppm != 0.0) {\n LOG(LOGS_INFO, \"Initial frequency %.3f ppm\", our_frequency_ppm);\n }\n }\n\n logfileid = CNF_GetLogTracking() ? LOG_FileOpen(\"tracking\",\n \" Date (UTC) Time IP Address St Freq ppm Skew ppm Offset L Co Offset sd Rem. corr. Root delay Root disp. Max. error\")\n : -1;\n\n max_update_skew = fabs(CNF_GetMaxUpdateSkew()) * 1.0e-6;\n\n correction_time_ratio = CNF_GetCorrectionTimeRatio();\n\n enable_local_stratum = CNF_AllowLocalReference(&local_stratum, &local_orphan, &local_distance);\n UTI_ZeroTimespec(&local_ref_time);\n\n leap_timeout_id = 0;\n leap_in_progress = 0;\n leap_mode = CNF_GetLeapSecMode();\n /* Switch to step mode if the system driver doesn't support leap */\n if (leap_mode == REF_LeapModeSystem && !LCL_CanSystemLeap())\n leap_mode = REF_LeapModeStep;\n\n leap_tzname = CNF_GetLeapSecTimezone();\n if (leap_tzname) {\n /* Check that the timezone has good data for Jun 30 2012 and Dec 31 2012 */\n if (get_tz_leap(1341014400, &tai_offset) == LEAP_InsertSecond && tai_offset == 34 &&\n get_tz_leap(1356912000, &tai_offset) == LEAP_Normal && tai_offset == 35) {\n LOG(LOGS_INFO, \"Using %s timezone to obtain leap second data\", leap_tzname);\n } else {\n LOG(LOGS_WARN, \"Timezone %s failed leap second check, ignoring\", leap_tzname);\n leap_tzname = NULL;\n }\n }\n\n CNF_GetMakeStep(&make_step_limit, &make_step_threshold);\n CNF_GetMaxChange(&max_offset_delay, &max_offset_ignore, &max_offset);\n CNF_GetMailOnChange(&do_mail_change, &mail_change_threshold, &mail_change_user);\n log_change_threshold = CNF_GetLogChange();\n\n CNF_GetFallbackDrifts(&fb_drift_min, &fb_drift_max);\n\n if (fb_drift_max >= fb_drift_min && fb_drift_min > 0) {\n fb_drifts = MallocArray(struct fb_drift, fb_drift_max - fb_drift_min + 1);\n memset(fb_drifts, 0, sizeof (struct fb_drift) * (fb_drift_max - fb_drift_min + 1));\n next_fb_drift = 0;\n fb_drift_timeout_id = 0;\n }\n\n UTI_ZeroTimespec(&our_ref_time);\n UTI_ZeroTimespec(&last_ref_update);\n last_ref_update_interval = 0.0;\n\n LCL_AddParameterChangeHandler(handle_slew, NULL);\n\n /* Make first entry in tracking log */\n REF_SetUnsynchronised();\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 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': 'Fix handling of errors during snapshot restore.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: HttpHeaderEntry::parse(const char *field_start, const char *field_end, const http_hdr_owner_type msgType)\n{\n /* note: name_start == field_start */\n const char *name_end = (const char *)memchr(field_start, ':', field_end - field_start);\n int name_len = name_end ? name_end - field_start :0;\n const char *value_start = field_start + name_len + 1; /* skip ':' */\n /* note: value_end == field_end */\n\n ++ HeaderEntryParsedCount;\n\n /* do we have a valid field name within this field? */\n\n if (!name_len || name_end > field_end)\n return NULL;\n\n if (name_len > 65534) {\n /* String must be LESS THAN 64K and it adds a terminating NULL */\n // TODO: update this to show proper name_len in Raw markup, but not print all that\n debugs(55, 2, \"ignoring huge header field (\" << Raw(\"field_start\", field_start, 100) << \"...)\");\n return NULL;\n }\n\n /*\n * RFC 7230 section 3.2.4:\n * \"No whitespace is allowed between the header field-name and colon.\n * ...\n * A server MUST reject any received request message that contains\n * whitespace between a header field-name and colon with a response code\n * of 400 (Bad Request). A proxy MUST remove any such whitespace from a\n * response message before forwarding the message downstream.\"\n */\n if (xisspace(field_start[name_len - 1])) {\n\n if (msgType == hoRequest)\n return nullptr;\n\n // for now, also let relaxed parser remove this BWS from any non-HTTP messages\n const bool stripWhitespace = (msgType == hoReply) ||\n Config.onoff.relaxed_header_parser;\n if (!stripWhitespace)\n return nullptr; // reject if we cannot strip\n\n debugs(55, Config.onoff.relaxed_header_parser <= 0 ? 1 : 2,\n \"NOTICE: Whitespace after header name in '\" << getStringPrefix(field_start, field_end-field_start) << \"'\");\n\n while (name_len > 0 && xisspace(field_start[name_len - 1]))\n --name_len;\n\n if (!name_len) {\n debugs(55, 2, \"found header with only whitespace for name\");\n return NULL;\n }\n }\n\n /* now we know we can parse it */\n\n debugs(55, 9, \"parsing HttpHeaderEntry: near '\" << getStringPrefix(field_start, field_end-field_start) << \"'\");\n\n /* is it a \"known\" field? */\n Http::HdrType id = Http::HeaderLookupTable.lookup(field_start,name_len).id;\n debugs(55, 9, \"got hdr-id=\" << id);\n\n String name;\n\n String value;\n\n if (id == Http::HdrType::BAD_HDR)\n id = Http::HdrType::OTHER;\n\n /* set field name */\n if (id == Http::HdrType::OTHER)\n name.limitInit(field_start, name_len);\n else\n name = Http::HeaderLookupTable.lookup(id).name;\n\n /* trim field value */\n while (value_start < field_end && xisspace(*value_start))\n ++value_start;\n\n while (value_start < field_end && xisspace(field_end[-1]))\n --field_end;\n\n if (field_end - value_start > 65534) {\n /* String must be LESS THAN 64K and it adds a terminating NULL */\n debugs(55, 2, \"WARNING: found '\" << name << \"' header of \" << (field_end - value_start) << \" bytes\");\n return NULL;\n }\n\n /* set field value */\n value.limitInit(value_start, field_end - value_start);\n\n if (id != Http::HdrType::BAD_HDR)\n ++ headerStatsTable[id].seenCount;\n\n debugs(55, 9, \"parsed HttpHeaderEntry: '\" << name << \": \" << value << \"'\");\n\n return new HttpHeaderEntry(id, name.termedBuf(), value.termedBuf());\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: static int parse_eops(extop **result, bool critical, int elem)\n{\n extop *eop = NULL, *prev = NULL;\n extop **tail = result;\n int sign;\n int i = tokval.t_type;\n int oper_num = 0;\n bool do_subexpr = false;\n\n *tail = NULL;\n\n /* End of string is obvious; ) ends a sub-expression list e.g. DUP */\n for (i = tokval.t_type; i != TOKEN_EOS; i = stdscan(NULL, &tokval)) {\n char endparen = ')'; /* Is a right paren the end of list? */\n\n if (i == ')')\n break;\n\n if (!eop) {\n nasm_new(eop);\n eop->dup = 1;\n eop->elem = elem;\n do_subexpr = false;\n }\n sign = +1;\n\n /*\n * end_expression_next() here is to distinguish this from\n * a string used as part of an expression...\n */\n if (i == TOKEN_QMARK) {\n eop->type = EOT_DB_RESERVE;\n } else if (do_subexpr && i == '(') {\n extop *subexpr;\n\n stdscan(NULL, &tokval); /* Skip paren */\n if (parse_eops(&eop->val.subexpr, critical, eop->elem) < 0)\n goto fail;\n\n subexpr = eop->val.subexpr;\n if (!subexpr) {\n /* Subexpression is empty */\n eop->type = EOT_NOTHING;\n } else if (!subexpr->next) {\n /* Subexpression is a single element, flatten */\n eop->val = subexpr->val;\n eop->type = subexpr->type;\n eop->dup *= subexpr->dup;\n nasm_free(subexpr);\n } else {\n eop->type = EOT_EXTOP;\n }\n\n /* We should have ended on a closing paren */\n if (tokval.t_type != ')') {\n nasm_nonfatal(\"expected `)' after subexpression, got `%s'\",\n i == TOKEN_EOS ?\n \"end of line\" : tokval.t_charptr);\n goto fail;\n }\n endparen = 0; /* This time the paren is not the end */\n } else if (i == '%') {\n /* %(expression_list) */\n do_subexpr = true;\n continue;\n } else if (i == TOKEN_SIZE) {\n /* Element size override */\n eop->elem = tokval.t_inttwo;\n do_subexpr = true;\n continue;\n } else if (i == TOKEN_STR && end_expression_next()) {\n eop->type = EOT_DB_STRING;\n eop->val.string.data = tokval.t_charptr;\n eop->val.string.len = tokval.t_inttwo;\n } else if (i == TOKEN_STRFUNC) {\n bool parens = false;\n const char *funcname = tokval.t_charptr;\n enum strfunc func = tokval.t_integer;\n\n i = stdscan(NULL, &tokval);\n if (i == '(') {\n parens = true;\n endparen = 0;\n i = stdscan(NULL, &tokval);\n }\n if (i != TOKEN_STR) {\n nasm_nonfatal(\"%s must be followed by a string constant\",\n funcname);\n eop->type = EOT_NOTHING;\n } else {\n eop->type = EOT_DB_STRING_FREE;\n eop->val.string.len =\n string_transform(tokval.t_charptr, tokval.t_inttwo,\n &eop->val.string.data, func);\n if (eop->val.string.len == (size_t)-1) {\n nasm_nonfatal(\"invalid input string to %s\", funcname);\n eop->type = EOT_NOTHING;\n }\n }\n if (parens && i && i != ')') {\n i = stdscan(NULL, &tokval);\n if (i != ')')\n nasm_nonfatal(\"unterminated %s function\", funcname);\n }\n } else if (i == '-' || i == '+') {\n char *save = stdscan_get();\n struct tokenval tmptok;\n\n sign = (i == '-') ? -1 : 1;\n if (stdscan(NULL, &tmptok) != TOKEN_FLOAT) {\n stdscan_set(save);\n goto is_expression;\n } else {\n tokval = tmptok;\n goto is_float;\n }\n } else if (i == TOKEN_FLOAT) {\n enum floatize fmt;\n is_float:\n eop->type = EOT_DB_FLOAT;\n\n fmt = float_deffmt(eop->elem);\n if (fmt == FLOAT_ERR) {\n nasm_nonfatal(\"no %d-bit floating-point format supported\",\n eop->elem << 3);\n eop->val.string.len = 0;\n } else if (eop->elem < 1) {\n nasm_nonfatal(\"floating-point constant\"\n \" encountered in unknown instruction\");\n /*\n * fix suggested by Pedro Gimeno... original line was:\n * eop->type = EOT_NOTHING;\n */\n eop->val.string.len = 0;\n } else {\n eop->val.string.len = eop->elem;\n\n eop = nasm_realloc(eop, sizeof(extop) + eop->val.string.len);\n eop->val.string.data = (char *)eop + sizeof(extop);\n if (!float_const(tokval.t_charptr, sign,\n (uint8_t *)eop->val.string.data, fmt))\n eop->val.string.len = 0;\n }\n if (!eop->val.string.len)\n eop->type = EOT_NOTHING;\n } else {\n /* anything else, assume it is an expression */\n expr *value;\n\n is_expression:\n value = evaluate(stdscan, NULL, &tokval, NULL,\n critical, NULL);\n i = tokval.t_type;\n if (!value) /* Error in evaluator */\n goto fail;\n if (tokval.t_flag & TFLAG_DUP) {\n /* Expression followed by DUP */\n if (!is_simple(value)) {\n nasm_nonfatal(\"non-constant argument supplied to DUP\");\n goto fail;\n } else if (value->value < 0) {\n nasm_nonfatal(\"negative argument supplied to DUP\");\n goto fail;\n }\n eop->dup *= (size_t)value->value;\n do_subexpr = true;\n continue;\n }\n if (value_to_extop(value, eop, location.segment)) {\n nasm_nonfatal(\"expression is not simple or relocatable\");\n }\n }\n\n if (eop->dup == 0 || eop->type == EOT_NOTHING) {\n nasm_free(eop);\n } else if (eop->type == EOT_DB_RESERVE &&\n prev && prev->type == EOT_DB_RESERVE &&\n prev->elem == eop->elem) {\n /* Coalesce multiple EOT_DB_RESERVE */\n prev->dup += eop->dup;\n nasm_free(eop);\n } else {\n /* Add this eop to the end of the chain */\n prev = eop;\n *tail = eop;\n tail = &eop->next;\n }\n\n oper_num++;\n eop = NULL; /* Done with this operand */\n\n /*\n * We're about to call stdscan(), which will eat the\n * comma that we're currently sitting on between\n * arguments. However, we'd better check first that it\n * _is_ a comma.\n */\n if (i == TOKEN_EOS || i == endparen)\t/* Already at end? */\n break;\n if (i != ',') {\n i = stdscan(NULL, &tokval);\t\t/* eat the comma or final paren */\n if (i == TOKEN_EOS || i == ')')\t/* got end of expression */\n break;\n if (i != ',') {\n nasm_nonfatal(\"comma expected after operand\");\n goto fail;\n }\n }\n }\n\n return oper_num;\n\nfail:\n if (eop)\n nasm_free(eop);\n return -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'parser: when flattening an eop, must preserve any data buffer\n\nAn eop may have a data buffer associated with it as part of the same\nmemory allocation. Therefore, we need to move \"subexpr\" up instead of\nmerging it into \"eop\".\n\nThis *partially* resolves BR 3392707, but that test case still\ntriggers a violation when using -gcv8.\n\nReported-by: Suhwan \nSigned-off-by: H. Peter Anvin (Intel) '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,\n\t\t struct packet_type *pt, struct net_device *orig_dev)\n{\n\tstruct sock *sk;\n\tstruct packet_sock *po;\n\tstruct sockaddr_ll *sll;\n\tunion tpacket_uhdr h;\n\tu8 *skb_head = skb->data;\n\tint skb_len = skb->len;\n\tunsigned int snaplen, res;\n\tunsigned long status = TP_STATUS_USER;\n\tunsigned short macoff, netoff, hdrlen;\n\tstruct sk_buff *copy_skb = NULL;\n\tstruct timespec64 ts;\n\t__u32 ts_status;\n\tbool is_drop_n_account = false;\n\tunsigned int slot_id = 0;\n\tbool do_vnet = false;\n\n\t/* struct tpacket{2,3}_hdr is aligned to a multiple of TPACKET_ALIGNMENT.\n\t * We may add members to them until current aligned size without forcing\n\t * userspace to call getsockopt(..., PACKET_HDRLEN, ...).\n\t */\n\tBUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h2)) != 32);\n\tBUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h3)) != 48);\n\n\tif (skb->pkt_type == PACKET_LOOPBACK)\n\t\tgoto drop;\n\n\tsk = pt->af_packet_priv;\n\tpo = pkt_sk(sk);\n\n\tif (!net_eq(dev_net(dev), sock_net(sk)))\n\t\tgoto drop;\n\n\tif (dev->header_ops) {\n\t\tif (sk->sk_type != SOCK_DGRAM)\n\t\t\tskb_push(skb, skb->data - skb_mac_header(skb));\n\t\telse if (skb->pkt_type == PACKET_OUTGOING) {\n\t\t\t/* Special case: outgoing packets have ll header at head */\n\t\t\tskb_pull(skb, skb_network_offset(skb));\n\t\t}\n\t}\n\n\tsnaplen = skb->len;\n\n\tres = run_filter(skb, sk, snaplen);\n\tif (!res)\n\t\tgoto drop_n_restore;\n\n\t/* If we are flooded, just give up */\n\tif (__packet_rcv_has_room(po, skb) == ROOM_NONE) {\n\t\tatomic_inc(&po->tp_drops);\n\t\tgoto drop_n_restore;\n\t}\n\n\tif (skb->ip_summed == CHECKSUM_PARTIAL)\n\t\tstatus |= TP_STATUS_CSUMNOTREADY;\n\telse if (skb->pkt_type != PACKET_OUTGOING &&\n\t\t (skb->ip_summed == CHECKSUM_COMPLETE ||\n\t\t skb_csum_unnecessary(skb)))\n\t\tstatus |= TP_STATUS_CSUM_VALID;\n\n\tif (snaplen > res)\n\t\tsnaplen = res;\n\n\tif (sk->sk_type == SOCK_DGRAM) {\n\t\tmacoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +\n\t\t\t\t po->tp_reserve;\n\t} else {\n\t\tunsigned int maclen = skb_network_offset(skb);\n\t\tnetoff = TPACKET_ALIGN(po->tp_hdrlen +\n\t\t\t\t (maclen < 16 ? 16 : maclen)) +\n\t\t\t\t po->tp_reserve;\n\t\tif (po->has_vnet_hdr) {\n\t\t\tnetoff += sizeof(struct virtio_net_hdr);\n\t\t\tdo_vnet = true;\n\t\t}\n\t\tmacoff = netoff - maclen;\n\t}\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tif (macoff + snaplen > po->rx_ring.frame_size) {\n\t\t\tif (po->copy_thresh &&\n\t\t\t atomic_read(&sk->sk_rmem_alloc) < sk->sk_rcvbuf) {\n\t\t\t\tif (skb_shared(skb)) {\n\t\t\t\t\tcopy_skb = skb_clone(skb, GFP_ATOMIC);\n\t\t\t\t} else {\n\t\t\t\t\tcopy_skb = skb_get(skb);\n\t\t\t\t\tskb_head = skb->data;\n\t\t\t\t}\n\t\t\t\tif (copy_skb)\n\t\t\t\t\tskb_set_owner_r(copy_skb, sk);\n\t\t\t}\n\t\t\tsnaplen = po->rx_ring.frame_size - macoff;\n\t\t\tif ((int)snaplen < 0) {\n\t\t\t\tsnaplen = 0;\n\t\t\t\tdo_vnet = false;\n\t\t\t}\n\t\t}\n\t} else if (unlikely(macoff + snaplen >\n\t\t\t GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len)) {\n\t\tu32 nval;\n\n\t\tnval = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len - macoff;\n\t\tpr_err_once(\"tpacket_rcv: packet too big, clamped from %u to %u. macoff=%u\\n\",\n\t\t\t snaplen, nval, macoff);\n\t\tsnaplen = nval;\n\t\tif (unlikely((int)snaplen < 0)) {\n\t\t\tsnaplen = 0;\n\t\t\tmacoff = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len;\n\t\t\tdo_vnet = false;\n\t\t}\n\t}\n\tspin_lock(&sk->sk_receive_queue.lock);\n\th.raw = packet_current_rx_frame(po, skb,\n\t\t\t\t\tTP_STATUS_KERNEL, (macoff+snaplen));\n\tif (!h.raw)\n\t\tgoto drop_n_account;\n\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tslot_id = po->rx_ring.head;\n\t\tif (test_bit(slot_id, po->rx_ring.rx_owner_map))\n\t\t\tgoto drop_n_account;\n\t\t__set_bit(slot_id, po->rx_ring.rx_owner_map);\n\t}\n\n\tif (do_vnet &&\n\t virtio_net_hdr_from_skb(skb, h.raw + macoff -\n\t\t\t\t sizeof(struct virtio_net_hdr),\n\t\t\t\t vio_le(), true, 0)) {\n\t\tif (po->tp_version == TPACKET_V3)\n\t\t\tprb_clear_blk_fill_status(&po->rx_ring);\n\t\tgoto drop_n_account;\n\t}\n\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tpacket_increment_rx_head(po, &po->rx_ring);\n\t/*\n\t * LOSING will be reported till you read the stats,\n\t * because it's COR - Clear On Read.\n\t * Anyways, moving it for V1/V2 only as V3 doesn't need this\n\t * at packet level.\n\t */\n\t\tif (atomic_read(&po->tp_drops))\n\t\t\tstatus |= TP_STATUS_LOSING;\n\t}\n\n\tpo->stats.stats1.tp_packets++;\n\tif (copy_skb) {\n\t\tstatus |= TP_STATUS_COPY;\n\t\t__skb_queue_tail(&sk->sk_receive_queue, copy_skb);\n\t}\n\tspin_unlock(&sk->sk_receive_queue.lock);\n\n\tskb_copy_bits(skb, 0, h.raw + macoff, snaplen);\n\n\tif (!(ts_status = tpacket_get_timestamp(skb, &ts, po->tp_tstamp)))\n\t\tktime_get_real_ts64(&ts);\n\n\tstatus |= ts_status;\n\n\tswitch (po->tp_version) {\n\tcase TPACKET_V1:\n\t\th.h1->tp_len = skb->len;\n\t\th.h1->tp_snaplen = snaplen;\n\t\th.h1->tp_mac = macoff;\n\t\th.h1->tp_net = netoff;\n\t\th.h1->tp_sec = ts.tv_sec;\n\t\th.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;\n\t\thdrlen = sizeof(*h.h1);\n\t\tbreak;\n\tcase TPACKET_V2:\n\t\th.h2->tp_len = skb->len;\n\t\th.h2->tp_snaplen = snaplen;\n\t\th.h2->tp_mac = macoff;\n\t\th.h2->tp_net = netoff;\n\t\th.h2->tp_sec = ts.tv_sec;\n\t\th.h2->tp_nsec = ts.tv_nsec;\n\t\tif (skb_vlan_tag_present(skb)) {\n\t\t\th.h2->tp_vlan_tci = skb_vlan_tag_get(skb);\n\t\t\th.h2->tp_vlan_tpid = ntohs(skb->vlan_proto);\n\t\t\tstatus |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;\n\t\t} else {\n\t\t\th.h2->tp_vlan_tci = 0;\n\t\t\th.h2->tp_vlan_tpid = 0;\n\t\t}\n\t\tmemset(h.h2->tp_padding, 0, sizeof(h.h2->tp_padding));\n\t\thdrlen = sizeof(*h.h2);\n\t\tbreak;\n\tcase TPACKET_V3:\n\t\t/* tp_nxt_offset,vlan are already populated above.\n\t\t * So DONT clear those fields here\n\t\t */\n\t\th.h3->tp_status |= status;\n\t\th.h3->tp_len = skb->len;\n\t\th.h3->tp_snaplen = snaplen;\n\t\th.h3->tp_mac = macoff;\n\t\th.h3->tp_net = netoff;\n\t\th.h3->tp_sec = ts.tv_sec;\n\t\th.h3->tp_nsec = ts.tv_nsec;\n\t\tmemset(h.h3->tp_padding, 0, sizeof(h.h3->tp_padding));\n\t\thdrlen = sizeof(*h.h3);\n\t\tbreak;\n\tdefault:\n\t\tBUG();\n\t}\n\n\tsll = h.raw + TPACKET_ALIGN(hdrlen);\n\tsll->sll_halen = dev_parse_header(skb, sll->sll_addr);\n\tsll->sll_family = AF_PACKET;\n\tsll->sll_hatype = dev->type;\n\tsll->sll_protocol = skb->protocol;\n\tsll->sll_pkttype = skb->pkt_type;\n\tif (unlikely(po->origdev))\n\t\tsll->sll_ifindex = orig_dev->ifindex;\n\telse\n\t\tsll->sll_ifindex = dev->ifindex;\n\n\tsmp_mb();\n\n#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tu8 *start, *end;\n\n\t\tend = (u8 *) PAGE_ALIGN((unsigned long) h.raw +\n\t\t\t\t\tmacoff + snaplen);\n\n\t\tfor (start = h.raw; start < end; start += PAGE_SIZE)\n\t\t\tflush_dcache_page(pgv_to_page(start));\n\t}\n\tsmp_wmb();\n#endif\n\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tspin_lock(&sk->sk_receive_queue.lock);\n\t\t__packet_set_status(po, h.raw, status);\n\t\t__clear_bit(slot_id, po->rx_ring.rx_owner_map);\n\t\tspin_unlock(&sk->sk_receive_queue.lock);\n\t\tsk->sk_data_ready(sk);\n\t} else if (po->tp_version == TPACKET_V3) {\n\t\tprb_clear_blk_fill_status(&po->rx_ring);\n\t}\n\ndrop_n_restore:\n\tif (skb_head != skb->data && skb_shared(skb)) {\n\t\tskb->data = skb_head;\n\t\tskb->len = skb_len;\n\t}\ndrop:\n\tif (!is_drop_n_account)\n\t\tconsume_skb(skb);\n\telse\n\t\tkfree_skb(skb);\n\treturn 0;\n\ndrop_n_account:\n\tspin_unlock(&sk->sk_receive_queue.lock);\n\tatomic_inc(&po->tp_drops);\n\tis_drop_n_account = true;\n\n\tsk->sk_data_ready(sk);\n\tkfree_skb(copy_skb);\n\tgoto drop_n_restore;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'net/packet: fix overflow in tpacket_rcv\n\nUsing tp_reserve to calculate netoff can overflow as\ntp_reserve is unsigned int and netoff is unsigned short.\n\nThis may lead to macoff receving a smaller value then\nsizeof(struct virtio_net_hdr), and if po->has_vnet_hdr\nis set, an out-of-bounds write will occur when\ncalling virtio_net_hdr_from_skb.\n\nThe bug is fixed by converting netoff to unsigned int\nand checking if it exceeds USHRT_MAX.\n\nThis addresses CVE-2020-14386\n\nFixes: 8913336a7e8d (\"packet: add PACKET_RESERVE sockopt\")\nSigned-off-by: Or Cohen \nSigned-off-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: static BROTLI_INLINE size_t BrotliGetRemainingBytes(BrotliBitReader* br) {\n return br->avail_in + (BrotliGetAvailableBits(br) >> 3);\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: int main(int argc, char* argv[]) {\n ParseCommandLineFlags(&argc, &argv, true);\n if (argc != 3) {\n printf(\"usage: draw_histogram.cc data output_file\\n\");\n return 1;\n }\n\n int height = FLAGS_height;\n int width = FLAGS_width;\n\n FILE* fin = fopen(argv[1], \"r\");\n FILE* fout = fopen(argv[2], \"wb\");\n\n uint8_t** pixel = new uint8_t*[height];\n int** histo = new int*[height];\n for (int i = 0; i < height; i++) {\n pixel[i] = new uint8_t[width];\n histo[i] = new int[width];\n }\n\n BuildHistogram(fin, histo);\n fclose(fin);\n\n ConvertToPixels(histo, pixel);\n\n DrawPixels(pixel, fout);\n fclose(fout);\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'Update (#826)\n\n * IMPORTANT: decoder: fix potential overflow when input chunk is >2GiB\r\n * simplify max Huffman table size calculation\r\n * eliminate symbol duplicates (static arrays in .h files)\r\n * minor combing in research/ code'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void vgacon_flush_scrollback(struct vc_data *c)\n{\n\tsize_t size = CONFIG_VGACON_SOFT_SCROLLBACK_SIZE * 1024;\n\n\tvgacon_scrollback_reset(c->vc_num, size);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'vgacon: remove software scrollback support\n\nYunhai Zhang recently fixed a VGA software scrollback bug in commit\nebfdfeeae8c0 (\"vgacon: Fix for missing check in scrollback handling\"),\nbut that then made people look more closely at some of this code, and\nthere were more problems on the vgacon side, but also the fbcon software\nscrollback.\n\nWe don't really have anybody who maintains this code - probably because\nnobody actually _uses_ it any more. Sure, people still use both VGA and\nthe framebuffer consoles, but they are no longer the main user\ninterfaces to the kernel, and haven't been for decades, so these kinds\nof extra features end up bitrotting and not really being used.\n\nSo rather than try to maintain a likely unused set of code, I'll just\naggressively remove it, and see if anybody even notices. Maybe there\nare people who haven't jumped on the whole GUI badnwagon yet, and think\nit's just a fad. And maybe those people use the scrollback code.\n\nIf that turns out to be the case, we can resurrect this again, once\nwe've found the sucker^Wmaintainer for it who actually uses it.\n\nReported-by: NopNop Nop \nTested-by: Willy Tarreau \nCc: \u5f20\u4e91\u6d77 \nAcked-by: Andy Lutomirski \nAcked-by: Willy Tarreau \nReviewed-by: Greg Kroah-Hartman \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ssize_t rbd_image_refresh(struct device *dev,\n\t\t\t\t struct device_attribute *attr,\n\t\t\t\t const char *buf,\n\t\t\t\t size_t size)\n{\n\tstruct rbd_device *rbd_dev = dev_to_rbd_dev(dev);\n\tint ret;\n\n\tret = rbd_dev_refresh(rbd_dev);\n\tif (ret)\n\t\treturn ret;\n\n\treturn size;\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: static void cancel_att_send_op(struct att_send_op *op)\n{\n\tif (op->destroy)\n\t\top->destroy(op->user_data);\n\n\top->user_data = NULL;\n\top->callback = NULL;\n\top->destroy = NULL;\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: proto_register_fb_zero(void)\n{\n static hf_register_info hf[] = {\n { &hf_fb_zero_puflags,\n { \"Public Flags\", \"fb_zero.puflags\",\n FT_UINT8, BASE_HEX, NULL, 0x0,\n \"Specifying per-packet public flags\", HFILL }\n },\n { &hf_fb_zero_puflags_vrsn,\n { \"Version\", \"fb_zero.puflags.version\",\n FT_BOOLEAN, 8, TFS(&tfs_yes_no), PUFLAGS_VRSN,\n \"Signifies that this packet also contains the version of the FB Zero protocol\", HFILL }\n },\n { &hf_fb_zero_puflags_unknown,\n { \"Unknown\", \"fb_zero.puflags.unknown\",\n FT_UINT8, BASE_HEX, NULL, PUFLAGS_UNKN,\n NULL, HFILL }\n },\n\n { &hf_fb_zero_version,\n { \"Version\", \"fb_zero.version\",\n FT_STRING, BASE_NONE, NULL, 0x0,\n \"32 bit opaque tag that represents the version of the ZB Zero (Always QTV)\", HFILL }\n },\n { &hf_fb_zero_length,\n { \"Length\", \"fb_zero.length\",\n FT_UINT32, BASE_DEC, NULL, 0x0,\n NULL, HFILL }\n },\n { &hf_fb_zero_tag,\n { \"Tag\", \"fb_zero.tag\",\n FT_STRING, BASE_NONE, NULL, 0x0,\n NULL, HFILL }\n },\n { &hf_fb_zero_tag_number,\n { \"Tag Number\", \"fb_zero.tag_number\",\n FT_UINT16, BASE_DEC, NULL, 0x0,\n NULL, HFILL }\n },\n { &hf_fb_zero_tags,\n { \"Tag/value\", \"fb_zero.tags\",\n FT_NONE, BASE_NONE, NULL, 0x0,\n NULL, HFILL }\n },\n { &hf_fb_zero_tag_type,\n { \"Tag Type\", \"fb_zero.tag_type\",\n FT_STRING, BASE_NONE, NULL, 0x0,\n NULL, HFILL }\n },\n { &hf_fb_zero_tag_offset_end,\n { \"Tag offset end\", \"fb_zero.tag_offset_end\",\n FT_UINT32, BASE_DEC, NULL, 0x0,\n NULL, HFILL }\n },\n { &hf_fb_zero_tag_length,\n { \"Tag length\", \"fb_zero.tag_offset_length\",\n FT_UINT32, BASE_DEC, NULL, 0x0,\n NULL, HFILL }\n },\n { &hf_fb_zero_tag_value,\n { \"Tag/value\", \"fb_zero.tag_value\",\n FT_BYTES, BASE_NONE, NULL, 0x0,\n NULL, HFILL }\n },\n { &hf_fb_zero_tag_sni,\n { \"Server Name Indication\", \"fb_zero.tag.sni\",\n FT_STRING, BASE_NONE, NULL, 0x0,\n \"The fully qualified DNS name of the server, canonicalised to lowercase with no trailing period\", HFILL }\n },\n { &hf_fb_zero_tag_vers,\n { \"Version\", \"fb_zero.tag.version\",\n FT_STRING, BASE_NONE, NULL, 0x0,\n \"Version of FB Zero supported\", HFILL }\n },\n { &hf_fb_zero_tag_sno,\n { \"Server nonce\", \"fb_zero.tag.sno\",\n FT_BYTES, BASE_NONE, NULL, 0x0,\n NULL, HFILL }\n },\n { &hf_fb_zero_tag_aead,\n { \"Authenticated encryption algorithms\", \"fb_zero.tag.aead\",\n FT_STRING, BASE_NONE, NULL, 0x0,\n \"A list of tags, in preference order, specifying the AEAD primitives supported by the server\", HFILL }\n },\n { &hf_fb_zero_tag_scid,\n { \"Server Config ID\", \"fb_zero.tag.scid\",\n FT_BYTES, BASE_NONE, NULL, 0x0,\n \"An opaque, 16-byte identifier for this server config\", HFILL }\n },\n { &hf_fb_zero_tag_time,\n { \"Time\", \"fb_zero.tag.time\",\n FT_UINT32, BASE_DEC, NULL, 0x0,\n NULL, HFILL }\n },\n { &hf_fb_zero_tag_alpn,\n { \"ALPN\", \"fb_zero.tag.alpn\",\n FT_STRING, BASE_NONE, NULL, 0x0,\n \"Application-Layer Protocol Negotiation supported\", HFILL }\n },\n { &hf_fb_zero_tag_pubs,\n { \"Public value\", \"fb_zero.tag.pubs\",\n FT_UINT24, BASE_DEC_HEX, NULL, 0x0,\n \"A list of public values, 24-bit, little-endian length prefixed\", HFILL }\n },\n { &hf_fb_zero_tag_kexs,\n { \"Key exchange algorithms\", \"fb_zero.tag.kexs\",\n FT_STRING, BASE_NONE, NULL, 0x0,\n \"A list of tags, in preference order, specifying the key exchange algorithms that the server supports\", HFILL }\n },\n { &hf_fb_zero_tag_nonc,\n { \"Client nonce\", \"fb_zero.tag.nonc\",\n FT_BYTES, BASE_NONE, NULL, 0x0,\n \"32 bytes consisting of 4 bytes of timestamp (big-endian, UNIX epoch seconds), 8 bytes of server orbit and 20 bytes of random data\", HFILL }\n },\n { &hf_fb_zero_tag_unknown,\n { \"Unknown tag\", \"fb_zero.tag.unknown\",\n FT_BYTES, BASE_NONE, NULL, 0x0,\n NULL, HFILL }\n },\n { &hf_fb_zero_padding,\n { \"Padding\", \"fb_zero.padding\",\n FT_BYTES, BASE_NONE, NULL, 0x0,\n NULL, HFILL }\n },\n { &hf_fb_zero_payload,\n { \"Payload\", \"fb_zero.payload\",\n FT_BYTES, BASE_NONE, NULL, 0x0,\n \"Fb Zero Payload..\", HFILL }\n },\n { &hf_fb_zero_unknown,\n { \"Unknown\", \"fb_zero.unknown\",\n FT_BYTES, BASE_NONE, NULL, 0x0,\n \"Unknown Data\", HFILL }\n },\n };\n\n\n static gint *ett[] = {\n &ett_fb_zero,\n &ett_fb_zero_puflags,\n &ett_fb_zero_prflags,\n &ett_fb_zero_ft,\n &ett_fb_zero_ftflags,\n &ett_fb_zero_tag_value\n };\n\n static ei_register_info ei[] = {\n { &ei_fb_zero_tag_undecoded, { \"fb_zero.tag.undecoded\", PI_UNDECODED, PI_NOTE, \"Dissector for FB Zero Tag code not implemented, Contact Wireshark developers if you want this supported\", EXPFILL }},\n { &ei_fb_zero_tag_length, { \"fb_zero.tag.length.truncated\", PI_MALFORMED, PI_NOTE, \"Truncated Tag Length...\", EXPFILL }},\n { &ei_fb_zero_tag_unknown, { \"fb_zero.tag.unknown.data\", PI_UNDECODED, PI_NOTE, \"Unknown Data\", EXPFILL }},\n };\n\n expert_module_t *expert_fb_zero;\n\n proto_fb_zero = proto_register_protocol(\"(Facebook) Zero Protocol\", \"FBZERO\", \"fb_zero\");\n\n fb_zero_handle = register_dissector(\"fb_zero\", dissect_fb_zero, proto_fb_zero);\n\n proto_register_field_array(proto_fb_zero, hf, array_length(hf));\n proto_register_subtree_array(ett, array_length(ett));\n\n expert_fb_zero = expert_register_protocol(proto_fb_zero);\n expert_register_field_array(expert_fb_zero, ei, array_length(ei));\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 gboolean udscs_server_accept_cb(GSocketService *service,\n GSocketConnection *socket_conn,\n GObject *source_object,\n gpointer user_data)\n{\n struct udscs_server *server = user_data;\n UdscsConnection *new_conn;\n\n new_conn = g_object_new(UDSCS_TYPE_CONNECTION, NULL);\n new_conn->debug = server->debug;\n new_conn->read_callback = server->read_callback;\n g_object_ref(socket_conn);\n vdagent_connection_setup(VDAGENT_CONNECTION(new_conn),\n G_IO_STREAM(socket_conn),\n FALSE,\n sizeof(struct udscs_message_header),\n server->error_cb);\n\n server->connections = g_list_prepend(server->connections, new_conn);\n\n if (server->debug)\n syslog(LOG_DEBUG, \"new client accepted: %p\", new_conn);\n\n if (server->connect_callback)\n server->connect_callback(new_conn);\n\n return TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-770'], 'message': 'Avoids unlimited agent connections\n\nLimit the number of agents that can be connected.\nAvoids reaching the maximum number of files in a process.\nBeside one file descriptor per agent the daemon open just some\nother fixed number of files.\n\nThis issue was reported by SUSE security team.\n\nSigned-off-by: Frediano Ziglio '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: AuthenticodeVerify (\r\n IN CONST UINT8 *AuthData,\r\n IN UINTN DataSize,\r\n IN CONST UINT8 *TrustedCert,\r\n IN UINTN CertSize,\r\n IN CONST UINT8 *ImageHash,\r\n IN UINTN HashSize\r\n )\r\n{\r\n BOOLEAN Status;\r\n PKCS7 *Pkcs7;\r\n CONST UINT8 *Temp;\r\n CONST UINT8 *OrigAuthData;\r\n UINT8 *SpcIndirectDataContent;\r\n UINT8 Asn1Byte;\r\n UINTN ContentSize;\r\n CONST UINT8 *SpcIndirectDataOid;\r\n\r\n //\r\n // Check input parameters.\r\n //\r\n if ((AuthData == NULL) || (TrustedCert == NULL) || (ImageHash == NULL)) {\r\n return FALSE;\r\n }\r\n\r\n if ((DataSize > INT_MAX) || (CertSize > INT_MAX) || (HashSize > INT_MAX)) {\r\n return FALSE;\r\n }\r\n\r\n Status = FALSE;\r\n Pkcs7 = NULL;\r\n OrigAuthData = AuthData;\r\n\r\n //\r\n // Retrieve & Parse PKCS#7 Data (DER encoding) from Authenticode Signature\r\n //\r\n Temp = AuthData;\r\n Pkcs7 = d2i_PKCS7 (NULL, &Temp, (int)DataSize);\r\n if (Pkcs7 == NULL) {\r\n goto _Exit;\r\n }\r\n\r\n //\r\n // Check if it's PKCS#7 Signed Data (for Authenticode Scenario)\r\n //\r\n if (!PKCS7_type_is_signed (Pkcs7)) {\r\n goto _Exit;\r\n }\r\n\r\n //\r\n // NOTE: OpenSSL PKCS7 Decoder didn't work for Authenticode-format signed data due to\r\n // some authenticode-specific structure. Use opaque ASN.1 string to retrieve\r\n // PKCS#7 ContentInfo here.\r\n //\r\n SpcIndirectDataOid = OBJ_get0_data(Pkcs7->d.sign->contents->type);\r\n if (OBJ_length(Pkcs7->d.sign->contents->type) != sizeof(mSpcIndirectOidValue) ||\r\n CompareMem (\r\n SpcIndirectDataOid,\r\n mSpcIndirectOidValue,\r\n sizeof (mSpcIndirectOidValue)\r\n ) != 0) {\r\n //\r\n // Un-matched SPC_INDIRECT_DATA_OBJID.\r\n //\r\n goto _Exit;\r\n }\r\n\r\n\r\n SpcIndirectDataContent = (UINT8 *)(Pkcs7->d.sign->contents->d.other->value.asn1_string->data);\r\n\r\n //\r\n // Retrieve the SEQUENCE data size from ASN.1-encoded SpcIndirectDataContent.\r\n //\r\n Asn1Byte = *(SpcIndirectDataContent + 1);\r\n\r\n if ((Asn1Byte & 0x80) == 0) {\r\n //\r\n // Short Form of Length Encoding (Length < 128)\r\n //\r\n ContentSize = (UINTN) (Asn1Byte & 0x7F);\r\n //\r\n // Skip the SEQUENCE Tag;\r\n //\r\n SpcIndirectDataContent += 2;\r\n\r\n } else if ((Asn1Byte & 0x81) == 0x81) {\r\n //\r\n // Long Form of Length Encoding (128 <= Length < 255, Single Octet)\r\n //\r\n ContentSize = (UINTN) (*(UINT8 *)(SpcIndirectDataContent + 2));\r\n //\r\n // Skip the SEQUENCE Tag;\r\n //\r\n SpcIndirectDataContent += 3;\r\n\r\n } else if ((Asn1Byte & 0x82) == 0x82) {\r\n //\r\n // Long Form of Length Encoding (Length > 255, Two Octet)\r\n //\r\n ContentSize = (UINTN) (*(UINT8 *)(SpcIndirectDataContent + 2));\r\n ContentSize = (ContentSize << 8) + (UINTN)(*(UINT8 *)(SpcIndirectDataContent + 3));\r\n //\r\n // Skip the SEQUENCE Tag;\r\n //\r\n SpcIndirectDataContent += 4;\r\n\r\n } else {\r\n goto _Exit;\r\n }\r\n\r\n //\r\n // Compare the original file hash value to the digest retrieve from SpcIndirectDataContent\r\n // defined in Authenticode\r\n // NOTE: Need to double-check HashLength here!\r\n //\r\n if (CompareMem (SpcIndirectDataContent + ContentSize - HashSize, ImageHash, HashSize) != 0) {\r\n //\r\n // Un-matched PE/COFF Hash Value\r\n //\r\n goto _Exit;\r\n }\r\n\r\n //\r\n // Verifies the PKCS#7 Signed Data in PE/COFF Authenticode Signature\r\n //\r\n Status = (BOOLEAN) Pkcs7Verify (OrigAuthData, DataSize, TrustedCert, CertSize, SpcIndirectDataContent, ContentSize);\r\n\r\n_Exit:\r\n //\r\n // Release Resources\r\n //\r\n PKCS7_free (Pkcs7);\r\n\r\n return Status;\r\n}\r ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'CryptoPkg/BaseCryptLib: fix NULL dereference (CVE-2019-14584)\n\nREF: https://bugzilla.tianocore.org/show_bug.cgi?id=1914\n\nAuthenticodeVerify() calls OpenSSLs d2i_PKCS7() API to parse asn encoded\nsigned authenticode pkcs#7 data. when this successfully returns, a type\ncheck is done by calling PKCS7_type_is_signed() and then\nPkcs7->d.sign->contents->type is used. It is possible to construct an asn1\nblob that successfully decodes and have d2i_PKCS7() return a valid pointer\nand have PKCS7_type_is_signed() also return success but have Pkcs7->d.sign\nbe a NULL pointer.\n\nLooking at how PKCS7_verify() [inside of OpenSSL] implements checking for\npkcs7 structs it does the following:\n- call PKCS7_type_is_signed()\n- call PKCS7_get_detached()\nLooking into how PKCS7_get_detatched() is implemented, it checks to see if\np7->d.sign is NULL or if p7->d.sign->contents->d.ptr is NULL.\n\nAs such, the fix is to do the same as OpenSSL after calling d2i_PKCS7().\n- Add call to PKS7_get_detached() to existing error handling\n\nCc: Xiaoyu Lu \nCc: Guomin Jiang \nCc: Jiewen Yao \nCc: Laszlo Ersek \nSigned-off-by: Jian J Wang \nReviewed-by: Laszlo Ersek \nReviewed-by: Jiewen Yao '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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_unknown(\n\tfastd_socket_t *sock, const fastd_peer_address_t *local_addr, const fastd_peer_address_t *remote_addr,\n\tfastd_buffer_t *buffer) {\n\tconst uint8_t *packet_type = buffer->data;\n\n\tswitch (*packet_type) {\n\tcase PACKET_DATA:\n\t\tfastd_buffer_free(buffer);\n\n\t\tif (!backoff_unknown(remote_addr)) {\n\t\t\tpr_debug(\"unexpectedly received payload data from unknown address %I\", remote_addr);\n\t\t\tconf.protocol->handshake_init(sock, local_addr, remote_addr, NULL);\n\t\t}\n\t\tbreak;\n\n\tcase PACKET_HANDSHAKE:\n\t\tfastd_handshake_handle(sock, local_addr, remote_addr, NULL, 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: static void __evtchn_fifo_handle_events(unsigned cpu, bool drop)\n{\n\tstruct evtchn_fifo_control_block *control_block;\n\tunsigned long ready;\n\tunsigned q;\n\n\tcontrol_block = per_cpu(cpu_control_block, cpu);\n\n\tready = xchg(&control_block->ready, 0);\n\n\twhile (ready) {\n\t\tq = find_first_bit(&ready, EVTCHN_FIFO_MAX_QUEUES);\n\t\tconsume_one_event(cpu, control_block, q, &ready, drop);\n\t\tready |= xchg(&control_block->ready, 0);\n\t}\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: static void clear_evtchn_to_irq_row(unsigned row)\n{\n\tunsigned col;\n\n\tfor (col = 0; col < EVTCHN_PER_ROW; col++)\n\t\tevtchn_to_irq[row][col] = -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362', 'CWE-476'], 'message': 'xen/events: avoid removing an event channel while handling it\n\nToday it can happen that an event channel is being removed from the\nsystem while the event handling loop is active. This can lead to a\nrace resulting in crashes or WARN() splats when trying to access the\nirq_info structure related to the event channel.\n\nFix this problem by using a rwlock taken as reader in the event\nhandling loop and as writer when deallocating the irq_info structure.\n\nAs the observed problem was a NULL dereference in evtchn_from_irq()\nmake this function more robust against races by testing the irq_info\npointer to be not NULL before dereferencing it.\n\nAnd finally make all accesses to evtchn_to_irq[row][col] atomic ones\nin order to avoid seeing partial updates of an array element in irq\nhandling. Note that irq handling can be entered only for event channels\nwhich have been valid before, so any not populated row isn't a problem\nin this regard, as rows are only ever added and never removed.\n\nThis is XSA-331.\n\nCc: stable@vger.kernel.org\nReported-by: Marek Marczykowski-G\u00f3recki \nReported-by: Jinoh Kang \nSigned-off-by: Juergen Gross \nReviewed-by: Stefano Stabellini \nReviewed-by: Wei Liu '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: MagickExport Image *CropImageToTiles(const Image *image,\n const char *crop_geometry,ExceptionInfo *exception)\n{\n Image\n *next,\n *crop_image;\n\n MagickStatusType\n flags;\n\n RectangleInfo\n geometry;\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 crop_image=NewImageList();\n next=NewImageList();\n flags=ParseGravityGeometry(image,crop_geometry,&geometry,exception);\n if ((flags & AreaValue) != 0)\n {\n PointInfo\n delta,\n offset;\n\n RectangleInfo\n crop;\n\n size_t\n height,\n width;\n\n /*\n Crop into NxM tiles (@ flag).\n */\n width=image->columns;\n height=image->rows;\n if (geometry.width == 0)\n geometry.width=1;\n if (geometry.height == 0)\n geometry.height=1;\n if ((flags & AspectValue) == 0)\n {\n width-=(geometry.x < 0 ? -1 : 1)*geometry.x;\n height-=(geometry.y < 0 ? -1 : 1)*geometry.y;\n }\n else\n {\n width+=(geometry.x < 0 ? -1 : 1)*geometry.x;\n height+=(geometry.y < 0 ? -1 : 1)*geometry.y;\n }\n delta.x=(double) width/geometry.width;\n delta.y=(double) height/geometry.height;\n if (delta.x < 1.0)\n delta.x=1.0;\n if (delta.y < 1.0)\n delta.y=1.0;\n for (offset.y=0; offset.y < (double) height; )\n {\n if ((flags & AspectValue) == 0)\n {\n crop.y=(ssize_t) MagickRound((double) (offset.y-\n (geometry.y > 0 ? 0 : geometry.y)));\n offset.y+=delta.y; /* increment now to find width */\n crop.height=(size_t) MagickRound((double) (offset.y+\n (geometry.y < 0 ? 0 : geometry.y)));\n }\n else\n {\n crop.y=(ssize_t) MagickRound((double) (offset.y-\n (geometry.y > 0 ? geometry.y : 0)));\n offset.y+=delta.y; /* increment now to find width */\n crop.height=(size_t) MagickRound((double)\n (offset.y+(geometry.y < -1 ? geometry.y : 0)));\n }\n crop.height-=crop.y;\n crop.y+=image->page.y;\n for (offset.x=0; offset.x < (double) width; )\n {\n if ((flags & AspectValue) == 0)\n {\n crop.x=(ssize_t) MagickRound((double) (offset.x-\n (geometry.x > 0 ? 0 : geometry.x)));\n offset.x+=delta.x; /* increment now to find height */\n crop.width=(size_t) MagickRound((double) (offset.x+\n (geometry.x < 0 ? 0 : geometry.x)));\n }\n else\n {\n crop.x=(ssize_t) MagickRound((double) (offset.x-\n (geometry.x > 0 ? geometry.x : 0)));\n offset.x+=delta.x; /* increment now to find height */\n crop.width=(size_t) MagickRound((double) (offset.x+\n (geometry.x < 0 ? geometry.x : 0)));\n }\n crop.width-=crop.x;\n crop.x+=image->page.x;\n next=CropImage(image,&crop,exception);\n if (next != (Image *) NULL)\n AppendImageToList(&crop_image,next);\n }\n }\n ClearMagickException(exception);\n return(crop_image);\n }\n if (((geometry.width == 0) && (geometry.height == 0)) ||\n ((flags & XValue) != 0) || ((flags & YValue) != 0))\n {\n /*\n Crop a single region at +X+Y.\n */\n crop_image=CropImage(image,&geometry,exception);\n if ((crop_image != (Image *) NULL) && ((flags & AspectValue) != 0))\n {\n crop_image->page.width=geometry.width;\n crop_image->page.height=geometry.height;\n crop_image->page.x-=geometry.x;\n crop_image->page.y-=geometry.y;\n }\n return(crop_image);\n }\n if ((image->columns > geometry.width) || (image->rows > geometry.height))\n {\n RectangleInfo\n page;\n\n size_t\n height,\n width;\n\n ssize_t\n x,\n y;\n\n /*\n Crop into tiles of fixed size WxH.\n */\n page=image->page;\n if (page.width == 0)\n page.width=image->columns;\n if (page.height == 0)\n page.height=image->rows;\n width=geometry.width;\n if (width == 0)\n width=page.width;\n height=geometry.height;\n if (height == 0)\n height=page.height;\n next=NewImageList();\n for (y=0; y < (ssize_t) page.height; y+=(ssize_t) height)\n {\n for (x=0; x < (ssize_t) page.width; x+=(ssize_t) width)\n {\n geometry.width=width;\n geometry.height=height;\n geometry.x=x;\n geometry.y=y;\n next=CropImage(image,&geometry,exception);\n if (next == (Image *) NULL)\n break;\n AppendImageToList(&crop_image,next);\n }\n if (next == (Image *) NULL)\n break;\n }\n return(crop_image);\n }\n return(CloneImage(image,0,0,MagickTrue,exception));\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_enable(struct sunkbd *sunkbd, bool enable)\n{\n\tserio_pause_rx(sunkbd->serio);\n\tsunkbd->enabled = enable;\n\tserio_continue_rx(sunkbd->serio);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Input: sunkbd - avoid use-after-free in teardown paths\n\nWe need to make sure we cancel the reinit work before we tear down the\ndriver structures.\n\nReported-by: Bodong Zhao \nTested-by: Bodong Zhao \nCc: stable@vger.kernel.org\nSigned-off-by: Dmitry Torokhov '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline int do_fontx_ioctl(int cmd,\n\t\tstruct consolefontdesc __user *user_cfd,\n\t\tstruct console_font_op *op)\n{\n\tstruct consolefontdesc cfdarg;\n\tint i;\n\n\tif (copy_from_user(&cfdarg, user_cfd, sizeof(struct consolefontdesc)))\n\t\treturn -EFAULT;\n\n\tswitch (cmd) {\n\tcase PIO_FONTX:\n\t\top->op = KD_FONT_OP_SET;\n\t\top->flags = KD_FONT_FLAG_OLD;\n\t\top->width = 8;\n\t\top->height = cfdarg.charheight;\n\t\top->charcount = cfdarg.charcount;\n\t\top->data = cfdarg.chardata;\n\t\treturn con_font_op(vc_cons[fg_console].d, op);\n\tcase GIO_FONTX: {\n\t\top->op = KD_FONT_OP_GET;\n\t\top->flags = KD_FONT_FLAG_OLD;\n\t\top->width = 8;\n\t\top->height = cfdarg.charheight;\n\t\top->charcount = cfdarg.charcount;\n\t\top->data = cfdarg.chardata;\n\t\ti = con_font_op(vc_cons[fg_console].d, op);\n\t\tif (i)\n\t\t\treturn i;\n\t\tcfdarg.charheight = op->height;\n\t\tcfdarg.charcount = op->charcount;\n\t\tif (copy_to_user(user_cfd, &cfdarg, sizeof(struct consolefontdesc)))\n\t\t\treturn -EFAULT;\n\t\treturn 0;\n\t\t}\n\t}\n\treturn -EINVAL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-662'], 'message': 'tty: make FONTX ioctl use the tty pointer they were actually passed\n\nSome of the font tty ioctl's always used the current foreground VC for\ntheir operations. Don't do that then.\n\nThis fixes a data race on fg_console.\n\nSide note: both Michael Ellerman and Jiri Slaby point out that all these\nioctls are deprecated, and should probably have been removed long ago,\nand everything seems to be using the KDFONTOP ioctl instead.\n\nIn fact, Michael points out that it looks like busybox's loadfont\nprogram seems to have switched over to using KDFONTOP exactly _because_\nof this bug (ahem.. 12 years ago ;-).\n\nReported-by: Minh Yuan \nAcked-by: Michael Ellerman \nAcked-by: Jiri Slaby \nCc: Greg KH \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline QuantumAny ScaleQuantumToAny(const Quantum quantum,\n const QuantumAny range)\n{\n return((QuantumAny) (((double) range*quantum)/QuantumRange+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/1712'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: MagickPrivate ResizeFilter *AcquireResizeFilter(const Image *image,\n const FilterType filter,const MagickBooleanType cylindrical,\n ExceptionInfo *exception)\n{\n const char\n *artifact;\n\n FilterType\n filter_type,\n window_type;\n\n double\n B,\n C,\n value;\n\n register ResizeFilter\n *resize_filter;\n\n /*\n Table Mapping given Filter, into Weighting and Windowing functions.\n A 'Box' windowing function means its a simble non-windowed filter.\n An 'SincFast' filter function could be upgraded to a 'Jinc' filter if a\n \"cylindrical\" is requested, unless a 'Sinc' or 'SincFast' filter was\n specifically requested by the user.\n\n WARNING: The order of this table must match the order of the FilterType\n enumeration specified in \"resample.h\", or the filter names will not match\n the filter being setup.\n\n You can check filter setups with the \"filter:verbose\" expert setting.\n */\n static struct\n {\n FilterType\n filter,\n window;\n } const mapping[SentinelFilter] =\n {\n { UndefinedFilter, BoxFilter }, /* Undefined (default to Box) */\n { PointFilter, BoxFilter }, /* SPECIAL: Nearest neighbour */\n { BoxFilter, BoxFilter }, /* Box averaging filter */\n { TriangleFilter, BoxFilter }, /* Linear interpolation filter */\n { HermiteFilter, BoxFilter }, /* Hermite interpolation filter */\n { SincFastFilter, HannFilter }, /* Hann -- cosine-sinc */\n { SincFastFilter, HammingFilter }, /* Hamming -- '' variation */\n { SincFastFilter, BlackmanFilter }, /* Blackman -- 2*cosine-sinc */\n { GaussianFilter, BoxFilter }, /* Gaussian blur filter */\n { QuadraticFilter, BoxFilter }, /* Quadratic Gaussian approx */\n { CubicFilter, BoxFilter }, /* General Cubic Filter, Spline */\n { CatromFilter, BoxFilter }, /* Cubic-Keys interpolator */\n { MitchellFilter, BoxFilter }, /* 'Ideal' Cubic-Keys filter */\n { JincFilter, BoxFilter }, /* Raw 3-lobed Jinc function */\n { SincFilter, BoxFilter }, /* Raw 4-lobed Sinc function */\n { SincFastFilter, BoxFilter }, /* Raw fast sinc (\"Pade\"-type) */\n { SincFastFilter, KaiserFilter }, /* Kaiser -- square root-sinc */\n { LanczosFilter, WelchFilter }, /* Welch -- parabolic (3 lobe) */\n { SincFastFilter, CubicFilter }, /* Parzen -- cubic-sinc */\n { SincFastFilter, BohmanFilter }, /* Bohman -- 2*cosine-sinc */\n { SincFastFilter, TriangleFilter }, /* Bartlett -- triangle-sinc */\n { LagrangeFilter, BoxFilter }, /* Lagrange self-windowing */\n { LanczosFilter, LanczosFilter }, /* Lanczos Sinc-Sinc filters */\n { LanczosSharpFilter, LanczosSharpFilter }, /* | these require */\n { Lanczos2Filter, Lanczos2Filter }, /* | special handling */\n { Lanczos2SharpFilter, Lanczos2SharpFilter },\n { RobidouxFilter, BoxFilter }, /* Cubic Keys tuned for EWA */\n { RobidouxSharpFilter, BoxFilter }, /* Sharper Cubic Keys for EWA */\n { LanczosFilter, CosineFilter }, /* Cosine window (3 lobes) */\n { SplineFilter, BoxFilter }, /* Spline Cubic Filter */\n { LanczosRadiusFilter, LanczosFilter }, /* Lanczos with integer radius */\n { CubicSplineFilter, BoxFilter }, /* CubicSpline (2/3/4 lobes) */\n };\n /*\n Table mapping the filter/window from the above table to an actual function.\n The default support size for that filter as a weighting function, the range\n to scale with to use that function as a sinc windowing function, (typ 1.0).\n\n Note that the filter_type -> function is 1 to 1 except for Sinc(),\n SincFast(), and CubicBC() functions, which may have multiple filter to\n function associations.\n\n See \"filter:verbose\" handling below for the function -> filter mapping.\n */\n static struct\n {\n double\n (*function)(const double,const ResizeFilter*),\n support, /* Default lobes/support size of the weighting filter. */\n scale, /* Support when function used as a windowing function\n Typically equal to the location of the first zero crossing. */\n B,C; /* BC-spline coefficients, ignored if not a CubicBC filter. */\n ResizeWeightingFunctionType weightingFunctionType;\n } const filters[SentinelFilter] =\n {\n /* .--- support window (if used as a Weighting Function)\n | .--- first crossing (if used as a Windowing Function)\n | | .--- B value for Cubic Function\n | | | .---- C value for Cubic Function\n | | | | */\n { Box, 0.5, 0.5, 0.0, 0.0, BoxWeightingFunction }, /* Undefined (default to Box) */\n { Box, 0.0, 0.5, 0.0, 0.0, BoxWeightingFunction }, /* Point (special handling) */\n { Box, 0.5, 0.5, 0.0, 0.0, BoxWeightingFunction }, /* Box */\n { Triangle, 1.0, 1.0, 0.0, 0.0, TriangleWeightingFunction }, /* Triangle */\n { CubicBC, 1.0, 1.0, 0.0, 0.0, CubicBCWeightingFunction }, /* Hermite (cubic B=C=0) */\n { Hann, 1.0, 1.0, 0.0, 0.0, HannWeightingFunction }, /* Hann, cosine window */\n { Hamming, 1.0, 1.0, 0.0, 0.0, HammingWeightingFunction }, /* Hamming, '' variation */\n { Blackman, 1.0, 1.0, 0.0, 0.0, BlackmanWeightingFunction }, /* Blackman, 2*cosine window */\n { Gaussian, 2.0, 1.5, 0.0, 0.0, GaussianWeightingFunction }, /* Gaussian */\n { Quadratic, 1.5, 1.5, 0.0, 0.0, QuadraticWeightingFunction },/* Quadratic gaussian */\n { CubicBC, 2.0, 2.0, 1.0, 0.0, CubicBCWeightingFunction }, /* General Cubic Filter */\n { CubicBC, 2.0, 1.0, 0.0, 0.5, CubicBCWeightingFunction }, /* Catmull-Rom (B=0,C=1/2) */\n { CubicBC, 2.0, 8.0/7.0, 1./3., 1./3., CubicBCWeightingFunction }, /* Mitchell (B=C=1/3) */\n { Jinc, 3.0, 1.2196698912665045, 0.0, 0.0, JincWeightingFunction }, /* Raw 3-lobed Jinc */\n { Sinc, 4.0, 1.0, 0.0, 0.0, SincWeightingFunction }, /* Raw 4-lobed Sinc */\n { SincFast, 4.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Raw fast sinc (\"Pade\"-type) */\n { Kaiser, 1.0, 1.0, 0.0, 0.0, KaiserWeightingFunction }, /* Kaiser (square root window) */\n { Welch, 1.0, 1.0, 0.0, 0.0, WelchWeightingFunction }, /* Welch (parabolic window) */\n { CubicBC, 2.0, 2.0, 1.0, 0.0, CubicBCWeightingFunction }, /* Parzen (B-Spline window) */\n { Bohman, 1.0, 1.0, 0.0, 0.0, BohmanWeightingFunction }, /* Bohman, 2*Cosine window */\n { Triangle, 1.0, 1.0, 0.0, 0.0, TriangleWeightingFunction }, /* Bartlett (triangle window) */\n { Lagrange, 2.0, 1.0, 0.0, 0.0, LagrangeWeightingFunction }, /* Lagrange sinc approximation */\n { SincFast, 3.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos, 3-lobed Sinc-Sinc */\n { SincFast, 3.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos, Sharpened */\n { SincFast, 2.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos, 2-lobed */\n { SincFast, 2.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos2, sharpened */\n /* Robidoux: Keys cubic close to Lanczos2D sharpened */\n { CubicBC, 2.0, 1.1685777620836932,\n 0.37821575509399867, 0.31089212245300067, CubicBCWeightingFunction },\n /* RobidouxSharp: Sharper version of Robidoux */\n { CubicBC, 2.0, 1.105822933719019,\n 0.2620145123990142, 0.3689927438004929, CubicBCWeightingFunction },\n { Cosine, 1.0, 1.0, 0.0, 0.0, CosineWeightingFunction }, /* Low level cosine window */\n { CubicBC, 2.0, 2.0, 1.0, 0.0, CubicBCWeightingFunction }, /* Cubic B-Spline (B=1,C=0) */\n { SincFast, 3.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos, Interger Radius */\n { CubicSpline,2.0, 0.5, 0.0, 0.0, BoxWeightingFunction }, /* Spline Lobes 2-lobed */\n };\n /*\n The known zero crossings of the Jinc() or more accurately the Jinc(x*PI)\n function being used as a filter. It is used by the \"filter:lobes\" expert\n setting and for 'lobes' for Jinc functions in the previous table. This way\n users do not have to deal with the highly irrational lobe sizes of the Jinc\n filter.\n\n Values taken from\n http://cose.math.bas.bg/webMathematica/webComputing/BesselZeros.jsp\n using Jv-function with v=1, then dividing by PI.\n */\n static double\n jinc_zeros[16] =\n {\n 1.2196698912665045,\n 2.2331305943815286,\n 3.2383154841662362,\n 4.2410628637960699,\n 5.2427643768701817,\n 6.2439216898644877,\n 7.2447598687199570,\n 8.2453949139520427,\n 9.2458926849494673,\n 10.246293348754916,\n 11.246622794877883,\n 12.246898461138105,\n 13.247132522181061,\n 14.247333735806849,\n 15.247508563037300,\n 16.247661874700962\n };\n\n /*\n Allocate resize filter.\n */\n assert(image != (const Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(UndefinedFilter < filter && filter < SentinelFilter);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n (void) exception;\n resize_filter=(ResizeFilter *) AcquireCriticalMemory(sizeof(*resize_filter));\n (void) memset(resize_filter,0,sizeof(*resize_filter));\n /*\n Defaults for the requested filter.\n */\n filter_type=mapping[filter].filter;\n window_type=mapping[filter].window;\n resize_filter->blur=1.0;\n /* Promote 1D Windowed Sinc Filters to a 2D Windowed Jinc filters */\n if ((cylindrical != MagickFalse) && (filter_type == SincFastFilter) &&\n (filter != SincFastFilter))\n filter_type=JincFilter; /* 1D Windowed Sinc => 2D Windowed Jinc filters */\n\n /* Expert filter setting override */\n artifact=GetImageArtifact(image,\"filter:filter\");\n if (IsStringTrue(artifact) != MagickFalse)\n {\n ssize_t\n option;\n\n option=ParseCommandOption(MagickFilterOptions,MagickFalse,artifact);\n if ((UndefinedFilter < option) && (option < SentinelFilter))\n { /* Raw filter request - no window function. */\n filter_type=(FilterType) option;\n window_type=BoxFilter;\n }\n /* Filter override with a specific window function. */\n artifact=GetImageArtifact(image,\"filter:window\");\n if (artifact != (const char *) NULL)\n {\n option=ParseCommandOption(MagickFilterOptions,MagickFalse,artifact);\n if ((UndefinedFilter < option) && (option < SentinelFilter))\n window_type=(FilterType) option;\n }\n }\n else\n {\n /* Window specified, but no filter function? Assume Sinc/Jinc. */\n artifact=GetImageArtifact(image,\"filter:window\");\n if (artifact != (const char *) NULL)\n {\n ssize_t\n option;\n\n option=ParseCommandOption(MagickFilterOptions,MagickFalse,artifact);\n if ((UndefinedFilter < option) && (option < SentinelFilter))\n {\n filter_type= cylindrical != MagickFalse ? JincFilter\n : SincFastFilter;\n window_type=(FilterType) option;\n }\n }\n }\n\n /* Assign the real functions to use for the filters selected. */\n resize_filter->filter=filters[filter_type].function;\n resize_filter->support=filters[filter_type].support;\n resize_filter->filterWeightingType=filters[filter_type].weightingFunctionType;\n resize_filter->window=filters[window_type].function;\n resize_filter->windowWeightingType=filters[window_type].weightingFunctionType;\n resize_filter->scale=filters[window_type].scale;\n resize_filter->signature=MagickCoreSignature;\n\n /* Filter Modifications for orthogonal/cylindrical usage */\n if (cylindrical != MagickFalse)\n switch (filter_type)\n {\n case BoxFilter:\n /* Support for Cylindrical Box should be sqrt(2)/2 */\n resize_filter->support=(double) MagickSQ1_2;\n break;\n case LanczosFilter:\n case LanczosSharpFilter:\n case Lanczos2Filter:\n case Lanczos2SharpFilter:\n case LanczosRadiusFilter:\n resize_filter->filter=filters[JincFilter].function;\n resize_filter->window=filters[JincFilter].function;\n resize_filter->scale=filters[JincFilter].scale;\n /* number of lobes (support window size) remain unchanged */\n break;\n default:\n break;\n }\n /* Global Sharpening (regardless of orthoginal/cylindrical) */\n switch (filter_type)\n {\n case LanczosSharpFilter:\n resize_filter->blur *= 0.9812505644269356;\n break;\n case Lanczos2SharpFilter:\n resize_filter->blur *= 0.9549963639785485;\n break;\n /* case LanczosRadius: blur adjust is done after lobes */\n default:\n break;\n }\n\n /*\n Expert Option Modifications.\n */\n\n /* User Gaussian Sigma Override - no support change */\n if ((resize_filter->filter == Gaussian) ||\n (resize_filter->window == Gaussian) ) {\n value=0.5; /* guassian sigma default, half pixel */\n artifact=GetImageArtifact(image,\"filter:sigma\");\n if (artifact != (const char *) NULL)\n value=StringToDouble(artifact,(char **) NULL);\n /* Define coefficents for Gaussian */\n resize_filter->coefficient[0]=value; /* note sigma too */\n resize_filter->coefficient[1]=PerceptibleReciprocal(2.0*value*value); /* sigma scaling */\n resize_filter->coefficient[2]=PerceptibleReciprocal(Magick2PI*value*value);\n /* normalization - not actually needed or used! */\n if ( value > 0.5 )\n resize_filter->support *= 2*value; /* increase support linearly */\n }\n\n /* User Kaiser Alpha Override - no support change */\n if ((resize_filter->filter == Kaiser) ||\n (resize_filter->window == Kaiser) ) {\n value=6.5; /* default beta value for Kaiser bessel windowing function */\n artifact=GetImageArtifact(image,\"filter:alpha\"); /* FUTURE: depreciate */\n if (artifact != (const char *) NULL)\n value=StringToDouble(artifact,(char **) NULL);\n artifact=GetImageArtifact(image,\"filter:kaiser-beta\");\n if (artifact != (const char *) NULL)\n value=StringToDouble(artifact,(char **) NULL);\n artifact=GetImageArtifact(image,\"filter:kaiser-alpha\");\n if (artifact != (const char *) NULL)\n value=StringToDouble(artifact,(char **) NULL)*MagickPI;\n /* Define coefficents for Kaiser Windowing Function */\n resize_filter->coefficient[0]=value; /* alpha */\n resize_filter->coefficient[1]=PerceptibleReciprocal(I0(value));\n /* normalization */\n }\n\n /* Support Overrides */\n artifact=GetImageArtifact(image,\"filter:lobes\");\n if (artifact != (const char *) NULL)\n {\n ssize_t\n lobes;\n\n lobes=(ssize_t) StringToLong(artifact);\n if (lobes < 1)\n lobes=1;\n resize_filter->support=(double) lobes;\n }\n if (resize_filter->filter == Jinc)\n {\n /*\n Convert a Jinc function lobes value to a real support value.\n */\n if (resize_filter->support > 16)\n resize_filter->support=jinc_zeros[15]; /* largest entry in table */\n else\n resize_filter->support=jinc_zeros[((long) resize_filter->support)-1];\n /*\n Blur this filter so support is a integer value (lobes dependant).\n */\n if (filter_type == LanczosRadiusFilter)\n resize_filter->blur*=floor(resize_filter->support)/\n resize_filter->support;\n }\n /*\n Expert blur override.\n */\n artifact=GetImageArtifact(image,\"filter:blur\");\n if (artifact != (const char *) NULL)\n resize_filter->blur*=StringToDouble(artifact,(char **) NULL);\n if (resize_filter->blur < MagickEpsilon)\n resize_filter->blur=(double) MagickEpsilon;\n /*\n Expert override of the support setting.\n */\n artifact=GetImageArtifact(image,\"filter:support\");\n if (artifact != (const char *) NULL)\n resize_filter->support=fabs(StringToDouble(artifact,(char **) NULL));\n /*\n Scale windowing function separately to the support 'clipping' window\n that calling operator is planning to actually use. (Expert override)\n */\n resize_filter->window_support=resize_filter->support; /* default */\n artifact=GetImageArtifact(image,\"filter:win-support\");\n if (artifact != (const char *) NULL)\n resize_filter->window_support=fabs(StringToDouble(artifact,(char **) NULL));\n /*\n Adjust window function scaling to match windowing support for weighting\n function. This avoids a division on every filter call.\n */\n resize_filter->scale/=resize_filter->window_support;\n /*\n * Set Cubic Spline B,C values, calculate Cubic coefficients.\n */\n B=0.0;\n C=0.0;\n if ((resize_filter->filter == CubicBC) ||\n (resize_filter->window == CubicBC) )\n {\n B=filters[filter_type].B;\n C=filters[filter_type].C;\n if (filters[window_type].function == CubicBC)\n {\n B=filters[window_type].B;\n C=filters[window_type].C;\n }\n artifact=GetImageArtifact(image,\"filter:b\");\n if (artifact != (const char *) NULL)\n {\n B=StringToDouble(artifact,(char **) NULL);\n C=(1.0-B)/2.0; /* Calculate C to get a Keys cubic filter. */\n artifact=GetImageArtifact(image,\"filter:c\"); /* user C override */\n if (artifact != (const char *) NULL)\n C=StringToDouble(artifact,(char **) NULL);\n }\n else\n {\n artifact=GetImageArtifact(image,\"filter:c\");\n if (artifact != (const char *) NULL)\n {\n C=StringToDouble(artifact,(char **) NULL);\n B=1.0-2.0*C; /* Calculate B to get a Keys cubic filter. */\n }\n }\n {\n const double\n twoB = B+B;\n\n /*\n Convert B,C values into Cubic Coefficents. See CubicBC().\n */\n resize_filter->coefficient[0]=1.0-(1.0/3.0)*B;\n resize_filter->coefficient[1]=-3.0+twoB+C;\n resize_filter->coefficient[2]=2.0-1.5*B-C;\n resize_filter->coefficient[3]=(4.0/3.0)*B+4.0*C;\n resize_filter->coefficient[4]=-8.0*C-twoB;\n resize_filter->coefficient[5]=B+5.0*C;\n resize_filter->coefficient[6]=(-1.0/6.0)*B-C;\n }\n }\n\n /*\n Expert Option Request for verbose details of the resulting filter.\n */\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp master\n {\n#endif\n if (IsStringTrue(GetImageArtifact(image,\"filter:verbose\")) != MagickFalse)\n {\n double\n support,\n x;\n\n /*\n Set the weighting function properly when the weighting function\n may not exactly match the filter of the same name. EG: a Point\n filter is really uses a Box weighting function with a different\n support than is typically used.\n */\n if (resize_filter->filter == Box) filter_type=BoxFilter;\n if (resize_filter->filter == Sinc) filter_type=SincFilter;\n if (resize_filter->filter == SincFast) filter_type=SincFastFilter;\n if (resize_filter->filter == Jinc) filter_type=JincFilter;\n if (resize_filter->filter == CubicBC) filter_type=CubicFilter;\n if (resize_filter->window == Box) window_type=BoxFilter;\n if (resize_filter->window == Sinc) window_type=SincFilter;\n if (resize_filter->window == SincFast) window_type=SincFastFilter;\n if (resize_filter->window == Jinc) window_type=JincFilter;\n if (resize_filter->window == CubicBC) window_type=CubicFilter;\n /*\n Report Filter Details.\n */\n support=GetResizeFilterSupport(resize_filter); /* practical_support */\n (void) FormatLocaleFile(stdout,\n \"# Resampling Filter (for graphing)\\n#\\n\");\n (void) FormatLocaleFile(stdout,\"# filter = %s\\n\",\n CommandOptionToMnemonic(MagickFilterOptions,filter_type));\n (void) FormatLocaleFile(stdout,\"# window = %s\\n\",\n CommandOptionToMnemonic(MagickFilterOptions,window_type));\n (void) FormatLocaleFile(stdout,\"# support = %.*g\\n\",\n GetMagickPrecision(),(double) resize_filter->support);\n (void) FormatLocaleFile(stdout,\"# window-support = %.*g\\n\",\n GetMagickPrecision(),(double) resize_filter->window_support);\n (void) FormatLocaleFile(stdout,\"# scale-blur = %.*g\\n\",\n GetMagickPrecision(),(double) resize_filter->blur);\n if ((filter_type == GaussianFilter) || (window_type == GaussianFilter))\n (void) FormatLocaleFile(stdout,\"# gaussian-sigma = %.*g\\n\",\n GetMagickPrecision(),(double) resize_filter->coefficient[0]);\n if ( filter_type == KaiserFilter || window_type == KaiserFilter )\n (void) FormatLocaleFile(stdout,\"# kaiser-beta = %.*g\\n\",\n GetMagickPrecision(),(double) resize_filter->coefficient[0]);\n (void) FormatLocaleFile(stdout,\"# practical-support = %.*g\\n\",\n GetMagickPrecision(), (double) support);\n if ((filter_type == CubicFilter) || (window_type == CubicFilter))\n (void) FormatLocaleFile(stdout,\"# B,C = %.*g,%.*g\\n\",\n GetMagickPrecision(),(double) B,GetMagickPrecision(),(double) C);\n (void) FormatLocaleFile(stdout,\"\\n\");\n /*\n Output values of resulting filter graph -- for graphing filter result.\n */\n for (x=0.0; x <= support; x+=0.01f)\n (void) FormatLocaleFile(stdout,\"%5.2lf\\t%.*g\\n\",x,\n GetMagickPrecision(),(double)\n GetResizeFilterWeight(resize_filter,x));\n /*\n A final value so gnuplot can graph the 'stop' properly.\n */\n (void) FormatLocaleFile(stdout,\"%5.2lf\\t%.*g\\n\",support,\n GetMagickPrecision(),0.0);\n }\n /* Output the above once only for each image - remove setting */\n (void) DeleteImageArtifact((Image *) image,\"filter:verbose\");\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n }\n#endif\n return(resize_filter);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1718'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline unsigned int ScaleQuantumToMap(const Quantum quantum)\n{\n if (quantum < 0.0)\n return(0UL);\n if ((quantum/65537) >= (Quantum) MaxMap)\n return((unsigned int) MaxMap);\n#if !defined(MAGICKCORE_HDRI_SUPPORT)\n return((unsigned int) ((quantum+MagickULLConstant(32768))/\n MagickULLConstant(65537)));\n#else\n return((unsigned int) (quantum/65537.0+0.5));\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1751'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline MagickSizeType ScaleQuantumToLongLong(const Quantum quantum)\n{\n#if !defined(MAGICKCORE_HDRI_SUPPORT)\n return((MagickSizeType) (MagickULLConstant(281479271743489)*quantum));\n#else\n if (quantum <= 0.0)\n return(0UL);\n if ((281479271743489.0*quantum) >= 18446744073709551615.0)\n return(MagickULLConstant(18446744073709551615));\n return((MagickSizeType) (281479271743489.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: bool wsrep_setup_allowed_sst_methods() {\n std::string methods(wsrep_sst_allowed_methods);\n\n /* Check if the string is valid. In method name we allow only:\n alpha-num\n underscore\n dash\n but w do not allow leading and trailing dash.\n Method names have to be separated by colons (spaces before/after colon are\n allowed). Below regex may seem difficult, but in fact it is not:\n\n 1. Any number of leading spaces\n\n 2. Followed by alpha-num character or underscore\n 3. Followed by any number of underscore/dash\n 4. Followed by alpha-num character or underscore\n 5. 3 - 4 group is optional\n 6. Followed by colon (possibly with leading and/or trailing spaces)\n 7. 2 - 6 group is optional\n\n 8. Followed by alpha-num character or underscore\n 9. Followed by any number of underscore/dash\n 10. Followed by alpha-num character or underscore\n 11. 9 -10 group is optional\n\n 11. Followed by any number of trailing spaces */\n\n static std::regex validate_regex(\n \"\\\\s*(\\\\w([_-]*\\\\w)*(\\\\s*,\\\\s*))*\\\\w([_-]*\\\\w)*\\\\s*\", std::regex::nosubs);\n\n if (!std::regex_match(methods, validate_regex)) {\n WSREP_FATAL(\n \"Wrong format of --wsrep-sst-allowed-methods parameter value: %s\",\n wsrep_sst_allowed_methods);\n return true;\n }\n\n // split it into tokens and trim\n static std::regex split_regex(\"[^,\\\\s][^,]*[^,\\\\s]\");\n for (auto it =\n std::sregex_iterator(methods.begin(), methods.end(), split_regex);\n it != std::sregex_iterator(); ++it) {\n allowed_sst_methods.push_back(it->str());\n }\n\n return false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-77'], 'message': 'PXC-3392: Donor uses invalid SST methods\n\nDot allowed in SST method name.\nHyphen allowed in SST data.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: cdp_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\tstruct lldpd_mgmt *mgmt;\n\tstruct in_addr addr;\n#if 0\n\tu_int16_t cksum;\n#endif\n\tu_int8_t *software = NULL, *platform = NULL;\n\tint software_len = 0, platform_len = 0, proto, version, nb, caps;\n\tconst unsigned char cdpaddr[] = CDP_MULTICAST_ADDR;\n#ifdef ENABLE_FDP\n\tconst unsigned char fdpaddr[] = CDP_MULTICAST_ADDR;\n\tint fdp = 0;\n#endif\n\tu_int8_t *pos, *tlv, *pos_address, *pos_next_address;\n\tint length, len_eth, tlv_type, tlv_len, addresses_len, address_len;\n#ifdef ENABLE_DOT1\n\tstruct lldpd_vlan *vlan;\n#endif\n\n\tlog_debug(\"cdp\", \"decode CDP frame received on %s\",\n\t hardware->h_ifname);\n\n\tif ((chassis = calloc(1, sizeof(struct lldpd_chassis))) == NULL) {\n\t\tlog_warn(\"cdp\", \"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(\"cdp\", \"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#endif\n\n\tlength = s;\n\tpos = (u_int8_t*)frame;\n\n\tif (length < 2*ETHER_ADDR_LEN + sizeof(u_int16_t) /* Ethernet */ +\n\t 8 /* LLC */ + 4 /* CDP header */) {\n\t\tlog_warn(\"cdp\", \"too short CDP/FDP frame received on %s\", hardware->h_ifname);\n\t\tgoto malformed;\n\t}\n\n\tif (PEEK_CMP(cdpaddr, sizeof(cdpaddr)) != 0) {\n#ifdef ENABLE_FDP\n\t\tPEEK_RESTORE((u_int8_t*)frame);\n\t\tif (PEEK_CMP(fdpaddr, sizeof(fdpaddr)) != 0)\n\t\t\tfdp = 1;\n\t\telse {\n#endif\n\t\t\tlog_info(\"cdp\", \"frame not targeted at CDP/FDP multicast address received on %s\",\n\t\t\t hardware->h_ifname);\n\t\t\tgoto malformed;\n#ifdef ENABLE_FDP\n\t\t}\n#endif\n\t}\n\tPEEK_DISCARD(ETHER_ADDR_LEN);\t/* Don't care of source address */\n\tlen_eth = PEEK_UINT16;\n\tif (len_eth > length) {\n\t\tlog_warnx(\"cdp\", \"incorrect 802.3 frame size reported on %s\",\n\t\t hardware->h_ifname);\n\t\tgoto malformed;\n\t}\n\tPEEK_DISCARD(6);\t/* Skip beginning of LLC */\n\tproto = PEEK_UINT16;\n\tif (proto != LLC_PID_CDP) {\n\t\tif ((proto != LLC_PID_DRIP) &&\n\t\t (proto != LLC_PID_PAGP) &&\n\t\t (proto != LLC_PID_PVSTP) &&\n\t\t (proto != LLC_PID_UDLD) &&\n\t\t (proto != LLC_PID_VTP) &&\n\t\t (proto != LLC_PID_DTP) &&\n\t\t (proto != LLC_PID_STP))\n\t\t\tlog_debug(\"cdp\", \"incorrect LLC protocol ID received on %s\",\n\t\t\t hardware->h_ifname);\n\t\tgoto malformed;\n\t}\n\n#if 0\n\t/* Check checksum */\n\tcksum = frame_checksum(pos, len_eth - 8,\n#ifdef ENABLE_FDP\n\t !fdp\t\t/* fdp = 0 -> cisco checksum */\n#else\n\t 1\t\t\t/* cisco checksum */\n#endif\n\t\t);\n\tif (cksum != 0) {\n\t\tlog_info(\"cdp\", \"incorrect CDP/FDP checksum for frame received on %s (%d)\",\n\t\t\t hardware->h_ifname, cksum);\n\t\tgoto malformed;\n\t}\n#endif\n\n\t/* Check version */\n\tversion = PEEK_UINT8;\n\tif ((version != 1) && (version != 2)) {\n\t\tlog_warnx(\"cdp\", \"incorrect CDP/FDP version (%d) for frame received on %s\",\n\t\t version, hardware->h_ifname);\n\t\tgoto malformed;\n\t}\n\tchassis->c_ttl = PEEK_UINT8; /* TTL */\n\tPEEK_DISCARD_UINT16;\t /* Checksum, already checked */\n\n\twhile (length) {\n\t\tif (length < 4) {\n\t\t\tlog_warnx(\"cdp\", \"CDP/FDP TLV header is too large for \"\n\t\t\t \"frame received on %s\",\n\t\t\t hardware->h_ifname);\n\t\t\tgoto malformed;\n\t\t}\n\t\ttlv_type = PEEK_UINT16;\n\t\ttlv_len = PEEK_UINT16 - 4;\n\t\t(void)PEEK_SAVE(tlv);\n\t\tif ((tlv_len < 0) || (length < tlv_len)) {\n\t\t\tlog_warnx(\"cdp\", \"incorrect size in CDP/FDP TLV header for frame \"\n\t\t\t \"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 CDP_TLV_CHASSIS:\n\t\t\tif ((chassis->c_name = (char *)calloc(1, tlv_len + 1)) == NULL) {\n\t\t\t\tlog_warn(\"cdp\", \"unable to allocate memory for chassis name\");\n\t\t\t\tgoto malformed;\n\t\t\t}\n\t\t\tPEEK_BYTES(chassis->c_name, tlv_len);\n\t\t\tchassis->c_id_subtype = LLDP_CHASSISID_SUBTYPE_LOCAL;\n\t\t\tif ((chassis->c_id = (char *)malloc(tlv_len)) == NULL) {\n\t\t\t\tlog_warn(\"cdp\", \"unable to allocate memory for chassis ID\");\n\t\t\t\tgoto malformed;\n\t\t\t}\n\t\t\tmemcpy(chassis->c_id, chassis->c_name, tlv_len);\n\t\t\tchassis->c_id_len = tlv_len;\n\t\t\tbreak;\n\t\tcase CDP_TLV_ADDRESSES:\n\t\t\tCHECK_TLV_SIZE(4, \"Address\");\n\t\t\taddresses_len = tlv_len - 4;\n\t\t\tfor (nb = PEEK_UINT32; nb > 0; nb--) {\n\t\t\t\t(void)PEEK_SAVE(pos_address);\n\t\t\t\t/* We first try to get the real length of the packet */\n\t\t\t\tif (addresses_len < 2) {\n\t\t\t\t\tlog_warn(\"cdp\", \"too short address subframe \"\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\tgoto malformed;\n\t\t\t\t}\n\t\t\t\tPEEK_DISCARD_UINT8; addresses_len--;\n\t\t\t\taddress_len = PEEK_UINT8; addresses_len--;\n\t\t\t\tif (addresses_len < address_len + 2) {\n\t\t\t\t\tlog_warn(\"cdp\", \"too short address subframe \"\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\tgoto malformed;\n\t\t\t\t}\n\t\t\t\tPEEK_DISCARD(address_len);\n\t\t\t\taddresses_len -= address_len;\n\t\t\t\taddress_len = PEEK_UINT16; addresses_len -= 2;\n\t\t\t\tif (addresses_len < address_len) {\n\t\t\t\t\tlog_warn(\"cdp\", \"too short address subframe \"\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\tgoto malformed;\n\t\t\t\t}\n\t\t\t\tPEEK_DISCARD(address_len);\n\t\t\t\t(void)PEEK_SAVE(pos_next_address);\n\t\t\t\t/* Next, we go back and try to extract\n\t\t\t\t IPv4 address */\n\t\t\t\tPEEK_RESTORE(pos_address);\n\t\t\t\tif ((PEEK_UINT8 == 1) && (PEEK_UINT8 == 1) &&\n\t\t\t\t (PEEK_UINT8 == CDP_ADDRESS_PROTO_IP) &&\n\t\t\t\t (PEEK_UINT16 == sizeof(struct in_addr))) {\n\t\t\t\t\t\tPEEK_BYTES(&addr, sizeof(struct in_addr));\n\t\t\t\t\t\tmgmt = lldpd_alloc_mgmt(LLDPD_AF_IPV4, &addr, \n\t\t\t\t\t\t\t\t\tsizeof(struct in_addr), 0);\n\t\t\t\t\t\tif (mgmt == NULL) {\n\t\t\t\t\t\t\tassert(errno == ENOMEM);\n\t\t\t\t\t\t\tlog_warn(\"cdp\", \"unable to allocate memory for management address\");\n\t\t\t\t\t\t\tgoto malformed;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tTAILQ_INSERT_TAIL(&chassis->c_mgmt, mgmt, m_entries);\n\t\t\t\t}\n\t\t\t\t/* Go to the end of the address */\n\t\t\t\tPEEK_RESTORE(pos_next_address);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase CDP_TLV_PORT:\n\t\t\tif (tlv_len == 0) {\n\t\t\t\tlog_warn(\"cdp\", \"too short port description received\");\n\t\t\t\tgoto malformed;\n\t\t\t}\n\t\t\tif ((port->p_descr = (char *)calloc(1, tlv_len + 1)) == NULL) {\n\t\t\t\tlog_warn(\"cdp\", \"unable to allocate memory for port description\");\n\t\t\t\tgoto malformed;\n\t\t\t}\n\t\t\tPEEK_BYTES(port->p_descr, tlv_len);\n\t\t\tport->p_id_subtype = LLDP_PORTID_SUBTYPE_IFNAME;\n\t\t\tif ((port->p_id = (char *)calloc(1, tlv_len)) == NULL) {\n\t\t\t\tlog_warn(\"cdp\", \"unable to allocate memory for port ID\");\n\t\t\t\tgoto malformed;\n\t\t\t}\n\t\t\tmemcpy(port->p_id, port->p_descr, tlv_len);\n\t\t\tport->p_id_len = tlv_len;\n\t\t\tbreak;\n\t\tcase CDP_TLV_CAPABILITIES:\n#ifdef ENABLE_FDP\n\t\t\tif (fdp) {\n\t\t\t\t/* Capabilities are string with FDP */\n\t\t\t\tif (!strncmp(\"Router\", (char*)pos, tlv_len))\n\t\t\t\t\tchassis->c_cap_enabled = LLDP_CAP_ROUTER;\n\t\t\t\telse if (!strncmp(\"Switch\", (char*)pos, tlv_len))\n\t\t\t\t\tchassis->c_cap_enabled = LLDP_CAP_BRIDGE;\n\t\t\t\telse if (!strncmp(\"Bridge\", (char*)pos, tlv_len))\n\t\t\t\t\tchassis->c_cap_enabled = LLDP_CAP_REPEATER;\n\t\t\t\telse\n\t\t\t\t\tchassis->c_cap_enabled = LLDP_CAP_STATION;\n\t\t\t\tchassis->c_cap_available = chassis->c_cap_enabled;\n\t\t\t\tbreak;\n\t\t\t}\n#endif\n\t\t\tCHECK_TLV_SIZE(4, \"Capabilities\");\n\t\t\tcaps = PEEK_UINT32;\n\t\t\tif (caps & CDP_CAP_ROUTER)\n\t\t\t\tchassis->c_cap_enabled |= LLDP_CAP_ROUTER;\n\t\t\tif (caps & 0x0e)\n\t\t\t\tchassis->c_cap_enabled |= LLDP_CAP_BRIDGE;\n\t\t\tif (chassis->c_cap_enabled == 0)\n\t\t\t\tchassis->c_cap_enabled = LLDP_CAP_STATION;\n\t\t\tchassis->c_cap_available = chassis->c_cap_enabled;\n\t\t\tbreak;\n\t\tcase CDP_TLV_SOFTWARE:\n\t\t\tsoftware_len = tlv_len;\n\t\t\t(void)PEEK_SAVE(software);\n\t\t\tbreak;\n\t\tcase CDP_TLV_PLATFORM:\n\t\t\tplatform_len = tlv_len;\n\t\t\t(void)PEEK_SAVE(platform);\n\t\t\tbreak;\n#ifdef ENABLE_DOT1\n\t\tcase CDP_TLV_NATIVEVLAN:\n\t\t\tCHECK_TLV_SIZE(2, \"Native VLAN\");\n\t\t\tif ((vlan = (struct lldpd_vlan *)calloc(1,\n\t\t\t\tsizeof(struct lldpd_vlan))) == NULL) {\n\t\t\t\tlog_warn(\"cdp\", \"unable to alloc vlan \"\n\t\t\t\t\t \"structure for \"\n\t\t\t\t\t \"tlv received on %s\",\n\t\t\t\t\t hardware->h_ifname);\n\t\t\t\tgoto malformed;\n\t\t\t}\n\t\t\tvlan->v_vid = port->p_pvid = PEEK_UINT16;\n\t\t\tif (asprintf(&vlan->v_name, \"VLAN #%d\", vlan->v_vid) == -1) {\n\t\t\t\tlog_warn(\"cdp\", \"unable to alloc VLAN name for \"\n\t\t\t\t\t \"TLV received on %s\",\n\t\t\t\t\t hardware->h_ifname);\n\t\t\t\tfree(vlan);\n\t\t\t\tgoto malformed;\n\t\t\t}\n\t\t\tTAILQ_INSERT_TAIL(&port->p_vlans,\n\t\t\t\t\t vlan, v_entries);\n\t\t\tbreak;\n#endif\n\t\tdefault:\n\t\t\tlog_debug(\"cdp\", \"unknown CDP/FDP TLV type (%d) received on %s\",\n\t\t\t ntohs(tlv_type), hardware->h_ifname);\n\t\t\thardware->h_rx_unrecognized_cnt++;\n\t\t}\n\t\tPEEK_DISCARD(tlv + tlv_len - pos);\n\t}\n\tif (!software && platform) {\n\t\tif ((chassis->c_descr = (char *)calloc(1,\n\t\t\t platform_len + 1)) == NULL) {\n\t\t\tlog_warn(\"cdp\", \"unable to allocate memory for chassis description\");\n\t\t\tgoto malformed;\n\t\t}\n\t\tmemcpy(chassis->c_descr, platform, platform_len);\n\t} else if (software && !platform) {\n\t\tif ((chassis->c_descr = (char *)calloc(1,\n\t\t\t software_len + 1)) == NULL) {\n\t\t\tlog_warn(\"cdp\", \"unable to allocate memory for chassis description\");\n\t\t\tgoto malformed;\n\t\t}\n\t\tmemcpy(chassis->c_descr, software, software_len);\n\t} else if (software && platform) {\n#define CONCAT_PLATFORM \" running on\\n\"\n\t\tif ((chassis->c_descr = (char *)calloc(1,\n\t\t\t software_len + platform_len +\n\t\t\t strlen(CONCAT_PLATFORM) + 1)) == NULL) {\n\t\t\tlog_warn(\"cdp\", \"unable to allocate memory for chassis description\");\n\t\t\tgoto malformed;\n\t\t}\n\t\tmemcpy(chassis->c_descr, platform, platform_len);\n\t\tmemcpy(chassis->c_descr + platform_len,\n\t\t CONCAT_PLATFORM, strlen(CONCAT_PLATFORM));\n\t\tmemcpy(chassis->c_descr + platform_len + strlen(CONCAT_PLATFORM),\n\t\t software, software_len);\n\t}\n\tif ((chassis->c_id == NULL) ||\n\t (port->p_id == NULL) ||\n\t (chassis->c_name == NULL) ||\n\t (chassis->c_descr == NULL) ||\n\t (port->p_descr == NULL) ||\n\t (chassis->c_ttl == 0) ||\n\t (chassis->c_cap_enabled == 0)) {\n\t\tlog_warnx(\"cdp\", \"some mandatory CDP/FDP 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;\n\nmalformed:\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 inline void ConvertLuvToXYZ(const double L,const double u,const double v,\n double *X,double *Y,double *Z)\n{\n assert(X != (double *) NULL);\n assert(Y != (double *) NULL);\n assert(Z != (double *) NULL);\n if (L > (CIEK*CIEEpsilon))\n *Y=(double) pow((L+16.0)/116.0,3.0);\n else\n *Y=L/CIEK;\n *X=((*Y*((39.0*L/(v+13.0*L*(9.0*D65Y/(D65X+15.0*D65Y+3.0*D65Z))))-5.0))+\n 5.0*(*Y))/((((52.0*L/(u+13.0*L*(4.0*D65X/(D65X+15.0*D65Y+3.0*D65Z))))-1.0)/\n 3.0)-(-1.0/3.0));\n *Z=(*X*(((52.0*L/(u+13.0*L*(4.0*D65X/(D65X+15.0*D65Y+3.0*D65Z))))-1.0)/3.0))-\n 5.0*(*Y);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1739'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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_a_reply(const unsigned char *abuf, int alen,\n struct hostent **host,\n struct ares_addrttl *addrttls, 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 in_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_INET)\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_INET;\n hostent->h_length = sizeof(struct in_addr);\n\n if (naddrs)\n {\n addrs = ares_malloc(naddrs * sizeof(struct in_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_INET)\n {\n hostent->h_addr_list[i] = (char *)&addrs[i];\n memcpy(hostent->h_addr_list[i],\n &(CARES_INADDR_CAST(struct sockaddr_in *, next->ai_addr)->sin_addr),\n sizeof(struct in_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].ipaddr,\n &(CARES_INADDR_CAST(struct sockaddr_in *, next->ai_addr)->sin_addr),\n sizeof(struct in_addr));\n }\n ++i;\n }\n next = next->ai_next;\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: int pdf_is_pdf(FILE *fp)\n{\n int is_pdf;\n char *header;\n\n header = get_header(fp);\n\n if (header && strstr(header, \"%PDF-\"))\n is_pdf = 1;\n else \n is_pdf = 0;\n\n free(header);\n return is_pdf;\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: Status renameCollectionForApplyOps(OperationContext* opCtx,\n const std::string& dbName,\n const BSONElement& ui,\n const BSONObj& cmd,\n const repl::OpTime& renameOpTime) {\n\n const auto sourceNsElt = cmd.firstElement();\n const auto targetNsElt = cmd[\"to\"];\n uassert(ErrorCodes::TypeMismatch,\n \"'renameCollection' must be of type String\",\n sourceNsElt.type() == BSONType::String);\n uassert(ErrorCodes::TypeMismatch,\n \"'to' must be of type String\",\n targetNsElt.type() == BSONType::String);\n\n NamespaceString sourceNss(sourceNsElt.valueStringData());\n NamespaceString targetNss(targetNsElt.valueStringData());\n NamespaceString uiNss(getNamespaceFromUUIDElement(opCtx, ui));\n\n if ((repl::ReplicationCoordinator::get(opCtx)->getReplicationMode() ==\n repl::ReplicationCoordinator::modeNone) &&\n targetNss.isOplog()) {\n return Status(ErrorCodes::IllegalOperation,\n str::stream() << \"Cannot rename collection to the oplog\");\n }\n\n // If the UUID we're targeting already exists, rename from there no matter what.\n if (!uiNss.isEmpty()) {\n sourceNss = uiNss;\n }\n\n OptionalCollectionUUID targetUUID;\n if (!ui.eoo())\n targetUUID = uassertStatusOK(UUID::parse(ui));\n\n RenameCollectionOptions options;\n options.dropTarget = cmd[\"dropTarget\"].trueValue();\n if (cmd[\"dropTarget\"].type() == BinData) {\n auto uuid = uassertStatusOK(UUID::parse(cmd[\"dropTarget\"]));\n options.dropTargetUUID = uuid;\n }\n\n const Collection* const sourceColl =\n AutoGetCollectionForRead(opCtx, sourceNss, AutoGetCollection::ViewMode::kViewsPermitted)\n .getCollection();\n\n if (sourceNss.isDropPendingNamespace() || sourceColl == nullptr) {\n NamespaceString dropTargetNss;\n\n if (options.dropTarget)\n dropTargetNss = targetNss;\n\n if (options.dropTargetUUID) {\n dropTargetNss = getNamespaceFromUUID(opCtx, options.dropTargetUUID.get());\n }\n\n // Downgrade renameCollection to dropCollection.\n if (!dropTargetNss.isEmpty()) {\n BSONObjBuilder unusedResult;\n return dropCollection(opCtx,\n dropTargetNss,\n unusedResult,\n renameOpTime,\n DropCollectionSystemCollectionMode::kAllowSystemCollectionDrops);\n }\n\n return Status(ErrorCodes::NamespaceNotFound,\n str::stream()\n << \"renameCollection() cannot accept a source \"\n \"collection that does not exist or is in a drop-pending state: \"\n << sourceNss.toString());\n }\n\n const std::string dropTargetMsg =\n options.dropTargetUUID ? \" and drop \" + options.dropTargetUUID->toString() + \".\" : \".\";\n const std::string uuidString = targetUUID ? targetUUID->toString() : \"UUID unknown\";\n log() << \"renameCollectionForApplyOps: rename \" << sourceNss << \" (\" << uuidString << \") to \"\n << targetNss << dropTargetMsg;\n\n options.stayTemp = cmd[\"stayTemp\"].trueValue();\n return renameCollectionCommon(opCtx, sourceNss, targetNss, targetUUID, renameOpTime, options);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'SERVER-35636 renameCollectionForApplyOps checks for complete namespace'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TopologyManager::TopologyManager(SdamConfiguration config,\n ClockSource* clockSource,\n TopologyEventsPublisherPtr eventsPublisher)\n : _config(std::move(config)),\n _clockSource(clockSource),\n _topologyDescription(std::make_shared(_config)),\n _topologyStateMachine(std::make_unique(_config)),\n _topologyEventsPublisher(eventsPublisher) {} ; 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 validateServersInLatencyWindow(\n TestCaseResult* result,\n boost::optional> selectedServers) {\n if (!selectedServers && _inLatencyWindow.size() > 0) {\n std::stringstream errorMessage;\n errorMessage << \"did not select any servers, but expected '\" << _inLatencyWindow.size()\n << \"' to be selected.\";\n auto errorDescription = std::make_pair(\"servers in latency window\", errorMessage.str());\n result->errorDescriptions.push_back(errorDescription);\n } else if (selectedServers && selectedServers->size() != _inLatencyWindow.size()) {\n std::stringstream errorMessage;\n errorMessage << \"selected '\" << selectedServers->size() << \"' server(s), but expected '\"\n << _inLatencyWindow.size() << \"' to be selected.\";\n auto errorDescription = std::make_pair(\"servers in latency window\", errorMessage.str());\n result->errorDescriptions.push_back(errorDescription);\n } else {\n // Compare the server addresses of each server in the selectedServers and\n // _inLatencyWindow vectors. We do not need to compare the entire server description\n // because we only need to make sure that the correct server was chosen and are not\n // manipulating the ServerDescriptions at all.\n std::vector selectedHostAndPortes;\n std::vector expectedHostAndPortes;\n\n auto selectedServersIt = selectedServers->begin();\n for (auto expectedServersIt = _inLatencyWindow.begin();\n expectedServersIt != _inLatencyWindow.end();\n ++expectedServersIt) {\n selectedHostAndPortes.push_back((*selectedServersIt)->getAddress());\n expectedHostAndPortes.push_back((*expectedServersIt)->getAddress());\n\n selectedServersIt++;\n }\n\n std::sort(selectedHostAndPortes.begin(), selectedHostAndPortes.end());\n std::sort(expectedHostAndPortes.begin(), expectedHostAndPortes.end());\n if (!std::equal(selectedHostAndPortes.begin(),\n selectedHostAndPortes.end(),\n expectedHostAndPortes.begin())) {\n std::stringstream errorMessage;\n errorMessage << \"selected servers with addresses '\" << selectedHostAndPortes\n << \"' server(s), but expected '\" << expectedHostAndPortes\n << \"' to be selected.\";\n auto errorDescription =\n std::make_pair(\"servers in latency window\", errorMessage.str());\n result->errorDescriptions.push_back(errorDescription);\n return;\n }\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_read1(struct snd_rawmidi_substream *substream,\n\t\t\t\t unsigned char __user *userbuf,\n\t\t\t\t unsigned char *kernelbuf, long count)\n{\n\tunsigned long flags;\n\tlong result = 0, count1;\n\tstruct snd_rawmidi_runtime *runtime = substream->runtime;\n\tunsigned long appl_ptr;\n\n\tspin_lock_irqsave(&runtime->lock, flags);\n\twhile (count > 0 && runtime->avail) {\n\t\tcount1 = runtime->buffer_size - runtime->appl_ptr;\n\t\tif (count1 > count)\n\t\t\tcount1 = count;\n\t\tif (count1 > (int)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(kernelbuf + result, runtime->buffer + appl_ptr, count1);\n\t\tif (userbuf) {\n\t\t\tspin_unlock_irqrestore(&runtime->lock, flags);\n\t\t\tif (copy_to_user(userbuf + result,\n\t\t\t\t\t runtime->buffer + appl_ptr, count1)) {\n\t\t\t\treturn result > 0 ? result : -EFAULT;\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\tspin_unlock_irqrestore(&runtime->lock, flags);\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: void hfi1_mmu_rb_unregister(struct mmu_rb_handler *handler)\n{\n\tstruct mmu_rb_node *rbnode;\n\tstruct rb_node *node;\n\tunsigned long flags;\n\tstruct list_head del_list;\n\n\t/* Unregister first so we don't get any more notifications. */\n\tmmu_notifier_unregister(&handler->mn, handler->mm);\n\n\t/*\n\t * Make sure the wq delete handler is finished running. It will not\n\t * be triggered once the mmu notifiers are unregistered above.\n\t */\n\tflush_work(&handler->del_work);\n\n\tINIT_LIST_HEAD(&del_list);\n\n\tspin_lock_irqsave(&handler->lock, flags);\n\twhile ((node = rb_first_cached(&handler->root))) {\n\t\trbnode = rb_entry(node, struct mmu_rb_node, node);\n\t\trb_erase_cached(node, &handler->root);\n\t\t/* move from LRU list to delete list */\n\t\tlist_move(&rbnode->list, &del_list);\n\t}\n\tspin_unlock_irqrestore(&handler->lock, flags);\n\n\tdo_remove(handler, &del_list);\n\n\tkfree(handler);\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 void unpin_sdma_pages(struct sdma_mmu_node *node)\n{\n\tif (node->npages) {\n\t\tunpin_vector_pages(node->pq->mm, node->pages, 0, node->npages);\n\t\tatomic_sub(node->npages, &node->pq->n_locked);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'IB/hfi1: Ensure correct mm is used at all times\n\nTwo earlier bug fixes have created a security problem in the hfi1\ndriver. One fix aimed to solve an issue where current->mm was not valid\nwhen closing the hfi1 cdev. It attempted to do this by saving a cached\nvalue of the current->mm pointer at file open time. This is a problem if\nanother process with access to the FD calls in via write() or ioctl() to\npin pages via the hfi driver. The other fix tried to solve a use after\nfree by taking a reference on the mm.\n\nTo fix this correctly we use the existing cached value of the mm in the\nmmu notifier. Now we can check in the insert, evict, etc. routines that\ncurrent->mm matched what the notifier was registered for. If not, then\ndon't allow access. The register of the mmu notifier will save the mm\npointer.\n\nSince in do_exit() the exit_mm() is called before exit_files(), which\nwould call our close routine a reference is needed on the mm. We rely on\nthe mmgrab done by the registration of the notifier, whereas before it was\nexplicit. The mmu notifier deregistration happens when the user context is\ntorn down, the creation of which triggered the registration.\n\nAlso of note is we do not do any explicit work to protect the interval\ntree notifier. It doesn't seem that this is going to be needed since we\naren't actually doing anything with current->mm. The interval tree\nnotifier stuff still has a FIXME noted from a previous commit that will be\naddressed in a follow on patch.\n\nCc: \nFixes: e0cf75deab81 (\"IB/hfi1: Fix mm_struct use after free\")\nFixes: 3faa3d9a308e (\"IB/hfi1: Make use of mm consistent\")\nLink: https://lore.kernel.org/r/20201125210112.104301.51331.stgit@awfm-01.aw.intel.com\nSuggested-by: Jann Horn \nReported-by: Jason Gunthorpe \nReviewed-by: Ira Weiny \nReviewed-by: Mike Marciniszyn \nSigned-off-by: Dennis Dalessandro \nSigned-off-by: Jason Gunthorpe '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: 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 /* and +7 for https://github.com/uclouvain/openjpeg/issues/1283 (-M 3) */\n /* and +26 for https://github.com/uclouvain/openjpeg/issues/1283 (-M 7) */\n /* TODO: is there a theoretical upper-bound for the compressed code */\n /* block size ? */\n l_data_size = 26 + (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 again buffer size in opj_tcd_code_block_enc_allocate_data() (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: static int con_font_copy(struct vc_data *vc, struct console_font_op *op)\n{\n\tint con = op->height;\n\tint rc;\n\n\n\tconsole_lock();\n\tif (vc->vc_mode != KD_TEXT)\n\t\trc = -EINVAL;\n\telse if (!vc->vc_sw->con_font_copy)\n\t\trc = -ENOSYS;\n\telse if (con < 0 || !vc_cons_allocated(con))\n\t\trc = -ENOTTY;\n\telse if (con == vc->vc_num)\t/* nothing to do */\n\t\trc = 0;\n\telse\n\t\trc = vc->vc_sw->con_font_copy(vc, con);\n\tconsole_unlock();\n\treturn rc;\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: detach_vmas_to_be_unmapped(struct mm_struct *mm, struct vm_area_struct *vma,\n\tstruct vm_area_struct *prev, unsigned long end)\n{\n\tstruct vm_area_struct **insertion_point;\n\tstruct vm_area_struct *tail_vma = NULL;\n\n\tinsertion_point = (prev ? &prev->vm_next : &mm->mmap);\n\tvma->vm_prev = NULL;\n\tdo {\n\t\tvma_rb_erase(vma, &mm->mm_rb);\n\t\tmm->map_count--;\n\t\ttail_vma = vma;\n\t\tvma = vma->vm_next;\n\t} while (vma && vma->vm_start < end);\n\t*insertion_point = vma;\n\tif (vma) {\n\t\tvma->vm_prev = prev;\n\t\tvma_gap_update(vma);\n\t} else\n\t\tmm->highest_vm_end = prev ? vm_end_gap(prev) : 0;\n\ttail_vma->vm_next = NULL;\n\n\t/* Kill the cache */\n\tvmacache_invalidate(mm);\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: bucket_push (index_bucket *bucket,\n CK_OBJECT_HANDLE handle)\n{\n\tunsigned int alloc;\n\n\talloc = alloc_size (bucket->num);\n\tif (bucket->num + 1 > alloc) {\n\t\tCK_OBJECT_HANDLE *elem;\n\n\t\talloc = alloc ? alloc * 2 : 1;\n\t\treturn_val_if_fail (alloc != 0, false);\n\t\telem = realloc (bucket->elem, alloc * sizeof (CK_OBJECT_HANDLE));\n\t\treturn_val_if_fail (elem != NULL, false);\n\t\tbucket->elem = elem;\n\t}\n\n\treturn_val_if_fail (bucket->elem != NULL, false);\n\tbucket->elem[bucket->num++] = handle;\n\treturn true;\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: static int tiocgsid(struct tty_struct *tty, struct tty_struct *real_tty, pid_t __user *p)\n{\n\t/*\n\t * (tty == real_tty) is a cheap way of\n\t * testing if the tty is NOT a master pty.\n\t*/\n\tif (tty == real_tty && current->signal->tty != real_tty)\n\t\treturn -ENOTTY;\n\tif (!real_tty->session)\n\t\treturn -ENOTTY;\n\treturn put_user(pid_vnr(real_tty->session), p);\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 MagickBooleanType WritePOCKETMODImage(const ImageInfo *image_info,\n Image *image,ExceptionInfo *exception)\n{\n#define PocketPageOrder \"1,2,3,4,0,7,6,5\"\n\n const Image\n *next;\n\n Image\n *pages,\n *pocket_mod;\n\n MagickBooleanType\n status;\n\n register ssize_t\n i;\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 pocket_mod=NewImageList();\n pages=NewImageList();\n i=0;\n for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))\n {\n Image\n *page;\n\n if ((i == 0) || (i == 5) || (i == 6) || (i == 7))\n page=RotateImage(next,180.0,exception);\n else\n page=CloneImage(next,0,0,MagickTrue,exception);\n if (page == (Image *) NULL)\n break;\n (void) SetImageAlphaChannel(page,RemoveAlphaChannel,exception);\n page->scene=i++;\n AppendImageToList(&pages,page);\n if ((i == 8) || (GetNextImageInList(next) == (Image *) NULL))\n {\n Image\n *images,\n *page_layout;\n\n MontageInfo\n *montage_info;\n\n /*\n Create PocketMod page.\n */\n for (i=(ssize_t) GetImageListLength(pages); i < 8; i++)\n {\n page=CloneImage(pages,0,0,MagickTrue,exception);\n (void) QueryColorCompliance(\"#FFF\",AllCompliance,\n &page->background_color,exception);\n SetImageBackgroundColor(page,exception);\n page->scene=i;\n AppendImageToList(&pages,page);\n }\n images=CloneImages(pages,PocketPageOrder,exception);\n pages=DestroyImageList(pages);\n if (images == (Image *) NULL)\n break;\n montage_info=CloneMontageInfo(image_info,(MontageInfo *) NULL);\n (void) CloneString(&montage_info->geometry,\"877x1240+0+0\");\n (void) CloneString(&montage_info->tile,\"4x2\");\n (void) QueryColorCompliance(\"#000\",AllCompliance,\n &montage_info->border_color,exception);\n montage_info->border_width=2;\n page_layout=MontageImages(images,montage_info,exception);\n montage_info=DestroyMontageInfo(montage_info);\n images=DestroyImageList(images);\n if (page_layout == (Image *) NULL)\n break;\n AppendImageToList(&pocket_mod,page_layout);\n i=0;\n }\n }\n if (pocket_mod == (Image *) NULL)\n return(MagickFalse);\n status=WritePDFImage(image_info,GetFirstImageInList(pocket_mod),exception);\n pocket_mod=DestroyImageList(pocket_mod);\n return(status);\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_BOOL opj_t2_decode_packets(opj_tcd_t* tcd,\n opj_t2_t *p_t2,\n OPJ_UINT32 p_tile_no,\n opj_tcd_tile_t *p_tile,\n OPJ_BYTE *p_src,\n OPJ_UINT32 * p_data_read,\n OPJ_UINT32 p_max_len,\n opj_codestream_index_t *p_cstr_index,\n opj_event_mgr_t *p_manager)\n{\n OPJ_BYTE *l_current_data = p_src;\n opj_pi_iterator_t *l_pi = 00;\n OPJ_UINT32 pino;\n opj_image_t *l_image = p_t2->image;\n opj_cp_t *l_cp = p_t2->cp;\n opj_tcp_t *l_tcp = &(p_t2->cp->tcps[p_tile_no]);\n OPJ_UINT32 l_nb_bytes_read;\n OPJ_UINT32 l_nb_pocs = l_tcp->numpocs + 1;\n opj_pi_iterator_t *l_current_pi = 00;\n#ifdef TODO_MSD\n OPJ_UINT32 curtp = 0;\n OPJ_UINT32 tp_start_packno;\n#endif\n opj_packet_info_t *l_pack_info = 00;\n opj_image_comp_t* l_img_comp = 00;\n\n OPJ_ARG_NOT_USED(p_cstr_index);\n\n#ifdef TODO_MSD\n if (p_cstr_index) {\n l_pack_info = p_cstr_index->tile_index[p_tile_no].packet;\n }\n#endif\n\n /* create a packet iterator */\n l_pi = opj_pi_create_decode(l_image, l_cp, p_tile_no);\n if (!l_pi) {\n return OPJ_FALSE;\n }\n\n\n l_current_pi = l_pi;\n\n for (pino = 0; pino <= l_tcp->numpocs; ++pino) {\n\n /* if the resolution needed is too low, one dim of the tilec could be equal to zero\n * and no packets are used to decode this resolution and\n * l_current_pi->resno is always >= p_tile->comps[l_current_pi->compno].minimum_num_resolutions\n * and no l_img_comp->resno_decoded are computed\n */\n OPJ_BOOL* first_pass_failed = NULL;\n\n if (l_current_pi->poc.prg == OPJ_PROG_UNKNOWN) {\n /* TODO ADE : add an error */\n opj_pi_destroy(l_pi, l_nb_pocs);\n return OPJ_FALSE;\n }\n\n first_pass_failed = (OPJ_BOOL*)opj_malloc(l_image->numcomps * sizeof(OPJ_BOOL));\n if (!first_pass_failed) {\n opj_pi_destroy(l_pi, l_nb_pocs);\n return OPJ_FALSE;\n }\n memset(first_pass_failed, OPJ_TRUE, l_image->numcomps * sizeof(OPJ_BOOL));\n\n while (opj_pi_next(l_current_pi)) {\n OPJ_BOOL skip_packet = OPJ_FALSE;\n JAS_FPRINTF(stderr,\n \"packet offset=00000166 prg=%d cmptno=%02d rlvlno=%02d prcno=%03d lyrno=%02d\\n\\n\",\n l_current_pi->poc.prg1, l_current_pi->compno, l_current_pi->resno,\n l_current_pi->precno, l_current_pi->layno);\n\n /* If the packet layer is greater or equal than the maximum */\n /* number of layers, skip the packet */\n if (l_current_pi->layno >= l_tcp->num_layers_to_decode) {\n skip_packet = OPJ_TRUE;\n }\n /* If the packet resolution number is greater than the minimum */\n /* number of resolution allowed, skip the packet */\n else if (l_current_pi->resno >=\n p_tile->comps[l_current_pi->compno].minimum_num_resolutions) {\n skip_packet = OPJ_TRUE;\n } else {\n /* If no precincts of any band intersects the area of interest, */\n /* skip the packet */\n OPJ_UINT32 bandno;\n opj_tcd_tilecomp_t *tilec = &p_tile->comps[l_current_pi->compno];\n opj_tcd_resolution_t *res = &tilec->resolutions[l_current_pi->resno];\n\n skip_packet = OPJ_TRUE;\n for (bandno = 0; bandno < res->numbands; ++bandno) {\n opj_tcd_band_t* band = &res->bands[bandno];\n opj_tcd_precinct_t* prec = &band->precincts[l_current_pi->precno];\n\n if (opj_tcd_is_subband_area_of_interest(tcd,\n l_current_pi->compno,\n l_current_pi->resno,\n band->bandno,\n (OPJ_UINT32)prec->x0,\n (OPJ_UINT32)prec->y0,\n (OPJ_UINT32)prec->x1,\n (OPJ_UINT32)prec->y1)) {\n skip_packet = OPJ_FALSE;\n break;\n }\n }\n /*\n printf(\"packet cmptno=%02d rlvlno=%02d prcno=%03d lyrno=%02d -> %s\\n\",\n l_current_pi->compno, l_current_pi->resno,\n l_current_pi->precno, l_current_pi->layno, skip_packet ? \"skipped\" : \"kept\");\n */\n }\n\n if (!skip_packet) {\n l_nb_bytes_read = 0;\n\n first_pass_failed[l_current_pi->compno] = OPJ_FALSE;\n\n if (! opj_t2_decode_packet(p_t2, p_tile, l_tcp, l_current_pi, l_current_data,\n &l_nb_bytes_read, p_max_len, l_pack_info, p_manager)) {\n opj_pi_destroy(l_pi, l_nb_pocs);\n opj_free(first_pass_failed);\n return OPJ_FALSE;\n }\n\n l_img_comp = &(l_image->comps[l_current_pi->compno]);\n l_img_comp->resno_decoded = opj_uint_max(l_current_pi->resno,\n l_img_comp->resno_decoded);\n } else {\n l_nb_bytes_read = 0;\n if (! opj_t2_skip_packet(p_t2, p_tile, l_tcp, l_current_pi, l_current_data,\n &l_nb_bytes_read, p_max_len, l_pack_info, p_manager)) {\n opj_pi_destroy(l_pi, l_nb_pocs);\n opj_free(first_pass_failed);\n return OPJ_FALSE;\n }\n }\n\n if (first_pass_failed[l_current_pi->compno]) {\n l_img_comp = &(l_image->comps[l_current_pi->compno]);\n if (l_img_comp->resno_decoded == 0) {\n l_img_comp->resno_decoded =\n p_tile->comps[l_current_pi->compno].minimum_num_resolutions - 1;\n }\n }\n\n l_current_data += l_nb_bytes_read;\n p_max_len -= l_nb_bytes_read;\n\n /* INDEX >> */\n#ifdef TODO_MSD\n if (p_cstr_info) {\n opj_tile_info_v2_t *info_TL = &p_cstr_info->tile[p_tile_no];\n opj_packet_info_t *info_PK = &info_TL->packet[p_cstr_info->packno];\n tp_start_packno = 0;\n if (!p_cstr_info->packno) {\n info_PK->start_pos = info_TL->end_header + 1;\n } else if (info_TL->packet[p_cstr_info->packno - 1].end_pos >=\n (OPJ_INT32)\n p_cstr_info->tile[p_tile_no].tp[curtp].tp_end_pos) { /* New tile part */\n info_TL->tp[curtp].tp_numpacks = p_cstr_info->packno -\n tp_start_packno; /* Number of packets in previous tile-part */\n tp_start_packno = p_cstr_info->packno;\n curtp++;\n info_PK->start_pos = p_cstr_info->tile[p_tile_no].tp[curtp].tp_end_header + 1;\n } else {\n info_PK->start_pos = (l_cp->m_specific_param.m_enc.m_tp_on &&\n info_PK->start_pos) ? info_PK->start_pos : info_TL->packet[p_cstr_info->packno -\n 1].end_pos + 1;\n }\n info_PK->end_pos = info_PK->start_pos + l_nb_bytes_read - 1;\n info_PK->end_ph_pos += info_PK->start_pos -\n 1; /* End of packet header which now only represents the distance */\n ++p_cstr_info->packno;\n }\n#endif\n /* << INDEX */\n }\n ++l_current_pi;\n\n opj_free(first_pass_failed);\n }\n /* INDEX >> */\n#ifdef TODO_MSD\n if\n (p_cstr_info) {\n p_cstr_info->tile[p_tile_no].tp[curtp].tp_numpacks = p_cstr_info->packno -\n tp_start_packno; /* Number of packets in last tile-part */\n }\n#endif\n /* << INDEX */\n\n /* don't forget to release pi */\n opj_pi_destroy(l_pi, l_nb_pocs);\n *p_data_read = (OPJ_UINT32)(l_current_data - p_src);\n return OPJ_TRUE;\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: int main(int argc, char **argv)\n{\n\n opj_cparameters_t parameters; /* compression parameters */\n\n opj_stream_t *l_stream = 00;\n opj_codec_t* l_codec = 00;\n opj_image_t *image = NULL;\n raw_cparameters_t raw_cp;\n OPJ_SIZE_T num_compressed_files = 0;\n\n char indexfilename[OPJ_PATH_LEN]; /* index file name */\n\n unsigned int i, num_images, imageno;\n img_fol_t img_fol;\n dircnt_t *dirptr = NULL;\n\n int ret = 0;\n\n OPJ_BOOL bSuccess;\n OPJ_BOOL bUseTiles = OPJ_FALSE; /* OPJ_TRUE */\n OPJ_UINT32 l_nb_tiles = 4;\n int framerate = 0;\n OPJ_FLOAT64 t = opj_clock();\n\n /* set encoding parameters to default values */\n opj_set_default_encoder_parameters(¶meters);\n\n /* Initialize indexfilename and img_fol */\n *indexfilename = 0;\n memset(&img_fol, 0, sizeof(img_fol_t));\n\n /* raw_cp initialization */\n raw_cp.rawBitDepth = 0;\n raw_cp.rawComp = 0;\n raw_cp.rawComps = 0;\n raw_cp.rawHeight = 0;\n raw_cp.rawSigned = 0;\n raw_cp.rawWidth = 0;\n\n /* parse input and get user encoding parameters */\n parameters.tcp_mct = (char)\n 255; /* This will be set later according to the input image or the provided option */\n if (parse_cmdline_encoder(argc, argv, ¶meters, &img_fol, &raw_cp,\n indexfilename, sizeof(indexfilename), &framerate) == 1) {\n ret = 1;\n goto fin;\n }\n\n /* Read directory if necessary */\n if (img_fol.set_imgdir == 1) {\n num_images = get_num_images(img_fol.imgdirpath);\n dirptr = (dircnt_t*)malloc(sizeof(dircnt_t));\n if (dirptr) {\n dirptr->filename_buf = (char*)malloc(num_images * OPJ_PATH_LEN * sizeof(\n char)); /* Stores at max 10 image file names*/\n dirptr->filename = (char**) malloc(num_images * sizeof(char*));\n if (!dirptr->filename_buf) {\n ret = 0;\n goto fin;\n }\n for (i = 0; i < num_images; i++) {\n dirptr->filename[i] = dirptr->filename_buf + i * OPJ_PATH_LEN;\n }\n }\n if (load_images(dirptr, img_fol.imgdirpath) == 1) {\n ret = 0;\n goto fin;\n }\n if (num_images == 0) {\n fprintf(stdout, \"Folder is empty\\n\");\n ret = 0;\n goto fin;\n }\n } else {\n num_images = 1;\n }\n /*Encoding image one by one*/\n for (imageno = 0; imageno < num_images; imageno++) {\n image = NULL;\n fprintf(stderr, \"\\n\");\n\n if (img_fol.set_imgdir == 1) {\n if (get_next_file((int)imageno, dirptr, &img_fol, ¶meters)) {\n fprintf(stderr, \"skipping file...\\n\");\n continue;\n }\n }\n\n switch (parameters.decod_format) {\n case PGX_DFMT:\n break;\n case PXM_DFMT:\n break;\n case BMP_DFMT:\n break;\n case TIF_DFMT:\n break;\n case RAW_DFMT:\n case RAWL_DFMT:\n break;\n case TGA_DFMT:\n break;\n case PNG_DFMT:\n break;\n default:\n fprintf(stderr, \"skipping file...\\n\");\n continue;\n }\n\n /* decode the source image */\n /* ----------------------- */\n\n switch (parameters.decod_format) {\n case PGX_DFMT:\n image = pgxtoimage(parameters.infile, ¶meters);\n if (!image) {\n fprintf(stderr, \"Unable to load pgx file\\n\");\n ret = 1;\n goto fin;\n }\n break;\n\n case PXM_DFMT:\n image = pnmtoimage(parameters.infile, ¶meters);\n if (!image) {\n fprintf(stderr, \"Unable to load pnm file\\n\");\n ret = 1;\n goto fin;\n }\n break;\n\n case BMP_DFMT:\n image = bmptoimage(parameters.infile, ¶meters);\n if (!image) {\n fprintf(stderr, \"Unable to load bmp file\\n\");\n ret = 1;\n goto fin;\n }\n break;\n\n#ifdef OPJ_HAVE_LIBTIFF\n case TIF_DFMT:\n image = tiftoimage(parameters.infile, ¶meters);\n if (!image) {\n fprintf(stderr, \"Unable to load tiff file\\n\");\n ret = 1;\n goto fin;\n }\n break;\n#endif /* OPJ_HAVE_LIBTIFF */\n\n case RAW_DFMT:\n image = rawtoimage(parameters.infile, ¶meters, &raw_cp);\n if (!image) {\n fprintf(stderr, \"Unable to load raw file\\n\");\n ret = 1;\n goto fin;\n }\n break;\n\n case RAWL_DFMT:\n image = rawltoimage(parameters.infile, ¶meters, &raw_cp);\n if (!image) {\n fprintf(stderr, \"Unable to load raw file\\n\");\n ret = 1;\n goto fin;\n }\n break;\n\n case TGA_DFMT:\n image = tgatoimage(parameters.infile, ¶meters);\n if (!image) {\n fprintf(stderr, \"Unable to load tga file\\n\");\n ret = 1;\n goto fin;\n }\n break;\n\n#ifdef OPJ_HAVE_LIBPNG\n case PNG_DFMT:\n image = pngtoimage(parameters.infile, ¶meters);\n if (!image) {\n fprintf(stderr, \"Unable to load png file\\n\");\n ret = 1;\n goto fin;\n }\n break;\n#endif /* OPJ_HAVE_LIBPNG */\n }\n\n /* Can happen if input file is TIFF or PNG\n * and OPJ_HAVE_LIBTIF or OPJ_HAVE_LIBPNG is undefined\n */\n if (!image) {\n fprintf(stderr, \"Unable to load file: got no image\\n\");\n ret = 1;\n goto fin;\n }\n\n /* Decide if MCT should be used */\n if (parameters.tcp_mct == (char)\n 255) { /* mct mode has not been set in commandline */\n parameters.tcp_mct = (image->numcomps >= 3) ? 1 : 0;\n } else { /* mct mode has been set in commandline */\n if ((parameters.tcp_mct == 1) && (image->numcomps < 3)) {\n fprintf(stderr, \"RGB->YCC conversion cannot be used:\\n\");\n fprintf(stderr, \"Input image has less than 3 components\\n\");\n ret = 1;\n goto fin;\n }\n if ((parameters.tcp_mct == 2) && (!parameters.mct_data)) {\n fprintf(stderr, \"Custom MCT has been set but no array-based MCT\\n\");\n fprintf(stderr, \"has been provided. Aborting.\\n\");\n ret = 1;\n goto fin;\n }\n }\n\n if (OPJ_IS_IMF(parameters.rsiz) && framerate > 0) {\n const int mainlevel = OPJ_GET_IMF_MAINLEVEL(parameters.rsiz);\n if (mainlevel > 0 && mainlevel <= OPJ_IMF_MAINLEVEL_MAX) {\n const int limitMSamplesSec[] = {\n 0,\n OPJ_IMF_MAINLEVEL_1_MSAMPLESEC,\n OPJ_IMF_MAINLEVEL_2_MSAMPLESEC,\n OPJ_IMF_MAINLEVEL_3_MSAMPLESEC,\n OPJ_IMF_MAINLEVEL_4_MSAMPLESEC,\n OPJ_IMF_MAINLEVEL_5_MSAMPLESEC,\n OPJ_IMF_MAINLEVEL_6_MSAMPLESEC,\n OPJ_IMF_MAINLEVEL_7_MSAMPLESEC,\n OPJ_IMF_MAINLEVEL_8_MSAMPLESEC,\n OPJ_IMF_MAINLEVEL_9_MSAMPLESEC,\n OPJ_IMF_MAINLEVEL_10_MSAMPLESEC,\n OPJ_IMF_MAINLEVEL_11_MSAMPLESEC\n };\n OPJ_UINT32 avgcomponents = image->numcomps;\n double msamplespersec;\n if (image->numcomps == 3 &&\n image->comps[1].dx == 2 &&\n image->comps[1].dy == 2) {\n avgcomponents = 2;\n }\n msamplespersec = (double)image->x1 * image->y1 * avgcomponents * framerate /\n 1e6;\n if (msamplespersec > limitMSamplesSec[mainlevel]) {\n fprintf(stderr,\n \"Warning: MSamples/sec is %f, whereas limit is %d.\\n\",\n msamplespersec,\n limitMSamplesSec[mainlevel]);\n }\n }\n }\n\n /* encode the destination image */\n /* ---------------------------- */\n\n switch (parameters.cod_format) {\n case J2K_CFMT: { /* JPEG-2000 codestream */\n /* Get a decoder handle */\n l_codec = opj_create_compress(OPJ_CODEC_J2K);\n break;\n }\n case JP2_CFMT: { /* JPEG 2000 compressed image data */\n /* Get a decoder handle */\n l_codec = opj_create_compress(OPJ_CODEC_JP2);\n break;\n }\n default:\n fprintf(stderr, \"skipping file..\\n\");\n opj_stream_destroy(l_stream);\n continue;\n }\n\n /* catch events using our callbacks and give a local context */\n opj_set_info_handler(l_codec, info_callback, 00);\n opj_set_warning_handler(l_codec, warning_callback, 00);\n opj_set_error_handler(l_codec, error_callback, 00);\n\n if (bUseTiles) {\n parameters.cp_tx0 = 0;\n parameters.cp_ty0 = 0;\n parameters.tile_size_on = OPJ_TRUE;\n parameters.cp_tdx = 512;\n parameters.cp_tdy = 512;\n }\n if (! opj_setup_encoder(l_codec, ¶meters, image)) {\n fprintf(stderr, \"failed to encode image: opj_setup_encoder\\n\");\n opj_destroy_codec(l_codec);\n opj_image_destroy(image);\n ret = 1;\n goto fin;\n }\n\n /* open a byte stream for writing and allocate memory for all tiles */\n l_stream = opj_stream_create_default_file_stream(parameters.outfile, OPJ_FALSE);\n if (! l_stream) {\n ret = 1;\n goto fin;\n }\n\n /* encode the image */\n bSuccess = opj_start_compress(l_codec, image, l_stream);\n if (!bSuccess) {\n fprintf(stderr, \"failed to encode image: opj_start_compress\\n\");\n }\n if (bSuccess && bUseTiles) {\n OPJ_BYTE *l_data;\n OPJ_UINT32 l_data_size = 512 * 512 * 3;\n l_data = (OPJ_BYTE*) calloc(1, l_data_size);\n if (l_data == NULL) {\n ret = 1;\n goto fin;\n }\n for (i = 0; i < l_nb_tiles; ++i) {\n if (! opj_write_tile(l_codec, i, l_data, l_data_size, l_stream)) {\n fprintf(stderr, \"ERROR -> test_tile_encoder: failed to write the tile %d!\\n\",\n i);\n opj_stream_destroy(l_stream);\n opj_destroy_codec(l_codec);\n opj_image_destroy(image);\n ret = 1;\n goto fin;\n }\n }\n free(l_data);\n } else {\n bSuccess = bSuccess && opj_encode(l_codec, l_stream);\n if (!bSuccess) {\n fprintf(stderr, \"failed to encode image: opj_encode\\n\");\n }\n }\n bSuccess = bSuccess && opj_end_compress(l_codec, l_stream);\n if (!bSuccess) {\n fprintf(stderr, \"failed to encode image: opj_end_compress\\n\");\n }\n\n if (!bSuccess) {\n opj_stream_destroy(l_stream);\n opj_destroy_codec(l_codec);\n opj_image_destroy(image);\n fprintf(stderr, \"failed to encode image\\n\");\n remove(parameters.outfile);\n ret = 1;\n goto fin;\n }\n\n num_compressed_files++;\n fprintf(stdout, \"[INFO] Generated outfile %s\\n\", parameters.outfile);\n /* close and free the byte stream */\n opj_stream_destroy(l_stream);\n\n /* free remaining compression structures */\n opj_destroy_codec(l_codec);\n\n /* free image data */\n opj_image_destroy(image);\n\n }\n\n t = opj_clock() - t;\n if (num_compressed_files) {\n fprintf(stdout, \"encode time: %d ms \\n\",\n (int)((t * 1000.0) / (OPJ_FLOAT64)num_compressed_files));\n }\n\n ret = 0;\n\nfin:\n if (parameters.cp_comment) {\n free(parameters.cp_comment);\n }\n if (parameters.cp_matrice) {\n free(parameters.cp_matrice);\n }\n if (raw_cp.rawComps) {\n free(raw_cp.rawComps);\n }\n if (img_fol.imgdirpath) {\n free(img_fol.imgdirpath);\n }\n if (dirptr) {\n if (dirptr->filename_buf) {\n free(dirptr->filename_buf);\n }\n if (dirptr->filename) {\n free(dirptr->filename);\n }\n free(dirptr);\n }\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Add support for generation of PLT markers in encoder\n\n* -PLT switch added to opj_compress\n* Add a opj_encoder_set_extra_options() function that\n accepts a PLT=YES option, and could be expanded later\n for other uses.\n\n-------\n\nTesting with a Sentinel2 10m band, T36JTT_20160914T074612_B02.jp2,\ncoming from S2A_MSIL1C_20160914T074612_N0204_R135_T36JTT_20160914T081456.SAFE\n\nDecompress it to TIFF:\n```\nopj_uncompress -i T36JTT_20160914T074612_B02.jp2 -o T36JTT_20160914T074612_B02.tif\n```\n\nRecompress it with similar parameters as original:\n```\nopj_compress -n 5 -c [256,256],[256,256],[256,256],[256,256],[256,256] -t 1024,1024 -PLT -i T36JTT_20160914T074612_B02.tif -o T36JTT_20160914T074612_B02_PLT.jp2\n```\n\nDump codestream detail with GDAL dump_jp2.py utility (https://github.com/OSGeo/gdal/blob/master/gdal/swig/python/samples/dump_jp2.py)\n```\npython dump_jp2.py T36JTT_20160914T074612_B02.jp2 > /tmp/dump_sentinel2_ori.txt\npython dump_jp2.py T36JTT_20160914T074612_B02_PLT.jp2 > /tmp/dump_sentinel2_openjpeg_plt.txt\n```\n\nThe diff between both show very similar structure, and identical number of packets in PLT markers\n\nNow testing with Kakadu (KDU803_Demo_Apps_for_Linux-x86-64_200210)\n\nFull file decompression:\n```\nkdu_expand -i T36JTT_20160914T074612_B02_PLT.jp2 -o tmp.tif\n\nConsumed 121 tile-part(s) from a total of 121 tile(s).\nConsumed 80,318,806 codestream bytes (excluding any file format) = 5.329697\nbits/pel.\nProcessed using the multi-threaded environment, with\n 8 parallel threads of execution\n```\n\nPartial decompresson (presumably using PLT markers):\n```\nkdu_expand -i T36JTT_20160914T074612_B02.jp2 -o tmp.pgm -region \"{0.5,0.5},{0.01,0.01}\"\nkdu_expand -i T36JTT_20160914T074612_B02_PLT.jp2 -o tmp2.pgm -region \"{0.5,0.5},{0.01,0.01}\"\ndiff tmp.pgm tmp2.pgm && echo \"same !\"\n```\n\n-------\n\nFunded by ESA for S2-MPC project'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ipv6_sanity_check(const struct ovs_16aligned_ip6_hdr *nh, size_t size)\n{\n uint16_t plen;\n\n if (OVS_UNLIKELY(size < sizeof *nh)) {\n return false;\n }\n\n plen = ntohs(nh->ip6_plen);\n if (OVS_UNLIKELY(plen + IPV6_HEADER_LEN > size)) {\n return false;\n }\n /* Jumbo Payload option not supported yet. */\n if (OVS_UNLIKELY(size - (plen + IPV6_HEADER_LEN) > UINT8_MAX)) {\n return false;\n }\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 do_dma_pdma_cb(ESPState *s)\n{\n int to_device = ((s->rregs[ESP_RSTAT] & 7) == STAT_DO);\n int len;\n uint32_t n;\n\n if (s->do_cmd) {\n s->ti_size = 0;\n s->do_cmd = 0;\n do_cmd(s);\n esp_lower_drq(s);\n return;\n }\n\n if (to_device) {\n /* Copy FIFO data to device */\n len = MIN(s->async_len, ESP_FIFO_SZ);\n len = MIN(len, fifo8_num_used(&s->fifo));\n memcpy(s->async_buf, fifo8_pop_buf(&s->fifo, len, &n), len);\n s->async_buf += n;\n s->async_len -= n;\n s->ti_size += n;\n\n if (n < len) {\n /* Unaligned accesses can cause FIFO wraparound */\n len = len - n;\n memcpy(s->async_buf, fifo8_pop_buf(&s->fifo, len, &n), len);\n s->async_buf += n;\n s->async_len -= n;\n s->ti_size += n;\n }\n\n if (s->async_len == 0) {\n scsi_req_continue(s->current_req);\n return;\n }\n\n if (esp_get_tc(s) == 0) {\n esp_lower_drq(s);\n esp_dma_done(s);\n }\n\n return;\n } else {\n if (s->async_len == 0) {\n if (s->current_req) {\n /* Defer until the scsi layer has completed */\n scsi_req_continue(s->current_req);\n s->data_in_ready = false;\n }\n return;\n }\n\n if (esp_get_tc(s) != 0) {\n /* Copy device data to FIFO */\n len = MIN(s->async_len, esp_get_tc(s));\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 esp_set_tc(s, esp_get_tc(s) - len);\n\n if (esp_get_tc(s) == 0) {\n /* Indicate transfer to FIFO is complete */\n s->rregs[ESP_RSTAT] |= STAT_TC;\n }\n return;\n }\n\n /* Partially filled a scsi buffer. Complete immediately. */\n esp_lower_drq(s);\n esp_dma_done(s);\n }\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: uint64_t esp_reg_read(ESPState *s, uint32_t saddr)\n{\n uint32_t val;\n\n switch (saddr) {\n case ESP_FIFO:\n if (s->dma_memory_read && s->dma_memory_write &&\n (s->rregs[ESP_RSTAT] & STAT_PIO_MASK) == 0) {\n /* Data out. */\n qemu_log_mask(LOG_UNIMP, \"esp: PIO data read not implemented\\n\");\n s->rregs[ESP_FIFO] = 0;\n } else {\n s->rregs[ESP_FIFO] = esp_fifo_pop(s);\n }\n val = s->rregs[ESP_FIFO];\n break;\n case ESP_RINTR:\n /*\n * Clear sequence step, interrupt register and all status bits\n * except TC\n */\n val = s->rregs[ESP_RINTR];\n s->rregs[ESP_RINTR] = 0;\n s->rregs[ESP_RSTAT] &= ~STAT_TC;\n s->rregs[ESP_RSEQ] = SEQ_0;\n esp_lower_irq(s);\n break;\n case ESP_TCHI:\n /* Return the unique id if the value has never been written */\n if (!s->tchi_written) {\n val = s->chip_id;\n } else {\n val = s->rregs[saddr];\n }\n break;\n case ESP_RFLAGS:\n /* Bottom 5 bits indicate number of bytes in FIFO */\n val = fifo8_num_used(&s->fifo);\n break;\n default:\n val = s->rregs[saddr];\n break;\n }\n\n trace_esp_mem_readb(saddr, val);\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 uint32_t get_cmd(ESPState *s, uint32_t maxlen)\n{\n uint8_t buf[ESP_CMDFIFO_SZ];\n uint32_t dmalen, n;\n int target;\n\n target = s->wregs[ESP_WBUSID] & BUSID_DID;\n if (s->dma) {\n dmalen = MIN(esp_get_tc(s), maxlen);\n if (dmalen == 0) {\n return 0;\n }\n if (s->dma_memory_read) {\n s->dma_memory_read(s->dma_opaque, buf, dmalen);\n fifo8_push_all(&s->cmdfifo, buf, dmalen);\n } else {\n if (esp_select(s) < 0) {\n fifo8_reset(&s->cmdfifo);\n return -1;\n }\n esp_raise_drq(s);\n fifo8_reset(&s->cmdfifo);\n return 0;\n }\n } else {\n dmalen = MIN(fifo8_num_used(&s->fifo), maxlen);\n if (dmalen == 0) {\n return 0;\n }\n n = esp_fifo_pop_buf(&s->fifo, buf, dmalen);\n if (n >= 3) {\n buf[0] = buf[2] >> 5;\n }\n fifo8_push_all(&s->cmdfifo, buf, n);\n }\n trace_esp_get_cmd(dmalen, target);\n\n if (esp_select(s) < 0) {\n fifo8_reset(&s->cmdfifo);\n return -1;\n }\n return dmalen;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'esp: don't overflow cmdfifo in get_cmd()\n\nIf the guest tries to read a CDB using DMA and cmdfifo is not empty then it is\npossible to overflow cmdfifo.\n\nSince this can only occur by issuing deliberately incorrect instruction\nsequences, ensure that the maximum length of the CDB transferred to cmdfifo is\nlimited to the available free space within cmdfifo.\n\nBuglink: https://bugs.launchpad.net/qemu/+bug/1909247\nSigned-off-by: Mark Cave-Ayland \nReviewed-by: Philippe Mathieu-Daud\u00e9 \nTested-by: Alexander Bulekov \nMessage-Id: <20210407195801.685-9-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: table_regex_match(const char *string, const char *pattern)\n{\n\tregex_t preg;\n\tint\tcflags = REG_EXTENDED|REG_NOSUB;\n\n\tif (strncmp(pattern, \"(?i)\", 4) == 0) {\n\t\tcflags |= REG_ICASE;\n\t\tpattern += 4;\n\t}\n\n\tif (regcomp(&preg, pattern, cflags) != 0)\n\t\treturn (0);\n\n\tif (regexec(&preg, string, 0, NULL, 0) != 0)\n\t\treturn (0);\n\n\treturn (1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772', 'CWE-401'], 'message': 'Use regfree after we're done with preg.\n\nFrom 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: iscsi_aio_ioctl_cb(struct iscsi_context *iscsi, int status,\n void *command_data, void *opaque)\n{\n IscsiAIOCB *acb = opaque;\n\n if (status == SCSI_STATUS_CANCELLED) {\n if (!acb->bh) {\n acb->status = -ECANCELED;\n iscsi_schedule_bh(acb);\n }\n return;\n }\n\n acb->status = 0;\n if (status < 0) {\n error_report(\"Failed to ioctl(SG_IO) to iSCSI lun. %s\",\n iscsi_get_error(iscsi));\n acb->status = -iscsi_translate_sense(&acb->task->sense);\n }\n\n acb->ioh->driver_status = 0;\n acb->ioh->host_status = 0;\n acb->ioh->resid = 0;\n acb->ioh->status = status;\n\n#define SG_ERR_DRIVER_SENSE 0x08\n\n if (status == SCSI_STATUS_CHECK_CONDITION && acb->task->datain.size >= 2) {\n int ss;\n\n acb->ioh->driver_status |= SG_ERR_DRIVER_SENSE;\n\n acb->ioh->sb_len_wr = acb->task->datain.size - 2;\n ss = (acb->ioh->mx_sb_len >= acb->ioh->sb_len_wr) ?\n acb->ioh->mx_sb_len : acb->ioh->sb_len_wr;\n memcpy(acb->ioh->sbp, &acb->task->datain.data[2], ss);\n }\n\n iscsi_schedule_bh(acb);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'block/iscsi:fix heap-buffer-overflow in iscsi_aio_ioctl_cb\n\nThere is an overflow, the source 'datain.data[2]' is 100 bytes,\n but the 'ss' is 252 bytes.This may cause a security issue because\n we can access a lot of unrelated memory data.\n\nThe len for sbp copy data should take the minimum of mx_sb_len and\n sb_len_wr, not the maximum.\n\nIf we use iscsi device for VM backend storage, ASAN show stack:\n\nREAD of size 252 at 0xfffd149dcfc4 thread T0\n #0 0xaaad433d0d34 in __asan_memcpy (aarch64-softmmu/qemu-system-aarch64+0x2cb0d34)\n #1 0xaaad45f9d6d0 in iscsi_aio_ioctl_cb /qemu/block/iscsi.c:996:9\n #2 0xfffd1af0e2dc (/usr/lib64/iscsi/libiscsi.so.8+0xe2dc)\n #3 0xfffd1af0d174 (/usr/lib64/iscsi/libiscsi.so.8+0xd174)\n #4 0xfffd1af19fac (/usr/lib64/iscsi/libiscsi.so.8+0x19fac)\n #5 0xaaad45f9acc8 in iscsi_process_read /qemu/block/iscsi.c:403:5\n #6 0xaaad4623733c in aio_dispatch_handler /qemu/util/aio-posix.c:467:9\n #7 0xaaad4622f350 in aio_dispatch_handlers /qemu/util/aio-posix.c:510:20\n #8 0xaaad4622f350 in aio_dispatch /qemu/util/aio-posix.c:520\n #9 0xaaad46215944 in aio_ctx_dispatch /qemu/util/async.c:298:5\n #10 0xfffd1bed12f4 in g_main_context_dispatch (/lib64/libglib-2.0.so.0+0x512f4)\n #11 0xaaad46227de0 in glib_pollfds_poll /qemu/util/main-loop.c:219:9\n #12 0xaaad46227de0 in os_host_main_loop_wait /qemu/util/main-loop.c:242\n #13 0xaaad46227de0 in main_loop_wait /qemu/util/main-loop.c:518\n #14 0xaaad43d9d60c in qemu_main_loop /qemu/softmmu/vl.c:1662:9\n #15 0xaaad4607a5b0 in main /qemu/softmmu/main.c:49:5\n #16 0xfffd1a460b9c in __libc_start_main (/lib64/libc.so.6+0x20b9c)\n #17 0xaaad43320740 in _start (aarch64-softmmu/qemu-system-aarch64+0x2c00740)\n\n0xfffd149dcfc4 is located 0 bytes to the right of 100-byte region [0xfffd149dcf60,0xfffd149dcfc4)\nallocated by thread T0 here:\n #0 0xaaad433d1e70 in __interceptor_malloc (aarch64-softmmu/qemu-system-aarch64+0x2cb1e70)\n #1 0xfffd1af0e254 (/usr/lib64/iscsi/libiscsi.so.8+0xe254)\n #2 0xfffd1af0d174 (/usr/lib64/iscsi/libiscsi.so.8+0xd174)\n #3 0xfffd1af19fac (/usr/lib64/iscsi/libiscsi.so.8+0x19fac)\n #4 0xaaad45f9acc8 in iscsi_process_read /qemu/block/iscsi.c:403:5\n #5 0xaaad4623733c in aio_dispatch_handler /qemu/util/aio-posix.c:467:9\n #6 0xaaad4622f350 in aio_dispatch_handlers /qemu/util/aio-posix.c:510:20\n #7 0xaaad4622f350 in aio_dispatch /qemu/util/aio-posix.c:520\n #8 0xaaad46215944 in aio_ctx_dispatch /qemu/util/async.c:298:5\n #9 0xfffd1bed12f4 in g_main_context_dispatch (/lib64/libglib-2.0.so.0+0x512f4)\n #10 0xaaad46227de0 in glib_pollfds_poll /qemu/util/main-loop.c:219:9\n #11 0xaaad46227de0 in os_host_main_loop_wait /qemu/util/main-loop.c:242\n #12 0xaaad46227de0 in main_loop_wait /qemu/util/main-loop.c:518\n #13 0xaaad43d9d60c in qemu_main_loop /qemu/softmmu/vl.c:1662:9\n #14 0xaaad4607a5b0 in main /qemu/softmmu/main.c:49:5\n #15 0xfffd1a460b9c in __libc_start_main (/lib64/libc.so.6+0x20b9c)\n #16 0xaaad43320740 in _start (aarch64-softmmu/qemu-system-aarch64+0x2c00740)\n\nReported-by: Euler Robot \nSigned-off-by: Chen Qun \nReviewed-by: Stefan Hajnoczi \nMessage-id: 20200418062602.10776-1-kuhn.chenqun@huawei.com\nReviewed-by: Daniel P. Berrang\u00e9 \nSigned-off-by: Peter Maydell '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: MagickPrivate double GenerateDifferentialNoise(RandomInfo *random_info,\n const Quantum pixel,const NoiseType noise_type,const double 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: test_full_context (void)\n{\n g_autoptr(FlatpakBwrap) bwrap = flatpak_bwrap_new (NULL);\n g_autoptr(FlatpakContext) context = flatpak_context_new ();\n g_autoptr(FlatpakExports) exports = NULL;\n g_autoptr(GError) error = NULL;\n g_autoptr(GKeyFile) keyfile = g_key_file_new ();\n g_autofree gchar *text = NULL;\n g_auto(GStrv) strv = NULL;\n gsize i, n;\n\n g_key_file_set_value (keyfile,\n FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_SHARED,\n \"network;ipc;\");\n g_key_file_set_value (keyfile,\n FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_SOCKETS,\n \"x11;wayland;pulseaudio;session-bus;system-bus;\"\n \"fallback-x11;ssh-auth;pcsc;cups;\");\n g_key_file_set_value (keyfile,\n FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_DEVICES,\n \"dri;all;kvm;shm;\");\n g_key_file_set_value (keyfile,\n FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_FEATURES,\n \"devel;multiarch;bluetooth;canbus;\");\n g_key_file_set_value (keyfile,\n FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_FILESYSTEMS,\n \"host;/home;!/opt\");\n g_key_file_set_value (keyfile,\n FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_PERSISTENT,\n \".openarena;\");\n g_key_file_set_value (keyfile,\n FLATPAK_METADATA_GROUP_SESSION_BUS_POLICY,\n \"org.example.SessionService\",\n \"own\");\n g_key_file_set_value (keyfile,\n FLATPAK_METADATA_GROUP_SYSTEM_BUS_POLICY,\n \"net.example.SystemService\",\n \"talk\");\n g_key_file_set_value (keyfile,\n FLATPAK_METADATA_GROUP_ENVIRONMENT,\n \"HYPOTHETICAL_PATH\", \"/foo:/bar\");\n g_key_file_set_value (keyfile,\n FLATPAK_METADATA_GROUP_PREFIX_POLICY \"MyPolicy\",\n \"Colours\", \"blue;green;\");\n\n flatpak_context_load_metadata (context, keyfile, &error);\n g_assert_no_error (error);\n\n g_assert_cmpuint (context->shares, ==,\n (FLATPAK_CONTEXT_SHARED_NETWORK |\n FLATPAK_CONTEXT_SHARED_IPC));\n g_assert_cmpuint (context->shares_valid, ==, context->shares);\n g_assert_cmpuint (context->devices, ==,\n (FLATPAK_CONTEXT_DEVICE_DRI |\n FLATPAK_CONTEXT_DEVICE_ALL |\n FLATPAK_CONTEXT_DEVICE_KVM |\n FLATPAK_CONTEXT_DEVICE_SHM));\n g_assert_cmpuint (context->devices_valid, ==, context->devices);\n g_assert_cmpuint (context->sockets, ==,\n (FLATPAK_CONTEXT_SOCKET_X11 |\n FLATPAK_CONTEXT_SOCKET_WAYLAND |\n FLATPAK_CONTEXT_SOCKET_PULSEAUDIO |\n FLATPAK_CONTEXT_SOCKET_SESSION_BUS |\n FLATPAK_CONTEXT_SOCKET_SYSTEM_BUS |\n FLATPAK_CONTEXT_SOCKET_FALLBACK_X11 |\n FLATPAK_CONTEXT_SOCKET_SSH_AUTH |\n FLATPAK_CONTEXT_SOCKET_PCSC |\n FLATPAK_CONTEXT_SOCKET_CUPS));\n g_assert_cmpuint (context->sockets_valid, ==, context->sockets);\n g_assert_cmpuint (context->features, ==,\n (FLATPAK_CONTEXT_FEATURE_DEVEL |\n FLATPAK_CONTEXT_FEATURE_MULTIARCH |\n FLATPAK_CONTEXT_FEATURE_BLUETOOTH |\n FLATPAK_CONTEXT_FEATURE_CANBUS));\n g_assert_cmpuint (context->features_valid, ==, context->features);\n\n g_assert_cmpuint (flatpak_context_get_run_flags (context), ==,\n (FLATPAK_RUN_FLAG_DEVEL |\n FLATPAK_RUN_FLAG_MULTIARCH |\n FLATPAK_RUN_FLAG_BLUETOOTH |\n FLATPAK_RUN_FLAG_CANBUS));\n\n exports = flatpak_context_get_exports (context, \"com.example.App\");\n g_assert_nonnull (exports);\n\n g_clear_pointer (&exports, flatpak_exports_free);\n flatpak_context_append_bwrap_filesystem (context, bwrap,\n \"com.example.App\",\n NULL,\n NULL,\n &exports);\n print_bwrap (bwrap);\n g_assert_nonnull (exports);\n\n g_clear_pointer (&keyfile, g_key_file_unref);\n keyfile = g_key_file_new ();\n flatpak_context_save_metadata (context, FALSE, keyfile);\n text = g_key_file_to_data (keyfile, NULL, NULL);\n g_test_message (\"Saved:\\n%s\", text);\n g_clear_pointer (&text, g_free);\n\n /* Test that keys round-trip back into the file */\n strv = g_key_file_get_string_list (keyfile, FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_FILESYSTEMS,\n &n, &error);\n g_assert_nonnull (strv);\n /* The order is undefined, so sort them first */\n g_qsort_with_data (strv, n, sizeof (char *),\n (GCompareDataFunc) flatpak_strcmp0_ptr, NULL);\n i = 0;\n g_assert_cmpstr (strv[i++], ==, \"!/opt\");\n g_assert_cmpstr (strv[i++], ==, \"/home\");\n g_assert_cmpstr (strv[i++], ==, \"host\");\n g_assert_cmpstr (strv[i], ==, NULL);\n g_assert_cmpuint (i, ==, n);\n g_clear_pointer (&strv, g_strfreev);\n\n strv = g_key_file_get_string_list (keyfile, FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_SHARED,\n &n, &error);\n g_assert_no_error (error);\n g_assert_nonnull (strv);\n g_qsort_with_data (strv, n, sizeof (char *),\n (GCompareDataFunc) flatpak_strcmp0_ptr, NULL);\n i = 0;\n g_assert_cmpstr (strv[i++], ==, \"ipc\");\n g_assert_cmpstr (strv[i++], ==, \"network\");\n g_assert_cmpstr (strv[i], ==, NULL);\n g_assert_cmpuint (i, ==, n);\n g_clear_pointer (&strv, g_strfreev);\n\n strv = g_key_file_get_string_list (keyfile, FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_SOCKETS,\n &n, &error);\n g_assert_no_error (error);\n g_assert_nonnull (strv);\n g_qsort_with_data (strv, n, sizeof (char *),\n (GCompareDataFunc) flatpak_strcmp0_ptr, NULL);\n i = 0;\n g_assert_cmpstr (strv[i++], ==, \"cups\");\n g_assert_cmpstr (strv[i++], ==, \"fallback-x11\");\n g_assert_cmpstr (strv[i++], ==, \"pcsc\");\n g_assert_cmpstr (strv[i++], ==, \"pulseaudio\");\n g_assert_cmpstr (strv[i++], ==, \"session-bus\");\n g_assert_cmpstr (strv[i++], ==, \"ssh-auth\");\n g_assert_cmpstr (strv[i++], ==, \"system-bus\");\n g_assert_cmpstr (strv[i++], ==, \"wayland\");\n g_assert_cmpstr (strv[i++], ==, \"x11\");\n g_assert_cmpstr (strv[i], ==, NULL);\n g_assert_cmpuint (i, ==, n);\n g_clear_pointer (&strv, g_strfreev);\n\n strv = g_key_file_get_string_list (keyfile, FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_DEVICES,\n &n, &error);\n g_assert_no_error (error);\n g_assert_nonnull (strv);\n g_qsort_with_data (strv, n, sizeof (char *),\n (GCompareDataFunc) flatpak_strcmp0_ptr, NULL);\n i = 0;\n g_assert_cmpstr (strv[i++], ==, \"all\");\n g_assert_cmpstr (strv[i++], ==, \"dri\");\n g_assert_cmpstr (strv[i++], ==, \"kvm\");\n g_assert_cmpstr (strv[i++], ==, \"shm\");\n g_assert_cmpstr (strv[i], ==, NULL);\n g_assert_cmpuint (i, ==, n);\n g_clear_pointer (&strv, g_strfreev);\n\n strv = g_key_file_get_string_list (keyfile, FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_PERSISTENT,\n &n, &error);\n g_assert_no_error (error);\n g_assert_nonnull (strv);\n g_qsort_with_data (strv, n, sizeof (char *),\n (GCompareDataFunc) flatpak_strcmp0_ptr, NULL);\n i = 0;\n g_assert_cmpstr (strv[i++], ==, \".openarena\");\n g_assert_cmpstr (strv[i], ==, NULL);\n g_assert_cmpuint (i, ==, n);\n g_clear_pointer (&strv, g_strfreev);\n\n strv = g_key_file_get_keys (keyfile, FLATPAK_METADATA_GROUP_SESSION_BUS_POLICY,\n &n, &error);\n g_assert_no_error (error);\n g_assert_nonnull (strv);\n g_qsort_with_data (strv, n, sizeof (char *),\n (GCompareDataFunc) flatpak_strcmp0_ptr, NULL);\n i = 0;\n g_assert_cmpstr (strv[i++], ==, \"org.example.SessionService\");\n g_assert_cmpstr (strv[i], ==, NULL);\n g_assert_cmpuint (i, ==, n);\n g_clear_pointer (&strv, g_strfreev);\n\n text = g_key_file_get_string (keyfile, FLATPAK_METADATA_GROUP_SESSION_BUS_POLICY,\n \"org.example.SessionService\", &error);\n g_assert_no_error (error);\n g_assert_cmpstr (text, ==, \"own\");\n g_clear_pointer (&text, g_free);\n\n strv = g_key_file_get_keys (keyfile, FLATPAK_METADATA_GROUP_SYSTEM_BUS_POLICY,\n &n, &error);\n g_assert_no_error (error);\n g_assert_nonnull (strv);\n g_qsort_with_data (strv, n, sizeof (char *),\n (GCompareDataFunc) flatpak_strcmp0_ptr, NULL);\n i = 0;\n g_assert_cmpstr (strv[i++], ==, \"net.example.SystemService\");\n g_assert_cmpstr (strv[i], ==, NULL);\n g_assert_cmpuint (i, ==, n);\n g_clear_pointer (&strv, g_strfreev);\n\n text = g_key_file_get_string (keyfile, FLATPAK_METADATA_GROUP_SYSTEM_BUS_POLICY,\n \"net.example.SystemService\", &error);\n g_assert_no_error (error);\n g_assert_cmpstr (text, ==, \"talk\");\n g_clear_pointer (&text, g_free);\n\n strv = g_key_file_get_keys (keyfile, FLATPAK_METADATA_GROUP_ENVIRONMENT,\n &n, &error);\n g_assert_no_error (error);\n g_assert_nonnull (strv);\n g_qsort_with_data (strv, n, sizeof (char *),\n (GCompareDataFunc) flatpak_strcmp0_ptr, NULL);\n i = 0;\n g_assert_cmpstr (strv[i++], ==, \"HYPOTHETICAL_PATH\");\n g_assert_cmpstr (strv[i], ==, NULL);\n g_assert_cmpuint (i, ==, n);\n g_clear_pointer (&strv, g_strfreev);\n\n text = g_key_file_get_string (keyfile, FLATPAK_METADATA_GROUP_ENVIRONMENT,\n \"HYPOTHETICAL_PATH\", &error);\n g_assert_no_error (error);\n g_assert_cmpstr (text, ==, \"/foo:/bar\");\n g_clear_pointer (&text, g_free);\n\n strv = g_key_file_get_keys (keyfile, FLATPAK_METADATA_GROUP_PREFIX_POLICY \"MyPolicy\",\n &n, &error);\n g_assert_no_error (error);\n g_assert_nonnull (strv);\n g_qsort_with_data (strv, n, sizeof (char *),\n (GCompareDataFunc) flatpak_strcmp0_ptr, NULL);\n i = 0;\n g_assert_cmpstr (strv[i++], ==, \"Colours\");\n g_assert_cmpstr (strv[i], ==, NULL);\n g_assert_cmpuint (i, ==, n);\n g_clear_pointer (&strv, g_strfreev);\n\n strv = g_key_file_get_string_list (keyfile, FLATPAK_METADATA_GROUP_PREFIX_POLICY \"MyPolicy\",\n \"Colours\", &n, &error);\n g_assert_no_error (error);\n g_assert_nonnull (strv);\n g_qsort_with_data (strv, n, sizeof (char *),\n (GCompareDataFunc) flatpak_strcmp0_ptr, NULL);\n i = 0;\n g_assert_cmpstr (strv[i++], ==, \"blue\");\n g_assert_cmpstr (strv[i++], ==, \"green\");\n g_assert_cmpstr (strv[i], ==, NULL);\n g_assert_cmpuint (i, ==, n);\n g_clear_pointer (&strv, g_strfreev);\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: set_cmnd(void)\n{\n struct sudo_nss *nss;\n int ret = FOUND;\n debug_decl(set_cmnd, SUDOERS_DEBUG_PLUGIN);\n\n /* Allocate user_stat for find_path() and match functions. */\n user_stat = calloc(1, sizeof(struct stat));\n if (user_stat == NULL) {\n\tsudo_warnx(U_(\"%s: %s\"), __func__, U_(\"unable to allocate memory\"));\n\tdebug_return_int(NOT_FOUND_ERROR);\n }\n\n /* Default value for cmnd, overridden below. */\n if (user_cmnd == NULL)\n\tuser_cmnd = NewArgv[0];\n\n if (sudo_mode & (MODE_RUN | MODE_EDIT | MODE_CHECK)) {\n\tif (ISSET(sudo_mode, MODE_RUN | MODE_CHECK)) {\n\t const char *runchroot = user_runchroot;\n\t if (runchroot == NULL && def_runchroot != NULL &&\n\t\t strcmp(def_runchroot, \"*\") != 0)\n\t\trunchroot = def_runchroot;\n\n\t ret = set_cmnd_path(runchroot);\n\t if (ret == NOT_FOUND_ERROR) {\n\t\tif (errno == ENAMETOOLONG) {\n\t\t audit_failure(NewArgv, N_(\"command too long\"));\n\t\t}\n\t\tlog_warning(0, \"%s\", NewArgv[0]);\n\t\tdebug_return_int(ret);\n\t }\n\t}\n\n\t/* set user_args */\n\tif (NewArgc > 1) {\n\t char *to, *from, **av;\n\t size_t size, n;\n\n\t /* Alloc and build up user_args. */\n\t for (size = 0, av = NewArgv + 1; *av; av++)\n\t\tsize += strlen(*av) + 1;\n\t if (size == 0 || (user_args = malloc(size)) == NULL) {\n\t\tsudo_warnx(U_(\"%s: %s\"), __func__, U_(\"unable to allocate memory\"));\n\t\tdebug_return_int(NOT_FOUND_ERROR);\n\t }\n\t if (ISSET(sudo_mode, MODE_SHELL|MODE_LOGIN_SHELL)) {\n\t\t/*\n\t\t * When running a command via a shell, the sudo front-end\n\t\t * escapes potential meta chars. We unescape non-spaces\n\t\t * for sudoers matching and logging purposes.\n\t\t */\n\t\tfor (to = user_args, av = NewArgv + 1; (from = *av); av++) {\n\t\t while (*from) {\n\t\t\tif (from[0] == '\\\\' && !isspace((unsigned char)from[1]))\n\t\t\t from++;\n\t\t\t*to++ = *from++;\n\t\t }\n\t\t *to++ = ' ';\n\t\t}\n\t\t*--to = '\\0';\n\t } else {\n\t\tfor (to = user_args, av = NewArgv + 1; *av; av++) {\n\t\t n = strlcpy(to, *av, size - (to - user_args));\n\t\t if (n >= size - (to - user_args)) {\n\t\t\tsudo_warnx(U_(\"internal error, %s overflow\"), __func__);\n\t\t\tdebug_return_int(NOT_FOUND_ERROR);\n\t\t }\n\t\t to += n;\n\t\t *to++ = ' ';\n\t\t}\n\t\t*--to = '\\0';\n\t }\n\t}\n }\n\n if ((user_base = strrchr(user_cmnd, '/')) != NULL)\n\tuser_base++;\n else\n\tuser_base = user_cmnd;\n\n /* Convert \"sudo sudoedit\" -> \"sudoedit\" */\n if (ISSET(sudo_mode, MODE_RUN) && strcmp(user_base, \"sudoedit\") == 0) {\n\tCLR(sudo_mode, MODE_RUN);\n\tSET(sudo_mode, MODE_EDIT);\n\tsudo_warnx(\"%s\", U_(\"sudoedit doesn't need to be run via sudo\"));\n\tuser_base = user_cmnd = \"sudoedit\";\n }\n\n TAILQ_FOREACH(nss, snl, entries) {\n\tif (!update_defaults(nss->parse_tree, NULL, SETDEF_CMND, false)) {\n\t log_warningx(SLOG_SEND_MAIL|SLOG_NO_STDERR,\n\t\tN_(\"problem with defaults entries\"));\n\t}\n }\n\n debug_return_int(ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-193'], 'message': 'Fix potential buffer overflow when unescaping backslashes in user_args.\nAlso, do not try to unescaping backslashes unless in run mode *and*\nwe are running the command via a shell.\nFound by Qualys, this fixes CVE-2021-3156.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int uvc_scan_chain_forward(struct uvc_video_chain *chain,\n\tstruct uvc_entity *entity, struct uvc_entity *prev)\n{\n\tstruct uvc_entity *forward;\n\tint found;\n\n\t/* Forward scan */\n\tforward = NULL;\n\tfound = 0;\n\n\twhile (1) {\n\t\tforward = uvc_entity_by_reference(chain->dev, entity->id,\n\t\t\tforward);\n\t\tif (forward == NULL)\n\t\t\tbreak;\n\t\tif (forward == prev)\n\t\t\tcontinue;\n\n\t\tswitch (UVC_ENTITY_TYPE(forward)) {\n\t\tcase UVC_VC_EXTENSION_UNIT:\n\t\t\tif (forward->bNrInPins != 1) {\n\t\t\t\tuvc_trace(UVC_TRACE_DESCR, \"Extension unit %d \"\n\t\t\t\t\t \"has more than 1 input pin.\\n\",\n\t\t\t\t\t entity->id);\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\n\t\t\tlist_add_tail(&forward->chain, &chain->entities);\n\t\t\tif (uvc_trace_param & UVC_TRACE_PROBE) {\n\t\t\t\tif (!found)\n\t\t\t\t\tprintk(KERN_CONT \" (->\");\n\n\t\t\t\tprintk(KERN_CONT \" XU %d\", forward->id);\n\t\t\t\tfound = 1;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase UVC_OTT_VENDOR_SPECIFIC:\n\t\tcase UVC_OTT_DISPLAY:\n\t\tcase UVC_OTT_MEDIA_TRANSPORT_OUTPUT:\n\t\tcase UVC_TT_STREAMING:\n\t\t\tif (UVC_ENTITY_IS_ITERM(forward)) {\n\t\t\t\tuvc_trace(UVC_TRACE_DESCR, \"Unsupported input \"\n\t\t\t\t\t\"terminal %u.\\n\", forward->id);\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\n\t\t\tlist_add_tail(&forward->chain, &chain->entities);\n\t\t\tif (uvc_trace_param & UVC_TRACE_PROBE) {\n\t\t\t\tif (!found)\n\t\t\t\t\tprintk(KERN_CONT \" (->\");\n\n\t\t\t\tprintk(KERN_CONT \" OT %d\", forward->id);\n\t\t\t\tfound = 1;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (found)\n\t\tprintk(KERN_CONT \")\");\n\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(tvbuff_t *tvb, packet_info *pinfo, int offset, guint32 length, int codec, tvbuff_t **decompressed_tvb, int *decompressed_offset)\n{\n switch (codec) {\n case KAFKA_MESSAGE_CODEC_SNAPPY:\n return decompress_snappy(tvb, pinfo, offset, length, decompressed_tvb, decompressed_offset);\n case KAFKA_MESSAGE_CODEC_LZ4:\n return decompress_lz4(tvb, pinfo, offset, length, decompressed_tvb, decompressed_offset);\n case KAFKA_MESSAGE_CODEC_ZSTD:\n return decompress_zstd(tvb, pinfo, offset, length, decompressed_tvb, decompressed_offset);\n case KAFKA_MESSAGE_CODEC_GZIP:\n return decompress_gzip(tvb, pinfo, offset, length, decompressed_tvb, decompressed_offset);\n case KAFKA_MESSAGE_CODEC_NONE:\n return decompress_none(tvb, pinfo, offset, length, decompressed_tvb, decompressed_offset);\n default:\n col_append_str(pinfo->cinfo, COL_INFO, \" [unsupported compression type]\");\n return 0;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'Kafka: Limit our decompression size.\n\nDon't assume that the Internet has our best interests at heart when it\ngives us the size of our decompression buffer. Assign an arbitrary limit\nof 50 MB.\n\nThis fixes #16739 in that it takes care of\n\n** (process:17681): WARNING **: 20:03:07.440: Dissector bug, protocol Kafka, in packet 31: ../epan/proto.c:7043: failed assertion \"end >= fi->start\"\n\nwhich is different from the original error output. It looks like *that*\nmight have taken care of in one of the other recent Kafka bug fixes.\n\nThe decompression routines return a success or failure status. Use\ngbooleans instead of ints for that.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline void hid_map_usage(struct hid_input *hidinput,\n\t\tstruct hid_usage *usage, unsigned long **bit, int *max,\n\t\t__u8 type, __u16 c)\n{\n\tstruct input_dev *input = hidinput->input;\n\n\tusage->type = type;\n\tusage->code = c;\n\n\tswitch (type) {\n\tcase EV_ABS:\n\t\t*bit = input->absbit;\n\t\t*max = ABS_MAX;\n\t\tbreak;\n\tcase EV_REL:\n\t\t*bit = input->relbit;\n\t\t*max = REL_MAX;\n\t\tbreak;\n\tcase EV_KEY:\n\t\t*bit = input->keybit;\n\t\t*max = KEY_MAX;\n\t\tbreak;\n\tcase EV_LED:\n\t\t*bit = input->ledbit;\n\t\t*max = LED_MAX;\n\t\tbreak;\n\t}\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: authzPrettyNormal(\n\tstruct berval\t*val,\n\tstruct berval\t*normalized,\n\tvoid\t\t*ctx,\n\tint\t\tnormalize )\n{\n\tstruct berval\tbv;\n\tint\t\trc = LDAP_INVALID_SYNTAX;\n\tLDAPURLDesc\t*ludp = NULL;\n\tchar\t\t*lud_dn = NULL,\n\t\t\t*lud_filter = 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( val != NULL );\n\tassert( !BER_BVISNULL( val ) );\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( val->bv_val, \"dn\", STRLENOF( \"dn\" ) ) ) {\n\t\tstruct berval\tout = BER_BVNULL,\n\t\t\t\tprefix = BER_BVNULL;\n\t\tchar\t\t*ptr;\n\n\t\tbv.bv_val = val->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 = val->bv_len - ( bv.bv_val - val->bv_val );\n\n\t\t/* a single '*' means any DN without using regexes */\n\t\tif ( ber_bvccmp( &bv, '*' ) ) {\n\t\t\tber_str2bv_x( \"dn:*\", STRLENOF( \"dn:*\" ), 1, normalized, ctx );\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\tif ( normalize ) {\n\t\t\t\trc = dnNormalize( 0, NULL, NULL, &bv, &out, ctx );\n\t\t\t} else {\n\t\t\t\trc = dnPretty( NULL, &bv, &out, ctx );\n\t\t\t}\n\t\t\tif( rc != LDAP_SUCCESS ) {\n\t\t\t\treturn LDAP_INVALID_SYNTAX;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase LDAP_X_SCOPE_REGEX:\n\t\t\tnormalized->bv_len = STRLENOF( \"dn.regex:\" ) + bv.bv_len;\n\t\t\tnormalized->bv_val = ber_memalloc_x( normalized->bv_len + 1, ctx );\n\t\t\tptr = lutil_strcopy( normalized->bv_val, \"dn.regex:\" );\n\t\t\tptr = lutil_strncopy( ptr, bv.bv_val, bv.bv_len );\n\t\t\tptr[ 0 ] = '\\0';\n\t\t\treturn LDAP_SUCCESS;\n\n\t\tdefault:\n\t\t\treturn LDAP_INVALID_SYNTAX;\n\t\t}\n\n\t\t/* prepare prefix */\n\t\tswitch ( scope ) {\n\t\tcase LDAP_X_SCOPE_EXACT:\n\t\t\tBER_BVSTR( &prefix, \"dn:\" );\n\t\t\tbreak;\n\n\t\tcase LDAP_X_SCOPE_CHILDREN:\n\t\t\tBER_BVSTR( &prefix, \"dn.children:\" );\n\t\t\tbreak;\n\n\t\tcase LDAP_X_SCOPE_SUBTREE:\n\t\t\tBER_BVSTR( &prefix, \"dn.subtree:\" );\n\t\t\tbreak;\n\n\t\tcase LDAP_X_SCOPE_ONELEVEL:\n\t\t\tBER_BVSTR( &prefix, \"dn.onelevel:\" );\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tassert( 0 );\n\t\t\tbreak;\n\t\t}\n\n\t\tnormalized->bv_len = prefix.bv_len + out.bv_len;\n\t\tnormalized->bv_val = ber_memalloc_x( normalized->bv_len + 1, ctx );\n\t\t\n\t\tptr = lutil_strcopy( normalized->bv_val, prefix.bv_val );\n\t\tptr = lutil_strncopy( ptr, out.bv_val, out.bv_len );\n\t\tptr[ 0 ] = '\\0';\n\t\tber_memfree_x( out.bv_val, ctx );\n\n\t\treturn LDAP_SUCCESS;\n\n\t/*\n\t * 4) u[.mech[/realm]]:\n\t */\n\t} else if ( ( val->bv_val[ 0 ] == 'u' || val->bv_val[ 0 ] == 'U' )\n\t\t\t&& ( val->bv_val[ 1 ] == ':' \n\t\t\t\t|| val->bv_val[ 1 ] == '/' \n\t\t\t\t|| val->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 ) <= val->bv_len ) {\n\t\t\treturn LDAP_INVALID_SYNTAX;\n\t\t}\n\n\t\tid.bv_len = val->bv_len;\n\t\tid.bv_val = buf;\n\t\tstrncpy( buf, val->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\tber_dupbv_x( normalized, val, ctx );\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( val->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\t\t\t\tout = BER_BVNULL;\n\t\tchar\t\t*ptr;\n\n\t\tbv.bv_val = val->bv_val + STRLENOF( \"group\" );\n\t\tbv.bv_len = val->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 = val->bv_val;\n\t\t\tscope = LDAP_X_SCOPE_EXACT;\n\t\t\tgoto is_dn;\n\t\t}\n\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\tObjectClass\t\t*oc = NULL;\n\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\n\t\t\t\tmember_at = ad->ad_cname;\n\n\t\t\t}\n\n\t\t\toc = oc_bvfind( &group_oc );\n\t\t\tif ( oc == NULL ) {\n\t\t\t\treturn LDAP_INVALID_SYNTAX;\n\t\t\t}\n\n\t\t\tgroup_oc = oc->soc_cname;\n\t\t}\n\n\t\tgroup_dn.bv_val++;\n\t\tgroup_dn.bv_len = val->bv_len - ( group_dn.bv_val - val->bv_val );\n\n\t\tif ( normalize ) {\n\t\t\trc = dnNormalize( 0, NULL, NULL, &group_dn, &out, ctx );\n\t\t} else {\n\t\t\trc = dnPretty( NULL, &group_dn, &out, ctx );\n\t\t}\n\t\tif ( rc != LDAP_SUCCESS ) {\n\t\t\treturn rc;\n\t\t}\n\n\t\tnormalized->bv_len = STRLENOF( \"group\" \":\" ) + out.bv_len;\n\t\tif ( !BER_BVISNULL( &group_oc ) ) {\n\t\t\tnormalized->bv_len += STRLENOF( \"/\" ) + group_oc.bv_len;\n\t\t\tif ( !BER_BVISNULL( &member_at ) ) {\n\t\t\t\tnormalized->bv_len += STRLENOF( \"/\" ) + member_at.bv_len;\n\t\t\t}\n\t\t}\n\n\t\tnormalized->bv_val = ber_memalloc_x( normalized->bv_len + 1, ctx );\n\t\tptr = lutil_strcopy( normalized->bv_val, \"group\" );\n\t\tif ( !BER_BVISNULL( &group_oc ) ) {\n\t\t\tptr[ 0 ] = '/';\n\t\t\tptr++;\n\t\t\tptr = lutil_strncopy( ptr, group_oc.bv_val, group_oc.bv_len );\n\t\t\tif ( !BER_BVISNULL( &member_at ) ) {\n\t\t\t\tptr[ 0 ] = '/';\n\t\t\t\tptr++;\n\t\t\t\tptr = lutil_strncopy( ptr, member_at.bv_val, member_at.bv_len );\n\t\t\t}\n\t\t}\n\t\tptr[ 0 ] = ':';\n\t\tptr++;\n\t\tptr = lutil_strncopy( ptr, out.bv_val, out.bv_len );\n\t\tptr[ 0 ] = '\\0';\n\t\tber_memfree_x( out.bv_val, ctx );\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( val->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\n\t\tAC_MEMCPY( ludp->lud_scheme, \"ldap\", STRLENOF( \"ldap\" ) );\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 = val->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\tstruct berval\tfilterstr;\n\t\tFilter\t\t*f;\n\n\t\tlud_filter = ludp->lud_filter;\n\n\t\tf = str2filter( lud_filter );\n\t\tif ( f == NULL ) {\n\t\t\trc = LDAP_INVALID_SYNTAX;\n\t\t\tgoto done;\n\t\t}\n\t\tfilter2bv( f, &filterstr );\n\t\tfilter_free( f );\n\t\tif ( BER_BVISNULL( &filterstr ) ) {\n\t\t\trc = LDAP_INVALID_SYNTAX;\n\t\t\tgoto done;\n\t\t}\n\n\t\tludp->lud_filter = filterstr.bv_val;\n\t}\n\n\t/* Grab the searchbase */\n\tif ( ludp->lud_dn ) {\n\t\tstruct berval\tout = BER_BVNULL;\n\n\t\tlud_dn = ludp->lud_dn;\n\n\t\tber_str2bv( lud_dn, 0, 0, &bv );\n\t\tif ( normalize ) {\n\t\t\trc = dnNormalize( 0, NULL, NULL, &bv, &out, ctx );\n\t\t} else {\n\t\t\trc = dnPretty( NULL, &bv, &out, ctx );\n\t\t}\n\n\t\tif ( rc != LDAP_SUCCESS ) {\n\t\t\tgoto done;\n\t\t}\n\n\t\tludp->lud_dn = out.bv_val;\n\t} else {\n\t\trc = LDAP_INVALID_SYNTAX;\n\t\tgoto done;\n\t}\n\n\tludp->lud_port = 0;\n\tnormalized->bv_val = ldap_url_desc2str( ludp );\n\tif ( normalized->bv_val ) {\n\t\tnormalized->bv_len = strlen( normalized->bv_val );\n\n\t} else {\n\t\trc = LDAP_INVALID_SYNTAX;\n\t}\n\ndone:\n\tif ( lud_filter ) {\n\t\tif ( ludp->lud_filter != lud_filter ) {\n\t\t\tber_memfree( ludp->lud_filter );\n\t\t}\n\t\tludp->lud_filter = lud_filter;\n\t}\n\n\tif ( lud_dn ) {\n\t\tif ( ludp->lud_dn != lud_dn ) {\n\t\t\tber_memfree( ludp->lud_dn );\n\t\t}\n\t\tludp->lud_dn = lud_dn;\n\t}\n\n\tldap_free_urldesc( ludp );\n\n\treturn( rc );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'ITS#9406 fix debug msg'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: 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-191'], 'message': 'ITS#9427 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: void main_cleanup() {\n#ifdef USE_OS_THREADS\n CLI *c;\n unsigned i, threads;\n THREAD_ID *thread_list;\n\n CRYPTO_THREAD_write_lock(stunnel_locks[LOCK_THREAD_LIST]);\n threads=0;\n for(c=thread_head; c; c=c->thread_next) /* count client threads */\n threads++;\n thread_list=str_alloc((threads+1)*sizeof(THREAD_ID));\n i=0;\n for(c=thread_head; c; c=c->thread_next) { /* copy client threads */\n thread_list[i++]=c->thread_id;\n s_log(LOG_DEBUG, \"Terminating a thread for [%s]\", c->opt->servname);\n }\n if(cron_thread_id) { /* append cron_thread_id if used */\n thread_list[threads++]=cron_thread_id;\n s_log(LOG_DEBUG, \"Terminating the cron thread\");\n }\n CRYPTO_THREAD_unlock(stunnel_locks[LOCK_THREAD_LIST]);\n\n if(threads) {\n s_log(LOG_NOTICE, \"Terminating %u service thread(s)\", threads);\n writesocket(terminate_pipe[1], \"\", 1);\n for(i=0; i \"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 options_parse(CONF_TYPE type) {\n SERVICE_OPTIONS *section;\n\n options_defaults();\n section=&new_service_options;\n if(options_file(configuration_file, type, §ion))\n return 1;\n if(init_section(1, §ion))\n return 1;\n\n s_log(LOG_NOTICE, \"Configuration successful\");\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-295'], 'message': 'stunnel-5.57'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int bind_ports(void) {\n SERVICE_OPTIONS *opt;\n int listening_section;\n\n#ifdef USE_LIBWRAP\n /* execute after options_cmdline() to know service_options.next,\n * but as early as possible to avoid leaking file descriptors */\n /* retry on each bind_ports() in case stunnel.conf was reloaded\n without \"libwrap = no\" */\n libwrap_init();\n#endif /* USE_LIBWRAP */\n\n s_poll_init(fds, 1);\n\n /* allow clean unbind_ports() even though\n bind_ports() was not fully performed */\n for(opt=service_options.next; opt; opt=opt->next) {\n unsigned i;\n for(i=0; ilocal_addr.num; ++i)\n opt->local_fd[i]=INVALID_SOCKET;\n }\n\n listening_section=0;\n for(opt=service_options.next; opt; opt=opt->next) {\n opt->bound_ports=0;\n if(opt->local_addr.num) { /* ports to bind for this service */\n unsigned i;\n s_log(LOG_DEBUG, \"Binding service [%s]\", opt->servname);\n for(i=0; ilocal_addr.num; ++i) {\n SOCKET fd;\n fd=bind_port(opt, listening_section, i);\n opt->local_fd[i]=fd;\n if(fd!=INVALID_SOCKET) {\n s_poll_add(fds, fd, 1, 0);\n ++opt->bound_ports;\n }\n }\n if(!opt->bound_ports) {\n s_log(LOG_ERR, \"Binding service [%s] failed\", opt->servname);\n return 1;\n }\n ++listening_section;\n } else if(opt->exec_name && opt->connect_addr.names) {\n s_log(LOG_DEBUG, \"Skipped exec+connect service [%s]\", opt->servname);\n#ifndef OPENSSL_NO_TLSEXT\n } else if(!opt->option.client && opt->sni) {\n s_log(LOG_DEBUG, \"Skipped SNI slave service [%s]\", opt->servname);\n#endif\n } else { /* each service must define two endpoints */\n s_log(LOG_ERR, \"Invalid service [%s]\", opt->servname);\n return 1;\n }\n }\n if(listening_section \"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: static HashTable* wsdl_message(sdlCtx *ctx, xmlChar* message_name)\n{\n\txmlNodePtr trav, part, message = NULL, tmp;\n\tHashTable* parameters = NULL;\n\tchar *ctype;\n\n\tctype = strrchr((char*)message_name,':');\n\tif (ctype == NULL) {\n\t\tctype = (char*)message_name;\n\t} else {\n\t\t++ctype;\n\t}\n\tif ((tmp = zend_hash_str_find_ptr(&ctx->messages, ctype, strlen(ctype))) == NULL) {\n\t\tsoap_error1(E_ERROR, \"Parsing WSDL: Missing with name '%s'\", message_name);\n\t}\n\tmessage = tmp;\n\n\tparameters = emalloc(sizeof(HashTable));\n\tzend_hash_init(parameters, 0, NULL, delete_parameter, 0);\n\n\ttrav = message->children;\n\twhile (trav != NULL) {\n\t\txmlAttrPtr element, type, name;\n\t\tsdlParamPtr param;\n\n\t\tif (trav->ns != NULL && strcmp((char*)trav->ns->href, WSDL_NAMESPACE) != 0) {\n\t\t\tsoap_error1(E_ERROR, \"Parsing WSDL: Unexpected extensibility element <%s>\", trav->name);\n\t\t}\n\t\tif (node_is_equal(trav,\"documentation\")) {\n\t\t\ttrav = trav->next;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!node_is_equal(trav,\"part\")) {\n\t\t\tsoap_error1(E_ERROR, \"Parsing WSDL: Unexpected WSDL element <%s>\", trav->name);\n\t\t}\n\t\tpart = trav;\n\t\tparam = emalloc(sizeof(sdlParam));\n\t\tmemset(param,0,sizeof(sdlParam));\n\t\tparam->order = 0;\n\n\t\tname = get_attribute(part->properties, \"name\");\n\t\tif (name == NULL) {\n\t\t\tsoap_error1(E_ERROR, \"Parsing WSDL: No name associated with '%s'\", message->name);\n\t\t}\n\n\t\tparam->paramName = estrdup((char*)name->children->content);\n\n\t\ttype = get_attribute(part->properties, \"type\");\n\t\tif (type != NULL) {\n\t\t\tparam->encode = get_encoder_from_prefix(ctx->sdl, part, type->children->content);\n\t\t} else {\n\t\t\telement = get_attribute(part->properties, \"element\");\n\t\t\tif (element != NULL) {\n\t\t\t\tparam->element = get_element(ctx->sdl, part, element->children->content);\n\t\t\t\tif (param->element) {\n\t\t\t\t\tparam->encode = param->element->encode;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tzend_hash_next_index_insert_ptr(parameters, param);\n\n\t\ttrav = trav->next;\n\t}\n\treturn parameters;\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: static char *uncompress(int16_t field_count, char *start, char *end,\n\t\t\tchar *ptr, char *uncompressed, int uncomp_len,\n\t\t\tchar **uncompressed_ptr)\n{\n\tchar *uptr = *uncompressed_ptr; /* position in result buffer */\n\n\tdebug(\"count %d ptr %p end %p uptr %p\", field_count, ptr, end, uptr);\n\n\twhile (field_count-- > 0 && ptr < end) {\n\t\tint dlen;\t\t/* data field length */\n\t\tint ulen;\t\t/* uncompress length */\n\t\tint pos;\t\t/* position in compressed string */\n\t\tchar name[NS_MAXLABEL]; /* tmp label */\n\t\tuint16_t dns_type, dns_class;\n\t\tint comp_pos;\n\n\t\tif (!convert_label(start, end, ptr, name, NS_MAXLABEL,\n\t\t\t\t\t&pos, &comp_pos))\n\t\t\tgoto out;\n\n\t\t/*\n\t\t * Copy the uncompressed resource record, type, class and \\0 to\n\t\t * tmp buffer.\n\t\t */\n\n\t\tulen = strlen(name);\n\t\tstrncpy(uptr, name, uncomp_len - (uptr - uncompressed));\n\n\t\tdebug(\"pos %d ulen %d left %d name %s\", pos, ulen,\n\t\t\t(int)(uncomp_len - (uptr - uncompressed)), uptr);\n\n\t\tuptr += ulen;\n\t\t*uptr++ = '\\0';\n\n\t\tptr += pos;\n\n\t\t/*\n\t\t * We copy also the fixed portion of the result (type, class,\n\t\t * ttl, address length and the address)\n\t\t */\n\t\tmemcpy(uptr, ptr, NS_RRFIXEDSZ);\n\n\t\tdns_type = uptr[0] << 8 | uptr[1];\n\t\tdns_class = uptr[2] << 8 | uptr[3];\n\n\t\tif (dns_class != ns_c_in)\n\t\t\tgoto out;\n\n\t\tptr += NS_RRFIXEDSZ;\n\t\tuptr += NS_RRFIXEDSZ;\n\n\t\t/*\n\t\t * Then the variable portion of the result (data length).\n\t\t * Typically this portion is also compressed\n\t\t * so we need to uncompress it also when necessary.\n\t\t */\n\t\tif (dns_type == ns_t_cname) {\n\t\t\tif (!convert_label(start, end, ptr, uptr,\n\t\t\t\t\tuncomp_len - (uptr - uncompressed),\n\t\t\t\t\t\t&pos, &comp_pos))\n\t\t\t\tgoto out;\n\n\t\t\tuptr[-2] = comp_pos << 8;\n\t\t\tuptr[-1] = comp_pos & 0xff;\n\n\t\t\tuptr += comp_pos;\n\t\t\tptr += pos;\n\n\t\t} else if (dns_type == ns_t_a || dns_type == ns_t_aaaa) {\n\t\t\tdlen = uptr[-2] << 8 | uptr[-1];\n\n\t\t\tif (ptr + dlen > end) {\n\t\t\t\tdebug(\"data len %d too long\", dlen);\n\t\t\t\tgoto out;\n\t\t\t}\n\n\t\t\tmemcpy(uptr, ptr, dlen);\n\t\t\tuptr += dlen;\n\t\t\tptr += dlen;\n\n\t\t} else if (dns_type == ns_t_soa) {\n\t\t\tint total_len = 0;\n\t\t\tchar *len_ptr;\n\n\t\t\t/* Primary name server expansion */\n\t\t\tif (!convert_label(start, end, ptr, uptr,\n\t\t\t\t\tuncomp_len - (uptr - uncompressed),\n\t\t\t\t\t\t&pos, &comp_pos))\n\t\t\t\tgoto out;\n\n\t\t\ttotal_len += comp_pos;\n\t\t\tlen_ptr = &uptr[-2];\n\t\t\tptr += pos;\n\t\t\tuptr += comp_pos;\n\n\t\t\t/* Responsible authority's mailbox */\n\t\t\tif (!convert_label(start, end, ptr, uptr,\n\t\t\t\t\tuncomp_len - (uptr - uncompressed),\n\t\t\t\t\t\t&pos, &comp_pos))\n\t\t\t\tgoto out;\n\n\t\t\ttotal_len += comp_pos;\n\t\t\tptr += pos;\n\t\t\tuptr += comp_pos;\n\n\t\t\t/*\n\t\t\t * Copy rest of the soa fields (serial number,\n\t\t\t * refresh interval, retry interval, expiration\n\t\t\t * limit and minimum ttl). They are 20 bytes long.\n\t\t\t */\n\t\t\tmemcpy(uptr, ptr, 20);\n\t\t\tuptr += 20;\n\t\t\tptr += 20;\n\t\t\ttotal_len += 20;\n\n\t\t\t/*\n\t\t\t * Finally fix the length of the data part\n\t\t\t */\n\t\t\tlen_ptr[0] = total_len << 8;\n\t\t\tlen_ptr[1] = total_len & 0xff;\n\t\t}\n\n\t\t*uncompressed_ptr = uptr;\n\t}\n\n\treturn ptr;\n\nout:\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'dnsproxy: Add length checks to prevent buffer overflow\n\nFixes: CVE-2021-26675'" }, { "text": "[INST] Given the following code containing errors, provide Common 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 hdrblobInit(const void *uh, size_t uc,\n\t\trpmTagVal regionTag, int exact_size,\n\t\tstruct hdrblob_s *blob, char **emsg)\n{\n rpmRC rc = RPMRC_FAIL;\n\n memset(blob, 0, sizeof(*blob));\n blob->ei = (int32_t *) uh; /* discards const */\n blob->il = ntohl(blob->ei[0]);\n blob->dl = ntohl(blob->ei[1]);\n blob->pe = (entryInfo) &(blob->ei[2]);\n blob->pvlen = sizeof(blob->il) + sizeof(blob->dl) +\n\t\t (blob->il * sizeof(*blob->pe)) + blob->dl;\n blob->dataStart = (uint8_t *) (blob->pe + blob->il);\n blob->dataEnd = blob->dataStart + blob->dl;\n\n /* Is the blob the right size? */\n if (blob->pvlen >= headerMaxbytes || (uc && blob->pvlen != uc)) {\n\trasprintf(emsg, _(\"blob size(%d): BAD, 8 + 16 * il(%d) + dl(%d)\"),\n\t\t\tblob->pvlen, blob->il, blob->dl);\n\tgoto exit;\n }\n\n if (hdrblobVerifyRegion(regionTag, exact_size, blob, emsg) == RPMRC_FAIL)\n\tgoto exit;\n\n /* Sanity check the rest of the header structure. */\n if (hdrblobVerifyInfo(blob, emsg))\n\tgoto exit;\n\n rc = RPMRC_OK;\n\nexit:\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 = slap_sl_malloc( 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_host_get_param(struct Scsi_Host *shost, enum iscsi_host_param param,\n\t\t\t char *buf)\n{\n\tstruct iscsi_host *ihost = shost_priv(shost);\n\tint len;\n\n\tswitch (param) {\n\tcase ISCSI_HOST_PARAM_NETDEV_NAME:\n\t\tlen = sprintf(buf, \"%s\\n\", ihost->netdev);\n\t\tbreak;\n\tcase ISCSI_HOST_PARAM_HWADDRESS:\n\t\tlen = sprintf(buf, \"%s\\n\", ihost->hwaddress);\n\t\tbreak;\n\tcase ISCSI_HOST_PARAM_INITIATOR_NAME:\n\t\tlen = sprintf(buf, \"%s\\n\", ihost->initiatorname);\n\t\tbreak;\n\tdefault:\n\t\treturn -ENOSYS;\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 int intel_engine_setup(struct intel_gt *gt, enum intel_engine_id id)\n{\n\tconst struct engine_info *info = &intel_engines[id];\n\tstruct drm_i915_private *i915 = gt->i915;\n\tstruct intel_engine_cs *engine;\n\n\tBUILD_BUG_ON(MAX_ENGINE_CLASS >= BIT(GEN11_ENGINE_CLASS_WIDTH));\n\tBUILD_BUG_ON(MAX_ENGINE_INSTANCE >= BIT(GEN11_ENGINE_INSTANCE_WIDTH));\n\n\tif (GEM_DEBUG_WARN_ON(id >= ARRAY_SIZE(gt->engine)))\n\t\treturn -EINVAL;\n\n\tif (GEM_DEBUG_WARN_ON(info->class > MAX_ENGINE_CLASS))\n\t\treturn -EINVAL;\n\n\tif (GEM_DEBUG_WARN_ON(info->instance > MAX_ENGINE_INSTANCE))\n\t\treturn -EINVAL;\n\n\tif (GEM_DEBUG_WARN_ON(gt->engine_class[info->class][info->instance]))\n\t\treturn -EINVAL;\n\n\tengine = kzalloc(sizeof(*engine), GFP_KERNEL);\n\tif (!engine)\n\t\treturn -ENOMEM;\n\n\tBUILD_BUG_ON(BITS_PER_TYPE(engine->mask) < I915_NUM_ENGINES);\n\n\tengine->id = id;\n\tengine->legacy_idx = INVALID_ENGINE;\n\tengine->mask = BIT(id);\n\tengine->i915 = i915;\n\tengine->gt = gt;\n\tengine->uncore = gt->uncore;\n\tengine->hw_id = engine->guc_id = info->hw_id;\n\tengine->mmio_base = __engine_mmio_base(i915, info->mmio_bases);\n\n\tengine->class = info->class;\n\tengine->instance = info->instance;\n\t__sprint_engine_name(engine);\n\n\tengine->props.heartbeat_interval_ms =\n\t\tCONFIG_DRM_I915_HEARTBEAT_INTERVAL;\n\tengine->props.max_busywait_duration_ns =\n\t\tCONFIG_DRM_I915_MAX_REQUEST_BUSYWAIT;\n\tengine->props.preempt_timeout_ms =\n\t\tCONFIG_DRM_I915_PREEMPT_TIMEOUT;\n\tengine->props.stop_timeout_ms =\n\t\tCONFIG_DRM_I915_STOP_TIMEOUT;\n\tengine->props.timeslice_duration_ms =\n\t\tCONFIG_DRM_I915_TIMESLICE_DURATION;\n\n\t/* Override to uninterruptible for OpenCL workloads. */\n\tif (INTEL_GEN(i915) == 12 && engine->class == RENDER_CLASS)\n\t\tengine->props.preempt_timeout_ms = 0;\n\n\tengine->defaults = engine->props; /* never to change again */\n\n\tengine->context_size = intel_engine_context_size(gt, engine->class);\n\tif (WARN_ON(engine->context_size > BIT(20)))\n\t\tengine->context_size = 0;\n\tif (engine->context_size)\n\t\tDRIVER_CAPS(i915)->has_logical_contexts = true;\n\n\t/* Nothing to do here, execute in order of dependencies */\n\tengine->schedule = NULL;\n\n\tewma__engine_latency_init(&engine->latency);\n\tseqlock_init(&engine->stats.lock);\n\n\tATOMIC_INIT_NOTIFIER_HEAD(&engine->context_status_notifier);\n\n\t/* Scrub mmio state on takeover */\n\tintel_engine_sanitize_mmio(engine);\n\n\tgt->engine_class[info->class][info->instance] = engine;\n\tgt->engine[id] = engine;\n\n\treturn 0;\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: gtTileContig(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)\n{\n TIFF* tif = img->tif;\n tileContigRoutine put = img->put.contig;\n uint32 col, row, y, rowstoread;\n tmsize_t pos;\n uint32 tw, th;\n unsigned char* buf = NULL;\n int32 fromskew, toskew;\n uint32 nrow;\n int ret = 1, flip;\n uint32 this_tw, tocol;\n int32 this_toskew, leftmost_toskew;\n int32 leftmost_fromskew;\n uint32 leftmost_tw;\n tmsize_t bufsize;\n\n bufsize = TIFFTileSize(tif);\n if (bufsize == 0) {\n TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), \"%s\", \"No space for tile buffer\");\n return (0);\n }\n\n TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw);\n TIFFGetField(tif, TIFFTAG_TILELENGTH, &th);\n\n flip = setorientation(img);\n if (flip & FLIP_VERTICALLY) {\n\t y = h - 1;\n\t toskew = -(int32)(tw + w);\n }\n else {\n\t y = 0;\n\t toskew = -(int32)(tw - w);\n }\n \n /*\n *\tLeftmost tile is clipped on left side if col_offset > 0.\n */\n leftmost_fromskew = img->col_offset % tw;\n leftmost_tw = tw - leftmost_fromskew;\n leftmost_toskew = toskew + leftmost_fromskew;\n for (row = 0; ret != 0 && row < h; row += nrow)\n {\n rowstoread = th - (row + img->row_offset) % th;\n \tnrow = (row + rowstoread > h ? h - row : rowstoread);\n\tfromskew = leftmost_fromskew;\n\tthis_tw = leftmost_tw;\n\tthis_toskew = leftmost_toskew;\n\ttocol = 0;\n\tcol = img->col_offset;\n\twhile (tocol < w)\n {\n\t if (_TIFFReadTileAndAllocBuffer(tif, (void**) &buf, bufsize, col,\n\t\t\t row+img->row_offset, 0, 0)==(tmsize_t)(-1) &&\n (buf == NULL || img->stoponerr))\n {\n ret = 0;\n break;\n }\n pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif) + \\\n\t\t ((tmsize_t) fromskew * img->samplesperpixel);\n\t if (tocol + this_tw > w) \n\t {\n\t\t/*\n\t\t * Rightmost tile is clipped on right side.\n\t\t */\n\t\tfromskew = tw - (w - tocol);\n\t\tthis_tw = tw - fromskew;\n\t\tthis_toskew = toskew + fromskew;\n\t }\n\t (*put)(img, raster+y*w+tocol, tocol, y, this_tw, nrow, fromskew, this_toskew, buf + pos);\n\t tocol += this_tw;\n\t col += this_tw;\n\t /*\n\t * After the leftmost tile, tiles are no longer clipped on left side.\n\t */\n\t fromskew = 0;\n\t this_tw = tw;\n\t this_toskew = toskew;\n\t}\n\n y += ((flip & FLIP_VERTICALLY) ? -(int32) nrow : (int32) nrow);\n }\n _TIFFfree(buf);\n\n if (flip & FLIP_HORIZONTALLY) {\n\t uint32 line;\n\n\t for (line = 0; line < h; line++) {\n\t\t uint32 *left = raster + (line * w);\n\t\t uint32 *right = left + w - 1;\n\t\t \n\t\t while ( left < right ) {\n\t\t\t uint32 temp = *left;\n\t\t\t *left = *right;\n\t\t\t *right = temp;\n\t\t\t left++;\n\t\t\t\tright--;\n\t\t }\n\t }\n }\n\n return (ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'gtTileContig(): check Tile width for overflow\n\nfixes #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: sds _sdsnewlen(const void *init, size_t initlen, int trymalloc) {\n void *sh;\n sds s;\n char type = sdsReqType(initlen);\n /* Empty strings are usually created in order to append. Use type 8\n * since type 5 is not good at this. */\n if (type == SDS_TYPE_5 && initlen == 0) type = SDS_TYPE_8;\n int hdrlen = sdsHdrSize(type);\n unsigned char *fp; /* flags pointer. */\n size_t usable;\n\n sh = trymalloc?\n s_trymalloc_usable(hdrlen+initlen+1, &usable) :\n s_malloc_usable(hdrlen+initlen+1, &usable);\n if (sh == NULL) return NULL;\n if (init==SDS_NOINIT)\n init = NULL;\n else if (!init)\n memset(sh, 0, hdrlen+initlen+1);\n s = (char*)sh+hdrlen;\n fp = ((unsigned char*)s)-1;\n usable = usable-hdrlen-1;\n if (usable > sdsTypeMaxSize(type))\n usable = sdsTypeMaxSize(type);\n switch(type) {\n case SDS_TYPE_5: {\n *fp = type | (initlen << SDS_TYPE_BITS);\n break;\n }\n case SDS_TYPE_8: {\n SDS_HDR_VAR(8,s);\n sh->len = initlen;\n sh->alloc = usable;\n *fp = type;\n break;\n }\n case SDS_TYPE_16: {\n SDS_HDR_VAR(16,s);\n sh->len = initlen;\n sh->alloc = usable;\n *fp = type;\n break;\n }\n case SDS_TYPE_32: {\n SDS_HDR_VAR(32,s);\n sh->len = initlen;\n sh->alloc = usable;\n *fp = type;\n break;\n }\n case SDS_TYPE_64: {\n SDS_HDR_VAR(64,s);\n sh->len = initlen;\n sh->alloc = usable;\n *fp = type;\n break;\n }\n }\n if (initlen && init)\n memcpy(s, init, initlen);\n s[initlen] = '\\0';\n return s;\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 void sungem_send_packet(SunGEMState *s, const uint8_t *buf,\n int size)\n{\n NetClientState *nc = qemu_get_queue(s->nic);\n\n if (s->macregs[MAC_XIFCFG >> 2] & MAC_XIFCFG_LBCK) {\n nc->info->receive(nc, buf, size);\n } else {\n qemu_send_packet(nc, buf, size);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'sungem: switch to use qemu_receive_packet() for loopback\n\nThis patch switches to use qemu_receive_packet() which can detect\nreentrancy and return early.\n\nThis is intended to address CVE-2021-3416.\n\nCc: Prasad J Pandit \nCc: qemu-stable@nongnu.org\nReviewed-by: Mark Cave-Ayland \nReviewed-by: Philippe Mathieu-Daud\u00e9 \nReviewed-by: Alistair Francis \nSigned-off-by: Jason Wang '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int lo_do_open(struct lo_data *lo, struct lo_inode *inode,\n int existing_fd, struct fuse_file_info *fi)\n{\n ssize_t fh;\n int fd = existing_fd;\n int err;\n bool cap_fsetid_dropped = false;\n bool kill_suidgid = lo->killpriv_v2 && fi->kill_priv;\n\n update_open_flags(lo->writeback, lo->allow_direct_io, fi);\n\n if (fd < 0) {\n if (kill_suidgid) {\n err = drop_effective_cap(\"FSETID\", &cap_fsetid_dropped);\n if (err) {\n return err;\n }\n }\n\n fd = lo_inode_open(lo, inode, fi->flags);\n\n if (cap_fsetid_dropped) {\n if (gain_effective_cap(\"FSETID\")) {\n fuse_log(FUSE_LOG_ERR, \"Failed to gain CAP_FSETID\\n\");\n }\n }\n if (fd < 0) {\n return -fd;\n }\n }\n\n pthread_mutex_lock(&lo->mutex);\n fh = lo_add_fd_mapping(lo, fd);\n pthread_mutex_unlock(&lo->mutex);\n if (fh == -1) {\n close(fd);\n return ENOMEM;\n }\n\n fi->fh = fh;\n if (lo->cache == CACHE_NONE) {\n fi->direct_io = 1;\n } else if (lo->cache == CACHE_ALWAYS) {\n fi->keep_cache = 1;\n }\n return 0;\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: Status explain(OperationContext* opCtx,\n const OpMsgRequest& request,\n ExplainOptions::Verbosity verbosity,\n BSONObjBuilder* out) const override {\n std::string dbname = request.getDatabase().toString();\n const BSONObj& cmdObj = request.body;\n // Acquire locks and resolve possible UUID. The RAII object is optional, because in the case\n // of a view, the locks need to be released.\n boost::optional ctx;\n ctx.emplace(opCtx,\n CommandHelpers::parseNsOrUUID(dbname, cmdObj),\n AutoGetCollection::ViewMode::kViewsPermitted);\n const auto nss = ctx->getNss();\n\n // Parse the command BSON to a QueryRequest.\n const bool isExplain = true;\n auto qrStatus = QueryRequest::makeFromFindCommand(nss, cmdObj, isExplain);\n if (!qrStatus.isOK()) {\n return qrStatus.getStatus();\n }\n\n // Finish the parsing step by using the QueryRequest to create a CanonicalQuery.\n const ExtensionsCallbackReal extensionsCallback(opCtx, &nss);\n const boost::intrusive_ptr expCtx;\n auto statusWithCQ =\n CanonicalQuery::canonicalize(opCtx,\n std::move(qrStatus.getValue()),\n expCtx,\n extensionsCallback,\n MatchExpressionParser::kAllowAllSpecialFeatures);\n if (!statusWithCQ.isOK()) {\n return statusWithCQ.getStatus();\n }\n std::unique_ptr cq = std::move(statusWithCQ.getValue());\n\n if (ctx->getView()) {\n // Relinquish locks. The aggregation command will re-acquire them.\n ctx.reset();\n\n // Convert the find command into an aggregation using $match (and other stages, as\n // necessary), if possible.\n const auto& qr = cq->getQueryRequest();\n auto viewAggregationCommand = qr.asAggregationCommand();\n if (!viewAggregationCommand.isOK())\n return viewAggregationCommand.getStatus();\n\n // Create the agg request equivalent of the find operation, with the explain verbosity\n // included.\n auto aggRequest = AggregationRequest::parseFromBSON(\n nss, viewAggregationCommand.getValue(), verbosity);\n if (!aggRequest.isOK()) {\n return aggRequest.getStatus();\n }\n\n try {\n return runAggregate(\n opCtx, nss, aggRequest.getValue(), viewAggregationCommand.getValue(), *out);\n } catch (DBException& error) {\n if (error.code() == ErrorCodes::InvalidPipelineOperator) {\n return {ErrorCodes::InvalidPipelineOperator,\n str::stream() << \"Unsupported in view pipeline: \" << error.what()};\n }\n return error.toStatus();\n }\n }\n\n // The collection may be NULL. If so, getExecutor() should handle it by returning an\n // execution tree with an EOFStage.\n Collection* const collection = ctx->getCollection();\n\n // We have a parsed query. Time to get the execution plan for it.\n auto statusWithPlanExecutor = getExecutorFind(opCtx, collection, nss, std::move(cq));\n if (!statusWithPlanExecutor.isOK()) {\n return statusWithPlanExecutor.getStatus();\n }\n auto exec = std::move(statusWithPlanExecutor.getValue());\n\n // Got the execution tree. Explain it.\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 void dlg_update_routeset(pjsip_dialog *dlg, const pjsip_rx_data *rdata)\n{\n const pjsip_hdr *hdr, *end_hdr;\n //pj_int32_t msg_cseq;\n const pjsip_msg *msg;\n const pjsip_method update = { PJSIP_OTHER_METHOD, {\"UPDATE\", 6}};\n\n msg = rdata->msg_info.msg;\n //msg_cseq = rdata->msg_info.cseq->cseq;\n\n /* Ignore if route set has been frozen */\n if (dlg->route_set_frozen)\n\treturn;\n\n /* Ignore if the message is an UPDATE response (see ticket #1781) */\n if (pjsip_method_cmp(&rdata->msg_info.cseq->method, &update) == 0)\n\treturn;\n\n /* Only update route set if this message belongs to the same\n * transaction as the initial transaction that establishes dialog.\n */\n if (dlg->role == PJSIP_ROLE_UAC) {\n\n\t/* Ignore subsequent request from remote */\n\tif (msg->type != PJSIP_RESPONSE_MSG)\n\t return;\n\n\t/* Ignore subsequent responses with higher CSeq than initial CSeq.\n\t * Unfortunately this would be broken when the first request is\n\t * challenged!\n\t */\n\t//if (msg_cseq != dlg->local.first_cseq)\n\t// return;\n\n } else {\n\n\t/* For callee dialog, route set should have been set by initial\n\t * request and it will have been rejected by dlg->route_set_frozen\n\t * check above.\n\t */\n\tpj_assert(!\"Should not happen\");\n\n }\n\n /* Based on the checks above, we should only get response message here */\n pj_assert(msg->type == PJSIP_RESPONSE_MSG);\n\n /* Ignore if this is not 1xx or 2xx response */\n if (msg->line.status.code >= 300)\n\treturn;\n\n /* Reset route set */\n pj_list_init(&dlg->route_set);\n\n /* Update route set */\n end_hdr = &msg->hdr;\n for (hdr=msg->hdr.prev; hdr!=end_hdr; hdr=hdr->prev) {\n\tif (hdr->type == PJSIP_H_RECORD_ROUTE) {\n\t pjsip_route_hdr *r;\n\t r = (pjsip_route_hdr*) pjsip_hdr_clone(dlg->pool, hdr);\n\t pjsip_routing_hdr_set_route(r);\n\t pj_list_push_back(&dlg->route_set, r);\n\t}\n }\n\n PJ_LOG(5,(dlg->obj_name, \"Route-set updated\"));\n\n /* Freeze the route set only when the route set comes in 2xx response.\n * If it is in 1xx response, prepare to recompute the route set when\n * the 2xx response comes in.\n *\n * There is a debate whether route set should be frozen when the dialog\n * is established with reliable provisional response, but I think\n * it is safer to not freeze the route set (thus recompute the route set\n * upon receiving 2xx response). Also RFC 3261 says so in 13.2.2.4.\n *\n * The pjsip_method_creates_dialog() check protects from wrongly\n * freezing the route set upon receiving 200/OK response for PRACK.\n */\n if (pjsip_method_creates_dialog(&rdata->msg_info.cseq->method) &&\n\tPJSIP_IS_STATUS_IN_CLASS(msg->line.status.code, 200))\n {\n\tdlg->route_set_frozen = PJ_TRUE;\n\tPJ_LOG(5,(dlg->obj_name, \"Route-set frozen\"));\n }\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: FastHufDecoder::FastHufDecoder\n (const char *&table,\n int numBytes,\n int minSymbol,\n int maxSymbol,\n int rleSymbol)\n:\n _rleSymbol (rleSymbol),\n _numSymbols (0),\n _minCodeLength (255),\n _maxCodeLength (0),\n _idToSymbol (0)\n{\n //\n // List of symbols that we find with non-zero code lengths\n // (listed in the order we find them). Store these in the\n // same format as the code book stores codes + lengths - \n // low 6 bits are the length, everything above that is\n // the symbol.\n //\n\n std::vector symbols;\n\n //\n // The 'base' table is the minimum code at each code length. base[i]\n // is the smallest code (numerically) of length i.\n //\n\n Int64 base[MAX_CODE_LEN + 1]; \n\n //\n // The 'offset' table is the position (in sorted order) of the first id\n // of a given code lenght. Array is indexed by code length, like base. \n //\n\n Int64 offset[MAX_CODE_LEN + 1]; \n\n //\n // Count of how many codes at each length there are. Array is \n // indexed by code length, like base and offset.\n //\n\n size_t codeCount[MAX_CODE_LEN + 1]; \n\n for (int i = 0; i <= MAX_CODE_LEN; ++i)\n {\n codeCount[i] = 0;\n base[i] = 0xffffffffffffffffULL;\n offset[i] = 0;\n }\n\n //\n // Count the number of codes, the min/max code lengths, the number of\n // codes with each length, and record symbols with non-zero code\n // length as we find them.\n //\n\n const char *currByte = table;\n Int64 currBits = 0;\n int currBitCount = 0;\n\n const int SHORT_ZEROCODE_RUN = 59;\n const int LONG_ZEROCODE_RUN = 63;\n const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN;\n\n for (Int64 symbol = static_cast(minSymbol); symbol <= static_cast(maxSymbol); symbol++)\n {\n if (currByte - table > numBytes)\n {\n throw IEX_NAMESPACE::InputExc (\"Error decoding Huffman table \"\n \"(Truncated table data).\");\n }\n\n //\n // Next code length - either:\n // 0-58 (literal code length)\n // 59-62 (various lengths runs of 0)\n // 63 (run of n 0's, with n is the next 8 bits)\n //\n\n Int64 codeLen = readBits (6, currBits, currBitCount, currByte);\n\n if (codeLen == (Int64) LONG_ZEROCODE_RUN)\n {\n if (currByte - table > numBytes)\n {\n throw IEX_NAMESPACE::InputExc (\"Error decoding Huffman table \"\n \"(Truncated table data).\");\n }\n\n int runLen = readBits (8, currBits, currBitCount, currByte) +\n SHORTEST_LONG_RUN;\n\n if (symbol + runLen > static_cast(maxSymbol + 1))\n {\n throw IEX_NAMESPACE::InputExc (\"Error decoding Huffman table \"\n \"(Run beyond end of table).\");\n }\n \n symbol += runLen - 1;\n\n }\n else if (codeLen >= static_cast(SHORT_ZEROCODE_RUN))\n {\n int runLen = codeLen - SHORT_ZEROCODE_RUN + 2;\n\n if (symbol + runLen > static_cast(maxSymbol + 1))\n {\n throw IEX_NAMESPACE::InputExc (\"Error decoding Huffman table \"\n \"(Run beyond end of table).\");\n }\n\n symbol += runLen - 1;\n\n }\n else if (codeLen != 0)\n {\n symbols.push_back ((symbol << 6) | (codeLen & 63));\n\n if (codeLen < _minCodeLength)\n _minCodeLength = codeLen;\n\n if (codeLen > _maxCodeLength)\n _maxCodeLength = codeLen;\n\n codeCount[codeLen]++;\n }\n }\n\n for (int i = 0; i < MAX_CODE_LEN; ++i)\n _numSymbols += codeCount[i];\n\n table = currByte;\n\n //\n // Compute base - once we have the code length counts, there\n // is a closed form solution for this\n //\n\n {\n double* countTmp = new double[_maxCodeLength+1];\n\n for (int l = _minCodeLength; l <= _maxCodeLength; ++l)\n {\n countTmp[l] = (double)codeCount[l] * \n (double)(2 << (_maxCodeLength-l));\n }\n \n for (int l = _minCodeLength; l <= _maxCodeLength; ++l)\n {\n double tmp = 0;\n\n for (int k =l + 1; k <= _maxCodeLength; ++k)\n tmp += countTmp[k];\n \n tmp /= (double)(2 << (_maxCodeLength - l));\n\n base[l] = (Int64)ceil (tmp);\n }\n\n delete [] countTmp;\n }\n \n //\n // Compute offset - these are the positions of the first\n // id (not symbol) that has length [i]\n //\n\n offset[_maxCodeLength] = 0;\n\n for (int i= _maxCodeLength - 1; i >= _minCodeLength; i--)\n offset[i] = offset[i + 1] + codeCount[i + 1];\n\n //\n // Allocate and fill the symbol-to-id mapping. Smaller Ids should be\n // mapped to less-frequent symbols (which have longer codes). Use\n // the offset table to tell us where the id's for a given code \n // length start off.\n //\n\n _idToSymbol = new int[_numSymbols];\n\n Int64 mapping[MAX_CODE_LEN + 1];\n for (int i = 0; i < MAX_CODE_LEN + 1; ++i) \n mapping[i] = -1;\n for (int i = _minCodeLength; i <= _maxCodeLength; ++i)\n mapping[i] = offset[i];\n\n for (std::vector::const_iterator i = symbols.begin(); \n i != symbols.end();\n ++i)\n {\n int codeLen = *i & 63;\n int symbol = *i >> 6;\n\n if (mapping[codeLen] >= static_cast(_numSymbols))\n {\n delete[] _idToSymbol;\n _idToSymbol = NULL;\n throw IEX_NAMESPACE::InputExc (\"Huffman decode error \"\n \"(Invalid symbol in header).\");\n }\n _idToSymbol[mapping[codeLen]] = symbol;\n mapping[codeLen]++;\n }\n\n //\n // exceptions can be thrown whilst building tables. Delete\n // _idToSynmbol before re-throwing to prevent memory leak\n //\n try\n {\n buildTables(base, offset);\n }catch(...)\n {\n delete[] _idToSymbol;\n _idToSymbol = NULL;\n throw;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'compute Huf codelengths using 64 bit to prevent shift overflow\n\nSigned-off-by: Peter Hillman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: hufUncompress (const char compressed[],\n\t int nCompressed,\n\t unsigned short raw[],\n\t int nRaw)\n{\n //\n // need at least 20 bytes for header\n //\n if (nCompressed < 20 )\n {\n\tif (nRaw != 0)\n\t notEnoughData();\n\n\treturn;\n }\n\n int im = readUInt (compressed);\n int iM = readUInt (compressed + 4);\n // int tableLength = readUInt (compressed + 8);\n int nBits = readUInt (compressed + 12);\n\n if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE)\n\tinvalidTableSize();\n\n const char *ptr = compressed + 20;\n\n if ( ptr + (nBits+7 )/8 > compressed+nCompressed)\n {\n notEnoughData();\n return;\n }\n\n // \n // Fast decoder needs at least 2x64-bits of compressed data, and\n // needs to be run-able on this platform. Otherwise, fall back\n // to the original decoder\n //\n\n if (FastHufDecoder::enabled() && nBits > 128)\n {\n FastHufDecoder fhd (ptr, nCompressed - (ptr - compressed), im, iM, iM);\n fhd.decode ((unsigned char*)ptr, nBits, raw, nRaw);\n }\n else\n {\n AutoArray freq;\n AutoArray hdec;\n\n hufClearDecTable (hdec);\n\n hufUnpackEncTable (&ptr,\n nCompressed - (ptr - compressed),\n im,\n iM,\n freq);\n\n try\n {\n if (nBits > 8 * (nCompressed - (ptr - compressed)))\n invalidNBits();\n\n hufBuildDecTable (freq, im, iM, hdec);\n hufDecode (freq, hdec, ptr, nBits, iM, nRaw, raw);\n }\n catch (...)\n {\n hufFreeDecTable (hdec);\n throw;\n }\n\n hufFreeDecTable (hdec);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'prevent overflow in hufUncompress if nBits is large (#836)\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: pixReadFromTiffStream(TIFF *tif)\n{\nchar *text;\nl_uint8 *linebuf, *data, *rowptr;\nl_uint16 spp, bps, photometry, tiffcomp, orientation, sample_fmt;\nl_uint16 *redmap, *greenmap, *bluemap;\nl_int32 d, wpl, bpl, comptype, i, j, k, ncolors, rval, gval, bval, aval;\nl_int32 xres, yres, tiffbpl, packedbpl, halfsize;\nl_uint32 w, h, tiffword, read_oriented;\nl_uint32 *line, *ppixel, *tiffdata, *pixdata;\nPIX *pix, *pix1;\nPIXCMAP *cmap;\n\n PROCNAME(\"pixReadFromTiffStream\");\n\n if (!tif)\n return (PIX *)ERROR_PTR(\"tif not defined\", procName, NULL);\n\n read_oriented = 0;\n\n /* Only accept uint image data:\n * SAMPLEFORMAT_UINT = 1;\n * SAMPLEFORMAT_INT = 2;\n * SAMPLEFORMAT_IEEEFP = 3;\n * SAMPLEFORMAT_VOID = 4; */\n TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLEFORMAT, &sample_fmt);\n if (sample_fmt != SAMPLEFORMAT_UINT) {\n L_ERROR(\"sample format = %d is not uint\\n\", procName, sample_fmt);\n return NULL;\n }\n\n /* Can't read tiff in tiled format. For what is involved, see, e.g:\n * https://www.cs.rochester.edu/~nelson/courses/vision/\\\n * resources/tiff/libtiff.html#Tiles\n * A tiled tiff can be converted to a normal (strip) tif:\n * tiffcp -s */\n if (TIFFIsTiled(tif)) {\n L_ERROR(\"tiled format is not supported\\n\", procName);\n return NULL;\n }\n\n /* Old style jpeg is not supported. We tried supporting 8 bpp.\n * TIFFReadScanline() fails on this format, so we used RGBA\n * reading, which generates a 4 spp image, and pulled out the\n * red component. However, there were problems with double-frees\n * in cleanup. For RGB, tiffbpl is exactly half the size that\n * you would expect for the raster data in a scanline, which\n * is 3 * w. */\n TIFFGetFieldDefaulted(tif, TIFFTAG_COMPRESSION, &tiffcomp);\n if (tiffcomp == COMPRESSION_OJPEG) {\n L_ERROR(\"old style jpeg format is not supported\\n\", procName);\n return NULL;\n }\n\n /* Use default fields for bps and spp */\n TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &bps);\n TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &spp);\n if (bps != 1 && bps != 2 && bps != 4 && bps != 8 && bps != 16) {\n L_ERROR(\"invalid bps = %d\\n\", procName, bps);\n return NULL;\n }\n if (spp == 2 && bps != 8) {\n L_WARNING(\"for 2 spp, only handle 8 bps\\n\", procName);\n return NULL;\n }\n if (spp == 1)\n d = bps;\n else if (spp == 2) /* gray plus alpha */\n d = 32; /* will convert to RGBA */\n else if (spp == 3 || spp == 4)\n d = 32;\n else\n return (PIX *)ERROR_PTR(\"spp not in set {1,2,3,4}\", procName, NULL);\n\n TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);\n TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);\n if (w > MaxTiffWidth) {\n L_ERROR(\"width = %d pixels; too large\\n\", procName, w);\n return NULL;\n }\n if (h > MaxTiffHeight) {\n L_ERROR(\"height = %d pixels; too large\\n\", procName, h);\n return NULL;\n }\n\n /* The relation between the size of a byte buffer required to hold\n a raster of image pixels (packedbpl) and the size of the tiff\n buffer (tiffbuf) is either 1:1 or approximately 2:1, depending\n on how the data is stored and subsampled. Allow some slop\n when validating the relation between buffer size and the image\n parameters w, spp and bps. */\n tiffbpl = TIFFScanlineSize(tif);\n packedbpl = (bps * spp * w + 7) / 8;\n halfsize = L_ABS(2 * tiffbpl - packedbpl) <= 8;\n#if 0\n if (halfsize)\n L_INFO(\"packedbpl = %d is approx. twice tiffbpl = %d\\n\", procName,\n packedbpl, tiffbpl);\n#endif\n if (tiffbpl != packedbpl && !halfsize) {\n L_ERROR(\"invalid tiffbpl: tiffbpl = %d, packedbpl = %d, \"\n \"bps = %d, spp = %d, w = %d\\n\",\n procName, tiffbpl, packedbpl, bps, spp, w);\n return NULL;\n }\n\n if ((pix = pixCreate(w, h, d)) == NULL)\n return (PIX *)ERROR_PTR(\"pix not made\", procName, NULL);\n pixSetInputFormat(pix, IFF_TIFF);\n data = (l_uint8 *)pixGetData(pix);\n wpl = pixGetWpl(pix);\n bpl = 4 * wpl;\n\n if (spp == 1) {\n linebuf = (l_uint8 *)LEPT_CALLOC(tiffbpl + 1, sizeof(l_uint8));\n for (i = 0; i < h; i++) {\n if (TIFFReadScanline(tif, linebuf, i, 0) < 0) {\n LEPT_FREE(linebuf);\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"line read fail\", procName, NULL);\n }\n memcpy(data, linebuf, tiffbpl);\n data += bpl;\n }\n if (bps <= 8)\n pixEndianByteSwap(pix);\n else /* bps == 16 */\n pixEndianTwoByteSwap(pix);\n LEPT_FREE(linebuf);\n } else if (spp == 2 && bps == 8) { /* gray plus alpha */\n L_INFO(\"gray+alpha is not supported; converting to RGBA\\n\", procName);\n pixSetSpp(pix, 4);\n linebuf = (l_uint8 *)LEPT_CALLOC(tiffbpl + 1, sizeof(l_uint8));\n pixdata = pixGetData(pix);\n for (i = 0; i < h; i++) {\n if (TIFFReadScanline(tif, linebuf, i, 0) < 0) {\n LEPT_FREE(linebuf);\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"line read fail\", procName, NULL);\n }\n rowptr = linebuf;\n ppixel = pixdata + i * wpl;\n for (j = k = 0; j < w; j++) {\n /* Copy gray value into r, g and b */\n SET_DATA_BYTE(ppixel, COLOR_RED, rowptr[k]);\n SET_DATA_BYTE(ppixel, COLOR_GREEN, rowptr[k]);\n SET_DATA_BYTE(ppixel, COLOR_BLUE, rowptr[k++]);\n SET_DATA_BYTE(ppixel, L_ALPHA_CHANNEL, rowptr[k++]);\n ppixel++;\n }\n }\n LEPT_FREE(linebuf);\n } else { /* rgb and rgba */\n if ((tiffdata = (l_uint32 *)LEPT_CALLOC((size_t)w * h,\n sizeof(l_uint32))) == NULL) {\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"calloc fail for tiffdata\", procName, NULL);\n }\n /* TIFFReadRGBAImageOriented() converts to 8 bps */\n if (!TIFFReadRGBAImageOriented(tif, w, h, tiffdata,\n ORIENTATION_TOPLEFT, 0)) {\n LEPT_FREE(tiffdata);\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"failed to read tiffdata\", procName, NULL);\n } else {\n read_oriented = 1;\n }\n\n if (spp == 4) pixSetSpp(pix, 4);\n line = pixGetData(pix);\n for (i = 0; i < h; i++, line += wpl) {\n for (j = 0, ppixel = line; j < w; j++) {\n /* TIFFGet* are macros */\n tiffword = tiffdata[i * w + j];\n rval = TIFFGetR(tiffword);\n gval = TIFFGetG(tiffword);\n bval = TIFFGetB(tiffword);\n if (spp == 3) {\n composeRGBPixel(rval, gval, bval, ppixel);\n } else { /* spp == 4 */\n aval = TIFFGetA(tiffword);\n composeRGBAPixel(rval, gval, bval, aval, ppixel);\n }\n ppixel++;\n }\n }\n LEPT_FREE(tiffdata);\n }\n\n if (getTiffStreamResolution(tif, &xres, &yres) == 0) {\n pixSetXRes(pix, xres);\n pixSetYRes(pix, yres);\n }\n\n /* Find and save the compression type */\n comptype = getTiffCompressedFormat(tiffcomp);\n pixSetInputFormat(pix, comptype);\n\n if (TIFFGetField(tif, TIFFTAG_COLORMAP, &redmap, &greenmap, &bluemap)) {\n /* Save the colormap as a pix cmap. Because the\n * tiff colormap components are 16 bit unsigned,\n * and go from black (0) to white (0xffff), the\n * the pix cmap takes the most significant byte. */\n if (bps > 8) {\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"colormap size > 256\", procName, NULL);\n }\n if ((cmap = pixcmapCreate(bps)) == NULL) {\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"colormap not made\", procName, NULL);\n }\n ncolors = 1 << bps;\n for (i = 0; i < ncolors; i++)\n pixcmapAddColor(cmap, redmap[i] >> 8, greenmap[i] >> 8,\n bluemap[i] >> 8);\n if (pixSetColormap(pix, cmap)) {\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"invalid colormap\", procName, NULL);\n }\n\n /* Remove the colormap for 1 bpp. */\n if (bps == 1) {\n pix1 = pixRemoveColormap(pix, REMOVE_CMAP_BASED_ON_SRC);\n pixDestroy(&pix);\n pix = pix1;\n }\n } else { /* No colormap: check photometry and invert if necessary */\n if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometry)) {\n /* Guess default photometry setting. Assume min_is_white\n * if compressed 1 bpp; min_is_black otherwise. */\n if (tiffcomp == COMPRESSION_CCITTFAX3 ||\n tiffcomp == COMPRESSION_CCITTFAX4 ||\n tiffcomp == COMPRESSION_CCITTRLE ||\n tiffcomp == COMPRESSION_CCITTRLEW) {\n photometry = PHOTOMETRIC_MINISWHITE;\n } else {\n photometry = PHOTOMETRIC_MINISBLACK;\n }\n }\n if ((d == 1 && photometry == PHOTOMETRIC_MINISBLACK) ||\n (d == 8 && photometry == PHOTOMETRIC_MINISWHITE))\n pixInvert(pix, pix);\n }\n\n if (TIFFGetField(tif, TIFFTAG_ORIENTATION, &orientation)) {\n if (orientation >= 1 && orientation <= 8) {\n struct tiff_transform *transform = (read_oriented) ?\n &tiff_partial_orientation_transforms[orientation - 1] :\n &tiff_orientation_transforms[orientation - 1];\n if (transform->vflip) pixFlipTB(pix, pix);\n if (transform->hflip) pixFlipLR(pix, pix);\n if (transform->rotate) {\n PIX *oldpix = pix;\n pix = pixRotate90(oldpix, transform->rotate);\n pixDestroy(&oldpix);\n }\n }\n }\n\n text = NULL;\n TIFFGetField(tif, TIFFTAG_IMAGEDESCRIPTION, &text);\n if (text) pixSetText(pix, text);\n return pix;\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: autoar_extractor_step_extract (AutoarExtractor *self) {\n /* Step 3: Extract files\n * We have to re-open the archive to extract files\n */\n\n struct archive *a;\n struct archive_entry *entry;\n\n int r;\n\n g_debug (\"autoar_extractor_step_extract: called\");\n\n r = libarchive_create_read_object (self->use_raw_format, self, &a);\n if (r != ARCHIVE_OK) {\n if (self->error == NULL) {\n self->error =\n autoar_common_g_error_new_a (a, self->source_basename);\n }\n archive_read_free (a);\n return;\n }\n\n while ((r = archive_read_next_header (a, &entry)) == ARCHIVE_OK) {\n const char *pathname;\n const char *hardlink;\n g_autoptr (GFile) extracted_filename = NULL;\n g_autoptr (GFile) hardlink_filename = NULL;\n AutoarConflictAction action;\n gboolean file_conflict;\n\n if (g_cancellable_is_cancelled (self->cancellable)) {\n archive_read_free (a);\n return;\n }\n\n pathname = archive_entry_pathname (entry);\n hardlink = archive_entry_hardlink (entry);\n\n extracted_filename =\n autoar_extractor_do_sanitize_pathname (self, pathname);\n\n if (hardlink != NULL) {\n hardlink_filename =\n autoar_extractor_do_sanitize_pathname (self, hardlink);\n }\n\n /* Attempt to solve any name conflict before doing any operations */\n file_conflict = autoar_extractor_check_file_conflict (extracted_filename,\n archive_entry_filetype (entry));\n while (file_conflict) {\n GFile *new_extracted_filename = NULL;\n\n action = autoar_extractor_signal_conflict (self,\n extracted_filename,\n &new_extracted_filename);\n\n switch (action) {\n case AUTOAR_CONFLICT_OVERWRITE:\n /* It is expected that this will fail for non-empty directories to\n * prevent data loss.\n */\n g_file_delete (extracted_filename, self->cancellable, &self->error);\n if (self->error != NULL) {\n archive_read_free (a);\n return;\n }\n break;\n case AUTOAR_CONFLICT_CHANGE_DESTINATION:\n /* FIXME: If the destination is changed for directory, it should be\n * changed also for its children...\n */\n g_assert_nonnull (new_extracted_filename);\n g_clear_object (&extracted_filename);\n extracted_filename = new_extracted_filename;\n break;\n case AUTOAR_CONFLICT_SKIP:\n archive_read_data_skip (a);\n break;\n default:\n g_assert_not_reached ();\n break;\n }\n\n if (action != AUTOAR_CONFLICT_CHANGE_DESTINATION) {\n break;\n }\n\n file_conflict = autoar_extractor_check_file_conflict (extracted_filename,\n archive_entry_filetype (entry));\n }\n\n if (file_conflict && action == AUTOAR_CONFLICT_SKIP) {\n self->total_files -= 1;\n self->total_size -= archive_entry_size (entry);\n continue;\n }\n\n autoar_extractor_do_write_entry (self, a, entry,\n extracted_filename, hardlink_filename);\n\n if (self->error != NULL) {\n archive_read_free (a);\n return;\n }\n\n self->completed_files++;\n autoar_extractor_signal_progress (self);\n }\n\n if (r != ARCHIVE_EOF) {\n if (self->error == NULL) {\n self->error =\n autoar_common_g_error_new_a (a, self->source_basename);\n }\n archive_read_free (a);\n return;\n }\n\n archive_read_free (a);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59'], 'message': 'extractor: Do not allow symlink in parents\n\nCurrently, it is still possible that some files are extracted outside of\nthe destination dir in case of malicious archives. The checks from commit\nadb067e6 can be still bypassed in certain cases. See GNOME/file-roller#108\nfor more details. After some investigation, I am convinced that it would be\nbest to\tsimply disallow symlinks in parents. For example, `tar` fails to\nextract such files with the `ENOTDIR` error. Let's do the same here.\n\nFixes: https://gitlab.gnome.org/GNOME/gnome-autoar/-/issues/12'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: \nstatic int io_register_enable_rings(struct io_ring_ctx *ctx)\n{\n\tif (!(ctx->flags & IORING_SETUP_R_DISABLED))\n\t\treturn -EBADFD;\n\n\tif (ctx->restrictions.registered)\n\t\tctx->restricted = 1;\n\n\tctx->flags &= ~IORING_SETUP_R_DISABLED;\n\n\tio_sq_offload_start(ctx);\n\n\treturn 0; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-667'], 'message': 'io_uring: ensure that SQPOLL thread is started for exit\n\nIf we create it in a disabled state because IORING_SETUP_R_DISABLED is\nset on ring creation, we need to ensure that we've kicked the thread if\nwe're exiting before it's been explicitly disabled. Otherwise we can run\ninto a deadlock where exit is waiting go park the SQPOLL thread, but the\nSQPOLL thread itself is waiting to get a signal to start.\n\nThat results in the below trace of both tasks hung, waiting on each other:\n\nINFO: task syz-executor458:8401 blocked for more than 143 seconds.\n Not tainted 5.11.0-next-20210226-syzkaller #0\n\"echo 0 > /proc/sys/kernel/hung_task_timeout_secs\" disables this message.\ntask:syz-executor458 state:D stack:27536 pid: 8401 ppid: 8400 flags:0x00004004\nCall Trace:\n context_switch kernel/sched/core.c:4324 [inline]\n __schedule+0x90c/0x21a0 kernel/sched/core.c:5075\n schedule+0xcf/0x270 kernel/sched/core.c:5154\n schedule_timeout+0x1db/0x250 kernel/time/timer.c:1868\n do_wait_for_common kernel/sched/completion.c:85 [inline]\n __wait_for_common kernel/sched/completion.c:106 [inline]\n wait_for_common kernel/sched/completion.c:117 [inline]\n wait_for_completion+0x168/0x270 kernel/sched/completion.c:138\n io_sq_thread_park fs/io_uring.c:7115 [inline]\n io_sq_thread_park+0xd5/0x130 fs/io_uring.c:7103\n io_uring_cancel_task_requests+0x24c/0xd90 fs/io_uring.c:8745\n __io_uring_files_cancel+0x110/0x230 fs/io_uring.c:8840\n io_uring_files_cancel include/linux/io_uring.h:47 [inline]\n do_exit+0x299/0x2a60 kernel/exit.c:780\n do_group_exit+0x125/0x310 kernel/exit.c:922\n __do_sys_exit_group kernel/exit.c:933 [inline]\n __se_sys_exit_group kernel/exit.c:931 [inline]\n __x64_sys_exit_group+0x3a/0x50 kernel/exit.c:931\n do_syscall_64+0x2d/0x70 arch/x86/entry/common.c:46\n entry_SYSCALL_64_after_hwframe+0x44/0xae\nRIP: 0033:0x43e899\nRSP: 002b:00007ffe89376d48 EFLAGS: 00000246 ORIG_RAX: 00000000000000e7\nRAX: ffffffffffffffda RBX: 00000000004af2f0 RCX: 000000000043e899\nRDX: 000000000000003c RSI: 00000000000000e7 RDI: 0000000000000000\nRBP: 0000000000000000 R08: ffffffffffffffc0 R09: 0000000010000000\nR10: 0000000000008011 R11: 0000000000000246 R12: 00000000004af2f0\nR13: 0000000000000001 R14: 0000000000000000 R15: 0000000000000001\nINFO: task iou-sqp-8401:8402 can't die for more than 143 seconds.\ntask:iou-sqp-8401 state:D stack:30272 pid: 8402 ppid: 8400 flags:0x00004004\nCall Trace:\n context_switch kernel/sched/core.c:4324 [inline]\n __schedule+0x90c/0x21a0 kernel/sched/core.c:5075\n schedule+0xcf/0x270 kernel/sched/core.c:5154\n schedule_timeout+0x1db/0x250 kernel/time/timer.c:1868\n do_wait_for_common kernel/sched/completion.c:85 [inline]\n __wait_for_common kernel/sched/completion.c:106 [inline]\n wait_for_common kernel/sched/completion.c:117 [inline]\n wait_for_completion+0x168/0x270 kernel/sched/completion.c:138\n io_sq_thread+0x27d/0x1ae0 fs/io_uring.c:6717\n ret_from_fork+0x1f/0x30 arch/x86/entry/entry_64.S:294\nINFO: task iou-sqp-8401:8402 blocked for more than 143 seconds.\n\nReported-by: syzbot+fb5458330b4442f2090d@syzkaller.appspotmail.com\nSigned-off-by: Jens Axboe '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: gtls_connect_step1(struct Curl_easy *data,\n struct connectdata *conn,\n int sockindex)\n{\n struct ssl_connect_data *connssl = &conn->ssl[sockindex];\n struct ssl_backend_data *backend = connssl->backend;\n unsigned int init_flags;\n gnutls_session_t session;\n int rc;\n bool sni = TRUE; /* default is SNI enabled */\n void *transport_ptr = NULL;\n gnutls_push_func gnutls_transport_push = NULL;\n gnutls_pull_func gnutls_transport_pull = NULL;\n#ifdef ENABLE_IPV6\n struct in6_addr addr;\n#else\n struct in_addr addr;\n#endif\n const char *prioritylist;\n const char *err = NULL;\n const char * const hostname = SSL_HOST_NAME();\n long * const certverifyresult = &SSL_SET_OPTION_LVALUE(certverifyresult);\n\n if(connssl->state == ssl_connection_complete)\n /* to make us tolerant against being called more than once for the\n same connection */\n return CURLE_OK;\n\n if(!gtls_inited)\n gtls_init();\n\n /* Initialize certverifyresult to OK */\n *certverifyresult = 0;\n\n if(SSL_CONN_CONFIG(version) == CURL_SSLVERSION_SSLv2) {\n failf(data, \"GnuTLS does not support SSLv2\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n else if(SSL_CONN_CONFIG(version) == CURL_SSLVERSION_SSLv3)\n sni = FALSE; /* SSLv3 has no SNI */\n\n /* allocate a cred struct */\n rc = gnutls_certificate_allocate_credentials(&backend->cred);\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"gnutls_cert_all_cred() failed: %s\", gnutls_strerror(rc));\n return CURLE_SSL_CONNECT_ERROR;\n }\n\n#ifdef HAVE_GNUTLS_SRP\n if(SSL_SET_OPTION(authtype) == CURL_TLSAUTH_SRP) {\n infof(data, \"Using TLS-SRP username: %s\\n\", SSL_SET_OPTION(username));\n\n rc = gnutls_srp_allocate_client_credentials(\n &backend->srp_client_cred);\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"gnutls_srp_allocate_client_cred() failed: %s\",\n gnutls_strerror(rc));\n return CURLE_OUT_OF_MEMORY;\n }\n\n rc = gnutls_srp_set_client_credentials(backend->srp_client_cred,\n SSL_SET_OPTION(username),\n SSL_SET_OPTION(password));\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"gnutls_srp_set_client_cred() failed: %s\",\n gnutls_strerror(rc));\n return CURLE_BAD_FUNCTION_ARGUMENT;\n }\n }\n#endif\n\n if(SSL_CONN_CONFIG(CAfile)) {\n /* set the trusted CA cert bundle file */\n gnutls_certificate_set_verify_flags(backend->cred,\n GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);\n\n rc = gnutls_certificate_set_x509_trust_file(backend->cred,\n SSL_CONN_CONFIG(CAfile),\n GNUTLS_X509_FMT_PEM);\n if(rc < 0) {\n infof(data, \"error reading ca cert file %s (%s)\\n\",\n SSL_CONN_CONFIG(CAfile), gnutls_strerror(rc));\n if(SSL_CONN_CONFIG(verifypeer)) {\n *certverifyresult = rc;\n return CURLE_SSL_CACERT_BADFILE;\n }\n }\n else\n infof(data, \"found %d certificates in %s\\n\", rc,\n SSL_CONN_CONFIG(CAfile));\n }\n\n if(SSL_CONN_CONFIG(CApath)) {\n /* set the trusted CA cert directory */\n rc = gnutls_certificate_set_x509_trust_dir(backend->cred,\n SSL_CONN_CONFIG(CApath),\n GNUTLS_X509_FMT_PEM);\n if(rc < 0) {\n infof(data, \"error reading ca cert file %s (%s)\\n\",\n SSL_CONN_CONFIG(CApath), gnutls_strerror(rc));\n if(SSL_CONN_CONFIG(verifypeer)) {\n *certverifyresult = rc;\n return CURLE_SSL_CACERT_BADFILE;\n }\n }\n else\n infof(data, \"found %d certificates in %s\\n\",\n rc, SSL_CONN_CONFIG(CApath));\n }\n\n#ifdef CURL_CA_FALLBACK\n /* use system ca certificate store as fallback */\n if(SSL_CONN_CONFIG(verifypeer) &&\n !(SSL_CONN_CONFIG(CAfile) || SSL_CONN_CONFIG(CApath))) {\n gnutls_certificate_set_x509_system_trust(backend->cred);\n }\n#endif\n\n if(SSL_SET_OPTION(CRLfile)) {\n /* set the CRL list file */\n rc = gnutls_certificate_set_x509_crl_file(backend->cred,\n SSL_SET_OPTION(CRLfile),\n GNUTLS_X509_FMT_PEM);\n if(rc < 0) {\n failf(data, \"error reading crl file %s (%s)\",\n SSL_SET_OPTION(CRLfile), gnutls_strerror(rc));\n return CURLE_SSL_CRL_BADFILE;\n }\n else\n infof(data, \"found %d CRL in %s\\n\",\n rc, SSL_SET_OPTION(CRLfile));\n }\n\n /* Initialize TLS session as a client */\n init_flags = GNUTLS_CLIENT;\n\n#if defined(GNUTLS_FORCE_CLIENT_CERT)\n init_flags |= GNUTLS_FORCE_CLIENT_CERT;\n#endif\n\n#if defined(GNUTLS_NO_TICKETS)\n /* Disable TLS session tickets */\n init_flags |= GNUTLS_NO_TICKETS;\n#endif\n\n rc = gnutls_init(&backend->session, init_flags);\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"gnutls_init() failed: %d\", rc);\n return CURLE_SSL_CONNECT_ERROR;\n }\n\n /* convenient assign */\n session = backend->session;\n\n if((0 == Curl_inet_pton(AF_INET, hostname, &addr)) &&\n#ifdef ENABLE_IPV6\n (0 == Curl_inet_pton(AF_INET6, hostname, &addr)) &&\n#endif\n sni &&\n (gnutls_server_name_set(session, GNUTLS_NAME_DNS, hostname,\n strlen(hostname)) < 0))\n infof(data, \"WARNING: failed to configure server name indication (SNI) \"\n \"TLS extension\\n\");\n\n /* Use default priorities */\n rc = gnutls_set_default_priority(session);\n if(rc != GNUTLS_E_SUCCESS)\n return CURLE_SSL_CONNECT_ERROR;\n\n /* Ensure +SRP comes at the *end* of all relevant strings so that it can be\n * removed if a run-time error indicates that SRP is not supported by this\n * GnuTLS version */\n switch(SSL_CONN_CONFIG(version)) {\n case CURL_SSLVERSION_SSLv3:\n prioritylist = GNUTLS_CIPHERS \":-VERS-TLS-ALL:+VERS-SSL3.0\";\n break;\n case CURL_SSLVERSION_DEFAULT:\n case CURL_SSLVERSION_TLSv1:\n prioritylist = GNUTLS_CIPHERS \":-VERS-SSL3.0\"\n#ifdef HAS_TLS13\n \":+VERS-TLS1.3\"\n#endif\n ;\n break;\n case CURL_SSLVERSION_TLSv1_0:\n case CURL_SSLVERSION_TLSv1_1:\n case CURL_SSLVERSION_TLSv1_2:\n case CURL_SSLVERSION_TLSv1_3:\n {\n CURLcode result = set_ssl_version_min_max(&prioritylist, data);\n if(result != CURLE_OK)\n return result;\n break;\n }\n case CURL_SSLVERSION_SSLv2:\n failf(data, \"GnuTLS does not support SSLv2\");\n return CURLE_SSL_CONNECT_ERROR;\n default:\n failf(data, \"Unrecognized parameter passed via CURLOPT_SSLVERSION\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n\n#ifdef HAVE_GNUTLS_SRP\n /* Only add SRP to the cipher list if SRP is requested. Otherwise\n * GnuTLS will disable TLS 1.3 support. */\n if(SSL_SET_OPTION(authtype) == CURL_TLSAUTH_SRP) {\n size_t len = strlen(prioritylist);\n\n char *prioritysrp = malloc(len + sizeof(GNUTLS_SRP) + 1);\n if(!prioritysrp)\n return CURLE_OUT_OF_MEMORY;\n strcpy(prioritysrp, prioritylist);\n strcpy(prioritysrp + len, \":\" GNUTLS_SRP);\n\n rc = gnutls_priority_set_direct(session, prioritysrp, &err);\n free(prioritysrp);\n\n if((rc == GNUTLS_E_INVALID_REQUEST) && err) {\n infof(data, \"This GnuTLS does not support SRP\\n\");\n }\n }\n else {\n#endif\n rc = gnutls_priority_set_direct(session, prioritylist, &err);\n#ifdef HAVE_GNUTLS_SRP\n }\n#endif\n\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"Error %d setting GnuTLS cipher list starting with %s\",\n rc, err);\n return CURLE_SSL_CONNECT_ERROR;\n }\n\n if(conn->bits.tls_enable_alpn) {\n int cur = 0;\n gnutls_datum_t protocols[2];\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 protocols[cur].data = (unsigned char *)NGHTTP2_PROTO_VERSION_ID;\n protocols[cur].size = NGHTTP2_PROTO_VERSION_ID_LEN;\n cur++;\n infof(data, \"ALPN, offering %s\\n\", NGHTTP2_PROTO_VERSION_ID);\n }\n#endif\n\n protocols[cur].data = (unsigned char *)ALPN_HTTP_1_1;\n protocols[cur].size = ALPN_HTTP_1_1_LENGTH;\n cur++;\n infof(data, \"ALPN, offering %s\\n\", ALPN_HTTP_1_1);\n\n gnutls_alpn_set_protocols(session, protocols, cur, 0);\n }\n\n if(SSL_SET_OPTION(primary.clientcert)) {\n if(SSL_SET_OPTION(key_passwd)) {\n const unsigned int supported_key_encryption_algorithms =\n GNUTLS_PKCS_USE_PKCS12_3DES | GNUTLS_PKCS_USE_PKCS12_ARCFOUR |\n GNUTLS_PKCS_USE_PKCS12_RC2_40 | GNUTLS_PKCS_USE_PBES2_3DES |\n GNUTLS_PKCS_USE_PBES2_AES_128 | GNUTLS_PKCS_USE_PBES2_AES_192 |\n GNUTLS_PKCS_USE_PBES2_AES_256;\n rc = gnutls_certificate_set_x509_key_file2(\n backend->cred,\n SSL_SET_OPTION(primary.clientcert),\n SSL_SET_OPTION(key) ?\n SSL_SET_OPTION(key) : SSL_SET_OPTION(primary.clientcert),\n do_file_type(SSL_SET_OPTION(cert_type)),\n SSL_SET_OPTION(key_passwd),\n supported_key_encryption_algorithms);\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data,\n \"error reading X.509 potentially-encrypted key file: %s\",\n gnutls_strerror(rc));\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n else {\n if(gnutls_certificate_set_x509_key_file(\n backend->cred,\n SSL_SET_OPTION(primary.clientcert),\n SSL_SET_OPTION(key) ?\n SSL_SET_OPTION(key) : SSL_SET_OPTION(primary.clientcert),\n do_file_type(SSL_SET_OPTION(cert_type)) ) !=\n GNUTLS_E_SUCCESS) {\n failf(data, \"error reading X.509 key or certificate file\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n }\n\n#ifdef HAVE_GNUTLS_SRP\n /* put the credentials to the current session */\n if(SSL_SET_OPTION(authtype) == CURL_TLSAUTH_SRP) {\n rc = gnutls_credentials_set(session, GNUTLS_CRD_SRP,\n backend->srp_client_cred);\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"gnutls_credentials_set() failed: %s\", gnutls_strerror(rc));\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n else\n#endif\n {\n rc = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE,\n backend->cred);\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"gnutls_credentials_set() failed: %s\", gnutls_strerror(rc));\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n\n#ifndef CURL_DISABLE_PROXY\n if(conn->proxy_ssl[sockindex].use) {\n transport_ptr = conn->proxy_ssl[sockindex].backend->session;\n gnutls_transport_push = gtls_push_ssl;\n gnutls_transport_pull = gtls_pull_ssl;\n }\n else\n#endif\n {\n /* file descriptor for the socket */\n transport_ptr = &conn->sock[sockindex];\n gnutls_transport_push = gtls_push;\n gnutls_transport_pull = gtls_pull;\n }\n\n /* set the connection handle */\n gnutls_transport_set_ptr(session, transport_ptr);\n\n /* register callback functions to send and receive data. */\n gnutls_transport_set_push_function(session, gnutls_transport_push);\n gnutls_transport_set_pull_function(session, gnutls_transport_pull);\n\n if(SSL_CONN_CONFIG(verifystatus)) {\n rc = gnutls_ocsp_status_request_enable_client(session, NULL, 0, NULL);\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"gnutls_ocsp_status_request_enable_client() failed: %d\", rc);\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n\n /* This might be a reconnect, so we check for a session ID in the cache\n to speed up things */\n if(SSL_SET_OPTION(primary.sessionid)) {\n void *ssl_sessionid;\n size_t ssl_idsize;\n\n Curl_ssl_sessionid_lock(data);\n if(!Curl_ssl_getsessionid(data, conn,\n &ssl_sessionid, &ssl_idsize, sockindex)) {\n /* we got a session id, use it! */\n gnutls_session_set_data(session, ssl_sessionid, ssl_idsize);\n\n /* Informational message */\n infof(data, \"SSL re-using session ID\\n\");\n }\n Curl_ssl_sessionid_unlock(data);\n }\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: mesalink_connect_step3(struct connectdata *conn, int sockindex)\n{\n CURLcode result = CURLE_OK;\n struct ssl_connect_data *connssl = &conn->ssl[sockindex];\n\n DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);\n\n#ifdef MESALINK_HAVE_SESSION\n if(SSL_SET_OPTION(primary.sessionid)) {\n bool incache;\n SSL_SESSION *our_ssl_sessionid;\n void *old_ssl_sessionid = NULL;\n\n our_ssl_sessionid = SSL_get_session(BACKEND->handle);\n\n Curl_ssl_sessionid_lock(data);\n incache =\n !(Curl_ssl_getsessionid(data, conn,\n &old_ssl_sessionid, NULL, sockindex));\n if(incache) {\n if(old_ssl_sessionid != our_ssl_sessionid) {\n infof(data, \"old SSL session ID is stale, removing\\n\");\n Curl_ssl_delsessionid(data, old_ssl_sessionid);\n incache = FALSE;\n }\n }\n\n if(!incache) {\n result = Curl_ssl_addsessionid(\n data, conn, our_ssl_sessionid, 0 /* unknown size */, sockindex);\n if(result) {\n Curl_ssl_sessionid_unlock(data);\n failf(data, \"failed to store ssl session\");\n return result;\n }\n }\n Curl_ssl_sessionid_unlock(data);\n }\n#endif /* MESALINK_HAVE_SESSION */\n\n connssl->connecting_state = ssl_connect_done;\n\n return result;\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: equal_h (const struct ecc_modulo *p,\n\t const mp_limb_t *x1, const mp_limb_t *z1,\n\t const mp_limb_t *x2, const mp_limb_t *z2,\n\t mp_limb_t *scratch)\n{\n#define t0 scratch\n#define t1 (scratch + p->size)\n\n ecc_mod_mul (p, t0, x1, z2, t0);\n if (mpn_cmp (t0, p->m, p->size) >= 0)\n mpn_sub_n (t0, t0, p->m, p->size);\n\n ecc_mod_mul (p, t1, x2, z1, t1);\n if (mpn_cmp (t1, p->m, p->size) >= 0)\n mpn_sub_n (t1, t1, p->m, p->size);\n\n return mpn_cmp (t0, t1, p->size) == 0;\n\n#undef t0\n#undef t1\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Use ecc_mod_mul_canonical for point comparison.\n\n* eddsa-verify.c (equal_h): Use ecc_mod_mul_canonical.\n\n(cherry picked from commit 5b7608fde3a6d2ab82bffb35db1e4e330927c906)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: nm_wildcard_match_check(const char *str, const char *const *patterns, guint num_patterns)\n{\n gboolean has_optional = FALSE;\n gboolean has_any_optional = FALSE;\n guint i;\n\n for (i = 0; i < num_patterns; i++) {\n gboolean is_inverted;\n gboolean is_mandatory;\n gboolean match;\n const char *p;\n\n _pattern_parse(patterns[i], &p, &is_inverted, &is_mandatory);\n\n match = (fnmatch(p, str, 0) == 0);\n if (is_inverted)\n match = !match;\n\n if (is_mandatory) {\n if (!match)\n return FALSE;\n } else {\n has_any_optional = TRUE;\n if (match)\n has_optional = TRUE;\n }\n }\n\n return has_optional || !has_any_optional;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'core: fix crash in nm_wildcard_match_check()\n\nIt's not entirely clear how to treat %NULL.\nClearly \"match.interface-name=eth0\" should not\nmatch with an interface %NULL. But what about\n\"match.interface-name=!eth0\"? It's now implemented\nthat negative matches still succeed against %NULL.\nWhat about \"match.interface-name=*\"? That probably\nshould also match with %NULL. So we treat %NULL really\nlike \"\".\n\nAgainst commit 11cd443448bc ('iwd: Don't call IWD methods when device\nunmanaged'), we got this backtrace:\n\n #0 0x00007f1c164069f1 in __strnlen_avx2 () at ../sysdeps/x86_64/multiarch/strlen-avx2.S:62\n #1 0x00007f1c1637ac9e in __fnmatch (pattern=, string=, string@entry=0x0, flags=flags@entry=0) at fnmatch.c:379\n p = 0x0\n res = \n orig_pattern = \n n = \n wpattern = 0x7fff8d860730 L\"pci-0000:03:00.0\"\n ps = {__count = 0, __value = {__wch = 0, __wchb = \"\\000\\000\\000\"}}\n wpattern_malloc = 0x0\n wstring_malloc = 0x0\n wstring = \n alloca_used = 80\n __PRETTY_FUNCTION__ = \"__fnmatch\"\n #2 0x0000564484a978bf in nm_wildcard_match_check (str=0x0, patterns=, num_patterns=) at src/core/nm-core-utils.c:1959\n is_inverted = 0\n is_mandatory = 0\n match = \n p = 0x564486c43fa0 \"pci-0000:03:00.0\"\n has_optional = 0\n has_any_optional = 0\n i = \n #3 0x0000564484bf4797 in check_connection_compatible (self=, connection=, error=0x0) at src/core/devices/nm-device.c:7499\n patterns = \n device_driver = 0x564486c76bd0 \"veth\"\n num_patterns = 1\n priv = 0x564486cbe0b0\n __func__ = \"check_connection_compatible\"\n device_iface = \n local = 0x564486c99a60\n conn_iface = 0x0\n klass = \n s_match = 0x564486c63df0 [NMSettingMatch]\n #4 0x0000564484c38491 in check_connection_compatible (device=0x564486cbe590 [NMDeviceVeth], connection=0x564486c6b160, error=0x0) at src/core/devices/nm-device-ethernet.c:348\n self = 0x564486cbe590 [NMDeviceVeth]\n s_wired = \n\nFixes: 3ced486f4162 ('libnm/match: extend syntax for match patterns with '|', '&', '!' and '\\\\'')\n\nhttps://bugzilla.redhat.com/show_bug.cgi?id=1942741'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (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_create(union bpf_attr *attr)\n{\n\tint numa_node = bpf_map_attr_numa_node(attr);\n\tstruct bpf_map *map;\n\tint f_flags;\n\tint err;\n\n\terr = CHECK_ATTR(BPF_MAP_CREATE);\n\tif (err)\n\t\treturn -EINVAL;\n\n\tif (attr->btf_vmlinux_value_type_id) {\n\t\tif (attr->map_type != BPF_MAP_TYPE_STRUCT_OPS ||\n\t\t attr->btf_key_type_id || attr->btf_value_type_id)\n\t\t\treturn -EINVAL;\n\t} else if (attr->btf_key_type_id && !attr->btf_value_type_id) {\n\t\treturn -EINVAL;\n\t}\n\n\tf_flags = bpf_get_file_flag(attr->map_flags);\n\tif (f_flags < 0)\n\t\treturn f_flags;\n\n\tif (numa_node != NUMA_NO_NODE &&\n\t ((unsigned int)numa_node >= nr_node_ids ||\n\t !node_online(numa_node)))\n\t\treturn -EINVAL;\n\n\t/* find map type and init map: hashtable vs rbtree vs bloom vs ... */\n\tmap = find_and_alloc_map(attr);\n\tif (IS_ERR(map))\n\t\treturn PTR_ERR(map);\n\n\terr = bpf_obj_name_cpy(map->name, attr->map_name,\n\t\t\t sizeof(attr->map_name));\n\tif (err < 0)\n\t\tgoto free_map;\n\n\tatomic64_set(&map->refcnt, 1);\n\tatomic64_set(&map->usercnt, 1);\n\tmutex_init(&map->freeze_mutex);\n\n\tmap->spin_lock_off = -EINVAL;\n\tif (attr->btf_key_type_id || attr->btf_value_type_id ||\n\t /* Even the map's value is a kernel's struct,\n\t * the bpf_prog.o must have BTF to begin with\n\t * to figure out the corresponding kernel's\n\t * counter part. Thus, attr->btf_fd has\n\t * to be valid also.\n\t */\n\t attr->btf_vmlinux_value_type_id) {\n\t\tstruct btf *btf;\n\n\t\tbtf = btf_get_by_fd(attr->btf_fd);\n\t\tif (IS_ERR(btf)) {\n\t\t\terr = PTR_ERR(btf);\n\t\t\tgoto free_map;\n\t\t}\n\t\tmap->btf = btf;\n\n\t\tif (attr->btf_value_type_id) {\n\t\t\terr = map_check_btf(map, btf, attr->btf_key_type_id,\n\t\t\t\t\t attr->btf_value_type_id);\n\t\t\tif (err)\n\t\t\t\tgoto free_map;\n\t\t}\n\n\t\tmap->btf_key_type_id = attr->btf_key_type_id;\n\t\tmap->btf_value_type_id = attr->btf_value_type_id;\n\t\tmap->btf_vmlinux_value_type_id =\n\t\t\tattr->btf_vmlinux_value_type_id;\n\t}\n\n\terr = security_bpf_map_alloc(map);\n\tif (err)\n\t\tgoto free_map;\n\n\terr = bpf_map_alloc_id(map);\n\tif (err)\n\t\tgoto free_map_sec;\n\n\tbpf_map_save_memcg(map);\n\n\terr = bpf_map_new_fd(map, f_flags);\n\tif (err < 0) {\n\t\t/* failed to allocate fd.\n\t\t * bpf_map_put_with_uref() is needed because the above\n\t\t * bpf_map_alloc_id() has published the map\n\t\t * to the userspace and the userspace may\n\t\t * have refcnt-ed it through BPF_MAP_GET_FD_BY_ID.\n\t\t */\n\t\tbpf_map_put_with_uref(map);\n\t\treturn err;\n\t}\n\n\treturn err;\n\nfree_map_sec:\n\tsecurity_bpf_map_free(map);\nfree_map:\n\tbtf_put(map->btf);\n\tmap->ops->map_free(map);\n\treturn err;\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: MagickExport Image *WaveImage(const Image *image,const double amplitude,\n const double wave_length,ExceptionInfo *exception)\n{\n#define WaveImageTag \"Wave/Image\"\n\n CacheView\n *image_view,\n *wave_view;\n\n float\n *sine_map;\n\n Image\n *wave_image;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n progress;\n\n MagickPixelPacket\n zero;\n\n ssize_t\n i;\n\n ssize_t\n y;\n\n /*\n Initialize wave image attributes.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n wave_image=CloneImage(image,image->columns,(size_t) (image->rows+2.0*\n fabs(amplitude)),MagickTrue,exception);\n if (wave_image == (Image *) NULL)\n return((Image *) NULL);\n if (SetImageStorageClass(wave_image,DirectClass) == MagickFalse)\n {\n InheritException(exception,&wave_image->exception);\n wave_image=DestroyImage(wave_image);\n return((Image *) NULL);\n }\n if (wave_image->background_color.opacity != OpaqueOpacity)\n wave_image->matte=MagickTrue;\n /*\n Allocate sine map.\n */\n sine_map=(float *) AcquireQuantumMemory((size_t) wave_image->columns,\n sizeof(*sine_map));\n if (sine_map == (float *) NULL)\n {\n wave_image=DestroyImage(wave_image);\n ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n for (i=0; i < (ssize_t) wave_image->columns; i++)\n sine_map[i]=(float) fabs(amplitude)+amplitude*sin((double)\n ((2.0*MagickPI*i)/wave_length));\n /*\n Wave image.\n */\n status=MagickTrue;\n progress=0;\n GetMagickPixelPacket(wave_image,&zero);\n image_view=AcquireVirtualCacheView(image,exception);\n wave_view=AcquireAuthenticCacheView(wave_image,exception);\n (void) SetCacheViewVirtualPixelMethod(image_view,\n BackgroundVirtualPixelMethod);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static) shared(progress,status) \\\n magick_number_threads(image,wave_image,wave_image->rows,1)\n#endif\n for (y=0; y < (ssize_t) wave_image->rows; y++)\n {\n MagickPixelPacket\n pixel;\n\n IndexPacket\n *magick_restrict indexes;\n\n PixelPacket\n *magick_restrict q;\n\n ssize_t\n x;\n\n if (status == MagickFalse)\n continue;\n q=QueueCacheViewAuthenticPixels(wave_view,0,y,wave_image->columns,1,\n exception);\n if (q == (PixelPacket *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n indexes=GetCacheViewAuthenticIndexQueue(wave_view);\n pixel=zero;\n for (x=0; x < (ssize_t) wave_image->columns; x++)\n {\n status=InterpolateMagickPixelPacket(image,image_view,\n UndefinedInterpolatePixel,(double) x,(double) (y-sine_map[x]),&pixel,\n exception);\n if (status == MagickFalse)\n break;\n SetPixelPacket(wave_image,&pixel,q,indexes+x);\n q++;\n }\n if (SyncCacheViewAuthenticPixels(wave_view,exception) == MagickFalse)\n status=MagickFalse;\n if (image->progress_monitor != (MagickProgressMonitor) NULL)\n {\n MagickBooleanType\n proceed;\n\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp atomic\n#endif\n progress++;\n proceed=SetImageProgress(image,WaveImageTag,progress,image->rows);\n if (proceed == MagickFalse)\n status=MagickFalse;\n }\n }\n wave_view=DestroyCacheView(wave_view);\n image_view=DestroyCacheView(image_view);\n sine_map=(float *) RelinquishMagickMemory(sine_map);\n if (status == MagickFalse)\n wave_image=DestroyImage(wave_image);\n return(wave_image);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/3296'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: MagickExport MagickBooleanType PasskeyEncipherImage(Image *image,\n const StringInfo *passkey,ExceptionInfo *exception)\n{\n#define EncipherImageTag \"Encipher/Image \"\n\n AESInfo\n *aes_info;\n\n CacheView\n *image_view;\n\n char\n *signature;\n\n const unsigned char\n *digest;\n\n MagickBooleanType\n proceed;\n\n MagickSizeType\n extent;\n\n QuantumInfo\n *quantum_info;\n\n QuantumType\n quantum_type;\n\n unsigned char\n *p;\n\n SignatureInfo\n *signature_info;\n\n size_t\n length;\n\n ssize_t\n y;\n\n StringInfo\n *key,\n *nonce;\n\n unsigned char\n input_block[AESBlocksize],\n output_block[AESBlocksize],\n *pixels;\n\n /*\n Generate encipher key and nonce.\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 if (passkey == (const StringInfo *) NULL)\n return(MagickTrue);\n if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)\n return(MagickFalse);\n aes_info=AcquireAESInfo();\n key=CloneStringInfo(passkey);\n if (key == (StringInfo *) NULL)\n {\n aes_info=DestroyAESInfo(aes_info);\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }\n nonce=SplitStringInfo(key,GetStringInfoLength(key)/2);\n if (nonce == (StringInfo *) NULL)\n {\n key=DestroyStringInfo(key);\n aes_info=DestroyAESInfo(aes_info);\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }\n SetAESKey(aes_info,key);\n key=DestroyStringInfo(key);\n signature_info=AcquireSignatureInfo();\n UpdateSignature(signature_info,nonce);\n extent=(MagickSizeType) image->columns*image->rows;\n SetStringInfoLength(nonce,sizeof(extent));\n SetStringInfoDatum(nonce,(const unsigned char *) &extent);\n UpdateSignature(signature_info,nonce);\n nonce=DestroyStringInfo(nonce);\n FinalizeSignature(signature_info);\n signature=StringInfoToHexString(GetSignatureDigest(signature_info));\n (void) SetImageProperty(image,\"cipher:type\",\"AES\",exception);\n (void) SetImageProperty(image,\"cipher:mode\",\"CTR\",exception);\n (void) SetImageProperty(image,\"cipher:nonce\",signature,exception);\n signature=DestroyString(signature);\n (void) memset(input_block,0,sizeof(input_block));\n digest=GetStringInfoDatum(GetSignatureDigest(signature_info));\n (void) memcpy(input_block,digest,MagickMin(AESBlocksize,\n GetSignatureDigestsize(signature_info))*sizeof(*input_block));\n signature_info=DestroySignatureInfo(signature_info);\n /*\n Convert plain pixels to cipher pixels.\n */\n quantum_info=AcquireQuantumInfo((const ImageInfo *) NULL,image);\n if (quantum_info == (QuantumInfo *) NULL)\n {\n aes_info=DestroyAESInfo(aes_info);\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }\n quantum_type=GetQuantumType(image,exception);\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n image_view=AcquireAuthenticCacheView(image,exception);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n ssize_t\n i,\n x;\n\n Quantum\n *magick_restrict q;\n\n q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n length=ExportQuantumPixels(image,image_view,quantum_info,quantum_type,\n pixels,exception);\n p=pixels;\n for (x=0; x < (ssize_t) length; x+=AESBlocksize)\n {\n (void) memcpy(output_block,input_block,AESBlocksize*\n sizeof(*output_block));\n IncrementCipherNonce(AESBlocksize,input_block);\n EncipherAESBlock(aes_info,output_block,output_block);\n for (i=0; i < AESBlocksize; i++)\n p[i]^=output_block[i];\n p+=AESBlocksize;\n }\n (void) memcpy(output_block,input_block,AESBlocksize*\n sizeof(*output_block));\n EncipherAESBlock(aes_info,output_block,output_block);\n for (i=0; x < (ssize_t) length; x++)\n {\n p[i]^=output_block[i];\n i++;\n }\n (void) ImportQuantumPixels(image,image_view,quantum_info,quantum_type,\n pixels,exception);\n if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)\n break;\n proceed=SetImageProgress(image,EncipherImageTag,(MagickOffsetType) y,\n image->rows);\n if (proceed == MagickFalse)\n break;\n }\n image_view=DestroyCacheView(image_view);\n image->taint=MagickFalse;\n /*\n Free resources.\n */\n quantum_info=DestroyQuantumInfo(quantum_info);\n aes_info=DestroyAESInfo(aes_info);\n (void) memset(input_block,0,sizeof(input_block));\n (void) memset(output_block,0,sizeof(output_block));\n return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse);\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: DeepTiledInputFile::multiPartInitialize(InputPartData* part)\n{\n if (isTiled(part->header.type()) == false)\n THROW (IEX_NAMESPACE::ArgExc, \"Can't build a DeepTiledInputFile from a part of type \" << part->header.type());\n\n _data->_streamData = part->mutex;\n _data->header = part->header;\n _data->version = part->version;\n _data->partNumber = part->partNumber;\n _data->memoryMapped = _data->_streamData->is->isMemoryMapped();\n initialize();\n _data->tileOffsets.readFrom(part->chunkOffsets , _data->fileIsComplete);\n _data->_streamData->currentPosition = _data->_streamData->is->tellg();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Handle xsampling and bad seekg() calls in exrcheck (#872)\n\n* fix exrcheck xsampling!=1\r\n\r\nSigned-off-by: Peter Hillman \r\n\r\n* fix handling bad seekg() calls in exrcheck\r\n\r\nSigned-off-by: Peter Hillman \r\n\r\n* fix deeptile detection in multipart files\r\n\r\nSigned-off-by: Peter Hillman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int PackLinuxElf32::canUnpack()\n{\n if (super::canUnpack()) {\n return true;\n }\n if (Elf32_Ehdr::ET_DYN==get_te16(&ehdri.e_type)) {\n PackLinuxElf32help1(fi);\n }\n return false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-415'], 'message': 'PackLinuxElf::canUnpack must checkEhdr() for ELF input\n\nhttps://github.com/upx/upx/issues/485\n\tmodified: p_lx_elf.cpp'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int fuse_rename2(struct inode *olddir, struct dentry *oldent,\n\t\t\tstruct inode *newdir, struct dentry *newent,\n\t\t\tunsigned int flags)\n{\n\tstruct fuse_conn *fc = get_fuse_conn(olddir);\n\tint err;\n\n\tif (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))\n\t\treturn -EINVAL;\n\n\tif (flags) {\n\t\tif (fc->no_rename2 || fc->minor < 23)\n\t\t\treturn -EINVAL;\n\n\t\terr = fuse_rename_common(olddir, oldent, newdir, newent, flags,\n\t\t\t\t\t FUSE_RENAME2,\n\t\t\t\t\t sizeof(struct fuse_rename2_in));\n\t\tif (err == -ENOSYS) {\n\t\t\tfc->no_rename2 = 1;\n\t\t\terr = -EINVAL;\n\t\t}\n\t} else {\n\t\terr = fuse_rename_common(olddir, oldent, newdir, newent, 0,\n\t\t\t\t\t FUSE_RENAME,\n\t\t\t\t\t sizeof(struct fuse_rename_in));\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 fuse_flush(struct file *file, fl_owner_t id)\n{\n\tstruct inode *inode = file_inode(file);\n\tstruct fuse_mount *fm = get_fuse_mount(inode);\n\tstruct fuse_file *ff = file->private_data;\n\tstruct fuse_flush_in inarg;\n\tFUSE_ARGS(args);\n\tint err;\n\n\tif (is_bad_inode(inode))\n\t\treturn -EIO;\n\n\terr = write_inode_now(inode, 1);\n\tif (err)\n\t\treturn err;\n\n\tinode_lock(inode);\n\tfuse_sync_writes(inode);\n\tinode_unlock(inode);\n\n\terr = filemap_check_errors(file->f_mapping);\n\tif (err)\n\t\treturn err;\n\n\terr = 0;\n\tif (fm->fc->no_flush)\n\t\tgoto inval_attr_out;\n\n\tmemset(&inarg, 0, sizeof(inarg));\n\tinarg.fh = ff->fh;\n\tinarg.lock_owner = fuse_lock_owner_id(fm->fc, id);\n\targs.opcode = FUSE_FLUSH;\n\targs.nodeid = get_node_id(inode);\n\targs.in_numargs = 1;\n\targs.in_args[0].size = sizeof(inarg);\n\targs.in_args[0].value = &inarg;\n\targs.force = true;\n\n\terr = fuse_simple_request(fm, &args);\n\tif (err == -ENOSYS) {\n\t\tfm->fc->no_flush = 1;\n\t\terr = 0;\n\t}\n\ninval_attr_out:\n\t/*\n\t * In memory i_blocks is not maintained by fuse, if writeback cache is\n\t * enabled, i_blocks from cached attr may not be accurate.\n\t */\n\tif (!err && fm->fc->writeback_cache)\n\t\tfuse_invalidate_attr(inode);\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_readpage(struct file *file, struct page *page)\n{\n\tstruct inode *inode = page->mapping->host;\n\tint err;\n\n\terr = -EIO;\n\tif (is_bad_inode(inode))\n\t\tgoto out;\n\n\terr = fuse_do_readpage(file, page);\n\tfuse_invalidate_atime(inode);\n out:\n\tunlock_page(page);\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: RsaAdjustPrimeCandidate(\n\t\t\tbigNum prime,\n\t\t\tSEED_COMPAT_LEVEL seedCompatLevel // IN: compatibility level; libtpms added\n\t\t\t)\n{\n switch (seedCompatLevel) {\n case SEED_COMPAT_LEVEL_ORIGINAL:\n RsaAdjustPrimeCandidate_PreRev155(prime);\n break;\n /* case SEED_COMPAT_LEVEL_LAST: */\n case SEED_COMPAT_LEVEL_RSA_PRIME_ADJUST_FIX:\n RsaAdjustPrimeCandidate_New(prime);\n break;\n default:\n FAIL(FATAL_ERROR_INTERNAL);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-331'], 'message': 'tpm2: Activate SEED_COMPAT_LEVEL_RSA_PRIME_ADJUST_FIX\n\nSigned-off-by: Stefan Berger '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TEST_F(HttpConnectionManagerConfigTest, ServerPassThrough) {\n const std::string yaml_string = R\"EOF(\n stat_prefix: ingress_http\n server_header_transformation: PASS_THROUGH\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 EXPECT_EQ(HttpConnectionManagerConfig::HttpConnectionManagerProto::PASS_THROUGH,\n config.serverHeaderTransformation());\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'Implement handling of escaped slash characters in URL path\n\nFixes: CVE-2021-29492\n\nSigned-off-by: Yan Avlasov '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: sync_create_state_control(Slapi_Entry *e, LDAPControl **ctrlp, int type, Sync_Cookie *cookie)\n{\n int rc;\n BerElement *ber;\n struct berval *bvp;\n char *uuid;\n Slapi_Attr *attr;\n Slapi_Value *val;\n\n if (type == LDAP_SYNC_NONE || ctrlp == NULL || (ber = der_alloc()) == NULL) {\n return (LDAP_OPERATIONS_ERROR);\n }\n\n *ctrlp = NULL;\n\n slapi_entry_attr_find(e, SLAPI_ATTR_UNIQUEID, &attr);\n slapi_attr_first_value(attr, &val);\n uuid = sync_nsuniqueid2uuid(slapi_value_get_string(val));\n if ((rc = ber_printf(ber, \"{eo\", type, uuid, 16)) != -1) {\n if (cookie) {\n char *cookiestr = sync_cookie2str(cookie);\n rc = ber_printf(ber, \"s}\", cookiestr);\n slapi_ch_free((void **)&cookiestr);\n } else {\n rc = ber_printf(ber, \"}\");\n }\n }\n if (rc != -1) {\n rc = ber_flatten(ber, &bvp);\n }\n ber_free(ber, 1);\n slapi_ch_free((void **)&uuid);\n\n if (rc == -1) {\n return (LDAP_OPERATIONS_ERROR);\n }\n\n *ctrlp = (LDAPControl *)slapi_ch_malloc(sizeof(LDAPControl));\n (*ctrlp)->ldctl_iscritical = 0;\n (*ctrlp)->ldctl_oid = slapi_ch_strdup(LDAP_CONTROL_SYNC_STATE);\n (*ctrlp)->ldctl_value = *bvp; /* struct copy */\n\n bvp->bv_val = NULL;\n ber_bvfree(bvp);\n\n return (LDAP_SUCCESS);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Issue 4711 - SIGSEV with sync_repl (#4738)\n\nBug description:\n\tsync_repl sends back entries identified with a unique\n\tidentifier that is 'nsuniqueid'. If 'nsuniqueid' is\n\tmissing, then it may crash\n\nFix description:\n\tCheck a nsuniqueid is available else returns OP_ERR\n\nrelates: https://github.com/389ds/389-ds-base/issues/4711\n\nReviewed by: Pierre Rogier, James Chapman, William Brown (Thanks!)\n\nPlatforms tested: F33'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: sldns_bget_token_par(sldns_buffer *b, char *token, const char *delim,\n\tsize_t limit, int* par, const char* skipw)\n{\n\tint c, lc;\n\tint p; /* 0 -> no parentheses seen, >0 nr of ( seen */\n\tint com, quoted;\n\tchar *t;\n\tsize_t i;\n\tconst char *d;\n\tconst char *del;\n\n\t/* standard delimiters */\n\tif (!delim) {\n\t\t/* from isspace(3) */\n\t\tdel = LDNS_PARSE_NORMAL;\n\t} else {\n\t\tdel = delim;\n\t}\n\n\tp = (par?*par:0);\n\ti = 0;\n\tcom = 0;\n\tquoted = 0;\n\tt = token;\n\tlc = 0;\n\tif (del[0] == '\"') {\n\t\tquoted = 1;\n\t}\n\n\twhile ((c = sldns_bgetc(b)) != EOF) {\n\t\tif (c == '\\r') /* carriage return */\n\t\t\tc = ' ';\n\t\tif (c == '(' && lc != '\\\\' && !quoted) {\n\t\t\t/* this only counts for non-comments */\n\t\t\tif (com == 0) {\n\t\t\t\tif(par) (*par)++;\n\t\t\t\tp++;\n\t\t\t}\n\t\t\tlc = c;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c == ')' && lc != '\\\\' && !quoted) {\n\t\t\t/* this only counts for non-comments */\n\t\t\tif (com == 0) {\n\t\t\t\tif(par) (*par)--;\n\t\t\t\tp--;\n\t\t\t}\n\t\t\tlc = c;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (p < 0) {\n\t\t\t/* more ) then ( */\n\t\t\t*t = '\\0';\n\t\t\treturn 0;\n\t\t}\n\n\t\t/* do something with comments ; */\n\t\tif (c == ';' && quoted == 0) {\n\t\t\tif (lc != '\\\\') {\n\t\t\t\tcom = 1;\n\t\t\t}\n\t\t}\n\t\tif (c == '\"' && com == 0 && lc != '\\\\') {\n\t\t\tquoted = 1 - quoted;\n\t\t}\n\n\t\tif (c == '\\n' && com != 0) {\n\t\t\t/* comments */\n\t\t\tcom = 0;\n\t\t\t*t = ' ';\n\t\t\tlc = c;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (com == 1) {\n\t\t\t*t = ' ';\n\t\t\tlc = c;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c == '\\n' && p != 0) {\n\t\t\t/* in parentheses */\n\t\t\t/* do not write ' ' if we want to skip spaces */\n\t\t\tif(!(skipw && (strchr(skipw, c)||strchr(skipw, ' '))))\n\t\t\t\t*t++ = ' ';\n\t\t\tlc = c;\n\t\t\tcontinue;\n\t\t}\n\n\t\t/* check to skip whitespace at start, but also after ( */\n\t\tif(skipw && i==0 && !com && !quoted && lc != '\\\\') {\n\t\t\tif(strchr(skipw, c)) {\n\t\t\t\tlc = c;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\t/* check if we hit the delim */\n\t\tfor (d = del; *d; d++) {\n\t\t\t/* we can only exit if no parens or user tracks them */\n if (c == *d && lc != '\\\\' && (p == 0 || par)) {\n\t\t\t\tgoto tokenread;\n }\n\t\t}\n\n\t\ti++;\n\t\tif (limit > 0 && (i >= limit || (size_t)(t-token) >= limit)) {\n\t\t\t*t = '\\0';\n\t\t\treturn -1;\n\t\t}\n\t\t*t++ = c;\n\n\t\tif (c == '\\\\' && lc == '\\\\') {\n\t\t\tlc = 0;\n\t\t} else {\n\t\t\tlc = c;\n\t\t}\n\t}\n\t*t = '\\0';\n\tif (i == 0) {\n\t\t/* nothing read */\n\t\treturn -1;\n\t}\n\tif (!par && p != 0) {\n\t\treturn -1;\n\t}\n\treturn (ssize_t)i;\n\ntokenread:\n\tif(*del == '\"')\n\t\t/* do not skip over quotes after the string, they are part\n\t\t * of the next string. But skip over whitespace (if needed)*/\n\t\tsldns_bskipcs(b, del+1);\n\telse \tsldns_bskipcs(b, del);\n\t*t = '\\0';\n\n\tif (!par && p != 0) {\n\t\treturn -1;\n\t}\n\treturn (ssize_t)i;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': '- Fix Out of Bounds Write in sldns_bget_token_par(),\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: void usb_ep_combine_input_packets(USBEndpoint *ep)\n{\n USBPacket *p, *u, *next, *prev = NULL, *first = NULL;\n USBPort *port = ep->dev->port;\n int totalsize;\n\n assert(ep->pipeline);\n assert(ep->pid == USB_TOKEN_IN);\n\n QTAILQ_FOREACH_SAFE(p, &ep->queue, queue, next) {\n /* Empty the queue on a halt */\n if (ep->halted) {\n p->status = USB_RET_REMOVE_FROM_QUEUE;\n port->ops->complete(port, p);\n continue;\n }\n\n /* Skip packets already submitted to the device */\n if (p->state == USB_PACKET_ASYNC) {\n prev = p;\n continue;\n }\n usb_packet_check_state(p, USB_PACKET_QUEUED);\n\n /*\n * If the previous (combined) packet has the short_not_ok flag set\n * stop, as we must not submit packets to the device after a transfer\n * ending with short_not_ok packet.\n */\n if (prev && prev->short_not_ok) {\n break;\n }\n\n if (first) {\n if (first->combined == NULL) {\n USBCombinedPacket *combined = g_new0(USBCombinedPacket, 1);\n\n combined->first = first;\n QTAILQ_INIT(&combined->packets);\n qemu_iovec_init(&combined->iov, 2);\n usb_combined_packet_add(combined, first);\n }\n usb_combined_packet_add(first->combined, p);\n } else {\n first = p;\n }\n\n /* Is this packet the last one of a (combined) transfer? */\n totalsize = (p->combined) ? p->combined->iov.size : p->iov.size;\n if ((p->iov.size % ep->max_packet_size) != 0 || !p->short_not_ok ||\n next == NULL ||\n /* Work around for Linux usbfs bulk splitting + migration */\n (totalsize == (16 * KiB - 36) && p->int_req)) {\n usb_device_handle_data(ep->dev, first);\n assert(first->status == USB_RET_ASYNC);\n if (first->combined) {\n QTAILQ_FOREACH(u, &first->combined->packets, combined_entry) {\n usb_packet_set_state(u, USB_PACKET_ASYNC);\n }\n } else {\n usb_packet_set_state(first, USB_PACKET_ASYNC);\n }\n first = NULL;\n prev = p;\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-770'], 'message': 'usb: limit combined packets to 1 MiB (CVE-2021-3527)\n\nusb-host and usb-redirect try to batch bulk transfers by combining many\nsmall usb packets into a single, large transfer request, to reduce the\noverhead and improve performance.\n\nThis patch adds a size limit of 1 MiB for those combined packets to\nrestrict the host resources the guest can bind that way.\n\nSigned-off-by: Gerd Hoffmann \nMessage-Id: <20210503132915.2335822-6-kraxel@redhat.com>'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TEST(QueryProjectionTest, InvalidElemMatchTextProjection) {\n assertInvalidProjection(\"{}\", \"{a: {$elemMatch: {$text: {$search: 'str'}}}}\");\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: escape_xml(const char *text)\n{\n\tstatic char *escaped;\n\tstatic size_t escaped_size;\n\tchar *out;\n\tsize_t len;\n\n\tfor (out=escaped, len=0; *text; ++len, ++out, ++text) {\n\t\t/* Make sure there's plenty of room for a quoted character */\n\t\tif ((len + 8) > escaped_size) {\n\t\t\tchar *bigger_escaped;\n\t\t\tescaped_size += 128;\n\t\t\tbigger_escaped = realloc(escaped, escaped_size);\n\t\t\tif (!bigger_escaped) {\n\t\t\t\tfree(escaped);\t/* avoid leaking memory */\n\t\t\t\tescaped = NULL;\n\t\t\t\tescaped_size = 0;\n\t\t\t\t/* Error string is cleverly chosen to fail XML validation */\n\t\t\t\treturn \">>> out of memory <<<\";\n\t\t\t}\n\t\t\tout = bigger_escaped + len;\n\t\t\tescaped = bigger_escaped;\n\t\t}\n\t\tswitch (*text) {\n\t\t\tcase '&':\n\t\t\t\tstrcpy(out, \"&\");\n\t\t\t\tlen += strlen(out) - 1;\n\t\t\t\tout = escaped + len;\n\t\t\t\tbreak;\n\t\t\tcase '<':\n\t\t\t\tstrcpy(out, \"<\");\n\t\t\t\tlen += strlen(out) - 1;\n\t\t\t\tout = escaped + len;\n\t\t\t\tbreak;\n\t\t\tcase '>':\n\t\t\t\tstrcpy(out, \">\");\n\t\t\t\tlen += strlen(out) - 1;\n\t\t\t\tout = escaped + len;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t*out = *text;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t*out = '\\x0'; /* NUL terminate the string */\n\treturn escaped;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'added empty strign check, which would lead to NULL ptr deref/crash in exif XML display. fixes https://github.com/libexif/exif/issues/4'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)\n{\n\tstruct io_buffer *buf;\n\tu64 addr = pbuf->addr;\n\tint i, bid = pbuf->bid;\n\n\tfor (i = 0; i < pbuf->nbufs; i++) {\n\t\tbuf = kmalloc(sizeof(*buf), GFP_KERNEL);\n\t\tif (!buf)\n\t\t\tbreak;\n\n\t\tbuf->addr = addr;\n\t\tbuf->len = pbuf->len;\n\t\tbuf->bid = bid;\n\t\taddr += pbuf->len;\n\t\tbid++;\n\t\tif (!*head) {\n\t\t\tINIT_LIST_HEAD(&buf->list);\n\t\t\t*head = buf;\n\t\t} else {\n\t\t\tlist_add_tail(&buf->list, &(*head)->list);\n\t\t}\n\t}\n\n\treturn i ? i : -ENOMEM;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'io_uring: truncate lengths larger than MAX_RW_COUNT on provide buffers\n\nRead and write operations are capped to MAX_RW_COUNT. Some read ops rely on\nthat limit, and that is not guaranteed by the IORING_OP_PROVIDE_BUFFERS.\n\nTruncate those lengths when doing io_add_buffers, so buffer addresses still\nuse the uncapped length.\n\nAlso, take the chance and change struct io_buffer len member to __u32, so\nit matches struct io_provide_buffer len member.\n\nThis fixes CVE-2021-3491, also reported as ZDI-CAN-13546.\n\nFixes: ddf0322db79c (\"io_uring: add IORING_OP_PROVIDE_BUFFERS\")\nReported-by: Billy Jheng Bing-Jhong (@st424204)\nSigned-off-by: Thadeu Lima de Souza Cascardo \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 netlbl_cipsov4_list(struct sk_buff *skb, struct genl_info *info)\n{\n\tint ret_val;\n\tstruct sk_buff *ans_skb = NULL;\n\tu32 nlsze_mult = 1;\n\tvoid *data;\n\tu32 doi;\n\tstruct nlattr *nla_a;\n\tstruct nlattr *nla_b;\n\tstruct cipso_v4_doi *doi_def;\n\tu32 iter;\n\n\tif (!info->attrs[NLBL_CIPSOV4_A_DOI]) {\n\t\tret_val = -EINVAL;\n\t\tgoto list_failure;\n\t}\n\nlist_start:\n\tans_skb = nlmsg_new(NLMSG_DEFAULT_SIZE * nlsze_mult, GFP_KERNEL);\n\tif (ans_skb == NULL) {\n\t\tret_val = -ENOMEM;\n\t\tgoto list_failure;\n\t}\n\tdata = genlmsg_put_reply(ans_skb, info, &netlbl_cipsov4_gnl_family,\n\t\t\t\t 0, NLBL_CIPSOV4_C_LIST);\n\tif (data == NULL) {\n\t\tret_val = -ENOMEM;\n\t\tgoto list_failure;\n\t}\n\n\tdoi = nla_get_u32(info->attrs[NLBL_CIPSOV4_A_DOI]);\n\n\trcu_read_lock();\n\tdoi_def = cipso_v4_doi_getdef(doi);\n\tif (doi_def == NULL) {\n\t\tret_val = -EINVAL;\n\t\tgoto list_failure_lock;\n\t}\n\n\tret_val = nla_put_u32(ans_skb, NLBL_CIPSOV4_A_MTYPE, doi_def->type);\n\tif (ret_val != 0)\n\t\tgoto list_failure_lock;\n\n\tnla_a = nla_nest_start_noflag(ans_skb, NLBL_CIPSOV4_A_TAGLST);\n\tif (nla_a == NULL) {\n\t\tret_val = -ENOMEM;\n\t\tgoto list_failure_lock;\n\t}\n\tfor (iter = 0;\n\t iter < CIPSO_V4_TAG_MAXCNT &&\n\t doi_def->tags[iter] != CIPSO_V4_TAG_INVALID;\n\t iter++) {\n\t\tret_val = nla_put_u8(ans_skb,\n\t\t\t\t NLBL_CIPSOV4_A_TAG,\n\t\t\t\t doi_def->tags[iter]);\n\t\tif (ret_val != 0)\n\t\t\tgoto list_failure_lock;\n\t}\n\tnla_nest_end(ans_skb, nla_a);\n\n\tswitch (doi_def->type) {\n\tcase CIPSO_V4_MAP_TRANS:\n\t\tnla_a = nla_nest_start_noflag(ans_skb,\n\t\t\t\t\t NLBL_CIPSOV4_A_MLSLVLLST);\n\t\tif (nla_a == NULL) {\n\t\t\tret_val = -ENOMEM;\n\t\t\tgoto list_failure_lock;\n\t\t}\n\t\tfor (iter = 0;\n\t\t iter < doi_def->map.std->lvl.local_size;\n\t\t iter++) {\n\t\t\tif (doi_def->map.std->lvl.local[iter] ==\n\t\t\t CIPSO_V4_INV_LVL)\n\t\t\t\tcontinue;\n\n\t\t\tnla_b = nla_nest_start_noflag(ans_skb,\n\t\t\t\t\t\t NLBL_CIPSOV4_A_MLSLVL);\n\t\t\tif (nla_b == NULL) {\n\t\t\t\tret_val = -ENOMEM;\n\t\t\t\tgoto list_retry;\n\t\t\t}\n\t\t\tret_val = nla_put_u32(ans_skb,\n\t\t\t\t\t NLBL_CIPSOV4_A_MLSLVLLOC,\n\t\t\t\t\t iter);\n\t\t\tif (ret_val != 0)\n\t\t\t\tgoto list_retry;\n\t\t\tret_val = nla_put_u32(ans_skb,\n\t\t\t\t\t NLBL_CIPSOV4_A_MLSLVLREM,\n\t\t\t\t\t doi_def->map.std->lvl.local[iter]);\n\t\t\tif (ret_val != 0)\n\t\t\t\tgoto list_retry;\n\t\t\tnla_nest_end(ans_skb, nla_b);\n\t\t}\n\t\tnla_nest_end(ans_skb, nla_a);\n\n\t\tnla_a = nla_nest_start_noflag(ans_skb,\n\t\t\t\t\t NLBL_CIPSOV4_A_MLSCATLST);\n\t\tif (nla_a == NULL) {\n\t\t\tret_val = -ENOMEM;\n\t\t\tgoto list_retry;\n\t\t}\n\t\tfor (iter = 0;\n\t\t iter < doi_def->map.std->cat.local_size;\n\t\t iter++) {\n\t\t\tif (doi_def->map.std->cat.local[iter] ==\n\t\t\t CIPSO_V4_INV_CAT)\n\t\t\t\tcontinue;\n\n\t\t\tnla_b = nla_nest_start_noflag(ans_skb,\n\t\t\t\t\t\t NLBL_CIPSOV4_A_MLSCAT);\n\t\t\tif (nla_b == NULL) {\n\t\t\t\tret_val = -ENOMEM;\n\t\t\t\tgoto list_retry;\n\t\t\t}\n\t\t\tret_val = nla_put_u32(ans_skb,\n\t\t\t\t\t NLBL_CIPSOV4_A_MLSCATLOC,\n\t\t\t\t\t iter);\n\t\t\tif (ret_val != 0)\n\t\t\t\tgoto list_retry;\n\t\t\tret_val = nla_put_u32(ans_skb,\n\t\t\t\t\t NLBL_CIPSOV4_A_MLSCATREM,\n\t\t\t\t\t doi_def->map.std->cat.local[iter]);\n\t\t\tif (ret_val != 0)\n\t\t\t\tgoto list_retry;\n\t\t\tnla_nest_end(ans_skb, nla_b);\n\t\t}\n\t\tnla_nest_end(ans_skb, nla_a);\n\n\t\tbreak;\n\t}\n\trcu_read_unlock();\n\n\tgenlmsg_end(ans_skb, data);\n\treturn genlmsg_reply(ans_skb, info);\n\nlist_retry:\n\t/* XXX - this limit is a guesstimate */\n\tif (nlsze_mult < 4) {\n\t\trcu_read_unlock();\n\t\tkfree_skb(ans_skb);\n\t\tnlsze_mult *= 2;\n\t\tgoto list_start;\n\t}\nlist_failure_lock:\n\trcu_read_unlock();\nlist_failure:\n\tkfree_skb(ans_skb);\n\treturn ret_val;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'cipso,calipso: resolve a number of problems with the DOI refcounts\n\nThe current CIPSO and CALIPSO refcounting scheme for the DOI\ndefinitions is a bit flawed in that we:\n\n1. Don't correctly match gets/puts in netlbl_cipsov4_list().\n2. Decrement the refcount on each attempt to remove the DOI from the\n DOI list, only removing it from the list once the refcount drops\n to zero.\n\nThis patch fixes these problems by adding the missing \"puts\" to\nnetlbl_cipsov4_list() and introduces a more conventional, i.e.\nnot-buggy, refcounting mechanism to the DOI definitions. Upon the\naddition of a DOI to the DOI list, it is initialized with a refcount\nof one, removing a DOI from the list removes it from the list and\ndrops the refcount by one; \"gets\" and \"puts\" behave as expected with\nrespect to refcounts, increasing and decreasing the DOI's refcount by\none.\n\nFixes: b1edeb102397 (\"netlabel: Replace protocol/NetLabel linking with refrerence counts\")\nFixes: d7cce01504a0 (\"netlabel: Add support for removing a CALIPSO DOI.\")\nReported-by: syzbot+9ec037722d2603a9f52e@syzkaller.appspotmail.com\nSigned-off-by: Paul Moore \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: XSetStandardProperties (\n \tDisplay *dpy,\n \tWindow w,\t\t/* window to decorate */\n \t_Xconst char *name,\t/* name of application */\n \t_Xconst char *icon_string,/* name string for icon */\n\tPixmap icon_pixmap,\t/* pixmap to use as icon, or None */\n \tchar **argv,\t\t/* command to be used to restart application */\n \tint argc,\t\t/* count of arguments */\n \tXSizeHints *hints)\t/* size hints for window in its normal state */\n{\n\tXWMHints phints;\n\tphints.flags = 0;\n\n\tif (name != NULL) XStoreName (dpy, w, name);\n\n\tif (icon_string != NULL) {\n\t XChangeProperty (dpy, w, XA_WM_ICON_NAME, XA_STRING, 8,\n PropModeReplace,\n (_Xconst unsigned char *)icon_string,\n (int)safestrlen(icon_string));\n\t\t}\n\n\tif (icon_pixmap != None) {\n\t\tphints.icon_pixmap = icon_pixmap;\n\t\tphints.flags |= IconPixmapHint;\n\t\t}\n\tif (argv != NULL) XSetCommand(dpy, w, argv, argc);\n\n\tif (hints != NULL) XSetNormalHints(dpy, w, hints);\n\n\tif (phints.flags != 0) XSetWMHints(dpy, w, &phints);\n\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'Reject string longer than USHRT_MAX before sending them on the wire\n\nThe X protocol uses CARD16 values to represent the length so\nthis would overflow.\n\nCVE-2021-31535\n\nSigned-off-by: Matthieu Herrb '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: XLookupColor (\n\tregister Display *dpy,\n Colormap cmap,\n\t_Xconst char *spec,\n\tXColor *def,\n\tXColor *scr)\n{\n\tregister int n;\n\txLookupColorReply reply;\n\tregister xLookupColorReq *req;\n\tXcmsCCC ccc;\n\tXcmsColor cmsColor_exact;\n\n#ifdef XCMS\n\t/*\n\t * Let's Attempt to use Xcms and i18n approach to Parse Color\n\t */\n\tif ((ccc = XcmsCCCOfColormap(dpy, cmap)) != (XcmsCCC)NULL) {\n\t const char *tmpName = spec;\n\n\t switch (_XcmsResolveColorString(ccc, &tmpName, &cmsColor_exact,\n\t\t\t\t\t XcmsRGBFormat)) {\n\t case XcmsSuccess:\n\t case XcmsSuccessWithCompression:\n\t\t_XcmsRGB_to_XColor(&cmsColor_exact, def, 1);\n\t\tmemcpy((char *)scr, (char *)def, sizeof(XColor));\n\t\t_XUnresolveColor(ccc, scr);\n\t\treturn(1);\n\t case XcmsFailure:\n\t case _XCMS_NEWNAME:\n\t\t/*\n\t\t * if the result was _XCMS_NEWNAME tmpName points to\n\t\t * a string in cmsColNm.c:pairs table, for example,\n\t\t * gray70 would become tekhvc:0.0/70.0/0.0\n\t\t */\n\t\tbreak;\n\t }\n\t}\n#endif\n\n\t/*\n\t * Xcms and i18n methods failed, so lets pass it to the server\n\t * for parsing.\n\t */\n\n\tn = (int) strlen (spec);\n\tLockDisplay(dpy);\n\tGetReq (LookupColor, req);\n\treq->cmap = cmap;\n\treq->nbytes = n;\n\treq->length += (n + 3) >> 2;\n\tData (dpy, spec, (long)n);\n\tif (!_XReply (dpy, (xReply *) &reply, 0, xTrue)) {\n\t UnlockDisplay(dpy);\n\t SyncHandle();\n\t return (0);\n\t }\n\tdef->red = reply.exactRed;\n\tdef->green = reply.exactGreen;\n\tdef->blue = reply.exactBlue;\n\n\tscr->red = reply.screenRed;\n\tscr->green = reply.screenGreen;\n\tscr->blue = reply.screenBlue;\n\n\tUnlockDisplay(dpy);\n\tSyncHandle();\n\treturn (1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'Reject string longer than USHRT_MAX before sending them on the wire\n\nThe X protocol uses CARD16 values to represent the length so\nthis would overflow.\n\nCVE-2021-31535\n\nSigned-off-by: Matthieu Herrb '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: CacheManager::Start(const Comm::ConnectionPointer &client, HttpRequest * request, StoreEntry * entry)\n{\n debugs(16, 3, \"CacheManager::Start: '\" << entry->url() << \"'\" );\n\n Mgr::Command::Pointer cmd = ParseUrl(entry->url());\n if (!cmd) {\n ErrorState *err = new ErrorState(ERR_INVALID_URL, Http::scNotFound, request);\n err->url = xstrdup(entry->url());\n errorAppendEntry(entry, err);\n entry->expires = squid_curtime;\n return;\n }\n\n const char *actionName = cmd->profile->name;\n\n entry->expires = squid_curtime;\n\n debugs(16, 5, \"CacheManager: \" << client << \" requesting '\" << actionName << \"'\");\n\n /* get additional info from request headers */\n ParseHeaders(request, cmd->params);\n\n const char *userName = cmd->params.userName.size() ?\n cmd->params.userName.termedBuf() : \"unknown\";\n\n /* Check password */\n\n if (CheckPassword(*cmd) != 0) {\n /* build error message */\n ErrorState errState(ERR_CACHE_MGR_ACCESS_DENIED, Http::scUnauthorized, request);\n /* warn if user specified incorrect password */\n\n if (cmd->params.password.size()) {\n debugs(16, DBG_IMPORTANT, \"CacheManager: \" <<\n userName << \"@\" <<\n client << \": incorrect password for '\" <<\n actionName << \"'\" );\n } else {\n debugs(16, DBG_IMPORTANT, \"CacheManager: \" <<\n userName << \"@\" <<\n client << \": password needed for '\" <<\n actionName << \"'\" );\n }\n\n HttpReply *rep = errState.BuildHttpReply();\n\n#if HAVE_AUTH_MODULE_BASIC\n /*\n * add Authenticate header using action name as a realm because\n * password depends on the action\n */\n rep->header.putAuth(\"Basic\", actionName);\n#endif\n // Allow cachemgr and other XHR scripts access to our version string\n if (request->header.has(Http::HdrType::ORIGIN)) {\n rep->header.putExt(\"Access-Control-Allow-Origin\",request->header.getStr(Http::HdrType::ORIGIN));\n#if HAVE_AUTH_MODULE_BASIC\n rep->header.putExt(\"Access-Control-Allow-Credentials\",\"true\");\n#endif\n rep->header.putExt(\"Access-Control-Expose-Headers\",\"Server\");\n }\n\n /* store the reply */\n entry->replaceHttpReply(rep);\n\n entry->expires = squid_curtime;\n\n entry->complete();\n\n return;\n }\n\n if (request->header.has(Http::HdrType::ORIGIN)) {\n cmd->params.httpOrigin = request->header.getStr(Http::HdrType::ORIGIN);\n }\n\n debugs(16, 2, \"CacheManager: \" <<\n userName << \"@\" <<\n client << \" requesting '\" <<\n actionName << \"'\" );\n\n // special case: /squid-internal-mgr/ index page\n if (!strcmp(cmd->profile->name, \"index\")) {\n ErrorState err(MGR_INDEX, Http::scOkay, request);\n err.url = xstrdup(entry->url());\n HttpReply *rep = err.BuildHttpReply();\n if (strncmp(rep->body.content(),\"Internal Error:\", 15) == 0)\n rep->sline.set(Http::ProtocolVersion(1,1), Http::scNotFound);\n // Allow cachemgr and other XHR scripts access to our version string\n if (request->header.has(Http::HdrType::ORIGIN)) {\n rep->header.putExt(\"Access-Control-Allow-Origin\",request->header.getStr(Http::HdrType::ORIGIN));\n#if HAVE_AUTH_MODULE_BASIC\n rep->header.putExt(\"Access-Control-Allow-Credentials\",\"true\");\n#endif\n rep->header.putExt(\"Access-Control-Expose-Headers\",\"Server\");\n }\n entry->replaceHttpReply(rep);\n entry->complete();\n return;\n }\n\n if (UsingSmp() && IamWorkerProcess()) {\n // is client the right connection to pass here?\n AsyncJob::Start(new Mgr::Forwarder(client, cmd->params, request, entry));\n return;\n }\n\n Mgr::Action::Pointer action = cmd->profile->creator->create(cmd);\n Must(action != NULL);\n action->run(entry, true);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'Bug 5106: Broken cache manager URL parsing (#788)\n\nUse already parsed request-target URL in cache manager and\nupdate CacheManager to Tokanizer based URL parse\n\nRemoving use of sscan() and regex string processing which have\nproven to be problematic on many levels. Most particularly with\nregards to tolerance of normally harmless garbage syntax in URLs\nreceived.\n\nSupport for generic URI schemes is added possibly resolving some\nissues reported with ftp:// URL and manager access via ftp_port\nsockets.\n\nTruly generic support for /squid-internal-mgr/ path prefix is\nadded, fixing some user confusion about its use on cache_object:\nscheme URLs.\n\nTODO: support for single-name parameters and URL #fragments\nare left to future updates. As is refactoring the QueryParams\ndata storage to avoid SBuf data copying.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: clientInterpretRequestHeaders(ClientHttpRequest * http)\n{\n HttpRequest *request = http->request;\n HttpHeader *req_hdr = &request->header;\n bool no_cache = false;\n\n request->imslen = -1;\n request->ims = req_hdr->getTime(Http::HdrType::IF_MODIFIED_SINCE);\n\n if (request->ims > 0)\n request->flags.ims = true;\n\n if (!request->flags.ignoreCc) {\n if (request->cache_control) {\n if (request->cache_control->hasNoCache())\n no_cache=true;\n\n // RFC 2616: treat Pragma:no-cache as if it was Cache-Control:no-cache when Cache-Control is missing\n } else if (req_hdr->has(Http::HdrType::PRAGMA))\n no_cache = req_hdr->hasListMember(Http::HdrType::PRAGMA,\"no-cache\",',');\n }\n\n if (request->method == Http::METHOD_OTHER) {\n no_cache=true;\n }\n\n if (no_cache) {\n#if USE_HTTP_VIOLATIONS\n\n if (Config.onoff.reload_into_ims)\n request->flags.nocacheHack = true;\n else if (refresh_nocache_hack)\n request->flags.nocacheHack = true;\n else\n#endif\n\n request->flags.noCache = true;\n }\n\n /* ignore range header in non-GETs or non-HEADs */\n if (request->method == Http::METHOD_GET || request->method == Http::METHOD_HEAD) {\n // XXX: initialize if we got here without HttpRequest::parseHeader()\n if (!request->range)\n request->range = req_hdr->getRange();\n\n if (request->range) {\n request->flags.isRanged = true;\n clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->data;\n /* XXX: This is suboptimal. We should give the stream the range set,\n * and thereby let the top of the stream set the offset when the\n * size becomes known. As it is, we will end up requesting from 0\n * for evey -X range specification.\n * RBC - this may be somewhat wrong. We should probably set the range\n * iter up at this point.\n */\n node->readBuffer.offset = request->range->lowestOffset(0);\n http->range_iter.pos = request->range->begin();\n http->range_iter.end = request->range->end();\n http->range_iter.valid = true;\n }\n }\n\n /* Only HEAD and GET requests permit a Range or Request-Range header.\n * If these headers appear on any other type of request, delete them now.\n */\n else {\n req_hdr->delById(Http::HdrType::RANGE);\n req_hdr->delById(Http::HdrType::REQUEST_RANGE);\n request->ignoreRange(\"neither HEAD nor GET\");\n }\n\n if (req_hdr->has(Http::HdrType::AUTHORIZATION))\n request->flags.auth = true;\n\n clientCheckPinning(http);\n\n if (!request->url.userInfo().isEmpty())\n request->flags.auth = true;\n\n if (req_hdr->has(Http::HdrType::VIA)) {\n String s = req_hdr->getList(Http::HdrType::VIA);\n /*\n * ThisCache cannot be a member of Via header, \"1.1 ThisCache\" can.\n * Note ThisCache2 has a space prepended to the hostname so we don't\n * accidentally match super-domains.\n */\n\n if (strListIsSubstr(&s, ThisCache2, ',')) {\n debugObj(33, 1, \"WARNING: Forwarding loop detected for:\\n\",\n request, (ObjPackMethod) & httpRequestPack);\n request->flags.loopDetected = true;\n }\n\n#if USE_FORW_VIA_DB\n fvdbCountVia(s.termedBuf());\n\n#endif\n\n s.clean();\n }\n\n#if USE_FORW_VIA_DB\n\n if (req_hdr->has(Http::HdrType::X_FORWARDED_FOR)) {\n String s = req_hdr->getList(Http::HdrType::X_FORWARDED_FOR);\n fvdbCountForw(s.termedBuf());\n s.clean();\n }\n\n#endif\n\n request->flags.cachable = http->request->maybeCacheable();\n\n if (clientHierarchical(http))\n request->flags.hierarchical = true;\n\n debugs(85, 5, \"clientInterpretRequestHeaders: REQ_NOCACHE = \" <<\n (request->flags.noCache ? \"SET\" : \"NOT SET\"));\n debugs(85, 5, \"clientInterpretRequestHeaders: REQ_CACHABLE = \" <<\n (request->flags.cachable ? \"SET\" : \"NOT SET\"));\n debugs(85, 5, \"clientInterpretRequestHeaders: REQ_HIERARCHICAL = \" <<\n (request->flags.hierarchical ? \"SET\" : \"NOT SET\"));\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-116'], 'message': 'Handle more Range requests (#790)\n\nAlso removed some effectively unused code.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: read_yin_anydata(struct lys_module *module, struct lys_node *parent, struct lyxml_elem *yin, LYS_NODE type,\n int options, struct unres_schema *unres)\n{\n struct ly_ctx *ctx = module->ctx;\n struct lys_node *retval;\n struct lys_node_anydata *anyxml;\n struct lyxml_elem *sub, *next;\n const char *value;\n int r;\n int f_mand = 0;\n int c_must = 0, c_ftrs = 0, c_ext = 0;\n void *reallocated;\n\n anyxml = calloc(1, sizeof *anyxml);\n LY_CHECK_ERR_RETURN(!anyxml, LOGMEM(ctx), NULL);\n\n anyxml->nodetype = type;\n anyxml->prev = (struct lys_node *)anyxml;\n retval = (struct lys_node *)anyxml;\n\n if (read_yin_common(module, parent, retval, LYEXT_PAR_NODE, yin,\n OPT_IDENT | OPT_MODULE | ((options & LYS_PARSE_OPT_CFG_IGNORE) ? OPT_CFG_IGNORE :\n (options & LYS_PARSE_OPT_CFG_NOINHERIT) ? OPT_CFG_PARSE : OPT_CFG_PARSE | OPT_CFG_INHERIT), unres)) {\n goto error;\n }\n\n LOGDBG(LY_LDGYIN, \"parsing %s statement \\\"%s\\\"\", yin->name, retval->name);\n\n /* insert the node into the schema tree */\n if (lys_node_addchild(parent, lys_main_module(module), retval, options)) {\n goto error;\n }\n\n LY_TREE_FOR_SAFE(yin->child, next, sub) {\n if (strcmp(sub->ns->value, LY_NSYIN)) {\n /* extension */\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_ext, retval->ext_size, \"extensions\", \"anydata\", error);\n c_ext++;\n } else if (!strcmp(sub->name, \"mandatory\")) {\n if (f_mand) {\n LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name);\n goto error;\n }\n /* just checking the flags in leaf is not sufficient, we would allow\n * multiple mandatory statements with the \"false\" value\n */\n f_mand = 1;\n\n GETVAL(ctx, value, sub, \"value\");\n if (!strcmp(value, \"true\")) {\n anyxml->flags |= LYS_MAND_TRUE;\n } else if (!strcmp(value, \"false\")) {\n anyxml->flags |= LYS_MAND_FALSE;\n } else {\n LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, sub->name);\n goto error;\n }\n /* else false is the default value, so we can ignore it */\n\n if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub, LYEXT_SUBSTMT_MANDATORY, 0, unres)) {\n goto error;\n }\n lyxml_free(ctx, sub);\n } else if (!strcmp(sub->name, \"when\")) {\n if (anyxml->when) {\n LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name);\n goto error;\n }\n\n anyxml->when = read_yin_when(module, sub, unres);\n if (!anyxml->when) {\n lyxml_free(ctx, sub);\n goto error;\n }\n lyxml_free(ctx, sub);\n } else if (!strcmp(sub->name, \"must\")) {\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_must, anyxml->must_size, \"musts\", \"anydata\", error);\n c_must++;\n } else if (!strcmp(sub->name, \"if-feature\")) {\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_ftrs, retval->iffeature_size, \"if-features\", \"anydata\", error);\n c_ftrs++;\n\n } else {\n LOGVAL(ctx, LYE_INSTMT, LY_VLOG_LYS, retval, sub->name);\n goto error;\n }\n }\n\n /* middle part - process nodes with cardinality of 0..n */\n if (c_must) {\n anyxml->must = calloc(c_must, sizeof *anyxml->must);\n LY_CHECK_ERR_GOTO(!anyxml->must, LOGMEM(ctx), error);\n }\n if (c_ftrs) {\n anyxml->iffeature = calloc(c_ftrs, sizeof *anyxml->iffeature);\n LY_CHECK_ERR_GOTO(!anyxml->iffeature, LOGMEM(ctx), error);\n }\n if (c_ext) {\n /* some extensions may be already present from the substatements */\n reallocated = realloc(retval->ext, (c_ext + retval->ext_size) * sizeof *retval->ext);\n LY_CHECK_ERR_GOTO(!reallocated, LOGMEM(ctx), error);\n retval->ext = reallocated;\n\n /* init memory */\n memset(&retval->ext[retval->ext_size], 0, c_ext * sizeof *retval->ext);\n }\n\n LY_TREE_FOR_SAFE(yin->child, next, sub) {\n if (strcmp(sub->ns->value, LY_NSYIN)) {\n /* extension */\n r = lyp_yin_fill_ext(retval, LYEXT_PAR_NODE, 0, 0, module, sub, &retval->ext, &retval->ext_size, unres);\n if (r) {\n goto error;\n }\n } else if (!strcmp(sub->name, \"must\")) {\n r = fill_yin_must(module, sub, &anyxml->must[anyxml->must_size], unres);\n anyxml->must_size++;\n if (r) {\n goto error;\n }\n } else if (!strcmp(sub->name, \"if-feature\")) {\n r = fill_yin_iffeature(retval, 0, sub, &anyxml->iffeature[anyxml->iffeature_size], unres);\n anyxml->iffeature_size++;\n if (r) {\n goto error;\n }\n }\n }\n\n lyp_reduce_ext_list(&retval->ext, retval->ext_size, c_ext + retval->ext_size);\n\n /* check XPath dependencies */\n if (!(ctx->models.flags & LY_CTX_TRUSTED) && (anyxml->when || anyxml->must)) {\n if (options & LYS_PARSE_OPT_INGRP) {\n if (lyxp_node_check_syntax(retval)) {\n goto error;\n }\n } else {\n if (unres_schema_add_node(module, unres, retval, UNRES_XPATH, NULL) == -1) {\n goto error;\n }\n }\n }\n\n for (r = 0; r < retval->ext_size; ++r) {\n /* set flag, which represent LYEXT_OPT_VALID */\n if (retval->ext[r]->flags & LYEXT_OPT_VALID) {\n retval->flags |= LYS_VALID_EXT;\n break;\n }\n }\n\n return retval;\n\nerror:\n lys_node_free(ctx, retval, NULL, 0);\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-252'], 'message': 'yin parser BUGFIX invalid memory access\n\n... in case there were some unresolved\nextensions.\nFixes #1454\nFixes #1455'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: lys_node_free(struct lys_node *node, void (*private_destructor)(const struct lys_node *node, void *priv), int shallow)\n{\n struct ly_ctx *ctx;\n struct lys_node *sub, *next;\n\n if (!node) {\n return;\n }\n\n assert(node->module);\n assert(node->module->ctx);\n\n ctx = node->module->ctx;\n\n /* remove private object */\n if (node->priv && private_destructor) {\n private_destructor(node, node->priv);\n }\n\n /* common part */\n lydict_remove(ctx, node->name);\n if (!(node->nodetype & (LYS_INPUT | LYS_OUTPUT))) {\n lys_iffeature_free(ctx, node->iffeature, node->iffeature_size, shallow, private_destructor);\n lydict_remove(ctx, node->dsc);\n lydict_remove(ctx, node->ref);\n }\n\n if (!shallow && !(node->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {\n LY_TREE_FOR_SAFE(node->child, next, sub) {\n lys_node_free(sub, private_destructor, 0);\n }\n }\n\n lys_extension_instances_free(ctx, node->ext, node->ext_size, private_destructor);\n\n /* specific part */\n switch (node->nodetype) {\n case LYS_CONTAINER:\n lys_container_free(ctx, (struct lys_node_container *)node, private_destructor);\n break;\n case LYS_CHOICE:\n lys_when_free(ctx, ((struct lys_node_choice *)node)->when, private_destructor);\n break;\n case LYS_LEAF:\n lys_leaf_free(ctx, (struct lys_node_leaf *)node, private_destructor);\n break;\n case LYS_LEAFLIST:\n lys_leaflist_free(ctx, (struct lys_node_leaflist *)node, private_destructor);\n break;\n case LYS_LIST:\n lys_list_free(ctx, (struct lys_node_list *)node, private_destructor);\n break;\n case LYS_ANYXML:\n case LYS_ANYDATA:\n lys_anydata_free(ctx, (struct lys_node_anydata *)node, private_destructor);\n break;\n case LYS_USES:\n lys_uses_free(ctx, (struct lys_node_uses *)node, private_destructor);\n break;\n case LYS_CASE:\n lys_when_free(ctx, ((struct lys_node_case *)node)->when, private_destructor);\n break;\n case LYS_AUGMENT:\n /* do nothing */\n break;\n case LYS_GROUPING:\n lys_grp_free(ctx, (struct lys_node_grp *)node, private_destructor);\n break;\n case LYS_RPC:\n case LYS_ACTION:\n lys_rpc_action_free(ctx, (struct lys_node_rpc_action *)node, private_destructor);\n break;\n case LYS_NOTIF:\n lys_notif_free(ctx, (struct lys_node_notif *)node, private_destructor);\n break;\n case LYS_INPUT:\n case LYS_OUTPUT:\n lys_inout_free(ctx, (struct lys_node_inout *)node, private_destructor);\n break;\n case LYS_EXT:\n case LYS_UNKNOWN:\n LOGINT(ctx);\n break;\n }\n\n /* again common part */\n lys_node_unlink(node);\n free(node);\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: lys_node_dup_recursion(struct lys_module *module, struct lys_node *parent, const struct lys_node *node,\n struct unres_schema *unres, int shallow, int finalize)\n{\n struct lys_node *retval = NULL, *iter, *p;\n struct ly_ctx *ctx = module->ctx;\n enum int_log_opts prev_ilo;\n int i, j, rc;\n unsigned int size, size1, size2;\n struct unres_list_uniq *unique_info;\n uint16_t flags;\n\n struct lys_node_container *cont = NULL;\n struct lys_node_container *cont_orig = (struct lys_node_container *)node;\n struct lys_node_choice *choice = NULL;\n struct lys_node_choice *choice_orig = (struct lys_node_choice *)node;\n struct lys_node_leaf *leaf = NULL;\n struct lys_node_leaf *leaf_orig = (struct lys_node_leaf *)node;\n struct lys_node_leaflist *llist = NULL;\n struct lys_node_leaflist *llist_orig = (struct lys_node_leaflist *)node;\n struct lys_node_list *list = NULL;\n struct lys_node_list *list_orig = (struct lys_node_list *)node;\n struct lys_node_anydata *any = NULL;\n struct lys_node_anydata *any_orig = (struct lys_node_anydata *)node;\n struct lys_node_uses *uses = NULL;\n struct lys_node_uses *uses_orig = (struct lys_node_uses *)node;\n struct lys_node_rpc_action *rpc = NULL;\n struct lys_node_inout *io = NULL;\n struct lys_node_notif *ntf = NULL;\n struct lys_node_case *cs = NULL;\n struct lys_node_case *cs_orig = (struct lys_node_case *)node;\n\n /* we cannot just duplicate memory since the strings are stored in\n * dictionary and we need to update dictionary counters.\n */\n\n switch (node->nodetype) {\n case LYS_CONTAINER:\n cont = calloc(1, sizeof *cont);\n retval = (struct lys_node *)cont;\n break;\n\n case LYS_CHOICE:\n choice = calloc(1, sizeof *choice);\n retval = (struct lys_node *)choice;\n break;\n\n case LYS_LEAF:\n leaf = calloc(1, sizeof *leaf);\n retval = (struct lys_node *)leaf;\n break;\n\n case LYS_LEAFLIST:\n llist = calloc(1, sizeof *llist);\n retval = (struct lys_node *)llist;\n break;\n\n case LYS_LIST:\n list = calloc(1, sizeof *list);\n /* copy keys now so that when adding children, it can be properly checked in this parent */\n list->keys = calloc(list_orig->keys_size, sizeof *list->keys);\n LY_CHECK_ERR_GOTO(!list->keys, LOGMEM(ctx), error);\n list->keys_size = list_orig->keys_size;\n\n retval = (struct lys_node *)list;\n break;\n\n case LYS_ANYXML:\n case LYS_ANYDATA:\n any = calloc(1, sizeof *any);\n retval = (struct lys_node *)any;\n break;\n\n case LYS_USES:\n uses = calloc(1, sizeof *uses);\n retval = (struct lys_node *)uses;\n break;\n\n case LYS_CASE:\n cs = calloc(1, sizeof *cs);\n retval = (struct lys_node *)cs;\n break;\n\n case LYS_RPC:\n case LYS_ACTION:\n rpc = calloc(1, sizeof *rpc);\n retval = (struct lys_node *)rpc;\n break;\n\n case LYS_INPUT:\n case LYS_OUTPUT:\n io = calloc(1, sizeof *io);\n retval = (struct lys_node *)io;\n break;\n\n case LYS_NOTIF:\n ntf = calloc(1, sizeof *ntf);\n retval = (struct lys_node *)ntf;\n break;\n\n default:\n LOGINT(ctx);\n goto error;\n }\n LY_CHECK_ERR_RETURN(!retval, LOGMEM(ctx), NULL);\n\n /*\n * duplicate generic part of the structure\n */\n retval->name = lydict_insert(ctx, node->name, 0);\n retval->dsc = lydict_insert(ctx, node->dsc, 0);\n retval->ref = lydict_insert(ctx, node->ref, 0);\n retval->flags = node->flags;\n\n retval->module = module;\n retval->nodetype = node->nodetype;\n\n retval->prev = retval;\n\n /* copying unresolved extensions is not supported */\n if (unres_schema_find(unres, -1, (void *)&node->ext, UNRES_EXT) == -1) {\n retval->ext_size = node->ext_size;\n if (lys_ext_dup(ctx, module, node->ext, node->ext_size, retval, LYEXT_PAR_NODE, &retval->ext, shallow, unres)) {\n goto error;\n }\n }\n\n if (node->iffeature_size) {\n retval->iffeature_size = node->iffeature_size;\n retval->iffeature = calloc(retval->iffeature_size, sizeof *retval->iffeature);\n LY_CHECK_ERR_GOTO(!retval->iffeature, LOGMEM(ctx), error);\n }\n\n if (!shallow) {\n for (i = 0; i < node->iffeature_size; ++i) {\n resolve_iffeature_getsizes(&node->iffeature[i], &size1, &size2);\n if (size1) {\n /* there is something to duplicate */\n\n /* duplicate compiled expression */\n size = (size1 / 4) + ((size1 % 4) ? 1 : 0);\n retval->iffeature[i].expr = malloc(size * sizeof *retval->iffeature[i].expr);\n LY_CHECK_ERR_GOTO(!retval->iffeature[i].expr, LOGMEM(ctx), error);\n memcpy(retval->iffeature[i].expr, node->iffeature[i].expr, size * sizeof *retval->iffeature[i].expr);\n\n /* list of feature pointer must be updated to point to the resulting tree */\n retval->iffeature[i].features = calloc(size2, sizeof *retval->iffeature[i].features);\n LY_CHECK_ERR_GOTO(!retval->iffeature[i].features, LOGMEM(ctx); free(retval->iffeature[i].expr), error);\n\n for (j = 0; (unsigned int)j < size2; j++) {\n rc = unres_schema_dup(module, unres, &node->iffeature[i].features[j], UNRES_IFFEAT,\n &retval->iffeature[i].features[j]);\n if (rc == EXIT_FAILURE) {\n /* feature is resolved in origin, so copy it\n * - duplication is used for instantiating groupings\n * and if-feature inside grouping is supposed to be\n * resolved inside the original grouping, so we want\n * to keep pointers to features from the grouping\n * context */\n retval->iffeature[i].features[j] = node->iffeature[i].features[j];\n } else if (rc == -1) {\n goto error;\n } /* else unres was duplicated */\n }\n }\n\n /* duplicate if-feature's extensions */\n retval->iffeature[i].ext_size = node->iffeature[i].ext_size;\n if (lys_ext_dup(ctx, module, node->iffeature[i].ext, node->iffeature[i].ext_size,\n &retval->iffeature[i], LYEXT_PAR_IFFEATURE, &retval->iffeature[i].ext, shallow, unres)) {\n goto error;\n }\n }\n\n /* inherit config flags */\n p = parent;\n do {\n for (iter = p; iter && (iter->nodetype == LYS_USES); iter = iter->parent);\n } while (iter && iter->nodetype == LYS_AUGMENT && (p = ((struct lys_node_augment *)iter)->target));\n if (iter) {\n flags = iter->flags & LYS_CONFIG_MASK;\n } else {\n /* default */\n flags = LYS_CONFIG_W;\n }\n\n switch (finalize) {\n case 1:\n /* inherit config flags */\n if (retval->flags & LYS_CONFIG_SET) {\n /* skip nodes with an explicit config value */\n if ((flags & LYS_CONFIG_R) && (retval->flags & LYS_CONFIG_W)) {\n LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, \"true\", \"config\");\n LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, \"State nodes cannot have configuration nodes as children.\");\n goto error;\n }\n break;\n }\n\n if (retval->nodetype != LYS_USES) {\n retval->flags = (retval->flags & ~LYS_CONFIG_MASK) | flags;\n }\n\n /* inherit status */\n if ((parent->flags & LYS_STATUS_MASK) > (retval->flags & LYS_STATUS_MASK)) {\n /* but do it only in case the parent has a stonger status */\n retval->flags &= ~LYS_STATUS_MASK;\n retval->flags |= (parent->flags & LYS_STATUS_MASK);\n }\n break;\n case 2:\n /* erase config flags */\n retval->flags &= ~LYS_CONFIG_MASK;\n retval->flags &= ~LYS_CONFIG_SET;\n break;\n }\n\n /* connect it to the parent */\n if (lys_node_addchild(parent, retval->module, retval, 0)) {\n goto error;\n }\n\n /* go recursively */\n if (!(node->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {\n LY_TREE_FOR(node->child, iter) {\n if (iter->nodetype & LYS_GROUPING) {\n /* do not instantiate groupings */\n continue;\n }\n if (!lys_node_dup_recursion(module, retval, iter, unres, 0, finalize)) {\n goto error;\n }\n }\n }\n } else {\n if (node->iffeature_size) {\n memcpy(retval->iffeature, node->iffeature, retval->iffeature_size * sizeof *retval->iffeature);\n }\n }\n\n /*\n * duplicate specific part of the structure\n */\n switch (node->nodetype) {\n case LYS_CONTAINER:\n if (cont_orig->when) {\n cont->when = lys_when_dup(module, cont_orig->when, shallow, unres);\n LY_CHECK_GOTO(!cont->when, error);\n }\n cont->presence = lydict_insert(ctx, cont_orig->presence, 0);\n\n if (cont_orig->must) {\n cont->must = lys_restr_dup(module, cont_orig->must, cont_orig->must_size, shallow, unres);\n LY_CHECK_GOTO(!cont->must, error);\n cont->must_size = cont_orig->must_size;\n }\n\n /* typedefs are not needed in instantiated grouping, nor the deviation's shallow copy */\n\n break;\n case LYS_CHOICE:\n if (choice_orig->when) {\n choice->when = lys_when_dup(module, choice_orig->when, shallow, unres);\n LY_CHECK_GOTO(!choice->when, error);\n }\n\n if (!shallow) {\n if (choice_orig->dflt) {\n rc = lys_get_sibling(choice->child, lys_node_module(retval)->name, 0, choice_orig->dflt->name, 0,\n LYS_ANYDATA | LYS_CASE | LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST,\n (const struct lys_node **)&choice->dflt);\n if (rc) {\n if (rc == EXIT_FAILURE) {\n LOGINT(ctx);\n }\n goto error;\n }\n } else {\n /* useless to check return value, we don't know whether\n * there really wasn't any default defined or it just hasn't\n * been resolved, we just hope for the best :)\n */\n unres_schema_dup(module, unres, choice_orig, UNRES_CHOICE_DFLT, choice);\n }\n } else {\n choice->dflt = choice_orig->dflt;\n }\n break;\n\n case LYS_LEAF:\n if (lys_type_dup(module, retval, &(leaf->type), &(leaf_orig->type), lys_ingrouping(retval), shallow, unres)) {\n goto error;\n }\n leaf->units = lydict_insert(module->ctx, leaf_orig->units, 0);\n\n if (leaf_orig->dflt) {\n /* transform into JSON format, may not be possible later */\n ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);\n leaf->dflt = transform_schema2json(lys_main_module(leaf_orig->module), leaf_orig->dflt);\n ly_ilo_restore(NULL, prev_ilo, NULL, 0);\n if (!leaf->dflt) {\n /* invalid identityref format or it was already transformed, so ignore the error here */\n leaf->dflt = lydict_insert(ctx, leaf_orig->dflt, 0);\n }\n }\n\n if (leaf_orig->must) {\n leaf->must = lys_restr_dup(module, leaf_orig->must, leaf_orig->must_size, shallow, unres);\n LY_CHECK_GOTO(!leaf->must, error);\n leaf->must_size = leaf_orig->must_size;\n }\n\n if (leaf_orig->when) {\n leaf->when = lys_when_dup(module, leaf_orig->when, shallow, unres);\n LY_CHECK_GOTO(!leaf->when, error);\n }\n break;\n\n case LYS_LEAFLIST:\n if (lys_type_dup(module, retval, &(llist->type), &(llist_orig->type), lys_ingrouping(retval), shallow, unres)) {\n goto error;\n }\n llist->units = lydict_insert(module->ctx, llist_orig->units, 0);\n\n llist->min = llist_orig->min;\n llist->max = llist_orig->max;\n\n if (llist_orig->must) {\n llist->must = lys_restr_dup(module, llist_orig->must, llist_orig->must_size, shallow, unres);\n LY_CHECK_GOTO(!llist->must, error);\n llist->must_size = llist_orig->must_size;\n }\n\n if (llist_orig->dflt) {\n llist->dflt = malloc(llist_orig->dflt_size * sizeof *llist->dflt);\n LY_CHECK_ERR_GOTO(!llist->dflt, LOGMEM(ctx), error);\n llist->dflt_size = llist_orig->dflt_size;\n\n for (i = 0; i < llist->dflt_size; i++) {\n llist->dflt[i] = lydict_insert(ctx, llist_orig->dflt[i], 0);\n }\n }\n\n if (llist_orig->when) {\n llist->when = lys_when_dup(module, llist_orig->when, shallow, unres);\n }\n break;\n\n case LYS_LIST:\n list->min = list_orig->min;\n list->max = list_orig->max;\n\n if (list_orig->must) {\n list->must = lys_restr_dup(module, list_orig->must, list_orig->must_size, shallow, unres);\n LY_CHECK_GOTO(!list->must, error);\n list->must_size = list_orig->must_size;\n }\n\n /* typedefs are not needed in instantiated grouping, nor the deviation's shallow copy */\n\n if (list_orig->keys_size) {\n /* already done */\n /*list->keys = calloc(list_orig->keys_size, sizeof *list->keys);\n LY_CHECK_ERR_GOTO(!list->keys, LOGMEM(ctx), error);\n list->keys_size = list_orig->keys_size;*/\n list->keys_str = lydict_insert(ctx, list_orig->keys_str, 0);\n\n if (!shallow) {\n if (unres_schema_add_node(module, unres, list, UNRES_LIST_KEYS, NULL) == -1) {\n goto error;\n }\n } else {\n memcpy(list->keys, list_orig->keys, list_orig->keys_size * sizeof *list->keys);\n }\n }\n\n if (list_orig->unique) {\n list->unique = malloc(list_orig->unique_size * sizeof *list->unique);\n LY_CHECK_ERR_GOTO(!list->unique, LOGMEM(ctx), error);\n list->unique_size = list_orig->unique_size;\n\n for (i = 0; i < list->unique_size; ++i) {\n list->unique[i].expr = malloc(list_orig->unique[i].expr_size * sizeof *list->unique[i].expr);\n LY_CHECK_ERR_GOTO(!list->unique[i].expr, LOGMEM(ctx), error);\n list->unique[i].expr_size = list_orig->unique[i].expr_size;\n for (j = 0; j < list->unique[i].expr_size; j++) {\n list->unique[i].expr[j] = lydict_insert(ctx, list_orig->unique[i].expr[j], 0);\n\n /* if it stays in unres list, duplicate it also there */\n unique_info = malloc(sizeof *unique_info);\n LY_CHECK_ERR_GOTO(!unique_info, LOGMEM(ctx), error);\n unique_info->list = (struct lys_node *)list;\n unique_info->expr = list->unique[i].expr[j];\n unique_info->trg_type = &list->unique[i].trg_type;\n unres_schema_dup(module, unres, &list_orig, UNRES_LIST_UNIQ, unique_info);\n }\n }\n }\n\n if (list_orig->when) {\n list->when = lys_when_dup(module, list_orig->when, shallow, unres);\n LY_CHECK_GOTO(!list->when, error);\n }\n break;\n\n case LYS_ANYXML:\n case LYS_ANYDATA:\n if (any_orig->must) {\n any->must = lys_restr_dup(module, any_orig->must, any_orig->must_size, shallow, unres);\n LY_CHECK_GOTO(!any->must, error);\n any->must_size = any_orig->must_size;\n }\n\n if (any_orig->when) {\n any->when = lys_when_dup(module, any_orig->when, shallow, unres);\n LY_CHECK_GOTO(!any->when, error);\n }\n break;\n\n case LYS_USES:\n uses->grp = uses_orig->grp;\n\n if (uses_orig->when) {\n uses->when = lys_when_dup(module, uses_orig->when, shallow, unres);\n LY_CHECK_GOTO(!uses->when, error);\n }\n /* it is not needed to duplicate refine, nor augment. They are already applied to the uses children */\n break;\n\n case LYS_CASE:\n if (cs_orig->when) {\n cs->when = lys_when_dup(module, cs_orig->when, shallow, unres);\n LY_CHECK_GOTO(!cs->when, error);\n }\n break;\n\n case LYS_ACTION:\n case LYS_RPC:\n case LYS_INPUT:\n case LYS_OUTPUT:\n case LYS_NOTIF:\n /* typedefs are not needed in instantiated grouping, nor the deviation's shallow copy */\n break;\n\n default:\n /* LY_NODE_AUGMENT */\n LOGINT(ctx);\n goto error;\n }\n\n return retval;\n\nerror:\n lys_node_free(retval, NULL, 0);\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'schema tree BUGFIX freeing nodes with no module set\n\nContext must be passed explicitly for these cases.\nFixes #1452'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static apr_status_t session_identity_encode(request_rec * r, session_rec * z)\n{\n\n char *buffer = NULL;\n int length = 0;\n if (z->expiry) {\n char *expiry = apr_psprintf(z->pool, \"%\" APR_INT64_T_FMT, z->expiry);\n apr_table_setn(z->entries, SESSION_EXPIRY, expiry);\n }\n apr_table_do(identity_count, &length, z->entries, NULL);\n buffer = apr_pcalloc(r->pool, length + 1);\n apr_table_do(identity_concat, buffer, z->entries, NULL);\n z->encoded = buffer;\n return OK;\n\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_compute_root_tr(const struct rsa_public_key *pub,\n\t\t const struct rsa_private_key *key,\n\t\t void *random_ctx, nettle_random_func *random,\n\t\t mpz_t x, const mpz_t m)\n{\n TMP_GMP_DECL (l, mp_limb_t);\n int res;\n\n mp_size_t l_size = NETTLE_OCTET_SIZE_TO_LIMB_SIZE(key->size);\n TMP_GMP_ALLOC (l, l_size);\n\n res = _rsa_sec_compute_root_tr (pub, key, random_ctx, random, l,\n\t\t\t\t mpz_limbs_read(m), mpz_size(m));\n if (res) {\n mp_limb_t *xp = mpz_limbs_write (x, l_size);\n mpn_copyi (xp, l, l_size);\n mpz_limbs_finish (x, l_size);\n }\n\n TMP_GMP_FREE (l);\n return res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Change _rsa_sec_compute_root_tr to take a fix input size.\n\nImproves consistency with _rsa_sec_compute_root, and fixes zero-input bug.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void io_req_task_queue(struct io_kiocb *req)\n{\n\tint ret;\n\n\tinit_task_work(&req->task_work, io_req_task_submit);\n\n\tret = io_req_task_work_add(req, &req->task_work);\n\tif (unlikely(ret)) {\n\t\tstruct task_struct *tsk;\n\n\t\tinit_task_work(&req->task_work, io_req_task_cancel);\n\t\ttsk = io_wq_get_task(req->ctx->io_wq);\n\t\ttask_work_add(tsk, &req->task_work, 0);\n\t\twake_up_process(tsk);\n\t}\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: parse_ipsecrequest(struct xfrm_policy *xp, struct sadb_x_ipsecrequest *rq)\n{\n\tstruct net *net = xp_net(xp);\n\tstruct xfrm_tmpl *t = xp->xfrm_vec + xp->xfrm_nr;\n\tint mode;\n\n\tif (xp->xfrm_nr >= XFRM_MAX_DEPTH)\n\t\treturn -ELOOP;\n\n\tif (rq->sadb_x_ipsecrequest_mode == 0)\n\t\treturn -EINVAL;\n\n\tt->id.proto = rq->sadb_x_ipsecrequest_proto; /* XXX check proto */\n\tif ((mode = pfkey_mode_to_xfrm(rq->sadb_x_ipsecrequest_mode)) < 0)\n\t\treturn -EINVAL;\n\tt->mode = mode;\n\tif (rq->sadb_x_ipsecrequest_level == IPSEC_LEVEL_USE)\n\t\tt->optional = 1;\n\telse if (rq->sadb_x_ipsecrequest_level == IPSEC_LEVEL_UNIQUE) {\n\t\tt->reqid = rq->sadb_x_ipsecrequest_reqid;\n\t\tif (t->reqid > IPSEC_MANUAL_REQID_MAX)\n\t\t\tt->reqid = 0;\n\t\tif (!t->reqid && !(t->reqid = gen_reqid(net)))\n\t\t\treturn -ENOBUFS;\n\t}\n\n\t/* addresses present only in tunnel mode */\n\tif (t->mode == XFRM_MODE_TUNNEL) {\n\t\tint err;\n\n\t\terr = parse_sockaddr_pair(\n\t\t\t(struct sockaddr *)(rq + 1),\n\t\t\trq->sadb_x_ipsecrequest_len - sizeof(*rq),\n\t\t\t&t->saddr, &t->id.daddr, &t->encap_family);\n\t\tif (err)\n\t\t\treturn err;\n\t} else\n\t\tt->encap_family = xp->family;\n\n\t/* No way to set this via kame pfkey */\n\tt->allalgs = 1;\n\txp->xfrm_nr++;\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_lock_files(struct ucma_file *file1, struct ucma_file *file2)\n{\n\t/* Acquire mutex's based on pointer comparison to prevent deadlock. */\n\tif (file1 < file2) {\n\t\tmutex_lock(&file1->mut);\n\t\tmutex_lock_nested(&file2->mut, SINGLE_DEPTH_NESTING);\n\t} else {\n\t\tmutex_lock(&file2->mut);\n\t\tmutex_lock_nested(&file1->mut, SINGLE_DEPTH_NESTING);\n\t}\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_cache_expire(struct sss_cmdline *cmdline,\n struct sss_tool_ctx *tool_ctx,\n void *pvt)\n{\n errno_t ret;\n char *cmd_args = NULL;\n const char *cachecmd = SSS_CACHE;\n char *cmd = NULL;\n int i;\n\n if (cmdline->argc == 0) {\n ret = sssctl_run_command(cachecmd);\n goto done;\n }\n\n cmd_args = talloc_strdup(tool_ctx, \"\");\n if (cmd_args == NULL) {\n ret = ENOMEM;\n goto done;\n }\n\n for (i = 0; i < cmdline->argc; i++) {\n cmd_args = talloc_strdup_append(cmd_args, cmdline->argv[i]);\n if (i != cmdline->argc - 1) {\n cmd_args = talloc_strdup_append(cmd_args, \" \");\n }\n }\n\n cmd = talloc_asprintf(tool_ctx, \"%s %s\", cachecmd, cmd_args);\n if (cmd == NULL) {\n ret = ENOMEM;\n goto done;\n }\n\n ret = sssctl_run_command(cmd);\n\ndone:\n talloc_free(cmd_args);\n talloc_free(cmd);\n\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-78'], 'message': 'TOOLS: replace system() with execvp() to avoid execution of user supplied command\n\n:relnote: A flaw was found in SSSD, where the sssctl command was\nvulnerable to shell command injection via the logs-fetch and\ncache-expire subcommands. This flaw allows an attacker to trick\nthe root user into running a specially crafted sssctl command,\nsuch as via sudo, to gain root access. The highest threat from this\nvulnerability is to confidentiality, integrity, as well as system\navailability.\nThis patch fixes a flaw by replacing system() with execvp().\n\n:fixes: CVE-2021-3621\n\nReviewed-by: Pavel B\u0159ezina '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Jp2Image::encodeJp2Header(const DataBuf& boxBuf,DataBuf& outBuf)\n {\n DataBuf output(boxBuf.size_ + iccProfile_.size_ + 100); // allocate sufficient space\n int outlen = sizeof(Jp2BoxHeader) ; // now many bytes have we written to output?\n int inlen = sizeof(Jp2BoxHeader) ; // how many bytes have we read from boxBuf?\n Jp2BoxHeader* pBox = (Jp2BoxHeader*) boxBuf.pData_;\n int32_t length = getLong((byte*)&pBox->length, bigEndian);\n int32_t count = sizeof (Jp2BoxHeader);\n char* p = (char*) boxBuf.pData_;\n bool bWroteColor = false ;\n\n while ( count < length || !bWroteColor ) {\n Jp2BoxHeader* pSubBox = (Jp2BoxHeader*) (p+count) ;\n\n // copy data. pointer could be into a memory mapped file which we will decode!\n Jp2BoxHeader subBox ; memcpy(&subBox,pSubBox,sizeof(subBox));\n Jp2BoxHeader newBox = subBox;\n\n if ( count < length ) {\n subBox.length = getLong((byte*)&subBox.length, bigEndian);\n subBox.type = getLong((byte*)&subBox.type , bigEndian);\n#ifdef EXIV2_DEBUG_MESSAGES\n std::cout << \"Jp2Image::encodeJp2Header subbox: \"<< toAscii(subBox.type) << \" length = \" << subBox.length << std::endl;\n#endif\n count += subBox.length;\n newBox.type = subBox.type;\n } else {\n subBox.length=0;\n newBox.type = kJp2BoxTypeColorHeader;\n count = length;\n }\n\n int32_t newlen = subBox.length;\n if ( newBox.type == kJp2BoxTypeColorHeader ) {\n bWroteColor = true ;\n if ( ! iccProfileDefined() ) {\n const char* pad = \"\\x01\\x00\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x05\\x1cuuid\";\n uint32_t psize = 15;\n newlen = sizeof(newBox) + psize ;\n ul2Data((byte*)&newBox.length,psize ,bigEndian);\n ul2Data((byte*)&newBox.type ,newBox.type,bigEndian);\n ::memcpy(output.pData_+outlen ,&newBox ,sizeof(newBox));\n ::memcpy(output.pData_+outlen+sizeof(newBox) ,pad ,psize );\n } else {\n const char* pad = \"\\x02\\x00\\x00\";\n uint32_t psize = 3;\n newlen = sizeof(newBox) + psize + iccProfile_.size_;\n ul2Data((byte*)&newBox.length,newlen,bigEndian);\n ul2Data((byte*)&newBox.type,newBox.type,bigEndian);\n ::memcpy(output.pData_+outlen ,&newBox ,sizeof(newBox) );\n ::memcpy(output.pData_+outlen+sizeof(newBox) , pad ,psize );\n ::memcpy(output.pData_+outlen+sizeof(newBox)+psize,iccProfile_.pData_,iccProfile_.size_);\n }\n } else {\n ::memcpy(output.pData_+outlen,boxBuf.pData_+inlen,subBox.length);\n }\n\n outlen += newlen;\n inlen += subBox.length;\n }\n\n // allocate the correct number of bytes, copy the data and update the box header\n outBuf.alloc(outlen);\n ::memcpy(outBuf.pData_,output.pData_,outlen);\n pBox = (Jp2BoxHeader*) outBuf.pData_;\n ul2Data((byte*)&pBox->type,kJp2BoxTypeJp2Header,bigEndian);\n ul2Data((byte*)&pBox->length,outlen,bigEndian);\n } // Jp2Image::encodeJp2Header ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-787'], 'message': 'Better bounds checking in Jp2Image::encodeJp2Header()'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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_perm(struct cil_perm *perm)\n{\n\tcil_reset_classperms_list(perm->classperms);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'libsepol/cil: Destroy classperm list when resetting map perms\n\nMap perms share the same struct as regular perms, but only the\nmap perms use the classperms field. This field is a pointer to a\nlist of classperms that is created and added to when resolving\nclassmapping rules, so the map permission doesn't own any of the\ndata in the list and this list should be destroyed when the AST is\nreset.\n\nWhen resetting a perm, destroy the classperms list without destroying\nthe data in the list.\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: static int translate_compat_table(struct net *net,\n\t\t\t\t struct xt_table_info **pinfo,\n\t\t\t\t void **pentry0,\n\t\t\t\t const struct compat_arpt_replace *compatr)\n{\n\tunsigned int i, j;\n\tstruct xt_table_info *newinfo, *info;\n\tvoid *pos, *entry0, *entry1;\n\tstruct compat_arpt_entry *iter0;\n\tstruct arpt_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(NFPROTO_ARP);\n\tret = xt_compat_init_offsets(NFPROTO_ARP, 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_ARP_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\n\txt_compat_flush_offsets(NFPROTO_ARP);\n\txt_compat_unlock(NFPROTO_ARP);\n\n\tmemcpy(&repl, compatr, sizeof(*compatr));\n\n\tfor (i = 0; i < NF_ARP_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(NFPROTO_ARP);\n\txt_compat_unlock(NFPROTO_ARP);\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: check_compat_entry_size_and_hooks(struct ipt_entry *e,\n\t\t\t struct xt_table_info *newinfo,\n\t\t\t unsigned int *size,\n\t\t\t unsigned char *base,\n\t\t\t unsigned char *limit,\n\t\t\t unsigned int *hook_entries,\n\t\t\t unsigned int *underflows,\n\t\t\t unsigned int *i,\n\t\t\t const char *name)\n{\n\tstruct ipt_entry_target *t;\n\tstruct ipt_target *target;\n\tu_int16_t entry_offset;\n\tint ret, off, h, j;\n\n\tduprintf(\"check_compat_entry_size_and_hooks %p\\n\", e);\n\tif ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0\n\t || (unsigned char *)e + sizeof(struct compat_ipt_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_ipt_entry) +\n\t\t\tsizeof(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\tif (!ip_checkentry(&e->ip)) {\n\t\tduprintf(\"ip_tables: ip check failed %p %s.\\n\", e, name);\n\t\treturn -EINVAL;\n\t}\n\n\toff = 0;\n\tentry_offset = (void *)e - (void *)base;\n\tj = 0;\n\tret = IPT_MATCH_ITERATE(e, compat_check_calc_match, name, &e->ip,\n\t\t\te->comefrom, &off, &j);\n\tif (ret != 0)\n\t\tgoto cleanup_matches;\n\n\tt = ipt_get_target(e);\n\ttarget = try_then_request_module(xt_find_target(AF_INET,\n\t\t\t\t\t\t t->u.user.name,\n\t\t\t\t\t\t t->u.user.revision),\n\t\t\t\t\t \"ipt_%s\", t->u.user.name);\n\tif (IS_ERR(target) || !target) {\n\t\tduprintf(\"check_entry: `%s' not found\\n\", t->u.user.name);\n\t\tret = target ? PTR_ERR(target) : -ENOENT;\n\t\tgoto cleanup_matches;\n\t}\n\tt->u.kernel.target = target;\n\n\tif (t->u.kernel.target->compat)\n\t\tt->u.kernel.target->compat(t, NULL, &off, COMPAT_CALC_SIZE);\n\telse\n\t\txt_compat_target(t, NULL, &off, COMPAT_CALC_SIZE);\n\t*size += off;\n\tret = compat_add_offset(entry_offset, off);\n\tif (ret)\n\t\tgoto out;\n\n\t/* Check hooks & underflows */\n\tfor (h = 0; h < NF_IP_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\te->counters = ((struct ipt_counters) { 0, 0 });\n\te->comefrom = 0;\n\n\t(*i)++;\n\treturn 0;\n\nout:\n\tmodule_put(t->u.kernel.target->me);\ncleanup_matches:\n\tIPT_MATCH_ITERATE(e, cleanup_match, &j);\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: ImagingConvertTransparent(Imaging imIn, const char *mode, int r, int g, int b) {\n ImagingSectionCookie cookie;\n ImagingShuffler convert;\n Imaging imOut = NULL;\n int y;\n\n if (!imIn) {\n return (Imaging)ImagingError_ModeError();\n }\n\n if (!((strcmp(imIn->mode, \"RGB\") == 0 || strcmp(imIn->mode, \"1\") == 0 ||\n strcmp(imIn->mode, \"I\") == 0 || strcmp(imIn->mode, \"L\") == 0) &&\n strcmp(mode, \"RGBA\") == 0))\n#ifdef notdef\n {\n return (Imaging)ImagingError_ValueError(\"conversion not supported\");\n }\n#else\n {\n static char buf[100];\n sprintf(\n buf,\n \"conversion from %.10s to %.10s not supported in convert_transparent\",\n imIn->mode,\n mode);\n return (Imaging)ImagingError_ValueError(buf);\n }\n#endif\n\n if (strcmp(imIn->mode, \"RGB\") == 0) {\n convert = rgb2rgba;\n } else {\n if (strcmp(imIn->mode, \"1\") == 0) {\n convert = bit2rgb;\n } else if (strcmp(imIn->mode, \"I\") == 0) {\n convert = i2rgb;\n } else {\n convert = l2rgb;\n }\n g = b = r;\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 rgbT2rgba((UINT8 *)imOut->image[y], imIn->xsize, r, g, b);\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: ec_verify(krb5_context context, krb5_data *req_pkt, krb5_kdc_req *request,\n krb5_enc_tkt_part *enc_tkt_reply, krb5_pa_data *data,\n krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock,\n krb5_kdcpreauth_moddata moddata,\n krb5_kdcpreauth_verify_respond_fn respond, void *arg)\n{\n krb5_error_code retval = 0;\n krb5_enc_data *enc = NULL;\n krb5_data scratch, plain;\n krb5_keyblock *armor_key = cb->fast_armor(context, rock);\n krb5_pa_enc_ts *ts = NULL;\n krb5_keyblock *client_keys = NULL;\n krb5_keyblock *challenge_key = NULL;\n krb5_keyblock *kdc_challenge_key;\n krb5_kdcpreauth_modreq modreq = NULL;\n int i = 0;\n char *ai = NULL, *realmstr = NULL;\n krb5_data realm = request->server->realm;\n\n plain.data = NULL;\n\n if (armor_key == NULL) {\n retval = ENOENT;\n k5_setmsg(context, ENOENT,\n _(\"Encrypted Challenge used outside of FAST tunnel\"));\n }\n scratch.data = (char *) data->contents;\n scratch.length = data->length;\n if (retval == 0)\n retval = decode_krb5_enc_data(&scratch, &enc);\n if (retval == 0) {\n plain.data = malloc(enc->ciphertext.length);\n plain.length = enc->ciphertext.length;\n if (plain.data == NULL)\n retval = ENOMEM;\n }\n\n /* Check for a configured FAST ec auth indicator. */\n realmstr = k5memdup0(realm.data, realm.length, &retval);\n if (realmstr != NULL)\n retval = profile_get_string(context->profile, KRB5_CONF_REALMS,\n realmstr,\n KRB5_CONF_ENCRYPTED_CHALLENGE_INDICATOR,\n NULL, &ai);\n\n if (retval == 0)\n retval = cb->client_keys(context, rock, &client_keys);\n if (retval == 0) {\n for (i = 0; client_keys[i].enctype&& (retval == 0); i++ ) {\n retval = krb5_c_fx_cf2_simple(context,\n armor_key, \"clientchallengearmor\",\n &client_keys[i], \"challengelongterm\",\n &challenge_key);\n if (retval == 0)\n retval = krb5_c_decrypt(context, challenge_key,\n KRB5_KEYUSAGE_ENC_CHALLENGE_CLIENT,\n NULL, enc, &plain);\n if (challenge_key)\n krb5_free_keyblock(context, challenge_key);\n challenge_key = NULL;\n if (retval == 0)\n break;\n /*We failed to decrypt. Try next key*/\n retval = 0;\n }\n if (client_keys[i].enctype == 0) {\n retval = KRB5KDC_ERR_PREAUTH_FAILED;\n k5_setmsg(context, retval,\n _(\"Incorrect password in encrypted challenge\"));\n }\n }\n if (retval == 0)\n retval = decode_krb5_pa_enc_ts(&plain, &ts);\n if (retval == 0)\n retval = krb5_check_clockskew(context, ts->patimestamp);\n if (retval == 0) {\n enc_tkt_reply->flags |= TKT_FLG_PRE_AUTH;\n /*\n * If this fails, we won't generate a reply to the client. That may\n * cause the client to fail, but at this point the KDC has considered\n * this a success, so the return value is ignored.\n */\n if (krb5_c_fx_cf2_simple(context, armor_key, \"kdcchallengearmor\",\n &client_keys[i], \"challengelongterm\",\n &kdc_challenge_key) == 0) {\n modreq = (krb5_kdcpreauth_modreq)kdc_challenge_key;\n if (ai != NULL)\n cb->add_auth_indicator(context, rock, ai);\n }\n }\n cb->free_keys(context, rock, client_keys);\n if (plain.data)\n free(plain.data);\n if (enc)\n krb5_free_enc_data(context, enc);\n if (ts)\n krb5_free_pa_enc_ts(context, ts);\n free(realmstr);\n free(ai);\n\n (*respond)(arg, retval, modreq, NULL, NULL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix KDC null deref on bad encrypted challenge\n\nThe function ec_verify() in src/kdc/kdc_preauth_ec.c contains a check\nto avoid further processing if the armor key is NULL. However, this\ncheck is bypassed by a call to k5memdup0() which overwrites retval\nwith 0 if the allocation succeeds. If the armor key is NULL, a call\nto krb5_c_fx_cf2_simple() will then dereference it, resulting in a\ncrash. Add a check before the k5memdup0() call to avoid overwriting\nretval.\n\nCVE-2021-36222:\n\nIn MIT krb5 releases 1.16 and later, an unauthenticated attacker can\ncause a null dereference in the KDC by sending a request containing a\nPA-ENCRYPTED-CHALLENGE padata element without using FAST.\n\n[ghudson@mit.edu: trimmed patch; added test case; edited commit\nmessage]\n\nticket: 9007 (new)\ntags: pullup\ntarget_version: 1.19-next\ntarget_version: 1.18-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 update_discovery_filter(struct btd_adapter *adapter)\n{\n\tstruct mgmt_cp_start_service_discovery *sd_cp;\n\tGSList *l;\n\n\n\tDBG(\"\");\n\n\tif (discovery_filter_to_mgmt_cp(adapter, &sd_cp)) {\n\t\tbtd_error(adapter->dev_id,\n\t\t\t\t\"discovery_filter_to_mgmt_cp returned error\");\n\t\treturn -ENOMEM;\n\t}\n\n\tfor (l = adapter->discovery_list; l; l = g_slist_next(l)) {\n\t\tstruct discovery_client *client = l->data;\n\n\t\tif (!client->discovery_filter)\n\t\t\tcontinue;\n\n\t\tif (client->discovery_filter->discoverable)\n\t\t\tbreak;\n\t}\n\n\tset_discovery_discoverable(adapter, l ? true : false);\n\n\t/*\n\t * If filters are equal, then don't update scan, except for when\n\t * starting discovery.\n\t */\n\tif (filters_equal(adapter->current_discovery_filter, sd_cp) &&\n\t adapter->discovering != 0) {\n\t\tDBG(\"filters were equal, deciding to not restart the scan.\");\n\t\tg_free(sd_cp);\n\t\treturn 0;\n\t}\n\n\tg_free(adapter->current_discovery_filter);\n\tadapter->current_discovery_filter = sd_cp;\n\n\ttrigger_start_discovery(adapter, 0);\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 int decode_font(ASS_Track *track)\n{\n unsigned char *p;\n unsigned char *q;\n size_t i;\n size_t size; // original size\n size_t dsize; // decoded size\n unsigned char *buf = 0;\n\n ass_msg(track->library, MSGL_V, \"Font: %d bytes encoded data\",\n track->parser_priv->fontdata_used);\n size = track->parser_priv->fontdata_used;\n if (size % 4 == 1) {\n ass_msg(track->library, MSGL_ERR, \"Bad encoded data size\");\n goto error_decode_font;\n }\n buf = malloc(size / 4 * 3 + FFMAX(size % 4 - 1, 0));\n if (!buf)\n goto error_decode_font;\n q = buf;\n for (i = 0, p = (unsigned char *) track->parser_priv->fontdata;\n i < size / 4; i++, p += 4) {\n q = decode_chars(p, q, 4);\n }\n if (size % 4 == 2) {\n q = decode_chars(p, q, 2);\n } else if (size % 4 == 3) {\n q = decode_chars(p, q, 3);\n }\n dsize = q - buf;\n assert(dsize == size / 4 * 3 + FFMAX(size % 4 - 1, 0));\n\n if (track->library->extract_fonts) {\n ass_add_font(track->library, track->parser_priv->fontname,\n (char *) buf, dsize);\n }\n\nerror_decode_font:\n free(buf);\n reset_embedded_font_parsing(track->parser_priv);\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369', 'CWE-787'], 'message': 'decode_font: fix subtraction broken by change to unsigned type\n\nThis caused a one-byte buffer overwrite and an assertion failure.\n\nRegression in commit 910211f1c0078e37546f73e95306724358b89be2.\n\nDiscovered by OSS-Fuzz.\n\nFixes https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=26674.\nFixes https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=26678.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int oidc_cache_crypto_decrypt(request_rec *r, const char *cache_value,\n\t\tunsigned char *key, unsigned char **plaintext) {\n\n\tint len = -1;\n\n\t/* grab the base64url-encoded tag after the \".\" */\n\tchar *encoded_tag = strstr(cache_value, \".\");\n\tif (encoded_tag == NULL) {\n\t\toidc_error(r,\n\t\t\t\t\"corrupted cache value: no tag separator found in encrypted value\");\n\t\treturn FALSE;\n\t}\n\n\t/* make sure we don't modify the original string since it may be just a pointer into the cache (shm) */\n\tcache_value = apr_pstrmemdup(r->pool, cache_value,\n\t\t\tstrlen(cache_value) - strlen(encoded_tag));\n\tencoded_tag++;\n\n\t/* base64url decode the ciphertext */\n\tchar *d_bytes = NULL;\n\tint d_len = oidc_base64url_decode(r->pool, &d_bytes, cache_value);\n\n\t/* base64url decode the tag */\n\tchar *t_bytes = NULL;\n\tint t_len = oidc_base64url_decode(r->pool, &t_bytes, encoded_tag);\n\n\t/* see if we're still good to go */\n\tif ((d_len > 0) && (t_len > 0)) {\n\n\t\t/* allocated space for the plaintext */\n\t\t*plaintext = apr_pcalloc(r->pool,\n\t\t\t\t(d_len + EVP_CIPHER_block_size(OIDC_CACHE_CIPHER) - 1));\n\n\t\t/* decrypt the ciphertext providing the tag value */\n\n\t\tlen = oidc_cache_crypto_decrypt_impl(r, (unsigned char *) d_bytes,\n\t\t\t\td_len, OIDC_CACHE_CRYPTO_GCM_AAD,\n\t\t\t\tsizeof(OIDC_CACHE_CRYPTO_GCM_AAD), (unsigned char *) t_bytes,\n\t\t\t\tt_len, key, OIDC_CACHE_CRYPTO_GCM_IV,\n\t\t\t\tsizeof(OIDC_CACHE_CRYPTO_GCM_IV), *plaintext);\n\n\t\t/* check the result and make sure it is \\0 terminated */\n\t\tif (len > -1) {\n\t\t\t(*plaintext)[len] = '\\0';\n\t\t} else {\n\t\t\t*plaintext = NULL;\n\t\t}\n\n\t}\n\n\treturn len;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-330'], 'message': 'use encrypted JWTs for storing encrypted cache contents\n\n- avoid using static AAD/IV; thanks @niebardzo\n- bump to 2.4.9-dev\n\nSigned-off-by: Hans Zandbelt '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static pj_bool_t on_handshake_complete(pj_ssl_sock_t *ssock, \n\t\t\t\t pj_status_t status)\n{\n /* Cancel handshake timer */\n if (ssock->timer.id == TIMER_HANDSHAKE_TIMEOUT) {\n\tpj_timer_heap_cancel(ssock->param.timer_heap, &ssock->timer);\n\tssock->timer.id = TIMER_NONE;\n }\n\n /* Update certificates info on successful handshake */\n if (status == PJ_SUCCESS)\n\tssl_update_certs_info(ssock);\n\n /* Accepting */\n if (ssock->is_server) {\n\tif (status != PJ_SUCCESS) {\n\t /* Handshake failed in accepting, destroy our self silently. */\n\n\t char buf[PJ_INET6_ADDRSTRLEN+10];\n\n\t PJ_PERROR(3,(ssock->pool->obj_name, status,\n\t\t\t \"Handshake failed in accepting %s\",\n\t\t\t pj_sockaddr_print(&ssock->rem_addr, buf,\n\t\t\t\t\t sizeof(buf), 3)));\n\n\t if (ssock->param.cb.on_accept_complete2) {\n\t\t(*ssock->param.cb.on_accept_complete2) \n\t\t (ssock->parent, ssock, (pj_sockaddr_t*)&ssock->rem_addr, \n\t\t pj_sockaddr_get_len((pj_sockaddr_t*)&ssock->rem_addr), \n\t\t status);\n\t }\n\n\t /* Originally, this is a workaround for ticket #985. However,\n\t * a race condition may occur in multiple worker threads\n\t * environment when we are destroying SSL objects while other\n\t * threads are still accessing them.\n\t * Please see ticket #1930 for more info.\n\t */\n#if 1 //(defined(PJ_WIN32) && PJ_WIN32!=0)||(defined(PJ_WIN64) && PJ_WIN64!=0)\n\t if (ssock->param.timer_heap) {\n\t\tpj_time_val interval = {0, PJ_SSL_SOCK_DELAYED_CLOSE_TIMEOUT};\n\t\tpj_status_t status1;\n\n\t\tssock->ssl_state = SSL_STATE_NULL;\n\t\tssl_close_sockets(ssock);\n\n\t\tif (ssock->timer.id != TIMER_NONE) {\n\t\t pj_timer_heap_cancel(ssock->param.timer_heap,\n\t\t\t\t\t &ssock->timer);\n\t\t}\n\t\tpj_time_val_normalize(&interval);\n\t\tstatus1 = pj_timer_heap_schedule_w_grp_lock(\n\t\t\t\t\t\t ssock->param.timer_heap, \n\t\t\t\t\t\t &ssock->timer,\n\t\t\t\t\t\t &interval,\n\t\t\t\t\t\t TIMER_CLOSE,\n\t\t\t\t\t\t ssock->param.grp_lock);\n\t\tif (status1 != PJ_SUCCESS) {\n\t \t PJ_PERROR(3,(ssock->pool->obj_name, status,\n\t\t\t\t \"Failed to schedule a delayed close. \"\n\t\t\t\t \"Race condition may occur.\"));\n\t\t ssock->timer.id = TIMER_NONE;\n\t\t pj_ssl_sock_close(ssock);\n\t\t}\n\t } else {\n\t\tpj_ssl_sock_close(ssock);\n\t }\n#else\n\t {\n\t\tpj_ssl_sock_close(ssock);\n\t }\n#endif\n\n\t return PJ_FALSE;\n\t}\n\t/* Notify application the newly accepted SSL socket */\n\tif (ssock->param.cb.on_accept_complete2) {\n\t pj_bool_t ret;\n\t ret = (*ssock->param.cb.on_accept_complete2) \n\t\t (ssock->parent, ssock, (pj_sockaddr_t*)&ssock->rem_addr, \n\t\t pj_sockaddr_get_len((pj_sockaddr_t*)&ssock->rem_addr), \n\t\t status);\n\t if (ret == PJ_FALSE)\n\t\treturn PJ_FALSE;\t\n\t} else if (ssock->param.cb.on_accept_complete) {\n\t pj_bool_t ret;\n\t ret = (*ssock->param.cb.on_accept_complete)\n\t\t (ssock->parent, ssock, (pj_sockaddr_t*)&ssock->rem_addr,\n\t\t pj_sockaddr_get_len((pj_sockaddr_t*)&ssock->rem_addr));\n\t if (ret == PJ_FALSE)\n\t\treturn PJ_FALSE;\n\t}\n }\n\n /* Connecting */\n else {\n\t/* On failure, reset SSL socket state first, as app may try to \n\t * reconnect in the callback.\n\t */\n\tif (status != PJ_SUCCESS) {\n\t /* Server disconnected us, possibly due to SSL nego failure */\n\t ssl_reset_sock_state(ssock);\n\t}\n\tif (ssock->param.cb.on_connect_complete) {\n\t pj_bool_t ret;\n\t ret = (*ssock->param.cb.on_connect_complete)(ssock, status);\n\t if (ret == PJ_FALSE)\n\t\treturn PJ_FALSE;\n\t}\n }\n\n return PJ_TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362', 'CWE-703'], 'message': 'Merge pull request from GHSA-cv8x-p47p-99wr\n\n* - Avoid SSL socket parent/listener getting destroyed during handshake by increasing parent's reference count.\n- Add missing SSL socket close when the newly accepted SSL socket is discarded in SIP TLS transport.\n\n* - Fix silly mistake: accepted active socket created without group lock in SSL socket.\n- Replace assertion with normal validation check of SSL socket instance in OpenSSL verification callback (verify_cb()) to avoid crash, e.g: if somehow race condition with SSL socket destroy happens or OpenSSL application data index somehow gets corrupted.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void CrwMap::encode0x1810(const Image& image,\n const CrwMapping* pCrwMapping,\n CiffHeader* pHead)\n {\n assert(pCrwMapping != 0);\n assert(pHead != 0);\n\n const ExifKey kX(\"Exif.Photo.PixelXDimension\");\n const ExifKey kY(\"Exif.Photo.PixelYDimension\");\n const ExifKey kO(\"Exif.Image.Orientation\");\n const ExifData &exivData = image.exifData();\n const ExifData::const_iterator edX = exivData.findKey(kX);\n const ExifData::const_iterator edY = exivData.findKey(kY);\n const ExifData::const_iterator edO = exivData.findKey(kO);\n const ExifData::const_iterator edEnd = exivData.end();\n\n CiffComponent* cc = pHead->findComponent(pCrwMapping->crwTagId_,\n pCrwMapping->crwDir_);\n if (edX != edEnd || edY != edEnd || edO != edEnd) {\n uint32_t size = 28;\n if (cc && cc->size() > size) size = cc->size();\n DataBuf buf(size);\n std::memset(buf.pData_, 0x0, buf.size_);\n if (cc) std::memcpy(buf.pData_ + 8, cc->pData() + 8, cc->size() - 8);\n if (edX != edEnd && edX->size() == 4) {\n edX->copy(buf.pData_, pHead->byteOrder());\n }\n if (edY != edEnd && edY->size() == 4) {\n edY->copy(buf.pData_ + 4, pHead->byteOrder());\n }\n int32_t d = 0;\n if (edO != edEnd && edO->count() > 0 && edO->typeId() == unsignedShort) {\n d = RotationMap::degrees(static_cast(edO->toLong()));\n }\n l2Data(buf.pData_ + 12, d, pHead->byteOrder());\n pHead->add(pCrwMapping->crwTagId_, pCrwMapping->crwDir_, buf);\n }\n else {\n pHead->remove(pCrwMapping->crwTagId_, pCrwMapping->crwDir_);\n }\n } // CrwMap::encode0x1810 ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix 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: read_pattern_file ()\n{\n int max_new_patterns;\n char **new_save_patterns;\n int new_num_patterns;\n int i;\n dynamic_string pattern_name;\n FILE *pattern_fp;\n\n if (num_patterns < 0)\n num_patterns = 0;\n max_new_patterns = 1 + num_patterns;\n new_save_patterns = (char **) xmalloc (max_new_patterns * sizeof (char *));\n new_num_patterns = num_patterns;\n ds_init (&pattern_name, 128);\n\n pattern_fp = fopen (pattern_file_name, \"r\");\n if (pattern_fp == NULL)\n open_fatal (pattern_file_name);\n while (ds_fgetstr (pattern_fp, &pattern_name, '\\n') != NULL)\n {\n if (new_num_patterns >= max_new_patterns)\n\t{\n\t max_new_patterns += 1;\n\t new_save_patterns = (char **)\n\t xrealloc ((char *) new_save_patterns,\n\t\t max_new_patterns * sizeof (char *));\n\t}\n new_save_patterns[new_num_patterns] = xstrdup (pattern_name.ds_string);\n ++new_num_patterns;\n }\n if (ferror (pattern_fp) || fclose (pattern_fp) == EOF)\n close_error (pattern_file_name);\n\n for (i = 0; i < num_patterns; ++i)\n new_save_patterns[i] = save_patterns[i];\n\n save_patterns = new_save_patterns;\n num_patterns = new_num_patterns;\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: static noinline int join_transaction(struct btrfs_fs_info *fs_info,\n\t\t\t\t unsigned int type)\n{\n\tstruct btrfs_transaction *cur_trans;\n\n\tspin_lock(&fs_info->trans_lock);\nloop:\n\t/* The file system has been taken offline. No new transactions. */\n\tif (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {\n\t\tspin_unlock(&fs_info->trans_lock);\n\t\treturn -EROFS;\n\t}\n\n\tcur_trans = fs_info->running_transaction;\n\tif (cur_trans) {\n\t\tif (TRANS_ABORTED(cur_trans)) {\n\t\t\tspin_unlock(&fs_info->trans_lock);\n\t\t\treturn cur_trans->aborted;\n\t\t}\n\t\tif (btrfs_blocked_trans_types[cur_trans->state] & type) {\n\t\t\tspin_unlock(&fs_info->trans_lock);\n\t\t\treturn -EBUSY;\n\t\t}\n\t\trefcount_inc(&cur_trans->use_count);\n\t\tatomic_inc(&cur_trans->num_writers);\n\t\textwriter_counter_inc(cur_trans, type);\n\t\tspin_unlock(&fs_info->trans_lock);\n\t\treturn 0;\n\t}\n\tspin_unlock(&fs_info->trans_lock);\n\n\t/*\n\t * If we are ATTACH, we just want to catch the current transaction,\n\t * and commit it. If there is no transaction, just return ENOENT.\n\t */\n\tif (type == TRANS_ATTACH)\n\t\treturn -ENOENT;\n\n\t/*\n\t * JOIN_NOLOCK only happens during the transaction commit, so\n\t * it is impossible that ->running_transaction is NULL\n\t */\n\tBUG_ON(type == TRANS_JOIN_NOLOCK);\n\n\tcur_trans = kmalloc(sizeof(*cur_trans), GFP_NOFS);\n\tif (!cur_trans)\n\t\treturn -ENOMEM;\n\n\tspin_lock(&fs_info->trans_lock);\n\tif (fs_info->running_transaction) {\n\t\t/*\n\t\t * someone started a transaction after we unlocked. Make sure\n\t\t * to redo the checks above\n\t\t */\n\t\tkfree(cur_trans);\n\t\tgoto loop;\n\t} else if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {\n\t\tspin_unlock(&fs_info->trans_lock);\n\t\tkfree(cur_trans);\n\t\treturn -EROFS;\n\t}\n\n\tcur_trans->fs_info = fs_info;\n\tatomic_set(&cur_trans->pending_ordered, 0);\n\tinit_waitqueue_head(&cur_trans->pending_wait);\n\tatomic_set(&cur_trans->num_writers, 1);\n\textwriter_counter_init(cur_trans, type);\n\tinit_waitqueue_head(&cur_trans->writer_wait);\n\tinit_waitqueue_head(&cur_trans->commit_wait);\n\tcur_trans->state = TRANS_STATE_RUNNING;\n\t/*\n\t * One for this trans handle, one so it will live on until we\n\t * commit the transaction.\n\t */\n\trefcount_set(&cur_trans->use_count, 2);\n\tcur_trans->flags = 0;\n\tcur_trans->start_time = ktime_get_seconds();\n\n\tmemset(&cur_trans->delayed_refs, 0, sizeof(cur_trans->delayed_refs));\n\n\tcur_trans->delayed_refs.href_root = RB_ROOT_CACHED;\n\tcur_trans->delayed_refs.dirty_extent_root = RB_ROOT;\n\tatomic_set(&cur_trans->delayed_refs.num_entries, 0);\n\n\t/*\n\t * although the tree mod log is per file system and not per transaction,\n\t * the log must never go across transaction boundaries.\n\t */\n\tsmp_mb();\n\tif (!list_empty(&fs_info->tree_mod_seq_list))\n\t\tWARN(1, KERN_ERR \"BTRFS: tree_mod_seq_list not empty when creating a fresh transaction\\n\");\n\tif (!RB_EMPTY_ROOT(&fs_info->tree_mod_log))\n\t\tWARN(1, KERN_ERR \"BTRFS: tree_mod_log rb tree not empty when creating a fresh transaction\\n\");\n\tatomic64_set(&fs_info->tree_mod_seq, 0);\n\n\tspin_lock_init(&cur_trans->delayed_refs.lock);\n\n\tINIT_LIST_HEAD(&cur_trans->pending_snapshots);\n\tINIT_LIST_HEAD(&cur_trans->dev_update_list);\n\tINIT_LIST_HEAD(&cur_trans->switch_commits);\n\tINIT_LIST_HEAD(&cur_trans->dirty_bgs);\n\tINIT_LIST_HEAD(&cur_trans->io_bgs);\n\tINIT_LIST_HEAD(&cur_trans->dropped_roots);\n\tmutex_init(&cur_trans->cache_write_mutex);\n\tspin_lock_init(&cur_trans->dirty_bgs_lock);\n\tINIT_LIST_HEAD(&cur_trans->deleted_bgs);\n\tspin_lock_init(&cur_trans->dropped_roots_lock);\n\tINIT_LIST_HEAD(&cur_trans->releasing_ebs);\n\tspin_lock_init(&cur_trans->releasing_ebs_lock);\n\tatomic64_set(&cur_trans->chunk_bytes_reserved, 0);\n\tinit_waitqueue_head(&cur_trans->chunk_reserve_wait);\n\tlist_add_tail(&cur_trans->list, &fs_info->trans_list);\n\textent_io_tree_init(fs_info, &cur_trans->dirty_pages,\n\t\t\tIO_TREE_TRANS_DIRTY_PAGES, fs_info->btree_inode);\n\textent_io_tree_init(fs_info, &cur_trans->pinned_extents,\n\t\t\tIO_TREE_FS_PINNED_EXTENTS, NULL);\n\tfs_info->generation++;\n\tcur_trans->transid = fs_info->generation;\n\tfs_info->running_transaction = cur_trans;\n\tcur_trans->aborted = 0;\n\tspin_unlock(&fs_info->trans_lock);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-667'], 'message': 'btrfs: fix deadlock with concurrent chunk allocations involving system chunks\n\nWhen a task attempting to allocate a new chunk verifies that there is not\ncurrently enough free space in the system space_info and there is another\ntask that allocated a new system chunk but it did not finish yet the\ncreation of the respective block group, it waits for that other task to\nfinish creating the block group. This is to avoid exhaustion of the system\nchunk array in the superblock, which is limited, when we have a thundering\nherd of tasks allocating new chunks. This problem was described and fixed\nby commit eafa4fd0ad0607 (\"btrfs: fix exhaustion of the system chunk array\ndue to concurrent allocations\").\n\nHowever there are two very similar scenarios where this can lead to a\ndeadlock:\n\n1) Task B allocated a new system chunk and task A is waiting on task B\n to finish creation of the respective system block group. However before\n task B ends its transaction handle and finishes the creation of the\n system block group, it attempts to allocate another chunk (like a data\n chunk for an fallocate operation for a very large range). Task B will\n be unable to progress and allocate the new chunk, because task A set\n space_info->chunk_alloc to 1 and therefore it loops at\n btrfs_chunk_alloc() waiting for task A to finish its chunk allocation\n and set space_info->chunk_alloc to 0, but task A is waiting on task B\n to finish creation of the new system block group, therefore resulting\n in a deadlock;\n\n2) Task B allocated a new system chunk and task A is waiting on task B to\n finish creation of the respective system block group. By the time that\n task B enter the final phase of block group allocation, which happens\n at btrfs_create_pending_block_groups(), when it modifies the extent\n tree, the device tree or the chunk tree to insert the items for some\n new block group, it needs to allocate a new chunk, so it ends up at\n btrfs_chunk_alloc() and keeps looping there because task A has set\n space_info->chunk_alloc to 1, but task A is waiting for task B to\n finish creation of the new system block group and release the reserved\n system space, therefore resulting in a deadlock.\n\nIn short, the problem is if a task B needs to allocate a new chunk after\nit previously allocated a new system chunk and if another task A is\ncurrently waiting for task B to complete the allocation of the new system\nchunk.\n\nUnfortunately this deadlock scenario introduced by the previous fix for\nthe system chunk array exhaustion problem does not have a simple and short\nfix, and requires a big change to rework the chunk allocation code so that\nchunk btree updates are all made in the first phase of chunk allocation.\nAnd since this deadlock regression is being frequently hit on zoned\nfilesystems and the system chunk array exhaustion problem is triggered\nin more extreme cases (originally observed on PowerPC with a node size\nof 64K when running the fallocate tests from stress-ng), revert the\nchanges from that commit. The next patch in the series, with a subject\nof \"btrfs: rework chunk allocation to avoid exhaustion of the system\nchunk array\" does the necessary changes to fix the system chunk array\nexhaustion problem.\n\nReported-by: Naohiro Aota \nLink: https://lore.kernel.org/linux-btrfs/20210621015922.ewgbffxuawia7liz@naota-xeon/\nFixes: eafa4fd0ad0607 (\"btrfs: fix exhaustion of the system chunk array due to concurrent allocations\")\nCC: stable@vger.kernel.org # 5.12+\nTested-by: Shin'ichiro Kawasaki \nTested-by: Naohiro Aota \nSigned-off-by: Filipe Manana \nTested-by: David Sterba \nSigned-off-by: David Sterba '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int enter_svm_guest_mode(struct vcpu_svm *svm, u64 vmcb12_gpa,\n\t\t\t struct vmcb *vmcb12)\n{\n\tint ret;\n\n\tsvm->nested.vmcb12_gpa = vmcb12_gpa;\n\tload_nested_vmcb_control(svm, &vmcb12->control);\n\tnested_prepare_vmcb_save(svm, vmcb12);\n\tnested_prepare_vmcb_control(svm);\n\n\tret = nested_svm_load_cr3(&svm->vcpu, vmcb12->save.cr3,\n\t\t\t\t nested_npt_enabled(svm));\n\tif (ret)\n\t\treturn ret;\n\n\tsvm_set_gif(svm, true);\n\n\treturn 0;\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\tsquashfs_dir_header_2 dirh;\n\tchar buffer[sizeof(squashfs_dir_entry_2) + SQUASHFS_NAME_LEN + 1]\n\t\t__attribute__((aligned));\n\tsquashfs_dir_entry_2 *dire = (squashfs_dir_entry_2 *) buffer;\n\tlong long start;\n\tint bytes;\n\tint dir_count, size;\n\tstruct dir_ent *new_dir;\n\tstruct dir *dir;\n\n\tTRACE(\"squashfs_opendir: inode start block %d, offset %d\\n\",\n\t\tblock_start, offset);\n\n\t*i = read_inode(block_start, offset);\n\n\tdir = malloc(sizeof(struct dir));\n\tif(dir == NULL)\n\t\tEXIT_UNSQUASH(\"squashfs_opendir: malloc failed!\\n\");\n\n\tdir->dir_count = 0;\n\tdir->cur_entry = 0;\n\tdir->mode = (*i)->mode;\n\tdir->uid = (*i)->uid;\n\tdir->guid = (*i)->gid;\n\tdir->mtime = (*i)->time;\n\tdir->xattr = (*i)->xattr;\n\tdir->dirs = NULL;\n\n\tif ((*i)->data == 0)\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\t\t\n\tstart = sBlk.s.directory_table_start + (*i)->start;\n\tbytes = lookup_entry(directory_table_hash, start);\n\tif(bytes == -1)\n\t\tEXIT_UNSQUASH(\"squashfs_opendir: directory block %d not \"\n\t\t\t\"found!\\n\", block_start);\n\n\tbytes += (*i)->offset;\n\tsize = (*i)->data + bytes;\n\n\twhile(bytes < size) {\t\t\t\n\t\tif(swap) {\n\t\t\tsquashfs_dir_header_2 sdirh;\n\t\t\tmemcpy(&sdirh, directory_table + bytes, sizeof(sdirh));\n\t\t\tSQUASHFS_SWAP_DIR_HEADER_2(&dirh, &sdirh);\n\t\t} else\n\t\t\tmemcpy(&dirh, directory_table + bytes, sizeof(dirh));\n\t\n\t\tdir_count = dirh.count + 1;\n\t\tTRACE(\"squashfs_opendir: Read directory header @ byte position \"\n\t\t\t\"%d, %d directory entries\\n\", bytes, dir_count);\n\t\tbytes += sizeof(dirh);\n\n\t\t/* dir_count should never be larger than SQUASHFS_DIR_COUNT */\n\t\tif(dir_count > SQUASHFS_DIR_COUNT) {\n\t\t\tERROR(\"File system corrupted: too many entries in directory\\n\");\n\t\t\tgoto corrupted;\n\t\t}\n\n\t\twhile(dir_count--) {\n\t\t\tif(swap) {\n\t\t\t\tsquashfs_dir_entry_2 sdire;\n\t\t\t\tmemcpy(&sdire, directory_table + bytes,\n\t\t\t\t\tsizeof(sdire));\n\t\t\t\tSQUASHFS_SWAP_DIR_ENTRY_2(dire, &sdire);\n\t\t\t} else\n\t\t\t\tmemcpy(dire, directory_table + bytes,\n\t\t\t\t\tsizeof(*dire));\n\t\t\tbytes += sizeof(*dire);\n\n\t\t\t/* size should never be SQUASHFS_NAME_LEN or larger */\n\t\t\tif(dire->size >= SQUASHFS_NAME_LEN) {\n\t\t\t\tERROR(\"File system corrupted: filename too long\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tmemcpy(dire->name, directory_table + bytes,\n\t\t\t\tdire->size + 1);\n\t\t\tdire->name[dire->size + 1] = '\\0';\n\t\t\tTRACE(\"squashfs_opendir: directory entry %s, inode \"\n\t\t\t\t\"%d:%d, type %d\\n\", dire->name,\n\t\t\t\tdirh.start_block, dire->offset, dire->type);\n\t\t\tif((dir->dir_count % DIR_ENT_SIZE) == 0) {\n\t\t\t\tnew_dir = realloc(dir->dirs, (dir->dir_count +\n\t\t\t\t\tDIR_ENT_SIZE) * sizeof(struct dir_ent));\n\t\t\t\tif(new_dir == NULL)\n\t\t\t\t\tEXIT_UNSQUASH(\"squashfs_opendir: \"\n\t\t\t\t\t\t\"realloc failed!\\n\");\n\t\t\t\tdir->dirs = new_dir;\n\t\t\t}\n\t\t\tstrcpy(dir->dirs[dir->dir_count].name, dire->name);\n\t\t\tdir->dirs[dir->dir_count].start_block =\n\t\t\t\tdirh.start_block;\n\t\t\tdir->dirs[dir->dir_count].offset = dire->offset;\n\t\t\tdir->dirs[dir->dir_count].type = dire->type;\n\t\t\tdir->dir_count ++;\n\t\t\tbytes += dire->size + 1;\n\t\t}\n\t}\n\n\treturn dir;\n\ncorrupted:\n\tfree(dir->dirs);\n\tfree(dir);\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'Unsquashfs: fix write outside destination directory exploit\n\nAn issue on Github (https://github.com/plougher/squashfs-tools/issues/72)\nshows how some specially crafted Squashfs filesystems containing\ninvalid file names (with '/' and ..) can cause Unsquashfs to write\nfiles outside of the destination directory.\n\nThis commit fixes this exploit by checking all names for\nvalidity.\n\nIn doing so I have also added checks for '.' and for names that\nare shorter than they should be (names in the file system should\nnot have '\\0' terminators).\n\nSigned-off-by: Phillip Lougher '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int dissect_dvb_s2_bb(tvbuff_t *tvb, int cur_off, proto_tree *tree, packet_info *pinfo)\n{\n proto_item *ti;\n proto_tree *dvb_s2_bb_tree;\n\n guint8 input8, matype1;\n guint8 sync_flag = 0;\n guint16 input16, bb_data_len = 0, user_packet_length;\n\n int sub_dissected = 0, flag_is_ms = 0, new_off = 0;\n\n static int * const bb_header_bitfields[] = {\n &hf_dvb_s2_bb_matype1_gs,\n &hf_dvb_s2_bb_matype1_mis,\n &hf_dvb_s2_bb_matype1_acm,\n &hf_dvb_s2_bb_matype1_issyi,\n &hf_dvb_s2_bb_matype1_npd,\n &hf_dvb_s2_bb_matype1_low_ro,\n NULL\n };\n\n col_append_str(pinfo->cinfo, COL_PROTOCOL, \"BB \");\n col_append_str(pinfo->cinfo, COL_INFO, \"Baseband \");\n\n /* create display subtree for the protocol */\n ti = proto_tree_add_item(tree, proto_dvb_s2_bb, tvb, cur_off, DVB_S2_BB_HEADER_LEN, ENC_NA);\n dvb_s2_bb_tree = proto_item_add_subtree(ti, ett_dvb_s2_bb);\n\n matype1 = tvb_get_guint8(tvb, cur_off + DVB_S2_BB_OFFS_MATYPE1);\n new_off += 1;\n\n if (BIT_IS_CLEAR(matype1, DVB_S2_BB_MIS_POS))\n flag_is_ms = 1;\n\n proto_tree_add_bitmask_with_flags(dvb_s2_bb_tree, tvb, cur_off + DVB_S2_BB_OFFS_MATYPE1, hf_dvb_s2_bb_matype1,\n ett_dvb_s2_bb_matype1, bb_header_bitfields, ENC_BIG_ENDIAN, BMT_NO_FLAGS);\n\n input8 = tvb_get_guint8(tvb, cur_off + DVB_S2_BB_OFFS_MATYPE1);\n\n if ((pinfo->fd->num == 1) && (_use_low_rolloff_value != 0)) {\n _use_low_rolloff_value = 0;\n }\n if (((input8 & 0x03) == 3) && !_use_low_rolloff_value) {\n _use_low_rolloff_value = 1;\n }\n if (_use_low_rolloff_value) {\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_matype1_low_ro, tvb,\n cur_off + DVB_S2_BB_OFFS_MATYPE1, 1, ENC_BIG_ENDIAN);\n } else {\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_matype1_high_ro, tvb,\n cur_off + DVB_S2_BB_OFFS_MATYPE1, 1, ENC_BIG_ENDIAN);\n }\n\n input8 = tvb_get_guint8(tvb, cur_off + DVB_S2_BB_OFFS_MATYPE2);\n new_off += 1;\n if (flag_is_ms) {\n proto_tree_add_uint_format_value(dvb_s2_bb_tree, hf_dvb_s2_bb_matype2, tvb,\n cur_off + DVB_S2_BB_OFFS_MATYPE2, 1, input8, \"Input Stream Identifier (ISI): %d\",\n input8);\n } else {\n proto_tree_add_uint_format_value(dvb_s2_bb_tree, hf_dvb_s2_bb_matype2, tvb,\n cur_off + DVB_S2_BB_OFFS_MATYPE2, 1, input8, \"reserved\");\n }\n\n user_packet_length = input16 = tvb_get_ntohs(tvb, cur_off + DVB_S2_BB_OFFS_UPL);\n new_off += 2;\n\n proto_tree_add_uint_format(dvb_s2_bb_tree, hf_dvb_s2_bb_upl, tvb,\n cur_off + DVB_S2_BB_OFFS_UPL, 2, input16, \"User Packet Length: %d bits (%d bytes)\",\n (guint16) input16, (guint16) input16 / 8);\n\n bb_data_len = input16 = tvb_get_ntohs(tvb, cur_off + DVB_S2_BB_OFFS_DFL);\n bb_data_len /= 8;\n new_off += 2;\n\n proto_tree_add_uint_format_value(dvb_s2_bb_tree, hf_dvb_s2_bb_dfl, tvb,\n cur_off + DVB_S2_BB_OFFS_DFL, 2, input16, \"%d bits (%d bytes)\", input16, input16 / 8);\n\n new_off += 1;\n sync_flag = tvb_get_guint8(tvb, cur_off + DVB_S2_BB_OFFS_SYNC);\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_sync, tvb, cur_off + DVB_S2_BB_OFFS_SYNC, 1, ENC_BIG_ENDIAN);\n\n new_off += 2;\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_syncd, tvb, cur_off + DVB_S2_BB_OFFS_SYNCD, 2, ENC_BIG_ENDIAN);\n\n new_off += 1;\n proto_tree_add_checksum(dvb_s2_bb_tree, tvb, cur_off + DVB_S2_BB_OFFS_CRC, hf_dvb_s2_bb_crc, hf_dvb_s2_bb_crc_status, &ei_dvb_s2_bb_crc, pinfo,\n compute_crc8(tvb, DVB_S2_BB_HEADER_LEN - 1, cur_off), ENC_NA, PROTO_CHECKSUM_VERIFY);\n\n switch (matype1 & DVB_S2_BB_TSGS_MASK) {\n case DVB_S2_BB_TSGS_GENERIC_CONTINUOUS:\n /* Check GSE constraints on the BB header per 9.2.1 of ETSI TS 102 771 */\n if (BIT_IS_SET(matype1, DVB_S2_BB_ISSYI_POS)) {\n expert_add_info(pinfo, ti, &ei_dvb_s2_bb_issy_invalid);\n }\n if (BIT_IS_SET(matype1, DVB_S2_BB_NPD_POS)) {\n expert_add_info(pinfo, ti, &ei_dvb_s2_bb_npd_invalid);\n }\n if (user_packet_length != 0x0000) {\n expert_add_info_format(pinfo, ti, &ei_dvb_s2_bb_upl_invalid,\n \"UPL is 0x%04x. It must be 0x0000 for GSE packets.\", user_packet_length);\n }\n\n\n if (dvb_s2_df_dissection) {\n while (bb_data_len) {\n if (sync_flag == DVB_S2_BB_SYNC_EIP_CRC32 && bb_data_len == DVB_S2_BB_EIP_CRC32_LEN) {\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_eip_crc32, tvb, cur_off + new_off, bb_data_len, ENC_NA);\n bb_data_len = 0;\n new_off += DVB_S2_BB_EIP_CRC32_LEN;\n } else {\n /* start DVB-GSE dissector */\n sub_dissected = dissect_dvb_s2_gse(tvb, cur_off + new_off, tree, pinfo, bb_data_len);\n new_off += sub_dissected;\n\n if ((sub_dissected <= bb_data_len) && (sub_dissected >= DVB_S2_GSE_MINSIZE)) {\n bb_data_len -= sub_dissected;\n if (bb_data_len < DVB_S2_GSE_MINSIZE)\n bb_data_len = 0;\n }\n }\n }\n } else {\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_df, tvb, cur_off + new_off, bb_data_len, ENC_NA);\n new_off += bb_data_len;\n }\n break;\n\n case DVB_S2_BB_TSGS_GENERIC_PACKETIZED:\n proto_tree_add_item(tree, hf_dvb_s2_bb_packetized, tvb, cur_off + new_off, bb_data_len, ENC_NA);\n new_off += bb_data_len;\n break;\n\n case DVB_S2_BB_TSGS_TRANSPORT_STREAM:\n proto_tree_add_item(tree, hf_dvb_s2_bb_transport, tvb, cur_off + new_off, bb_data_len, ENC_NA);\n new_off += bb_data_len;\n break;\n\n default:\n proto_tree_add_item(tree, hf_dvb_s2_bb_reserved, tvb, cur_off + new_off,bb_data_len, ENC_NA);\n new_off += bb_data_len;\n expert_add_info(pinfo, ti, &ei_dvb_s2_bb_reserved);\n break;\n }\n\n return new_off;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'DVB-S2-BB: Prevent infinite loop\n\nCommit 4bf4ee88f0544727e7f89f3f288c6afd2f650a4c removed an else\nstatement that broke out of the BBFrame processing loop. Without\nit, infinite loops might be possible if the GSE frames have bit errors\nin the length field.\n\n\n(cherry picked from commit 0137c24d60934f131b25506a88c9464e4dc827de)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: os2_printer_fopen(gx_io_device * iodev, const char *fname, const char *access,\n FILE ** pfile, char *rfname, uint rnamelen)\n{\n os2_printer_t *pr = (os2_printer_t *)iodev->state;\n char driver_name[256];\n gs_lib_ctx_t *ctx = mem->gs_lib_ctx;\n gs_fs_list_t *fs = ctx->core->fs;\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 (out standard\n * file one). */\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, access, pfile);\n if (code < 0)\n return code;\n if (*pfile != NULL)\n return code;\n }\n\n /* If nothing claimed that, then continue with the\n * standard OS/2 way of working. */\n\n /* Make sure that printer exists. */\n if (pm_find_queue(pr->memory, fname, driver_name)) {\n /* error, list valid queue names */\n emprintf(pr->memory, \"Invalid queue name. Use one of:\\n\");\n pm_find_queue(pr->memory, NULL, NULL);\n return_error(gs_error_undefinedfilename);\n }\n\n strncpy(pr->queue, fname, sizeof(pr->queue)-1);\n\n /* Create a temporary file */\n *pfile = gp_open_scratch_file_impl(pr->memory, \"gs\", pr->filename, access, 0);\n if (*pfile == NULL)\n return_error(gs_fopen_errno_to_code(errno));\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\tsquashfs_dir_header_3 dirh;\n\tchar buffer[sizeof(squashfs_dir_entry_3) + SQUASHFS_NAME_LEN + 1]\n\t\t__attribute__((aligned));\n\tsquashfs_dir_entry_3 *dire = (squashfs_dir_entry_3 *) buffer;\n\tlong long start;\n\tint bytes = 0;\n\tint 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\tif(swap) {\n\t\t\tsquashfs_dir_header_3 sdirh;\n\t\t\tres = read_directory_data(&sdirh, &start, &offset, sizeof(sdirh));\n\t\t\tif(res)\n\t\t\t\tSQUASHFS_SWAP_DIR_HEADER_3(&dirh, &sdirh);\n\t\t} else\n\t\t\tres = read_directory_data(&dirh, &start, &offset, sizeof(dirh));\n\t\n\t\tif(res == FALSE)\n\t\t\tgoto corrupted;\n\n\t\tdir_count = dirh.count + 1;\n\t\tTRACE(\"squashfs_opendir: Read directory header @ byte position \"\n\t\t\t\"%d, %d directory entries\\n\", bytes, dir_count);\n\t\tbytes += sizeof(dirh);\n\n\t\t/* dir_count should never be larger than SQUASHFS_DIR_COUNT */\n\t\tif(dir_count > SQUASHFS_DIR_COUNT) {\n\t\t\tERROR(\"File system corrupted: too many entries in directory\\n\");\n\t\t\tgoto corrupted;\n\t\t}\n\n\t\twhile(dir_count--) {\n\t\t\tif(swap) {\n\t\t\t\tsquashfs_dir_entry_3 sdire;\n\t\t\t\tres = read_directory_data(&sdire, &start,\n\t\t\t\t\t&offset, sizeof(sdire));\n\t\t\t\tif(res)\n\t\t\t\t\tSQUASHFS_SWAP_DIR_ENTRY_3(dire, &sdire);\n\t\t\t} else\n\t\t\t\tres = read_directory_data(dire, &start,\n\t\t\t\t\t&offset, sizeof(*dire));\n\n\t\t\tif(res == FALSE)\n\t\t\t\tgoto corrupted;\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\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: int processCommand(client *c) {\n moduleCallCommandFilters(c);\n\n /* The QUIT command is handled separately. Normal command procs will\n * go through checking for replication and QUIT will cause trouble\n * when FORCE_REPLICATION is enabled and would be implemented in\n * a regular command proc. */\n if (!strcasecmp(c->argv[0]->ptr,\"quit\")) {\n addReply(c,shared.ok);\n c->flags |= CLIENT_CLOSE_AFTER_REPLY;\n return C_ERR;\n }\n\n /* Now lookup the command and check ASAP about trivial error conditions\n * such as wrong arity, bad command name and so forth. */\n c->cmd = c->lastcmd = lookupCommand(c->argv[0]->ptr);\n if (!c->cmd) {\n sds args = sdsempty();\n int i;\n for (i=1; i < c->argc && sdslen(args) < 128; i++)\n args = sdscatprintf(args, \"`%.*s`, \", 128-(int)sdslen(args), (char*)c->argv[i]->ptr);\n rejectCommandFormat(c,\"unknown command `%s`, with args beginning with: %s\",\n (char*)c->argv[0]->ptr, args);\n sdsfree(args);\n return C_OK;\n } else if ((c->cmd->arity > 0 && c->cmd->arity != c->argc) ||\n (c->argc < -c->cmd->arity)) {\n rejectCommandFormat(c,\"wrong number of arguments for '%s' command\",\n c->cmd->name);\n return C_OK;\n }\n\n int is_write_command = (c->cmd->flags & CMD_WRITE) ||\n (c->cmd->proc == execCommand && (c->mstate.cmd_flags & CMD_WRITE));\n int is_denyoom_command = (c->cmd->flags & CMD_DENYOOM) ||\n (c->cmd->proc == execCommand && (c->mstate.cmd_flags & CMD_DENYOOM));\n int is_denystale_command = !(c->cmd->flags & CMD_STALE) ||\n (c->cmd->proc == execCommand && (c->mstate.cmd_inv_flags & CMD_STALE));\n int is_denyloading_command = !(c->cmd->flags & CMD_LOADING) ||\n (c->cmd->proc == execCommand && (c->mstate.cmd_inv_flags & CMD_LOADING));\n\n /* Check if the user is authenticated. This check is skipped in case\n * the default user is flagged as \"nopass\" and is active. */\n int auth_required = (!(DefaultUser->flags & USER_FLAG_NOPASS) ||\n (DefaultUser->flags & USER_FLAG_DISABLED)) &&\n !c->authenticated;\n if (auth_required) {\n /* AUTH and HELLO and no auth modules are valid even in\n * non-authenticated state. */\n if (!(c->cmd->flags & CMD_NO_AUTH)) {\n rejectCommand(c,shared.noautherr);\n return C_OK;\n }\n }\n\n /* Check if the user can run this command according to the current\n * ACLs. */\n int acl_keypos;\n int acl_retval = ACLCheckCommandPerm(c,&acl_keypos);\n if (acl_retval != ACL_OK) {\n addACLLogEntry(c,acl_retval,acl_keypos,NULL);\n if (acl_retval == ACL_DENIED_CMD)\n rejectCommandFormat(c,\n \"-NOPERM this user has no permissions to run \"\n \"the '%s' command or its subcommand\", c->cmd->name);\n else\n rejectCommandFormat(c,\n \"-NOPERM this user has no permissions to access \"\n \"one of the keys used as arguments\");\n return C_OK;\n }\n\n /* If cluster is enabled perform the cluster redirection here.\n * However we don't perform the redirection if:\n * 1) The sender of this command is our master.\n * 2) The command has no key arguments. */\n if (server.cluster_enabled &&\n !(c->flags & CLIENT_MASTER) &&\n !(c->flags & CLIENT_LUA &&\n server.lua_caller->flags & CLIENT_MASTER) &&\n !(c->cmd->getkeys_proc == NULL && c->cmd->firstkey == 0 &&\n c->cmd->proc != execCommand))\n {\n int hashslot;\n int error_code;\n clusterNode *n = getNodeByQuery(c,c->cmd,c->argv,c->argc,\n &hashslot,&error_code);\n if (n == NULL || n != server.cluster->myself) {\n if (c->cmd->proc == execCommand) {\n discardTransaction(c);\n } else {\n flagTransaction(c);\n }\n clusterRedirectClient(c,n,hashslot,error_code);\n return C_OK;\n }\n }\n\n /* Handle the maxmemory directive.\n *\n * Note that we do not want to reclaim memory if we are here re-entering\n * the event loop since there is a busy Lua script running in timeout\n * condition, to avoid mixing the propagation of scripts with the\n * propagation of DELs due to eviction. */\n if (server.maxmemory && !server.lua_timedout) {\n int out_of_memory = freeMemoryIfNeededAndSafe() == C_ERR;\n /* freeMemoryIfNeeded may flush slave output buffers. This may result\n * into a slave, that may be the active client, to be freed. */\n if (server.current_client == NULL) return C_ERR;\n\n int reject_cmd_on_oom = is_denyoom_command;\n /* If client is in MULTI/EXEC context, queuing may consume an unlimited\n * amount of memory, so we want to stop that.\n * However, we never want to reject DISCARD, or even EXEC (unless it\n * contains denied commands, in which case is_denyoom_command is already\n * set. */\n if (c->flags & CLIENT_MULTI &&\n c->cmd->proc != execCommand &&\n c->cmd->proc != discardCommand) {\n reject_cmd_on_oom = 1;\n }\n\n if (out_of_memory && reject_cmd_on_oom) {\n rejectCommand(c, shared.oomerr);\n return C_OK;\n }\n\n /* Save out_of_memory result at script start, otherwise if we check OOM\n * until first write within script, memory used by lua stack and\n * arguments might interfere. */\n if (c->cmd->proc == evalCommand || c->cmd->proc == evalShaCommand) {\n server.lua_oom = out_of_memory;\n }\n }\n\n /* Make sure to use a reasonable amount of memory for client side\n * caching metadata. */\n if (server.tracking_clients) trackingLimitUsedSlots();\n\n /* Don't accept write commands if there are problems persisting on disk\n * and if this is a master instance. */\n int deny_write_type = writeCommandsDeniedByDiskError();\n if (deny_write_type != DISK_ERROR_TYPE_NONE &&\n server.masterhost == NULL &&\n (is_write_command ||c->cmd->proc == pingCommand))\n {\n if (deny_write_type == DISK_ERROR_TYPE_RDB)\n rejectCommand(c, shared.bgsaveerr);\n else\n rejectCommandFormat(c,\n \"-MISCONF Errors writing to the AOF file: %s\",\n strerror(server.aof_last_write_errno));\n return C_OK;\n }\n\n /* Don't accept write commands if there are not enough good slaves and\n * user configured the min-slaves-to-write option. */\n if (server.masterhost == NULL &&\n server.repl_min_slaves_to_write &&\n server.repl_min_slaves_max_lag &&\n is_write_command &&\n server.repl_good_slaves_count < server.repl_min_slaves_to_write)\n {\n rejectCommand(c, shared.noreplicaserr);\n return C_OK;\n }\n\n /* Don't accept write commands if this is a read only slave. But\n * accept write commands if this is our master. */\n if (server.masterhost && server.repl_slave_ro &&\n !(c->flags & CLIENT_MASTER) &&\n is_write_command)\n {\n rejectCommand(c, shared.roslaveerr);\n return C_OK;\n }\n\n /* Only allow a subset of commands in the context of Pub/Sub if the\n * connection is in RESP2 mode. With RESP3 there are no limits. */\n if ((c->flags & CLIENT_PUBSUB && c->resp == 2) &&\n c->cmd->proc != pingCommand &&\n c->cmd->proc != subscribeCommand &&\n c->cmd->proc != unsubscribeCommand &&\n c->cmd->proc != psubscribeCommand &&\n c->cmd->proc != punsubscribeCommand) {\n rejectCommandFormat(c,\n \"Can't execute '%s': only (P)SUBSCRIBE / \"\n \"(P)UNSUBSCRIBE / PING / QUIT are allowed in this context\",\n c->cmd->name);\n return C_OK;\n }\n\n /* Only allow commands with flag \"t\", such as INFO, SLAVEOF and so on,\n * when slave-serve-stale-data is no and we are a slave with a broken\n * link with master. */\n if (server.masterhost && server.repl_state != REPL_STATE_CONNECTED &&\n server.repl_serve_stale_data == 0 &&\n is_denystale_command)\n {\n rejectCommand(c, shared.masterdownerr);\n return C_OK;\n }\n\n /* Loading DB? Return an error if the command has not the\n * CMD_LOADING flag. */\n if (server.loading && is_denyloading_command) {\n rejectCommand(c, shared.loadingerr);\n return C_OK;\n }\n\n /* Lua script too slow? Only allow a limited number of commands.\n * Note that we need to allow the transactions commands, otherwise clients\n * sending a transaction with pipelining without error checking, may have\n * the MULTI plus a few initial commands refused, then the timeout\n * condition resolves, and the bottom-half of the transaction gets\n * executed, see Github PR #7022. */\n if (server.lua_timedout &&\n c->cmd->proc != authCommand &&\n c->cmd->proc != helloCommand &&\n c->cmd->proc != replconfCommand &&\n c->cmd->proc != multiCommand &&\n c->cmd->proc != discardCommand &&\n c->cmd->proc != watchCommand &&\n c->cmd->proc != unwatchCommand &&\n !(c->cmd->proc == shutdownCommand &&\n c->argc == 2 &&\n tolower(((char*)c->argv[1]->ptr)[0]) == 'n') &&\n !(c->cmd->proc == scriptCommand &&\n c->argc == 2 &&\n tolower(((char*)c->argv[1]->ptr)[0]) == 'k'))\n {\n rejectCommand(c, shared.slowscripterr);\n return C_OK;\n }\n\n /* Exec the command */\n if (c->flags & CLIENT_MULTI &&\n c->cmd->proc != execCommand && c->cmd->proc != discardCommand &&\n c->cmd->proc != multiCommand && c->cmd->proc != watchCommand)\n {\n queueMultiCommand(c);\n addReply(c,shared.queued);\n } else {\n call(c,CMD_CALL_FULL);\n c->woff = server.master_repl_offset;\n if (listLength(server.ready_keys))\n handleClientsBlockedOnKeys();\n }\n return C_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-770'], 'message': 'Prevent unauthenticated client from easily consuming lots of memory (CVE-2021-32675)\n\nThis change sets a low limit for multibulk and bulk length in the\nprotocol for unauthenticated connections, so that they can't easily\ncause redis to allocate massive amounts of memory by sending just a few\ncharacters on the network.\nThe new limits are 10 arguments of 16kb each (instead of 1m of 512mb)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void linsertCommand(client *c) {\n int where;\n robj *subject;\n listTypeIterator *iter;\n listTypeEntry entry;\n int inserted = 0;\n\n if (strcasecmp(c->argv[2]->ptr,\"after\") == 0) {\n where = LIST_TAIL;\n } else if (strcasecmp(c->argv[2]->ptr,\"before\") == 0) {\n where = LIST_HEAD;\n } else {\n addReply(c,shared.syntaxerr);\n return;\n }\n\n if ((subject = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||\n checkType(c,subject,OBJ_LIST)) return;\n\n /* Seek pivot from head to tail */\n iter = listTypeInitIterator(subject,0,LIST_TAIL);\n while (listTypeNext(iter,&entry)) {\n if (listTypeEqual(&entry,c->argv[3])) {\n listTypeInsert(&entry,c->argv[4],where);\n inserted = 1;\n break;\n }\n }\n listTypeReleaseIterator(iter);\n\n if (inserted) {\n signalModifiedKey(c,c->db,c->argv[1]);\n notifyKeyspaceEvent(NOTIFY_LIST,\"linsert\",\n c->argv[1],c->db->id);\n server.dirty++;\n } else {\n /* Notify client of a failed insert */\n addReplyLongLong(c,-1);\n return;\n }\n\n addReplyLongLong(c,listTypeLength(subject));\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: REDIS_STATIC int _quicklistNodeAllowMerge(const quicklistNode *a,\n const quicklistNode *b,\n const int fill) {\n if (!a || !b)\n return 0;\n\n /* approximate merged ziplist size (- 11 to remove one ziplist\n * header/trailer) */\n unsigned int merge_sz = a->sz + b->sz - 11;\n if (likely(_quicklistNodeSizeMeetsOptimizationRequirement(merge_sz, fill)))\n return 1;\n else if (!sizeMeetsSafetyLimit(merge_sz))\n return 0;\n else if ((int)(a->count + b->count) <= fill)\n return 1;\n else\n return 0;\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: MOBI_RET mobi_parse_huffdic(const MOBIData *m, MOBIHuffCdic *huffcdic) {\n MOBI_RET ret;\n const size_t offset = mobi_get_kf8offset(m);\n if (m->mh == NULL || m->mh->huff_rec_index == NULL || m->mh->huff_rec_count == NULL) {\n debug_print(\"%s\", \"HUFF/CDIC records metadata not found in MOBI header\\n\");\n return MOBI_DATA_CORRUPT;\n }\n const size_t huff_rec_index = *m->mh->huff_rec_index + offset;\n const size_t huff_rec_count = *m->mh->huff_rec_count;\n if (huff_rec_count > HUFF_RECORD_MAXCNT) {\n debug_print(\"Too many HUFF record (%zu)\\n\", huff_rec_count);\n return MOBI_DATA_CORRUPT;\n }\n const MOBIPdbRecord *curr = mobi_get_record_by_seqnumber(m, huff_rec_index);\n if (curr == NULL || huff_rec_count < 2) {\n debug_print(\"%s\", \"HUFF/CDIC record not found\\n\");\n return MOBI_DATA_CORRUPT;\n }\n if (curr->size < HUFF_RECORD_MINSIZE) {\n debug_print(\"HUFF record too short (%zu b)\\n\", curr->size);\n return MOBI_DATA_CORRUPT;\n }\n ret = mobi_parse_huff(huffcdic, curr);\n if (ret != MOBI_SUCCESS) {\n debug_print(\"%s\", \"HUFF parsing failed\\n\");\n return ret;\n }\n curr = curr->next;\n /* allocate memory for symbols data in each CDIC record */\n huffcdic->symbols = malloc((huff_rec_count - 1) * sizeof(*huffcdic->symbols));\n if (huffcdic->symbols == NULL) {\n debug_print(\"%s\\n\", \"Memory allocation failed\");\n return MOBI_MALLOC_FAILED;\n }\n /* get following CDIC records */\n size_t i = 0;\n while (i < huff_rec_count - 1) {\n if (curr == NULL) {\n debug_print(\"%s\\n\", \"CDIC record not found\");\n return MOBI_DATA_CORRUPT;\n }\n ret = mobi_parse_cdic(huffcdic, curr, i++);\n if (ret != MOBI_SUCCESS) {\n debug_print(\"%s\", \"CDIC parsing failed\\n\");\n return ret;\n }\n curr = curr->next;\n }\n return MOBI_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix potential out-of-buffer read while parsing corrupt file, closes #38'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void fpm_scoreboard_proc_free(struct fpm_scoreboard_s *scoreboard, int child_index) /* {{{ */\n{\n\tif (!scoreboard) {\n\t\treturn;\n\t}\n\n\tif (child_index < 0 || (unsigned int)child_index >= scoreboard->nprocs) {\n\t\treturn;\n\t}\n\n\tif (scoreboard->procs[child_index] && scoreboard->procs[child_index]->used > 0) {\n\t\tmemset(scoreboard->procs[child_index], 0, sizeof(struct fpm_scoreboard_proc_s));\n\t}\n\n\t/* set this slot as free to avoid search on next alloc */\n\tscoreboard->free_proc = child_index;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix bug #81026 (PHP-FPM oob R/W in root process leading to priv escalation)\n\nThe main change is to store scoreboard procs directly to the variable sized\narray rather than indirectly through the pointer.\n\nSigned-off-by: Stanislav Malyshev '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int readOHDRHeaderMessageDataLayout(struct READER *reader,\n struct DATAOBJECT *data) {\n\n int i, err;\n unsigned size;\n\n uint8_t dimensionality, layout_class;\n uint32_t dataset_element_size;\n uint64_t data_address, store, data_size;\n\n UNUSED(dataset_element_size);\n UNUSED(data_size);\n\n if (fgetc(reader->fhd) != 3) {\n // LCOV_EXCL_START\n mylog(\"object OHDR message data layout message must have version 3\\n\");\n return MYSOFA_INVALID_FORMAT;\n // LCOV_EXCL_STOP\n }\n\n layout_class = (uint8_t)fgetc(reader->fhd);\n mylog(\"data layout %d\\n\", layout_class);\n\n switch (layout_class) {\n#if 0\n\tcase 0:\n\tdata_size = readValue(reader, 2);\n\tfseek(reader->fhd, data_size, SEEK_CUR);\n\tmylog(\"TODO 0 SIZE %u\\n\", data_size);\n\tbreak;\n#endif\n case 1:\n data_address = readValue(reader, reader->superblock.size_of_offsets);\n data_size = readValue(reader, reader->superblock.size_of_lengths);\n mylog(\"CHUNK Contiguous SIZE %\" PRIu64 \"\\n\", data_size);\n\n if (validAddress(reader, data_address)) {\n store = ftell(reader->fhd);\n if (fseek(reader->fhd, data_address, SEEK_SET) < 0)\n return errno; // LCOV_EXCL_LINE\n if (!data->data) {\n if (data_size > 0x10000000)\n return MYSOFA_INVALID_FORMAT;\n data->data_len = data_size;\n data->data = calloc(1, data_size);\n if (!data->data)\n return MYSOFA_NO_MEMORY; // LCOV_EXCL_LINE\n }\n err = fread(data->data, 1, data_size, reader->fhd);\n if (err != data_size)\n return MYSOFA_READ_ERROR; // LCOV_EXCL_LINE\n if (fseek(reader->fhd, store, SEEK_SET) < 0)\n return errno; // LCOV_EXCL_LINE\n }\n break;\n\n case 2:\n dimensionality = (uint8_t)fgetc(reader->fhd);\n mylog(\"dimensionality %d\\n\", dimensionality);\n\n if (dimensionality < 1 || dimensionality > DATAOBJECT_MAX_DIMENSIONALITY) {\n mylog(\"data layout 2: invalid dimensionality %d %lu %lu\\n\",\n dimensionality, sizeof(data->datalayout_chunk),\n sizeof(data->datalayout_chunk[0]));\n return MYSOFA_INVALID_FORMAT; // LCOV_EXCL_LINE\n }\n data_address = readValue(reader, reader->superblock.size_of_offsets);\n mylog(\" CHUNK %\" PRIX64 \"\\n\", data_address);\n for (i = 0; i < dimensionality; i++) {\n data->datalayout_chunk[i] = readValue(reader, 4);\n mylog(\" %d\\n\", data->datalayout_chunk[i]);\n }\n /* TODO last entry? error in spec: ?*/\n\n size = data->datalayout_chunk[dimensionality - 1];\n for (i = 0; i < data->ds.dimensionality; i++)\n size *= data->ds.dimension_size[i];\n\n if (validAddress(reader, data_address) && dimensionality <= 4) {\n store = ftell(reader->fhd);\n if (fseek(reader->fhd, data_address, SEEK_SET) < 0)\n return errno; // LCOV_EXCL_LINE\n if (!data->data) {\n if (size > 0x10000000)\n return MYSOFA_INVALID_FORMAT; // LCOV_EXCL_LINE\n data->data_len = size;\n data->data = calloc(1, size);\n if (!data->data)\n return MYSOFA_NO_MEMORY; // LCOV_EXCL_LINE\n }\n err = treeRead(reader, data);\n if (err)\n return err; // LCOV_EXCL_LINE\n if (fseek(reader->fhd, store, SEEK_SET) < 0)\n return errno; // LCOV_EXCL_LINE\n }\n break;\n\n default:\n // LCOV_EXCL_START\n mylog(\"object OHDR message data layout message has unknown layout class \"\n \"%d\\n\",\n layout_class);\n return MYSOFA_INVALID_FORMAT;\n // LCOV_EXCL_STOP\n }\n\n return MYSOFA_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix for issue 163'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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 pending_op *send_read(struct btd_device *device,\n\t\t\t\t\tstruct gatt_db_attribute *attrib,\n\t\t\t\t\tGDBusProxy *proxy,\n\t\t\t\t\tstruct queue *owner_queue,\n\t\t\t\t\tunsigned int id,\n\t\t\t\t\tuint16_t offset,\n\t\t\t\t\tuint8_t link_type)\n{\n\tstruct pending_op *op;\n\n\top = pending_read_new(device, owner_queue, attrib, id, offset,\n\t\t\t\t\t\t\tlink_type);\n\n\tif (g_dbus_proxy_method_call(proxy, \"ReadValue\", read_setup_cb,\n\t\t\t\tread_reply_cb, op, pending_op_free) == TRUE)\n\t\treturn op;\n\n\tpending_op_free(op);\n\n\treturn NULL;\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: ex_put(exarg_T *eap)\n{\n // \":0put\" works like \":1put!\".\n if (eap->line2 == 0)\n {\n\teap->line2 = 1;\n\teap->forceit = TRUE;\n }\n curwin->w_cursor.lnum = eap->line2;\n do_put(eap->regname, NULL, eap->forceit ? BACKWARD : FORWARD, 1L,\n\t\t\t\t\t\t PUT_LINE|PUT_CURSLINE);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-122'], 'message': 'patch 8.2.3581: reading character past end of line\n\nProblem: Reading character past end of line.\nSolution: Correct the cursor column.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,\n mode_t mode, unsigned long set, unsigned long clear)\n{\n\tint r;\n\tconst int sf_mask = 0\n#ifdef SF_APPEND\n\t | SF_APPEND\n#endif\n#ifdef SF_ARCHIVED\n\t | SF_ARCHIVED\n#endif\n#ifdef SF_IMMUTABLE\n\t | SF_IMMUTABLE\n#endif\n#ifdef SF_NOUNLINK\n\t | SF_NOUNLINK\n#endif\n\t;\n\t(void)mode; /* UNUSED */\n\n\tif (set == 0 && clear == 0)\n\t\treturn (ARCHIVE_OK);\n\n\t/*\n\t * XXX Is the stat here really necessary? Or can I just use\n\t * the 'set' flags directly? In particular, I'm not sure\n\t * about the correct approach if we're overwriting an existing\n\t * file that already has flags on it. XXX\n\t */\n\tif ((r = lazy_stat(a)) != ARCHIVE_OK)\n\t\treturn (r);\n\n\ta->st.st_flags &= ~clear;\n\ta->st.st_flags |= set;\n\n\t/* Only super-user may change SF_* flags */\n\n\tif (a->user_uid != 0)\n\t\ta->st.st_flags &= ~sf_mask;\n\n#ifdef HAVE_FCHFLAGS\n\t/* If platform has fchflags() and we were given an fd, use it. */\n\tif (fd >= 0 && fchflags(fd, a->st.st_flags) == 0)\n\t\treturn (ARCHIVE_OK);\n#endif\n\t/*\n\t * If we can't use the fd to set the flags, we'll use the\n\t * pathname to set flags. We prefer lchflags() but will use\n\t * chflags() if we must.\n\t */\n#ifdef HAVE_LCHFLAGS\n\tif (lchflags(name, a->st.st_flags) == 0)\n\t\treturn (ARCHIVE_OK);\n#elif defined(HAVE_CHFLAGS)\n\tif (S_ISLNK(a->st.st_mode)) {\n\t\tarchive_set_error(&a->archive, errno,\n\t\t \"Can't set file flags on symlink.\");\n\t\treturn (ARCHIVE_WARN);\n\t}\n\tif (chflags(name, a->st.st_flags) == 0)\n\t\treturn (ARCHIVE_OK);\n#endif\n\tarchive_set_error(&a->archive, errno,\n\t \"Failed to set file flags\");\n\treturn (ARCHIVE_WARN);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59'], 'message': 'Never follow symlinks when setting file flags on Linux\n\nWhen opening a file descriptor to set file flags on linux, ensure\nno symbolic links are followed. This fixes the case when an archive\ncontains a directory entry followed by a symlink entry with the same\npath. The fixup code would modify file flags of the symlink target.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: set_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\tacl_t\t\t acl;\n\tacl_entry_t\t acl_entry;\n\tacl_permset_t\t acl_permset;\n#if ARCHIVE_ACL_FREEBSD_NFS4\n\tacl_flagset_t\t acl_flagset;\n\tint\t\t r;\n#endif\n\tint\t\t ret;\n\tint\t\t ae_type, ae_permset, ae_tag, ae_id;\n\tint\t\t perm_map_size;\n\tconst acl_perm_map_t\t*perm_map;\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\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\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#if ARCHIVE_ACL_FREEBSD_NFS4\n\tcase ARCHIVE_ENTRY_ACL_TYPE_NFS4:\n\t\tacl_type = ACL_TYPE_NFS4;\n\t\tbreak;\n#endif\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\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\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#if ARCHIVE_ACL_FREEBSD_NFS4\n\t\tcase ARCHIVE_ENTRY_ACL_EVERYONE:\n\t\t\tacl_set_tag_type(acl_entry, ACL_EVERYONE);\n\t\t\tbreak;\n#endif\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#if ARCHIVE_ACL_FREEBSD_NFS4\n\t\tr = 0;\n\t\tswitch (ae_type) {\n\t\tcase ARCHIVE_ENTRY_ACL_TYPE_ALLOW:\n\t\t\tr = acl_set_entry_type_np(acl_entry,\n\t\t\t ACL_ENTRY_TYPE_ALLOW);\n\t\t\tbreak;\n\t\tcase ARCHIVE_ENTRY_ACL_TYPE_DENY:\n\t\t\tr = acl_set_entry_type_np(acl_entry,\n\t\t\t ACL_ENTRY_TYPE_DENY);\n\t\t\tbreak;\n\t\tcase ARCHIVE_ENTRY_ACL_TYPE_AUDIT:\n\t\t\tr = acl_set_entry_type_np(acl_entry,\n\t\t\t ACL_ENTRY_TYPE_AUDIT);\n\t\t\tbreak;\n\t\tcase ARCHIVE_ENTRY_ACL_TYPE_ALARM:\n\t\t\tr = acl_set_entry_type_np(acl_entry,\n\t\t\t ACL_ENTRY_TYPE_ALARM);\n\t\t\tbreak;\n\t\tcase ARCHIVE_ENTRY_ACL_TYPE_ACCESS:\n\t\tcase ARCHIVE_ENTRY_ACL_TYPE_DEFAULT:\n\t\t\t// These don't translate directly into the system ACL.\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tarchive_set_error(a, ARCHIVE_ERRNO_MISC,\n\t\t\t \"Unsupported ACL entry type\");\n\t\t\tret = ARCHIVE_FAILED;\n\t\t\tgoto exit_free;\n\t\t}\n\n\t\tif (r != 0) {\n\t\t\tarchive_set_error(a, errno,\n\t\t\t \"Failed to set ACL entry type\");\n\t\t\tret = ARCHIVE_FAILED;\n\t\t\tgoto exit_free;\n\t\t}\n#endif\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#if ARCHIVE_ACL_FREEBSD_NFS4\n\t\tif (ae_requested_type == ARCHIVE_ENTRY_ACL_TYPE_NFS4) {\n\t\t\tperm_map_size = acl_nfs4_perm_map_size;\n\t\t\tperm_map = acl_nfs4_perm_map;\n\t\t} else {\n#endif\n\t\t\tperm_map_size = acl_posix_perm_map_size;\n\t\t\tperm_map = acl_posix_perm_map;\n#if ARCHIVE_ACL_FREEBSD_NFS4\n\t\t}\n#endif\n\n\t\tfor (i = 0; i < perm_map_size; ++i) {\n\t\t\tif (ae_permset & perm_map[i].a_perm) {\n\t\t\t\tif (acl_add_perm(acl_permset,\n\t\t\t\t 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#if ARCHIVE_ACL_FREEBSD_NFS4\n\t\tif (ae_requested_type == ARCHIVE_ENTRY_ACL_TYPE_NFS4) {\n\t\t\t/*\n\t\t\t * acl_get_flagset_np() fails with non-NFSv4 ACLs\n\t\t\t */\n\t\t\tif (acl_get_flagset_np(acl_entry, &acl_flagset) != 0) {\n\t\t\t\tarchive_set_error(a, errno,\n\t\t\t\t \"Failed to get flagset from an NFSv4 \"\n\t\t\t\t \"ACL entry\");\n\t\t\t\tret = ARCHIVE_FAILED;\n\t\t\t\tgoto exit_free;\n\t\t\t}\n\t\t\tif (acl_clear_flags_np(acl_flagset) != 0) {\n\t\t\t\tarchive_set_error(a, errno,\n\t\t\t\t \"Failed to clear flags from an NFSv4 \"\n\t\t\t\t \"ACL flagset\");\n\t\t\t\tret = ARCHIVE_FAILED;\n\t\t\t\tgoto exit_free;\n\t\t\t}\n\t\t\tfor (i = 0; i < acl_nfs4_flag_map_size; ++i) {\n\t\t\t\tif (ae_permset & acl_nfs4_flag_map[i].a_perm) {\n\t\t\t\t\tif (acl_add_flag_np(acl_flagset,\n\t\t\t\t\t acl_nfs4_flag_map[i].p_perm) != 0) {\n\t\t\t\t\t\tarchive_set_error(a, errno,\n\t\t\t\t\t\t \"Failed to add flag to \"\n\t\t\t\t\t\t \"NFSv4 ACL flagset\");\n\t\t\t\t\t\tret = ARCHIVE_FAILED;\n\t\t\t\t\t\tgoto exit_free;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n#endif\n\t}\n\n\t/* Try restoring the ACL through 'fd' if we can. */\n\tif (fd >= 0) {\n\t\tif (acl_set_fd_np(fd, acl, acl_type) == 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}\n#if HAVE_ACL_SET_LINK_NP\n\telse if (acl_set_link_np(name, acl_type, acl) != 0)\n#else\n\t/* FreeBSD older than 8.0 */\n\telse if (acl_set_file(name, acl_type, acl) != 0)\n#endif\n\t{\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: int mnt_fs_is_deleted(struct libmnt_fs *fs)\n{\n\treturn mnt_fs_get_flags(fs) & MNT_FS_DELETED;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-552', 'CWE-703'], 'message': 'libmount: remove support for deleted mount table entries\n\nThe \"(deleted)\" suffix has been originally used by kernel for deleted\nmountpoints. Since kernel commit 9d4d65748a5ca26ea8650e50ba521295549bf4e3\n(Dec 2014) kernel does not use this suffix for mount stuff in /proc at\nall. Let's remove this support from libmount too.\n\nSigned-off-by: Karel Zak '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: find_file_in_path_option(\n char_u\t*ptr,\t\t// file name\n int\t\tlen,\t\t// length of file name\n int\t\toptions,\n int\t\tfirst,\t\t// use count'th matching file name\n char_u\t*path_option,\t// p_path or p_cdpath\n int\t\tfind_what,\t// FINDFILE_FILE, _DIR or _BOTH\n char_u\t*rel_fname,\t// file name we are looking relative to.\n char_u\t*suffixes)\t// list of suffixes, 'suffixesadd' option\n{\n static char_u\t*dir;\n static int\t\tdid_findfile_init = FALSE;\n char_u\t\tsave_char;\n char_u\t\t*file_name = NULL;\n char_u\t\t*buf = NULL;\n int\t\t\trel_to_curdir;\n# ifdef AMIGA\n struct Process\t*proc = (struct Process *)FindTask(0L);\n APTR\t\tsave_winptr = proc->pr_WindowPtr;\n\n // Avoid a requester here for a volume that doesn't exist.\n proc->pr_WindowPtr = (APTR)-1L;\n# endif\n\n if (first == TRUE)\n {\n\t// copy file name into NameBuff, expanding environment variables\n\tsave_char = ptr[len];\n\tptr[len] = NUL;\n\texpand_env_esc(ptr, NameBuff, MAXPATHL, FALSE, TRUE, NULL);\n\tptr[len] = save_char;\n\n\tvim_free(ff_file_to_find);\n\tff_file_to_find = vim_strsave(NameBuff);\n\tif (ff_file_to_find == NULL)\t// out of memory\n\t{\n\t file_name = NULL;\n\t goto theend;\n\t}\n\tif (options & FNAME_UNESC)\n\t{\n\t // Change all \"\\ \" to \" \".\n\t for (ptr = ff_file_to_find; *ptr != NUL; ++ptr)\n\t\tif (ptr[0] == '\\\\' && ptr[1] == ' ')\n\t\t mch_memmove(ptr, ptr + 1, STRLEN(ptr));\n\t}\n }\n\n rel_to_curdir = (ff_file_to_find[0] == '.'\n\t\t && (ff_file_to_find[1] == NUL\n\t\t\t|| vim_ispathsep(ff_file_to_find[1])\n\t\t\t|| (ff_file_to_find[1] == '.'\n\t\t\t && (ff_file_to_find[2] == NUL\n\t\t\t\t|| vim_ispathsep(ff_file_to_find[2])))));\n if (vim_isAbsName(ff_file_to_find)\n\t // \"..\", \"../path\", \".\" and \"./path\": don't use the path_option\n\t || rel_to_curdir\n# if defined(MSWIN)\n\t // handle \"\\tmp\" as absolute path\n\t || vim_ispathsep(ff_file_to_find[0])\n\t // handle \"c:name\" as absolute path\n\t || (ff_file_to_find[0] != NUL && ff_file_to_find[1] == ':')\n# endif\n# ifdef AMIGA\n\t // handle \":tmp\" as absolute path\n\t || ff_file_to_find[0] == ':'\n# endif\n )\n {\n\t/*\n\t * Absolute path, no need to use \"path_option\".\n\t * If this is not a first call, return NULL. We already returned a\n\t * filename on the first call.\n\t */\n\tif (first == TRUE)\n\t{\n\t int\t\tl;\n\t int\t\trun;\n\n\t if (path_with_url(ff_file_to_find))\n\t {\n\t\tfile_name = vim_strsave(ff_file_to_find);\n\t\tgoto theend;\n\t }\n\n\t // When FNAME_REL flag given first use the directory of the file.\n\t // Otherwise or when this fails use the current directory.\n\t for (run = 1; run <= 2; ++run)\n\t {\n\t\tl = (int)STRLEN(ff_file_to_find);\n\t\tif (run == 1\n\t\t\t&& rel_to_curdir\n\t\t\t&& (options & FNAME_REL)\n\t\t\t&& rel_fname != NULL\n\t\t\t&& STRLEN(rel_fname) + l < MAXPATHL)\n\t\t{\n\t\t STRCPY(NameBuff, rel_fname);\n\t\t STRCPY(gettail(NameBuff), ff_file_to_find);\n\t\t l = (int)STRLEN(NameBuff);\n\t\t}\n\t\telse\n\t\t{\n\t\t STRCPY(NameBuff, ff_file_to_find);\n\t\t run = 2;\n\t\t}\n\n\t\t// When the file doesn't exist, try adding parts of\n\t\t// 'suffixesadd'.\n\t\tbuf = suffixes;\n\t\tfor (;;)\n\t\t{\n\t\t if (mch_getperm(NameBuff) >= 0\n\t\t\t && (find_what == FINDFILE_BOTH\n\t\t\t\t || ((find_what == FINDFILE_DIR)\n\t\t\t\t\t\t == mch_isdir(NameBuff))))\n\t\t {\n\t\t\tfile_name = vim_strsave(NameBuff);\n\t\t\tgoto theend;\n\t\t }\n\t\t if (*buf == NUL)\n\t\t\tbreak;\n\t\t copy_option_part(&buf, NameBuff + l, MAXPATHL - l, \",\");\n\t\t}\n\t }\n\t}\n }\n else\n {\n\t/*\n\t * Loop over all paths in the 'path' or 'cdpath' option.\n\t * When \"first\" is set, first setup to the start of the option.\n\t * Otherwise continue to find the next match.\n\t */\n\tif (first == TRUE)\n\t{\n\t // vim_findfile_free_visited can handle a possible NULL pointer\n\t vim_findfile_free_visited(fdip_search_ctx);\n\t dir = path_option;\n\t did_findfile_init = FALSE;\n\t}\n\n\tfor (;;)\n\t{\n\t if (did_findfile_init)\n\t {\n\t\tfile_name = vim_findfile(fdip_search_ctx);\n\t\tif (file_name != NULL)\n\t\t break;\n\n\t\tdid_findfile_init = FALSE;\n\t }\n\t else\n\t {\n\t\tchar_u *r_ptr;\n\n\t\tif (dir == NULL || *dir == NUL)\n\t\t{\n\t\t // We searched all paths of the option, now we can\n\t\t // free the search context.\n\t\t vim_findfile_cleanup(fdip_search_ctx);\n\t\t fdip_search_ctx = NULL;\n\t\t break;\n\t\t}\n\n\t\tif ((buf = alloc(MAXPATHL)) == NULL)\n\t\t break;\n\n\t\t// copy next path\n\t\tbuf[0] = 0;\n\t\tcopy_option_part(&dir, buf, MAXPATHL, \" ,\");\n\n# ifdef FEAT_PATH_EXTRA\n\t\t// get the stopdir string\n\t\tr_ptr = vim_findfile_stopdir(buf);\n# else\n\t\tr_ptr = NULL;\n# endif\n\t\tfdip_search_ctx = vim_findfile_init(buf, ff_file_to_find,\n\t\t\t\t\t r_ptr, 100, FALSE, find_what,\n\t\t\t\t\t fdip_search_ctx, FALSE, rel_fname);\n\t\tif (fdip_search_ctx != NULL)\n\t\t did_findfile_init = TRUE;\n\t\tvim_free(buf);\n\t }\n\t}\n }\n if (file_name == NULL && (options & FNAME_MESS))\n {\n\tif (first == TRUE)\n\t{\n\t if (find_what == FINDFILE_DIR)\n\t\tsemsg(_(\"E344: Can't find directory \\\"%s\\\" in cdpath\"),\n\t\t\tff_file_to_find);\n\t else\n\t\tsemsg(_(\"E345: Can't find file \\\"%s\\\" in path\"),\n\t\t\tff_file_to_find);\n\t}\n\telse\n\t{\n\t if (find_what == FINDFILE_DIR)\n\t\tsemsg(_(\"E346: No more directory \\\"%s\\\" found in cdpath\"),\n\t\t\tff_file_to_find);\n\t else\n\t\tsemsg(_(\"E347: No more file \\\"%s\\\" found in path\"),\n\t\t\tff_file_to_find);\n\t}\n }\n\ntheend:\n# ifdef AMIGA\n proc->pr_WindowPtr = save_winptr;\n# endif\n return file_name;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-122'], 'message': 'patch 8.2.3611: crash when using CTRL-W f without finding a file name\n\nProblem: Crash when using CTRL-W f without finding a file name.\nSolution: Bail out when the file name length is zero.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int bpf_map_mmap(struct file *filp, struct vm_area_struct *vma)\n{\n\tstruct bpf_map *map = filp->private_data;\n\tint err;\n\n\tif (!map->ops->map_mmap || map_value_has_spin_lock(map) ||\n\t map_value_has_timer(map))\n\t\treturn -ENOTSUPP;\n\n\tif (!(vma->vm_flags & VM_SHARED))\n\t\treturn -EINVAL;\n\n\tmutex_lock(&map->freeze_mutex);\n\n\tif (vma->vm_flags & VM_WRITE) {\n\t\tif (map->frozen) {\n\t\t\terr = -EPERM;\n\t\t\tgoto out;\n\t\t}\n\t\t/* map is meant to be read-only, so do not allow mapping as\n\t\t * writable, because it's possible to leak a writable page\n\t\t * reference and allows user-space to still modify it after\n\t\t * freezing, while verifier will assume contents do not change\n\t\t */\n\t\tif (map->map_flags & BPF_F_RDONLY_PROG) {\n\t\t\terr = -EACCES;\n\t\t\tgoto out;\n\t\t}\n\t}\n\n\t/* set default open/close callbacks */\n\tvma->vm_ops = &bpf_map_default_vmops;\n\tvma->vm_private_data = map;\n\tvma->vm_flags &= ~VM_MAYEXEC;\n\tif (!(vma->vm_flags & VM_WRITE))\n\t\t/* disallow re-mapping with PROT_WRITE */\n\t\tvma->vm_flags &= ~VM_MAYWRITE;\n\n\terr = map->ops->map_mmap(map, vma);\n\tif (err)\n\t\tgoto out;\n\n\tif (vma->vm_flags & VM_MAYWRITE)\n\t\tmap->writecnt++;\nout:\n\tmutex_unlock(&map->freeze_mutex);\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: static int ep_loop_check_proc(void *priv, void *cookie, int call_nests)\n{\n\tint error = 0;\n\tstruct file *file = priv;\n\tstruct eventpoll *ep = file->private_data;\n\tstruct eventpoll *ep_tovisit;\n\tstruct rb_node *rbp;\n\tstruct epitem *epi;\n\n\tmutex_lock_nested(&ep->mtx, call_nests + 1);\n\tep->visited = 1;\n\tlist_add(&ep->visited_list_link, &visited_list);\n\tfor (rbp = rb_first_cached(&ep->rbr); rbp; rbp = rb_next(rbp)) {\n\t\tepi = rb_entry(rbp, struct epitem, rbn);\n\t\tif (unlikely(is_file_epoll(epi->ffd.file))) {\n\t\t\tep_tovisit = epi->ffd.file->private_data;\n\t\t\tif (ep_tovisit->visited)\n\t\t\t\tcontinue;\n\t\t\terror = ep_call_nested(&poll_loop_ncalls,\n\t\t\t\t\tep_loop_check_proc, epi->ffd.file,\n\t\t\t\t\tep_tovisit, current);\n\t\t\tif (error != 0)\n\t\t\t\tbreak;\n\t\t} else {\n\t\t\t/*\n\t\t\t * If we've reached a file that is not associated with\n\t\t\t * an ep, then we need to check if the newly added\n\t\t\t * links are going to add too many wakeup paths. We do\n\t\t\t * this by adding it to the tfile_check_list, if it's\n\t\t\t * not already there, and calling reverse_path_check()\n\t\t\t * during ep_insert().\n\t\t\t */\n\t\t\tif (list_empty(&epi->ffd.file->f_tfile_llink)) {\n\t\t\t\tget_file(epi->ffd.file);\n\t\t\t\tlist_add(&epi->ffd.file->f_tfile_llink,\n\t\t\t\t\t &tfile_check_list);\n\t\t\t}\n\t\t}\n\t}\n\tmutex_unlock(&ep->mtx);\n\n\treturn error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'fix regression in \"epoll: Keep a reference on files added to the check list\"\n\nepoll_loop_check_proc() can run into a file already committed to destruction;\nwe can't grab a reference on those and don't need to add them to the set for\nreverse path check anyway.\n\nTested-by: Marc Zyngier \nFixes: a9ed4a6560b8 (\"epoll: Keep a reference on files added to the check list\")\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 reencrypt_recovery(struct crypt_device *cd,\n\t\tstruct luks2_hdr *hdr,\n\t\tuint64_t device_size,\n\t\tstruct volume_key *vks)\n{\n\tint r;\n\tstruct luks2_reencrypt *rh = NULL;\n\n\tr = reencrypt_load(cd, hdr, device_size, NULL, &rh);\n\tif (r < 0) {\n\t\tlog_err(cd, _(\"Failed to load LUKS2 reencryption context.\"));\n\t\treturn r;\n\t}\n\n\tr = reencrypt_recover_segment(cd, hdr, rh, vks);\n\tif (r < 0)\n\t\tgoto out;\n\n\tif ((r = reencrypt_assign_segments(cd, hdr, rh, 0, 0)))\n\t\tgoto out;\n\n\tr = reencrypt_context_update(cd, rh);\n\tif (r) {\n\t\tlog_err(cd, _(\"Failed to update reencryption context.\"));\n\t\tgoto out;\n\t}\n\n\tr = reencrypt_teardown_ok(cd, hdr, rh);\n\tif (!r)\n\t\tr = LUKS2_hdr_write(cd, hdr);\nout:\n\tLUKS2_reencrypt_free(cd, rh);\n\n\treturn r;\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: libxlDomainDestroyInternal(libxlDriverPrivate *driver,\n virDomainObj *vm)\n{\n g_autoptr(libxlDriverConfig) cfg = libxlDriverConfigGet(driver);\n libxlDomainObjPrivate *priv = vm->privateData;\n int ret = -1;\n\n /* Ignore next LIBXL_EVENT_TYPE_DOMAIN_DEATH as the caller will handle\n * domain death appropriately already (having more info, like the reason).\n */\n priv->ignoreDeathEvent = true;\n /* Unlock virDomainObj during destroy, which can take considerable\n * time on large memory domains.\n */\n virObjectUnlock(vm);\n ret = libxl_domain_destroy(cfg->ctx, vm->def->id, NULL);\n virObjectLock(vm);\n if (ret)\n priv->ignoreDeathEvent = false;\n\n return ret;\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: 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 struct libxlEventHandlerThreadInfo *thread_info = NULL;\n virThread thread;\n g_autofree char *thread_name = 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 /*\n * Start event-specific threads to handle shutdown and death.\n * They are potentially lengthy operations and we don't want to be\n * blocking this event handler while they are in progress.\n */\n if (event->type == LIBXL_EVENT_TYPE_DOMAIN_SHUTDOWN) {\n thread_info = g_new0(struct libxlEventHandlerThreadInfo, 1);\n\n thread_info->driver = driver;\n thread_info->vm = vm;\n thread_info->event = (libxl_event *)event;\n thread_name = g_strdup_printf(\"shutdown-event-%d\", event->domid);\n /*\n * Cleanup will be handled by the shutdown thread.\n */\n if (virThreadCreateFull(&thread, false, libxlDomainShutdownThread,\n thread_name, false, thread_info) < 0) {\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 goto cleanup;\n }\n /*\n * virDomainObjEndAPI is called in the shutdown thread, where\n * libxlEventHandlerThreadInfo and libxl_event are also freed.\n */\n return;\n } else if (event->type == LIBXL_EVENT_TYPE_DOMAIN_DEATH) {\n thread_info = g_new0(struct libxlEventHandlerThreadInfo, 1);\n\n thread_info->driver = driver;\n thread_info->vm = vm;\n thread_info->event = (libxl_event *)event;\n thread_name = g_strdup_printf(\"death-event-%d\", event->domid);\n /*\n * Cleanup will be handled by the death thread.\n */\n if (virThreadCreateFull(&thread, false, libxlDomainDeathThread,\n thread_name, false, thread_info) < 0) {\n /*\n * Not much we can do on error here except log it.\n */\n VIR_ERROR(_(\"Failed to create thread to handle domain death\"));\n goto cleanup;\n }\n /*\n * virDomainObjEndAPI is called in the death thread, where\n * libxlEventHandlerThreadInfo and libxl_event are also freed.\n */\n return;\n }\n\n cleanup:\n virDomainObjEndAPI(&vm);\n VIR_FREE(thread_info);\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-703', 'CWE-667'], 'message': 'libxl: Search for virDomainObj in event handler threads\n\nlibxl can deliver events and invoke callbacks on any application thread\ncalling into libxl. This can cause deadlock in the libvirt libxl driver\n\nThread 19 (Thread 0x7f31411ec700 (LWP 14068) \"libvirtd\"):\n#0 0x00007f318520cc7d in __lll_lock_wait () from /lib64/libpthread.so.0\n#1 0x00007f3185205ed5 in pthread_mutex_lock () from /lib64/libpthread.so.0\n#2 0x00007f3189488015 in virMutexLock (m=) at ../../src/util/virthread.c:79\n#3 0x00007f3189463f3b in virObjectLock (anyobj=) at ../../src/util/virobject.c:433\n#4 0x00007f31894f2f41 in virDomainObjListSearchID (payload=0x7f317400a6d0, name=, data=0x7f31411eaeac) at ../../src/conf/virdomainobjlist.c:105\n#5 0x00007f3189437ac5 in virHashSearch (ctable=0x7f3124025a30, iter=iter@entry=0x7f31894f2f30 , data=data@entry=0x7f31411eaeac, name=name@entry=0x0) at ../../src/util/virhash.c:745\n#6 0x00007f31894f3919 in virDomainObjListFindByID (doms=0x7f3124025430, id=) at ../../src/conf/virdomainobjlist.c:121\n#7 0x00007f3152f292e5 in libxlDomainEventHandler (data=0x7f3124023d80, event=0x7f310c010ae0) at ../../src/libxl/libxl_domain.c:660\n#8 0x00007f3152c6ff5d in egc_run_callbacks (egc=egc@entry=0x7f31411eaf50) at libxl_event.c:1427\n#9 0x00007f3152c718bd in libxl__egc_cleanup (egc=0x7f31411eaf50) at libxl_event.c:1458\n#10 libxl__ao_inprogress (ao=ao@entry=0x7f310c00b8a0, file=file@entry=0x7f3152cce987 \"libxl_domain.c\", line=line@entry=730, func=func@entry=0x7f3152ccf750 <__func__.22238> \"libxl_domain_unpause\") at libxl_event.c:2047\n#11 0x00007f3152c8c5b8 in libxl_domain_unpause (ctx=0x7f3124015a40, domid=, ao_how=ao_how@entry=0x0) at libxl_domain.c:730\n#12 0x00007f3152f2a584 in libxl_domain_unpause_0x041200 (domid=, ctx=) at /usr/include/libxl.h:1756\n#13 libxlDomainStart (driver=driver@entry=0x7f3124023d80, vm=vm@entry=0x7f317400a6d0, start_paused=start_paused@entry=false, restore_fd=restore_fd@entry=-1, restore_ver=, restore_ver@entry=2) at ../../src/libxl/libxl_domain.c:1482\n#14 0x00007f3152f2a6e3 in libxlDomainStartNew (driver=driver@entry=0x7f3124023d80, vm=vm@entry=0x7f317400a6d0, start_paused=start_paused@entry=false) at ../../src/libxl/libxl_domain.c:1545\n#15 0x00007f3152f2a789 in libxlDomainShutdownHandleRestart (driver=0x7f3124023d80, vm=0x7f317400a6d0) at ../../src/libxl/libxl_domain.c:464\n#16 0x00007f3152f2a9e4 in libxlDomainShutdownThread (opaque=) at ../../src/libxl/libxl_domain.c:559\n#17 0x00007f3189487ee2 in virThreadHelper (data=) at ../../src/util/virthread.c:196\n#18 0x00007f3185203539 in start_thread () from /lib64/libpthread.so.0\n#19 0x00007f3184f3becf in clone () from /lib64/libc.so.6\n\nFrame 16 runs a thread created to handle domain shutdown processing for\ndomid 28712. In this case the event contained the reboot reason, so the\nold domain is destroyed and a new one is created by libxlDomainStart new.\nAfter starting the domain, it is unpaused by calling libxl_domain_unpause\nin frame 12. While the thread is running within libxl, libxl takes the\nopportunity to deliver a pending domain shutdown event for unrelated domid\n28710. While searching for the associated virDomainObj by ID, a deadlock is\nencountered when attempting to lock the virDomainObj for domid 28712, which\nis already locked since this thread is processing its shutdown event.\n\nThe deadlock can be avoided by moving the search for a virDomainObj\nassociated with the event domid to the shutdown thread. The same is done\nfor the death thread.\n\nSigned-off-by: Jim Fehlig \nReviewed-by: Daniel P. Berrang\u00e9 \nReviewed-by: J\u00e1n Tomko '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Status OplogApplicationChecks::checkAuthForCommand(OperationContext* opCtx,\n const std::string& dbname,\n const BSONObj& cmdObj,\n OplogApplicationValidity validity) {\n AuthorizationSession* authSession = AuthorizationSession::get(opCtx->getClient());\n if (validity == OplogApplicationValidity::kNeedsSuperuser) {\n std::vector universalPrivileges;\n RoleGraph::generateUniversalPrivileges(&universalPrivileges);\n if (!authSession->isAuthorizedForPrivileges(universalPrivileges)) {\n return Status(ErrorCodes::Unauthorized, \"Unauthorized\");\n }\n return Status::OK();\n }\n if (validity == OplogApplicationValidity::kNeedsForceAndUseUUID) {\n if (!authSession->isAuthorizedForActionsOnResource(\n ResourcePattern::forClusterResource(),\n {ActionType::forceUUID, ActionType::useUUID})) {\n return Status(ErrorCodes::Unauthorized, \"Unauthorized\");\n }\n validity = OplogApplicationValidity::kOk;\n }\n if (validity == OplogApplicationValidity::kNeedsUseUUID) {\n if (!authSession->isAuthorizedForActionsOnResource(ResourcePattern::forClusterResource(),\n ActionType::useUUID)) {\n return Status(ErrorCodes::Unauthorized, \"Unauthorized\");\n }\n validity = OplogApplicationValidity::kOk;\n }\n fassert(40314, validity == OplogApplicationValidity::kOk);\n\n boost::optional maybeDisableValidation;\n if (shouldBypassDocumentValidationForCommand(cmdObj))\n maybeDisableValidation.emplace(opCtx);\n\n const bool alwaysUpsert =\n cmdObj.hasField(\"alwaysUpsert\") ? cmdObj[\"alwaysUpsert\"].trueValue() : true;\n\n checkBSONType(BSONType::Array, cmdObj.firstElement());\n for (const BSONElement& e : cmdObj.firstElement().Array()) {\n checkBSONType(BSONType::Object, e);\n Status status = OplogApplicationChecks::checkOperationAuthorization(\n opCtx, dbname, e.Obj(), authSession, alwaysUpsert);\n if (!status.isOK()) {\n return status;\n }\n }\n\n BSONElement preconditions = cmdObj[\"preCondition\"];\n if (!preconditions.eoo()) {\n for (const BSONElement& precondition : preconditions.Array()) {\n checkBSONType(BSONType::Object, precondition);\n BSONElement nsElem = precondition.Obj()[\"ns\"];\n checkBSONType(BSONType::String, nsElem);\n NamespaceString nss(nsElem.checkAndGetStringData());\n\n if (!authSession->isAuthorizedForActionsOnResource(\n ResourcePattern::forExactNamespace(nss), ActionType::find)) {\n return Status(ErrorCodes::Unauthorized, \"Unauthorized to check precondition\");\n }\n }\n }\n\n return Status::OK();\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: lambda_function_body(\n\tchar_u\t **arg,\n\ttypval_T *rettv,\n\tevalarg_T *evalarg,\n\tgarray_T *newargs,\n\tgarray_T *argtypes,\n\tint\t varargs,\n\tgarray_T *default_args,\n\tchar_u\t *ret_type)\n{\n int\t\tevaluate = (evalarg->eval_flags & EVAL_EVALUATE);\n garray_T\t*gap = &evalarg->eval_ga;\n garray_T\t*freegap = &evalarg->eval_freega;\n ufunc_T\t*ufunc = NULL;\n exarg_T\teap;\n garray_T\tnewlines;\n char_u\t*cmdline = NULL;\n int\t\tret = FAIL;\n char_u\t*line_to_free = NULL;\n partial_T\t*pt;\n char_u\t*name;\n int\t\tlnum_save = -1;\n linenr_T\tsourcing_lnum_top = SOURCING_LNUM;\n\n if (!ends_excmd2(*arg, skipwhite(*arg + 1)))\n {\n\tsemsg(_(e_trailing_arg), *arg + 1);\n\treturn FAIL;\n }\n\n CLEAR_FIELD(eap);\n eap.cmdidx = CMD_block;\n eap.forceit = FALSE;\n eap.cmdlinep = &cmdline;\n eap.skip = !evaluate;\n if (evalarg->eval_cctx != NULL)\n\tfill_exarg_from_cctx(&eap, evalarg->eval_cctx);\n else\n {\n\teap.getline = evalarg->eval_getline;\n\teap.cookie = evalarg->eval_cookie;\n }\n\n ga_init2(&newlines, (int)sizeof(char_u *), 10);\n if (get_function_body(&eap, &newlines, NULL, &line_to_free) == FAIL)\n {\n\tvim_free(cmdline);\n\tgoto erret;\n }\n\n // When inside a lambda must add the function lines to evalarg.eval_ga.\n evalarg->eval_break_count += newlines.ga_len;\n if (gap->ga_itemsize > 0)\n {\n\tint\tidx;\n\tchar_u\t*last;\n\tsize_t plen;\n\tchar_u *pnl;\n\n\tfor (idx = 0; idx < newlines.ga_len; ++idx)\n\t{\n\t char_u *p = skipwhite(((char_u **)newlines.ga_data)[idx]);\n\n\t if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL)\n\t\tgoto erret;\n\n\t // Going to concatenate the lines after parsing. For an empty or\n\t // comment line use an empty string.\n\t // Insert NL characters at the start of each line, the string will\n\t // be split again later in .get_lambda_tv().\n\t if (*p == NUL || vim9_comment_start(p))\n\t\tp = (char_u *)\"\";\n\t plen = STRLEN(p);\n\t pnl = vim_strnsave((char_u *)\"\\n\", plen + 1);\n\t if (pnl != NULL)\n\t\tmch_memmove(pnl + 1, p, plen + 1);\n\t ((char_u **)gap->ga_data)[gap->ga_len++] = pnl;\n\t ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl;\n\t}\n\tif (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL)\n\t goto erret;\n\tif (cmdline != NULL)\n\t // more is following after the \"}\", which was skipped\n\t last = cmdline;\n\telse\n\t // nothing is following the \"}\"\n\t last = (char_u *)\"}\";\n\tplen = STRLEN(last);\n\tpnl = vim_strnsave((char_u *)\"\\n\", plen + 1);\n\tif (pnl != NULL)\n\t mch_memmove(pnl + 1, last, plen + 1);\n\t((char_u **)gap->ga_data)[gap->ga_len++] = pnl;\n\t((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl;\n }\n\n if (cmdline != NULL)\n {\n\tgarray_T *tfgap = &evalarg->eval_tofree_ga;\n\n\t// Something comes after the \"}\".\n\t*arg = eap.nextcmd;\n\n\t// \"arg\" points into cmdline, need to keep the line and free it later.\n\tif (ga_grow(tfgap, 1) == OK)\n\t{\n\t ((char_u **)(tfgap->ga_data))[tfgap->ga_len++] = cmdline;\n\t evalarg->eval_using_cmdline = TRUE;\n\t}\n }\n else\n\t*arg = (char_u *)\"\";\n\n if (!evaluate)\n {\n\tret = OK;\n\tgoto erret;\n }\n\n name = get_lambda_name();\n ufunc = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1);\n if (ufunc == NULL)\n\tgoto erret;\n set_ufunc_name(ufunc, name);\n if (hash_add(&func_hashtab, UF2HIKEY(ufunc)) == FAIL)\n\tgoto erret;\n ufunc->uf_flags = FC_LAMBDA;\n ufunc->uf_refcount = 1;\n ufunc->uf_args = *newargs;\n newargs->ga_data = NULL;\n ufunc->uf_def_args = *default_args;\n default_args->ga_data = NULL;\n ufunc->uf_func_type = &t_func_any;\n\n // error messages are for the first function line\n lnum_save = SOURCING_LNUM;\n SOURCING_LNUM = sourcing_lnum_top;\n\n // parse argument types\n if (parse_argument_types(ufunc, argtypes, varargs) == FAIL)\n {\n\tSOURCING_LNUM = lnum_save;\n\tgoto erret;\n }\n\n // parse the return type, if any\n if (parse_return_type(ufunc, ret_type) == FAIL)\n\tgoto erret;\n\n pt = ALLOC_CLEAR_ONE(partial_T);\n if (pt == NULL)\n\tgoto erret;\n pt->pt_func = ufunc;\n pt->pt_refcount = 1;\n\n ufunc->uf_lines = newlines;\n newlines.ga_data = NULL;\n if (sandbox)\n\tufunc->uf_flags |= FC_SANDBOX;\n if (!ASCII_ISUPPER(*ufunc->uf_name))\n\tufunc->uf_flags |= FC_VIM9;\n ufunc->uf_script_ctx = current_sctx;\n ufunc->uf_script_ctx_version = current_sctx.sc_version;\n ufunc->uf_script_ctx.sc_lnum += sourcing_lnum_top;\n set_function_type(ufunc);\n\n function_using_block_scopes(ufunc, evalarg->eval_cstack);\n\n rettv->vval.v_partial = pt;\n rettv->v_type = VAR_PARTIAL;\n ufunc = NULL;\n ret = OK;\n\nerret:\n if (lnum_save >= 0)\n\tSOURCING_LNUM = lnum_save;\n vim_free(line_to_free);\n ga_clear_strings(&newlines);\n if (newargs != NULL)\n\tga_clear_strings(newargs);\n ga_clear_strings(default_args);\n if (ufunc != NULL)\n {\n\tfunc_clear(ufunc, TRUE);\n\tfunc_free(ufunc, TRUE);\n }\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: \nstatic int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,\n\t\t\t\t\tconst struct mmu_notifier_range *range)\n{\n\tstruct kvm *kvm = mmu_notifier_to_kvm(mn);\n\tconst struct kvm_hva_range hva_range = {\n\t\t.start\t\t= range->start,\n\t\t.end\t\t= range->end,\n\t\t.pte\t\t= __pte(0),\n\t\t.handler\t= kvm_unmap_gfn_range,\n\t\t.on_lock\t= kvm_inc_notifier_count,\n\t\t.flush_on_ret\t= true,\n\t\t.may_block\t= mmu_notifier_range_blockable(range),\n\t};\n\n\ttrace_kvm_unmap_hva_range(range->start, range->end);\n\n\t/*\n\t * Prevent memslot modification between range_start() and range_end()\n\t * so that conditionally locking provides the same result in both\n\t * functions. Without that guarantee, the mmu_notifier_count\n\t * adjustments will be imbalanced.\n\t *\n\t * Pairs with the decrement in range_end().\n\t */\n\tspin_lock(&kvm->mn_invalidate_lock);\n\tkvm->mn_active_invalidate_count++;\n\tspin_unlock(&kvm->mn_invalidate_lock);\n\n\tgfn_to_pfn_cache_invalidate_start(kvm, range->start, range->end,\n\t\t\t\t\t hva_range.may_block);\n\n\t__kvm_handle_hva_range(kvm, &hva_range);\n\n\treturn 0; ; 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_line(\n\texarg_T\t\t*eap,\n\tchar_u\t\t**line_to_free,\n\tint\t\tindent,\n\tgetline_opt_T\tgetline_options)\n{\n char_u *theline;\n\n if (eap->getline == NULL)\n\ttheline = getcmdline(':', 0L, indent, 0);\n else\n\ttheline = eap->getline(':', eap->cookie, indent, getline_options);\n if (theline != NULL)\n {\n\tif (*eap->cmdlinep == *line_to_free)\n\t *eap->cmdlinep = theline;\n\tvim_free(*line_to_free);\n\t*line_to_free = theline;\n }\n\n return theline;\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: get_function_body(\n\texarg_T\t *eap,\n\tgarray_T *newlines,\n\tchar_u\t *line_arg_in,\n\tchar_u\t **line_to_free)\n{\n linenr_T\tsourcing_lnum_top = SOURCING_LNUM;\n linenr_T\tsourcing_lnum_off;\n int\t\tsaved_wait_return = need_wait_return;\n char_u\t*line_arg = line_arg_in;\n int\t\tvim9_function = eap->cmdidx == CMD_def\n\t\t\t\t\t\t || eap->cmdidx == CMD_block;\n#define MAX_FUNC_NESTING 50\n char\tnesting_def[MAX_FUNC_NESTING];\n char\tnesting_inline[MAX_FUNC_NESTING];\n int\t\tnesting = 0;\n getline_opt_T getline_options;\n int\t\tindent = 2;\n char_u\t*skip_until = NULL;\n int\t\tret = FAIL;\n int\t\tis_heredoc = FALSE;\n int\t\theredoc_concat_len = 0;\n garray_T\theredoc_ga;\n char_u\t*heredoc_trimmed = NULL;\n\n ga_init2(&heredoc_ga, 1, 500);\n\n // Detect having skipped over comment lines to find the return\n // type. Add NULL lines to keep the line count correct.\n sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie);\n if (SOURCING_LNUM < sourcing_lnum_off)\n {\n\tsourcing_lnum_off -= SOURCING_LNUM;\n\tif (ga_grow(newlines, sourcing_lnum_off) == FAIL)\n\t goto theend;\n\twhile (sourcing_lnum_off-- > 0)\n\t ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL;\n }\n\n nesting_def[0] = vim9_function;\n nesting_inline[0] = eap->cmdidx == CMD_block;\n getline_options = vim9_function\n\t\t\t\t? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT;\n for (;;)\n {\n\tchar_u\t*theline;\n\tchar_u\t*p;\n\tchar_u\t*arg;\n\n\tif (KeyTyped)\n\t{\n\t msg_scroll = TRUE;\n\t saved_wait_return = FALSE;\n\t}\n\tneed_wait_return = FALSE;\n\n\tif (line_arg != NULL)\n\t{\n\t // Use eap->arg, split up in parts by line breaks.\n\t theline = line_arg;\n\t p = vim_strchr(theline, '\\n');\n\t if (p == NULL)\n\t\tline_arg += STRLEN(line_arg);\n\t else\n\t {\n\t\t*p = NUL;\n\t\tline_arg = p + 1;\n\t }\n\t}\n\telse\n\t{\n\t theline = get_function_line(eap, line_to_free, indent,\n\t\t\t\t\t\t\t getline_options);\n\t}\n\tif (KeyTyped)\n\t lines_left = Rows - 1;\n\tif (theline == NULL)\n\t{\n\t // Use the start of the function for the line number.\n\t SOURCING_LNUM = sourcing_lnum_top;\n\t if (skip_until != NULL)\n\t\tsemsg(_(e_missing_heredoc_end_marker_str), skip_until);\n\t else if (nesting_inline[nesting])\n\t\temsg(_(e_missing_end_block));\n\t else if (eap->cmdidx == CMD_def)\n\t\temsg(_(e_missing_enddef));\n\t else\n\t\temsg(_(e_missing_endfunction));\n\t goto theend;\n\t}\n\n\t// Detect line continuation: SOURCING_LNUM increased more than one.\n\tsourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie);\n\tif (SOURCING_LNUM < sourcing_lnum_off)\n\t sourcing_lnum_off -= SOURCING_LNUM;\n\telse\n\t sourcing_lnum_off = 0;\n\n\tif (skip_until != NULL)\n\t{\n\t // Don't check for \":endfunc\"/\":enddef\" between\n\t // * \":append\" and \".\"\n\t // * \":python < 0)\n\t\t {\n\t\t\t// Replace the starting line with all the concatenated\n\t\t\t// lines.\n\t\t\tga_concat(&heredoc_ga, theline);\n\t\t\tvim_free(((char_u **)(newlines->ga_data))[\n\t\t\t\t\t\t heredoc_concat_len - 1]);\n\t\t\t((char_u **)(newlines->ga_data))[\n\t\t\t\t heredoc_concat_len - 1] = heredoc_ga.ga_data;\n\t\t\tga_init(&heredoc_ga);\n\t\t\theredoc_concat_len = 0;\n\t\t\ttheline += STRLEN(theline); // skip the \"EOF\"\n\t\t }\n\t\t}\n\t }\n\t}\n\telse\n\t{\n\t int\t c;\n\t char_u *end;\n\n\t // skip ':' and blanks\n\t for (p = theline; VIM_ISWHITE(*p) || *p == ':'; ++p)\n\t\t;\n\n\t // Check for \"endfunction\", \"enddef\" or \"}\".\n\t // When a \":\" follows it must be a dict key; \"enddef: value,\"\n\t if (nesting_inline[nesting]\n\t\t ? *p == '}'\n\t\t : (checkforcmd(&p, nesting_def[nesting]\n\t\t\t\t\t\t? \"enddef\" : \"endfunction\", 4)\n\t\t\t&& *p != ':'))\n\t {\n\t\tif (nesting-- == 0)\n\t\t{\n\t\t char_u *nextcmd = NULL;\n\n\t\t if (*p == '|' || *p == '}')\n\t\t\tnextcmd = p + 1;\n\t\t else if (line_arg != NULL && *skipwhite(line_arg) != NUL)\n\t\t\tnextcmd = line_arg;\n\t\t else if (*p != NUL && *p != (vim9_function ? '#' : '\"')\n\t\t\t\t\t && (vim9_function || p_verbose > 0))\n\t\t {\n\t\t\tSOURCING_LNUM = sourcing_lnum_top\n\t\t\t\t\t\t\t+ newlines->ga_len + 1;\n\t\t\tif (eap->cmdidx == CMD_def)\n\t\t\t semsg(_(e_text_found_after_str_str), \"enddef\", p);\n\t\t\telse\n\t\t\t give_warning2((char_u *)\n\t\t\t\t _(\"W22: Text found after :endfunction: %s\"),\n\t\t\t\t p, TRUE);\n\t\t }\n\t\t if (nextcmd != NULL && *skipwhite(nextcmd) != NUL)\n\t\t {\n\t\t\t// Another command follows. If the line came from \"eap\"\n\t\t\t// we can simply point into it, otherwise we need to\n\t\t\t// change \"eap->cmdlinep\".\n\t\t\teap->nextcmd = nextcmd;\n\t\t\tif (*line_to_free != NULL\n\t\t\t\t\t && *eap->cmdlinep != *line_to_free)\n\t\t\t{\n\t\t\t vim_free(*eap->cmdlinep);\n\t\t\t *eap->cmdlinep = *line_to_free;\n\t\t\t *line_to_free = NULL;\n\t\t\t}\n\t\t }\n\t\t break;\n\t\t}\n\t }\n\n\t // Check for mismatched \"endfunc\" or \"enddef\".\n\t // We don't check for \"def\" inside \"func\" thus we also can't check\n\t // for \"enddef\".\n\t // We continue to find the end of the function, although we might\n\t // not find it.\n\t else if (nesting_def[nesting])\n\t {\n\t\tif (checkforcmd(&p, \"endfunction\", 4) && *p != ':')\n\t\t emsg(_(e_mismatched_endfunction));\n\t }\n\t else if (eap->cmdidx == CMD_def && checkforcmd(&p, \"enddef\", 4))\n\t\temsg(_(e_mismatched_enddef));\n\n\t // Increase indent inside \"if\", \"while\", \"for\" and \"try\", decrease\n\t // at \"end\".\n\t if (indent > 2 && (*p == '}' || STRNCMP(p, \"end\", 3) == 0))\n\t\tindent -= 2;\n\t else if (STRNCMP(p, \"if\", 2) == 0\n\t\t || STRNCMP(p, \"wh\", 2) == 0\n\t\t || STRNCMP(p, \"for\", 3) == 0\n\t\t || STRNCMP(p, \"try\", 3) == 0)\n\t\tindent += 2;\n\n\t // Check for defining a function inside this function.\n\t // Only recognize \"def\" inside \"def\", not inside \"function\",\n\t // For backwards compatibility, see Test_function_python().\n\t c = *p;\n\t if (is_function_cmd(&p)\n\t\t || (eap->cmdidx == CMD_def && checkforcmd(&p, \"def\", 3)))\n\t {\n\t\tif (*p == '!')\n\t\t p = skipwhite(p + 1);\n\t\tp += eval_fname_script(p);\n\t\tvim_free(trans_function_name(&p, NULL, TRUE, 0, NULL,\n\t\t\t\t\t\t\t\t NULL, NULL));\n\t\tif (*skipwhite(p) == '(')\n\t\t{\n\t\t if (nesting == MAX_FUNC_NESTING - 1)\n\t\t\temsg(_(e_function_nesting_too_deep));\n\t\t else\n\t\t {\n\t\t\t++nesting;\n\t\t\tnesting_def[nesting] = (c == 'd');\n\t\t\tnesting_inline[nesting] = FALSE;\n\t\t\tindent += 2;\n\t\t }\n\t\t}\n\t }\n\n\t if (nesting_def[nesting] ? *p != '#' : *p != '\"')\n\t {\n\t\t// Not a comment line: check for nested inline function.\n\t\tend = p + STRLEN(p) - 1;\n\t\twhile (end > p && VIM_ISWHITE(*end))\n\t\t --end;\n\t\tif (end > p + 1 && *end == '{' && VIM_ISWHITE(end[-1]))\n\t\t{\n\t\t int\t is_block;\n\n\t\t // check for trailing \"=> {\": start of an inline function\n\t\t --end;\n\t\t while (end > p && VIM_ISWHITE(*end))\n\t\t\t--end;\n\t\t is_block = end > p + 2 && end[-1] == '=' && end[0] == '>';\n\t\t if (!is_block)\n\t\t {\n\t\t\tchar_u *s = p;\n\n\t\t\t// check for line starting with \"au\" for :autocmd or\n\t\t\t// \"com\" for :command, these can use a {} block\n\t\t\tis_block = checkforcmd_noparen(&s, \"autocmd\", 2)\n\t\t\t\t || checkforcmd_noparen(&s, \"command\", 3);\n\t\t }\n\n\t\t if (is_block)\n\t\t {\n\t\t\tif (nesting == MAX_FUNC_NESTING - 1)\n\t\t\t emsg(_(e_function_nesting_too_deep));\n\t\t\telse\n\t\t\t{\n\t\t\t ++nesting;\n\t\t\t nesting_def[nesting] = TRUE;\n\t\t\t nesting_inline[nesting] = TRUE;\n\t\t\t indent += 2;\n\t\t\t}\n\t\t }\n\t\t}\n\t }\n\n\t // Check for \":append\", \":change\", \":insert\". Not for :def.\n\t p = skip_range(p, FALSE, NULL);\n\t if (!vim9_function\n\t\t&& ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))\n\t\t || (p[0] == 'c'\n\t\t\t&& (!ASCII_ISALPHA(p[1]) || (p[1] == 'h'\n\t\t\t\t&& (!ASCII_ISALPHA(p[2]) || (p[2] == 'a'\n\t\t\t\t\t&& (STRNCMP(&p[3], \"nge\", 3) != 0\n\t\t\t\t\t || !ASCII_ISALPHA(p[6])))))))\n\t\t || (p[0] == 'i'\n\t\t\t&& (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'\n\t\t\t\t&& (!ASCII_ISALPHA(p[2])\n\t\t\t\t || (p[2] == 's'\n\t\t\t\t\t&& (!ASCII_ISALPHA(p[3])\n\t\t\t\t\t\t|| p[3] == 'e'))))))))\n\t\tskip_until = vim_strsave((char_u *)\".\");\n\n\t // Check for \":python <cmdidx == CMD_def)\n\t\t heredoc_concat_len = newlines->ga_len + 1;\n\t }\n\n\t // Check for \":cmd v =<< [trim] EOF\"\n\t // and \":cmd [a, b] =<< [trim] EOF\"\n\t // and \"lines =<< [trim] EOF\" for Vim9\n\t // Where \"cmd\" can be \"let\", \"var\", \"final\" or \"const\".\n\t arg = skipwhite(skiptowhite(p));\n\t if (*arg == '[')\n\t\targ = vim_strchr(arg, ']');\n\t if (arg != NULL)\n\t {\n\t\tint found = (eap->cmdidx == CMD_def && arg[0] == '='\n\t\t\t\t\t && arg[1] == '<' && arg[2] =='<');\n\n\t\tif (!found)\n\t\t // skip over the argument after \"cmd\"\n\t\t arg = skipwhite(skiptowhite(arg));\n\t\tif (found || (arg[0] == '=' && arg[1] == '<' && arg[2] =='<'\n\t\t\t&& (checkforcmd(&p, \"let\", 2)\n\t\t\t || checkforcmd(&p, \"var\", 3)\n\t\t\t || checkforcmd(&p, \"final\", 5)\n\t\t\t || checkforcmd(&p, \"const\", 5))))\n\t\t{\n\t\t p = skipwhite(arg + 3);\n\t\t if (STRNCMP(p, \"trim\", 4) == 0)\n\t\t {\n\t\t\t// Ignore leading white space.\n\t\t\tp = skipwhite(p + 4);\n\t\t\theredoc_trimmed = vim_strnsave(theline,\n\t\t\t\t\t\t skipwhite(theline) - theline);\n\t\t }\n\t\t skip_until = vim_strnsave(p, skiptowhite(p) - p);\n\t\t getline_options = GETLINE_NONE;\n\t\t is_heredoc = TRUE;\n\t\t}\n\t }\n\t}\n\n\t// Add the line to the function.\n\tif (ga_grow(newlines, 1 + sourcing_lnum_off) == FAIL)\n\t goto theend;\n\n\tif (heredoc_concat_len > 0)\n\t{\n\t // For a :def function \"python << EOF\" concatenates all the lines,\n\t // to be used for the instruction later.\n\t ga_concat(&heredoc_ga, theline);\n\t ga_concat(&heredoc_ga, (char_u *)\"\\n\");\n\t p = vim_strsave((char_u *)\"\");\n\t}\n\telse\n\t{\n\t // Copy the line to newly allocated memory. get_one_sourceline()\n\t // allocates 250 bytes per line, this saves 80% on average. The\n\t // cost is an extra alloc/free.\n\t p = vim_strsave(theline);\n\t}\n\tif (p == NULL)\n\t goto theend;\n\t((char_u **)(newlines->ga_data))[newlines->ga_len++] = p;\n\n\t// Add NULL lines for continuation lines, so that the line count is\n\t// equal to the index in the growarray.\n\twhile (sourcing_lnum_off-- > 0)\n\t ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL;\n\n\t// Check for end of eap->arg.\n\tif (line_arg != NULL && *line_arg == NUL)\n\t line_arg = NULL;\n }\n\n // Return OK when no error was detected.\n if (!did_emsg)\n\tret = OK;\n\ntheend:\n vim_free(skip_until);\n vim_free(heredoc_trimmed);\n vim_free(heredoc_ga.ga_data);\n need_wait_return |= saved_wait_return;\n return ret;\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: time_t base64totime_t(char* s, database* db, const char* field_name){\n \n byte* b=decode_base64(s,strlen(s),NULL);\n char* endp;\n \n if (b==NULL||strcmp(s,\"0\")==0) {\n \n /* Should we print error here? */\n free(b);\n \n return 0;\n } else {\n time_t t = strtol((char *)b,&endp,10);\n \n if (endp[0]!='\\0') {\n LOG_DB_FORMAT_LINE(LOG_LEVEL_WARNING, could not read '%s' from database: strtoll failed for '%s' (base64 encoded value: '%s'), field_name, b, s)\n free(b);\n return 0;\n }\n log_msg(LOG_LEVEL_DEBUG, \"base64totime_t: converted '%s': '%s' to %lld (base64 encoded value '%s')\", field_name, b, (long long) t, s);\n free(b);\n return t;\n }\n \n \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: win_redr_status(win_T *wp, int ignore_pum UNUSED)\n{\n int\t\trow;\n char_u\t*p;\n int\t\tlen;\n int\t\tfillchar;\n int\t\tattr;\n int\t\tthis_ru_col;\n static int busy = FALSE;\n\n // It's possible to get here recursively when 'statusline' (indirectly)\n // invokes \":redrawstatus\". Simply ignore the call then.\n if (busy)\n\treturn;\n busy = TRUE;\n\n row = statusline_row(wp);\n\n wp->w_redr_status = FALSE;\n if (wp->w_status_height == 0)\n {\n\t// no status line, can only be last window\n\tredraw_cmdline = TRUE;\n }\n else if (!redrawing()\n\t // don't update status line when popup menu is visible and may be\n\t // drawn over it, unless it will be redrawn later\n\t || (!ignore_pum && pum_visible()))\n {\n\t// Don't redraw right now, do it later.\n\twp->w_redr_status = TRUE;\n }\n#ifdef FEAT_STL_OPT\n else if (*p_stl != NUL || *wp->w_p_stl != NUL)\n {\n\t// redraw custom status line\n\tredraw_custom_statusline(wp);\n }\n#endif\n else\n {\n\tfillchar = fillchar_status(&attr, wp);\n\n\tget_trans_bufname(wp->w_buffer);\n\tp = NameBuff;\n\tlen = (int)STRLEN(p);\n\n\tif (bt_help(wp->w_buffer)\n#ifdef FEAT_QUICKFIX\n\t\t|| wp->w_p_pvw\n#endif\n\t\t|| bufIsChanged(wp->w_buffer)\n\t\t|| wp->w_buffer->b_p_ro)\n\t *(p + len++) = ' ';\n\tif (bt_help(wp->w_buffer))\n\t{\n\t vim_snprintf((char *)p + len, MAXPATHL - len, \"%s\", _(\"[Help]\"));\n\t len += (int)STRLEN(p + len);\n\t}\n#ifdef FEAT_QUICKFIX\n\tif (wp->w_p_pvw)\n\t{\n\t vim_snprintf((char *)p + len, MAXPATHL - len, \"%s\", _(\"[Preview]\"));\n\t len += (int)STRLEN(p + len);\n\t}\n#endif\n\tif (bufIsChanged(wp->w_buffer)\n#ifdef FEAT_TERMINAL\n\t\t&& !bt_terminal(wp->w_buffer)\n#endif\n\t\t)\n\t{\n\t vim_snprintf((char *)p + len, MAXPATHL - len, \"%s\", \"[+]\");\n\t len += (int)STRLEN(p + len);\n\t}\n\tif (wp->w_buffer->b_p_ro)\n\t{\n\t vim_snprintf((char *)p + len, MAXPATHL - len, \"%s\", _(\"[RO]\"));\n\t len += (int)STRLEN(p + len);\n\t}\n\n\tthis_ru_col = ru_col - (Columns - wp->w_width);\n\tif (this_ru_col < (wp->w_width + 1) / 2)\n\t this_ru_col = (wp->w_width + 1) / 2;\n\tif (this_ru_col <= 1)\n\t{\n\t p = (char_u *)\"<\";\t\t// No room for file name!\n\t len = 1;\n\t}\n\telse if (has_mbyte)\n\t{\n\t int\tclen = 0, i;\n\n\t // Count total number of display cells.\n\t clen = mb_string2cells(p, -1);\n\n\t // Find first character that will fit.\n\t // Going from start to end is much faster for DBCS.\n\t for (i = 0; p[i] != NUL && clen >= this_ru_col - 1;\n\t\t i += (*mb_ptr2len)(p + i))\n\t\tclen -= (*mb_ptr2cells)(p + i);\n\t len = clen;\n\t if (i > 0)\n\t {\n\t\tp = p + i - 1;\n\t\t*p = '<';\n\t\t++len;\n\t }\n\n\t}\n\telse if (len > this_ru_col - 1)\n\t{\n\t p += len - (this_ru_col - 1);\n\t *p = '<';\n\t len = this_ru_col - 1;\n\t}\n\n\tscreen_puts(p, row, wp->w_wincol, attr);\n\tscreen_fill(row, row + 1, len + wp->w_wincol,\n\t\t\tthis_ru_col + wp->w_wincol, fillchar, fillchar, attr);\n\n\tif (get_keymap_str(wp, (char_u *)\"<%s>\", NameBuff, MAXPATHL)\n\t\t&& (int)(this_ru_col - len) > (int)(STRLEN(NameBuff) + 1))\n\t screen_puts(NameBuff, row, (int)(this_ru_col - STRLEN(NameBuff)\n\t\t\t\t\t\t - 1 + wp->w_wincol), attr);\n\n#ifdef FEAT_CMDL_INFO\n\twin_redr_ruler(wp, TRUE, ignore_pum);\n#endif\n }\n\n /*\n * May need to draw the character below the vertical separator.\n */\n if (wp->w_vsep_width != 0 && wp->w_status_height != 0 && redrawing())\n {\n\tif (stl_connected(wp))\n\t fillchar = fillchar_status(&attr, wp);\n\telse\n\t fillchar = fillchar_vsep(&attr);\n\tscreen_putchar(fillchar, row, W_ENDCOL(wp), attr);\n }\n busy = FALSE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-122'], 'message': 'patch 8.2.4074: going over the end of NameBuff\n\nProblem: Going over the end of NameBuff.\nSolution: Check length when appending a 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: block_insert(\n oparg_T\t\t*oap,\n char_u\t\t*s,\n int\t\t\tb_insert,\n struct block_def\t*bdp)\n{\n int\t\tts_val;\n int\t\tcount = 0;\t// extra spaces to replace a cut TAB\n int\t\tspaces = 0;\t// non-zero if cutting a TAB\n colnr_T\toffset;\t\t// pointer along new line\n colnr_T\tstartcol;\t// column where insert starts\n unsigned\ts_len;\t\t// STRLEN(s)\n char_u\t*newp, *oldp;\t// new, old lines\n linenr_T\tlnum;\t\t// loop var\n int\t\toldstate = State;\n\n State = INSERT;\t\t// don't want REPLACE for State\n s_len = (unsigned)STRLEN(s);\n\n for (lnum = oap->start.lnum + 1; lnum <= oap->end.lnum; lnum++)\n {\n\tblock_prep(oap, bdp, lnum, TRUE);\n\tif (bdp->is_short && b_insert)\n\t continue;\t// OP_INSERT, line ends before block start\n\n\toldp = ml_get(lnum);\n\n\tif (b_insert)\n\t{\n\t ts_val = bdp->start_char_vcols;\n\t spaces = bdp->startspaces;\n\t if (spaces != 0)\n\t\tcount = ts_val - 1; // we're cutting a TAB\n\t offset = bdp->textcol;\n\t}\n\telse // append\n\t{\n\t ts_val = bdp->end_char_vcols;\n\t if (!bdp->is_short) // spaces = padding after block\n\t {\n\t\tspaces = (bdp->endspaces ? ts_val - bdp->endspaces : 0);\n\t\tif (spaces != 0)\n\t\t count = ts_val - 1; // we're cutting a TAB\n\t\toffset = bdp->textcol + bdp->textlen - (spaces != 0);\n\t }\n\t else // spaces = padding to block edge\n\t {\n\t\t// if $ used, just append to EOL (ie spaces==0)\n\t\tif (!bdp->is_MAX)\n\t\t spaces = (oap->end_vcol - bdp->end_vcol) + 1;\n\t\tcount = spaces;\n\t\toffset = bdp->textcol + bdp->textlen;\n\t }\n\t}\n\n\tif (has_mbyte && spaces > 0)\n\t{\n\t int off;\n\n\t // Avoid starting halfway a multi-byte character.\n\t if (b_insert)\n\t {\n\t\toff = (*mb_head_off)(oldp, oldp + offset + spaces);\n\t\tspaces -= off;\n\t\tcount -= off;\n\t }\n\t else\n\t {\n\t\t// spaces fill the gap, the character that's at the edge moves\n\t\t// right\n\t\toff = (*mb_head_off)(oldp, oldp + offset);\n\t\toffset -= off;\n\t }\n\t}\n\tif (spaces < 0) // can happen when the cursor was moved\n\t spaces = 0;\n\n\t// Make sure the allocated size matches what is actually copied below.\n\tnewp = alloc(STRLEN(oldp) + spaces + s_len\n\t\t + (spaces > 0 && !bdp->is_short ? ts_val - spaces : 0)\n\t\t\t\t\t\t\t\t + count + 1);\n\tif (newp == NULL)\n\t continue;\n\n\t// copy up to shifted part\n\tmch_memmove(newp, oldp, (size_t)offset);\n\toldp += offset;\n\n\t// insert pre-padding\n\tvim_memset(newp + offset, ' ', (size_t)spaces);\n\tstartcol = offset + spaces;\n\n\t// copy the new text\n\tmch_memmove(newp + startcol, s, (size_t)s_len);\n\toffset += s_len;\n\n\tif (spaces > 0 && !bdp->is_short)\n\t{\n\t if (*oldp == TAB)\n\t {\n\t\t// insert post-padding\n\t\tvim_memset(newp + offset + spaces, ' ',\n\t\t\t\t\t\t (size_t)(ts_val - spaces));\n\t\t// we're splitting a TAB, don't copy it\n\t\toldp++;\n\t\t// We allowed for that TAB, remember this now\n\t\tcount++;\n\t }\n\t else\n\t\t// Not a TAB, no extra spaces\n\t\tcount = spaces;\n\t}\n\n\tif (spaces > 0)\n\t offset += count;\n\tSTRMOVE(newp + offset, oldp);\n\n\tml_replace(lnum, newp, FALSE);\n\n\tif (b_insert)\n\t // correct any text properties\n\t inserted_bytes(lnum, startcol, s_len);\n\n\tif (lnum == oap->end.lnum)\n\t{\n\t // Set \"']\" mark to the end of the block instead of the end of\n\t // the insert in the first line.\n\t curbuf->b_op_end.lnum = oap->end.lnum;\n\t curbuf->b_op_end.col = offset;\n\t}\n } // for all lnum\n\n changed_lines(oap->start.lnum + 1, 0, oap->end.lnum + 1, 0L);\n\n State = oldstate;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-122', 'CWE-787'], 'message': 'patch 8.2.4151: reading beyond the end of a line\n\nProblem: Reading beyond the end of a line.\nSolution: For block insert only use the offset for correcting the 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: 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) && *preword != NUL)\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-121', 'CWE-787'], 'message': 'patch 8.2.4247: stack corruption when looking for spell suggestions\n\nProblem: Stack corruption when looking for spell suggestions.\nSolution: Prevent the depth increased too much. Add a five second time\n limit to finding suggestions.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: buf_copy_options(buf_T *buf, int flags)\n{\n int\t\tshould_copy = TRUE;\n char_u\t*save_p_isk = NULL;\t // init for GCC\n int\t\tdont_do_help;\n int\t\tdid_isk = FALSE;\n\n /*\n * Skip this when the option defaults have not been set yet. Happens when\n * main() allocates the first buffer.\n */\n if (p_cpo != NULL)\n {\n\t/*\n\t * Always copy when entering and 'cpo' contains 'S'.\n\t * Don't copy when already initialized.\n\t * Don't copy when 'cpo' contains 's' and not entering.\n\t * 'S'\tBCO_ENTER initialized\t's' should_copy\n\t * yes\t yes\t X\t X\tTRUE\n\t * yes\t no\t yes\t X\tFALSE\n\t * no\t X\t yes\t X\tFALSE\n\t * X\t no\t no\tyes\tFALSE\n\t * X\t no\t no\tno\tTRUE\n\t * no\t yes\t no\t X\tTRUE\n\t */\n\tif ((vim_strchr(p_cpo, CPO_BUFOPTGLOB) == NULL || !(flags & BCO_ENTER))\n\t\t&& (buf->b_p_initialized\n\t\t || (!(flags & BCO_ENTER)\n\t\t\t&& vim_strchr(p_cpo, CPO_BUFOPT) != NULL)))\n\t should_copy = FALSE;\n\n\tif (should_copy || (flags & BCO_ALWAYS))\n\t{\n#ifdef FEAT_EVAL\n\t CLEAR_FIELD(buf->b_p_script_ctx);\n\t init_buf_opt_idx();\n#endif\n\t // Don't copy the options specific to a help buffer when\n\t // BCO_NOHELP is given or the options were initialized already\n\t // (jumping back to a help file with CTRL-T or CTRL-O)\n\t dont_do_help = ((flags & BCO_NOHELP) && buf->b_help)\n\t\t\t\t\t\t || buf->b_p_initialized;\n\t if (dont_do_help)\t\t// don't free b_p_isk\n\t {\n\t\tsave_p_isk = buf->b_p_isk;\n\t\tbuf->b_p_isk = NULL;\n\t }\n\t /*\n\t * Always free the allocated strings. If not already initialized,\n\t * reset 'readonly' and copy 'fileformat'.\n\t */\n\t if (!buf->b_p_initialized)\n\t {\n\t\tfree_buf_options(buf, TRUE);\n\t\tbuf->b_p_ro = FALSE;\t\t// don't copy readonly\n\t\tbuf->b_p_tx = p_tx;\n\t\tbuf->b_p_fenc = vim_strsave(p_fenc);\n\t\tswitch (*p_ffs)\n\t\t{\n\t\t case 'm':\n\t\t\tbuf->b_p_ff = vim_strsave((char_u *)FF_MAC); break;\n\t\t case 'd':\n\t\t\tbuf->b_p_ff = vim_strsave((char_u *)FF_DOS); break;\n\t\t case 'u':\n\t\t\tbuf->b_p_ff = vim_strsave((char_u *)FF_UNIX); break;\n\t\t default:\n\t\t\tbuf->b_p_ff = vim_strsave(p_ff);\n\t\t}\n\t\tif (buf->b_p_ff != NULL)\n\t\t buf->b_start_ffc = *buf->b_p_ff;\n\t\tbuf->b_p_bh = empty_option;\n\t\tbuf->b_p_bt = empty_option;\n\t }\n\t else\n\t\tfree_buf_options(buf, FALSE);\n\n\t buf->b_p_ai = p_ai;\n\t COPY_OPT_SCTX(buf, BV_AI);\n\t buf->b_p_ai_nopaste = p_ai_nopaste;\n\t buf->b_p_sw = p_sw;\n\t COPY_OPT_SCTX(buf, BV_SW);\n\t buf->b_p_tw = p_tw;\n\t COPY_OPT_SCTX(buf, BV_TW);\n\t buf->b_p_tw_nopaste = p_tw_nopaste;\n\t buf->b_p_tw_nobin = p_tw_nobin;\n\t buf->b_p_wm = p_wm;\n\t COPY_OPT_SCTX(buf, BV_WM);\n\t buf->b_p_wm_nopaste = p_wm_nopaste;\n\t buf->b_p_wm_nobin = p_wm_nobin;\n\t buf->b_p_bin = p_bin;\n\t COPY_OPT_SCTX(buf, BV_BIN);\n\t buf->b_p_bomb = p_bomb;\n\t COPY_OPT_SCTX(buf, BV_BOMB);\n\t buf->b_p_fixeol = p_fixeol;\n\t COPY_OPT_SCTX(buf, BV_FIXEOL);\n\t buf->b_p_et = p_et;\n\t COPY_OPT_SCTX(buf, BV_ET);\n\t buf->b_p_et_nobin = p_et_nobin;\n\t buf->b_p_et_nopaste = p_et_nopaste;\n\t buf->b_p_ml = p_ml;\n\t COPY_OPT_SCTX(buf, BV_ML);\n\t buf->b_p_ml_nobin = p_ml_nobin;\n\t buf->b_p_inf = p_inf;\n\t COPY_OPT_SCTX(buf, BV_INF);\n\t if (cmdmod.cmod_flags & CMOD_NOSWAPFILE)\n\t\tbuf->b_p_swf = FALSE;\n\t else\n\t {\n\t\tbuf->b_p_swf = p_swf;\n\t\tCOPY_OPT_SCTX(buf, BV_SWF);\n\t }\n\t buf->b_p_cpt = vim_strsave(p_cpt);\n\t COPY_OPT_SCTX(buf, BV_CPT);\n#ifdef BACKSLASH_IN_FILENAME\n\t buf->b_p_csl = vim_strsave(p_csl);\n\t COPY_OPT_SCTX(buf, BV_CSL);\n#endif\n#ifdef FEAT_COMPL_FUNC\n\t buf->b_p_cfu = vim_strsave(p_cfu);\n\t COPY_OPT_SCTX(buf, BV_CFU);\n\t set_buflocal_cfu_callback(buf);\n\t buf->b_p_ofu = vim_strsave(p_ofu);\n\t COPY_OPT_SCTX(buf, BV_OFU);\n\t set_buflocal_ofu_callback(buf);\n#endif\n#ifdef FEAT_EVAL\n\t buf->b_p_tfu = vim_strsave(p_tfu);\n\t COPY_OPT_SCTX(buf, BV_TFU);\n\t set_buflocal_tfu_callback(buf);\n#endif\n\t buf->b_p_sts = p_sts;\n\t COPY_OPT_SCTX(buf, BV_STS);\n\t buf->b_p_sts_nopaste = p_sts_nopaste;\n#ifdef FEAT_VARTABS\n\t buf->b_p_vsts = vim_strsave(p_vsts);\n\t COPY_OPT_SCTX(buf, BV_VSTS);\n\t if (p_vsts && p_vsts != empty_option)\n\t\t(void)tabstop_set(p_vsts, &buf->b_p_vsts_array);\n\t else\n\t\tbuf->b_p_vsts_array = 0;\n\t buf->b_p_vsts_nopaste = p_vsts_nopaste\n\t\t\t\t ? vim_strsave(p_vsts_nopaste) : NULL;\n#endif\n\t buf->b_p_sn = p_sn;\n\t COPY_OPT_SCTX(buf, BV_SN);\n\t buf->b_p_com = vim_strsave(p_com);\n\t COPY_OPT_SCTX(buf, BV_COM);\n#ifdef FEAT_FOLDING\n\t buf->b_p_cms = vim_strsave(p_cms);\n\t COPY_OPT_SCTX(buf, BV_CMS);\n#endif\n\t buf->b_p_fo = vim_strsave(p_fo);\n\t COPY_OPT_SCTX(buf, BV_FO);\n\t buf->b_p_flp = vim_strsave(p_flp);\n\t COPY_OPT_SCTX(buf, BV_FLP);\n\t // NOTE: Valgrind may report a bogus memory leak for 'nrformats'\n\t // when it is set to 8 bytes in defaults.vim.\n\t buf->b_p_nf = vim_strsave(p_nf);\n\t COPY_OPT_SCTX(buf, BV_NF);\n\t buf->b_p_mps = vim_strsave(p_mps);\n\t COPY_OPT_SCTX(buf, BV_MPS);\n#ifdef FEAT_SMARTINDENT\n\t buf->b_p_si = p_si;\n\t COPY_OPT_SCTX(buf, BV_SI);\n#endif\n\t buf->b_p_ci = p_ci;\n\t COPY_OPT_SCTX(buf, BV_CI);\n#ifdef FEAT_CINDENT\n\t buf->b_p_cin = p_cin;\n\t COPY_OPT_SCTX(buf, BV_CIN);\n\t buf->b_p_cink = vim_strsave(p_cink);\n\t COPY_OPT_SCTX(buf, BV_CINK);\n\t buf->b_p_cino = vim_strsave(p_cino);\n\t COPY_OPT_SCTX(buf, BV_CINO);\n#endif\n\t // Don't copy 'filetype', it must be detected\n\t buf->b_p_ft = empty_option;\n\t buf->b_p_pi = p_pi;\n\t COPY_OPT_SCTX(buf, BV_PI);\n#if defined(FEAT_SMARTINDENT) || defined(FEAT_CINDENT)\n\t buf->b_p_cinw = vim_strsave(p_cinw);\n\t COPY_OPT_SCTX(buf, BV_CINW);\n#endif\n#ifdef FEAT_LISP\n\t buf->b_p_lisp = p_lisp;\n\t COPY_OPT_SCTX(buf, BV_LISP);\n#endif\n#ifdef FEAT_SYN_HL\n\t // Don't copy 'syntax', it must be set\n\t buf->b_p_syn = empty_option;\n\t buf->b_p_smc = p_smc;\n\t COPY_OPT_SCTX(buf, BV_SMC);\n\t buf->b_s.b_syn_isk = empty_option;\n#endif\n#ifdef FEAT_SPELL\n\t buf->b_s.b_p_spc = vim_strsave(p_spc);\n\t COPY_OPT_SCTX(buf, BV_SPC);\n\t (void)compile_cap_prog(&buf->b_s);\n\t buf->b_s.b_p_spf = vim_strsave(p_spf);\n\t COPY_OPT_SCTX(buf, BV_SPF);\n\t buf->b_s.b_p_spl = vim_strsave(p_spl);\n\t COPY_OPT_SCTX(buf, BV_SPL);\n\t buf->b_s.b_p_spo = vim_strsave(p_spo);\n\t COPY_OPT_SCTX(buf, BV_SPO);\n#endif\n#if defined(FEAT_CINDENT) && defined(FEAT_EVAL)\n\t buf->b_p_inde = vim_strsave(p_inde);\n\t COPY_OPT_SCTX(buf, BV_INDE);\n\t buf->b_p_indk = vim_strsave(p_indk);\n\t COPY_OPT_SCTX(buf, BV_INDK);\n#endif\n\t buf->b_p_fp = empty_option;\n#if defined(FEAT_EVAL)\n\t buf->b_p_fex = vim_strsave(p_fex);\n\t COPY_OPT_SCTX(buf, BV_FEX);\n#endif\n#ifdef FEAT_CRYPT\n\t buf->b_p_key = vim_strsave(p_key);\n\t COPY_OPT_SCTX(buf, BV_KEY);\n#endif\n#ifdef FEAT_SEARCHPATH\n\t buf->b_p_sua = vim_strsave(p_sua);\n\t COPY_OPT_SCTX(buf, BV_SUA);\n#endif\n#ifdef FEAT_KEYMAP\n\t buf->b_p_keymap = vim_strsave(p_keymap);\n\t COPY_OPT_SCTX(buf, BV_KMAP);\n\t buf->b_kmap_state |= KEYMAP_INIT;\n#endif\n#ifdef FEAT_TERMINAL\n\t buf->b_p_twsl = p_twsl;\n\t COPY_OPT_SCTX(buf, BV_TWSL);\n#endif\n\t // This isn't really an option, but copying the langmap and IME\n\t // state from the current buffer is better than resetting it.\n\t buf->b_p_iminsert = p_iminsert;\n\t COPY_OPT_SCTX(buf, BV_IMI);\n\t buf->b_p_imsearch = p_imsearch;\n\t COPY_OPT_SCTX(buf, BV_IMS);\n\n\t // options that are normally global but also have a local value\n\t // are not copied, start using the global value\n\t buf->b_p_ar = -1;\n\t buf->b_p_ul = NO_LOCAL_UNDOLEVEL;\n\t buf->b_p_bkc = empty_option;\n\t buf->b_bkc_flags = 0;\n#ifdef FEAT_QUICKFIX\n\t buf->b_p_gp = empty_option;\n\t buf->b_p_mp = empty_option;\n\t buf->b_p_efm = empty_option;\n#endif\n\t buf->b_p_ep = empty_option;\n\t buf->b_p_kp = empty_option;\n\t buf->b_p_path = empty_option;\n\t buf->b_p_tags = empty_option;\n\t buf->b_p_tc = empty_option;\n\t buf->b_tc_flags = 0;\n#ifdef FEAT_FIND_ID\n\t buf->b_p_def = empty_option;\n\t buf->b_p_inc = empty_option;\n# ifdef FEAT_EVAL\n\t buf->b_p_inex = vim_strsave(p_inex);\n\t COPY_OPT_SCTX(buf, BV_INEX);\n# endif\n#endif\n\t buf->b_p_dict = empty_option;\n\t buf->b_p_tsr = empty_option;\n#ifdef FEAT_COMPL_FUNC\n\t buf->b_p_tsrfu = empty_option;\n#endif\n#ifdef FEAT_TEXTOBJ\n\t buf->b_p_qe = vim_strsave(p_qe);\n\t COPY_OPT_SCTX(buf, BV_QE);\n#endif\n#if defined(FEAT_BEVAL) && defined(FEAT_EVAL)\n\t buf->b_p_bexpr = empty_option;\n#endif\n#if defined(FEAT_CRYPT)\n\t buf->b_p_cm = empty_option;\n#endif\n#ifdef FEAT_PERSISTENT_UNDO\n\t buf->b_p_udf = p_udf;\n\t COPY_OPT_SCTX(buf, BV_UDF);\n#endif\n#ifdef FEAT_LISP\n\t buf->b_p_lw = empty_option;\n#endif\n\t buf->b_p_menc = empty_option;\n\n\t /*\n\t * Don't copy the options set by ex_help(), use the saved values,\n\t * when going from a help buffer to a non-help buffer.\n\t * Don't touch these at all when BCO_NOHELP is used and going from\n\t * or to a help buffer.\n\t */\n\t if (dont_do_help)\n\t {\n\t\tbuf->b_p_isk = save_p_isk;\n#ifdef FEAT_VARTABS\n\t\tif (p_vts && p_vts != empty_option && !buf->b_p_vts_array)\n\t\t (void)tabstop_set(p_vts, &buf->b_p_vts_array);\n\t\telse\n\t\t buf->b_p_vts_array = NULL;\n#endif\n\t }\n\t else\n\t {\n\t\tbuf->b_p_isk = vim_strsave(p_isk);\n\t\tCOPY_OPT_SCTX(buf, BV_ISK);\n\t\tdid_isk = TRUE;\n\t\tbuf->b_p_ts = p_ts;\n\t\tCOPY_OPT_SCTX(buf, BV_TS);\n#ifdef FEAT_VARTABS\n\t\tbuf->b_p_vts = vim_strsave(p_vts);\n\t\tCOPY_OPT_SCTX(buf, BV_VTS);\n\t\tif (p_vts && p_vts != empty_option && !buf->b_p_vts_array)\n\t\t (void)tabstop_set(p_vts, &buf->b_p_vts_array);\n\t\telse\n\t\t buf->b_p_vts_array = NULL;\n#endif\n\t\tbuf->b_help = FALSE;\n\t\tif (buf->b_p_bt[0] == 'h')\n\t\t clear_string_option(&buf->b_p_bt);\n\t\tbuf->b_p_ma = p_ma;\n\t\tCOPY_OPT_SCTX(buf, BV_MA);\n\t }\n\t}\n\n\t/*\n\t * When the options should be copied (ignoring BCO_ALWAYS), set the\n\t * flag that indicates that the options have been initialized.\n\t */\n\tif (should_copy)\n\t buf->b_p_initialized = TRUE;\n }\n\n check_buf_options(buf);\t // make sure we don't have NULLs\n if (did_isk)\n\t(void)buf_init_chartab(buf, FALSE);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-122', 'CWE-787'], 'message': 'patch 8.2.4245: \":retab 0\" may cause illegal memory access\n\nProblem: \":retab 0\" may cause illegal memory access.\nSolution: Limit the value of 'tabstop' to 10000.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: null_asynch_write (struct rw *rw,\n struct command *command,\n nbd_completion_callback cb)\n{\n int dummy = 0;\n\n if (cb.callback (cb.user_data, &dummy) == -1) {\n perror (rw->name);\n exit (EXIT_FAILURE);\n }\n} ; 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: int nfs_atomic_open(struct inode *dir, struct dentry *dentry,\n\t\t struct file *file, unsigned open_flags,\n\t\t umode_t mode)\n{\n\tDECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);\n\tstruct nfs_open_context *ctx;\n\tstruct dentry *res;\n\tstruct iattr attr = { .ia_valid = ATTR_OPEN };\n\tstruct inode *inode;\n\tunsigned int lookup_flags = 0;\n\tunsigned long dir_verifier;\n\tbool switched = false;\n\tint created = 0;\n\tint err;\n\n\t/* Expect a negative dentry */\n\tBUG_ON(d_inode(dentry));\n\n\tdfprintk(VFS, \"NFS: atomic_open(%s/%lu), %pd\\n\",\n\t\t\tdir->i_sb->s_id, dir->i_ino, dentry);\n\n\terr = nfs_check_flags(open_flags);\n\tif (err)\n\t\treturn err;\n\n\t/* NFS only supports OPEN on regular files */\n\tif ((open_flags & O_DIRECTORY)) {\n\t\tif (!d_in_lookup(dentry)) {\n\t\t\t/*\n\t\t\t * Hashed negative dentry with O_DIRECTORY: dentry was\n\t\t\t * revalidated and is fine, no need to perform lookup\n\t\t\t * again\n\t\t\t */\n\t\t\treturn -ENOENT;\n\t\t}\n\t\tlookup_flags = LOOKUP_OPEN|LOOKUP_DIRECTORY;\n\t\tgoto no_open;\n\t}\n\n\tif (dentry->d_name.len > NFS_SERVER(dir)->namelen)\n\t\treturn -ENAMETOOLONG;\n\n\tif (open_flags & O_CREAT) {\n\t\tstruct nfs_server *server = NFS_SERVER(dir);\n\n\t\tif (!(server->attr_bitmask[2] & FATTR4_WORD2_MODE_UMASK))\n\t\t\tmode &= ~current_umask();\n\n\t\tattr.ia_valid |= ATTR_MODE;\n\t\tattr.ia_mode = mode;\n\t}\n\tif (open_flags & O_TRUNC) {\n\t\tattr.ia_valid |= ATTR_SIZE;\n\t\tattr.ia_size = 0;\n\t}\n\n\tif (!(open_flags & O_CREAT) && !d_in_lookup(dentry)) {\n\t\td_drop(dentry);\n\t\tswitched = true;\n\t\tdentry = d_alloc_parallel(dentry->d_parent,\n\t\t\t\t\t &dentry->d_name, &wq);\n\t\tif (IS_ERR(dentry))\n\t\t\treturn PTR_ERR(dentry);\n\t\tif (unlikely(!d_in_lookup(dentry)))\n\t\t\treturn finish_no_open(file, dentry);\n\t}\n\n\tctx = create_nfs_open_context(dentry, open_flags, file);\n\terr = PTR_ERR(ctx);\n\tif (IS_ERR(ctx))\n\t\tgoto out;\n\n\ttrace_nfs_atomic_open_enter(dir, ctx, open_flags);\n\tinode = NFS_PROTO(dir)->open_context(dir, ctx, open_flags, &attr, &created);\n\tif (created)\n\t\tfile->f_mode |= FMODE_CREATED;\n\tif (IS_ERR(inode)) {\n\t\terr = PTR_ERR(inode);\n\t\ttrace_nfs_atomic_open_exit(dir, ctx, open_flags, err);\n\t\tput_nfs_open_context(ctx);\n\t\td_drop(dentry);\n\t\tswitch (err) {\n\t\tcase -ENOENT:\n\t\t\td_splice_alias(NULL, dentry);\n\t\t\tif (nfs_server_capable(dir, NFS_CAP_CASE_INSENSITIVE))\n\t\t\t\tdir_verifier = inode_peek_iversion_raw(dir);\n\t\t\telse\n\t\t\t\tdir_verifier = nfs_save_change_attribute(dir);\n\t\t\tnfs_set_verifier(dentry, dir_verifier);\n\t\t\tbreak;\n\t\tcase -EISDIR:\n\t\tcase -ENOTDIR:\n\t\t\tgoto no_open;\n\t\tcase -ELOOP:\n\t\t\tif (!(open_flags & O_NOFOLLOW))\n\t\t\t\tgoto no_open;\n\t\t\tbreak;\n\t\t\t/* case -EINVAL: */\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t\tgoto out;\n\t}\n\n\terr = nfs_finish_open(ctx, ctx->dentry, file, open_flags);\n\ttrace_nfs_atomic_open_exit(dir, ctx, open_flags, err);\n\tput_nfs_open_context(ctx);\nout:\n\tif (unlikely(switched)) {\n\t\td_lookup_done(dentry);\n\t\tdput(dentry);\n\t}\n\treturn err;\n\nno_open:\n\tres = nfs_lookup(dir, dentry, lookup_flags);\n\tif (switched) {\n\t\td_lookup_done(dentry);\n\t\tif (!res)\n\t\t\tres = dentry;\n\t\telse\n\t\t\tdput(dentry);\n\t}\n\tif (IS_ERR(res))\n\t\treturn PTR_ERR(res);\n\treturn finish_no_open(file, res);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-909'], 'message': 'NFSv4: Handle case where the lookup of a directory fails\n\nIf the application sets the O_DIRECTORY flag, and tries to open a\nregular file, nfs_atomic_open() will punt to doing a regular lookup.\nIf the server then returns a regular file, we will happily return a\nfile descriptor with uninitialised open state.\n\nThe fix is to return the expected ENOTDIR error in these cases.\n\nReported-by: Lyu Tao \nFixes: 0dd2b474d0b6 (\"nfs: implement i_op->atomic_open()\")\nSigned-off-by: Trond Myklebust \nSigned-off-by: Anna Schumaker '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: RawTile OpenJPEGImage::getRegion( int ha, int va, unsigned int res, int layers, int x, int y, unsigned int w, unsigned int h ){\n\n // Scale up our output bit depth to the nearest factor of 8\n unsigned int obpc = bpc;\n if( bpc <= 16 && bpc > 8 ) obpc = 16;\n else if( bpc <= 8 ) obpc = 8;\n \n#ifdef DEBUG\n Timer timer;\n timer.start();\n#endif\n\n RawTile rawtile( 0, res, ha, va, w, h, channels, obpc );\n\n if( obpc == 16 ) rawtile.data = new unsigned short[w * h * channels];\n else if( obpc == 8 ) rawtile.data = new unsigned char[w * h * channels];\n else throw file_error( \"OpenJPEG :: Unsupported number of bits\" );\n\n rawtile.dataLength = w*h*channels*(obpc/8);\n rawtile.filename = getImagePath();\n rawtile.timestamp = timestamp;\n\n process( res, layers, x, y, w, h, rawtile.data );\n\n#ifdef DEBUG\n logfile << \"OpenJPEG :: getRegion() :: \" << timer.getTime() << \" microseconds\" << endl;\n#endif\n\n return rawtile;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': '- Modified TileManager.cc to verify that malloc() has correctly allocated memory.\n- Updated numerical types to std::size_t in RawTile.h, TileManager.cc, KakaduImage.cc, OpenJPEG.cc and Transforms.cc when allocating memory via new to avoid integer overflow - fixes remaining problems identified in https://github.com/ruven/iipsrv/issues/223.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static char *ask_new_shell(char *question, char *oldshell)\n{\n\tint len;\n\tchar *ans = NULL;\n#ifdef HAVE_LIBREADLINE\n\trl_attempted_completion_function = shell_name_completion;\n#else\n\tsize_t dummy = 0;\n#endif\n\tif (!oldshell)\n\t\toldshell = \"\";\n\tprintf(\"%s [%s]:\", question, oldshell);\n#ifdef HAVE_LIBREADLINE\n\tif ((ans = readline(\" \")) == NULL)\n#else\n\tputchar(' ');\n\tfflush(stdout);\n\tif (getline(&ans, &dummy, stdin) < 0)\n#endif\n\t\treturn NULL;\n\t/* remove the newline at the end of ans. */\n\tltrim_whitespace((unsigned char *) ans);\n\tlen = rtrim_whitespace((unsigned char *) ans);\n\tif (len == 0)\n\t\treturn NULL;\n\treturn ans;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-209'], 'message': 'chsh, chfn: remove readline support [CVE-2022-0563]\n\nThe readline library uses INPUTRC= environment variable to get a path\nto the library config file. When the library cannot parse the\nspecified file, it prints an error message containing data from the\nfile.\n\nUnfortunately, the library does not use secure_getenv() (or a similar\nconcept) to avoid vulnerabilities that could occur if set-user-ID or\nset-group-ID programs.\n\nReported-by: Rory Mackie \nSigned-off-by: Karel Zak '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)\n{\n\tstruct dev_data\t\t*dev = fd->private_data;\n\tssize_t\t\t\tvalue, length = len;\n\tunsigned\t\ttotal;\n\tu32\t\t\ttag;\n\tchar\t\t\t*kbuf;\n\n\tspin_lock_irq(&dev->lock);\n\tif (dev->state > STATE_DEV_OPENED) {\n\t\tvalue = ep0_write(fd, buf, len, ptr);\n\t\tspin_unlock_irq(&dev->lock);\n\t\treturn value;\n\t}\n\tspin_unlock_irq(&dev->lock);\n\n\tif ((len < (USB_DT_CONFIG_SIZE + USB_DT_DEVICE_SIZE + 4)) ||\n\t (len > PAGE_SIZE * 4))\n\t\treturn -EINVAL;\n\n\t/* we might need to change message format someday */\n\tif (copy_from_user (&tag, buf, 4))\n\t\treturn -EFAULT;\n\tif (tag != 0)\n\t\treturn -EINVAL;\n\tbuf += 4;\n\tlength -= 4;\n\n\tkbuf = memdup_user(buf, length);\n\tif (IS_ERR(kbuf))\n\t\treturn PTR_ERR(kbuf);\n\n\tspin_lock_irq (&dev->lock);\n\tvalue = -EINVAL;\n\tif (dev->buf) {\n\t\tkfree(kbuf);\n\t\tgoto fail;\n\t}\n\tdev->buf = kbuf;\n\n\t/* full or low speed config */\n\tdev->config = (void *) kbuf;\n\ttotal = le16_to_cpu(dev->config->wTotalLength);\n\tif (!is_valid_config(dev->config, total) ||\n\t\t\ttotal > length - USB_DT_DEVICE_SIZE)\n\t\tgoto fail;\n\tkbuf += total;\n\tlength -= total;\n\n\t/* optional high speed config */\n\tif (kbuf [1] == USB_DT_CONFIG) {\n\t\tdev->hs_config = (void *) kbuf;\n\t\ttotal = le16_to_cpu(dev->hs_config->wTotalLength);\n\t\tif (!is_valid_config(dev->hs_config, total) ||\n\t\t\t\ttotal > length - USB_DT_DEVICE_SIZE)\n\t\t\tgoto fail;\n\t\tkbuf += total;\n\t\tlength -= total;\n\t} else {\n\t\tdev->hs_config = NULL;\n\t}\n\n\t/* could support multiple configs, using another encoding! */\n\n\t/* device descriptor (tweaked for paranoia) */\n\tif (length != USB_DT_DEVICE_SIZE)\n\t\tgoto fail;\n\tdev->dev = (void *)kbuf;\n\tif (dev->dev->bLength != USB_DT_DEVICE_SIZE\n\t\t\t|| dev->dev->bDescriptorType != USB_DT_DEVICE\n\t\t\t|| dev->dev->bNumConfigurations != 1)\n\t\tgoto fail;\n\tdev->dev->bcdUSB = cpu_to_le16 (0x0200);\n\n\t/* triggers gadgetfs_bind(); then we can enumerate. */\n\tspin_unlock_irq (&dev->lock);\n\tif (dev->hs_config)\n\t\tgadgetfs_driver.max_speed = USB_SPEED_HIGH;\n\telse\n\t\tgadgetfs_driver.max_speed = USB_SPEED_FULL;\n\n\tvalue = usb_gadget_probe_driver(&gadgetfs_driver);\n\tif (value != 0) {\n\t\tkfree (dev->buf);\n\t\tdev->buf = NULL;\n\t} else {\n\t\t/* at this point \"good\" hardware has for the first time\n\t\t * let the USB the host see us. alternatively, if users\n\t\t * unplug/replug that will clear all the error state.\n\t\t *\n\t\t * note: everything running before here was guaranteed\n\t\t * to choke driver model style diagnostics. from here\n\t\t * on, they can work ... except in cleanup paths that\n\t\t * kick in after the ep0 descriptor is closed.\n\t\t */\n\t\tvalue = len;\n\t\tdev->gadget_registered = true;\n\t}\n\treturn value;\n\nfail:\n\tspin_unlock_irq (&dev->lock);\n\tpr_debug (\"%s: %s fail %zd, %p\\n\", shortname, __func__, value, dev);\n\tkfree (dev->buf);\n\tdev->buf = NULL;\n\treturn value;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-763'], 'message': 'usb: gadget: don't release an existing dev->buf\n\ndev->buf does not need to be released if it already exists before\nexecuting dev_config.\n\nAcked-by: Alan Stern \nSigned-off-by: Hangyu Hua \nLink: https://lore.kernel.org/r/20211231172138.7993-2-hbh25y@gmail.com\nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: R_API RBinJavaAttrInfo *r_bin_java_stack_map_table_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut32 i = 0;\n\tut64 offset = 0;\n\tRBinJavaStackMapFrame *stack_frame = NULL, *new_stack_frame = NULL;\n\tif (sz < 10) {\n\t\treturn NULL;\n\t}\n\tRBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);\n\toffset += 6;\n\tIFDBG eprintf(\"r_bin_java_stack_map_table_attr_new: New stack map allocated.\\n\");\n\tif (!attr) {\n\t\treturn NULL;\n\t}\n\tattr->info.stack_map_table_attr.stack_map_frame_entries = r_list_newf (r_bin_java_stack_frame_free);\n\t// IFDBG r_bin_java_print_source_code_file_attr_summary(attr);\n\t// Current spec does not call for variable sizes.\n\tattr->info.stack_map_table_attr.number_of_entries = R_BIN_JAVA_USHORT (buffer, offset);\n\toffset += 2;\n\tIFDBG eprintf (\"r_bin_java_stack_map_table_attr_new: Processing stack map, summary is:\\n\");\n\tIFDBG r_bin_java_print_stack_map_table_attr_summary(attr);\n\tfor (i = 0; i < attr->info.stack_map_table_attr.number_of_entries; i++) {\n\t\t// read next stack frame\n\t\tIFDBG eprintf (\"Reading StackMap Entry #%d @ 0x%08\"PFMT64x \"\\n\", i, buf_offset + offset);\n\t\tif (stack_frame == NULL && R_BIN_JAVA_GLOBAL_BIN && R_BIN_JAVA_GLOBAL_BIN->current_code_attr) {\n\t\t\tIFDBG eprintf (\"Setting an implicit frame at #%d @ 0x%08\"PFMT64x \"\\n\", i, buf_offset + offset);\n\t\t\tstack_frame = R_BIN_JAVA_GLOBAL_BIN->current_code_attr->info.code_attr.implicit_frame;\n\t\t}\n\t\tIFDBG eprintf (\"Reading StackMap Entry #%d @ 0x%08\"PFMT64x \", current stack_frame: %p\\n\", i, buf_offset + offset, stack_frame);\n\t\tif (offset >= sz) {\n\t\t\tr_bin_java_stack_map_table_attr_free (attr);\n\t\t\treturn NULL;\n\t\t}\n\t\tnew_stack_frame = r_bin_java_stack_map_frame_new (buffer + offset, sz - offset, stack_frame, buf_offset + offset);\n\t\tif (new_stack_frame) {\n\t\t\toffset += new_stack_frame->size;\n\t\t\t// append stack frame to the list\n\t\t\tr_list_append (attr->info.stack_map_table_attr.stack_map_frame_entries, (void *) new_stack_frame);\n\t\t\tstack_frame = new_stack_frame;\n\t\t} else {\n\t\t\teprintf (\"r_bin_java_stack_map_table_attr_new: Unable to parse the stack frame for the stack map table.\\n\");\n\t\t\tr_bin_java_stack_map_table_attr_free (attr);\n\t\t\tattr = NULL;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (attr) {\n\t\tattr->size = offset;\n\t}\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 ut64 r_bin_java_element_pair_calc_size(RBinJavaElementValuePair *evp) {\n\tut64 sz = 0;\n\tif (evp == NULL) {\n\t\treturn sz;\n\t}\n\t// evp->element_name_idx = r_bin_java_read_short(bin, bin->b->cur);\n\tsz += 2;\n\t// evp->value = r_bin_java_element_value_new (bin, offset+2);\n\tif (evp->value) {\n\t\tsz += r_bin_java_element_value_calc_size (evp->value);\n\t}\n\treturn sz;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-788'], 'message': 'Improve boundary checks to fix oobread segfaults ##crash\n\n* Reported by Cen Zhang via huntr.dev\n* Reproducer: bins/fuzzed/javaoob-havoc.class'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static pyc_object *get_tuple_object(RBuffer *buffer) {\n\tpyc_object *ret = NULL;\n\tbool error = false;\n\tut32 n = 0;\n\n\tn = get_ut32 (buffer, &error);\n\tif (n > ST32_MAX) {\n\t\teprintf (\"bad marshal data (tuple size out of range)\\n\");\n\t\treturn NULL;\n\t}\n\tif (error) {\n\t\treturn NULL;\n\t}\n\tret = get_array_object_generic (buffer, n);\n\tif (ret) {\n\t\tret->type = TYPE_TUPLE;\n\t\treturn ret;\n\t}\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-825'], 'message': 'Fix UAF in pyc parser ##crash\n\n* Reported by Cen Zhang via huntr.dev\n* Reproducer: bins/fuzzed/harep2.pyc'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: storeRawNames(XML_Parser parser) {\n TAG *tag = parser->m_tagStack;\n while (tag) {\n int bufSize;\n int nameLen = sizeof(XML_Char) * (tag->name.strLen + 1);\n char *rawNameBuf = tag->buf + nameLen;\n /* Stop if already stored. Since m_tagStack is a stack, we can stop\n at the first entry that has already been copied; everything\n below it in the stack is already been accounted for in a\n previous call to this function.\n */\n if (tag->rawName == rawNameBuf)\n break;\n /* For re-use purposes we need to ensure that the\n size of tag->buf is a multiple of sizeof(XML_Char).\n */\n bufSize = nameLen + ROUND_UP(tag->rawNameLength, sizeof(XML_Char));\n if (bufSize > tag->bufEnd - tag->buf) {\n char *temp = (char *)REALLOC(parser, tag->buf, bufSize);\n if (temp == NULL)\n return XML_FALSE;\n /* if tag->name.str points to tag->buf (only when namespace\n processing is off) then we have to update it\n */\n if (tag->name.str == (XML_Char *)tag->buf)\n tag->name.str = (XML_Char *)temp;\n /* if tag->name.localPart is set (when namespace processing is on)\n then update it as well, since it will always point into tag->buf\n */\n if (tag->name.localPart)\n tag->name.localPart\n = (XML_Char *)temp + (tag->name.localPart - (XML_Char *)tag->buf);\n tag->buf = temp;\n tag->bufEnd = temp + bufSize;\n rawNameBuf = temp + nameLen;\n }\n memcpy(rawNameBuf, tag->rawName, tag->rawNameLength);\n tag->rawName = rawNameBuf;\n tag = tag->parent;\n }\n return XML_TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Prevent integer overflow in storeRawNames\n\nIt is possible to use an integer overflow in storeRawNames for out of\nboundary heap writes. Default configuration is affected. If compiled\nwith XML_UNICODE then the attack does not work. Compiling with\n-fsanitize=address confirms the following proof of concept.\n\nThe problem can be exploited by abusing the m_buffer expansion logic.\nEven though the initial size of m_buffer is a power of two, eventually\nit can end up a little bit lower, thus allowing allocations very close\nto INT_MAX (since INT_MAX/2 can be surpassed). This means that tag\nnames can be parsed which are almost INT_MAX in size.\n\nUnfortunately (from an attacker point of view) INT_MAX/2 is also a\nlimitation in string pools. Having a tag name of INT_MAX/2 characters\nor more is not possible.\n\nExpat can convert between different encodings. UTF-16 documents which\ncontain only ASCII representable characters are twice as large as their\nASCII encoded counter-parts.\n\nThe proof of concept works by taking these three considerations into\naccount:\n\n1. Move the m_buffer size slightly below a power of two by having a\n short root node . This allows the m_buffer to grow very close\n to INT_MAX.\n2. The string pooling forbids tag names longer than or equal to\n INT_MAX/2, so keep the attack tag name smaller than that.\n3. To be able to still overflow INT_MAX even though the name is\n limited at INT_MAX/2-1 (nul byte) we use UTF-16 encoding and a tag\n which only contains ASCII characters. UTF-16 always stores two\n bytes per character while the tag name is converted to using only\n one. Our attack node byte count must be a bit higher than\n 2/3 INT_MAX so the converted tag name is around INT_MAX/3 which\n in sum can overflow INT_MAX.\n\nThanks to our small root node, m_buffer can handle 2/3 INT_MAX bytes\nwithout running into INT_MAX boundary check. The string pooling is\nable to store INT_MAX/3 as tag name because the amount is below\nINT_MAX/2 limitation. And creating the sum of both eventually overflows\nin storeRawNames.\n\nProof of Concept:\n\n1. Compile expat with -fsanitize=address.\n\n2. Create Proof of Concept binary which iterates through input\n file 16 MB at once for better performance and easier integer\n calculations:\n\n```\ncat > poc.c << EOF\n #include \n #include \n #include \n #include \n\n #define CHUNK (16 * 1024 * 1024)\n int main(int argc, char *argv[]) {\n XML_Parser parser;\n FILE *fp;\n char *buf;\n int i;\n\n if (argc != 2)\n errx(1, \"usage: poc file.xml\");\n if ((parser = XML_ParserCreate(NULL)) == NULL)\n errx(1, \"failed to create expat parser\");\n if ((fp = fopen(argv[1], \"r\")) == NULL) {\n XML_ParserFree(parser);\n err(1, \"failed to open file\");\n }\n if ((buf = malloc(CHUNK)) == NULL) {\n fclose(fp);\n XML_ParserFree(parser);\n err(1, \"failed to allocate buffer\");\n }\n i = 0;\n while (fread(buf, CHUNK, 1, fp) == 1) {\n printf(\"iteration %d: XML_Parse returns %d\\n\", ++i,\n XML_Parse(parser, buf, CHUNK, XML_FALSE));\n }\n free(buf);\n fclose(fp);\n XML_ParserFree(parser);\n return 0;\n }\nEOF\ngcc -fsanitize=address -lexpat -o poc poc.c\n```\n\n3. Construct specially prepared UTF-16 XML file:\n\n```\ndd if=/dev/zero bs=1024 count=794624 | tr '\\0' 'a' > poc-utf8.xml\necho -n '<' | dd conv=notrunc of=poc-utf8.xml\necho -n '><' | dd conv=notrunc of=poc-utf8.xml bs=1 seek=805306368\niconv -f UTF-8 -t UTF-16LE poc-utf8.xml > poc-utf16.xml\n```\n\n4. Run proof of concept:\n\n```\n./poc poc-utf16.xml\n```'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static cache_accel_t *read_cache_accel(RBuffer *cache_buf, cache_hdr_t *hdr, cache_map_t *maps) {\n\tif (!cache_buf || !hdr || !hdr->accelerateInfoSize || !hdr->accelerateInfoAddr) {\n\t\treturn NULL;\n\t}\n\n\tut64 offset = va2pa (hdr->accelerateInfoAddr, hdr->mappingCount, maps, cache_buf, 0, NULL, NULL);\n\tif (!offset) {\n\t\treturn NULL;\n\t}\n\n\tut64 size = sizeof (cache_accel_t);\n\tcache_accel_t *accel = R_NEW0 (cache_accel_t);\n\tif (!accel) {\n\t\treturn NULL;\n\t}\n\n\tif (r_buf_fread_at (cache_buf, offset, (ut8*) accel, \"16il\", 1) != size) {\n\t\tR_FREE (accel);\n\t\treturn NULL;\n\t}\n\n\taccel->imagesExtrasOffset += offset;\n\taccel->bottomUpListOffset += offset;\n\taccel->dylibTrieOffset += offset;\n\taccel->initializersOffset += offset;\n\taccel->dofSectionsOffset += offset;\n\taccel->reExportListOffset += offset;\n\taccel->depListOffset += offset;\n\taccel->rangeTableOffset += offset;\n\n\treturn accel;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix heap buffer overflow in dyldcache parser ##crash\n\n* Reported by: Lazymio via huntr.dev\n* Reproducer: dyldovf'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xmlValidNormalizeAttributeValue(xmlDocPtr doc, xmlNodePtr elem,\n\t\t\t const xmlChar *name, const xmlChar *value) {\n xmlChar *ret, *dst;\n const xmlChar *src;\n xmlAttributePtr attrDecl = NULL;\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\tif ((fullname != fn) && (fullname != elem->name))\n\t xmlFree(fullname);\n }\n attrDecl = xmlGetDtdAttrDesc(doc->intSubset, elem->name, name);\n if ((attrDecl == NULL) && (doc->extSubset != NULL))\n\tattrDecl = xmlGetDtdAttrDesc(doc->extSubset, elem->name, name);\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 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 void read_module(RBuffer *b, ut64 addr, struct minidump_module *module) {\n\tst64 o_addr = r_buf_seek (b, 0, R_BUF_CUR);\n\tr_buf_seek (b, addr, R_BUF_SET);\n\tmodule->base_of_image = r_buf_read_le64 (b);\n\tmodule->size_of_image = r_buf_read_le32 (b);\n\tmodule->check_sum = r_buf_read_le32 (b);\n\tmodule->time_date_stamp = r_buf_read_le32 (b);\n\tmodule->module_name_rva = r_buf_read_le32 (b);\n\tmodule->version_info.dw_signature = r_buf_read_le32 (b);\n\tmodule->version_info.dw_struc_version = r_buf_read_le32 (b);\n\tmodule->version_info.dw_file_version_ms = r_buf_read_le32 (b);\n\tmodule->version_info.dw_file_version_ls = r_buf_read_le32 (b);\n\tmodule->version_info.dw_product_version_ms = r_buf_read_le32 (b);\n\tmodule->version_info.dw_product_version_ls = r_buf_read_le32 (b);\n\tmodule->version_info.dw_file_flags_mask = r_buf_read_le32 (b);\n\tmodule->version_info.dw_file_flags = r_buf_read_le32 (b);\n\tmodule->version_info.dw_file_os = r_buf_read_le32 (b);\n\tmodule->version_info.dw_file_type = r_buf_read_le32 (b);\n\tmodule->version_info.dw_file_subtype = r_buf_read_le32 (b);\n\tmodule->version_info.dw_file_date_ms = r_buf_read_le32 (b);\n\tmodule->version_info.dw_file_date_ls = r_buf_read_le32 (b);\n\tmodule->cv_record.data_size = r_buf_read_le32 (b);\n\tmodule->cv_record.rva = r_buf_read_le32 (b);\n\tmodule->misc_record.data_size = r_buf_read_le32 (b);\n\tmodule->misc_record.rva = r_buf_read_le32 (b);\n\tmodule->reserved_0 = r_buf_read_le64 (b);\n\tmodule->reserved_1 = r_buf_read_le64 (b);\n\tr_buf_seek (b, o_addr, R_BUF_SET);\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 bin_pe_init_metadata_hdr(RBinPEObj* pe) {\n\tPE_(image_metadata_header) * metadata = R_NEW0 (PE_(image_metadata_header));\n\tif (!metadata) {\n\t\treturn false;\n\t}\n\tPE_DWord metadata_directory = pe->clr_hdr? PE_(va2pa) (pe, pe->clr_hdr->MetaDataDirectoryAddress): 0;\n\tif (!metadata_directory) {\n\t\tfree (metadata);\n\t\treturn false;\n\t}\n\tint rr = r_buf_fread_at (pe->b, metadata_directory,\n\t\t(ut8*) metadata, pe->big_endian? \"1I2S\": \"1i2s\", 1);\n\tif (rr < 1) {\n\t\tgoto fail;\n\t}\n\n\trr = r_buf_fread_at (pe->b, metadata_directory + 8,\n\t\t(ut8*) (&metadata->Reserved), pe->big_endian? \"1I\": \"1i\", 1);\n\tif (rr < 1) {\n\t\tgoto fail;\n\t}\n\n\trr = r_buf_fread_at (pe->b, metadata_directory + 12,\n\t\t(ut8*) (&metadata->VersionStringLength), pe->big_endian? \"1I\": \"1i\", 1);\n\tif (rr < 1) {\n\t\tgoto fail;\n\t}\n\n\teprintf (\"Metadata Signature: 0x%\"PFMT64x\" 0x%\"PFMT64x\" %d\\n\",\n\t\t(ut64)metadata_directory, (ut64)metadata->Signature, (int)metadata->VersionStringLength);\n\n\t// read the version string\n\tint len = metadata->VersionStringLength; // XXX: dont trust this length\n\tif (len > 0) {\n\t\tmetadata->VersionString = calloc (1, len + 1);\n\t\tif (!metadata->VersionString) {\n\t\t\tgoto fail;\n\t\t}\n\n\t\trr = r_buf_read_at (pe->b, metadata_directory + 16, (ut8*)(metadata->VersionString), len);\n\t\tif (rr != len) {\n\t\t\teprintf (\"Warning: read (metadata header) - cannot parse version string\\n\");\n\t\t\tfree (metadata->VersionString);\n\t\t\tfree (metadata);\n\t\t\treturn 0;\n\t\t}\n\t\teprintf (\".NET Version: %s\\n\", metadata->VersionString);\n\t}\n\n\t// read the header after the string\n\trr = r_buf_fread_at (pe->b, metadata_directory + 16 + metadata->VersionStringLength,\n\t\t(ut8*) (&metadata->Flags), pe->big_endian? \"2S\": \"2s\", 1);\n\n\tif (rr < 1) {\n\t\tgoto fail;\n\t}\n\n\teprintf (\"Number of Metadata Streams: %d\\n\", metadata->NumberOfStreams);\n\tpe->metadata_header = metadata;\n\n\n\t// read metadata streams\n\tint stream_addr = metadata_directory + 20 + metadata->VersionStringLength;\n\tPE_(image_metadata_stream) * stream;\n\tPE_(image_metadata_stream) **streams = calloc (sizeof (PE_(image_metadata_stream)*), metadata->NumberOfStreams);\n\tif (!streams) {\n\t\tgoto fail;\n\t}\n\tint count;\n\tfor (count = 0; count < metadata->NumberOfStreams; count++) {\n\t\tstream = R_NEW0 (PE_(image_metadata_stream));\n\t\tif (!stream) {\n\t\t\tfree (streams);\n\t\t\tgoto fail;\n\t\t}\n\t\tif (r_buf_size (pe->b) < (stream_addr + 8 + MAX_METADATA_STRING_LENGTH)) {\n\t\t\teprintf (\"Truncated\\n\");\n\t\t\tfree (stream);\n\t\t\tfree (streams);\n\t\t\tgoto fail;\n\t\t}\n\t\tif (r_buf_fread_at (pe->b, stream_addr, (ut8*) stream, pe->big_endian? \"2I\": \"2i\", 1) < 1) {\n\t\t\tfree (stream);\n\t\t\tfree (streams);\n\t\t\tgoto fail;\n\t\t}\n\t\teprintf (\"DirectoryAddress: %x Size: %x\\n\", stream->Offset, stream->Size);\n\t\tchar* stream_name = calloc (1, MAX_METADATA_STRING_LENGTH + 1);\n\n\t\tif (!stream_name) {\n\t\t\tfree (stream);\n\t\t\tfree (streams);\n\t\t\tgoto fail;\n\t\t}\n\n\t\tint c = bin_pe_read_metadata_string (stream_name, pe->b, stream_addr + 8);\n\t\tif (c == 0) {\n\t\t\tfree (stream_name);\n\t\t\tfree (stream);\n\t\t\tfree (streams);\n\t\t\tgoto fail;\n\t\t}\n\t\teprintf (\"Stream name: %s %d\\n\", stream_name, c);\n\t\tstream->Name = stream_name;\n\t\tstreams[count] = stream;\n\t\tstream_addr += 8 + c;\n\t}\n\tpe->streams = streams;\n\treturn true;\nfail:\n\teprintf (\"Warning: read (metadata header)\\n\");\n\tfree (metadata);\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: R_API st64 r_buf_read_at(RBuffer *b, ut64 addr, ut8 *buf, ut64 len) {\n\tr_return_val_if_fail (b && buf, -1);\n\tst64 o_addr = r_buf_seek (b, 0, R_BUF_CUR);\n\tst64 r = r_buf_seek (b, addr, R_BUF_SET);\n\tif (r < 0) {\n\t\treturn r;\n\t}\n\n\tr = r_buf_read (b, buf, len);\n\tr_buf_seek (b, o_addr, R_BUF_SET);\n\treturn r;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Fix DoS in PE/QNX/DYLDCACHE/PSX parsers ##crash\n\n* Reported by lazymio\n* Reproducer: AAA4AAAAAB4='" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static size_t copy_page_to_iter_pipe(struct page *page, size_t offset, size_t bytes,\n\t\t\t struct iov_iter *i)\n{\n\tstruct pipe_inode_info *pipe = i->pipe;\n\tstruct pipe_buffer *buf;\n\tunsigned int p_tail = pipe->tail;\n\tunsigned int p_mask = pipe->ring_size - 1;\n\tunsigned int i_head = i->head;\n\tsize_t off;\n\n\tif (unlikely(bytes > i->count))\n\t\tbytes = i->count;\n\n\tif (unlikely(!bytes))\n\t\treturn 0;\n\n\tif (!sanity(i))\n\t\treturn 0;\n\n\toff = i->iov_offset;\n\tbuf = &pipe->bufs[i_head & p_mask];\n\tif (off) {\n\t\tif (offset == off && buf->page == page) {\n\t\t\t/* merge with the last one */\n\t\t\tbuf->len += bytes;\n\t\t\ti->iov_offset += bytes;\n\t\t\tgoto out;\n\t\t}\n\t\ti_head++;\n\t\tbuf = &pipe->bufs[i_head & p_mask];\n\t}\n\tif (pipe_full(i_head, p_tail, pipe->max_usage))\n\t\treturn 0;\n\n\tbuf->ops = &page_cache_pipe_buf_ops;\n\tget_page(page);\n\tbuf->page = page;\n\tbuf->offset = offset;\n\tbuf->len = bytes;\n\n\tpipe->head = i_head + 1;\n\ti->iov_offset = offset + bytes;\n\ti->head = i_head;\nout:\n\ti->count -= bytes;\n\treturn bytes;\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: nwfilterConnectNumOfNWFilters(virConnectPtr conn)\n{\n if (virConnectNumOfNWFiltersEnsureACL(conn) < 0)\n return -1;\n\n return virNWFilterObjListNumOfNWFilters(driver->nwfilters, conn,\n virConnectNumOfNWFiltersCheckACL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-667'], 'message': 'nwfilter: fix crash when counting number of network filters\n\nThe virNWFilterObjListNumOfNWFilters method iterates over the\ndriver->nwfilters, accessing virNWFilterObj instances. As such\nit needs to be protected against concurrent modification of\nthe driver->nwfilters object.\n\nThis API allows unprivileged users to connect, so users with\nread-only access to libvirt can cause a denial of service\ncrash if they are able to race with a call of virNWFilterUndefine.\nSince network filters are usually statically defined, this is\nconsidered a low severity problem.\n\nThis is assigned CVE-2022-0897.\n\nReviewed-by: Eric Blake \nSigned-off-by: Daniel P. Berrang\u00e9 '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void destroy_surface(struct swaylock_surface *surface) {\n\twl_list_remove(&surface->link);\n\tif (surface->layer_surface != NULL) {\n\t\tzwlr_layer_surface_v1_destroy(surface->layer_surface);\n\t}\n\tif (surface->surface != NULL) {\n\t\twl_surface_destroy(surface->surface);\n\t}\n\tdestroy_buffer(&surface->buffers[0]);\n\tdestroy_buffer(&surface->buffers[1]);\n\tdestroy_buffer(&surface->indicator_buffers[0]);\n\tdestroy_buffer(&surface->indicator_buffers[1]);\n\twl_output_destroy(surface->output);\n\tfree(surface);\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: local block_state deflate_huff(s, flush)\n deflate_state *s;\n int flush;\n{\n int bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we have a literal to write. */\n if (s->lookahead == 0) {\n fill_window(s);\n if (s->lookahead == 0) {\n if (flush == Z_NO_FLUSH)\n return need_more;\n break; /* flush the current block */\n }\n }\n\n /* Output a literal byte */\n s->match_length = 0;\n Tracevv((stderr,\"%c\", s->window[s->strstart]));\n _tr_tally_lit (s, s->window[s->strstart], bflush);\n s->lookahead--;\n s->strstart++;\n if (bflush) FLUSH_BLOCK(s, 0);\n }\n s->insert = 0;\n if (flush == Z_FINISH) {\n FLUSH_BLOCK(s, 1);\n return finish_done;\n }\n if (s->last_lit)\n FLUSH_BLOCK(s, 0);\n return block_done;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-787'], 'message': 'Fix a bug that can crash deflate on some input when using Z_FIXED.\n\nThis bug was reported by Danilo Ramos of Eideticom, Inc. It has\nlain in wait 13 years before being found! The bug was introduced\nin zlib 1.2.2.2, with the addition of the Z_FIXED option. That\noption forces the use of fixed Huffman codes. For rare inputs with\na large number of distant matches, the pending buffer into which\nthe compressed data is written can overwrite the distance symbol\ntable which it overlays. That results in corrupted output due to\ninvalid distances, and can result in out-of-bound accesses,\ncrashing the application.\n\nThe fix here combines the distance buffer and literal/length\nbuffers into a single symbol buffer. Now three bytes of pending\nbuffer space are opened up for each literal or length/distance\npair consumed, instead of the previous two bytes. This assures\nthat the pending buffer cannot overwrite the symbol table, since\nthe maximum fixed code compressed length/distance is 31 bits, and\nsince there are four bytes of pending space for every three bytes\nof symbol space.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void *MACH0_(mach0_free)(struct MACH0_(obj_t) *mo) {\n\tif (!mo) {\n\t\treturn NULL;\n\t}\n\n\tsize_t i;\n\tif (mo->symbols) {\n\t\tfor (i = 0; !mo->symbols[i].last; i++) {\n\t\t\tfree (mo->symbols[i].name);\n\t\t}\n\t\tfree (mo->symbols);\n\t}\n\tfree (mo->segs);\n\tfree (mo->sects);\n\tfree (mo->symtab);\n\tfree (mo->symstr);\n\tfree (mo->indirectsyms);\n\tfree (mo->imports_by_ord);\n\tht_pp_free (mo->imports_by_name);\n\tfree (mo->dyld_info);\n\tfree (mo->toc);\n\tfree (mo->modtab);\n\tfree (mo->libs);\n\tfree (mo->func_start);\n\tfree (mo->signature);\n\tfree (mo->intrp);\n\tfree (mo->compiler);\n\tif (mo->chained_starts) {\n\t\tfor (i = 0; i < mo->nsegs; i++) {\n\t\t\tif (mo->chained_starts[i]) {\n\t\t\t\tfree (mo->chained_starts[i]->page_start);\n\t\t\t\tfree (mo->chained_starts[i]);\n\t\t\t}\n\t\t}\n\t\tfree (mo->chained_starts);\n\t}\n\tr_buf_free (mo->b);\n\tfree (mo);\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Fix heap OOB read in macho.iterate_chained_fixups ##crash\n\n* Reported by peacock-doris via huntr.dev\r\n* Reproducer 'tests_65305'\r\n\r\nmrmacete:\r\n* Return early if segs_count is 0\r\n* Initialize segs_count also for reconstructed fixups\r\n\r\nCo-authored-by: pancake \r\nCo-authored-by: Francesco Tamagni '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int stimer_set_count(struct kvm_vcpu_hv_stimer *stimer, u64 count,\n\t\t\t bool host)\n{\n\tstruct kvm_vcpu *vcpu = hv_stimer_to_vcpu(stimer);\n\tstruct kvm_vcpu_hv_synic *synic = to_hv_synic(vcpu);\n\n\tif (!synic->active && !host)\n\t\treturn 1;\n\n\ttrace_kvm_hv_stimer_set_count(hv_stimer_to_vcpu(stimer)->vcpu_id,\n\t\t\t\t stimer->index, count, host);\n\n\tstimer_cleanup(stimer);\n\tstimer->count = count;\n\tif (stimer->count == 0)\n\t\tstimer->config.enable = 0;\n\telse if (stimer->config.auto_enable)\n\t\tstimer->config.enable = 1;\n\n\tif (stimer->config.enable)\n\t\tstimer_mark_pending(stimer, false);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'KVM: x86: Forbid VMM to set SYNIC/STIMER MSRs when SynIC wasn't activated\n\nSetting non-zero values to SYNIC/STIMER MSRs activates certain features,\nthis should not happen when KVM_CAP_HYPERV_SYNIC{,2} was not activated.\n\nNote, it would've been better to forbid writing anything to SYNIC/STIMER\nMSRs, including zeroes, however, at least QEMU tries clearing\nHV_X64_MSR_STIMER0_CONFIG without SynIC. HV_X64_MSR_EOM MSR is somewhat\n'special' as writing zero there triggers an action, this also should not\nhappen when SynIC wasn't activated.\n\nSigned-off-by: Vitaly Kuznetsov \nMessage-Id: <20220325132140.25650-4-vkuznets@redhat.com>\nCc: stable@vger.kernel.org\nSigned-off-by: Paolo Bonzini '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void ax25_kill_by_device(struct net_device *dev)\n{\n\tax25_dev *ax25_dev;\n\tax25_cb *s;\n\tstruct sock *sk;\n\n\tif ((ax25_dev = ax25_dev_ax25dev(dev)) == NULL)\n\t\treturn;\n\n\tspin_lock_bh(&ax25_list_lock);\nagain:\n\tax25_for_each(s, &ax25_list) {\n\t\tif (s->ax25_dev == ax25_dev) {\n\t\t\tsk = s->sk;\n\t\t\tsock_hold(sk);\n\t\t\tspin_unlock_bh(&ax25_list_lock);\n\t\t\tlock_sock(sk);\n\t\t\ts->ax25_dev = NULL;\n\t\t\tax25_dev_put(ax25_dev);\n\t\t\trelease_sock(sk);\n\t\t\tax25_disconnect(s, ENETUNREACH);\n\t\t\tspin_lock_bh(&ax25_list_lock);\n\t\t\tsock_put(sk);\n\t\t\t/* The entry could have been deleted from the\n\t\t\t * list meanwhile and thus the next pointer is\n\t\t\t * no longer valid. Play it safe and restart\n\t\t\t * the scan. Forward progress is ensured\n\t\t\t * because we set s->ax25_dev to NULL and we\n\t\t\t * are never passed a NULL 'dev' argument.\n\t\t\t */\n\t\t\tgoto again;\n\t\t}\n\t}\n\tspin_unlock_bh(&ax25_list_lock);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'ax25: fix NPD bug in ax25_disconnect\n\nThe ax25_disconnect() in ax25_kill_by_device() is not\nprotected by any locks, thus there is a race condition\nbetween ax25_disconnect() and ax25_destroy_socket().\nwhen ax25->sk is assigned as NULL by ax25_destroy_socket(),\na NULL pointer dereference bug will occur if site (1) or (2)\ndereferences ax25->sk.\n\nax25_kill_by_device() | ax25_release()\n ax25_disconnect() | ax25_destroy_socket()\n ... |\n if(ax25->sk != NULL) | ...\n ... | ax25->sk = NULL;\n bh_lock_sock(ax25->sk); //(1) | ...\n ... |\n bh_unlock_sock(ax25->sk); //(2)|\n\nThis patch moves ax25_disconnect() into lock_sock(), which can\nsynchronize with ax25_destroy_socket() in ax25_release().\n\nFail log:\n===============================================================\nBUG: kernel NULL pointer dereference, address: 0000000000000088\n...\nRIP: 0010:_raw_spin_lock+0x7e/0xd0\n...\nCall Trace:\nax25_disconnect+0xf6/0x220\nax25_device_event+0x187/0x250\nraw_notifier_call_chain+0x5e/0x70\ndev_close_many+0x17d/0x230\nrollback_registered_many+0x1f1/0x950\nunregister_netdevice_queue+0x133/0x200\nunregister_netdev+0x13/0x20\n...\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_rt_del(struct ax25_routes_struct *route)\n{\n\tax25_route *s, *t, *ax25_rt;\n\tax25_dev *ax25_dev;\n\n\tif ((ax25_dev = ax25_addr_ax25dev(&route->port_addr)) == NULL)\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\ts = ax25_rt;\n\t\tax25_rt = ax25_rt->next;\n\t\tif (s->dev == ax25_dev->dev &&\n\t\t ax25cmp(&route->dest_addr, &s->callsign) == 0) {\n\t\t\tif (ax25_route_list == s) {\n\t\t\t\tax25_route_list = s->next;\n\t\t\t\tax25_put_route(s);\n\t\t\t} else {\n\t\t\t\tfor (t = ax25_route_list; t != NULL; t = t->next) {\n\t\t\t\t\tif (t->next == s) {\n\t\t\t\t\t\tt->next = s->next;\n\t\t\t\t\t\tax25_put_route(s);\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\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: void ax25_dev_device_down(struct net_device *dev)\n{\n\tax25_dev *s, *ax25_dev;\n\n\tif ((ax25_dev = ax25_dev_ax25dev(dev)) == NULL)\n\t\treturn;\n\n\tax25_unregister_dev_sysctl(ax25_dev);\n\n\tspin_lock_bh(&ax25_dev_lock);\n\n#ifdef CONFIG_AX25_DAMA_SLAVE\n\tax25_ds_del_timer(ax25_dev);\n#endif\n\n\t/*\n\t *\tRemove any packet forwarding that points to this device.\n\t */\n\tfor (s = ax25_dev_list; s != NULL; s = s->next)\n\t\tif (s->forward == dev)\n\t\t\ts->forward = NULL;\n\n\tif ((s = ax25_dev_list) == ax25_dev) {\n\t\tax25_dev_list = s->next;\n\t\tax25_dev_put(ax25_dev);\n\t\tspin_unlock_bh(&ax25_dev_lock);\n\t\tdev->ax25_ptr = NULL;\n\t\tdev_put_track(dev, &ax25_dev->dev_tracker);\n\t\tax25_dev_put(ax25_dev);\n\t\treturn;\n\t}\n\n\twhile (s != NULL && s->next != NULL) {\n\t\tif (s->next == ax25_dev) {\n\t\t\ts->next = ax25_dev->next;\n\t\t\tax25_dev_put(ax25_dev);\n\t\t\tspin_unlock_bh(&ax25_dev_lock);\n\t\t\tdev->ax25_ptr = NULL;\n\t\t\tdev_put_track(dev, &ax25_dev->dev_tracker);\n\t\t\tax25_dev_put(ax25_dev);\n\t\t\treturn;\n\t\t}\n\n\t\ts = s->next;\n\t}\n\tspin_unlock_bh(&ax25_dev_lock);\n\tdev->ax25_ptr = NULL;\n\tax25_dev_put(ax25_dev);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'ax25: fix reference count leaks of ax25_dev\n\nThe previous commit d01ffb9eee4a (\"ax25: add refcount in ax25_dev\nto avoid UAF bugs\") introduces refcount into ax25_dev, but there\nare reference leak paths in ax25_ctl_ioctl(), ax25_fwd_ioctl(),\nax25_rt_add(), ax25_rt_del() and ax25_rt_opt().\n\nThis patch uses ax25_dev_put() and adjusts the position of\nax25_addr_ax25dev() to fix reference cout leaks of ax25_dev.\n\nFixes: d01ffb9eee4a (\"ax25: add refcount in ax25_dev to avoid UAF bugs\")\nSigned-off-by: Duoming Zhou \nReviewed-by: Dan Carpenter \nLink: https://lore.kernel.org/r/20220203150811.42256-1-duoming@zju.edu.cn\nSigned-off-by: Jakub Kicinski '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static netdev_tx_t mcba_usb_start_xmit(struct sk_buff *skb,\n\t\t\t\t struct net_device *netdev)\n{\n\tstruct mcba_priv *priv = netdev_priv(netdev);\n\tstruct can_frame *cf = (struct can_frame *)skb->data;\n\tstruct mcba_usb_ctx *ctx = NULL;\n\tstruct net_device_stats *stats = &priv->netdev->stats;\n\tu16 sid;\n\tint err;\n\tstruct mcba_usb_msg_can usb_msg = {\n\t\t.cmd_id = MBCA_CMD_TRANSMIT_MESSAGE_EV\n\t};\n\n\tif (can_dropped_invalid_skb(netdev, skb))\n\t\treturn NETDEV_TX_OK;\n\n\tctx = mcba_usb_get_free_ctx(priv, cf);\n\tif (!ctx)\n\t\treturn NETDEV_TX_BUSY;\n\n\tif (cf->can_id & CAN_EFF_FLAG) {\n\t\t/* SIDH | SIDL | EIDH | EIDL\n\t\t * 28 - 21 | 20 19 18 x x x 17 16 | 15 - 8 | 7 - 0\n\t\t */\n\t\tsid = MCBA_SIDL_EXID_MASK;\n\t\t/* store 28-18 bits */\n\t\tsid |= (cf->can_id & 0x1ffc0000) >> 13;\n\t\t/* store 17-16 bits */\n\t\tsid |= (cf->can_id & 0x30000) >> 16;\n\t\tput_unaligned_be16(sid, &usb_msg.sid);\n\n\t\t/* store 15-0 bits */\n\t\tput_unaligned_be16(cf->can_id & 0xffff, &usb_msg.eid);\n\t} else {\n\t\t/* SIDH | SIDL\n\t\t * 10 - 3 | 2 1 0 x x x x x\n\t\t */\n\t\tput_unaligned_be16((cf->can_id & CAN_SFF_MASK) << 5,\n\t\t\t\t &usb_msg.sid);\n\t\tusb_msg.eid = 0;\n\t}\n\n\tusb_msg.dlc = cf->len;\n\n\tmemcpy(usb_msg.data, cf->data, usb_msg.dlc);\n\n\tif (cf->can_id & CAN_RTR_FLAG)\n\t\tusb_msg.dlc |= MCBA_DLC_RTR_MASK;\n\n\tcan_put_echo_skb(skb, priv->netdev, ctx->ndx, 0);\n\n\terr = mcba_usb_xmit(priv, (struct mcba_usb_msg *)&usb_msg, ctx);\n\tif (err)\n\t\tgoto xmit_failed;\n\n\treturn NETDEV_TX_OK;\n\nxmit_failed:\n\tcan_free_echo_skb(priv->netdev, ctx->ndx, NULL);\n\tmcba_usb_free_ctx(ctx);\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: mcba_usb: mcba_usb_start_xmit(): fix double dev_kfree_skb in error path\n\nThere is no need to call dev_kfree_skb() when usb_submit_urb() fails\nbecause can_put_echo_skb() deletes original skb and\ncan_free_echo_skb() deletes the cloned skb.\n\nFixes: 51f3baad7de9 (\"can: mcba_usb: Add support for Microchip CAN BUS Analyzer\")\nLink: https://lore.kernel.org/all/20220311080208.45047-1-hbh25y@gmail.com\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_segments(r_bin_ne_obj_t *bin) {\n\tint i;\n\tif (!bin) {\n\t\treturn NULL;\n\t}\n\tRList *segments = r_list_newf (free);\n\tfor (i = 0; i < bin->ne_header->SegCount; i++) {\n\t\tRBinSection *bs = R_NEW0 (RBinSection);\n\t\tNE_image_segment_entry *se = &bin->segment_entries[i];\n\t\tif (!bs) {\n\t\t\treturn segments;\n\t\t}\n\t\tbs->size = se->length;\n\t\tbs->vsize = se->minAllocSz ? se->minAllocSz : 64000;\n\t\tbs->bits = R_SYS_BITS_16;\n\t\tbs->is_data = se->flags & IS_DATA;\n\t\tbs->perm = __translate_perms (se->flags);\n\t\tbs->paddr = (ut64)se->offset * bin->alignment;\n\t\tbs->name = r_str_newf (\"%s.%\" PFMT64d, se->flags & IS_MOVEABLE ? \"MOVEABLE\" : \"FIXED\", bs->paddr);\n\t\tbs->is_segment = true;\n\t\tr_list_append (segments, bs);\n\t}\n\tbin->segments = segments;\n\treturn segments;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-129'], 'message': 'Fix oobread segfaults in the NE bin parser ##crash\n\n* Reported by @han0nly via huntr.dev\n* Reproducers: seed1 seed2\n* BountyID: ad3c9c4c-76e7-40c8-bd4a-c095acd8bb40'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: CImg& _load_bmp(std::FILE *const file, const char *const filename) {\n if (!file && !filename)\n throw CImgArgumentException(_cimg_instance\n \"load_bmp(): Specified filename is (null).\",\n cimg_instance);\n\n std::FILE *const nfile = file?file:cimg::fopen(filename,\"rb\");\n CImg header(54);\n cimg::fread(header._data,54,nfile);\n if (*header!='B' || header[1]!='M') {\n if (!file) cimg::fclose(nfile);\n throw CImgIOException(_cimg_instance\n \"load_bmp(): Invalid BMP file '%s'.\",\n cimg_instance,\n filename?filename:\"(FILE*)\");\n }\n\n // Read header and pixel buffer\n int\n file_size = header[0x02] + (header[0x03]<<8) + (header[0x04]<<16) + (header[0x05]<<24),\n offset = header[0x0A] + (header[0x0B]<<8) + (header[0x0C]<<16) + (header[0x0D]<<24),\n header_size = header[0x0E] + (header[0x0F]<<8) + (header[0x10]<<16) + (header[0x11]<<24),\n dx = header[0x12] + (header[0x13]<<8) + (header[0x14]<<16) + (header[0x15]<<24),\n dy = header[0x16] + (header[0x17]<<8) + (header[0x18]<<16) + (header[0x19]<<24),\n compression = header[0x1E] + (header[0x1F]<<8) + (header[0x20]<<16) + (header[0x21]<<24),\n nb_colors = header[0x2E] + (header[0x2F]<<8) + (header[0x30]<<16) + (header[0x31]<<24),\n bpp = header[0x1C] + (header[0x1D]<<8);\n\n if (!file_size || file_size==offset) {\n cimg::fseek(nfile,0,SEEK_END);\n file_size = (int)cimg::ftell(nfile);\n cimg::fseek(nfile,54,SEEK_SET);\n }\n if (header_size>40) cimg::fseek(nfile,header_size - 40,SEEK_CUR);\n\n const int\n dx_bytes = (bpp==1)?(dx/8 + (dx%8?1:0)):((bpp==4)?(dx/2 + (dx%2)):(int)((longT)dx*bpp/8)),\n align_bytes = (4 - dx_bytes%4)%4;\n const ulongT\n cimg_iobuffer = (ulongT)24*1024*1024,\n buf_size = (ulongT)cimg::abs(dy)*(dx_bytes + align_bytes);\n\n CImg colormap;\n if (bpp<16) { if (!nb_colors) nb_colors = 1<0) cimg::fseek(nfile,xoffset,SEEK_CUR);\n\n CImg buffer;\n if (buf_size=2) for (int y = height() - 1; y>=0; --y) {\n if (buf_size>=cimg_iobuffer) {\n if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break;\n cimg::fseek(nfile,align_bytes,SEEK_CUR);\n }\n unsigned char mask = 0x80, val = 0;\n cimg_forX(*this,x) {\n if (mask==0x80) val = *(ptrs++);\n const unsigned char *col = (unsigned char*)(colormap._data + (val&mask?1:0));\n (*this)(x,y,2) = (T)*(col++);\n (*this)(x,y,1) = (T)*(col++);\n (*this)(x,y,0) = (T)*(col++);\n mask = cimg::ror(mask);\n }\n ptrs+=align_bytes;\n }\n } break;\n case 4 : { // 16 colors\n if (colormap._width>=16) for (int y = height() - 1; y>=0; --y) {\n if (buf_size>=cimg_iobuffer) {\n if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break;\n cimg::fseek(nfile,align_bytes,SEEK_CUR);\n }\n unsigned char mask = 0xF0, val = 0;\n cimg_forX(*this,x) {\n if (mask==0xF0) val = *(ptrs++);\n const unsigned char color = (unsigned char)((mask<16)?(val&mask):((val&mask)>>4));\n const unsigned char *col = (unsigned char*)(colormap._data + color);\n (*this)(x,y,2) = (T)*(col++);\n (*this)(x,y,1) = (T)*(col++);\n (*this)(x,y,0) = (T)*(col++);\n mask = cimg::ror(mask,4);\n }\n ptrs+=align_bytes;\n }\n } break;\n case 8 : { // 256 colors\n if (colormap._width>=256) for (int y = height() - 1; y>=0; --y) {\n if (buf_size>=cimg_iobuffer) {\n if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break;\n cimg::fseek(nfile,align_bytes,SEEK_CUR);\n }\n cimg_forX(*this,x) {\n const unsigned char *col = (unsigned char*)(colormap._data + *(ptrs++));\n (*this)(x,y,2) = (T)*(col++);\n (*this)(x,y,1) = (T)*(col++);\n (*this)(x,y,0) = (T)*(col++);\n }\n ptrs+=align_bytes;\n }\n } break;\n case 16 : { // 16 bits colors (RGB565)\n for (int y = height() - 1; y>=0; --y) {\n if (buf_size>=cimg_iobuffer) {\n if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break;\n cimg::fseek(nfile,align_bytes,SEEK_CUR);\n }\n cimg_forX(*this,x) {\n const unsigned char c1 = *(ptrs++), c2 = *(ptrs++);\n const unsigned short col = (unsigned short)c2<<8 | c1;\n (*this)(x,y,2) = (T)((col&0x1F)<<3);\n (*this)(x,y,1) = (T)(((col>>5)&0x3F)<<3);\n (*this)(x,y,0) = (T)(((col>>11)&0x1F)<<3);\n }\n ptrs+=align_bytes;\n }\n } break;\n case 24 : { // 24 bits colors\n for (int y = height() - 1; y>=0; --y) {\n if (buf_size>=cimg_iobuffer) {\n if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break;\n cimg::fseek(nfile,align_bytes,SEEK_CUR);\n }\n cimg_forX(*this,x) {\n (*this)(x,y,2) = (T)*(ptrs++);\n (*this)(x,y,1) = (T)*(ptrs++);\n (*this)(x,y,0) = (T)*(ptrs++);\n }\n ptrs+=align_bytes;\n }\n } break;\n case 32 : { // 32 bits colors\n for (int y = height() - 1; y>=0; --y) {\n if (buf_size>=cimg_iobuffer) {\n if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break;\n cimg::fseek(nfile,align_bytes,SEEK_CUR);\n }\n cimg_forX(*this,x) {\n (*this)(x,y,2) = (T)*(ptrs++);\n (*this)(x,y,1) = (T)*(ptrs++);\n (*this)(x,y,0) = (T)*(ptrs++);\n ++ptrs;\n }\n ptrs+=align_bytes;\n }\n } break;\n }\n if (dy<0) mirror('y');\n if (!file) cimg::fclose(nfile);\n return *this;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-770'], 'message': 'CImg<>::load_bmp() and CImg<>::load_pandore(): Check that dimensions encoded in file does not exceed file size.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: litest_utils_suite(void)\n{\n\tTCase *tc;\n\tSuite *s;\n\n\ts = suite_create(\"litest:utils\");\n\ttc = tcase_create(\"utils\");\n\n\ttcase_add_test(tc, bitfield_helpers);\n\ttcase_add_test(tc, matrix_helpers);\n\ttcase_add_test(tc, ratelimit_helpers);\n\ttcase_add_test(tc, dpi_parser);\n\ttcase_add_test(tc, wheel_click_parser);\n\ttcase_add_test(tc, wheel_click_count_parser);\n\ttcase_add_test(tc, dimension_prop_parser);\n\ttcase_add_test(tc, reliability_prop_parser);\n\ttcase_add_test(tc, calibration_prop_parser);\n\ttcase_add_test(tc, range_prop_parser);\n\ttcase_add_test(tc, boolean_prop_parser);\n\ttcase_add_test(tc, evcode_prop_parser);\n\ttcase_add_test(tc, input_prop_parser);\n\ttcase_add_test(tc, evdev_abs_parser);\n\ttcase_add_test(tc, safe_atoi_test);\n\ttcase_add_test(tc, safe_atoi_base_16_test);\n\ttcase_add_test(tc, safe_atoi_base_8_test);\n\ttcase_add_test(tc, safe_atou_test);\n\ttcase_add_test(tc, safe_atou_base_16_test);\n\ttcase_add_test(tc, safe_atou_base_8_test);\n\ttcase_add_test(tc, safe_atod_test);\n\ttcase_add_test(tc, strsplit_test);\n\ttcase_add_test(tc, strargv_test);\n\ttcase_add_test(tc, kvsplit_double_test);\n\ttcase_add_test(tc, strjoin_test);\n\ttcase_add_test(tc, strstrip_test);\n\ttcase_add_test(tc, strendswith_test);\n\ttcase_add_test(tc, strstartswith_test);\n\ttcase_add_test(tc, time_conversion);\n\ttcase_add_test(tc, human_time);\n\n\ttcase_add_test(tc, list_test_insert);\n\ttcase_add_test(tc, list_test_append);\n\ttcase_add_test(tc, list_test_foreach);\n\ttcase_add_test(tc, strverscmp_test);\n\ttcase_add_test(tc, streq_test);\n\ttcase_add_test(tc, strneq_test);\n\ttcase_add_test(tc, trunkname_test);\n\ttcase_add_test(tc, basename_test);\n\n\tsuite_add_tcase(s, tc);\n\n\treturn s;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-134'], 'message': 'evdev: strip the device name of format directives\n\nThis fixes a format string vulnerabilty.\n\nevdev_log_message() composes a format string consisting of a fixed\nprefix (including the rendered device name) and the passed-in format\nbuffer. This format string is then passed with the arguments to the\nactual log handler, which usually and eventually ends up being printf.\n\nIf the device name contains a printf-style format directive, these ended\nup in the format string and thus get interpreted correctly, e.g. for a\ndevice \"Foo%sBar\" the log message vs printf invocation ends up being:\n evdev_log_message(device, \"some message %s\", \"some argument\");\n printf(\"event9 - Foo%sBar: some message %s\", \"some argument\");\n\nThis can enable an attacker to execute malicious code with the\nprivileges of the process using libinput.\n\nTo exploit this, an attacker needs to be able to create a kernel device\nwith a malicious name, e.g. through /dev/uinput or a Bluetooth device.\n\nTo fix this, convert any potential format directives in the device name\nby duplicating percentages.\n\nPre-rendering the device to avoid the issue altogether would be nicer\nbut the current log level hooks do not easily allow for this. The device\nname is the only user-controlled part of the format string.\n\nA second potential issue is the sysname of the device which is also\nsanitized.\n\nThis issue was found by Albin Eldst\u00e5l-Ahrens and Benjamin Svensson from\nAssured AB, and independently by Lukas Lamster.\n\nFixes #752\n\nSigned-off-by: Peter Hutterer \n(cherry picked from commit a423d7d3269dc32a87384f79e29bb5ac021c83d1)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void free_clt(struct rtrs_clt_sess *clt)\n{\n\tfree_permits(clt);\n\tfree_percpu(clt->pcpu_path);\n\tmutex_destroy(&clt->paths_ev_mutex);\n\tmutex_destroy(&clt->paths_mutex);\n\t/* release callback will free clt in last put */\n\tdevice_unregister(&clt->dev);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'RDMA/rtrs-clt: Fix possible double free in error case\n\nCallback function rtrs_clt_dev_release() for put_device() calls kfree(clt)\nto free memory. We shouldn't call kfree(clt) again, and we can't use the\nclt after kfree too.\n\nReplace device_register() with device_initialize() and device_add() so that\ndev_set_name can() be used appropriately.\n\nMove mutex_destroy() to the release function so it can be called in\nthe alloc_clt err path.\n\nFixes: eab098246625 (\"RDMA/rtrs-clt: Refactor the failure cases in alloc_clt\")\nLink: https://lore.kernel.org/r/20220217030929.323849-1-haris.iqbal@ionos.com\nReported-by: Miaoqian Lin \nSigned-off-by: Md Haris Iqbal \nReviewed-by: Jack Wang \nSigned-off-by: Jason Gunthorpe '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: RCoreSymCacheElement *r_coresym_cache_element_new(RBinFile *bf, RBuffer *buf, ut64 off, int bits, char * file_name) {\n\tRCoreSymCacheElement *result = NULL;\n\tut8 *b = NULL;\n\tRCoreSymCacheElementHdr *hdr = r_coresym_cache_element_header_new (buf, off, bits);\n\tif (!hdr) {\n\t\treturn NULL;\n\t}\n\tif (hdr->version != 1) {\n\t\teprintf (\"Unsupported CoreSymbolication cache version (%d)\\n\", hdr->version);\n\t\tgoto beach;\n\t}\n\tif (hdr->size == 0 || hdr->size > r_buf_size (buf) - off) {\n\t\teprintf (\"Corrupted CoreSymbolication header: size out of bounds (0x%x)\\n\", hdr->size);\n\t\tgoto beach;\n\t}\n\tresult = R_NEW0 (RCoreSymCacheElement);\n\tif (!result) {\n\t\tgoto beach;\n\t}\n\tresult->hdr = hdr;\n\tb = malloc (hdr->size);\n\tif (!b) {\n\t\tgoto beach;\n\t}\n\tif (r_buf_read_at (buf, off, b, hdr->size) != hdr->size) {\n\t\tgoto beach;\n\t}\n\tut8 *end = b + hdr->size;\n\tif (file_name) {\n\t\tresult->file_name = file_name;\n\t} else if (hdr->file_name_off) {\n\t\tresult->file_name = str_dup_safe (b, b + (size_t)hdr->file_name_off, end);\n\t}\n\tif (hdr->version_off) {\n\t\tresult->binary_version = str_dup_safe (b, b + (size_t)hdr->version_off, end);\n\t}\n\tconst size_t word_size = bits / 8;\n\tconst ut64 start_of_sections = (ut64)hdr->n_segments * R_CS_EL_SIZE_SEG + R_CS_EL_OFF_SEGS;\n\tconst ut64 sect_size = (bits == 32) ? R_CS_EL_SIZE_SECT_32 : R_CS_EL_SIZE_SECT_64;\n\tconst ut64 start_of_symbols = start_of_sections + (ut64)hdr->n_sections * sect_size;\n\tconst ut64 start_of_lined_symbols = start_of_symbols + (ut64)hdr->n_symbols * R_CS_EL_SIZE_SYM;\n\tconst ut64 start_of_line_info = start_of_lined_symbols + (ut64)hdr->n_lined_symbols * R_CS_EL_SIZE_LSYM;\n\tconst ut64 start_of_unknown_pairs = start_of_line_info + (ut64)hdr->n_line_info * R_CS_EL_SIZE_LINFO;\n\tconst ut64 start_of_strings = start_of_unknown_pairs + (ut64)hdr->n_symbols * 8;\n\n\tut64 page_zero_size = 0;\n\tsize_t page_zero_idx = 0;\n\tif (UT32_MUL_OVFCHK (hdr->n_segments, sizeof (RCoreSymCacheElementSegment))) {\n\t\tgoto beach;\n\t} else if (UT32_MUL_OVFCHK (hdr->n_sections, sizeof (RCoreSymCacheElementSection))) {\n\t\tgoto beach;\n\t} else if (UT32_MUL_OVFCHK (hdr->n_symbols, sizeof (RCoreSymCacheElementSymbol))) {\n\t\tgoto beach;\n\t} else if (UT32_MUL_OVFCHK (hdr->n_lined_symbols, sizeof (RCoreSymCacheElementLinedSymbol))) {\n\t\tgoto beach;\n\t} else if (UT32_MUL_OVFCHK (hdr->n_line_info, sizeof (RCoreSymCacheElementLineInfo))) {\n\t\tgoto beach;\n\t}\n\tif (hdr->n_segments > 0) {\n\t\tresult->segments = R_NEWS0 (RCoreSymCacheElementSegment, hdr->n_segments);\n\t\tif (!result->segments) {\n\t\t\tgoto beach;\n\t\t}\n\t\tsize_t i;\n\t\tut8 *cursor = b + R_CS_EL_OFF_SEGS;\n\t\tfor (i = 0; i < hdr->n_segments && cursor + sizeof (RCoreSymCacheElementSegment) < end; i++) {\n\t\t\tRCoreSymCacheElementSegment *seg = &result->segments[i];\n\t\t\tseg->paddr = seg->vaddr = r_read_le64 (cursor);\n\t\t\tcursor += 8;\n\t\t\tif (cursor >= end) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tseg->size = seg->vsize = r_read_le64 (cursor);\n\t\t\tcursor += 8;\n\t\t\tif (cursor >= end) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tseg->name = str_dup_safe_fixed (b, cursor, 16, end);\n\t\t\tcursor += 16;\n\t\t\tif (!seg->name) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!strcmp (seg->name, \"__PAGEZERO\")) {\n\t\t\t\tpage_zero_size = seg->size;\n\t\t\t\tpage_zero_idx = i;\n\t\t\t\tseg->paddr = seg->vaddr = 0;\n\t\t\t\tseg->size = 0;\n\t\t\t}\n\t\t}\n\t\tfor (i = 0; i < hdr->n_segments && page_zero_size > 0; i++) {\n\t\t\tif (i == page_zero_idx) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tRCoreSymCacheElementSegment *seg = &result->segments[i];\n\t\t\tif (seg->vaddr < page_zero_size) {\n\t\t\t\tseg->vaddr += page_zero_size;\n\t\t\t}\n\t\t}\n\t}\n\tbool relative_to_strings = false;\n\tut8* string_origin;\n\tif (hdr->n_sections > 0) {\n\t\tresult->sections = R_NEWS0 (RCoreSymCacheElementSection, hdr->n_sections);\n\t\tif (!result->sections) {\n\t\t\tgoto beach;\n\t\t}\n\t\tsize_t i;\n\t\tut8 *cursor = b + start_of_sections;\n\t\tfor (i = 0; i < hdr->n_sections && cursor < end; i++) {\n\t\t\tut8 *sect_start = cursor;\n\t\t\tRCoreSymCacheElementSection *sect = &result->sections[i];\n\t\t\tsect->vaddr = sect->paddr = r_read_ble (cursor, false, bits);\n\t\t\tif (sect->vaddr < page_zero_size) {\n\t\t\t\tsect->vaddr += page_zero_size;\n\t\t\t}\n\t\t\tcursor += word_size;\n\t\t\tif (cursor + word_size >= end) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tsect->size = r_read_ble (cursor, false, bits);\n\t\t\tcursor += word_size;\n\t\t\tif (cursor + word_size >= end) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tut64 sect_name_off = r_read_ble (cursor, false, bits);\n\t\t\tif (!i && !sect_name_off) {\n\t\t\t\trelative_to_strings = true;\n\t\t\t}\n\t\t\tcursor += word_size;\n\t\t\tif (bits == 32) {\n\t\t\t\tcursor += word_size;\n\t\t\t}\n\t\t\tstring_origin = relative_to_strings? b + start_of_strings : sect_start;\n\t\t\tif (sect_name_off < (ut64)(size_t)(end - string_origin)) {\n\t\t\t\tsect->name = str_dup_safe (b, string_origin + sect_name_off, end);\n\t\t\t} else {\n\t\t\t\tsect->name = strdup (\"\");\n\t\t\t}\n\t\t}\n\t}\n\tif (hdr->n_symbols) {\n\t\tresult->symbols = R_NEWS0 (RCoreSymCacheElementSymbol, hdr->n_symbols);\n\t\tif (!result->symbols) {\n\t\t\tgoto beach;\n\t\t}\n\t\tsize_t i;\n\t\tut8 *cursor = b + start_of_symbols;\n\t\tfor (i = 0; i < hdr->n_symbols && cursor + R_CS_EL_SIZE_SYM <= end; i++) {\n\t\t\tRCoreSymCacheElementSymbol *sym = &result->symbols[i];\n\t\t\tsym->paddr = r_read_le32 (cursor);\n\t\t\tsym->size = r_read_le32 (cursor + 0x4);\n\t\t\tsym->unk1 = r_read_le32 (cursor + 0x8);\n\t\t\tsize_t name_off = r_read_le32 (cursor + 0xc);\n\t\t\tsize_t mangled_name_off = r_read_le32 (cursor + 0x10);\n\t\t\tsym->unk2 = (st32)r_read_le32 (cursor + 0x14);\n\t\t\tstring_origin = relative_to_strings? b + start_of_strings : cursor;\n\t\t\tsym->name = str_dup_safe (b, string_origin + name_off, end);\n\t\t\tif (!sym->name) {\n\t\t\t\tcursor += R_CS_EL_SIZE_SYM;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tstring_origin = relative_to_strings? b + start_of_strings : cursor;\n\t\t\tsym->mangled_name = str_dup_safe (b, string_origin + mangled_name_off, end);\n\t\t\tif (!sym->mangled_name) {\n\t\t\t\tcursor += R_CS_EL_SIZE_SYM;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcursor += R_CS_EL_SIZE_SYM;\n\t\t}\n\t}\n\tif (hdr->n_lined_symbols) {\n\t\tresult->lined_symbols = R_NEWS0 (RCoreSymCacheElementLinedSymbol, hdr->n_lined_symbols);\n\t\tif (!result->lined_symbols) {\n\t\t\tgoto beach;\n\t\t}\n\t\tsize_t i;\n\t\tut8 *cursor = b + start_of_lined_symbols;\n\t\tfor (i = 0; i < hdr->n_lined_symbols && cursor + R_CS_EL_SIZE_LSYM <= end; i++) {\n\t\t\tRCoreSymCacheElementLinedSymbol *lsym = &result->lined_symbols[i];\n\t\t\tlsym->sym.paddr = r_read_le32 (cursor);\n\t\t\tlsym->sym.size = r_read_le32 (cursor + 0x4);\n\t\t\tlsym->sym.unk1 = r_read_le32 (cursor + 0x8);\n\t\t\tsize_t name_off = r_read_le32 (cursor + 0xc);\n\t\t\tsize_t mangled_name_off = r_read_le32 (cursor + 0x10);\n\t\t\tlsym->sym.unk2 = (st32)r_read_le32 (cursor + 0x14);\n\t\t\tsize_t file_name_off = r_read_le32 (cursor + 0x18);\n\t\t\tlsym->flc.line = r_read_le32 (cursor + 0x1c);\n\t\t\tlsym->flc.col = r_read_le32 (cursor + 0x20);\n\t\t\tstring_origin = relative_to_strings? b + start_of_strings : cursor;\n\t\t\tlsym->sym.name = str_dup_safe (b, string_origin + name_off, end);\n\t\t\tif (!lsym->sym.name) {\n\t\t\t\tcursor += R_CS_EL_SIZE_LSYM;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tstring_origin = relative_to_strings? b + start_of_strings : cursor;\n\t\t\tlsym->sym.mangled_name = str_dup_safe (b, string_origin + mangled_name_off, end);\n\t\t\tif (!lsym->sym.mangled_name) {\n\t\t\t\tcursor += R_CS_EL_SIZE_LSYM;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tstring_origin = relative_to_strings? b + start_of_strings : cursor;\n\t\t\tlsym->flc.file = str_dup_safe (b, string_origin + file_name_off, end);\n\t\t\tif (!lsym->flc.file) {\n\t\t\t\tcursor += R_CS_EL_SIZE_LSYM;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcursor += R_CS_EL_SIZE_LSYM;\n\t\t\tmeta_add_fileline (bf, r_coresym_cache_element_pa2va (result, lsym->sym.paddr), lsym->sym.size, &lsym->flc);\n\t\t}\n\t}\n\tif (hdr->n_line_info) {\n\t\tresult->line_info = R_NEWS0 (RCoreSymCacheElementLineInfo, hdr->n_line_info);\n\t\tif (!result->line_info) {\n\t\t\tgoto beach;\n\t\t}\n\t\tsize_t i;\n\t\tut8 *cursor = b + start_of_line_info;\n\t\tfor (i = 0; i < hdr->n_line_info && cursor + R_CS_EL_SIZE_LINFO <= end; i++) {\n\t\t\tRCoreSymCacheElementLineInfo *info = &result->line_info[i];\n\t\t\tinfo->paddr = r_read_le32 (cursor);\n\t\t\tinfo->size = r_read_le32 (cursor + 4);\n\t\t\tsize_t file_name_off = r_read_le32 (cursor + 8);\n\t\t\tinfo->flc.line = r_read_le32 (cursor + 0xc);\n\t\t\tinfo->flc.col = r_read_le32 (cursor + 0x10);\n\t\t\tstring_origin = relative_to_strings? b + start_of_strings : cursor;\n\t\t\tinfo->flc.file = str_dup_safe (b, string_origin + file_name_off, end);\n\t\t\tif (!info->flc.file) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcursor += R_CS_EL_SIZE_LINFO;\n\t\t\tmeta_add_fileline (bf, r_coresym_cache_element_pa2va (result, info->paddr), info->size, &info->flc);\n\t\t}\n\t}\n\n\t/*\n\t * TODO:\n\t * Figure out the meaning of the 2 arrays of hdr->n_symbols\n\t * 32-bit integers located at the end of line info.\n\t * Those are the last info before the strings at the end.\n\t */\n\nbeach:\n\tfree (b);\n\treturn result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-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\t\t\t bool poll_only)\n\t__must_hold(&ctx->completion_lock)\n{\n\tstruct hlist_head *list;\n\tstruct io_kiocb *req;\n\n\tlist = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];\n\thlist_for_each_entry(req, list, hash_node) {\n\t\tif (sqe_addr != req->user_data)\n\t\t\tcontinue;\n\t\tif (poll_only && req->opcode != IORING_OP_POLL_ADD)\n\t\t\tcontinue;\n\t\treturn req;\n\t}\n\treturn NULL; ; 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_decode_infl(unsigned char *decoded, int *decoded_size, const unsigned char *rule) {\n int pos = *decoded_size;\n char mod = 'i';\n char dir = '<';\n char olddir;\n unsigned char c;\n while ((c = *rule++)) {\n if (c <= 4) {\n mod = (c <= 2) ? 'i' : 'd'; /* insert, delete */\n olddir = dir;\n dir = (c & 2) ? '<' : '>'; /* left, right */\n if (olddir != dir && olddir) {\n pos = (c & 2) ? *decoded_size : 0;\n }\n }\n else if (c > 10 && c < 20) {\n if (dir == '>') {\n pos = *decoded_size;\n }\n pos -= c - 10;\n dir = 0;\n if (pos < 0 || pos > *decoded_size) {\n debug_print(\"Position setting failed (%s)\\n\", decoded);\n return MOBI_DATA_CORRUPT;\n }\n }\n else {\n if (mod == 'i') {\n const unsigned char *s = decoded + pos;\n unsigned char *d = decoded + pos + 1;\n const int l = *decoded_size - pos;\n if (l < 0 || d + l > decoded + INDX_INFLBUF_SIZEMAX) {\n debug_print(\"Out of buffer in %s at pos: %i\\n\", decoded, pos);\n return MOBI_DATA_CORRUPT;\n }\n memmove(d, s, (size_t) l);\n decoded[pos] = c;\n (*decoded_size)++;\n if (dir == '>') { pos++; }\n } else {\n if (dir == '<') { pos--; }\n const unsigned char *s = decoded + pos + 1;\n unsigned char *d = decoded + pos;\n const int l = *decoded_size - pos;\n if (l < 0 || d + l > decoded + INDX_INFLBUF_SIZEMAX) {\n debug_print(\"Out of buffer in %s at pos: %i\\n\", decoded, pos);\n return MOBI_DATA_CORRUPT;\n }\n if (decoded[pos] != c) {\n debug_print(\"Character mismatch in %s at pos: %i (%c != %c)\\n\", decoded, pos, decoded[pos], c);\n return MOBI_DATA_CORRUPT;\n }\n memmove(d, s, (size_t) l);\n (*decoded_size)--;\n }\n }\n }\n return MOBI_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Fix wrong boundary checks in inflections parser resulting in stack 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_Solid(int width, int height, SDL_Color fg, Uint32 *color)\n{\n const int alignment = Get_Alignement() - 1;\n SDL_Surface *textbuf;\n Sint64 size;\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 = 1;\n\n /* Fill the palette: 1 is foreground */\n {\n SDL_Palette *palette = textbuf->format->palette;\n palette->colors[0].r = 255 - fg.r;\n palette->colors[0].g = 255 - fg.g;\n palette->colors[0].b = 255 - fg.b;\n palette->colors[1].r = fg.r;\n palette->colors[1].g = fg.g;\n palette->colors[1].b = fg.b;\n palette->colors[1].a = fg.a;\n }\n\n SDL_SetColorKey(textbuf, SDL_TRUE, 0);\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: xmlBufferCreateSize(size_t size) {\n xmlBufferPtr ret;\n\n ret = (xmlBufferPtr) xmlMalloc(sizeof(xmlBuffer));\n if (ret == NULL) {\n\txmlTreeErrMemory(\"creating buffer\");\n return(NULL);\n }\n ret->use = 0;\n ret->alloc = xmlBufferAllocScheme;\n ret->size = (size ? size+2 : 0); /* +1 for ending null */\n if (ret->size){\n ret->content = (xmlChar *) xmlMallocAtomic(ret->size * sizeof(xmlChar));\n if (ret->content == NULL) {\n\t xmlTreeErrMemory(\"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[MaxTextExtent];\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 PixelPacket\n *q;\n\n size_t\n extent,\n length;\n\n ssize_t\n count,\n y;\n\n unsigned char\n magick[4],\n *pixels;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n 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);\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);\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);\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);\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);\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);\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 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 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);\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);\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);\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,\n sizeof(cin.film.format));\n (void) SetImageProperty(image,\"dpx:film.format\",property);\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);\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);\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 void *) NULL,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);\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);\n if (status == MagickFalse)\n {\n InheritException(exception,&image->exception);\n return(DestroyImageList(image));\n }\n (void) SetImageBackgroundColor(image);\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 extent=GetQuantumExtent(image,quantum_info,quantum_type);\n (void) extent;\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 == (PixelPacket *) NULL)\n break;\n stream=ReadBlobStream(image,length,pixels,&count);\n if (count != (ssize_t) 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);\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 kdb_local(kdb_reason_t reason, int error, struct pt_regs *regs,\n\t\t kdb_dbtrap_t db_result)\n{\n\tchar *cmdbuf;\n\tint diag;\n\tstruct task_struct *kdb_current =\n\t\tkdb_curr_task(raw_smp_processor_id());\n\n\tKDB_DEBUG_STATE(\"kdb_local 1\", reason);\n\tkdb_go_count = 0;\n\tif (reason == KDB_REASON_DEBUG) {\n\t\t/* special case below */\n\t} else {\n\t\tkdb_printf(\"\\nEntering kdb (current=0x%px, pid %d) \",\n\t\t\t kdb_current, kdb_current ? kdb_current->pid : 0);\n#if defined(CONFIG_SMP)\n\t\tkdb_printf(\"on processor %d \", raw_smp_processor_id());\n#endif\n\t}\n\n\tswitch (reason) {\n\tcase KDB_REASON_DEBUG:\n\t{\n\t\t/*\n\t\t * If re-entering kdb after a single step\n\t\t * command, don't print the message.\n\t\t */\n\t\tswitch (db_result) {\n\t\tcase KDB_DB_BPT:\n\t\t\tkdb_printf(\"\\nEntering kdb (0x%px, pid %d) \",\n\t\t\t\t kdb_current, kdb_current->pid);\n#if defined(CONFIG_SMP)\n\t\t\tkdb_printf(\"on processor %d \", raw_smp_processor_id());\n#endif\n\t\t\tkdb_printf(\"due to Debug @ \" kdb_machreg_fmt \"\\n\",\n\t\t\t\t instruction_pointer(regs));\n\t\t\tbreak;\n\t\tcase KDB_DB_SS:\n\t\t\tbreak;\n\t\tcase KDB_DB_SSBPT:\n\t\t\tKDB_DEBUG_STATE(\"kdb_local 4\", reason);\n\t\t\treturn 1;\t/* kdba_db_trap did the work */\n\t\tdefault:\n\t\t\tkdb_printf(\"kdb: Bad result from kdba_db_trap: %d\\n\",\n\t\t\t\t db_result);\n\t\t\tbreak;\n\t\t}\n\n\t}\n\t\tbreak;\n\tcase KDB_REASON_ENTER:\n\t\tif (KDB_STATE(KEYBOARD))\n\t\t\tkdb_printf(\"due to Keyboard Entry\\n\");\n\t\telse\n\t\t\tkdb_printf(\"due to KDB_ENTER()\\n\");\n\t\tbreak;\n\tcase KDB_REASON_KEYBOARD:\n\t\tKDB_STATE_SET(KEYBOARD);\n\t\tkdb_printf(\"due to Keyboard Entry\\n\");\n\t\tbreak;\n\tcase KDB_REASON_ENTER_SLAVE:\n\t\t/* drop through, slaves only get released via cpu switch */\n\tcase KDB_REASON_SWITCH:\n\t\tkdb_printf(\"due to cpu switch\\n\");\n\t\tbreak;\n\tcase KDB_REASON_OOPS:\n\t\tkdb_printf(\"Oops: %s\\n\", kdb_diemsg);\n\t\tkdb_printf(\"due to oops @ \" kdb_machreg_fmt \"\\n\",\n\t\t\t instruction_pointer(regs));\n\t\tkdb_dumpregs(regs);\n\t\tbreak;\n\tcase KDB_REASON_SYSTEM_NMI:\n\t\tkdb_printf(\"due to System NonMaskable Interrupt\\n\");\n\t\tbreak;\n\tcase KDB_REASON_NMI:\n\t\tkdb_printf(\"due to NonMaskable Interrupt @ \"\n\t\t\t kdb_machreg_fmt \"\\n\",\n\t\t\t instruction_pointer(regs));\n\t\tbreak;\n\tcase KDB_REASON_SSTEP:\n\tcase KDB_REASON_BREAK:\n\t\tkdb_printf(\"due to %s @ \" kdb_machreg_fmt \"\\n\",\n\t\t\t reason == KDB_REASON_BREAK ?\n\t\t\t \"Breakpoint\" : \"SS trap\", instruction_pointer(regs));\n\t\t/*\n\t\t * Determine if this breakpoint is one that we\n\t\t * are interested in.\n\t\t */\n\t\tif (db_result != KDB_DB_BPT) {\n\t\t\tkdb_printf(\"kdb: error return from kdba_bp_trap: %d\\n\",\n\t\t\t\t db_result);\n\t\t\tKDB_DEBUG_STATE(\"kdb_local 6\", reason);\n\t\t\treturn 0;\t/* Not for us, dismiss it */\n\t\t}\n\t\tbreak;\n\tcase KDB_REASON_RECURSE:\n\t\tkdb_printf(\"due to Recursion @ \" kdb_machreg_fmt \"\\n\",\n\t\t\t instruction_pointer(regs));\n\t\tbreak;\n\tdefault:\n\t\tkdb_printf(\"kdb: unexpected reason code: %d\\n\", reason);\n\t\tKDB_DEBUG_STATE(\"kdb_local 8\", reason);\n\t\treturn 0;\t/* Not for us, dismiss it */\n\t}\n\n\twhile (1) {\n\t\t/*\n\t\t * Initialize pager context.\n\t\t */\n\t\tkdb_nextline = 1;\n\t\tKDB_STATE_CLEAR(SUPPRESS);\n\t\tkdb_grepping_flag = 0;\n\t\t/* ensure the old search does not leak into '/' commands */\n\t\tkdb_grep_string[0] = '\\0';\n\n\t\tcmdbuf = cmd_cur;\n\t\t*cmdbuf = '\\0';\n\t\t*(cmd_hist[cmd_head]) = '\\0';\n\ndo_full_getstr:\n\t\t/* PROMPT can only be set if we have MEM_READ permission. */\n\t\tsnprintf(kdb_prompt_str, CMD_BUFLEN, kdbgetenv(\"PROMPT\"),\n\t\t\t raw_smp_processor_id());\n\t\tif (defcmd_in_progress)\n\t\t\tstrncat(kdb_prompt_str, \"[defcmd]\", CMD_BUFLEN);\n\n\t\t/*\n\t\t * Fetch command from keyboard\n\t\t */\n\t\tcmdbuf = kdb_getstr(cmdbuf, CMD_BUFLEN, kdb_prompt_str);\n\t\tif (*cmdbuf != '\\n') {\n\t\t\tif (*cmdbuf < 32) {\n\t\t\t\tif (cmdptr == cmd_head) {\n\t\t\t\t\tstrscpy(cmd_hist[cmd_head], cmd_cur,\n\t\t\t\t\t\tCMD_BUFLEN);\n\t\t\t\t\t*(cmd_hist[cmd_head] +\n\t\t\t\t\t strlen(cmd_hist[cmd_head])-1) = '\\0';\n\t\t\t\t}\n\t\t\t\tif (!handle_ctrl_cmd(cmdbuf))\n\t\t\t\t\t*(cmd_cur+strlen(cmd_cur)-1) = '\\0';\n\t\t\t\tcmdbuf = cmd_cur;\n\t\t\t\tgoto do_full_getstr;\n\t\t\t} else {\n\t\t\t\tstrscpy(cmd_hist[cmd_head], cmd_cur,\n\t\t\t\t\tCMD_BUFLEN);\n\t\t\t}\n\n\t\t\tcmd_head = (cmd_head+1) % KDB_CMD_HISTORY_COUNT;\n\t\t\tif (cmd_head == cmd_tail)\n\t\t\t\tcmd_tail = (cmd_tail+1) % KDB_CMD_HISTORY_COUNT;\n\t\t}\n\n\t\tcmdptr = cmd_head;\n\t\tdiag = kdb_parse(cmdbuf);\n\t\tif (diag == KDB_NOTFOUND) {\n\t\t\tdrop_newline(cmdbuf);\n\t\t\tkdb_printf(\"Unknown kdb command: '%s'\\n\", cmdbuf);\n\t\t\tdiag = 0;\n\t\t}\n\t\tif (diag == KDB_CMD_GO\n\t\t || diag == KDB_CMD_CPU\n\t\t || diag == KDB_CMD_SS\n\t\t || diag == KDB_CMD_KGDB)\n\t\t\tbreak;\n\n\t\tif (diag)\n\t\t\tkdb_cmderror(diag);\n\t}\n\tKDB_DEBUG_STATE(\"kdb_local 9\", diag);\n\treturn diag;\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_fw_download(struct nfc_dev *dev, const char *firmware_name)\n{\n\tint rc = 0;\n\n\tpr_debug(\"%s do firmware %s\\n\", dev_name(&dev->dev), firmware_name);\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 = -EBUSY;\n\t\tgoto error;\n\t}\n\n\tif (!dev->ops->fw_download) {\n\t\trc = -EOPNOTSUPP;\n\t\tgoto error;\n\t}\n\n\tdev->fw_download_in_progress = true;\n\trc = dev->ops->fw_download(dev, firmware_name);\n\tif (rc)\n\t\tdev->fw_download_in_progress = false;\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: buflist_match(\n regmatch_T\t*rmp,\n buf_T\t*buf,\n int\t\tignore_case) // when TRUE ignore case, when FALSE use 'fic'\n{\n char_u\t*match;\n\n // First try the short file name, then the long file name.\n match = fname_match(rmp, buf->b_sfname, ignore_case);\n if (match == NULL)\n\tmatch = fname_match(rmp, buf->b_ffname, ignore_case);\n\n return match;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'patch 8.2.4938: crash when matching buffer with invalid pattern\n\nProblem: Crash when matching buffer with invalid pattern.\nSolution: Check for NULL regprog.'" }, { "text": "[INST] Given the following code containing errors, provide Common 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_image_props (XcfInfo *info,\n GimpImage *image)\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_COLORMAP:\n {\n guint32 n_colors;\n guchar cmap[GIMP_IMAGE_COLORMAP_SIZE];\n\n xcf_read_int32 (info, &n_colors, 1);\n\n if (n_colors > (GIMP_IMAGE_COLORMAP_SIZE / 3))\n {\n gimp_message (info->gimp, G_OBJECT (info->progress),\n GIMP_MESSAGE_ERROR,\n \"Maximum colormap size (%d) exceeded\",\n GIMP_IMAGE_COLORMAP_SIZE);\n return FALSE;\n }\n\n if (info->file_version == 0)\n {\n gint i;\n\n gimp_message_literal (info->gimp, G_OBJECT (info->progress),\n GIMP_MESSAGE_WARNING,\n _(\"XCF warning: version 0 of XCF file format\\n\"\n \"did not save indexed colormaps correctly.\\n\"\n \"Substituting grayscale map.\"));\n\n if (! xcf_seek_pos (info, info->cp + n_colors, NULL))\n return FALSE;\n\n for (i = 0; i < n_colors; i++)\n {\n cmap[i * 3 + 0] = i;\n cmap[i * 3 + 1] = i;\n cmap[i * 3 + 2] = i;\n }\n }\n else\n {\n xcf_read_int8 (info, cmap, n_colors * 3);\n }\n\n /* only set color map if image is indexed, this is just\n * sanity checking to make sure gimp doesn't end up with\n * an image state that is impossible.\n */\n if (gimp_image_get_base_type (image) == GIMP_INDEXED)\n gimp_image_set_colormap (image, cmap, n_colors, FALSE);\n\n GIMP_LOG (XCF, \"prop colormap n_colors=%d\", n_colors);\n }\n break;\n\n case PROP_COMPRESSION:\n {\n guint8 compression;\n\n xcf_read_int8 (info, (guint8 *) &compression, 1);\n\n if ((compression != COMPRESS_NONE) &&\n (compression != COMPRESS_RLE) &&\n (compression != COMPRESS_ZLIB) &&\n (compression != COMPRESS_FRACTAL))\n {\n gimp_message (info->gimp, G_OBJECT (info->progress),\n GIMP_MESSAGE_ERROR,\n \"Unknown compression type: %d\",\n (gint) compression);\n return FALSE;\n }\n\n info->compression = compression;\n\n gimp_image_set_xcf_compression (image,\n compression >= COMPRESS_ZLIB);\n\n GIMP_LOG (XCF, \"prop compression=%d\", compression);\n }\n break;\n\n case PROP_GUIDES:\n {\n GimpImagePrivate *private = GIMP_IMAGE_GET_PRIVATE (image);\n gint32 position;\n gint8 orientation;\n gint i, nguides;\n\n nguides = prop_size / (4 + 1);\n for (i = 0; i < nguides; i++)\n {\n xcf_read_int32 (info, (guint32 *) &position, 1);\n xcf_read_int8 (info, (guint8 *) &orientation, 1);\n\n /* Some very old XCF had -1 guides which have been\n * skipped since 2003 (commit 909a28ced2).\n * Then XCF up to version 14 only had positive guide\n * positions.\n * Since XCF 15 (GIMP 3.0), off-canvas guides became a\n * thing.\n */\n if (info->file_version < 15 && position < 0)\n continue;\n\n GIMP_LOG (XCF, \"prop guide orientation=%d position=%d\",\n orientation, position);\n\n switch (orientation)\n {\n case XCF_ORIENTATION_HORIZONTAL:\n if (info->file_version < 15 && position > gimp_image_get_height (image))\n gimp_message (info->gimp, G_OBJECT (info->progress),\n GIMP_MESSAGE_WARNING,\n \"Ignoring off-canvas horizontal guide (position %d) in XCF %d file\",\n position, info->file_version);\n else\n gimp_image_add_hguide (image, position, FALSE);\n break;\n\n case XCF_ORIENTATION_VERTICAL:\n if (info->file_version < 15 && position > gimp_image_get_width (image))\n gimp_message (info->gimp, G_OBJECT (info->progress),\n GIMP_MESSAGE_WARNING,\n \"Ignoring off-canvas vertical guide (position %d) in XCF %d file\",\n position, info->file_version);\n else\n gimp_image_add_vguide (image, position, FALSE);\n break;\n\n default:\n gimp_message_literal (info->gimp, G_OBJECT (info->progress),\n GIMP_MESSAGE_WARNING,\n \"Guide orientation out of range in XCF file\");\n continue;\n }\n }\n\n /* this is silly as the order of guides doesn't really matter,\n * but it restores the list to its original order, which\n * cannot be wrong --Mitch\n */\n private->guides = g_list_reverse (private->guides);\n }\n break;\n\n case PROP_SAMPLE_POINTS:\n {\n gint n_sample_points, i;\n\n n_sample_points = prop_size / (5 * 4);\n for (i = 0; i < n_sample_points; i++)\n {\n GimpSamplePoint *sample_point;\n gint32 x, y;\n GimpColorPickMode pick_mode;\n guint32 padding[2] = { 0, };\n\n xcf_read_int32 (info, (guint32 *) &x, 1);\n xcf_read_int32 (info, (guint32 *) &y, 1);\n xcf_read_int32 (info, (guint32 *) &pick_mode, 1);\n xcf_read_int32 (info, (guint32 *) padding, 2);\n\n GIMP_LOG (XCF, \"prop sample point x=%d y=%d mode=%d\",\n x, y, pick_mode);\n\n if (pick_mode > GIMP_COLOR_PICK_MODE_LAST)\n pick_mode = GIMP_COLOR_PICK_MODE_PIXEL;\n\n sample_point = gimp_image_add_sample_point_at_pos (image,\n x, y, FALSE);\n gimp_image_set_sample_point_pick_mode (image, sample_point,\n pick_mode, FALSE);\n }\n }\n break;\n\n case PROP_OLD_SAMPLE_POINTS:\n {\n gint32 x, y;\n gint i, n_sample_points;\n\n /* if there are already sample points, we loaded the new\n * prop before\n */\n if (gimp_image_get_sample_points (image))\n {\n if (! xcf_skip_unknown_prop (info, prop_size))\n return FALSE;\n\n break;\n }\n\n n_sample_points = prop_size / (4 + 4);\n for (i = 0; i < n_sample_points; i++)\n {\n xcf_read_int32 (info, (guint32 *) &x, 1);\n xcf_read_int32 (info, (guint32 *) &y, 1);\n\n GIMP_LOG (XCF, \"prop old sample point x=%d y=%d\", x, y);\n\n gimp_image_add_sample_point_at_pos (image, x, y, FALSE);\n }\n }\n break;\n\n case PROP_RESOLUTION:\n {\n gfloat xres, yres;\n\n xcf_read_float (info, &xres, 1);\n xcf_read_float (info, &yres, 1);\n\n GIMP_LOG (XCF, \"prop resolution x=%f y=%f\", xres, yres);\n\n if (xres < GIMP_MIN_RESOLUTION || xres > GIMP_MAX_RESOLUTION ||\n yres < GIMP_MIN_RESOLUTION || yres > GIMP_MAX_RESOLUTION)\n {\n GimpTemplate *template = image->gimp->config->default_image;\n\n gimp_message_literal (info->gimp, G_OBJECT (info->progress),\n GIMP_MESSAGE_WARNING,\n \"Warning, resolution out of range in XCF file\");\n xres = gimp_template_get_resolution_x (template);\n yres = gimp_template_get_resolution_y (template);\n }\n\n gimp_image_set_resolution (image, xres, yres);\n }\n break;\n\n case PROP_TATTOO:\n {\n xcf_read_int32 (info, &info->tattoo_state, 1);\n\n GIMP_LOG (XCF, \"prop tattoo state=%d\", info->tattoo_state);\n }\n break;\n\n case PROP_PARASITES:\n {\n goffset base = info->cp;\n\n while (info->cp - base < prop_size)\n {\n GimpParasite *p = xcf_load_parasite (info);\n GError *error = NULL;\n\n if (! p)\n {\n gimp_message (info->gimp, G_OBJECT (info->progress),\n GIMP_MESSAGE_WARNING,\n \"Invalid image parasite found. \"\n \"Possibly corrupt XCF file.\");\n\n xcf_seek_pos (info, base + prop_size, NULL);\n continue;\n }\n\n if (! gimp_image_parasite_validate (image, p, &error))\n {\n gimp_message (info->gimp, G_OBJECT (info->progress),\n GIMP_MESSAGE_WARNING,\n \"Warning, invalid image parasite in XCF file: %s\",\n error->message);\n g_clear_error (&error);\n }\n else\n {\n gimp_image_parasite_attach (image, p, FALSE);\n }\n\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 GIMP_MESSAGE_WARNING,\n \"Error while loading an image's parasites\");\n }\n break;\n\n case PROP_UNIT:\n {\n guint32 unit;\n\n xcf_read_int32 (info, &unit, 1);\n\n GIMP_LOG (XCF, \"prop unit=%d\", unit);\n\n if ((unit <= GIMP_UNIT_PIXEL) ||\n (unit >= gimp_unit_get_number_of_built_in_units ()))\n {\n gimp_message_literal (info->gimp, G_OBJECT (info->progress),\n GIMP_MESSAGE_WARNING,\n \"Warning, unit out of range in XCF file, \"\n \"falling back to inches\");\n unit = GIMP_UNIT_INCH;\n }\n\n gimp_image_set_unit (image, unit);\n }\n break;\n\n case PROP_PATHS:\n xcf_load_old_paths (info, image);\n break;\n\n case PROP_USER_UNIT:\n {\n gchar *unit_strings[5];\n float factor;\n guint32 digits;\n GimpUnit unit;\n gint num_units;\n gint i;\n\n xcf_read_float (info, &factor, 1);\n xcf_read_int32 (info, &digits, 1);\n xcf_read_string (info, unit_strings, 5);\n\n for (i = 0; i < 5; i++)\n if (unit_strings[i] == NULL)\n unit_strings[i] = g_strdup (\"\");\n\n num_units = gimp_unit_get_number_of_units ();\n\n for (unit = gimp_unit_get_number_of_built_in_units ();\n unit < num_units; unit++)\n {\n /* if the factor and the identifier match some unit\n * in unitrc, use the unitrc unit\n */\n if ((ABS (gimp_unit_get_factor (unit) - factor) < 1e-5) &&\n (strcmp (unit_strings[0],\n gimp_unit_get_identifier (unit)) == 0))\n {\n break;\n }\n }\n\n /* no match */\n if (unit == num_units)\n unit = gimp_unit_new (unit_strings[0],\n factor,\n digits,\n unit_strings[1],\n unit_strings[2],\n unit_strings[3],\n unit_strings[4]);\n\n gimp_image_set_unit (image, unit);\n\n for (i = 0; i < 5; i++)\n g_free (unit_strings[i]);\n }\n break;\n\n case PROP_VECTORS:\n {\n goffset base = info->cp;\n\n if (xcf_load_vectors (info, image))\n {\n if (base + prop_size != info->cp)\n {\n g_printerr (\"Mismatch in PROP_VECTORS size: \"\n \"skipping %\" G_GOFFSET_FORMAT \" bytes.\\n\",\n base + prop_size - info->cp);\n xcf_seek_pos (info, base + prop_size, NULL);\n }\n }\n else\n {\n /* skip silently since we don't understand the format and\n * xcf_load_vectors already explained what was wrong\n */\n xcf_seek_pos (info, base + prop_size, NULL);\n }\n }\n break;\n\n case PROP_ITEM_SET:\n {\n GimpItemList *set = NULL;\n gchar *label;\n GType item_type = 0;\n guint32 itype;\n guint32 method;\n\n xcf_read_int32 (info, &itype, 1);\n xcf_read_int32 (info, &method, 1);\n xcf_read_string (info, &label, 1);\n\n if (itype == 0)\n item_type = GIMP_TYPE_LAYER;\n else\n item_type = GIMP_TYPE_CHANNEL;\n\n if (itype > 1)\n {\n g_printerr (\"xcf: unsupported item set '%s' type: %d (skipping)\\n\",\n label ? label : \"unnamed\", itype);\n /* Only case where we break because we wouldn't even\n * know where to categorize the item set anyway. */\n break;\n }\n else if (label == NULL)\n {\n g_printerr (\"xcf: item set without a name or pattern (skipping)\\n\");\n }\n else if (method != G_MAXUINT32 && method > GIMP_SELECT_GLOB_PATTERN)\n {\n g_printerr (\"xcf: unsupported item set '%s' selection method attribute: 0x%x (skipping)\\n\",\n label, method);\n }\n else\n {\n if (method == G_MAXUINT32)\n {\n /* Don't use gimp_item_list_named_new() because it\n * doesn't allow NULL items (it would try to get the\n * selected items instead).\n */\n set = g_object_new (GIMP_TYPE_ITEM_LIST,\n \"image\", image,\n \"name\", label,\n \"is-pattern\", FALSE,\n \"item-type\", item_type,\n \"items\", NULL,\n NULL);\n }\n else\n {\n set = gimp_item_list_pattern_new (image, item_type,\n method, label);\n }\n }\n\n /* Note: we are still adding invalid item sets as NULL on\n * purpose, in order not to break order-base association\n * between PROP_ITEM_SET and PROP_ITEM_SET_ITEM.\n */\n if (item_type == GIMP_TYPE_LAYER)\n info->layer_sets = g_list_prepend (info->layer_sets, set);\n else\n info->channel_sets = g_list_prepend (info->channel_sets, set);\n }\n break;\n\n default:\n#ifdef GIMP_UNSTABLE\n g_printerr (\"unexpected/unknown image 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-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: do_window(\n int\t\tnchar,\n long\tPrenum,\n int\t\txchar)\t // extra char from \":wincmd gx\" or NUL\n{\n long\tPrenum1;\n win_T\t*wp;\n#if defined(FEAT_SEARCHPATH) || defined(FEAT_FIND_ID)\n char_u\t*ptr;\n linenr_T lnum = -1;\n#endif\n#ifdef FEAT_FIND_ID\n int\t\ttype = FIND_DEFINE;\n int\t\tlen;\n#endif\n char_u\tcbuf[40];\n\n if (ERROR_IF_ANY_POPUP_WINDOW)\n\treturn;\n\n#ifdef FEAT_CMDWIN\n# define CHECK_CMDWIN \\\n do { \\\n\tif (cmdwin_type != 0) \\\n\t{ \\\n\t emsg(_(e_invalid_in_cmdline_window)); \\\n\t return; \\\n\t} \\\n } while (0)\n#else\n# define CHECK_CMDWIN do { /**/ } while (0)\n#endif\n\n Prenum1 = Prenum == 0 ? 1 : Prenum;\n\n switch (nchar)\n {\n// split current window in two parts, horizontally\n case 'S':\n case Ctrl_S:\n case 's':\n\t\tCHECK_CMDWIN;\n\t\treset_VIsual_and_resel();\t// stop Visual mode\n#ifdef FEAT_QUICKFIX\n\t\t// When splitting the quickfix window open a new buffer in it,\n\t\t// don't replicate the quickfix buffer.\n\t\tif (bt_quickfix(curbuf))\n\t\t goto newwindow;\n#endif\n#ifdef FEAT_GUI\n\t\tneed_mouse_correct = TRUE;\n#endif\n\t\t(void)win_split((int)Prenum, 0);\n\t\tbreak;\n\n// split current window in two parts, vertically\n case Ctrl_V:\n case 'v':\n\t\tCHECK_CMDWIN;\n\t\treset_VIsual_and_resel();\t// stop Visual mode\n#ifdef FEAT_QUICKFIX\n\t\t// When splitting the quickfix window open a new buffer in it,\n\t\t// don't replicate the quickfix buffer.\n\t\tif (bt_quickfix(curbuf))\n\t\t goto newwindow;\n#endif\n#ifdef FEAT_GUI\n\t\tneed_mouse_correct = TRUE;\n#endif\n\t\t(void)win_split((int)Prenum, WSP_VERT);\n\t\tbreak;\n\n// split current window and edit alternate file\n case Ctrl_HAT:\n case '^':\n\t\tCHECK_CMDWIN;\n\t\treset_VIsual_and_resel();\t// stop Visual mode\n\n\t\tif (buflist_findnr(Prenum == 0\n\t\t\t\t\t? curwin->w_alt_fnum : Prenum) == NULL)\n\t\t{\n\t\t if (Prenum == 0)\n\t\t\temsg(_(e_no_alternate_file));\n\t\t else\n\t\t\tsemsg(_(e_buffer_nr_not_found), Prenum);\n\t\t break;\n\t\t}\n\n\t\tif (!curbuf_locked() && win_split(0, 0) == OK)\n\t\t (void)buflist_getfile(\n\t\t\t Prenum == 0 ? curwin->w_alt_fnum : Prenum,\n\t\t\t (linenr_T)0, GETF_ALT, FALSE);\n\t\tbreak;\n\n// open new window\n case Ctrl_N:\n case 'n':\n\t\tCHECK_CMDWIN;\n\t\treset_VIsual_and_resel();\t// stop Visual mode\n#ifdef FEAT_QUICKFIX\nnewwindow:\n#endif\n\t\tif (Prenum)\n\t\t // window height\n\t\t vim_snprintf((char *)cbuf, sizeof(cbuf) - 5, \"%ld\", Prenum);\n\t\telse\n\t\t cbuf[0] = NUL;\n#if defined(FEAT_QUICKFIX)\n\t\tif (nchar == 'v' || nchar == Ctrl_V)\n\t\t STRCAT(cbuf, \"v\");\n#endif\n\t\tSTRCAT(cbuf, \"new\");\n\t\tdo_cmdline_cmd(cbuf);\n\t\tbreak;\n\n// quit current window\n case Ctrl_Q:\n case 'q':\n\t\treset_VIsual_and_resel();\t// stop Visual mode\n\t\tcmd_with_count(\"quit\", cbuf, sizeof(cbuf), Prenum);\n\t\tdo_cmdline_cmd(cbuf);\n\t\tbreak;\n\n// close current window\n case Ctrl_C:\n case 'c':\n\t\treset_VIsual_and_resel();\t// stop Visual mode\n\t\tcmd_with_count(\"close\", cbuf, sizeof(cbuf), Prenum);\n\t\tdo_cmdline_cmd(cbuf);\n\t\tbreak;\n\n#if defined(FEAT_QUICKFIX)\n// close preview window\n case Ctrl_Z:\n case 'z':\n\t\tCHECK_CMDWIN;\n\t\treset_VIsual_and_resel();\t// stop Visual mode\n\t\tdo_cmdline_cmd((char_u *)\"pclose\");\n\t\tbreak;\n\n// cursor to preview window\n case 'P':\n\t\tFOR_ALL_WINDOWS(wp)\n\t\t if (wp->w_p_pvw)\n\t\t\tbreak;\n\t\tif (wp == NULL)\n\t\t emsg(_(e_there_is_no_preview_window));\n\t\telse\n\t\t win_goto(wp);\n\t\tbreak;\n#endif\n\n// close all but current window\n case Ctrl_O:\n case 'o':\n\t\tCHECK_CMDWIN;\n\t\treset_VIsual_and_resel();\t// stop Visual mode\n\t\tcmd_with_count(\"only\", cbuf, sizeof(cbuf), Prenum);\n\t\tdo_cmdline_cmd(cbuf);\n\t\tbreak;\n\n// cursor to next window with wrap around\n case Ctrl_W:\n case 'w':\n// cursor to previous window with wrap around\n case 'W':\n\t\tCHECK_CMDWIN;\n\t\tif (ONE_WINDOW && Prenum != 1)\t// just one window\n\t\t beep_flush();\n\t\telse\n\t\t{\n\t\t if (Prenum)\t\t\t// go to specified window\n\t\t {\n\t\t\tfor (wp = firstwin; --Prenum > 0; )\n\t\t\t{\n\t\t\t if (wp->w_next == NULL)\n\t\t\t\tbreak;\n\t\t\t else\n\t\t\t\twp = wp->w_next;\n\t\t\t}\n\t\t }\n\t\t else\n\t\t {\n\t\t\tif (nchar == 'W')\t // go to previous window\n\t\t\t{\n\t\t\t wp = curwin->w_prev;\n\t\t\t if (wp == NULL)\n\t\t\t\twp = lastwin;\t // wrap around\n\t\t\t}\n\t\t\telse\t\t\t // go to next window\n\t\t\t{\n\t\t\t wp = curwin->w_next;\n\t\t\t if (wp == NULL)\n\t\t\t\twp = firstwin;\t // wrap around\n\t\t\t}\n\t\t }\n\t\t win_goto(wp);\n\t\t}\n\t\tbreak;\n\n// cursor to window below\n case 'j':\n case K_DOWN:\n case Ctrl_J:\n\t\tCHECK_CMDWIN;\n\t\twin_goto_ver(FALSE, Prenum1);\n\t\tbreak;\n\n// cursor to window above\n case 'k':\n case K_UP:\n case Ctrl_K:\n\t\tCHECK_CMDWIN;\n\t\twin_goto_ver(TRUE, Prenum1);\n\t\tbreak;\n\n// cursor to left window\n case 'h':\n case K_LEFT:\n case Ctrl_H:\n case K_BS:\n\t\tCHECK_CMDWIN;\n\t\twin_goto_hor(TRUE, Prenum1);\n\t\tbreak;\n\n// cursor to right window\n case 'l':\n case K_RIGHT:\n case Ctrl_L:\n\t\tCHECK_CMDWIN;\n\t\twin_goto_hor(FALSE, Prenum1);\n\t\tbreak;\n\n// move window to new tab page\n case 'T':\n\t\tCHECK_CMDWIN;\n\t\tif (one_window())\n\t\t msg(_(m_onlyone));\n\t\telse\n\t\t{\n\t\t tabpage_T\t*oldtab = curtab;\n\t\t tabpage_T\t*newtab;\n\n\t\t // First create a new tab with the window, then go back to\n\t\t // the old tab and close the window there.\n\t\t wp = curwin;\n\t\t if (win_new_tabpage((int)Prenum) == OK\n\t\t\t\t\t\t && valid_tabpage(oldtab))\n\t\t {\n\t\t\tnewtab = curtab;\n\t\t\tgoto_tabpage_tp(oldtab, TRUE, TRUE);\n\t\t\tif (curwin == wp)\n\t\t\t win_close(curwin, FALSE);\n\t\t\tif (valid_tabpage(newtab))\n\t\t\t goto_tabpage_tp(newtab, TRUE, TRUE);\n\t\t }\n\t\t}\n\t\tbreak;\n\n// cursor to top-left window\n case 't':\n case Ctrl_T:\n\t\twin_goto(firstwin);\n\t\tbreak;\n\n// cursor to bottom-right window\n case 'b':\n case Ctrl_B:\n\t\twin_goto(lastwin);\n\t\tbreak;\n\n// cursor to last accessed (previous) window\n case 'p':\n case Ctrl_P:\n\t\tif (!win_valid(prevwin))\n\t\t beep_flush();\n\t\telse\n\t\t win_goto(prevwin);\n\t\tbreak;\n\n// exchange current and next window\n case 'x':\n case Ctrl_X:\n\t\tCHECK_CMDWIN;\n\t\twin_exchange(Prenum);\n\t\tbreak;\n\n// rotate windows downwards\n case Ctrl_R:\n case 'r':\n\t\tCHECK_CMDWIN;\n\t\treset_VIsual_and_resel();\t// stop Visual mode\n\t\twin_rotate(FALSE, (int)Prenum1); // downwards\n\t\tbreak;\n\n// rotate windows upwards\n case 'R':\n\t\tCHECK_CMDWIN;\n\t\treset_VIsual_and_resel();\t// stop Visual mode\n\t\twin_rotate(TRUE, (int)Prenum1);\t // upwards\n\t\tbreak;\n\n// move window to the very top/bottom/left/right\n case 'K':\n case 'J':\n case 'H':\n case 'L':\n\t\tCHECK_CMDWIN;\n\t\twin_totop((int)Prenum,\n\t\t\t((nchar == 'H' || nchar == 'L') ? WSP_VERT : 0)\n\t\t\t| ((nchar == 'H' || nchar == 'K') ? WSP_TOP : WSP_BOT));\n\t\tbreak;\n\n// make all windows the same height\n case '=':\n#ifdef FEAT_GUI\n\t\tneed_mouse_correct = TRUE;\n#endif\n\t\twin_equal(NULL, FALSE, 'b');\n\t\tbreak;\n\n// increase current window height\n case '+':\n#ifdef FEAT_GUI\n\t\tneed_mouse_correct = TRUE;\n#endif\n\t\twin_setheight(curwin->w_height + (int)Prenum1);\n\t\tbreak;\n\n// decrease current window height\n case '-':\n#ifdef FEAT_GUI\n\t\tneed_mouse_correct = TRUE;\n#endif\n\t\twin_setheight(curwin->w_height - (int)Prenum1);\n\t\tbreak;\n\n// set current window height\n case Ctrl__:\n case '_':\n#ifdef FEAT_GUI\n\t\tneed_mouse_correct = TRUE;\n#endif\n\t\twin_setheight(Prenum ? (int)Prenum : 9999);\n\t\tbreak;\n\n// increase current window width\n case '>':\n#ifdef FEAT_GUI\n\t\tneed_mouse_correct = TRUE;\n#endif\n\t\twin_setwidth(curwin->w_width + (int)Prenum1);\n\t\tbreak;\n\n// decrease current window width\n case '<':\n#ifdef FEAT_GUI\n\t\tneed_mouse_correct = TRUE;\n#endif\n\t\twin_setwidth(curwin->w_width - (int)Prenum1);\n\t\tbreak;\n\n// set current window width\n case '|':\n#ifdef FEAT_GUI\n\t\tneed_mouse_correct = TRUE;\n#endif\n\t\twin_setwidth(Prenum != 0 ? (int)Prenum : 9999);\n\t\tbreak;\n\n// jump to tag and split window if tag exists (in preview window)\n#if defined(FEAT_QUICKFIX)\n case '}':\n\t\tCHECK_CMDWIN;\n\t\tif (Prenum)\n\t\t g_do_tagpreview = Prenum;\n\t\telse\n\t\t g_do_tagpreview = p_pvh;\n#endif\n\t\t// FALLTHROUGH\n case ']':\n case Ctrl_RSB:\n\t\tCHECK_CMDWIN;\n\t\t// keep Visual mode, can select words to use as a tag\n\t\tif (Prenum)\n\t\t postponed_split = Prenum;\n\t\telse\n\t\t postponed_split = -1;\n#ifdef FEAT_QUICKFIX\n\t\tif (nchar != '}')\n\t\t g_do_tagpreview = 0;\n#endif\n\n\t\t// Execute the command right here, required when \"wincmd ]\"\n\t\t// was used in a function.\n\t\tdo_nv_ident(Ctrl_RSB, NUL);\n\t\tbreak;\n\n#ifdef FEAT_SEARCHPATH\n// edit file name under cursor in a new window\n case 'f':\n case 'F':\n case Ctrl_F:\nwingotofile:\n\t\tCHECK_CMDWIN;\n\n\t\tptr = grab_file_name(Prenum1, &lnum);\n\t\tif (ptr != NULL)\n\t\t{\n\t\t tabpage_T\t*oldtab = curtab;\n\t\t win_T\t*oldwin = curwin;\n# ifdef FEAT_GUI\n\t\t need_mouse_correct = TRUE;\n# endif\n\t\t setpcmark();\n\t\t if (win_split(0, 0) == OK)\n\t\t {\n\t\t\tRESET_BINDING(curwin);\n\t\t\tif (do_ecmd(0, ptr, NULL, NULL, ECMD_LASTL,\n\t\t\t\t\t\t ECMD_HIDE, NULL) == FAIL)\n\t\t\t{\n\t\t\t // Failed to open the file, close the window\n\t\t\t // opened for it.\n\t\t\t win_close(curwin, FALSE);\n\t\t\t goto_tabpage_win(oldtab, oldwin);\n\t\t\t}\n\t\t\telse if (nchar == 'F' && lnum >= 0)\n\t\t\t{\n\t\t\t curwin->w_cursor.lnum = lnum;\n\t\t\t check_cursor_lnum();\n\t\t\t beginline(BL_SOL | BL_FIX);\n\t\t\t}\n\t\t }\n\t\t vim_free(ptr);\n\t\t}\n\t\tbreak;\n#endif\n\n#ifdef FEAT_FIND_ID\n// Go to the first occurrence of the identifier under cursor along path in a\n// new window -- webb\n case 'i':\t\t\t // Go to any match\n case Ctrl_I:\n\t\ttype = FIND_ANY;\n\t\t// FALLTHROUGH\n case 'd':\t\t\t // Go to definition, using 'define'\n case Ctrl_D:\n\t\tCHECK_CMDWIN;\n\t\tif ((len = find_ident_under_cursor(&ptr, FIND_IDENT)) == 0)\n\t\t break;\n\t\tfind_pattern_in_path(ptr, 0, len, TRUE,\n\t\t\tPrenum == 0 ? TRUE : FALSE, type,\n\t\t\tPrenum1, ACTION_SPLIT, (linenr_T)1, (linenr_T)MAXLNUM);\n\t\tcurwin->w_set_curswant = TRUE;\n\t\tbreak;\n#endif\n\n// Quickfix window only: view the result under the cursor in a new split.\n#if defined(FEAT_QUICKFIX)\n case K_KENTER:\n case CAR:\n\t\tif (bt_quickfix(curbuf))\n\t\t qf_view_result(TRUE);\n\t\tbreak;\n#endif\n\n// CTRL-W g extended commands\n case 'g':\n case Ctrl_G:\n\t\tCHECK_CMDWIN;\n#ifdef USE_ON_FLY_SCROLL\n\t\tdont_scroll = TRUE;\t\t// disallow scrolling here\n#endif\n\t\t++no_mapping;\n\t\t++allow_keys; // no mapping for xchar, but allow key codes\n\t\tif (xchar == NUL)\n\t\t xchar = plain_vgetc();\n\t\tLANGMAP_ADJUST(xchar, TRUE);\n\t\t--no_mapping;\n\t\t--allow_keys;\n#ifdef FEAT_CMDL_INFO\n\t\t(void)add_to_showcmd(xchar);\n#endif\n\t\tswitch (xchar)\n\t\t{\n#if defined(FEAT_QUICKFIX)\n\t\t case '}':\n\t\t\txchar = Ctrl_RSB;\n\t\t\tif (Prenum)\n\t\t\t g_do_tagpreview = Prenum;\n\t\t\telse\n\t\t\t g_do_tagpreview = p_pvh;\n#endif\n\t\t\t// FALLTHROUGH\n\t\t case ']':\n\t\t case Ctrl_RSB:\n\t\t\t// keep Visual mode, can select words to use as a tag\n\t\t\tif (Prenum)\n\t\t\t postponed_split = Prenum;\n\t\t\telse\n\t\t\t postponed_split = -1;\n\n\t\t\t// Execute the command right here, required when\n\t\t\t// \"wincmd g}\" was used in a function.\n\t\t\tdo_nv_ident('g', xchar);\n\t\t\tbreak;\n\n#ifdef FEAT_SEARCHPATH\n\t\t case 'f':\t // CTRL-W gf: \"gf\" in a new tab page\n\t\t case 'F':\t // CTRL-W gF: \"gF\" in a new tab page\n\t\t\tcmdmod.cmod_tab = tabpage_index(curtab) + 1;\n\t\t\tnchar = xchar;\n\t\t\tgoto wingotofile;\n#endif\n\t\t case 't':\t // CTRL-W gt: go to next tab page\n\t\t\tgoto_tabpage((int)Prenum);\n\t\t\tbreak;\n\n\t\t case 'T':\t // CTRL-W gT: go to previous tab page\n\t\t\tgoto_tabpage(-(int)Prenum1);\n\t\t\tbreak;\n\n\t\t case TAB:\t // CTRL-W g: go to last used tab page\n\t\t\tif (goto_tabpage_lastused() == FAIL)\n\t\t\t beep_flush();\n\t\t\tbreak;\n\n\t\t default:\n\t\t\tbeep_flush();\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\n default:\tbeep_flush();\n\t\tbreak;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'patch 8.2.4979: accessing freed memory when line is flushed\n\nProblem: Accessing freed memory when line is flushed.\nSolution: Make a copy of the pattern to search for.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: nv_brackets(cmdarg_T *cap)\n{\n pos_T\tprev_pos;\n pos_T\t*pos = NULL;\t // init for GCC\n pos_T\told_pos;\t // cursor position before command\n int\t\tflag;\n long\tn;\n\n cap->oap->motion_type = MCHAR;\n cap->oap->inclusive = FALSE;\n old_pos = curwin->w_cursor;\n curwin->w_cursor.coladd = 0; // TODO: don't do this for an error.\n\n#ifdef FEAT_SEARCHPATH\n // \"[f\" or \"]f\" : Edit file under the cursor (same as \"gf\")\n if (cap->nchar == 'f')\n\tnv_gotofile(cap);\n else\n#endif\n\n#ifdef FEAT_FIND_ID\n // Find the occurrence(s) of the identifier or define under cursor\n // in current and included files or jump to the first occurrence.\n //\n //\t\t\tsearch\t list\t jump\n //\t\t fwd bwd fwd\t bwd\t fwd\tbwd\n // identifier \"]i\" \"[i\" \"]I\" \"[I\"\t\"]^I\" \"[^I\"\n // define\t \"]d\" \"[d\" \"]D\" \"[D\"\t\"]^D\" \"[^D\"\n if (vim_strchr((char_u *)\"iI\\011dD\\004\", cap->nchar) != NULL)\n {\n\tchar_u\t*ptr;\n\tint\tlen;\n\n\tif ((len = find_ident_under_cursor(&ptr, FIND_IDENT)) == 0)\n\t clearop(cap->oap);\n\telse\n\t{\n\t find_pattern_in_path(ptr, 0, len, TRUE,\n\t\tcap->count0 == 0 ? !isupper(cap->nchar) : FALSE,\n\t\t((cap->nchar & 0xf) == ('d' & 0xf)) ? FIND_DEFINE : FIND_ANY,\n\t\tcap->count1,\n\t\tisupper(cap->nchar) ? ACTION_SHOW_ALL :\n\t\t\t islower(cap->nchar) ? ACTION_SHOW : ACTION_GOTO,\n\t\tcap->cmdchar == ']' ? curwin->w_cursor.lnum + 1 : (linenr_T)1,\n\t\t(linenr_T)MAXLNUM);\n\t curwin->w_set_curswant = TRUE;\n\t}\n }\n else\n#endif\n\n // \"[{\", \"[(\", \"]}\" or \"])\": go to Nth unclosed '{', '(', '}' or ')'\n // \"[#\", \"]#\": go to start/end of Nth innermost #if..#endif construct.\n // \"[/\", \"[*\", \"]/\", \"]*\": go to Nth comment start/end.\n // \"[m\" or \"]m\" search for prev/next start of (Java) method.\n // \"[M\" or \"]M\" search for prev/next end of (Java) method.\n if ( (cap->cmdchar == '['\n\t\t&& vim_strchr((char_u *)\"{(*/#mM\", cap->nchar) != NULL)\n\t || (cap->cmdchar == ']'\n\t\t&& vim_strchr((char_u *)\"})*/#mM\", cap->nchar) != NULL))\n\tnv_bracket_block(cap, &old_pos);\n\n // \"[[\", \"[]\", \"]]\" and \"][\": move to start or end of function\n else if (cap->nchar == '[' || cap->nchar == ']')\n {\n\tif (cap->nchar == cap->cmdchar)\t\t // \"]]\" or \"[[\"\n\t flag = '{';\n\telse\n\t flag = '}';\t\t // \"][\" or \"[]\"\n\n\tcurwin->w_set_curswant = TRUE;\n\t// Imitate strange Vi behaviour: When using \"]]\" with an operator\n\t// we also stop at '}'.\n\tif (!findpar(&cap->oap->inclusive, cap->arg, cap->count1, flag,\n\t (cap->oap->op_type != OP_NOP\n\t\t\t\t && cap->arg == FORWARD && flag == '{')))\n\t clearopbeep(cap->oap);\n\telse\n\t{\n\t if (cap->oap->op_type == OP_NOP)\n\t\tbeginline(BL_WHITE | BL_FIX);\n#ifdef FEAT_FOLDING\n\t if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP)\n\t\tfoldOpenCursor();\n#endif\n\t}\n }\n\n // \"[p\", \"[P\", \"]P\" and \"]p\": put with indent adjustment\n else if (cap->nchar == 'p' || cap->nchar == 'P')\n {\n\tnv_put_opt(cap, TRUE);\n }\n\n // \"['\", \"[`\", \"]'\" and \"]`\": jump to next mark\n else if (cap->nchar == '\\'' || cap->nchar == '`')\n {\n\tpos = &curwin->w_cursor;\n\tfor (n = cap->count1; n > 0; --n)\n\t{\n\t prev_pos = *pos;\n\t pos = getnextmark(pos, cap->cmdchar == '[' ? BACKWARD : FORWARD,\n\t\t\t\t\t\t\t cap->nchar == '\\'');\n\t if (pos == NULL)\n\t\tbreak;\n\t}\n\tif (pos == NULL)\n\t pos = &prev_pos;\n\tnv_cursormark(cap, cap->nchar == '\\'', pos);\n }\n\n // [ or ] followed by a middle mouse click: put selected text with\n // indent adjustment. Any other button just does as usual.\n else if (cap->nchar >= K_RIGHTRELEASE && cap->nchar <= K_LEFTMOUSE)\n {\n\t(void)do_mouse(cap->oap, cap->nchar,\n\t\t (cap->cmdchar == ']') ? FORWARD : BACKWARD,\n\t\t cap->count1, PUT_FIXINDENT);\n }\n\n#ifdef FEAT_FOLDING\n // \"[z\" and \"]z\": move to start or end of open fold.\n else if (cap->nchar == 'z')\n {\n\tif (foldMoveTo(FALSE, cap->cmdchar == ']' ? FORWARD : BACKWARD,\n\t\t\t\t\t\t\t cap->count1) == FAIL)\n\t clearopbeep(cap->oap);\n }\n#endif\n\n#ifdef FEAT_DIFF\n // \"[c\" and \"]c\": move to next or previous diff-change.\n else if (cap->nchar == 'c')\n {\n\tif (diff_move_to(cap->cmdchar == ']' ? FORWARD : BACKWARD,\n\t\t\t\t\t\t\t cap->count1) == FAIL)\n\t clearopbeep(cap->oap);\n }\n#endif\n\n#ifdef FEAT_SPELL\n // \"[s\", \"[S\", \"]s\" and \"]S\": move to next spell error.\n else if (cap->nchar == 's' || cap->nchar == 'S')\n {\n\tsetpcmark();\n\tfor (n = 0; n < cap->count1; ++n)\n\t if (spell_move_to(curwin, cap->cmdchar == ']' ? FORWARD : BACKWARD,\n\t\t\t cap->nchar == 's' ? TRUE : FALSE, FALSE, NULL) == 0)\n\t {\n\t\tclearopbeep(cap->oap);\n\t\tbreak;\n\t }\n\t else\n\t\tcurwin->w_set_curswant = TRUE;\n# ifdef FEAT_FOLDING\n\tif (cap->oap->op_type == OP_NOP && (fdo_flags & FDO_SEARCH) && KeyTyped)\n\t foldOpenCursor();\n# endif\n }\n#endif\n\n // Not a valid cap->nchar.\n else\n\tclearopbeep(cap->oap);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'patch 8.2.5024: using freed memory with \"]d\"\n\nProblem: Using freed memory with \"]d\".\nSolution: Copy the pattern before searching.'" }, { "text": "[INST] Given the following code containing errors, provide Common 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\tif (task && head->task != task)\n\t\treturn false;\n\treturn cancel_all;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'io_uring: reinstate the inflight tracking\n\nAfter some debugging, it was realized that we really do still need the\nold inflight tracking for any file type that has io_uring_fops assigned.\nIf we don't, then trivial circular references will mean that we never get\nthe ctx cleaned up and hence it'll leak.\n\nJust bring back the inflight tracking, which then also means we can\neliminate the conditional dropping of the file when task_work is queued.\n\nFixes: d5361233e9ab (\"io_uring: drop the old style inflight file tracking\")\nSigned-off-by: Jens Axboe '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void __io_req_task_work_add(struct io_kiocb *req,\n\t\t\t\t struct io_uring_task *tctx,\n\t\t\t\t struct io_wq_work_list *list)\n{\n\tstruct io_ring_ctx *ctx = req->ctx;\n\tstruct io_wq_work_node *node;\n\tunsigned long flags;\n\tbool running;\n\n\tio_drop_inflight_file(req);\n\n\tspin_lock_irqsave(&tctx->task_lock, flags);\n\twq_list_add_tail(&req->io_task_work.node, list);\n\trunning = tctx->task_running;\n\tif (!running)\n\t\ttctx->task_running = true;\n\tspin_unlock_irqrestore(&tctx->task_lock, flags);\n\n\t/* task_work already pending, we're done */\n\tif (running)\n\t\treturn;\n\n\tif (ctx->flags & IORING_SETUP_TASKRUN_FLAG)\n\t\tatomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);\n\n\tif (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))\n\t\treturn;\n\n\tspin_lock_irqsave(&tctx->task_lock, flags);\n\ttctx->task_running = false;\n\tnode = wq_list_merge(&tctx->prio_task_list, &tctx->task_list);\n\tspin_unlock_irqrestore(&tctx->task_lock, flags);\n\n\twhile (node) {\n\t\treq = container_of(node, struct io_kiocb, io_task_work.node);\n\t\tnode = node->next;\n\t\tif (llist_add(&req->io_task_work.fallback_node,\n\t\t\t &req->ctx->fallback_llist))\n\t\t\tschedule_delayed_work(&req->ctx->fallback_work, 1);\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: MOBI_RET mobi_trie_insert_infl(MOBITrie **root, const MOBIIndx *indx, size_t i) {\n MOBIIndexEntry e = indx->entries[i];\n char *inflected = e.label;\n for (size_t j = 0; j < e.tags_count; j++) {\n MOBIIndexTag t = e.tags[j];\n if (t.tagid == INDX_TAGARR_INFL_PARTS_V1) {\n for (size_t k = 0; k < t.tagvalues_count - 1; k += 2) {\n uint32_t len = t.tagvalues[k];\n uint32_t offset = t.tagvalues[k + 1];\n char *base = mobi_get_cncx_string_flat(indx->cncx_record, offset, len);\n if (base == NULL) {\n return MOBI_MALLOC_FAILED;\n }\n MOBI_RET ret = mobi_trie_insert_reversed(root, base, inflected);\n free(base);\n if (ret != MOBI_SUCCESS) {\n return ret;\n }\n }\n }\n }\n return MOBI_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix issue with corrupt files with tagvalues_count = 0 that caused null pointer dereference'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void caps_print_filter(pid_t pid) {\n\tEUID_ASSERT();\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\tuint64_t caps = extract_caps(pid);\n\tint i;\n\tuint64_t mask;\n\tint elems = sizeof(capslist) / sizeof(capslist[0]);\n\tfor (i = 0, mask = 1; i < elems; i++, mask <<= 1) {\n\t\tprintf(\"%-18.18s - %s\\n\", capslist[i].name, (mask & caps)? \"enabled\": \"disabled\");\n\t}\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: int main(int argc, char **argv, char **envp) {\n\tint i;\n\tint prog_index = -1;\t\t\t // index in argv where the program command starts\n\tint lockfd_network = -1;\n\tint lockfd_directory = -1;\n\tint option_cgroup = 0;\n\tint custom_profile = 0;\t// custom profile loaded\n\tint arg_caps_cmdline = 0; \t// caps requested on command line (used to break out of --chroot)\n\tint arg_netlock = 0;\n\tchar **ptr;\n\n\n\t// sanitize the umask\n\torig_umask = umask(022);\n\n\t// drop permissions by default and rise them when required\n\tEUID_INIT();\n\tEUID_USER();\n\n\t// check standard streams before opening any file\n\tfix_std_streams();\n\n\t// argument count should be larger than 0\n\tif (argc == 0 || !argv || strlen(argv[0]) == 0) {\n\t\tfprintf(stderr, \"Error: argv is invalid\\n\");\n\t\texit(1);\n\t} else if (argc >= MAX_ARGS) {\n\t\tfprintf(stderr, \"Error: too many arguments: argc (%d) >= MAX_ARGS (%d)\\n\", argc, MAX_ARGS);\n\t\texit(1);\n\t}\n\n\t// sanity check for arguments\n\tfor (i = 0; i < argc; i++) {\n\t\tif (strlen(argv[i]) >= MAX_ARG_LEN) {\n\t\t\tfprintf(stderr, \"Error: too long arguments: argv[%d] len (%zu) >= MAX_ARG_LEN (%d)\\n\", i, strlen(argv[i]), MAX_ARG_LEN);\n\t\t\texit(1);\n\t\t}\n\t}\n\n\t// Stash environment variables\n\tfor (i = 0, ptr = envp; ptr && *ptr && i < MAX_ENVS; i++, ptr++)\n\t\tenv_store(*ptr, SETENV);\n\n\t// sanity check for environment variables\n\tif (i >= MAX_ENVS) {\n\t\tfprintf(stderr, \"Error: too many environment variables: >= MAX_ENVS (%d)\\n\", MAX_ENVS);\n\t\texit(1);\n\t}\n\n\t// Reapply a minimal set of environment variables\n\tenv_apply_whitelist();\n\n\t// process --quiet\n\tconst char *env_quiet = env_get(\"FIREJAIL_QUIET\");\n\tif (check_arg(argc, argv, \"--quiet\", 1) || (env_quiet && strcmp(env_quiet, \"yes\") == 0))\n\t\targ_quiet = 1;\n\n\t// check if the user is allowed to use firejail\n\tinit_cfg(argc, argv);\n\n\t// get starting timestamp\n\ttimetrace_start();\n\n\t// check argv[0] symlink wrapper if this is not a login shell\n\tif (*argv[0] != '-')\n\t\trun_symlink(argc, argv, 0); // if symlink detected, this function will not return\n\n\t// check if we already have a sandbox running\n\t// If LXC is detected, start firejail sandbox\n\t// otherwise try to detect a PID namespace by looking under /proc for specific kernel processes and:\n\t//\t- start the application in a /bin/bash shell\n\tif (check_namespace_virt() == 0) {\n\t\tEUID_ROOT();\n\t\tint rv = check_kernel_procs();\n\t\tEUID_USER();\n\t\tif (rv == 0) {\n\t\t\tif (check_arg(argc, argv, \"--version\", 1)) {\n\t\t\t\tprint_version();\n\t\t\t\texit(0);\n\t\t\t}\n\n\t\t\t// start the program directly without sandboxing\n\t\t\trun_no_sandbox(argc, argv);\n\t\t\t__builtin_unreachable();\n\t\t}\n\t}\n\n\t// profile builder\n\tif (check_arg(argc, argv, \"--build\", 0)) // supports both --build and --build=filename\n\t\trun_builder(argc, argv); // this function will not return\n\n\t// intrusion detection system\n#ifdef HAVE_IDS\n\tif (check_arg(argc, argv, \"--ids-\", 0)) // supports both --ids-init and --ids-check\n\t\trun_ids(argc, argv); // this function will not return\n#else\n\tif (check_arg(argc, argv, \"--ids-\", 0)) { // supports both --ids-init and --ids-check\n\t\tfprintf(stderr, \"Error: IDS features disabled in your Firejail build.\\n\"\n\t\t\t\"\\tTo enable it, configure your build system using --enable-ids.\\n\"\n\t\t\t\"\\tExample: ./configure --prefix=/usr --enable-ids\\n\\n\");\n\t\texit(1);\n\t}\n#endif\n\n\tEUID_ROOT();\n#ifndef HAVE_SUID\n\tif (geteuid() != 0) {\n\t\tfprintf(stderr, \"Error: Firejail needs to be SUID.\\n\");\n\t\tfprintf(stderr, \"Assuming firejail is installed in /usr/bin, execute the following command as root:\\n\");\n\t\tfprintf(stderr, \" chmod u+s /usr/bin/firejail\\n\");\n\t}\n#endif\n\n\t// build /run/firejail directory structure\n\tpreproc_build_firejail_dir();\n\tconst char *container_name = env_get(\"container\");\n\tif (!container_name || strcmp(container_name, \"firejail\")) {\n\t\tlockfd_directory = open(RUN_DIRECTORY_LOCK_FILE, O_WRONLY | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR);\n\t\tif (lockfd_directory != -1) {\n\t\t\tint rv = fchown(lockfd_directory, 0, 0);\n\t\t\t(void) rv;\n\t\t\tflock(lockfd_directory, LOCK_EX);\n\t\t}\n\t\tpreproc_clean_run();\n\t\tflock(lockfd_directory, LOCK_UN);\n\t\tclose(lockfd_directory);\n\t}\n\n\tdelete_run_files(getpid());\n\tatexit(clear_atexit);\n\tEUID_USER();\n\n\t// check if the parent is sshd daemon\n\tint parent_sshd = 0;\n\t{\n\t\tpid_t ppid = getppid();\n\t\tEUID_ROOT();\n\t\tchar *comm = pid_proc_comm(ppid);\n\t\tEUID_USER();\n\t\tif (comm) {\n\t\t\tif (strcmp(comm, \"sshd\") == 0) {\n\t\t\t\targ_quiet = 1;\n\t\t\t\tparent_sshd = 1;\n\n#ifdef DEBUG_RESTRICTED_SHELL\n\t\t\t\t{EUID_ROOT();\n\t\t\t\tFILE *fp = fopen(\"/firelog\", \"we\");\n\t\t\t\tif (fp) {\n\t\t\t\t\tint i;\n\t\t\t\t\tfprintf(fp, \"argc %d: \", argc);\n\t\t\t\t\tfor (i = 0; i < argc; i++)\n\t\t\t\t\t\tfprintf(fp, \"#%s# \", argv[i]);\n\t\t\t\t\tfprintf(fp, \"\\n\");\n\t\t\t\t\tfclose(fp);\n\t\t\t\t}\n\t\t\t\tEUID_USER();}\n#endif\n\t\t\t\t// run sftp and scp directly without any sandboxing\n\t\t\t\t// regular login has argv[0] == \"-firejail\"\n\t\t\t\tif (*argv[0] != '-') {\n\t\t\t\t\tif (strcmp(argv[1], \"-c\") == 0 && argc > 2) {\n\t\t\t\t\t\tif (strcmp(argv[2], \"/usr/lib/openssh/sftp-server\") == 0 ||\n\t\t\t\t\t\t strncmp(argv[2], \"scp \", 4) == 0) {\n#ifdef DEBUG_RESTRICTED_SHELL\n\t\t\t\t\t\t\t{EUID_ROOT();\n\t\t\t\t\t\t\tFILE *fp = fopen(\"/firelog\", \"ae\");\n\t\t\t\t\t\t\tif (fp) {\n\t\t\t\t\t\t\t\tfprintf(fp, \"run without a sandbox\\n\");\n\t\t\t\t\t\t\t\tfclose(fp);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tEUID_USER();}\n#endif\n\n\t\t\t\t\t\t\tdrop_privs(1);\n\t\t\t\t\t\t\tumask(orig_umask);\n\n\t\t\t\t\t\t\t// restore original environment variables\n\t\t\t\t\t\t\tenv_apply_all();\n\t\t\t\t\t\t\tint rv = system(argv[2]);\n\t\t\t\t\t\t\texit(rv);\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\tfree(comm);\n\t\t}\n\t}\n\tEUID_ASSERT();\n\n\t// is this a login shell, or a command passed by sshd,\n\t// insert command line options from /etc/firejail/login.users\n\tif (*argv[0] == '-' || parent_sshd) {\n\t\tif (argc == 1)\n\t\t\tlogin_shell = 1;\n\t\tfullargc = restricted_shell(cfg.username);\n\t\tif (fullargc) {\n\n#ifdef DEBUG_RESTRICTED_SHELL\n\t\t\t{EUID_ROOT();\n\t\t\tFILE *fp = fopen(\"/firelog\", \"ae\");\n\t\t\tif (fp) {\n\t\t\t\tfprintf(fp, \"fullargc %d: \", fullargc);\n\t\t\t\tint i;\n\t\t\t\tfor (i = 0; i < fullargc; i++)\n\t\t\t\t\tfprintf(fp, \"#%s# \", fullargv[i]);\n\t\t\t\tfprintf(fp, \"\\n\");\n\t\t\t\tfclose(fp);\n\t\t\t}\n\t\t\tEUID_USER();}\n#endif\n\n\t\t\tint j;\n\t\t\tfor (i = 1, j = fullargc; i < argc && j < MAX_ARGS; i++, j++, fullargc++)\n\t\t\t\tfullargv[j] = argv[i];\n\n\t\t\t// replace argc/argv with fullargc/fullargv\n\t\t\targv = fullargv;\n\t\t\targc = j;\n\n#ifdef DEBUG_RESTRICTED_SHELL\n\t\t\t{EUID_ROOT();\n\t\t\tFILE *fp = fopen(\"/firelog\", \"ae\");\n\t\t\tif (fp) {\n\t\t\t\tfprintf(fp, \"argc %d: \", argc);\n\t\t\t\tint i;\n\t\t\t\tfor (i = 0; i < argc; i++)\n\t\t\t\t\tfprintf(fp, \"#%s# \", argv[i]);\n\t\t\t\tfprintf(fp, \"\\n\");\n\t\t\t\tfclose(fp);\n\t\t\t}\n\t\t\tEUID_USER();}\n#endif\n\t\t}\n\t}\n#ifdef HAVE_OUTPUT\n\telse {\n\t\t// check --output option and execute it;\n\t\tcheck_output(argc, argv); // the function will not return if --output or --output-stderr option was found\n\t}\n#endif\n\tEUID_ASSERT();\n\n\t// --ip=dhcp - we need access to /sbin and /usr/sbin directories in order to run ISC DHCP client (dhclient)\n\t// these paths are disabled in disable-common.inc\n\tif ((i = check_arg(argc, argv, \"--ip\", 0)) != 0) {\n\t\tif (strncmp(argv[i] + 4, \"=dhcp\", 5) == 0) {\n\t\t\tprofile_add(\"noblacklist /sbin\");\n\t\t\tprofile_add(\"noblacklist /usr/sbin\");\n\t\t}\n\t}\n\n\t// process allow-debuggers\n\tif (check_arg(argc, argv, \"--allow-debuggers\", 1)) {\n\t\t// check kernel version\n\t\tstruct utsname u;\n\t\tint rv = uname(&u);\n\t\tif (rv != 0)\n\t\t\terrExit(\"uname\");\n\t\tint major;\n\t\tint minor;\n\t\tif (2 != sscanf(u.release, \"%d.%d\", &major, &minor)) {\n\t\t\tfprintf(stderr, \"Error: cannot extract Linux kernel version: %s\\n\", u.version);\n\t\t\texit(1);\n\t\t}\n\t\tif (major < 4 || (major == 4 && minor < 8)) {\n\t\t\tfprintf(stderr, \"Error: --allow-debuggers is disabled on Linux kernels prior to 4.8. \"\n\t\t\t\t\"A bug in ptrace call allows a full bypass of the seccomp filter. \"\n\t\t\t\t\"Your current kernel version is %d.%d.\\n\", major, minor);\n\t\t\texit(1);\n\t\t}\n\n\t\targ_allow_debuggers = 1;\n\t\tchar *cmd = strdup(\"noblacklist ${PATH}/strace\");\n\t\tif (!cmd)\n\t\t\terrExit(\"strdup\");\n\t\tprofile_add(cmd);\n\t}\n\n\t// for appimages we need to remove \"include disable-shell.inc from the profile\n\t// a --profile command can show up before --appimage\n\tif (check_arg(argc, argv, \"--appimage\", 1))\n\t\targ_appimage = 1;\n\n\t// check for force-nonewprivs in /etc/firejail/firejail.config file\n\tif (checkcfg(CFG_FORCE_NONEWPRIVS))\n\t\targ_nonewprivs = 1;\n\n\t// check oom\n\tif ((i = check_arg(argc, argv, \"--oom=\", 0)) != 0)\n\t\toom_set(argv[i] + 6);\n\n\t// parse arguments\n\tfor (i = 1; i < argc; i++) {\n\t\trun_cmd_and_exit(i, argc, argv); // will exit if the command is recognized\n\n\t\tif (strcmp(argv[i], \"--debug\") == 0) {\n\t\t\targ_debug = 1;\n\t\t\targ_quiet = 0;\n\t\t}\n\t\telse if (strcmp(argv[i], \"--debug-blacklists\") == 0)\n\t\t\targ_debug_blacklists = 1;\n\t\telse if (strcmp(argv[i], \"--debug-whitelists\") == 0)\n\t\t\targ_debug_whitelists = 1;\n\t\telse if (strcmp(argv[i], \"--debug-private-lib\") == 0)\n\t\t\targ_debug_private_lib = 1;\n\t\telse if (strcmp(argv[i], \"--quiet\") == 0) {\n\t\t\tif (!arg_debug)\n\t\t\t\targ_quiet = 1;\n\t\t}\n\t\telse if (strcmp(argv[i], \"--allow-debuggers\") == 0) {\n\t\t\t// already handled\n\t\t}\n\n\n\t\t//*************************************\n\t\t// x11\n\t\t//*************************************\n\n#ifdef HAVE_X11\n\t\telse if (strncmp(argv[i], \"--xephyr-screen=\", 16) == 0) {\n\t\t\tif (checkcfg(CFG_X11))\n\t\t\t\t; // the processing is done directly in x11.c\n\t\t\telse\n\t\t\t\texit_err_feature(\"x11\");\n\t\t}\n#endif\n\t\t//*************************************\n\t\t// filtering\n\t\t//*************************************\n#ifdef HAVE_APPARMOR\n\t\telse if (strcmp(argv[i], \"--apparmor\") == 0)\n\t\t\targ_apparmor = 1;\n#endif\n\t\telse if (strncmp(argv[i], \"--protocol=\", 11) == 0) {\n\t\t\tif (checkcfg(CFG_SECCOMP)) {\n\t\t\t\tconst char *add = argv[i] + 11;\n\t\t\t\tprofile_list_augment(&cfg.protocol, add);\n\t\t\t\tif (arg_debug)\n\t\t\t\t\tfprintf(stderr, \"[option] combined protocol list: \\\"%s\\\"\\n\", cfg.protocol);\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"seccomp\");\n\t\t}\n\t\telse if (strcmp(argv[i], \"--seccomp\") == 0) {\n\t\t\tif (checkcfg(CFG_SECCOMP)) {\n\t\t\t\tif (arg_seccomp) {\n\t\t\t\t\tfprintf(stderr, \"Error: seccomp already enabled\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\targ_seccomp = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"seccomp\");\n\t\t}\n\t\telse if (strncmp(argv[i], \"--seccomp=\", 10) == 0) {\n\t\t\tif (checkcfg(CFG_SECCOMP)) {\n\t\t\t\tif (arg_seccomp) {\n\t\t\t\t\tfprintf(stderr, \"Error: seccomp already enabled\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\targ_seccomp = 1;\n\t\t\t\tcfg.seccomp_list = seccomp_check_list(argv[i] + 10);\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"seccomp\");\n\t\t}\n\t\telse if (strncmp(argv[i], \"--seccomp.32=\", 13) == 0) {\n\t\t\tif (checkcfg(CFG_SECCOMP)) {\n\t\t\t\tif (arg_seccomp32) {\n\t\t\t\t\tfprintf(stderr, \"Error: seccomp.32 already enabled\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\targ_seccomp32 = 1;\n\t\t\t\tcfg.seccomp_list32 = seccomp_check_list(argv[i] + 13);\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"seccomp\");\n\t\t}\n\t\telse if (strncmp(argv[i], \"--seccomp.drop=\", 15) == 0) {\n\t\t\tif (checkcfg(CFG_SECCOMP)) {\n\t\t\t\tif (arg_seccomp) {\n\t\t\t\t\tfprintf(stderr, \"Error: seccomp already enabled\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\targ_seccomp = 1;\n\t\t\t\tcfg.seccomp_list_drop = seccomp_check_list(argv[i] + 15);\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"seccomp\");\n\t\t}\n\t\telse if (strncmp(argv[i], \"--seccomp.32.drop=\", 18) == 0) {\n\t\t\tif (checkcfg(CFG_SECCOMP)) {\n\t\t\t\tif (arg_seccomp32) {\n\t\t\t\t\tfprintf(stderr, \"Error: seccomp.32 already enabled\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\targ_seccomp32 = 1;\n\t\t\t\tcfg.seccomp_list_drop32 = seccomp_check_list(argv[i] + 18);\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"seccomp\");\n\t\t}\n\t\telse if (strncmp(argv[i], \"--seccomp.keep=\", 15) == 0) {\n\t\t\tif (checkcfg(CFG_SECCOMP)) {\n\t\t\t\tif (arg_seccomp) {\n\t\t\t\t\tfprintf(stderr, \"Error: seccomp already enabled\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\targ_seccomp = 1;\n\t\t\t\tcfg.seccomp_list_keep = seccomp_check_list(argv[i] + 15);\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"seccomp\");\n\t\t}\n\t\telse if (strncmp(argv[i], \"--seccomp.32.keep=\", 18) == 0) {\n\t\t\tif (checkcfg(CFG_SECCOMP)) {\n\t\t\t\tif (arg_seccomp32) {\n\t\t\t\t\tfprintf(stderr, \"Error: seccomp.32 already enabled\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\targ_seccomp32 = 1;\n\t\t\t\tcfg.seccomp_list_keep32 = seccomp_check_list(argv[i] + 18);\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"seccomp\");\n\t\t}\n\t\telse if (strcmp(argv[i], \"--seccomp.block-secondary\") == 0) {\n\t\t\tif (checkcfg(CFG_SECCOMP)) {\n\t\t\t\tif (arg_seccomp32) {\n\t\t\t\t\tfprintf(stderr, \"Error: seccomp.32 conflicts with block-secondary\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\targ_seccomp_block_secondary = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"seccomp\");\n\t\t}\n\t\telse if (strcmp(argv[i], \"--memory-deny-write-execute\") == 0) {\n\t\t\tif (checkcfg(CFG_SECCOMP))\n\t\t\t\targ_memory_deny_write_execute = 1;\n\t\t\telse\n\t\t\t\texit_err_feature(\"seccomp\");\n\t\t}\n\t\telse if (strncmp(argv[i], \"--seccomp-error-action=\", 23) == 0) {\n\t\t\tif (checkcfg(CFG_SECCOMP)) {\n\t\t\t\tint config_seccomp_error_action = checkcfg(CFG_SECCOMP_ERROR_ACTION);\n\t\t\t\tif (config_seccomp_error_action == -1) {\n\t\t\t\t\tif (strcmp(argv[i] + 23, \"kill\") == 0)\n\t\t\t\t\t\targ_seccomp_error_action = SECCOMP_RET_KILL;\n\t\t\t\t\telse if (strcmp(argv[i] + 23, \"log\") == 0)\n\t\t\t\t\t\targ_seccomp_error_action = SECCOMP_RET_LOG;\n\t\t\t\t\telse {\n\t\t\t\t\t\targ_seccomp_error_action = errno_find_name(argv[i] + 23);\n\t\t\t\t\t\tif (arg_seccomp_error_action == -1)\n\t\t\t\t\t\t\terrExit(\"seccomp-error-action: unknown errno\");\n\t\t\t\t\t}\n\t\t\t\t\tcfg.seccomp_error_action = strdup(argv[i] + 23);\n\t\t\t\t\tif (!cfg.seccomp_error_action)\n\t\t\t\t\t\terrExit(\"strdup\");\n\t\t\t\t} else\n\t\t\t\t\texit_err_feature(\"seccomp-error-action\");\n\n\t\t\t} else\n\t\t\t\texit_err_feature(\"seccomp\");\n\t\t}\n\t\telse if (strcmp(argv[i], \"--caps\") == 0) {\n\t\t\targ_caps_default_filter = 1;\n\t\t\targ_caps_cmdline = 1;\n\t\t}\n\t\telse if (strcmp(argv[i], \"--caps.drop=all\") == 0)\n\t\t\targ_caps_drop_all = 1;\n\t\telse if (strncmp(argv[i], \"--caps.drop=\", 12) == 0) {\n\t\t\targ_caps_drop = 1;\n\t\t\targ_caps_list = strdup(argv[i] + 12);\n\t\t\tif (!arg_caps_list)\n\t\t\t\terrExit(\"strdup\");\n\t\t\t// verify caps list and exit if problems\n\t\t\tcaps_check_list(arg_caps_list, NULL);\n\t\t\targ_caps_cmdline = 1;\n\t\t}\n\t\telse if (strncmp(argv[i], \"--caps.keep=\", 12) == 0) {\n\t\t\targ_caps_keep = 1;\n\t\t\targ_caps_list = strdup(argv[i] + 12);\n\t\t\tif (!arg_caps_list)\n\t\t\t\terrExit(\"strdup\");\n\t\t\t// verify caps list and exit if problems\n\t\t\tcaps_check_list(arg_caps_list, NULL);\n\t\t\targ_caps_cmdline = 1;\n\t\t}\n\t\telse if (strcmp(argv[i], \"--trace\") == 0)\n\t\t\targ_trace = 1;\n\t\telse if (strncmp(argv[i], \"--trace=\", 8) == 0) {\n\t\t\targ_trace = 1;\n\t\t\targ_tracefile = argv[i] + 8;\n\t\t\tif (*arg_tracefile == '\\0') {\n\t\t\t\tfprintf(stderr, \"Error: invalid trace option\\n\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tinvalid_filename(arg_tracefile, 0); // no globbing\n\t\t\tif (strstr(arg_tracefile, \"..\")) {\n\t\t\t\tfprintf(stderr, \"Error: invalid file name %s\\n\", arg_tracefile);\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\t// if the filename starts with ~, expand the home directory\n\t\t\tif (*arg_tracefile == '~') {\n\t\t\t\tchar *tmp;\n\t\t\t\tif (asprintf(&tmp, \"%s%s\", cfg.homedir, arg_tracefile + 1) == -1)\n\t\t\t\t\terrExit(\"asprintf\");\n\t\t\t\targ_tracefile = tmp;\n\t\t\t}\n\t\t}\n\t\telse if (strcmp(argv[i], \"--tracelog\") == 0)\n\t\t\targ_tracelog = 1;\n\t\telse if (strncmp(argv[i], \"--rlimit-cpu=\", 13) == 0) {\n\t\t\tcheck_unsigned(argv[i] + 13, \"Error: invalid rlimit\");\n\t\t\tsscanf(argv[i] + 13, \"%llu\", &cfg.rlimit_cpu);\n\t\t\targ_rlimit_cpu = 1;\n\t\t}\n\t\telse if (strncmp(argv[i], \"--rlimit-nofile=\", 16) == 0) {\n\t\t\tcheck_unsigned(argv[i] + 16, \"Error: invalid rlimit\");\n\t\t\tsscanf(argv[i] + 16, \"%llu\", &cfg.rlimit_nofile);\n\t\t\targ_rlimit_nofile = 1;\n\t\t}\n\t\telse if (strncmp(argv[i], \"--rlimit-nproc=\", 15) == 0) {\n\t\t\tcheck_unsigned(argv[i] + 15, \"Error: invalid rlimit\");\n\t\t\tsscanf(argv[i] + 15, \"%llu\", &cfg.rlimit_nproc);\n\t\t\targ_rlimit_nproc = 1;\n\t\t}\n\t\telse if (strncmp(argv[i], \"--rlimit-fsize=\", 15) == 0) {\n\t\t\tcfg.rlimit_fsize = parse_arg_size(argv[i] + 15);\n\t\t\tif (cfg.rlimit_fsize == 0) {\n\t\t\t\tperror(\"Error: invalid rlimit-fsize. Only use positive numbers and k, m or g suffix.\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\targ_rlimit_fsize = 1;\n\t\t}\n\t\telse if (strncmp(argv[i], \"--rlimit-sigpending=\", 20) == 0) {\n\t\t\tcheck_unsigned(argv[i] + 20, \"Error: invalid rlimit\");\n\t\t\tsscanf(argv[i] + 20, \"%llu\", &cfg.rlimit_sigpending);\n\t\t\targ_rlimit_sigpending = 1;\n\t\t}\n\t\telse if (strncmp(argv[i], \"--rlimit-as=\", 12) == 0) {\n\t\t\tcfg.rlimit_as = parse_arg_size(argv[i] + 12);\n\t\t\tif (cfg.rlimit_as == 0) {\n\t\t\t\tperror(\"Error: invalid rlimit-as. Only use positive numbers and k, m or g suffix.\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\targ_rlimit_as = 1;\n\t\t}\n\t\telse if (strncmp(argv[i], \"--ipc-namespace\", 15) == 0)\n\t\t\targ_ipc = 1;\n\t\telse if (strncmp(argv[i], \"--cpu=\", 6) == 0)\n\t\t\tread_cpu_list(argv[i] + 6);\n\t\telse if (strncmp(argv[i], \"--nice=\", 7) == 0) {\n\t\t\tcfg.nice = atoi(argv[i] + 7);\n\t\t\tif (getuid() != 0 &&cfg.nice < 0)\n\t\t\t\tcfg.nice = 0;\n\t\t\targ_nice = 1;\n\t\t}\n\t\telse if (strncmp(argv[i], \"--cgroup=\", 9) == 0) {\n\t\t\tif (checkcfg(CFG_CGROUP)) {\n\t\t\t\tif (option_cgroup) {\n\t\t\t\t\tfprintf(stderr, \"Error: only one cgroup can be defined\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tcfg.cgroup = strdup(argv[i] + 9);\n\t\t\t\tif (!cfg.cgroup)\n\t\t\t\t\terrExit(\"strdup\");\n\n\t\t\t\tcheck_cgroup_file(cfg.cgroup);\n\t\t\t\tset_cgroup(cfg.cgroup, getpid());\n\t\t\t\toption_cgroup = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"cgroup\");\n\t\t}\n\n\t\t//*************************************\n\t\t// filesystem\n\t\t//*************************************\n\t\telse if (strcmp(argv[i], \"--allusers\") == 0)\n\t\t\targ_allusers = 1;\n\t\telse if (strncmp(argv[i], \"--bind=\", 7) == 0) {\n\t\t\tif (checkcfg(CFG_BIND)) {\n\t\t\t\tchar *line;\n\t\t\t\tif (asprintf(&line, \"bind %s\", argv[i] + 7) == -1)\n\t\t\t\t\terrExit(\"asprintf\");\n\n\t\t\t\tprofile_check_line(line, 0, NULL);\t// will exit if something wrong\n\t\t\t\tprofile_add(line);\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"bind\");\n\t\t}\n\t\telse if (strncmp(argv[i], \"--tmpfs=\", 8) == 0) {\n\t\t\tchar *line;\n\t\t\tif (asprintf(&line, \"tmpfs %s\", argv[i] + 8) == -1)\n\t\t\t\terrExit(\"asprintf\");\n\n\t\t\tprofile_check_line(line, 0, NULL);\t// will exit if something wrong\n\t\t\tprofile_add(line);\n\t\t}\n\n\t\telse if (strncmp(argv[i], \"--blacklist=\", 12) == 0) {\n\t\t\tchar *line;\n\t\t\tif (asprintf(&line, \"blacklist %s\", argv[i] + 12) == -1)\n\t\t\t\terrExit(\"asprintf\");\n\n\t\t\tprofile_check_line(line, 0, NULL);\t// will exit if something wrong\n\t\t\tprofile_add(line);\n\t\t}\n\t\telse if (strncmp(argv[i], \"--noblacklist=\", 14) == 0) {\n\t\t\tchar *line;\n\t\t\tif (asprintf(&line, \"noblacklist %s\", argv[i] + 14) == -1)\n\t\t\t\terrExit(\"asprintf\");\n\n\t\t\tprofile_check_line(line, 0, NULL);\t// will exit if something wrong\n\t\t\tprofile_add(line);\n\t\t}\n\t\telse if (strncmp(argv[i], \"--whitelist=\", 12) == 0) {\n\t\t\tchar *line;\n\t\t\tif (asprintf(&line, \"whitelist %s\", argv[i] + 12) == -1)\n\t\t\t\terrExit(\"asprintf\");\n\n\t\t\tprofile_check_line(line, 0, NULL);\t// will exit if something wrong\n\t\t\tprofile_add(line);\n\t\t}\n\t\telse if (strncmp(argv[i], \"--nowhitelist=\", 14) == 0) {\n\t\t\tchar *line;\n\t\t\tif (asprintf(&line, \"nowhitelist %s\", argv[i] + 14) == -1)\n\t\t\t\terrExit(\"asprintf\");\n\n\t\t\tprofile_check_line(line, 0, NULL);\t// will exit if something wrong\n\t\t\tprofile_add(line);\n\t\t}\n\n\t\telse if (strncmp(argv[i], \"--mkdir=\", 8) == 0) {\n\t\t\tchar *line;\n\t\t\tif (asprintf(&line, \"mkdir %s\", argv[i] + 8) == -1)\n\t\t\t\terrExit(\"asprintf\");\n\t\t\t/* Note: Applied both immediately in profile_check_line()\n\t\t\t * and later on via fs_blacklist().\n\t\t\t */\n\t\t\tprofile_check_line(line, 0, NULL);\n\t\t\tprofile_add(line);\n\t\t}\n\t\telse if (strncmp(argv[i], \"--mkfile=\", 9) == 0) {\n\t\t\tchar *line;\n\t\t\tif (asprintf(&line, \"mkfile %s\", argv[i] + 9) == -1)\n\t\t\t\terrExit(\"asprintf\");\n\t\t\t/* Note: Applied both immediately in profile_check_line()\n\t\t\t * and later on via fs_blacklist().\n\t\t\t */\n\t\t\tprofile_check_line(line, 0, NULL);\n\t\t\tprofile_add(line);\n\t\t}\n\t\telse if (strncmp(argv[i], \"--read-only=\", 12) == 0) {\n\t\t\tchar *line;\n\t\t\tif (asprintf(&line, \"read-only %s\", argv[i] + 12) == -1)\n\t\t\t\terrExit(\"asprintf\");\n\n\t\t\tprofile_check_line(line, 0, NULL);\t// will exit if something wrong\n\t\t\tprofile_add(line);\n\t\t}\n\t\telse if (strncmp(argv[i], \"--noexec=\", 9) == 0) {\n\t\t\tchar *line;\n\t\t\tif (asprintf(&line, \"noexec %s\", argv[i] + 9) == -1)\n\t\t\t\terrExit(\"asprintf\");\n\n\t\t\tprofile_check_line(line, 0, NULL);\t// will exit if something wrong\n\t\t\tprofile_add(line);\n\t\t}\n\t\telse if (strncmp(argv[i], \"--read-write=\", 13) == 0) {\n\t\t\tchar *line;\n\t\t\tif (asprintf(&line, \"read-write %s\", argv[i] + 13) == -1)\n\t\t\t\terrExit(\"asprintf\");\n\n\t\t\tprofile_check_line(line, 0, NULL);\t// will exit if something wrong\n\t\t\tprofile_add(line);\n\t\t}\n\t\telse if (strcmp(argv[i], \"--disable-mnt\") == 0)\n\t\t\targ_disable_mnt = 1;\n#ifdef HAVE_OVERLAYFS\n\t\telse if (strcmp(argv[i], \"--overlay\") == 0) {\n\t\t\tif (checkcfg(CFG_OVERLAYFS)) {\n\t\t\t\tif (arg_overlay) {\n\t\t\t\t\tfprintf(stderr, \"Error: only one overlay command is allowed\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\n\t\t\t\tif (cfg.chrootdir) {\n\t\t\t\t\tfprintf(stderr, \"Error: --overlay and --chroot options are mutually exclusive\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tstruct stat s;\n\t\t\t\tif (stat(\"/proc/sys/kernel/grsecurity\", &s) == 0) {\n\t\t\t\t\tfprintf(stderr, \"Error: --overlay option is not available on Grsecurity systems\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\targ_overlay = 1;\n\t\t\t\targ_overlay_keep = 1;\n\n\t\t\t\tchar *subdirname;\n\t\t\t\tif (asprintf(&subdirname, \"%d\", getpid()) == -1)\n\t\t\t\t\terrExit(\"asprintf\");\n\t\t\t\tcfg.overlay_dir = fs_check_overlay_dir(subdirname, arg_overlay_reuse);\n\n\t\t\t\tfree(subdirname);\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"overlayfs\");\n\t\t}\n\t\telse if (strncmp(argv[i], \"--overlay-named=\", 16) == 0) {\n\t\t\tif (checkcfg(CFG_OVERLAYFS)) {\n\t\t\t\tif (arg_overlay) {\n\t\t\t\t\tfprintf(stderr, \"Error: only one overlay command is allowed\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tif (cfg.chrootdir) {\n\t\t\t\t\tfprintf(stderr, \"Error: --overlay and --chroot options are mutually exclusive\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tstruct stat s;\n\t\t\t\tif (stat(\"/proc/sys/kernel/grsecurity\", &s) == 0) {\n\t\t\t\t\tfprintf(stderr, \"Error: --overlay option is not available on Grsecurity systems\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\targ_overlay = 1;\n\t\t\t\targ_overlay_keep = 1;\n\t\t\t\targ_overlay_reuse = 1;\n\n\t\t\t\tchar *subdirname = argv[i] + 16;\n\t\t\t\tif (*subdirname == '\\0') {\n\t\t\t\t\tfprintf(stderr, \"Error: invalid overlay option\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\n\t\t\t\t// check name\n\t\t\t\tinvalid_filename(subdirname, 0); // no globbing\n\t\t\t\tif (strstr(subdirname, \"..\") || strstr(subdirname, \"/\")) {\n\t\t\t\t\tfprintf(stderr, \"Error: invalid overlay name\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tcfg.overlay_dir = fs_check_overlay_dir(subdirname, arg_overlay_reuse);\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"overlayfs\");\n\t\t}\n\t\telse if (strcmp(argv[i], \"--overlay-tmpfs\") == 0) {\n\t\t\tif (checkcfg(CFG_OVERLAYFS)) {\n\t\t\t\tif (arg_overlay) {\n\t\t\t\t\tfprintf(stderr, \"Error: only one overlay command is allowed\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tif (cfg.chrootdir) {\n\t\t\t\t\tfprintf(stderr, \"Error: --overlay and --chroot options are mutually exclusive\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tstruct stat s;\n\t\t\t\tif (stat(\"/proc/sys/kernel/grsecurity\", &s) == 0) {\n\t\t\t\t\tfprintf(stderr, \"Error: --overlay option is not available on Grsecurity systems\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\targ_overlay = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"overlayfs\");\n\t\t}\n#endif\n#ifdef HAVE_FIRETUNNEL\n\t\telse if (strcmp(argv[i], \"--tunnel\") == 0) {\n\t\t\t// try to connect to the default client side of the tunnel\n\t\t\t// if this fails, try the default server side of the tunnel\n\t\t\tif (access(\"/run/firetunnel/ftc\", R_OK) == 0)\n\t\t\t\tprofile_read(\"/run/firetunnel/ftc\");\n\t\t\telse if (access(\"/run/firetunnel/fts\", R_OK) == 0)\n\t\t\t\tprofile_read(\"/run/firetunnel/fts\");\n\t\t\telse {\n\t\t\t\tfprintf(stderr, \"Error: no default firetunnel found, please specify it using --tunnel=devname option\\n\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t}\n\t\telse if (strncmp(argv[i], \"--tunnel=\", 9) == 0) {\n\t\t\tchar *fname;\n\n\t\t\tif (asprintf(&fname, \"/run/firetunnel/%s\", argv[i] + 9) == -1)\n\t\t\t\terrExit(\"asprintf\");\n\t\t\tinvalid_filename(fname, 0); // no globbing\n\t\t\tif (access(fname, R_OK) == 0)\n\t\t\t\tprofile_read(fname);\n\t\t\telse {\n\t\t\t\tfprintf(stderr, \"Error: tunnel not found\\n\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t}\n#endif\n\t\telse if (strncmp(argv[i], \"--include=\", 10) == 0) {\n\t\t\tchar *ppath = expand_macros(argv[i] + 10);\n\t\t\tif (!ppath)\n\t\t\t\terrExit(\"strdup\");\n\n\t\t\tchar *ptr = ppath;\n\t\t\twhile (*ptr != '/' && *ptr != '\\0')\n\t\t\t\tptr++;\n\t\t\tif (*ptr == '\\0') {\n\t\t\t\tif (access(ppath, R_OK)) {\n\t\t\t\t\tprofile_read(ppath);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// ppath contains no '/' and is not a local file, assume it's a name\n\t\t\t\t\tint rv = profile_find_firejail(ppath, 0);\n\t\t\t\t\tif (!rv) {\n\t\t\t\t\t\tfprintf(stderr, \"Error: no profile with name \\\"%s\\\" found.\\n\", ppath);\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// ppath contains a '/', assume it's a path\n\t\t\t\tprofile_read(ppath);\n\t\t\t}\n\n\t\t\tfree(ppath);\n\t\t}\n\t\telse if (strncmp(argv[i], \"--profile=\", 10) == 0) {\n\t\t\t// multiple profile files are allowed!\n\n\t\t\tif (arg_noprofile) {\n\t\t\t\tfprintf(stderr, \"Error: --noprofile and --profile options are mutually exclusive\\n\");\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\tchar *ppath = expand_macros(argv[i] + 10);\n\t\t\tif (!ppath)\n\t\t\t\terrExit(\"strdup\");\n\n\t\t\t// checking for strange chars in the file name, no globbing\n\t\t\tinvalid_filename(ppath, 0);\n\n\t\t\tif (*ppath == ':' || access(ppath, R_OK) || is_dir(ppath)) {\n\t\t\t\tint has_colon = (*ppath == ':');\n\t\t\t\tchar *ptr = ppath;\n\t\t\t\twhile (*ptr != '/' && *ptr != '.' && *ptr != '\\0')\n\t\t\t\t\tptr++;\n\t\t\t\t// profile path contains no / or . chars,\n\t\t\t\t// assume its a profile name\n\t\t\t\tif (*ptr != '\\0') {\n\t\t\t\t\tfprintf(stderr, \"Error: inaccessible profile file: %s\\n\", ppath);\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\n\t\t\t\t// profile was not read in previously, try to see if\n\t\t\t\t// we were given a profile name.\n\t\t\t\tif (!profile_find_firejail(ppath + has_colon, 1)) {\n\t\t\t\t\t// do not fall through to default profile,\n\t\t\t\t\t// because the user should be notified that\n\t\t\t\t\t// given profile arg could not be used.\n\t\t\t\t\tfprintf(stderr, \"Error: no profile with name \\\"%s\\\" found.\\n\", ppath);\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tcustom_profile = 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprofile_read(ppath);\n\t\t\t\tcustom_profile = 1;\n\t\t\t}\n\t\t\tfree(ppath);\n\t\t}\n\t\telse if (strcmp(argv[i], \"--noprofile\") == 0) {\n\t\t\tif (custom_profile) {\n\t\t\t\tfprintf(stderr, \"Error: --profile and --noprofile options are mutually exclusive\\n\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\targ_noprofile = 1;\n\t\t\t// force keep-config-pulse in order to keep ~/.config/pulse as is\n\t\t\targ_keep_config_pulse = 1;\n\t\t}\n\t\telse if (strncmp(argv[i], \"--ignore=\", 9) == 0) {\n\t\t\tif (custom_profile) {\n\t\t\t\tfprintf(stderr, \"Error: please use --profile after --ignore\\n\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tprofile_add_ignore(argv[i] + 9);\n\t\t}\n\t\telse if (strncmp(argv[i], \"--keep-fd=\", 10) == 0) {\n\t\t\tif (strcmp(argv[i] + 10, \"all\") == 0)\n\t\t\t\targ_keep_fd_all = 1;\n\t\t\telse {\n\t\t\t\tconst char *add = argv[i] + 10;\n\t\t\t\tprofile_list_augment(&cfg.keep_fd, add);\n\t\t\t}\n\t\t}\n#ifdef HAVE_CHROOT\n\t\telse if (strncmp(argv[i], \"--chroot=\", 9) == 0) {\n\t\t\tif (checkcfg(CFG_CHROOT)) {\n\t\t\t\tif (arg_overlay) {\n\t\t\t\t\tfprintf(stderr, \"Error: --overlay and --chroot options are mutually exclusive\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\n\t\t\t\tstruct stat s;\n\t\t\t\tif (stat(\"/proc/sys/kernel/grsecurity\", &s) == 0) {\n\t\t\t\t\tfprintf(stderr, \"Error: --chroot option is not available on Grsecurity systems\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\t// extract chroot dirname\n\t\t\t\tcfg.chrootdir = argv[i] + 9;\n\t\t\t\tif (*cfg.chrootdir == '\\0') {\n\t\t\t\t\tfprintf(stderr, \"Error: invalid chroot option\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tinvalid_filename(cfg.chrootdir, 0); // no globbing\n\n\t\t\t\t// if the directory starts with ~, expand the home directory\n\t\t\t\tif (*cfg.chrootdir == '~') {\n\t\t\t\t\tchar *tmp;\n\t\t\t\t\tif (asprintf(&tmp, \"%s%s\", cfg.homedir, cfg.chrootdir + 1) == -1)\n\t\t\t\t\t\terrExit(\"asprintf\");\n\t\t\t\t\tcfg.chrootdir = tmp;\n\t\t\t\t}\n\t\t\t\t// check chroot directory\n\t\t\t\tfs_check_chroot_dir();\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"chroot\");\n\t\t}\n#endif\n\t\telse if (strcmp(argv[i], \"--writable-etc\") == 0) {\n\t\t\tif (cfg.etc_private_keep) {\n\t\t\t\tfprintf(stderr, \"Error: --private-etc and --writable-etc are mutually exclusive\\n\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\targ_writable_etc = 1;\n\t\t}\n\t\telse if (strcmp(argv[i], \"--keep-config-pulse\") == 0) {\n\t\t\targ_keep_config_pulse = 1;\n\t\t}\n\t\telse if (strcmp(argv[i], \"--writable-var\") == 0) {\n\t\t\targ_writable_var = 1;\n\t\t}\n\t\telse if (strcmp(argv[i], \"--keep-var-tmp\") == 0) {\n\t\t arg_keep_var_tmp = 1;\n\t\t}\n\t\telse if (strcmp(argv[i], \"--writable-run-user\") == 0) {\n\t\t\targ_writable_run_user = 1;\n\t\t}\n\t\telse if (strcmp(argv[i], \"--writable-var-log\") == 0) {\n\t\t\targ_writable_var_log = 1;\n\t\t}\n\t\telse if (strcmp(argv[i], \"--machine-id\") == 0) {\n\t\t\targ_machineid = 1;\n\t\t}\n\t\telse if (strcmp(argv[i], \"--private\") == 0) {\n\t\t\targ_private = 1;\n\t\t}\n\t\telse if (strncmp(argv[i], \"--private=\", 10) == 0) {\n\t\t\tif (cfg.home_private_keep) {\n\t\t\t\tfprintf(stderr, \"Error: a private list of files was already defined with --private-home option.\\n\");\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\t// extract private home dirname\n\t\t\tcfg.home_private = argv[i] + 10;\n\t\t\tif (*cfg.home_private == '\\0') {\n\t\t\t\tfprintf(stderr, \"Error: invalid private option\\n\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tfs_check_private_dir();\n\n\t\t\t// downgrade to --private if the directory is the user home directory\n\t\t\tif (strcmp(cfg.home_private, cfg.homedir) == 0) {\n\t\t\t\tfree(cfg.home_private);\n\t\t\t\tcfg.home_private = NULL;\n\t\t\t}\n\t\t\targ_private = 1;\n\t\t}\n#ifdef HAVE_PRIVATE_HOME\n\t\telse if (strncmp(argv[i], \"--private-home=\", 15) == 0) {\n\t\t\tif (checkcfg(CFG_PRIVATE_HOME)) {\n\t\t\t\tif (cfg.home_private) {\n\t\t\t\t\tfprintf(stderr, \"Error: a private home directory was already defined with --private option.\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\n\t\t\t\t// extract private home dirname\n\t\t\t\tif (*(argv[i] + 15) == '\\0') {\n\t\t\t\t\tfprintf(stderr, \"Error: invalid private-home option\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tif (cfg.home_private_keep) {\n\t\t\t\t\tif ( asprintf(&cfg.home_private_keep, \"%s,%s\", cfg.home_private_keep, argv[i] + 15) < 0 )\n\t\t\t\t\t\terrExit(\"asprintf\");\n\t\t\t\t} else\n\t\t\t\t\tcfg.home_private_keep = argv[i] + 15;\n\t\t\t\targ_private = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"private-home\");\n\t\t}\n#endif\n\t\telse if (strcmp(argv[i], \"--private-dev\") == 0) {\n\t\t\targ_private_dev = 1;\n\t\t}\n\t\telse if (strcmp(argv[i], \"--keep-dev-shm\") == 0) {\n\t\t\targ_keep_dev_shm = 1;\n\t\t}\n\t\telse if (strncmp(argv[i], \"--private-etc=\", 14) == 0) {\n\t\t\tif (checkcfg(CFG_PRIVATE_ETC)) {\n\t\t\t\tif (arg_writable_etc) {\n\t\t\t\t\tfprintf(stderr, \"Error: --private-etc and --writable-etc are mutually exclusive\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\n\t\t\t\t// extract private etc list\n\t\t\t\tif (*(argv[i] + 14) == '\\0') {\n\t\t\t\t\tfprintf(stderr, \"Error: invalid private-etc option\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tif (cfg.etc_private_keep) {\n\t\t\t\t\tif ( asprintf(&cfg.etc_private_keep, \"%s,%s\", cfg.etc_private_keep, argv[i] + 14) < 0 )\n\t\t\t\t\t\terrExit(\"asprintf\");\n\t\t\t\t} else\n\t\t\t\t\tcfg.etc_private_keep = argv[i] + 14;\n\t\t\t\targ_private_etc = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"private-etc\");\n\t\t}\n\t\telse if (strncmp(argv[i], \"--private-opt=\", 14) == 0) {\n\t\t\tif (checkcfg(CFG_PRIVATE_OPT)) {\n\t\t\t\t// extract private opt list\n\t\t\t\tif (*(argv[i] + 14) == '\\0') {\n\t\t\t\t\tfprintf(stderr, \"Error: invalid private-opt option\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tif (cfg.opt_private_keep) {\n\t\t\t\t\tif ( asprintf(&cfg.opt_private_keep, \"%s,%s\", cfg.opt_private_keep, argv[i] + 14) < 0 )\n\t\t\t\t\t\terrExit(\"asprintf\");\n\t\t\t\t} else\n\t\t\t\t\tcfg.opt_private_keep = argv[i] + 14;\n\t\t\t\targ_private_opt = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"private-opt\");\n\t\t}\n\t\telse if (strncmp(argv[i], \"--private-srv=\", 14) == 0) {\n\t\t\tif (checkcfg(CFG_PRIVATE_SRV)) {\n\t\t\t\t// extract private srv list\n\t\t\t\tif (*(argv[i] + 14) == '\\0') {\n\t\t\t\t\tfprintf(stderr, \"Error: invalid private-srv option\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tif (cfg.srv_private_keep) {\n\t\t\t\t\tif ( asprintf(&cfg.srv_private_keep, \"%s,%s\", cfg.srv_private_keep, argv[i] + 14) < 0 )\n\t\t\t\t\t\terrExit(\"asprintf\");\n\t\t\t\t} else\n\t\t\t\t\tcfg.srv_private_keep = argv[i] + 14;\n\t\t\t\targ_private_srv = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"private-srv\");\n\t\t}\n\t\telse if (strncmp(argv[i], \"--private-bin=\", 14) == 0) {\n\t\t\tif (checkcfg(CFG_PRIVATE_BIN)) {\n\t\t\t\t// extract private bin list\n\t\t\t\tif (*(argv[i] + 14) == '\\0') {\n\t\t\t\t\tfprintf(stderr, \"Error: invalid private-bin option\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tif (cfg.bin_private_keep) {\n\t\t\t\t\tif ( asprintf(&cfg.bin_private_keep, \"%s,%s\", cfg.bin_private_keep, argv[i] + 14) < 0 )\n\t\t\t\t\t\terrExit(\"asprintf\");\n\t\t\t\t} else\n\t\t\t\t\tcfg.bin_private_keep = argv[i] + 14;\n\t\t\t\targ_private_bin = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"private-bin\");\n\t\t}\n\t\telse if (strncmp(argv[i], \"--private-lib\", 13) == 0) {\n\t\t\tif (checkcfg(CFG_PRIVATE_LIB)) {\n\t\t\t\t// extract private lib list (if any)\n\t\t\t\tif (argv[i][13] == '=') {\n\t\t\t\t\tif (cfg.lib_private_keep) {\n\t\t\t\t\t\tif (argv[i][14] != '\\0' && asprintf(&cfg.lib_private_keep, \"%s,%s\", cfg.lib_private_keep, argv[i] + 14) < 0)\n\t\t\t\t\t\t\terrExit(\"asprintf\");\n\t\t\t\t\t} else\n\t\t\t\t\t\tcfg.lib_private_keep = argv[i] + 14;\n\t\t\t\t}\n\t\t\t\targ_private_lib = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"private-lib\");\n\t\t}\n\t\telse if (strcmp(argv[i], \"--private-tmp\") == 0) {\n\t\t\targ_private_tmp = 1;\n\t\t}\n#ifdef HAVE_USERTMPFS\n\t\telse if (strcmp(argv[i], \"--private-cache\") == 0) {\n\t\t\tif (checkcfg(CFG_PRIVATE_CACHE))\n\t\t\t\targ_private_cache = 1;\n\t\t\telse\n\t\t\t\texit_err_feature(\"private-cache\");\n\t\t}\n#endif\n\t\telse if (strcmp(argv[i], \"--private-cwd\") == 0) {\n\t\t\tcfg.cwd = NULL;\n\t\t\targ_private_cwd = 1;\n\t\t}\n\t\telse if (strncmp(argv[i], \"--private-cwd=\", 14) == 0) {\n\t\t\tif (*(argv[i] + 14) == '\\0') {\n\t\t\t\tfprintf(stderr, \"Error: invalid private-cwd option\\n\");\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\tfs_check_private_cwd(argv[i] + 14);\n\t\t\targ_private_cwd = 1;\n\t\t}\n\n\t\t//*************************************\n\t\t// hostname, etc\n\t\t//*************************************\n\t\telse if (strncmp(argv[i], \"--name=\", 7) == 0) {\n\t\t\tcfg.name = argv[i] + 7;\n\t\t\tif (strlen(cfg.name) == 0) {\n\t\t\t\tfprintf(stderr, \"Error: please provide a name for sandbox\\n\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\t\telse if (strncmp(argv[i], \"--hostname=\", 11) == 0) {\n\t\t\tcfg.hostname = argv[i] + 11;\n\t\t\tif (strlen(cfg.hostname) == 0) {\n\t\t\t\tfprintf(stderr, \"Error: please provide a hostname for sandbox\\n\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\t\telse if (strcmp(argv[i], \"--nogroups\") == 0)\n\t\t\targ_nogroups = 1;\n#ifdef HAVE_USERNS\n\t\telse if (strcmp(argv[i], \"--noroot\") == 0) {\n\t\t\tif (checkcfg(CFG_USERNS))\n\t\t\t\tcheck_user_namespace();\n\t\t\telse\n\t\t\t\texit_err_feature(\"noroot\");\n\t\t}\n#endif\n\t\telse if (strcmp(argv[i], \"--nonewprivs\") == 0)\n\t\t\targ_nonewprivs = 1;\n\t\telse if (strncmp(argv[i], \"--env=\", 6) == 0)\n\t\t\tenv_store(argv[i] + 6, SETENV);\n\t\telse if (strncmp(argv[i], \"--rmenv=\", 8) == 0)\n\t\t\tenv_store(argv[i] + 8, RMENV);\n\t\telse if (strcmp(argv[i], \"--nosound\") == 0)\n\t\t\targ_nosound = 1;\n\t\telse if (strcmp(argv[i], \"--noautopulse\") == 0)\n\t\t\targ_keep_config_pulse = 1;\n\t\telse if (strcmp(argv[i], \"--novideo\") == 0)\n\t\t\targ_novideo = 1;\n\t\telse if (strcmp(argv[i], \"--no3d\") == 0)\n\t\t\targ_no3d = 1;\n\t\telse if (strcmp(argv[i], \"--noprinters\") == 0) {\n\t\t\targ_noprinters = 1;\n\t\t\tprofile_add(\"blacklist /dev/lp*\");\n\t\t\tprofile_add(\"blacklist /run/cups/cups.sock\");\n\t\t}\n\t\telse if (strcmp(argv[i], \"--notv\") == 0)\n\t\t\targ_notv = 1;\n\t\telse if (strcmp(argv[i], \"--nodvd\") == 0)\n\t\t\targ_nodvd = 1;\n\t\telse if (strcmp(argv[i], \"--nou2f\") == 0)\n\t\t\targ_nou2f = 1;\n\t\telse if (strcmp(argv[i], \"--noinput\") == 0)\n\t\t\targ_noinput = 1;\n\t\telse if (strcmp(argv[i], \"--nodbus\") == 0) {\n\t\t\targ_dbus_user = DBUS_POLICY_BLOCK;\n\t\t\targ_dbus_system = DBUS_POLICY_BLOCK;\n\t\t}\n\n\t\t//*************************************\n\t\t// D-BUS proxy\n\t\t//*************************************\n#ifdef HAVE_DBUSPROXY\n\t\telse if (strncmp(\"--dbus-user=\", argv[i], 12) == 0) {\n\t\t\tif (strcmp(\"filter\", argv[i] + 12) == 0) {\n\t\t\t\tif (arg_dbus_user == DBUS_POLICY_BLOCK) {\n\t\t\t\t\tfprintf(stderr, \"Warning: Cannot relax --dbus-user policy, it is already set to block\\n\");\n\t\t\t\t} else {\n\t\t\t\t\targ_dbus_user = DBUS_POLICY_FILTER;\n\t\t\t\t}\n\t\t\t} else if (strcmp(\"none\", argv[i] + 12) == 0) {\n\t\t\t\tif (arg_dbus_log_user) {\n\t\t\t\t\tfprintf(stderr, \"Error: --dbus-user.log requires --dbus-user=filter\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\targ_dbus_user = DBUS_POLICY_BLOCK;\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"Unknown dbus-user policy: %s\\n\", argv[i] + 12);\n\t\t\t\texit(1);\n\t\t\t}\n\t\t}\n\t\telse if (strncmp(argv[i], \"--dbus-user.see=\", 16) == 0) {\n\t\t\tchar *line;\n\t\t\tif (asprintf(&line, \"dbus-user.see %s\", argv[i] + 16) == -1)\n\t\t\t\terrExit(\"asprintf\");\n\n\t\t\tprofile_check_line(line, 0, NULL); // will exit if something wrong\n\t\t\tprofile_add(line);\n\t\t}\n\t\telse if (strncmp(argv[i], \"--dbus-user.talk=\", 17) == 0) {\n\t\t\tchar *line;\n\t\t\tif (asprintf(&line, \"dbus-user.talk %s\", argv[i] + 17) == -1)\n\t\t\t\terrExit(\"asprintf\");\n\n\t\t\tprofile_check_line(line, 0, NULL); // will exit if something wrong\n\t\t\tprofile_add(line);\n\t\t}\n\t\telse if (strncmp(argv[i], \"--dbus-user.own=\", 16) == 0) {\n\t\t\tchar *line;\n\t\t\tif (asprintf(&line, \"dbus-user.own %s\", argv[i] + 16) == -1)\n\t\t\t\terrExit(\"asprintf\");\n\n\t\t\tprofile_check_line(line, 0, NULL); // will exit if something wrong\n\t\t\tprofile_add(line);\n\t\t}\n\t\telse if (strncmp(argv[i], \"--dbus-user.call=\", 17) == 0) {\n\t\t\tchar *line;\n\t\t\tif (asprintf(&line, \"dbus-user.call %s\", argv[i] + 17) == -1)\n\t\t\t\terrExit(\"asprintf\");\n\n\t\t\tprofile_check_line(line, 0, NULL); // will exit if something wrong\n\t\t\tprofile_add(line);\n\t\t}\n\t\telse if (strncmp(argv[i], \"--dbus-user.broadcast=\", 22) == 0) {\n\t\t\tchar *line;\n\t\t\tif (asprintf(&line, \"dbus-user.broadcast %s\", argv[i] + 22) == -1)\n\t\t\t\terrExit(\"asprintf\");\n\n\t\t\tprofile_check_line(line, 0, NULL); // will exit if something wrong\n\t\t\tprofile_add(line);\n\t\t}\n\t\telse if (strncmp(\"--dbus-system=\", argv[i], 14) == 0) {\n\t\t\tif (strcmp(\"filter\", argv[i] + 14) == 0) {\n\t\t\t\tif (arg_dbus_system == DBUS_POLICY_BLOCK) {\n\t\t\t\t\tfprintf(stderr, \"Warning: Cannot relax --dbus-system policy, it is already set to block\\n\");\n\t\t\t\t} else {\n\t\t\t\t\targ_dbus_system = DBUS_POLICY_FILTER;\n\t\t\t\t}\n\t\t\t} else if (strcmp(\"none\", argv[i] + 14) == 0) {\n\t\t\t\tif (arg_dbus_log_system) {\n\t\t\t\t\tfprintf(stderr, \"Error: --dbus-system.log requires --dbus-system=filter\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\targ_dbus_system = DBUS_POLICY_BLOCK;\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"Unknown dbus-system policy: %s\\n\", argv[i] + 14);\n\t\t\t\texit(1);\n\t\t\t}\n\t\t}\n\t\telse if (strncmp(argv[i], \"--dbus-system.see=\", 18) == 0) {\n\t\t\tchar *line;\n\t\t\tif (asprintf(&line, \"dbus-system.see %s\", argv[i] + 18) == -1)\n\t\t\t\terrExit(\"asprintf\");\n\n\t\t\tprofile_check_line(line, 0, NULL); // will exit if something wrong\n\t\t\tprofile_add(line);\n\t\t}\n\t\telse if (strncmp(argv[i], \"--dbus-system.talk=\", 19) == 0) {\n\t\t\tchar *line;\n\t\t\tif (asprintf(&line, \"dbus-system.talk %s\", argv[i] + 19) == -1)\n\t\t\t\terrExit(\"asprintf\");\n\n\t\t\tprofile_check_line(line, 0, NULL); // will exit if something wrong\n\t\t\tprofile_add(line);\n\t\t}\n\t\telse if (strncmp(argv[i], \"--dbus-system.own=\", 18) == 0) {\n\t\t\tchar *line;\n\t\t\tif (asprintf(&line, \"dbus-system.own %s\", argv[i] + 18) == -1)\n\t\t\t\terrExit(\"asprintf\");\n\n\t\t\tprofile_check_line(line, 0, NULL); // will exit if something wrong\n\t\t\tprofile_add(line);\n\t\t}\n\t\telse if (strncmp(argv[i], \"--dbus-system.call=\", 19) == 0) {\n\t\t\tchar *line;\n\t\t\tif (asprintf(&line, \"dbus-system.call %s\", argv[i] + 19) == -1)\n\t\t\t\terrExit(\"asprintf\");\n\n\t\t\tprofile_check_line(line, 0, NULL); // will exit if something wrong\n\t\t\tprofile_add(line);\n\t\t}\n\t\telse if (strncmp(argv[i], \"--dbus-system.broadcast=\", 24) == 0) {\n\t\t\tchar *line;\n\t\t\tif (asprintf(&line, \"dbus-system.broadcast %s\", argv[i] + 24) == -1)\n\t\t\t\terrExit(\"asprintf\");\n\n\t\t\tprofile_check_line(line, 0, NULL); // will exit if something wrong\n\t\t\tprofile_add(line);\n\t\t}\n\t\telse if (strncmp(argv[i], \"--dbus-log=\", 11) == 0) {\n\t\t\tif (arg_dbus_log_file != NULL) {\n\t\t\t\tfprintf(stderr, \"Error: --dbus-log option already specified\\n\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\targ_dbus_log_file = argv[i] + 11;\n\t\t}\n\t\telse if (strcmp(argv[i], \"--dbus-user.log\") == 0) {\n\t\t\tif (arg_dbus_user != DBUS_POLICY_FILTER) {\n\t\t\t\tfprintf(stderr, \"Error: --dbus-user.log requires --dbus-user=filter\\n\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\targ_dbus_log_user = 1;\n\t\t}\n\t\telse if (strcmp(argv[i], \"--dbus-system.log\") == 0) {\n\t\t\tif (arg_dbus_system != DBUS_POLICY_FILTER) {\n\t\t\t\tfprintf(stderr, \"Error: --dbus-system.log requires --dbus-system=filter\\n\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\targ_dbus_log_system = 1;\n\t\t}\n#endif\n\n\t\t//*************************************\n\t\t// network\n\t\t//*************************************\n\t\telse if (strcmp(argv[i], \"--net=none\") == 0) {\n\t\t\targ_nonetwork = 1;\n\t\t\tcfg.bridge0.configured = 0;\n\t\t\tcfg.bridge1.configured = 0;\n\t\t\tcfg.bridge2.configured = 0;\n\t\t\tcfg.bridge3.configured = 0;\n\t\t\tcfg.interface0.configured = 0;\n\t\t\tcfg.interface1.configured = 0;\n\t\t\tcfg.interface2.configured = 0;\n\t\t\tcfg.interface3.configured = 0;\n\t\t\tcontinue;\n\t\t}\n#ifdef HAVE_NETWORK\n\t\telse if (strcmp(argv[i], \"--netlock\") == 0) {\n\t\t\tif (checkcfg(CFG_NETWORK))\n\t\t\t\targ_netlock = 1;\n\t\t\telse\n\t\t\t\texit_err_feature(\"networking\");\n\t\t}\n\t\telse if (strncmp(argv[i], \"--netlock=\", 10) == 0) {\n\t\t\tif (checkcfg(CFG_NETWORK)) {\n\t\t\t\tpid_t pid = require_pid(argv[i] + 10);\n\t\t\t\tnetfilter_netlock(pid);\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"networking\");\n\t\t\texit(0);\n\t\t}\n\t\telse if (strncmp(argv[i], \"--interface=\", 12) == 0) {\n\t\t\tif (checkcfg(CFG_NETWORK)) {\n\t\t\t\t// checks\n\t\t\t\tif (arg_nonetwork) {\n\t\t\t\t\tfprintf(stderr, \"Error: --network=none and --interface are incompatible\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tif (strcmp(argv[i] + 12, \"lo\") == 0) {\n\t\t\t\t\tfprintf(stderr, \"Error: cannot use lo device in --interface command\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tint ifindex = if_nametoindex(argv[i] + 12);\n\t\t\t\tif (ifindex <= 0) {\n\t\t\t\t\tfprintf(stderr, \"Error: cannot find interface %s\\n\", argv[i] + 12);\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\n\t\t\t\tInterface *intf;\n\t\t\t\tif (cfg.interface0.configured == 0)\n\t\t\t\t\tintf = &cfg.interface0;\n\t\t\t\telse if (cfg.interface1.configured == 0)\n\t\t\t\t\tintf = &cfg.interface1;\n\t\t\t\telse if (cfg.interface2.configured == 0)\n\t\t\t\t\tintf = &cfg.interface2;\n\t\t\t\telse if (cfg.interface3.configured == 0)\n\t\t\t\t\tintf = &cfg.interface3;\n\t\t\t\telse {\n\t\t\t\t\tfprintf(stderr, \"Error: maximum 4 interfaces are allowed\\n\");\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\n\t\t\t\tintf->dev = strdup(argv[i] + 12);\n\t\t\t\tif (!intf->dev)\n\t\t\t\t\terrExit(\"strdup\");\n\n\t\t\t\tif (net_get_if_addr(intf->dev, &intf->ip, &intf->mask, intf->mac, &intf->mtu)) {\n\t\t\t\t\tfwarning(\"interface %s is not configured\\n\", intf->dev);\n\t\t\t\t}\n\t\t\t\tintf->configured = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"networking\");\n\t\t}\n\n\t\telse if (strncmp(argv[i], \"--net=\", 6) == 0) {\n\t\t\tif (checkcfg(CFG_NETWORK)) {\n\t\t\t\tif (strcmp(argv[i] + 6, \"none\") == 0) {\n\t\t\t\t\targ_nonetwork = 1;\n\t\t\t\t\tcfg.bridge0.configured = 0;\n\t\t\t\t\tcfg.bridge1.configured = 0;\n\t\t\t\t\tcfg.bridge2.configured = 0;\n\t\t\t\t\tcfg.bridge3.configured = 0;\n\t\t\t\t\tcfg.interface0.configured = 0;\n\t\t\t\t\tcfg.interface1.configured = 0;\n\t\t\t\t\tcfg.interface2.configured = 0;\n\t\t\t\t\tcfg.interface3.configured = 0;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (strcmp(argv[i] + 6, \"lo\") == 0) {\n\t\t\t\t\tfprintf(stderr, \"Error: cannot attach to lo device\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\n\t\t\t\tBridge *br;\n\t\t\t\tif (cfg.bridge0.configured == 0)\n\t\t\t\t\tbr = &cfg.bridge0;\n\t\t\t\telse if (cfg.bridge1.configured == 0)\n\t\t\t\t\tbr = &cfg.bridge1;\n\t\t\t\telse if (cfg.bridge2.configured == 0)\n\t\t\t\t\tbr = &cfg.bridge2;\n\t\t\t\telse if (cfg.bridge3.configured == 0)\n\t\t\t\t\tbr = &cfg.bridge3;\n\t\t\t\telse {\n\t\t\t\t\tfprintf(stderr, \"Error: maximum 4 network devices are allowed\\n\");\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t\tbr->dev = argv[i] + 6;\n\t\t\t\tbr->configured = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"networking\");\n\t\t}\n\n\t\telse if (strncmp(argv[i], \"--veth-name=\", 12) == 0) {\n\t\t\tif (checkcfg(CFG_NETWORK)) {\n\t\t\t\tBridge *br = last_bridge_configured();\n\t\t\t\tif (br == NULL) {\n\t\t\t\t\tfprintf(stderr, \"Error: no network device configured\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tbr->veth_name = strdup(argv[i] + 12);\n\t\t\t\tif (br->veth_name == NULL)\n\t\t\t\t\terrExit(\"strdup\");\n\t\t\t\tif (*br->veth_name == '\\0') {\n\t\t\t\t\tfprintf(stderr, \"Error: no veth-name configured\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"networking\");\n\t\t}\n\n\t\telse if (strcmp(argv[i], \"--scan\") == 0) {\n\t\t\tif (checkcfg(CFG_NETWORK)) {\n\t\t\t\targ_scan = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"networking\");\n\t\t}\n\t\telse if (strncmp(argv[i], \"--iprange=\", 10) == 0) {\n\t\t\tif (checkcfg(CFG_NETWORK)) {\n\t\t\t\tBridge *br = last_bridge_configured();\n\t\t\t\tif (br == NULL) {\n\t\t\t\t\tfprintf(stderr, \"Error: no network device configured\\n\");\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t\tif (br->iprange_start || br->iprange_end) {\n\t\t\t\t\tfprintf(stderr, \"Error: cannot configure the IP range twice for the same interface\\n\");\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\n\t\t\t\t// parse option arguments\n\t\t\t\tchar *firstip = argv[i] + 10;\n\t\t\t\tchar *secondip = firstip;\n\t\t\t\twhile (*secondip != '\\0') {\n\t\t\t\t\tif (*secondip == ',')\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tsecondip++;\n\t\t\t\t}\n\t\t\t\tif (*secondip == '\\0') {\n\t\t\t\t\tfprintf(stderr, \"Error: invalid IP range\\n\");\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t\t*secondip = '\\0';\n\t\t\t\tsecondip++;\n\n\t\t\t\t// check addresses\n\t\t\t\tif (atoip(firstip, &br->iprange_start) || atoip(secondip, &br->iprange_end) ||\n\t\t\t\t br->iprange_start >= br->iprange_end) {\n\t\t\t\t\tfprintf(stderr, \"Error: invalid IP range\\n\");\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"networking\");\n\t\t}\n\n\t\telse if (strncmp(argv[i], \"--mac=\", 6) == 0) {\n\t\t\tif (checkcfg(CFG_NETWORK)) {\n\t\t\t\tBridge *br = last_bridge_configured();\n\t\t\t\tif (br == NULL) {\n\t\t\t\t\tfprintf(stderr, \"Error: no network device configured\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tif (mac_not_zero(br->macsandbox)) {\n\t\t\t\t\tfprintf(stderr, \"Error: cannot configure the MAC address twice for the same interface\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\n\t\t\t\t// read the address\n\t\t\t\tif (atomac(argv[i] + 6, br->macsandbox)) {\n\t\t\t\t\tfprintf(stderr, \"Error: invalid MAC address\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\n\t\t\t\t// check multicast address\n\t\t\t\tif (br->macsandbox[0] & 1) {\n\t\t\t\t\tfprintf(stderr, \"Error: invalid MAC address (multicast)\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"networking\");\n\t\t}\n\n\t\telse if (strncmp(argv[i], \"--mtu=\", 6) == 0) {\n\t\t\tif (checkcfg(CFG_NETWORK)) {\n\t\t\t\tBridge *br = last_bridge_configured();\n\t\t\t\tif (br == NULL) {\n\t\t\t\t\tfprintf(stderr, \"Error: no network device configured\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\n\t\t\t\tif (sscanf(argv[i] + 6, \"%d\", &br->mtu) != 1 || br->mtu < 576 || br->mtu > 9198) {\n\t\t\t\t\tfprintf(stderr, \"Error: invalid mtu value\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"networking\");\n\t\t}\n\n\t\telse if (strncmp(argv[i], \"--ip=\", 5) == 0) {\n\t\t\tif (checkcfg(CFG_NETWORK)) {\n\t\t\t\tBridge *br = last_bridge_configured();\n\t\t\t\tif (br == NULL) {\n\t\t\t\t\tfprintf(stderr, \"Error: no network device configured\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tif (br->arg_ip_none || br->ipsandbox) {\n\t\t\t\t\tfprintf(stderr, \"Error: cannot configure the IP address twice for the same interface\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\n\t\t\t\t// configure this IP address for the last bridge defined\n\t\t\t\tif (strcmp(argv[i] + 5, \"none\") == 0)\n\t\t\t\t\tbr->arg_ip_none = 1;\n\t\t\t\telse if (strcmp(argv[i] + 5, \"dhcp\") == 0) {\n\t\t\t\t\tbr->arg_ip_none = 1;\n\t\t\t\t\tbr->arg_ip_dhcp = 1;\n\t\t\t\t} else {\n\t\t\t\t\tif (atoip(argv[i] + 5, &br->ipsandbox)) {\n\t\t\t\t\t\tfprintf(stderr, \"Error: invalid IP address\\n\");\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"networking\");\n\t\t}\n\n\t\telse if (strncmp(argv[i], \"--netmask=\", 10) == 0) {\n\t\t\tif (checkcfg(CFG_NETWORK)) {\n\t\t\t\tBridge *br = last_bridge_configured();\n\t\t\t\tif (br == NULL) {\n\t\t\t\t\tfprintf(stderr, \"Error: no network device configured\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tif (br->arg_ip_none || br->mask) {\n\t\t\t\t\tfprintf(stderr, \"Error: cannot configure the network mask twice for the same interface\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\n\t\t\t\t// configure this network mask for the last bridge defined\n\t\t\t\tif (atoip(argv[i] + 10, &br->mask)) {\n\t\t\t\t\tfprintf(stderr, \"Error: invalid network mask\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"networking\");\n\t\t}\n\n\t\telse if (strncmp(argv[i], \"--ip6=\", 6) == 0) {\n\t\t\tif (checkcfg(CFG_NETWORK)) {\n\t\t\t\tBridge *br = last_bridge_configured();\n\t\t\t\tif (br == NULL) {\n\t\t\t\t\tfprintf(stderr, \"Error: no network device configured\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tif (br->arg_ip6_dhcp || br->ip6sandbox) {\n\t\t\t\t\tfprintf(stderr, \"Error: cannot configure the IP address twice for the same interface\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\n\t\t\t\t// configure this IP address for the last bridge defined\n\t\t\t\tif (strcmp(argv[i] + 6, \"dhcp\") == 0)\n\t\t\t\t\tbr->arg_ip6_dhcp = 1;\n\t\t\t\telse {\n\t\t\t\t\tif (check_ip46_address(argv[i] + 6) == 0) {\n\t\t\t\t\t\tfprintf(stderr, \"Error: invalid IPv6 address\\n\");\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\n\t\t\t\t\tbr->ip6sandbox = strdup(argv[i] + 6);\n\t\t\t\t\tif (br->ip6sandbox == NULL)\n\t\t\t\t\t\terrExit(\"strdup\");\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"networking\");\n\t\t}\n\n\n\t\telse if (strncmp(argv[i], \"--defaultgw=\", 12) == 0) {\n\t\t\tif (checkcfg(CFG_NETWORK)) {\n\t\t\t\tif (atoip(argv[i] + 12, &cfg.defaultgw)) {\n\t\t\t\t\tfprintf(stderr, \"Error: invalid IP address\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"networking\");\n\t\t}\n#endif\n\t\telse if (strncmp(argv[i], \"--dns=\", 6) == 0) {\n\t\t\tif (check_ip46_address(argv[i] + 6) == 0) {\n\t\t\t\tfprintf(stderr, \"Error: invalid DNS server IPv4 or IPv6 address\\n\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tchar *dns = strdup(argv[i] + 6);\n\t\t\tif (!dns)\n\t\t\t\terrExit(\"strdup\");\n\n\t\t\tif (cfg.dns1 == NULL)\n\t\t\t\tcfg.dns1 = dns;\n\t\t\telse if (cfg.dns2 == NULL)\n\t\t\t\tcfg.dns2 = dns;\n\t\t\telse if (cfg.dns3 == NULL)\n\t\t\t\tcfg.dns3 = dns;\n\t\t\telse if (cfg.dns4 == NULL)\n\t\t\t\tcfg.dns4 = dns;\n\t\t\telse {\n\t\t\t\tfwarning(\"up to 4 DNS servers can be specified, %s ignored\\n\", dns);\n\t\t\t\tfree(dns);\n\t\t\t}\n\t\t}\n\n\t\telse if (strncmp(argv[i], \"--hosts-file=\", 13) == 0)\n\t\t\tcfg.hosts_file = fs_check_hosts_file(argv[i] + 13);\n\n#ifdef HAVE_NETWORK\n\t\telse if (strcmp(argv[i], \"--netfilter\") == 0) {\n\t\t\tif (checkcfg(CFG_NETWORK)) {\n\t\t\t\targ_netfilter = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"networking\");\n\t\t}\n\n\t\telse if (strncmp(argv[i], \"--netfilter=\", 12) == 0) {\n\t\t\tif (checkcfg(CFG_NETWORK)) {\n\t\t\t\targ_netfilter = 1;\n\t\t\t\targ_netfilter_file = argv[i] + 12;\n\n\t\t\t\t// expand tilde\n\t\t\t\tif (*arg_netfilter_file == '~') {\n\t\t\t\t\tchar *tmp;\n\t\t\t\t\tif (asprintf(&tmp, \"%s%s\", cfg.homedir, arg_netfilter_file + 1) == -1)\n\t\t\t\t\t\terrExit(\"asprintf\");\n\t\t\t\t\targ_netfilter_file = tmp;\n\t\t\t\t}\n\n\t\t\t\tcheck_netfilter_file(arg_netfilter_file);\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"networking\");\n\t\t}\n\n\t\telse if (strncmp(argv[i], \"--netfilter6=\", 13) == 0) {\n\t\t\tif (checkcfg(CFG_NETWORK)) {\n\t\t\t\targ_netfilter6 = 1;\n\t\t\t\targ_netfilter6_file = argv[i] + 13;\n\n\t\t\t\t// expand tilde\n\t\t\t\tif (*arg_netfilter6_file == '~') {\n\t\t\t\t\tchar *tmp;\n\t\t\t\t\tif (asprintf(&tmp, \"%s%s\", cfg.homedir, arg_netfilter6_file + 1) == -1)\n\t\t\t\t\t\terrExit(\"asprintf\");\n\t\t\t\t\targ_netfilter6_file = tmp;\n\t\t\t\t}\n\n\t\t\t\tcheck_netfilter_file(arg_netfilter6_file);\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"networking\");\n\t\t}\n\n\t\telse if (strncmp(argv[i], \"--netns=\", 8) == 0) {\n\t\t\tif (checkcfg(CFG_NETWORK)) {\n\t\t\t\targ_netns = argv[i] + 8;\n\t\t\t\tcheck_netns(arg_netns);\n\t\t\t}\n\t\t\telse\n\t\t\t\texit_err_feature(\"networking\");\n\t\t}\n#endif\n\t\t//*************************************\n\t\t// command\n\t\t//*************************************\n\t\telse if (strncmp(argv[i], \"--timeout=\", 10) == 0)\n\t\t\tcfg.timeout = extract_timeout(argv[i] + 10);\n\t\telse if (strcmp(argv[i], \"--appimage\") == 0) {\n\t\t\t// already handled\n\t\t}\n\t\telse if (strncmp(argv[i], \"--oom=\", 6) == 0) {\n\t\t\t// already handled\n\t\t}\n\t\telse if (strcmp(argv[i], \"--shell=none\") == 0) {\n\t\t\targ_shell_none = 1;\n\t\t\tif (cfg.shell) {\n\t\t\t\tfprintf(stderr, \"Error: a shell was already specified\\n\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\t\telse if (strncmp(argv[i], \"--shell=\", 8) == 0) {\n\t\t\tif (arg_shell_none) {\n\t\t\t\tfprintf(stderr, \"Error: --shell=none was already specified.\\n\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tinvalid_filename(argv[i] + 8, 0); // no globbing\n\n\t\t\tif (cfg.shell) {\n\t\t\t\tfprintf(stderr, \"Error: only one user shell can be specified\\n\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tcfg.shell = argv[i] + 8;\n\n\t\t\tif (is_dir(cfg.shell) || strstr(cfg.shell, \"..\")) {\n\t\t\t\tfprintf(stderr, \"Error: invalid shell\\n\");\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\t// access call checks as real UID/GID, not as effective UID/GID\n\t\t\tif(cfg.chrootdir) {\n\t\t\t\tchar *shellpath;\n\t\t\t\tif (asprintf(&shellpath, \"%s%s\", cfg.chrootdir, cfg.shell) == -1)\n\t\t\t\t\terrExit(\"asprintf\");\n\t\t\t\tif (access(shellpath, X_OK)) {\n\t\t\t\t\tfprintf(stderr, \"Error: cannot access shell file in chroot\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tfree(shellpath);\n\t\t\t} else if (access(cfg.shell, X_OK)) {\n\t\t\t\tfprintf(stderr, \"Error: cannot access shell file\\n\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t}\n\t\telse if (strcmp(argv[i], \"-c\") == 0) {\n\t\t\targ_command = 1;\n\t\t\tif (i == (argc - 1)) {\n\t\t\t\tfprintf(stderr, \"Error: option -c requires an argument\\n\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\n\t\t// unlike all other x11 features, this is available always\n\t\telse if (strcmp(argv[i], \"--x11=none\") == 0) {\n\t\t\targ_x11_block = 1;\n\t\t}\n#ifdef HAVE_X11\n\t\telse if (strcmp(argv[i], \"--x11=xorg\") == 0) {\n\t\t\tif (checkcfg(CFG_X11))\n\t\t\t\targ_x11_xorg = 1;\n\t\t\telse\n\t\t\t\texit_err_feature(\"x11\");\n\t\t}\n#endif\n\t\telse if (strncmp(argv[i], \"--join-or-start=\", 16) == 0) {\n\t\t\t// NOTE: this is second part of option handler,\n\t\t\t//\t\t atempt to find and join sandbox is done in other one\n\n\t\t\t// set sandbox name and start normally\n\t\t\tcfg.name = argv[i] + 16;\n\t\t\tif (strlen(cfg.name) == 0) {\n\t\t\t\tfprintf(stderr, \"Error: please provide a name for sandbox\\n\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\t\telse if (strcmp(argv[i], \"--deterministic-exit-code\") == 0) {\n\t\t\targ_deterministic_exit_code = 1;\n\t\t}\n\t\telse if (strcmp(argv[i], \"--deterministic-shutdown\") == 0) {\n\t\t\targ_deterministic_shutdown = 1;\n\t\t}\n\t\telse if (strcmp(argv[i], \"--tab\") == 0)\n\t\t\targ_tab = 1;\n\t\telse {\n\t\t\t// double dash - positional params to follow\n\t\t\tif (strcmp(argv[i], \"--\") == 0) {\n\t\t\t\targ_doubledash = 1;\n\t\t\t\ti++;\n\t\t\t\tif (i >= argc) {\n\t\t\t\t\tfprintf(stderr, \"Error: program name not found\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// is this an invalid option?\n\t\t\telse if (*argv[i] == '-') {\n\t\t\t\tfprintf(stderr, \"Error: invalid %s command line option\\n\", argv[i]);\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\t// we have a program name coming\n\t\t\tif (arg_appimage) {\n\t\t\t\tcfg.command_name = strdup(argv[i]);\n\t\t\t\tif (!cfg.command_name)\n\t\t\t\t\terrExit(\"strdup\");\n\n\t\t\t\t// disable shell=* for appimages\n\t\t\t\targ_shell_none = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t\textract_command_name(i, argv);\n\t\t\tprog_index = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tEUID_ASSERT();\n\n\t// exit chroot, overlay and appimage sandboxes when caps are explicitly specified on command line\n\tif (getuid() != 0 && arg_caps_cmdline) {\n\t\tchar *opt = NULL;\n\t\tif (arg_appimage)\n\t\t\topt = \"appimage\";\n\t\telse if (arg_overlay)\n\t\t\topt = \"overlay\";\n\t\telse if (cfg.chrootdir)\n\t\t\topt = \"chroot\";\n\n\t\tif (opt) {\n\t\t\tfprintf(stderr, \"Error: all capabilities are dropped for %s by default.\\n\"\n\t\t\t\t\"Please remove --caps options from the command line.\\n\", opt);\n\t\t\texit(1);\n\t\t}\n\t}\n\n\t// prog_index could still be -1 if no program was specified\n\tif (prog_index == -1 && arg_shell_none) {\n\t\tfprintf(stderr, \"Error: shell=none configured, but no program specified\\n\");\n\t\texit(1);\n\t}\n\n\t// check trace configuration\n\tif (arg_trace && arg_tracelog) {\n\t\tfwarning(\"--trace and --tracelog are mutually exclusive; --tracelog disabled\\n\");\n\t}\n\n\t// check user namespace (--noroot) options\n\tif (arg_noroot) {\n\t\tif (arg_overlay) {\n\t\t\tfwarning(\"--overlay and --noroot are mutually exclusive, --noroot disabled...\\n\");\n\t\t\targ_noroot = 0;\n\t\t}\n\t\telse if (cfg.chrootdir) {\n\t\t\tfwarning(\"--chroot and --noroot are mutually exclusive, --noroot disabled...\\n\");\n\t\t\targ_noroot = 0;\n\t\t}\n\t}\n\n\t// check writable_etc and DNS/DHCP\n\tif (arg_writable_etc) {\n\t\tif (cfg.dns1 != NULL || any_dhcp()) {\n\t\t\t// we could end up overwriting the real /etc/resolv.conf, so we better exit now!\n\t\t\tfprintf(stderr, \"Error: --dns/--ip=dhcp and --writable-etc are mutually exclusive\\n\");\n\t\t\texit(1);\n\t\t}\n\t}\n\n\n\n\t// enable seccomp if only seccomp.block-secondary was specified\n\tif (arg_seccomp_block_secondary)\n\t\targ_seccomp = 1;\n\n\t// log command\n\tlogargs(argc, argv);\n\tif (fullargc) {\n\t\tchar *msg;\n\t\tif (asprintf(&msg, \"user %s entering restricted shell\", cfg.username) == -1)\n\t\t\terrExit(\"asprintf\");\n\t\tlogmsg(msg);\n\t\tfree(msg);\n\t}\n\n\t// guess shell if unspecified\n\tif (!arg_shell_none && !cfg.shell) {\n\t\tcfg.shell = guess_shell();\n\t\tif (!cfg.shell) {\n\t\t\tfprintf(stderr, \"Error: unable to guess your shell, please set explicitly by using --shell option.\\n\");\n\t\t\texit(1);\n\t\t}\n\t\tif (arg_debug)\n\t\t\tprintf(\"Autoselecting %s as shell\\n\", cfg.shell);\n\t}\n\n\t// build the sandbox command\n\tif (prog_index == -1 && cfg.shell) {\n\t\tassert(cfg.command_line == NULL); // runs cfg.shell\n\t\tif (arg_appimage) {\n\t\t\tfprintf(stderr, \"Error: no appimage archive specified\\n\");\n\t\t\texit(1);\n\t\t}\n\n\t\tcfg.window_title = cfg.shell;\n\t\tcfg.command_name = cfg.shell;\n\t}\n\telse if (arg_appimage) {\n\t\tif (arg_debug)\n\t\t\tprintf(\"Configuring appimage environment\\n\");\n\t\tappimage_set(cfg.command_name);\n\t\tbuild_appimage_cmdline(&cfg.command_line, &cfg.window_title, argc, argv, prog_index, true);\n\t}\n\telse {\n\t\t// Only add extra quotes if we were not launched by sshd.\n\t\tbuild_cmdline(&cfg.command_line, &cfg.window_title, argc, argv, prog_index, !parent_sshd);\n\t}\n/*\telse {\n\t\tfprintf(stderr, \"Error: command must be specified when --shell=none used.\\n\");\n\t\texit(1);\n\t}*/\n\n\tassert(cfg.command_name);\n\tif (arg_debug)\n\t\tprintf(\"Command name #%s#\\n\", cfg.command_name);\n\n\n\t// load the profile\n\tif (!arg_noprofile && !custom_profile) {\n\t\tif (arg_appimage) {\n\t\t\tcustom_profile = appimage_find_profile(cfg.command_name);\n\t\t\t// disable shell=* for appimages\n\t\t\targ_shell_none = 0;\n\t\t}\n\t\telse\n\t\t\tcustom_profile = profile_find_firejail(cfg.command_name, 1);\n\t}\n\n\t// use default.profile as the default\n\tif (!custom_profile && !arg_noprofile) {\n\t\tchar *profile_name = DEFAULT_USER_PROFILE;\n\t\tif (getuid() == 0)\n\t\t\tprofile_name = DEFAULT_ROOT_PROFILE;\n\t\tif (arg_debug)\n\t\t\tprintf(\"Attempting to find %s.profile...\\n\", profile_name);\n\n\t\tcustom_profile = profile_find_firejail(profile_name, 1);\n\n\t\tif (!custom_profile) {\n\t\t\tfprintf(stderr, \"Error: no %s installed\\n\", profile_name);\n\t\t\texit(1);\n\t\t}\n\n\t\tif (custom_profile)\n\t\t\tfmessage(\"\\n** Note: you can use --noprofile to disable %s.profile **\\n\\n\", profile_name);\n\t}\n\tEUID_ASSERT();\n\n\t// block X11 sockets\n\tif (arg_x11_block)\n\t\tx11_block();\n\n\t// check network configuration options - it will exit if anything went wrong\n\tnet_check_cfg();\n\n\t// customization of default seccomp filter\n\tif (config_seccomp_filter_add) {\n\t\tif (arg_seccomp && !cfg.seccomp_list_keep && !cfg.seccomp_list_drop)\n\t\t\tprofile_list_augment(&cfg.seccomp_list, config_seccomp_filter_add);\n\n\t\tif (arg_seccomp32 && !cfg.seccomp_list_keep32 && !cfg.seccomp_list_drop32)\n\t\t\tprofile_list_augment(&cfg.seccomp_list32, config_seccomp_filter_add);\n\t}\n\n\tif (arg_seccomp)\n\t\targ_seccomp_postexec = check_postexec(cfg.seccomp_list) || check_postexec(cfg.seccomp_list_drop);\n\n\tbool need_preload = arg_trace || arg_tracelog || arg_seccomp_postexec;\n\tif (need_preload && (cfg.seccomp_list32 || cfg.seccomp_list_drop32 || cfg.seccomp_list_keep32))\n\t\tfwarning(\"preload libraries (trace, tracelog, postexecseccomp due to seccomp.drop=execve etc.) are incompatible with 32 bit filters\\n\");\n\n\t// check and assign an IP address - for macvlan it will be done again in the sandbox!\n\tif (any_bridge_configured()) {\n\t\tEUID_ROOT();\n\t\tlockfd_network = open(RUN_NETWORK_LOCK_FILE, O_WRONLY | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR);\n\t\tif (lockfd_network != -1) {\n\t\t\tint rv = fchown(lockfd_network, 0, 0);\n\t\t\t(void) rv;\n\t\t\tflock(lockfd_network, LOCK_EX);\n\t\t}\n\n\t\tif (cfg.bridge0.configured && cfg.bridge0.arg_ip_none == 0)\n\t\t\tcheck_network(&cfg.bridge0);\n\t\tif (cfg.bridge1.configured && cfg.bridge1.arg_ip_none == 0)\n\t\t\tcheck_network(&cfg.bridge1);\n\t\tif (cfg.bridge2.configured && cfg.bridge2.arg_ip_none == 0)\n\t\t\tcheck_network(&cfg.bridge2);\n\t\tif (cfg.bridge3.configured && cfg.bridge3.arg_ip_none == 0)\n\t\t\tcheck_network(&cfg.bridge3);\n\n\t\t// save network mapping in shared memory\n\t\tnetwork_set_run_file(sandbox_pid);\n\t\tEUID_USER();\n\t}\n\tEUID_ASSERT();\n\n\tif (arg_noroot && arg_overlay) {\n\t\tfwarning(\"--overlay and --noroot are mutually exclusive, noroot disabled\\n\");\n\t\targ_noroot = 0;\n\t}\n\telse if (arg_noroot && cfg.chrootdir) {\n\t\tfwarning(\"--chroot and --noroot are mutually exclusive, noroot disabled\\n\");\n\t\targ_noroot = 0;\n\t}\n\n\n\t// set name and x11 run files\n\tEUID_ROOT();\n\tlockfd_directory = open(RUN_DIRECTORY_LOCK_FILE, O_WRONLY | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR);\n\tif (lockfd_directory != -1) {\n\t\tint rv = fchown(lockfd_directory, 0, 0);\n\t\t(void) rv;\n\t\tflock(lockfd_directory, LOCK_EX);\n\t}\n\tif (cfg.name)\n\t\tset_name_run_file(sandbox_pid);\n\tint display = x11_display();\n\tif (display > 0)\n\t\tset_x11_run_file(sandbox_pid, display);\n\tif (lockfd_directory != -1) {\n\t\tflock(lockfd_directory, LOCK_UN);\n\t\tclose(lockfd_directory);\n\t}\n\tEUID_USER();\n\n#ifdef HAVE_DBUSPROXY\n\tif (checkcfg(CFG_DBUS)) {\n\t\tdbus_check_profile();\n\t\tif (arg_dbus_user == DBUS_POLICY_FILTER ||\n\t\t\targ_dbus_system == DBUS_POLICY_FILTER) {\n\t\t\tEUID_ROOT();\n\t\t\tdbus_proxy_start();\n\t\t\tEUID_USER();\n\t\t}\n\t}\n#endif\n\n\t// create the parent-child communication pipe\n\tif (pipe2(parent_to_child_fds, O_CLOEXEC) < 0)\n\t\terrExit(\"pipe\");\n\tif (pipe2(child_to_parent_fds, O_CLOEXEC) < 0)\n\t\terrExit(\"pipe\");\n\n\t// clone environment\n\tint flags = CLONE_NEWNS | CLONE_NEWPID | CLONE_NEWUTS | SIGCHLD;\n\n\t// in root mode also enable CLONE_NEWIPC\n\t// in user mode CLONE_NEWIPC will break MIT Shared Memory Extension (MIT-SHM)\n\tif (getuid() == 0 || arg_ipc) {\n\t\tflags |= CLONE_NEWIPC;\n\t\tif (arg_debug)\n\t\t\tprintf(\"Enabling IPC namespace\\n\");\n\t}\n\n\tif (any_bridge_configured() || any_interface_configured() || arg_nonetwork) {\n\t\tflags |= CLONE_NEWNET;\n\t}\n\telse if (arg_debug)\n\t\tprintf(\"Using the local network stack\\n\");\n\n\tEUID_ASSERT();\n\tEUID_ROOT();\n#ifdef __ia64__\n\tchild = __clone2(sandbox,\n\t\tchild_stack,\n\t\tSTACK_SIZE,\n\t\tflags,\n\t\tNULL);\n#else\n\tchild = clone(sandbox,\n\t\tchild_stack + STACK_SIZE,\n\t\tflags,\n\t\tNULL);\n#endif\n\tif (child == -1)\n\t\terrExit(\"clone\");\n\tEUID_USER();\n\n\tif (!arg_command && !arg_quiet) {\n\t\tfmessage(\"Parent pid %u, child pid %u\\n\", sandbox_pid, child);\n\t\t// print the path of the new log directory\n\t\tif (getuid() == 0) // only for root\n\t\t\tprintf(\"The new log directory is /proc/%d/root/var/log\\n\", child);\n\t}\n\n\tif (!arg_nonetwork) {\n\t\tEUID_ROOT();\n\t\tpid_t net_child = fork();\n\t\tif (net_child < 0)\n\t\t\terrExit(\"fork\");\n\t\tif (net_child == 0) {\n\t\t\t// elevate privileges in order to get grsecurity working\n\t\t\tif (setreuid(0, 0))\n\t\t\t\terrExit(\"setreuid\");\n\t\t\tif (setregid(0, 0))\n\t\t\t\terrExit(\"setregid\");\n\t\t\tnetwork_main(child);\n\t\t\tif (arg_debug)\n\t\t\t\tprintf(\"Host network configured\\n\");\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\twaitpid(net_child, NULL, 0);\n\t\tEUID_USER();\n\t}\n\tEUID_ASSERT();\n\n\t// close each end of the unused pipes\n\tclose(parent_to_child_fds[0]);\n\tclose(child_to_parent_fds[1]);\n\n\t// notify child that base setup is complete\n\tnotify_other(parent_to_child_fds[1]);\n\n\t// wait for child to create new user namespace with CLONE_NEWUSER\n\twait_for_other(child_to_parent_fds[0]);\n\tclose(child_to_parent_fds[0]);\n\n\tif (arg_noroot) {\n\t\t// update the UID and GID maps in the new child user namespace\n\t\t// uid\n\t\tchar *map_path;\n\t\tif (asprintf(&map_path, \"/proc/%d/uid_map\", child) == -1)\n\t\t\terrExit(\"asprintf\");\n\n\t\tchar *map;\n\t\tuid_t uid = getuid();\n\t\tif (asprintf(&map, \"%d %d 1\", uid, uid) == -1)\n\t\t\terrExit(\"asprintf\");\n\t\tEUID_ROOT();\n\t\tupdate_map(map, map_path);\n\t\tEUID_USER();\n\t\tfree(map);\n\t\tfree(map_path);\n\n\t\t// gid file\n\t\tif (asprintf(&map_path, \"/proc/%d/gid_map\", child) == -1)\n\t\t\terrExit(\"asprintf\");\n\t\tchar gidmap[1024];\n\t\tchar *ptr = gidmap;\n\t\t*ptr = '\\0';\n\n\t\t// add user group\n\t\tgid_t gid = getgid();\n\t\tsprintf(ptr, \"%d %d 1\\n\", gid, gid);\n\t\tptr += strlen(ptr);\n\n\t\tgid_t g;\n\t\tif (!arg_nogroups || !check_can_drop_all_groups()) {\n\t\t\t// add audio group\n\t\t\tif (!arg_nosound) {\n\t\t\t\tg = get_group_id(\"audio\");\n\t\t\t\tif (g) {\n\t\t\t\t\tsprintf(ptr, \"%d %d 1\\n\", g, g);\n\t\t\t\t\tptr += strlen(ptr);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// add video group\n\t\t\tif (!arg_novideo) {\n\t\t\t\tg = get_group_id(\"video\");\n\t\t\t\tif (g) {\n\t\t\t\t\tsprintf(ptr, \"%d %d 1\\n\", g, g);\n\t\t\t\t\tptr += strlen(ptr);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// add render/vglusers group\n\t\t\tif (!arg_no3d) {\n\t\t\t\tg = get_group_id(\"render\");\n\t\t\t\tif (g) {\n\t\t\t\t\tsprintf(ptr, \"%d %d 1\\n\", g, g);\n\t\t\t\t\tptr += strlen(ptr);\n\t\t\t\t}\n\t\t\t\tg = get_group_id(\"vglusers\");\n\t\t\t\tif (g) {\n\t\t\t\t\tsprintf(ptr, \"%d %d 1\\n\", g, g);\n\t\t\t\t\tptr += strlen(ptr);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// add lp group\n\t\t\tif (!arg_noprinters) {\n\t\t\t\tg = get_group_id(\"lp\");\n\t\t\t\tif (g) {\n\t\t\t\t\tsprintf(ptr, \"%d %d 1\\n\", g, g);\n\t\t\t\t\tptr += strlen(ptr);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// add cdrom/optical groups\n\t\t\tif (!arg_nodvd) {\n\t\t\t\tg = get_group_id(\"cdrom\");\n\t\t\t\tif (g) {\n\t\t\t\t\tsprintf(ptr, \"%d %d 1\\n\", g, g);\n\t\t\t\t\tptr += strlen(ptr);\n\t\t\t\t}\n\t\t\t\tg = get_group_id(\"optical\");\n\t\t\t\tif (g) {\n\t\t\t\t\tsprintf(ptr, \"%d %d 1\\n\", g, g);\n\t\t\t\t\tptr += strlen(ptr);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// add input group\n\t\t\tif (!arg_noinput) {\n\t\t\t\tg = get_group_id(\"input\");\n\t\t\t\tif (g) {\n\t\t\t\t\tsprintf(ptr, \"%d %d 1\\n\", g, g);\n\t\t\t\t\tptr += strlen(ptr);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!arg_nogroups) {\n\t\t\t// add firejail group\n\t\t\tg = get_group_id(\"firejail\");\n\t\t\tif (g) {\n\t\t\t\tsprintf(ptr, \"%d %d 1\\n\", g, g);\n\t\t\t\tptr += strlen(ptr);\n\t\t\t}\n\n\t\t\t// add tty group\n\t\t\tg = get_group_id(\"tty\");\n\t\t\tif (g) {\n\t\t\t\tsprintf(ptr, \"%d %d 1\\n\", g, g);\n\t\t\t\tptr += strlen(ptr);\n\t\t\t}\n\n\t\t\t// add games group\n\t\t\tg = get_group_id(\"games\");\n\t\t\tif (g) {\n\t\t\t\tsprintf(ptr, \"%d %d 1\\n\", g, g);\n\t\t\t}\n\t\t}\n\n\t\tEUID_ROOT();\n\t\tupdate_map(gidmap, map_path);\n\t\tEUID_USER();\n\t\tfree(map_path);\n\t}\n\tEUID_ASSERT();\n\n\t// notify child that UID/GID mapping is complete\n\tnotify_other(parent_to_child_fds[1]);\n\tclose(parent_to_child_fds[1]);\n\n\tEUID_ROOT();\n\tif (lockfd_network != -1) {\n\t\tflock(lockfd_network, LOCK_UN);\n\t\tclose(lockfd_network);\n\t}\n\tEUID_USER();\n\n\t// lock netfilter firewall\n\tif (arg_netlock) {\n\t\tchar *cmd;\n\t\tif (asprintf(&cmd, \"firejail --netlock=%d&\", getpid()) == -1)\n\t\t\terrExit(\"asprintf\");\n\t\tint rv = system(cmd);\n\t\t(void) rv;\n\t\tfree(cmd);\n\t}\n\n\tint status = 0;\n\t//*****************************\n\t// following code is signal-safe\n\n\t// handle CTRL-C in parent\n\tinstall_handler();\n\n\t// wait for the child to finish\n\twaitpid(child, &status, 0);\n\n\t// restore default signal actions\n\tsignal(SIGTERM, SIG_DFL);\n\tsignal(SIGINT, SIG_DFL);\n\n\t// end of signal-safe code\n\t//*****************************\n\n\n\n\tif (WIFEXITED(status)){\n\t\tmyexit(WEXITSTATUS(status));\n\t} else if (WIFSIGNALED(status)) {\n\t\t// distinguish fatal signals by adding 128\n\t\tmyexit(128 + WTERMSIG(status));\n\t} else {\n\t\tmyexit(1);\n\t}\n\n\treturn 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: void enter_network_namespace(pid_t pid) {\n\t// in case the pid is that of a firejail process, use the pid of the first child process\n\tpid_t child = switch_to_child(pid);\n\n\t// exit if no permission to join the sandbox\n\tcheck_join_permission(child);\n\n\t// check network namespace\n\tchar *name;\n\tif (asprintf(&name, \"/run/firejail/network/%d-netmap\", pid) == -1)\n\t\terrExit(\"asprintf\");\n\tstruct stat s;\n\tif (stat(name, &s) == -1) {\n\t\tfprintf(stderr, \"Error: the sandbox doesn't use a new network namespace\\n\");\n\t\texit(1);\n\t}\n\n\t// join the namespace\n\tEUID_ROOT();\n\tif (join_namespace(child, \"net\")) {\n\t\tfprintf(stderr, \"Error: cannot join the network namespace\\n\");\n\t\texit(1);\n\t}\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: int process_stat(ProcessHandle process, const char *fname, struct stat *s) {\n\tint rv = process_stat_nofail(process, fname, s);\n\tif (rv) {\n\t\tfprintf(stderr, \"Error: cannot stat /proc/%d/%s: %s\\n\", process->pid, fname, strerror(errno));\n\t\texit(1);\n\t}\n\n\treturn rv;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-269', 'CWE-94'], 'message': 'CVE-2022-31214: fixing the fix'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: cmdline_insert_reg(int *gotesc UNUSED)\n{\n int\t\ti;\n int\t\tc;\n\n#ifdef USE_ON_FLY_SCROLL\n dont_scroll = TRUE;\t// disallow scrolling here\n#endif\n putcmdline('\"', TRUE);\n ++no_mapping;\n ++allow_keys;\n i = c = plain_vgetc();\t// CTRL-R \n if (i == Ctrl_O)\n\ti = Ctrl_R;\t\t// CTRL-R CTRL-O == CTRL-R CTRL-R\n if (i == Ctrl_R)\n\tc = plain_vgetc();\t// CTRL-R CTRL-R \n extra_char = NUL;\n --no_mapping;\n --allow_keys;\n#ifdef FEAT_EVAL\n /*\n * Insert the result of an expression.\n * Need to save the current command line, to be able to enter\n * a new one...\n */\n new_cmdpos = -1;\n if (c == '=')\n {\n\tif (ccline.cmdfirstc == '=' // can't do this recursively\n\t\t|| cmdline_star > 0) // or when typing a password\n\t{\n\t beep_flush();\n\t c = ESC;\n\t}\n\telse\n\t c = get_expr_register();\n }\n#endif\n if (c != ESC)\t // use ESC to cancel inserting register\n {\n\tcmdline_paste(c, i == Ctrl_R, FALSE);\n\n#ifdef FEAT_EVAL\n\t// When there was a serious error abort getting the\n\t// command line.\n\tif (aborting())\n\t{\n\t *gotesc = TRUE; // will free ccline.cmdbuff after\n\t // putting it in history\n\t return GOTO_NORMAL_MODE;\n\t}\n#endif\n\tKeyTyped = FALSE;\t// Don't do p_wc completion.\n#ifdef FEAT_EVAL\n\tif (new_cmdpos >= 0)\n\t{\n\t // set_cmdline_pos() was used\n\t if (new_cmdpos > ccline.cmdlen)\n\t\tccline.cmdpos = ccline.cmdlen;\n\t else\n\t\tccline.cmdpos = new_cmdpos;\n\t}\n#endif\n }\n // remove the double quote\n redrawcmd();\n\n // The text has been stuffed, the command line didn't change yet.\n return CMDLINE_NOT_CHANGED;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-126', 'CWE-787'], 'message': 'patch 8.2.5148: invalid memory access when using expression on command line\n\nProblem: Invalid memory access when using an expression on the command line.\nSolution: Make sure the position does not go negative.'" }, { "text": "[INST] Given the following code containing errors, provide Common 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_shellsize(void)\n{\n if (Rows < min_rows())\t// need room for one window and command line\n\tRows = min_rows();\n limit_screen_size();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'patch 8.2.5160: accessing invalid memory after changing terminal size\n\nProblem: Accessing invalid memory after changing terminal size.\nSolution: Adjust cmdline_row and msg_row to the value of Rows.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ins_compl_stop(int c, int prev_mode, int retval)\n{\n char_u\t*ptr;\n int\t\twant_cindent;\n\n // Get here when we have finished typing a sequence of ^N and\n // ^P or other completion characters in CTRL-X mode. Free up\n // memory that was used, and make sure we can redo the insert.\n if (compl_curr_match != NULL || compl_leader != NULL || c == Ctrl_E)\n {\n\t// If any of the original typed text has been changed, eg when\n\t// ignorecase is set, we must add back-spaces to the redo\n\t// buffer. We add as few as necessary to delete just the part\n\t// of the original text that has changed.\n\t// When using the longest match, edited the match or used\n\t// CTRL-E then don't use the current match.\n\tif (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)\n\t ptr = compl_curr_match->cp_str;\n\telse\n\t ptr = NULL;\n\tins_compl_fixRedoBufForLeader(ptr);\n }\n\n want_cindent = (get_can_cindent() && cindent_on());\n\n // When completing whole lines: fix indent for 'cindent'.\n // Otherwise, break line if it's too long.\n if (compl_cont_mode == CTRL_X_WHOLE_LINE)\n {\n\t// re-indent the current line\n\tif (want_cindent)\n\t{\n\t do_c_expr_indent();\n\t want_cindent = FALSE;\t// don't do it again\n\t}\n }\n else\n {\n\tint prev_col = curwin->w_cursor.col;\n\n\t// put the cursor on the last char, for 'tw' formatting\n\tif (prev_col > 0)\n\t dec_cursor();\n\t// only format when something was inserted\n\tif (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)\n\t insertchar(NUL, 0, -1);\n\tif (prev_col > 0\n\t\t&& ml_get_curline()[curwin->w_cursor.col] != NUL)\n\t inc_cursor();\n }\n\n // If the popup menu is displayed pressing CTRL-Y means accepting\n // the selection without inserting anything. When\n // compl_enter_selects is set the Enter key does the same.\n if ((c == Ctrl_Y || (compl_enter_selects\n\t\t && (c == CAR || c == K_KENTER || c == NL)))\n\t && pum_visible())\n\tretval = TRUE;\n\n // CTRL-E means completion is Ended, go back to the typed text.\n // but only do this, if the Popup is still visible\n if (c == Ctrl_E)\n {\n\tins_compl_delete();\n\tif (compl_leader != NULL)\n\t ins_bytes(compl_leader + get_compl_len());\n\telse if (compl_first_match != NULL)\n\t ins_bytes(compl_orig_text + get_compl_len());\n\tretval = TRUE;\n }\n\n auto_format(FALSE, TRUE);\n\n // Trigger the CompleteDonePre event to give scripts a chance to\n // act upon the completion before clearing the info, and restore\n // ctrl_x_mode, so that complete_info() can be used.\n ctrl_x_mode = prev_mode;\n ins_apply_autocmds(EVENT_COMPLETEDONEPRE);\n\n ins_compl_free();\n compl_started = FALSE;\n compl_matches = 0;\n if (!shortmess(SHM_COMPLETIONMENU))\n\tmsg_clr_cmdline();\t// necessary for \"noshowmode\"\n ctrl_x_mode = CTRL_X_NORMAL;\n compl_enter_selects = FALSE;\n if (edit_submode != NULL)\n {\n\tedit_submode = NULL;\n\tshowmode();\n }\n\n#ifdef FEAT_CMDWIN\n if (c == Ctrl_C && cmdwin_type != 0)\n\t// Avoid the popup menu remains displayed when leaving the\n\t// command line window.\n\tupdate_screen(0);\n#endif\n // Indent now if a key was typed that is in 'cinkeys'.\n if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))\n\tdo_c_expr_indent();\n // Trigger the CompleteDone event to give scripts a chance to act\n // upon the end of completion.\n ins_apply_autocmds(EVENT_COMPLETEDONE);\n\n return retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'patch 9.0.0020: with some completion reading past end of string\n\nProblem: With some completion reading past end of string.\nSolution: Check the length of the 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: static void rose_heartbeat_expiry(struct timer_list *t)\n{\n\tstruct sock *sk = from_timer(sk, t, sk_timer);\n\tstruct rose_sock *rose = rose_sk(sk);\n\n\tbh_lock_sock(sk);\n\tswitch (rose->state) {\n\tcase ROSE_STATE_0:\n\t\t/* Magic here: If we listen() and a new link dies before it\n\t\t is accepted() it isn't 'dead' so doesn't get removed. */\n\t\tif (sock_flag(sk, SOCK_DESTROY) ||\n\t\t (sk->sk_state == TCP_LISTEN && sock_flag(sk, SOCK_DEAD))) {\n\t\t\tbh_unlock_sock(sk);\n\t\t\trose_destroy_socket(sk);\n\t\t\treturn;\n\t\t}\n\t\tbreak;\n\n\tcase ROSE_STATE_3:\n\t\t/*\n\t\t * Check for the state of the receive buffer.\n\t\t */\n\t\tif (atomic_read(&sk->sk_rmem_alloc) < (sk->sk_rcvbuf / 2) &&\n\t\t (rose->condition & ROSE_COND_OWN_RX_BUSY)) {\n\t\t\trose->condition &= ~ROSE_COND_OWN_RX_BUSY;\n\t\t\trose->condition &= ~ROSE_COND_ACK_PENDING;\n\t\t\trose->vl = rose->vr;\n\t\t\trose_write_internal(sk, ROSE_RR);\n\t\t\trose_stop_timer(sk);\t/* HB */\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\t}\n\n\trose_start_heartbeat(sk);\n\tbh_unlock_sock(sk);\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: l_noret luaG_runerror (lua_State *L, const char *fmt, ...) {\n CallInfo *ci = L->ci;\n const char *msg;\n va_list argp;\n luaC_checkGC(L); /* error message uses memory */\n va_start(argp, fmt);\n msg = luaO_pushvfstring(L, fmt, argp); /* format message */\n va_end(argp);\n if (isLua(ci)) /* if Lua function, add source:line information */\n luaG_addinfo(L, msg, ci_func(ci)->p->source, getcurrentline(ci));\n luaG_errormsg(L);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Save stack space while handling errors\n\nBecause error handling (luaG_errormsg) uses slots from EXTRA_STACK,\nand some errors can recur (e.g., string overflow while creating an\nerror message in 'luaG_runerror', or a C-stack overflow before calling\nthe message handler), the code should use stack slots with parsimony.\n\nThis commit fixes the bug \"Lua-stack overflow when C stack overflows\nwhile handling an error\".'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: CheckSetDeviceIndicators(char *wire,\n DeviceIntPtr dev,\n int num, int *status_rtrn, ClientPtr client)\n{\n xkbDeviceLedsWireDesc *ledWire;\n int i;\n XkbSrvLedInfoPtr sli;\n\n ledWire = (xkbDeviceLedsWireDesc *) wire;\n for (i = 0; i < num; i++) {\n if (client->swapped) {\n swaps(&ledWire->ledClass);\n swaps(&ledWire->ledID);\n swapl(&ledWire->namesPresent);\n swapl(&ledWire->mapsPresent);\n swapl(&ledWire->physIndicators);\n }\n\n sli = XkbFindSrvLedInfo(dev, ledWire->ledClass, ledWire->ledID,\n XkbXI_IndicatorsMask);\n if (sli != NULL) {\n register int n;\n register unsigned bit;\n int nMaps, nNames;\n CARD32 *atomWire;\n xkbIndicatorMapWireDesc *mapWire;\n\n nMaps = nNames = 0;\n for (n = 0, bit = 1; n < XkbNumIndicators; n++, bit <<= 1) {\n if (ledWire->namesPresent & bit)\n nNames++;\n if (ledWire->mapsPresent & bit)\n nMaps++;\n }\n atomWire = (CARD32 *) &ledWire[1];\n if (nNames > 0) {\n for (n = 0; n < nNames; n++) {\n if (client->swapped) {\n swapl(atomWire);\n }\n CHK_ATOM_OR_NONE3(((Atom) (*atomWire)), client->errorValue,\n *status_rtrn, NULL);\n atomWire++;\n }\n }\n mapWire = (xkbIndicatorMapWireDesc *) atomWire;\n if (nMaps > 0) {\n for (n = 0; n < nMaps; n++) {\n if (client->swapped) {\n swaps(&mapWire->virtualMods);\n swapl(&mapWire->ctrls);\n }\n CHK_MASK_LEGAL3(0x21, mapWire->whichGroups,\n XkbIM_UseAnyGroup,\n client->errorValue, *status_rtrn, NULL);\n CHK_MASK_LEGAL3(0x22, mapWire->whichMods, XkbIM_UseAnyMods,\n client->errorValue, *status_rtrn, NULL);\n mapWire++;\n }\n }\n ledWire = (xkbDeviceLedsWireDesc *) mapWire;\n }\n else {\n /* SHOULD NEVER HAPPEN */\n return (char *) ledWire;\n }\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: \nprivate void\nrestore_cont(struct magic_set *ms, struct cont *c)\n{\n\tfree(ms->c.li); ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix #81723: Memory corruption in finfo_buffer()\n\nWe need to use the same memory allocator throughout.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int vt_disallocate(unsigned int vc_num)\n{\n\tstruct vc_data *vc = NULL;\n\tint ret = 0;\n\n\tconsole_lock();\n\tif (vt_busy(vc_num))\n\t\tret = -EBUSY;\n\telse if (vc_num)\n\t\tvc = vc_deallocate(vc_num);\n\tconsole_unlock();\n\n\tif (vc && vc_num >= MIN_NR_CONSOLES) {\n\t\ttty_port_destroy(&vc->port);\n\t\tkfree(vc);\n\t}\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-362'], 'message': 'vt: vt_ioctl: fix VT_DISALLOCATE freeing in-use virtual console\n\nThe VT_DISALLOCATE ioctl can free a virtual console while tty_release()\nis still running, causing a use-after-free in con_shutdown(). This\noccurs because VT_DISALLOCATE considers a virtual console's\n'struct vc_data' to be unused as soon as the corresponding tty's\nrefcount hits 0. But actually it may be still being closed.\n\nFix this by making vc_data be reference-counted via the embedded\n'struct tty_port'. A newly allocated virtual console has refcount 1.\nOpening it for the first time increments the refcount to 2. Closing it\nfor the last time decrements the refcount (in tty_operations::cleanup()\nso that it happens late enough), as does VT_DISALLOCATE.\n\nReproducer:\n\t#include \n\t#include \n\t#include \n\t#include \n\n\tint main()\n\t{\n\t\tif (fork()) {\n\t\t\tfor (;;)\n\t\t\t\tclose(open(\"/dev/tty5\", O_RDWR));\n\t\t} else {\n\t\t\tint fd = open(\"/dev/tty10\", O_RDWR);\n\n\t\t\tfor (;;)\n\t\t\t\tioctl(fd, VT_DISALLOCATE, 5);\n\t\t}\n\t}\n\nKASAN report:\n\tBUG: KASAN: use-after-free in con_shutdown+0x76/0x80 drivers/tty/vt/vt.c:3278\n\tWrite of size 8 at addr ffff88806a4ec108 by task syz_vt/129\n\n\tCPU: 0 PID: 129 Comm: syz_vt Not tainted 5.6.0-rc2 #11\n\tHardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS ?-20191223_100556-anatol 04/01/2014\n\tCall Trace:\n\t [...]\n\t con_shutdown+0x76/0x80 drivers/tty/vt/vt.c:3278\n\t release_tty+0xa8/0x410 drivers/tty/tty_io.c:1514\n\t tty_release_struct+0x34/0x50 drivers/tty/tty_io.c:1629\n\t tty_release+0x984/0xed0 drivers/tty/tty_io.c:1789\n\t [...]\n\n\tAllocated by task 129:\n\t [...]\n\t kzalloc include/linux/slab.h:669 [inline]\n\t vc_allocate drivers/tty/vt/vt.c:1085 [inline]\n\t vc_allocate+0x1ac/0x680 drivers/tty/vt/vt.c:1066\n\t con_install+0x4d/0x3f0 drivers/tty/vt/vt.c:3229\n\t tty_driver_install_tty drivers/tty/tty_io.c:1228 [inline]\n\t tty_init_dev+0x94/0x350 drivers/tty/tty_io.c:1341\n\t tty_open_by_driver drivers/tty/tty_io.c:1987 [inline]\n\t tty_open+0x3ca/0xb30 drivers/tty/tty_io.c:2035\n\t [...]\n\n\tFreed by task 130:\n\t [...]\n\t kfree+0xbf/0x1e0 mm/slab.c:3757\n\t vt_disallocate drivers/tty/vt/vt_ioctl.c:300 [inline]\n\t vt_ioctl+0x16dc/0x1e30 drivers/tty/vt/vt_ioctl.c:818\n\t tty_ioctl+0x9db/0x11b0 drivers/tty/tty_io.c:2660\n\t [...]\n\nFixes: 4001d7b7fc27 (\"vt: push down the tty lock so we can see what is left to tackle\")\nCc: # v3.4+\nReported-by: syzbot+522643ab5729b0421998@syzkaller.appspotmail.com\nAcked-by: Jiri Slaby \nSigned-off-by: Eric Biggers \nLink: https://lore.kernel.org/r/20200322034305.210082-2-ebiggers@kernel.org\nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int print_deleg_lookup(RES* ssl, struct worker* worker, uint8_t* nm,\n\tsize_t nmlen, int ATTR_UNUSED(nmlabs))\n{\n\t/* deep links into the iterator module */\n\tstruct delegpt* dp;\n\tstruct dns_msg* msg;\n\tstruct regional* region = worker->scratchpad;\n\tchar b[260];\n\tstruct query_info qinfo;\n\tstruct iter_hints_stub* stub;\n\tregional_free_all(region);\n\tqinfo.qname = nm;\n\tqinfo.qname_len = nmlen;\n\tqinfo.qtype = LDNS_RR_TYPE_A;\n\tqinfo.qclass = LDNS_RR_CLASS_IN;\n\tqinfo.local_alias = NULL;\n\n\tdname_str(nm, b);\n\tif(!ssl_printf(ssl, \"The following name servers are used for lookup \"\n\t\t\"of %s\\n\", b)) \n\t\treturn 0;\n\t\n\tdp = forwards_lookup(worker->env.fwds, nm, qinfo.qclass);\n\tif(dp) {\n\t\tif(!ssl_printf(ssl, \"forwarding request:\\n\"))\n\t\t\treturn 0;\n\t\tprint_dp_main(ssl, dp, NULL);\n\t\tprint_dp_details(ssl, worker, dp);\n\t\treturn 1;\n\t}\n\t\n\twhile(1) {\n\t\tdp = dns_cache_find_delegation(&worker->env, nm, nmlen, \n\t\t\tqinfo.qtype, qinfo.qclass, region, &msg, \n\t\t\t*worker->env.now);\n\t\tif(!dp) {\n\t\t\treturn ssl_printf(ssl, \"no delegation from \"\n\t\t\t\t\"cache; goes to configured roots\\n\");\n\t\t}\n\t\t/* go up? */\n\t\tif(iter_dp_is_useless(&qinfo, BIT_RD, dp,\n\t\t\t(worker->env.cfg->do_ip4 && worker->back->num_ip4 != 0),\n\t\t\t(worker->env.cfg->do_ip6 && worker->back->num_ip6 != 0))) {\n\t\t\tprint_dp_main(ssl, dp, msg);\n\t\t\tprint_dp_details(ssl, worker, dp);\n\t\t\tif(!ssl_printf(ssl, \"cache delegation was \"\n\t\t\t\t\"useless (no IP addresses)\\n\"))\n\t\t\t\treturn 0;\n\t\t\tif(dname_is_root(nm)) {\n\t\t\t\t/* goes to root config */\n\t\t\t\treturn ssl_printf(ssl, \"no delegation from \"\n\t\t\t\t\t\"cache; goes to configured roots\\n\");\n\t\t\t} else {\n\t\t\t\t/* useless, goes up */\n\t\t\t\tnm = dp->name;\n\t\t\t\tnmlen = dp->namelen;\n\t\t\t\tdname_remove_label(&nm, &nmlen);\n\t\t\t\tdname_str(nm, b);\n\t\t\t\tif(!ssl_printf(ssl, \"going up, lookup %s\\n\", b))\n\t\t\t\t\treturn 0;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t} \n\t\tstub = hints_lookup_stub(worker->env.hints, nm, qinfo.qclass,\n\t\t\tdp);\n\t\tif(stub) {\n\t\t\tif(stub->noprime) {\n\t\t\t\tif(!ssl_printf(ssl, \"The noprime stub servers \"\n\t\t\t\t\t\"are used:\\n\"))\n\t\t\t\t\treturn 0;\n\t\t\t} else {\n\t\t\t\tif(!ssl_printf(ssl, \"The stub is primed \"\n\t\t\t\t\t\t\"with servers:\\n\"))\n\t\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tprint_dp_main(ssl, stub->dp, NULL);\n\t\t\tprint_dp_details(ssl, worker, stub->dp);\n\t\t} else {\n\t\t\tprint_dp_main(ssl, dp, msg);\n\t\t\tprint_dp_details(ssl, worker, dp);\n\t\t}\n\t\tbreak;\n\t}\n\n\treturn 1;\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: processInitRequest(struct module_qstate* qstate, struct iter_qstate* iq,\n\tstruct iter_env* ie, int id)\n{\n\tuint8_t* delname, *dpname=NULL;\n\tsize_t delnamelen, dpnamelen=0;\n\tstruct dns_msg* msg = NULL;\n\n\tlog_query_info(VERB_DETAIL, \"resolving\", &qstate->qinfo);\n\t/* check effort */\n\n\t/* We enforce a maximum number of query restarts. This is primarily a\n\t * cheap way to prevent CNAME loops. */\n\tif(iq->query_restart_count > MAX_RESTART_COUNT) {\n\t\tverbose(VERB_QUERY, \"request has exceeded the maximum number\"\n\t\t\t\" of query restarts with %d\", iq->query_restart_count);\n\t\terrinf(qstate, \"request has exceeded the maximum number \"\n\t\t\t\"restarts (eg. indirections)\");\n\t\tif(iq->qchase.qname)\n\t\t\terrinf_dname(qstate, \"stop at\", iq->qchase.qname);\n\t\treturn error_response(qstate, id, LDNS_RCODE_SERVFAIL);\n\t}\n\n\t/* We enforce a maximum recursion/dependency depth -- in general, \n\t * this is unnecessary for dependency loops (although it will \n\t * catch those), but it provides a sensible limit to the amount \n\t * of work required to answer a given query. */\n\tverbose(VERB_ALGO, \"request has dependency depth of %d\", iq->depth);\n\tif(iq->depth > ie->max_dependency_depth) {\n\t\tverbose(VERB_QUERY, \"request has exceeded the maximum \"\n\t\t\t\"dependency depth with depth of %d\", iq->depth);\n\t\terrinf(qstate, \"request has exceeded the maximum dependency \"\n\t\t\t\"depth (eg. nameserver lookup recursion)\");\n\t\treturn error_response(qstate, id, LDNS_RCODE_SERVFAIL);\n\t}\n\n\t/* If the request is qclass=ANY, setup to generate each class */\n\tif(qstate->qinfo.qclass == LDNS_RR_CLASS_ANY) {\n\t\tiq->qchase.qclass = 0;\n\t\treturn next_state(iq, COLLECT_CLASS_STATE);\n\t}\n\n\t/*\n\t * If we are restricted by a forward-zone or a stub-zone, we\n\t * can't re-fetch glue for this delegation point.\n\t * we won\u2019t try to re-fetch glue if the iq->dp is null.\n\t */\n\tif (iq->refetch_glue &&\n\t iq->dp &&\n\t !can_have_last_resort(qstate->env, iq->dp->name,\n\t iq->dp->namelen, iq->qchase.qclass, NULL)) {\n\t iq->refetch_glue = 0;\n\t}\n\n\t/* Resolver Algorithm Step 1 -- Look for the answer in local data. */\n\n\t/* This either results in a query restart (CNAME cache response), a\n\t * terminating response (ANSWER), or a cache miss (null). */\n\t\n\tif (iter_stub_fwd_no_cache(qstate, &iq->qchase, &dpname, &dpnamelen)) {\n\t\t/* Asked to not query cache. */\n\t\tverbose(VERB_ALGO, \"no-cache set, going to the network\");\n\t\tqstate->no_cache_lookup = 1;\n\t\tqstate->no_cache_store = 1;\n\t\tmsg = NULL;\n\t} else if(qstate->blacklist) {\n\t\t/* if cache, or anything else, was blacklisted then\n\t\t * getting older results from cache is a bad idea, no cache */\n\t\tverbose(VERB_ALGO, \"cache blacklisted, going to the network\");\n\t\tmsg = NULL;\n\t} else if(!qstate->no_cache_lookup) {\n\t\tmsg = dns_cache_lookup(qstate->env, iq->qchase.qname, \n\t\t\tiq->qchase.qname_len, iq->qchase.qtype, \n\t\t\tiq->qchase.qclass, qstate->query_flags,\n\t\t\tqstate->region, qstate->env->scratch, 0, dpname,\n\t\t\tdpnamelen);\n\t\tif(!msg && qstate->env->neg_cache &&\n\t\t\titer_qname_indicates_dnssec(qstate->env, &iq->qchase)) {\n\t\t\t/* lookup in negative cache; may result in\n\t\t\t * NOERROR/NODATA or NXDOMAIN answers that need validation */\n\t\t\tmsg = val_neg_getmsg(qstate->env->neg_cache, &iq->qchase,\n\t\t\t\tqstate->region, qstate->env->rrset_cache,\n\t\t\t\tqstate->env->scratch_buffer, \n\t\t\t\t*qstate->env->now, 1/*add SOA*/, NULL, \n\t\t\t\tqstate->env->cfg);\n\t\t}\n\t\t/* item taken from cache does not match our query name, thus\n\t\t * security needs to be re-examined later */\n\t\tif(msg && query_dname_compare(qstate->qinfo.qname,\n\t\t\tiq->qchase.qname) != 0)\n\t\t\tmsg->rep->security = sec_status_unchecked;\n\t}\n\tif(msg) {\n\t\t/* handle positive cache response */\n\t\tenum response_type type = response_type_from_cache(msg, \n\t\t\t&iq->qchase);\n\t\tif(verbosity >= VERB_ALGO) {\n\t\t\tlog_dns_msg(\"msg from cache lookup\", &msg->qinfo, \n\t\t\t\tmsg->rep);\n\t\t\tverbose(VERB_ALGO, \"msg ttl is %d, prefetch ttl %d\", \n\t\t\t\t(int)msg->rep->ttl, \n\t\t\t\t(int)msg->rep->prefetch_ttl);\n\t\t}\n\n\t\tif(type == RESPONSE_TYPE_CNAME) {\n\t\t\tuint8_t* sname = 0;\n\t\t\tsize_t slen = 0;\n\t\t\tverbose(VERB_ALGO, \"returning CNAME response from \"\n\t\t\t\t\"cache\");\n\t\t\tif(!handle_cname_response(qstate, iq, msg, \n\t\t\t\t&sname, &slen)) {\n\t\t\t\terrinf(qstate, \"failed to prepend CNAME \"\n\t\t\t\t\t\"components, malloc failure\");\n\t\t\t\treturn error_response(qstate, id, \n\t\t\t\t\tLDNS_RCODE_SERVFAIL);\n\t\t\t}\n\t\t\tiq->qchase.qname = sname;\n\t\t\tiq->qchase.qname_len = slen;\n\t\t\t/* This *is* a query restart, even if it is a cheap \n\t\t\t * one. */\n\t\t\tiq->dp = NULL;\n\t\t\tiq->refetch_glue = 0;\n\t\t\tiq->query_restart_count++;\n\t\t\tiq->sent_count = 0;\n\t\t\tiq->dp_target_count = 0;\n\t\t\tsock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);\n\t\t\tif(qstate->env->cfg->qname_minimisation)\n\t\t\t\tiq->minimisation_state = INIT_MINIMISE_STATE;\n\t\t\treturn next_state(iq, INIT_REQUEST_STATE);\n\t\t}\n\n\t\t/* if from cache, NULL, else insert 'cache IP' len=0 */\n\t\tif(qstate->reply_origin)\n\t\t\tsock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);\n\t\tif(FLAGS_GET_RCODE(msg->rep->flags) == LDNS_RCODE_SERVFAIL)\n\t\t\terrinf(qstate, \"SERVFAIL in cache\");\n\t\t/* it is an answer, response, to final state */\n\t\tverbose(VERB_ALGO, \"returning answer from cache.\");\n\t\tiq->response = msg;\n\t\treturn final_state(iq);\n\t}\n\n\t/* attempt to forward the request */\n\tif(forward_request(qstate, iq))\n\t{\n\t\tif(!iq->dp) {\n\t\t\tlog_err(\"alloc failure for forward dp\");\n\t\t\terrinf(qstate, \"malloc failure for forward zone\");\n\t\t\treturn error_response(qstate, id, LDNS_RCODE_SERVFAIL);\n\t\t}\n\t\tiq->refetch_glue = 0;\n\t\tiq->minimisation_state = DONOT_MINIMISE_STATE;\n\t\t/* the request has been forwarded.\n\t\t * forwarded requests need to be immediately sent to the \n\t\t * next state, QUERYTARGETS. */\n\t\treturn next_state(iq, QUERYTARGETS_STATE);\n\t}\n\n\t/* Resolver Algorithm Step 2 -- find the \"best\" servers. */\n\n\t/* first, adjust for DS queries. To avoid the grandparent problem, \n\t * we just look for the closest set of server to the parent of qname.\n\t * When re-fetching glue we also need to ask the parent.\n\t */\n\tif(iq->refetch_glue) {\n\t\tif(!iq->dp) {\n\t\t\tlog_err(\"internal or malloc fail: no dp for refetch\");\n\t\t\terrinf(qstate, \"malloc failure, for delegation info\");\n\t\t\treturn error_response(qstate, id, LDNS_RCODE_SERVFAIL);\n\t\t}\n\t\tdelname = iq->dp->name;\n\t\tdelnamelen = iq->dp->namelen;\n\t} else {\n\t\tdelname = iq->qchase.qname;\n\t\tdelnamelen = iq->qchase.qname_len;\n\t}\n\tif(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue ||\n\t (iq->qchase.qtype == LDNS_RR_TYPE_NS && qstate->prefetch_leeway\n\t && can_have_last_resort(qstate->env, delname, delnamelen, iq->qchase.qclass, NULL))) {\n\t\t/* remove first label from delname, root goes to hints,\n\t\t * but only to fetch glue, not for qtype=DS. */\n\t\t/* also when prefetching an NS record, fetch it again from\n\t\t * its parent, just as if it expired, so that you do not\n\t\t * get stuck on an older nameserver that gives old NSrecords */\n\t\tif(dname_is_root(delname) && (iq->refetch_glue ||\n\t\t\t(iq->qchase.qtype == LDNS_RR_TYPE_NS &&\n\t\t\tqstate->prefetch_leeway)))\n\t\t\tdelname = NULL; /* go to root priming */\n\t\telse \tdname_remove_label(&delname, &delnamelen);\n\t}\n\t/* delname is the name to lookup a delegation for. If NULL rootprime */\n\twhile(1) {\n\t\t\n\t\t/* Lookup the delegation in the cache. If null, then the \n\t\t * cache needs to be primed for the qclass. */\n\t\tif(delname)\n\t\t iq->dp = dns_cache_find_delegation(qstate->env, delname, \n\t\t\tdelnamelen, iq->qchase.qtype, iq->qchase.qclass, \n\t\t\tqstate->region, &iq->deleg_msg,\n\t\t\t*qstate->env->now+qstate->prefetch_leeway);\n\t\telse iq->dp = NULL;\n\n\t\t/* If the cache has returned nothing, then we have a \n\t\t * root priming situation. */\n\t\tif(iq->dp == NULL) {\n\t\t\tint r;\n\t\t\t/* if under auth zone, no prime needed */\n\t\t\tif(!auth_zone_delegpt(qstate, iq, delname, delnamelen))\n\t\t\t\treturn error_response(qstate, id, \n\t\t\t\t\tLDNS_RCODE_SERVFAIL);\n\t\t\tif(iq->dp) /* use auth zone dp */\n\t\t\t\treturn next_state(iq, INIT_REQUEST_2_STATE);\n\t\t\t/* if there is a stub, then no root prime needed */\n\t\t\tr = prime_stub(qstate, iq, id, delname,\n\t\t\t\tiq->qchase.qclass);\n\t\t\tif(r == 2)\n\t\t\t\tbreak; /* got noprime-stub-zone, continue */\n\t\t\telse if(r)\n\t\t\t\treturn 0; /* stub prime request made */\n\t\t\tif(forwards_lookup_root(qstate->env->fwds, \n\t\t\t\tiq->qchase.qclass)) {\n\t\t\t\t/* forward zone root, no root prime needed */\n\t\t\t\t/* fill in some dp - safety belt */\n\t\t\t\tiq->dp = hints_lookup_root(qstate->env->hints, \n\t\t\t\t\tiq->qchase.qclass);\n\t\t\t\tif(!iq->dp) {\n\t\t\t\t\tlog_err(\"internal error: no hints dp\");\n\t\t\t\t\terrinf(qstate, \"no hints for this class\");\n\t\t\t\t\treturn error_response(qstate, id, \n\t\t\t\t\t\tLDNS_RCODE_SERVFAIL);\n\t\t\t\t}\n\t\t\t\tiq->dp = delegpt_copy(iq->dp, qstate->region);\n\t\t\t\tif(!iq->dp) {\n\t\t\t\t\tlog_err(\"out of memory in safety belt\");\n\t\t\t\t\terrinf(qstate, \"malloc failure, in safety belt\");\n\t\t\t\t\treturn error_response(qstate, id, \n\t\t\t\t\t\tLDNS_RCODE_SERVFAIL);\n\t\t\t\t}\n\t\t\t\treturn next_state(iq, INIT_REQUEST_2_STATE);\n\t\t\t}\n\t\t\t/* Note that the result of this will set a new\n\t\t\t * DelegationPoint based on the result of priming. */\n\t\t\tif(!prime_root(qstate, iq, id, iq->qchase.qclass))\n\t\t\t\treturn error_response(qstate, id, \n\t\t\t\t\tLDNS_RCODE_REFUSED);\n\n\t\t\t/* priming creates and sends a subordinate query, with \n\t\t\t * this query as the parent. So further processing for \n\t\t\t * this event will stop until reactivated by the \n\t\t\t * results of priming. */\n\t\t\treturn 0;\n\t\t}\n\t\tif(!iq->ratelimit_ok && qstate->prefetch_leeway)\n\t\t\tiq->ratelimit_ok = 1; /* allow prefetches, this keeps\n\t\t\totherwise valid data in the cache */\n\n\t\t/* see if this dp not useless.\n\t\t * It is useless if:\n\t\t *\to all NS items are required glue. \n\t\t *\t or the query is for NS item that is required glue.\n\t\t *\to no addresses are provided.\n\t\t *\to RD qflag is on.\n\t\t * Instead, go up one level, and try to get even further\n\t\t * If the root was useless, use safety belt information. \n\t\t * Only check cache returns, because replies for servers\n\t\t * could be useless but lead to loops (bumping into the\n\t\t * same server reply) if useless-checked.\n\t\t */\n\t\tif(iter_dp_is_useless(&qstate->qinfo, qstate->query_flags, \n\t\t\tiq->dp, ie->supports_ipv4, ie->supports_ipv6)) {\n\t\t\tstruct delegpt* retdp = NULL;\n\t\t\tif(!can_have_last_resort(qstate->env, iq->dp->name, iq->dp->namelen, iq->qchase.qclass, &retdp)) {\n\t\t\t\tif(retdp) {\n\t\t\t\t\tverbose(VERB_QUERY, \"cache has stub \"\n\t\t\t\t\t\t\"or fwd but no addresses, \"\n\t\t\t\t\t\t\"fallback to config\");\n\t\t\t\t\tiq->dp = delegpt_copy(retdp,\n\t\t\t\t\t\tqstate->region);\n\t\t\t\t\tif(!iq->dp) {\n\t\t\t\t\t\tlog_err(\"out of memory in \"\n\t\t\t\t\t\t\t\"stub/fwd fallback\");\n\t\t\t\t\t\terrinf(qstate, \"malloc failure, for fallback to config\");\n\t\t\t\t\t\treturn error_response(qstate,\n\t\t\t\t\t\t id, LDNS_RCODE_SERVFAIL);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tverbose(VERB_ALGO, \"useless dp \"\n\t\t\t\t\t\"but cannot go up, servfail\");\n\t\t\t\tdelegpt_log(VERB_ALGO, iq->dp);\n\t\t\t\terrinf(qstate, \"no useful nameservers, \"\n\t\t\t\t\t\"and cannot go up\");\n\t\t\t\terrinf_dname(qstate, \"for zone\", iq->dp->name);\n\t\t\t\treturn error_response(qstate, id, \n\t\t\t\t\tLDNS_RCODE_SERVFAIL);\n\t\t\t}\n\t\t\tif(dname_is_root(iq->dp->name)) {\n\t\t\t\t/* use safety belt */\n\t\t\t\tverbose(VERB_QUERY, \"Cache has root NS but \"\n\t\t\t\t\"no addresses. Fallback to the safety belt.\");\n\t\t\t\tiq->dp = hints_lookup_root(qstate->env->hints, \n\t\t\t\t\tiq->qchase.qclass);\n\t\t\t\t/* note deleg_msg is from previous lookup,\n\t\t\t\t * but RD is on, so it is not used */\n\t\t\t\tif(!iq->dp) {\n\t\t\t\t\tlog_err(\"internal error: no hints dp\");\n\t\t\t\t\treturn error_response(qstate, id, \n\t\t\t\t\t\tLDNS_RCODE_REFUSED);\n\t\t\t\t}\n\t\t\t\tiq->dp = delegpt_copy(iq->dp, qstate->region);\n\t\t\t\tif(!iq->dp) {\n\t\t\t\t\tlog_err(\"out of memory in safety belt\");\n\t\t\t\t\terrinf(qstate, \"malloc failure, in safety belt, for root\");\n\t\t\t\t\treturn error_response(qstate, id, \n\t\t\t\t\t\tLDNS_RCODE_SERVFAIL);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\tverbose(VERB_ALGO, \n\t\t\t\t\t\"cache delegation was useless:\");\n\t\t\t\tdelegpt_log(VERB_ALGO, iq->dp);\n\t\t\t\t/* go up */\n\t\t\t\tdelname = iq->dp->name;\n\t\t\t\tdelnamelen = iq->dp->namelen;\n\t\t\t\tdname_remove_label(&delname, &delnamelen);\n\t\t\t}\n\t\t} else break;\n\t}\n\n\tverbose(VERB_ALGO, \"cache delegation returns delegpt\");\n\tdelegpt_log(VERB_ALGO, iq->dp);\n\n\t/* Otherwise, set the current delegation point and move on to the \n\t * next state. */\n\treturn next_state(iq, INIT_REQUEST_2_STATE);\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: find_closest_of_type(struct module_env* env, uint8_t* qname, size_t qnamelen, \n\tuint16_t qclass, time_t now, uint16_t searchtype, int stripfront)\n{\n\tstruct ub_packed_rrset_key *rrset;\n\tuint8_t lablen;\n\n\tif(stripfront) {\n\t\t/* strip off so that DNAMEs have strict subdomain match */\n\t\tlablen = *qname;\n\t\tqname += lablen + 1;\n\t\tqnamelen -= lablen + 1;\n\t}\n\n\t/* snip off front part of qname until the type is found */\n\twhile(qnamelen > 0) {\n\t\tif((rrset = rrset_cache_lookup(env->rrset_cache, qname, \n\t\t\tqnamelen, searchtype, qclass, 0, now, 0)))\n\t\t\treturn rrset;\n\n\t\t/* snip off front label */\n\t\tlablen = *qname;\n\t\tqname += lablen + 1;\n\t\tqnamelen -= lablen + 1;\n\t}\n\treturn NULL;\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: compile_lock_unlock(\n lval_T *lvp,\n char_u *name_end,\n exarg_T *eap,\n int\t deep,\n void *coookie)\n{\n cctx_T\t*cctx = coookie;\n int\t\tcc = *name_end;\n char_u\t*p = lvp->ll_name;\n int\t\tret = OK;\n size_t\tlen;\n char_u\t*buf;\n isntype_T\tisn = ISN_EXEC;\n\n if (cctx->ctx_skip == SKIP_YES)\n\treturn OK;\n\n // Cannot use :lockvar and :unlockvar on local variables.\n if (p[1] != ':')\n {\n\tchar_u *end = find_name_end(p, NULL, NULL, FNE_CHECK_START);\n\n\tif (lookup_local(p, end - p, NULL, cctx) == OK)\n\t{\n\t char_u *s = p;\n\n\t if (*end != '.' && *end != '[')\n\t {\n\t\temsg(_(e_cannot_lock_unlock_local_variable));\n\t\treturn FAIL;\n\t }\n\n\t // For \"d.member\" put the local variable on the stack, it will be\n\t // passed to ex_lockvar() indirectly.\n\t if (compile_load(&s, end, cctx, FALSE, FALSE) == FAIL)\n\t\treturn FAIL;\n\t isn = ISN_LOCKUNLOCK;\n\t}\n }\n\n // Checking is done at runtime.\n *name_end = NUL;\n len = name_end - p + 20;\n buf = alloc(len);\n if (buf == NULL)\n\tret = FAIL;\n else\n {\n\tchar *cmd = eap->cmdidx == CMD_lockvar ? \"lockvar\" : \"unlockvar\";\n\n\tif (deep < 0)\n\t vim_snprintf((char *)buf, len, \"%s! %s\", cmd, p);\n\telse\n\t vim_snprintf((char *)buf, len, \"%s %d %s\", cmd, deep, p);\n\tret = generate_EXEC_copy(cctx, isn, buf);\n\n\tvim_free(buf);\n\t*name_end = cc;\n }\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-122'], 'message': 'patch 9.0.0211: invalid memory access when compiling :lockvar\n\nProblem: Invalid memory access when compiling :lockvar.\nSolution: Don't read past the end of the 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: get_lambda_tv(\n\tchar_u\t **arg,\n\ttypval_T *rettv,\n\tint\t types_optional,\n\tevalarg_T *evalarg)\n{\n int\t\tevaluate = evalarg != NULL\n\t\t\t\t && (evalarg->eval_flags & EVAL_EVALUATE);\n garray_T\tnewargs;\n garray_T\tnewlines;\n garray_T\t*pnewargs;\n garray_T\targtypes;\n garray_T\tdefault_args;\n ufunc_T\t*fp = NULL;\n partial_T *pt = NULL;\n int\t\tvarargs;\n char_u\t*ret_type = NULL;\n int\t\tret;\n char_u\t*s;\n char_u\t*start, *end;\n int\t\t*old_eval_lavars = eval_lavars_used;\n int\t\teval_lavars = FALSE;\n char_u\t*tofree1 = NULL;\n char_u\t*tofree2 = NULL;\n int\t\tequal_arrow = **arg == '(';\n int\t\twhite_error = FALSE;\n int\t\tcalled_emsg_start = called_emsg;\n int\t\tvim9script = in_vim9script();\n long\tstart_lnum = SOURCING_LNUM;\n\n if (equal_arrow && !vim9script)\n\treturn NOTDONE;\n\n ga_init(&newargs);\n ga_init(&newlines);\n\n // First, check if this is really a lambda expression. \"->\" or \"=>\" must\n // be found after the arguments.\n s = *arg + 1;\n ret = get_function_args(&s, equal_arrow ? ')' : '-', NULL,\n\t types_optional ? &argtypes : NULL, types_optional, evalarg,\n\t\t\t\t\tNULL, &default_args, TRUE, NULL, NULL);\n if (ret == FAIL || skip_arrow(s, equal_arrow, &ret_type, NULL) == NULL)\n {\n\tif (types_optional)\n\t ga_clear_strings(&argtypes);\n\treturn called_emsg == called_emsg_start ? NOTDONE : FAIL;\n }\n\n // Parse the arguments for real.\n if (evaluate)\n\tpnewargs = &newargs;\n else\n\tpnewargs = NULL;\n *arg += 1;\n ret = get_function_args(arg, equal_arrow ? ')' : '-', pnewargs,\n\t types_optional ? &argtypes : NULL, types_optional, evalarg,\n\t\t\t\t\t &varargs, &default_args,\n\t\t\t\t\t FALSE, NULL, NULL);\n if (ret == FAIL\n\t\t || (s = skip_arrow(*arg, equal_arrow, &ret_type,\n\t\tequal_arrow || vim9script ? &white_error : NULL)) == NULL)\n {\n\tif (types_optional)\n\t ga_clear_strings(&argtypes);\n\tga_clear_strings(&newargs);\n\treturn white_error ? FAIL : NOTDONE;\n }\n *arg = s;\n\n // Skipping over linebreaks may make \"ret_type\" invalid, make a copy.\n if (ret_type != NULL)\n {\n\tret_type = vim_strsave(ret_type);\n\ttofree2 = ret_type;\n }\n\n // Set up a flag for checking local variables and arguments.\n if (evaluate)\n\teval_lavars_used = &eval_lavars;\n\n *arg = skipwhite_and_linebreak(*arg, evalarg);\n\n // Recognize \"{\" as the start of a function body.\n if (equal_arrow && **arg == '{')\n {\n\tif (evalarg == NULL)\n\t // cannot happen?\n\t goto theend;\n\tSOURCING_LNUM = start_lnum; // used for where lambda is defined\n\tif (lambda_function_body(arg, rettv, evalarg, pnewargs,\n\t\t\t types_optional ? &argtypes : NULL, varargs,\n\t\t\t &default_args, ret_type) == FAIL)\n\t goto errret;\n\tgoto theend;\n }\n if (default_args.ga_len > 0)\n {\n\temsg(_(e_cannot_use_default_values_in_lambda));\n\tgoto errret;\n }\n\n // Get the start and the end of the expression.\n start = *arg;\n ret = skip_expr_concatenate(arg, &start, &end, evalarg);\n if (ret == FAIL)\n\tgoto errret;\n if (evalarg != NULL)\n {\n\t// avoid that the expression gets freed when another line break follows\n\ttofree1 = evalarg->eval_tofree;\n\tevalarg->eval_tofree = NULL;\n }\n\n if (!equal_arrow)\n {\n\t*arg = skipwhite_and_linebreak(*arg, evalarg);\n\tif (**arg != '}')\n\t{\n\t semsg(_(e_expected_right_curly_str), *arg);\n\t goto errret;\n\t}\n\t++*arg;\n }\n\n if (evaluate)\n {\n\tint\t len;\n\tint\t flags = FC_LAMBDA;\n\tchar_u\t *p;\n\tchar_u\t *line_end;\n\tchar_u\t *name = get_lambda_name();\n\n\tfp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1);\n\tif (fp == NULL)\n\t goto errret;\n\tfp->uf_def_status = UF_NOT_COMPILED;\n\tpt = ALLOC_CLEAR_ONE(partial_T);\n\tif (pt == NULL)\n\t goto errret;\n\n\tga_init2(&newlines, sizeof(char_u *), 1);\n\tif (ga_grow(&newlines, 1) == FAIL)\n\t goto errret;\n\n\t// If there are line breaks, we need to split up the string.\n\tline_end = vim_strchr(start, '\\n');\n\tif (line_end == NULL || line_end > end)\n\t line_end = end;\n\n\t// Add \"return \" before the expression (or the first line).\n\tlen = 7 + (int)(line_end - start) + 1;\n\tp = alloc(len);\n\tif (p == NULL)\n\t goto errret;\n\t((char_u **)(newlines.ga_data))[newlines.ga_len++] = p;\n\tSTRCPY(p, \"return \");\n\tvim_strncpy(p + 7, start, line_end - start);\n\n\tif (line_end != end)\n\t{\n\t // Add more lines, split by line breaks. Thus is used when a\n\t // lambda with { cmds } is encountered.\n\t while (*line_end == '\\n')\n\t {\n\t\tif (ga_grow(&newlines, 1) == FAIL)\n\t\t goto errret;\n\t\tstart = line_end + 1;\n\t\tline_end = vim_strchr(start, '\\n');\n\t\tif (line_end == NULL)\n\t\t line_end = end;\n\t\t((char_u **)(newlines.ga_data))[newlines.ga_len++] =\n\t\t\t\t\t vim_strnsave(start, line_end - start);\n\t }\n\t}\n\n\tif (strstr((char *)p + 7, \"a:\") == NULL)\n\t // No a: variables are used for sure.\n\t flags |= FC_NOARGS;\n\n\tfp->uf_refcount = 1;\n\tset_ufunc_name(fp, name);\n\tfp->uf_args = newargs;\n\tga_init(&fp->uf_def_args);\n\tif (types_optional)\n\t{\n\t if (parse_argument_types(fp, &argtypes,\n\t\t\t\t\t\tvim9script && varargs) == FAIL)\n\t\tgoto errret;\n\t if (ret_type != NULL)\n\t {\n\t\tfp->uf_ret_type = parse_type(&ret_type,\n\t\t\t\t\t\t &fp->uf_type_list, TRUE);\n\t\tif (fp->uf_ret_type == NULL)\n\t\t goto errret;\n\t }\n\t else\n\t\tfp->uf_ret_type = &t_unknown;\n\t}\n\n\tfp->uf_lines = newlines;\n\tif (current_funccal != NULL && eval_lavars)\n\t{\n\t flags |= FC_CLOSURE;\n\t if (register_closure(fp) == FAIL)\n\t\tgoto errret;\n\t}\n\n#ifdef FEAT_PROFILE\n\tif (prof_def_func())\n\t func_do_profile(fp);\n#endif\n\tif (sandbox)\n\t flags |= FC_SANDBOX;\n\t// In legacy script a lambda can be called with more args than\n\t// uf_args.ga_len. In Vim9 script \"...name\" has to be used.\n\tfp->uf_varargs = !vim9script || varargs;\n\tfp->uf_flags = flags;\n\tfp->uf_calls = 0;\n\tfp->uf_script_ctx = current_sctx;\n\t// Use the line number of the arguments.\n\tfp->uf_script_ctx.sc_lnum += start_lnum;\n\n\tfunction_using_block_scopes(fp, evalarg->eval_cstack);\n\n\tpt->pt_func = fp;\n\tpt->pt_refcount = 1;\n\trettv->vval.v_partial = pt;\n\trettv->v_type = VAR_PARTIAL;\n\n\thash_add(&func_hashtab, UF2HIKEY(fp));\n }\n\ntheend:\n eval_lavars_used = old_eval_lavars;\n if (evalarg != NULL && evalarg->eval_tofree == NULL)\n\tevalarg->eval_tofree = tofree1;\n else\n\tvim_free(tofree1);\n vim_free(tofree2);\n if (types_optional)\n\tga_clear_strings(&argtypes);\n\n return OK;\n\nerrret:\n ga_clear_strings(&newargs);\n ga_clear_strings(&newlines);\n ga_clear_strings(&default_args);\n if (types_optional)\n {\n\tga_clear_strings(&argtypes);\n\tif (fp != NULL)\n\t vim_free(fp->uf_arg_types);\n }\n vim_free(fp);\n vim_free(pt);\n if (evalarg != NULL && evalarg->eval_tofree == NULL)\n\tevalarg->eval_tofree = tofree1;\n else\n\tvim_free(tofree1);\n vim_free(tofree2);\n eval_lavars_used = old_eval_lavars;\n return FAIL;\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 void cgroup_pressure_release(struct kernfs_open_file *of)\n{\n\tstruct cgroup_file_ctx *ctx = of->priv;\n\n\tpsi_trigger_replace(&ctx->psi.trigger, NULL);\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 runtime_status_show(struct device *dev,\n\t\t\t\tstruct device_attribute *attr, char *buf)\n{\n\tconst char *p;\n\n\tif (dev->power.runtime_error) {\n\t\tp = \"error\\n\";\n\t} else if (dev->power.disable_depth) {\n\t\tp = \"unsupported\\n\";\n\t} else {\n\t\tswitch (dev->power.runtime_status) {\n\t\tcase RPM_SUSPENDED:\n\t\t\tp = \"suspended\\n\";\n\t\t\tbreak;\n\t\tcase RPM_SUSPENDING:\n\t\t\tp = \"suspending\\n\";\n\t\t\tbreak;\n\t\tcase RPM_RESUMING:\n\t\t\tp = \"resuming\\n\";\n\t\t\tbreak;\n\t\tcase RPM_ACTIVE:\n\t\t\tp = \"active\\n\";\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn -EIO;\n\t\t}\n\t}\n\treturn sprintf(buf, p);\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_tsx_async_abort(struct device *dev,\n\t\t\t\t\tstruct device_attribute *attr,\n\t\t\t\t\tchar *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 print_cpus_isolated(struct device *dev,\n\t\t\t\t struct device_attribute *attr, char *buf)\n{\n\tint n;\n\tcpumask_var_t isolated;\n\n\tif (!alloc_cpumask_var(&isolated, GFP_KERNEL))\n\t\treturn -ENOMEM;\n\n\tcpumask_andnot(isolated, cpu_possible_mask,\n\t\t housekeeping_cpumask(HK_FLAG_DOMAIN));\n\tn = sprintf(buf, \"%*pbl\\n\", cpumask_pr_args(isolated));\n\n\tfree_cpumask_var(isolated);\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 runtime_active_kids_show(struct device *dev,\n\t\t\t\t\tstruct device_attribute *attr,\n\t\t\t\t\tchar *buf)\n{\n\treturn sprintf(buf, \"%d\\n\", dev->power.ignore_children ?\n\t\t0 : atomic_read(&dev->power.child_count));\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 sync_state_only_show(struct device *dev,\n\t\t\t\t struct device_attribute *attr, char *buf)\n{\n\tstruct device_link *link = to_devlink(dev);\n\n\treturn sprintf(buf, \"%d\\n\", !!(link->flags & DL_FLAG_SYNC_STATE_ONLY));\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 driver_override_show(struct device *dev,\n\t\t\t\t struct device_attribute *attr, char *buf)\n{\n\tstruct platform_device *pdev = to_platform_device(dev);\n\tssize_t len;\n\n\tdevice_lock(dev);\n\tlen = sprintf(buf, \"%s\\n\", pdev->driver_override);\n\tdevice_unlock(dev);\n\treturn len;\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 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 | __GFP_ZERO);\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-362'], 'message': 'af_key: Do not call xfrm_probe_algs in parallel\n\nWhen namespace support was added to xfrm/afkey, it caused the\npreviously single-threaded call to xfrm_probe_algs to become\nmulti-threaded. This is buggy and needs to be fixed with a mutex.\n\nReported-by: Abhishek Shah \nFixes: 283bc9f35bbb (\"xfrm: Namespacify xfrm state/policy locks\")\nSigned-off-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: void LibRaw::parseSonySR2(uchar *cbuf_SR2, unsigned SR2SubIFDOffset,\n unsigned SR2SubIFDLength, unsigned dng_writer)\n{\n unsigned c;\n unsigned entries, tag_id, tag_type, tag_datalen;\n INT64 sr2_offset, tag_offset, tag_data, tag_dataoffset;\n int TagProcessed;\n int tag_dataunitlen;\n float num;\n int i;\n int WBCTC_count;\n entries = sget2(cbuf_SR2);\n if (entries > 1000)\n return;\n tag_offset = 2;\n WBCTC_count = 0;\n while (entries--) {\n if (tiff_sget (SR2SubIFDOffset, cbuf_SR2, SR2SubIFDLength,\n &tag_offset, &tag_id, &tag_type, &tag_dataoffset,\n &tag_datalen, &tag_dataunitlen) == 0) {\n TagProcessed = 0;\n if (dng_writer == nonDNG) {\n switch (tag_id) {\n case 0x7300:\n FORC4 cblack[c] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n TagProcessed = 1;\n break;\n case 0x7303:\n FORC4 cam_mul[GRBG_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n TagProcessed = 1;\n break;\n case 0x7310:\n FORC4 cblack[RGGB_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n i = cblack[3];\n FORC3 if (i > cblack[c]) i = cblack[c];\n FORC4 cblack[c] -= i;\n black = i;\n TagProcessed = 1;\n break;\n case 0x7313:\n FORC4 cam_mul[RGGB_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n TagProcessed = 1;\n break;\n case 0x74a0:\n ilm.MaxAp4MaxFocal = sgetreal(tag_type, cbuf_SR2 + tag_dataoffset);\n TagProcessed = 1;\n break;\n case 0x74a1:\n ilm.MaxAp4MinFocal = sgetreal(tag_type, cbuf_SR2 + tag_dataoffset);\n TagProcessed = 1;\n break;\n case 0x74a2:\n ilm.MaxFocal = sgetreal(tag_type, cbuf_SR2 + tag_dataoffset);\n TagProcessed = 1;\n break;\n case 0x74a3:\n ilm.MinFocal = sgetreal(tag_type, cbuf_SR2 + tag_dataoffset);\n TagProcessed = 1;\n break;\n case 0x7800:\n for (i = 0; i < 3; i++)\n {\n num = 0.0;\n for (c = 0; c < 3; c++)\n {\n imgdata.color.ccm[i][c] =\n (float)((short)sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * (i * 3 + c)));\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 TagProcessed = 1;\n break;\n case 0x787f:\n if (tag_datalen == 3)\n {\n FORC3 imgdata.color.linear_max[c] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n imgdata.color.linear_max[3] = imgdata.color.linear_max[1];\n }\n else if (tag_datalen == 1)\n {\n imgdata.color.linear_max[0] = imgdata.color.linear_max[1] =\n imgdata.color.linear_max[2] = imgdata.color.linear_max[3] =\n sget2(cbuf_SR2 + tag_dataoffset);\n }\n TagProcessed = 1;\n break;\n }\n }\n\n if (!TagProcessed) {\n if ((tag_id >= 0x7480) && (tag_id <= 0x7486)) {\n i = tag_id - 0x7480;\n if (Sony_SR2_wb_list[i] > 255) {\n icWBCCTC[WBCTC_count][0] = Sony_SR2_wb_list[i];\n FORC3 icWBCCTC[WBCTC_count][c + 1] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n icWBCCTC[WBCTC_count][4] = icWBCCTC[WBCTC_count][2];\n WBCTC_count++;\n } else {\n FORC3 icWBC[Sony_SR2_wb_list[i]][c] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n icWBC[Sony_SR2_wb_list[i]][3] = icWBC[Sony_SR2_wb_list[i]][1];\n }\n } else if ((tag_id >= 0x7820) && (tag_id <= 0x782d)) {\n i = tag_id - 0x7820;\n if (Sony_SR2_wb_list1[i] > 255) {\n icWBCCTC[WBCTC_count][0] = Sony_SR2_wb_list1[i];\n FORC3 icWBCCTC[WBCTC_count][c + 1] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n icWBCCTC[WBCTC_count][4] = icWBCCTC[WBCTC_count][2];\n if (Sony_SR2_wb_list1[i] == 3200) {\n FORC3 icWBC[LIBRAW_WBI_StudioTungsten][c] = icWBCCTC[WBCTC_count][c + 1];\n icWBC[LIBRAW_WBI_StudioTungsten][3] = icWBC[LIBRAW_WBI_StudioTungsten][1];\n }\n WBCTC_count++;\n } else {\n FORC3 icWBC[Sony_SR2_wb_list1[i]][c] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n icWBC[Sony_SR2_wb_list1[i]][3] = icWBC[Sony_SR2_wb_list1[i]][1];\n }\n } else if (tag_id == 0x7302) {\n FORC4 icWBC[LIBRAW_WBI_Auto][GRBG_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n } else if (tag_id == 0x7312) {\n FORC4 icWBC[LIBRAW_WBI_Auto][RGGB_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n }\n }\n }\n }\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: h2v2_merged_upsample_565D_internal(j_decompress_ptr cinfo,\n 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 outptr0, outptr1;\n JSAMPROW inptr00, inptr01, 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 JLONG d0 = dither_matrix[cinfo->output_scanline & DITHER_MASK];\n JLONG d1 = dither_matrix[(cinfo->output_scanline + 1) & DITHER_MASK];\n unsigned int r, g, b;\n JLONG rgb;\n SHIFT_TEMPS\n\n inptr00 = input_buf[0][in_row_group_ctr * 2];\n inptr01 = input_buf[0][in_row_group_ctr * 2 + 1];\n inptr1 = input_buf[1][in_row_group_ctr];\n inptr2 = input_buf[2][in_row_group_ctr];\n outptr0 = output_buf[0];\n outptr1 = output_buf[1];\n\n /* Loop for each group 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 4 Y values and emit 4 pixels */\n y = GETJSAMPLE(*inptr00++);\n r = range_limit[DITHER_565_R(y + cred, d0)];\n g = range_limit[DITHER_565_G(y + cgreen, d0)];\n b = range_limit[DITHER_565_B(y + cblue, d0)];\n d0 = DITHER_ROTATE(d0);\n rgb = PACK_SHORT_565(r, g, b);\n\n y = GETJSAMPLE(*inptr00++);\n r = range_limit[DITHER_565_R(y + cred, d0)];\n g = range_limit[DITHER_565_G(y + cgreen, d0)];\n b = range_limit[DITHER_565_B(y + cblue, d0)];\n d0 = DITHER_ROTATE(d0);\n rgb = PACK_TWO_PIXELS(rgb, PACK_SHORT_565(r, g, b));\n\n WRITE_TWO_PIXELS(outptr0, rgb);\n outptr0 += 4;\n\n y = GETJSAMPLE(*inptr01++);\n r = range_limit[DITHER_565_R(y + cred, d1)];\n g = range_limit[DITHER_565_G(y + cgreen, d1)];\n b = range_limit[DITHER_565_B(y + cblue, d1)];\n d1 = DITHER_ROTATE(d1);\n rgb = PACK_SHORT_565(r, g, b);\n\n y = GETJSAMPLE(*inptr01++);\n r = range_limit[DITHER_565_R(y + cred, d1)];\n g = range_limit[DITHER_565_G(y + cgreen, d1)];\n b = range_limit[DITHER_565_B(y + cblue, d1)];\n d1 = DITHER_ROTATE(d1);\n rgb = PACK_TWO_PIXELS(rgb, PACK_SHORT_565(r, g, b));\n\n WRITE_TWO_PIXELS(outptr1, rgb);\n outptr1 += 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\n y = GETJSAMPLE(*inptr00);\n r = range_limit[DITHER_565_R(y + cred, d0)];\n g = range_limit[DITHER_565_G(y + cgreen, d0)];\n b = range_limit[DITHER_565_B(y + cblue, d0)];\n rgb = PACK_SHORT_565(r, g, b);\n *(INT16 *)outptr0 = (INT16)rgb;\n\n y = GETJSAMPLE(*inptr01);\n r = range_limit[DITHER_565_R(y + cred, d1)];\n g = range_limit[DITHER_565_G(y + cgreen, d1)];\n b = range_limit[DITHER_565_B(y + cblue, d1)];\n rgb = PACK_SHORT_565(r, g, b);\n *(INT16 *)outptr1 = (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: static void ExportIndexQuantum(const Image *image,QuantumInfo *quantum_info,\n const MagickSizeType number_pixels,const PixelPacket *magick_restrict p,\n const IndexPacket *magick_restrict indexes,unsigned char *magick_restrict q,\n ExceptionInfo *exception)\n{\n ssize_t\n x;\n\n ssize_t\n bit;\n\n if (image->storage_class != PseudoClass)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),ImageError,\n \"ColormappedImageRequired\",\"`%s'\",image->filename);\n return;\n }\n switch (quantum_info->depth)\n {\n case 1:\n {\n unsigned char\n pixel;\n\n for (x=((ssize_t) number_pixels-7); x > 0; x-=8)\n {\n pixel=(unsigned char) *indexes++;\n *q=((pixel & 0x01) << 7);\n pixel=(unsigned char) *indexes++;\n *q|=((pixel & 0x01) << 6);\n pixel=(unsigned char) *indexes++;\n *q|=((pixel & 0x01) << 5);\n pixel=(unsigned char) *indexes++;\n *q|=((pixel & 0x01) << 4);\n pixel=(unsigned char) *indexes++;\n *q|=((pixel & 0x01) << 3);\n pixel=(unsigned char) *indexes++;\n *q|=((pixel & 0x01) << 2);\n pixel=(unsigned char) *indexes++;\n *q|=((pixel & 0x01) << 1);\n pixel=(unsigned char) *indexes++;\n *q|=((pixel & 0x01) << 0);\n q++;\n }\n if ((number_pixels % 8) != 0)\n {\n *q='\\0';\n for (bit=7; bit >= (ssize_t) (8-(number_pixels % 8)); bit--)\n {\n pixel=(unsigned char) *indexes++;\n *q|=((pixel & 0x01) << (unsigned char) bit);\n }\n q++;\n }\n break;\n }\n case 4:\n {\n unsigned char\n pixel;\n\n for (x=0; x < (ssize_t) (number_pixels-1) ; x+=2)\n {\n pixel=(unsigned char) *indexes++;\n *q=((pixel & 0xf) << 4);\n pixel=(unsigned char) *indexes++;\n *q|=((pixel & 0xf) << 0);\n q++;\n }\n if ((number_pixels % 2) != 0)\n {\n pixel=(unsigned char) *indexes++;\n *q=((pixel & 0xf) << 4);\n q++;\n }\n break;\n }\n case 8:\n {\n for (x=0; x < (ssize_t) number_pixels; x++)\n {\n q=PopCharPixel((unsigned char) GetPixelIndex(indexes+x),q);\n q+=quantum_info->pad;\n }\n break;\n }\n case 16:\n {\n if (quantum_info->format == FloatingPointQuantumFormat)\n {\n for (x=0; x < (ssize_t) number_pixels; x++)\n {\n q=PopShortPixel(quantum_info->endian,SinglePrecisionToHalf(QuantumScale*\n GetPixelIndex(indexes+x)),q);\n q+=quantum_info->pad;\n }\n break;\n }\n for (x=0; x < (ssize_t) number_pixels; x++)\n {\n q=PopShortPixel(quantum_info->endian,(unsigned short) GetPixelIndex(indexes+x),q);\n q+=quantum_info->pad;\n }\n break;\n }\n case 32:\n {\n if (quantum_info->format == FloatingPointQuantumFormat)\n {\n for (x=0; x < (ssize_t) number_pixels; x++)\n {\n q=PopFloatPixel(quantum_info,(float) GetPixelIndex(indexes+x),q);\n p++;\n q+=quantum_info->pad;\n }\n break;\n }\n for (x=0; x < (ssize_t) number_pixels; x++)\n {\n q=PopLongPixel(quantum_info->endian,(unsigned int) GetPixelIndex(indexes+x),q);\n q+=quantum_info->pad;\n }\n break;\n }\n case 64:\n {\n if (quantum_info->format == FloatingPointQuantumFormat)\n {\n for (x=0; x < (ssize_t) number_pixels; x++)\n {\n q=PopDoublePixel(quantum_info,(double) GetPixelIndex(indexes+x),\n q);\n p++;\n q+=quantum_info->pad;\n }\n break;\n }\n }\n default:\n {\n for (x=0; x < (ssize_t) number_pixels; x++)\n {\n q=PopQuantumPixel(quantum_info,\n GetPixelIndex(indexes+x),q);\n p++;\n q+=quantum_info->pad;\n }\n break;\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'https://github.com/ImageMagick/ImageMagick/pull/3083'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void svm_handle_exit_irqoff(struct kvm_vcpu *vcpu)\n{\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 pyc_object *get_complex_object(RzBinPycObj *pyc, RzBuffer *buffer) {\n\tpyc_object *ret = NULL;\n\tbool error = false;\n\tut32 size = 0;\n\tut32 n1 = 0;\n\tut32 n2 = 0;\n\n\tret = RZ_NEW0(pyc_object);\n\tif (!ret) {\n\t\treturn NULL;\n\t}\n\n\tif ((pyc->magic_int & 0xffff) <= 62061) {\n\t\tn1 = get_ut8(buffer, &error);\n\t} else {\n\t\tn1 = get_st32(buffer, &error);\n\t}\n\tif (error) {\n\t\tfree(ret);\n\t\treturn NULL;\n\t}\n\tut8 *s1 = malloc(n1 + 1);\n\tif (!s1) {\n\t\treturn NULL;\n\t}\n\t/* object contain string representation of the number */\n\tsize = rz_buf_read(buffer, s1, n1);\n\tif (size != n1) {\n\t\tRZ_FREE(s1);\n\t\tRZ_FREE(ret);\n\t\treturn NULL;\n\t}\n\ts1[n1] = '\\0';\n\n\tif ((pyc->magic_int & 0xffff) <= 62061) {\n\t\tn2 = get_ut8(buffer, &error);\n\t} else\n\t\tn2 = get_st32(buffer, &error);\n\tif (error) {\n\t\treturn NULL;\n\t}\n\tut8 *s2 = malloc(n2 + 1);\n\tif (!s2) {\n\t\treturn NULL;\n\t}\n\t/* object contain string representation of the number */\n\tsize = rz_buf_read(buffer, s2, n2);\n\tif (size != n2) {\n\t\tRZ_FREE(s1);\n\t\tRZ_FREE(s2);\n\t\tRZ_FREE(ret);\n\t\treturn NULL;\n\t}\n\ts2[n2] = '\\0';\n\n\tret->type = TYPE_COMPLEX;\n\tret->data = rz_str_newf(\"%s+%sj\", s1, s2);\n\tRZ_FREE(s1);\n\tRZ_FREE(s2);\n\tif (!ret->data) {\n\t\tRZ_FREE(ret);\n\t\treturn NULL;\n\t}\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'fix #2963 - oob write (1 byte) in pyc/marshal.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 RzList *symbols(RzBinFile *bf) {\n\tif (!bf) {\n\t\treturn NULL;\n\t}\n\tLuacBinInfo *bin_info_obj = GET_INTERNAL_BIN_INFO_OBJ(bf);\n\tif (!bin_info_obj) {\n\t\treturn NULL;\n\t}\n\n\treturn bin_info_obj->symbol_list;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-787'], 'message': 'Fix oob read on _luac_build_info and luac memleaks'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bgp_auth_parse (struct peer *peer, u_char *pnt, size_t length)\n{\n bgp_notify_send (peer, \n\t\t BGP_NOTIFY_OPEN_ERR, \n\t\t BGP_NOTIFY_OPEN_AUTH_FAILURE); \n return -1;\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: static int bgp_capability_msg_parse(struct peer *peer, uint8_t *pnt,\n\t\t\t\t bgp_size_t length)\n{\n\tuint8_t *end;\n\tstruct capability_mp_data mpc;\n\tstruct capability_header *hdr;\n\tuint8_t action;\n\tiana_afi_t pkt_afi;\n\tafi_t afi;\n\tiana_safi_t pkt_safi;\n\tsafi_t safi;\n\n\tend = pnt + length;\n\n\twhile (pnt < end) {\n\t\t/* We need at least action, capability code and capability\n\t\t * length. */\n\t\tif (pnt + 3 > end) {\n\t\t\tzlog_info(\"%s Capability length error\", peer->host);\n\t\t\tbgp_notify_send(peer, BGP_NOTIFY_CEASE,\n\t\t\t\t\tBGP_NOTIFY_SUBCODE_UNSPECIFIC);\n\t\t\treturn BGP_Stop;\n\t\t}\n\t\taction = *pnt;\n\t\thdr = (struct capability_header *)(pnt + 1);\n\n\t\t/* Action value check. */\n\t\tif (action != CAPABILITY_ACTION_SET\n\t\t && action != CAPABILITY_ACTION_UNSET) {\n\t\t\tzlog_info(\"%s Capability Action Value error %d\",\n\t\t\t\t peer->host, action);\n\t\t\tbgp_notify_send(peer, BGP_NOTIFY_CEASE,\n\t\t\t\t\tBGP_NOTIFY_SUBCODE_UNSPECIFIC);\n\t\t\treturn BGP_Stop;\n\t\t}\n\n\t\tif (bgp_debug_neighbor_events(peer))\n\t\t\tzlog_debug(\n\t\t\t\t\"%s CAPABILITY has action: %d, code: %u, length %u\",\n\t\t\t\tpeer->host, action, hdr->code, hdr->length);\n\n\t\t/* Capability length check. */\n\t\tif ((pnt + hdr->length + 3) > end) {\n\t\t\tzlog_info(\"%s Capability length error\", peer->host);\n\t\t\tbgp_notify_send(peer, BGP_NOTIFY_CEASE,\n\t\t\t\t\tBGP_NOTIFY_SUBCODE_UNSPECIFIC);\n\t\t\treturn BGP_Stop;\n\t\t}\n\n\t\t/* Fetch structure to the byte stream. */\n\t\tmemcpy(&mpc, pnt + 3, sizeof(struct capability_mp_data));\n\t\tpnt += hdr->length + 3;\n\n\t\t/* We know MP Capability Code. */\n\t\tif (hdr->code == CAPABILITY_CODE_MP) {\n\t\t\tpkt_afi = ntohs(mpc.afi);\n\t\t\tpkt_safi = mpc.safi;\n\n\t\t\t/* Ignore capability when override-capability is set. */\n\t\t\tif (CHECK_FLAG(peer->flags,\n\t\t\t\t PEER_FLAG_OVERRIDE_CAPABILITY))\n\t\t\t\tcontinue;\n\n\t\t\t/* Convert AFI, SAFI to internal values. */\n\t\t\tif (bgp_map_afi_safi_iana2int(pkt_afi, pkt_safi, &afi,\n\t\t\t\t\t\t &safi)) {\n\t\t\t\tif (bgp_debug_neighbor_events(peer))\n\t\t\t\t\tzlog_debug(\n\t\t\t\t\t\t\"%s Dynamic Capability MP_EXT afi/safi invalid (%s/%s)\",\n\t\t\t\t\t\tpeer->host,\n\t\t\t\t\t\tiana_afi2str(pkt_afi),\n\t\t\t\t\t\tiana_safi2str(pkt_safi));\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/* Address family check. */\n\t\t\tif (bgp_debug_neighbor_events(peer))\n\t\t\t\tzlog_debug(\n\t\t\t\t\t\"%s CAPABILITY has %s MP_EXT CAP for afi/safi: %s/%s\",\n\t\t\t\t\tpeer->host,\n\t\t\t\t\taction == CAPABILITY_ACTION_SET\n\t\t\t\t\t\t? \"Advertising\"\n\t\t\t\t\t\t: \"Removing\",\n\t\t\t\t\tiana_afi2str(pkt_afi),\n\t\t\t\t\tiana_safi2str(pkt_safi));\n\n\t\t\tif (action == CAPABILITY_ACTION_SET) {\n\t\t\t\tpeer->afc_recv[afi][safi] = 1;\n\t\t\t\tif (peer->afc[afi][safi]) {\n\t\t\t\t\tpeer->afc_nego[afi][safi] = 1;\n\t\t\t\t\tbgp_announce_route(peer, afi, safi,\n\t\t\t\t\t\t\t false);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tpeer->afc_recv[afi][safi] = 0;\n\t\t\t\tpeer->afc_nego[afi][safi] = 0;\n\n\t\t\t\tif (peer_active_nego(peer))\n\t\t\t\t\tbgp_clear_route(peer, afi, safi);\n\t\t\t\telse\n\t\t\t\t\treturn BGP_Stop;\n\t\t\t}\n\t\t} else {\n\t\t\tflog_warn(\n\t\t\t\tEC_BGP_UNRECOGNIZED_CAPABILITY,\n\t\t\t\t\"%s unrecognized capability code: %d - ignored\",\n\t\t\t\tpeer->host, hdr->code);\n\t\t}\n\t}\n\n\t/* No FSM action necessary */\n\treturn BGP_PACKET_NOOP;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'bgpd: Make sure hdr length is at a minimum of what is expected\n\nEnsure that if the capability length specified is enough data.\n\nSigned-off-by: Donald Sharp '" }, { "text": "[INST] Given the following code containing errors, provide Common 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_finally(exarg_T *eap)\n{\n int\t\tidx;\n int\t\tskip = FALSE;\n int\t\tpending = CSTP_NONE;\n cstack_T\t*cstack = eap->cstack;\n\n if (cmdmod_error(FALSE))\n\treturn;\n\n if (cstack->cs_trylevel <= 0 || cstack->cs_idx < 0)\n\teap->errmsg = _(e_finally_without_try);\n else\n {\n\tif (!(cstack->cs_flags[cstack->cs_idx] & CSF_TRY))\n\t{\n\t eap->errmsg = get_end_emsg(cstack);\n\t for (idx = cstack->cs_idx - 1; idx > 0; --idx)\n\t\tif (cstack->cs_flags[idx] & CSF_TRY)\n\t\t break;\n\t // Make this error pending, so that the commands in the following\n\t // finally clause can be executed. This overrules also a pending\n\t // \":continue\", \":break\", \":return\", or \":finish\".\n\t pending = CSTP_ERROR;\n\t}\n\telse\n\t idx = cstack->cs_idx;\n\n\tif (cstack->cs_flags[idx] & CSF_FINALLY)\n\t{\n\t // Give up for a multiple \":finally\" and ignore it.\n\t eap->errmsg = _(e_multiple_finally);\n\t return;\n\t}\n\trewind_conditionals(cstack, idx, CSF_WHILE | CSF_FOR,\n\t\t\t\t\t\t &cstack->cs_looplevel);\n\n\t/*\n\t * Don't do something when the corresponding try block never got active\n\t * (because of an inactive surrounding conditional or after an error or\n\t * interrupt or throw) or for a \":finally\" without \":try\" or a multiple\n\t * \":finally\". After every other error (did_emsg or the conditional\n\t * errors detected above) or after an interrupt (got_int) or an\n\t * exception (did_throw), the finally clause must be executed.\n\t */\n\tskip = !(cstack->cs_flags[cstack->cs_idx] & CSF_TRUE);\n\n\tif (!skip)\n\t{\n\t // When debugging or a breakpoint was encountered, display the\n\t // debug prompt (if not already done). The user then knows that the\n\t // finally clause is executed.\n\t if (dbg_check_skipped(eap))\n\t {\n\t\t// Handle a \">quit\" debug command as if an interrupt had\n\t\t// occurred before the \":finally\". That is, discard the\n\t\t// original exception and replace it by an interrupt\n\t\t// exception.\n\t\t(void)do_intthrow(cstack);\n\t }\n\n\t /*\n\t * If there is a preceding catch clause and it caught the exception,\n\t * finish the exception now. This happens also after errors except\n\t * when this is a multiple \":finally\" or one not within a \":try\".\n\t * After an error or interrupt, this also discards a pending\n\t * \":continue\", \":break\", \":finish\", or \":return\" from the preceding\n\t * try block or catch clause.\n\t */\n\t cleanup_conditionals(cstack, CSF_TRY, FALSE);\n\n\t if (cstack->cs_idx >= 0\n\t\t\t && (cstack->cs_flags[cstack->cs_idx] & CSF_TRY))\n\t {\n\t\t// Variables declared in the previous block can no longer be\n\t\t// used.\n\t\tleave_block(cstack);\n\t\tenter_block(cstack);\n\t }\n\n\t /*\n\t * Make did_emsg, got_int, did_throw pending. If set, they overrule\n\t * a pending \":continue\", \":break\", \":return\", or \":finish\". Then\n\t * we have particularly to discard a pending return value (as done\n\t * by the call to cleanup_conditionals() above when did_emsg or\n\t * got_int is set). The pending values are restored by the\n\t * \":endtry\", except if there is a new error, interrupt, exception,\n\t * \":continue\", \":break\", \":return\", or \":finish\" in the following\n\t * finally clause. A missing \":endwhile\", \":endfor\" or \":endif\"\n\t * detected here is treated as if did_emsg and did_throw had\n\t * already been set, respectively in case that the error is not\n\t * converted to an exception, did_throw had already been unset.\n\t * We must not set did_emsg here since that would suppress the\n\t * error message.\n\t */\n\t if (pending == CSTP_ERROR || did_emsg || got_int || did_throw)\n\t {\n\t\tif (cstack->cs_pending[cstack->cs_idx] == CSTP_RETURN)\n\t\t{\n\t\t report_discard_pending(CSTP_RETURN,\n\t\t\t\t\t cstack->cs_rettv[cstack->cs_idx]);\n\t\t discard_pending_return(cstack->cs_rettv[cstack->cs_idx]);\n\t\t}\n\t\tif (pending == CSTP_ERROR && !did_emsg)\n\t\t pending |= (THROW_ON_ERROR) ? CSTP_THROW : 0;\n\t\telse\n\t\t pending |= did_throw ? CSTP_THROW : 0;\n\t\tpending |= did_emsg ? CSTP_ERROR : 0;\n\t\tpending |= got_int ? CSTP_INTERRUPT : 0;\n\t\tcstack->cs_pending[cstack->cs_idx] = pending;\n\n\t\t// It's mandatory that the current exception is stored in the\n\t\t// cstack so that it can be rethrown at the \":endtry\" or be\n\t\t// discarded if the finally clause is left by a \":continue\",\n\t\t// \":break\", \":return\", \":finish\", error, interrupt, or another\n\t\t// exception. When emsg() is called for a missing \":endif\" or\n\t\t// a missing \":endwhile\"/\":endfor\" detected here, the\n\t\t// exception will be discarded.\n\t\tif (did_throw && cstack->cs_exception[cstack->cs_idx]\n\t\t\t\t\t\t\t != current_exception)\n\t\t internal_error(\"ex_finally()\");\n\t }\n\n\t /*\n\t * Set CSL_HAD_FINA, so do_cmdline() will reset did_emsg,\n\t * got_int, and did_throw and make the finally clause active.\n\t * This will happen after emsg() has been called for a missing\n\t * \":endif\" or a missing \":endwhile\"/\":endfor\" detected here, so\n\t * that the following finally clause will be executed even then.\n\t */\n\t cstack->cs_lflags |= CSL_HAD_FINA;\n\t}\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'patch 9.0.0577: buffer underflow with unexpected :finally\n\nProblem: Buffer underflow with unexpected :finally.\nSolution: Check CSF_TRY can be found.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int __io_sync_cancel(struct io_uring_task *tctx,\n\t\t\t struct io_cancel_data *cd, int fd)\n{\n\tstruct io_ring_ctx *ctx = cd->ctx;\n\n\t/* fixed must be grabbed every time since we drop the uring_lock */\n\tif ((cd->flags & IORING_ASYNC_CANCEL_FD) &&\n\t (cd->flags & IORING_ASYNC_CANCEL_FD_FIXED)) {\n\t\tunsigned long file_ptr;\n\n\t\tif (unlikely(fd > ctx->nr_user_files))\n\t\t\treturn -EBADF;\n\t\tfd = array_index_nospec(fd, ctx->nr_user_files);\n\t\tfile_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;\n\t\tcd->file = (struct file *) (file_ptr & FFS_MASK);\n\t\tif (!cd->file)\n\t\t\treturn -EBADF;\n\t}\n\n\treturn __io_async_cancel(cd, tctx, 0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-193'], 'message': 'io_uring: fix off-by-one in sync cancelation file check\n\nThe passed in index should be validated against the number of registered\nfiles we have, it needs to be smaller than the index value to avoid going\none beyond the end.\n\nFixes: 78a861b94959 (\"io_uring: add sync cancelation API through io_uring_register()\")\nReported-by: Luo Likang \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: unsigned int get_random_int(void)\n{\n\t/*\n\t * Use IP's RNG. It suits our purpose perfectly: it re-keys itself\n\t * every second, from the entropy pool (and thus creates a limited\n\t * drain on it), and uses halfMD4Transform within the second. We\n\t * also mix it with jiffies and the PID:\n\t */\n\treturn secure_ip_id((__force __be32)(current->pid + jiffies));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'random: make get_random_int() more random\n\nIt's a really simple patch that basically just open-codes the current\n\"secure_ip_id()\" call, but when open-coding it we now use a _static_\nhashing area, so that it gets updated every time.\n\nAnd to make sure somebody can't just start from the same original seed of\nall-zeroes, and then do the \"half_md4_transform()\" over and over until\nthey get the same sequence as the kernel has, each iteration also mixes in\nthe same old \"current->pid + jiffies\" we used - so we should now have a\nregular strong pseudo-number generator, but we also have one that doesn't\nhave a single seed.\n\nNote: the \"pid + jiffies\" is just meant to be a tiny tiny bit of noise. It\nhas no real meaning. It could be anything. I just picked the previous\nseed, it's just that now we keep the state in between calls and that will\nfeed into the next result, and that should make all the difference.\n\nI made that hash be a per-cpu data just to avoid cache-line ping-pong:\nhaving multiple CPU's write to the same data would be fine for randomness,\nand add yet another layer of chaos to it, but since get_random_int() is\nsupposed to be a fast interface I did it that way instead. I considered\nusing \"__raw_get_cpu_var()\" to avoid any preemption overhead while still\ngetting the hash be _mostly_ ping-pong free, but in the end good taste won\nout.\n\nSigned-off-by: Ingo Molnar \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int update_add_entry(struct libmnt_update *upd, struct libmnt_lock *lc)\n{\n\tFILE *f;\n\tint rc = 0, u_lc = -1;\n\n\tassert(upd);\n\tassert(upd->fs);\n\n\tDBG(UPDATE, mnt_debug_h(upd, \"%s: add entry\", upd->filename));\n\n\tif (lc)\n\t\tmnt_lock_file(lc);\n\telse if (upd->userspace_only)\n\t\tu_lc = utab_lock(upd->filename);\n\n\tf = fopen(upd->filename, \"a+\");\n\tif (f) {\n\t\trc = upd->userspace_only ? fprintf_utab_fs(f, upd->fs) :\n\t\t\t\t\t fprintf_mtab_fs(f, upd->fs);\n\t\tDBG(UPDATE, mnt_debug_h(upd, \"%s: add [rc=%d]\", upd->filename, rc));\n\t\tfclose(f);\n\t} else {\n\t\tDBG(UPDATE, mnt_debug_h(upd, \"%s: failed: %m\", upd->filename));\n\t\trc = -errno;\n\t}\n\tif (lc)\n\t\tmnt_unlock_file(lc);\n\telse if (u_lc != -1)\n\t\tutab_unlock(u_lc);\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: queryfree (struct dns_transmit *d)\n{\n if (!d->query)\n return;\n alloc_free (d->query);\n d->query = 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: getHTTPResponse(int s, int * size)\n{\n\tchar buf[2048];\n\tint n;\n\tint endofheaders = 0;\n\tint chunked = 0;\n\tint content_length = -1;\n\tunsigned int chunksize = 0;\n\tunsigned int bytestocopy = 0;\n\t/* buffers : */\n\tchar * header_buf;\n\tunsigned int header_buf_len = 2048;\n\tunsigned int header_buf_used = 0;\n\tchar * content_buf;\n\tunsigned int content_buf_len = 2048;\n\tunsigned int content_buf_used = 0;\n\tchar chunksize_buf[32];\n\tunsigned int chunksize_buf_index;\n\n\theader_buf = malloc(header_buf_len);\n\tcontent_buf = malloc(content_buf_len);\n\tchunksize_buf[0] = '\\0';\n\tchunksize_buf_index = 0;\n\n\twhile((n = receivedata(s, buf, 2048, 5000, NULL)) > 0)\n\t{\n\t\tif(endofheaders == 0)\n\t\t{\n\t\t\tint i;\n\t\t\tint linestart=0;\n\t\t\tint colon=0;\n\t\t\tint valuestart=0;\n\t\t\tif(header_buf_used + n > header_buf_len) {\n\t\t\t\theader_buf = realloc(header_buf, header_buf_used + n);\n\t\t\t\theader_buf_len = header_buf_used + n;\n\t\t\t}\n\t\t\tmemcpy(header_buf + header_buf_used, buf, n);\n\t\t\theader_buf_used += n;\n\t\t\t/* search for CR LF CR LF (end of headers)\n\t\t\t * recognize also LF LF */\n\t\t\ti = 0;\n\t\t\twhile(i < ((int)header_buf_used-1) && (endofheaders == 0)) {\n\t\t\t\tif(header_buf[i] == '\\r') {\n\t\t\t\t\ti++;\n\t\t\t\t\tif(header_buf[i] == '\\n') {\n\t\t\t\t\t\ti++;\n\t\t\t\t\t\tif(i < (int)header_buf_used && header_buf[i] == '\\r') {\n\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\tif(i < (int)header_buf_used && header_buf[i] == '\\n') {\n\t\t\t\t\t\t\t\tendofheaders = i+1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if(header_buf[i] == '\\n') {\n\t\t\t\t\ti++;\n\t\t\t\t\tif(header_buf[i] == '\\n') {\n\t\t\t\t\t\tendofheaders = i+1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\t\t\tif(endofheaders == 0)\n\t\t\t\tcontinue;\n\t\t\t/* parse header lines */\n\t\t\tfor(i = 0; i < endofheaders - 1; i++) {\n\t\t\t\tif(colon <= linestart && header_buf[i]==':')\n\t\t\t\t{\n\t\t\t\t\tcolon = i;\n\t\t\t\t\twhile(i < (endofheaders-1)\n\t\t\t\t\t && (header_buf[i+1] == ' ' || header_buf[i+1] == '\\t'))\n\t\t\t\t\t\ti++;\n\t\t\t\t\tvaluestart = i + 1;\n\t\t\t\t}\n\t\t\t\t/* detecting end of line */\n\t\t\t\telse if(header_buf[i]=='\\r' || header_buf[i]=='\\n')\n\t\t\t\t{\n\t\t\t\t\tif(colon > linestart && valuestart > colon)\n\t\t\t\t\t{\n#ifdef DEBUG\n\t\t\t\t\t\tprintf(\"header='%.*s', value='%.*s'\\n\",\n\t\t\t\t\t\t colon-linestart, header_buf+linestart,\n\t\t\t\t\t\t i-valuestart, header_buf+valuestart);\n#endif\n\t\t\t\t\t\tif(0==strncasecmp(header_buf+linestart, \"content-length\", colon-linestart))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontent_length = atoi(header_buf+valuestart);\n#ifdef DEBUG\n\t\t\t\t\t\t\tprintf(\"Content-Length: %d\\n\", content_length);\n#endif\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(0==strncasecmp(header_buf+linestart, \"transfer-encoding\", colon-linestart)\n\t\t\t\t\t\t && 0==strncasecmp(header_buf+valuestart, \"chunked\", 7))\n\t\t\t\t\t\t{\n#ifdef DEBUG\n\t\t\t\t\t\t\tprintf(\"chunked transfer-encoding!\\n\");\n#endif\n\t\t\t\t\t\t\tchunked = 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\twhile(header_buf[i]=='\\r' || header_buf[i] == '\\n')\n\t\t\t\t\t\ti++;\n\t\t\t\t\tlinestart = i;\n\t\t\t\t\tcolon = linestart;\n\t\t\t\t\tvaluestart = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\t/* copy the remaining of the received data back to buf */\n\t\t\tn = header_buf_used - endofheaders;\n\t\t\tmemcpy(buf, header_buf + endofheaders, n);\n\t\t\t/* if(headers) */\n\t\t}\n\t\tif(endofheaders)\n\t\t{\n\t\t\t/* content */\n\t\t\tif(chunked)\n\t\t\t{\n\t\t\t\tint i = 0;\n\t\t\t\twhile(i < n)\n\t\t\t\t{\n\t\t\t\t\tif(chunksize == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t/* reading chunk size */\n\t\t\t\t\t\tif(chunksize_buf_index == 0) {\n\t\t\t\t\t\t\t/* skipping any leading CR LF */\n\t\t\t\t\t\t\tif(i= '0'\n\t\t\t\t\t\t\t && chunksize_buf[j] <= '9')\n\t\t\t\t\t\t\t\tchunksize = (chunksize << 4) + (chunksize_buf[j] - '0');\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tchunksize = (chunksize << 4) + ((chunksize_buf[j] | 32) - 'a' + 10);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tchunksize_buf[0] = '\\0';\n\t\t\t\t\t\t\tchunksize_buf_index = 0;\n\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t/* not finished to get chunksize */\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n#ifdef DEBUG\n\t\t\t\t\t\tprintf(\"chunksize = %u (%x)\\n\", chunksize, chunksize);\n#endif\n\t\t\t\t\t\tif(chunksize == 0)\n\t\t\t\t\t\t{\n#ifdef DEBUG\n\t\t\t\t\t\t\tprintf(\"end of HTTP content - %d %d\\n\", i, n);\n\t\t\t\t\t\t\t/*printf(\"'%.*s'\\n\", n-i, buf+i);*/\n#endif\n\t\t\t\t\t\t\tgoto end_of_stream;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbytestocopy = ((int)chunksize < (n - i))?chunksize:(unsigned int)(n - i);\n\t\t\t\t\tif((content_buf_used + bytestocopy) > content_buf_len)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(content_length >= (int)(content_buf_used + bytestocopy)) {\n\t\t\t\t\t\t\tcontent_buf_len = content_length;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcontent_buf_len = content_buf_used + bytestocopy;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontent_buf = (char *)realloc((void *)content_buf,\n\t\t\t\t\t\t content_buf_len);\n\t\t\t\t\t}\n\t\t\t\t\tmemcpy(content_buf + content_buf_used, buf + i, bytestocopy);\n\t\t\t\t\tcontent_buf_used += bytestocopy;\n\t\t\t\t\ti += bytestocopy;\n\t\t\t\t\tchunksize -= bytestocopy;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t/* not chunked */\n\t\t\t\tif(content_length > 0\n\t\t\t\t && (int)(content_buf_used + n) > content_length) {\n\t\t\t\t\t/* skipping additional bytes */\n\t\t\t\t\tn = content_length - content_buf_used;\n\t\t\t\t}\n\t\t\t\tif(content_buf_used + n > content_buf_len)\n\t\t\t\t{\n\t\t\t\t\tif(content_length >= (int)(content_buf_used + n)) {\n\t\t\t\t\t\tcontent_buf_len = content_length;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcontent_buf_len = content_buf_used + n;\n\t\t\t\t\t}\n\t\t\t\t\tcontent_buf = (char *)realloc((void *)content_buf,\n\t\t\t\t\t content_buf_len);\n\t\t\t\t}\n\t\t\t\tmemcpy(content_buf + content_buf_used, buf, n);\n\t\t\t\tcontent_buf_used += n;\n\t\t\t}\n\t\t}\n\t\t/* use the Content-Length header value if available */\n\t\tif(content_length > 0 && (int)content_buf_used >= content_length)\n\t\t{\n#ifdef DEBUG\n\t\t\tprintf(\"End of HTTP content\\n\");\n#endif\n\t\t\tbreak;\n\t\t}\n\t}\nend_of_stream:\n\tfree(header_buf); header_buf = NULL;\n\t*size = content_buf_used;\n\tif(content_buf_used == 0)\n\t{\n\t\tfree(content_buf);\n\t\tcontent_buf = NULL;\n\t}\n\treturn content_buf;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-703'], 'message': 'miniwget.c: fixed potential buffer overrun'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int treo_attach(struct usb_serial *serial)\n{\n\tstruct usb_serial_port *swap_port;\n\n\t/* Only do this endpoint hack for the Handspring devices with\n\t * interrupt in endpoints, which for now are the Treo devices. */\n\tif (!((le16_to_cpu(serial->dev->descriptor.idVendor)\n\t\t\t\t\t\t== HANDSPRING_VENDOR_ID) ||\n\t\t(le16_to_cpu(serial->dev->descriptor.idVendor)\n\t\t\t\t\t\t== KYOCERA_VENDOR_ID)) ||\n\t\t(serial->num_interrupt_in == 0))\n\t\treturn 0;\n\n\t/*\n\t* It appears that Treos and Kyoceras want to use the\n\t* 1st bulk in endpoint to communicate with the 2nd bulk out endpoint,\n\t* so let's swap the 1st and 2nd bulk in and interrupt endpoints.\n\t* Note that swapping the bulk out endpoints would break lots of\n\t* apps that want to communicate on the second port.\n\t*/\n#define COPY_PORT(dest, src)\t\t\t\t\t\t\\\n\tdo { \\\n\t\tint i;\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\t\tfor (i = 0; i < ARRAY_SIZE(src->read_urbs); ++i) {\t\\\n\t\t\tdest->read_urbs[i] = src->read_urbs[i];\t\t\\\n\t\t\tdest->read_urbs[i]->context = dest;\t\t\\\n\t\t\tdest->bulk_in_buffers[i] = src->bulk_in_buffers[i]; \\\n\t\t}\t\t\t\t\t\t\t\\\n\t\tdest->read_urb = src->read_urb;\t\t\t\t\\\n\t\tdest->bulk_in_endpointAddress = src->bulk_in_endpointAddress;\\\n\t\tdest->bulk_in_buffer = src->bulk_in_buffer;\t\t\\\n\t\tdest->bulk_in_size = src->bulk_in_size;\t\t\t\\\n\t\tdest->interrupt_in_urb = src->interrupt_in_urb;\t\t\\\n\t\tdest->interrupt_in_urb->context = dest;\t\t\t\\\n\t\tdest->interrupt_in_endpointAddress = \\\n\t\t\t\t\tsrc->interrupt_in_endpointAddress;\\\n\t\tdest->interrupt_in_buffer = src->interrupt_in_buffer;\t\\\n\t} while (0);\n\n\tswap_port = kmalloc(sizeof(*swap_port), GFP_KERNEL);\n\tif (!swap_port)\n\t\treturn -ENOMEM;\n\tCOPY_PORT(swap_port, serial->port[0]);\n\tCOPY_PORT(serial->port[0], serial->port[1]);\n\tCOPY_PORT(serial->port[1], swap_port);\n\tkfree(swap_port);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-703'], 'message': 'USB: visor: fix null-deref at probe\n\nFix null-pointer dereference at probe should a (malicious) Treo device\nlack the expected endpoints.\n\nSpecifically, the Treo port-setup hack was dereferencing the bulk-in and\ninterrupt-in urbs without first making sure they had been allocated by\ncore.\n\nFixes: 1da177e4c3f4 (\"Linux-2.6.12-rc2\")\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: static int local_mknod(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 = mknodat(dirfd, name, SM_LOCAL_MODE_BITS | S_IFREG, 0);\n if (err == -1) {\n goto out;\n }\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 = mknodat(dirfd, name, credp->fc_mode, credp->fc_rdev);\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, 0);\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_delay(uint32_t delay_ms)\n{\n if (!kbd_timer) {\n kbd_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL, qemu_input_queue_process,\n &kbd_queue);\n }\n qemu_input_queue_delay(&kbd_queue, kbd_timer,\n delay_ms ? delay_ms : kbd_default_delay_ms);\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: void PersianCalendar::handleComputeFields(int32_t julianDay, UErrorCode &/*status*/) {\n int32_t year, month, dayOfMonth, dayOfYear;\n\n int32_t daysSinceEpoch = julianDay - PERSIAN_EPOCH;\n year = 1 + ClockMath::floorDivide(33 * daysSinceEpoch + 3, 12053);\n\n int32_t farvardin1 = 365 * (year - 1) + ClockMath::floorDivide(8 * year + 21, 33);\n dayOfYear = (daysSinceEpoch - farvardin1); // 0-based\n if (dayOfYear < 216) { // Compute 0-based month\n month = dayOfYear / 31;\n } else {\n month = (dayOfYear - 6) / 30;\n }\n dayOfMonth = dayOfYear - kPersianNumDays[month] + 1;\n ++dayOfYear; // Make it 1-based now\n\n internalSet(UCAL_ERA, 0);\n internalSet(UCAL_YEAR, year);\n internalSet(UCAL_EXTENDED_YEAR, year);\n internalSet(UCAL_MONTH, month);\n internalSet(UCAL_DAY_OF_MONTH, dayOfMonth);\n internalSet(UCAL_DAY_OF_YEAR, dayOfYear);\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 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\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: Guarantee sanitized buffer on pread failure\n\nAs mentioned in the previous patch, we left the state of the buffer\nundefined if we fail pread prior to attempting NBD_CMD_READ. Better\nis to tweak the generator to sanitize the buffer unconditionally, as a\nway of hardening against potential bugs in client applications that\nfail to check for errors, but which should not be leaking\nuninitialized data. In the process, we can document that the contents\nof buf are now merely unspecified, rather than undefined (valgrind\nwill no longer complain if you read buf, regardless of how nbd_pread\nfailed).\n\nSince always calling memset() can be a performance hit if the client\nalso sanitizes the buffer or is willing to take the audit risk, the\nnext patch will add a knob that allows the client to control when this\nhappens.\n\nThis patch causes changes to just the four APIs\nnbd_{aio_,}pread{,_structured}, with the generated lib/api.c changes\nlooking like:\n\n| --- lib/api.c.bak 2022-02-10 08:15:05.418371357 -0600\n| +++ lib/api.c 2022-02-10 08:15:13.224372023 -0600\n| @@ -2871,6 +2871,7 @@ nbd_pread (struct nbd_handle *h, void *b\n| debug (h, \"enter: buf= count=%zu offset=%\" PRIu64 \" flags=0x%x\", count, offset, flags);\n| }\n|\n| + memset (buf, 0, count);\n| if (unlikely (!pread_in_permitted_state (h))) {\n| ret = -1;\n| goto out;\n\nMessage-Id: <20220209220726.1902761-3-eblake@redhat.com>\nAcked-by: Laszlo Ersek \n[eblake: enhance commit message to show generated file diff]\nReviewed-by: Richard W.M. Jones \n\n(cherry picked from commit c7fbc71de54bf4e477011176197ad22950a02aa3)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void dwgCompressor::decompress18(duint8 *cbuf, duint8 *dbuf, duint64 csize, duint64 dsize){\n bufC = cbuf;\n sizeC = csize -2;\n DRW_DBG(\"dwgCompressor::decompress, last 2 bytes: \");\n DRW_DBGH(bufC[sizeC]);DRW_DBGH(bufC[sizeC+1]);DRW_DBG(\"\\n\");\n sizeC = csize;\n\n duint32 compBytes;\n duint32 compOffset;\n duint32 litCount;\n\n pos=0; //current position in compressed buffer\n duint32 rpos=0; //current position in resulting decompressed buffer\n litCount = litLength18();\n //copy first literal length\n for (duint32 i=0; i < litCount; ++i) {\n dbuf[rpos++] = bufC[pos++];\n }\n\n while (pos < csize && (rpos < dsize+1)){//rpos < dsize to prevent crash more robust are needed\n duint8 oc = bufC[pos++]; //next opcode\n if (oc == 0x10){\n compBytes = longCompressionOffset()+ 9;\n compOffset = twoByteOffset(&litCount) + 0x3FFF;\n if (litCount == 0)\n litCount= litLength18();\n } else if (oc > 0x11 && oc< 0x20){\n compBytes = (oc & 0x0F) + 2;\n compOffset = twoByteOffset(&litCount) + 0x3FFF;\n if (litCount == 0)\n litCount= litLength18();\n } else if (oc == 0x20){\n compBytes = longCompressionOffset() + 0x21;\n compOffset = twoByteOffset(&litCount);\n if (litCount == 0)\n litCount= litLength18();\n } else if (oc > 0x20 && oc< 0x40){\n compBytes = oc - 0x1E;\n compOffset = twoByteOffset(&litCount);\n if (litCount == 0)\n litCount= litLength18();\n } else if ( oc > 0x3F){\n compBytes = ((oc & 0xF0) >> 4) - 1;\n duint8 ll2 = bufC[pos++];\n compOffset = (ll2 << 2) | ((oc & 0x0C) >> 2);\n litCount = oc & 0x03;\n if (litCount < 1){\n litCount= litLength18();}\n } else if (oc == 0x11){\n DRW_DBG(\"dwgCompressor::decompress, end of input stream, Cpos: \");\n DRW_DBG(pos);DRW_DBG(\", Dpos: \");DRW_DBG(rpos);DRW_DBG(\"\\n\");\n return; //end of input stream\n } else { //ll < 0x10\n DRW_DBG(\"WARNING dwgCompressor::decompress, failed, illegal char, Cpos: \");\n DRW_DBG(pos);DRW_DBG(\", Dpos: \");DRW_DBG(rpos);DRW_DBG(\"\\n\");\n return; //fails, not valid\n }\n //copy \"compressed data\", if size allows\n if (dsize \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-191'], 'message': 'fixed out-of-bounds write vulnerability CVE-2021-21898\n\nas reported in TALOS-2021-1349 / CVE-2021-21898,\ndwgCompressor::decompress18() could be abused with a malformed DWG file\nto force out-of-bounds write and possibly lead to malicious code\nexecution.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void dwgCompressor::readInstructions21(duint8 *cbuf, duint32 *si, duint8 *oc, duint32 *so, duint32 *l){\n duint32 length;\n duint32 srcIndex = *si;\n duint32 sourceOffset;\n unsigned char opCode = *oc;\n switch ((opCode >> 4)) {\n case 0:\n length = (opCode & 0xf) + 0x13;\n sourceOffset = cbuf[srcIndex++];\n opCode = cbuf[srcIndex++];\n length = ((opCode >> 3) & 0x10) + length;\n sourceOffset = ((opCode & 0x78) << 5) + 1 + sourceOffset;\n break;\n case 1:\n length = (opCode & 0xf) + 3;\n sourceOffset = cbuf[srcIndex++];\n opCode = cbuf[srcIndex++];\n sourceOffset = ((opCode & 0xf8) << 5) + 1 + sourceOffset;\n break;\n case 2:\n sourceOffset = cbuf[srcIndex++];\n sourceOffset = ((cbuf[srcIndex++] << 8) & 0xff00) | sourceOffset;\n length = opCode & 7;\n if ((opCode & 8) == 0) {\n opCode = cbuf[srcIndex++];\n length = (opCode & 0xf8) + length;\n } else {\n sourceOffset++;\n length = (cbuf[srcIndex++] << 3) + length;\n opCode = cbuf[srcIndex++];\n length = (((opCode & 0xf8) << 8) + length) + 0x100;\n }\n break;\n default:\n length = opCode >> 4;\n sourceOffset = opCode & 15;\n opCode = cbuf[srcIndex++];\n sourceOffset = (((opCode & 0xf8) << 1) + sourceOffset) + 1;\n break;\n }\n *oc = opCode;\n *si = srcIndex;\n *so = sourceOffset;\n *l = length;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-191'], 'message': 'fixed heap buffer overflow vulnerability CVE-2021-21899\n\nas reported in TALOS-2021-1350 / CVE-2021-21899,\ndwgCompressor::decompress21() could be abused with a malformed DWG file\nto force heap buffer overflow and possibly lead to malicious code\nexecution.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static GF_Err gf_media_export_filters(GF_MediaExporter *dumper)\n{\n\tchar *args, szSubArgs[1024], szExt[30];\n\tGF_Filter *file_out, *reframer, *remux=NULL, *src_filter;\n\tGF_FilterSession *fsess;\n\tGF_Err e = GF_OK;\n\tu32 codec_id=0;\n\tu32 sample_count=0;\n\tBool skip_write_filter = GF_FALSE;\n\tBool ext_forced = GF_FALSE;\n\tBool use_dynext = GF_FALSE;\n\n\targs = NULL;\n\tstrcpy(szExt, \"\");\n\tif (dumper->trackID && dumper->file) {\n\t\tu32 msubtype = 0;\n\t\tu32 mtype = 0;\n\t\tu32 afmt = 0;\n\t\tGF_PixelFormat pfmt = 0;\n\t\tGF_ESD *esd;\n\t\tconst char *export_ext = dumper->out_name ? gf_file_ext_start(dumper->out_name) : NULL;\n\t\tu32 track_num = gf_isom_get_track_by_id(dumper->file, dumper->trackID);\n\t\tif (!track_num) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_AUTHOR, (\"[Exporter] No tracks with ID %d in file\\n\", dumper->trackID));\n\t\t\treturn GF_BAD_PARAM;\n\t\t}\n\t\tesd = gf_media_map_esd(dumper->file, track_num, 0);\n\t\tsample_count = gf_isom_get_sample_count(dumper->file, dumper->trackID);\n\t\tif (esd) {\n\t\t\tif (esd->decoderConfig->objectTypeIndicationdecoderConfig->streamType, esd->decoderConfig->objectTypeIndication);\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\tif (esd->decoderConfig->decoderSpecificInfo && (codec_id==GF_CODECID_AAC_MPEG4)) {\n\t\t\t\t\tGF_M4ADecSpecInfo acfg;\n\t\t\t\t\tgf_m4a_get_config(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, &acfg);\n\t\t\t\t\tif (acfg.base_object_type == GF_M4A_USAC)\n\t\t\t\t\t\tcodec_id = GF_CODECID_USAC;\n\t\t\t\t}\n#endif\n\t\t\t} else {\n\t\t\t\tcodec_id = esd->decoderConfig->objectTypeIndication;\n\t\t\t}\n\t\t}\n\t\tif (!codec_id) {\n\t\t\tmsubtype = gf_isom_get_media_subtype(dumper->file, track_num, 1);\n\t\t\tcodec_id = gf_codec_id_from_isobmf(msubtype);\n\t\t}\n\t\tmtype = gf_isom_get_media_type(dumper->file, track_num);\n\t\tif (!codec_id) {\n\t\t\tpfmt = gf_pixel_fmt_from_qt_type(msubtype);\n\t\t\tif (pfmt) codec_id = GF_CODECID_RAW;\n\t\t}\n\n\t\tif (!codec_id) {\n\t\t\tstrcpy(szExt, gf_4cc_to_str(msubtype));\n\t\t\text_forced = GF_TRUE;\n\t\t} else if (codec_id==GF_CODECID_RAW) {\n\t\t\tswitch (mtype) {\n\t\t\tcase GF_ISOM_MEDIA_VISUAL:\n\t\t\tcase GF_ISOM_MEDIA_AUXV:\n\t\t\tcase GF_ISOM_MEDIA_PICT:\n\t\t\t\tif (pfmt)\n\t\t\t\t\tstrcpy(szExt, gf_pixel_fmt_sname(pfmt));\n\t\t\t\tbreak;\n\t\t\tcase GF_ISOM_MEDIA_AUDIO:\n\t\t\t\tafmt = gf_audio_fmt_from_isobmf(msubtype);\n\t\t\t\tif (afmt)\n\t\t\t\t\tstrcpy(szExt, gf_audio_fmt_name(afmt));\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tstrcpy(szExt, gf_4cc_to_str(msubtype));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\tconst char *sname = gf_codecid_file_ext(codec_id);\n\t\t\tif (export_ext && strstr(sname, export_ext+1)) {\n\t\t\t\tszExt[0]=0;\n\t\t\t} else {\n\t\t\t\tchar *sep;\n\t\t\t\tstrncpy(szExt, sname, 29);\n\t\t\t\tszExt[29]=0;\n\t\t\t\tsep = strchr(szExt, '|');\n\t\t\t\tif (sep) sep[0] = 0;\n\t\t\t}\n\t\t}\n\t\tswitch (mtype) {\n\t\tcase GF_ISOM_MEDIA_VISUAL:\n\t\tcase GF_ISOM_MEDIA_AUXV:\n\t\tcase GF_ISOM_MEDIA_PICT:\n\t\tcase GF_ISOM_MEDIA_AUDIO:\n\t\t\tskip_write_filter = codec_id ? GF_TRUE : GF_FALSE;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tswitch (codec_id) {\n\t\t\tcase GF_CODECID_WEBVTT:\n\t\t\t\tskip_write_filter = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\tcase GF_CODECID_META_TEXT:\n\t\t\tcase GF_CODECID_META_XML:\n\t\t\tcase GF_CODECID_SUBS_TEXT:\n\t\t\tcase GF_CODECID_SUBS_XML:\n\t\t\tcase GF_CODECID_SIMPLE_TEXT:\n\t\t\t\t//use dynamic extension\n\t\t\t\tszExt[0] = 0;\n\t\t\t\tuse_dynext = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\t//TODO, move these two to filters one of these days\n\t\tif ((codec_id==GF_CODECID_VORBIS) || (codec_id==GF_CODECID_THEORA) || (codec_id==GF_CODECID_OPUS)) {\n\t\t\tchar *outname = dumper->out_name;\n\t\t\tif (outname && !strcmp(outname, \"std\")) outname=NULL;\n\t\t\tif (esd) gf_odf_desc_del((GF_Descriptor *) esd);\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\treturn gf_dump_to_ogg(dumper, outname, track_num);\n#else\n\t\t\treturn GF_NOT_SUPPORTED;\n#endif\n\n\t\t}\n\t\tif (codec_id==GF_CODECID_SUBPIC) {\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\tchar *dsi = NULL;\n\t\t\tu32 dsi_size = 0;\n\t\t\tif (esd && esd->decoderConfig && esd->decoderConfig->decoderSpecificInfo) {\n\t\t\t\tdsi = esd->decoderConfig->decoderSpecificInfo->data;\n\t\t\t\tdsi_size = esd->decoderConfig->decoderSpecificInfo->dataLength;\n\t\t\t}\n\t\t\te = gf_dump_to_vobsub(dumper, dumper->out_name, track_num, dsi, dsi_size);\n#else\n\t\t\te = GF_NOT_SUPPORTED;\n#endif\n\t\t\tif (esd) gf_odf_desc_del((GF_Descriptor *) esd);\n\t\t\treturn e;\n\t\t}\n\t\tif (esd) gf_odf_desc_del((GF_Descriptor *) esd);\n\t} else {\n\t\tconst char *export_ext = dumper->out_name ? gf_file_ext_start(dumper->out_name) : NULL;\n\t\tskip_write_filter = GF_TRUE;\n\t\tif (!export_ext)\n\t\t\tuse_dynext = GF_TRUE;\n\t}\n\n\tfsess = gf_fs_new_defaults(0);\n\tif (!fsess) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_AUTHOR, (\"[Exporter] Failed to create filter session\\n\"));\n\t\treturn GF_OUT_OF_MEM;\n\t}\n\tfile_out = NULL;\n\targs = NULL;\n\n\tif (dumper->flags & GF_EXPORT_REMUX) {\n\t\tfile_out = gf_fs_load_destination(fsess, dumper->out_name, NULL, NULL, &e);\n\t\tif (!file_out) {\n\t\t\tgf_fs_del(fsess);\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_AUTHOR, (\"[Exporter] Cannot open destination %s\\n\", dumper->out_name));\n\t\t\treturn e;\n\t\t}\n\t}\n\t//except in nhml inband file dump, create a sink filter\n\telse if (!dumper->dump_file) {\n\t\tBool no_ext = (dumper->flags & GF_EXPORT_NO_FILE_EXT) ? GF_TRUE : GF_FALSE;\n\t\tchar *ext = gf_file_ext_start(dumper->out_name);\n\t\t//mux args, for now we only dump to file\n\t\te = gf_dynstrcat(&args, \"fout:dst=\", NULL);\n\t\te |= gf_dynstrcat(&args, dumper->out_name, NULL);\n\n\t\tif (dumper->flags & GF_EXPORT_NHNT) {\n\t\t\tstrcpy(szExt, \"nhnt\");\n\t\t\te |= gf_dynstrcat(&args, \":clone\", NULL);\n\t\t\tno_ext = GF_TRUE;\n\t\t\tif (!ext)\n\t\t\t\te |= gf_dynstrcat(&args, \":dynext\", NULL);\n\t\t} else if (dumper->flags & GF_EXPORT_NHML) {\n\t\t\tstrcpy(szExt, \"nhml\");\n\t\t\te |= gf_dynstrcat(&args, \":clone\", NULL);\n\t\t\tno_ext = GF_TRUE;\n\t\t\tif (!ext)\n\t\t\t\te |= gf_dynstrcat(&args, \":dynext\", NULL);\n\t\t}\n\n\t\tif (dumper->flags & GF_EXPORT_RAW_SAMPLES) {\n\t\t\tif (!dumper->sample_num) {\n\n\t\t\t\text = gf_file_ext_start(args);\n\t\t\t\tif (ext) ext[0] = 0;\n\t\t\t\tif (sample_count>=1000) {\n\t\t\t\t\te |= gf_dynstrcat(&args, \"_$num%08d$\", NULL);\n\t\t\t\t} else if (sample_count) {\n\t\t\t\t\te |= gf_dynstrcat(&args, \"_$num%03d$\", NULL);\n\t\t\t\t} else {\n\t\t\t\t\te |= gf_dynstrcat(&args, \"_$num$\", NULL);\n\t\t\t\t}\n\t\t\t\text = gf_file_ext_start(dumper->out_name);\n\t\t\t\tif (ext) e |= gf_dynstrcat(&args, ext, NULL);\n\t\t\t}\n\t\t\te |= gf_dynstrcat(&args, \":dynext\", NULL);\n\t\t} else if (dumper->trackID && strlen(szExt) ) {\n\t\t\tif (!no_ext && !gf_file_ext_start(dumper->out_name)) {\n\t\t\t\tif (args) gf_free(args);\n\t\t\t\targs=NULL;\n\t\t\t\te = gf_dynstrcat(&args, \"fout:dst=\", NULL);\n\t\t\t\te |= gf_dynstrcat(&args, dumper->out_name, NULL);\n\t\t\t\te |= gf_dynstrcat(&args, szExt, \".\");\n\t\t\t} else {\n\t\t\t\te |= gf_dynstrcat(&args, \":ext=\", NULL);\n\t\t\t\te |= gf_dynstrcat(&args, szExt, NULL);\n\t\t\t}\n\t\t} else if ((dumper->trackID || dumper->track_type) && use_dynext) {\n\t\t\te |= gf_dynstrcat(&args, \":dynext\", NULL);\n\t\t}\n\t\tif (e) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_AUTHOR, (\"[Exporter] Cannot load arguments for output file dumper\\n\"));\n\t\t\tif (args) gf_free(args);\n\t\t\tgf_fs_del(fsess);\n\t\t\treturn e;\n\t\t}\n\n\t\tfile_out = gf_fs_load_filter(fsess, args, &e);\n\t\tif (!file_out) {\n\t\t\tgf_fs_del(fsess);\n\t\t\tif (args) gf_free(args);\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_AUTHOR, (\"[Exporter] Cannot load output file dumper\\n\"));\n\t\t\treturn e;\n\t\t}\n\t}\n\tif (args) gf_free(args);\n\targs = NULL;\n\n\t//raw sample frame, force loading filter generic write in frame mode\n\tif (dumper->flags & GF_EXPORT_RAW_SAMPLES) {\n\t\te = gf_dynstrcat(&args, \"writegen:frame\", NULL);\n\t\tif (dumper->sample_num) {\n\t\t\tsprintf(szSubArgs, \":sstart=%d:send=%d\", dumper->sample_num, dumper->sample_num);\n\t\t\te |= gf_dynstrcat(&args, szSubArgs, NULL);\n\t\t}\n\t\tremux = e ? NULL : gf_fs_load_filter(fsess, args, &e);\n\t\tif (!remux || e) {\n\t\t\tgf_fs_del(fsess);\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_AUTHOR, (\"[Exporter] Cannot load stream->file filter\\n\"));\n\t\t\tif (args) gf_free(args);\n\t\t\treturn e ? e : GF_FILTER_NOT_FOUND;\n\t\t}\n\t}\n\telse if (dumper->flags & GF_EXPORT_NHNT) {\n\t\tremux = gf_fs_load_filter(fsess, \"nhntw:exporter\", &e);\n\t\tif (!remux) {\n\t\t\tgf_fs_del(fsess);\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_AUTHOR, (\"[Exporter] Cannot load NHNT write filter\\n\"));\n\t\t\treturn e;\n\t\t}\n\t}\n\telse if (dumper->flags & GF_EXPORT_NHML) {\n\t\te = gf_dynstrcat(&args, \"nhmlw:exporter:name=\", NULL);\n\t\te |= gf_dynstrcat(&args, dumper->out_name, NULL);\n\t\tif (dumper->flags & GF_EXPORT_NHML_FULL)\n\t\t\te |= gf_dynstrcat(&args, \":pckp\", NULL);\n\t\tif (dumper->dump_file) {\n\t\t\tsprintf(szSubArgs, \":nhmlonly:filep=%p\", dumper->dump_file);\n\t\t\te |= gf_dynstrcat(&args, szSubArgs, NULL);\n\t\t}\n\t\tremux = e ? NULL : gf_fs_load_filter(fsess, args, &e);\n\t\tif (!remux || e) {\n\t\t\tgf_fs_del(fsess);\n\t\t\tif (args) gf_free(args);\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_AUTHOR, (\"[Exporter] Cannot load NHML write filter\\n\"));\n\t\t\treturn e ? e : GF_FILTER_NOT_FOUND;\n\t\t}\n\t} else if (!skip_write_filter) {\n\t\te = gf_dynstrcat(&args, \"writegen:exporter\", NULL);\n\t\t//extension has been forced, override ext at output of writegen\n\t\tif (ext_forced) {\n\t\t\te |= gf_dynstrcat(&args, \":#Extension=\", NULL);\n\t\t\te |= gf_dynstrcat(&args, szExt, NULL);\n\t\t}\n\n\t\tremux = e ? NULL : gf_fs_load_filter(fsess, args, &e);\n\t\tif (!remux) {\n\t\t\tgf_fs_del(fsess);\n\t\t\tif (args) gf_free(args);\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_AUTHOR, (\"[Exporter] Cannot load stream->file filter\\n\"));\n\t\t\treturn e;\n\t\t}\n\t}\n\tif (args) gf_free(args);\n\targs = NULL;\n\n\t//force a reframer filter, connected to our input\n\te = gf_dynstrcat(&args, \"reframer:SID=1\", NULL);\n\tif (dumper->trackID) {\n\t\tsprintf(szSubArgs, \"#PID=%d\", dumper->trackID);\n\t\te |= gf_dynstrcat(&args, szSubArgs, NULL);\n\t}\n\te |= gf_dynstrcat(&args, \":exporter\", NULL);\n\tif (dumper->flags & GF_EXPORT_SVC_LAYER)\n\t\te |= gf_dynstrcat(&args, \":extract=layer\", NULL);\n\tif (dumper->flags & GF_EXPORT_WEBVTT_NOMERGE)\n\t\te |= gf_dynstrcat(&args, \":merge\", NULL);\n\n\treframer = gf_fs_load_filter(fsess, args, &e);\n\tif (!reframer || e) {\n\t\tgf_fs_del(fsess);\n\t\tif (args) gf_free(args);\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_AUTHOR, (\"[Exporter] Cannot load reframer filter\\n\"));\n\t\treturn e ? e : GF_FILTER_NOT_FOUND;\n\t}\n\tif (args) gf_free(args);\n\targs = NULL;\n\n\t//we already have the file loaded, directly load the mp4dmx filter with this file\n\tif (dumper->file) {\n\t\t//we want to expose every track\n\t\te = gf_dynstrcat(&args, \"mp4dmx:FID=1:noedit:alltk:allt\", NULL);\n\t\tif (!e) {\n\t\t\tsprintf(szSubArgs, \":mov=%p\", dumper->file);\n\t\t\te = gf_dynstrcat(&args, szSubArgs, NULL);\n\t\t}\n\t\t\n\t\t//we want to expose every track\n\t\tsrc_filter = gf_fs_load_filter(fsess, args, &e);\n\n\t\tgf_free(args);\n\t\targs = NULL;\n\t} else {\n\t\t//we want to expose every track\n\t\tsrc_filter = gf_fs_load_source(fsess, dumper->in_name, \"FID=1:noedit:alltk:allt\", NULL, &e);\n\t}\n\n\tif (!src_filter || e) {\n\t\tgf_fs_del(fsess);\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_AUTHOR, (\"[Exporter] Cannot load filter for input file \\\"%s\\\": %s\\n\", dumper->in_name, gf_error_to_string(e) ));\n\t\treturn e;\n\t}\n\n\tif (dumper->track_type) {\n\t\tconst char *mtype = (dumper->track_type==1) ? \"video\" : \"audio\";\n\t\tif (dumper->trackID) {\n\t\t\tsprintf(szSubArgs, \"%s%d\", mtype, dumper->trackID);\n\t\t} else {\n\t\t\tsprintf(szSubArgs, \"%s\", mtype);\n\t\t}\n\t}\n\telse if (dumper->trackID) {\n\t\tsprintf(szSubArgs, \"PID=%d\", dumper->trackID);\n\t}\n\tif (remux) {\n\t\tgf_filter_set_source(file_out, remux, (dumper->trackID || dumper->track_type) ? szSubArgs : NULL);\n\t\tgf_filter_set_source(remux, reframer, (dumper->trackID || dumper->track_type) ? szSubArgs : NULL);\n\t} else {\n\t\tgf_filter_set_source(file_out, reframer, (dumper->trackID || dumper->track_type) ? szSubArgs : NULL);\n\t}\n\n\te = gf_fs_run(fsess);\n\tif (e>GF_OK) e = GF_OK;\n\tif (!e) e = gf_fs_get_last_connect_error(fsess);\n\tif (!e) e = gf_fs_get_last_process_error(fsess);\n\n\tif (!e) {\n\t\tif (dumper->file)\n\t\t\tgf_fs_print_unused_args(fsess, NULL);\n\t\telse\n\t\t\tgf_fs_print_unused_args(fsess, \"alltk,allt,noedit\");\n\t}\n\tgf_fs_print_non_connected(fsess);\n\tif (dumper->print_stats_graph & 1) gf_fs_print_stats(fsess);\n\tif (dumper->print_stats_graph & 2) gf_fs_print_connections(fsess);\n\tgf_fs_del(fsess);\n\treturn e;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'fixed #1769 (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: int treeRead(struct READER *reader, struct DATAOBJECT *data) {\n\n\tint i, j, err, olen, elements, size, x, y, z, b, e, dy, dz, sx, sy, sz, dzy,\n\t\tszy;\n\tchar *input, *output;\n\n\tuint8_t node_type, node_level;\n\tuint16_t entries_used;\n\tuint32_t size_of_chunk;\n\tuint32_t filter_mask;\n\tuint64_t address_of_left_sibling, address_of_right_sibling, start[4],\n\t\tchild_pointer, key, store;\n\n\tchar buf[4];\n\n\tUNUSED(node_level);\n\tUNUSED(address_of_right_sibling);\n\tUNUSED(address_of_left_sibling);\n\tUNUSED(key);\n\n\tif (data->ds.dimensionality > 3) {\n\t\tlog(\"TREE dimensions > 3\");\n\t\treturn MYSOFA_INVALID_FORMAT;\n\t}\n\n\t/* read signature */\n\tif (fread(buf, 1, 4, reader->fhd) != 4 || strncmp(buf, \"TREE\", 4)) {\n\t\tlog(\"cannot read signature of TREE\\n\");\n\t\treturn MYSOFA_INVALID_FORMAT;\n\t} log(\"%08lX %.4s\\n\", (uint64_t )ftell(reader->fhd) - 4, buf);\n\n\tnode_type = (uint8_t)fgetc(reader->fhd);\n\tnode_level = (uint8_t)fgetc(reader->fhd);\n\tentries_used = (uint16_t)readValue(reader, 2);\n\tif(entries_used>0x1000)\n\t\treturn MYSOFA_UNSUPPORTED_FORMAT;\n\taddress_of_left_sibling = readValue(reader,\n\t\t\t\t\t reader->superblock.size_of_offsets);\n\taddress_of_right_sibling = readValue(reader,\n\t\t\t\t\t reader->superblock.size_of_offsets);\n\n\telements = 1;\n\tfor (j = 0; j < data->ds.dimensionality; j++)\n\t\telements *= data->datalayout_chunk[j];\n\tdy = data->datalayout_chunk[1];\n\tdz = data->datalayout_chunk[2];\n\tsx = data->ds.dimension_size[0];\n\tsy = data->ds.dimension_size[1];\n\tsz = data->ds.dimension_size[2];\n\tdzy = dz * dy;\n\tszy = sz * sy;\n\tsize = data->datalayout_chunk[data->ds.dimensionality];\n\n\tlog(\"elements %d size %d\\n\",elements,size);\n\n\tif (!(output = malloc(elements * size))) {\n\t\treturn MYSOFA_NO_MEMORY;\n\t}\n\n\tfor (e = 0; e < entries_used * 2; e++) {\n\t\tif (node_type == 0) {\n\t\t\tkey = readValue(reader, reader->superblock.size_of_lengths);\n\t\t} else {\n\t\t\tsize_of_chunk = (uint32_t)readValue(reader, 4);\n\t\t\tfilter_mask = (uint32_t)readValue(reader, 4);\n\t\t\tif (filter_mask) {\n\t\t\t\tlog(\"TREE all filters must be enabled\\n\");\n\t\t\t\tfree(output);\n\t\t\t\treturn MYSOFA_INVALID_FORMAT;\n\t\t\t}\n\n\t\t\tfor (j = 0; j < data->ds.dimensionality; j++) {\n\t\t\t\tstart[j] = readValue(reader, 8);\n\t\t\t\tlog(\"start %d %lu\\n\",j,start[j]);\n\t\t\t}\n\n\t\t\tif (readValue(reader, 8)) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tchild_pointer = readValue(reader,\n\t\t\t\t\t\t reader->superblock.size_of_offsets);\n\t\t\tlog(\" data at %lX len %u\\n\", child_pointer, size_of_chunk);\n\n\t\t\t/* read data */\n\t\t\tstore = ftell(reader->fhd);\n\t\t\tif (fseek(reader->fhd, child_pointer, SEEK_SET)<0) {\n\t\t\t\tfree(output);\n\t\t\t\treturn errno;\n\t\t\t}\n\n\t\t\tif (!(input = malloc(size_of_chunk))) {\n\t\t\t\tfree(output);\n\t\t\t\treturn MYSOFA_NO_MEMORY;\n\t\t\t}\n\t\t\tif (fread(input, 1, size_of_chunk, reader->fhd) != size_of_chunk) {\n\t\t\t\tfree(output);\n\t\t\t\tfree(input);\n\t\t\t\treturn MYSOFA_INVALID_FORMAT;\n\t\t\t}\n\n\t\t\tolen = elements * size;\n\t\t\terr = gunzip(size_of_chunk, input, &olen, output);\n\t\t\tfree(input);\n\n\t\t\tlog(\" gunzip %d %d %d\\n\",err, olen, elements*size);\n\t\t\tif (err || olen != elements * size) {\n\t\t\t\tfree(output);\n\t\t\t\treturn MYSOFA_INVALID_FORMAT;\n\t\t\t}\n\n\t\t\tswitch (data->ds.dimensionality) {\n\t\t\tcase 1:\n\t\t\t\tfor (i = 0; i < olen; i++) {\n\t\t\t\t\tb = i / elements;\n\t\t\t\t\tx = i % elements + start[0];\n\t\t\t\t\tif (x < sx) {\n\t\t\t\t\t\tj = x * size + b;\n\t\t\t\t\t\t((char*)data->data)[j] = output[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tfor (i = 0; i < olen; i++) {\n\t\t\t\t\tb = i / elements;\n\t\t\t\t\tx = i % elements;\n\t\t\t\t\ty = x % dy + start[1];\n\t\t\t\t\tx = x / dy + start[0];\n\t\t\t\t\tif (y < sy && x < sx) {\n\t\t\t\t\t\tj = ((x * sy + y) * size) + b;\n\t\t\t\t\t\t((char*)data->data)[j] = output[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tfor (i = 0; i < olen; i++) {\n\t\t\t\t\tb = i / elements;\n\t\t\t\t\tx = i % elements;\n\t\t\t\t\tz = x % dz + start[2];\n\t\t\t\t\ty = (x / dz) % dy + start[1];\n\t\t\t\t\tx = (x / dzy) + start[0];\n\t\t\t\t\tif (z < sz && y < sy && x < sx) {\n\t\t\t\t\t\tj = (x * szy + y * sz + z) * size + b;\n\t\t\t\t\t\t((char*)data->data)[j] = output[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tlog(\"invalid dim\\n\");\n\t\t\t\treturn MYSOFA_INTERNAL_ERROR;\n\t\t\t}\n\n\t\t\tif(fseek(reader->fhd, store, SEEK_SET)<0) {\n\t\t\t\tfree(output);\n\t\t\t\treturn errno;\n\t\t\t}\n\t\t}\n\t}\n\n\tfree(output);\n\tif(fseek(reader->fhd, 4, SEEK_CUR)<0) /* skip checksum */\n\t\treturn errno;\n\n\treturn MYSOFA_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-703'], 'message': 'Fixed security issue 1'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int rose_rx_call_request(struct sk_buff *skb, struct net_device *dev, struct rose_neigh *neigh, unsigned int lci)\n{\n\tstruct sock *sk;\n\tstruct sock *make;\n\tstruct rose_sock *make_rose;\n\tstruct rose_facilities_struct facilities;\n\tint n, len;\n\n\tskb->sk = NULL;\t\t/* Initially we don't know who it's for */\n\n\t/*\n\t *\tskb->data points to the rose frame start\n\t */\n\tmemset(&facilities, 0x00, sizeof(struct rose_facilities_struct));\n\n\tlen = (((skb->data[3] >> 4) & 0x0F) + 1) >> 1;\n\tlen += (((skb->data[3] >> 0) & 0x0F) + 1) >> 1;\n\tif (!rose_parse_facilities(skb->data + len + 4, &facilities)) {\n\t\trose_transmit_clear_request(neigh, lci, ROSE_INVALID_FACILITY, 76);\n\t\treturn 0;\n\t}\n\n\tsk = rose_find_listener(&facilities.source_addr, &facilities.source_call);\n\n\t/*\n\t * We can't accept the Call Request.\n\t */\n\tif (sk == NULL || sk_acceptq_is_full(sk) ||\n\t (make = rose_make_new(sk)) == NULL) {\n\t\trose_transmit_clear_request(neigh, lci, ROSE_NETWORK_CONGESTION, 120);\n\t\treturn 0;\n\t}\n\n\tskb->sk = make;\n\tmake->sk_state = TCP_ESTABLISHED;\n\tmake_rose = rose_sk(make);\n\n\tmake_rose->lci = lci;\n\tmake_rose->dest_addr = facilities.dest_addr;\n\tmake_rose->dest_call = facilities.dest_call;\n\tmake_rose->dest_ndigis = facilities.dest_ndigis;\n\tfor (n = 0 ; n < facilities.dest_ndigis ; n++)\n\t\tmake_rose->dest_digis[n] = facilities.dest_digis[n];\n\tmake_rose->source_addr = facilities.source_addr;\n\tmake_rose->source_call = facilities.source_call;\n\tmake_rose->source_ndigis = facilities.source_ndigis;\n\tfor (n = 0 ; n < facilities.source_ndigis ; n++)\n\t\tmake_rose->source_digis[n]= facilities.source_digis[n];\n\tmake_rose->neighbour = neigh;\n\tmake_rose->device = dev;\n\tmake_rose->facilities = facilities;\n\n\tmake_rose->neighbour->use++;\n\n\tif (rose_sk(sk)->defer) {\n\t\tmake_rose->state = ROSE_STATE_5;\n\t} else {\n\t\trose_write_internal(make, ROSE_CALL_ACCEPTED);\n\t\tmake_rose->state = ROSE_STATE_3;\n\t\trose_start_idletimer(make);\n\t}\n\n\tmake_rose->condition = 0x00;\n\tmake_rose->vs = 0;\n\tmake_rose->va = 0;\n\tmake_rose->vr = 0;\n\tmake_rose->vl = 0;\n\tsk->sk_ack_backlog++;\n\n\trose_insert_socket(make);\n\n\tskb_queue_head(&sk->sk_receive_queue, skb);\n\n\trose_start_heartbeat(make);\n\n\tif (!sock_flag(sk, SOCK_DEAD))\n\t\tsk->sk_data_ready(sk, skb->len);\n\n\treturn 1;\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: void build_ntlmssp_negotiate_blob(unsigned char *pbuffer,\n\t\t\t\t\t struct cifs_ses *ses)\n{\n\tNEGOTIATE_MESSAGE *sec_blob = (NEGOTIATE_MESSAGE *)pbuffer;\n\t__u32 flags;\n\n\tmemset(pbuffer, 0, sizeof(NEGOTIATE_MESSAGE));\n\tmemcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8);\n\tsec_blob->MessageType = NtLmNegotiate;\n\n\t/* BB is NTLMV2 session security format easier to use here? */\n\tflags = NTLMSSP_NEGOTIATE_56 |\tNTLMSSP_REQUEST_TARGET |\n\t\tNTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE |\n\t\tNTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC;\n\tif (ses->server->sign) {\n\t\tflags |= NTLMSSP_NEGOTIATE_SIGN;\n\t\tif (!ses->server->session_estab ||\n\t\t\t\tses->ntlmssp->sesskey_per_smbsess)\n\t\t\tflags |= NTLMSSP_NEGOTIATE_KEY_XCH;\n\t}\n\n\tsec_blob->NegotiateFlags = cpu_to_le32(flags);\n\n\tsec_blob->WorkstationName.BufferOffset = 0;\n\tsec_blob->WorkstationName.Length = 0;\n\tsec_blob->WorkstationName.MaximumLength = 0;\n\n\t/* Domain name is sent on the Challenge not Negotiate NTLMSSP request */\n\tsec_blob->DomainName.BufferOffset = 0;\n\tsec_blob->DomainName.Length = 0;\n\tsec_blob->DomainName.MaximumLength = 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'CIFS: Enable encryption during session setup phase\n\nIn order to allow encryption on SMB connection we need to exchange\na session key and generate encryption and decryption keys.\n\nSigned-off-by: Pavel Shilovsky '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Compute(OpKernelContext* context) override {\n const Tensor& input_sizes = context->input(0);\n const Tensor& filter = context->input(1);\n const Tensor& out_backprop = context->input(2);\n\n TensorShape input_shape;\n OP_REQUIRES_OK(context,\n Conv2DBackpropComputeInputShape(input_sizes, filter.shape(),\n out_backprop.shape(),\n data_format_, &input_shape));\n\n ConvBackpropDimensions dims;\n OP_REQUIRES_OK(context,\n ConvBackpropComputeDimensionsV2(\n \"Conv2DCustomBackpropInput\", /*num_spatial_dims=*/2,\n input_shape, filter.shape(), out_backprop.shape(),\n /*dilations=*/{1, 1, 1, 1}, strides_, padding_,\n explicit_paddings_, data_format_, &dims));\n\n OP_REQUIRES(context, dims.in_depth == filter.shape().dim_size(2),\n errors::InvalidArgument(\"Computed input depth \", dims.in_depth,\n \" doesn't match filter input depth \",\n filter.shape().dim_size(2)));\n OP_REQUIRES(\n context, dims.out_depth == filter.shape().dim_size(3),\n errors::InvalidArgument(\"Computed output depth \", dims.out_depth,\n \" doesn't match filter output depth \",\n filter.shape().dim_size(3)));\n\n Tensor* in_backprop = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, input_shape, &in_backprop));\n\n // If there is nothing to compute, return.\n if (input_shape.num_elements() == 0) {\n return;\n }\n\n// TODO(ezhulenev): Remove custom kernel and move XSMM support to\n// LaunchConv2DBackpropInputOp functor.\n#if defined TENSORFLOW_USE_LIBXSMM_CONVOLUTIONS && \\\n defined TENSORFLOW_USE_LIBXSMM_BACKWARD_CONVOLUTIONS\n int64 pad_top, pad_bottom;\n int64 pad_left, pad_right;\n OP_REQUIRES_OK(\n context,\n GetWindowedOutputSizeVerbose(\n dims.spatial_dims[0].input_size, dims.spatial_dims[0].filter_size,\n dims.spatial_dims[0].stride, padding_,\n &dims.spatial_dims[0].output_size, &pad_top, &pad_bottom));\n OP_REQUIRES_OK(\n context,\n GetWindowedOutputSizeVerbose(\n dims.spatial_dims[1].input_size, dims.spatial_dims[1].filter_size,\n dims.spatial_dims[1].stride, padding_,\n &dims.spatial_dims[1].output_size, &pad_left, &pad_right));\n\n if (pad_left == pad_right && pad_top == pad_bottom) {\n if (LaunchXsmmBackwardInputConvolution()(\n context, context->eigen_device(),\n in_backprop->tensor(), filter.tensor(),\n out_backprop.tensor(), dims.spatial_dims[0].input_size,\n dims.spatial_dims[1].input_size,\n static_cast(dims.spatial_dims[0].stride),\n static_cast(dims.spatial_dims[1].stride),\n static_cast(pad_top), static_cast(pad_left),\n data_format_)) {\n return;\n }\n }\n#else\n int64 pad_top, pad_bottom;\n int64 pad_left, pad_right;\n#endif\n if (padding_ == Padding::EXPLICIT) {\n pad_top = explicit_paddings_[2];\n pad_bottom = explicit_paddings_[3];\n pad_left = explicit_paddings_[4];\n pad_right = explicit_paddings_[5];\n }\n OP_REQUIRES_OK(\n context,\n GetWindowedOutputSizeVerbose(\n dims.spatial_dims[0].input_size, dims.spatial_dims[0].filter_size,\n dims.spatial_dims[0].stride, padding_,\n &dims.spatial_dims[0].output_size, &pad_top, &pad_bottom));\n OP_REQUIRES_OK(\n context,\n GetWindowedOutputSizeVerbose(\n dims.spatial_dims[1].input_size, dims.spatial_dims[1].filter_size,\n dims.spatial_dims[1].stride, padding_,\n &dims.spatial_dims[1].output_size, &pad_left, &pad_right));\n\n // The total dimension size of each kernel.\n const int filter_total_size = dims.spatial_dims[0].filter_size *\n dims.spatial_dims[1].filter_size *\n dims.in_depth;\n // The output image size is the spatial size of the output.\n const int output_image_size =\n dims.spatial_dims[0].output_size * dims.spatial_dims[1].output_size;\n\n // TODO(andydavis) Get L2/L3 cache sizes from device.\n const size_t l2_cache_size = 256LL << 10;\n const size_t l3_cache_size = 30LL << 20;\n\n // Use L3 cache size as target working set size.\n const size_t target_working_set_size = l3_cache_size / sizeof(T);\n\n // Calculate size of matrices involved in MatMul: C = A x B.\n const size_t size_A = output_image_size * dims.out_depth;\n\n const size_t size_B = filter_total_size * dims.out_depth;\n\n const size_t size_C = output_image_size * filter_total_size;\n\n const size_t work_unit_size = size_A + size_B + size_C;\n\n auto worker_threads = *(context->device()->tensorflow_cpu_worker_threads());\n\n // Calculate per-thread work unit size.\n const size_t thread_work_unit_size =\n work_unit_size / worker_threads.num_threads;\n\n // Set minimum per-thread work unit size to size of L2 cache.\n const size_t min_thread_work_unit_size = l2_cache_size / sizeof(T);\n\n // Use parallel tensor contractions if there is no batching, or if the\n // minimum per-thread work unit size threshold has been exceeded.\n // Otherwise, revert to multiple single-threaded matmul ops running in\n // parallel to keep all threads busy.\n // TODO(andydavis) Explore alternatives to branching the code in this way\n // (i.e. run multiple, parallel tensor contractions in another thread pool).\n const bool use_parallel_contraction =\n dims.batch_size == 1 ||\n thread_work_unit_size >= min_thread_work_unit_size;\n\n const size_t shard_size =\n use_parallel_contraction\n ? 1\n : (target_working_set_size + work_unit_size - 1) / work_unit_size;\n\n Tensor col_buffer;\n OP_REQUIRES_OK(context,\n context->allocate_temp(\n DataTypeToEnum::value,\n TensorShape({static_cast(shard_size),\n static_cast(output_image_size),\n static_cast(filter_total_size)}),\n &col_buffer));\n\n // The input offset corresponding to a single input image.\n const int input_offset = dims.spatial_dims[0].input_size *\n dims.spatial_dims[1].input_size * dims.in_depth;\n // The output offset corresponding to a single output image.\n const int output_offset = dims.spatial_dims[0].output_size *\n dims.spatial_dims[1].output_size * dims.out_depth;\n\n const T* filter_data = filter.template flat().data();\n T* col_buffer_data = col_buffer.template flat().data();\n const T* out_backprop_data = out_backprop.template flat().data();\n\n auto in_backprop_flat = in_backprop->template flat();\n T* input_backprop_data = in_backprop_flat.data();\n in_backprop_flat.device(context->eigen_device()) =\n in_backprop_flat.constant(T(0));\n\n if (use_parallel_contraction) {\n typedef Eigen::TensorMap,\n Eigen::Unaligned>\n TensorMap;\n typedef Eigen::TensorMap,\n Eigen::Unaligned>\n ConstTensorMap;\n\n // Initialize contraction dims (we need to transpose 'B' below).\n Eigen::array, 1> contract_dims;\n contract_dims[0].first = 1;\n contract_dims[0].second = 1;\n\n for (int image_id = 0; image_id < dims.batch_size; ++image_id) {\n // Compute gradient into col_buffer.\n TensorMap C(col_buffer_data, output_image_size, filter_total_size);\n\n ConstTensorMap A(out_backprop_data + output_offset * image_id,\n output_image_size, dims.out_depth);\n ConstTensorMap B(filter_data, filter_total_size, dims.out_depth);\n\n C.device(context->eigen_cpu_device()) = A.contract(B, contract_dims);\n\n Col2im(\n col_buffer_data, dims.in_depth, dims.spatial_dims[0].input_size,\n dims.spatial_dims[1].input_size, dims.spatial_dims[0].filter_size,\n dims.spatial_dims[1].filter_size, pad_top, pad_left, pad_bottom,\n pad_right, dims.spatial_dims[0].stride, dims.spatial_dims[1].stride,\n input_backprop_data);\n\n input_backprop_data += input_offset;\n }\n } else {\n for (int image_id = 0; image_id < dims.batch_size;\n image_id += shard_size) {\n const int shard_limit =\n std::min(static_cast(shard_size),\n static_cast(dims.batch_size) - image_id);\n\n auto shard = [&context, &dims, &pad_top, &pad_left, &pad_bottom,\n &pad_right, &output_image_size, &filter_total_size,\n &input_backprop_data, &col_buffer_data,\n &out_backprop_data, &filter_data, &input_offset,\n &output_offset, &size_C](int64 start, int64 limit) {\n for (int shard_id = start; shard_id < limit; ++shard_id) {\n T* im2col_buf = col_buffer_data + shard_id * size_C;\n T* input_data = input_backprop_data + shard_id * input_offset;\n const T* out_data = out_backprop_data + shard_id * output_offset;\n\n Conv2DCustomBackpropInputMatMulFunctor()(\n context, out_data, filter_data, filter_total_size,\n output_image_size, dims.out_depth, im2col_buf);\n\n Col2im(im2col_buf, dims.in_depth,\n dims.spatial_dims[0].input_size,\n dims.spatial_dims[1].input_size,\n dims.spatial_dims[0].filter_size,\n dims.spatial_dims[1].filter_size, pad_top, pad_left,\n pad_bottom, pad_right, dims.spatial_dims[0].stride,\n dims.spatial_dims[1].stride, input_data);\n }\n };\n Shard(worker_threads.num_threads, worker_threads.workers, shard_limit,\n work_unit_size, shard);\n\n input_backprop_data += input_offset * shard_limit;\n out_backprop_data += output_offset * shard_limit;\n }\n }\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'Prevent yet another division by zero\n\nPiperOrigin-RevId: 369343977\nChange-Id: I1a60da4cf512e60fd91e069c16e026544632fe7f'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Compute(OpKernelContext* ctx) override {\n const Tensor& input = ctx->input(kInputTensorIndex);\n const Tensor& input_min = ctx->input(kInputMinIndex);\n const Tensor& input_max = ctx->input(kInputMaxIndex);\n\n const size_t depth = input_max.NumElements();\n OP_REQUIRES(\n ctx, input_min.dim_size(0) == depth,\n errors::InvalidArgument(\"input_min has incorrect size, expected \",\n depth, \" was \", input_min.dim_size(0)));\n OP_REQUIRES(\n ctx, input_max.dim_size(0) == depth,\n errors::InvalidArgument(\"input_max has incorrect size, expected \",\n depth, \" was \", input_max.dim_size(0)));\n\n const float* input_min_data = input_min.flat().data();\n const float* input_max_data = input_max.flat().data();\n std::vector ranges(depth);\n bool is_non_negative = true;\n Eigen::array shuffling({1, 0});\n auto input_matrix = input.flat_inner_dims();\n\n // TODO: verify performance of not transposing and finding the min max\n // directly from input_matrix vs the one presented below of transposing and\n // using the transposed matrix as the transposing operation in itself might\n // be more costly.\n // Note that this operation is a calibration step for quantization and will\n // cease to exist in the final inference graph(will exist as a const node).\n auto transposed_input = input_matrix.shuffle(shuffling);\n\n // Find the ranges of each channel in parallel.\n float out_min_max = std::numeric_limits::min();\n\n#ifdef ENABLE_ONEDNN_OPENMP\n#ifdef _MSC_VER\n#pragma omp parallel for\n#else\n#pragma omp parallel for reduction(max : out_min_max)\n#endif\n#endif // ENABLE_ONEDNN_OPENMP\n // TODO: Add eigen parallel_for\n for (int64_t i = 0; i < depth; ++i) {\n Eigen::Tensor min =\n transposed_input.chip<0>(i).minimum();\n Eigen::Tensor max =\n transposed_input.chip<0>(i).maximum();\n const int32_t min_per_channel = min();\n const int32_t max_per_channel = max();\n const int32_t abs_max =\n std::max(std::abs(min_per_channel), std::abs(max_per_channel));\n float scale =\n std::max(std::abs(input_min_data[i]), std::abs(input_max_data[i]));\n ranges[i] =\n scale * static_cast(abs_max) / static_cast(1L << 31);\n if (min_per_channel < 0) is_non_negative = false;\n\n // Thread-local out_min_max.\n out_min_max = std::max(out_min_max, ranges[i]);\n }\n\n // All local out_min_max gets max-reduced into one global out_min_max at\n // the end of the loop by specifying reduction(max:out_min_max) along with\n // omp parallel for.\n\n // Fixing max to clip_value_max_ (example 6.0 to support relu6)\n if (out_min_max > clip_value_max_) out_min_max = clip_value_max_;\n\n Tensor* output_min = nullptr;\n Tensor* output_max = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(kOutputMinIndex, {}, &output_min));\n OP_REQUIRES_OK(ctx, ctx->allocate_output(kOutputMaxIndex, {}, &output_max));\n output_min->flat()(0) = is_non_negative ? 0.0f : -out_min_max;\n output_max->flat()(0) = out_min_max;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-703'], 'message': 'Add more validation to `RequantizationRangePerChannel`.\n\nPiperOrigin-RevId: 387693946\nChange-Id: Ife8dcbdb021bec4787eef6a4361dd08f17c14bd6'" }, { "text": "[INST] Given the following code containing errors, provide Common 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_TCHECK_16BITS(&bp[6]);\n\t\t\t\tND_PRINT((ndo, \", (bad vrrp cksum %x)\",\n\t\t\t\t\tEXTRACT_16BITS(&bp[6])));\n\t\t\t}\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-787'], 'message': '(for 4.9.3) VRRP: Add a missing bounds check\n\nIn vrrp_print().\n\nThis fixes a buffer over-read discovered by Konrad Rieck and\nBhargava Shastry.\n\nAdd a test using the capture file supplied by the reporter(s)\nrestricted to VRRP packets.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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::LowerBoundFunctor::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: int processClientServerHello(struct ndpi_detection_module_struct *ndpi_struct,\n\t\t\t struct ndpi_flow_struct *flow, uint32_t quic_version) {\n struct ndpi_packet_struct *packet = &flow->packet;\n union ja3_info ja3;\n u_int8_t invalid_ja3 = 0;\n u_int16_t tls_version, ja3_str_len;\n char ja3_str[JA3_STR_LEN];\n ndpi_MD5_CTX ctx;\n u_char md5_hash[16];\n int i;\n u_int16_t total_len;\n u_int8_t handshake_type;\n char buffer[64] = { '\\0' };\n int is_quic = (quic_version != 0);\n int is_dtls = packet->udp && (!is_quic);\n\n#ifdef DEBUG_TLS\n printf(\"TLS %s() called\\n\", __FUNCTION__);\n#endif\n\n memset(&ja3, 0, sizeof(ja3));\n\n handshake_type = packet->payload[0];\n total_len = (packet->payload[1] << 16) + (packet->payload[2] << 8) + packet->payload[3];\n\n if((total_len > packet->payload_packet_len) || (packet->payload[1] != 0x0))\n return(0); /* Not found */\n\n total_len = packet->payload_packet_len;\n\n /* At least \"magic\" 3 bytes, null for string end, otherwise no need to waste cpu cycles */\n if(total_len > 4) {\n u_int16_t base_offset = (!is_dtls) ? 38 : 46;\n u_int16_t version_offset = (!is_dtls) ? 4 : 12;\n u_int16_t offset = (!is_dtls) ? 38 : 46, extension_len, j;\n u_int8_t session_id_len = 0;\n\n if((base_offset >= total_len) ||\n (version_offset + 1) >= total_len)\n return 0; /* Not found */\n\n session_id_len = packet->payload[base_offset];\n\n#ifdef DEBUG_TLS\n printf(\"TLS [len: %u][handshake_type: %02X]\\n\", packet->payload_packet_len, handshake_type);\n#endif\n\n tls_version = ntohs(*((u_int16_t*)&packet->payload[version_offset]));\n\n if(handshake_type == 0x02 /* Server Hello */) {\n int i, rc;\n\n ja3.server.tls_handshake_version = tls_version;\n\n#ifdef DEBUG_TLS\n printf(\"TLS Server Hello [version: 0x%04X]\\n\", tls_version);\n#endif\n\n /*\n\tThe server hello decides about the TLS version of this flow\n\thttps://networkengineering.stackexchange.com/questions/55752/why-does-wireshark-show-version-tls-1-2-here-instead-of-tls-1-3\n */\n if(packet->udp)\n\toffset += session_id_len + 1;\n else {\n\tif(tls_version < 0x7F15 /* TLS 1.3 lacks of session id */)\n\t offset += session_id_len+1;\n }\n\n if((offset+3) > packet->payload_packet_len)\n\treturn(0); /* Not found */\n\n ja3.server.num_cipher = 1, ja3.server.cipher[0] = ntohs(*((u_int16_t*)&packet->payload[offset]));\n if((flow->protos.tls_quic_stun.tls_quic.server_unsafe_cipher = ndpi_is_safe_ssl_cipher(ja3.server.cipher[0])) == 1)\n\tndpi_set_risk(flow, NDPI_TLS_WEAK_CIPHER);\n\n flow->protos.tls_quic_stun.tls_quic.server_cipher = ja3.server.cipher[0];\n\n#ifdef DEBUG_TLS\n printf(\"TLS [server][session_id_len: %u][cipher: %04X]\\n\", session_id_len, ja3.server.cipher[0]);\n#endif\n\n offset += 2 + 1;\n\n if((offset + 1) < packet->payload_packet_len) /* +1 because we are goint to read 2 bytes */\n\textension_len = ntohs(*((u_int16_t*)&packet->payload[offset]));\n else\n\textension_len = 0;\n\n#ifdef DEBUG_TLS\n printf(\"TLS [server][extension_len: %u]\\n\", extension_len);\n#endif\n offset += 2;\n\n for(i=0; i packet->payload_packet_len) break;\n\n\textension_id = ntohs(*((u_int16_t*)&packet->payload[offset]));\n\textension_len = ntohs(*((u_int16_t*)&packet->payload[offset+2]));\n\n\tif(ja3.server.num_tls_extension < MAX_NUM_JA3)\n\t ja3.server.tls_extension[ja3.server.num_tls_extension++] = extension_id;\n\n#ifdef DEBUG_TLS\n\tprintf(\"TLS [server][extension_id: %u/0x%04X][len: %u]\\n\",\n\t extension_id, extension_id, extension_len);\n#endif\n\n\tif(extension_id == 43 /* supported versions */) {\n\t if(extension_len >= 2) {\n\t u_int16_t tls_version = ntohs(*((u_int16_t*)&packet->payload[offset+4]));\n\n#ifdef DEBUG_TLS\n\t printf(\"TLS [server] [TLS version: 0x%04X]\\n\", tls_version);\n#endif\n\n\t flow->protos.tls_quic_stun.tls_quic.ssl_version = ja3.server.tls_supported_version = tls_version;\n\t }\n\t} else if(extension_id == 16 /* application_layer_protocol_negotiation (ALPN) */) {\n\t u_int16_t s_offset = offset+4;\n\t u_int16_t tot_alpn_len = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\t char alpn_str[256];\n\t u_int8_t alpn_str_len = 0, i;\n\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [ALPN: block_len=%u/len=%u]\\n\", extension_len, tot_alpn_len);\n#endif\n\t s_offset += 2;\n\t tot_alpn_len += s_offset;\n\n\t while(s_offset < tot_alpn_len && s_offset < total_len) {\n\t u_int8_t alpn_i, alpn_len = packet->payload[s_offset++];\n\n\t if((s_offset + alpn_len) <= tot_alpn_len) {\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [ALPN: %u]\\n\", alpn_len);\n#endif\n\n\t if((alpn_str_len+alpn_len+1) < (sizeof(alpn_str)-1)) {\n\t if(alpn_str_len > 0) {\n\t alpn_str[alpn_str_len] = ',';\n\t alpn_str_len++;\n\t }\n\n\t for(alpn_i=0; alpn_ipayload[s_offset+alpn_i];\n\t }\n\n\t s_offset += alpn_len, alpn_str_len += alpn_len;;\n\t } else {\n\t ndpi_set_risk(flow, NDPI_TLS_UNCOMMON_ALPN);\n\t break;\n\t }\n\t } else {\n\t ndpi_set_risk(flow, NDPI_TLS_UNCOMMON_ALPN);\n\t break;\n\t }\n\t } /* while */\n\n\t alpn_str[alpn_str_len] = '\\0';\n\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [ALPN: %s][len: %u]\\n\", alpn_str, alpn_str_len);\n#endif\n\t if(flow->protos.tls_quic_stun.tls_quic.alpn == NULL)\n\t flow->protos.tls_quic_stun.tls_quic.alpn = ndpi_strdup(alpn_str);\n\n\t if(flow->protos.tls_quic_stun.tls_quic.alpn != NULL)\n\t tlsCheckUncommonALPN(flow);\n\n\t snprintf(ja3.server.alpn, sizeof(ja3.server.alpn), \"%s\", alpn_str);\n\n\t /* Replace , with - as in JA3 */\n\t for(i=0; ja3.server.alpn[i] != '\\0'; i++)\n\t if(ja3.server.alpn[i] == ',') ja3.server.alpn[i] = '-';\n\t} else if(extension_id == 11 /* ec_point_formats groups */) {\n\t u_int16_t s_offset = offset+4 + 1;\n\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [EllipticCurveFormat: len=%u]\\n\", extension_len);\n#endif\n\t if((s_offset+extension_len-1) <= total_len) {\n\t for(i=0; ipayload[s_offset+i];\n\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [EllipticCurveFormat: %u]\\n\", s_group);\n#endif\n\n\t if(ja3.server.num_elliptic_curve_point_format < MAX_NUM_JA3)\n\t\tja3.server.elliptic_curve_point_format[ja3.server.num_elliptic_curve_point_format++] = s_group;\n\t else {\n\t\tinvalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\tprintf(\"Server TLS Invalid num elliptic %u\\n\", ja3.server.num_elliptic_curve_point_format);\n#endif\n\t }\n\t }\n\t } else {\n\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS Invalid len %u vs %u\\n\", s_offset+extension_len, total_len);\n#endif\n\t }\n\t}\n\n\ti += 4 + extension_len, offset += 4 + extension_len;\n } /* for */\n\n ja3_str_len = snprintf(ja3_str, sizeof(ja3_str), \"%u,\", ja3.server.tls_handshake_version);\n\n for(i=0; i 0) ? \"-\" : \"\", ja3.server.cipher[i]);\n\n\tif(rc <= 0) break; else ja3_str_len += rc;\n }\n\n rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, \",\");\n if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc;\n\n /* ********** */\n\n for(i=0; i 0) ? \"-\" : \"\", ja3.server.tls_extension[i]);\n\n\tif(rc <= 0) break; else ja3_str_len += rc;\n }\n\n if(ndpi_struct->enable_ja3_plus) {\n\tfor(i=0; i 0) ? \"-\" : \"\", ja3.server.elliptic_curve_point_format[i]);\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t}\n\n\tif(ja3.server.alpn[0] != '\\0') {\n\t rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, \",%s\", ja3.server.alpn);\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\t}\n\n#ifdef DEBUG_TLS\n\tprintf(\"[JA3+] Server: %s \\n\", ja3_str);\n#endif\n } else {\n#ifdef DEBUG_TLS\n\tprintf(\"[JA3] Server: %s \\n\", ja3_str);\n#endif\n }\n\n ndpi_MD5Init(&ctx);\n ndpi_MD5Update(&ctx, (const unsigned char *)ja3_str, strlen(ja3_str));\n ndpi_MD5Final(md5_hash, &ctx);\n\n for(i=0, j=0; i<16; i++) {\n\tint rc = snprintf(&flow->protos.tls_quic_stun.tls_quic.ja3_server[j],\n\t\t\t sizeof(flow->protos.tls_quic_stun.tls_quic.ja3_server)-j, \"%02x\", md5_hash[i]);\n\tif(rc <= 0) break; else j += rc;\n }\n\n#ifdef DEBUG_TLS\n printf(\"[JA3] Server: %s \\n\", flow->protos.tls_quic_stun.tls_quic.ja3_server);\n#endif\n } else if(handshake_type == 0x01 /* Client Hello */) {\n u_int16_t cipher_len, cipher_offset;\n u_int8_t cookie_len = 0;\n\n flow->protos.tls_quic_stun.tls_quic.ssl_version = ja3.client.tls_handshake_version = tls_version;\n if(flow->protos.tls_quic_stun.tls_quic.ssl_version < 0x0302) /* TLSv1.1 */\n\tndpi_set_risk(flow, NDPI_TLS_OBSOLETE_VERSION);\n\n if((session_id_len+base_offset+3) > packet->payload_packet_len)\n\treturn(0); /* Not found */\n\n if(!is_dtls) {\n\tcipher_len = packet->payload[session_id_len+base_offset+2] + (packet->payload[session_id_len+base_offset+1] << 8);\n\tcipher_offset = base_offset + session_id_len + 3;\n } else {\n\tcookie_len = packet->payload[base_offset+session_id_len+1];\n#ifdef DEBUG_TLS\n\tprintf(\"[JA3] Client: DTLS cookie len %d\\n\", cookie_len);\n#endif\n\tif((session_id_len+base_offset+cookie_len+4) > packet->payload_packet_len)\n\t return(0); /* Not found */\n\tcipher_len = ntohs(*((u_int16_t*)&packet->payload[base_offset+session_id_len+cookie_len+2]));\n\tcipher_offset = base_offset + session_id_len + cookie_len + 4;\n }\n\n#ifdef DEBUG_TLS\n printf(\"Client TLS [client cipher_len: %u][tls_version: 0x%04X]\\n\", cipher_len, tls_version);\n#endif\n\n if((cipher_offset+cipher_len) <= total_len) {\n\tu_int8_t safari_ciphers = 0, chrome_ciphers = 0;\n\n\tfor(i=0; ipayload[cipher_offset+i];\n\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS [cipher suite: %u/0x%04X] [%d/%u]\\n\", ntohs(*id), ntohs(*id), i, cipher_len);\n#endif\n\t if((*id == 0) || (packet->payload[cipher_offset+i] != packet->payload[cipher_offset+i+1])) {\n\t u_int16_t cipher_id = ntohs(*id);\n\t /*\n\t Skip GREASE [https://tools.ietf.org/id/draft-ietf-tls-grease-01.html]\n\t https://engineering.salesforce.com/tls-fingerprinting-with-ja3-and-ja3s-247362855967\n\t */\n\n\t if(ja3.client.num_cipher < MAX_NUM_JA3)\n\t ja3.client.cipher[ja3.client.num_cipher++] = cipher_id;\n\t else {\n\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS Invalid cipher %u\\n\", ja3.client.num_cipher);\n#endif\n\t }\n\n\t switch(cipher_id) {\n\t case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:\n\t case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:\n\t safari_ciphers++;\n\t break;\n\n\t case TLS_CIPHER_GREASE_RESERVED_0:\n\t case TLS_AES_128_GCM_SHA256:\n\t case TLS_AES_256_GCM_SHA384:\n\t case TLS_CHACHA20_POLY1305_SHA256:\n\t chrome_ciphers++;\n\t break;\n\n\t case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:\n\t case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:\n\t case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:\n\t case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:\n\t case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:\n\t case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:\n\t case TLS_RSA_WITH_AES_128_CBC_SHA:\n\t case TLS_RSA_WITH_AES_256_CBC_SHA:\n\t case TLS_RSA_WITH_AES_128_GCM_SHA256:\n\t case TLS_RSA_WITH_AES_256_GCM_SHA384:\n\t safari_ciphers++, chrome_ciphers++;\n\t break;\n\t }\n\t }\n\n\t i += 2;\n\t} /* for */\n\n\tif(chrome_ciphers == 13)\n\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_chrome_tls = 1;\n\telse if(safari_ciphers == 12)\n\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_safari_tls = 1;\n } else {\n\tinvalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\tprintf(\"Client TLS Invalid len %u vs %u\\n\", (cipher_offset+cipher_len), total_len);\n#endif\n }\n\n offset = base_offset + session_id_len + cookie_len + cipher_len + 2;\n offset += (!is_dtls) ? 1 : 2;\n\n if(offset < total_len) {\n\tu_int16_t compression_len;\n\tu_int16_t extensions_len;\n\n\tcompression_len = packet->payload[offset];\n\toffset++;\n\n#ifdef DEBUG_TLS\n\tprintf(\"Client TLS [compression_len: %u]\\n\", compression_len);\n#endif\n\n\t// offset += compression_len + 3;\n\toffset += compression_len;\n\n\tif(offset+1 < total_len) {\n\t extensions_len = ntohs(*((u_int16_t*)&packet->payload[offset]));\n\t offset += 2;\n\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS [extensions_len: %u]\\n\", extensions_len);\n#endif\n\n\t if((extensions_len+offset) <= total_len) {\n\t /* Move to the first extension\n\t Type is u_int to avoid possible overflow on extension_len addition */\n\t u_int extension_offset = 0;\n\t u_int32_t j;\n\n\t while(extension_offset < extensions_len &&\n\t\t offset+extension_offset+4 <= total_len) {\n\t u_int16_t extension_id, extension_len, extn_off = offset+extension_offset;\n\n\n\t extension_id = ntohs(*((u_int16_t*)&packet->payload[offset+extension_offset]));\n\t extension_offset += 2;\n\n\t extension_len = ntohs(*((u_int16_t*)&packet->payload[offset+extension_offset]));\n\t extension_offset += 2;\n\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS [extension_id: %u][extension_len: %u]\\n\", extension_id, extension_len);\n#endif\n\n\t if((extension_id == 0) || (packet->payload[extn_off] != packet->payload[extn_off+1])) {\n\t\t/* Skip GREASE */\n\n\t\tif(ja3.client.num_tls_extension < MAX_NUM_JA3)\n\t\t ja3.client.tls_extension[ja3.client.num_tls_extension++] = extension_id;\n\t\telse {\n\t\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS Invalid extensions %u\\n\", ja3.client.num_tls_extension);\n#endif\n\t\t}\n\t }\n\n\t if(extension_id == 0 /* server name */) {\n\t\tu_int16_t len;\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"[TLS] Extensions: found server name\\n\");\n#endif\n\t\tif((offset+extension_offset+4) < packet->payload_packet_len) {\n\n\t\t len = (packet->payload[offset+extension_offset+3] << 8) + packet->payload[offset+extension_offset+4];\n\t\t len = (u_int)ndpi_min(len, sizeof(buffer)-1);\n\n\t\t if((offset+extension_offset+5+len) <= packet->payload_packet_len) {\n\t\t strncpy(buffer, (char*)&packet->payload[offset+extension_offset+5], len);\n\t\t buffer[len] = '\\0';\n\n\t\t cleanupServerName(buffer, sizeof(buffer));\n\n\t\t snprintf(flow->protos.tls_quic_stun.tls_quic.client_requested_server_name,\n\t\t\t sizeof(flow->protos.tls_quic_stun.tls_quic.client_requested_server_name),\n\t\t\t \"%s\", buffer);\n#ifdef DEBUG_TLS\n\t\t printf(\"[TLS] SNI: [%s]\\n\", buffer);\n#endif\n\t\t if(!is_quic) {\n\t\t if(ndpi_match_hostname_protocol(ndpi_struct, flow, NDPI_PROTOCOL_TLS, buffer, strlen(buffer)))\n\t\t flow->l4.tcp.tls.subprotocol_detected = 1;\n\t\t } else {\n\t\t if(ndpi_match_hostname_protocol(ndpi_struct, flow, NDPI_PROTOCOL_QUIC, buffer, strlen(buffer)))\n\t\t flow->l4.tcp.tls.subprotocol_detected = 1;\n\t\t }\n\n\t\t if(ndpi_check_dga_name(ndpi_struct, flow,\n\t\t\t\t\t flow->protos.tls_quic_stun.tls_quic.client_requested_server_name, 1)) {\n\t\t char *sni = flow->protos.tls_quic_stun.tls_quic.client_requested_server_name;\n\t\t int len = strlen(sni);\n\n#ifdef DEBUG_TLS\n\t\t printf(\"[TLS] SNI: (DGA) [%s]\\n\", flow->protos.tls_quic_stun.tls_quic.client_requested_server_name);\n#endif\n\n\t\t if((len >= 4)\n\t\t /* Check if it ends in .com or .net */\n\t\t && ((strcmp(&sni[len-4], \".com\") == 0) || (strcmp(&sni[len-4], \".net\") == 0))\n\t\t && (strncmp(sni, \"www.\", 4) == 0)) /* Not starting with www.... */\n\t\t ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_TOR, NDPI_PROTOCOL_TLS);\n\t\t } else {\n#ifdef DEBUG_TLS\n\t\t printf(\"[TLS] SNI: (NO DGA) [%s]\\n\", flow->protos.tls_quic_stun.tls_quic.client_requested_server_name);\n#endif\n\t\t }\n\t\t } else {\n#ifdef DEBUG_TLS\n\t\t printf(\"[TLS] Extensions server len too short: %u vs %u\\n\",\n\t\t\t offset+extension_offset+5+len,\n\t\t\t packet->payload_packet_len);\n#endif\n\t\t }\n\t\t}\n\t } else if(extension_id == 10 /* supported groups */) {\n\t\tu_int16_t s_offset = offset+extension_offset + 2;\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [EllipticCurveGroups: len=%u]\\n\", extension_len);\n#endif\n\n\t\tif((s_offset+extension_len-2) <= total_len) {\n\t\t for(i=0; ipayload[s_offset+i]));\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [EllipticCurve: %u/0x%04X]\\n\", s_group, s_group);\n#endif\n\t\t if((s_group == 0) || (packet->payload[s_offset+i] != packet->payload[s_offset+i+1])) {\n\t\t /* Skip GREASE */\n\t\t if(ja3.client.num_elliptic_curve < MAX_NUM_JA3)\n\t\t\tja3.client.elliptic_curve[ja3.client.num_elliptic_curve++] = s_group;\n\t\t else {\n\t\t\tinvalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t\tprintf(\"Client TLS Invalid num elliptic %u\\n\", ja3.client.num_elliptic_curve);\n#endif\n\t\t }\n\t\t }\n\n\t\t i += 2;\n\t\t }\n\t\t} else {\n\t\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS Invalid len %u vs %u\\n\", (s_offset+extension_len-1), total_len);\n#endif\n\t\t}\n\t } else if(extension_id == 11 /* ec_point_formats groups */) {\n\t\tu_int16_t s_offset = offset+extension_offset + 1;\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [EllipticCurveFormat: len=%u]\\n\", extension_len);\n#endif\n\t\tif((s_offset+extension_len-1) <= total_len) {\n\t\t for(i=0; ipayload[s_offset+i];\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [EllipticCurveFormat: %u]\\n\", s_group);\n#endif\n\n\t\t if(ja3.client.num_elliptic_curve_point_format < MAX_NUM_JA3)\n\t\t ja3.client.elliptic_curve_point_format[ja3.client.num_elliptic_curve_point_format++] = s_group;\n\t\t else {\n\t\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS Invalid num elliptic %u\\n\", ja3.client.num_elliptic_curve_point_format);\n#endif\n\t\t }\n\t\t }\n\t\t} else {\n\t\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS Invalid len %u vs %u\\n\", s_offset+extension_len, total_len);\n#endif\n\t\t}\n\t } else if(extension_id == 13 /* signature algorithms */) {\n\t\tu_int16_t s_offset = offset+extension_offset, safari_signature_algorithms = 0, chrome_signature_algorithms = 0;\n\t\tu_int16_t tot_signature_algorithms_len = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [SIGNATURE_ALGORITHMS: block_len=%u/len=%u]\\n\", extension_len, tot_signature_algorithms_len);\n#endif\n\n\t\ts_offset += 2;\n\t\ttot_signature_algorithms_len = ndpi_min((sizeof(ja3.client.signature_algorithms) / 2) - 1, tot_signature_algorithms_len);\n\n#ifdef TLS_HANDLE_SIGNATURE_ALGORITMS\n\t\tflow->protos.tls_quic_stun.tls_quic.num_tls_signature_algorithms = ndpi_min(tot_signature_algorithms_len / 2, MAX_NUM_TLS_SIGNATURE_ALGORITHMS);\n\n\t\tmemcpy(flow->protos.tls_quic_stun.tls_quic.client_signature_algorithms,\n\t\t &packet->payload[s_offset], 2 /* 16 bit */*flow->protos.tls_quic_stun.tls_quic.num_tls_signature_algorithms);\n#endif\n\n\t\tfor(i=0; ipayload[s_offset+i]);\n\n\t\t if(rc < 0) break;\n\t\t}\n\n\t\tfor(i=0; ipayload[s_offset+i]));\n\n\t\t // printf(\"=>> %04X\\n\", cipher_id);\n\n\t\t switch(cipher_id) {\n\t\t case ECDSA_SECP521R1_SHA512:\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_firefox_tls = 1;\n\t\t break;\n\n\t\t case ECDSA_SECP256R1_SHA256:\n\t\t case ECDSA_SECP384R1_SHA384:\n\t\t case RSA_PKCS1_SHA256:\n\t\t case RSA_PKCS1_SHA384:\n\t\t case RSA_PKCS1_SHA512:\n\t\t case RSA_PSS_RSAE_SHA256:\n\t\t case RSA_PSS_RSAE_SHA384:\n\t\t case RSA_PSS_RSAE_SHA512:\n\t\t chrome_signature_algorithms++, safari_signature_algorithms++;\n\t\t break;\n\t\t }\n\t\t}\n\n\t\tif(flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_firefox_tls)\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_safari_tls = 0,\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_chrome_tls = 0;\n\n\t\tif(safari_signature_algorithms != 8)\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_safari_tls = 0;\n\n\t\tif(chrome_signature_algorithms != 8)\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_chrome_tls = 0;\n\n\t\tja3.client.signature_algorithms[i*2] = '\\0';\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [SIGNATURE_ALGORITHMS: %s]\\n\", ja3.client.signature_algorithms);\n#endif\n\t } else if(extension_id == 16 /* application_layer_protocol_negotiation */) {\n\t\tu_int16_t s_offset = offset+extension_offset;\n\t\tu_int16_t tot_alpn_len = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\t\tchar alpn_str[256];\n\t\tu_int8_t alpn_str_len = 0, i;\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [ALPN: block_len=%u/len=%u]\\n\", extension_len, tot_alpn_len);\n#endif\n\t\ts_offset += 2;\n\t\ttot_alpn_len += s_offset;\n\n\t\twhile(s_offset < tot_alpn_len && s_offset < total_len) {\n\t\t u_int8_t alpn_i, alpn_len = packet->payload[s_offset++];\n\n\t\t if((s_offset + alpn_len) <= tot_alpn_len &&\n\t\t (s_offset + alpn_len) <= total_len) {\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [ALPN: %u]\\n\", alpn_len);\n#endif\n\n\t\t if((alpn_str_len+alpn_len+1) < (sizeof(alpn_str)-1)) {\n\t\t if(alpn_str_len > 0) {\n\t\t\talpn_str[alpn_str_len] = ',';\n\t\t\talpn_str_len++;\n\t\t }\n\n\t\t for(alpn_i=0; alpn_ipayload[s_offset+alpn_i];\n\n\t\t s_offset += alpn_len, alpn_str_len += alpn_len;;\n\t\t } else\n\t\t break;\n\t\t } else\n\t\t break;\n\t\t} /* while */\n\n\t\talpn_str[alpn_str_len] = '\\0';\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [ALPN: %s][len: %u]\\n\", alpn_str, alpn_str_len);\n#endif\n\t\tif(flow->protos.tls_quic_stun.tls_quic.alpn == NULL)\n\t\t flow->protos.tls_quic_stun.tls_quic.alpn = ndpi_strdup(alpn_str);\n\n\t\tsnprintf(ja3.client.alpn, sizeof(ja3.client.alpn), \"%s\", alpn_str);\n\n\t\t/* Replace , with - as in JA3 */\n\t\tfor(i=0; ja3.client.alpn[i] != '\\0'; i++)\n\t\t if(ja3.client.alpn[i] == ',') ja3.client.alpn[i] = '-';\n\n\t } else if(extension_id == 43 /* supported versions */) {\n\t\tu_int16_t s_offset = offset+extension_offset;\n\t\tu_int8_t version_len = packet->payload[s_offset];\n\t\tchar version_str[256];\n\t\tu_int8_t version_str_len = 0;\n\t\tversion_str[0] = 0;\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [TLS version len: %u]\\n\", version_len);\n#endif\n\n\t\tif(version_len == (extension_len-1)) {\n\t\t u_int8_t j;\n\t\t u_int16_t supported_versions_offset = 0;\n\n\t\t s_offset++;\n\n\t\t // careful not to overflow and loop forever with u_int8_t\n\t\t for(j=0; j+1payload[s_offset+j]));\n\t\t u_int8_t unknown_tls_version;\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [TLS version: %s/0x%04X]\\n\",\n\t\t\t ndpi_ssl_version2str(flow, tls_version, &unknown_tls_version), tls_version);\n#endif\n\n\t\t if((version_str_len+8) < sizeof(version_str)) {\n\t\t int rc = snprintf(&version_str[version_str_len],\n\t\t\t\t\tsizeof(version_str) - version_str_len, \"%s%s\",\n\t\t\t\t\t(version_str_len > 0) ? \",\" : \"\",\n\t\t\t\t\tndpi_ssl_version2str(flow, tls_version, &unknown_tls_version));\n\t\t if(rc <= 0)\n\t\t\tbreak;\n\t\t else\n\t\t\tversion_str_len += rc;\n\n\t\t rc = snprintf(&ja3.client.supported_versions[supported_versions_offset],\n\t\t\t\t sizeof(ja3.client.supported_versions)-supported_versions_offset,\n\t\t\t\t \"%s%04X\", (j > 0) ? \"-\" : \"\", tls_version);\n\n\t\t if(rc > 0)\n\t\t\tsupported_versions_offset += rc;\n\t\t }\n\t\t }\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [SUPPORTED_VERSIONS: %s]\\n\", ja3.client.supported_versions);\n#endif\n\n\t\t if(flow->protos.tls_quic_stun.tls_quic.tls_supported_versions == NULL)\n\t\t flow->protos.tls_quic_stun.tls_quic.tls_supported_versions = ndpi_strdup(version_str);\n\t\t}\n\t } else if(extension_id == 65486 /* encrypted server name */) {\n\t\t/*\n\t\t - https://tools.ietf.org/html/draft-ietf-tls-esni-06\n\t\t - https://blog.cloudflare.com/encrypted-sni/\n\t\t*/\n\t\tu_int16_t e_offset = offset+extension_offset;\n\t\tu_int16_t initial_offset = e_offset;\n\t\tu_int16_t e_sni_len, cipher_suite = ntohs(*((u_int16_t*)&packet->payload[e_offset]));\n\n\t\tflow->protos.tls_quic_stun.tls_quic.encrypted_sni.cipher_suite = cipher_suite;\n\n\t\te_offset += 2; /* Cipher suite len */\n\n\t\t/* Key Share Entry */\n\t\te_offset += 2; /* Group */\n\t\te_offset += ntohs(*((u_int16_t*)&packet->payload[e_offset])) + 2; /* Lenght */\n\n\t\tif((e_offset+4) < packet->payload_packet_len) {\n\t\t /* Record Digest */\n\t\t e_offset += ntohs(*((u_int16_t*)&packet->payload[e_offset])) + 2; /* Lenght */\n\n\t\t if((e_offset+4) < packet->payload_packet_len) {\n\t\t e_sni_len = ntohs(*((u_int16_t*)&packet->payload[e_offset]));\n\t\t e_offset += 2;\n\n\t\t if((e_offset+e_sni_len-extension_len-initial_offset) >= 0 &&\n\t\t e_offset+e_sni_len < packet->payload_packet_len) {\n#ifdef DEBUG_ENCRYPTED_SNI\n\t\t printf(\"Client TLS [Encrypted Server Name len: %u]\\n\", e_sni_len);\n#endif\n\n\t\t if(flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni == NULL) {\n\t\t\tflow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni = (char*)ndpi_malloc(e_sni_len*2+1);\n\n\t\t\tif(flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni) {\n\t\t\t u_int16_t i, off;\n\n\t\t\t for(i=e_offset, off=0; i<(e_offset+e_sni_len); i++) {\n\t\t\t int rc = sprintf(&flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni[off], \"%02X\", packet->payload[i] & 0XFF);\n\n\t\t\t if(rc <= 0) {\n\t\t\t flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni[off] = '\\0';\n\t\t\t break;\n\t\t\t } else\n\t\t\t off += rc;\n\t\t\t }\n\t\t\t}\n\t\t }\n\t\t }\n\t\t }\n\t\t}\n\t } else if(extension_id == 65445 || /* QUIC transport parameters (drafts version) */\n\t\t extension_id == 57) { /* QUIC transport parameters (final version) */\n\t\tu_int16_t s_offset = offset+extension_offset;\n\t\tuint16_t final_offset;\n\t\tint using_var_int = is_version_with_var_int_transport_params(quic_version);\n\n\t\tif(!using_var_int) {\n\t\t if(s_offset+1 >= total_len) {\n\t\t final_offset = 0; /* Force skipping extension */\n\t\t } else {\n\t\t u_int16_t seq_len = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\t\t s_offset += 2;\n\t final_offset = MIN(total_len, s_offset + seq_len);\n\t\t }\n\t\t} else {\n\t final_offset = MIN(total_len, s_offset + extension_len);\n\t\t}\n\n\t\twhile(s_offset < final_offset) {\n\t\t u_int64_t param_type, param_len;\n\n if(!using_var_int) {\n\t\t if(s_offset+3 >= final_offset)\n\t\t break;\n\t\t param_type = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\t\t param_len = ntohs(*((u_int16_t*)&packet->payload[s_offset + 2]));\n\t\t s_offset += 4;\n\t\t } else {\n\t\t if(s_offset >= final_offset ||\n\t\t (s_offset + quic_len_buffer_still_required(packet->payload[s_offset])) >= final_offset)\n\t\t break;\n\t\t s_offset += quic_len(&packet->payload[s_offset], ¶m_type);\n\n\t\t if(s_offset >= final_offset ||\n\t\t (s_offset + quic_len_buffer_still_required(packet->payload[s_offset])) >= final_offset)\n\t\t break;\n\t\t s_offset += quic_len(&packet->payload[s_offset], ¶m_len);\n\t\t }\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [QUIC TP: Param 0x%x Len %d]\\n\", (int)param_type, (int)param_len);\n#endif\n\t\t if(s_offset+param_len > final_offset)\n\t\t break;\n\n\t\t if(param_type==0x3129) {\n#ifdef DEBUG_TLS\n\t\t printf(\"UA [%.*s]\\n\", (int)param_len, &packet->payload[s_offset]);\n#endif\n\t\t http_process_user_agent(ndpi_struct, flow,\n\t\t\t\t\t &packet->payload[s_offset], param_len);\n\t\t break;\n\t\t }\n\t\t s_offset += param_len;\n\t\t}\n\t }\n\n\t extension_offset += extension_len; /* Move to the next extension */\n\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS [extension_offset/len: %u/%u]\\n\", extension_offset, extension_len);\n#endif\n\t } /* while */\n\n\t if(!invalid_ja3) {\n\t int rc;\n\n\t compute_ja3c:\n\t ja3_str_len = snprintf(ja3_str, sizeof(ja3_str), \"%u,\", ja3.client.tls_handshake_version);\n\n\t for(i=0; i 0) ? \"-\" : \"\", ja3.client.cipher[i]);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t }\n\n\t rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, \",\");\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\n\t /* ********** */\n\n\t for(i=0; i 0) ? \"-\" : \"\", ja3.client.tls_extension[i]);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t }\n\n\t rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, \",\");\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\n\t /* ********** */\n\n\t for(i=0; i 0) ? \"-\" : \"\", ja3.client.elliptic_curve[i]);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t }\n\n\t rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, \",\");\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\n\t for(i=0; i 0) ? \"-\" : \"\", ja3.client.elliptic_curve_point_format[i]);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t }\n\n\t if(ndpi_struct->enable_ja3_plus) {\n\t\trc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len,\n\t\t\t \",%s,%s,%s\", ja3.client.signature_algorithms, ja3.client.supported_versions, ja3.client.alpn);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\t }\n\n#ifdef DEBUG_JA3C\n\t printf(\"[JA3+] Client: %s \\n\", ja3_str);\n#endif\n\n\t ndpi_MD5Init(&ctx);\n\t ndpi_MD5Update(&ctx, (const unsigned char *)ja3_str, strlen(ja3_str));\n\t ndpi_MD5Final(md5_hash, &ctx);\n\n\t for(i=0, j=0; i<16; i++) {\n\t\trc = snprintf(&flow->protos.tls_quic_stun.tls_quic.ja3_client[j],\n\t\t\t sizeof(flow->protos.tls_quic_stun.tls_quic.ja3_client)-j, \"%02x\",\n\t\t\t md5_hash[i]);\n\t\tif(rc > 0) j += rc; else break;\n\t }\n\n#ifdef DEBUG_JA3C\n\t printf(\"[JA3] Client: %s \\n\", flow->protos.tls_quic_stun.tls_quic.ja3_client);\n#endif\n\n\t if(ndpi_struct->malicious_ja3_automa.ac_automa != NULL) {\n\t\tu_int16_t rc1 = ndpi_match_string(ndpi_struct->malicious_ja3_automa.ac_automa,\n\t\t\t\t\t\t flow->protos.tls_quic_stun.tls_quic.ja3_client);\n\n\t\tif(rc1 > 0)\n\t\t ndpi_set_risk(flow, NDPI_MALICIOUS_JA3);\n\t }\n\t }\n\n\t /* Before returning to the caller we need to make a final check */\n\t if((flow->protos.tls_quic_stun.tls_quic.ssl_version >= 0x0303) /* >= TLSv1.2 */\n\t && (flow->protos.tls_quic_stun.tls_quic.alpn == NULL) /* No ALPN */) {\n\t ndpi_set_risk(flow, NDPI_TLS_NOT_CARRYING_HTTPS);\n\t }\n\n\t /* Suspicious Domain Fronting:\n\t https://github.com/SixGenInc/Noctilucent/blob/master/docs/ */\n\t if(flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni &&\n\t flow->protos.tls_quic_stun.tls_quic.client_requested_server_name[0] != '\\0') {\n\t ndpi_set_risk(flow, NDPI_TLS_SUSPICIOUS_ESNI_USAGE);\n\t }\n\n\t /* Add check for missing SNI */\n\t if((flow->protos.tls_quic_stun.tls_quic.client_requested_server_name[0] == 0)\n\t && (flow->protos.tls_quic_stun.tls_quic.ssl_version >= 0x0302) /* TLSv1.1 */\n\t && (flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni == NULL) /* No ESNI */\n\t ) {\n\t /* This is a bit suspicious */\n\t ndpi_set_risk(flow, NDPI_TLS_MISSING_SNI);\n\t }\n\n\t return(2 /* Client Certificate */);\n\t } else {\n#ifdef DEBUG_TLS\n\t printf(\"[TLS] Client: too short [%u vs %u]\\n\",\n\t\t (extensions_len+offset), total_len);\n#endif\n\t }\n\t} else if(offset == total_len) {\n\t /* TLS does not have extensions etc */\n\t goto compute_ja3c;\n\t}\n } else {\n#ifdef DEBUG_TLS\n\tprintf(\"[JA3] Client: invalid length detected\\n\");\n#endif\n }\n }\n }\n\n return(0); /* Not found */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Added further checks'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _dl_dst_substitute (struct link_map *l, const char *name, char *result,\n\t\t int is_path)\n{\n char *last_elem, *wp;\n\n /* Now fill the result path. While copying over the string we keep\n track of the start of the last path element. When we come accross\n a DST we copy over the value or (if the value is not available)\n leave the entire path element out. */\n last_elem = wp = result;\n\n do\n {\n if (*name == '$')\n\t{\n\t const char *repl;\n\t size_t len;\n\n\t if ((((strncmp (&name[1], \"ORIGIN\", 6) == 0 && (len = 7) != 0)\n\t\t|| (strncmp (&name[1], \"PLATFORM\", 8) == 0 && (len = 9) != 0))\n\t && (name[len] == '\\0' || name[len] == '/'\n\t\t || (is_path && name[len] == ':')))\n\t || (name[1] == '{'\n\t\t && ((strncmp (&name[2], \"ORIGIN}\", 7) == 0 && (len = 9) != 0)\n\t\t || (strncmp (&name[2], \"PLATFORM}\", 9) == 0\n\t\t\t && (len = 11) != 0))))\n\t {\n\t repl = ((len == 7 || name[2] == 'O')\n\t\t ? (__libc_enable_secure ? NULL : l->l_origin)\n\t\t : _dl_platform);\n\n\t if (repl != NULL && repl != (const char *) -1)\n\t\t{\n\t\t wp = __stpcpy (wp, repl);\n\t\t name += len;\n\t\t}\n\t else\n\t\t{\n\t\t /* We cannot use this path element, the value of the\n\t\t replacement is unknown. */\n\t\t wp = last_elem;\n\t\t name += len;\n\t\t while (*name != '\\0' && (!is_path || *name != ':'))\n\t\t ++name;\n\t\t}\n\t }\n\t else\n\t /* No DST we recognize. */\n\t *wp++ = *name++;\n\t}\n else if (is_path && *name == ':')\n\t{\n\t *wp++ = *name++;\n\t last_elem = wp;\n\t}\n else\n\t*wp++ = *name++;\n }\n while (*name != '\\0');\n\n *wp = '\\0';\n\n return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-252'], 'message': 'Update.\n\n1999-11-09 Ulrich Drepper \n\n\t* elf/dl-load.c (_dl_dst_count): Allow $ORIGIN to point to\n\tdirectory with the reference since this is as secure as using the\n\tobject with the dependency.\n\t(_dl_dst_substitute): Likewise.\n\n\t* elf/dl-load.c (_dl_dst_count): Change strings in first two\n\tstrncmp calls to allow reuse.\n\t(_dl_dst_substitute): Likewise.\n\n1999-11-01 Arnold D. Robbins \n\n\t* posix/regex.c (init_syntax_once): move below definition of\n\tISALNUM etc., then use ISALNUM to init the table, so that\n\tthe word ops will work if i18n'ed.\n\t(SYNTAX): And subscript with 0xFF for 8bit character sets.\n\n1999-11-09 Andreas Jaeger \n\n\t* sysdeps/unix/getlogin_r.c (getlogin_r): Sync with getlogin\n\timplementation for ttyname_r call; fix inverted condition; return\n\tut_user. Closes PR libc/1438.\n\n1999-11-09 Ulrich Drepper \n\n\t* timezone/checktab.awk: Update from tzcode1999h.\n\t* timezone/africa: Update from tzdata1999i.\n\t* timezone/asia: Likewise.\n\t* timezone/australasia: Likewise.\n\t* timezone/backward: Likewise.\n\t* timezone/europe: Likewise.\n\t* timezone/northamerica: Likewise.\n\t* timezone/southamerica: Likewise.\n\t* timezone/iso3166.tab: Likewise.\n\t* timezone/zone.tab: Likewise.\n\n\t* sysdeps/unix/sysv/linux/bits/resource.h: Define values also as\n\tmacros. Patch by brg@csua.berkeley.edu [PR libc/1439].\n\n1999-11-09 Andreas Jaeger \n\n\t* posix/Makefile (tests): Added tst-getlogin.\n\n\t* posix/tst-getlogin.c: New file, contains simple tests for\n\tgetlogin and getlogin_r.\n\n1999-11-09 Andreas Schwab \n\n\t* misc/syslog.c: For LOG_PERROR only append a newline if\n\tnecessary.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PJ_DEF(pj_status_t) pjmedia_rtcp_fb_parse_pli(\n\t\t\t\t\tconst void *buf,\n\t\t\t\t\tpj_size_t length)\n{\n pjmedia_rtcp_common *hdr = (pjmedia_rtcp_common*) buf;\n\n PJ_ASSERT_RETURN(buf, PJ_EINVAL);\n\n if (length < 12)\n \treturn PJ_ETOOSMALL;\n\n /* PLI uses pt==RTCP_PSFB and FMT==1 */\n if (hdr->pt != RTCP_PSFB || hdr->count != 1)\n\treturn PJ_ENOTFOUND;\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: size_t OpenMP4SourceUDTA(char *filename)\n{\n\tmp4object *mp4 = (mp4object *)malloc(sizeof(mp4object));\n\tif (mp4 == NULL) return 0;\n\n\tmemset(mp4, 0, sizeof(mp4object));\n\n#ifdef _WINDOWS\n\tfopen_s(&mp4->mediafp, filename, \"rb\");\n#else\n\tmp4->mediafp = fopen(filename, \"rb\");\n#endif\n\n\tif (mp4->mediafp)\n\t{\n\t\tuint32_t qttag, qtsize32, len;\n\t\tint32_t nest = 0;\n\t\tuint64_t nestsize[MAX_NEST_LEVEL] = { 0 };\n\t\tuint64_t lastsize = 0, qtsize;\n\n\t\tdo\n\t\t{\n\t\t\tlen = fread(&qtsize32, 1, 4, mp4->mediafp);\n\t\t\tlen += fread(&qttag, 1, 4, mp4->mediafp);\n\t\t\tif (len == 8)\n\t\t\t{\n\t\t\t\tif (!GPMF_VALID_FOURCC(qttag))\n\t\t\t\t{\n\t\t\t\t\tLONGSEEK(mp4->mediafp, lastsize - 8 - 8, SEEK_CUR);\n\n\t\t\t\t\tNESTSIZE(lastsize - 8);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tqtsize32 = BYTESWAP32(qtsize32);\n\n\t\t\t\tif (qtsize32 == 1) // 64-bit Atom\n\t\t\t\t{\n\t\t\t\t\tfread(&qtsize, 1, 8, mp4->mediafp);\n\t\t\t\t\tqtsize = BYTESWAP64(qtsize) - 8;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tqtsize = qtsize32;\n\n\t\t\t\tnest++;\n\n\t\t\t\tif (qtsize < 8) break;\n\t\t\t\tif (nest >= MAX_NEST_LEVEL) break;\n\n\t\t\t\tnestsize[nest] = qtsize;\n\t\t\t\tlastsize = qtsize;\n\n\t\t\t\tif (qttag == MAKEID('m', 'd', 'a', 't') ||\n\t\t\t\t\tqttag == MAKEID('f', 't', 'y', 'p'))\n\t\t\t\t{\n\t\t\t\t\tLONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR);\n\t\t\t\t\tNESTSIZE(qtsize);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (qttag == MAKEID('G', 'P', 'M', 'F'))\n\t\t\t\t{\n\t\t\t\t\tmp4->videolength += 1.0;\n\t\t\t\t\tmp4->metadatalength += 1.0;\n\n\t\t\t\t\tmp4->indexcount = (int)mp4->metadatalength;\n\n\t\t\t\t\tmp4->metasizes = (uint32_t *)malloc(mp4->indexcount * 4 + 4); memset(mp4->metasizes, 0, mp4->indexcount * 4 + 4);\n\t\t\t\t\tmp4->metaoffsets = (uint64_t *)malloc(mp4->indexcount * 8 + 8); memset(mp4->metaoffsets, 0, mp4->indexcount * 8 + 8);\n\n\t\t\t\t\tmp4->metasizes[0] = (int)qtsize - 8;\n\t\t\t\t\tmp4->metaoffsets[0] = ftell(mp4->mediafp);\n\t\t\t\t\tmp4->metasize_count = 1;\n\n\t\t\t\t\treturn (size_t)mp4; // not an MP4, RAW GPMF which has not inherent timing, assigning a during of 1second.\n\t\t\t\t}\n\t\t\t\tif (qttag != MAKEID('m', 'o', 'o', 'v') && //skip over all but these atoms\n\t\t\t\t\tqttag != MAKEID('u', 'd', 't', 'a'))\n\t\t\t\t{\n\t\t\t\t\tLONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR);\n\t\t\t\t\tNESTSIZE(qtsize);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tNESTSIZE(8);\n\t\t\t\t}\n\t\t\t}\n\t\t} while (len > 0);\n\t}\n\treturn (size_t)mp4;\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: ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,\n\t\t\t\thandle_t *handle, unsigned int reserv_clstrs)\n{\n\tstruct buffer_head *bitmap_bh = NULL;\n\tstruct ext4_group_desc *gdp;\n\tstruct buffer_head *gdp_bh;\n\tstruct ext4_sb_info *sbi;\n\tstruct super_block *sb;\n\text4_fsblk_t block;\n\tint err, len;\n\n\tBUG_ON(ac->ac_status != AC_STATUS_FOUND);\n\tBUG_ON(ac->ac_b_ex.fe_len <= 0);\n\n\tsb = ac->ac_sb;\n\tsbi = EXT4_SB(sb);\n\n\tbitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);\n\tif (IS_ERR(bitmap_bh)) {\n\t\terr = PTR_ERR(bitmap_bh);\n\t\tbitmap_bh = NULL;\n\t\tgoto out_err;\n\t}\n\n\tBUFFER_TRACE(bitmap_bh, \"getting write access\");\n\terr = ext4_journal_get_write_access(handle, bitmap_bh);\n\tif (err)\n\t\tgoto out_err;\n\n\terr = -EIO;\n\tgdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);\n\tif (!gdp)\n\t\tgoto out_err;\n\n\text4_debug(\"using block group %u(%d)\\n\", ac->ac_b_ex.fe_group,\n\t\t\text4_free_group_clusters(sb, gdp));\n\n\tBUFFER_TRACE(gdp_bh, \"get_write_access\");\n\terr = ext4_journal_get_write_access(handle, gdp_bh);\n\tif (err)\n\t\tgoto out_err;\n\n\tblock = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);\n\n\tlen = EXT4_C2B(sbi, ac->ac_b_ex.fe_len);\n\tif (!ext4_data_block_valid(sbi, block, len)) {\n\t\text4_error(sb, \"Allocating blocks %llu-%llu which overlap \"\n\t\t\t \"fs metadata\", block, block+len);\n\t\t/* File system mounted not to panic on error\n\t\t * Fix the bitmap and return EFSCORRUPTED\n\t\t * We leak some of the blocks here.\n\t\t */\n\t\text4_lock_group(sb, ac->ac_b_ex.fe_group);\n\t\text4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,\n\t\t\t ac->ac_b_ex.fe_len);\n\t\text4_unlock_group(sb, ac->ac_b_ex.fe_group);\n\t\terr = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);\n\t\tif (!err)\n\t\t\terr = -EFSCORRUPTED;\n\t\tgoto out_err;\n\t}\n\n\text4_lock_group(sb, ac->ac_b_ex.fe_group);\n#ifdef AGGRESSIVE_CHECK\n\t{\n\t\tint i;\n\t\tfor (i = 0; i < ac->ac_b_ex.fe_len; i++) {\n\t\t\tBUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,\n\t\t\t\t\t\tbitmap_bh->b_data));\n\t\t}\n\t}\n#endif\n\text4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,\n\t\t ac->ac_b_ex.fe_len);\n\tif (ext4_has_group_desc_csum(sb) &&\n\t (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {\n\t\tgdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);\n\t\text4_free_group_clusters_set(sb, gdp,\n\t\t\t\t\t ext4_free_clusters_after_init(sb,\n\t\t\t\t\t\tac->ac_b_ex.fe_group, gdp));\n\t}\n\tlen = ext4_free_group_clusters(sb, gdp) - ac->ac_b_ex.fe_len;\n\text4_free_group_clusters_set(sb, gdp, len);\n\text4_block_bitmap_csum_set(sb, ac->ac_b_ex.fe_group, gdp, bitmap_bh);\n\text4_group_desc_csum_set(sb, ac->ac_b_ex.fe_group, gdp);\n\n\text4_unlock_group(sb, ac->ac_b_ex.fe_group);\n\tpercpu_counter_sub(&sbi->s_freeclusters_counter, ac->ac_b_ex.fe_len);\n\t/*\n\t * Now reduce the dirty block count also. Should not go negative\n\t */\n\tif (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))\n\t\t/* release all the reserved blocks if non delalloc */\n\t\tpercpu_counter_sub(&sbi->s_dirtyclusters_counter,\n\t\t\t\t reserv_clstrs);\n\n\tif (sbi->s_log_groups_per_flex) {\n\t\text4_group_t flex_group = ext4_flex_group(sbi,\n\t\t\t\t\t\t\t ac->ac_b_ex.fe_group);\n\t\tatomic64_sub(ac->ac_b_ex.fe_len,\n\t\t\t &sbi_array_rcu_deref(sbi, s_flex_groups,\n\t\t\t\t\t\t flex_group)->free_clusters);\n\t}\n\n\terr = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);\n\tif (err)\n\t\tgoto out_err;\n\terr = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);\n\nout_err:\n\tbrelse(bitmap_bh);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'ext4: check journal inode extents more carefully\n\nCurrently, system zones just track ranges of block, that are \"important\"\nfs metadata (bitmaps, group descriptors, journal blocks, etc.). This\nhowever complicates how extent tree (or indirect blocks) can be checked\nfor inodes that actually track such metadata - currently the journal\ninode but arguably we should be treating quota files or resize inode\nsimilarly. We cannot run __ext4_ext_check() on such metadata inodes when\nloading their extents as that would immediately trigger the validity\nchecks and so we just hack around that and special-case the journal\ninode. This however leads to a situation that a journal inode which has\nextent tree of depth at least one can have invalid extent tree that gets\nunnoticed until ext4_cache_extents() crashes.\n\nTo overcome this limitation, track inode number each system zone belongs\nto (0 is used for zones not belonging to any inode). We can then verify\ninode number matches the expected one when verifying extent tree and\nthus avoid the false errors. With this there's no need to to\nspecial-case journal inode during extent tree checking anymore so remove\nit.\n\nFixes: 0a944e8a6c66 (\"ext4: don't perform block validity checks on the journal inode\")\nReported-by: Wolfgang Frisch \nReviewed-by: Lukas Czerner \nSigned-off-by: Jan Kara \nLink: https://lore.kernel.org/r/20200728130437.7804-4-jack@suse.cz\nSigned-off-by: Theodore Ts'o '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ext4_data_block_valid_rcu(struct ext4_sb_info *sbi,\n\t\t\t\t struct ext4_system_blocks *system_blks,\n\t\t\t\t ext4_fsblk_t start_blk,\n\t\t\t\t unsigned int count)\n{\n\tstruct ext4_system_zone *entry;\n\tstruct rb_node *n;\n\n\tif ((start_blk <= le32_to_cpu(sbi->s_es->s_first_data_block)) ||\n\t (start_blk + count < start_blk) ||\n\t (start_blk + count > ext4_blocks_count(sbi->s_es)))\n\t\treturn 0;\n\n\tif (system_blks == NULL)\n\t\treturn 1;\n\n\tn = system_blks->root.rb_node;\n\twhile (n) {\n\t\tentry = rb_entry(n, struct ext4_system_zone, node);\n\t\tif (start_blk + count - 1 < entry->start_blk)\n\t\t\tn = n->rb_left;\n\t\telse if (start_blk >= (entry->start_blk + entry->count))\n\t\t\tn = n->rb_right;\n\t\telse\n\t\t\treturn 0;\n\t}\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'ext4: check journal inode extents more carefully\n\nCurrently, system zones just track ranges of block, that are \"important\"\nfs metadata (bitmaps, group descriptors, journal blocks, etc.). This\nhowever complicates how extent tree (or indirect blocks) can be checked\nfor inodes that actually track such metadata - currently the journal\ninode but arguably we should be treating quota files or resize inode\nsimilarly. We cannot run __ext4_ext_check() on such metadata inodes when\nloading their extents as that would immediately trigger the validity\nchecks and so we just hack around that and special-case the journal\ninode. This however leads to a situation that a journal inode which has\nextent tree of depth at least one can have invalid extent tree that gets\nunnoticed until ext4_cache_extents() crashes.\n\nTo overcome this limitation, track inode number each system zone belongs\nto (0 is used for zones not belonging to any inode). We can then verify\ninode number matches the expected one when verifying extent tree and\nthus avoid the false errors. With this there's no need to to\nspecial-case journal inode during extent tree checking anymore so remove\nit.\n\nFixes: 0a944e8a6c66 (\"ext4: don't perform block validity checks on the journal inode\")\nReported-by: Wolfgang Frisch \nReviewed-by: Lukas Czerner \nSigned-off-by: Jan Kara \nLink: https://lore.kernel.org/r/20200728130437.7804-4-jack@suse.cz\nSigned-off-by: Theodore Ts'o '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: njs_function_lambda_call(njs_vm_t *vm)\n{\n uint32_t n;\n njs_int_t ret;\n njs_frame_t *frame;\n njs_value_t *args, **local, *value;\n njs_value_t **cur_local, **cur_closures, **cur_temp;\n njs_function_t *function;\n njs_declaration_t *declr;\n njs_function_lambda_t *lambda;\n\n frame = (njs_frame_t *) vm->top_frame;\n function = frame->native.function;\n\n if (function->global && !function->closure_copied) {\n ret = njs_function_capture_global_closures(vm, function);\n if (njs_slow_path(ret != NJS_OK)) {\n return NJS_ERROR;\n }\n }\n\n lambda = function->u.lambda;\n\n args = vm->top_frame->arguments;\n local = vm->top_frame->local + function->args_offset;\n\n /* Move all arguments. */\n\n for (n = 0; n < function->args_count; n++) {\n if (!njs_is_valid(args)) {\n njs_set_undefined(args);\n }\n\n *local++ = args++;\n }\n\n /* Store current level. */\n\n cur_local = vm->levels[NJS_LEVEL_LOCAL];\n cur_closures = vm->levels[NJS_LEVEL_CLOSURE];\n cur_temp = vm->levels[NJS_LEVEL_TEMP];\n\n /* Replace current level. */\n\n vm->levels[NJS_LEVEL_LOCAL] = vm->top_frame->local;\n vm->levels[NJS_LEVEL_CLOSURE] = njs_function_closures(function);\n vm->levels[NJS_LEVEL_TEMP] = frame->native.temp;\n\n if (lambda->rest_parameters) {\n ret = njs_function_rest_parameters_init(vm, &frame->native);\n if (njs_slow_path(ret != NJS_OK)) {\n return NJS_ERROR;\n }\n }\n\n /* Self */\n\n if (lambda->self != NJS_INDEX_NONE) {\n value = njs_scope_value(vm, lambda->self);\n\n if (!njs_is_valid(value)) {\n njs_set_function(value, function);\n }\n }\n\n vm->active_frame = frame;\n\n /* Closures */\n\n n = lambda->ndeclarations;\n\n while (n != 0) {\n n--;\n\n declr = &lambda->declarations[n];\n value = njs_scope_value(vm, declr->index);\n\n *value = *declr->value;\n\n function = njs_function_value_copy(vm, value);\n if (njs_slow_path(function == NULL)) {\n return NJS_ERROR;\n }\n\n ret = njs_function_capture_closure(vm, function, function->u.lambda);\n if (njs_slow_path(ret != NJS_OK)) {\n return ret;\n }\n }\n\n ret = njs_vmcode_interpreter(vm, lambda->start);\n\n /* Restore current level. */\n vm->levels[NJS_LEVEL_LOCAL] = cur_local;\n vm->levels[NJS_LEVEL_CLOSURE] = cur_closures;\n vm->levels[NJS_LEVEL_TEMP] = cur_temp;\n\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed recursive async function calls.\n\nPreviously, PromiseCapability record was stored (function->context)\ndirectly in function object during a function invocation. This is\nnot correct, because PromiseCapability record should be linked to\ncurrent execution context. As a result, function->context is\noverwritten with consecutive recursive calls which results in\nuse-after-free.\n\nThis closes #451 issue on Github.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ipx_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\tstruct msghdr *msg, size_t size, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct ipx_sock *ipxs = ipx_sk(sk);\n\tstruct sockaddr_ipx *sipx = (struct sockaddr_ipx *)msg->msg_name;\n\tstruct ipxhdr *ipx = NULL;\n\tstruct sk_buff *skb;\n\tint copied, rc;\n\n\tlock_sock(sk);\n\t/* put the autobinding in */\n\tif (!ipxs->port) {\n\t\tstruct sockaddr_ipx uaddr;\n\n\t\tuaddr.sipx_port\t\t= 0;\n\t\tuaddr.sipx_network \t= 0;\n\n#ifdef CONFIG_IPX_INTERN\n\t\trc = -ENETDOWN;\n\t\tif (!ipxs->intrfc)\n\t\t\tgoto out; /* Someone zonked the iface */\n\t\tmemcpy(uaddr.sipx_node, ipxs->intrfc->if_node, IPX_NODE_LEN);\n#endif\t/* CONFIG_IPX_INTERN */\n\n\t\trc = __ipx_bind(sock, (struct sockaddr *)&uaddr,\n\t\t\t sizeof(struct sockaddr_ipx));\n\t\tif (rc)\n\t\t\tgoto out;\n\t}\n\n\trc = -ENOTCONN;\n\tif (sock_flag(sk, SOCK_ZAPPED))\n\t\tgoto out;\n\n\tskb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,\n\t\t\t\tflags & MSG_DONTWAIT, &rc);\n\tif (!skb)\n\t\tgoto out;\n\n\tipx \t= ipx_hdr(skb);\n\tcopied \t= ntohs(ipx->ipx_pktsize) - sizeof(struct ipxhdr);\n\tif (copied > size) {\n\t\tcopied = size;\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t}\n\n\trc = skb_copy_datagram_iovec(skb, sizeof(struct ipxhdr), msg->msg_iov,\n\t\t\t\t copied);\n\tif (rc)\n\t\tgoto out_free;\n\tif (skb->tstamp.tv64)\n\t\tsk->sk_stamp = skb->tstamp;\n\n\tmsg->msg_namelen = sizeof(*sipx);\n\n\tif (sipx) {\n\t\tsipx->sipx_family\t= AF_IPX;\n\t\tsipx->sipx_port\t\t= ipx->ipx_source.sock;\n\t\tmemcpy(sipx->sipx_node, ipx->ipx_source.node, IPX_NODE_LEN);\n\t\tsipx->sipx_network\t= IPX_SKB_CB(skb)->ipx_source_net;\n\t\tsipx->sipx_type \t= ipx->ipx_type;\n\t\tsipx->sipx_zero\t\t= 0;\n\t}\n\trc = copied;\n\nout_free:\n\tskb_free_datagram(sk, skb);\nout:\n\trelease_sock(sk);\n\treturn rc;\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 caif_seqpkt_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\t struct msghdr *m, size_t len, int flags)\n\n{\n\tstruct sock *sk = sock->sk;\n\tstruct sk_buff *skb;\n\tint ret;\n\tint copylen;\n\n\tret = -EOPNOTSUPP;\n\tif (m->msg_flags&MSG_OOB)\n\t\tgoto read_error;\n\n\tm->msg_namelen = 0;\n\n\tskb = skb_recv_datagram(sk, flags, 0 , &ret);\n\tif (!skb)\n\t\tgoto read_error;\n\tcopylen = skb->len;\n\tif (len < copylen) {\n\t\tm->msg_flags |= MSG_TRUNC;\n\t\tcopylen = len;\n\t}\n\n\tret = skb_copy_datagram_iovec(skb, 0, m->msg_iov, copylen);\n\tif (ret)\n\t\tgoto out_free;\n\n\tret = (flags & MSG_TRUNC) ? skb->len : copylen;\nout_free:\n\tskb_free_datagram(sk, skb);\n\tcaif_check_flow_release(sk);\n\treturn ret;\n\nread_error:\n\treturn ret;\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 unix_stream_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\t struct msghdr *msg, size_t size,\n\t\t\t int flags)\n{\n\tstruct sock_iocb *siocb = kiocb_to_siocb(iocb);\n\tstruct scm_cookie tmp_scm;\n\tstruct sock *sk = sock->sk;\n\tstruct unix_sock *u = unix_sk(sk);\n\tstruct sockaddr_un *sunaddr = msg->msg_name;\n\tint copied = 0;\n\tint check_creds = 0;\n\tint target;\n\tint err = 0;\n\tlong timeo;\n\tint skip;\n\n\terr = -EINVAL;\n\tif (sk->sk_state != TCP_ESTABLISHED)\n\t\tgoto out;\n\n\terr = -EOPNOTSUPP;\n\tif (flags&MSG_OOB)\n\t\tgoto out;\n\n\ttarget = sock_rcvlowat(sk, flags&MSG_WAITALL, size);\n\ttimeo = sock_rcvtimeo(sk, flags&MSG_DONTWAIT);\n\n\tmsg->msg_namelen = 0;\n\n\t/* Lock the socket to prevent queue disordering\n\t * while sleeps in memcpy_tomsg\n\t */\n\n\tif (!siocb->scm) {\n\t\tsiocb->scm = &tmp_scm;\n\t\tmemset(&tmp_scm, 0, sizeof(tmp_scm));\n\t}\n\n\terr = mutex_lock_interruptible(&u->readlock);\n\tif (err) {\n\t\terr = sock_intr_errno(timeo);\n\t\tgoto out;\n\t}\n\n\tdo {\n\t\tint chunk;\n\t\tstruct sk_buff *skb, *last;\n\n\t\tunix_state_lock(sk);\n\t\tlast = skb = skb_peek(&sk->sk_receive_queue);\nagain:\n\t\tif (skb == NULL) {\n\t\t\tunix_sk(sk)->recursion_level = 0;\n\t\t\tif (copied >= target)\n\t\t\t\tgoto unlock;\n\n\t\t\t/*\n\t\t\t *\tPOSIX 1003.1g mandates this order.\n\t\t\t */\n\n\t\t\terr = sock_error(sk);\n\t\t\tif (err)\n\t\t\t\tgoto unlock;\n\t\t\tif (sk->sk_shutdown & RCV_SHUTDOWN)\n\t\t\t\tgoto unlock;\n\n\t\t\tunix_state_unlock(sk);\n\t\t\terr = -EAGAIN;\n\t\t\tif (!timeo)\n\t\t\t\tbreak;\n\t\t\tmutex_unlock(&u->readlock);\n\n\t\t\ttimeo = unix_stream_data_wait(sk, timeo, last);\n\n\t\t\tif (signal_pending(current)\n\t\t\t || mutex_lock_interruptible(&u->readlock)) {\n\t\t\t\terr = sock_intr_errno(timeo);\n\t\t\t\tgoto out;\n\t\t\t}\n\n\t\t\tcontinue;\n unlock:\n\t\t\tunix_state_unlock(sk);\n\t\t\tbreak;\n\t\t}\n\n\t\tskip = sk_peek_offset(sk, flags);\n\t\twhile (skip >= unix_skb_len(skb)) {\n\t\t\tskip -= unix_skb_len(skb);\n\t\t\tlast = skb;\n\t\t\tskb = skb_peek_next(skb, &sk->sk_receive_queue);\n\t\t\tif (!skb)\n\t\t\t\tgoto again;\n\t\t}\n\n\t\tunix_state_unlock(sk);\n\n\t\tif (check_creds) {\n\t\t\t/* Never glue messages from different writers */\n\t\t\tif ((UNIXCB(skb).pid != siocb->scm->pid) ||\n\t\t\t !uid_eq(UNIXCB(skb).uid, siocb->scm->creds.uid) ||\n\t\t\t !gid_eq(UNIXCB(skb).gid, siocb->scm->creds.gid))\n\t\t\t\tbreak;\n\t\t} else if (test_bit(SOCK_PASSCRED, &sock->flags)) {\n\t\t\t/* Copy credentials */\n\t\t\tscm_set_cred(siocb->scm, UNIXCB(skb).pid, UNIXCB(skb).uid, UNIXCB(skb).gid);\n\t\t\tcheck_creds = 1;\n\t\t}\n\n\t\t/* Copy address just once */\n\t\tif (sunaddr) {\n\t\t\tunix_copy_addr(msg, skb->sk);\n\t\t\tsunaddr = NULL;\n\t\t}\n\n\t\tchunk = min_t(unsigned int, unix_skb_len(skb) - skip, size);\n\t\tif (skb_copy_datagram_iovec(skb, UNIXCB(skb).consumed + skip,\n\t\t\t\t\t msg->msg_iov, chunk)) {\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\tUNIXCB(skb).consumed += chunk;\n\n\t\t\tsk_peek_offset_bwd(sk, chunk);\n\n\t\t\tif (UNIXCB(skb).fp)\n\t\t\t\tunix_detach_fds(siocb->scm, skb);\n\n\t\t\tif (unix_skb_len(skb))\n\t\t\t\tbreak;\n\n\t\t\tskb_unlink(skb, &sk->sk_receive_queue);\n\t\t\tconsume_skb(skb);\n\n\t\t\tif (siocb->scm->fp)\n\t\t\t\tbreak;\n\t\t} else {\n\t\t\t/* It is questionable, see note in unix_dgram_recvmsg.\n\t\t\t */\n\t\t\tif (UNIXCB(skb).fp)\n\t\t\t\tsiocb->scm->fp = scm_fp_dup(UNIXCB(skb).fp);\n\n\t\t\tsk_peek_offset_fwd(sk, chunk);\n\n\t\t\tbreak;\n\t\t}\n\t} while (size);\n\n\tmutex_unlock(&u->readlock);\n\tscm_recv(sock, msg, siocb->scm, flags);\nout:\n\treturn copied ? : 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 ___sys_recvmsg(struct socket *sock, struct msghdr __user *msg,\n\t\t\t struct msghdr *msg_sys, unsigned int flags, int nosec)\n{\n\tstruct compat_msghdr __user *msg_compat =\n\t (struct compat_msghdr __user *)msg;\n\tstruct iovec iovstack[UIO_FASTIOV];\n\tstruct iovec *iov = iovstack;\n\tunsigned long cmsg_ptr;\n\tint err, total_len, len;\n\n\t/* kernel mode address */\n\tstruct sockaddr_storage addr;\n\n\t/* user mode address pointers */\n\tstruct sockaddr __user *uaddr;\n\tint __user *uaddr_len;\n\n\tif (MSG_CMSG_COMPAT & flags) {\n\t\tif (get_compat_msghdr(msg_sys, msg_compat))\n\t\t\treturn -EFAULT;\n\t} else {\n\t\terr = copy_msghdr_from_user(msg_sys, msg);\n\t\tif (err)\n\t\t\treturn err;\n\t}\n\n\tif (msg_sys->msg_iovlen > UIO_FASTIOV) {\n\t\terr = -EMSGSIZE;\n\t\tif (msg_sys->msg_iovlen > UIO_MAXIOV)\n\t\t\tgoto out;\n\t\terr = -ENOMEM;\n\t\tiov = kmalloc(msg_sys->msg_iovlen * sizeof(struct iovec),\n\t\t\t GFP_KERNEL);\n\t\tif (!iov)\n\t\t\tgoto out;\n\t}\n\n\t/*\n\t * Save the user-mode address (verify_iovec will change the\n\t * kernel msghdr to use the kernel address space)\n\t */\n\n\tuaddr = (__force void __user *)msg_sys->msg_name;\n\tuaddr_len = COMPAT_NAMELEN(msg);\n\tif (MSG_CMSG_COMPAT & flags) {\n\t\terr = verify_compat_iovec(msg_sys, iov, &addr, VERIFY_WRITE);\n\t} else\n\t\terr = verify_iovec(msg_sys, iov, &addr, VERIFY_WRITE);\n\tif (err < 0)\n\t\tgoto out_freeiov;\n\ttotal_len = err;\n\n\tcmsg_ptr = (unsigned long)msg_sys->msg_control;\n\tmsg_sys->msg_flags = flags & (MSG_CMSG_CLOEXEC|MSG_CMSG_COMPAT);\n\n\tif (sock->file->f_flags & O_NONBLOCK)\n\t\tflags |= MSG_DONTWAIT;\n\terr = (nosec ? sock_recvmsg_nosec : sock_recvmsg)(sock, msg_sys,\n\t\t\t\t\t\t\t total_len, flags);\n\tif (err < 0)\n\t\tgoto out_freeiov;\n\tlen = err;\n\n\tif (uaddr != NULL) {\n\t\terr = move_addr_to_user(&addr,\n\t\t\t\t\tmsg_sys->msg_namelen, uaddr,\n\t\t\t\t\tuaddr_len);\n\t\tif (err < 0)\n\t\t\tgoto out_freeiov;\n\t}\n\terr = __put_user((msg_sys->msg_flags & ~MSG_CMSG_COMPAT),\n\t\t\t COMPAT_FLAGS(msg));\n\tif (err)\n\t\tgoto out_freeiov;\n\tif (MSG_CMSG_COMPAT & flags)\n\t\terr = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr,\n\t\t\t\t &msg_compat->msg_controllen);\n\telse\n\t\terr = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr,\n\t\t\t\t &msg->msg_controllen);\n\tif (err)\n\t\tgoto out_freeiov;\n\terr = len;\n\nout_freeiov:\n\tif (iov != iovstack)\n\t\tkfree(iov);\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: void Compute(OpKernelContext* context) override {\n const Tensor& indices = context->input(0);\n const Tensor& values = context->input(1);\n const Tensor& shape = context->input(2);\n const Tensor& weights = context->input(3);\n bool use_weights = weights.NumElements() > 0;\n\n bool is_1d = shape.NumElements() == 1;\n int num_batches = is_1d ? 1 : shape.flat()(0);\n int num_values = values.NumElements();\n\n const auto indices_values = indices.matrix();\n const auto values_values = values.flat();\n const auto weight_values = weights.flat();\n\n auto per_batch_counts = BatchedMap(num_batches);\n\n T max_value = 0;\n\n for (int idx = 0; idx < num_values; ++idx) {\n int batch = is_1d ? 0 : indices_values(idx, 0);\n const auto& value = values_values(idx);\n if (value >= 0 && (maxlength_ <= 0 || value < maxlength_)) {\n if (binary_output_) {\n per_batch_counts[batch][value] = 1;\n } else if (use_weights) {\n per_batch_counts[batch][value] += weight_values(idx);\n } else {\n per_batch_counts[batch][value]++;\n }\n if (value > max_value) {\n max_value = value;\n }\n }\n }\n\n int num_output_values = GetOutputSize(max_value, maxlength_, minlength_);\n OP_REQUIRES_OK(context, OutputSparse(per_batch_counts, num_output_values,\n is_1d, context));\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-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: main(int argc, char** argv)\n{\n if (argc < 2) {\n PrintUsageAndExit();\n }\n \n // default options\n Options.input = NULL;\n Options.verbose = false;\n Options.hls_version = 0;\n Options.pmt_pid = 0x100;\n Options.audio_pid = 0x101;\n Options.video_pid = 0x102;\n Options.audio_track_id = -1;\n Options.video_track_id = -1;\n Options.audio_format = AUDIO_FORMAT_TS;\n Options.output_single_file = false;\n Options.show_info = false;\n Options.index_filename = \"stream.m3u8\";\n Options.iframe_index_filename = NULL;\n Options.segment_filename_template = NULL;\n Options.segment_url_template = NULL;\n Options.segment_duration = 6;\n Options.segment_duration_threshold = DefaultSegmentDurationThreshold;\n Options.allow_cache = NULL;\n Options.encryption_key_hex = NULL;\n Options.encryption_mode = ENCRYPTION_MODE_NONE;\n Options.encryption_iv_mode = ENCRYPTION_IV_MODE_NONE;\n Options.encryption_key_uri = \"key.bin\";\n Options.encryption_key_format = NULL;\n Options.encryption_key_format_versions = NULL;\n Options.pcr_offset = AP4_MPEG2_TS_DEFAULT_PCR_OFFSET;\n AP4_SetMemory(Options.encryption_key, 0, sizeof(Options.encryption_key));\n AP4_SetMemory(Options.encryption_iv, 0, sizeof(Options.encryption_iv));\n AP4_SetMemory(&Stats, 0, sizeof(Stats));\n\n // parse command line\n AP4_Result result;\n char** args = argv+1;\n while (const char* arg = *args++) {\n if (!strcmp(arg, \"--verbose\")) {\n Options.verbose = true;\n } else if (!strcmp(arg, \"--hls-version\")) {\n if (*args == NULL) {\n fprintf(stderr, \"ERROR: --hls-version requires a number\\n\");\n return 1;\n }\n Options.hls_version = (unsigned int)strtoul(*args++, NULL, 10);\n if (Options.hls_version ==0) {\n fprintf(stderr, \"ERROR: --hls-version requires number > 0\\n\");\n return 1;\n }\n } else if (!strcmp(arg, \"--segment-duration\")) {\n if (*args == NULL) {\n fprintf(stderr, \"ERROR: --segment-duration requires a number\\n\");\n return 1;\n }\n Options.segment_duration = (unsigned int)strtoul(*args++, NULL, 10);\n } else if (!strcmp(arg, \"--segment-duration-threshold\")) {\n if (*args == NULL) {\n fprintf(stderr, \"ERROR: --segment-duration-threshold requires a number\\n\");\n return 1;\n }\n Options.segment_duration_threshold = (unsigned int)strtoul(*args++, NULL, 10);\n } else if (!strcmp(arg, \"--segment-filename-template\")) {\n if (*args == NULL) {\n fprintf(stderr, \"ERROR: --segment-filename-template requires an argument\\n\");\n return 1;\n }\n Options.segment_filename_template = *args++;\n } else if (!strcmp(arg, \"--segment-url-template\")) {\n if (*args == NULL) {\n fprintf(stderr, \"ERROR: --segment-url-template requires an argument\\n\");\n return 1;\n }\n Options.segment_url_template = *args++;\n } else if (!strcmp(arg, \"--allow-cache\")) {\n if (*args == NULL || (strcmp(*args, \"NO\") && strcmp(*args, \"YES\"))) {\n fprintf(stderr, \"ERROR: --allow-cache requires a YES or NO argument\\n\");\n return 1;\n }\n Options.allow_cache = *args++;\n } else if (!strcmp(arg, \"--pmt-pid\")) {\n if (*args == NULL) {\n fprintf(stderr, \"ERROR: --pmt-pid requires a number\\n\");\n return 1;\n }\n Options.pmt_pid = (unsigned int)strtoul(*args++, NULL, 10);\n } else if (!strcmp(arg, \"--audio-pid\")) {\n if (*args == NULL) {\n fprintf(stderr, \"ERROR: --audio-pid requires a number\\n\");\n return 1;\n }\n Options.audio_pid = (unsigned int)strtoul(*args++, NULL, 10);\n } else if (!strcmp(arg, \"--video-pid\")) {\n if (*args == NULL) {\n fprintf(stderr, \"ERROR: --video-pid requires a number\\n\");\n return 1;\n }\n Options.video_pid = (unsigned int)strtoul(*args++, NULL, 10);\n } else if (!strcmp(arg, \"--audio-track-id\")) {\n if (*args == NULL) {\n fprintf(stderr, \"ERROR: --audio-track-id requires a number\\n\");\n return 1;\n }\n Options.audio_track_id = (unsigned int)strtoul(*args++, NULL, 10);\n } else if (!strcmp(arg, \"--audio-format\")) {\n if (*args == NULL) {\n fprintf(stderr, \"ERROR: --audio-format requires an argument\\n\");\n return 1;\n }\n const char* format = *args++;\n if (!strcmp(format, \"ts\")) {\n Options.audio_format = AUDIO_FORMAT_TS;\n } else if (!strcmp(format, \"packed\")) {\n Options.audio_format = AUDIO_FORMAT_PACKED;\n } else {\n fprintf(stderr, \"ERROR: unknown audio format\\n\");\n return 1;\n }\n } else if (!strcmp(arg, \"--video-track-id\")) {\n if (*args == NULL) {\n fprintf(stderr, \"ERROR: --video-track-id requires a number\\n\");\n return 1;\n }\n Options.video_track_id = (unsigned int)strtoul(*args++, NULL, 10);\n } else if (!strcmp(arg, \"--pcr-offset\")) {\n if (*args == NULL) {\n fprintf(stderr, \"ERROR: --pcr-offset requires a number\\n\");\n return 1;\n }\n Options.pcr_offset = (unsigned int)strtoul(*args++, NULL, 10);\n } else if (!strcmp(arg, \"--output-single-file\")) {\n Options.output_single_file = true;\n } else if (!strcmp(arg, \"--index-filename\")) {\n if (*args == NULL) {\n fprintf(stderr, \"ERROR: --index-filename requires a filename\\n\");\n return 1;\n }\n Options.index_filename = *args++;\n } else if (!strcmp(arg, \"--iframe-index-filename\")) {\n if (*args == NULL) {\n fprintf(stderr, \"ERROR: --iframe-index-filename requires a filename\\n\");\n return 1;\n }\n Options.iframe_index_filename = *args++;\n } else if (!strcmp(arg, \"--show-info\")) {\n Options.show_info = true;\n } else if (!strcmp(arg, \"--encryption-key\")) {\n if (*args == NULL) {\n fprintf(stderr, \"ERROR: --encryption-key requires an argument\\n\");\n return 1;\n }\n Options.encryption_key_hex = *args++;\n result = AP4_ParseHex(Options.encryption_key_hex, Options.encryption_key, 16);\n if (AP4_FAILED(result)) {\n fprintf(stderr, \"ERROR: invalid hex key\\n\");\n return 1;\n }\n if (Options.encryption_mode == ENCRYPTION_MODE_NONE) {\n Options.encryption_mode = ENCRYPTION_MODE_AES_128;\n }\n } else if (!strcmp(arg, \"--encryption-mode\")) {\n if (*args == NULL) {\n fprintf(stderr, \"ERROR: --encryption-mode requires an argument\\n\");\n return 1;\n }\n if (strncmp(*args, \"AES-128\", 7) == 0) {\n Options.encryption_mode = ENCRYPTION_MODE_AES_128;\n } else if (strncmp(*args, \"SAMPLE-AES\", 10) == 0) {\n Options.encryption_mode = ENCRYPTION_MODE_SAMPLE_AES;\n } else {\n fprintf(stderr, \"ERROR: unknown encryption mode\\n\");\n return 1;\n }\n ++args;\n } else if (!strcmp(arg, \"--encryption-iv-mode\")) {\n if (*args == NULL) {\n fprintf(stderr, \"ERROR: --encryption-iv-mode requires an argument\\n\");\n return 1;\n }\n if (strncmp(*args, \"sequence\", 8) == 0) {\n Options.encryption_iv_mode = ENCRYPTION_IV_MODE_SEQUENCE;\n } else if (strncmp(*args, \"random\", 6) == 0) {\n Options.encryption_iv_mode = ENCRYPTION_IV_MODE_RANDOM;\n } else if (strncmp(*args, \"fps\", 3) == 0) {\n Options.encryption_iv_mode = ENCRYPTION_IV_MODE_FPS;\n } else {\n fprintf(stderr, \"ERROR: unknown encryption IV mode\\n\");\n return 1;\n }\n ++args;\n } else if (!strcmp(arg, \"--encryption-key-uri\")) {\n if (*args == NULL) {\n fprintf(stderr, \"ERROR: --encryption-key-uri requires an argument\\n\");\n return 1;\n }\n Options.encryption_key_uri = *args++;\n } else if (!strcmp(arg, \"--encryption-key-format\")) {\n if (*args == NULL) {\n fprintf(stderr, \"ERROR: --encryption-key-format requires an argument\\n\");\n return 1;\n }\n Options.encryption_key_format = *args++;\n } else if (!strcmp(arg, \"--encryption-key-format-versions\")) {\n if (*args == NULL) {\n fprintf(stderr, \"ERROR: --encryption-key-format-versions requires an argument\\n\");\n return 1;\n }\n Options.encryption_key_format_versions = *args++;\n } else if (!strcmp(arg, \"--encryption-key-line\")) {\n if (*args == NULL) {\n fprintf(stderr, \"ERROR: --encryption-key-line requires an argument\\n\");\n return 1;\n }\n Options.encryption_key_lines.Append(*args++);\n } else if (Options.input == NULL) {\n Options.input = arg;\n } else {\n fprintf(stderr, \"ERROR: unexpected argument: %s\\n\", arg);\n return 1;\n }\n }\n\n // check args\n if (Options.input == NULL) {\n fprintf(stderr, \"ERROR: missing input file name\\n\");\n return 1;\n }\n if (Options.encryption_mode == ENCRYPTION_MODE_NONE && Options.encryption_key_lines.ItemCount() != 0) {\n fprintf(stderr, \"ERROR: --encryption-key-line requires --encryption-key and --encryption-key-mode\\n\");\n return 1;\n }\n if (Options.encryption_mode != ENCRYPTION_MODE_NONE && Options.encryption_key_hex == NULL) {\n fprintf(stderr, \"ERROR: no encryption key specified\\n\");\n return 1;\n }\n if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES && Options.hls_version > 0 && Options.hls_version < 5) {\n Options.hls_version = 5;\n fprintf(stderr, \"WARNING: forcing version to 5 in order to support SAMPLE-AES encryption\\n\");\n }\n if (Options.iframe_index_filename && Options.hls_version > 0 && Options.hls_version < 4) {\n fprintf(stderr, \"WARNING: forcing version to 4 in order to support I-FRAME-ONLY playlists\\n\");\n Options.hls_version = 4;\n }\n if (Options.encryption_iv_mode == ENCRYPTION_IV_MODE_NONE && Options.encryption_mode != ENCRYPTION_MODE_NONE) {\n if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) {\n // sequence-mode IVs don't work well with i-frame only playlists, use random instead\n Options.encryption_iv_mode = ENCRYPTION_IV_MODE_RANDOM;\n } else {\n Options.encryption_iv_mode = ENCRYPTION_IV_MODE_SEQUENCE;\n }\n }\n if ((Options.encryption_key_format || Options.encryption_key_format_versions) && Options.hls_version > 0 && Options.hls_version < 5) {\n Options.hls_version = 5;\n fprintf(stderr, \"WARNING: forcing version to 5 in order to support KEYFORMAT and/or KEYFORMATVERSIONS\\n\");\n }\n if (Options.output_single_file && Options.hls_version > 0 && Options.hls_version < 4) {\n Options.hls_version = 4;\n fprintf(stderr, \"WARNING: forcing version to 4 in order to support single file output\\n\");\n }\n if (Options.hls_version == 0) {\n // default version is 3 for cleartext or AES-128 encryption, and 5 for SAMPLE-AES\n if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) {\n Options.hls_version = 5;\n } else if (Options.output_single_file || Options.iframe_index_filename) {\n Options.hls_version = 4;\n } else {\n Options.hls_version = 3;\n }\n }\n \n if (Options.verbose && Options.show_info) {\n fprintf(stderr, \"WARNING: --verbose will be ignored because --show-info is selected\\n\");\n Options.verbose = false;\n }\n\n // compute some derived values\n if (Options.iframe_index_filename == NULL) {\n if (Options.hls_version >= 4) {\n Options.iframe_index_filename = \"iframes.m3u8\";\n }\n }\n if (Options.audio_format == AUDIO_FORMAT_TS) {\n if (Options.segment_filename_template == NULL) {\n if (Options.output_single_file) {\n Options.segment_filename_template = \"stream.ts\";\n } else {\n Options.segment_filename_template = \"segment-%d.ts\";\n }\n }\n if (Options.segment_url_template == NULL) {\n if (Options.output_single_file) {\n Options.segment_url_template = \"stream.ts\";\n } else {\n Options.segment_url_template = \"segment-%d.ts\";\n }\n }\n }\n \n if (Options.encryption_iv_mode == ENCRYPTION_IV_MODE_FPS) {\n if (AP4_StringLength(Options.encryption_key_hex) != 64) {\n fprintf(stderr, \"ERROR: 'fps' IV mode requires a 32 byte key value (64 characters in hex)\\n\");\n return 1;\n }\n result = AP4_ParseHex(Options.encryption_key_hex+32, Options.encryption_iv, 16);\n if (AP4_FAILED(result)) {\n fprintf(stderr, \"ERROR: invalid hex IV\\n\");\n return 1;\n }\n } else if (Options.encryption_iv_mode == ENCRYPTION_IV_MODE_RANDOM) {\n result = AP4_System_GenerateRandomBytes(Options.encryption_iv, sizeof(Options.encryption_iv));\n if (AP4_FAILED(result)) {\n fprintf(stderr, \"ERROR: failed to get random IV (%d)\\n\", result);\n return 1;\n }\n }\n \n\t// create the input stream\n AP4_ByteStream* input = NULL;\n result = AP4_FileByteStream::Create(Options.input, AP4_FileByteStream::STREAM_MODE_READ, input);\n if (AP4_FAILED(result)) {\n fprintf(stderr, \"ERROR: cannot open input (%d)\\n\", result);\n return 1;\n }\n \n\t// open the file\n AP4_File* input_file = new AP4_File(*input, true);\n\n // get the movie\n AP4_SampleDescription* sample_description;\n AP4_Movie* movie = input_file->GetMovie();\n if (movie == NULL) {\n fprintf(stderr, \"ERROR: no movie in file\\n\");\n return 1;\n }\n\n // get the audio and video tracks\n AP4_Track* audio_track = NULL;\n if (Options.audio_track_id == -1) {\n audio_track = movie->GetTrack(AP4_Track::TYPE_AUDIO);\n } else if (Options.audio_track_id > 0) {\n audio_track = movie->GetTrack((AP4_UI32)Options.audio_track_id);\n if (audio_track == NULL) {\n fprintf(stderr, \"ERROR: audio track ID %d not found\\n\", Options.audio_track_id);\n return 1;\n }\n if (audio_track->GetType() != AP4_Track::TYPE_AUDIO) {\n fprintf(stderr, \"ERROR: track ID %d is not an audio track\\n\", Options.audio_track_id);\n return 1;\n }\n }\n AP4_Track* video_track = NULL;\n if (Options.video_track_id == -1) {\n video_track = movie->GetTrack(AP4_Track::TYPE_VIDEO);\n } else if (Options.video_track_id > 0) {\n video_track = movie->GetTrack((AP4_UI32)Options.video_track_id);\n if (video_track == NULL) {\n fprintf(stderr, \"ERROR: video track ID %d not found\\n\", Options.video_track_id);\n return 1;\n }\n if (video_track->GetType() != AP4_Track::TYPE_VIDEO) {\n fprintf(stderr, \"ERROR: track ID %d is not a video track\\n\", Options.video_track_id);\n return 1;\n }\n }\n if (audio_track == NULL && video_track == NULL) {\n fprintf(stderr, \"ERROR: no suitable tracks found\\n\");\n delete input_file;\n input->Release();\n return 1;\n }\n if (Options.audio_format == AUDIO_FORMAT_PACKED && video_track != NULL) {\n if (audio_track == NULL) {\n fprintf(stderr, \"ERROR: packed audio format requires an audio track\\n\");\n return 1;\n }\n fprintf(stderr, \"WARNING: ignoring video track because of the packed audio format\\n\");\n video_track = NULL;\n }\n if (video_track == NULL) {\n Options.segment_duration_threshold = 0;\n }\n \n // create the appropriate readers\n AP4_LinearReader* linear_reader = NULL;\n SampleReader* audio_reader = NULL;\n SampleReader* video_reader = NULL;\n if (movie->HasFragments()) {\n // create a linear reader to get the samples\n linear_reader = new AP4_LinearReader(*movie, input);\n \n if (audio_track) {\n linear_reader->EnableTrack(audio_track->GetId());\n audio_reader = new FragmentedSampleReader(*linear_reader, audio_track->GetId());\n }\n if (video_track) {\n linear_reader->EnableTrack(video_track->GetId());\n video_reader = new FragmentedSampleReader(*linear_reader, video_track->GetId());\n }\n } else {\n if (audio_track) {\n audio_reader = new TrackSampleReader(*audio_track);\n }\n if (video_track) {\n video_reader = new TrackSampleReader(*video_track);\n }\n }\n \n AP4_Mpeg2TsWriter* ts_writer = NULL;\n AP4_Mpeg2TsWriter::SampleStream* audio_stream = NULL;\n AP4_Mpeg2TsWriter::SampleStream* video_stream = NULL;\n AP4_UI08 nalu_length_size = 0;\n PackedAudioWriter* packed_writer = NULL;\n if (Options.audio_format == AUDIO_FORMAT_PACKED) {\n packed_writer = new PackedAudioWriter();\n \n // figure out the file extensions if needed\n sample_description = audio_track->GetSampleDescription(0);\n if (sample_description == NULL) {\n fprintf(stderr, \"ERROR: unable to parse audio sample description\\n\");\n goto end;\n }\n if (Options.segment_filename_template == NULL || Options.segment_url_template == NULL) {\n const char* default_stream_name = \"stream.es\";\n const char* default_stream_pattern = \"segment-%d.es\";\n if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_MP4A) {\n AP4_MpegAudioSampleDescription* mpeg_audio_desc = AP4_DYNAMIC_CAST(AP4_MpegAudioSampleDescription, sample_description);\n if (mpeg_audio_desc == NULL ||\n !(mpeg_audio_desc->GetObjectTypeId() == AP4_OTI_MPEG4_AUDIO ||\n mpeg_audio_desc->GetObjectTypeId() == AP4_OTI_MPEG2_AAC_AUDIO_LC ||\n mpeg_audio_desc->GetObjectTypeId() == AP4_OTI_MPEG2_AAC_AUDIO_MAIN)) {\n fprintf(stderr, \"ERROR: only AAC audio is supported\\n\");\n return 1;\n }\n default_stream_name = \"stream.aac\";\n default_stream_pattern = \"segment-%d.aac\";\n } else if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_AC_3) {\n default_stream_name = \"stream.ac3\";\n default_stream_pattern = \"segment-%d.ac3\";\n } else if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_EC_3) {\n default_stream_name = \"stream.ec3\";\n default_stream_pattern = \"segment-%d.ec3\";\n } else if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_AC_4) {\n default_stream_name = \"stream.ac4\";\n default_stream_pattern = \"segment-%d.ac4\";\n }\n\n // override the segment names\n if (Options.segment_filename_template == NULL) {\n if (Options.output_single_file) {\n Options.segment_filename_template = default_stream_name;\n } else {\n Options.segment_filename_template = default_stream_pattern;\n }\n }\n if (Options.segment_url_template == NULL) {\n if (Options.output_single_file) {\n Options.segment_url_template = default_stream_name;\n } else {\n Options.segment_url_template = default_stream_pattern;\n }\n }\n }\n } else {\n // create an MPEG2 TS Writer\n ts_writer = new AP4_Mpeg2TsWriter(Options.pmt_pid);\n\n // add the audio stream\n if (audio_track) {\n sample_description = audio_track->GetSampleDescription(0);\n if (sample_description == NULL) {\n fprintf(stderr, \"ERROR: unable to parse audio sample description\\n\");\n goto end;\n }\n\n unsigned int stream_type = 0;\n unsigned int stream_id = 0;\n if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_MP4A) {\n if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) {\n stream_type = AP4_MPEG2_STREAM_TYPE_SAMPLE_AES_ISO_IEC_13818_7;\n } else {\n stream_type = AP4_MPEG2_STREAM_TYPE_ISO_IEC_13818_7;\n }\n stream_id = AP4_MPEG2_TS_DEFAULT_STREAM_ID_AUDIO;\n } else if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_AC_3) {\n if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) {\n stream_type = AP4_MPEG2_STREAM_TYPE_SAMPLE_AES_ATSC_AC3;\n } else {\n stream_type = AP4_MPEG2_STREAM_TYPE_ATSC_AC3;\n }\n stream_id = AP4_MPEG2_TS_STREAM_ID_PRIVATE_STREAM_1;\n } else if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_EC_3) {\n if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) {\n stream_type = AP4_MPEG2_STREAM_TYPE_SAMPLE_AES_ATSC_EAC3;\n } else {\n stream_type = AP4_MPEG2_STREAM_TYPE_ATSC_EAC3;\n }\n stream_id = AP4_MPEG2_TS_STREAM_ID_PRIVATE_STREAM_1;\n } else {\n fprintf(stderr, \"ERROR: audio codec not supported\\n\");\n return 1;\n }\n if (stream_type == AP4_MPEG2_STREAM_TYPE_ATSC_EAC3) {\n // E-AC-3 descriptor\n unsigned int number_of_channels = 0;\n AP4_String track_language;\n AP4_Dec3Atom* dec3 = AP4_DYNAMIC_CAST(AP4_Dec3Atom, sample_description->GetDetails().GetChild(AP4_ATOM_TYPE_DEC3));\n AP4_BitWriter bits(8);\n bits.Write(0xCC, 8);\n bits.Write(0x06, 8); // fixed value\n bits.Write(0xC0, 8); // reserved, bsid_flag, mainid_flag, asvc_flag, mixinfoexists, substream1_flag, substream2_flag and substream3_flag \n bits.Write(24, 5); // reserved, full_service_flag and service_type\n if (dec3->GetSubStreams()[0].acmod == 0) {\n number_of_channels = 1;\n } else if (dec3->GetSubStreams()[0].acmod == 1) {\n number_of_channels = 0;\n } else if (dec3->GetSubStreams()[0].acmod == 2) {\n number_of_channels = 2;\n } else {\n number_of_channels = 4;\n }\n if (dec3->GetSubStreams()[0].num_dep_sub > 0) {\n number_of_channels = 5;\n }\n bits.Write(number_of_channels, 3); // number_of_channels\n bits.Write(4, 3); // language_flag, language_flag_2, reserved\n bits.Write(dec3->GetSubStreams()[0].bsid, 5); // bsid\n track_language = audio_track->GetTrackLanguage();\n if (track_language.GetLength() == 3) {\n bits.Write(track_language.GetChars()[0], 8);\n bits.Write(track_language.GetChars()[1], 8);\n bits.Write(track_language.GetChars()[2], 8);\n } else {\n bits.Write(0x75, 8);\n bits.Write(0x6E, 8);\n bits.Write(0x64, 8);\n }\n // setup the audio stream\n result = ts_writer->SetAudioStream(audio_track->GetMediaTimeScale(),\n stream_type,\n stream_id,\n audio_stream,\n Options.audio_pid,\n bits.GetData(), 8,\n Options.pcr_offset);\n } else {\n // setup the audio stream\n result = ts_writer->SetAudioStream(audio_track->GetMediaTimeScale(),\n stream_type,\n stream_id,\n audio_stream,\n Options.audio_pid,\n NULL, 0,\n Options.pcr_offset);\n }\n if (AP4_FAILED(result)) {\n fprintf(stderr, \"could not create audio stream (%d)\\n\", result);\n goto end;\n }\n }\n \n // add the video stream\n if (video_track) {\n sample_description = video_track->GetSampleDescription(0);\n if (sample_description == NULL) {\n fprintf(stderr, \"ERROR: unable to parse video sample description\\n\");\n goto end;\n }\n \n // decide on the stream type\n unsigned int stream_type = 0;\n unsigned int stream_id = AP4_MPEG2_TS_DEFAULT_STREAM_ID_VIDEO;\n if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_AVC1 ||\n sample_description->GetFormat() == AP4_SAMPLE_FORMAT_AVC2 ||\n sample_description->GetFormat() == AP4_SAMPLE_FORMAT_AVC3 ||\n sample_description->GetFormat() == AP4_SAMPLE_FORMAT_AVC4 ||\n sample_description->GetFormat() == AP4_SAMPLE_FORMAT_DVAV ||\n sample_description->GetFormat() == AP4_SAMPLE_FORMAT_DVA1) {\n if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) {\n stream_type = AP4_MPEG2_STREAM_TYPE_SAMPLE_AES_AVC;\n AP4_AvcSampleDescription* avc_desc = AP4_DYNAMIC_CAST(AP4_AvcSampleDescription, sample_description);\n if (avc_desc == NULL) {\n fprintf(stderr, \"ERROR: not a proper AVC track\\n\");\n return 1;\n }\n nalu_length_size = avc_desc->GetNaluLengthSize();\n } else {\n stream_type = AP4_MPEG2_STREAM_TYPE_AVC;\n }\n } else if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_HEV1 ||\n sample_description->GetFormat() == AP4_SAMPLE_FORMAT_HVC1 ||\n sample_description->GetFormat() == AP4_SAMPLE_FORMAT_DVHE ||\n sample_description->GetFormat() == AP4_SAMPLE_FORMAT_DVH1) {\n stream_type = AP4_MPEG2_STREAM_TYPE_HEVC;\n } else {\n fprintf(stderr, \"ERROR: video codec not supported\\n\");\n return 1;\n }\n if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) {\n if (stream_type != AP4_MPEG2_STREAM_TYPE_SAMPLE_AES_AVC) {\n fprintf(stderr, \"ERROR: AES-SAMPLE encryption can only be used with H.264 video\\n\");\n return 1;\n }\n }\n \n // setup the video stream\n result = ts_writer->SetVideoStream(video_track->GetMediaTimeScale(),\n stream_type,\n stream_id,\n video_stream,\n Options.video_pid,\n NULL, 0,\n Options.pcr_offset);\n if (AP4_FAILED(result)) {\n fprintf(stderr, \"could not create video stream (%d)\\n\", result);\n goto end;\n }\n }\n }\n \n result = WriteSamples(ts_writer, packed_writer,\n audio_track, audio_reader, audio_stream,\n video_track, video_reader, video_stream,\n Options.segment_duration_threshold,\n nalu_length_size);\n if (AP4_FAILED(result)) {\n fprintf(stderr, \"ERROR: failed to write samples (%d)\\n\", result);\n }\n\n if (Options.show_info) {\n double average_segment_bitrate = 0.0;\n if (Stats.segments_total_duration != 0.0) {\n average_segment_bitrate = 8.0*(double)Stats.segments_total_size/Stats.segments_total_duration;\n }\n double average_iframe_bitrate = 0.0;\n if (Stats.segments_total_duration != 0.0) {\n average_iframe_bitrate = 8.0*(double)Stats.iframes_total_size/Stats.segments_total_duration;\n }\n\n double frame_rate = 0.0;\n if (video_track && (Stats.segments_total_duration != 0.0)) {\n double sample_count = (double)video_track->GetSampleCount();\n double media_duration = (double)video_track->GetMediaDuration();\n double timescale = (double)video_track->GetMediaTimeScale();\n if (media_duration > 0.0) {\n frame_rate = sample_count/(media_duration/timescale);\n }\n }\n\n printf(\n \"{\\n\"\n );\n printf(\n \" \\\"stats\\\": {\\n\"\n \" \\\"duration\\\": %f,\\n\"\n \" \\\"avg_segment_bitrate\\\": %f,\\n\"\n \" \\\"max_segment_bitrate\\\": %f,\\n\"\n \" \\\"avg_iframe_bitrate\\\": %f,\\n\"\n \" \\\"max_iframe_bitrate\\\": %f,\\n\"\n \" \\\"frame_rate\\\": %f\\n\"\n \" }\",\n (double)movie->GetDurationMs()/1000.0,\n average_segment_bitrate,\n Stats.max_segment_bitrate,\n average_iframe_bitrate,\n Stats.max_iframe_bitrate,\n frame_rate\n );\n if (audio_track) {\n AP4_String codec;\n AP4_SampleDescription* sdesc = audio_track->GetSampleDescription(0);\n if (sdesc) {\n sdesc->GetCodecString(codec);\n }\n printf(\n \",\\n\"\n \" \\\"audio\\\": {\\n\"\n \" \\\"codec\\\": \\\"%s\\\"\\n\"\n \" }\",\n codec.GetChars()\n );\n }\n if (video_track) {\n AP4_String codec;\n AP4_UI16 width = (AP4_UI16)(video_track->GetWidth()/65536.0);\n AP4_UI16 height = (AP4_UI16)(video_track->GetHeight()/65536.0);\n AP4_SampleDescription* sdesc = video_track->GetSampleDescription(0);\n if (sdesc) {\n sdesc->GetCodecString(codec);\n AP4_VideoSampleDescription* video_desc = AP4_DYNAMIC_CAST(AP4_VideoSampleDescription, sdesc);\n if (video_desc) {\n width = video_desc->GetWidth();\n height = video_desc->GetHeight();\n }\n }\n printf(\n \",\\n\"\n \" \\\"video\\\": {\\n\"\n \" \\\"codec\\\": \\\"%s\\\",\\n\"\n \" \\\"width\\\": %d,\\n\"\n \" \\\"height\\\": %d\\n\"\n \" }\",\n codec.GetChars(),\n width,\n height\n );\n }\n printf(\n \"\\n\"\n \"}\\n\"\n );\n }\n \nend:\n delete ts_writer;\n delete packed_writer;\n delete input_file;\n input->Release();\n delete linear_reader;\n delete audio_reader;\n delete video_reader;\n \n return result == AP4_SUCCESS?0:1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'fix #691'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: s32 vvc_parse_picture_header(GF_BitStream *bs, VVCState *vvc, VVCSliceInfo *si)\n{\n\tu32 pps_id;\n\n\tsi->irap_or_gdr_pic = gf_bs_read_int_log(bs, 1, \"irap_or_gdr_pic\");\n\tsi->non_ref_pic = gf_bs_read_int_log(bs, 1, \"non_ref_pic\");\n\tif (si->irap_or_gdr_pic)\n\t\tsi->gdr_pic = gf_bs_read_int_log(bs, 1, \"gdr_pic\");\n\tif ((si->inter_slice_allowed_flag = gf_bs_read_int_log(bs, 1, \"inter_slice_allowed_flag\")))\n\t\tsi->intra_slice_allowed_flag = gf_bs_read_int_log(bs, 1, \"intra_slice_allowed_flag\");\n\n\tpps_id = gf_bs_read_ue_log(bs, \"pps_id\");\n\tif (pps_id >= 64)\n\t\treturn -1;\n\tsi->pps = &vvc->pps[pps_id];\n\tsi->sps = &vvc->sps[si->pps->sps_id];\n\tsi->poc_lsb = gf_bs_read_int_log(bs, si->sps->log2_max_poc_lsb, \"poc_lsb\");\n\n\tsi->recovery_point_valid = 0;\n\tsi->gdr_recovery_count = 0;\n\tif (si->gdr_pic) {\n\t\tsi->recovery_point_valid = 1;\n\t\tsi->gdr_recovery_count = gf_bs_read_ue_log(bs, \"gdr_recovery_count\");\n\t}\n\tgf_bs_read_int_log(bs, si->sps->ph_num_extra_bits, \"ph_extra_bits\");\n\n\tif (si->sps->poc_msb_cycle_flag) {\n\t\tif ( (si->poc_msb_cycle_present_flag = gf_bs_read_int_log(bs, 1, \"poc_msb_cycle_present_flag\"))) {\n\t\t\tsi->poc_msb_cycle = gf_bs_read_int_log(bs, si->sps->poc_msb_cycle_len, \"poc_msb_cycle\");\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-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: const FieldID& activeUnionMemberId(const void* object, ptrdiff_t offset) {\n return *reinterpret_cast(\n offset + static_cast(object));\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: static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl )\n{\n int ret;\n const mbedtls_ssl_ciphersuite_t *ciphersuite_info =\n ssl->transform_negotiate->ciphersuite_info;\n unsigned char *p = NULL, *end = NULL;\n\n MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> parse server key exchange\" ) );\n\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)\n if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )\n {\n MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= skip parse server key exchange\" ) );\n ssl->state++;\n return( 0 );\n }\n ((void) p);\n ((void) end);\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \\\n defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)\n if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||\n ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )\n {\n if( ( ret = ssl_get_ecdh_params_from_cert( ssl ) ) != 0 )\n {\n MBEDTLS_SSL_DEBUG_RET( 1, \"ssl_get_ecdh_params_from_cert\", ret );\n mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n return( ret );\n }\n\n MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= skip parse server key exchange\" ) );\n ssl->state++;\n return( 0 );\n }\n ((void) p);\n ((void) end);\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||\n MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */\n\n if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )\n {\n MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_read_record\", ret );\n return( ret );\n }\n\n if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message\" ) );\n mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );\n return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );\n }\n\n /*\n * ServerKeyExchange may be skipped with PSK and RSA-PSK when the server\n * doesn't use a psk_identity_hint\n */\n if( ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE )\n {\n if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||\n ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )\n {\n /* Current message is probably either\n * CertificateRequest or ServerHelloDone */\n ssl->keep_current_message = 1;\n goto exit;\n }\n\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"server key exchange message must \"\n \"not be skipped\" ) );\n mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );\n\n return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );\n }\n\n p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );\n end = ssl->in_msg + ssl->in_hslen;\n MBEDTLS_SSL_DEBUG_BUF( 3, \"server key exchange\", p, end - p );\n\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)\n if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||\n ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||\n ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||\n ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )\n {\n if( ssl_parse_server_psk_hint( ssl, &p, end ) != 0 )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message\" ) );\n mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );\n return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n }\n } /* FALLTROUGH */\n#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \\\n defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)\n if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||\n ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )\n ; /* nothing more to do */\n else\n#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED ||\n MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \\\n defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)\n if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ||\n ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )\n {\n if( ssl_parse_server_dh_params( ssl, &p, end ) != 0 )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message\" ) );\n mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );\n return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n }\n }\n else\n#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||\n MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \\\n defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \\\n defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)\n if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||\n ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||\n ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )\n {\n if( ssl_parse_server_ecdh_params( ssl, &p, end ) != 0 )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message\" ) );\n mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );\n return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n }\n }\n else\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||\n MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||\n MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )\n {\n ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx,\n p, end - p );\n if( ret != 0 )\n {\n MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ecjpake_read_round_two\", ret );\n mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );\n return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n }\n }\n else\n#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n }\n\n#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)\n if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) )\n {\n size_t sig_len, hashlen;\n unsigned char hash[64];\n mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;\n mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;\n unsigned char *params = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );\n size_t params_len = p - params;\n\n /*\n * Handle the digitally-signed structure\n */\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )\n {\n if( ssl_parse_signature_algorithm( ssl, &p, end,\n &md_alg, &pk_alg ) != 0 )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message\" ) );\n mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );\n return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n }\n\n if( pk_alg != mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ) )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message\" ) );\n mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );\n return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n }\n }\n else\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \\\n defined(MBEDTLS_SSL_PROTO_TLS1_1)\n if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )\n {\n pk_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );\n\n /* Default hash for ECDSA is SHA-1 */\n if( pk_alg == MBEDTLS_PK_ECDSA && md_alg == MBEDTLS_MD_NONE )\n md_alg = MBEDTLS_MD_SHA1;\n }\n else\n#endif\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n }\n\n /*\n * Read signature\n */\n sig_len = ( p[0] << 8 ) | p[1];\n p += 2;\n\n if( end != p + sig_len )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message\" ) );\n mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n }\n\n MBEDTLS_SSL_DEBUG_BUF( 3, \"signature\", p, sig_len );\n\n /*\n * Compute the hash that has been signed\n */\n#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \\\n defined(MBEDTLS_SSL_PROTO_TLS1_1)\n if( md_alg == MBEDTLS_MD_NONE )\n {\n hashlen = 36;\n ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash, params,\n params_len );\n if( ret != 0 )\n return( ret );\n }\n else\n#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \\\n MBEDTLS_SSL_PROTO_TLS1_1 */\n#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \\\n defined(MBEDTLS_SSL_PROTO_TLS1_2)\n if( md_alg != MBEDTLS_MD_NONE )\n {\n /* Info from md_alg will be used instead */\n hashlen = 0;\n ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, params,\n params_len, md_alg );\n if( ret != 0 )\n return( ret );\n }\n else\n#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \\\n MBEDTLS_SSL_PROTO_TLS1_2 */\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n }\n\n MBEDTLS_SSL_DEBUG_BUF( 3, \"parameters hash\", hash, hashlen != 0 ? hashlen :\n (unsigned int) ( mbedtls_md_get_size( mbedtls_md_info_from_type( md_alg ) ) ) );\n\n if( ssl->session_negotiate->peer_cert == NULL )\n {\n MBEDTLS_SSL_DEBUG_MSG( 2, ( \"certificate required\" ) );\n mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );\n }\n\n /*\n * Verify signature\n */\n if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk, pk_alg ) )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message\" ) );\n mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );\n }\n\n if( ( ret = mbedtls_pk_verify( &ssl->session_negotiate->peer_cert->pk,\n md_alg, hash, hashlen, p, sig_len ) ) != 0 )\n {\n mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR );\n MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_pk_verify\", ret );\n return( ret );\n }\n }\n#endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */\n\nexit:\n ssl->state++;\n\n MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= parse server key exchange\" ) );\n\n return( 0 );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-125', 'CWE-295'], 'message': 'Add bounds check before signature length 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: AP4_AvccAtom::InspectFields(AP4_AtomInspector& inspector)\n{\n inspector.AddField(\"Configuration Version\", m_ConfigurationVersion);\n const char* profile_name = GetProfileName(m_Profile);\n if (profile_name) {\n inspector.AddField(\"Profile\", profile_name);\n } else {\n inspector.AddField(\"Profile\", m_Profile);\n }\n inspector.AddField(\"Profile Compatibility\", m_ProfileCompatibility, AP4_AtomInspector::HINT_HEX);\n inspector.AddField(\"Level\", m_Level);\n inspector.AddField(\"NALU Length Size\", m_NaluLengthSize);\n for (unsigned int i=0; i \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-703'], 'message': 'fixed possible crashes on malformed inputs.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int get_rx_bufs(struct vhost_virtqueue *vq,\n\t\t struct vring_used_elem *heads,\n\t\t int datalen,\n\t\t unsigned *iovcount,\n\t\t struct vhost_log *log,\n\t\t unsigned *log_num,\n\t\t unsigned int quota)\n{\n\tunsigned int out, in;\n\tint seg = 0;\n\tint headcount = 0;\n\tunsigned d;\n\tint r, nlogs = 0;\n\n\twhile (datalen > 0 && headcount < quota) {\n\t\tif (unlikely(seg >= UIO_MAXIOV)) {\n\t\t\tr = -ENOBUFS;\n\t\t\tgoto err;\n\t\t}\n\t\td = vhost_get_vq_desc(vq->dev, vq, vq->iov + seg,\n\t\t\t\t ARRAY_SIZE(vq->iov) - seg, &out,\n\t\t\t\t &in, log, log_num);\n\t\tif (d == vq->num) {\n\t\t\tr = 0;\n\t\t\tgoto err;\n\t\t}\n\t\tif (unlikely(out || in <= 0)) {\n\t\t\tvq_err(vq, \"unexpected descriptor format for RX: \"\n\t\t\t\t\"out %d, in %d\\n\", out, in);\n\t\t\tr = -EINVAL;\n\t\t\tgoto err;\n\t\t}\n\t\tif (unlikely(log)) {\n\t\t\tnlogs += *log_num;\n\t\t\tlog += *log_num;\n\t\t}\n\t\theads[headcount].id = d;\n\t\theads[headcount].len = iov_length(vq->iov + seg, in);\n\t\tdatalen -= heads[headcount].len;\n\t\t++headcount;\n\t\tseg += in;\n\t}\n\theads[headcount - 1].len += datalen;\n\t*iovcount = seg;\n\tif (unlikely(log))\n\t\t*log_num = nlogs;\n\treturn headcount;\nerr:\n\tvhost_discard_vq_desc(vq, headcount);\n\treturn r;\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: void CLASS foveon_dp_load_raw()\n{\n unsigned c, roff[4], row, col, diff;\n ushort huff[512], vpred[2][2], hpred[2];\n\n fseek (ifp, 8, SEEK_CUR);\n foveon_huff (huff);\n roff[0] = 48;\n FORC3 roff[c+1] = -(-(roff[c] + get4()) & -16);\n FORC3 {\n fseek (ifp, data_offset+roff[c], SEEK_SET);\n getbits(-1);\n vpred[0][0] = vpred[0][1] = vpred[1][0] = vpred[1][1] = 512;\n for (row=0; row < height; row++) {\n#ifdef LIBRAW_LIBRARY_BUILD\n checkCancel();\n#endif\n for (col=0; col < width; col++) {\n\tdiff = ljpeg_diff(huff);\n\tif (col < 2) hpred[col] = vpred[row & 1][col] += diff;\n\telse hpred[col & 1] += diff;\n\timage[row*width+col][c] = hpred[col & 1];\n }\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787', 'CWE-190'], 'message': 'Fixed possible foveon buffer overrun (Secunia SA750000)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: l_strnstart(const char *tstr1, u_int tl1, const char *str2, u_int l2)\n{\n\n\tif (tl1 > l2)\n\t\treturn 0;\n\n\treturn (strncmp(tstr1, str2, tl1) == 0 ? 1 : 0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13010/BEEP: Do bounds checking when comparing strings.\n\nThis fixes a buffer over-read discovered by Brian 'geeknik' Carpenter.\n\nAdd a test using the capture file supplied by the reporter(s).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void urlParsePostBody(struct URL *url,\n const struct HttpConnection *http,\n const char *buf, int len) {\n struct HashMap contentType;\n initHashMap(&contentType, urlDestroyHashMapEntry, NULL);\n const char *ctHeader = getFromHashMap(&http->header, \"content-type\");\n urlParseHeaderLine(&contentType, ctHeader, ctHeader ? strlen(ctHeader) : 0);\n if (getRefFromHashMap(&contentType, \"application/x-www-form-urlencoded\")) {\n urlParseQueryString(&url->args, buf, len);\n } else if (getRefFromHashMap(&contentType, \"multipart/form-data\")) {\n const char *boundary = getFromHashMap(&contentType, \"boundary\");\n if (boundary && *boundary) {\n const char *lastPart = NULL;\n for (const char *part = buf; len > 0; ) {\n const char *ptr;\n if ((part == buf && (ptr = urlMemstr(part, len, \"--\")) != NULL) ||\n (ptr = urlMemstr(part, len, \"\\r\\n--\")) != NULL) {\n len -= ptr - part + (part == buf ? 2 : 4);\n part = ptr + (part == buf ? 2 : 4);\n if (!urlMemcmp(part, len, boundary)) {\n int i = strlen(boundary);\n len -= i;\n part += i;\n if (!urlMemcmp(part, len, \"\\r\\n\")) {\n len -= 2;\n part += 2;\n if (lastPart) {\n urlParsePart(url, lastPart, ptr - lastPart);\n } else {\n if (ptr != buf) {\n info(\"[http] Ignoring prologue before \\\"multipart/form-data\\\"!\");\n }\n }\n lastPart = part;\n } else if (!urlMemcmp(part, len, \"--\\r\\n\")) {\n len -= 4;\n part += 4;\n urlParsePart(url, lastPart, ptr - lastPart);\n lastPart = NULL;\n if (len > 0) {\n info(\"[http] Ignoring epilogue past end of \\\"multipart/\"\n\t\t\t\t \"form-data\\\"!\");\n }\n }\n }\n }\n }\n if (lastPart) {\n warn(\"[http] Missing final \\\"boundary\\\" for \\\"multipart/form-data\\\"!\");\n }\n } else {\n warn(\"[http] Missing \\\"boundary\\\" information for \\\"multipart/form-data\\\"!\");\n }\n }\n destroyHashMap(&contentType);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703', 'CWE-835'], 'message': 'Rolling code for version 2.21'" }, { "text": "[INST] Given the following code containing errors, provide Common 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(\"Negated Class test\", \"[general]\")\n{\n parser parser(R\"(\n ROOT <- [^a-z_]+\n )\");\n\n bool ret = parser;\n REQUIRE(ret == true);\n\n REQUIRE(parser.parse(\"ABC123\"));\n REQUIRE_FALSE(parser.parse(\"ABcZ\"));\n REQUIRE_FALSE(parser.parse(\"ABCZ_\"));\n REQUIRE_FALSE(parser.parse(\"\"));\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: inline size_t codepoint_length(const char *s8, size_t l) {\n if (l) {\n auto b = static_cast(s8[0]);\n if ((b & 0x80) == 0) {\n return 1;\n } else if ((b & 0xE0) == 0xC0) {\n return 2;\n } else if ((b & 0xF0) == 0xE0) {\n return 3;\n } else if ((b & 0xF8) == 0xF0) {\n return 4;\n }\n }\n return 0;\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(\"Token check test\", \"[general]\")\n{\n parser parser(R\"(\n EXPRESSION <- _ TERM (TERM_OPERATOR TERM)*\n TERM <- FACTOR (FACTOR_OPERATOR FACTOR)*\n FACTOR <- NUMBER / '(' _ EXPRESSION ')' _\n TERM_OPERATOR <- < [-+] > _\n FACTOR_OPERATOR <- < [/*] > _\n NUMBER <- < [0-9]+ > _\n _ <- [ \\t\\r\\n]*\n )\");\n\n REQUIRE(parser[\"EXPRESSION\"].is_token() == false);\n REQUIRE(parser[\"FACTOR\"].is_token() == false);\n REQUIRE(parser[\"FACTOR_OPERATOR\"].is_token() == true);\n REQUIRE(parser[\"NUMBER\"].is_token() == true);\n REQUIRE(parser[\"_\"].is_token() == true);\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 inline bool kvm_apic_has_events(struct kvm_vcpu *vcpu)\n{\n\treturn vcpu->arch.apic->pending_events;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'kvm: x86: fix kvm_apic_has_events to check for NULL pointer\n\nMalicious (or egregiously buggy) userspace can trigger it, but it\nshould never happen in normal operation.\n\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: gerbv_gdk_draw_prim20(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 linewidth_idx = 1;\n const int start_x_idx = 2;\n const int start_y_idx = 3;\n const int end_x_idx = 4;\n const int end_y_idx = 5;\n const int rotation_idx = 6;\n const int nuf_points = 2;\n GdkGC *local_gc = gdk_gc_new(pixmap);\n GdkPoint points[nuf_points];\n GdkColor color;\n int i;\n\n gdk_gc_copy(local_gc, gc);\n\n /* Exposure */\n if (p[exposure_idx] == 0.0) {\n\tcolor.pixel = 0;\n\tgdk_gc_set_foreground(local_gc, &color);\n }\n\n gdk_gc_set_line_attributes(local_gc, \n\t\t\t (int)round(scale * p[linewidth_idx]),\n\t\t\t GDK_LINE_SOLID, \n\t\t\t GDK_CAP_BUTT, \n\t\t\t GDK_JOIN_MITER);\n\n points[0].x = (p[start_x_idx] * scale);\n points[0].y = (p[start_y_idx] * scale);\n points[1].x = (p[end_x_idx] * scale);\n points[1].y = (p[end_y_idx] * 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_draw_line(pixmap, local_gc, \n\t\t points[0].x, points[0].y, \n\t\t points[1].x, points[1].y);\n \n gdk_gc_unref(local_gc);\n\n return;\n} /* gerbv_gdk_draw_prim20 */ ; 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_RecvOpen(WOLFSSH* ssh, int reqId, byte* data, word32 maxSz)\n#ifndef USE_WINDOWS_API\n{\n WS_SFTP_FILEATRB atr;\n WFD fd;\n word32 sz;\n char* dir;\n word32 reason;\n word32 idx = 0;\n int m = 0;\n int ret = WS_SUCCESS;\n\n word32 outSz = sizeof(WFD) + UINT32_SZ + WOLFSSH_SFTP_HEADER;\n byte* out = NULL;\n\n char* res = NULL;\n char ier[] = \"Internal Failure\";\n char oer[] = \"Open File Error\";\n\n if (ssh == NULL) {\n return WS_BAD_ARGUMENT;\n }\n\n WLOG(WS_LOG_SFTP, \"Receiving WOLFSSH_FTP_OPEN\");\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 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 idx += sz;\n\n /* get reason for opening file */\n ato32(data + idx, &reason); idx += UINT32_SZ;\n\n /* @TODO handle attributes */\n SFTP_ParseAtributes_buffer(ssh, &atr, data, &idx, maxSz);\n if ((reason & WOLFSSH_FXF_READ) && (reason & WOLFSSH_FXF_WRITE)) {\n m |= WOLFSSH_O_RDWR;\n }\n else {\n if (reason & WOLFSSH_FXF_READ) {\n m |= WOLFSSH_O_RDONLY;\n }\n if (reason & WOLFSSH_FXF_WRITE) {\n m |= WOLFSSH_O_WRONLY;\n }\n }\n\n if (reason & WOLFSSH_FXF_APPEND) {\n m |= WOLFSSH_O_APPEND;\n }\n if (reason & WOLFSSH_FXF_CREAT) {\n m |= WOLFSSH_O_CREAT;\n }\n if (reason & WOLFSSH_FXF_TRUNC) {\n m |= WOLFSSH_O_TRUNC;\n }\n if (reason & WOLFSSH_FXF_EXCL) {\n m |= WOLFSSH_O_EXCL;\n }\n\n /* if file permissions not set then use default */\n if (!(atr.flags & WOLFSSH_FILEATRB_PERM)) {\n atr.per = 0644;\n }\n\n if (wolfSSH_CleanPath(ssh, dir) < 0) {\n WFREE(dir, ssh->ctx->heap, DYNTYPE_BUFFER);\n return WS_FATAL_ERROR;\n }\n fd = WOPEN(dir, m, atr.per);\n if (fd < 0) {\n WLOG(WS_LOG_SFTP, \"Error opening file %s\", dir);\n res = oer;\n if (wolfSSH_SFTP_CreateStatus(ssh, WOLFSSH_FTP_FAILURE, reqId, res,\n \"English\", NULL, &outSz) != WS_SIZE_ONLY) {\n WFREE(dir, ssh->ctx->heap, DYNTYPE_BUFFER);\n return WS_FATAL_ERROR;\n }\n ret = WS_BAD_FILE_E;\n }\n\n#ifdef WOLFSSH_STOREHANDLE\n if (ret == WS_SUCCESS) {\n if ((ret = SFTP_AddHandleNode(ssh, (byte*)&fd, sizeof(WFD), dir)) != WS_SUCCESS) {\n WLOG(WS_LOG_SFTP, \"Unable to store handle\");\n res = ier;\n if (wolfSSH_SFTP_CreateStatus(ssh, WOLFSSH_FTP_FAILURE, reqId, res,\n \"English\", NULL, &outSz) != WS_SIZE_ONLY) {\n WFREE(dir, ssh->ctx->heap, DYNTYPE_BUFFER);\n return WS_FATAL_ERROR;\n }\n ret = WS_FATAL_ERROR;\n }\n }\n#endif\n WFREE(dir, ssh->ctx->heap, DYNTYPE_BUFFER);\n\n /* create packet */\n out = (byte*)WMALLOC(outSz, ssh->ctx->heap, DYNTYPE_BUFFER);\n if (out == NULL) {\n return WS_MEMORY_E;\n }\n if (ret == WS_SUCCESS) {\n if (SFTP_CreatePacket(ssh, WOLFSSH_FTP_HANDLE, out, outSz,\n (byte*)&fd, sizeof(WFD)) != WS_SUCCESS) {\n return WS_FATAL_ERROR;\n }\n }\n else {\n if (wolfSSH_SFTP_CreateStatus(ssh, WOLFSSH_FTP_FAILURE, reqId, res,\n \"English\", out, &outSz) != 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 (void)ier;\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: static void ok_jpg_generate_huffman_table(ok_jpg_huffman_table *huff, const uint8_t *bits) {\n // JPEG spec: \"Generate_size_table\"\n int k = 0;\n for (uint8_t i = 1; i <= 16; i++) {\n for (int j = 1; j <= bits[i]; j++) {\n huff->size[k++] = i;\n }\n }\n huff->size[k] = 0;\n huff->count = k;\n\n // JPEG spec: \"Generate_code_table\"\n k = 0;\n uint16_t code = 0;\n int si = huff->size[0];\n while (true) {\n huff->code[k] = code;\n code++;\n k++;\n int si2 = huff->size[k];\n if (si2 == 0) {\n break;\n }\n if (si2 > si) {\n code <<= (si2 - si);\n si = si2;\n }\n }\n\n // JPEG spec: \"Decoder_tables\"\n int j = 0;\n for (int i = 0; i < 16; i++) {\n if (bits[i + 1] == 0) {\n huff->maxcode[i] = -1;\n } else {\n huff->valptr[i] = j;\n huff->mincode[i] = huff->code[j];\n j += bits[i + 1];\n huff->maxcode[i] = huff->code[j - 1];\n if (i >= HUFFMAN_LOOKUP_SIZE_BITS) {\n huff->maxcode[i] = (huff->maxcode[i] << (15 - i)) | ((1 << (15 - i)) - 1);\n }\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'ok_jpg: Fix invalid DHT (#11)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Integer InvertibleRWFunction::CalculateInverse(RandomNumberGenerator &rng, const Integer &x) const\n{\n\tDoQuickSanityCheck();\n\tModularArithmetic modn(m_n);\n\tInteger r, rInv;\n\tdo {\t// do this in a loop for people using small numbers for testing\n\t\tr.Randomize(rng, Integer::One(), m_n - Integer::One());\n\t\trInv = modn.MultiplicativeInverse(r);\n\t} while (rInv.IsZero());\n\tInteger re = modn.Square(r);\n\tre = modn.Multiply(re, x);\t\t\t// blind\n\n\tInteger cp=re%m_p, cq=re%m_q;\n\tif (Jacobi(cp, m_p) * Jacobi(cq, m_q) != 1)\n\t{\n\t\tcp = cp.IsOdd() ? (cp+m_p) >> 1 : cp >> 1;\n\t\tcq = cq.IsOdd() ? (cq+m_q) >> 1 : cq >> 1;\n\t}\n\n\t#pragma omp parallel\n\t\t#pragma omp sections\n\t\t{\n\t\t\t#pragma omp section\n\t\t\t\tcp = ModularSquareRoot(cp, m_p);\n\t\t\t#pragma omp section\n\t\t\t\tcq = ModularSquareRoot(cq, m_q);\n\t\t}\n\n\tInteger y = CRT(cq, m_q, cp, m_p, m_u);\n\ty = modn.Multiply(y, rInv);\t\t\t\t// unblind\n\ty = STDMIN(y, m_n-y);\n\tif (ApplyFunction(y) != x)\t\t\t\t// check\n\t\tthrow Exception(Exception::OTHER_ERROR, \"InvertibleRWFunction: computational error during private key operation\");\n\treturn y;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-399'], 'message': 'Fix for CVE-2015-2141. Thanks to Evgeny Sidorov for reporting. Squaring to satisfy Jacobi requirements suggested by JPM.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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_report(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_report_lock);\n\tif (skb_queue_len(&idev->mc_report_queue) < MLD_MAX_SKBS) {\n\t\t__skb_queue_tail(&idev->mc_report_queue, skb);\n\t\tif (!mod_delayed_work(mld_wq, &idev->mc_report_work, 0))\n\t\t\tin6_dev_hold(idev);\n\t}\n\tspin_unlock_bh(&idev->mc_report_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: void SparseFillEmptyRowsOpImpl(OpKernelContext* context,\n AsyncOpKernel::DoneCallback done = nullptr) {\n // Note that setting this empty lambda as the default parameter value directly\n // can cause strange compiler/linker errors, so we do it like this instead.\n if (!done) {\n done = [] {};\n }\n\n const int kIndicesInput = 0;\n const int kValuesInput = 1;\n const int kDenseShapeInput = 2;\n const int kDefaultValueInput = 3;\n\n const Tensor& indices_t = context->input(kIndicesInput);\n const Tensor& values_t = context->input(kValuesInput);\n const Tensor& dense_shape_t = context->input(kDenseShapeInput);\n const Tensor& default_value_t = context->input(kDefaultValueInput);\n\n OP_REQUIRES_ASYNC(\n context, TensorShapeUtils::IsVector(dense_shape_t.shape()),\n errors::InvalidArgument(\"dense_shape must be a vector, saw: \",\n dense_shape_t.shape().DebugString()),\n done);\n OP_REQUIRES_ASYNC(context, TensorShapeUtils::IsMatrix(indices_t.shape()),\n errors::InvalidArgument(\"indices must be a matrix, saw: \",\n indices_t.shape().DebugString()),\n done);\n OP_REQUIRES_ASYNC(context, TensorShapeUtils::IsVector(values_t.shape()),\n errors::InvalidArgument(\"values must be a vector, saw: \",\n values_t.shape().DebugString()),\n done);\n OP_REQUIRES_ASYNC(\n context, TensorShapeUtils::IsScalar(default_value_t.shape()),\n errors::InvalidArgument(\"default_value must be a scalar, saw: \",\n default_value_t.shape().DebugString()),\n done);\n // TODO(ebrevdo): add shape checks between values, indices,\n // dense_shape. Also add check that dense rank > 0.\n\n using FunctorType = functor::SparseFillEmptyRows;\n OP_REQUIRES_OK_ASYNC(context,\n FunctorType()(context, default_value_t, indices_t,\n values_t, dense_shape_t, done),\n done);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-703'], 'message': 'Fix heap-buffer-overflow issue with `tf.raw_ops.SparseFillEmptyRows`.\n\nPiperOrigin-RevId: 372009178\nChange-Id: Ia1a9e9691ecaa072f32fb39a0887b2aabd399210'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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_show_object(struct object *object,\n\t\t\t struct strbuf *path,\n\t\t\t const char *last, void *data)\n{\n\tstruct bitmap_test_data *tdata = data;\n\tint bitmap_pos;\n\n\tbitmap_pos = bitmap_position(object->oid.hash);\n\tif (bitmap_pos < 0)\n\t\tdie(\"Object not in bitmap: %s\\n\", oid_to_hex(&object->oid));\n\n\tbitmap_set(tdata->base, bitmap_pos);\n\tdisplay_progress(tdata->prg, ++tdata->seen);\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 record_recent_object(struct object *obj,\n\t\t\t\t struct strbuf *path,\n\t\t\t\t const char *last,\n\t\t\t\t void *data)\n{\n\tsha1_array_append(&recent_objects, obj->oid.hash);\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 int udf_encode_fh(struct inode *inode, __u32 *fh, int *lenp,\n\t\t\t struct inode *parent)\n{\n\tint len = *lenp;\n\tstruct kernel_lb_addr location = UDF_I(inode)->i_location;\n\tstruct fid *fid = (struct fid *)fh;\n\tint type = FILEID_UDF_WITHOUT_PARENT;\n\n\tif (parent && (len < 5)) {\n\t\t*lenp = 5;\n\t\treturn 255;\n\t} else if (len < 3) {\n\t\t*lenp = 3;\n\t\treturn 255;\n\t}\n\n\t*lenp = 3;\n\tfid->udf.block = location.logicalBlockNum;\n\tfid->udf.partref = location.partitionReferenceNum;\n\tfid->udf.generation = inode->i_generation;\n\n\tif (parent) {\n\t\tlocation = UDF_I(parent)->i_location;\n\t\tfid->udf.parent_block = location.logicalBlockNum;\n\t\tfid->udf.parent_partref = location.partitionReferenceNum;\n\t\tfid->udf.parent_generation = inode->i_generation;\n\t\t*lenp = 5;\n\t\ttype = FILEID_UDF_WITH_PARENT;\n\t}\n\n\treturn type;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'udf: avoid info leak on export\n\nFor type 0x51 the udf.parent_partref member in struct fid gets copied\nuninitialized to userland. Fix this by initializing it to 0.\n\nSigned-off-by: Mathias Krause \nSigned-off-by: Jan Kara '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int vfio_msi_enable(struct vfio_pci_device *vdev, int nvec, bool msix)\n{\n\tstruct pci_dev *pdev = vdev->pdev;\n\tunsigned int flag = msix ? PCI_IRQ_MSIX : PCI_IRQ_MSI;\n\tint ret;\n\n\tif (!is_irq_none(vdev))\n\t\treturn -EINVAL;\n\n\tvdev->ctx = kzalloc(nvec * sizeof(struct vfio_pci_irq_ctx), GFP_KERNEL);\n\tif (!vdev->ctx)\n\t\treturn -ENOMEM;\n\n\t/* return the number of supported vectors if we can't get all: */\n\tret = pci_alloc_irq_vectors(pdev, 1, nvec, flag);\n\tif (ret < nvec) {\n\t\tif (ret > 0)\n\t\t\tpci_free_irq_vectors(pdev);\n\t\tkfree(vdev->ctx);\n\t\treturn ret;\n\t}\n\n\tvdev->num_ctx = nvec;\n\tvdev->irq_type = msix ? VFIO_PCI_MSIX_IRQ_INDEX :\n\t\t\t\tVFIO_PCI_MSI_IRQ_INDEX;\n\n\tif (!msix) {\n\t\t/*\n\t\t * Compute the virtual hardware field for max msi vectors -\n\t\t * it is the log base 2 of the number of vectors.\n\t\t */\n\t\tvdev->msi_qmax = fls(nvec * 2 - 1) - 1;\n\t}\n\n\treturn 0;\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: static int decode_avp(struct l2tp_avp_t *avp, const struct l2tp_attr_t *RV,\n\t\t const char *secret, size_t secret_len)\n{\n\tMD5_CTX md5_ctx;\n\tuint8_t md5[MD5_DIGEST_LENGTH];\n\tuint8_t p1[MD5_DIGEST_LENGTH];\n\tuint8_t *prev_block = NULL;\n\tuint16_t attr_len;\n\tuint16_t orig_attr_len;\n\tuint16_t bytes_left;\n\tuint16_t blocks_left;\n\tuint16_t last_block_len;\n\n\tif (avp->length < sizeof(struct l2tp_avp_t) + 2) {\n\t\t/* Hidden AVPs must contain at least two bytes\n\t\t for storing original attribute length */\n\t\tlog_warn(\"l2tp: incorrect hidden avp received (type %hu):\"\n\t\t\t \" length too small (%hu bytes)\\n\",\n\t\t\t ntohs(avp->type), avp->length);\n\t\treturn -1;\n\t}\n\tattr_len = avp->length - sizeof(struct l2tp_avp_t);\n\n\t/* Decode first block */\n\tMD5_Init(&md5_ctx);\n\tMD5_Update(&md5_ctx, &avp->type, sizeof(avp->type));\n\tMD5_Update(&md5_ctx, secret, secret_len);\n\tMD5_Update(&md5_ctx, RV->val.octets, RV->length);\n\tMD5_Final(p1, &md5_ctx);\n\n\tif (attr_len <= MD5_DIGEST_LENGTH) {\n\t\tmemxor(avp->val, p1, attr_len);\n\t\treturn 0;\n\t}\n\n\tmemxor(p1, avp->val, MD5_DIGEST_LENGTH);\n\torig_attr_len = ntohs(*(uint16_t *)p1);\n\n\tif (orig_attr_len <= MD5_DIGEST_LENGTH - 2) {\n\t\t/* Enough bytes decoded already, no need to decode padding */\n\t\tmemcpy(avp->val, p1, MD5_DIGEST_LENGTH);\n\t\treturn 0;\n\t}\n\n\tif (orig_attr_len > attr_len - 2) {\n\t\tlog_warn(\"l2tp: incorrect hidden avp received (type %hu):\"\n\t\t\t \" original attribute length too big (ciphered\"\n\t\t\t \" attribute length: %hu bytes, advertised original\"\n\t\t\t \" attribute length: %hu bytes)\\n\",\n\t\t\t ntohs(avp->type), attr_len, orig_attr_len);\n\t\treturn -1;\n\t}\n\n\t/* Decode remaining blocks. Start from the last block as\n\t preceding blocks must be kept hidden for computing MD5s */\n\tbytes_left = orig_attr_len + 2 - MD5_DIGEST_LENGTH;\n\tlast_block_len = bytes_left % MD5_DIGEST_LENGTH;\n\tblocks_left = bytes_left / MD5_DIGEST_LENGTH;\n\tif (last_block_len) {\n\t\tprev_block = avp->val + blocks_left * MD5_DIGEST_LENGTH;\n\t\tMD5_Init(&md5_ctx);\n\t\tMD5_Update(&md5_ctx, secret, secret_len);\n\t\tMD5_Update(&md5_ctx, prev_block, MD5_DIGEST_LENGTH);\n\t\tMD5_Final(md5, &md5_ctx);\n\t\tmemxor(prev_block + MD5_DIGEST_LENGTH, md5, last_block_len);\n\t\tprev_block -= MD5_DIGEST_LENGTH;\n\t} else\n\t\tprev_block = avp->val + (blocks_left - 1) * MD5_DIGEST_LENGTH;\n\n\twhile (prev_block >= avp->val) {\n\t\tMD5_Init(&md5_ctx);\n\t\tMD5_Update(&md5_ctx, secret, secret_len);\n\t\tMD5_Update(&md5_ctx, prev_block, MD5_DIGEST_LENGTH);\n\t\tMD5_Final(md5, &md5_ctx);\n\t\tmemxor(prev_block + MD5_DIGEST_LENGTH, md5, MD5_DIGEST_LENGTH);\n\t\tprev_block -= MD5_DIGEST_LENGTH;\n\t}\n\tmemcpy(avp->val, p1, MD5_DIGEST_LENGTH);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-125', 'CWE-120'], 'message': 'l2tp: fix RCE through buffer overflow & fix LE/BE compatibility\n\nUnsufficent checks of valid l2tp header & avp length cause possible\nRCE through buffer overflow, reported by https://github.com/WinMin\nswings & leommxj, Chaitin Security Research Lab. Add missed header\nlength and avp length validation to fix the issue.\n\nOrder of struct bitfields is implementation-defined so current code\ndoesn't play well with big-endian arch. switch to explicit flag bit\nchecking/gathering to fix the issue.\n\nRFC 2661 and 3931 requires that length, seqeuence flags must be set\nand offset flag must not be set, so avp-premissive can't help in\nthis cases.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void* swoole_unserialize_arr(void *buffer, zval *zvalue, uint32_t nNumOfElements, long flag)\n{\n //Initialize zend array\n zend_ulong h, nIndex, max_index = 0;\n uint32_t size = cp_zend_hash_check_size(nNumOfElements);\n if (!size)\n {\n return NULL;\n }\n if (!buffer)\n {\n php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"illegal unserialize data\");\n return NULL;\n }\n ZVAL_NEW_ARR(zvalue);\n //Initialize buckets\n zend_array *ht = Z_ARR_P(zvalue);\n ht->nTableSize = size;\n ht->nNumUsed = nNumOfElements;\n ht->nNumOfElements = nNumOfElements;\n ht->nNextFreeElement = 0;\n#ifdef HASH_FLAG_APPLY_PROTECTION\n ht->u.flags = HASH_FLAG_APPLY_PROTECTION;\n#endif\n ht->nTableMask = -(ht->nTableSize);\n ht->pDestructor = ZVAL_PTR_DTOR;\n\n GC_SET_REFCOUNT(ht, 1);\n GC_TYPE_INFO(ht) = IS_ARRAY;\n // if (ht->nNumUsed)\n //{\n // void *arData = ecalloc(1, len);\n HT_SET_DATA_ADDR(ht, emalloc(HT_SIZE(ht)));\n ht->u.flags |= HASH_FLAG_INITIALIZED;\n int ht_hash_size = HT_HASH_SIZE((ht)->nTableMask);\n if (ht_hash_size <= 0)\n {\n php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"illegal unserialize data\");\n return NULL;\n }\n HT_HASH_RESET(ht);\n //}\n\n\n int idx;\n Bucket *p;\n for(idx = 0; idx < nNumOfElements; idx++)\n {\n if (!buffer)\n {\n php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"illegal array unserialize data\");\n return NULL;\n }\n SBucketType type = *((SBucketType*) buffer);\n buffer += sizeof (SBucketType);\n p = ht->arData + idx;\n /* Initialize key */\n if (type.key_type == KEY_TYPE_STRING)\n {\n size_t key_len;\n if (type.key_len == 3)\n {//read the same mem\n void *str_pool_addr = get_pack_string_len_addr(&buffer, &key_len);\n p->key = zend_string_init((char*) str_pool_addr, key_len, 0);\n h = zend_inline_hash_func((char*) str_pool_addr, key_len);\n p->key->h = p->h = h;\n }\n else\n {//move step\n if (type.key_len == 1)\n {\n key_len = *((zend_uchar*) buffer);\n buffer += sizeof (zend_uchar);\n }\n else if (type.key_len == 2)\n {\n key_len = *((unsigned short*) buffer);\n buffer += sizeof (unsigned short);\n }\n else\n {\n key_len = *((size_t*) buffer);\n buffer += sizeof (size_t);\n }\n p->key = zend_string_init((char*) buffer, key_len, 0);\n // h = zend_inline_hash_func((char*) buffer, key_len);\n h = zend_inline_hash_func((char*) buffer, key_len);\n buffer += key_len;\n p->key->h = p->h = h;\n }\n }\n else\n {\n if (type.key_len == 0)\n {\n //means pack\n h = p->h = idx;\n p->key = NULL;\n max_index = p->h + 1;\n // ht->u.flags |= HASH_FLAG_PACKED;\n }\n else\n {\n if (type.key_len == 1)\n {\n h = *((zend_uchar*) buffer);\n buffer += sizeof (zend_uchar);\n }\n else if (type.key_len == 2)\n {\n h = *((unsigned short*) buffer);\n buffer += sizeof (unsigned short);\n }\n else\n {\n h = *((zend_ulong*) buffer);\n buffer += sizeof (zend_ulong);\n }\n p->h = h;\n p->key = NULL;\n if (h >= max_index)\n {\n max_index = h + 1;\n }\n }\n }\n /* Initialize hash */\n nIndex = h | ht->nTableMask;\n Z_NEXT(p->val) = HT_HASH(ht, nIndex);\n HT_HASH(ht, nIndex) = HT_IDX_TO_HASH(idx);\n\n /* Initialize data type */\n p->val.u1.v.type = type.data_type;\n Z_TYPE_FLAGS(p->val) = 0;\n\n /* Initialize data */\n if (type.data_type == IS_STRING)\n {\n size_t data_len;\n if (type.data_len == 3)\n {//read the same mem\n void *str_pool_addr = get_pack_string_len_addr(&buffer, &data_len);\n p->val.value.str = zend_string_init((char*) str_pool_addr, data_len, 0);\n }\n else\n {\n if (type.data_len == 1)\n {\n data_len = *((zend_uchar*) buffer);\n buffer += sizeof (zend_uchar);\n }\n else if (type.data_len == 2)\n {\n data_len = *((unsigned short*) buffer);\n buffer += sizeof (unsigned short);\n }\n else\n {\n data_len = *((size_t*) buffer);\n buffer += sizeof (size_t);\n }\n p->val.value.str = zend_string_init((char*) buffer, data_len, 0);\n buffer += data_len;\n }\n Z_TYPE_INFO(p->val) = IS_STRING_EX;\n }\n else if (type.data_type == IS_ARRAY)\n {\n uint32_t num = 0;\n buffer = get_array_real_len(buffer, type.data_len, &num);\n buffer = swoole_unserialize_arr(buffer, &p->val, num, flag);\n }\n else if (type.data_type == IS_LONG)\n {\n buffer = swoole_unserialize_long(buffer, &p->val, type);\n }\n else if (type.data_type == IS_DOUBLE)\n {\n p->val.value = *((zend_value*) buffer);\n buffer += sizeof (zend_value);\n }\n else if (type.data_type == IS_UNDEF)\n {\n buffer = swoole_unserialize_object(buffer, &p->val, type.data_len, NULL, flag);\n Z_TYPE_INFO(p->val) = IS_OBJECT_EX;\n }\n\n }\n ht->nNextFreeElement = max_index;\n\n return buffer;\n\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: main (\n int argc,\n char *argv[]\n)\n{\n int exit_val;\n fribidi_boolean file_found;\n char *s;\n FILE *IN;\n\n text_width = default_text_width;\n do_break = true;\n do_pad = true;\n do_mirror = true;\n do_clean = false;\n do_reorder_nsm = false;\n show_input = false;\n show_visual = true;\n show_basedir = false;\n show_ltov = false;\n show_vtol = false;\n show_levels = false;\n char_set = \"UTF-8\";\n bol_text = NULL;\n eol_text = NULL;\n input_base_direction = FRIBIDI_PAR_ON;\n\n if ((s = (char *) getenv (\"COLUMNS\")))\n {\n int i;\n\n i = atoi (s);\n if (i > 0)\n\ttext_width = i;\n }\n\n#define CHARSETDESC 257\n#define CAPRTL 258\n\n /* Parse the command line with getopt library */\n /* Must set argv[0], getopt uses it to generate error messages */\n argv[0] = appname;\n while (1)\n {\n int option_index = 0, c;\n static struct option long_options[] = {\n\t{\"help\", 0, 0, 'h'},\n\t{\"version\", 0, 0, 'V'},\n\t{\"verbose\", 0, 0, 'v'},\n\t{\"debug\", 0, 0, 'd'},\n\t{\"test\", 0, 0, 't'},\n\t{\"charset\", 1, 0, 'c'},\n\t{\"charsetdesc\", 1, 0, CHARSETDESC},\n\t{\"caprtl\", 0, 0, CAPRTL},\n\t{\"showinput\", 0, (int *) (void *) &show_input, true},\n\t{\"nopad\", 0, (int *) (void *) &do_pad, false},\n\t{\"nobreak\", 0, (int *) (void *) &do_break, false},\n\t{\"width\", 1, 0, 'w'},\n\t{\"bol\", 1, 0, 'B'},\n\t{\"eol\", 1, 0, 'E'},\n\t{\"nomirror\", 0, (int *) (void *) &do_mirror, false},\n\t{\"reordernsm\", 0, (int *) (void *) &do_reorder_nsm, true},\n\t{\"clean\", 0, (int *) (void *) &do_clean, true},\n\t{\"ltr\", 0, (int *) (void *) &input_base_direction, FRIBIDI_PAR_LTR},\n\t{\"rtl\", 0, (int *) (void *) &input_base_direction, FRIBIDI_PAR_RTL},\n\t{\"wltr\", 0, (int *) (void *) &input_base_direction,\n\t FRIBIDI_PAR_WLTR},\n\t{\"wrtl\", 0, (int *) (void *) &input_base_direction,\n\t FRIBIDI_PAR_WRTL},\n\t{\"basedir\", 0, (int *) (void *) &show_basedir, true},\n\t{\"ltov\", 0, (int *) (void *) &show_ltov, true},\n\t{\"vtol\", 0, (int *) (void *) &show_vtol, true},\n\t{\"levels\", 0, (int *) (void *) &show_levels, true},\n\t{\"novisual\", 0, (int *) (void *) &show_visual, false},\n\t{0, 0, 0, 0}\n };\n\n c =\n\tgetopt_long (argc, argv, \"hVvdtc:w:B:E:\", long_options,\n\t\t &option_index);\n if (c == -1)\n\tbreak;\n\n switch (c)\n\t{\n\tcase 0:\n\t break;\n\tcase 'h':\n\t help ();\n\t break;\n\tcase 'V':\n\t version ();\n\t break;\n\tcase 'v':\n\t show_basedir = show_ltov = show_vtol = show_levels = true;\n\t break;\n\tcase 'w':\n\t text_width = atoi (optarg);\n\t if (text_width <= 0)\n\t die2 (\"invalid screen width `%s'\\n\", optarg);\n\t break;\n\tcase 'B':\n\t bol_text = optarg;\n\t break;\n\tcase 'E':\n\t eol_text = optarg;\n\t break;\n\tcase 'd':\n\t if (!fribidi_set_debug (true))\n\t die1\n\t (\"lib\" FRIBIDI\n\t \" must be compiled with DEBUG option to enable\\nturn debug info on.\\n\");\n\t break;\n\tcase 't':\n\t do_clean = show_input = do_reorder_nsm = true;\n\t do_break = false;\n\t text_width = default_text_width;\n\t break;\n\tcase 'c':\n\t char_set = my_fribidi_strdup (optarg);\n\t if (!char_set)\n\t die1 (\"memory allocation failed for char_set!\");\n\t break;\n\tcase CAPRTL:\n\t char_set = \"CapRTL\";\n\t break;\n\tcase CHARSETDESC:\n\t char_set = optarg;\n\t char_set_num = fribidi_parse_charset (char_set);\n\t if (!char_set_num)\n\t die2 (\"unrecognized character set `%s'\\n\", char_set);\n\t if (!fribidi_char_set_desc (char_set_num))\n\t die2 (\"no description available for character set `%s'\\n\",\n\t\t fribidi_char_set_name (char_set_num));\n\t else\n\t printf (\"Descriptions for character set %s:\\n\"\n\t\t \"\\n\" \"%s\", fribidi_char_set_title (char_set_num),\n\t\t fribidi_char_set_desc (char_set_num));\n\t exit (0);\n\t break;\n\tcase ':':\n\tcase '?':\n\t die2 (NULL, NULL);\n\t break;\n\tdefault:\n\t break;\n\t}\n }\n\n char_set_num = fribidi_parse_charset (char_set);\n\n if (!char_set_num)\n die2 (\"unrecognized character set `%s'\\n\", char_set);\n\nFRIBIDI_BEGIN_IGNORE_DEPRECATIONS\n fribidi_set_mirroring (do_mirror);\n fribidi_set_reorder_nsm (do_reorder_nsm);\nFRIBIDI_END_IGNORE_DEPRECATIONS\n exit_val = 0;\n file_found = false;\n while (optind < argc || !file_found)\n {\n const char *filename;\n\n filename = optind < argc ? argv[optind++] : \"-\";\n file_found = true;\n\n /* Open the infile for reading */\n if (filename[0] == '-' && !filename[1])\n\t{\n\t IN = stdin;\n\t}\n else\n\t{\n\t IN = fopen (filename, \"r\");\n\t if (!IN)\n\t {\n\t fprintf (stderr, \"%s: %s: no such file or directory\\n\",\n\t\t appname, filename);\n\t exit_val = 1;\n\t continue;\n\t }\n\t}\n\n /* Read and process input one line at a time */\n {\n\tchar S_[MAX_STR_LEN];\n\tint padding_width, break_width;\n\n\tpadding_width = show_input ? (text_width - 10) / 2 : text_width;\n\tbreak_width = do_break ? padding_width : 3 * MAX_STR_LEN;\n\n\twhile (fgets (S_, sizeof (S_) - 1, IN))\n\t {\n\t const char *new_line, *nl_found;\n\t FriBidiChar logical[MAX_STR_LEN];\n\t char outstring[MAX_STR_LEN];\n\t FriBidiParType base;\n\t FriBidiStrIndex len;\n\n\t nl_found = \"\";\n\t S_[sizeof (S_) - 1] = 0;\n\t len = strlen (S_);\n\t /* chop */\n\t if (S_[len - 1] == '\\n')\n\t {\n\t\tlen--;\n\t\tS_[len] = '\\0';\n\t\tnew_line = \"\\n\";\n\t }\n\t else\n\t new_line = \"\";\n\t /* TODO: handle \\r */\n\n\t len = fribidi_charset_to_unicode (char_set_num, S_, len, logical);\n\n\t {\n\t FriBidiChar *visual;\n\t FriBidiStrIndex *ltov, *vtol;\n\t FriBidiLevel *levels;\n\t fribidi_boolean log2vis;\n\n\t visual = show_visual ? ALLOCATE (FriBidiChar,\n\t\t\t\t\t len + 1\n\t ) : NULL;\n\t ltov = show_ltov ? ALLOCATE (FriBidiStrIndex,\n\t\t\t\t\t len + 1\n\t ) : NULL;\n\t vtol = show_vtol ? ALLOCATE (FriBidiStrIndex,\n\t\t\t\t\t len + 1\n\t ) : NULL;\n\t levels = show_levels ? ALLOCATE (FriBidiLevel,\n\t\t\t\t\t len + 1\n\t ) : NULL;\n\n\t /* Create a bidi string. */\n\t base = input_base_direction;\n\n\t log2vis = fribidi_log2vis (logical, len, &base,\n\t\t\t\t\t /* output */\n\t\t\t\t\t visual, ltov, vtol, levels);\n\n\t if (log2vis)\n\t\t{\n\n\t\t if (show_input)\n\t\t printf (\"%-*s => \", padding_width, S_);\n\n\t\t /* Remove explicit marks, if asked for. */\n\n\t\t if (do_clean)\n\t\t len =\n\t\t fribidi_remove_bidi_marks (visual, len, ltov, vtol,\n\t\t\t\t\t\t levels);\n\n\t\t if (show_visual)\n\t\t {\n\t\t printf (\"%s\", nl_found);\n\n\t\t if (bol_text)\n\t\t\tprintf (\"%s\", bol_text);\n\n\t\t /* Convert it to input charset and print. */\n\t\t {\n\t\t\tFriBidiStrIndex idx, st;\n\t\t\tfor (idx = 0; idx < len;)\n\t\t\t {\n\t\t\t FriBidiStrIndex wid, inlen;\n\n\t\t\t wid = break_width;\n\t\t\t st = idx;\n\t\t\t if (char_set_num != FRIBIDI_CHAR_SET_CAP_RTL)\n\t\t\t while (wid > 0 && idx < len)\n\t\t\t\t{\n\t\t\t\t wid -=\n\t\t\t\t FRIBIDI_IS_EXPLICIT_OR_ISOLATE_OR_BN_OR_NSM\n\t\t\t\t (fribidi_get_bidi_type (visual[idx])) ? 0\n\t\t\t\t : 1;\n\t\t\t\t idx++;\n\t\t\t\t}\n\t\t\t else\n\t\t\t while (wid > 0 && idx < len)\n\t\t\t\t{\n\t\t\t\t wid--;\n\t\t\t\t idx++;\n\t\t\t\t}\n\t\t\t if (wid < 0 && idx - st > 1)\n\t\t\t idx--;\n\t\t\t inlen = idx - st;\n\n\t\t\t fribidi_unicode_to_charset (char_set_num,\n\t\t\t\t\t\t\tvisual + st, inlen,\n\t\t\t\t\t\t\toutstring);\n\t\t\t if (FRIBIDI_IS_RTL (base))\n\t\t\t printf (\"%*s\",\n\t\t\t\t (int) (do_pad ? (padding_width +\n\t\t\t\t\t\t strlen (outstring) -\n\t\t\t\t\t\t (break_width -\n\t\t\t\t\t\t\twid)) : 0),\n\t\t\t\t outstring);\n\t\t\t else\n\t\t\t printf (\"%s\", outstring);\n\t\t\t if (idx < len)\n\t\t\t printf (\"\\n\");\n\t\t\t }\n\t\t }\n\t\t if (eol_text)\n\t\t\tprintf (\"%s\", eol_text);\n\n\t\t nl_found = \"\\n\";\n\t\t }\n\t\t if (show_basedir)\n\t\t {\n\t\t printf (\"%s\", nl_found);\n\t\t printf (\"Base direction: %s\",\n\t\t\t (FRIBIDI_DIR_TO_LEVEL (base) ? \"R\" : \"L\"));\n\t\t nl_found = \"\\n\";\n\t\t }\n\t\t if (show_ltov)\n\t\t {\n\t\t FriBidiStrIndex i;\n\n\t\t printf (\"%s\", nl_found);\n\t\t for (i = 0; i < len; i++)\n\t\t\tprintf (\"%ld \", (long) ltov[i]);\n\t\t nl_found = \"\\n\";\n\t\t }\n\t\t if (show_vtol)\n\t\t {\n\t\t FriBidiStrIndex i;\n\n\t\t printf (\"%s\", nl_found);\n\t\t for (i = 0; i < len; i++)\n\t\t\tprintf (\"%ld \", (long) vtol[i]);\n\t\t nl_found = \"\\n\";\n\t\t }\n\t\t if (show_levels)\n\t\t {\n\t\t FriBidiStrIndex i;\n\n\t\t printf (\"%s\", nl_found);\n\t\t for (i = 0; i < len; i++)\n\t\t\tprintf (\"%d \", (int) levels[i]);\n\t\t nl_found = \"\\n\";\n\t\t }\n\t\t}\n\t else\n\t\t{\n\t\t exit_val = 2;\n\t\t}\n\n\t if (show_visual)\n\t\tfree (visual);\n\t if (show_ltov)\n\t\tfree (ltov);\n\t if (show_vtol)\n\t\tfree (vtol);\n\t if (show_levels)\n\t\tfree (levels);\n\t }\n\n\t if (*nl_found)\n\t printf (\"%s\", new_line);\n\t }\n }\n }\n\n return exit_val;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix the stack buffer overflow issue\n\nstrlen() could returns 0. Without a conditional check for len,\naccessing S_ pointer with len - 1 may causes a stack buffer overflow.\n\nAddressSanitizer reports this like:\n==1219243==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7ffdce043c1f at pc 0x000000403547 bp 0x7ffdce0\n43b30 sp 0x7ffdce043b28\nREAD of size 1 at 0x7ffdce043c1f thread T0\n #0 0x403546 in main ../bin/fribidi-main.c:393\n #1 0x7f226804e58f in __libc_start_call_main (/lib64/libc.so.6+0x2d58f)\n #2 0x7f226804e648 in __libc_start_main_impl (/lib64/libc.so.6+0x2d648)\n #3 0x4036f4 in _start (/tmp/fribidi/build/bin/fribidi+0x4036f4)\n\nAddress 0x7ffdce043c1f is located in stack of thread T0 at offset 63 in frame\n #0 0x4022bf in main ../bin/fribidi-main.c:193\n\n This frame has 5 object(s):\n [32, 36) 'option_index' (line 233)\n [48, 52) 'base' (line 386)\n [64, 65064) 'S_' (line 375) <== Memory access at offset 63 underflows this variable\n [65328, 130328) 'outstring' (line 385)\n [130592, 390592) 'logical' (line 384)\n\nThis fixes https://github.com/fribidi/fribidi/issues/181'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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 count_type __read_io_type(struct page *page)\n{\n\tstruct address_space *mapping = page->mapping;\n\n\tif (mapping) {\n\t\tstruct inode *inode = mapping->host;\n\t\tstruct f2fs_sb_info *sbi = F2FS_I_SB(inode);\n\n\t\tif (inode->i_ino == F2FS_META_INO(sbi))\n\t\t\treturn F2FS_RD_META;\n\n\t\tif (inode->i_ino == F2FS_NODE_INO(sbi))\n\t\t\treturn F2FS_RD_NODE;\n\t}\n\treturn F2FS_RD_DATA;\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: char *parse_mount_options(ntfs_fuse_context_t *ctx,\n\t\t\tconst struct ntfs_options *popts, BOOL low_fuse)\n{\n\tchar *options, *s, *opt, *val, *ret = NULL;\n\tconst char *orig_opts = popts->options;\n\tBOOL no_def_opts = FALSE;\n\tint default_permissions = 0;\n\tint permissions = 0;\n\tint acl = 0;\n\tint want_permissions = 0;\n\tint intarg;\n\tconst struct DEFOPTION *poptl;\n\n\tctx->secure_flags = 0;\n#ifdef HAVE_SETXATTR\t/* extended attributes interface required */\n\tctx->efs_raw = FALSE;\n#endif /* HAVE_SETXATTR */\n\tctx->compression = DEFAULT_COMPRESSION;\n\toptions = strdup(orig_opts ? orig_opts : \"\");\n\tif (!options) {\n\t\tntfs_log_perror(\"%s: strdup failed\", EXEC_NAME);\n\t\treturn NULL;\n\t}\n\t\n\ts = options;\n\twhile (s && *s && (val = strsep(&s, \",\"))) {\n\t\topt = strsep(&val, \"=\");\n\t\tpoptl = optionlist;\n\t\twhile (poptl->name && strcmp(poptl->name,opt))\n\t\t\tpoptl++;\n\t\tif (poptl->name) {\n\t\t\tif ((poptl->flags & FLGOPT_BOGUS)\n\t\t\t && bogus_option_value(val, opt))\n\t\t\t\tgoto err_exit;\n\t\t\tif ((poptl->flags & FLGOPT_OCTAL)\n\t\t\t && (!val\n\t\t\t\t|| !sscanf(val, \"%o\", &intarg))) {\n\t\t\t\tntfs_log_error(\"'%s' option needs an octal value\\n\",\n\t\t\t\t\topt);\n\t\t\t\tgoto err_exit;\n\t\t\t}\n\t\t\tif (poptl->flags & FLGOPT_DECIMAL) {\n\t\t\t\tif ((poptl->flags & FLGOPT_OPTIONAL) && !val)\n\t\t\t\t\tintarg = 0;\n\t\t\t\telse\n\t\t\t\t\tif (!val\n\t\t\t\t\t || !sscanf(val, \"%i\", &intarg)) {\n\t\t\t\t\t\tntfs_log_error(\"'%s' option \"\n\t\t\t\t\t\t \"needs a decimal value\\n\",\n\t\t\t\t\t\t\topt);\n\t\t\t\t\t\tgoto err_exit;\n\t\t\t\t\t}\n\t\t\t}\n\t\t\tif ((poptl->flags & FLGOPT_STRING)\n\t\t\t && missing_option_value(val, opt))\n\t\t\t\tgoto err_exit;\n\n\t\t\tswitch (poptl->type) {\n\t\t\tcase OPT_RO :\n\t\t\tcase OPT_FAKE_RW :\n\t\t\t\tctx->ro = TRUE;\n\t\t\t\tbreak;\n\t\t\tcase OPT_RW :\n\t\t\t\tctx->rw = TRUE;\n\t\t\t\tbreak;\n\t\t\tcase OPT_NOATIME :\n\t\t\t\tctx->atime = ATIME_DISABLED;\n\t\t\t\tbreak;\n\t\t\tcase OPT_ATIME :\n\t\t\t\tctx->atime = ATIME_ENABLED;\n\t\t\t\tbreak;\n\t\t\tcase OPT_RELATIME :\n\t\t\t\tctx->atime = ATIME_RELATIVE;\n\t\t\t\tbreak;\n\t\t\tcase OPT_DMTIME :\n\t\t\t\tif (!intarg)\n\t\t\t\t\tintarg = DEFAULT_DMTIME;\n\t\t\t\tctx->dmtime = intarg*10000000LL;\n\t\t\t\tbreak;\n\t\t\tcase OPT_NO_DEF_OPTS :\n\t\t\t\tno_def_opts = TRUE; /* Don't add default options. */\n\t\t\t\tctx->silent = FALSE; /* cancel default silent */\n\t\t\t\tbreak;\n\t\t\tcase OPT_DEFAULT_PERMISSIONS :\n\t\t\t\tdefault_permissions = 1;\n\t\t\t\tbreak;\n\t\t\tcase OPT_PERMISSIONS :\n\t\t\t\tpermissions = 1;\n\t\t\t\tbreak;\n#if POSIXACLS\n\t\t\tcase OPT_ACL :\n\t\t\t\tacl = 1;\n\t\t\t\tbreak;\n#endif\n\t\t\tcase OPT_UMASK :\n\t\t\t\tctx->dmask = ctx->fmask = intarg;\n\t\t\t\twant_permissions = 1;\n\t\t\t\tbreak;\n\t\t\tcase OPT_FMASK :\n\t\t\t\tctx->fmask = intarg;\n\t\t\t \twant_permissions = 1;\n\t\t\t\tbreak;\n\t\t\tcase OPT_DMASK :\n\t\t\t\tctx->dmask = intarg;\n\t\t\t \twant_permissions = 1;\n\t\t\t\tbreak;\n\t\t\tcase OPT_UID :\n\t\t\t\tctx->uid = intarg;\n\t\t\t \twant_permissions = 1;\n\t\t\t\tbreak;\n\t\t\tcase OPT_GID :\n\t\t\t\tctx->gid = intarg;\n\t\t\t\twant_permissions = 1;\n\t\t\t\tbreak;\n\t\t\tcase OPT_SHOW_SYS_FILES :\n\t\t\t\tctx->show_sys_files = TRUE;\n\t\t\t\tbreak;\n\t\t\tcase OPT_HIDE_HID_FILES :\n\t\t\t\tctx->hide_hid_files = TRUE;\n\t\t\t\tbreak;\n\t\t\tcase OPT_HIDE_DOT_FILES :\n\t\t\t\tctx->hide_dot_files = TRUE;\n\t\t\t\tbreak;\n\t\t\tcase OPT_WINDOWS_NAMES :\n\t\t\t\tctx->windows_names = TRUE;\n\t\t\t\tbreak;\n\t\t\tcase OPT_IGNORE_CASE :\n\t\t\t\tif (low_fuse)\n\t\t\t\t\tctx->ignore_case = TRUE;\n\t\t\t\telse {\n\t\t\t\t\tntfs_log_error(\"'%s' is an unsupported option.\\n\",\n\t\t\t\t\t\tpoptl->name);\n\t\t\t\t\tgoto err_exit;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase OPT_COMPRESSION :\n\t\t\t\tctx->compression = TRUE;\n\t\t\t\tbreak;\n\t\t\tcase OPT_NOCOMPRESSION :\n\t\t\t\tctx->compression = FALSE;\n\t\t\t\tbreak;\n\t\t\tcase OPT_SILENT :\n\t\t\t\tctx->silent = TRUE;\n\t\t\t\tbreak;\n\t\t\tcase OPT_RECOVER :\n\t\t\t\tctx->recover = TRUE;\n\t\t\t\tbreak;\n\t\t\tcase OPT_NORECOVER :\n\t\t\t\tctx->recover = FALSE;\n\t\t\t\tbreak;\n\t\t\tcase OPT_REMOVE_HIBERFILE :\n\t\t\t\tctx->hiberfile = TRUE;\n\t\t\t\tbreak;\n\t\t\tcase OPT_SYNC :\n\t\t\t\tctx->sync = TRUE;\n\t\t\t\tbreak;\n#ifdef FUSE_CAP_BIG_WRITES\n\t\t\tcase OPT_BIG_WRITES :\n\t\t\t\tctx->big_writes = TRUE;\n\t\t\t\tbreak;\n#endif\n\t\t\tcase OPT_LOCALE :\n\t\t\t\tntfs_set_char_encoding(val);\n\t\t\t\tbreak;\n#if defined(__APPLE__) || defined(__DARWIN__)\n#ifdef ENABLE_NFCONV\n\t\t\tcase OPT_NFCONV :\n\t\t\t\tif (ntfs_macosx_normalize_filenames(1)) {\n\t\t\t\t\tntfs_log_error(\"ntfs_macosx_normalize_filenames(1) failed!\\n\");\n\t\t\t\t\tgoto err_exit;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase OPT_NONFCONV :\n\t\t\t\tif (ntfs_macosx_normalize_filenames(0)) {\n\t\t\t\t\tntfs_log_error(\"ntfs_macosx_normalize_filenames(0) failed!\\n\");\n\t\t\t\t\tgoto err_exit;\n\t\t\t\t}\n\t\t\t\tbreak;\n#endif /* ENABLE_NFCONV */\n#endif /* defined(__APPLE__) || defined(__DARWIN__) */\n\t\t\tcase OPT_STREAMS_INTERFACE :\n\t\t\t\tif (!strcmp(val, \"none\"))\n\t\t\t\t\tctx->streams = NF_STREAMS_INTERFACE_NONE;\n\t\t\t\telse if (!strcmp(val, \"xattr\"))\n\t\t\t\t\tctx->streams = NF_STREAMS_INTERFACE_XATTR;\n\t\t\t\telse if (!strcmp(val, \"openxattr\"))\n\t\t\t\t\tctx->streams = NF_STREAMS_INTERFACE_OPENXATTR;\n\t\t\t\telse if (!low_fuse && !strcmp(val, \"windows\"))\n\t\t\t\t\tctx->streams = NF_STREAMS_INTERFACE_WINDOWS;\n\t\t\t\telse {\n\t\t\t\t\tntfs_log_error(\"Invalid named data streams \"\n\t\t\t\t\t\t\"access interface.\\n\");\n\t\t\t\t\tgoto err_exit;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase OPT_USER_XATTR :\n#if defined(__APPLE__) || defined(__DARWIN__)\n\t\t\t\t/* macOS builds use non-namespaced extended\n\t\t\t\t * attributes by default since it matches the\n\t\t\t\t * standard behaviour of macOS filesystems. */\n\t\t\t\tctx->streams = NF_STREAMS_INTERFACE_OPENXATTR;\n#else\n\t\t\t\tctx->streams = NF_STREAMS_INTERFACE_XATTR;\n#endif\n\t\t\t\tbreak;\n\t\t\tcase OPT_NOAUTO :\n\t\t\t\t/* Don't pass noauto option to fuse. */\n\t\t\t\tbreak;\n\t\t\tcase OPT_DEBUG :\n\t\t\t\tctx->debug = TRUE;\n\t\t\t\tntfs_log_set_levels(NTFS_LOG_LEVEL_DEBUG);\n\t\t\t\tntfs_log_set_levels(NTFS_LOG_LEVEL_TRACE);\n\t\t\t\tbreak;\n\t\t\tcase OPT_NO_DETACH :\n\t\t\t\tctx->no_detach = TRUE;\n\t\t\t\tbreak;\n\t\t\tcase OPT_REMOUNT :\n\t\t\t\tntfs_log_error(\"Remounting is not supported at present.\"\n\t\t\t\t\t\" You have to umount volume and then \"\n\t\t\t\t\t\"mount it once again.\\n\");\n\t\t\t\tgoto err_exit;\n\t\t\tcase OPT_BLKSIZE :\n\t\t\t\tntfs_log_info(\"WARNING: blksize option is ignored \"\n\t\t\t\t \"because ntfs-3g must calculate it.\\n\");\n\t\t\t\tbreak;\n\t\t\tcase OPT_INHERIT :\n\t\t\t\t/*\n\t\t\t\t * do not overwrite inherited permissions\n\t\t\t\t * in create()\n\t\t\t\t */\n\t\t\t\tctx->inherit = TRUE;\n\t\t\t\tbreak;\n\t\t\tcase OPT_ADDSECURIDS :\n\t\t\t\t/*\n\t\t\t\t * create security ids for files being read\n\t\t\t\t * with an individual security attribute\n\t\t\t\t */\n\t\t\t\tctx->secure_flags |= (1 << SECURITY_ADDSECURIDS);\n\t\t\t\tbreak;\n\t\t\tcase OPT_STATICGRPS :\n\t\t\t\t/*\n\t\t\t\t * use static definition of groups\n\t\t\t\t * for file access control\n\t\t\t\t */\n\t\t\t\tctx->secure_flags |= (1 << SECURITY_STATICGRPS);\n\t\t\t\tbreak;\n\t\t\tcase OPT_USERMAPPING :\n\t\t\t\tctx->usermap_path = strdup(val);\n\t\t\t\tif (!ctx->usermap_path) {\n\t\t\t\t\tntfs_log_error(\"no more memory to store \"\n\t\t\t\t\t\t\"'usermapping' option.\\n\");\n\t\t\t\t\tgoto err_exit;\n\t\t\t\t}\n\t\t\t\tbreak;\n#ifdef HAVE_SETXATTR\t/* extended attributes interface required */\n#ifdef XATTR_MAPPINGS\n\t\t\tcase OPT_XATTRMAPPING :\n\t\t\t\tctx->xattrmap_path = strdup(val);\n\t\t\t\tif (!ctx->xattrmap_path) {\n\t\t\t\t\tntfs_log_error(\"no more memory to store \"\n\t\t\t\t\t\t\"'xattrmapping' option.\\n\");\n\t\t\t\t\tgoto err_exit;\n\t\t\t\t}\n\t\t\t\tbreak;\n#endif /* XATTR_MAPPINGS */\n\t\t\tcase OPT_EFS_RAW :\n\t\t\t\tctx->efs_raw = TRUE;\n\t\t\t\tbreak;\n#endif /* HAVE_SETXATTR */\n\t\t\tcase OPT_POSIX_NLINK :\n\t\t\t\tctx->posix_nlink = TRUE;\n\t\t\t\tbreak;\n\t\t\tcase OPT_SPECIAL_FILES :\n\t\t\t\tif (!strcmp(val, \"interix\"))\n\t\t\t\t\tctx->special_files = NTFS_FILES_INTERIX;\n\t\t\t\telse if (!strcmp(val, \"wsl\"))\n\t\t\t\t\tctx->special_files = NTFS_FILES_WSL;\n\t\t\t\telse {\n\t\t\t\t\tntfs_log_error(\"Invalid special_files\"\n\t\t\t\t\t\t\" mode.\\n\");\n\t\t\t\t\tgoto err_exit;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase OPT_FSNAME : /* Filesystem name. */\n\t\t\t/*\n\t\t\t * We need this to be able to check whether filesystem\n\t\t\t * mounted or not.\n\t\t\t * (falling through to default)\n\t\t\t */\n\t\t\tdefault :\n\t\t\t\tntfs_log_error(\"'%s' is an unsupported option.\\n\",\n\t\t\t\t\tpoptl->name);\n\t\t\t\tgoto err_exit;\n\t\t\t}\n\t\t\tif ((poptl->flags & FLGOPT_APPEND)\n\t\t\t && (ntfs_strappend(&ret, poptl->name)\n\t\t\t\t || ntfs_strappend(&ret, \",\")))\n\t\t\t\tgoto err_exit;\n\t\t} else { /* Probably FUSE option. */\n\t\t\tif (ntfs_strappend(&ret, opt))\n\t\t\t\tgoto err_exit;\n\t\t\tif (val) {\n\t\t\t\tif (ntfs_strappend(&ret, \"=\"))\n\t\t\t\t\tgoto err_exit;\n\t\t\t\tif (ntfs_strappend(&ret, val))\n\t\t\t\t\tgoto err_exit;\n\t\t\t}\n\t\t\tif (ntfs_strappend(&ret, \",\"))\n\t\t\t\tgoto err_exit;\n\t\t}\n\t}\n\tif (!no_def_opts && ntfs_strappend(&ret, def_opts))\n\t\tgoto err_exit;\n\tif ((default_permissions || (permissions && !acl))\n\t\t\t&& ntfs_strappend(&ret, \"default_permissions,\"))\n\t\tgoto err_exit;\n\t\t\t/* The atime options exclude each other */\n\tif (ctx->atime == ATIME_RELATIVE && ntfs_strappend(&ret, \"relatime,\"))\n\t\tgoto err_exit;\n\telse if (ctx->atime == ATIME_ENABLED && ntfs_strappend(&ret, \"atime,\"))\n\t\tgoto err_exit;\n\telse if (ctx->atime == ATIME_DISABLED && ntfs_strappend(&ret, \"noatime,\"))\n\t\tgoto err_exit;\n\t\n\tif (ntfs_strappend(&ret, \"fsname=\"))\n\t\tgoto err_exit;\n\tif (ntfs_strappend(&ret, popts->device))\n\t\tgoto err_exit;\n\tif (permissions && !acl)\n\t\tctx->secure_flags |= (1 << SECURITY_DEFAULT);\n\tif (acl)\n\t\tctx->secure_flags |= (1 << SECURITY_ACL);\n\tif (want_permissions)\n\t\tctx->secure_flags |= (1 << SECURITY_WANTED);\n\tif (ctx->ro) {\n\t\tctx->secure_flags &= ~(1 << SECURITY_ADDSECURIDS);\n\t\tctx->hiberfile = FALSE;\n\t\tctx->rw = FALSE;\n\t}\nexit:\n\tfree(options);\n\treturn ret;\nerr_exit:\n\tfree(ret);\n\tret = NULL;\n\tgoto exit;\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_avp_print(netdissect_options *ndo, const u_char *dat, int length)\n{\n\tu_int len;\n\tconst uint16_t *ptr = (const uint16_t *)dat;\n\tuint16_t attr_type;\n\tint hidden = FALSE;\n\n\tif (length <= 0) {\n\t\treturn;\n\t}\n\n\tND_PRINT((ndo, \" \"));\n\n\tND_TCHECK(*ptr);\t/* Flags & Length */\n\tlen = EXTRACT_16BITS(ptr) & L2TP_AVP_HDR_LEN_MASK;\n\n\t/* If it is not long enough to contain the header, we'll give up. */\n\tif (len < 6)\n\t\tgoto trunc;\n\n\t/* If it goes past the end of the remaining length of the packet,\n\t we'll give up. */\n\tif (len > (u_int)length)\n\t\tgoto trunc;\n\n\t/* If it goes past the end of the remaining length of the captured\n\t data, we'll give up. */\n\tND_TCHECK2(*ptr, len);\n\t/* After this point, no need to worry about truncation */\n\n\tif (EXTRACT_16BITS(ptr) & L2TP_AVP_HDR_FLAG_MANDATORY) {\n\t\tND_PRINT((ndo, \"*\"));\n\t}\n\tif (EXTRACT_16BITS(ptr) & L2TP_AVP_HDR_FLAG_HIDDEN) {\n\t\thidden = TRUE;\n\t\tND_PRINT((ndo, \"?\"));\n\t}\n\tptr++;\n\n\tif (EXTRACT_16BITS(ptr)) {\n\t\t/* Vendor Specific Attribute */\n\t ND_PRINT((ndo, \"VENDOR%04x:\", EXTRACT_16BITS(ptr))); ptr++;\n\t\tND_PRINT((ndo, \"ATTR%04x\", EXTRACT_16BITS(ptr))); ptr++;\n\t\tND_PRINT((ndo, \"(\"));\n\t\tprint_octets(ndo, (const u_char *)ptr, len-6);\n\t\tND_PRINT((ndo, \")\"));\n\t} else {\n\t\t/* IETF-defined Attributes */\n\t\tptr++;\n\t\tattr_type = EXTRACT_16BITS(ptr); ptr++;\n\t\tND_PRINT((ndo, \"%s\", tok2str(l2tp_avp2str, \"AVP-#%u\", attr_type)));\n\t\tND_PRINT((ndo, \"(\"));\n\t\tif (hidden) {\n\t\t\tND_PRINT((ndo, \"???\"));\n\t\t} else {\n\t\t\tswitch (attr_type) {\n\t\t\tcase L2TP_AVP_MSGTYPE:\n\t\t\t\tl2tp_msgtype_print(ndo, (const u_char *)ptr);\n\t\t\t\tbreak;\n\t\t\tcase L2TP_AVP_RESULT_CODE:\n\t\t\t\tl2tp_result_code_print(ndo, (const u_char *)ptr, len-6);\n\t\t\t\tbreak;\n\t\t\tcase L2TP_AVP_PROTO_VER:\n\t\t\t\tl2tp_proto_ver_print(ndo, ptr);\n\t\t\t\tbreak;\n\t\t\tcase L2TP_AVP_FRAMING_CAP:\n\t\t\t\tl2tp_framing_cap_print(ndo, (const u_char *)ptr);\n\t\t\t\tbreak;\n\t\t\tcase L2TP_AVP_BEARER_CAP:\n\t\t\t\tl2tp_bearer_cap_print(ndo, (const u_char *)ptr);\n\t\t\t\tbreak;\n\t\t\tcase L2TP_AVP_TIE_BREAKER:\n\t\t\t\tprint_octets(ndo, (const u_char *)ptr, 8);\n\t\t\t\tbreak;\n\t\t\tcase L2TP_AVP_FIRM_VER:\n\t\t\tcase L2TP_AVP_ASSND_TUN_ID:\n\t\t\tcase L2TP_AVP_RECV_WIN_SIZE:\n\t\t\tcase L2TP_AVP_ASSND_SESS_ID:\n\t\t\t\tprint_16bits_val(ndo, ptr);\n\t\t\t\tbreak;\n\t\t\tcase L2TP_AVP_HOST_NAME:\n\t\t\tcase L2TP_AVP_VENDOR_NAME:\n\t\t\tcase L2TP_AVP_CALLING_NUMBER:\n\t\t\tcase L2TP_AVP_CALLED_NUMBER:\n\t\t\tcase L2TP_AVP_SUB_ADDRESS:\n\t\t\tcase L2TP_AVP_PROXY_AUTH_NAME:\n\t\t\tcase L2TP_AVP_PRIVATE_GRP_ID:\n\t\t\t\tprint_string(ndo, (const u_char *)ptr, len-6);\n\t\t\t\tbreak;\n\t\t\tcase L2TP_AVP_CHALLENGE:\n\t\t\tcase L2TP_AVP_INI_RECV_LCP:\n\t\t\tcase L2TP_AVP_LAST_SENT_LCP:\n\t\t\tcase L2TP_AVP_LAST_RECV_LCP:\n\t\t\tcase L2TP_AVP_PROXY_AUTH_CHAL:\n\t\t\tcase L2TP_AVP_PROXY_AUTH_RESP:\n\t\t\tcase L2TP_AVP_RANDOM_VECTOR:\n\t\t\t\tprint_octets(ndo, (const u_char *)ptr, len-6);\n\t\t\t\tbreak;\n\t\t\tcase L2TP_AVP_Q931_CC:\n\t\t\t\tl2tp_q931_cc_print(ndo, (const u_char *)ptr, len-6);\n\t\t\t\tbreak;\n\t\t\tcase L2TP_AVP_CHALLENGE_RESP:\n\t\t\t\tprint_octets(ndo, (const u_char *)ptr, 16);\n\t\t\t\tbreak;\n\t\t\tcase L2TP_AVP_CALL_SER_NUM:\n\t\t\tcase L2TP_AVP_MINIMUM_BPS:\n\t\t\tcase L2TP_AVP_MAXIMUM_BPS:\n\t\t\tcase L2TP_AVP_TX_CONN_SPEED:\n\t\t\tcase L2TP_AVP_PHY_CHANNEL_ID:\n\t\t\tcase L2TP_AVP_RX_CONN_SPEED:\n\t\t\t\tprint_32bits_val(ndo, (const uint32_t *)ptr);\n\t\t\t\tbreak;\n\t\t\tcase L2TP_AVP_BEARER_TYPE:\n\t\t\t\tl2tp_bearer_type_print(ndo, (const u_char *)ptr);\n\t\t\t\tbreak;\n\t\t\tcase L2TP_AVP_FRAMING_TYPE:\n\t\t\t\tl2tp_framing_type_print(ndo, (const u_char *)ptr);\n\t\t\t\tbreak;\n\t\t\tcase L2TP_AVP_PACKET_PROC_DELAY:\n\t\t\t\tl2tp_packet_proc_delay_print(ndo);\n\t\t\t\tbreak;\n\t\t\tcase L2TP_AVP_PROXY_AUTH_TYPE:\n\t\t\t\tl2tp_proxy_auth_type_print(ndo, (const u_char *)ptr);\n\t\t\t\tbreak;\n\t\t\tcase L2TP_AVP_PROXY_AUTH_ID:\n\t\t\t\tl2tp_proxy_auth_id_print(ndo, (const u_char *)ptr);\n\t\t\t\tbreak;\n\t\t\tcase L2TP_AVP_CALL_ERRORS:\n\t\t\t\tl2tp_call_errors_print(ndo, (const u_char *)ptr);\n\t\t\t\tbreak;\n\t\t\tcase L2TP_AVP_ACCM:\n\t\t\t\tl2tp_accm_print(ndo, (const u_char *)ptr);\n\t\t\t\tbreak;\n\t\t\tcase L2TP_AVP_SEQ_REQUIRED:\n\t\t\t\tbreak;\t/* No Attribute Value */\n\t\t\tcase L2TP_AVP_PPP_DISCON_CC:\n\t\t\t\tl2tp_ppp_discon_cc_print(ndo, (const u_char *)ptr, len-6);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tND_PRINT((ndo, \")\"));\n\t}\n\n\tl2tp_avp_print(ndo, dat+len, length-len);\n\treturn;\n\n trunc:\n\tND_PRINT((ndo, \"|...\"));\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: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\n const TfLiteTensor* ids;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &ids));\n const TfLiteTensor* indices;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &indices));\n const TfLiteTensor* dense_shape;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 2, &dense_shape));\n const TfLiteTensor* weights;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 3, &weights));\n const TfLiteTensor* value;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 4, &value));\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-190'], 'message': 'Fix a dangerous integer overflow and a malloc of negative size.\n\nPiperOrigin-RevId: 371254154\nChange-Id: I250a98a3df26328770167025670235a963a72da0'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool Decode(string_view encoded, std::string* raw) {\n for (auto iter = encoded.begin(); iter != encoded.end(); ++iter) {\n if (*iter == '%') {\n if (++iter == encoded.end()) {\n // Invalid URI string, two hexadecimal digits must follow '%'.\n return false;\n }\n\n int h_decimal = 0;\n if (!HexToDecimal(*iter, &h_decimal)) {\n return false;\n }\n\n if (++iter == encoded.end()) {\n // Invalid URI string, two hexadecimal digits must follow '%'.\n return false;\n }\n\n int l_decimal = 0;\n if (!HexToDecimal(*iter, &l_decimal)) {\n return false;\n }\n\n raw->push_back(static_cast((h_decimal << 4) + l_decimal));\n\n } else if (*iter > 127 || *iter < 0) {\n // Invalid encoded URI string, must be entirely ASCII.\n return false;\n } else {\n raw->push_back(*iter);\n }\n }\n\n return true;\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: mcs_recv_connect_response(STREAM mcs_data)\n{\n\tUNUSED(mcs_data);\n\tuint8 result;\n\tint length;\n\tSTREAM s;\n\tRD_BOOL is_fastpath;\n\tuint8 fastpath_hdr;\n\n\tlogger(Protocol, Debug, \"%s()\", __func__);\n\ts = iso_recv(&is_fastpath, &fastpath_hdr);\n\n\tif (s == NULL)\n\t\treturn False;\n\n\tber_parse_header(s, MCS_CONNECT_RESPONSE, &length);\n\n\tber_parse_header(s, BER_TAG_RESULT, &length);\n\tin_uint8(s, result);\n\tif (result != 0)\n\t{\n\t\tlogger(Protocol, Error, \"mcs_recv_connect_response(), result=%d\", result);\n\t\treturn False;\n\t}\n\n\tber_parse_header(s, BER_TAG_INTEGER, &length);\n\tin_uint8s(s, length);\t/* connect id */\n\tmcs_parse_domain_params(s);\n\n\tber_parse_header(s, BER_TAG_OCTET_STRING, &length);\n\n\tsec_process_mcs_data(s);\n\t/*\n\t if (length > mcs_data->size)\n\t {\n\t logger(Protocol, Error, \"mcs_recv_connect_response(), expected length=%d, got %d\",length, mcs_data->size);\n\t length = mcs_data->size;\n\t }\n\n\t in_uint8a(s, mcs_data->data, length);\n\t mcs_data->p = mcs_data->data;\n\t mcs_data->end = mcs_data->data + length;\n\t */\n\treturn s_check_end(s);\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: cssp_read_tsrequest(STREAM token, STREAM pubkey)\n{\n\tSTREAM s;\n\tint length;\n\tint tagval;\n\n\ts = tcp_recv(NULL, 4);\n\n\tif (s == NULL)\n\t\treturn False;\n\n\t// verify ASN.1 header\n\tif (s->p[0] != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED))\n\t{\n\t\tlogger(Protocol, Error,\n\t\t \"cssp_read_tsrequest(), expected BER_TAG_SEQUENCE|BER_TAG_CONSTRUCTED, got %x\",\n\t\t s->p[0]);\n\t\treturn False;\n\t}\n\n\t// peek at first 4 bytes to get full message length\n\tif (s->p[1] < 0x80)\n\t\tlength = s->p[1] - 2;\n\telse if (s->p[1] == 0x81)\n\t\tlength = s->p[2] - 1;\n\telse if (s->p[1] == 0x82)\n\t\tlength = (s->p[2] << 8) | s->p[3];\n\telse\n\t\treturn False;\n\n\t// receive the remainings of message\n\ts = tcp_recv(s, length);\n\n\t// parse the response and into nego token\n\tif (!ber_in_header(s, &tagval, &length) ||\n\t tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED))\n\t\treturn False;\n\n\t// version [0]\n\tif (!ber_in_header(s, &tagval, &length) ||\n\t tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0))\n\t\treturn False;\n\tin_uint8s(s, length);\n\n\t// negoToken [1]\n\tif (token)\n\t{\n\t\tif (!ber_in_header(s, &tagval, &length)\n\t\t || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1))\n\t\t\treturn False;\n\t\tif (!ber_in_header(s, &tagval, &length)\n\t\t || tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED))\n\t\t\treturn False;\n\t\tif (!ber_in_header(s, &tagval, &length)\n\t\t || tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED))\n\t\t\treturn False;\n\t\tif (!ber_in_header(s, &tagval, &length)\n\t\t || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0))\n\t\t\treturn False;\n\n\t\tif (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING)\n\t\t\treturn False;\n\n\t\ttoken->end = token->p = token->data;\n\t\tout_uint8p(token, s->p, length);\n\t\ts_mark_end(token);\n\t}\n\n\t// pubKey [3]\n\tif (pubkey)\n\t{\n\t\tif (!ber_in_header(s, &tagval, &length)\n\t\t || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 3))\n\t\t\treturn False;\n\n\t\tif (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING)\n\t\t\treturn False;\n\n\t\tpubkey->data = pubkey->p = s->p;\n\t\tpubkey->end = pubkey->data + length;\n\t\tpubkey->size = length;\n\t}\n\n\n\treturn True;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-125', 'CWE-703', 'CWE-787'], 'message': 'Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ikev2_auth_print(netdissect_options *ndo, u_char tpay,\n\t\tconst struct isakmp_gen *ext,\n\t\tu_int item_len _U_, const u_char *ep,\n\t\tuint32_t phase _U_, uint32_t doi _U_,\n\t\tuint32_t proto _U_, int depth _U_)\n{\n\tstruct ikev2_auth a;\n\tconst char *v2_auth[]={ \"invalid\", \"rsasig\",\n\t\t\t\t\"shared-secret\", \"dsssig\" };\n\tconst u_char *authdata = (const u_char*)ext + sizeof(a);\n\tunsigned int len;\n\n\tND_TCHECK(*ext);\n\tUNALIGNED_MEMCPY(&a, ext, sizeof(a));\n\tikev2_pay_print(ndo, NPSTR(tpay), a.h.critical);\n\tlen = ntohs(a.h.len);\n\n\tND_PRINT((ndo,\" len=%d method=%s\", len-4,\n\t\t STR_OR_ID(a.auth_method, v2_auth)));\n\n\tif (1 < ndo->ndo_vflag && 4 < len) {\n\t\tND_PRINT((ndo,\" authdata=(\"));\n\t\tif (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a)))\n\t\t\tgoto trunc;\n\t\tND_PRINT((ndo,\") \"));\n\t} else if(ndo->ndo_vflag && 4 < len) {\n\t\tif(!ike_show_somedata(ndo, authdata, ep)) goto trunc;\n\t}\n\n\treturn (const u_char *)ext + len;\ntrunc:\n\tND_PRINT((ndo,\" [|%s]\", NPSTR(tpay)));\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 copy_to_user_tmpl(struct xfrm_policy *xp, struct sk_buff *skb)\n{\n\tstruct xfrm_user_tmpl vec[XFRM_MAX_DEPTH];\n\tint i;\n\n\tif (xp->xfrm_nr == 0)\n\t\treturn 0;\n\n\tfor (i = 0; i < xp->xfrm_nr; i++) {\n\t\tstruct xfrm_user_tmpl *up = &vec[i];\n\t\tstruct xfrm_tmpl *kp = &xp->xfrm_vec[i];\n\n\t\tmemcpy(&up->id, &kp->id, sizeof(up->id));\n\t\tup->family = kp->encap_family;\n\t\tmemcpy(&up->saddr, &kp->saddr, sizeof(up->saddr));\n\t\tup->reqid = kp->reqid;\n\t\tup->mode = kp->mode;\n\t\tup->share = kp->share;\n\t\tup->optional = kp->optional;\n\t\tup->aalgos = kp->aalgos;\n\t\tup->ealgos = kp->ealgos;\n\t\tup->calgos = kp->calgos;\n\t}\n\n\treturn nla_put(skb, XFRMA_TMPL,\n\t\t sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr, vec);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'xfrm_user: fix info leak in copy_to_user_tmpl()\n\nThe memory used for the template copy is a local stack variable. As\nstruct xfrm_user_tmpl contains multiple holes added by the compiler for\nalignment, not initializing the memory will lead to leaking stack bytes\nto userland. Add an explicit memset(0) to avoid the info leak.\n\nInitial version of the patch by Brad Spengler.\n\nCc: Brad Spengler \nSigned-off-by: Mathias Krause \nAcked-by: Steffen Klassert \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int crypto_pcomp_report(struct sk_buff *skb, struct crypto_alg *alg)\n{\n\tstruct crypto_report_comp rpcomp;\n\n\tsnprintf(rpcomp.type, CRYPTO_MAX_ALG_NAME, \"%s\", \"pcomp\");\n\n\tif (nla_put(skb, CRYPTOCFGA_REPORT_COMPRESS,\n\t\t sizeof(struct crypto_report_comp), &rpcomp))\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_rng_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: virtual void ComputeWithReservedSpace(OpKernelContext* context,\n bool use_reserved_space) {\n Tensor x = context->input(0);\n const Tensor& scale = context->input(1);\n const Tensor& offset = context->input(2);\n const Tensor& estimated_mean = context->input(3);\n const Tensor& estimated_variance = context->input(4);\n const Tensor* side_input = has_side_input_ ? &context->input(5) : nullptr;\n\n OP_REQUIRES(context, x.dims() == 4 || x.dims() == 5,\n errors::InvalidArgument(\"input must be 4 or 5-dimensional\",\n x.shape().DebugString()));\n OP_REQUIRES(context, scale.dims() == 1,\n errors::InvalidArgument(\"scale must be 1-dimensional\",\n scale.shape().DebugString()));\n OP_REQUIRES(context, offset.dims() == 1,\n errors::InvalidArgument(\"offset must be 1-dimensional\",\n offset.shape().DebugString()));\n OP_REQUIRES(context, estimated_mean.dims() == 1,\n errors::InvalidArgument(\"estimated_mean must be 1-dimensional\",\n estimated_mean.shape().DebugString()));\n OP_REQUIRES(\n context, estimated_variance.dims() == 1,\n errors::InvalidArgument(\"estimated_variance must be 1-dimensional\",\n estimated_variance.shape().DebugString()));\n bool use_reshape = (x.dims() == 5);\n auto x_shape = x.shape();\n TensorShape dest_shape;\n if (use_reshape) {\n const int64 in_batch = GetTensorDim(x, tensor_format_, 'N');\n int64 in_planes = GetTensorDim(x, tensor_format_, '0');\n int64 in_rows = GetTensorDim(x, tensor_format_, '1');\n int64 in_cols = GetTensorDim(x, tensor_format_, '2');\n const int64 in_depth = GetTensorDim(x, tensor_format_, 'C');\n dest_shape = ShapeFromFormat(tensor_format_, in_batch,\n {{in_planes, in_rows * in_cols}}, in_depth);\n OP_REQUIRES(context, x.CopyFrom(x, dest_shape),\n errors::InvalidArgument(\"Error during tensor copy.\"));\n }\n\n if (has_side_input_) {\n OP_REQUIRES(context, side_input->shape() == x.shape(),\n errors::InvalidArgument(\n \"side_input shape must be equal to input shape: \",\n side_input->shape().DebugString(),\n \" != \", x.shape().DebugString()));\n }\n\n if (activation_mode_ != FbnActivationMode::kIdentity) {\n // NOTE(ezhulenev): This requirement is coming from implementation\n // details of cudnnBatchNormalizationForwardTrainingEx.\n OP_REQUIRES(\n context, !is_training_ || x.dim_size(3) % 4 == 0,\n errors::InvalidArgument(\"FusedBatchNorm with activation requires \"\n \"channel dimension to be a multiple of 4.\"));\n }\n\n Tensor* y = nullptr;\n auto alloc_shape = use_reshape ? dest_shape : x_shape;\n OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(\n {0}, 0, alloc_shape, &y));\n\n Tensor* batch_mean = nullptr;\n OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(\n {3}, 1, scale.shape(), &batch_mean));\n Tensor* batch_var = nullptr;\n OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(\n {4}, 2, scale.shape(), &batch_var));\n Tensor* saved_mean = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(3, scale.shape(), &saved_mean));\n Tensor* saved_maybe_inv_var = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(4, scale.shape(),\n &saved_maybe_inv_var));\n\n if (is_training_) {\n functor::FusedBatchNorm()(\n context, x, scale, offset, estimated_mean, estimated_variance,\n side_input, epsilon_, exponential_avg_factor_, activation_mode_, y,\n batch_mean, batch_var, saved_mean, saved_maybe_inv_var,\n tensor_format_, use_reserved_space);\n } else {\n functor::FusedBatchNorm()(\n context, x, scale, offset, estimated_mean, estimated_variance,\n side_input, epsilon_, exponential_avg_factor_, activation_mode_, y,\n batch_mean, batch_var, saved_mean, saved_maybe_inv_var,\n tensor_format_, use_reserved_space);\n }\n if (use_reshape) {\n OP_REQUIRES(context, y->CopyFrom(*y, x_shape),\n errors::InvalidArgument(\"Error during tensor copy.\"));\n }\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-703'], 'message': 'Add missing valuidation to FusedBatchNorm.\n\nPiperOrigin-RevId: 372460336\nChange-Id: Ic8c4e4de67c58a741bd87f2e182bed07247d1126'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ssize_t aio_setup_iocb(struct kiocb *kiocb, bool compat)\n{\n\tstruct file *file = kiocb->ki_filp;\n\tssize_t ret = 0;\n\n\tswitch (kiocb->ki_opcode) {\n\tcase IOCB_CMD_PREAD:\n\t\tret = -EBADF;\n\t\tif (unlikely(!(file->f_mode & FMODE_READ)))\n\t\t\tbreak;\n\t\tret = -EFAULT;\n\t\tif (unlikely(!access_ok(VERIFY_WRITE, kiocb->ki_buf,\n\t\t\tkiocb->ki_left)))\n\t\t\tbreak;\n\t\tret = security_file_permission(file, MAY_READ);\n\t\tif (unlikely(ret))\n\t\t\tbreak;\n\t\tret = aio_setup_single_vector(kiocb);\n\t\tif (ret)\n\t\t\tbreak;\n\t\tret = -EINVAL;\n\t\tif (file->f_op->aio_read)\n\t\t\tkiocb->ki_retry = aio_rw_vect_retry;\n\t\tbreak;\n\tcase IOCB_CMD_PWRITE:\n\t\tret = -EBADF;\n\t\tif (unlikely(!(file->f_mode & FMODE_WRITE)))\n\t\t\tbreak;\n\t\tret = -EFAULT;\n\t\tif (unlikely(!access_ok(VERIFY_READ, kiocb->ki_buf,\n\t\t\tkiocb->ki_left)))\n\t\t\tbreak;\n\t\tret = security_file_permission(file, MAY_WRITE);\n\t\tif (unlikely(ret))\n\t\t\tbreak;\n\t\tret = aio_setup_single_vector(kiocb);\n\t\tif (ret)\n\t\t\tbreak;\n\t\tret = -EINVAL;\n\t\tif (file->f_op->aio_write)\n\t\t\tkiocb->ki_retry = aio_rw_vect_retry;\n\t\tbreak;\n\tcase IOCB_CMD_PREADV:\n\t\tret = -EBADF;\n\t\tif (unlikely(!(file->f_mode & FMODE_READ)))\n\t\t\tbreak;\n\t\tret = security_file_permission(file, MAY_READ);\n\t\tif (unlikely(ret))\n\t\t\tbreak;\n\t\tret = aio_setup_vectored_rw(READ, kiocb, compat);\n\t\tif (ret)\n\t\t\tbreak;\n\t\tret = -EINVAL;\n\t\tif (file->f_op->aio_read)\n\t\t\tkiocb->ki_retry = aio_rw_vect_retry;\n\t\tbreak;\n\tcase IOCB_CMD_PWRITEV:\n\t\tret = -EBADF;\n\t\tif (unlikely(!(file->f_mode & FMODE_WRITE)))\n\t\t\tbreak;\n\t\tret = security_file_permission(file, MAY_WRITE);\n\t\tif (unlikely(ret))\n\t\t\tbreak;\n\t\tret = aio_setup_vectored_rw(WRITE, kiocb, compat);\n\t\tif (ret)\n\t\t\tbreak;\n\t\tret = -EINVAL;\n\t\tif (file->f_op->aio_write)\n\t\t\tkiocb->ki_retry = aio_rw_vect_retry;\n\t\tbreak;\n\tcase IOCB_CMD_FDSYNC:\n\t\tret = -EINVAL;\n\t\tif (file->f_op->aio_fsync)\n\t\t\tkiocb->ki_retry = aio_fdsync;\n\t\tbreak;\n\tcase IOCB_CMD_FSYNC:\n\t\tret = -EINVAL;\n\t\tif (file->f_op->aio_fsync)\n\t\t\tkiocb->ki_retry = aio_fsync;\n\t\tbreak;\n\tdefault:\n\t\tdprintk(\"EINVAL: io_submit: no operation provided\\n\");\n\t\tret = -EINVAL;\n\t}\n\n\tif (!kiocb->ki_retry)\n\t\treturn ret;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'vfs: make AIO use the proper rw_verify_area() area helpers\n\nWe had for some reason overlooked the AIO interface, and it didn't use\nthe proper rw_verify_area() helper function that checks (for example)\nmandatory locking on the file, and that the size of the access doesn't\ncause us to overflow the provided offset limits etc.\n\nInstead, AIO did just the security_file_permission() thing (that\nrw_verify_area() also does) directly.\n\nThis fixes it to do all the proper helper functions, which not only\nmeans that now mandatory file locking works with AIO too, we can\nactually remove lines of code.\n\nReported-by: Manish Honap \nCc: stable@vger.kernel.org\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: SQLWCHAR* _single_string_alloc_and_expand( LPCSTR in )\n{\n SQLWCHAR *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( sizeof( SQLWCHAR ) * ( len + 1 ));\n\n len = 0;\n while ( in[ len ] != 0 )\n {\n chr[ len ] = 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: 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\t\t\tstruct rt6_info *rt)\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 err;\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->protocol = htons(ETH_P_IPV6);\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, rt);\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-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: int mongo_env_write_socket( mongo *conn, const void *buf, int len ) {\n const char *cbuf = buf;\n#ifdef _WIN32\n int flags = 0;\n#else\n#ifdef __APPLE__\n int flags = 0;\n#else\n int flags = MSG_NOSIGNAL;\n#endif\n#endif\n\n while ( len ) {\n int sent = send( conn->sock, cbuf, len, flags );\n if ( sent == -1 ) {\n if (errno == EPIPE)\n conn->connected = 0;\n conn->err = MONGO_IO_ERROR;\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: static int bson_append_estart( bson *b, int type, const char *name, const int dataSize ) {\n const int len = strlen( name ) + 1;\n\n if ( b->finished ) {\n b->err |= BSON_ALREADY_FINISHED;\n return BSON_ERROR;\n }\n\n if ( bson_ensure_space( b, 1 + len + dataSize ) == BSON_ERROR ) {\n return BSON_ERROR;\n }\n\n if( bson_check_field_name( b, ( const char * )name, len - 1 ) == BSON_ERROR ) {\n bson_builder_error( b );\n return BSON_ERROR;\n }\n\n bson_append_byte( b, ( char )type );\n bson_append( b, name, len );\n return BSON_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'don't mix up int and size_t (first pass to fix that)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: MONGO_EXPORT int bson_append_code_n( bson *b, const char *name, const char *value, int len ) {\n return bson_append_string_base( b, name, value, len, BSON_CODE );\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 bson_check_field_name( bson *b, const char *string,\n const int length ) {\n\n return bson_validate_string( b, ( const unsigned char * )string, length, 1, 1, 1 );\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 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 OP_REQUIRES(\n c, params.shape().dims() >= batch_dims_,\n errors::InvalidArgument(\"params must have at least \", batch_dims_,\n \" (batch_dims) dimensions but it has shape \",\n params.shape().DebugString()));\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-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_n_print(netdissect_options *ndo, u_char tpay _U_,\n\t const struct isakmp_gen *ext, u_int item_len,\n\t const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_,\n\t uint32_t proto0 _U_, int depth _U_)\n{\n\tconst struct ikev1_pl_n *p;\n\tstruct ikev1_pl_n n;\n\tconst u_char *cp;\n\tconst u_char *ep2;\n\tuint32_t doi;\n\tuint32_t proto;\n\tstatic const char *notify_error_str[] = {\n\t\tNULL,\t\t\t\t\"INVALID-PAYLOAD-TYPE\",\n\t\t\"DOI-NOT-SUPPORTED\",\t\t\"SITUATION-NOT-SUPPORTED\",\n\t\t\"INVALID-COOKIE\",\t\t\"INVALID-MAJOR-VERSION\",\n\t\t\"INVALID-MINOR-VERSION\",\t\"INVALID-EXCHANGE-TYPE\",\n\t\t\"INVALID-FLAGS\",\t\t\"INVALID-MESSAGE-ID\",\n\t\t\"INVALID-PROTOCOL-ID\",\t\t\"INVALID-SPI\",\n\t\t\"INVALID-TRANSFORM-ID\",\t\t\"ATTRIBUTES-NOT-SUPPORTED\",\n\t\t\"NO-PROPOSAL-CHOSEN\",\t\t\"BAD-PROPOSAL-SYNTAX\",\n\t\t\"PAYLOAD-MALFORMED\",\t\t\"INVALID-KEY-INFORMATION\",\n\t\t\"INVALID-ID-INFORMATION\",\t\"INVALID-CERT-ENCODING\",\n\t\t\"INVALID-CERTIFICATE\",\t\t\"CERT-TYPE-UNSUPPORTED\",\n\t\t\"INVALID-CERT-AUTHORITY\",\t\"INVALID-HASH-INFORMATION\",\n\t\t\"AUTHENTICATION-FAILED\",\t\"INVALID-SIGNATURE\",\n\t\t\"ADDRESS-NOTIFICATION\",\t\t\"NOTIFY-SA-LIFETIME\",\n\t\t\"CERTIFICATE-UNAVAILABLE\",\t\"UNSUPPORTED-EXCHANGE-TYPE\",\n\t\t\"UNEQUAL-PAYLOAD-LENGTHS\",\n\t};\n\tstatic const char *ipsec_notify_error_str[] = {\n\t\t\"RESERVED\",\n\t};\n\tstatic const char *notify_status_str[] = {\n\t\t\"CONNECTED\",\n\t};\n\tstatic const char *ipsec_notify_status_str[] = {\n\t\t\"RESPONDER-LIFETIME\",\t\t\"REPLAY-STATUS\",\n\t\t\"INITIAL-CONTACT\",\n\t};\n/* NOTE: these macro must be called with x in proper range */\n\n/* 0 - 8191 */\n#define NOTIFY_ERROR_STR(x) \\\n\tSTR_OR_ID((x), notify_error_str)\n\n/* 8192 - 16383 */\n#define IPSEC_NOTIFY_ERROR_STR(x) \\\n\tSTR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str)\n\n/* 16384 - 24575 */\n#define NOTIFY_STATUS_STR(x) \\\n\tSTR_OR_ID((u_int)((x) - 16384), notify_status_str)\n\n/* 24576 - 32767 */\n#define IPSEC_NOTIFY_STATUS_STR(x) \\\n\tSTR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str)\n\n\tND_PRINT((ndo,\"%s:\", NPSTR(ISAKMP_NPTYPE_N)));\n\n\tp = (const struct ikev1_pl_n *)ext;\n\tND_TCHECK(*p);\n\tUNALIGNED_MEMCPY(&n, ext, sizeof(n));\n\tdoi = ntohl(n.doi);\n\tproto = n.prot_id;\n\tif (doi != 1) {\n\t\tND_PRINT((ndo,\" doi=%d\", doi));\n\t\tND_PRINT((ndo,\" proto=%d\", proto));\n\t\tif (ntohs(n.type) < 8192)\n\t\t\tND_PRINT((ndo,\" type=%s\", NOTIFY_ERROR_STR(ntohs(n.type))));\n\t\telse if (ntohs(n.type) < 16384)\n\t\t\tND_PRINT((ndo,\" type=%s\", numstr(ntohs(n.type))));\n\t\telse if (ntohs(n.type) < 24576)\n\t\t\tND_PRINT((ndo,\" type=%s\", NOTIFY_STATUS_STR(ntohs(n.type))));\n\t\telse\n\t\t\tND_PRINT((ndo,\" type=%s\", numstr(ntohs(n.type))));\n\t\tif (n.spi_size) {\n\t\t\tND_PRINT((ndo,\" spi=\"));\n\t\t\tif (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))\n\t\t\t\tgoto trunc;\n\t\t}\n\t\treturn (const u_char *)(p + 1) + n.spi_size;\n\t}\n\n\tND_PRINT((ndo,\" doi=ipsec\"));\n\tND_PRINT((ndo,\" proto=%s\", PROTOIDSTR(proto)));\n\tif (ntohs(n.type) < 8192)\n\t\tND_PRINT((ndo,\" type=%s\", NOTIFY_ERROR_STR(ntohs(n.type))));\n\telse if (ntohs(n.type) < 16384)\n\t\tND_PRINT((ndo,\" type=%s\", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type))));\n\telse if (ntohs(n.type) < 24576)\n\t\tND_PRINT((ndo,\" type=%s\", NOTIFY_STATUS_STR(ntohs(n.type))));\n\telse if (ntohs(n.type) < 32768)\n\t\tND_PRINT((ndo,\" type=%s\", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type))));\n\telse\n\t\tND_PRINT((ndo,\" type=%s\", numstr(ntohs(n.type))));\n\tif (n.spi_size) {\n\t\tND_PRINT((ndo,\" spi=\"));\n\t\tif (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))\n\t\t\tgoto trunc;\n\t}\n\n\tcp = (const u_char *)(p + 1) + n.spi_size;\n\tep2 = (const u_char *)p + item_len;\n\n\tif (cp < ep) {\n\t\tswitch (ntohs(n.type)) {\n\t\tcase IPSECDOI_NTYPE_RESPONDER_LIFETIME:\n\t\t {\n\t\t\tconst struct attrmap *map = oakley_t_map;\n\t\t\tsize_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]);\n\t\t\tND_PRINT((ndo,\" attrs=(\"));\n\t\t\twhile (cp < ep && cp < ep2) {\n\t\t\t\tcp = ikev1_attrmap_print(ndo, cp,\n\t\t\t\t\t(ep < ep2) ? ep : ep2, map, nmap);\n\t\t\t}\n\t\t\tND_PRINT((ndo,\")\"));\n\t\t\tbreak;\n\t\t }\n\t\tcase IPSECDOI_NTYPE_REPLAY_STATUS:\n\t\t\tND_PRINT((ndo,\" status=(\"));\n\t\t\tND_PRINT((ndo,\"replay detection %sabled\",\n\t\t\t\t EXTRACT_32BITS(cp) ? \"en\" : \"dis\"));\n\t\t\tND_PRINT((ndo,\")\"));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t/*\n\t\t\t * XXX - fill in more types here; see, for example,\n\t\t\t * draft-ietf-ipsec-notifymsg-04.\n\t\t\t */\n\t\t\tif (ndo->ndo_vflag > 3) {\n\t\t\t\tND_PRINT((ndo,\" data=(\"));\n\t\t\t\tif (!rawprint(ndo, (const uint8_t *)(cp), ep - cp))\n\t\t\t\t\tgoto trunc;\n\t\t\t\tND_PRINT((ndo,\")\"));\n\t\t\t} else {\n\t\t\t\tif (!ike_show_somedata(ndo, cp, ep))\n\t\t\t\t\tgoto trunc;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn (const u_char *)ext + item_len;\ntrunc:\n\tND_PRINT((ndo,\" [|%s]\", NPSTR(ISAKMP_NPTYPE_N)));\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', '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 const Tensor& out_backprop = context->input(2);\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 // Verify that the incoming gradient tensor has the expected size\n // [ batch, out_rows, out_cols, depth ]\n const int batch = input.dim_size(0);\n const int depth = input.dim_size(3);\n OP_REQUIRES(context,\n batch == out_backprop.dim_size(0) &&\n out_rows == out_backprop.dim_size(1) &&\n out_cols == out_backprop.dim_size(2) &&\n depth == out_backprop.dim_size(3),\n errors::InvalidArgument(\"out_backprop has incompatible size.\"));\n\n // The computed filter_backprop has the same dimensions as the filter:\n // [ batch, input_rows, input_cols, depth ]\n Tensor* filter_backprop = nullptr;\n OP_REQUIRES_OK(\n context, context->allocate_output(0, filter.shape(), &filter_backprop));\n\n // If there is nothing to compute, return.\n if (filter.shape().num_elements() == 0) {\n return;\n }\n\n functor::DilationBackpropFilter()(\n context->eigen_device(), input.tensor(),\n filter.tensor(), out_backprop.tensor(), stride_rows,\n stride_cols, rate_rows, rate_cols, pad_top, pad_left,\n filter_backprop->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: static void nhmldump_send_frame(GF_NHMLDumpCtx *ctx, char *data, u32 data_size, GF_FilterPacket *pck)\n{\n\tGF_FilterPacket *dst_pck;\n\tchar nhml[1024];\n\tconst GF_PropertyValue *p;\n\tu32 size;\n\tu8 *output;\n\tGF_FilterSAPType sap = gf_filter_pck_get_sap(pck);\n\tu64 dts = gf_filter_pck_get_dts(pck);\n\tu64 cts = gf_filter_pck_get_cts(pck);\n\n\tif (dts==GF_FILTER_NO_TS) dts = cts;\n\tif (cts==GF_FILTER_NO_TS) cts = dts;\n\n\tctx->pck_num++;\n\tsprintf(nhml, \"pck_num, dts, data_size);\n\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\tif (ctx->pckp || (cts != dts) ) {\n\t\tsprintf(nhml, \"CTSOffset=\\\"%d\\\" \", (s32) ((s64)cts - (s64)dts));\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t}\n\tif (sap==GF_FILTER_SAP_1) {\n\t\tsprintf(nhml, \"isRAP=\\\"yes\\\" \");\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t} else if (sap) {\n\t\tsprintf(nhml, \"SAPType=\\\"%d\\\" \", sap);\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t} else if (ctx->pckp) {\n\t\tsprintf(nhml, \"isRAP=\\\"no\\\" \");\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\tif ((sap==GF_FILTER_SAP_4) || (sap==GF_FILTER_SAP_4_PROL)) {\n\t\t\ts32 roll = gf_filter_pck_get_roll_info(pck);\n\t\t\tsprintf(nhml, \"SAPType=\\\"4\\\" %s=\\\"%d\\\" \", (sap==GF_FILTER_SAP_4_PROL) ? \"prol\" : \"roll\", roll);\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\t}\n\n\tif (ctx->pckp) {\n\t\tu64 bo;\n\t\tu32 duration, idx;\n\t\tsprintf(nhml, \"mediaOffset=\\\"\"LLU\"\\\" \", ctx->mdia_pos);\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\t\tbo = gf_filter_pck_get_byte_offset(pck);\n\t\tif (bo!=GF_FILTER_NO_BO) {\n\t\t\tsprintf(nhml, \"sourceByteOffset=\\\"\"LLU\"\\\" \", bo);\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\t\tduration = gf_filter_pck_get_duration(pck);\n\t\tif (duration) {\n\t\t\tsprintf(nhml, \"duration=\\\"%d\\\" \", duration);\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\t\tidx = gf_filter_pck_get_carousel_version(pck);\n\t\tif (idx) {\n\t\t\tsprintf(nhml, \"carouselVersion=\\\"%d\\\" \", idx);\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\t\tidx = 0;\n\t\twhile (1) {\n\t\t\tu32 prop_4cc;\n\t\t\tconst char *prop_name;\n\t\t\tp = gf_filter_pck_enum_properties(pck, &idx, &prop_4cc, &prop_name);\n\t\t\tif (!p) break;\n\t\t\tif (prop_4cc == GF_PROP_PCK_SUBS) continue;\n\t\t\tnhmldump_pck_property(ctx, prop_4cc, prop_name, p);\n\t\t}\n\t}\n\n\tif (ctx->chksum) {\n\t\tif (ctx->chksum==1) {\n\t\t\tu32 crc = gf_crc_32(data, data_size);\n\t\t\tsprintf(nhml, \"crc=\\\"%08X\\\" \", crc);\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t} else {\n\t\t\tu32 j;\n\t\t\tu8 hash[GF_SHA1_DIGEST_SIZE];\n\t\t\tgf_sha1_csum(data, data_size, hash);\n\t\t\tsprintf(nhml, \"sha1=\\\"\");\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t\tfor (j=0; j<20; j++) {\n\t\t\t\tsprintf(nhml, \"%02X\", hash[j]);\n\t\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t\t}\n\t\t\tsprintf(nhml, \"\\\" \");\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\t}\n\n\tsprintf(nhml, \">\\n\");\n\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\tp = gf_filter_pck_get_property(pck, GF_PROP_PCK_SUBS);\n\tif (p) {\n\t\tu32 offset_in_sample = 0;\n\t\tBool first_subs = GF_TRUE;\n\t\tif (!ctx->bs_r) ctx->bs_r = gf_bs_new(p->value.data.ptr, p->value.data.size, GF_BITSTREAM_READ);\n\t\telse gf_bs_reassign_buffer(ctx->bs_r, p->value.data.ptr, p->value.data.size);\n\n\t\t//(data) binary blob containing N [(u32)flags(u32)size(u32)reserved(u8)priority(u8) discardable]\n\t\twhile (gf_bs_available(ctx->bs_r)) {\n\t\t\tu32 s_flags = gf_bs_read_u32(ctx->bs_r);\n\t\t\tu32 s_size = gf_bs_read_u32(ctx->bs_r);\n\t\t\tu32 s_res = gf_bs_read_u32(ctx->bs_r);\n\t\t\tu8 s_prio = gf_bs_read_u8(ctx->bs_r);\n\t\t\tu8 s_discard = gf_bs_read_u8(ctx->bs_r);\n\n\n\t\t\tif (offset_in_sample + s_size > data_size) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_MEDIA, (\"Wrong subsample info: sample size %d vs subsample offset+size %dn\", data_size, offset_in_sample + s_size));\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (ctx->is_stpp && ctx->nhmlonly) {\n\t\t\t\tif (first_subs) {\n\t\t\t\t\tsprintf(nhml, \"\\n\");\n\t\t\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\t\t\t\t\tgf_bs_write_data(ctx->bs_w, data, s_size);\n\n\t\t\t\t\tsprintf(nhml, \"\\n\");\n\t\t\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t\t\t} else {\n\t\t\t\t\tu32 d_size;\n\t\t\t\t\tif (ctx->b64_buffer_size<2*s_size) {\n\t\t\t\t\t\tctx->b64_buffer_size = 2 * s_size;\n\t\t\t\t\t\tctx->b64_buffer = gf_realloc(ctx->b64_buffer, ctx->b64_buffer_size);\n\t\t\t\t\t}\n\t\t\t\t\td_size = gf_base64_encode(data + offset_in_sample, s_size, ctx->b64_buffer, ctx->b64_buffer_size);\n\t\t\t\t\tctx->b64_buffer[d_size] = 0;\n\t\t\t\t\tsprintf(nhml, \"bs_w, nhml, (u32) strlen(nhml));\n\t\t\t\t\tgf_bs_write_data(ctx->bs_w, ctx->b64_buffer, d_size);\n\t\t\t\t\tsprintf(nhml, \"\\\">\\n\");\n\t\t\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsprintf(nhml, \"\\n\", s_size, s_flags, s_res, s_prio, s_discard);\n\t\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t\t}\n\t\t\tfirst_subs = GF_FALSE;\n\t\t}\n\t} else if (ctx->is_stpp && ctx->nhmlonly) {\n\t\tsprintf(nhml, \"bs_w, nhml, (u32) strlen(nhml));\n\t\tgf_bs_write_data(ctx->bs_w, data, data_size);\n\t\tsprintf(nhml, \"]]>\\n\");\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t}\n\tsprintf(nhml, \"\\n\");\n\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\tgf_bs_get_content_no_truncate(ctx->bs_w, &ctx->nhml_buffer, &size, &ctx->nhml_buffer_size);\n\n\tif (ctx->filep) {\n\t\tgf_fwrite(ctx->nhml_buffer, size, ctx->filep);\n\t\treturn;\n\t}\n\n\tdst_pck = gf_filter_pck_new_alloc(ctx->opid_nhml, size, &output);\n\tif (dst_pck) {\n\t\tmemcpy(output, ctx->nhml_buffer, size);\n\t\tgf_filter_pck_set_framing(dst_pck, GF_FALSE, GF_FALSE);\n\t\tgf_filter_pck_send(dst_pck);\n\t}\n\n\tctx->mdia_pos += data_size;\n\n\tif (ctx->opid_mdia) {\n\t\t//send the complete data packet\n\t\tdst_pck = gf_filter_pck_new_ref(ctx->opid_mdia, 0, data_size, pck);\n\t\tif (!dst_pck) return;\n\n\t\tgf_filter_pck_merge_properties(pck, dst_pck);\n\t\t//keep byte offset ?\n//\t\tgf_filter_pck_set_byte_offset(dst_pck, GF_FILTER_NO_BO);\n\n\t\tgf_filter_pck_set_framing(dst_pck, ctx->first, GF_FALSE);\n\t\tgf_filter_pck_send(dst_pck);\n\t}\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: void test_re()\n{\n assert_true_rule(\n \"rule test { strings: $a = /ssi/ condition: $a }\",\n \"mississippi\\tmississippi.mississippi\\nmississippi\");\n\n assert_true_rule(\n \"rule test { strings: $a = /ssi(s|p)/ condition: $a }\",\n \"mississippi\\tmississippi.mississippi\\nmississippi\");\n\n assert_true_rule(\n \"rule test { strings: $a = /ssim*/ condition: $a }\",\n \"mississippi\\tmississippi.mississippi\\nmississippi\");\n\n assert_true_rule(\n \"rule test { strings: $a = /ssa?/ condition: $a }\",\n \"mississippi\\tmississippi.mississippi\\nmississippi\");\n\n assert_true_rule(\n \"rule test { strings: $a = /Miss/ nocase condition: $a }\",\n \"mississippi\\tmississippi.mississippi\\nmississippi\");\n\n assert_true_rule(\n \"rule test { strings: $a = /(M|N)iss/ nocase condition: $a }\",\n \"mississippi\\tmississippi.mississippi\\nmississippi\");\n\n assert_true_rule(\n \"rule test { strings: $a = /[M-N]iss/ nocase condition: $a }\",\n \"mississippi\\tmississippi.mississippi\\nmississippi\");\n\n assert_true_rule(\n \"rule test { strings: $a = /(Mi|ssi)ssippi/ nocase condition: $a }\",\n \"mississippi\\tmississippi.mississippi\\nmississippi\");\n\n assert_true_rule(\n \"rule test { strings: $a = /ppi\\\\tmi/ condition: $a }\",\n \"mississippi\\tmississippi.mississippi\\nmississippi\");\n\n assert_true_rule(\n \"rule test { strings: $a = /ppi\\\\.mi/ condition: $a }\",\n \"mississippi\\tmississippi.mississippi\\nmississippi\");\n\n assert_true_rule(\n \"rule test { strings: $a = /^mississippi/ fullword condition: $a }\",\n \"mississippi\\tmississippi.mississippi\\nmississippi\");\n\n assert_true_rule(\n \"rule test { strings: $a = /mississippi.*mississippi$/s condition: $a }\",\n \"mississippi\\tmississippi.mississippi\\nmississippi\");\n\n assert_false_rule(\n \"rule test { strings: $a = /^ssi/ condition: $a }\",\n \"mississippi\");\n\n assert_false_rule(\n \"rule test { strings: $a = /ssi$/ condition: $a }\",\n \"mississippi\");\n\n assert_false_rule(\n \"rule test { strings: $a = /ssissi/ fullword condition: $a }\",\n \"mississippi\");\n\n assert_false_rule(\n \"rule test { strings: $a = /^[isp]+/ condition: $a }\",\n \"mississippi\");\n\n assert_true_rule_blob(\n \"rule test { strings: $a = /a.{1,2}b/ wide condition: !a == 6 }\",\n \"a\\0x\\0b\\0\");\n\n assert_true_rule_blob(\n \"rule test { strings: $a = /a.{1,2}b/ wide condition: !a == 8 }\",\n \"a\\0x\\0x\\0b\\0\");\n\n assert_regexp_syntax_error(\")\");\n assert_true_regexp(\"abc\", \"abc\", \"abc\");\n assert_false_regexp(\"abc\", \"xbc\");\n assert_false_regexp(\"abc\", \"axc\");\n assert_false_regexp(\"abc\", \"abx\");\n assert_true_regexp(\"abc\", \"xabcx\", \"abc\");\n assert_true_regexp(\"abc\", \"ababc\", \"abc\");\n assert_true_regexp(\"a.c\", \"abc\", \"abc\");\n assert_false_regexp(\"a.b\", \"a\\nb\");\n assert_false_regexp(\"a.*b\", \"acc\\nccb\");\n assert_false_regexp(\"a.{4,5}b\", \"acc\\nccb\");\n assert_true_regexp(\"a.b\", \"a\\rb\", \"a\\rb\");\n assert_true_regexp(\"ab*c\", \"abc\", \"abc\");\n assert_true_regexp(\"ab*c\", \"ac\", \"ac\");\n assert_true_regexp(\"ab*bc\", \"abc\", \"abc\");\n assert_true_regexp(\"ab*bc\", \"abbc\", \"abbc\");\n assert_true_regexp(\"a.*bb\", \"abbbb\", \"abbbb\");\n assert_true_regexp(\"a.*?bbb\", \"abbbbbb\", \"abbb\");\n assert_true_regexp(\"a.*c\", \"ac\", \"ac\");\n assert_true_regexp(\"a.*c\", \"axyzc\", \"axyzc\");\n assert_true_regexp(\"ab+c\", \"abbc\", \"abbc\");\n assert_false_regexp(\"ab+c\", \"ac\");\n assert_true_regexp(\"ab+\", \"abbbb\", \"abbbb\");\n assert_true_regexp(\"ab+?\", \"abbbb\", \"ab\");\n assert_false_regexp(\"ab+bc\", \"abc\");\n assert_false_regexp(\"ab+bc\", \"abq\");\n assert_true_regexp(\"a+b+c\", \"aabbabc\", \"abc\");\n assert_false_regexp(\"ab?bc\", \"abbbbc\");\n assert_true_regexp(\"ab?c\", \"abc\", \"abc\");\n assert_true_regexp(\"ab*?\", \"abbb\", \"a\");\n assert_true_regexp(\"ab?c\", \"ac\", \"ac\");\n assert_true_regexp(\"ab??\", \"ab\", \"a\");\n assert_true_regexp(\"a(b|x)c\", \"abc\", \"abc\");\n assert_true_regexp(\"a(b|x)c\", \"axc\", \"axc\");\n assert_true_regexp(\"a(b|.)c\", \"axc\", \"axc\");\n assert_true_regexp(\"a(b|x|y)c\", \"ayc\", \"ayc\");\n assert_true_regexp(\"(a+|b)*\", \"ab\", \"ab\");\n assert_true_regexp(\"a|b|c|d|e\", \"e\", \"e\");\n assert_true_regexp(\"(a|b|c|d|e)f\", \"ef\", \"ef\");\n assert_true_regexp(\".b{2}\", \"abb\", \"abb\");\n assert_true_regexp(\".b{2,3}\", \"abbb\", \"abbb\");\n assert_true_regexp(\".b{2,3}?\", \"abbb\", \"abb\");\n assert_true_regexp(\"ab{2,3}c\", \"abbbc\", \"abbbc\");\n assert_true_regexp(\"ab{2,3}?c\", \"abbbc\", \"abbbc\");\n assert_true_regexp(\".b{2,3}cccc\", \"abbbcccc\", \"abbbcccc\");\n assert_true_regexp(\".b{2,3}?cccc\", \"abbbcccc\", \"bbbcccc\");\n assert_true_regexp(\"a.b{2,3}cccc\", \"aabbbcccc\", \"aabbbcccc\");\n assert_true_regexp(\"ab{2,3}c\", \"abbbc\", \"abbbc\");\n assert_true_regexp(\"ab{2,3}?c\", \"abbbc\", \"abbbc\");\n assert_true_regexp(\"ab{0,1}?c\", \"abc\", \"abc\");\n assert_true_regexp(\"a{0,1}?bc\", \"abc\", \"abc\");\n assert_true_regexp(\"a{0,1}bc\", \"bbc\", \"bc\");\n assert_true_regexp(\"a{0,1}?bc\", \"abc\", \"bc\");\n assert_true_regexp(\"aa{0,1}?bc\", \"abc\", \"abc\");\n assert_true_regexp(\"aa{0,1}?bc\", \"abc\", \"abc\");\n assert_true_regexp(\"aa{0,1}bc\", \"abc\", \"abc\");\n assert_true_regexp(\"ab{1}c\", \"abc\", \"abc\");\n assert_true_regexp(\"ab{1,2}c\", \"abbc\", \"abbc\");\n assert_true_regexp(\"ab{1,}c\", \"abbbc\", \"abbbc\");\n assert_false_regexp(\"ab{1,}b\", \"ab\");\n assert_false_regexp(\"ab{1}c\", \"abbc\");\n assert_true_regexp(\"ab{0,}c\", \"ac\", \"ac\");\n assert_true_regexp(\"ab{1,1}c\", \"abc\", \"abc\");\n assert_true_regexp(\"ab{0,}c\", \"abbbc\", \"abbbc\");\n assert_true_regexp(\"ab{,3}c\", \"abbbc\", \"abbbc\");\n assert_false_regexp(\"ab{,2}c\", \"abbbc\");\n assert_false_regexp(\"ab{4,5}bc\", \"abbbbc\");\n assert_true_regexp(\"ab{0,1}\", \"abbbbb\", \"ab\");\n assert_true_regexp(\"ab{0,2}\", \"abbbbb\", \"abb\");\n assert_true_regexp(\"ab{0,3}\", \"abbbbb\", \"abbb\");\n assert_true_regexp(\"ab{0,4}\", \"abbbbb\", \"abbbb\");\n assert_true_regexp(\"ab{1,1}\", \"abbbbb\", \"ab\");\n assert_true_regexp(\"ab{1,2}\", \"abbbbb\", \"abb\");\n assert_true_regexp(\"ab{1,3}\", \"abbbbb\", \"abbb\");\n assert_true_regexp(\"ab{2,2}\", \"abbbbb\", \"abb\");\n assert_true_regexp(\"ab{2,3}\", \"abbbbb\", \"abbb\");\n assert_true_regexp(\"ab{1,3}?\", \"abbbbb\", \"ab\");\n assert_true_regexp(\"ab{0,1}?\", \"abbbbb\", \"a\");\n assert_true_regexp(\"ab{0,2}?\", \"abbbbb\", \"a\");\n assert_true_regexp(\"ab{0,3}?\", \"abbbbb\", \"a\");\n assert_true_regexp(\"ab{0,4}?\", \"abbbbb\", \"a\");\n assert_true_regexp(\"ab{1,1}?\", \"abbbbb\", \"ab\");\n assert_true_regexp(\"ab{1,2}?\", \"abbbbb\", \"ab\");\n assert_true_regexp(\"ab{1,3}?\", \"abbbbb\", \"ab\");\n assert_true_regexp(\"ab{2,2}?\", \"abbbbb\", \"abb\");\n assert_true_regexp(\"ab{2,3}?\", \"abbbbb\", \"abb\");\n assert_true_regexp(\".(abc){0,1}\", \"xabcabcabcabc\", \"xabc\");\n assert_true_regexp(\".(abc){0,2}\", \"xabcabcabcabc\", \"xabcabc\");\n assert_true_regexp(\"x{1,2}abcd\", \"xxxxabcd\", \"xxabcd\");\n assert_true_regexp(\"x{1,2}abcd\", \"xxxxabcd\", \"xxabcd\");\n assert_true_regexp(\"ab{.*}\", \"ab{c}\", \"ab{c}\");\n assert_true_regexp(\".(aa){1,2}\", \"aaaaaaaaaa\", \"aaaaa\");\n assert_true_regexp(\"a.(bc.){2}\", \"aabcabca\", \"aabcabca\");\n assert_true_regexp(\"(ab{1,2}c){1,3}\", \"abbcabc\", \"abbcabc\");\n assert_true_regexp(\"ab(c|cc){1,3}d\", \"abccccccd\", \"abccccccd\");\n assert_true_regexp(\"a[bx]c\", \"abc\", \"abc\");\n assert_true_regexp(\"a[bx]c\", \"axc\", \"axc\");\n assert_true_regexp(\"a[0-9]*b\", \"ab\", \"ab\");\n assert_true_regexp(\"a[0-9]*b\", \"a0123456789b\", \"a0123456789b\");\n assert_true_regexp(\"[0-9a-f]+\", \"0123456789abcdef\", \"0123456789abcdef\");\n assert_true_regexp(\"[0-9a-f]+\", \"xyz0123456789xyz\", \"0123456789\");\n assert_true_regexp(\"a[\\\\s\\\\S]b\", \"a b\", \"a b\");\n assert_true_regexp(\"a[\\\\d\\\\D]b\", \"a1b\", \"a1b\");\n assert_false_regexp(\"[x-z]+\", \"abc\");\n assert_true_regexp(\"a[-]?c\", \"ac\", \"ac\");\n assert_true_regexp(\"a[-b]\", \"a-\", \"a-\");\n assert_true_regexp(\"a[-b]\", \"ab\", \"ab\");\n assert_true_regexp(\"a[b-]\", \"a-\", \"a-\");\n assert_true_regexp(\"a[b-]\", \"ab\", \"ab\");\n assert_true_regexp(\"[a-c-e]\", \"b\", \"b\");\n assert_true_regexp(\"[a-c-e]\", \"-\", \"-\");\n assert_false_regexp(\"[a-c-e]\", \"d\");\n assert_regexp_syntax_error(\"[b-a]\");\n assert_regexp_syntax_error(\"(abc\");\n assert_regexp_syntax_error(\"abc)\");\n assert_regexp_syntax_error(\"a[]b\");\n assert_true_regexp(\"a[\\\\-b]\", \"a-\", \"a-\");\n assert_true_regexp(\"a[\\\\-b]\", \"ab\", \"ab\");\n assert_true_regexp(\"a]\", \"a]\", \"a]\");\n assert_true_regexp(\"a[]]b\", \"a]b\", \"a]b\");\n assert_true_regexp(\"a[\\\\]]b\", \"a]b\", \"a]b\");\n assert_true_regexp(\"a[^bc]d\", \"aed\", \"aed\");\n assert_false_regexp(\"a[^bc]d\", \"abd\");\n assert_true_regexp(\"a[^-b]c\", \"adc\", \"adc\");\n assert_false_regexp(\"a[^-b]c\", \"a-c\");\n assert_false_regexp(\"a[^]b]c\", \"a]c\");\n assert_true_regexp(\"a[^]b]c\", \"adc\", \"adc\");\n assert_true_regexp(\"[^ab]*\", \"cde\", \"cde\");\n assert_regexp_syntax_error(\")(\");\n assert_true_regexp(\"a\\\\sb\", \"a b\", \"a b\");\n assert_true_regexp(\"a\\\\sb\", \"a\\tb\", \"a\\tb\");\n assert_true_regexp(\"a\\\\sb\", \"a\\rb\", \"a\\rb\");\n assert_true_regexp(\"a\\\\sb\", \"a\\nb\", \"a\\nb\");\n assert_true_regexp(\"a\\\\sb\", \"a\\vb\", \"a\\vb\");\n assert_true_regexp(\"a\\\\sb\", \"a\\fb\", \"a\\fb\");\n assert_false_regexp(\"a\\\\Sb\", \"a b\");\n assert_false_regexp(\"a\\\\Sb\", \"a\\tb\");\n assert_false_regexp(\"a\\\\Sb\", \"a\\rb\");\n assert_false_regexp(\"a\\\\Sb\", \"a\\nb\");\n assert_false_regexp(\"a\\\\Sb\", \"a\\vb\");\n assert_false_regexp(\"a\\\\Sb\", \"a\\fb\");\n assert_true_regexp(\"\\\\n\\\\r\\\\t\\\\f\\\\a\", \"\\n\\r\\t\\f\\a\", \"\\n\\r\\t\\f\\a\");\n assert_true_regexp(\"[\\\\n][\\\\r][\\\\t][\\\\f][\\\\a]\", \"\\n\\r\\t\\f\\a\", \"\\n\\r\\t\\f\\a\");\n assert_true_regexp(\"\\\\x01\\\\x02\\\\x03\", \"\\x01\\x02\\x03\", \"\\x01\\x02\\x03\");\n assert_true_regexp(\"[\\\\x01-\\\\x03]+\", \"\\x01\\x02\\x03\", \"\\x01\\x02\\x03\");\n assert_false_regexp(\"[\\\\x00-\\\\x02]+\", \"\\x03\\x04\\x05\");\n assert_true_regexp(\"[\\\\x5D]\", \"]\", \"]\");\n assert_true_regexp(\"[\\\\0x5A-\\\\x5D]\", \"\\x5B\", \"\\x5B\");\n assert_true_regexp(\"[\\\\x5D-\\\\x5F]\", \"\\x5E\", \"\\x5E\");\n assert_true_regexp(\"[\\\\x5C-\\\\x5F]\", \"\\x5E\", \"\\x5E\");\n assert_true_regexp(\"[\\\\x5D-\\\\x5F]\", \"\\x5E\", \"\\x5E\");\n assert_true_regexp(\"a\\\\wc\", \"abc\", \"abc\");\n assert_true_regexp(\"a\\\\wc\", \"a_c\", \"a_c\");\n assert_true_regexp(\"a\\\\wc\", \"a0c\", \"a0c\");\n assert_false_regexp(\"a\\\\wc\", \"a*c\");\n assert_true_regexp(\"\\\\w+\", \"--ab_cd0123--\", \"ab_cd0123\");\n assert_true_regexp(\"[\\\\w]+\", \"--ab_cd0123--\", \"ab_cd0123\");\n assert_true_regexp(\"\\\\D+\", \"1234abc5678\", \"abc\");\n assert_true_regexp(\"[\\\\d]+\", \"0123456789\", \"0123456789\");\n assert_true_regexp(\"[\\\\D]+\", \"1234abc5678\", \"abc\");\n assert_true_regexp(\"[\\\\da-fA-F]+\", \"123abc\", \"123abc\");\n assert_false_regexp(\"^(ab|cd)e\", \"abcde\");\n assert_true_regexp(\"(abc|)ef\", \"abcdef\", \"ef\");\n assert_true_regexp(\"(abc|)ef\", \"abcef\", \"abcef\");\n assert_true_regexp(\"\\\\babc\", \"abc\", \"abc\");\n assert_true_regexp(\"abc\\\\b\", \"abc\", \"abc\");\n assert_false_regexp(\"\\\\babc\", \"1abc\");\n assert_false_regexp(\"abc\\\\b\", \"abc1\");\n assert_true_regexp(\"abc\\\\s\\\\b\", \"abc x\", \"abc \");\n assert_false_regexp(\"abc\\\\s\\\\b\", \"abc \");\n assert_true_regexp(\"\\\\babc\\\\b\", \" abc \", \"abc\");\n assert_true_regexp(\"\\\\b\\\\w\\\\w\\\\w\\\\b\", \" abc \", \"abc\");\n assert_true_regexp(\"\\\\w\\\\w\\\\w\\\\b\", \"abcd\", \"bcd\");\n assert_true_regexp(\"\\\\b\\\\w\\\\w\\\\w\", \"abcd\", \"abc\");\n assert_false_regexp(\"\\\\b\\\\w\\\\w\\\\w\\\\b\", \"abcd\");\n assert_false_regexp(\"\\\\Babc\", \"abc\");\n assert_false_regexp(\"abc\\\\B\", \"abc\");\n assert_true_regexp(\"\\\\Babc\", \"1abc\", \"abc\");\n assert_true_regexp(\"abc\\\\B\", \"abc1\", \"abc\");\n assert_false_regexp(\"abc\\\\s\\\\B\", \"abc x\");\n assert_true_regexp(\"abc\\\\s\\\\B\", \"abc \", \"abc \");\n assert_true_regexp(\"\\\\w\\\\w\\\\w\\\\B\", \"abcd\", \"abc\");\n assert_true_regexp(\"\\\\B\\\\w\\\\w\\\\w\", \"abcd\", \"bcd\");\n assert_false_regexp(\"\\\\B\\\\w\\\\w\\\\w\\\\B\", \"abcd\");\n\n // This is allowed in most regexp engines but in order to keep the\n // grammar free of shift/reduce conflicts I've decided not supporting\n // it. Users can use the (abc|) form instead.\n assert_regexp_syntax_error(\"(|abc)ef\");\n\n assert_true_regexp(\"((a)(b)c)(d)\", \"abcd\", \"abcd\");\n assert_true_regexp(\"(a|b)c*d\", \"abcd\", \"bcd\");\n assert_true_regexp(\"(ab|ab*)bc\", \"abc\", \"abc\");\n assert_true_regexp(\"a([bc]*)c*\", \"abc\", \"abc\");\n assert_true_regexp(\"a([bc]*)c*\", \"ac\", \"ac\");\n assert_true_regexp(\"a([bc]*)c*\", \"a\", \"a\");\n assert_true_regexp(\"a([bc]*)(c*d)\", \"abcd\", \"abcd\");\n assert_true_regexp(\"a([bc]+)(c*d)\", \"abcd\", \"abcd\");\n assert_true_regexp(\"a([bc]*)(c+d)\", \"abcd\", \"abcd\");\n assert_true_regexp(\"a[bcd]*dcdcde\", \"adcdcde\", \"adcdcde\");\n assert_false_regexp(\"a[bcd]+dcdcde\", \"adcdcde\");\n assert_true_regexp(\"\\\\((.*), (.*)\\\\)\", \"(a, b)\", \"(a, b)\");\n assert_true_regexp(\"abc|123$\", \"abcx\", \"abc\");\n assert_false_regexp(\"abc|123$\", \"123x\");\n assert_true_regexp(\"abc|^123\", \"123\", \"123\");\n assert_false_regexp(\"abc|^123\", \"x123\");\n assert_true_regexp(\"^abc$\", \"abc\", \"abc\");\n assert_false_regexp(\"^abc$\", \"abcc\");\n assert_true_regexp(\"^abc\", \"abcc\", \"abc\");\n assert_false_regexp(\"^abc$\", \"aabc\");\n assert_false_regexp(\"abc^\", \"abc\");\n assert_false_regexp(\"ab^c\", \"abc\");\n assert_false_regexp(\"a^bcdef\", \"abcdef\")\n assert_true_regexp(\"abc$\", \"aabc\", \"abc\");\n assert_false_regexp(\"$abc\", \"abc\");\n assert_true_regexp(\"(a|a$)bcd\", \"abcd\", \"abcd\");\n assert_false_regexp(\"(a$|a$)bcd\", \"abcd\");\n assert_false_regexp(\"(abc$|ab$)\", \"abcd\");\n assert_true_regexp(\"^a(bc+|b[eh])g|.h$\", \"abhg\", \"abhg\");\n assert_true_regexp(\"(bc+d$|ef*g.|h?i(j|k))\", \"effgz\", \"effgz\");\n assert_true_regexp(\"(bc+d$|ef*g.|h?i(j|k))\", \"ij\", \"ij\");\n assert_false_regexp(\"(bc+d$|ef*g.|h?i(j|k))\", \"effg\");\n assert_false_regexp(\"(bc+d$|ef*g.|h?i(j|k))\", \"bcdd\");\n assert_true_regexp(\"(bc+d$|ef*g.|h?i(j|k))\", \"reffgz\", \"effgz\");\n\n // Test case for issue #324\n assert_true_regexp(\"whatever| x. x\", \" xy x\", \" xy x\");\n\n // test case for issue #503, \\x without two following hex-digits\n assert_regexp_syntax_error(\"\\\\x0\");\n assert_regexp_syntax_error(\"\\\\x\");\n\n assert_regexp_syntax_error(\"x{0,0}\");\n assert_regexp_syntax_error(\"x{0}\");\n\n assert_regexp_syntax_error(\"\\\\xxy\");\n\n assert_error(\n \"rule test { strings: $a = /a\\\\/ condition: $a }\",\n ERROR_SYNTAX_ERROR);\n\n assert_error(\n \"rule test { strings: $a = /[a\\\\/ condition: $a }\",\n ERROR_SYNTAX_ERROR);\n\n assert_true_rule_blob(\n \"rule test { \\\n strings: $a = /MZ.{300,}t/ \\\n condition: !a == 317 }\",\n PE32_FILE);\n\n assert_true_rule_blob(\n \"rule test { \\\n strings: $a = /MZ.{300,}?t/ \\\n condition: !a == 314 }\",\n PE32_FILE);\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: static int iucv_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\t struct msghdr *msg, size_t len, int flags)\n{\n\tint noblock = flags & MSG_DONTWAIT;\n\tstruct sock *sk = sock->sk;\n\tstruct iucv_sock *iucv = iucv_sk(sk);\n\tunsigned int copied, rlen;\n\tstruct sk_buff *skb, *rskb, *cskb;\n\tint err = 0;\n\n\tif ((sk->sk_state == IUCV_DISCONN) &&\n\t skb_queue_empty(&iucv->backlog_skb_q) &&\n\t skb_queue_empty(&sk->sk_receive_queue) &&\n\t list_empty(&iucv->message_q.list))\n\t\treturn 0;\n\n\tif (flags & (MSG_OOB))\n\t\treturn -EOPNOTSUPP;\n\n\t/* receive/dequeue next skb:\n\t * the function understands MSG_PEEK and, thus, does not dequeue skb */\n\tskb = skb_recv_datagram(sk, flags, noblock, &err);\n\tif (!skb) {\n\t\tif (sk->sk_shutdown & RCV_SHUTDOWN)\n\t\t\treturn 0;\n\t\treturn err;\n\t}\n\n\trlen = skb->len;\t\t/* real length of skb */\n\tcopied = min_t(unsigned int, rlen, len);\n\tif (!rlen)\n\t\tsk->sk_shutdown = sk->sk_shutdown | RCV_SHUTDOWN;\n\n\tcskb = skb;\n\tif (skb_copy_datagram_iovec(cskb, 0, msg->msg_iov, copied)) {\n\t\tif (!(flags & MSG_PEEK))\n\t\t\tskb_queue_head(&sk->sk_receive_queue, skb);\n\t\treturn -EFAULT;\n\t}\n\n\t/* SOCK_SEQPACKET: set MSG_TRUNC if recv buf size is too small */\n\tif (sk->sk_type == SOCK_SEQPACKET) {\n\t\tif (copied < rlen)\n\t\t\tmsg->msg_flags |= MSG_TRUNC;\n\t\t/* each iucv message contains a complete record */\n\t\tmsg->msg_flags |= MSG_EOR;\n\t}\n\n\t/* create control message to store iucv msg target class:\n\t * get the trgcls from the control buffer of the skb due to\n\t * fragmentation of original iucv message. */\n\terr = put_cmsg(msg, SOL_IUCV, SCM_IUCV_TRGCLS,\n\t\t\tCB_TRGCLS_LEN, CB_TRGCLS(skb));\n\tif (err) {\n\t\tif (!(flags & MSG_PEEK))\n\t\t\tskb_queue_head(&sk->sk_receive_queue, skb);\n\t\treturn err;\n\t}\n\n\t/* Mark read part of skb as used */\n\tif (!(flags & MSG_PEEK)) {\n\n\t\t/* SOCK_STREAM: re-queue skb if it contains unreceived data */\n\t\tif (sk->sk_type == SOCK_STREAM) {\n\t\t\tskb_pull(skb, copied);\n\t\t\tif (skb->len) {\n\t\t\t\tskb_queue_head(&sk->sk_receive_queue, skb);\n\t\t\t\tgoto done;\n\t\t\t}\n\t\t}\n\n\t\tkfree_skb(skb);\n\t\tif (iucv->transport == AF_IUCV_TRANS_HIPER) {\n\t\t\tatomic_inc(&iucv->msg_recv);\n\t\t\tif (atomic_read(&iucv->msg_recv) > iucv->msglimit) {\n\t\t\t\tWARN_ON(1);\n\t\t\t\tiucv_sock_close(sk);\n\t\t\t\treturn -EFAULT;\n\t\t\t}\n\t\t}\n\n\t\t/* Queue backlog skbs */\n\t\tspin_lock_bh(&iucv->message_q.lock);\n\t\trskb = skb_dequeue(&iucv->backlog_skb_q);\n\t\twhile (rskb) {\n\t\t\tif (sock_queue_rcv_skb(sk, rskb)) {\n\t\t\t\tskb_queue_head(&iucv->backlog_skb_q,\n\t\t\t\t\t\trskb);\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\trskb = skb_dequeue(&iucv->backlog_skb_q);\n\t\t\t}\n\t\t}\n\t\tif (skb_queue_empty(&iucv->backlog_skb_q)) {\n\t\t\tif (!list_empty(&iucv->message_q.list))\n\t\t\t\tiucv_process_message_q(sk);\n\t\t\tif (atomic_read(&iucv->msg_recv) >=\n\t\t\t\t\t\t\tiucv->msglimit / 2) {\n\t\t\t\terr = iucv_send_ctrl(sk, AF_IUCV_FLAG_WIN);\n\t\t\t\tif (err) {\n\t\t\t\t\tsk->sk_state = IUCV_DISCONN;\n\t\t\t\t\tsk->sk_state_change(sk);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tspin_unlock_bh(&iucv->message_q.lock);\n\t}\n\ndone:\n\t/* SOCK_SEQPACKET: return real length if MSG_TRUNC is set */\n\tif (sk->sk_type == SOCK_SEQPACKET && (flags & MSG_TRUNC))\n\t\tcopied = rlen;\n\n\treturn copied;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'iucv: Fix missing msg_namelen update in iucv_sock_recvmsg()\n\nThe current code does not fill the msg_name member in case it is set.\nIt also does not set the msg_namelen member to 0 and therefore makes\nnet/socket.c leak the local, uninitialized sockaddr_storage variable\nto userland -- 128 bytes of kernel stack memory.\n\nFix that by simply setting msg_namelen to 0 as obviously nobody cared\nabout iucv_sock_recvmsg() not filling the msg_name in case it was set.\n\nCc: Ursula Braun \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: 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 regs[a] = mrb_hash_get(mrb, va, vb);\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 regs[a] = mrb_str_aref(mrb, va, vb, mrb_undef_value());\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 regs[a] = mrb_vm_const_get(mrb, syms[b]);\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 regs[a] = mrb_const_get(mrb, regs[a], syms[b]);\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;\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 regs[a] = mrb_hash_get(mrb, kdict, k);\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 size_t 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 regs[a] = mrb_range_new(mrb, regs[a], regs[a+1], FALSE);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_RANGE_EXC, B) {\n regs[a] = mrb_range_new(mrb, regs[a], regs[a+1], TRUE);\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-125', 'CWE-94'], 'message': 'vm.c: should check type before hash access.\n\nSince the operand of double splat (`**`) may not be a hash, simple\nassertion (previous code since d42a64e) was not enough for this 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: int hugepage_madvise(struct vm_area_struct *vma,\n\t\t unsigned long *vm_flags, int advice)\n{\n\tswitch (advice) {\n\tcase MADV_HUGEPAGE:\n\t\t/*\n\t\t * Be somewhat over-protective like KSM for now!\n\t\t */\n\t\tif (*vm_flags & (VM_HUGEPAGE |\n\t\t\t\t VM_SHARED | VM_MAYSHARE |\n\t\t\t\t VM_PFNMAP | VM_IO | VM_DONTEXPAND |\n\t\t\t\t VM_RESERVED | VM_HUGETLB | VM_INSERTPAGE |\n\t\t\t\t VM_MIXEDMAP | VM_SAO))\n\t\t\treturn -EINVAL;\n\t\t*vm_flags &= ~VM_NOHUGEPAGE;\n\t\t*vm_flags |= VM_HUGEPAGE;\n\t\t/*\n\t\t * If the vma become good for khugepaged to scan,\n\t\t * register it here without waiting a page fault that\n\t\t * may not happen any time soon.\n\t\t */\n\t\tif (unlikely(khugepaged_enter_vma_merge(vma)))\n\t\t\treturn -ENOMEM;\n\t\tbreak;\n\tcase MADV_NOHUGEPAGE:\n\t\t/*\n\t\t * Be somewhat over-protective like KSM for now!\n\t\t */\n\t\tif (*vm_flags & (VM_NOHUGEPAGE |\n\t\t\t\t VM_SHARED | VM_MAYSHARE |\n\t\t\t\t VM_PFNMAP | VM_IO | VM_DONTEXPAND |\n\t\t\t\t VM_RESERVED | VM_HUGETLB | VM_INSERTPAGE |\n\t\t\t\t VM_MIXEDMAP | VM_SAO))\n\t\t\treturn -EINVAL;\n\t\t*vm_flags &= ~VM_HUGEPAGE;\n\t\t*vm_flags |= VM_NOHUGEPAGE;\n\t\t/*\n\t\t * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning\n\t\t * this vma even if we leave the mm registered in khugepaged if\n\t\t * it got registered before VM_NOHUGEPAGE was set.\n\t\t */\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-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_close(struct session_request *sr)\n{\n int id;\n unsigned int hash;\n struct vhost_fdt_hash_table *ht = NULL;\n struct vhost_fdt_hash_chain *hc;\n\n if (config->fdt == MK_FALSE) {\n return close(sr->fd_file);\n }\n\n id = sr->vhost_fdt_id;\n hash = sr->vhost_fdt_hash;\n\n ht = mk_vhost_fdt_table_lookup(id, sr->host_conf);\n if (mk_unlikely(!ht)) {\n return close(sr->fd_file);\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 check if we should close */\n hc->readers--;\n if (hc->readers == 0) {\n hc->fd = -1;\n hc->hash = 0;\n ht->av_slots++;\n return close(sr->fd_file);\n }\n else {\n return 0;\n }\n }\n\n return close(sr->fd_file);\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: static void parse_sec_attr_44(sc_file_t *file, const u8 *buf, size_t len)\n{\n\t/* OpenSc Operation values for each command operation-type */\n\tconst int df_idx[8] = {\t /* byte 1 = OpenSC type of AC Bit0, byte 2 = OpenSC type of AC Bit1 ...*/\n\t\tSC_AC_OP_DELETE, SC_AC_OP_CREATE, SC_AC_OP_CREATE,\n\t\tSC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,\n\t\tSC_AC_OP_LOCK, SC_AC_OP_DELETE, -1};\n\tconst int ef_idx[8] = {\n\t\tSC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE,\n\t\tSC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,\n\t\t-1, SC_AC_OP_ERASE, -1};\n\tconst int efi_idx[8] = { /* internal EF used for RSA keys */\n\t\tSC_AC_OP_READ, SC_AC_OP_ERASE, SC_AC_OP_UPDATE,\n\t\tSC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,\n\t\t-1, SC_AC_OP_ERASE, -1};\n\n\tu8\t\tbValue;\n\tint\t\ti;\n\tint\t\tiKeyRef = 0;\n\tint\t\tiMethod;\n\tint\t\tiPinCount;\n\tint\t\tiOffset = 0;\n\tint\t\tiOperation;\n\tconst int*\tp_idx;\n\n\t/* Check all sub-AC definitions within the total AC */\n\twhile (len > 1) {\t\t\t\t/* minimum length = 2 */\n\t\tint\tiACLen = buf[iOffset] & 0x0F;\n\n\t\tiPinCount = -1;\t\t\t/* default no pin required */\n\t\tiMethod = SC_AC_NONE;\t\t/* default no authentication required */\n\n\t\tif (buf[iOffset] & 0X80) { /* AC in adaptive coding */\n\t\t\t/* Evaluates only the command-byte, not the optional P1/P2/Option bytes */\n\t\t\tint\tiParmLen = 1;\t\t\t/* command-byte is always present */\n\t\t\tint\tiKeyLen = 0;\t\t\t/* Encryption key is optional */\n\n\t\t\tif (buf[iOffset] & 0x20) iKeyLen++;\n\t\t\tif (buf[iOffset+1] & 0x40) iParmLen++;\n\t\t\tif (buf[iOffset+1] & 0x20) iParmLen++;\n\t\t\tif (buf[iOffset+1] & 0x10) iParmLen++;\n\t\t\tif (buf[iOffset+1] & 0x08) iParmLen++;\n\n\t\t\t/* Get KeyNumber if available */\n\t\t\tif(iKeyLen) {\n\t\t\t\tint iSC = buf[iOffset+iACLen];\n\n\t\t\t\tswitch( (iSC>>5) & 0x03 ){\n\t\t\t\tcase 0:\n\t\t\t\t\tiMethod = SC_AC_TERM;\t\t/* key authentication */\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tiMethod = SC_AC_AUT;\t\t/* key authentication */\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\tcase 3:\n\t\t\t\t\tiMethod = SC_AC_PRO;\t\t/* secure messaging */\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tiKeyRef = iSC & 0x1F;\t\t\t/* get key number */\n\t\t\t}\n\n\t\t\t/* Get PinNumber if available */\n\t\t\tif (iACLen > (1+iParmLen+iKeyLen)) { /* check via total length if pin is present */\n\t\t\t\tiKeyRef = buf[iOffset+1+1+iParmLen]; /* PTL + AM-header + parameter-bytes */\n\t\t\t\tiMethod = SC_AC_CHV;\n\t\t\t}\n\n\t\t\t/* Convert SETCOS command to OpenSC command group */\n\t\t\tswitch(buf[iOffset+2]){\n\t\t\tcase 0x2A:\t\t\t/* crypto operation */\n\t\t\t\tiOperation = SC_AC_OP_CRYPTO;\n\t\t\t\tbreak;\n\t\t\tcase 0x46:\t\t\t/* key-generation operation */\n\t\t\t\tiOperation = SC_AC_OP_UPDATE;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tiOperation = SC_AC_OP_SELECT;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tsc_file_add_acl_entry(file, iOperation, iMethod, iKeyRef);\n\t\t}\n\t\telse { /* AC in simple coding */\n\t\t\t /* Initial AC is treated as an operational AC */\n\n\t\t\t/* Get specific Cmd groups for specified file-type */\n\t\t\tswitch (file->type) {\n\t\t\tcase SC_FILE_TYPE_DF: /* DF */\n\t\t\t\tp_idx = df_idx;\n\t\t\t\tbreak;\n\t\t\tcase SC_FILE_TYPE_INTERNAL_EF: /* EF for RSA keys */\n\t\t\t\tp_idx = efi_idx;\n\t\t\t\tbreak;\n\t\t\tdefault: /* EF */\n\t\t\t\tp_idx = ef_idx;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t/* Encryption key present ? */\n\t\t\tiPinCount = iACLen - 1;\t\t\n\n\t\t\tif (buf[iOffset] & 0x20) {\n\t\t\t\tint iSC = buf[iOffset + iACLen];\n\n\t\t\t\tswitch( (iSC>>5) & 0x03 ) {\n\t\t\t\tcase 0:\n\t\t\t\t\tiMethod = SC_AC_TERM;\t\t/* key authentication */\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tiMethod = SC_AC_AUT;\t\t/* key authentication */\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\tcase 3:\n\t\t\t\t\tiMethod = SC_AC_PRO;\t\t/* secure messaging */\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tiKeyRef = iSC & 0x1F;\t\t\t/* get key number */\n\n\t\t\t\tiPinCount--;\t\t\t\t/* one byte used for keyReference */\n\t\t\t}\n\n\t\t\t/* Pin present ? */\n\t\t\tif ( iPinCount > 0 ) {\n\t\t\t\tiKeyRef = buf[iOffset + 2];\t/* pin ref */\n\t\t\t\tiMethod = SC_AC_CHV;\n\t\t\t}\n\n\t\t\t/* Add AC for each command-operationType into OpenSc structure */\n\t\t\tbValue = buf[iOffset + 1];\n\t\t\tfor (i = 0; i < 8; i++) {\n\t\t\t\tif((bValue & 1) && (p_idx[i] >= 0))\n\t\t\t\t\tsc_file_add_acl_entry(file, p_idx[i], iMethod, iKeyRef);\n\t\t\t\tbValue >>= 1;\n\t\t\t}\n\t\t}\n\t\t/* Current field treated, get next AC sub-field */\n\t\tiOffset += iACLen +1;\t\t/* AC + PTL-byte */\n\t\tlen -= iACLen +1;\n\t}\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: int sc_asn1_read_tag(const u8 ** buf, size_t buflen, unsigned int *cla_out,\n\t\t unsigned int *tag_out, size_t *taglen)\n{\n\tconst u8 *p = *buf;\n\tsize_t left = buflen, len;\n\tunsigned int cla, tag, i;\n\n\tif (left < 2)\n\t\treturn SC_ERROR_INVALID_ASN1_OBJECT;\n\t*buf = NULL;\n\tif (*p == 0xff || *p == 0) {\n\t\t/* end of data reached */\n\t\t*taglen = 0;\n\t\t*tag_out = SC_ASN1_TAG_EOC;\n\t\treturn SC_SUCCESS;\n\t}\n\t/* parse tag byte(s)\n\t * Resulted tag is presented by integer that has not to be\n\t * confused with the 'tag number' part of ASN.1 tag.\n\t */\n\tcla = (*p & SC_ASN1_TAG_CLASS) | (*p & SC_ASN1_TAG_CONSTRUCTED);\n\ttag = *p & SC_ASN1_TAG_PRIMITIVE;\n\tp++;\n\tleft--;\n\tif (tag == SC_ASN1_TAG_PRIMITIVE) {\n\t\t/* high tag number */\n\t\tsize_t n = SC_ASN1_TAGNUM_SIZE - 1;\n\t\t/* search the last tag octet */\n\t\twhile (left-- != 0 && n != 0) {\n\t\t\ttag <<= 8;\n\t\t\ttag |= *p;\n\t\t\tif ((*p++ & 0x80) == 0)\n\t\t\t\tbreak;\n\t\t\tn--;\n\t\t}\n\t\tif (left == 0 || n == 0)\n\t\t\t/* either an invalid tag or it doesn't fit in\n\t\t\t * unsigned int */\n\t\t\treturn SC_ERROR_INVALID_ASN1_OBJECT;\n\t}\n\n\t/* parse length byte(s) */\n\tlen = *p & 0x7f;\n\tif (*p++ & 0x80) {\n\t\tunsigned int a = 0;\n\t\tif (len > 4 || len > left)\n\t\t\treturn SC_ERROR_INVALID_ASN1_OBJECT;\n\t\tleft -= len;\n\t\tfor (i = 0; i < len; i++) {\n\t\t\ta <<= 8;\n\t\t\ta |= *p;\n\t\t\tp++;\n\t\t}\n\t\tlen = a;\n\t}\n\n\t*cla_out = cla;\n\t*tag_out = tag;\n\t*taglen = len;\n\t*buf = p;\n\n\tif (len > left)\n\t\treturn SC_ERROR_ASN1_END_OF_CONTENTS;\n\n\treturn SC_SUCCESS;\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 ModuleSQL::init()\n{\n\tDispatcher = new DispatcherThread(this);\n\tServerInstance->Threads.Start(Dispatcher);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Initialise and deallocate the MySQL library correctly.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: mrb_vm_exec(mrb_state *mrb, const struct RProc *proc, const mrb_code *pc)\n{\n /* mrb_assert(MRB_PROC_CFUNC_P(proc)) */\n const mrb_irep *irep = proc->body.irep;\n const mrb_pool_value *pool = irep->pool;\n const mrb_sym *syms = irep->syms;\n mrb_code insn;\n int ai = mrb_gc_arena_save(mrb);\n struct mrb_jmpbuf *prev_jmp = mrb->jmp;\n struct mrb_jmpbuf c_jmp;\n uint32_t a;\n uint16_t b;\n uint16_t c;\n mrb_sym mid;\n const struct mrb_irep_catch_handler *ch;\n\n#ifdef DIRECT_THREADED\n static const void * const optable[] = {\n#define OPCODE(x,_) &&L_OP_ ## x,\n#include \"mruby/ops.h\"\n#undef OPCODE\n };\n#endif\n\n mrb_bool exc_catched = FALSE;\nRETRY_TRY_BLOCK:\n\n MRB_TRY(&c_jmp) {\n\n if (exc_catched) {\n exc_catched = FALSE;\n mrb_gc_arena_restore(mrb, ai);\n if (mrb->exc && mrb->exc->tt == MRB_TT_BREAK)\n goto L_BREAK;\n goto L_RAISE;\n }\n mrb->jmp = &c_jmp;\n mrb_vm_ci_proc_set(mrb->c->ci, proc);\n\n#define regs (mrb->c->ci->stack)\n INIT_DISPATCH {\n CASE(OP_NOP, Z) {\n /* do nothing */\n NEXT;\n }\n\n CASE(OP_MOVE, BB) {\n regs[a] = regs[b];\n NEXT;\n }\n\n CASE(OP_LOADL, BB) {\n switch (pool[b].tt) { /* number */\n case IREP_TT_INT32:\n regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i32);\n break;\n case IREP_TT_INT64:\n#if defined(MRB_INT64)\n regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64);\n break;\n#else\n#if defined(MRB_64BIT)\n if (INT32_MIN <= pool[b].u.i64 && pool[b].u.i64 <= INT32_MAX) {\n regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64);\n break;\n }\n#endif\n goto L_INT_OVERFLOW;\n#endif\n case IREP_TT_BIGINT:\n#ifdef MRB_USE_BIGINT\n {\n const char *s = pool[b].u.str;\n regs[a] = mrb_bint_new_str(mrb, s+2, (mrb_int)s[0], (mrb_int)s[1]);\n }\n break;\n#else\n goto L_INT_OVERFLOW;\n#endif\n#ifndef MRB_NO_FLOAT\n case IREP_TT_FLOAT:\n regs[a] = mrb_float_value(mrb, pool[b].u.f);\n break;\n#endif\n default:\n /* should not happen (tt:string) */\n regs[a] = mrb_nil_value();\n break;\n }\n NEXT;\n }\n\n CASE(OP_LOADI, BB) {\n SET_FIXNUM_VALUE(regs[a], b);\n NEXT;\n }\n\n CASE(OP_LOADINEG, BB) {\n SET_FIXNUM_VALUE(regs[a], -b);\n NEXT;\n }\n\n CASE(OP_LOADI__1,B) goto L_LOADI;\n CASE(OP_LOADI_0,B) goto L_LOADI;\n CASE(OP_LOADI_1,B) goto L_LOADI;\n CASE(OP_LOADI_2,B) goto L_LOADI;\n CASE(OP_LOADI_3,B) goto L_LOADI;\n CASE(OP_LOADI_4,B) goto L_LOADI;\n CASE(OP_LOADI_5,B) goto L_LOADI;\n CASE(OP_LOADI_6,B) goto L_LOADI;\n CASE(OP_LOADI_7, B) {\n L_LOADI:\n SET_FIXNUM_VALUE(regs[a], (mrb_int)insn - (mrb_int)OP_LOADI_0);\n NEXT;\n }\n\n CASE(OP_LOADI16, BS) {\n SET_FIXNUM_VALUE(regs[a], (mrb_int)(int16_t)b);\n NEXT;\n }\n\n CASE(OP_LOADI32, BSS) {\n SET_INT_VALUE(mrb, regs[a], (int32_t)(((uint32_t)b<<16)+c));\n NEXT;\n }\n\n CASE(OP_LOADSYM, BB) {\n SET_SYM_VALUE(regs[a], syms[b]);\n NEXT;\n }\n\n CASE(OP_LOADNIL, B) {\n SET_NIL_VALUE(regs[a]);\n NEXT;\n }\n\n CASE(OP_LOADSELF, B) {\n regs[a] = regs[0];\n NEXT;\n }\n\n CASE(OP_LOADT, B) {\n SET_TRUE_VALUE(regs[a]);\n NEXT;\n }\n\n CASE(OP_LOADF, B) {\n SET_FALSE_VALUE(regs[a]);\n NEXT;\n }\n\n CASE(OP_GETGV, BB) {\n mrb_value val = mrb_gv_get(mrb, syms[b]);\n regs[a] = val;\n NEXT;\n }\n\n CASE(OP_SETGV, BB) {\n mrb_gv_set(mrb, syms[b], regs[a]);\n NEXT;\n }\n\n CASE(OP_GETSV, BB) {\n mrb_value val = mrb_vm_special_get(mrb, syms[b]);\n regs[a] = val;\n NEXT;\n }\n\n CASE(OP_SETSV, BB) {\n mrb_vm_special_set(mrb, syms[b], regs[a]);\n NEXT;\n }\n\n CASE(OP_GETIV, BB) {\n regs[a] = mrb_iv_get(mrb, regs[0], syms[b]);\n NEXT;\n }\n\n CASE(OP_SETIV, BB) {\n mrb_iv_set(mrb, regs[0], syms[b], regs[a]);\n NEXT;\n }\n\n CASE(OP_GETCV, BB) {\n mrb_value val;\n val = mrb_vm_cv_get(mrb, syms[b]);\n regs[a] = val;\n NEXT;\n }\n\n CASE(OP_SETCV, BB) {\n mrb_vm_cv_set(mrb, syms[b], regs[a]);\n NEXT;\n }\n\n CASE(OP_GETIDX, B) {\n mrb_value va = regs[a], vb = regs[a+1];\n switch (mrb_type(va)) {\n case MRB_TT_ARRAY:\n if (!mrb_integer_p(vb)) goto getidx_fallback;\n regs[a] = mrb_ary_entry(va, mrb_integer(vb));\n break;\n case MRB_TT_HASH:\n va = mrb_hash_get(mrb, va, vb);\n regs[a] = va;\n break;\n case MRB_TT_STRING:\n switch (mrb_type(vb)) {\n case MRB_TT_INTEGER:\n case MRB_TT_STRING:\n case MRB_TT_RANGE:\n va = mrb_str_aref(mrb, va, vb, mrb_undef_value());\n regs[a] = va;\n break;\n default:\n goto getidx_fallback;\n }\n break;\n default:\n getidx_fallback:\n mid = MRB_OPSYM(aref);\n goto L_SEND_SYM;\n }\n NEXT;\n }\n\n CASE(OP_SETIDX, B) {\n c = 2;\n mid = MRB_OPSYM(aset);\n SET_NIL_VALUE(regs[a+3]);\n goto L_SENDB_SYM;\n }\n\n CASE(OP_GETCONST, BB) {\n mrb_value v = mrb_vm_const_get(mrb, syms[b]);\n regs[a] = v;\n NEXT;\n }\n\n CASE(OP_SETCONST, BB) {\n mrb_vm_const_set(mrb, syms[b], regs[a]);\n NEXT;\n }\n\n CASE(OP_GETMCNST, BB) {\n mrb_value v = mrb_const_get(mrb, regs[a], syms[b]);\n regs[a] = v;\n NEXT;\n }\n\n CASE(OP_SETMCNST, BB) {\n mrb_const_set(mrb, regs[a+1], syms[b], regs[a]);\n NEXT;\n }\n\n CASE(OP_GETUPVAR, BBB) {\n mrb_value *regs_a = regs + a;\n struct REnv *e = uvenv(mrb, c);\n\n if (e && b < MRB_ENV_LEN(e)) {\n *regs_a = e->stack[b];\n }\n else {\n *regs_a = mrb_nil_value();\n }\n NEXT;\n }\n\n CASE(OP_SETUPVAR, BBB) {\n struct REnv *e = uvenv(mrb, c);\n\n if (e) {\n mrb_value *regs_a = regs + a;\n\n if (b < MRB_ENV_LEN(e)) {\n e->stack[b] = *regs_a;\n mrb_write_barrier(mrb, (struct RBasic*)e);\n }\n }\n NEXT;\n }\n\n CASE(OP_JMP, S) {\n pc += (int16_t)a;\n JUMP;\n }\n CASE(OP_JMPIF, BS) {\n if (mrb_test(regs[a])) {\n pc += (int16_t)b;\n JUMP;\n }\n NEXT;\n }\n CASE(OP_JMPNOT, BS) {\n if (!mrb_test(regs[a])) {\n pc += (int16_t)b;\n JUMP;\n }\n NEXT;\n }\n CASE(OP_JMPNIL, BS) {\n if (mrb_nil_p(regs[a])) {\n pc += (int16_t)b;\n JUMP;\n }\n NEXT;\n }\n\n CASE(OP_JMPUW, S) {\n a = (uint32_t)((pc - irep->iseq) + (int16_t)a);\n CHECKPOINT_RESTORE(RBREAK_TAG_JUMP) {\n struct RBreak *brk = (struct RBreak*)mrb->exc;\n mrb_value target = mrb_break_value_get(brk);\n mrb_assert(mrb_integer_p(target));\n a = (uint32_t)mrb_integer(target);\n mrb_assert(a >= 0 && a < irep->ilen);\n }\n CHECKPOINT_MAIN(RBREAK_TAG_JUMP) {\n ch = catch_handler_find(mrb, mrb->c->ci, pc, MRB_CATCH_FILTER_ENSURE);\n if (ch) {\n /* avoiding a jump from a catch handler into the same handler */\n if (a < mrb_irep_catch_handler_unpack(ch->begin) || a >= mrb_irep_catch_handler_unpack(ch->end)) {\n THROW_TAGGED_BREAK(mrb, RBREAK_TAG_JUMP, proc, mrb_fixnum_value(a));\n }\n }\n }\n CHECKPOINT_END(RBREAK_TAG_JUMP);\n\n mrb->exc = NULL; /* clear break object */\n pc = irep->iseq + a;\n JUMP;\n }\n\n CASE(OP_EXCEPT, B) {\n mrb_value exc;\n\n if (mrb->exc == NULL) {\n exc = mrb_nil_value();\n }\n else {\n switch (mrb->exc->tt) {\n case MRB_TT_BREAK:\n case MRB_TT_EXCEPTION:\n exc = mrb_obj_value(mrb->exc);\n break;\n default:\n mrb_assert(!\"bad mrb_type\");\n exc = mrb_nil_value();\n break;\n }\n mrb->exc = NULL;\n }\n regs[a] = exc;\n NEXT;\n }\n CASE(OP_RESCUE, BB) {\n mrb_value exc = regs[a]; /* exc on stack */\n mrb_value e = regs[b];\n struct RClass *ec;\n\n switch (mrb_type(e)) {\n case MRB_TT_CLASS:\n case MRB_TT_MODULE:\n break;\n default:\n {\n mrb_value exc;\n\n exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR,\n \"class or module required for rescue clause\");\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n }\n ec = mrb_class_ptr(e);\n regs[b] = mrb_bool_value(mrb_obj_is_kind_of(mrb, exc, ec));\n NEXT;\n }\n\n CASE(OP_RAISEIF, B) {\n mrb_value exc = regs[a];\n if (mrb_break_p(exc)) {\n mrb->exc = mrb_obj_ptr(exc);\n goto L_BREAK;\n }\n mrb_exc_set(mrb, exc);\n if (mrb->exc) {\n goto L_RAISE;\n }\n NEXT;\n }\n\n CASE(OP_SSEND, BBB) {\n regs[a] = regs[0];\n insn = OP_SEND;\n }\n goto L_SENDB;\n\n CASE(OP_SSENDB, BBB) {\n regs[a] = regs[0];\n }\n goto L_SENDB;\n\n CASE(OP_SEND, BBB)\n goto L_SENDB;\n\n L_SEND_SYM:\n c = 1;\n /* push nil after arguments */\n SET_NIL_VALUE(regs[a+2]);\n goto L_SENDB_SYM;\n\n CASE(OP_SENDB, BBB)\n L_SENDB:\n mid = syms[b];\n L_SENDB_SYM:\n {\n mrb_callinfo *ci = mrb->c->ci;\n mrb_method_t m;\n struct RClass *cls;\n mrb_value recv, blk;\n\n ARGUMENT_NORMALIZE(a, &c, insn);\n\n recv = regs[a];\n cls = mrb_class(mrb, recv);\n m = mrb_method_search_vm(mrb, &cls, mid);\n if (MRB_METHOD_UNDEF_P(m)) {\n m = prepare_missing(mrb, recv, mid, &cls, a, &c, blk, 0);\n mid = MRB_SYM(method_missing);\n }\n\n /* push callinfo */\n ci = cipush(mrb, a, 0, cls, NULL, mid, c);\n\n if (MRB_METHOD_CFUNC_P(m)) {\n if (MRB_METHOD_PROC_P(m)) {\n struct RProc *p = MRB_METHOD_PROC(m);\n\n mrb_vm_ci_proc_set(ci, p);\n recv = p->body.func(mrb, recv);\n }\n else {\n if (MRB_METHOD_NOARG_P(m)) {\n check_method_noarg(mrb, ci);\n }\n recv = MRB_METHOD_FUNC(m)(mrb, recv);\n }\n mrb_gc_arena_shrink(mrb, ai);\n if (mrb->exc) goto L_RAISE;\n ci = mrb->c->ci;\n if (mrb_proc_p(blk)) {\n struct RProc *p = mrb_proc_ptr(blk);\n if (p && !MRB_PROC_STRICT_P(p) && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) {\n p->flags |= MRB_PROC_ORPHAN;\n }\n }\n if (!ci->u.target_class) { /* return from context modifying method (resume/yield) */\n if (ci->cci == CINFO_RESUMED) {\n mrb->jmp = prev_jmp;\n return recv;\n }\n else {\n mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));\n proc = ci[-1].proc;\n irep = proc->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n }\n }\n ci->stack[0] = recv;\n /* pop stackpos */\n ci = cipop(mrb);\n pc = ci->pc;\n }\n else {\n /* setup environment for calling method */\n mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m)));\n irep = proc->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs);\n pc = irep->iseq;\n }\n }\n JUMP;\n\n CASE(OP_CALL, Z) {\n mrb_callinfo *ci = mrb->c->ci;\n mrb_value recv = ci->stack[0];\n struct RProc *m = mrb_proc_ptr(recv);\n\n /* replace callinfo */\n ci->u.target_class = MRB_PROC_TARGET_CLASS(m);\n mrb_vm_ci_proc_set(ci, m);\n if (MRB_PROC_ENV_P(m)) {\n ci->mid = MRB_PROC_ENV(m)->mid;\n }\n\n /* prepare stack */\n if (MRB_PROC_CFUNC_P(m)) {\n recv = MRB_PROC_CFUNC(m)(mrb, recv);\n mrb_gc_arena_shrink(mrb, ai);\n if (mrb->exc) goto L_RAISE;\n /* pop stackpos */\n ci = cipop(mrb);\n pc = ci->pc;\n ci[1].stack[0] = recv;\n irep = mrb->c->ci->proc->body.irep;\n }\n else {\n /* setup environment for calling method */\n proc = m;\n irep = m->body.irep;\n if (!irep) {\n mrb->c->ci->stack[0] = mrb_nil_value();\n a = 0;\n c = OP_R_NORMAL;\n goto L_OP_RETURN_BODY;\n }\n mrb_int nargs = mrb_ci_bidx(ci)+1;\n if (nargs < irep->nregs) {\n mrb_stack_extend(mrb, irep->nregs);\n stack_clear(regs+nargs, irep->nregs-nargs);\n }\n if (MRB_PROC_ENV_P(m)) {\n regs[0] = MRB_PROC_ENV(m)->stack[0];\n }\n pc = irep->iseq;\n }\n pool = irep->pool;\n syms = irep->syms;\n JUMP;\n }\n\n CASE(OP_SUPER, BB) {\n mrb_method_t m;\n struct RClass *cls;\n mrb_callinfo *ci = mrb->c->ci;\n mrb_value recv, blk;\n const struct RProc *p = ci->proc;\n mrb_sym mid = ci->mid;\n struct RClass* target_class = MRB_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 = (uint8_t)len;\n\n /* clear local (but non-argument) variables */\n if (irep->nlocals-blk_pos-1 > 0) {\n stack_clear(®s[blk_pos+1], irep->nlocals-blk_pos-1);\n }\n JUMP;\n }\n\n CASE(OP_KARG, BB) {\n mrb_value k = mrb_symbol_value(syms[b]);\n mrb_int kidx = mrb_ci_kidx(mrb->c->ci);\n mrb_value kdict, v;\n\n if (kidx < 0 || !mrb_hash_p(kdict=regs[kidx]) || !mrb_hash_key_p(mrb, kdict, k)) {\n mrb_value str = mrb_format(mrb, \"missing keyword: %v\", k);\n mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str));\n goto L_RAISE;\n }\n v = mrb_hash_get(mrb, kdict, k);\n regs[a] = v;\n mrb_hash_delete_key(mrb, kdict, k);\n NEXT;\n }\n\n CASE(OP_KEY_P, BB) {\n mrb_value k = mrb_symbol_value(syms[b]);\n mrb_int kidx = mrb_ci_kidx(mrb->c->ci);\n mrb_value kdict;\n mrb_bool key_p = FALSE;\n\n if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx])) {\n key_p = mrb_hash_key_p(mrb, kdict, k);\n }\n regs[a] = mrb_bool_value(key_p);\n NEXT;\n }\n\n CASE(OP_KEYEND, Z) {\n mrb_int kidx = mrb_ci_kidx(mrb->c->ci);\n mrb_value kdict;\n\n if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx]) && !mrb_hash_empty_p(mrb, kdict)) {\n mrb_value keys = mrb_hash_keys(mrb, kdict);\n mrb_value key1 = RARRAY_PTR(keys)[0];\n mrb_value str = mrb_format(mrb, \"unknown keyword: %v\", key1);\n mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str));\n goto L_RAISE;\n }\n NEXT;\n }\n\n CASE(OP_BREAK, B) {\n c = OP_R_BREAK;\n goto L_RETURN;\n }\n CASE(OP_RETURN_BLK, B) {\n c = OP_R_RETURN;\n goto L_RETURN;\n }\n CASE(OP_RETURN, B)\n c = OP_R_NORMAL;\n L_RETURN:\n {\n mrb_callinfo *ci;\n\n ci = mrb->c->ci;\n if (ci->mid) {\n mrb_value blk = regs[mrb_ci_bidx(ci)];\n\n if (mrb_proc_p(blk)) {\n struct RProc *p = mrb_proc_ptr(blk);\n\n if (!MRB_PROC_STRICT_P(p) &&\n ci > mrb->c->cibase && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) {\n p->flags |= MRB_PROC_ORPHAN;\n }\n }\n }\n\n if (mrb->exc) {\n L_RAISE:\n ci = mrb->c->ci;\n if (ci == mrb->c->cibase) {\n ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL);\n if (ch == NULL) goto L_FTOP;\n goto L_CATCH;\n }\n while ((ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL)) == NULL) {\n ci = cipop(mrb);\n if (ci[1].cci == CINFO_SKIP && prev_jmp) {\n mrb->jmp = prev_jmp;\n MRB_THROW(prev_jmp);\n }\n pc = ci[0].pc;\n if (ci == mrb->c->cibase) {\n ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL);\n if (ch == NULL) {\n L_FTOP: /* fiber top */\n if (mrb->c == mrb->root_c) {\n mrb->c->ci->stack = mrb->c->stbase;\n goto L_STOP;\n }\n else {\n struct mrb_context *c = mrb->c;\n\n c->status = MRB_FIBER_TERMINATED;\n mrb->c = c->prev;\n c->prev = NULL;\n goto L_RAISE;\n }\n }\n break;\n }\n }\n L_CATCH:\n if (ch == NULL) goto L_STOP;\n if (FALSE) {\n L_CATCH_TAGGED_BREAK: /* from THROW_TAGGED_BREAK() or UNWIND_ENSURE() */\n ci = mrb->c->ci;\n }\n proc = ci->proc;\n irep = proc->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n mrb_stack_extend(mrb, irep->nregs);\n pc = irep->iseq + mrb_irep_catch_handler_unpack(ch->target);\n }\n else {\n mrb_int acc;\n mrb_value v;\n\n ci = mrb->c->ci;\n v = regs[a];\n mrb_gc_protect(mrb, v);\n switch (c) {\n case OP_R_RETURN:\n /* Fall through to OP_R_NORMAL otherwise */\n if (ci->cci == CINFO_NONE && MRB_PROC_ENV_P(proc) && !MRB_PROC_STRICT_P(proc)) {\n const struct RProc *dst;\n mrb_callinfo *cibase;\n cibase = mrb->c->cibase;\n dst = top_proc(mrb, proc);\n\n if (MRB_PROC_ENV_P(dst)) {\n struct REnv *e = MRB_PROC_ENV(dst);\n\n if (!MRB_ENV_ONSTACK_P(e) || (e->cxt && e->cxt != mrb->c)) {\n localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n goto L_RAISE;\n }\n }\n /* check jump destination */\n while (cibase <= ci && ci->proc != dst) {\n if (ci->cci > CINFO_NONE) { /* jump cross C boundary */\n localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n goto L_RAISE;\n }\n ci--;\n }\n if (ci <= cibase) { /* no jump destination */\n localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n goto L_RAISE;\n }\n ci = mrb->c->ci;\n while (cibase <= ci && ci->proc != dst) {\n CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_BLOCK) {\n cibase = mrb->c->cibase;\n dst = top_proc(mrb, proc);\n }\n CHECKPOINT_MAIN(RBREAK_TAG_RETURN_BLOCK) {\n UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_BLOCK, proc, v);\n }\n CHECKPOINT_END(RBREAK_TAG_RETURN_BLOCK);\n ci = cipop(mrb);\n pc = ci->pc;\n }\n proc = ci->proc;\n mrb->exc = NULL; /* clear break object */\n break;\n }\n /* fallthrough */\n case OP_R_NORMAL:\n NORMAL_RETURN:\n if (ci == mrb->c->cibase) {\n struct mrb_context *c;\n c = mrb->c;\n\n if (!c->prev) { /* toplevel return */\n regs[irep->nlocals] = v;\n goto CHECKPOINT_LABEL_MAKE(RBREAK_TAG_STOP);\n }\n if (!c->vmexec && c->prev->ci == c->prev->cibase) {\n mrb_value exc = mrb_exc_new_lit(mrb, E_FIBER_ERROR, \"double resume\");\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_TOPLEVEL) {\n c = mrb->c;\n }\n CHECKPOINT_MAIN(RBREAK_TAG_RETURN_TOPLEVEL) {\n UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_TOPLEVEL, proc, v);\n }\n CHECKPOINT_END(RBREAK_TAG_RETURN_TOPLEVEL);\n /* automatic yield at the end */\n c->status = MRB_FIBER_TERMINATED;\n mrb->c = c->prev;\n mrb->c->status = MRB_FIBER_RUNNING;\n c->prev = NULL;\n if (c->vmexec) {\n mrb_gc_arena_restore(mrb, ai);\n c->vmexec = FALSE;\n mrb->jmp = prev_jmp;\n return v;\n }\n ci = mrb->c->ci;\n }\n CHECKPOINT_RESTORE(RBREAK_TAG_RETURN) {\n /* do nothing */\n }\n CHECKPOINT_MAIN(RBREAK_TAG_RETURN) {\n UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN, proc, v);\n }\n CHECKPOINT_END(RBREAK_TAG_RETURN);\n mrb->exc = NULL; /* clear break object */\n break;\n case OP_R_BREAK:\n if (MRB_PROC_STRICT_P(proc)) goto NORMAL_RETURN;\n if (MRB_PROC_ORPHAN_P(proc)) {\n mrb_value exc;\n\n L_BREAK_ERROR:\n exc = mrb_exc_new_lit(mrb, E_LOCALJUMP_ERROR,\n \"break from proc-closure\");\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n if (!MRB_PROC_ENV_P(proc) || !MRB_ENV_ONSTACK_P(MRB_PROC_ENV(proc))) {\n goto L_BREAK_ERROR;\n }\n else {\n struct REnv *e = MRB_PROC_ENV(proc);\n\n if (e->cxt != mrb->c) {\n goto L_BREAK_ERROR;\n }\n }\n CHECKPOINT_RESTORE(RBREAK_TAG_BREAK) {\n /* do nothing */\n }\n CHECKPOINT_MAIN(RBREAK_TAG_BREAK) {\n UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK, proc, v);\n }\n CHECKPOINT_END(RBREAK_TAG_BREAK);\n /* break from fiber block */\n if (ci == mrb->c->cibase && ci->pc) {\n struct mrb_context *c = mrb->c;\n\n mrb->c = c->prev;\n c->prev = NULL;\n ci = mrb->c->ci;\n }\n if (ci->cci > CINFO_NONE) {\n ci = cipop(mrb);\n mrb->exc = (struct RObject*)break_new(mrb, RBREAK_TAG_BREAK, proc, v);\n mrb_gc_arena_restore(mrb, ai);\n mrb->c->vmexec = FALSE;\n mrb->jmp = prev_jmp;\n MRB_THROW(prev_jmp);\n }\n if (FALSE) {\n struct RBreak *brk;\n\n L_BREAK:\n brk = (struct RBreak*)mrb->exc;\n proc = mrb_break_proc_get(brk);\n v = mrb_break_value_get(brk);\n ci = mrb->c->ci;\n\n switch (mrb_break_tag_get(brk)) {\n#define DISPATCH_CHECKPOINTS(n, i) case n: goto CHECKPOINT_LABEL_MAKE(n);\n RBREAK_TAG_FOREACH(DISPATCH_CHECKPOINTS)\n#undef DISPATCH_CHECKPOINTS\n default:\n mrb_assert(!\"wrong break tag\");\n }\n }\n while (mrb->c->cibase < ci && ci[-1].proc != proc->upper) {\n if (ci[-1].cci == CINFO_SKIP) {\n goto L_BREAK_ERROR;\n }\n CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_UPPER) {\n /* do nothing */\n }\n CHECKPOINT_MAIN(RBREAK_TAG_BREAK_UPPER) {\n UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_UPPER, proc, v);\n }\n CHECKPOINT_END(RBREAK_TAG_BREAK_UPPER);\n ci = cipop(mrb);\n pc = ci->pc;\n }\n CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_INTARGET) {\n /* do nothing */\n }\n CHECKPOINT_MAIN(RBREAK_TAG_BREAK_INTARGET) {\n UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_INTARGET, proc, v);\n }\n CHECKPOINT_END(RBREAK_TAG_BREAK_INTARGET);\n if (ci == mrb->c->cibase) {\n goto L_BREAK_ERROR;\n }\n mrb->exc = NULL; /* clear break object */\n break;\n default:\n /* cannot happen */\n break;\n }\n mrb_assert(ci == mrb->c->ci);\n mrb_assert(mrb->exc == NULL);\n\n if (mrb->c->vmexec && !mrb_vm_ci_target_class(ci)) {\n mrb_gc_arena_restore(mrb, ai);\n mrb->c->vmexec = FALSE;\n mrb->jmp = prev_jmp;\n return v;\n }\n acc = ci->cci;\n ci = cipop(mrb);\n if (acc == CINFO_SKIP || acc == CINFO_DIRECT) {\n mrb_gc_arena_restore(mrb, ai);\n mrb->jmp = prev_jmp;\n return v;\n }\n pc = ci->pc;\n DEBUG(fprintf(stderr, \"from :%s\\n\", mrb_sym_name(mrb, ci->mid)));\n proc = ci->proc;\n irep = proc->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n\n ci[1].stack[0] = v;\n mrb_gc_arena_restore(mrb, ai);\n }\n JUMP;\n }\n\n CASE(OP_BLKPUSH, BS) {\n int m1 = (b>>11)&0x3f;\n int r = (b>>10)&0x1;\n int m2 = (b>>5)&0x1f;\n int kd = (b>>4)&0x1;\n int lv = (b>>0)&0xf;\n mrb_value *stack;\n\n if (lv == 0) stack = regs + 1;\n else {\n struct REnv *e = uvenv(mrb, lv-1);\n if (!e || (!MRB_ENV_ONSTACK_P(e) && e->mid == 0) ||\n MRB_ENV_LEN(e) <= m1+r+m2+1) {\n localjump_error(mrb, LOCALJUMP_ERROR_YIELD);\n goto L_RAISE;\n }\n stack = e->stack + 1;\n }\n if (mrb_nil_p(stack[m1+r+m2+kd])) {\n localjump_error(mrb, LOCALJUMP_ERROR_YIELD);\n goto L_RAISE;\n }\n regs[a] = stack[m1+r+m2+kd];\n NEXT;\n }\n\n#if !defined(MRB_USE_BIGINT) || defined(MRB_INT32)\n L_INT_OVERFLOW:\n {\n mrb_value exc = mrb_exc_new_lit(mrb, E_RANGE_ERROR, \"integer overflow\");\n mrb_exc_set(mrb, exc);\n }\n goto L_RAISE;\n#endif\n\n#define TYPES2(a,b) ((((uint16_t)(a))<<8)|(((uint16_t)(b))&0xff))\n#define OP_MATH(op_name) \\\n /* need to check if op is overridden */ \\\n switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { \\\n OP_MATH_CASE_INTEGER(op_name); \\\n OP_MATH_CASE_FLOAT(op_name, integer, float); \\\n OP_MATH_CASE_FLOAT(op_name, float, integer); \\\n OP_MATH_CASE_FLOAT(op_name, float, float); \\\n OP_MATH_CASE_STRING_##op_name(); \\\n default: \\\n mid = MRB_OPSYM(op_name); \\\n goto L_SEND_SYM; \\\n } \\\n NEXT;\n#define OP_MATH_CASE_INTEGER(op_name) \\\n case TYPES2(MRB_TT_INTEGER, MRB_TT_INTEGER): \\\n { \\\n mrb_int x = mrb_integer(regs[a]), y = mrb_integer(regs[a+1]), z; \\\n if (mrb_int_##op_name##_overflow(x, y, &z)) { \\\n OP_MATH_OVERFLOW_INT(op_name,x,y); \\\n } \\\n else \\\n SET_INT_VALUE(mrb,regs[a], z); \\\n } \\\n break\n#ifdef MRB_NO_FLOAT\n#define OP_MATH_CASE_FLOAT(op_name, t1, t2) (void)0\n#else\n#define OP_MATH_CASE_FLOAT(op_name, t1, t2) \\\n case TYPES2(OP_MATH_TT_##t1, OP_MATH_TT_##t2): \\\n { \\\n mrb_float z = mrb_##t1(regs[a]) OP_MATH_OP_##op_name mrb_##t2(regs[a+1]); \\\n SET_FLOAT_VALUE(mrb, regs[a], z); \\\n } \\\n break\n#endif\n#ifdef MRB_USE_BIGINT\n#define OP_MATH_OVERFLOW_INT(op,x,y) regs[a] = mrb_bint_##op##_ii(mrb,x,y)\n#else\n#define OP_MATH_OVERFLOW_INT(op,x,y) goto L_INT_OVERFLOW\n#endif\n#define OP_MATH_CASE_STRING_add() \\\n case TYPES2(MRB_TT_STRING, MRB_TT_STRING): \\\n regs[a] = mrb_str_plus(mrb, regs[a], regs[a+1]); \\\n mrb_gc_arena_restore(mrb, ai); \\\n break\n#define OP_MATH_CASE_STRING_sub() (void)0\n#define OP_MATH_CASE_STRING_mul() (void)0\n#define OP_MATH_OP_add +\n#define OP_MATH_OP_sub -\n#define OP_MATH_OP_mul *\n#define OP_MATH_TT_integer MRB_TT_INTEGER\n#define OP_MATH_TT_float MRB_TT_FLOAT\n\n CASE(OP_ADD, B) {\n OP_MATH(add);\n }\n\n CASE(OP_SUB, B) {\n OP_MATH(sub);\n }\n\n CASE(OP_MUL, B) {\n OP_MATH(mul);\n }\n\n CASE(OP_DIV, B) {\n#ifndef MRB_NO_FLOAT\n mrb_float x, y, f;\n#endif\n\n /* need to check if op is overridden */\n switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\n case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\n {\n mrb_int x = mrb_integer(regs[a]);\n mrb_int y = mrb_integer(regs[a+1]);\n mrb_int div = mrb_div_int(mrb, x, y);\n SET_INT_VALUE(mrb, regs[a], div);\n }\n NEXT;\n#ifndef MRB_NO_FLOAT\n case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):\n x = (mrb_float)mrb_integer(regs[a]);\n y = mrb_float(regs[a+1]);\n break;\n case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):\n x = mrb_float(regs[a]);\n y = (mrb_float)mrb_integer(regs[a+1]);\n break;\n case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\n x = mrb_float(regs[a]);\n y = mrb_float(regs[a+1]);\n break;\n#endif\n default:\n mid = MRB_OPSYM(div);\n goto L_SEND_SYM;\n }\n\n#ifndef MRB_NO_FLOAT\n f = mrb_div_float(x, y);\n SET_FLOAT_VALUE(mrb, regs[a], f);\n#endif\n NEXT;\n }\n\n#define OP_MATHI(op_name) \\\n /* need to check if op is overridden */ \\\n switch (mrb_type(regs[a])) { \\\n OP_MATHI_CASE_INTEGER(op_name); \\\n OP_MATHI_CASE_FLOAT(op_name); \\\n default: \\\n SET_INT_VALUE(mrb,regs[a+1], b); \\\n mid = MRB_OPSYM(op_name); \\\n goto L_SEND_SYM; \\\n } \\\n NEXT;\n#define OP_MATHI_CASE_INTEGER(op_name) \\\n case MRB_TT_INTEGER: \\\n { \\\n mrb_int x = mrb_integer(regs[a]), y = (mrb_int)b, z; \\\n if (mrb_int_##op_name##_overflow(x, y, &z)) { \\\n OP_MATH_OVERFLOW_INT(op_name,x,y); \\\n } \\\n else \\\n SET_INT_VALUE(mrb,regs[a], z); \\\n } \\\n break\n#ifdef MRB_NO_FLOAT\n#define OP_MATHI_CASE_FLOAT(op_name) (void)0\n#else\n#define OP_MATHI_CASE_FLOAT(op_name) \\\n case MRB_TT_FLOAT: \\\n { \\\n mrb_float z = mrb_float(regs[a]) OP_MATH_OP_##op_name b; \\\n SET_FLOAT_VALUE(mrb, regs[a], z); \\\n } \\\n break\n#endif\n\n CASE(OP_ADDI, BB) {\n OP_MATHI(add);\n }\n\n CASE(OP_SUBI, BB) {\n OP_MATHI(sub);\n }\n\n#define OP_CMP_BODY(op,v1,v2) (v1(regs[a]) op v2(regs[a+1]))\n\n#ifdef MRB_NO_FLOAT\n#define OP_CMP(op,sym) do {\\\n int result;\\\n /* need to check if - is overridden */\\\n switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\\\n case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\\\n result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\\\n break;\\\n default:\\\n mid = MRB_OPSYM(sym);\\\n goto L_SEND_SYM;\\\n }\\\n if (result) {\\\n SET_TRUE_VALUE(regs[a]);\\\n }\\\n else {\\\n SET_FALSE_VALUE(regs[a]);\\\n }\\\n} while(0)\n#else\n#define OP_CMP(op, sym) do {\\\n int result;\\\n /* need to check if - is overridden */\\\n switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\\\n case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\\\n result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\\\n break;\\\n case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):\\\n result = OP_CMP_BODY(op,mrb_fixnum,mrb_float);\\\n break;\\\n case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):\\\n result = OP_CMP_BODY(op,mrb_float,mrb_fixnum);\\\n break;\\\n case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\\\n result = OP_CMP_BODY(op,mrb_float,mrb_float);\\\n break;\\\n default:\\\n mid = MRB_OPSYM(sym);\\\n goto L_SEND_SYM;\\\n }\\\n if (result) {\\\n SET_TRUE_VALUE(regs[a]);\\\n }\\\n else {\\\n SET_FALSE_VALUE(regs[a]);\\\n }\\\n} while(0)\n#endif\n\n CASE(OP_EQ, B) {\n if (mrb_obj_eq(mrb, regs[a], regs[a+1])) {\n SET_TRUE_VALUE(regs[a]);\n }\n else {\n OP_CMP(==,eq);\n }\n NEXT;\n }\n\n CASE(OP_LT, B) {\n OP_CMP(<,lt);\n NEXT;\n }\n\n CASE(OP_LE, B) {\n OP_CMP(<=,le);\n NEXT;\n }\n\n CASE(OP_GT, B) {\n OP_CMP(>,gt);\n NEXT;\n }\n\n CASE(OP_GE, B) {\n OP_CMP(>=,ge);\n NEXT;\n }\n\n CASE(OP_ARRAY, BB) {\n regs[a] = mrb_ary_new_from_values(mrb, b, ®s[a]);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n CASE(OP_ARRAY2, BBB) {\n regs[a] = mrb_ary_new_from_values(mrb, c, ®s[b]);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_ARYCAT, B) {\n mrb_value splat = mrb_ary_splat(mrb, regs[a+1]);\n if (mrb_nil_p(regs[a])) {\n regs[a] = splat;\n }\n else {\n mrb_assert(mrb_array_p(regs[a]));\n mrb_ary_concat(mrb, regs[a], splat);\n }\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_ARYPUSH, BB) {\n mrb_assert(mrb_array_p(regs[a]));\n for (mrb_int i=0; i pre + post) {\n v = mrb_ary_new_from_values(mrb, len - pre - post, ARY_PTR(ary)+pre);\n regs[a++] = v;\n while (post--) {\n regs[a++] = ARY_PTR(ary)[len-post-1];\n }\n }\n else {\n v = mrb_ary_new_capa(mrb, 0);\n regs[a++] = v;\n for (idx=0; idx+pre> 2;\n if (pool[b].tt & IREP_TT_SFLAG) {\n sym = mrb_intern_static(mrb, pool[b].u.str, len);\n }\n else {\n sym = mrb_intern(mrb, pool[b].u.str, len);\n }\n regs[a] = mrb_symbol_value(sym);\n NEXT;\n }\n\n CASE(OP_STRING, BB) {\n mrb_int len;\n\n mrb_assert((pool[b].tt&IREP_TT_NFLAG)==0);\n len = pool[b].tt >> 2;\n if (pool[b].tt & IREP_TT_SFLAG) {\n regs[a] = mrb_str_new_static(mrb, pool[b].u.str, len);\n }\n else {\n regs[a] = mrb_str_new(mrb, pool[b].u.str, len);\n }\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_STRCAT, B) {\n mrb_assert(mrb_string_p(regs[a]));\n mrb_str_concat(mrb, regs[a], regs[a+1]);\n NEXT;\n }\n\n CASE(OP_HASH, BB) {\n mrb_value hash = mrb_hash_new_capa(mrb, b);\n int i;\n int lim = a+b*2;\n\n for (i=a; ireps[b];\n\n if (c & OP_L_CAPTURE) {\n p = mrb_closure_new(mrb, nirep);\n }\n else {\n p = mrb_proc_new(mrb, nirep);\n p->flags |= MRB_PROC_SCOPE;\n }\n if (c & OP_L_STRICT) p->flags |= MRB_PROC_STRICT;\n regs[a] = mrb_obj_value(p);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n CASE(OP_BLOCK, BB) {\n c = OP_L_BLOCK;\n goto L_MAKE_LAMBDA;\n }\n CASE(OP_METHOD, BB) {\n c = OP_L_METHOD;\n goto L_MAKE_LAMBDA;\n }\n\n CASE(OP_RANGE_INC, B) {\n mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], FALSE);\n regs[a] = v;\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_RANGE_EXC, B) {\n mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], TRUE);\n regs[a] = v;\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_OCLASS, B) {\n regs[a] = mrb_obj_value(mrb->object_class);\n NEXT;\n }\n\n CASE(OP_CLASS, BB) {\n struct RClass *c = 0, *baseclass;\n mrb_value base, super;\n mrb_sym id = syms[b];\n\n base = regs[a];\n super = regs[a+1];\n if (mrb_nil_p(base)) {\n baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);\n if (!baseclass) baseclass = mrb->object_class;\n base = mrb_obj_value(baseclass);\n }\n c = mrb_vm_define_class(mrb, base, super, id);\n regs[a] = mrb_obj_value(c);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_MODULE, BB) {\n struct RClass *cls = 0, *baseclass;\n mrb_value base;\n mrb_sym id = syms[b];\n\n base = regs[a];\n if (mrb_nil_p(base)) {\n baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);\n if (!baseclass) baseclass = mrb->object_class;\n base = mrb_obj_value(baseclass);\n }\n cls = mrb_vm_define_module(mrb, base, id);\n regs[a] = mrb_obj_value(cls);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_EXEC, BB)\n {\n mrb_value recv = regs[a];\n struct RProc *p;\n const mrb_irep *nirep = irep->reps[b];\n\n /* prepare closure */\n p = mrb_proc_new(mrb, nirep);\n p->c = NULL;\n mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)proc);\n MRB_PROC_SET_TARGET_CLASS(p, mrb_class_ptr(recv));\n p->flags |= MRB_PROC_SCOPE;\n\n /* prepare call stack */\n cipush(mrb, a, 0, mrb_class_ptr(recv), p, 0, 0);\n\n irep = p->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n mrb_stack_extend(mrb, irep->nregs);\n stack_clear(regs+1, irep->nregs-1);\n pc = irep->iseq;\n JUMP;\n }\n\n CASE(OP_DEF, BB) {\n struct RClass *target = mrb_class_ptr(regs[a]);\n struct RProc *p = mrb_proc_ptr(regs[a+1]);\n mrb_method_t m;\n mrb_sym mid = syms[b];\n\n MRB_METHOD_FROM_PROC(m, p);\n mrb_define_method_raw(mrb, target, mid, m);\n mrb_method_added(mrb, target, mid);\n mrb_gc_arena_restore(mrb, ai);\n regs[a] = mrb_symbol_value(mid);\n NEXT;\n }\n\n CASE(OP_SCLASS, B) {\n regs[a] = mrb_singleton_class(mrb, regs[a]);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_TCLASS, B) {\n struct RClass *target = check_target_class(mrb);\n if (!target) goto L_RAISE;\n regs[a] = mrb_obj_value(target);\n NEXT;\n }\n\n CASE(OP_ALIAS, BB) {\n struct RClass *target = check_target_class(mrb);\n\n if (!target) goto L_RAISE;\n mrb_alias_method(mrb, target, syms[a], syms[b]);\n mrb_method_added(mrb, target, syms[a]);\n NEXT;\n }\n CASE(OP_UNDEF, B) {\n struct RClass *target = check_target_class(mrb);\n\n if (!target) goto L_RAISE;\n mrb_undef_method_id(mrb, target, syms[a]);\n NEXT;\n }\n\n CASE(OP_DEBUG, Z) {\n FETCH_BBB();\n#ifdef MRB_USE_DEBUG_HOOK\n mrb->debug_op_hook(mrb, irep, pc, regs);\n#else\n#ifndef MRB_NO_STDIO\n printf(\"OP_DEBUG %d %d %d\\n\", a, b, c);\n#else\n abort();\n#endif\n#endif\n NEXT;\n }\n\n CASE(OP_ERR, B) {\n size_t len = pool[a].tt >> 2;\n mrb_value exc;\n\n mrb_assert((pool[a].tt&IREP_TT_NFLAG)==0);\n exc = mrb_exc_new(mrb, E_LOCALJUMP_ERROR, pool[a].u.str, len);\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n\n CASE(OP_EXT1, Z) {\n insn = READ_B();\n switch (insn) {\n#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _1(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;\n#include \"mruby/ops.h\"\n#undef OPCODE\n }\n pc--;\n NEXT;\n }\n CASE(OP_EXT2, Z) {\n insn = READ_B();\n switch (insn) {\n#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _2(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;\n#include \"mruby/ops.h\"\n#undef OPCODE\n }\n pc--;\n NEXT;\n }\n CASE(OP_EXT3, Z) {\n uint8_t insn = READ_B();\n switch (insn) {\n#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _3(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;\n#include \"mruby/ops.h\"\n#undef OPCODE\n }\n pc--;\n NEXT;\n }\n\n CASE(OP_STOP, Z) {\n /* stop VM */\n CHECKPOINT_RESTORE(RBREAK_TAG_STOP) {\n /* do nothing */\n }\n CHECKPOINT_MAIN(RBREAK_TAG_STOP) {\n UNWIND_ENSURE(mrb, mrb->c->ci, pc, RBREAK_TAG_STOP, proc, mrb_nil_value());\n }\n CHECKPOINT_END(RBREAK_TAG_STOP);\n L_STOP:\n mrb->jmp = prev_jmp;\n if (mrb->exc) {\n mrb_assert(mrb->exc->tt == MRB_TT_EXCEPTION);\n return mrb_obj_value(mrb->exc);\n }\n return regs[irep->nlocals];\n }\n }\n END_DISPATCH;\n#undef regs\n }\n MRB_CATCH(&c_jmp) {\n mrb_callinfo *ci = mrb->c->ci;\n while (ci > mrb->c->cibase && ci->cci == CINFO_DIRECT) {\n ci = cipop(mrb);\n }\n exc_catched = TRUE;\n pc = ci->pc;\n goto RETRY_TRY_BLOCK;\n }\n MRB_END_EXC(&c_jmp);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'vm.c: check if target_class is NULL (when prepended).'" }, { "text": "[INST] Given the following code containing errors, provide Common 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 CSteamNetworkConnectionBase::ProcessPlainTextDataChunk( int usecTimeSinceLast, RecvPacketContext_t &ctx )\n{\n\t#define DECODE_ERROR( ... ) do { \\\n\t\tConnectionState_ProblemDetectedLocally( k_ESteamNetConnectionEnd_Misc_InternalError, __VA_ARGS__ ); \\\n\t\treturn false; } while(false)\n\n\t#define EXPECT_BYTES(n,pszWhatFor) \\\n\t\tdo { \\\n\t\t\tif ( pDecode + (n) > pEnd ) \\\n\t\t\t\tDECODE_ERROR( \"SNP decode overrun, %d bytes for %s\", (n), pszWhatFor ); \\\n\t\t} while (false)\n\n\t#define READ_8BITU( var, pszWhatFor ) \\\n\t\tdo { EXPECT_BYTES(1,pszWhatFor); var = *(uint8 *)pDecode; pDecode += 1; } while(false)\n\n\t#define READ_16BITU( var, pszWhatFor ) \\\n\t\tdo { EXPECT_BYTES(2,pszWhatFor); var = LittleWord(*(uint16 *)pDecode); pDecode += 2; } while(false)\n\n\t#define READ_24BITU( var, pszWhatFor ) \\\n\t\tdo { EXPECT_BYTES(3,pszWhatFor); \\\n\t\t\tvar = *(uint8 *)pDecode; pDecode += 1; \\\n\t\t\tvar |= uint32( LittleWord(*(uint16 *)pDecode) ) << 8U; pDecode += 2; \\\n\t\t} while(false)\n\n\t#define READ_32BITU( var, pszWhatFor ) \\\n\t\tdo { EXPECT_BYTES(4,pszWhatFor); var = LittleDWord(*(uint32 *)pDecode); pDecode += 4; } while(false)\n\n\t#define READ_48BITU( var, pszWhatFor ) \\\n\t\tdo { EXPECT_BYTES(6,pszWhatFor); \\\n\t\t\tvar = LittleWord( *(uint16 *)pDecode ); pDecode += 2; \\\n\t\t\tvar |= uint64( LittleDWord(*(uint32 *)pDecode) ) << 16U; pDecode += 4; \\\n\t\t} while(false)\n\n\t#define READ_64BITU( var, pszWhatFor ) \\\n\t\tdo { EXPECT_BYTES(8,pszWhatFor); var = LittleQWord(*(uint64 *)pDecode); pDecode += 8; } while(false)\n\n\t#define READ_VARINT( var, pszWhatFor ) \\\n\t\tdo { pDecode = DeserializeVarInt( pDecode, pEnd, var ); if ( !pDecode ) { DECODE_ERROR( \"SNP data chunk decode overflow, varint for %s\", pszWhatFor ); } } while(false)\n\n\t#define READ_SEGMENT_DATA_SIZE( is_reliable ) \\\n\t\tint cbSegmentSize; \\\n\t\t{ \\\n\t\t\tint sizeFlags = nFrameType & 7; \\\n\t\t\tif ( sizeFlags <= 4 ) \\\n\t\t\t{ \\\n\t\t\t\tuint8 lowerSizeBits; \\\n\t\t\t\tREAD_8BITU( lowerSizeBits, #is_reliable \" size lower bits\" ); \\\n\t\t\t\tcbSegmentSize = (sizeFlags<<8) + lowerSizeBits; \\\n\t\t\t\tif ( pDecode + cbSegmentSize > pEnd ) \\\n\t\t\t\t{ \\\n\t\t\t\t\tDECODE_ERROR( \"SNP decode overrun %d bytes for %s segment data.\", cbSegmentSize, #is_reliable ); \\\n\t\t\t\t} \\\n\t\t\t} \\\n\t\t\telse if ( sizeFlags == 7 ) \\\n\t\t\t{ \\\n\t\t\t\tcbSegmentSize = pEnd - pDecode; \\\n\t\t\t} \\\n\t\t\telse \\\n\t\t\t{ \\\n\t\t\t\tDECODE_ERROR( \"Invalid SNP frame lead byte 0x%02x. (size bits)\", nFrameType ); \\\n\t\t\t} \\\n\t\t} \\\n\t\tconst uint8 *pSegmentData = pDecode; \\\n\t\tpDecode += cbSegmentSize;\n\n\t// Make sure we have initialized the connection\n\tAssert( BStateIsActive() );\n\n\tconst SteamNetworkingMicroseconds usecNow = ctx.m_usecNow;\n\tconst int64 nPktNum = ctx.m_nPktNum;\n\tbool bInhibitMarkReceived = false;\n\n\tconst int nLogLevelPacketDecode = m_connectionConfig.m_LogLevel_PacketDecode.Get();\n\tSpewVerboseGroup( nLogLevelPacketDecode, \"[%s] decode pkt %lld\\n\", GetDescription(), (long long)nPktNum );\n\n\t// Decode frames until we get to the end of the payload\n\tconst byte *pDecode = (const byte *)ctx.m_pPlainText;\n\tconst byte *pEnd = pDecode + ctx.m_cbPlainText;\n\tint64 nCurMsgNum = 0;\n\tint64 nDecodeReliablePos = 0;\n\twhile ( pDecode < pEnd )\n\t{\n\n\t\tuint8 nFrameType = *pDecode;\n\t\t++pDecode;\n\t\tif ( ( nFrameType & 0xc0 ) == 0x00 )\n\t\t{\n\n\t\t\t//\n\t\t\t// Unreliable segment\n\t\t\t//\n\n\t\t\t// Decode message number\n\t\t\tif ( nCurMsgNum == 0 )\n\t\t\t{\n\t\t\t\t// First unreliable frame. Message number is absolute, but only bottom N bits are sent\n\t\t\t\tstatic const char szUnreliableMsgNumOffset[] = \"unreliable msgnum\";\n\t\t\t\tint64 nLowerBits, nMask;\n\t\t\t\tif ( nFrameType & 0x10 )\n\t\t\t\t{\n\t\t\t\t\tREAD_32BITU( nLowerBits, szUnreliableMsgNumOffset );\n\t\t\t\t\tnMask = 0xffffffff;\n\t\t\t\t\tnCurMsgNum = NearestWithSameLowerBits( (int32)nLowerBits, m_receiverState.m_nHighestSeenMsgNum );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tREAD_16BITU( nLowerBits, szUnreliableMsgNumOffset );\n\t\t\t\t\tnMask = 0xffff;\n\t\t\t\t\tnCurMsgNum = NearestWithSameLowerBits( (int16)nLowerBits, m_receiverState.m_nHighestSeenMsgNum );\n\t\t\t\t}\n\t\t\t\tAssert( ( nCurMsgNum & nMask ) == nLowerBits );\n\n\t\t\t\tif ( nCurMsgNum <= 0 )\n\t\t\t\t{\n\t\t\t\t\tDECODE_ERROR( \"SNP decode unreliable msgnum underflow. %llx mod %llx, highest seen %llx\",\n\t\t\t\t\t\t(unsigned long long)nLowerBits, (unsigned long long)( nMask+1 ), (unsigned long long)m_receiverState.m_nHighestSeenMsgNum );\n\t\t\t\t}\n\t\t\t\tif ( std::abs( nCurMsgNum - m_receiverState.m_nHighestSeenMsgNum ) > (nMask>>2) )\n\t\t\t\t{\n\t\t\t\t\t// We really should never get close to this boundary.\n\t\t\t\t\tSpewWarningRateLimited( usecNow, \"Sender sent abs unreliable message number using %llx mod %llx, highest seen %llx\\n\",\n\t\t\t\t\t\t(unsigned long long)nLowerBits, (unsigned long long)( nMask+1 ), (unsigned long long)m_receiverState.m_nHighestSeenMsgNum );\n\t\t\t\t}\n\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif ( nFrameType & 0x10 )\n\t\t\t\t{\n\t\t\t\t\tuint64 nMsgNumOffset;\n\t\t\t\t\tREAD_VARINT( nMsgNumOffset, \"unreliable msgnum offset\" );\n\t\t\t\t\tnCurMsgNum += nMsgNumOffset;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t++nCurMsgNum;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ( nCurMsgNum > m_receiverState.m_nHighestSeenMsgNum )\n\t\t\t\tm_receiverState.m_nHighestSeenMsgNum = nCurMsgNum;\n\n\t\t\t//\n\t\t\t// Decode segment offset in message\n\t\t\t//\n\t\t\tuint32 nOffset = 0;\n\t\t\tif ( nFrameType & 0x08 )\n\t\t\t\tREAD_VARINT( nOffset, \"unreliable data offset\" );\n\n\t\t\t//\n\t\t\t// Decode size, locate segment data\n\t\t\t//\n\t\t\tREAD_SEGMENT_DATA_SIZE( unreliable )\n\t\t\tAssert( cbSegmentSize > 0 ); // !TEST! Bogus assert, zero byte messages are OK. Remove after testing\n\n\t\t\t// Receive the segment\n\t\t\tbool bLastSegmentInMessage = ( nFrameType & 0x20 ) != 0;\n\t\t\tSNP_ReceiveUnreliableSegment( nCurMsgNum, nOffset, pSegmentData, cbSegmentSize, bLastSegmentInMessage, usecNow );\n\t\t}\n\t\telse if ( ( nFrameType & 0xe0 ) == 0x40 )\n\t\t{\n\n\t\t\t//\n\t\t\t// Reliable segment\n\t\t\t//\n\n\t\t\t// First reliable segment?\n\t\t\tif ( nDecodeReliablePos == 0 )\n\t\t\t{\n\n\t\t\t\t// Stream position is absolute. How many bits?\n\t\t\t\tstatic const char szFirstReliableStreamPos[] = \"first reliable streampos\";\n\t\t\t\tint64 nOffset, nMask;\n\t\t\t\tswitch ( nFrameType & (3<<3) )\n\t\t\t\t{\n\t\t\t\t\tcase 0<<3: READ_24BITU( nOffset, szFirstReliableStreamPos ); nMask = (1ll<<24)-1; break;\n\t\t\t\t\tcase 1<<3: READ_32BITU( nOffset, szFirstReliableStreamPos ); nMask = (1ll<<32)-1; break;\n\t\t\t\t\tcase 2<<3: READ_48BITU( nOffset, szFirstReliableStreamPos ); nMask = (1ll<<48)-1; break;\n\t\t\t\t\tdefault: DECODE_ERROR( \"Reserved reliable stream pos size\" );\n\t\t\t\t}\n\n\t\t\t\t// What do we expect to receive next?\n\t\t\t\tint64 nExpectNextStreamPos = m_receiverState.m_nReliableStreamPos + len( m_receiverState.m_bufReliableStream );\n\n\t\t\t\t// Find the stream offset closest to that\n\t\t\t\tnDecodeReliablePos = ( nExpectNextStreamPos & ~nMask ) + nOffset;\n\t\t\t\tif ( nDecodeReliablePos + (nMask>>1) < nExpectNextStreamPos )\n\t\t\t\t{\n\t\t\t\t\tnDecodeReliablePos += nMask+1;\n\t\t\t\t\tAssert( ( nDecodeReliablePos & nMask ) == nOffset );\n\t\t\t\t\tAssert( nExpectNextStreamPos < nDecodeReliablePos );\n\t\t\t\t\tAssert( nExpectNextStreamPos + (nMask>>1) >= nDecodeReliablePos );\n\t\t\t\t}\n\t\t\t\tif ( nDecodeReliablePos <= 0 )\n\t\t\t\t{\n\t\t\t\t\tDECODE_ERROR( \"SNP decode first reliable stream pos underflow. %llx mod %llx, expected next %llx\",\n\t\t\t\t\t\t(unsigned long long)nOffset, (unsigned long long)( nMask+1 ), (unsigned long long)nExpectNextStreamPos );\n\t\t\t\t}\n\t\t\t\tif ( std::abs( nDecodeReliablePos - nExpectNextStreamPos ) > (nMask>>2) )\n\t\t\t\t{\n\t\t\t\t\t// We really should never get close to this boundary.\n\t\t\t\t\tSpewWarningRateLimited( usecNow, \"Sender sent reliable stream pos using %llx mod %llx, expected next %llx\\n\",\n\t\t\t\t\t\t(unsigned long long)nOffset, (unsigned long long)( nMask+1 ), (unsigned long long)nExpectNextStreamPos );\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// Subsequent reliable message encode the position as an offset from previous.\n\t\t\t\tstatic const char szOtherReliableStreamPos[] = \"reliable streampos offset\";\n\t\t\t\tint64 nOffset;\n\t\t\t\tswitch ( nFrameType & (3<<3) )\n\t\t\t\t{\n\t\t\t\t\tcase 0<<3: nOffset = 0; break;\n\t\t\t\t\tcase 1<<3: READ_8BITU( nOffset, szOtherReliableStreamPos ); break;\n\t\t\t\t\tcase 2<<3: READ_16BITU( nOffset, szOtherReliableStreamPos ); break;\n\t\t\t\t\tdefault: READ_32BITU( nOffset, szOtherReliableStreamPos ); break;\n\t\t\t\t}\n\t\t\t\tnDecodeReliablePos += nOffset;\n\t\t\t}\n\n\t\t\t//\n\t\t\t// Decode size, locate segment data\n\t\t\t//\n\t\t\tREAD_SEGMENT_DATA_SIZE( reliable )\n\n\t\t\t// Ingest the segment.\n\t\t\tif ( !SNP_ReceiveReliableSegment( nPktNum, nDecodeReliablePos, pSegmentData, cbSegmentSize, usecNow ) )\n\t\t\t{\n\t\t\t\tif ( !BStateIsActive() )\n\t\t\t\t\treturn false; // we decided to nuke the connection - abort packet processing\n\n\t\t\t\t// We're not able to ingest this reliable segment at the moment,\n\t\t\t\t// but we didn't terminate the connection. So do not ack this packet\n\t\t\t\t// to the peer. We need them to retransmit\n\t\t\t\tbInhibitMarkReceived = true;\n\t\t\t}\n\n\t\t\t// Advance pointer for the next reliable segment, if any.\n\t\t\tnDecodeReliablePos += cbSegmentSize;\n\n\t\t\t// Decoding rules state that if we have established a message number,\n\t\t\t// (from an earlier unreliable message), then we advance it.\n\t\t\tif ( nCurMsgNum > 0 ) \n\t\t\t\t++nCurMsgNum;\n\t\t}\n\t\telse if ( ( nFrameType & 0xfc ) == 0x80 )\n\t\t{\n\t\t\t//\n\t\t\t// Stop waiting\n\t\t\t//\n\n\t\t\tint64 nOffset = 0;\n\t\t\tstatic const char szStopWaitingOffset[] = \"stop_waiting offset\";\n\t\t\tswitch ( nFrameType & 3 )\n\t\t\t{\n\t\t\t\tcase 0: READ_8BITU( nOffset, szStopWaitingOffset ); break;\n\t\t\t\tcase 1: READ_16BITU( nOffset, szStopWaitingOffset ); break;\n\t\t\t\tcase 2: READ_24BITU( nOffset, szStopWaitingOffset ); break;\n\t\t\t\tcase 3: READ_64BITU( nOffset, szStopWaitingOffset ); break;\n\t\t\t}\n\t\t\tif ( nOffset >= nPktNum )\n\t\t\t{\n\t\t\t\tDECODE_ERROR( \"stop_waiting pktNum %llu offset %llu\", nPktNum, nOffset );\n\t\t\t}\n\t\t\t++nOffset;\n\t\t\tint64 nMinPktNumToSendAcks = nPktNum-nOffset;\n\t\t\tif ( nMinPktNumToSendAcks == m_receiverState.m_nMinPktNumToSendAcks )\n\t\t\t\tcontinue;\n\t\t\tif ( nMinPktNumToSendAcks < m_receiverState.m_nMinPktNumToSendAcks )\n\t\t\t{\n\t\t\t\t// Sender must never reduce this number! Check for bugs or bogus sender\n\t\t\t\tif ( nPktNum >= m_receiverState.m_nPktNumUpdatedMinPktNumToSendAcks )\n\t\t\t\t{\n\t\t\t\t\tDECODE_ERROR( \"SNP stop waiting reduced %lld (pkt %lld) -> %lld (pkt %lld)\",\n\t\t\t\t\t\t(long long)m_receiverState.m_nMinPktNumToSendAcks,\n\t\t\t\t\t\t(long long)m_receiverState.m_nPktNumUpdatedMinPktNumToSendAcks,\n\t\t\t\t\t\t(long long)nMinPktNumToSendAcks,\n\t\t\t\t\t\t(long long)nPktNum\n\t\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tSpewDebugGroup( nLogLevelPacketDecode, \"[%s] decode pkt %lld stop waiting: %lld (was %lld)\",\n\t\t\t\tGetDescription(),\n\t\t\t\t(long long)nPktNum,\n\t\t\t\t(long long)nMinPktNumToSendAcks, (long long)m_receiverState.m_nMinPktNumToSendAcks );\n\t\t\tm_receiverState.m_nMinPktNumToSendAcks = nMinPktNumToSendAcks;\n\t\t\tm_receiverState.m_nPktNumUpdatedMinPktNumToSendAcks = nPktNum;\n\n\t\t\t// Trim from the front of the packet gap list,\n\t\t\t// we can stop reporting these losses to the sender\n\t\t\tauto h = m_receiverState.m_mapPacketGaps.begin();\n\t\t\twhile ( h->first <= m_receiverState.m_nMinPktNumToSendAcks )\n\t\t\t{\n\t\t\t\tif ( h->second.m_nEnd > m_receiverState.m_nMinPktNumToSendAcks )\n\t\t\t\t{\n\t\t\t\t\t// Ug. You're not supposed to modify the key in a map.\n\t\t\t\t\t// I suppose that's legit, since you could violate the ordering.\n\t\t\t\t\t// but in this case I know that this change is OK.\n\t\t\t\t\tconst_cast( h->first ) = m_receiverState.m_nMinPktNumToSendAcks;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t// Were we pending an ack on this?\n\t\t\t\tif ( m_receiverState.m_itPendingAck == h )\n\t\t\t\t\t++m_receiverState.m_itPendingAck;\n\n\t\t\t\t// Were we pending a nack on this?\n\t\t\t\tif ( m_receiverState.m_itPendingNack == h )\n\t\t\t\t{\n\t\t\t\t\t// I am not sure this is even possible.\n\t\t\t\t\tAssertMsg( false, \"Expiring packet gap, which had pending NACK\" );\n\n\t\t\t\t\t// But just in case, this would be the proper action\n\t\t\t\t\t++m_receiverState.m_itPendingNack;\n\t\t\t\t}\n\n\t\t\t\t// Packet loss is in the past. Forget about it and move on\n\t\t\t\th = m_receiverState.m_mapPacketGaps.erase(h);\n\t\t\t}\n\t\t}\n\t\telse if ( ( nFrameType & 0xf0 ) == 0x90 )\n\t\t{\n\n\t\t\t//\n\t\t\t// Ack\n\t\t\t//\n\n\t\t\t#if STEAMNETWORKINGSOCKETS_SNP_PARANOIA > 0\n\t\t\t\tm_senderState.DebugCheckInFlightPacketMap();\n\t\t\t\t#if STEAMNETWORKINGSOCKETS_SNP_PARANOIA == 1\n\t\t\t\tif ( ( nPktNum & 255 ) == 0 ) // only do it periodically\n\t\t\t\t#endif\n\t\t\t\t{\n\t\t\t\t\tm_senderState.DebugCheckInFlightPacketMap();\n\t\t\t\t}\n\t\t\t#endif\n\n\t\t\t// Parse latest received sequence number\n\t\t\tint64 nLatestRecvSeqNum;\n\t\t\t{\n\t\t\t\tstatic const char szAckLatestPktNum[] = \"ack latest pktnum\";\n\t\t\t\tint64 nLowerBits, nMask;\n\t\t\t\tif ( nFrameType & 0x40 )\n\t\t\t\t{\n\t\t\t\t\tREAD_32BITU( nLowerBits, szAckLatestPktNum );\n\t\t\t\t\tnMask = 0xffffffff;\n\t\t\t\t\tnLatestRecvSeqNum = NearestWithSameLowerBits( (int32)nLowerBits, m_statsEndToEnd.m_nNextSendSequenceNumber );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tREAD_16BITU( nLowerBits, szAckLatestPktNum );\n\t\t\t\t\tnMask = 0xffff;\n\t\t\t\t\tnLatestRecvSeqNum = NearestWithSameLowerBits( (int16)nLowerBits, m_statsEndToEnd.m_nNextSendSequenceNumber );\n\t\t\t\t}\n\t\t\t\tAssert( ( nLatestRecvSeqNum & nMask ) == nLowerBits );\n\n\t\t\t\t// Find the message number that is closes to \n\t\t\t\tif ( nLatestRecvSeqNum < 0 )\n\t\t\t\t{\n\t\t\t\t\tDECODE_ERROR( \"SNP decode ack latest pktnum underflow. %llx mod %llx, next send %llx\",\n\t\t\t\t\t\t(unsigned long long)nLowerBits, (unsigned long long)( nMask+1 ), (unsigned long long)m_statsEndToEnd.m_nNextSendSequenceNumber );\n\t\t\t\t}\n\t\t\t\tif ( std::abs( nLatestRecvSeqNum - m_statsEndToEnd.m_nNextSendSequenceNumber ) > (nMask>>2) )\n\t\t\t\t{\n\t\t\t\t\t// We really should never get close to this boundary.\n\t\t\t\t\tSpewWarningRateLimited( usecNow, \"Sender sent abs latest recv pkt number using %llx mod %llx, next send %llx\\n\",\n\t\t\t\t\t\t(unsigned long long)nLowerBits, (unsigned long long)( nMask+1 ), (unsigned long long)m_statsEndToEnd.m_nNextSendSequenceNumber );\n\t\t\t\t}\n\t\t\t\tif ( nLatestRecvSeqNum >= m_statsEndToEnd.m_nNextSendSequenceNumber )\n\t\t\t\t{\n\t\t\t\t\tDECODE_ERROR( \"SNP decode ack latest pktnum %lld (%llx mod %llx), but next outoing packet is %lld (%llx).\",\n\t\t\t\t\t\t(long long)nLatestRecvSeqNum, (unsigned long long)nLowerBits, (unsigned long long)( nMask+1 ),\n\t\t\t\t\t\t(long long)m_statsEndToEnd.m_nNextSendSequenceNumber, (unsigned long long)m_statsEndToEnd.m_nNextSendSequenceNumber\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tSpewDebugGroup( nLogLevelPacketDecode, \"[%s] decode pkt %lld latest recv %lld\\n\",\n\t\t\t\tGetDescription(),\n\t\t\t\t(long long)nPktNum, (long long)nLatestRecvSeqNum\n\t\t\t);\n\n\t\t\t// Locate our bookkeeping for this packet, or the latest one before it\n\t\t\t// Remember, we have a sentinel with a low, invalid packet number\n\t\t\tAssert( !m_senderState.m_mapInFlightPacketsByPktNum.empty() );\n\t\t\tauto inFlightPkt = m_senderState.m_mapInFlightPacketsByPktNum.upper_bound( nLatestRecvSeqNum );\n\t\t\t--inFlightPkt;\n\t\t\tAssert( inFlightPkt->first <= nLatestRecvSeqNum );\n\n\t\t\t// Parse out delay, and process the ping\n\t\t\t{\n\t\t\t\tuint16 nPackedDelay;\n\t\t\t\tREAD_16BITU( nPackedDelay, \"ack delay\" );\n\t\t\t\tif ( nPackedDelay != 0xffff && inFlightPkt->first == nLatestRecvSeqNum && inFlightPkt->second.m_pTransport == ctx.m_pTransport )\n\t\t\t\t{\n\t\t\t\t\tSteamNetworkingMicroseconds usecDelay = SteamNetworkingMicroseconds( nPackedDelay ) << k_nAckDelayPrecisionShift;\n\t\t\t\t\tSteamNetworkingMicroseconds usecElapsed = usecNow - inFlightPkt->second.m_usecWhenSent;\n\t\t\t\t\tAssert( usecElapsed >= 0 );\n\n\t\t\t\t\t// Account for their reported delay, and calculate ping, in MS\n\t\t\t\t\tint msPing = ( usecElapsed - usecDelay ) / 1000;\n\n\t\t\t\t\t// Does this seem bogus? (We allow a small amount of slop.)\n\t\t\t\t\t// NOTE: A malicious sender could lie about this delay, tricking us\n\t\t\t\t\t// into thinking that the real network latency is low, they are just\n\t\t\t\t\t// delaying their replies. This actually matters, since the ping time\n\t\t\t\t\t// is an input into the rate calculation. So we might need to\n\t\t\t\t\t// occasionally send pings that require an immediately reply, and\n\t\t\t\t\t// if those ping times seem way out of whack with the ones where they are\n\t\t\t\t\t// allowed to send a delay, take action against them.\n\t\t\t\t\tif ( msPing < -1 || msPing > 2000 )\n\t\t\t\t\t{\n\t\t\t\t\t\t// Either they are lying or some weird timer stuff is happening.\n\t\t\t\t\t\t// Either way, discard it.\n\n\t\t\t\t\t\tSpewMsgGroup( m_connectionConfig.m_LogLevel_AckRTT.Get(), \"[%s] decode pkt %lld latest recv %lld delay %lluusec INVALID ping %lldusec\\n\",\n\t\t\t\t\t\t\tGetDescription(),\n\t\t\t\t\t\t\t(long long)nPktNum, (long long)nLatestRecvSeqNum,\n\t\t\t\t\t\t\t(unsigned long long)usecDelay,\n\t\t\t\t\t\t\t(long long)usecElapsed\n\t\t\t\t\t\t);\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// Clamp, if we have slop\n\t\t\t\t\t\tif ( msPing < 0 )\n\t\t\t\t\t\t\tmsPing = 0;\n\t\t\t\t\t\tProcessSNPPing( msPing, ctx );\n\n\t\t\t\t\t\t// Spew\n\t\t\t\t\t\tSpewVerboseGroup( m_connectionConfig.m_LogLevel_AckRTT.Get(), \"[%s] decode pkt %lld latest recv %lld delay %.1fms elapsed %.1fms ping %dms\\n\",\n\t\t\t\t\t\t\tGetDescription(),\n\t\t\t\t\t\t\t(long long)nPktNum, (long long)nLatestRecvSeqNum,\n\t\t\t\t\t\t\t(float)(usecDelay * 1e-3 ),\n\t\t\t\t\t\t\t(float)(usecElapsed * 1e-3 ),\n\t\t\t\t\t\t\tmsPing\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Parse number of blocks\n\t\t\tint nBlocks = nFrameType&7;\n\t\t\tif ( nBlocks == 7 )\n\t\t\t\tREAD_8BITU( nBlocks, \"ack num blocks\" );\n\n\t\t\t// If they actually sent us any blocks, that means they are fragmented.\n\t\t\t// We should make sure and tell them to stop sending us these nacks\n\t\t\t// and move forward.\n\t\t\tif ( nBlocks > 0 )\n\t\t\t{\n\t\t\t\t// Decrease flush delay the more blocks they send us.\n\t\t\t\t// FIXME - This is not an optimal way to do this. Forcing us to\n\t\t\t\t// ack everything is not what we want to do. Instead, we should\n\t\t\t\t// use a separate timer for when we need to flush out a stop_waiting\n\t\t\t\t// packet!\n\t\t\t\tSteamNetworkingMicroseconds usecDelay = 250*1000 / nBlocks;\n\t\t\t\tQueueFlushAllAcks( usecNow + usecDelay );\n\t\t\t}\n\n\t\t\t// Process ack blocks, working backwards from the latest received sequence number.\n\t\t\t// Note that we have to parse all this stuff out, even if it's old news (packets older\n\t\t\t// than the stop_aiting value we sent), because we need to do that to get to the rest\n\t\t\t// of the packet.\n\t\t\tbool bAckedReliableRange = false;\n\t\t\tint64 nPktNumAckEnd = nLatestRecvSeqNum+1;\n\t\t\twhile ( nBlocks >= 0 )\n\t\t\t{\n\n\t\t\t\t// Parse out number of acks/nacks.\n\t\t\t\t// Have we parsed all the real blocks?\n\t\t\t\tint64 nPktNumAckBegin, nPktNumNackBegin;\n\t\t\t\tif ( nBlocks == 0 )\n\t\t\t\t{\n\t\t\t\t\t// Implicit block. Everything earlier between the last\n\t\t\t\t\t// NACK and the stop_waiting value is implicitly acked!\n\t\t\t\t\tif ( nPktNumAckEnd <= m_senderState.m_nMinPktWaitingOnAck )\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tnPktNumAckBegin = m_senderState.m_nMinPktWaitingOnAck;\n\t\t\t\t\tnPktNumNackBegin = nPktNumAckBegin;\n\t\t\t\t\tSpewDebugGroup( nLogLevelPacketDecode, \"[%s] decode pkt %lld ack last block ack begin %lld\\n\",\n\t\t\t\t\t\tGetDescription(),\n\t\t\t\t\t\t(long long)nPktNum, (long long)nPktNumAckBegin );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tuint8 nBlockHeader;\n\t\t\t\t\tREAD_8BITU( nBlockHeader, \"ack block header\" );\n\n\t\t\t\t\t// Ack count?\n\t\t\t\t\tint64 numAcks = ( nBlockHeader>> 4 ) & 7;\n\t\t\t\t\tif ( nBlockHeader & 0x80 )\n\t\t\t\t\t{\n\t\t\t\t\t\tuint64 nUpperBits;\n\t\t\t\t\t\tREAD_VARINT( nUpperBits, \"ack count upper bits\" );\n\t\t\t\t\t\tif ( nUpperBits > 100000 )\n\t\t\t\t\t\t\tDECODE_ERROR( \"Ack count of %llu<<3 is crazy\", (unsigned long long)nUpperBits );\n\t\t\t\t\t\tnumAcks |= nUpperBits<<3;\n\t\t\t\t\t}\n\t\t\t\t\tnPktNumAckBegin = nPktNumAckEnd - numAcks;\n\t\t\t\t\tif ( nPktNumAckBegin < 0 )\n\t\t\t\t\t\tDECODE_ERROR( \"Ack range underflow, end=%lld, num=%lld\", (long long)nPktNumAckEnd, (long long)numAcks );\n\n\t\t\t\t\t// Extended nack count?\n\t\t\t\t\tint64 numNacks = nBlockHeader & 7;\n\t\t\t\t\tif ( nBlockHeader & 0x08)\n\t\t\t\t\t{\n\t\t\t\t\t\tuint64 nUpperBits;\n\t\t\t\t\t\tREAD_VARINT( nUpperBits, \"nack count upper bits\" );\n\t\t\t\t\t\tif ( nUpperBits > 100000 )\n\t\t\t\t\t\t\tDECODE_ERROR( \"Nack count of %llu<<3 is crazy\", nUpperBits );\n\t\t\t\t\t\tnumNacks |= nUpperBits<<3;\n\t\t\t\t\t}\n\t\t\t\t\tnPktNumNackBegin = nPktNumAckBegin - numNacks;\n\t\t\t\t\tif ( nPktNumNackBegin < 0 )\n\t\t\t\t\t\tDECODE_ERROR( \"Nack range underflow, end=%lld, num=%lld\", (long long)nPktNumAckBegin, (long long)numAcks );\n\n\t\t\t\t\tSpewDebugGroup( nLogLevelPacketDecode, \"[%s] decode pkt %lld nack [%lld,%lld) ack [%lld,%lld)\\n\",\n\t\t\t\t\t\tGetDescription(),\n\t\t\t\t\t\t(long long)nPktNum,\n\t\t\t\t\t\t(long long)nPktNumNackBegin, (long long)( nPktNumNackBegin + numNacks ),\n\t\t\t\t\t\t(long long)nPktNumAckBegin, (long long)( nPktNumAckBegin + numAcks )\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Process acks first.\n\t\t\t\tAssert( nPktNumAckBegin >= 0 );\n\t\t\t\twhile ( inFlightPkt->first >= nPktNumAckBegin )\n\t\t\t\t{\n\t\t\t\t\tAssert( inFlightPkt->first < nPktNumAckEnd );\n\n\t\t\t\t\t// Scan reliable segments, and see if any are marked for retry or are in flight\n\t\t\t\t\tfor ( const SNPRange_t &relRange: inFlightPkt->second.m_vecReliableSegments )\n\t\t\t\t\t{\n\n\t\t\t\t\t\t// If range is present, it should be in only one of these two tables.\n\t\t\t\t\t\tif ( m_senderState.m_listInFlightReliableRange.erase( relRange ) == 0 )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif ( m_senderState.m_listReadyRetryReliableRange.erase( relRange ) > 0 )\n\t\t\t\t\t\t\t{\n\n\t\t\t\t\t\t\t\t// When we put stuff into the reliable retry list, we mark it as pending again.\n\t\t\t\t\t\t\t\t// But now it's acked, so it's no longer pending, even though we didn't send it.\n\t\t\t\t\t\t\t\tm_senderState.m_cbPendingReliable -= int( relRange.length() );\n\t\t\t\t\t\t\t\tAssert( m_senderState.m_cbPendingReliable >= 0 );\n\n\t\t\t\t\t\t\t\tbAckedReliableRange = true;\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\tbAckedReliableRange = true;\n\t\t\t\t\t\t\tAssert( m_senderState.m_listReadyRetryReliableRange.count( relRange ) == 0 );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Check if this was the next packet we were going to timeout, then advance\n\t\t\t\t\t// pointer. This guy didn't timeout.\n\t\t\t\t\tif ( inFlightPkt == m_senderState.m_itNextInFlightPacketToTimeout )\n\t\t\t\t\t\t++m_senderState.m_itNextInFlightPacketToTimeout;\n\n\t\t\t\t\t// No need to track this anymore, remove from our table\n\t\t\t\t\tinFlightPkt = m_senderState.m_mapInFlightPacketsByPktNum.erase( inFlightPkt );\n\t\t\t\t\t--inFlightPkt;\n\t\t\t\t\tm_senderState.MaybeCheckInFlightPacketMap();\n\t\t\t\t}\n\n\t\t\t\t// Ack of in-flight end-to-end stats?\n\t\t\t\tif ( nPktNumAckBegin <= m_statsEndToEnd.m_pktNumInFlight && m_statsEndToEnd.m_pktNumInFlight < nPktNumAckEnd )\n\t\t\t\t\tm_statsEndToEnd.InFlightPktAck( usecNow );\n\n\t\t\t\t// Process nacks.\n\t\t\t\tAssert( nPktNumNackBegin >= 0 );\n\t\t\t\twhile ( inFlightPkt->first >= nPktNumNackBegin )\n\t\t\t\t{\n\t\t\t\t\tAssert( inFlightPkt->first < nPktNumAckEnd );\n\t\t\t\t\tSNP_SenderProcessPacketNack( inFlightPkt->first, inFlightPkt->second, \"NACK\" );\n\n\t\t\t\t\t// We'll keep the record on hand, though, in case an ACK comes in\n\t\t\t\t\t--inFlightPkt;\n\t\t\t\t}\n\n\t\t\t\t// Continue on to the the next older block\n\t\t\t\tnPktNumAckEnd = nPktNumNackBegin;\n\t\t\t\t--nBlocks;\n\t\t\t}\n\n\t\t\t// Should we check for discarding reliable messages we are keeping around in case\n\t\t\t// of retransmission, since we know now that they were delivered?\n\t\t\tif ( bAckedReliableRange )\n\t\t\t{\n\t\t\t\tm_senderState.RemoveAckedReliableMessageFromUnackedList();\n\n\t\t\t\t// Spew where we think the peer is decoding the reliable stream\n\t\t\t\tif ( nLogLevelPacketDecode >= k_ESteamNetworkingSocketsDebugOutputType_Debug )\n\t\t\t\t{\n\n\t\t\t\t\tint64 nPeerReliablePos = m_senderState.m_nReliableStreamPos;\n\t\t\t\t\tif ( !m_senderState.m_listInFlightReliableRange.empty() )\n\t\t\t\t\t\tnPeerReliablePos = std::min( nPeerReliablePos, m_senderState.m_listInFlightReliableRange.begin()->first.m_nBegin );\n\t\t\t\t\tif ( !m_senderState.m_listReadyRetryReliableRange.empty() )\n\t\t\t\t\t\tnPeerReliablePos = std::min( nPeerReliablePos, m_senderState.m_listReadyRetryReliableRange.begin()->first.m_nBegin );\n\n\t\t\t\t\tSpewDebugGroup( nLogLevelPacketDecode, \"[%s] decode pkt %lld peer reliable pos = %lld\\n\",\n\t\t\t\t\t\tGetDescription(),\n\t\t\t\t\t\t(long long)nPktNum, (long long)nPeerReliablePos );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check if any of this was new info, then advance our stop_waiting value.\n\t\t\tif ( nLatestRecvSeqNum > m_senderState.m_nMinPktWaitingOnAck )\n\t\t\t{\n\t\t\t\tSpewVerboseGroup( nLogLevelPacketDecode, \"[%s] updating min_waiting_on_ack %lld -> %lld\\n\",\n\t\t\t\t\tGetDescription(),\n\t\t\t\t\t(long long)m_senderState.m_nMinPktWaitingOnAck, (long long)nLatestRecvSeqNum );\n\t\t\t\tm_senderState.m_nMinPktWaitingOnAck = nLatestRecvSeqNum;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tDECODE_ERROR( \"Invalid SNP frame lead byte 0x%02x\", nFrameType );\n\t\t}\n\t}\n\n\t// Should we record that we received it?\n\tif ( bInhibitMarkReceived )\n\t{\n\t\t// Something really odd. High packet loss / fragmentation.\n\t\t// Potentially the peer is being abusive and we need\n\t\t// to protect ourselves.\n\t\t//\n\t\t// Act as if the packet was dropped. This will cause the\n\t\t// peer's sender logic to interpret this as additional packet\n\t\t// loss and back off. That's a feature, not a bug.\n\t}\n\telse\n\t{\n\n\t\t// Update structures needed to populate our ACKs.\n\t\t// If we received reliable data now, then schedule an ack\n\t\tbool bScheduleAck = nDecodeReliablePos > 0;\n\t\tSNP_RecordReceivedPktNum( nPktNum, usecNow, bScheduleAck );\n\t}\n\n\t// Track end-to-end flow. Even if we decided to tell our peer that\n\t// we did not receive this, we want our own stats to reflect\n\t// that we did. (And we want to be able to quickly reject a\n\t// packet with this same number.)\n\t//\n\t// Also, note that order of operations is important. This call must\n\t// happen after the SNP_RecordReceivedPktNum call above\n\tm_statsEndToEnd.TrackProcessSequencedPacket( nPktNum, usecNow, usecTimeSinceLast );\n\n\t// Packet can be processed further\n\treturn true;\n\n\t// Make sure these don't get used beyond where we intended them to get used\n\t#undef DECODE_ERROR\n\t#undef EXPECT_BYTES\n\t#undef READ_8BITU\n\t#undef READ_16BITU\n\t#undef READ_24BITU\n\t#undef READ_32BITU\n\t#undef READ_64BITU\n\t#undef READ_VARINT\n\t#undef READ_SEGMENT_DATA_SIZE\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Drop unreliable segments with weird offset/size.\n\nAnd be more deliberate about limits of unreliable message/segment sizes.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: R_API int r_sys_cmd_str_full(const char *cmd, const char *input, char **output, int *len, char **sterr) {\n\teprintf (\"r_sys_cmd_str: not yet implemented for this platform\\n\");\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: R_API bool r_socket_connect (RSocket *s, const char *host, const char *port, int proto, unsigned int timeout) {\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: R_API int r_socket_ready(RSocket *s, int secs, int usecs) {\n#if __UNIX__\n\t//int msecs = (1000 * secs) + (usecs / 1000);\n\tint msecs = (usecs / 1000);\n\tstruct pollfd fds[1];\n\tfds[0].fd = s->fd;\n\tfds[0].events = POLLIN | POLLPRI;\n\tfds[0].revents = POLLNVAL | POLLHUP | POLLERR;\n\treturn poll ((struct pollfd *)&fds, 1, msecs);\n#elif __WINDOWS__\n\tfd_set rfds;\n\tstruct timeval tv;\n\tif (s->fd == R_INVALID_SOCKET) {\n\t\treturn -1;\n\t}\n\tFD_ZERO (&rfds);\n\tFD_SET (s->fd, &rfds);\n\ttv.tv_sec = secs;\n\ttv.tv_usec = usecs;\n\treturn select (s->fd + 1, &rfds, NULL, NULL, &tv);\n#else\n\treturn true; /* always ready if unknown */\n#endif\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::create(std::size_t capacity) {\n // For smaller-sized buffers, allocate the IOBuf, SharedInfo, and the buffer\n // all with a single allocation.\n //\n // We don't do this for larger buffers since it can be wasteful if the user\n // needs to reallocate the buffer but keeps using the same IOBuf object.\n // In this case we can't free the data space until the IOBuf is also\n // destroyed. Callers can explicitly call createCombined() or\n // createSeparate() if they know their use case better, and know if they are\n // likely to reallocate the buffer later.\n if (capacity <= kDefaultCombinedBufSize) {\n return createCombined(capacity);\n }\n\n // if we have nallocx, we want to allocate the capacity and the overhead in\n // a single allocation only if we do not cross into the next allocation class\n // for some buffer sizes, this can use about 25% extra memory\n if (canNallocx()) {\n auto mallocSize = goodMallocSize(capacity);\n // round capacity to a multiple of 8\n size_t minSize = ((capacity + 7) & ~7) + sizeof(SharedInfo);\n // if we do not have space for the overhead, allocate the mem separateley\n if (mallocSize < minSize) {\n auto* buf = checkedMalloc(mallocSize);\n return takeOwnership(SIZED_FREE, buf, mallocSize, 0, 0);\n }\n }\n\n return createSeparate(capacity);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': '[folly] Add additional overflow checks to IOBuf - CVE-2021-24036\n\nSummary:\nAs per title\n\nCVE-2021-24036\n\nReviewed By: jan\n\nDifferential Revision: D27938605\n\nfbshipit-source-id: 7481c54ae6fbb7b67b15b3631d5357c2f7043f9c'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void Sp_split_regexp(js_State *J)\n{\n\tjs_Regexp *re;\n\tconst char *text;\n\tint limit, len, k;\n\tconst char *p, *a, *b, *c, *e;\n\tResub m;\n\n\ttext = checkstring(J, 0);\n\tre = js_toregexp(J, 1);\n\tlimit = js_isdefined(J, 2) ? js_tointeger(J, 2) : 1 << 30;\n\n\tjs_newarray(J);\n\tlen = 0;\n\n\te = text + strlen(text);\n\n\t/* splitting the empty string */\n\tif (e == text) {\n\t\tif (js_regexec(re->prog, text, &m, 0)) {\n\t\t\tif (len == limit) return;\n\t\t\tjs_pushliteral(J, \"\");\n\t\t\tjs_setindex(J, -2, 0);\n\t\t}\n\t\treturn;\n\t}\n\n\tp = a = text;\n\twhile (a < e) {\n\t\tif (js_regexec(re->prog, a, &m, a > text ? REG_NOTBOL : 0))\n\t\t\tbreak; /* no match */\n\n\t\tb = m.sub[0].sp;\n\t\tc = m.sub[0].ep;\n\n\t\t/* empty string at end of last match */\n\t\tif (b == p) {\n\t\t\t++a;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (len == limit) return;\n\t\tjs_pushlstring(J, p, b - p);\n\t\tjs_setindex(J, -2, len++);\n\n\t\tfor (k = 1; k < m.nsub; ++k) {\n\t\t\tif (len == limit) return;\n\t\t\tjs_pushlstring(J, m.sub[k].sp, m.sub[k].ep - m.sub[k].sp);\n\t\t\tjs_setindex(J, -2, len++);\n\t\t}\n\n\t\ta = p = c;\n\t}\n\n\tif (len == limit) return;\n\tjs_pushstring(J, p);\n\tjs_setindex(J, -2, len);\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_realloc(\n sixel_allocator_t /* in */ *allocator, /* allocator object */\n void /* in */ *p, /* existing buffer to be re-allocated */\n size_t /* in */ n) /* re-allocation size */\n{\n /* precondition */\n assert(allocator);\n assert(allocator->fn_realloc);\n\n return allocator->fn_realloc(p, n);\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: static void gf_isom_write_tx3g(GF_Tx3gSampleEntryBox *a, GF_BitStream *bs, u32 sidx, u32 sidx_offset)\n{\n\tu32 size, j, fount_count;\n\tBool is_qt_text = (a->type==GF_ISOM_BOX_TYPE_TEXT) ? GF_TRUE : GF_FALSE;\n\tconst char *qt_fontname = NULL;\n\tvoid gpp_write_rgba(GF_BitStream *bs, u32 col);\n\tvoid gpp_write_box(GF_BitStream *bs, GF_BoxRecord *rec);\n\tvoid gpp_write_style(GF_BitStream *bs, GF_StyleRecord *rec);\n\n\n\tif (sidx_offset) gf_bs_write_u8(bs, sidx + sidx_offset);\n\n\t/*SINCE WINCE HAS A READONLY VERSION OF MP4 WE MUST DO IT BY HAND*/\n\tsize = 8 + 18 + 8 + 12;\n\tsize += 8 + 2;\n\tfount_count = 0;\n\tif (is_qt_text) {\n\t\tGF_TextSampleEntryBox *qt = (GF_TextSampleEntryBox *)a;\n\t\tif (qt->textName) {\n\t\t\tqt_fontname = qt->textName;\n\t\t\tfount_count = 1;\n\t\t}\n\t} else {\n\t\tif (a->font_table) {\n\t\t\tfount_count = a->font_table->entry_count;\n\t\t\tfor (j=0; jfont_table->fonts[j].fontName) size += (u32) strlen(a->font_table->fonts[j].fontName);\n\t\t\t}\n\t\t}\n\t}\n\t/*write TextSampleEntry box*/\n\tgf_bs_write_u32(bs, size);\n\tgf_bs_write_u32(bs, a->type);\n\tgf_bs_write_data(bs, a->reserved, 6);\n\tgf_bs_write_u16(bs, a->dataReferenceIndex);\n\tgf_bs_write_u32(bs, a->displayFlags);\n\tgf_bs_write_u8(bs, a->horizontal_justification);\n\tgf_bs_write_u8(bs, a->vertical_justification);\n\tgpp_write_rgba(bs, a->back_color);\n\tgpp_write_box(bs, &a->default_box);\n\tgpp_write_style(bs, &a->default_style);\n\t/*write font table box*/\n\tsize -= (8 + 18 + 8 + 12);\n\tgf_bs_write_u32(bs, size);\n\tgf_bs_write_u32(bs, GF_ISOM_BOX_TYPE_FTAB);\n\n\tgf_bs_write_u16(bs, fount_count);\n\tfor (j=0; jfont_table->fonts[j].fontID);\n\t\t\tif (a->font_table->fonts[j].fontName) {\n\t\t\t\tu32 len = (u32) strlen(a->font_table->fonts[j].fontName);\n\t\t\t\tgf_bs_write_u8(bs, len);\n\t\t\t\tgf_bs_write_data(bs, a->font_table->fonts[j].fontName, len);\n\t\t\t} else {\n\t\t\t\tgf_bs_write_u8(bs, 0);\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 #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: int parse_config(char *filename, bridge_t **bridges)\n{\n dictionary *ubridge_config = NULL;\n const char *value;\n const char *bridge_name;\n int i, nsec;\n\n if ((ubridge_config = iniparser_load(filename)) == NULL) {\n return FALSE;\n }\n\n nsec = iniparser_getnsec(ubridge_config);\n for (i = 0; i < nsec; i++) {\n bridge_t *bridge;\n nio_t *source_nio = NULL;\n nio_t *destination_nio = NULL;\n\n bridge_name = iniparser_getsecname(ubridge_config, i);\n printf(\"Parsing %s\\n\", bridge_name);\n if (getstr(ubridge_config, bridge_name, \"source_udp\", &value))\n source_nio = create_udp_tunnel(value);\n else if (getstr(ubridge_config, bridge_name, \"source_unix\", &value))\n source_nio = create_unix_socket(value);\n else if (getstr(ubridge_config, bridge_name, \"source_ethernet\", &value))\n source_nio = open_ethernet_device(value);\n else if (getstr(ubridge_config, bridge_name, \"source_tap\", &value))\n source_nio = open_tap_device(value);\n#ifdef LINUX_RAW\n else if (getstr(ubridge_config, bridge_name, \"source_linux_raw\", &value))\n source_nio = open_linux_raw(value);\n#endif\n#ifdef __APPLE__\n else if (getstr(ubridge_config, bridge_name, \"source_fusion_vmnet\", &value))\n source_nio = open_fusion_vmnet(value);\n#endif\n else\n fprintf(stderr, \"source NIO not found\\n\");\n\n if (getstr(ubridge_config, bridge_name, \"destination_udp\", &value))\n destination_nio = create_udp_tunnel(value);\n else if (getstr(ubridge_config, bridge_name, \"destination_unix\", &value))\n destination_nio = create_unix_socket(value);\n else if (getstr(ubridge_config, bridge_name, \"destination_ethernet\", &value))\n destination_nio = open_ethernet_device(value);\n else if (getstr(ubridge_config, bridge_name, \"destination_tap\", &value))\n destination_nio = open_tap_device(value);\n#ifdef LINUX_RAW\n else if (getstr(ubridge_config, bridge_name, \"destination_linux_raw\", &value))\n source_nio = open_linux_raw(value);\n#endif\n#ifdef __APPLE__\n else if (getstr(ubridge_config, bridge_name, \"destination_fusion_vmnet\", &value))\n destination_nio = open_fusion_vmnet(value);\n#endif\n else\n fprintf(stderr, \"destination NIO not found\\n\");\n\n if (source_nio && destination_nio) {\n bridge = add_bridge(bridges);\n bridge->source_nio = source_nio;\n bridge->destination_nio = destination_nio;\n if (!(bridge->name = strdup(bridge_name))) {\n fprintf(stderr, \"bridge creation: insufficient memory\\n\");\n return FALSE;\n }\n parse_capture(ubridge_config, bridge_name, bridge);\n parse_filter(ubridge_config, bridge_name, bridge);\n }\n else if (source_nio != NULL)\n free_nio(source_nio);\n else if (destination_nio != NULL)\n free_nio(destination_nio);\n }\n iniparser_freedict(ubridge_config);\n return TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-269'], 'message': 'Hide errored line content during parsing configuration INI file on default'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int rfcomm_get_dev_list(void __user *arg)\n{\n\tstruct rfcomm_dev *dev;\n\tstruct rfcomm_dev_list_req *dl;\n\tstruct rfcomm_dev_info *di;\n\tint n = 0, size, err;\n\tu16 dev_num;\n\n\tBT_DBG(\"\");\n\n\tif (get_user(dev_num, (u16 __user *) arg))\n\t\treturn -EFAULT;\n\n\tif (!dev_num || dev_num > (PAGE_SIZE * 4) / sizeof(*di))\n\t\treturn -EINVAL;\n\n\tsize = sizeof(*dl) + dev_num * sizeof(*di);\n\n\tdl = kmalloc(size, GFP_KERNEL);\n\tif (!dl)\n\t\treturn -ENOMEM;\n\n\tdi = dl->dev_info;\n\n\tspin_lock(&rfcomm_dev_lock);\n\n\tlist_for_each_entry(dev, &rfcomm_dev_list, list) {\n\t\tif (test_bit(RFCOMM_TTY_RELEASED, &dev->flags))\n\t\t\tcontinue;\n\t\t(di + n)->id = dev->id;\n\t\t(di + n)->flags = dev->flags;\n\t\t(di + n)->state = dev->dlc->state;\n\t\t(di + n)->channel = dev->channel;\n\t\tbacpy(&(di + n)->src, &dev->src);\n\t\tbacpy(&(di + n)->dst, &dev->dst);\n\t\tif (++n >= dev_num)\n\t\t\tbreak;\n\t}\n\n\tspin_unlock(&rfcomm_dev_lock);\n\n\tdl->dev_num = n;\n\tsize = sizeof(*dl) + n * sizeof(*di);\n\n\terr = copy_to_user(arg, dl, size);\n\tkfree(dl);\n\n\treturn err ? -EFAULT : 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Bluetooth: RFCOMM - Fix info leak in ioctl(RFCOMMGETDEVLIST)\n\nThe RFCOMM code fails to initialize the two padding bytes of struct\nrfcomm_dev_list_req inserted for alignment before copying it to\nuserland. Additionally there are two padding bytes in each instance of\nstruct rfcomm_dev_info. The ioctl() that for disclosures two bytes plus\ndev_num times two bytes uninitialized kernel heap memory.\n\nAllocate the memory using kzalloc() to fix this issue.\n\nSigned-off-by: Mathias Krause \nCc: Marcel Holtmann \nCc: Gustavo Padovan \nCc: Johan Hedberg \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int __init mbochs_dev_init(void)\n{\n\tint ret = 0;\n\n\tret = alloc_chrdev_region(&mbochs_devt, 0, MINORMASK + 1, MBOCHS_NAME);\n\tif (ret < 0) {\n\t\tpr_err(\"Error: failed to register mbochs_dev, err: %d\\n\", ret);\n\t\treturn ret;\n\t}\n\tcdev_init(&mbochs_cdev, &vd_fops);\n\tcdev_add(&mbochs_cdev, mbochs_devt, MINORMASK + 1);\n\tpr_info(\"%s: major %d\\n\", __func__, MAJOR(mbochs_devt));\n\n\tret = mdev_register_driver(&mbochs_driver);\n\tif (ret)\n\t\tgoto err_cdev;\n\n\tmbochs_class = class_create(THIS_MODULE, MBOCHS_CLASS_NAME);\n\tif (IS_ERR(mbochs_class)) {\n\t\tpr_err(\"Error: failed to register mbochs_dev class\\n\");\n\t\tret = PTR_ERR(mbochs_class);\n\t\tgoto err_driver;\n\t}\n\tmbochs_dev.class = mbochs_class;\n\tmbochs_dev.release = mbochs_device_release;\n\tdev_set_name(&mbochs_dev, \"%s\", MBOCHS_NAME);\n\n\tret = device_register(&mbochs_dev);\n\tif (ret)\n\t\tgoto err_class;\n\n\tret = mdev_register_device(&mbochs_dev, &mdev_fops);\n\tif (ret)\n\t\tgoto err_device;\n\n\treturn 0;\n\nerr_device:\n\tdevice_unregister(&mbochs_dev);\nerr_class:\n\tclass_destroy(mbochs_class);\nerr_driver:\n\tmdev_unregister_driver(&mbochs_driver);\nerr_cdev:\n\tcdev_del(&mbochs_cdev);\n\tunregister_chrdev_region(mbochs_devt, MINORMASK + 1);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-401'], 'message': 'vfio/mbochs: Fix missing error unwind of mbochs_used_mbytes\n\nConvert mbochs to use an atomic scheme for this like mtty was changed\ninto. The atomic fixes various race conditions with probing. Add the\nmissing error unwind. Also add the missing kfree of mdev_state->pages.\n\nFixes: 681c1615f891 (\"vfio/mbochs: Convert to use vfio_register_group_dev()\")\nReported-by: Cornelia Huck \nCo-developed-by: Alex Williamson \nReviewed-by: Christoph Hellwig \nSigned-off-by: Jason Gunthorpe \nReviewed-by: Cornelia Huck \nLink: https://lore.kernel.org/r/2-v4-9ea22c5e6afb+1adf-vfio_reflck_jgg@nvidia.com\nSigned-off-by: Alex Williamson '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static CURLcode pop3_parse_url_path(struct connectdata *conn)\n{\n /* the pop3 struct is already inited in pop3_connect() */\n struct pop3_conn *pop3c = &conn->proto.pop3c;\n struct SessionHandle *data = conn->data;\n const char *path = data->state.path;\n\n /* url decode the path and use this mailbox */\n pop3c->mailbox = curl_easy_unescape(data, path, 0, NULL);\n if(!pop3c->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 operator()(OpKernelContext* ctx, const CPUDevice& d, const T* rate_flat,\n int num_rate, int num_samples,\n const random::PhiloxRandom& rng, U* samples_flat) {\n // Two different algorithms are employed, depending on the size of\n // rate.\n // If rate < 10, we use an algorithm attributed to Knuth:\n // Seminumerical Algorithms. Art of Computer Programming, Volume 2.\n //\n // This algorithm runs in O(rate) time, and will require O(rate)\n // uniform variates.\n //\n // If rate >= 10 we use a transformation-rejection algorithm from\n // pairs of uniform random variables due to Hormann.\n // http://www.sciencedirect.com/science/article/pii/0167668793909974\n //\n // The algorithm has an acceptance rate of ~89% for the smallest rate\n // (~10),\n // and higher accept rates for higher rate, so runtime is\n // O(NumRate * NumSamples * k) with k ~ 1 / 0.89.\n //\n // We partition work first across rates then across\n // samples-per-rate to\n // avoid a couple flops which can be done on a per-rate basis.\n\n typedef random::UniformDistribution Uniform;\n\n auto DoWork = [num_samples, num_rate, &rng, samples_flat, rate_flat](\n int start_output, int limit_output) {\n // Capturing \"rng\" by value would only make a copy for the _shared_\n // lambda. Since we want to let each worker have its own copy, we pass\n // \"rng\" by reference and explicitly do a copy assignment.\n\n Uniform uniform;\n typename Uniform::ResultType uniform_result;\n for (int64 output_idx = start_output; output_idx < limit_output;\n /* output_idx incremented within inner loop below */) {\n const int64 rate_idx = output_idx / num_samples;\n\n // Several calculations can be done on a per-rate basis.\n const CT rate = CT(rate_flat[rate_idx]);\n\n auto samples_rate_output = samples_flat + rate_idx;\n\n if (rate < CT(10)) {\n // Knuth's algorithm for generating Poisson random variates.\n // Given a Poisson process, the time between events is exponentially\n // distributed. If we have a Poisson process with rate lambda, then,\n // the time between events is distributed Exp(lambda). If X ~\n // Uniform(0, 1), then Y ~ Exp(lambda), where Y = -log(X) / lambda.\n // Thus to simulate a Poisson draw, we can draw X_i ~ Exp(lambda),\n // and N ~ Poisson(lambda), where N is the least number such that\n // \\sum_i^N X_i > 1.\n const CT exp_neg_rate = Eigen::numext::exp(-rate);\n\n // Compute the rest of the samples for the current rate value.\n for (int64 sample_idx = output_idx % num_samples;\n sample_idx < num_samples && output_idx < limit_output;\n sample_idx++, output_idx++) {\n random::PhiloxRandom gen = rng;\n gen.Skip(kReservedSamplesPerOutput * output_idx);\n int16 uniform_remaining = 0;\n\n CT prod = 1;\n CT x = 0;\n\n // Keep trying until we surpass e^(-rate). This will take\n // expected time proportional to rate.\n while (true) {\n UNIFORM(u);\n prod = prod * u;\n if (prod <= exp_neg_rate &&\n x <= CT(Eigen::NumTraits::highest())) {\n samples_rate_output[sample_idx * num_rate] = U(x);\n break;\n }\n x += 1;\n }\n }\n continue;\n }\n // Transformed rejection due to Hormann.\n //\n // Given a CDF F(x), and G(x), a dominating distribution chosen such\n // that it is close to the inverse CDF F^-1(x), compute the following\n // steps:\n //\n // 1) Generate U and V, two independent random variates. Set U = U - 0.5\n // (this step isn't strictly necessary, but is done to make some\n // calculations symmetric and convenient. Henceforth, G is defined on\n // [-0.5, 0.5]).\n //\n // 2) If V <= alpha * F'(G(U)) * G'(U), return floor(G(U)), else return\n // to step 1. alpha is the acceptance probability of the rejection\n // algorithm.\n //\n // For more details on transformed rejection, see:\n // http://citeseer.ist.psu.edu/viewdoc/citations;jsessionid=1BEB35946CC807879F55D42512E5490C?doi=10.1.1.48.3054.\n //\n // The dominating distribution in this case:\n //\n // G(u) = (2 * a / (2 - |u|) + b) * u + c\n\n using Eigen::numext::log;\n const CT log_rate = log(rate);\n\n // Constants used to define the dominating distribution. Names taken\n // from Hormann's paper. Constants were chosen to define the tightest\n // G(u) for the inverse Poisson CDF.\n const CT b = CT(0.931) + CT(2.53) * Eigen::numext::sqrt(rate);\n const CT a = CT(-0.059) + CT(0.02483) * b;\n\n // This is the inverse acceptance rate. At a minimum (when rate = 10),\n // this corresponds to ~75% acceptance. As the rate becomes larger, this\n // approaches ~89%.\n const CT inv_alpha = CT(1.1239) + CT(1.1328) / (b - CT(3.4));\n\n // Compute the rest of the samples for the current rate value.\n for (int64 sample_idx = output_idx % num_samples;\n sample_idx < num_samples && output_idx < limit_output;\n sample_idx++, output_idx++) {\n random::PhiloxRandom gen = rng;\n gen.Skip(kReservedSamplesPerOutput * output_idx);\n int16 uniform_remaining = 0;\n\n while (true) {\n UNIFORM(u);\n u -= CT(0.5);\n UNIFORM(v);\n\n CT u_shifted = CT(0.5) - Eigen::numext::abs(u);\n CT k = Eigen::numext::floor((CT(2) * a / u_shifted + b) * u + rate +\n CT(0.43));\n\n if (k > CT(Eigen::NumTraits::highest())) {\n // retry in case of overflow.\n continue;\n }\n\n // When alpha * f(G(U)) * G'(U) is close to 1, it is possible to\n // find a rectangle (-u_r, u_r) x (0, v_r) under the curve, such\n // that if v <= v_r and |u| <= u_r, then we can accept.\n // Here v_r = 0.9227 - 3.6224 / (b - 2) and u_r = 0.43.\n if (u_shifted >= CT(0.07) &&\n v <= CT(0.9277) - CT(3.6224) / (b - CT(2))) {\n samples_rate_output[sample_idx * num_rate] = U(k);\n break;\n }\n\n if (k < 0 || (u_shifted < CT(0.013) && v > u_shifted)) {\n continue;\n }\n\n // The expression below is equivalent to the computation of step 2)\n // in transformed rejection (v <= alpha * F'(G(u)) * G'(u)).\n CT s = log(v * inv_alpha / (a / (u_shifted * u_shifted) + b));\n CT t = -rate + k * log_rate - Eigen::numext::lgamma(k + 1);\n if (s <= t) {\n samples_rate_output[sample_idx * num_rate] = U(k);\n break;\n }\n }\n }\n }\n };\n\n // This will depend on rate.\n // For rate < 10, on average, O(rate) calls to uniform are\n // needed, with that\n // many multiplies. ~10 uniform calls on average with ~25 cost op calls.\n //\n // Very roughly, for rate >= 10, the single call to log + call to\n // lgamma\n // occur for ~60 percent of samples.\n // 2 x 100 (64-bit cycles per log) * 0.62 = ~124\n // Additionally, there are ~10 other ops (+, *, /, ...) at 3-6 cycles each:\n // 40 * .62 = ~25.\n //\n // Finally, there are several other ops that are done every loop along with\n // 2 uniform generations along with 5 other ops at 3-6 cycles each.\n // ~15 / .89 = ~16\n //\n // In total this should be ~165 + 2 * Uniform::kElementCost.\n // We assume that half the tensor has rate < 10, so on average 6\n // uniform's\n // will be needed. We will upper bound the other op cost by the one for\n // rate > 10.\n static const int kElementCost = 165 + 6 * Uniform::kElementCost +\n 6 * random::PhiloxRandom::kElementCost;\n auto worker_threads = *(ctx->device()->tensorflow_cpu_worker_threads());\n Shard(worker_threads.num_threads, worker_threads.workers,\n num_rate * num_samples, kElementCost, DoWork);\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: read_data_section (Bit_Chain *sec_dat, Bit_Chain *dat,\n r2007_section *restrict sections_map,\n r2007_page *restrict pages_map, Dwg_Section_Type sec_type)\n{\n r2007_section *section;\n r2007_page *page;\n uint64_t max_decomp_size;\n BITCODE_RC *decomp;\n int error = 0, i;\n\n section = get_section (sections_map, sec_type);\n sec_dat->chain = NULL;\n if (section == NULL)\n {\n if (sec_type < SECTION_REVHISTORY\n && sec_type != SECTION_TEMPLATE\n && sec_type != SECTION_OBJFREESPACE)\n {\n LOG_WARN (\"Failed to find section_info[%u]\", (int)sec_type)\n return DWG_ERR_SECTIONNOTFOUND;\n }\n else\n {\n LOG_TRACE (\"Found no section_info[%u]\\n\", (int)sec_type)\n return DWG_ERR_VALUEOUTOFBOUNDS;\n }\n }\n\n max_decomp_size = section->data_size;\n if (max_decomp_size > 0x2f000000) // 790Mb\n {\n LOG_ERROR (\"Invalid max decompression size %\" PRIu64, max_decomp_size);\n return DWG_ERR_INVALIDDWG;\n }\n decomp = (BITCODE_RC *)calloc (max_decomp_size, 1);\n if (decomp == NULL)\n {\n LOG_ERROR (\"Out of memory\")\n return DWG_ERR_OUTOFMEM;\n }\n LOG_HANDLE (\"Alloc data section of size %\" PRIu64 \"\\n\", max_decomp_size)\n\n sec_dat->bit = 0;\n sec_dat->byte = 0;\n sec_dat->size = max_decomp_size;\n sec_dat->version = dat->version;\n sec_dat->from_version = dat->from_version;\n\n for (i = 0; i < (int)section->num_pages; i++)\n {\n r2007_section_page *section_page = section->pages[i];\n page = get_page (pages_map, section_page->id);\n if (page == NULL)\n {\n free (decomp);\n LOG_ERROR (\"Failed to find page %d\", (int)section_page->id)\n return DWG_ERR_PAGENOTFOUND;\n }\n if (section_page->offset > max_decomp_size)\n {\n free (decomp);\n LOG_ERROR (\"Invalid section_page->offset %ld > %ld\",\n (long)section_page->offset, (long)max_decomp_size)\n return DWG_ERR_VALUEOUTOFBOUNDS;\n }\n\n dat->byte = page->offset;\n // only if compressed. TODO: Isn't there a compressed flag as with 2004+?\n // theoretically the sizes could still be the same.\n if (section_page->comp_size != section_page->uncomp_size)\n {\n error = read_data_page (dat, &decomp[section_page->offset],\n page->size, section_page->comp_size,\n section_page->uncomp_size);\n if (error)\n {\n free (decomp);\n LOG_ERROR (\"Failed to read compressed page\")\n return error;\n }\n }\n else\n {\n memcpy (&decomp[section_page->offset], &dat->chain[dat->byte],\n section_page->uncomp_size);\n }\n }\n sec_dat->chain = decomp;\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'decode_r2007: fix for invalid section size\n\nSee GH #350. With fuzzing section->data_size might not fit\nsection_page->uncomp_size.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Bool rfbOptPamAuth(void)\n{\n SecTypeData *s;\n\n for (s = secTypes; s->name != NULL; s++) {\n if ((!strcmp(s->name, \"unixlogin\") ||\n !strcmp(&s->name[strlen(s->name) - 5], \"plain\")) && s->enabled)\n return TRUE;\n }\n\n return FALSE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Server: Fix two issues identified by ASan\n\n1. If the TLSPlain and X509Plain security types were both disabled, then\n rfbOptPamAuth() would overflow the name field in the secTypes\n structure when testing the \"none\" security type, since the name of\n that security type has less than five characters. This issue was\n innocuous, since the overflow was fully contained within the secTypes\n structure, but the ASan error caused Xvnc to abort, which made it\n difficult to detect other errors.\n\n2. If an ill-behaved RFB client sent the TurboVNC Server a fence\n message with more than 64 bytes, then the TurboVNC Server would\n try to read that message and subsequently overflow the stack before\n it detected that the payload was too large. This could never have\n occurred with any of the VNC viewers that currently support the RFB\n flow control extensions (TigerVNC and TurboVNC, namely.) This issue\n was also innocuous, since the stack overflow affected two variables\n (newScreens and errMsg) that were never accessed before the function\n returned.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int __init acpi_custom_method_init(void)\n{\n\tif (!acpi_debugfs_dir)\n\t\treturn -ENOENT;\n\n\tcm_dentry = debugfs_create_file(\"custom_method\", S_IWUSR,\n\t\t\t\t\tacpi_debugfs_dir, NULL, &cm_fops);\n\tif (!cm_dentry)\n\t\treturn -ENODEV;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'ACPI: Split out custom_method functionality into an own driver\n\nWith /sys/kernel/debug/acpi/custom_method root can write\nto arbitrary memory and increase his priveleges, even if\nthese are restricted.\n\n-> Make this an own debug .config option and warn about the\nsecurity issue in the config description.\n\n-> Still keep acpi/debugfs.c which now only creates an empty\n /sys/kernel/debug/acpi directory. There might be other\n users of it later.\n\nSigned-off-by: Thomas Renninger \nAcked-by: Rafael J. Wysocki \nAcked-by: rui.zhang@intel.com\nSigned-off-by: Len Brown '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ff_h263_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,\n AVPacket *avpkt)\n{\n const uint8_t *buf = avpkt->data;\n int buf_size = avpkt->size;\n MpegEncContext *s = avctx->priv_data;\n int ret;\n int slice_ret = 0;\n AVFrame *pict = data;\n\n /* no supplementary picture */\n if (buf_size == 0) {\n /* special case for last picture */\n if (s->low_delay == 0 && s->next_picture_ptr) {\n if ((ret = av_frame_ref(pict, s->next_picture_ptr->f)) < 0)\n return ret;\n s->next_picture_ptr = NULL;\n\n *got_frame = 1;\n }\n\n return 0;\n }\n\n if (s->avctx->flags & AV_CODEC_FLAG_TRUNCATED) {\n int next;\n\n if (CONFIG_MPEG4_DECODER && s->codec_id == AV_CODEC_ID_MPEG4) {\n next = ff_mpeg4_find_frame_end(&s->parse_context, buf, buf_size);\n } else if (CONFIG_H263_DECODER && s->codec_id == AV_CODEC_ID_H263) {\n next = ff_h263_find_frame_end(&s->parse_context, buf, buf_size);\n } else if (CONFIG_H263P_DECODER && s->codec_id == AV_CODEC_ID_H263P) {\n next = ff_h263_find_frame_end(&s->parse_context, buf, buf_size);\n } else {\n av_log(s->avctx, AV_LOG_ERROR,\n \"this codec does not support truncated bitstreams\\n\");\n return AVERROR(ENOSYS);\n }\n\n if (ff_combine_frame(&s->parse_context, next, (const uint8_t **)&buf,\n &buf_size) < 0)\n return buf_size;\n }\n\nretry:\n if (s->divx_packed && s->bitstream_buffer_size) {\n int i;\n for(i=0; i < buf_size-3; i++) {\n if (buf[i]==0 && buf[i+1]==0 && buf[i+2]==1) {\n if (buf[i+3]==0xB0) {\n av_log(s->avctx, AV_LOG_WARNING, \"Discarding excessive bitstream in packed xvid\\n\");\n s->bitstream_buffer_size = 0;\n }\n break;\n }\n }\n }\n\n if (s->bitstream_buffer_size && (s->divx_packed || buf_size <= MAX_NVOP_SIZE)) // divx 5.01+/xvid frame reorder\n ret = init_get_bits8(&s->gb, s->bitstream_buffer,\n s->bitstream_buffer_size);\n else\n ret = init_get_bits8(&s->gb, buf, buf_size);\n\n s->bitstream_buffer_size = 0;\n if (ret < 0)\n return ret;\n\n if (!s->context_initialized)\n // we need the idct permutation for reading a custom matrix\n ff_mpv_idct_init(s);\n\n /* let's go :-) */\n if (CONFIG_WMV2_DECODER && s->msmpeg4_version == 5) {\n ret = ff_wmv2_decode_picture_header(s);\n } else if (CONFIG_MSMPEG4_DECODER && s->msmpeg4_version) {\n ret = ff_msmpeg4_decode_picture_header(s);\n } else if (CONFIG_MPEG4_DECODER && avctx->codec_id == AV_CODEC_ID_MPEG4) {\n if (s->avctx->extradata_size && s->picture_number == 0) {\n GetBitContext gb;\n\n if (init_get_bits8(&gb, s->avctx->extradata, s->avctx->extradata_size) >= 0 )\n ff_mpeg4_decode_picture_header(avctx->priv_data, &gb);\n }\n ret = ff_mpeg4_decode_picture_header(avctx->priv_data, &s->gb);\n } else if (CONFIG_H263I_DECODER && s->codec_id == AV_CODEC_ID_H263I) {\n ret = ff_intel_h263_decode_picture_header(s);\n } else if (CONFIG_FLV_DECODER && s->h263_flv) {\n ret = ff_flv_decode_picture_header(s);\n } else {\n ret = ff_h263_decode_picture_header(s);\n }\n\n if (ret < 0 || ret == FRAME_SKIPPED) {\n if ( s->width != avctx->coded_width\n || s->height != avctx->coded_height) {\n av_log(s->avctx, AV_LOG_WARNING, \"Reverting picture dimensions change due to header decoding failure\\n\");\n s->width = avctx->coded_width;\n s->height= avctx->coded_height;\n }\n }\n if (ret == FRAME_SKIPPED)\n return get_consumed_bytes(s, buf_size);\n\n /* skip if the header was thrashed */\n if (ret < 0) {\n av_log(s->avctx, AV_LOG_ERROR, \"header damaged\\n\");\n return ret;\n }\n\n if (!s->context_initialized) {\n avctx->pix_fmt = h263_get_format(avctx);\n if ((ret = ff_mpv_common_init(s)) < 0)\n return ret;\n }\n\n if (!s->current_picture_ptr || s->current_picture_ptr->f->data[0]) {\n int i = ff_find_unused_picture(s->avctx, s->picture, 0);\n if (i < 0)\n return i;\n s->current_picture_ptr = &s->picture[i];\n }\n\n avctx->has_b_frames = !s->low_delay;\n\n if (CONFIG_MPEG4_DECODER && avctx->codec_id == AV_CODEC_ID_MPEG4) {\n if (ff_mpeg4_workaround_bugs(avctx) == 1)\n goto retry;\n if (s->studio_profile != (s->idsp.idct == NULL))\n ff_mpv_idct_init(s);\n }\n\n /* After H.263 & MPEG-4 header decode we have the height, width,\n * and other parameters. So then we could init the picture.\n * FIXME: By the way H.263 decoder is evolving it should have\n * an H263EncContext */\n if (s->width != avctx->coded_width ||\n s->height != avctx->coded_height ||\n s->context_reinit) {\n /* H.263 could change picture size any time */\n s->context_reinit = 0;\n\n ret = ff_set_dimensions(avctx, s->width, s->height);\n if (ret < 0)\n return ret;\n\n ff_set_sar(avctx, avctx->sample_aspect_ratio);\n\n if ((ret = ff_mpv_common_frame_size_change(s)))\n return ret;\n\n if (avctx->pix_fmt != h263_get_format(avctx)) {\n av_log(avctx, AV_LOG_ERROR, \"format change not supported\\n\");\n avctx->pix_fmt = AV_PIX_FMT_NONE;\n return AVERROR_UNKNOWN;\n }\n }\n\n if (s->codec_id == AV_CODEC_ID_H263 ||\n s->codec_id == AV_CODEC_ID_H263P ||\n s->codec_id == AV_CODEC_ID_H263I)\n s->gob_index = H263_GOB_HEIGHT(s->height);\n\n // for skipping the frame\n s->current_picture.f->pict_type = s->pict_type;\n s->current_picture.f->key_frame = s->pict_type == AV_PICTURE_TYPE_I;\n\n /* skip B-frames if we don't have reference frames */\n if (!s->last_picture_ptr &&\n (s->pict_type == AV_PICTURE_TYPE_B || s->droppable))\n return get_consumed_bytes(s, buf_size);\n if ((avctx->skip_frame >= AVDISCARD_NONREF &&\n s->pict_type == AV_PICTURE_TYPE_B) ||\n (avctx->skip_frame >= AVDISCARD_NONKEY &&\n s->pict_type != AV_PICTURE_TYPE_I) ||\n avctx->skip_frame >= AVDISCARD_ALL)\n return get_consumed_bytes(s, buf_size);\n\n if (s->next_p_frame_damaged) {\n if (s->pict_type == AV_PICTURE_TYPE_B)\n return get_consumed_bytes(s, buf_size);\n else\n s->next_p_frame_damaged = 0;\n }\n\n if ((!s->no_rounding) || s->pict_type == AV_PICTURE_TYPE_B) {\n s->me.qpel_put = s->qdsp.put_qpel_pixels_tab;\n s->me.qpel_avg = s->qdsp.avg_qpel_pixels_tab;\n } else {\n s->me.qpel_put = s->qdsp.put_no_rnd_qpel_pixels_tab;\n s->me.qpel_avg = s->qdsp.avg_qpel_pixels_tab;\n }\n\n if ((ret = ff_mpv_frame_start(s, avctx)) < 0)\n return ret;\n\n if (!s->divx_packed)\n ff_thread_finish_setup(avctx);\n\n if (avctx->hwaccel) {\n ret = avctx->hwaccel->start_frame(avctx, s->gb.buffer,\n s->gb.buffer_end - s->gb.buffer);\n if (ret < 0 )\n return ret;\n }\n\n ff_mpeg_er_frame_start(s);\n\n /* the second part of the wmv2 header contains the MB skip bits which\n * are stored in current_picture->mb_type which is not available before\n * ff_mpv_frame_start() */\n if (CONFIG_WMV2_DECODER && s->msmpeg4_version == 5) {\n ret = ff_wmv2_decode_secondary_picture_header(s);\n if (ret < 0)\n return ret;\n if (ret == 1)\n goto frame_end;\n }\n\n /* decode each macroblock */\n s->mb_x = 0;\n s->mb_y = 0;\n\n slice_ret = decode_slice(s);\n while (s->mb_y < s->mb_height) {\n if (s->msmpeg4_version) {\n if (s->slice_height == 0 || s->mb_x != 0 || slice_ret < 0 ||\n (s->mb_y % s->slice_height) != 0 || get_bits_left(&s->gb) < 0)\n break;\n } else {\n int prev_x = s->mb_x, prev_y = s->mb_y;\n if (ff_h263_resync(s) < 0)\n break;\n if (prev_y * s->mb_width + prev_x < s->mb_y * s->mb_width + s->mb_x)\n s->er.error_occurred = 1;\n }\n\n if (s->msmpeg4_version < 4 && s->h263_pred)\n ff_mpeg4_clean_buffers(s);\n\n if (decode_slice(s) < 0)\n slice_ret = AVERROR_INVALIDDATA;\n }\n\n if (s->msmpeg4_version && s->msmpeg4_version < 4 &&\n s->pict_type == AV_PICTURE_TYPE_I)\n if (!CONFIG_MSMPEG4_DECODER ||\n ff_msmpeg4_decode_ext_header(s, buf_size) < 0)\n s->er.error_status_table[s->mb_num - 1] = ER_MB_ERROR;\n\n av_assert1(s->bitstream_buffer_size == 0);\nframe_end:\n ff_er_frame_end(&s->er);\n\n if (avctx->hwaccel) {\n ret = avctx->hwaccel->end_frame(avctx);\n if (ret < 0)\n return ret;\n }\n\n ff_mpv_frame_end(s);\n\n if (CONFIG_MPEG4_DECODER && avctx->codec_id == AV_CODEC_ID_MPEG4)\n ff_mpeg4_frame_end(avctx, buf, buf_size);\n\n if (!s->divx_packed && avctx->hwaccel)\n ff_thread_finish_setup(avctx);\n\n av_assert1(s->current_picture.f->pict_type == s->current_picture_ptr->f->pict_type);\n av_assert1(s->current_picture.f->pict_type == s->pict_type);\n if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay) {\n if ((ret = av_frame_ref(pict, s->current_picture_ptr->f)) < 0)\n return ret;\n ff_print_debug_info(s, s->current_picture_ptr, pict);\n ff_mpv_export_qp_table(s, pict, s->current_picture_ptr, FF_QSCALE_TYPE_MPEG1);\n } else if (s->last_picture_ptr) {\n if ((ret = av_frame_ref(pict, s->last_picture_ptr->f)) < 0)\n return ret;\n ff_print_debug_info(s, s->last_picture_ptr, pict);\n ff_mpv_export_qp_table(s, pict, s->last_picture_ptr, FF_QSCALE_TYPE_MPEG1);\n }\n\n if (s->last_picture_ptr || s->low_delay) {\n if ( pict->format == AV_PIX_FMT_YUV420P\n && (s->codec_tag == AV_RL32(\"GEOV\") || s->codec_tag == AV_RL32(\"GEOX\"))) {\n int x, y, p;\n av_frame_make_writable(pict);\n for (p=0; p<3; p++) {\n int w = AV_CEIL_RSHIFT(pict-> width, !!p);\n int h = AV_CEIL_RSHIFT(pict->height, !!p);\n int linesize = pict->linesize[p];\n for (y=0; y<(h>>1); y++)\n for (x=0; xdata[p][x + y*linesize],\n pict->data[p][x + (h-1-y)*linesize]);\n }\n }\n *got_frame = 1;\n }\n\n if (slice_ret < 0 && (avctx->err_recognition & AV_EF_EXPLODE))\n return slice_ret;\n else\n return get_consumed_bytes(s, buf_size);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-617'], 'message': 'avcodec/mpeg4videodec: Remove use of FF_PROFILE_MPEG4_SIMPLE_STUDIO as indicator of studio profile\n\nThe profile field is changed by code inside and outside the decoder,\nits not a reliable indicator of the internal codec state.\nMaintaining it consistency with studio_profile is messy.\nIts easier to just avoid it and use only studio_profile\n\nFixes: assertion failure\nFixes: ffmpeg_crash_9.avi\n\nFound-by: Thuan Pham, Marcel B\u00f6hme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart\nSigned-off-by: Michael Niedermayer '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static NO_INLINE JsVar *jspGetNamedFieldInParents(JsVar *object, const char* name, bool returnName) {\n // Now look in prototypes\n JsVar * child = jspeiFindChildFromStringInParents(object, name);\n\n /* Check for builtins via separate function\n * This way we save on RAM for built-ins because everything comes out of program code */\n if (!child) {\n child = jswFindBuiltInFunction(object, name);\n }\n\n /* We didn't get here if we found a child in the object itself, so\n * if we're here then we probably have the wrong name - so for example\n * with `a.b = c;` could end up setting `a.prototype.b` (bug #360)\n *\n * Also we might have got a built-in, which wouldn't have a name on it\n * anyway - so in both cases, strip the name if it is there, and create\n * a new name that references the object we actually requested the\n * member from..\n */\n if (child && returnName) {\n // Get rid of existing name\n if (jsvIsName(child)) {\n JsVar *t = jsvGetValueOfName(child);\n jsvUnLock(child);\n child = t;\n }\n // create a new name\n JsVar *nameVar = jsvNewFromString(name);\n JsVar *newChild = jsvCreateNewChild(object, nameVar, child);\n jsvUnLock2(nameVar, child);\n child = newChild;\n }\n\n // If not found and is the prototype, create it\n if (!child) {\n if (jsvIsFunction(object) && strcmp(name, JSPARSE_PROTOTYPE_VAR)==0) {\n // prototype is supposed to be an object\n JsVar *proto = jsvNewObject();\n // make sure it has a 'constructor' variable that points to the object it was part of\n jsvObjectSetChild(proto, JSPARSE_CONSTRUCTOR_VAR, object);\n child = jsvAddNamedChild(object, proto, JSPARSE_PROTOTYPE_VAR);\n jspEnsureIsPrototype(object, child);\n jsvUnLock(proto);\n } else if (strcmp(name, JSPARSE_INHERITS_VAR)==0) {\n const char *objName = jswGetBasicObjectName(object);\n if (objName) {\n child = jspNewPrototype(objName);\n }\n }\n }\n\n return child;\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, bool* out) {\n if (v == Py_True) {\n *out = true;\n } else if (v == Py_False) {\n *out = false;\n } else if (PyIsInstance(v, &PyBoolArrType_Type)) { // NumPy\n *out = PyObject_IsTrue(v);\n } else {\n return ErrorMixedTypes;\n }\n return nullptr;\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: static int ensure_valid_ownership(const char *path)\n{\n\tstruct safe_directory_data data = { .path = path };\n\n\tif (!git_env_bool(\"GIT_TEST_ASSUME_DIFFERENT_OWNER\", 0) &&\n\t is_path_owned_by_current_user(path))\n\t\treturn 1;\n\n\tread_very_early_config(safe_directory_cb, &data);\n\n\treturn data.is_safe;\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_POLICY_Unmarshal(TPMI_RH_HIERARCHY_POLICY *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 {\n\t\t BOOL isNotHP = (*target < TPM_RH_ACT_0) || (*target > TPM_RH_ACT_F);\n\t\t if (isNotHP) {\n\t\t rc = TPM_RC_VALUE;\n\t\t }\n\t }\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_OBJECT_Unmarshal(TPMI_ALG_SYM_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_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 case TPM_ALG_TDES:\n#endif\t\t\t// iibtpms added end\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_RH_ENDORSEMENT_Unmarshal(TPMI_RH_ENDORSEMENT *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n{\n TPM_RC rc = TPM_RC_SUCCESS;\n\n if (rc == TPM_RC_SUCCESS) {\n\trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n }\n if (rc == TPM_RC_SUCCESS) {\n\tswitch (*target) {\n\t case TPM_RH_ENDORSEMENT:\n\t break;\n\t case TPM_RH_NULL:\n\t if (allowNull) {\n\t\tbreak;\n\t }\n\t default:\n\t rc = TPM_RC_VALUE;\n\t}\n }\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal\n\nRestore the original value of the memory location where data from\na stream was unmarshalled and the unmarshalled value was found to\nbe illegal. The goal is to not keep illegal values in memory.\n\nSigned-off-by: Stefan Berger '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TPM_ECC_CURVE_Unmarshal(TPM_ECC_CURVE *target, BYTE **buffer, INT32 *size)\n{\n TPM_RC rc = TPM_RC_SUCCESS;\n\n if (rc == TPM_RC_SUCCESS) {\n\trc = UINT16_Unmarshal(target, buffer, size);\n }\n if (rc == TPM_RC_SUCCESS) {\n\tswitch (*target) {\n\t case TPM_ECC_NONE:\n\t case TPM_ECC_NIST_P192:\n\t case TPM_ECC_NIST_P224:\n\t case TPM_ECC_NIST_P256:\n\t case TPM_ECC_NIST_P384:\n\t case TPM_ECC_NIST_P521:\n\t case TPM_ECC_BN_P256:\n\t case TPM_ECC_BN_P638:\n\t case TPM_ECC_SM2_P256:\n\t break;\n\t default:\n\t rc = TPM_RC_CURVE;\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_ENTITY_Unmarshal(TPMI_DH_ENTITY *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 isNotOwner = *target != TPM_RH_OWNER;\n\tBOOL isNotEndorsement = *target != TPM_RH_ENDORSEMENT;\n\tBOOL isNotPlatform = *target != TPM_RH_PLATFORM;\n\tBOOL isNotLockout = *target != TPM_RH_LOCKOUT;\n\tBOOL isNotTransient = (*target < TRANSIENT_FIRST) || (*target > TRANSIENT_LAST);\n\tBOOL isNotPersistent = (*target < PERSISTENT_FIRST) || (*target > PERSISTENT_LAST);\n\tBOOL isNotNv = (*target < NV_INDEX_FIRST) || (*target > NV_INDEX_LAST);\n\tBOOL isNotPcr = (*target > PCR_LAST);\n\tBOOL isNotAuth = (*target < TPM_RH_AUTH_00) || (*target > TPM_RH_AUTH_FF);\n\tBOOL isNotLegalNull = (*target != TPM_RH_NULL) || !allowNull;\n\tif (isNotOwner &&\n\t isNotEndorsement &&\n\t isNotPlatform &&\n\t isNotLockout &&\n\t isNotTransient &&\n\t isNotPersistent &&\n\t isNotNv &&\n\t isNotPcr &&\n\t isNotAuth &&\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: TPMI_ALG_KDF_Unmarshal(TPMI_ALG_KDF *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_MGF1\n\t case TPM_ALG_MGF1:\n#endif\n#if ALG_KDF1_SP800_56A\n\t case TPM_ALG_KDF1_SP800_56A:\t\n#endif\n#if ALG_KDF2\n\t case TPM_ALG_KDF2:\t\t\t\n#endif\n#if ALG_KDF1_SP800_108\n\t case TPM_ALG_KDF1_SP800_108:\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_KDF;\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_CONTEXT_Unmarshal(TPMI_DH_CONTEXT *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\tBOOL isNotPolicySession = (*target < POLICY_SESSION_FIRST) || (*target > POLICY_SESSION_LAST);\n\tBOOL isNotTransient = (*target < TRANSIENT_FIRST) || (*target > TRANSIENT_LAST);\n\tif (isNotHmacSession &&\n\t isNotPolicySession &&\n\t isNotTransient) {\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: void Compute(OpKernelContext* context) override {\n // boxes: [batch_size, num_anchors, q, 4]\n const Tensor& boxes = context->input(0);\n // scores: [batch_size, num_anchors, num_classes]\n const Tensor& scores = context->input(1);\n OP_REQUIRES(\n context, (boxes.dim_size(0) == scores.dim_size(0)),\n errors::InvalidArgument(\"boxes and scores must have same batch size\"));\n\n // max_output_size: scalar\n const Tensor& max_output_size = context->input(2);\n OP_REQUIRES(\n context, TensorShapeUtils::IsScalar(max_output_size.shape()),\n errors::InvalidArgument(\"max_size_per_class must be 0-D, got shape \",\n max_output_size.shape().DebugString()));\n const int max_size_per_class = max_output_size.scalar()();\n // max_total_size: scalar\n const Tensor& max_total_size = context->input(3);\n OP_REQUIRES(\n context, TensorShapeUtils::IsScalar(max_total_size.shape()),\n errors::InvalidArgument(\"max_total_size must be 0-D, got shape \",\n max_total_size.shape().DebugString()));\n const int max_total_size_per_batch = max_total_size.scalar()();\n OP_REQUIRES(context, max_total_size_per_batch > 0,\n errors::InvalidArgument(\"max_total_size must be > 0\"));\n // Throw warning when `max_total_size` is too large as it may cause OOM.\n if (max_total_size_per_batch > pow(10, 6)) {\n LOG(WARNING) << \"Detected a large value for `max_total_size`. This may \"\n << \"cause OOM error. (max_total_size: \"\n << max_total_size.scalar()() << \")\";\n }\n // iou_threshold: scalar\n const Tensor& iou_threshold = context->input(4);\n OP_REQUIRES(context, TensorShapeUtils::IsScalar(iou_threshold.shape()),\n errors::InvalidArgument(\"iou_threshold must be 0-D, got shape \",\n iou_threshold.shape().DebugString()));\n const float iou_threshold_val = iou_threshold.scalar()();\n\n // score_threshold: scalar\n const Tensor& score_threshold = context->input(5);\n OP_REQUIRES(\n context, TensorShapeUtils::IsScalar(score_threshold.shape()),\n errors::InvalidArgument(\"score_threshold must be 0-D, got shape \",\n score_threshold.shape().DebugString()));\n const float score_threshold_val = score_threshold.scalar()();\n\n OP_REQUIRES(context, iou_threshold_val >= 0 && iou_threshold_val <= 1,\n errors::InvalidArgument(\"iou_threshold must be in [0, 1]\"));\n int num_boxes = 0;\n const int num_classes = scores.dim_size(2);\n ParseAndCheckCombinedNMSBoxSizes(context, boxes, &num_boxes, num_classes);\n CheckCombinedNMSScoreSizes(context, num_boxes, scores);\n\n if (!context->status().ok()) {\n return;\n }\n BatchedNonMaxSuppressionOp(context, boxes, scores, num_boxes,\n max_size_per_class, max_total_size_per_batch,\n score_threshold_val, iou_threshold_val,\n pad_per_class_, clip_boxes_);\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369', 'CWE-681'], 'message': 'Prevent overflow due to integer conversion to unsigned.\n\nPiperOrigin-RevId: 387738045\nChange-Id: Id7e95bc07e02df1c66b72bd09f389608c87bdebe'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int x509_crt_verify_child(\n mbedtls_x509_crt *child, mbedtls_x509_crt *parent,\n mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl,\n const mbedtls_x509_crt_profile *profile,\n int path_cnt, int self_cnt, uint32_t *flags,\n int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),\n void *p_vrfy )\n{\n int ret;\n uint32_t parent_flags = 0;\n unsigned char hash[MBEDTLS_MD_MAX_SIZE];\n mbedtls_x509_crt *grandparent;\n const mbedtls_md_info_t *md_info;\n\n /* Counting intermediate self signed certificates */\n if( ( path_cnt != 0 ) && x509_name_cmp( &child->issuer, &child->subject ) == 0 )\n self_cnt++;\n\n /* path_cnt is 0 for the first intermediate CA */\n if( 1 + path_cnt > MBEDTLS_X509_MAX_INTERMEDIATE_CA )\n {\n *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;\n return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED );\n }\n\n if( mbedtls_x509_time_is_past( &child->valid_to ) )\n *flags |= MBEDTLS_X509_BADCERT_EXPIRED;\n\n if( mbedtls_x509_time_is_future( &child->valid_from ) )\n *flags |= MBEDTLS_X509_BADCERT_FUTURE;\n\n if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 )\n *flags |= MBEDTLS_X509_BADCERT_BAD_MD;\n\n if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 )\n *flags |= MBEDTLS_X509_BADCERT_BAD_PK;\n\n md_info = mbedtls_md_info_from_type( child->sig_md );\n if( md_info == NULL )\n {\n /*\n * Cannot check 'unknown' hash\n */\n *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;\n }\n else\n {\n mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash );\n\n if( x509_profile_check_key( profile, child->sig_pk, &parent->pk ) != 0 )\n *flags |= MBEDTLS_X509_BADCERT_BAD_KEY;\n\n if( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent->pk,\n child->sig_md, hash, mbedtls_md_get_size( md_info ),\n child->sig.p, child->sig.len ) != 0 )\n {\n *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;\n }\n }\n\n#if defined(MBEDTLS_X509_CRL_PARSE_C)\n /* Check trusted CA's CRL for the given crt */\n *flags |= x509_crt_verifycrl(child, parent, ca_crl, profile );\n#endif\n\n /* Look for a grandparent in trusted CAs */\n for( grandparent = trust_ca;\n grandparent != NULL;\n grandparent = grandparent->next )\n {\n if( x509_crt_check_parent( parent, grandparent,\n 0, path_cnt == 0 ) == 0 )\n break;\n }\n\n if( grandparent != NULL )\n {\n ret = x509_crt_verify_top( parent, grandparent, ca_crl, profile,\n path_cnt + 1, self_cnt, &parent_flags, f_vrfy, p_vrfy );\n if( ret != 0 )\n return( ret );\n }\n else\n {\n /* Look for a grandparent upwards the chain */\n for( grandparent = parent->next;\n grandparent != NULL;\n grandparent = grandparent->next )\n {\n /* +2 because the current step is not yet accounted for\n * and because max_pathlen is one higher than it should be.\n * Also self signed certificates do not count to the limit. */\n if( grandparent->max_pathlen > 0 &&\n grandparent->max_pathlen < 2 + path_cnt - self_cnt )\n {\n continue;\n }\n\n if( x509_crt_check_parent( parent, grandparent,\n 0, path_cnt == 0 ) == 0 )\n break;\n }\n\n /* Is our parent part of the chain or at the top? */\n if( grandparent != NULL )\n {\n ret = x509_crt_verify_child( parent, grandparent, trust_ca, ca_crl,\n profile, path_cnt + 1, self_cnt, &parent_flags,\n f_vrfy, p_vrfy );\n if( ret != 0 )\n return( ret );\n }\n else\n {\n ret = x509_crt_verify_top( parent, trust_ca, ca_crl, profile,\n path_cnt + 1, self_cnt, &parent_flags,\n f_vrfy, p_vrfy );\n if( ret != 0 )\n return( ret );\n }\n }\n\n /* child is verified to be a child of the parent, call verify callback */\n if( NULL != f_vrfy )\n if( ( ret = f_vrfy( p_vrfy, child, path_cnt, flags ) ) != 0 )\n return( ret );\n\n *flags |= parent_flags;\n\n return( 0 );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'Only return VERIFY_FAILED from a single point\n\nEverything else is a fatal error. Also improve documentation about that for\nthe vrfy callback.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ikev2_auth_print(netdissect_options *ndo, u_char tpay,\n\t\tconst struct isakmp_gen *ext,\n\t\tu_int item_len _U_, const u_char *ep,\n\t\tuint32_t phase _U_, uint32_t doi _U_,\n\t\tuint32_t proto _U_, int depth _U_)\n{\n\tstruct ikev2_auth a;\n\tconst char *v2_auth[]={ \"invalid\", \"rsasig\",\n\t\t\t\t\"shared-secret\", \"dsssig\" };\n\tconst u_char *authdata = (const u_char*)ext + sizeof(a);\n\tunsigned int len;\n\n\tND_TCHECK(*ext);\n\tUNALIGNED_MEMCPY(&a, ext, sizeof(a));\n\tikev2_pay_print(ndo, NPSTR(tpay), a.h.critical);\n\tlen = ntohs(a.h.len);\n\n\t/*\n\t * Our caller has ensured that the length is >= 4.\n\t */\n\tND_PRINT((ndo,\" len=%u method=%s\", len-4,\n\t\t STR_OR_ID(a.auth_method, v2_auth)));\n\tif (len > 4) {\n\t\tif (ndo->ndo_vflag > 1) {\n\t\t\tND_PRINT((ndo, \" authdata=(\"));\n\t\t\tif (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a)))\n\t\t\t\tgoto trunc;\n\t\t\tND_PRINT((ndo, \") \"));\n\t\t} else if (ndo->ndo_vflag) {\n\t\t\tif (!ike_show_somedata(ndo, authdata, ep))\n\t\t\t\tgoto trunc;\n\t\t}\n\t}\n\n\treturn (const u_char *)ext + len;\ntrunc:\n\tND_PRINT((ndo,\" [|%s]\", NPSTR(tpay)));\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: 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 if (!TrustedPrimitives::IsOutsideEnclave(sgx_params, sizeof(SgxParams))) {\n TrustedPrimitives::BestEffortAbort(\n \"UntrustedCall: sgx_param should be in untrusted memory\");\n }\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 if (!TrustedPrimitives::IsOutsideEnclave(sgx_params->input,\n sgx_params->input_size)) {\n TrustedPrimitives::BestEffortAbort(\n \"UntrustedCall: sgx_param input should be in untrusted memory\");\n }\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 (!TrustedPrimitives::IsOutsideEnclave(sgx_params->output,\n sgx_params->output_size)) {\n TrustedPrimitives::BestEffortAbort(\n \"UntrustedCall: sgx_param output should be in untrusted memory\");\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-200', 'CWE-668'], 'message': 'Store untrusted input to enclave variable\n\nThe untrusted input pointer should be stored to trusted variable before\nchecking to avoid unexpected modifications after checking.\n\nPiperOrigin-RevId: 362553830\nChange-Id: I743f9bd3487de60269e247d74f2188f2ffc06d01'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int sanitize_ptr_alu(struct bpf_verifier_env *env,\n\t\t\t struct bpf_insn *insn,\n\t\t\t const struct bpf_reg_state *ptr_reg,\n\t\t\t const struct bpf_reg_state *off_reg,\n\t\t\t struct bpf_reg_state *dst_reg,\n\t\t\t struct bpf_sanitize_info *info,\n\t\t\t const bool commit_window)\n{\n\tstruct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;\n\tstruct bpf_verifier_state *vstate = env->cur_state;\n\tbool off_is_imm = tnum_is_const(off_reg->var_off);\n\tbool off_is_neg = off_reg->smin_value < 0;\n\tbool ptr_is_dst_reg = ptr_reg == dst_reg;\n\tu8 opcode = BPF_OP(insn->code);\n\tu32 alu_state, alu_limit;\n\tstruct bpf_reg_state tmp;\n\tbool ret;\n\tint err;\n\n\tif (can_skip_alu_sanitation(env, insn))\n\t\treturn 0;\n\n\t/* We already marked aux for masking from non-speculative\n\t * paths, thus we got here in the first place. We only care\n\t * to explore bad access from here.\n\t */\n\tif (vstate->speculative)\n\t\tgoto do_sim;\n\n\tif (!commit_window) {\n\t\tif (!tnum_is_const(off_reg->var_off) &&\n\t\t (off_reg->smin_value < 0) != (off_reg->smax_value < 0))\n\t\t\treturn REASON_BOUNDS;\n\n\t\tinfo->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||\n\t\t\t\t (opcode == BPF_SUB && !off_is_neg);\n\t}\n\n\terr = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);\n\tif (err < 0)\n\t\treturn err;\n\n\tif (commit_window) {\n\t\t/* In commit phase we narrow the masking window based on\n\t\t * the observed pointer move after the simulated operation.\n\t\t */\n\t\talu_state = info->aux.alu_state;\n\t\talu_limit = abs(info->aux.alu_limit - alu_limit);\n\t} else {\n\t\talu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;\n\t\talu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;\n\t\talu_state |= ptr_is_dst_reg ?\n\t\t\t BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;\n\t}\n\n\terr = update_alu_sanitation_state(aux, alu_state, alu_limit);\n\tif (err < 0)\n\t\treturn err;\ndo_sim:\n\t/* If we're in commit phase, we're done here given we already\n\t * pushed the truncated dst_reg into the speculative verification\n\t * stack.\n\t *\n\t * Also, when register is a known constant, we rewrite register-based\n\t * operation to immediate-based, and thus do not need masking (and as\n\t * a consequence, do not need to simulate the zero-truncation either).\n\t */\n\tif (commit_window || off_is_imm)\n\t\treturn 0;\n\n\t/* Simulate and find potential out-of-bounds access under\n\t * speculative execution from truncation as a result of\n\t * masking when off was not within expected range. If off\n\t * sits in dst, then we temporarily need to move ptr there\n\t * to simulate dst (== 0) +/-= ptr. Needed, for example,\n\t * for cases where we use K-based arithmetic in one direction\n\t * and truncated reg-based in the other in order to explore\n\t * bad access.\n\t */\n\tif (!ptr_is_dst_reg) {\n\t\ttmp = *dst_reg;\n\t\t*dst_reg = *ptr_reg;\n\t}\n\tret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);\n\tif (!ptr_is_dst_reg && ret)\n\t\t*dst_reg = tmp;\n\treturn !ret ? REASON_STACK : 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-203'], 'message': 'bpf: Fix leakage under speculation on mispredicted branches\n\nThe verifier only enumerates valid control-flow paths and skips paths that\nare unreachable in the non-speculative domain. And so it can miss issues\nunder speculative execution on mispredicted branches.\n\nFor example, a type confusion has been demonstrated with the following\ncrafted program:\n\n // r0 = pointer to a map array entry\n // r6 = pointer to readable stack slot\n // r9 = scalar controlled by attacker\n 1: r0 = *(u64 *)(r0) // cache miss\n 2: if r0 != 0x0 goto line 4\n 3: r6 = r9\n 4: if r0 != 0x1 goto line 6\n 5: r9 = *(u8 *)(r6)\n 6: // leak r9\n\nSince line 3 runs iff r0 == 0 and line 5 runs iff r0 == 1, the verifier\nconcludes that the pointer dereference on line 5 is safe. But: if the\nattacker trains both the branches to fall-through, such that the following\nis speculatively executed ...\n\n r6 = r9\n r9 = *(u8 *)(r6)\n // leak r9\n\n... then the program will dereference an attacker-controlled value and could\nleak its content under speculative execution via side-channel. This requires\nto mistrain the branch predictor, which can be rather tricky, because the\nbranches are mutually exclusive. However such training can be done at\ncongruent addresses in user space using different branches that are not\nmutually exclusive. That is, by training branches in user space ...\n\n A: if r0 != 0x0 goto line C\n B: ...\n C: if r0 != 0x0 goto line D\n D: ...\n\n... such that addresses A and C collide to the same CPU branch prediction\nentries in the PHT (pattern history table) as those of the BPF program's\nlines 2 and 4, respectively. A non-privileged attacker could simply brute\nforce such collisions in the PHT until observing the attack succeeding.\n\nAlternative methods to mistrain the branch predictor are also possible that\navoid brute forcing the collisions in the PHT. A reliable attack has been\ndemonstrated, for example, using the following crafted program:\n\n // r0 = pointer to a [control] map array entry\n // r7 = *(u64 *)(r0 + 0), training/attack phase\n // r8 = *(u64 *)(r0 + 8), oob address\n // [...]\n // r0 = pointer to a [data] map array entry\n 1: if r7 == 0x3 goto line 3\n 2: r8 = r0\n // crafted sequence of conditional jumps to separate the conditional\n // branch in line 193 from the current execution flow\n 3: if r0 != 0x0 goto line 5\n 4: if r0 == 0x0 goto exit\n 5: if r0 != 0x0 goto line 7\n 6: if r0 == 0x0 goto exit\n [...]\n 187: if r0 != 0x0 goto line 189\n 188: if r0 == 0x0 goto exit\n // load any slowly-loaded value (due to cache miss in phase 3) ...\n 189: r3 = *(u64 *)(r0 + 0x1200)\n // ... and turn it into known zero for verifier, while preserving slowly-\n // loaded dependency when executing:\n 190: r3 &= 1\n 191: r3 &= 2\n // speculatively bypassed phase dependency\n 192: r7 += r3\n 193: if r7 == 0x3 goto exit\n 194: r4 = *(u8 *)(r8 + 0)\n // leak r4\n\nAs can be seen, in training phase (phase != 0x3), the condition in line 1\nturns into false and therefore r8 with the oob address is overridden with\nthe valid map value address, which in line 194 we can read out without\nissues. However, in attack phase, line 2 is skipped, and due to the cache\nmiss in line 189 where the map value is (zeroed and later) added to the\nphase register, the condition in line 193 takes the fall-through path due\nto prior branch predictor training, where under speculation, it'll load the\nbyte at oob address r8 (unknown scalar type at that point) which could then\nbe leaked via side-channel.\n\nOne way to mitigate these is to 'branch off' an unreachable path, meaning,\nthe current verification path keeps following the is_branch_taken() path\nand we push the other branch to the verification stack. Given this is\nunreachable from the non-speculative domain, this branch's vstate is\nexplicitly marked as speculative. This is needed for two reasons: i) if\nthis path is solely seen from speculative execution, then we later on still\nwant the dead code elimination to kick in in order to sanitize these\ninstructions with jmp-1s, and ii) to ensure that paths walked in the\nnon-speculative domain are not pruned from earlier walks of paths walked in\nthe speculative domain. Additionally, for robustness, we mark the registers\nwhich have been part of the conditional as unknown in the speculative path\ngiven there should be no assumptions made on their content.\n\nThe fix in here mitigates type confusion attacks described earlier due to\ni) all code paths in the BPF program being explored and ii) existing\nverifier logic already ensuring that given memory access instruction\nreferences one specific data structure.\n\nAn alternative to this fix that has also been looked at in this scope was to\nmark aux->alu_state at the jump instruction with a BPF_JMP_TAKEN state as\nwell as direction encoding (always-goto, always-fallthrough, unknown), such\nthat mixing of different always-* directions themselves as well as mixing of\nalways-* with unknown directions would cause a program rejection by the\nverifier, e.g. programs with constructs like 'if ([...]) { x = 0; } else\n{ x = 1; }' with subsequent 'if (x == 1) { [...] }'. For unprivileged, this\nwould result in only single direction always-* taken paths, and unknown taken\npaths being allowed, such that the former could be patched from a conditional\njump to an unconditional jump (ja). Compared to this approach here, it would\nhave two downsides: i) valid programs that otherwise are not performing any\npointer arithmetic, etc, would potentially be rejected/broken, and ii) we are\nrequired to turn off path pruning for unprivileged, where both can be avoided\nin this work through pushing the invalid branch to the verification stack.\n\nThe issue was originally discovered by Adam and Ofek, and later independently\ndiscovered and reported as a result of Benedict and Piotr's research work.\n\nFixes: b2157399cc98 (\"bpf: prevent out-of-bounds speculation\")\nReported-by: Adam Morrison \nReported-by: Ofek Kirzner \nReported-by: Benedict Schlueter \nReported-by: Piotr Krysiuk \nSigned-off-by: Daniel Borkmann \nReviewed-by: John Fastabend \nReviewed-by: Benedict Schlueter \nReviewed-by: Piotr Krysiuk \nAcked-by: Alexei Starovoitov '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int fr_add_pvc(struct net_device *frad, unsigned int dlci, int type)\n{\n\thdlc_device *hdlc = dev_to_hdlc(frad);\n\tpvc_device *pvc;\n\tstruct net_device *dev;\n\tint used;\n\n\tif ((pvc = add_pvc(frad, dlci)) == NULL) {\n\t\tnetdev_warn(frad, \"Memory squeeze on fr_add_pvc()\\n\");\n\t\treturn -ENOBUFS;\n\t}\n\n\tif (*get_dev_p(pvc, type))\n\t\treturn -EEXIST;\n\n\tused = pvc_is_used(pvc);\n\n\tif (type == ARPHRD_ETHER)\n\t\tdev = alloc_netdev(0, \"pvceth%d\", ether_setup);\n\telse\n\t\tdev = alloc_netdev(0, \"pvc%d\", pvc_setup);\n\n\tif (!dev) {\n\t\tnetdev_warn(frad, \"Memory squeeze on fr_pvc()\\n\");\n\t\tdelete_unused_pvcs(hdlc);\n\t\treturn -ENOBUFS;\n\t}\n\n\tif (type == ARPHRD_ETHER)\n\t\trandom_ether_addr(dev->dev_addr);\n\telse {\n\t\t*(__be16*)dev->dev_addr = htons(dlci);\n\t\tdlci_to_q922(dev->broadcast, dlci);\n\t}\n\tdev->netdev_ops = &pvc_ops;\n\tdev->mtu = HDLC_MAX_MTU;\n\tdev->tx_queue_len = 0;\n\tdev->ml_priv = pvc;\n\n\tif (register_netdevice(dev) != 0) {\n\t\tfree_netdev(dev);\n\t\tdelete_unused_pvcs(hdlc);\n\t\treturn -EIO;\n\t}\n\n\tdev->destructor = free_netdev;\n\t*get_dev_p(pvc, type) = dev;\n\tif (!used) {\n\t\tstate(hdlc)->dce_changed = 1;\n\t\tstate(hdlc)->dce_pvc_count++;\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-264'], 'message': 'net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared\n\nAfter the last patch, We are left in a state in which only drivers calling\nether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real\nhardware call ether_setup for their net_devices and don't hold any state in\ntheir skbs. There are a handful of drivers that violate this assumption of\ncourse, and need to be fixed up. This patch identifies those drivers, and marks\nthem as not being able to support the safe transmission of skbs by clearning the\nIFF_TX_SKB_SHARING flag in priv_flags\n\nSigned-off-by: Neil Horman \nCC: Karsten Keil \nCC: \"David S. Miller\" \nCC: Jay Vosburgh \nCC: Andy Gospodarek \nCC: Patrick McHardy \nCC: Krzysztof Halasa \nCC: \"John W. Linville\" \nCC: Greg Kroah-Hartman \nCC: Marcel Holtmann \nCC: Johannes Berg \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void bond_setup(struct net_device *bond_dev)\n{\n\tstruct bonding *bond = netdev_priv(bond_dev);\n\n\t/* initialize rwlocks */\n\trwlock_init(&bond->lock);\n\trwlock_init(&bond->curr_slave_lock);\n\n\tbond->params = bonding_defaults;\n\n\t/* Initialize pointers */\n\tbond->dev = bond_dev;\n\tINIT_LIST_HEAD(&bond->vlan_list);\n\n\t/* Initialize the device entry points */\n\tether_setup(bond_dev);\n\tbond_dev->netdev_ops = &bond_netdev_ops;\n\tbond_dev->ethtool_ops = &bond_ethtool_ops;\n\tbond_set_mode_ops(bond, bond->params.mode);\n\n\tbond_dev->destructor = bond_destructor;\n\n\t/* Initialize the device options */\n\tbond_dev->tx_queue_len = 0;\n\tbond_dev->flags |= IFF_MASTER|IFF_MULTICAST;\n\tbond_dev->priv_flags |= IFF_BONDING;\n\tbond_dev->priv_flags &= ~IFF_XMIT_DST_RELEASE;\n\n\t/* At first, we block adding VLANs. That's the only way to\n\t * prevent problems that occur when adding VLANs over an\n\t * empty bond. The block will be removed once non-challenged\n\t * slaves are enslaved.\n\t */\n\tbond_dev->features |= NETIF_F_VLAN_CHALLENGED;\n\n\t/* don't acquire bond device's netif_tx_lock when\n\t * transmitting */\n\tbond_dev->features |= NETIF_F_LLTX;\n\n\t/* By default, we declare the bond to be fully\n\t * VLAN hardware accelerated capable. Special\n\t * care is taken in the various xmit functions\n\t * when there are slaves that are not hw accel\n\t * capable\n\t */\n\n\tbond_dev->hw_features = BOND_VLAN_FEATURES |\n\t\t\t\tNETIF_F_HW_VLAN_TX |\n\t\t\t\tNETIF_F_HW_VLAN_RX |\n\t\t\t\tNETIF_F_HW_VLAN_FILTER;\n\n\tbond_dev->hw_features &= ~(NETIF_F_ALL_CSUM & ~NETIF_F_NO_CSUM);\n\tbond_dev->features |= bond_dev->hw_features;\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_rqst(struct TCP_Server_Info *server, struct smb_rqst *rqst)\n{\n\tint rc;\n\tstruct kvec *iov = rqst->rq_iov;\n\tint n_vec = rqst->rq_nvec;\n\tunsigned int smb_buf_length = get_rfc1002_length(iov[0].iov_base);\n\tunsigned int i;\n\tsize_t total_len = 0, sent;\n\tstruct socket *ssocket = server->ssocket;\n\tint val = 1;\n\n\tcFYI(1, \"Sending smb: smb_len=%u\", smb_buf_length);\n\tdump_smb(iov[0].iov_base, iov[0].iov_len);\n\n\t/* cork the socket */\n\tkernel_setsockopt(ssocket, SOL_TCP, TCP_CORK,\n\t\t\t\t(char *)&val, sizeof(val));\n\n\trc = smb_send_kvec(server, iov, n_vec, &sent);\n\tif (rc < 0)\n\t\tgoto uncork;\n\n\ttotal_len += sent;\n\n\t/* now walk the page array and send each page in it */\n\tfor (i = 0; i < rqst->rq_npages; i++) {\n\t\tstruct kvec p_iov;\n\n\t\tcifs_rqst_page_to_kvec(rqst, i, &p_iov);\n\t\trc = smb_send_kvec(server, &p_iov, 1, &sent);\n\t\tkunmap(rqst->rq_pages[i]);\n\t\tif (rc < 0)\n\t\t\tbreak;\n\n\t\ttotal_len += sent;\n\t}\n\nuncork:\n\t/* uncork it */\n\tval = 0;\n\tkernel_setsockopt(ssocket, SOL_TCP, TCP_CORK,\n\t\t\t\t(char *)&val, sizeof(val));\n\n\tif ((total_len > 0) && (total_len != smb_buf_length + 4)) {\n\t\tcFYI(1, \"partial send (wanted=%u sent=%zu): terminating \"\n\t\t\t\"session\", smb_buf_length + 4, total_len);\n\t\t/*\n\t\t * If we have only sent part of an SMB then the next SMB could\n\t\t * be taken as the remainder of this one. We need to kill the\n\t\t * socket so the server throws away the partial SMB\n\t\t */\n\t\tserver->tcpStatus = CifsNeedReconnect;\n\t}\n\n\tif (rc < 0 && rc != -EINTR)\n\t\tcERROR(1, \"Error %d sending data on socket to server\", rc);\n\telse\n\t\trc = 0;\n\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: inline void AveragePool(const PoolParams& params,\n const RuntimeShape& input_shape, const int8* input_data,\n const RuntimeShape& output_shape, int8* output_data) {\n ruy::profiler::ScopeLabel label(\"AveragePool/8bitWith32bitAccumulator\");\n\n // Here, and in other pooling ops, in order to maintain locality of reference,\n // to minimize some recalculations, and to load into NEON vector registers, we\n // use an inner loop down the depth. Since depths can be large and hence we\n // would need arbitrarily large temporary storage, we divide the work up into\n // depth tranches just within the batch loop.\n static constexpr int kPoolingAccTrancheSize = 256;\n\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\n int32 acc[kPoolingAccTrancheSize];\n for (int batch = 0; batch < batches; ++batch) {\n // We proceed through the depth in tranches (see comment above). The\n // depth_base is the depth at the beginning of the tranche. The\n // tranche_depth is the depth dimension of the tranche.\n for (int depth_base = 0; depth_base < depth;\n depth_base += kPoolingAccTrancheSize) {\n const int tranche_depth =\n std::min(depth - depth_base, kPoolingAccTrancheSize);\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 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 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 const int filter_count =\n (filter_x_end - filter_x_start) * (filter_y_end - filter_y_start);\n memset(acc, 0, tranche_depth * sizeof(acc[0]));\n const int8* input_ptr =\n input_data + depth_base +\n depth * (in_x_origin +\n input_width * (in_y_origin + input_height * batch));\n for (int fy = filter_y_start; fy < filter_y_end; fy++) {\n const int8* input_row_ptr =\n input_ptr + depth * (fy * input_width + filter_x_start);\n for (int fx = filter_x_start; fx < filter_x_end; fx++) {\n const int8* input_channel_ptr = input_row_ptr;\n int channel = 0;\n#ifdef USE_NEON\n for (; channel <= tranche_depth - 16; channel += 16) {\n int16x4_t acc_reg[4];\n int8x16_t input_reg = vld1q_s8(input_channel_ptr);\n input_channel_ptr += 16;\n acc_reg[0] = vget_low_s16(vmovl_s8(vget_low_s8(input_reg)));\n acc_reg[1] = vget_high_s16(vmovl_s8(vget_low_s8(input_reg)));\n acc_reg[2] = vget_low_s16(vmovl_s8(vget_high_s8(input_reg)));\n acc_reg[3] = vget_high_s16(vmovl_s8(vget_high_s8(input_reg)));\n for (int i = 0; i < 4; i++) {\n vst1q_s32(\n acc + channel + 4 * i,\n vaddw_s16(vld1q_s32(acc + channel + 4 * i), acc_reg[i]));\n }\n }\n for (; channel <= tranche_depth - 8; channel += 8) {\n int16x4_t acc_reg[2];\n int16x8_t input_reg = vmovl_s8(vld1_s8(input_channel_ptr));\n input_channel_ptr += 8;\n acc_reg[0] = vget_low_s16(input_reg);\n acc_reg[1] = vget_high_s16(input_reg);\n for (int i = 0; i < 2; i++) {\n vst1q_s32(\n acc + channel + 4 * i,\n vaddw_s16(vld1q_s32(acc + channel + 4 * i), acc_reg[i]));\n }\n }\n#endif\n for (; channel < tranche_depth; ++channel) {\n acc[channel] += *input_channel_ptr++;\n }\n input_row_ptr += depth;\n }\n }\n int8* output_ptr = output_data + Offset(output_shape, batch, out_y,\n out_x, depth_base);\n int channel = 0;\n#ifdef USE_NEON\n for (; channel <= tranche_depth - 8; channel += 8) {\n int16 buf[8];\n for (int i = 0; i < 8; i++) {\n buf[i] =\n acc[channel + i] > 0\n ? (acc[channel + i] + filter_count / 2) / filter_count\n : (acc[channel + i] - filter_count / 2) / filter_count;\n }\n int8x8_t buf8 = vqmovn_s16(vld1q_s16(buf));\n buf8 = vmin_s8(buf8, vdup_n_s8(params.quantized_activation_max));\n buf8 = vmax_s8(buf8, vdup_n_s8(params.quantized_activation_min));\n vst1_s8(output_ptr + channel, buf8);\n }\n#endif\n for (; channel < tranche_depth; ++channel) {\n int16 a = acc[channel] > 0\n ? (acc[channel] + filter_count / 2) / filter_count\n : (acc[channel] - filter_count / 2) / filter_count;\n a = std::max(a, params.quantized_activation_min);\n a = std::min(a, params.quantized_activation_max);\n output_ptr[channel] = static_cast(a);\n }\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: void AverageEvalQuantizedUint8(TfLiteContext* context, TfLiteNode* node,\n TfLitePoolParams* params, OpData* data,\n const TfLiteTensor* input,\n TfLiteTensor* output) {\n int32_t activation_min;\n int32_t activation_max;\n (void)CalculateActivationRangeQuantized(context, params->activation, output,\n &activation_min, &activation_max);\n#define TF_LITE_AVERAGE_POOL(type) \\\n tflite::PoolParams op_params; \\\n op_params.stride_height = params->stride_height; \\\n op_params.stride_width = params->stride_width; \\\n op_params.filter_height = params->filter_height; \\\n op_params.filter_width = params->filter_width; \\\n op_params.padding_values.height = data->padding.height; \\\n op_params.padding_values.width = data->padding.width; \\\n op_params.quantized_activation_min = activation_min; \\\n op_params.quantized_activation_max = activation_max; \\\n type::AveragePool(op_params, GetTensorShape(input), \\\n GetTensorData(input), GetTensorShape(output), \\\n GetTensorData(output))\n if (kernel_type == kReference) {\n TF_LITE_AVERAGE_POOL(reference_ops);\n } else {\n TF_LITE_AVERAGE_POOL(optimized_ops);\n }\n#undef TF_LITE_AVERAGE_POOL\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'Prevent a division by 0 in average ops.\n\nPiperOrigin-RevId: 385184660\nChange-Id: I7affd4554f9b336fca29ac68f633232c094d0bd3'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int adts_decode_extradata(AVFormatContext *s, ADTSContext *adts, const uint8_t *buf, int size)\n{\n GetBitContext gb;\n PutBitContext pb;\n MPEG4AudioConfig m4ac;\n int off;\n\n init_get_bits(&gb, buf, size * 8);\n off = avpriv_mpeg4audio_get_config2(&m4ac, buf, size, 1, s);\n if (off < 0)\n return off;\n skip_bits_long(&gb, off);\n adts->objecttype = m4ac.object_type - 1;\n adts->sample_rate_index = m4ac.sampling_index;\n adts->channel_conf = m4ac.chan_config;\n\n if (adts->objecttype > 3U) {\n av_log(s, AV_LOG_ERROR, \"MPEG-4 AOT %d is not allowed in ADTS\\n\", adts->objecttype+1);\n return AVERROR_INVALIDDATA;\n }\n if (adts->sample_rate_index == 15) {\n av_log(s, AV_LOG_ERROR, \"Escape sample rate index illegal in ADTS\\n\");\n return AVERROR_INVALIDDATA;\n }\n if (get_bits(&gb, 1)) {\n av_log(s, AV_LOG_ERROR, \"960/120 MDCT window is not allowed in ADTS\\n\");\n return AVERROR_INVALIDDATA;\n }\n if (get_bits(&gb, 1)) {\n av_log(s, AV_LOG_ERROR, \"Scalable configurations are not allowed in ADTS\\n\");\n return AVERROR_INVALIDDATA;\n }\n if (get_bits(&gb, 1)) {\n av_log(s, AV_LOG_ERROR, \"Extension flag is not allowed in ADTS\\n\");\n return AVERROR_INVALIDDATA;\n }\n if (!adts->channel_conf) {\n init_put_bits(&pb, adts->pce_data, MAX_PCE_SIZE);\n\n put_bits(&pb, 3, 5); //ID_PCE\n adts->pce_size = (ff_copy_pce_data(&pb, &gb) + 3) / 8;\n flush_put_bits(&pb);\n }\n\n adts->write_adts = 1;\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-252'], 'message': 'avformat/adtsenc: return value check for init_get_bits in adts_decode_extradata\n\nAs the second argument for init_get_bits (buf) can be crafted, a return value check for this function call is necessary.\n'buf' is part of 'AVPacket pkt'.\nreplace init_get_bits with init_get_bits8.\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: ecma_bigint_to_string (ecma_value_t value, /**< BigInt value */\n ecma_bigint_digit_t radix) /**< conversion radix */\n{\n JERRY_ASSERT (ecma_is_value_bigint (value));\n\n if (value == ECMA_BIGINT_ZERO)\n {\n return ecma_new_ecma_string_from_code_unit (LIT_CHAR_0);\n }\n\n uint32_t char_start_p, char_size_p;\n ecma_extended_primitive_t *bigint_p = ecma_get_extended_primitive_from_value (value);\n lit_utf8_byte_t *string_buffer_p = ecma_big_uint_to_string (bigint_p, radix, &char_start_p, &char_size_p);\n\n if (JERRY_UNLIKELY (string_buffer_p == NULL))\n {\n ecma_raise_range_error (ECMA_ERR_MSG (\"Cannot allocate memory for a string representation of a BigInt value\"));\n return NULL;\n }\n\n JERRY_ASSERT (char_start_p > 0);\n\n if (bigint_p->u.bigint_sign_and_size & ECMA_BIGINT_SIGN)\n {\n string_buffer_p[--char_start_p] = LIT_CHAR_MINUS;\n }\n\n ecma_string_t *string_p;\n string_p = ecma_new_ecma_string_from_utf8 (string_buffer_p + char_start_p, char_size_p - char_start_p);\n\n jmem_heap_free_block (string_buffer_p, char_size_p);\n return string_p;\n} /* ecma_bigint_to_string */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Improve parse_identifier (#4691)\n\nAscii string length is no longer computed during string allocation.\r\n\r\nJerryScript-DCO-1.0-Signed-off-by: Daniel Batiz batizjob@gmail.com'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: lexer_token_is_async (parser_context_t *context_p) /**< context */\n{\n JERRY_ASSERT (context_p->token.type == LEXER_LITERAL\n || context_p->token.type == LEXER_TEMPLATE_LITERAL);\n\n return (context_p->token.keyword_type == LEXER_KEYW_ASYNC\n && !context_p->token.lit_location.has_escape);\n} /* lexer_token_is_async */ ; 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_append_argument (parser_context_t *context_p, /**< context */\n scanner_context_t *scanner_context_p) /**< scanner context */\n{\n scanner_literal_pool_t *literal_pool_p = scanner_context_p->active_literal_pool_p;\n parser_list_iterator_t literal_iterator;\n parser_list_iterator_init (&literal_pool_p->literal_pool, &literal_iterator);\n lexer_lit_location_t *literal_location_p = &context_p->token.lit_location;\n lexer_lit_location_t *literal_p;\n\n const uint8_t *char_p = literal_location_p->char_p;\n prop_length_t length = literal_location_p->length;\n\n JERRY_ASSERT (SCANNER_LITERAL_POOL_MAY_HAVE_ARGUMENTS (literal_pool_p->status_flags));\n\n if (JERRY_LIKELY (!context_p->token.lit_location.has_escape))\n {\n while ((literal_p = (lexer_lit_location_t *) parser_list_iterator_next (&literal_iterator)) != NULL)\n {\n if (literal_p->length == length)\n {\n if (JERRY_LIKELY (!literal_p->has_escape))\n {\n if (memcmp (literal_p->char_p, char_p, length) == 0)\n {\n break;\n }\n }\n else if (lexer_compare_identifier_to_string (literal_p, char_p, length))\n {\n break;\n }\n }\n }\n }\n else\n {\n while ((literal_p = (lexer_lit_location_t *) parser_list_iterator_next (&literal_iterator)) != NULL)\n {\n if (lexer_compare_identifiers (context_p, literal_p, literal_location_p))\n {\n break;\n }\n }\n }\n\n uint8_t literal_type = SCANNER_LITERAL_IS_ARG;\n\n if (literal_p != NULL)\n {\n literal_p->length = 0;\n\n#if JERRY_ESNEXT\n if (literal_p->type & SCANNER_LITERAL_IS_USED)\n {\n literal_type = SCANNER_LITERAL_IS_ARG | SCANNER_LITERAL_EARLY_CREATE;\n }\n#endif /* JERRY_ESNEXT */\n }\n\n literal_p = (lexer_lit_location_t *) parser_list_append (context_p, &literal_pool_p->literal_pool);\n\n *literal_p = context_p->token.lit_location;\n literal_p->type = literal_type;\n\n return literal_p;\n} /* scanner_append_argument */ ; 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: NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension, PIRP Irp)\n{\n\tPIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp);\n\tNTSTATUS ntStatus;\n\n\tswitch (irpSp->Parameters.DeviceIoControl.IoControlCode)\n\t{\n\tcase TC_IOCTL_GET_DRIVER_VERSION:\n\tcase TC_IOCTL_LEGACY_GET_DRIVER_VERSION:\n\t\tif (ValidateIOBufferSize (Irp, sizeof (LONG), ValidateOutput))\n\t\t{\n\t\t\tLONG tmp = VERSION_NUM;\n\t\t\tmemcpy (Irp->AssociatedIrp.SystemBuffer, &tmp, 4);\n\t\t\tIrp->IoStatus.Information = sizeof (LONG);\n\t\t\tIrp->IoStatus.Status = STATUS_SUCCESS;\n\t\t}\n\t\tbreak;\n\n\tcase TC_IOCTL_GET_DEVICE_REFCOUNT:\n\t\tif (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput))\n\t\t{\n\t\t\t*(int *) Irp->AssociatedIrp.SystemBuffer = DeviceObject->ReferenceCount;\n\t\t\tIrp->IoStatus.Information = sizeof (int);\n\t\t\tIrp->IoStatus.Status = STATUS_SUCCESS;\n\t\t}\n\t\tbreak;\n\n\tcase TC_IOCTL_IS_DRIVER_UNLOAD_DISABLED:\n\t\tif (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput))\n\t\t{\n\t\t\tLONG deviceObjectCount = 0;\n\n\t\t\t*(int *) Irp->AssociatedIrp.SystemBuffer = DriverUnloadDisabled;\n\n\t\t\tif (IoEnumerateDeviceObjectList (TCDriverObject, NULL, 0, &deviceObjectCount) == STATUS_BUFFER_TOO_SMALL && deviceObjectCount > 1)\n\t\t\t\t*(int *) Irp->AssociatedIrp.SystemBuffer = TRUE;\n\n\t\t\tIrp->IoStatus.Information = sizeof (int);\n\t\t\tIrp->IoStatus.Status = STATUS_SUCCESS;\n\t\t}\n\t\tbreak;\n\n\tcase TC_IOCTL_IS_ANY_VOLUME_MOUNTED:\n\t\tif (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput))\n\t\t{\n\t\t\tint drive;\n\t\t\t*(int *) Irp->AssociatedIrp.SystemBuffer = 0;\n\n\t\t\tfor (drive = MIN_MOUNTED_VOLUME_DRIVE_NUMBER; drive <= MAX_MOUNTED_VOLUME_DRIVE_NUMBER; ++drive)\n\t\t\t{\n\t\t\t\tif (GetVirtualVolumeDeviceObject (drive))\n\t\t\t\t{\n\t\t\t\t\t*(int *) Irp->AssociatedIrp.SystemBuffer = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (IsBootDriveMounted())\n\t\t\t\t*(int *) Irp->AssociatedIrp.SystemBuffer = 1;\n\n\t\t\tIrp->IoStatus.Information = sizeof (int);\n\t\t\tIrp->IoStatus.Status = STATUS_SUCCESS;\n\t\t}\n\t\tbreak;\n\n\tcase TC_IOCTL_OPEN_TEST:\n\t\t{\n\t\t\tOPEN_TEST_STRUCT *opentest = (OPEN_TEST_STRUCT *) Irp->AssociatedIrp.SystemBuffer;\n\t\t\tOBJECT_ATTRIBUTES ObjectAttributes;\n\t\t\tHANDLE NtFileHandle;\n\t\t\tUNICODE_STRING FullFileName;\n\t\t\tIO_STATUS_BLOCK IoStatus;\n\t\t\tLARGE_INTEGER offset;\n\t\t\tACCESS_MASK access = FILE_READ_ATTRIBUTES;\n\n\t\t\tif (!ValidateIOBufferSize (Irp, sizeof (OPEN_TEST_STRUCT), ValidateInputOutput))\n\t\t\t\tbreak;\n\n\t\t\tEnsureNullTerminatedString (opentest->wszFileName, sizeof (opentest->wszFileName));\n\t\t\tRtlInitUnicodeString (&FullFileName, opentest->wszFileName);\n\n\t\t\tInitializeObjectAttributes (&ObjectAttributes, &FullFileName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL);\n\n\t\t\tif (opentest->bDetectTCBootLoader || opentest->DetectFilesystem || opentest->bComputeVolumeIDs)\n\t\t\t\taccess |= FILE_READ_DATA;\n\n\t\t\tntStatus = ZwCreateFile (&NtFileHandle,\n\t\t\t\t\t\t SYNCHRONIZE | access, &ObjectAttributes, &IoStatus, NULL,\n\t\t\t\t\t\t 0, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0);\n\n\t\t\tif (NT_SUCCESS (ntStatus))\n\t\t\t{\n\t\t\t\topentest->TCBootLoaderDetected = FALSE;\n\t\t\t\topentest->FilesystemDetected = FALSE;\n\t\t\t\tmemset (opentest->VolumeIDComputed, 0, sizeof (opentest->VolumeIDComputed));\n\t\t\t\tmemset (opentest->volumeIDs, 0, sizeof (opentest->volumeIDs));\n\n\t\t\t\tif (opentest->bDetectTCBootLoader || opentest->DetectFilesystem || opentest->bComputeVolumeIDs)\n\t\t\t\t{\n\t\t\t\t\tbyte *readBuffer = TCalloc (TC_MAX_VOLUME_SECTOR_SIZE);\n\t\t\t\t\tif (!readBuffer)\n\t\t\t\t\t{\n\t\t\t\t\t\tntStatus = STATUS_INSUFFICIENT_RESOURCES;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tif (opentest->bDetectTCBootLoader || opentest->DetectFilesystem)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// Determine if the first sector contains a portion of the VeraCrypt Boot Loader\n\n\t\t\t\t\t\t\toffset.QuadPart = 0;\n\n\t\t\t\t\t\t\tntStatus = ZwReadFile (NtFileHandle,\n\t\t\t\t\t\t\t\tNULL,\n\t\t\t\t\t\t\t\tNULL,\n\t\t\t\t\t\t\t\tNULL,\n\t\t\t\t\t\t\t\t&IoStatus,\n\t\t\t\t\t\t\t\treadBuffer,\n\t\t\t\t\t\t\t\tTC_MAX_VOLUME_SECTOR_SIZE,\n\t\t\t\t\t\t\t\t&offset,\n\t\t\t\t\t\t\t\tNULL);\n\n\t\t\t\t\t\t\tif (NT_SUCCESS (ntStatus))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsize_t i;\n\n\t\t\t\t\t\t\t\tif (opentest->bDetectTCBootLoader && IoStatus.Information >= TC_SECTOR_SIZE_BIOS)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t// Search for the string \"VeraCrypt\"\n\t\t\t\t\t\t\t\t\tfor (i = 0; i < TC_SECTOR_SIZE_BIOS - strlen (TC_APP_NAME); ++i)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tif (memcmp (readBuffer + i, TC_APP_NAME, strlen (TC_APP_NAME)) == 0)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\topentest->TCBootLoaderDetected = TRUE;\n\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif (opentest->DetectFilesystem && IoStatus.Information >= sizeof (int64))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tswitch (BE64 (*(uint64 *) readBuffer))\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcase 0xEB52904E54465320ULL: // NTFS\n\t\t\t\t\t\t\t\t\tcase 0xEB3C904D53444F53ULL: // FAT16/FAT32\n\t\t\t\t\t\t\t\t\tcase 0xEB58904D53444F53ULL: // FAT32\n\t\t\t\t\t\t\t\t\tcase 0xEB76904558464154ULL: // exFAT\n\t\t\t\t\t\t\t\t\tcase 0x0000005265465300ULL: // ReFS\n\t\t\t\t\t\t\t\t\tcase 0xEB58906D6B66732EULL: // FAT32 mkfs.fat\n\t\t\t\t\t\t\t\t\tcase 0xEB58906D6B646F73ULL: // FAT32 mkfs.vfat/mkdosfs\n\t\t\t\t\t\t\t\t\tcase 0xEB3C906D6B66732EULL: // FAT16/FAT12 mkfs.fat\n\t\t\t\t\t\t\t\t\tcase 0xEB3C906D6B646F73ULL: // FAT16/FAT12 mkfs.vfat/mkdosfs\n\t\t\t\t\t\t\t\t\t\topentest->FilesystemDetected = TRUE;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase 0x0000000000000000ULL:\n\t\t\t\t\t\t\t\t\t\t// all 512 bytes are zeroes => unencrypted filesystem like Microsoft reserved partition\n\t\t\t\t\t\t\t\t\t\tif (IsAllZeroes (readBuffer + 8, TC_VOLUME_HEADER_EFFECTIVE_SIZE - 8))\n\t\t\t\t\t\t\t\t\t\t\topentest->FilesystemDetected = TRUE;\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}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (opentest->bComputeVolumeIDs && (!opentest->DetectFilesystem || !opentest->FilesystemDetected))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint volumeType;\n\t\t\t\t\t\t\t// Go through all volume types (e.g., normal, hidden)\n\t\t\t\t\t\t\tfor (volumeType = TC_VOLUME_TYPE_NORMAL;\n\t\t\t\t\t\t\t\tvolumeType < TC_VOLUME_TYPE_COUNT;\n\t\t\t\t\t\t\t\tvolumeType++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t/* Read the volume header */\n\t\t\t\t\t\t\t\tswitch (volumeType)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcase TC_VOLUME_TYPE_NORMAL:\n\t\t\t\t\t\t\t\t\toffset.QuadPart = TC_VOLUME_HEADER_OFFSET;\n\t\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\t\tcase TC_VOLUME_TYPE_HIDDEN:\n\n\t\t\t\t\t\t\t\t\toffset.QuadPart = TC_HIDDEN_VOLUME_HEADER_OFFSET;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tntStatus = ZwReadFile (NtFileHandle,\n\t\t\t\t\t\t\t\tNULL,\n\t\t\t\t\t\t\t\tNULL,\n\t\t\t\t\t\t\t\tNULL,\n\t\t\t\t\t\t\t\t&IoStatus,\n\t\t\t\t\t\t\t\treadBuffer,\n\t\t\t\t\t\t\t\tTC_MAX_VOLUME_SECTOR_SIZE,\n\t\t\t\t\t\t\t\t&offset,\n\t\t\t\t\t\t\t\tNULL);\n\n\t\t\t\t\t\t\t\tif (NT_SUCCESS (ntStatus))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t/* compute the ID of this volume: SHA-256 of the effective header */\n\t\t\t\t\t\t\t\t\tsha256 (opentest->volumeIDs[volumeType], readBuffer, TC_VOLUME_HEADER_EFFECTIVE_SIZE);\n\t\t\t\t\t\t\t\t\topentest->VolumeIDComputed[volumeType] = TRUE;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tTCfree (readBuffer);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tZwClose (NtFileHandle);\n\t\t\t\tDump (\"Open test on file %ls success.\\n\", opentest->wszFileName);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n#if 0\n\t\t\t\tDump (\"Open test on file %ls failed NTSTATUS 0x%08x\\n\", opentest->wszFileName, ntStatus);\n#endif\n\t\t\t}\n\n\t\t\tIrp->IoStatus.Information = NT_SUCCESS (ntStatus) ? sizeof (OPEN_TEST_STRUCT) : 0;\n\t\t\tIrp->IoStatus.Status = ntStatus;\n\t\t}\n\t\tbreak;\n\n\tcase TC_IOCTL_GET_SYSTEM_DRIVE_CONFIG:\n\t\t{\n\t\t\tGetSystemDriveConfigurationRequest *request = (GetSystemDriveConfigurationRequest *) Irp->AssociatedIrp.SystemBuffer;\n\t\t\tOBJECT_ATTRIBUTES ObjectAttributes;\n\t\t\tHANDLE NtFileHandle;\n\t\t\tUNICODE_STRING FullFileName;\n\t\t\tIO_STATUS_BLOCK IoStatus;\n\t\t\tLARGE_INTEGER offset;\n\t\t\tbyte readBuffer [TC_SECTOR_SIZE_BIOS];\n\n\t\t\tif (!ValidateIOBufferSize (Irp, sizeof (GetSystemDriveConfigurationRequest), ValidateInputOutput))\n\t\t\t\tbreak;\n\n\t\t\tEnsureNullTerminatedString (request->DevicePath, sizeof (request->DevicePath));\n\t\t\tRtlInitUnicodeString (&FullFileName, request->DevicePath);\n\n\t\t\tInitializeObjectAttributes (&ObjectAttributes, &FullFileName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL);\n\n\t\t\tntStatus = ZwCreateFile (&NtFileHandle,\n\t\t\t\tSYNCHRONIZE | GENERIC_READ, &ObjectAttributes, &IoStatus, NULL,\n\t\t\t\tFILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT | FILE_RANDOM_ACCESS, NULL, 0);\n\n\t\t\tif (NT_SUCCESS (ntStatus))\n\t\t\t{\n\t\t\t\t// Determine if the first sector contains a portion of the VeraCrypt Boot Loader\n\t\t\t\toffset.QuadPart = 0;\t// MBR\n\n\t\t\t\tntStatus = ZwReadFile (NtFileHandle,\n\t\t\t\t\tNULL,\n\t\t\t\t\tNULL,\n\t\t\t\t\tNULL,\n\t\t\t\t\t&IoStatus,\n\t\t\t\t\treadBuffer,\n\t\t\t\t\tsizeof(readBuffer),\n\t\t\t\t\t&offset,\n\t\t\t\t\tNULL);\n\n\t\t\t\tif (NT_SUCCESS (ntStatus))\n\t\t\t\t{\n\t\t\t\t\tsize_t i;\n\n\t\t\t\t\t// Check for dynamic drive\n\t\t\t\t\trequest->DriveIsDynamic = FALSE;\n\n\t\t\t\t\tif (readBuffer[510] == 0x55 && readBuffer[511] == 0xaa)\n\t\t\t\t\t{\n\t\t\t\t\t\tint i;\n\t\t\t\t\t\tfor (i = 0; i < 4; ++i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (readBuffer[446 + i * 16 + 4] == PARTITION_LDM)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\trequest->DriveIsDynamic = TRUE;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\trequest->BootLoaderVersion = 0;\n\t\t\t\t\trequest->Configuration = 0;\n\t\t\t\t\trequest->UserConfiguration = 0;\n\t\t\t\t\trequest->CustomUserMessage[0] = 0;\n\n\t\t\t\t\t// Search for the string \"VeraCrypt\"\n\t\t\t\t\tfor (i = 0; i < sizeof (readBuffer) - strlen (TC_APP_NAME); ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (memcmp (readBuffer + i, TC_APP_NAME, strlen (TC_APP_NAME)) == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trequest->BootLoaderVersion = BE16 (*(uint16 *) (readBuffer + TC_BOOT_SECTOR_VERSION_OFFSET));\n\t\t\t\t\t\t\trequest->Configuration = readBuffer[TC_BOOT_SECTOR_CONFIG_OFFSET];\n\n\t\t\t\t\t\t\tif (request->BootLoaderVersion != 0 && request->BootLoaderVersion <= VERSION_NUM)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\trequest->UserConfiguration = readBuffer[TC_BOOT_SECTOR_USER_CONFIG_OFFSET];\n\t\t\t\t\t\t\t\tmemcpy (request->CustomUserMessage, readBuffer + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH);\n\t\t\t\t\t\t\t}\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\tIrp->IoStatus.Status = STATUS_SUCCESS;\n\t\t\t\t\tIrp->IoStatus.Information = sizeof (*request);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tIrp->IoStatus.Status = ntStatus;\n\t\t\t\t\tIrp->IoStatus.Information = 0;\n\t\t\t\t}\n\n\t\t\t\tZwClose (NtFileHandle);\n\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tIrp->IoStatus.Status = ntStatus;\n\t\t\t\tIrp->IoStatus.Information = 0;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase TC_IOCTL_WIPE_PASSWORD_CACHE:\n\t\tWipeCache ();\n\n\t\tIrp->IoStatus.Status = STATUS_SUCCESS;\n\t\tIrp->IoStatus.Information = 0;\n\t\tbreak;\n\n\tcase TC_IOCTL_GET_PASSWORD_CACHE_STATUS:\n\t\tIrp->IoStatus.Status = cacheEmpty ? STATUS_PIPE_EMPTY : STATUS_SUCCESS;\n\t\tIrp->IoStatus.Information = 0;\n\t\tbreak;\n\n\tcase TC_IOCTL_SET_PORTABLE_MODE_STATUS:\n\t\tif (!UserCanAccessDriveDevice())\n\t\t{\n\t\t\tIrp->IoStatus.Status = STATUS_ACCESS_DENIED;\n\t\t\tIrp->IoStatus.Information = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tPortableMode = TRUE;\n\t\t\tDump (\"Setting portable mode\\n\");\n\t\t}\n\t\tbreak;\n\n\tcase TC_IOCTL_GET_PORTABLE_MODE_STATUS:\n\t\tIrp->IoStatus.Status = PortableMode ? STATUS_SUCCESS : STATUS_PIPE_EMPTY;\n\t\tIrp->IoStatus.Information = 0;\n\t\tbreak;\n\n\tcase TC_IOCTL_GET_MOUNTED_VOLUMES:\n\n\t\tif (ValidateIOBufferSize (Irp, sizeof (MOUNT_LIST_STRUCT), ValidateOutput))\n\t\t{\n\t\t\tMOUNT_LIST_STRUCT *list = (MOUNT_LIST_STRUCT *) Irp->AssociatedIrp.SystemBuffer;\n\t\t\tPDEVICE_OBJECT ListDevice;\n\t\t\tint drive;\n\n\t\t\tlist->ulMountedDrives = 0;\n\n\t\t\tfor (drive = MIN_MOUNTED_VOLUME_DRIVE_NUMBER; drive <= MAX_MOUNTED_VOLUME_DRIVE_NUMBER; ++drive)\n\t\t\t{\n\t\t\t\tPEXTENSION ListExtension;\n\n\t\t\t\tListDevice = GetVirtualVolumeDeviceObject (drive);\n\t\t\t\tif (!ListDevice)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tListExtension = (PEXTENSION) ListDevice->DeviceExtension;\n\t\t\t\tif (IsVolumeAccessibleByCurrentUser (ListExtension))\n\t\t\t\t{\n\t\t\t\t\tlist->ulMountedDrives |= (1 << ListExtension->nDosDriveNo);\n\t\t\t\t\tRtlStringCbCopyW (list->wszVolume[ListExtension->nDosDriveNo], sizeof(list->wszVolume[ListExtension->nDosDriveNo]),ListExtension->wszVolume);\n\t\t\t\t\tRtlStringCbCopyW (list->wszLabel[ListExtension->nDosDriveNo], sizeof(list->wszLabel[ListExtension->nDosDriveNo]),ListExtension->wszLabel);\n\t\t\t\t\tmemcpy (list->volumeID[ListExtension->nDosDriveNo], ListExtension->volumeID, VOLUME_ID_SIZE);\n\t\t\t\t\tlist->diskLength[ListExtension->nDosDriveNo] = ListExtension->DiskLength;\n\t\t\t\t\tlist->ea[ListExtension->nDosDriveNo] = ListExtension->cryptoInfo->ea;\n\t\t\t\t\tif (ListExtension->cryptoInfo->hiddenVolume)\n\t\t\t\t\t\tlist->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_HIDDEN;\t// Hidden volume\n\t\t\t\t\telse if (ListExtension->cryptoInfo->bHiddenVolProtectionAction)\n\t\t\t\t\t\tlist->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_OUTER_VOL_WRITE_PREVENTED;\t// Normal/outer volume (hidden volume protected AND write already prevented)\n\t\t\t\t\telse if (ListExtension->cryptoInfo->bProtectHiddenVolume)\n\t\t\t\t\t\tlist->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_OUTER;\t// Normal/outer volume (hidden volume protected)\n\t\t\t\t\telse\n\t\t\t\t\t\tlist->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_NORMAL;\t// Normal volume\n\t\t\t\t\tlist->truecryptMode[ListExtension->nDosDriveNo] = ListExtension->cryptoInfo->bTrueCryptMode;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tIrp->IoStatus.Status = STATUS_SUCCESS;\n\t\t\tIrp->IoStatus.Information = sizeof (MOUNT_LIST_STRUCT);\n\t\t}\n\t\tbreak;\n\n\tcase TC_IOCTL_LEGACY_GET_MOUNTED_VOLUMES:\n\t\tif (ValidateIOBufferSize (Irp, sizeof (uint32), ValidateOutput))\n\t\t{\n\t\t\t// Prevent the user from downgrading to versions lower than 5.0 by faking mounted volumes.\n\t\t\t// The user could render the system unbootable by downgrading when boot encryption\n\t\t\t// is active or being set up.\n\n\t\t\tmemset (Irp->AssociatedIrp.SystemBuffer, 0, irpSp->Parameters.DeviceIoControl.OutputBufferLength);\n\t\t\t*(uint32 *) Irp->AssociatedIrp.SystemBuffer = 0xffffFFFF;\n\n\t\t\tIrp->IoStatus.Status = STATUS_SUCCESS;\n\t\t\tIrp->IoStatus.Information = irpSp->Parameters.DeviceIoControl.OutputBufferLength;\n\t\t}\n\t\tbreak;\n\n\tcase TC_IOCTL_GET_VOLUME_PROPERTIES:\n\t\tif (ValidateIOBufferSize (Irp, sizeof (VOLUME_PROPERTIES_STRUCT), ValidateInputOutput))\n\t\t{\n\t\t\tVOLUME_PROPERTIES_STRUCT *prop = (VOLUME_PROPERTIES_STRUCT *) Irp->AssociatedIrp.SystemBuffer;\n\t\t\tPDEVICE_OBJECT ListDevice = GetVirtualVolumeDeviceObject (prop->driveNo);\n\n\t\t\tIrp->IoStatus.Status = STATUS_INVALID_PARAMETER;\n\t\t\tIrp->IoStatus.Information = 0;\n\n\t\t\tif (ListDevice)\n\t\t\t{\n\t\t\t\tPEXTENSION ListExtension = (PEXTENSION) ListDevice->DeviceExtension;\n\t\t\t\tif (IsVolumeAccessibleByCurrentUser (ListExtension))\n\t\t\t\t{\n\t\t\t\t\tprop->uniqueId = ListExtension->UniqueVolumeId;\n\t\t\t\t\tRtlStringCbCopyW (prop->wszVolume, sizeof(prop->wszVolume),ListExtension->wszVolume);\n\t\t\t\t\tRtlStringCbCopyW (prop->wszLabel, sizeof(prop->wszLabel),ListExtension->wszLabel);\n\t\t\t\t\tmemcpy (prop->volumeID, ListExtension->volumeID, VOLUME_ID_SIZE);\n\t\t\t\t\tprop->bDriverSetLabel = ListExtension->bDriverSetLabel;\n\t\t\t\t\tprop->diskLength = ListExtension->DiskLength;\n\t\t\t\t\tprop->ea = ListExtension->cryptoInfo->ea;\n\t\t\t\t\tprop->mode = ListExtension->cryptoInfo->mode;\n\t\t\t\t\tprop->pkcs5 = ListExtension->cryptoInfo->pkcs5;\n\t\t\t\t\tprop->pkcs5Iterations = ListExtension->cryptoInfo->noIterations;\n\t\t\t\t\tprop->volumePim = ListExtension->cryptoInfo->volumePim;\n#if 0\n\t\t\t\t\tprop->volumeCreationTime = ListExtension->cryptoInfo->volume_creation_time;\n\t\t\t\t\tprop->headerCreationTime = ListExtension->cryptoInfo->header_creation_time;\n#endif\n\t\t\t\t\tprop->volumeHeaderFlags = ListExtension->cryptoInfo->HeaderFlags;\n\t\t\t\t\tprop->readOnly = ListExtension->bReadOnly;\n\t\t\t\t\tprop->removable = ListExtension->bRemovable;\n\t\t\t\t\tprop->partitionInInactiveSysEncScope = ListExtension->PartitionInInactiveSysEncScope;\n\t\t\t\t\tprop->hiddenVolume = ListExtension->cryptoInfo->hiddenVolume;\n\n\t\t\t\t\tif (ListExtension->cryptoInfo->bProtectHiddenVolume)\n\t\t\t\t\t\tprop->hiddenVolProtection = ListExtension->cryptoInfo->bHiddenVolProtectionAction ? HIDVOL_PROT_STATUS_ACTION_TAKEN : HIDVOL_PROT_STATUS_ACTIVE;\n\t\t\t\t\telse\n\t\t\t\t\t\tprop->hiddenVolProtection = HIDVOL_PROT_STATUS_NONE;\n\n\t\t\t\t\tprop->totalBytesRead = ListExtension->Queue.TotalBytesRead;\n\t\t\t\t\tprop->totalBytesWritten = ListExtension->Queue.TotalBytesWritten;\n\n\t\t\t\t\tprop->volFormatVersion = ListExtension->cryptoInfo->LegacyVolume ? TC_VOLUME_FORMAT_VERSION_PRE_6_0 : TC_VOLUME_FORMAT_VERSION;\n\n\t\t\t\t\tIrp->IoStatus.Status = STATUS_SUCCESS;\n\t\t\t\t\tIrp->IoStatus.Information = sizeof (VOLUME_PROPERTIES_STRUCT);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase TC_IOCTL_GET_RESOLVED_SYMLINK:\n\t\tif (ValidateIOBufferSize (Irp, sizeof (RESOLVE_SYMLINK_STRUCT), ValidateInputOutput))\n\t\t{\n\t\t\tRESOLVE_SYMLINK_STRUCT *resolve = (RESOLVE_SYMLINK_STRUCT *) Irp->AssociatedIrp.SystemBuffer;\n\t\t\t{\n\t\t\t\tNTSTATUS ntStatus;\n\n\t\t\t\tEnsureNullTerminatedString (resolve->symLinkName, sizeof (resolve->symLinkName));\n\n\t\t\t\tntStatus = SymbolicLinkToTarget (resolve->symLinkName,\n\t\t\t\t\tresolve->targetName,\n\t\t\t\t\tsizeof (resolve->targetName));\n\n\t\t\t\tIrp->IoStatus.Information = sizeof (RESOLVE_SYMLINK_STRUCT);\n\t\t\t\tIrp->IoStatus.Status = ntStatus;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase TC_IOCTL_GET_DRIVE_PARTITION_INFO:\n\t\tif (ValidateIOBufferSize (Irp, sizeof (DISK_PARTITION_INFO_STRUCT), ValidateInputOutput))\n\t\t{\n\t\t\tDISK_PARTITION_INFO_STRUCT *info = (DISK_PARTITION_INFO_STRUCT *) Irp->AssociatedIrp.SystemBuffer;\n\t\t\t{\n\t\t\t\tPARTITION_INFORMATION_EX pi;\n\t\t\t\tNTSTATUS ntStatus;\n\n\t\t\t\tEnsureNullTerminatedString (info->deviceName, sizeof (info->deviceName));\n\n\t\t\t\tntStatus = TCDeviceIoControl (info->deviceName, IOCTL_DISK_GET_PARTITION_INFO_EX, NULL, 0, &pi, sizeof (pi));\n\t\t\t\tif (NT_SUCCESS(ntStatus))\n\t\t\t\t{\n\t\t\t\t\tmemset (&info->partInfo, 0, sizeof (info->partInfo));\n\n\t\t\t\t\tinfo->partInfo.PartitionLength = pi.PartitionLength;\n\t\t\t\t\tinfo->partInfo.PartitionNumber = pi.PartitionNumber;\n\t\t\t\t\tinfo->partInfo.StartingOffset = pi.StartingOffset;\n\n\t\t\t\t\tif (pi.PartitionStyle == PARTITION_STYLE_MBR)\n\t\t\t\t\t{\n\t\t\t\t\t\tinfo->partInfo.PartitionType = pi.Mbr.PartitionType;\n\t\t\t\t\t\tinfo->partInfo.BootIndicator = pi.Mbr.BootIndicator;\n\t\t\t\t\t}\n\n\t\t\t\t\tinfo->IsGPT = pi.PartitionStyle == PARTITION_STYLE_GPT;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// Windows 2000 does not support IOCTL_DISK_GET_PARTITION_INFO_EX\n\t\t\t\t\tntStatus = TCDeviceIoControl (info->deviceName, IOCTL_DISK_GET_PARTITION_INFO, NULL, 0, &info->partInfo, sizeof (info->partInfo));\n\t\t\t\t\tinfo->IsGPT = FALSE;\n\t\t\t\t}\n\n\t\t\t\tif (!NT_SUCCESS (ntStatus))\n\t\t\t\t{\n\t\t\t\t\tGET_LENGTH_INFORMATION lengthInfo;\n\t\t\t\t\tntStatus = TCDeviceIoControl (info->deviceName, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, &lengthInfo, sizeof (lengthInfo));\n\n\t\t\t\t\tif (NT_SUCCESS (ntStatus))\n\t\t\t\t\t{\n\t\t\t\t\t\tmemset (&info->partInfo, 0, sizeof (info->partInfo));\n\t\t\t\t\t\tinfo->partInfo.PartitionLength = lengthInfo.Length;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tinfo->IsDynamic = FALSE;\n\n\t\t\t\tif (NT_SUCCESS (ntStatus) && OsMajorVersion >= 6)\n\t\t\t\t{\n#\t\t\t\t\tdefine IOCTL_VOLUME_IS_DYNAMIC CTL_CODE(IOCTL_VOLUME_BASE, 18, METHOD_BUFFERED, FILE_ANY_ACCESS)\n\t\t\t\t\tif (!NT_SUCCESS (TCDeviceIoControl (info->deviceName, IOCTL_VOLUME_IS_DYNAMIC, NULL, 0, &info->IsDynamic, sizeof (info->IsDynamic))))\n\t\t\t\t\t\tinfo->IsDynamic = FALSE;\n\t\t\t\t}\n\n\t\t\t\tIrp->IoStatus.Information = sizeof (DISK_PARTITION_INFO_STRUCT);\n\t\t\t\tIrp->IoStatus.Status = ntStatus;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase TC_IOCTL_GET_DRIVE_GEOMETRY:\n\t\tif (ValidateIOBufferSize (Irp, sizeof (DISK_GEOMETRY_STRUCT), ValidateInputOutput))\n\t\t{\n\t\t\tDISK_GEOMETRY_STRUCT *g = (DISK_GEOMETRY_STRUCT *) Irp->AssociatedIrp.SystemBuffer;\n\t\t\t{\n\t\t\t\tNTSTATUS ntStatus;\n\n\t\t\t\tEnsureNullTerminatedString (g->deviceName, sizeof (g->deviceName));\n\t\t\t\tDump (\"Calling IOCTL_DISK_GET_DRIVE_GEOMETRY on %ls\\n\", g->deviceName);\n\n\t\t\t\tntStatus = TCDeviceIoControl (g->deviceName,\n\t\t\t\t\tIOCTL_DISK_GET_DRIVE_GEOMETRY,\n\t\t\t\t\tNULL, 0, &g->diskGeometry, sizeof (g->diskGeometry));\n\n\t\t\t\tIrp->IoStatus.Information = sizeof (DISK_GEOMETRY_STRUCT);\n\t\t\t\tIrp->IoStatus.Status = ntStatus;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase VC_IOCTL_GET_DRIVE_GEOMETRY_EX:\n\t\tif (ValidateIOBufferSize (Irp, sizeof (DISK_GEOMETRY_EX_STRUCT), ValidateInputOutput))\n\t\t{\n\t\t\tDISK_GEOMETRY_EX_STRUCT *g = (DISK_GEOMETRY_EX_STRUCT *) Irp->AssociatedIrp.SystemBuffer;\n\t\t\t{\n\t\t\t\tNTSTATUS ntStatus;\n\t\t\t\tPVOID buffer = TCalloc (256); // enough for DISK_GEOMETRY_EX and padded data\n\t\t\t\tif (buffer)\n\t\t\t\t{\n\t\t\t\t\tEnsureNullTerminatedString (g->deviceName, sizeof (g->deviceName));\n\t\t\t\t\tDump (\"Calling IOCTL_DISK_GET_DRIVE_GEOMETRY_EX on %ls\\n\", g->deviceName);\n\n\t\t\t\t\tntStatus = TCDeviceIoControl (g->deviceName,\n\t\t\t\t\t\tIOCTL_DISK_GET_DRIVE_GEOMETRY_EX,\n\t\t\t\t\t\tNULL, 0, buffer, 256);\n\n\t\t\t\t\tif (NT_SUCCESS(ntStatus))\n\t\t\t\t\t{\n\t\t\t\t\t\tPDISK_GEOMETRY_EX pGeo = (PDISK_GEOMETRY_EX) buffer;\n\t\t\t\t\t\tmemcpy (&g->diskGeometry, &pGeo->Geometry, sizeof (DISK_GEOMETRY));\n\t\t\t\t\t\tg->DiskSize.QuadPart = pGeo->DiskSize.QuadPart;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tDISK_GEOMETRY dg = {0};\n\t\t\t\t\t\tDump (\"Failed. Calling IOCTL_DISK_GET_DRIVE_GEOMETRY on %ls\\n\", g->deviceName);\n\t\t\t\t\t\tntStatus = TCDeviceIoControl (g->deviceName,\n\t\t\t\t\t\t\tIOCTL_DISK_GET_DRIVE_GEOMETRY,\n\t\t\t\t\t\t\tNULL, 0, &dg, sizeof (dg));\n\n\t\t\t\t\t\tif (NT_SUCCESS(ntStatus))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmemcpy (&g->diskGeometry, &dg, sizeof (DISK_GEOMETRY));\n\t\t\t\t\t\t\tg->DiskSize.QuadPart = dg.Cylinders.QuadPart * dg.SectorsPerTrack * dg.TracksPerCylinder * dg.BytesPerSector;\n\n\t\t\t\t\t\t\tif (OsMajorVersion >= 6)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tSTORAGE_READ_CAPACITY storage = {0};\n\t\t\t\t\t\t\t\tNTSTATUS lStatus;\n\t\t\t\t\t\t\t\tstorage.Version = sizeof (STORAGE_READ_CAPACITY);\n\t\t\t\t\t\t\t\tDump (\"Calling IOCTL_STORAGE_READ_CAPACITY on %ls\\n\", g->deviceName);\n\t\t\t\t\t\t\t\tlStatus = TCDeviceIoControl (g->deviceName,\n\t\t\t\t\t\t\t\t\tIOCTL_STORAGE_READ_CAPACITY,\n\t\t\t\t\t\t\t\t\tNULL, 0, &storage, sizeof (STORAGE_READ_CAPACITY));\n\t\t\t\t\t\t\t\tif (\tNT_SUCCESS(lStatus)\n\t\t\t\t\t\t\t\t\t&& (storage.Size == sizeof (STORAGE_READ_CAPACITY))\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\t\tg->DiskSize.QuadPart = storage.DiskLength.QuadPart;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tTCfree (buffer);\n\n\t\t\t\t\tIrp->IoStatus.Information = sizeof (DISK_GEOMETRY_EX_STRUCT);\n\t\t\t\t\tIrp->IoStatus.Status = ntStatus;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tIrp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES;\n\t\t\t\t\tIrp->IoStatus.Information = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase TC_IOCTL_PROBE_REAL_DRIVE_SIZE:\n\t\tif (ValidateIOBufferSize (Irp, sizeof (ProbeRealDriveSizeRequest), ValidateInputOutput))\n\t\t{\n\t\t\tProbeRealDriveSizeRequest *request = (ProbeRealDriveSizeRequest *) Irp->AssociatedIrp.SystemBuffer;\n\t\t\tNTSTATUS status;\n\t\t\tUNICODE_STRING name;\n\t\t\tPFILE_OBJECT fileObject;\n\t\t\tPDEVICE_OBJECT deviceObject;\n\n\t\t\tEnsureNullTerminatedString (request->DeviceName, sizeof (request->DeviceName));\n\n\t\t\tRtlInitUnicodeString (&name, request->DeviceName);\n\t\t\tstatus = IoGetDeviceObjectPointer (&name, FILE_READ_ATTRIBUTES, &fileObject, &deviceObject);\n\t\t\tif (!NT_SUCCESS (status))\n\t\t\t{\n\t\t\t\tIrp->IoStatus.Information = 0;\n\t\t\t\tIrp->IoStatus.Status = status;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tstatus = ProbeRealDriveSize (deviceObject, &request->RealDriveSize);\n\t\t\tObDereferenceObject (fileObject);\n\n\t\t\tif (status == STATUS_TIMEOUT)\n\t\t\t{\n\t\t\t\trequest->TimeOut = TRUE;\n\t\t\t\tIrp->IoStatus.Information = sizeof (ProbeRealDriveSizeRequest);\n\t\t\t\tIrp->IoStatus.Status = STATUS_SUCCESS;\n\t\t\t}\n\t\t\telse if (!NT_SUCCESS (status))\n\t\t\t{\n\t\t\t\tIrp->IoStatus.Information = 0;\n\t\t\t\tIrp->IoStatus.Status = status;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\trequest->TimeOut = FALSE;\n\t\t\t\tIrp->IoStatus.Information = sizeof (ProbeRealDriveSizeRequest);\n\t\t\t\tIrp->IoStatus.Status = status;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase TC_IOCTL_MOUNT_VOLUME:\n\t\tif (ValidateIOBufferSize (Irp, sizeof (MOUNT_STRUCT), ValidateInputOutput))\n\t\t{\n\t\t\tMOUNT_STRUCT *mount = (MOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer;\n\n\t\t\tif (mount->VolumePassword.Length > MAX_PASSWORD || mount->ProtectedHidVolPassword.Length > MAX_PASSWORD\n\t\t\t\t||\tmount->pkcs5_prf < 0 || mount->pkcs5_prf > LAST_PRF_ID\n\t\t\t\t||\tmount->VolumePim < -1 || mount->VolumePim == INT_MAX\n\t\t\t\t|| mount->ProtectedHidVolPkcs5Prf < 0 || mount->ProtectedHidVolPkcs5Prf > LAST_PRF_ID\n\t\t\t\t|| (mount->bTrueCryptMode != FALSE && mount->bTrueCryptMode != TRUE)\n\t\t\t\t)\n\t\t\t{\n\t\t\t\tIrp->IoStatus.Status = STATUS_INVALID_PARAMETER;\n\t\t\t\tIrp->IoStatus.Information = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tEnsureNullTerminatedString (mount->wszVolume, sizeof (mount->wszVolume));\n\t\t\tEnsureNullTerminatedString (mount->wszLabel, sizeof (mount->wszLabel));\n\n\t\t\tIrp->IoStatus.Information = sizeof (MOUNT_STRUCT);\n\t\t\tIrp->IoStatus.Status = MountDevice (DeviceObject, mount);\n\n\t\t\tburn (&mount->VolumePassword, sizeof (mount->VolumePassword));\n\t\t\tburn (&mount->ProtectedHidVolPassword, sizeof (mount->ProtectedHidVolPassword));\n\t\t\tburn (&mount->pkcs5_prf, sizeof (mount->pkcs5_prf));\n\t\t\tburn (&mount->VolumePim, sizeof (mount->VolumePim));\n\t\t\tburn (&mount->bTrueCryptMode, sizeof (mount->bTrueCryptMode));\n\t\t\tburn (&mount->ProtectedHidVolPkcs5Prf, sizeof (mount->ProtectedHidVolPkcs5Prf));\n\t\t\tburn (&mount->ProtectedHidVolPim, sizeof (mount->ProtectedHidVolPim));\n\t\t}\n\t\tbreak;\n\n\tcase TC_IOCTL_DISMOUNT_VOLUME:\n\t\tif (ValidateIOBufferSize (Irp, sizeof (UNMOUNT_STRUCT), ValidateInputOutput))\n\t\t{\n\t\t\tUNMOUNT_STRUCT *unmount = (UNMOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer;\n\t\t\tPDEVICE_OBJECT ListDevice = GetVirtualVolumeDeviceObject (unmount->nDosDriveNo);\n\n\t\t\tunmount->nReturnCode = ERR_DRIVE_NOT_FOUND;\n\n\t\t\tif (ListDevice)\n\t\t\t{\n\t\t\t\tPEXTENSION ListExtension = (PEXTENSION) ListDevice->DeviceExtension;\n\n\t\t\t\tif (IsVolumeAccessibleByCurrentUser (ListExtension))\n\t\t\t\t\tunmount->nReturnCode = UnmountDevice (unmount, ListDevice, unmount->ignoreOpenFiles);\n\t\t\t}\n\n\t\t\tIrp->IoStatus.Information = sizeof (UNMOUNT_STRUCT);\n\t\t\tIrp->IoStatus.Status = STATUS_SUCCESS;\n\t\t}\n\t\tbreak;\n\n\tcase TC_IOCTL_DISMOUNT_ALL_VOLUMES:\n\t\tif (ValidateIOBufferSize (Irp, sizeof (UNMOUNT_STRUCT), ValidateInputOutput))\n\t\t{\n\t\t\tUNMOUNT_STRUCT *unmount = (UNMOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer;\n\n\t\t\tunmount->nReturnCode = UnmountAllDevices (unmount, unmount->ignoreOpenFiles);\n\n\t\t\tIrp->IoStatus.Information = sizeof (UNMOUNT_STRUCT);\n\t\t\tIrp->IoStatus.Status = STATUS_SUCCESS;\n\t\t}\n\t\tbreak;\n\n\tcase TC_IOCTL_BOOT_ENCRYPTION_SETUP:\n\t\tIrp->IoStatus.Status = StartBootEncryptionSetup (DeviceObject, Irp, irpSp);\n\t\tIrp->IoStatus.Information = 0;\n\t\tbreak;\n\n\tcase TC_IOCTL_ABORT_BOOT_ENCRYPTION_SETUP:\n\t\tIrp->IoStatus.Status = AbortBootEncryptionSetup();\n\t\tIrp->IoStatus.Information = 0;\n\t\tbreak;\n\n\tcase TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS:\n\t\tGetBootEncryptionStatus (Irp, irpSp);\n\t\tbreak;\n\n\tcase TC_IOCTL_GET_BOOT_ENCRYPTION_SETUP_RESULT:\n\t\tIrp->IoStatus.Information = 0;\n\t\tIrp->IoStatus.Status = GetSetupResult();\n\t\tbreak;\n\n\tcase TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES:\n\t\tGetBootDriveVolumeProperties (Irp, irpSp);\n\t\tbreak;\n\n\tcase TC_IOCTL_GET_BOOT_LOADER_VERSION:\n\t\tGetBootLoaderVersion (Irp, irpSp);\n\t\tbreak;\n\n\tcase TC_IOCTL_REOPEN_BOOT_VOLUME_HEADER:\n\t\tReopenBootVolumeHeader (Irp, irpSp);\n\t\tbreak;\n\n\tcase VC_IOCTL_GET_BOOT_LOADER_FINGERPRINT:\n\t\tGetBootLoaderFingerprint (Irp, irpSp);\n\t\tbreak;\n\n\tcase TC_IOCTL_GET_BOOT_ENCRYPTION_ALGORITHM_NAME:\n\t\tGetBootEncryptionAlgorithmName (Irp, irpSp);\n\t\tbreak;\n\n\tcase TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING:\n\t\tif (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput))\n\t\t{\n\t\t\t*(int *) Irp->AssociatedIrp.SystemBuffer = IsHiddenSystemRunning() ? 1 : 0;\n\t\t\tIrp->IoStatus.Information = sizeof (int);\n\t\t\tIrp->IoStatus.Status = STATUS_SUCCESS;\n\t\t}\n\t\tbreak;\n\n\tcase TC_IOCTL_START_DECOY_SYSTEM_WIPE:\n\t\tIrp->IoStatus.Status = StartDecoySystemWipe (DeviceObject, Irp, irpSp);\n\t\tIrp->IoStatus.Information = 0;\n\t\tbreak;\n\n\tcase TC_IOCTL_ABORT_DECOY_SYSTEM_WIPE:\n\t\tIrp->IoStatus.Status = AbortDecoySystemWipe();\n\t\tIrp->IoStatus.Information = 0;\n\t\tbreak;\n\n\tcase TC_IOCTL_GET_DECOY_SYSTEM_WIPE_RESULT:\n\t\tIrp->IoStatus.Status = GetDecoySystemWipeResult();\n\t\tIrp->IoStatus.Information = 0;\n\t\tbreak;\n\n\tcase TC_IOCTL_GET_DECOY_SYSTEM_WIPE_STATUS:\n\t\tGetDecoySystemWipeStatus (Irp, irpSp);\n\t\tbreak;\n\n\tcase TC_IOCTL_WRITE_BOOT_DRIVE_SECTOR:\n\t\tIrp->IoStatus.Status = WriteBootDriveSector (Irp, irpSp);\n\t\tIrp->IoStatus.Information = 0;\n\t\tbreak;\n\n\tcase TC_IOCTL_GET_WARNING_FLAGS:\n\t\tif (ValidateIOBufferSize (Irp, sizeof (GetWarningFlagsRequest), ValidateOutput))\n\t\t{\n\t\t\tGetWarningFlagsRequest *flags = (GetWarningFlagsRequest *) Irp->AssociatedIrp.SystemBuffer;\n\n\t\t\tflags->PagingFileCreationPrevented = PagingFileCreationPrevented;\n\t\t\tPagingFileCreationPrevented = FALSE;\n\t\t\tflags->SystemFavoriteVolumeDirty = SystemFavoriteVolumeDirty;\n\t\t\tSystemFavoriteVolumeDirty = FALSE;\n\n\t\t\tIrp->IoStatus.Information = sizeof (GetWarningFlagsRequest);\n\t\t\tIrp->IoStatus.Status = STATUS_SUCCESS;\n\t\t}\n\t\tbreak;\n\n\tcase TC_IOCTL_SET_SYSTEM_FAVORITE_VOLUME_DIRTY:\n\t\tif (UserCanAccessDriveDevice())\n\t\t{\n\t\t\tSystemFavoriteVolumeDirty = TRUE;\n\t\t\tIrp->IoStatus.Status = STATUS_SUCCESS;\n\t\t}\n\t\telse\n\t\t\tIrp->IoStatus.Status = STATUS_ACCESS_DENIED;\n\n\t\tIrp->IoStatus.Information = 0;\n\t\tbreak;\n\n\tcase TC_IOCTL_REREAD_DRIVER_CONFIG:\n\t\tIrp->IoStatus.Status = ReadRegistryConfigFlags (FALSE);\n\t\tIrp->IoStatus.Information = 0;\n\t\tbreak;\n\n\tcase TC_IOCTL_GET_SYSTEM_DRIVE_DUMP_CONFIG:\n\t\tif (\t(ValidateIOBufferSize (Irp, sizeof (GetSystemDriveDumpConfigRequest), ValidateOutput))\n\t\t\t&&\t(Irp->RequestorMode == KernelMode)\n\t\t\t)\n\t\t{\n\t\t\tGetSystemDriveDumpConfigRequest *request = (GetSystemDriveDumpConfigRequest *) Irp->AssociatedIrp.SystemBuffer;\n\n\t\t\trequest->BootDriveFilterExtension = GetBootDriveFilterExtension();\n\t\t\tif (IsBootDriveMounted() && request->BootDriveFilterExtension)\n\t\t\t{\n\t\t\t\trequest->HwEncryptionEnabled = IsHwEncryptionEnabled();\n\t\t\t\tIrp->IoStatus.Status = STATUS_SUCCESS;\n\t\t\t\tIrp->IoStatus.Information = sizeof (*request);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tIrp->IoStatus.Status = STATUS_INVALID_PARAMETER;\n\t\t\t\tIrp->IoStatus.Information = 0;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\treturn TCCompleteIrp (Irp, STATUS_INVALID_DEVICE_REQUEST, 0);\n\t}\n\n\n#if defined(DEBUG) || defined(DEBUG_TRACE)\n\tif (!NT_SUCCESS (Irp->IoStatus.Status))\n\t{\n\t\tswitch (irpSp->Parameters.DeviceIoControl.IoControlCode)\n\t\t{\n\t\tcase TC_IOCTL_GET_MOUNTED_VOLUMES:\n\t\tcase TC_IOCTL_GET_PASSWORD_CACHE_STATUS:\n\t\tcase TC_IOCTL_GET_PORTABLE_MODE_STATUS:\n\t\tcase TC_IOCTL_SET_PORTABLE_MODE_STATUS:\n\t\tcase TC_IOCTL_OPEN_TEST:\n\t\tcase TC_IOCTL_GET_RESOLVED_SYMLINK:\n\t\tcase TC_IOCTL_GET_DRIVE_PARTITION_INFO:\n\t\tcase TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES:\n\t\tcase TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS:\n\t\tcase TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING:\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tDump (\"IOCTL error 0x%08x\\n\", Irp->IoStatus.Status);\n\t\t}\n\t}\n#endif\n\n\treturn TCCompleteIrp (Irp, Irp->IoStatus.Status, Irp->IoStatus.Information);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Windows: fix low severity vulnerability in driver that allowed reading 3 bytes of kernel stack memory (with a rare possibility of 25 additional bytes). Reported by Tim Harrison.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: std::vector CSoundFile::GetLength(enmGetLengthResetMode adjustMode, GetLengthTarget target)\n{\n\tstd::vector results;\n\tGetLengthType retval;\n\tretval.startOrder = target.startOrder;\n\tretval.startRow = target.startRow;\n\n\t// Are we trying to reach a certain pattern position?\n\tconst bool hasSearchTarget = target.mode != GetLengthTarget::NoTarget;\n\tconst bool adjustSamplePos = (adjustMode & eAdjustSamplePositions) == eAdjustSamplePositions;\n\n\tSEQUENCEINDEX sequence = target.sequence;\n\tif(sequence >= Order.GetNumSequences()) sequence = Order.GetCurrentSequenceIndex();\n\tconst ModSequence &orderList = Order(sequence);\n\n\tGetLengthMemory memory(*this);\n\tCSoundFile::PlayState &playState = *memory.state;\n\t// Temporary visited rows vector (so that GetLength() won't interfere with the player code if the module is playing at the same time)\n\tRowVisitor visitedRows(*this, sequence);\n\n\tplayState.m_nNextRow = playState.m_nRow = target.startRow;\n\tplayState.m_nNextOrder = playState.m_nCurrentOrder = target.startOrder;\n\n\t// Fast LUTs for commands that are too weird / complicated / whatever to emulate in sample position adjust mode.\n\tstd::bitset forbiddenCommands;\n\tstd::bitset forbiddenVolCommands;\n\n\tif(adjustSamplePos)\n\t{\n\t\tforbiddenCommands.set(CMD_ARPEGGIO); forbiddenCommands.set(CMD_PORTAMENTOUP);\n\t\tforbiddenCommands.set(CMD_PORTAMENTODOWN); forbiddenCommands.set(CMD_XFINEPORTAUPDOWN);\n\t\tforbiddenCommands.set(CMD_NOTESLIDEUP); forbiddenCommands.set(CMD_NOTESLIDEUPRETRIG);\n\t\tforbiddenCommands.set(CMD_NOTESLIDEDOWN); forbiddenCommands.set(CMD_NOTESLIDEDOWNRETRIG);\n\t\tforbiddenVolCommands.set(VOLCMD_PORTAUP); forbiddenVolCommands.set(VOLCMD_PORTADOWN);\n\n\t\t// Optimize away channels for which it's pointless to adjust sample positions\n\t\tfor(CHANNELINDEX i = 0; i < GetNumChannels(); i++)\n\t\t{\n\t\t\tif(ChnSettings[i].dwFlags[CHN_MUTE]) memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL;\n\t\t}\n\t\tif(target.mode == GetLengthTarget::SeekPosition && target.pos.order < orderList.size())\n\t\t{\n\t\t\t// If we know where to seek, we can directly rule out any channels on which a new note would be triggered right at the start.\n\t\t\tconst PATTERNINDEX seekPat = orderList[target.pos.order];\n\t\t\tif(Patterns.IsValidPat(seekPat) && Patterns[seekPat].IsValidRow(target.pos.row))\n\t\t\t{\n\t\t\t\tconst ModCommand *m = Patterns[seekPat].GetRow(target.pos.row);\n\t\t\t\tfor(CHANNELINDEX i = 0; i < GetNumChannels(); i++, m++)\n\t\t\t\t{\n\t\t\t\t\tif(m->note == NOTE_NOTECUT || m->note == NOTE_KEYOFF || (m->note == NOTE_FADE && GetNumInstruments())\n\t\t\t\t\t\t|| (m->IsNote() && !m->IsPortamento()))\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// If samples are being synced, force them to resync if tick duration changes\n\tuint32 oldTickDuration = 0;\n\n\tfor (;;)\n\t{\n\t\t// Time target reached.\n\t\tif(target.mode == GetLengthTarget::SeekSeconds && memory.elapsedTime >= target.time)\n\t\t{\n\t\t\tretval.targetReached = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tuint32 rowDelay = 0, tickDelay = 0;\n\t\tplayState.m_nRow = playState.m_nNextRow;\n\t\tplayState.m_nCurrentOrder = playState.m_nNextOrder;\n\n\t\tif(orderList.IsValidPat(playState.m_nCurrentOrder) && playState.m_nRow >= Patterns[orderList[playState.m_nCurrentOrder]].GetNumRows())\n\t\t{\n\t\t\tplayState.m_nRow = 0;\n\t\t\tif(m_playBehaviour[kFT2LoopE60Restart])\n\t\t\t{\n\t\t\t\tplayState.m_nRow = playState.m_nNextPatStartRow;\n\t\t\t\tplayState.m_nNextPatStartRow = 0;\n\t\t\t}\n\t\t\tplayState.m_nCurrentOrder = ++playState.m_nNextOrder;\n\t\t}\n\n\t\t// Check if pattern is valid\n\t\tplayState.m_nPattern = playState.m_nCurrentOrder < orderList.size() ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex();\n\t\tbool positionJumpOnThisRow = false;\n\t\tbool patternBreakOnThisRow = false;\n\t\tbool patternLoopEndedOnThisRow = false, patternLoopStartedOnThisRow = false;\n\n\t\tif(!Patterns.IsValidPat(playState.m_nPattern) && playState.m_nPattern != orderList.GetInvalidPatIndex() && target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order)\n\t\t{\n\t\t\t// Early test: Target is inside +++ or non-existing pattern\n\t\t\tretval.targetReached = true;\n\t\t\tbreak;\n\t\t}\n\n\t\twhile(playState.m_nPattern >= Patterns.Size())\n\t\t{\n\t\t\t// End of song?\n\t\t\tif((playState.m_nPattern == orderList.GetInvalidPatIndex()) || (playState.m_nCurrentOrder >= orderList.size()))\n\t\t\t{\n\t\t\t\tif(playState.m_nCurrentOrder == orderList.GetRestartPos())\n\t\t\t\t\tbreak;\n\t\t\t\telse\n\t\t\t\t\tplayState.m_nCurrentOrder = orderList.GetRestartPos();\n\t\t\t} else\n\t\t\t{\n\t\t\t\tplayState.m_nCurrentOrder++;\n\t\t\t}\n\t\t\tplayState.m_nPattern = (playState.m_nCurrentOrder < orderList.size()) ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex();\n\t\t\tplayState.m_nNextOrder = playState.m_nCurrentOrder;\n\t\t\tif((!Patterns.IsValidPat(playState.m_nPattern)) && visitedRows.IsVisited(playState.m_nCurrentOrder, 0, true))\n\t\t\t{\n\t\t\t\tif(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true))\n\t\t\t\t{\n\t\t\t\t\t// We aren't searching for a specific row, or we couldn't find any more unvisited rows.\n\t\t\t\t\tbreak;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\t// We haven't found the target row yet, but we found some other unplayed row... continue searching from here.\n\t\t\t\t\tretval.duration = memory.elapsedTime;\n\t\t\t\t\tresults.push_back(retval);\n\t\t\t\t\tretval.startRow = playState.m_nRow;\n\t\t\t\t\tretval.startOrder = playState.m_nNextOrder;\n\t\t\t\t\tmemory.Reset();\n\n\t\t\t\t\tplayState.m_nCurrentOrder = playState.m_nNextOrder;\n\t\t\t\t\tplayState.m_nPattern = orderList[playState.m_nCurrentOrder];\n\t\t\t\t\tplayState.m_nNextRow = playState.m_nRow;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(playState.m_nNextOrder == ORDERINDEX_INVALID)\n\t\t{\n\t\t\t// GetFirstUnvisitedRow failed, so there is nothing more to play\n\t\t\tbreak;\n\t\t}\n\n\t\t// Skip non-existing patterns\n\t\tif(!Patterns.IsValidPat(playState.m_nPattern))\n\t\t{\n\t\t\t// If there isn't even a tune, we should probably stop here.\n\t\t\tif(playState.m_nCurrentOrder == orderList.GetRestartPos())\n\t\t\t{\n\t\t\t\tif(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true))\n\t\t\t\t{\n\t\t\t\t\t// We aren't searching for a specific row, or we couldn't find any more unvisited rows.\n\t\t\t\t\tbreak;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\t// We haven't found the target row yet, but we found some other unplayed row... continue searching from here.\n\t\t\t\t\tretval.duration = memory.elapsedTime;\n\t\t\t\t\tresults.push_back(retval);\n\t\t\t\t\tretval.startRow = playState.m_nRow;\n\t\t\t\t\tretval.startOrder = playState.m_nNextOrder;\n\t\t\t\t\tmemory.Reset();\n\t\t\t\t\tplayState.m_nNextRow = playState.m_nRow;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tplayState.m_nNextOrder = playState.m_nCurrentOrder + 1;\n\t\t\tcontinue;\n\t\t}\n\t\t// Should never happen\n\t\tif(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows())\n\t\t\tplayState.m_nRow = 0;\n\n\t\t// Check whether target was reached.\n\t\tif(target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order && playState.m_nRow == target.pos.row)\n\t\t{\n\t\t\tretval.targetReached = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tif(visitedRows.IsVisited(playState.m_nCurrentOrder, playState.m_nRow, true))\n\t\t{\n\t\t\tif(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true))\n\t\t\t{\n\t\t\t\t// We aren't searching for a specific row, or we couldn't find any more unvisited rows.\n\t\t\t\tbreak;\n\t\t\t} else\n\t\t\t{\n\t\t\t\t// We haven't found the target row yet, but we found some other unplayed row... continue searching from here.\n\t\t\t\tretval.duration = memory.elapsedTime;\n\t\t\t\tresults.push_back(retval);\n\t\t\t\tretval.startRow = playState.m_nRow;\n\t\t\t\tretval.startOrder = playState.m_nNextOrder;\n\t\t\t\tmemory.Reset();\n\t\t\t\tplayState.m_nNextRow = playState.m_nRow;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tretval.endOrder = playState.m_nCurrentOrder;\n\t\tretval.endRow = playState.m_nRow;\n\n\t\t// Update next position\n\t\tplayState.m_nNextRow = playState.m_nRow + 1;\n\n\t\t// Jumped to invalid pattern row?\n\t\tif(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows())\n\t\t{\n\t\t\tplayState.m_nRow = 0;\n\t\t}\n\t\t// New pattern?\n\t\tif(!playState.m_nRow)\n\t\t{\n\t\t\tfor(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++)\n\t\t\t{\n\t\t\t\tmemory.chnSettings[chn].patLoop = memory.elapsedTime;\n\t\t\t\tmemory.chnSettings[chn].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t}\n\t\t}\n\n\t\tModChannel *pChn = playState.Chn;\n\t\t\n\t\t// For various effects, we need to know first how many ticks there are in this row.\n\t\tconst ModCommand *p = Patterns[playState.m_nPattern].GetpModCommand(playState.m_nRow, 0);\n\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, p++)\n\t\t{\n\t\t\tif(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE])\t// not even effects are processed on muted S3M channels\n\t\t\t\tcontinue;\n\t\t\tif(p->IsPcNote())\n\t\t\t{\n#ifndef NO_PLUGINS\n\t\t\t\tif((adjustMode & eAdjust) && p->instr > 0 && p->instr <= MAX_MIXPLUGINS)\n\t\t\t\t{\n\t\t\t\t\tmemory.plugParams[std::make_pair(p->instr, p->GetValueVolCol())] = p->GetValueEffectCol();\n\t\t\t\t}\n#endif // NO_PLUGINS\n\t\t\t\tpChn[nChn].rowCommand.Clear();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tpChn[nChn].rowCommand = *p;\n\t\t\tswitch(p->command)\n\t\t\t{\n\t\t\tcase CMD_SPEED:\n\t\t\t\tSetSpeed(playState, p->param);\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_TEMPO:\n\t\t\t\tif(m_playBehaviour[kMODVBlankTiming])\n\t\t\t\t{\n\t\t\t\t\t// ProTracker MODs with VBlank timing: All Fxx parameters set the tick count.\n\t\t\t\t\tif(p->param != 0) SetSpeed(playState, p->param);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_S3MCMDEX:\n\t\t\t\tif((p->param & 0xF0) == 0x60)\n\t\t\t\t{\n\t\t\t\t\t// Fine Pattern Delay\n\t\t\t\t\ttickDelay += (p->param & 0x0F);\n\t\t\t\t} else if((p->param & 0xF0) == 0xE0 && !rowDelay)\n\t\t\t\t{\n\t\t\t\t\t// Pattern Delay\n\t\t\t\t\tif(!(GetType() & MOD_TYPE_S3M) || (p->param & 0x0F) != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t// While Impulse Tracker *does* count S60 as a valid row delay (and thus ignores any other row delay commands on the right),\n\t\t\t\t\t\t// Scream Tracker 3 simply ignores such commands.\n\t\t\t\t\t\trowDelay = 1 + (p->param & 0x0F);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_MODCMDEX:\n\t\t\t\tif((p->param & 0xF0) == 0xE0)\n\t\t\t\t{\n\t\t\t\t\t// Pattern Delay\n\t\t\t\t\trowDelay = 1 + (p->param & 0x0F);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(rowDelay == 0) rowDelay = 1;\n\t\tconst uint32 numTicks = (playState.m_nMusicSpeed + tickDelay) * rowDelay;\n\t\tconst uint32 nonRowTicks = numTicks - rowDelay;\n\n\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++) if(!pChn->rowCommand.IsEmpty())\n\t\t{\n\t\t\tif(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE])\t// not even effects are processed on muted S3M channels\n\t\t\t\tcontinue;\n\t\t\tModCommand::COMMAND command = pChn->rowCommand.command;\n\t\t\tModCommand::PARAM param = pChn->rowCommand.param;\n\t\t\tModCommand::NOTE note = pChn->rowCommand.note;\n\n\t\t\tif (pChn->rowCommand.instr)\n\t\t\t{\n\t\t\t\tpChn->nNewIns = pChn->rowCommand.instr;\n\t\t\t\tpChn->nLastNote = NOTE_NONE;\n\t\t\t\tmemory.chnSettings[nChn].vol = 0xFF;\n\t\t\t}\n\t\t\tif (pChn->rowCommand.IsNote()) pChn->nLastNote = note;\n\n\t\t\t// Update channel panning\n\t\t\tif(pChn->rowCommand.IsNote() || pChn->rowCommand.instr)\n\t\t\t{\n\t\t\t\tSAMPLEINDEX smp = 0;\n\t\t\t\tif(GetNumInstruments())\n\t\t\t\t{\n\t\t\t\t\tModInstrument *pIns;\n\t\t\t\t\tif(pChn->nNewIns <= GetNumInstruments() && (pIns = Instruments[pChn->nNewIns]) != nullptr)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(pIns->dwFlags[INS_SETPANNING])\n\t\t\t\t\t\t\tpChn->nPan = pIns->nPan;\n\t\t\t\t\t\tif(ModCommand::IsNote(note))\n\t\t\t\t\t\t\tsmp = pIns->Keyboard[note - NOTE_MIN];\n\t\t\t\t\t}\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tsmp = pChn->nNewIns;\n\t\t\t\t}\n\t\t\t\tif(smp > 0 && smp <= GetNumSamples() && Samples[smp].uFlags[CHN_PANNING])\n\t\t\t\t{\n\t\t\t\t\tpChn->nPan = Samples[smp].nPan;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tswitch(pChn->rowCommand.volcmd)\n\t\t\t{\n\t\t\tcase VOLCMD_VOLUME:\n\t\t\t\tmemory.chnSettings[nChn].vol = pChn->rowCommand.vol;\n\t\t\t\tbreak;\n\t\t\tcase VOLCMD_VOLSLIDEUP:\n\t\t\tcase VOLCMD_VOLSLIDEDOWN:\n\t\t\t\tif(pChn->rowCommand.vol != 0)\n\t\t\t\t\tpChn->nOldVolParam = pChn->rowCommand.vol;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tswitch(command)\n\t\t\t{\n\t\t\t// Position Jump\n\t\t\tcase CMD_POSITIONJUMP:\n\t\t\t\tpositionJumpOnThisRow = true;\n\t\t\t\tplayState.m_nNextOrder = static_cast(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn));\n\t\t\t\tplayState.m_nNextPatStartRow = 0; // FT2 E60 bug\n\t\t\t\t// see https://forum.openmpt.org/index.php?topic=2769.0 - FastTracker resets Dxx if Bxx is called _after_ Dxx\n\t\t\t\t// Test case: PatternJump.mod\n\t\t\t\tif(!patternBreakOnThisRow || (GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM)))\n\t\t\t\t\tplayState.m_nNextRow = 0;\n\n\t\t\t\tif (adjustMode & eAdjust)\n\t\t\t\t{\n\t\t\t\t\tpChn->nPatternLoopCount = 0;\n\t\t\t\t\tpChn->nPatternLoop = 0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t// Pattern Break\n\t\t\tcase CMD_PATTERNBREAK:\n\t\t\t\t{\n\t\t\t\t\tROWINDEX row = PatternBreak(playState, nChn, param);\n\t\t\t\t\tif(row != ROWINDEX_INVALID)\n\t\t\t\t\t{\n\t\t\t\t\t\tpatternBreakOnThisRow = true;\n\t\t\t\t\t\tplayState.m_nNextRow = row;\n\n\t\t\t\t\t\tif(!positionJumpOnThisRow)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tplayState.m_nNextOrder = playState.m_nCurrentOrder + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(adjustMode & eAdjust)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpChn->nPatternLoopCount = 0;\n\t\t\t\t\t\t\tpChn->nPatternLoop = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t// Set Tempo\n\t\t\tcase CMD_TEMPO:\n\t\t\t\tif(!m_playBehaviour[kMODVBlankTiming])\n\t\t\t\t{\n\t\t\t\t\tTEMPO tempo(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn), 0);\n\t\t\t\t\tif ((adjustMode & eAdjust) && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT)))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (tempo.GetInt()) pChn->nOldTempo = static_cast(tempo.GetInt()); else tempo.Set(pChn->nOldTempo);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (tempo.GetInt() >= 0x20) playState.m_nMusicTempo = tempo;\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t// Tempo Slide\n\t\t\t\t\t\tTEMPO tempoDiff((tempo.GetInt() & 0x0F) * nonRowTicks, 0);\n\t\t\t\t\t\tif ((tempo.GetInt() & 0xF0) == 0x10)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tplayState.m_nMusicTempo += tempoDiff;\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(tempoDiff < playState.m_nMusicTempo)\n\t\t\t\t\t\t\t\tplayState.m_nMusicTempo -= tempoDiff;\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tplayState.m_nMusicTempo.Set(0);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tTEMPO tempoMin = GetModSpecifications().GetTempoMin(), tempoMax = GetModSpecifications().GetTempoMax();\n\t\t\t\t\tif(m_playBehaviour[kTempoClamp])\t// clamp tempo correctly in compatible mode\n\t\t\t\t\t{\n\t\t\t\t\t\ttempoMax.Set(255);\n\t\t\t\t\t}\n\t\t\t\t\tLimit(playState.m_nMusicTempo, tempoMin, tempoMax);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_S3MCMDEX:\n\t\t\t\tswitch(param & 0xF0)\n\t\t\t\t{\n\t\t\t\tcase 0x90:\n\t\t\t\t\tif(param <= 0x91)\n\t\t\t\t\t{\n\t\t\t\t\t\tpChn->dwFlags.set(CHN_SURROUND, param == 0x91);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 0xA0:\n\t\t\t\t\t// High sample offset\n\t\t\t\t\tpChn->nOldHiOffset = param & 0x0F;\n\t\t\t\t\tbreak;\n\t\t\t\t\n\t\t\t\tcase 0xB0:\n\t\t\t\t\t// Pattern Loop\n\t\t\t\t\tif (param & 0x0F)\n\t\t\t\t\t{\n\t\t\t\t\t\tpatternLoopEndedOnThisRow = true;\n\t\t\t\t\t} else\n\t\t\t\t\t{\n\t\t\t\t\t\tCHANNELINDEX firstChn = nChn, lastChn = nChn;\n\t\t\t\t\t\tif(GetType() == MOD_TYPE_S3M)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// ST3 has only one global loop memory.\n\t\t\t\t\t\t\tfirstChn = 0;\n\t\t\t\t\t\t\tlastChn = GetNumChannels() - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor(CHANNELINDEX c = firstChn; c <= lastChn; c++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmemory.chnSettings[c].patLoop = memory.elapsedTime;\n\t\t\t\t\t\t\tmemory.chnSettings[c].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t\t\t\t\tmemory.chnSettings[c].patLoopStart = playState.m_nRow;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpatternLoopStartedOnThisRow = true;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 0xF0:\n\t\t\t\t\t// Active macro\n\t\t\t\t\tpChn->nActiveMacro = param & 0x0F;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_MODCMDEX:\n\t\t\t\tswitch(param & 0xF0)\n\t\t\t\t{\n\t\t\t\tcase 0x60:\n\t\t\t\t\t// Pattern Loop\n\t\t\t\t\tif (param & 0x0F)\n\t\t\t\t\t{\n\t\t\t\t\t\tplayState.m_nNextPatStartRow = memory.chnSettings[nChn].patLoopStart; // FT2 E60 bug\n\t\t\t\t\t\tpatternLoopEndedOnThisRow = true;\n\t\t\t\t\t} else\n\t\t\t\t\t{\n\t\t\t\t\t\tpatternLoopStartedOnThisRow = true;\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoop = memory.elapsedTime;\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopStart = playState.m_nRow;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 0xF0:\n\t\t\t\t\t// Active macro\n\t\t\t\t\tpChn->nActiveMacro = param & 0x0F;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_XFINEPORTAUPDOWN:\n\t\t\t\t// ignore high offset in compatible mode\n\t\t\t\tif(((param & 0xF0) == 0xA0) && !m_playBehaviour[kFT2RestrictXCommand]) pChn->nOldHiOffset = param & 0x0F;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// The following calculations are not interesting if we just want to get the song length.\n\t\t\tif (!(adjustMode & eAdjust)) continue;\n\t\t\tswitch(command)\n\t\t\t{\n\t\t\t// Portamento Up/Down\n\t\t\tcase CMD_PORTAMENTOUP:\n\t\t\t\tif(param)\n\t\t\t\t{\n\t\t\t\t\t// FT2 compatibility: Separate effect memory for all portamento commands\n\t\t\t\t\t// Test case: Porta-LinkMem.xm\n\t\t\t\t\tif(!m_playBehaviour[kFT2PortaUpDownMemory])\n\t\t\t\t\t\tpChn->nOldPortaDown = param;\n\t\t\t\t\tpChn->nOldPortaUp = param;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase CMD_PORTAMENTODOWN:\n\t\t\t\tif(param)\n\t\t\t\t{\n\t\t\t\t\t// FT2 compatibility: Separate effect memory for all portamento commands\n\t\t\t\t\t// Test case: Porta-LinkMem.xm\n\t\t\t\t\tif(!m_playBehaviour[kFT2PortaUpDownMemory])\n\t\t\t\t\t\tpChn->nOldPortaUp = param;\n\t\t\t\t\tpChn->nOldPortaDown = param;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t// Tone-Portamento\n\t\t\tcase CMD_TONEPORTAMENTO:\n\t\t\t\tif (param) pChn->nPortamentoSlide = param << 2;\n\t\t\t\tbreak;\n\t\t\t// Offset\n\t\t\tcase CMD_OFFSET:\n\t\t\t\tif (param) pChn->oldOffset = param << 8;\n\t\t\t\tbreak;\n\t\t\t// Volume Slide\n\t\t\tcase CMD_VOLUMESLIDE:\n\t\t\tcase CMD_TONEPORTAVOL:\n\t\t\t\tif (param) pChn->nOldVolumeSlide = param;\n\t\t\t\tbreak;\n\t\t\t// Set Volume\n\t\t\tcase CMD_VOLUME:\n\t\t\t\tmemory.chnSettings[nChn].vol = param;\n\t\t\t\tbreak;\n\t\t\t// Global Volume\n\t\t\tcase CMD_GLOBALVOLUME:\n\t\t\t\tif(!(GetType() & GLOBALVOL_7BIT_FORMATS) && param < 128) param *= 2;\n\t\t\t\t// IT compatibility 16. ST3 and IT ignore out-of-range values\n\t\t\t\tif(param <= 128)\n\t\t\t\t{\n\t\t\t\t\tplayState.m_nGlobalVolume = param * 2;\n\t\t\t\t} else if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_S3M)))\n\t\t\t\t{\n\t\t\t\t\tplayState.m_nGlobalVolume = 256;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t// Global Volume Slide\n\t\t\tcase CMD_GLOBALVOLSLIDE:\n\t\t\t\tif(m_playBehaviour[kPerChannelGlobalVolSlide])\n\t\t\t\t{\n\t\t\t\t\t// IT compatibility 16. Global volume slide params are stored per channel (FT2/IT)\n\t\t\t\t\tif (param) pChn->nOldGlobalVolSlide = param; else param = pChn->nOldGlobalVolSlide;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tif (param) playState.Chn[0].nOldGlobalVolSlide = param; else param = playState.Chn[0].nOldGlobalVolSlide;\n\t\t\t\t}\n\t\t\t\tif (((param & 0x0F) == 0x0F) && (param & 0xF0))\n\t\t\t\t{\n\t\t\t\t\tparam >>= 4;\n\t\t\t\t\tif (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;\n\t\t\t\t\tplayState.m_nGlobalVolume += param << 1;\n\t\t\t\t} else if (((param & 0xF0) == 0xF0) && (param & 0x0F))\n\t\t\t\t{\n\t\t\t\t\tparam = (param & 0x0F) << 1;\n\t\t\t\t\tif (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;\n\t\t\t\t\tplayState.m_nGlobalVolume -= param;\n\t\t\t\t} else if (param & 0xF0)\n\t\t\t\t{\n\t\t\t\t\tparam >>= 4;\n\t\t\t\t\tparam <<= 1;\n\t\t\t\t\tif (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;\n\t\t\t\t\tplayState.m_nGlobalVolume += param * nonRowTicks;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tparam = (param & 0x0F) << 1;\n\t\t\t\t\tif (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;\n\t\t\t\t\tplayState.m_nGlobalVolume -= param * nonRowTicks;\n\t\t\t\t}\n\t\t\t\tLimit(playState.m_nGlobalVolume, 0, 256);\n\t\t\t\tbreak;\n\t\t\tcase CMD_CHANNELVOLUME:\n\t\t\t\tif (param <= 64) pChn->nGlobalVol = param;\n\t\t\t\tbreak;\n\t\t\tcase CMD_CHANNELVOLSLIDE:\n\t\t\t\t{\n\t\t\t\t\tif (param) pChn->nOldChnVolSlide = param; else param = pChn->nOldChnVolSlide;\n\t\t\t\t\tint32 volume = pChn->nGlobalVol;\n\t\t\t\t\tif((param & 0x0F) == 0x0F && (param & 0xF0))\n\t\t\t\t\t\tvolume += (param >> 4);\t\t// Fine Up\n\t\t\t\t\telse if((param & 0xF0) == 0xF0 && (param & 0x0F))\n\t\t\t\t\t\tvolume -= (param & 0x0F);\t// Fine Down\n\t\t\t\t\telse if(param & 0x0F)\t\t\t// Down\n\t\t\t\t\t\tvolume -= (param & 0x0F) * nonRowTicks;\n\t\t\t\t\telse\t\t\t\t\t\t\t// Up\n\t\t\t\t\t\tvolume += ((param & 0xF0) >> 4) * nonRowTicks;\n\t\t\t\t\tLimit(volume, 0, 64);\n\t\t\t\t\tpChn->nGlobalVol = volume;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase CMD_PANNING8:\n\t\t\t\tPanning(pChn, param, Pan8bit);\n\t\t\t\tbreak;\n\t\t\tcase CMD_MODCMDEX:\n\t\t\t\tif(param < 0x10)\n\t\t\t\t{\n\t\t\t\t\t// LED filter\n\t\t\t\t\tfor(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++)\n\t\t\t\t\t{\n\t\t\t\t\t\tplayState.Chn[chn].dwFlags.set(CHN_AMIGAFILTER, !(param & 1));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tMPT_FALLTHROUGH;\n\t\t\tcase CMD_S3MCMDEX:\n\t\t\t\tif((param & 0xF0) == 0x80)\n\t\t\t\t{\n\t\t\t\t\tPanning(pChn, (param & 0x0F), Pan4bit);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_VIBRATOVOL:\n\t\t\t\tif (param) pChn->nOldVolumeSlide = param;\n\t\t\t\tparam = 0;\n\t\t\t\tMPT_FALLTHROUGH;\n\t\t\tcase CMD_VIBRATO:\n\t\t\t\tVibrato(pChn, param);\n\t\t\t\tbreak;\n\t\t\tcase CMD_FINEVIBRATO:\n\t\t\t\tFineVibrato(pChn, param);\n\t\t\t\tbreak;\n\t\t\tcase CMD_TREMOLO:\n\t\t\t\tTremolo(pChn, param);\n\t\t\t\tbreak;\n\t\t\tcase CMD_PANBRELLO:\n\t\t\t\tPanbrello(pChn, param);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tswitch(pChn->rowCommand.volcmd)\n\t\t\t{\n\t\t\tcase VOLCMD_PANNING:\n\t\t\t\tPanning(pChn, pChn->rowCommand.vol, Pan6bit);\n\t\t\t\tbreak;\n\n\t\t\tcase VOLCMD_VIBRATOSPEED:\n\t\t\t\t// FT2 does not automatically enable vibrato with the \"set vibrato speed\" command\n\t\t\t\tif(m_playBehaviour[kFT2VolColVibrato])\n\t\t\t\t\tpChn->nVibratoSpeed = pChn->rowCommand.vol & 0x0F;\n\t\t\t\telse\n\t\t\t\t\tVibrato(pChn, pChn->rowCommand.vol << 4);\n\t\t\t\tbreak;\n\t\t\tcase VOLCMD_VIBRATODEPTH:\n\t\t\t\tVibrato(pChn, pChn->rowCommand.vol);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Process vibrato / tremolo / panbrello\n\t\t\tswitch(pChn->rowCommand.command)\n\t\t\t{\n\t\t\tcase CMD_VIBRATO:\n\t\t\tcase CMD_FINEVIBRATO:\n\t\t\tcase CMD_VIBRATOVOL:\n\t\t\t\tif(adjustMode & eAdjust)\n\t\t\t\t{\n\t\t\t\t\tuint32 vibTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks;\n\t\t\t\t\tuint32 inc = pChn->nVibratoSpeed * vibTicks;\n\t\t\t\t\tif(m_playBehaviour[kITVibratoTremoloPanbrello])\n\t\t\t\t\t\tinc *= 4;\n\t\t\t\t\tpChn->nVibratoPos += static_cast(inc);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_TREMOLO:\n\t\t\t\tif(adjustMode & eAdjust)\n\t\t\t\t{\n\t\t\t\t\tuint32 tremTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks;\n\t\t\t\t\tuint32 inc = pChn->nTremoloSpeed * tremTicks;\n\t\t\t\t\tif(m_playBehaviour[kITVibratoTremoloPanbrello])\n\t\t\t\t\t\tinc *= 4;\n\t\t\t\t\tpChn->nTremoloPos += static_cast(inc);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_PANBRELLO:\n\t\t\t\tif(adjustMode & eAdjust)\n\t\t\t\t{\n\t\t\t\t\t// Panbrello effect is permanent in compatible mode, so actually apply panbrello for the last tick of this row\n\t\t\t\t\tpChn->nPanbrelloPos += static_cast(pChn->nPanbrelloSpeed * (numTicks - 1));\n\t\t\t\t\tProcessPanbrello(pChn);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// Interpret F00 effect in XM files as \"stop song\"\n\t\tif(GetType() == MOD_TYPE_XM && playState.m_nMusicSpeed == uint16_max)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\n\t\tplayState.m_nCurrentRowsPerBeat = m_nDefaultRowsPerBeat;\n\t\tif(Patterns[playState.m_nPattern].GetOverrideSignature())\n\t\t{\n\t\t\tplayState.m_nCurrentRowsPerBeat = Patterns[playState.m_nPattern].GetRowsPerBeat();\n\t\t}\n\n\t\tconst uint32 tickDuration = GetTickDuration(playState);\n\t\tconst uint32 rowDuration = tickDuration * numTicks;\n\t\tmemory.elapsedTime += static_cast(rowDuration) / static_cast(m_MixerSettings.gdwMixingFreq);\n\t\tplayState.m_lTotalSampleCount += rowDuration;\n\n\t\tif(adjustSamplePos)\n\t\t{\n\t\t\t// Super experimental and dirty sample seeking\n\t\t\tpChn = playState.Chn;\n\t\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++)\n\t\t\t{\n\t\t\t\tif(memory.chnSettings[nChn].ticksToRender == GetLengthMemory::IGNORE_CHANNEL)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tuint32 startTick = 0;\n\t\t\t\tconst ModCommand &m = pChn->rowCommand;\n\t\t\t\tuint32 paramHi = m.param >> 4, paramLo = m.param & 0x0F;\n\t\t\t\tbool porta = m.command == CMD_TONEPORTAMENTO || m.command == CMD_TONEPORTAVOL || m.volcmd == VOLCMD_TONEPORTAMENTO;\n\t\t\t\tbool stopNote = patternLoopStartedOnThisRow;\t// It's too much trouble to keep those pattern loops in sync...\n\n\t\t\t\tif(m.instr) pChn->proTrackerOffset = 0;\n\t\t\t\tif(m.IsNote())\n\t\t\t\t{\n\t\t\t\t\tif(porta && memory.chnSettings[nChn].incChanged)\n\t\t\t\t\t{\n\t\t\t\t\t\t// If there's a portamento, the current channel increment mustn't be 0 in NoteChange()\n\t\t\t\t\t\tpChn->increment = GetChannelIncrement(pChn, pChn->nPeriod, 0);\n\t\t\t\t\t}\n\t\t\t\t\tint32 setPan = pChn->nPan;\n\t\t\t\t\tpChn->nNewNote = pChn->nLastNote;\n\t\t\t\t\tif(pChn->nNewIns != 0) InstrumentChange(pChn, pChn->nNewIns, porta);\n\t\t\t\t\tNoteChange(pChn, m.note, porta);\n\t\t\t\t\tmemory.chnSettings[nChn].incChanged = true;\n\n\t\t\t\t\tif((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xD0 && paramLo < numTicks)\n\t\t\t\t\t{\n\t\t\t\t\t\tstartTick = paramLo;\n\t\t\t\t\t} else if(m.command == CMD_DELAYCUT && paramHi < numTicks)\n\t\t\t\t\t{\n\t\t\t\t\t\tstartTick = paramHi;\n\t\t\t\t\t}\n\t\t\t\t\tif(rowDelay > 1 && startTick != 0 && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT)))\n\t\t\t\t\t{\n\t\t\t\t\t\tstartTick += (playState.m_nMusicSpeed + tickDelay) * (rowDelay - 1);\n\t\t\t\t\t}\n\t\t\t\t\tif(!porta) memory.chnSettings[nChn].ticksToRender = 0;\n\n\t\t\t\t\t// Panning commands have to be re-applied after a note change with potential pan change.\n\t\t\t\t\tif(m.command == CMD_PANNING8\n\t\t\t\t\t\t|| ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && paramHi == 0x8)\n\t\t\t\t\t\t|| m.volcmd == VOLCMD_PANNING)\n\t\t\t\t\t{\n\t\t\t\t\t\tpChn->nPan = setPan;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(m.command == CMD_OFFSET)\n\t\t\t\t\t{\n\t\t\t\t\t\tbool isExtended = false;\n\t\t\t\t\t\tSmpLength offset = CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn, &isExtended);\n\t\t\t\t\t\tif(!isExtended)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\toffset <<= 8;\n\t\t\t\t\t\t\tif(offset == 0) offset = pChn->oldOffset;\n\t\t\t\t\t\t\toffset += static_cast(pChn->nOldHiOffset) << 16;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tSampleOffset(*pChn, offset);\n\t\t\t\t\t} else if(m.command == CMD_OFFSETPERCENTAGE)\n\t\t\t\t\t{\n\t\t\t\t\t\tSampleOffset(*pChn, Util::muldiv_unsigned(pChn->nLength, m.param, 255));\n\t\t\t\t\t} else if(m.command == CMD_REVERSEOFFSET && pChn->pModSample != nullptr)\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\t// Re-sync what we've got so far\n\t\t\t\t\t\tReverseSampleOffset(*pChn, m.param);\n\t\t\t\t\t\tstartTick = playState.m_nMusicSpeed - 1;\n\t\t\t\t\t} else if(m.volcmd == VOLCMD_OFFSET)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(m.vol <= CountOf(pChn->pModSample->cues) && pChn->pModSample != nullptr)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSmpLength offset;\n\t\t\t\t\t\t\tif(m.vol == 0)\n\t\t\t\t\t\t\t\toffset = pChn->oldOffset;\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\toffset = pChn->oldOffset = pChn->pModSample->cues[m.vol - 1];\n\t\t\t\t\t\t\tSampleOffset(*pChn, offset);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(m.note == NOTE_KEYOFF || m.note == NOTE_NOTECUT || (m.note == NOTE_FADE && GetNumInstruments())\n\t\t\t\t\t|| ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xC0 && paramLo < numTicks)\n\t\t\t\t\t|| (m.command == CMD_DELAYCUT && paramLo != 0 && startTick + paramLo < numTicks))\n\t\t\t\t{\n\t\t\t\t\tstopNote = true;\n\t\t\t\t}\n\n\t\t\t\tif(m.command == CMD_VOLUME)\n\t\t\t\t{\n\t\t\t\t\tpChn->nVolume = m.param * 4;\n\t\t\t\t} else if(m.volcmd == VOLCMD_VOLUME)\n\t\t\t\t{\n\t\t\t\t\tpChn->nVolume = m.vol * 4;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(pChn->pModSample && !stopNote)\n\t\t\t\t{\n\t\t\t\t\t// Check if we don't want to emulate some effect and thus stop processing.\n\t\t\t\t\tif(m.command < MAX_EFFECTS)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(forbiddenCommands[m.command])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstopNote = true;\n\t\t\t\t\t\t} else if(m.command == CMD_MODCMDEX)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// Special case: Slides using extended commands\n\t\t\t\t\t\t\tswitch(m.param & 0xF0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcase 0x10:\n\t\t\t\t\t\t\tcase 0x20:\n\t\t\t\t\t\t\t\tstopNote = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif(m.volcmd < forbiddenVolCommands.size() && forbiddenVolCommands[m.volcmd])\n\t\t\t\t\t{\n\t\t\t\t\t\tstopNote = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(stopNote)\n\t\t\t\t{\n\t\t\t\t\tpChn->Stop();\n\t\t\t\t\tmemory.chnSettings[nChn].ticksToRender = 0;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tif(oldTickDuration != tickDuration && oldTickDuration != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\t// Re-sync what we've got so far\n\t\t\t\t\t}\n\n\t\t\t\t\tswitch(m.command)\n\t\t\t\t\t{\n\t\t\t\t\tcase CMD_TONEPORTAVOL:\n\t\t\t\t\tcase CMD_VOLUMESLIDE:\n\t\t\t\t\tcase CMD_VIBRATOVOL:\n\t\t\t\t\t\tif(m.param || (GetType() != MOD_TYPE_MOD))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor(uint32 i = 0; i < numTicks; i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tpChn->isFirstTick = (i == 0);\n\t\t\t\t\t\t\t\tVolumeSlide(pChn, m.param);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase CMD_MODCMDEX:\n\t\t\t\t\t\tif((m.param & 0x0F) || (GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2)))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpChn->isFirstTick = true;\n\t\t\t\t\t\t\tswitch(m.param & 0xF0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcase 0xA0: FineVolumeUp(pChn, m.param & 0x0F, false); break;\n\t\t\t\t\t\t\tcase 0xB0: FineVolumeDown(pChn, m.param & 0x0F, false); break;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase CMD_S3MCMDEX:\n\t\t\t\t\t\tif(m.param == 0x9E)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// Play forward\n\t\t\t\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\t// Re-sync what we've got so far\n\t\t\t\t\t\t\tpChn->dwFlags.reset(CHN_PINGPONGFLAG);\n\t\t\t\t\t\t} else if(m.param == 0x9F)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// Reverse\n\t\t\t\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\t// Re-sync what we've got so far\n\t\t\t\t\t\t\tpChn->dwFlags.set(CHN_PINGPONGFLAG);\n\t\t\t\t\t\t\tif(!pChn->position.GetInt() && pChn->nLength && (m.IsNote() || !pChn->dwFlags[CHN_LOOP]))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tpChn->position.Set(pChn->nLength - 1, SamplePosition::fractMax);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if((m.param & 0xF0) == 0x70)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// TODO\n\t\t\t\t\t\t\t//ExtendedS3MCommands(nChn, param);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tpChn->isFirstTick = true;\n\t\t\t\t\tswitch(m.volcmd)\n\t\t\t\t\t{\n\t\t\t\t\tcase VOLCMD_FINEVOLUP:\t\tFineVolumeUp(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break;\n\t\t\t\t\tcase VOLCMD_FINEVOLDOWN:\tFineVolumeDown(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break;\n\t\t\t\t\tcase VOLCMD_VOLSLIDEUP:\n\t\t\t\t\tcase VOLCMD_VOLSLIDEDOWN:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// IT Compatibility: Volume column volume slides have their own memory\n\t\t\t\t\t\t\t// Test case: VolColMemory.it\n\t\t\t\t\t\t\tModCommand::VOL vol = m.vol;\n\t\t\t\t\t\t\tif(vol == 0 && m_playBehaviour[kITVolColMemory])\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvol = pChn->nOldVolParam;\n\t\t\t\t\t\t\t\tif(vol == 0)\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif(m.volcmd == VOLCMD_VOLSLIDEUP)\n\t\t\t\t\t\t\t\tvol <<= 4;\n\t\t\t\t\t\t\tfor(uint32 i = 0; i < numTicks; i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tpChn->isFirstTick = (i == 0);\n\t\t\t\t\t\t\t\tVolumeSlide(pChn, vol);\n\t\t\t\t\t\t\t}\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\tif(porta)\n\t\t\t\t\t{\n\t\t\t\t\t\t// Portamento needs immediate syncing, as the pitch changes on each tick\n\t\t\t\t\t\tuint32 portaTick = memory.chnSettings[nChn].ticksToRender + startTick + 1;\n\t\t\t\t\t\tmemory.chnSettings[nChn].ticksToRender += numTicks;\n\t\t\t\t\t\tmemory.RenderChannel(nChn, tickDuration, portaTick);\n\t\t\t\t\t} else\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.chnSettings[nChn].ticksToRender += (numTicks - startTick);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\toldTickDuration = tickDuration;\n\n\t\t// Pattern loop is not executed in FT2 if there are any position jump or pattern break commands on the same row.\n\t\t// Pattern loop is not executed in IT if there are any position jump commands on the same row.\n\t\t// Test case for FT2 exception: PatLoop-Jumps.xm, PatLoop-Various.xm\n\t\t// Test case for IT: exception: LoopBreak.it\n\t\tif(patternLoopEndedOnThisRow\n\t\t\t&& (!m_playBehaviour[kFT2PatternLoopWithJumps] || !(positionJumpOnThisRow || patternBreakOnThisRow))\n\t\t\t&& (!m_playBehaviour[kITPatternLoopWithJumps] || !positionJumpOnThisRow))\n\t\t{\n\t\t\tstd::map startTimes;\n\t\t\t// This is really just a simple estimation for nested pattern loops. It should handle cases correctly where all parallel loops start and end on the same row.\n\t\t\t// If one of them starts or ends \"in between\", it will most likely calculate a wrong duration.\n\t\t\t// For S3M files, it's also way off.\n\t\t\tpChn = playState.Chn;\n\t\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++)\n\t\t\t{\n\t\t\t\tModCommand::COMMAND command = pChn->rowCommand.command;\n\t\t\t\tModCommand::PARAM param = pChn->rowCommand.param;\n\t\t\t\tif((command == CMD_S3MCMDEX && param >= 0xB1 && param <= 0xBF)\n\t\t\t\t\t|| (command == CMD_MODCMDEX && param >= 0x61 && param <= 0x6F))\n\t\t\t\t{\n\t\t\t\t\tconst double start = memory.chnSettings[nChn].patLoop;\n\t\t\t\t\tif(!startTimes[start]) startTimes[start] = 1;\n\t\t\t\t\tstartTimes[start] = mpt::lcm(startTimes[start], 1 + (param & 0x0F));\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor(const auto &i : startTimes)\n\t\t\t{\n\t\t\t\tmemory.elapsedTime += (memory.elapsedTime - i.first) * (double)(i.second - 1);\n\t\t\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++)\n\t\t\t\t{\n\t\t\t\t\tif(memory.chnSettings[nChn].patLoop == i.first)\n\t\t\t\t\t{\n\t\t\t\t\t\tplayState.m_lTotalSampleCount += (playState.m_lTotalSampleCount - memory.chnSettings[nChn].patLoopSmp) * (i.second - 1);\n\t\t\t\t\t\tif(m_playBehaviour[kITPatternLoopTargetReset] || (GetType() == MOD_TYPE_S3M))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmemory.chnSettings[nChn].patLoop = memory.elapsedTime;\n\t\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopStart = playState.m_nRow + 1;\n\t\t\t\t\t\t}\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\tif(GetType() == MOD_TYPE_IT)\n\t\t\t{\n\t\t\t\t// IT pattern loop start row update - at the end of a pattern loop, set pattern loop start to next row (for upcoming pattern loops with missing SB0)\n\t\t\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++)\n\t\t\t\t{\n\t\t\t\t\tif((pChn->rowCommand.command == CMD_S3MCMDEX && pChn->rowCommand.param >= 0xB1 && pChn->rowCommand.param <= 0xBF))\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoop = memory.elapsedTime;\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now advance the sample positions for sample seeking on channels that are still playing\n\tif(adjustSamplePos)\n\t{\n\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++)\n\t\t{\n\t\t\tif(memory.chnSettings[nChn].ticksToRender != GetLengthMemory::IGNORE_CHANNEL)\n\t\t\t{\n\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\n\t\t\t}\n\t\t}\n\t}\n\n\tif(retval.targetReached || target.mode == GetLengthTarget::NoTarget)\n\t{\n\t\tretval.lastOrder = playState.m_nCurrentOrder;\n\t\tretval.lastRow = playState.m_nRow;\n\t}\n\tretval.duration = memory.elapsedTime;\n\tresults.push_back(retval);\n\n\t// Store final variables\n\tif(adjustMode & eAdjust)\n\t{\n\t\tif(retval.targetReached || target.mode == GetLengthTarget::NoTarget)\n\t\t{\n\t\t\t// Target found, or there is no target (i.e. play whole song)...\n\t\t\tm_PlayState = std::move(playState);\n\t\t\tm_PlayState.m_nNextRow = m_PlayState.m_nRow;\n\t\t\tm_PlayState.m_nFrameDelay = m_PlayState.m_nPatternDelay = 0;\n\t\t\tm_PlayState.m_nTickCount = Util::MaxValueOfType(m_PlayState.m_nTickCount) - 1;\n\t\t\tm_PlayState.m_bPositionChanged = true;\n\t\t\tfor(CHANNELINDEX n = 0; n < GetNumChannels(); n++)\n\t\t\t{\n\t\t\t\tif(m_PlayState.Chn[n].nLastNote != NOTE_NONE)\n\t\t\t\t{\n\t\t\t\t\tm_PlayState.Chn[n].nNewNote = m_PlayState.Chn[n].nLastNote;\n\t\t\t\t}\n\t\t\t\tif(memory.chnSettings[n].vol != 0xFF && !adjustSamplePos)\n\t\t\t\t{\n\t\t\t\t\tm_PlayState.Chn[n].nVolume = std::min(memory.chnSettings[n].vol, uint8(64)) * 4;\n\t\t\t\t}\n\t\t\t}\n\n#ifndef NO_PLUGINS\n\t\t\t// If there were any PC events, update plugin parameters to their latest value.\n\t\t\tstd::bitset plugSetProgram;\n\t\t\tfor(const auto ¶m : memory.plugParams)\n\t\t\t{\n\t\t\t\tPLUGINDEX plug = param.first.first - 1;\n\t\t\t\tIMixPlugin *plugin = m_MixPlugins[plug].pMixPlugin;\n\t\t\t\tif(plugin != nullptr)\n\t\t\t\t{\n\t\t\t\t\tif(!plugSetProgram[plug])\n\t\t\t\t\t{\n\t\t\t\t\t\t// Used for bridged plugins to avoid sending out individual messages for each parameter.\n\t\t\t\t\t\tplugSetProgram.set(plug);\n\t\t\t\t\t\tplugin->BeginSetProgram();\n\t\t\t\t\t}\n\t\t\t\t\tplugin->SetParameter(param.first.second, param.second / PlugParamValue(ModCommand::maxColumnValue));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(plugSetProgram.any())\n\t\t\t{\n\t\t\t\tfor(PLUGINDEX i = 0; i < MAX_MIXPLUGINS; i++)\n\t\t\t\t{\n\t\t\t\t\tif(plugSetProgram[i])\n\t\t\t\t\t{\n\t\t\t\t\t\tm_MixPlugins[i].pMixPlugin->EndSetProgram();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n#endif // NO_PLUGINS\n\t\t} else if(adjustMode != eAdjustOnSuccess)\n\t\t{\n\t\t\t// Target not found (e.g. when jumping to a hidden sub song), reset global variables...\n\t\t\tm_PlayState.m_nMusicSpeed = m_nDefaultSpeed;\n\t\t\tm_PlayState.m_nMusicTempo = m_nDefaultTempo;\n\t\t\tm_PlayState.m_nGlobalVolume = m_nDefaultGlobalVolume;\n\t\t}\n\t\t// When adjusting the playback status, we will also want to update the visited rows vector according to the current position.\n\t\tif(sequence != Order.GetCurrentSequenceIndex())\n\t\t{\n\t\t\tOrder.SetSequence(sequence);\n\t\t}\n\t\tvisitedSongRows.Set(visitedRows);\n\t}\n\n\treturn results;\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': '[Fix] Possible out-of-bounds read when computing length of some IT files with pattern loops (OpenMPT: formats that are converted to IT, libopenmpt: IT/ITP/MO3), caught with afl-fuzz.\n\ngit-svn-id: https://source.openmpt.org/svn/openmpt/trunk/OpenMPT@10027 56274372-70c3-4bfc-bfc3-4c3a0b034d27'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: QInt16() {} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-908', 'CWE-787'], 'message': 'Default initialize fixed point Eigen types.\n\nIn certain cases, tensors are filled with default values of the type. But, for these fixed point types, these values were uninitialized. Thus, we would have uninitialized memory access bugs, some of which were caught by MSAN.\n\nPiperOrigin-RevId: 344101137\nChange-Id: I14555fda74dca3b5f1582da9008901937e3f14e2'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ghash_update(struct shash_desc *desc,\n\t\t\t const u8 *src, unsigned int srclen)\n{\n\tstruct ghash_desc_ctx *dctx = shash_desc_ctx(desc);\n\tstruct ghash_ctx *ctx = crypto_shash_ctx(desc->tfm);\n\tu8 *dst = dctx->buffer;\n\n\tif (dctx->bytes) {\n\t\tint n = min(srclen, dctx->bytes);\n\t\tu8 *pos = dst + (GHASH_BLOCK_SIZE - dctx->bytes);\n\n\t\tdctx->bytes -= n;\n\t\tsrclen -= n;\n\n\t\twhile (n--)\n\t\t\t*pos++ ^= *src++;\n\n\t\tif (!dctx->bytes)\n\t\t\tgf128mul_4k_lle((be128 *)dst, ctx->gf128);\n\t}\n\n\twhile (srclen >= GHASH_BLOCK_SIZE) {\n\t\tcrypto_xor(dst, src, GHASH_BLOCK_SIZE);\n\t\tgf128mul_4k_lle((be128 *)dst, ctx->gf128);\n\t\tsrc += GHASH_BLOCK_SIZE;\n\t\tsrclen -= GHASH_BLOCK_SIZE;\n\t}\n\n\tif (srclen) {\n\t\tdctx->bytes = GHASH_BLOCK_SIZE - srclen;\n\t\twhile (srclen--)\n\t\t\t*dst++ ^= *src++;\n\t}\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_set (hb_set_t *set,\n\t const hb_set_t *other)\n{\n if (unlikely (hb_object_is_immutable (set)))\n return;\n\n set->set (*other);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': '[set] Make all operators null-safe again\n\nChanged my mind.\n\nAlso for hb_map_clear().\n\nPart of https://github.com/harfbuzz/harfbuzz/pull/3162'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: SYSCALL_DEFINE4(osf_wait4, pid_t, pid, int __user *, ustatus, int, options,\n\t\tstruct rusage32 __user *, ur)\n{\n\tstruct rusage r;\n\tlong ret, err;\n\tmm_segment_t old_fs;\n\n\tif (!ur)\n\t\treturn sys_wait4(pid, ustatus, options, NULL);\n\n\told_fs = get_fs();\n\t\t\n\tset_fs (KERNEL_DS);\n\tret = sys_wait4(pid, ustatus, options, (struct rusage __user *) &r);\n\tset_fs (old_fs);\n\n\tif (!access_ok(VERIFY_WRITE, ur, sizeof(*ur)))\n\t\treturn -EFAULT;\n\n\terr = 0;\n\terr |= __put_user(r.ru_utime.tv_sec, &ur->ru_utime.tv_sec);\n\terr |= __put_user(r.ru_utime.tv_usec, &ur->ru_utime.tv_usec);\n\terr |= __put_user(r.ru_stime.tv_sec, &ur->ru_stime.tv_sec);\n\terr |= __put_user(r.ru_stime.tv_usec, &ur->ru_stime.tv_usec);\n\terr |= __put_user(r.ru_maxrss, &ur->ru_maxrss);\n\terr |= __put_user(r.ru_ixrss, &ur->ru_ixrss);\n\terr |= __put_user(r.ru_idrss, &ur->ru_idrss);\n\terr |= __put_user(r.ru_isrss, &ur->ru_isrss);\n\terr |= __put_user(r.ru_minflt, &ur->ru_minflt);\n\terr |= __put_user(r.ru_majflt, &ur->ru_majflt);\n\terr |= __put_user(r.ru_nswap, &ur->ru_nswap);\n\terr |= __put_user(r.ru_inblock, &ur->ru_inblock);\n\terr |= __put_user(r.ru_oublock, &ur->ru_oublock);\n\terr |= __put_user(r.ru_msgsnd, &ur->ru_msgsnd);\n\terr |= __put_user(r.ru_msgrcv, &ur->ru_msgrcv);\n\terr |= __put_user(r.ru_nsignals, &ur->ru_nsignals);\n\terr |= __put_user(r.ru_nvcsw, &ur->ru_nvcsw);\n\terr |= __put_user(r.ru_nivcsw, &ur->ru_nivcsw);\n\n\treturn err ? err : ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-264', 'CWE-189'], 'message': 'alpha: fix several security issues\n\nFix several security issues in Alpha-specific syscalls. Untested, but\nmostly trivial.\n\n1. Signedness issue in osf_getdomainname allows copying out-of-bounds\nkernel memory to userland.\n\n2. Signedness issue in osf_sysinfo allows copying large amounts of\nkernel memory to userland.\n\n3. Typo (?) in osf_getsysinfo bounds minimum instead of maximum copy\nsize, allowing copying large amounts of kernel memory to userland.\n\n4. Usage of user pointer in osf_wait4 while under KERNEL_DS allows\nprivilege escalation via writing return value of sys_wait4 to kernel\nmemory.\n\nSigned-off-by: Dan Rosenberg \nCc: Richard Henderson \nCc: Ivan Kokshaysky \nCc: Matt Turner \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void FilterManager::maybeEndEncode(bool end_stream) {\n if (end_stream) {\n filter_manager_callbacks_.endStream();\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'CVE-2021-43825\n\nResponse filter manager crash\n\nSigned-off-by: Yan Avlasov '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: 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\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\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 may_zeroout;\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\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\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\t/*\n \t * If the uninitialized extent begins at the same logical\n \t * block where the write begins, and the write completely\n \t * covers the extent, then we don't need to split it.\n \t */\n\tif ((map->m_lblk == ee_block) && (allocated <= map->m_len))\n\t\treturn allocated;\n\n\terr = ext4_ext_get_access(handle, inode, path + depth);\n\tif (err)\n\t\tgoto out;\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\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, flags);\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\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\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/*\n\t * ex2: map->m_lblk to map->m_lblk + map->m_len-1 : to be written\n\t * using direct I/O, uninitialised still.\n\t */\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\text4_ext_mark_uninitialized(ex2);\n\tif (ex2 != ex)\n\t\tgoto insert;\n\t/* Mark modified extent as dirty */\n\terr = ext4_ext_dirty(handle, inode, path + depth);\n\text_debug(\"out here\\n\");\n\tgoto out;\ninsert:\n\terr = ext4_ext_insert_extent(handle, inode, path, &newex, flags);\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: nfs4_proc_create(struct inode *dir, struct dentry *dentry, struct iattr *sattr,\n int flags, struct nameidata *nd)\n{\n\tstruct path path = {\n\t\t.mnt = nd->path.mnt,\n\t\t.dentry = dentry,\n\t};\n\tstruct nfs4_state *state;\n\tstruct rpc_cred *cred;\n\tint status = 0;\n\n\tcred = rpc_lookup_cred();\n\tif (IS_ERR(cred)) {\n\t\tstatus = PTR_ERR(cred);\n\t\tgoto out;\n\t}\n\tstate = nfs4_do_open(dir, &path, flags, sattr, cred);\n\td_drop(dentry);\n\tif (IS_ERR(state)) {\n\t\tstatus = PTR_ERR(state);\n\t\tgoto out_putcred;\n\t}\n\td_add(dentry, igrab(state->inode));\n\tnfs_set_verifier(dentry, nfs_save_change_attribute(dir));\n\tif (flags & O_EXCL) {\n\t\tstruct nfs_fattr fattr;\n\t\tstatus = nfs4_do_setattr(state->inode, cred, &fattr, sattr, state);\n\t\tif (status == 0)\n\t\t\tnfs_setattr_update_inode(state->inode, sattr);\n\t\tnfs_post_op_update_inode(state->inode, &fattr);\n\t}\n\tif (status == 0 && (nd->flags & LOOKUP_OPEN) != 0)\n\t\tstatus = nfs4_intent_set_file(nd, &path, state);\n\telse\n\t\tnfs4_close_sync(&path, state, flags);\nout_putcred:\n\tput_rpccred(cred);\nout:\n\treturn status;\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 nfs4_open_prepare(struct rpc_task *task, void *calldata)\n{\n\tstruct nfs4_opendata *data = calldata;\n\tstruct nfs4_state_owner *sp = data->owner;\n\n\tif (nfs_wait_on_sequence(data->o_arg.seqid, task) != 0)\n\t\treturn;\n\t/*\n\t * Check if we still need to send an OPEN call, or if we can use\n\t * a delegation instead.\n\t */\n\tif (data->state != NULL) {\n\t\tstruct nfs_delegation *delegation;\n\n\t\tif (can_open_cached(data->state, data->o_arg.open_flags & (FMODE_READ|FMODE_WRITE|O_EXCL)))\n\t\t\tgoto out_no_action;\n\t\trcu_read_lock();\n\t\tdelegation = rcu_dereference(NFS_I(data->state->inode)->delegation);\n\t\tif (delegation != NULL &&\n\t\t test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags) == 0) {\n\t\t\trcu_read_unlock();\n\t\t\tgoto out_no_action;\n\t\t}\n\t\trcu_read_unlock();\n\t}\n\t/* Update sequence id. */\n\tdata->o_arg.id = sp->so_owner_id.id;\n\tdata->o_arg.clientid = sp->so_client->cl_clientid;\n\tif (data->o_arg.claim == NFS4_OPEN_CLAIM_PREVIOUS) {\n\t\ttask->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_NOATTR];\n\t\tnfs_copy_fh(&data->o_res.fh, data->o_arg.fh);\n\t}\n\tdata->timestamp = jiffies;\n\trpc_call_start(task);\n\treturn;\nout_no_action:\n\ttask->tk_action = NULL;\n\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 struct nfs4_opendata *nfs4_opendata_alloc(struct path *path,\n\t\tstruct nfs4_state_owner *sp, int flags,\n\t\tconst struct iattr *attrs)\n{\n\tstruct dentry *parent = dget_parent(path->dentry);\n\tstruct inode *dir = parent->d_inode;\n\tstruct nfs_server *server = NFS_SERVER(dir);\n\tstruct nfs4_opendata *p;\n\n\tp = kzalloc(sizeof(*p), GFP_KERNEL);\n\tif (p == NULL)\n\t\tgoto err;\n\tp->o_arg.seqid = nfs_alloc_seqid(&sp->so_seqid);\n\tif (p->o_arg.seqid == NULL)\n\t\tgoto err_free;\n\tp->path.mnt = mntget(path->mnt);\n\tp->path.dentry = dget(path->dentry);\n\tp->dir = parent;\n\tp->owner = sp;\n\tatomic_inc(&sp->so_count);\n\tp->o_arg.fh = NFS_FH(dir);\n\tp->o_arg.open_flags = flags,\n\tp->o_arg.clientid = server->nfs_client->cl_clientid;\n\tp->o_arg.id = sp->so_owner_id.id;\n\tp->o_arg.name = &p->path.dentry->d_name;\n\tp->o_arg.server = server;\n\tp->o_arg.bitmask = server->attr_bitmask;\n\tp->o_arg.claim = NFS4_OPEN_CLAIM_NULL;\n\tif (flags & O_EXCL) {\n\t\tu32 *s = (u32 *) p->o_arg.u.verifier.data;\n\t\ts[0] = jiffies;\n\t\ts[1] = current->pid;\n\t} else if (flags & O_CREAT) {\n\t\tp->o_arg.u.attrs = &p->attrs;\n\t\tmemcpy(&p->attrs, attrs, sizeof(p->attrs));\n\t}\n\tp->c_arg.fh = &p->o_res.fh;\n\tp->c_arg.stateid = &p->o_res.stateid;\n\tp->c_arg.seqid = p->o_arg.seqid;\n\tnfs4_init_opendata_res(p);\n\tkref_init(&p->kref);\n\treturn p;\nerr_free:\n\tkfree(p);\nerr:\n\tdput(parent);\n\treturn NULL;\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 kodak_c603_load_raw()\n{\n uchar *pixel;\n int row, col, y, cb, cr, rgb[3], c;\n\n pixel = (uchar *) calloc (raw_width, 3*sizeof *pixel);\n merror (pixel, \"kodak_c603_load_raw()\");\n#ifdef LIBRAW_LIBRARY_BUILD\n try {\n#endif\n for (row=0; row < height; row++) {\n#ifdef LIBRAW_LIBRARY_BUILD\n checkCancel();\n#endif\n if (~row & 1)\n if (fread (pixel, raw_width, 3, ifp) < 3) derror();\n for (col=0; col < width; col++) {\n y = pixel[width*2*(row & 1) + col];\n cb = pixel[width + (col & -2)] - 128;\n cr = pixel[width + (col & -2)+1] - 128;\n rgb[1] = y - ((cb + cr + 2) >> 2);\n rgb[2] = rgb[1] + cb;\n rgb[0] = rgb[1] + cr;\n FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)];\n }\n }\n#ifdef LIBRAW_LIBRARY_BUILD\n } catch(...) {\n free (pixel);\n throw;\n }\n#endif\n free (pixel);\n maximum = curve[0xff];\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': '0.18.17'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void CLASS kodak_rgb_load_raw()\n{\n short buf[768], *bp;\n int row, col, len, c, i, rgb[3],ret;\n ushort *ip=image[0];\n\n for (row=0; row < height; row++)\n {\n#ifdef LIBRAW_LIBRARY_BUILD\n checkCancel();\n#endif\n for (col=0; col < width; col+=256) {\n len = MIN (256, width-col);\n ret = kodak_65000_decode (buf, len*3);\n memset (rgb, 0, sizeof rgb);\n for (bp=buf, i=0; i < len; i++, ip+=4)\n#ifdef LIBRAW_LIBRARY_BUILD\n if(load_flags == 12)\n {\n FORC3 ip[c] = ret ? (*bp++) : (rgb[c] += *bp++);\n }\n else\n#endif\n FORC3 if ((ip[c] = ret ? (*bp++) : (rgb[c] += *bp++)) >> 12) derror();\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': '0.18.17'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static struct dentry *ecryptfs_mount(struct file_system_type *fs_type, int flags,\n\t\t\tconst char *dev_name, void *raw_data)\n{\n\tstruct super_block *s;\n\tstruct ecryptfs_sb_info *sbi;\n\tstruct ecryptfs_dentry_info *root_info;\n\tconst char *err = \"Getting sb failed\";\n\tstruct inode *inode;\n\tstruct path path;\n\tint rc;\n\n\tsbi = kmem_cache_zalloc(ecryptfs_sb_info_cache, GFP_KERNEL);\n\tif (!sbi) {\n\t\trc = -ENOMEM;\n\t\tgoto out;\n\t}\n\n\trc = ecryptfs_parse_options(sbi, raw_data);\n\tif (rc) {\n\t\terr = \"Error parsing options\";\n\t\tgoto out;\n\t}\n\n\ts = sget(fs_type, NULL, set_anon_super, NULL);\n\tif (IS_ERR(s)) {\n\t\trc = PTR_ERR(s);\n\t\tgoto out;\n\t}\n\n\ts->s_flags = flags;\n\trc = bdi_setup_and_register(&sbi->bdi, \"ecryptfs\", BDI_CAP_MAP_COPY);\n\tif (rc)\n\t\tgoto out1;\n\n\tecryptfs_set_superblock_private(s, sbi);\n\ts->s_bdi = &sbi->bdi;\n\n\t/* ->kill_sb() will take care of sbi after that point */\n\tsbi = NULL;\n\ts->s_op = &ecryptfs_sops;\n\ts->s_d_op = &ecryptfs_dops;\n\n\terr = \"Reading sb failed\";\n\trc = kern_path(dev_name, LOOKUP_FOLLOW | LOOKUP_DIRECTORY, &path);\n\tif (rc) {\n\t\tecryptfs_printk(KERN_WARNING, \"kern_path() failed\\n\");\n\t\tgoto out1;\n\t}\n\tif (path.dentry->d_sb->s_type == &ecryptfs_fs_type) {\n\t\trc = -EINVAL;\n\t\tprintk(KERN_ERR \"Mount on filesystem of type \"\n\t\t\t\"eCryptfs explicitly disallowed due to \"\n\t\t\t\"known incompatibilities\\n\");\n\t\tgoto out_free;\n\t}\n\tecryptfs_set_superblock_lower(s, path.dentry->d_sb);\n\ts->s_maxbytes = path.dentry->d_sb->s_maxbytes;\n\ts->s_blocksize = path.dentry->d_sb->s_blocksize;\n\ts->s_magic = ECRYPTFS_SUPER_MAGIC;\n\n\tinode = ecryptfs_get_inode(path.dentry->d_inode, s);\n\trc = PTR_ERR(inode);\n\tif (IS_ERR(inode))\n\t\tgoto out_free;\n\n\ts->s_root = d_alloc_root(inode);\n\tif (!s->s_root) {\n\t\tiput(inode);\n\t\trc = -ENOMEM;\n\t\tgoto out_free;\n\t}\n\n\trc = -ENOMEM;\n\troot_info = kmem_cache_zalloc(ecryptfs_dentry_info_cache, GFP_KERNEL);\n\tif (!root_info)\n\t\tgoto out_free;\n\n\t/* ->kill_sb() will take care of root_info */\n\tecryptfs_set_dentry_private(s->s_root, root_info);\n\tecryptfs_set_dentry_lower(s->s_root, path.dentry);\n\tecryptfs_set_dentry_lower_mnt(s->s_root, path.mnt);\n\n\ts->s_flags |= MS_ACTIVE;\n\treturn dget(s->s_root);\n\nout_free:\n\tpath_put(&path);\nout1:\n\tdeactivate_locked_super(s);\nout:\n\tif (sbi) {\n\t\tecryptfs_destroy_mount_crypt_stat(&sbi->mount_crypt_stat);\n\t\tkmem_cache_free(ecryptfs_sb_info_cache, sbi);\n\t}\n\tprintk(KERN_ERR \"%s; rc = [%d]\\n\", err, rc);\n\treturn ERR_PTR(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: char *compose_path(ctrl_t *ctrl, char *path)\n{\n\tstruct stat st;\n\tstatic char rpath[PATH_MAX];\n\tchar *name, *ptr;\n\tchar dir[PATH_MAX] = { 0 };\n\n\tstrlcpy(dir, ctrl->cwd, sizeof(dir));\n\tDBG(\"Compose path from cwd: %s, arg: %s\", ctrl->cwd, path ?: \"\");\n\tif (!path || !strlen(path))\n\t\tgoto check;\n\n\tif (path) {\n\t\tif (path[0] != '/') {\n\t\t\tif (dir[strlen(dir) - 1] != '/')\n\t\t\t\tstrlcat(dir, \"/\", sizeof(dir));\n\t\t}\n\t\tstrlcat(dir, path, sizeof(dir));\n\t}\n\ncheck:\n\twhile ((ptr = strstr(dir, \"//\")))\n\t\tmemmove(ptr, &ptr[1], strlen(&ptr[1]) + 1);\n\n\tif (!chrooted) {\n\t\tsize_t len = strlen(home);\n\n\t\tDBG(\"Server path from CWD: %s\", dir);\n\t\tif (len > 0 && home[len - 1] == '/')\n\t\t\tlen--;\n\t\tmemmove(dir + len, dir, strlen(dir) + 1);\n\t\tmemcpy(dir, home, len);\n\t\tDBG(\"Resulting non-chroot path: %s\", dir);\n\t}\n\n\t/*\n\t * Handle directories slightly differently, since dirname() on a\n\t * directory returns the parent directory. So, just squash ..\n\t */\n\tif (!stat(dir, &st) && S_ISDIR(st.st_mode)) {\n\t\tif (!realpath(dir, rpath))\n\t\t\treturn NULL;\n\t} else {\n\t\t/*\n\t\t * Check realpath() of directory containing the file, a\n\t\t * STOR may want to save a new file. Then append the\n\t\t * file and return it.\n\t\t */\n\t\tname = basename(path);\n\t\tptr = dirname(dir);\n\n\t\tmemset(rpath, 0, sizeof(rpath));\n\t\tif (!realpath(ptr, rpath)) {\n\t\t\tINFO(\"Failed realpath(%s): %m\", ptr);\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (rpath[1] != 0)\n\t\t\tstrlcat(rpath, \"/\", sizeof(rpath));\n\t\tstrlcat(rpath, name, sizeof(rpath));\n\t}\n\n\tif (!chrooted && strncmp(dir, home, strlen(home))) {\n\t\tDBG(\"Failed non-chroot dir:%s vs home:%s\", dir, home);\n\t\treturn NULL;\n\t}\n\n\treturn rpath;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'FTP/TFTP: Fix directory traversal regression, reported by Aaron Esau\n\nSigned-off-by: Joachim Nilsson '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int cuse_channel_release(struct inode *inode, struct file *file)\n{\n\tstruct fuse_dev *fud = file->private_data;\n\tstruct cuse_conn *cc = fc_to_cc(fud->fc);\n\tint rc;\n\n\t/* remove from the conntbl, no more access from this point on */\n\tmutex_lock(&cuse_lock);\n\tlist_del_init(&cc->list);\n\tmutex_unlock(&cuse_lock);\n\n\t/* remove device */\n\tif (cc->dev)\n\t\tdevice_unregister(cc->dev);\n\tif (cc->cdev) {\n\t\tunregister_chrdev_region(cc->cdev->dev, 1);\n\t\tcdev_del(cc->cdev);\n\t}\n\n\trc = fuse_dev_release(inode, file);\t/* puts the base reference */\n\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'cuse: fix memory leak\n\nThe problem is that fuse_dev_alloc() acquires an extra reference to cc.fc,\nand the original ref count is never dropped.\n\nReported-by: Colin Ian King \nSigned-off-by: Miklos Szeredi \nFixes: cc080e9e9be1 (\"fuse: introduce per-instance fuse_dev structure\")\nCc: # v4.2+'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int get_rock_ridge_filename(struct iso_directory_record *de,\n\t\t\t char *retname, struct inode *inode)\n{\n\tstruct rock_state rs;\n\tstruct rock_ridge *rr;\n\tint sig;\n\tint retnamlen = 0;\n\tint truncate = 0;\n\tint ret = 0;\n\n\tif (!ISOFS_SB(inode->i_sb)->s_rock)\n\t\treturn 0;\n\t*retname = 0;\n\n\tinit_rock_state(&rs, inode);\n\tsetup_rock_ridge(de, inode, &rs);\nrepeat:\n\n\twhile (rs.len > 2) { /* There may be one byte for padding somewhere */\n\t\trr = (struct rock_ridge *)rs.chr;\n\t\t/*\n\t\t * Ignore rock ridge info if rr->len is out of range, but\n\t\t * don't return -EIO because that would make the file\n\t\t * invisible.\n\t\t */\n\t\tif (rr->len < 3)\n\t\t\tgoto out;\t/* Something got screwed up here */\n\t\tsig = isonum_721(rs.chr);\n\t\tif (rock_check_overflow(&rs, sig))\n\t\t\tgoto eio;\n\t\trs.chr += rr->len;\n\t\trs.len -= rr->len;\n\t\t/*\n\t\t * As above, just ignore the rock ridge info if rr->len\n\t\t * is bogus.\n\t\t */\n\t\tif (rs.len < 0)\n\t\t\tgoto out;\t/* Something got screwed up here */\n\n\t\tswitch (sig) {\n\t\tcase SIG('R', 'R'):\n\t\t\tif ((rr->u.RR.flags[0] & RR_NM) == 0)\n\t\t\t\tgoto out;\n\t\t\tbreak;\n\t\tcase SIG('S', 'P'):\n\t\t\tif (check_sp(rr, inode))\n\t\t\t\tgoto out;\n\t\t\tbreak;\n\t\tcase SIG('C', 'E'):\n\t\t\trs.cont_extent = isonum_733(rr->u.CE.extent);\n\t\t\trs.cont_offset = isonum_733(rr->u.CE.offset);\n\t\t\trs.cont_size = isonum_733(rr->u.CE.size);\n\t\t\tbreak;\n\t\tcase SIG('N', 'M'):\n\t\t\tif (truncate)\n\t\t\t\tbreak;\n\t\t\tif (rr->len < 5)\n\t\t\t\tbreak;\n\t\t\t/*\n\t\t\t * If the flags are 2 or 4, this indicates '.' or '..'.\n\t\t\t * We don't want to do anything with this, because it\n\t\t\t * screws up the code that calls us. We don't really\n\t\t\t * care anyways, since we can just use the non-RR\n\t\t\t * name.\n\t\t\t */\n\t\t\tif (rr->u.NM.flags & 6)\n\t\t\t\tbreak;\n\n\t\t\tif (rr->u.NM.flags & ~1) {\n\t\t\t\tprintk(\"Unsupported NM flag settings (%d)\\n\",\n\t\t\t\t\trr->u.NM.flags);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif ((strlen(retname) + rr->len - 5) >= 254) {\n\t\t\t\ttruncate = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tstrncat(retname, rr->u.NM.name, rr->len - 5);\n\t\t\tretnamlen += rr->len - 5;\n\t\t\tbreak;\n\t\tcase SIG('R', 'E'):\n\t\t\tkfree(rs.buffer);\n\t\t\treturn -1;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\tret = rock_continue(&rs);\n\tif (ret == 0)\n\t\tgoto repeat;\n\tif (ret == 1)\n\t\treturn retnamlen; /* If 0, this file did not have a NM field */\nout:\n\tkfree(rs.buffer);\n\treturn ret;\neio:\n\tret = -EIO;\n\tgoto out;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'get_rock_ridge_filename(): handle malformed NM entries\n\nPayloads of NM entries are not supposed to contain NUL. When we run\ninto such, only the part prior to the first NUL goes into the\nconcatenation (i.e. the directory entry name being encoded by a bunch\nof NM entries). We do stop when the amount collected so far + the\nclaimed amount in the current NM entry exceed 254. So far, so good,\nbut what we return as the total length is the sum of *claimed*\nsizes, not the actual amount collected. And that can grow pretty\nlarge - not unlimited, since you'd need to put CE entries in\nbetween to be able to get more than the maximum that could be\ncontained in one isofs directory entry / continuation chunk and\nwe are stop once we'd encountered 32 CEs, but you can get about 8Kb\neasily. And that's what will be passed to readdir callback as the\nname length. 8Kb __copy_to_user() from a buffer allocated by\n__get_free_page()\n\nCc: stable@vger.kernel.org # 0.98pl6+ (yes, really)\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: DefineSequence(ParseState *pstate, CreateSeqStmt *seq)\n{\n\tFormData_pg_sequence seqform;\n\tFormData_pg_sequence_data seqdataform;\n\tbool\t\tneed_seq_rewrite;\n\tList\t *owned_by;\n\tCreateStmt *stmt = makeNode(CreateStmt);\n\tOid\t\t\tseqoid;\n\tObjectAddress address;\n\tRelation\trel;\n\tHeapTuple\ttuple;\n\tTupleDesc\ttupDesc;\n\tDatum\t\tvalue[SEQ_COL_LASTCOL];\n\tbool\t\tnull[SEQ_COL_LASTCOL];\n\tDatum\t\tpgs_values[Natts_pg_sequence];\n\tbool\t\tpgs_nulls[Natts_pg_sequence];\n\tint\t\t\ti;\n\n\t/*\n\t * If if_not_exists was given and a relation with the same name already\n\t * exists, bail out. (Note: we needn't check this when not if_not_exists,\n\t * because DefineRelation will complain anyway.)\n\t */\n\tif (seq->if_not_exists)\n\t{\n\t\tRangeVarGetAndCheckCreationNamespace(seq->sequence, NoLock, &seqoid);\n\t\tif (OidIsValid(seqoid))\n\t\t{\n\t\t\tereport(NOTICE,\n\t\t\t\t\t(errcode(ERRCODE_DUPLICATE_TABLE),\n\t\t\t\t\t errmsg(\"relation \\\"%s\\\" already exists, skipping\",\n\t\t\t\t\t\t\tseq->sequence->relname)));\n\t\t\treturn InvalidObjectAddress;\n\t\t}\n\t}\n\n\t/* Check and set all option values */\n\tinit_params(pstate, seq->options, seq->for_identity, true,\n\t\t\t\t&seqform, &seqdataform,\n\t\t\t\t&need_seq_rewrite, &owned_by);\n\n\t/*\n\t * Create relation (and fill value[] and null[] for the tuple)\n\t */\n\tstmt->tableElts = NIL;\n\tfor (i = SEQ_COL_FIRSTCOL; i <= SEQ_COL_LASTCOL; i++)\n\t{\n\t\tColumnDef *coldef = makeNode(ColumnDef);\n\n\t\tcoldef->inhcount = 0;\n\t\tcoldef->is_local = true;\n\t\tcoldef->is_not_null = true;\n\t\tcoldef->is_from_type = false;\n\t\tcoldef->storage = 0;\n\t\tcoldef->raw_default = NULL;\n\t\tcoldef->cooked_default = NULL;\n\t\tcoldef->collClause = NULL;\n\t\tcoldef->collOid = InvalidOid;\n\t\tcoldef->constraints = NIL;\n\t\tcoldef->location = -1;\n\n\t\tnull[i - 1] = false;\n\n\t\tswitch (i)\n\t\t{\n\t\t\tcase SEQ_COL_LASTVAL:\n\t\t\t\tcoldef->typeName = makeTypeNameFromOid(INT8OID, -1);\n\t\t\t\tcoldef->colname = \"last_value\";\n\t\t\t\tvalue[i - 1] = Int64GetDatumFast(seqdataform.last_value);\n\t\t\t\tbreak;\n\t\t\tcase SEQ_COL_LOG:\n\t\t\t\tcoldef->typeName = makeTypeNameFromOid(INT8OID, -1);\n\t\t\t\tcoldef->colname = \"log_cnt\";\n\t\t\t\tvalue[i - 1] = Int64GetDatum((int64) 0);\n\t\t\t\tbreak;\n\t\t\tcase SEQ_COL_CALLED:\n\t\t\t\tcoldef->typeName = makeTypeNameFromOid(BOOLOID, -1);\n\t\t\t\tcoldef->colname = \"is_called\";\n\t\t\t\tvalue[i - 1] = BoolGetDatum(false);\n\t\t\t\tbreak;\n\t\t}\n\t\tstmt->tableElts = lappend(stmt->tableElts, coldef);\n\t}\n\n\tstmt->relation = seq->sequence;\n\tstmt->inhRelations = NIL;\n\tstmt->constraints = NIL;\n\tstmt->options = NIL;\n\tstmt->oncommit = ONCOMMIT_NOOP;\n\tstmt->tablespacename = NULL;\n\tstmt->if_not_exists = seq->if_not_exists;\n\n\taddress = DefineRelation(stmt, RELKIND_SEQUENCE, seq->ownerId, NULL, NULL);\n\tseqoid = address.objectId;\n\tAssert(seqoid != InvalidOid);\n\n\trel = table_open(seqoid, AccessExclusiveLock);\n\ttupDesc = RelationGetDescr(rel);\n\n\t/* now initialize the sequence's data */\n\ttuple = heap_form_tuple(tupDesc, value, null);\n\tfill_seq_with_data(rel, tuple);\n\n\t/* process OWNED BY if given */\n\tif (owned_by)\n\t\tprocess_owned_by(rel, owned_by, seq->for_identity);\n\n\ttable_close(rel, NoLock);\n\n\t/* fill in pg_sequence */\n\trel = table_open(SequenceRelationId, RowExclusiveLock);\n\ttupDesc = RelationGetDescr(rel);\n\n\tmemset(pgs_nulls, 0, sizeof(pgs_nulls));\n\n\tpgs_values[Anum_pg_sequence_seqrelid - 1] = ObjectIdGetDatum(seqoid);\n\tpgs_values[Anum_pg_sequence_seqtypid - 1] = ObjectIdGetDatum(seqform.seqtypid);\n\tpgs_values[Anum_pg_sequence_seqstart - 1] = Int64GetDatumFast(seqform.seqstart);\n\tpgs_values[Anum_pg_sequence_seqincrement - 1] = Int64GetDatumFast(seqform.seqincrement);\n\tpgs_values[Anum_pg_sequence_seqmax - 1] = Int64GetDatumFast(seqform.seqmax);\n\tpgs_values[Anum_pg_sequence_seqmin - 1] = Int64GetDatumFast(seqform.seqmin);\n\tpgs_values[Anum_pg_sequence_seqcache - 1] = Int64GetDatumFast(seqform.seqcache);\n\tpgs_values[Anum_pg_sequence_seqcycle - 1] = BoolGetDatum(seqform.seqcycle);\n\n\ttuple = heap_form_tuple(tupDesc, pgs_values, pgs_nulls);\n\tCatalogTupleInsert(rel, tuple);\n\n\theap_freetuple(tuple);\n\ttable_close(rel, RowExclusiveLock);\n\n\treturn address;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-94'], 'message': 'In extensions, don't replace objects not belonging to the extension.\n\nPreviously, if an extension script did CREATE OR REPLACE and there was\nan existing object not belonging to the extension, it would overwrite\nthe object and adopt it into the extension. This is problematic, first\nbecause the overwrite is probably unintentional, and second because we\ndidn't change the object's ownership. Thus a hostile user could create\nan object in advance of an expected CREATE EXTENSION command, and would\nthen have ownership rights on an extension object, which could be\nmodified for trojan-horse-type attacks.\n\nHence, forbid CREATE OR REPLACE of an existing object unless it already\nbelongs to the extension. (Note that we've always forbidden replacing\nan object that belongs to some other extension; only the behavior for\npreviously-free-standing objects changes here.)\n\nFor the same reason, also fail CREATE IF NOT EXISTS when there is\nan existing object that doesn't belong to the extension.\n\nOur thanks to Sven Klemm for reporting this problem.\n\nSecurity: CVE-2022-2625'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ff_amf_get_field_value(const uint8_t *data, const uint8_t *data_end,\n const uint8_t *name, uint8_t *dst, int dst_size)\n{\n int namelen = strlen(name);\n int len;\n\n while (*data != AMF_DATA_TYPE_OBJECT && data < data_end) {\n len = ff_amf_tag_size(data, data_end);\n if (len < 0)\n len = data_end - data;\n data += len;\n }\n if (data_end - data < 3)\n return -1;\n data++;\n for (;;) {\n int size = bytestream_get_be16(&data);\n if (!size)\n break;\n if (size < 0 || size >= data_end - data)\n return -1;\n data += size;\n if (size == namelen && !memcmp(data-size, name, namelen)) {\n switch (*data++) {\n case AMF_DATA_TYPE_NUMBER:\n snprintf(dst, dst_size, \"%g\", av_int2double(AV_RB64(data)));\n break;\n case AMF_DATA_TYPE_BOOL:\n snprintf(dst, dst_size, \"%s\", *data ? \"true\" : \"false\");\n break;\n case AMF_DATA_TYPE_STRING:\n len = bytestream_get_be16(&data);\n av_strlcpy(dst, data, FFMIN(len+1, dst_size));\n break;\n default:\n return -1;\n }\n return 0;\n }\n len = ff_amf_tag_size(data, data_end);\n if (len < 0 || len >= data_end - data)\n return -1;\n data += len;\n }\n return -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'avformat/rtmppkt: Convert ff_amf_get_field_value() to bytestream2\n\nFixes: out of array accesses\n\nFound-by: JunDong Xie of Ant-financial Light-Year Security Lab\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: bit_write_UMC (Bit_Chain *dat, BITCODE_UMC val)\n{\n int i, j;\n int negative;\n unsigned char byte[5];\n BITCODE_UMC mask;\n BITCODE_UMC value;\n\n value = val;\n mask = 0x0000007f;\n for (i = 4, j = 0; i >= 0; i--, j += 7)\n {\n byte[i] = (unsigned char)((value & mask) >> j);\n byte[i] |= 0x80;\n mask = mask << 7;\n }\n for (i = 0; i < 4; i++)\n if (byte[i] & 0x7f)\n break;\n\n if (byte[i] & 0x40)\n i--;\n byte[i] &= 0x7f;\n for (j = 4; j >= i; j--)\n bit_write_RC (dat, byte[j]);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'encode: protect from stack under-flow\n\nFrom GH #178 fuzzing'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static 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(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', 'CWE-703'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/654'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: gimp_channel_is_empty (GimpChannel *channel)\n{\n g_return_val_if_fail (GIMP_IS_CHANNEL (channel), FALSE);\n\n return GIMP_CHANNEL_GET_CLASS (channel)->is_empty (channel);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'app: fix #8230 crash in gimp_layer_invalidate_boundary when channel is NULL\n\ngimp_channel_is_empty returns FALSE if channel is NULL. This causes\ngimp_layer_invalidate_boundary to crash if the mask channel is NULL.\n\nWith a NULL channel gimp_channel_is_empty should return TRUE, just like\nthe similar gimp_image_is_empty does, because returning FALSE here\nsuggests we have a non empty channel.\n\n(cherry picked from commit 22af0bcfe67c1c86381f33975ca7fdbde6b36b39)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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;\n\tint exthdrlen;\n\tint dst_exthdrlen;\n\tint hh_len;\n\tint mtu;\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\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->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-399'], 'message': 'ipv6: ip6_append_data_mtu did not care about pmtudisc and frag_size\n\nIf the socket had an IPV6_MTU value set, ip6_append_data_mtu lost track\nof this when appending the second frame on a corked socket. This results\nin the following splat:\n\n[37598.993962] ------------[ cut here ]------------\n[37598.994008] kernel BUG at net/core/skbuff.c:2064!\n[37598.994008] invalid opcode: 0000 [#1] SMP\n[37598.994008] Modules linked in: tcp_lp uvcvideo videobuf2_vmalloc videobuf2_memops videobuf2_core videodev media vfat fat usb_storage fuse ebtable_nat xt_CHECKSUM bridge stp llc ipt_MASQUERADE nf_conntrack_netbios_ns nf_conntrack_broadcast ip6table_mangle ip6t_REJECT nf_conntrack_ipv6 nf_defrag_ipv6 iptable_nat\n+nf_nat_ipv4 nf_nat iptable_mangle nf_conntrack_ipv4 nf_defrag_ipv4 xt_conntrack nf_conntrack ebtable_filter ebtables ip6table_filter ip6_tables be2iscsi iscsi_boot_sysfs bnx2i cnic uio cxgb4i cxgb4 cxgb3i cxgb3 mdio libcxgbi ib_iser rdma_cm ib_addr iw_cm ib_cm ib_sa ib_mad ib_core iscsi_tcp libiscsi_tcp libiscsi\n+scsi_transport_iscsi rfcomm bnep iTCO_wdt iTCO_vendor_support snd_hda_codec_conexant arc4 iwldvm mac80211 snd_hda_intel acpi_cpufreq mperf coretemp snd_hda_codec microcode cdc_wdm cdc_acm\n[37598.994008] snd_hwdep cdc_ether snd_seq snd_seq_device usbnet mii joydev btusb snd_pcm bluetooth i2c_i801 e1000e lpc_ich mfd_core ptp iwlwifi pps_core snd_page_alloc mei cfg80211 snd_timer thinkpad_acpi snd tpm_tis soundcore rfkill tpm tpm_bios vhost_net tun macvtap macvlan kvm_intel kvm uinput binfmt_misc\n+dm_crypt i915 i2c_algo_bit drm_kms_helper drm i2c_core wmi video\n[37598.994008] CPU 0\n[37598.994008] Pid: 27320, comm: t2 Not tainted 3.9.6-200.fc18.x86_64 #1 LENOVO 27744PG/27744PG\n[37598.994008] RIP: 0010:[] [] skb_copy_and_csum_bits+0x325/0x330\n[37598.994008] RSP: 0018:ffff88003670da18 EFLAGS: 00010202\n[37598.994008] RAX: ffff88018105c018 RBX: 0000000000000004 RCX: 00000000000006c0\n[37598.994008] RDX: ffff88018105a6c0 RSI: ffff88018105a000 RDI: ffff8801e1b0aa00\n[37598.994008] RBP: ffff88003670da78 R08: 0000000000000000 R09: ffff88018105c040\n[37598.994008] R10: ffff8801e1b0aa00 R11: 0000000000000000 R12: 000000000000fff8\n[37598.994008] R13: 00000000000004fc R14: 00000000ffff0504 R15: 0000000000000000\n[37598.994008] FS: 00007f28eea59740(0000) GS:ffff88023bc00000(0000) knlGS:0000000000000000\n[37598.994008] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b\n[37598.994008] CR2: 0000003d935789e0 CR3: 00000000365cb000 CR4: 00000000000407f0\n[37598.994008] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000\n[37598.994008] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400\n[37598.994008] Process t2 (pid: 27320, threadinfo ffff88003670c000, task ffff88022c162ee0)\n[37598.994008] Stack:\n[37598.994008] ffff88022e098a00 ffff88020f973fc0 0000000000000008 00000000000004c8\n[37598.994008] ffff88020f973fc0 00000000000004c4 ffff88003670da78 ffff8801e1b0a200\n[37598.994008] 0000000000000018 00000000000004c8 ffff88020f973fc0 00000000000004c4\n[37598.994008] Call Trace:\n[37598.994008] [] ip6_append_data+0xccf/0xfe0\n[37598.994008] [] ? ip_copy_metadata+0x1a0/0x1a0\n[37598.994008] [] ? _raw_spin_lock_bh+0x16/0x40\n[37598.994008] [] udpv6_sendmsg+0x1ed/0xc10\n[37598.994008] [] ? sock_has_perm+0x75/0x90\n[37598.994008] [] inet_sendmsg+0x63/0xb0\n[37598.994008] [] ? selinux_socket_sendmsg+0x23/0x30\n[37598.994008] [] sock_sendmsg+0xb0/0xe0\n[37598.994008] [] ? __switch_to+0x181/0x4a0\n[37598.994008] [] sys_sendto+0x12d/0x180\n[37598.994008] [] ? __audit_syscall_entry+0x94/0xf0\n[37598.994008] [] ? syscall_trace_enter+0x231/0x240\n[37598.994008] [] tracesys+0xdd/0xe2\n[37598.994008] Code: fe 07 00 00 48 c7 c7 04 28 a6 81 89 45 a0 4c 89 4d b8 44 89 5d a8 e8 1b ac b1 ff 44 8b 5d a8 4c 8b 4d b8 8b 45 a0 e9 cf fe ff ff <0f> 0b 66 0f 1f 84 00 00 00 00 00 66 66 66 66 90 55 48 89 e5 48\n[37598.994008] RIP [] skb_copy_and_csum_bits+0x325/0x330\n[37598.994008] RSP \n[37599.007323] ---[ end trace d69f6a17f8ac8eee ]---\n\nWhile there, also check if path mtu discovery is activated for this\nsocket. The logic was adapted from ip6_append_data when first writing\non the corked socket.\n\nThis bug was introduced with commit\n0c1833797a5a6ec23ea9261d979aa18078720b74 (\"ipv6: fix incorrect ipsec\nfragment\").\n\nv2:\na) Replace IPV6_PMTU_DISC_DO with IPV6_PMTUDISC_PROBE.\nb) Don't pass ipv6_pinfo to ip6_append_data_mtu (suggestion by Gao\n feng, thanks!).\nc) Change mtu to unsigned int, else we get a warning about\n non-matching types because of the min()-macro type-check.\n\nAcked-by: Gao feng \nCc: YOSHIFUJI Hideaki \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int __net_init sctp_net_init(struct net *net)\n{\n\tint status;\n\n\t/*\n\t * 14. Suggested SCTP Protocol Parameter Values\n\t */\n\t/* The following protocol parameters are RECOMMENDED: */\n\t/* RTO.Initial - 3 seconds */\n\tnet->sctp.rto_initial\t\t\t= SCTP_RTO_INITIAL;\n\t/* RTO.Min - 1 second */\n\tnet->sctp.rto_min\t \t\t= SCTP_RTO_MIN;\n\t/* RTO.Max - 60 seconds */\n\tnet->sctp.rto_max \t\t\t= SCTP_RTO_MAX;\n\t/* RTO.Alpha - 1/8 */\n\tnet->sctp.rto_alpha\t\t\t= SCTP_RTO_ALPHA;\n\t/* RTO.Beta - 1/4 */\n\tnet->sctp.rto_beta\t\t\t= SCTP_RTO_BETA;\n\n\t/* Valid.Cookie.Life - 60 seconds */\n\tnet->sctp.valid_cookie_life\t\t= SCTP_DEFAULT_COOKIE_LIFE;\n\n\t/* Whether Cookie Preservative is enabled(1) or not(0) */\n\tnet->sctp.cookie_preserve_enable \t= 1;\n\n\t/* Default sctp sockets to use md5 as their hmac alg */\n#if defined (CONFIG_SCTP_DEFAULT_COOKIE_HMAC_MD5)\n\tnet->sctp.sctp_hmac_alg\t\t\t= \"md5\";\n#elif defined (CONFIG_SCTP_DEFAULT_COOKIE_HMAC_SHA1)\n\tnet->sctp.sctp_hmac_alg\t\t\t= \"sha1\";\n#else\n\tnet->sctp.sctp_hmac_alg\t\t\t= NULL;\n#endif\n\n\t/* Max.Burst\t\t - 4 */\n\tnet->sctp.max_burst\t\t\t= SCTP_DEFAULT_MAX_BURST;\n\n\t/* Association.Max.Retrans - 10 attempts\n\t * Path.Max.Retrans - 5 attempts (per destination address)\n\t * Max.Init.Retransmits - 8 attempts\n\t */\n\tnet->sctp.max_retrans_association\t= 10;\n\tnet->sctp.max_retrans_path\t\t= 5;\n\tnet->sctp.max_retrans_init\t\t= 8;\n\n\t/* Sendbuffer growth\t - do per-socket accounting */\n\tnet->sctp.sndbuf_policy\t\t\t= 0;\n\n\t/* Rcvbuffer growth\t - do per-socket accounting */\n\tnet->sctp.rcvbuf_policy\t\t\t= 0;\n\n\t/* HB.interval - 30 seconds */\n\tnet->sctp.hb_interval\t\t\t= SCTP_DEFAULT_TIMEOUT_HEARTBEAT;\n\n\t/* delayed SACK timeout */\n\tnet->sctp.sack_timeout\t\t\t= SCTP_DEFAULT_TIMEOUT_SACK;\n\n\t/* Disable ADDIP by default. */\n\tnet->sctp.addip_enable = 0;\n\tnet->sctp.addip_noauth = 0;\n\tnet->sctp.default_auto_asconf = 0;\n\n\t/* Enable PR-SCTP by default. */\n\tnet->sctp.prsctp_enable = 1;\n\n\t/* Disable AUTH by default. */\n\tnet->sctp.auth_enable = 0;\n\n\t/* Set SCOPE policy to enabled */\n\tnet->sctp.scope_policy = SCTP_SCOPE_POLICY_ENABLE;\n\n\t/* Set the default rwnd update threshold */\n\tnet->sctp.rwnd_upd_shift = SCTP_DEFAULT_RWND_SHIFT;\n\n\t/* Initialize maximum autoclose timeout. */\n\tnet->sctp.max_autoclose\t\t= INT_MAX / HZ;\n\n\tstatus = sctp_sysctl_net_register(net);\n\tif (status)\n\t\tgoto err_sysctl_register;\n\n\t/* Allocate and initialise sctp mibs. */\n\tstatus = init_sctp_mibs(net);\n\tif (status)\n\t\tgoto err_init_mibs;\n\n\t/* Initialize proc fs directory. */\n\tstatus = sctp_proc_init(net);\n\tif (status)\n\t\tgoto err_init_proc;\n\n\tsctp_dbg_objcnt_init(net);\n\n\t/* Initialize the control inode/socket for handling OOTB packets. */\n\tif ((status = sctp_ctl_sock_init(net))) {\n\t\tpr_err(\"Failed to initialize the SCTP control sock\\n\");\n\t\tgoto err_ctl_sock_init;\n\t}\n\n\t/* Initialize the local address list. */\n\tINIT_LIST_HEAD(&net->sctp.local_addr_list);\n\tspin_lock_init(&net->sctp.local_addr_lock);\n\tsctp_get_local_addr_list(net);\n\n\t/* Initialize the address event list */\n\tINIT_LIST_HEAD(&net->sctp.addr_waitq);\n\tINIT_LIST_HEAD(&net->sctp.auto_asconf_splist);\n\tspin_lock_init(&net->sctp.addr_wq_lock);\n\tnet->sctp.addr_wq_timer.expires = 0;\n\tsetup_timer(&net->sctp.addr_wq_timer, sctp_addr_wq_timeout_handler,\n\t\t (unsigned long)net);\n\n\treturn 0;\n\nerr_ctl_sock_init:\n\tsctp_dbg_objcnt_exit(net);\n\tsctp_proc_exit(net);\nerr_init_proc:\n\tcleanup_sctp_mibs(net);\nerr_init_mibs:\n\tsctp_sysctl_net_unregister(net);\nerr_sysctl_register:\n\treturn status;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'sctp: fix race on protocol/netns initialization\n\nConsider sctp module is unloaded and is being requested because an user\nis creating a sctp socket.\n\nDuring initialization, sctp will add the new protocol type and then\ninitialize pernet subsys:\n\n status = sctp_v4_protosw_init();\n if (status)\n goto err_protosw_init;\n\n status = sctp_v6_protosw_init();\n if (status)\n goto err_v6_protosw_init;\n\n status = register_pernet_subsys(&sctp_net_ops);\n\nThe problem is that after those calls to sctp_v{4,6}_protosw_init(), it\nis possible for userspace to create SCTP sockets like if the module is\nalready fully loaded. If that happens, one of the possible effects is\nthat we will have readers for net->sctp.local_addr_list list earlier\nthan expected and sctp_net_init() does not take precautions while\ndealing with that list, leading to a potential panic but not limited to\nthat, as sctp_sock_init() will copy a bunch of blank/partially\ninitialized values from net->sctp.\n\nThe race happens like this:\n\n CPU 0 | CPU 1\n socket() |\n __sock_create | socket()\n inet_create | __sock_create\n list_for_each_entry_rcu( |\n answer, &inetsw[sock->type], |\n list) { | inet_create\n /* no hits */ |\n if (unlikely(err)) { |\n ... |\n request_module() |\n /* socket creation is blocked |\n * the module is fully loaded |\n */ |\n sctp_init |\n sctp_v4_protosw_init |\n inet_register_protosw |\n list_add_rcu(&p->list, |\n last_perm); |\n | list_for_each_entry_rcu(\n | answer, &inetsw[sock->type],\n sctp_v6_protosw_init | list) {\n | /* hit, so assumes protocol\n | * is already loaded\n | */\n | /* socket creation continues\n | * before netns is initialized\n | */\n register_pernet_subsys |\n\nSimply inverting the initialization order between\nregister_pernet_subsys() and sctp_v4_protosw_init() is not possible\nbecause register_pernet_subsys() will create a control sctp socket, so\nthe protocol must be already visible by then. Deferring the socket\ncreation to a work-queue is not good specially because we loose the\nability to handle its errors.\n\nSo, as suggested by Vlad, the fix is to split netns initialization in\ntwo moments: defaults and control socket, so that the defaults are\nalready loaded by when we register the protocol, while control socket\ninitialization is kept at the same moment it is today.\n\nFixes: 4db67e808640 (\"sctp: Make the address lists per network namespace\")\nSigned-off-by: Vlad Yasevich \nSigned-off-by: Marcelo Ricardo Leitner \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ::tensorflow::Status ValidateInputs(\n std::vector rt_nested_splits,\n const Tensor& rt_dense_values_in) {\n for (int i = 0; i < rt_nested_splits.size(); ++i) {\n if (rt_nested_splits[i].size() == 0) {\n return InvalidArgument(\"ragged splits may not be empty.\");\n }\n if (rt_nested_splits[i](0) != 0) {\n return InvalidArgument(\"First value of ragged splits must be 0.\");\n }\n if (i > 0) {\n SPLITS_TYPE last_split =\n rt_nested_splits[i - 1](rt_nested_splits[i - 1].size() - 1);\n if (rt_nested_splits[i].size() != last_split + 1) {\n return InvalidArgument(\n \"Final value of ragged splits must match the length \"\n \"the corresponding ragged values.\");\n }\n }\n }\n if (rt_dense_values_in.dim_size(0) !=\n rt_nested_splits.back()(rt_nested_splits.back().size() - 1)) {\n return InvalidArgument(\n \"Final value of ragged splits must match the length \"\n \"the corresponding ragged values.\");\n }\n return ::tensorflow::Status::OK();\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-824'], 'message': 'Add missing validation to `RaggedTensorToSparse`.\n\nThere needs to be a check that the splits allow for valid ragged tensors.\n\nPiperOrigin-RevId: 387712169\nChange-Id: I2499175324b82b65d159a260c7f83b98ceb5cc7d'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: AcpiNsEvaluate (\n ACPI_EVALUATE_INFO *Info)\n{\n ACPI_STATUS Status;\n\n\n ACPI_FUNCTION_TRACE (NsEvaluate);\n\n\n if (!Info)\n {\n return_ACPI_STATUS (AE_BAD_PARAMETER);\n }\n\n if (!Info->Node)\n {\n /*\n * Get the actual namespace node for the target object if we\n * need to. Handles these cases:\n *\n * 1) Null node, valid pathname from root (absolute path)\n * 2) Node and valid pathname (path relative to Node)\n * 3) Node, Null pathname\n */\n Status = AcpiNsGetNode (Info->PrefixNode, Info->RelativePathname,\n ACPI_NS_NO_UPSEARCH, &Info->Node);\n if (ACPI_FAILURE (Status))\n {\n return_ACPI_STATUS (Status);\n }\n }\n\n /*\n * For a method alias, we must grab the actual method node so that\n * proper scoping context will be established before execution.\n */\n if (AcpiNsGetType (Info->Node) == ACPI_TYPE_LOCAL_METHOD_ALIAS)\n {\n Info->Node = ACPI_CAST_PTR (\n ACPI_NAMESPACE_NODE, Info->Node->Object);\n }\n\n /* Complete the info block initialization */\n\n Info->ReturnObject = NULL;\n Info->NodeFlags = Info->Node->Flags;\n Info->ObjDesc = AcpiNsGetAttachedObject (Info->Node);\n\n ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, \"%s [%p] Value %p\\n\",\n Info->RelativePathname, Info->Node,\n AcpiNsGetAttachedObject (Info->Node)));\n\n /* Get info if we have a predefined name (_HID, etc.) */\n\n Info->Predefined = AcpiUtMatchPredefinedMethod (Info->Node->Name.Ascii);\n\n /* Get the full pathname to the object, for use in warning messages */\n\n Info->FullPathname = AcpiNsGetNormalizedPathname (Info->Node, TRUE);\n if (!Info->FullPathname)\n {\n return_ACPI_STATUS (AE_NO_MEMORY);\n }\n\n /* Count the number of arguments being passed in */\n\n Info->ParamCount = 0;\n if (Info->Parameters)\n {\n while (Info->Parameters[Info->ParamCount])\n {\n Info->ParamCount++;\n }\n\n /* Warn on impossible argument count */\n\n if (Info->ParamCount > ACPI_METHOD_NUM_ARGS)\n {\n ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, ACPI_WARN_ALWAYS,\n \"Excess arguments (%u) - using only %u\",\n Info->ParamCount, ACPI_METHOD_NUM_ARGS));\n\n Info->ParamCount = ACPI_METHOD_NUM_ARGS;\n }\n }\n\n /*\n * For predefined names: Check that the declared argument count\n * matches the ACPI spec -- otherwise this is a BIOS error.\n */\n AcpiNsCheckAcpiCompliance (Info->FullPathname, Info->Node,\n Info->Predefined);\n\n /*\n * For all names: Check that the incoming argument count for\n * this method/object matches the actual ASL/AML definition.\n */\n AcpiNsCheckArgumentCount (Info->FullPathname, Info->Node,\n Info->ParamCount, Info->Predefined);\n\n /* For predefined names: Typecheck all incoming arguments */\n\n AcpiNsCheckArgumentTypes (Info);\n\n /*\n * Three major evaluation cases:\n *\n * 1) Object types that cannot be evaluated by definition\n * 2) The object is a control method -- execute it\n * 3) The object is not a method -- just return it's current value\n */\n switch (AcpiNsGetType (Info->Node))\n {\n case ACPI_TYPE_DEVICE:\n case ACPI_TYPE_EVENT:\n case ACPI_TYPE_MUTEX:\n case ACPI_TYPE_REGION:\n case ACPI_TYPE_THERMAL:\n case ACPI_TYPE_LOCAL_SCOPE:\n /*\n * 1) Disallow evaluation of certain object types. For these,\n * object evaluation is undefined and not supported.\n */\n ACPI_ERROR ((AE_INFO,\n \"%s: Evaluation of object type [%s] is not supported\",\n Info->FullPathname,\n AcpiUtGetTypeName (Info->Node->Type)));\n\n Status = AE_TYPE;\n goto Cleanup;\n\n case ACPI_TYPE_METHOD:\n /*\n * 2) Object is a control method - execute it\n */\n\n /* Verify that there is a method object associated with this node */\n\n if (!Info->ObjDesc)\n {\n ACPI_ERROR ((AE_INFO, \"%s: Method has no attached sub-object\",\n Info->FullPathname));\n Status = AE_NULL_OBJECT;\n goto Cleanup;\n }\n\n ACPI_DEBUG_PRINT ((ACPI_DB_EXEC,\n \"**** Execute method [%s] at AML address %p length %X\\n\",\n Info->FullPathname,\n Info->ObjDesc->Method.AmlStart + 1,\n Info->ObjDesc->Method.AmlLength - 1));\n\n /*\n * Any namespace deletion must acquire both the namespace and\n * interpreter locks to ensure that no thread is using the portion of\n * the namespace that is being deleted.\n *\n * Execute the method via the interpreter. The interpreter is locked\n * here before calling into the AML parser\n */\n AcpiExEnterInterpreter ();\n Status = AcpiPsExecuteMethod (Info);\n AcpiExExitInterpreter ();\n break;\n\n default:\n /*\n * 3) All other non-method objects -- get the current object value\n */\n\n /*\n * Some objects require additional resolution steps (e.g., the Node\n * may be a field that must be read, etc.) -- we can't just grab\n * the object out of the node.\n *\n * Use ResolveNodeToValue() to get the associated value.\n *\n * NOTE: we can get away with passing in NULL for a walk state because\n * the Node is guaranteed to not be a reference to either a method\n * local or a method argument (because this interface is never called\n * from a running method.)\n *\n * Even though we do not directly invoke the interpreter for object\n * resolution, we must lock it because we could access an OpRegion.\n * The OpRegion access code assumes that the interpreter is locked.\n */\n AcpiExEnterInterpreter ();\n\n /* TBD: ResolveNodeToValue has a strange interface, fix */\n\n Info->ReturnObject = ACPI_CAST_PTR (ACPI_OPERAND_OBJECT, Info->Node);\n\n Status = AcpiExResolveNodeToValue (ACPI_CAST_INDIRECT_PTR (\n ACPI_NAMESPACE_NODE, &Info->ReturnObject), NULL);\n AcpiExExitInterpreter ();\n\n if (ACPI_FAILURE (Status))\n {\n Info->ReturnObject = NULL;\n goto Cleanup;\n }\n\n ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, \"Returned object %p [%s]\\n\",\n Info->ReturnObject,\n AcpiUtGetObjectTypeName (Info->ReturnObject)));\n\n Status = AE_CTRL_RETURN_VALUE; /* Always has a \"return value\" */\n break;\n }\n\n /*\n * For predefined names, check the return value against the ACPI\n * specification. Some incorrect return value types are repaired.\n */\n (void) AcpiNsCheckReturnValue (Info->Node, Info, Info->ParamCount,\n Status, &Info->ReturnObject);\n\n /* Check if there is a return value that must be dealt with */\n\n if (Status == AE_CTRL_RETURN_VALUE)\n {\n /* If caller does not want the return value, delete it */\n\n if (Info->Flags & ACPI_IGNORE_RETURN_VALUE)\n {\n AcpiUtRemoveReference (Info->ReturnObject);\n Info->ReturnObject = NULL;\n }\n\n /* Map AE_CTRL_RETURN_VALUE to AE_OK, we are done with it */\n\n Status = AE_OK;\n }\n\n ACPI_DEBUG_PRINT ((ACPI_DB_NAMES,\n \"*** Completed evaluation of object %s ***\\n\",\n Info->RelativePathname));\n\nCleanup:\n /*\n * Namespace was unlocked by the handling AcpiNs* function, so we\n * just free the pathname and return\n */\n ACPI_FREE (Info->FullPathname);\n Info->FullPathname = NULL;\n return_ACPI_STATUS (Status);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'acpi: acpica: fix acpi operand cache leak in nseval.c\n\nI found an ACPI cache leak in ACPI early termination and boot continuing case.\n\nWhen early termination occurs due to malicious ACPI table, Linux kernel\nterminates ACPI function and continues to boot process. While kernel terminates\nACPI function, kmem_cache_destroy() reports Acpi-Operand cache leak.\n\nBoot log of ACPI operand cache leak is as follows:\n>[ 0.464168] ACPI: Added _OSI(Module Device)\n>[ 0.467022] ACPI: Added _OSI(Processor Device)\n>[ 0.469376] ACPI: Added _OSI(3.0 _SCP Extensions)\n>[ 0.471647] ACPI: Added _OSI(Processor Aggregator Device)\n>[ 0.477997] ACPI Error: Null stack entry at ffff880215c0aad8 (20170303/exresop-174)\n>[ 0.482706] ACPI Exception: AE_AML_INTERNAL, While resolving operands for [OpcodeName unavailable] (20170303/dswexec-461)\n>[ 0.487503] ACPI Error: Method parse/execution failed [\\DBG] (Node ffff88021710ab40), AE_AML_INTERNAL (20170303/psparse-543)\n>[ 0.492136] ACPI Error: Method parse/execution failed [\\_SB._INI] (Node ffff88021710a618), AE_AML_INTERNAL (20170303/psparse-543)\n>[ 0.497683] ACPI: Interpreter enabled\n>[ 0.499385] ACPI: (supports S0)\n>[ 0.501151] ACPI: Using IOAPIC for interrupt routing\n>[ 0.503342] ACPI Error: Null stack entry at ffff880215c0aad8 (20170303/exresop-174)\n>[ 0.506522] ACPI Exception: AE_AML_INTERNAL, While resolving operands for [OpcodeName unavailable] (20170303/dswexec-461)\n>[ 0.510463] ACPI Error: Method parse/execution failed [\\DBG] (Node ffff88021710ab40), AE_AML_INTERNAL (20170303/psparse-543)\n>[ 0.514477] ACPI Error: Method parse/execution failed [\\_PIC] (Node ffff88021710ab18), AE_AML_INTERNAL (20170303/psparse-543)\n>[ 0.518867] ACPI Exception: AE_AML_INTERNAL, Evaluating _PIC (20170303/bus-991)\n>[ 0.522384] kmem_cache_destroy Acpi-Operand: Slab cache still has objects\n>[ 0.524597] CPU: 1 PID: 1 Comm: swapper/0 Not tainted 4.12.0-rc5 #26\n>[ 0.526795] Hardware name: innotek GmbH VirtualBox/VirtualBox, BIOS VirtualBox 12/01/2006\n>[ 0.529668] Call Trace:\n>[ 0.530811] ? dump_stack+0x5c/0x81\n>[ 0.532240] ? kmem_cache_destroy+0x1aa/0x1c0\n>[ 0.533905] ? acpi_os_delete_cache+0xa/0x10\n>[ 0.535497] ? acpi_ut_delete_caches+0x3f/0x7b\n>[ 0.537237] ? acpi_terminate+0xa/0x14\n>[ 0.538701] ? acpi_init+0x2af/0x34f\n>[ 0.540008] ? acpi_sleep_proc_init+0x27/0x27\n>[ 0.541593] ? do_one_initcall+0x4e/0x1a0\n>[ 0.543008] ? kernel_init_freeable+0x19e/0x21f\n>[ 0.546202] ? rest_init+0x80/0x80\n>[ 0.547513] ? kernel_init+0xa/0x100\n>[ 0.548817] ? ret_from_fork+0x25/0x30\n>[ 0.550587] vgaarb: loaded\n>[ 0.551716] EDAC MC: Ver: 3.0.0\n>[ 0.553744] PCI: Probing PCI hardware\n>[ 0.555038] PCI host bridge to bus 0000:00\n> ... Continue to boot and log is omitted ...\n\nI analyzed this memory leak in detail and found AcpiNsEvaluate() function\nonly removes Info->ReturnObject in AE_CTRL_RETURN_VALUE case. But, when errors\noccur, the status value is not AE_CTRL_RETURN_VALUE, and Info->ReturnObject is\nalso not null. Therefore, this causes acpi operand memory leak.\n\nThis cache leak causes a security threat because an old kernel (<= 4.9) shows\nmemory locations of kernel functions in stack dump. Some malicious users\ncould use this information to neutralize kernel ASLR.\n\nI made a patch to fix ACPI operand cache leak.\n\nSigned-off-by: Seunghun Han '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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 *alloc_huge_page(struct vm_area_struct *vma,\n\t\t\t\t unsigned long addr, int avoid_reserve)\n{\n\tstruct hstate *h = hstate_vma(vma);\n\tstruct page *page;\n\tstruct address_space *mapping = vma->vm_file->f_mapping;\n\tstruct inode *inode = mapping->host;\n\tlong chg;\n\n\t/*\n\t * Processes that did not create the mapping will have no reserves and\n\t * will not have accounted against quota. Check that the quota can be\n\t * made before satisfying the allocation\n\t * MAP_NORESERVE mappings may also need pages and quota allocated\n\t * if no reserve mapping overlaps.\n\t */\n\tchg = vma_needs_reservation(h, vma, addr);\n\tif (chg < 0)\n\t\treturn ERR_PTR(-VM_FAULT_OOM);\n\tif (chg)\n\t\tif (hugetlb_get_quota(inode->i_mapping, chg))\n\t\t\treturn ERR_PTR(-VM_FAULT_SIGBUS);\n\n\tspin_lock(&hugetlb_lock);\n\tpage = dequeue_huge_page_vma(h, vma, addr, avoid_reserve);\n\tspin_unlock(&hugetlb_lock);\n\n\tif (!page) {\n\t\tpage = alloc_buddy_huge_page(h, NUMA_NO_NODE);\n\t\tif (!page) {\n\t\t\thugetlb_put_quota(inode->i_mapping, chg);\n\t\t\treturn ERR_PTR(-VM_FAULT_SIGBUS);\n\t\t}\n\t}\n\n\tset_page_private(page, (unsigned long) mapping);\n\n\tvma_commit_reservation(h, vma, addr);\n\n\treturn page;\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: void hugetlb_put_quota(struct address_space *mapping, long delta)\n{\n\tstruct hugetlbfs_sb_info *sbinfo = HUGETLBFS_SB(mapping->host->i_sb);\n\n\tif (sbinfo->free_blocks > -1) {\n\t\tspin_lock(&sbinfo->stat_lock);\n\t\tsbinfo->free_blocks += delta;\n\t\tspin_unlock(&sbinfo->stat_lock);\n\t}\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 read_image_tga( gdIOCtx *ctx, oTga *tga )\n{\n\tint pixel_block_size = (tga->bits / 8);\n\tint image_block_size = (tga->width * tga->height) * pixel_block_size;\n\tuint8_t* decompression_buffer = NULL;\n\tunsigned char* conversion_buffer = NULL;\n\tint buffer_caret = 0;\n\tint bitmap_caret = 0;\n\tint i = 0;\n\tint j = 0;\n\tuint8_t encoded_pixels;\n\n\tif(overflow2(tga->width, tga->height)) {\n\t\treturn -1;\n\t}\n\n\tif(overflow2(tga->width * tga->height, pixel_block_size)) {\n\t\treturn -1;\n\t}\n\n\tif(overflow2(image_block_size, sizeof(int))) {\n\t\treturn -1;\n\t}\n\n\t/*! \\todo Add more image type support.\n\t */\n\tif (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE)\n\t\treturn -1;\n\n\t/*!\t\\brief Allocate memmory for image block\n\t * Allocate a chunk of memory for the image block to be passed into.\n\t */\n\ttga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int));\n\tif (tga->bitmap == NULL)\n\t\treturn -1;\n\n\tswitch (tga->imagetype) {\n\tcase TGA_TYPE_RGB:\n\t\t/*! \\brief Read in uncompressed RGB TGA\n\t\t * Chunk load the pixel data from an uncompressed RGB type TGA.\n\t\t */\n\t\tconversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));\n\t\tif (conversion_buffer == NULL) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tif (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {\n\t\t\tgd_error(\"gd-tga: premature end of image data\\n\");\n\t\t\tgdFree(conversion_buffer);\n\t\t\treturn -1;\n\t\t}\n\n\t\twhile (buffer_caret < image_block_size) {\n\t\t\ttga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret];\n\t\t\tbuffer_caret++;\n\t\t}\n\n\t\tgdFree(conversion_buffer);\n\t\tbreak;\n\n\tcase TGA_TYPE_RGB_RLE:\n\t\t/*! \\brief Read in RLE compressed RGB TGA\n\t\t * Chunk load the pixel data from an RLE compressed RGB type TGA.\n\t\t */\n\t\tdecompression_buffer = (uint8_t*) gdMalloc(image_block_size * sizeof(uint8_t));\n\t\tif (decompression_buffer == NULL) {\n\t\t\treturn -1;\n\t\t}\n\t\tconversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));\n\t\tif (conversion_buffer == NULL) {\n\t\t\tgd_error(\"gd-tga: premature end of image data\\n\");\n\t\t\tgdFree( decompression_buffer );\n\t\t\treturn -1;\n\t\t}\n\n\t\tif (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {\n\t\t\tgdFree(conversion_buffer);\n\t\t\tgdFree(decompression_buffer);\n\t\t\treturn -1;\n\t\t}\n\n\t\tbuffer_caret = 0;\n\n\t\twhile( buffer_caret < image_block_size) {\n\t\t\tdecompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret];\n\t\t\tbuffer_caret++;\n\t\t}\n\n\t\tbuffer_caret = 0;\n\n\t\twhile( bitmap_caret < image_block_size ) {\n\n\t\t\tif ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) {\n\t\t\t\tencoded_pixels = ( ( decompression_buffer[ buffer_caret ] & 127 ) + 1 );\n\t\t\t\tbuffer_caret++;\n\n\t\t\t\tfor (i = 0; i < encoded_pixels; i++) {\n\t\t\t\t\tfor (j = 0; j < pixel_block_size; j++, bitmap_caret++) {\n\t\t\t\t\t\ttga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbuffer_caret += pixel_block_size;\n\t\t\t} else {\n\t\t\t\tencoded_pixels = decompression_buffer[ buffer_caret ] + 1;\n\t\t\t\tbuffer_caret++;\n\n\t\t\t\tfor (i = 0; i < encoded_pixels; i++) {\n\t\t\t\t\tfor( j = 0; j < pixel_block_size; j++, bitmap_caret++ ) {\n\t\t\t\t\t\ttga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];\n\t\t\t\t\t}\n\t\t\t\t\tbuffer_caret += pixel_block_size;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tgdFree( decompression_buffer );\n\t\tgdFree( conversion_buffer );\n\t\tbreak;\n\t}\n\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415', 'CWE-125'], 'message': 'bug #248, fix Out-Of-Bounds Read in read_image_tga'" }, { "text": "[INST] Given the following code containing errors, provide Common 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 WebContents::SendIPCMessageToFrame(bool internal,\n int32_t frame_id,\n const std::string& channel,\n v8::Local args) {\n v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();\n blink::CloneableMessage message;\n if (!gin::ConvertFromV8(isolate, args, &message)) {\n isolate->ThrowException(v8::Exception::Error(\n gin::StringToV8(isolate, \"Failed to serialize arguments\")));\n return false;\n }\n auto frames = web_contents()->GetAllFrames();\n auto iter = std::find_if(frames.begin(), frames.end(), [frame_id](auto* f) {\n return f->GetRoutingID() == frame_id;\n });\n if (iter == frames.end())\n return false;\n if (!(*iter)->IsRenderFrameLive())\n return false;\n\n mojo::AssociatedRemote electron_renderer;\n (*iter)->GetRemoteAssociatedInterfaces()->GetInterface(&electron_renderer);\n electron_renderer->Message(internal, channel, std::move(message),\n 0 /* sender_id */);\n return true;\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_ws_create_req(agooCon c, long mlen) {\n uint8_t\top = 0x0F & *c->buf;\n\n if (NULL == (c->req = agoo_req_create(mlen))) {\n\tagoo_log_cat(&agoo_error_cat, \"Out of memory attempting to allocate request.\");\n\treturn true;\n }\n if (NULL == c->up || agoo_server.ctx_nil_value == c->up->ctx) {\n\treturn true;\n }\n memset(c->req, 0, sizeof(struct _agooReq));\n if ((long)c->bcnt <= mlen) {\n\tmemcpy(c->req->msg, c->buf, c->bcnt);\n\tif ((long)c->bcnt < mlen) {\n\t memset(c->req->msg + c->bcnt, 0, mlen - c->bcnt);\n\t}\n } else {\n\tmemcpy(c->req->msg, c->buf, mlen);\n }\n c->req->msg[mlen] = '\\0';\n c->req->mlen = mlen;\n c->req->method = (AGOO_WS_OP_BIN == op) ? AGOO_ON_BIN : AGOO_ON_MSG;\n c->req->upgrade = AGOO_UP_NONE;\n c->req->up = c->up;\n c->req->res = NULL;\n if (c->up->on_msg) {\n\tc->req->hook = agoo_hook_create(AGOO_NONE, NULL, c->up->ctx, PUSH_HOOK, &agoo_server.eval_queue);\n }\n return false;\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: BGD_DECLARE(gdImagePtr) gdImageCreateFromTgaCtx(gdIOCtx* ctx)\n{\n\tint bitmap_caret = 0;\n\toTga *tga = NULL;\n\t/*\tint pixel_block_size = 0;\n\t\tint image_block_size = 0; */\n\tvolatile gdImagePtr image = NULL;\n\tint x = 0;\n\tint y = 0;\n\n\ttga = (oTga *) gdMalloc(sizeof(oTga));\n\tif (!tga) {\n\t\treturn NULL;\n\t}\n\n\ttga->bitmap = NULL;\n\ttga->ident = NULL;\n\n\tif (read_header_tga(ctx, tga) < 0) {\n\t\tfree_tga(tga);\n\t\treturn NULL;\n\t}\n\n\t/*TODO: Will this be used?\n\t\tpixel_block_size = tga->bits / 8;\n\t\timage_block_size = (tga->width * tga->height) * pixel_block_size;\n\t*/\n\n\tif (read_image_tga(ctx, tga) < 0) {\n\t\tfree_tga(tga);\n\t\treturn NULL;\n\t}\n\n\timage = gdImageCreateTrueColor((int)tga->width, (int)tga->height );\n\n\tif (image == 0) {\n\t\tfree_tga( tga );\n\t\treturn NULL;\n\t}\n\n\t/*!\t\\brief Populate GD image object\n\t * Copy the pixel data from our tga bitmap buffer into the GD image\n\t * Disable blending and save the alpha channel per default\n\t */\n\tif (tga->alphabits) {\n\t\tgdImageAlphaBlending(image, 0);\n\t\tgdImageSaveAlpha(image, 1);\n\t}\n\n\t/* TODO: use alphabits as soon as we support 24bit and other alpha bps (ie != 8bits) */\n\tfor (y = 0; y < tga->height; y++) {\n\t\tregister int *tpix = image->tpixels[y];\n\t\tfor ( x = 0; x < tga->width; x++, tpix++) {\n\t\t\tif (tga->bits == TGA_BPP_24) {\n\t\t\t\t*tpix = gdTrueColor(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret]);\n\t\t\t\tbitmap_caret += 3;\n\t\t\t} else if (tga->bits == TGA_BPP_32 || tga->alphabits) {\n\t\t\t\tregister int a = tga->bitmap[bitmap_caret + 3];\n\n\t\t\t\t*tpix = gdTrueColorAlpha(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret], gdAlphaMax - (a >> 1));\n\t\t\t\tbitmap_caret += 4;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (tga->flipv && tga->fliph) {\n\t\tgdImageFlipBoth(image);\n\t} else if (tga->flipv) {\n\t\tgdImageFlipVertical(image);\n\t} else if (tga->fliph) {\n\t\tgdImageFlipHorizontal(image);\n\t}\n\n\tfree_tga(tga);\n\n\treturn image;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Unsupported TGA bpp/alphabit combinations should error gracefully\n\nCurrently, only 24bpp without alphabits and 32bpp with 8 alphabits are\nreally supported. All other combinations will be rejected with a warning.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool PM_io_parser::read_hedge(Halfedge_handle e)\n{ // syntax: index { opposite, prev, next, vertex, face, mark }\n int n, eo, epr, ene, v, f; bool m;\n if ( !(in >> n) ||\n !check_sep(\"{\") ||\n !(in >> eo) || !check_sep(\",\") ||\n !(in >> epr) || !check_sep(\",\") ||\n !(in >> ene) || !check_sep(\",\") ||\n !(in >> v) || !check_sep(\",\") ||\n !(in >> f) || !check_sep(\",\") ||\n !(in >> m) || !check_sep(\"}\") )\n return false;\n CGAL_assertion_msg\n (eo >= 0 || (std::size_t) eo < en || epr >= 0 || (std::size_t) epr < en || ene >= 0 || (std::size_t) ene < en ||\n v >= 0 || (std::size_t) v < vn || f >= 0 || (std::size_t) f < fn ,\n \"wrong index in read_hedge\");\n\n // precond: objects exist!\n CGAL_assertion(EI[e->opposite()]);\n e->set_prev(Halfedge_of[epr]);\n e->set_next(Halfedge_of[ene]);\n e->set_vertex(Vertex_of[v]);\n e->set_face(Face_of[f]);\n mark(e) = m;\n return true;\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: CollationCreate(const char *collname, Oid collnamespace,\n\t\t\t\tOid collowner,\n\t\t\t\tchar collprovider,\n\t\t\t\tbool collisdeterministic,\n\t\t\t\tint32 collencoding,\n\t\t\t\tconst char *collcollate, const char *collctype,\n\t\t\t\tconst char *collversion,\n\t\t\t\tbool if_not_exists,\n\t\t\t\tbool quiet)\n{\n\tRelation\trel;\n\tTupleDesc\ttupDesc;\n\tHeapTuple\ttup;\n\tDatum\t\tvalues[Natts_pg_collation];\n\tbool\t\tnulls[Natts_pg_collation];\n\tNameData\tname_name,\n\t\t\t\tname_collate,\n\t\t\t\tname_ctype;\n\tOid\t\t\toid;\n\tObjectAddress myself,\n\t\t\t\treferenced;\n\n\tAssertArg(collname);\n\tAssertArg(collnamespace);\n\tAssertArg(collowner);\n\tAssertArg(collcollate);\n\tAssertArg(collctype);\n\n\t/*\n\t * Make sure there is no existing collation of same name & encoding.\n\t *\n\t * This would be caught by the unique index anyway; we're just giving a\n\t * friendlier error message. The unique index provides a backstop against\n\t * race conditions.\n\t */\n\tif (SearchSysCacheExists3(COLLNAMEENCNSP,\n\t\t\t\t\t\t\t PointerGetDatum(collname),\n\t\t\t\t\t\t\t Int32GetDatum(collencoding),\n\t\t\t\t\t\t\t ObjectIdGetDatum(collnamespace)))\n\t{\n\t\tif (quiet)\n\t\t\treturn InvalidOid;\n\t\telse if (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 collencoding == -1\n\t\t\t\t\t ? errmsg(\"collation \\\"%s\\\" already exists, skipping\",\n\t\t\t\t\t\t\t collname)\n\t\t\t\t\t : errmsg(\"collation \\\"%s\\\" for encoding \\\"%s\\\" already exists, skipping\",\n\t\t\t\t\t\t\t collname, pg_encoding_to_char(collencoding))));\n\t\t\treturn InvalidOid;\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 collencoding == -1\n\t\t\t\t\t ? errmsg(\"collation \\\"%s\\\" already exists\",\n\t\t\t\t\t\t\t collname)\n\t\t\t\t\t : errmsg(\"collation \\\"%s\\\" for encoding \\\"%s\\\" already exists\",\n\t\t\t\t\t\t\t collname, pg_encoding_to_char(collencoding))));\n\t}\n\n\t/* open pg_collation; see below about the lock level */\n\trel = table_open(CollationRelationId, ShareRowExclusiveLock);\n\n\t/*\n\t * Also forbid a specific-encoding collation shadowing an any-encoding\n\t * collation, or an any-encoding collation being shadowed (see\n\t * get_collation_name()). This test is not backed up by the unique index,\n\t * so we take a ShareRowExclusiveLock earlier, to protect against\n\t * concurrent changes fooling this check.\n\t */\n\tif ((collencoding == -1 &&\n\t\t SearchSysCacheExists3(COLLNAMEENCNSP,\n\t\t\t\t\t\t\t PointerGetDatum(collname),\n\t\t\t\t\t\t\t Int32GetDatum(GetDatabaseEncoding()),\n\t\t\t\t\t\t\t ObjectIdGetDatum(collnamespace))) ||\n\t\t(collencoding != -1 &&\n\t\t SearchSysCacheExists3(COLLNAMEENCNSP,\n\t\t\t\t\t\t\t PointerGetDatum(collname),\n\t\t\t\t\t\t\t Int32GetDatum(-1),\n\t\t\t\t\t\t\t ObjectIdGetDatum(collnamespace))))\n\t{\n\t\tif (quiet)\n\t\t{\n\t\t\ttable_close(rel, NoLock);\n\t\t\treturn InvalidOid;\n\t\t}\n\t\telse if (if_not_exists)\n\t\t{\n\t\t\ttable_close(rel, NoLock);\n\t\t\tereport(NOTICE,\n\t\t\t\t\t(errcode(ERRCODE_DUPLICATE_OBJECT),\n\t\t\t\t\t errmsg(\"collation \\\"%s\\\" already exists, skipping\",\n\t\t\t\t\t\t\tcollname)));\n\t\t\treturn InvalidOid;\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(\"collation \\\"%s\\\" already exists\",\n\t\t\t\t\t\t\tcollname)));\n\t}\n\n\ttupDesc = RelationGetDescr(rel);\n\n\t/* form a tuple */\n\tmemset(nulls, 0, sizeof(nulls));\n\n\tnamestrcpy(&name_name, collname);\n\toid = GetNewOidWithIndex(rel, CollationOidIndexId,\n\t\t\t\t\t\t\t Anum_pg_collation_oid);\n\tvalues[Anum_pg_collation_oid - 1] = ObjectIdGetDatum(oid);\n\tvalues[Anum_pg_collation_collname - 1] = NameGetDatum(&name_name);\n\tvalues[Anum_pg_collation_collnamespace - 1] = ObjectIdGetDatum(collnamespace);\n\tvalues[Anum_pg_collation_collowner - 1] = ObjectIdGetDatum(collowner);\n\tvalues[Anum_pg_collation_collprovider - 1] = CharGetDatum(collprovider);\n\tvalues[Anum_pg_collation_collisdeterministic - 1] = BoolGetDatum(collisdeterministic);\n\tvalues[Anum_pg_collation_collencoding - 1] = Int32GetDatum(collencoding);\n\tnamestrcpy(&name_collate, collcollate);\n\tvalues[Anum_pg_collation_collcollate - 1] = NameGetDatum(&name_collate);\n\tnamestrcpy(&name_ctype, collctype);\n\tvalues[Anum_pg_collation_collctype - 1] = NameGetDatum(&name_ctype);\n\tif (collversion)\n\t\tvalues[Anum_pg_collation_collversion - 1] = CStringGetTextDatum(collversion);\n\telse\n\t\tnulls[Anum_pg_collation_collversion - 1] = true;\n\n\ttup = heap_form_tuple(tupDesc, values, nulls);\n\n\t/* insert a new tuple */\n\tCatalogTupleInsert(rel, tup);\n\tAssert(OidIsValid(oid));\n\n\t/* set up dependencies for the new collation */\n\tmyself.classId = CollationRelationId;\n\tmyself.objectId = oid;\n\tmyself.objectSubId = 0;\n\n\t/* create dependency on namespace */\n\treferenced.classId = NamespaceRelationId;\n\treferenced.objectId = collnamespace;\n\treferenced.objectSubId = 0;\n\trecordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);\n\n\t/* create dependency on owner */\n\trecordDependencyOnOwner(CollationRelationId, oid, collowner);\n\n\t/* dependency on extension */\n\trecordDependencyOnCurrentExtension(&myself, false);\n\n\t/* Post creation hook for new collation */\n\tInvokeObjectPostCreateHook(CollationRelationId, oid, 0);\n\n\theap_freetuple(tup);\n\ttable_close(rel, NoLock);\n\n\treturn oid;\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: rsvp_obj_print(netdissect_options *ndo,\n const u_char *pptr, u_int plen, const u_char *tptr,\n const char *ident, u_int tlen,\n const struct rsvp_common_header *rsvp_com_header)\n{\n const struct rsvp_object_header *rsvp_obj_header;\n const u_char *obj_tptr;\n union {\n const struct rsvp_obj_integrity_t *rsvp_obj_integrity;\n const struct rsvp_obj_frr_t *rsvp_obj_frr;\n } obj_ptr;\n\n u_short rsvp_obj_len,rsvp_obj_ctype,obj_tlen,intserv_serv_tlen;\n int hexdump,processed,padbytes,error_code,error_value,i,sigcheck;\n union {\n\tfloat f;\n\tuint32_t i;\n } bw;\n uint8_t namelen;\n\n u_int action, subchannel;\n\n while(tlen>=sizeof(struct rsvp_object_header)) {\n /* did we capture enough for fully decoding the object header ? */\n ND_TCHECK2(*tptr, sizeof(struct rsvp_object_header));\n\n rsvp_obj_header = (const struct rsvp_object_header *)tptr;\n rsvp_obj_len=EXTRACT_16BITS(rsvp_obj_header->length);\n rsvp_obj_ctype=rsvp_obj_header->ctype;\n\n if(rsvp_obj_len % 4) {\n ND_PRINT((ndo, \"%sERROR: object header size %u not a multiple of 4\", ident, rsvp_obj_len));\n return -1;\n }\n if(rsvp_obj_len < sizeof(struct rsvp_object_header)) {\n ND_PRINT((ndo, \"%sERROR: object header too short %u < %lu\", ident, rsvp_obj_len,\n (unsigned long)sizeof(const struct rsvp_object_header)));\n return -1;\n }\n\n ND_PRINT((ndo, \"%s%s Object (%u) Flags: [%s\",\n ident,\n tok2str(rsvp_obj_values,\n \"Unknown\",\n rsvp_obj_header->class_num),\n rsvp_obj_header->class_num,\n ((rsvp_obj_header->class_num) & 0x80) ? \"ignore\" : \"reject\"));\n\n if (rsvp_obj_header->class_num > 128)\n ND_PRINT((ndo, \" %s\",\n ((rsvp_obj_header->class_num) & 0x40) ? \"and forward\" : \"silently\"));\n\n ND_PRINT((ndo, \" if unknown], Class-Type: %s (%u), length: %u\",\n tok2str(rsvp_ctype_values,\n \"Unknown\",\n ((rsvp_obj_header->class_num)<<8)+rsvp_obj_ctype),\n rsvp_obj_ctype,\n rsvp_obj_len));\n\n if(tlen < rsvp_obj_len) {\n ND_PRINT((ndo, \"%sERROR: object goes past end of objects TLV\", ident));\n return -1;\n }\n\n obj_tptr=tptr+sizeof(struct rsvp_object_header);\n obj_tlen=rsvp_obj_len-sizeof(struct rsvp_object_header);\n\n /* did we capture enough for fully decoding the object ? */\n if (!ND_TTEST2(*tptr, rsvp_obj_len))\n return -1;\n hexdump=FALSE;\n\n switch(rsvp_obj_header->class_num) {\n case RSVP_OBJ_SESSION:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_IPV4:\n if (obj_tlen < 8)\n return -1;\n ND_PRINT((ndo, \"%s IPv4 DestAddress: %s, Protocol ID: 0x%02x\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n *(obj_tptr + sizeof(struct in_addr))));\n ND_PRINT((ndo, \"%s Flags: [0x%02x], DestPort %u\",\n ident,\n *(obj_tptr+5),\n EXTRACT_16BITS(obj_tptr + 6)));\n obj_tlen-=8;\n obj_tptr+=8;\n break;\n case RSVP_CTYPE_IPV6:\n if (obj_tlen < 20)\n return -1;\n ND_PRINT((ndo, \"%s IPv6 DestAddress: %s, Protocol ID: 0x%02x\",\n ident,\n ip6addr_string(ndo, obj_tptr),\n *(obj_tptr + sizeof(struct in6_addr))));\n ND_PRINT((ndo, \"%s Flags: [0x%02x], DestPort %u\",\n ident,\n *(obj_tptr+sizeof(struct in6_addr)+1),\n EXTRACT_16BITS(obj_tptr + sizeof(struct in6_addr) + 2)));\n obj_tlen-=20;\n obj_tptr+=20;\n break;\n\n case RSVP_CTYPE_TUNNEL_IPV6:\n if (obj_tlen < 36)\n return -1;\n ND_PRINT((ndo, \"%s IPv6 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s\",\n ident,\n ip6addr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr+18),\n ip6addr_string(ndo, obj_tptr + 20)));\n obj_tlen-=36;\n obj_tptr+=36;\n break;\n\n case RSVP_CTYPE_14: /* IPv6 p2mp LSP Tunnel */\n if (obj_tlen < 26)\n return -1;\n ND_PRINT((ndo, \"%s IPv6 P2MP LSP ID: 0x%08x, Tunnel ID: 0x%04x, Extended Tunnel ID: %s\",\n ident,\n EXTRACT_32BITS(obj_tptr),\n EXTRACT_16BITS(obj_tptr+6),\n ip6addr_string(ndo, obj_tptr + 8)));\n obj_tlen-=26;\n obj_tptr+=26;\n break;\n case RSVP_CTYPE_13: /* IPv4 p2mp LSP Tunnel */\n if (obj_tlen < 12)\n return -1;\n ND_PRINT((ndo, \"%s IPv4 P2MP LSP ID: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr+6),\n ipaddr_string(ndo, obj_tptr + 8)));\n obj_tlen-=12;\n obj_tptr+=12;\n break;\n case RSVP_CTYPE_TUNNEL_IPV4:\n case RSVP_CTYPE_UNI_IPV4:\n if (obj_tlen < 12)\n return -1;\n ND_PRINT((ndo, \"%s IPv4 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr+6),\n ipaddr_string(ndo, obj_tptr + 8)));\n obj_tlen-=12;\n obj_tptr+=12;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_CONFIRM:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_IPV4:\n if (obj_tlen < sizeof(struct in_addr))\n return -1;\n ND_PRINT((ndo, \"%s IPv4 Receiver Address: %s\",\n ident,\n ipaddr_string(ndo, obj_tptr)));\n obj_tlen-=sizeof(struct in_addr);\n obj_tptr+=sizeof(struct in_addr);\n break;\n case RSVP_CTYPE_IPV6:\n if (obj_tlen < sizeof(struct in6_addr))\n return -1;\n ND_PRINT((ndo, \"%s IPv6 Receiver Address: %s\",\n ident,\n ip6addr_string(ndo, obj_tptr)));\n obj_tlen-=sizeof(struct in6_addr);\n obj_tptr+=sizeof(struct in6_addr);\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_NOTIFY_REQ:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_IPV4:\n if (obj_tlen < sizeof(struct in_addr))\n return -1;\n ND_PRINT((ndo, \"%s IPv4 Notify Node Address: %s\",\n ident,\n ipaddr_string(ndo, obj_tptr)));\n obj_tlen-=sizeof(struct in_addr);\n obj_tptr+=sizeof(struct in_addr);\n break;\n case RSVP_CTYPE_IPV6:\n if (obj_tlen < sizeof(struct in6_addr))\n return-1;\n ND_PRINT((ndo, \"%s IPv6 Notify Node Address: %s\",\n ident,\n ip6addr_string(ndo, obj_tptr)));\n obj_tlen-=sizeof(struct in6_addr);\n obj_tptr+=sizeof(struct in6_addr);\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_SUGGESTED_LABEL: /* fall through */\n case RSVP_OBJ_UPSTREAM_LABEL: /* fall through */\n case RSVP_OBJ_RECOVERY_LABEL: /* fall through */\n case RSVP_OBJ_LABEL:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1:\n while(obj_tlen >= 4 ) {\n ND_PRINT((ndo, \"%s Label: %u\", ident, EXTRACT_32BITS(obj_tptr)));\n obj_tlen-=4;\n obj_tptr+=4;\n }\n break;\n case RSVP_CTYPE_2:\n if (obj_tlen < 4)\n return-1;\n ND_PRINT((ndo, \"%s Generalized Label: %u\",\n ident,\n EXTRACT_32BITS(obj_tptr)));\n obj_tlen-=4;\n obj_tptr+=4;\n break;\n case RSVP_CTYPE_3:\n if (obj_tlen < 12)\n return-1;\n ND_PRINT((ndo, \"%s Waveband ID: %u%s Start Label: %u, Stop Label: %u\",\n ident,\n EXTRACT_32BITS(obj_tptr),\n ident,\n EXTRACT_32BITS(obj_tptr+4),\n EXTRACT_32BITS(obj_tptr + 8)));\n obj_tlen-=12;\n obj_tptr+=12;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_STYLE:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1:\n if (obj_tlen < 4)\n return-1;\n ND_PRINT((ndo, \"%s Reservation Style: %s, Flags: [0x%02x]\",\n ident,\n tok2str(rsvp_resstyle_values,\n \"Unknown\",\n EXTRACT_24BITS(obj_tptr+1)),\n *(obj_tptr)));\n obj_tlen-=4;\n obj_tptr+=4;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_SENDER_TEMPLATE:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_IPV4:\n if (obj_tlen < 8)\n return-1;\n ND_PRINT((ndo, \"%s Source Address: %s, Source Port: %u\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr + 6)));\n obj_tlen-=8;\n obj_tptr+=8;\n break;\n case RSVP_CTYPE_IPV6:\n if (obj_tlen < 20)\n return-1;\n ND_PRINT((ndo, \"%s Source Address: %s, Source Port: %u\",\n ident,\n ip6addr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr + 18)));\n obj_tlen-=20;\n obj_tptr+=20;\n break;\n case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */\n if (obj_tlen < 40)\n return-1;\n ND_PRINT((ndo, \"%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x\"\n \"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x\",\n ident,\n ip6addr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr+18),\n ident,\n ip6addr_string(ndo, obj_tptr+20),\n EXTRACT_16BITS(obj_tptr + 38)));\n obj_tlen-=40;\n obj_tptr+=40;\n break;\n case RSVP_CTYPE_TUNNEL_IPV4:\n if (obj_tlen < 8)\n return-1;\n ND_PRINT((ndo, \"%s IPv4 Tunnel Sender Address: %s, LSP-ID: 0x%04x\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr + 6)));\n obj_tlen-=8;\n obj_tptr+=8;\n break;\n case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */\n if (obj_tlen < 16)\n return-1;\n ND_PRINT((ndo, \"%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x\"\n \"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr+6),\n ident,\n ipaddr_string(ndo, obj_tptr+8),\n EXTRACT_16BITS(obj_tptr + 12)));\n obj_tlen-=16;\n obj_tptr+=16;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_LABEL_REQ:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1:\n while(obj_tlen >= 4 ) {\n ND_PRINT((ndo, \"%s L3 Protocol ID: %s\",\n ident,\n tok2str(ethertype_values,\n \"Unknown Protocol (0x%04x)\",\n EXTRACT_16BITS(obj_tptr + 2))));\n obj_tlen-=4;\n obj_tptr+=4;\n }\n break;\n case RSVP_CTYPE_2:\n if (obj_tlen < 12)\n return-1;\n ND_PRINT((ndo, \"%s L3 Protocol ID: %s\",\n ident,\n tok2str(ethertype_values,\n \"Unknown Protocol (0x%04x)\",\n EXTRACT_16BITS(obj_tptr + 2))));\n ND_PRINT((ndo, \",%s merge capability\",((*(obj_tptr + 4)) & 0x80) ? \"no\" : \"\" ));\n ND_PRINT((ndo, \"%s Minimum VPI/VCI: %u/%u\",\n ident,\n (EXTRACT_16BITS(obj_tptr+4))&0xfff,\n (EXTRACT_16BITS(obj_tptr + 6)) & 0xfff));\n ND_PRINT((ndo, \"%s Maximum VPI/VCI: %u/%u\",\n ident,\n (EXTRACT_16BITS(obj_tptr+8))&0xfff,\n (EXTRACT_16BITS(obj_tptr + 10)) & 0xfff));\n obj_tlen-=12;\n obj_tptr+=12;\n break;\n case RSVP_CTYPE_3:\n if (obj_tlen < 12)\n return-1;\n ND_PRINT((ndo, \"%s L3 Protocol ID: %s\",\n ident,\n tok2str(ethertype_values,\n \"Unknown Protocol (0x%04x)\",\n EXTRACT_16BITS(obj_tptr + 2))));\n ND_PRINT((ndo, \"%s Minimum/Maximum DLCI: %u/%u, %s%s bit DLCI\",\n ident,\n (EXTRACT_32BITS(obj_tptr+4))&0x7fffff,\n (EXTRACT_32BITS(obj_tptr+8))&0x7fffff,\n (((EXTRACT_16BITS(obj_tptr+4)>>7)&3) == 0 ) ? \"10\" : \"\",\n (((EXTRACT_16BITS(obj_tptr + 4) >> 7) & 3) == 2 ) ? \"23\" : \"\"));\n obj_tlen-=12;\n obj_tptr+=12;\n break;\n case RSVP_CTYPE_4:\n if (obj_tlen < 4)\n return-1;\n ND_PRINT((ndo, \"%s LSP Encoding Type: %s (%u)\",\n ident,\n tok2str(gmpls_encoding_values,\n \"Unknown\",\n *obj_tptr),\n\t\t *obj_tptr));\n ND_PRINT((ndo, \"%s Switching Type: %s (%u), Payload ID: %s (0x%04x)\",\n ident,\n tok2str(gmpls_switch_cap_values,\n \"Unknown\",\n *(obj_tptr+1)),\n\t\t *(obj_tptr+1),\n tok2str(gmpls_payload_values,\n \"Unknown\",\n EXTRACT_16BITS(obj_tptr+2)),\n\t\t EXTRACT_16BITS(obj_tptr + 2)));\n obj_tlen-=4;\n obj_tptr+=4;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_RRO:\n case RSVP_OBJ_ERO:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_IPV4:\n while(obj_tlen >= 4 ) {\n\t\t u_char length;\n\n\t\t ND_TCHECK2(*obj_tptr, 4);\n\t\t length = *(obj_tptr + 1);\n ND_PRINT((ndo, \"%s Subobject Type: %s, length %u\",\n ident,\n tok2str(rsvp_obj_xro_values,\n \"Unknown %u\",\n RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)),\n length));\n\n if (length == 0) { /* prevent infinite loops */\n ND_PRINT((ndo, \"%s ERROR: zero length ERO subtype\", ident));\n break;\n }\n\n switch(RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)) {\n\t\t u_char prefix_length;\n\n case RSVP_OBJ_XRO_IPV4:\n\t\t\tif (length != 8) {\n\t\t\t\tND_PRINT((ndo, \" ERROR: length != 8\"));\n\t\t\t\tgoto invalid;\n\t\t\t}\n\t\t\tND_TCHECK2(*obj_tptr, 8);\n\t\t\tprefix_length = *(obj_tptr+6);\n\t\t\tif (prefix_length != 32) {\n\t\t\t\tND_PRINT((ndo, \" ERROR: Prefix length %u != 32\",\n\t\t\t\t\t prefix_length));\n\t\t\t\tgoto invalid;\n\t\t\t}\n ND_PRINT((ndo, \", %s, %s/%u, Flags: [%s]\",\n RSVP_OBJ_XRO_MASK_LOOSE(*obj_tptr) ? \"Loose\" : \"Strict\",\n ipaddr_string(ndo, obj_tptr+2),\n *(obj_tptr+6),\n bittok2str(rsvp_obj_rro_flag_values,\n \"none\",\n *(obj_tptr + 7)))); /* rfc3209 says that this field is rsvd. */\n break;\n case RSVP_OBJ_XRO_LABEL:\n\t\t\tif (length != 8) {\n\t\t\t\tND_PRINT((ndo, \" ERROR: length != 8\"));\n\t\t\t\tgoto invalid;\n\t\t\t}\n\t\t\tND_TCHECK2(*obj_tptr, 8);\n ND_PRINT((ndo, \", Flags: [%s] (%#x), Class-Type: %s (%u), %u\",\n bittok2str(rsvp_obj_rro_label_flag_values,\n \"none\",\n *(obj_tptr+2)),\n *(obj_tptr+2),\n tok2str(rsvp_ctype_values,\n \"Unknown\",\n *(obj_tptr+3) + 256*RSVP_OBJ_RRO),\n *(obj_tptr+3),\n EXTRACT_32BITS(obj_tptr + 4)));\n }\n obj_tlen-=*(obj_tptr+1);\n obj_tptr+=*(obj_tptr+1);\n }\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_HELLO:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1:\n case RSVP_CTYPE_2:\n if (obj_tlen < 8)\n return-1;\n ND_PRINT((ndo, \"%s Source Instance: 0x%08x, Destination Instance: 0x%08x\",\n ident,\n EXTRACT_32BITS(obj_tptr),\n EXTRACT_32BITS(obj_tptr + 4)));\n obj_tlen-=8;\n obj_tptr+=8;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_RESTART_CAPABILITY:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1:\n if (obj_tlen < 8)\n return-1;\n ND_PRINT((ndo, \"%s Restart Time: %ums, Recovery Time: %ums\",\n ident,\n EXTRACT_32BITS(obj_tptr),\n EXTRACT_32BITS(obj_tptr + 4)));\n obj_tlen-=8;\n obj_tptr+=8;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_SESSION_ATTRIBUTE:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_TUNNEL_IPV4:\n if (obj_tlen < 4)\n return-1;\n namelen = *(obj_tptr+3);\n if (obj_tlen < 4+namelen)\n return-1;\n ND_PRINT((ndo, \"%s Session Name: \", ident));\n for (i = 0; i < namelen; i++)\n safeputchar(ndo, *(obj_tptr + 4 + i));\n ND_PRINT((ndo, \"%s Setup Priority: %u, Holding Priority: %u, Flags: [%s] (%#x)\",\n ident,\n (int)*obj_tptr,\n (int)*(obj_tptr+1),\n bittok2str(rsvp_session_attribute_flag_values,\n \"none\",\n *(obj_tptr+2)),\n *(obj_tptr + 2)));\n obj_tlen-=4+*(obj_tptr+3);\n obj_tptr+=4+*(obj_tptr+3);\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n\tcase RSVP_OBJ_GENERALIZED_UNI:\n switch(rsvp_obj_ctype) {\n\t\tint subobj_type,af,subobj_len,total_subobj_len;\n\n case RSVP_CTYPE_1:\n\n if (obj_tlen < 4)\n return-1;\n\n\t\t/* read variable length subobjects */\n\t\ttotal_subobj_len = obj_tlen;\n while(total_subobj_len > 0) {\n subobj_len = EXTRACT_16BITS(obj_tptr);\n subobj_type = (EXTRACT_16BITS(obj_tptr+2))>>8;\n af = (EXTRACT_16BITS(obj_tptr+2))&0x00FF;\n\n ND_PRINT((ndo, \"%s Subobject Type: %s (%u), AF: %s (%u), length: %u\",\n ident,\n tok2str(rsvp_obj_generalized_uni_values, \"Unknown\", subobj_type),\n subobj_type,\n tok2str(af_values, \"Unknown\", af), af,\n subobj_len));\n\n if(subobj_len == 0)\n goto invalid;\n\n switch(subobj_type) {\n case RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS:\n case RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS:\n\n switch(af) {\n case AFNUM_INET:\n if (subobj_len < 8)\n return -1;\n ND_PRINT((ndo, \"%s UNI IPv4 TNA address: %s\",\n ident, ipaddr_string(ndo, obj_tptr + 4)));\n break;\n case AFNUM_INET6:\n if (subobj_len < 20)\n return -1;\n ND_PRINT((ndo, \"%s UNI IPv6 TNA address: %s\",\n ident, ip6addr_string(ndo, obj_tptr + 4)));\n break;\n case AFNUM_NSAP:\n if (subobj_len) {\n /* unless we have a TLV parser lets just hexdump */\n hexdump=TRUE;\n }\n break;\n }\n break;\n\n case RSVP_GEN_UNI_SUBOBJ_DIVERSITY:\n if (subobj_len) {\n /* unless we have a TLV parser lets just hexdump */\n hexdump=TRUE;\n }\n break;\n\n case RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL:\n if (subobj_len < 16) {\n return -1;\n }\n\n ND_PRINT((ndo, \"%s U-bit: %x, Label type: %u, Logical port id: %u, Label: %u\",\n ident,\n ((EXTRACT_32BITS(obj_tptr+4))>>31),\n ((EXTRACT_32BITS(obj_tptr+4))&0xFF),\n EXTRACT_32BITS(obj_tptr+8),\n EXTRACT_32BITS(obj_tptr + 12)));\n break;\n\n case RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL:\n if (subobj_len < 8) {\n return -1;\n }\n\n ND_PRINT((ndo, \"%s Service level: %u\",\n ident, (EXTRACT_32BITS(obj_tptr + 4)) >> 24));\n break;\n\n default:\n hexdump=TRUE;\n break;\n }\n total_subobj_len-=subobj_len;\n obj_tptr+=subobj_len;\n obj_tlen+=subobj_len;\n\t\t}\n\n if (total_subobj_len) {\n /* unless we have a TLV parser lets just hexdump */\n hexdump=TRUE;\n }\n break;\n\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_RSVP_HOP:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */\n case RSVP_CTYPE_IPV4:\n if (obj_tlen < 8)\n return-1;\n ND_PRINT((ndo, \"%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n EXTRACT_32BITS(obj_tptr + 4)));\n obj_tlen-=8;\n obj_tptr+=8;\n if (obj_tlen)\n hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */\n break;\n case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */\n case RSVP_CTYPE_IPV6:\n if (obj_tlen < 20)\n return-1;\n ND_PRINT((ndo, \"%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x\",\n ident,\n ip6addr_string(ndo, obj_tptr),\n EXTRACT_32BITS(obj_tptr + 16)));\n obj_tlen-=20;\n obj_tptr+=20;\n hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_TIME_VALUES:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1:\n if (obj_tlen < 4)\n return-1;\n ND_PRINT((ndo, \"%s Refresh Period: %ums\",\n ident,\n EXTRACT_32BITS(obj_tptr)));\n obj_tlen-=4;\n obj_tptr+=4;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n /* those three objects do share the same semantics */\n case RSVP_OBJ_SENDER_TSPEC:\n case RSVP_OBJ_ADSPEC:\n case RSVP_OBJ_FLOWSPEC:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_2:\n if (obj_tlen < 4)\n return-1;\n ND_PRINT((ndo, \"%s Msg-Version: %u, length: %u\",\n ident,\n (*obj_tptr & 0xf0) >> 4,\n EXTRACT_16BITS(obj_tptr + 2) << 2));\n obj_tptr+=4; /* get to the start of the service header */\n obj_tlen-=4;\n\n while (obj_tlen >= 4) {\n intserv_serv_tlen=EXTRACT_16BITS(obj_tptr+2)<<2;\n ND_PRINT((ndo, \"%s Service Type: %s (%u), break bit %s set, Service length: %u\",\n ident,\n tok2str(rsvp_intserv_service_type_values,\"unknown\",*(obj_tptr)),\n *(obj_tptr),\n (*(obj_tptr+1)&0x80) ? \"\" : \"not\",\n intserv_serv_tlen));\n\n obj_tptr+=4; /* get to the start of the parameter list */\n obj_tlen-=4;\n\n while (intserv_serv_tlen>=4) {\n processed = rsvp_intserv_print(ndo, obj_tptr, obj_tlen);\n if (processed == 0)\n break;\n obj_tlen-=processed;\n intserv_serv_tlen-=processed;\n obj_tptr+=processed;\n }\n }\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_FILTERSPEC:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_IPV4:\n if (obj_tlen < 8)\n return-1;\n ND_PRINT((ndo, \"%s Source Address: %s, Source Port: %u\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr + 6)));\n obj_tlen-=8;\n obj_tptr+=8;\n break;\n case RSVP_CTYPE_IPV6:\n if (obj_tlen < 20)\n return-1;\n ND_PRINT((ndo, \"%s Source Address: %s, Source Port: %u\",\n ident,\n ip6addr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr + 18)));\n obj_tlen-=20;\n obj_tptr+=20;\n break;\n case RSVP_CTYPE_3:\n if (obj_tlen < 20)\n return-1;\n ND_PRINT((ndo, \"%s Source Address: %s, Flow Label: %u\",\n ident,\n ip6addr_string(ndo, obj_tptr),\n EXTRACT_24BITS(obj_tptr + 17)));\n obj_tlen-=20;\n obj_tptr+=20;\n break;\n case RSVP_CTYPE_TUNNEL_IPV6:\n if (obj_tlen < 20)\n return-1;\n ND_PRINT((ndo, \"%s Source Address: %s, LSP-ID: 0x%04x\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr + 18)));\n obj_tlen-=20;\n obj_tptr+=20;\n break;\n case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */\n if (obj_tlen < 40)\n return-1;\n ND_PRINT((ndo, \"%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x\"\n \"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x\",\n ident,\n ip6addr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr+18),\n ident,\n ip6addr_string(ndo, obj_tptr+20),\n EXTRACT_16BITS(obj_tptr + 38)));\n obj_tlen-=40;\n obj_tptr+=40;\n break;\n case RSVP_CTYPE_TUNNEL_IPV4:\n if (obj_tlen < 8)\n return-1;\n ND_PRINT((ndo, \"%s Source Address: %s, LSP-ID: 0x%04x\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr + 6)));\n obj_tlen-=8;\n obj_tptr+=8;\n break;\n case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */\n if (obj_tlen < 16)\n return-1;\n ND_PRINT((ndo, \"%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x\"\n \"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n EXTRACT_16BITS(obj_tptr+6),\n ident,\n ipaddr_string(ndo, obj_tptr+8),\n EXTRACT_16BITS(obj_tptr + 12)));\n obj_tlen-=16;\n obj_tptr+=16;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_FASTREROUTE:\n /* the differences between c-type 1 and 7 are minor */\n obj_ptr.rsvp_obj_frr = (const struct rsvp_obj_frr_t *)obj_tptr;\n bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);\n\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1: /* new style */\n if (obj_tlen < sizeof(struct rsvp_obj_frr_t))\n return-1;\n ND_PRINT((ndo, \"%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps\",\n ident,\n (int)obj_ptr.rsvp_obj_frr->setup_prio,\n (int)obj_ptr.rsvp_obj_frr->hold_prio,\n (int)obj_ptr.rsvp_obj_frr->hop_limit,\n bw.f * 8 / 1000000));\n ND_PRINT((ndo, \"%s Include-any: 0x%08x, Exclude-any: 0x%08x, Include-all: 0x%08x\",\n ident,\n EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any),\n EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any),\n EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_all)));\n obj_tlen-=sizeof(struct rsvp_obj_frr_t);\n obj_tptr+=sizeof(struct rsvp_obj_frr_t);\n break;\n\n case RSVP_CTYPE_TUNNEL_IPV4: /* old style */\n if (obj_tlen < 16)\n return-1;\n ND_PRINT((ndo, \"%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps\",\n ident,\n (int)obj_ptr.rsvp_obj_frr->setup_prio,\n (int)obj_ptr.rsvp_obj_frr->hold_prio,\n (int)obj_ptr.rsvp_obj_frr->hop_limit,\n bw.f * 8 / 1000000));\n ND_PRINT((ndo, \"%s Include Colors: 0x%08x, Exclude Colors: 0x%08x\",\n ident,\n EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any),\n EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any)));\n obj_tlen-=16;\n obj_tptr+=16;\n break;\n\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_DETOUR:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_TUNNEL_IPV4:\n while(obj_tlen >= 8) {\n ND_PRINT((ndo, \"%s PLR-ID: %s, Avoid-Node-ID: %s\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n ipaddr_string(ndo, obj_tptr + 4)));\n obj_tlen-=8;\n obj_tptr+=8;\n }\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_CLASSTYPE:\n case RSVP_OBJ_CLASSTYPE_OLD: /* fall through */\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1:\n ND_PRINT((ndo, \"%s CT: %u\",\n ident,\n EXTRACT_32BITS(obj_tptr) & 0x7));\n obj_tlen-=4;\n obj_tptr+=4;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_ERROR_SPEC:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */\n case RSVP_CTYPE_IPV4:\n if (obj_tlen < 8)\n return-1;\n error_code=*(obj_tptr+5);\n error_value=EXTRACT_16BITS(obj_tptr+6);\n ND_PRINT((ndo, \"%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)\",\n ident,\n ipaddr_string(ndo, obj_tptr),\n *(obj_tptr+4),\n ident,\n tok2str(rsvp_obj_error_code_values,\"unknown\",error_code),\n error_code));\n switch (error_code) {\n case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING:\n ND_PRINT((ndo, \", Error Value: %s (%u)\",\n tok2str(rsvp_obj_error_code_routing_values,\"unknown\",error_value),\n error_value));\n break;\n case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE: /* fall through */\n case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD:\n ND_PRINT((ndo, \", Error Value: %s (%u)\",\n tok2str(rsvp_obj_error_code_diffserv_te_values,\"unknown\",error_value),\n error_value));\n break;\n default:\n ND_PRINT((ndo, \", Unknown Error Value (%u)\", error_value));\n break;\n }\n obj_tlen-=8;\n obj_tptr+=8;\n break;\n case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */\n case RSVP_CTYPE_IPV6:\n if (obj_tlen < 20)\n return-1;\n error_code=*(obj_tptr+17);\n error_value=EXTRACT_16BITS(obj_tptr+18);\n ND_PRINT((ndo, \"%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)\",\n ident,\n ip6addr_string(ndo, obj_tptr),\n *(obj_tptr+16),\n ident,\n tok2str(rsvp_obj_error_code_values,\"unknown\",error_code),\n error_code));\n\n switch (error_code) {\n case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING:\n ND_PRINT((ndo, \", Error Value: %s (%u)\",\n tok2str(rsvp_obj_error_code_routing_values,\"unknown\",error_value),\n\t\t\t error_value));\n break;\n default:\n break;\n }\n obj_tlen-=20;\n obj_tptr+=20;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_PROPERTIES:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1:\n if (obj_tlen < 4)\n return-1;\n padbytes = EXTRACT_16BITS(obj_tptr+2);\n ND_PRINT((ndo, \"%s TLV count: %u, padding bytes: %u\",\n ident,\n EXTRACT_16BITS(obj_tptr),\n padbytes));\n obj_tlen-=4;\n obj_tptr+=4;\n /* loop through as long there is anything longer than the TLV header (2) */\n while(obj_tlen >= 2 + padbytes) {\n ND_PRINT((ndo, \"%s %s TLV (0x%02x), length: %u\", /* length includes header */\n ident,\n tok2str(rsvp_obj_prop_tlv_values,\"unknown\",*obj_tptr),\n *obj_tptr,\n *(obj_tptr + 1)));\n if (obj_tlen < *(obj_tptr+1))\n return-1;\n if (*(obj_tptr+1) < 2)\n return -1;\n print_unknown_data(ndo, obj_tptr + 2, \"\\n\\t\\t\", *(obj_tptr + 1) - 2);\n obj_tlen-=*(obj_tptr+1);\n obj_tptr+=*(obj_tptr+1);\n }\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_MESSAGE_ID: /* fall through */\n case RSVP_OBJ_MESSAGE_ID_ACK: /* fall through */\n case RSVP_OBJ_MESSAGE_ID_LIST:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1:\n case RSVP_CTYPE_2:\n if (obj_tlen < 8)\n return-1;\n ND_PRINT((ndo, \"%s Flags [0x%02x], epoch: %u\",\n ident,\n *obj_tptr,\n EXTRACT_24BITS(obj_tptr + 1)));\n obj_tlen-=4;\n obj_tptr+=4;\n /* loop through as long there are no messages left */\n while(obj_tlen >= 4) {\n ND_PRINT((ndo, \"%s Message-ID 0x%08x (%u)\",\n ident,\n EXTRACT_32BITS(obj_tptr),\n EXTRACT_32BITS(obj_tptr)));\n obj_tlen-=4;\n obj_tptr+=4;\n }\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_INTEGRITY:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1:\n if (obj_tlen < sizeof(struct rsvp_obj_integrity_t))\n return-1;\n obj_ptr.rsvp_obj_integrity = (const struct rsvp_obj_integrity_t *)obj_tptr;\n ND_PRINT((ndo, \"%s Key-ID 0x%04x%08x, Sequence 0x%08x%08x, Flags [%s]\",\n ident,\n EXTRACT_16BITS(obj_ptr.rsvp_obj_integrity->key_id),\n EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->key_id+2),\n EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence),\n EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence+4),\n bittok2str(rsvp_obj_integrity_flag_values,\n \"none\",\n obj_ptr.rsvp_obj_integrity->flags)));\n ND_PRINT((ndo, \"%s MD5-sum 0x%08x%08x%08x%08x \",\n ident,\n EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest),\n EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+4),\n EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+8),\n EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest + 12)));\n\n sigcheck = signature_verify(ndo, pptr, plen,\n obj_ptr.rsvp_obj_integrity->digest,\n rsvp_clear_checksum,\n rsvp_com_header);\n ND_PRINT((ndo, \" (%s)\", tok2str(signature_check_values, \"Unknown\", sigcheck)));\n\n obj_tlen+=sizeof(struct rsvp_obj_integrity_t);\n obj_tptr+=sizeof(struct rsvp_obj_integrity_t);\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_ADMIN_STATUS:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1:\n if (obj_tlen < 4)\n return-1;\n ND_PRINT((ndo, \"%s Flags [%s]\", ident,\n bittok2str(rsvp_obj_admin_status_flag_values, \"none\",\n EXTRACT_32BITS(obj_tptr))));\n obj_tlen-=4;\n obj_tptr+=4;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_LABEL_SET:\n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1:\n if (obj_tlen < 4)\n return-1;\n action = (EXTRACT_16BITS(obj_tptr)>>8);\n\n ND_PRINT((ndo, \"%s Action: %s (%u), Label type: %u\", ident,\n tok2str(rsvp_obj_label_set_action_values, \"Unknown\", action),\n action, ((EXTRACT_32BITS(obj_tptr) & 0x7F))));\n\n switch (action) {\n case LABEL_SET_INCLUSIVE_RANGE:\n case LABEL_SET_EXCLUSIVE_RANGE: /* fall through */\n\n\t\t /* only a couple of subchannels are expected */\n\t\t if (obj_tlen < 12)\n\t\t\treturn -1;\n\t\t ND_PRINT((ndo, \"%s Start range: %u, End range: %u\", ident,\n EXTRACT_32BITS(obj_tptr+4),\n EXTRACT_32BITS(obj_tptr + 8)));\n\t\t obj_tlen-=12;\n\t\t obj_tptr+=12;\n break;\n\n default:\n obj_tlen-=4;\n obj_tptr+=4;\n subchannel = 1;\n while(obj_tlen >= 4 ) {\n ND_PRINT((ndo, \"%s Subchannel #%u: %u\", ident, subchannel,\n EXTRACT_32BITS(obj_tptr)));\n obj_tptr+=4;\n obj_tlen-=4;\n subchannel++;\n }\n break;\n }\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case RSVP_OBJ_S2L:\n switch (rsvp_obj_ctype) {\n case RSVP_CTYPE_IPV4:\n if (obj_tlen < 4)\n return-1;\n ND_PRINT((ndo, \"%s Sub-LSP destination address: %s\",\n ident, ipaddr_string(ndo, obj_tptr)));\n\n obj_tlen-=4;\n obj_tptr+=4;\n break;\n case RSVP_CTYPE_IPV6:\n if (obj_tlen < 16)\n return-1;\n ND_PRINT((ndo, \"%s Sub-LSP destination address: %s\",\n ident, ip6addr_string(ndo, obj_tptr)));\n\n obj_tlen-=16;\n obj_tptr+=16;\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n /*\n * FIXME those are the defined objects that lack a decoder\n * you are welcome to contribute code ;-)\n */\n\n case RSVP_OBJ_SCOPE:\n case RSVP_OBJ_POLICY_DATA:\n case RSVP_OBJ_ACCEPT_LABEL_SET:\n case RSVP_OBJ_PROTECTION:\n default:\n if (ndo->ndo_vflag <= 1)\n print_unknown_data(ndo, obj_tptr, \"\\n\\t \", obj_tlen); /* FIXME indentation */\n break;\n }\n /* do we also want to see a hex dump ? */\n if (ndo->ndo_vflag > 1 || hexdump == TRUE)\n print_unknown_data(ndo, tptr + sizeof(struct rsvp_object_header), \"\\n\\t \", /* FIXME indentation */\n rsvp_obj_len - sizeof(struct rsvp_object_header));\n\n tptr+=rsvp_obj_len;\n tlen-=rsvp_obj_len;\n }\n return 0;\ninvalid:\n ND_PRINT((ndo, \"%s\", istr));\n return -1;\ntrunc:\n ND_PRINT((ndo, \"\\n\\t\\t\"));\n ND_PRINT((ndo, \"%s\", tstr));\n return -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13048/RSVP: fix decoding of Fast Reroute objects\n\nIn rsvp_obj_print() the case block for Class-Num 205 (FAST_REROUTE) from\nRFC 4090 Section 4.1 could over-read accessing the buffer contents before\nmaking the bounds check. Rearrange those steps the correct way around.\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: 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 const int32_t node_id_first = node_id_range(0); // inclusive\n const int32_t node_id_last = node_id_range(1); // exclusive\n\n const Tensor* stats_summary_indices_t;\n OP_REQUIRES_OK(context, context->input(\"stats_summary_indices\",\n &stats_summary_indices_t));\n const auto stats_summary_indices = stats_summary_indices_t->matrix();\n const int32_t num_sparse_entries = stats_summary_indices_t->dim_size(0);\n\n const Tensor* stats_summary_values_t;\n OP_REQUIRES_OK(context, context->input(\"stats_summary_values\",\n &stats_summary_values_t));\n const auto stats_summary_values = stats_summary_values_t->vec();\n\n const Tensor* stats_summary_shape_t;\n OP_REQUIRES_OK(\n context, context->input(\"stats_summary_shape\", &stats_summary_shape_t));\n const auto stats_summary_shape = stats_summary_shape_t->vec();\n const int32_t num_buckets = stats_summary_shape(2) - 1;\n const int32_t stats_dims = stats_summary_shape(3);\n\n const Tensor* l1_t;\n OP_REQUIRES_OK(context, context->input(\"l1\", &l1_t));\n const auto l1 = l1_t->scalar()();\n\n const Tensor* l2_t;\n OP_REQUIRES_OK(context, context->input(\"l2\", &l2_t));\n const auto l2 = l2_t->scalar()();\n\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\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_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 FeatureMap f_map;\n\n int32_t previous_node_id = -1;\n for (int idx = 0; idx < num_sparse_entries; ++idx) {\n int32_t node_id = stats_summary_indices(idx, 0);\n if (node_id != previous_node_id) {\n process_node(f_map, &output_node_ids, &output_gains,\n &output_feature_dimensions, &output_thresholds,\n &output_left_node_contribs, &output_right_node_contribs,\n &output_split_types, previous_node_id, min_node_weight, l1,\n l2, num_buckets);\n f_map.clear();\n }\n previous_node_id = node_id;\n DCHECK_LE(node_id_first, node_id);\n DCHECK_LT(node_id, node_id_last);\n const int32_t feature_dim = stats_summary_indices(idx, 1);\n const int32_t bucket_id = stats_summary_indices(idx, 2);\n const int32_t stat_dim = stats_summary_indices(idx, 3);\n std::pair const& f_insert_result = f_map.insert(\n FeatureMapIterator::value_type(feature_dim, BucketMap()));\n auto& b_map = f_insert_result.first->second;\n std::pair const& b_insert_result =\n b_map.insert(BucketMapIterator::value_type(\n bucket_id, std::vector(stats_dims)));\n auto& stats = b_insert_result.first->second;\n stats[stat_dim] = stats_summary_values(idx);\n } // for node_id\n // process the last node id\n process_node(f_map, &output_node_ids, &output_gains,\n &output_feature_dimensions, &output_thresholds,\n &output_left_node_contribs, &output_right_node_contribs,\n &output_split_types, previous_node_id, min_node_weight, l1, l2,\n num_buckets);\n\n const int num_nodes = output_node_ids.size();\n // output_node_ids\n Tensor* output_node_ids_t = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(\"node_ids\", {num_nodes},\n &output_node_ids_t));\n auto output_node_ids_vec = output_node_ids_t->vec();\n\n // output_gains\n Tensor* output_gains_t;\n OP_REQUIRES_OK(context, context->allocate_output(\"gains\", {num_nodes},\n &output_gains_t));\n auto output_gains_vec = output_gains_t->vec();\n\n // output_feature_dimensions\n Tensor* output_feature_dimension_t;\n OP_REQUIRES_OK(context,\n context->allocate_output(\"feature_dimensions\", {num_nodes},\n &output_feature_dimension_t));\n auto output_feature_dimensions_vec =\n output_feature_dimension_t->vec();\n\n // output_thresholds\n Tensor* output_thresholds_t;\n OP_REQUIRES_OK(context, context->allocate_output(\"thresholds\", {num_nodes},\n &output_thresholds_t));\n auto output_thresholds_vec = output_thresholds_t->vec();\n\n // output_left_node_contribs\n Tensor* output_left_node_contribs_t;\n OP_REQUIRES_OK(\n context, context->allocate_output(\"left_node_contribs\", {num_nodes, 1},\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(\n context, context->allocate_output(\"right_node_contribs\", {num_nodes, 1},\n &output_right_node_contribs_t));\n auto output_right_node_contribs_matrix =\n output_right_node_contribs_t->matrix();\n\n // split type\n Tensor* output_split_types_t;\n OP_REQUIRES_OK(\n context, context->allocate_output(\"split_with_default_directions\",\n {num_nodes}, &output_split_types_t));\n auto output_split_types_vec = output_split_types_t->vec();\n\n // Sets output tensors from vectors.\n for (int i = 0; i < num_nodes; ++i) {\n output_node_ids_vec(i) = output_node_ids[i];\n // Adjust the gains to penalize by tree complexity.\n output_gains_vec(i) = output_gains[i] - tree_complexity;\n output_feature_dimensions_vec(i) = output_feature_dimensions[i];\n output_thresholds_vec(i) = output_thresholds[i];\n // TODO(crawles): change this for multi-class.\n output_left_node_contribs_matrix(i, 0) = output_left_node_contribs[i];\n output_right_node_contribs_matrix(i, 0) = output_right_node_contribs[i];\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-125', 'CWE-369'], 'message': 'In tf.raw_ops.BoostedTreesSparseCalculateBestFeatureSplit, limit stat_dim in stats_summary_indices to under stats_dims in stats_summary_shape\n\nPiperOrigin-RevId: 387171191\nChange-Id: I83ca8a75b22aa78c037e8b98779da6cced16bfaa'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ff_init_buffer_info(AVCodecContext *avctx, AVFrame *frame)\n{\n if (avctx->internal->pkt) {\n frame->pkt_pts = avctx->internal->pkt->pts;\n av_frame_set_pkt_pos (frame, avctx->internal->pkt->pos);\n av_frame_set_pkt_duration(frame, avctx->internal->pkt->duration);\n av_frame_set_pkt_size (frame, avctx->internal->pkt->size);\n } else {\n frame->pkt_pts = AV_NOPTS_VALUE;\n av_frame_set_pkt_pos (frame, -1);\n av_frame_set_pkt_duration(frame, 0);\n av_frame_set_pkt_size (frame, -1);\n }\n frame->reordered_opaque = avctx->reordered_opaque;\n\n switch (avctx->codec->type) {\n case AVMEDIA_TYPE_VIDEO:\n if (frame->format < 0)\n frame->format = avctx->pix_fmt;\n if (!frame->sample_aspect_ratio.num)\n frame->sample_aspect_ratio = avctx->sample_aspect_ratio;\n if (av_frame_get_colorspace(frame) == AVCOL_SPC_UNSPECIFIED)\n av_frame_set_colorspace(frame, avctx->colorspace);\n if (av_frame_get_color_range(frame) == AVCOL_RANGE_UNSPECIFIED)\n av_frame_set_color_range(frame, avctx->color_range);\n break;\n case AVMEDIA_TYPE_AUDIO:\n if (!frame->sample_rate)\n frame->sample_rate = avctx->sample_rate;\n if (frame->format < 0)\n frame->format = avctx->sample_fmt;\n if (!frame->channel_layout) {\n if (avctx->channel_layout) {\n if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=\n avctx->channels) {\n av_log(avctx, AV_LOG_ERROR, \"Inconsistent channel \"\n \"configuration.\\n\");\n return AVERROR(EINVAL);\n }\n\n frame->channel_layout = avctx->channel_layout;\n } else {\n if (avctx->channels > FF_SANE_NB_CHANNELS) {\n av_log(avctx, AV_LOG_ERROR, \"Too many channels: %d.\\n\",\n avctx->channels);\n return AVERROR(ENOSYS);\n }\n }\n }\n av_frame_set_channels(frame, avctx->channels);\n break;\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'avcodec/utils: set AVFrame format unconditional\n\nFixes inconsistency and out of array accesses\nFixes: 10cdd7e63e7f66e3e66273939e0863dd-asan_heap-oob_1a4ff32_7078_cov_4056274555_mov_h264_aac__mp4box_frag.mp4\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: int avpriv_ac3_parse_header(AC3HeaderInfo **phdr, const uint8_t *buf,\n size_t size)\n{\n return AVERROR(ENOSYS);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'avcodec/ac3_parser: Check init_get_bits8() for failure\n\nFixes: null pointer dereference\nFixes: ffmpeg_crash_6.avi\n\nFound-by: Thuan Pham, Marcel B\u00f6hme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart\nReviewed-by: Paul B Mahol \nSigned-off-by: Michael Niedermayer '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void kdc_post_fork(struct task_server *task, struct process_details *pd)\n{\n\tstruct kdc_server *kdc;\n\tkrb5_kdc_configuration *kdc_config = NULL;\n\tNTSTATUS status;\n\tkrb5_error_code ret;\n\tint ldb_ret;\n\n\tif (task == NULL) {\n\t\ttask_server_terminate(task, \"kdc: Null task\", true);\n\t\treturn;\n\t}\n\tif (task->private_data == NULL) {\n\t\ttask_server_terminate(task, \"kdc: No kdc_server info\", true);\n\t\treturn;\n\t}\n\tkdc = talloc_get_type_abort(task->private_data, struct kdc_server);\n\n\t/* get a samdb connection */\n\tkdc->samdb = samdb_connect(kdc,\n\t\t\t\t kdc->task->event_ctx,\n\t\t\t\t kdc->task->lp_ctx,\n\t\t\t\t system_session(kdc->task->lp_ctx),\n\t\t\t\t NULL,\n\t\t\t\t 0);\n\tif (!kdc->samdb) {\n\t\tDBG_WARNING(\"kdc_task_init: unable to connect to samdb\\n\");\n\t\ttask_server_terminate(task, \"kdc: krb5_init_context samdb connect failed\", true);\n\t\treturn;\n\t}\n\n\tldb_ret = samdb_rodc(kdc->samdb, &kdc->am_rodc);\n\tif (ldb_ret != LDB_SUCCESS) {\n\t\tDBG_WARNING(\"kdc_task_init: \"\n\t\t\t \"Cannot determine if we are an RODC: %s\\n\",\n\t\t\t ldb_errstring(kdc->samdb));\n\t\ttask_server_terminate(task, \"kdc: krb5_init_context samdb RODC connect failed\", true);\n\t\treturn;\n\t}\n\n\tkdc->proxy_timeout = lpcfg_parm_int(kdc->task->lp_ctx, NULL, \"kdc\", \"proxy timeout\", 5);\n\n\tinitialize_krb5_error_table();\n\n\tret = smb_krb5_init_context(kdc, task->lp_ctx, &kdc->smb_krb5_context);\n\tif (ret) {\n\t\tDBG_WARNING(\"kdc_task_init: krb5_init_context failed (%s)\\n\",\n\t\t\t error_message(ret));\n\t\ttask_server_terminate(task, \"kdc: krb5_init_context failed\", true);\n\t\treturn;\n\t}\n\n\tkrb5_add_et_list(kdc->smb_krb5_context->krb5_context, initialize_hdb_error_table_r);\n\n\tret = krb5_kdc_get_config(kdc->smb_krb5_context->krb5_context,\n\t\t\t\t &kdc_config);\n\tif(ret) {\n\t\ttask_server_terminate(task, \"kdc: failed to get KDC configuration\", true);\n\t\treturn;\n\t}\n\n\tkdc_config->logf = (krb5_log_facility *)kdc->smb_krb5_context->pvt_log_data;\n\tkdc_config->db = talloc(kdc, struct HDB *);\n\tif (!kdc_config->db) {\n\t\ttask_server_terminate(task, \"kdc: out of memory\", true);\n\t\treturn;\n\t}\n\tkdc_config->num_db = 1;\n\n\t/*\n\t * This restores the behavior before\n\t * commit 255e3e18e00f717d99f3bc57c8a8895ff624f3c3\n\t * s4:heimdal: import lorikeet-heimdal-201107150856\n\t * (commit 48936803fae4a2fb362c79365d31f420c917b85b)\n\t *\n\t * as_use_strongest_session_key,preauth_use_strongest_session_key\n\t * and tgs_use_strongest_session_key are input to the\n\t * _kdc_find_etype() function. The old bahavior is in\n\t * the use_strongest_session_key=FALSE code path.\n\t * (The only remaining difference in _kdc_find_etype()\n\t * is the is_preauth parameter.)\n\t *\n\t * The old behavior in the _kdc_get_preferred_key()\n\t * function is use_strongest_server_key=TRUE.\n\t */\n\tkdc_config->tgt_use_strongest_session_key = false;\n\tkdc_config->preauth_use_strongest_session_key = true;\n\tkdc_config->svc_use_strongest_session_key = false;\n\tkdc_config->use_strongest_server_key = true;\n\n\tkdc_config->force_include_pa_etype_salt = true;\n\n\t/*\n\t * For Samba CVE-2020-25719 Require PAC to be present\n\t * This instructs Heimdal to match AD behaviour,\n\t * as seen after Microsoft's CVE-2021-42287 when\n\t * PacRequestorEnforcement is set to 2.\n\t *\n\t * Samba BUG: https://bugzilla.samba.org/show_bug.cgi?id=14686\n\t * REF: https://support.microsoft.com/en-au/topic/kb5008380-authentication-updates-cve-2021-42287-9dafac11-e0d0-4cb8-959a-143bd0201041\n\t */\n\n\tkdc_config->require_pac = true;\n\n\t/*\n\t * By default we enable RFC6113/FAST support,\n\t * but we have an option to disable in order to\n\t * test against a KDC with FAST support.\n\t */\n\tkdc_config->enable_fast = lpcfg_kdc_enable_fast(task->lp_ctx);\n\n\t/*\n\t * Match Windows and RFC6113 and Windows but break older\n\t * Heimdal clients.\n\t */\n\tkdc_config->enable_armored_pa_enc_timestamp = false;\n\n\t/* Register hdb-samba4 hooks for use as a keytab */\n\n\tkdc->base_ctx = talloc_zero(kdc, struct samba_kdc_base_context);\n\tif (!kdc->base_ctx) {\n\t\ttask_server_terminate(task, \"kdc: out of memory\", true);\n\t\treturn;\n\t}\n\n\tkdc->base_ctx->ev_ctx = task->event_ctx;\n\tkdc->base_ctx->lp_ctx = task->lp_ctx;\n\tkdc->base_ctx->msg_ctx = task->msg_ctx;\n\n\tstatus = hdb_samba4_create_kdc(kdc->base_ctx,\n\t\t\t\t kdc->smb_krb5_context->krb5_context,\n\t\t\t\t &kdc_config->db[0]);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\ttask_server_terminate(task, \"kdc: hdb_samba4_create_kdc (setup KDC database) failed\", true);\n\t\treturn;\n\t}\n\n\tret = krb5_plugin_register(kdc->smb_krb5_context->krb5_context,\n\t\t\t\t PLUGIN_TYPE_DATA, \"hdb_samba4_interface\",\n\t\t\t\t &hdb_samba4_interface);\n\tif(ret) {\n\t\ttask_server_terminate(task, \"kdc: failed to register hdb plugin\", true);\n\t\treturn;\n\t}\n\n\tkdc->keytab_name = talloc_asprintf(kdc, \"HDB:samba4:&%p\", kdc->base_ctx);\n\tif (kdc->keytab_name == NULL) {\n\t\ttask_server_terminate(task,\n\t\t\t\t \"kdc: Failed to set keytab name\",\n\t\t\t\t true);\n\t\treturn;\n\t}\n\n\tret = krb5_kt_register(kdc->smb_krb5_context->krb5_context, &hdb_kt_ops);\n\tif(ret) {\n\t\ttask_server_terminate(task, \"kdc: failed to register keytab plugin\", true);\n\t\treturn;\n\t}\n\n\t/* Register KDC hooks */\n\tret = krb5_plugin_register(kdc->smb_krb5_context->krb5_context,\n\t\t\t\t PLUGIN_TYPE_DATA, \"kdc\",\n\t\t\t\t &kdc_plugin_table);\n\tif(ret) {\n\t\ttask_server_terminate(task, \"kdc: failed to register kdc plugin\", true);\n\t\treturn;\n\t}\n\n\tret = krb5_kdc_plugin_init(kdc->smb_krb5_context->krb5_context);\n\n\tif(ret) {\n\t\ttask_server_terminate(task, \"kdc: failed to init kdc plugin\", true);\n\t\treturn;\n\t}\n\n\tret = krb5_kdc_pkinit_config(kdc->smb_krb5_context->krb5_context, kdc_config);\n\n\tif(ret) {\n\t\ttask_server_terminate(task, \"kdc: failed to init kdc pkinit subsystem\", true);\n\t\treturn;\n\t}\n\tkdc->private_data = kdc_config;\n\n\tstatus = IRPC_REGISTER(task->msg_ctx, irpc, KDC_CHECK_GENERIC_KERBEROS,\n\t\t\t kdc_check_generic_kerberos, kdc);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\ttask_server_terminate(task, \"kdc failed to setup monitoring\", true);\n\t\treturn;\n\t}\n\n\tirpc_add_name(task->msg_ctx, \"kdc_server\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-288'], 'message': 'CVE-2022-32744 s4:kdc: Don't allow HDB keytab iteration\n\nA fallback in krb5_rd_req_ctx() means that Samba's kpasswd service will\ntry many inappropriate keys to decrypt the ticket supplied to it. For\nexample, it will accept a ticket encrypted with the Administrator's key,\nwhen it should rather accept only tickets encrypted with the krbtgt's\nkey (and not an RODC krbtgt). To fix this, declare the HDB keytab using\nthe HDBGET ops, which do not support iteration.\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=15074\n\nSigned-off-by: Joseph Sutton \nReviewed-by: Andreas Schneider '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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\tint i;\n\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_unloaded_module_list *unloaded_module_list;\n\n\tstruct avrf_handle_operation *handle_operations;\n\tstruct minidump_memory_descriptor *memories;\n\tstruct minidump_memory_descriptor64 *memories64;\n\tstruct minidump_memory_info *memory_infos;\n\tstruct minidump_module *modules;\n\tstruct minidump_thread *threads;\n\tstruct minidump_thread_ex *ex_threads;\n\tstruct minidump_thread_info *thread_infos;\n\tstruct minidump_unloaded_module *unloaded_modules;\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 (entry->location.rva + entry->location.data_size > obj->b->length) {\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\tthread_list = (struct minidump_thread_list *)(obj->b->buf + entry->location.rva);\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\tsdb_fmt (\"d[%i]? \"\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\tfor (i = 0; i < thread_list->number_of_threads; i++) {\n\t\t\tthreads = (struct minidump_thread *)(&(thread_list->threads));\n\t\t\tr_list_append (obj->streams.threads, &(threads[i]));\n\t\t}\n\t\tbreak;\n\tcase MODULE_LIST_STREAM:\n\t\tmodule_list = (struct minidump_module_list *)(obj->b->buf + 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\tsdb_fmt (\"d[%i]? \"\n\t\t\t\t\"NumberOfModule (mdmp_module)Modules\",\n\t\t\t\tmodule_list->number_of_modules,\n\t\t\t\t0),\n\t\t\t0);\n\n\t\tfor (i = 0; i < module_list->number_of_modules; i++) {\n\t\t\tmodules = (struct minidump_module *)(&(module_list->modules));\n\t\t\tr_list_append(obj->streams.modules, &(modules[i]));\n\t\t}\n\t\tbreak;\n\tcase MEMORY_LIST_STREAM:\n\t\tmemory_list = (struct minidump_memory_list *)(obj->b->buf + entry->location.rva);\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\tsdb_fmt (\"d[%i]? \"\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\t\t0),\n\t\t\t0);\n\n\t\tfor (i = 0; i < memory_list->number_of_memory_ranges; i++) {\n\t\t\tmemories = (struct minidump_memory_descriptor *)(&(memory_list->memory_ranges));\n\t\t\tr_list_append (obj->streams.memories, &(memories[i]));\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 = (struct minidump_exception_stream *)(obj->b->buf + entry->location.rva);\n\n\t\tsdb_set (obj->kv, \"mdmp_exception.format\", \"[4]E[4]Eqqdd[15]q \"\n\t\t\t\"(mdmp_exception_code)ExceptionCode \"\n\t\t\t\"(mdmp_exception_flags)ExceptionFlags \"\n\t\t\t\"ExceptionRecord ExceptionAddress \"\n\t\t\t\"NumberParameters __UnusedAlignment \"\n\t\t\t\"ExceptionInformation\", 0);\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\"ThreadId __Alignment \"\n\t\t\t\"(mdmp_exception)ExceptionRecord \"\n\t\t\t\"(mdmp_location_descriptor)ThreadContext\", 0);\n\n\t\tbreak;\n\tcase SYSTEM_INFO_STREAM:\n\t\tobj->streams.system_info = (struct minidump_system_info *)(obj->b->buf + entry->location.rva);\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\tthread_ex_list = (struct minidump_thread_ex_list *)(obj->b->buf + entry->location.rva);\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\tsdb_fmt (\"d[%i]? NumberOfThreads \"\n\t\t\t\t\"(mdmp_thread_ex)Threads\",\n\t\t\t\tthread_ex_list->number_of_threads, 0),\n\t\t\t0);\n\n\t\tfor (i = 0; i < thread_ex_list->number_of_threads; i++) {\n\t\t\tex_threads = (struct minidump_thread_ex *)(&(thread_ex_list->threads));\n\t\t\tr_list_append (obj->streams.ex_threads, &(ex_threads[i]));\n\t\t}\n\t\tbreak;\n\tcase MEMORY_64_LIST_STREAM:\n\t\tmemory64_list = (struct minidump_memory64_list *)(obj->b->buf + entry->location.rva);\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\tsdb_fmt (\"qq[%i]? 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\tfor (i = 0; i < memory64_list->number_of_memory_ranges; i++) {\n\t\t\tmemories64 = (struct minidump_memory_descriptor64 *)(&(memory64_list->memory_ranges));\n\t\t\tr_list_append (obj->streams.memories64.memories, &(memories64[i]));\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 = obj->b->buf + entry->location.rva;\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 = obj->b->buf + entry->location.rva;\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 = (struct minidump_handle_data_stream *)(obj->b->buf + entry->location.rva);\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 = (struct minidump_function_table_stream *)(obj->b->buf + entry->location.rva);\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\tunloaded_module_list = (struct minidump_unloaded_module_list *)(obj->b->buf + entry->location.rva);\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\tfor (i = 0; i < unloaded_module_list->number_of_entries; i++) {\n\t\t\tunloaded_modules = (struct minidump_unloaded_module *)((ut8 *)&unloaded_module_list + sizeof (struct minidump_unloaded_module_list));\n\t\t\tr_list_append (obj->streams.unloaded_modules, &(unloaded_modules[i]));\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 = (struct minidump_misc_info *)(obj->b->buf + entry->location.rva);\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\tmemory_info_list = (struct minidump_memory_info_list *)(obj->b->buf + entry->location.rva);\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\tsdb_fmt (\"ddq[%i]? 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\tfor (i = 0; i < memory_info_list->number_of_entries; i++) {\n\t\t\tmemory_infos = (struct minidump_memory_info *)((ut8 *)memory_info_list + sizeof (struct minidump_memory_info_list));\n\t\t\tr_list_append (obj->streams.memory_infos, &(memory_infos[i]));\n\t\t}\n\t\tbreak;\n\tcase THREAD_INFO_LIST_STREAM:\n\t\t/* TODO: Not yet fully parsed or utilised */\n\t\tthread_info_list = (struct minidump_thread_info_list *)(obj->b->buf + entry->location.rva);\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\tfor (i = 0; i < thread_info_list->number_of_entries; i++) {\n\t\t\tthread_infos = (struct minidump_thread_info *)((ut8 *)thread_info_list + sizeof (struct minidump_thread_info_list));\n\t\t\tr_list_append (obj->streams.thread_infos, &(thread_infos[i]));\n\t\t}\n\t\tbreak;\n\tcase HANDLE_OPERATION_LIST_STREAM:\n\t\t/* TODO: Not yet fully parsed or utilised */\n\t\thandle_operation_list = (struct minidump_handle_operation_list *)(obj->b->buf + entry->location.rva);\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\tfor (i = 0; i < handle_operation_list->number_of_entries; i++) {\n\t\t\thandle_operations = (struct avrf_handle_operation *)((ut8 *)handle_operation_list + sizeof (struct minidump_handle_operation_list));\n\t\t\tr_list_append (obj->streams.operations, &(handle_operations[i]));\n\t\t}\n\n\t\tbreak;\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 %i\\n\", entry->stream_type);\n\t\treturn false;\n\t}\n\treturn true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix #10464 - oobread crash in mdmp (#10683)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)\n{\n\tint start = 0;\n\tu32 prev_legacy, cur_legacy;\n\tmutex_lock(&kvm->arch.vpit->pit_state.lock);\n\tprev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;\n\tcur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;\n\tif (!prev_legacy && cur_legacy)\n\t\tstart = 1;\n\tmemcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,\n\t sizeof(kvm->arch.vpit->pit_state.channels));\n\tkvm->arch.vpit->pit_state.flags = ps->flags;\n\tkvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);\n\tmutex_unlock(&kvm->arch.vpit->pit_state.lock);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'KVM: x86: Reload pit counters for all channels when restoring state\n\nCurrently if userspace restores the pit counters with a count of 0\non channels 1 or 2 and the guest attempts to read the count on those\nchannels, then KVM will perform a mod of 0 and crash. This will ensure\nthat 0 values are converted to 65536 as per the spec.\n\nThis is CVE-2015-7513.\n\nSigned-off-by: Andy Honig \nSigned-off-by: Paolo Bonzini '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: STATIC U8 *\nS_reghop3(U8 *s, SSize_t off, const U8* lim)\n{\n /* return the position 'off' UTF-8 characters away from 's', forward if\n * 'off' >= 0, backwards if negative. But don't go outside of position\n * 'lim', which better be < s if off < 0 */\n\n PERL_ARGS_ASSERT_REGHOP3;\n\n if (off >= 0) {\n\twhile (off-- && s < lim) {\n\t /* XXX could check well-formedness here */\n\t s += UTF8SKIP(s);\n\t}\n }\n else {\n while (off++ && s > lim) {\n s--;\n if (UTF8_IS_CONTINUED(*s)) {\n while (s > lim && UTF8_IS_CONTINUATION(*s))\n s--;\n\t }\n /* XXX could check well-formedness here */\n\t}\n }\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::UpdateService(CString StartName) {\n\tSC_HANDLE hSCManager;\n\tSC_HANDLE hService;\n\n\tif(m_toolsOnly)\n\t\treturn;\n\n\tSetCurrent(IDS_OPEN_SCM);\n\thSCManager= OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);\n\tif (!hSCManager) {\n\t\tMsgBox(IDS_ERR_OPEN_SCM, GetErrMessage());\n\t\treturn;\n\t}\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_OPEN_SERVICE);\n\thService = OpenService(hSCManager, BIND_SERVICE_NAME,\n\t\t\t SERVICE_CHANGE_CONFIG);\n\tif (!hService)\n\t{\n\t\tMsgBox(IDS_ERR_OPEN_SERVICE, GetErrMessage());\n\t\tif (hSCManager)\n\t\t\tCloseServiceHandle(hSCManager);\n\t\treturn;\n\t} else {\n\t\tif (ChangeServiceConfig(hService, dwServiceType, dwStart,\n\t\t\tSERVICE_ERROR_NORMAL, namedLoc, NULL, NULL, NULL,\n\t\t\tStartName, m_accountPassword, BIND_DISPLAY_NAME)\n\t\t\t!= TRUE) {\n\t\t\tDWORD err = GetLastError();\n\t\t\tMsgBox(IDS_ERR_UPDATE_SERVICE, GetErrMessage());\n\t\t}\n\t}\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, SmallWithNoZero) {\n const int stride = 1;\n TF_ASSERT_OK(NodeDefBuilder(\"quantized_conv_op\", \"QuantizedConv2D\")\n .Input(FakeInput(DT_QUINT8))\n .Input(FakeInput(DT_QUINT8))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Attr(\"out_type\", DataTypeToEnum::v())\n .Attr(\"strides\", {1, stride, stride, 1})\n .Attr(\"padding\", \"SAME\")\n .Finalize(node_def()));\n TF_ASSERT_OK(InitOp());\n const int depth = 1;\n const int image_width = 4;\n const int image_height = 3;\n const int image_batch_count = 1;\n // Here we're testing a slow implementation path, where zero is not\n // representable in the image data and so simple border padding is not\n // possible, so we have a min value greater than 0.\n const float image_min = 1.0f;\n const float image_max = 12.0f;\n Tensor image_float(DT_FLOAT,\n {image_batch_count, image_height, image_width, depth});\n test::FillValues(&image_float,\n {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12});\n Tensor image_quantized =\n FloatTensorToQuantized(image_float, image_min, image_max);\n const int filter_size = 3;\n const int filter_count = 1;\n const float filter_min = 1.0f;\n const float filter_max = 9.0f;\n Tensor filter_float(DT_FLOAT,\n {filter_size, filter_size, depth, filter_count});\n test::FillValues(&filter_float, {1, 4, 7, 2, 5, 8, 3, 6, 9});\n Tensor filter_quantized =\n FloatTensorToQuantized(filter_float, filter_min, filter_max);\n AddInputFromArray(image_quantized.shape(),\n image_quantized.flat());\n AddInputFromArray(filter_quantized.shape(),\n filter_quantized.flat());\n AddInputFromArray(TensorShape({1}), {image_min});\n AddInputFromArray(TensorShape({1}), {image_max});\n AddInputFromArray(TensorShape({1}), {filter_min});\n AddInputFromArray(TensorShape({1}), {filter_max});\n TF_ASSERT_OK(RunOpKernel());\n const int expected_width = image_width;\n const int expected_height = image_height * filter_count;\n Tensor expected_float(\n DT_FLOAT, TensorShape({image_batch_count, expected_height, expected_width,\n filter_count}));\n test::FillValues(&expected_float, {105, 150, 183, 95, 235, 312, 357,\n 178, 187, 234, 261, 121});\n const Tensor& output_quantized = *GetOutput(0);\n const float output_min = GetOutput(1)->flat()(0);\n const float output_max = GetOutput(2)->flat()(0);\n Tensor output_float =\n QuantizedTensorToFloat(output_quantized, output_min, output_max);\n test::ExpectTensorNear(expected_float, output_float, 1.0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-476'], 'message': 'Fix undefined behavior in QuantizedConv2D\n\nAdded more input validation and tests. Prior to this, we could get\n`nullptr` exceptions when attempting to access 0th elements of 0-sized\ninputs, leading to security vulnerability bugs.\n\nAlso needed to modify `quantized_conv_ops_test.cc` for consistency.\nPreviously the CPU kernel did technically support passing tensors\nof rank larger than 0 for min/max values. However, the XLA kernels do not.\n\nPiperOrigin-RevId: 445518507'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void WriteBinaryGltfStream(std::ostream &stream,\n const std::string &content,\n const std::vector &binBuffer) {\n const std::string header = \"glTF\";\n const int version = 2;\n\n const uint32_t content_size = uint32_t(content.size());\n const uint32_t binBuffer_size = uint32_t(binBuffer.size());\n // determine number of padding bytes required to ensure 4 byte alignment\n const uint32_t content_padding_size = content_size % 4 == 0 ? 0 : 4 - content_size % 4;\n const uint32_t bin_padding_size = binBuffer_size % 4 == 0 ? 0 : 4 - binBuffer_size % 4;\n\n // 12 bytes for header, JSON content length, 8 bytes for JSON chunk info.\n // Chunk data must be located at 4-byte boundary, which may require padding\n const uint32_t length =\n 12 + 8 + content_size + content_padding_size +\n (binBuffer_size ? (8 + binBuffer_size + bin_padding_size) : 0);\n\n stream.write(header.c_str(), std::streamsize(header.size()));\n stream.write(reinterpret_cast(&version), sizeof(version));\n stream.write(reinterpret_cast(&length), sizeof(length));\n\n // JSON chunk info, then JSON data\n const uint32_t model_length = uint32_t(content.size()) + content_padding_size;\n const uint32_t model_format = 0x4E4F534A;\n stream.write(reinterpret_cast(&model_length),\n sizeof(model_length));\n stream.write(reinterpret_cast(&model_format),\n sizeof(model_format));\n stream.write(content.c_str(), std::streamsize(content.size()));\n\n // Chunk must be multiplies of 4, so pad with spaces\n if (content_padding_size > 0) {\n const std::string padding = std::string(size_t(content_padding_size), ' ');\n stream.write(padding.c_str(), std::streamsize(padding.size()));\n }\n if (binBuffer.size() > 0) {\n // BIN chunk info, then BIN data\n const uint32_t bin_length = uint32_t(binBuffer.size()) + bin_padding_size;\n const uint32_t bin_format = 0x004e4942;\n stream.write(reinterpret_cast(&bin_length),\n sizeof(bin_length));\n stream.write(reinterpret_cast(&bin_format),\n sizeof(bin_format));\n stream.write(reinterpret_cast(binBuffer.data()),\n std::streamsize(binBuffer.size()));\n // Chunksize must be multiplies of 4, so pad with zeroes\n if (bin_padding_size > 0) {\n const std::vector padding =\n std::vector(size_t(bin_padding_size), 0);\n stream.write(reinterpret_cast(padding.data()),\n std::streamsize(padding.size()));\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Do not expand file path since its not necessary for glTF asset path(URI) and for security reason(`wordexp`).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline int ccid_hc_rx_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_rx_getsockopt != NULL)\n\t\trc = ccid->ccid_ops->ccid_hc_rx_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: static uint32_t estimate_re_size(const RE *re0, std::vector &stack)\n{\n // the estimated size of the last sub-RE visited by DFS\n uint32_t size = 0;\n\n const StackItem i0 = {re0, 0, 0};\n stack.push_back(i0);\n\n while (!stack.empty()) {\n const StackItem i = stack.back();\n stack.pop_back();\n\n const RE *re = i.re;\n if (re->type == RE::NIL) {\n size = 0;\n }\n else if (re->type == RE::SYM || re->type == RE::TAG) {\n size = 1;\n }\n else if (re->type == RE::ALT) {\n if (i.succ == 0) {\n // recurse into the left sub-RE\n StackItem k = {re, 0, 1};\n stack.push_back(k);\n StackItem j = {re->alt.re1, 0, 0};\n stack.push_back(j);\n }\n else if (i.succ == 1) {\n // recurse into the right sub-RE\n StackItem k = {re, size, 2};\n stack.push_back(k);\n StackItem j = {re->alt.re2, 0, 0};\n stack.push_back(j);\n }\n else {\n // both sub-RE visited, recursive return\n size = i.size // left sub-RE (saved on stack)\n + size // right sub-RE (just visited by DFS)\n + 1; // additional state for alternative\n }\n }\n else if (re->type == RE::CAT) {\n if (i.succ == 0) {\n // recurse into the left sub-RE\n StackItem k = {re, 0, 1};\n stack.push_back(k);\n StackItem j = {re->cat.re1, 0, 0};\n stack.push_back(j);\n }\n else if (i.succ == 1) {\n // recurse into the right sub-RE\n StackItem k = {re, size, 2};\n stack.push_back(k);\n StackItem j = {re->cat.re2, 0, 0};\n stack.push_back(j);\n }\n else {\n // both sub-RE visited, recursive return\n size = i.size // left sub-RE (saved on stack)\n + size; // right sub-RE (just visited by DFS)\n }\n }\n else if (re->type == RE::ITER) {\n if (i.succ == 0) {\n // recurse into the sub-RE\n StackItem k = {re, 0, 1};\n stack.push_back(k);\n StackItem j = {re->iter.re, 0, 0};\n stack.push_back(j);\n }\n else {\n // sub-RE visited, recursive return\n const uint32_t min = re->iter.min, max = re->iter.max;\n size = max == AST::MANY\n ? size * min + 1\n : size * max + (max - min);\n }\n }\n }\n\n DASSERT(stack.empty());\n return size;\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: ZEND_API void ZEND_FASTCALL _zend_hash_init(HashTable *ht, uint32_t nSize, dtor_func_t pDestructor, zend_bool persistent ZEND_FILE_LINE_DC)\n{\n\tGC_REFCOUNT(ht) = 1;\n\tGC_TYPE_INFO(ht) = IS_ARRAY;\n\tht->u.flags = (persistent ? HASH_FLAG_PERSISTENT : 0) | HASH_FLAG_APPLY_PROTECTION | HASH_FLAG_STATIC_KEYS;\n\tht->nTableSize = zend_hash_check_size(nSize);\n\tht->nTableMask = HT_MIN_MASK;\n\tHT_SET_DATA_ADDR(ht, &uninitialized_bucket);\n\tht->nNumUsed = 0;\n\tht->nNumOfElements = 0;\n\tht->nInternalPointer = HT_INVALID_IDX;\n\tht->nNextFreeElement = 0;\n\tht->pDestructor = pDestructor;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix #73832 - leave the table in a safe state if the size is too big.'" }, { "text": "[INST] Given the following code containing errors, provide Common 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 ConvertAnyFormat(void * ValuePtr, int Format)\n{\n double Value;\n Value = 0;\n\n switch(Format){\n case FMT_SBYTE: Value = *(signed char *)ValuePtr; break;\n case FMT_BYTE: Value = *(uchar *)ValuePtr; break;\n\n case FMT_USHORT: Value = Get16u(ValuePtr); break;\n case FMT_ULONG: Value = Get32u(ValuePtr); break;\n\n case FMT_URATIONAL:\n case FMT_SRATIONAL: \n {\n int Num,Den;\n Num = Get32s(ValuePtr);\n Den = Get32s(4+(char *)ValuePtr);\n if (Den == 0){\n Value = 0;\n }else{\n if (Format == FMT_SRATIONAL){\n Value = (double)Num/Den;\n }else{\n Value = (double)(unsigned)Num/(double)(unsigned)Den;\n }\n }\n break;\n }\n\n case FMT_SSHORT: Value = (signed short)Get16u(ValuePtr); break;\n case FMT_SLONG: Value = Get32s(ValuePtr); break;\n\n // Not sure if this is correct (never seen float used in Exif format)\n case FMT_SINGLE: Value = (double)*(float *)ValuePtr; break;\n case FMT_DOUBLE: Value = *(double *)ValuePtr; break;\n\n default:\n ErrNonfatal(\"Illegal format code %d in Exif header\",Format,0);\n }\n return Value;\n} ; 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: static unsigned int nft_parse_register(const struct nlattr *attr)\n{\n\tunsigned int reg;\n\n\treg = ntohl(nla_get_be32(attr));\n\tswitch (reg) {\n\tcase NFT_REG_VERDICT...NFT_REG_4:\n\t\treturn reg * NFT_REG_SIZE / NFT_REG32_SIZE;\n\tdefault:\n\t\treturn reg + NFT_REG_SIZE / NFT_REG32_SIZE - NFT_REG32_00;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'netfilter: nf_tables: validate registers coming from userspace.\n\nBail out in case userspace uses unsupported registers.\n\nFixes: 49499c3e6e18 (\"netfilter: nf_tables: switch registers to 32 bit addressing\")\nSigned-off-by: Pablo Neira Ayuso '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: hermesBuiltinApply(void *, Runtime *runtime, NativeArgs args) {\n GCScopeMarkerRAII marker{runtime};\n\n Handle fn = args.dyncastArg(0);\n if (LLVM_UNLIKELY(!fn)) {\n return runtime->raiseTypeErrorForValue(\n args.getArgHandle(0), \" is not a function\");\n }\n\n Handle argArray = args.dyncastArg(1);\n if (LLVM_UNLIKELY(!argArray)) {\n return runtime->raiseTypeError(\"args must be an array\");\n }\n\n uint32_t len = JSArray::getLength(*argArray);\n\n bool isConstructor = args.getArgCount() == 2;\n\n MutableHandle<> thisVal{runtime};\n if (isConstructor) {\n auto thisValRes = Callable::createThisForConstruct(fn, runtime);\n if (LLVM_UNLIKELY(thisValRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n thisVal = *thisValRes;\n } else {\n thisVal = args.getArg(2);\n }\n\n ScopedNativeCallFrame newFrame{\n runtime, len, *fn, isConstructor, thisVal.getHermesValue()};\n for (uint32_t i = 0; i < len; ++i) {\n newFrame->getArgRef(i) = argArray->at(runtime, i);\n }\n return isConstructor ? Callable::construct(fn, runtime, thisVal)\n : Callable::call(fn, runtime);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Added stack overflow check for hermes::vm:: hermesBuiltinApply\n\nSummary: This adds a missing check for stack overflow.\n\nReviewed By: tmikov\n\nDifferential Revision: D20104955\n\nfbshipit-source-id: 1f37e23d2e28ebcd3aa4176d134b8418e7059ebd'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void __init netlink_add_usersock_entry(void)\n{\n\tstruct listeners *listeners;\n\tint groups = 32;\n\n\tlisteners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);\n\tif (!listeners)\n\t\tpanic(\"netlink_add_usersock_entry: Cannot allocate listeners\\n\");\n\n\tnetlink_table_grab();\n\n\tnl_table[NETLINK_USERSOCK].groups = groups;\n\trcu_assign_pointer(nl_table[NETLINK_USERSOCK].listeners, listeners);\n\tnl_table[NETLINK_USERSOCK].module = THIS_MODULE;\n\tnl_table[NETLINK_USERSOCK].registered = 1;\n\n\tnetlink_table_ungrab();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284'], 'message': 'netlink: fix possible spoofing from non-root processes\n\nNon-root user-space processes can send Netlink messages to other\nprocesses that are well-known for being subscribed to Netlink\nasynchronous notifications. This allows ilegitimate non-root\nprocess to send forged messages to Netlink subscribers.\n\nThe userspace process usually verifies the legitimate origin in\ntwo ways:\n\na) Socket credentials. If UID != 0, then the message comes from\n some ilegitimate process and the message needs to be dropped.\n\nb) Netlink portID. In general, portID == 0 means that the origin\n of the messages comes from the kernel. Thus, discarding any\n message not coming from the kernel.\n\nHowever, ctnetlink sets the portID in event messages that has\nbeen triggered by some user-space process, eg. conntrack utility.\nSo other processes subscribed to ctnetlink events, eg. conntrackd,\nknow that the event was triggered by some user-space action.\n\nNeither of the two ways to discard ilegitimate messages coming\nfrom non-root processes can help for ctnetlink.\n\nThis patch adds capability validation in case that dst_pid is set\nin netlink_sendmsg(). This approach is aggressive since existing\napplications using any Netlink bus to deliver messages between\ntwo user-space processes will break. Note that the exception is\nNETLINK_USERSOCK, since it is reserved for netlink-to-netlink\nuserspace communication.\n\nStill, if anyone wants that his Netlink bus allows netlink-to-netlink\nuserspace, then they can set NL_NONROOT_SEND. However, by default,\nI don't think it makes sense to allow to use NETLINK_ROUTE to\ncommunicate two processes that are sending no matter what information\nthat is not related to link/neighbouring/routing. They should be using\nNETLINK_USERSOCK instead for that.\n\nSigned-off-by: Pablo Neira Ayuso \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: boost::optional SaplingNotePlaintext::decrypt(\n const SaplingEncCiphertext &ciphertext,\n const uint256 &epk,\n const uint256 &esk,\n const uint256 &pk_d,\n const uint256 &cmu\n)\n{\n auto pt = AttemptSaplingEncDecryption(ciphertext, epk, esk, pk_d);\n if (!pt) {\n return boost::none;\n }\n\n // Deserialize from the plaintext\n CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n ss << pt.get();\n\n SaplingNotePlaintext ret;\n ss >> ret;\n\n uint256 cmu_expected;\n if (!librustzcash_sapling_compute_cm(\n ret.d.data(),\n pk_d.begin(),\n ret.value(),\n ret.rcm.begin(),\n cmu_expected.begin()\n ))\n {\n return boost::none;\n }\n\n if (cmu_expected != cmu) {\n return boost::none;\n }\n\n 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: decode_rt_routing_info(netdissect_options *ndo,\n const u_char *pptr, char *buf, u_int buflen)\n{\n\tuint8_t route_target[8];\n\tu_int plen;\n\n\tND_TCHECK(pptr[0]);\n\tplen = pptr[0]; /* get prefix length */\n\n\tif (0 == plen) {\n\t\tsnprintf(buf, buflen, \"default route target\");\n\t\treturn 1;\n\t}\n\n\tif (32 > plen)\n\t\treturn -1;\n\n plen-=32; /* adjust prefix length */\n\n\tif (64 < plen)\n\t\treturn -1;\n\n\tmemset(&route_target, 0, sizeof(route_target));\n\tND_TCHECK2(pptr[1], (plen + 7) / 8);\n\tmemcpy(&route_target, &pptr[1], (plen + 7) / 8);\n\tif (plen % 8) {\n\t\t((u_char *)&route_target)[(plen + 7) / 8 - 1] &=\n\t\t\t((0xff00 >> (plen % 8)) & 0xff);\n\t}\n\tsnprintf(buf, buflen, \"origin AS: %s, route target %s\",\n\t as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+1)),\n\t bgp_vpn_rd_print(ndo, (u_char *)&route_target));\n\n\treturn 5 + (plen + 7) / 8;\n\ntrunc:\n\treturn -2;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13053/BGP: fix VPN route target bounds checks\n\ndecode_rt_routing_info() didn't check bounds before fetching 4 octets of\nthe origin AS field and could over-read the input buffer, put it right.\n\nIt also fetched the varying number of octets of the route target field\nfrom 4 octets lower than the correct offset, put it right.\n\nIt also used the same temporary buffer explicitly through as_printf()\nand implicitly through bgp_vpn_rd_print() so the end result of snprintf()\nwas not what was originally intended.\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: TPML_TAGGED_TPM_PROPERTY_Unmarshal(TPML_TAGGED_TPM_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_TPM_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_PROPERTY_Unmarshal(&target->tpmProperty[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_ALG_PROPERTY_Unmarshal(TPML_ALG_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_CAP_ALGS) {\n\t rc = TPM_RC_SIZE;\n\t}\n }\n for (i = 0 ; (rc == TPM_RC_SUCCESS) && (i < target->count) ; i++) {\n\trc = TPMS_ALG_PROPERTY_Unmarshal(&target->algProperties[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: GF_Err abst_box_read(GF_Box *s, GF_BitStream *bs)\n{\n\tGF_AdobeBootstrapInfoBox *ptr = (GF_AdobeBootstrapInfoBox *)s;\n\tint i;\n\tu32 tmp_strsize;\n\tchar *tmp_str;\n\tGF_Err e;\n\n\tISOM_DECREASE_SIZE(ptr, 25)\n\tptr->bootstrapinfo_version = gf_bs_read_u32(bs);\n\tptr->profile = gf_bs_read_int(bs, 2);\n\tptr->live = gf_bs_read_int(bs, 1);\n\tptr->update = gf_bs_read_int(bs, 1);\n\tptr->reserved = gf_bs_read_int(bs, 4);\n\tptr->time_scale = gf_bs_read_u32(bs);\n\tptr->current_media_time = gf_bs_read_u64(bs);\n\tptr->smpte_time_code_offset = gf_bs_read_u64(bs);\n\n\ti=0;\n\tif (ptr->size<8) return GF_ISOM_INVALID_FILE;\n\ttmp_strsize =(u32)ptr->size;\n\ttmp_str = gf_malloc(sizeof(char)*tmp_strsize);\n\tif (!tmp_str) return GF_OUT_OF_MEM;\n\tmemset(tmp_str, 0, sizeof(char)*tmp_strsize);\n\n\twhile (tmp_strsize) {\n\t\tISOM_DECREASE_SIZE(ptr, 1)\n\t\ttmp_str[i] = gf_bs_read_u8(bs);\n\t\ttmp_strsize--;\n\t\tif (!tmp_str[i])\n\t\t\tbreak;\n\t\ti++;\n\t}\n\tif (i) {\n\t\tptr->movie_identifier = gf_strdup(tmp_str);\n\t}\n\n\tISOM_DECREASE_SIZE(ptr, 1)\n\tptr->server_entry_count = gf_bs_read_u8(bs);\n\tfor (i=0; iserver_entry_count; i++) {\n\t\tint j=0;\n\t\ttmp_strsize=(u32)ptr->size;\n\t\twhile (tmp_strsize) {\n\t\t\tISOM_DECREASE_SIZE(ptr, 1)\n\t\t\ttmp_str[j] = gf_bs_read_u8(bs);\n\t\t\ttmp_strsize--;\n\t\t\tif (!tmp_str[j])\n\t\t\t\tbreak;\n\t\t\tj++;\n\t\t}\n\t\tif (j) {\n\t\t\tgf_list_insert(ptr->server_entry_table, gf_strdup(tmp_str), i);\n\t\t}\n\t}\n\n\tISOM_DECREASE_SIZE(ptr, 1)\n\tptr->quality_entry_count = gf_bs_read_u8(bs);\n\tfor (i=0; iquality_entry_count; i++) {\n\t\tint j=0;\n\t\ttmp_strsize=(u32)ptr->size;\n\t\twhile (tmp_strsize) {\n\t\t\tISOM_DECREASE_SIZE(ptr, 1)\n\t\t\ttmp_str[j] = gf_bs_read_u8(bs);\n\t\t\ttmp_strsize--;\n\t\t\tif (!tmp_str[j])\n\t\t\t\tbreak;\n\t\t\tj++;\n\t\t}\n\n\t\tif (j) {\n\t\t\tgf_list_insert(ptr->quality_entry_table, gf_strdup(tmp_str), i);\n\t\t}\n\t}\n\n\ti=0;\n\ttmp_strsize=(u32)ptr->size;\n\twhile (tmp_strsize) {\n\t\tISOM_DECREASE_SIZE(ptr, 1)\n\t\ttmp_str[i] = gf_bs_read_u8(bs);\n\t\ttmp_strsize--;\n\t\tif (!tmp_str[i])\n\t\t\tbreak;\n\t\ti++;\n\t}\n\tif (i) {\n\t\tptr->drm_data = gf_strdup(tmp_str);\n\t}\n\n\ti=0;\n\ttmp_strsize=(u32)ptr->size;\n\twhile (tmp_strsize) {\n\t\tISOM_DECREASE_SIZE(ptr, 1)\n\t\ttmp_str[i] = gf_bs_read_u8(bs);\n\t\ttmp_strsize--;\n\t\tif (!tmp_str[i])\n\t\t\tbreak;\n\t\ti++;\n\t}\n\tif (i) {\n\t\tptr->meta_data = gf_strdup(tmp_str);\n\t}\n\n\tISOM_DECREASE_SIZE(ptr, 1)\n\tptr->segment_run_table_count = gf_bs_read_u8(bs);\n\tfor (i=0; isegment_run_table_count; i++) {\n\t\tGF_AdobeSegmentRunTableBox *asrt = NULL;\n\t\te = gf_isom_box_parse((GF_Box **)&asrt, bs);\n\t\tif (e) {\n\t\t\tif (asrt) gf_isom_box_del((GF_Box*)asrt);\n\t\t\tgf_free(tmp_str);\n\t\t\treturn e;\n\t\t}\n\t\tgf_list_add(ptr->segment_run_table_entries, asrt);\n\t}\n\n\tISOM_DECREASE_SIZE(ptr, 1)\n\tptr->fragment_run_table_count = gf_bs_read_u8(bs);\n\tfor (i=0; ifragment_run_table_count; i++) {\n\t\tGF_AdobeFragmentRunTableBox *afrt = NULL;\n\t\te = gf_isom_box_parse((GF_Box **)&afrt, bs);\n\t\tif (e) {\n\t\t\tif (afrt) gf_isom_box_del((GF_Box*)afrt);\n\t\t\tgf_free(tmp_str);\n\t\t\treturn e;\n\t\t}\n\t\tgf_list_add(ptr->fragment_run_table_entries, afrt);\n\t}\n\n\tgf_free(tmp_str);\n\n\treturn GF_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'fixed #1733'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (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_uids_guids(long long *table_start)\n{\n\tint res, i;\n\tint bytes = SQUASHFS_ID_BYTES(sBlk.s.no_ids);\n\tint indexes = SQUASHFS_ID_BLOCKS(sBlk.s.no_ids);\n\tlong long id_index_table[indexes];\n\n\tTRACE(\"read_uids_guids: no_ids %d\\n\", sBlk.s.no_ids);\n\n\tid_table = malloc(bytes);\n\tif(id_table == NULL) {\n\t\tERROR(\"read_uids_guids: failed to allocate id table\\n\");\n\t\treturn FALSE;\n\t}\n\n\tres = read_fs_bytes(fd, sBlk.s.id_table_start,\n\t\tSQUASHFS_ID_BLOCK_BYTES(sBlk.s.no_ids), id_index_table);\n\tif(res == FALSE) {\n\t\tERROR(\"read_uids_guids: failed to read id index table\\n\");\n\t\treturn FALSE;\n\t}\n\tSQUASHFS_INSWAP_ID_BLOCKS(id_index_table, indexes);\n\n\t/*\n\t * id_index_table[0] stores the start of the compressed id blocks.\n\t * This by definition is also the end of the previous filesystem\n\t * table - this may be the exports table if it is present, or the\n\t * fragments table if it isn't.\n\t */\n\t*table_start = id_index_table[0];\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\tres = read_block(fd, id_index_table[i], NULL, expected,\n\t\t\t((char *) id_table) + i * SQUASHFS_METADATA_SIZE);\n\t\tif(res == FALSE) {\n\t\t\tERROR(\"read_uids_guids: failed to read id table block\"\n\t\t\t\t\"\\n\");\n\t\t\treturn FALSE;\n\t\t}\n\t}\n\n\tSQUASHFS_INSWAP_INTS(id_table, sBlk.s.no_ids);\n\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: void ndpi_search_oracle(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow)\n{\n struct ndpi_packet_struct *packet = &flow->packet;\n u_int16_t dport = 0, sport = 0;\n\n NDPI_LOG_DBG(ndpi_struct, \"search ORACLE\\n\");\n\n if(packet->tcp != NULL) {\n sport = ntohs(packet->tcp->source), dport = ntohs(packet->tcp->dest);\n NDPI_LOG_DBG2(ndpi_struct, \"calculating ORACLE over tcp\\n\");\n /* Oracle Database 9g,10g,11g */\n if ((dport == 1521 || sport == 1521)\n\t&& (((packet->payload[0] == 0x07) && (packet->payload[1] == 0xff) && (packet->payload[2] == 0x00))\n\t || ((packet->payload_packet_len >= 232) && ((packet->payload[0] == 0x00) || (packet->payload[0] == 0x01)) \n\t && (packet->payload[1] != 0x00)\n\t && (packet->payload[2] == 0x00)\n\t\t && (packet->payload[3] == 0x00)))) {\n NDPI_LOG_INFO(ndpi_struct, \"found oracle\\n\");\n ndpi_int_oracle_add_connection(ndpi_struct, flow);\n } else if (packet->payload_packet_len == 213 && packet->payload[0] == 0x00 &&\n packet->payload[1] == 0xd5 && packet->payload[2] == 0x00 &&\n packet->payload[3] == 0x00 ) {\n NDPI_LOG_INFO(ndpi_struct, \"found oracle\\n\");\n ndpi_int_oracle_add_connection(ndpi_struct, flow);\n }\n } else {\n NDPI_EXCLUDE_PROTO(ndpi_struct, flow);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Adds bound check in oracle protocol\n\nFound by oss-fuzz\nhttps://bugs.chromium.org/p/oss-fuzz/issues/detail?id=21780'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int sbusfb_ioctl_helper(unsigned long cmd, unsigned long arg,\n\t\t\tstruct fb_info *info,\n\t\t\tint type, int fb_depth, unsigned long fb_size)\n{\n\tswitch(cmd) {\n\tcase FBIOGTYPE: {\n\t\tstruct fbtype __user *f = (struct fbtype __user *) arg;\n\n\t\tif (put_user(type, &f->fb_type) ||\n\t\t __put_user(info->var.yres, &f->fb_height) ||\n\t\t __put_user(info->var.xres, &f->fb_width) ||\n\t\t __put_user(fb_depth, &f->fb_depth) ||\n\t\t __put_user(0, &f->fb_cmsize) ||\n\t\t __put_user(fb_size, &f->fb_cmsize))\n\t\t\treturn -EFAULT;\n\t\treturn 0;\n\t}\n\tcase FBIOPUTCMAP_SPARC: {\n\t\tstruct fbcmap __user *c = (struct fbcmap __user *) arg;\n\t\tstruct fb_cmap cmap;\n\t\tu16 red, green, blue;\n\t\tu8 red8, green8, blue8;\n\t\tunsigned char __user *ured;\n\t\tunsigned char __user *ugreen;\n\t\tunsigned char __user *ublue;\n\t\tint index, count, i;\n\n\t\tif (get_user(index, &c->index) ||\n\t\t __get_user(count, &c->count) ||\n\t\t __get_user(ured, &c->red) ||\n\t\t __get_user(ugreen, &c->green) ||\n\t\t __get_user(ublue, &c->blue))\n\t\t\treturn -EFAULT;\n\n\t\tcmap.len = 1;\n\t\tcmap.red = &red;\n\t\tcmap.green = &green;\n\t\tcmap.blue = &blue;\n\t\tcmap.transp = NULL;\n\t\tfor (i = 0; i < count; i++) {\n\t\t\tint err;\n\n\t\t\tif (get_user(red8, &ured[i]) ||\n\t\t\t get_user(green8, &ugreen[i]) ||\n\t\t\t get_user(blue8, &ublue[i]))\n\t\t\t\treturn -EFAULT;\n\n\t\t\tred = red8 << 8;\n\t\t\tgreen = green8 << 8;\n\t\t\tblue = blue8 << 8;\n\n\t\t\tcmap.start = index + i;\n\t\t\terr = fb_set_cmap(&cmap, info);\n\t\t\tif (err)\n\t\t\t\treturn err;\n\t\t}\n\t\treturn 0;\n\t}\n\tcase FBIOGETCMAP_SPARC: {\n\t\tstruct fbcmap __user *c = (struct fbcmap __user *) arg;\n\t\tunsigned char __user *ured;\n\t\tunsigned char __user *ugreen;\n\t\tunsigned char __user *ublue;\n\t\tstruct fb_cmap *cmap = &info->cmap;\n\t\tint index, count, i;\n\t\tu8 red, green, blue;\n\n\t\tif (get_user(index, &c->index) ||\n\t\t __get_user(count, &c->count) ||\n\t\t __get_user(ured, &c->red) ||\n\t\t __get_user(ugreen, &c->green) ||\n\t\t __get_user(ublue, &c->blue))\n\t\t\treturn -EFAULT;\n\n\t\tif (index + count > cmap->len)\n\t\t\treturn -EINVAL;\n\n\t\tfor (i = 0; i < count; i++) {\n\t\t\tred = cmap->red[index + i] >> 8;\n\t\t\tgreen = cmap->green[index + i] >> 8;\n\t\t\tblue = cmap->blue[index + i] >> 8;\n\t\t\tif (put_user(red, &ured[i]) ||\n\t\t\t put_user(green, &ugreen[i]) ||\n\t\t\t put_user(blue, &ublue[i]))\n\t\t\t\treturn -EFAULT;\n\t\t}\n\t\treturn 0;\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-200'], 'message': 'fbdev: Fixing arbitrary kernel leak in case FBIOGETCMAP_SPARC in sbusfb_ioctl_helper().\n\nFixing arbitrary kernel leak in case FBIOGETCMAP_SPARC in\nsbusfb_ioctl_helper().\n\n'index' is defined as an int in sbusfb_ioctl_helper().\nWe retrieve this from the user:\nif (get_user(index, &c->index) ||\n __get_user(count, &c->count) ||\n __get_user(ured, &c->red) ||\n __get_user(ugreen, &c->green) ||\n __get_user(ublue, &c->blue))\n return -EFAULT;\n\nand then we use 'index' in the following way:\nred = cmap->red[index + i] >> 8;\ngreen = cmap->green[index + i] >> 8;\nblue = cmap->blue[index + i] >> 8;\n\nThis is a classic information leak vulnerability. 'index' should be\nan unsigned int, given its usage above.\n\nThis patch is straight-forward; it changes 'index' to unsigned int\nin two switch-cases: FBIOGETCMAP_SPARC && FBIOPUTCMAP_SPARC.\n\nThis patch fixes CVE-2018-6412.\n\nSigned-off-by: Peter Malone \nAcked-by: Mathieu Malaterre \nSigned-off-by: Bartlomiej Zolnierkiewicz '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: sasl_process_packet(struct sasl_session *const restrict p, char *const restrict buf, const size_t len)\n{\n\tstruct sasl_output_buf outbuf = {\n\t\t.buf = NULL,\n\t\t.len = 0,\n\t\t.flags = ASASL_OUTFLAG_NONE,\n\t};\n\n\tenum sasl_mechanism_result rc;\n\tbool have_responded = false;\n\n\tif (! p->mechptr && ! len)\n\t{\n\t\t// First piece of data in a session is the name of the SASL mechanism that will be used\n\t\tif (! (p->mechptr = sasl_mechanism_find(buf)))\n\t\t{\n\t\t\t(void) sasl_sts(p->uid, 'M', sasl_mechlist_string);\n\t\t\treturn false;\n\t\t}\n\n\t\t(void) sasl_sourceinfo_recreate(p);\n\n\t\tif (p->mechptr->mech_start)\n\t\t\trc = p->mechptr->mech_start(p, &outbuf);\n\t\telse\n\t\t\trc = ASASL_MRESULT_CONTINUE;\n\t}\n\telse if (! p->mechptr)\n\t{\n\t\t(void) slog(LG_DEBUG, \"%s: session has no mechanism?\", MOWGLI_FUNC_NAME);\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\trc = sasl_process_input(p, buf, len, &outbuf);\n\t}\n\n\tif (outbuf.buf && outbuf.len)\n\t{\n\t\tif (! sasl_process_output(p, &outbuf))\n\t\t\treturn false;\n\n\t\thave_responded = true;\n\t}\n\n\t// Some progress has been made, reset timeout.\n\tp->flags &= ~ASASL_SFLAG_MARKED_FOR_DELETION;\n\n\tswitch (rc)\n\t{\n\t\tcase ASASL_MRESULT_CONTINUE:\n\t\t{\n\t\t\tif (! have_responded)\n\t\t\t\t/* We want more data from the client, but we haven't sent any of our own.\n\t\t\t\t * Send an empty string to advance the session. -- amdj\n\t\t\t\t */\n\t\t\t\t(void) sasl_sts(p->uid, 'C', \"+\");\n\n\t\t\treturn true;\n\t\t}\n\n\t\tcase ASASL_MRESULT_SUCCESS:\n\t\t{\n\t\t\tstruct user *const u = user_find(p->uid);\n\t\t\tstruct myuser *const mu = sasl_user_can_login(p);\n\n\t\t\tif (! mu)\n\t\t\t{\n\t\t\t\tif (u)\n\t\t\t\t\t(void) notice(saslsvs->nick, u->nick, LOGIN_CANCELLED_STR);\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t/* If the user is already on the network, attempt to log them in immediately.\n\t\t\t * Otherwise, we will log them in on introduction of user to network\n\t\t\t */\n\t\t\tif (u && ! sasl_handle_login(p, u, mu))\n\t\t\t\treturn false;\n\n\t\t\treturn sasl_session_success(p, mu, (u != NULL));\n\t\t}\n\n\t\tcase ASASL_MRESULT_FAILURE:\n\t\t{\n\t\t\tif (*p->authceid)\n\t\t\t{\n\t\t\t\t/* If we reach this, they failed SASL auth, so if they were trying\n\t\t\t\t * to authenticate as a specific user, run bad_password() on them.\n\t\t\t\t */\n\t\t\t\tstruct myuser *const mu = myuser_find_uid(p->authceid);\n\n\t\t\t\tif (! mu)\n\t\t\t\t\treturn false;\n\n\t\t\t\t/* We might have more information to construct a more accurate sourceinfo now?\n\t\t\t\t * TODO: Investigate whether this is necessary\n\t\t\t\t */\n\t\t\t\t(void) sasl_sourceinfo_recreate(p);\n\n\t\t\t\t(void) logcommand(p->si, CMDLOG_LOGIN, \"failed LOGIN (%s) to \\2%s\\2 (bad password)\",\n\t\t\t\t p->mechptr->name, entity(mu)->name);\n\t\t\t\t(void) bad_password(p->si, mu);\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}\n\n\t\tcase ASASL_MRESULT_ERROR:\n\t\t\treturn false;\n\t}\n\n\t/* This is only here to keep GCC happy -- Clang can see that the switch() handles all legal\n\t * values of the enumeration, and so knows that this function will never get to this point;\n\t * GCC is dumb, and warns that control reaches the end of this non-void function. -- amdj\n\t */\n\treturn false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287', 'CWE-288'], 'message': 'saslserv/main: Track EID we're pending login to\n\nThe existing model does not remember that we've sent a SVSLOGIN for a\ngiven SASL session, and simply assumes that if a client is introduced\nwith a SASL session open, that session must have succeeded. The security\nof this approach requires ircd to implicitly abort SASL sessions on\nclient registration.\n\nThis also means that if a client successfully authenticates and then\ndoes something else its pending login is forgotten about, even though a\nSVSLOGIN has been sent for it, and the ircd is going to think it's\nlogged in.\n\nThis change removes the dependency on ircd's state machine by keeping\nexplicit track of the pending login, i.e. the one we've most recently\nsent a SVSLOGIN for. The next commit will ensure that a client abort\n(even an implicit one) doesn't blow that information away.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Compute(OpKernelContext* context) override {\n // Here's the basic idea:\n // Batch and depth dimension are independent from row and col dimension. And\n // because FractionalAvgPool currently only support pooling along row and\n // col, we can basically think of this 4D tensor backpropagation as\n // operation of a series of 2D planes.\n //\n // For each element of a 'slice' (2D plane) of output_backprop, we need to\n // figure out its contributors when doing FractionalAvgPool operation. This\n // can be done based on row_pooling_sequence, col_pooling_seq and\n // overlapping.\n // Once we figure out the original contributors, we just need to evenly\n // divide the value of this element among these contributors.\n //\n // Internally, we divide the out_backprop tensor and store it in a temporary\n // tensor of double type. And cast it to the corresponding type.\n typedef Eigen::Map>\n ConstEigenMatrixMap;\n typedef Eigen::Map>\n EigenDoubleMatrixMap;\n\n // Grab the inputs.\n const Tensor& orig_input_tensor_shape = context->input(0);\n OP_REQUIRES(context,\n orig_input_tensor_shape.dims() == 1 &&\n orig_input_tensor_shape.NumElements() == 4,\n errors::InvalidArgument(\"original input tensor shape must be\"\n \"1-dimensional and 4 elements\"));\n const Tensor& out_backprop = context->input(1);\n const Tensor& row_seq_tensor = context->input(2);\n const Tensor& col_seq_tensor = context->input(3);\n\n const int64_t out_batch = out_backprop.dim_size(0);\n const int64_t out_rows = out_backprop.dim_size(1);\n const int64_t out_cols = out_backprop.dim_size(2);\n const int64_t out_depth = out_backprop.dim_size(3);\n\n OP_REQUIRES(context, row_seq_tensor.NumElements() > out_rows,\n errors::InvalidArgument(\"Given out_backprop shape \",\n out_backprop.shape().DebugString(),\n \", row_seq_tensor must have at least \",\n out_rows + 1, \" elements, but got \",\n row_seq_tensor.NumElements()));\n OP_REQUIRES(context, col_seq_tensor.NumElements() > out_cols,\n errors::InvalidArgument(\"Given out_backprop shape \",\n out_backprop.shape().DebugString(),\n \", col_seq_tensor must have at least \",\n out_cols + 1, \" elements, but got \",\n col_seq_tensor.NumElements()));\n\n auto row_seq_tensor_flat = row_seq_tensor.flat();\n auto col_seq_tensor_flat = col_seq_tensor.flat();\n auto orig_input_tensor_shape_flat = orig_input_tensor_shape.flat();\n\n const int64_t in_batch = orig_input_tensor_shape_flat(0);\n const int64_t in_rows = orig_input_tensor_shape_flat(1);\n const int64_t in_cols = orig_input_tensor_shape_flat(2);\n const int64_t in_depth = orig_input_tensor_shape_flat(3);\n\n constexpr int tensor_in_and_out_dims = 4;\n // Transform orig_input_tensor_shape into TensorShape\n TensorShape in_shape;\n for (auto i = 0; i < tensor_in_and_out_dims; ++i) {\n in_shape.AddDim(orig_input_tensor_shape_flat(i));\n }\n\n // Create intermediate in_backprop.\n Tensor in_backprop_tensor_temp;\n OP_REQUIRES_OK(context, context->forward_input_or_allocate_temp(\n {0}, DataTypeToEnum::v(), in_shape,\n &in_backprop_tensor_temp));\n in_backprop_tensor_temp.flat().setZero();\n // Transform 4D tensor to 2D matrix.\n EigenDoubleMatrixMap in_backprop_tensor_temp_mat(\n in_backprop_tensor_temp.flat().data(), in_depth,\n in_cols * in_rows * in_batch);\n ConstEigenMatrixMap out_backprop_mat(out_backprop.flat().data(),\n out_depth,\n out_cols * out_rows * out_batch);\n // Loop through each element of out_backprop and evenly distribute the\n // element to the corresponding pooling cell.\n const int64_t in_max_row_index = in_rows - 1;\n const int64_t in_max_col_index = in_cols - 1;\n for (int64_t b = 0; b < out_batch; ++b) {\n for (int64_t r = 0; r < out_rows; ++r) {\n const int64_t in_row_start = row_seq_tensor_flat(r);\n int64_t in_row_end = overlapping_ ? row_seq_tensor_flat(r + 1)\n : row_seq_tensor_flat(r + 1) - 1;\n in_row_end = std::min(in_row_end, in_max_row_index);\n for (int64_t c = 0; c < out_cols; ++c) {\n const int64_t in_col_start = col_seq_tensor_flat(c);\n int64_t in_col_end = overlapping_ ? col_seq_tensor_flat(c + 1)\n : col_seq_tensor_flat(c + 1) - 1;\n in_col_end = std::min(in_col_end, in_max_col_index);\n\n const int64_t num_elements_in_pooling_cell =\n (in_row_end - in_row_start + 1) * (in_col_end - in_col_start + 1);\n const int64_t out_index = (b * out_rows + r) * out_cols + c;\n // Now we can evenly distribute out_backprop(b, h, w, *) to\n // in_backprop(b, hs:he, ws:we, *).\n for (int64_t in_r = in_row_start; in_r <= in_row_end; ++in_r) {\n for (int64_t in_c = in_col_start; in_c <= in_col_end; ++in_c) {\n const int64_t in_index = (b * in_rows + in_r) * in_cols + in_c;\n // Walk through each channel (depth).\n for (int64_t d = 0; d < out_depth; ++d) {\n const double out_backprop_element = static_cast(\n out_backprop_mat.coeffRef(d, out_index));\n double& in_backprop_ref =\n in_backprop_tensor_temp_mat.coeffRef(d, in_index);\n in_backprop_ref +=\n out_backprop_element / num_elements_in_pooling_cell;\n }\n }\n }\n }\n }\n }\n\n // Depending on the type, cast double to type T.\n Tensor* in_backprop_tensor = nullptr;\n OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(\n {0}, 0, in_shape, &in_backprop_tensor));\n auto in_backprop_tensor_flat = in_backprop_tensor->flat();\n auto in_backprop_tensor_temp_flat = in_backprop_tensor_temp.flat();\n for (int64_t i = 0; i < in_backprop_tensor_flat.size(); ++i) {\n in_backprop_tensor_flat(i) =\n static_cast(in_backprop_tensor_temp_flat(i));\n }\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-787'], 'message': 'Validate dimensions of input tensor in `FractionalAvgPoolGrad`\n\nPiperOrigin-RevId: 388286227\nChange-Id: Ieb7566155e92acc8993a2212c76deacadc0edc8a'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int gfs2_bmap_alloc(struct inode *inode, const sector_t lblock,\n\t\t\t struct buffer_head *bh_map, struct metapath *mp,\n\t\t\t const unsigned int sheight,\n\t\t\t const unsigned int height,\n\t\t\t const unsigned int maxlen)\n{\n\tstruct gfs2_inode *ip = GFS2_I(inode);\n\tstruct gfs2_sbd *sdp = GFS2_SB(inode);\n\tstruct buffer_head *dibh = mp->mp_bh[0];\n\tu64 bn, dblock = 0;\n\tunsigned n, i, blks, alloced = 0, iblks = 0, branch_start = 0;\n\tunsigned dblks = 0;\n\tunsigned ptrs_per_blk;\n\tconst unsigned end_of_metadata = height - 1;\n\tint eob = 0;\n\tenum alloc_state state;\n\t__be64 *ptr;\n\t__be64 zero_bn = 0;\n\n\tBUG_ON(sheight < 1);\n\tBUG_ON(dibh == NULL);\n\n\tgfs2_trans_add_bh(ip->i_gl, dibh, 1);\n\n\tif (height == sheight) {\n\t\tstruct buffer_head *bh;\n\t\t/* Bottom indirect block exists, find unalloced extent size */\n\t\tptr = metapointer(end_of_metadata, mp);\n\t\tbh = mp->mp_bh[end_of_metadata];\n\t\tdblks = gfs2_extent_length(bh->b_data, bh->b_size, ptr, maxlen,\n\t\t\t\t\t &eob);\n\t\tBUG_ON(dblks < 1);\n\t\tstate = ALLOC_DATA;\n\t} else {\n\t\t/* Need to allocate indirect blocks */\n\t\tptrs_per_blk = height > 1 ? sdp->sd_inptrs : sdp->sd_diptrs;\n\t\tdblks = min(maxlen, ptrs_per_blk - mp->mp_list[end_of_metadata]);\n\t\tif (height == ip->i_height) {\n\t\t\t/* Writing into existing tree, extend tree down */\n\t\t\tiblks = height - sheight;\n\t\t\tstate = ALLOC_GROW_DEPTH;\n\t\t} else {\n\t\t\t/* Building up tree height */\n\t\t\tstate = ALLOC_GROW_HEIGHT;\n\t\t\tiblks = height - ip->i_height;\n\t\t\tbranch_start = metapath_branch_start(mp);\n\t\t\tiblks += (height - branch_start);\n\t\t}\n\t}\n\n\t/* start of the second part of the function (state machine) */\n\n\tblks = dblks + iblks;\n\ti = sheight;\n\tdo {\n\t\tint error;\n\t\tn = blks - alloced;\n\t\terror = gfs2_alloc_block(ip, &bn, &n);\n\t\tif (error)\n\t\t\treturn error;\n\t\talloced += n;\n\t\tif (state != ALLOC_DATA || gfs2_is_jdata(ip))\n\t\t\tgfs2_trans_add_unrevoke(sdp, bn, n);\n\t\tswitch (state) {\n\t\t/* Growing height of tree */\n\t\tcase ALLOC_GROW_HEIGHT:\n\t\t\tif (i == 1) {\n\t\t\t\tptr = (__be64 *)(dibh->b_data +\n\t\t\t\t\t\t sizeof(struct gfs2_dinode));\n\t\t\t\tzero_bn = *ptr;\n\t\t\t}\n\t\t\tfor (; i - 1 < height - ip->i_height && n > 0; i++, n--)\n\t\t\t\tgfs2_indirect_init(mp, ip->i_gl, i, 0, bn++);\n\t\t\tif (i - 1 == height - ip->i_height) {\n\t\t\t\ti--;\n\t\t\t\tgfs2_buffer_copy_tail(mp->mp_bh[i],\n\t\t\t\t\t\tsizeof(struct gfs2_meta_header),\n\t\t\t\t\t\tdibh, sizeof(struct gfs2_dinode));\n\t\t\t\tgfs2_buffer_clear_tail(dibh,\n\t\t\t\t\t\tsizeof(struct gfs2_dinode) +\n\t\t\t\t\t\tsizeof(__be64));\n\t\t\t\tptr = (__be64 *)(mp->mp_bh[i]->b_data +\n\t\t\t\t\tsizeof(struct gfs2_meta_header));\n\t\t\t\t*ptr = zero_bn;\n\t\t\t\tstate = ALLOC_GROW_DEPTH;\n\t\t\t\tfor(i = branch_start; i < height; i++) {\n\t\t\t\t\tif (mp->mp_bh[i] == NULL)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tbrelse(mp->mp_bh[i]);\n\t\t\t\t\tmp->mp_bh[i] = NULL;\n\t\t\t\t}\n\t\t\t\ti = branch_start;\n\t\t\t}\n\t\t\tif (n == 0)\n\t\t\t\tbreak;\n\t\t/* Branching from existing tree */\n\t\tcase ALLOC_GROW_DEPTH:\n\t\t\tif (i > 1 && i < height)\n\t\t\t\tgfs2_trans_add_bh(ip->i_gl, mp->mp_bh[i-1], 1);\n\t\t\tfor (; i < height && n > 0; i++, n--)\n\t\t\t\tgfs2_indirect_init(mp, ip->i_gl, i,\n\t\t\t\t\t\t mp->mp_list[i-1], bn++);\n\t\t\tif (i == height)\n\t\t\t\tstate = ALLOC_DATA;\n\t\t\tif (n == 0)\n\t\t\t\tbreak;\n\t\t/* Tree complete, adding data blocks */\n\t\tcase ALLOC_DATA:\n\t\t\tBUG_ON(n > dblks);\n\t\t\tBUG_ON(mp->mp_bh[end_of_metadata] == NULL);\n\t\t\tgfs2_trans_add_bh(ip->i_gl, mp->mp_bh[end_of_metadata], 1);\n\t\t\tdblks = n;\n\t\t\tptr = metapointer(end_of_metadata, mp);\n\t\t\tdblock = bn;\n\t\t\twhile (n-- > 0)\n\t\t\t\t*ptr++ = cpu_to_be64(bn++);\n\t\t\tbreak;\n\t\t}\n\t} while ((state != ALLOC_DATA) || !dblock);\n\n\tip->i_height = height;\n\tgfs2_add_inode_blocks(&ip->i_inode, alloced);\n\tgfs2_dinode_out(ip, mp->mp_bh[0]->b_data);\n\tmap_bh(bh_map, inode->i_sb, dblock);\n\tbh_map->b_size = dblks << inode->i_blkbits;\n\tset_buffer_new(bh_map);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'GFS2: rewrite fallocate code to write blocks directly\n\nGFS2's fallocate code currently goes through the page cache. Since it's only\nwriting to the end of the file or to holes in it, it doesn't need to, and it\nwas causing issues on low memory environments. This patch pulls in some of\nSteve's block allocation work, and uses it to simply allocate the blocks for\nthe file, and zero them out at allocation time. It provides a slight\nperformance increase, and it dramatically simplifies the code.\n\nSigned-off-by: Benjamin Marzinski \nSigned-off-by: Steven Whitehouse '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void HierarchicalBitmapRequester::PrepareForDecoding(void)\n{\n#if ACCUSOFT_CODE\n\n UBYTE i;\n\n BuildCommon();\n\n if (m_ppDecodingMCU == NULL) {\n m_ppDecodingMCU = (struct Line **)m_pEnviron->AllocMem(sizeof(struct Line *) * m_ucCount*8);\n memset(m_ppDecodingMCU,0,sizeof(struct Line *) * m_ucCount * 8);\n }\n\n if (m_ppUpsampler == NULL) {\n m_ppUpsampler = (class UpsamplerBase **)m_pEnviron->AllocMem(sizeof(class UpsamplerBase *) * m_ucCount);\n memset(m_ppUpsampler,0,sizeof(class Upsampler *) * m_ucCount);\n\n for(i = 0;i < m_ucCount;i++) {\n class Component *comp = m_pFrame->ComponentOf(i);\n UBYTE sx = comp->SubXOf();\n UBYTE sy = comp->SubYOf();\n\n if (sx > 1 || sy > 1) {\n m_ppUpsampler[i] = UpsamplerBase::CreateUpsampler(m_pEnviron,sx,sy,\n m_ulPixelWidth,m_ulPixelHeight,\n m_pFrame->TablesOf()->isChromaCentered());\n m_bSubsampling = true;\n }\n }\n }\n\n if (m_pLargestScale)\n m_pLargestScale->PrepareForDecoding();\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'The code now checks for consistency of the MCU sizes across\nhierarchical levels, and fails in case they are different.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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 oz_usb_handle_ep_data(struct oz_usb_ctx *usb_ctx,\n\tstruct oz_usb_hdr *usb_hdr, int len)\n{\n\tstruct oz_data *data_hdr = (struct oz_data *)usb_hdr;\n\n\tswitch (data_hdr->format) {\n\tcase OZ_DATA_F_MULTIPLE_FIXED: {\n\t\t\tstruct oz_multiple_fixed *body =\n\t\t\t\t(struct oz_multiple_fixed *)data_hdr;\n\t\t\tu8 *data = body->data;\n\t\t\tint n;\n\t\t\tif (!body->unit_size)\n\t\t\t\tbreak;\n\t\t\tn = (len - sizeof(struct oz_multiple_fixed)+1)\n\t\t\t\t/ body->unit_size;\n\t\t\twhile (n--) {\n\t\t\t\toz_hcd_data_ind(usb_ctx->hport, body->endpoint,\n\t\t\t\t\tdata, body->unit_size);\n\t\t\t\tdata += body->unit_size;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase OZ_DATA_F_ISOC_FIXED: {\n\t\t\tstruct oz_isoc_fixed *body =\n\t\t\t\t(struct oz_isoc_fixed *)data_hdr;\n\t\t\tint data_len = len-sizeof(struct oz_isoc_fixed)+1;\n\t\t\tint unit_size = body->unit_size;\n\t\t\tu8 *data = body->data;\n\t\t\tint count;\n\t\t\tint i;\n\n\t\t\tif (!unit_size)\n\t\t\t\tbreak;\n\t\t\tcount = data_len/unit_size;\n\t\t\tfor (i = 0; i < count; i++) {\n\t\t\t\toz_hcd_data_ind(usb_ctx->hport,\n\t\t\t\t\tbody->endpoint, data, unit_size);\n\t\t\t\tdata += unit_size;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'ozwpan: unchecked signed subtraction leads to DoS\n\nThe subtraction here was using a signed integer and did not have any\nbounds checking at all. This commit adds proper bounds checking, made\neasy by use of an unsigned integer. This way, a single packet won't be\nable to remotely trigger a massive loop, locking up the system for a\nconsiderable amount of time. A PoC follows below, which requires\nozprotocol.h from this module.\n\n=-=-=-=-=-=\n\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n\n #define u8 uint8_t\n #define u16 uint16_t\n #define u32 uint32_t\n #define __packed __attribute__((__packed__))\n #include \"ozprotocol.h\"\n\nstatic int hex2num(char c)\n{\n\tif (c >= '0' && c <= '9')\n\t\treturn c - '0';\n\tif (c >= 'a' && c <= 'f')\n\t\treturn c - 'a' + 10;\n\tif (c >= 'A' && c <= 'F')\n\t\treturn c - 'A' + 10;\n\treturn -1;\n}\nstatic int hwaddr_aton(const char *txt, uint8_t *addr)\n{\n\tint i;\n\tfor (i = 0; i < 6; i++) {\n\t\tint a, b;\n\t\ta = hex2num(*txt++);\n\t\tif (a < 0)\n\t\t\treturn -1;\n\t\tb = hex2num(*txt++);\n\t\tif (b < 0)\n\t\t\treturn -1;\n\t\t*addr++ = (a << 4) | b;\n\t\tif (i < 5 && *txt++ != ':')\n\t\t\treturn -1;\n\t}\n\treturn 0;\n}\n\nint main(int argc, char *argv[])\n{\n\tif (argc < 3) {\n\t\tfprintf(stderr, \"Usage: %s interface destination_mac\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\n\tuint8_t dest_mac[6];\n\tif (hwaddr_aton(argv[2], dest_mac)) {\n\t\tfprintf(stderr, \"Invalid mac address.\\n\");\n\t\treturn 1;\n\t}\n\n\tint sockfd = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW);\n\tif (sockfd < 0) {\n\t\tperror(\"socket\");\n\t\treturn 1;\n\t}\n\n\tstruct ifreq if_idx;\n\tint interface_index;\n\tstrncpy(if_idx.ifr_ifrn.ifrn_name, argv[1], IFNAMSIZ - 1);\n\tif (ioctl(sockfd, SIOCGIFINDEX, &if_idx) < 0) {\n\t\tperror(\"SIOCGIFINDEX\");\n\t\treturn 1;\n\t}\n\tinterface_index = if_idx.ifr_ifindex;\n\tif (ioctl(sockfd, SIOCGIFHWADDR, &if_idx) < 0) {\n\t\tperror(\"SIOCGIFHWADDR\");\n\t\treturn 1;\n\t}\n\tuint8_t *src_mac = (uint8_t *)&if_idx.ifr_hwaddr.sa_data;\n\n\tstruct {\n\t\tstruct ether_header ether_header;\n\t\tstruct oz_hdr oz_hdr;\n\t\tstruct oz_elt oz_elt;\n\t\tstruct oz_elt_connect_req oz_elt_connect_req;\n\t\tstruct oz_elt oz_elt2;\n\t\tstruct oz_multiple_fixed oz_multiple_fixed;\n\t} __packed packet = {\n\t\t.ether_header = {\n\t\t\t.ether_type = htons(OZ_ETHERTYPE),\n\t\t\t.ether_shost = { src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5] },\n\t\t\t.ether_dhost = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] }\n\t\t},\n\t\t.oz_hdr = {\n\t\t\t.control = OZ_F_ACK_REQUESTED | (OZ_PROTOCOL_VERSION << OZ_VERSION_SHIFT),\n\t\t\t.last_pkt_num = 0,\n\t\t\t.pkt_num = htole32(0)\n\t\t},\n\t\t.oz_elt = {\n\t\t\t.type = OZ_ELT_CONNECT_REQ,\n\t\t\t.length = sizeof(struct oz_elt_connect_req)\n\t\t},\n\t\t.oz_elt_connect_req = {\n\t\t\t.mode = 0,\n\t\t\t.resv1 = {0},\n\t\t\t.pd_info = 0,\n\t\t\t.session_id = 0,\n\t\t\t.presleep = 0,\n\t\t\t.ms_isoc_latency = 0,\n\t\t\t.host_vendor = 0,\n\t\t\t.keep_alive = 0,\n\t\t\t.apps = htole16((1 << OZ_APPID_USB) | 0x1),\n\t\t\t.max_len_div16 = 0,\n\t\t\t.ms_per_isoc = 0,\n\t\t\t.up_audio_buf = 0,\n\t\t\t.ms_per_elt = 0\n\t\t},\n\t\t.oz_elt2 = {\n\t\t\t.type = OZ_ELT_APP_DATA,\n\t\t\t.length = sizeof(struct oz_multiple_fixed) - 3\n\t\t},\n\t\t.oz_multiple_fixed = {\n\t\t\t.app_id = OZ_APPID_USB,\n\t\t\t.elt_seq_num = 0,\n\t\t\t.type = OZ_USB_ENDPOINT_DATA,\n\t\t\t.endpoint = 0,\n\t\t\t.format = OZ_DATA_F_MULTIPLE_FIXED,\n\t\t\t.unit_size = 1,\n\t\t\t.data = {0}\n\t\t}\n\t};\n\n\tstruct sockaddr_ll socket_address = {\n\t\t.sll_ifindex = interface_index,\n\t\t.sll_halen = ETH_ALEN,\n\t\t.sll_addr = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] }\n\t};\n\n\tif (sendto(sockfd, &packet, sizeof(packet), 0, (struct sockaddr *)&socket_address, sizeof(socket_address)) < 0) {\n\t\tperror(\"sendto\");\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nSigned-off-by: Jason A. Donenfeld \nAcked-by: Dan Carpenter \nCc: stable \nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void CarbonProtocolReader::skip(const FieldType ft) {\n switch (ft) {\n case FieldType::True:\n case FieldType::False: {\n break;\n }\n case FieldType::Int8: {\n readRaw();\n break;\n }\n case FieldType::Int16: {\n readRaw();\n break;\n }\n case FieldType::Int32: {\n readRaw();\n break;\n }\n case FieldType::Int64: {\n readRaw();\n break;\n }\n case FieldType::Double: {\n readRaw();\n break;\n }\n case FieldType::Float: {\n readRaw();\n break;\n }\n case FieldType::Binary: {\n readRaw();\n break;\n }\n case FieldType::List: {\n skipLinearContainer();\n break;\n }\n case FieldType::Struct: {\n readStructBegin();\n while (true) {\n const auto fieldType = readFieldHeader().first;\n if (fieldType == FieldType::Stop) {\n break;\n }\n skip(fieldType);\n }\n readStructEnd();\n break;\n }\n case FieldType::Set: {\n skipLinearContainer();\n break;\n }\n case FieldType::Map: {\n skipKVContainer();\n break;\n }\n default: { break; }\n }\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: \t__acquires(¤t->sighand->siglock)\n{\n\tbool gstop_done = false;\n\n\tif (arch_ptrace_stop_needed(exit_code, info)) {\n\t\t/*\n\t\t * The arch code has something special to do before a\n\t\t * ptrace stop. This is allowed to block, e.g. for faults\n\t\t * on user stack pages. We can't keep the siglock while\n\t\t * calling arch_ptrace_stop, so we must release it now.\n\t\t * To preserve proper semantics, we must do this before\n\t\t * any signal bookkeeping like checking group_stop_count.\n\t\t * Meanwhile, a SIGKILL could come in before we retake the\n\t\t * siglock. That must prevent us from sleeping in TASK_TRACED.\n\t\t * So after regaining the lock, we must check for SIGKILL.\n\t\t */\n\t\tspin_unlock_irq(¤t->sighand->siglock);\n\t\tarch_ptrace_stop(exit_code, info);\n\t\tspin_lock_irq(¤t->sighand->siglock);\n\t\tif (sigkill_pending(current))\n\t\t\treturn;\n\t}\n\n\t/*\n\t * We're committing to trapping. TRACED should be visible before\n\t * TRAPPING is cleared; otherwise, the tracer might fail do_wait().\n\t * Also, transition to TRACED and updates to ->jobctl should be\n\t * atomic with respect to siglock and should be done after the arch\n\t * hook as siglock is released and regrabbed across it.\n\t */\n\tset_current_state(TASK_TRACED);\n\n\tcurrent->last_siginfo = info;\n\tcurrent->exit_code = exit_code;\n\n\t/*\n\t * If @why is CLD_STOPPED, we're trapping to participate in a group\n\t * stop. Do the bookkeeping. Note that if SIGCONT was delievered\n\t * across siglock relocks since INTERRUPT was scheduled, PENDING\n\t * could be clear now. We act as if SIGCONT is received after\n\t * TASK_TRACED is entered - ignore it.\n\t */\n\tif (why == CLD_STOPPED && (current->jobctl & JOBCTL_STOP_PENDING))\n\t\tgstop_done = task_participate_group_stop(current);\n\n\t/* any trap clears pending STOP trap, STOP trap clears NOTIFY */\n\ttask_clear_jobctl_pending(current, JOBCTL_TRAP_STOP);\n\tif (info && info->si_code >> 8 == PTRACE_EVENT_STOP)\n\t\ttask_clear_jobctl_pending(current, JOBCTL_TRAP_NOTIFY);\n\n\t/* entering a trap, clear TRAPPING */\n\ttask_clear_jobctl_trapping(current);\n\n\tspin_unlock_irq(¤t->sighand->siglock);\n\tread_lock(&tasklist_lock);\n\tif (may_ptrace_stop()) {\n\t\t/*\n\t\t * Notify parents of the stop.\n\t\t *\n\t\t * While ptraced, there are two parents - the ptracer and\n\t\t * the real_parent of the group_leader. The ptracer should\n\t\t * know about every stop while the real parent is only\n\t\t * interested in the completion of group stop. The states\n\t\t * for the two don't interact with each other. Notify\n\t\t * separately unless they're gonna be duplicates.\n\t\t */\n\t\tdo_notify_parent_cldstop(current, true, why);\n\t\tif (gstop_done && ptrace_reparented(current))\n\t\t\tdo_notify_parent_cldstop(current, false, why);\n\n\t\t/*\n\t\t * Don't want to allow preemption here, because\n\t\t * sys_ptrace() needs this task to be inactive.\n\t\t *\n\t\t * XXX: implement read_unlock_no_resched().\n\t\t */\n\t\tpreempt_disable();\n\t\tread_unlock(&tasklist_lock);\n\t\tpreempt_enable_no_resched();\n\t\tfreezable_schedule();\n\t} else {\n\t\t/*\n\t\t * By the time we got the lock, our tracer went away.\n\t\t * Don't drop the lock yet, another tracer may come.\n\t\t *\n\t\t * If @gstop_done, the ptracer went away between group stop\n\t\t * completion and here. During detach, it would have set\n\t\t * JOBCTL_STOP_PENDING on us and we'll re-enter\n\t\t * TASK_STOPPED in do_signal_stop() on return, so notifying\n\t\t * the real parent of the group stop completion is enough.\n\t\t */\n\t\tif (gstop_done)\n\t\t\tdo_notify_parent_cldstop(current, false, why);\n\n\t\t__set_current_state(TASK_RUNNING);\n\t\tif (clear_code)\n\t\t\tcurrent->exit_code = 0;\n\t\tread_unlock(&tasklist_lock);\n\t}\n\n\t/*\n\t * We are back. Now reacquire the siglock before touching\n\t * last_siginfo, so that we are sure to have synchronized with\n\t * any signal-sending on another CPU that wants to examine it.\n\t */\n\tspin_lock_irq(¤t->sighand->siglock);\n\tcurrent->last_siginfo = NULL;\n\n\t/* LISTENING can be set only during STOP traps, clear it */\n\tcurrent->jobctl &= ~JOBCTL_LISTENING;\n\n\t/*\n\t * Queued signals ignored us while we were stopped for tracing.\n\t * So check for any that we should take before resuming user mode.\n\t * This sets TIF_SIGPENDING, but never clears it.\n\t */\n\trecalc_sigpending_tsk(current);\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: null_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p)\n{\n\tu_int length = h->len;\n\tu_int caplen = h->caplen;\n\tu_int family;\n\n\tif (caplen < NULL_HDRLEN) {\n\t\tND_PRINT((ndo, \"[|null]\"));\n\t\treturn (NULL_HDRLEN);\n\t}\n\n\tmemcpy((char *)&family, (const char *)p, sizeof(family));\n\n\t/*\n\t * This isn't necessarily in our host byte order; if this is\n\t * a DLT_LOOP capture, it's in network byte order, and if\n\t * this is a DLT_NULL capture from a machine with the opposite\n\t * byte-order, it's in the opposite byte order from ours.\n\t *\n\t * If the upper 16 bits aren't all zero, assume it's byte-swapped.\n\t */\n\tif ((family & 0xFFFF0000) != 0)\n\t\tfamily = SWAPLONG(family);\n\n\tif (ndo->ndo_eflag)\n\t\tnull_hdr_print(ndo, family, length);\n\n\tlength -= NULL_HDRLEN;\n\tcaplen -= NULL_HDRLEN;\n\tp += NULL_HDRLEN;\n\n\tswitch (family) {\n\n\tcase BSD_AFNUM_INET:\n\t\tip_print(ndo, p, length);\n\t\tbreak;\n\n\tcase BSD_AFNUM_INET6_BSD:\n\tcase BSD_AFNUM_INET6_FREEBSD:\n\tcase BSD_AFNUM_INET6_DARWIN:\n\t\tip6_print(ndo, p, length);\n\t\tbreak;\n\n\tcase BSD_AFNUM_ISO:\n\t\tisoclns_print(ndo, p, length, caplen);\n\t\tbreak;\n\n\tcase BSD_AFNUM_APPLETALK:\n\t\tatalk_print(ndo, p, length);\n\t\tbreak;\n\n\tcase BSD_AFNUM_IPX:\n\t\tipx_print(ndo, p, length);\n\t\tbreak;\n\n\tdefault:\n\t\t/* unknown AF_ value */\n\t\tif (!ndo->ndo_eflag)\n\t\t\tnull_hdr_print(ndo, family, length + NULL_HDRLEN);\n\t\tif (!ndo->ndo_suppress_default_print)\n\t\t\tND_DEFAULTPRINT(p, caplen);\n\t}\n\n\treturn (NULL_HDRLEN);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print().\n\nThis fixes a buffer over-read discovered by Kamil Frankowicz.\n\nDon't pass the remaining caplen - that's too hard to get right, and we\nwere getting it wrong in at least one case; just use ND_TTEST().\n\nAdd a test using the capture file supplied by the reporter(s).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: isoclns_print(netdissect_options *ndo,\n const uint8_t *p, u_int length, u_int caplen)\n{\n\tif (caplen <= 1) { /* enough bytes on the wire ? */\n\t\tND_PRINT((ndo, \"|OSI\"));\n\t\treturn;\n\t}\n\n\tif (ndo->ndo_eflag)\n\t\tND_PRINT((ndo, \"OSI NLPID %s (0x%02x): \", tok2str(nlpid_values, \"Unknown\", *p), *p));\n\n\tswitch (*p) {\n\n\tcase NLPID_CLNP:\n\t\tif (!clnp_print(ndo, p, length))\n\t\t\tprint_unknown_data(ndo, p, \"\\n\\t\", caplen);\n\t\tbreak;\n\n\tcase NLPID_ESIS:\n\t\tesis_print(ndo, p, length);\n\t\treturn;\n\n\tcase NLPID_ISIS:\n\t\tif (!isis_print(ndo, p, length))\n\t\t\tprint_unknown_data(ndo, p, \"\\n\\t\", caplen);\n\t\tbreak;\n\n\tcase NLPID_NULLNS:\n\t\tND_PRINT((ndo, \"%slength: %u\", ndo->ndo_eflag ? \"\" : \", \", length));\n\t\tbreak;\n\n\tcase NLPID_Q933:\n\t\tq933_print(ndo, p + 1, length - 1);\n\t\tbreak;\n\n\tcase NLPID_IP:\n\t\tip_print(ndo, p + 1, length - 1);\n\t\tbreak;\n\n\tcase NLPID_IP6:\n\t\tip6_print(ndo, p + 1, length - 1);\n\t\tbreak;\n\n\tcase NLPID_PPP:\n\t\tppp_print(ndo, p + 1, length - 1);\n\t\tbreak;\n\n\tdefault:\n\t\tif (!ndo->ndo_eflag)\n\t\t\tND_PRINT((ndo, \"OSI NLPID 0x%02x unknown\", *p));\n\t\tND_PRINT((ndo, \"%slength: %u\", ndo->ndo_eflag ? \"\" : \", \", length));\n\t\tif (caplen > 1)\n\t\t\tprint_unknown_data(ndo, p, \"\\n\\t\", caplen);\n\t\tbreak;\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_Expression(ScriptParser *parser)\n{\n\tu32 val = gf_bs_read_int(parser->bs, NUMBITS_EXPR_TYPE);\n\tif (parser->codec->LastError) return;\n\n\tswitch(val) {\n\tcase ET_CURVED_EXPR:\n\t\tSFS_AddString(parser, \"(\");\n\t\tSFS_CompoundExpression(parser);\n\t\tSFS_AddString(parser, \")\");\n\t\tbreak;\n\tcase ET_NEGATIVE:\n\t\tSFS_AddString(parser, \"-\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_NOT:\n\t\tSFS_AddString(parser, \"!\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_ONESCOMP:\n\t\tSFS_AddString(parser, \"~\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_INCREMENT:\n\t\tSFS_AddString(parser, \"++\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_DECREMENT:\n\t\tSFS_AddString(parser, \"--\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_POST_INCREMENT:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"++\");\n\t\tbreak;\n\tcase ET_POST_DECREMENT:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"--\");\n\t\tbreak;\n\tcase ET_CONDTEST:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \" ? \");\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \" : \");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_STRING:\n\t\tSFS_AddString(parser, \"'\");\n\t\tSFS_GetString(parser);\n\t\tSFS_AddString(parser, \"'\");\n\t\tbreak;\n\tcase ET_NUMBER:\n\t\tSFS_GetNumber(parser);\n\t\tbreak;\n\tcase ET_IDENTIFIER:\n\t\tSFS_Identifier(parser);\n\t\tbreak;\n\tcase ET_FUNCTION_CALL:\n\t\tSFS_FunctionCall(parser);\n\t\tbreak;\n\tcase ET_NEW:\n\t\tSFS_NewObject(parser);\n\t\tbreak;\n\tcase ET_OBJECT_MEMBER_ACCESS:\n\t\tSFS_ObjectMemberAccess(parser);\n\t\tbreak;\n\tcase ET_OBJECT_METHOD_CALL:\n\t\tSFS_ObjectMethodCall(parser);\n\t\tbreak;\n\tcase ET_ARRAY_DEREFERENCE:\n\t\tSFS_ArrayDeref(parser);\n\t\tbreak;\n\n\tcase ET_MULTIPLY:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"*\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_DIVIDE:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"/\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_MOD:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"%\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_PLUS:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"+\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_MINUS:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"-\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_LSHIFT:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"<<\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_RSHIFT:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \">>\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_RSHIFTFILL:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \">>>\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_AND:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"&\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_XOR:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"^\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_OR:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"|\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_LT:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"<\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_LE:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"<=\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_GT:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \">\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_GE:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \">=\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_EQ:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"==\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_NE:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"!=\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_LAND:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"&&\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_LOR:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"||\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_ASSIGN:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"=\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_PLUSEQ:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"+=\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_MINUSEQ:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"-=\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_MULTIPLYEQ:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"*=\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_DIVIDEEQ:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"/=\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_MODEQ:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"%=\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_LSHIFTEQ:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"<<=\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_RSHIFTEQ:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \">>=\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_RSHIFTFILLEQ:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \">>>=\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_ANDEQ:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"&=\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_XOREQ:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"^=\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_OREQ:\n\t\tSFS_Expression(parser);\n\t\tSFS_AddString(parser, \"|=\");\n\t\tSFS_Expression(parser);\n\t\tbreak;\n\tcase ET_BOOLEAN:\n\t\tSFS_GetBoolean(parser);\n\t\tbreak;\n\tcase ET_VAR:\n\t\tSFS_AddString(parser, \"var \");\n\t\tSFS_Arguments(parser, GF_TRUE);\n\t\tbreak;\n\tcase ET_FUNCTION_ASSIGN:\n\t\tSFS_AddString(parser, \"function \");\n\t\tSFS_Arguments(parser, GF_FALSE);\n\t\tSFS_StatementBlock(parser, GF_TRUE);\n\t\tbreak;\n\tdefault:\n\t\tparser->codec->LastError = GF_NON_COMPLIANT_BITSTREAM;\n\t\tbreak;\n\t}\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: NO_INLINE JsVar *jspeStatement() {\n#ifdef USE_DEBUGGER\n if (execInfo.execute&EXEC_DEBUGGER_NEXT_LINE &&\n lex->tk!=';' &&\n JSP_SHOULD_EXECUTE) {\n lex->tokenLastStart = jsvStringIteratorGetIndex(&lex->tokenStart.it)-1;\n jsiDebuggerLoop();\n }\n#endif\n if (lex->tk==LEX_ID ||\n lex->tk==LEX_INT ||\n lex->tk==LEX_FLOAT ||\n lex->tk==LEX_STR ||\n lex->tk==LEX_TEMPLATE_LITERAL ||\n lex->tk==LEX_REGEX ||\n lex->tk==LEX_R_NEW ||\n lex->tk==LEX_R_NULL ||\n lex->tk==LEX_R_UNDEFINED ||\n lex->tk==LEX_R_TRUE ||\n lex->tk==LEX_R_FALSE ||\n lex->tk==LEX_R_THIS ||\n lex->tk==LEX_R_DELETE ||\n lex->tk==LEX_R_TYPEOF ||\n lex->tk==LEX_R_VOID ||\n lex->tk==LEX_R_SUPER ||\n lex->tk==LEX_PLUSPLUS ||\n lex->tk==LEX_MINUSMINUS ||\n lex->tk=='!' ||\n lex->tk=='-' ||\n lex->tk=='+' ||\n lex->tk=='~' ||\n lex->tk=='[' ||\n lex->tk=='(') {\n /* Execute a simple statement that only contains basic arithmetic... */\n return jspeExpression();\n } else if (lex->tk=='{') {\n /* A block of code */\n jspeBlock();\n return 0;\n } else if (lex->tk==';') {\n /* Empty statement - to allow things like ;;; */\n JSP_ASSERT_MATCH(';');\n return 0;\n } else if (lex->tk==LEX_R_VAR ||\n lex->tk==LEX_R_LET ||\n lex->tk==LEX_R_CONST) {\n return jspeStatementVar();\n } else if (lex->tk==LEX_R_IF) {\n return jspeStatementIf();\n } else if (lex->tk==LEX_R_DO) {\n return jspeStatementDoOrWhile(false);\n } else if (lex->tk==LEX_R_WHILE) {\n return jspeStatementDoOrWhile(true);\n } else if (lex->tk==LEX_R_FOR) {\n return jspeStatementFor();\n } else if (lex->tk==LEX_R_TRY) {\n return jspeStatementTry();\n } else if (lex->tk==LEX_R_RETURN) {\n return jspeStatementReturn();\n } else if (lex->tk==LEX_R_THROW) {\n return jspeStatementThrow();\n } else if (lex->tk==LEX_R_FUNCTION) {\n return jspeStatementFunctionDecl(false/* function */);\n#ifndef SAVE_ON_FLASH\n } else if (lex->tk==LEX_R_CLASS) {\n return jspeStatementFunctionDecl(true/* class */);\n#endif\n } else if (lex->tk==LEX_R_CONTINUE) {\n JSP_ASSERT_MATCH(LEX_R_CONTINUE);\n if (JSP_SHOULD_EXECUTE) {\n if (!(execInfo.execute & EXEC_IN_LOOP))\n jsExceptionHere(JSET_SYNTAXERROR, \"CONTINUE statement outside of FOR or WHILE loop\");\n else\n execInfo.execute = (execInfo.execute & (JsExecFlags)~EXEC_RUN_MASK) | EXEC_CONTINUE;\n }\n } else if (lex->tk==LEX_R_BREAK) {\n JSP_ASSERT_MATCH(LEX_R_BREAK);\n if (JSP_SHOULD_EXECUTE) {\n if (!(execInfo.execute & (EXEC_IN_LOOP|EXEC_IN_SWITCH)))\n jsExceptionHere(JSET_SYNTAXERROR, \"BREAK statement outside of SWITCH, FOR or WHILE loop\");\n else\n execInfo.execute = (execInfo.execute & (JsExecFlags)~EXEC_RUN_MASK) | EXEC_BREAK;\n }\n } else if (lex->tk==LEX_R_SWITCH) {\n return jspeStatementSwitch();\n } else if (lex->tk==LEX_R_DEBUGGER) {\n JSP_ASSERT_MATCH(LEX_R_DEBUGGER);\n#ifdef USE_DEBUGGER\n if (JSP_SHOULD_EXECUTE)\n jsiDebuggerLoop();\n#endif\n } else JSP_MATCH(LEX_EOF);\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-674'], 'message': 'Fix stack overflow if interpreting a file full of '{' (fix #1448)'" }, { "text": "[INST] Given the following code containing errors, provide Common 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 inode_capable(const struct inode *inode, int cap)\n{\n\tstruct user_namespace *ns = current_user_ns();\n\n\treturn ns_capable(ns, cap) && kuid_has_mapping(ns, inode->i_uid);\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: mark_trusted_task_done (GObject *source_object,\n GAsyncResult *res,\n gpointer user_data)\n{\n MarkTrustedJob *job = user_data;\n\n g_object_unref (job->file);\n\n if (job->done_callback)\n {\n job->done_callback (!job_aborted ((CommonJob *) job),\n job->done_callback_data);\n }\n\n finalize_common ((CommonJob *) job);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'mime-actions: use file metadata for trusting desktop files\n\nCurrently we only trust desktop files that have the executable bit\nset, and don't replace the displayed icon or the displayed name until\nit's trusted, which prevents for running random programs by a malicious\ndesktop file.\n\nHowever, the executable permission is preserved if the desktop file\ncomes from a compressed file.\n\nTo prevent this, add a metadata::trusted metadata to the file once the\nuser acknowledges the file as trusted. This adds metadata to the file,\nwhich cannot be added unless it has access to the computer.\n\nAlso remove the SHEBANG \"trusted\" content we were putting inside the\ndesktop file, since that doesn't add more security since it can come\nwith the file itself.\n\nhttps://bugzilla.gnome.org/show_bug.cgi?id=777991'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int decode_slice_header(H264Context *h, H264Context *h0)\n{\n unsigned int first_mb_in_slice;\n unsigned int pps_id;\n int ret;\n unsigned int slice_type, tmp, i, j;\n int last_pic_structure, last_pic_droppable;\n int must_reinit;\n int needs_reinit = 0;\n int field_pic_flag, bottom_field_flag;\n\n h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;\n h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;\n\n first_mb_in_slice = get_ue_golomb_long(&h->gb);\n\n if (first_mb_in_slice == 0) { // FIXME better field boundary detection\n if (h0->current_slice && h->cur_pic_ptr && FIELD_PICTURE(h)) {\n field_end(h, 1);\n }\n\n h0->current_slice = 0;\n if (!h0->first_field) {\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 h->cur_pic_ptr = NULL;\n }\n }\n\n slice_type = get_ue_golomb_31(&h->gb);\n if (slice_type > 9) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"slice type %d too large at %d %d\\n\",\n slice_type, h->mb_x, h->mb_y);\n return AVERROR_INVALIDDATA;\n }\n if (slice_type > 4) {\n slice_type -= 5;\n h->slice_type_fixed = 1;\n } else\n h->slice_type_fixed = 0;\n\n slice_type = golomb_to_pict_type[slice_type];\n h->slice_type = slice_type;\n h->slice_type_nos = slice_type & 3;\n\n if (h->nal_unit_type == NAL_IDR_SLICE &&\n h->slice_type_nos != AV_PICTURE_TYPE_I) {\n av_log(h->avctx, AV_LOG_ERROR, \"A non-intra slice in an IDR NAL unit.\\n\");\n return AVERROR_INVALIDDATA;\n }\n\n // to make a few old functions happy, it's wrong though\n h->pict_type = h->slice_type;\n\n pps_id = get_ue_golomb(&h->gb);\n if (pps_id >= MAX_PPS_COUNT) {\n av_log(h->avctx, AV_LOG_ERROR, \"pps_id %u out of range\\n\", pps_id);\n return AVERROR_INVALIDDATA;\n }\n if (!h0->pps_buffers[pps_id]) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"non-existing PPS %u referenced\\n\",\n pps_id);\n return AVERROR_INVALIDDATA;\n }\n if (h0->au_pps_id >= 0 && pps_id != h0->au_pps_id) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"PPS change from %d to %d forbidden\\n\",\n h0->au_pps_id, pps_id);\n return AVERROR_INVALIDDATA;\n }\n h->pps = *h0->pps_buffers[pps_id];\n\n if (!h0->sps_buffers[h->pps.sps_id]) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"non-existing SPS %u referenced\\n\",\n h->pps.sps_id);\n return AVERROR_INVALIDDATA;\n }\n\n if (h->pps.sps_id != h->sps.sps_id ||\n h->pps.sps_id != h->current_sps_id ||\n h0->sps_buffers[h->pps.sps_id]->new) {\n\n h->sps = *h0->sps_buffers[h->pps.sps_id];\n\n if (h->mb_width != h->sps.mb_width ||\n h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) ||\n h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||\n h->cur_chroma_format_idc != h->sps.chroma_format_idc\n )\n needs_reinit = 1;\n\n if (h->bit_depth_luma != h->sps.bit_depth_luma ||\n h->chroma_format_idc != h->sps.chroma_format_idc) {\n h->bit_depth_luma = h->sps.bit_depth_luma;\n h->chroma_format_idc = h->sps.chroma_format_idc;\n needs_reinit = 1;\n }\n if ((ret = h264_set_parameter_from_sps(h)) < 0)\n return ret;\n }\n\n h->avctx->profile = ff_h264_get_profile(&h->sps);\n h->avctx->level = h->sps.level_idc;\n h->avctx->refs = h->sps.ref_frame_count;\n\n must_reinit = (h->context_initialized &&\n ( 16*h->sps.mb_width != h->avctx->coded_width\n || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height\n || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma\n || h->cur_chroma_format_idc != h->sps.chroma_format_idc\n || av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio)\n || h->mb_width != h->sps.mb_width\n || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag)\n ));\n if (h0->avctx->pix_fmt != get_pixel_format(h0, 0))\n must_reinit = 1;\n\n h->mb_width = h->sps.mb_width;\n h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);\n h->mb_num = h->mb_width * h->mb_height;\n h->mb_stride = h->mb_width + 1;\n\n h->b_stride = h->mb_width * 4;\n\n h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p\n\n h->width = 16 * h->mb_width;\n h->height = 16 * h->mb_height;\n\n ret = init_dimensions(h);\n if (ret < 0)\n return ret;\n\n if (h->sps.video_signal_type_present_flag) {\n h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG\n : AVCOL_RANGE_MPEG;\n if (h->sps.colour_description_present_flag) {\n if (h->avctx->colorspace != h->sps.colorspace)\n needs_reinit = 1;\n h->avctx->color_primaries = h->sps.color_primaries;\n h->avctx->color_trc = h->sps.color_trc;\n h->avctx->colorspace = h->sps.colorspace;\n }\n }\n\n if (h->context_initialized &&\n (h->width != h->avctx->coded_width ||\n h->height != h->avctx->coded_height ||\n must_reinit ||\n needs_reinit)) {\n if (h != h0) {\n av_log(h->avctx, AV_LOG_ERROR, \"changing width/height on \"\n \"slice %d\\n\", h0->current_slice + 1);\n return AVERROR_INVALIDDATA;\n }\n\n flush_change(h);\n\n if ((ret = get_pixel_format(h, 1)) < 0)\n return ret;\n h->avctx->pix_fmt = ret;\n\n av_log(h->avctx, AV_LOG_INFO, \"Reinit context to %dx%d, \"\n \"pix_fmt: %s\\n\", h->width, h->height, av_get_pix_fmt_name(h->avctx->pix_fmt));\n\n if ((ret = h264_slice_header_init(h, 1)) < 0) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"h264_slice_header_init() failed\\n\");\n return ret;\n }\n }\n if (!h->context_initialized) {\n if (h != h0) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"Cannot (re-)initialize context during parallel decoding.\\n\");\n return AVERROR_PATCHWELCOME;\n }\n\n if ((ret = get_pixel_format(h, 1)) < 0)\n return ret;\n h->avctx->pix_fmt = ret;\n\n if ((ret = h264_slice_header_init(h, 0)) < 0) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"h264_slice_header_init() failed\\n\");\n return ret;\n }\n }\n\n if (h == h0 && h->dequant_coeff_pps != pps_id) {\n h->dequant_coeff_pps = pps_id;\n init_dequant_tables(h);\n }\n\n h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);\n\n h->mb_mbaff = 0;\n h->mb_aff_frame = 0;\n last_pic_structure = h0->picture_structure;\n last_pic_droppable = h0->droppable;\n h->droppable = h->nal_ref_idc == 0;\n if (h->sps.frame_mbs_only_flag) {\n h->picture_structure = PICT_FRAME;\n } else {\n if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {\n av_log(h->avctx, AV_LOG_ERROR, \"This stream was generated by a broken encoder, invalid 8x8 inference\\n\");\n return -1;\n }\n field_pic_flag = get_bits1(&h->gb);\n if (field_pic_flag) {\n bottom_field_flag = get_bits1(&h->gb);\n h->picture_structure = PICT_TOP_FIELD + bottom_field_flag;\n } else {\n h->picture_structure = PICT_FRAME;\n h->mb_aff_frame = h->sps.mb_aff;\n }\n }\n h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;\n\n if (h0->current_slice != 0) {\n if (last_pic_structure != h->picture_structure ||\n last_pic_droppable != h->droppable) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"Changing field mode (%d -> %d) between slices is not allowed\\n\",\n last_pic_structure, h->picture_structure);\n h->picture_structure = last_pic_structure;\n h->droppable = last_pic_droppable;\n return AVERROR_INVALIDDATA;\n } else if (!h0->cur_pic_ptr) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"unset cur_pic_ptr on slice %d\\n\",\n h0->current_slice + 1);\n return AVERROR_INVALIDDATA;\n }\n } else {\n /* Shorten frame num gaps so we don't have to allocate reference\n * frames just to throw them away */\n if (h->frame_num != h->prev_frame_num) {\n int unwrap_prev_frame_num = h->prev_frame_num;\n int max_frame_num = 1 << h->sps.log2_max_frame_num;\n\n if (unwrap_prev_frame_num > h->frame_num)\n unwrap_prev_frame_num -= max_frame_num;\n\n if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {\n unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;\n if (unwrap_prev_frame_num < 0)\n unwrap_prev_frame_num += max_frame_num;\n\n h->prev_frame_num = unwrap_prev_frame_num;\n }\n }\n\n /* See if we have a decoded first field looking for a pair...\n * Here, we're using that to see if we should mark previously\n * decode frames as \"finished\".\n * We have to do that before the \"dummy\" in-between frame allocation,\n * since that can modify h->cur_pic_ptr. */\n if (h0->first_field) {\n assert(h0->cur_pic_ptr);\n assert(h0->cur_pic_ptr->f.buf[0]);\n assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);\n\n /* Mark old field/frame as completed */\n if (h0->cur_pic_ptr->tf.owner == h0->avctx) {\n ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,\n last_pic_structure == PICT_BOTTOM_FIELD);\n }\n\n /* figure out if we have a complementary field pair */\n if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {\n /* Previous field is unmatched. Don't display it, but let it\n * remain for reference if marked as such. */\n if (last_pic_structure != PICT_FRAME) {\n ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,\n last_pic_structure == PICT_TOP_FIELD);\n }\n } else {\n if (h0->cur_pic_ptr->frame_num != h->frame_num) {\n /* This and previous field were reference, but had\n * different frame_nums. Consider this field first in\n * pair. Throw away previous field except for reference\n * purposes. */\n if (last_pic_structure != PICT_FRAME) {\n ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,\n last_pic_structure == PICT_TOP_FIELD);\n }\n } else {\n /* Second field in complementary pair */\n if (!((last_pic_structure == PICT_TOP_FIELD &&\n h->picture_structure == PICT_BOTTOM_FIELD) ||\n (last_pic_structure == PICT_BOTTOM_FIELD &&\n h->picture_structure == PICT_TOP_FIELD))) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"Invalid field mode combination %d/%d\\n\",\n last_pic_structure, h->picture_structure);\n h->picture_structure = last_pic_structure;\n h->droppable = last_pic_droppable;\n return AVERROR_INVALIDDATA;\n } else if (last_pic_droppable != h->droppable) {\n avpriv_request_sample(h->avctx,\n \"Found reference and non-reference fields in the same frame, which\");\n h->picture_structure = last_pic_structure;\n h->droppable = last_pic_droppable;\n return AVERROR_PATCHWELCOME;\n }\n }\n }\n }\n\n while (h->frame_num != h->prev_frame_num && !h0->first_field &&\n h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {\n Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;\n av_log(h->avctx, AV_LOG_DEBUG, \"Frame num gap %d %d\\n\",\n h->frame_num, h->prev_frame_num);\n if (!h->sps.gaps_in_frame_num_allowed_flag)\n for(i=0; ilast_pocs); i++)\n h->last_pocs[i] = INT_MIN;\n ret = h264_frame_start(h);\n if (ret < 0) {\n h0->first_field = 0;\n return ret;\n }\n\n h->prev_frame_num++;\n h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;\n h->cur_pic_ptr->frame_num = h->prev_frame_num;\n ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);\n ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);\n ret = ff_generate_sliding_window_mmcos(h, 1);\n if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))\n return ret;\n ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);\n if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))\n return ret;\n /* Error concealment: If a ref is missing, copy the previous ref\n * in its place.\n * FIXME: Avoiding a memcpy would be nice, but ref handling makes\n * many assumptions about there being no actual duplicates.\n * FIXME: This does not copy padding for out-of-frame motion\n * vectors. Given we are concealing a lost frame, this probably\n * is not noticeable by comparison, but it should be fixed. */\n if (h->short_ref_count) {\n if (prev) {\n av_image_copy(h->short_ref[0]->f.data,\n h->short_ref[0]->f.linesize,\n (const uint8_t **)prev->f.data,\n prev->f.linesize,\n h->avctx->pix_fmt,\n h->mb_width * 16,\n h->mb_height * 16);\n h->short_ref[0]->poc = prev->poc + 2;\n }\n h->short_ref[0]->frame_num = h->prev_frame_num;\n }\n }\n\n /* See if we have a decoded first field looking for a pair...\n * We're using that to see whether to continue decoding in that\n * frame, or to allocate a new one. */\n if (h0->first_field) {\n assert(h0->cur_pic_ptr);\n assert(h0->cur_pic_ptr->f.buf[0]);\n assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);\n\n /* figure out if we have a complementary field pair */\n if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {\n /* Previous field is unmatched. Don't display it, but let it\n * remain for reference if marked as such. */\n h0->cur_pic_ptr = NULL;\n h0->first_field = FIELD_PICTURE(h);\n } else {\n if (h0->cur_pic_ptr->frame_num != h->frame_num) {\n ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,\n h0->picture_structure==PICT_BOTTOM_FIELD);\n /* This and the previous field had different frame_nums.\n * Consider this field first in pair. Throw away previous\n * one except for reference purposes. */\n h0->first_field = 1;\n h0->cur_pic_ptr = NULL;\n } else {\n /* Second field in complementary pair */\n h0->first_field = 0;\n }\n }\n } else {\n /* Frame or first field in a potentially complementary pair */\n h0->first_field = FIELD_PICTURE(h);\n }\n\n if (!FIELD_PICTURE(h) || h0->first_field) {\n if (h264_frame_start(h) < 0) {\n h0->first_field = 0;\n return AVERROR_INVALIDDATA;\n }\n } else {\n release_unused_pictures(h, 0);\n }\n /* Some macroblocks can be accessed before they're available in case\n * of lost slices, MBAFF or threading. */\n if (FIELD_PICTURE(h)) {\n for(i = (h->picture_structure == PICT_BOTTOM_FIELD); imb_height; i++)\n memset(h->slice_table + i*h->mb_stride, -1, (h->mb_stride - (i+1==h->mb_height)) * sizeof(*h->slice_table));\n } else {\n memset(h->slice_table, -1,\n (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));\n }\n h0->last_slice_type = -1;\n }\n if (h != h0 && (ret = clone_slice(h, h0)) < 0)\n return ret;\n\n /* can't be in alloc_tables because linesize isn't known there.\n * FIXME: redo bipred weight to not require extra buffer? */\n for (i = 0; i < h->slice_context_count; i++)\n if (h->thread_context[i]) {\n ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);\n if (ret < 0)\n return ret;\n }\n\n h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup\n\n av_assert1(h->mb_num == h->mb_width * h->mb_height);\n if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||\n first_mb_in_slice >= h->mb_num) {\n av_log(h->avctx, AV_LOG_ERROR, \"first_mb_in_slice overflow\\n\");\n return AVERROR_INVALIDDATA;\n }\n h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width;\n h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) <<\n FIELD_OR_MBAFF_PICTURE(h);\n if (h->picture_structure == PICT_BOTTOM_FIELD)\n h->resync_mb_y = h->mb_y = h->mb_y + 1;\n av_assert1(h->mb_y < h->mb_height);\n\n if (h->picture_structure == PICT_FRAME) {\n h->curr_pic_num = h->frame_num;\n h->max_pic_num = 1 << h->sps.log2_max_frame_num;\n } else {\n h->curr_pic_num = 2 * h->frame_num + 1;\n h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);\n }\n\n if (h->nal_unit_type == NAL_IDR_SLICE)\n get_ue_golomb(&h->gb); /* idr_pic_id */\n\n if (h->sps.poc_type == 0) {\n h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);\n\n if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)\n h->delta_poc_bottom = get_se_golomb(&h->gb);\n }\n\n if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {\n h->delta_poc[0] = get_se_golomb(&h->gb);\n\n if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)\n h->delta_poc[1] = get_se_golomb(&h->gb);\n }\n\n ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc);\n\n if (h->pps.redundant_pic_cnt_present)\n h->redundant_pic_count = get_ue_golomb(&h->gb);\n\n ret = ff_set_ref_count(h);\n if (ret < 0)\n return ret;\n\n if (slice_type != AV_PICTURE_TYPE_I &&\n (h0->current_slice == 0 ||\n slice_type != h0->last_slice_type ||\n memcmp(h0->last_ref_count, h0->ref_count, sizeof(h0->ref_count)))) {\n\n ff_h264_fill_default_ref_list(h);\n }\n\n if (h->slice_type_nos != AV_PICTURE_TYPE_I) {\n ret = ff_h264_decode_ref_pic_list_reordering(h);\n if (ret < 0) {\n h->ref_count[1] = h->ref_count[0] = 0;\n return ret;\n }\n }\n\n if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||\n (h->pps.weighted_bipred_idc == 1 &&\n h->slice_type_nos == AV_PICTURE_TYPE_B))\n ff_pred_weight_table(h);\n else if (h->pps.weighted_bipred_idc == 2 &&\n h->slice_type_nos == AV_PICTURE_TYPE_B) {\n implicit_weight_table(h, -1);\n } else {\n h->use_weight = 0;\n for (i = 0; i < 2; i++) {\n h->luma_weight_flag[i] = 0;\n h->chroma_weight_flag[i] = 0;\n }\n }\n\n // If frame-mt is enabled, only update mmco tables for the first slice\n // in a field. Subsequent slices can temporarily clobber h->mmco_index\n // or h->mmco, which will cause ref list mix-ups and decoding errors\n // further down the line. This may break decoding if the first slice is\n // corrupt, thus we only do this if frame-mt is enabled.\n if (h->nal_ref_idc) {\n ret = ff_h264_decode_ref_pic_marking(h0, &h->gb,\n !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||\n h0->current_slice == 0);\n if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))\n return AVERROR_INVALIDDATA;\n }\n\n if (FRAME_MBAFF(h)) {\n ff_h264_fill_mbaff_ref_list(h);\n\n if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {\n implicit_weight_table(h, 0);\n implicit_weight_table(h, 1);\n }\n }\n\n if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)\n ff_h264_direct_dist_scale_factor(h);\n ff_h264_direct_ref_list_init(h);\n\n if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {\n tmp = get_ue_golomb_31(&h->gb);\n if (tmp > 2) {\n av_log(h->avctx, AV_LOG_ERROR, \"cabac_init_idc %u overflow\\n\", tmp);\n return AVERROR_INVALIDDATA;\n }\n h->cabac_init_idc = tmp;\n }\n\n h->last_qscale_diff = 0;\n tmp = h->pps.init_qp + get_se_golomb(&h->gb);\n if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {\n av_log(h->avctx, AV_LOG_ERROR, \"QP %u out of range\\n\", tmp);\n return AVERROR_INVALIDDATA;\n }\n h->qscale = tmp;\n h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);\n h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);\n // FIXME qscale / qp ... stuff\n if (h->slice_type == AV_PICTURE_TYPE_SP)\n get_bits1(&h->gb); /* sp_for_switch_flag */\n if (h->slice_type == AV_PICTURE_TYPE_SP ||\n h->slice_type == AV_PICTURE_TYPE_SI)\n get_se_golomb(&h->gb); /* slice_qs_delta */\n\n h->deblocking_filter = 1;\n h->slice_alpha_c0_offset = 52;\n h->slice_beta_offset = 52;\n if (h->pps.deblocking_filter_parameters_present) {\n tmp = get_ue_golomb_31(&h->gb);\n if (tmp > 2) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"deblocking_filter_idc %u out of range\\n\", tmp);\n return AVERROR_INVALIDDATA;\n }\n h->deblocking_filter = tmp;\n if (h->deblocking_filter < 2)\n h->deblocking_filter ^= 1; // 1<->0\n\n if (h->deblocking_filter) {\n h->slice_alpha_c0_offset += get_se_golomb(&h->gb) << 1;\n h->slice_beta_offset += get_se_golomb(&h->gb) << 1;\n if (h->slice_alpha_c0_offset > 104U ||\n h->slice_beta_offset > 104U) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"deblocking filter parameters %d %d out of range\\n\",\n h->slice_alpha_c0_offset, h->slice_beta_offset);\n return AVERROR_INVALIDDATA;\n }\n }\n }\n\n if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||\n (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&\n h->slice_type_nos != AV_PICTURE_TYPE_I) ||\n (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&\n h->slice_type_nos == AV_PICTURE_TYPE_B) ||\n (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&\n h->nal_ref_idc == 0))\n h->deblocking_filter = 0;\n\n if (h->deblocking_filter == 1 && h0->max_contexts > 1) {\n if (h->avctx->flags2 & CODEC_FLAG2_FAST) {\n /* Cheat slightly for speed:\n * Do not bother to deblock across slices. */\n h->deblocking_filter = 2;\n } else {\n h0->max_contexts = 1;\n if (!h0->single_decode_warning) {\n av_log(h->avctx, AV_LOG_INFO,\n \"Cannot parallelize deblocking type 1, decoding such frames in sequential order\\n\");\n h0->single_decode_warning = 1;\n }\n if (h != h0) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"Deblocking switched inside frame.\\n\");\n return 1;\n }\n }\n }\n h->qp_thresh = 15 + 52 -\n FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -\n FFMAX3(0,\n h->pps.chroma_qp_index_offset[0],\n h->pps.chroma_qp_index_offset[1]) +\n 6 * (h->sps.bit_depth_luma - 8);\n\n h0->last_slice_type = slice_type;\n memcpy(h0->last_ref_count, h0->ref_count, sizeof(h0->last_ref_count));\n h->slice_num = ++h0->current_slice;\n\n if (h->slice_num)\n h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y;\n if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y\n && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y\n && h->slice_num >= MAX_SLICES) {\n //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case\n av_log(h->avctx, AV_LOG_WARNING, \"Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\\n\", h->slice_num, MAX_SLICES);\n }\n\n for (j = 0; j < 2; j++) {\n int id_list[16];\n int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];\n for (i = 0; i < 16; i++) {\n id_list[i] = 60;\n if (j < h->list_count && i < h->ref_count[j] &&\n h->ref_list[j][i].f.buf[0]) {\n int k;\n AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer;\n for (k = 0; k < h->short_ref_count; k++)\n if (h->short_ref[k]->f.buf[0]->buffer == buf) {\n id_list[i] = k;\n break;\n }\n for (k = 0; k < h->long_ref_count; k++)\n if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) {\n id_list[i] = h->short_ref_count + k;\n break;\n }\n }\n }\n\n ref2frm[0] =\n ref2frm[1] = -1;\n for (i = 0; i < 16; i++)\n ref2frm[i + 2] = 4 * id_list[i] + (h->ref_list[j][i].reference & 3);\n ref2frm[18 + 0] =\n ref2frm[18 + 1] = -1;\n for (i = 16; i < 48; i++)\n ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +\n (h->ref_list[j][i].reference & 3);\n }\n\n if (h->ref_count[0]) h->er.last_pic = &h->ref_list[0][0];\n if (h->ref_count[1]) h->er.next_pic = &h->ref_list[1][0];\n h->er.ref_count = h->ref_count[0];\n h0->au_pps_id = pps_id;\n h->sps.new =\n h0->sps_buffers[h->pps.sps_id]->new = 0;\n h->current_sps_id = h->pps.sps_id;\n\n if (h->avctx->debug & FF_DEBUG_PICT_INFO) {\n av_log(h->avctx, AV_LOG_DEBUG,\n \"slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\\n\",\n h->slice_num,\n (h->picture_structure == PICT_FRAME ? \"F\" : h->picture_structure == PICT_TOP_FIELD ? \"T\" : \"B\"),\n first_mb_in_slice,\n av_get_picture_type_char(h->slice_type),\n h->slice_type_fixed ? \" fix\" : \"\",\n h->nal_unit_type == NAL_IDR_SLICE ? \" IDR\" : \"\",\n pps_id, h->frame_num,\n h->cur_pic_ptr->field_poc[0],\n h->cur_pic_ptr->field_poc[1],\n h->ref_count[0], h->ref_count[1],\n h->qscale,\n h->deblocking_filter,\n h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,\n h->use_weight,\n h->use_weight == 1 && h->use_weight_chroma ? \"c\" : \"\",\n h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? \"SPAT\" : \"TEMP\") : \"\");\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'avcodec/h264: more completely check the loop filter parameters\n\nFixes out of array read\nFixes: caa65cc01655505705129b677189f036-signal_sigsegv_fdcc43_2681_cov_3043376737_PPH422I5_Panasonic_A.264\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: __getcwd_generic (char *buf, size_t size)\n{\n /* Lengths of big file name components and entire file names, and a\n deep level of file name nesting. These numbers are not upper\n bounds; they are merely large values suitable for initial\n allocations, designed to be large enough for most real-world\n uses. */\n enum\n {\n BIG_FILE_NAME_COMPONENT_LENGTH = 255,\n BIG_FILE_NAME_LENGTH = MIN (4095, PATH_MAX - 1),\n DEEP_NESTING = 100\n };\n\n#if HAVE_OPENAT_SUPPORT\n int fd = AT_FDCWD;\n bool fd_needs_closing = false;\n#else\n char dots[DEEP_NESTING * sizeof \"..\" + BIG_FILE_NAME_COMPONENT_LENGTH + 1];\n char *dotlist = dots;\n size_t dotsize = sizeof dots;\n size_t dotlen = 0;\n#endif\n DIR *dirstream = NULL;\n dev_t rootdev, thisdev;\n ino_t rootino, thisino;\n char *dir;\n register char *dirp;\n struct __stat64_t64 st;\n size_t allocated = size;\n size_t used;\n\n#if HAVE_MINIMALLY_WORKING_GETCWD\n /* If AT_FDCWD is not defined, the algorithm below is O(N**2) and\n this is much slower than the system getcwd (at least on\n GNU/Linux). So trust the system getcwd's results unless they\n look suspicious.\n\n Use the system getcwd even if we have openat support, since the\n system getcwd works even when a parent is unreadable, while the\n openat-based approach does not.\n\n But on AIX 5.1..7.1, the system getcwd is not even minimally\n working: If the current directory name is slightly longer than\n PATH_MAX, it omits the first directory component and returns\n this wrong result with errno = 0. */\n\n# undef getcwd\n dir = getcwd_system (buf, size);\n if (dir || (size && errno == ERANGE))\n return dir;\n\n /* Solaris getcwd (NULL, 0) fails with errno == EINVAL, but it has\n internal magic that lets it work even if an ancestor directory is\n inaccessible, which is better in many cases. So in this case try\n again with a buffer that's almost always big enough. */\n if (errno == EINVAL && buf == NULL && size == 0)\n {\n char big_buffer[BIG_FILE_NAME_LENGTH + 1];\n dir = getcwd_system (big_buffer, sizeof big_buffer);\n if (dir)\n return strdup (dir);\n }\n\n# if HAVE_PARTLY_WORKING_GETCWD\n /* The system getcwd works, except it sometimes fails when it\n shouldn't, setting errno to ERANGE, ENAMETOOLONG, or ENOENT. */\n if (errno != ERANGE && errno != ENAMETOOLONG && errno != ENOENT)\n return NULL;\n# endif\n#endif\n if (size == 0)\n {\n if (buf != NULL)\n {\n __set_errno (EINVAL);\n return NULL;\n }\n\n allocated = BIG_FILE_NAME_LENGTH + 1;\n }\n\n if (buf == NULL)\n {\n dir = malloc (allocated);\n if (dir == NULL)\n return NULL;\n }\n else\n dir = buf;\n\n dirp = dir + allocated;\n *--dirp = '\\0';\n\n if (__lstat64_time64 (\".\", &st) < 0)\n goto lose;\n thisdev = st.st_dev;\n thisino = st.st_ino;\n\n if (__lstat64_time64 (\"/\", &st) < 0)\n goto lose;\n rootdev = st.st_dev;\n rootino = st.st_ino;\n\n while (!(thisdev == rootdev && thisino == rootino))\n {\n struct dirent64 *d;\n dev_t dotdev;\n ino_t dotino;\n bool mount_point;\n int parent_status;\n size_t dirroom;\n size_t namlen;\n bool use_d_ino = true;\n\n /* Look at the parent directory. */\n#if HAVE_OPENAT_SUPPORT\n fd = __openat64 (fd, \"..\", O_RDONLY);\n if (fd < 0)\n goto lose;\n fd_needs_closing = true;\n parent_status = __fstat64_time64 (fd, &st);\n#else\n dotlist[dotlen++] = '.';\n dotlist[dotlen++] = '.';\n dotlist[dotlen] = '\\0';\n parent_status = __lstat64_time64 (dotlist, &st);\n#endif\n if (parent_status != 0)\n goto lose;\n\n if (dirstream && __closedir (dirstream) != 0)\n {\n dirstream = NULL;\n goto lose;\n }\n\n /* Figure out if this directory is a mount point. */\n dotdev = st.st_dev;\n dotino = st.st_ino;\n mount_point = dotdev != thisdev;\n\n /* Search for the last directory. */\n#if HAVE_OPENAT_SUPPORT\n dirstream = __fdopendir (fd);\n if (dirstream == NULL)\n goto lose;\n fd_needs_closing = false;\n#else\n dirstream = __opendir (dotlist);\n if (dirstream == NULL)\n goto lose;\n dotlist[dotlen++] = '/';\n#endif\n for (;;)\n {\n /* Clear errno to distinguish EOF from error if readdir returns\n NULL. */\n __set_errno (0);\n d = __readdir64 (dirstream);\n\n /* When we've iterated through all directory entries without finding\n one with a matching d_ino, rewind the stream and consider each\n name again, but this time, using lstat. This is necessary in a\n chroot on at least one system (glibc-2.3.6 + linux 2.6.12), where\n .., ../.., ../../.., etc. all had the same device number, yet the\n d_ino values for entries in / did not match those obtained\n via lstat. */\n if (d == NULL && errno == 0 && use_d_ino)\n {\n use_d_ino = false;\n __rewinddir (dirstream);\n d = __readdir64 (dirstream);\n }\n\n if (d == NULL)\n {\n if (errno == 0)\n /* EOF on dirstream, which can mean e.g., that the current\n directory has been removed. */\n __set_errno (ENOENT);\n goto lose;\n }\n if (d->d_name[0] == '.' &&\n (d->d_name[1] == '\\0' ||\n (d->d_name[1] == '.' && d->d_name[2] == '\\0')))\n continue;\n\n if (use_d_ino)\n {\n bool match = (MATCHING_INO (d, thisino) || mount_point);\n if (! match)\n continue;\n }\n\n {\n int entry_status;\n#if HAVE_OPENAT_SUPPORT\n entry_status = __fstatat64_time64 (fd, d->d_name, &st,\n\t\t\t\t\t AT_SYMLINK_NOFOLLOW);\n#else\n /* Compute size needed for this file name, or for the file\n name \"..\" in the same directory, whichever is larger.\n Room for \"..\" might be needed the next time through\n the outer loop. */\n size_t name_alloc = _D_ALLOC_NAMLEN (d);\n size_t filesize = dotlen + MAX (sizeof \"..\", name_alloc);\n\n if (filesize < dotlen)\n goto memory_exhausted;\n\n if (dotsize < filesize)\n {\n /* My, what a deep directory tree you have, Grandma. */\n size_t newsize = MAX (filesize, dotsize * 2);\n size_t i;\n if (newsize < dotsize)\n goto memory_exhausted;\n if (dotlist != dots)\n free (dotlist);\n dotlist = malloc (newsize);\n if (dotlist == NULL)\n goto lose;\n dotsize = newsize;\n\n i = 0;\n do\n {\n dotlist[i++] = '.';\n dotlist[i++] = '.';\n dotlist[i++] = '/';\n }\n while (i < dotlen);\n }\n\n memcpy (dotlist + dotlen, d->d_name, _D_ALLOC_NAMLEN (d));\n entry_status = __lstat64_time64 (dotlist, &st);\n#endif\n /* We don't fail here if we cannot stat() a directory entry.\n This can happen when (network) file systems fail. If this\n entry is in fact the one we are looking for we will find\n out soon as we reach the end of the directory without\n having found anything. */\n if (entry_status == 0 && S_ISDIR (st.st_mode)\n && st.st_dev == thisdev && st.st_ino == thisino)\n break;\n }\n }\n\n dirroom = dirp - dir;\n namlen = _D_EXACT_NAMLEN (d);\n\n if (dirroom <= namlen)\n {\n if (size != 0)\n {\n __set_errno (ERANGE);\n goto lose;\n }\n else\n {\n char *tmp;\n size_t oldsize = allocated;\n\n allocated += MAX (allocated, namlen);\n if (allocated < oldsize\n || ! (tmp = realloc (dir, allocated)))\n goto memory_exhausted;\n\n /* Move current contents up to the end of the buffer.\n This is guaranteed to be non-overlapping. */\n dirp = memcpy (tmp + allocated - (oldsize - dirroom),\n tmp + dirroom,\n oldsize - dirroom);\n dir = tmp;\n }\n }\n dirp -= namlen;\n memcpy (dirp, d->d_name, namlen);\n *--dirp = '/';\n\n thisdev = dotdev;\n thisino = dotino;\n }\n\n if (dirstream && __closedir (dirstream) != 0)\n {\n dirstream = NULL;\n goto lose;\n }\n\n if (dirp == &dir[allocated - 1])\n *--dirp = '/';\n\n#if ! HAVE_OPENAT_SUPPORT\n if (dotlist != dots)\n free (dotlist);\n#endif\n\n used = dir + allocated - dirp;\n memmove (dir, dirp, used);\n\n if (size == 0)\n /* Ensure that the buffer is only as large as necessary. */\n buf = (used < allocated ? realloc (dir, used) : dir);\n\n if (buf == NULL)\n /* Either buf was NULL all along, or 'realloc' failed but\n we still have the original string. */\n buf = dir;\n\n return buf;\n\n memory_exhausted:\n __set_errno (ENOMEM);\n lose:\n {\n int save = errno;\n if (dirstream)\n __closedir (dirstream);\n#if HAVE_OPENAT_SUPPORT\n if (fd_needs_closing)\n __close_nocancel_nostatus (fd);\n#else\n if (dotlist != dots)\n free (dotlist);\n#endif\n if (buf == NULL)\n free (dir);\n __set_errno (save);\n }\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284'], 'message': 'getcwd: Set errno to ERANGE for size == 1 (CVE-2021-3999)\n\nNo valid path returned by getcwd would fit into 1 byte, so reject the\nsize early and return NULL with errno set to ERANGE. This change is\nprompted by CVE-2021-3999, which describes a single byte buffer\nunderflow and overflow when all of the following conditions are met:\n\n- The buffer size (i.e. the second argument of getcwd) is 1 byte\n- The current working directory is too long\n- '/' is also mounted on the current working directory\n\nSequence of events:\n\n- In sysdeps/unix/sysv/linux/getcwd.c, the syscall returns ENAMETOOLONG\n because the linux kernel checks for name length before it checks\n buffer size\n\n- The code falls back to the generic getcwd in sysdeps/posix\n\n- In the generic func, the buf[0] is set to '\\0' on line 250\n\n- this while loop on line 262 is bypassed:\n\n while (!(thisdev == rootdev && thisino == rootino))\n\n since the rootfs (/) is bind mounted onto the directory and the flow\n goes on to line 449, where it puts a '/' in the byte before the\n buffer.\n\n- Finally on line 458, it moves 2 bytes (the underflowed byte and the\n '\\0') to the buf[0] and buf[1], resulting in a 1 byte buffer overflow.\n\n- buf is returned on line 469 and errno is not set.\n\nThis resolves BZ #28769.\n\nReviewed-by: Andreas Schwab \nReviewed-by: Adhemerval Zanella \nSigned-off-by: Qualys Security Advisory \nSigned-off-by: Siddhesh Poyarekar '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int install_relocation_handler(int num_cpus, size_t save_state_size)\n{\n\tstruct smm_loader_params smm_params = {\n\t\t.per_cpu_stack_size = CONFIG_SMM_STUB_STACK_SIZE,\n\t\t.num_concurrent_stacks = num_cpus,\n\t\t.per_cpu_save_state_size = save_state_size,\n\t\t.num_concurrent_save_states = 1,\n\t\t.handler = smm_do_relocation,\n\t};\n\n\t/* Allow callback to override parameters. */\n\tif (mp_state.ops.adjust_smm_params != NULL)\n\t\tmp_state.ops.adjust_smm_params(&smm_params, 0);\n\n\tif (smm_setup_relocation_handler(&smm_params))\n\t\treturn -1;\n\n\tadjust_smm_apic_id_map(&smm_params);\n\n\treturn 0;\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: ip6_print(netdissect_options *ndo, const u_char *bp, u_int length)\n{\n\tregister const struct ip6_hdr *ip6;\n\tregister int advance;\n\tu_int len;\n\tconst u_char *ipend;\n\tregister const u_char *cp;\n\tregister u_int payload_len;\n\tint nh;\n\tint fragmented = 0;\n\tu_int flow;\n\n\tip6 = (const struct ip6_hdr *)bp;\n\n\tND_TCHECK(*ip6);\n\tif (length < sizeof (struct ip6_hdr)) {\n\t\tND_PRINT((ndo, \"truncated-ip6 %u\", length));\n\t\treturn;\n\t}\n\n if (!ndo->ndo_eflag)\n ND_PRINT((ndo, \"IP6 \"));\n\n\tif (IP6_VERSION(ip6) != 6) {\n ND_PRINT((ndo,\"version error: %u != 6\", IP6_VERSION(ip6)));\n return;\n\t}\n\n\tpayload_len = EXTRACT_16BITS(&ip6->ip6_plen);\n\tlen = payload_len + sizeof(struct ip6_hdr);\n\tif (length < len)\n\t\tND_PRINT((ndo, \"truncated-ip6 - %u bytes missing!\",\n\t\t\tlen - length));\n\n if (ndo->ndo_vflag) {\n flow = EXTRACT_32BITS(&ip6->ip6_flow);\n ND_PRINT((ndo, \"(\"));\n#if 0\n /* rfc1883 */\n if (flow & 0x0f000000)\n\t\tND_PRINT((ndo, \"pri 0x%02x, \", (flow & 0x0f000000) >> 24));\n if (flow & 0x00ffffff)\n\t\tND_PRINT((ndo, \"flowlabel 0x%06x, \", flow & 0x00ffffff));\n#else\n /* RFC 2460 */\n if (flow & 0x0ff00000)\n\t\tND_PRINT((ndo, \"class 0x%02x, \", (flow & 0x0ff00000) >> 20));\n if (flow & 0x000fffff)\n\t\tND_PRINT((ndo, \"flowlabel 0x%05x, \", flow & 0x000fffff));\n#endif\n\n ND_PRINT((ndo, \"hlim %u, next-header %s (%u) payload length: %u) \",\n ip6->ip6_hlim,\n tok2str(ipproto_values,\"unknown\",ip6->ip6_nxt),\n ip6->ip6_nxt,\n payload_len));\n }\n\n\t/*\n\t * Cut off the snapshot length to the end of the IP payload.\n\t */\n\tipend = bp + len;\n\tif (ipend < ndo->ndo_snapend)\n\t\tndo->ndo_snapend = ipend;\n\n\tcp = (const u_char *)ip6;\n\tadvance = sizeof(struct ip6_hdr);\n\tnh = ip6->ip6_nxt;\n\twhile (cp < ndo->ndo_snapend && advance > 0) {\n\t\tcp += advance;\n\t\tlen -= advance;\n\n\t\tif (cp == (const u_char *)(ip6 + 1) &&\n\t\t nh != IPPROTO_TCP && nh != IPPROTO_UDP &&\n\t\t nh != IPPROTO_DCCP && nh != IPPROTO_SCTP) {\n\t\t\tND_PRINT((ndo, \"%s > %s: \", ip6addr_string(ndo, &ip6->ip6_src),\n\t\t\t\t ip6addr_string(ndo, &ip6->ip6_dst)));\n\t\t}\n\n\t\tswitch (nh) {\n\t\tcase IPPROTO_HOPOPTS:\n\t\t\tadvance = hbhopt_print(ndo, cp);\n\t\t\tif (advance < 0)\n\t\t\t\treturn;\n\t\t\tnh = *cp;\n\t\t\tbreak;\n\t\tcase IPPROTO_DSTOPTS:\n\t\t\tadvance = dstopt_print(ndo, cp);\n\t\t\tif (advance < 0)\n\t\t\t\treturn;\n\t\t\tnh = *cp;\n\t\t\tbreak;\n\t\tcase IPPROTO_FRAGMENT:\n\t\t\tadvance = frag6_print(ndo, cp, (const u_char *)ip6);\n\t\t\tif (advance < 0 || ndo->ndo_snapend <= cp + advance)\n\t\t\t\treturn;\n\t\t\tnh = *cp;\n\t\t\tfragmented = 1;\n\t\t\tbreak;\n\n\t\tcase IPPROTO_MOBILITY_OLD:\n\t\tcase IPPROTO_MOBILITY:\n\t\t\t/*\n\t\t\t * XXX - we don't use \"advance\"; RFC 3775 says that\n\t\t\t * the next header field in a mobility header\n\t\t\t * should be IPPROTO_NONE, but speaks of\n\t\t\t * the possiblity of a future extension in\n\t\t\t * which payload can be piggybacked atop a\n\t\t\t * mobility header.\n\t\t\t */\n\t\t\tadvance = mobility_print(ndo, cp, (const u_char *)ip6);\n\t\t\tnh = *cp;\n\t\t\treturn;\n\t\tcase IPPROTO_ROUTING:\n\t\t\tadvance = rt6_print(ndo, cp, (const u_char *)ip6);\n\t\t\tnh = *cp;\n\t\t\tbreak;\n\t\tcase IPPROTO_SCTP:\n\t\t\tsctp_print(ndo, cp, (const u_char *)ip6, len);\n\t\t\treturn;\n\t\tcase IPPROTO_DCCP:\n\t\t\tdccp_print(ndo, cp, (const u_char *)ip6, len);\n\t\t\treturn;\n\t\tcase IPPROTO_TCP:\n\t\t\ttcp_print(ndo, cp, len, (const u_char *)ip6, fragmented);\n\t\t\treturn;\n\t\tcase IPPROTO_UDP:\n\t\t\tudp_print(ndo, cp, len, (const u_char *)ip6, fragmented);\n\t\t\treturn;\n\t\tcase IPPROTO_ICMPV6:\n\t\t\ticmp6_print(ndo, cp, len, (const u_char *)ip6, fragmented);\n\t\t\treturn;\n\t\tcase IPPROTO_AH:\n\t\t\tadvance = ah_print(ndo, cp);\n\t\t\tnh = *cp;\n\t\t\tbreak;\n\t\tcase IPPROTO_ESP:\n\t\t {\n\t\t\tint enh, padlen;\n\t\t\tadvance = esp_print(ndo, cp, len, (const u_char *)ip6, &enh, &padlen);\n\t\t\tnh = enh & 0xff;\n\t\t\tlen -= padlen;\n\t\t\tbreak;\n\t\t }\n\t\tcase IPPROTO_IPCOMP:\n\t\t {\n\t\t\tipcomp_print(ndo, cp);\n\t\t\t/*\n\t\t\t * Either this has decompressed the payload and\n\t\t\t * printed it, in which case there's nothing more\n\t\t\t * to do, or it hasn't, in which case there's\n\t\t\t * nothing more to do.\n\t\t\t */\n\t\t\tadvance = -1;\n\t\t\tbreak;\n\t\t }\n\n\t\tcase IPPROTO_PIM:\n\t\t\tpim_print(ndo, cp, len, (const u_char *)ip6);\n\t\t\treturn;\n\n\t\tcase IPPROTO_OSPF:\n\t\t\tospf6_print(ndo, cp, len);\n\t\t\treturn;\n\n\t\tcase IPPROTO_IPV6:\n\t\t\tip6_print(ndo, cp, len);\n\t\t\treturn;\n\n\t\tcase IPPROTO_IPV4:\n\t\t ip_print(ndo, cp, len);\n\t\t\treturn;\n\n case IPPROTO_PGM:\n pgm_print(ndo, cp, len, (const u_char *)ip6);\n return;\n\n\t\tcase IPPROTO_GRE:\n\t\t\tgre_print(ndo, cp, len);\n\t\t\treturn;\n\n\t\tcase IPPROTO_RSVP:\n\t\t\trsvp_print(ndo, cp, len);\n\t\t\treturn;\n\n\t\tcase IPPROTO_NONE:\n\t\t\tND_PRINT((ndo, \"no next header\"));\n\t\t\treturn;\n\n\t\tdefault:\n\t\t\tND_PRINT((ndo, \"ip-proto-%d %d\", nh, len));\n\t\t\treturn;\n\t\t}\n\t}\n\n\treturn;\ntrunc:\n\tND_PRINT((ndo, \"[|ip6]\"));\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: static int pkey_gost2018_encrypt(EVP_PKEY_CTX *pctx, unsigned char *out,\n size_t *out_len, const unsigned char *key,\n size_t key_len)\n{\n PSKeyTransport_gost *pst = NULL;\n EVP_PKEY *pubk = EVP_PKEY_CTX_get0_pkey(pctx);\n struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(pctx);\n int pkey_nid = EVP_PKEY_base_id(pubk);\n unsigned char expkeys[64];\n EVP_PKEY *sec_key = NULL;\n int ret = 0;\n int mac_nid = NID_undef;\n size_t mac_len = 0;\n int exp_len = 0, iv_len = 0;\n unsigned char *exp_buf = NULL;\n int key_is_ephemeral = 0;\n\n switch (data->cipher_nid) {\n case NID_magma_ctr:\n mac_nid = NID_magma_mac;\n mac_len = 8;\n iv_len = 4;\n break;\n case NID_grasshopper_ctr:\n mac_nid = NID_grasshopper_mac;\n mac_len = 16;\n iv_len = 8;\n break;\n default:\n GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_INVALID_CIPHER);\n return -1;\n break;\n }\n exp_len = key_len + mac_len;\n exp_buf = OPENSSL_malloc(exp_len);\n if (!exp_buf) {\n GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);\n return -1;\n }\n\n sec_key = EVP_PKEY_CTX_get0_peerkey(pctx);\n if (!sec_key)\n {\n sec_key = EVP_PKEY_new();\n if (sec_key == NULL) {\n GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE );\n goto err;\n }\n\n if (!EVP_PKEY_assign(sec_key, EVP_PKEY_base_id(pubk), EC_KEY_new())\n || !EVP_PKEY_copy_parameters(sec_key, pubk)\n || !gost_ec_keygen(EVP_PKEY_get0(sec_key))) {\n GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT,\n GOST_R_ERROR_COMPUTING_SHARED_KEY);\n goto err;\n }\n key_is_ephemeral = 1;\n }\n\n if (data->shared_ukm_size == 0) {\n if (RAND_bytes(data->shared_ukm, 32) <= 0) {\n GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_INTERNAL_ERROR);\n goto err;\n }\n data->shared_ukm_size = 32;\n }\n\n if (gost_keg(data->shared_ukm, pkey_nid,\n EC_KEY_get0_public_key(EVP_PKEY_get0(pubk)),\n EVP_PKEY_get0(sec_key), expkeys) <= 0) {\n GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT,\n GOST_R_ERROR_COMPUTING_EXPORT_KEYS);\n goto err;\n }\n\n if (gost_kexp15(key, key_len, data->cipher_nid, expkeys + 32,\n mac_nid, expkeys + 0, data->shared_ukm + 24, iv_len,\n exp_buf, &exp_len) <= 0) {\n GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_CANNOT_PACK_EPHEMERAL_KEY);\n goto err;\n }\n\n pst = PSKeyTransport_gost_new();\n if (!pst) {\n GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);\n goto err;\n }\n\n pst->ukm = ASN1_OCTET_STRING_new();\n if (pst->ukm == NULL) {\n GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);\n goto err;\n }\n\n if (!ASN1_OCTET_STRING_set(pst->ukm, data->shared_ukm, data->shared_ukm_size)) {\n GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);\n goto err;\n }\n\n if (!ASN1_OCTET_STRING_set(pst->psexp, exp_buf, exp_len)) {\n GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE);\n goto err;\n }\n\n if (!X509_PUBKEY_set(&pst->ephem_key, out ? sec_key : pubk)) {\n GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_CANNOT_PACK_EPHEMERAL_KEY);\n goto err;\n }\n\n if ((*out_len = i2d_PSKeyTransport_gost(pst, out ? &out : NULL)) > 0)\n ret = 1;\n err:\n OPENSSL_cleanse(expkeys, sizeof(expkeys));\n if (key_is_ephemeral)\n EVP_PKEY_free(sec_key);\n\n PSKeyTransport_gost_free(pst);\n OPENSSL_free(exp_buf);\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'Fix buffer overrun in creating key transport blob according to RFC 9189, 4.2.4.1\n\nResolves: CVE-2022-29242'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Compute(OpKernelContext* context) override {\n const Tensor& input = context->input(0);\n const TensorShape& input_shape = input.shape();\n const int32_t input_dims = input_shape.dims();\n\n const Tensor& segment_id = context->input(1);\n const TensorShape& segment_id_shape = segment_id.shape();\n const int32_t segment_dims = segment_id_shape.dims();\n\n const Tensor& num_segments_tensor = context->input(2);\n OP_REQUIRES(context, num_segments_tensor.NumElements() != 0,\n errors::InvalidArgument(\"Number of segments cannot be empty.\"));\n auto num_segments = num_segments_tensor.scalar()();\n\n OP_REQUIRES(\n context, num_segments >= 0,\n errors::InvalidArgument(\n \"Number of segments must be non-negative but got \", num_segments));\n OP_REQUIRES(context, segment_dims != 0,\n errors::InvalidArgument(\"Segment_id cannot have rank 0\"));\n\n OP_REQUIRES(\n context, segment_dims <= input_dims,\n errors::OutOfRange(\"Invalid segment_id rank \", segment_dims,\n \" for input with \", input_dims, \" dimension(s)\"));\n for (auto i = 0; i < segment_dims; i++) {\n OP_REQUIRES(\n context, segment_id_shape.dim_size(i) == input_shape.dim_size(i),\n errors::InvalidArgument(\n \"Segment dimension is \", segment_id_shape.dim_size(i),\n \" while input dimension is \", input_dims, \" in rank \", i));\n }\n\n // Making output tensor.\n Tensor* output_tensor = nullptr;\n TensorShape output_shape =\n GetOutputShape(input_shape, segment_id_shape, num_segments);\n OP_REQUIRES_OK(context, context->allocate_output(\"output\", output_shape,\n &output_tensor));\n\n // Preparating flat tensors.\n auto output_flat = output_tensor->flat();\n auto flat_segment_id = segment_id.flat();\n auto flat_input = input.flat();\n\n for (int i = 0; i < flat_segment_id.size(); i++) {\n OP_REQUIRES(\n context,\n ((flat_segment_id(i) < num_segments) && (flat_segment_id(i) >= 0)),\n errors::InvalidArgument(\n \"segment_ids are not allowed to exceed num_segments or\"\n \" to have negative values.\"));\n }\n\n int64_t big_stride;\n int64_t small_stride;\n std::tie(big_stride, small_stride) =\n GetStrides(input_shape, segment_id_shape);\n auto relative_offset_set =\n GetFlattenedRelativeOffsets(small_stride, big_stride);\n for (auto start_offset = 0; start_offset < big_stride; start_offset++) {\n for (auto i = 0; i < relative_offset_set.size(); i++) {\n auto output_index = start_offset + flat_segment_id(i) * big_stride;\n auto offset = start_offset + relative_offset_set[i];\n if (output_flat(output_index).length() != 0)\n output_flat(output_index).append(separator_.c_str());\n output_flat(output_index).append(flat_input(offset));\n }\n }\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-703'], 'message': 'Fix tf.raw_ops.UnsortedSegmentJoin vulnerability with invalid num_segments.\n\nCheck that input is actually a scalar before treating it as such.\n\nPiperOrigin-RevId: 445206880'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (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_data(void *opaque, uint8_t *buf, int buf_size)\n{\n struct playlist *v = opaque;\n HLSContext *c = v->parent->priv_data;\n int ret, i;\n int just_opened = 0;\n\nrestart:\n if (!v->needed)\n return AVERROR_EOF;\n\n if (!v->input) {\n int64_t reload_interval;\n\n /* Check that the playlist is still needed before opening a new\n * segment. */\n if (v->ctx && v->ctx->nb_streams &&\n v->parent->nb_streams >= v->stream_offset + v->ctx->nb_streams) {\n v->needed = 0;\n for (i = v->stream_offset; i < v->stream_offset + v->ctx->nb_streams;\n i++) {\n if (v->parent->streams[i]->discard < AVDISCARD_ALL)\n v->needed = 1;\n }\n }\n if (!v->needed) {\n av_log(v->parent, AV_LOG_INFO, \"No longer receiving playlist %d\\n\",\n v->index);\n return AVERROR_EOF;\n }\n\n /* If this is a live stream and the reload interval has elapsed since\n * the last playlist reload, reload the playlists now. */\n reload_interval = default_reload_interval(v);\n\nreload:\n if (!v->finished &&\n av_gettime() - v->last_load_time >= reload_interval) {\n if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) {\n av_log(v->parent, AV_LOG_WARNING, \"Failed to reload playlist %d\\n\",\n v->index);\n return ret;\n }\n /* If we need to reload the playlist again below (if\n * there's still no more segments), switch to a reload\n * interval of half the target duration. */\n reload_interval = v->target_duration / 2;\n }\n if (v->cur_seq_no < v->start_seq_no) {\n av_log(NULL, AV_LOG_WARNING,\n \"skipping %d segments ahead, expired from playlists\\n\",\n v->start_seq_no - v->cur_seq_no);\n v->cur_seq_no = v->start_seq_no;\n }\n if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {\n if (v->finished)\n return AVERROR_EOF;\n while (av_gettime() - v->last_load_time < reload_interval) {\n if (ff_check_interrupt(c->interrupt_callback))\n return AVERROR_EXIT;\n av_usleep(100*1000);\n }\n /* Enough time has elapsed since the last reload */\n goto reload;\n }\n\n ret = open_input(c, v);\n if (ret < 0) {\n av_log(v->parent, AV_LOG_WARNING, \"Failed to open segment of playlist %d\\n\",\n v->index);\n return ret;\n }\n just_opened = 1;\n }\n\n ret = read_from_url(v, buf, buf_size, READ_NORMAL);\n if (ret > 0) {\n if (just_opened && v->is_id3_timestamped != 0) {\n /* Intercept ID3 tags here, elementary audio streams are required\n * to convey timestamps using them in the beginning of each segment. */\n intercept_id3(v, buf, buf_size, &ret);\n }\n\n return ret;\n }\n ffurl_close(v->input);\n v->input = NULL;\n v->cur_seq_no++;\n\n c->cur_seq_no = v->cur_seq_no;\n\n goto restart;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'avformat/hls: Fix DoS due to infinite loop\n\nFixes: loop.m3u\n\nThe default max iteration count of 1000 is arbitrary and ideas for a better solution are welcome\n\nFound-by: Xiaohei and Wangchu from Alibaba Security Team\n\nPrevious version reviewed-by: Steven Liu \nSigned-off-by: Michael Niedermayer \n(cherry picked from commit 7ec414892ddcad88313848494b6fc5f437c9ca4a)\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 dex_parse_debug_item(RBinFile *binfile, RBinDexObj *bin,\n\t\t\t\t RBinDexClass *c, int MI, int MA, int paddr, int ins_size,\n\t\t\t\t int insns_size, char *class_name, int regsz,\n\t\t\t\t int debug_info_off) {\n\tstruct r_bin_t *rbin = binfile->rbin;\n\tconst ut8 *p4 = r_buf_get_at (binfile->buf, debug_info_off, NULL);\n\tconst ut8 *p4_end = p4 + binfile->buf->length - debug_info_off;\n\tut64 line_start;\n\tut64 parameters_size;\n\tut64 param_type_idx;\n\tut16 argReg = regsz - ins_size;\n\tut64 source_file_idx = c->source_file;\n\tRList *params, *debug_positions, *emitted_debug_locals = NULL; \n\tbool keep = true;\n\tif (argReg > regsz) {\n\t\treturn; // this return breaks tests\n\t}\n\tp4 = r_uleb128 (p4, p4_end - p4, &line_start);\n\tp4 = r_uleb128 (p4, p4_end - p4, ¶meters_size);\n\t// TODO: check when we should use source_file\n\t// The state machine consists of five registers\n\tut32 address = 0;\n\tut32 line = line_start;\n\tif (!(debug_positions = r_list_newf ((RListFree)free))) {\n\t\treturn;\t\n\t}\n\tif (!(emitted_debug_locals = r_list_newf ((RListFree)free))) {\n\t\tr_list_free (debug_positions);\n\t\treturn;\n\t}\n\n\tstruct dex_debug_local_t debug_locals[regsz];\n\tmemset (debug_locals, 0, sizeof (struct dex_debug_local_t) * regsz);\n\tif (!(MA & 0x0008)) {\n\t\tdebug_locals[argReg].name = \"this\";\n\t\tdebug_locals[argReg].descriptor = r_str_newf(\"%s;\", class_name);\n\t\tdebug_locals[argReg].startAddress = 0;\n\t\tdebug_locals[argReg].signature = NULL;\n\t\tdebug_locals[argReg].live = true;\n\t\targReg++;\n\t}\n\tif (!(params = dex_method_signature2 (bin, MI))) {\n\t\tr_list_free (debug_positions);\n\t\tr_list_free (emitted_debug_locals);\n\t\treturn;\n\t}\n\n\tRListIter *iter = r_list_iterator (params);\n\tchar *name;\n\tchar *type;\n\tint reg;\n\n\tr_list_foreach (params, iter, type) {\n\t\tif ((argReg >= regsz) || !type || parameters_size <= 0) {\n\t\t\tr_list_free (debug_positions);\n\t\t\tr_list_free (params);\n\t\t\tr_list_free (emitted_debug_locals);\n\t\t\treturn;\n\t\t}\n\t\tp4 = r_uleb128 (p4, p4_end - p4, ¶m_type_idx); // read uleb128p1\n\t\tparam_type_idx -= 1;\n\t\tname = getstr (bin, param_type_idx);\n\t\treg = argReg;\n\t\tswitch (type[0]) {\n\t\tcase 'D':\n\t\tcase 'J':\n\t\t\targReg += 2;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\targReg += 1;\n\t\t\tbreak;\n\t\t}\n\t\tif (name) {\n\t\t\tdebug_locals[reg].name = name;\n\t\t\tdebug_locals[reg].descriptor = type;\n\t\t\tdebug_locals[reg].signature = NULL;\n\t\t\tdebug_locals[reg].startAddress = address;\n\t\t\tdebug_locals[reg].live = true;\n\t\t}\n\t\t--parameters_size;\n\t}\n\n\tut8 opcode = *(p4++) & 0xff;\n\twhile (keep) {\n\t\tswitch (opcode) {\n\t\tcase 0x0: // DBG_END_SEQUENCE\n\t\t\tkeep = false;\n\t\t\tbreak;\n\t\tcase 0x1: // DBG_ADVANCE_PC\n\t\t\t{\n\t\t\tut64 addr_diff;\n\t\t\tp4 = r_uleb128 (p4, p4_end - p4, &addr_diff);\n\t\t\taddress += addr_diff;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 0x2: // DBG_ADVANCE_LINE\n\t\t\t{\n\t\t\tst64 line_diff = r_sleb128 (&p4, p4_end);\n\t\t\tline += line_diff;\n\t\t\t}\n\t\t\tbreak;\t\n\t\tcase 0x3: // DBG_START_LOCAL\n\t\t\t{\n\t\t\tut64 register_num;\n\t\t\tut64 name_idx;\n\t\t\tut64 type_idx;\n\t\t\tp4 = r_uleb128 (p4, p4_end - p4, ®ister_num);\n\t\t\tp4 = r_uleb128 (p4, p4_end - p4, &name_idx); \n\t\t\tname_idx -= 1;\n\t\t\tp4 = r_uleb128 (p4, p4_end - p4, &type_idx); \n\t\t\ttype_idx -= 1;\n\t\t\tif (register_num >= regsz) {\n\t\t\t\tr_list_free (debug_positions);\n\t\t\t\tr_list_free (params);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Emit what was previously there, if anything\n\t\t\t// emitLocalCbIfLive\n\t\t\tif (debug_locals[register_num].live) {\n\t\t\t\tstruct dex_debug_local_t *local = malloc (\n\t\t\t\t\tsizeof (struct dex_debug_local_t));\n\t\t\t\tif (!local) {\n\t\t\t\t\tkeep = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tlocal->name = debug_locals[register_num].name;\n\t\t\t\tlocal->descriptor = debug_locals[register_num].descriptor;\n\t\t\t\tlocal->startAddress = debug_locals[register_num].startAddress;\n\t\t\t\tlocal->signature = debug_locals[register_num].signature;\n\t\t\t\tlocal->live = true;\n\t\t\t\tlocal->reg = register_num;\n\t\t\t\tlocal->endAddress = address;\n\t\t\t\tr_list_append (emitted_debug_locals, local);\n\t\t\t}\n\t\t\tdebug_locals[register_num].name = getstr (bin, name_idx);\n\t\t\tdebug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx);\n\t\t\tdebug_locals[register_num].startAddress = address;\n\t\t\tdebug_locals[register_num].signature = NULL;\n\t\t\tdebug_locals[register_num].live = true;\n\t\t\t//eprintf(\"DBG_START_LOCAL %x %x %x\\n\", register_num, name_idx, type_idx);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 0x4: //DBG_START_LOCAL_EXTENDED\n\t\t\t{\n\t\t\tut64 register_num;\n\t\t\tut64 name_idx;\n\t\t\tut64 type_idx;\n\t\t\tut64 sig_idx;\n\t\t\tp4 = r_uleb128 (p4, p4_end - p4, ®ister_num);\n\t\t\tp4 = r_uleb128 (p4, p4_end - p4, &name_idx);\n\t\t\tname_idx -= 1;\n\t\t\tp4 = r_uleb128 (p4, p4_end - p4, &type_idx);\n\t\t\ttype_idx -= 1;\n\t\t\tp4 = r_uleb128 (p4, p4_end - p4, &sig_idx);\n\t\t\tsig_idx -= 1;\n\t\t\tif (register_num >= regsz) {\n\t\t\t\tr_list_free (debug_positions);\n\t\t\t\tr_list_free (params);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Emit what was previously there, if anything\n\t\t\t// emitLocalCbIfLive\n\t\t\tif (debug_locals[register_num].live) {\n\t\t\t\tstruct dex_debug_local_t *local = malloc (\n\t\t\t\t\tsizeof (struct dex_debug_local_t));\n\t\t\t\tif (!local) {\n\t\t\t\t\tkeep = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tlocal->name = debug_locals[register_num].name;\n\t\t\t\tlocal->descriptor = debug_locals[register_num].descriptor;\n\t\t\t\tlocal->startAddress = debug_locals[register_num].startAddress;\n\t\t\t\tlocal->signature = debug_locals[register_num].signature;\n\t\t\t\tlocal->live = true;\n\t\t\t\tlocal->reg = register_num;\n\t\t\t\tlocal->endAddress = address;\n\t\t\t\tr_list_append (emitted_debug_locals, local);\n\t\t\t}\n\n\t\t\tdebug_locals[register_num].name = getstr (bin, name_idx);\n\t\t\tdebug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx);\n\t\t\tdebug_locals[register_num].startAddress = address;\n\t\t\tdebug_locals[register_num].signature = getstr (bin, sig_idx);\n\t\t\tdebug_locals[register_num].live = true;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 0x5: // DBG_END_LOCAL\n\t\t\t{\n\t\t\tut64 register_num;\n\t\t\tp4 = r_uleb128 (p4, p4_end - p4, ®ister_num);\n\t\t\t// emitLocalCbIfLive\n\t\t\tif (debug_locals[register_num].live) {\n\t\t\t\tstruct dex_debug_local_t *local = malloc (\n\t\t\t\t\tsizeof (struct dex_debug_local_t));\n\t\t\t\tif (!local) {\n\t\t\t\t\tkeep = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tlocal->name = debug_locals[register_num].name;\n\t\t\t\tlocal->descriptor = debug_locals[register_num].descriptor;\n\t\t\t\tlocal->startAddress = debug_locals[register_num].startAddress;\n\t\t\t\tlocal->signature = debug_locals[register_num].signature;\n\t\t\t\tlocal->live = true;\n\t\t\t\tlocal->reg = register_num;\n\t\t\t\tlocal->endAddress = address;\n\t\t\t\tr_list_append (emitted_debug_locals, local);\n\t\t\t}\n\t\t\tdebug_locals[register_num].live = false;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 0x6: // DBG_RESTART_LOCAL\n\t\t\t{\n\t\t\tut64 register_num;\n\t\t\tp4 = r_uleb128 (p4, p4_end - p4, ®ister_num);\n\t\t\tif (!debug_locals[register_num].live) {\n\t\t\t\tdebug_locals[register_num].startAddress = address;\n\t\t\t\tdebug_locals[register_num].live = true;\n\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 0x7: //DBG_SET_PROLOGUE_END\n\t\t\tbreak;\n\t\tcase 0x8: //DBG_SET_PROLOGUE_BEGIN\n\t\t\tbreak;\n\t\tcase 0x9:\n\t\t\t{\n\t\t\tp4 = r_uleb128 (p4, p4_end - p4, &source_file_idx);\n\t\t\tsource_file_idx--;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t{\n\t\t\tint adjusted_opcode = opcode - 0x0a;\n\t\t\taddress += (adjusted_opcode / 15);\n\t\t\tline += -4 + (adjusted_opcode % 15);\n\t\t\tstruct dex_debug_position_t *position =\n\t\t\t\tmalloc (sizeof (struct dex_debug_position_t));\n\t\t\tif (!position) {\n\t\t\t\tkeep = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tposition->source_file_idx = source_file_idx;\n\t\t\tposition->address = address;\n\t\t\tposition->line = line;\n\t\t\tr_list_append (debug_positions, position);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\topcode = *(p4++) & 0xff;\n\t}\n\n\tif (!binfile->sdb_addrinfo) {\n\t\tbinfile->sdb_addrinfo = sdb_new0 ();\n\t}\n\n\tchar *fileline;\n\tchar offset[64];\n\tchar *offset_ptr;\n\n\tRListIter *iter1;\n\tstruct dex_debug_position_t *pos;\n\tr_list_foreach (debug_positions, iter1, pos) {\n\t\tfileline = r_str_newf (\"%s|%\"PFMT64d, getstr (bin, pos->source_file_idx), pos->line);\n\t\toffset_ptr = sdb_itoa (pos->address + paddr, offset, 16);\n\t\tsdb_set (binfile->sdb_addrinfo, offset_ptr, fileline, 0);\n\t\tsdb_set (binfile->sdb_addrinfo, fileline, offset_ptr, 0);\n\t}\n\n\tif (!dexdump) {\n\t\tr_list_free (debug_positions);\n\t\tr_list_free (emitted_debug_locals);\n\t\tr_list_free (params);\n\t\treturn;\n\t}\n\n\tRListIter *iter2;\n\tstruct dex_debug_position_t *position;\n\n\trbin->cb_printf (\" positions :\\n\");\n\tr_list_foreach (debug_positions, iter2, position) {\n\t\trbin->cb_printf (\" 0x%04llx line=%llu\\n\",\n\t\t\t\t position->address, position->line);\n\t}\n\n\trbin->cb_printf (\" locals :\\n\");\n\n\tRListIter *iter3;\n\tstruct dex_debug_local_t *local;\n\tr_list_foreach (emitted_debug_locals, iter3, local) {\n\t\tif (local->signature) {\n\t\t\trbin->cb_printf (\n\t\t\t\t\" 0x%04x - 0x%04x reg=%d %s %s %s\\n\",\n\t\t\t\tlocal->startAddress, local->endAddress,\n\t\t\t\tlocal->reg, local->name, local->descriptor,\n\t\t\t\tlocal->signature);\n\t\t} else {\n\t\t\trbin->cb_printf (\n\t\t\t\t\" 0x%04x - 0x%04x reg=%d %s %s\\n\",\n\t\t\t\tlocal->startAddress, local->endAddress,\n\t\t\t\tlocal->reg, local->name, local->descriptor);\n\t\t}\n\t}\n\n\tfor (reg = 0; reg < regsz; reg++) {\n\t\tif (debug_locals[reg].live) {\n\t\t\tif (debug_locals[reg].signature) {\n\t\t\t\trbin->cb_printf (\n\t\t\t\t\t\" 0x%04x - 0x%04x reg=%d %s %s \"\n\t\t\t\t\t\"%s\\n\",\n\t\t\t\t\tdebug_locals[reg].startAddress,\n\t\t\t\t\tinsns_size, reg, debug_locals[reg].name,\n\t\t\t\t\tdebug_locals[reg].descriptor,\n\t\t\t\t\tdebug_locals[reg].signature);\n\t\t\t} else {\n\t\t\t\trbin->cb_printf (\n\t\t\t\t\t\" 0x%04x - 0x%04x reg=%d %s %s\"\n\t\t\t\t\t\"\\n\",\n\t\t\t\t\tdebug_locals[reg].startAddress,\n\t\t\t\t\tinsns_size, reg, debug_locals[reg].name,\n\t\t\t\t\tdebug_locals[reg].descriptor);\n\t\t\t}\n\t\t}\n\t}\n\tr_list_free (debug_positions);\n\tr_list_free (emitted_debug_locals);\n\tr_list_free (params);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'fix #6872'" }, { "text": "[INST] Given the following code containing errors, provide Common 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 abst_box_read(GF_Box *s, GF_BitStream *bs)\n{\n\tGF_AdobeBootstrapInfoBox *ptr = (GF_AdobeBootstrapInfoBox *)s;\n\tint i;\n\tu32 tmp_strsize;\n\tchar *tmp_str;\n\tGF_Err e;\n\n\tISOM_DECREASE_SIZE(ptr, 25)\n\tptr->bootstrapinfo_version = gf_bs_read_u32(bs);\n\tptr->profile = gf_bs_read_int(bs, 2);\n\tptr->live = gf_bs_read_int(bs, 1);\n\tptr->update = gf_bs_read_int(bs, 1);\n\tptr->reserved = gf_bs_read_int(bs, 4);\n\tptr->time_scale = gf_bs_read_u32(bs);\n\tptr->current_media_time = gf_bs_read_u64(bs);\n\tptr->smpte_time_code_offset = gf_bs_read_u64(bs);\n\n\ti=0;\n\tif (ptr->size<8) return GF_ISOM_INVALID_FILE;\n\ttmp_strsize =(u32)ptr->size-8;\n\ttmp_str = gf_malloc(sizeof(char)*tmp_strsize);\n\tif (!tmp_str) return GF_OUT_OF_MEM;\n\tmemset(tmp_str, 0, sizeof(char)*tmp_strsize);\n\n\twhile (tmp_strsize) {\n\t\tISOM_DECREASE_SIZE(ptr, 1)\n\t\ttmp_str[i] = gf_bs_read_u8(bs);\n\t\ttmp_strsize--;\n\t\tif (!tmp_str[i])\n\t\t\tbreak;\n\t\ti++;\n\t}\n\tif (i) {\n\t\tptr->movie_identifier = gf_strdup(tmp_str);\n\t}\n\n\tISOM_DECREASE_SIZE(ptr, 1)\n\tptr->server_entry_count = gf_bs_read_u8(bs);\n\tfor (i=0; iserver_entry_count; i++) {\n\t\tint j=0;\n\t\ttmp_strsize=(u32)ptr->size;\n\t\twhile (tmp_strsize) {\n\t\t\tISOM_DECREASE_SIZE(ptr, 1)\n\t\t\ttmp_str[j] = gf_bs_read_u8(bs);\n\t\t\ttmp_strsize--;\n\t\t\tif (!tmp_str[j])\n\t\t\t\tbreak;\n\t\t\tj++;\n\t\t}\n\t\tif (j) {\n\t\t\tgf_list_insert(ptr->server_entry_table, gf_strdup(tmp_str), i);\n\t\t}\n\t}\n\n\tISOM_DECREASE_SIZE(ptr, 1)\n\tptr->quality_entry_count = gf_bs_read_u8(bs);\n\tfor (i=0; iquality_entry_count; i++) {\n\t\tint j=0;\n\t\ttmp_strsize=(u32)ptr->size;\n\t\twhile (tmp_strsize) {\n\t\t\tISOM_DECREASE_SIZE(ptr, 1)\n\t\t\ttmp_str[j] = gf_bs_read_u8(bs);\n\t\t\ttmp_strsize--;\n\t\t\tif (!tmp_str[j])\n\t\t\t\tbreak;\n\t\t\tj++;\n\t\t}\n\n\t\tif (j) {\n\t\t\tgf_list_insert(ptr->quality_entry_table, gf_strdup(tmp_str), i);\n\t\t}\n\t}\n\n\ti=0;\n\ttmp_strsize=(u32)ptr->size;\n\twhile (tmp_strsize) {\n\t\tISOM_DECREASE_SIZE(ptr, 1)\n\t\ttmp_str[i] = gf_bs_read_u8(bs);\n\t\ttmp_strsize--;\n\t\tif (!tmp_str[i])\n\t\t\tbreak;\n\t\ti++;\n\t}\n\tif (i) {\n\t\tptr->drm_data = gf_strdup(tmp_str);\n\t}\n\n\ti=0;\n\ttmp_strsize=(u32)ptr->size;\n\twhile (tmp_strsize) {\n\t\tISOM_DECREASE_SIZE(ptr, 1)\n\t\ttmp_str[i] = gf_bs_read_u8(bs);\n\t\ttmp_strsize--;\n\t\tif (!tmp_str[i])\n\t\t\tbreak;\n\t\ti++;\n\t}\n\tif (i) {\n\t\tptr->meta_data = gf_strdup(tmp_str);\n\t}\n\n\tISOM_DECREASE_SIZE(ptr, 1)\n\tptr->segment_run_table_count = gf_bs_read_u8(bs);\n\tfor (i=0; isegment_run_table_count; i++) {\n\t\tGF_AdobeSegmentRunTableBox *asrt = NULL;\n\t\te = gf_isom_box_parse((GF_Box **)&asrt, bs);\n\t\tif (e) {\n\t\t\tif (asrt) gf_isom_box_del((GF_Box*)asrt);\n\t\t\tgf_free(tmp_str);\n\t\t\treturn e;\n\t\t}\n\t\tgf_list_add(ptr->segment_run_table_entries, asrt);\n\t}\n\n\tISOM_DECREASE_SIZE(ptr, 1)\n\tptr->fragment_run_table_count = gf_bs_read_u8(bs);\n\tfor (i=0; ifragment_run_table_count; i++) {\n\t\tGF_AdobeFragmentRunTableBox *afrt = NULL;\n\t\te = gf_isom_box_parse((GF_Box **)&afrt, bs);\n\t\tif (e) {\n\t\t\tif (afrt) gf_isom_box_del((GF_Box*)afrt);\n\t\t\tgf_free(tmp_str);\n\t\t\treturn e;\n\t\t}\n\t\tgf_list_add(ptr->fragment_run_table_entries, afrt);\n\t}\n\n\tgf_free(tmp_str);\n\n\treturn GF_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'fixed #1568'" }, { "text": "[INST] Given the following code containing errors, provide Common 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_unlock(pthread_mutex_t *mutex)\n{\n\tLeaveCriticalSection(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: GF_Err schm_box_read(GF_Box *s, GF_BitStream *bs)\n{\n\tGF_SchemeTypeBox *ptr = (GF_SchemeTypeBox *)s;\n\n\tISOM_DECREASE_SIZE(ptr, 8);\n\tptr->scheme_type = gf_bs_read_u32(bs);\n\tptr->scheme_version = gf_bs_read_u32(bs);\n\n\tif (ptr->size && (ptr->flags & 0x000001)) {\n\t\tu32 len = (u32) (ptr->size);\n\t\tptr->URI = (char*)gf_malloc(sizeof(char)*len);\n\t\tif (!ptr->URI) return GF_OUT_OF_MEM;\n\t\tgf_bs_read_data(bs, ptr->URI, len);\n\t}\n\treturn GF_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'fixed #1879'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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 nlmclnt_unlock_callback(struct rpc_task *task, void *data)\n{\n\tstruct nlm_rqst\t*req = data;\n\tu32 status = ntohl(req->a_res.status);\n\n\tif (RPC_ASSASSINATED(task))\n\t\tgoto die;\n\n\tif (task->tk_status < 0) {\n\t\tdprintk(\"lockd: unlock failed (err = %d)\\n\", -task->tk_status);\n\t\tgoto retry_rebind;\n\t}\n\tif (status == NLM_LCK_DENIED_GRACE_PERIOD) {\n\t\trpc_delay(task, NLMCLNT_GRACE_WAIT);\n\t\tgoto retry_unlock;\n\t}\n\tif (status != NLM_LCK_GRANTED)\n\t\tprintk(KERN_WARNING \"lockd: unexpected unlock status: %d\\n\", status);\ndie:\n\treturn;\n retry_rebind:\n\tnlm_rebind_host(req->a_host);\n retry_unlock:\n\trpc_restart_call(task);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-399', 'CWE-703'], 'message': 'NLM: Don't hang forever on NLM unlock requests\n\nIf the NLM daemon is killed on the NFS server, we can currently end up\nhanging forever on an 'unlock' request, instead of aborting. Basically,\nif the rpcbind request fails, or the server keeps returning garbage, we\nreally want to quit instead of retrying.\n\nTested-by: Vasily Averin \nSigned-off-by: Trond Myklebust \nCc: stable@kernel.org'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static NTSTATUS ldapsrv_SearchRequest(struct ldapsrv_call *call)\n{\n\tstruct ldap_SearchRequest *req = &call->request->r.SearchRequest;\n\tstruct ldap_Result *done;\n\tstruct ldapsrv_reply *done_r;\n\tTALLOC_CTX *local_ctx;\n\tstruct ldapsrv_context *callback_ctx = NULL;\n\tstruct ldb_context *samdb = talloc_get_type(call->conn->ldb, struct ldb_context);\n\tstruct ldb_dn *basedn;\n\tstruct ldb_request *lreq;\n\tstruct ldb_control *search_control;\n\tstruct ldb_search_options_control *search_options;\n\tstruct ldb_control *extended_dn_control;\n\tstruct ldb_extended_dn_control *extended_dn_decoded = NULL;\n\tstruct ldb_control *notification_control = NULL;\n\tenum ldb_scope scope = LDB_SCOPE_DEFAULT;\n\tconst char **attrs = NULL;\n\tconst char *scope_str, *errstr = NULL;\n\tint result = -1;\n\tint ldb_ret = -1;\n\tunsigned int i;\n\tint extended_type = 1;\n\n\tDEBUG(10, (\"SearchRequest\"));\n\tDEBUGADD(10, (\" basedn: %s\", req->basedn));\n\tDEBUGADD(10, (\" filter: %s\\n\", ldb_filter_from_tree(call, req->tree)));\n\n\tlocal_ctx = talloc_new(call);\n\tNT_STATUS_HAVE_NO_MEMORY(local_ctx);\n\n\tbasedn = ldb_dn_new(local_ctx, samdb, req->basedn);\n\tNT_STATUS_HAVE_NO_MEMORY(basedn);\n\n\tDEBUG(10, (\"SearchRequest: basedn: [%s]\\n\", req->basedn));\n\tDEBUG(10, (\"SearchRequest: filter: [%s]\\n\", ldb_filter_from_tree(call, req->tree)));\n\n\tswitch (req->scope) {\n\t\tcase LDAP_SEARCH_SCOPE_BASE:\n\t\t\tscope_str = \"BASE\";\n\t\t\tscope = LDB_SCOPE_BASE;\n\t\t\tbreak;\n\t\tcase LDAP_SEARCH_SCOPE_SINGLE:\n\t\t\tscope_str = \"ONE\";\n\t\t\tscope = LDB_SCOPE_ONELEVEL;\n\t\t\tbreak;\n\t\tcase LDAP_SEARCH_SCOPE_SUB:\n\t\t\tscope_str = \"SUB\";\n\t\t\tscope = LDB_SCOPE_SUBTREE;\n\t\t\tbreak;\n\t default:\n\t\t\tresult = LDAP_PROTOCOL_ERROR;\n\t\t\tmap_ldb_error(local_ctx, LDB_ERR_PROTOCOL_ERROR, NULL,\n\t\t\t\t&errstr);\n\t\t\terrstr = talloc_asprintf(local_ctx,\n\t\t\t\t\"%s. Invalid scope\", errstr);\n\t\t\tgoto reply;\n\t}\n\tDEBUG(10,(\"SearchRequest: scope: [%s]\\n\", scope_str));\n\n\tif (req->num_attributes >= 1) {\n\t\tattrs = talloc_array(local_ctx, const char *, req->num_attributes+1);\n\t\tNT_STATUS_HAVE_NO_MEMORY(attrs);\n\n\t\tfor (i=0; i < req->num_attributes; i++) {\n\t\t\tDEBUG(10,(\"SearchRequest: attrs: [%s]\\n\",req->attributes[i]));\n\t\t\tattrs[i] = req->attributes[i];\n\t\t}\n\t\tattrs[i] = NULL;\n\t}\n\n\tDEBUG(5,(\"ldb_request %s dn=%s filter=%s\\n\", \n\t\t scope_str, req->basedn, ldb_filter_from_tree(call, req->tree)));\n\n\tcallback_ctx = talloc_zero(local_ctx, struct ldapsrv_context);\n\tNT_STATUS_HAVE_NO_MEMORY(callback_ctx);\n\tcallback_ctx->call = call;\n\tcallback_ctx->extended_type = extended_type;\n\tcallback_ctx->attributesonly = req->attributesonly;\n\n\tldb_ret = ldb_build_search_req_ex(&lreq, samdb, local_ctx,\n\t\t\t\t\t basedn, scope,\n\t\t\t\t\t req->tree, attrs,\n\t\t\t\t\t call->request->controls,\n\t\t\t\t\t callback_ctx,\n\t\t\t\t\t ldap_server_search_callback,\n\t\t\t\t\t NULL);\n\n\tif (ldb_ret != LDB_SUCCESS) {\n\t\tgoto reply;\n\t}\n\n\tif (call->conn->global_catalog) {\n\t\tsearch_control = ldb_request_get_control(lreq, LDB_CONTROL_SEARCH_OPTIONS_OID);\n\n\t\tsearch_options = NULL;\n\t\tif (search_control) {\n\t\t\tsearch_options = talloc_get_type(search_control->data, struct ldb_search_options_control);\n\t\t\tsearch_options->search_options |= LDB_SEARCH_OPTION_PHANTOM_ROOT;\n\t\t} else {\n\t\t\tsearch_options = talloc(lreq, struct ldb_search_options_control);\n\t\t\tNT_STATUS_HAVE_NO_MEMORY(search_options);\n\t\t\tsearch_options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;\n\t\t\tldb_request_add_control(lreq, LDB_CONTROL_SEARCH_OPTIONS_OID, false, search_options);\n\t\t}\n\t} else {\n\t\tldb_request_add_control(lreq, DSDB_CONTROL_NO_GLOBAL_CATALOG, false, NULL);\n\t}\n\n\textended_dn_control = ldb_request_get_control(lreq, LDB_CONTROL_EXTENDED_DN_OID);\n\n\tif (extended_dn_control) {\n\t\tif (extended_dn_control->data) {\n\t\t\textended_dn_decoded = talloc_get_type(extended_dn_control->data, struct ldb_extended_dn_control);\n\t\t\textended_type = extended_dn_decoded->type;\n\t\t} else {\n\t\t\textended_type = 0;\n\t\t}\n\t\tcallback_ctx->extended_type = extended_type;\n\t}\n\n\tnotification_control = ldb_request_get_control(lreq, LDB_CONTROL_NOTIFICATION_OID);\n\tif (notification_control != NULL) {\n\t\tconst struct ldapsrv_call *pc = NULL;\n\t\tsize_t count = 0;\n\n\t\tfor (pc = call->conn->pending_calls; pc != NULL; pc = pc->next) {\n\t\t\tcount += 1;\n\t\t}\n\n\t\tif (count >= call->conn->limits.max_notifications) {\n\t\t\tDEBUG(10,(\"SearchRequest: error MaxNotificationPerConn\\n\"));\n\t\t\tresult = map_ldb_error(local_ctx,\n\t\t\t\t\t LDB_ERR_ADMIN_LIMIT_EXCEEDED,\n\t\t\t\t\t \"MaxNotificationPerConn reached\",\n\t\t\t\t\t &errstr);\n\t\t\tgoto reply;\n\t\t}\n\n\t\t/*\n\t\t * For now we need to do periodic retries on our own.\n\t\t * As the dsdb_notification module will return after each run.\n\t\t */\n\t\tcall->notification.busy = true;\n\t}\n\n\t{\n\t\tconst char *scheme = NULL;\n\t\tswitch (call->conn->referral_scheme) {\n\t\tcase LDAP_REFERRAL_SCHEME_LDAPS:\n\t\t\tscheme = \"ldaps\";\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tscheme = \"ldap\";\n\t\t}\n\t\tldb_ret = ldb_set_opaque(\n\t\t\tsamdb,\n\t\t\tLDAP_REFERRAL_SCHEME_OPAQUE,\n\t\t\tdiscard_const_p(char *, scheme));\n\t\tif (ldb_ret != LDB_SUCCESS) {\n\t\t\tgoto reply;\n\t\t}\n\t}\n\n\t{\n\t\ttime_t timeout = call->conn->limits.search_timeout;\n\n\t\tif (timeout == 0\n\t\t || (req->timelimit != 0\n\t\t\t&& req->timelimit < timeout))\n\t\t{\n\t\t\ttimeout = req->timelimit;\n\t\t}\n\t\tldb_set_timeout(samdb, lreq, timeout);\n\t}\n\n\tif (!call->conn->is_privileged) {\n\t\tldb_req_mark_untrusted(lreq);\n\t}\n\n\tLDB_REQ_SET_LOCATION(lreq);\n\n\tldb_ret = ldb_request(samdb, lreq);\n\n\tif (ldb_ret != LDB_SUCCESS) {\n\t\tgoto reply;\n\t}\n\n\tldb_ret = ldb_wait(lreq->handle, LDB_WAIT_ALL);\n\n\tif (ldb_ret == LDB_SUCCESS) {\n\t\tif (call->notification.busy) {\n\t\t\t/* Move/Add it to the end */\n\t\t\tDLIST_DEMOTE(call->conn->pending_calls, call);\n\t\t\tcall->notification.generation =\n\t\t\t\tcall->conn->service->notification.generation;\n\n\t\t\tif (callback_ctx->count != 0) {\n\t\t\t\tcall->notification.generation += 1;\n\t\t\t\tldapsrv_notification_retry_setup(call->conn->service,\n\t\t\t\t\t\t\t\t true);\n\t\t\t}\n\n\t\t\ttalloc_free(local_ctx);\n\t\t\treturn NT_STATUS_OK;\n\t\t}\n\t}\n\nreply:\n\tDLIST_REMOVE(call->conn->pending_calls, call);\n\tcall->notification.busy = false;\n\n\tdone_r = ldapsrv_init_reply(call, LDAP_TAG_SearchResultDone);\n\tNT_STATUS_HAVE_NO_MEMORY(done_r);\n\n\tdone = &done_r->msg->r.SearchResultDone;\n\tdone->dn = NULL;\n\tdone->referral = NULL;\n\n\tif (result != -1) {\n\t} else if (ldb_ret == LDB_SUCCESS) {\n\t\tif (callback_ctx->controls) {\n\t\t\tdone_r->msg->controls = callback_ctx->controls;\n\t\t\ttalloc_steal(done_r->msg, callback_ctx->controls);\n\t\t}\n\t\tresult = LDB_SUCCESS;\n\t} else {\n\t\tDEBUG(10,(\"SearchRequest: error\\n\"));\n\t\tresult = map_ldb_error(local_ctx, ldb_ret, ldb_errstring(samdb),\n\t\t\t\t &errstr);\n\t}\n\n\tdone->resultcode = result;\n\tdone->errormessage = (errstr?talloc_strdup(done_r, errstr):NULL);\n\n\ttalloc_free(local_ctx);\n\n\treturn ldapsrv_queue_reply_forced(call, done_r);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'CVE-2021-3670 ldap_server: Remove duplicate print of LDAP search details\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=14694\n\nSigned-off-by: Andrew Bartlett \nReviewed-by: Douglas Bagnall \n(cherry picked from commit 2b3af3b560c9617a233c131376c870fce146c002)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TEE_Result syscall_cryp_obj_populate(unsigned long obj,\n\t\t\tstruct utee_attribute *usr_attrs,\n\t\t\tunsigned long attr_count)\n{\n\tTEE_Result res;\n\tstruct tee_ta_session *sess;\n\tstruct tee_obj *o;\n\tconst struct tee_cryp_obj_type_props *type_props;\n\tTEE_Attribute *attrs = NULL;\n\n\tres = tee_ta_get_current_session(&sess);\n\tif (res != TEE_SUCCESS)\n\t\treturn res;\n\n\tres = tee_obj_get(to_user_ta_ctx(sess->ctx),\n\t\t\t tee_svc_uref_to_vaddr(obj), &o);\n\tif (res != TEE_SUCCESS)\n\t\treturn res;\n\n\t/* Must be a transient object */\n\tif ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0)\n\t\treturn TEE_ERROR_BAD_PARAMETERS;\n\n\t/* Must not be initialized already */\n\tif ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)\n\t\treturn TEE_ERROR_BAD_PARAMETERS;\n\n\ttype_props = tee_svc_find_type_props(o->info.objectType);\n\tif (!type_props)\n\t\treturn TEE_ERROR_NOT_IMPLEMENTED;\n\n\tattrs = malloc(sizeof(TEE_Attribute) * attr_count);\n\tif (!attrs)\n\t\treturn TEE_ERROR_OUT_OF_MEMORY;\n\tres = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_attrs, attr_count,\n\t\t\t attrs);\n\tif (res != TEE_SUCCESS)\n\t\tgoto out;\n\n\tres = tee_svc_cryp_check_attr(ATTR_USAGE_POPULATE, type_props,\n\t\t\t\t attrs, attr_count);\n\tif (res != TEE_SUCCESS)\n\t\tgoto out;\n\n\tres = tee_svc_cryp_obj_populate_type(o, type_props, attrs, attr_count);\n\tif (res == TEE_SUCCESS)\n\t\to->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;\n\nout:\n\tfree(attrs);\n\treturn res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'svc: check for allocation overflow in syscall_cryp_obj_populate\n\nWithout checking for overflow there is a risk of allocating a buffer\nwith size smaller than anticipated and as a consequence of that it might\nlead to a heap based overflow with attacker controlled data written\noutside the boundaries of the buffer.\n\nFixes: OP-TEE-2018-0009: \"Integer overflow in crypto system calls\"\n\nSigned-off-by: Joakim Bech \nTested-by: Joakim Bech (QEMU v7, v8)\nReviewed-by: Jens Wiklander \nReported-by: Riscure \nReported-by: Alyssa Milburn \nAcked-by: Etienne Carriere '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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_avc_read_sps_bs_internal(GF_BitStream *bs, AVCState *avc, u32 subseq_sps, u32 *vui_flag_pos, u32 nal_hdr)\n{\n\tAVC_SPS *sps;\n\ts32 mb_width, mb_height, sps_id = -1;\n\tu32 profile_idc, level_idc, pcomp, i, chroma_format_idc, cl = 0, cr = 0, ct = 0, cb = 0, luma_bd, chroma_bd;\n\tu8 separate_colour_plane_flag = 0;\n\n\tif (!vui_flag_pos) {\n\t\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);\n\t}\n\n\tif (!bs) {\n\t\treturn -1;\n\t}\n\n\tif (!nal_hdr) {\n\t\tgf_bs_read_int_log(bs, 1, \"forbidden_zero_bit\");\n\t\tgf_bs_read_int_log(bs, 2, \"nal_ref_idc\");\n\t\tgf_bs_read_int_log(bs, 5, \"nal_unit_type\");\n\t}\n\tprofile_idc = gf_bs_read_int_log(bs, 8, \"profile_idc\");\n\n\tpcomp = gf_bs_read_int_log(bs, 8, \"profile_compatibility\");\n\t/*sanity checks*/\n\tif (pcomp & 0x3)\n\t\treturn -1;\n\n\tlevel_idc = gf_bs_read_int_log(bs, 8, \"level_idc\");\n\n\t/*SubsetSps is used to be sure that AVC SPS are not going to be scratched\n\tby subset SPS. According to the SVC standard, subset SPS can have the same sps_id\n\tthan its base layer, but it does not refer to the same SPS. */\n\tsps_id = gf_bs_read_ue_log(bs, \"sps_id\") + GF_SVC_SSPS_ID_SHIFT * subseq_sps;\n\tif ((sps_id < 0) || (sps_id >= 32)) {\n\t\treturn -1;\n\t}\n\n\tluma_bd = chroma_bd = 0;\n\tsps = &avc->sps[sps_id];\n\tchroma_format_idc = sps->ChromaArrayType = 1;\n\tsps->state |= subseq_sps ? AVC_SUBSPS_PARSED : AVC_SPS_PARSED;\n\n\t/*High Profile and SVC*/\n\tswitch (profile_idc) {\n\tcase 100:\n\tcase 110:\n\tcase 122:\n\tcase 244:\n\tcase 44:\n\t\t/*sanity checks: note1 from 7.4.2.1.1 of iso/iec 14496-10-N11084*/\n\t\tif (pcomp & 0xE0)\n\t\t\treturn -1;\n\tcase 83:\n\tcase 86:\n\tcase 118:\n\tcase 128:\n\t\tchroma_format_idc = gf_bs_read_ue_log(bs, \"chroma_format_idc\");\n\t\tsps->ChromaArrayType = chroma_format_idc;\n\t\tif (chroma_format_idc == 3) {\n\t\t\tseparate_colour_plane_flag = gf_bs_read_int_log(bs, 1, \"separate_colour_plane_flag\");\n\t\t\t/*\n\t\t\tDepending on the value of separate_colour_plane_flag, the value of the variable ChromaArrayType is assigned as follows.\n\t\t\t\\96\tIf separate_colour_plane_flag is equal to 0, ChromaArrayType is set equal to chroma_format_idc.\n\t\t\t\\96\tOtherwise (separate_colour_plane_flag is equal to 1), ChromaArrayType is set equal to 0.\n\t\t\t*/\n\t\t\tif (separate_colour_plane_flag) sps->ChromaArrayType = 0;\n\t\t}\n\t\tluma_bd = gf_bs_read_ue_log(bs, \"luma_bit_depth\");\n\t\tchroma_bd = gf_bs_read_ue_log(bs, \"chroma_bit_depth\");\n\t\t/*qpprime_y_zero_transform_bypass_flag = */ gf_bs_read_int_log(bs, 1, \"qpprime_y_zero_transform_bypass_flag\");\n\t\t/*seq_scaling_matrix_present_flag*/\n\t\tif (gf_bs_read_int_log(bs, 1, \"seq_scaling_matrix_present_flag\")) {\n\t\t\tu32 k;\n\t\t\tfor (k = 0; k < 8; k++) {\n\t\t\t\tif (gf_bs_read_int_log_idx(bs, 1, \"seq_scaling_list_present_flag\", k)) {\n\t\t\t\t\tu32 z, last = 8, next = 8;\n\t\t\t\t\tu32 sl = k < 6 ? 16 : 64;\n\t\t\t\t\tfor (z = 0; z < sl; z++) {\n\t\t\t\t\t\tif (next) {\n\t\t\t\t\t\t\ts32 delta = gf_bs_read_se(bs);\n\t\t\t\t\t\t\tnext = (last + delta + 256) % 256;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlast = next ? next : last;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\n\tsps->profile_idc = profile_idc;\n\tsps->level_idc = level_idc;\n\tsps->prof_compat = pcomp;\n\tsps->log2_max_frame_num = gf_bs_read_ue_log(bs, \"log2_max_frame_num\") + 4;\n\tsps->poc_type = gf_bs_read_ue_log(bs, \"poc_type\");\n\tsps->chroma_format = chroma_format_idc;\n\tsps->luma_bit_depth_m8 = luma_bd;\n\tsps->chroma_bit_depth_m8 = chroma_bd;\n\n\tif (sps->poc_type == 0) {\n\t\tsps->log2_max_poc_lsb = gf_bs_read_ue_log(bs, \"log2_max_poc_lsb\") + 4;\n\t}\n\telse if (sps->poc_type == 1) {\n\t\tsps->delta_pic_order_always_zero_flag = gf_bs_read_int_log(bs, 1, \"delta_pic_order_always_zero_flag\");\n\t\tsps->offset_for_non_ref_pic = gf_bs_read_se_log(bs, \"offset_for_non_ref_pic\");\n\t\tsps->offset_for_top_to_bottom_field = gf_bs_read_se_log(bs, \"offset_for_top_to_bottom_field\");\n\t\tsps->poc_cycle_length = gf_bs_read_ue_log(bs, \"poc_cycle_length\");\n\t\tif (sps->poc_cycle_length > GF_ARRAY_LENGTH(sps->offset_for_ref_frame)) {\n\t\t\tsps->poc_cycle_length = 255;\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[avc-h264] offset_for_ref_frame overflow from poc_cycle_length\\n\"));\n\t\t\treturn -1;\n\t\t}\n\t\tfor (i = 0; i < sps->poc_cycle_length; i++)\n\t\t\tsps->offset_for_ref_frame[i] = gf_bs_read_se_log_idx(bs, \"offset_for_ref_frame\", i);\n\t}\n\tif (sps->poc_type > 2) {\n\t\treturn -1;\n\t}\n\tsps->max_num_ref_frames = gf_bs_read_ue_log(bs, \"max_num_ref_frames\");\n\tsps->gaps_in_frame_num_value_allowed_flag = gf_bs_read_int_log(bs, 1, \"gaps_in_frame_num_value_allowed_flag\");\n\tmb_width = gf_bs_read_ue_log(bs, \"pic_width_in_mbs_minus1\") + 1;\n\tmb_height = gf_bs_read_ue_log(bs, \"pic_height_in_map_units_minus1\") + 1;\n\n\tsps->frame_mbs_only_flag = gf_bs_read_int_log(bs, 1, \"frame_mbs_only_flag\");\n\n\tsps->width = mb_width * 16;\n\tsps->height = (2 - sps->frame_mbs_only_flag) * mb_height * 16;\n\n\tif (!sps->frame_mbs_only_flag) sps->mb_adaptive_frame_field_flag = gf_bs_read_int_log(bs, 1, \"mb_adaptive_frame_field_flag\");\n\tgf_bs_read_int_log(bs, 1, \"direct_8x8_inference_flag\");\n\n\tif (gf_bs_read_int_log(bs, 1, \"frame_cropping_flag\")) {\n\t\tint CropUnitX, CropUnitY, SubWidthC = -1, SubHeightC = -1;\n\n\t\tif (chroma_format_idc == 1) {\n\t\t\tSubWidthC = 2; SubHeightC = 2;\n\t\t}\n\t\telse if (chroma_format_idc == 2) {\n\t\t\tSubWidthC = 2; SubHeightC = 1;\n\t\t}\n\t\telse if ((chroma_format_idc == 3) && (separate_colour_plane_flag == 0)) {\n\t\t\tSubWidthC = 1; SubHeightC = 1;\n\t\t}\n\n\t\tif (sps->ChromaArrayType == 0) {\n\t\t\tassert(SubWidthC == -1);\n\t\t\tCropUnitX = 1;\n\t\t\tCropUnitY = 2 - sps->frame_mbs_only_flag;\n\t\t}\n\t\telse {\n\t\t\tCropUnitX = SubWidthC;\n\t\t\tCropUnitY = SubHeightC * (2 - sps->frame_mbs_only_flag);\n\t\t}\n\n\t\tcl = gf_bs_read_ue_log(bs, \"frame_crop_left_offset\");\n\t\tcr = gf_bs_read_ue_log(bs, \"frame_crop_right_offset\");\n\t\tct = gf_bs_read_ue_log(bs, \"frame_crop_top_offset\");\n\t\tcb = gf_bs_read_ue_log(bs, \"frame_crop_bottom_offset\");\n\n\t\tsps->width -= CropUnitX * (cl + cr);\n\t\tsps->height -= CropUnitY * (ct + cb);\n\t\tcl *= CropUnitX;\n\t\tcr *= CropUnitX;\n\t\tct *= CropUnitY;\n\t\tcb *= CropUnitY;\n\t}\n\tsps->crop.left = cl;\n\tsps->crop.right = cr;\n\tsps->crop.top = ct;\n\tsps->crop.bottom = cb;\n\n\tif (vui_flag_pos) {\n\t\t*vui_flag_pos = (u32)gf_bs_get_bit_offset(bs);\n\t}\n\t/*vui_parameters_present_flag*/\n\tsps->vui_parameters_present_flag = gf_bs_read_int_log(bs, 1, \"vui_parameters_present_flag\");\n\tif (sps->vui_parameters_present_flag) {\n\t\tsps->vui.aspect_ratio_info_present_flag = gf_bs_read_int_log(bs, 1, \"aspect_ratio_info_present_flag\");\n\t\tif (sps->vui.aspect_ratio_info_present_flag) {\n\t\t\ts32 aspect_ratio_idc = gf_bs_read_int_log(bs, 8, \"aspect_ratio_idc\");\n\t\t\tif (aspect_ratio_idc == 255) {\n\t\t\t\tsps->vui.par_num = gf_bs_read_int_log(bs, 16, \"aspect_ratio_num\");\n\t\t\t\tsps->vui.par_den = gf_bs_read_int_log(bs, 16, \"aspect_ratio_den\");\n\t\t\t}\n\t\t\telse if (aspect_ratio_idc < GF_ARRAY_LENGTH(avc_hevc_sar) ) {\n\t\t\t\tsps->vui.par_num = avc_hevc_sar[aspect_ratio_idc].w;\n\t\t\t\tsps->vui.par_den = avc_hevc_sar[aspect_ratio_idc].h;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[avc-h264] Unknown aspect_ratio_idc: your video may have a wrong aspect ratio. Contact the GPAC team!\\n\"));\n\t\t\t}\n\t\t}\n\t\tsps->vui.overscan_info_present_flag = gf_bs_read_int_log(bs, 1, \"overscan_info_present_flag\");\n\t\tif (sps->vui.overscan_info_present_flag)\n\t\t\tgf_bs_read_int_log(bs, 1, \"overscan_appropriate_flag\");\n\n\t\t/* default values */\n\t\tsps->vui.video_format = 5;\n\t\tsps->vui.colour_primaries = 2;\n\t\tsps->vui.transfer_characteristics = 2;\n\t\tsps->vui.matrix_coefficients = 2;\n\t\t/* now read values if possible */\n\t\tsps->vui.video_signal_type_present_flag = gf_bs_read_int_log(bs, 1, \"video_signal_type_present_flag\");\n\t\tif (sps->vui.video_signal_type_present_flag) {\n\t\t\tsps->vui.video_format = gf_bs_read_int_log(bs, 3, \"video_format\");\n\t\t\tsps->vui.video_full_range_flag = gf_bs_read_int_log(bs, 1, \"video_full_range_flag\");\n\t\t\tsps->vui.colour_description_present_flag = gf_bs_read_int_log(bs, 1, \"colour_description_present_flag\");\n\t\t\tif (sps->vui.colour_description_present_flag) {\n\t\t\t\tsps->vui.colour_primaries = gf_bs_read_int_log(bs, 8, \"colour_primaries\");\n\t\t\t\tsps->vui.transfer_characteristics = gf_bs_read_int_log(bs, 8, \"transfer_characteristics\");\n\t\t\t\tsps->vui.matrix_coefficients = gf_bs_read_int_log(bs, 8, \"matrix_coefficients\");\n\t\t\t}\n\t\t}\n\n\t\tif (gf_bs_read_int_log(bs, 1, \"chroma_location_info_present_flag\")) {\n\t\t\tgf_bs_read_ue_log(bs, \"chroma_sample_location_type_top_field\");\n\t\t\tgf_bs_read_ue_log(bs, \"chroma_sample_location_type_bottom_field\");\n\t\t}\n\n\t\tsps->vui.timing_info_present_flag = gf_bs_read_int_log(bs, 1, \"timing_info_present_flag\");\n\t\tif (sps->vui.timing_info_present_flag) {\n\t\t\tsps->vui.num_units_in_tick = gf_bs_read_int_log(bs, 32, \"num_units_in_tick\");\n\t\t\tsps->vui.time_scale = gf_bs_read_int_log(bs, 32, \"time_scale\");\n\t\t\tsps->vui.fixed_frame_rate_flag = gf_bs_read_int_log(bs, 1, \"fixed_frame_rate_flag\");\n\t\t}\n\n\t\tsps->vui.nal_hrd_parameters_present_flag = gf_bs_read_int_log(bs, 1, \"nal_hrd_parameters_present_flag\");\n\t\tif (sps->vui.nal_hrd_parameters_present_flag)\n\t\t\tif (avc_parse_hrd_parameters(bs, &sps->vui.hrd)<0) return -1;\n\n\t\tsps->vui.vcl_hrd_parameters_present_flag = gf_bs_read_int_log(bs, 1, \"vcl_hrd_parameters_present_flag\");\n\t\tif (sps->vui.vcl_hrd_parameters_present_flag)\n\t\t\tif (avc_parse_hrd_parameters(bs, &sps->vui.hrd)<0) return -1;\n\n\t\tif (sps->vui.nal_hrd_parameters_present_flag || sps->vui.vcl_hrd_parameters_present_flag)\n\t\t\tsps->vui.low_delay_hrd_flag = gf_bs_read_int_log(bs, 1, \"low_delay_hrd_flag\");\n\n\t\tsps->vui.pic_struct_present_flag = gf_bs_read_int_log(bs, 1, \"pic_struct_present_flag\");\n\t}\n\t/*end of seq_parameter_set_data*/\n\n\tif (subseq_sps) {\n\t\tif ((profile_idc == 83) || (profile_idc == 86)) {\n\t\t\tu8 extended_spatial_scalability_idc;\n\t\t\t/*parsing seq_parameter_set_svc_extension*/\n\n\t\t\tgf_bs_read_int_log(bs, 1, \"inter_layer_deblocking_filter_control_present_flag\");\n\t\t\textended_spatial_scalability_idc = gf_bs_read_int_log(bs, 2, \"extended_spatial_scalability_idc\");\n\t\t\tif (sps->ChromaArrayType == 1 || sps->ChromaArrayType == 2) {\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"chroma_phase_x_plus1_flag\");\n\t\t\t}\n\t\t\tif (sps->ChromaArrayType == 1) {\n\t\t\t\tgf_bs_read_int_log(bs, 2, \"chroma_phase_y_plus1\");\n\t\t\t}\n\t\t\tif (extended_spatial_scalability_idc == 1) {\n\t\t\t\tif (sps->ChromaArrayType > 0) {\n\t\t\t\t\tgf_bs_read_int_log(bs, 1, \"seq_ref_layer_chroma_phase_x_plus1_flag\");\n\t\t\t\t\tgf_bs_read_int_log(bs, 2, \"seq_ref_layer_chroma_phase_y_plus1\");\n\t\t\t\t}\n\t\t\t\tgf_bs_read_se_log(bs, \"seq_scaled_ref_layer_left_offset\");\n\t\t\t\tgf_bs_read_se_log(bs, \"seq_scaled_ref_layer_top_offset\");\n\t\t\t\tgf_bs_read_se_log(bs, \"seq_scaled_ref_layer_right_offset\");\n\t\t\t\tgf_bs_read_se_log(bs, \"seq_scaled_ref_layer_bottom_offset\");\n\t\t\t}\n\t\t\tif (gf_bs_read_int_log(bs, 1, \"seq_tcoeff_level_prediction_flag\")) {\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"adaptive_tcoeff_level_prediction_flag\");\n\t\t\t}\n\t\t\tgf_bs_read_int_log(bs, 1, \"slice_header_restriction_flag\");\n\n\t\t\tif (gf_bs_read_int_log(bs, 1, \"svc_vui_parameters_present\")) {\n\t\t\t\tu32 vui_ext_num_entries_minus1 = gf_bs_read_ue_log(bs, \"vui_ext_num_entries_minus1\");\n\n\t\t\t\tfor (i = 0; i <= vui_ext_num_entries_minus1; i++) {\n\t\t\t\t\tu8 vui_ext_nal_hrd_parameters_present_flag, vui_ext_vcl_hrd_parameters_present_flag, vui_ext_timing_info_present_flag;\n\t\t\t\t\tgf_bs_read_int_log(bs, 3, \"vui_ext_dependency_id\");\n\t\t\t\t\tgf_bs_read_int_log(bs, 4, \"vui_ext_quality_id\");\n\t\t\t\t\tgf_bs_read_int_log(bs, 3, \"vui_ext_temporal_id\");\n\t\t\t\t\tvui_ext_timing_info_present_flag = gf_bs_read_int_log(bs, 1, \"vui_ext_timing_info_present_flag\");\n\t\t\t\t\tif (vui_ext_timing_info_present_flag) {\n\t\t\t\t\t\tgf_bs_read_int_log(bs, 32, \"vui_ext_num_units_in_tick\");\n\t\t\t\t\t\tgf_bs_read_int_log(bs, 32, \"vui_ext_time_scale\");\n\t\t\t\t\t\tgf_bs_read_int_log(bs, 1, \"vui_ext_fixed_frame_rate_flag\");\n\t\t\t\t\t}\n\t\t\t\t\tvui_ext_nal_hrd_parameters_present_flag = gf_bs_read_int_log(bs, 1, \"vui_ext_nal_hrd_parameters_present_flag\");\n\t\t\t\t\tif (vui_ext_nal_hrd_parameters_present_flag) {\n\t\t\t\t\t\t//hrd_parameters( )\n\t\t\t\t\t}\n\t\t\t\t\tvui_ext_vcl_hrd_parameters_present_flag = gf_bs_read_int_log(bs, 1, \"vui_ext_vcl_hrd_parameters_present_flag\");\n\t\t\t\t\tif (vui_ext_vcl_hrd_parameters_present_flag) {\n\t\t\t\t\t\t//hrd_parameters( )\n\t\t\t\t\t}\n\t\t\t\t\tif (vui_ext_nal_hrd_parameters_present_flag || vui_ext_vcl_hrd_parameters_present_flag) {\n\t\t\t\t\t\tgf_bs_read_int_log(bs, 1, \"vui_ext_low_delay_hrd_flag\");\n\t\t\t\t\t}\n\t\t\t\t\tgf_bs_read_int_log(bs, 1, \"vui_ext_pic_struct_present_flag\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if ((profile_idc == 118) || (profile_idc == 128)) {\n\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CODING, (\"[avc-h264] MVC parsing not implemented - skipping parsing end of Subset SPS\\n\"));\n\t\t\treturn sps_id;\n\t\t}\n\n\t\tif (gf_bs_read_int_log(bs, 1, \"additional_extension2\")) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[avc-h264] skipping parsing end of Subset SPS (additional_extension2)\\n\"));\n\t\t\treturn sps_id;\n\t\t}\n\t}\n\treturn sps_id;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'fixed #2067'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int fill_thread_core_info(struct elf_thread_core_info *t,\n\t\t\t\t const struct user_regset_view *view,\n\t\t\t\t long signr, size_t *total)\n{\n\tunsigned int i;\n\n\t/*\n\t * NT_PRSTATUS is the one special case, because the regset data\n\t * goes into the pr_reg field inside the note contents, rather\n\t * than being the whole note contents. We fill the reset in here.\n\t * We assume that regset 0 is NT_PRSTATUS.\n\t */\n\tfill_prstatus(&t->prstatus, t->task, signr);\n\t(void) view->regsets[0].get(t->task, &view->regsets[0],\n\t\t\t\t 0, sizeof(t->prstatus.pr_reg),\n\t\t\t\t &t->prstatus.pr_reg, NULL);\n\n\tfill_note(&t->notes[0], \"CORE\", NT_PRSTATUS,\n\t\t sizeof(t->prstatus), &t->prstatus);\n\t*total += notesize(&t->notes[0]);\n\n\tdo_thread_regset_writeback(t->task, &view->regsets[0]);\n\n\t/*\n\t * Each other regset might generate a note too. For each regset\n\t * that has no core_note_type or is inactive, we leave t->notes[i]\n\t * all zero and we'll know to skip writing it later.\n\t */\n\tfor (i = 1; i < view->n; ++i) {\n\t\tconst struct user_regset *regset = &view->regsets[i];\n\t\tdo_thread_regset_writeback(t->task, regset);\n\t\tif (regset->core_note_type &&\n\t\t (!regset->active || regset->active(t->task, regset))) {\n\t\t\tint ret;\n\t\t\tsize_t size = regset->n * regset->size;\n\t\t\tvoid *data = kmalloc(size, GFP_KERNEL);\n\t\t\tif (unlikely(!data))\n\t\t\t\treturn 0;\n\t\t\tret = regset->get(t->task, regset,\n\t\t\t\t\t 0, size, data, NULL);\n\t\t\tif (unlikely(ret))\n\t\t\t\tkfree(data);\n\t\t\telse {\n\t\t\t\tif (regset->core_note_type != NT_PRFPREG)\n\t\t\t\t\tfill_note(&t->notes[i], \"LINUX\",\n\t\t\t\t\t\t regset->core_note_type,\n\t\t\t\t\t\t size, data);\n\t\t\t\telse {\n\t\t\t\t\tt->prstatus.pr_fpvalid = 1;\n\t\t\t\t\tfill_note(&t->notes[i], \"CORE\",\n\t\t\t\t\t\t NT_PRFPREG, size, data);\n\t\t\t\t}\n\t\t\t\t*total += notesize(&t->notes[i]);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 1;\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_interpreter(njs_vm_t *vm, u_char *pc, void *promise_cap,\n void *async_ctx)\n{\n u_char *catch;\n double num, exponent;\n int32_t i32;\n uint32_t u32;\n njs_str_t string;\n njs_uint_t hint;\n njs_bool_t valid, lambda_call;\n njs_value_t *retval, *value1, *value2;\n njs_value_t *src, *s1, *s2, dst;\n njs_value_t *function, name;\n njs_value_t numeric1, numeric2, primitive1, primitive2;\n njs_frame_t *frame;\n njs_jump_off_t ret;\n njs_vmcode_await_t *await;\n njs_native_frame_t *previous, *native;\n njs_property_next_t *next;\n njs_vmcode_import_t *import;\n njs_vmcode_finally_t *finally;\n njs_vmcode_generic_t *vmcode;\n njs_vmcode_variable_t *var;\n njs_vmcode_move_arg_t *move_arg;\n njs_vmcode_prop_get_t *get;\n njs_vmcode_prop_set_t *set;\n njs_vmcode_operation_t op;\n njs_vmcode_prop_next_t *pnext;\n njs_vmcode_test_jump_t *test_jump;\n njs_vmcode_equal_jump_t *equal;\n njs_vmcode_try_return_t *try_return;\n njs_vmcode_method_frame_t *method_frame;\n njs_vmcode_function_copy_t *fcopy;\n njs_vmcode_prop_accessor_t *accessor;\n njs_vmcode_try_trampoline_t *try_trampoline;\n njs_vmcode_function_frame_t *function_frame;\n\n njs_vmcode_debug(vm, pc, \"ENTER\");\n\nnext:\n\n for ( ;; ) {\n\n vmcode = (njs_vmcode_generic_t *) pc;\n\n /*\n * The first operand is passed as is in value2 to\n * NJS_VMCODE_JUMP,\n * NJS_VMCODE_IF_TRUE_JUMP,\n * NJS_VMCODE_IF_FALSE_JUMP,\n * NJS_VMCODE_FUNCTION_FRAME,\n * NJS_VMCODE_FUNCTION_CALL,\n * NJS_VMCODE_RETURN,\n * NJS_VMCODE_TRY_START,\n * NJS_VMCODE_TRY_CONTINUE,\n * NJS_VMCODE_TRY_BREAK,\n * NJS_VMCODE_TRY_END,\n * NJS_VMCODE_CATCH,\n * NJS_VMCODE_THROW,\n * NJS_VMCODE_STOP.\n */\n value2 = (njs_value_t *) vmcode->operand1;\n value1 = NULL;\n\n switch (vmcode->code.operands) {\n\n case NJS_VMCODE_3OPERANDS:\n njs_vmcode_operand(vm, vmcode->operand3, value2);\n\n /* Fall through. */\n\n case NJS_VMCODE_2OPERANDS:\n njs_vmcode_operand(vm, vmcode->operand2, value1);\n }\n\n op = vmcode->code.operation;\n\n /*\n * On success an operation returns size of the bytecode,\n * a jump offset or zero after the call or return operations.\n * Jumps can return a negative offset. Compilers can generate\n * (ret < 0 && ret >= NJS_PREEMPT)\n * as a single unsigned comparision.\n */\n\n#ifdef NJS_OPCODE_DEBUG\n njs_disassemble(pc, NULL, 1, NULL);\n#endif\n\n if (op > NJS_VMCODE_NORET) {\n\n if (op == NJS_VMCODE_MOVE) {\n njs_vmcode_operand(vm, vmcode->operand1, retval);\n *retval = *value1;\n\n pc += sizeof(njs_vmcode_move_t);\n goto next;\n }\n\n if (op == NJS_VMCODE_PROPERTY_GET) {\n get = (njs_vmcode_prop_get_t *) pc;\n njs_vmcode_operand(vm, get->value, retval);\n\n ret = njs_value_property(vm, value1, value2, retval);\n if (njs_slow_path(ret == NJS_ERROR)) {\n goto error;\n }\n\n pc += sizeof(njs_vmcode_prop_get_t);\n goto next;\n }\n\n switch (op) {\n case NJS_VMCODE_INCREMENT:\n case NJS_VMCODE_POST_INCREMENT:\n case NJS_VMCODE_DECREMENT:\n case NJS_VMCODE_POST_DECREMENT:\n if (njs_slow_path(!njs_is_numeric(value2))) {\n ret = njs_value_to_numeric(vm, value2, &numeric1);\n if (njs_slow_path(ret != NJS_OK)) {\n goto error;\n }\n\n num = njs_number(&numeric1);\n\n } else {\n num = njs_number(value2);\n }\n\n njs_set_number(value1,\n num + (1 - 2 * ((op - NJS_VMCODE_INCREMENT) >> 1)));\n\n njs_vmcode_operand(vm, vmcode->operand1, retval);\n\n if (op & 1) {\n njs_set_number(retval, num);\n\n } else {\n *retval = *value1;\n }\n\n pc += sizeof(njs_vmcode_3addr_t);\n goto next;\n\n case NJS_VMCODE_GLOBAL_GET:\n get = (njs_vmcode_prop_get_t *) pc;\n njs_vmcode_operand(vm, get->value, retval);\n\n ret = njs_value_property(vm, value1, value2, retval);\n if (njs_slow_path(ret == NJS_ERROR)) {\n goto error;\n }\n\n pc += sizeof(njs_vmcode_prop_get_t);\n\n if (ret == NJS_OK) {\n pc += sizeof(njs_vmcode_error_t);\n }\n\n goto next;\n\n /*\n * njs_vmcode_try_return() saves a return value to use it later by\n * njs_vmcode_finally(), and jumps to the nearest try_break block.\n */\n case NJS_VMCODE_TRY_RETURN:\n njs_vmcode_operand(vm, vmcode->operand1, retval);\n *retval = *value1;\n\n try_return = (njs_vmcode_try_return_t *) pc;\n pc += try_return->offset;\n goto next;\n\n case NJS_VMCODE_LESS:\n case NJS_VMCODE_GREATER:\n case NJS_VMCODE_LESS_OR_EQUAL:\n case NJS_VMCODE_GREATER_OR_EQUAL:\n case NJS_VMCODE_ADDITION:\n if (njs_slow_path(!njs_is_primitive(value1))) {\n hint = (op == NJS_VMCODE_ADDITION) && njs_is_date(value1);\n ret = njs_value_to_primitive(vm, &primitive1, value1, hint);\n if (ret != NJS_OK) {\n goto error;\n }\n\n value1 = &primitive1;\n }\n\n if (njs_slow_path(!njs_is_primitive(value2))) {\n hint = (op == NJS_VMCODE_ADDITION) && njs_is_date(value2);\n ret = njs_value_to_primitive(vm, &primitive2, value2, hint);\n if (ret != NJS_OK) {\n goto error;\n }\n\n value2 = &primitive2;\n }\n\n if (njs_slow_path(njs_is_symbol(value1)\n || njs_is_symbol(value2)))\n {\n njs_symbol_conversion_failed(vm,\n (op == NJS_VMCODE_ADDITION) &&\n (njs_is_string(value1) || njs_is_string(value2)));\n\n goto error;\n }\n\n njs_vmcode_operand(vm, vmcode->operand1, retval);\n\n if (op == NJS_VMCODE_ADDITION) {\n if (njs_fast_path(njs_is_numeric(value1)\n && njs_is_numeric(value2)))\n {\n njs_set_number(retval, njs_number(value1)\n + njs_number(value2));\n pc += sizeof(njs_vmcode_3addr_t);\n goto next;\n }\n\n if (njs_is_string(value1)) {\n s1 = value1;\n s2 = &dst;\n src = value2;\n\n } else {\n s1 = &dst;\n s2 = value2;\n src = value1;\n }\n\n ret = njs_primitive_value_to_string(vm, &dst, src);\n if (njs_slow_path(ret != NJS_OK)) {\n goto error;\n }\n\n ret = njs_string_concat(vm, s1, s2);\n if (njs_slow_path(ret == NJS_ERROR)) {\n goto error;\n }\n\n *retval = vm->retval;\n\n pc += ret;\n goto next;\n }\n\n if ((uint8_t) (op - NJS_VMCODE_GREATER) < 2) {\n /* NJS_VMCODE_GREATER, NJS_VMCODE_LESS_OR_EQUAL */\n src = value1;\n value1 = value2;\n value2 = src;\n }\n\n ret = njs_primitive_values_compare(vm, value1, value2);\n\n if (op < NJS_VMCODE_LESS_OR_EQUAL) {\n ret = ret > 0;\n\n } else {\n ret = ret == 0;\n }\n\n njs_set_boolean(retval, ret);\n\n pc += sizeof(njs_vmcode_3addr_t);\n goto next;\n\n case NJS_VMCODE_EQUAL:\n case NJS_VMCODE_NOT_EQUAL:\n ret = njs_values_equal(vm, value1, value2);\n if (njs_slow_path(ret < 0)) {\n goto error;\n }\n\n ret ^= op - NJS_VMCODE_EQUAL;\n\n njs_vmcode_operand(vm, vmcode->operand1, retval);\n njs_set_boolean(retval, ret);\n\n pc += sizeof(njs_vmcode_3addr_t);\n goto next;\n\n case NJS_VMCODE_SUBSTRACTION:\n case NJS_VMCODE_MULTIPLICATION:\n case NJS_VMCODE_EXPONENTIATION:\n case NJS_VMCODE_DIVISION:\n case NJS_VMCODE_REMAINDER:\n case NJS_VMCODE_BITWISE_AND:\n case NJS_VMCODE_BITWISE_OR:\n case NJS_VMCODE_BITWISE_XOR:\n case NJS_VMCODE_LEFT_SHIFT:\n case NJS_VMCODE_RIGHT_SHIFT:\n case NJS_VMCODE_UNSIGNED_RIGHT_SHIFT:\n if (njs_slow_path(!njs_is_numeric(value1))) {\n ret = njs_value_to_numeric(vm, value1, &numeric1);\n if (njs_slow_path(ret != NJS_OK)) {\n goto error;\n }\n\n value1 = &numeric1;\n }\n\n if (njs_slow_path(!njs_is_numeric(value2))) {\n ret = njs_value_to_numeric(vm, value2, &numeric2);\n if (njs_slow_path(ret != NJS_OK)) {\n goto error;\n }\n\n value2 = &numeric2;\n }\n\n num = njs_number(value1);\n\n njs_vmcode_operand(vm, vmcode->operand1, retval);\n pc += sizeof(njs_vmcode_3addr_t);\n\n switch (op) {\n case NJS_VMCODE_SUBSTRACTION:\n num -= njs_number(value2);\n break;\n\n case NJS_VMCODE_MULTIPLICATION:\n num *= njs_number(value2);\n break;\n\n case NJS_VMCODE_EXPONENTIATION:\n exponent = njs_number(value2);\n\n /*\n * According to ES7:\n * 1. If exponent is NaN, the result should be NaN;\n * 2. The result of +/-1 ** +/-Infinity should be NaN.\n */\n valid = njs_expect(1, fabs(num) != 1\n || (!isnan(exponent)\n && !isinf(exponent)));\n\n num = valid ? pow(num, exponent) : NAN;\n break;\n\n case NJS_VMCODE_DIVISION:\n num /= njs_number(value2);\n break;\n\n case NJS_VMCODE_REMAINDER:\n num = fmod(num, njs_number(value2));\n break;\n\n case NJS_VMCODE_BITWISE_AND:\n case NJS_VMCODE_BITWISE_OR:\n case NJS_VMCODE_BITWISE_XOR:\n i32 = njs_number_to_int32(njs_number(value2));\n\n switch (op) {\n case NJS_VMCODE_BITWISE_AND:\n i32 &= njs_number_to_int32(num);\n break;\n\n case NJS_VMCODE_BITWISE_OR:\n i32 |= njs_number_to_int32(num);\n break;\n\n case NJS_VMCODE_BITWISE_XOR:\n i32 ^= njs_number_to_int32(num);\n break;\n }\n\n njs_set_int32(retval, i32);\n goto next;\n\n default:\n u32 = njs_number_to_uint32(njs_number(value2)) & 0x1f;\n\n switch (op) {\n case NJS_VMCODE_LEFT_SHIFT:\n case NJS_VMCODE_RIGHT_SHIFT:\n i32 = njs_number_to_int32(num);\n\n if (op == NJS_VMCODE_LEFT_SHIFT) {\n /* Shifting of negative numbers is undefined. */\n i32 = (uint32_t) i32 << u32;\n } else {\n i32 >>= u32;\n }\n\n njs_set_int32(retval, i32);\n break;\n\n default: /* NJS_VMCODE_UNSIGNED_RIGHT_SHIFT */\n njs_set_uint32(retval,\n njs_number_to_uint32(num) >> u32);\n }\n\n goto next;\n }\n\n njs_set_number(retval, num);\n goto next;\n\n case NJS_VMCODE_OBJECT_COPY:\n ret = njs_vmcode_object_copy(vm, value1, value2);\n break;\n\n case NJS_VMCODE_TEMPLATE_LITERAL:\n ret = njs_vmcode_template_literal(vm, value1, value2);\n break;\n\n case NJS_VMCODE_PROPERTY_IN:\n ret = njs_vmcode_property_in(vm, value1, value2);\n break;\n\n case NJS_VMCODE_PROPERTY_DELETE:\n ret = njs_value_property_delete(vm, value1, value2, NULL, 1);\n if (njs_fast_path(ret != NJS_ERROR)) {\n vm->retval = njs_value_true;\n\n ret = sizeof(njs_vmcode_3addr_t);\n }\n\n break;\n\n case NJS_VMCODE_PROPERTY_FOREACH:\n ret = njs_vmcode_property_foreach(vm, value1, value2, pc);\n break;\n\n case NJS_VMCODE_STRICT_EQUAL:\n case NJS_VMCODE_STRICT_NOT_EQUAL:\n ret = njs_values_strict_equal(value1, value2);\n\n ret ^= op - NJS_VMCODE_STRICT_EQUAL;\n\n njs_vmcode_operand(vm, vmcode->operand1, retval);\n njs_set_boolean(retval, ret);\n\n pc += sizeof(njs_vmcode_3addr_t);\n goto next;\n\n case NJS_VMCODE_TEST_IF_TRUE:\n case NJS_VMCODE_TEST_IF_FALSE:\n case NJS_VMCODE_COALESCE:\n if (op == NJS_VMCODE_COALESCE) {\n ret = !njs_is_null_or_undefined(value1);\n\n } else {\n ret = njs_is_true(value1);\n ret ^= op - NJS_VMCODE_TEST_IF_TRUE;\n }\n\n if (ret) {\n test_jump = (njs_vmcode_test_jump_t *) pc;\n ret = test_jump->offset;\n\n } else {\n ret = sizeof(njs_vmcode_3addr_t);\n }\n\n njs_vmcode_operand(vm, vmcode->operand1, retval);\n *retval = *value1;\n\n pc += ret;\n goto next;\n\n case NJS_VMCODE_UNARY_PLUS:\n case NJS_VMCODE_UNARY_NEGATION:\n case NJS_VMCODE_BITWISE_NOT:\n if (njs_slow_path(!njs_is_numeric(value1))) {\n ret = njs_value_to_numeric(vm, value1, &numeric1);\n if (njs_slow_path(ret != NJS_OK)) {\n goto error;\n }\n\n value1 = &numeric1;\n }\n\n num = njs_number(value1);\n njs_vmcode_operand(vm, vmcode->operand1, retval);\n\n switch (op) {\n case NJS_VMCODE_UNARY_NEGATION:\n num = -num;\n\n /* Fall through. */\n case NJS_VMCODE_UNARY_PLUS:\n njs_set_number(retval, num);\n break;\n\n case NJS_VMCODE_BITWISE_NOT:\n njs_set_int32(retval, ~njs_number_to_uint32(num));\n }\n\n pc += sizeof(njs_vmcode_2addr_t);\n goto next;\n\n case NJS_VMCODE_LOGICAL_NOT:\n njs_vmcode_operand(vm, vmcode->operand1, retval);\n njs_set_boolean(retval, !njs_is_true(value1));\n\n pc += sizeof(njs_vmcode_2addr_t);\n goto next;\n\n case NJS_VMCODE_OBJECT:\n ret = njs_vmcode_object(vm);\n break;\n\n case NJS_VMCODE_ARRAY:\n ret = njs_vmcode_array(vm, pc);\n break;\n\n case NJS_VMCODE_FUNCTION:\n ret = njs_vmcode_function(vm, pc);\n break;\n\n case NJS_VMCODE_REGEXP:\n ret = njs_vmcode_regexp(vm, pc);\n break;\n\n case NJS_VMCODE_INSTANCE_OF:\n ret = njs_vmcode_instance_of(vm, value1, value2);\n break;\n\n case NJS_VMCODE_TYPEOF:\n ret = njs_vmcode_typeof(vm, value1, value2);\n break;\n\n case NJS_VMCODE_VOID:\n njs_set_undefined(&vm->retval);\n\n ret = sizeof(njs_vmcode_2addr_t);\n break;\n\n case NJS_VMCODE_DELETE:\n njs_release(vm, value1);\n vm->retval = njs_value_true;\n\n ret = sizeof(njs_vmcode_2addr_t);\n break;\n\n case NJS_VMCODE_DEBUGGER:\n ret = njs_vmcode_debugger(vm);\n break;\n\n default:\n njs_internal_error(vm, \"%d has retval\", op);\n goto error;\n }\n\n if (njs_slow_path(ret < 0 && ret >= NJS_PREEMPT)) {\n break;\n }\n\n njs_vmcode_operand(vm, vmcode->operand1, retval);\n njs_release(vm, retval);\n *retval = vm->retval;\n\n } else {\n\n switch (op) {\n case NJS_VMCODE_MOVE_ARG:\n move_arg = (njs_vmcode_move_arg_t *) pc;\n native = vm->top_frame;\n\n hint = move_arg->dst;\n\n value1 = &native->arguments_offset[hint];\n njs_vmcode_operand(vm, move_arg->src, value2);\n\n *value1 = *value2;\n\n ret = sizeof(njs_vmcode_move_arg_t);\n break;\n\n case NJS_VMCODE_STOP:\n njs_vmcode_operand(vm, (njs_index_t) value2, value2);\n vm->retval = *value2;\n\n njs_vmcode_debug(vm, pc, \"EXIT STOP\");\n\n return NJS_OK;\n\n case NJS_VMCODE_JUMP:\n ret = (njs_jump_off_t) value2;\n break;\n\n case NJS_VMCODE_PROPERTY_SET:\n set = (njs_vmcode_prop_set_t *) pc;\n njs_vmcode_operand(vm, set->value, retval);\n\n ret = njs_value_property_set(vm, value1, value2, retval);\n if (njs_slow_path(ret == NJS_ERROR)) {\n goto error;\n }\n\n ret = sizeof(njs_vmcode_prop_set_t);\n break;\n\n case NJS_VMCODE_PROPERTY_ACCESSOR:\n accessor = (njs_vmcode_prop_accessor_t *) pc;\n njs_vmcode_operand(vm, accessor->value, function);\n\n ret = njs_value_to_key(vm, &name, value2);\n if (njs_slow_path(ret != NJS_OK)) {\n njs_internal_error(vm, \"failed conversion of type \\\"%s\\\" \"\n \"to string while property define\",\n njs_type_string(value2->type));\n goto error;\n }\n\n ret = njs_object_prop_define(vm, value1, &name, function,\n accessor->type);\n if (njs_slow_path(ret != NJS_OK)) {\n goto error;\n }\n\n ret = sizeof(njs_vmcode_prop_accessor_t);\n break;\n\n case NJS_VMCODE_IF_TRUE_JUMP:\n case NJS_VMCODE_IF_FALSE_JUMP:\n ret = njs_is_true(value1);\n\n ret ^= op - NJS_VMCODE_IF_TRUE_JUMP;\n\n ret = ret ? (njs_jump_off_t) value2\n : (njs_jump_off_t) sizeof(njs_vmcode_cond_jump_t);\n\n break;\n\n case NJS_VMCODE_IF_EQUAL_JUMP:\n if (njs_values_strict_equal(value1, value2)) {\n equal = (njs_vmcode_equal_jump_t *) pc;\n ret = equal->offset;\n\n } else {\n ret = sizeof(njs_vmcode_3addr_t);\n }\n\n break;\n\n case NJS_VMCODE_PROPERTY_INIT:\n set = (njs_vmcode_prop_set_t *) pc;\n njs_vmcode_operand(vm, set->value, retval);\n ret = njs_vmcode_property_init(vm, value1, value2, retval);\n if (njs_slow_path(ret == NJS_ERROR)) {\n goto error;\n }\n\n break;\n\n case NJS_VMCODE_RETURN:\n njs_vmcode_operand(vm, (njs_index_t) value2, value2);\n\n njs_vmcode_debug(vm, pc, \"EXIT RETURN\");\n\n return njs_vmcode_return(vm, NULL, value2);\n\n case NJS_VMCODE_FUNCTION_COPY:\n fcopy = (njs_vmcode_function_copy_t *) pc;\n ret = njs_vmcode_function_copy(vm, fcopy->function,\n fcopy->retval);\n break;\n\n case NJS_VMCODE_FUNCTION_FRAME:\n function_frame = (njs_vmcode_function_frame_t *) pc;\n\n /* TODO: external object instead of void this. */\n\n ret = njs_function_frame_create(vm, value1,\n &njs_value_undefined,\n (uintptr_t) value2,\n function_frame->ctor);\n\n if (njs_slow_path(ret != NJS_OK)) {\n goto error;\n }\n\n ret = sizeof(njs_vmcode_function_frame_t);\n break;\n\n case NJS_VMCODE_METHOD_FRAME:\n method_frame = (njs_vmcode_method_frame_t *) pc;\n\n ret = njs_value_property(vm, value1, value2, &dst);\n if (njs_slow_path(ret == NJS_ERROR)) {\n goto error;\n }\n\n if (njs_slow_path(!njs_is_function(&dst))) {\n ret = njs_value_to_key(vm, &dst, value2);\n if (njs_slow_path(ret != NJS_OK)) {\n goto error;\n }\n\n njs_key_string_get(vm, &dst, &string);\n njs_type_error(vm,\n \"(intermediate value)[\\\"%V\\\"] is not a function\",\n &string);\n goto error;\n }\n\n ret = njs_function_frame_create(vm, &dst, value1,\n method_frame->nargs,\n method_frame->ctor);\n\n if (njs_slow_path(ret != NJS_OK)) {\n goto error;\n }\n\n ret = sizeof(njs_vmcode_method_frame_t);\n break;\n\n case NJS_VMCODE_FUNCTION_CALL:\n vm->active_frame->native.pc = pc;\n\n njs_vmcode_operand(vm, (njs_index_t) value2, value2);\n\n ret = njs_function_frame_invoke(vm, value2);\n if (njs_slow_path(ret == NJS_ERROR)) {\n goto error;\n }\n\n njs_vmcode_debug(vm, pc, \"RESUME\");\n\n ret = sizeof(njs_vmcode_function_call_t);\n break;\n\n case NJS_VMCODE_PROPERTY_NEXT:\n pnext = (njs_vmcode_prop_next_t *) pc;\n retval = njs_scope_value(vm, pnext->retval);\n\n njs_assert(njs_is_data(value2, NJS_DATA_TAG_FOREACH_NEXT));\n next = njs_data(value2);\n\n if (next->index < next->array->length) {\n *retval = next->array->start[next->index++];\n\n ret = pnext->offset;\n break;\n }\n\n njs_mp_free(vm->mem_pool, next);\n\n ret = sizeof(njs_vmcode_prop_next_t);\n break;\n\n case NJS_VMCODE_ARGUMENTS:\n ret = njs_vmcode_arguments(vm, pc);\n if (njs_slow_path(ret == NJS_ERROR)) {\n goto error;\n }\n\n break;\n\n case NJS_VMCODE_PROTO_INIT:\n set = (njs_vmcode_prop_set_t *) pc;\n njs_vmcode_operand(vm, set->value, retval);\n ret = njs_vmcode_proto_init(vm, value1, value2, retval);\n if (njs_slow_path(ret == NJS_ERROR)) {\n goto error;\n }\n\n break;\n\n case NJS_VMCODE_IMPORT:\n import = (njs_vmcode_import_t *) pc;\n retval = njs_scope_value(vm, import->retval);\n ret = njs_vmcode_import(vm, import->module, retval);\n if (njs_slow_path(ret == NJS_ERROR)) {\n goto error;\n }\n\n break;\n\n case NJS_VMCODE_AWAIT:\n await = (njs_vmcode_await_t *) pc;\n\n njs_vmcode_debug(vm, pc, \"EXIT AWAIT\");\n\n return njs_vmcode_await(vm, await, promise_cap, async_ctx);\n\n case NJS_VMCODE_TRY_START:\n ret = njs_vmcode_try_start(vm, value1, value2, pc);\n if (njs_slow_path(ret == NJS_ERROR)) {\n goto error;\n }\n\n break;\n\n case NJS_VMCODE_THROW:\n njs_vmcode_operand(vm, (njs_index_t) value2, value2);\n vm->retval = *value2;\n goto error;\n\n case NJS_VMCODE_TRY_BREAK:\n try_trampoline = (njs_vmcode_try_trampoline_t *) pc;\n value1 = njs_scope_value(vm, try_trampoline->exit_value);\n\n ret = njs_vmcode_try_break(vm, value1, value2);\n break;\n\n case NJS_VMCODE_TRY_CONTINUE:\n try_trampoline = (njs_vmcode_try_trampoline_t *) pc;\n value1 = njs_scope_value(vm, try_trampoline->exit_value);\n\n ret = njs_vmcode_try_continue(vm, value1, value2);\n break;\n\n case NJS_VMCODE_TRY_END:\n ret = njs_vmcode_try_end(vm, value1, value2);\n break;\n\n /*\n * njs_vmcode_catch() is set on the start of a \"catch\" block to\n * store exception and to remove a \"try\" block if there is no\n * \"finally\" block or to update a catch address to the start of\n * a \"finally\" block.\n * njs_vmcode_catch() is set on the start of a \"finally\" block\n * to store uncaught exception and to remove a \"try\" block.\n */\n case NJS_VMCODE_CATCH:\n *value1 = vm->retval;\n\n if ((njs_jump_off_t) value2 == sizeof(njs_vmcode_catch_t)) {\n ret = njs_vmcode_try_end(vm, value1, value2);\n\n } else {\n frame = (njs_frame_t *) vm->top_frame;\n frame->exception.catch = pc + (njs_jump_off_t) value2;\n ret = sizeof(njs_vmcode_catch_t);\n }\n\n break;\n\n case NJS_VMCODE_FINALLY:\n finally = (njs_vmcode_finally_t *) pc;\n value1 = njs_scope_value(vm, finally->exit_value);\n\n ret = njs_vmcode_finally(vm, value1, value2, pc);\n\n switch (ret) {\n case NJS_OK:\n\n njs_vmcode_debug(vm, pc, \"EXIT FINALLY\");\n\n return NJS_OK;\n case NJS_ERROR:\n goto error;\n }\n\n break;\n\n case NJS_VMCODE_LET:\n var = (njs_vmcode_variable_t *) pc;\n value1 = njs_scope_value(vm, var->dst);\n\n if (njs_is_valid(value1)) {\n value1 = njs_mp_alloc(vm->mem_pool, sizeof(njs_value_t));\n if (njs_slow_path(value1 == NULL)) {\n njs_memory_error(vm);\n goto error;\n }\n\n njs_scope_value_set(vm, var->dst, value1);\n }\n\n njs_set_undefined(value1);\n\n ret = sizeof(njs_vmcode_variable_t);\n break;\n\n case NJS_VMCODE_LET_UPDATE:\n var = (njs_vmcode_variable_t *) pc;\n value2 = njs_scope_value(vm, var->dst);\n\n value1 = njs_mp_alloc(vm->mem_pool, sizeof(njs_value_t));\n if (njs_slow_path(value1 == NULL)) {\n njs_memory_error(vm);\n goto error;\n }\n\n *value1 = *value2;\n\n njs_scope_value_set(vm, var->dst, value1);\n\n ret = sizeof(njs_vmcode_variable_t);\n break;\n\n case NJS_VMCODE_INITIALIZATION_TEST:\n var = (njs_vmcode_variable_t *) pc;\n value1 = njs_scope_value(vm, var->dst);\n\n if (njs_is_valid(value1)) {\n ret = sizeof(njs_vmcode_variable_t);\n break;\n }\n\n /* Fall through. */\n\n case NJS_VMCODE_NOT_INITIALIZED:\n njs_reference_error(vm, \"cannot access variable \"\n \"before initialization\");\n goto error;\n\n case NJS_VMCODE_ERROR:\n njs_vmcode_error(vm, pc);\n goto error;\n\n case NJS_VMCODE_ASSIGNMENT_ERROR:\n njs_type_error(vm, \"assignment to constant variable\");\n goto error;\n\n default:\n njs_internal_error(vm, \"%d has NO retval\", op);\n goto error;\n }\n }\n\n pc += ret;\n }\n\nerror:\n\n if (njs_is_error(&vm->retval)) {\n vm->active_frame->native.pc = pc;\n (void) njs_error_stack_attach(vm, &vm->retval);\n }\n\n for ( ;; ) {\n native = vm->top_frame;\n\n if (!native->native) {\n frame = (njs_frame_t *) native;\n catch = frame->exception.catch;\n\n if (catch != NULL) {\n pc = catch;\n\n goto next;\n }\n }\n\n previous = native->previous;\n if (previous == NULL) {\n break;\n }\n\n lambda_call = (native == &vm->active_frame->native);\n\n njs_vm_scopes_restore(vm, native, previous);\n\n if (native->size != 0) {\n vm->stack_size -= native->size;\n njs_mp_free(vm->mem_pool, native);\n }\n\n if (lambda_call) {\n break;\n }\n }\n\n njs_vmcode_debug(vm, pc, \"EXIT ERROR\");\n\n return NJS_ERROR;\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: void do_write_general()\n {\n if (res.body.length() < res_stream_threshold_)\n {\n res_body_copy_.swap(res.body);\n buffers_.emplace_back(res_body_copy_.data(), res_body_copy_.size());\n\n do_write();\n\n if (need_to_start_read_after_complete_)\n {\n need_to_start_read_after_complete_ = false;\n start_deadline();\n do_read();\n }\n }\n else\n {\n is_writing = true;\n asio::write(adaptor_.socket(), buffers_); // Write the response start / headers\n cancel_deadline_timer();\n if (res.body.length() > 0)\n {\n std::string buf;\n std::vector buffers;\n\n while (res.body.length() > 16384)\n {\n //buf.reserve(16385);\n buf = res.body.substr(0, 16384);\n res.body = res.body.substr(16384);\n buffers.clear();\n buffers.push_back(asio::buffer(buf));\n do_write_sync(buffers);\n }\n // Collect whatever is left (less than 16KB) and send it down the socket\n // buf.reserve(is.length());\n buf = res.body;\n res.body.clear();\n\n buffers.clear();\n buffers.push_back(asio::buffer(buf));\n do_write_sync(buffers);\n }\n is_writing = false;\n if (close_connection_)\n {\n adaptor_.shutdown_readwrite();\n adaptor_.close();\n CROW_LOG_DEBUG << this << \" from write (res_stream)\";\n check_destroy();\n }\n\n res.end();\n res.clear();\n buffers_.clear();\n }\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: s32 gf_media_avc_read_sps(const char *sps_data, u32 sps_size, AVCState *avc, u32 subseq_sps, u32 *vui_flag_pos)\n{\n\tAVC_SPS *sps;\n\tu32 ChromaArrayType = 0;\n\ts32 mb_width, mb_height, sps_id = -1;\n\tu32 profile_idc, level_idc, pcomp, i, chroma_format_idc, cl=0, cr=0, ct=0, cb=0, luma_bd, chroma_bd;\n\tu8 separate_colour_plane_flag = 0;\n\tGF_BitStream *bs;\n\tchar *sps_data_without_emulation_bytes = NULL;\n\tu32 sps_data_without_emulation_bytes_size = 0;\n\n\t/*SPS still contains emulation bytes*/\n\tsps_data_without_emulation_bytes = gf_malloc(sps_size*sizeof(char));\n\tsps_data_without_emulation_bytes_size = avc_remove_emulation_bytes(sps_data, sps_data_without_emulation_bytes, sps_size);\n\tbs = gf_bs_new(sps_data_without_emulation_bytes, sps_data_without_emulation_bytes_size, GF_BITSTREAM_READ);\n\tif (!bs) {\n\t\tsps_id = -1;\n\t\tgoto exit;\n\t}\n\tif (vui_flag_pos) *vui_flag_pos = 0;\n\n\t/*nal hdr*/ gf_bs_read_int(bs, 8);\n\n\tprofile_idc = gf_bs_read_int(bs, 8);\n\n\tpcomp = gf_bs_read_int(bs, 8);\n\t/*sanity checks*/\n\tif (pcomp & 0x3)\n\t\tgoto exit;\n\n\tlevel_idc = gf_bs_read_int(bs, 8);\n\n\t/*SubsetSps is used to be sure that AVC SPS are not going to be scratched\n\tby subset SPS. According to the SVC standard, subset SPS can have the same sps_id\n\tthan its base layer, but it does not refer to the same SPS. */\n\tsps_id = bs_get_ue(bs) + GF_SVC_SSPS_ID_SHIFT * subseq_sps;\n\tif (sps_id >=32) {\n\t\tsps_id = -1;\n\t\tgoto exit;\n\t}\n\tif (sps_id < 0) {\n\t\tsps_id = -1;\n\t\tgoto exit;\n\t}\n\n\tluma_bd = chroma_bd = 0;\n\tchroma_format_idc = ChromaArrayType = 1;\n\tsps = &avc->sps[sps_id];\n\tsps->state |= subseq_sps ? AVC_SUBSPS_PARSED : AVC_SPS_PARSED;\n\n\t/*High Profile and SVC*/\n\tswitch (profile_idc) {\n\tcase 100:\n\tcase 110:\n\tcase 122:\n\tcase 244:\n\tcase 44:\n\t\t/*sanity checks: note1 from 7.4.2.1.1 of iso/iec 14496-10-N11084*/\n\t\tif (pcomp & 0xE0)\n\t\t\tgoto exit;\n\tcase 83:\n\tcase 86:\n\tcase 118:\n\tcase 128:\n\t\tchroma_format_idc = bs_get_ue(bs);\n\t\tChromaArrayType = chroma_format_idc;\n\t\tif (chroma_format_idc == 3) {\n\t\t\tseparate_colour_plane_flag = gf_bs_read_int(bs, 1);\n\t\t\t/*\n\t\t\tDepending on the value of separate_colour_plane_flag, the value of the variable ChromaArrayType is assigned as follows.\n\t\t\t\\96\tIf separate_colour_plane_flag is equal to 0, ChromaArrayType is set equal to chroma_format_idc.\n\t\t\t\\96\tOtherwise (separate_colour_plane_flag is equal to 1), ChromaArrayType is set equal to 0.\n\t\t\t*/\n\t\t\tif (separate_colour_plane_flag) ChromaArrayType = 0;\n\t\t}\n\t\tluma_bd = bs_get_ue(bs);\n\t\tchroma_bd = bs_get_ue(bs);\n\t\t/*qpprime_y_zero_transform_bypass_flag = */ gf_bs_read_int(bs, 1);\n\t\t/*seq_scaling_matrix_present_flag*/\n\t\tif (gf_bs_read_int(bs, 1)) {\n\t\t\tu32 k;\n\t\t\tfor (k=0; k<8; k++) {\n\t\t\t\tif (gf_bs_read_int(bs, 1)) {\n\t\t\t\t\tu32 z, last = 8, next = 8;\n\t\t\t\t\tu32 sl = k<6 ? 16 : 64;\n\t\t\t\t\tfor (z=0; zprofile_idc = profile_idc;\n\tsps->level_idc = level_idc;\n\tsps->prof_compat = pcomp;\n\tsps->log2_max_frame_num = bs_get_ue(bs) + 4;\n\tsps->poc_type = bs_get_ue(bs);\n\tsps->chroma_format = chroma_format_idc;\n\tsps->luma_bit_depth_m8 = luma_bd;\n\tsps->chroma_bit_depth_m8 = chroma_bd;\n\n\tif (sps->poc_type == 0) {\n\t\tsps->log2_max_poc_lsb = bs_get_ue(bs) + 4;\n\t} else if(sps->poc_type == 1) {\n\t\tsps->delta_pic_order_always_zero_flag = gf_bs_read_int(bs, 1);\n\t\tsps->offset_for_non_ref_pic = bs_get_se(bs);\n\t\tsps->offset_for_top_to_bottom_field = bs_get_se(bs);\n\t\tsps->poc_cycle_length = bs_get_ue(bs);\n\t\tfor(i=0; ipoc_cycle_length; i++) sps->offset_for_ref_frame[i] = bs_get_se(bs);\n\t}\n\tif (sps->poc_type > 2) {\n\t\tsps_id = -1;\n\t\tgoto exit;\n\t}\n\tsps->max_num_ref_frames = bs_get_ue(bs); \n\tsps->gaps_in_frame_num_value_allowed_flag = gf_bs_read_int(bs, 1); \n\tmb_width = bs_get_ue(bs) + 1;\n\tmb_height= bs_get_ue(bs) + 1;\n\n\tsps->frame_mbs_only_flag = gf_bs_read_int(bs, 1);\n\n\tsps->width = mb_width * 16;\n\tsps->height = (2-sps->frame_mbs_only_flag) * mb_height * 16;\n\t\n\tif (!sps->frame_mbs_only_flag) sps->mb_adaptive_frame_field_flag = gf_bs_read_int(bs, 1);\n\tgf_bs_read_int(bs, 1); /*direct_8x8_inference_flag*/\n\t\n\tif (gf_bs_read_int(bs, 1)) { /*crop*/\n\t\tint CropUnitX, CropUnitY, SubWidthC = -1, SubHeightC = -1;\n\n\t\tif (chroma_format_idc == 1) {\n\t\t\tSubWidthC = 2, SubHeightC = 2;\n\t\t} else if (chroma_format_idc == 2) {\n\t\t\tSubWidthC = 2, SubHeightC = 1;\n\t\t} else if ((chroma_format_idc == 3) && (separate_colour_plane_flag == 0)) {\n\t\t\tSubWidthC = 1, SubHeightC = 1;\n\t\t}\n\n\t\tif (ChromaArrayType == 0) {\n\t\t\tassert(SubWidthC==-1);\n\t\t\tCropUnitX = 1;\n\t\t\tCropUnitY = 2-sps->frame_mbs_only_flag;\n\t\t} else {\n\t\t\tCropUnitX = SubWidthC;\n\t\t\tCropUnitY = SubHeightC * (2-sps->frame_mbs_only_flag);\n\t\t}\n\n\t\tcl = bs_get_ue(bs); /*crop_left*/\n\t\tcr = bs_get_ue(bs); /*crop_right*/\n\t\tct = bs_get_ue(bs); /*crop_top*/\n\t\tcb = bs_get_ue(bs); /*crop_bottom*/\n\n\t\tsps->width -= CropUnitX * (cl + cr);\n\t\tsps->height -= CropUnitY * (ct + cb);\n\t\tcl *= CropUnitX;\n\t\tcr *= CropUnitX;\n\t\tct *= CropUnitY;\n\t\tcb *= CropUnitY;\n\t} \n\tsps->crop.left = cl;\n\tsps->crop.right = cr;\n\tsps->crop.top = ct;\n\tsps->crop.bottom = cb;\n\n\tif (vui_flag_pos) {\n\t\t*vui_flag_pos = (u32) gf_bs_get_bit_offset(bs);\n\t}\n\t/*vui_parameters_present_flag*/\n\tsps->vui_parameters_present_flag = gf_bs_read_int(bs, 1);\n\tif (sps->vui_parameters_present_flag) {\n\t\tsps->vui.aspect_ratio_info_present_flag = gf_bs_read_int(bs, 1);\n\t\tif (sps->vui.aspect_ratio_info_present_flag) {\n\t\t\ts32 aspect_ratio_idc = gf_bs_read_int(bs, 8);\n\t\t\tif (aspect_ratio_idc == 255) {\n\t\t\t\tsps->vui.par_num = gf_bs_read_int(bs, 16); /*AR num*/\n\t\t\t\tsps->vui.par_den = gf_bs_read_int(bs, 16); /*AR den*/\n\t\t\t} else if (aspect_ratio_idc<14) {\n\t\t\t\tsps->vui.par_num = avc_sar[aspect_ratio_idc].w;\n\t\t\t\tsps->vui.par_den = avc_sar[aspect_ratio_idc].h;\n\t\t\t}\n\t\t}\n\t\tsps->vui.overscan_info_present_flag = gf_bs_read_int(bs, 1);\n\t\tif(sps->vui.overscan_info_present_flag)\t\t\n\t\t\tgf_bs_read_int(bs, 1);\t\t/* overscan_appropriate_flag */\n\n\t\t/* default values */\n\t\tsps->vui.video_format = 5;\n\t\tsps->vui.colour_primaries = 2;\n\t\tsps->vui.transfer_characteristics = 2;\n\t\tsps->vui.matrix_coefficients = 2;\n\t\t/* now read values if possible */\n\t\tsps->vui.video_signal_type_present_flag = gf_bs_read_int(bs, 1);\n\t\tif (sps->vui.video_signal_type_present_flag) {\n\t\t\tsps->vui.video_format = gf_bs_read_int(bs, 3);\n\t\t\tsps->vui.video_full_range_flag = gf_bs_read_int(bs, 1);\n\t\t\tsps->vui.colour_description_present_flag = gf_bs_read_int(bs, 1);\n\t\t\tif (sps->vui.colour_description_present_flag) { \n\t\t\t\tsps->vui.colour_primaries = gf_bs_read_int(bs, 8); \n\t\t\t\tsps->vui.transfer_characteristics = gf_bs_read_int(bs, 8); \n\t\t\t\tsps->vui.matrix_coefficients = gf_bs_read_int(bs, 8); \n\t\t\t}\n\t\t}\n\n\t\tif (gf_bs_read_int(bs, 1)) {\t/* chroma_location_info_present_flag */\n\t\t\tbs_get_ue(bs);\t\t\t\t/* chroma_sample_location_type_top_field */\n\t\t\tbs_get_ue(bs);\t\t\t\t/* chroma_sample_location_type_bottom_field */\n\t\t}\n\n\t\tsps->vui.timing_info_present_flag = gf_bs_read_int(bs, 1);\n\t\tif (sps->vui.timing_info_present_flag) {\n\t\t\tsps->vui.num_units_in_tick = gf_bs_read_int(bs, 32);\n\t\t\tsps->vui.time_scale = gf_bs_read_int(bs, 32);\n\t\t\tsps->vui.fixed_frame_rate_flag = gf_bs_read_int(bs, 1);\n\t\t}\n\n\t\tsps->vui.nal_hrd_parameters_present_flag = gf_bs_read_int(bs, 1);\n\t\tif (sps->vui.nal_hrd_parameters_present_flag)\n\t\t\tavc_parse_hrd_parameters(bs, &sps->vui.hrd);\n\n\t\tsps->vui.vcl_hrd_parameters_present_flag = gf_bs_read_int(bs, 1);\n\t\tif (sps->vui.vcl_hrd_parameters_present_flag)\n\t\t\tavc_parse_hrd_parameters(bs, &sps->vui.hrd);\n\n\t\tif (sps->vui.nal_hrd_parameters_present_flag || sps->vui.vcl_hrd_parameters_present_flag)\n\t\t\tsps->vui.low_delay_hrd_flag = gf_bs_read_int(bs, 1); \n\n\t\tsps->vui.pic_struct_present_flag = gf_bs_read_int(bs, 1);\n\t}\n\t/*end of seq_parameter_set_data*/\n\n\tif (subseq_sps) {\n\t\tif ((profile_idc==83) || (profile_idc==86)) {\n\t\t\tu8 extended_spatial_scalability_idc;\n\t\t\t/*parsing seq_parameter_set_svc_extension*/\n\n\t\t\t/*inter_layer_deblocking_filter_control_present_flag=*/\tgf_bs_read_int(bs, 1);\n\t\t\textended_spatial_scalability_idc = gf_bs_read_int(bs, 2);\n\t\t\tif (ChromaArrayType == 1 || ChromaArrayType == 2) {\n\t\t\t\t/*chroma_phase_x_plus1_flag*/ gf_bs_read_int(bs, 1);\n\t\t\t}\n\t\t\tif( ChromaArrayType == 1 ) {\n\t\t\t\t/*chroma_phase_y_plus1*/ gf_bs_read_int(bs, 2);\n\t\t\t}\n\t\t\tif (extended_spatial_scalability_idc == 1) {\n\t\t\t\tif( ChromaArrayType > 0 ) {\n\t\t\t\t\t/*seq_ref_layer_chroma_phase_x_plus1_flag*/gf_bs_read_int(bs, 1);\n\t\t\t\t\t/*seq_ref_layer_chroma_phase_y_plus1*/gf_bs_read_int(bs, 2);\n\t\t\t\t}\n\t\t\t\t/*seq_scaled_ref_layer_left_offset*/ bs_get_se(bs);\n\t\t\t\t/*seq_scaled_ref_layer_top_offset*/bs_get_se(bs);\n\t\t\t\t/*seq_scaled_ref_layer_right_offset*/bs_get_se(bs);\n\t\t\t\t/*seq_scaled_ref_layer_bottom_offset*/bs_get_se(bs);\n\t\t\t}\n\t\t\tif (/*seq_tcoeff_level_prediction_flag*/gf_bs_read_int(bs, 1)) {\n\t\t\t\t/*adaptive_tcoeff_level_prediction_flag*/ gf_bs_read_int(bs, 1);\n\t\t\t}\n\t\t\t/*slice_header_restriction_flag*/gf_bs_read_int(bs, 1);\n\n\t\t\t/*svc_vui_parameters_present*/\n\t\t\tif (gf_bs_read_int(bs, 1)) {\n\t\t\t\tu32 i, vui_ext_num_entries_minus1;\n\t\t\t\tvui_ext_num_entries_minus1 = bs_get_ue(bs);\n\n\t\t\t\tfor (i=0; i <= vui_ext_num_entries_minus1; i++) {\n\t\t\t\t\tu8 vui_ext_nal_hrd_parameters_present_flag, vui_ext_vcl_hrd_parameters_present_flag, vui_ext_timing_info_present_flag;\n\t\t\t\t\t/*u8 vui_ext_dependency_id =*/ gf_bs_read_int(bs, 3);\n\t\t\t\t\t/*u8 vui_ext_quality_id =*/ gf_bs_read_int(bs, 4);\n\t\t\t\t\t/*u8 vui_ext_temporal_id =*/ gf_bs_read_int(bs, 3);\n\t\t\t\t\tvui_ext_timing_info_present_flag = gf_bs_read_int(bs, 1);\n\t\t\t\t\tif (vui_ext_timing_info_present_flag) {\n\t\t\t\t\t\t/*u32 vui_ext_num_units_in_tick = */gf_bs_read_int(bs, 32);\n\t\t\t\t\t\t/*u32 vui_ext_time_scale = */gf_bs_read_int(bs, 32);\n\t\t\t\t\t\t/*u8 vui_ext_fixed_frame_rate_flag = */gf_bs_read_int(bs, 1);\n\t\t\t\t\t}\n\t\t\t\t\tvui_ext_nal_hrd_parameters_present_flag = gf_bs_read_int(bs, 1);\n\t\t\t\t\tif (vui_ext_nal_hrd_parameters_present_flag) {\n\t\t\t\t\t\t//hrd_parameters( )\n\t\t\t\t\t}\n\t\t\t\t\tvui_ext_vcl_hrd_parameters_present_flag = gf_bs_read_int(bs, 1);\n\t\t\t\t\tif (vui_ext_vcl_hrd_parameters_present_flag) {\n\t\t\t\t\t\t//hrd_parameters( )\n\t\t\t\t\t}\n\t\t\t\t\tif ( vui_ext_nal_hrd_parameters_present_flag || vui_ext_vcl_hrd_parameters_present_flag) {\n\t\t\t\t\t\t/*vui_ext_low_delay_hrd_flag*/gf_bs_read_int(bs, 1);\n\t\t\t\t\t}\n\t\t\t\t\t/*vui_ext_pic_struct_present_flag*/gf_bs_read_int(bs, 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if ((profile_idc==118) || (profile_idc==128)) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[avc-h264] MVC not supported - skipping parsing end of Subset SPS\\n\"));\n\t\t\tgoto exit;\n\t\t}\n\n\t\tif (gf_bs_read_int(bs, 1)) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[avc-h264] skipping parsing end of Subset SPS (additional_extension2)\\n\"));\n\t\t\tgoto exit;\n\t\t}\n\t}\n\nexit:\n\tgf_bs_del(bs);\n\tgf_free(sps_data_without_emulation_bytes);\n\treturn sps_id;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'fix some exploitable overflows (#994, #997)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: grub_ext2_iterate_dir (grub_fshelp_node_t dir,\n\t\t int (*hook) (const char *filename,\n\t\t\t\t enum grub_fshelp_filetype filetype,\n\t\t\t\t grub_fshelp_node_t node,\n\t\t\t\t void *closure),\n\t\t void *closure)\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 if (hook)\n while (fpos < grub_le_to_cpu32 (diro->inode.size))\n {\n struct ext2_dirent dirent;\n\n grub_ext2_read_file (diro, NULL, NULL, 0, fpos, sizeof (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.namelen != 0)\n\t{\n#ifndef _MSC_VER\n\t char filename[dirent.namelen + 1]; \n#else\n\t char * filename = grub_malloc (dirent.namelen + 1);\n#endif\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, 0,\n\t\t\t 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, closure))\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-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 addr_t* MACH0_(get_entrypoint)(struct MACH0_(obj_t)* bin) {\n\tstruct addr_t *entry;\n\tint i;\n\n\tif (!bin->entry && !bin->sects) {\n\t\treturn NULL;\n\t}\n\tif (!(entry = calloc (1, sizeof (struct addr_t)))) {\n\t\treturn NULL;\n\t}\n\n\tif (bin->entry) {\n\t\tentry->addr = entry_to_vaddr (bin);\n\t\tentry->offset = addr_to_offset (bin, entry->addr);\n\t\tentry->haddr = sdb_num_get (bin->kv, \"mach0.entry.offset\", 0);\n\t}\n\n\tif (!bin->entry || entry->offset == 0) {\n\t\t// XXX: section name doesnt matters at all.. just check for exec flags\n\t\tfor (i = 0; i < bin->nsects; i++) {\n\t\t\tif (!strncmp (bin->sects[i].sectname, \"__text\", 6)) {\n\t\t\t\tentry->offset = (ut64)bin->sects[i].offset;\n\t\t\t\tsdb_num_set (bin->kv, \"mach0.entry\", entry->offset, 0);\n\t\t\t\tentry->addr = (ut64)bin->sects[i].addr;\n\t\t\t\tif (!entry->addr) { // workaround for object files\n\t\t\t\t\tentry->addr = entry->offset;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tbin->entry = entry->addr;\n\t}\n\n\treturn entry;\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_eval_sels(agooErr err, gqlDoc doc, gqlRef ref, gqlField field, gqlSel sels, gqlValue result, int depth) {\n gqlSel\tsel;\n gqlField\tsf = NULL;\n\n // TBD if depth over max then return an error\n\n for (sel = sels; NULL != sel; sel = sel->next) {\n\tif (NULL != field) {\n\t if (NULL == sel->name) {\n\t\tsf = field;\n\t } else {\n\t\tsf = gql_type_get_field(field->type, sel->name);\n\t }\n\t} else {\n\t sf = NULL;\n\t}\n\tif (NULL != sel->inline_frag) {\n\t if (frag_include(doc, sel->inline_frag, ref)) {\n\t\tif (AGOO_ERR_OK != gql_eval_sels(err, doc, ref, sf, sel->inline_frag->sels, result, depth)) {\n\t\t return err->code;\n\t\t}\n\t }\n\t} else if (NULL != sel->frag) {\n\t gqlFrag\tfrag;\n\n\t for (frag = doc->frags; NULL != frag; frag = frag->next) {\n\t\tif (NULL != frag->name && 0 == strcmp(frag->name, sel->frag)) {\n\t\t if (frag_include(doc, frag, ref)) {\n\t\t\tif (AGOO_ERR_OK != gql_eval_sels(err, doc, ref, sf, frag->sels, result, depth)) {\n\t\t\t return err->code;\n\t\t\t}\n\t\t }\n\t\t}\n\t }\n\t} else {\n\t if (AGOO_ERR_OK != doc->funcs.resolve(err, doc, ref, sf, sel, result, depth)) {\n\t\treturn err->code;\n\t }\n\t}\n }\n return AGOO_ERR_OK;\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: static int sco_sock_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 sco_pinfo *pi = sco_pi(sk);\n\n\tlock_sock(sk);\n\n\tif (sk->sk_state == BT_CONNECT2 &&\n\t test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) {\n\t\thci_conn_accept(pi->conn->hcon, 0);\n\t\tsk->sk_state = BT_CONFIG;\n\n\t\trelease_sock(sk);\n\t\treturn 0;\n\t}\n\n\trelease_sock(sk);\n\n\treturn bt_sock_recvmsg(iocb, sock, msg, len, flags);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Bluetooth: SCO - Fix missing msg_namelen update in sco_sock_recvmsg()\n\nIf the socket is in state BT_CONNECT2 and BT_SK_DEFER_SETUP is set in\nthe flags, sco_sock_recvmsg() returns early with 0 without updating the\npossibly set msg_namelen member. This, in turn, leads to a 128 byte\nkernel stack leak in net/socket.c.\n\nFix this by updating msg_namelen in this case. For all other cases it\nwill be handled in bt_sock_recvmsg().\n\nCc: Marcel Holtmann \nCc: Gustavo Padovan \nCc: Johan Hedberg \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 oe_iov_sync(\n const struct oe_iovec* iov,\n int iovcnt,\n const void* buf_,\n size_t buf_size)\n{\n struct oe_iovec* buf = (struct oe_iovec*)buf_;\n int ret = -1;\n int i;\n size_t n;\n\n /* Reject invalid parameters. */\n if (iovcnt < 0 || (iovcnt > 0 && !iov))\n goto done;\n\n /* Synchronize the data. */\n for (i = 0, n = buf_size; i < iovcnt; i++)\n {\n if (buf[i].iov_len != iov[i].iov_len)\n goto done;\n\n if (buf[i].iov_len)\n {\n if (buf[i].iov_base && !iov[i].iov_base)\n goto done;\n\n if (!buf[i].iov_base && iov[i].iov_base)\n goto done;\n\n if (!buf[i].iov_base)\n continue;\n\n /* Fail if buffer data is exhausted. */\n if (n < buf[i].iov_len)\n goto done;\n\n /* Sync the base data for this element. */\n {\n /* Note: buf[i].iov_base is an offset here (not a pointer). */\n uint8_t* src = (uint8_t*)buf[i].iov_base + (uint64_t)buf;\n size_t src_size = buf[i].iov_len;\n uint8_t* dest = (uint8_t*)iov[i].iov_base;\n size_t dest_size = iov[i].iov_len;\n\n if (src_size != dest_size)\n goto done;\n\n if (src < (uint8_t*)buf || src > (uint8_t*)buf + buf_size)\n goto done;\n\n if (oe_memcpy_s(dest, dest_size, src, src_size) != OE_OK)\n goto done;\n }\n }\n\n n -= buf[i].iov_len;\n }\n\n ret = 0;\n\ndone:\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 _hostfs_pwrite(\n oe_fd_t* desc,\n const void* buf,\n size_t count,\n oe_off_t offset)\n{\n ssize_t ret = -1;\n file_t* file = _cast_file(desc);\n\n if (!file)\n OE_RAISE_ERRNO(OE_EINVAL);\n\n if (oe_syscall_pwrite_ocall(&ret, file->host_fd, buf, count, offset) !=\n 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: static ssize_t _hostsock_send(\n oe_fd_t* sock_,\n const void* buf,\n size_t count,\n int flags)\n{\n ssize_t ret = -1;\n sock_t* sock = _cast_sock(sock_);\n\n oe_errno = 0;\n\n if (!sock || (count && !buf))\n OE_RAISE_ERRNO(OE_EINVAL);\n\n if (oe_syscall_send_ocall(&ret, sock->host_fd, buf, count, flags) != 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: int main(int argc, char **argv) {\n\tint result;\n\tint error = FALSE;\n\tint display_license = FALSE;\n\tint display_help = FALSE;\n\tint c = 0;\n\tstruct tm *tm, tm_s;\n\ttime_t now;\n\tchar datestring[256];\n\tnagios_macros *mac;\n\tconst char *worker_socket = NULL;\n\tint i;\n#ifdef HAVE_SIGACTION\n\tstruct sigaction sig_action;\n#endif\n\n#ifdef HAVE_GETOPT_H\n\tint option_index = 0;\n\tstatic struct option long_options[] = {\n\t\t\t{\"help\", no_argument, 0, 'h'},\n\t\t\t{\"version\", no_argument, 0, 'V'},\n\t\t\t{\"license\", no_argument, 0, 'V'},\n\t\t\t{\"verify-config\", no_argument, 0, 'v'},\n\t\t\t{\"daemon\", no_argument, 0, 'd'},\n\t\t\t{\"test-scheduling\", no_argument, 0, 's'},\n\t\t\t{\"precache-objects\", no_argument, 0, 'p'},\n\t\t\t{\"use-precached-objects\", no_argument, 0, 'u'},\n\t\t\t{\"enable-timing-point\", no_argument, 0, 'T'},\n\t\t\t{\"worker\", required_argument, 0, 'W'},\n\t\t\t{0, 0, 0, 0}\n\t\t};\n#define getopt(argc, argv, o) getopt_long(argc, argv, o, long_options, &option_index)\n#endif\n\n\tmemset(&loadctl, 0, sizeof(loadctl));\n\tmac = get_global_macros();\n\n\t/* make sure we have the correct number of command line arguments */\n\tif(argc < 2)\n\t\terror = TRUE;\n\n\t/* get all command line arguments */\n\twhile(1) {\n\t\tc = getopt(argc, argv, \"+hVvdspuxTW\");\n\n\t\tif(c == -1 || c == EOF)\n\t\t\tbreak;\n\n\t\tswitch(c) {\n\n\t\t\tcase '?': /* usage */\n\t\t\tcase 'h':\n\t\t\t\tdisplay_help = TRUE;\n\t\t\t\tbreak;\n\n\t\t\tcase 'V': /* version */\n\t\t\t\tdisplay_license = TRUE;\n\t\t\t\tbreak;\n\n\t\t\tcase 'v': /* verify */\n\t\t\t\tverify_config++;\n\t\t\t\tbreak;\n\n\t\t\tcase 's': /* scheduling check */\n\t\t\t\ttest_scheduling = TRUE;\n\t\t\t\tbreak;\n\n\t\t\tcase 'd': /* daemon mode */\n\t\t\t\tdaemon_mode = TRUE;\n\t\t\t\tbreak;\n\n\t\t\tcase 'p': /* precache object config */\n\t\t\t\tprecache_objects = TRUE;\n\t\t\t\tbreak;\n\n\t\t\tcase 'u': /* use precached object config */\n\t\t\t\tuse_precached_objects = TRUE;\n\t\t\t\tbreak;\n\t\t\tcase 'T':\n\t\t\t\tenable_timing_point = TRUE;\n\t\t\t\tbreak;\n\t\t\tcase 'W':\n\t\t\t\tworker_socket = optarg;\n\t\t\t\tbreak;\n\n\t\t\tcase 'x':\n\t\t\t\tprintf(\"Warning: -x is deprecated and will be removed\\n\");\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t}\n\n#ifdef DEBUG_MEMORY\n\tmtrace();\n#endif\n\t/* if we're a worker we can skip everything below */\n\tif(worker_socket) {\n\t\texit(nagios_core_worker(worker_socket));\n\t}\n\n\t/* Initialize configuration variables */ \n\tinit_main_cfg_vars(1);\n\tinit_shared_cfg_vars(1);\n\n\tif(daemon_mode == FALSE) {\n\t\tprintf(\"\\nNagios Core %s\\n\", PROGRAM_VERSION);\n\t\tprintf(\"Copyright (c) 2009-present Nagios Core Development Team and Community Contributors\\n\");\n\t\tprintf(\"Copyright (c) 1999-2009 Ethan Galstad\\n\");\n\t\tprintf(\"Last Modified: %s\\n\", PROGRAM_MODIFICATION_DATE);\n\t\tprintf(\"License: GPL\\n\\n\");\n\t\tprintf(\"Website: https://www.nagios.org\\n\");\n\t\t}\n\n\t/* just display the license */\n\tif(display_license == TRUE) {\n\n\t\tprintf(\"This program is free software; you can redistribute it and/or modify\\n\");\n\t\tprintf(\"it under the terms of the GNU General Public License version 2 as\\n\");\n\t\tprintf(\"published by the Free Software Foundation.\\n\\n\");\n\t\tprintf(\"This program is distributed in the hope that it will be useful,\\n\");\n\t\tprintf(\"but WITHOUT ANY WARRANTY; without even the implied warranty of\\n\");\n\t\tprintf(\"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\\n\");\n\t\tprintf(\"GNU General Public License for more details.\\n\\n\");\n\t\tprintf(\"You should have received a copy of the GNU General Public License\\n\");\n\t\tprintf(\"along with this program; if not, write to the Free Software\\n\");\n\t\tprintf(\"Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\\n\\n\");\n\n\t\texit(OK);\n\t\t}\n\n\t/* make sure we got the main config file on the command line... */\n\tif(optind >= argc)\n\t\terror = TRUE;\n\n\t/* if there are no command line options (or if we encountered an error), print usage */\n\tif(error == TRUE || display_help == TRUE) {\n\n\t\tprintf(\"Usage: %s [options] \\n\", argv[0]);\n\t\tprintf(\"\\n\");\n\t\tprintf(\"Options:\\n\");\n\t\tprintf(\"\\n\");\n\t\tprintf(\" -v, --verify-config Verify all configuration data (-v -v for more info)\\n\");\n\t\tprintf(\" -s, --test-scheduling Shows projected/recommended check scheduling and other\\n\");\n\t\tprintf(\" diagnostic info based on the current configuration files.\\n\");\n\t\tprintf(\" -T, --enable-timing-point Enable timed commentary on initialization\\n\");\n\t\tprintf(\" -x, --dont-verify-paths Deprecated (Don't check for circular object paths)\\n\");\n\t\tprintf(\" -p, --precache-objects Precache object configuration\\n\");\n\t\tprintf(\" -u, --use-precached-objects Use precached object config file\\n\");\n\t\tprintf(\" -d, --daemon Starts Nagios in daemon mode, instead of as a foreground process\\n\");\n\t\tprintf(\" -W, --worker /path/to/socket Act as a worker for an already running daemon\\n\");\n\t\tprintf(\"\\n\");\n\t\tprintf(\"Visit the Nagios website at https://www.nagios.org/ for bug fixes, new\\n\");\n\t\tprintf(\"releases, online documentation, FAQs, information on subscribing to\\n\");\n\t\tprintf(\"the mailing lists, and commercial support options for Nagios.\\n\");\n\t\tprintf(\"\\n\");\n\n\t\texit(ERROR);\n\t\t}\n\n\n\t/*\n\t * config file is last argument specified.\n\t * Make sure it uses an absolute path\n\t */\n\tconfig_file = nspath_absolute(argv[optind], NULL);\n\tif(config_file == NULL) {\n\t\tprintf(\"Error allocating memory.\\n\");\n\t\texit(ERROR);\n\t\t}\n\n\tconfig_file_dir = nspath_absolute_dirname(config_file, NULL);\n\n\t/* \n\t * Set the signal handler for the SIGXFSZ signal here because\n\t * we may encounter this signal before the other signal handlers\n\t * are set.\n\t */\n#ifdef HAVE_SIGACTION\n\tsig_action.sa_sigaction = NULL;\n\tsig_action.sa_handler = handle_sigxfsz;\n\tsigfillset(&sig_action.sa_mask);\n\tsig_action.sa_flags = SA_NODEFER|SA_RESTART;\n\tsigaction(SIGXFSZ, &sig_action, NULL);\n#else\n\tsignal(SIGXFSZ, handle_sigxfsz);\n#endif\n\n\t/*\n\t * let's go to town. We'll be noisy if we're verifying config\n\t * or running scheduling tests.\n\t */\n\tif(verify_config || test_scheduling || precache_objects) {\n\t\treset_variables();\n\t\t/*\n\t\t * if we don't beef up our resource limits as much as\n\t\t * we can, it's quite possible we'll run headlong into\n\t\t * EAGAIN due to too many processes when we try to\n\t\t * drop privileges later.\n\t\t */\n\t\tset_loadctl_defaults();\n\n\t\tif(verify_config)\n\t\t\tprintf(\"Reading configuration data...\\n\");\n\n\t\t/* read our config file */\n\t\tresult = read_main_config_file(config_file);\n\t\tif(result != OK) {\n\t\t\tprintf(\" Error processing main config file!\\n\\n\");\n\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\n\t\tif(verify_config)\n\t\t\tprintf(\" Read main config file okay...\\n\");\n\n\t\t/* drop privileges */\n\t\tif((result = drop_privileges(nagios_user, nagios_group)) == ERROR) {\n\t\t\tprintf(\" Failed to drop privileges. Aborting.\");\n\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\n\t\t/*\n\t\t * this must come after dropping privileges, so we make\n\t\t * sure to test access permissions as the right user.\n\t\t */\n\t\tif (!verify_config && test_configured_paths() == ERROR) {\n\t\t\tprintf(\" One or more path problems detected. Aborting.\\n\");\n\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\n\t\t/* read object config files */\n\t\tresult = read_all_object_data(config_file);\n\t\tif(result != OK) {\n\t\t\tprintf(\" Error processing object config files!\\n\\n\");\n\t\t\t/* if the config filename looks fishy, warn the user */\n\t\t\tif(!strstr(config_file, \"nagios.cfg\")) {\n\t\t\t\tprintf(\"\\n***> The name of the main configuration file looks suspicious...\\n\");\n\t\t\t\tprintf(\"\\n\");\n\t\t\t\tprintf(\" Make sure you are specifying the name of the MAIN configuration file on\\n\");\n\t\t\t\tprintf(\" the command line and not the name of another configuration file. The\\n\");\n\t\t\t\tprintf(\" main configuration file is typically '%s'\\n\", DEFAULT_CONFIG_FILE);\n\t\t\t\t}\n\n\t\t\tprintf(\"\\n***> One or more problems was encountered while processing the config files...\\n\");\n\t\t\tprintf(\"\\n\");\n\t\t\tprintf(\" Check your configuration file(s) to ensure that they contain valid\\n\");\n\t\t\tprintf(\" directives and data definitions. If you are upgrading from a previous\\n\");\n\t\t\tprintf(\" version of Nagios, you should be aware that some variables/definitions\\n\");\n\t\t\tprintf(\" may have been removed or modified in this version. Make sure to read\\n\");\n\t\t\tprintf(\" the HTML documentation regarding the config files, as well as the\\n\");\n\t\t\tprintf(\" 'Whats New' section to find out what has changed.\\n\\n\");\n\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\n\t\tif(verify_config) {\n\t\t\tprintf(\" Read object config files okay...\\n\\n\");\n\t\t\tprintf(\"Running pre-flight check on configuration data...\\n\\n\");\n\t\t\t}\n\n\t\t/* run the pre-flight check to make sure things look okay... */\n\t\tresult = pre_flight_check();\n\n\t\tif(result != OK) {\n\t\t\tprintf(\"\\n***> One or more problems was encountered while running the pre-flight check...\\n\");\n\t\t\tprintf(\"\\n\");\n\t\t\tprintf(\" Check your configuration file(s) to ensure that they contain valid\\n\");\n\t\t\tprintf(\" directives and data definitions. If you are upgrading from a previous\\n\");\n\t\t\tprintf(\" version of Nagios, you should be aware that some variables/definitions\\n\");\n\t\t\tprintf(\" may have been removed or modified in this version. Make sure to read\\n\");\n\t\t\tprintf(\" the HTML documentation regarding the config files, as well as the\\n\");\n\t\t\tprintf(\" 'Whats New' section to find out what has changed.\\n\\n\");\n\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\n\t\tif(verify_config) {\n\t\t\tprintf(\"\\nThings look okay - No serious problems were detected during the pre-flight check\\n\");\n\t\t\t}\n\n\t\t/* scheduling tests need a bit more than config verifications */\n\t\tif(test_scheduling == TRUE) {\n\n\t\t\t/* we'll need the event queue here so we can time insertions */\n\t\t\tinit_event_queue();\n\t\t\ttiming_point(\"Done initializing event queue\\n\");\n\n\t\t\t/* read initial service and host state information */\n\t\t\tinitialize_retention_data(config_file);\n\t\t\tread_initial_state_information();\n\t\t\ttiming_point(\"Retention data and initial state parsed\\n\");\n\n\t\t\t/* initialize the event timing loop */\n\t\t\tinit_timing_loop();\n\t\t\ttiming_point(\"Timing loop initialized\\n\");\n\n\t\t\t/* display scheduling information */\n\t\t\tdisplay_scheduling_info();\n\t\t\t}\n\n\t\tif(precache_objects) {\n\t\t\tresult = fcache_objects(object_precache_file);\n\t\t\ttiming_point(\"Done precaching objects\\n\");\n\t\t\tif(result == OK) {\n\t\t\t\tprintf(\"Object precache file created:\\n%s\\n\", object_precache_file);\n\t\t\t\t}\n\t\t\telse {\n\t\t\t\tprintf(\"Failed to precache objects to '%s': %s\\n\", object_precache_file, strerror(errno));\n\t\t\t\t}\n\t\t\t}\n\n\t\t/* clean up after ourselves */\n\t\tcleanup();\n\n\t\t/* exit */\n\t\ttiming_point(\"Exiting\\n\");\n\n\t\t/* make valgrind shut up about still reachable memory */\n\t\tneb_free_module_list();\n\t\tfree(config_file_dir);\n\t\tfree(config_file);\n\n\t\texit(result);\n\t\t}\n\n\n\t/* else start to monitor things... */\n\telse {\n\n\t\t/*\n\t\t * if we're called with a relative path we must make\n\t\t * it absolute so we can launch our workers.\n\t\t * If not, we needn't bother, as we're using execvp()\n\t\t */\n\t\tif (strchr(argv[0], '/'))\n\t\t\tnagios_binary_path = nspath_absolute(argv[0], NULL);\n\t\telse\n\t\t\tnagios_binary_path = strdup(argv[0]);\n\n\t\tif (!nagios_binary_path) {\n\t\t\tlogit(NSLOG_RUNTIME_ERROR, TRUE, \"Error: Unable to allocate memory for nagios_binary_path\\n\");\n\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\n\t\tif (!(nagios_iobs = iobroker_create())) {\n\t\t\tlogit(NSLOG_RUNTIME_ERROR, TRUE, \"Error: Failed to create IO broker set: %s\\n\",\n\t\t\t\t strerror(errno));\n\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\n\t\t/* keep monitoring things until we get a shutdown command */\n\t\tdo {\n\t\t\t/* reset internal book-keeping (in case we're restarting) */\n\t\t\twproc_num_workers_spawned = wproc_num_workers_online = 0;\n\t\t\tcaught_signal = sigshutdown = FALSE;\n\t\t\tsig_id = 0;\n\n\t\t\t/* reset program variables */\n\t\t\treset_variables();\n\t\t\ttiming_point(\"Variables reset\\n\");\n\n\t\t\t/* get PID */\n\t\t\tnagios_pid = (int)getpid();\n\n\t\t\t/* read in the configuration files (main and resource config files) */\n\t\t\tresult = read_main_config_file(config_file);\n\t\t\tif (result != OK) {\n\t\t\t\tlogit(NSLOG_CONFIG_ERROR, TRUE, \"Error: Failed to process config file '%s'. Aborting\\n\", config_file);\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t}\n\t\t\ttiming_point(\"Main config file read\\n\");\n\n\t\t\t/* NOTE 11/06/07 EG moved to after we read config files, as user may have overridden timezone offset */\n\t\t\t/* get program (re)start time and save as macro */\n\t\t\tprogram_start = time(NULL);\n\t\t\tmy_free(mac->x[MACRO_PROCESSSTARTTIME]);\n\t\t\tasprintf(&mac->x[MACRO_PROCESSSTARTTIME], \"%llu\", (unsigned long long)program_start);\n\n\t\t\t/* drop privileges */\n\t\t\tif(drop_privileges(nagios_user, nagios_group) == ERROR) {\n\n\t\t\t\tlogit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_CONFIG_ERROR, TRUE, \"Failed to drop privileges. Aborting.\");\n\n\t\t\t\tcleanup();\n\t\t\t\texit(ERROR);\n\t\t\t\t}\n\n\t\t\tif (test_path_access(nagios_binary_path, X_OK)) {\n\t\t\t\tlogit(NSLOG_RUNTIME_ERROR, TRUE, \"Error: failed to access() %s: %s\\n\", nagios_binary_path, strerror(errno));\n\t\t\t\tlogit(NSLOG_RUNTIME_ERROR, TRUE, \"Error: Spawning workers will be impossible. Aborting.\\n\");\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t}\n\n\t\t\tif (test_configured_paths() == ERROR) {\n\t\t\t\t/* error has already been logged */\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t}\n\t\t\t/* enter daemon mode (unless we're restarting...) */\n\t\t\tif(daemon_mode == TRUE && sigrestart == FALSE) {\n\n\t\t\t\tresult = daemon_init();\n\n\t\t\t\t/* we had an error daemonizing, so bail... */\n\t\t\t\tif(result == ERROR) {\n\t\t\t\t\tlogit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR, TRUE, \"Bailing out due to failure to daemonize. (PID=%d)\", (int)getpid());\n\t\t\t\t\tcleanup();\n\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t\t}\n\n\t\t\t\t/* get new PID */\n\t\t\t\tnagios_pid = (int)getpid();\n\t\t\t\t}\n\n\t\t\t/* this must be logged after we read config data, as user may have changed location of main log file */\n\t\t\tlogit(NSLOG_PROCESS_INFO, TRUE, \"Nagios %s starting... (PID=%d)\\n\", PROGRAM_VERSION, (int)getpid());\n\n\t\t\t/* log the local time - may be different than clock time due to timezone offset */\n\t\t\tnow = time(NULL);\n\t\t\ttm = localtime_r(&now, &tm_s);\n\t\t\tstrftime(datestring, sizeof(datestring), \"%a %b %d %H:%M:%S %Z %Y\", tm);\n\t\t\tlogit(NSLOG_PROCESS_INFO, TRUE, \"Local time is %s\", datestring);\n\n\t\t\t/* write log version/info */\n\t\t\twrite_log_file_info(NULL);\n\n\t\t\t/* open debug log now that we're the right user */\n\t\t\topen_debug_log();\n\n#ifdef USE_EVENT_BROKER\n\t\t\t/* initialize modules */\n\t\t\tneb_init_modules();\n\t\t\tneb_init_callback_list();\n#endif\n\t\t\ttiming_point(\"NEB module API initialized\\n\");\n\n\t\t\t/* handle signals (interrupts) before we do any socket I/O */\n\t\t\tsetup_sighandler();\n\n\t\t\t/*\n\t\t\t * Initialize query handler and event subscription service.\n\t\t\t * This must be done before modules are initialized, so\n\t\t\t * the modules can use our in-core stuff properly\n\t\t\t */\n\t\t\tif (qh_init(qh_socket_path ? qh_socket_path : DEFAULT_QUERY_SOCKET) != OK) {\n\t\t\t\tlogit(NSLOG_RUNTIME_ERROR, TRUE, \"Error: Failed to initialize query handler. Aborting\\n\");\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\t\t\ttiming_point(\"Query handler initialized\\n\");\n\t\t\tnerd_init();\n\t\t\ttiming_point(\"NERD initialized\\n\");\n\n\t\t\t/* initialize check workers */\n\t\t\tif(init_workers(num_check_workers) < 0) {\n\t\t\t\tlogit(NSLOG_RUNTIME_ERROR, TRUE, \"Failed to spawn workers. Aborting\\n\");\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\t\t\ttiming_point(\"%u workers spawned\\n\", wproc_num_workers_spawned);\n\t\t\ti = 0;\n\t\t\twhile (i < 50 && wproc_num_workers_online < wproc_num_workers_spawned) {\n\t\t\t\tiobroker_poll(nagios_iobs, 50);\n\t\t\t\ti++;\n\t\t\t}\n\t\t\ttiming_point(\"%u workers connected\\n\", wproc_num_workers_online);\n\n\t\t\t/* now that workers have arrived we can set the defaults */\n\t\t\tset_loadctl_defaults();\n\n#ifdef USE_EVENT_BROKER\n\t\t\t/* load modules */\n\t\t\tif (neb_load_all_modules() != OK) {\n\t\t\t\tlogit(NSLOG_CONFIG_ERROR, ERROR, \"Error: Module loading failed. Aborting.\\n\");\n\t\t\t\t/* if we're dumping core, we must remove all dl-files */\n\t\t\t\tif (daemon_dumps_core)\n\t\t\t\t\tneb_unload_all_modules(NEBMODULE_FORCE_UNLOAD, NEBMODULE_NEB_SHUTDOWN);\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t}\n\t\t\ttiming_point(\"Modules loaded\\n\");\n\n\t\t\t/* send program data to broker */\n\t\t\tbroker_program_state(NEBTYPE_PROCESS_PRELAUNCH, NEBFLAG_NONE, NEBATTR_NONE, NULL);\n\t\t\ttiming_point(\"First callback made\\n\");\n#endif\n\n\t\t\t/* read in all object config data */\n\t\t\tif(result == OK)\n\t\t\t\tresult = read_all_object_data(config_file);\n\n\t\t\t/* there was a problem reading the config files */\n\t\t\tif(result != OK)\n\t\t\t\tlogit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_CONFIG_ERROR, TRUE, \"Bailing out due to one or more errors encountered in the configuration files. Run Nagios from the command line with the -v option to verify your config before restarting. (PID=%d)\", (int)getpid());\n\n\t\t\telse {\n\n\t\t\t\t/* run the pre-flight check to make sure everything looks okay*/\n\t\t\t\tif((result = pre_flight_check()) != OK)\n\t\t\t\t\tlogit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_VERIFICATION_ERROR, TRUE, \"Bailing out due to errors encountered while running the pre-flight check. Run Nagios from the command line with the -v option to verify your config before restarting. (PID=%d)\\n\", (int)getpid());\n\t\t\t\t}\n\n\t\t\t/* an error occurred that prevented us from (re)starting */\n\t\t\tif(result != OK) {\n\n\t\t\t\t/* if we were restarting, we need to cleanup from the previous run */\n\t\t\t\tif(sigrestart == TRUE) {\n\n\t\t\t\t\t/* clean up the status data */\n\t\t\t\t\tcleanup_status_data(TRUE);\n\t\t\t\t\t}\n\n#ifdef USE_EVENT_BROKER\n\t\t\t\t/* send program data to broker */\n\t\t\t\tbroker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_PROCESS_INITIATED, NEBATTR_SHUTDOWN_ABNORMAL, NULL);\n#endif\n\t\t\t\tcleanup();\n\t\t\t\texit(ERROR);\n\t\t\t\t}\n\n\t\t\ttiming_point(\"Object configuration parsed and understood\\n\");\n\n\t\t\t/* write the objects.cache file */\n\t\t\tfcache_objects(object_cache_file);\n\t\t\ttiming_point(\"Objects cached\\n\");\n\n\t\t\tinit_event_queue();\n\t\t\ttiming_point(\"Event queue initialized\\n\");\n\n\n#ifdef USE_EVENT_BROKER\n\t\t\t/* send program data to broker */\n\t\t\tbroker_program_state(NEBTYPE_PROCESS_START, NEBFLAG_NONE, NEBATTR_NONE, NULL);\n#endif\n\n\t\t\t/* initialize status data unless we're starting */\n\t\t\tif(sigrestart == FALSE) {\n\t\t\t\tinitialize_status_data(config_file);\n\t\t\t\ttiming_point(\"Status data initialized\\n\");\n\t\t\t\t}\n\n\t\t\t/* initialize scheduled downtime data */\n\t\t\tinitialize_downtime_data();\n\t\t\ttiming_point(\"Downtime data initialized\\n\");\n\n\t\t\t/* read initial service and host state information */\n\t\t\tinitialize_retention_data(config_file);\n\t\t\ttiming_point(\"Retention data initialized\\n\");\n\t\t\tread_initial_state_information();\n\t\t\ttiming_point(\"Initial state information read\\n\");\n\n\t\t\t/* initialize comment data */\n\t\t\tinitialize_comment_data();\n\t\t\ttiming_point(\"Comment data initialized\\n\");\n\n\t\t\t/* initialize performance data */\n\t\t\tinitialize_performance_data(config_file);\n\t\t\ttiming_point(\"Performance data initialized\\n\");\n\n\t\t\t/* initialize the event timing loop */\n\t\t\tinit_timing_loop();\n\t\t\ttiming_point(\"Event timing loop initialized\\n\");\n\n\t\t\t/* initialize check statistics */\n\t\t\tinit_check_stats();\n\t\t\ttiming_point(\"check stats initialized\\n\");\n\n\t\t\t/* check for updates */\n\t\t\tcheck_for_nagios_updates(FALSE, TRUE);\n\t\t\ttiming_point(\"Update check concluded\\n\");\n\n\t\t\t/* update all status data (with retained information) */\n\t\t\tupdate_all_status_data();\n\t\t\ttiming_point(\"Status data updated\\n\");\n\n\t\t\t/* log initial host and service state */\n\t\t\tlog_host_states(INITIAL_STATES, NULL);\n\t\t\tlog_service_states(INITIAL_STATES, NULL);\n\t\t\ttiming_point(\"Initial states logged\\n\");\n\n\t\t\t/* reset the restart flag */\n\t\t\tsigrestart = FALSE;\n\n\t\t\t/* fire up command file worker */\n\t\t\tlaunch_command_file_worker();\n\t\t\ttiming_point(\"Command file worker launched\\n\");\n\n#ifdef USE_EVENT_BROKER\n\t\t\t/* send program data to broker */\n\t\t\tbroker_program_state(NEBTYPE_PROCESS_EVENTLOOPSTART, NEBFLAG_NONE, NEBATTR_NONE, NULL);\n#endif\n\n\t\t\t/* get event start time and save as macro */\n\t\t\tevent_start = time(NULL);\n\t\t\tmy_free(mac->x[MACRO_EVENTSTARTTIME]);\n\t\t\tasprintf(&mac->x[MACRO_EVENTSTARTTIME], \"%llu\", (unsigned long long)event_start);\n\n\t\t\ttiming_point(\"Entering event execution loop\\n\");\n\t\t\t/***** start monitoring all services *****/\n\t\t\t/* (doesn't return until a restart or shutdown signal is encountered) */\n\t\t\tevent_execution_loop();\n\n\t\t\t/*\n\t\t\t * immediately deinitialize the query handler so it\n\t\t\t * can remove modules that have stashed data with it\n\t\t\t */\n\t\t\tqh_deinit(qh_socket_path ? qh_socket_path : DEFAULT_QUERY_SOCKET);\n\n\t\t\t/* 03/01/2007 EG Moved from sighandler() to prevent FUTEX locking problems under NPTL */\n\t\t\t/* 03/21/2007 EG SIGSEGV signals are still logged in sighandler() so we don't loose them */\n\t\t\t/* did we catch a signal? */\n\t\t\tif(caught_signal == TRUE) {\n\n\t\t\t\tif(sig_id == SIGHUP)\n\t\t\t\t\tlogit(NSLOG_PROCESS_INFO, TRUE, \"Caught SIGHUP, restarting...\\n\");\n\n\t\t\t\t}\n\n#ifdef USE_EVENT_BROKER\n\t\t\t/* send program data to broker */\n\t\t\tbroker_program_state(NEBTYPE_PROCESS_EVENTLOOPEND, NEBFLAG_NONE, NEBATTR_NONE, NULL);\n\t\t\tif(sigshutdown == TRUE)\n\t\t\t\tbroker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_USER_INITIATED, NEBATTR_SHUTDOWN_NORMAL, NULL);\n\t\t\telse if(sigrestart == TRUE)\n\t\t\t\tbroker_program_state(NEBTYPE_PROCESS_RESTART, NEBFLAG_USER_INITIATED, NEBATTR_RESTART_NORMAL, NULL);\n#endif\n\n\t\t\t/* save service and host state information */\n\t\t\tsave_state_information(FALSE);\n\t\t\tcleanup_retention_data();\n\n\t\t\t/* clean up performance data */\n\t\t\tcleanup_performance_data();\n\n\t\t\t/* clean up the scheduled downtime data */\n\t\t\tcleanup_downtime_data();\n\n\t\t\t/* clean up the status data unless we're restarting */\n\t\t\tif(sigrestart == FALSE) {\n\t\t\t\tcleanup_status_data(TRUE);\n\t\t\t\t}\n\n\t\t\tfree_worker_memory(WPROC_FORCE);\n\t\t\t/* shutdown stuff... */\n\t\t\tif(sigshutdown == TRUE) {\n\t\t\t\tiobroker_destroy(nagios_iobs, IOBROKER_CLOSE_SOCKETS);\n\t\t\t\tnagios_iobs = NULL;\n\n\t\t\t\t/* log a shutdown message */\n\t\t\t\tlogit(NSLOG_PROCESS_INFO, TRUE, \"Successfully shutdown... (PID=%d)\\n\", (int)getpid());\n\t\t\t\t}\n\n\t\t\t/* clean up after ourselves */\n\t\t\tcleanup();\n\n\t\t\t/* close debug log */\n\t\t\tclose_debug_log();\n\n\t\t\t}\n\t\twhile(sigrestart == TRUE && sigshutdown == FALSE);\n\n\t\tif(daemon_mode == TRUE)\n\t\t\tunlink(lock_file);\n\n\t\t/* free misc memory */\n\t\tmy_free(lock_file);\n\t\tmy_free(config_file);\n\t\tmy_free(config_file_dir);\n\t\tmy_free(nagios_binary_path);\n\t\t}\n\n\treturn OK;\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-665', 'CWE-284'], 'message': 'halfway revert hack/configure changes - switch order of daemon_init/drop_privileges'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int link_pipe(struct pipe_inode_info *ipipe,\n\t\t struct pipe_inode_info *opipe,\n\t\t size_t len, unsigned int flags)\n{\n\tstruct pipe_buffer *ibuf, *obuf;\n\tint ret = 0, i = 0, nbuf;\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\t/*\n\t\t * If we have iterated all input buffers or ran out of\n\t\t * output room, break.\n\t\t */\n\t\tif (i >= ipipe->nrbufs || opipe->nrbufs >= opipe->buffers)\n\t\t\tbreak;\n\n\t\tibuf = ipipe->bufs + ((ipipe->curbuf + i) & (ipipe->buffers-1));\n\t\tnbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);\n\n\t\t/*\n\t\t * Get a reference to this pipe buffer,\n\t\t * so we can copy the contents over.\n\t\t */\n\t\tpipe_buf_get(ipipe, ibuf);\n\n\t\tobuf = opipe->bufs + nbuf;\n\t\t*obuf = *ibuf;\n\n\t\t/*\n\t\t * Don't inherit the gift flag, we need to\n\t\t * prevent multiple steals of this page.\n\t\t */\n\t\tobuf->flags &= ~PIPE_BUF_FLAG_GIFT;\n\n\t\tif (obuf->len > len)\n\t\t\tobuf->len = len;\n\n\t\topipe->nrbufs++;\n\t\tret += obuf->len;\n\t\tlen -= obuf->len;\n\t\ti++;\n\t} while (len);\n\n\t/*\n\t * return EAGAIN if we have the potential of some data in the\n\t * future, otherwise just return 0\n\t */\n\tif (!ret && ipipe->waiting_writers && (flags & SPLICE_F_NONBLOCK))\n\t\tret = -EAGAIN;\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\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 vorbis_header(AVFormatContext *s, int idx)\n{\n struct ogg *ogg = s->priv_data;\n AVStream *st = s->streams[idx];\n struct ogg_stream *os = ogg->streams + idx;\n struct oggvorbis_private *priv;\n int pkt_type = os->buf[os->pstart];\n\n if (!os->private) {\n os->private = av_mallocz(sizeof(struct oggvorbis_private));\n if (!os->private)\n return AVERROR(ENOMEM);\n }\n\n if (!(pkt_type & 1))\n return 0;\n\n if (os->psize < 1 || pkt_type > 5)\n return AVERROR_INVALIDDATA;\n\n priv = os->private;\n\n if (priv->packet[pkt_type >> 1])\n return AVERROR_INVALIDDATA;\n if (pkt_type > 1 && !priv->packet[0] || pkt_type > 3 && !priv->packet[1])\n return AVERROR_INVALIDDATA;\n\n priv->len[pkt_type >> 1] = os->psize;\n priv->packet[pkt_type >> 1] = av_mallocz(os->psize);\n if (!priv->packet[pkt_type >> 1])\n return AVERROR(ENOMEM);\n memcpy(priv->packet[pkt_type >> 1], os->buf + os->pstart, os->psize);\n if (os->buf[os->pstart] == 1) {\n const uint8_t *p = os->buf + os->pstart + 7; /* skip \"\\001vorbis\" tag */\n unsigned blocksize, bs0, bs1;\n int srate;\n int channels;\n\n if (os->psize != 30)\n return AVERROR_INVALIDDATA;\n\n if (bytestream_get_le32(&p) != 0) /* vorbis_version */\n return AVERROR_INVALIDDATA;\n\n channels = bytestream_get_byte(&p);\n if (st->codec->channels && channels != st->codec->channels) {\n av_log(s, AV_LOG_ERROR, \"Channel change is not supported\\n\");\n return AVERROR_PATCHWELCOME;\n }\n st->codec->channels = channels;\n srate = bytestream_get_le32(&p);\n p += 4; // skip maximum bitrate\n st->codec->bit_rate = bytestream_get_le32(&p); // nominal bitrate\n p += 4; // skip minimum bitrate\n\n blocksize = bytestream_get_byte(&p);\n bs0 = blocksize & 15;\n bs1 = blocksize >> 4;\n\n if (bs0 > bs1)\n return AVERROR_INVALIDDATA;\n if (bs0 < 6 || bs1 > 13)\n return AVERROR_INVALIDDATA;\n\n if (bytestream_get_byte(&p) != 1) /* framing_flag */\n return AVERROR_INVALIDDATA;\n\n st->codec->codec_type = AVMEDIA_TYPE_AUDIO;\n st->codec->codec_id = AV_CODEC_ID_VORBIS;\n\n if (srate > 0) {\n st->codec->sample_rate = srate;\n avpriv_set_pts_info(st, 64, 1, srate);\n }\n } else if (os->buf[os->pstart] == 3) {\n if (vorbis_update_metadata(s, idx) >= 0) {\n // drop all metadata we parsed and which is not required by libvorbis\n unsigned new_len = 7 + 4 + AV_RL32(priv->packet[1] + 7) + 4 + 1;\n if (new_len >= 16 && new_len < os->psize) {\n AV_WL32(priv->packet[1] + new_len - 5, 0);\n priv->packet[1][new_len - 1] = 1;\n priv->len[1] = new_len;\n }\n }\n } else {\n int ret = fixup_vorbis_headers(s, priv, &st->codec->extradata);\n if (ret < 0) {\n st->codec->extradata_size = 0;\n return ret;\n }\n st->codec->extradata_size = ret;\n if ((ret = avpriv_vorbis_parse_extradata(st->codec, &priv->vp))) {\n av_freep(&st->codec->extradata);\n st->codec->extradata_size = 0;\n return ret;\n }\n }\n\n return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'avformat/oggparsevorbis: check packet size before reading new_len from it\n\nFixes out of array read\nFixes: 34260c7981118fb38fba61809bf4dd5a-asan_heap-oob_93b923_1508_cov_951051643_DivX640x480_oggvorbis.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: ext4_xattr_put_super(struct super_block *sb)\n{\n\tmb_cache_shrink(sb->s_bdev);\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: static long ion_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)\n{\n\tstruct ion_client *client = filp->private_data;\n\tstruct ion_device *dev = client->dev;\n\tstruct ion_handle *cleanup_handle = NULL;\n\tint ret = 0;\n\tunsigned int dir;\n\n\tunion {\n\t\tstruct ion_fd_data fd;\n\t\tstruct ion_allocation_data allocation;\n\t\tstruct ion_handle_data handle;\n\t\tstruct ion_custom_data custom;\n\t} data;\n\n\tdir = ion_ioctl_dir(cmd);\n\n\tif (_IOC_SIZE(cmd) > sizeof(data))\n\t\treturn -EINVAL;\n\n\tif (dir & _IOC_WRITE)\n\t\tif (copy_from_user(&data, (void __user *)arg, _IOC_SIZE(cmd)))\n\t\t\treturn -EFAULT;\n\n\tswitch (cmd) {\n\tcase ION_IOC_ALLOC:\n\t{\n\t\tstruct ion_handle *handle;\n\n\t\thandle = ion_alloc(client, data.allocation.len,\n\t\t\t\t\t\tdata.allocation.align,\n\t\t\t\t\t\tdata.allocation.heap_id_mask,\n\t\t\t\t\t\tdata.allocation.flags);\n\t\tif (IS_ERR(handle))\n\t\t\treturn PTR_ERR(handle);\n\n\t\tdata.allocation.handle = handle->id;\n\n\t\tcleanup_handle = handle;\n\t\tbreak;\n\t}\n\tcase ION_IOC_FREE:\n\t{\n\t\tstruct ion_handle *handle;\n\n\t\thandle = ion_handle_get_by_id(client, data.handle.handle);\n\t\tif (IS_ERR(handle))\n\t\t\treturn PTR_ERR(handle);\n\t\tion_free(client, handle);\n\t\tion_handle_put(handle);\n\t\tbreak;\n\t}\n\tcase ION_IOC_SHARE:\n\tcase ION_IOC_MAP:\n\t{\n\t\tstruct ion_handle *handle;\n\n\t\thandle = ion_handle_get_by_id(client, data.handle.handle);\n\t\tif (IS_ERR(handle))\n\t\t\treturn PTR_ERR(handle);\n\t\tdata.fd.fd = ion_share_dma_buf_fd(client, handle);\n\t\tion_handle_put(handle);\n\t\tif (data.fd.fd < 0)\n\t\t\tret = data.fd.fd;\n\t\tbreak;\n\t}\n\tcase ION_IOC_IMPORT:\n\t{\n\t\tstruct ion_handle *handle;\n\n\t\thandle = ion_import_dma_buf_fd(client, data.fd.fd);\n\t\tif (IS_ERR(handle))\n\t\t\tret = PTR_ERR(handle);\n\t\telse\n\t\t\tdata.handle.handle = handle->id;\n\t\tbreak;\n\t}\n\tcase ION_IOC_SYNC:\n\t{\n\t\tret = ion_sync_for_device(client, data.fd.fd);\n\t\tbreak;\n\t}\n\tcase ION_IOC_CUSTOM:\n\t{\n\t\tif (!dev->custom_ioctl)\n\t\t\treturn -ENOTTY;\n\t\tret = dev->custom_ioctl(client, data.custom.cmd,\n\t\t\t\t\t\tdata.custom.arg);\n\t\tbreak;\n\t}\n\tdefault:\n\t\treturn -ENOTTY;\n\t}\n\n\tif (dir & _IOC_READ) {\n\t\tif (copy_to_user((void __user *)arg, &data, _IOC_SIZE(cmd))) {\n\t\t\tif (cleanup_handle)\n\t\t\t\tion_free(client, cleanup_handle);\n\t\t\treturn -EFAULT;\n\t\t}\n\t}\n\treturn ret;\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: hash_new_from_values(mrb_state *mrb, mrb_int argc, mrb_value *regs)\n{\n mrb_value hash = mrb_hash_new_capa(mrb, argc);\n while (argc--) {\n mrb_hash_set(mrb, hash, regs[0], regs[1]);\n regs += 2;\n }\n return hash;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'vm.c (hash_new_from_regs): stack may be reallocated.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: juniper_services_print(netdissect_options *ndo,\n const struct pcap_pkthdr *h, register const u_char *p)\n{\n struct juniper_l2info_t l2info;\n struct juniper_services_header {\n uint8_t svc_id;\n uint8_t flags_len;\n uint8_t svc_set_id[2];\n uint8_t dir_iif[4];\n };\n const struct juniper_services_header *sh;\n\n l2info.pictype = DLT_JUNIPER_SERVICES;\n if (juniper_parse_header(ndo, p, h, &l2info) == 0)\n return l2info.header_len;\n\n p+=l2info.header_len;\n sh = (const struct juniper_services_header *)p;\n\n if (ndo->ndo_eflag)\n ND_PRINT((ndo, \"service-id %u flags 0x%02x service-set-id 0x%04x iif %u: \",\n sh->svc_id,\n sh->flags_len,\n EXTRACT_16BITS(&sh->svc_set_id),\n EXTRACT_24BITS(&sh->dir_iif[1])));\n\n /* no proto field - lets guess by first byte of IP header*/\n ip_heuristic_guess (ndo, p, l2info.length);\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-12993/Juniper: Add more bounds checks.\n\nThis fixes a buffer over-read discovered by Kamil Frankowicz.\n\nAdd tests using the capture files supplied by the reporter(s).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Compute(OpKernelContext* context) override {\n const Tensor& input = context->input(0);\n const TensorShape& input_shape = input.shape();\n const int32_t input_dims = input_shape.dims();\n\n const Tensor& segment_id = context->input(1);\n const TensorShape& segment_id_shape = segment_id.shape();\n const int32_t segment_dims = segment_id_shape.dims();\n\n const Tensor& num_segments_tensor = context->input(2);\n OP_REQUIRES(context, num_segments_tensor.NumElements() != 0,\n errors::InvalidArgument(\"Number of segments cannot be empty.\"));\n auto num_segments = num_segments_tensor.scalar()();\n\n OP_REQUIRES(context, segment_dims != 0,\n errors::InvalidArgument(\"Segment_id cannot have rank 0\"));\n\n OP_REQUIRES(\n context, segment_dims <= input_dims,\n errors::OutOfRange(\"Invalid segment_id rank \", segment_dims,\n \" for input with \", input_dims, \" dimension(s)\"));\n for (auto i = 0; i < segment_dims; i++) {\n OP_REQUIRES(\n context, segment_id_shape.dim_size(i) == input_shape.dim_size(i),\n errors::InvalidArgument(\n \"Segment dimension is \", segment_id_shape.dim_size(i),\n \" while input dimension is \", input_dims, \" in rank \", i));\n }\n\n // Making output tensor.\n Tensor* output_tensor = nullptr;\n TensorShape output_shape =\n GetOutputShape(input_shape, segment_id_shape, num_segments);\n OP_REQUIRES_OK(context, context->allocate_output(\"output\", output_shape,\n &output_tensor));\n\n // Preparating flat tensors.\n auto output_flat = output_tensor->flat();\n auto flat_segment_id = segment_id.flat();\n auto flat_input = input.flat();\n\n for (int i = 0; i < flat_segment_id.size(); i++) {\n OP_REQUIRES(\n context,\n ((flat_segment_id(i) < num_segments) && (flat_segment_id(i) >= 0)),\n errors::InvalidArgument(\n \"segment_ids are not allowed to exceed num_segments or\"\n \" to have negative values.\"));\n }\n\n int64_t big_stride;\n int64_t small_stride;\n std::tie(big_stride, small_stride) =\n GetStrides(input_shape, segment_id_shape);\n auto relative_offset_set =\n GetFlattenedRelativeOffsets(small_stride, big_stride);\n for (auto start_offset = 0; start_offset < big_stride; start_offset++) {\n for (auto i = 0; i < relative_offset_set.size(); i++) {\n auto output_index = start_offset + flat_segment_id(i) * big_stride;\n auto offset = start_offset + relative_offset_set[i];\n if (output_flat(output_index).length() != 0)\n output_flat(output_index).append(separator_.c_str());\n output_flat(output_index).append(flat_input(offset));\n }\n }\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-703'], 'message': 'Validate `num_segments > 0` in `unsorted_segment_join`\n\nFixes #55305\n\nPiperOrigin-RevId: 442047005'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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 DetectRunCleanup(DetectEngineThreadCtx *det_ctx,\n Packet *p, Flow * const pflow)\n{\n PACKET_PROFILING_DETECT_START(p, PROF_DETECT_CLEANUP);\n /* cleanup pkt specific part of the patternmatcher */\n PacketPatternCleanup(det_ctx);\n\n if (pflow != NULL) {\n /* update inspected tracker for raw reassembly */\n if (p->proto == IPPROTO_TCP && pflow->protoctx != NULL) {\n StreamReassembleRawUpdateProgress(pflow->protoctx, p,\n det_ctx->raw_stream_progress);\n\n DetectEngineCleanHCBDBuffers(det_ctx);\n }\n }\n PACKET_PROFILING_DETECT_END(p, PROF_DETECT_CLEANUP);\n SCReturn;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-347'], 'message': 'stream: fix false negative on bad RST\n\nIf a bad RST was received the stream inspection would not happen\nfor that packet, but it would still move the 'raw progress' tracker\nforward. Following good packets would then fail to detect anything\nbefore the 'raw progress' position.\n\nBug #2770\n\nReported-by: Alexey Vishnyakov'" }, { "text": "[INST] Given the following code containing errors, provide Common 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_volume(Volume_handle ch) {\n\n bool OK = true;\n int index;\n char cc;\n\n in >> index;\n OK = OK && test_string(\"{\");\n\n in >> cc;\n while(isdigit(cc)) {\n in.putback(cc);\n in >> index;\n ch->shell_entry_objects().push_back(make_object(SFace_of[index]));\n in >> cc;\n }\n in >> ch->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: 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\tkfree_skb(skb);\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-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: StringMatching::~StringMatching() {\n\t// TODO Auto-generated destructor stub\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: string_255 topicName() const\n {\n return topic_name_;\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: \nstatic void\nyydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, void *yyscanner, RE_LEX_ENVIRONMENT *lex_env)\n{\n YYUSE (yyvaluep);\n YYUSE (yyscanner);\n YYUSE (lex_env);\n if (!yymsg)\n yymsg = \"Deleting\";\n YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);\n\n YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN\n switch (yytype)\n {\n case 6: /* _CLASS_ */\n#line 96 \"re_grammar.y\" /* yacc.c:1257 */\n { yr_free(((*yyvaluep).class_vector)); }\n#line 1045 \"re_grammar.c\" /* yacc.c:1257 */\n break;\n\n case 26: /* alternative */\n#line 97 \"re_grammar.y\" /* yacc.c:1257 */\n { yr_re_node_destroy(((*yyvaluep).re_node)); }\n#line 1051 \"re_grammar.c\" /* yacc.c:1257 */\n break;\n\n case 27: /* concatenation */\n#line 98 \"re_grammar.y\" /* yacc.c:1257 */\n { yr_re_node_destroy(((*yyvaluep).re_node)); }\n#line 1057 \"re_grammar.c\" /* yacc.c:1257 */\n break;\n\n case 28: /* repeat */\n#line 99 \"re_grammar.y\" /* yacc.c:1257 */\n { yr_re_node_destroy(((*yyvaluep).re_node)); }\n#line 1063 \"re_grammar.c\" /* yacc.c:1257 */\n break;\n\n case 29: /* single */\n#line 100 \"re_grammar.y\" /* yacc.c:1257 */\n { yr_re_node_destroy(((*yyvaluep).re_node)); }\n#line 1069 \"re_grammar.c\" /* yacc.c:1257 */\n break;\n\n\n default:\n break;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-674', 'CWE-787'], 'message': 'Fix issue #674. Move regexp limits to limits.h.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: dwg_free_object (Dwg_Object *obj)\n{\n int error = 0;\n long unsigned int j;\n Dwg_Data *dwg;\n Bit_Chain *dat = &pdat;\n\n if (obj && obj->parent)\n {\n dwg = obj->parent;\n dat->version = dwg->header.version;\n }\n else\n return;\n if (obj->type == DWG_TYPE_FREED || obj->tio.object == NULL)\n return;\n dat->from_version = dat->version;\n if (obj->supertype == DWG_SUPERTYPE_UNKNOWN)\n goto unhandled;\n\n switch (obj->type)\n {\n case DWG_TYPE_TEXT:\n dwg_free_TEXT (dat, obj);\n break;\n case DWG_TYPE_ATTRIB:\n dwg_free_ATTRIB (dat, obj);\n break;\n case DWG_TYPE_ATTDEF:\n dwg_free_ATTDEF (dat, obj);\n break;\n case DWG_TYPE_BLOCK:\n dwg_free_BLOCK (dat, obj);\n break;\n case DWG_TYPE_ENDBLK:\n dwg_free_ENDBLK (dat, obj);\n break;\n case DWG_TYPE_SEQEND:\n dwg_free_SEQEND (dat, obj);\n break;\n case DWG_TYPE_INSERT:\n dwg_free_INSERT (dat, obj);\n break;\n case DWG_TYPE_MINSERT:\n dwg_free_MINSERT (dat, obj);\n break;\n case DWG_TYPE_VERTEX_2D:\n dwg_free_VERTEX_2D (dat, obj);\n break;\n case DWG_TYPE_VERTEX_3D:\n dwg_free_VERTEX_3D (dat, obj);\n break;\n case DWG_TYPE_VERTEX_MESH:\n dwg_free_VERTEX_MESH (dat, obj);\n break;\n case DWG_TYPE_VERTEX_PFACE:\n dwg_free_VERTEX_PFACE (dat, obj);\n break;\n case DWG_TYPE_VERTEX_PFACE_FACE:\n dwg_free_VERTEX_PFACE_FACE (dat, obj);\n break;\n case DWG_TYPE_POLYLINE_2D:\n dwg_free_POLYLINE_2D (dat, obj);\n break;\n case DWG_TYPE_POLYLINE_3D:\n dwg_free_POLYLINE_3D (dat, obj);\n break;\n case DWG_TYPE_ARC:\n dwg_free_ARC (dat, obj);\n break;\n case DWG_TYPE_CIRCLE:\n dwg_free_CIRCLE (dat, obj);\n break;\n case DWG_TYPE_LINE:\n dwg_free_LINE (dat, obj);\n break;\n case DWG_TYPE_DIMENSION_ORDINATE:\n dwg_free_DIMENSION_ORDINATE (dat, obj);\n break;\n case DWG_TYPE_DIMENSION_LINEAR:\n dwg_free_DIMENSION_LINEAR (dat, obj);\n break;\n case DWG_TYPE_DIMENSION_ALIGNED:\n dwg_free_DIMENSION_ALIGNED (dat, obj);\n break;\n case DWG_TYPE_DIMENSION_ANG3PT:\n dwg_free_DIMENSION_ANG3PT (dat, obj);\n break;\n case DWG_TYPE_DIMENSION_ANG2LN:\n dwg_free_DIMENSION_ANG2LN (dat, obj);\n break;\n case DWG_TYPE_DIMENSION_RADIUS:\n dwg_free_DIMENSION_RADIUS (dat, obj);\n break;\n case DWG_TYPE_DIMENSION_DIAMETER:\n dwg_free_DIMENSION_DIAMETER (dat, obj);\n break;\n case DWG_TYPE_POINT:\n dwg_free_POINT (dat, obj);\n break;\n case DWG_TYPE__3DFACE:\n dwg_free__3DFACE (dat, obj);\n break;\n case DWG_TYPE_POLYLINE_PFACE:\n dwg_free_POLYLINE_PFACE (dat, obj);\n break;\n case DWG_TYPE_POLYLINE_MESH:\n dwg_free_POLYLINE_MESH (dat, obj);\n break;\n case DWG_TYPE_SOLID:\n dwg_free_SOLID (dat, obj);\n break;\n case DWG_TYPE_TRACE:\n dwg_free_TRACE (dat, obj);\n break;\n case DWG_TYPE_SHAPE:\n dwg_free_SHAPE (dat, obj);\n break;\n case DWG_TYPE_VIEWPORT:\n dwg_free_VIEWPORT (dat, obj);\n break;\n case DWG_TYPE_ELLIPSE:\n dwg_free_ELLIPSE (dat, obj);\n break;\n case DWG_TYPE_SPLINE:\n dwg_free_SPLINE (dat, obj);\n break;\n case DWG_TYPE_REGION:\n dwg_free_REGION (dat, obj);\n break;\n case DWG_TYPE__3DSOLID:\n dwg_free__3DSOLID (dat, obj);\n break; /* Check the type of the object */\n case DWG_TYPE_BODY:\n dwg_free_BODY (dat, obj);\n break;\n case DWG_TYPE_RAY:\n dwg_free_RAY (dat, obj);\n break;\n case DWG_TYPE_XLINE:\n dwg_free_XLINE (dat, obj);\n break;\n case DWG_TYPE_DICTIONARY:\n dwg_free_DICTIONARY (dat, obj);\n break;\n case DWG_TYPE_MTEXT:\n dwg_free_MTEXT (dat, obj);\n break;\n case DWG_TYPE_LEADER:\n dwg_free_LEADER (dat, obj);\n break;\n case DWG_TYPE_TOLERANCE:\n dwg_free_TOLERANCE (dat, obj);\n break;\n case DWG_TYPE_MLINE:\n dwg_free_MLINE (dat, obj);\n break;\n case DWG_TYPE_BLOCK_CONTROL:\n dwg_free_BLOCK_CONTROL (dat, obj);\n break;\n case DWG_TYPE_BLOCK_HEADER:\n dwg_free_BLOCK_HEADER (dat, obj);\n break;\n case DWG_TYPE_LAYER_CONTROL:\n dwg_free_LAYER_CONTROL (dat, obj);\n break;\n case DWG_TYPE_LAYER:\n dwg_free_LAYER (dat, obj);\n break;\n case DWG_TYPE_STYLE_CONTROL:\n dwg_free_STYLE_CONTROL (dat, obj);\n break;\n case DWG_TYPE_STYLE:\n dwg_free_STYLE (dat, obj);\n break;\n case DWG_TYPE_LTYPE_CONTROL:\n dwg_free_LTYPE_CONTROL (dat, obj);\n break;\n case DWG_TYPE_LTYPE:\n dwg_free_LTYPE (dat, obj);\n break;\n case DWG_TYPE_VIEW_CONTROL:\n dwg_free_VIEW_CONTROL (dat, obj);\n break;\n case DWG_TYPE_VIEW:\n dwg_free_VIEW (dat, obj);\n break;\n case DWG_TYPE_UCS_CONTROL:\n dwg_free_UCS_CONTROL (dat, obj);\n break;\n case DWG_TYPE_UCS:\n dwg_free_UCS (dat, obj);\n break;\n case DWG_TYPE_VPORT_CONTROL:\n dwg_free_VPORT_CONTROL (dat, obj);\n break;\n case DWG_TYPE_VPORT:\n dwg_free_VPORT (dat, obj);\n break;\n case DWG_TYPE_APPID_CONTROL:\n dwg_free_APPID_CONTROL (dat, obj);\n break;\n case DWG_TYPE_APPID:\n dwg_free_APPID (dat, obj);\n break;\n case DWG_TYPE_DIMSTYLE_CONTROL:\n dwg_free_DIMSTYLE_CONTROL (dat, obj);\n break;\n case DWG_TYPE_DIMSTYLE:\n dwg_free_DIMSTYLE (dat, obj);\n break;\n case DWG_TYPE_VPORT_ENTITY_CONTROL:\n dwg_free_VPORT_ENTITY_CONTROL (dat, obj);\n break;\n case DWG_TYPE_VPORT_ENTITY_HEADER:\n dwg_free_VPORT_ENTITY_HEADER (dat, obj);\n break;\n case DWG_TYPE_GROUP:\n dwg_free_GROUP (dat, obj);\n break;\n case DWG_TYPE_MLINESTYLE:\n dwg_free_MLINESTYLE (dat, obj);\n break;\n case DWG_TYPE_OLE2FRAME:\n dwg_free_OLE2FRAME (dat, obj);\n break;\n case DWG_TYPE_DUMMY:\n dwg_free_DUMMY (dat, obj);\n break;\n case DWG_TYPE_LONG_TRANSACTION:\n dwg_free_LONG_TRANSACTION (dat, obj);\n break;\n case DWG_TYPE_LWPOLYLINE:\n dwg_free_LWPOLYLINE (dat, obj);\n break;\n case DWG_TYPE_HATCH:\n dwg_free_HATCH (dat, obj);\n break;\n case DWG_TYPE_XRECORD:\n dwg_free_XRECORD (dat, obj);\n break;\n case DWG_TYPE_PLACEHOLDER:\n dwg_free_PLACEHOLDER (dat, obj);\n break;\n case DWG_TYPE_OLEFRAME:\n dwg_free_OLEFRAME (dat, obj);\n break;\n#ifdef DEBUG_VBA_PROJECT\n case DWG_TYPE_VBA_PROJECT:\n dwg_free_VBA_PROJECT (dat, obj);\n break;\n#endif\n case DWG_TYPE_LAYOUT:\n dwg_free_LAYOUT (dat, obj);\n break;\n case DWG_TYPE_PROXY_ENTITY:\n dwg_free_PROXY_ENTITY (dat, obj);\n break;\n case DWG_TYPE_PROXY_OBJECT:\n dwg_free_PROXY_OBJECT (dat, obj);\n break;\n default:\n if (obj->type == obj->parent->layout_type)\n {\n SINCE (R_13)\n {\n dwg_free_LAYOUT (dat, obj); // XXX avoid double-free, esp. in eed\n }\n }\n\n else if ((error = dwg_free_variable_type (obj->parent, obj))\n & DWG_ERR_UNHANDLEDCLASS)\n {\n int is_entity;\n int i;\n Dwg_Class *klass;\n\n unhandled:\n is_entity = 0;\n i = obj->type - 500;\n klass = NULL;\n\n dwg = obj->parent;\n if (dwg->dwg_class && i >= 0 && i < (int)dwg->num_classes)\n {\n klass = &dwg->dwg_class[i];\n is_entity = klass ? dwg_class_is_entity (klass) : 0;\n }\n // indxf (and later injson) already creates some DEBUGGING classes\n if (obj->fixedtype == DWG_TYPE_TABLE)\n {\n // just the preview, i.e. common. plus some colors: leak\n dwg_free_UNKNOWN_ENT (dat, obj);\n }\n else if (obj->fixedtype == DWG_TYPE_DATATABLE)\n {\n dwg_free_UNKNOWN_OBJ (dat, obj);\n }\n else if (klass && !is_entity)\n {\n dwg_free_UNKNOWN_OBJ (dat, obj);\n }\n else if (klass && is_entity)\n {\n dwg_free_UNKNOWN_ENT (dat, obj);\n }\n else // not a class\n {\n FREE_IF (obj->tio.unknown);\n }\n }\n }\n /* With this importer the dxfname is dynamic, just the name is const */\n if (dwg->opts & DWG_OPTS_INDXF)\n FREE_IF (obj->dxfname);\n obj->type = DWG_TYPE_FREED;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'cleanup tio.unknown\n\nnot needed anymore, we only have UNKNOWN_OBJ or UNKNOWN_ENT with full common\nentity_data.\nFixes GH #178 heap_overflow2'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,\n\t\t\t\t unsigned long arg)\n{\n\tstruct mm_struct *mm = ctx->mm;\n\tstruct vm_area_struct *vma, *prev, *cur;\n\tint ret;\n\tstruct uffdio_range uffdio_unregister;\n\tunsigned long new_flags;\n\tbool found;\n\tunsigned long start, end, vma_end;\n\tconst void __user *buf = (void __user *)arg;\n\n\tret = -EFAULT;\n\tif (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))\n\t\tgoto out;\n\n\tret = validate_range(mm, uffdio_unregister.start,\n\t\t\t uffdio_unregister.len);\n\tif (ret)\n\t\tgoto out;\n\n\tstart = uffdio_unregister.start;\n\tend = start + uffdio_unregister.len;\n\n\tret = -ENOMEM;\n\tif (!mmget_not_zero(mm))\n\t\tgoto out;\n\n\tdown_write(&mm->mmap_sem);\n\tvma = find_vma_prev(mm, start, &prev);\n\tif (!vma)\n\t\tgoto out_unlock;\n\n\t/* check that there's at least one vma in the range */\n\tret = -EINVAL;\n\tif (vma->vm_start >= end)\n\t\tgoto out_unlock;\n\n\t/*\n\t * If the first vma contains huge pages, make sure start address\n\t * is aligned to huge page size.\n\t */\n\tif (is_vm_hugetlb_page(vma)) {\n\t\tunsigned long vma_hpagesize = vma_kernel_pagesize(vma);\n\n\t\tif (start & (vma_hpagesize - 1))\n\t\t\tgoto out_unlock;\n\t}\n\n\t/*\n\t * Search for not compatible vmas.\n\t */\n\tfound = false;\n\tret = -EINVAL;\n\tfor (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {\n\t\tcond_resched();\n\n\t\tBUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^\n\t\t !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));\n\n\t\t/*\n\t\t * Check not compatible vmas, not strictly required\n\t\t * here as not compatible vmas cannot have an\n\t\t * userfaultfd_ctx registered on them, but this\n\t\t * provides for more strict behavior to notice\n\t\t * unregistration errors.\n\t\t */\n\t\tif (!vma_can_userfault(cur))\n\t\t\tgoto out_unlock;\n\n\t\tfound = true;\n\t}\n\tBUG_ON(!found);\n\n\tif (vma->vm_start < start)\n\t\tprev = vma;\n\n\tret = 0;\n\tdo {\n\t\tcond_resched();\n\n\t\tBUG_ON(!vma_can_userfault(vma));\n\n\t\t/*\n\t\t * Nothing to do: this vma is already registered into this\n\t\t * userfaultfd and with the right tracking mode too.\n\t\t */\n\t\tif (!vma->vm_userfaultfd_ctx.ctx)\n\t\t\tgoto skip;\n\n\t\tif (vma->vm_start > start)\n\t\t\tstart = vma->vm_start;\n\t\tvma_end = min(end, vma->vm_end);\n\n\t\tif (userfaultfd_missing(vma)) {\n\t\t\t/*\n\t\t\t * Wake any concurrent pending userfault while\n\t\t\t * we unregister, so they will not hang\n\t\t\t * permanently and it avoids userland to call\n\t\t\t * UFFDIO_WAKE explicitly.\n\t\t\t */\n\t\t\tstruct userfaultfd_wake_range range;\n\t\t\trange.start = start;\n\t\t\trange.len = vma_end - start;\n\t\t\twake_userfault(vma->vm_userfaultfd_ctx.ctx, &range);\n\t\t}\n\n\t\tnew_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);\n\t\tprev = vma_merge(mm, prev, start, vma_end, new_flags,\n\t\t\t\t vma->anon_vma, vma->vm_file, vma->vm_pgoff,\n\t\t\t\t vma_policy(vma),\n\t\t\t\t NULL_VM_UFFD_CTX);\n\t\tif (prev) {\n\t\t\tvma = prev;\n\t\t\tgoto next;\n\t\t}\n\t\tif (vma->vm_start < start) {\n\t\t\tret = split_vma(mm, vma, start, 1);\n\t\t\tif (ret)\n\t\t\t\tbreak;\n\t\t}\n\t\tif (vma->vm_end > end) {\n\t\t\tret = split_vma(mm, vma, end, 0);\n\t\t\tif (ret)\n\t\t\t\tbreak;\n\t\t}\n\tnext:\n\t\t/*\n\t\t * In the vma_merge() successful mprotect-like case 8:\n\t\t * the next vma was merged into the current one and\n\t\t * the current one has not been updated yet.\n\t\t */\n\t\tvma->vm_flags = new_flags;\n\t\tvma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;\n\n\tskip:\n\t\tprev = vma;\n\t\tstart = vma->vm_end;\n\t\tvma = vma->vm_next;\n\t} while (vma && vma->vm_start < end);\nout_unlock:\n\tup_write(&mm->mmap_sem);\n\tmmput(mm);\nout:\n\treturn ret;\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: inline bool ResolveAxis(const int num_dims, const int* axis,\n const int64_t num_axis, int* out_axis,\n int* out_num_axis) {\n *out_num_axis = 0; // Just in case.\n // Short-circuit axis resolution for scalars; the axis will go unused.\n if (num_dims == 0) {\n return true;\n }\n // o(n^2) is fine since out_num_axis should be really small, mostly <= 4\n for (int64_t idx = 0; idx < num_axis; ++idx) {\n // Handle negative index. A positive index 'p_idx' can be represented as a\n // negative index 'n_idx' as: n_idx = p_idx-num_dims\n // eg: For num_dims=3, [0, 1, 2] is the same as [-3, -2, -1] */\n int current = axis[idx] < 0 ? (axis[idx] + num_dims) : axis[idx];\n TFLITE_DCHECK(current >= 0 && current < num_dims);\n bool is_dup = false;\n for (int j = 0; j < *out_num_axis; ++j) {\n if (out_axis[j] == current) {\n is_dup = true;\n break;\n }\n }\n if (!is_dup) {\n out_axis[*out_num_axis] = current;\n *out_num_axis += 1;\n }\n }\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': '[tflite] Ensure `ResolveAxis` properly handles negative inputs.\n\nIn Python, a list `l` of length `n` allows indexing with negative indices, `l[i]`. The only constraint is that `n + i` becomes positive. Code in `ResolveAxis` assumes the constraints and only checks it using a `DCHECK`. But the macro is a no-op in non-debug builds and that can result in reading from negative offsets (buffer underflows).\n\nPiperOrigin-RevId: 332530683\nChange-Id: I464e073fee618054ae3719a3679739007bb3f3bc'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void TestGatherNd(int* param_dims, const ParamType* param_data, int* index_dims,\n const IndexType* index_data, int* output_dims,\n ParamType* output_data,\n const ParamType* expected_output_data) {\n TfLiteIntArray* pdims = IntArrayFromInts(param_dims);\n TfLiteIntArray* idims = IntArrayFromInts(index_dims);\n TfLiteIntArray* odims = IntArrayFromInts(output_dims);\n\n constexpr int inputs_size = 2;\n constexpr int outputs_size = 1;\n constexpr int tensors_size = inputs_size + outputs_size;\n TfLiteTensor tensors[tensors_size] = {\n CreateTensor(param_data, pdims),\n CreateTensor(index_data, idims),\n CreateTensor(output_data, odims),\n };\n int inputs_array_data[] = {2, 0, 1};\n TfLiteIntArray* inputs_array = IntArrayFromInts(inputs_array_data);\n int outputs_array_data[] = {1, 2};\n TfLiteIntArray* outputs_array = IntArrayFromInts(outputs_array_data);\n\n const TfLiteRegistration registration = Register_GATHER_ND();\n micro::KernelRunner runner(registration, tensors, tensors_size, inputs_array,\n outputs_array, /*builtin_data=*/nullptr);\n TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, runner.InitAndPrepare());\n TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, runner.Invoke());\n\n // The output tensor's data and shape have been updated by the kernel.\n TfLiteTensor* actual_output_tensor = &tensors[2];\n TfLiteIntArray* actual_output_dims = actual_output_tensor->dims;\n const int output_size = ElementCount(*actual_output_dims);\n for (int i = 0; i < output_size; ++i) {\n TF_LITE_MICRO_EXPECT_EQ(expected_output_data[i], output_data[i]);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'GatherNd verifies that an index is valid before reading. (#1286)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static uint get_alen(char *arg, int default_len)\n{\n\tint\tj;\n\tint\talen;\n\n\talen = default_len;\n\tfor (j = 0; j < 8; j++) {\n\t\tif (arg[j] == '.') {\n\t\t\talen = arg[j+1] - '0';\n\t\t\tbreak;\n\t\t} else if (arg[j] == '\\0')\n\t\t\tbreak;\n\t}\n\treturn alen;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'i2c: fix stack buffer overflow vulnerability in i2c md command\n\nWhen running \"i2c md 0 0 80000100\", the function do_i2c_md parses the\nlength into an unsigned int variable named length. The value is then\nmoved to a signed variable:\n\n int nbytes = length;\n #define DISP_LINE_LEN 16\n int linebytes = (nbytes > DISP_LINE_LEN) ? DISP_LINE_LEN : nbytes;\n ret = dm_i2c_read(dev, addr, linebuf, linebytes);\n\nOn systems where integers are 32 bits wide, 0x80000100 is a negative\nvalue to \"nbytes > DISP_LINE_LEN\" is false and linebytes gets assigned\n0x80000100 instead of 16.\n\nThe consequence is that the function which reads from the i2c device\n(dm_i2c_read or i2c_read) is called with a 16-byte stack buffer to fill\nbut with a size parameter which is too large. In some cases, this could\ntrigger a crash. But with some i2c drivers, such as drivers/i2c/nx_i2c.c\n(used with \"nexell,s5pxx18-i2c\" bus), the size is actually truncated to\na 16-bit integer. This is because function i2c_transfer expects an\nunsigned short length. In such a case, an attacker who can control the\nresponse of an i2c device can overwrite the return address of a function\nand execute arbitrary code through Return-Oriented Programming.\n\nFix this issue by using unsigned integers types in do_i2c_md. While at\nit, make also alen unsigned, as signed sizes can cause vulnerabilities\nwhen people forgot to check that they can be negative.\n\nSigned-off-by: Nicolas Iooss \nReviewed-by: Heiko Schocher '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline struct old_rng_alg *crypto_old_rng_alg(struct crypto_rng *tfm)\n{\n\treturn &crypto_rng_tfm(tfm)->__crt_alg->cra_rng;\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: void grubfs_free (GrubFS *gf) {\n\tif (gf) {\n\t\tif (gf->file && gf->file->device)\n\t\t\tfree (gf->file->device->disk);\n\t\t//free (gf->file->device);\n\t\tfree (gf->file);\n\t\tfree (gf);\n\t}\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: njs_typed_array_alloc(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs,\n njs_bool_t zeroing, njs_object_type_t type)\n{\n double num;\n int64_t i, length;\n uint32_t element_size;\n uint64_t size, offset;\n njs_int_t ret;\n njs_value_t *value, prop;\n njs_array_t *src_array;\n njs_typed_array_t *array, *src_tarray;\n njs_array_buffer_t *buffer;\n\n size = 0;\n length = 0;\n offset = 0;\n\n buffer = NULL;\n src_array = NULL;\n src_tarray = NULL;\n\n element_size = njs_typed_array_element_size(type);\n\n value = njs_arg(args, nargs, 0);\n\n if (njs_is_array_buffer(value)) {\n buffer = njs_array_buffer(value);\n\n ret = njs_value_to_index(vm, njs_arg(args, nargs, 1), &offset);\n if (njs_slow_path(ret != NJS_OK)) {\n return NULL;\n }\n\n if (njs_slow_path((offset % element_size) != 0)) {\n njs_range_error(vm, \"start offset must be multiple of %uD\",\n element_size);\n return NULL;\n }\n\n if (njs_is_defined(njs_arg(args, nargs, 2))) {\n ret = njs_value_to_index(vm, njs_argument(args, 2), &size);\n if (njs_slow_path(ret != NJS_OK)) {\n return NULL;\n }\n }\n\n if (njs_slow_path(njs_is_detached_buffer(buffer))) {\n njs_type_error(vm, \"detached buffer\");\n return NULL;\n }\n\n if (njs_is_defined(njs_arg(args, nargs, 2))) {\n ret = njs_value_to_index(vm, njs_argument(args, 2), &size);\n if (njs_slow_path(ret != NJS_OK)) {\n return NULL;\n }\n\n size *= element_size;\n\n if (njs_slow_path((offset + size) > buffer->size)) {\n njs_range_error(vm, \"Invalid typed array length: %uL\", size);\n return NULL;\n }\n\n } else {\n if (njs_slow_path((buffer->size % element_size) != 0)) {\n njs_range_error(vm, \"byteLength of buffer must be \"\n \"multiple of %uD\", element_size);\n return NULL;\n }\n\n if (offset > buffer->size) {\n njs_range_error(vm, \"byteOffset %uL is outside the bound of \"\n \"the buffer\", offset);\n return NULL;\n }\n\n size = buffer->size - offset;\n }\n\n } else if (njs_is_typed_array(value)) {\n src_tarray = njs_typed_array(value);\n if (njs_slow_path(njs_is_detached_buffer(src_tarray->buffer))) {\n njs_type_error(vm, \"detached buffer\");\n return NULL;\n }\n\n size = (uint64_t) njs_typed_array_length(src_tarray) * element_size;\n\n } else if (njs_is_object(value)) {\n if (njs_is_fast_array(value)) {\n src_array = njs_array(value);\n length = src_array->length;\n\n } else {\n ret = njs_object_length(vm, value, &length);\n if (njs_slow_path(ret == NJS_ERROR)) {\n return NULL;\n }\n }\n\n size = length * element_size;\n\n } else {\n ret = njs_value_to_index(vm, value, &size);\n if (njs_slow_path(ret != NJS_OK)) {\n return NULL;\n }\n\n size *= element_size;\n }\n\n if (buffer == NULL) {\n buffer = njs_array_buffer_alloc(vm, size, zeroing);\n if (njs_slow_path(buffer == NULL)) {\n return NULL;\n }\n }\n\n array = njs_mp_zalloc(vm->mem_pool, sizeof(njs_typed_array_t));\n if (njs_slow_path(array == NULL)) {\n goto memory_error;\n }\n\n array->buffer = buffer;\n array->offset = offset / element_size;\n array->byte_length = size;\n array->type = type;\n\n if (src_tarray != NULL) {\n if (type != src_tarray->type) {\n length = njs_typed_array_length(src_tarray);\n for (i = 0; i < length; i++) {\n njs_typed_array_prop_set(vm, array, i,\n njs_typed_array_prop(src_tarray, i));\n }\n\n } else {\n memcpy(&buffer->u.u8[0], &src_tarray->buffer->u.u8[0], size);\n }\n\n } else if (src_array != NULL) {\n for (i = 0; i < length; i++) {\n ret = njs_value_to_number(vm, &src_array->start[i], &num);\n if (njs_slow_path(ret == NJS_ERROR)) {\n return NULL;\n }\n\n if (ret == NJS_OK) {\n njs_typed_array_prop_set(vm, array, i, num);\n }\n }\n\n } else if (!njs_is_array_buffer(value) && njs_is_object(value)) {\n for (i = 0; i < length; i++) {\n ret = njs_value_property_i64(vm, value, i, &prop);\n if (njs_slow_path(ret == NJS_ERROR)) {\n return NULL;\n }\n\n num = NAN;\n\n if (ret == NJS_OK) {\n ret = njs_value_to_number(vm, &prop, &num);\n if (njs_slow_path(ret == NJS_ERROR)) {\n return NULL;\n }\n }\n\n njs_typed_array_prop_set(vm, array, i, num);\n }\n }\n\n njs_lvlhsh_init(&array->object.hash);\n njs_lvlhsh_init(&array->object.shared_hash);\n array->object.__proto__ = &vm->prototypes[type].object;\n array->object.type = NJS_TYPED_ARRAY;\n array->object.extensible = 1;\n array->object.fast_array = 1;\n\n return array;\n\nmemory_error:\n\n njs_memory_error(vm);\n\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed typed-array ctor when source array is changed while iterating.\n\nPreviously, the function used optimization for ordinary arrays with no\ngaps (so called fast arrays). For a fast array code took elements\ndirectly from internal flat C array. The direct pointer may become\ninvalid as side-effect of custom valueOf() method for an element.\n\nThe fix is to eliminate the micro-optimization which uses direct\npointers.\n\nThe problem is similar to the 9578cc729205 (0.7.2) commit.\n\nThis closes #523 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 l2cap_sock_listen(struct socket *sock, int backlog)\n{\n\tstruct sock *sk = sock->sk;\n\tint err = 0;\n\n\tBT_DBG(\"sk %p backlog %d\", sk, backlog);\n\n\tlock_sock(sk);\n\n\tif (sk->sk_state != BT_BOUND || sock->type != SOCK_SEQPACKET) {\n\t\terr = -EBADFD;\n\t\tgoto done;\n\t}\n\n\tswitch (l2cap_pi(sk)->mode) {\n\tcase L2CAP_MODE_BASIC:\n\t\tbreak;\n\tcase L2CAP_MODE_ERTM:\n\t\tif (enable_ertm)\n\t\t\tbreak;\n\t\t/* fall through */\n\tdefault:\n\t\terr = -ENOTSUPP;\n\t\tgoto done;\n\t}\n\n\tif (!l2cap_pi(sk)->psm) {\n\t\tbdaddr_t *src = &bt_sk(sk)->src;\n\t\tu16 psm;\n\n\t\terr = -EINVAL;\n\n\t\twrite_lock_bh(&l2cap_sk_list.lock);\n\n\t\tfor (psm = 0x1001; psm < 0x1100; psm += 2)\n\t\t\tif (!__l2cap_get_sock_by_addr(cpu_to_le16(psm), src)) {\n\t\t\t\tl2cap_pi(sk)->psm = cpu_to_le16(psm);\n\t\t\t\tl2cap_pi(sk)->sport = cpu_to_le16(psm);\n\t\t\t\terr = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\twrite_unlock_bh(&l2cap_sk_list.lock);\n\n\t\tif (err < 0)\n\t\t\tgoto done;\n\t}\n\n\tsk->sk_max_ack_backlog = backlog;\n\tsk->sk_ack_backlog = 0;\n\tsk->sk_state = BT_LISTEN;\n\ndone:\n\trelease_sock(sk);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-119', 'CWE-787'], 'message': 'Bluetooth: Add configuration support for ERTM and Streaming mode\n\nAdd support to config_req and config_rsp to configure ERTM and Streaming\nmode. If the remote device specifies ERTM or Streaming mode, then the\nsame mode is proposed. Otherwise ERTM or Basic mode is used. And in case\nof a state 2 device, the remote device should propose the same mode. If\nnot, then the channel gets disconnected.\n\nSigned-off-by: Gustavo F. Padovan \nSigned-off-by: Marcel Holtmann '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void test_base64_decode(void)\n{\n char buffer[16];\n int len = mutt_b64_decode(buffer, encoded);\n if (!TEST_CHECK(len == sizeof(clear) - 1))\n {\n TEST_MSG(\"Expected: %zu\", sizeof(clear) - 1);\n TEST_MSG(\"Actual : %zu\", len);\n }\n buffer[len] = '\\0';\n if (!TEST_CHECK(strcmp(buffer, clear) == 0))\n {\n TEST_MSG(\"Expected: %s\", clear);\n TEST_MSG(\"Actual : %s\", buffer);\n }\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: static int directblockRead(struct READER *reader, struct DATAOBJECT *dataobject,\n\t\tstruct FRACTALHEAP *fractalheap) {\n\n\tchar buf[4], *name, *value;\n\tint size, offset_size, length_size, err, len;\n\tuint8_t typeandversion;\n\tuint64_t unknown, heap_header_address, block_offset, block_size, offset,\n\t\t\tlength;\n\tlong store;\n\tstruct DIR *dir;\n\tstruct MYSOFA_ATTRIBUTE *attr;\n\n\tUNUSED(offset);\n\tUNUSED(block_size);\n\tUNUSED(block_offset);\n\n\t/* read signature */\n\tif (fread(buf, 1, 4, reader->fhd) != 4 || strncmp(buf, \"FHDB\", 4)) {\n\t\tlog(\"cannot read signature of fractal heap indirect block\\n\");\n\t\treturn MYSOFA_INVALID_FORMAT;\n\t}\n\tlog(\"%08\" PRIX64 \" %.4s\\n\", (uint64_t )ftell(reader->fhd) - 4, buf);\n\n\tif (fgetc(reader->fhd) != 0) {\n\t\tlog(\"object FHDB must have version 0\\n\");\n\t\treturn MYSOFA_UNSUPPORTED_FORMAT;\n\t}\n\n\t/* ignore heap_header_address */\n\tif (fseek(reader->fhd, reader->superblock.size_of_offsets, SEEK_CUR) < 0)\n\t\treturn errno;\n\n\tsize = (fractalheap->maximum_heap_size + 7) / 8;\n\tblock_offset = readValue(reader, size);\n\n\tif (fractalheap->flags & 2)\n\t\tif (fseek(reader->fhd, 4, SEEK_CUR))\n\t\t\treturn errno;\n\n\toffset_size = ceilf(log2f(fractalheap->maximum_heap_size) / 8);\n\tif (fractalheap->maximum_direct_block_size < fractalheap->maximum_size)\n\t\tlength_size = ceilf(log2f(fractalheap->maximum_direct_block_size) / 8);\n\telse\n\t\tlength_size = ceilf(log2f(fractalheap->maximum_size) / 8);\n\n\tlog(\" %d %\" PRIu64 \" %d\\n\",size,block_offset,offset_size);\n\n\t/*\n\t * 00003e00 00 46 48 44 42 00 40 02 00 00 00 00 00 00 00 00 |.FHDB.@.........|\n\t 00003e10 00 00 00 83 8d ac f6 >03 00 0c 00 08 00 04 00 00 |................|\n\t 00003e20 43 6f 6e 76 65 6e 74 69 6f 6e 73 00 13 00 00 00 |Conventions.....|\n\t 00003e30 04 00 00 00 02 00 00 00 53 4f 46 41< 03 00 08 00 |........SOFA....|\n\t 00003e40 08 00 04 00 00 56 65 72 73 69 6f 6e 00 13 00 00 |.....Version....|\n\t 00003e50 00 03 00 00 00 02 00 00 00 30 2e 36 03 00 10 00 |.........0.6....|\n\t 00003e60 08 00 04 00 00 53 4f 46 41 43 6f 6e 76 65 6e 74 |.....SOFAConvent|\n\t 00003e70 69 6f 6e 73 00 13 00 00 00 13 00 00 00 02 00 00 |ions............|\n\t 00003e80 00 53 69 6d 70 6c 65 46 72 65 65 46 69 65 6c 64 |.SimpleFreeField|\n\t 00003e90 48 52 49 52 03 00 17 00 08 00 04 00 00 53 4f 46 |HRIR.........SOF|\n\t 00003ea0 41 43 6f 6e 76 65 6e 74 69 6f 6e 73 56 65 72 73 |AConventionsVers|\n\t 00003eb0 69 6f 6e 00 13 00 00 00 03 00 00 00 02 00 00 00 |ion.............|\n\t *\n\t */\n\tdo {\n\t\ttypeandversion = (uint8_t) fgetc(reader->fhd);\n\t\toffset = readValue(reader, offset_size);\n\t\tlength = readValue(reader, length_size);\n\t\tif (offset > 0x10000000 || length > 0x10000000)\n\t\t\treturn MYSOFA_UNSUPPORTED_FORMAT;\n\n\t\tlog(\" %d %4\" PRIX64 \" %\" PRIX64 \" %08lX\\n\",typeandversion,offset,length,ftell(reader->fhd));\n\n\t\t/* TODO: for the following part, the specification is incomplete */\n\t\tif (typeandversion == 3) {\n\t\t\t/*\n\t\t\t * this seems to be a name and value pair\n\t\t\t */\n\n\t\t\tif (readValue(reader, 5) != 0x0000040008) {\n\t\t\t\tlog(\"FHDB type 3 unsupported values\");\n\t\t\t\treturn MYSOFA_UNSUPPORTED_FORMAT;\n\t\t\t}\n\n\t\t\tif (!(name = malloc(length+1)))\n\t\t\t\treturn MYSOFA_NO_MEMORY;\n\t\t\tif (fread(name, 1, length, reader->fhd) != length) {\n\t\t\t\tfree(name);\n\t\t\t\treturn MYSOFA_READ_ERROR;\n\t\t\t}\n\t\t\tname[length]=0;\t\n\n\t\t\tif (readValue(reader, 4) != 0x00000013) {\n\t\t\t\tlog(\"FHDB type 3 unsupported values\");\n\t\t\t\tfree(name);\n\t\t\t\treturn MYSOFA_UNSUPPORTED_FORMAT;\n\t\t\t}\n\n\t\t\tlen = (int) readValue(reader, 2);\n\t\t\tif (len > 0x1000 || len < 0) {\n\t\t\t\tfree(name);\n\t\t\t\treturn MYSOFA_UNSUPPORTED_FORMAT;\n\t\t\t}\n\n\t\t\t/* TODO: Get definition of this field */\n\t\t\tunknown = readValue(reader, 6);\n\t\t\tif (unknown == 0x000000020200)\n\t\t\t\tvalue = NULL;\n\t\t\telse if (unknown == 0x000000020000) {\n\t\t\t\tif (!(value = malloc(len + 1))) {\n\t\t\t\t\tfree(name);\n\t\t\t\t\treturn MYSOFA_NO_MEMORY;\n\t\t\t\t}\n\t\t\t\tif (fread(value, 1, len, reader->fhd) != len) {\n\t\t\t\t\tfree(value);\n\t\t\t\t\tfree(name);\n\t\t\t\t\treturn MYSOFA_READ_ERROR;\n\t\t\t\t}\n\t\t\t\tvalue[len] = 0;\n\t\t\t} else if (unknown == 0x20000020000) {\n\t\t\t\tif (!(value = malloc(5))) {\n\t\t\t\t\tfree(name);\n\t\t\t\t\treturn MYSOFA_NO_MEMORY;\n\t\t\t\t}\n\t\t\t\tstrcpy(value, \"\");\n\t\t\t} else {\n\t\t\t\tlog(\"FHDB type 3 unsupported values: %12\" PRIX64 \"\\n\",unknown);\n\t\t\t\tfree(name);\n\t\t\t\t/* TODO:\t\t\treturn MYSOFA_UNSUPPORTED_FORMAT; */\n\t\t\t\treturn MYSOFA_OK;\n\t\t\t} \n\t\t\tlog(\" %s = %s\\n\", name, value);\n\n\t\t\tattr = malloc(sizeof(struct MYSOFA_ATTRIBUTE));\n\t\t\tattr->name = name;\n\t\t\tattr->value = value;\n\t\t\tattr->next = dataobject->attributes;\n\t\t\tdataobject->attributes = attr;\n\n\t\t} else if (typeandversion == 1) {\n\t\t\t/*\n\t\t\t * pointer to another data object\n\t\t\t */\n\t\t\tunknown = readValue(reader, 6);\n\t\t\tif (unknown) {\n\t\t\t\tlog(\"FHDB type 1 unsupported values\\n\");\n\t\t\t\treturn MYSOFA_UNSUPPORTED_FORMAT;\n\t\t\t}\n\n\t\t\tlen = fgetc(reader->fhd);\n\t\t\tif (len < 0)\n\t\t\t\treturn MYSOFA_READ_ERROR;\n\t\t\tassert(len < 0x100);\n\n\t\t\tif (!(name = malloc(len + 1)))\n\t\t\t\treturn MYSOFA_NO_MEMORY;\n\t\t\tif (fread(name, 1, len, reader->fhd) != len) {\n\t\t\t\tfree(name);\n\t\t\t\treturn MYSOFA_READ_ERROR;\n\t\t\t}\n\t\t\tname[len] = 0;\n\n\t\t\theap_header_address = readValue(reader,\n\t\t\t\t\treader->superblock.size_of_offsets);\n\n\t\t\tlog(\"\\nfractal head type 1 length %4\" PRIX64 \" name %s address %\" PRIX64 \"\\n\", length, name, heap_header_address);\n\n\t\t\tdir = malloc(sizeof(struct DIR));\n\t\t\tif (!dir) {\n\t\t\t\tfree(name);\n\t\t\t\treturn MYSOFA_NO_MEMORY;\n\t\t\t}\n\t\t\tmemset(dir, 0, sizeof(*dir));\n\n\t\t\tdir->next = dataobject->directory;\n\t\t\tdataobject->directory = dir;\n\n\t\t\tstore = ftell(reader->fhd);\n\t\t\tif (fseek(reader->fhd, heap_header_address, SEEK_SET)) {\n\t\t\t\tfree(name);\n\t\t\t\treturn errno;\n\t\t\t}\n\n\t\t\terr = dataobjectRead(reader, &dir->dataobject, name);\n\t\t\tif (err) {\n\t\t\t\treturn err;\n\t\t\t}\n\n\t\t\tif (store < 0) {\n\t\t\t\treturn errno;\n\t\t\t}\n\t\t\tif (fseek(reader->fhd, store, SEEK_SET) < 0)\n\t\t\t\treturn errno;\n\n\t\t} else if (typeandversion != 0) {\n\t\t\t/* TODO is must be avoided somehow */\n\t\t\tlog(\"fractal head unknown type %d\\n\", typeandversion);\n\t\t\t/*\t\t\treturn MYSOFA_UNSUPPORTED_FORMAT; */\n\t\t\treturn MYSOFA_OK;\n\t\t}\n\n\t} while (typeandversion != 0);\n\n\treturn MYSOFA_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-787'], 'message': 'Fixed recursive function calls'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: gstd_accept(int fd, char **display_creds, char **export_name, char **mech)\n{\n\tgss_name_t\t client;\n\tgss_OID\t\t mech_oid;\n\tstruct gstd_tok *tok;\n\tgss_ctx_id_t\t ctx = GSS_C_NO_CONTEXT;\n\tgss_buffer_desc\t in, out;\n\tOM_uint32\t maj, min;\n\tint\t\t ret;\n\n\t*display_creds = NULL;\n\t*export_name = NULL;\n\tout.length = 0;\n\tin.length = 0;\n\tread_packet(fd, &in, 60000, 1);\nagain:\n\twhile ((ret = read_packet(fd, &in, 60000, 0)) == -2)\n\t\t;\n\n\tif (ret < 1)\n\t\treturn NULL;\n\n\tmaj = gss_accept_sec_context(&min, &ctx, GSS_C_NO_CREDENTIAL,\n\t &in, GSS_C_NO_CHANNEL_BINDINGS, &client, &mech_oid, &out, NULL,\n\t NULL, NULL);\n\n\tif (out.length && write_packet(fd, &out)) {\n\t\tgss_release_buffer(&min, &out);\n\t\treturn NULL;\n\t}\n\n\tGSTD_GSS_ERROR(maj, min, NULL, \"gss_accept_sec_context\");\n\n\tif (maj & GSS_S_CONTINUE_NEEDED)\n\t\tgoto again;\n\n\t*display_creds = gstd_get_display_name(client);\n\t*export_name = gstd_get_export_name(client);\n\t*mech = gstd_get_mech(mech_oid);\n\n\tgss_release_name(&min, &client);\n\tSETUP_GSTD_TOK(tok, ctx, fd, \"gstd_accept\");\n\treturn tok;\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 int get_bitmap_file(struct mddev *mddev, void __user * arg)\n{\n\tmdu_bitmap_file_t *file = NULL; /* too big for stack allocation */\n\tchar *ptr;\n\tint err;\n\n\tfile = kmalloc(sizeof(*file), GFP_NOIO);\n\tif (!file)\n\t\treturn -ENOMEM;\n\n\terr = 0;\n\tspin_lock(&mddev->lock);\n\t/* bitmap disabled, zero the first byte and copy out */\n\tif (!mddev->bitmap_info.file)\n\t\tfile->pathname[0] = '\\0';\n\telse if ((ptr = file_path(mddev->bitmap_info.file,\n\t\t\t file->pathname, sizeof(file->pathname))),\n\t\t IS_ERR(ptr))\n\t\terr = PTR_ERR(ptr);\n\telse\n\t\tmemmove(file->pathname, ptr,\n\t\t\tsizeof(file->pathname)-(ptr-file->pathname));\n\tspin_unlock(&mddev->lock);\n\n\tif (err == 0 &&\n\t copy_to_user(arg, file, sizeof(*file)))\n\t\terr = -EFAULT;\n\n\tkfree(file);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'md: use kzalloc() when bitmap is disabled\n\nIn drivers/md/md.c get_bitmap_file() uses kmalloc() for creating a\nmdu_bitmap_file_t called \"file\".\n\n5769 file = kmalloc(sizeof(*file), GFP_NOIO);\n5770 if (!file)\n5771 return -ENOMEM;\n\nThis structure is copied to user space at the end of the function.\n\n5786 if (err == 0 &&\n5787 copy_to_user(arg, file, sizeof(*file)))\n5788 err = -EFAULT\n\nBut if bitmap is disabled only the first byte of \"file\" is initialized\nwith zero, so it's possible to read some bytes (up to 4095) of kernel\nspace memory from user space. This is an information leak.\n\n5775 /* bitmap disabled, zero the first byte and copy out */\n5776 if (!mddev->bitmap_info.file)\n5777 file->pathname[0] = '\\0';\n\nSigned-off-by: Benjamin Randazzo \nSigned-off-by: NeilBrown '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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_teardown_cb(struct l2cap_chan *chan, int err)\n{\n\tstruct sock *sk = chan->data;\n\tstruct sock *parent;\n\n\tBT_DBG(\"chan %p state %s\", chan, state_to_string(chan->state));\n\n\t/* This callback can be called both for server (BT_LISTEN)\n\t * sockets as well as \"normal\" ones. To avoid lockdep warnings\n\t * with child socket locking (through l2cap_sock_cleanup_listen)\n\t * we need separation into separate nesting levels. The simplest\n\t * way to accomplish this is to inherit the nesting level used\n\t * for the channel.\n\t */\n\tlock_sock_nested(sk, atomic_read(&chan->nesting));\n\n\tparent = bt_sk(sk)->parent;\n\n\tswitch (chan->state) {\n\tcase BT_OPEN:\n\tcase BT_BOUND:\n\tcase BT_CLOSED:\n\t\tbreak;\n\tcase BT_LISTEN:\n\t\tl2cap_sock_cleanup_listen(sk);\n\t\tsk->sk_state = BT_CLOSED;\n\t\tchan->state = BT_CLOSED;\n\n\t\tbreak;\n\tdefault:\n\t\tsk->sk_state = BT_CLOSED;\n\t\tchan->state = BT_CLOSED;\n\n\t\tsk->sk_err = err;\n\n\t\tif (parent) {\n\t\t\tbt_accept_unlink(sk);\n\t\t\tparent->sk_data_ready(parent);\n\t\t} else {\n\t\t\tsk->sk_state_change(sk);\n\t\t}\n\n\t\tbreak;\n\t}\n\trelease_sock(sk);\n\n\t/* Only zap after cleanup to avoid use after free race */\n\tsock_set_flag(sk, SOCK_ZAPPED);\n\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: asmlinkage long sys_oabi_semtimedop(int semid,\n\t\t\t\t struct oabi_sembuf __user *tsops,\n\t\t\t\t unsigned nsops,\n\t\t\t\t const struct timespec __user *timeout)\n{\n\tstruct sembuf *sops;\n\tstruct timespec local_timeout;\n\tlong err;\n\tint i;\n\n\tif (nsops < 1)\n\t\treturn -EINVAL;\n\tsops = kmalloc(sizeof(*sops) * nsops, GFP_KERNEL);\n\tif (!sops)\n\t\treturn -ENOMEM;\n\terr = 0;\n\tfor (i = 0; i < nsops; i++) {\n\t\t__get_user_error(sops[i].sem_num, &tsops->sem_num, err);\n\t\t__get_user_error(sops[i].sem_op, &tsops->sem_op, err);\n\t\t__get_user_error(sops[i].sem_flg, &tsops->sem_flg, err);\n\t\ttsops++;\n\t}\n\tif (timeout) {\n\t\t/* copy this as well before changing domain protection */\n\t\terr |= copy_from_user(&local_timeout, timeout, sizeof(*timeout));\n\t\ttimeout = &local_timeout;\n\t}\n\tif (err) {\n\t\terr = -EFAULT;\n\t} else {\n\t\tmm_segment_t fs = get_fs();\n\t\tset_fs(KERNEL_DS);\n\t\terr = sys_semtimedop(semid, sops, nsops, timeout);\n\t\tset_fs(fs);\n\t}\n\tkfree(sops);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'ARM: 6891/1: prevent heap corruption in OABI semtimedop\n\nWhen CONFIG_OABI_COMPAT is set, the wrapper for semtimedop does not\nbound the nsops argument. A sufficiently large value will cause an\ninteger overflow in allocation size, followed by copying too much data\ninto the allocated buffer. Fix this by restricting nsops to SEMOPM.\nUntested.\n\nCc: stable@kernel.org\nSigned-off-by: Dan Rosenberg \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: static bool check_underflow(const struct ipt_entry *e)\n{\n\tconst struct xt_entry_target *t;\n\tunsigned int verdict;\n\n\tif (!unconditional(&e->ip))\n\t\treturn false;\n\tt = ipt_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: static inline bool unconditional(const struct ipt_ip *ip)\n{\n\tstatic const struct ipt_ip uncond;\n\n\treturn memcmp(ip, &uncond, sizeof(uncond)) == 0;\n#undef FWINV\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 int zerocopy_sg_from_iovec(struct sk_buff *skb, const struct iovec *from,\n\t\t\t\t int offset, size_t count)\n{\n\tint len = iov_length(from, count) - offset;\n\tint copy = skb_headlen(skb);\n\tint size, offset1 = 0;\n\tint i = 0;\n\n\t/* Skip over from offset */\n\twhile (count && (offset >= from->iov_len)) {\n\t\toffset -= from->iov_len;\n\t\t++from;\n\t\t--count;\n\t}\n\n\t/* copy up to skb headlen */\n\twhile (count && (copy > 0)) {\n\t\tsize = min_t(unsigned int, copy, from->iov_len - offset);\n\t\tif (copy_from_user(skb->data + offset1, from->iov_base + offset,\n\t\t\t\t size))\n\t\t\treturn -EFAULT;\n\t\tif (copy > size) {\n\t\t\t++from;\n\t\t\t--count;\n\t\t\toffset = 0;\n\t\t} else\n\t\t\toffset += size;\n\t\tcopy -= size;\n\t\toffset1 += size;\n\t}\n\n\tif (len == offset1)\n\t\treturn 0;\n\n\twhile (count--) {\n\t\tstruct page *page[MAX_SKB_FRAGS];\n\t\tint num_pages;\n\t\tunsigned long base;\n\t\tunsigned long truesize;\n\n\t\tlen = from->iov_len - offset;\n\t\tif (!len) {\n\t\t\toffset = 0;\n\t\t\t++from;\n\t\t\tcontinue;\n\t\t}\n\t\tbase = (unsigned long)from->iov_base + offset;\n\t\tsize = ((base & ~PAGE_MASK) + len + ~PAGE_MASK) >> PAGE_SHIFT;\n\t\tnum_pages = get_user_pages_fast(base, size, 0, &page[i]);\n\t\tif ((num_pages != size) ||\n\t\t (num_pages > MAX_SKB_FRAGS - skb_shinfo(skb)->nr_frags)) {\n\t\t\tfor (i = 0; i < num_pages; i++)\n\t\t\t\tput_page(page[i]);\n\t\t\treturn -EFAULT;\n\t\t}\n\t\ttruesize = size * PAGE_SIZE;\n\t\tskb->data_len += len;\n\t\tskb->len += len;\n\t\tskb->truesize += truesize;\n\t\tatomic_add(truesize, &skb->sk->sk_wmem_alloc);\n\t\twhile (len) {\n\t\t\tint off = base & ~PAGE_MASK;\n\t\t\tint size = min_t(int, len, PAGE_SIZE - off);\n\t\t\t__skb_fill_page_desc(skb, i, page[i], off, size);\n\t\t\tskb_shinfo(skb)->nr_frags++;\n\t\t\t/* increase sk_wmem_alloc */\n\t\t\tbase += size;\n\t\t\tlen -= size;\n\t\t\ti++;\n\t\t}\n\t\toffset = 0;\n\t\t++from;\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': 'macvtap: zerocopy: validate vectors before building skb\n\nThere're several reasons that the vectors need to be validated:\n\n- Return error when caller provides vectors whose num is greater than UIO_MAXIOV.\n- Linearize part of skb when userspace provides vectors grater than MAX_SKB_FRAGS.\n- Return error when userspace provides vectors whose total length may exceed\n- MAX_SKB_FRAGS * PAGE_SIZE.\n\nSigned-off-by: Jason Wang \nSigned-off-by: Michael S. Tsirkin '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n if (output->type == kTfLiteFloat32) {\n#define TF_LITE_LOCAL_RESPONSE_NORM(type) \\\n tflite::LocalResponseNormalizationParams op_params; \\\n op_params.range = params->radius; \\\n op_params.bias = params->bias; \\\n op_params.alpha = params->alpha; \\\n op_params.beta = params->beta; \\\n type::LocalResponseNormalization( \\\n op_params, GetTensorShape(input), GetTensorData(input), \\\n GetTensorShape(output), GetTensorData(output))\n if (kernel_type == kReference) {\n TF_LITE_LOCAL_RESPONSE_NORM(reference_ops);\n }\n if (kernel_type == kGenericOptimized) {\n TF_LITE_LOCAL_RESPONSE_NORM(optimized_ops);\n }\n#undef TF_LITE_LOCAL_RESPONSE_NORM\n } else {\n context->ReportError(context, \"Output type is %d, requires float.\",\n 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 EvalQuantized(TfLiteContext* context, TfLiteNode* node,\n OpData* data, const RuntimeShape& lhs_shape,\n const TfLiteTensor* lhs,\n const RuntimeShape& rhs_shape,\n const TfLiteTensor* rhs, TfLiteTensor* output) {\n if (lhs->type == kTfLiteFloat32) {\n TfLiteTensor* input_quantized = GetTemporary(context, node, /*index=*/2);\n TfLiteTensor* scaling_factors = GetTemporary(context, node, /*index=*/3);\n TfLiteTensor* accum_scratch = GetTemporary(context, node, /*index=*/4);\n TfLiteTensor* input_offsets = GetTemporary(context, node, /*index=*/5);\n TfLiteTensor* row_sums = GetTemporary(context, node, /*index=*/6);\n return EvalHybrid(\n context, node, data, lhs_shape, lhs, rhs_shape, rhs, input_quantized,\n scaling_factors, accum_scratch, row_sums, input_offsets, output);\n } else if (lhs->type == kTfLiteInt8) {\n return EvalInt8(context, data, lhs_shape, lhs, rhs_shape, rhs,\n GetTensorShape(output), output);\n } else {\n TF_LITE_KERNEL_LOG(\n context, \"Currently only hybrid and int8 quantization is supported.\\n\");\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 const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n if (type == kGenericOptimized) {\n optimized_ops::Floor(GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\n } else {\n reference_ops::Floor(GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\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 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 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 if (output->type == kTfLiteUInt8) {\n TF_LITE_ENSURE_STATUS(CalculateActivationRangeQuantized(\n context, params->activation, output, &data->output_activation_min,\n &data->output_activation_max));\n const 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: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n const TfLiteTensor* begin = GetInput(context, node, kBeginTensor);\n const TfLiteTensor* size = GetInput(context, node, kSizeTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n if (IsDynamicTensor(output)) {\n TF_LITE_ENSURE_OK(context,\n ResizeOutputShape(context, input, begin, size, output));\n }\n\n std::vector begins;\n begins.reserve(kMaxDim);\n std::vector sizes;\n sizes.reserve(kMaxDim);\n\n for (int i = NumDimensions(input); i < kMaxDim; ++i) {\n begins.push_back(0);\n sizes.push_back(1);\n }\n\n if (begin->type == kTfLiteInt32) {\n GetBeginAndSizeVectors(NumDimensions(input), begin, size, &begins,\n &sizes);\n } else if (begin->type == kTfLiteInt64) {\n GetBeginAndSizeVectors(NumDimensions(input), begin, size, &begins,\n &sizes);\n } else {\n context->ReportError(\n context, \"Type %d is currently not supported by Slice.\", begin->type);\n return kTfLiteError;\n }\n\n // The original Slice op implementation only accepted 4-D sizes. That\n // constraint is, for the present, maintained here.\n //\n // The dimensions in the kernel used to be in reverse-order, and TFLite\n // arranged the begins and sizes vectors accordingly. This macro incorporates\n // the needed reversing.\n#define TF_LITE_SLICE(data_type, kernel_type) \\\n { \\\n TF_LITE_ENSURE_EQ(context, begins.size(), 4); \\\n TF_LITE_ENSURE_EQ(context, sizes.size(), 4); \\\n tflite::SliceParams op_params; \\\n op_params.begin_count = 4; \\\n op_params.size_count = 4; \\\n for (int i = 0; i < 4; ++i) { \\\n op_params.begin[i] = begins[i]; \\\n op_params.size[i] = sizes[i]; \\\n } \\\n \\\n if (kernel_type == kGenericOptimized) { \\\n optimized_ops::Slice(op_params, GetTensorShape(input), input, \\\n GetTensorShape(output), output); \\\n } else { \\\n reference_ops::Slice(op_params, GetTensorShape(input), input, \\\n GetTensorShape(output), output); \\\n } \\\n }\n\n switch (input->type) {\n case kTfLiteFloat32:\n TF_LITE_SLICE(float, kernel_type);\n break;\n case kTfLiteInt32:\n TF_LITE_SLICE(int32_t, kernel_type);\n break;\n case kTfLiteInt64:\n TF_LITE_SLICE(int64_t, kernel_type);\n break;\n case kTfLiteInt8:\n TF_LITE_SLICE(int8_t, kernel_type);\n break;\n case kTfLiteInt16:\n TF_LITE_SLICE(int16_t, kernel_type);\n break;\n case kTfLiteUInt8:\n TF_LITE_SLICE(uint8_t, kernel_type);\n break;\n case kTfLiteBool:\n TF_LITE_SLICE(bool, kernel_type);\n break;\n case kTfLiteString:\n TF_LITE_SLICE(string, kernel_type);\n break;\n default:\n context->ReportError(\n context, \"Type %d is currently not supported by Slice.\", input->type);\n return kTfLiteError;\n }\n#undef TF_LITE_SLICE\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* cond_tensor =\n GetInput(context, node, kInputConditionTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n if (cond_tensor->type != kTfLiteBool) {\n context->ReportError(context,\n \"Condition tensor must be of type bool, but saw '%s'.\",\n TfLiteTypeGetName(cond_tensor->type));\n return kTfLiteError;\n }\n\n // As output will be a 2D tensor of indices, use int64 to be consistent with\n // tensorflow.\n output->type = kTfLiteInt64;\n\n // Exit early if cond is a non-const tensor. Set output tensor to dynamic so\n // output size can be determined in Eval.\n if (!IsConstantTensor(cond_tensor)) {\n SetTensorToDynamic(output);\n return kTfLiteOk;\n }\n return ResizeOutputTensor(context, cond_tensor, output);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n auto* params = reinterpret_cast(node->builtin_data);\n\n // Split sentence to words.\n std::vector words;\n tflite::StringRef strref = tflite::GetString(GetInput(context, node, 0), 0);\n int prev_idx = 0;\n for (int i = 1; i < strref.len; i++) {\n if (isspace(*(strref.str + i))) {\n if (i > prev_idx && !isspace(*(strref.str + prev_idx))) {\n words.push_back({strref.str + prev_idx, i - prev_idx});\n }\n prev_idx = i + 1;\n }\n }\n if (strref.len > prev_idx) {\n words.push_back({strref.str + prev_idx, strref.len - prev_idx});\n }\n\n // Generate n-grams recursively.\n tflite::DynamicBuffer buf;\n if (words.size() < params->ngram_size) {\n buf.WriteToTensorAsVector(GetOutput(context, node, 0));\n return kTfLiteOk;\n }\n\n // Stack stores the index of word used to generate ngram.\n // The size of stack is the size of ngram.\n std::vector stack(params->ngram_size, 0);\n // Stack index that indicates which depth the recursion is operating at.\n int stack_idx = 1;\n int num_words = words.size();\n\n while (stack_idx >= 0) {\n if (ShouldStepInRecursion(params, stack, stack_idx, num_words)) {\n // When current depth can fill with a new word\n // and the new word is within the max range to skip,\n // fill this word to stack, recurse into next depth.\n stack[stack_idx]++;\n stack_idx++;\n if (stack_idx < params->ngram_size) {\n stack[stack_idx] = stack[stack_idx - 1];\n }\n } else {\n if (ShouldIncludeCurrentNgram(params, stack_idx)) {\n // Add n-gram to tensor buffer when the stack has filled with enough\n // words to generate the ngram.\n std::vector gram(stack_idx);\n for (int i = 0; i < stack_idx; i++) {\n gram[i] = words[stack[i]];\n }\n buf.AddJoinedString(gram, ' ');\n }\n // When current depth cannot fill with a valid new word,\n // and not in last depth to generate ngram,\n // step back to previous depth to iterate to next possible word.\n stack_idx--;\n }\n }\n\n buf.WriteToTensorAsVector(GetOutput(context, node, 0));\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 switch (input->type) {\n case kTfLiteInt64:\n reference_ops::Negate(\n GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\n break;\n case kTfLiteInt32:\n reference_ops::Negate(\n GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\n break;\n case kTfLiteFloat32:\n reference_ops::Negate(GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output),\n GetTensorData(output));\n break;\n default:\n context->ReportError(\n context,\n \"Neg only currently supports int64, int32, 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: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* lookup = GetInput(context, node, 0);\n TF_LITE_ENSURE_EQ(context, NumDimensions(lookup), 1);\n TF_LITE_ENSURE_EQ(context, lookup->type, kTfLiteInt32);\n\n const TfLiteTensor* value = GetInput(context, node, 1);\n TF_LITE_ENSURE(context, NumDimensions(value) >= 2);\n\n TfLiteTensor* output = GetOutput(context, node, 0);\n TfLiteIntArray* outputSize = TfLiteIntArrayCreate(NumDimensions(value));\n\n outputSize->data[0] = SizeOfDimension(lookup, 0);\n outputSize->data[1] = SizeOfDimension(value, 1);\n for (int i = 2; i < NumDimensions(value); i++) {\n outputSize->data[i] = SizeOfDimension(value, i);\n }\n return context->ResizeTensor(context, output, outputSize);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 3);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 2);\n\n const TfLiteTensor* lookup = GetInput(context, node, 0);\n TF_LITE_ENSURE_EQ(context, NumDimensions(lookup), 1);\n TF_LITE_ENSURE_EQ(context, lookup->type, kTfLiteInt32);\n\n const TfLiteTensor* key = GetInput(context, node, 1);\n TF_LITE_ENSURE_EQ(context, NumDimensions(key), 1);\n TF_LITE_ENSURE_EQ(context, key->type, kTfLiteInt32);\n\n const TfLiteTensor* value = GetInput(context, node, 2);\n TF_LITE_ENSURE(context, NumDimensions(value) >= 1);\n TF_LITE_ENSURE_EQ(context, SizeOfDimension(key, 0),\n SizeOfDimension(value, 0));\n if (value->type == kTfLiteString) {\n TF_LITE_ENSURE_EQ(context, NumDimensions(value), 1);\n }\n\n TfLiteTensor* hits = GetOutput(context, node, 1);\n TF_LITE_ENSURE_EQ(context, hits->type, kTfLiteUInt8);\n TfLiteIntArray* hitSize = TfLiteIntArrayCreate(1);\n hitSize->data[0] = SizeOfDimension(lookup, 0);\n\n TfLiteTensor* output = GetOutput(context, node, 0);\n TF_LITE_ENSURE_EQ(context, value->type, output->type);\n\n TfLiteStatus status = kTfLiteOk;\n if (output->type != kTfLiteString) {\n TfLiteIntArray* outputSize = TfLiteIntArrayCreate(NumDimensions(value));\n outputSize->data[0] = SizeOfDimension(lookup, 0);\n for (int i = 1; i < NumDimensions(value); i++) {\n outputSize->data[i] = SizeOfDimension(value, i);\n }\n status = context->ResizeTensor(context, output, outputSize);\n }\n if (context->ResizeTensor(context, hits, hitSize) != kTfLiteOk) {\n status = kTfLiteError;\n }\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: inline TfLiteStatus EvalImpl(TfLiteContext* context, TfLiteNode* node,\n std::function func,\n TfLiteType expected_type) {\n const TfLiteTensor* input = GetInput(context, node, 0);\n TfLiteTensor* output = GetOutput(context, node, 0);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, expected_type);\n const int64_t num_elements = NumElements(input);\n const T* in_data = GetTensorData(input);\n T* out_data = GetTensorData(output);\n for (int64_t i = 0; i < num_elements; ++i) {\n out_data[i] = func(in_data[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 HardSwishEval(TfLiteContext* context, TfLiteNode* node) {\n HardSwishData* data = static_cast(node->user_data);\n\n const TfLiteTensor* input = GetInput(context, node, 0);\n TfLiteTensor* output = GetOutput(context, node, 0);\n switch (input->type) {\n case kTfLiteFloat32: {\n if (kernel_type == kReference) {\n reference_ops::HardSwish(\n GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\n } else {\n optimized_ops::HardSwish(\n GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\n }\n return kTfLiteOk;\n } break;\n case kTfLiteUInt8: {\n HardSwishParams& params = data->params;\n if (kernel_type == kReference) {\n reference_ops::HardSwish(\n params, GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\n } else {\n optimized_ops::HardSwish(\n params, GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\n }\n return kTfLiteOk;\n } break;\n case kTfLiteInt8: {\n HardSwishParams& params = data->params;\n if (kernel_type == kReference) {\n reference_ops::HardSwish(\n params, GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\n } else {\n optimized_ops::HardSwish(\n params, GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\n }\n return kTfLiteOk;\n } break;\n default:\n TF_LITE_KERNEL_LOG(\n context,\n \"Only float32, uint8 and int8 are supported currently, got %s.\",\n TfLiteTypeGetName(input->type));\n return kTfLiteError;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: 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 output->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 // 8bit -> 8bit general quantized path, with general rescalings\n // as well as, int16 -> int16 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 // 8bit -> 8bit general quantized path, with general rescalings\n // as well as, 16bit -> 16bit with general rescalings\n data->input1_offset = -input1->params.zero_point;\n data->input2_offset = -input2->params.zero_point;\n data->output_offset = output->params.zero_point;\n\n // The shift is set to 15 for 16-bit and 20 in case of 8-bit, accordingly.\n // In case of 16-bit we have 65535 << 15 which is less than 1 << 31,\n // therefore the addition will still fit in a 32 bit accumulator.\n data->left_shift = !pot_scale_int16 ? 15 : 20;\n const double twice_max_input_scale =\n 2 * std::max(input1->params.scale, input2->params.scale);\n const double real_input1_multiplier =\n input1->params.scale / twice_max_input_scale;\n const double real_input2_multiplier =\n input2->params.scale / twice_max_input_scale;\n const double real_output_multiplier =\n twice_max_input_scale /\n ((1 << data->left_shift) * output->params.scale);\n\n QuantizeMultiplierSmallerThanOneExp(\n real_input1_multiplier, &data->input1_multiplier, &data->input1_shift);\n\n QuantizeMultiplierSmallerThanOneExp(\n real_input2_multiplier, &data->input2_multiplier, &data->input2_shift);\n\n QuantizeMultiplierSmallerThanOneExp(\n real_output_multiplier, &data->output_multiplier, &data->output_shift);\n\n TF_LITE_ENSURE_STATUS(CalculateActivationRangeQuantized(\n context, params->activation, output, &data->output_activation_min,\n &data->output_activation_max));\n } else if (output->type == kTfLiteInt16) {\n // 16bit -> 16bit special quantized path, supporting only a rather\n // narrow case of quantization parameters: zero_points must all be 0\n // (\"symmetric quantization\") and scales must be power-of-two (which\n // we abbreviate as \"POT\" below). The intended use case for this path\n // is in LSTM cells, where, due to the constraints of implementing\n // some of the math in these LSTM cells in fixed-point arithmetic,\n // we need to have such symmetric, power-of-two quantization\n // (Fixed-point formats are inherently symmetric, power-of-two).\n TF_LITE_ENSURE_EQ(context, input1->params.zero_point, 0);\n TF_LITE_ENSURE_EQ(context, input2->params.zero_point, 0);\n TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0);\n\n TF_LITE_ENSURE(context, input1_scale_is_pot);\n TF_LITE_ENSURE(context, input2_scale_is_pot);\n TF_LITE_ENSURE(context, output_scale_is_pot);\n\n data->input1_shift = input1_scale_log2_rounded - output_scale_log2_rounded;\n data->input2_shift = input2_scale_log2_rounded - output_scale_log2_rounded;\n\n // Shifting of one input is supported. The graph quantization should ensure\n // that the other input matches the output.\n TF_LITE_ENSURE(context, data->input1_shift == 0 || data->input2_shift == 0);\n TF_LITE_ENSURE(context, data->input1_shift <= 0);\n TF_LITE_ENSURE(context, data->input2_shift <= 0);\n\n TF_LITE_ENSURE_STATUS(CalculateActivationRangeQuantized(\n context, params->activation, output, &data->output_activation_min,\n &data->output_activation_max));\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 Eval(TfLiteContext* context, TfLiteNode* node) {\n // Retrieve tensors (All should be allocated by now)\n const TfLiteTensor* output_shape =\n GetInput(context, node, kOutputShapeTensor);\n const TfLiteTensor* weights = GetInput(context, node, kWeightsTensor);\n const TfLiteTensor* input = GetInput(context, node, kDataInputTensor);\n const TfLiteTensor* bias =\n (NumInputs(node) == 4)\n ? GetOptionalInputTensor(context, node, kBiasTensor)\n : nullptr;\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n OpData* data = reinterpret_cast(node->user_data);\n TfLiteTensor* col2im = data->has_col2im\n ? GetTemporary(context, node, data->col2im_index)\n : nullptr;\n TfLiteTensor* transposed_weights =\n data->weights_are_transposed\n ? GetTemporary(context, node, data->transposed_weights_index)\n : nullptr;\n const auto* params =\n reinterpret_cast(node->builtin_data);\n\n // Resize any deferred dynamic tensors\n if (IsDynamicTensor(output)) {\n TF_LITE_ENSURE_OK(context, ResizeTensor(context, output_shape, output));\n }\n if (data->has_col2im && IsDynamicTensor(col2im)) {\n TF_LITE_ENSURE_OK(context, ResizeCol2ImTensor(context, output_shape,\n weights, input, col2im));\n }\n\n // Get height and width of the output image.\n const int width = SizeOfDimension(output, 2);\n const int height = SizeOfDimension(output, 1);\n const int filter_width = SizeOfDimension(weights, 2);\n const int filter_height = SizeOfDimension(weights, 1);\n\n int unused_output_height, unused_output_width;\n data->padding = ComputePaddingHeightWidth(\n params->stride_height, params->stride_width, 1, 1, height, width,\n filter_height, filter_width, params->padding, &unused_output_height,\n &unused_output_width);\n\n // Currently support float32, uint8, int8, int16.\n switch (input->type) {\n case kTfLiteFloat32: {\n // Only for GenericOptimized path, we use transposed weights.\n if (data->weights_are_transposed) {\n if (!IsConstantTensor(weights)) {\n ResizeAndTransposeWeights(context, weights, transposed_weights);\n }\n }\n EvalFloat(context, params, data, input, weights, bias,\n transposed_weights, col2im, output);\n break;\n }\n case kTfLiteUInt8: {\n TfLiteTensor* scratch_buffer =\n GetTemporary(context, node, data->scratch_tensor_index);\n if (IsDynamicTensor(scratch_buffer)) {\n TF_LITE_ENSURE_OK(context,\n ResizeTensor(context, output_shape, scratch_buffer));\n }\n if (data->weights_are_transposed) {\n if (!IsConstantTensor(weights)) {\n ResizeAndTransposeWeights(context, weights, transposed_weights);\n }\n }\n EvalQuantized(context, params, data, input, weights,\n transposed_weights, bias, col2im, output,\n scratch_buffer);\n break;\n }\n case kTfLiteInt8: {\n TfLiteTensor* scratch_buffer =\n GetTemporary(context, node, data->scratch_tensor_index);\n if (IsDynamicTensor(scratch_buffer)) {\n TF_LITE_ENSURE_OK(context,\n ResizeTensor(context, output_shape, scratch_buffer));\n }\n if (data->weights_are_transposed && !IsConstantTensor(weights)) {\n ResizeAndTransposeWeights(context, weights, transposed_weights);\n }\n EvalQuantizedPerChannel(context, params, data, input,\n weights, transposed_weights, bias,\n col2im, output, scratch_buffer);\n break;\n }\n case kTfLiteInt16: {\n TfLiteTensor* scratch_buffer =\n GetTemporary(context, node, data->scratch_tensor_index);\n if (IsDynamicTensor(scratch_buffer)) {\n TF_LITE_ENSURE_OK(context,\n ResizeTensor(context, output_shape, scratch_buffer));\n }\n if (data->weights_are_transposed && !IsConstantTensor(weights)) {\n ResizeAndTransposeWeights(context, weights, transposed_weights);\n }\n EvalQuantizedPerChannel16x8(context, params, data, input, weights,\n transposed_weights, bias, col2im, output,\n scratch_buffer);\n break;\n }\n default:\n context->ReportError(context, \"Type '%s' is not currently supported.\",\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 Prepare(TfLiteContext* context, TfLiteNode* node) {\n const auto* params = reinterpret_cast(node->builtin_data);\n OpData* op_data = reinterpret_cast(node->user_data);\n int scratch_tensor_index = op_data->scratch_tensor_index;\n\n // Check we have all the inputs and outputs we need.\n TF_LITE_ENSURE_EQ(context, node->outputs->size, 1);\n TF_LITE_ENSURE_EQ(context, node->inputs->size, 5);\n\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n const TfLiteTensor* weights_feature =\n GetInput(context, node, kWeightsFeatureTensor);\n const TfLiteTensor* weights_time =\n GetInput(context, node, kWeightsTimeTensor);\n\n TF_LITE_ENSURE(context,\n input->type == kTfLiteFloat32 || input->type == kTfLiteInt8);\n\n // Check all the parameters of tensor match within themselves and match the\n // input configuration.\n const int rank = params->rank;\n const int batch_size = input->dims->data[0];\n const int num_filters = weights_feature->dims->data[0];\n TF_LITE_ENSURE_EQ(context, num_filters % rank, 0);\n const int num_units = num_filters / rank;\n const int memory_size = weights_time->dims->data[1];\n TF_LITE_ENSURE_EQ(context, input->dims->data[1],\n weights_feature->dims->data[1]);\n TF_LITE_ENSURE_EQ(context, weights_time->dims->data[0], num_filters);\n\n const TfLiteTensor* bias = GetOptionalInputTensor(context, node, kBiasTensor);\n if (bias) {\n TF_LITE_ENSURE_EQ(context, bias->dims->data[0], num_units);\n }\n\n const TfLiteTensor* state = GetInput(context, node, kStateTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n // Check the shape of input state tensors.\n TF_LITE_ENSURE_EQ(context, NumDimensions(state), 2);\n TF_LITE_ENSURE_EQ(context, SizeOfDimension(state, 0), batch_size);\n TF_LITE_ENSURE_EQ(context, SizeOfDimension(state, 1),\n memory_size * num_filters);\n\n // Resize output.\n TfLiteIntArray* output_size_array = TfLiteIntArrayCreate(2);\n output_size_array->data[0] = batch_size;\n output_size_array->data[1] = num_units;\n TF_LITE_ENSURE_OK(context,\n context->ResizeTensor(context, output, output_size_array));\n\n // The weights are of consistent type, so it suffices to check one.\n const bool is_hybrid_op = IsHybridOp(input, weights_feature);\n const bool is_full_integer = input->type == kTfLiteInt8;\n\n // Resize scratch.\n TfLiteIntArrayFree(node->temporaries);\n if (is_hybrid_op) {\n node->temporaries = TfLiteIntArrayCreate(6);\n } else if (is_full_integer) {\n node->temporaries = TfLiteIntArrayCreate(2);\n } else {\n node->temporaries = TfLiteIntArrayCreate(1);\n }\n node->temporaries->data[0] = scratch_tensor_index;\n\n TfLiteIntArray* scratch_size_array = TfLiteIntArrayCreate(2);\n scratch_size_array->data[0] = batch_size;\n scratch_size_array->data[1] = num_filters;\n\n TfLiteTensor* scratch_tensor = GetTemporary(context, node, /*index=*/0);\n\n // The scratch buffer is of type int32 for full integer svdf and it's of type\n // float32 for hybrid and float case.\n if (is_full_integer) {\n scratch_tensor->type = kTfLiteInt32;\n } else {\n scratch_tensor->type = kTfLiteFloat32;\n }\n scratch_tensor->allocation_type = kTfLiteArenaRw;\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, scratch_tensor,\n scratch_size_array));\n\n if (is_hybrid_op) {\n op_data->compute_row_sums = true;\n // Tell interpreter to allocate temporary tensors to store quantized values\n // of input tensors.\n node->temporaries->data[1] = scratch_tensor_index + 1;\n TfLiteTensor* input_quantized = GetTemporary(context, node, /*index=*/1);\n input_quantized->type = weights_feature->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\n // Tell interpreter to allocate temporary tensors to store scaling factors.\n node->temporaries->data[2] = 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\n // Used to store dequantized weights_time matrix for hybrid computation of\n // matmul(state, weights_time), which occurs in floating point.\n node->temporaries->data[3] = scratch_tensor_index + 3;\n TfLiteTensor* float_weights_time = GetTemporary(context, node, /*index=*/3);\n float_weights_time->type = kTfLiteFloat32;\n // Persistent so that we can compute the dequantized weights only once.\n float_weights_time->allocation_type = kTfLiteArenaRwPersistent;\n if (!TfLiteIntArrayEqual(float_weights_time->dims, weights_time->dims)) {\n TfLiteIntArray* float_weights_time_size =\n TfLiteIntArrayCopy(weights_time->dims);\n TF_LITE_ENSURE_OK(context,\n context->ResizeTensor(context, float_weights_time,\n float_weights_time_size));\n }\n\n node->temporaries->data[4] = scratch_tensor_index + 4;\n TfLiteTensor* zero_points = GetTemporary(context, node, /*index=*/4);\n zero_points->type = kTfLiteFloat32;\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] = zero_points_dims[0];\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, zero_points,\n zero_points_size));\n }\n\n node->temporaries->data[5] = scratch_tensor_index + 5;\n TfLiteTensor* row_sums = GetTemporary(context, node, /*index=*/5);\n row_sums->type = kTfLiteFloat32;\n row_sums->allocation_type = kTfLiteArenaRwPersistent;\n int row_sums_dims[1] = {num_filters};\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_full_integer) {\n // Allocated one extra tensor.\n TfLiteIntArray* output_temp_size_array = TfLiteIntArrayCreate(2);\n output_temp_size_array->data[0] = num_units;\n output_temp_size_array->data[1] = batch_size;\n node->temporaries->data[1] = scratch_tensor_index + 1;\n TfLiteTensor* output_temp = GetTemporary(context, node, /*index=*/1);\n output_temp->type = kTfLiteInt32;\n output_temp->allocation_type = kTfLiteArenaRw;\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, output_temp,\n output_temp_size_array));\n\n // Calculate effective scales.\n auto* input_params =\n reinterpret_cast(input->quantization.params);\n auto* weights_feature_params = reinterpret_cast(\n weights_feature->quantization.params);\n auto* state_params =\n reinterpret_cast(state->quantization.params);\n auto* weight_time_params = reinterpret_cast(\n weights_time->quantization.params);\n auto* output_params = reinterpret_cast(\n output->quantization.params);\n const double effective_scale_1 = input_params->scale->data[0] *\n weights_feature_params->scale->data[0] /\n state_params->scale->data[0];\n const double effective_scale_2 = state_params->scale->data[0] *\n weight_time_params->scale->data[0] /\n output_params->scale->data[0];\n QuantizeMultiplier(effective_scale_1, &op_data->effective_scale_1_a,\n &op_data->effective_scale_1_b);\n QuantizeMultiplier(effective_scale_2, &op_data->effective_scale_2_a,\n &op_data->effective_scale_2_b);\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\n bool has_bias = NumInputs(node) == 4;\n\n // Sanity checks on op\n TF_LITE_ENSURE(context, has_bias || NumInputs(node) == 3);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n // Retrieve tensors\n const TfLiteTensor* output_shape =\n GetInput(context, node, kOutputShapeTensor);\n const TfLiteTensor* weights = GetInput(context, node, kWeightsTensor);\n const TfLiteTensor* input = GetInput(context, node, kDataInputTensor);\n const TfLiteTensor* bias = nullptr;\n\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n // Tensor sanity checks\n TF_LITE_ENSURE_EQ(context, NumDimensions(output_shape), 1);\n TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);\n TF_LITE_ENSURE_EQ(context, NumDimensions(weights), 4);\n TF_LITE_ENSURE(context,\n input->type == kTfLiteFloat32 || input->type == kTfLiteUInt8 ||\n input->type == kTfLiteInt8 || input->type == kTfLiteInt16);\n\n if (has_bias) {\n bias = GetOptionalInputTensor(context, node, kBiasTensor);\n if (bias) {\n if (input->type == kTfLiteUInt8 || input->type == kTfLiteInt8) {\n TF_LITE_ENSURE_TYPES_EQ(context, bias->type, kTfLiteInt32);\n if (input->type == kTfLiteInt8) {\n TF_LITE_ENSURE_EQ(context, bias->params.zero_point, 0);\n }\n } else if (input->type == kTfLiteInt16) {\n TF_LITE_ENSURE_EQ(context, bias->type, kTfLiteInt64);\n TF_LITE_ENSURE_EQ(context, bias->params.zero_point, 0);\n } else {\n TF_LITE_ENSURE_TYPES_EQ(context, bias->type, input->type);\n }\n TF_LITE_ENSURE_EQ(context, NumElements(bias),\n SizeOfDimension(weights, 0));\n }\n }\n\n if (input->type == kTfLiteInt16) {\n TF_LITE_ENSURE_EQ(context, weights->type, kTfLiteInt8);\n TF_LITE_ENSURE_EQ(context, input->params.zero_point, 0);\n TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0);\n } else {\n TF_LITE_ENSURE_TYPES_EQ(context, weights->type, input->type);\n }\n TF_LITE_ENSURE_TYPES_EQ(context, output->type, input->type);\n // Ensure that weights and inputs have the same channel dimension.\n // Note: TOCO will reorder weights in the following format: OHWI.\n TF_LITE_ENSURE_EQ(context, SizeOfDimension(input, 3),\n SizeOfDimension(weights, 3));\n\n // Allocate col2Im, transposed_weights & scratch Tensor.\n TF_LITE_ENSURE_STATUS(AllocateTemporaryTensorsIfRequired(\n context, input->type, weights->type, node));\n\n OpData* user_data = reinterpret_cast(node->user_data);\n TfLiteTensor* col2im = nullptr;\n if (data->has_col2im) {\n node->temporaries->data[data->col2im_index] = data->col2im_id;\n col2im = GetTemporary(context, node, user_data->col2im_index);\n }\n\n if (!IsConstantTensor(output_shape)) {\n // Defer resizing until Eval().\n SetTensorToDynamic(output);\n if (data->has_col2im) {\n SetTensorToDynamic(col2im);\n }\n } else {\n TF_LITE_ENSURE_STATUS(ResizeTensor(context, output_shape, output));\n if (data->has_col2im) {\n TF_LITE_ENSURE_STATUS(\n ResizeCol2ImTensor(context, output_shape, weights, input, col2im));\n }\n }\n\n if (data->weights_are_transposed) {\n node->temporaries->data[data->transposed_weights_index] =\n data->transposed_weights_id;\n TfLiteTensor* transposed_weights =\n GetTemporary(context, node, user_data->transposed_weights_index);\n if (!IsConstantTensor(weights)) {\n SetTensorToDynamic(transposed_weights);\n } else {\n ResizeAndTransposeWeights(context, weights, transposed_weights);\n }\n }\n\n if (input->type == kTfLiteUInt8 || input->type == kTfLiteInt8 ||\n input->type == kTfLiteInt16) {\n node->temporaries->data[data->scratch_tensor_index] =\n data->scratch_tensor_id;\n TfLiteTensor* scratch_buffer =\n GetTemporary(context, node, data->scratch_tensor_index);\n if (input->type == kTfLiteInt16) {\n scratch_buffer->type = kTfLiteInt64;\n } else {\n scratch_buffer->type = kTfLiteInt32;\n }\n\n scratch_buffer->allocation_type = kTfLiteDynamic;\n if (!IsConstantTensor(output_shape)) {\n SetTensorToDynamic(scratch_buffer);\n } else {\n TF_LITE_ENSURE_STATUS(\n ResizeTensor(context, output_shape, scratch_buffer));\n }\n\n TF_LITE_ENSURE_EQ(context, weights->quantization.type,\n kTfLiteAffineQuantization);\n const auto* affine_quantization =\n reinterpret_cast(\n weights->quantization.params);\n TF_LITE_ENSURE(context, affine_quantization);\n TF_LITE_ENSURE(context, affine_quantization->scale);\n const int number_channel = affine_quantization->scale->size;\n data->per_channel_output_multiplier.resize(number_channel);\n data->per_channel_output_shift.resize(number_channel);\n TF_LITE_ENSURE_STATUS(tflite::PopulateConvolutionQuantizationParams(\n context, input, weights, bias, output, kTfLiteActNone,\n &data->output_multiplier, &data->output_shift,\n &data->output_activation_min, &data->output_activation_max,\n data->per_channel_output_multiplier.data(),\n data->per_channel_output_shift.data()));\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, bool is_arg_max) {\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n const TfLiteTensor* axis = GetInput(context, node, kAxis);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n if (IsDynamicTensor(output)) {\n TF_LITE_ENSURE_STATUS(ResizeOutput(context, input, axis, output));\n }\n\n#define TF_LITE_ARG_MIN_MAX(data_type, axis_type, output_type) \\\n optimized_ops::ArgMinMax( \\\n GetTensorShape(input), GetTensorData(input), \\\n GetTensorData(axis), GetTensorShape(output), \\\n GetTensorData(output), \\\n GetComparefunction(is_arg_max))\n if (axis->type == kTfLiteInt32) {\n switch (output->type) {\n case kTfLiteInt32: {\n switch (input->type) {\n case kTfLiteFloat32:\n TF_LITE_ARG_MIN_MAX(float, int32_t, int32_t);\n break;\n case kTfLiteUInt8:\n TF_LITE_ARG_MIN_MAX(uint8_t, int32_t, int32_t);\n break;\n case kTfLiteInt8:\n TF_LITE_ARG_MIN_MAX(int8_t, int32_t, int32_t);\n break;\n case kTfLiteInt32:\n TF_LITE_ARG_MIN_MAX(int32_t, int32_t, int32_t);\n break;\n default:\n context->ReportError(context,\n \"Only float32, uint8, int8 and int32 are \"\n \"supported currently, got %s.\",\n TfLiteTypeGetName(input->type));\n return kTfLiteError;\n }\n } break;\n case kTfLiteInt64: {\n switch (input->type) {\n case kTfLiteFloat32:\n TF_LITE_ARG_MIN_MAX(float, int32_t, int64_t);\n break;\n case kTfLiteUInt8:\n TF_LITE_ARG_MIN_MAX(uint8_t, int32_t, int64_t);\n break;\n case kTfLiteInt8:\n TF_LITE_ARG_MIN_MAX(int8_t, int32_t, int64_t);\n break;\n case kTfLiteInt32:\n TF_LITE_ARG_MIN_MAX(int32_t, int32_t, int64_t);\n break;\n default:\n context->ReportError(context,\n \"Only float32, uint8, int8 and int32 are \"\n \"supported currently, got %s.\",\n TfLiteTypeGetName(input->type));\n return kTfLiteError;\n }\n } break;\n default:\n context->ReportError(\n context, \"Only int32 and int64 are supported currently, got %s.\",\n TfLiteTypeGetName(output->type));\n return kTfLiteError;\n }\n } else {\n switch (output->type) {\n case kTfLiteInt32: {\n switch (input->type) {\n case kTfLiteFloat32:\n TF_LITE_ARG_MIN_MAX(float, int64_t, int32_t);\n break;\n case kTfLiteUInt8:\n TF_LITE_ARG_MIN_MAX(uint8_t, int64_t, int32_t);\n break;\n case kTfLiteInt8:\n TF_LITE_ARG_MIN_MAX(int8_t, int64_t, int32_t);\n break;\n case kTfLiteInt32:\n TF_LITE_ARG_MIN_MAX(int32_t, int64_t, int32_t);\n break;\n default:\n context->ReportError(context,\n \"Only float32, uint8, int8 and int32 are \"\n \"supported currently, got %s.\",\n TfLiteTypeGetName(input->type));\n return kTfLiteError;\n }\n } break;\n case kTfLiteInt64: {\n switch (input->type) {\n case kTfLiteFloat32:\n TF_LITE_ARG_MIN_MAX(float, int64_t, int64_t);\n break;\n case kTfLiteUInt8:\n TF_LITE_ARG_MIN_MAX(uint8_t, int64_t, int64_t);\n break;\n case kTfLiteInt8:\n TF_LITE_ARG_MIN_MAX(int8_t, int64_t, int64_t);\n break;\n case kTfLiteInt32:\n TF_LITE_ARG_MIN_MAX(int32_t, int64_t, int64_t);\n break;\n default:\n context->ReportError(context,\n \"Only float32, uint8, int8 and int32 are \"\n \"supported currently, got %s.\",\n TfLiteTypeGetName(input->type));\n return kTfLiteError;\n }\n } break;\n default:\n context->ReportError(\n context, \"Only int32 and int64 are supported currently, got %s.\",\n TfLiteTypeGetName(output->type));\n return kTfLiteError;\n }\n }\n#undef TF_LITE_ARG_MIN_MAX\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 GenericPrepare(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), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n TfLiteTensor* output = GetOutput(context, node, 0);\n const TfLiteTensor* input = GetInput(context, node, 0);\n TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n\n int batches = input->dims->data[0];\n int height = input->dims->data[1];\n int width = input->dims->data[2];\n int channels_out = input->dims->data[3];\n\n // Matching GetWindowedOutputSize in TensorFlow.\n auto padding = params->padding;\n int out_width, out_height;\n\n data->padding = ComputePaddingHeightWidth(\n params->stride_height, params->stride_width, 1, 1, height, width,\n params->filter_height, params->filter_width, padding, &out_height,\n &out_width);\n\n if (input->type == kTfLiteUInt8 || input->type == kTfLiteInt8) {\n if (pool_type == kAverage || pool_type == kMax) {\n TFLITE_DCHECK_LE(std::abs(input->params.scale - output->params.scale),\n 1.0e-6);\n TFLITE_DCHECK_EQ(input->params.zero_point, output->params.zero_point);\n }\n if (pool_type == kL2) {\n // We currently don't have a quantized implementation of L2Pool\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, kTfLiteFloat32);\n }\n }\n\n TfLiteIntArray* output_size = TfLiteIntArrayCreate(4);\n output_size->data[0] = batches;\n output_size->data[1] = out_height;\n output_size->data[2] = out_width;\n output_size->data[3] = channels_out;\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 LogicalImpl(TfLiteContext* context, TfLiteNode* node,\n bool (*func)(bool, bool)) {\n OpData* data = reinterpret_cast(node->user_data);\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 if (data->requires_broadcast) {\n reference_ops::BroadcastBinaryFunction4DSlow(\n GetTensorShape(input1), GetTensorData(input1),\n GetTensorShape(input2), GetTensorData(input2),\n GetTensorShape(output), GetTensorData(output), func);\n } else {\n reference_ops::BinaryFunction(\n GetTensorShape(input1), GetTensorData(input1),\n GetTensorShape(input2), GetTensorData(input2),\n GetTensorShape(output), GetTensorData(output), func);\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* op_data = reinterpret_cast(node->user_data);\n int num_inputs = node->inputs->size;\n // The number of outputs should be the same as number of inputs.\n TF_LITE_ENSURE_EQ(context, node->outputs->size, num_inputs);\n\n // Check subgraph indices and get subgraphs.\n Subgraph* this_subgraph = reinterpret_cast(context->impl_);\n auto* subgraphs = this_subgraph->GetSubgraphs();\n TF_LITE_ENSURE(context, op_data->cond_subgraph_index < subgraphs->size());\n TF_LITE_ENSURE(context, op_data->body_subgraph_index < subgraphs->size());\n\n Subgraph* cond_subgraph = (*subgraphs)[op_data->cond_subgraph_index].get();\n Subgraph* body_subgraph = (*subgraphs)[op_data->body_subgraph_index].get();\n\n // Check input & output count of the condition subgraph.\n TF_LITE_ENSURE_EQ(context, cond_subgraph->inputs().size(), num_inputs);\n TF_LITE_ENSURE_EQ(context, cond_subgraph->outputs().size(), 1);\n\n // Check input & output count of the body subgraph.\n TF_LITE_ENSURE_EQ(context, body_subgraph->inputs().size(), num_inputs);\n TF_LITE_ENSURE_EQ(context, body_subgraph->outputs().size(), num_inputs);\n\n // Prepare and check the condition subgraph.\n TF_LITE_ENSURE_OK(\n context, CopyTensorsShapeAndType(\n context, this_subgraph, TfLiteIntArrayView(node->inputs),\n cond_subgraph, cond_subgraph->inputs(), true));\n TF_LITE_ENSURE_OK(context, cond_subgraph->AllocateTensors());\n TfLiteTensor* cond_output =\n cond_subgraph->tensor(cond_subgraph->outputs()[0]);\n // TODO(ycling): Handle the case the cond subgraph has dynamic tensor outputs.\n // This should rarely happens. In most cases the output is static with shape\n // [1]. However theoretically intermediate tensors in the cond subgraph\n // can be dynamic.\n if (IsDynamicTensor(cond_output)) {\n op_data->cond_has_dynamic_output_tensors = true;\n } else {\n TF_LITE_ENSURE_STATUS(CheckCondOutput(context, cond_output));\n }\n\n // Prepare and check the body subgraph.\n TF_LITE_ENSURE_OK(\n context, CopyTensorsShapeAndType(\n context, this_subgraph, TfLiteIntArrayView(node->inputs),\n body_subgraph, body_subgraph->inputs(), true));\n TF_LITE_ENSURE_OK(context, body_subgraph->AllocateTensors());\n if (body_subgraph->HasDynamicTensors()) {\n op_data->body_has_dynamic_output_tensors = true;\n } else {\n for (int i = 0; i < num_inputs; ++i) {\n TfLiteTensor* body_input =\n body_subgraph->tensor(body_subgraph->inputs()[i]);\n TfLiteTensor* body_output =\n body_subgraph->tensor(body_subgraph->outputs()[i]);\n TF_LITE_ENSURE_TYPES_EQ(context, body_input->type, body_output->type);\n\n // TODO(ycling): Support dynamic sized body subgraph.\n TF_LITE_ENSURE(context, !IsDynamicTensor(body_output));\n if (!TfLiteIntArrayEqual(body_input->dims, body_output->dims)) {\n // If the output shape of the body subgraph is static w.r.t. a fixed\n // input size, but it's different from input size, it's still considered\n // dynamic. For example: If a subgraph keeps padding its input with a\n // fixed padding, the output shape is static w.r.t the input shape and\n // padding, but running it in a loop will keep bloating the tensor.\n op_data->body_has_dynamic_output_tensors = true;\n break;\n }\n }\n }\n for (int i = 0; i < num_inputs; ++i) {\n TfLiteTensor* output = GetOutput(context, node, i);\n if (op_data->body_has_dynamic_output_tensors) {\n SetTensorToDynamic(output);\n } else {\n TfLiteTensor* body_output =\n body_subgraph->tensor(body_subgraph->outputs()[i]);\n TfLiteIntArray* output_size = TfLiteIntArrayCopy(body_output->dims);\n TF_LITE_ENSURE_OK(context,\n context->ResizeTensor(context, output, output_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 TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n // TODO(ahentz): these two checks would make the new implementation\n // incompatible with some existing models, where params is not specified. It\n // is OK not to have them because toco would have set input and output types\n // to match the parameters.\n // auto* params = reinterpret_cast(node->builtin_data);\n // TF_LITE_ENSURE_EQ(context, input->type, params->in_data_type);\n // TF_LITE_ENSURE_EQ(context, output->type, params->out_data_type);\n\n return context->ResizeTensor(context, output,\n TfLiteIntArrayCopy(input->dims));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n // There are two ways in which the 'output' can be made dynamic: it could be\n // a string tensor, or its shape cannot be calculated during Prepare(). In\n // either case, we now have all the information to calculate its shape.\n if (IsDynamicTensor(output)) {\n TF_LITE_ENSURE_OK(context, ResizeOutput(context, node));\n }\n\n // Note that string tensors are always \"dynamic\" in the sense that their size\n // is not known until we have all the content. This applies even when their\n // shape is known ahead of time. As a result, a string tensor is never given\n // any memory by ResizeOutput(), and we need to do it manually here. Since\n // reshape doesn't change the data, the output tensor needs exactly as many\n // bytes as the input tensor.\n if (output->type == kTfLiteString) {\n auto bytes_required = input->bytes;\n TfLiteTensorRealloc(bytes_required, output);\n output->bytes = bytes_required;\n }\n\n memcpy(output->data.raw, input->data.raw, input->bytes);\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 if (input->type != kTfLiteFloat32) {\n TF_LITE_UNSUPPORTED_TYPE(context, input->type, \"Ceil\");\n }\n\n optimized_ops::Ceil(GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\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 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 (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-119', 'CWE-125'], 'message': 'Fix #10465 - Avoid string on low addresses (workaround) for corrupted dwarf (#10478)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: krb5_encode_krbsecretkey(krb5_key_data *key_data_in, int n_key_data,\n krb5_kvno mkvno) {\n struct berval **ret = NULL;\n int currkvno;\n int num_versions = 1;\n int i, j, last;\n krb5_error_code err = 0;\n krb5_key_data *key_data;\n\n if (n_key_data <= 0)\n return NULL;\n\n /* Make a shallow copy of the key data so we can alter it. */\n key_data = k5calloc(n_key_data, sizeof(*key_data), &err);\n if (key_data_in == NULL)\n goto cleanup;\n memcpy(key_data, key_data_in, n_key_data * sizeof(*key_data));\n\n /* Unpatched krb5 1.11 and 1.12 cannot decode KrbKey sequences with no salt\n * field. For compatibility, always encode a salt field. */\n for (i = 0; i < n_key_data; i++) {\n if (key_data[i].key_data_ver == 1) {\n key_data[i].key_data_ver = 2;\n key_data[i].key_data_type[1] = KRB5_KDB_SALTTYPE_NORMAL;\n key_data[i].key_data_length[1] = 0;\n key_data[i].key_data_contents[1] = NULL;\n }\n }\n\n /* Find the number of key versions */\n for (i = 0; i < n_key_data - 1; i++)\n if (key_data[i].key_data_kvno != key_data[i + 1].key_data_kvno)\n num_versions++;\n\n ret = (struct berval **) calloc (num_versions + 1, sizeof (struct berval *));\n if (ret == NULL) {\n err = ENOMEM;\n goto cleanup;\n }\n for (i = 0, last = 0, j = 0, currkvno = key_data[0].key_data_kvno; i < n_key_data; i++) {\n krb5_data *code;\n if (i == n_key_data - 1 || key_data[i + 1].key_data_kvno != currkvno) {\n ret[j] = k5alloc(sizeof(struct berval), &err);\n if (ret[j] == NULL)\n goto cleanup;\n err = asn1_encode_sequence_of_keys(key_data + last,\n (krb5_int16)i - last + 1,\n mkvno, &code);\n if (err)\n goto cleanup;\n /*CHECK_NULL(ret[j]); */\n ret[j]->bv_len = code->length;\n ret[j]->bv_val = code->data;\n free(code);\n j++;\n last = i + 1;\n\n currkvno = key_data[i].key_data_kvno;\n }\n }\n ret[num_versions] = NULL;\n\ncleanup:\n\n free(key_data);\n if (err != 0) {\n if (ret != NULL) {\n for (i = 0; i <= num_versions; i++)\n if (ret[i] != NULL)\n free (ret[i]);\n free (ret);\n ret = NULL;\n }\n }\n\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Fix LDAP key data segmentation [CVE-2014-4345]\n\nFor principal entries having keys with multiple kvnos (due to use of\n-keepold), the LDAP KDB module makes an attempt to store all the keys\nhaving the same kvno into a single krbPrincipalKey attribute value.\nThere is a fencepost error in the loop, causing currkvno to be set to\nthe just-processed value instead of the next kvno. As a result, the\nsecond and all following groups of multiple keys by kvno are each\nstored in two krbPrincipalKey attribute values. Fix the loop to use\nthe correct kvno value.\n\nCVE-2014-4345:\n\nIn MIT krb5, when kadmind is configured to use LDAP for the KDC\ndatabase, an authenticated remote attacker can cause it to perform an\nout-of-bounds write (buffer overrun) by performing multiple cpw\n-keepold operations. An off-by-one error while copying key\ninformation to the new database entry results in keys sharing a common\nkvno being written to different array buckets, in an array whose size\nis determined by the number of kvnos present. After sufficient\niterations, the extra writes extend past the end of the\n(NULL-terminated) array. The NULL terminator is always written after\nthe end of the loop, so no out-of-bounds data is read, it is only\nwritten.\n\nHistorically, it has been possible to convert an out-of-bounds write\ninto remote code execution in some cases, though the necessary\nexploits must be tailored to the individual application and are\nusually quite complicated. Depending on the allocated length of the\narray, an out-of-bounds write may also cause a segmentation fault\nand/or application crash.\n\n CVSSv2 Vector: AV:N/AC:M/Au:S/C:C/I:C/A:C/E:POC/RL:OF/RC:C\n\n[ghudson@mit.edu: clarified commit message]\n[kaduk@mit.edu: CVE summary, CVSSv2 vector]\n\n(cherry picked from commit 81c332e29f10887c6b9deb065f81ba259f4c7e03)\n\nticket: 7980\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: local void process(char *path)\n{\n int method = -1; /* get_header() return value */\n size_t len; /* length of base name (minus suffix) */\n struct stat st; /* to get file type and mod time */\n /* all compressed suffixes for decoding search, in length order */\n static char *sufs[] = {\".z\", \"-z\", \"_z\", \".Z\", \".gz\", \"-gz\", \".zz\", \"-zz\",\n \".zip\", \".ZIP\", \".tgz\", NULL};\n\n /* open input file with name in, descriptor ind -- set name and mtime */\n if (path == NULL) {\n strcpy(g.inf, \"\");\n g.ind = 0;\n g.name = NULL;\n g.mtime = g.headis & 2 ?\n (fstat(g.ind, &st) ? time(NULL) : st.st_mtime) : 0;\n len = 0;\n }\n else {\n /* set input file name (already set if recursed here) */\n if (path != g.inf) {\n strncpy(g.inf, path, sizeof(g.inf));\n if (g.inf[sizeof(g.inf) - 1])\n bail(\"name too long: \", path);\n }\n len = strlen(g.inf);\n\n /* try to stat input file -- if not there and decoding, look for that\n name with compressed suffixes */\n if (lstat(g.inf, &st)) {\n if (errno == ENOENT && (g.list || g.decode)) {\n char **try = sufs;\n do {\n if (*try == NULL || len + strlen(*try) >= sizeof(g.inf))\n break;\n strcpy(g.inf + len, *try++);\n errno = 0;\n } while (lstat(g.inf, &st) && errno == ENOENT);\n }\n#ifdef EOVERFLOW\n if (errno == EOVERFLOW || errno == EFBIG)\n bail(g.inf,\n \" too large -- not compiled with large file support\");\n#endif\n if (errno) {\n g.inf[len] = 0;\n complain(\"%s does not exist -- skipping\", g.inf);\n return;\n }\n len = strlen(g.inf);\n }\n\n /* only process regular files, but allow symbolic links if -f,\n recurse into directory if -r */\n if ((st.st_mode & S_IFMT) != S_IFREG &&\n (st.st_mode & S_IFMT) != S_IFLNK &&\n (st.st_mode & S_IFMT) != S_IFDIR) {\n complain(\"%s is a special file or device -- skipping\", g.inf);\n return;\n }\n if ((st.st_mode & S_IFMT) == S_IFLNK && !g.force && !g.pipeout) {\n complain(\"%s is a symbolic link -- skipping\", g.inf);\n return;\n }\n if ((st.st_mode & S_IFMT) == S_IFDIR && !g.recurse) {\n complain(\"%s is a directory -- skipping\", g.inf);\n return;\n }\n\n /* recurse into directory (assumes Unix) */\n if ((st.st_mode & S_IFMT) == S_IFDIR) {\n char *roll, *item, *cut, *base, *bigger;\n size_t len, hold;\n DIR *here;\n struct dirent *next;\n\n /* accumulate list of entries (need to do this, since readdir()\n behavior not defined if directory modified between calls) */\n here = opendir(g.inf);\n if (here == NULL)\n return;\n hold = 512;\n roll = MALLOC(hold);\n if (roll == NULL)\n bail(\"not enough memory\", \"\");\n *roll = 0;\n item = roll;\n while ((next = readdir(here)) != NULL) {\n if (next->d_name[0] == 0 ||\n (next->d_name[0] == '.' && (next->d_name[1] == 0 ||\n (next->d_name[1] == '.' && next->d_name[2] == 0))))\n continue;\n len = strlen(next->d_name) + 1;\n if (item + len + 1 > roll + hold) {\n do { /* make roll bigger */\n hold <<= 1;\n } while (item + len + 1 > roll + hold);\n bigger = REALLOC(roll, hold);\n if (bigger == NULL) {\n FREE(roll);\n bail(\"not enough memory\", \"\");\n }\n item = bigger + (item - roll);\n roll = bigger;\n }\n strcpy(item, next->d_name);\n item += len;\n *item = 0;\n }\n closedir(here);\n\n /* run process() for each entry in the directory */\n cut = base = g.inf + strlen(g.inf);\n if (base > g.inf && base[-1] != (unsigned char)'/') {\n if ((size_t)(base - g.inf) >= sizeof(g.inf))\n bail(\"path too long\", g.inf);\n *base++ = '/';\n }\n item = roll;\n while (*item) {\n strncpy(base, item, sizeof(g.inf) - (base - g.inf));\n if (g.inf[sizeof(g.inf) - 1]) {\n strcpy(g.inf + (sizeof(g.inf) - 4), \"...\");\n bail(\"path too long: \", g.inf);\n }\n process(g.inf);\n item += strlen(item) + 1;\n }\n *cut = 0;\n\n /* release list of entries */\n FREE(roll);\n return;\n }\n\n /* don't compress .gz (or provided suffix) files, unless -f */\n if (!(g.force || g.list || g.decode) && len >= strlen(g.sufx) &&\n strcmp(g.inf + len - strlen(g.sufx), g.sufx) == 0) {\n complain(\"%s ends with %s -- skipping\", g.inf, g.sufx);\n return;\n }\n\n /* create output file only if input file has compressed suffix */\n if (g.decode == 1 && !g.pipeout && !g.list) {\n int suf = compressed_suffix(g.inf);\n if (suf == 0) {\n complain(\"%s does not have compressed suffix -- skipping\",\n g.inf);\n return;\n }\n len -= suf;\n }\n\n /* open input file */\n g.ind = open(g.inf, O_RDONLY, 0);\n if (g.ind < 0)\n bail(\"read error on \", g.inf);\n\n /* prepare gzip header information for compression */\n g.name = g.headis & 1 ? justname(g.inf) : NULL;\n g.mtime = g.headis & 2 ? st.st_mtime : 0;\n }\n SET_BINARY_MODE(g.ind);\n\n /* if decoding or testing, try to read gzip header */\n g.hname = NULL;\n if (g.decode) {\n in_init();\n method = get_header(1);\n if (method != 8 && method != 257 &&\n /* gzip -cdf acts like cat on uncompressed input */\n !(method == -2 && g.force && g.pipeout && g.decode != 2 &&\n !g.list)) {\n RELEASE(g.hname);\n if (g.ind != 0)\n close(g.ind);\n if (method != -1)\n complain(method < 0 ? \"%s is not compressed -- skipping\" :\n \"%s has unknown compression method -- skipping\",\n g.inf);\n return;\n }\n\n /* if requested, test input file (possibly a special list) */\n if (g.decode == 2) {\n if (method == 8)\n infchk();\n else {\n unlzw();\n if (g.list) {\n g.in_tot -= 3;\n show_info(method, 0, g.out_tot, 0);\n }\n }\n RELEASE(g.hname);\n if (g.ind != 0)\n close(g.ind);\n return;\n }\n }\n\n /* if requested, just list information about input file */\n if (g.list) {\n list_info();\n RELEASE(g.hname);\n if (g.ind != 0)\n close(g.ind);\n return;\n }\n\n /* create output file out, descriptor outd */\n if (path == NULL || g.pipeout) {\n /* write to stdout */\n g.outf = MALLOC(strlen(\"\") + 1);\n if (g.outf == NULL)\n bail(\"not enough memory\", \"\");\n strcpy(g.outf, \"\");\n g.outd = 1;\n if (!g.decode && !g.force && isatty(g.outd))\n bail(\"trying to write compressed data to a terminal\",\n \" (use -f to force)\");\n }\n else {\n char *to, *repl;\n\n /* use header name for output when decompressing with -N */\n to = g.inf;\n if (g.decode && (g.headis & 1) != 0 && g.hname != NULL) {\n to = g.hname;\n len = strlen(g.hname);\n }\n\n /* replace .tgz with .tar when decoding */\n repl = g.decode && strcmp(to + len, \".tgz\") ? \"\" : \".tar\";\n\n /* create output file and open to write */\n g.outf = MALLOC(len + (g.decode ? strlen(repl) : strlen(g.sufx)) + 1);\n if (g.outf == NULL)\n bail(\"not enough memory\", \"\");\n memcpy(g.outf, to, len);\n strcpy(g.outf + len, g.decode ? repl : g.sufx);\n g.outd = open(g.outf, O_CREAT | O_TRUNC | O_WRONLY |\n (g.force ? 0 : O_EXCL), 0600);\n\n /* if exists and not -f, give user a chance to overwrite */\n if (g.outd < 0 && errno == EEXIST && isatty(0) && g.verbosity) {\n int ch, reply;\n\n fprintf(stderr, \"%s exists -- overwrite (y/n)? \", g.outf);\n fflush(stderr);\n reply = -1;\n do {\n ch = getchar();\n if (reply < 0 && ch != ' ' && ch != '\\t')\n reply = ch == 'y' || ch == 'Y' ? 1 : 0;\n } while (ch != EOF && ch != '\\n' && ch != '\\r');\n if (reply == 1)\n g.outd = open(g.outf, O_CREAT | O_TRUNC | O_WRONLY,\n 0600);\n }\n\n /* if exists and no overwrite, report and go on to next */\n if (g.outd < 0 && errno == EEXIST) {\n complain(\"%s exists -- skipping\", g.outf);\n RELEASE(g.outf);\n RELEASE(g.hname);\n if (g.ind != 0)\n close(g.ind);\n return;\n }\n\n /* if some other error, give up */\n if (g.outd < 0)\n bail(\"write error on \", g.outf);\n }\n SET_BINARY_MODE(g.outd);\n RELEASE(g.hname);\n\n /* process ind to outd */\n if (g.verbosity > 1)\n fprintf(stderr, \"%s to %s \", g.inf, g.outf);\n if (g.decode) {\n if (method == 8)\n infchk();\n else if (method == 257)\n unlzw();\n else\n cat();\n }\n#ifndef NOTHREAD\n else if (g.procs > 1)\n parallel_compress();\n#endif\n else\n single_compress(0);\n if (g.verbosity > 1) {\n putc('\\n', stderr);\n fflush(stderr);\n }\n\n /* finish up, copy attributes, set times, delete original */\n if (g.ind != 0)\n close(g.ind);\n if (g.outd != 1) {\n if (close(g.outd))\n bail(\"write error on \", g.outf);\n g.outd = -1; /* now prevent deletion on interrupt */\n if (g.ind != 0) {\n copymeta(g.inf, g.outf);\n if (!g.keep)\n unlink(g.inf);\n }\n if (g.decode && (g.headis & 2) != 0 && g.stamp)\n touch(g.outf, g.stamp);\n }\n RELEASE(g.outf);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-22'], 'message': 'When decompressing with -N or -NT, strip any path from header name.\n\nThis uses the path of the compressed file combined with the name\nfrom the header as the name of the decompressed output file. Any\npath information in the header name is stripped. This avoids a\npossible vulnerability where absolute or descending paths are put\nin the gzip header.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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 nhmldump_send_header(GF_NHMLDumpCtx *ctx)\n{\n\tGF_FilterPacket *dst_pck;\n\tchar nhml[1024];\n\tu32 size;\n\tu8 *output;\n\tconst GF_PropertyValue *p;\n\n\tctx->szRootName = \"NHNTStream\";\n\tif (ctx->dims) {\n\t\tctx->szRootName = \"DIMSStream\";\n\t}\n\n\tif (!ctx->filep) {\n\t\tsprintf(nhml, \"\\n\");\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t}\n\n\t/*write header*/\n\tsprintf(nhml, \"<%s version=\\\"1.0\\\" \", ctx->szRootName);\n\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\n\tNHML_PRINT_UINT(GF_PROP_PID_ID, NULL, \"trackID\")\n\tNHML_PRINT_UINT(GF_PROP_PID_TIMESCALE, NULL, \"timeScale\")\n\n\tp = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_IN_IOD);\n\tif (p && p->value.boolean) {\n\t\tsprintf(nhml, \"inRootOD=\\\"yes\\\" \");\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t}\n\n\tif (ctx->oti && (ctx->otistreamtype, ctx->oti);\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32)strlen(nhml));\n\t} else {\n\t\tp = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_SUBTYPE);\n\t\tif (p) {\n\t\t\tsprintf(nhml, \"%s=\\\"%s\\\" \", \"mediaType\", gf_4cc_to_str(p->value.uint));\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\t\t\tNHML_PRINT_4CC(GF_PROP_PID_ISOM_SUBTYPE, \"mediaSubType\", \"mediaSubType\")\n\t\t} else {\n\t\t\tNHML_PRINT_4CC(GF_PROP_PID_CODECID, NULL, \"codecID\")\n\t\t}\n\t}\n\n\tif (ctx->w && ctx->h) {\n\t\t//compatibility with old arch, we might want to remove this\n\t\tswitch (ctx->streamtype) {\n\t\tcase GF_STREAM_VISUAL:\n\t\tcase GF_STREAM_SCENE:\n\t\t\tsprintf(nhml, \"width=\\\"%d\\\" height=\\\"%d\\\" \", ctx->w, ctx->h);\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\telse if (ctx->sr && ctx->chan) {\n\t\tsprintf(nhml, \"sampleRate=\\\"%d\\\" numChannels=\\\"%d\\\" \", ctx->sr, ctx->chan);\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\tsprintf(nhml, \"sampleRate=\\\"%d\\\" numChannels=\\\"%d\\\" \", ctx->sr, ctx->chan);\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\tp = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_AUDIO_FORMAT);\n\t\tsprintf(nhml, \"bitsPerSample=\\\"%d\\\" \", gf_audio_fmt_bit_depth(p->value.uint));\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t}\n\n\tNHML_PRINT_4CC(0, \"codec_vendor\", \"codecVendor\")\n\tNHML_PRINT_UINT(0, \"codec_version\", \"codecVersion\")\n\tNHML_PRINT_UINT(0, \"codec_revision\", \"codecRevision\")\n\tNHML_PRINT_STRING(0, \"compressor_name\", \"compressorName\")\n\tNHML_PRINT_UINT(0, \"temporal_quality\", \"temporalQuality\")\n\tNHML_PRINT_UINT(0, \"spatial_quality\", \"spatialQuality\")\n\tNHML_PRINT_UINT(0, \"hres\", \"horizontalResolution\")\n\tNHML_PRINT_UINT(0, \"vres\", \"verticalResolution\")\n\tNHML_PRINT_UINT(GF_PROP_PID_BIT_DEPTH_Y, NULL, \"bitDepth\")\n\n\tNHML_PRINT_STRING(0, \"meta:xmlns\", \"xml_namespace\")\n\tNHML_PRINT_STRING(0, \"meta:schemaloc\", \"xml_schema_location\")\n\tNHML_PRINT_STRING(0, \"meta:mime\", \"mime_type\")\n\n\tNHML_PRINT_STRING(0, \"meta:config\", \"config\")\n\tNHML_PRINT_STRING(0, \"meta:aux_mimes\", \"aux_mime_type\")\n\n\tif (ctx->codecid == GF_CODECID_DIMS) {\n\t\tif (gf_filter_pid_get_property_str(ctx->ipid, \"meta:xmlns\")==NULL) {\n\t\t\tsprintf(nhml, \"xmlns=\\\"http://www.3gpp.org/richmedia\\\" \");\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\n\t\tNHML_PRINT_UINT(0, \"dims:profile\", \"profile\")\n\t\tNHML_PRINT_UINT(0, \"dims:level\", \"level\")\n\t\tNHML_PRINT_UINT(0, \"dims:pathComponents\", \"pathComponents\")\n\n\t\tp = gf_filter_pid_get_property_str(ctx->ipid, \"dims:fullRequestHost\");\n\t\tif (p) {\n\t\t\tsprintf(nhml, \"useFullRequestHost=\\\"%s\\\" \", p->value.boolean ? \"yes\" : \"no\");\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\t\tp = gf_filter_pid_get_property_str(ctx->ipid, \"dims:streamType\");\n\t\tif (p) {\n\t\t\tsprintf(nhml, \"stream_type=\\\"%s\\\" \", p->value.boolean ? \"primary\" : \"secondary\");\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\t\tp = gf_filter_pid_get_property_str(ctx->ipid, \"dims:redundant\");\n\t\tif (p) {\n\t\t\tsprintf(nhml, \"contains_redundant=\\\"%s\\\" \", (p->value.uint==1) ? \"main\" : ((p->value.uint==1) ? \"redundant\" : \"main+redundant\") );\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\t\tNHML_PRINT_UINT(0, \"dims:scriptTypes\", \"scriptTypes\")\n\t}\n\n\t//send DCD\n\tif (ctx->opid_info) {\n\t\tsprintf(nhml, \"specificInfoFile=\\\"%s\\\" \", gf_file_basename(ctx->info_file) );\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\t\tdst_pck = gf_filter_pck_new_shared(ctx->opid_info, ctx->dcfg, ctx->dcfg_size, NULL);\n\t\tgf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_TRUE);\n\t\tgf_filter_pck_set_readonly(dst_pck);\n\t\tgf_filter_pck_send(dst_pck);\n\t}\n\n\tNHML_PRINT_STRING(0, \"meta:encoding\", \"encoding\")\n\tNHML_PRINT_STRING(0, \"meta:contentEncoding\", \"content_encoding\")\n\tctx->uncompress = GF_FALSE;\n\tif (p) {\n\t\tif (!strcmp(p->value.string, \"deflate\")) ctx->uncompress = GF_TRUE;\n\t\telse {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_AUTHOR, (\"[NHMLMx] content_encoding %s not supported\\n\", p->value.string ));\n\t\t}\n\t}\n\n\tif (ctx->opid_mdia) {\n\t\tsprintf(nhml, \"baseMediaFile=\\\"%s\\\" \", gf_file_basename(ctx->media_file) );\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t}\n\tsprintf(nhml, \">\\n\");\n\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\tgf_bs_get_content_no_truncate(ctx->bs_w, &ctx->nhml_buffer, &size, &ctx->nhml_buffer_size);\n\n\tif (ctx->filep) {\n\t\tgf_fwrite(ctx->nhml_buffer, size, ctx->filep);\n\t\treturn;\n\t}\n\n\tdst_pck = gf_filter_pck_new_alloc(ctx->opid_nhml, size, &output);\n\tmemcpy(output, ctx->nhml_buffer, size);\n\tgf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_FALSE);\n\tgf_filter_pck_send(dst_pck);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"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: int Helper::processExec(QProcess *process, const QString &command, int timeout, QIODevice::OpenMode mode)\n{\n m_processStandardOutput.clear();\n m_processStandardError.clear();\n\n QEventLoop loop;\n QTimer timer;\n\n timer.setSingleShot(true);\n timer.setInterval(timeout);\n\n timer.connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);\n loop.connect(process, static_cast(&QProcess::finished), &loop, &QEventLoop::exit);\n\n // \u9632\u6b62\u5b50\u8fdb\u7a0b\u8f93\u51fa\u4fe1\u606f\u5c06\u7ba1\u9053\u585e\u6ee1\u5bfc\u81f4\u8fdb\u7a0b\u963b\u585e\n process->connect(process, &QProcess::readyReadStandardError, process, [process] {\n m_processStandardError.append(process->readAllStandardError());\n });\n process->connect(process, &QProcess::readyReadStandardOutput, process, [process] {\n m_processStandardOutput.append(process->readAllStandardOutput());\n });\n\n if (timeout > 0) {\n timer.start();\n } else {\n QTimer::singleShot(10000, process, [process] {\n dCWarning(\"\\\"%s %s\\\" running for more than 10 seconds, state=%d, pid_file_exist=%d\",\n qPrintable(process->program()), qPrintable(process->arguments().join(\" \")),\n (int)process->state(), (int)QFile::exists(QString(\"/proc/%1\").arg(process->pid())));\n });\n }\n\n if (Global::debugLevel > 1)\n dCDebug(\"Exec: \\\"%s\\\", timeout: %d\", qPrintable(command), timeout);\n\n process->start(command, mode);\n process->waitForStarted();\n\n if (process->error() != QProcess::UnknownError) {\n dCError(process->errorString());\n\n return -1;\n }\n\n if (process->state() == QProcess::Running) {\n loop.exec();\n }\n\n if (process->state() != QProcess::NotRunning) {\n dCDebug(\"The \\\"%s\\\" timeout, timeout: %d\", qPrintable(command), timeout);\n\n if (QFile::exists(QString(\"/proc/%1\").arg(process->pid()))) {\n process->terminate();\n process->waitForFinished();\n } else {\n dCDebug(\"The \\\"%s\\\" is quit, but the QProcess object state is not NotRunning\");\n }\n }\n\n m_processStandardOutput.append(process->readAllStandardOutput());\n m_processStandardError.append(process->readAllStandardError());\n\n if (Global::debugLevel > 1) {\n dCDebug(\"Done: \\\"%s\\\", exit code: %d\", qPrintable(command), process->exitCode());\n\n if (process->exitCode() != 0) {\n dCError(\"error: \\\"%s\\\"\\nstdout: \\\"%s\\\"\", qPrintable(m_processStandardError), qPrintable(m_processStandardOutput));\n }\n }\n\n return process->exitCode();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'fix: Do not use the \"/tmp\" directory\n\nhttps://github.com/linuxdeepin/deepin-clone/issues/16\nhttps://bugzilla.opensuse.org/show_bug.cgi?id=1130388'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void fx_TypedArray(txMachine* the)\n{\n\ttxSlot* instance = fxConstructTypedArray(the);\n\ttxSlot* dispatch = instance->next;\n\ttxSlot* view = dispatch->next;\n\ttxSlot* buffer = view->next;\n\ttxSlot* data = C_NULL;\n\ttxU2 shift = dispatch->value.typedArray.dispatch->shift;\n\ttxSlot* slot;\n\tif ((mxArgc > 0) && (mxArgv(0)->kind == XS_REFERENCE_KIND)) {\n\t\tslot = mxArgv(0)->value.reference->next;\n\t\tif (slot && ((slot->kind == XS_ARRAY_BUFFER_KIND) || (slot->kind == XS_HOST_KIND))) {\n\t\t\ttxInteger offset = fxArgToByteLength(the, 1, 0);\n\t\t\ttxInteger size;\n\t\t\ttxSlot* info;\n\t\t\tif (offset & ((1 << shift) - 1))\n\t\t\t\tmxRangeError(\"invalid byteOffset %ld\", offset);\n\t\t\tsize = fxArgToByteLength(the, 2, -1);\n\t\t\tinfo = fxGetBufferInfo(the, mxArgv(0));\n\t\t\tif (size >= 0) {\n\t\t\t\tsize <<= shift;\n\t\t\t\tif (info->value.bufferInfo.length < (offset + size))\n\t\t\t\t\tmxRangeError(\"out of range byteLength %ld\", size);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (info->value.bufferInfo.length & ((1 << shift) - 1))\n\t\t\t\t\tmxRangeError(\"invalid byteLength %ld\", info->value.bufferInfo.length);\n\t\t\t\tsize = info->value.bufferInfo.length - offset;\n\t\t\t\tif (size < 0)\n\t\t\t\t\tmxRangeError(\"out of range byteLength %ld\", size);\n\t\t\t\tif (info->value.bufferInfo.maxLength >= 0)\n\t\t\t\t\tsize = -1;\n\t\t\t}\n\t\t\tview->value.dataView.offset = offset;\n\t\t\tview->value.dataView.size = size;\n\t\t\tbuffer->kind = XS_REFERENCE_KIND;\n\t\t\tbuffer->value.reference = mxArgv(0)->value.reference;\n\t\t}\n\t\telse if (slot && (slot->kind == XS_TYPED_ARRAY_KIND)) {\n\t\t\ttxSlot* sourceDispatch = slot;\n\t\t\ttxSlot* sourceView = sourceDispatch->next;\n\t\t\ttxSlot* sourceBuffer = sourceView->next;\n\t\t\ttxU2 sourceShift = sourceDispatch->value.typedArray.dispatch->shift;\n\t\t\ttxInteger sourceLength = fxCheckDataViewSize(the, sourceView, sourceBuffer, XS_IMMUTABLE) >> sourceShift;\n\t\t\ttxSlot* sourceData = sourceBuffer->value.reference->next;\n\t\t\ttxInteger sourceDelta = sourceDispatch->value.typedArray.dispatch->size;\n\t\t\ttxInteger sourceOffset = sourceView->value.dataView.offset;\n\t\t\ttxInteger offset = 0;\n\t\t\ttxInteger size = sourceLength << shift;\n\t\t\t/* THIS */\n\t\t\tmxPushUninitialized();\t\n\t\t\t/* FUNCTION */\n\t\t\tmxPush(mxArrayBufferConstructor);\n\t\t\t/* TARGET */\n\t\t\tif (sourceData->kind == XS_ARRAY_BUFFER_KIND) {\n\t\t\t\tmxPushSlot(sourceBuffer);\n\t\t\t\tmxGetID(mxID(_constructor));\n\t\t\t\tfxToSpeciesConstructor(the, &mxArrayBufferConstructor);\n\t\t\t}\n\t\t\telse\n\t\t\t\tmxPush(mxArrayBufferConstructor);\n\t\t\t/* RESULT */\n\t\t\tmxPushUndefined();\t\n\t\t\tmxPushUninitialized();\t\n\t\t\tmxPushUninitialized();\t\n\t\t\t/* ARGUMENTS */\n\t\t\tsourceLength = fxGetDataViewSize(the, sourceView, sourceBuffer) >> sourceShift;\n\t\t\tsize = sourceLength << shift;\n\t\t\tmxPushInteger(size);\n\t\t\tmxRunCount(1);\n\t\t\tmxPullSlot(buffer);\n\t\t\tsourceLength = fxCheckDataViewSize(the, sourceView, sourceBuffer, XS_IMMUTABLE) >> sourceShift;\n\t\t\tsize = sourceLength << shift;\n\t\t\t\n\t\t\tdata = fxCheckArrayBufferDetached(the, buffer, XS_MUTABLE);\n\t\t\tview->value.dataView.offset = offset;\n\t\t\tview->value.dataView.size = size;\n\t\t\tif (dispatch == sourceDispatch)\n\t\t\t\tc_memcpy(data->value.arrayBuffer.address + offset, sourceData->value.arrayBuffer.address + sourceOffset, size);\n\t\t\telse {\n\t\t\t\ttxBoolean contentType = (dispatch->value.typedArray.dispatch->constructorID == _BigInt64Array)\n\t\t\t\t\t\t|| (dispatch->value.typedArray.dispatch->constructorID == _BigUint64Array);\n\t\t\t\ttxBoolean sourceContentType = (sourceDispatch->value.typedArray.dispatch->constructorID == _BigInt64Array)\n\t\t\t\t\t\t|| (sourceDispatch->value.typedArray.dispatch->constructorID == _BigUint64Array);\n\t\t\t\tif (contentType != sourceContentType)\n\t\t\t\t\tmxTypeError(\"incompatible content type\");\n\t\t\t\tmxPushUndefined();\n\t\t\t\twhile (offset < size) {\n\t\t\t\t\t(*sourceDispatch->value.typedArray.dispatch->getter)(the, sourceData, sourceOffset, the->stack, EndianNative);\n\t\t\t\t\t(*dispatch->value.typedArray.dispatch->coerce)(the, the->stack);\n\t\t\t\t\t(*dispatch->value.typedArray.dispatch->setter)(the, data, offset, the->stack, EndianNative);\n\t\t\t\t\tsourceOffset += sourceDelta;\n\t\t\t\t\toffset += 1 << shift;\n\t\t\t\t}\n\t\t\t\tmxPop();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tfx_TypedArray_from_object(the, instance, C_NULL, C_NULL);\n\t\t}\n\t}\n\telse {\n txInteger length = fxArgToByteLength(the, 0, 0);\n if (length & (((1 << shift) - 1) << (32 - shift)))\n\t\t\tmxRangeError(\"out of range byteLength\");\n length <<= shift;\n\t\tmxPush(mxArrayBufferConstructor);\n\t\tmxNew();\n\t\tmxPushInteger(length);\n\t\tmxRunCount(1);\n\t\tmxPullSlot(buffer);\n view->value.dataView.offset = 0;\n view->value.dataView.size = length;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'XS: #896'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int wvlan_uil_put_info(struct uilreq *urq, struct wl_private *lp)\n{\n\tint result = 0;\n\tltv_t *pLtv;\n\tbool_t ltvAllocated = FALSE;\n\tENCSTRCT sEncryption;\n\n#ifdef USE_WDS\n\thcf_16 hcfPort = HCF_PORT_0;\n#endif /* USE_WDS */\n\t/*------------------------------------------------------------------------*/\n\tDBG_FUNC(\"wvlan_uil_put_info\");\n\tDBG_ENTER(DbgInfo);\n\n\n\tif (urq->hcfCtx == &(lp->hcfCtx)) {\n\t\tif (capable(CAP_NET_ADMIN)) {\n\t\t\tif ((urq->data != NULL) && (urq->len != 0)) {\n\t\t\t\t/* Make sure that we have at least a command and length to send. */\n\t\t\t\tif (urq->len < (sizeof(hcf_16) * 2)) {\n\t\t\t\t\turq->len = sizeof(lp->ltvRecord);\n\t\t\t\t\turq->result = UIL_ERR_LEN;\n\t\t\t\t\tDBG_ERROR(DbgInfo, \"No Length/Type in LTV!!!\\n\");\n\t\t\t\t\tDBG_ERROR(DbgInfo, \"UIL_ERR_LEN\\n\");\n\t\t\t\t\tDBG_LEAVE(DbgInfo);\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\t/* Verify the user buffer */\n\t\t\t\tresult = verify_area(VERIFY_READ, urq->data, urq->len);\n\t\t\t\tif (result != 0) {\n\t\t\t\t\turq->result = UIL_FAILURE;\n\t\t\t\t\tDBG_ERROR(DbgInfo, \"verify_area(), VERIFY_READ FAILED\\n\");\n\t\t\t\t\tDBG_LEAVE(DbgInfo);\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\t/* Get only the command and length information. */\n\t\t\t\tcopy_from_user(&(lp->ltvRecord), urq->data, sizeof(hcf_16) * 2);\n\n\t\t\t\t/* Make sure the incoming LTV record length is within the bounds of the\n\t\t\t\t IOCTL length */\n\t\t\t\tif (((lp->ltvRecord.len + 1) * sizeof(hcf_16)) > urq->len) {\n\t\t\t\t\turq->len = sizeof(lp->ltvRecord);\n\t\t\t\t\turq->result = UIL_ERR_LEN;\n\t\t\t\t\tDBG_ERROR(DbgInfo, \"UIL_ERR_LEN\\n\");\n\t\t\t\t\tDBG_LEAVE(DbgInfo);\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\t/* If the requested length is greater than the size of our local\n\t\t\t\t LTV record, try to allocate it from the kernel stack.\n\t\t\t\t Otherwise, we just use our local LTV record. */\n\t\t\t\tif (urq->len > sizeof(lp->ltvRecord)) {\n\t\t\t\t\tpLtv = kmalloc(urq->len, GFP_KERNEL);\n\t\t\t\t\tif (pLtv != NULL) {\n\t\t\t\t\t\tltvAllocated = TRUE;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tDBG_ERROR(DbgInfo, \"Alloc FAILED\\n\");\n\t\t\t\t\t\turq->len = sizeof(lp->ltvRecord);\n\t\t\t\t\t\turq->result = UIL_ERR_LEN;\n\t\t\t\t\t\tresult = -ENOMEM;\n\t\t\t\t\t\tDBG_LEAVE(DbgInfo);\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tpLtv = &(lp->ltvRecord);\n\t\t\t\t}\n\n\t\t\t\t/* Copy the data from the user's buffer into the local LTV\n\t\t\t\t record data area. */\n\t\t\t\tcopy_from_user(pLtv, urq->data, urq->len);\n\n\n\t\t\t\t/* We need to snoop the commands to see if there is anything we\n\t\t\t\t need to store for the purposes of a reset or start/stop\n\t\t\t\t sequence. Perform endian translation as needed */\n\t\t\t\tswitch (pLtv->typ) {\n\t\t\t\tcase CFG_CNF_PORT_TYPE:\n\t\t\t\t\tlp->PortType = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_CNF_OWN_MAC_ADDR:\n\t\t\t\t\t/* TODO: determine if we are going to store anything based on this */\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_CNF_OWN_CHANNEL:\n\t\t\t\t\tlp->Channel = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n\t\t\t\t/* CFG_CNF_OWN_SSID currently same as CNF_DESIRED_SSID. Do we\n\t\t\t\t need separate storage for this? */\n\t\t\t\t/* case CFG_CNF_OWN_SSID: */\n\t\t\t\tcase CFG_CNF_OWN_ATIM_WINDOW:\n\t\t\t\t\tlp->atimWindow = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_CNF_SYSTEM_SCALE:\n\t\t\t\t\tlp->DistanceBetweenAPs = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\n\t\t\t\tcase CFG_CNF_MAX_DATA_LEN:\n\t\t\t\t\t/* TODO: determine if we are going to store anything based\n\t\t\t\t\t on this */\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_CNF_PM_ENABLED:\n\t\t\t\t\tlp->PMEnabled = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_CNF_MCAST_RX:\n\t\t\t\t\tlp->MulticastReceive = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_CNF_MAX_SLEEP_DURATION:\n\t\t\t\t\tlp->MaxSleepDuration = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_CNF_HOLDOVER_DURATION:\n\t\t\t\t\tlp->holdoverDuration = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_CNF_OWN_NAME:\n\t\t\t\t\tmemset(lp->StationName, 0, sizeof(lp->StationName));\n\t\t\t\t\tmemcpy((void *)lp->StationName, (void *)&pLtv->u.u8[2], (size_t)pLtv->u.u16[0]);\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_CNF_LOAD_BALANCING:\n\t\t\t\t\tlp->loadBalancing = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_CNF_MEDIUM_DISTRIBUTION:\n\t\t\t\t\tlp->mediumDistribution = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n#ifdef WARP\n\t\t\t\tcase CFG_CNF_TX_POW_LVL:\n\t\t\t\t\tlp->txPowLevel = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n\t\t\t\t/* case CFG_CNF_SHORT_RETRY_LIMIT: */ /* Short Retry Limit */\n\t\t\t\t/* case 0xFC33: */ /* Long Retry Limit */\n\t\t\t\tcase CFG_SUPPORTED_RATE_SET_CNTL: /* Supported Rate Set Control */\n\t\t\t\t\tlp->srsc[0] = pLtv->u.u16[0];\n\t\t\t\t\tlp->srsc[1] = pLtv->u.u16[1];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tpLtv->u.u16[1] = CNV_INT_TO_LITTLE(pLtv->u.u16[1]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_BASIC_RATE_SET_CNTL: /* Basic Rate Set Control */\n\t\t\t\t\tlp->brsc[0] = pLtv->u.u16[0];\n\t\t\t\t\tlp->brsc[1] = pLtv->u.u16[1];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tpLtv->u.u16[1] = CNV_INT_TO_LITTLE(pLtv->u.u16[1]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_CNF_CONNECTION_CNTL:\n\t\t\t\t\tlp->connectionControl = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n\t\t\t\t/* case CFG_PROBE_DATA_RATE: */\n#endif /* HERMES25 */\n\n#if 1 /* ;? (HCF_TYPE) & HCF_TYPE_AP */\n\t\t/* ;?should we restore this to allow smaller memory footprint */\n\n\t\t\t\tcase CFG_CNF_OWN_DTIM_PERIOD:\n\t\t\t\t\tlp->DTIMPeriod = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n#ifdef WARP\n\t\t\t\tcase CFG_CNF_OWN_BEACON_INTERVAL: /* Own Beacon Interval */\n\t\t\t\t\tlp->ownBeaconInterval = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n#endif /* WARP */\n\t\t\t\tcase CFG_COEXISTENSE_BEHAVIOUR: /* Coexistence behavior */\n\t\t\t\t\tlp->coexistence = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n#ifdef USE_WDS\n\t\t\t\tcase CFG_CNF_WDS_ADDR1:\n\t\t\t\t\tmemcpy(&lp->wds_port[0].wdsAddress, &pLtv->u.u8[0], ETH_ALEN);\n\t\t\t\t\thcfPort = HCF_PORT_1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_CNF_WDS_ADDR2:\n\t\t\t\t\tmemcpy(&lp->wds_port[1].wdsAddress, &pLtv->u.u8[0], ETH_ALEN);\n\t\t\t\t\thcfPort = HCF_PORT_2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_CNF_WDS_ADDR3:\n\t\t\t\t\tmemcpy(&lp->wds_port[2].wdsAddress, &pLtv->u.u8[0], ETH_ALEN);\n\t\t\t\t\thcfPort = HCF_PORT_3;\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_CNF_WDS_ADDR4:\n\t\t\t\t\tmemcpy(&lp->wds_port[3].wdsAddress, &pLtv->u.u8[0], ETH_ALEN);\n\t\t\t\t\thcfPort = HCF_PORT_4;\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_CNF_WDS_ADDR5:\n\t\t\t\t\tmemcpy(&lp->wds_port[4].wdsAddress, &pLtv->u.u8[0], ETH_ALEN);\n\t\t\t\t\thcfPort = HCF_PORT_5;\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_CNF_WDS_ADDR6:\n\t\t\t\t\tmemcpy(&lp->wds_port[5].wdsAddress, &pLtv->u.u8[0], ETH_ALEN);\n\t\t\t\t\thcfPort = HCF_PORT_6;\n\t\t\t\t\tbreak;\n#endif /* USE_WDS */\n\n\t\t\t\tcase CFG_CNF_MCAST_PM_BUF:\n\t\t\t\t\tlp->multicastPMBuffering = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_CNF_REJECT_ANY:\n\t\t\t\t\tlp->RejectAny = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n#endif\n\n\t\t\t\tcase CFG_CNF_ENCRYPTION:\n\t\t\t\t\tlp->EnableEncryption = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_CNF_AUTHENTICATION:\n\t\t\t\t\tlp->authentication = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n#if 1 /* ;? (HCF_TYPE) & HCF_TYPE_AP */\n\t\t/* ;?should we restore this to allow smaller memory footprint */\n\n\t\t\t\t/* case CFG_CNF_EXCL_UNENCRYPTED:\n\t\t\t\t\tlp->ExcludeUnencrypted = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak; */\n\t\t\t\tcase CFG_CNF_MCAST_RATE:\n\t\t\t\t\t/* TODO: determine if we are going to store anything based on this */\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_CNF_INTRA_BSS_RELAY:\n\t\t\t\t\tlp->intraBSSRelay = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n#endif\n\n\t\t\t\tcase CFG_CNF_MICRO_WAVE:\n\t\t\t\t\t/* TODO: determine if we are going to store anything based on this */\n\t\t\t\t\tbreak;\n\t\t\t\t/*case CFG_CNF_LOAD_BALANCING:*/\n\t\t\t\t\t/* TODO: determine if we are going to store anything based on this */\n\t\t\t\t\t/* break; */\n\t\t\t\t/* case CFG_CNF_MEDIUM_DISTRIBUTION: */\n\t\t\t\t\t/* TODO: determine if we are going to store anything based on this */\n\t\t\t\t\t/* break; */\n\t\t\t\t/* case CFG_CNF_RX_ALL_GROUP_ADDRESS: */\n\t\t\t\t\t/* TODO: determine if we are going to store anything based on this */\n\t\t\t\t\t/* break; */\n\t\t\t\t/* case CFG_CNF_COUNTRY_INFO: */\n\t\t\t\t\t/* TODO: determine if we are going to store anything based on this */\n\t\t\t\t\t/* break; */\n\t\t\t\tcase CFG_CNF_OWN_SSID:\n\t\t\t\t/* case CNF_DESIRED_SSID: */\n\t\t\t\tcase CFG_DESIRED_SSID:\n\t\t\t\t\tmemset(lp->NetworkName, 0, sizeof(lp->NetworkName));\n\t\t\t\t\tmemcpy((void *)lp->NetworkName, (void *)&pLtv->u.u8[2], (size_t)pLtv->u.u16[0]);\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\n\t\t\t\t\t/* take care of the special network name \"ANY\" case */\n\t\t\t\t\tif ((strlen(&pLtv->u.u8[2]) == 0) ||\n\t\t\t\t\t (strcmp(&pLtv->u.u8[2], \"ANY\") == 0) ||\n\t\t\t\t\t (strcmp(&pLtv->u.u8[2], \"any\") == 0)) {\n\t\t\t\t\t\t/* set the SSID_STRCT llen field (u16[0]) to zero, and the\n\t\t\t\t\t\teffectually null the string u8[2] */\n\t\t\t\t\t\tpLtv->u.u16[0] = 0;\n\t\t\t\t\t\tpLtv->u.u8[2] = 0;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_GROUP_ADDR:\n\t\t\t\t\t/* TODO: determine if we are going to store anything based on this */\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_CREATE_IBSS:\n\t\t\t\t\tlp->CreateIBSS = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_RTS_THRH:\n\t\t\t\t\tlp->RTSThreshold = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_TX_RATE_CNTL:\n\t\t\t\t\tlp->TxRateControl[0] = pLtv->u.u16[0];\n\t\t\t\t\tlp->TxRateControl[1] = pLtv->u.u16[1];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tpLtv->u.u16[1] = CNV_INT_TO_LITTLE(pLtv->u.u16[1]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_PROMISCUOUS_MODE:\n\t\t\t\t\t/* TODO: determine if we are going to store anything based on this */\n\t\t\t\t\tbreak;\n\t\t\t\t/* case CFG_WAKE_ON_LAN: */\n\t\t\t\t\t/* TODO: determine if we are going to store anything based on this */\n\t\t\t\t\t/* break; */\n#if 1 /* ;? #if (HCF_TYPE) & HCF_TYPE_AP */\n\t\t/* ;?should we restore this to allow smaller memory footprint */\n\t\t\t\tcase CFG_RTS_THRH0:\n\t\t\t\t\tlp->RTSThreshold = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_TX_RATE_CNTL0:\n/*;?no idea what this should be, get going so comment it out\t\t\t\t\tlp->TxRateControl = pLtv->u.u16[0];*/\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n#ifdef USE_WDS\n\t\t\t\tcase CFG_RTS_THRH1:\n\t\t\t\t\tlp->wds_port[0].rtsThreshold = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\thcfPort = HCF_PORT_1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_RTS_THRH2:\n\t\t\t\t\tlp->wds_port[1].rtsThreshold = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\thcfPort = HCF_PORT_2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_RTS_THRH3:\n\t\t\t\t\tlp->wds_port[2].rtsThreshold = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\thcfPort = HCF_PORT_3;\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_RTS_THRH4:\n\t\t\t\t\tlp->wds_port[3].rtsThreshold = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\thcfPort = HCF_PORT_4;\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_RTS_THRH5:\n\t\t\t\t\tlp->wds_port[4].rtsThreshold = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\thcfPort = HCF_PORT_5;\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_RTS_THRH6:\n\t\t\t\t\tlp->wds_port[5].rtsThreshold = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\thcfPort = HCF_PORT_6;\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_TX_RATE_CNTL1:\n\t\t\t\t\tlp->wds_port[0].txRateCntl = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\thcfPort = HCF_PORT_1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_TX_RATE_CNTL2:\n\t\t\t\t\tlp->wds_port[1].txRateCntl = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\thcfPort = HCF_PORT_2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_TX_RATE_CNTL3:\n\t\t\t\t\tlp->wds_port[2].txRateCntl = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\thcfPort = HCF_PORT_3;\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_TX_RATE_CNTL4:\n\t\t\t\t\tlp->wds_port[3].txRateCntl = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\thcfPort = HCF_PORT_4;\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_TX_RATE_CNTL5:\n\t\t\t\t\tlp->wds_port[4].txRateCntl = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\thcfPort = HCF_PORT_5;\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_TX_RATE_CNTL6:\n\t\t\t\t\tlp->wds_port[5].txRateCntl = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\thcfPort = HCF_PORT_6;\n\t\t\t\t\tbreak;\n#endif /* USE_WDS */\n#endif /* (HCF_TYPE) & HCF_TYPE_AP */\n\n\t\t\t\tcase CFG_DEFAULT_KEYS:\n\t\t\t\t\t{\n\t\t\t\t\t\tCFG_DEFAULT_KEYS_STRCT *pKeys = (CFG_DEFAULT_KEYS_STRCT *)pLtv;\n\n\t\t\t\t\t\tpKeys->key[0].len = CNV_INT_TO_LITTLE(pKeys->key[0].len);\n\t\t\t\t\t\tpKeys->key[1].len = CNV_INT_TO_LITTLE(pKeys->key[1].len);\n\t\t\t\t\t\tpKeys->key[2].len = CNV_INT_TO_LITTLE(pKeys->key[2].len);\n\t\t\t\t\t\tpKeys->key[3].len = CNV_INT_TO_LITTLE(pKeys->key[3].len);\n\n\t\t\t\t\t\tmemcpy((void *)&(lp->DefaultKeys), (void *)pKeys,\n\t\t\t\t\t\t\t\tsizeof(CFG_DEFAULT_KEYS_STRCT));\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_TX_KEY_ID:\n\t\t\t\t\tlp->TransmitKeyID = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_SCAN_SSID:\n\t\t\t\t\t/* TODO: determine if we are going to store anything based on this */\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_TICK_TIME:\n\t\t\t\t\t/* TODO: determine if we are going to store anything based on this */\n\t\t\t\t\tbreak;\n\t\t\t\t/* these RIDS are Info RIDs, and should they be allowed for puts??? */\n\t\t\t\tcase CFG_MAX_LOAD_TIME:\n\t\t\t\tcase CFG_DL_BUF:\n\t\t\t\t/* case CFG_HSI_SUP_RANGE: */\n\t\t\t\tcase CFG_NIC_SERIAL_NUMBER:\n\t\t\t\tcase CFG_NIC_IDENTITY:\n\t\t\t\tcase CFG_NIC_MFI_SUP_RANGE:\n\t\t\t\tcase CFG_NIC_CFI_SUP_RANGE:\n\t\t\t\tcase CFG_NIC_TEMP_TYPE:\n\t\t\t\tcase CFG_NIC_PROFILE:\n\t\t\t\tcase CFG_FW_IDENTITY:\n\t\t\t\tcase CFG_FW_SUP_RANGE:\n\t\t\t\tcase CFG_MFI_ACT_RANGES_STA:\n\t\t\t\tcase CFG_CFI_ACT_RANGES_STA:\n\t\t\t\tcase CFG_PORT_STAT:\n\t\t\t\tcase CFG_CUR_SSID:\n\t\t\t\tcase CFG_CUR_BSSID:\n\t\t\t\tcase CFG_COMMS_QUALITY:\n\t\t\t\tcase CFG_CUR_TX_RATE:\n\t\t\t\tcase CFG_CUR_BEACON_INTERVAL:\n\t\t\t\tcase CFG_CUR_SCALE_THRH:\n\t\t\t\tcase CFG_PROTOCOL_RSP_TIME:\n\t\t\t\tcase CFG_CUR_SHORT_RETRY_LIMIT:\n\t\t\t\tcase CFG_CUR_LONG_RETRY_LIMIT:\n\t\t\t\tcase CFG_MAX_TX_LIFETIME:\n\t\t\t\tcase CFG_MAX_RX_LIFETIME:\n\t\t\t\tcase CFG_CF_POLLABLE:\n\t\t\t\tcase CFG_AUTHENTICATION_ALGORITHMS:\n\t\t\t\tcase CFG_PRIVACY_OPT_IMPLEMENTED:\n\t\t\t\t/* case CFG_CURRENT_REMOTE_RATES: */\n\t\t\t\t/* case CFG_CURRENT_USED_RATES: */\n\t\t\t\t/* case CFG_CURRENT_SYSTEM_SCALE: */\n\t\t\t\t/* case CFG_CURRENT_TX_RATE1: */\n\t\t\t\t/* case CFG_CURRENT_TX_RATE2: */\n\t\t\t\t/* case CFG_CURRENT_TX_RATE3: */\n\t\t\t\t/* case CFG_CURRENT_TX_RATE4: */\n\t\t\t\t/* case CFG_CURRENT_TX_RATE5: */\n\t\t\t\t/* case CFG_CURRENT_TX_RATE6: */\n\t\t\t\tcase CFG_NIC_MAC_ADDR:\n\t\t\t\tcase CFG_PCF_INFO:\n\t\t\t\t/* case CFG_CURRENT_COUNTRY_INFO: */\n\t\t\t\tcase CFG_PHY_TYPE:\n\t\t\t\tcase CFG_CUR_CHANNEL:\n\t\t\t\t/* case CFG_CURRENT_POWER_STATE: */\n\t\t\t\t/* case CFG_CCAMODE: */\n\t\t\t\tcase CFG_SUPPORTED_DATA_RATES:\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_AP_MODE:\n/*;?\t\t\t\tlp->DownloadFirmware = (pLtv->u.u16[0]) + 1; */\n\t\t\t\t\tDBG_ERROR(DbgInfo, \"set CFG_AP_MODE no longer supported\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_ENCRYPT_STRING:\n\t\t\t\t\t/* TODO: ENDIAN TRANSLATION HERE??? */\n\t\t\t\t\tmemset(lp->szEncryption, 0, sizeof(lp->szEncryption));\n\t\t\t\t\tmemcpy((void *)lp->szEncryption, (void *)&pLtv->u.u8[0],\n\t\t\t\t\t\t\t(pLtv->len * sizeof(hcf_16)));\n\t\t\t\t\twl_wep_decode(CRYPT_CODE, &sEncryption,\n\t\t\t\t\t\t\t\t lp->szEncryption);\n\n\t\t\t\t\t/* the Linux driver likes to use 1-4 for the key IDs, and then\n\t\t\t\t\tconvert to 0-3 when sending to the card. The Windows code\n\t\t\t\t\tbase used 0-3 in the API DLL, which was ported to Linux. For\n\t\t\t\t\tthe sake of the user experience, we decided to keep 0-3 as the\n\t\t\t\t\tnumbers used in the DLL; and will perform the +1 conversion here.\n\t\t\t\t\tWe could have converted the entire Linux driver, but this is\n\t\t\t\t\tless obtrusive. This may be a \"todo\" to convert the whole driver */\n\t\t\t\t\tlp->TransmitKeyID = sEncryption.wTxKeyID + 1;\n\t\t\t\t\tlp->EnableEncryption = sEncryption.wEnabled;\n\n\t\t\t\t\tmemcpy(&lp->DefaultKeys, &sEncryption.EncStr,\n\t\t\t\t\t\t\tsizeof(CFG_DEFAULT_KEYS_STRCT));\n\t\t\t\t\tbreak;\n\t\t\t\t/*case CFG_COUNTRY_STRING:\n\t\t\t\t\tmemset(lp->countryString, 0, sizeof(lp->countryString));\n\t\t\t\t\tmemcpy((void *)lp->countryString, (void *)&pLtv->u.u8[2], (size_t)pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n\t\t\t\t*/\n\n\t\t\t\tcase CFG_DRIVER_ENABLE:\n\t\t\t\t\tlp->driverEnable = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_WOLAS_ENABLE:\n\t\t\t\t\tlp->wolasEnable = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_SET_WPA_AUTH_KEY_MGMT_SUITE:\n\t\t\t\t\tlp->AuthKeyMgmtSuite = pLtv->u.u16[0];\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_DISASSOCIATE_ADDR:\n\t\t\t\t\tpLtv->u.u16[ETH_ALEN / 2] = CNV_INT_TO_LITTLE(pLtv->u.u16[ETH_ALEN / 2]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_ADD_TKIP_DEFAULT_KEY:\n\t\t\t\tcase CFG_REMOVE_TKIP_DEFAULT_KEY:\n\t\t\t\t\t/* Endian convert the Tx Key Information */\n\t\t\t\t\tpLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_ADD_TKIP_MAPPED_KEY:\n\t\t\t\t\tbreak;\n\t\t\t\tcase CFG_REMOVE_TKIP_MAPPED_KEY:\n\t\t\t\t\tbreak;\n\t\t\t\t/* some RIDs just can't be put */\n\t\t\t\tcase CFG_MB_INFO:\n\t\t\t\tcase CFG_IFB:\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t/* This code will prevent Static Configuration Entities from\n\t\t\t\t being sent to the card, as they require a call to\n\t\t\t\t UIL_ACT_APPLY to take effect. Dynamic Entities will be sent\n\t\t\t\t immediately */\n\t\t\t\tswitch (pLtv->typ) {\n\t\t\t\tcase CFG_CNF_PORT_TYPE:\n\t\t\t\tcase CFG_CNF_OWN_MAC_ADDR:\n\t\t\t\tcase CFG_CNF_OWN_CHANNEL:\n\t\t\t\tcase CFG_CNF_OWN_SSID:\n\t\t\t\tcase CFG_CNF_OWN_ATIM_WINDOW:\n\t\t\t\tcase CFG_CNF_SYSTEM_SCALE:\n\t\t\t\tcase CFG_CNF_MAX_DATA_LEN:\n\t\t\t\tcase CFG_CNF_PM_ENABLED:\n\t\t\t\tcase CFG_CNF_MCAST_RX:\n\t\t\t\tcase CFG_CNF_MAX_SLEEP_DURATION:\n\t\t\t\tcase CFG_CNF_HOLDOVER_DURATION:\n\t\t\t\tcase CFG_CNF_OWN_NAME:\n\t\t\t\tcase CFG_CNF_LOAD_BALANCING:\n\t\t\t\tcase CFG_CNF_MEDIUM_DISTRIBUTION:\n#ifdef WARP\n\t\t\t\tcase CFG_CNF_TX_POW_LVL:\n\t\t\t\tcase CFG_CNF_CONNECTION_CNTL:\n\t\t\t\t/*case CFG_PROBE_DATA_RATE: */\n#endif /* HERMES25 */\n#if 1 /*;? (HCF_TYPE) & HCF_TYPE_AP */\n\t\t/*;?should we restore this to allow smaller memory footprint */\n\t\t\t\tcase CFG_CNF_OWN_DTIM_PERIOD:\n#ifdef WARP\n\t\t\t\tcase CFG_CNF_OWN_BEACON_INTERVAL: /* Own Beacon Interval */\n#endif /* WARP */\n#ifdef USE_WDS\n\t\t\t\tcase CFG_CNF_WDS_ADDR1:\n\t\t\t\tcase CFG_CNF_WDS_ADDR2:\n\t\t\t\tcase CFG_CNF_WDS_ADDR3:\n\t\t\t\tcase CFG_CNF_WDS_ADDR4:\n\t\t\t\tcase CFG_CNF_WDS_ADDR5:\n\t\t\t\tcase CFG_CNF_WDS_ADDR6:\n#endif\n\t\t\t\tcase CFG_CNF_MCAST_PM_BUF:\n\t\t\t\tcase CFG_CNF_REJECT_ANY:\n#endif\n\n\t\t\t\tcase CFG_CNF_ENCRYPTION:\n\t\t\t\tcase CFG_CNF_AUTHENTICATION:\n#if 1 /* ;? (HCF_TYPE) & HCF_TYPE_AP */\n\t\t/* ;?should we restore this to allow smaller memory footprint */\n\n\t\t\t\tcase CFG_CNF_EXCL_UNENCRYPTED:\n\t\t\t\tcase CFG_CNF_MCAST_RATE:\n\t\t\t\tcase CFG_CNF_INTRA_BSS_RELAY:\n#endif\n\n\t\t\t\tcase CFG_CNF_MICRO_WAVE:\n\t\t\t\t/* case CFG_CNF_LOAD_BALANCING: */\n\t\t\t\t/* case CFG_CNF_MEDIUM_DISTRIBUTION: */\n\t\t\t\t/* case CFG_CNF_RX_ALL_GROUP_ADDRESS: */\n\t\t\t\t/* case CFG_CNF_COUNTRY_INFO: */\n\t\t\t\t/* case CFG_COUNTRY_STRING: */\n\t\t\t\tcase CFG_AP_MODE:\n\t\t\t\tcase CFG_ENCRYPT_STRING:\n\t\t\t\t/* case CFG_DRIVER_ENABLE: */\n\t\t\t\tcase CFG_WOLAS_ENABLE:\n\t\t\t\tcase CFG_MB_INFO:\n\t\t\t\tcase CFG_IFB:\n\t\t\t\t\tbreak;\n\t\t\t\t/* Deal with this dynamic MSF RID, as it's required for WPA */\n\t\t\t\tcase CFG_DRIVER_ENABLE:\n\t\t\t\t\tif (lp->driverEnable) {\n\t\t\t\t\t\thcf_cntl(&(lp->hcfCtx), HCF_CNTL_ENABLE | HCF_PORT_0);\n\t\t\t\t\t\thcf_cntl(&(lp->hcfCtx), HCF_CNTL_CONNECT);\n\t\t\t\t\t} else {\n\t\t\t\t\t\thcf_cntl(&(lp->hcfCtx), HCF_CNTL_DISABLE | HCF_PORT_0);\n\t\t\t\t\t\thcf_cntl(&(lp->hcfCtx), HCF_CNTL_DISCONNECT);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\twl_act_int_off(lp);\n\t\t\t\t\turq->result = hcf_put_info(&(lp->hcfCtx), (LTVP) pLtv);\n\t\t\t\t\twl_act_int_on(lp);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (ltvAllocated)\n\t\t\t\t\tkfree(pLtv);\n\t\t\t} else {\n\t\t\t\turq->result = UIL_FAILURE;\n\t\t\t}\n\t\t} else {\n\t\t\tDBG_ERROR(DbgInfo, \"EPERM\\n\");\n\t\t\turq->result = UIL_FAILURE;\n\t\t\tresult = -EPERM;\n\t\t}\n\t} else {\n\t\tDBG_ERROR(DbgInfo, \"UIL_ERR_WRONG_IFB\\n\");\n\t\turq->result = UIL_ERR_WRONG_IFB;\n\t}\n\n\tDBG_LEAVE(DbgInfo);\n\treturn result;\n} /* wvlan_uil_put_info */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'staging: wlags49_h2: buffer overflow setting station name\n\nWe need to check the length parameter before doing the memcpy(). I've\nactually changed it to strlcpy() as well so that it's NUL terminated.\n\nYou need CAP_NET_ADMIN to trigger these so it's not the end of the\nworld.\n\nReported-by: Nico Golde \nReported-by: Fabian Yamaguchi \nSigned-off-by: Dan Carpenter \nCc: stable@kernel.org\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr)\n{\n\tvcpu->arch.apic->vapic_addr = vapic_addr;\n\tif (vapic_addr)\n\t\t__set_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);\n\telse\n\t\t__clear_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);\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: static int wc_ecc_gen_k(WC_RNG* rng, int size, mp_int* k, mp_int* order)\n{\n int err;\n#ifdef WOLFSSL_SMALL_STACK\n byte* buf;\n#else\n byte buf[ECC_MAXSIZE_GEN];\n#endif\n\n#ifdef WOLFSSL_SMALL_STACK\n buf = (byte*)XMALLOC(ECC_MAXSIZE_GEN, NULL, DYNAMIC_TYPE_ECC_BUFFER);\n if (buf == NULL)\n return MEMORY_E;\n#endif\n\n /*generate 8 extra bytes to mitigate bias from the modulo operation below*/\n /*see section A.1.2 in 'Suite B Implementor's Guide to FIPS 186-3 (ECDSA)'*/\n size += 8;\n\n /* make up random string */\n err = wc_RNG_GenerateBlock(rng, buf, size);\n\n /* load random buffer data into k */\n if (err == 0)\n err = mp_read_unsigned_bin(k, (byte*)buf, size);\n\n /* quick sanity check to make sure we're not dealing with a 0 key */\n if (err == MP_OKAY) {\n if (mp_iszero(k) == MP_YES)\n err = MP_ZERO_E;\n }\n\n /* the key should be smaller than the order of base point */\n if (err == MP_OKAY) {\n if (mp_cmp(k, order) != MP_LT) {\n err = mp_mod(k, order, k);\n }\n }\n\n ForceZero(buf, ECC_MAXSIZE);\n#ifdef WOLFSSL_SMALL_STACK\n XFREE(buf, NULL, DYNAMIC_TYPE_ECC_BUFFER);\n#endif\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: void ComputeAsync(OpKernelContext* context, DoneCallback done) override {\n // The shape of 'grads' is [num_boxes, crop_height, crop_width, depth].\n const Tensor& grads = 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 'image_size' is [4].\n const Tensor& image_size = context->input(3);\n\n // Validate input shapes.\n OP_REQUIRES_ASYNC(context, grads.dims() == 4,\n errors::InvalidArgument(\"grads image must be 4-D\",\n grads.shape().DebugString()),\n done);\n const int crop_height = grads.dim_size(1);\n const int crop_width = grads.dim_size(2);\n OP_REQUIRES_ASYNC(\n context, crop_height > 0 && crop_width > 0,\n errors::InvalidArgument(\"grads 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 OP_REQUIRES_ASYNC(\n context, grads.dim_size(0) == num_boxes,\n errors::InvalidArgument(\"boxes and grads have incompatible shape\"),\n done);\n\n OP_REQUIRES_ASYNC(context, image_size.dims() == 1,\n errors::InvalidArgument(\"image_size must be 1-D\",\n image_size.shape().DebugString()),\n done);\n OP_REQUIRES_ASYNC(context, image_size.dim_size(0) == 4,\n errors::InvalidArgument(\"image_size must have 4 elements\",\n image_size.shape().DebugString()),\n done);\n auto image_size_vec = image_size.vec();\n const int batch_size = internal::SubtleMustCopy(image_size_vec(0));\n const int image_height = internal::SubtleMustCopy(image_size_vec(1));\n const int image_width = internal::SubtleMustCopy(image_size_vec(2));\n const int depth = internal::SubtleMustCopy(image_size_vec(3));\n OP_REQUIRES_ASYNC(\n context, image_height > 0 && image_width > 0,\n errors::InvalidArgument(\"image dimensions must be positive\"), done);\n OP_REQUIRES_ASYNC(\n context, grads.dim_size(3) == depth,\n errors::InvalidArgument(\"image_size and grads are incompatible\"), done);\n\n if (std::is_same::value) {\n OP_REQUIRES_ASYNC(\n context, !OpDeterminismRequired(),\n errors::Unimplemented(\n \"Deterministic GPU implementation of CropAndResizeBackpropImage\"\n \" not available.\"),\n done);\n }\n\n // Allocate output tensor.\n Tensor* output = nullptr;\n OP_REQUIRES_OK_ASYNC(\n context,\n context->allocate_output(\n 0, TensorShape({batch_size, image_height, image_width, depth}),\n &output),\n done);\n\n auto compute_callback = [this, context, output]() {\n const Tensor& grads = context->input(0);\n const Tensor& boxes = context->input(1);\n const Tensor& box_index = context->input(2);\n const bool status = functor::CropAndResizeBackpropImage()(\n context, grads.tensor(), boxes.tensor(),\n box_index.tensor(), output->tensor(), method_);\n\n if (!status) {\n context->SetStatus(errors::Internal(\n \"Failed to launch CropAndResizeBackpropImage kernel.\"));\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 int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,\n\t\t struct packet_type *pt, struct net_device *orig_dev)\n{\n\tstruct sock *sk;\n\tstruct packet_sock *po;\n\tstruct sockaddr_ll *sll;\n\tunion {\n\t\tstruct tpacket_hdr *h1;\n\t\tstruct tpacket2_hdr *h2;\n\t\tvoid *raw;\n\t} h;\n\tu8 *skb_head = skb->data;\n\tint skb_len = skb->len;\n\tunsigned int snaplen, res;\n\tunsigned long status = TP_STATUS_LOSING|TP_STATUS_USER;\n\tunsigned short macoff, netoff, hdrlen;\n\tstruct sk_buff *copy_skb = NULL;\n\tstruct timeval tv;\n\tstruct timespec ts;\n\tstruct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb);\n\n\tif (skb->pkt_type == PACKET_LOOPBACK)\n\t\tgoto drop;\n\n\tsk = pt->af_packet_priv;\n\tpo = pkt_sk(sk);\n\n\tif (!net_eq(dev_net(dev), sock_net(sk)))\n\t\tgoto drop;\n\n\tif (dev->header_ops) {\n\t\tif (sk->sk_type != SOCK_DGRAM)\n\t\t\tskb_push(skb, skb->data - skb_mac_header(skb));\n\t\telse if (skb->pkt_type == PACKET_OUTGOING) {\n\t\t\t/* Special case: outgoing packets have ll header at head */\n\t\t\tskb_pull(skb, skb_network_offset(skb));\n\t\t}\n\t}\n\n\tif (skb->ip_summed == CHECKSUM_PARTIAL)\n\t\tstatus |= TP_STATUS_CSUMNOTREADY;\n\n\tsnaplen = skb->len;\n\n\tres = run_filter(skb, sk, snaplen);\n\tif (!res)\n\t\tgoto drop_n_restore;\n\tif (snaplen > res)\n\t\tsnaplen = res;\n\n\tif (sk->sk_type == SOCK_DGRAM) {\n\t\tmacoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +\n\t\t\t\t po->tp_reserve;\n\t} else {\n\t\tunsigned maclen = skb_network_offset(skb);\n\t\tnetoff = TPACKET_ALIGN(po->tp_hdrlen +\n\t\t\t\t (maclen < 16 ? 16 : maclen)) +\n\t\t\tpo->tp_reserve;\n\t\tmacoff = netoff - maclen;\n\t}\n\n\tif (macoff + snaplen > po->rx_ring.frame_size) {\n\t\tif (po->copy_thresh &&\n\t\t atomic_read(&sk->sk_rmem_alloc) + skb->truesize <\n\t\t (unsigned)sk->sk_rcvbuf) {\n\t\t\tif (skb_shared(skb)) {\n\t\t\t\tcopy_skb = skb_clone(skb, GFP_ATOMIC);\n\t\t\t} else {\n\t\t\t\tcopy_skb = skb_get(skb);\n\t\t\t\tskb_head = skb->data;\n\t\t\t}\n\t\t\tif (copy_skb)\n\t\t\t\tskb_set_owner_r(copy_skb, sk);\n\t\t}\n\t\tsnaplen = po->rx_ring.frame_size - macoff;\n\t\tif ((int)snaplen < 0)\n\t\t\tsnaplen = 0;\n\t}\n\n\tspin_lock(&sk->sk_receive_queue.lock);\n\th.raw = packet_current_frame(po, &po->rx_ring, TP_STATUS_KERNEL);\n\tif (!h.raw)\n\t\tgoto ring_is_full;\n\tpacket_increment_head(&po->rx_ring);\n\tpo->stats.tp_packets++;\n\tif (copy_skb) {\n\t\tstatus |= TP_STATUS_COPY;\n\t\t__skb_queue_tail(&sk->sk_receive_queue, copy_skb);\n\t}\n\tif (!po->stats.tp_drops)\n\t\tstatus &= ~TP_STATUS_LOSING;\n\tspin_unlock(&sk->sk_receive_queue.lock);\n\n\tskb_copy_bits(skb, 0, h.raw + macoff, snaplen);\n\n\tswitch (po->tp_version) {\n\tcase TPACKET_V1:\n\t\th.h1->tp_len = skb->len;\n\t\th.h1->tp_snaplen = snaplen;\n\t\th.h1->tp_mac = macoff;\n\t\th.h1->tp_net = netoff;\n\t\tif ((po->tp_tstamp & SOF_TIMESTAMPING_SYS_HARDWARE)\n\t\t\t\t&& shhwtstamps->syststamp.tv64)\n\t\t\ttv = ktime_to_timeval(shhwtstamps->syststamp);\n\t\telse if ((po->tp_tstamp & SOF_TIMESTAMPING_RAW_HARDWARE)\n\t\t\t\t&& shhwtstamps->hwtstamp.tv64)\n\t\t\ttv = ktime_to_timeval(shhwtstamps->hwtstamp);\n\t\telse if (skb->tstamp.tv64)\n\t\t\ttv = ktime_to_timeval(skb->tstamp);\n\t\telse\n\t\t\tdo_gettimeofday(&tv);\n\t\th.h1->tp_sec = tv.tv_sec;\n\t\th.h1->tp_usec = tv.tv_usec;\n\t\thdrlen = sizeof(*h.h1);\n\t\tbreak;\n\tcase TPACKET_V2:\n\t\th.h2->tp_len = skb->len;\n\t\th.h2->tp_snaplen = snaplen;\n\t\th.h2->tp_mac = macoff;\n\t\th.h2->tp_net = netoff;\n\t\tif ((po->tp_tstamp & SOF_TIMESTAMPING_SYS_HARDWARE)\n\t\t\t\t&& shhwtstamps->syststamp.tv64)\n\t\t\tts = ktime_to_timespec(shhwtstamps->syststamp);\n\t\telse if ((po->tp_tstamp & SOF_TIMESTAMPING_RAW_HARDWARE)\n\t\t\t\t&& shhwtstamps->hwtstamp.tv64)\n\t\t\tts = ktime_to_timespec(shhwtstamps->hwtstamp);\n\t\telse if (skb->tstamp.tv64)\n\t\t\tts = ktime_to_timespec(skb->tstamp);\n\t\telse\n\t\t\tgetnstimeofday(&ts);\n\t\th.h2->tp_sec = ts.tv_sec;\n\t\th.h2->tp_nsec = ts.tv_nsec;\n\t\tif (vlan_tx_tag_present(skb)) {\n\t\t\th.h2->tp_vlan_tci = vlan_tx_tag_get(skb);\n\t\t\tstatus |= TP_STATUS_VLAN_VALID;\n\t\t} else {\n\t\t\th.h2->tp_vlan_tci = 0;\n\t\t}\n\t\thdrlen = sizeof(*h.h2);\n\t\tbreak;\n\tdefault:\n\t\tBUG();\n\t}\n\n\tsll = h.raw + TPACKET_ALIGN(hdrlen);\n\tsll->sll_halen = dev_parse_header(skb, sll->sll_addr);\n\tsll->sll_family = AF_PACKET;\n\tsll->sll_hatype = dev->type;\n\tsll->sll_protocol = skb->protocol;\n\tsll->sll_pkttype = skb->pkt_type;\n\tif (unlikely(po->origdev))\n\t\tsll->sll_ifindex = orig_dev->ifindex;\n\telse\n\t\tsll->sll_ifindex = dev->ifindex;\n\n\t__packet_set_status(po, h.raw, status);\n\tsmp_mb();\n#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1\n\t{\n\t\tu8 *start, *end;\n\n\t\tend = (u8 *)PAGE_ALIGN((unsigned long)h.raw + macoff + snaplen);\n\t\tfor (start = h.raw; start < end; start += PAGE_SIZE)\n\t\t\tflush_dcache_page(pgv_to_page(start));\n\t}\n#endif\n\n\tsk->sk_data_ready(sk, 0);\n\ndrop_n_restore:\n\tif (skb_head != skb->data && skb_shared(skb)) {\n\t\tskb->data = skb_head;\n\t\tskb->len = skb_len;\n\t}\ndrop:\n\tkfree_skb(skb);\n\treturn 0;\n\nring_is_full:\n\tpo->stats.tp_drops++;\n\tspin_unlock(&sk->sk_receive_queue.lock);\n\n\tsk->sk_data_ready(sk, 0);\n\tkfree_skb(copy_skb);\n\tgoto drop_n_restore;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-264'], 'message': 'af_packet: prevent information leak\n\nIn 2.6.27, commit 393e52e33c6c2 (packet: deliver VLAN TCI to userspace)\nadded a small information leak.\n\nAdd padding field and make sure its zeroed before copy to user.\n\nSigned-off-by: Eric Dumazet \nCC: Patrick McHardy \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: explicit DataFormatDimMapOp(OpKernelConstruction* context)\n : OpKernel(context) {\n string src_format;\n OP_REQUIRES_OK(context, context->GetAttr(\"src_format\", &src_format));\n string dst_format;\n OP_REQUIRES_OK(context, context->GetAttr(\"dst_format\", &dst_format));\n OP_REQUIRES(context, src_format.size() == 4 || src_format.size() == 5,\n errors::InvalidArgument(strings::StrCat(\n \"Source format must of length 4 or 5, received \"\n \"src_format = \",\n src_format)));\n OP_REQUIRES(\n context, dst_format.size() == 4 || dst_format.size() == 5,\n errors::InvalidArgument(strings::StrCat(\n \"Destination format must of length 4 or 5, received dst_format = \",\n dst_format)));\n dst_idx_ = Tensor(DT_INT32, {static_cast(src_format.size())});\n for (int i = 0; i < src_format.size(); ++i) {\n for (int j = 0; j < dst_format.size(); ++j) {\n if (dst_format[j] == src_format[i]) {\n dst_idx_.vec()(i) = j;\n break;\n }\n }\n }\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Validate that `DataFormat*` attributes form a permutation.\n\nThe `src_format` and `dst_format` attributes for the `DataFormatDimMap` and `DataFormatVecPermute` raw ops are supposed to determine a permutation. However, this was not validated and could result in unitialized memory accesses as well as writes outside of bounds and potential crashes.\n\nWhile here, we also test that the format attributes have the needed length, add tests for all validation failure cases, remove unnecessary calls to `strings::StrCat`, and fix a few grammar errors.\n\nThis will be cherry-picked on the supported release branches.\n\nPiperOrigin-RevId: 346135579\nChange-Id: I1c76392382c89ad8f072d5bc93d70669851eb404'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int log_replay(struct ntfs_inode *ni, bool *initialized)\n{\n\tint err;\n\tstruct ntfs_sb_info *sbi = ni->mi.sbi;\n\tstruct ntfs_log *log;\n\n\tstruct restart_info rst_info, rst_info2;\n\tu64 rec_lsn, ra_lsn, checkpt_lsn = 0, rlsn = 0;\n\tstruct ATTR_NAME_ENTRY *attr_names = NULL;\n\tstruct ATTR_NAME_ENTRY *ane;\n\tstruct RESTART_TABLE *dptbl = NULL;\n\tstruct RESTART_TABLE *trtbl = NULL;\n\tconst struct RESTART_TABLE *rt;\n\tstruct RESTART_TABLE *oatbl = NULL;\n\tstruct inode *inode;\n\tstruct OpenAttr *oa;\n\tstruct ntfs_inode *ni_oe;\n\tstruct ATTRIB *attr = NULL;\n\tu64 size, vcn, undo_next_lsn;\n\tCLST rno, lcn, lcn0, len0, clen;\n\tvoid *data;\n\tstruct NTFS_RESTART *rst = NULL;\n\tstruct lcb *lcb = NULL;\n\tstruct OPEN_ATTR_ENRTY *oe;\n\tstruct TRANSACTION_ENTRY *tr;\n\tstruct DIR_PAGE_ENTRY *dp;\n\tu32 i, bytes_per_attr_entry;\n\tu32 l_size = ni->vfs_inode.i_size;\n\tu32 orig_file_size = l_size;\n\tu32 page_size, vbo, tail, off, dlen;\n\tu32 saved_len, rec_len, transact_id;\n\tbool use_second_page;\n\tstruct RESTART_AREA *ra2, *ra = NULL;\n\tstruct CLIENT_REC *ca, *cr;\n\t__le16 client;\n\tstruct RESTART_HDR *rh;\n\tconst struct LFS_RECORD_HDR *frh;\n\tconst struct LOG_REC_HDR *lrh;\n\tbool is_mapped;\n\tbool is_ro = sb_rdonly(sbi->sb);\n\tu64 t64;\n\tu16 t16;\n\tu32 t32;\n\n\t/* Get the size of page. NOTE: To replay we can use default page. */\n#if PAGE_SIZE >= DefaultLogPageSize && PAGE_SIZE <= DefaultLogPageSize * 2\n\tpage_size = norm_file_page(PAGE_SIZE, &l_size, true);\n#else\n\tpage_size = norm_file_page(PAGE_SIZE, &l_size, false);\n#endif\n\tif (!page_size)\n\t\treturn -EINVAL;\n\n\tlog = kzalloc(sizeof(struct ntfs_log), GFP_NOFS);\n\tif (!log)\n\t\treturn -ENOMEM;\n\n\tlog->ni = ni;\n\tlog->l_size = l_size;\n\tlog->one_page_buf = kmalloc(page_size, GFP_NOFS);\n\n\tif (!log->one_page_buf) {\n\t\terr = -ENOMEM;\n\t\tgoto out;\n\t}\n\n\tlog->page_size = page_size;\n\tlog->page_mask = page_size - 1;\n\tlog->page_bits = blksize_bits(page_size);\n\n\t/* Look for a restart area on the disk. */\n\terr = log_read_rst(log, l_size, true, &rst_info);\n\tif (err)\n\t\tgoto out;\n\n\t/* remember 'initialized' */\n\t*initialized = rst_info.initialized;\n\n\tif (!rst_info.restart) {\n\t\tif (rst_info.initialized) {\n\t\t\t/* No restart area but the file is not initialized. */\n\t\t\terr = -EINVAL;\n\t\t\tgoto out;\n\t\t}\n\n\t\tlog_init_pg_hdr(log, page_size, page_size, 1, 1);\n\t\tlog_create(log, l_size, 0, get_random_int(), false, false);\n\n\t\tlog->ra = ra;\n\n\t\tra = log_create_ra(log);\n\t\tif (!ra) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto out;\n\t\t}\n\t\tlog->ra = ra;\n\t\tlog->init_ra = true;\n\n\t\tgoto process_log;\n\t}\n\n\t/*\n\t * If the restart offset above wasn't zero then we won't\n\t * look for a second restart.\n\t */\n\tif (rst_info.vbo)\n\t\tgoto check_restart_area;\n\n\terr = log_read_rst(log, l_size, false, &rst_info2);\n\n\t/* Determine which restart area to use. */\n\tif (!rst_info2.restart || rst_info2.last_lsn <= rst_info.last_lsn)\n\t\tgoto use_first_page;\n\n\tuse_second_page = true;\n\n\tif (rst_info.chkdsk_was_run && page_size != rst_info.vbo) {\n\t\tstruct RECORD_PAGE_HDR *sp = NULL;\n\t\tbool usa_error;\n\n\t\tif (!read_log_page(log, page_size, &sp, &usa_error) &&\n\t\t sp->rhdr.sign == NTFS_CHKD_SIGNATURE) {\n\t\t\tuse_second_page = false;\n\t\t}\n\t\tkfree(sp);\n\t}\n\n\tif (use_second_page) {\n\t\tkfree(rst_info.r_page);\n\t\tmemcpy(&rst_info, &rst_info2, sizeof(struct restart_info));\n\t\trst_info2.r_page = NULL;\n\t}\n\nuse_first_page:\n\tkfree(rst_info2.r_page);\n\ncheck_restart_area:\n\t/*\n\t * If the restart area is at offset 0, we want\n\t * to write the second restart area first.\n\t */\n\tlog->init_ra = !!rst_info.vbo;\n\n\t/* If we have a valid page then grab a pointer to the restart area. */\n\tra2 = rst_info.valid_page\n\t\t ? Add2Ptr(rst_info.r_page,\n\t\t\t\tle16_to_cpu(rst_info.r_page->ra_off))\n\t\t : NULL;\n\n\tif (rst_info.chkdsk_was_run ||\n\t (ra2 && ra2->client_idx[1] == LFS_NO_CLIENT_LE)) {\n\t\tbool wrapped = false;\n\t\tbool use_multi_page = false;\n\t\tu32 open_log_count;\n\n\t\t/* Do some checks based on whether we have a valid log page. */\n\t\tif (!rst_info.valid_page) {\n\t\t\topen_log_count = get_random_int();\n\t\t\tgoto init_log_instance;\n\t\t}\n\t\topen_log_count = le32_to_cpu(ra2->open_log_count);\n\n\t\t/*\n\t\t * If the restart page size isn't changing then we want to\n\t\t * check how much work we need to do.\n\t\t */\n\t\tif (page_size != le32_to_cpu(rst_info.r_page->sys_page_size))\n\t\t\tgoto init_log_instance;\n\ninit_log_instance:\n\t\tlog_init_pg_hdr(log, page_size, page_size, 1, 1);\n\n\t\tlog_create(log, l_size, rst_info.last_lsn, open_log_count,\n\t\t\t wrapped, use_multi_page);\n\n\t\tra = log_create_ra(log);\n\t\tif (!ra) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto out;\n\t\t}\n\t\tlog->ra = ra;\n\n\t\t/* Put the restart areas and initialize\n\t\t * the log file as required.\n\t\t */\n\t\tgoto process_log;\n\t}\n\n\tif (!ra2) {\n\t\terr = -EINVAL;\n\t\tgoto out;\n\t}\n\n\t/*\n\t * If the log page or the system page sizes have changed, we can't\n\t * use the log file. We must use the system page size instead of the\n\t * default size if there is not a clean shutdown.\n\t */\n\tt32 = le32_to_cpu(rst_info.r_page->sys_page_size);\n\tif (page_size != t32) {\n\t\tl_size = orig_file_size;\n\t\tpage_size =\n\t\t\tnorm_file_page(t32, &l_size, t32 == DefaultLogPageSize);\n\t}\n\n\tif (page_size != t32 ||\n\t page_size != le32_to_cpu(rst_info.r_page->page_size)) {\n\t\terr = -EINVAL;\n\t\tgoto out;\n\t}\n\n\t/* If the file size has shrunk then we won't mount it. */\n\tif (l_size < le64_to_cpu(ra2->l_size)) {\n\t\terr = -EINVAL;\n\t\tgoto out;\n\t}\n\n\tlog_init_pg_hdr(log, page_size, page_size,\n\t\t\tle16_to_cpu(rst_info.r_page->major_ver),\n\t\t\tle16_to_cpu(rst_info.r_page->minor_ver));\n\n\tlog->l_size = le64_to_cpu(ra2->l_size);\n\tlog->seq_num_bits = le32_to_cpu(ra2->seq_num_bits);\n\tlog->file_data_bits = sizeof(u64) * 8 - log->seq_num_bits;\n\tlog->seq_num_mask = (8 << log->file_data_bits) - 1;\n\tlog->last_lsn = le64_to_cpu(ra2->current_lsn);\n\tlog->seq_num = log->last_lsn >> log->file_data_bits;\n\tlog->ra_off = le16_to_cpu(rst_info.r_page->ra_off);\n\tlog->restart_size = log->sys_page_size - log->ra_off;\n\tlog->record_header_len = le16_to_cpu(ra2->rec_hdr_len);\n\tlog->ra_size = le16_to_cpu(ra2->ra_len);\n\tlog->data_off = le16_to_cpu(ra2->data_off);\n\tlog->data_size = log->page_size - log->data_off;\n\tlog->reserved = log->data_size - log->record_header_len;\n\n\tvbo = lsn_to_vbo(log, log->last_lsn);\n\n\tif (vbo < log->first_page) {\n\t\t/* This is a pseudo lsn. */\n\t\tlog->l_flags |= NTFSLOG_NO_LAST_LSN;\n\t\tlog->next_page = log->first_page;\n\t\tgoto find_oldest;\n\t}\n\n\t/* Find the end of this log record. */\n\toff = final_log_off(log, log->last_lsn,\n\t\t\t le32_to_cpu(ra2->last_lsn_data_len));\n\n\t/* If we wrapped the file then increment the sequence number. */\n\tif (off <= vbo) {\n\t\tlog->seq_num += 1;\n\t\tlog->l_flags |= NTFSLOG_WRAPPED;\n\t}\n\n\t/* Now compute the next log page to use. */\n\tvbo &= ~log->sys_page_mask;\n\ttail = log->page_size - (off & log->page_mask) - 1;\n\n\t/*\n\t *If we can fit another log record on the page,\n\t * move back a page the log file.\n\t */\n\tif (tail >= log->record_header_len) {\n\t\tlog->l_flags |= NTFSLOG_REUSE_TAIL;\n\t\tlog->next_page = vbo;\n\t} else {\n\t\tlog->next_page = next_page_off(log, vbo);\n\t}\n\nfind_oldest:\n\t/*\n\t * Find the oldest client lsn. Use the last\n\t * flushed lsn as a starting point.\n\t */\n\tlog->oldest_lsn = log->last_lsn;\n\toldest_client_lsn(Add2Ptr(ra2, le16_to_cpu(ra2->client_off)),\n\t\t\t ra2->client_idx[1], &log->oldest_lsn);\n\tlog->oldest_lsn_off = lsn_to_vbo(log, log->oldest_lsn);\n\n\tif (log->oldest_lsn_off < log->first_page)\n\t\tlog->l_flags |= NTFSLOG_NO_OLDEST_LSN;\n\n\tif (!(ra2->flags & RESTART_SINGLE_PAGE_IO))\n\t\tlog->l_flags |= NTFSLOG_WRAPPED | NTFSLOG_MULTIPLE_PAGE_IO;\n\n\tlog->current_openlog_count = le32_to_cpu(ra2->open_log_count);\n\tlog->total_avail_pages = log->l_size - log->first_page;\n\tlog->total_avail = log->total_avail_pages >> log->page_bits;\n\tlog->max_current_avail = log->total_avail * log->reserved;\n\tlog->total_avail = log->total_avail * log->data_size;\n\n\tlog->current_avail = current_log_avail(log);\n\n\tra = kzalloc(log->restart_size, GFP_NOFS);\n\tif (!ra) {\n\t\terr = -ENOMEM;\n\t\tgoto out;\n\t}\n\tlog->ra = ra;\n\n\tt16 = le16_to_cpu(ra2->client_off);\n\tif (t16 == offsetof(struct RESTART_AREA, clients)) {\n\t\tmemcpy(ra, ra2, log->ra_size);\n\t} else {\n\t\tmemcpy(ra, ra2, offsetof(struct RESTART_AREA, clients));\n\t\tmemcpy(ra->clients, Add2Ptr(ra2, t16),\n\t\t le16_to_cpu(ra2->ra_len) - t16);\n\n\t\tlog->current_openlog_count = get_random_int();\n\t\tra->open_log_count = cpu_to_le32(log->current_openlog_count);\n\t\tlog->ra_size = offsetof(struct RESTART_AREA, clients) +\n\t\t\t sizeof(struct CLIENT_REC);\n\t\tra->client_off =\n\t\t\tcpu_to_le16(offsetof(struct RESTART_AREA, clients));\n\t\tra->ra_len = cpu_to_le16(log->ra_size);\n\t}\n\n\tle32_add_cpu(&ra->open_log_count, 1);\n\n\t/* Now we need to walk through looking for the last lsn. */\n\terr = last_log_lsn(log);\n\tif (err)\n\t\tgoto out;\n\n\tlog->current_avail = current_log_avail(log);\n\n\t/* Remember which restart area to write first. */\n\tlog->init_ra = rst_info.vbo;\n\nprocess_log:\n\t/* 1.0, 1.1, 2.0 log->major_ver/minor_ver - short values. */\n\tswitch ((log->major_ver << 16) + log->minor_ver) {\n\tcase 0x10000:\n\tcase 0x10001:\n\tcase 0x20000:\n\t\tbreak;\n\tdefault:\n\t\tntfs_warn(sbi->sb, \"\\x24LogFile version %d.%d is not supported\",\n\t\t\t log->major_ver, log->minor_ver);\n\t\terr = -EOPNOTSUPP;\n\t\tlog->set_dirty = true;\n\t\tgoto out;\n\t}\n\n\t/* One client \"NTFS\" per logfile. */\n\tca = Add2Ptr(ra, le16_to_cpu(ra->client_off));\n\n\tfor (client = ra->client_idx[1];; client = cr->next_client) {\n\t\tif (client == LFS_NO_CLIENT_LE) {\n\t\t\t/* Insert \"NTFS\" client LogFile. */\n\t\t\tclient = ra->client_idx[0];\n\t\t\tif (client == LFS_NO_CLIENT_LE) {\n\t\t\t\terr = -EINVAL;\n\t\t\t\tgoto out;\n\t\t\t}\n\n\t\t\tt16 = le16_to_cpu(client);\n\t\t\tcr = ca + t16;\n\n\t\t\tremove_client(ca, cr, &ra->client_idx[0]);\n\n\t\t\tcr->restart_lsn = 0;\n\t\t\tcr->oldest_lsn = cpu_to_le64(log->oldest_lsn);\n\t\t\tcr->name_bytes = cpu_to_le32(8);\n\t\t\tcr->name[0] = cpu_to_le16('N');\n\t\t\tcr->name[1] = cpu_to_le16('T');\n\t\t\tcr->name[2] = cpu_to_le16('F');\n\t\t\tcr->name[3] = cpu_to_le16('S');\n\n\t\t\tadd_client(ca, t16, &ra->client_idx[1]);\n\t\t\tbreak;\n\t\t}\n\n\t\tcr = ca + le16_to_cpu(client);\n\n\t\tif (cpu_to_le32(8) == cr->name_bytes &&\n\t\t cpu_to_le16('N') == cr->name[0] &&\n\t\t cpu_to_le16('T') == cr->name[1] &&\n\t\t cpu_to_le16('F') == cr->name[2] &&\n\t\t cpu_to_le16('S') == cr->name[3])\n\t\t\tbreak;\n\t}\n\n\t/* Update the client handle with the client block information. */\n\tlog->client_id.seq_num = cr->seq_num;\n\tlog->client_id.client_idx = client;\n\n\terr = read_rst_area(log, &rst, &ra_lsn);\n\tif (err)\n\t\tgoto out;\n\n\tif (!rst)\n\t\tgoto out;\n\n\tbytes_per_attr_entry = !rst->major_ver ? 0x2C : 0x28;\n\n\tcheckpt_lsn = le64_to_cpu(rst->check_point_start);\n\tif (!checkpt_lsn)\n\t\tcheckpt_lsn = ra_lsn;\n\n\t/* Allocate and Read the Transaction Table. */\n\tif (!rst->transact_table_len)\n\t\tgoto check_dirty_page_table;\n\n\tt64 = le64_to_cpu(rst->transact_table_lsn);\n\terr = read_log_rec_lcb(log, t64, lcb_ctx_prev, &lcb);\n\tif (err)\n\t\tgoto out;\n\n\tlrh = lcb->log_rec;\n\tfrh = lcb->lrh;\n\trec_len = le32_to_cpu(frh->client_data_len);\n\n\tif (!check_log_rec(lrh, rec_len, le32_to_cpu(frh->transact_id),\n\t\t\t bytes_per_attr_entry)) {\n\t\terr = -EINVAL;\n\t\tgoto out;\n\t}\n\n\tt16 = le16_to_cpu(lrh->redo_off);\n\n\trt = Add2Ptr(lrh, t16);\n\tt32 = rec_len - t16;\n\n\t/* Now check that this is a valid restart table. */\n\tif (!check_rstbl(rt, t32)) {\n\t\terr = -EINVAL;\n\t\tgoto out;\n\t}\n\n\ttrtbl = kmemdup(rt, t32, GFP_NOFS);\n\tif (!trtbl) {\n\t\terr = -ENOMEM;\n\t\tgoto out;\n\t}\n\n\tlcb_put(lcb);\n\tlcb = NULL;\n\ncheck_dirty_page_table:\n\t/* The next record back should be the Dirty Pages Table. */\n\tif (!rst->dirty_pages_len)\n\t\tgoto check_attribute_names;\n\n\tt64 = le64_to_cpu(rst->dirty_pages_table_lsn);\n\terr = read_log_rec_lcb(log, t64, lcb_ctx_prev, &lcb);\n\tif (err)\n\t\tgoto out;\n\n\tlrh = lcb->log_rec;\n\tfrh = lcb->lrh;\n\trec_len = le32_to_cpu(frh->client_data_len);\n\n\tif (!check_log_rec(lrh, rec_len, le32_to_cpu(frh->transact_id),\n\t\t\t bytes_per_attr_entry)) {\n\t\terr = -EINVAL;\n\t\tgoto out;\n\t}\n\n\tt16 = le16_to_cpu(lrh->redo_off);\n\n\trt = Add2Ptr(lrh, t16);\n\tt32 = rec_len - t16;\n\n\t/* Now check that this is a valid restart table. */\n\tif (!check_rstbl(rt, t32)) {\n\t\terr = -EINVAL;\n\t\tgoto out;\n\t}\n\n\tdptbl = kmemdup(rt, t32, GFP_NOFS);\n\tif (!dptbl) {\n\t\terr = -ENOMEM;\n\t\tgoto out;\n\t}\n\n\t/* Convert Ra version '0' into version '1'. */\n\tif (rst->major_ver)\n\t\tgoto end_conv_1;\n\n\tdp = NULL;\n\twhile ((dp = enum_rstbl(dptbl, dp))) {\n\t\tstruct DIR_PAGE_ENTRY_32 *dp0 = (struct DIR_PAGE_ENTRY_32 *)dp;\n\t\t// NOTE: Danger. Check for of boundary.\n\t\tmemmove(&dp->vcn, &dp0->vcn_low,\n\t\t\t2 * sizeof(u64) +\n\t\t\t\tle32_to_cpu(dp->lcns_follow) * sizeof(u64));\n\t}\n\nend_conv_1:\n\tlcb_put(lcb);\n\tlcb = NULL;\n\n\t/*\n\t * Go through the table and remove the duplicates,\n\t * remembering the oldest lsn values.\n\t */\n\tif (sbi->cluster_size <= log->page_size)\n\t\tgoto trace_dp_table;\n\n\tdp = NULL;\n\twhile ((dp = enum_rstbl(dptbl, dp))) {\n\t\tstruct DIR_PAGE_ENTRY *next = dp;\n\n\t\twhile ((next = enum_rstbl(dptbl, next))) {\n\t\t\tif (next->target_attr == dp->target_attr &&\n\t\t\t next->vcn == dp->vcn) {\n\t\t\t\tif (le64_to_cpu(next->oldest_lsn) <\n\t\t\t\t le64_to_cpu(dp->oldest_lsn)) {\n\t\t\t\t\tdp->oldest_lsn = next->oldest_lsn;\n\t\t\t\t}\n\n\t\t\t\tfree_rsttbl_idx(dptbl, PtrOffset(dptbl, next));\n\t\t\t}\n\t\t}\n\t}\ntrace_dp_table:\ncheck_attribute_names:\n\t/* The next record should be the Attribute Names. */\n\tif (!rst->attr_names_len)\n\t\tgoto check_attr_table;\n\n\tt64 = le64_to_cpu(rst->attr_names_lsn);\n\terr = read_log_rec_lcb(log, t64, lcb_ctx_prev, &lcb);\n\tif (err)\n\t\tgoto out;\n\n\tlrh = lcb->log_rec;\n\tfrh = lcb->lrh;\n\trec_len = le32_to_cpu(frh->client_data_len);\n\n\tif (!check_log_rec(lrh, rec_len, le32_to_cpu(frh->transact_id),\n\t\t\t bytes_per_attr_entry)) {\n\t\terr = -EINVAL;\n\t\tgoto out;\n\t}\n\n\tt32 = lrh_length(lrh);\n\trec_len -= t32;\n\n\tattr_names = kmemdup(Add2Ptr(lrh, t32), rec_len, GFP_NOFS);\n\n\tlcb_put(lcb);\n\tlcb = NULL;\n\ncheck_attr_table:\n\t/* The next record should be the attribute Table. */\n\tif (!rst->open_attr_len)\n\t\tgoto check_attribute_names2;\n\n\tt64 = le64_to_cpu(rst->open_attr_table_lsn);\n\terr = read_log_rec_lcb(log, t64, lcb_ctx_prev, &lcb);\n\tif (err)\n\t\tgoto out;\n\n\tlrh = lcb->log_rec;\n\tfrh = lcb->lrh;\n\trec_len = le32_to_cpu(frh->client_data_len);\n\n\tif (!check_log_rec(lrh, rec_len, le32_to_cpu(frh->transact_id),\n\t\t\t bytes_per_attr_entry)) {\n\t\terr = -EINVAL;\n\t\tgoto out;\n\t}\n\n\tt16 = le16_to_cpu(lrh->redo_off);\n\n\trt = Add2Ptr(lrh, t16);\n\tt32 = rec_len - t16;\n\n\tif (!check_rstbl(rt, t32)) {\n\t\terr = -EINVAL;\n\t\tgoto out;\n\t}\n\n\toatbl = kmemdup(rt, t32, GFP_NOFS);\n\tif (!oatbl) {\n\t\terr = -ENOMEM;\n\t\tgoto out;\n\t}\n\n\tlog->open_attr_tbl = oatbl;\n\n\t/* Clear all of the Attr pointers. */\n\toe = NULL;\n\twhile ((oe = enum_rstbl(oatbl, oe))) {\n\t\tif (!rst->major_ver) {\n\t\t\tstruct OPEN_ATTR_ENRTY_32 oe0;\n\n\t\t\t/* Really 'oe' points to OPEN_ATTR_ENRTY_32. */\n\t\t\tmemcpy(&oe0, oe, SIZEOF_OPENATTRIBUTEENTRY0);\n\n\t\t\toe->bytes_per_index = oe0.bytes_per_index;\n\t\t\toe->type = oe0.type;\n\t\t\toe->is_dirty_pages = oe0.is_dirty_pages;\n\t\t\toe->name_len = 0;\n\t\t\toe->ref = oe0.ref;\n\t\t\toe->open_record_lsn = oe0.open_record_lsn;\n\t\t}\n\n\t\toe->is_attr_name = 0;\n\t\toe->ptr = NULL;\n\t}\n\n\tlcb_put(lcb);\n\tlcb = NULL;\n\ncheck_attribute_names2:\n\tif (!rst->attr_names_len)\n\t\tgoto trace_attribute_table;\n\n\tane = attr_names;\n\tif (!oatbl)\n\t\tgoto trace_attribute_table;\n\twhile (ane->off) {\n\t\t/* TODO: Clear table on exit! */\n\t\toe = Add2Ptr(oatbl, le16_to_cpu(ane->off));\n\t\tt16 = le16_to_cpu(ane->name_bytes);\n\t\toe->name_len = t16 / sizeof(short);\n\t\toe->ptr = ane->name;\n\t\toe->is_attr_name = 2;\n\t\tane = Add2Ptr(ane, sizeof(struct ATTR_NAME_ENTRY) + t16);\n\t}\n\ntrace_attribute_table:\n\t/*\n\t * If the checkpt_lsn is zero, then this is a freshly\n\t * formatted disk and we have no work to do.\n\t */\n\tif (!checkpt_lsn) {\n\t\terr = 0;\n\t\tgoto out;\n\t}\n\n\tif (!oatbl) {\n\t\toatbl = init_rsttbl(bytes_per_attr_entry, 8);\n\t\tif (!oatbl) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto out;\n\t\t}\n\t}\n\n\tlog->open_attr_tbl = oatbl;\n\n\t/* Start the analysis pass from the Checkpoint lsn. */\n\trec_lsn = checkpt_lsn;\n\n\t/* Read the first lsn. */\n\terr = read_log_rec_lcb(log, checkpt_lsn, lcb_ctx_next, &lcb);\n\tif (err)\n\t\tgoto out;\n\n\t/* Loop to read all subsequent records to the end of the log file. */\nnext_log_record_analyze:\n\terr = read_next_log_rec(log, lcb, &rec_lsn);\n\tif (err)\n\t\tgoto out;\n\n\tif (!rec_lsn)\n\t\tgoto end_log_records_enumerate;\n\n\tfrh = lcb->lrh;\n\ttransact_id = le32_to_cpu(frh->transact_id);\n\trec_len = le32_to_cpu(frh->client_data_len);\n\tlrh = lcb->log_rec;\n\n\tif (!check_log_rec(lrh, rec_len, transact_id, bytes_per_attr_entry)) {\n\t\terr = -EINVAL;\n\t\tgoto out;\n\t}\n\n\t/*\n\t * The first lsn after the previous lsn remembered\n\t * the checkpoint is the first candidate for the rlsn.\n\t */\n\tif (!rlsn)\n\t\trlsn = rec_lsn;\n\n\tif (LfsClientRecord != frh->record_type)\n\t\tgoto next_log_record_analyze;\n\n\t/*\n\t * Now update the Transaction Table for this transaction. If there\n\t * is no entry present or it is unallocated we allocate the entry.\n\t */\n\tif (!trtbl) {\n\t\ttrtbl = init_rsttbl(sizeof(struct TRANSACTION_ENTRY),\n\t\t\t\t INITIAL_NUMBER_TRANSACTIONS);\n\t\tif (!trtbl) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto out;\n\t\t}\n\t}\n\n\ttr = Add2Ptr(trtbl, transact_id);\n\n\tif (transact_id >= bytes_per_rt(trtbl) ||\n\t tr->next != RESTART_ENTRY_ALLOCATED_LE) {\n\t\ttr = alloc_rsttbl_from_idx(&trtbl, transact_id);\n\t\tif (!tr) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto out;\n\t\t}\n\t\ttr->transact_state = TransactionActive;\n\t\ttr->first_lsn = cpu_to_le64(rec_lsn);\n\t}\n\n\ttr->prev_lsn = tr->undo_next_lsn = cpu_to_le64(rec_lsn);\n\n\t/*\n\t * If this is a compensation log record, then change\n\t * the undo_next_lsn to be the undo_next_lsn of this record.\n\t */\n\tif (lrh->undo_op == cpu_to_le16(CompensationLogRecord))\n\t\ttr->undo_next_lsn = frh->client_undo_next_lsn;\n\n\t/* Dispatch to handle log record depending on type. */\n\tswitch (le16_to_cpu(lrh->redo_op)) {\n\tcase InitializeFileRecordSegment:\n\tcase DeallocateFileRecordSegment:\n\tcase WriteEndOfFileRecordSegment:\n\tcase CreateAttribute:\n\tcase DeleteAttribute:\n\tcase UpdateResidentValue:\n\tcase UpdateNonresidentValue:\n\tcase UpdateMappingPairs:\n\tcase SetNewAttributeSizes:\n\tcase AddIndexEntryRoot:\n\tcase DeleteIndexEntryRoot:\n\tcase AddIndexEntryAllocation:\n\tcase DeleteIndexEntryAllocation:\n\tcase WriteEndOfIndexBuffer:\n\tcase SetIndexEntryVcnRoot:\n\tcase SetIndexEntryVcnAllocation:\n\tcase UpdateFileNameRoot:\n\tcase UpdateFileNameAllocation:\n\tcase SetBitsInNonresidentBitMap:\n\tcase ClearBitsInNonresidentBitMap:\n\tcase UpdateRecordDataRoot:\n\tcase UpdateRecordDataAllocation:\n\tcase ZeroEndOfFileRecord:\n\t\tt16 = le16_to_cpu(lrh->target_attr);\n\t\tt64 = le64_to_cpu(lrh->target_vcn);\n\t\tdp = find_dp(dptbl, t16, t64);\n\n\t\tif (dp)\n\t\t\tgoto copy_lcns;\n\n\t\t/*\n\t\t * Calculate the number of clusters per page the system\n\t\t * which wrote the checkpoint, possibly creating the table.\n\t\t */\n\t\tif (dptbl) {\n\t\t\tt32 = (le16_to_cpu(dptbl->size) -\n\t\t\t sizeof(struct DIR_PAGE_ENTRY)) /\n\t\t\t sizeof(u64);\n\t\t} else {\n\t\t\tt32 = log->clst_per_page;\n\t\t\tkfree(dptbl);\n\t\t\tdptbl = init_rsttbl(struct_size(dp, page_lcns, t32),\n\t\t\t\t\t 32);\n\t\t\tif (!dptbl) {\n\t\t\t\terr = -ENOMEM;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t}\n\n\t\tdp = alloc_rsttbl_idx(&dptbl);\n\t\tif (!dp) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto out;\n\t\t}\n\t\tdp->target_attr = cpu_to_le32(t16);\n\t\tdp->transfer_len = cpu_to_le32(t32 << sbi->cluster_bits);\n\t\tdp->lcns_follow = cpu_to_le32(t32);\n\t\tdp->vcn = cpu_to_le64(t64 & ~((u64)t32 - 1));\n\t\tdp->oldest_lsn = cpu_to_le64(rec_lsn);\n\ncopy_lcns:\n\t\t/*\n\t\t * Copy the Lcns from the log record into the Dirty Page Entry.\n\t\t * TODO: For different page size support, must somehow make\n\t\t * whole routine a loop, case Lcns do not fit below.\n\t\t */\n\t\tt16 = le16_to_cpu(lrh->lcns_follow);\n\t\tfor (i = 0; i < t16; i++) {\n\t\t\tsize_t j = (size_t)(le64_to_cpu(lrh->target_vcn) -\n\t\t\t\t\t le64_to_cpu(dp->vcn));\n\t\t\tdp->page_lcns[j + i] = lrh->page_lcns[i];\n\t\t}\n\n\t\tgoto next_log_record_analyze;\n\n\tcase DeleteDirtyClusters: {\n\t\tu32 range_count =\n\t\t\tle16_to_cpu(lrh->redo_len) / sizeof(struct LCN_RANGE);\n\t\tconst struct LCN_RANGE *r =\n\t\t\tAdd2Ptr(lrh, le16_to_cpu(lrh->redo_off));\n\n\t\t/* Loop through all of the Lcn ranges this log record. */\n\t\tfor (i = 0; i < range_count; i++, r++) {\n\t\t\tu64 lcn0 = le64_to_cpu(r->lcn);\n\t\t\tu64 lcn_e = lcn0 + le64_to_cpu(r->len) - 1;\n\n\t\t\tdp = NULL;\n\t\t\twhile ((dp = enum_rstbl(dptbl, dp))) {\n\t\t\t\tu32 j;\n\n\t\t\t\tt32 = le32_to_cpu(dp->lcns_follow);\n\t\t\t\tfor (j = 0; j < t32; j++) {\n\t\t\t\t\tt64 = le64_to_cpu(dp->page_lcns[j]);\n\t\t\t\t\tif (t64 >= lcn0 && t64 <= lcn_e)\n\t\t\t\t\t\tdp->page_lcns[j] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tgoto next_log_record_analyze;\n\t\t;\n\t}\n\n\tcase OpenNonresidentAttribute:\n\t\tt16 = le16_to_cpu(lrh->target_attr);\n\t\tif (t16 >= bytes_per_rt(oatbl)) {\n\t\t\t/*\n\t\t\t * Compute how big the table needs to be.\n\t\t\t * Add 10 extra entries for some cushion.\n\t\t\t */\n\t\t\tu32 new_e = t16 / le16_to_cpu(oatbl->size);\n\n\t\t\tnew_e += 10 - le16_to_cpu(oatbl->used);\n\n\t\t\toatbl = extend_rsttbl(oatbl, new_e, ~0u);\n\t\t\tlog->open_attr_tbl = oatbl;\n\t\t\tif (!oatbl) {\n\t\t\t\terr = -ENOMEM;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t}\n\n\t\t/* Point to the entry being opened. */\n\t\toe = alloc_rsttbl_from_idx(&oatbl, t16);\n\t\tlog->open_attr_tbl = oatbl;\n\t\tif (!oe) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto out;\n\t\t}\n\n\t\t/* Initialize this entry from the log record. */\n\t\tt16 = le16_to_cpu(lrh->redo_off);\n\t\tif (!rst->major_ver) {\n\t\t\t/* Convert version '0' into version '1'. */\n\t\t\tstruct OPEN_ATTR_ENRTY_32 *oe0 = Add2Ptr(lrh, t16);\n\n\t\t\toe->bytes_per_index = oe0->bytes_per_index;\n\t\t\toe->type = oe0->type;\n\t\t\toe->is_dirty_pages = oe0->is_dirty_pages;\n\t\t\toe->name_len = 0; //oe0.name_len;\n\t\t\toe->ref = oe0->ref;\n\t\t\toe->open_record_lsn = oe0->open_record_lsn;\n\t\t} else {\n\t\t\tmemcpy(oe, Add2Ptr(lrh, t16), bytes_per_attr_entry);\n\t\t}\n\n\t\tt16 = le16_to_cpu(lrh->undo_len);\n\t\tif (t16) {\n\t\t\toe->ptr = kmalloc(t16, GFP_NOFS);\n\t\t\tif (!oe->ptr) {\n\t\t\t\terr = -ENOMEM;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\toe->name_len = t16 / sizeof(short);\n\t\t\tmemcpy(oe->ptr,\n\t\t\t Add2Ptr(lrh, le16_to_cpu(lrh->undo_off)), t16);\n\t\t\toe->is_attr_name = 1;\n\t\t} else {\n\t\t\toe->ptr = NULL;\n\t\t\toe->is_attr_name = 0;\n\t\t}\n\n\t\tgoto next_log_record_analyze;\n\n\tcase HotFix:\n\t\tt16 = le16_to_cpu(lrh->target_attr);\n\t\tt64 = le64_to_cpu(lrh->target_vcn);\n\t\tdp = find_dp(dptbl, t16, t64);\n\t\tif (dp) {\n\t\t\tsize_t j = le64_to_cpu(lrh->target_vcn) -\n\t\t\t\t le64_to_cpu(dp->vcn);\n\t\t\tif (dp->page_lcns[j])\n\t\t\t\tdp->page_lcns[j] = lrh->page_lcns[0];\n\t\t}\n\t\tgoto next_log_record_analyze;\n\n\tcase EndTopLevelAction:\n\t\ttr = Add2Ptr(trtbl, transact_id);\n\t\ttr->prev_lsn = cpu_to_le64(rec_lsn);\n\t\ttr->undo_next_lsn = frh->client_undo_next_lsn;\n\t\tgoto next_log_record_analyze;\n\n\tcase PrepareTransaction:\n\t\ttr = Add2Ptr(trtbl, transact_id);\n\t\ttr->transact_state = TransactionPrepared;\n\t\tgoto next_log_record_analyze;\n\n\tcase CommitTransaction:\n\t\ttr = Add2Ptr(trtbl, transact_id);\n\t\ttr->transact_state = TransactionCommitted;\n\t\tgoto next_log_record_analyze;\n\n\tcase ForgetTransaction:\n\t\tfree_rsttbl_idx(trtbl, transact_id);\n\t\tgoto next_log_record_analyze;\n\n\tcase Noop:\n\tcase OpenAttributeTableDump:\n\tcase AttributeNamesDump:\n\tcase DirtyPageTableDump:\n\tcase TransactionTableDump:\n\t\t/* The following cases require no action the Analysis Pass. */\n\t\tgoto next_log_record_analyze;\n\n\tdefault:\n\t\t/*\n\t\t * All codes will be explicitly handled.\n\t\t * If we see a code we do not expect, then we are trouble.\n\t\t */\n\t\tgoto next_log_record_analyze;\n\t}\n\nend_log_records_enumerate:\n\tlcb_put(lcb);\n\tlcb = NULL;\n\n\t/*\n\t * Scan the Dirty Page Table and Transaction Table for\n\t * the lowest lsn, and return it as the Redo lsn.\n\t */\n\tdp = NULL;\n\twhile ((dp = enum_rstbl(dptbl, dp))) {\n\t\tt64 = le64_to_cpu(dp->oldest_lsn);\n\t\tif (t64 && t64 < rlsn)\n\t\t\trlsn = t64;\n\t}\n\n\ttr = NULL;\n\twhile ((tr = enum_rstbl(trtbl, tr))) {\n\t\tt64 = le64_to_cpu(tr->first_lsn);\n\t\tif (t64 && t64 < rlsn)\n\t\t\trlsn = t64;\n\t}\n\n\t/*\n\t * Only proceed if the Dirty Page Table or Transaction\n\t * table are not empty.\n\t */\n\tif ((!dptbl || !dptbl->total) && (!trtbl || !trtbl->total))\n\t\tgoto end_reply;\n\n\tsbi->flags |= NTFS_FLAGS_NEED_REPLAY;\n\tif (is_ro)\n\t\tgoto out;\n\n\t/* Reopen all of the attributes with dirty pages. */\n\toe = NULL;\nnext_open_attribute:\n\n\toe = enum_rstbl(oatbl, oe);\n\tif (!oe) {\n\t\terr = 0;\n\t\tdp = NULL;\n\t\tgoto next_dirty_page;\n\t}\n\n\toa = kzalloc(sizeof(struct OpenAttr), GFP_NOFS);\n\tif (!oa) {\n\t\terr = -ENOMEM;\n\t\tgoto out;\n\t}\n\n\tinode = ntfs_iget5(sbi->sb, &oe->ref, NULL);\n\tif (IS_ERR(inode))\n\t\tgoto fake_attr;\n\n\tif (is_bad_inode(inode)) {\n\t\tiput(inode);\nfake_attr:\n\t\tif (oa->ni) {\n\t\t\tiput(&oa->ni->vfs_inode);\n\t\t\toa->ni = NULL;\n\t\t}\n\n\t\tattr = attr_create_nonres_log(sbi, oe->type, 0, oe->ptr,\n\t\t\t\t\t oe->name_len, 0);\n\t\tif (!attr) {\n\t\t\tkfree(oa);\n\t\t\terr = -ENOMEM;\n\t\t\tgoto out;\n\t\t}\n\t\toa->attr = attr;\n\t\toa->run1 = &oa->run0;\n\t\tgoto final_oe;\n\t}\n\n\tni_oe = ntfs_i(inode);\n\toa->ni = ni_oe;\n\n\tattr = ni_find_attr(ni_oe, NULL, NULL, oe->type, oe->ptr, oe->name_len,\n\t\t\t NULL, NULL);\n\n\tif (!attr)\n\t\tgoto fake_attr;\n\n\tt32 = le32_to_cpu(attr->size);\n\toa->attr = kmemdup(attr, t32, GFP_NOFS);\n\tif (!oa->attr)\n\t\tgoto fake_attr;\n\n\tif (!S_ISDIR(inode->i_mode)) {\n\t\tif (attr->type == ATTR_DATA && !attr->name_len) {\n\t\t\toa->run1 = &ni_oe->file.run;\n\t\t\tgoto final_oe;\n\t\t}\n\t} else {\n\t\tif (attr->type == ATTR_ALLOC &&\n\t\t attr->name_len == ARRAY_SIZE(I30_NAME) &&\n\t\t !memcmp(attr_name(attr), I30_NAME, sizeof(I30_NAME))) {\n\t\t\toa->run1 = &ni_oe->dir.alloc_run;\n\t\t\tgoto final_oe;\n\t\t}\n\t}\n\n\tif (attr->non_res) {\n\t\tu16 roff = le16_to_cpu(attr->nres.run_off);\n\t\tCLST svcn = le64_to_cpu(attr->nres.svcn);\n\n\t\terr = run_unpack(&oa->run0, sbi, inode->i_ino, svcn,\n\t\t\t\t le64_to_cpu(attr->nres.evcn), svcn,\n\t\t\t\t Add2Ptr(attr, roff), t32 - roff);\n\t\tif (err < 0) {\n\t\t\tkfree(oa->attr);\n\t\t\toa->attr = NULL;\n\t\t\tgoto fake_attr;\n\t\t}\n\t\terr = 0;\n\t}\n\toa->run1 = &oa->run0;\n\tattr = oa->attr;\n\nfinal_oe:\n\tif (oe->is_attr_name == 1)\n\t\tkfree(oe->ptr);\n\toe->is_attr_name = 0;\n\toe->ptr = oa;\n\toe->name_len = attr->name_len;\n\n\tgoto next_open_attribute;\n\n\t/*\n\t * Now loop through the dirty page table to extract all of the Vcn/Lcn.\n\t * Mapping that we have, and insert it into the appropriate run.\n\t */\nnext_dirty_page:\n\tdp = enum_rstbl(dptbl, dp);\n\tif (!dp)\n\t\tgoto do_redo_1;\n\n\toe = Add2Ptr(oatbl, le32_to_cpu(dp->target_attr));\n\n\tif (oe->next != RESTART_ENTRY_ALLOCATED_LE)\n\t\tgoto next_dirty_page;\n\n\toa = oe->ptr;\n\tif (!oa)\n\t\tgoto next_dirty_page;\n\n\ti = -1;\nnext_dirty_page_vcn:\n\ti += 1;\n\tif (i >= le32_to_cpu(dp->lcns_follow))\n\t\tgoto next_dirty_page;\n\n\tvcn = le64_to_cpu(dp->vcn) + i;\n\tsize = (vcn + 1) << sbi->cluster_bits;\n\n\tif (!dp->page_lcns[i])\n\t\tgoto next_dirty_page_vcn;\n\n\trno = ino_get(&oe->ref);\n\tif (rno <= MFT_REC_MIRR &&\n\t size < (MFT_REC_VOL + 1) * sbi->record_size &&\n\t oe->type == ATTR_DATA) {\n\t\tgoto next_dirty_page_vcn;\n\t}\n\n\tlcn = le64_to_cpu(dp->page_lcns[i]);\n\n\tif ((!run_lookup_entry(oa->run1, vcn, &lcn0, &len0, NULL) ||\n\t lcn0 != lcn) &&\n\t !run_add_entry(oa->run1, vcn, lcn, 1, false)) {\n\t\terr = -ENOMEM;\n\t\tgoto out;\n\t}\n\tattr = oa->attr;\n\tt64 = le64_to_cpu(attr->nres.alloc_size);\n\tif (size > t64) {\n\t\tattr->nres.valid_size = attr->nres.data_size =\n\t\t\tattr->nres.alloc_size = cpu_to_le64(size);\n\t}\n\tgoto next_dirty_page_vcn;\n\ndo_redo_1:\n\t/*\n\t * Perform the Redo Pass, to restore all of the dirty pages to the same\n\t * contents that they had immediately before the crash. If the dirty\n\t * page table is empty, then we can skip the entire Redo Pass.\n\t */\n\tif (!dptbl || !dptbl->total)\n\t\tgoto do_undo_action;\n\n\trec_lsn = rlsn;\n\n\t/*\n\t * Read the record at the Redo lsn, before falling\n\t * into common code to handle each record.\n\t */\n\terr = read_log_rec_lcb(log, rlsn, lcb_ctx_next, &lcb);\n\tif (err)\n\t\tgoto out;\n\n\t/*\n\t * Now loop to read all of our log records forwards, until\n\t * we hit the end of the file, cleaning up at the end.\n\t */\ndo_action_next:\n\tfrh = lcb->lrh;\n\n\tif (LfsClientRecord != frh->record_type)\n\t\tgoto read_next_log_do_action;\n\n\ttransact_id = le32_to_cpu(frh->transact_id);\n\trec_len = le32_to_cpu(frh->client_data_len);\n\tlrh = lcb->log_rec;\n\n\tif (!check_log_rec(lrh, rec_len, transact_id, bytes_per_attr_entry)) {\n\t\terr = -EINVAL;\n\t\tgoto out;\n\t}\n\n\t/* Ignore log records that do not update pages. */\n\tif (lrh->lcns_follow)\n\t\tgoto find_dirty_page;\n\n\tgoto read_next_log_do_action;\n\nfind_dirty_page:\n\tt16 = le16_to_cpu(lrh->target_attr);\n\tt64 = le64_to_cpu(lrh->target_vcn);\n\tdp = find_dp(dptbl, t16, t64);\n\n\tif (!dp)\n\t\tgoto read_next_log_do_action;\n\n\tif (rec_lsn < le64_to_cpu(dp->oldest_lsn))\n\t\tgoto read_next_log_do_action;\n\n\tt16 = le16_to_cpu(lrh->target_attr);\n\tif (t16 >= bytes_per_rt(oatbl)) {\n\t\terr = -EINVAL;\n\t\tgoto out;\n\t}\n\n\toe = Add2Ptr(oatbl, t16);\n\n\tif (oe->next != RESTART_ENTRY_ALLOCATED_LE) {\n\t\terr = -EINVAL;\n\t\tgoto out;\n\t}\n\n\toa = oe->ptr;\n\n\tif (!oa) {\n\t\terr = -EINVAL;\n\t\tgoto out;\n\t}\n\tattr = oa->attr;\n\n\tvcn = le64_to_cpu(lrh->target_vcn);\n\n\tif (!run_lookup_entry(oa->run1, vcn, &lcn, NULL, NULL) ||\n\t lcn == SPARSE_LCN) {\n\t\tgoto read_next_log_do_action;\n\t}\n\n\t/* Point to the Redo data and get its length. */\n\tdata = Add2Ptr(lrh, le16_to_cpu(lrh->redo_off));\n\tdlen = le16_to_cpu(lrh->redo_len);\n\n\t/* Shorten length by any Lcns which were deleted. */\n\tsaved_len = dlen;\n\n\tfor (i = le16_to_cpu(lrh->lcns_follow); i; i--) {\n\t\tsize_t j;\n\t\tu32 alen, voff;\n\n\t\tvoff = le16_to_cpu(lrh->record_off) +\n\t\t le16_to_cpu(lrh->attr_off);\n\t\tvoff += le16_to_cpu(lrh->cluster_off) << SECTOR_SHIFT;\n\n\t\t/* If the Vcn question is allocated, we can just get out. */\n\t\tj = le64_to_cpu(lrh->target_vcn) - le64_to_cpu(dp->vcn);\n\t\tif (dp->page_lcns[j + i - 1])\n\t\t\tbreak;\n\n\t\tif (!saved_len)\n\t\t\tsaved_len = 1;\n\n\t\t/*\n\t\t * Calculate the allocated space left relative to the\n\t\t * log record Vcn, after removing this unallocated Vcn.\n\t\t */\n\t\talen = (i - 1) << sbi->cluster_bits;\n\n\t\t/*\n\t\t * If the update described this log record goes beyond\n\t\t * the allocated space, then we will have to reduce the length.\n\t\t */\n\t\tif (voff >= alen)\n\t\t\tdlen = 0;\n\t\telse if (voff + dlen > alen)\n\t\t\tdlen = alen - voff;\n\t}\n\n\t/*\n\t * If the resulting dlen from above is now zero,\n\t * we can skip this log record.\n\t */\n\tif (!dlen && saved_len)\n\t\tgoto read_next_log_do_action;\n\n\tt16 = le16_to_cpu(lrh->redo_op);\n\tif (can_skip_action(t16))\n\t\tgoto read_next_log_do_action;\n\n\t/* Apply the Redo operation a common routine. */\n\terr = do_action(log, oe, lrh, t16, data, dlen, rec_len, &rec_lsn);\n\tif (err)\n\t\tgoto out;\n\n\t/* Keep reading and looping back until end of file. */\nread_next_log_do_action:\n\terr = read_next_log_rec(log, lcb, &rec_lsn);\n\tif (!err && rec_lsn)\n\t\tgoto do_action_next;\n\n\tlcb_put(lcb);\n\tlcb = NULL;\n\ndo_undo_action:\n\t/* Scan Transaction Table. */\n\ttr = NULL;\ntransaction_table_next:\n\ttr = enum_rstbl(trtbl, tr);\n\tif (!tr)\n\t\tgoto undo_action_done;\n\n\tif (TransactionActive != tr->transact_state || !tr->undo_next_lsn) {\n\t\tfree_rsttbl_idx(trtbl, PtrOffset(trtbl, tr));\n\t\tgoto transaction_table_next;\n\t}\n\n\tlog->transaction_id = PtrOffset(trtbl, tr);\n\tundo_next_lsn = le64_to_cpu(tr->undo_next_lsn);\n\n\t/*\n\t * We only have to do anything if the transaction has\n\t * something its undo_next_lsn field.\n\t */\n\tif (!undo_next_lsn)\n\t\tgoto commit_undo;\n\n\t/* Read the first record to be undone by this transaction. */\n\terr = read_log_rec_lcb(log, undo_next_lsn, lcb_ctx_undo_next, &lcb);\n\tif (err)\n\t\tgoto out;\n\n\t/*\n\t * Now loop to read all of our log records forwards,\n\t * until we hit the end of the file, cleaning up at the end.\n\t */\nundo_action_next:\n\n\tlrh = lcb->log_rec;\n\tfrh = lcb->lrh;\n\ttransact_id = le32_to_cpu(frh->transact_id);\n\trec_len = le32_to_cpu(frh->client_data_len);\n\n\tif (!check_log_rec(lrh, rec_len, transact_id, bytes_per_attr_entry)) {\n\t\terr = -EINVAL;\n\t\tgoto out;\n\t}\n\n\tif (lrh->undo_op == cpu_to_le16(Noop))\n\t\tgoto read_next_log_undo_action;\n\n\toe = Add2Ptr(oatbl, le16_to_cpu(lrh->target_attr));\n\toa = oe->ptr;\n\n\tt16 = le16_to_cpu(lrh->lcns_follow);\n\tif (!t16)\n\t\tgoto add_allocated_vcns;\n\n\tis_mapped = run_lookup_entry(oa->run1, le64_to_cpu(lrh->target_vcn),\n\t\t\t\t &lcn, &clen, NULL);\n\n\t/*\n\t * If the mapping isn't already the table or the mapping\n\t * corresponds to a hole the mapping, we need to make sure\n\t * there is no partial page already memory.\n\t */\n\tif (is_mapped && lcn != SPARSE_LCN && clen >= t16)\n\t\tgoto add_allocated_vcns;\n\n\tvcn = le64_to_cpu(lrh->target_vcn);\n\tvcn &= ~(log->clst_per_page - 1);\n\nadd_allocated_vcns:\n\tfor (i = 0, vcn = le64_to_cpu(lrh->target_vcn),\n\t size = (vcn + 1) << sbi->cluster_bits;\n\t i < t16; i++, vcn += 1, size += sbi->cluster_size) {\n\t\tattr = oa->attr;\n\t\tif (!attr->non_res) {\n\t\t\tif (size > le32_to_cpu(attr->res.data_size))\n\t\t\t\tattr->res.data_size = cpu_to_le32(size);\n\t\t} else {\n\t\t\tif (size > le64_to_cpu(attr->nres.data_size))\n\t\t\t\tattr->nres.valid_size = attr->nres.data_size =\n\t\t\t\t\tattr->nres.alloc_size =\n\t\t\t\t\t\tcpu_to_le64(size);\n\t\t}\n\t}\n\n\tt16 = le16_to_cpu(lrh->undo_op);\n\tif (can_skip_action(t16))\n\t\tgoto read_next_log_undo_action;\n\n\t/* Point to the Redo data and get its length. */\n\tdata = Add2Ptr(lrh, le16_to_cpu(lrh->undo_off));\n\tdlen = le16_to_cpu(lrh->undo_len);\n\n\t/* It is time to apply the undo action. */\n\terr = do_action(log, oe, lrh, t16, data, dlen, rec_len, NULL);\n\nread_next_log_undo_action:\n\t/*\n\t * Keep reading and looping back until we have read the\n\t * last record for this transaction.\n\t */\n\terr = read_next_log_rec(log, lcb, &rec_lsn);\n\tif (err)\n\t\tgoto out;\n\n\tif (rec_lsn)\n\t\tgoto undo_action_next;\n\n\tlcb_put(lcb);\n\tlcb = NULL;\n\ncommit_undo:\n\tfree_rsttbl_idx(trtbl, log->transaction_id);\n\n\tlog->transaction_id = 0;\n\n\tgoto transaction_table_next;\n\nundo_action_done:\n\n\tntfs_update_mftmirr(sbi, 0);\n\n\tsbi->flags &= ~NTFS_FLAGS_NEED_REPLAY;\n\nend_reply:\n\n\terr = 0;\n\tif (is_ro)\n\t\tgoto out;\n\n\trh = kzalloc(log->page_size, GFP_NOFS);\n\tif (!rh) {\n\t\terr = -ENOMEM;\n\t\tgoto out;\n\t}\n\n\trh->rhdr.sign = NTFS_RSTR_SIGNATURE;\n\trh->rhdr.fix_off = cpu_to_le16(offsetof(struct RESTART_HDR, fixups));\n\tt16 = (log->page_size >> SECTOR_SHIFT) + 1;\n\trh->rhdr.fix_num = cpu_to_le16(t16);\n\trh->sys_page_size = cpu_to_le32(log->page_size);\n\trh->page_size = cpu_to_le32(log->page_size);\n\n\tt16 = ALIGN(offsetof(struct RESTART_HDR, fixups) + sizeof(short) * t16,\n\t\t 8);\n\trh->ra_off = cpu_to_le16(t16);\n\trh->minor_ver = cpu_to_le16(1); // 0x1A:\n\trh->major_ver = cpu_to_le16(1); // 0x1C:\n\n\tra2 = Add2Ptr(rh, t16);\n\tmemcpy(ra2, ra, sizeof(struct RESTART_AREA));\n\n\tra2->client_idx[0] = 0;\n\tra2->client_idx[1] = LFS_NO_CLIENT_LE;\n\tra2->flags = cpu_to_le16(2);\n\n\tle32_add_cpu(&ra2->open_log_count, 1);\n\n\tntfs_fix_pre_write(&rh->rhdr, log->page_size);\n\n\terr = ntfs_sb_write_run(sbi, &ni->file.run, 0, rh, log->page_size, 0);\n\tif (!err)\n\t\terr = ntfs_sb_write_run(sbi, &log->ni->file.run, log->page_size,\n\t\t\t\t\trh, log->page_size, 0);\n\n\tkfree(rh);\n\tif (err)\n\t\tgoto out;\n\nout:\n\tkfree(rst);\n\tif (lcb)\n\t\tlcb_put(lcb);\n\n\t/*\n\t * Scan the Open Attribute Table to close all of\n\t * the open attributes.\n\t */\n\toe = NULL;\n\twhile ((oe = enum_rstbl(oatbl, oe))) {\n\t\trno = ino_get(&oe->ref);\n\n\t\tif (oe->is_attr_name == 1) {\n\t\t\tkfree(oe->ptr);\n\t\t\toe->ptr = NULL;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (oe->is_attr_name)\n\t\t\tcontinue;\n\n\t\toa = oe->ptr;\n\t\tif (!oa)\n\t\t\tcontinue;\n\n\t\trun_close(&oa->run0);\n\t\tkfree(oa->attr);\n\t\tif (oa->ni)\n\t\t\tiput(&oa->ni->vfs_inode);\n\t\tkfree(oa);\n\t}\n\n\tkfree(trtbl);\n\tkfree(oatbl);\n\tkfree(dptbl);\n\tkfree(attr_names);\n\tkfree(rst_info.r_page);\n\n\tkfree(ra);\n\tkfree(log->one_page_buf);\n\n\tif (err)\n\t\tsbi->flags |= NTFS_FLAGS_NEED_REPLAY;\n\n\tif (err == -EROFS)\n\t\terr = 0;\n\telse if (log->set_dirty)\n\t\tntfs_set_state(sbi, NTFS_DIRTY_ERROR);\n\n\tkfree(log);\n\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'fs/ntfs3: Fix invalid free in log_replay\n\nlog_read_rst() returns ENOMEM error when there is not enough memory.\nIn this case, if info is returned without initialization,\nit attempts to kfree the uninitialized info->r_page pointer. This patch\nmoves the memset initialization code to before log_read_rst() is called.\n\nReported-by: Gerald Lee \nSigned-off-by: Namjae Jeon \nSigned-off-by: Konstantin Komarov '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int __driver_rfc4106_decrypt(struct aead_request *req)\n{\n\tu8 one_entry_in_sg = 0;\n\tu8 *src, *dst, *assoc;\n\tunsigned long tempCipherLen = 0;\n\t__be32 counter = cpu_to_be32(1);\n\tint retval = 0;\n\tstruct crypto_aead *tfm = crypto_aead_reqtfm(req);\n\tstruct aesni_rfc4106_gcm_ctx *ctx = aesni_rfc4106_gcm_ctx_get(tfm);\n\tu32 key_len = ctx->aes_key_expanded.key_length;\n\tvoid *aes_ctx = &(ctx->aes_key_expanded);\n\tunsigned long auth_tag_len = crypto_aead_authsize(tfm);\n\tu8 iv_and_authTag[32+AESNI_ALIGN];\n\tu8 *iv = (u8 *) PTR_ALIGN((u8 *)iv_and_authTag, AESNI_ALIGN);\n\tu8 *authTag = iv + 16;\n\tstruct scatter_walk src_sg_walk;\n\tstruct scatter_walk assoc_sg_walk;\n\tstruct scatter_walk dst_sg_walk;\n\tunsigned int i;\n\n\tif (unlikely((req->cryptlen < auth_tag_len) ||\n\t\t(req->assoclen != 8 && req->assoclen != 12)))\n\t\treturn -EINVAL;\n\tif (unlikely(auth_tag_len != 8 && auth_tag_len != 12 && auth_tag_len != 16))\n\t return -EINVAL;\n\tif (unlikely(key_len != AES_KEYSIZE_128 &&\n\t key_len != AES_KEYSIZE_192 &&\n\t key_len != AES_KEYSIZE_256))\n\t return -EINVAL;\n\n\t/* Assuming we are supporting rfc4106 64-bit extended */\n\t/* sequence numbers We need to have the AAD length */\n\t/* equal to 8 or 12 bytes */\n\n\ttempCipherLen = (unsigned long)(req->cryptlen - auth_tag_len);\n\t/* IV below built */\n\tfor (i = 0; i < 4; i++)\n\t\t*(iv+i) = ctx->nonce[i];\n\tfor (i = 0; i < 8; i++)\n\t\t*(iv+4+i) = req->iv[i];\n\t*((__be32 *)(iv+12)) = counter;\n\n\tif ((sg_is_last(req->src)) && (sg_is_last(req->assoc))) {\n\t\tone_entry_in_sg = 1;\n\t\tscatterwalk_start(&src_sg_walk, req->src);\n\t\tscatterwalk_start(&assoc_sg_walk, req->assoc);\n\t\tsrc = scatterwalk_map(&src_sg_walk);\n\t\tassoc = scatterwalk_map(&assoc_sg_walk);\n\t\tdst = src;\n\t\tif (unlikely(req->src != req->dst)) {\n\t\t\tscatterwalk_start(&dst_sg_walk, req->dst);\n\t\t\tdst = scatterwalk_map(&dst_sg_walk);\n\t\t}\n\n\t} else {\n\t\t/* Allocate memory for src, dst, assoc */\n\t\tsrc = kmalloc(req->cryptlen + req->assoclen, GFP_ATOMIC);\n\t\tif (!src)\n\t\t\treturn -ENOMEM;\n\t\tassoc = (src + req->cryptlen + auth_tag_len);\n\t\tscatterwalk_map_and_copy(src, req->src, 0, req->cryptlen, 0);\n\t\tscatterwalk_map_and_copy(assoc, req->assoc, 0,\n\t\t\treq->assoclen, 0);\n\t\tdst = src;\n\t}\n\n\taesni_gcm_dec_tfm(aes_ctx, dst, src, tempCipherLen, iv,\n\t\tctx->hash_subkey, assoc, (unsigned long)req->assoclen,\n\t\tauthTag, auth_tag_len);\n\n\t/* Compare generated tag with passed in tag. */\n\tretval = crypto_memneq(src + tempCipherLen, authTag, auth_tag_len) ?\n\t\t-EBADMSG : 0;\n\n\tif (one_entry_in_sg) {\n\t\tif (unlikely(req->src != req->dst)) {\n\t\t\tscatterwalk_unmap(dst);\n\t\t\tscatterwalk_done(&dst_sg_walk, 0, 0);\n\t\t}\n\t\tscatterwalk_unmap(src);\n\t\tscatterwalk_unmap(assoc);\n\t\tscatterwalk_done(&src_sg_walk, 0, 0);\n\t\tscatterwalk_done(&assoc_sg_walk, 0, 0);\n\t} else {\n\t\tscatterwalk_map_and_copy(dst, req->dst, 0, req->cryptlen, 1);\n\t\tkfree(src);\n\t}\n\treturn retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'crypto: aesni - fix memory usage in GCM decryption\n\nThe kernel crypto API logic requires the caller to provide the\nlength of (ciphertext || authentication tag) as cryptlen for the\nAEAD decryption operation. Thus, the cipher implementation must\ncalculate the size of the plaintext output itself and cannot simply use\ncryptlen.\n\nThe RFC4106 GCM decryption operation tries to overwrite cryptlen memory\nin req->dst. As the destination buffer for decryption only needs to hold\nthe plaintext memory but cryptlen references the input buffer holding\n(ciphertext || authentication tag), the assumption of the destination\nbuffer length in RFC4106 GCM operation leads to a too large size. This\npatch simply uses the already calculated plaintext size.\n\nIn addition, this patch fixes the offset calculation of the AAD buffer\npointer: as mentioned before, cryptlen already includes the size of the\ntag. Thus, the tag does not need to be added. With the addition, the AAD\nwill be written beyond the already allocated buffer.\n\nNote, this fixes a kernel crash that can be triggered from user space\nvia AF_ALG(aead) -- simply use the libkcapi test application\nfrom [1] and update it to use rfc4106-gcm-aes.\n\nUsing [1], the changes were tested using CAVS vectors to demonstrate\nthat the crypto operation still delivers the right results.\n\n[1] http://www.chronox.de/libkcapi.html\n\nCC: Tadeusz Struk \nCc: stable@vger.kernel.org\nSigned-off-by: Stephan Mueller \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: Status CalculateOutputIndex(OpKernelContext* context, int dimension,\n const vector& parent_output_index,\n INDEX_TYPE output_index_multiplier,\n INDEX_TYPE output_size,\n vector* result) {\n const RowPartitionTensor row_partition_tensor =\n GetRowPartitionTensor(context, dimension);\n auto partition_type = GetRowPartitionTypeByDimension(dimension);\n switch (partition_type) {\n case RowPartitionType::VALUE_ROWIDS:\n CalculateOutputIndexValueRowID(\n context, row_partition_tensor, parent_output_index,\n output_index_multiplier, output_size, result);\n return tensorflow::Status::OK();\n case RowPartitionType::ROW_SPLITS:\n if (row_partition_tensor.size() - 1 > parent_output_index.size()) {\n return errors::InvalidArgument(\n \"Row partition size is greater than output size: \",\n row_partition_tensor.size() - 1, \" > \",\n parent_output_index.size());\n }\n CalculateOutputIndexRowSplit(\n context, row_partition_tensor, parent_output_index,\n output_index_multiplier, output_size, result);\n return tensorflow::Status::OK();\n default:\n return errors::InvalidArgument(\n \"Unsupported partition type:\",\n RowPartitionTypeToString(partition_type));\n }\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-131', 'CWE-787'], 'message': 'Fix heap OOB / undefined behavior in `RaggedTensorToTensor`\n\nPiperOrigin-RevId: 373244623\nChange-Id: I2d6cbbc8c67b238a8815bf58097f7586d87c54f2'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int yam_ioctl(struct net_device *dev, struct ifreq *ifr, 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, ifr->ifr_data, sizeof(int)))\n\t\t return -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\tif ((ym = kmalloc(sizeof(struct yamdrv_ioctl_mcs), GFP_KERNEL)) == NULL)\n\t\t\treturn -ENOBUFS;\n\t\tif (copy_from_user(ym, ifr->ifr_data, sizeof(struct yamdrv_ioctl_mcs))) {\n\t\t\tkfree(ym);\n\t\t\treturn -EFAULT;\n\t\t}\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, ifr->ifr_data, sizeof(struct yamdrv_ioctl_cfg)))\n\t\t\t return -EFAULT;\n\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\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(ifr->ifr_data, &yi, sizeof(struct yamdrv_ioctl_cfg)))\n\t\t\t return -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-399'], 'message': 'hamradio/yam: fix info leak in ioctl\n\nThe yam_ioctl() code fails to initialise the cmd field\nof the struct yamdrv_ioctl_cfg. Add an explicit memset(0)\nbefore filling the structure to avoid the 4-byte info leak.\n\nSigned-off-by: Salva Peir\u00f3 \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 read_image_tga( gdIOCtx *ctx, oTga *tga )\n{\n\tint pixel_block_size = (tga->bits / 8);\n\tint image_block_size = (tga->width * tga->height) * pixel_block_size;\n\tuint8_t* decompression_buffer = NULL;\n\tunsigned char* conversion_buffer = NULL;\n\tint buffer_caret = 0;\n\tint bitmap_caret = 0;\n\tint i = 0;\n\tint j = 0;\n\tuint8_t encoded_pixels;\n\n\tif(overflow2(tga->width, tga->height)) {\n\t\treturn -1;\n\t}\n\n\tif(overflow2(tga->width * tga->height, pixel_block_size)) {\n\t\treturn -1;\n\t}\n\n\tif(overflow2(image_block_size, sizeof(int))) {\n\t\treturn -1;\n\t}\n\n\t/*! \\todo Add more image type support.\n\t */\n\tif (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE)\n\t\treturn -1;\n\n\t/*!\t\\brief Allocate memmory for image block\n\t * Allocate a chunk of memory for the image block to be passed into.\n\t */\n\ttga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int));\n\tif (tga->bitmap == NULL)\n\t\treturn -1;\n\n\tswitch (tga->imagetype) {\n\tcase TGA_TYPE_RGB:\n\t\t/*! \\brief Read in uncompressed RGB TGA\n\t\t * Chunk load the pixel data from an uncompressed RGB type TGA.\n\t\t */\n\t\tconversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));\n\t\tif (conversion_buffer == NULL) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tif (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {\n\t\t\tgd_error(\"gd-tga: premature end of image data\\n\");\n\t\t\tgdFree(conversion_buffer);\n\t\t\treturn -1;\n\t\t}\n\n\t\twhile (buffer_caret < image_block_size) {\n\t\t\ttga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret];\n\t\t\tbuffer_caret++;\n\t\t}\n\n\t\tgdFree(conversion_buffer);\n\t\tbreak;\n\n\tcase TGA_TYPE_RGB_RLE:\n\t\t/*! \\brief Read in RLE compressed RGB TGA\n\t\t * Chunk load the pixel data from an RLE compressed RGB type TGA.\n\t\t */\n\t\tdecompression_buffer = (uint8_t*) gdMalloc(image_block_size * sizeof(uint8_t));\n\t\tif (decompression_buffer == NULL) {\n\t\t\treturn -1;\n\t\t}\n\t\tconversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));\n\t\tif (conversion_buffer == NULL) {\n\t\t\tgd_error(\"gd-tga: premature end of image data\\n\");\n\t\t\tgdFree( decompression_buffer );\n\t\t\treturn -1;\n\t\t}\n\n\t\tif (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {\n\t\t\tgdFree(conversion_buffer);\n\t\t\tgdFree(decompression_buffer);\n\t\t\treturn -1;\n\t\t}\n\n\t\tbuffer_caret = 0;\n\n\t\twhile( buffer_caret < image_block_size) {\n\t\t\tdecompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret];\n\t\t\tbuffer_caret++;\n\t\t}\n\n\t\tbuffer_caret = 0;\n\n\t\twhile( bitmap_caret < image_block_size ) {\n\t\t\t\n\t\t\tif ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) {\n\t\t\t\tencoded_pixels = ( ( decompression_buffer[ buffer_caret ] & 127 ) + 1 );\n\t\t\t\tbuffer_caret++;\n\n\t\t\t\tif (encoded_pixels != 0) {\n\t\t\t\t\n\t\t\t\t\tif (!((buffer_caret + (encoded_pixels * pixel_block_size)) < image_block_size)) {\n\t\t\t\t\t\tgdFree( decompression_buffer );\n\t\t\t\t\t\tgdFree( conversion_buffer );\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (i = 0; i < encoded_pixels; i++) {\n\t\t\t\t\t\tfor (j = 0; j < pixel_block_size; j++, bitmap_caret++) {\n\t\t\t\t\t\t\ttga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbuffer_caret += pixel_block_size;\n\t\t\t} else {\n\t\t\t\tencoded_pixels = decompression_buffer[ buffer_caret ] + 1;\n\t\t\t\tbuffer_caret++;\n\n\t\t\t\tif (encoded_pixels != 0) {\n\t\t\t\t\n\t\t\t\t\tif (!((buffer_caret + (encoded_pixels * pixel_block_size)) < image_block_size)) {\n\t\t\t\t\t\tgdFree( decompression_buffer );\n\t\t\t\t\t\tgdFree( conversion_buffer );\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (i = 0; i < encoded_pixels; i++) {\n\t\t\t\t\t\tfor( j = 0; j < pixel_block_size; j++, bitmap_caret++ ) {\n\t\t\t\t\t\t\ttga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbuffer_caret += pixel_block_size;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tgdFree( decompression_buffer );\n\t\tgdFree( conversion_buffer );\n\t\tbreak;\n\t}\n\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Proper fix for #248'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)\n{\n\tconst struct sched_class *class;\n\n\tif (p->sched_class == rq->curr->sched_class) {\n\t\trq->curr->sched_class->check_preempt_curr(rq, p, flags);\n\t} else {\n\t\tfor_each_class(class) {\n\t\t\tif (class == rq->curr->sched_class)\n\t\t\t\tbreak;\n\t\t\tif (class == p->sched_class) {\n\t\t\t\tresched_task(rq->curr);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t/*\n\t * A queue event has occurred, and we're going to schedule. In\n\t * this case, we can save a useless back to back clock update.\n\t */\n\tif (test_tsk_need_resched(rq->curr))\n\t\trq->skip_clock_update = 1;\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 yy52;\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: bool Scanner::lex_str_chr(char quote, ASTChar &ast)\n{\n tok = cur;\n ast.loc = cur_loc();\n #line 837 \"../src/parse/lex.re\"\n\n if (globopts->input_encoding == Enc::ASCII) {\n \n#line 4645 \"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 yy711;\n\t\tif (yych == '\\n') goto yy715;\n\t\tgoto yy713;\n\t} else {\n\t\tif (yych <= '\\r') goto yy717;\n\t\tif (yych == '\\\\') goto yy718;\n\t\tgoto yy713;\n\t}\nyy711:\n\t++cur;\n#line 819 \"../src/parse/lex.re\"\n\t{ fail_if_eof(); ast.chr = 0; return true; }\n#line 4664 \"src/parse/lex.cc\"\nyy713:\n\t++cur;\nyy714:\n#line 821 \"../src/parse/lex.re\"\n\t{ ast.chr = decode(tok); return tok[0] != quote; }\n#line 4670 \"src/parse/lex.cc\"\nyy715:\n\t++cur;\n#line 813 \"../src/parse/lex.re\"\n\t{ msg.error(ast.loc, \"newline in character string\"); exit(1); }\n#line 4675 \"src/parse/lex.cc\"\nyy717:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '\\n') goto yy715;\n\tgoto yy714;\nyy718:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '`') {\n\t\tif (yych <= '3') {\n\t\t\tif (yych <= '\\n') {\n\t\t\t\tif (yych <= 0x00) goto yy719;\n\t\t\t\tif (yych <= '\\t') goto yy720;\n\t\t\t\tgoto yy715;\n\t\t\t} else {\n\t\t\t\tif (yych == '\\r') goto yy722;\n\t\t\t\tif (yych <= '/') goto yy720;\n\t\t\t\tgoto yy723;\n\t\t\t}\n\t\t} else {\n\t\t\tif (yych <= 'W') {\n\t\t\t\tif (yych <= '7') goto yy725;\n\t\t\t\tif (yych == 'U') goto yy726;\n\t\t\t\tgoto yy720;\n\t\t\t} else {\n\t\t\t\tif (yych <= 'X') goto yy728;\n\t\t\t\tif (yych == '\\\\') goto yy729;\n\t\t\t\tgoto yy720;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (yych <= 'q') {\n\t\t\tif (yych <= 'e') {\n\t\t\t\tif (yych <= 'a') goto yy731;\n\t\t\t\tif (yych <= 'b') goto yy733;\n\t\t\t\tgoto yy720;\n\t\t\t} else {\n\t\t\t\tif (yych <= 'f') goto yy735;\n\t\t\t\tif (yych == 'n') goto yy737;\n\t\t\t\tgoto yy720;\n\t\t\t}\n\t\t} else {\n\t\t\tif (yych <= 'u') {\n\t\t\t\tif (yych <= 'r') goto yy739;\n\t\t\t\tif (yych <= 's') goto yy720;\n\t\t\t\tif (yych <= 't') goto yy741;\n\t\t\t\tgoto yy728;\n\t\t\t} else {\n\t\t\t\tif (yych <= 'v') goto yy743;\n\t\t\t\tif (yych == 'x') goto yy745;\n\t\t\t\tgoto yy720;\n\t\t\t}\n\t\t}\n\t}\nyy719:\n#line 816 \"../src/parse/lex.re\"\n\t{ msg.error(ast.loc, \"syntax error in escape sequence\"); exit(1); }\n#line 4731 \"src/parse/lex.cc\"\nyy720:\n\t++cur;\nyy721:\n#line 832 \"../src/parse/lex.re\"\n\t{\n ast.chr = decode(tok + 1);\n if (tok[1] != quote) msg.warn.useless_escape(ast.loc, tok, cur);\n return true;\n }\n#line 4741 \"src/parse/lex.cc\"\nyy722:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '\\n') goto yy715;\n\tgoto yy721;\nyy723:\n\tyyaccept = 0;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= '/') goto yy724;\n\tif (yych <= '7') goto yy746;\nyy724:\n#line 815 \"../src/parse/lex.re\"\n\t{ msg.error(ast.loc, \"syntax error in octal escape sequence\"); exit(1); }\n#line 4754 \"src/parse/lex.cc\"\nyy725:\n\t++cur;\n\tgoto yy724;\nyy726:\n\tyyaccept = 1;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy727;\n\t\tif (yych <= '9') goto yy748;\n\t} else {\n\t\tif (yych <= 'F') goto yy748;\n\t\tif (yych <= '`') goto yy727;\n\t\tif (yych <= 'f') goto yy748;\n\t}\nyy727:\n#line 814 \"../src/parse/lex.re\"\n\t{ msg.error(ast.loc, \"syntax error in hexadecimal escape sequence\"); exit(1); }\n#line 4772 \"src/parse/lex.cc\"\nyy728:\n\tyyaccept = 1;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy727;\n\t\tif (yych <= '9') goto yy749;\n\t\tgoto yy727;\n\t} else {\n\t\tif (yych <= 'F') goto yy749;\n\t\tif (yych <= '`') goto yy727;\n\t\tif (yych <= 'f') goto yy749;\n\t\tgoto yy727;\n\t}\nyy729:\n\t++cur;\n#line 831 \"../src/parse/lex.re\"\n\t{ ast.chr = static_cast('\\\\'); return true; }\n#line 4790 \"src/parse/lex.cc\"\nyy731:\n\t++cur;\n#line 824 \"../src/parse/lex.re\"\n\t{ ast.chr = static_cast('\\a'); return true; }\n#line 4795 \"src/parse/lex.cc\"\nyy733:\n\t++cur;\n#line 825 \"../src/parse/lex.re\"\n\t{ ast.chr = static_cast('\\b'); return true; }\n#line 4800 \"src/parse/lex.cc\"\nyy735:\n\t++cur;\n#line 826 \"../src/parse/lex.re\"\n\t{ ast.chr = static_cast('\\f'); return true; }\n#line 4805 \"src/parse/lex.cc\"\nyy737:\n\t++cur;\n#line 827 \"../src/parse/lex.re\"\n\t{ ast.chr = static_cast('\\n'); return true; }\n#line 4810 \"src/parse/lex.cc\"\nyy739:\n\t++cur;\n#line 828 \"../src/parse/lex.re\"\n\t{ ast.chr = static_cast('\\r'); return true; }\n#line 4815 \"src/parse/lex.cc\"\nyy741:\n\t++cur;\n#line 829 \"../src/parse/lex.re\"\n\t{ ast.chr = static_cast('\\t'); return true; }\n#line 4820 \"src/parse/lex.cc\"\nyy743:\n\t++cur;\n#line 830 \"../src/parse/lex.re\"\n\t{ ast.chr = static_cast('\\v'); return true; }\n#line 4825 \"src/parse/lex.cc\"\nyy745:\n\tyyaccept = 1;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy727;\n\t\tif (yych <= '9') goto yy750;\n\t\tgoto yy727;\n\t} else {\n\t\tif (yych <= 'F') goto yy750;\n\t\tif (yych <= '`') goto yy727;\n\t\tif (yych <= 'f') goto yy750;\n\t\tgoto yy727;\n\t}\nyy746:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '/') goto yy747;\n\tif (yych <= '7') goto yy751;\nyy747:\n\tcur = mar;\n\tif (yyaccept == 0) {\n\t\tgoto yy724;\n\t} else {\n\t\tgoto yy727;\n\t}\nyy748:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy747;\n\t\tif (yych <= '9') goto yy753;\n\t\tgoto yy747;\n\t} else {\n\t\tif (yych <= 'F') goto yy753;\n\t\tif (yych <= '`') goto yy747;\n\t\tif (yych <= 'f') goto yy753;\n\t\tgoto yy747;\n\t}\nyy749:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy747;\n\t\tif (yych <= '9') goto yy754;\n\t\tgoto yy747;\n\t} else {\n\t\tif (yych <= 'F') goto yy754;\n\t\tif (yych <= '`') goto yy747;\n\t\tif (yych <= 'f') goto yy754;\n\t\tgoto yy747;\n\t}\nyy750:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy747;\n\t\tif (yych <= '9') goto yy755;\n\t\tgoto yy747;\n\t} else {\n\t\tif (yych <= 'F') goto yy755;\n\t\tif (yych <= '`') goto yy747;\n\t\tif (yych <= 'f') goto yy755;\n\t\tgoto yy747;\n\t}\nyy751:\n\t++cur;\n#line 823 \"../src/parse/lex.re\"\n\t{ ast.chr = unesc_oct(tok, cur); return true; }\n#line 4890 \"src/parse/lex.cc\"\nyy753:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy747;\n\t\tif (yych <= '9') goto yy757;\n\t\tgoto yy747;\n\t} else {\n\t\tif (yych <= 'F') goto yy757;\n\t\tif (yych <= '`') goto yy747;\n\t\tif (yych <= 'f') goto yy757;\n\t\tgoto yy747;\n\t}\nyy754:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy747;\n\t\tif (yych <= '9') goto yy750;\n\t\tgoto yy747;\n\t} else {\n\t\tif (yych <= 'F') goto yy750;\n\t\tif (yych <= '`') goto yy747;\n\t\tif (yych <= 'f') goto yy750;\n\t\tgoto yy747;\n\t}\nyy755:\n\t++cur;\n#line 822 \"../src/parse/lex.re\"\n\t{ ast.chr = unesc_hex(tok, cur); return true; }\n#line 4919 \"src/parse/lex.cc\"\nyy757:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy747;\n\t\tif (yych >= ':') goto yy747;\n\t} else {\n\t\tif (yych <= 'F') goto yy758;\n\t\tif (yych <= '`') goto yy747;\n\t\tif (yych >= 'g') goto yy747;\n\t}\nyy758:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy747;\n\t\tif (yych <= '9') goto yy749;\n\t\tgoto yy747;\n\t} else {\n\t\tif (yych <= 'F') goto yy749;\n\t\tif (yych <= '`') goto yy747;\n\t\tif (yych <= 'f') goto yy749;\n\t\tgoto yy747;\n\t}\n}\n#line 839 \"../src/parse/lex.re\"\n\n }\n else {\n \n#line 4948 \"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 yy761;\n\t\t\tif (yych == '\\n') goto yy765;\n\t\t\tgoto yy763;\n\t\t} else {\n\t\t\tif (yych <= '\\r') goto yy767;\n\t\t\tif (yych == '\\\\') goto yy768;\n\t\t\tgoto yy763;\n\t\t}\n\t} else {\n\t\tif (yych <= 0xEF) {\n\t\t\tif (yych <= 0xC1) goto yy770;\n\t\t\tif (yych <= 0xDF) goto yy772;\n\t\t\tif (yych <= 0xE0) goto yy773;\n\t\t\tgoto yy774;\n\t\t} else {\n\t\t\tif (yych <= 0xF0) goto yy775;\n\t\t\tif (yych <= 0xF3) goto yy776;\n\t\t\tif (yych <= 0xF4) goto yy777;\n\t\t\tgoto yy770;\n\t\t}\n\t}\nyy761:\n\t++cur;\n#line 819 \"../src/parse/lex.re\"\n\t{ fail_if_eof(); ast.chr = 0; return true; }\n#line 4981 \"src/parse/lex.cc\"\nyy763:\n\t++cur;\nyy764:\n#line 821 \"../src/parse/lex.re\"\n\t{ ast.chr = decode(tok); return tok[0] != quote; }\n#line 4987 \"src/parse/lex.cc\"\nyy765:\n\t++cur;\n#line 813 \"../src/parse/lex.re\"\n\t{ msg.error(ast.loc, \"newline in character string\"); exit(1); }\n#line 4992 \"src/parse/lex.cc\"\nyy767:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '\\n') goto yy765;\n\tgoto yy764;\nyy768:\n\tyyaccept = 0;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= 'f') {\n\t\tif (yych <= 'T') {\n\t\t\tif (yych <= '\\f') {\n\t\t\t\tif (yych <= 0x00) goto yy769;\n\t\t\t\tif (yych == '\\n') goto yy765;\n\t\t\t\tgoto yy778;\n\t\t\t} else {\n\t\t\t\tif (yych <= '/') {\n\t\t\t\t\tif (yych <= '\\r') goto yy780;\n\t\t\t\t\tgoto yy778;\n\t\t\t\t} else {\n\t\t\t\t\tif (yych <= '3') goto yy781;\n\t\t\t\t\tif (yych <= '7') goto yy783;\n\t\t\t\t\tgoto yy778;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif (yych <= '\\\\') {\n\t\t\t\tif (yych <= 'W') {\n\t\t\t\t\tif (yych <= 'U') goto yy784;\n\t\t\t\t\tgoto yy778;\n\t\t\t\t} else {\n\t\t\t\t\tif (yych <= 'X') goto yy786;\n\t\t\t\t\tif (yych <= '[') goto yy778;\n\t\t\t\t\tgoto yy787;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (yych <= 'a') {\n\t\t\t\t\tif (yych <= '`') goto yy778;\n\t\t\t\t\tgoto yy789;\n\t\t\t\t} else {\n\t\t\t\t\tif (yych <= 'b') goto yy791;\n\t\t\t\t\tif (yych <= 'e') goto yy778;\n\t\t\t\t\tgoto yy793;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (yych <= 'w') {\n\t\t\tif (yych <= 'r') {\n\t\t\t\tif (yych == 'n') goto yy795;\n\t\t\t\tif (yych <= 'q') goto yy778;\n\t\t\t\tgoto yy797;\n\t\t\t} else {\n\t\t\t\tif (yych <= 't') {\n\t\t\t\t\tif (yych <= 's') goto yy778;\n\t\t\t\t\tgoto yy799;\n\t\t\t\t} else {\n\t\t\t\t\tif (yych <= 'u') goto yy786;\n\t\t\t\t\tif (yych <= 'v') goto yy801;\n\t\t\t\t\tgoto yy778;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif (yych <= 0xE0) {\n\t\t\t\tif (yych <= 0x7F) {\n\t\t\t\t\tif (yych <= 'x') goto yy803;\n\t\t\t\t\tgoto yy778;\n\t\t\t\t} else {\n\t\t\t\t\tif (yych <= 0xC1) goto yy769;\n\t\t\t\t\tif (yych <= 0xDF) goto yy804;\n\t\t\t\t\tgoto yy806;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (yych <= 0xF0) {\n\t\t\t\t\tif (yych <= 0xEF) goto yy807;\n\t\t\t\t\tgoto yy808;\n\t\t\t\t} else {\n\t\t\t\t\tif (yych <= 0xF3) goto yy809;\n\t\t\t\t\tif (yych <= 0xF4) goto yy810;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\nyy769:\n#line 816 \"../src/parse/lex.re\"\n\t{ msg.error(ast.loc, \"syntax error in escape sequence\"); exit(1); }\n#line 5077 \"src/parse/lex.cc\"\nyy770:\n\t++cur;\nyy771:\n#line 817 \"../src/parse/lex.re\"\n\t{ msg.error(ast.loc, \"syntax error\"); exit(1); }\n#line 5083 \"src/parse/lex.cc\"\nyy772:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= 0x7F) goto yy771;\n\tif (yych <= 0xBF) goto yy763;\n\tgoto yy771;\nyy773:\n\tyyaccept = 1;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= 0x9F) goto yy771;\n\tif (yych <= 0xBF) goto yy811;\n\tgoto yy771;\nyy774:\n\tyyaccept = 1;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= 0x7F) goto yy771;\n\tif (yych <= 0xBF) goto yy811;\n\tgoto yy771;\nyy775:\n\tyyaccept = 1;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= 0x8F) goto yy771;\n\tif (yych <= 0xBF) goto yy812;\n\tgoto yy771;\nyy776:\n\tyyaccept = 1;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= 0x7F) goto yy771;\n\tif (yych <= 0xBF) goto yy812;\n\tgoto yy771;\nyy777:\n\tyyaccept = 1;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= 0x7F) goto yy771;\n\tif (yych <= 0x8F) goto yy812;\n\tgoto yy771;\nyy778:\n\t++cur;\nyy779:\n#line 832 \"../src/parse/lex.re\"\n\t{\n ast.chr = decode(tok + 1);\n if (tok[1] != quote) msg.warn.useless_escape(ast.loc, tok, cur);\n return true;\n }\n#line 5128 \"src/parse/lex.cc\"\nyy780:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '\\n') goto yy765;\n\tgoto yy779;\nyy781:\n\tyyaccept = 2;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= '/') goto yy782;\n\tif (yych <= '7') goto yy813;\nyy782:\n#line 815 \"../src/parse/lex.re\"\n\t{ msg.error(ast.loc, \"syntax error in octal escape sequence\"); exit(1); }\n#line 5141 \"src/parse/lex.cc\"\nyy783:\n\t++cur;\n\tgoto yy782;\nyy784:\n\tyyaccept = 3;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy785;\n\t\tif (yych <= '9') goto yy814;\n\t} else {\n\t\tif (yych <= 'F') goto yy814;\n\t\tif (yych <= '`') goto yy785;\n\t\tif (yych <= 'f') goto yy814;\n\t}\nyy785:\n#line 814 \"../src/parse/lex.re\"\n\t{ msg.error(ast.loc, \"syntax error in hexadecimal escape sequence\"); exit(1); }\n#line 5159 \"src/parse/lex.cc\"\nyy786:\n\tyyaccept = 3;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy785;\n\t\tif (yych <= '9') goto yy815;\n\t\tgoto yy785;\n\t} else {\n\t\tif (yych <= 'F') goto yy815;\n\t\tif (yych <= '`') goto yy785;\n\t\tif (yych <= 'f') goto yy815;\n\t\tgoto yy785;\n\t}\nyy787:\n\t++cur;\n#line 831 \"../src/parse/lex.re\"\n\t{ ast.chr = static_cast('\\\\'); return true; }\n#line 5177 \"src/parse/lex.cc\"\nyy789:\n\t++cur;\n#line 824 \"../src/parse/lex.re\"\n\t{ ast.chr = static_cast('\\a'); return true; }\n#line 5182 \"src/parse/lex.cc\"\nyy791:\n\t++cur;\n#line 825 \"../src/parse/lex.re\"\n\t{ ast.chr = static_cast('\\b'); return true; }\n#line 5187 \"src/parse/lex.cc\"\nyy793:\n\t++cur;\n#line 826 \"../src/parse/lex.re\"\n\t{ ast.chr = static_cast('\\f'); return true; }\n#line 5192 \"src/parse/lex.cc\"\nyy795:\n\t++cur;\n#line 827 \"../src/parse/lex.re\"\n\t{ ast.chr = static_cast('\\n'); return true; }\n#line 5197 \"src/parse/lex.cc\"\nyy797:\n\t++cur;\n#line 828 \"../src/parse/lex.re\"\n\t{ ast.chr = static_cast('\\r'); return true; }\n#line 5202 \"src/parse/lex.cc\"\nyy799:\n\t++cur;\n#line 829 \"../src/parse/lex.re\"\n\t{ ast.chr = static_cast('\\t'); return true; }\n#line 5207 \"src/parse/lex.cc\"\nyy801:\n\t++cur;\n#line 830 \"../src/parse/lex.re\"\n\t{ ast.chr = static_cast('\\v'); return true; }\n#line 5212 \"src/parse/lex.cc\"\nyy803:\n\tyyaccept = 3;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy785;\n\t\tif (yych <= '9') goto yy816;\n\t\tgoto yy785;\n\t} else {\n\t\tif (yych <= 'F') goto yy816;\n\t\tif (yych <= '`') goto yy785;\n\t\tif (yych <= 'f') goto yy816;\n\t\tgoto yy785;\n\t}\nyy804:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= 0x7F) goto yy805;\n\tif (yych <= 0xBF) goto yy778;\nyy805:\n\tcur = mar;\n\tif (yyaccept <= 1) {\n\t\tif (yyaccept == 0) {\n\t\t\tgoto yy769;\n\t\t} else {\n\t\t\tgoto yy771;\n\t\t}\n\t} else {\n\t\tif (yyaccept == 2) {\n\t\t\tgoto yy782;\n\t\t} else {\n\t\t\tgoto yy785;\n\t\t}\n\t}\nyy806:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= 0x9F) goto yy805;\n\tif (yych <= 0xBF) goto yy804;\n\tgoto yy805;\nyy807:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= 0x7F) goto yy805;\n\tif (yych <= 0xBF) goto yy804;\n\tgoto yy805;\nyy808:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= 0x8F) goto yy805;\n\tif (yych <= 0xBF) goto yy807;\n\tgoto yy805;\nyy809:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= 0x7F) goto yy805;\n\tif (yych <= 0xBF) goto yy807;\n\tgoto yy805;\nyy810:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= 0x7F) goto yy805;\n\tif (yych <= 0x8F) goto yy807;\n\tgoto yy805;\nyy811:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= 0x7F) goto yy805;\n\tif (yych <= 0xBF) goto yy763;\n\tgoto yy805;\nyy812:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= 0x7F) goto yy805;\n\tif (yych <= 0xBF) goto yy811;\n\tgoto yy805;\nyy813:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '/') goto yy805;\n\tif (yych <= '7') goto yy817;\n\tgoto yy805;\nyy814:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy805;\n\t\tif (yych <= '9') goto yy819;\n\t\tgoto yy805;\n\t} else {\n\t\tif (yych <= 'F') goto yy819;\n\t\tif (yych <= '`') goto yy805;\n\t\tif (yych <= 'f') goto yy819;\n\t\tgoto yy805;\n\t}\nyy815:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy805;\n\t\tif (yych <= '9') goto yy820;\n\t\tgoto yy805;\n\t} else {\n\t\tif (yych <= 'F') goto yy820;\n\t\tif (yych <= '`') goto yy805;\n\t\tif (yych <= 'f') goto yy820;\n\t\tgoto yy805;\n\t}\nyy816:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy805;\n\t\tif (yych <= '9') goto yy821;\n\t\tgoto yy805;\n\t} else {\n\t\tif (yych <= 'F') goto yy821;\n\t\tif (yych <= '`') goto yy805;\n\t\tif (yych <= 'f') goto yy821;\n\t\tgoto yy805;\n\t}\nyy817:\n\t++cur;\n#line 823 \"../src/parse/lex.re\"\n\t{ ast.chr = unesc_oct(tok, cur); return true; }\n#line 5325 \"src/parse/lex.cc\"\nyy819:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy805;\n\t\tif (yych <= '9') goto yy823;\n\t\tgoto yy805;\n\t} else {\n\t\tif (yych <= 'F') goto yy823;\n\t\tif (yych <= '`') goto yy805;\n\t\tif (yych <= 'f') goto yy823;\n\t\tgoto yy805;\n\t}\nyy820:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy805;\n\t\tif (yych <= '9') goto yy816;\n\t\tgoto yy805;\n\t} else {\n\t\tif (yych <= 'F') goto yy816;\n\t\tif (yych <= '`') goto yy805;\n\t\tif (yych <= 'f') goto yy816;\n\t\tgoto yy805;\n\t}\nyy821:\n\t++cur;\n#line 822 \"../src/parse/lex.re\"\n\t{ ast.chr = unesc_hex(tok, cur); return true; }\n#line 5354 \"src/parse/lex.cc\"\nyy823:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy805;\n\t\tif (yych >= ':') goto yy805;\n\t} else {\n\t\tif (yych <= 'F') goto yy824;\n\t\tif (yych <= '`') goto yy805;\n\t\tif (yych >= 'g') goto yy805;\n\t}\nyy824:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy805;\n\t\tif (yych <= '9') goto yy815;\n\t\tgoto yy805;\n\t} else {\n\t\tif (yych <= 'F') goto yy815;\n\t\tif (yych <= '`') goto yy805;\n\t\tif (yych <= 'f') goto yy815;\n\t\tgoto yy805;\n\t}\n}\n#line 842 \"../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: int Scanner::scan()\n{\n const char *p, *x, *y;\nscan:\n tok = cur;\n location = cur_loc();\n\n#line 1706 \"src/parse/lex.cc\"\n{\n\tunsigned char yych;\n\tunsigned int yyaccept = 0;\n\tstatic const unsigned char yybm[] = {\n\t\t 0, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 144, 0, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t144, 128, 0, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t224, 224, 224, 224, 224, 224, 224, 224, \n\t\t224, 224, 128, 128, 128, 128, 128, 128, \n\t\t128, 160, 160, 160, 160, 160, 160, 160, \n\t\t160, 160, 160, 160, 160, 160, 160, 160, \n\t\t160, 160, 160, 160, 160, 160, 160, 160, \n\t\t160, 160, 160, 128, 0, 128, 128, 160, \n\t\t128, 160, 160, 160, 160, 160, 160, 160, \n\t\t160, 160, 160, 160, 160, 160, 160, 160, \n\t\t160, 160, 160, 160, 160, 160, 160, 160, \n\t\t160, 160, 160, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t};\n\tif ((lim - cur) < 9) { if (!fill(9)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yybm[0+yych] & 16) {\n\t\tgoto yy278;\n\t}\n\tif (yych <= '9') {\n\t\tif (yych <= '$') {\n\t\t\tif (yych <= '\\r') {\n\t\t\t\tif (yych <= 0x08) goto yy276;\n\t\t\t\tif (yych <= '\\n') goto yy281;\n\t\t\t\tif (yych >= '\\r') goto yy283;\n\t\t\t} else {\n\t\t\t\tif (yych <= '!') {\n\t\t\t\t\tif (yych >= ' ') goto yy284;\n\t\t\t\t} else {\n\t\t\t\t\tif (yych <= '\"') goto yy285;\n\t\t\t\t\tif (yych <= '#') goto yy287;\n\t\t\t\t\tgoto yy288;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif (yych <= '*') {\n\t\t\t\tif (yych <= '&') {\n\t\t\t\t\tif (yych <= '%') goto yy290;\n\t\t\t\t} else {\n\t\t\t\t\tif (yych <= '\\'') goto yy291;\n\t\t\t\t\tif (yych <= ')') goto yy288;\n\t\t\t\t\tgoto yy293;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (yych <= '-') {\n\t\t\t\t\tif (yych <= '+') goto yy288;\n\t\t\t\t} else {\n\t\t\t\t\tif (yych <= '.') goto yy294;\n\t\t\t\t\tif (yych <= '/') goto yy296;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (yych <= '[') {\n\t\t\tif (yych <= '=') {\n\t\t\t\tif (yych <= ':') goto yy297;\n\t\t\t\tif (yych <= ';') goto yy288;\n\t\t\t\tif (yych <= '<') goto yy298;\n\t\t\t\tgoto yy300;\n\t\t\t} else {\n\t\t\t\tif (yych <= '?') {\n\t\t\t\t\tif (yych >= '?') goto yy288;\n\t\t\t\t} else {\n\t\t\t\t\tif (yych <= '@') goto yy287;\n\t\t\t\t\tif (yych <= 'Z') goto yy301;\n\t\t\t\t\tgoto yy304;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif (yych <= 'q') {\n\t\t\t\tif (yych <= '^') {\n\t\t\t\t\tif (yych <= '\\\\') goto yy288;\n\t\t\t\t} else {\n\t\t\t\t\tif (yych != '`') goto yy301;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (yych <= 'z') {\n\t\t\t\t\tif (yych <= 'r') goto yy306;\n\t\t\t\t\tgoto yy301;\n\t\t\t\t} else {\n\t\t\t\t\tif (yych <= '{') goto yy307;\n\t\t\t\t\tif (yych <= '|') goto yy288;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\nyy276:\n\t++cur;\nyy277:\n#line 569 \"../src/parse/lex.re\"\n\t{\n msg.error(tok_loc(), \"unexpected character: '%c'\", *tok);\n exit(1);\n }\n#line 1824 \"src/parse/lex.cc\"\nyy278:\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] & 16) {\n\t\tgoto yy278;\n\t}\n#line 551 \"../src/parse/lex.re\"\n\t{ goto scan; }\n#line 1834 \"src/parse/lex.cc\"\nyy281:\n\tyyaccept = 0;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= 0x1F) {\n\t\tif (yych == '\\t') goto yy309;\n\t} else {\n\t\tif (yych <= ' ') goto yy309;\n\t\tif (yych == '#') goto yy312;\n\t}\nyy282:\n#line 558 \"../src/parse/lex.re\"\n\t{\n next_line();\n if (lexer_state == LEX_FLEX_NAME) {\n lexer_state = LEX_NORMAL;\n return TOKEN_FID_END;\n }\n else {\n goto scan;\n }\n }\n#line 1856 \"src/parse/lex.cc\"\nyy283:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '\\n') goto yy281;\n\tgoto yy277;\nyy284:\n\tyyaccept = 1;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych == 'i') goto yy314;\n\tif (yych == 'u') goto yy315;\n\tgoto yy277;\nyy285:\n\t++cur;\n#line 443 \"../src/parse/lex.re\"\n\t{ yylval.regexp = lex_str('\"'); return TOKEN_REGEXP; }\n#line 1871 \"src/parse/lex.cc\"\nyy287:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '^') {\n\t\tif (yych <= '@') goto yy277;\n\t\tif (yych <= 'Z') goto yy316;\n\t\tgoto yy277;\n\t} else {\n\t\tif (yych == '`') goto yy277;\n\t\tif (yych <= 'z') goto yy316;\n\t\tgoto yy277;\n\t}\nyy288:\n\t++cur;\nyy289:\n#line 452 \"../src/parse/lex.re\"\n\t{ return *tok; }\n#line 1888 \"src/parse/lex.cc\"\nyy290:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '}') goto yy319;\n\tgoto yy277;\nyy291:\n\t++cur;\n#line 442 \"../src/parse/lex.re\"\n\t{ yylval.regexp = lex_str('\\''); return TOKEN_REGEXP; }\n#line 1897 \"src/parse/lex.cc\"\nyy293:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '/') goto yy319;\n\tgoto yy289;\nyy294:\n\t++cur;\n#line 546 \"../src/parse/lex.re\"\n\t{\n yylval.regexp = ast_dot(tok_loc());\n return TOKEN_REGEXP;\n }\n#line 1909 \"src/parse/lex.cc\"\nyy296:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '*') goto yy321;\n\tif (yych == '/') goto yy323;\n\tgoto yy289;\nyy297:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '=') goto yy325;\n\tgoto yy277;\nyy298:\n\t++cur;\n#line 435 \"../src/parse/lex.re\"\n\t{ return lex_clist(); }\n#line 1923 \"src/parse/lex.cc\"\nyy300:\n\tyyaccept = 2;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych == '>') goto yy327;\n\tgoto yy289;\nyy301:\n\t++cur;\n\tif (lim <= cur) { if (!fill(1)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\nyy302:\n\tif (yybm[0+yych] & 32) {\n\t\tgoto yy301;\n\t}\n#line 501 \"../src/parse/lex.re\"\n\t{\n if (!globopts->FFlag || lex_namedef_context_re2c()) {\n yylval.str = newstr(tok, cur);\n return TOKEN_ID;\n }\n else if (lex_namedef_context_flex()) {\n yylval.str = newstr(tok, cur);\n lexer_state = LEX_FLEX_NAME;\n return TOKEN_FID;\n }\n else {\n // consume one character, otherwise we risk breaking operator\n // precedence in cases like ab*: it should be a(b)*, not (ab)*\n cur = tok + 1;\n\n ASTChar c = {static_cast(tok[0]), tok_loc()};\n std::vector *str = new std::vector;\n str->push_back(c);\n yylval.regexp = ast_str(tok_loc(), str, false);\n return TOKEN_REGEXP;\n }\n }\n#line 1960 \"src/parse/lex.cc\"\nyy304:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '^') goto yy329;\n#line 444 \"../src/parse/lex.re\"\n\t{ yylval.regexp = lex_cls(false); return TOKEN_REGEXP; }\n#line 1966 \"src/parse/lex.cc\"\nyy306:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy331;\n\tgoto yy302;\nyy307:\n\tyyaccept = 3;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yybm[0+yych] & 64) {\n\t\tgoto yy334;\n\t}\n\tif (yych <= 'Z') {\n\t\tif (yych == ',') goto yy332;\n\t\tif (yych >= 'A') goto yy336;\n\t} else {\n\t\tif (yych <= '_') {\n\t\t\tif (yych >= '_') goto yy336;\n\t\t} else {\n\t\t\tif (yych <= '`') goto yy308;\n\t\t\tif (yych <= 'z') goto yy336;\n\t\t}\n\t}\nyy308:\n#line 427 \"../src/parse/lex.re\"\n\t{ lex_code_in_braces(); return TOKEN_CODE; }\n#line 1991 \"src/parse/lex.cc\"\nyy309:\n\t++cur;\n\tif (lim <= cur) { if (!fill(1)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= 0x1F) {\n\t\tif (yych == '\\t') goto yy309;\n\t} else {\n\t\tif (yych <= ' ') goto yy309;\n\t\tif (yych == '#') goto yy312;\n\t}\nyy311:\n\tcur = mar;\n\tif (yyaccept <= 3) {\n\t\tif (yyaccept <= 1) {\n\t\t\tif (yyaccept == 0) {\n\t\t\t\tgoto yy282;\n\t\t\t} else {\n\t\t\t\tgoto yy277;\n\t\t\t}\n\t\t} else {\n\t\t\tif (yyaccept == 2) {\n\t\t\t\tgoto yy289;\n\t\t\t} else {\n\t\t\t\tgoto yy308;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (yyaccept <= 5) {\n\t\t\tif (yyaccept == 4) {\n\t\t\t\tgoto yy326;\n\t\t\t} else {\n\t\t\t\tgoto yy333;\n\t\t\t}\n\t\t} else {\n\t\t\tif (yyaccept == 6) {\n\t\t\t\tgoto yy353;\n\t\t\t} else {\n\t\t\t\tgoto yy379;\n\t\t\t}\n\t\t}\n\t}\nyy312:\n\t++cur;\n\tif ((lim - cur) < 5) { if (!fill(5)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= 0x1F) {\n\t\tif (yych == '\\t') goto yy312;\n\t\tgoto yy311;\n\t} else {\n\t\tif (yych <= ' ') goto yy312;\n\t\tif (yych == 'l') goto yy338;\n\t\tgoto yy311;\n\t}\nyy314:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'n') goto yy339;\n\tgoto yy311;\nyy315:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 's') goto yy340;\n\tgoto yy311;\nyy316:\n\t++cur;\n\tif (lim <= cur) { if (!fill(1)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= 'Z') {\n\t\tif (yych <= '/') goto yy318;\n\t\tif (yych <= '9') goto yy316;\n\t\tif (yych >= 'A') goto yy316;\n\t} else {\n\t\tif (yych <= '_') {\n\t\t\tif (yych >= '_') goto yy316;\n\t\t} else {\n\t\t\tif (yych <= '`') goto yy318;\n\t\t\tif (yych <= 'z') goto yy316;\n\t\t}\n\t}\nyy318:\n#line 447 \"../src/parse/lex.re\"\n\t{\n yylval.regexp = ast_tag(tok_loc(), newstr(tok + 1, cur), tok[0] == '#');\n return TOKEN_REGEXP;\n }\n#line 2075 \"src/parse/lex.cc\"\nyy319:\n\t++cur;\n#line 440 \"../src/parse/lex.re\"\n\t{ tok = cur; return 0; }\n#line 2080 \"src/parse/lex.cc\"\nyy321:\n\t++cur;\n#line 438 \"../src/parse/lex.re\"\n\t{ lex_c_comment(); goto scan; }\n#line 2085 \"src/parse/lex.cc\"\nyy323:\n\t++cur;\n#line 437 \"../src/parse/lex.re\"\n\t{ lex_cpp_comment(); goto scan; }\n#line 2090 \"src/parse/lex.cc\"\nyy325:\n\tyyaccept = 4;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych == '>') goto yy327;\nyy326:\n#line 428 \"../src/parse/lex.re\"\n\t{ lex_code_indented(); return TOKEN_CODE; }\n#line 2098 \"src/parse/lex.cc\"\nyy327:\n\t++cur;\n\tif (lim <= cur) { if (!fill(1)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '\\t') {\n\t\t\tif (yych <= 0x08) goto yy311;\n\t\t\tgoto yy327;\n\t\t} else {\n\t\t\tif (yych == ' ') goto yy327;\n\t\t\tgoto yy311;\n\t\t}\n\t} else {\n\t\tif (yych <= '_') {\n\t\t\tif (yych <= 'Z') {\n\t\t\t\tyyt1 = cur;\n\t\t\t\tgoto yy341;\n\t\t\t}\n\t\t\tif (yych <= '^') goto yy311;\n\t\t\tyyt1 = cur;\n\t\t\tgoto yy341;\n\t\t} else {\n\t\t\tif (yych <= '`') goto yy311;\n\t\t\tif (yych <= 'z') {\n\t\t\t\tyyt1 = cur;\n\t\t\t\tgoto yy341;\n\t\t\t}\n\t\t\tgoto yy311;\n\t\t}\n\t}\nyy329:\n\t++cur;\n#line 445 \"../src/parse/lex.re\"\n\t{ yylval.regexp = lex_cls(true); return TOKEN_REGEXP; }\n#line 2133 \"src/parse/lex.cc\"\nyy331:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '2') goto yy344;\n\tgoto yy302;\nyy332:\n\t++cur;\nyy333:\n#line 484 \"../src/parse/lex.re\"\n\t{\n msg.error(tok_loc(), \"illegal closure form, use '{n}', '{n,}', '{n,m}' \"\n \"where n and m are numbers\");\n exit(1);\n }\n#line 2147 \"src/parse/lex.cc\"\nyy334:\n\t++cur;\n\tif ((lim - cur) < 2) { if (!fill(2)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yybm[0+yych] & 64) {\n\t\tgoto yy334;\n\t}\n\tif (yych == ',') {\n\t\tyyt1 = cur;\n\t\tgoto yy345;\n\t}\n\tif (yych == '}') goto yy346;\n\tgoto yy311;\nyy336:\n\t++cur;\n\tif (lim <= cur) { if (!fill(1)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= '^') {\n\t\tif (yych <= '9') {\n\t\t\tif (yych <= '/') goto yy311;\n\t\t\tgoto yy336;\n\t\t} else {\n\t\t\tif (yych <= '@') goto yy311;\n\t\t\tif (yych <= 'Z') goto yy336;\n\t\t\tgoto yy311;\n\t\t}\n\t} else {\n\t\tif (yych <= 'z') {\n\t\t\tif (yych == '`') goto yy311;\n\t\t\tgoto yy336;\n\t\t} else {\n\t\t\tif (yych == '}') goto yy348;\n\t\t\tgoto yy311;\n\t\t}\n\t}\nyy338:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'i') goto yy350;\n\tgoto yy311;\nyy339:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'c') goto yy351;\n\tgoto yy311;\nyy340:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy352;\n\tgoto yy311;\nyy341:\n\t++cur;\n\tif (lim <= cur) { if (!fill(1)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= 'Z') {\n\t\tif (yych <= '/') goto yy343;\n\t\tif (yych <= '9') goto yy341;\n\t\tif (yych >= 'A') goto yy341;\n\t} else {\n\t\tif (yych <= '_') {\n\t\t\tif (yych >= '_') goto yy341;\n\t\t} else {\n\t\t\tif (yych <= '`') goto yy343;\n\t\t\tif (yych <= 'z') goto yy341;\n\t\t}\n\t}\nyy343:\n\tp = yyt1;\n#line 430 \"../src/parse/lex.re\"\n\t{\n yylval.str = newstr(p, cur);\n return tok[0] == ':' ? TOKEN_CJUMP : TOKEN_CNEXT;\n }\n#line 2218 \"src/parse/lex.cc\"\nyy344:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'c') goto yy354;\n\tgoto yy302;\nyy345:\n\tyyaccept = 5;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= '/') goto yy333;\n\tif (yych <= '9') goto yy355;\n\tif (yych == '}') goto yy357;\n\tgoto yy333;\nyy346:\n\t++cur;\n#line 454 \"../src/parse/lex.re\"\n\t{\n if (!s_to_u32_unsafe (tok + 1, cur - 1, yylval.bounds.min)) {\n msg.error(tok_loc(), \"repetition count overflow\");\n exit(1);\n }\n yylval.bounds.max = yylval.bounds.min;\n return TOKEN_CLOSESIZE;\n }\n#line 2241 \"src/parse/lex.cc\"\nyy348:\n\t++cur;\n#line 490 \"../src/parse/lex.re\"\n\t{\n if (!globopts->FFlag) {\n msg.error(tok_loc(), \"curly braces for names only allowed with -F switch\");\n exit(1);\n }\n yylval.str = newstr(tok + 1, cur - 1);\n return TOKEN_ID;\n }\n#line 2253 \"src/parse/lex.cc\"\nyy350:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'n') goto yy359;\n\tgoto yy311;\nyy351:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'l') goto yy360;\n\tgoto yy311;\nyy352:\n\tyyaccept = 6;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych == ':') goto yy361;\nyy353:\n#line 539 \"../src/parse/lex.re\"\n\t{\n msg.error(tok_loc(), \"ill-formed use directive: expected `!use`\"\n \" followed by a colon, a block name, optional spaces, a semicolon,\"\n \" and finally a space, a newline, or the end of block\");\n exit(1);\n }\n#line 2274 \"src/parse/lex.cc\"\nyy354:\n\tyych = (unsigned char)*++cur;\n\tif (yych == ':') goto yy362;\n\tgoto yy302;\nyy355:\n\t++cur;\n\tif (lim <= cur) { if (!fill(1)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= '/') goto yy311;\n\tif (yych <= '9') goto yy355;\n\tif (yych == '}') goto yy364;\n\tgoto yy311;\nyy357:\n\t++cur;\n#line 475 \"../src/parse/lex.re\"\n\t{\n if (!s_to_u32_unsafe (tok + 1, cur - 2, yylval.bounds.min)) {\n msg.error(tok_loc(), \"repetition lower bound overflow\");\n exit(1);\n }\n yylval.bounds.max = std::numeric_limits::max();\n return TOKEN_CLOSESIZE;\n }\n#line 2298 \"src/parse/lex.cc\"\nyy359:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy366;\n\tgoto yy311;\nyy360:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'u') goto yy367;\n\tgoto yy311;\nyy361:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '^') {\n\t\tif (yych <= '@') goto yy311;\n\t\tif (yych <= 'Z') {\n\t\t\tyyt1 = cur;\n\t\t\tgoto yy368;\n\t\t}\n\t\tgoto yy311;\n\t} else {\n\t\tif (yych == '`') goto yy311;\n\t\tif (yych <= 'z') {\n\t\t\tyyt1 = cur;\n\t\t\tgoto yy368;\n\t\t}\n\t\tgoto yy311;\n\t}\nyy362:\n\t++cur;\n#line 499 \"../src/parse/lex.re\"\n\t{ return TOKEN_CONF; }\n#line 2328 \"src/parse/lex.cc\"\nyy364:\n\t++cur;\n\tp = yyt1;\n#line 463 \"../src/parse/lex.re\"\n\t{\n if (!s_to_u32_unsafe (tok + 1, p, yylval.bounds.min)) {\n msg.error(tok_loc(), \"repetition lower bound overflow\");\n exit(1);\n }\n if (!s_to_u32_unsafe (p + 1, cur - 1, yylval.bounds.max)) {\n msg.error(tok_loc(), \"repetition upper bound overflow\");\n exit(1);\n }\n return TOKEN_CLOSESIZE;\n }\n#line 2344 \"src/parse/lex.cc\"\nyy366:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '0') goto yy371;\n\tif (yych <= '9') goto yy311;\n\tgoto yy371;\nyy367:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'd') goto yy372;\n\tgoto yy311;\nyy368:\n\t++cur;\n\tif ((lim - cur) < 3) { if (!fill(3)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= ':') {\n\t\tif (yych <= 0x1F) {\n\t\t\tif (yych == '\\t') {\n\t\t\t\tyyt2 = cur;\n\t\t\t\tgoto yy373;\n\t\t\t}\n\t\t\tgoto yy311;\n\t\t} else {\n\t\t\tif (yych <= ' ') {\n\t\t\t\tyyt2 = cur;\n\t\t\t\tgoto yy373;\n\t\t\t}\n\t\t\tif (yych <= '/') goto yy311;\n\t\t\tif (yych <= '9') goto yy368;\n\t\t\tgoto yy311;\n\t\t}\n\t} else {\n\t\tif (yych <= '^') {\n\t\t\tif (yych <= ';') {\n\t\t\t\tyyt2 = cur;\n\t\t\t\tgoto yy375;\n\t\t\t}\n\t\t\tif (yych <= '@') goto yy311;\n\t\t\tif (yych <= 'Z') goto yy368;\n\t\t\tgoto yy311;\n\t\t} else {\n\t\t\tif (yych == '`') goto yy311;\n\t\t\tif (yych <= 'z') goto yy368;\n\t\t\tgoto yy311;\n\t\t}\n\t}\nyy370:\n\t++cur;\n\tif (lim <= cur) { if (!fill(1)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\nyy371:\n\tif (yych <= 0x1F) {\n\t\tif (yych == '\\t') goto yy370;\n\t\tgoto yy311;\n\t} else {\n\t\tif (yych <= ' ') goto yy370;\n\t\tif (yych <= '0') goto yy311;\n\t\tif (yych <= '9') {\n\t\t\tyyt1 = cur;\n\t\t\tgoto yy376;\n\t\t}\n\t\tgoto yy311;\n\t}\nyy372:\n\tyych = (unsigned char)*++cur;\n\tif (yych == 'e') goto yy378;\n\tgoto yy311;\nyy373:\n\t++cur;\n\tif ((lim - cur) < 3) { if (!fill(3)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= 0x1F) {\n\t\tif (yych == '\\t') goto yy373;\n\t\tgoto yy311;\n\t} else {\n\t\tif (yych <= ' ') goto yy373;\n\t\tif (yych != ';') goto yy311;\n\t}\nyy375:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '\\r') {\n\t\tif (yych <= 0x08) goto yy311;\n\t\tif (yych <= '\\n') {\n\t\t\tyyt3 = cur;\n\t\t\tgoto yy380;\n\t\t}\n\t\tif (yych <= '\\f') goto yy311;\n\t\tyyt3 = cur;\n\t\tgoto yy380;\n\t} else {\n\t\tif (yych <= ' ') {\n\t\t\tif (yych <= 0x1F) goto yy311;\n\t\t\tyyt3 = cur;\n\t\t\tgoto yy380;\n\t\t} else {\n\t\t\tif (yych == '*') {\n\t\t\t\tyyt3 = cur;\n\t\t\t\tgoto yy382;\n\t\t\t}\n\t\t\tgoto yy311;\n\t\t}\n\t}\nyy376:\n\t++cur;\n\tif ((lim - cur) < 2) { if (!fill(2)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= '\\r') {\n\t\tif (yych <= '\\t') {\n\t\t\tif (yych <= 0x08) goto yy311;\n\t\t\tgoto yy383;\n\t\t} else {\n\t\t\tif (yych <= '\\n') goto yy385;\n\t\t\tif (yych <= '\\f') goto yy311;\n\t\t\tgoto yy387;\n\t\t}\n\t} else {\n\t\tif (yych <= ' ') {\n\t\t\tif (yych <= 0x1F) goto yy311;\n\t\t\tgoto yy383;\n\t\t} else {\n\t\t\tif (yych <= '/') goto yy311;\n\t\t\tif (yych <= '9') goto yy376;\n\t\t\tgoto yy311;\n\t\t}\n\t}\nyy378:\n\tyyaccept = 7;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych == '\\t') goto yy388;\n\tif (yych == ' ') goto yy388;\nyy379:\n#line 528 \"../src/parse/lex.re\"\n\t{\n msg.error(tok_loc(), \"ill-formed include directive: expected `!include`\"\n \" followed by spaces, a double-quoted file path, optional spaces, a\"\n \" semicolon, and finally a space, a newline, or the end of block\");\n exit(1);\n }\n#line 2481 \"src/parse/lex.cc\"\nyy380:\n\t++cur;\n\tx = yyt1;\n\ty = yyt2;\n\tcur = yyt3;\n#line 535 \"../src/parse/lex.re\"\n\t{\n yylval.str = newstr(x, y); // save the name of the used block\n return TOKEN_BLOCK;\n }\n#line 2492 \"src/parse/lex.cc\"\nyy382:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '/') goto yy380;\n\tgoto yy311;\nyy383:\n\t++cur;\n\tif (lim <= cur) { if (!fill(1)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= 0x1F) {\n\t\tif (yych == '\\t') goto yy383;\n\t\tgoto yy311;\n\t} else {\n\t\tif (yych <= ' ') goto yy383;\n\t\tif (yych == '\"') goto yy390;\n\t\tgoto yy311;\n\t}\nyy385:\n\t++cur;\n\tcur = yyt1;\n#line 553 \"../src/parse/lex.re\"\n\t{\n set_sourceline ();\n return TOKEN_LINE_INFO;\n }\n#line 2517 \"src/parse/lex.cc\"\nyy387:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '\\n') goto yy385;\n\tgoto yy311;\nyy388:\n\t++cur;\n\tif (lim <= cur) { if (!fill(1)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= 0x1F) {\n\t\tif (yych == '\\t') goto yy388;\n\t\tgoto yy311;\n\t} else {\n\t\tif (yych <= ' ') goto yy388;\n\t\tif (yych == '\"') {\n\t\t\tyyt1 = cur;\n\t\t\tgoto yy392;\n\t\t}\n\t\tgoto yy311;\n\t}\nyy390:\n\t++cur;\n\tif ((lim - cur) < 3) { if (!fill(3)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yybm[0+yych] & 128) {\n\t\tgoto yy390;\n\t}\n\tif (yych <= '\\n') goto yy311;\n\tif (yych <= '\"') goto yy394;\n\tgoto yy395;\nyy392:\n\t++cur;\n\tif ((lim - cur) < 4) { if (!fill(4)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= '!') {\n\t\tif (yych <= 0x00) goto yy311;\n\t\tif (yych == '\\n') goto yy311;\n\t\tgoto yy392;\n\t} else {\n\t\tif (yych <= '\"') goto yy396;\n\t\tif (yych == '\\\\') goto yy397;\n\t\tgoto yy392;\n\t}\nyy394:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '\\n') goto yy385;\n\tif (yych == '\\r') goto yy387;\n\tgoto yy311;\nyy395:\n\t++cur;\n\tif (lim <= cur) { if (!fill(1)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= 0x00) goto yy311;\n\tif (yych == '\\n') goto yy311;\n\tgoto yy390;\nyy396:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= 0x1F) {\n\t\tif (yych == '\\t') {\n\t\t\tyyt2 = cur;\n\t\t\tgoto yy398;\n\t\t}\n\t\tgoto yy311;\n\t} else {\n\t\tif (yych <= ' ') {\n\t\t\tyyt2 = cur;\n\t\t\tgoto yy398;\n\t\t}\n\t\tif (yych == ';') {\n\t\t\tyyt2 = cur;\n\t\t\tgoto yy400;\n\t\t}\n\t\tgoto yy311;\n\t}\nyy397:\n\t++cur;\n\tif (lim <= cur) { if (!fill(1)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= 0x00) goto yy311;\n\tif (yych == '\\n') goto yy311;\n\tgoto yy392;\nyy398:\n\t++cur;\n\tif ((lim - cur) < 3) { if (!fill(3)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= 0x1F) {\n\t\tif (yych == '\\t') goto yy398;\n\t\tgoto yy311;\n\t} else {\n\t\tif (yych <= ' ') goto yy398;\n\t\tif (yych != ';') goto yy311;\n\t}\nyy400:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '\\r') {\n\t\tif (yych <= 0x08) goto yy311;\n\t\tif (yych <= '\\n') {\n\t\t\tyyt3 = cur;\n\t\t\tgoto yy401;\n\t\t}\n\t\tif (yych <= '\\f') goto yy311;\n\t\tyyt3 = cur;\n\t} else {\n\t\tif (yych <= ' ') {\n\t\t\tif (yych <= 0x1F) goto yy311;\n\t\t\tyyt3 = cur;\n\t\t} else {\n\t\t\tif (yych == '*') {\n\t\t\t\tyyt3 = cur;\n\t\t\t\tgoto yy403;\n\t\t\t}\n\t\t\tgoto yy311;\n\t\t}\n\t}\nyy401:\n\t++cur;\n\tx = yyt1;\n\ty = yyt2;\n\tcur = yyt3;\n#line 524 \"../src/parse/lex.re\"\n\t{\n include(getstr(x + 1, y - 1), tok);\n goto scan;\n }\n#line 2641 \"src/parse/lex.cc\"\nyy403:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '/') goto yy401;\n\tgoto yy311;\n}\n#line 573 \"../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_block_end(Output &out, bool allow_garbage)\n{\n bool multiline = false;\nloop:\n\n#line 1419 \"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) < 2) { if (!fill(2)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yybm[0+yych] & 128) {\n\t\tgoto yy234;\n\t}\n\tif (yych <= '\\f') {\n\t\tif (yych <= 0x08) goto yy232;\n\t\tif (yych <= '\\n') goto yy237;\n\t} else {\n\t\tif (yych <= '\\r') goto yy239;\n\t\tif (yych == '*') goto yy240;\n\t}\nyy232:\n\t++cur;\nyy233:\n#line 356 \"../src/parse/lex.re\"\n\t{\n if (allow_garbage && !is_eof()) goto loop;\n msg.error(cur_loc(), \"ill-formed end of block: expected optional\"\n \" whitespaces followed by `*\" \"/`\");\n return false;\n }\n#line 1478 \"src/parse/lex.cc\"\nyy234:\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 yy234;\n\t}\n#line 366 \"../src/parse/lex.re\"\n\t{ goto loop; }\n#line 1488 \"src/parse/lex.cc\"\nyy237:\n\t++cur;\n#line 367 \"../src/parse/lex.re\"\n\t{ next_line(); multiline = true; goto loop; }\n#line 1493 \"src/parse/lex.cc\"\nyy239:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '\\n') goto yy237;\n\tgoto yy233;\nyy240:\n\tyych = (unsigned char)*++cur;\n\tif (yych != '/') goto yy233;\n\t++cur;\n#line 362 \"../src/parse/lex.re\"\n\t{\n if (multiline) out.wdelay_stmt(0, code_line_info_input(out.allocator, cur_loc()));\n return true;\n }\n#line 1507 \"src/parse/lex.cc\"\n}\n#line 368 \"../src/parse/lex.re\"\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Emit an error when repetition lower bound exceeds upper bound.\n\nHistorically this was allowed and re2c swapped the bounds. However, it\nmost likely indicates an error in user code and there is only a single\noccurrence in the tests (and the test in an artificial one), so although\nthe change is backwards incompatible there is low chance of breaking\nreal-world code.\n\nThis fixes second test case in the bug #394 \"Stack overflow due to\nrecursion in src/dfa/dead_rules.cc\" (the actual fix is to limit DFA size\nbut the test also has counted repetition with swapped bounds).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: \tswitch (yych) {\n\t\tcase 'a': goto yy6;\n\t\tdefault: goto yy5;\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: TEST_F(RouterTest, RetryUpstreamResetResponseStarted) {\n NiceMock encoder1;\n Http::ResponseDecoder* response_decoder = nullptr;\n EXPECT_CALL(cm_.thread_local_cluster_.conn_pool_, newStream(_, _))\n .WillOnce(Invoke(\n [&](Http::ResponseDecoder& decoder,\n Http::ConnectionPool::Callbacks& callbacks) -> Http::ConnectionPool::Cancellable* {\n response_decoder = &decoder;\n callbacks.onPoolReady(encoder1, cm_.thread_local_cluster_.conn_pool_.host_,\n upstream_stream_info_, Http::Protocol::Http10);\n return nullptr;\n }));\n expectResponseTimerCreate();\n\n Http::TestRequestHeaderMapImpl headers{{\"x-envoy-retry-on\", \"5xx\"}, {\"x-envoy-internal\", \"true\"}};\n HttpTestUtility::addDefaultHeaders(headers);\n router_.decodeHeaders(headers, true);\n EXPECT_EQ(1U,\n callbacks_.route_->route_entry_.virtual_cluster_.stats().upstream_rq_total_.value());\n\n // Since the response is already started we don't retry.\n EXPECT_CALL(*router_.retry_state_, shouldRetryHeaders(_, _)).WillOnce(Return(RetryStatus::No));\n EXPECT_CALL(callbacks_, encodeHeaders_(_, false));\n Http::ResponseHeaderMapPtr response_headers(\n new Http::TestResponseHeaderMapImpl{{\":status\", \"200\"}});\n EXPECT_CALL(cm_.thread_local_cluster_.conn_pool_.host_->outlier_detector_,\n putHttpResponseCode(200));\n response_decoder->decodeHeaders(std::move(response_headers), false);\n EXPECT_CALL(cm_.thread_local_cluster_.conn_pool_.host_->outlier_detector_,\n putResult(Upstream::Outlier::Result::LocalOriginConnectFailed, _));\n // Normally, sendLocalReply will actually send the reply, but in this case the\n // HCM will detect the headers have already been sent and not route through\n // the encoder again.\n EXPECT_CALL(callbacks_, sendLocalReply(_, _, _, _, _)).WillOnce(testing::InvokeWithoutArgs([] {\n }));\n encoder1.stream_.resetStream(Http::StreamResetReason::RemoteReset);\n // For normal HTTP, once we have a 200 we consider this a success, even if a\n // later reset occurs.\n EXPECT_TRUE(verifyHostUpstreamStats(1, 0));\n EXPECT_EQ(1U,\n callbacks_.route_->route_entry_.virtual_cluster_.stats().upstream_rq_total_.value());\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: */\nstatic void php_wddx_process_data(void *user_data, const XML_Char *s, int len)\n{\n\tst_entry *ent;\n\twddx_stack *stack = (wddx_stack *)user_data;\n\tTSRMLS_FETCH();\n\n\tif (!wddx_stack_is_empty(stack) && !stack->done) {\n\t\twddx_stack_top(stack, (void**)&ent);\n\t\tswitch (ent->type) {\n\t\t\tcase ST_STRING:\n\t\t\t\tif (Z_STRLEN_P(ent->data) == 0) {\n\t\t\t\t\tSTR_FREE(Z_STRVAL_P(ent->data));\n\t\t\t\t\tZ_STRVAL_P(ent->data) = estrndup(s, len);\n\t\t\t\t\tZ_STRLEN_P(ent->data) = len;\n\t\t\t\t} else {\n\t\t\t\t\tZ_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1);\n\t\t\t\t\tmemcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len);\n\t\t\t\t\tZ_STRLEN_P(ent->data) += len;\n\t\t\t\t\tZ_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\\0';\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase ST_BINARY:\n\t\t\t\tif (Z_STRLEN_P(ent->data) == 0) {\n\t\t\t\t\tSTR_FREE(Z_STRVAL_P(ent->data));\n\t\t\t\t\tZ_STRVAL_P(ent->data) = estrndup(s, len + 1);\n\t\t\t\t} else {\n\t\t\t\t\tZ_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1);\n\t\t\t\t\tmemcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len);\n\t\t\t\t}\n\t\t\t\tZ_STRLEN_P(ent->data) += len;\n\t\t\t\tZ_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\\0';\n\t\t\t\tbreak;\n\n\t\t\tcase ST_NUMBER:\n\t\t\t\tZ_TYPE_P(ent->data) = IS_STRING;\n\t\t\t\tZ_STRLEN_P(ent->data) = len;\n\t\t\t\tZ_STRVAL_P(ent->data) = estrndup(s, len);\n\t\t\t\tconvert_scalar_to_number(ent->data TSRMLS_CC);\n\t\t\t\tbreak;\n\n\t\t\tcase ST_BOOLEAN:\n\t\t\t\tif(!ent->data) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (!strcmp(s, \"true\")) {\n\t\t\t\t\tZ_LVAL_P(ent->data) = 1;\n\t\t\t\t} else if (!strcmp(s, \"false\")) {\n\t\t\t\t\tZ_LVAL_P(ent->data) = 0;\n\t\t\t\t} else {\n\t\t\t\t\tzval_ptr_dtor(&ent->data);\n\t\t\t\t\tif (ent->varname) {\n\t\t\t\t\t\tefree(ent->varname);\n\t\t\t\t\t\tent->varname = NULL;\n\t\t\t\t\t}\n\t\t\t\t\tent->data = NULL;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase ST_DATETIME: {\n\t\t\t\tchar *tmp;\n\n\t\t\t\ttmp = emalloc(len + 1);\n\t\t\t\tmemcpy(tmp, s, len);\n\t\t\t\ttmp[len] = '\\0';\n\n\t\t\t\tZ_LVAL_P(ent->data) = php_parse_date(tmp, NULL);\n\t\t\t\t/* date out of range < 1969 or > 2038 */\n\t\t\t\tif (Z_LVAL_P(ent->data) == -1) {\n\t\t\t\t\tZ_TYPE_P(ent->data) = IS_STRING;\n\t\t\t\t\tZ_STRLEN_P(ent->data) = len;\n\t\t\t\t\tZ_STRVAL_P(ent->data) = estrndup(s, len);\n\t\t\t\t}\n\t\t\t\tefree(tmp);\n\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #72749: wddx_deserialize allows illegal memory access'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: pimv2_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\tint advance;\n\tenum checksum_status cksum_status;\n\n\tep = (const u_char *)ndo->ndo_snapend;\n\tif (bp >= ep)\n\t\treturn;\n\tif (ep > bp + len)\n\t\tep = bp + len;\n\tND_TCHECK(pim->pim_rsv);\n\tpimv2_addr_len = pim->pim_rsv;\n\tif (pimv2_addr_len != 0)\n\t\tND_PRINT((ndo, \", RFC2117-encoding\"));\n\n\tND_PRINT((ndo, \", cksum 0x%04x \", EXTRACT_16BITS(&pim->pim_cksum)));\n\tif (EXTRACT_16BITS(&pim->pim_cksum) == 0) {\n\t\tND_PRINT((ndo, \"(unverified)\"));\n\t} else {\n\t\tif (PIM_TYPE(pim->pim_typever) == PIMV2_TYPE_REGISTER) {\n\t\t\t/*\n\t\t\t * The checksum only covers the packet header,\n\t\t\t * not the encapsulated packet.\n\t\t\t */\n\t\t\tcksum_status = pimv2_check_checksum(ndo, bp, bp2, 8);\n\t\t\tif (cksum_status == INCORRECT) {\n\t\t\t\t/*\n\t\t\t\t * To quote RFC 4601, \"For interoperability\n\t\t\t\t * reasons, a message carrying a checksum\n\t\t\t\t * calculated over the entire PIM Register\n\t\t\t\t * message should also be accepted.\"\n\t\t\t\t */\n\t\t\t\tcksum_status = pimv2_check_checksum(ndo, bp, bp2, len);\n\t\t\t}\n\t\t} else {\n\t\t\t/*\n\t\t\t * The checksum covers the entire packet.\n\t\t\t */\n\t\t\tcksum_status = pimv2_check_checksum(ndo, bp, bp2, len);\n\t\t}\n\t\tswitch (cksum_status) {\n\n\t\tcase CORRECT:\n\t\t\tND_PRINT((ndo, \"(correct)\"));\n\t\t\tbreak;\n\n\t\tcase INCORRECT:\n\t\t\tND_PRINT((ndo, \"(incorrect)\"));\n\t\t\tbreak;\n\n\t\tcase UNVERIFIED:\n\t\t\tND_PRINT((ndo, \"(unverified)\"));\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tswitch (PIM_TYPE(pim->pim_typever)) {\n\tcase PIMV2_TYPE_HELLO:\n\t {\n\t\tuint16_t otype, olen;\n\t\tbp += 4;\n\t\twhile (bp < ep) {\n\t\t\tND_TCHECK2(bp[0], 4);\n\t\t\totype = EXTRACT_16BITS(&bp[0]);\n\t\t\tolen = EXTRACT_16BITS(&bp[2]);\n\t\t\tND_TCHECK2(bp[0], 4 + olen);\n\t\t\tND_PRINT((ndo, \"\\n\\t %s Option (%u), length %u, Value: \",\n\t\t\t tok2str(pimv2_hello_option_values, \"Unknown\", otype),\n\t\t\t otype,\n\t\t\t olen));\n\t\t\tbp += 4;\n\n\t\t\tswitch (otype) {\n\t\t\tcase PIMV2_HELLO_OPTION_HOLDTIME:\n\t\t\t\tif (olen != 2) {\n\t\t\t\t\tND_PRINT((ndo, \"ERROR: Option Length != 2 Bytes (%u)\", olen));\n\t\t\t\t} else {\n\t\t\t\t\tunsigned_relts_print(ndo, EXTRACT_16BITS(bp));\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase PIMV2_HELLO_OPTION_LANPRUNEDELAY:\n\t\t\t\tif (olen != 4) {\n\t\t\t\t\tND_PRINT((ndo, \"ERROR: Option Length != 4 Bytes (%u)\", olen));\n\t\t\t\t} else {\n\t\t\t\t\tchar t_bit;\n\t\t\t\t\tuint16_t lan_delay, override_interval;\n\t\t\t\t\tlan_delay = EXTRACT_16BITS(bp);\n\t\t\t\t\toverride_interval = EXTRACT_16BITS(bp+2);\n\t\t\t\t\tt_bit = (lan_delay & 0x8000)? 1 : 0;\n\t\t\t\t\tlan_delay &= ~0x8000;\n\t\t\t\t\tND_PRINT((ndo, \"\\n\\t T-bit=%d, LAN delay %dms, Override interval %dms\",\n\t\t\t\t\tt_bit, lan_delay, override_interval));\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase PIMV2_HELLO_OPTION_DR_PRIORITY_OLD:\n\t\t\tcase PIMV2_HELLO_OPTION_DR_PRIORITY:\n\t\t\t\tswitch (olen) {\n\t\t\t\tcase 0:\n\t\t\t\t\tND_PRINT((ndo, \"Bi-Directional Capability (Old)\"));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 4:\n\t\t\t\t\tND_PRINT((ndo, \"%u\", EXTRACT_32BITS(bp)));\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tND_PRINT((ndo, \"ERROR: Option Length != 4 Bytes (%u)\", olen));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase PIMV2_HELLO_OPTION_GENID:\n\t\t\t\tif (olen != 4) {\n\t\t\t\t\tND_PRINT((ndo, \"ERROR: Option Length != 4 Bytes (%u)\", olen));\n\t\t\t\t} else {\n\t\t\t\t\tND_PRINT((ndo, \"0x%08x\", EXTRACT_32BITS(bp)));\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase PIMV2_HELLO_OPTION_REFRESH_CAP:\n\t\t\t\tif (olen != 4) {\n\t\t\t\t\tND_PRINT((ndo, \"ERROR: Option Length != 4 Bytes (%u)\", olen));\n\t\t\t\t} else {\n\t\t\t\t\tND_PRINT((ndo, \"v%d\", *bp));\n\t\t\t\t\tif (*(bp+1) != 0) {\n\t\t\t\t\t\tND_PRINT((ndo, \", interval \"));\n\t\t\t\t\t\tunsigned_relts_print(ndo, *(bp+1));\n\t\t\t\t\t}\n\t\t\t\t\tif (EXTRACT_16BITS(bp+2) != 0) {\n\t\t\t\t\t\tND_PRINT((ndo, \" ?0x%04x?\", EXTRACT_16BITS(bp+2)));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase PIMV2_HELLO_OPTION_BIDIR_CAP:\n\t\t\t\tbreak;\n\n\t\t\tcase PIMV2_HELLO_OPTION_ADDRESS_LIST_OLD:\n\t\t\tcase PIMV2_HELLO_OPTION_ADDRESS_LIST:\n\t\t\t\tif (ndo->ndo_vflag > 1) {\n\t\t\t\t\tconst u_char *ptr = bp;\n\t\t\t\t\twhile (ptr < (bp+olen)) {\n\t\t\t\t\t\tND_PRINT((ndo, \"\\n\\t \"));\n\t\t\t\t\t\tadvance = pimv2_addr_print(ndo, ptr, pimv2_unicast, 0);\n\t\t\t\t\t\tif (advance < 0) {\n\t\t\t\t\t\t\tND_PRINT((ndo, \"...\"));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tptr += advance;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif (ndo->ndo_vflag <= 1)\n\t\t\t\t\tprint_unknown_data(ndo, bp, \"\\n\\t \", olen);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/* do we want to see an additionally hexdump ? */\n\t\t\tif (ndo->ndo_vflag> 1)\n\t\t\t\tprint_unknown_data(ndo, bp, \"\\n\\t \", olen);\n\t\t\tbp += olen;\n\t\t}\n\t\tbreak;\n\t }\n\n\tcase PIMV2_TYPE_REGISTER:\n\t{\n\t\tconst struct ip *ip;\n\n\t\tND_TCHECK2(*(bp + 4), PIMV2_REGISTER_FLAG_LEN);\n\n\t\tND_PRINT((ndo, \", Flags [ %s ]\\n\\t\",\n\t\t tok2str(pimv2_register_flag_values,\n\t\t \"none\",\n\t\t EXTRACT_32BITS(bp+4))));\n\n\t\tbp += 8; len -= 8;\n\t\t/* encapsulated multicast packet */\n\t\tip = (const struct ip *)bp;\n\t\tswitch (IP_V(ip)) {\n case 0: /* Null header */\n\t\t\tND_PRINT((ndo, \"IP-Null-header %s > %s\",\n\t\t\t ipaddr_string(ndo, &ip->ip_src),\n\t\t\t ipaddr_string(ndo, &ip->ip_dst)));\n\t\t\tbreak;\n\n\t\tcase 4:\t/* IPv4 */\n\t\t\tip_print(ndo, bp, len);\n\t\t\tbreak;\n\n\t\tcase 6:\t/* IPv6 */\n\t\t\tip6_print(ndo, bp, len);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tND_PRINT((ndo, \"IP ver %d\", IP_V(ip)));\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\t}\n\n\tcase PIMV2_TYPE_REGISTER_STOP:\n\t\tbp += 4; len -= 4;\n\t\tif (bp >= ep)\n\t\t\tbreak;\n\t\tND_PRINT((ndo, \" group=\"));\n\t\tif ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {\n\t\t\tND_PRINT((ndo, \"...\"));\n\t\t\tbreak;\n\t\t}\n\t\tbp += advance; len -= advance;\n\t\tif (bp >= ep)\n\t\t\tbreak;\n\t\tND_PRINT((ndo, \" source=\"));\n\t\tif ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {\n\t\t\tND_PRINT((ndo, \"...\"));\n\t\t\tbreak;\n\t\t}\n\t\tbp += advance; len -= advance;\n\t\tbreak;\n\n\tcase PIMV2_TYPE_JOIN_PRUNE:\n\tcase PIMV2_TYPE_GRAFT:\n\tcase PIMV2_TYPE_GRAFT_ACK:\n\n\n /*\n * 0 1 2 3\n * 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 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * |PIM Ver| Type | Addr length | Checksum |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | Unicast-Upstream Neighbor Address |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | Reserved | Num groups | Holdtime |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | Encoded-Multicast Group Address-1 |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | Number of Joined Sources | Number of Pruned Sources |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | Encoded-Joined Source Address-1 |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | . |\n * | . |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | Encoded-Joined Source Address-n |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | Encoded-Pruned Source Address-1 |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | . |\n * | . |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | Encoded-Pruned Source Address-n |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | . |\n * | . |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | Encoded-Multicast Group Address-n |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n */\n\n\t {\n\t\tuint8_t ngroup;\n\t\tuint16_t holdtime;\n\t\tuint16_t njoin;\n\t\tuint16_t nprune;\n\t\tint i, j;\n\n\t\tbp += 4; len -= 4;\n\t\tif (PIM_TYPE(pim->pim_typever) != 7) {\t/*not for Graft-ACK*/\n\t\t\tif (bp >= ep)\n\t\t\t\tbreak;\n\t\t\tND_PRINT((ndo, \", upstream-neighbor: \"));\n\t\t\tif ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {\n\t\t\t\tND_PRINT((ndo, \"...\"));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbp += advance; len -= advance;\n\t\t}\n\t\tif (bp + 4 > ep)\n\t\t\tbreak;\n\t\tngroup = bp[1];\n\t\tholdtime = EXTRACT_16BITS(&bp[2]);\n\t\tND_PRINT((ndo, \"\\n\\t %u group(s)\", ngroup));\n\t\tif (PIM_TYPE(pim->pim_typever) != 7) {\t/*not for Graft-ACK*/\n\t\t\tND_PRINT((ndo, \", holdtime: \"));\n\t\t\tif (holdtime == 0xffff)\n\t\t\t\tND_PRINT((ndo, \"infinite\"));\n\t\t\telse\n\t\t\t\tunsigned_relts_print(ndo, holdtime);\n\t\t}\n\t\tbp += 4; len -= 4;\n\t\tfor (i = 0; i < ngroup; i++) {\n\t\t\tif (bp >= ep)\n\t\t\t\tgoto jp_done;\n\t\t\tND_PRINT((ndo, \"\\n\\t group #%u: \", i+1));\n\t\t\tif ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {\n\t\t\t\tND_PRINT((ndo, \"...)\"));\n\t\t\t\tgoto jp_done;\n\t\t\t}\n\t\t\tbp += advance; len -= advance;\n\t\t\tif (bp + 4 > ep) {\n\t\t\t\tND_PRINT((ndo, \"...)\"));\n\t\t\t\tgoto jp_done;\n\t\t\t}\n\t\t\tnjoin = EXTRACT_16BITS(&bp[0]);\n\t\t\tnprune = EXTRACT_16BITS(&bp[2]);\n\t\t\tND_PRINT((ndo, \", joined sources: %u, pruned sources: %u\", njoin, nprune));\n\t\t\tbp += 4; len -= 4;\n\t\t\tfor (j = 0; j < njoin; j++) {\n\t\t\t\tND_PRINT((ndo, \"\\n\\t joined source #%u: \", j+1));\n\t\t\t\tif ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) {\n\t\t\t\t\tND_PRINT((ndo, \"...)\"));\n\t\t\t\t\tgoto jp_done;\n\t\t\t\t}\n\t\t\t\tbp += advance; len -= advance;\n\t\t\t}\n\t\t\tfor (j = 0; j < nprune; j++) {\n\t\t\t\tND_PRINT((ndo, \"\\n\\t pruned source #%u: \", j+1));\n\t\t\t\tif ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) {\n\t\t\t\t\tND_PRINT((ndo, \"...)\"));\n\t\t\t\t\tgoto jp_done;\n\t\t\t\t}\n\t\t\t\tbp += advance; len -= advance;\n\t\t\t}\n\t\t}\n\tjp_done:\n\t\tbreak;\n\t }\n\n\tcase PIMV2_TYPE_BOOTSTRAP:\n\t{\n\t\tint i, j, frpcnt;\n\t\tbp += 4;\n\n\t\t/* Fragment Tag, Hash Mask len, and BSR-priority */\n\t\tif (bp + sizeof(uint16_t) >= ep) break;\n\t\tND_PRINT((ndo, \" tag=%x\", EXTRACT_16BITS(bp)));\n\t\tbp += sizeof(uint16_t);\n\t\tif (bp >= ep) break;\n\t\tND_PRINT((ndo, \" hashmlen=%d\", bp[0]));\n\t\tif (bp + 1 >= ep) break;\n\t\tND_PRINT((ndo, \" BSRprio=%d\", bp[1]));\n\t\tbp += 2;\n\n\t\t/* Encoded-Unicast-BSR-Address */\n\t\tif (bp >= ep) break;\n\t\tND_PRINT((ndo, \" BSR=\"));\n\t\tif ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {\n\t\t\tND_PRINT((ndo, \"...\"));\n\t\t\tbreak;\n\t\t}\n\t\tbp += advance;\n\n\t\tfor (i = 0; bp < ep; i++) {\n\t\t\t/* Encoded-Group Address */\n\t\t\tND_PRINT((ndo, \" (group%d: \", i));\n\t\t\tif ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0))\n\t\t\t < 0) {\n\t\t\t\tND_PRINT((ndo, \"...)\"));\n\t\t\t\tgoto bs_done;\n\t\t\t}\n\t\t\tbp += advance;\n\n\t\t\t/* RP-Count, Frag RP-Cnt, and rsvd */\n\t\t\tif (bp >= ep) {\n\t\t\t\tND_PRINT((ndo, \"...)\"));\n\t\t\t\tgoto bs_done;\n\t\t\t}\n\t\t\tND_PRINT((ndo, \" RPcnt=%d\", bp[0]));\n\t\t\tif (bp + 1 >= ep) {\n\t\t\t\tND_PRINT((ndo, \"...)\"));\n\t\t\t\tgoto bs_done;\n\t\t\t}\n\t\t\tND_PRINT((ndo, \" FRPcnt=%d\", frpcnt = bp[1]));\n\t\t\tbp += 4;\n\n\t\t\tfor (j = 0; j < frpcnt && bp < ep; j++) {\n\t\t\t\t/* each RP info */\n\t\t\t\tND_PRINT((ndo, \" RP%d=\", j));\n\t\t\t\tif ((advance = pimv2_addr_print(ndo, bp,\n\t\t\t\t\t\t\t\tpimv2_unicast,\n\t\t\t\t\t\t\t\t0)) < 0) {\n\t\t\t\t\tND_PRINT((ndo, \"...)\"));\n\t\t\t\t\tgoto bs_done;\n\t\t\t\t}\n\t\t\t\tbp += advance;\n\n\t\t\t\tif (bp + 1 >= ep) {\n\t\t\t\t\tND_PRINT((ndo, \"...)\"));\n\t\t\t\t\tgoto bs_done;\n\t\t\t\t}\n\t\t\t\tND_PRINT((ndo, \",holdtime=\"));\n\t\t\t\tunsigned_relts_print(ndo, EXTRACT_16BITS(bp));\n\t\t\t\tif (bp + 2 >= ep) {\n\t\t\t\t\tND_PRINT((ndo, \"...)\"));\n\t\t\t\t\tgoto bs_done;\n\t\t\t\t}\n\t\t\t\tND_PRINT((ndo, \",prio=%d\", bp[2]));\n\t\t\t\tbp += 4;\n\t\t\t}\n\t\t\tND_PRINT((ndo, \")\"));\n\t\t}\n\t bs_done:\n\t\tbreak;\n\t}\n\tcase PIMV2_TYPE_ASSERT:\n\t\tbp += 4; len -= 4;\n\t\tif (bp >= ep)\n\t\t\tbreak;\n\t\tND_PRINT((ndo, \" group=\"));\n\t\tif ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {\n\t\t\tND_PRINT((ndo, \"...\"));\n\t\t\tbreak;\n\t\t}\n\t\tbp += advance; len -= advance;\n\t\tif (bp >= ep)\n\t\t\tbreak;\n\t\tND_PRINT((ndo, \" src=\"));\n\t\tif ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {\n\t\t\tND_PRINT((ndo, \"...\"));\n\t\t\tbreak;\n\t\t}\n\t\tbp += advance; len -= advance;\n\t\tif (bp + 8 > ep)\n\t\t\tbreak;\n\t\tif (bp[0] & 0x80)\n\t\t\tND_PRINT((ndo, \" RPT\"));\n\t\tND_PRINT((ndo, \" pref=%u\", EXTRACT_32BITS(&bp[0]) & 0x7fffffff));\n\t\tND_PRINT((ndo, \" metric=%u\", EXTRACT_32BITS(&bp[4])));\n\t\tbreak;\n\n\tcase PIMV2_TYPE_CANDIDATE_RP:\n\t{\n\t\tint i, pfxcnt;\n\t\tbp += 4;\n\n\t\t/* Prefix-Cnt, Priority, and Holdtime */\n\t\tif (bp >= ep) break;\n\t\tND_PRINT((ndo, \" prefix-cnt=%d\", bp[0]));\n\t\tpfxcnt = bp[0];\n\t\tif (bp + 1 >= ep) break;\n\t\tND_PRINT((ndo, \" prio=%d\", bp[1]));\n\t\tif (bp + 3 >= ep) break;\n\t\tND_PRINT((ndo, \" holdtime=\"));\n\t\tunsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2]));\n\t\tbp += 4;\n\n\t\t/* Encoded-Unicast-RP-Address */\n\t\tif (bp >= ep) break;\n\t\tND_PRINT((ndo, \" RP=\"));\n\t\tif ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {\n\t\t\tND_PRINT((ndo, \"...\"));\n\t\t\tbreak;\n\t\t}\n\t\tbp += advance;\n\n\t\t/* Encoded-Group Addresses */\n\t\tfor (i = 0; i < pfxcnt && bp < ep; i++) {\n\t\t\tND_PRINT((ndo, \" Group%d=\", i));\n\t\t\tif ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0))\n\t\t\t < 0) {\n\t\t\t\tND_PRINT((ndo, \"...\"));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbp += advance;\n\t\t}\n\t\tbreak;\n\t}\n\n\tcase PIMV2_TYPE_PRUNE_REFRESH:\n\t\tND_PRINT((ndo, \" src=\"));\n\t\tif ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {\n\t\t\tND_PRINT((ndo, \"...\"));\n\t\t\tbreak;\n\t\t}\n\t\tbp += advance;\n\t\tND_PRINT((ndo, \" grp=\"));\n\t\tif ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {\n\t\t\tND_PRINT((ndo, \"...\"));\n\t\t\tbreak;\n\t\t}\n\t\tbp += advance;\n\t\tND_PRINT((ndo, \" forwarder=\"));\n\t\tif ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {\n\t\t\tND_PRINT((ndo, \"...\"));\n\t\t\tbreak;\n\t\t}\n\t\tbp += advance;\n\t\tND_TCHECK2(bp[0], 2);\n\t\tND_PRINT((ndo, \" TUNR \"));\n\t\tunsigned_relts_print(ndo, EXTRACT_16BITS(bp));\n\t\tbreak;\n\n\n\t default:\n\t\tND_PRINT((ndo, \" [type %d]\", PIM_TYPE(pim->pim_typever)));\n\t\tbreak;\n\t}\n\n\treturn;\n\ntrunc:\n\tND_PRINT((ndo, \"[|pim]\"));\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: DefineSequence(ParseState *pstate, CreateSeqStmt *seq)\n{\n\tFormData_pg_sequence seqform;\n\tFormData_pg_sequence_data seqdataform;\n\tbool\t\tneed_seq_rewrite;\n\tList\t *owned_by;\n\tCreateStmt *stmt = makeNode(CreateStmt);\n\tOid\t\t\tseqoid;\n\tObjectAddress address;\n\tRelation\trel;\n\tHeapTuple\ttuple;\n\tTupleDesc\ttupDesc;\n\tDatum\t\tvalue[SEQ_COL_LASTCOL];\n\tbool\t\tnull[SEQ_COL_LASTCOL];\n\tDatum\t\tpgs_values[Natts_pg_sequence];\n\tbool\t\tpgs_nulls[Natts_pg_sequence];\n\tint\t\t\ti;\n\n\t/* Unlogged sequences are not implemented -- not clear if useful. */\n\tif (seq->sequence->relpersistence == RELPERSISTENCE_UNLOGGED)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t errmsg(\"unlogged sequences are not supported\")));\n\n\t/*\n\t * If if_not_exists was given and a relation with the same name already\n\t * exists, bail out. (Note: we needn't check this when not if_not_exists,\n\t * because DefineRelation will complain anyway.)\n\t */\n\tif (seq->if_not_exists)\n\t{\n\t\tRangeVarGetAndCheckCreationNamespace(seq->sequence, NoLock, &seqoid);\n\t\tif (OidIsValid(seqoid))\n\t\t{\n\t\t\tereport(NOTICE,\n\t\t\t\t\t(errcode(ERRCODE_DUPLICATE_TABLE),\n\t\t\t\t\t errmsg(\"relation \\\"%s\\\" already exists, skipping\",\n\t\t\t\t\t\t\tseq->sequence->relname)));\n\t\t\treturn InvalidObjectAddress;\n\t\t}\n\t}\n\n\t/* Check and set all option values */\n\tinit_params(pstate, seq->options, seq->for_identity, true,\n\t\t\t\t&seqform, &seqdataform,\n\t\t\t\t&need_seq_rewrite, &owned_by);\n\n\t/*\n\t * Create relation (and fill value[] and null[] for the tuple)\n\t */\n\tstmt->tableElts = NIL;\n\tfor (i = SEQ_COL_FIRSTCOL; i <= SEQ_COL_LASTCOL; i++)\n\t{\n\t\tColumnDef *coldef = makeNode(ColumnDef);\n\n\t\tcoldef->inhcount = 0;\n\t\tcoldef->is_local = true;\n\t\tcoldef->is_not_null = true;\n\t\tcoldef->is_from_type = false;\n\t\tcoldef->storage = 0;\n\t\tcoldef->raw_default = NULL;\n\t\tcoldef->cooked_default = NULL;\n\t\tcoldef->collClause = NULL;\n\t\tcoldef->collOid = InvalidOid;\n\t\tcoldef->constraints = NIL;\n\t\tcoldef->location = -1;\n\n\t\tnull[i - 1] = false;\n\n\t\tswitch (i)\n\t\t{\n\t\t\tcase SEQ_COL_LASTVAL:\n\t\t\t\tcoldef->typeName = makeTypeNameFromOid(INT8OID, -1);\n\t\t\t\tcoldef->colname = \"last_value\";\n\t\t\t\tvalue[i - 1] = Int64GetDatumFast(seqdataform.last_value);\n\t\t\t\tbreak;\n\t\t\tcase SEQ_COL_LOG:\n\t\t\t\tcoldef->typeName = makeTypeNameFromOid(INT8OID, -1);\n\t\t\t\tcoldef->colname = \"log_cnt\";\n\t\t\t\tvalue[i - 1] = Int64GetDatum((int64) 0);\n\t\t\t\tbreak;\n\t\t\tcase SEQ_COL_CALLED:\n\t\t\t\tcoldef->typeName = makeTypeNameFromOid(BOOLOID, -1);\n\t\t\t\tcoldef->colname = \"is_called\";\n\t\t\t\tvalue[i - 1] = BoolGetDatum(false);\n\t\t\t\tbreak;\n\t\t}\n\t\tstmt->tableElts = lappend(stmt->tableElts, coldef);\n\t}\n\n\tstmt->relation = seq->sequence;\n\tstmt->inhRelations = NIL;\n\tstmt->constraints = NIL;\n\tstmt->options = NIL;\n\tstmt->oncommit = ONCOMMIT_NOOP;\n\tstmt->tablespacename = NULL;\n\tstmt->if_not_exists = seq->if_not_exists;\n\n\taddress = DefineRelation(stmt, RELKIND_SEQUENCE, seq->ownerId, NULL, NULL);\n\tseqoid = address.objectId;\n\tAssert(seqoid != InvalidOid);\n\n\trel = heap_open(seqoid, AccessExclusiveLock);\n\ttupDesc = RelationGetDescr(rel);\n\n\t/* now initialize the sequence's data */\n\ttuple = heap_form_tuple(tupDesc, value, null);\n\tfill_seq_with_data(rel, tuple);\n\n\t/* process OWNED BY if given */\n\tif (owned_by)\n\t\tprocess_owned_by(rel, owned_by, seq->for_identity);\n\n\theap_close(rel, NoLock);\n\n\t/* fill in pg_sequence */\n\trel = heap_open(SequenceRelationId, RowExclusiveLock);\n\ttupDesc = RelationGetDescr(rel);\n\n\tmemset(pgs_nulls, 0, sizeof(pgs_nulls));\n\n\tpgs_values[Anum_pg_sequence_seqrelid - 1] = ObjectIdGetDatum(seqoid);\n\tpgs_values[Anum_pg_sequence_seqtypid - 1] = ObjectIdGetDatum(seqform.seqtypid);\n\tpgs_values[Anum_pg_sequence_seqstart - 1] = Int64GetDatumFast(seqform.seqstart);\n\tpgs_values[Anum_pg_sequence_seqincrement - 1] = Int64GetDatumFast(seqform.seqincrement);\n\tpgs_values[Anum_pg_sequence_seqmax - 1] = Int64GetDatumFast(seqform.seqmax);\n\tpgs_values[Anum_pg_sequence_seqmin - 1] = Int64GetDatumFast(seqform.seqmin);\n\tpgs_values[Anum_pg_sequence_seqcache - 1] = Int64GetDatumFast(seqform.seqcache);\n\tpgs_values[Anum_pg_sequence_seqcycle - 1] = BoolGetDatum(seqform.seqcycle);\n\n\ttuple = heap_form_tuple(tupDesc, pgs_values, pgs_nulls);\n\tCatalogTupleInsert(rel, tuple);\n\n\theap_freetuple(tuple);\n\theap_close(rel, RowExclusiveLock);\n\n\treturn address;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-94'], 'message': 'In extensions, don't replace objects not belonging to the extension.\n\nPreviously, if an extension script did CREATE OR REPLACE and there was\nan existing object not belonging to the extension, it would overwrite\nthe object and adopt it into the extension. This is problematic, first\nbecause the overwrite is probably unintentional, and second because we\ndidn't change the object's ownership. Thus a hostile user could create\nan object in advance of an expected CREATE EXTENSION command, and would\nthen have ownership rights on an extension object, which could be\nmodified for trojan-horse-type attacks.\n\nHence, forbid CREATE OR REPLACE of an existing object unless it already\nbelongs to the extension. (Note that we've always forbidden replacing\nan object that belongs to some other extension; only the behavior for\npreviously-free-standing objects changes here.)\n\nFor the same reason, also fail CREATE IF NOT EXISTS when there is\nan existing object that doesn't belong to the extension.\n\nOur thanks to Sven Klemm for reporting this problem.\n\nSecurity: CVE-2022-2625'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static bool ldm_frag_add (const u8 *data, int size, struct list_head *frags)\n{\n\tstruct frag *f;\n\tstruct list_head *item;\n\tint rec, num, group;\n\n\tBUG_ON (!data || !frags);\n\n\tif (size < 2 * VBLK_SIZE_HEAD) {\n\t\tldm_error(\"Value of size is to small.\");\n\t\treturn false;\n\t}\n\n\tgroup = get_unaligned_be32(data + 0x08);\n\trec = get_unaligned_be16(data + 0x0C);\n\tnum = get_unaligned_be16(data + 0x0E);\n\tif ((num < 1) || (num > 4)) {\n\t\tldm_error (\"A VBLK claims to have %d parts.\", num);\n\t\treturn false;\n\t}\n\tif (rec >= num) {\n\t\tldm_error(\"REC value (%d) exceeds NUM value (%d)\", rec, num);\n\t\treturn false;\n\t}\n\n\tlist_for_each (item, frags) {\n\t\tf = list_entry (item, struct frag, list);\n\t\tif (f->group == group)\n\t\t\tgoto found;\n\t}\n\n\tf = kmalloc (sizeof (*f) + size*num, GFP_KERNEL);\n\tif (!f) {\n\t\tldm_crit (\"Out of memory.\");\n\t\treturn false;\n\t}\n\n\tf->group = group;\n\tf->num = num;\n\tf->rec = rec;\n\tf->map = 0xFF << num;\n\n\tlist_add_tail (&f->list, frags);\nfound:\n\tif (f->map & (1 << rec)) {\n\t\tldm_error (\"Duplicate VBLK, part %d.\", rec);\n\t\tf->map &= 0x7F;\t\t\t/* Mark the group as broken */\n\t\treturn false;\n\t}\n\n\tf->map |= (1 << rec);\n\n\tdata += VBLK_SIZE_HEAD;\n\tsize -= VBLK_SIZE_HEAD;\n\n\tmemcpy (f->data+rec*(size-VBLK_SIZE_HEAD)+VBLK_SIZE_HEAD, data, size);\n\n\treturn true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix for buffer overflow in ldm_frag_add not sufficient\n\nAs Ben Hutchings discovered [1], the patch for CVE-2011-1017 (buffer\noverflow in ldm_frag_add) is not sufficient. The original patch in\ncommit c340b1d64000 (\"fs/partitions/ldm.c: fix oops caused by corrupted\npartition table\") does not consider that, for subsequent fragments,\npreviously allocated memory is used.\n\n[1] http://lkml.org/lkml/2011/5/6/407\n\nReported-by: Ben Hutchings \nSigned-off-by: Timo Warns \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 Compute(OpKernelContext* const context) override {\n // node_ids\n const Tensor* node_ids_t;\n OP_REQUIRES_OK(context, context->input(\"node_ids\", &node_ids_t));\n const auto node_ids = node_ids_t->vec();\n // gradients\n const Tensor* gradients_t;\n OP_REQUIRES_OK(context, context->input(\"gradients\", &gradients_t));\n const auto gradients = gradients_t->matrix();\n // hessians\n const Tensor* hessians_t;\n OP_REQUIRES_OK(context, context->input(\"hessians\", &hessians_t));\n const auto hessians = hessians_t->matrix();\n // bucketized_features\n OpInputList bucketized_features_list;\n OP_REQUIRES_OK(context, context->input_list(\"bucketized_features_list\",\n &bucketized_features_list));\n // Infer batch size.\n const int64_t batch_size = node_ids_t->dim_size(0);\n\n // Allocate temporary stats tensor (Rank 4).\n Tensor temp_stats_double_t;\n OP_REQUIRES_OK(context, context->allocate_temp(\n DT_DOUBLE,\n {num_features_, max_splits_, num_buckets_, 2},\n &temp_stats_double_t));\n auto temp_stats_double = temp_stats_double_t.tensor();\n temp_stats_double.setZero();\n\n // Partition by node, and then bucketize.\n for (int feature_idx = 0; feature_idx < num_features_; ++feature_idx) {\n const auto& features = bucketized_features_list[feature_idx].vec();\n for (int i = 0; i < batch_size; ++i) {\n const int32_t node = node_ids(i);\n const int32_t bucket = features(i);\n temp_stats_double(feature_idx, node, bucket, 0) += gradients(i, 0);\n temp_stats_double(feature_idx, node, bucket, 1) += hessians(i, 0);\n }\n }\n\n // Copy temp tensor over to output tensor.\n Tensor* output_stats_summary_t = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(\n \"stats_summary\", temp_stats_double_t.shape(),\n &output_stats_summary_t));\n output_stats_summary_t->tensor() =\n temp_stats_double.template cast();\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: int unit_name_path_escape(const char *f, char **ret) {\n char *p, *s;\n\n assert(f);\n assert(ret);\n\n p = strdupa(f);\n if (!p)\n return -ENOMEM;\n\n path_simplify(p);\n\n if (empty_or_root(p))\n s = strdup(\"-\");\n else {\n if (!path_is_normalized(p))\n return -EINVAL;\n\n /* Truncate trailing slashes */\n delete_trailing_chars(p, \"/\");\n\n /* Truncate leading slashes */\n p = skip_leading_chars(p, \"/\");\n\n s = unit_name_escape(p);\n }\n if (!s)\n return -ENOMEM;\n\n *ret = s;\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'basic/unit-name: do not use strdupa() on a path\n\nThe path may have unbounded length, for example through a fuse mount.\n\nCVE-2021-33910: attacked controlled alloca() leads to crash in systemd and\nultimately a kernel panic. Systemd parses the content of /proc/self/mountinfo\nand each mountpoint is passed to mount_setup_unit(), which calls\nunit_name_path_escape() underneath. A local attacker who is able to mount a\nfilesystem with a very long path can crash systemd and the whole system.\n\nhttps://bugzilla.redhat.com/show_bug.cgi?id=1970887\n\nThe resulting string length is bounded by UNIT_NAME_MAX, which is 256. But we\ncan't easily check the length after simplification before doing the\nsimplification, which in turns uses a copy of the string we can write to.\nSo we can't reject paths that are too long before doing the duplication.\nHence the most obvious solution is to switch back to strdup(), as before\n7410616cd9dbbec97cf98d75324da5cda2b2f7a2.\n\n(cherry picked from commit 441e0115646d54f080e5c3bb0ba477c892861ab9)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus ResizeOutputTensors(TfLiteContext* context, TfLiteNode* node,\n const TfLiteTensor* input,\n const TfLiteTensor* size_splits,\n const TfLiteTensor* axis) {\n int axis_value = GetTensorData(axis)[0];\n if (axis_value < 0) {\n axis_value += NumDimensions(input);\n }\n\n std::vector size_splits_vector;\n if (size_splits->type == kTfLiteInt32) {\n GetSizeSplitsVector(size_splits, &size_splits_vector);\n } else if (size_splits->type == kTfLiteInt64) {\n GetSizeSplitsVector(size_splits, &size_splits_vector);\n } else {\n context->ReportError(context, \"size_splits only support type int32|int64.\");\n return kTfLiteError;\n }\n\n int minus_one_index = -1;\n int64_t size_splits_sum = 0;\n\n for (int i = 0; i < size_splits_vector.size(); ++i) {\n if (size_splits_vector.at(i) == -1) {\n if (minus_one_index == -1) {\n minus_one_index = i;\n } else {\n context->ReportError(context,\n \"The size_splits contains more than one -1.\");\n }\n } else {\n size_splits_sum += size_splits_vector.at(i);\n }\n }\n\n const int input_size = SizeOfDimension(input, axis_value);\n\n if (minus_one_index != -1) {\n if (size_splits_sum > input_size) {\n context->ReportError(\n context,\n \"The sum of size_splits must be less than the dimension of value.\");\n } else {\n size_splits_vector[minus_one_index] = input_size - size_splits_sum;\n }\n } else if (size_splits_sum != input_size) {\n context->ReportError(\n context,\n \"The size_splits must sum to the dimension of value along axis.\");\n }\n\n for (int i = 0; i < NumOutputs(node); ++i) {\n TfLiteIntArray* output_dims = TfLiteIntArrayCopy(input->dims);\n output_dims->data[axis_value] = size_splits_vector.at(i);\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, i, &output));\n TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, output, output_dims));\n }\n\n return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Prevent array OOB read/write\n\nPiperOrigin-RevId: 371026165\nChange-Id: I26ac6372c87246e03c7eb8c94e84c84d86054b36'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (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_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb)\n{\n MpegEncContext *s = &ctx->m;\n int width, height, vo_ver_id;\n\n /* vol header */\n skip_bits(gb, 1); /* random access */\n s->vo_type = get_bits(gb, 8);\n if (get_bits1(gb) != 0) { /* is_ol_id */\n vo_ver_id = get_bits(gb, 4); /* vo_ver_id */\n skip_bits(gb, 3); /* vo_priority */\n } else {\n vo_ver_id = 1;\n }\n s->aspect_ratio_info = get_bits(gb, 4);\n if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {\n s->avctx->sample_aspect_ratio.num = get_bits(gb, 8); // par_width\n s->avctx->sample_aspect_ratio.den = get_bits(gb, 8); // par_height\n } else {\n s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info];\n }\n\n if ((s->vol_control_parameters = get_bits1(gb))) { /* vol control parameter */\n int chroma_format = get_bits(gb, 2);\n if (chroma_format != CHROMA_420)\n av_log(s->avctx, AV_LOG_ERROR, \"illegal chroma format\\n\");\n\n s->low_delay = get_bits1(gb);\n if (get_bits1(gb)) { /* vbv parameters */\n get_bits(gb, 15); /* first_half_bitrate */\n skip_bits1(gb); /* marker */\n get_bits(gb, 15); /* latter_half_bitrate */\n skip_bits1(gb); /* marker */\n get_bits(gb, 15); /* first_half_vbv_buffer_size */\n skip_bits1(gb); /* marker */\n get_bits(gb, 3); /* latter_half_vbv_buffer_size */\n get_bits(gb, 11); /* first_half_vbv_occupancy */\n skip_bits1(gb); /* marker */\n get_bits(gb, 15); /* latter_half_vbv_occupancy */\n skip_bits1(gb); /* marker */\n }\n } else {\n /* is setting low delay flag only once the smartest thing to do?\n * low delay detection won't be overriden. */\n if (s->picture_number == 0)\n s->low_delay = 0;\n }\n\n ctx->shape = get_bits(gb, 2); /* vol shape */\n if (ctx->shape != RECT_SHAPE)\n av_log(s->avctx, AV_LOG_ERROR, \"only rectangular vol supported\\n\");\n if (ctx->shape == GRAY_SHAPE && vo_ver_id != 1) {\n av_log(s->avctx, AV_LOG_ERROR, \"Gray shape not supported\\n\");\n skip_bits(gb, 4); /* video_object_layer_shape_extension */\n }\n\n check_marker(gb, \"before time_increment_resolution\");\n\n s->avctx->time_base.den = get_bits(gb, 16);\n if (!s->avctx->time_base.den) {\n av_log(s->avctx, AV_LOG_ERROR, \"time_base.den==0\\n\");\n s->avctx->time_base.num = 0;\n return -1;\n }\n\n ctx->time_increment_bits = av_log2(s->avctx->time_base.den - 1) + 1;\n if (ctx->time_increment_bits < 1)\n ctx->time_increment_bits = 1;\n\n check_marker(gb, \"before fixed_vop_rate\");\n\n if (get_bits1(gb) != 0) /* fixed_vop_rate */\n s->avctx->time_base.num = get_bits(gb, ctx->time_increment_bits);\n else\n s->avctx->time_base.num = 1;\n\n ctx->t_frame = 0;\n\n if (ctx->shape != BIN_ONLY_SHAPE) {\n if (ctx->shape == RECT_SHAPE) {\n check_marker(gb, \"before width\");\n width = get_bits(gb, 13);\n check_marker(gb, \"before height\");\n height = get_bits(gb, 13);\n check_marker(gb, \"after height\");\n if (width && height && /* they should be non zero but who knows */\n !(s->width && s->codec_tag == AV_RL32(\"MP4S\"))) {\n if (s->width && s->height &&\n (s->width != width || s->height != height))\n s->context_reinit = 1;\n s->width = width;\n s->height = height;\n }\n }\n\n s->progressive_sequence =\n s->progressive_frame = get_bits1(gb) ^ 1;\n s->interlaced_dct = 0;\n if (!get_bits1(gb) && (s->avctx->debug & FF_DEBUG_PICT_INFO))\n av_log(s->avctx, AV_LOG_INFO, /* OBMC Disable */\n \"MPEG4 OBMC not supported (very likely buggy encoder)\\n\");\n if (vo_ver_id == 1)\n ctx->vol_sprite_usage = get_bits1(gb); /* vol_sprite_usage */\n else\n ctx->vol_sprite_usage = get_bits(gb, 2); /* vol_sprite_usage */\n\n if (ctx->vol_sprite_usage == STATIC_SPRITE)\n av_log(s->avctx, AV_LOG_ERROR, \"Static Sprites not supported\\n\");\n if (ctx->vol_sprite_usage == STATIC_SPRITE ||\n ctx->vol_sprite_usage == GMC_SPRITE) {\n if (ctx->vol_sprite_usage == STATIC_SPRITE) {\n skip_bits(gb, 13); // sprite_width\n skip_bits1(gb); /* marker */\n skip_bits(gb, 13); // sprite_height\n skip_bits1(gb); /* marker */\n skip_bits(gb, 13); // sprite_left\n skip_bits1(gb); /* marker */\n skip_bits(gb, 13); // sprite_top\n skip_bits1(gb); /* marker */\n }\n ctx->num_sprite_warping_points = get_bits(gb, 6);\n if (ctx->num_sprite_warping_points > 3) {\n av_log(s->avctx, AV_LOG_ERROR,\n \"%d sprite_warping_points\\n\",\n ctx->num_sprite_warping_points);\n ctx->num_sprite_warping_points = 0;\n return -1;\n }\n s->sprite_warping_accuracy = get_bits(gb, 2);\n ctx->sprite_brightness_change = get_bits1(gb);\n if (ctx->vol_sprite_usage == STATIC_SPRITE)\n skip_bits1(gb); // low_latency_sprite\n }\n // FIXME sadct disable bit if verid!=1 && shape not rect\n\n if (get_bits1(gb) == 1) { /* not_8_bit */\n s->quant_precision = get_bits(gb, 4); /* quant_precision */\n if (get_bits(gb, 4) != 8) /* bits_per_pixel */\n av_log(s->avctx, AV_LOG_ERROR, \"N-bit not supported\\n\");\n if (s->quant_precision != 5)\n av_log(s->avctx, AV_LOG_ERROR,\n \"quant precision %d\\n\", s->quant_precision);\n if (s->quant_precision<3 || s->quant_precision>9) {\n s->quant_precision = 5;\n }\n } else {\n s->quant_precision = 5;\n }\n\n // FIXME a bunch of grayscale shape things\n\n if ((s->mpeg_quant = get_bits1(gb))) { /* vol_quant_type */\n int i, v;\n\n /* load default matrixes */\n for (i = 0; i < 64; i++) {\n int j = s->dsp.idct_permutation[i];\n v = ff_mpeg4_default_intra_matrix[i];\n s->intra_matrix[j] = v;\n s->chroma_intra_matrix[j] = v;\n\n v = ff_mpeg4_default_non_intra_matrix[i];\n s->inter_matrix[j] = v;\n s->chroma_inter_matrix[j] = v;\n }\n\n /* load custom intra matrix */\n if (get_bits1(gb)) {\n int last = 0;\n for (i = 0; i < 64; i++) {\n int j;\n v = get_bits(gb, 8);\n if (v == 0)\n break;\n\n last = v;\n j = s->dsp.idct_permutation[ff_zigzag_direct[i]];\n s->intra_matrix[j] = last;\n s->chroma_intra_matrix[j] = last;\n }\n\n /* replicate last value */\n for (; i < 64; i++) {\n int j = s->dsp.idct_permutation[ff_zigzag_direct[i]];\n s->intra_matrix[j] = last;\n s->chroma_intra_matrix[j] = last;\n }\n }\n\n /* load custom non intra matrix */\n if (get_bits1(gb)) {\n int last = 0;\n for (i = 0; i < 64; i++) {\n int j;\n v = get_bits(gb, 8);\n if (v == 0)\n break;\n\n last = v;\n j = s->dsp.idct_permutation[ff_zigzag_direct[i]];\n s->inter_matrix[j] = v;\n s->chroma_inter_matrix[j] = v;\n }\n\n /* replicate last value */\n for (; i < 64; i++) {\n int j = s->dsp.idct_permutation[ff_zigzag_direct[i]];\n s->inter_matrix[j] = last;\n s->chroma_inter_matrix[j] = last;\n }\n }\n\n // FIXME a bunch of grayscale shape things\n }\n\n if (vo_ver_id != 1)\n s->quarter_sample = get_bits1(gb);\n else\n s->quarter_sample = 0;\n\n if (!get_bits1(gb)) {\n int pos = get_bits_count(gb);\n int estimation_method = get_bits(gb, 2);\n if (estimation_method < 2) {\n if (!get_bits1(gb)) {\n ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* opaque */\n ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* transparent */\n ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_cae */\n ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* inter_cae */\n ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* no_update */\n ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* upampling */\n }\n if (!get_bits1(gb)) {\n ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_blocks */\n ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter_blocks */\n ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter4v_blocks */\n ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* not coded blocks */\n }\n if (!check_marker(gb, \"in complexity estimation part 1\")) {\n skip_bits_long(gb, pos - get_bits_count(gb));\n goto no_cplx_est;\n }\n if (!get_bits1(gb)) {\n ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_coeffs */\n ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_lines */\n ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* vlc_syms */\n ctx->cplx_estimation_trash_i += 4 * get_bits1(gb); /* vlc_bits */\n }\n if (!get_bits1(gb)) {\n ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* apm */\n ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* npm */\n ctx->cplx_estimation_trash_b += 8 * get_bits1(gb); /* interpolate_mc_q */\n ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* forwback_mc_q */\n ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel2 */\n ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel4 */\n }\n if (!check_marker(gb, \"in complexity estimation part 2\")) {\n skip_bits_long(gb, pos - get_bits_count(gb));\n goto no_cplx_est;\n }\n if (estimation_method == 1) {\n ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* sadct */\n ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* qpel */\n }\n } else\n av_log(s->avctx, AV_LOG_ERROR,\n \"Invalid Complexity estimation method %d\\n\",\n estimation_method);\n } else {\n\nno_cplx_est:\n ctx->cplx_estimation_trash_i =\n ctx->cplx_estimation_trash_p =\n ctx->cplx_estimation_trash_b = 0;\n }\n\n ctx->resync_marker = !get_bits1(gb); /* resync_marker_disabled */\n\n s->data_partitioning = get_bits1(gb);\n if (s->data_partitioning)\n ctx->rvlc = get_bits1(gb);\n\n if (vo_ver_id != 1) {\n ctx->new_pred = get_bits1(gb);\n if (ctx->new_pred) {\n av_log(s->avctx, AV_LOG_ERROR, \"new pred not supported\\n\");\n skip_bits(gb, 2); /* requested upstream message type */\n skip_bits1(gb); /* newpred segment type */\n }\n if (get_bits1(gb)) // reduced_res_vop\n av_log(s->avctx, AV_LOG_ERROR,\n \"reduced resolution VOP not supported\\n\");\n } else {\n ctx->new_pred = 0;\n }\n\n ctx->scalability = get_bits1(gb);\n\n if (ctx->scalability) {\n GetBitContext bak = *gb;\n int h_sampling_factor_n;\n int h_sampling_factor_m;\n int v_sampling_factor_n;\n int v_sampling_factor_m;\n\n skip_bits1(gb); // hierarchy_type\n skip_bits(gb, 4); /* ref_layer_id */\n skip_bits1(gb); /* ref_layer_sampling_dir */\n h_sampling_factor_n = get_bits(gb, 5);\n h_sampling_factor_m = get_bits(gb, 5);\n v_sampling_factor_n = get_bits(gb, 5);\n v_sampling_factor_m = get_bits(gb, 5);\n ctx->enhancement_type = get_bits1(gb);\n\n if (h_sampling_factor_n == 0 || h_sampling_factor_m == 0 ||\n v_sampling_factor_n == 0 || v_sampling_factor_m == 0) {\n /* illegal scalability header (VERY broken encoder),\n * trying to workaround */\n ctx->scalability = 0;\n *gb = bak;\n } else\n av_log(s->avctx, AV_LOG_ERROR, \"scalability not supported\\n\");\n\n // bin shape stuff FIXME\n }\n }\n\n if (s->avctx->debug&FF_DEBUG_PICT_INFO) {\n av_log(s->avctx, AV_LOG_DEBUG, \"tb %d/%d, tincrbits:%d, qp_prec:%d, ps:%d, %s%s%s%s\\n\",\n s->avctx->time_base.num, s->avctx->time_base.den,\n ctx->time_increment_bits,\n s->quant_precision,\n s->progressive_sequence,\n ctx->scalability ? \"scalability \" :\"\" , s->quarter_sample ? \"qpel \" : \"\",\n s->data_partitioning ? \"partition \" : \"\", ctx->rvlc ? \"rvlc \" : \"\"\n );\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'avcodec/mpeg4videodec: Check for bitstream overread in decode_vol_header()\n\nFixes out of array read\nFixes: 08e48e9daae7d8f8ab6dbe3919e797e5-asan_heap-oob_157461c_5295_cov_1266798650_firefing.mpg\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: void mm_release(struct task_struct *tsk, struct mm_struct *mm)\n{\n\tstruct completion *vfork_done = tsk->vfork_done;\n\n\t/* Get rid of any cached register state */\n\tdeactivate_mm(tsk, mm);\n\n\t/* notify parent sleeping on vfork() */\n\tif (vfork_done) {\n\t\ttsk->vfork_done = NULL;\n\t\tcomplete(vfork_done);\n\t}\n\n\t/*\n\t * If we're exiting normally, clear a user-space tid field if\n\t * requested. We leave this alone when dying by signal, to leave\n\t * the value intact in a core dump, and to save the unnecessary\n\t * trouble otherwise. Userland only wants this done for a sys_exit.\n\t */\n\tif (tsk->clear_child_tid\n\t && !(tsk->flags & PF_SIGNALED)\n\t && atomic_read(&mm->mm_users) > 1) {\n\t\tu32 __user * tidptr = tsk->clear_child_tid;\n\t\ttsk->clear_child_tid = NULL;\n\n\t\t/*\n\t\t * We don't check the error code - if userspace has\n\t\t * not set up a proper pointer then tough luck.\n\t\t */\n\t\tput_user(0, tidptr);\n\t\tsys_futex(tidptr, FUTEX_WAKE, 1, NULL, NULL, 0);\n\t}\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: AP_DECLARE(int) ap_process_request_internal(request_rec *r)\n{\n int file_req = (r->main && r->filename);\n int access_status;\n core_dir_config *d;\n\n /* Ignore embedded %2F's in path for proxy requests */\n if (!r->proxyreq && r->parsed_uri.path) {\n d = ap_get_core_module_config(r->per_dir_config);\n if (d->allow_encoded_slashes) {\n access_status = ap_unescape_url_keep2f(r->parsed_uri.path, d->decode_encoded_slashes);\n }\n else {\n access_status = ap_unescape_url(r->parsed_uri.path);\n }\n if (access_status) {\n if (access_status == HTTP_NOT_FOUND) {\n if (! d->allow_encoded_slashes) {\n ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00026)\n \"found %%2f (encoded '/') in URI \"\n \"(decoded='%s'), returning 404\",\n r->parsed_uri.path);\n }\n }\n return access_status;\n }\n }\n\n ap_getparents(r->uri); /* OK --- shrinking transformations... */\n\n /* All file subrequests are a huge pain... they cannot bubble through the\n * next several steps. Only file subrequests are allowed an empty uri,\n * otherwise let translate_name kill the request.\n */\n if (!file_req) {\n if ((access_status = ap_location_walk(r))) {\n return access_status;\n }\n if ((access_status = ap_if_walk(r))) {\n return access_status;\n }\n\n /* Don't set per-dir loglevel if LogLevelOverride is set */\n if (!r->connection->log) {\n d = ap_get_core_module_config(r->per_dir_config);\n if (d->log)\n r->log = d->log;\n }\n\n if ((access_status = ap_run_translate_name(r))) {\n return decl_die(access_status, \"translate\", r);\n }\n }\n\n /* Reset to the server default config prior to running map_to_storage\n */\n r->per_dir_config = r->server->lookup_defaults;\n\n if ((access_status = ap_run_map_to_storage(r))) {\n /* This request wasn't in storage (e.g. TRACE) */\n return access_status;\n }\n\n /* Rerun the location walk, which overrides any map_to_storage config.\n */\n if ((access_status = ap_location_walk(r))) {\n return access_status;\n }\n if ((access_status = ap_if_walk(r))) {\n return access_status;\n }\n\n /* Don't set per-dir loglevel if LogLevelOverride is set */\n if (!r->connection->log) {\n d = ap_get_core_module_config(r->per_dir_config);\n if (d->log)\n r->log = d->log;\n }\n\n if ((access_status = ap_run_post_perdir_config(r))) {\n return access_status;\n }\n\n /* Only on the main request! */\n if (r->main == NULL) {\n if ((access_status = ap_run_header_parser(r))) {\n return access_status;\n }\n }\n\n /* Skip authn/authz if the parent or prior request passed the authn/authz,\n * and that configuration didn't change (this requires optimized _walk()\n * functions in map_to_storage that use the same merge results given\n * identical input.) If the config changes, we must re-auth.\n */\n if (r->prev && (r->prev->per_dir_config == r->per_dir_config)) {\n r->user = r->prev->user;\n r->ap_auth_type = r->prev->ap_auth_type;\n }\n else if (r->main && (r->main->per_dir_config == r->per_dir_config)) {\n r->user = r->main->user;\n r->ap_auth_type = r->main->ap_auth_type;\n }\n else {\n switch (ap_satisfies(r)) {\n case SATISFY_ALL:\n case SATISFY_NOSPEC:\n if ((access_status = ap_run_access_checker(r)) != OK) {\n return decl_die(access_status,\n \"check access (with Satisfy All)\", r);\n }\n\n access_status = ap_run_access_checker_ex(r);\n if (access_status == OK) {\n ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r,\n \"request authorized without authentication by \"\n \"access_checker_ex hook: %s\", r->uri);\n }\n else if (access_status != DECLINED) {\n return decl_die(access_status, \"check access\", r);\n }\n else {\n if ((access_status = ap_run_check_user_id(r)) != OK) {\n return decl_die(access_status, \"check user\", r);\n }\n if (r->user == NULL) {\n /* don't let buggy authn module crash us in authz */\n ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00027)\n \"No authentication done but request not \"\n \"allowed without authentication for %s. \"\n \"Authentication not configured?\",\n r->uri);\n access_status = HTTP_INTERNAL_SERVER_ERROR;\n return decl_die(access_status, \"check user\", r);\n }\n if ((access_status = ap_run_auth_checker(r)) != OK) {\n return decl_die(access_status, \"check authorization\", r);\n }\n }\n break;\n case SATISFY_ANY:\n if ((access_status = ap_run_access_checker(r)) == OK) {\n ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r,\n \"request authorized without authentication by \"\n \"access_checker hook and 'Satisfy any': %s\",\n r->uri);\n break;\n }\n\n access_status = ap_run_access_checker_ex(r);\n if (access_status == OK) {\n ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r,\n \"request authorized without authentication by \"\n \"access_checker_ex hook: %s\", r->uri);\n }\n else if (access_status != DECLINED) {\n return decl_die(access_status, \"check access\", r);\n }\n else {\n if ((access_status = ap_run_check_user_id(r)) != OK) {\n return decl_die(access_status, \"check user\", r);\n }\n if (r->user == NULL) {\n /* don't let buggy authn module crash us in authz */\n ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00028)\n \"No authentication done but request not \"\n \"allowed without authentication for %s. \"\n \"Authentication not configured?\",\n r->uri);\n access_status = HTTP_INTERNAL_SERVER_ERROR;\n return decl_die(access_status, \"check user\", r);\n }\n if ((access_status = ap_run_auth_checker(r)) != OK) {\n return decl_die(access_status, \"check authorization\", r);\n }\n }\n break;\n }\n }\n /* XXX Must make certain the ap_run_type_checker short circuits mime\n * in mod-proxy for r->proxyreq && r->parsed_uri.scheme\n * && !strcmp(r->parsed_uri.scheme, \"http\")\n */\n if ((access_status = ap_run_type_checker(r)) != OK) {\n return decl_die(access_status, \"find types\", r);\n }\n\n if ((access_status = ap_run_fixups(r)) != OK) {\n ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r, \"fixups hook gave %d: %s\",\n access_status, r->uri);\n return access_status;\n }\n\n return OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'SECURITY: CVE-2015-3185 (cve.mitre.org)\n\nReplacement of ap_some_auth_required (unusable in Apache httpd 2.4)\nwith new ap_some_authn_required and ap_force_authn hook.\n\nSubmitted by: breser\n\n\ngit-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1684524 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: isis_print_extd_ip_reach(netdissect_options *ndo,\n const uint8_t *tptr, const char *ident, uint16_t afi)\n{\n char ident_buffer[20];\n uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */\n u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen;\n\n if (!ND_TTEST2(*tptr, 4))\n return (0);\n metric = EXTRACT_32BITS(tptr);\n processed=4;\n tptr+=4;\n\n if (afi == AF_INET) {\n if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */\n return (0);\n status_byte=*(tptr++);\n bit_length = status_byte&0x3f;\n if (bit_length > 32) {\n ND_PRINT((ndo, \"%sIPv4 prefix: bad bit length %u\",\n ident,\n bit_length));\n return (0);\n }\n processed++;\n } else if (afi == AF_INET6) {\n if (!ND_TTEST2(*tptr, 1)) /* fetch status & prefix_len byte */\n return (0);\n status_byte=*(tptr++);\n bit_length=*(tptr++);\n if (bit_length > 128) {\n ND_PRINT((ndo, \"%sIPv6 prefix: bad bit length %u\",\n ident,\n bit_length));\n return (0);\n }\n processed+=2;\n } else\n return (0); /* somebody is fooling us */\n\n byte_length = (bit_length + 7) / 8; /* prefix has variable length encoding */\n\n if (!ND_TTEST2(*tptr, byte_length))\n return (0);\n memset(prefix, 0, sizeof prefix); /* clear the copy buffer */\n memcpy(prefix,tptr,byte_length); /* copy as much as is stored in the TLV */\n tptr+=byte_length;\n processed+=byte_length;\n\n if (afi == AF_INET)\n ND_PRINT((ndo, \"%sIPv4 prefix: %15s/%u\",\n ident,\n ipaddr_string(ndo, prefix),\n bit_length));\n else if (afi == AF_INET6)\n ND_PRINT((ndo, \"%sIPv6 prefix: %s/%u\",\n ident,\n ip6addr_string(ndo, prefix),\n bit_length));\n\n ND_PRINT((ndo, \", Distribution: %s, Metric: %u\",\n ISIS_MASK_TLV_EXTD_IP_UPDOWN(status_byte) ? \"down\" : \"up\",\n metric));\n\n if (afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte))\n ND_PRINT((ndo, \", sub-TLVs present\"));\n else if (afi == AF_INET6)\n ND_PRINT((ndo, \", %s%s\",\n ISIS_MASK_TLV_EXTD_IP6_IE(status_byte) ? \"External\" : \"Internal\",\n ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte) ? \", sub-TLVs present\" : \"\"));\n\n if ((afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte))\n || (afi == AF_INET6 && ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte))\n\t) {\n /* assume that one prefix can hold more\n than one subTLV - therefore the first byte must reflect\n the aggregate bytecount of the subTLVs for this prefix\n */\n if (!ND_TTEST2(*tptr, 1))\n return (0);\n sublen=*(tptr++);\n processed+=sublen+1;\n ND_PRINT((ndo, \" (%u)\", sublen)); /* print out subTLV length */\n\n while (sublen>0) {\n if (!ND_TTEST2(*tptr,2))\n return (0);\n subtlvtype=*(tptr++);\n subtlvlen=*(tptr++);\n /* prepend the indent string */\n snprintf(ident_buffer, sizeof(ident_buffer), \"%s \",ident);\n if (!isis_print_ip_reach_subtlv(ndo, tptr, subtlvtype, subtlvlen, ident_buffer))\n return(0);\n tptr+=subtlvlen;\n sublen-=(subtlvlen+2);\n }\n }\n return (processed);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-12998/IS-IS: Check for 2 bytes if we're going to fetch 2 bytes.\n\nProbably a copy-and-pasteo.\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: static int l2tp_ip6_recvmsg(struct kiocb *iocb, struct sock *sk,\n\t\t\t struct msghdr *msg, size_t len, int noblock,\n\t\t\t int flags, int *addr_len)\n{\n\tstruct ipv6_pinfo *np = inet6_sk(sk);\n\tstruct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)msg->msg_name;\n\tsize_t copied = 0;\n\tint err = -EOPNOTSUPP;\n\tstruct sk_buff *skb;\n\n\tif (flags & MSG_OOB)\n\t\tgoto out;\n\n\tif (addr_len)\n\t\t*addr_len = sizeof(*lsa);\n\n\tif (flags & MSG_ERRQUEUE)\n\t\treturn ipv6_recv_error(sk, msg, len);\n\n\tskb = skb_recv_datagram(sk, flags, noblock, &err);\n\tif (!skb)\n\t\tgoto out;\n\n\tcopied = skb->len;\n\tif (len < copied) {\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t\tcopied = len;\n\t}\n\n\terr = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\tif (err)\n\t\tgoto done;\n\n\tsock_recv_timestamp(msg, sk, skb);\n\n\t/* Copy the address. */\n\tif (lsa) {\n\t\tlsa->l2tp_family = AF_INET6;\n\t\tlsa->l2tp_unused = 0;\n\t\tlsa->l2tp_addr = ipv6_hdr(skb)->saddr;\n\t\tlsa->l2tp_flowinfo = 0;\n\t\tlsa->l2tp_scope_id = 0;\n\t\tif (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL)\n\t\t\tlsa->l2tp_scope_id = IP6CB(skb)->iif;\n\t}\n\n\tif (np->rxopt.all)\n\t\tip6_datagram_recv_ctl(sk, msg, skb);\n\n\tif (flags & MSG_TRUNC)\n\t\tcopied = skb->len;\ndone:\n\tskb_free_datagram(sk, skb);\nout:\n\treturn err ? err : copied;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'l2tp: fix info leak in l2tp_ip6_recvmsg()\n\nThe L2TP code for IPv6 fails to initialize the l2tp_conn_id member of\nstruct sockaddr_l2tpip6 and therefore leaks four bytes kernel stack\nin l2tp_ip6_recvmsg() in case msg_name is set.\n\nInitialize l2tp_conn_id with 0 to avoid the info leak.\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: static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)\n{\n\tu32 exit_intr_info;\n\n\tif (!(vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY\n\t || vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI))\n\t\treturn;\n\n\tvmx->exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);\n\texit_intr_info = vmx->exit_intr_info;\n\n\t/* Handle machine checks before interrupts are enabled */\n\tif (is_machine_check(exit_intr_info))\n\t\tkvm_machine_check();\n\n\t/* We need to handle NMIs before interrupts are enabled */\n\tif ((exit_intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR &&\n\t (exit_intr_info & INTR_INFO_VALID_MASK)) {\n\t\tkvm_before_handle_nmi(&vmx->vcpu);\n\t\tasm(\"int $2\");\n\t\tkvm_after_handle_nmi(&vmx->vcpu);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-388'], 'message': 'kvm: nVMX: Allow L1 to intercept software exceptions (#BP and #OF)\n\nWhen L2 exits to L0 due to \"exception or NMI\", software exceptions\n(#BP and #OF) for which L1 has requested an intercept should be\nhandled by L1 rather than L0. Previously, only hardware exceptions\nwere forwarded to L1.\n\nSigned-off-by: Jim Mattson \nCc: stable@vger.kernel.org\nSigned-off-by: Paolo Bonzini '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: tgs_build_reply(krb5_context context,\n\t\tkrb5_kdc_configuration *config,\n\t\tKDC_REQ *req,\n\t\tKDC_REQ_BODY *b,\n\t\thdb_entry_ex *krbtgt,\n\t\tkrb5_enctype krbtgt_etype,\n\t\tconst krb5_keyblock *replykey,\n\t\tint rk_is_subkey,\n\t\tkrb5_ticket *ticket,\n\t\tkrb5_data *reply,\n\t\tconst char *from,\n\t\tconst char **e_text,\n\t\tAuthorizationData **auth_data,\n\t\tconst struct sockaddr *from_addr)\n{\n krb5_error_code ret;\n krb5_principal cp = NULL, sp = NULL, rsp = NULL, tp = NULL, dp = NULL;\n krb5_principal krbtgt_out_principal = NULL;\n char *spn = NULL, *cpn = NULL, *tpn = NULL, *dpn = NULL, *krbtgt_out_n = NULL;\n hdb_entry_ex *server = NULL, *client = NULL, *s4u2self_impersonated_client = NULL;\n HDB *clientdb, *s4u2self_impersonated_clientdb;\n krb5_realm ref_realm = NULL;\n EncTicketPart *tgt = &ticket->ticket;\n krb5_principals spp = NULL;\n const EncryptionKey *ekey;\n krb5_keyblock sessionkey;\n krb5_kvno kvno;\n krb5_data rspac;\n const char *our_realm = /* Realm of this KDC */\n krb5_principal_get_comp_string(context, krbtgt->entry.principal, 1);\n char **capath = NULL;\n size_t num_capath = 0;\n\n hdb_entry_ex *krbtgt_out = NULL;\n\n METHOD_DATA enc_pa_data;\n\n PrincipalName *s;\n Realm r;\n EncTicketPart adtkt;\n char opt_str[128];\n int signedpath = 0;\n\n Key *tkey_check;\n Key *tkey_sign;\n int flags = HDB_F_FOR_TGS_REQ;\n\n memset(&sessionkey, 0, sizeof(sessionkey));\n memset(&adtkt, 0, sizeof(adtkt));\n krb5_data_zero(&rspac);\n memset(&enc_pa_data, 0, sizeof(enc_pa_data));\n\n s = b->sname;\n r = b->realm;\n\n /* \n * Always to do CANON, see comment below about returned server principal (rsp).\n */\n flags |= HDB_F_CANON;\n\n if(b->kdc_options.enc_tkt_in_skey){\n\tTicket *t;\n\thdb_entry_ex *uu;\n\tkrb5_principal p;\n\tKey *uukey;\n\tkrb5uint32 second_kvno = 0;\n\tkrb5uint32 *kvno_ptr = NULL;\n\n\tif(b->additional_tickets == NULL ||\n\t b->additional_tickets->len == 0){\n\t ret = KRB5KDC_ERR_BADOPTION; /* ? */\n\t kdc_log(context, config, 0,\n\t\t \"No second ticket present in request\");\n\t goto out;\n\t}\n\tt = &b->additional_tickets->val[0];\n\tif(!get_krbtgt_realm(&t->sname)){\n\t kdc_log(context, config, 0,\n\t\t \"Additional ticket is not a ticket-granting ticket\");\n\t ret = KRB5KDC_ERR_POLICY;\n\t goto out;\n\t}\n\t_krb5_principalname2krb5_principal(context, &p, t->sname, t->realm);\n\tif(t->enc_part.kvno){\n\t second_kvno = *t->enc_part.kvno;\n\t kvno_ptr = &second_kvno;\n\t}\n\tret = _kdc_db_fetch(context, config, p,\n\t\t\t HDB_F_GET_KRBTGT, kvno_ptr,\n\t\t\t NULL, &uu);\n\tkrb5_free_principal(context, p);\n\tif(ret){\n\t if (ret == HDB_ERR_NOENTRY)\n\t\tret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;\n\t goto out;\n\t}\n\tret = hdb_enctype2key(context, &uu->entry, NULL,\n\t\t\t t->enc_part.etype, &uukey);\n\tif(ret){\n\t _kdc_free_ent(context, uu);\n\t ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */\n\t goto out;\n\t}\n\tret = krb5_decrypt_ticket(context, t, &uukey->key, &adtkt, 0);\n\t_kdc_free_ent(context, uu);\n\tif(ret)\n\t goto out;\n\n\tret = verify_flags(context, config, &adtkt, spn);\n\tif (ret)\n\t goto out;\n\n\ts = &adtkt.cname;\n\tr = adtkt.crealm;\n }\n\n _krb5_principalname2krb5_principal(context, &sp, *s, r);\n ret = krb5_unparse_name(context, sp, &spn);\n if (ret)\n\tgoto out;\n _krb5_principalname2krb5_principal(context, &cp, tgt->cname, tgt->crealm);\n ret = krb5_unparse_name(context, cp, &cpn);\n if (ret)\n\tgoto out;\n unparse_flags (KDCOptions2int(b->kdc_options),\n\t\t asn1_KDCOptions_units(),\n\t\t opt_str, sizeof(opt_str));\n if(*opt_str)\n\tkdc_log(context, config, 0,\n\t\t\"TGS-REQ %s from %s for %s [%s]\",\n\t\tcpn, from, spn, opt_str);\n else\n\tkdc_log(context, config, 0,\n\t\t\"TGS-REQ %s from %s for %s\", cpn, from, spn);\n\n /*\n * Fetch server\n */\n\nserver_lookup:\n ret = _kdc_db_fetch(context, config, sp, HDB_F_GET_SERVER | flags,\n\t\t\tNULL, NULL, &server);\n\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\", sp);\n\tgoto out;\n } else if (ret == HDB_ERR_WRONG_REALM) {\n free(ref_realm);\n\tref_realm = strdup(server->entry.principal->realm);\n\tif (ref_realm == NULL) {\n ret = krb5_enomem(context);\n\t goto out;\n\t}\n\n\tkdc_log(context, config, 5,\n\t\t\"Returning a referral to realm %s for \"\n\t\t\"server %s.\",\n\t\tref_realm, spn);\n\tkrb5_free_principal(context, sp);\n\tsp = NULL;\n\tret = krb5_make_principal(context, &sp, r, KRB5_TGS_NAME,\n\t\t\t\t ref_realm, NULL);\n\tif (ret)\n\t goto out;\n\tfree(spn);\n spn = NULL;\n\tret = krb5_unparse_name(context, sp, &spn);\n\tif (ret)\n\t goto out;\n\n\tgoto server_lookup;\n } else if (ret) {\n\tconst char *new_rlm, *msg;\n\tRealm req_rlm;\n\tkrb5_realm *realms;\n\n\tif ((req_rlm = get_krbtgt_realm(&sp->name)) != NULL) {\n if (capath == NULL) {\n /* With referalls, hierarchical capaths are always enabled */\n ret = _krb5_find_capath(context, tgt->crealm, our_realm,\n req_rlm, TRUE, &capath, &num_capath);\n if (ret)\n goto out;\n }\n new_rlm = num_capath > 0 ? capath[--num_capath] : NULL;\n if (new_rlm) {\n kdc_log(context, config, 5, \"krbtgt from %s via %s for \"\n \"realm %s not found, trying %s\", tgt->crealm,\n our_realm, req_rlm, new_rlm);\n\n free(ref_realm);\n ref_realm = strdup(new_rlm);\n if (ref_realm == NULL) {\n ret = krb5_enomem(context);\n goto out;\n }\n\n krb5_free_principal(context, sp);\n sp = NULL;\n krb5_make_principal(context, &sp, r,\n KRB5_TGS_NAME, ref_realm, NULL);\n free(spn);\n spn = NULL;\n ret = krb5_unparse_name(context, sp, &spn);\n if (ret)\n goto out;\n goto server_lookup;\n }\n\t} else if (need_referral(context, config, &b->kdc_options, sp, &realms)) {\n\t if (strcmp(realms[0], sp->realm) != 0) {\n\t\tkdc_log(context, config, 5,\n\t\t\t\"Returning a referral to realm %s for \"\n\t\t\t\"server %s that was not found\",\n\t\t\trealms[0], spn);\n\t\tkrb5_free_principal(context, sp);\n sp = NULL;\n\t\tkrb5_make_principal(context, &sp, r, KRB5_TGS_NAME,\n\t\t\t\t realms[0], NULL);\n\t\tfree(spn);\n spn = NULL;\n\t\tret = krb5_unparse_name(context, sp, &spn);\n\t\tif (ret) {\n\t\t krb5_free_host_realm(context, realms);\n\t\t goto out;\n\t\t}\n\n free(ref_realm);\n\t\tref_realm = strdup(realms[0]);\n\n\t\tkrb5_free_host_realm(context, realms);\n\t\tgoto server_lookup;\n\t }\n\t krb5_free_host_realm(context, realms);\n\t}\n\tmsg = krb5_get_error_message(context, ret);\n\tkdc_log(context, config, 0,\n\t\t\"Server not found in database: %s: %s\", spn, msg);\n\tkrb5_free_error_message(context, msg);\n\tif (ret == HDB_ERR_NOENTRY)\n\t ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;\n\tgoto out;\n }\n\n /* the name returned to the client depend on what was asked for,\n * return canonical name if kdc_options.canonicalize was set, the\n * client wants the true name of the principal, if not it just\n * wants the name its asked for.\n */\n\n if (b->kdc_options.canonicalize)\n\trsp = server->entry.principal;\n else\n\trsp = sp;\n\n\n /*\n * Select enctype, return key and kvno.\n */\n\n {\n\tkrb5_enctype etype;\n\n\tif(b->kdc_options.enc_tkt_in_skey) {\n\t size_t i;\n\t ekey = &adtkt.key;\n\t for(i = 0; i < b->etype.len; i++)\n\t\tif (b->etype.val[i] == adtkt.key.keytype)\n\t\t break;\n\t if(i == b->etype.len) {\n\t\tkdc_log(context, config, 0,\n\t\t\t\"Addition ticket have not matching etypes\");\n\t\tkrb5_clear_error_message(context);\n\t\tret = KRB5KDC_ERR_ETYPE_NOSUPP;\n\t\tgoto out;\n\t }\n\t etype = b->etype.val[i];\n\t kvno = 0;\n\t} else {\n\t Key *skey;\n\n\t ret = _kdc_find_etype(context,\n\t\t\t\t krb5_principal_is_krbtgt(context, sp) ?\n\t\t\t\t config->tgt_use_strongest_session_key :\n\t\t\t\t config->svc_use_strongest_session_key, FALSE,\n\t\t\t\t server, b->etype.val, b->etype.len, &etype,\n\t\t\t\t NULL);\n\t if(ret) {\n\t\tkdc_log(context, config, 0,\n\t\t\t\"Server (%s) has no support for etypes\", spn);\n\t\tgoto out;\n\t }\n\t ret = _kdc_get_preferred_key(context, config, server, spn,\n\t\t\t\t\t NULL, &skey);\n\t if(ret) {\n\t\tkdc_log(context, config, 0,\n\t\t\t\"Server (%s) has no supported etypes\", spn);\n\t\tgoto out;\n\t }\n\t ekey = &skey->key;\n\t kvno = server->entry.kvno;\n\t}\n\n\tret = krb5_generate_random_keyblock(context, etype, &sessionkey);\n\tif (ret)\n\t goto out;\n }\n\n /*\n * Check that service is in the same realm as the krbtgt. If it's\n * not the same, it's someone that is using a uni-directional trust\n * backward.\n */\n\n /*\n * Validate authoriation data\n */\n\n ret = hdb_enctype2key(context, &krbtgt->entry, NULL, /* XXX use the right kvno! */\n\t\t\t krbtgt_etype, &tkey_check);\n if(ret) {\n\tkdc_log(context, config, 0,\n\t\t \"Failed to find key for krbtgt PAC check\");\n\tgoto out;\n }\n\n /* \n * Now refetch the primary krbtgt, and get the current kvno (the\n * sign check may have been on an old kvno, and the server may\n * have been an incoming trust)\n */\n \n ret = krb5_make_principal(context,\n &krbtgt_out_principal,\n our_realm,\n KRB5_TGS_NAME,\n our_realm,\n NULL);\n if (ret) {\n kdc_log(context, config, 0,\n \"Failed to make krbtgt principal name object for \"\n \"authz-data signatures\");\n goto out;\n }\n ret = krb5_unparse_name(context, krbtgt_out_principal, &krbtgt_out_n);\n if (ret) {\n kdc_log(context, config, 0,\n \"Failed to make krbtgt principal name object for \"\n \"authz-data signatures\");\n goto out;\n }\n\n ret = _kdc_db_fetch(context, config, krbtgt_out_principal,\n\t\t\tHDB_F_GET_KRBTGT, NULL, NULL, &krbtgt_out);\n if (ret) {\n\tchar *ktpn = NULL;\n\tret = krb5_unparse_name(context, krbtgt->entry.principal, &ktpn);\n\tkdc_log(context, config, 0,\n\t\t\"No such principal %s (needed for authz-data signature keys) \"\n\t\t\"while processing TGS-REQ for service %s with krbtg %s\",\n\t\tkrbtgt_out_n, spn, (ret == 0) ? ktpn : \"\");\n\tfree(ktpn);\n\tret = KRB5KRB_AP_ERR_NOT_US;\n\tgoto out;\n }\n\n /* \n * The first realm is the realm of the service, the second is\n * krbtgt//@REALM component of the krbtgt DN the request was\n * encrypted to. The redirection via the krbtgt_out entry allows\n * the DB to possibly correct the case of the realm (Samba4 does\n * this) before the strcmp() \n */\n if (strcmp(krb5_principal_get_realm(context, server->entry.principal),\n\t krb5_principal_get_realm(context, krbtgt_out->entry.principal)) != 0) {\n\tchar *ktpn;\n\tret = krb5_unparse_name(context, krbtgt_out->entry.principal, &ktpn);\n\tkdc_log(context, config, 0,\n\t\t\"Request with wrong krbtgt: %s\",\n\t\t(ret == 0) ? ktpn : \"\");\n\tif(ret == 0)\n\t free(ktpn);\n\tret = KRB5KRB_AP_ERR_NOT_US;\n\tgoto out;\n }\n\n ret = _kdc_get_preferred_key(context, config, krbtgt_out, krbtgt_out_n,\n\t\t\t\t NULL, &tkey_sign);\n if (ret) {\n\tkdc_log(context, config, 0,\n\t\t \"Failed to find key for krbtgt PAC signature\");\n\tgoto out;\n }\n ret = hdb_enctype2key(context, &krbtgt_out->entry, NULL,\n\t\t\t tkey_sign->key.keytype, &tkey_sign);\n if(ret) {\n\tkdc_log(context, config, 0,\n\t\t \"Failed to find key for krbtgt PAC signature\");\n\tgoto out;\n }\n\n ret = _kdc_db_fetch(context, config, cp, HDB_F_GET_CLIENT | flags,\n\t\t\tNULL, &clientdb, &client);\n if(ret == HDB_ERR_NOT_FOUND_HERE) {\n\t/* This is OK, we are just trying to find out if they have\n\t * been disabled or deleted in the meantime, missing secrets\n\t * is OK */\n } else if(ret){\n\tconst char *krbtgt_realm, *msg;\n\n\t/*\n\t * If the client belongs to the same realm as our krbtgt, it\n\t * should exist in the local database.\n\t *\n\t */\n\n\tkrbtgt_realm = krb5_principal_get_realm(context, krbtgt_out->entry.principal);\n\n\tif(strcmp(krb5_principal_get_realm(context, cp), krbtgt_realm) == 0) {\n\t if (ret == HDB_ERR_NOENTRY)\n\t\tret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;\n\t kdc_log(context, config, 1, \"Client no longer in database: %s\",\n\t\t cpn);\n\t goto out;\n\t}\n\n\tmsg = krb5_get_error_message(context, ret);\n\tkdc_log(context, config, 1, \"Client not found in database: %s\", msg);\n\tkrb5_free_error_message(context, msg);\n }\n\n ret = check_PAC(context, config, cp, NULL,\n\t\t client, server, krbtgt,\n\t\t &tkey_check->key,\n\t\t ekey, &tkey_sign->key,\n\t\t tgt, &rspac, &signedpath);\n if (ret) {\n\tconst char *msg = krb5_get_error_message(context, ret);\n\tkdc_log(context, config, 0,\n\t\t\"Verify PAC failed for %s (%s) from %s with %s\",\n\t\tspn, cpn, from, msg);\n\tkrb5_free_error_message(context, msg);\n\tgoto out;\n }\n\n /* also check the krbtgt for signature */\n ret = check_KRB5SignedPath(context,\n\t\t\t config,\n\t\t\t krbtgt,\n\t\t\t cp,\n\t\t\t tgt,\n\t\t\t &spp,\n\t\t\t &signedpath);\n if (ret) {\n\tconst char *msg = krb5_get_error_message(context, ret);\n\tkdc_log(context, config, 0,\n\t\t\"KRB5SignedPath check failed for %s (%s) from %s with %s\",\n\t\tspn, cpn, from, msg);\n\tkrb5_free_error_message(context, msg);\n\tgoto out;\n }\n\n /*\n * Process request\n */\n\n /* by default the tgt principal matches the client principal */\n tp = cp;\n tpn = cpn;\n\n if (client) {\n\tconst PA_DATA *sdata;\n\tint i = 0;\n\n\tsdata = _kdc_find_padata(req, &i, KRB5_PADATA_FOR_USER);\n\tif (sdata) {\n\t krb5_crypto crypto;\n\t krb5_data datack;\n\t PA_S4U2Self self;\n\t const char *str;\n\n\t ret = decode_PA_S4U2Self(sdata->padata_value.data,\n\t\t\t\t sdata->padata_value.length,\n\t\t\t\t &self, NULL);\n\t if (ret) {\n\t\tkdc_log(context, config, 0, \"Failed to decode PA-S4U2Self\");\n\t\tgoto out;\n\t }\n\n\t ret = _krb5_s4u2self_to_checksumdata(context, &self, &datack);\n\t if (ret)\n\t\tgoto out;\n\n\t ret = krb5_crypto_init(context, &tgt->key, 0, &crypto);\n\t if (ret) {\n\t\tconst char *msg = krb5_get_error_message(context, ret);\n\t\tfree_PA_S4U2Self(&self);\n\t\tkrb5_data_free(&datack);\n\t\tkdc_log(context, config, 0, \"krb5_crypto_init failed: %s\", msg);\n\t\tkrb5_free_error_message(context, msg);\n\t\tgoto out;\n\t }\n\n\t ret = krb5_verify_checksum(context,\n\t\t\t\t crypto,\n\t\t\t\t KRB5_KU_OTHER_CKSUM,\n\t\t\t\t datack.data,\n\t\t\t\t datack.length,\n\t\t\t\t &self.cksum);\n\t krb5_data_free(&datack);\n\t krb5_crypto_destroy(context, crypto);\n\t if (ret) {\n\t\tconst char *msg = krb5_get_error_message(context, ret);\n\t\tfree_PA_S4U2Self(&self);\n\t\tkdc_log(context, config, 0,\n\t\t\t\"krb5_verify_checksum failed for S4U2Self: %s\", msg);\n\t\tkrb5_free_error_message(context, msg);\n\t\tgoto out;\n\t }\n\n\t ret = _krb5_principalname2krb5_principal(context,\n\t\t\t\t\t\t &tp,\n\t\t\t\t\t\t self.name,\n\t\t\t\t\t\t self.realm);\n\t free_PA_S4U2Self(&self);\n\t if (ret)\n\t\tgoto out;\n\n\t ret = krb5_unparse_name(context, tp, &tpn);\n\t if (ret)\n\t\tgoto out;\n\n\t /* If we were about to put a PAC into the ticket, we better fix it to be the right PAC */\n\t if(rspac.data) {\n\t\tkrb5_pac p = NULL;\n\t\tkrb5_data_free(&rspac);\n\t\tret = _kdc_db_fetch(context, config, tp, HDB_F_GET_CLIENT | flags,\n\t\t\t\t NULL, &s4u2self_impersonated_clientdb, &s4u2self_impersonated_client);\n\t\tif (ret) {\n\t\t const char *msg;\n\n\t\t /*\n\t\t * If the client belongs to the same realm as our krbtgt, it\n\t\t * should exist in the local database.\n\t\t *\n\t\t */\n\n\t\t if (ret == HDB_ERR_NOENTRY)\n\t\t\tret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;\n\t\t msg = krb5_get_error_message(context, ret);\n\t\t kdc_log(context, config, 1,\n\t\t\t \"S2U4Self principal to impersonate %s not found in database: %s\",\n\t\t\t tpn, msg);\n\t\t krb5_free_error_message(context, msg);\n\t\t goto out;\n\t\t}\n\t\tret = _kdc_pac_generate(context, s4u2self_impersonated_client, &p);\n\t\tif (ret) {\n\t\t kdc_log(context, config, 0, \"PAC generation failed for -- %s\",\n\t\t\t tpn);\n\t\t goto out;\n\t\t}\n\t\tif (p != NULL) {\n\t\t ret = _krb5_pac_sign(context, p, ticket->ticket.authtime,\n\t\t\t\t\t s4u2self_impersonated_client->entry.principal,\n\t\t\t\t\t ekey, &tkey_sign->key,\n\t\t\t\t\t &rspac);\n\t\t krb5_pac_free(context, p);\n\t\t if (ret) {\n\t\t\tkdc_log(context, config, 0, \"PAC signing failed for -- %s\",\n\t\t\t\ttpn);\n\t\t\tgoto out;\n\t\t }\n\t\t}\n\t }\n\n\t /*\n\t * Check that service doing the impersonating is\n\t * requesting a ticket to it-self.\n\t */\n\t ret = check_s4u2self(context, config, clientdb, client, sp);\n\t if (ret) {\n\t\tkdc_log(context, config, 0, \"S4U2Self: %s is not allowed \"\n\t\t\t\"to impersonate to service \"\n\t\t\t\"(tried for user %s to service %s)\",\n\t\t\tcpn, tpn, spn);\n\t\tgoto out;\n\t }\n\n\t /*\n\t * If the service isn't trusted for authentication to\n\t * delegation, remove the forward flag.\n\t */\n\n\t if (client->entry.flags.trusted_for_delegation) {\n\t\tstr = \"[forwardable]\";\n\t } else {\n\t\tb->kdc_options.forwardable = 0;\n\t\tstr = \"\";\n\t }\n\t kdc_log(context, config, 0, \"s4u2self %s impersonating %s to \"\n\t\t \"service %s %s\", cpn, tpn, spn, str);\n\t}\n }\n\n /*\n * Constrained delegation\n */\n\n if (client != NULL\n\t&& b->additional_tickets != NULL\n\t&& b->additional_tickets->len != 0\n\t&& b->kdc_options.enc_tkt_in_skey == 0)\n {\n\tint ad_signedpath = 0;\n\tKey *clientkey;\n\tTicket *t;\n\n\t/*\n\t * Require that the KDC have issued the service's krbtgt (not\n\t * self-issued ticket with kimpersonate(1).\n\t */\n\tif (!signedpath) {\n\t ret = KRB5KDC_ERR_BADOPTION;\n\t kdc_log(context, config, 0,\n\t\t \"Constrained delegation done on service ticket %s/%s\",\n\t\t cpn, spn);\n\t goto out;\n\t}\n\n\tt = &b->additional_tickets->val[0];\n\n\tret = hdb_enctype2key(context, &client->entry,\n\t\t\t hdb_kvno2keys(context, &client->entry,\n\t\t\t\t\t t->enc_part.kvno ? * t->enc_part.kvno : 0),\n\t\t\t t->enc_part.etype, &clientkey);\n\tif(ret){\n\t ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */\n\t goto out;\n\t}\n\n\tret = krb5_decrypt_ticket(context, t, &clientkey->key, &adtkt, 0);\n\tif (ret) {\n\t kdc_log(context, config, 0,\n\t\t \"failed to decrypt ticket for \"\n\t\t \"constrained delegation from %s to %s \", cpn, spn);\n\t goto out;\n\t}\n\n\tret = _krb5_principalname2krb5_principal(context,\n\t\t\t\t\t\t &tp,\n\t\t\t\t\t\t adtkt.cname,\n\t\t\t\t\t\t adtkt.crealm);\n\tif (ret)\n\t goto out;\n\n\tret = krb5_unparse_name(context, tp, &tpn);\n\tif (ret)\n\t goto out;\n\n\tret = _krb5_principalname2krb5_principal(context,\n\t\t\t\t\t\t &dp,\n\t\t\t\t\t\t t->sname,\n\t\t\t\t\t\t t->realm);\n\tif (ret)\n\t goto out;\n\n\tret = krb5_unparse_name(context, dp, &dpn);\n\tif (ret)\n\t goto out;\n\n\t/* check that ticket is valid */\n\tif (adtkt.flags.forwardable == 0) {\n\t kdc_log(context, config, 0,\n\t\t \"Missing forwardable flag on ticket for \"\n\t\t \"constrained delegation from %s (%s) as %s to %s \",\n\t\t cpn, dpn, tpn, spn);\n\t ret = KRB5KDC_ERR_BADOPTION;\n\t goto out;\n\t}\n\n\tret = check_constrained_delegation(context, config, clientdb,\n\t\t\t\t\t client, server, sp);\n\tif (ret) {\n\t kdc_log(context, config, 0,\n\t\t \"constrained delegation from %s (%s) as %s to %s not allowed\",\n\t\t cpn, dpn, tpn, spn);\n\t goto out;\n\t}\n\n\tret = verify_flags(context, config, &adtkt, tpn);\n\tif (ret) {\n\t goto out;\n\t}\n\n\tkrb5_data_free(&rspac);\n\n\t/*\n\t * generate the PAC for the user.\n\t *\n\t * TODO: pass in t->sname and t->realm and build\n\t * a S4U_DELEGATION_INFO blob to the PAC.\n\t */\n\tret = check_PAC(context, config, tp, dp,\n\t\t\tclient, server, krbtgt,\n\t\t\t&clientkey->key,\n\t\t\tekey, &tkey_sign->key,\n\t\t\t&adtkt, &rspac, &ad_signedpath);\n\tif (ret) {\n\t const char *msg = krb5_get_error_message(context, ret);\n\t kdc_log(context, config, 0,\n\t\t \"Verify delegated PAC failed to %s for client\"\n\t\t \"%s (%s) as %s from %s with %s\",\n\t\t spn, cpn, dpn, tpn, from, msg);\n\t krb5_free_error_message(context, msg);\n\t goto out;\n\t}\n\n\t/*\n\t * Check that the KDC issued the user's ticket.\n\t */\n\tret = check_KRB5SignedPath(context,\n\t\t\t\t config,\n\t\t\t\t krbtgt,\n\t\t\t\t cp,\n\t\t\t\t &adtkt,\n\t\t\t\t NULL,\n\t\t\t\t &ad_signedpath);\n\tif (ret) {\n\t const char *msg = krb5_get_error_message(context, ret);\n\t kdc_log(context, config, 0,\n\t\t \"KRB5SignedPath check from service %s failed \"\n\t\t \"for delegation to %s for client %s (%s)\"\n\t\t \"from %s failed with %s\",\n\t\t spn, tpn, dpn, cpn, from, msg);\n\t krb5_free_error_message(context, msg);\n\t goto out;\n\t}\n\n\tif (!ad_signedpath) {\n\t ret = KRB5KDC_ERR_BADOPTION;\n\t kdc_log(context, config, 0,\n\t\t \"Ticket not signed with PAC nor SignedPath service %s failed \"\n\t\t \"for delegation to %s for client %s (%s)\"\n\t\t \"from %s\",\n\t\t spn, tpn, dpn, cpn, from);\n\t goto out;\n\t}\n\n\tkdc_log(context, config, 0, \"constrained delegation for %s \"\n\t\t\"from %s (%s) to %s\", tpn, cpn, dpn, spn);\n }\n\n /*\n * Check flags\n */\n\n ret = kdc_check_flags(context, config,\n\t\t\t client, cpn,\n\t\t\t server, spn,\n\t\t\t FALSE);\n if(ret)\n\tgoto out;\n\n if((b->kdc_options.validate || b->kdc_options.renew) &&\n !krb5_principal_compare(context,\n\t\t\t krbtgt->entry.principal,\n\t\t\t server->entry.principal)){\n\tkdc_log(context, config, 0, \"Inconsistent request.\");\n\tret = KRB5KDC_ERR_SERVER_NOMATCH;\n\tgoto out;\n }\n\n /* check for valid set of addresses */\n if(!_kdc_check_addresses(context, config, tgt->caddr, from_addr)) {\n\tret = KRB5KRB_AP_ERR_BADADDR;\n\tkdc_log(context, config, 0, \"Request from wrong address\");\n\tgoto out;\n }\n\n /*\n * If this is an referral, add server referral data to the\n * auth_data reply .\n */\n if (ref_realm) {\n\tPA_DATA pa;\n\tkrb5_crypto crypto;\n\n\tkdc_log(context, config, 0,\n\t\t\"Adding server referral to %s\", ref_realm);\n\n\tret = krb5_crypto_init(context, &sessionkey, 0, &crypto);\n\tif (ret)\n\t goto out;\n\n\tret = build_server_referral(context, config, crypto, ref_realm,\n\t\t\t\t NULL, s, &pa.padata_value);\n\tkrb5_crypto_destroy(context, crypto);\n\tif (ret) {\n\t kdc_log(context, config, 0,\n\t\t \"Failed building server referral\");\n\t goto out;\n\t}\n\tpa.padata_type = KRB5_PADATA_SERVER_REFERRAL;\n\n\tret = add_METHOD_DATA(&enc_pa_data, &pa);\n\tkrb5_data_free(&pa.padata_value);\n\tif (ret) {\n\t kdc_log(context, config, 0,\n\t\t \"Add server referral METHOD-DATA failed\");\n\t goto out;\n\t}\n }\n\n /*\n *\n */\n\n ret = tgs_make_reply(context,\n\t\t\t config,\n\t\t\t b,\n\t\t\t tp,\n\t\t\t tgt,\n\t\t\t replykey,\n\t\t\t rk_is_subkey,\n\t\t\t ekey,\n\t\t\t &sessionkey,\n\t\t\t kvno,\n\t\t\t *auth_data,\n\t\t\t server,\n\t\t\t rsp,\n\t\t\t spn,\n\t\t\t client,\n\t\t\t cp,\n\t\t\t krbtgt_out,\n\t\t\t tkey_sign->key.keytype,\n\t\t\t spp,\n\t\t\t &rspac,\n\t\t\t &enc_pa_data,\n\t\t\t e_text,\n\t\t\t reply);\n\nout:\n if (tpn != cpn)\n\t free(tpn);\n free(spn);\n free(cpn);\n free(dpn);\n free(krbtgt_out_n);\n _krb5_free_capath(context, capath);\n\n krb5_data_free(&rspac);\n krb5_free_keyblock_contents(context, &sessionkey);\n if(krbtgt_out)\n\t_kdc_free_ent(context, krbtgt_out);\n if(server)\n\t_kdc_free_ent(context, server);\n if(client)\n\t_kdc_free_ent(context, client);\n if(s4u2self_impersonated_client)\n\t_kdc_free_ent(context, s4u2self_impersonated_client);\n\n if (tp && tp != cp)\n\tkrb5_free_principal(context, tp);\n krb5_free_principal(context, cp);\n krb5_free_principal(context, dp);\n krb5_free_principal(context, sp);\n krb5_free_principal(context, krbtgt_out_principal);\n free(ref_realm);\n free_METHOD_DATA(&enc_pa_data);\n\n free_EncTicketPart(&adtkt);\n\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-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: PHPAPI int php_var_unserialize(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 && cursor[0] != 'R') {\n\t\tvar_push(var_hash, rval);\n\t}\n\n\tstart = cursor;\n\n\n\n\n#line 495 \"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\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 860 \"ext/standard/var_unserializer.re\"\n\t{ return 0; }\n#line 557 \"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 854 \"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 TSRMLS_CC, E_NOTICE, \"Unexpected end of serialized data\");\n\treturn 0; /* not sure if it should be 0 or 1 here? */\n}\n#line 606 \"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 707 \"ext/standard/var_unserializer.re\"\n\t{\n\tsize_t len, len2, len3, maxlen;\n\tlong elements;\n\tchar *class_name;\n\tzend_class_entry *ce;\n\tzend_class_entry **pce;\n\tint incomplete_class = 0;\n\n\tint custom_object = 0;\n\n\tzval *user_func;\n\tzval *retval_ptr;\n\tzval **args[1];\n\tzval *arg_func_name;\n\n if (!var_hash) return 0;\n\tif (*start == 'C') {\n\t\tcustom_object = 1;\n\t}\n\n\tINIT_PZVAL(*rval);\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\tclass_name = (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(class_name, \"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 = estrndup(class_name, len);\n\n\tdo {\n\t\t/* Try to find class directly */\n\t\tBG(serialize_lock)++;\n\t\tif (zend_lookup_class(class_name, len2, &pce TSRMLS_CC) == SUCCESS) {\n\t\t\tBG(serialize_lock)--;\n\t\t\tif (EG(exception)) {\n\t\t\t\tefree(class_name);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tce = *pce;\n\t\t\tbreak;\n\t\t}\n\t\tBG(serialize_lock)--;\n\n\t\tif (EG(exception)) {\n\t\t\tefree(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\tMAKE_STD_ZVAL(user_func);\n\t\tZVAL_STRING(user_func, PG(unserialize_callback_func), 1);\n\t\targs[0] = &arg_func_name;\n\t\tMAKE_STD_ZVAL(arg_func_name);\n\t\tZVAL_STRING(arg_func_name, class_name, 1);\n\t\tBG(serialize_lock)++;\n\t\tif (call_user_function_ex(CG(function_table), NULL, user_func, &retval_ptr, 1, args, 0, NULL TSRMLS_CC) != SUCCESS) {\n\t\t\tBG(serialize_lock)--;\n\t\t\tif (EG(exception)) {\n\t\t\t\tefree(class_name);\n\t\t\t\tzval_ptr_dtor(&user_func);\n\t\t\t\tzval_ptr_dtor(&arg_func_name);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"defined (%s) but not found\", user_func->value.str.val);\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(&arg_func_name);\n\t\t\tbreak;\n\t\t}\n\t\tBG(serialize_lock)--;\n\t\tif (retval_ptr) {\n\t\t\tzval_ptr_dtor(&retval_ptr);\n\t\t}\n\t\tif (EG(exception)) {\n\t\t\tefree(class_name);\n\t\t\tzval_ptr_dtor(&user_func);\n\t\t\tzval_ptr_dtor(&arg_func_name);\n\t\t\treturn 0;\n\t\t}\n\n\t\t/* The callback function may have defined the class */\n\t\tif (zend_lookup_class(class_name, len2, &pce TSRMLS_CC) == SUCCESS) {\n\t\t\tce = *pce;\n\t\t} else {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Function %s() hasn't defined the class it was called for\", user_func->value.str.val);\n\t\t\tincomplete_class = 1;\n\t\t\tce = PHP_IC_ENTRY;\n\t\t}\n\n\t\tzval_ptr_dtor(&user_func);\n\t\tzval_ptr_dtor(&arg_func_name);\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, class_name, len2);\n\t\t}\n\t\tefree(class_name);\n\t\treturn ret;\n\t}\n\n\telements = object_common1(UNSERIALIZE_PASSTHRU, ce);\n\n\tif (incomplete_class) {\n\t\tphp_store_class_name(*rval, class_name, len2);\n\t}\n\tefree(class_name);\n\n\treturn object_common2(UNSERIALIZE_PASSTHRU, elements);\n}\n#line 784 \"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 698 \"ext/standard/var_unserializer.re\"\n\t{\n if (!var_hash) return 0;\n\n\tINIT_PZVAL(*rval);\n\n\treturn object_common2(UNSERIALIZE_PASSTHRU,\n\t\t\tobject_common1(UNSERIALIZE_PASSTHRU, ZEND_STANDARD_CLASS_DEF_PTR));\n}\n#line 818 \"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 677 \"ext/standard/var_unserializer.re\"\n\t{\n\tlong 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) {\n\t\treturn 0;\n\t}\n\n\tINIT_PZVAL(*rval);\n\n\tarray_init_size(*rval, elements);\n\n\tif (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_ARRVAL_PP(rval), elements, 0)) {\n\t\treturn 0;\n\t}\n\n\treturn finish_nested_data(UNSERIALIZE_PASSTHRU);\n}\n#line 860 \"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 642 \"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\tif ((str = unserialize_str(&YYCURSOR, &len, maxlen)) == NULL) {\n\t\treturn 0;\n\t}\n\n\tif (*(YYCURSOR) != '\"') {\n\t\tefree(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\tINIT_PZVAL(*rval);\n\tZVAL_STRINGL(*rval, str, len, 0);\n\treturn 1;\n}\n#line 916 \"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 609 \"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\tINIT_PZVAL(*rval);\n\tZVAL_STRINGL(*rval, str, len, 1);\n\treturn 1;\n}\n#line 970 \"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 599 \"ext/standard/var_unserializer.re\"\n\t{\n#if SIZEOF_LONG == 4\nuse_double:\n#endif\n\t*p = YYCURSOR;\n\tINIT_PZVAL(*rval);\n\tZVAL_DOUBLE(*rval, zend_strtod((const char *)start + 2, NULL));\n\treturn 1;\n}\n#line 1068 \"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 584 \"ext/standard/var_unserializer.re\"\n\t{\n\t*p = YYCURSOR;\n\tINIT_PZVAL(*rval);\n\n\tif (!strncmp(start + 2, \"NAN\", 3)) {\n\t\tZVAL_DOUBLE(*rval, php_get_nan());\n\t} else if (!strncmp(start + 2, \"INF\", 3)) {\n\t\tZVAL_DOUBLE(*rval, php_get_inf());\n\t} else if (!strncmp(start + 2, \"-INF\", 4)) {\n\t\tZVAL_DOUBLE(*rval, -php_get_inf());\n\t}\n\n\treturn 1;\n}\n#line 1142 \"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 557 \"ext/standard/var_unserializer.re\"\n\t{\n#if SIZEOF_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 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(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\tINIT_PZVAL(*rval);\n\tZVAL_LONG(*rval, parse_iv(start + 2));\n\treturn 1;\n}\n#line 1196 \"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 550 \"ext/standard/var_unserializer.re\"\n\t{\n\t*p = YYCURSOR;\n\tINIT_PZVAL(*rval);\n\tZVAL_BOOL(*rval, parse_iv(start + 2));\n\treturn 1;\n}\n#line 1211 \"ext/standard/var_unserializer.c\"\nyy87:\n\t++YYCURSOR;\n#line 543 \"ext/standard/var_unserializer.re\"\n\t{\n\t*p = YYCURSOR;\n\tINIT_PZVAL(*rval);\n\tZVAL_NULL(*rval);\n\treturn 1;\n}\n#line 1221 \"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 520 \"ext/standard/var_unserializer.re\"\n\t{\n\tlong id;\n\n \t*p = YYCURSOR;\n\tif (!var_hash) return 0;\n\n\tid = parse_iv(start + 2) - 1;\n\tif (id == -1 || var_access(var_hash, id, &rval_ref) != SUCCESS) {\n\t\treturn 0;\n\t}\n\n\tif (*rval == *rval_ref) return 0;\n\n\tif (*rval != NULL) {\n\t\tvar_push_dtor_no_addref(var_hash, rval);\n\t}\n\t*rval = *rval_ref;\n\tZ_ADDREF_PP(rval);\n\tZ_UNSET_ISREF_PP(rval);\n\n\treturn 1;\n}\n#line 1267 \"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 499 \"ext/standard/var_unserializer.re\"\n\t{\n\tlong id;\n\n \t*p = YYCURSOR;\n\tif (!var_hash) return 0;\n\n\tid = parse_iv(start + 2) - 1;\n\tif (id == -1 || var_access(var_hash, id, &rval_ref) != SUCCESS) {\n\t\treturn 0;\n\t}\n\n\tif (*rval != NULL) {\n\t\tvar_push_dtor_no_addref(var_hash, rval);\n\t}\n\t*rval = *rval_ref;\n\tZ_ADDREF_PP(rval);\n\tZ_SET_ISREF_PP(rval);\n\n\treturn 1;\n}\n#line 1311 \"ext/standard/var_unserializer.c\"\n}\n#line 862 \"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-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 H AbslHashValue(H h, const TensorKey& k) {\n const uint8* d = static_cast(k.data());\n size_t s = k.AllocatedBytes();\n std::vector vec;\n vec.reserve(s);\n for (int i = 0; i < s; i++) {\n vec.push_back(d[i]);\n }\n return H::combine(std::move(h), s);\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: int phar_verify_signature(php_stream *fp, size_t end_of_phar, php_uint32 sig_type, char *sig, int sig_len, char *fname, char **signature, int *signature_len, char **error) /* {{{ */\n{\n\tint read_size, len;\n\tzend_off_t read_len;\n\tunsigned char buf[1024];\n\n\tphp_stream_rewind(fp);\n\n\tswitch (sig_type) {\n\t\tcase PHAR_SIG_OPENSSL: {\n#ifdef PHAR_HAVE_OPENSSL\n\t\t\tBIO *in;\n\t\t\tEVP_PKEY *key;\n\t\t\tEVP_MD *mdtype = (EVP_MD *) EVP_sha1();\n\t\t\tEVP_MD_CTX md_ctx;\n#else\n\t\t\tint tempsig;\n#endif\n\t\t\tzend_string *pubkey = NULL;\n\t\t\tchar *pfile;\n\t\t\tphp_stream *pfp;\n#ifndef PHAR_HAVE_OPENSSL\n\t\t\tif (!zend_hash_str_exists(&module_registry, \"openssl\", sizeof(\"openssl\")-1)) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 0, \"openssl not loaded\");\n\t\t\t\t}\n\t\t\t\treturn FAILURE;\n\t\t\t}\n#endif\n\t\t\t/* use __FILE__ . '.pubkey' for public key file */\n\t\t\tspprintf(&pfile, 0, \"%s.pubkey\", fname);\n\t\t\tpfp = php_stream_open_wrapper(pfile, \"rb\", 0, NULL);\n\t\t\tefree(pfile);\n\n\t\t\tif (!pfp || !(pubkey = php_stream_copy_to_mem(pfp, PHP_STREAM_COPY_ALL, 0)) || !ZSTR_LEN(pubkey)) {\n\t\t\t\tif (pfp) {\n\t\t\t\t\tphp_stream_close(pfp);\n\t\t\t\t}\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 0, \"openssl public key could not be read\");\n\t\t\t\t}\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\n\t\t\tphp_stream_close(pfp);\n#ifndef PHAR_HAVE_OPENSSL\n\t\t\ttempsig = sig_len;\n\n\t\t\tif (FAILURE == phar_call_openssl_signverify(0, fp, end_of_phar, pubkey ? ZSTR_VAL(pubkey) : NULL, pubkey ? ZSTR_LEN(pubkey) : 0, &sig, &tempsig)) {\n\t\t\t\tif (pubkey) {\n\t\t\t\t\tzend_string_release(pubkey);\n\t\t\t\t}\n\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 0, \"openssl signature could not be verified\");\n\t\t\t\t}\n\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\n\t\t\tif (pubkey) {\n\t\t\t\tzend_string_release(pubkey);\n\t\t\t}\n\n\t\t\tsig_len = tempsig;\n#else\n\t\t\tin = BIO_new_mem_buf(pubkey ? ZSTR_VAL(pubkey) : NULL, pubkey ? ZSTR_LEN(pubkey) : 0);\n\n\t\t\tif (NULL == in) {\n\t\t\t\tzend_string_release(pubkey);\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 0, \"openssl signature could not be processed\");\n\t\t\t\t}\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\n\t\t\tkey = PEM_read_bio_PUBKEY(in, NULL,NULL, NULL);\n\t\t\tBIO_free(in);\n\t\t\tzend_string_release(pubkey);\n\n\t\t\tif (NULL == key) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 0, \"openssl signature could not be processed\");\n\t\t\t\t}\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\n\t\t\tEVP_VerifyInit(&md_ctx, mdtype);\n\t\t\tread_len = end_of_phar;\n\n\t\t\tif (read_len > sizeof(buf)) {\n\t\t\t\tread_size = sizeof(buf);\n\t\t\t} else {\n\t\t\t\tread_size = (int)read_len;\n\t\t\t}\n\n\t\t\tphp_stream_seek(fp, 0, SEEK_SET);\n\n\t\t\twhile (read_size && (len = php_stream_read(fp, (char*)buf, read_size)) > 0) {\n\t\t\t\tEVP_VerifyUpdate (&md_ctx, buf, len);\n\t\t\t\tread_len -= (zend_off_t)len;\n\n\t\t\t\tif (read_len < read_size) {\n\t\t\t\t\tread_size = (int)read_len;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (EVP_VerifyFinal(&md_ctx, (unsigned char *)sig, sig_len, key) != 1) {\n\t\t\t\t/* 1: signature verified, 0: signature does not match, -1: failed signature operation */\n\t\t\t\tEVP_MD_CTX_cleanup(&md_ctx);\n\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 0, \"broken openssl signature\");\n\t\t\t\t}\n\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\n\t\t\tEVP_MD_CTX_cleanup(&md_ctx);\n#endif\n\n\t\t\t*signature_len = phar_hex_str((const char*)sig, sig_len, signature);\n\t\t}\n\t\tbreak;\n#ifdef PHAR_HASH_OK\n\t\tcase PHAR_SIG_SHA512: {\n\t\t\tunsigned char digest[64];\n\t\t\tPHP_SHA512_CTX context;\n\n\t\t\tPHP_SHA512Init(&context);\n\t\t\tread_len = end_of_phar;\n\n\t\t\tif (read_len > sizeof(buf)) {\n\t\t\t\tread_size = sizeof(buf);\n\t\t\t} else {\n\t\t\t\tread_size = (int)read_len;\n\t\t\t}\n\n\t\t\twhile ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) {\n\t\t\t\tPHP_SHA512Update(&context, buf, len);\n\t\t\t\tread_len -= (zend_off_t)len;\n\t\t\t\tif (read_len < read_size) {\n\t\t\t\t\tread_size = (int)read_len;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tPHP_SHA512Final(digest, &context);\n\n\t\t\tif (memcmp(digest, sig, sizeof(digest))) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 0, \"broken signature\");\n\t\t\t\t}\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\n\t\t\t*signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature);\n\t\t\tbreak;\n\t\t}\n\t\tcase PHAR_SIG_SHA256: {\n\t\t\tunsigned char digest[32];\n\t\t\tPHP_SHA256_CTX context;\n\n\t\t\tPHP_SHA256Init(&context);\n\t\t\tread_len = end_of_phar;\n\n\t\t\tif (read_len > sizeof(buf)) {\n\t\t\t\tread_size = sizeof(buf);\n\t\t\t} else {\n\t\t\t\tread_size = (int)read_len;\n\t\t\t}\n\n\t\t\twhile ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) {\n\t\t\t\tPHP_SHA256Update(&context, buf, len);\n\t\t\t\tread_len -= (zend_off_t)len;\n\t\t\t\tif (read_len < read_size) {\n\t\t\t\t\tread_size = (int)read_len;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tPHP_SHA256Final(digest, &context);\n\n\t\t\tif (memcmp(digest, sig, sizeof(digest))) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 0, \"broken signature\");\n\t\t\t\t}\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\n\t\t\t*signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature);\n\t\t\tbreak;\n\t\t}\n#else\n\t\tcase PHAR_SIG_SHA512:\n\t\tcase PHAR_SIG_SHA256:\n\t\t\tif (error) {\n\t\t\t\tspprintf(error, 0, \"unsupported signature\");\n\t\t\t}\n\t\t\treturn FAILURE;\n#endif\n\t\tcase PHAR_SIG_SHA1: {\n\t\t\tunsigned char digest[20];\n\t\t\tPHP_SHA1_CTX context;\n\n\t\t\tPHP_SHA1Init(&context);\n\t\t\tread_len = end_of_phar;\n\n\t\t\tif (read_len > sizeof(buf)) {\n\t\t\t\tread_size = sizeof(buf);\n\t\t\t} else {\n\t\t\t\tread_size = (int)read_len;\n\t\t\t}\n\n\t\t\twhile ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) {\n\t\t\t\tPHP_SHA1Update(&context, buf, len);\n\t\t\t\tread_len -= (zend_off_t)len;\n\t\t\t\tif (read_len < read_size) {\n\t\t\t\t\tread_size = (int)read_len;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tPHP_SHA1Final(digest, &context);\n\n\t\t\tif (memcmp(digest, sig, sizeof(digest))) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 0, \"broken signature\");\n\t\t\t\t}\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\n\t\t\t*signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature);\n\t\t\tbreak;\n\t\t}\n\t\tcase PHAR_SIG_MD5: {\n\t\t\tunsigned char digest[16];\n\t\t\tPHP_MD5_CTX context;\n\n\t\t\tPHP_MD5Init(&context);\n\t\t\tread_len = end_of_phar;\n\n\t\t\tif (read_len > sizeof(buf)) {\n\t\t\t\tread_size = sizeof(buf);\n\t\t\t} else {\n\t\t\t\tread_size = (int)read_len;\n\t\t\t}\n\n\t\t\twhile ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) {\n\t\t\t\tPHP_MD5Update(&context, buf, len);\n\t\t\t\tread_len -= (zend_off_t)len;\n\t\t\t\tif (read_len < read_size) {\n\t\t\t\t\tread_size = (int)read_len;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tPHP_MD5Final(digest, &context);\n\n\t\t\tif (memcmp(digest, sig, sizeof(digest))) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 0, \"broken signature\");\n\t\t\t\t}\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\n\t\t\t*signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature);\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tif (error) {\n\t\t\t\tspprintf(error, 0, \"broken or unsupported signature\");\n\t\t\t}\n\t\t\treturn FAILURE;\n\t}\n\treturn SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix bug #72928 - Out of bound when verify signature of zip phar in phar_parse_zipfile\n\n(cherry picked from commit 19484ab77466f99c78fc0e677f7e03da0584d6a2)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: win_exchange(long Prenum)\n{\n frame_T\t*frp;\n frame_T\t*frp2;\n win_T\t*wp;\n win_T\t*wp2;\n int\t\ttemp;\n\n if (ERROR_IF_ANY_POPUP_WINDOW)\n\treturn;\n if (ONE_WINDOW)\t // just one window\n {\n\tbeep_flush();\n\treturn;\n }\n\n#ifdef FEAT_GUI\n need_mouse_correct = TRUE;\n#endif\n\n /*\n * find window to exchange with\n */\n if (Prenum)\n {\n\tfrp = curwin->w_frame->fr_parent->fr_child;\n\twhile (frp != NULL && --Prenum > 0)\n\t frp = frp->fr_next;\n }\n else if (curwin->w_frame->fr_next != NULL)\t// Swap with next\n\tfrp = curwin->w_frame->fr_next;\n else // Swap last window in row/col with previous\n\tfrp = curwin->w_frame->fr_prev;\n\n // We can only exchange a window with another window, not with a frame\n // containing windows.\n if (frp == NULL || frp->fr_win == NULL || frp->fr_win == curwin)\n\treturn;\n wp = frp->fr_win;\n\n/*\n * 1. remove curwin from the list. Remember after which window it was in wp2\n * 2. insert curwin before wp in the list\n * if wp != wp2\n * 3. remove wp from the list\n * 4. insert wp after wp2\n * 5. exchange the status line height and vsep width.\n */\n wp2 = curwin->w_prev;\n frp2 = curwin->w_frame->fr_prev;\n if (wp->w_prev != curwin)\n {\n\twin_remove(curwin, NULL);\n\tframe_remove(curwin->w_frame);\n\twin_append(wp->w_prev, curwin);\n\tframe_insert(frp, curwin->w_frame);\n }\n if (wp != wp2)\n {\n\twin_remove(wp, NULL);\n\tframe_remove(wp->w_frame);\n\twin_append(wp2, wp);\n\tif (frp2 == NULL)\n\t frame_insert(wp->w_frame->fr_parent->fr_child, wp->w_frame);\n\telse\n\t frame_append(frp2, wp->w_frame);\n }\n temp = curwin->w_status_height;\n curwin->w_status_height = wp->w_status_height;\n wp->w_status_height = temp;\n temp = curwin->w_vsep_width;\n curwin->w_vsep_width = wp->w_vsep_width;\n wp->w_vsep_width = temp;\n\n frame_fix_height(curwin);\n frame_fix_height(wp);\n frame_fix_width(curwin);\n frame_fix_width(wp);\n\n (void)win_comp_pos();\t\t// recompute window positions\n\n win_enter(wp, TRUE);\n redraw_all_later(NOT_VALID);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'patch 8.2.4154: ml_get error when exchanging windows in Visual mode\n\nProblem: ml_get error when exchanging windows in Visual mode.\nSolution: Correct end of Visual area when entering another buffer.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: fb_mmap(struct file *file, struct vm_area_struct * vma)\n{\n\tstruct fb_info *info = file_fb_info(file);\n\tstruct fb_ops *fb;\n\tunsigned long off;\n\tunsigned long start;\n\tu32 len;\n\n\tif (!info)\n\t\treturn -ENODEV;\n\tif (vma->vm_pgoff > (~0UL >> PAGE_SHIFT))\n\t\treturn -EINVAL;\n\toff = vma->vm_pgoff << PAGE_SHIFT;\n\tfb = info->fbops;\n\tif (!fb)\n\t\treturn -ENODEV;\n\tmutex_lock(&info->mm_lock);\n\tif (fb->fb_mmap) {\n\t\tint res;\n\t\tres = fb->fb_mmap(info, vma);\n\t\tmutex_unlock(&info->mm_lock);\n\t\treturn res;\n\t}\n\n\t/* frame buffer memory */\n\tstart = info->fix.smem_start;\n\tlen = PAGE_ALIGN((start & ~PAGE_MASK) + info->fix.smem_len);\n\tif (off >= len) {\n\t\t/* memory mapped io */\n\t\toff -= len;\n\t\tif (info->var.accel_flags) {\n\t\t\tmutex_unlock(&info->mm_lock);\n\t\t\treturn -EINVAL;\n\t\t}\n\t\tstart = info->fix.mmio_start;\n\t\tlen = PAGE_ALIGN((start & ~PAGE_MASK) + info->fix.mmio_len);\n\t}\n\tmutex_unlock(&info->mm_lock);\n\tstart &= PAGE_MASK;\n\tif ((vma->vm_end - vma->vm_start + off) > len)\n\t\treturn -EINVAL;\n\toff += start;\n\tvma->vm_pgoff = off >> PAGE_SHIFT;\n\t/* VM_IO | VM_DONTEXPAND | VM_DONTDUMP are set by io_remap_pfn_range()*/\n\tvma->vm_page_prot = vm_get_page_prot(vma->vm_flags);\n\tfb_pgprotect(file, vma, off);\n\tif (io_remap_pfn_range(vma, vma->vm_start, off >> PAGE_SHIFT,\n\t\t\t vma->vm_end - vma->vm_start, vma->vm_page_prot))\n\t\treturn -EAGAIN;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'vm: convert fb_mmap to vm_iomap_memory() helper\n\nThis is my example conversion of a few existing mmap users. The\nfb_mmap() case is a good example because it is a bit more complicated\nthan some: fb_mmap() mmaps one of two different memory areas depending\non the page offset of the mmap (but happily there is never any mixing of\nthe two, so the helper function still works).\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: construct_command_line(struct manager_ctx *manager, struct server *server)\n{\n static char cmd[BUF_SIZE];\n char *method = manager->method;\n int i;\n\n build_config(working_dir, server);\n\n if (server->method) method = server->method;\n memset(cmd, 0, BUF_SIZE);\n snprintf(cmd, BUF_SIZE,\n \"%s -m %s --manager-address %s -f %s/.shadowsocks_%s.pid -c %s/.shadowsocks_%s.conf\",\n executable, method, manager->manager_address,\n working_dir, server->port, working_dir, server->port);\n\n if (manager->acl != NULL) {\n int len = strlen(cmd);\n snprintf(cmd + len, BUF_SIZE - len, \" --acl %s\", manager->acl);\n }\n if (manager->timeout != NULL) {\n int len = strlen(cmd);\n snprintf(cmd + len, BUF_SIZE - len, \" -t %s\", manager->timeout);\n }\n#ifdef HAVE_SETRLIMIT\n if (manager->nofile) {\n int len = strlen(cmd);\n snprintf(cmd + len, BUF_SIZE - len, \" -n %d\", manager->nofile);\n }\n#endif\n if (manager->user != NULL) {\n int len = strlen(cmd);\n snprintf(cmd + len, BUF_SIZE - len, \" -a %s\", manager->user);\n }\n if (manager->verbose) {\n int len = strlen(cmd);\n snprintf(cmd + len, BUF_SIZE - len, \" -v\");\n }\n if (server->mode == NULL && manager->mode == UDP_ONLY) {\n int len = strlen(cmd);\n snprintf(cmd + len, BUF_SIZE - len, \" -U\");\n }\n if (server->mode == NULL && manager->mode == TCP_AND_UDP) {\n int len = strlen(cmd);\n snprintf(cmd + len, BUF_SIZE - len, \" -u\");\n }\n if (server->fast_open[0] == 0 && manager->fast_open) {\n int len = strlen(cmd);\n snprintf(cmd + len, BUF_SIZE - len, \" --fast-open\");\n }\n if (manager->ipv6first) {\n int len = strlen(cmd);\n snprintf(cmd + len, BUF_SIZE - len, \" -6\");\n }\n if (manager->mtu) {\n int len = strlen(cmd);\n snprintf(cmd + len, BUF_SIZE - len, \" --mtu %d\", manager->mtu);\n }\n if (server->plugin == NULL && manager->plugin) {\n int len = strlen(cmd);\n snprintf(cmd + len, BUF_SIZE - len, \" --plugin \\\"%s\\\"\", manager->plugin);\n }\n if (server->plugin_opts == NULL && manager->plugin_opts) {\n int len = strlen(cmd);\n snprintf(cmd + len, BUF_SIZE - len, \" --plugin-opts \\\"%s\\\"\", manager->plugin_opts);\n }\n for (i = 0; i < manager->nameserver_num; i++) {\n int len = strlen(cmd);\n snprintf(cmd + len, BUF_SIZE - len, \" -d %s\", manager->nameservers[i]);\n }\n for (i = 0; i < manager->host_num; i++) {\n int len = strlen(cmd);\n snprintf(cmd + len, BUF_SIZE - len, \" -s %s\", manager->hosts[i]);\n }\n // Always enable reuse port\n {\n int len = strlen(cmd);\n snprintf(cmd + len, BUF_SIZE - len, \" --reuse-port\");\n }\n\n if (verbose) {\n LOGI(\"cmd: %s\", cmd);\n }\n\n return cmd;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-78', 'CWE-787'], 'message': 'Fix #1734'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int mincore_unmapped_range(unsigned long addr, unsigned long end,\n\t\t\t\t struct mm_walk *walk)\n{\n\twalk->private += __mincore_unmapped_range(addr, end,\n\t\t\t\t\t\t walk->vma, walk->private);\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: TEST_F(RouterTest, MissingRequiredHeaders) {\n NiceMock encoder;\n Http::ResponseDecoder* response_decoder = nullptr;\n EXPECT_CALL(cm_.thread_local_cluster_.conn_pool_, newStream(_, _))\n .WillOnce(Invoke(\n [&](Http::ResponseDecoder& decoder,\n Http::ConnectionPool::Callbacks& callbacks) -> Http::ConnectionPool::Cancellable* {\n response_decoder = &decoder;\n callbacks.onPoolReady(encoder, cm_.thread_local_cluster_.conn_pool_.host_,\n upstream_stream_info_, Http::Protocol::Http10);\n return nullptr;\n }));\n expectResponseTimerCreate();\n\n Http::TestRequestHeaderMapImpl headers;\n HttpTestUtility::addDefaultHeaders(headers);\n headers.removeMethod();\n\n EXPECT_CALL(encoder, encodeHeaders(_, _))\n .WillOnce(Invoke([](const Http::RequestHeaderMap& headers, bool) -> Http::Status {\n return Http::HeaderUtility::checkRequiredRequestHeaders(headers);\n }));\n EXPECT_CALL(\n callbacks_,\n sendLocalReply(Http::Code::ServiceUnavailable,\n testing::Eq(\"missing required header: :method\"), _, _,\n \"filter_removed_required_request_headers{missing required header: :method}\"))\n .WillOnce(testing::InvokeWithoutArgs([] {}));\n router_.decodeHeaders(headers, true);\n router_.onDestroy();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': '[1.20] CVE-2022-21655\n\nCrash with direct_response\n\nSigned-off-by: Otto van der Schaaf '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ax25_recvmsg(struct kiocb *iocb, struct socket *sock,\n\tstruct msghdr *msg, size_t size, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct sk_buff *skb;\n\tint copied;\n\tint err = 0;\n\n\tlock_sock(sk);\n\t/*\n\t * \tThis works for seqpacket too. The receiver has ordered the\n\t *\tqueue for us! We do one quick check first though\n\t */\n\tif (sk->sk_type == SOCK_SEQPACKET && sk->sk_state != TCP_ESTABLISHED) {\n\t\terr = -ENOTCONN;\n\t\tgoto out;\n\t}\n\n\t/* Now we can treat all alike */\n\tskb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,\n\t\t\t\tflags & MSG_DONTWAIT, &err);\n\tif (skb == NULL)\n\t\tgoto out;\n\n\tif (!ax25_sk(sk)->pidincl)\n\t\tskb_pull(skb, 1);\t\t/* Remove PID */\n\n\tskb_reset_transport_header(skb);\n\tcopied = skb->len;\n\n\tif (copied > size) {\n\t\tcopied = size;\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t}\n\n\tskb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\n\tif (msg->msg_namelen != 0) {\n\t\tstruct sockaddr_ax25 *sax = (struct sockaddr_ax25 *)msg->msg_name;\n\t\tax25_digi digi;\n\t\tax25_address src;\n\t\tconst unsigned char *mac = skb_mac_header(skb);\n\n\t\tax25_addr_parse(mac + 1, skb->data - mac - 1, &src, NULL,\n\t\t\t\t&digi, NULL, NULL);\n\t\tsax->sax25_family = AF_AX25;\n\t\t/* We set this correctly, even though we may not let the\n\t\t application know the digi calls further down (because it\n\t\t did NOT ask to know them). This could get political... **/\n\t\tsax->sax25_ndigis = digi.ndigi;\n\t\tsax->sax25_call = src;\n\n\t\tif (sax->sax25_ndigis != 0) {\n\t\t\tint ct;\n\t\t\tstruct full_sockaddr_ax25 *fsa = (struct full_sockaddr_ax25 *)sax;\n\n\t\t\tfor (ct = 0; ct < digi.ndigi; ct++)\n\t\t\t\tfsa->fsa_digipeater[ct] = digi.calls[ct];\n\t\t}\n\t\tmsg->msg_namelen = sizeof(struct full_sockaddr_ax25);\n\t}\n\n\tskb_free_datagram(sk, skb);\n\terr = copied;\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-200'], 'message': 'ax25: fix info leak via msg_name in ax25_recvmsg()\n\nWhen msg_namelen is non-zero the sockaddr info gets filled out, as\nrequested, but the code fails to initialize the padding bytes of struct\nsockaddr_ax25 inserted by the compiler for alignment. Additionally the\nmsg_namelen value is updated to sizeof(struct full_sockaddr_ax25) but is\nnot always filled up to this size.\n\nBoth issues lead to the fact that the code will leak uninitialized\nkernel stack bytes in net/socket.c.\n\nFix both issues by initializing the memory with memset(0).\n\nCc: Ralf Baechle \nSigned-off-by: Mathias Krause \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ripng_print(netdissect_options *ndo, const u_char *dat, unsigned int length)\n{\n\tregister const struct rip6 *rp = (const struct rip6 *)dat;\n\tregister const struct netinfo6 *ni;\n\tregister u_int amt;\n\tregister u_int i;\n\tint j;\n\tint trunc;\n\n\tif (ndo->ndo_snapend < dat)\n\t\treturn;\n\tamt = ndo->ndo_snapend - dat;\n\ti = min(length, amt);\n\tif (i < (sizeof(struct rip6) - sizeof(struct netinfo6)))\n\t\treturn;\n\ti -= (sizeof(struct rip6) - sizeof(struct netinfo6));\n\n\tswitch (rp->rip6_cmd) {\n\n\tcase RIP6_REQUEST:\n\t\tj = length / sizeof(*ni);\n\t\tif (j == 1\n\t\t && rp->rip6_nets->rip6_metric == HOPCNT_INFINITY6\n\t\t && IN6_IS_ADDR_UNSPECIFIED(&rp->rip6_nets->rip6_dest)) {\n\t\t\tND_PRINT((ndo, \" ripng-req dump\"));\n\t\t\tbreak;\n\t\t}\n\t\tif (j * sizeof(*ni) != length - 4)\n\t\t\tND_PRINT((ndo, \" ripng-req %d[%u]:\", j, length));\n\t\telse\n\t\t\tND_PRINT((ndo, \" ripng-req %d:\", j));\n\t\ttrunc = ((i / sizeof(*ni)) * sizeof(*ni) != i);\n\t\tfor (ni = rp->rip6_nets; i >= sizeof(*ni);\n\t\t i -= sizeof(*ni), ++ni) {\n\t\t\tif (ndo->ndo_vflag > 1)\n\t\t\t\tND_PRINT((ndo, \"\\n\\t\"));\n\t\t\telse\n\t\t\t\tND_PRINT((ndo, \" \"));\n\t\t\trip6_entry_print(ndo, ni, 0);\n\t\t}\n\t\tbreak;\n\tcase RIP6_RESPONSE:\n\t\tj = length / sizeof(*ni);\n\t\tif (j * sizeof(*ni) != length - 4)\n\t\t\tND_PRINT((ndo, \" ripng-resp %d[%u]:\", j, length));\n\t\telse\n\t\t\tND_PRINT((ndo, \" ripng-resp %d:\", j));\n\t\ttrunc = ((i / sizeof(*ni)) * sizeof(*ni) != i);\n\t\tfor (ni = rp->rip6_nets; i >= sizeof(*ni);\n\t\t i -= sizeof(*ni), ++ni) {\n\t\t\tif (ndo->ndo_vflag > 1)\n\t\t\t\tND_PRINT((ndo, \"\\n\\t\"));\n\t\t\telse\n\t\t\t\tND_PRINT((ndo, \" \"));\n\t\t\trip6_entry_print(ndo, ni, ni->rip6_metric);\n\t\t}\n\t\tif (trunc)\n\t\t\tND_PRINT((ndo, \"[|ripng]\"));\n\t\tbreak;\n\tdefault:\n\t\tND_PRINT((ndo, \" ripng-%d ?? %u\", rp->rip6_cmd, length));\n\t\tbreak;\n\t}\n\tif (rp->rip6_vers != RIP6_VERSION)\n\t\tND_PRINT((ndo, \" [vers %d]\", rp->rip6_vers));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'CVE-2017-12992/RIPng: Clean up bounds checking.\n\nDo bounds checking as we access items.\n\nScan the list of netinfo6 entries based on the supplied packet length,\nwithout taking the captured length into account; let the aforementioned\nbounds checking handle that.\n\nThis fixes a buffer over-read discovered by Kamil Frankowicz.\n\nAdd a test using the capture file supplied by the reporter(s).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int sd_e_h(GWindow gw, GEvent *event) {\n struct sd_data *sd = GDrawGetUserData(gw);\n\n if ( sd==NULL )\nreturn( true );\n \n if ( event->type==et_close ) {\n\tSD_DoCancel( sd );\n } else if ( event->type==et_char ) {\n\tif ( event->u.chr.keysym == GK_F1 || event->u.chr.keysym == GK_Help ) {\n\t help(\"scripting.html\");\nreturn( true );\n\t}\nreturn( false );\n } else if ( event->type == et_map )\t/* Above palettes */\n\tGDrawRaise(gw);\n else if ( event->type == et_resize )\n\tGDrawRequestExpose(gw,NULL,false);\nreturn( true );\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(errors::Unimplemented(\n \"The Conv2D op currently only supports the NHWC tensor format on the \"\n \"CPU. The op was given the format: \",\n ToString(data_format)));\n return;\n }\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\n const int64 in_depth = input.dim_size(3);\n const int64 out_depth = output->dim_size(3);\n const int64 patch_depth = filter.dim_size(2);\n\n if (in_depth % patch_depth != 0) {\n ctx->SetStatus(errors::InvalidArgument(\n \"input depth must be evenly divisible by filter depth: \", in_depth,\n \" vs \", patch_depth));\n return;\n }\n\n const int64 num_groups = in_depth / patch_depth;\n if (out_depth % num_groups != 0 || out_depth < num_groups) {\n ctx->SetStatus(errors::InvalidArgument(\n \"output depth must be evenly divisible by number of groups: \",\n out_depth, \" vs \", num_groups));\n return;\n }\n\n if (in_depth != patch_depth) {\n LaunchGrouped()(ctx, input, filter, row_stride, col_stride,\n row_dilation, col_dilation, padding, explicit_paddings,\n output, data_format);\n } else {\n LaunchGeneric()(ctx, input, filter, row_stride, col_stride,\n row_dilation, col_dilation, padding,\n explicit_paddings, output, data_format);\n }\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: ut32 armass_assemble(const char *str, ut64 off, int thumb) {\n\tint i, j;\n\tchar buf[128];\n\tArmOpcode aop = {.off = off};\n\tfor (i = j = 0; i < sizeof (buf) - 1 && str[i]; i++, j++) {\n\t\tif (str[j] == '#') {\n\t\t\ti--; continue;\n\t\t}\n\t\tbuf[i] = tolower ((const ut8)str[j]);\n\t}\n\tbuf[i] = 0;\n\tarm_opcode_parse (&aop, buf);\n\taop.off = off;\n\tif (thumb < 0 || thumb > 1) {\n\t\treturn -1;\n\t}\n\tif (!assemble[thumb] (&aop, off, buf)) {\n\t\t//eprintf (\"armass: Unknown opcode (%s)\\n\", buf);\n\t\treturn -1;\n\t}\n\treturn aop.o;\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 RtmpProtocol::handle_chunk(RtmpPacket::Ptr packet) {\n auto &chunk_data = *packet;\n switch (chunk_data.type_id) {\n case MSG_ACK: {\n if (chunk_data.buffer.size() < 4) {\n throw std::runtime_error(\"MSG_ACK: Not enough data\");\n }\n //auto bytePeerRecv = load_be32(&chunk_data.buffer[0]);\n //TraceL << \"MSG_ACK:\" << bytePeerRecv;\n break;\n }\n\n case MSG_SET_CHUNK: {\n if (chunk_data.buffer.size() < 4) {\n throw std::runtime_error(\"MSG_SET_CHUNK :Not enough data\");\n }\n _chunk_size_in = load_be32(&chunk_data.buffer[0]);\n TraceL << \"MSG_SET_CHUNK:\" << _chunk_size_in;\n break;\n }\n\n case MSG_USER_CONTROL: {\n //user control message\n if (chunk_data.buffer.size() < 2) {\n throw std::runtime_error(\"MSG_USER_CONTROL: Not enough data.\");\n }\n uint16_t event_type = load_be16(&chunk_data.buffer[0]);\n chunk_data.buffer.erase(0, 2);\n switch (event_type) {\n case CONTROL_PING_REQUEST: {\n if (chunk_data.buffer.size() < 4) {\n throw std::runtime_error(\"CONTROL_PING_REQUEST: Not enough data.\");\n }\n uint32_t timeStamp = load_be32(&chunk_data.buffer[0]);\n //TraceL << \"CONTROL_PING_REQUEST:\" << time_stamp;\n sendUserControl(CONTROL_PING_RESPONSE, timeStamp);\n break;\n }\n\n case CONTROL_PING_RESPONSE: {\n if (chunk_data.buffer.size() < 4) {\n throw std::runtime_error(\"CONTROL_PING_RESPONSE: Not enough data.\");\n }\n //uint32_t time_stamp = load_be32(&chunk_data.buffer[0]);\n //TraceL << \"CONTROL_PING_RESPONSE:\" << time_stamp;\n break;\n }\n\n case CONTROL_STREAM_BEGIN: {\n //\u5f00\u59cb\u64ad\u653e\n if (chunk_data.buffer.size() < 4) {\n WarnL << \"CONTROL_STREAM_BEGIN: Not enough data:\" << chunk_data.buffer.size();\n break;\n }\n uint32_t stream_index = load_be32(&chunk_data.buffer[0]);\n onStreamBegin(stream_index);\n TraceL << \"CONTROL_STREAM_BEGIN:\" << stream_index;\n break;\n }\n\n case CONTROL_STREAM_EOF: {\n //\u6682\u505c\n if (chunk_data.buffer.size() < 4) {\n throw std::runtime_error(\"CONTROL_STREAM_EOF: Not enough data.\");\n }\n uint32_t stream_index = load_be32(&chunk_data.buffer[0]);\n onStreamEof(stream_index);\n TraceL << \"CONTROL_STREAM_EOF:\" << stream_index;\n break;\n }\n\n case CONTROL_STREAM_DRY: {\n //\u505c\u6b62\u64ad\u653e\n if (chunk_data.buffer.size() < 4) {\n throw std::runtime_error(\"CONTROL_STREAM_DRY: Not enough data.\");\n }\n uint32_t stream_index = load_be32(&chunk_data.buffer[0]);\n onStreamDry(stream_index);\n TraceL << \"CONTROL_STREAM_DRY:\" << stream_index;\n break;\n }\n\n default: /*WarnL << \"unhandled user control:\" << event_type; */ break;\n }\n break;\n }\n\n case MSG_WIN_SIZE: {\n _windows_size = load_be32(&chunk_data.buffer[0]);\n TraceL << \"MSG_WIN_SIZE:\" << _windows_size;\n break;\n }\n\n case MSG_SET_PEER_BW: {\n _bandwidth = load_be32(&chunk_data.buffer[0]);\n _band_limit_type = chunk_data.buffer[4];\n TraceL << \"MSG_SET_PEER_BW:\" << _windows_size;\n break;\n }\n\n case MSG_AGGREGATE: {\n auto ptr = (uint8_t *) chunk_data.buffer.data();\n auto ptr_tail = ptr + chunk_data.buffer.size();\n uint32_t latest_ts, timestamp;\n timestamp = chunk_data.time_stamp;\n bool first_message = true;\n while (ptr + 8 + 3 < ptr_tail) {\n auto type = *ptr;\n ptr += 1;\n auto size = load_be24(ptr);\n ptr += 3;\n auto ts = load_be24(ptr);\n ptr += 3;\n ts |= (*ptr << 24);\n ptr += 1;\n ptr += 3;\n //\u53c2\u8003FFmpeg\u591a\u62f7\u8d1d\u4e864\u4e2a\u5b57\u8282\n size += 4;\n if (ptr + size > ptr_tail) {\n break;\n }\n if (!first_message) {\n timestamp += ts - latest_ts;\n }\n first_message = false;\n latest_ts = ts;\n auto sub_packet_ptr = RtmpPacket::create();\n auto &sub_packet = *sub_packet_ptr;\n sub_packet.buffer.assign((char *)ptr, size);\n sub_packet.type_id = type;\n sub_packet.body_size = size;\n sub_packet.time_stamp = timestamp;\n sub_packet.stream_index = chunk_data.stream_index;\n sub_packet.chunk_id = chunk_data.chunk_id;\n handle_chunk(std::move(sub_packet_ptr));\n ptr += size;\n }\n break;\n }\n\n default: onRtmpChunk(std::move(packet)); break;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': '\u4fee\u590drtmp\u6c47\u62a5\u7a97\u53e3\u592a\u5c0f\u5bfc\u81f4\u5faa\u73af\u9012\u5f52\u7684bug\uff1a#1839'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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::IsOutsideEnclave(\n output_len, sizeof(uint64_t))) {\n asylo::primitives::TrustedPrimitives::BestEffortAbort(\n \"ecall_restore: input/output 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-787'], 'message': 'Check output of ecall_restore is outside enclave\n\nPiperOrigin-RevId: 334265380\nChange-Id: Ifbaead6bce56f01b2a4d69f53ca508d0138f6f61'" }, { "text": "[INST] Given the following code containing errors, provide Common 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::removePage(QPDFObjectHandle page)\n{\n int pos = findPage(page); // also ensures flat /Pages\n QTC::TC(\"qpdf\", \"QPDF remove page\",\n (pos == 0) ? 0 : // remove at beginning\n (pos == static_cast(\n this->m->all_pages.size() - 1)) ? 1 : // end\n 2); // remove in middle\n\n QPDFObjectHandle pages = getRoot().getKey(\"/Pages\");\n QPDFObjectHandle kids = pages.getKey(\"/Kids\");\n\n kids.eraseItem(pos);\n int npages = kids.getArrayNItems();\n pages.replaceKey(\"/Count\", QPDFObjectHandle::newInteger(npages));\n this->m->all_pages.erase(this->m->all_pages.begin() + pos);\n assert(this->m->all_pages.size() == static_cast(npages));\n this->m->pageobj_to_pages_pos.erase(page.getObjGen());\n assert(this->m->pageobj_to_pages_pos.size() == static_cast(npages));\n for (int i = pos; i < npages; ++i)\n {\n insertPageobjToPage(this->m->all_pages.at(i), i, false);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int main(int argc, char* argv[])\n{\n whoami = QUtil::getWhoami(argv[0]);\n\n // For libtool's sake....\n if (strncmp(whoami, \"lt-\", 3) == 0)\n {\n\twhoami += 3;\n }\n\n if (argc != 3)\n {\n\tusage();\n }\n char const* filename = argv[1];\n int pageno = QUtil::string_to_int(argv[2]);\n\n try\n {\n\tQPDF pdf;\n\tpdf.processFile(filename);\n std::vector pages =\n QPDFPageDocumentHelper(pdf).getAllPages();\n if ((pageno < 1) || (static_cast(pageno) > pages.size()))\n {\n usage();\n }\n\n QPDFPageObjectHelper& page = pages.at(pageno-1);\n ParserCallbacks cb;\n page.parsePageContents(&cb);\n }\n catch (std::exception& e)\n {\n\tstd::cerr << whoami << \": \" << e.what() << std::endl;\n\texit(2);\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: RC4::RC4(unsigned char const* key_data, int key_len)\n{\n if (key_len == -1)\n {\n\tkey_len = strlen(reinterpret_cast(key_data));\n }\n\n for (int i = 0; i < 256; ++i)\n {\n key.state[i] = i;\n }\n key.x = 0;\n key.y = 0;\n\n int i1 = 0;\n int i2 = 0;\n for (int i = 0; i < 256; ++i)\n {\n\ti2 = (key_data[i1] + key.state[i] + i2) % 256;\n\tswap_byte(key.state[i], key.state[i2]);\n\ti1 = (i1 + 1) % key_len;\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: pad_or_truncate_password_V4(std::string const& password)\n{\n char k1[key_bytes];\n pad_or_truncate_password_V4(password, k1);\n return std::string(k1, key_bytes);\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: BitWriter::flush()\n{\n if (bit_offset < 7)\n {\n\tint bits_to_write = bit_offset + 1;\n\twrite_bits(this->ch, this->bit_offset, 0, bits_to_write, this->pl);\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: pad_or_truncate_password_V4(std::string const& password, char k1[key_bytes])\n{\n int password_bytes = std::min(static_cast(key_bytes),\n password.length());\n int pad_bytes = key_bytes - password_bytes;\n memcpy(k1, password.c_str(), password_bytes);\n memcpy(k1 + password_bytes, padding_string, pad_bytes);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ArgParser::argOiMinHeight(char* parameter)\n{\n o.oi_min_height = QUtil::string_to_int(parameter);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Pl_LZWDecoder::handleCode(int code)\n{\n if (this->eod)\n {\n\treturn;\n }\n\n if (code == 256)\n {\n\tif (! this->table.empty())\n\t{\n\t QTC::TC(\"libtests\", \"Pl_LZWDecoder intermediate reset\");\n\t}\n\tthis->table.clear();\n\tthis->code_size = 9;\n }\n else if (code == 257)\n {\n\tthis->eod = true;\n }\n else\n {\n\tif (this->last_code != 256)\n\t{\n\t // Add to the table from last time. New table entry would\n\t // be what we read last plus the first character of what\n\t // we're reading now.\n\t unsigned char next = '\\0';\n\t unsigned int table_size = table.size();\n\t if (code < 256)\n\t {\n\t\t// just read < 256; last time's next was code\n\t\tnext = code;\n\t }\n\t else if (code > 257)\n\t {\n\t\tsize_t idx = code - 258;\n\t\tif (idx > table_size)\n\t\t{\n\t\t throw std::runtime_error(\"LZWDecoder: bad code received\");\n\t\t}\n\t\telse if (idx == table_size)\n\t\t{\n\t\t // The encoder would have just created this entry,\n\t\t // so the first character of this entry would have\n\t\t // been the same as the first character of the\n\t\t // last entry.\n\t\t QTC::TC(\"libtests\", \"Pl_LZWDecoder last was table size\");\n\t\t next = getFirstChar(this->last_code);\n\t\t}\n\t\telse\n\t\t{\n\t\t next = getFirstChar(code);\n\t\t}\n\t }\n\t unsigned int new_idx = 258 + table_size;\n\t if (new_idx == 4096)\n\t {\n\t\tthrow std::runtime_error(\"LZWDecoder: table full\");\n\t }\n\t addToTable(next);\n\t unsigned int change_idx = new_idx + code_change_delta;\n\t if ((change_idx == 511) ||\n\t\t(change_idx == 1023) ||\n\t\t(change_idx == 2047))\n\t {\n\t\t++this->code_size;\n\t }\n\t}\n\n\tif (code < 256)\n\t{\n\t unsigned char ch = static_cast(code);\n\t getNext()->write(&ch, 1);\n\t}\n\telse\n\t{\n\t Buffer& b = table.at(code - 258);\n\t getNext()->write(b.getBuffer(), b.getSize());\n\t}\n }\n\n this->last_code = code;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: iterate_md5_digest(MD5& md5, MD5::Digest& digest, int iterations, int key_len)\n{\n md5.digest(digest);\n\n for (int i = 0; i < iterations; ++i)\n {\n\tMD5 m;\n\tm.encodeDataIncrementally(reinterpret_cast(digest),\n key_len);\n\tm.digest(digest);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Pl_PNGFilter::encodeRow()\n{\n // For now, hard-code to using UP filter.\n unsigned char ch = 2;\n getNext()->write(&ch, 1);\n if (this->prev_row)\n {\n\tfor (unsigned int i = 0; i < this->bytes_per_row; ++i)\n\t{\n\t ch = this->cur_row[i] - this->prev_row[i];\n\t getNext()->write(&ch, 1);\n\t}\n }\n else\n {\n\tgetNext()->write(this->cur_row, this->bytes_per_row);\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::recoverStreamLength(PointerHolder input,\n\t\t\t int objid, int generation,\n qpdf_offset_t stream_offset)\n{\n // Try to reconstruct stream length by looking for\n // endstream or endobj\n warn(QPDFExc(qpdf_e_damaged_pdf, input->getName(),\n\t\t this->m->last_object_description, stream_offset,\n\t\t \"attempting to recover stream length\"));\n\n PatternFinder ef(*this, &QPDF::findEndstream);\n size_t length = 0;\n if (this->m->file->findFirst(\"end\", stream_offset, 0, ef))\n {\n length = this->m->file->tell() - stream_offset;\n // Reread endstream but, if it was endobj, don't skip that.\n QPDFTokenizer::Token t = readToken(this->m->file);\n if (t.getValue() == \"endobj\")\n {\n this->m->file->seek(this->m->file->getLastOffset(), SEEK_SET);\n }\n }\n\n if (length)\n {\n\tint this_obj_offset = 0;\n\tQPDFObjGen this_obj(0, 0);\n\n\t// Make sure this is inside this object\n\tfor (std::map::iterator iter =\n\t\t this->m->xref_table.begin();\n\t iter != this->m->xref_table.end(); ++iter)\n\t{\n\t QPDFObjGen const& og = (*iter).first;\n\t QPDFXRefEntry const& entry = (*iter).second;\n\t if (entry.getType() == 1)\n\t {\n\t\tqpdf_offset_t obj_offset = entry.getOffset();\n\t\tif ((obj_offset > stream_offset) &&\n\t\t ((this_obj_offset == 0) ||\n\t\t (this_obj_offset > obj_offset)))\n\t\t{\n\t\t this_obj_offset = obj_offset;\n\t\t this_obj = og;\n\t\t}\n\t }\n\t}\n\tif (this_obj_offset &&\n\t (this_obj.getObj() == objid) &&\n\t (this_obj.getGen() == generation))\n\t{\n\t // Well, we found endstream\\nendobj within the space\n\t // allowed for this object, so we're probably in good\n\t // shape.\n\t}\n\telse\n\t{\n\t QTC::TC(\"qpdf\", \"QPDF found wrong endstream in recovery\");\n\t}\n }\n\n if (length == 0)\n {\n warn(QPDFExc(qpdf_e_damaged_pdf, input->getName(),\n this->m->last_object_description, stream_offset,\n \"unable to recover stream data;\"\n \" treating stream as empty\"));\n }\n else\n {\n warn(QPDFExc(qpdf_e_damaged_pdf, input->getName(),\n this->m->last_object_description, stream_offset,\n \"recovered stream length: \" +\n QUtil::int_to_string(length)));\n }\n\n QTC::TC(\"qpdf\", \"QPDF recovered stream length\");\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: QUtil::utf16_to_utf8(std::string const& val)\n{\n std::string result;\n // This code uses unsigned long and unsigned short to hold\n // codepoint values. It requires unsigned long to be at least\n // 32 bits and unsigned short to be at least 16 bits, but it\n // will work fine if they are larger.\n unsigned long codepoint = 0L;\n size_t len = val.length();\n size_t start = 0;\n if (is_utf16(val))\n {\n start += 2;\n }\n // If the string has an odd number of bytes, the last byte is\n // ignored.\n for (unsigned int i = start; i < len; i += 2)\n {\n // Convert from UTF16-BE. If we get a malformed\n // codepoint, this code will generate incorrect output\n // without giving a warning. Specifically, a high\n // codepoint not followed by a low codepoint will be\n // discarded, and a low codepoint not preceded by a high\n // codepoint will just get its low 10 bits output.\n unsigned short bits =\n (static_cast(val.at(i)) << 8) +\n static_cast(val.at(i+1));\n if ((bits & 0xFC00) == 0xD800)\n {\n codepoint = 0x10000 + ((bits & 0x3FF) << 10);\n continue;\n }\n else if ((bits & 0xFC00) == 0xDC00)\n {\n if (codepoint != 0)\n {\n QTC::TC(\"qpdf\", \"QUtil non-trivial UTF-16\");\n }\n codepoint += bits & 0x3FF;\n }\n else\n {\n codepoint = bits;\n }\n\n result += QUtil::toUTF8(codepoint);\n codepoint = 0;\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: QPDFFormFieldObjectHelper::getChoices()\n{\n std::vector result;\n if (! isChoice())\n {\n return result;\n }\n QPDFObjectHandle opt = getInheritableFieldValue(\"/Opt\");\n if (opt.isArray())\n {\n size_t n = opt.getArrayNItems();\n for (size_t i = 0; i < n; ++i)\n {\n QPDFObjectHandle item = opt.getArrayItem(i);\n if (item.isString())\n {\n result.push_back(item.getUTF8Value());\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: QPDFWriter::unparseObject(QPDFObjectHandle object, int level,\n\t\t\t unsigned int flags, size_t stream_length,\n bool compress)\n{\n QPDFObjGen old_og = object.getObjGen();\n unsigned int child_flags = flags & ~f_stream;\n\n std::string indent;\n for (int i = 0; i < level; ++i)\n {\n\tindent += \" \";\n }\n\n if (object.isArray())\n {\n\t// Note: PDF spec 1.4 implementation note 121 states that\n\t// Acrobat requires a space after the [ in the /H key of the\n\t// linearization parameter dictionary. We'll do this\n\t// unconditionally for all arrays because it looks nicer and\n\t// doesn't make the files that much bigger.\n\twriteString(\"[\");\n\twriteStringQDF(\"\\n\");\n\tint n = object.getArrayNItems();\n\tfor (int i = 0; i < n; ++i)\n\t{\n\t writeStringQDF(indent);\n\t writeStringQDF(\" \");\n\t writeStringNoQDF(\" \");\n\t unparseChild(object.getArrayItem(i), level + 1, child_flags);\n\t writeStringQDF(\"\\n\");\n\t}\n\twriteStringQDF(indent);\n\twriteStringNoQDF(\" \");\n\twriteString(\"]\");\n }\n else if (object.isDictionary())\n {\n // Make a shallow copy of this object so we can modify it\n // safely without affecting the original. This code makes\n // assumptions about things that are made true in\n // prepareFileForWrite, such as that certain things are direct\n // objects so that replacing them doesn't leave unreferenced\n // objects in the output.\n object = object.shallowCopy();\n\n // Handle special cases for specific dictionaries.\n\n // Extensions dictionaries.\n\n // We have one of several cases:\n //\n // * We need ADBE\n // - We already have Extensions\n // - If it has the right ADBE, preserve it\n // - Otherwise, replace ADBE\n // - We don't have Extensions: create one from scratch\n // * We don't want ADBE\n // - We already have Extensions\n // - If it only has ADBE, remove it\n // - If it has other things, keep those and remove ADBE\n // - We have no extensions: no action required\n //\n // Before writing, we guarantee that /Extensions, if present,\n // is direct through the ADBE dictionary, so we can modify in\n // place.\n\n bool is_root = false;\n bool have_extensions_other = false;\n bool have_extensions_adbe = false;\n\n QPDFObjectHandle extensions;\n if (old_og == this->m->pdf.getRoot().getObjGen())\n {\n is_root = true;\n if (object.hasKey(\"/Extensions\") &&\n object.getKey(\"/Extensions\").isDictionary())\n {\n extensions = object.getKey(\"/Extensions\");\n }\n }\n\n if (extensions.isInitialized())\n {\n std::set keys = extensions.getKeys();\n if (keys.count(\"/ADBE\") > 0)\n {\n have_extensions_adbe = true;\n keys.erase(\"/ADBE\");\n }\n if (keys.size() > 0)\n {\n have_extensions_other = true;\n }\n }\n\n bool need_extensions_adbe = (this->m->final_extension_level > 0);\n\n if (is_root)\n {\n if (need_extensions_adbe)\n {\n if (! (have_extensions_other || have_extensions_adbe))\n {\n // We need Extensions and don't have it. Create\n // it here.\n QTC::TC(\"qpdf\", \"QPDFWriter create Extensions\",\n this->m->qdf_mode ? 0 : 1);\n extensions = QPDFObjectHandle::newDictionary();\n object.replaceKey(\"/Extensions\", extensions);\n }\n }\n else if (! have_extensions_other)\n {\n // We have Extensions dictionary and don't want one.\n if (have_extensions_adbe)\n {\n QTC::TC(\"qpdf\", \"QPDFWriter remove existing Extensions\");\n object.removeKey(\"/Extensions\");\n extensions = QPDFObjectHandle(); // uninitialized\n }\n }\n }\n\n if (extensions.isInitialized())\n {\n QTC::TC(\"qpdf\", \"QPDFWriter preserve Extensions\");\n QPDFObjectHandle adbe = extensions.getKey(\"/ADBE\");\n if (adbe.isDictionary() &&\n adbe.hasKey(\"/BaseVersion\") &&\n adbe.getKey(\"/BaseVersion\").isName() &&\n (adbe.getKey(\"/BaseVersion\").getName() ==\n \"/\" + this->m->final_pdf_version) &&\n adbe.hasKey(\"/ExtensionLevel\") &&\n adbe.getKey(\"/ExtensionLevel\").isInteger() &&\n (adbe.getKey(\"/ExtensionLevel\").getIntValue() ==\n this->m->final_extension_level))\n {\n QTC::TC(\"qpdf\", \"QPDFWriter preserve ADBE\");\n }\n else\n {\n if (need_extensions_adbe)\n {\n extensions.replaceKey(\n \"/ADBE\",\n QPDFObjectHandle::parse(\n \"<< /BaseVersion /\" + this->m->final_pdf_version +\n \" /ExtensionLevel \" +\n QUtil::int_to_string(\n this->m->final_extension_level) +\n \" >>\"));\n }\n else\n {\n QTC::TC(\"qpdf\", \"QPDFWriter remove ADBE\");\n extensions.removeKey(\"/ADBE\");\n }\n }\n }\n\n // Stream dictionaries.\n\n if (flags & f_stream)\n {\n // Suppress /Length since we will write it manually\n object.removeKey(\"/Length\");\n\n // If /DecodeParms is an empty list, remove it.\n if (object.getKey(\"/DecodeParms\").isArray() &&\n (0 == object.getKey(\"/DecodeParms\").getArrayNItems()))\n {\n QTC::TC(\"qpdf\", \"QPDFWriter remove empty DecodeParms\");\n object.removeKey(\"/DecodeParms\");\n }\n\n\t if (flags & f_filtered)\n {\n // We will supply our own filter and decode\n // parameters.\n object.removeKey(\"/Filter\");\n object.removeKey(\"/DecodeParms\");\n }\n else\n {\n // Make sure, no matter what else we have, that we\n // don't have /Crypt in the output filters.\n QPDFObjectHandle filter = object.getKey(\"/Filter\");\n QPDFObjectHandle decode_parms = object.getKey(\"/DecodeParms\");\n if (filter.isOrHasName(\"/Crypt\"))\n {\n if (filter.isName())\n {\n object.removeKey(\"/Filter\");\n object.removeKey(\"/DecodeParms\");\n }\n else\n {\n int idx = -1;\n for (int i = 0; i < filter.getArrayNItems(); ++i)\n {\n QPDFObjectHandle item = filter.getArrayItem(i);\n if (item.isName() && item.getName() == \"/Crypt\")\n {\n idx = i;\n break;\n }\n }\n if (idx >= 0)\n {\n // If filter is an array, then the code in\n // QPDF_Stream has already verified that\n // DecodeParms and Filters are arrays of\n // the same length, but if they weren't\n // for some reason, eraseItem does type\n // and bounds checking.\n QTC::TC(\"qpdf\", \"QPDFWriter remove Crypt\");\n filter.eraseItem(idx);\n decode_parms.eraseItem(idx);\n }\n }\n }\n }\n }\n\n\twriteString(\"<<\");\n\twriteStringQDF(\"\\n\");\n\n\tstd::set keys = object.getKeys();\n\tfor (std::set::iterator iter = keys.begin();\n\t iter != keys.end(); ++iter)\n\t{\n\t std::string const& key = *iter;\n\n\t writeStringQDF(indent);\n\t writeStringQDF(\" \");\n\t writeStringNoQDF(\" \");\n\t writeString(QPDF_Name::normalizeName(key));\n\t writeString(\" \");\n unparseChild(object.getKey(key), level + 1, child_flags);\n\t writeStringQDF(\"\\n\");\n\t}\n\n\tif (flags & f_stream)\n\t{\n\t writeStringQDF(indent);\n\t writeStringQDF(\" \");\n\t writeString(\" /Length \");\n\n\t if (this->m->direct_stream_lengths)\n\t {\n\t\twriteString(QUtil::int_to_string(stream_length));\n\t }\n\t else\n\t {\n\t\twriteString(\n\t\t QUtil::int_to_string(this->m->cur_stream_length_id));\n\t\twriteString(\" 0 R\");\n\t }\n\t writeStringQDF(\"\\n\");\n\t if (compress && (flags & f_filtered))\n\t {\n\t\twriteStringQDF(indent);\n\t\twriteStringQDF(\" \");\n\t\twriteString(\" /Filter /FlateDecode\");\n\t\twriteStringQDF(\"\\n\");\n\t }\n\t}\n\n\twriteStringQDF(indent);\n\twriteStringNoQDF(\" \");\n\twriteString(\">>\");\n }\n else if (object.isStream())\n {\n\t// Write stream data to a buffer.\n\tint new_id = this->m->obj_renumber[old_og];\n\tif (! this->m->direct_stream_lengths)\n\t{\n\t this->m->cur_stream_length_id = new_id + 1;\n\t}\n\tQPDFObjectHandle stream_dict = object.getDict();\n\n\tbool is_metadata = false;\n\tif (stream_dict.getKey(\"/Type\").isName() &&\n\t (stream_dict.getKey(\"/Type\").getName() == \"/Metadata\"))\n\t{\n\t is_metadata = true;\n\t}\n\tbool filter = (object.isDataModified() ||\n this->m->compress_streams ||\n this->m->stream_decode_level);\n\tif (this->m->compress_streams)\n\t{\n\t // Don't filter if the stream is already compressed with\n\t // FlateDecode. We don't want to make it worse by getting\n\t // rid of a predictor or otherwise messing with it. We\n\t // should also avoid messing with anything that's\n\t // compressed with a lossy compression scheme, but we\n\t // don't support any of those right now.\n\t QPDFObjectHandle filter_obj = stream_dict.getKey(\"/Filter\");\n if ((! object.isDataModified()) &&\n filter_obj.isName() &&\n\t\t((filter_obj.getName() == \"/FlateDecode\") ||\n\t\t (filter_obj.getName() == \"/Fl\")))\n\t {\n\t\tQTC::TC(\"qpdf\", \"QPDFWriter not recompressing /FlateDecode\");\n\t\tfilter = false;\n\t }\n\t}\n\tbool normalize = false;\n\tbool compress = false;\n bool uncompress = false;\n\tif (is_metadata &&\n\t ((! this->m->encrypted) || (this->m->encrypt_metadata == false)))\n\t{\n\t QTC::TC(\"qpdf\", \"QPDFWriter not compressing metadata\");\n\t filter = true;\n\t compress = false;\n uncompress = true;\n\t}\n\telse if (this->m->normalize_content &&\n this->m->normalized_streams.count(old_og))\n\t{\n\t normalize = true;\n\t filter = true;\n\t}\n\telse if (filter && this->m->compress_streams)\n\t{\n\t compress = true;\n\t QTC::TC(\"qpdf\", \"QPDFWriter compressing uncompressed stream\");\n\t}\n\n\tflags |= f_stream;\n\n PointerHolder stream_data;\n bool filtered = false;\n for (int attempt = 1; attempt <= 2; ++attempt)\n {\n pushPipeline(new Pl_Buffer(\"stream data\"));\n activatePipelineStack();\n\n filtered =\n object.pipeStreamData(\n this->m->pipeline,\n (((filter && normalize) ? qpdf_ef_normalize : 0) |\n ((filter && compress) ? qpdf_ef_compress : 0)),\n (filter\n ? (uncompress ? qpdf_dl_all : this->m->stream_decode_level)\n : qpdf_dl_none), false, (attempt == 1));\n popPipelineStack(&stream_data);\n if (filter && (! filtered))\n {\n // Try again\n filter = false;\n }\n else\n {\n break;\n }\n }\n\tif (filtered)\n\t{\n\t flags |= f_filtered;\n\t}\n\telse\n\t{\n\t compress = false;\n\t}\n\n\tthis->m->cur_stream_length = stream_data->getSize();\n\tif (is_metadata && this->m->encrypted && (! this->m->encrypt_metadata))\n\t{\n\t // Don't encrypt stream data for the metadata stream\n\t this->m->cur_data_key.clear();\n\t}\n\tadjustAESStreamLength(this->m->cur_stream_length);\n\tunparseObject(stream_dict, 0, flags,\n this->m->cur_stream_length, compress);\n\twriteString(\"\\nstream\\n\");\n\tpushEncryptionFilter();\n\twriteBuffer(stream_data);\n\tchar last_char = this->m->pipeline->getLastChar();\n\tpopPipelineStack();\n\n if (this->m->newline_before_endstream ||\n (this->m->qdf_mode && (last_char != '\\n')))\n {\n writeString(\"\\n\");\n this->m->added_newline = true;\n }\n else\n {\n this->m->added_newline = false;\n }\n\twriteString(\"endstream\");\n }\n else if (object.isString())\n {\n\tstd::string val;\n\tif (this->m->encrypted &&\n\t (! (flags & f_in_ostream)) &&\n\t (! this->m->cur_data_key.empty()))\n\t{\n\t val = object.getStringValue();\n\t if (this->m->encrypt_use_aes)\n\t {\n\t\tPl_Buffer bufpl(\"encrypted string\");\n\t\tPl_AES_PDF pl(\n \"aes encrypt string\", &bufpl, true,\n QUtil::unsigned_char_pointer(this->m->cur_data_key),\n this->m->cur_data_key.length());\n\t\tpl.write(QUtil::unsigned_char_pointer(val), val.length());\n\t\tpl.finish();\n\t\tBuffer* buf = bufpl.getBuffer();\n\t\tval = QPDF_String(\n\t\t std::string(reinterpret_cast(buf->getBuffer()),\n\t\t\t\tbuf->getSize())).unparse(true);\n\t\tdelete buf;\n\t }\n\t else\n\t {\n\t\tchar* tmp = QUtil::copy_string(val);\n\t\tsize_t vlen = val.length();\n\t\tRC4 rc4(QUtil::unsigned_char_pointer(this->m->cur_data_key),\n\t\t\tthis->m->cur_data_key.length());\n\t\trc4.process(QUtil::unsigned_char_pointer(tmp), vlen);\n\t\tval = QPDF_String(std::string(tmp, vlen)).unparse();\n\t\tdelete [] tmp;\n\t }\n\t}\n\telse\n\t{\n\t val = object.unparseResolved();\n\t}\n\twriteString(val);\n }\n else\n {\n\twriteString(object.unparseResolved());\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: QPDFAnnotationObjectHelper::getFlags()\n{\n QPDFObjectHandle flags_obj = this->oh.getKey(\"/F\");\n return flags_obj.isInteger() ? flags_obj.getIntValue() : 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ImageInverter::provideStreamData(int objid, int generation,\n\t\t\t\t Pipeline* pipeline)\n{\n // Use the object and generation number supplied to look up the\n // image data. Then invert the image data and write the inverted\n // data to the pipeline.\n PointerHolder data =\n this->image_data[QPDFObjGen(objid, generation)];\n size_t size = data->getSize();\n unsigned char* buf = data->getBuffer();\n unsigned char ch;\n for (size_t i = 0; i < size; ++i)\n {\n\tch = static_cast(0xff) - buf[i];\n\tpipeline->write(&ch, 1);\n }\n pipeline->finish();\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_DCT::decompress(void* cinfo_p, Buffer* b)\n{\n struct jpeg_decompress_struct* cinfo =\n reinterpret_cast(cinfo_p);\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#endif\n jpeg_create_decompress(cinfo);\n#if ((defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || \\\n defined(__clang__))\n# pragma GCC diagnostic pop\n#endif\n jpeg_buffer_src(cinfo, b);\n\n (void) jpeg_read_header(cinfo, TRUE);\n (void) jpeg_calc_output_dimensions(cinfo);\n\n int width = cinfo->output_width * cinfo->output_components;\n JSAMPARRAY buffer = (*cinfo->mem->alloc_sarray)\n (reinterpret_cast(cinfo), JPOOL_IMAGE, width, 1);\n\n (void) jpeg_start_decompress(cinfo);\n while (cinfo->output_scanline < cinfo->output_height)\n {\n (void) jpeg_read_scanlines(cinfo, buffer, 1);\n this->getNext()->write(reinterpret_cast(buffer[0]),\n width * sizeof(buffer[0][0]));\n }\n (void) jpeg_finish_decompress(cinfo);\n this->getNext()->finish();\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::lengthNextN(int first_object, int n,\n\t\t std::list& errors)\n{\n int length = 0;\n for (int i = 0; i < n; ++i)\n {\n\tQPDFObjGen og(first_object + i, 0);\n\tif (this->m->xref_table.count(og) == 0)\n\t{\n\t errors.push_back(\n\t\t\"no xref table entry for \" +\n\t\tQUtil::int_to_string(first_object + i) + \" 0\");\n\t}\n\telse\n\t{\n\t if (this->m->obj_cache.count(og) == 0)\n {\n stopOnError(\"found unknown object while\"\n \" calculating length for linearization data\");\n }\n\t length += this->m->obj_cache[og].end_after_space -\n\t\tgetLinearizationOffset(og);\n\t}\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: int main(int argc, char* argv[])\n{\n bool encrypt = true;\n bool cbc_mode = true;\n char* hexkey = 0;\n char* infilename = 0;\n char* outfilename = 0;\n bool zero_iv = false;\n bool static_iv = false;\n bool disable_padding = false;\n\n for (int i = 1; i < argc; ++i)\n {\n char* arg = argv[i];\n if ((arg[0] == '-') || (arg[0] == '+'))\n {\n if (strcmp(arg, \"-cbc\") == 0)\n {\n cbc_mode = false;\n }\n else if (strcmp(arg, \"+cbc\") == 0)\n {\n cbc_mode = true;\n }\n else if (strcmp(arg, \"-decrypt\") == 0)\n {\n encrypt = false;\n }\n else if (strcmp(arg, \"-encrypt\") == 0)\n {\n encrypt = true;\n }\n else if (strcmp(arg, \"-zero-iv\") == 0)\n {\n zero_iv = true;\n }\n else if (strcmp(arg, \"-static-iv\") == 0)\n {\n static_iv = true;\n }\n else if (strcmp(arg, \"-no-padding\") == 0)\n {\n disable_padding = true;\n }\n else\n {\n usage();\n }\n }\n else if (argc == i + 3)\n {\n hexkey = argv[i];\n infilename = argv[i+1];\n outfilename = argv[i+2];\n break;\n }\n else\n {\n usage();\n }\n }\n if (outfilename == 0)\n {\n usage();\n }\n\n unsigned int hexkeylen = strlen(hexkey);\n unsigned int keylen = hexkeylen / 2;\n\n FILE* infile = QUtil::safe_fopen(infilename, \"rb\");\n FILE* outfile = QUtil::safe_fopen(outfilename, \"wb\");\n unsigned char* key = new unsigned char[keylen];\n for (unsigned int i = 0; i < strlen(hexkey); i += 2)\n {\n\tchar t[3];\n\tt[0] = hexkey[i];\n\tt[1] = hexkey[i + 1];\n\tt[2] = '\\0';\n\n\tlong val = strtol(t, 0, 16);\n\tkey[i/2] = static_cast(val);\n }\n\n Pl_StdioFile* out = new Pl_StdioFile(\"stdout\", outfile);\n Pl_AES_PDF* aes = new Pl_AES_PDF(\"aes_128_cbc\", out, encrypt, key, keylen);\n delete [] key;\n key = 0;\n if (! cbc_mode)\n {\n\taes->disableCBC();\n }\n if (zero_iv)\n {\n aes->useZeroIV();\n }\n else if (static_iv)\n {\n aes->useStaticIV();\n }\n if (disable_padding)\n {\n aes->disablePadding();\n }\n\n // 16 < buffer size, buffer_size is not a multiple of 8 for testing\n unsigned char buf[83];\n bool done = false;\n while (! done)\n {\n\tsize_t len = fread(buf, 1, sizeof(buf), infile);\n\tif (len <= 0)\n\t{\n\t done = true;\n\t}\n\telse\n\t{\n\t aes->write(buf, len);\n\t}\n }\n aes->finish();\n delete aes;\n delete out;\n fclose(infile);\n fclose(outfile);\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: QUtil::safe_fopen(char const* filename, char const* mode)\n{\n FILE* f = 0;\n#ifdef _WIN32\n // Convert the utf-8 encoded filename argument to wchar_t*. First,\n // convert to utf16, then to wchar_t*. Note that u16 will start\n // with the UTF16 marker, which we skip.\n std::string u16 = utf8_to_utf16(filename);\n size_t len = u16.length();\n size_t wlen = (len / 2) - 1;\n PointerHolder wfilenamep(true, new wchar_t[wlen + 1]);\n wchar_t* wfilename = wfilenamep.getPointer();\n wfilename[wlen] = 0;\n for (unsigned int i = 2; i < len; i += 2)\n {\n wfilename[(i/2) - 1] =\n static_cast(\n (static_cast(u16.at(i)) << 8) +\n static_cast(u16.at(i+1)));\n }\n PointerHolder wmodep(true, new wchar_t[strlen(mode) + 1]);\n wchar_t* wmode = wmodep.getPointer();\n wmode[strlen(mode)] = 0;\n for (size_t i = 0; i < strlen(mode); ++i)\n {\n wmode[i] = mode[i];\n }\n\n#ifdef _MSC_VER\n errno_t err = _wfopen_s(&f, wfilename, wmode);\n if (err != 0)\n {\n errno = err;\n }\n#else\n f = _wfopen(wfilename, wmode);\n#endif\n if (f == 0)\n {\n throw_system_error(std::string(\"open \") + filename);\n }\n#else\n f = fopen_wrapper(std::string(\"open \") + filename, fopen(filename, mode));\n#endif\n return f;\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::setEncryptionParametersInternal(\n int V, int R, int key_len, long P,\n std::string const& O, std::string const& U,\n std::string const& OE, std::string const& UE, std::string const& Perms,\n std::string const& id1, std::string const& user_password,\n std::string const& encryption_key)\n{\n this->m->encryption_V = V;\n this->m->encryption_R = R;\n this->m->encryption_dictionary[\"/Filter\"] = \"/Standard\";\n this->m->encryption_dictionary[\"/V\"] = QUtil::int_to_string(V);\n this->m->encryption_dictionary[\"/Length\"] =\n QUtil::int_to_string(key_len * 8);\n this->m->encryption_dictionary[\"/R\"] = QUtil::int_to_string(R);\n this->m->encryption_dictionary[\"/P\"] = QUtil::int_to_string(P);\n this->m->encryption_dictionary[\"/O\"] = QPDF_String(O).unparse(true);\n this->m->encryption_dictionary[\"/U\"] = QPDF_String(U).unparse(true);\n if (V >= 5)\n {\n this->m->encryption_dictionary[\"/OE\"] = QPDF_String(OE).unparse(true);\n this->m->encryption_dictionary[\"/UE\"] = QPDF_String(UE).unparse(true);\n this->m->encryption_dictionary[\"/Perms\"] =\n QPDF_String(Perms).unparse(true);\n }\n if (R >= 6)\n {\n setMinimumPDFVersion(\"1.7\", 8);\n }\n else if (R == 5)\n {\n setMinimumPDFVersion(\"1.7\", 3);\n }\n else if (R == 4)\n {\n setMinimumPDFVersion(this->m->encrypt_use_aes ? \"1.6\" : \"1.5\");\n }\n else if (R == 3)\n {\n setMinimumPDFVersion(\"1.4\");\n }\n else\n {\n setMinimumPDFVersion(\"1.3\");\n }\n\n if ((R >= 4) && (! this->m->encrypt_metadata))\n {\n\tthis->m->encryption_dictionary[\"/EncryptMetadata\"] = \"false\";\n }\n if ((V == 4) || (V == 5))\n {\n\t// The spec says the value for the crypt filter key can be\n\t// anything, and xpdf seems to agree. However, Adobe Reader\n\t// won't open our files unless we use /StdCF.\n\tthis->m->encryption_dictionary[\"/StmF\"] = \"/StdCF\";\n\tthis->m->encryption_dictionary[\"/StrF\"] = \"/StdCF\";\n\tstd::string method = (this->m->encrypt_use_aes\n ? ((V < 5) ? \"/AESV2\" : \"/AESV3\")\n : \"/V2\");\n // The PDF spec says the /Length key is optional, but the PDF\n // previewer on some versions of MacOS won't open encrypted\n // files without it.\n\tthis->m->encryption_dictionary[\"/CF\"] =\n\t \"<< /StdCF << /AuthEvent /DocOpen /CFM \" + method +\n \" /Length \" + std::string((V < 5) ? \"16\" : \"32\") + \" >> >>\";\n }\n\n this->m->encrypted = true;\n QPDF::EncryptionData encryption_data(\n\tV, R, key_len, P, O, U, OE, UE, Perms, id1, this->m->encrypt_metadata);\n if (V < 5)\n {\n this->m->encryption_key = QPDF::compute_encryption_key(\n user_password, encryption_data);\n }\n else\n {\n this->m->encryption_key = encryption_key;\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: QPDFFormFieldObjectHelper::getQuadding()\n{\n int result = 0;\n QPDFObjectHandle fv = getInheritableFieldValue(\"/Q\");\n if (fv.isInteger())\n {\n QTC::TC(\"qpdf\", \"QPDFFormFieldObjectHelper Q present\");\n result = static_cast(fv.getIntValue());\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: QPDFObjectHandle::isRectangle()\n{\n if (! isArray())\n {\n return false;\n }\n if (getArrayNItems() != 4)\n {\n return false;\n }\n for (size_t i = 0; i < 4; ++i)\n {\n if (! getArrayItem(i).isNumber())\n {\n return false;\n }\n }\n return true;\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 write_outfile(QPDF& pdf, Options& o)\n{\n if (o.split_pages)\n {\n // Generate output file pattern\n std::string before;\n std::string after;\n size_t len = strlen(o.outfilename);\n char* num_spot = strstr(const_cast(o.outfilename), \"%d\");\n if (num_spot != 0)\n {\n QTC::TC(\"qpdf\", \"qpdf split-pages %d\");\n before = std::string(o.outfilename, (num_spot - o.outfilename));\n after = num_spot + 2;\n }\n else if ((len >= 4) &&\n (QUtil::strcasecmp(o.outfilename + len - 4, \".pdf\") == 0))\n {\n QTC::TC(\"qpdf\", \"qpdf split-pages .pdf\");\n before = std::string(o.outfilename, len - 4) + \"-\";\n after = o.outfilename + len - 4;\n }\n else\n {\n QTC::TC(\"qpdf\", \"qpdf split-pages other\");\n before = std::string(o.outfilename) + \"-\";\n }\n\n if (! o.preserve_unreferenced_page_resources)\n {\n QPDFPageDocumentHelper dh(pdf);\n dh.removeUnreferencedResources();\n }\n QPDFPageLabelDocumentHelper pldh(pdf);\n std::vector const& pages = pdf.getAllPages();\n int pageno_len = QUtil::int_to_string(pages.size()).length();\n unsigned int num_pages = pages.size();\n for (unsigned int i = 0; i < num_pages; i += o.split_pages)\n {\n unsigned int first = i + 1;\n unsigned int last = i + o.split_pages;\n if (last > num_pages)\n {\n last = num_pages;\n }\n QPDF outpdf;\n outpdf.emptyPDF();\n for (unsigned int pageno = first; pageno <= last; ++pageno)\n {\n QPDFObjectHandle page = pages.at(pageno - 1);\n outpdf.addPage(page, false);\n }\n if (pldh.hasPageLabels())\n {\n std::vector labels;\n pldh.getLabelsForPageRange(first - 1, last - 1, 0, labels);\n QPDFObjectHandle page_labels =\n QPDFObjectHandle::newDictionary();\n page_labels.replaceKey(\n \"/Nums\", QPDFObjectHandle::newArray(labels));\n outpdf.getRoot().replaceKey(\"/PageLabels\", page_labels);\n }\n std::string page_range = QUtil::int_to_string(first, pageno_len);\n if (o.split_pages > 1)\n {\n page_range += \"-\" + QUtil::int_to_string(last, pageno_len);\n }\n std::string outfile = before + page_range + after;\n QPDFWriter w(outpdf, outfile.c_str());\n set_writer_options(outpdf, o, w);\n w.write();\n if (o.verbose)\n {\n std::cout << whoami << \": wrote file \" << outfile << std::endl;\n }\n }\n }\n else\n {\n if (strcmp(o.outfilename, \"-\") == 0)\n {\n o.outfilename = 0;\n }\n QPDFWriter w(pdf, o.outfilename);\n set_writer_options(pdf, o, w);\n w.write();\n if (o.verbose)\n {\n std::cout << whoami << \": wrote file \"\n << o.outfilename << std::endl;\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static const ut8 *r_bin_dwarf_parse_attr_value(const ut8 *obuf, int obuf_len,\n\t\tRBinDwarfAttrSpec *spec, RBinDwarfAttrValue *value,\n\t\tconst RBinDwarfCompUnitHdr *hdr,\n\t\tconst ut8 *debug_str, size_t debug_str_len) {\n\tconst ut8 *buf = obuf;\n\tconst ut8 *buf_end = obuf + obuf_len;\n\tsize_t j;\n\n\tif (!spec || !value || !hdr || !obuf || obuf_len < 0) {\n\t\treturn NULL;\n\t}\n\n\tvalue->form = spec->attr_form;\n\tvalue->name = spec->attr_name;\n\tvalue->encoding.block.data = NULL;\n\tvalue->encoding.str_struct.string = NULL;\n\tvalue->encoding.str_struct.offset = 0;\n\n\tswitch (spec->attr_form) {\n\tcase DW_FORM_addr:\n\t\tswitch (hdr->pointer_size) {\n\t\tcase 1:\n\t\t\tvalue->encoding.address = READ (buf, ut8);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tvalue->encoding.address = READ (buf, ut16);\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tvalue->encoding.address = READ (buf, ut32);\n\t\t\tbreak;\n\t\tcase 8:\n\t\t\tvalue->encoding.address = READ (buf, ut64);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\teprintf(\"DWARF: Unexpected pointer size: %u\\n\", (unsigned)hdr->pointer_size);\n\t\t\treturn NULL;\n\t\t}\n\t\tbreak;\n\tcase DW_FORM_block2:\n\t\tvalue->encoding.block.length = READ (buf, ut16);\n\t\tif (value->encoding.block.length > 0) {\n\t\t\tvalue->encoding.block.data = calloc (sizeof(ut8), value->encoding.block.length);\n\t\t\tfor (j = 0; j < value->encoding.block.length; j++) {\n\t\t\t\tvalue->encoding.block.data[j] = READ (buf, ut8);\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase DW_FORM_block4:\n\t\tvalue->encoding.block.length = READ (buf, ut32);\n\t\tif (value->encoding.block.length > 0) {\n\t\t\tut8 *data = calloc (sizeof (ut8), value->encoding.block.length);\n\t\t\tif (data) {\n\t\t\t\tfor (j = 0; j < value->encoding.block.length; j++) {\n\t\t\t\t\tdata[j] = READ (buf, ut8);\n\t\t\t\t}\n\t\t\t}\n\t\t\tvalue->encoding.block.data = data;\n\t\t}\n\t\tbreak;\n\tcase DW_FORM_data2:\n\t\tvalue->encoding.data = READ (buf, ut16);\n\t\tbreak;\n\tcase DW_FORM_data4:\n\t\tvalue->encoding.data = READ (buf, ut32);\n\t\tbreak;\n\tcase DW_FORM_data8:\n\t\tvalue->encoding.data = READ (buf, ut64);\n\t\tbreak;\n\tcase DW_FORM_string:\n\t\tvalue->encoding.str_struct.string = *buf? strdup ((const char*)buf) : NULL;\n\t\tbuf += (strlen ((const char*)buf) + 1);\n\t\tbreak;\n\tcase DW_FORM_block:\n\t\tbuf = r_uleb128 (buf, buf_end - buf, &value->encoding.block.length);\n\t\tif (!buf) {\n\t\t\treturn NULL;\n\t\t}\n\t\tvalue->encoding.block.data = calloc (sizeof(ut8), value->encoding.block.length);\n\t\tfor (j = 0; j < value->encoding.block.length; j++) {\n\t\t\tvalue->encoding.block.data[j] = READ (buf, ut8);\n\t\t}\n\t\tbreak;\n\tcase DW_FORM_block1:\n\t\tvalue->encoding.block.length = READ (buf, ut8);\n\t\tvalue->encoding.block.data = calloc (sizeof (ut8), value->encoding.block.length + 1);\n\t\tfor (j = 0; j < value->encoding.block.length; j++) {\n\t\t\tvalue->encoding.block.data[j] = READ (buf, ut8);\n\t\t}\n\t\tbreak;\n\tcase DW_FORM_flag:\n\t\tvalue->encoding.flag = READ (buf, ut8);\n\t\tbreak;\n\tcase DW_FORM_sdata:\n\t\tbuf = r_leb128 (buf, &value->encoding.sdata);\n\t\tbreak;\n\tcase DW_FORM_strp:\n\t\tvalue->encoding.str_struct.offset = READ (buf, ut32);\n\t\tif (debug_str && value->encoding.str_struct.offset < debug_str_len) {\n\t\t\tvalue->encoding.str_struct.string = strdup (\n\t\t\t\t(const char *)(debug_str +\n\t\t\t\t\tvalue->encoding.str_struct.offset));\n\t\t} else {\n\t\t\tvalue->encoding.str_struct.string = NULL;\n\t\t}\n\t\tbreak;\n\tcase DW_FORM_udata:\n\t\t{\n\t\t\tut64 ndata = 0;\n\t\t\tconst ut8 *data = (const ut8*)&ndata;\n\t\t\tbuf = r_uleb128 (buf, R_MIN (sizeof (data), (size_t)(buf_end - buf)), &ndata);\n\t\t\tmemcpy (&value->encoding.data, data, sizeof (value->encoding.data));\n\t\t\tvalue->encoding.str_struct.string = NULL;\n\t\t}\n\t\tbreak;\n\tcase DW_FORM_ref_addr:\n\t\tvalue->encoding.reference = READ (buf, ut64); // addr size of machine\n\t\tbreak;\n\tcase DW_FORM_ref1:\n\t\tvalue->encoding.reference = READ (buf, ut8);\n\t\tbreak;\n\tcase DW_FORM_ref2:\n\t\tvalue->encoding.reference = READ (buf, ut16);\n\t\tbreak;\n\tcase DW_FORM_ref4:\n\t\tvalue->encoding.reference = READ (buf, ut32);\n\t\tbreak;\n\tcase DW_FORM_ref8:\n\t\tvalue->encoding.reference = READ (buf, ut64);\n\t\tbreak;\n\tcase DW_FORM_data1:\n\t\tvalue->encoding.data = READ (buf, ut8);\n\t\tbreak;\n\tdefault:\n\t\teprintf (\"Unknown DW_FORM 0x%02\"PFMT64x\"\\n\", spec->attr_form);\n\t\tvalue->encoding.data = 0;\n\t\treturn NULL;\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: static ssize_t ib_ucm_write(struct file *filp, const char __user *buf,\n\t\t\t size_t len, loff_t *pos)\n{\n\tstruct ib_ucm_file *file = filp->private_data;\n\tstruct ib_ucm_cmd_hdr hdr;\n\tssize_t result;\n\n\tif (len < sizeof(hdr))\n\t\treturn -EINVAL;\n\n\tif (copy_from_user(&hdr, buf, sizeof(hdr)))\n\t\treturn -EFAULT;\n\n\tif (hdr.cmd >= ARRAY_SIZE(ucm_cmd_table))\n\t\treturn -EINVAL;\n\n\tif (hdr.in + sizeof(hdr) > len)\n\t\treturn -EINVAL;\n\n\tresult = ucm_cmd_table[hdr.cmd](file, buf + sizeof(hdr),\n\t\t\t\t\thdr.in, hdr.out);\n\tif (!result)\n\t\tresult = len;\n\n\treturn result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'IB/security: Restrict use of the write() interface\n\nThe drivers/infiniband stack uses write() as a replacement for\nbi-directional ioctl(). This is not safe. There are ways to\ntrigger write calls that result in the return structure that\nis normally written to user space being shunted off to user\nspecified kernel memory instead.\n\nFor the immediate repair, detect and deny suspicious accesses to\nthe write API.\n\nFor long term, update the user space libraries and the kernel API\nto something that doesn't present the same security vulnerabilities\n(likely a structured ioctl() interface).\n\nThe impacted uAPI interfaces are generally only available if\nhardware from drivers/infiniband is installed in the system.\n\nReported-by: Jann Horn \nSigned-off-by: Linus Torvalds \nSigned-off-by: Jason Gunthorpe \n[ Expanded check to all known write() entry points ]\nCc: stable@vger.kernel.org\nSigned-off-by: Doug Ledford '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: isis_print_mt_capability_subtlv(netdissect_options *ndo,\n const uint8_t *tptr, int len)\n{\n int stlv_type, stlv_len, tmp;\n\n while (len > 2)\n {\n stlv_type = *(tptr++);\n stlv_len = *(tptr++);\n\n /* first lets see if we know the subTLVs name*/\n ND_PRINT((ndo, \"\\n\\t %s subTLV #%u, length: %u\",\n tok2str(isis_mt_capability_subtlv_values, \"unknown\", stlv_type),\n stlv_type,\n stlv_len));\n\n len = len - 2;\n\n switch (stlv_type)\n {\n case ISIS_SUBTLV_SPB_INSTANCE:\n\n ND_TCHECK2(*tptr, ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN);\n\n ND_PRINT((ndo, \"\\n\\t CIST Root-ID: %08x\", EXTRACT_32BITS(tptr)));\n tptr = tptr+4;\n ND_PRINT((ndo, \" %08x\", EXTRACT_32BITS(tptr)));\n tptr = tptr+4;\n ND_PRINT((ndo, \", Path Cost: %08x\", EXTRACT_32BITS(tptr)));\n tptr = tptr+4;\n ND_PRINT((ndo, \", Prio: %d\", EXTRACT_16BITS(tptr)));\n tptr = tptr + 2;\n ND_PRINT((ndo, \"\\n\\t RES: %d\",\n EXTRACT_16BITS(tptr) >> 5));\n ND_PRINT((ndo, \", V: %d\",\n (EXTRACT_16BITS(tptr) >> 4) & 0x0001));\n ND_PRINT((ndo, \", SPSource-ID: %d\",\n (EXTRACT_32BITS(tptr) & 0x000fffff)));\n tptr = tptr+4;\n ND_PRINT((ndo, \", No of Trees: %x\", *(tptr)));\n\n tmp = *(tptr++);\n\n len = len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN;\n\n while (tmp)\n {\n ND_TCHECK2(*tptr, ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN);\n\n ND_PRINT((ndo, \"\\n\\t U:%d, M:%d, A:%d, RES:%d\",\n *(tptr) >> 7, (*(tptr) >> 6) & 0x01,\n (*(tptr) >> 5) & 0x01, (*(tptr) & 0x1f)));\n\n tptr++;\n\n ND_PRINT((ndo, \", ECT: %08x\", EXTRACT_32BITS(tptr)));\n\n tptr = tptr + 4;\n\n ND_PRINT((ndo, \", BVID: %d, SPVID: %d\",\n (EXTRACT_24BITS(tptr) >> 12) & 0x000fff,\n EXTRACT_24BITS(tptr) & 0x000fff));\n\n tptr = tptr + 3;\n len = len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN;\n tmp--;\n }\n\n break;\n\n case ISIS_SUBTLV_SPBM_SI:\n\n ND_TCHECK2(*tptr, 8);\n\n ND_PRINT((ndo, \"\\n\\t BMAC: %08x\", EXTRACT_32BITS(tptr)));\n tptr = tptr+4;\n ND_PRINT((ndo, \"%04x\", EXTRACT_16BITS(tptr)));\n tptr = tptr+2;\n\n ND_PRINT((ndo, \", RES: %d, VID: %d\", EXTRACT_16BITS(tptr) >> 12,\n (EXTRACT_16BITS(tptr)) & 0x0fff));\n\n tptr = tptr+2;\n len = len - 8;\n stlv_len = stlv_len - 8;\n\n while (stlv_len >= 4) {\n ND_TCHECK2(*tptr, 4);\n ND_PRINT((ndo, \"\\n\\t T: %d, R: %d, RES: %d, ISID: %d\",\n (EXTRACT_32BITS(tptr) >> 31),\n (EXTRACT_32BITS(tptr) >> 30) & 0x01,\n (EXTRACT_32BITS(tptr) >> 24) & 0x03f,\n (EXTRACT_32BITS(tptr)) & 0x0ffffff));\n\n tptr = tptr + 4;\n len = len - 4;\n stlv_len = stlv_len - 4;\n }\n\n break;\n\n default:\n break;\n }\n }\n return 0;\n\n trunc:\n ND_PRINT((ndo, \"\\n\\t\\t\"));\n ND_PRINT((ndo, \"%s\", tstr));\n return(1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13026/IS-IS: Clean up processing of subTLVs.\n\nAdd bounds checks, do a common check to make sure we captured the entire\nsubTLV, add checks to make sure the subTLV fits within the TLV.\n\nThis fixes a buffer over-read discovered by Bhargava Shastry,\nSecT/TU Berlin.\n\nAdd tests using the capture files supplied by the reporter(s), modified\nso the capture files won't be rejected as an invalid capture.\n\nUpdate existing tests for changes to IS-IS dissector.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: fep_client_open (const char *address)\n{\n FepClient *client;\n struct sockaddr_un sun;\n ssize_t sun_len;\n int retval;\n\n if (!address)\n address = getenv (\"LIBFEP_CONTROL_SOCK\");\n if (!address)\n return NULL;\n\n if (strlen (address) + 1 >= sizeof(sun.sun_path))\n {\n fep_log (FEP_LOG_LEVEL_WARNING,\n\t \"unix domain socket path too long: %d + 1 >= %d\",\n\t strlen (address),\n\t sizeof (sun.sun_path));\n free (address);\n return NULL;\n }\n\n client = xzalloc (sizeof(FepClient));\n client->filter_running = false;\n client->messages = NULL;\n\n memset (&sun, 0, sizeof(struct sockaddr_un));\n sun.sun_family = AF_UNIX;\n\n#ifdef __linux__\n sun.sun_path[0] = '\\0';\n memcpy (sun.sun_path + 1, address, strlen (address));\n sun_len = offsetof (struct sockaddr_un, sun_path) + strlen (address) + 1;\n#else\n memcpy (sun.sun_path, address, strlen (address));\n sun_len = sizeof (struct sockaddr_un);\n#endif\n\n client->control = socket (AF_UNIX, SOCK_STREAM, 0);\n if (client->control < 0)\n {\n free (client);\n return NULL;\n }\n\n retval = connect (client->control,\n\t\t (const struct sockaddr *) &sun,\n\t\t sun_len);\n if (retval < 0)\n {\n close (client->control);\n free (client);\n return NULL;\n }\n\n return client;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'Don't use abstract Unix domain sockets'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool CModules::GetModInfo(CModInfo& ModInfo, const CString& sModule,\n CString& sRetMsg) {\n CString sModPath, sTmp;\n\n bool bSuccess;\n bool bHandled = false;\n GLOBALMODULECALL(OnGetModInfo(ModInfo, sModule, bSuccess, sRetMsg),\n &bHandled);\n if (bHandled) return bSuccess;\n\n if (!FindModPath(sModule, sModPath, sTmp)) {\n sRetMsg = t_f(\"Unable to find module {1}.\")(sModule);\n return false;\n }\n\n return GetModPathInfo(ModInfo, sModule, sModPath, sRetMsg);\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 journal_unmap_buffer(journal_t *journal, struct buffer_head *bh)\n{\n\ttransaction_t *transaction;\n\tstruct journal_head *jh;\n\tint may_free = 1;\n\tint ret;\n\n\tBUFFER_TRACE(bh, \"entry\");\n\n\t/*\n\t * It is safe to proceed here without the j_list_lock because the\n\t * buffers cannot be stolen by try_to_free_buffers as long as we are\n\t * holding the page lock. --sct\n\t */\n\n\tif (!buffer_jbd(bh))\n\t\tgoto zap_buffer_unlocked;\n\n\t/* OK, we have data buffer in journaled mode */\n\twrite_lock(&journal->j_state_lock);\n\tjbd_lock_bh_state(bh);\n\tspin_lock(&journal->j_list_lock);\n\n\tjh = jbd2_journal_grab_journal_head(bh);\n\tif (!jh)\n\t\tgoto zap_buffer_no_jh;\n\n\t/*\n\t * We cannot remove the buffer from checkpoint lists until the\n\t * transaction adding inode to orphan list (let's call it T)\n\t * is committed. Otherwise if the transaction changing the\n\t * buffer would be cleaned from the journal before T is\n\t * committed, a crash will cause that the correct contents of\n\t * the buffer will be lost. On the other hand we have to\n\t * clear the buffer dirty bit at latest at the moment when the\n\t * transaction marking the buffer as freed in the filesystem\n\t * structures is committed because from that moment on the\n\t * buffer can be reallocated and used by a different page.\n\t * Since the block hasn't been freed yet but the inode has\n\t * already been added to orphan list, it is safe for us to add\n\t * the buffer to BJ_Forget list of the newest transaction.\n\t */\n\ttransaction = jh->b_transaction;\n\tif (transaction == NULL) {\n\t\t/* First case: not on any transaction. If it\n\t\t * has no checkpoint link, then we can zap it:\n\t\t * it's a writeback-mode buffer so we don't care\n\t\t * if it hits disk safely. */\n\t\tif (!jh->b_cp_transaction) {\n\t\t\tJBUFFER_TRACE(jh, \"not on any transaction: zap\");\n\t\t\tgoto zap_buffer;\n\t\t}\n\n\t\tif (!buffer_dirty(bh)) {\n\t\t\t/* bdflush has written it. We can drop it now */\n\t\t\tgoto zap_buffer;\n\t\t}\n\n\t\t/* OK, it must be in the journal but still not\n\t\t * written fully to disk: it's metadata or\n\t\t * journaled data... */\n\n\t\tif (journal->j_running_transaction) {\n\t\t\t/* ... and once the current transaction has\n\t\t\t * committed, the buffer won't be needed any\n\t\t\t * longer. */\n\t\t\tJBUFFER_TRACE(jh, \"checkpointed: add to BJ_Forget\");\n\t\t\tret = __dispose_buffer(jh,\n\t\t\t\t\tjournal->j_running_transaction);\n\t\t\tjbd2_journal_put_journal_head(jh);\n\t\t\tspin_unlock(&journal->j_list_lock);\n\t\t\tjbd_unlock_bh_state(bh);\n\t\t\twrite_unlock(&journal->j_state_lock);\n\t\t\treturn ret;\n\t\t} else {\n\t\t\t/* There is no currently-running transaction. So the\n\t\t\t * orphan record which we wrote for this file must have\n\t\t\t * passed into commit. We must attach this buffer to\n\t\t\t * the committing transaction, if it exists. */\n\t\t\tif (journal->j_committing_transaction) {\n\t\t\t\tJBUFFER_TRACE(jh, \"give to committing trans\");\n\t\t\t\tret = __dispose_buffer(jh,\n\t\t\t\t\tjournal->j_committing_transaction);\n\t\t\t\tjbd2_journal_put_journal_head(jh);\n\t\t\t\tspin_unlock(&journal->j_list_lock);\n\t\t\t\tjbd_unlock_bh_state(bh);\n\t\t\t\twrite_unlock(&journal->j_state_lock);\n\t\t\t\treturn ret;\n\t\t\t} else {\n\t\t\t\t/* The orphan record's transaction has\n\t\t\t\t * committed. We can cleanse this buffer */\n\t\t\t\tclear_buffer_jbddirty(bh);\n\t\t\t\tgoto zap_buffer;\n\t\t\t}\n\t\t}\n\t} else if (transaction == journal->j_committing_transaction) {\n\t\tJBUFFER_TRACE(jh, \"on committing transaction\");\n\t\t/*\n\t\t * The buffer is committing, we simply cannot touch\n\t\t * it. So we just set j_next_transaction to the\n\t\t * running transaction (if there is one) and mark\n\t\t * buffer as freed so that commit code knows it should\n\t\t * clear dirty bits when it is done with the buffer.\n\t\t */\n\t\tset_buffer_freed(bh);\n\t\tif (journal->j_running_transaction && buffer_jbddirty(bh))\n\t\t\tjh->b_next_transaction = journal->j_running_transaction;\n\t\tjbd2_journal_put_journal_head(jh);\n\t\tspin_unlock(&journal->j_list_lock);\n\t\tjbd_unlock_bh_state(bh);\n\t\twrite_unlock(&journal->j_state_lock);\n\t\treturn 0;\n\t} else {\n\t\t/* Good, the buffer belongs to the running transaction.\n\t\t * We are writing our own transaction's data, not any\n\t\t * previous one's, so it is safe to throw it away\n\t\t * (remember that we expect the filesystem to have set\n\t\t * i_size already for this truncate so recovery will not\n\t\t * expose the disk blocks we are discarding here.) */\n\t\tJ_ASSERT_JH(jh, transaction == journal->j_running_transaction);\n\t\tJBUFFER_TRACE(jh, \"on running transaction\");\n\t\tmay_free = __dispose_buffer(jh, transaction);\n\t}\n\nzap_buffer:\n\tjbd2_journal_put_journal_head(jh);\nzap_buffer_no_jh:\n\tspin_unlock(&journal->j_list_lock);\n\tjbd_unlock_bh_state(bh);\n\twrite_unlock(&journal->j_state_lock);\nzap_buffer_unlocked:\n\tclear_buffer_dirty(bh);\n\tJ_ASSERT_BH(bh, !buffer_jbddirty(bh));\n\tclear_buffer_mapped(bh);\n\tclear_buffer_req(bh);\n\tclear_buffer_new(bh);\n\tbh->b_bdev = NULL;\n\treturn may_free;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'jbd2: clear BH_Delay & BH_Unwritten in journal_unmap_buffer\n\njournal_unmap_buffer()'s zap_buffer: code clears a lot of buffer head\nstate ala discard_buffer(), but does not touch _Delay or _Unwritten as\ndiscard_buffer() does.\n\nThis can be problematic in some areas of the ext4 code which assume\nthat if they have found a buffer marked unwritten or delay, then it's\na live one. Perhaps those spots should check whether it is mapped\nas well, but if jbd2 is going to tear down a buffer, let's really\ntear it down completely.\n\nWithout this I get some fsx failures on sub-page-block filesystems\nup until v3.2, at which point 4e96b2dbbf1d7e81f22047a50f862555a6cb87cb\nand 189e868fa8fdca702eb9db9d8afc46b5cb9144c9 make the failures go\naway, because buried within that large change is some more flag\nclearing. I still think it's worth doing in jbd2, since\n->invalidatepage leads here directly, and it's the right place\nto clear away these flags.\n\nSigned-off-by: Eric Sandeen \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: static int fuzzerTests(U32 seed, U32 nbTests, unsigned startTest, U32 const maxDurationS, double compressibility, int bigTests)\n{\n static const U32 maxSrcLog = 23;\n static const U32 maxSampleLog = 22;\n size_t const srcBufferSize = (size_t)1<= testNb) { DISPLAYUPDATE(2, \"\\r%6u/%6u \", testNb, nbTests); }\n else { DISPLAYUPDATE(2, \"\\r%6u \", testNb); }\n\n FUZ_rand(&coreSeed);\n { U32 const prime1 = 2654435761U; lseed = coreSeed ^ prime1; }\n\n /* srcBuffer selection [0-4] */\n { U32 buffNb = FUZ_rand(&lseed) & 0x7F;\n if (buffNb & 7) buffNb=2; /* most common : compressible (P) */\n else {\n buffNb >>= 3;\n if (buffNb & 7) {\n const U32 tnb[2] = { 1, 3 }; /* barely/highly compressible */\n buffNb = tnb[buffNb >> 3];\n } else {\n const U32 tnb[2] = { 0, 4 }; /* not compressible / sparse */\n buffNb = tnb[buffNb >> 3];\n } }\n srcBuffer = cNoiseBuffer[buffNb];\n }\n\n /* select src segment */\n sampleSize = FUZ_randomLength(&lseed, maxSampleLog);\n\n /* create sample buffer (to catch read error with valgrind & sanitizers) */\n sampleBuffer = (BYTE*)malloc(sampleSize);\n CHECK(sampleBuffer==NULL, \"not enough memory for sample buffer\");\n { size_t const sampleStart = FUZ_rand(&lseed) % (srcBufferSize - sampleSize);\n memcpy(sampleBuffer, srcBuffer + sampleStart, sampleSize); }\n crcOrig = XXH64(sampleBuffer, sampleSize, 0);\n\n /* compression tests */\n { int const cLevelPositive =\n ( FUZ_rand(&lseed) %\n (ZSTD_maxCLevel() - (FUZ_highbit32((U32)sampleSize) / cLevelLimiter)) )\n + 1;\n int const cLevel = ((FUZ_rand(&lseed) & 15) == 3) ?\n - (int)((FUZ_rand(&lseed) & 7) + 1) : /* test negative cLevel */\n cLevelPositive;\n DISPLAYLEVEL(5, \"fuzzer t%u: Simple compression test (level %i) \\n\", testNb, cLevel);\n cSize = ZSTD_compressCCtx(ctx, cBuffer, cBufferSize, sampleBuffer, sampleSize, cLevel);\n CHECK(ZSTD_isError(cSize), \"ZSTD_compressCCtx failed : %s\", ZSTD_getErrorName(cSize));\n\n /* compression failure test : too small dest buffer */\n if (cSize > 3) {\n const size_t missing = (FUZ_rand(&lseed) % (cSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */\n const size_t tooSmallSize = cSize - missing;\n const U32 endMark = 0x4DC2B1A9;\n memcpy(dstBuffer+tooSmallSize, &endMark, 4);\n { size_t const errorCode = ZSTD_compressCCtx(ctx, dstBuffer, tooSmallSize, sampleBuffer, sampleSize, cLevel);\n CHECK(!ZSTD_isError(errorCode), \"ZSTD_compressCCtx should have failed ! (buffer too small : %u < %u)\", (U32)tooSmallSize, (U32)cSize); }\n { U32 endCheck; memcpy(&endCheck, dstBuffer+tooSmallSize, 4);\n CHECK(endCheck != endMark, \"ZSTD_compressCCtx : dst buffer overflow\"); }\n } }\n\n /* frame header decompression test */\n { ZSTD_frameHeader zfh;\n CHECK_Z( ZSTD_getFrameHeader(&zfh, cBuffer, cSize) );\n CHECK(zfh.frameContentSize != sampleSize, \"Frame content size incorrect\");\n }\n\n /* Decompressed size test */\n { unsigned long long const rSize = ZSTD_findDecompressedSize(cBuffer, cSize);\n CHECK(rSize != sampleSize, \"decompressed size incorrect\");\n }\n\n /* successful decompression test */\n DISPLAYLEVEL(5, \"fuzzer t%u: simple decompression test \\n\", testNb);\n { size_t const margin = (FUZ_rand(&lseed) & 1) ? 0 : (FUZ_rand(&lseed) & 31) + 1;\n size_t const dSize = ZSTD_decompress(dstBuffer, sampleSize + margin, cBuffer, cSize);\n CHECK(dSize != sampleSize, \"ZSTD_decompress failed (%s) (srcSize : %u ; cSize : %u)\", ZSTD_getErrorName(dSize), (U32)sampleSize, (U32)cSize);\n { U64 const crcDest = XXH64(dstBuffer, sampleSize, 0);\n CHECK(crcOrig != crcDest, \"decompression result corrupted (pos %u / %u)\", (U32)findDiff(sampleBuffer, dstBuffer, sampleSize), (U32)sampleSize);\n } }\n\n free(sampleBuffer); /* no longer useful after this point */\n\n /* truncated src decompression test */\n DISPLAYLEVEL(5, \"fuzzer t%u: decompression of truncated source \\n\", testNb);\n { size_t const missing = (FUZ_rand(&lseed) % (cSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */\n size_t const tooSmallSize = cSize - missing;\n void* cBufferTooSmall = malloc(tooSmallSize); /* valgrind will catch read overflows */\n CHECK(cBufferTooSmall == NULL, \"not enough memory !\");\n memcpy(cBufferTooSmall, cBuffer, tooSmallSize);\n { size_t const errorCode = ZSTD_decompress(dstBuffer, dstBufferSize, cBufferTooSmall, tooSmallSize);\n CHECK(!ZSTD_isError(errorCode), \"ZSTD_decompress should have failed ! (truncated src buffer)\"); }\n free(cBufferTooSmall);\n }\n\n /* too small dst decompression test */\n DISPLAYLEVEL(5, \"fuzzer t%u: decompress into too small dst buffer \\n\", testNb);\n if (sampleSize > 3) {\n size_t const missing = (FUZ_rand(&lseed) % (sampleSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */\n size_t const tooSmallSize = sampleSize - missing;\n static const BYTE token = 0xA9;\n dstBuffer[tooSmallSize] = token;\n { size_t const errorCode = ZSTD_decompress(dstBuffer, tooSmallSize, cBuffer, cSize);\n CHECK(!ZSTD_isError(errorCode), \"ZSTD_decompress should have failed : %u > %u (dst buffer too small)\", (U32)errorCode, (U32)tooSmallSize); }\n CHECK(dstBuffer[tooSmallSize] != token, \"ZSTD_decompress : dst buffer overflow\");\n }\n\n /* noisy src decompression test */\n if (cSize > 6) {\n /* insert noise into src */\n { U32 const maxNbBits = FUZ_highbit32((U32)(cSize-4));\n size_t pos = 4; /* preserve magic number (too easy to detect) */\n for (;;) {\n /* keep some original src */\n { U32 const nbBits = FUZ_rand(&lseed) % maxNbBits;\n size_t const mask = (1<= cSize) break;\n /* add noise */\n { U32 const nbBitsCodes = FUZ_rand(&lseed) % maxNbBits;\n U32 const nbBits = nbBitsCodes ? nbBitsCodes-1 : 0;\n size_t const mask = (1<sampleSize),\n \"ZSTD_decompress on noisy src : result is too large : %u > %u (dst buffer)\", (U32)decompressResult, (U32)sampleSize);\n }\n { U32 endCheck; memcpy(&endCheck, dstBuffer+sampleSize, 4);\n CHECK(endMark!=endCheck, \"ZSTD_decompress on noisy src : dst buffer overflow\");\n } } } /* noisy src decompression test */\n\n /*===== Bufferless streaming compression test, scattered segments and dictionary =====*/\n DISPLAYLEVEL(5, \"fuzzer t%u: Bufferless streaming compression test \\n\", testNb);\n { U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;\n U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;\n int const cLevel = (FUZ_rand(&lseed) %\n (ZSTD_maxCLevel() -\n (MAX(testLog, dictLog) / cLevelLimiter))) +\n 1;\n maxTestSize = FUZ_rLogLength(&lseed, testLog);\n if (maxTestSize >= dstBufferSize) maxTestSize = dstBufferSize-1;\n\n dictSize = FUZ_rLogLength(&lseed, dictLog); /* needed also for decompression */\n dict = srcBuffer + (FUZ_rand(&lseed) % (srcBufferSize - dictSize));\n\n DISPLAYLEVEL(6, \"fuzzer t%u: Compressing up to <=%u bytes at level %i with dictionary size %u \\n\",\n testNb, (U32)maxTestSize, cLevel, (U32)dictSize);\n\n if (FUZ_rand(&lseed) & 0xF) {\n CHECK_Z ( ZSTD_compressBegin_usingDict(refCtx, dict, dictSize, cLevel) );\n } else {\n ZSTD_compressionParameters const cPar = ZSTD_getCParams(cLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize);\n ZSTD_frameParameters const fPar = { FUZ_rand(&lseed)&1 /* contentSizeFlag */,\n !(FUZ_rand(&lseed)&3) /* contentChecksumFlag*/,\n 0 /*NodictID*/ }; /* note : since dictionary is fake, dictIDflag has no impact */\n ZSTD_parameters const p = FUZ_makeParams(cPar, fPar);\n CHECK_Z ( ZSTD_compressBegin_advanced(refCtx, dict, dictSize, p, 0) );\n }\n CHECK_Z( ZSTD_copyCCtx(ctx, refCtx, 0) );\n }\n\n { U32 const nbChunks = (FUZ_rand(&lseed) & 127) + 2;\n U32 n;\n XXH64_state_t xxhState;\n XXH64_reset(&xxhState, 0);\n for (totalTestSize=0, cSize=0, n=0 ; n maxTestSize) break;\n\n { size_t const compressResult = ZSTD_compressContinue(ctx, cBuffer+cSize, cBufferSize-cSize, srcBuffer+segmentStart, segmentSize);\n CHECK (ZSTD_isError(compressResult), \"multi-segments compression error : %s\", ZSTD_getErrorName(compressResult));\n cSize += compressResult;\n }\n XXH64_update(&xxhState, srcBuffer+segmentStart, segmentSize);\n memcpy(mirrorBuffer + totalTestSize, srcBuffer+segmentStart, segmentSize);\n totalTestSize += segmentSize;\n }\n\n { size_t const flushResult = ZSTD_compressEnd(ctx, cBuffer+cSize, cBufferSize-cSize, NULL, 0);\n CHECK (ZSTD_isError(flushResult), \"multi-segments epilogue error : %s\", ZSTD_getErrorName(flushResult));\n cSize += flushResult;\n }\n crcOrig = XXH64_digest(&xxhState);\n }\n\n /* streaming decompression test */\n DISPLAYLEVEL(5, \"fuzzer t%u: Bufferless streaming decompression test \\n\", testNb);\n /* ensure memory requirement is good enough (should always be true) */\n { ZSTD_frameHeader zfh;\n CHECK( ZSTD_getFrameHeader(&zfh, cBuffer, ZSTD_frameHeaderSize_max),\n \"ZSTD_getFrameHeader(): error retrieving frame information\");\n { size_t const roundBuffSize = ZSTD_decodingBufferSize_min(zfh.windowSize, zfh.frameContentSize);\n CHECK_Z(roundBuffSize);\n CHECK((roundBuffSize > totalTestSize) && (zfh.frameContentSize!=ZSTD_CONTENTSIZE_UNKNOWN),\n \"ZSTD_decodingBufferSize_min() requires more memory (%u) than necessary (%u)\",\n (U32)roundBuffSize, (U32)totalTestSize );\n } }\n if (dictSize<8) dictSize=0, dict=NULL; /* disable dictionary */\n CHECK_Z( ZSTD_decompressBegin_usingDict(dctx, dict, dictSize) );\n totalCSize = 0;\n totalGenSize = 0;\n while (totalCSize < cSize) {\n size_t const inSize = ZSTD_nextSrcSizeToDecompress(dctx);\n size_t const genSize = ZSTD_decompressContinue(dctx, dstBuffer+totalGenSize, dstBufferSize-totalGenSize, cBuffer+totalCSize, inSize);\n CHECK (ZSTD_isError(genSize), \"ZSTD_decompressContinue error : %s\", ZSTD_getErrorName(genSize));\n totalGenSize += genSize;\n totalCSize += inSize;\n }\n CHECK (ZSTD_nextSrcSizeToDecompress(dctx) != 0, \"frame not fully decoded\");\n CHECK (totalGenSize != totalTestSize, \"streaming decompressed data : wrong size\")\n CHECK (totalCSize != cSize, \"compressed data should be fully read\")\n { U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0);\n CHECK(crcOrig != crcDest, \"streaming decompressed data corrupted (pos %u / %u)\",\n (U32)findDiff(mirrorBuffer, dstBuffer, totalTestSize), (U32)totalTestSize);\n }\n } /* for ( ; (testNb <= nbTests) */\n DISPLAY(\"\\r%u fuzzer tests completed \\n\", testNb-1);\n\n_cleanup:\n ZSTD_freeCCtx(refCtx);\n ZSTD_freeCCtx(ctx);\n ZSTD_freeDCtx(dctx);\n free(cNoiseBuffer[0]);\n free(cNoiseBuffer[1]);\n free(cNoiseBuffer[2]);\n free(cNoiseBuffer[3]);\n free(cNoiseBuffer[4]);\n free(cBuffer);\n free(dstBuffer);\n free(mirrorBuffer);\n return result;\n\n_output_error:\n result = 1;\n goto _cleanup;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'fixed T36302429'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void TestJlCompress::extractDir()\n{\n QFETCH(QString, zipName);\n QFETCH(QStringList, fileNames);\n QDir curDir;\n if (!curDir.mkpath(\"jlext/jldir\")) {\n QFAIL(\"Couldn't mkpath jlext/jldir\");\n }\n if (!createTestFiles(fileNames)) {\n QFAIL(\"Couldn't create test files\");\n }\n if (!createTestArchive(zipName, fileNames)) {\n QFAIL(\"Couldn't create test archive\");\n }\n QStringList extracted;\n QCOMPARE((extracted = JlCompress::extractDir(zipName, \"jlext/jldir\"))\n .count(), fileNames.count());\n foreach (QString fileName, fileNames) {\n QString fullName = \"jlext/jldir/\" + fileName;\n QFileInfo fileInfo(fullName);\n QFileInfo extInfo(\"tmp/\" + fileName);\n if (!fileInfo.isDir())\n QCOMPARE(fileInfo.size(), extInfo.size());\n QCOMPARE(fileInfo.permissions(), extInfo.permissions());\n curDir.remove(fullName);\n curDir.rmpath(fileInfo.dir().path());\n QString absolutePath = fileInfo.absoluteFilePath();\n if (fileInfo.isDir() && !absolutePath.endsWith('/'))\n\t absolutePath += '/';\n QVERIFY(extracted.contains(absolutePath));\n }\n // now test the QIODevice* overload\n QFile zipFile(zipName);\n QVERIFY(zipFile.open(QIODevice::ReadOnly));\n QCOMPARE((extracted = JlCompress::extractDir(&zipFile, \"jlext/jldir\"))\n .count(), fileNames.count());\n foreach (QString fileName, fileNames) {\n QString fullName = \"jlext/jldir/\" + fileName;\n QFileInfo fileInfo(fullName);\n QFileInfo extInfo(\"tmp/\" + fileName);\n if (!fileInfo.isDir())\n QCOMPARE(fileInfo.size(), extInfo.size());\n QCOMPARE(fileInfo.permissions(), extInfo.permissions());\n curDir.remove(fullName);\n curDir.rmpath(fileInfo.dir().path());\n QString absolutePath = fileInfo.absoluteFilePath();\n if (fileInfo.isDir() && !absolutePath.endsWith('/'))\n absolutePath += '/';\n QVERIFY(extracted.contains(absolutePath));\n }\n zipFile.close();\n curDir.rmpath(\"jlext/jldir\");\n removeTestFiles(fileNames);\n curDir.remove(zipName);\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: void readTOMLConf(toml::value &root)\n{\n const auto §ion_common = toml::find(root, \"common\");\n string_array default_url, insert_url;\n\n find_if_exist(section_common, \"default_url\", default_url, \"insert_url\", insert_url);\n global.defaultUrls = join(default_url, \"|\");\n global.insertUrls = join(insert_url, \"|\");\n\n bool filter = false;\n find_if_exist(section_common,\n \"api_mode\", global.APIMode,\n \"api_access_token\", global.accessToken,\n \"exclude_remarks\", global.excludeRemarks,\n \"include_remarks\", global.includeRemarks,\n \"enable_insert\", global.enableInsert,\n \"prepend_insert_url\", global.prependInsert,\n \"enable_filter\", filter,\n \"default_external_config\", global.defaultExtConfig,\n \"base_path\", global.basePath,\n \"clash_rule_base\", global.clashBase,\n \"surge_rule_base\", global.surgeBase,\n \"surfboard_rule_base\", global.surfboardBase,\n \"mellow_rule_base\", global.mellowBase,\n \"quan_rule_base\", global.quanBase,\n \"quanx_rule_base\", global.quanXBase,\n \"loon_rule_base\", global.loonBase,\n \"proxy_config\", global.proxyConfig,\n \"proxy_ruleset\", global.proxyRuleset,\n \"proxy_subscription\", global.proxySubscription,\n \"append_proxy_type\", global.appendType\n );\n\n if(filter)\n find_if_exist(section_common, \"filter_script\", global.filterScript);\n else\n global.filterScript.clear();\n\n safe_set_streams(toml::find_or(root, \"userinfo\", \"stream_rule\", RegexMatchConfigs{}));\n safe_set_times(toml::find_or(root, \"userinfo\", \"time_rule\", RegexMatchConfigs{}));\n\n const auto §ion_node_pref = toml::find(root, \"node_pref\");\n\n find_if_exist(section_node_pref,\n \"udp_flag\", global.UDPFlag,\n \"tcp_fast_open_flag\", global.TFOFlag,\n \"skip_cert_verify_flag\", global.skipCertVerify,\n \"tls13_flag\", global.TLS13Flag,\n \"sort_flag\", global.enableSort,\n \"sort_script\", global.sortScript,\n \"filter_deprecated_nodes\", global.filterDeprecated,\n \"append_sub_userinfo\", global.appendUserinfo,\n \"clash_use_new_field_name\", global.clashUseNewField,\n \"clash_proxies_style\", global.clashProxiesStyle\n );\n\n auto renameconfs = toml::find_or>(section_node_pref, \"rename_node\", {});\n importItems(renameconfs, \"rename_node\", false);\n safe_set_renames(toml::get(toml::value(renameconfs)));\n\n const auto §ion_managed = toml::find(root, \"managed_config\");\n\n find_if_exist(section_managed,\n \"write_managed_config\", global.writeManagedConfig,\n \"managed_config_prefix\", global.managedConfigPrefix,\n \"config_update_interval\", global.updateInterval,\n \"config_update_strict\", global.updateStrict,\n \"quanx_device_id\", global.quanXDevID\n );\n\n const auto §ion_surge_external = toml::find(root, \"surge_external_proxy\");\n find_if_exist(section_surge_external,\n \"surge_ssr_path\", global.surgeSSRPath,\n \"resolve_hostname\", global.surgeResolveHostname\n );\n\n const auto §ion_emojis = toml::find(root, \"emojis\");\n\n find_if_exist(section_emojis,\n \"add_emoji\", global.addEmoji,\n \"remove_old_emoji\", global.removeEmoji\n );\n\n auto emojiconfs = toml::find_or>(section_emojis, \"emoji\", {});\n importItems(emojiconfs, \"emoji\", false);\n safe_set_emojis(toml::get(toml::value(emojiconfs)));\n\n auto groups = toml::find_or>(root, \"custom_groups\", {});\n importItems(groups, \"custom_groups\", false);\n global.customProxyGroups = toml::get(toml::value(groups));\n\n const auto §ion_ruleset = toml::find(root, \"ruleset\");\n\n find_if_exist(section_ruleset,\n \"enabled\", global.enableRuleGen,\n \"overwrite_original_rules\", global.overwriteOriginalRules,\n \"update_ruleset_on_request\", global.updateRulesetOnRequest\n );\n\n auto rulesets = toml::find_or>(root, \"rulesets\", {});\n importItems(rulesets, \"rulesets\", false);\n global.customRulesets = toml::get(toml::value(rulesets));\n\n const auto §ion_template = toml::find(root, \"template\");\n\n global.templatePath = toml::find_or(section_template, \"template_path\", \"template\");\n\n eraseElements(global.templateVars);\n operate_toml_kv_table(toml::find_or>(section_template, \"globals\", {}), \"key\", \"value\", [&](const toml::value &key, const toml::value &value)\n {\n global.templateVars[key.as_string()] = value.as_string();\n });\n\n webServer.reset_redirect();\n operate_toml_kv_table(toml::find_or>(root, \"aliases\", {}), \"uri\", \"target\", [&](const toml::value &key, const toml::value &value)\n {\n webServer.append_redirect(key.as_string(), value.as_string());\n });\n\n auto tasks = toml::find_or>(root, \"tasks\", {});\n importItems(tasks, \"tasks\", false);\n global.cronTasks = toml::get(toml::value(tasks));\n\n const auto §ion_server = toml::find(root, \"server\");\n\n find_if_exist(section_server,\n \"listen\", global.listenAddress,\n \"port\", global.listenPort,\n \"serve_file_root\", webServer.serve_file_root\n );\n webServer.serve_file = !webServer.serve_file_root.empty();\n\n const auto §ion_advanced = toml::find(root, \"advanced\");\n\n std::string log_level;\n bool enable_cache = true;\n int cache_subscription = global.cacheSubscription, cache_config = global.cacheConfig, cache_ruleset = global.cacheRuleset;\n\n find_if_exist(section_advanced,\n \"log_level\", log_level,\n \"print_debug_info\", global.printDbgInfo,\n \"max_pending_connections\", global.maxPendingConns,\n \"max_concurrent_threads\", global.maxConcurThreads,\n \"max_allowed_rulesets\", global.maxAllowedRulesets,\n \"max_allowed_rules\", global.maxAllowedRules,\n \"max_allowed_download_size\", global.maxAllowedDownloadSize,\n \"enable_cache\", enable_cache,\n \"cache_subscription\", cache_subscription,\n \"cache_config\", cache_config,\n \"cache_ruleset\", cache_ruleset,\n \"script_clean_context\", global.scriptCleanContext,\n \"async_fetch_ruleset\", global.asyncFetchRuleset,\n \"skip_failed_links\", global.skipFailedLinks\n );\n\n if(global.printDbgInfo)\n global.logLevel = LOG_LEVEL_VERBOSE;\n else\n {\n switch(hash_(log_level))\n {\n case \"warn\"_hash:\n global.logLevel = LOG_LEVEL_WARNING;\n break;\n case \"error\"_hash:\n global.logLevel = LOG_LEVEL_ERROR;\n break;\n case \"fatal\"_hash:\n global.logLevel = LOG_LEVEL_FATAL;\n break;\n case \"verbose\"_hash:\n global.logLevel = LOG_LEVEL_VERBOSE;\n break;\n case \"debug\"_hash:\n global.logLevel = LOG_LEVEL_DEBUG;\n break;\n default:\n global.logLevel = LOG_LEVEL_INFO;\n }\n }\n\n if(enable_cache)\n {\n global.cacheSubscription = cache_subscription;\n global.cacheConfig = cache_config;\n global.cacheRuleset = cache_ruleset;\n }\n else\n {\n global.cacheSubscription = global.cacheConfig = global.cacheRuleset = 0;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-434', 'CWE-94'], 'message': 'Enhancements\n\nAdd authorization check before loading scripts.\nAdd detailed logs when loading preference settings.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void ValidateInputs(OpKernelContext* ctx,\n const CSRSparseMatrix& sparse_matrix,\n const Tensor& permutation_indices, int* batch_size,\n int64* num_rows) {\n OP_REQUIRES(ctx, sparse_matrix.dtype() == DataTypeToEnum::value,\n errors::InvalidArgument(\n \"Asked for a CSRSparseMatrix of type \",\n DataTypeString(DataTypeToEnum::value),\n \" but saw dtype: \", DataTypeString(sparse_matrix.dtype())));\n\n const Tensor& dense_shape = sparse_matrix.dense_shape();\n const int rank = dense_shape.dim_size(0);\n OP_REQUIRES(ctx, rank == 2 || rank == 3,\n errors::InvalidArgument(\"sparse matrix must have rank 2 or 3; \",\n \"but dense_shape has size \", rank));\n const int row_dim = (rank == 2) ? 0 : 1;\n auto dense_shape_vec = dense_shape.vec();\n *num_rows = dense_shape_vec(row_dim);\n const int64 num_cols = dense_shape_vec(row_dim + 1);\n OP_REQUIRES(ctx, *num_rows == num_cols,\n errors::InvalidArgument(\"sparse matrix must be square; got: \",\n *num_rows, \" != \", num_cols));\n const TensorShape& perm_shape = permutation_indices.shape();\n OP_REQUIRES(\n ctx, perm_shape.dims() + 1 == rank,\n errors::InvalidArgument(\n \"sparse matrix must have the same rank as permutation; got: \", rank,\n \" != \", perm_shape.dims(), \" + 1.\"));\n OP_REQUIRES(\n ctx, perm_shape.dim_size(rank - 2) == *num_rows,\n errors::InvalidArgument(\n \"permutation must have the same number of elements in each batch \"\n \"as the number of rows in sparse matrix; got: \",\n perm_shape.dim_size(rank - 2), \" != \", *num_rows));\n\n *batch_size = sparse_matrix.batch_size();\n if (*batch_size > 1) {\n OP_REQUIRES(\n ctx, perm_shape.dim_size(0) == *batch_size,\n errors::InvalidArgument(\"permutation must have the same batch size \"\n \"as sparse matrix; got: \",\n perm_shape.dim_size(0), \" != \", *batch_size));\n }\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: static int key_notify_policy_flush(const struct km_event *c)\n{\n\tstruct sk_buff *skb_out;\n\tstruct sadb_msg *hdr;\n\n\tskb_out = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC);\n\tif (!skb_out)\n\t\treturn -ENOBUFS;\n\thdr = (struct sadb_msg *) skb_put(skb_out, sizeof(struct sadb_msg));\n\thdr->sadb_msg_type = SADB_X_SPDFLUSH;\n\thdr->sadb_msg_seq = c->seq;\n\thdr->sadb_msg_pid = c->portid;\n\thdr->sadb_msg_version = PF_KEY_V2;\n\thdr->sadb_msg_errno = (uint8_t) 0;\n\thdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t));\n\tpfkey_broadcast(skb_out, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net);\n\treturn 0;\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'af_key: initialize satype in key_notify_policy_flush()\n\nThis field was left uninitialized. Some user daemons perform check against this\nfield.\n\nSigned-off-by: Nicolas Dichtel \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: int ip6_fragment(struct sk_buff *skb, int (*output)(struct sk_buff *))\n{\n\tstruct sk_buff *frag;\n\tstruct rt6_info *rt = (struct rt6_info*)skb_dst(skb);\n\tstruct ipv6_pinfo *np = skb->sk ? inet6_sk(skb->sk) : NULL;\n\tstruct ipv6hdr *tmp_hdr;\n\tstruct frag_hdr *fh;\n\tunsigned int mtu, hlen, left, len;\n\t__be32 frag_id = 0;\n\tint ptr, offset = 0, err=0;\n\tu8 *prevhdr, nexthdr = 0;\n\tstruct net *net = dev_net(skb_dst(skb)->dev);\n\n\thlen = ip6_find_1stfragopt(skb, &prevhdr);\n\tnexthdr = *prevhdr;\n\n\tmtu = ip6_skb_dst_mtu(skb);\n\n\t/* We must not fragment if the socket is set to force MTU discovery\n\t * or if the skb it not generated by a local socket.\n\t */\n\tif (!skb->local_df && skb->len > mtu) {\n\t\tskb->dev = skb_dst(skb)->dev;\n\t\ticmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);\n\t\tIP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),\n\t\t\t IPSTATS_MIB_FRAGFAILS);\n\t\tkfree_skb(skb);\n\t\treturn -EMSGSIZE;\n\t}\n\n\tif (np && np->frag_size < mtu) {\n\t\tif (np->frag_size)\n\t\t\tmtu = np->frag_size;\n\t}\n\tmtu -= hlen + sizeof(struct frag_hdr);\n\n\tif (skb_has_frag_list(skb)) {\n\t\tint first_len = skb_pagelen(skb);\n\t\tstruct sk_buff *frag2;\n\n\t\tif (first_len - hlen > mtu ||\n\t\t ((first_len - hlen) & 7) ||\n\t\t skb_cloned(skb))\n\t\t\tgoto slow_path;\n\n\t\tskb_walk_frags(skb, frag) {\n\t\t\t/* Correct geometry. */\n\t\t\tif (frag->len > mtu ||\n\t\t\t ((frag->len & 7) && frag->next) ||\n\t\t\t skb_headroom(frag) < hlen)\n\t\t\t\tgoto slow_path_clean;\n\n\t\t\t/* Partially cloned skb? */\n\t\t\tif (skb_shared(frag))\n\t\t\t\tgoto slow_path_clean;\n\n\t\t\tBUG_ON(frag->sk);\n\t\t\tif (skb->sk) {\n\t\t\t\tfrag->sk = skb->sk;\n\t\t\t\tfrag->destructor = sock_wfree;\n\t\t\t}\n\t\t\tskb->truesize -= frag->truesize;\n\t\t}\n\n\t\terr = 0;\n\t\toffset = 0;\n\t\tfrag = skb_shinfo(skb)->frag_list;\n\t\tskb_frag_list_init(skb);\n\t\t/* BUILD HEADER */\n\n\t\t*prevhdr = NEXTHDR_FRAGMENT;\n\t\ttmp_hdr = kmemdup(skb_network_header(skb), hlen, GFP_ATOMIC);\n\t\tif (!tmp_hdr) {\n\t\t\tIP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),\n\t\t\t\t IPSTATS_MIB_FRAGFAILS);\n\t\t\treturn -ENOMEM;\n\t\t}\n\n\t\t__skb_pull(skb, hlen);\n\t\tfh = (struct frag_hdr*)__skb_push(skb, sizeof(struct frag_hdr));\n\t\t__skb_push(skb, hlen);\n\t\tskb_reset_network_header(skb);\n\t\tmemcpy(skb_network_header(skb), tmp_hdr, hlen);\n\n\t\tipv6_select_ident(fh);\n\t\tfh->nexthdr = nexthdr;\n\t\tfh->reserved = 0;\n\t\tfh->frag_off = htons(IP6_MF);\n\t\tfrag_id = fh->identification;\n\n\t\tfirst_len = skb_pagelen(skb);\n\t\tskb->data_len = first_len - skb_headlen(skb);\n\t\tskb->len = first_len;\n\t\tipv6_hdr(skb)->payload_len = htons(first_len -\n\t\t\t\t\t\t sizeof(struct ipv6hdr));\n\n\t\tdst_hold(&rt->dst);\n\n\t\tfor (;;) {\n\t\t\t/* Prepare header of the next frame,\n\t\t\t * before previous one went down. */\n\t\t\tif (frag) {\n\t\t\t\tfrag->ip_summed = CHECKSUM_NONE;\n\t\t\t\tskb_reset_transport_header(frag);\n\t\t\t\tfh = (struct frag_hdr*)__skb_push(frag, sizeof(struct frag_hdr));\n\t\t\t\t__skb_push(frag, hlen);\n\t\t\t\tskb_reset_network_header(frag);\n\t\t\t\tmemcpy(skb_network_header(frag), tmp_hdr,\n\t\t\t\t hlen);\n\t\t\t\toffset += skb->len - hlen - sizeof(struct frag_hdr);\n\t\t\t\tfh->nexthdr = nexthdr;\n\t\t\t\tfh->reserved = 0;\n\t\t\t\tfh->frag_off = htons(offset);\n\t\t\t\tif (frag->next != NULL)\n\t\t\t\t\tfh->frag_off |= htons(IP6_MF);\n\t\t\t\tfh->identification = frag_id;\n\t\t\t\tipv6_hdr(frag)->payload_len =\n\t\t\t\t\t\thtons(frag->len -\n\t\t\t\t\t\t sizeof(struct ipv6hdr));\n\t\t\t\tip6_copy_metadata(frag, skb);\n\t\t\t}\n\n\t\t\terr = output(skb);\n\t\t\tif(!err)\n\t\t\t\tIP6_INC_STATS(net, ip6_dst_idev(&rt->dst),\n\t\t\t\t\t IPSTATS_MIB_FRAGCREATES);\n\n\t\t\tif (err || !frag)\n\t\t\t\tbreak;\n\n\t\t\tskb = frag;\n\t\t\tfrag = skb->next;\n\t\t\tskb->next = NULL;\n\t\t}\n\n\t\tkfree(tmp_hdr);\n\n\t\tif (err == 0) {\n\t\t\tIP6_INC_STATS(net, ip6_dst_idev(&rt->dst),\n\t\t\t\t IPSTATS_MIB_FRAGOKS);\n\t\t\tdst_release(&rt->dst);\n\t\t\treturn 0;\n\t\t}\n\n\t\twhile (frag) {\n\t\t\tskb = frag->next;\n\t\t\tkfree_skb(frag);\n\t\t\tfrag = skb;\n\t\t}\n\n\t\tIP6_INC_STATS(net, ip6_dst_idev(&rt->dst),\n\t\t\t IPSTATS_MIB_FRAGFAILS);\n\t\tdst_release(&rt->dst);\n\t\treturn err;\n\nslow_path_clean:\n\t\tskb_walk_frags(skb, frag2) {\n\t\t\tif (frag2 == frag)\n\t\t\t\tbreak;\n\t\t\tfrag2->sk = NULL;\n\t\t\tfrag2->destructor = NULL;\n\t\t\tskb->truesize += frag2->truesize;\n\t\t}\n\t}\n\nslow_path:\n\tleft = skb->len - hlen;\t\t/* Space per frame */\n\tptr = hlen;\t\t\t/* Where to start from */\n\n\t/*\n\t *\tFragment the datagram.\n\t */\n\n\t*prevhdr = NEXTHDR_FRAGMENT;\n\n\t/*\n\t *\tKeep copying data until we run out.\n\t */\n\twhile(left > 0)\t{\n\t\tlen = left;\n\t\t/* IF: it doesn't fit, use 'mtu' - the data space left */\n\t\tif (len > mtu)\n\t\t\tlen = mtu;\n\t\t/* IF: we are not sending up to and including the packet end\n\t\t then align the next start on an eight byte boundary */\n\t\tif (len < left)\t{\n\t\t\tlen &= ~7;\n\t\t}\n\t\t/*\n\t\t *\tAllocate buffer.\n\t\t */\n\n\t\tif ((frag = alloc_skb(len+hlen+sizeof(struct frag_hdr)+LL_ALLOCATED_SPACE(rt->dst.dev), GFP_ATOMIC)) == NULL) {\n\t\t\tNETDEBUG(KERN_INFO \"IPv6: frag: no memory for new fragment!\\n\");\n\t\t\tIP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),\n\t\t\t\t IPSTATS_MIB_FRAGFAILS);\n\t\t\terr = -ENOMEM;\n\t\t\tgoto fail;\n\t\t}\n\n\t\t/*\n\t\t *\tSet up data on packet\n\t\t */\n\n\t\tip6_copy_metadata(frag, skb);\n\t\tskb_reserve(frag, LL_RESERVED_SPACE(rt->dst.dev));\n\t\tskb_put(frag, len + hlen + sizeof(struct frag_hdr));\n\t\tskb_reset_network_header(frag);\n\t\tfh = (struct frag_hdr *)(skb_network_header(frag) + hlen);\n\t\tfrag->transport_header = (frag->network_header + hlen +\n\t\t\t\t\t sizeof(struct frag_hdr));\n\n\t\t/*\n\t\t *\tCharge the memory for the fragment to any owner\n\t\t *\tit might possess\n\t\t */\n\t\tif (skb->sk)\n\t\t\tskb_set_owner_w(frag, skb->sk);\n\n\t\t/*\n\t\t *\tCopy the packet header into the new buffer.\n\t\t */\n\t\tskb_copy_from_linear_data(skb, skb_network_header(frag), hlen);\n\n\t\t/*\n\t\t *\tBuild fragment header.\n\t\t */\n\t\tfh->nexthdr = nexthdr;\n\t\tfh->reserved = 0;\n\t\tif (!frag_id) {\n\t\t\tipv6_select_ident(fh);\n\t\t\tfrag_id = fh->identification;\n\t\t} else\n\t\t\tfh->identification = frag_id;\n\n\t\t/*\n\t\t *\tCopy a block of the IP datagram.\n\t\t */\n\t\tif (skb_copy_bits(skb, ptr, skb_transport_header(frag), len))\n\t\t\tBUG();\n\t\tleft -= len;\n\n\t\tfh->frag_off = htons(offset);\n\t\tif (left > 0)\n\t\t\tfh->frag_off |= htons(IP6_MF);\n\t\tipv6_hdr(frag)->payload_len = htons(frag->len -\n\t\t\t\t\t\t sizeof(struct ipv6hdr));\n\n\t\tptr += len;\n\t\toffset += len;\n\n\t\t/*\n\t\t *\tPut this fragment into the sending queue.\n\t\t */\n\t\terr = output(frag);\n\t\tif (err)\n\t\t\tgoto fail;\n\n\t\tIP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),\n\t\t\t IPSTATS_MIB_FRAGCREATES);\n\t}\n\tIP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),\n\t\t IPSTATS_MIB_FRAGOKS);\n\tkfree_skb(skb);\n\treturn err;\n\nfail:\n\tIP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),\n\t\t IPSTATS_MIB_FRAGFAILS);\n\tkfree_skb(skb);\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: GF_Err stbl_AddDTS(GF_SampleTableBox *stbl, u64 DTS, u32 *sampleNumber, u32 LastAUDefDuration, u32 nb_packed_samples)\n{\n\tu32 i, j, sampNum;\n\tu64 *DTSs, curDTS;\n\tBool inserted;\n\tGF_SttsEntry *ent;\n\n\tGF_TimeToSampleBox *stts = stbl->TimeToSample;\n\n\t//reset the reading cache when adding a sample\n\tstts->r_FirstSampleInEntry = 0;\n\n\t*sampleNumber = 0;\n\tif (!nb_packed_samples)\n\t\tnb_packed_samples=1;\n\n\t//if we don't have an entry, that's the first one...\n\tif (!stts->nb_entries) {\n\t\t//assert the first DTS is 0. If not, that will break the whole file\n\t\tif (DTS) return GF_BAD_PARAM;\n\t\tstts->alloc_size = 1;\n\t\tstts->nb_entries = 1;\n\t\tstts->entries = gf_malloc(sizeof(GF_SttsEntry));\n\t\tif (!stts->entries) return GF_OUT_OF_MEM;\n\t\tstts->entries[0].sampleCount = nb_packed_samples;\n\t\tstts->entries[0].sampleDelta = (nb_packed_samples>1) ? 0 : LastAUDefDuration;\n\t\t(*sampleNumber) = 1;\n\t\tstts->w_currentSampleNum = nb_packed_samples;\n\t\treturn GF_OK;\n\t}\n\t//check the last DTS - we allow 0-duration samples (same DTS)\n\tif (DTS >= stts->w_LastDTS) {\n\t\tu32 nb_extra = 0;\n\t\tent = &stts->entries[stts->nb_entries-1];\n\t\tif (!ent->sampleDelta && (ent->sampleCount>1)) {\n\t\t\tent->sampleDelta = (u32) ( DTS / ent->sampleCount);\n\t\t\tstts->w_LastDTS = DTS - ent->sampleDelta;\n\t\t}\n\t\t//OK, we're adding at the end\n\t\tif ((DTS == stts->w_LastDTS + ent->sampleDelta)\n\t\t\t//for raw audio, consider (dts==last_dts) and (dts==last_dts+2*delta) as sample append to cope with\n\t\t\t//timescale vs samplerate precision\n\t\t\t|| ((nb_packed_samples>1) && ((DTS == stts->w_LastDTS) || (DTS == stts->w_LastDTS + 2*ent->sampleDelta) ))\n\t\t) {\n\t\t\t(*sampleNumber) = stts->w_currentSampleNum + 1;\n\t\t\tent->sampleCount += nb_packed_samples;\n\t\t\tstts->w_currentSampleNum += nb_packed_samples;\n\t\t\tstts->w_LastDTS = DTS + ent->sampleDelta * (nb_packed_samples-1);\n\t\t\treturn GF_OK;\n\t\t}\n\t\t//we need to split the entry\n\t\tif (ent->sampleCount == 1) {\n\t\t\t//FIXME - we need more tests with timed text\n#if 0\n\t\t\tif (stts->w_LastDTS)\n\t\t\t\tent->sampleDelta += (u32) (DTS - stts->w_LastDTS);\n\t\t\telse\n\t\t\t\tent->sampleDelta = (u32) DTS;\n#else\n\t\t\t//use this one and adjust...\n\t\t\tent->sampleDelta = (u32) (DTS - stts->w_LastDTS);\n#endif\n\n\t\t\tent->sampleCount ++;\n\t\t\t//little opt, merge last entry with previous one if same delta\n\t\t\tif ((stts->nb_entries>=2) && (ent->sampleDelta== stts->entries[stts->nb_entries-2].sampleDelta)) {\n\t\t\t\tstts->entries[stts->nb_entries-2].sampleCount += ent->sampleCount;\n\t\t\t\tstts->nb_entries--;\n\t\t\t}\n\t\t\tstts->w_currentSampleNum ++;\n\t\t\tstts->w_LastDTS = DTS;\n\t\t\t(*sampleNumber) = stts->w_currentSampleNum;\n\t\t\treturn GF_OK;\n\t\t}\n\t\t//we definitely need to split the entry ;)\n\t\tent->sampleCount --;\n\n\t\tif (nb_packed_samples>1)\n\t\t\tnb_extra = 1;\n\n\t\tif (stts->alloc_size <= stts->nb_entries + nb_extra) {\n\t\t\tALLOC_INC(stts->alloc_size);\n\t\t\tstts->entries = gf_realloc(stts->entries, sizeof(GF_SttsEntry)*stts->alloc_size);\n\t\t\tif (!stts->entries) return GF_OUT_OF_MEM;\n\t\t\tmemset(&stts->entries[stts->nb_entries], 0, sizeof(GF_SttsEntry)*(stts->alloc_size-stts->nb_entries) );\n\t\t}\n\n\t\tif (nb_extra)\n\t\t\tnb_extra = stts->entries[stts->nb_entries-1].sampleDelta;\n\n\t\tent = &stts->entries[stts->nb_entries];\n\t\tstts->nb_entries++;\n\n\t\tif (nb_packed_samples==1) {\n\t\t\tent->sampleCount = 2;\n\t\t\tent->sampleDelta = (u32) (DTS - stts->w_LastDTS);\n\t\t\tstts->w_LastDTS = DTS;\n\t\t\t(*sampleNumber) = stts->w_currentSampleNum+1;\n\t\t\tstts->w_currentSampleNum += 1;\n\t\t\treturn GF_OK;\n\t\t}\n\n\t\tent->sampleCount = 1;\n\t\tent->sampleDelta = (u32) (DTS - stts->w_LastDTS);\n\n\t\tent = &stts->entries[stts->nb_entries];\n\t\tstts->nb_entries++;\n\n\t\tent->sampleCount = nb_packed_samples;\n\t\tent->sampleDelta = nb_extra;\n\t\tstts->w_LastDTS = DTS;\n\t\t(*sampleNumber) = stts->w_currentSampleNum + 1;\n\t\tstts->w_currentSampleNum += nb_packed_samples;\n\t\treturn GF_OK;\n\t}\n\n\n\t//unpack the DTSs and locate new sample...\n\tDTSs = (u64*)gf_malloc(sizeof(u64) * (stbl->SampleSize->sampleCount+2) );\n\tif (!DTSs) return GF_OUT_OF_MEM;\n\tcurDTS = 0;\n\tsampNum = 0;\n\tent = NULL;\n\tinserted = 0;\n\tfor (i=0; inb_entries; i++) {\n\t\tent = & stts->entries[i];\n\t\tfor (j = 0; jsampleCount; j++) {\n\t\t\tif (!inserted && (curDTS > DTS)) {\n\t\t\t\tDTSs[sampNum] = DTS;\n\t\t\t\tsampNum++;\n\t\t\t\t*sampleNumber = sampNum;\n\t\t\t\tinserted = 1;\n\t\t\t}\n\t\t\tDTSs[sampNum] = curDTS;\n\t\t\tcurDTS += ent->sampleDelta;\n\t\t\tsampNum ++;\n\t\t}\n\t}\n\tif (!inserted) {\n\t\tgf_free(DTSs);\n\t\treturn GF_BAD_PARAM;\n\t}\n\n\t/*we will at most insert 3 new entries*/\n\tif (stts->nb_entries+3 >= stts->alloc_size) {\n\t\tstts->alloc_size += 3;\n\t\tstts->entries = gf_realloc(stts->entries, sizeof(GF_SttsEntry)*stts->alloc_size);\n\t\tif (!stts->entries) return GF_OUT_OF_MEM;\n\t\tmemset(&stts->entries[stts->nb_entries], 0, sizeof(GF_SttsEntry)*(stts->alloc_size - stts->nb_entries) );\n\t}\n\n\t/*repack the DTSs*/\n\tj=0;\n\tstts->nb_entries = 1;\n\tstts->entries[0].sampleCount = 1;\n\tstts->entries[0].sampleDelta = (u32) DTSs[1] /* - (DTS[0] which is 0)*/;\n\tfor (i=1; iSampleSize->sampleCount+1; i++) {\n\t\tif (i == stbl->SampleSize->sampleCount) {\n\t\t\t//and by default, our last sample has the same delta as the prev\n\t\t\tstts->entries[j].sampleCount++;\n\t\t} else if (stts->entries[j].sampleDelta == (u32) ( DTSs[i+1] - DTSs[i]) ) {\n\t\t\tstts->entries[j].sampleCount ++;\n\t\t} else {\n\t\t\tstts->nb_entries ++;\n\t\t\tj++;\n\t\t\tstts->entries[j].sampleCount = 1;\n\t\t\tstts->entries[j].sampleDelta = (u32) (DTSs[i+1] - DTSs[i]);\n\t\t}\n\t}\n\tgf_free(DTSs);\n\n\t//reset the cache to the end\n\tstts->w_currentSampleNum = stbl->SampleSize->sampleCount + 1;\n\treturn GF_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'fixed #1774 (fuzz)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: 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, ACL_KIND_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: static int dxtory_decode_v1_rgb(AVCodecContext *avctx, AVFrame *pic,\n const uint8_t *src, int src_size,\n int id, int bpp)\n{\n int h;\n uint8_t *dst;\n int ret;\n\n if (src_size < avctx->width * avctx->height * bpp) {\n av_log(avctx, AV_LOG_ERROR, \"packet too small\\n\");\n return AVERROR_INVALIDDATA;\n }\n\n avctx->pix_fmt = id;\n if ((ret = ff_get_buffer(avctx, pic, 0)) < 0)\n return ret;\n\n dst = pic->data[0];\n for (h = 0; h < avctx->height; h++) {\n memcpy(dst, src, avctx->width * bpp);\n src += avctx->width * bpp;\n dst += pic->linesize[0];\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 samldb_lockout_time(struct samldb_ctx *ac)\n{\n\tstruct ldb_context *ldb = ldb_module_get_ctx(ac->module);\n\tNTTIME lockoutTime;\n\tstruct ldb_message_element *el;\n\tstruct ldb_message *tmp_msg;\n\tint ret;\n\n\tret = dsdb_get_expected_new_values(ac,\n\t\t\t\t\t ac->msg,\n\t\t\t\t\t \"lockoutTime\",\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: 'lockoutTime' 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 \"lockoutTime\" */\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\tlockoutTime = ldb_msg_find_attr_as_int64(tmp_msg,\n\t\t\t\t\t\t \"lockoutTime\",\n\t\t\t\t\t\t 0);\n\ttalloc_free(tmp_msg);\n\n\tif (lockoutTime != 0) {\n\t\treturn LDB_SUCCESS;\n\t}\n\n\t/* lockoutTime == 0 resets badPwdCount */\n\tldb_msg_remove_attr(ac->msg, \"badPwdCount\");\n\tret = samdb_msg_add_int(ldb, ac->msg, ac->msg,\n\t\t\t\t\"badPwdCount\", 0);\n\tif (ret != LDB_SUCCESS) {\n\t\treturn ret;\n\t}\n\tel = ldb_msg_find_element(ac->msg, \"badPwdCount\");\n\tel->flags = LDB_FLAG_MOD_REPLACE;\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 add_time_element(struct ldb_message *msg, const char *attr, time_t t)\n{\n\tstruct ldb_message_element *el;\n\tchar *s;\n\tint ret;\n\n\tif (ldb_msg_find_element(msg, attr) != NULL) {\n\t\treturn LDB_SUCCESS;\n\t}\n\n\ts = ldb_timestring(msg, t);\n\tif (s == NULL) {\n\t\treturn LDB_ERR_OPERATIONS_ERROR;\n\t}\n\n\tret = ldb_msg_add_string(msg, attr, s);\n\tif (ret != LDB_SUCCESS) {\n\t\treturn ret;\n\t}\n\n\tel = ldb_msg_find_element(msg, attr);\n\t/* always set as replace. This works because on add ops, the flag\n\t is ignored */\n\tel->flags = LDB_FLAG_MOD_REPLACE;\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 tr_prepare_attributes(struct tr_context *ac)\n{\n\tstruct ldb_context *ldb = ldb_module_get_ctx(ac->module);\n\tint ret;\n\tstruct ldb_message_element *el = NULL;\n\tuint32_t account_type, user_account_control;\n\tstruct ldb_dn *objectcategory = NULL;\n\n\tac->mod_msg = ldb_msg_copy_shallow(ac, ac->req_msg);\n\tif (ac->mod_msg == NULL) {\n\t\treturn ldb_oom(ldb);\n\t}\n\n\tac->mod_res = talloc_zero(ac, struct ldb_result);\n\tif (ac->mod_res == NULL) {\n\t\treturn ldb_oom(ldb);\n\t}\n\n\tret = ldb_build_mod_req(&ac->mod_req, ldb, ac,\n\t\t\t\tac->mod_msg,\n\t\t\t\tNULL,\n\t\t\t\tac->mod_res,\n\t\t\t\tldb_modify_default_callback,\n\t\t\t\tac->req);\n\tLDB_REQ_SET_LOCATION(ac->mod_req);\n\tif (ret != LDB_SUCCESS) {\n\t\treturn ret;\n\t}\n\n\t/* - remove distinguishedName - we don't need it */\n\tldb_msg_remove_attr(ac->mod_msg, \"distinguishedName\");\n\n\t/* remove isRecycled */\n\tret = ldb_msg_add_empty(ac->mod_msg, \"isRecycled\",\n\t\t\t\tLDB_FLAG_MOD_DELETE, NULL);\n\tif (ret != LDB_SUCCESS) {\n\t\tldb_asprintf_errstring(ldb, \"Failed to reset isRecycled attribute: %s\", ldb_strerror(ret));\n\t\treturn LDB_ERR_OPERATIONS_ERROR;\n\t}\n\n\t/* objectClass is USER */\n\tif (samdb_find_attribute(ldb, ac->search_msg, \"objectclass\", \"user\") != NULL) {\n\t\tuint32_t primary_group_rid;\n\t\t/* restoring 'user' instance attribute is heavily borrowed from samldb.c */\n\n\t\t/* Default values */\n\t\tret = dsdb_user_obj_set_defaults(ldb, ac->mod_msg, ac->mod_req);\n\t\tif (ret != LDB_SUCCESS) return ret;\n\n\t\t/* \"userAccountControl\" must exists on deleted object */\n\t\tuser_account_control = ldb_msg_find_attr_as_uint(ac->search_msg,\n\t\t\t\t\t\t\t\"userAccountControl\",\n\t\t\t\t\t\t\t(uint32_t)-1);\n\t\tif (user_account_control == (uint32_t)-1) {\n\t\t\treturn ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR,\n\t\t\t\t\t \"reanimate: No 'userAccountControl' attribute found!\");\n\t\t}\n\n\t\t/* restore \"sAMAccountType\" */\n\t\tret = dsdb_user_obj_set_account_type(ldb, ac->mod_msg,\n\t\t\t\t\t\t user_account_control, NULL);\n\t\tif (ret != LDB_SUCCESS) {\n\t\t\treturn ret;\n\t\t}\n\n\t\t/* \"userAccountControl\" -> \"primaryGroupID\" mapping */\n\t\tret = dsdb_user_obj_set_primary_group_id(ldb, ac->mod_msg,\n\t\t\t\t\t\t\t user_account_control,\n\t\t\t\t\t\t\t &primary_group_rid);\n\t\tif (ret != LDB_SUCCESS) {\n\t\t\treturn ret;\n\t\t}\n\t\t/*\n\t\t * Older AD deployments don't know about the\n\t\t * RODC group\n\t\t */\n\t\tif (primary_group_rid == DOMAIN_RID_READONLY_DCS) {\n\t\t\t/* TODO: check group exists */\n\t\t}\n\n\t}\n\n\t/* objectClass is GROUP */\n\tif (samdb_find_attribute(ldb, ac->search_msg, \"objectclass\", \"group\") != NULL) {\n\t\t/* \"groupType\" -> \"sAMAccountType\" */\n\t\tuint32_t group_type;\n\n\t\tel = ldb_msg_find_element(ac->search_msg, \"groupType\");\n\t\tif (el == NULL) {\n\t\t\treturn ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR,\n\t\t\t\t\t \"reanimate: Unexpected: missing groupType attribute.\");\n\t\t}\n\n\t\tgroup_type = ldb_msg_find_attr_as_uint(ac->search_msg,\n\t\t\t\t\t\t \"groupType\", 0);\n\n\t\taccount_type = ds_gtype2atype(group_type);\n\t\tif (account_type == 0) {\n\t\t\treturn ldb_error(ldb, LDB_ERR_UNWILLING_TO_PERFORM,\n\t\t\t\t\t \"reanimate: Unrecognized account type!\");\n\t\t}\n\t\tret = samdb_msg_add_uint(ldb, ac->mod_msg, ac->mod_msg,\n\t\t\t\t\t \"sAMAccountType\", account_type);\n\t\tif (ret != LDB_SUCCESS) {\n\t\t\treturn ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR,\n\t\t\t\t\t \"reanimate: Failed to add sAMAccountType to restored object.\");\n\t\t}\n\t\tel = ldb_msg_find_element(ac->mod_msg, \"sAMAccountType\");\n\t\tel->flags = LDB_FLAG_MOD_REPLACE;\n\n\t\t/* Default values set by Windows */\n\t\tret = samdb_find_or_add_attribute(ldb, ac->mod_msg,\n\t\t\t\t\t\t \"adminCount\", \"0\");\n\t\tif (ret != LDB_SUCCESS) return ret;\n\t\tret = samdb_find_or_add_attribute(ldb, ac->mod_msg,\n\t\t\t\t\t\t \"operatorCount\", \"0\");\n\t\tif (ret != LDB_SUCCESS) return ret;\n\t}\n\n\t/* - restore objectCategory if not present */\n\tobjectcategory = ldb_msg_find_attr_as_dn(ldb, ac, ac->search_msg,\n\t\t\t\t\t\t \"objectCategory\");\n\tif (objectcategory == NULL) {\n\t\tconst char *value;\n\n\t\tret = dsdb_make_object_category(ldb, ac->schema, ac->search_msg,\n\t\t\t\t\t\tac->mod_msg, &value);\n\t\tif (ret != LDB_SUCCESS) {\n\t\t\treturn ret;\n\t\t}\n\n\t\tret = ldb_msg_add_string(ac->mod_msg, \"objectCategory\", value);\n\t\tif (ret != LDB_SUCCESS) {\n\t\t\treturn ret;\n\t\t}\n\t\tel = ldb_msg_find_element(ac->mod_msg, \"objectCategory\");\n\t\tel->flags = LDB_FLAG_MOD_ADD;\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: decode_multicast_vpn(netdissect_options *ndo,\n const u_char *pptr, char *buf, u_int buflen)\n{\n uint8_t route_type, route_length, addr_length, sg_length;\n u_int offset;\n\n\tND_TCHECK2(pptr[0], 2);\n route_type = *pptr++;\n route_length = *pptr++;\n\n snprintf(buf, buflen, \"Route-Type: %s (%u), length: %u\",\n tok2str(bgp_multicast_vpn_route_type_values,\n \"Unknown\", route_type),\n route_type, route_length);\n\n switch(route_type) {\n case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI:\n ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);\n offset = strlen(buf);\n snprintf(buf + offset, buflen - offset, \", RD: %s, Originator %s\",\n bgp_vpn_rd_print(ndo, pptr),\n bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN,\n (route_length - BGP_VPN_RD_LEN) << 3));\n break;\n case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI:\n ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4);\n offset = strlen(buf);\n\t snprintf(buf + offset, buflen - offset, \", RD: %s, Source-AS %s\",\n\t\tbgp_vpn_rd_print(ndo, pptr),\n\t\tas_printf(ndo, astostr, sizeof(astostr),\n\t\tEXTRACT_32BITS(pptr + BGP_VPN_RD_LEN)));\n break;\n\n case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI:\n ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);\n offset = strlen(buf);\n snprintf(buf + offset, buflen - offset, \", RD: %s\",\n bgp_vpn_rd_print(ndo, pptr));\n pptr += BGP_VPN_RD_LEN;\n\n sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen);\n addr_length = route_length - sg_length;\n\n ND_TCHECK2(pptr[0], addr_length);\n offset = strlen(buf);\n snprintf(buf + offset, buflen - offset, \", Originator %s\",\n bgp_vpn_ip_print(ndo, pptr, addr_length << 3));\n break;\n\n case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE:\n ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);\n offset = strlen(buf);\n snprintf(buf + offset, buflen - offset, \", RD: %s\",\n bgp_vpn_rd_print(ndo, pptr));\n pptr += BGP_VPN_RD_LEN;\n\n bgp_vpn_sg_print(ndo, pptr, buf, buflen);\n break;\n\n case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */\n case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN:\n ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);\n offset = strlen(buf);\n\t snprintf(buf + offset, buflen - offset, \", RD: %s, Source-AS %s\",\n\t\tbgp_vpn_rd_print(ndo, pptr),\n\t\tas_printf(ndo, astostr, sizeof(astostr),\n\t\tEXTRACT_32BITS(pptr + BGP_VPN_RD_LEN)));\n pptr += BGP_VPN_RD_LEN;\n\n bgp_vpn_sg_print(ndo, pptr, buf, buflen);\n break;\n\n /*\n * no per route-type printing yet.\n */\n case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF:\n default:\n break;\n }\n\n return route_length + 2;\n\ntrunc:\n\treturn -2;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13043/BGP: fix decoding of MVPN route types 6 and 7\n\nRFC 6514 Section 4.6 defines the structure for Shared Tree Join (6) and\nSource Tree Join (7) multicast VPN route types. decode_multicast_vpn()\ndidn't implement the Source AS field of that structure properly, adjust\nthe offsets to put it right.\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: SPL_METHOD(Array, unserialize)\n{\n\tspl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\n\tchar *buf;\n\tint buf_len;\n\tconst unsigned char *p, *s;\n\tphp_unserialize_data_t var_hash;\n\tzval *pmembers, *pflags = NULL;\n\tHashTable *aht;\n\tlong flags;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s\", &buf, &buf_len) == FAILURE) {\n\t\treturn;\n\t}\n\n\tif (buf_len == 0) {\n\t\treturn;\n\t}\n\n\taht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);\n\tif (aht->nApplyCount > 0) {\n\t\tzend_error(E_WARNING, \"Modification of ArrayObject during sorting is prohibited\");\n\t\treturn;\n\t}\n\n\t/* storage */\n\ts = p = (const unsigned char*)buf;\n\tPHP_VAR_UNSERIALIZE_INIT(var_hash);\n\n\tif (*p!= 'x' || *++p != ':') {\n\t\tgoto outexcept;\n\t}\n\t++p;\n\n\tALLOC_INIT_ZVAL(pflags);\n\tif (!php_var_unserialize(&pflags, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pflags) != IS_LONG) {\n\t\tgoto outexcept;\n\t}\n\n\tvar_push_dtor(&var_hash, &pflags);\n\t--p; /* for ';' */\n\tflags = Z_LVAL_P(pflags);\n\t/* flags needs to be verified and we also need to verify whether the next\n\t * thing we get is ';'. After that we require an 'm' or somethign else\n\t * where 'm' stands for members and anything else should be an array. If\n\t * neither 'a' or 'm' follows we have an error. */\n\n\tif (*p != ';') {\n\t\tgoto outexcept;\n\t}\n\t++p;\n\n\tif (*p!='m') {\n\t\tif (*p!='a' && *p!='O' && *p!='C' && *p!='r') {\n\t\t\tgoto outexcept;\n\t\t}\n\t\tintern->ar_flags &= ~SPL_ARRAY_CLONE_MASK;\n\t\tintern->ar_flags |= flags & SPL_ARRAY_CLONE_MASK;\n\t\tzval_ptr_dtor(&intern->array);\n\t\tALLOC_INIT_ZVAL(intern->array);\n\t\tif (!php_var_unserialize(&intern->array, &p, s + buf_len, &var_hash TSRMLS_CC)) {\n\t\t\tgoto outexcept;\n\t\t}\n\t\tvar_push_dtor(&var_hash, &intern->array);\n\t}\n\tif (*p != ';') {\n\t\tgoto outexcept;\n\t}\n\t++p;\n\n\t/* members */\n\tif (*p!= 'm' || *++p != ':') {\n\t\tgoto outexcept;\n\t}\n\t++p;\n\n\tALLOC_INIT_ZVAL(pmembers);\n\tif (!php_var_unserialize(&pmembers, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pmembers) != IS_ARRAY) {\n\t\tzval_ptr_dtor(&pmembers);\n\t\tgoto outexcept;\n\t}\n\n\tvar_push_dtor(&var_hash, &pmembers);\n\t/* copy members */\n\tif (!intern->std.properties) {\n\t\trebuild_object_properties(&intern->std);\n\t}\n\tzend_hash_copy(intern->std.properties, Z_ARRVAL_P(pmembers), (copy_ctor_func_t) zval_add_ref, (void *) NULL, sizeof(zval *));\n\tzval_ptr_dtor(&pmembers);\n\n\t/* done reading $serialized */\n\n\tPHP_VAR_UNSERIALIZE_DESTROY(var_hash);\n\tif (pflags) {\n\t\tzval_ptr_dtor(&pflags);\n\t}\n\treturn;\n\noutexcept:\n\tPHP_VAR_UNSERIALIZE_DESTROY(var_hash);\n\tif (pflags) {\n\t\tzval_ptr_dtor(&pflags);\n\t}\n\tzend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Error at offset %ld of %d bytes\", (long)((char*)p - buf), buf_len);\n\treturn;\n\n} /* }}} */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-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: err_t verify_signed_hash(const struct RSA_public_key *k\n , u_char *s, unsigned int s_max_octets\n , u_char **psig\n , size_t hash_len\n , const u_char *sig_val, size_t sig_len)\n{\n unsigned int padlen;\n\n /* actual exponentiation; see PKCS#1 v2.0 5.1 */\n {\n\tchunk_t temp_s;\n\tMP_INT c;\n\n\tn_to_mpz(&c, sig_val, sig_len);\n\toswcrypto.mod_exp(&c, &c, &k->e, &k->n);\n\n\ttemp_s = mpz_to_n(&c, sig_len);\t/* back to octets */\n if(s_max_octets < sig_len) {\n return \"2\"\"exponentiation failed; too many octets\";\n }\n\tmemcpy(s, temp_s.ptr, sig_len);\n\tpfree(temp_s.ptr);\n\tmpz_clear(&c);\n }\n\n /* check signature contents */\n /* verify padding (not including any DER digest info! */\n padlen = sig_len - 3 - hash_len;\n /* now check padding */\n\n DBG(DBG_CRYPT,\n\tDBG_dump(\"verify_sh decrypted SIG1:\", s, sig_len));\n DBG(DBG_CRYPT, DBG_log(\"pad_len calculated: %d hash_len: %d\", padlen, (int)hash_len));\n\n /* skip padding */\n if(s[0] != 0x00\n || s[1] != 0x01\n || s[padlen+2] != 0x00) {\n\treturn \"3\"\"SIG padding does not check out\";\n }\n\n s += padlen + 3;\n (*psig) = s;\n\n /* return SUCCESS */\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-347'], 'message': 'wo#7449 . verify padding contents for IKEv2 RSA sig check\n\nSpecial thanks to Sze Yiu Chau of Purdue University (schau@purdue.edu)\nwho reported the 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: TEST_F(ZNCTest, AwayNotify) {\n auto znc = Run();\n auto ircd = ConnectIRCd();\n auto client = ConnectClient();\n client.Write(\"CAP LS\");\n client.Write(\"PASS :hunter2\");\n client.Write(\"NICK nick\");\n client.Write(\"USER user/test x x :x\");\n QByteArray cap_ls;\n client.ReadUntilAndGet(\" LS :\", cap_ls);\n ASSERT_THAT(cap_ls.toStdString(), AllOf(HasSubstr(\"cap-notify\"), Not(HasSubstr(\"away-notify\"))));\n client.Write(\"CAP REQ :cap-notify\");\n client.ReadUntil(\"ACK :cap-notify\");\n client.Write(\"CAP END\");\n client.ReadUntil(\" 001 \");\n ircd.ReadUntil(\"USER\");\n ircd.Write(\"CAP user LS :away-notify\");\n ircd.ReadUntil(\"CAP REQ :away-notify\");\n ircd.Write(\"CAP user ACK :away-notify\");\n ircd.ReadUntil(\"CAP END\");\n ircd.Write(\":server 001 user :welcome\");\n client.ReadUntil(\"CAP user NEW :away-notify\");\n client.Write(\"CAP REQ :away-notify\");\n client.ReadUntil(\"ACK :away-notify\");\n ircd.Write(\":x!y@z AWAY :reason\");\n client.ReadUntil(\":x!y@z AWAY :reason\");\n ircd.Close();\n client.ReadUntil(\"DEL :away-notify\");\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: static int flashsv_decode_frame(AVCodecContext *avctx, void *data,\n int *got_frame, AVPacket *avpkt)\n{\n int buf_size = avpkt->size;\n FlashSVContext *s = avctx->priv_data;\n int h_blocks, v_blocks, h_part, v_part, i, j, ret;\n GetBitContext gb;\n int last_blockwidth = s->block_width;\n int last_blockheight= s->block_height;\n\n /* no supplementary picture */\n if (buf_size == 0)\n return 0;\n if (buf_size < 4)\n return -1;\n\n init_get_bits(&gb, avpkt->data, buf_size * 8);\n\n /* start to parse the bitstream */\n s->block_width = 16 * (get_bits(&gb, 4) + 1);\n s->image_width = get_bits(&gb, 12);\n s->block_height = 16 * (get_bits(&gb, 4) + 1);\n s->image_height = get_bits(&gb, 12);\n\n if ( last_blockwidth != s->block_width\n || last_blockheight!= s->block_height)\n av_freep(&s->blocks);\n\n if (s->ver == 2) {\n skip_bits(&gb, 6);\n if (get_bits1(&gb)) {\n avpriv_request_sample(avctx, \"iframe\");\n return AVERROR_PATCHWELCOME;\n }\n if (get_bits1(&gb)) {\n avpriv_request_sample(avctx, \"Custom palette\");\n return AVERROR_PATCHWELCOME;\n }\n }\n\n /* calculate number of blocks and size of border (partial) blocks */\n h_blocks = s->image_width / s->block_width;\n h_part = s->image_width % s->block_width;\n v_blocks = s->image_height / s->block_height;\n v_part = s->image_height % s->block_height;\n\n /* the block size could change between frames, make sure the buffer\n * is large enough, if not, get a larger one */\n if (s->block_size < s->block_width * s->block_height) {\n int tmpblock_size = 3 * s->block_width * s->block_height;\n\n s->tmpblock = av_realloc(s->tmpblock, tmpblock_size);\n if (!s->tmpblock) {\n av_log(avctx, AV_LOG_ERROR, \"Can't allocate decompression buffer.\\n\");\n return AVERROR(ENOMEM);\n }\n if (s->ver == 2) {\n s->deflate_block_size = calc_deflate_block_size(tmpblock_size);\n if (s->deflate_block_size <= 0) {\n av_log(avctx, AV_LOG_ERROR, \"Can't determine deflate buffer size.\\n\");\n return -1;\n }\n s->deflate_block = av_realloc(s->deflate_block, s->deflate_block_size);\n if (!s->deflate_block) {\n av_log(avctx, AV_LOG_ERROR, \"Can't allocate deflate buffer.\\n\");\n return AVERROR(ENOMEM);\n }\n }\n }\n s->block_size = s->block_width * s->block_height;\n\n /* initialize the image size once */\n if (avctx->width == 0 && avctx->height == 0) {\n avcodec_set_dimensions(avctx, s->image_width, s->image_height);\n }\n\n /* check for changes of image width and image height */\n if (avctx->width != s->image_width || avctx->height != s->image_height) {\n av_log(avctx, AV_LOG_ERROR,\n \"Frame width or height differs from first frame!\\n\");\n av_log(avctx, AV_LOG_ERROR, \"fh = %d, fv %d vs ch = %d, cv = %d\\n\",\n avctx->height, avctx->width, s->image_height, s->image_width);\n return AVERROR_INVALIDDATA;\n }\n\n /* we care for keyframes only in Screen Video v2 */\n s->is_keyframe = (avpkt->flags & AV_PKT_FLAG_KEY) && (s->ver == 2);\n if (s->is_keyframe) {\n s->keyframedata = av_realloc(s->keyframedata, avpkt->size);\n memcpy(s->keyframedata, avpkt->data, avpkt->size);\n }\n if(s->ver == 2 && !s->blocks)\n s->blocks = av_mallocz((v_blocks + !!v_part) * (h_blocks + !!h_part)\n * sizeof(s->blocks[0]));\n\n av_dlog(avctx, \"image: %dx%d block: %dx%d num: %dx%d part: %dx%d\\n\",\n s->image_width, s->image_height, s->block_width, s->block_height,\n h_blocks, v_blocks, h_part, v_part);\n\n if ((ret = ff_reget_buffer(avctx, &s->frame)) < 0)\n return ret;\n\n /* loop over all block columns */\n for (j = 0; j < v_blocks + (v_part ? 1 : 0); j++) {\n\n int y_pos = j * s->block_height; // vertical position in frame\n int cur_blk_height = (j < v_blocks) ? s->block_height : v_part;\n\n /* loop over all block rows */\n for (i = 0; i < h_blocks + (h_part ? 1 : 0); i++) {\n int x_pos = i * s->block_width; // horizontal position in frame\n int cur_blk_width = (i < h_blocks) ? s->block_width : h_part;\n int has_diff = 0;\n\n /* get the size of the compressed zlib chunk */\n int size = get_bits(&gb, 16);\n\n s->color_depth = 0;\n s->zlibprime_curr = 0;\n s->zlibprime_prev = 0;\n s->diff_start = 0;\n s->diff_height = cur_blk_height;\n\n if (8 * size > get_bits_left(&gb)) {\n av_frame_unref(&s->frame);\n return AVERROR_INVALIDDATA;\n }\n\n if (s->ver == 2 && size) {\n skip_bits(&gb, 3);\n s->color_depth = get_bits(&gb, 2);\n has_diff = get_bits1(&gb);\n s->zlibprime_curr = get_bits1(&gb);\n s->zlibprime_prev = get_bits1(&gb);\n\n if (s->color_depth != 0 && s->color_depth != 2) {\n av_log(avctx, AV_LOG_ERROR,\n \"%dx%d invalid color depth %d\\n\", i, j, s->color_depth);\n return AVERROR_INVALIDDATA;\n }\n\n if (has_diff) {\n if (!s->keyframe) {\n av_log(avctx, AV_LOG_ERROR,\n \"inter frame without keyframe\\n\");\n return AVERROR_INVALIDDATA;\n }\n s->diff_start = get_bits(&gb, 8);\n s->diff_height = get_bits(&gb, 8);\n av_log(avctx, AV_LOG_DEBUG,\n \"%dx%d diff start %d height %d\\n\",\n i, j, s->diff_start, s->diff_height);\n size -= 2;\n }\n\n if (s->zlibprime_prev)\n av_log(avctx, AV_LOG_DEBUG, \"%dx%d zlibprime_prev\\n\", i, j);\n\n if (s->zlibprime_curr) {\n int col = get_bits(&gb, 8);\n int row = get_bits(&gb, 8);\n av_log(avctx, AV_LOG_DEBUG, \"%dx%d zlibprime_curr %dx%d\\n\", i, j, col, row);\n size -= 2;\n avpriv_request_sample(avctx, \"zlibprime_curr\");\n return AVERROR_PATCHWELCOME;\n }\n if (!s->blocks && (s->zlibprime_curr || s->zlibprime_prev)) {\n av_log(avctx, AV_LOG_ERROR, \"no data available for zlib \"\n \"priming\\n\");\n return AVERROR_INVALIDDATA;\n }\n size--; // account for flags byte\n }\n\n if (has_diff) {\n int k;\n int off = (s->image_height - y_pos - 1) * s->frame.linesize[0];\n\n for (k = 0; k < cur_blk_height; k++)\n memcpy(s->frame.data[0] + off - k*s->frame.linesize[0] + x_pos*3,\n s->keyframe + off - k*s->frame.linesize[0] + x_pos*3,\n cur_blk_width * 3);\n }\n\n /* skip unchanged blocks, which have size 0 */\n if (size) {\n if (flashsv_decode_block(avctx, avpkt, &gb, size,\n cur_blk_width, cur_blk_height,\n x_pos, y_pos,\n i + j * (h_blocks + !!h_part)))\n av_log(avctx, AV_LOG_ERROR,\n \"error in decompression of block %dx%d\\n\", i, j);\n }\n }\n }\n if (s->is_keyframe && s->ver == 2) {\n if (!s->keyframe) {\n s->keyframe = av_malloc(s->frame.linesize[0] * avctx->height);\n if (!s->keyframe) {\n av_log(avctx, AV_LOG_ERROR, \"Cannot allocate image data\\n\");\n return AVERROR(ENOMEM);\n }\n }\n memcpy(s->keyframe, s->frame.data[0], s->frame.linesize[0] * avctx->height);\n }\n\n if ((ret = av_frame_ref(data, &s->frame)) < 0)\n return ret;\n\n *got_frame = 1;\n\n if ((get_bits_count(&gb) / 8) != buf_size)\n av_log(avctx, AV_LOG_ERROR, \"buffer not fully consumed (%d != %d)\\n\",\n buf_size, (get_bits_count(&gb) / 8));\n\n /* report that the buffer was completely consumed */\n return buf_size;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'avcodec/flashsv: check diff_start/height\n\nFixes out of array accesses\nFixes Ticket2844\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: static const char *skip( const char *in )\n{\n\twhile ( in && *in && (unsigned char) *in <= 32 )\n\t\tin++;\n\treturn in;\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_DeleteItemFromObject( cJSON *object, const char *string )\n{\n\tcJSON_Delete( cJSON_DetachItemFromObject( object, string ) );\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: const char *cJSON_GetErrorPtr( void )\n{\n\treturn ep;\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 *print_array( cJSON *item, int depth, int fmt )\n{\n\tchar **entries;\n\tchar *out = 0, *ptr, *ret;\n\tint len = 5;\n\tcJSON *child = item->child;\n\tint numentries = 0, i = 0, fail = 0;\n\t\n\t/* How many entries in the array? */\n\twhile ( child ) {\n\t\t++numentries;\n\t\tchild = child->next;\n\t}\n\t/* Allocate an array to hold the values for each. */\n\tif ( ! ( entries = (char**) cJSON_malloc( numentries * sizeof(char*) ) ) )\n\t\treturn 0;\n\tmemset( entries, 0, numentries * sizeof(char*) );\n\t/* Retrieve all the results. */\n\tchild = item->child;\n\twhile ( child && ! fail ) {\n\t\tret = print_value( child, depth + 1, fmt );\n\t\tentries[i++] = ret;\n\t\tif ( ret )\n\t\t\tlen += strlen( ret ) + 2 + ( fmt ? 1 : 0 );\n\t\telse\n\t\t\tfail = 1;\n\t\tchild = child -> next;\n\t}\n\t\n\t/* If we didn't fail, try to malloc the output string. */\n\tif ( ! fail ) {\n\t\tout = (char*) cJSON_malloc( len );\n\t\tif ( ! out )\n\t\t\tfail = 1;\n\t}\n\n\t/* Handle failure. */\n\tif ( fail ) {\n\t\tfor ( i = 0; i < numentries; ++i )\n\t\t\tif ( entries[i] )\n\t\t\t\tcJSON_free( entries[i] );\n\t\tcJSON_free( entries );\n\t\treturn 0;\n\t}\n\t\n\t/* Compose the output array. */\n\t*out = '[';\n\tptr = out + 1;\n\t*ptr = 0;\n\tfor ( i = 0; i < numentries; ++i ) {\n\t\tstrcpy( ptr, entries[i] );\n\t\tptr += strlen( entries[i] );\n\t\tif ( i != numentries - 1 ) {\n\t\t\t*ptr++ = ',';\n\t\t\tif ( fmt )\n\t\t\t\t*ptr++ = ' ';\n\t\t\t*ptr = 0;\n\t\t}\n\t\tcJSON_free( entries[i] );\n\t}\n\tcJSON_free( entries );\n\t*ptr++ = ']';\n\t*ptr++ = 0;\n\treturn out;\t\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 void suffix_object( cJSON *prev, cJSON *item )\n{\n\tprev->next = item;\n\titem->prev = prev;\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: Status SparseTensorToCSRSparseMatrixCPUFunctor::operator()(\n const int64 batch_size, const int num_rows,\n TTypes::ConstMatrix indices, TTypes::Vec batch_ptr,\n TTypes::Vec csr_row_ptr, TTypes::Vec csr_col_ind) {\n // Validate inputs.\n if (batch_ptr.size() != batch_size + 1) {\n return errors::InvalidArgument(\n \"Expected batch_ptr.size() == batch_size + 1. Got: \", batch_ptr.size(),\n \" vs. \", batch_size + 1);\n }\n if (csr_row_ptr.size() != batch_size * (num_rows + 1)) {\n return errors::InvalidArgument(\n \"Expected csr_row_ptr.size() == batch_size * (num_rows + 1). Got: \",\n csr_row_ptr.size(), \" vs. \", batch_size * (num_rows + 1));\n }\n\n const int64 total_nnz = indices.dimension(0);\n const int rank = indices.dimension(1);\n if (rank == 2 && batch_size != 1) {\n return errors::InvalidArgument(\n \"Expected batch_size == 1 when rank is 2. Got batch_size: \",\n batch_size);\n }\n if (csr_col_ind.size() != total_nnz) {\n return errors::InvalidArgument(\n \"Expected csr_col_ind.size() == total_nnz. Got: \", csr_col_ind.size(),\n \" vs. \", total_nnz);\n }\n\n int prev_batch = -1;\n if (rank == 2) {\n // For a single batch, the batch_ptrs are {0, total_nnz}.\n batch_ptr(0) = 0;\n ++prev_batch;\n\n for (int64 i = 0; i < total_nnz; ++i) {\n // For now, the rows pointers store the corresponding row counts.\n csr_row_ptr(indices(i, 0) + 1) += 1;\n csr_col_ind(i) = indices(i, 1);\n }\n } else { // rank == 3\n for (int64 i = 0; i < total_nnz; ++i) {\n const int cur_batch = indices(i, 0);\n // For now, the rows pointers store the corresponding row counts.\n csr_row_ptr(cur_batch * (num_rows + 1) + indices(i, 1) + 1) += 1;\n csr_col_ind(i) = indices(i, 2);\n\n // We're at a new batch and might have skipped over empty batches.\n while (prev_batch < cur_batch) {\n // The previous batch ends at position i.\n batch_ptr(prev_batch + 1) = i;\n ++prev_batch;\n }\n }\n }\n // Set the last element of batch_ptr and account for trailing empty batches.\n while (prev_batch < batch_size) {\n batch_ptr(prev_batch + 1) = total_nnz;\n ++prev_batch;\n }\n\n // Compute the cumulative row counts for each batch.\n for (int batch_idx = 0; batch_idx < batch_size; ++batch_idx) {\n auto* row_ptr_batch = csr_row_ptr.data() + batch_idx * (num_rows + 1);\n std::partial_sum(row_ptr_batch, row_ptr_batch + num_rows + 1,\n row_ptr_batch);\n }\n return Status::OK();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-131', 'CWE-369'], 'message': 'Fix crash in `SparseTensorToCSRSparseMatrixCPUFunctor`\n\nPiperOrigin-RevId: 370110290\nChange-Id: I4451e92661a55c2180f80d38b67a9b50bf5edec5'" }, { "text": "[INST] Given the following code containing errors, provide Common 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 if (Elf32_Dyn::DT_NEEDED != d_tag\n && dt_table[d_tag]\n && get_te32(&dynp->d_val)\n != get_te32(&dynp0[-1+ dt_table[d_tag]].d_val)) {\n char msg[50]; snprintf(msg, sizeof(msg),\n \"duplicate DT_%#x: [%#x] [%#x]\",\n d_tag, -1+ dt_table[d_tag], -1+ ndx);\n throwCantPack(msg);\n }\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 (sz_sym < sizeof(Elf32_Sym)) {\n char msg[50]; snprintf(msg, sizeof(msg),\n \"bad DT_SYMENT %x\", sz_sym);\n throwCantPack(msg);\n }\n if (v_sym < v_str) {\n symnum_end = (v_str - v_sym) / sz_sym;\n }\n if (symnum_end < 1) {\n throwCantPack(\"bad DT_SYMTAB\");\n }\n }\n // DT_HASH often ends at DT_SYMTAB\n unsigned const v_hsh = elf_unsigned_dynamic(Elf32_Dyn::DT_HASH);\n if (v_hsh && file_image) {\n hashtab = (unsigned const *)elf_find_dynamic(Elf32_Dyn::DT_HASH);\n if (!hashtab) {\n char msg[40]; snprintf(msg, sizeof(msg),\n \"bad DT_HASH %#x\", v_hsh);\n throwCantPack(msg);\n }\n unsigned const nbucket = get_te32(&hashtab[0]);\n unsigned const *const buckets = &hashtab[2];\n unsigned const *const chains = &buckets[nbucket]; (void)chains;\n\n unsigned const v_sym = !x_sym ? 0 : get_te32(&dynp0[-1+ x_sym].d_val);\n if (!nbucket || (nbucket>>31) || !v_sym || file_size <= v_sym\n || ((v_hsh < v_sym) && (v_sym - v_hsh) < sizeof(*buckets)*(2+ nbucket))\n ) {\n char msg[80]; snprintf(msg, sizeof(msg),\n \"bad DT_HASH nbucket=%#x len=%#x\",\n nbucket, (v_sym - v_hsh));\n throwCantPack(msg);\n }\n unsigned chmax = 0;\n for (unsigned j= 0; j < nbucket; ++j) {\n if (chmax < buckets[j]) {\n chmax = buckets[j];\n }\n }\n if ((v_hsh < v_sym) && (v_sym - v_hsh) <\n (sizeof(*buckets)*(2+ nbucket) + sizeof(*chains)*(1+ chmax))) {\n char msg[80]; 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 if (!gashtab) {\n char msg[40]; snprintf(msg, sizeof(msg),\n \"bad DT_GNU_HASH %#x\", v_gsh);\n throwCantPack(msg);\n }\n unsigned const n_bucket = get_te32(&gashtab[0]);\n unsigned const symbias = get_te32(&gashtab[1]);\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 if (!n_bucket || (1u<<31) <= n_bucket /* fie on fuzzers */\n || (void const *)&file_image[file_size] <= (void const *)hasharr) {\n char msg[80]; snprintf(msg, sizeof(msg),\n \"bad n_bucket %#x\\n\", n_bucket);\n throwCantPack(msg);\n }\n //unsigned const *const gashend = &hasharr[n_bucket]; // minimum, except:\n // Rust and Android trim unused zeroes from high end of hasharr[]\n unsigned bmax = 0;\n for (unsigned j= 0; j < n_bucket; ++j) {\n if (buckets[j]) {\n if (buckets[j] < symbias) {\n char msg[50]; snprintf(msg, sizeof(msg),\n \"bad DT_GNU_HASH bucket[%d] < symbias{%#x}\\n\",\n buckets[j], symbias);\n throwCantPack(msg);\n }\n if (bmax < buckets[j]) {\n bmax = buckets[j];\n }\n }\n }\n if ((1+ bmax) < symbias) {\n char msg[80]; snprintf(msg, sizeof(msg),\n \"bad DT_GNU_HASH (1+ max_bucket)=%#x < symbias=%#x\", 1+ bmax, symbias);\n throwCantPack(msg);\n }\n bmax -= symbias;\n\n unsigned const v_sym = !x_sym ? 0 : get_te32(&dynp0[-1+ x_sym].d_val);\n unsigned r = 0;\n if (!n_bucket || !n_bitmask || !v_sym\n || (r=1, ((-1+ n_bitmask) & n_bitmask)) // not a power of 2\n || (r=2, (8*sizeof(unsigned) <= gnu_shift)) // shifted result always == 0\n || (r=3, (n_bucket>>30)) // fie on fuzzers\n || (r=4, (n_bitmask>>30))\n || (r=5, ((file_size/sizeof(unsigned))\n <= ((sizeof(*bitmask)/sizeof(unsigned))*n_bitmask + 2*n_bucket))) // FIXME: weak\n || (r=6, ((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)*(1+ bmax) // hasharr\n )) )\n ) {\n char msg[90]; snprintf(msg, sizeof(msg),\n \"bad DT_GNU_HASH n_bucket=%#x n_bitmask=%#x len=%#lx r=%d\",\n n_bucket, n_bitmask, (long unsigned)(v_sym - v_gsh), r);\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-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: lldp_private_8023_print(netdissect_options *ndo,\n const u_char *tptr, u_int tlv_len)\n{\n int subtype, hexdump = FALSE;\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_8023_subtype_values, \"unknown\", subtype),\n subtype));\n\n switch (subtype) {\n case LLDP_PRIVATE_8023_SUBTYPE_MACPHY:\n if (tlv_len < 9) {\n return hexdump;\n }\n ND_PRINT((ndo, \"\\n\\t autonegotiation [%s] (0x%02x)\",\n bittok2str(lldp_8023_autonegotiation_values, \"none\", *(tptr+4)),\n *(tptr + 4)));\n ND_PRINT((ndo, \"\\n\\t PMD autoneg capability [%s] (0x%04x)\",\n bittok2str(lldp_pmd_capability_values,\"unknown\", EXTRACT_16BITS(tptr+5)),\n EXTRACT_16BITS(tptr + 5)));\n ND_PRINT((ndo, \"\\n\\t MAU type %s (0x%04x)\",\n tok2str(lldp_mau_types_values, \"unknown\", EXTRACT_16BITS(tptr+7)),\n EXTRACT_16BITS(tptr + 7)));\n break;\n\n case LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER:\n if (tlv_len < 7) {\n return hexdump;\n }\n ND_PRINT((ndo, \"\\n\\t MDI power support [%s], power pair %s, power class %s\",\n bittok2str(lldp_mdi_values, \"none\", *(tptr+4)),\n tok2str(lldp_mdi_power_pairs_values, \"unknown\", *(tptr+5)),\n tok2str(lldp_mdi_power_class_values, \"unknown\", *(tptr + 6))));\n break;\n\n case LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR:\n if (tlv_len < 9) {\n return hexdump;\n }\n ND_PRINT((ndo, \"\\n\\t aggregation status [%s], aggregation port ID %u\",\n bittok2str(lldp_aggregation_values, \"none\", *(tptr+4)),\n EXTRACT_32BITS(tptr + 5)));\n break;\n\n case LLDP_PRIVATE_8023_SUBTYPE_MTU:\n ND_PRINT((ndo, \"\\n\\t MTU size %u\", EXTRACT_16BITS(tptr + 4)));\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-125', 'CWE-787'], 'message': 'CVE-2017-13054/LLDP: add a missing length check\n\nIn lldp_private_8023_print() the case block for subtype 4 (Maximum Frame\nSize TLV, IEEE 802.3bc-2009 Section 79.3.4) did not include the length\ncheck and could over-read the input buffer, put it right.\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: int create_dpb(davs2_mgr_t *mgr)\n{\n davs2_seq_t *seq = &mgr->seq_info;\n uint8_t *mem_ptr = NULL;\n size_t mem_size = 0;\n int i;\n\n mgr->dpbsize = mgr->num_decoders + seq->picture_reorder_delay + 16; /// !!! FIXME: decide dpb buffer size ?\n mgr->dpbsize += 8; // FIXME: \u04aa\n\n mem_size = mgr->dpbsize * sizeof(davs2_frame_t *)\n + davs2_frame_get_size(seq->i_enc_width, seq->i_enc_height, seq->head.chroma_format, 1) * mgr->dpbsize\n + davs2_frame_get_size(seq->i_enc_width, seq->i_enc_height, seq->head.chroma_format, 0)\n + CACHE_LINE_SIZE * (mgr->dpbsize + 2);\n\n mem_ptr = (uint8_t *)davs2_malloc(mem_size);\n if (mem_ptr == NULL) {\n return -1;\n }\n\n mgr->dpb = (davs2_frame_t **)mem_ptr;\n mem_ptr += mgr->dpbsize * sizeof(davs2_frame_t *);\n ALIGN_POINTER(mem_ptr);\n\n for (i = 0; i < mgr->dpbsize; i++) {\n mgr->dpb[i] = davs2_frame_new(seq->i_enc_width, seq->i_enc_height, seq->head.chroma_format, &mem_ptr, 1);\n ALIGN_POINTER(mem_ptr);\n\n if (mgr->dpb[i] == NULL) {\n return -1;\n }\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-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 inline int handle_dots(struct nameidata *nd, int type)\n{\n\tif (type == LAST_DOTDOT) {\n\t\tif (nd->flags & LOOKUP_RCU) {\n\t\t\treturn follow_dotdot_rcu(nd);\n\t\t} else\n\t\t\tfollow_dotdot(nd);\n\t}\n\treturn 0;\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 sgpd_dump(GF_Box *a, FILE * trace)\n{\n\tu32 i;\n\tGF_SampleGroupDescriptionBox *ptr = (GF_SampleGroupDescriptionBox*) a;\n\tif (!a) return GF_BAD_PARAM;\n\n\tgf_isom_box_dump_start(a, \"SampleGroupDescriptionBox\", trace);\n\n\tif (ptr->grouping_type)\n\t\tfprintf(trace, \"grouping_type=\\\"%s\\\"\", gf_4cc_to_str(ptr->grouping_type) );\n\tif (ptr->version==1) fprintf(trace, \" default_length=\\\"%d\\\"\", ptr->default_length);\n\tif ((ptr->version>=2) && ptr->default_description_index) fprintf(trace, \" default_group_index=\\\"%d\\\"\", ptr->default_description_index);\n\tfprintf(trace, \">\\n\");\n\tfor (i=0; igroup_descriptions); i++) {\n\t\tvoid *entry = gf_list_get(ptr->group_descriptions, i);\n\t\tswitch (ptr->grouping_type) {\n\t\tcase GF_ISOM_SAMPLE_GROUP_ROLL:\n\t\t\tfprintf(trace, \"\\n\", ((GF_RollRecoveryEntry*)entry)->roll_distance );\n\t\t\tbreak;\n\t\tcase GF_ISOM_SAMPLE_GROUP_PROL:\n\t\t\tfprintf(trace, \"\\n\", ((GF_RollRecoveryEntry*)entry)->roll_distance );\n\t\t\tbreak;\n\t\tcase GF_ISOM_SAMPLE_GROUP_TELE:\n\t\t\tfprintf(trace, \"\\n\", ((GF_TemporalLevelEntry*)entry)->level_independently_decodable);\n\t\t\tbreak;\n\t\tcase GF_ISOM_SAMPLE_GROUP_RAP:\n\t\t\tfprintf(trace, \"num_leading_samples_known ? \"yes\" : \"no\");\n\t\t\tif (((GF_VisualRandomAccessEntry*)entry)->num_leading_samples_known)\n\t\t\t\tfprintf(trace, \" num_leading_samples=\\\"%d\\\"\", ((GF_VisualRandomAccessEntry*)entry)->num_leading_samples);\n\t\t\tfprintf(trace, \"/>\\n\");\n\t\t\tbreak;\n\t\tcase GF_ISOM_SAMPLE_GROUP_SYNC:\n\t\t\tfprintf(trace, \"\\n\", ((GF_SYNCEntry*)entry)->NALU_type);\n\t\t\tbreak;\n\t\tcase GF_ISOM_SAMPLE_GROUP_SEIG:\n\t\t\tfprintf(trace, \"IsProtected, ((GF_CENCSampleEncryptionGroupEntry*)entry)->Per_Sample_IV_size);\n\t\t\tdump_data_hex(trace, (char *)((GF_CENCSampleEncryptionGroupEntry*)entry)->KID, 16);\n\t\t\tif ((((GF_CENCSampleEncryptionGroupEntry*)entry)->IsProtected == 1) && !((GF_CENCSampleEncryptionGroupEntry*)entry)->Per_Sample_IV_size) {\n\t\t\t\tfprintf(trace, \"\\\" constant_IV_size=\\\"%d\\\" constant_IV=\\\"\", ((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV_size);\n\t\t\t\tdump_data_hex(trace, (char *)((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV, ((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV_size);\n\t\t\t}\n\t\t\tfprintf(trace, \"\\\"/>\\n\");\n\t\t\tbreak;\n\t\tcase GF_ISOM_SAMPLE_GROUP_OINF:\n\t\t\toinf_entry_dump(entry, trace);\n\t\t\tbreak;\n\t\tcase GF_ISOM_SAMPLE_GROUP_LINF:\n\t\t\tlinf_dump(entry, trace);\n\t\t\tbreak;\n\t\tcase GF_ISOM_SAMPLE_GROUP_TRIF:\n\t\t\ttrif_dump(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);\n\t\t\tbreak;\n\t\t\t\n\t\tcase GF_ISOM_SAMPLE_GROUP_NALM:\n\t\t\tnalm_dump(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);\n\t\t\tbreak;\n\t\tcase GF_ISOM_SAMPLE_GROUP_SAP:\n\t\t\tfprintf(trace, \"\\n\", ((GF_SAPEntry*)entry)->dependent_flag, ((GF_SAPEntry*)entry)->SAP_type);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tfprintf(trace, \"length);\n\t\t\tdump_data(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);\n\t\t\tfprintf(trace, \"\\\"/>\\n\");\n\t\t}\n\t}\n\tif (!ptr->size) {\n\t\tswitch (ptr->grouping_type) {\n\t\tcase GF_ISOM_SAMPLE_GROUP_ROLL:\n\t\t\tfprintf(trace, \"\\n\");\n\t\t\tbreak;\n\t\tcase GF_ISOM_SAMPLE_GROUP_PROL:\n\t\t\tfprintf(trace, \"\\n\");\n\t\t\tbreak;\n\t\tcase GF_ISOM_SAMPLE_GROUP_TELE:\n\t\t\tfprintf(trace, \"\\n\");\n\t\t\tbreak;\n\t\tcase GF_ISOM_SAMPLE_GROUP_RAP:\n\t\t\tfprintf(trace, \"\\n\");\n\t\t\tbreak;\n\t\tcase GF_ISOM_SAMPLE_GROUP_SYNC:\n\t\t\tfprintf(trace, \"\\n\");\n\t\t\tbreak;\n\t\tcase GF_ISOM_SAMPLE_GROUP_SEIG:\n\t\t\tfprintf(trace, \"\\n\");\n\t\t\tbreak;\n\t\tcase GF_ISOM_SAMPLE_GROUP_OINF:\n\t\t\toinf_entry_dump(NULL, trace);\n\t\t\tbreak;\n\t\tcase GF_ISOM_SAMPLE_GROUP_LINF:\n\t\t\tlinf_dump(NULL, trace);\n\t\t\tbreak;\n\t\tcase GF_ISOM_SAMPLE_GROUP_TRIF:\n\t\t\ttrif_dump(trace, NULL, 0);\n\t\t\tbreak;\n\t\tcase GF_ISOM_SAMPLE_GROUP_NALM:\n\t\t\tnalm_dump(trace, NULL, 0);\n\t\t\tbreak;\n\t\tcase GF_ISOM_SAMPLE_GROUP_SAP:\n\t\t\tfprintf(trace, \"\\n\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tfprintf(trace, \"\\n\");\n\t\t}\n\t}\n\n\tgf_isom_box_dump_done(\"SampleGroupDescriptionBox\", 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: 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 if (Elf32_Dyn::DT_NEEDED != d_tag\n && dt_table[d_tag]\n && get_te32(&dynp->d_val)\n != get_te32(&dynp0[-1+ dt_table[d_tag]].d_val)) {\n char msg[50]; snprintf(msg, sizeof(msg),\n \"duplicate DT_%#x: [%#x] [%#x]\",\n d_tag, -1+ dt_table[d_tag], -1+ ndx);\n throwCantPack(msg);\n }\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(Elf32_Dyn::DT_HASH);\n if (v_hsh && file_image) {\n hashtab = (unsigned const *)elf_find_dynamic(Elf32_Dyn::DT_HASH);\n if (!hashtab) {\n char msg[40]; snprintf(msg, sizeof(msg),\n \"bad DT_HASH %#x\", v_hsh);\n throwCantPack(msg);\n }\n unsigned const nbucket = get_te32(&hashtab[0]);\n unsigned const *const buckets = &hashtab[2];\n unsigned const *const chains = &buckets[nbucket]; (void)chains;\n\n unsigned const v_sym = get_te32(&dynp0[-1+ x_sym].d_val);\n if (!nbucket\n || (nbucket>>31) || (file_size/sizeof(unsigned)) <= (2*nbucket) // FIXME: weak\n || ((v_hsh < v_sym) && (v_sym - v_hsh) < (sizeof(unsigned)*2 // headers\n + sizeof(*buckets)*nbucket // buckets\n + sizeof(*chains) *nbucket // chains\n ))\n ) {\n char msg[90]; snprintf(msg, sizeof(msg),\n \"bad DT_HASH nbucket=%#x len=%#x\",\n nbucket, (v_sym - v_hsh));\n throwCantPack(msg);\n }\n }\n // DT_GNU_HASH often ends at DT_SYMTAB; FIXME: not for Android?\n unsigned const v_gsh = elf_unsigned_dynamic(Elf32_Dyn::DT_GNU_HASH);\n if (v_gsh && file_image) {\n gashtab = (unsigned const *)elf_find_dynamic(Elf32_Dyn::DT_GNU_HASH);\n if (!gashtab) {\n char msg[40]; snprintf(msg, sizeof(msg),\n \"bad DT_GNU_HASH %#x\", v_gsh);\n throwCantPack(msg);\n }\n unsigned const n_bucket = get_te32(&gashtab[0]);\n unsigned const n_bitmask = get_te32(&gashtab[2]);\n unsigned const gnu_shift = get_te32(&gashtab[3]);\n 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-703', 'CWE-369'], 'message': 'Detect bogus DT_SYMENT.\n\nhttps://github.com/upx/upx/issues/331\n\tmodified: p_lx_elf.cpp'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static bool GetUpdateFile( update_t *p_update )\n{\n stream_t *p_stream = NULL;\n char *psz_version_line = NULL;\n char *psz_update_data = NULL;\n\n p_stream = stream_UrlNew( p_update->p_libvlc, UPDATE_VLC_STATUS_URL );\n if( !p_stream )\n {\n msg_Err( p_update->p_libvlc, \"Failed to open %s for reading\",\n UPDATE_VLC_STATUS_URL );\n goto error;\n }\n\n const int64_t i_read = stream_Size( p_stream );\n psz_update_data = malloc( i_read + 1 ); /* terminating '\\0' */\n if( !psz_update_data )\n goto error;\n\n if( stream_Read( p_stream, psz_update_data, i_read ) != i_read )\n {\n msg_Err( p_update->p_libvlc, \"Couldn't download update file %s\",\n UPDATE_VLC_STATUS_URL );\n goto error;\n }\n psz_update_data[i_read] = '\\0';\n\n stream_Delete( p_stream );\n p_stream = NULL;\n\n /* first line : version number */\n char *psz_update_data_parser = psz_update_data;\n size_t i_len = strcspn( psz_update_data, \"\\r\\n\" );\n psz_update_data_parser += i_len;\n while( *psz_update_data_parser == '\\r' || *psz_update_data_parser == '\\n' )\n psz_update_data_parser++;\n\n if( !(psz_version_line = malloc( i_len + 1)) )\n goto error;\n strncpy( psz_version_line, psz_update_data, i_len );\n psz_version_line[i_len] = '\\0';\n\n p_update->release.i_extra = 0;\n int ret = sscanf( psz_version_line, \"%i.%i.%i.%i\",\n &p_update->release.i_major, &p_update->release.i_minor,\n &p_update->release.i_revision, &p_update->release.i_extra);\n if( ret != 3 && ret != 4 )\n {\n msg_Err( p_update->p_libvlc, \"Update version false formated\" );\n goto error;\n }\n\n /* second line : URL */\n i_len = strcspn( psz_update_data_parser, \"\\r\\n\" );\n if( i_len == 0 )\n {\n msg_Err( p_update->p_libvlc, \"Update file %s is corrupted: URL missing\",\n UPDATE_VLC_STATUS_URL );\n\n goto error;\n }\n\n if( !(p_update->release.psz_url = malloc( i_len + 1)) )\n goto error;\n strncpy( p_update->release.psz_url, psz_update_data_parser, i_len );\n p_update->release.psz_url[i_len] = '\\0';\n\n psz_update_data_parser += i_len;\n while( *psz_update_data_parser == '\\r' || *psz_update_data_parser == '\\n' )\n psz_update_data_parser++;\n\n /* Remaining data : description */\n i_len = strlen( psz_update_data_parser );\n if( i_len == 0 )\n {\n msg_Err( p_update->p_libvlc,\n \"Update file %s is corrupted: description missing\",\n UPDATE_VLC_STATUS_URL );\n goto error;\n }\n\n if( !(p_update->release.psz_desc = malloc( i_len + 1)) )\n goto error;\n strncpy( p_update->release.psz_desc, psz_update_data_parser, i_len );\n p_update->release.psz_desc[i_len] = '\\0';\n\n /* Now that we know the status is valid, we must download its signature\n * to authenticate it */\n signature_packet_t sign;\n if( download_signature( VLC_OBJECT( p_update->p_libvlc ), &sign,\n UPDATE_VLC_STATUS_URL ) != VLC_SUCCESS )\n {\n msg_Err( p_update->p_libvlc, \"Couldn't download signature of status file\" );\n goto error;\n }\n\n if( sign.type != BINARY_SIGNATURE && sign.type != TEXT_SIGNATURE )\n {\n msg_Err( p_update->p_libvlc, \"Invalid signature type\" );\n goto error;\n }\n\n p_update->p_pkey = (public_key_t*)malloc( sizeof( public_key_t ) );\n if( !p_update->p_pkey )\n goto error;\n\n if( parse_public_key( videolan_public_key, sizeof( videolan_public_key ),\n p_update->p_pkey, NULL ) != VLC_SUCCESS )\n {\n msg_Err( p_update->p_libvlc, \"Couldn't parse embedded public key, something went really wrong...\" );\n FREENULL( p_update->p_pkey );\n goto error;\n }\n\n memcpy( p_update->p_pkey->longid, videolan_public_key_longid, 8 );\n\n if( memcmp( sign.issuer_longid, p_update->p_pkey->longid , 8 ) != 0 )\n {\n msg_Dbg( p_update->p_libvlc, \"Need to download the GPG key\" );\n public_key_t *p_new_pkey = download_key(\n VLC_OBJECT(p_update->p_libvlc),\n sign.issuer_longid, videolan_public_key_longid );\n if( !p_new_pkey )\n {\n msg_Err( p_update->p_libvlc, \"Couldn't download GPG key\" );\n FREENULL( p_update->p_pkey );\n goto error;\n }\n\n uint8_t *p_hash = hash_from_public_key( p_new_pkey );\n if( !p_hash )\n {\n msg_Err( p_update->p_libvlc, \"Failed to hash signature\" );\n free( p_new_pkey );\n FREENULL( p_update->p_pkey );\n goto error;\n }\n\n if( verify_signature( &p_new_pkey->sig,\n &p_update->p_pkey->key, p_hash ) == VLC_SUCCESS )\n {\n free( p_hash );\n msg_Info( p_update->p_libvlc, \"Key authenticated\" );\n free( p_update->p_pkey );\n p_update->p_pkey = p_new_pkey;\n }\n else\n {\n free( p_hash );\n msg_Err( p_update->p_libvlc, \"Key signature invalid !\" );\n goto error;\n }\n }\n\n uint8_t *p_hash = hash_from_text( psz_update_data, &sign );\n if( !p_hash )\n {\n msg_Warn( p_update->p_libvlc, \"Can't compute hash for status file\" );\n goto error;\n }\n\n else if( p_hash[0] != sign.hash_verification[0] ||\n p_hash[1] != sign.hash_verification[1] )\n {\n msg_Warn( p_update->p_libvlc, \"Bad hash for status file\" );\n free( p_hash );\n goto error;\n }\n\n else if( verify_signature( &sign, &p_update->p_pkey->key, p_hash )\n != VLC_SUCCESS )\n {\n msg_Err( p_update->p_libvlc, \"BAD SIGNATURE for status file\" );\n free( p_hash );\n goto error;\n }\n\n else\n {\n msg_Info( p_update->p_libvlc, \"Status file authenticated\" );\n free( p_hash );\n free( psz_version_line );\n free( psz_update_data );\n return true;\n }\n\nerror:\n if( p_stream )\n stream_Delete( p_stream );\n free( psz_version_line );\n free( psz_update_data );\n return false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'misc: update: fix buffer overflow in updater\n\nOn 32 bit builds, parsing of update status files with a size of\n4294967295 or more lead to an integer truncation in a call to malloc\nand a subsequent buffer overflow. This happened prior to checking the\nfiles' signature. The commit fixes this by disallowing overly large\nstatus files (above 65k in practice)\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: isis_print_is_reach_subtlv(netdissect_options *ndo,\n const uint8_t *tptr, u_int subt, u_int subl,\n const char *ident)\n{\n u_int te_class,priority_level,gmpls_switch_cap;\n union { /* int to float conversion buffer for several subTLVs */\n float f;\n uint32_t i;\n } bw;\n\n /* first lets see if we know the subTLVs name*/\n\tND_PRINT((ndo, \"%s%s subTLV #%u, length: %u\",\n\t ident, tok2str(isis_ext_is_reach_subtlv_values, \"unknown\", subt),\n\t subt, subl));\n\n\tND_TCHECK2(*tptr, subl);\n\n switch(subt) {\n case ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP:\n case ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID:\n case ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID:\n\t if (subl >= 4) {\n\t ND_PRINT((ndo, \", 0x%08x\", EXTRACT_32BITS(tptr)));\n\t if (subl == 8) /* rfc4205 */\n\t ND_PRINT((ndo, \", 0x%08x\", EXTRACT_32BITS(tptr+4)));\n\t }\n\t break;\n case ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR:\n case ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR:\n if (subl >= sizeof(struct in_addr))\n ND_PRINT((ndo, \", %s\", ipaddr_string(ndo, tptr)));\n break;\n case ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW :\n\tcase ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW:\n if (subl >= 4) {\n bw.i = EXTRACT_32BITS(tptr);\n ND_PRINT((ndo, \", %.3f Mbps\", bw.f * 8 / 1000000));\n }\n break;\n case ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW :\n if (subl >= 32) {\n for (te_class = 0; te_class < 8; te_class++) {\n bw.i = EXTRACT_32BITS(tptr);\n ND_PRINT((ndo, \"%s TE-Class %u: %.3f Mbps\",\n ident,\n te_class,\n bw.f * 8 / 1000000));\n\t\ttptr+=4;\n\t }\n }\n break;\n case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS: /* fall through */\n case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD:\n ND_PRINT((ndo, \"%sBandwidth Constraints Model ID: %s (%u)\",\n ident,\n tok2str(diffserv_te_bc_values, \"unknown\", *tptr),\n *tptr));\n tptr++;\n /* decode BCs until the subTLV ends */\n for (te_class = 0; te_class < (subl-1)/4; te_class++) {\n ND_TCHECK2(*tptr, 4);\n bw.i = EXTRACT_32BITS(tptr);\n ND_PRINT((ndo, \"%s Bandwidth constraint CT%u: %.3f Mbps\",\n ident,\n te_class,\n bw.f * 8 / 1000000));\n\t\ttptr+=4;\n }\n break;\n case ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC:\n if (subl >= 3)\n ND_PRINT((ndo, \", %u\", EXTRACT_24BITS(tptr)));\n break;\n case ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE:\n if (subl == 2) {\n ND_PRINT((ndo, \", [ %s ] (0x%04x)\",\n bittok2str(isis_subtlv_link_attribute_values,\n \"Unknown\",\n EXTRACT_16BITS(tptr)),\n EXTRACT_16BITS(tptr)));\n }\n break;\n case ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE:\n if (subl >= 2) {\n ND_PRINT((ndo, \", %s, Priority %u\",\n\t\t bittok2str(gmpls_link_prot_values, \"none\", *tptr),\n *(tptr+1)));\n }\n break;\n case ISIS_SUBTLV_SPB_METRIC:\n if (subl >= 6) {\n ND_PRINT((ndo, \", LM: %u\", EXTRACT_24BITS(tptr)));\n tptr=tptr+3;\n ND_PRINT((ndo, \", P: %u\", *(tptr)));\n tptr++;\n ND_PRINT((ndo, \", P-ID: %u\", EXTRACT_16BITS(tptr)));\n }\n break;\n case ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR:\n if (subl >= 36) {\n gmpls_switch_cap = *tptr;\n ND_PRINT((ndo, \"%s Interface Switching Capability:%s\",\n ident,\n tok2str(gmpls_switch_cap_values, \"Unknown\", gmpls_switch_cap)));\n ND_PRINT((ndo, \", LSP Encoding: %s\",\n tok2str(gmpls_encoding_values, \"Unknown\", *(tptr + 1))));\n\t tptr+=4;\n ND_PRINT((ndo, \"%s Max LSP Bandwidth:\", ident));\n for (priority_level = 0; priority_level < 8; priority_level++) {\n bw.i = EXTRACT_32BITS(tptr);\n ND_PRINT((ndo, \"%s priority level %d: %.3f Mbps\",\n ident,\n priority_level,\n bw.f * 8 / 1000000));\n\t\ttptr+=4;\n }\n subl-=36;\n switch (gmpls_switch_cap) {\n case GMPLS_PSC1:\n case GMPLS_PSC2:\n case GMPLS_PSC3:\n case GMPLS_PSC4:\n ND_TCHECK2(*tptr, 6);\n bw.i = EXTRACT_32BITS(tptr);\n ND_PRINT((ndo, \"%s Min LSP Bandwidth: %.3f Mbps\", ident, bw.f * 8 / 1000000));\n ND_PRINT((ndo, \"%s Interface MTU: %u\", ident, EXTRACT_16BITS(tptr + 4)));\n break;\n case GMPLS_TSC:\n ND_TCHECK2(*tptr, 8);\n bw.i = EXTRACT_32BITS(tptr);\n ND_PRINT((ndo, \"%s Min LSP Bandwidth: %.3f Mbps\", ident, bw.f * 8 / 1000000));\n ND_PRINT((ndo, \"%s Indication %s\", ident,\n tok2str(gmpls_switch_cap_tsc_indication_values, \"Unknown (%u)\", *(tptr + 4))));\n break;\n default:\n /* there is some optional stuff left to decode but this is as of yet\n not specified so just lets hexdump what is left */\n if(subl>0){\n if (!print_unknown_data(ndo, tptr, \"\\n\\t\\t \", subl))\n return(0);\n }\n }\n }\n break;\n default:\n if (!print_unknown_data(ndo, tptr, \"\\n\\t\\t \", subl))\n return(0);\n break;\n }\n return(1);\n\ntrunc:\n return(0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13055/IS-IS: fix an Extended IS Reachability sub-TLV\n\nIn isis_print_is_reach_subtlv() one of the case blocks did not check that\nthe sub-TLV \"V\" is actually present and could over-read the input buffer.\nAdd a length check to fix that and remove a useless boundary check from\na loop because the boundary is tested for the full length of \"V\" before\nthe switch block.\n\nUpdate one of the prior test cases as it turns out it depended on this\npreviously incorrect code path to make it to its own malformed structure\nfurther down the buffer, the bugfix has changed its output.\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 int rfcomm_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct bt_security sec;\n\tint len, err = 0;\n\n\tBT_DBG(\"sk %p\", sk);\n\n\tif (level == SOL_RFCOMM)\n\t\treturn rfcomm_sock_getsockopt_old(sock, optname, optval, optlen);\n\n\tif (level != SOL_BLUETOOTH)\n\t\treturn -ENOPROTOOPT;\n\n\tif (get_user(len, optlen))\n\t\treturn -EFAULT;\n\n\tlock_sock(sk);\n\n\tswitch (optname) {\n\tcase BT_SECURITY:\n\t\tif (sk->sk_type != SOCK_STREAM) {\n\t\t\terr = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\n\t\tsec.level = rfcomm_pi(sk)->sec_level;\n\n\t\tlen = min_t(unsigned int, len, sizeof(sec));\n\t\tif (copy_to_user(optval, (char *) &sec, len))\n\t\t\terr = -EFAULT;\n\n\t\tbreak;\n\n\tcase BT_DEFER_SETUP:\n\t\tif (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) {\n\t\t\terr = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (put_user(test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags),\n\t\t\t (u32 __user *) optval))\n\t\t\terr = -EFAULT;\n\n\t\tbreak;\n\n\tdefault:\n\t\terr = -ENOPROTOOPT;\n\t\tbreak;\n\t}\n\n\trelease_sock(sk);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Bluetooth: RFCOMM - Fix info leak in getsockopt(BT_SECURITY)\n\nThe RFCOMM code fails to initialize the key_size member of struct\nbt_security before copying it to userland -- that for leaking one\nbyte kernel stack. Initialize key_size with 0 to avoid the info\nleak.\n\nSigned-off-by: Mathias Krause \nCc: Marcel Holtmann \nCc: Gustavo Padovan \nCc: Johan Hedberg \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: vm_loop (vm_frame_ctx_t *frame_ctx_p) /**< frame context */\n{\n const ecma_compiled_code_t *bytecode_header_p = frame_ctx_p->shared_p->bytecode_header_p;\n const uint8_t *byte_code_p = frame_ctx_p->byte_code_p;\n ecma_value_t *literal_start_p = frame_ctx_p->literal_start_p;\n\n ecma_value_t *stack_top_p;\n uint16_t encoding_limit;\n uint16_t encoding_delta;\n uint16_t register_end;\n uint16_t ident_end;\n uint16_t const_literal_end;\n int32_t branch_offset = 0;\n uint8_t branch_offset_length = 0;\n ecma_value_t left_value;\n ecma_value_t right_value;\n ecma_value_t result = ECMA_VALUE_EMPTY;\n bool is_strict = ((bytecode_header_p->status_flags & CBC_CODE_FLAGS_STRICT_MODE) != 0);\n\n /* Prepare for byte code execution. */\n if (!(bytecode_header_p->status_flags & CBC_CODE_FLAGS_FULL_LITERAL_ENCODING))\n {\n encoding_limit = CBC_SMALL_LITERAL_ENCODING_LIMIT;\n encoding_delta = CBC_SMALL_LITERAL_ENCODING_DELTA;\n }\n else\n {\n encoding_limit = CBC_FULL_LITERAL_ENCODING_LIMIT;\n encoding_delta = CBC_FULL_LITERAL_ENCODING_DELTA;\n }\n\n if (bytecode_header_p->status_flags & CBC_CODE_FLAGS_UINT16_ARGUMENTS)\n {\n cbc_uint16_arguments_t *args_p = (cbc_uint16_arguments_t *) (bytecode_header_p);\n register_end = args_p->register_end;\n ident_end = args_p->ident_end;\n const_literal_end = args_p->const_literal_end;\n }\n else\n {\n cbc_uint8_arguments_t *args_p = (cbc_uint8_arguments_t *) (bytecode_header_p);\n register_end = args_p->register_end;\n ident_end = args_p->ident_end;\n const_literal_end = args_p->const_literal_end;\n }\n\n stack_top_p = frame_ctx_p->stack_top_p;\n\n /* Outer loop for exception handling. */\n while (true)\n {\n /* Internal loop for byte code execution. */\n while (true)\n {\n const uint8_t *byte_code_start_p = byte_code_p;\n uint8_t opcode = *byte_code_p++;\n uint32_t opcode_data = opcode;\n\n if (opcode == CBC_EXT_OPCODE)\n {\n opcode = *byte_code_p++;\n opcode_data = (uint32_t) ((CBC_END + 1) + opcode);\n }\n\n opcode_data = vm_decode_table[opcode_data];\n\n left_value = ECMA_VALUE_UNDEFINED;\n right_value = ECMA_VALUE_UNDEFINED;\n\n uint32_t operands = VM_OC_GET_ARGS_INDEX (opcode_data);\n\n if (operands >= VM_OC_GET_LITERAL)\n {\n uint16_t literal_index;\n READ_LITERAL_INDEX (literal_index);\n READ_LITERAL (literal_index, left_value);\n\n if (operands != VM_OC_GET_LITERAL)\n {\n switch (operands)\n {\n case VM_OC_GET_LITERAL_LITERAL:\n {\n uint16_t second_literal_index;\n READ_LITERAL_INDEX (second_literal_index);\n READ_LITERAL (second_literal_index, right_value);\n break;\n }\n case VM_OC_GET_STACK_LITERAL:\n {\n JERRY_ASSERT (stack_top_p > VM_GET_REGISTERS (frame_ctx_p) + register_end);\n right_value = left_value;\n left_value = *(--stack_top_p);\n break;\n }\n default:\n {\n JERRY_ASSERT (operands == VM_OC_GET_THIS_LITERAL);\n\n right_value = left_value;\n left_value = ecma_copy_value (frame_ctx_p->this_binding);\n break;\n }\n }\n }\n }\n else if (operands >= VM_OC_GET_STACK)\n {\n JERRY_ASSERT (operands == VM_OC_GET_STACK\n || operands == VM_OC_GET_STACK_STACK);\n\n JERRY_ASSERT (stack_top_p > VM_GET_REGISTERS (frame_ctx_p) + register_end);\n left_value = *(--stack_top_p);\n\n if (operands == VM_OC_GET_STACK_STACK)\n {\n JERRY_ASSERT (stack_top_p > VM_GET_REGISTERS (frame_ctx_p) + register_end);\n right_value = left_value;\n left_value = *(--stack_top_p);\n }\n }\n else if (operands == VM_OC_GET_BRANCH)\n {\n branch_offset_length = CBC_BRANCH_OFFSET_LENGTH (opcode);\n JERRY_ASSERT (branch_offset_length >= 1 && branch_offset_length <= 3);\n\n branch_offset = *(byte_code_p++);\n\n if (JERRY_UNLIKELY (branch_offset_length != 1))\n {\n branch_offset <<= 8;\n branch_offset |= *(byte_code_p++);\n\n if (JERRY_UNLIKELY (branch_offset_length == 3))\n {\n branch_offset <<= 8;\n branch_offset |= *(byte_code_p++);\n }\n }\n\n if (opcode_data & VM_OC_BACKWARD_BRANCH)\n {\n#if JERRY_VM_EXEC_STOP\n if (JERRY_CONTEXT (vm_exec_stop_cb) != NULL\n && --JERRY_CONTEXT (vm_exec_stop_counter) == 0)\n {\n result = JERRY_CONTEXT (vm_exec_stop_cb) (JERRY_CONTEXT (vm_exec_stop_user_p));\n\n if (ecma_is_value_undefined (result))\n {\n JERRY_CONTEXT (vm_exec_stop_counter) = JERRY_CONTEXT (vm_exec_stop_frequency);\n }\n else\n {\n JERRY_CONTEXT (vm_exec_stop_counter) = 1;\n\n if (ecma_is_value_error_reference (result))\n {\n ecma_raise_error_from_error_reference (result);\n }\n else\n {\n jcontext_raise_exception (result);\n }\n\n JERRY_ASSERT (jcontext_has_pending_exception ());\n jcontext_set_abort_flag (true);\n result = ECMA_VALUE_ERROR;\n goto error;\n }\n }\n#endif /* JERRY_VM_EXEC_STOP */\n\n branch_offset = -branch_offset;\n }\n }\n\n switch (VM_OC_GROUP_GET_INDEX (opcode_data))\n {\n case VM_OC_POP:\n {\n JERRY_ASSERT (stack_top_p > VM_GET_REGISTERS (frame_ctx_p) + register_end);\n ecma_free_value (*(--stack_top_p));\n continue;\n }\n case VM_OC_POP_BLOCK:\n {\n ecma_fast_free_value (VM_GET_REGISTER (frame_ctx_p, 0));\n VM_GET_REGISTERS (frame_ctx_p)[0] = *(--stack_top_p);\n continue;\n }\n case VM_OC_PUSH:\n {\n *stack_top_p++ = left_value;\n continue;\n }\n case VM_OC_PUSH_TWO:\n {\n *stack_top_p++ = left_value;\n *stack_top_p++ = right_value;\n continue;\n }\n case VM_OC_PUSH_THREE:\n {\n uint16_t literal_index;\n\n *stack_top_p++ = left_value;\n left_value = ECMA_VALUE_UNDEFINED;\n\n READ_LITERAL_INDEX (literal_index);\n READ_LITERAL (literal_index, left_value);\n\n *stack_top_p++ = right_value;\n *stack_top_p++ = left_value;\n continue;\n }\n case VM_OC_PUSH_UNDEFINED:\n {\n *stack_top_p++ = ECMA_VALUE_UNDEFINED;\n continue;\n }\n case VM_OC_PUSH_TRUE:\n {\n *stack_top_p++ = ECMA_VALUE_TRUE;\n continue;\n }\n case VM_OC_PUSH_FALSE:\n {\n *stack_top_p++ = ECMA_VALUE_FALSE;\n continue;\n }\n case VM_OC_PUSH_NULL:\n {\n *stack_top_p++ = ECMA_VALUE_NULL;\n continue;\n }\n case VM_OC_PUSH_THIS:\n {\n *stack_top_p++ = ecma_copy_value (frame_ctx_p->this_binding);\n continue;\n }\n case VM_OC_PUSH_0:\n {\n *stack_top_p++ = ecma_make_integer_value (0);\n continue;\n }\n case VM_OC_PUSH_POS_BYTE:\n {\n ecma_integer_value_t number = *byte_code_p++;\n *stack_top_p++ = ecma_make_integer_value (number + 1);\n continue;\n }\n case VM_OC_PUSH_NEG_BYTE:\n {\n ecma_integer_value_t number = *byte_code_p++;\n *stack_top_p++ = ecma_make_integer_value (-(number + 1));\n continue;\n }\n case VM_OC_PUSH_LIT_0:\n {\n stack_top_p[0] = left_value;\n stack_top_p[1] = ecma_make_integer_value (0);\n stack_top_p += 2;\n continue;\n }\n case VM_OC_PUSH_LIT_POS_BYTE:\n {\n ecma_integer_value_t number = *byte_code_p++;\n stack_top_p[0] = left_value;\n stack_top_p[1] = ecma_make_integer_value (number + 1);\n stack_top_p += 2;\n continue;\n }\n case VM_OC_PUSH_LIT_NEG_BYTE:\n {\n ecma_integer_value_t number = *byte_code_p++;\n stack_top_p[0] = left_value;\n stack_top_p[1] = ecma_make_integer_value (-(number + 1));\n stack_top_p += 2;\n continue;\n }\n case VM_OC_PUSH_OBJECT:\n {\n ecma_object_t *obj_p = ecma_create_object (ecma_builtin_get (ECMA_BUILTIN_ID_OBJECT_PROTOTYPE),\n 0,\n ECMA_OBJECT_TYPE_GENERAL);\n\n *stack_top_p++ = ecma_make_object_value (obj_p);\n continue;\n }\n case VM_OC_PUSH_NAMED_FUNC_EXPR:\n {\n ecma_object_t *func_p = ecma_get_object_from_value (left_value);\n\n JERRY_ASSERT (ecma_get_object_type (func_p) == ECMA_OBJECT_TYPE_FUNCTION);\n\n ecma_extended_object_t *ext_func_p = (ecma_extended_object_t *) func_p;\n\n JERRY_ASSERT (frame_ctx_p->lex_env_p ==\n ECMA_GET_NON_NULL_POINTER_FROM_POINTER_TAG (ecma_object_t, ext_func_p->u.function.scope_cp));\n\n ecma_object_t *name_lex_env = ecma_create_decl_lex_env (frame_ctx_p->lex_env_p);\n\n ecma_op_create_immutable_binding (name_lex_env, ecma_get_string_from_value (right_value), left_value);\n\n ECMA_SET_NON_NULL_POINTER_TAG (ext_func_p->u.function.scope_cp, name_lex_env, 0);\n\n ecma_free_value (right_value);\n ecma_deref_object (name_lex_env);\n *stack_top_p++ = left_value;\n continue;\n }\n case VM_OC_CREATE_BINDING:\n {\n#if !JERRY_ESNEXT\n JERRY_ASSERT (opcode == CBC_CREATE_VAR);\n#endif /* !JERRY_ESNEXT */\n\n uint32_t literal_index;\n\n READ_LITERAL_INDEX (literal_index);\n\n ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]);\n\n JERRY_ASSERT (ecma_get_lex_env_type (frame_ctx_p->lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE);\n JERRY_ASSERT (ecma_find_named_property (frame_ctx_p->lex_env_p, name_p) == NULL);\n\n uint8_t prop_attributes = ECMA_PROPERTY_FLAG_WRITABLE;\n\n#if JERRY_ESNEXT\n if (opcode == CBC_CREATE_LET)\n {\n prop_attributes = ECMA_PROPERTY_ENUMERABLE_WRITABLE;\n }\n else if (opcode == CBC_CREATE_CONST)\n {\n prop_attributes = ECMA_PROPERTY_FLAG_ENUMERABLE;\n }\n\n ecma_property_value_t *property_value_p;\n property_value_p = ecma_create_named_data_property (frame_ctx_p->lex_env_p, name_p, prop_attributes, NULL);\n\n if (opcode != CBC_CREATE_VAR)\n {\n property_value_p->value = ECMA_VALUE_UNINITIALIZED;\n }\n#else /* !JERRY_ESNEXT */\n ecma_create_named_data_property (frame_ctx_p->lex_env_p, name_p, prop_attributes, NULL);\n#endif /* JERRY_ESNEXT */\n\n continue;\n }\n case VM_OC_VAR_EVAL:\n {\n uint32_t literal_index;\n ecma_value_t lit_value = ECMA_VALUE_UNDEFINED;\n\n if (opcode == CBC_CREATE_VAR_FUNC_EVAL)\n {\n uint32_t value_index;\n READ_LITERAL_INDEX (value_index);\n JERRY_ASSERT (value_index >= const_literal_end);\n\n lit_value = vm_construct_literal_object (frame_ctx_p,\n literal_start_p[value_index]);\n }\n\n READ_LITERAL_INDEX (literal_index);\n JERRY_ASSERT (literal_index >= register_end);\n\n ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]);\n ecma_object_t *lex_env_p = frame_ctx_p->lex_env_p;\n\n while (lex_env_p->type_flags_refs & ECMA_OBJECT_FLAG_BLOCK)\n {\n#if JERRY_ESNEXT && !(defined JERRY_NDEBUG)\n if (ecma_get_lex_env_type (lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE)\n {\n ecma_property_t *property_p = ecma_find_named_property (lex_env_p, name_p);\n\n JERRY_ASSERT (property_p == NULL || !(*property_p & ECMA_PROPERTY_FLAG_ENUMERABLE));\n }\n#endif /* JERRY_ESNEXT && !JERRY_NDEBUG */\n\n JERRY_ASSERT (lex_env_p->u2.outer_reference_cp != JMEM_CP_NULL);\n lex_env_p = ECMA_GET_NON_NULL_POINTER (ecma_object_t, lex_env_p->u2.outer_reference_cp);\n }\n\n#if JERRY_ESNEXT && !(defined JERRY_NDEBUG)\n if (ecma_get_lex_env_type (lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE)\n {\n ecma_property_t *property_p = ecma_find_named_property (lex_env_p, name_p);\n\n JERRY_ASSERT (property_p == NULL || !(*property_p & ECMA_PROPERTY_FLAG_ENUMERABLE));\n }\n#endif /* JERRY_ESNEXT && !JERRY_NDEBUG */\n\n /* 'Variable declaration' */\n result = ecma_op_has_binding (lex_env_p, name_p);\n\n#if JERRY_BUILTIN_PROXY\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n#endif /* JERRY_BUILTIN_PROXY */\n\n ecma_property_t *prop_p = NULL;\n\n if (ecma_is_value_false (result))\n {\n bool is_configurable = (frame_ctx_p->status_flags & VM_FRAME_CTX_DIRECT_EVAL) != 0;\n prop_p = ecma_op_create_mutable_binding (lex_env_p, name_p, is_configurable);\n\n if (JERRY_UNLIKELY (prop_p == ECMA_PROPERTY_POINTER_ERROR))\n {\n result = ECMA_VALUE_ERROR;\n goto error;\n }\n }\n\n if (lit_value != ECMA_VALUE_UNDEFINED)\n {\n JERRY_ASSERT (ecma_is_value_object (lit_value));\n\n if (prop_p != NULL)\n {\n JERRY_ASSERT (ecma_is_value_undefined (ECMA_PROPERTY_VALUE_PTR (prop_p)->value));\n JERRY_ASSERT (ecma_is_property_writable (*prop_p));\n ECMA_PROPERTY_VALUE_PTR (prop_p)->value = lit_value;\n ecma_free_object (lit_value);\n }\n else\n {\n result = ecma_op_put_value_lex_env_base (lex_env_p, name_p, is_strict, lit_value);\n ecma_free_object (lit_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n }\n }\n continue;\n }\n#if JERRY_ESNEXT\n case VM_OC_EXT_VAR_EVAL:\n {\n uint32_t literal_index;\n ecma_value_t lit_value = ECMA_VALUE_UNDEFINED;\n\n JERRY_ASSERT (byte_code_start_p[0] == CBC_EXT_OPCODE);\n\n if (opcode == CBC_EXT_CREATE_VAR_FUNC_EVAL)\n {\n uint32_t value_index;\n READ_LITERAL_INDEX (value_index);\n JERRY_ASSERT (value_index >= const_literal_end);\n\n lit_value = vm_construct_literal_object (frame_ctx_p,\n literal_start_p[value_index]);\n }\n\n READ_LITERAL_INDEX (literal_index);\n JERRY_ASSERT (literal_index >= register_end);\n\n ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]);\n ecma_object_t *lex_env_p = frame_ctx_p->lex_env_p;\n ecma_object_t *prev_lex_env_p = NULL;\n\n while (lex_env_p->type_flags_refs & ECMA_OBJECT_FLAG_BLOCK)\n {\n#if !(defined JERRY_NDEBUG)\n if (ecma_get_lex_env_type (lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE)\n {\n ecma_property_t *property_p = ecma_find_named_property (lex_env_p, name_p);\n\n JERRY_ASSERT (property_p == NULL || !(*property_p & ECMA_PROPERTY_FLAG_ENUMERABLE));\n }\n#endif /* !JERRY_NDEBUG */\n\n JERRY_ASSERT (lex_env_p->u2.outer_reference_cp != JMEM_CP_NULL);\n prev_lex_env_p = lex_env_p;\n lex_env_p = ECMA_GET_NON_NULL_POINTER (ecma_object_t, lex_env_p->u2.outer_reference_cp);\n }\n\n JERRY_ASSERT (ecma_get_lex_env_type (lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE);\n JERRY_ASSERT (prev_lex_env_p != NULL\n && ecma_get_lex_env_type (prev_lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE);\n\n ecma_property_t *property_p = ecma_find_named_property (prev_lex_env_p, name_p);\n ecma_property_value_t *property_value_p;\n\n if (property_p == NULL)\n {\n property_value_p = ecma_create_named_data_property (prev_lex_env_p,\n name_p,\n ECMA_PROPERTY_CONFIGURABLE_WRITABLE,\n NULL);\n\n if (lit_value == ECMA_VALUE_UNDEFINED)\n {\n continue;\n }\n }\n else\n {\n if (lit_value == ECMA_VALUE_UNDEFINED)\n {\n continue;\n }\n\n property_value_p = ECMA_PROPERTY_VALUE_PTR (property_p);\n ecma_free_value_if_not_object (property_value_p->value);\n }\n\n property_value_p->value = lit_value;\n ecma_deref_object (ecma_get_object_from_value (lit_value));\n continue;\n }\n#endif /* JERRY_ESNEXT */\n case VM_OC_CREATE_ARGUMENTS:\n {\n uint32_t literal_index;\n READ_LITERAL_INDEX (literal_index);\n\n JERRY_ASSERT (frame_ctx_p->shared_p->status_flags & VM_FRAME_CTX_SHARED_HAS_ARG_LIST);\n\n result = ecma_op_create_arguments_object ((vm_frame_ctx_shared_args_t *) (frame_ctx_p->shared_p),\n frame_ctx_p->lex_env_p);\n\n if (literal_index < register_end)\n {\n JERRY_ASSERT (VM_GET_REGISTER (frame_ctx_p, literal_index) == ECMA_VALUE_UNDEFINED);\n VM_GET_REGISTER (frame_ctx_p, literal_index) = result;\n continue;\n }\n\n ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]);\n\n JERRY_ASSERT (ecma_find_named_property (frame_ctx_p->lex_env_p, name_p) == NULL);\n\n uint8_t prop_attributes = ECMA_PROPERTY_FLAG_WRITABLE;\n ecma_property_value_t *property_value_p;\n\n property_value_p = ecma_create_named_data_property (frame_ctx_p->lex_env_p, name_p, prop_attributes, NULL);\n property_value_p->value = result;\n\n ecma_deref_object (ecma_get_object_from_value (result));\n continue;\n }\n#if JERRY_SNAPSHOT_EXEC\n case VM_OC_SET_BYTECODE_PTR:\n {\n memcpy (&byte_code_p, byte_code_p++, sizeof (uintptr_t));\n frame_ctx_p->byte_code_start_p = byte_code_p;\n continue;\n }\n#endif /* JERRY_SNAPSHOT_EXEC */\n case VM_OC_INIT_ARG_OR_FUNC:\n {\n uint32_t literal_index, value_index;\n ecma_value_t lit_value;\n bool release = false;\n\n READ_LITERAL_INDEX (value_index);\n\n if (value_index < register_end)\n {\n /* Take (not copy) the reference. */\n lit_value = ecma_copy_value_if_not_object (VM_GET_REGISTER (frame_ctx_p, value_index));\n }\n else\n {\n lit_value = vm_construct_literal_object (frame_ctx_p,\n literal_start_p[value_index]);\n release = true;\n }\n\n READ_LITERAL_INDEX (literal_index);\n\n JERRY_ASSERT (value_index != literal_index);\n JERRY_ASSERT (value_index >= register_end || literal_index >= register_end);\n\n if (literal_index < register_end)\n {\n ecma_fast_free_value (VM_GET_REGISTER (frame_ctx_p, literal_index));\n JERRY_ASSERT (release);\n VM_GET_REGISTER (frame_ctx_p, literal_index) = lit_value;\n continue;\n }\n\n ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]);\n\n JERRY_ASSERT (ecma_get_lex_env_type (frame_ctx_p->lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE);\n JERRY_ASSERT (ecma_find_named_property (frame_ctx_p->lex_env_p, name_p) == NULL);\n\n ecma_property_value_t *property_value_p;\n property_value_p = ecma_create_named_data_property (frame_ctx_p->lex_env_p,\n name_p,\n ECMA_PROPERTY_FLAG_WRITABLE,\n NULL);\n\n JERRY_ASSERT (property_value_p->value == ECMA_VALUE_UNDEFINED);\n property_value_p->value = lit_value;\n\n if (release)\n {\n ecma_deref_object (ecma_get_object_from_value (lit_value));\n }\n continue;\n }\n#if JERRY_ESNEXT\n case VM_OC_CHECK_VAR:\n {\n JERRY_ASSERT (CBC_FUNCTION_GET_TYPE (frame_ctx_p->shared_p->bytecode_header_p->status_flags)\n == CBC_FUNCTION_SCRIPT);\n\n uint32_t literal_index;\n READ_LITERAL_INDEX (literal_index);\n\n if ((frame_ctx_p->lex_env_p->type_flags_refs & ECMA_OBJECT_FLAG_BLOCK) == 0)\n {\n continue;\n }\n\n ecma_string_t *const literal_name_p = ecma_get_string_from_value (literal_start_p[literal_index]);\n ecma_property_t *const binding_p = ecma_find_named_property (frame_ctx_p->lex_env_p, literal_name_p);\n\n if (binding_p != NULL)\n {\n result = ecma_raise_syntax_error (ECMA_ERR_MSG (ecma_error_local_variable_is_redeclared));\n goto error;\n }\n\n continue;\n }\n case VM_OC_CHECK_LET:\n {\n JERRY_ASSERT (CBC_FUNCTION_GET_TYPE (frame_ctx_p->shared_p->bytecode_header_p->status_flags)\n == CBC_FUNCTION_SCRIPT);\n\n uint32_t literal_index;\n READ_LITERAL_INDEX (literal_index);\n\n ecma_string_t *literal_name_p = ecma_get_string_from_value (literal_start_p[literal_index]);\n ecma_object_t *lex_env_p = frame_ctx_p->lex_env_p;\n\n if (lex_env_p->type_flags_refs & ECMA_OBJECT_FLAG_BLOCK)\n {\n result = opfunc_lexical_scope_has_restricted_binding (frame_ctx_p, literal_name_p);\n\n if (!ecma_is_value_false (result))\n {\n if (ecma_is_value_true (result))\n {\n result = ecma_raise_syntax_error (ECMA_ERR_MSG (ecma_error_local_variable_is_redeclared));\n }\n\n JERRY_ASSERT (ECMA_IS_VALUE_ERROR (result));\n goto error;\n }\n\n continue;\n }\n\n result = ecma_op_has_binding (lex_env_p, literal_name_p);\n\n#if JERRY_BUILTIN_PROXY\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n#endif /* JERRY_BUILTIN_PROXY */\n\n if (ecma_is_value_true (result))\n {\n result = ecma_raise_syntax_error (ECMA_ERR_MSG (ecma_error_local_variable_is_redeclared));\n goto error;\n }\n\n continue;\n }\n case VM_OC_ASSIGN_LET_CONST:\n {\n uint32_t literal_index;\n READ_LITERAL_INDEX (literal_index);\n\n JERRY_ASSERT (literal_index >= register_end);\n JERRY_ASSERT (ecma_get_lex_env_type (frame_ctx_p->lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE\n || (ecma_get_lex_env_type (frame_ctx_p->lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_CLASS\n && (frame_ctx_p->lex_env_p->type_flags_refs & ECMA_OBJECT_FLAG_LEXICAL_ENV_HAS_DATA)));\n\n ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]);\n ecma_property_t *property_p = ecma_find_named_property (frame_ctx_p->lex_env_p, name_p);\n\n JERRY_ASSERT (property_p != NULL\n && ECMA_PROPERTY_IS_RAW_DATA (*property_p)\n && (*property_p & ECMA_PROPERTY_FLAG_DATA));\n JERRY_ASSERT (ECMA_PROPERTY_VALUE_PTR (property_p)->value == ECMA_VALUE_UNINITIALIZED);\n\n ECMA_PROPERTY_VALUE_PTR (property_p)->value = left_value;\n\n if (ecma_is_value_object (left_value))\n {\n ecma_deref_object (ecma_get_object_from_value (left_value));\n }\n continue;\n }\n case VM_OC_INIT_BINDING:\n {\n uint32_t literal_index;\n\n READ_LITERAL_INDEX (literal_index);\n\n JERRY_ASSERT (literal_index >= register_end);\n\n ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]);\n\n JERRY_ASSERT (ecma_get_lex_env_type (frame_ctx_p->lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE);\n JERRY_ASSERT (ecma_find_named_property (frame_ctx_p->lex_env_p, name_p) == NULL);\n\n uint8_t prop_attributes = ECMA_PROPERTY_FLAG_WRITABLE;\n\n if (opcode == CBC_INIT_LET)\n {\n prop_attributes = ECMA_PROPERTY_ENUMERABLE_WRITABLE;\n }\n else if (opcode == CBC_INIT_CONST)\n {\n prop_attributes = ECMA_PROPERTY_FLAG_ENUMERABLE;\n }\n\n ecma_property_value_t *property_value_p;\n property_value_p = ecma_create_named_data_property (frame_ctx_p->lex_env_p,\n name_p,\n prop_attributes,\n NULL);\n\n JERRY_ASSERT (property_value_p->value == ECMA_VALUE_UNDEFINED);\n\n ecma_value_t value = *(--stack_top_p);\n\n property_value_p->value = value;\n ecma_deref_if_object (value);\n continue;\n }\n case VM_OC_THROW_CONST_ERROR:\n {\n result = ecma_raise_type_error (ECMA_ERR_MSG (\"Constant bindings cannot be reassigned\"));\n goto error;\n }\n case VM_OC_COPY_TO_GLOBAL:\n {\n uint32_t literal_index;\n READ_LITERAL_INDEX (literal_index);\n\n ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]);\n ecma_object_t *lex_env_p = frame_ctx_p->lex_env_p;\n\n while (lex_env_p->type_flags_refs & ECMA_OBJECT_FLAG_BLOCK)\n {\n#ifndef JERRY_NDEBUG\n if (ecma_get_lex_env_type (lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE)\n {\n ecma_property_t *property_p = ecma_find_named_property (lex_env_p, name_p);\n\n JERRY_ASSERT (property_p == NULL || !(*property_p & ECMA_PROPERTY_FLAG_ENUMERABLE));\n }\n#endif /* !JERRY_NDEBUG */\n\n JERRY_ASSERT (lex_env_p->u2.outer_reference_cp != JMEM_CP_NULL);\n lex_env_p = ECMA_GET_NON_NULL_POINTER (ecma_object_t, lex_env_p->u2.outer_reference_cp);\n }\n\n if (ecma_get_lex_env_type (lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE)\n {\n ecma_property_t *property_p = ecma_find_named_property (lex_env_p, name_p);\n ecma_property_value_t *prop_value_p;\n\n if (property_p == NULL)\n {\n prop_value_p = ecma_create_named_data_property (lex_env_p,\n name_p,\n ECMA_PROPERTY_FLAG_WRITABLE,\n NULL);\n }\n else\n {\n#ifndef JERRY_NDEBUG\n JERRY_ASSERT (!(*property_p & ECMA_PROPERTY_FLAG_ENUMERABLE));\n#endif /* !JERRY_NDEBUG */\n prop_value_p = ECMA_PROPERTY_VALUE_PTR (property_p);\n }\n\n ecma_named_data_property_assign_value (lex_env_p, prop_value_p, left_value);\n }\n else\n {\n result = ecma_op_set_mutable_binding (lex_env_p, name_p, left_value, is_strict);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n }\n\n goto free_left_value;\n }\n case VM_OC_COPY_FROM_ARG:\n {\n uint32_t literal_index;\n READ_LITERAL_INDEX (literal_index);\n JERRY_ASSERT (literal_index >= register_end);\n\n ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]);\n ecma_object_t *lex_env_p = frame_ctx_p->lex_env_p;\n ecma_object_t *arg_lex_env_p = ECMA_GET_NON_NULL_POINTER (ecma_object_t, lex_env_p->u2.outer_reference_cp);\n\n JERRY_ASSERT ((lex_env_p->type_flags_refs & ECMA_OBJECT_FLAG_BLOCK)\n && ecma_get_lex_env_type (lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE);\n JERRY_ASSERT (arg_lex_env_p != NULL\n && !(arg_lex_env_p->type_flags_refs & ECMA_OBJECT_FLAG_BLOCK)\n && ecma_get_lex_env_type (arg_lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE);\n\n ecma_property_value_t *property_value_p;\n property_value_p = ecma_create_named_data_property (lex_env_p,\n name_p,\n ECMA_PROPERTY_FLAG_WRITABLE,\n NULL);\n\n ecma_property_t *property_p = ecma_find_named_property (arg_lex_env_p, name_p);\n JERRY_ASSERT (property_p != NULL);\n\n ecma_property_value_t *arg_prop_value_p = ECMA_PROPERTY_VALUE_PTR (property_p);\n property_value_p->value = ecma_copy_value_if_not_object (arg_prop_value_p->value);\n continue;\n }\n case VM_OC_CLONE_CONTEXT:\n {\n JERRY_ASSERT (byte_code_start_p[0] == CBC_EXT_OPCODE);\n\n bool copy_values = (byte_code_start_p[1] == CBC_EXT_CLONE_FULL_CONTEXT);\n frame_ctx_p->lex_env_p = ecma_clone_decl_lexical_environment (frame_ctx_p->lex_env_p, copy_values);\n continue;\n }\n case VM_OC_SET__PROTO__:\n {\n result = ecma_builtin_object_object_set_proto (stack_top_p[-1], left_value);\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n goto free_left_value;\n }\n case VM_OC_PUSH_STATIC_FIELD_FUNC:\n {\n JERRY_ASSERT (byte_code_start_p[0] == CBC_EXT_OPCODE\n && (byte_code_start_p[1] == CBC_EXT_PUSH_STATIC_FIELD_FUNC\n || byte_code_start_p[1] == CBC_EXT_PUSH_STATIC_COMPUTED_FIELD_FUNC));\n\n bool push_computed = (byte_code_start_p[1] == CBC_EXT_PUSH_STATIC_COMPUTED_FIELD_FUNC);\n ecma_value_t value = stack_top_p[-1];\n\n if (!push_computed)\n {\n stack_top_p++;\n }\n\n memmove (stack_top_p - 3, stack_top_p - 4, 3 * sizeof (ecma_value_t));\n stack_top_p[-4] = left_value;\n\n if (!push_computed)\n {\n continue;\n }\n\n left_value = value;\n /* FALLTHRU */\n }\n case VM_OC_ADD_COMPUTED_FIELD:\n {\n JERRY_ASSERT (byte_code_start_p[0] == CBC_EXT_OPCODE\n && (byte_code_start_p[1] == CBC_EXT_PUSH_STATIC_COMPUTED_FIELD_FUNC\n || byte_code_start_p[1] == CBC_EXT_ADD_COMPUTED_FIELD\n || byte_code_start_p[1] == CBC_EXT_ADD_STATIC_COMPUTED_FIELD));\n\n int index = (byte_code_start_p[1] == CBC_EXT_ADD_COMPUTED_FIELD) ? -2 : -4;\n result = opfunc_add_computed_field (stack_top_p[index], left_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n goto free_left_value;\n }\n case VM_OC_COPY_DATA_PROPERTIES:\n {\n left_value = *(--stack_top_p);\n\n if (ecma_is_value_undefined (left_value) || ecma_is_value_null (left_value))\n {\n continue;\n }\n\n result = opfunc_copy_data_properties (stack_top_p[-1], left_value, ECMA_VALUE_UNDEFINED);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n goto free_left_value;\n }\n case VM_OC_SET_COMPUTED_PROPERTY:\n {\n /* Swap values. */\n left_value ^= right_value;\n right_value ^= left_value;\n left_value ^= right_value;\n /* FALLTHRU */\n }\n#endif /* JERRY_ESNEXT */\n case VM_OC_SET_PROPERTY:\n {\n JERRY_STATIC_ASSERT (VM_OC_NON_STATIC_FLAG == VM_OC_BACKWARD_BRANCH,\n vm_oc_non_static_flag_must_be_equal_to_vm_oc_backward_branch);\n\n JERRY_ASSERT ((opcode_data >> VM_OC_NON_STATIC_SHIFT) <= 0x1);\n\n ecma_string_t *prop_name_p = ecma_op_to_property_key (right_value);\n\n if (JERRY_UNLIKELY (prop_name_p == NULL))\n {\n result = ECMA_VALUE_ERROR;\n goto error;\n }\n\n#if JERRY_ESNEXT\n if (JERRY_UNLIKELY (ecma_compare_ecma_string_to_magic_id (prop_name_p, LIT_MAGIC_STRING_PROTOTYPE))\n && !(opcode_data & VM_OC_NON_STATIC_FLAG))\n {\n result = ecma_raise_type_error (ECMA_ERR_MSG (ecma_error_class_is_non_configurable));\n goto error;\n }\n\n const int index = (int) (opcode_data >> VM_OC_NON_STATIC_SHIFT) - 2;\n#else /* !JERRY_ESNEXT */\n const int index = -1;\n#endif /* JERRY_ESNEXT */\n\n ecma_object_t *object_p = ecma_get_object_from_value (stack_top_p[index]);\n\n opfunc_set_data_property (object_p, prop_name_p, left_value);\n ecma_deref_ecma_string (prop_name_p);\n\n goto free_both_values;\n }\n case VM_OC_SET_GETTER:\n case VM_OC_SET_SETTER:\n {\n JERRY_ASSERT ((opcode_data >> VM_OC_NON_STATIC_SHIFT) <= 0x1);\n\n ecma_string_t *prop_name_p = ecma_op_to_property_key (left_value);\n\n if (JERRY_UNLIKELY (prop_name_p == NULL))\n {\n result = ECMA_VALUE_ERROR;\n goto error;\n }\n\n#if JERRY_ESNEXT\n if (JERRY_UNLIKELY (ecma_compare_ecma_string_to_magic_id (prop_name_p, LIT_MAGIC_STRING_PROTOTYPE))\n && !(opcode_data & VM_OC_NON_STATIC_FLAG))\n {\n result = ecma_raise_type_error (ECMA_ERR_MSG (ecma_error_class_is_non_configurable));\n goto error;\n }\n\n const int index = (int) (opcode_data >> VM_OC_NON_STATIC_SHIFT) - 2;\n#else /* !JERRY_ESNEXT */\n const int index = -1;\n#endif /* JERRY_ESNEXT */\n\n opfunc_set_accessor (VM_OC_GROUP_GET_INDEX (opcode_data) == VM_OC_SET_GETTER,\n stack_top_p[index],\n prop_name_p,\n right_value);\n\n ecma_deref_ecma_string (prop_name_p);\n\n goto free_both_values;\n }\n case VM_OC_PUSH_ARRAY:\n {\n /* Note: this operation cannot throw an exception */\n *stack_top_p++ = ecma_make_object_value (ecma_op_new_array_object (0));\n continue;\n }\n#if JERRY_ESNEXT\n case VM_OC_LOCAL_EVAL:\n {\n ECMA_CLEAR_LOCAL_PARSE_OPTS ();\n uint8_t parse_opts = *byte_code_p++;\n ECMA_SET_LOCAL_PARSE_OPTS (parse_opts);\n continue;\n }\n case VM_OC_SUPER_CALL:\n {\n uint8_t arguments_list_len = *byte_code_p++;\n\n if (opcode >= CBC_EXT_SPREAD_SUPER_CALL)\n {\n stack_top_p -= arguments_list_len;\n ecma_collection_t *arguments_p = opfunc_spread_arguments (stack_top_p, arguments_list_len);\n\n if (JERRY_UNLIKELY (arguments_p == NULL))\n {\n result = ECMA_VALUE_ERROR;\n goto error;\n }\n\n stack_top_p++;\n ECMA_SET_INTERNAL_VALUE_POINTER (stack_top_p[-1], arguments_p);\n }\n else\n {\n stack_top_p -= arguments_list_len;\n }\n\n frame_ctx_p->call_operation = VM_EXEC_SUPER_CALL;\n frame_ctx_p->byte_code_p = byte_code_start_p;\n frame_ctx_p->stack_top_p = stack_top_p;\n return ECMA_VALUE_UNDEFINED;\n }\n case VM_OC_PUSH_CLASS_ENVIRONMENT:\n {\n uint16_t literal_index;\n\n READ_LITERAL_INDEX (literal_index);\n opfunc_push_class_environment (frame_ctx_p, &stack_top_p, literal_start_p[literal_index]);\n continue;\n }\n case VM_OC_PUSH_IMPLICIT_CTOR:\n {\n *stack_top_p++ = opfunc_create_implicit_class_constructor (opcode,\n frame_ctx_p->shared_p->bytecode_header_p);\n continue;\n }\n case VM_OC_INIT_CLASS:\n {\n result = opfunc_init_class (frame_ctx_p, stack_top_p);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n continue;\n }\n case VM_OC_FINALIZE_CLASS:\n {\n JERRY_ASSERT (opcode == CBC_EXT_FINALIZE_NAMED_CLASS || opcode == CBC_EXT_FINALIZE_ANONYMOUS_CLASS);\n\n if (opcode == CBC_EXT_FINALIZE_NAMED_CLASS)\n {\n uint16_t literal_index;\n READ_LITERAL_INDEX (literal_index);\n left_value = literal_start_p[literal_index];\n }\n\n opfunc_finalize_class (frame_ctx_p, &stack_top_p, left_value);\n continue;\n }\n case VM_OC_SET_FIELD_INIT:\n {\n ecma_string_t *property_name_p = ecma_get_magic_string (LIT_INTERNAL_MAGIC_STRING_CLASS_FIELD_INIT);\n ecma_object_t *object_p = ecma_get_object_from_value (stack_top_p[-2]);\n\n ecma_property_value_t *property_value_p = ecma_create_named_data_property (object_p,\n property_name_p,\n ECMA_PROPERTY_FIXED,\n NULL);\n property_value_p->value = left_value;\n\n property_name_p = ecma_get_internal_string (LIT_INTERNAL_MAGIC_STRING_CLASS_FIELD_COMPUTED);\n ecma_property_t *property_p = ecma_find_named_property (object_p, property_name_p);\n\n if (property_p != NULL)\n {\n property_value_p = ECMA_PROPERTY_VALUE_PTR (property_p);\n ecma_value_t *compact_collection_p = ECMA_GET_INTERNAL_VALUE_POINTER (ecma_value_t,\n property_value_p->value);\n compact_collection_p = ecma_compact_collection_shrink (compact_collection_p);\n ECMA_SET_INTERNAL_VALUE_POINTER (property_value_p->value, compact_collection_p);\n }\n\n goto free_left_value;\n }\n case VM_OC_RUN_FIELD_INIT:\n {\n JERRY_ASSERT (frame_ctx_p->shared_p->status_flags & VM_FRAME_CTX_SHARED_NON_ARROW_FUNC);\n result = opfunc_init_class_fields (frame_ctx_p->shared_p->function_object_p, frame_ctx_p->this_binding);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n continue;\n }\n case VM_OC_RUN_STATIC_FIELD_INIT:\n {\n left_value = stack_top_p[-2];\n stack_top_p[-2] = stack_top_p[-1];\n stack_top_p--;\n\n result = opfunc_init_static_class_fields (left_value, stack_top_p[-1]);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n goto free_left_value;\n }\n case VM_OC_SET_NEXT_COMPUTED_FIELD:\n {\n ecma_integer_value_t next_index = ecma_get_integer_from_value (stack_top_p[-2]) + 1;\n stack_top_p[-2] = ecma_make_integer_value (next_index);\n stack_top_p++;\n\n JERRY_ASSERT (frame_ctx_p->shared_p->status_flags & VM_FRAME_CTX_SHARED_HAS_CLASS_FIELDS);\n\n ecma_value_t *computed_class_fields_p = VM_GET_COMPUTED_CLASS_FIELDS (frame_ctx_p);\n JERRY_ASSERT ((ecma_value_t) next_index < ECMA_COMPACT_COLLECTION_GET_SIZE (computed_class_fields_p));\n\n result = stack_top_p[-2];\n stack_top_p[-1] = ecma_copy_value (computed_class_fields_p[next_index]);\n stack_top_p[-2] = ecma_copy_value (frame_ctx_p->this_binding);\n break;\n }\n case VM_OC_PUSH_SUPER_CONSTRUCTOR:\n {\n result = ecma_op_function_get_super_constructor (vm_get_class_function (frame_ctx_p));\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n continue;\n }\n case VM_OC_RESOLVE_LEXICAL_THIS:\n {\n result = ecma_op_get_this_binding (frame_ctx_p->lex_env_p);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n continue;\n }\n case VM_OC_OBJECT_LITERAL_HOME_ENV:\n {\n if (opcode == CBC_EXT_PUSH_OBJECT_SUPER_ENVIRONMENT)\n {\n ecma_value_t obj_value = stack_top_p[-1];\n ecma_object_t *obj_env_p = ecma_create_lex_env_class (frame_ctx_p->lex_env_p, 0);\n\n ECMA_SET_NON_NULL_POINTER (obj_env_p->u1.bound_object_cp, ecma_get_object_from_value (obj_value));\n stack_top_p[-1] = ecma_make_object_value (obj_env_p);\n *stack_top_p++ = obj_value;\n }\n else\n {\n JERRY_ASSERT (opcode == CBC_EXT_POP_OBJECT_SUPER_ENVIRONMENT);\n ecma_deref_object (ecma_get_object_from_value (stack_top_p[-2]));\n stack_top_p[-2] = stack_top_p[-1];\n stack_top_p--;\n }\n continue;\n }\n case VM_OC_SET_HOME_OBJECT:\n {\n int offset = opcode == CBC_EXT_OBJECT_LITERAL_SET_HOME_OBJECT_COMPUTED ? -1 : 0;\n opfunc_set_home_object (ecma_get_object_from_value (stack_top_p[-1]),\n ecma_get_object_from_value (stack_top_p[-3 + offset]));\n continue;\n }\n case VM_OC_SUPER_REFERENCE:\n {\n result = opfunc_form_super_reference (&stack_top_p, frame_ctx_p, left_value, opcode);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n goto free_left_value;\n }\n case VM_OC_SET_FUNCTION_NAME:\n {\n char *prefix_p = NULL;\n lit_utf8_size_t prefix_size = 0;\n\n if (opcode != CBC_EXT_SET_FUNCTION_NAME)\n {\n ecma_value_t prop_name_value;\n\n if (opcode == CBC_EXT_SET_CLASS_NAME)\n {\n uint16_t literal_index;\n READ_LITERAL_INDEX (literal_index);\n prop_name_value = literal_start_p[literal_index];\n }\n else\n {\n prop_name_value = stack_top_p[-2];\n }\n\n ecma_string_t *prop_name_p = ecma_op_to_property_key (prop_name_value);\n\n if (JERRY_UNLIKELY (prop_name_p == NULL))\n {\n result = ECMA_VALUE_ERROR;\n goto error;\n }\n\n left_value = ecma_make_prop_name_value (prop_name_p);\n\n if (opcode != CBC_EXT_SET_CLASS_NAME)\n {\n ecma_ref_ecma_string (prop_name_p);\n ecma_free_value (stack_top_p[-2]);\n stack_top_p[-2] = left_value;\n }\n\n if (opcode == CBC_EXT_SET_COMPUTED_GETTER_NAME || opcode == CBC_EXT_SET_COMPUTED_SETTER_NAME)\n {\n prefix_p = (opcode == CBC_EXT_SET_COMPUTED_GETTER_NAME) ? \"get \" : \"set \";\n prefix_size = 4;\n }\n }\n\n ecma_object_t *func_obj_p = ecma_get_object_from_value (stack_top_p[-1]);\n\n if (ecma_find_named_property (func_obj_p, ecma_get_magic_string (LIT_MAGIC_STRING_NAME)) != NULL)\n {\n ecma_free_value (left_value);\n continue;\n }\n\n ecma_property_value_t *value_p;\n value_p = ecma_create_named_data_property (func_obj_p,\n ecma_get_magic_string (LIT_MAGIC_STRING_NAME),\n ECMA_PROPERTY_FLAG_CONFIGURABLE,\n NULL);\n\n if (ecma_get_object_type (func_obj_p) == ECMA_OBJECT_TYPE_FUNCTION)\n {\n ECMA_SET_SECOND_BIT_TO_POINTER_TAG (((ecma_extended_object_t *) func_obj_p)->u.function.scope_cp);\n }\n\n value_p->value = ecma_op_function_form_name (ecma_get_prop_name_from_value (left_value),\n prefix_p,\n prefix_size);\n ecma_free_value (left_value);\n continue;\n }\n case VM_OC_PUSH_SPREAD_ELEMENT:\n {\n *stack_top_p++ = ECMA_VALUE_SPREAD_ELEMENT;\n continue;\n }\n case VM_OC_PUSH_REST_OBJECT:\n {\n vm_frame_ctx_shared_t *shared_p = frame_ctx_p->shared_p;\n\n JERRY_ASSERT (shared_p->status_flags & VM_FRAME_CTX_SHARED_HAS_ARG_LIST);\n\n const ecma_value_t *arg_list_p = ((vm_frame_ctx_shared_args_t *) shared_p)->arg_list_p;\n uint32_t arg_list_len = ((vm_frame_ctx_shared_args_t *) shared_p)->arg_list_len;\n uint16_t argument_end;\n\n if (bytecode_header_p->status_flags & CBC_CODE_FLAGS_UINT16_ARGUMENTS)\n {\n argument_end = ((cbc_uint16_arguments_t *) bytecode_header_p)->argument_end;\n }\n else\n {\n argument_end = ((cbc_uint8_arguments_t *) bytecode_header_p)->argument_end;\n }\n\n if (arg_list_len < argument_end)\n {\n arg_list_len = argument_end;\n }\n\n result = ecma_op_new_array_object_from_buffer (arg_list_p + argument_end,\n arg_list_len - argument_end);\n\n JERRY_ASSERT (!ECMA_IS_VALUE_ERROR (result));\n *stack_top_p++ = result;\n continue;\n }\n case VM_OC_ITERATOR_CONTEXT_CREATE:\n {\n result = ecma_op_get_iterator (stack_top_p[-1], ECMA_VALUE_SYNC_ITERATOR, &left_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n uint32_t context_size = (uint32_t) (stack_top_p\n + PARSER_ITERATOR_CONTEXT_STACK_ALLOCATION\n - VM_LAST_CONTEXT_END ());\n stack_top_p += PARSER_ITERATOR_CONTEXT_STACK_ALLOCATION;\n VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, context_size);\n\n stack_top_p[-1] = VM_CREATE_CONTEXT (VM_CONTEXT_ITERATOR, context_size) | VM_CONTEXT_CLOSE_ITERATOR;\n stack_top_p[-2] = result;\n stack_top_p[-3] = left_value;\n\n continue;\n }\n case VM_OC_ITERATOR_STEP:\n {\n ecma_value_t *last_context_end_p = VM_LAST_CONTEXT_END ();\n\n ecma_value_t iterator = last_context_end_p[-2];\n ecma_value_t next_method = last_context_end_p[-3];\n\n result = ecma_op_iterator_step (iterator, next_method);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n last_context_end_p[-1] &= (uint32_t) ~VM_CONTEXT_CLOSE_ITERATOR;\n goto error;\n }\n\n ecma_value_t value = ECMA_VALUE_UNDEFINED;\n\n if (!ecma_is_value_false (result))\n {\n value = ecma_op_iterator_value (result);\n ecma_free_value (result);\n\n if (ECMA_IS_VALUE_ERROR (value))\n {\n last_context_end_p[-1] &= (uint32_t) ~VM_CONTEXT_CLOSE_ITERATOR;\n result = value;\n goto error;\n }\n }\n else\n {\n last_context_end_p[-1] &= (uint32_t) ~VM_CONTEXT_CLOSE_ITERATOR;\n }\n\n *stack_top_p++ = value;\n continue;\n }\n case VM_OC_ITERATOR_CONTEXT_END:\n {\n JERRY_ASSERT (VM_LAST_CONTEXT_END () == stack_top_p);\n\n if (stack_top_p[-1] & VM_CONTEXT_CLOSE_ITERATOR)\n {\n stack_top_p[-1] &= (uint32_t) ~VM_CONTEXT_CLOSE_ITERATOR;\n result = ecma_op_iterator_close (stack_top_p[-2]);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n }\n\n stack_top_p = vm_stack_context_abort_variable_length (frame_ctx_p,\n stack_top_p,\n PARSER_ITERATOR_CONTEXT_STACK_ALLOCATION);\n continue;\n }\n case VM_OC_DEFAULT_INITIALIZER:\n {\n JERRY_ASSERT (stack_top_p > VM_GET_REGISTERS (frame_ctx_p) + register_end);\n\n if (stack_top_p[-1] != ECMA_VALUE_UNDEFINED)\n {\n byte_code_p = byte_code_start_p + branch_offset;\n continue;\n }\n\n stack_top_p--;\n continue;\n }\n case VM_OC_REST_INITIALIZER:\n {\n ecma_object_t *array_p = ecma_op_new_array_object (0);\n JERRY_ASSERT (ecma_op_object_is_fast_array (array_p));\n\n ecma_value_t *last_context_end_p = VM_LAST_CONTEXT_END ();\n ecma_value_t iterator = last_context_end_p[-2];\n ecma_value_t next_method = last_context_end_p[-3];\n uint32_t index = 0;\n\n while (true)\n {\n result = ecma_op_iterator_step (iterator, next_method);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n last_context_end_p[-1] &= (uint32_t) ~VM_CONTEXT_CLOSE_ITERATOR;\n ecma_deref_object (array_p);\n goto error;\n }\n\n if (ecma_is_value_false (result))\n {\n last_context_end_p[-1] &= (uint32_t) ~VM_CONTEXT_CLOSE_ITERATOR;\n break;\n }\n\n ecma_value_t value = ecma_op_iterator_value (result);\n ecma_free_value (result);\n\n if (ECMA_IS_VALUE_ERROR (value))\n {\n ecma_deref_object (array_p);\n result = value;\n goto error;\n }\n\n bool set_result = ecma_fast_array_set_property (array_p, index++, value);\n JERRY_ASSERT (set_result);\n ecma_free_value (value);\n }\n\n *stack_top_p++ = ecma_make_object_value (array_p);\n continue;\n }\n case VM_OC_OBJ_INIT_CONTEXT_CREATE:\n {\n left_value = stack_top_p[-1];\n vm_stack_context_type_t context_type = VM_CONTEXT_OBJ_INIT;\n uint32_t context_stack_allocation = PARSER_OBJ_INIT_CONTEXT_STACK_ALLOCATION;\n\n if (opcode == CBC_EXT_OBJ_INIT_REST_CONTEXT_CREATE)\n {\n context_type = VM_CONTEXT_OBJ_INIT_REST;\n context_stack_allocation = PARSER_OBJ_INIT_REST_CONTEXT_STACK_ALLOCATION;\n }\n\n uint32_t context_size = (uint32_t) (stack_top_p + context_stack_allocation - VM_LAST_CONTEXT_END ());\n stack_top_p += context_stack_allocation;\n VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, context_size);\n\n stack_top_p[-1] = VM_CREATE_CONTEXT (context_type, context_size);\n stack_top_p[-2] = left_value;\n\n if (context_type == VM_CONTEXT_OBJ_INIT_REST)\n {\n stack_top_p[-3] = ecma_make_object_value (ecma_op_new_array_object (0));\n }\n continue;\n }\n case VM_OC_OBJ_INIT_CONTEXT_END:\n {\n JERRY_ASSERT (stack_top_p == VM_LAST_CONTEXT_END ());\n\n uint32_t context_stack_allocation = PARSER_OBJ_INIT_CONTEXT_STACK_ALLOCATION;\n\n if (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_OBJ_INIT_REST)\n {\n context_stack_allocation = PARSER_OBJ_INIT_REST_CONTEXT_STACK_ALLOCATION;\n }\n\n stack_top_p = vm_stack_context_abort_variable_length (frame_ctx_p,\n stack_top_p,\n context_stack_allocation);\n continue;\n }\n case VM_OC_OBJ_INIT_PUSH_REST:\n {\n ecma_value_t *last_context_end_p = VM_LAST_CONTEXT_END ();\n if (!ecma_op_require_object_coercible (last_context_end_p[-2]))\n {\n result = ECMA_VALUE_ERROR;\n goto error;\n }\n\n ecma_object_t *prototype_p = ecma_builtin_get (ECMA_BUILTIN_ID_OBJECT_PROTOTYPE);\n ecma_object_t *result_object_p = ecma_create_object (prototype_p, 0, ECMA_OBJECT_TYPE_GENERAL);\n\n left_value = ecma_make_object_value (result_object_p);\n result = opfunc_copy_data_properties (left_value, last_context_end_p[-2], last_context_end_p[-3]);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n ecma_free_value (last_context_end_p[-3]);\n last_context_end_p[-3] = last_context_end_p[-2];\n last_context_end_p[-2] = ECMA_VALUE_UNDEFINED;\n\n *stack_top_p++ = left_value;\n continue;\n }\n case VM_OC_INITIALIZER_PUSH_NAME:\n {\n if (JERRY_UNLIKELY (!ecma_is_value_prop_name (left_value)))\n {\n ecma_string_t *property_key = ecma_op_to_property_key (left_value);\n\n if (property_key == NULL)\n {\n result = ECMA_VALUE_ERROR;\n goto error;\n }\n\n ecma_free_value (left_value);\n left_value = ecma_make_string_value (property_key);\n }\n\n ecma_value_t *last_context_end_p = VM_LAST_CONTEXT_END ();\n ecma_object_t *array_obj_p = ecma_get_object_from_value (last_context_end_p[-3]);\n JERRY_ASSERT (ecma_get_object_type (array_obj_p) == ECMA_OBJECT_TYPE_ARRAY);\n\n ecma_extended_object_t *ext_array_obj_p = (ecma_extended_object_t *) array_obj_p;\n ecma_fast_array_set_property (array_obj_p, ext_array_obj_p->u.array.length, left_value);\n /* FALLTHRU */\n }\n case VM_OC_INITIALIZER_PUSH_PROP:\n {\n ecma_value_t *last_context_end_p = VM_LAST_CONTEXT_END ();\n ecma_value_t base = last_context_end_p[-2];\n\n if (opcode == CBC_EXT_INITIALIZER_PUSH_PROP)\n {\n left_value = *last_context_end_p++;\n while (last_context_end_p < stack_top_p)\n {\n last_context_end_p[-1] = *last_context_end_p;\n last_context_end_p++;\n }\n stack_top_p--;\n }\n\n result = vm_op_get_value (base, left_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n goto free_left_value;\n }\n case VM_OC_SPREAD_ARGUMENTS:\n {\n uint8_t arguments_list_len = *byte_code_p++;\n stack_top_p -= arguments_list_len;\n\n ecma_collection_t *arguments_p = opfunc_spread_arguments (stack_top_p, arguments_list_len);\n\n if (JERRY_UNLIKELY (arguments_p == NULL))\n {\n result = ECMA_VALUE_ERROR;\n goto error;\n }\n\n stack_top_p++;\n ECMA_SET_INTERNAL_VALUE_POINTER (stack_top_p[-1], arguments_p);\n\n frame_ctx_p->call_operation = VM_EXEC_SPREAD_OP;\n frame_ctx_p->byte_code_p = byte_code_start_p;\n frame_ctx_p->stack_top_p = stack_top_p;\n return ECMA_VALUE_UNDEFINED;\n }\n case VM_OC_CREATE_GENERATOR:\n {\n frame_ctx_p->call_operation = VM_EXEC_RETURN;\n frame_ctx_p->byte_code_p = byte_code_p;\n frame_ctx_p->stack_top_p = stack_top_p;\n\n vm_executable_object_t *executable_object_p;\n executable_object_p = opfunc_create_executable_object (frame_ctx_p, VM_CREATE_EXECUTABLE_OBJECT_GENERATOR);\n\n return ecma_make_object_value ((ecma_object_t *) executable_object_p);\n }\n case VM_OC_YIELD:\n {\n frame_ctx_p->call_operation = VM_EXEC_RETURN;\n frame_ctx_p->byte_code_p = byte_code_p;\n frame_ctx_p->stack_top_p = --stack_top_p;\n return *stack_top_p;\n }\n case VM_OC_ASYNC_YIELD:\n {\n ecma_extended_object_t *async_generator_object_p = VM_GET_EXECUTABLE_OBJECT (frame_ctx_p);\n\n opfunc_async_generator_yield (async_generator_object_p, stack_top_p[-1]);\n\n frame_ctx_p->call_operation = VM_EXEC_RETURN;\n frame_ctx_p->byte_code_p = byte_code_p;\n frame_ctx_p->stack_top_p = --stack_top_p;\n return ECMA_VALUE_UNDEFINED;\n }\n case VM_OC_ASYNC_YIELD_ITERATOR:\n {\n ecma_extended_object_t *async_generator_object_p = VM_GET_EXECUTABLE_OBJECT (frame_ctx_p);\n\n JERRY_ASSERT (!(async_generator_object_p->u.cls.u2.executable_obj_flags\n & ECMA_EXECUTABLE_OBJECT_DO_AWAIT_OR_YIELD));\n\n /* Byte code is executed at the first time. */\n left_value = stack_top_p[-1];\n result = ecma_op_get_iterator (left_value, ECMA_VALUE_ASYNC_ITERATOR, stack_top_p - 1);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n ecma_free_value (left_value);\n left_value = result;\n result = ecma_op_iterator_next (left_value, stack_top_p[-1], ECMA_VALUE_UNDEFINED);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n result = ecma_promise_async_await (async_generator_object_p, result);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n async_generator_object_p->u.cls.u2.executable_obj_flags |= ECMA_EXECUTABLE_OBJECT_DO_AWAIT_OR_YIELD;\n *VM_GET_EXECUTABLE_ITERATOR (frame_ctx_p) = left_value;\n\n frame_ctx_p->call_operation = VM_EXEC_RETURN;\n frame_ctx_p->byte_code_p = byte_code_p;\n frame_ctx_p->stack_top_p = stack_top_p;\n return ECMA_VALUE_UNDEFINED;\n }\n case VM_OC_AWAIT:\n {\n if (JERRY_UNLIKELY (!(frame_ctx_p->shared_p->status_flags & VM_FRAME_CTX_SHARED_EXECUTABLE)))\n {\n frame_ctx_p->call_operation = VM_EXEC_RETURN;\n frame_ctx_p->byte_code_p = byte_code_p;\n frame_ctx_p->stack_top_p = --stack_top_p;\n\n result = opfunc_async_create_and_await (frame_ctx_p, *stack_top_p, 0);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n return result;\n }\n /* FALLTHRU */\n }\n case VM_OC_GENERATOR_AWAIT:\n {\n ecma_extended_object_t *async_generator_object_p = VM_GET_EXECUTABLE_OBJECT (frame_ctx_p);\n\n result = ecma_promise_async_await (async_generator_object_p, *(--stack_top_p));\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n frame_ctx_p->call_operation = VM_EXEC_RETURN;\n frame_ctx_p->byte_code_p = byte_code_p;\n frame_ctx_p->stack_top_p = stack_top_p;\n return ECMA_VALUE_UNDEFINED;\n }\n case VM_OC_EXT_RETURN:\n {\n result = left_value;\n left_value = ECMA_VALUE_UNDEFINED;\n\n ecma_value_t *stack_bottom_p = VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth;\n\n while (stack_top_p > stack_bottom_p)\n {\n ecma_fast_free_value (*(--stack_top_p));\n }\n\n goto error;\n }\n case VM_OC_ASYNC_EXIT:\n {\n JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p);\n\n if (!(frame_ctx_p->shared_p->status_flags & VM_FRAME_CTX_SHARED_EXECUTABLE))\n {\n result = ecma_op_create_promise_object (ECMA_VALUE_EMPTY, ECMA_VALUE_UNDEFINED, NULL);\n }\n else\n {\n result = *VM_GET_EXECUTABLE_ITERATOR (frame_ctx_p);\n *VM_GET_EXECUTABLE_ITERATOR (frame_ctx_p) = ECMA_VALUE_UNDEFINED;\n }\n\n vm_stack_context_type_t context_type = VM_GET_CONTEXT_TYPE (stack_top_p[-1]);\n\n if (context_type == VM_CONTEXT_TRY)\n {\n JERRY_ASSERT (frame_ctx_p->context_depth == PARSER_TRY_CONTEXT_STACK_ALLOCATION);\n left_value = ECMA_VALUE_UNDEFINED;\n }\n else\n {\n JERRY_ASSERT (frame_ctx_p->context_depth == PARSER_FINALLY_CONTEXT_STACK_ALLOCATION);\n left_value = stack_top_p[-2];\n }\n\n if (context_type == VM_CONTEXT_FINALLY_THROW)\n {\n ecma_reject_promise (result, left_value);\n }\n else\n {\n JERRY_ASSERT (context_type == VM_CONTEXT_TRY || context_type == VM_CONTEXT_FINALLY_RETURN);\n ecma_fulfill_promise (result, left_value);\n }\n\n ecma_free_value (left_value);\n\n frame_ctx_p->context_depth = 0;\n frame_ctx_p->call_operation = VM_NO_EXEC_OP;\n return result;\n }\n case VM_OC_STRING_CONCAT:\n {\n ecma_string_t *left_str_p = ecma_op_to_string (left_value);\n\n if (JERRY_UNLIKELY (left_str_p == NULL))\n {\n result = ECMA_VALUE_ERROR;\n goto error;\n }\n ecma_string_t *right_str_p = ecma_op_to_string (right_value);\n\n if (JERRY_UNLIKELY (right_str_p == NULL))\n {\n ecma_deref_ecma_string (left_str_p);\n result = ECMA_VALUE_ERROR;\n goto error;\n }\n\n ecma_string_t *result_str_p = ecma_concat_ecma_strings (left_str_p, right_str_p);\n ecma_deref_ecma_string (right_str_p);\n\n *stack_top_p++ = ecma_make_string_value (result_str_p);\n goto free_both_values;\n }\n case VM_OC_GET_TEMPLATE_OBJECT:\n {\n uint8_t tagged_idx = *byte_code_p++;\n ecma_collection_t *collection_p = ecma_compiled_code_get_tagged_template_collection (bytecode_header_p);\n JERRY_ASSERT (tagged_idx < collection_p->item_count);\n\n *stack_top_p++ = ecma_copy_value (collection_p->buffer_p[tagged_idx]);\n continue;\n }\n case VM_OC_PUSH_NEW_TARGET:\n {\n ecma_object_t *new_target_object_p = JERRY_CONTEXT (current_new_target_p);\n if (new_target_object_p == NULL)\n {\n *stack_top_p++ = ECMA_VALUE_UNDEFINED;\n }\n else\n {\n ecma_ref_object (new_target_object_p);\n *stack_top_p++ = ecma_make_object_value (new_target_object_p);\n }\n continue;\n }\n case VM_OC_REQUIRE_OBJECT_COERCIBLE:\n {\n if (!ecma_op_require_object_coercible (stack_top_p[-1]))\n {\n result = ECMA_VALUE_ERROR;\n goto error;\n }\n continue;\n }\n case VM_OC_ASSIGN_SUPER:\n {\n result = opfunc_assign_super_reference (&stack_top_p, frame_ctx_p, opcode_data);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n continue;\n }\n#endif /* JERRY_ESNEXT */\n case VM_OC_PUSH_ELISON:\n {\n *stack_top_p++ = ECMA_VALUE_ARRAY_HOLE;\n continue;\n }\n case VM_OC_APPEND_ARRAY:\n {\n uint16_t values_length = *byte_code_p++;\n stack_top_p -= values_length;\n\n#if JERRY_ESNEXT\n if (*byte_code_start_p == CBC_EXT_OPCODE)\n {\n values_length = (uint16_t) (values_length | OPFUNC_HAS_SPREAD_ELEMENT);\n }\n#endif /* JERRY_ESNEXT */\n result = opfunc_append_array (stack_top_p, values_length);\n\n#if JERRY_ESNEXT\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n#else /* !JERRY_ESNEXT */\n JERRY_ASSERT (ecma_is_value_empty (result));\n#endif /* JERRY_ESNEXT */\n continue;\n }\n case VM_OC_IDENT_REFERENCE:\n {\n uint16_t literal_index;\n\n READ_LITERAL_INDEX (literal_index);\n\n JERRY_ASSERT (literal_index < ident_end);\n\n if (literal_index < register_end)\n {\n *stack_top_p++ = ECMA_VALUE_REGISTER_REF;\n *stack_top_p++ = ecma_make_integer_value (literal_index);\n *stack_top_p++ = ecma_fast_copy_value (VM_GET_REGISTER (frame_ctx_p, literal_index));\n }\n else\n {\n ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]);\n\n ecma_object_t *ref_base_lex_env_p;\n\n result = ecma_op_get_value_lex_env_base (frame_ctx_p->lex_env_p,\n &ref_base_lex_env_p,\n name_p);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n ecma_ref_object (ref_base_lex_env_p);\n ecma_ref_ecma_string (name_p);\n *stack_top_p++ = ecma_make_object_value (ref_base_lex_env_p);\n *stack_top_p++ = ecma_make_string_value (name_p);\n *stack_top_p++ = result;\n }\n continue;\n }\n case VM_OC_PROP_GET:\n {\n result = vm_op_get_value (left_value, right_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n goto free_both_values;\n }\n case VM_OC_PROP_REFERENCE:\n {\n /* Forms with reference requires preserving the base and offset. */\n\n if (opcode == CBC_PUSH_PROP_REFERENCE)\n {\n left_value = stack_top_p[-2];\n right_value = stack_top_p[-1];\n }\n else if (opcode == CBC_PUSH_PROP_LITERAL_REFERENCE)\n {\n *stack_top_p++ = left_value;\n right_value = left_value;\n left_value = stack_top_p[-2];\n }\n else\n {\n JERRY_ASSERT (opcode == CBC_PUSH_PROP_LITERAL_LITERAL_REFERENCE\n || opcode == CBC_PUSH_PROP_THIS_LITERAL_REFERENCE);\n *stack_top_p++ = left_value;\n *stack_top_p++ = right_value;\n }\n /* FALLTHRU */\n }\n case VM_OC_PROP_PRE_INCR:\n case VM_OC_PROP_PRE_DECR:\n case VM_OC_PROP_POST_INCR:\n case VM_OC_PROP_POST_DECR:\n {\n result = vm_op_get_value (left_value,\n right_value);\n\n if (opcode < CBC_PRE_INCR)\n {\n left_value = ECMA_VALUE_UNDEFINED;\n right_value = ECMA_VALUE_UNDEFINED;\n }\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n if (opcode < CBC_PRE_INCR)\n {\n break;\n }\n\n stack_top_p += 2;\n left_value = result;\n right_value = ECMA_VALUE_UNDEFINED;\n /* FALLTHRU */\n }\n case VM_OC_PRE_INCR:\n case VM_OC_PRE_DECR:\n case VM_OC_POST_INCR:\n case VM_OC_POST_DECR:\n {\n uint32_t opcode_flags = VM_OC_GROUP_GET_INDEX (opcode_data) - VM_OC_PROP_PRE_INCR;\n ecma_number_t result_number;\n\n byte_code_p = byte_code_start_p + 1;\n\n if (ecma_is_value_integer_number (left_value))\n {\n result = left_value;\n left_value = ECMA_VALUE_UNDEFINED;\n\n ecma_integer_value_t int_value = (ecma_integer_value_t) result;\n ecma_integer_value_t int_increase = 0;\n\n if (opcode_flags & VM_OC_DECREMENT_OPERATOR_FLAG)\n {\n if (int_value > ECMA_INTEGER_NUMBER_MIN_SHIFTED)\n {\n int_increase = -(1 << ECMA_DIRECT_SHIFT);\n }\n }\n else if (int_value < ECMA_INTEGER_NUMBER_MAX_SHIFTED)\n {\n int_increase = 1 << ECMA_DIRECT_SHIFT;\n }\n\n if (JERRY_LIKELY (int_increase != 0))\n {\n /* Postfix operators require the unmodifed number value. */\n if (opcode_flags & VM_OC_POST_INCR_DECR_OPERATOR_FLAG)\n {\n POST_INCREASE_DECREASE_PUT_RESULT (result);\n }\n\n result = (ecma_value_t) (int_value + int_increase);\n break;\n }\n result_number = (ecma_number_t) ecma_get_integer_from_value (result);\n }\n else if (ecma_is_value_float_number (left_value))\n {\n result = left_value;\n left_value = ECMA_VALUE_UNDEFINED;\n result_number = ecma_get_number_from_value (result);\n }\n else\n {\n result = ecma_op_to_numeric (left_value, &result_number, ECMA_TO_NUMERIC_ALLOW_BIGINT);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n ecma_free_value (left_value);\n left_value = ECMA_VALUE_UNDEFINED;\n\n#if JERRY_BUILTIN_BIGINT\n if (JERRY_UNLIKELY (ecma_is_value_bigint (result)))\n {\n ecma_bigint_unary_operation_type operation_type = ECMA_BIGINT_UNARY_INCREASE;\n\n if (opcode_flags & VM_OC_DECREMENT_OPERATOR_FLAG)\n {\n operation_type = ECMA_BIGINT_UNARY_DECREASE;\n }\n\n /* Postfix operators require the unmodifed number value. */\n if (opcode_flags & VM_OC_POST_INCR_DECR_OPERATOR_FLAG)\n {\n POST_INCREASE_DECREASE_PUT_RESULT (result);\n\n result = ecma_bigint_unary (result, operation_type);\n }\n else\n {\n ecma_value_t original_value = result;\n result = ecma_bigint_unary (original_value, operation_type);\n ecma_free_value (original_value);\n }\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n break;\n }\n#endif /* JERRY_BUILTIN_BIGINT */\n\n result = ecma_make_number_value (result_number);\n }\n\n ecma_number_t increase = ECMA_NUMBER_ONE;\n\n if (opcode_flags & VM_OC_DECREMENT_OPERATOR_FLAG)\n {\n /* For decrement operators */\n increase = ECMA_NUMBER_MINUS_ONE;\n }\n\n /* Postfix operators require the unmodifed number value. */\n if (opcode_flags & VM_OC_POST_INCR_DECR_OPERATOR_FLAG)\n {\n POST_INCREASE_DECREASE_PUT_RESULT (result);\n\n result = ecma_make_number_value (result_number + increase);\n break;\n }\n\n if (ecma_is_value_integer_number (result))\n {\n result = ecma_make_number_value (result_number + increase);\n }\n else\n {\n result = ecma_update_float_number (result, result_number + increase);\n }\n break;\n }\n case VM_OC_ASSIGN:\n {\n result = left_value;\n left_value = ECMA_VALUE_UNDEFINED;\n break;\n }\n case VM_OC_MOV_IDENT:\n {\n uint32_t literal_index;\n\n READ_LITERAL_INDEX (literal_index);\n\n JERRY_ASSERT (literal_index < register_end);\n JERRY_ASSERT (!(opcode_data & (VM_OC_PUT_STACK | VM_OC_PUT_BLOCK)));\n\n ecma_fast_free_value (VM_GET_REGISTER (frame_ctx_p, literal_index));\n VM_GET_REGISTER (frame_ctx_p, literal_index) = left_value;\n continue;\n }\n case VM_OC_ASSIGN_PROP:\n {\n result = stack_top_p[-1];\n stack_top_p[-1] = left_value;\n left_value = ECMA_VALUE_UNDEFINED;\n break;\n }\n case VM_OC_ASSIGN_PROP_THIS:\n {\n result = stack_top_p[-1];\n stack_top_p[-1] = ecma_copy_value (frame_ctx_p->this_binding);\n *stack_top_p++ = left_value;\n left_value = ECMA_VALUE_UNDEFINED;\n break;\n }\n case VM_OC_RETURN_FUNCTION_END:\n {\n if (CBC_FUNCTION_GET_TYPE (bytecode_header_p->status_flags) == CBC_FUNCTION_SCRIPT)\n {\n result = VM_GET_REGISTER (frame_ctx_p, 0);\n VM_GET_REGISTERS (frame_ctx_p)[0] = ECMA_VALUE_UNDEFINED;\n }\n else\n {\n result = ECMA_VALUE_UNDEFINED;\n }\n\n goto error;\n }\n case VM_OC_RETURN:\n {\n JERRY_ASSERT (opcode == CBC_RETURN\n || opcode == CBC_RETURN_WITH_LITERAL);\n\n result = left_value;\n left_value = ECMA_VALUE_UNDEFINED;\n goto error;\n }\n case VM_OC_THROW:\n {\n jcontext_raise_exception (left_value);\n\n result = ECMA_VALUE_ERROR;\n left_value = ECMA_VALUE_UNDEFINED;\n goto error;\n }\n case VM_OC_THROW_REFERENCE_ERROR:\n {\n result = ecma_raise_reference_error (ECMA_ERR_MSG (\"Undefined reference\"));\n goto error;\n }\n case VM_OC_EVAL:\n {\n JERRY_CONTEXT (status_flags) |= ECMA_STATUS_DIRECT_EVAL;\n JERRY_ASSERT ((*byte_code_p >= CBC_CALL && *byte_code_p <= CBC_CALL2_PROP_BLOCK)\n || (*byte_code_p == CBC_EXT_OPCODE\n && byte_code_p[1] >= CBC_EXT_SPREAD_CALL\n && byte_code_p[1] <= CBC_EXT_SPREAD_CALL_PROP_BLOCK));\n continue;\n }\n case VM_OC_CALL:\n {\n frame_ctx_p->call_operation = VM_EXEC_CALL;\n frame_ctx_p->byte_code_p = byte_code_start_p;\n frame_ctx_p->stack_top_p = stack_top_p;\n return ECMA_VALUE_UNDEFINED;\n }\n case VM_OC_NEW:\n {\n frame_ctx_p->call_operation = VM_EXEC_CONSTRUCT;\n frame_ctx_p->byte_code_p = byte_code_start_p;\n frame_ctx_p->stack_top_p = stack_top_p;\n return ECMA_VALUE_UNDEFINED;\n }\n case VM_OC_ERROR:\n {\n JERRY_ASSERT (frame_ctx_p->byte_code_p[1] == CBC_EXT_ERROR);\n#if JERRY_DEBUGGER\n frame_ctx_p->byte_code_p = JERRY_CONTEXT (debugger_exception_byte_code_p);\n#endif /* JERRY_DEBUGGER */\n\n result = ECMA_VALUE_ERROR;\n goto error;\n }\n case VM_OC_RESOLVE_BASE_FOR_CALL:\n {\n ecma_value_t this_value = stack_top_p[-3];\n\n if (this_value == ECMA_VALUE_REGISTER_REF)\n {\n /* Lexical environment cannot be 'this' value. */\n stack_top_p[-2] = ECMA_VALUE_UNDEFINED;\n stack_top_p[-3] = ECMA_VALUE_UNDEFINED;\n }\n else if (vm_get_implicit_this_value (&this_value))\n {\n ecma_free_value (stack_top_p[-3]);\n stack_top_p[-3] = this_value;\n }\n\n continue;\n }\n case VM_OC_PROP_DELETE:\n {\n result = vm_op_delete_prop (left_value, right_value, is_strict);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n JERRY_ASSERT (ecma_is_value_boolean (result));\n\n *stack_top_p++ = result;\n goto free_both_values;\n }\n case VM_OC_DELETE:\n {\n uint16_t literal_index;\n\n READ_LITERAL_INDEX (literal_index);\n\n if (literal_index < register_end)\n {\n *stack_top_p++ = ECMA_VALUE_FALSE;\n continue;\n }\n\n result = vm_op_delete_var (literal_start_p[literal_index],\n frame_ctx_p->lex_env_p);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n JERRY_ASSERT (ecma_is_value_boolean (result));\n\n *stack_top_p++ = result;\n continue;\n }\n case VM_OC_JUMP:\n {\n byte_code_p = byte_code_start_p + branch_offset;\n continue;\n }\n case VM_OC_BRANCH_IF_STRICT_EQUAL:\n {\n ecma_value_t value = *(--stack_top_p);\n\n JERRY_ASSERT (stack_top_p > VM_GET_REGISTERS (frame_ctx_p) + register_end);\n\n if (ecma_op_strict_equality_compare (value, stack_top_p[-1]))\n {\n byte_code_p = byte_code_start_p + branch_offset;\n ecma_free_value (*--stack_top_p);\n }\n ecma_free_value (value);\n continue;\n }\n case VM_OC_BRANCH_IF_TRUE:\n case VM_OC_BRANCH_IF_FALSE:\n case VM_OC_BRANCH_IF_LOGICAL_TRUE:\n case VM_OC_BRANCH_IF_LOGICAL_FALSE:\n {\n uint32_t opcode_flags = VM_OC_GROUP_GET_INDEX (opcode_data) - VM_OC_BRANCH_IF_TRUE;\n ecma_value_t value = *(--stack_top_p);\n\n bool boolean_value = ecma_op_to_boolean (value);\n\n if (opcode_flags & VM_OC_BRANCH_IF_FALSE_FLAG)\n {\n boolean_value = !boolean_value;\n }\n\n if (boolean_value)\n {\n byte_code_p = byte_code_start_p + branch_offset;\n if (opcode_flags & VM_OC_LOGICAL_BRANCH_FLAG)\n {\n /* \"Push\" the value back to the stack. */\n ++stack_top_p;\n continue;\n }\n }\n\n ecma_fast_free_value (value);\n continue;\n }\n#if JERRY_ESNEXT\n case VM_OC_BRANCH_IF_NULLISH:\n {\n left_value = stack_top_p[-1];\n\n if (!ecma_is_value_null (left_value) && !ecma_is_value_undefined (left_value))\n {\n byte_code_p = byte_code_start_p + branch_offset;\n continue;\n }\n --stack_top_p;\n continue;\n }\n#endif /* JERRY_ESNEXT */\n case VM_OC_PLUS:\n case VM_OC_MINUS:\n {\n result = opfunc_unary_operation (left_value, VM_OC_GROUP_GET_INDEX (opcode_data) == VM_OC_PLUS);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n goto free_left_value;\n }\n case VM_OC_NOT:\n {\n *stack_top_p++ = ecma_make_boolean_value (!ecma_op_to_boolean (left_value));\n JERRY_ASSERT (ecma_is_value_boolean (stack_top_p[-1]));\n goto free_left_value;\n }\n case VM_OC_BIT_NOT:\n {\n JERRY_STATIC_ASSERT (ECMA_DIRECT_TYPE_MASK == ((1 << ECMA_DIRECT_SHIFT) - 1),\n direct_type_mask_must_fill_all_bits_before_the_value_starts);\n\n if (ecma_is_value_integer_number (left_value))\n {\n *stack_top_p++ = (~ECMA_DIRECT_TYPE_MASK) ^ left_value;\n goto free_left_value;\n }\n\n result = do_number_bitwise_not (left_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n goto free_left_value;\n }\n case VM_OC_VOID:\n {\n *stack_top_p++ = ECMA_VALUE_UNDEFINED;\n goto free_left_value;\n }\n case VM_OC_TYPEOF_IDENT:\n {\n uint16_t literal_index;\n\n READ_LITERAL_INDEX (literal_index);\n\n JERRY_ASSERT (literal_index < ident_end);\n\n if (literal_index < register_end)\n {\n left_value = ecma_copy_value (VM_GET_REGISTER (frame_ctx_p, literal_index));\n }\n else\n {\n ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]);\n\n ecma_object_t *ref_base_lex_env_p;\n\n result = ecma_op_get_value_lex_env_base (frame_ctx_p->lex_env_p,\n &ref_base_lex_env_p,\n name_p);\n\n if (ref_base_lex_env_p == NULL)\n {\n jcontext_release_exception ();\n result = ECMA_VALUE_UNDEFINED;\n }\n else if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n left_value = result;\n }\n /* FALLTHRU */\n }\n case VM_OC_TYPEOF:\n {\n result = opfunc_typeof (left_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n goto free_left_value;\n }\n case VM_OC_ADD:\n {\n if (ecma_are_values_integer_numbers (left_value, right_value))\n {\n ecma_integer_value_t left_integer = ecma_get_integer_from_value (left_value);\n ecma_integer_value_t right_integer = ecma_get_integer_from_value (right_value);\n *stack_top_p++ = ecma_make_int32_value ((int32_t) (left_integer + right_integer));\n continue;\n }\n\n if (ecma_is_value_float_number (left_value)\n && ecma_is_value_number (right_value))\n {\n ecma_number_t new_value = (ecma_get_float_from_value (left_value) +\n ecma_get_number_from_value (right_value));\n\n *stack_top_p++ = ecma_update_float_number (left_value, new_value);\n ecma_free_number (right_value);\n continue;\n }\n\n if (ecma_is_value_float_number (right_value)\n && ecma_is_value_integer_number (left_value))\n {\n ecma_number_t new_value = ((ecma_number_t) ecma_get_integer_from_value (left_value) +\n ecma_get_float_from_value (right_value));\n\n *stack_top_p++ = ecma_update_float_number (right_value, new_value);\n continue;\n }\n\n result = opfunc_addition (left_value, right_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n goto free_both_values;\n }\n case VM_OC_SUB:\n {\n JERRY_STATIC_ASSERT (ECMA_INTEGER_NUMBER_MAX * 2 <= INT32_MAX\n && ECMA_INTEGER_NUMBER_MIN * 2 >= INT32_MIN,\n doubled_ecma_numbers_must_fit_into_int32_range);\n\n JERRY_ASSERT (!ECMA_IS_VALUE_ERROR (left_value)\n && !ECMA_IS_VALUE_ERROR (right_value));\n\n if (ecma_are_values_integer_numbers (left_value, right_value))\n {\n ecma_integer_value_t left_integer = ecma_get_integer_from_value (left_value);\n ecma_integer_value_t right_integer = ecma_get_integer_from_value (right_value);\n *stack_top_p++ = ecma_make_int32_value ((int32_t) (left_integer - right_integer));\n continue;\n }\n\n if (ecma_is_value_float_number (left_value)\n && ecma_is_value_number (right_value))\n {\n ecma_number_t new_value = (ecma_get_float_from_value (left_value) -\n ecma_get_number_from_value (right_value));\n\n *stack_top_p++ = ecma_update_float_number (left_value, new_value);\n ecma_free_number (right_value);\n continue;\n }\n\n if (ecma_is_value_float_number (right_value)\n && ecma_is_value_integer_number (left_value))\n {\n ecma_number_t new_value = ((ecma_number_t) ecma_get_integer_from_value (left_value) -\n ecma_get_float_from_value (right_value));\n\n *stack_top_p++ = ecma_update_float_number (right_value, new_value);\n continue;\n }\n\n result = do_number_arithmetic (NUMBER_ARITHMETIC_SUBTRACTION,\n left_value,\n right_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n goto free_both_values;\n }\n case VM_OC_MUL:\n {\n JERRY_ASSERT (!ECMA_IS_VALUE_ERROR (left_value)\n && !ECMA_IS_VALUE_ERROR (right_value));\n\n JERRY_STATIC_ASSERT (ECMA_INTEGER_MULTIPLY_MAX * ECMA_INTEGER_MULTIPLY_MAX <= ECMA_INTEGER_NUMBER_MAX\n && -(ECMA_INTEGER_MULTIPLY_MAX * ECMA_INTEGER_MULTIPLY_MAX) >= ECMA_INTEGER_NUMBER_MIN,\n square_of_integer_multiply_max_must_fit_into_integer_value_range);\n\n if (ecma_are_values_integer_numbers (left_value, right_value))\n {\n ecma_integer_value_t left_integer = ecma_get_integer_from_value (left_value);\n ecma_integer_value_t right_integer = ecma_get_integer_from_value (right_value);\n\n if (-ECMA_INTEGER_MULTIPLY_MAX <= left_integer\n && left_integer <= ECMA_INTEGER_MULTIPLY_MAX\n && -ECMA_INTEGER_MULTIPLY_MAX <= right_integer\n && right_integer <= ECMA_INTEGER_MULTIPLY_MAX\n && left_integer != 0\n && right_integer != 0)\n {\n *stack_top_p++ = ecma_integer_multiply (left_integer, right_integer);\n continue;\n }\n\n ecma_number_t multiply = (ecma_number_t) left_integer * (ecma_number_t) right_integer;\n *stack_top_p++ = ecma_make_number_value (multiply);\n continue;\n }\n\n if (ecma_is_value_float_number (left_value)\n && ecma_is_value_number (right_value))\n {\n ecma_number_t new_value = (ecma_get_float_from_value (left_value) *\n ecma_get_number_from_value (right_value));\n\n *stack_top_p++ = ecma_update_float_number (left_value, new_value);\n ecma_free_number (right_value);\n continue;\n }\n\n if (ecma_is_value_float_number (right_value)\n && ecma_is_value_integer_number (left_value))\n {\n ecma_number_t new_value = ((ecma_number_t) ecma_get_integer_from_value (left_value) *\n ecma_get_float_from_value (right_value));\n\n *stack_top_p++ = ecma_update_float_number (right_value, new_value);\n continue;\n }\n\n result = do_number_arithmetic (NUMBER_ARITHMETIC_MULTIPLICATION,\n left_value,\n right_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n goto free_both_values;\n }\n case VM_OC_DIV:\n {\n JERRY_ASSERT (!ECMA_IS_VALUE_ERROR (left_value)\n && !ECMA_IS_VALUE_ERROR (right_value));\n\n result = do_number_arithmetic (NUMBER_ARITHMETIC_DIVISION,\n left_value,\n right_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n goto free_both_values;\n }\n case VM_OC_MOD:\n {\n JERRY_ASSERT (!ECMA_IS_VALUE_ERROR (left_value)\n && !ECMA_IS_VALUE_ERROR (right_value));\n\n if (ecma_are_values_integer_numbers (left_value, right_value))\n {\n ecma_integer_value_t left_integer = ecma_get_integer_from_value (left_value);\n ecma_integer_value_t right_integer = ecma_get_integer_from_value (right_value);\n\n if (right_integer != 0)\n {\n ecma_integer_value_t mod_result = left_integer % right_integer;\n\n if (mod_result != 0 || left_integer >= 0)\n {\n *stack_top_p++ = ecma_make_integer_value (mod_result);\n continue;\n }\n }\n }\n\n result = do_number_arithmetic (NUMBER_ARITHMETIC_REMAINDER,\n left_value,\n right_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n goto free_both_values;\n }\n#if JERRY_ESNEXT\n case VM_OC_EXP:\n {\n result = do_number_arithmetic (NUMBER_ARITHMETIC_EXPONENTIATION,\n left_value,\n right_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n goto free_both_values;\n }\n#endif /* JERRY_ESNEXT */\n case VM_OC_EQUAL:\n {\n result = opfunc_equality (left_value, right_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n goto free_both_values;\n }\n case VM_OC_NOT_EQUAL:\n {\n result = opfunc_equality (left_value, right_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = ecma_invert_boolean_value (result);\n goto free_both_values;\n }\n case VM_OC_STRICT_EQUAL:\n {\n bool is_equal = ecma_op_strict_equality_compare (left_value, right_value);\n\n result = ecma_make_boolean_value (is_equal);\n\n *stack_top_p++ = result;\n goto free_both_values;\n }\n case VM_OC_STRICT_NOT_EQUAL:\n {\n bool is_equal = ecma_op_strict_equality_compare (left_value, right_value);\n\n result = ecma_make_boolean_value (!is_equal);\n\n *stack_top_p++ = result;\n goto free_both_values;\n }\n case VM_OC_BIT_OR:\n {\n JERRY_STATIC_ASSERT (ECMA_DIRECT_TYPE_MASK == ((1 << ECMA_DIRECT_SHIFT) - 1),\n direct_type_mask_must_fill_all_bits_before_the_value_starts);\n\n if (ecma_are_values_integer_numbers (left_value, right_value))\n {\n *stack_top_p++ = left_value | right_value;\n continue;\n }\n\n result = do_number_bitwise_logic (NUMBER_BITWISE_LOGIC_OR,\n left_value,\n right_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n goto free_both_values;\n }\n case VM_OC_BIT_XOR:\n {\n JERRY_STATIC_ASSERT (ECMA_DIRECT_TYPE_MASK == ((1 << ECMA_DIRECT_SHIFT) - 1),\n direct_type_mask_must_fill_all_bits_before_the_value_starts);\n\n if (ecma_are_values_integer_numbers (left_value, right_value))\n {\n *stack_top_p++ = left_value ^ right_value;\n continue;\n }\n\n result = do_number_bitwise_logic (NUMBER_BITWISE_LOGIC_XOR,\n left_value,\n right_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n goto free_both_values;\n }\n case VM_OC_BIT_AND:\n {\n JERRY_STATIC_ASSERT (ECMA_DIRECT_TYPE_MASK == ((1 << ECMA_DIRECT_SHIFT) - 1),\n direct_type_mask_must_fill_all_bits_before_the_value_starts);\n\n if (ecma_are_values_integer_numbers (left_value, right_value))\n {\n *stack_top_p++ = left_value & right_value;\n continue;\n }\n\n result = do_number_bitwise_logic (NUMBER_BITWISE_LOGIC_AND,\n left_value,\n right_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n goto free_both_values;\n }\n case VM_OC_LEFT_SHIFT:\n {\n JERRY_STATIC_ASSERT (ECMA_DIRECT_TYPE_MASK == ((1 << ECMA_DIRECT_SHIFT) - 1),\n direct_type_mask_must_fill_all_bits_before_the_value_starts);\n\n if (ecma_are_values_integer_numbers (left_value, right_value))\n {\n ecma_integer_value_t left_integer = ecma_get_integer_from_value (left_value);\n ecma_integer_value_t right_integer = ecma_get_integer_from_value (right_value);\n *stack_top_p++ = ecma_make_int32_value ((int32_t) (left_integer << (right_integer & 0x1f)));\n continue;\n }\n\n result = do_number_bitwise_logic (NUMBER_BITWISE_SHIFT_LEFT,\n left_value,\n right_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n goto free_both_values;\n }\n case VM_OC_RIGHT_SHIFT:\n {\n JERRY_STATIC_ASSERT (ECMA_DIRECT_TYPE_MASK == ((1 << ECMA_DIRECT_SHIFT) - 1),\n direct_type_mask_must_fill_all_bits_before_the_value_starts);\n\n if (ecma_are_values_integer_numbers (left_value, right_value))\n {\n ecma_integer_value_t left_integer = ecma_get_integer_from_value (left_value);\n ecma_integer_value_t right_integer = ecma_get_integer_from_value (right_value);\n *stack_top_p++ = ecma_make_integer_value (left_integer >> (right_integer & 0x1f));\n continue;\n }\n\n result = do_number_bitwise_logic (NUMBER_BITWISE_SHIFT_RIGHT,\n left_value,\n right_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n goto free_both_values;\n }\n case VM_OC_UNS_RIGHT_SHIFT:\n {\n JERRY_STATIC_ASSERT (ECMA_DIRECT_TYPE_MASK == ((1 << ECMA_DIRECT_SHIFT) - 1),\n direct_type_mask_must_fill_all_bits_before_the_value_starts);\n\n if (ecma_are_values_integer_numbers (left_value, right_value))\n {\n uint32_t left_uint32 = (uint32_t) ecma_get_integer_from_value (left_value);\n ecma_integer_value_t right_integer = ecma_get_integer_from_value (right_value);\n *stack_top_p++ = ecma_make_uint32_value (left_uint32 >> (right_integer & 0x1f));\n continue;\n }\n\n result = do_number_bitwise_logic (NUMBER_BITWISE_SHIFT_URIGHT,\n left_value,\n right_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n goto free_both_values;\n }\n case VM_OC_LESS:\n {\n if (ecma_are_values_integer_numbers (left_value, right_value))\n {\n bool is_less = (ecma_integer_value_t) left_value < (ecma_integer_value_t) right_value;\n#if !JERRY_VM_EXEC_STOP\n /* This is a lookahead to the next opcode to improve performance.\n * If it is CBC_BRANCH_IF_TRUE_BACKWARD, execute it. */\n if (*byte_code_p <= CBC_BRANCH_IF_TRUE_BACKWARD_3 && *byte_code_p >= CBC_BRANCH_IF_TRUE_BACKWARD)\n {\n byte_code_start_p = byte_code_p++;\n branch_offset_length = CBC_BRANCH_OFFSET_LENGTH (*byte_code_start_p);\n JERRY_ASSERT (branch_offset_length >= 1 && branch_offset_length <= 3);\n\n if (is_less)\n {\n branch_offset = *(byte_code_p++);\n\n if (JERRY_UNLIKELY (branch_offset_length != 1))\n {\n branch_offset <<= 8;\n branch_offset |= *(byte_code_p++);\n if (JERRY_UNLIKELY (branch_offset_length == 3))\n {\n branch_offset <<= 8;\n branch_offset |= *(byte_code_p++);\n }\n }\n\n /* Note: The opcode is a backward branch. */\n byte_code_p = byte_code_start_p - branch_offset;\n }\n else\n {\n byte_code_p += branch_offset_length;\n }\n\n continue;\n }\n#endif /* !JERRY_VM_EXEC_STOP */\n *stack_top_p++ = ecma_make_boolean_value (is_less);\n continue;\n }\n\n if (ecma_is_value_number (left_value) && ecma_is_value_number (right_value))\n {\n ecma_number_t left_number = ecma_get_number_from_value (left_value);\n ecma_number_t right_number = ecma_get_number_from_value (right_value);\n\n *stack_top_p++ = ecma_make_boolean_value (left_number < right_number);\n goto free_both_values;\n }\n\n result = opfunc_relation (left_value, right_value, true, false);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n goto free_both_values;\n }\n case VM_OC_GREATER:\n {\n if (ecma_are_values_integer_numbers (left_value, right_value))\n {\n ecma_integer_value_t left_integer = (ecma_integer_value_t) left_value;\n ecma_integer_value_t right_integer = (ecma_integer_value_t) right_value;\n\n *stack_top_p++ = ecma_make_boolean_value (left_integer > right_integer);\n continue;\n }\n\n if (ecma_is_value_number (left_value) && ecma_is_value_number (right_value))\n {\n ecma_number_t left_number = ecma_get_number_from_value (left_value);\n ecma_number_t right_number = ecma_get_number_from_value (right_value);\n\n *stack_top_p++ = ecma_make_boolean_value (left_number > right_number);\n goto free_both_values;\n }\n\n result = opfunc_relation (left_value, right_value, false, false);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n goto free_both_values;\n }\n case VM_OC_LESS_EQUAL:\n {\n if (ecma_are_values_integer_numbers (left_value, right_value))\n {\n ecma_integer_value_t left_integer = (ecma_integer_value_t) left_value;\n ecma_integer_value_t right_integer = (ecma_integer_value_t) right_value;\n\n *stack_top_p++ = ecma_make_boolean_value (left_integer <= right_integer);\n continue;\n }\n\n if (ecma_is_value_number (left_value) && ecma_is_value_number (right_value))\n {\n ecma_number_t left_number = ecma_get_number_from_value (left_value);\n ecma_number_t right_number = ecma_get_number_from_value (right_value);\n\n *stack_top_p++ = ecma_make_boolean_value (left_number <= right_number);\n goto free_both_values;\n }\n\n result = opfunc_relation (left_value, right_value, false, true);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n goto free_both_values;\n }\n case VM_OC_GREATER_EQUAL:\n {\n if (ecma_are_values_integer_numbers (left_value, right_value))\n {\n ecma_integer_value_t left_integer = (ecma_integer_value_t) left_value;\n ecma_integer_value_t right_integer = (ecma_integer_value_t) right_value;\n\n *stack_top_p++ = ecma_make_boolean_value (left_integer >= right_integer);\n continue;\n }\n\n if (ecma_is_value_number (left_value) && ecma_is_value_number (right_value))\n {\n ecma_number_t left_number = ecma_get_number_from_value (left_value);\n ecma_number_t right_number = ecma_get_number_from_value (right_value);\n\n *stack_top_p++ = ecma_make_boolean_value (left_number >= right_number);\n goto free_both_values;\n }\n\n result = opfunc_relation (left_value, right_value, true, true);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n goto free_both_values;\n }\n case VM_OC_IN:\n {\n result = opfunc_in (left_value, right_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n goto free_both_values;\n }\n case VM_OC_INSTANCEOF:\n {\n result = opfunc_instanceof (left_value, right_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n goto free_both_values;\n }\n case VM_OC_BLOCK_CREATE_CONTEXT:\n {\n#if JERRY_ESNEXT\n ecma_value_t *stack_context_top_p;\n stack_context_top_p = VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth;\n\n JERRY_ASSERT (stack_context_top_p == stack_top_p || stack_context_top_p == stack_top_p - 1);\n\n if (byte_code_start_p[0] != CBC_EXT_OPCODE)\n {\n branch_offset += (int32_t) (byte_code_start_p - frame_ctx_p->byte_code_start_p);\n\n if (stack_context_top_p != stack_top_p)\n {\n /* Preserve the value of switch statement. */\n stack_context_top_p[1] = stack_context_top_p[0];\n }\n\n stack_context_top_p[0] = VM_CREATE_CONTEXT_WITH_ENV (VM_CONTEXT_BLOCK, branch_offset);\n\n VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_BLOCK_CONTEXT_STACK_ALLOCATION);\n stack_top_p += PARSER_BLOCK_CONTEXT_STACK_ALLOCATION;\n }\n else\n {\n JERRY_ASSERT (byte_code_start_p[1] == CBC_EXT_TRY_CREATE_ENV);\n\n JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_context_top_p[-1]) == VM_CONTEXT_TRY\n || VM_GET_CONTEXT_TYPE (stack_context_top_p[-1]) == VM_CONTEXT_CATCH\n || VM_GET_CONTEXT_TYPE (stack_context_top_p[-1]) == VM_CONTEXT_FINALLY_JUMP\n || VM_GET_CONTEXT_TYPE (stack_context_top_p[-1]) == VM_CONTEXT_FINALLY_THROW\n || VM_GET_CONTEXT_TYPE (stack_context_top_p[-1]) == VM_CONTEXT_FINALLY_RETURN);\n\n JERRY_ASSERT (!(stack_context_top_p[-1] & VM_CONTEXT_HAS_LEX_ENV));\n\n stack_context_top_p[-1] |= VM_CONTEXT_HAS_LEX_ENV;\n }\n#else /* !JERRY_ESNEXT */\n JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-2]) == VM_CONTEXT_CATCH\n && !(stack_top_p[-2] & VM_CONTEXT_HAS_LEX_ENV));\n\n stack_top_p[-2] |= VM_CONTEXT_HAS_LEX_ENV;\n#endif /* JERRY_ESNEXT */\n\n frame_ctx_p->lex_env_p = ecma_create_decl_lex_env (frame_ctx_p->lex_env_p);\n frame_ctx_p->lex_env_p->type_flags_refs |= ECMA_OBJECT_FLAG_BLOCK;\n\n continue;\n }\n case VM_OC_WITH:\n {\n ecma_value_t value = *(--stack_top_p);\n ecma_object_t *object_p;\n ecma_object_t *with_env_p;\n\n branch_offset += (int32_t) (byte_code_start_p - frame_ctx_p->byte_code_start_p);\n\n JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p);\n\n result = ecma_op_to_object (value);\n ecma_free_value (value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n object_p = ecma_get_object_from_value (result);\n\n with_env_p = ecma_create_object_lex_env (frame_ctx_p->lex_env_p, object_p);\n ecma_deref_object (object_p);\n\n VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_WITH_CONTEXT_STACK_ALLOCATION);\n stack_top_p += PARSER_WITH_CONTEXT_STACK_ALLOCATION;\n\n stack_top_p[-1] = VM_CREATE_CONTEXT_WITH_ENV (VM_CONTEXT_WITH, branch_offset);\n\n with_env_p->type_flags_refs |= ECMA_OBJECT_FLAG_BLOCK;\n frame_ctx_p->lex_env_p = with_env_p;\n continue;\n }\n case VM_OC_FOR_IN_INIT:\n {\n ecma_value_t value = *(--stack_top_p);\n\n JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p);\n\n ecma_value_t expr_obj_value = ECMA_VALUE_UNDEFINED;\n ecma_collection_t *prop_names_p = opfunc_for_in (value, &expr_obj_value);\n ecma_free_value (value);\n\n if (prop_names_p == NULL)\n {\n#if JERRY_ESNEXT\n if (JERRY_UNLIKELY (ECMA_IS_VALUE_ERROR (expr_obj_value)))\n {\n result = expr_obj_value;\n goto error;\n }\n#endif /* JERRY_ESNEXT */\n\n /* The collection is already released */\n byte_code_p = byte_code_start_p + branch_offset;\n continue;\n }\n\n branch_offset += (int32_t) (byte_code_start_p - frame_ctx_p->byte_code_start_p);\n\n VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_FOR_IN_CONTEXT_STACK_ALLOCATION);\n stack_top_p += PARSER_FOR_IN_CONTEXT_STACK_ALLOCATION;\n stack_top_p[-1] = VM_CREATE_CONTEXT (VM_CONTEXT_FOR_IN, branch_offset);\n ECMA_SET_INTERNAL_VALUE_ANY_POINTER (stack_top_p[-2], prop_names_p);\n stack_top_p[-3] = 0;\n stack_top_p[-4] = expr_obj_value;\n\n#if JERRY_ESNEXT\n if (byte_code_p[0] == CBC_EXT_OPCODE && byte_code_p[1] == CBC_EXT_CLONE_CONTEXT)\n {\n /* No need to duplicate the first context. */\n byte_code_p += 2;\n }\n#endif /* JERRY_ESNEXT */\n continue;\n }\n case VM_OC_FOR_IN_GET_NEXT:\n {\n ecma_value_t *context_top_p = VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth;\n\n ecma_collection_t *collection_p;\n collection_p = ECMA_GET_INTERNAL_VALUE_POINTER (ecma_collection_t, context_top_p[-2]);\n\n JERRY_ASSERT (VM_GET_CONTEXT_TYPE (context_top_p[-1]) == VM_CONTEXT_FOR_IN);\n\n uint32_t index = context_top_p[-3];\n ecma_value_t *buffer_p = collection_p->buffer_p;\n\n *stack_top_p++ = buffer_p[index];\n context_top_p[-3]++;\n continue;\n }\n case VM_OC_FOR_IN_HAS_NEXT:\n {\n JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p);\n\n ecma_collection_t *collection_p;\n collection_p = ECMA_GET_INTERNAL_VALUE_POINTER (ecma_collection_t, stack_top_p[-2]);\n\n JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FOR_IN);\n\n ecma_value_t *buffer_p = collection_p->buffer_p;\n ecma_object_t *object_p = ecma_get_object_from_value (stack_top_p[-4]);\n uint32_t index = stack_top_p[-3];\n\n while (index < collection_p->item_count)\n {\n ecma_string_t *prop_name_p = ecma_get_prop_name_from_value (buffer_p[index]);\n\n result = ecma_op_object_has_property (object_p, prop_name_p);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n if (JERRY_LIKELY (ecma_is_value_true (result)))\n {\n byte_code_p = byte_code_start_p + branch_offset;\n break;\n }\n\n ecma_deref_ecma_string (prop_name_p);\n index++;\n }\n\n if (index == collection_p->item_count)\n {\n ecma_deref_object (object_p);\n ecma_collection_destroy (collection_p);\n VM_MINUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_FOR_IN_CONTEXT_STACK_ALLOCATION);\n stack_top_p -= PARSER_FOR_IN_CONTEXT_STACK_ALLOCATION;\n }\n else\n {\n stack_top_p[-3] = index;\n }\n continue;\n }\n#if JERRY_ESNEXT\n case VM_OC_FOR_OF_INIT:\n {\n ecma_value_t value = *(--stack_top_p);\n\n JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p);\n\n ecma_value_t next_method;\n ecma_value_t iterator = ecma_op_get_iterator (value, ECMA_VALUE_SYNC_ITERATOR, &next_method);\n\n ecma_free_value (value);\n\n if (ECMA_IS_VALUE_ERROR (iterator))\n {\n result = iterator;\n goto error;\n }\n\n result = ecma_op_iterator_step (iterator, next_method);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n ecma_free_value (iterator);\n ecma_free_value (next_method);\n goto error;\n }\n\n if (ecma_is_value_false (result))\n {\n ecma_free_value (iterator);\n ecma_free_value (next_method);\n byte_code_p = byte_code_start_p + branch_offset;\n continue;\n }\n\n ecma_value_t next_value = ecma_op_iterator_value (result);\n ecma_free_value (result);\n\n if (ECMA_IS_VALUE_ERROR (next_value))\n {\n result = next_value;\n ecma_free_value (iterator);\n ecma_free_value (next_method);\n goto error;\n }\n\n branch_offset += (int32_t) (byte_code_start_p - frame_ctx_p->byte_code_start_p);\n\n VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_FOR_OF_CONTEXT_STACK_ALLOCATION);\n stack_top_p += PARSER_FOR_OF_CONTEXT_STACK_ALLOCATION;\n stack_top_p[-1] = VM_CREATE_CONTEXT (VM_CONTEXT_FOR_OF, branch_offset) | VM_CONTEXT_CLOSE_ITERATOR;\n stack_top_p[-2] = next_value;\n stack_top_p[-3] = iterator;\n stack_top_p[-4] = next_method;\n\n if (byte_code_p[0] == CBC_EXT_OPCODE && byte_code_p[1] == CBC_EXT_CLONE_CONTEXT)\n {\n /* No need to duplicate the first context. */\n byte_code_p += 2;\n }\n continue;\n }\n case VM_OC_FOR_OF_GET_NEXT:\n {\n ecma_value_t *context_top_p = VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth;\n JERRY_ASSERT (VM_GET_CONTEXT_TYPE (context_top_p[-1]) == VM_CONTEXT_FOR_OF\n || VM_GET_CONTEXT_TYPE (context_top_p[-1]) == VM_CONTEXT_FOR_AWAIT_OF);\n JERRY_ASSERT (context_top_p[-1] & VM_CONTEXT_CLOSE_ITERATOR);\n\n *stack_top_p++ = context_top_p[-2];\n context_top_p[-2] = ECMA_VALUE_UNDEFINED;\n continue;\n }\n case VM_OC_FOR_OF_HAS_NEXT:\n {\n JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p);\n JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FOR_OF);\n JERRY_ASSERT (stack_top_p[-1] & VM_CONTEXT_CLOSE_ITERATOR);\n\n stack_top_p[-1] &= (uint32_t) ~VM_CONTEXT_CLOSE_ITERATOR;\n result = ecma_op_iterator_step (stack_top_p[-3], stack_top_p[-4]);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n if (ecma_is_value_false (result))\n {\n ecma_free_value (stack_top_p[-2]);\n ecma_free_value (stack_top_p[-3]);\n ecma_free_value (stack_top_p[-4]);\n VM_MINUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_FOR_OF_CONTEXT_STACK_ALLOCATION);\n stack_top_p -= PARSER_FOR_OF_CONTEXT_STACK_ALLOCATION;\n continue;\n }\n\n ecma_value_t next_value = ecma_op_iterator_value (result);\n ecma_free_value (result);\n\n if (ECMA_IS_VALUE_ERROR (next_value))\n {\n result = next_value;\n goto error;\n }\n\n JERRY_ASSERT (stack_top_p[-2] == ECMA_VALUE_UNDEFINED);\n stack_top_p[-1] |= VM_CONTEXT_CLOSE_ITERATOR;\n stack_top_p[-2] = next_value;\n byte_code_p = byte_code_start_p + branch_offset;\n continue;\n }\n case VM_OC_FOR_AWAIT_OF_INIT:\n {\n ecma_value_t value = *(--stack_top_p);\n\n JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p);\n\n ecma_value_t next_method;\n result = ecma_op_get_iterator (value, ECMA_VALUE_ASYNC_ITERATOR, &next_method);\n\n ecma_free_value (value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n ecma_value_t iterator = result;\n result = ecma_op_iterator_next (result, next_method, ECMA_VALUE_EMPTY);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n ecma_free_value (iterator);\n ecma_free_value (next_method);\n goto error;\n }\n\n branch_offset += (int32_t) (byte_code_start_p - frame_ctx_p->byte_code_start_p);\n\n VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_FOR_AWAIT_OF_CONTEXT_STACK_ALLOCATION);\n stack_top_p += PARSER_FOR_AWAIT_OF_CONTEXT_STACK_ALLOCATION;\n stack_top_p[-1] = VM_CREATE_CONTEXT (VM_CONTEXT_FOR_AWAIT_OF, branch_offset);\n stack_top_p[-2] = ECMA_VALUE_UNDEFINED;\n stack_top_p[-3] = iterator;\n stack_top_p[-4] = next_method;\n\n if (byte_code_p[0] == CBC_EXT_OPCODE && byte_code_p[1] == CBC_EXT_CLONE_CONTEXT)\n {\n /* No need to duplicate the first context. */\n byte_code_p += 2;\n }\n\n frame_ctx_p->call_operation = VM_EXEC_RETURN;\n frame_ctx_p->byte_code_p = byte_code_p;\n frame_ctx_p->stack_top_p = stack_top_p;\n\n uint16_t extra_flags = (ECMA_EXECUTABLE_OBJECT_DO_AWAIT_OR_YIELD\n | (ECMA_AWAIT_FOR_NEXT << ECMA_AWAIT_STATE_SHIFT));\n\n if (CBC_FUNCTION_GET_TYPE (bytecode_header_p->status_flags) == CBC_FUNCTION_ASYNC_GENERATOR\n || (frame_ctx_p->shared_p->status_flags & VM_FRAME_CTX_SHARED_EXECUTABLE))\n {\n ecma_extended_object_t *executable_object_p = VM_GET_EXECUTABLE_OBJECT (frame_ctx_p);\n result = ecma_promise_async_await (executable_object_p, result);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n executable_object_p->u.cls.u2.executable_obj_flags |= extra_flags;\n return ECMA_VALUE_UNDEFINED;\n }\n\n result = opfunc_async_create_and_await (frame_ctx_p, result, extra_flags);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n return result;\n }\n case VM_OC_FOR_AWAIT_OF_HAS_NEXT:\n {\n JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p);\n JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FOR_AWAIT_OF);\n JERRY_ASSERT (stack_top_p[-1] & VM_CONTEXT_CLOSE_ITERATOR);\n\n stack_top_p[-1] &= (uint32_t) ~VM_CONTEXT_CLOSE_ITERATOR;\n result = ecma_op_iterator_next (stack_top_p[-3], stack_top_p[-4], ECMA_VALUE_EMPTY);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n ecma_extended_object_t *executable_object_p = VM_GET_EXECUTABLE_OBJECT (frame_ctx_p);\n result = ecma_promise_async_await (executable_object_p, result);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n uint16_t extra_flags = (ECMA_EXECUTABLE_OBJECT_DO_AWAIT_OR_YIELD\n | (ECMA_AWAIT_FOR_NEXT << ECMA_AWAIT_STATE_SHIFT));\n executable_object_p->u.cls.u2.executable_obj_flags |= extra_flags;\n\n frame_ctx_p->call_operation = VM_EXEC_RETURN;\n frame_ctx_p->byte_code_p = byte_code_start_p + branch_offset;\n frame_ctx_p->stack_top_p = stack_top_p;\n return ECMA_VALUE_UNDEFINED;\n }\n#endif /* JERRY_ESNEXT */\n case VM_OC_TRY:\n {\n /* Try opcode simply creates the try context. */\n branch_offset += (int32_t) (byte_code_start_p - frame_ctx_p->byte_code_start_p);\n\n JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p);\n\n VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_TRY_CONTEXT_STACK_ALLOCATION);\n stack_top_p += PARSER_TRY_CONTEXT_STACK_ALLOCATION;\n\n stack_top_p[-1] = VM_CREATE_CONTEXT (VM_CONTEXT_TRY, branch_offset);\n continue;\n }\n case VM_OC_CATCH:\n {\n /* Catches are ignored and turned to jumps. */\n JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p);\n JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_TRY);\n\n byte_code_p = byte_code_start_p + branch_offset;\n continue;\n }\n case VM_OC_FINALLY:\n {\n branch_offset += (int32_t) (byte_code_start_p - frame_ctx_p->byte_code_start_p);\n\n JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p);\n\n JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_TRY\n || VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_CATCH);\n\n if (stack_top_p[-1] & VM_CONTEXT_HAS_LEX_ENV)\n {\n ecma_object_t *lex_env_p = frame_ctx_p->lex_env_p;\n JERRY_ASSERT (lex_env_p->u2.outer_reference_cp != JMEM_CP_NULL);\n frame_ctx_p->lex_env_p = ECMA_GET_NON_NULL_POINTER (ecma_object_t, lex_env_p->u2.outer_reference_cp);\n ecma_deref_object (lex_env_p);\n }\n\n VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_FINALLY_CONTEXT_EXTRA_STACK_ALLOCATION);\n stack_top_p += PARSER_FINALLY_CONTEXT_EXTRA_STACK_ALLOCATION;\n\n stack_top_p[-1] = VM_CREATE_CONTEXT (VM_CONTEXT_FINALLY_JUMP, branch_offset);\n stack_top_p[-2] = (ecma_value_t) branch_offset;\n continue;\n }\n case VM_OC_CONTEXT_END:\n {\n JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p);\n JERRY_ASSERT (!(stack_top_p[-1] & VM_CONTEXT_CLOSE_ITERATOR));\n\n ecma_value_t context_type = VM_GET_CONTEXT_TYPE (stack_top_p[-1]);\n\n if (!VM_CONTEXT_IS_FINALLY (context_type))\n {\n stack_top_p = vm_stack_context_abort (frame_ctx_p, stack_top_p);\n\n JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p);\n continue;\n }\n\n#if JERRY_ESNEXT\n if (stack_top_p[-1] & VM_CONTEXT_HAS_LEX_ENV)\n {\n ecma_object_t *lex_env_p = frame_ctx_p->lex_env_p;\n JERRY_ASSERT (lex_env_p->u2.outer_reference_cp != JMEM_CP_NULL);\n frame_ctx_p->lex_env_p = ECMA_GET_NON_NULL_POINTER (ecma_object_t, lex_env_p->u2.outer_reference_cp);\n ecma_deref_object (lex_env_p);\n }\n#endif /* JERRY_ESNEXT */\n\n VM_MINUS_EQUAL_U16 (frame_ctx_p->context_depth,\n PARSER_FINALLY_CONTEXT_STACK_ALLOCATION);\n stack_top_p -= PARSER_FINALLY_CONTEXT_STACK_ALLOCATION;\n\n if (context_type == VM_CONTEXT_FINALLY_RETURN)\n {\n result = *stack_top_p;\n goto error;\n }\n\n if (context_type == VM_CONTEXT_FINALLY_THROW)\n {\n jcontext_raise_exception (*stack_top_p);\n#if JERRY_VM_THROW\n JERRY_CONTEXT (status_flags) |= ECMA_STATUS_ERROR_THROWN;\n#endif /* JERRY_VM_THROW */\n result = ECMA_VALUE_ERROR;\n\n#if JERRY_DEBUGGER\n JERRY_DEBUGGER_SET_FLAGS (JERRY_DEBUGGER_VM_EXCEPTION_THROWN);\n#endif /* JERRY_DEBUGGER */\n goto error;\n }\n\n JERRY_ASSERT (context_type == VM_CONTEXT_FINALLY_JUMP);\n\n uint32_t jump_target = *stack_top_p;\n\n vm_stack_found_type type = vm_stack_find_finally (frame_ctx_p,\n stack_top_p,\n VM_CONTEXT_FINALLY_JUMP,\n jump_target);\n stack_top_p = frame_ctx_p->stack_top_p;\n switch (type)\n {\n case VM_CONTEXT_FOUND_FINALLY:\n {\n byte_code_p = frame_ctx_p->byte_code_p;\n\n JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FINALLY_JUMP);\n stack_top_p[-2] = jump_target;\n break;\n }\n#if JERRY_ESNEXT\n case VM_CONTEXT_FOUND_ERROR:\n {\n JERRY_ASSERT (jcontext_has_pending_exception ());\n result = ECMA_VALUE_ERROR;\n goto error;\n }\n case VM_CONTEXT_FOUND_AWAIT:\n {\n JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FINALLY_JUMP);\n stack_top_p[-2] = jump_target;\n return ECMA_VALUE_UNDEFINED;\n }\n#endif /* JERRY_ESNEXT */\n default:\n {\n byte_code_p = frame_ctx_p->byte_code_start_p + jump_target;\n break;\n }\n }\n\n JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p);\n continue;\n }\n case VM_OC_JUMP_AND_EXIT_CONTEXT:\n {\n JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p);\n JERRY_ASSERT (!jcontext_has_pending_exception ());\n\n branch_offset += (int32_t) (byte_code_start_p - frame_ctx_p->byte_code_start_p);\n\n vm_stack_found_type type = vm_stack_find_finally (frame_ctx_p,\n stack_top_p,\n VM_CONTEXT_FINALLY_JUMP,\n (uint32_t) branch_offset);\n stack_top_p = frame_ctx_p->stack_top_p;\n switch (type)\n {\n case VM_CONTEXT_FOUND_FINALLY:\n {\n byte_code_p = frame_ctx_p->byte_code_p;\n\n JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FINALLY_JUMP);\n stack_top_p[-2] = (uint32_t) branch_offset;\n break;\n }\n#if JERRY_ESNEXT\n case VM_CONTEXT_FOUND_ERROR:\n {\n JERRY_ASSERT (jcontext_has_pending_exception ());\n result = ECMA_VALUE_ERROR;\n goto error;\n }\n case VM_CONTEXT_FOUND_AWAIT:\n {\n JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FINALLY_JUMP);\n stack_top_p[-2] = (uint32_t) branch_offset;\n return ECMA_VALUE_UNDEFINED;\n }\n#endif /* JERRY_ESNEXT */\n default:\n {\n byte_code_p = frame_ctx_p->byte_code_start_p + branch_offset;\n break;\n }\n }\n\n JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p);\n continue;\n }\n#if JERRY_MODULE_SYSTEM\n case VM_OC_MODULE_IMPORT:\n {\n left_value = *(--stack_top_p);\n\n ecma_value_t user_value = ECMA_VALUE_UNDEFINED;\n ecma_value_t script_value = ((cbc_uint8_arguments_t *) bytecode_header_p)->script_value;\n\n#if JERRY_SNAPSHOT_EXEC\n if (JERRY_UNLIKELY (!(bytecode_header_p->status_flags & CBC_CODE_FLAGS_STATIC_FUNCTION)))\n {\n#endif /* JERRY_SNAPSHOT_EXEC */\n cbc_script_t *script_p = ECMA_GET_INTERNAL_VALUE_POINTER (cbc_script_t, script_value);\n\n if (script_p->refs_and_type & CBC_SCRIPT_HAS_USER_VALUE)\n {\n user_value = CBC_SCRIPT_GET_USER_VALUE (script_p);\n }\n#if JERRY_SNAPSHOT_EXEC\n }\n#endif /* JERRY_SNAPSHOT_EXEC */\n\n result = ecma_module_import (left_value, user_value);\n ecma_free_value (left_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n goto error;\n }\n\n *stack_top_p++ = result;\n continue;\n }\n case VM_OC_MODULE_IMPORT_META:\n {\n ecma_value_t script_value = ((cbc_uint8_arguments_t *) bytecode_header_p)->script_value;\n cbc_script_t *script_p = ECMA_GET_INTERNAL_VALUE_POINTER (cbc_script_t, script_value);\n\n JERRY_ASSERT (script_p->refs_and_type & CBC_SCRIPT_HAS_IMPORT_META);\n\n ecma_value_t import_meta = CBC_SCRIPT_GET_IMPORT_META (script_p, script_p->refs_and_type);\n ecma_object_t *import_meta_object_p = ecma_get_object_from_value (import_meta);\n\n if (ecma_get_object_type (import_meta_object_p) != ECMA_OBJECT_TYPE_GENERAL)\n {\n JERRY_ASSERT (ecma_object_class_is (import_meta_object_p, ECMA_OBJECT_CLASS_MODULE));\n\n ecma_value_t module = import_meta;\n import_meta_object_p = ecma_create_object (NULL, 0, ECMA_OBJECT_TYPE_GENERAL);\n import_meta = ecma_make_object_value (import_meta_object_p);\n\n if (JERRY_CONTEXT (module_import_meta_callback_p) != NULL)\n {\n void *user_p = JERRY_CONTEXT (module_import_meta_callback_user_p);\n JERRY_CONTEXT (module_import_meta_callback_p) (module, import_meta, user_p);\n }\n\n CBC_SCRIPT_GET_IMPORT_META (script_p, script_p->refs_and_type) = import_meta;\n }\n else\n {\n ecma_ref_object (import_meta_object_p);\n }\n\n *stack_top_p++ = import_meta;\n continue;\n }\n#endif /* JERRY_MODULE_SYSTEM */\n#if JERRY_DEBUGGER\n case VM_OC_BREAKPOINT_ENABLED:\n {\n if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_VM_IGNORE)\n {\n continue;\n }\n\n JERRY_ASSERT (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_CONNECTED);\n\n JERRY_ASSERT (!(frame_ctx_p->shared_p->bytecode_header_p->status_flags & CBC_CODE_FLAGS_DEBUGGER_IGNORE));\n\n frame_ctx_p->byte_code_p = byte_code_start_p;\n\n jerry_debugger_breakpoint_hit (JERRY_DEBUGGER_BREAKPOINT_HIT);\n if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_VM_EXCEPTION_THROWN)\n {\n result = ECMA_VALUE_ERROR;\n goto error;\n }\n continue;\n }\n case VM_OC_BREAKPOINT_DISABLED:\n {\n if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_VM_IGNORE)\n {\n continue;\n }\n\n JERRY_ASSERT (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_CONNECTED);\n\n JERRY_ASSERT (!(frame_ctx_p->shared_p->bytecode_header_p->status_flags & CBC_CODE_FLAGS_DEBUGGER_IGNORE));\n\n frame_ctx_p->byte_code_p = byte_code_start_p;\n\n if ((JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_VM_STOP)\n && (JERRY_CONTEXT (debugger_stop_context) == NULL\n || JERRY_CONTEXT (debugger_stop_context) == JERRY_CONTEXT (vm_top_context_p)))\n {\n jerry_debugger_breakpoint_hit (JERRY_DEBUGGER_BREAKPOINT_HIT);\n if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_VM_EXCEPTION_THROWN)\n {\n result = ECMA_VALUE_ERROR;\n goto error;\n }\n continue;\n }\n\n if (JERRY_CONTEXT (debugger_message_delay) > 0)\n {\n JERRY_CONTEXT (debugger_message_delay)--;\n continue;\n }\n\n JERRY_CONTEXT (debugger_message_delay) = JERRY_DEBUGGER_MESSAGE_FREQUENCY;\n\n if (jerry_debugger_receive (NULL))\n {\n continue;\n }\n\n if ((JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_VM_STOP)\n && (JERRY_CONTEXT (debugger_stop_context) == NULL\n || JERRY_CONTEXT (debugger_stop_context) == JERRY_CONTEXT (vm_top_context_p)))\n {\n jerry_debugger_breakpoint_hit (JERRY_DEBUGGER_BREAKPOINT_HIT);\n if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_VM_EXCEPTION_THROWN)\n {\n result = ECMA_VALUE_ERROR;\n goto error;\n }\n }\n continue;\n }\n#endif /* JERRY_DEBUGGER */\n case VM_OC_NONE:\n default:\n {\n JERRY_ASSERT (VM_OC_GROUP_GET_INDEX (opcode_data) == VM_OC_NONE);\n\n jerry_fatal (ERR_DISABLED_BYTE_CODE);\n }\n }\n\n JERRY_ASSERT (VM_OC_HAS_PUT_RESULT (opcode_data));\n\n if (opcode_data & VM_OC_PUT_IDENT)\n {\n uint16_t literal_index;\n\n READ_LITERAL_INDEX (literal_index);\n\n if (literal_index < register_end)\n {\n ecma_fast_free_value (VM_GET_REGISTER (frame_ctx_p, literal_index));\n VM_GET_REGISTER (frame_ctx_p, literal_index) = result;\n\n if (opcode_data & (VM_OC_PUT_STACK | VM_OC_PUT_BLOCK))\n {\n result = ecma_fast_copy_value (result);\n }\n }\n else\n {\n ecma_string_t *var_name_str_p = ecma_get_string_from_value (literal_start_p[literal_index]);\n\n ecma_value_t put_value_result = ecma_op_put_value_lex_env_base (frame_ctx_p->lex_env_p,\n var_name_str_p,\n is_strict,\n result);\n\n if (ECMA_IS_VALUE_ERROR (put_value_result))\n {\n ecma_free_value (result);\n result = put_value_result;\n goto error;\n }\n\n if (!(opcode_data & (VM_OC_PUT_STACK | VM_OC_PUT_BLOCK)))\n {\n ecma_fast_free_value (result);\n }\n }\n }\n else if (opcode_data & VM_OC_PUT_REFERENCE)\n {\n ecma_value_t property = *(--stack_top_p);\n ecma_value_t base = *(--stack_top_p);\n\n if (base == ECMA_VALUE_REGISTER_REF)\n {\n property = (ecma_value_t) ecma_get_integer_from_value (property);\n ecma_fast_free_value (VM_GET_REGISTER (frame_ctx_p, property));\n VM_GET_REGISTER (frame_ctx_p, property) = result;\n\n if (!(opcode_data & (VM_OC_PUT_STACK | VM_OC_PUT_BLOCK)))\n {\n goto free_both_values;\n }\n result = ecma_fast_copy_value (result);\n }\n else\n {\n ecma_value_t set_value_result = vm_op_set_value (base,\n property,\n result,\n is_strict);\n\n if (ECMA_IS_VALUE_ERROR (set_value_result))\n {\n ecma_free_value (result);\n result = set_value_result;\n goto error;\n }\n\n if (!(opcode_data & (VM_OC_PUT_STACK | VM_OC_PUT_BLOCK)))\n {\n ecma_fast_free_value (result);\n goto free_both_values;\n }\n }\n }\n\n if (opcode_data & VM_OC_PUT_STACK)\n {\n *stack_top_p++ = result;\n }\n else if (opcode_data & VM_OC_PUT_BLOCK)\n {\n ecma_fast_free_value (VM_GET_REGISTER (frame_ctx_p, 0));\n VM_GET_REGISTERS (frame_ctx_p)[0] = result;\n }\n\nfree_both_values:\n ecma_fast_free_value (right_value);\nfree_left_value:\n ecma_fast_free_value (left_value);\n }\n\nerror:\n ecma_fast_free_value (left_value);\n ecma_fast_free_value (right_value);\n\n if (ECMA_IS_VALUE_ERROR (result))\n {\n JERRY_ASSERT (jcontext_has_pending_exception ());\n ecma_value_t *stack_bottom_p = VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth;\n\n while (stack_top_p > stack_bottom_p)\n {\n ecma_value_t stack_item = *(--stack_top_p);\n#if JERRY_ESNEXT\n if (stack_item == ECMA_VALUE_RELEASE_LEX_ENV)\n {\n opfunc_pop_lexical_environment (frame_ctx_p);\n continue;\n }\n#endif /* JERRY_ESNEXT */\n ecma_fast_free_value (stack_item);\n }\n\n#if JERRY_VM_THROW\n if (!(JERRY_CONTEXT (status_flags) & ECMA_STATUS_ERROR_THROWN))\n {\n JERRY_CONTEXT (status_flags) |= ECMA_STATUS_ERROR_THROWN;\n\n jerry_vm_throw_callback_t vm_throw_callback_p = JERRY_CONTEXT (vm_throw_callback_p);\n\n if (vm_throw_callback_p != NULL)\n {\n vm_throw_callback_p (JERRY_CONTEXT (error_value), JERRY_CONTEXT (vm_throw_callback_user_p));\n }\n }\n#endif /* JERRY_VM_THROW */\n\n#if JERRY_DEBUGGER\n const uint32_t dont_stop = (JERRY_DEBUGGER_VM_IGNORE_EXCEPTION\n | JERRY_DEBUGGER_VM_IGNORE\n | JERRY_DEBUGGER_VM_EXCEPTION_THROWN);\n\n if ((JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_CONNECTED)\n && !(frame_ctx_p->shared_p->bytecode_header_p->status_flags\n & (CBC_CODE_FLAGS_DEBUGGER_IGNORE | CBC_CODE_FLAGS_STATIC_FUNCTION))\n && !(JERRY_CONTEXT (debugger_flags) & dont_stop))\n {\n /* Save the error to a local value, because the engine enters breakpoint mode after,\n therefore an evaluation error, or user-created error throw would overwrite it. */\n ecma_value_t current_error_value = JERRY_CONTEXT (error_value);\n\n if (jerry_debugger_send_exception_string (current_error_value))\n {\n jerry_debugger_breakpoint_hit (JERRY_DEBUGGER_EXCEPTION_HIT);\n\n if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_VM_EXCEPTION_THROWN)\n {\n ecma_free_value (current_error_value);\n }\n else\n {\n JERRY_CONTEXT (error_value) = current_error_value;\n }\n\n JERRY_DEBUGGER_SET_FLAGS (JERRY_DEBUGGER_VM_EXCEPTION_THROWN);\n }\n }\n#endif /* JERRY_DEBUGGER */\n }\n\n JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p);\n\n if (frame_ctx_p->context_depth == 0)\n {\n /* In most cases there is no context. */\n frame_ctx_p->call_operation = VM_NO_EXEC_OP;\n return result;\n }\n\n if (!ECMA_IS_VALUE_ERROR (result))\n {\n switch (vm_stack_find_finally (frame_ctx_p,\n stack_top_p,\n VM_CONTEXT_FINALLY_RETURN,\n 0))\n {\n case VM_CONTEXT_FOUND_FINALLY:\n {\n stack_top_p = frame_ctx_p->stack_top_p;\n byte_code_p = frame_ctx_p->byte_code_p;\n\n JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FINALLY_RETURN);\n JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p);\n stack_top_p[-2] = result;\n continue;\n }\n#if JERRY_ESNEXT\n case VM_CONTEXT_FOUND_ERROR:\n {\n JERRY_ASSERT (jcontext_has_pending_exception ());\n\n ecma_free_value (result);\n stack_top_p = frame_ctx_p->stack_top_p;\n result = ECMA_VALUE_ERROR;\n break;\n }\n case VM_CONTEXT_FOUND_AWAIT:\n {\n stack_top_p = frame_ctx_p->stack_top_p;\n\n JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FINALLY_RETURN);\n stack_top_p[-2] = result;\n return ECMA_VALUE_UNDEFINED;\n }\n#endif /* JERRY_ESNEXT */\n default:\n {\n goto finish;\n }\n }\n }\n\n JERRY_ASSERT (jcontext_has_pending_exception ());\n\n if (!jcontext_has_pending_abort ())\n {\n switch (vm_stack_find_finally (frame_ctx_p,\n stack_top_p,\n VM_CONTEXT_FINALLY_THROW,\n 0))\n {\n case VM_CONTEXT_FOUND_FINALLY:\n {\n stack_top_p = frame_ctx_p->stack_top_p;\n byte_code_p = frame_ctx_p->byte_code_p;\n\n JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p);\n JERRY_ASSERT (!(stack_top_p[-1] & VM_CONTEXT_HAS_LEX_ENV));\n\n#if JERRY_DEBUGGER\n JERRY_DEBUGGER_CLEAR_FLAGS (JERRY_DEBUGGER_VM_EXCEPTION_THROWN);\n#endif /* JERRY_DEBUGGER */\n\n result = jcontext_take_exception ();\n\n if (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FINALLY_THROW)\n {\n stack_top_p[-2] = result;\n continue;\n }\n\n JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_CATCH);\n\n *stack_top_p++ = result;\n continue;\n }\n#if JERRY_ESNEXT\n case VM_CONTEXT_FOUND_AWAIT:\n {\n JERRY_ASSERT (VM_GET_CONTEXT_TYPE (frame_ctx_p->stack_top_p[-1]) == VM_CONTEXT_FINALLY_THROW);\n return ECMA_VALUE_UNDEFINED;\n }\n#endif /* JERRY_ESNEXT */\n default:\n {\n break;\n }\n }\n }\n else\n {\n do\n {\n JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p);\n\n stack_top_p = vm_stack_context_abort (frame_ctx_p, stack_top_p);\n }\n while (frame_ctx_p->context_depth > 0);\n }\n\nfinish:\n frame_ctx_p->call_operation = VM_NO_EXEC_OP;\n return result;\n }\n} /* vm_loop */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Fix for-in collection cleanup on abrupt 'has' result (#4807)\n\nThis patch fixes #4747\r\n\r\nJerryScript-DCO-1.0-Signed-off-by: Robert Fancsik robert.fancsik@h-lab.eu'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: GF_Err stbl_GetSampleInfos(GF_SampleTableBox *stbl, u32 sampleNumber, u64 *offset, u32 *chunkNumber, u32 *descIndex, GF_StscEntry **out_ent)\n{\n\tGF_Err e;\n\tu32 i, k, offsetInChunk, size, chunk_num;\n\tGF_ChunkOffsetBox *stco;\n\tGF_ChunkLargeOffsetBox *co64;\n\tGF_StscEntry *ent;\n\n\t(*offset) = 0;\n\t(*chunkNumber) = (*descIndex) = 0;\n\tif (out_ent) (*out_ent) = NULL;\n\tif (!stbl || !sampleNumber) return GF_BAD_PARAM;\n\tif (!stbl->ChunkOffset || !stbl->SampleToChunk || !stbl->SampleSize) return GF_ISOM_INVALID_FILE;\n\n\tif (stbl->SampleSize && stbl->SampleToChunk->nb_entries == stbl->SampleSize->sampleCount) {\n\t\tent = &stbl->SampleToChunk->entries[sampleNumber-1];\n\t\tif (!ent) return GF_BAD_PARAM;\n\t\t(*descIndex) = ent->sampleDescriptionIndex;\n\t\t(*chunkNumber) = sampleNumber;\n\t\tif (out_ent) *out_ent = ent;\n\t\tif ( stbl->ChunkOffset->type == GF_ISOM_BOX_TYPE_STCO) {\n\t\t\tstco = (GF_ChunkOffsetBox *)stbl->ChunkOffset;\n\t\t\tif (!stco->offsets) return GF_ISOM_INVALID_FILE;\n\n\t\t\t(*offset) = (u64) stco->offsets[sampleNumber - 1];\n\t\t} else {\n\t\t\tco64 = (GF_ChunkLargeOffsetBox *)stbl->ChunkOffset;\n\t\t\tif (!co64->offsets) return GF_ISOM_INVALID_FILE;\n\n\t\t\t(*offset) = co64->offsets[sampleNumber - 1];\n\t\t}\n\t\treturn GF_OK;\n\t}\n\n\t//check our cache: if desired sample is at or above current cache entry, start from here\n\tif (stbl->SampleToChunk->firstSampleInCurrentChunk &&\n\t (stbl->SampleToChunk->firstSampleInCurrentChunk <= sampleNumber)) {\n\n\t\ti = stbl->SampleToChunk->currentIndex;\n\t\tent = &stbl->SampleToChunk->entries[stbl->SampleToChunk->currentIndex];\n\t\tGetGhostNum(ent, i, stbl->SampleToChunk->nb_entries, stbl);\n\t\tk = stbl->SampleToChunk->currentChunk;\n\t}\n\t//otherwise start from first entry\n\telse {\n\t\ti = 0;\n\t\tstbl->SampleToChunk->currentIndex = 0;\n\t\tstbl->SampleToChunk->currentChunk = 1;\n\t\tstbl->SampleToChunk->ghostNumber = 1;\n\t\tstbl->SampleToChunk->firstSampleInCurrentChunk = 1;\n\t\tent = &stbl->SampleToChunk->entries[0];\n\t\tGetGhostNum(ent, 0, stbl->SampleToChunk->nb_entries, stbl);\n\t\tk = stbl->SampleToChunk->currentChunk;\n\t}\n\n\t//first get the chunk\n\tfor (; i < stbl->SampleToChunk->nb_entries; i++) {\n\t\tassert(stbl->SampleToChunk->firstSampleInCurrentChunk <= sampleNumber);\n\t\t//corrupted file (less sample2chunk info than sample count\n\t\tif (k > stbl->SampleToChunk->ghostNumber) {\n\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t}\n\n\n\t\t//check if sample is in current chunk\n\t\tu32 max_chunks_in_entry = stbl->SampleToChunk->ghostNumber - k;\n\t\tu32 nb_chunks_for_sample = sampleNumber - stbl->SampleToChunk->firstSampleInCurrentChunk;\n\t\tif (ent->samplesPerChunk) \n\t\t\tnb_chunks_for_sample /= ent->samplesPerChunk;\n\n\t\tif (\n\t\t\t(nb_chunks_for_sample <= max_chunks_in_entry)\n\t\t\t&& (stbl->SampleToChunk->firstSampleInCurrentChunk + (nb_chunks_for_sample+1) * ent->samplesPerChunk > sampleNumber)\n\t\t) {\n\n\t\t\tstbl->SampleToChunk->firstSampleInCurrentChunk += nb_chunks_for_sample * ent->samplesPerChunk;\n\t\t\tstbl->SampleToChunk->currentChunk += nb_chunks_for_sample;\n\t\t\tgoto sample_found;\n\t\t}\n\t\tmax_chunks_in_entry += 1;\n\t\tstbl->SampleToChunk->firstSampleInCurrentChunk += max_chunks_in_entry * ent->samplesPerChunk;\n\t\tstbl->SampleToChunk->currentChunk += max_chunks_in_entry;\n\n\t\t//not in this entry, get the next entry if not the last one\n\t\tif (i+1 != stbl->SampleToChunk->nb_entries) {\n\t\t\tent = &stbl->SampleToChunk->entries[i+1];\n\t\t\t//update the GhostNumber\n\t\t\tGetGhostNum(ent, i+1, stbl->SampleToChunk->nb_entries, stbl);\n\t\t\t//update the entry in our cache\n\t\t\tstbl->SampleToChunk->currentIndex = i+1;\n\t\t\tstbl->SampleToChunk->currentChunk = 1;\n\t\t\tk = 1;\n\t\t}\n\t}\n\t//if we get here, gasp, the sample was not found\n\treturn GF_ISOM_INVALID_FILE;\n\nsample_found:\n\n\t(*descIndex) = ent->sampleDescriptionIndex;\n\t(*chunkNumber) = chunk_num = ent->firstChunk + stbl->SampleToChunk->currentChunk - 1;\n\tif (out_ent) *out_ent = ent;\n\tif (! *chunkNumber)\n\t\treturn GF_ISOM_INVALID_FILE;\n\t\n\t//ok, get the size of all the previous samples in the chunk\n\toffsetInChunk = 0;\n\t//constant size\n\tif (stbl->SampleSize && stbl->SampleSize->sampleSize) {\n\t\tu32 diff = sampleNumber - stbl->SampleToChunk->firstSampleInCurrentChunk;\n\t\toffsetInChunk += diff * stbl->SampleSize->sampleSize;\n\t} else if ((stbl->r_last_chunk_num == chunk_num) && (stbl->r_last_sample_num == sampleNumber)) {\n\t\toffsetInChunk = stbl->r_last_offset_in_chunk;\n\t} else if ((stbl->r_last_chunk_num == chunk_num) && (stbl->r_last_sample_num + 1 == sampleNumber)) {\n\t\te = stbl_GetSampleSize(stbl->SampleSize, stbl->r_last_sample_num, &size);\n\t\tif (e) return e;\n\t\tstbl->r_last_offset_in_chunk += size;\n\t\tstbl->r_last_sample_num = sampleNumber;\n\t\toffsetInChunk = stbl->r_last_offset_in_chunk;\n\t} else {\n\t\t//warning, firstSampleInChunk is at least 1 - not 0\n\t\tfor (i = stbl->SampleToChunk->firstSampleInCurrentChunk; i < sampleNumber; i++) {\n\t\t\te = stbl_GetSampleSize(stbl->SampleSize, i, &size);\n\t\t\tif (e) return e;\n\t\t\toffsetInChunk += size;\n\t\t}\n\t\tstbl->r_last_chunk_num = chunk_num;\n\t\tstbl->r_last_sample_num = sampleNumber;\n\t\tstbl->r_last_offset_in_chunk = offsetInChunk;\n\t}\n\t//OK, that's the size of our offset in the chunk\n\t//now get the chunk\n\tif ( stbl->ChunkOffset->type == GF_ISOM_BOX_TYPE_STCO) {\n\t\tstco = (GF_ChunkOffsetBox *)stbl->ChunkOffset;\n\t\tif (stco->nb_entries < (*chunkNumber) ) return GF_ISOM_INVALID_FILE;\n\t\t(*offset) = (u64) stco->offsets[(*chunkNumber) - 1] + (u64) offsetInChunk;\n\t} else {\n\t\tco64 = (GF_ChunkLargeOffsetBox *)stbl->ChunkOffset;\n\t\tif (co64->nb_entries < (*chunkNumber) ) return GF_ISOM_INVALID_FILE;\n\t\t(*offset) = co64->offsets[(*chunkNumber) - 1] + (u64) offsetInChunk;\n\t}\n\treturn GF_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-401'], 'message': 'fixed #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: DefragIPv4TooLargeTest(void)\n{\n DefragContext *dc = NULL;\n Packet *p = NULL;\n int ret = 0;\n\n DefragInit();\n\n dc = DefragContextNew();\n if (dc == NULL)\n goto end;\n\n /* Create a fragment that would extend past the max allowable size\n * for an IPv4 packet. */\n p = BuildTestPacket(1, 8183, 0, 'A', 71);\n if (p == NULL)\n goto end;\n\n /* We do not expect a packet returned. */\n if (Defrag(NULL, NULL, p, NULL) != NULL)\n goto end;\n if (!ENGINE_ISSET_EVENT(p, IPV4_FRAG_PKT_TOO_LARGE))\n goto end;\n\n /* The fragment should have been ignored so no fragments should have\n * been allocated from the pool. */\n if (dc->frag_pool->outstanding != 0)\n return 0;\n\n ret = 1;\nend:\n if (dc != NULL)\n DefragContextDestroy(dc);\n if (p != NULL)\n SCFree(p);\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: DefragRegisterTests(void)\n{\n#ifdef UNITTESTS\n UtRegisterTest(\"DefragInOrderSimpleTest\", DefragInOrderSimpleTest);\n UtRegisterTest(\"DefragReverseSimpleTest\", DefragReverseSimpleTest);\n UtRegisterTest(\"DefragSturgesNovakBsdTest\", DefragSturgesNovakBsdTest);\n UtRegisterTest(\"DefragSturgesNovakLinuxTest\", DefragSturgesNovakLinuxTest);\n UtRegisterTest(\"DefragSturgesNovakWindowsTest\",\n DefragSturgesNovakWindowsTest);\n UtRegisterTest(\"DefragSturgesNovakSolarisTest\",\n DefragSturgesNovakSolarisTest);\n UtRegisterTest(\"DefragSturgesNovakFirstTest\", DefragSturgesNovakFirstTest);\n UtRegisterTest(\"DefragSturgesNovakLastTest\", DefragSturgesNovakLastTest);\n\n UtRegisterTest(\"DefragIPv4NoDataTest\", DefragIPv4NoDataTest);\n UtRegisterTest(\"DefragIPv4TooLargeTest\", DefragIPv4TooLargeTest);\n\n UtRegisterTest(\"IPV6DefragInOrderSimpleTest\", IPV6DefragInOrderSimpleTest);\n UtRegisterTest(\"IPV6DefragReverseSimpleTest\", IPV6DefragReverseSimpleTest);\n UtRegisterTest(\"IPV6DefragSturgesNovakBsdTest\",\n IPV6DefragSturgesNovakBsdTest);\n UtRegisterTest(\"IPV6DefragSturgesNovakLinuxTest\",\n IPV6DefragSturgesNovakLinuxTest);\n UtRegisterTest(\"IPV6DefragSturgesNovakWindowsTest\",\n IPV6DefragSturgesNovakWindowsTest);\n UtRegisterTest(\"IPV6DefragSturgesNovakSolarisTest\",\n IPV6DefragSturgesNovakSolarisTest);\n UtRegisterTest(\"IPV6DefragSturgesNovakFirstTest\",\n IPV6DefragSturgesNovakFirstTest);\n UtRegisterTest(\"IPV6DefragSturgesNovakLastTest\",\n IPV6DefragSturgesNovakLastTest);\n\n UtRegisterTest(\"DefragVlanTest\", DefragVlanTest);\n UtRegisterTest(\"DefragVlanQinQTest\", DefragVlanQinQTest);\n UtRegisterTest(\"DefragTrackerReuseTest\", DefragTrackerReuseTest);\n UtRegisterTest(\"DefragTimeoutTest\", DefragTimeoutTest);\n UtRegisterTest(\"DefragMfIpv4Test\", DefragMfIpv4Test);\n UtRegisterTest(\"DefragMfIpv6Test\", DefragMfIpv6Test);\n#endif /* UNITTESTS */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-358'], 'message': 'defrag - take protocol into account during re-assembly\n\nThe IP protocol was not being used to match fragments with\ntheir packets allowing a carefully constructed packet\nwith a different protocol to be matched, allowing re-assembly\nto complete, creating a packet that would not be re-assembled\nby the destination host.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: \t\tvoid Phase2() final {\n\t\t\tLocal context_handle = Deref(context);\n\t\t\tContext::Scope context_scope{context_handle};\n\t\t\tLocal key_inner = key->CopyInto();\n\t\t\tLocal object = Local::Cast(Deref(reference));\n\t\t\t// Delete key before transferring in, potentially freeing up some v8 heap\n\t\t\tUnmaybe(object->Delete(context_handle, key_inner));\n\t\t\tLocal val_inner = val->TransferIn();\n\t\t\tdid_set = Unmaybe(object->Set(context_handle, key_inner, val_inner));\n\t\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-913'], 'message': 'Don't invoke accessors or proxies via Reference functions'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static UINT dvcman_receive_channel_data(drdynvcPlugin* drdynvc,\n IWTSVirtualChannelManager* pChannelMgr,\n UINT32 ChannelId, wStream* data)\n{\n\tUINT status = CHANNEL_RC_OK;\n\tDVCMAN_CHANNEL* channel;\n\tsize_t dataSize = Stream_GetRemainingLength(data);\n\tchannel = (DVCMAN_CHANNEL*) dvcman_find_channel_by_id(pChannelMgr, ChannelId);\n\n\tif (!channel)\n\t{\n\t\t/* Windows 8.1 tries to open channels not created.\n\t\t\t\t * Ignore cases like this. */\n\t\tWLog_Print(drdynvc->log, WLOG_ERROR, \"ChannelId %\"PRIu32\" not found!\", ChannelId);\n\t\treturn CHANNEL_RC_OK;\n\t}\n\n\tif (channel->dvc_data)\n\t{\n\t\t/* Fragmented data */\n\t\tif (Stream_GetPosition(channel->dvc_data) + dataSize > (UINT32) Stream_Capacity(\n\t\t channel->dvc_data))\n\t\t{\n\t\t\tWLog_Print(drdynvc->log, WLOG_ERROR, \"data exceeding declared length!\");\n\t\t\tStream_Release(channel->dvc_data);\n\t\t\tchannel->dvc_data = NULL;\n\t\t\treturn ERROR_INVALID_DATA;\n\t\t}\n\n\t\tStream_Write(channel->dvc_data, Stream_Pointer(data), dataSize);\n\n\t\tif (Stream_GetPosition(channel->dvc_data) >= channel->dvc_data_length)\n\t\t{\n\t\t\tStream_SealLength(channel->dvc_data);\n\t\t\tStream_SetPosition(channel->dvc_data, 0);\n\t\t\tstatus = channel->channel_callback->OnDataReceived(channel->channel_callback,\n\t\t\t channel->dvc_data);\n\t\t\tStream_Release(channel->dvc_data);\n\t\t\tchannel->dvc_data = NULL;\n\t\t}\n\t}\n\telse\n\t{\n\t\tstatus = channel->channel_callback->OnDataReceived(channel->channel_callback,\n\t\t data);\n\t}\n\n\treturn status;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix for #4866: Added additional length checks'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {\n if (index >= dtypes_.size()) {\n return Status(errors::InvalidArgument(\n \"Index '\", index, \"' for key '\", key.scalar()(),\n \"' was out of bounds '\", dtypes_.size(), \"'.\"));\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: TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {\n if (tuple[index].has_value()) {\n return Status(errors::InvalidArgument(\n \"The tensor for index '\", index, \"' for key '\", key.scalar()(),\n \"' was already initialized '\", dtypes_.size(), \"'.\"));\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: ECDSA_PrivateKey::create_signature_op(RandomNumberGenerator& /*rng*/,\n const std::string& params,\n const std::string& provider) const\n {\n#if defined(BOTAN_HAS_BEARSSL)\n if(provider == \"bearssl\" || provider.empty())\n {\n try\n {\n return make_bearssl_ecdsa_sig_op(*this, params);\n }\n catch(Lookup_Error& e)\n {\n if(provider == \"bearssl\")\n throw;\n }\n }\n#endif\n\n#if defined(BOTAN_HAS_OPENSSL)\n if(provider == \"openssl\" || provider.empty())\n {\n try\n {\n return make_openssl_ecdsa_sig_op(*this, params);\n }\n catch(Lookup_Error& e)\n {\n if(provider == \"openssl\")\n throw;\n }\n }\n#endif\n\n if(provider == \"base\" || provider.empty())\n return std::unique_ptr(new ECDSA_Signature_Operation(*this, params));\n\n throw Provider_Not_Found(algo_name(), provider);\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Address DSA/ECDSA side channel'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int filter_frame(AVFilterLink *inlink, AVFrame *in)\n{\n AVFilterContext *ctx = inlink->dst;\n LutContext *s = ctx->priv;\n AVFilterLink *outlink = ctx->outputs[0];\n AVFrame *out;\n uint8_t *inrow, *outrow, *inrow0, *outrow0;\n int i, j, plane, direct = 0;\n\n if (av_frame_is_writable(in)) {\n direct = 1;\n out = in;\n } else {\n out = ff_get_video_buffer(outlink, outlink->w, outlink->h);\n if (!out) {\n av_frame_free(&in);\n return AVERROR(ENOMEM);\n }\n av_frame_copy_props(out, in);\n }\n\n if (s->is_rgb) {\n /* packed */\n inrow0 = in ->data[0];\n outrow0 = out->data[0];\n\n for (i = 0; i < in->height; i ++) {\n int w = inlink->w;\n const uint8_t (*tab)[256] = (const uint8_t (*)[256])s->lut;\n inrow = inrow0;\n outrow = outrow0;\n for (j = 0; j < w; j++) {\n switch (s->step) {\n case 4: outrow[3] = tab[3][inrow[3]]; // Fall-through\n case 3: outrow[2] = tab[2][inrow[2]]; // Fall-through\n case 2: outrow[1] = tab[1][inrow[1]]; // Fall-through\n default: outrow[0] = tab[0][inrow[0]];\n }\n outrow += s->step;\n inrow += s->step;\n }\n inrow0 += in ->linesize[0];\n outrow0 += out->linesize[0];\n }\n } else {\n /* planar */\n for (plane = 0; plane < 4 && in->data[plane]; plane++) {\n int vsub = plane == 1 || plane == 2 ? s->vsub : 0;\n int hsub = plane == 1 || plane == 2 ? s->hsub : 0;\n int h = FF_CEIL_RSHIFT(inlink->h, vsub);\n int w = FF_CEIL_RSHIFT(inlink->w, hsub);\n\n inrow = in ->data[plane];\n outrow = out->data[plane];\n\n for (i = 0; i < h; i++) {\n const uint8_t *tab = s->lut[plane];\n for (j = 0; j < w; j++)\n outrow[j] = tab[inrow[j]];\n inrow += in ->linesize[plane];\n outrow += out->linesize[plane];\n }\n }\n }\n\n if (!direct)\n av_frame_free(&in);\n\n return ff_filter_frame(outlink, 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 bool parse_reconnect(struct pool *pool, json_t *val)\n{\n\tchar *sockaddr_url, *stratum_port, *tmp;\n\tchar *url, *port, address[256];\n\n\tif (opt_disable_client_reconnect) {\n\t\tapplog(LOG_WARNING, \"Stratum client.reconnect forbidden, aborting.\");\n\t\treturn false;\n\t}\n\n\tmemset(address, 0, 255);\n\turl = (char *)json_string_value(json_array_get(val, 0));\n\tif (!url)\n\t\turl = pool->sockaddr_url;\n\n\tport = (char *)json_string_value(json_array_get(val, 1));\n\tif (!port)\n\t\tport = pool->stratum_port;\n\n\tsprintf(address, \"%s:%s\", url, port);\n\n\tif (!extract_sockaddr(address, &sockaddr_url, &stratum_port))\n\t\treturn false;\n\n\tapplog(LOG_NOTICE, \"Reconnect requested from %s to %s\", get_pool_name(pool), address);\n\n\tclear_pool_work(pool);\n\n\tmutex_lock(&pool->stratum_lock);\n\t__suspend_stratum(pool);\n\ttmp = pool->sockaddr_url;\n\tpool->sockaddr_url = sockaddr_url;\n\tpool->stratum_url = pool->sockaddr_url;\n\tfree(tmp);\n\ttmp = pool->stratum_port;\n\tpool->stratum_port = stratum_port;\n\tfree(tmp);\n\tmutex_unlock(&pool->stratum_lock);\n\n\tif (!restart_stratum(pool)) {\n\t\tpool_failed(pool);\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-119', 'CWE-787'], 'message': 'stratum: parse_reconnect(): treat pool-sent URL as untrusted.\n\nThanks to Mick Ayzenberg for reminding\nthat this existed and highlighting the offender.\n\nAlso to Luke-jr for actually fixing this in bfgminer. :D'" }, { "text": "[INST] Given the following code containing errors, provide Common 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\tconst char *safepath = SAFE_PATH;\n\tconst char *confpath = NULL;\n\tchar *shargv[] = { NULL, NULL };\n\tchar *sh;\n\tconst char *cmd;\n\tchar cmdline[LINE_MAX];\n\tchar myname[_PW_NAME_LEN + 1];\n\tstruct passwd *original_pw, *target_pw;\n\tstruct rule *rule;\n\tuid_t uid;\n\tuid_t target = 0;\n\tgid_t groups[NGROUPS_MAX + 1];\n\tint ngroups;\n\tint i, ch;\n\tint sflag = 0;\n\tint nflag = 0;\n\tchar cwdpath[PATH_MAX];\n\tconst char *cwd;\n\tchar *login_style = NULL;\n\tchar **envp;\n\n\t#ifndef linux\n\tsetprogname(\"doas\");\n\t#endif\n\n\t#ifndef linux\n\tclosefrom(STDERR_FILENO + 1);\n\t#endif\n\n\tuid = getuid();\n\n\twhile ((ch = getopt(argc, argv, \"a:C:nsu:\")) != -1) {\n/*\twhile ((ch = getopt(argc, argv, \"a:C:Lnsu:\")) != -1) { */\n\t\tswitch (ch) {\n\t\tcase 'a':\n\t\t\tlogin_style = optarg;\n\t\t\tbreak;\n\t\tcase 'C':\n\t\t\tconfpath = optarg;\n\t\t\tbreak;\n/*\t\tcase 'L':\n\t\t\ti = open(\"/dev/tty\", O_RDWR);\n\t\t\tif (i != -1)\n\t\t\t\tioctl(i, TIOCCLRVERAUTH);\n\t\t\texit(i != -1);\n*/\n\t\tcase 'u':\n\t\t\tif (parseuid(optarg, &target) != 0)\n\t\t\t\terrx(1, \"unknown user\");\n\t\t\tbreak;\n\t\tcase 'n':\n\t\t\tnflag = 1;\n\t\t\tbreak;\n\t\tcase 's':\n\t\t\tsflag = 1;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tusage();\n\t\t\tbreak;\n\t\t}\n\t}\n\targv += optind;\n\targc -= optind;\n\n\tif (confpath) {\n\t\tif (sflag)\n\t\t\tusage();\n\t} else if ((!sflag && !argc) || (sflag && argc))\n\t\tusage();\n\n\toriginal_pw = getpwuid(uid);\n\tif (! original_pw)\n\t\terr(1, \"getpwuid failed\");\n\tif (strlcpy(myname, original_pw->pw_name, sizeof(myname)) >= sizeof(myname))\n\t\terrx(1, \"pw_name too long\");\n\n\tngroups = getgroups(NGROUPS_MAX, groups);\n\tif (ngroups == -1)\n\t\terr(1, \"can't get groups\");\n\tgroups[ngroups++] = getgid();\n\n\tif (sflag) {\n\t\tsh = getenv(\"SHELL\");\n\t\tif (sh == NULL || *sh == '\\0') {\n\t\t\tshargv[0] = strdup(original_pw->pw_shell);\n\t\t\tif (shargv[0] == NULL)\n\t\t\t\terr(1, NULL);\n\t\t} else\n\t\t\tshargv[0] = sh;\n\t\targv = shargv;\n\t\targc = 1;\n\t}\n\n\tif (confpath) {\n\t\tcheckconfig(confpath, argc, argv, uid, groups, ngroups,\n\t\t target);\n\t\texit(1);\t/* fail safe */\n\t}\n\n\tif (geteuid())\n\t\terrx(1, \"not installed setuid\");\n\n\tparseconfig(DOAS_CONF, 1);\n\n\t/* cmdline is used only for logging, no need to abort on truncate */\n\t(void)strlcpy(cmdline, argv[0], sizeof(cmdline));\n\tfor (i = 1; i < argc; i++) {\n\t\tif (strlcat(cmdline, \" \", sizeof(cmdline)) >= sizeof(cmdline))\n\t\t\tbreak;\n\t\tif (strlcat(cmdline, argv[i], sizeof(cmdline)) >= sizeof(cmdline))\n\t\t\tbreak;\n\t}\n\n\tcmd = argv[0];\n\tif (!permit(uid, groups, ngroups, &rule, target, cmd,\n\t (const char **)argv + 1)) {\n\t\tsyslog(LOG_AUTHPRIV | LOG_NOTICE,\n\t\t \"failed command for %s: %s\", myname, cmdline);\n\t\terrc(1, EPERM, NULL);\n\t}\n\n\tif (!(rule->options & NOPASS)) {\n\t\tif (nflag)\n\t\t\terrx(1, \"Authorization required\");\n\n#if defined(USE_BSD_AUTH) \n\t\tauthuser(myname, login_style, rule->options & PERSIST);\n#elif defined(USE_PAM)\n#define PAM_END(msg) do { \t\t\t\t\t\t\\\n\tsyslog(LOG_ERR, \"%s: %s\", msg, pam_strerror(pamh, pam_err)); \t\\\n\twarnx(\"%s: %s\", msg, pam_strerror(pamh, pam_err));\t\t\\\n\tpam_end(pamh, pam_err);\t\t\t\t\t\t\\\n\texit(EXIT_FAILURE);\t\t\t\t\t\t\\\n} while (/*CONSTCOND*/0)\n\t\tpam_handle_t *pamh = NULL;\n\t\tint pam_err;\n\n/* #ifndef linux */\n\t\tint temp_stdin;\n\n\t\t/* openpam_ttyconv checks if stdin is a terminal and\n\t\t * if it is then does not bother to open /dev/tty.\n\t\t * The result is that PAM writes the password prompt\n\t\t * directly to stdout. In scenarios where stdin is a\n\t\t * terminal, but stdout is redirected to a file\n\t\t * e.g. by running doas ls &> ls.out interactively,\n\t\t * the password prompt gets written to ls.out as well.\n\t\t * By closing stdin first we forces PAM to read/write\n\t\t * to/from the terminal directly. We restore stdin\n\t\t * after authenticating. */\n\t\ttemp_stdin = dup(STDIN_FILENO);\n\t\tif (temp_stdin == -1)\n\t\t\terr(1, \"dup\");\n\t\tclose(STDIN_FILENO);\n/* #else */\n\t\t/* force password prompt to display on stderr, not stdout */\n\t\tint temp_stdout = dup(1);\n\t\tif (temp_stdout == -1)\n\t\t\terr(1, \"dup\");\n\t\tclose(1);\n\t\tif (dup2(2, 1) == -1)\n\t\t\terr(1, \"dup2\");\n/* #endif */\n\n\t\tpam_err = pam_start(\"doas\", myname, &pamc, &pamh);\n\t\tif (pam_err != PAM_SUCCESS) {\n\t\t\tif (pamh != NULL)\n\t\t\t\tPAM_END(\"pam_start\");\n\t\t\tsyslog(LOG_ERR, \"pam_start failed: %s\",\n\t\t\t pam_strerror(pamh, pam_err));\n\t\t\terrx(EXIT_FAILURE, \"pam_start failed\");\n\t\t}\n\n\t\tswitch (pam_err = pam_authenticate(pamh, PAM_SILENT)) {\n\t\tcase PAM_SUCCESS:\n\t\t\tswitch (pam_err = pam_acct_mgmt(pamh, PAM_SILENT)) {\n\t\t\tcase PAM_SUCCESS:\n\t\t\t\tbreak;\n\n\t\t\tcase PAM_NEW_AUTHTOK_REQD:\n\t\t\t\tpam_err = pam_chauthtok(pamh,\n\t\t\t\t PAM_SILENT|PAM_CHANGE_EXPIRED_AUTHTOK);\n\t\t\t\tif (pam_err != PAM_SUCCESS)\n\t\t\t\t\tPAM_END(\"pam_chauthtok\");\n\t\t\t\tbreak;\n\n\t\t\tcase PAM_AUTH_ERR:\n\t\t\tcase PAM_USER_UNKNOWN:\n\t\t\tcase PAM_MAXTRIES:\n\t\t\t\tsyslog(LOG_AUTHPRIV | LOG_NOTICE,\n\t\t\t\t \"failed auth for %s\", myname);\n errx(EXIT_FAILURE, \"second authentication failed\");\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tPAM_END(\"pam_acct_mgmt\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase PAM_AUTH_ERR:\n\t\tcase PAM_USER_UNKNOWN:\n\t\tcase PAM_MAXTRIES:\n\t\t\tsyslog(LOG_AUTHPRIV | LOG_NOTICE,\n\t\t\t \"failed auth for %s\", myname);\n errx(EXIT_FAILURE, \"authentication failed\");\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tPAM_END(\"pam_authenticate\");\n\t\t\tbreak;\n\t\t}\n\t\tpam_end(pamh, pam_err);\n\n#ifndef linux\n\t\t/* Re-establish stdin */\n\t\tif (dup2(temp_stdin, STDIN_FILENO) == -1)\n\t\t\terr(1, \"dup2\");\n\t\tclose(temp_stdin);\n#else \n\t\t/* Re-establish stdout */\n\t\tclose(1);\n\t\tif (dup2(temp_stdout, 1) == -1)\n\t\t\terr(1, \"dup2\");\n#endif\n#else\n#error\tNo auth module!\n#endif\n\t}\n\n /*\n\tif (pledge(\"stdio rpath getpw exec id\", NULL) == -1)\n\t\terr(1, \"pledge\");\n */\n\ttarget_pw = getpwuid(target);\n\tif (! target_pw)\n\t\terrx(1, \"no passwd entry for target\");\n\n#if defined(HAVE_LOGIN_CAP_H)\n\tif (setusercontext(NULL, target_pw, target, LOGIN_SETGROUP |\n\t LOGIN_SETPRIORITY | LOGIN_SETRESOURCES | LOGIN_SETUMASK |\n\t LOGIN_SETUSER) != 0)\n\t\terrx(1, \"failed to set user context for target\");\n#endif\n /*\n\tif (pledge(\"stdio rpath exec\", NULL) == -1)\n\t\terr(1, \"pledge\");\n */\n\n\tif (getcwd(cwdpath, sizeof(cwdpath)) == NULL)\n\t\tcwd = \"(failed)\";\n\telse\n\t\tcwd = cwdpath;\n\n\t/*\n if (pledge(\"stdio exec\", NULL) == -1)\n\t\terr(1, \"pledge\");\n */\n#ifndef HAVE_LOGIN_CAP_H\n /* If we effectively are root, set the UID to actually be root to avoid\n permission errors. */\n if (target != 0)\n setuid(target);\n if ( geteuid() == ROOT_UID )\n setuid(ROOT_UID);\n#endif\n\n\tsyslog(LOG_AUTHPRIV | LOG_INFO, \"%s ran command %s as %s from %s\",\n\t myname, cmdline, target_pw->pw_name, cwd);\n\n\tenvp = prepenv(rule, original_pw, target_pw);\n\n\tif (rule->cmd) {\n\t\tif (setenv(\"PATH\", safepath, 1) == -1)\n\t\t\terr(1, \"failed to set PATH '%s'\", safepath);\n\t}\n\texecvpe(cmd, argv, envp);\n\tif (errno == ENOENT)\n\t\terrx(1, \"%s: command not found\", cmd);\n\terr(1, \"%s\", cmd);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-269'], 'message': 'fix the setusercontext(3) workaround\n\nSeeing this being used on even more system like Illumos with this ugly\nand security critical bug open makes me cringe every time I check if it\nwas finally fixed.\n\nI reported it directly to the maintainer in 2017. I reported it to\npkgsrc-security@netbsd.org without a 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: parse_wcc_attr(netdissect_options *ndo,\n const uint32_t *dp)\n{\n\tND_PRINT((ndo, \" sz %\" PRIu64, EXTRACT_64BITS(&dp[0])));\n\tND_PRINT((ndo, \" mtime %u.%06u ctime %u.%06u\",\n\t EXTRACT_32BITS(&dp[2]), EXTRACT_32BITS(&dp[3]),\n\t EXTRACT_32BITS(&dp[4]), EXTRACT_32BITS(&dp[5])));\n\treturn (dp + 6);\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: grantpt (int fd)\n{\n int retval = -1;\n#ifdef PATH_MAX\n char _buf[PATH_MAX];\n#else\n char _buf[512];\n#endif\n char *buf = _buf;\n struct stat64 st;\n\n if (__builtin_expect (pts_name (fd, &buf, sizeof (_buf), &st), 0))\n {\n int save_errno = errno;\n\n /* Check, if the file descriptor is valid. pts_name returns the\n\t wrong errno number, so we cannot use that. */\n if (__libc_fcntl (fd, F_GETFD) == -1 && errno == EBADF)\n\treturn -1;\n\n /* If the filedescriptor is no TTY, grantpt has to set errno\n\t to EINVAL. */\n if (save_errno == ENOTTY)\n\t __set_errno (EINVAL);\n else\n\t __set_errno (save_errno);\n\n return -1;\n }\n\n /* Make sure that we own the device. */\n uid_t uid = __getuid ();\n if (st.st_uid != uid)\n {\n if (__chown (buf, uid, st.st_gid) < 0)\n\tgoto helper;\n }\n\n static int tty_gid = -1;\n if (__builtin_expect (tty_gid == -1, 0))\n {\n char *grtmpbuf;\n struct group grbuf;\n size_t grbuflen = __sysconf (_SC_GETGR_R_SIZE_MAX);\n struct group *p;\n\n /* Get the group ID of the special `tty' group. */\n if (grbuflen == (size_t) -1L)\n\t/* `sysconf' does not support _SC_GETGR_R_SIZE_MAX.\n\t Try a moderate value. */\n\tgrbuflen = 1024;\n grtmpbuf = (char *) __alloca (grbuflen);\n __getgrnam_r (TTY_GROUP, &grbuf, grtmpbuf, grbuflen, &p);\n if (p != NULL)\n\ttty_gid = p->gr_gid;\n }\n gid_t gid = tty_gid == -1 ? __getgid () : tty_gid;\n\n /* Make sure the group of the device is that special group. */\n if (st.st_gid != gid)\n {\n if (__chown (buf, uid, gid) < 0)\n\tgoto helper;\n }\n\n /* Make sure the permission mode is set to readable and writable by\n the owner, and writable by the group. */\n if ((st.st_mode & ACCESSPERMS) != (S_IRUSR|S_IWUSR|S_IWGRP))\n {\n if (__chmod (buf, S_IRUSR|S_IWUSR|S_IWGRP) < 0)\n\tgoto helper;\n }\n\n retval = 0;\n goto cleanup;\n\n /* We have to use the helper program. */\n helper:;\n\n pid_t pid = __fork ();\n if (pid == -1)\n goto cleanup;\n else if (pid == 0)\n {\n /* Disable core dumps. */\n struct rlimit rl = { 0, 0 };\n __setrlimit (RLIMIT_CORE, &rl);\n\n /* We pass the master pseudo terminal as file descriptor PTY_FILENO. */\n if (fd != PTY_FILENO)\n\tif (__dup2 (fd, PTY_FILENO) < 0)\n\t _exit (FAIL_EBADF);\n\n#ifdef CLOSE_ALL_FDS\n CLOSE_ALL_FDS ();\n#endif\n\n execle (_PATH_PT_CHOWN, basename (_PATH_PT_CHOWN), NULL, NULL);\n _exit (FAIL_EXEC);\n }\n else\n {\n int w;\n\n if (__waitpid (pid, &w, 0) == -1)\n\tgoto cleanup;\n if (!WIFEXITED (w))\n\t__set_errno (ENOEXEC);\n else\n\tswitch (WEXITSTATUS (w))\n\t {\n\t case 0:\n\t retval = 0;\n\t break;\n\t case FAIL_EBADF:\n\t __set_errno (EBADF);\n\t break;\n\t case FAIL_EINVAL:\n\t __set_errno (EINVAL);\n\t break;\n\t case FAIL_EACCES:\n\t __set_errno (EACCES);\n\t break;\n\t case FAIL_EXEC:\n\t __set_errno (ENOEXEC);\n\t break;\n\t case FAIL_ENOMEM:\n\t __set_errno (ENOMEM);\n\t break;\n\n\t default:\n\t assert(! \"getpt: internal error: invalid exit code from pt_chown\");\n\t }\n }\n\n cleanup:\n if (buf != _buf)\n free (buf);\n\n return retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284'], 'message': 'CVE-2013-2207, BZ #15755: Disable pt_chown.\n\nThe helper binary pt_chown tricked into granting access to another\nuser's pseudo-terminal.\n\nPre-conditions for the attack:\n\n * Attacker with local user account\n * Kernel with FUSE support\n * \"user_allow_other\" in /etc/fuse.conf\n * Victim with allocated slave in /dev/pts\n\nUsing the setuid installed pt_chown and a weak check on whether a file\ndescriptor is a tty, an attacker could fake a pty check using FUSE and\ntrick pt_chown to grant ownership of a pty descriptor that the current\nuser does not own. It cannot access /dev/pts/ptmx however.\n\nIn most modern distributions pt_chown is not needed because devpts\nis enabled by default. The fix for this CVE is to disable building\nand using pt_chown by default. We still provide a configure option\nto enable hte use of pt_chown but distributions do so at their own\nrisk.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void derive_boundaryStrength(de265_image* img, bool vertical, int yStart,int yEnd,\n int xStart,int xEnd)\n{\n int xIncr = vertical ? 2 : 1;\n int yIncr = vertical ? 1 : 2;\n int xOffs = vertical ? 1 : 0;\n int yOffs = vertical ? 0 : 1;\n int edgeMask = vertical ?\n (DEBLOCK_FLAG_VERTI | DEBLOCK_PB_EDGE_VERTI) :\n (DEBLOCK_FLAG_HORIZ | DEBLOCK_PB_EDGE_HORIZ);\n int transformEdgeMask = vertical ? DEBLOCK_FLAG_VERTI : DEBLOCK_FLAG_HORIZ;\n\n xEnd = libde265_min(xEnd,img->get_deblk_width());\n yEnd = libde265_min(yEnd,img->get_deblk_height());\n\n int TUShift = img->get_sps().Log2MinTrafoSize;\n int TUStride= img->get_sps().PicWidthInTbsY;\n\n for (int y=yStart;yget_deblk_flags(xDi,yDi) & edgeMask) ? \"edge\" : \"...\");\n\n uint8_t edgeFlags = img->get_deblk_flags(xDi,yDi);\n\n if (edgeFlags & edgeMask) {\n bool p_is_intra_pred = (img->get_pred_mode(xDi-xOffs, yDi-yOffs) == MODE_INTRA);\n bool q_is_intra_pred = (img->get_pred_mode(xDi, yDi ) == MODE_INTRA);\n\n int bS;\n\n if (p_is_intra_pred || q_is_intra_pred) {\n bS = 2;\n }\n else {\n // opposing site\n int xDiOpp = xDi-xOffs;\n int yDiOpp = yDi-yOffs;\n\n if ((edgeFlags & transformEdgeMask) &&\n (img->get_nonzero_coefficient(xDi ,yDi) ||\n img->get_nonzero_coefficient(xDiOpp,yDiOpp))) {\n bS = 1;\n }\n else {\n\n bS = 0;\n\n const PBMotion& mviP = img->get_mv_info(xDiOpp,yDiOpp);\n const PBMotion& mviQ = img->get_mv_info(xDi ,yDi);\n\n slice_segment_header* shdrP = img->get_SliceHeader(xDiOpp,yDiOpp);\n slice_segment_header* shdrQ = img->get_SliceHeader(xDi ,yDi);\n\n int refPicP0 = mviP.predFlag[0] ? shdrP->RefPicList[0][ mviP.refIdx[0] ] : -1;\n int refPicP1 = mviP.predFlag[1] ? shdrP->RefPicList[1][ mviP.refIdx[1] ] : -1;\n int refPicQ0 = mviQ.predFlag[0] ? shdrQ->RefPicList[0][ mviQ.refIdx[0] ] : -1;\n int refPicQ1 = mviQ.predFlag[1] ? shdrQ->RefPicList[1][ mviQ.refIdx[1] ] : -1;\n\n bool samePics = ((refPicP0==refPicQ0 && refPicP1==refPicQ1) ||\n (refPicP0==refPicQ1 && refPicP1==refPicQ0));\n\n if (!samePics) {\n bS = 1;\n }\n else {\n MotionVector mvP0 = mviP.mv[0]; if (!mviP.predFlag[0]) { mvP0.x=mvP0.y=0; }\n MotionVector mvP1 = mviP.mv[1]; if (!mviP.predFlag[1]) { mvP1.x=mvP1.y=0; }\n MotionVector mvQ0 = mviQ.mv[0]; if (!mviQ.predFlag[0]) { mvQ0.x=mvQ0.y=0; }\n MotionVector mvQ1 = mviQ.mv[1]; if (!mviQ.predFlag[1]) { mvQ1.x=mvQ1.y=0; }\n\n int numMV_P = mviP.predFlag[0] + mviP.predFlag[1];\n int numMV_Q = mviQ.predFlag[0] + mviQ.predFlag[1];\n\n if (numMV_P!=numMV_Q) {\n img->decctx->add_warning(DE265_WARNING_NUMMVP_NOT_EQUAL_TO_NUMMVQ, false);\n img->integrity = INTEGRITY_DECODING_ERRORS;\n }\n\n // two different reference pictures or only one reference picture\n if (refPicP0 != refPicP1) {\n\n if (refPicP0 == refPicQ0) {\n if (abs_value(mvP0.x-mvQ0.x) >= 4 ||\n abs_value(mvP0.y-mvQ0.y) >= 4 ||\n abs_value(mvP1.x-mvQ1.x) >= 4 ||\n abs_value(mvP1.y-mvQ1.y) >= 4) {\n bS = 1;\n }\n }\n else {\n if (abs_value(mvP0.x-mvQ1.x) >= 4 ||\n abs_value(mvP0.y-mvQ1.y) >= 4 ||\n abs_value(mvP1.x-mvQ0.x) >= 4 ||\n abs_value(mvP1.y-mvQ0.y) >= 4) {\n bS = 1;\n }\n }\n }\n else {\n assert(refPicQ0==refPicQ1);\n\n if ((abs_value(mvP0.x-mvQ0.x) >= 4 ||\n abs_value(mvP0.y-mvQ0.y) >= 4 ||\n abs_value(mvP1.x-mvQ1.x) >= 4 ||\n abs_value(mvP1.y-mvQ1.y) >= 4)\n &&\n (abs_value(mvP0.x-mvQ1.x) >= 4 ||\n abs_value(mvP0.y-mvQ1.y) >= 4 ||\n abs_value(mvP1.x-mvQ0.x) >= 4 ||\n abs_value(mvP1.y-mvQ0.y) >= 4)) {\n bS = 1;\n }\n }\n }\n\n /*\n printf(\"unimplemented deblocking code for CU at %d;%d\\n\",xDi,yDi);\n\n logerror(LogDeblock, \"unimplemented code reached (file %s, line %d)\\n\",\n __FILE__, __LINE__);\n */\n }\n }\n\n img->set_deblk_bS(xDi,yDi, bS);\n }\n else {\n img->set_deblk_bS(xDi,yDi, 0);\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'fix reading invalid images where shdr references are NULL in part of the image (#302)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: RCMS *r_pkcs7_parse_cms (const ut8 *buffer, ut32 length) {\n\tRASN1Object *object;\n\tRCMS *container;\n\tif (!buffer || !length) {\n\t\treturn NULL;\n\t}\n\tcontainer = R_NEW0 (RCMS);\n\tif (!container) {\n\t\treturn NULL;\n\t}\n\tobject = r_asn1_create_object (buffer, length);\n\tif (!object || object->list.length != 2 || !object->list.objects[0] || object->list.objects[1]->list.length != 1) {\n\t\tr_asn1_free_object (object);\n\t\tfree (container);\n\t\treturn NULL;\n\t}\n\tcontainer->contentType = r_asn1_stringify_oid (object->list.objects[0]->sector, object->list.objects[0]->length);\n\tr_pkcs7_parse_signeddata (&container->signedData, object->list.objects[1]->list.objects[0]);\n\tr_asn1_free_object (object);\n\treturn container;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix #7152 - Null deref in cms'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int samdb_msg_add_delval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,\n\t\t\t struct ldb_message *msg, const char *attr_name,\n\t\t\t const char *value)\n{\n\tstruct ldb_message_element *el;\n\tstruct ldb_val val, *vals;\n\tchar *v;\n\tunsigned int i;\n\tbool found = false;\n\tint ret;\n\n\tv = talloc_strdup(mem_ctx, value);\n\tif (v == NULL) {\n\t\treturn ldb_oom(sam_ldb);\n\t}\n\n\tval.data = (uint8_t *) v;\n\tval.length = strlen(v);\n\n\tif (val.length == 0) {\n\t\t/* allow empty strings as non-existent attributes */\n\t\treturn LDB_SUCCESS;\n\t}\n\n\tfor (i = 0; i < msg->num_elements; i++) {\n\t\tel = &msg->elements[i];\n\t\tif ((ldb_attr_cmp(el->name, attr_name) == 0) &&\n\t\t (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE)) {\n\t\t\tfound = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (!found) {\n\t\tret = ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_DELETE,\n\t\t\t\t\t&el);\n\t\tif (ret != LDB_SUCCESS) {\n\t\t\treturn ret;\n\t\t}\n\t}\n\n\tvals = talloc_realloc(msg->elements, el->values, struct ldb_val,\n\t\t\t el->num_values + 1);\n\tif (vals == NULL) {\n\t\treturn ldb_oom(sam_ldb);\n\t}\n\tel->values = vals;\n\tel->values[el->num_values] = val;\n\t++(el->num_values);\n\n\treturn LDB_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2022-32746 ldb: Ensure shallow copy modifications do not affect original message\n\nUsing the newly added ldb flag, we can now detect when a message has\nbeen shallow-copied so that its elements share their values with the\noriginal message elements. Then when adding values to the copied\nmessage, we now make a copy of the shared values array first.\n\nThis should prevent a use-after-free that occurred in LDB modules when\nnew values were added to a shallow copy of a message by calling\ntalloc_realloc() on the original values array, invalidating the 'values'\npointer in the original message element. The original values pointer can\nlater be used in the database audit logging module which logs database\nrequests, and potentially cause a crash.\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=15009\n\nSigned-off-by: Joseph Sutton '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: DecodeIPV6ExtHdrs(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t len, PacketQueue *pq)\n{\n SCEnter();\n\n uint8_t *orig_pkt = pkt;\n uint8_t nh = 0; /* careful, 0 is actually a real type */\n uint16_t hdrextlen = 0;\n uint16_t plen;\n char dstopts = 0;\n char exthdr_fh_done = 0;\n int hh = 0;\n int rh = 0;\n int eh = 0;\n int ah = 0;\n\n nh = IPV6_GET_NH(p);\n plen = len;\n\n while(1)\n {\n /* No upper layer, but we do have data. Suspicious. */\n if (nh == IPPROTO_NONE && plen > 0) {\n ENGINE_SET_EVENT(p, IPV6_DATA_AFTER_NONE_HEADER);\n SCReturn;\n }\n\n if (plen < 2) { /* minimal needed in a hdr */\n SCReturn;\n }\n\n switch(nh)\n {\n case IPPROTO_TCP:\n IPV6_SET_L4PROTO(p,nh);\n DecodeTCP(tv, dtv, p, pkt, plen, pq);\n SCReturn;\n\n case IPPROTO_UDP:\n IPV6_SET_L4PROTO(p,nh);\n DecodeUDP(tv, dtv, p, pkt, plen, pq);\n SCReturn;\n\n case IPPROTO_ICMPV6:\n IPV6_SET_L4PROTO(p,nh);\n DecodeICMPV6(tv, dtv, p, pkt, plen, pq);\n SCReturn;\n\n case IPPROTO_SCTP:\n IPV6_SET_L4PROTO(p,nh);\n DecodeSCTP(tv, dtv, p, pkt, plen, pq);\n SCReturn;\n\n case IPPROTO_ROUTING:\n IPV6_SET_L4PROTO(p,nh);\n hdrextlen = 8 + (*(pkt+1) * 8); /* 8 bytes + length in 8 octet units */\n\n SCLogDebug(\"hdrextlen %\"PRIu8, hdrextlen);\n\n if (hdrextlen > plen) {\n ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR);\n SCReturn;\n }\n\n if (rh) {\n ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_RH);\n /* skip past this extension so we can continue parsing the rest\n * of the packet */\n nh = *pkt;\n pkt += hdrextlen;\n plen -= hdrextlen;\n break;\n }\n\n rh = 1;\n IPV6_EXTHDR_SET_RH(p);\n\n uint8_t ip6rh_type = *(pkt + 2);\n if (ip6rh_type == 0) {\n ENGINE_SET_EVENT(p, IPV6_EXTHDR_RH_TYPE_0);\n }\n p->ip6eh.rh_type = ip6rh_type;\n\n nh = *pkt;\n pkt += hdrextlen;\n plen -= hdrextlen;\n break;\n\n case IPPROTO_HOPOPTS:\n case IPPROTO_DSTOPTS:\n {\n IPV6OptHAO hao_s, *hao = &hao_s;\n IPV6OptRA ra_s, *ra = &ra_s;\n IPV6OptJumbo jumbo_s, *jumbo = &jumbo_s;\n uint16_t optslen = 0;\n\n IPV6_SET_L4PROTO(p,nh);\n hdrextlen = (*(pkt+1) + 1) << 3;\n if (hdrextlen > plen) {\n ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR);\n SCReturn;\n }\n\n uint8_t *ptr = pkt + 2; /* +2 to go past nxthdr and len */\n\n /* point the pointers to right structures\n * in Packet. */\n if (nh == IPPROTO_HOPOPTS) {\n if (hh) {\n ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_HH);\n /* skip past this extension so we can continue parsing the rest\n * of the packet */\n nh = *pkt;\n pkt += hdrextlen;\n plen -= hdrextlen;\n break;\n }\n\n hh = 1;\n\n optslen = ((*(pkt + 1) + 1 ) << 3) - 2;\n }\n else if (nh == IPPROTO_DSTOPTS)\n {\n if (dstopts == 0) {\n optslen = ((*(pkt + 1) + 1 ) << 3) - 2;\n dstopts = 1;\n } else if (dstopts == 1) {\n optslen = ((*(pkt + 1) + 1 ) << 3) - 2;\n dstopts = 2;\n } else {\n ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_DH);\n /* skip past this extension so we can continue parsing the rest\n * of the packet */\n nh = *pkt;\n pkt += hdrextlen;\n plen -= hdrextlen;\n break;\n }\n }\n\n if (optslen > plen) {\n /* since the packet is long enough (we checked\n * plen against hdrlen, the optlen must be malformed. */\n ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);\n /* skip past this extension so we can continue parsing the rest\n * of the packet */\n nh = *pkt;\n pkt += hdrextlen;\n plen -= hdrextlen;\n break;\n }\n/** \\todo move into own function to loaded on demand */\n uint16_t padn_cnt = 0;\n uint16_t other_cnt = 0;\n uint16_t offset = 0;\n while(offset < optslen)\n {\n if (*ptr == IPV6OPT_PAD1)\n {\n padn_cnt++;\n offset++;\n ptr++;\n continue;\n }\n\n if (offset + 1 >= optslen) {\n ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);\n break;\n }\n\n /* length field for each opt */\n uint8_t ip6_optlen = *(ptr + 1);\n\n /* see if the optlen from the packet fits the total optslen */\n if ((offset + 1 + ip6_optlen) > optslen) {\n ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);\n break;\n }\n\n if (*ptr == IPV6OPT_PADN) /* PadN */\n {\n //printf(\"PadN option\\n\");\n padn_cnt++;\n\n /* a zero padN len would be weird */\n if (ip6_optlen == 0)\n ENGINE_SET_EVENT(p, IPV6_EXTHDR_ZERO_LEN_PADN);\n }\n else if (*ptr == IPV6OPT_RA) /* RA */\n {\n ra->ip6ra_type = *(ptr);\n ra->ip6ra_len = ip6_optlen;\n\n if (ip6_optlen < sizeof(ra->ip6ra_value)) {\n ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);\n break;\n }\n\n memcpy(&ra->ip6ra_value, (ptr + 2), sizeof(ra->ip6ra_value));\n ra->ip6ra_value = SCNtohs(ra->ip6ra_value);\n //printf(\"RA option: type %\" PRIu32 \" len %\" PRIu32 \" value %\" PRIu32 \"\\n\",\n // ra->ip6ra_type, ra->ip6ra_len, ra->ip6ra_value);\n other_cnt++;\n }\n else if (*ptr == IPV6OPT_JUMBO) /* Jumbo */\n {\n jumbo->ip6j_type = *(ptr);\n jumbo->ip6j_len = ip6_optlen;\n\n if (ip6_optlen < sizeof(jumbo->ip6j_payload_len)) {\n ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);\n break;\n }\n\n memcpy(&jumbo->ip6j_payload_len, (ptr+2), sizeof(jumbo->ip6j_payload_len));\n jumbo->ip6j_payload_len = SCNtohl(jumbo->ip6j_payload_len);\n //printf(\"Jumbo option: type %\" PRIu32 \" len %\" PRIu32 \" payload len %\" PRIu32 \"\\n\",\n // jumbo->ip6j_type, jumbo->ip6j_len, jumbo->ip6j_payload_len);\n }\n else if (*ptr == IPV6OPT_HAO) /* HAO */\n {\n hao->ip6hao_type = *(ptr);\n hao->ip6hao_len = ip6_optlen;\n\n if (ip6_optlen < sizeof(hao->ip6hao_hoa)) {\n ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);\n break;\n }\n\n memcpy(&hao->ip6hao_hoa, (ptr+2), sizeof(hao->ip6hao_hoa));\n //printf(\"HAO option: type %\" PRIu32 \" len %\" PRIu32 \" \",\n // hao->ip6hao_type, hao->ip6hao_len);\n //char addr_buf[46];\n //PrintInet(AF_INET6, (char *)&(hao->ip6hao_hoa),\n // addr_buf,sizeof(addr_buf));\n //printf(\"home addr %s\\n\", addr_buf);\n other_cnt++;\n } else {\n if (nh == IPPROTO_HOPOPTS)\n ENGINE_SET_EVENT(p, IPV6_HOPOPTS_UNKNOWN_OPT);\n else\n ENGINE_SET_EVENT(p, IPV6_DSTOPTS_UNKNOWN_OPT);\n\n other_cnt++;\n }\n uint16_t optlen = (*(ptr + 1) + 2);\n ptr += optlen; /* +2 for opt type and opt len fields */\n offset += optlen;\n }\n /* flag packets that have only padding */\n if (padn_cnt > 0 && other_cnt == 0) {\n if (nh == IPPROTO_HOPOPTS)\n ENGINE_SET_EVENT(p, IPV6_HOPOPTS_ONLY_PADDING);\n else\n ENGINE_SET_EVENT(p, IPV6_DSTOPTS_ONLY_PADDING);\n }\n\n nh = *pkt;\n pkt += hdrextlen;\n plen -= hdrextlen;\n break;\n }\n\n case IPPROTO_FRAGMENT:\n {\n IPV6_SET_L4PROTO(p,nh);\n /* store the offset of this extension into the packet\n * past the ipv6 header. We use it in defrag for creating\n * a defragmented packet without the frag header */\n if (exthdr_fh_done == 0) {\n p->ip6eh.fh_offset = pkt - orig_pkt;\n exthdr_fh_done = 1;\n }\n\n uint16_t prev_hdrextlen = hdrextlen;\n hdrextlen = sizeof(IPV6FragHdr);\n if (hdrextlen > plen) {\n ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR);\n SCReturn;\n }\n\n /* for the frag header, the length field is reserved */\n if (*(pkt + 1) != 0) {\n ENGINE_SET_EVENT(p, IPV6_FH_NON_ZERO_RES_FIELD);\n /* non fatal, lets try to continue */\n }\n\n if (IPV6_EXTHDR_ISSET_FH(p)) {\n ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_FH);\n nh = *pkt;\n pkt += hdrextlen;\n plen -= hdrextlen;\n break;\n }\n\n /* set the header flag first */\n IPV6_EXTHDR_SET_FH(p);\n\n /* parse the header and setup the vars */\n DecodeIPV6FragHeader(p, pkt, hdrextlen, plen, prev_hdrextlen);\n\n /* if FH has offset 0 and no more fragments are coming, we\n * parse this packet further right away, no defrag will be\n * needed. It is a useless FH then though, so we do set an\n * decoder event. */\n if (p->ip6eh.fh_more_frags_set == 0 && p->ip6eh.fh_offset == 0) {\n ENGINE_SET_EVENT(p, IPV6_EXTHDR_USELESS_FH);\n\n nh = *pkt;\n pkt += hdrextlen;\n plen -= hdrextlen;\n break;\n }\n\n /* the rest is parsed upon reassembly */\n p->flags |= PKT_IS_FRAGMENT;\n SCReturn;\n }\n case IPPROTO_ESP:\n {\n IPV6_SET_L4PROTO(p,nh);\n hdrextlen = sizeof(IPV6EspHdr);\n if (hdrextlen > plen) {\n ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR);\n SCReturn;\n }\n\n if (eh) {\n ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_EH);\n SCReturn;\n }\n\n eh = 1;\n\n nh = IPPROTO_NONE;\n pkt += hdrextlen;\n plen -= hdrextlen;\n break;\n }\n case IPPROTO_AH:\n {\n IPV6_SET_L4PROTO(p,nh);\n /* we need the header as a minimum */\n hdrextlen = sizeof(IPV6AuthHdr);\n /* the payload len field is the number of extra 4 byte fields,\n * IPV6AuthHdr already contains the first */\n if (*(pkt+1) > 0)\n hdrextlen += ((*(pkt+1) - 1) * 4);\n\n SCLogDebug(\"hdrextlen %\"PRIu8, hdrextlen);\n\n if (hdrextlen > plen) {\n ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR);\n SCReturn;\n }\n\n IPV6AuthHdr *ahhdr = (IPV6AuthHdr *)pkt;\n if (ahhdr->ip6ah_reserved != 0x0000) {\n ENGINE_SET_EVENT(p, IPV6_EXTHDR_AH_RES_NOT_NULL);\n }\n\n if (ah) {\n ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_AH);\n nh = *pkt;\n pkt += hdrextlen;\n plen -= hdrextlen;\n break;\n }\n\n ah = 1;\n\n nh = *pkt;\n pkt += hdrextlen;\n plen -= hdrextlen;\n break;\n }\n case IPPROTO_IPIP:\n IPV6_SET_L4PROTO(p,nh);\n DecodeIPv4inIPv6(tv, dtv, p, pkt, plen, pq);\n SCReturn;\n /* none, last header */\n case IPPROTO_NONE:\n IPV6_SET_L4PROTO(p,nh);\n SCReturn;\n case IPPROTO_ICMP:\n ENGINE_SET_EVENT(p,IPV6_WITH_ICMPV4);\n SCReturn;\n /* no parsing yet, just skip it */\n case IPPROTO_MH:\n case IPPROTO_HIP:\n case IPPROTO_SHIM6:\n hdrextlen = 8 + (*(pkt+1) * 8); /* 8 bytes + length in 8 octet units */\n if (hdrextlen > plen) {\n ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR);\n SCReturn;\n }\n nh = *pkt;\n pkt += hdrextlen;\n plen -= hdrextlen;\n break;\n default:\n ENGINE_SET_EVENT(p, IPV6_UNKNOWN_NEXT_HEADER);\n IPV6_SET_L4PROTO(p,nh);\n SCReturn;\n }\n }\n\n SCReturn;\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: escape_xml(const char *text)\n{\n\tstatic char *escaped;\n\tstatic size_t escaped_size;\n\tchar *out;\n\tsize_t len;\n\n\tif (!strlen(text)) return \"empty string\";\n\n\tfor (out=escaped, len=0; *text; ++len, ++out, ++text) {\n\t\t/* Make sure there's plenty of room for a quoted character */\n\t\tif ((len + 8) > escaped_size) {\n\t\t\tchar *bigger_escaped;\n\t\t\tescaped_size += 128;\n\t\t\tbigger_escaped = realloc(escaped, escaped_size);\n\t\t\tif (!bigger_escaped) {\n\t\t\t\tfree(escaped);\t/* avoid leaking memory */\n\t\t\t\tescaped = NULL;\n\t\t\t\tescaped_size = 0;\n\t\t\t\t/* Error string is cleverly chosen to fail XML validation */\n\t\t\t\treturn \">>> out of memory <<<\";\n\t\t\t}\n\t\t\tout = bigger_escaped + len;\n\t\t\tescaped = bigger_escaped;\n\t\t}\n\t\tswitch (*text) {\n\t\t\tcase '&':\n\t\t\t\tstrcpy(out, \"&\");\n\t\t\t\tlen += strlen(out) - 1;\n\t\t\t\tout = escaped + len;\n\t\t\t\tbreak;\n\t\t\tcase '<':\n\t\t\t\tstrcpy(out, \"<\");\n\t\t\t\tlen += strlen(out) - 1;\n\t\t\t\tout = escaped + len;\n\t\t\t\tbreak;\n\t\t\tcase '>':\n\t\t\t\tstrcpy(out, \">\");\n\t\t\t\tlen += strlen(out) - 1;\n\t\t\t\tout = escaped + len;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t*out = *text;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t*out = '\\x0'; /* NUL terminate the string */\n\treturn escaped;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'actually return empty stringand not 'em,pty string' 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 int session_new(nghttp2_session **session_ptr,\n const nghttp2_session_callbacks *callbacks,\n void *user_data, int server,\n const nghttp2_option *option, nghttp2_mem *mem) {\n int rv;\n size_t nbuffer;\n size_t max_deflate_dynamic_table_size =\n NGHTTP2_HD_DEFAULT_MAX_DEFLATE_BUFFER_SIZE;\n\n if (mem == NULL) {\n mem = nghttp2_mem_default();\n }\n\n *session_ptr = nghttp2_mem_calloc(mem, 1, sizeof(nghttp2_session));\n if (*session_ptr == NULL) {\n rv = NGHTTP2_ERR_NOMEM;\n goto fail_session;\n }\n\n (*session_ptr)->mem = *mem;\n mem = &(*session_ptr)->mem;\n\n /* next_stream_id is initialized in either\n nghttp2_session_client_new2 or nghttp2_session_server_new2 */\n\n nghttp2_stream_init(&(*session_ptr)->root, 0, NGHTTP2_STREAM_FLAG_NONE,\n NGHTTP2_STREAM_IDLE, NGHTTP2_DEFAULT_WEIGHT, 0, 0, NULL,\n mem);\n\n (*session_ptr)->remote_window_size = NGHTTP2_INITIAL_CONNECTION_WINDOW_SIZE;\n (*session_ptr)->recv_window_size = 0;\n (*session_ptr)->consumed_size = 0;\n (*session_ptr)->recv_reduction = 0;\n (*session_ptr)->local_window_size = NGHTTP2_INITIAL_CONNECTION_WINDOW_SIZE;\n\n (*session_ptr)->goaway_flags = NGHTTP2_GOAWAY_NONE;\n (*session_ptr)->local_last_stream_id = (1u << 31) - 1;\n (*session_ptr)->remote_last_stream_id = (1u << 31) - 1;\n\n (*session_ptr)->pending_local_max_concurrent_stream =\n NGHTTP2_DEFAULT_MAX_CONCURRENT_STREAMS;\n (*session_ptr)->pending_enable_push = 1;\n\n if (server) {\n (*session_ptr)->server = 1;\n }\n\n init_settings(&(*session_ptr)->remote_settings);\n init_settings(&(*session_ptr)->local_settings);\n\n (*session_ptr)->max_incoming_reserved_streams =\n NGHTTP2_MAX_INCOMING_RESERVED_STREAMS;\n\n /* Limit max outgoing concurrent streams to sensible value */\n (*session_ptr)->remote_settings.max_concurrent_streams = 100;\n\n (*session_ptr)->max_send_header_block_length = NGHTTP2_MAX_HEADERSLEN;\n (*session_ptr)->max_outbound_ack = NGHTTP2_DEFAULT_MAX_OBQ_FLOOD_ITEM;\n\n if (option) {\n if ((option->opt_set_mask & NGHTTP2_OPT_NO_AUTO_WINDOW_UPDATE) &&\n option->no_auto_window_update) {\n\n (*session_ptr)->opt_flags |= NGHTTP2_OPTMASK_NO_AUTO_WINDOW_UPDATE;\n }\n\n if (option->opt_set_mask & NGHTTP2_OPT_PEER_MAX_CONCURRENT_STREAMS) {\n\n (*session_ptr)->remote_settings.max_concurrent_streams =\n option->peer_max_concurrent_streams;\n }\n\n if (option->opt_set_mask & NGHTTP2_OPT_MAX_RESERVED_REMOTE_STREAMS) {\n\n (*session_ptr)->max_incoming_reserved_streams =\n option->max_reserved_remote_streams;\n }\n\n if ((option->opt_set_mask & NGHTTP2_OPT_NO_RECV_CLIENT_MAGIC) &&\n option->no_recv_client_magic) {\n\n (*session_ptr)->opt_flags |= NGHTTP2_OPTMASK_NO_RECV_CLIENT_MAGIC;\n }\n\n if ((option->opt_set_mask & NGHTTP2_OPT_NO_HTTP_MESSAGING) &&\n option->no_http_messaging) {\n\n (*session_ptr)->opt_flags |= NGHTTP2_OPTMASK_NO_HTTP_MESSAGING;\n }\n\n if (option->opt_set_mask & NGHTTP2_OPT_USER_RECV_EXT_TYPES) {\n memcpy((*session_ptr)->user_recv_ext_types, option->user_recv_ext_types,\n sizeof((*session_ptr)->user_recv_ext_types));\n }\n\n if (option->opt_set_mask & NGHTTP2_OPT_BUILTIN_RECV_EXT_TYPES) {\n (*session_ptr)->builtin_recv_ext_types = option->builtin_recv_ext_types;\n }\n\n if ((option->opt_set_mask & NGHTTP2_OPT_NO_AUTO_PING_ACK) &&\n option->no_auto_ping_ack) {\n (*session_ptr)->opt_flags |= NGHTTP2_OPTMASK_NO_AUTO_PING_ACK;\n }\n\n if (option->opt_set_mask & NGHTTP2_OPT_MAX_SEND_HEADER_BLOCK_LENGTH) {\n (*session_ptr)->max_send_header_block_length =\n option->max_send_header_block_length;\n }\n\n if (option->opt_set_mask & NGHTTP2_OPT_MAX_DEFLATE_DYNAMIC_TABLE_SIZE) {\n max_deflate_dynamic_table_size = option->max_deflate_dynamic_table_size;\n }\n\n if ((option->opt_set_mask & NGHTTP2_OPT_NO_CLOSED_STREAMS) &&\n option->no_closed_streams) {\n (*session_ptr)->opt_flags |= NGHTTP2_OPTMASK_NO_CLOSED_STREAMS;\n }\n\n if (option->opt_set_mask & NGHTTP2_OPT_MAX_OUTBOUND_ACK) {\n (*session_ptr)->max_outbound_ack = option->max_outbound_ack;\n }\n }\n\n rv = nghttp2_hd_deflate_init2(&(*session_ptr)->hd_deflater,\n max_deflate_dynamic_table_size, mem);\n if (rv != 0) {\n goto fail_hd_deflater;\n }\n rv = nghttp2_hd_inflate_init(&(*session_ptr)->hd_inflater, mem);\n if (rv != 0) {\n goto fail_hd_inflater;\n }\n rv = nghttp2_map_init(&(*session_ptr)->streams, mem);\n if (rv != 0) {\n goto fail_map;\n }\n\n nbuffer = ((*session_ptr)->max_send_header_block_length +\n NGHTTP2_FRAMEBUF_CHUNKLEN - 1) /\n NGHTTP2_FRAMEBUF_CHUNKLEN;\n\n if (nbuffer == 0) {\n nbuffer = 1;\n }\n\n /* 1 for Pad Field. */\n rv = nghttp2_bufs_init3(&(*session_ptr)->aob.framebufs,\n NGHTTP2_FRAMEBUF_CHUNKLEN, nbuffer, 1,\n NGHTTP2_FRAME_HDLEN + 1, mem);\n if (rv != 0) {\n goto fail_aob_framebuf;\n }\n\n active_outbound_item_reset(&(*session_ptr)->aob, mem);\n\n (*session_ptr)->callbacks = *callbacks;\n (*session_ptr)->user_data = user_data;\n\n session_inbound_frame_reset(*session_ptr);\n\n if (nghttp2_enable_strict_preface) {\n nghttp2_inbound_frame *iframe = &(*session_ptr)->iframe;\n\n if (server && ((*session_ptr)->opt_flags &\n NGHTTP2_OPTMASK_NO_RECV_CLIENT_MAGIC) == 0) {\n iframe->state = NGHTTP2_IB_READ_CLIENT_MAGIC;\n iframe->payloadleft = NGHTTP2_CLIENT_MAGIC_LEN;\n } else {\n iframe->state = NGHTTP2_IB_READ_FIRST_SETTINGS;\n }\n\n if (!server) {\n (*session_ptr)->aob.state = NGHTTP2_OB_SEND_CLIENT_MAGIC;\n nghttp2_bufs_add(&(*session_ptr)->aob.framebufs, NGHTTP2_CLIENT_MAGIC,\n NGHTTP2_CLIENT_MAGIC_LEN);\n }\n }\n\n return 0;\n\nfail_aob_framebuf:\n nghttp2_map_free(&(*session_ptr)->streams);\nfail_map:\n nghttp2_hd_inflate_free(&(*session_ptr)->hd_inflater);\nfail_hd_inflater:\n nghttp2_hd_deflate_free(&(*session_ptr)->hd_deflater);\nfail_hd_deflater:\n nghttp2_mem_free(mem, *session_ptr);\nfail_session:\n return rv;\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: static int read_part_of_packet(AVFormatContext *s, int64_t *pts,\n int *len, int *strid, int read_packet) {\n AVIOContext *pb = s->pb;\n PVAContext *pvactx = s->priv_data;\n int syncword, streamid, reserved, flags, length, pts_flag;\n int64_t pva_pts = AV_NOPTS_VALUE, startpos;\n int ret;\n\nrecover:\n startpos = avio_tell(pb);\n\n syncword = avio_rb16(pb);\n streamid = avio_r8(pb);\n avio_r8(pb); /* counter not used */\n reserved = avio_r8(pb);\n flags = avio_r8(pb);\n length = avio_rb16(pb);\n\n pts_flag = flags & 0x10;\n\n if (syncword != PVA_MAGIC) {\n pva_log(s, AV_LOG_ERROR, \"invalid syncword\\n\");\n return AVERROR(EIO);\n }\n if (streamid != PVA_VIDEO_PAYLOAD && streamid != PVA_AUDIO_PAYLOAD) {\n pva_log(s, AV_LOG_ERROR, \"invalid streamid\\n\");\n return AVERROR(EIO);\n }\n if (reserved != 0x55) {\n pva_log(s, AV_LOG_WARNING, \"expected reserved byte to be 0x55\\n\");\n }\n if (length > PVA_MAX_PAYLOAD_LENGTH) {\n pva_log(s, AV_LOG_ERROR, \"invalid payload length %u\\n\", length);\n return AVERROR(EIO);\n }\n\n if (streamid == PVA_VIDEO_PAYLOAD && pts_flag) {\n pva_pts = avio_rb32(pb);\n length -= 4;\n } else if (streamid == PVA_AUDIO_PAYLOAD) {\n /* PVA Audio Packets either start with a signaled PES packet or\n * are a continuation of the previous PES packet. New PES packets\n * always start at the beginning of a PVA Packet, never somewhere in\n * the middle. */\n if (!pvactx->continue_pes) {\n int pes_signal, pes_header_data_length, pes_packet_length,\n pes_flags;\n unsigned char pes_header_data[256];\n\n pes_signal = avio_rb24(pb);\n avio_r8(pb);\n pes_packet_length = avio_rb16(pb);\n pes_flags = avio_rb16(pb);\n pes_header_data_length = avio_r8(pb);\n\n if (pes_signal != 1 || pes_header_data_length == 0) {\n pva_log(s, AV_LOG_WARNING, \"expected non empty signaled PES packet, \"\n \"trying to recover\\n\");\n avio_skip(pb, length - 9);\n if (!read_packet)\n return AVERROR(EIO);\n goto recover;\n }\n\n ret = avio_read(pb, pes_header_data, pes_header_data_length);\n if (ret != pes_header_data_length)\n return ret < 0 ? ret : AVERROR_INVALIDDATA;\n length -= 9 + pes_header_data_length;\n\n pes_packet_length -= 3 + pes_header_data_length;\n\n pvactx->continue_pes = pes_packet_length;\n\n if (pes_flags & 0x80 && (pes_header_data[0] & 0xf0) == 0x20) {\n if (pes_header_data_length < 5) {\n pva_log(s, AV_LOG_ERROR, \"header too short\\n\");\n avio_skip(pb, length);\n return AVERROR_INVALIDDATA;\n }\n pva_pts = ff_parse_pes_pts(pes_header_data);\n }\n }\n\n pvactx->continue_pes -= length;\n\n if (pvactx->continue_pes < 0) {\n pva_log(s, AV_LOG_WARNING, \"audio data corruption\\n\");\n pvactx->continue_pes = 0;\n }\n }\n\n if (pva_pts != AV_NOPTS_VALUE)\n av_add_index_entry(s->streams[streamid-1], startpos, pva_pts, 0, 0, AVINDEX_KEYFRAME);\n\n *pts = pva_pts;\n *len = length;\n *strid = streamid;\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'avformat/pva: Check for EOF before retrying in read_part_of_packet()\n\nFixes: Infinite loop\nFixes: pva-4b1835dbc2027bf3c567005dcc78e85199240d06\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: TEE_Result syscall_hash_init(unsigned long state,\n\t\t\t const void *iv __maybe_unused,\n\t\t\t size_t iv_len __maybe_unused)\n{\n\tTEE_Result res;\n\tstruct tee_cryp_state *cs;\n\tstruct tee_ta_session *sess;\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\tswitch (TEE_ALG_GET_CLASS(cs->algo)) {\n\tcase TEE_OPERATION_DIGEST:\n\t\tres = crypto_hash_init(cs->ctx, cs->algo);\n\t\tif (res != TEE_SUCCESS)\n\t\t\treturn res;\n\t\tbreak;\n\tcase TEE_OPERATION_MAC:\n\t\t{\n\t\t\tstruct tee_obj *o;\n\t\t\tstruct tee_cryp_obj_secret *key;\n\n\t\t\tres = tee_obj_get(to_user_ta_ctx(sess->ctx),\n\t\t\t\t\t cs->key1, &o);\n\t\t\tif (res != TEE_SUCCESS)\n\t\t\t\treturn res;\n\t\t\tif ((o->info.handleFlags &\n\t\t\t TEE_HANDLE_FLAG_INITIALIZED) == 0)\n\t\t\t\treturn TEE_ERROR_BAD_PARAMETERS;\n\n\t\t\tkey = (struct tee_cryp_obj_secret *)o->attr;\n\t\t\tres = crypto_mac_init(cs->ctx, cs->algo,\n\t\t\t\t\t (void *)(key + 1), key->key_size);\n\t\t\tif (res != TEE_SUCCESS)\n\t\t\t\treturn res;\n\t\t\tbreak;\n\t\t}\n\tdefault:\n\t\treturn TEE_ERROR_BAD_PARAMETERS;\n\t}\n\n\treturn TEE_SUCCESS;\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: FilterConfigSharedPtr getConfig() {\n envoy::extensions::filters::http::oauth2::v3::OAuth2Config p;\n auto* endpoint = p.mutable_token_endpoint();\n endpoint->set_cluster(\"auth.example.com\");\n endpoint->set_uri(\"auth.example.com/_oauth\");\n endpoint->mutable_timeout()->set_seconds(1);\n p.set_redirect_uri(\"%REQ(:scheme)%://%REQ(:authority)%\" + TEST_CALLBACK);\n p.mutable_redirect_path_matcher()->mutable_path()->set_exact(TEST_CALLBACK);\n p.set_authorization_endpoint(\"https://auth.example.com/oauth/authorize/\");\n p.mutable_signout_path()->mutable_path()->set_exact(\"/_signout\");\n p.set_forward_bearer_token(true);\n p.add_auth_scopes(\"user\");\n p.add_auth_scopes(\"openid\");\n p.add_auth_scopes(\"email\");\n p.add_resources(\"oauth2-resource\");\n p.add_resources(\"http://example.com\");\n p.add_resources(\"https://example.com\");\n auto* matcher = p.add_pass_through_matcher();\n matcher->set_name(\":method\");\n matcher->mutable_string_match()->set_exact(\"OPTIONS\");\n auto credentials = p.mutable_credentials();\n credentials->set_client_id(TEST_CLIENT_ID);\n credentials->mutable_token_secret()->set_name(\"secret\");\n credentials->mutable_hmac_secret()->set_name(\"hmac\");\n // Skipping setting credentials.cookie_names field should give default cookie names:\n // BearerToken, OauthHMAC, and OauthExpires.\n\n MessageUtil::validate(p, ProtobufMessage::getStrictValidationVisitor());\n\n // Create filter config.\n auto secret_reader = std::make_shared();\n FilterConfigSharedPtr c = std::make_shared(p, factory_context_.cluster_manager_,\n secret_reader, scope_, \"test.\");\n\n return c;\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: void CLASS parse_qt (int end)\n{\n unsigned save, size;\n char tag[4];\n\n order = 0x4d4d;\n while (ftell(ifp)+7 < end) {\n save = ftell(ifp);\n if ((size = get4()) < 8) return;\n fread (tag, 4, 1, ifp);\n if (!memcmp(tag,\"moov\",4) ||\n\t!memcmp(tag,\"udta\",4) ||\n\t!memcmp(tag,\"CNTH\",4))\n parse_qt (save+size);\n if (!memcmp(tag,\"CNDA\",4))\n parse_jpeg (ftell(ifp));\n fseek (ifp, save+size, SEEK_SET);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'parse_qt: 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: static unsigned xen_netbk_tx_build_gops(struct xen_netbk *netbk)\n{\n\tstruct gnttab_copy *gop = netbk->tx_copy_ops, *request_gop;\n\tstruct sk_buff *skb;\n\tint ret;\n\n\twhile (((nr_pending_reqs(netbk) + MAX_SKB_FRAGS) < MAX_PENDING_REQS) &&\n\t\t!list_empty(&netbk->net_schedule_list)) {\n\t\tstruct xenvif *vif;\n\t\tstruct xen_netif_tx_request txreq;\n\t\tstruct xen_netif_tx_request txfrags[MAX_SKB_FRAGS];\n\t\tstruct page *page;\n\t\tstruct xen_netif_extra_info extras[XEN_NETIF_EXTRA_TYPE_MAX-1];\n\t\tu16 pending_idx;\n\t\tRING_IDX idx;\n\t\tint work_to_do;\n\t\tunsigned int data_len;\n\t\tpending_ring_idx_t index;\n\n\t\t/* Get a netif from the list with work to do. */\n\t\tvif = poll_net_schedule_list(netbk);\n\t\tif (!vif)\n\t\t\tcontinue;\n\n\t\tRING_FINAL_CHECK_FOR_REQUESTS(&vif->tx, work_to_do);\n\t\tif (!work_to_do) {\n\t\t\txenvif_put(vif);\n\t\t\tcontinue;\n\t\t}\n\n\t\tidx = vif->tx.req_cons;\n\t\trmb(); /* Ensure that we see the request before we copy it. */\n\t\tmemcpy(&txreq, RING_GET_REQUEST(&vif->tx, idx), sizeof(txreq));\n\n\t\t/* Credit-based scheduling. */\n\t\tif (txreq.size > vif->remaining_credit &&\n\t\t tx_credit_exceeded(vif, txreq.size)) {\n\t\t\txenvif_put(vif);\n\t\t\tcontinue;\n\t\t}\n\n\t\tvif->remaining_credit -= txreq.size;\n\n\t\twork_to_do--;\n\t\tvif->tx.req_cons = ++idx;\n\n\t\tmemset(extras, 0, sizeof(extras));\n\t\tif (txreq.flags & XEN_NETTXF_extra_info) {\n\t\t\twork_to_do = xen_netbk_get_extras(vif, extras,\n\t\t\t\t\t\t\t work_to_do);\n\t\t\tidx = vif->tx.req_cons;\n\t\t\tif (unlikely(work_to_do < 0)) {\n\t\t\t\tnetbk_tx_err(vif, &txreq, idx);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tret = netbk_count_requests(vif, &txreq, txfrags, work_to_do);\n\t\tif (unlikely(ret < 0)) {\n\t\t\tnetbk_tx_err(vif, &txreq, idx - ret);\n\t\t\tcontinue;\n\t\t}\n\t\tidx += ret;\n\n\t\tif (unlikely(txreq.size < ETH_HLEN)) {\n\t\t\tnetdev_dbg(vif->dev,\n\t\t\t\t \"Bad packet size: %d\\n\", txreq.size);\n\t\t\tnetbk_tx_err(vif, &txreq, idx);\n\t\t\tcontinue;\n\t\t}\n\n\t\t/* No crossing a page as the payload mustn't fragment. */\n\t\tif (unlikely((txreq.offset + txreq.size) > PAGE_SIZE)) {\n\t\t\tnetdev_dbg(vif->dev,\n\t\t\t\t \"txreq.offset: %x, size: %u, end: %lu\\n\",\n\t\t\t\t txreq.offset, txreq.size,\n\t\t\t\t (txreq.offset&~PAGE_MASK) + txreq.size);\n\t\t\tnetbk_tx_err(vif, &txreq, idx);\n\t\t\tcontinue;\n\t\t}\n\n\t\tindex = pending_index(netbk->pending_cons);\n\t\tpending_idx = netbk->pending_ring[index];\n\n\t\tdata_len = (txreq.size > PKT_PROT_LEN &&\n\t\t\t ret < MAX_SKB_FRAGS) ?\n\t\t\tPKT_PROT_LEN : txreq.size;\n\n\t\tskb = alloc_skb(data_len + NET_SKB_PAD + NET_IP_ALIGN,\n\t\t\t\tGFP_ATOMIC | __GFP_NOWARN);\n\t\tif (unlikely(skb == NULL)) {\n\t\t\tnetdev_dbg(vif->dev,\n\t\t\t\t \"Can't allocate a skb in start_xmit.\\n\");\n\t\t\tnetbk_tx_err(vif, &txreq, idx);\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Packets passed to netif_rx() must have some headroom. */\n\t\tskb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);\n\n\t\tif (extras[XEN_NETIF_EXTRA_TYPE_GSO - 1].type) {\n\t\t\tstruct xen_netif_extra_info *gso;\n\t\t\tgso = &extras[XEN_NETIF_EXTRA_TYPE_GSO - 1];\n\n\t\t\tif (netbk_set_skb_gso(vif, skb, gso)) {\n\t\t\t\tkfree_skb(skb);\n\t\t\t\tnetbk_tx_err(vif, &txreq, idx);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\t/* XXX could copy straight to head */\n\t\tpage = xen_netbk_alloc_page(netbk, skb, pending_idx);\n\t\tif (!page) {\n\t\t\tkfree_skb(skb);\n\t\t\tnetbk_tx_err(vif, &txreq, idx);\n\t\t\tcontinue;\n\t\t}\n\n\t\tgop->source.u.ref = txreq.gref;\n\t\tgop->source.domid = vif->domid;\n\t\tgop->source.offset = txreq.offset;\n\n\t\tgop->dest.u.gmfn = virt_to_mfn(page_address(page));\n\t\tgop->dest.domid = DOMID_SELF;\n\t\tgop->dest.offset = txreq.offset;\n\n\t\tgop->len = txreq.size;\n\t\tgop->flags = GNTCOPY_source_gref;\n\n\t\tgop++;\n\n\t\tmemcpy(&netbk->pending_tx_info[pending_idx].req,\n\t\t &txreq, sizeof(txreq));\n\t\tnetbk->pending_tx_info[pending_idx].vif = vif;\n\t\t*((u16 *)skb->data) = pending_idx;\n\n\t\t__skb_put(skb, data_len);\n\n\t\tskb_shinfo(skb)->nr_frags = ret;\n\t\tif (data_len < txreq.size) {\n\t\t\tskb_shinfo(skb)->nr_frags++;\n\t\t\tfrag_set_pending_idx(&skb_shinfo(skb)->frags[0],\n\t\t\t\t\t pending_idx);\n\t\t} else {\n\t\t\tfrag_set_pending_idx(&skb_shinfo(skb)->frags[0],\n\t\t\t\t\t INVALID_PENDING_IDX);\n\t\t}\n\n\t\tnetbk->pending_cons++;\n\n\t\trequest_gop = xen_netbk_get_requests(netbk, vif,\n\t\t\t\t\t\t skb, txfrags, gop);\n\t\tif (request_gop == NULL) {\n\t\t\tkfree_skb(skb);\n\t\t\tnetbk_tx_err(vif, &txreq, idx);\n\t\t\tcontinue;\n\t\t}\n\t\tgop = request_gop;\n\n\t\t__skb_queue_tail(&netbk->tx_queue, skb);\n\n\t\tvif->tx.req_cons = idx;\n\t\txen_netbk_check_rx_xenvif(vif);\n\n\t\tif ((gop-netbk->tx_copy_ops) >= ARRAY_SIZE(netbk->tx_copy_ops))\n\t\t\tbreak;\n\t}\n\n\treturn gop - netbk->tx_copy_ops;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'xen/netback: shutdown the ring if it contains garbage.\n\nA buggy or malicious frontend should not be able to confuse netback.\nIf we spot anything which is not as it should be then shutdown the\ndevice and don't try to continue with the ring in a potentially\nhostile state. Well behaved and non-hostile frontends will not be\npenalised.\n\nAs well as making the existing checks for such errors fatal also add a\nnew check that ensures that there isn't an insane number of requests\non the ring (i.e. more than would fit in the ring). If the ring\ncontains garbage then previously is was possible to loop over this\ninsane number, getting an error each time and therefore not generating\nany more pending requests and therefore not exiting the loop in\nxen_netbk_tx_build_gops for an externded period.\n\nAlso turn various netdev_dbg calls which no precipitate a fatal error\ninto netdev_err, they are rate limited because the device is shutdown\nafterwards.\n\nThis fixes at least one known DoS/softlockup of the backend domain.\n\nSigned-off-by: Ian Campbell \nReviewed-by: Konrad Rzeszutek Wilk \nAcked-by: Jan Beulich \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int udf_symlink_filler(struct file *file, struct page *page)\n{\n\tstruct inode *inode = page->mapping->host;\n\tstruct buffer_head *bh = NULL;\n\tunsigned char *symlink;\n\tint err = -EIO;\n\tunsigned char *p = kmap(page);\n\tstruct udf_inode_info *iinfo;\n\tuint32_t pos;\n\n\tiinfo = UDF_I(inode);\n\tpos = udf_block_map(inode, 0);\n\n\tdown_read(&iinfo->i_data_sem);\n\tif (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) {\n\t\tsymlink = iinfo->i_ext.i_data + iinfo->i_lenEAttr;\n\t} else {\n\t\tbh = sb_bread(inode->i_sb, pos);\n\n\t\tif (!bh)\n\t\t\tgoto out;\n\n\t\tsymlink = bh->b_data;\n\t}\n\n\tudf_pc_to_char(inode->i_sb, symlink, inode->i_size, p);\n\tbrelse(bh);\n\n\tup_read(&iinfo->i_data_sem);\n\tSetPageUptodate(page);\n\tkunmap(page);\n\tunlock_page(page);\n\treturn 0;\n\nout:\n\tup_read(&iinfo->i_data_sem);\n\tSetPageError(page);\n\tkunmap(page);\n\tunlock_page(page);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'udf: Verify symlink size before loading it\n\nUDF specification allows arbitrarily large symlinks. However we support\nonly symlinks at most one block large. Check the length of the symlink\nso that we don't access memory beyond end of the symlink block.\n\nCC: stable@vger.kernel.org\nReported-by: Carl Henrik Lunde \nSigned-off-by: Jan Kara '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int utf8s_to_utf16s(const u8 *s, int len, wchar_t *pwcs)\n{\n\tu16 *op;\n\tint size;\n\tunicode_t u;\n\n\top = pwcs;\n\twhile (*s && len > 0) {\n\t\tif (*s & 0x80) {\n\t\t\tsize = utf8_to_utf32(s, len, &u);\n\t\t\tif (size < 0)\n\t\t\t\treturn -EINVAL;\n\n\t\t\tif (u >= PLANE_SIZE) {\n\t\t\t\tu -= PLANE_SIZE;\n\t\t\t\t*op++ = (wchar_t) (SURROGATE_PAIR |\n\t\t\t\t\t\t((u >> 10) & SURROGATE_BITS));\n\t\t\t\t*op++ = (wchar_t) (SURROGATE_PAIR |\n\t\t\t\t\t\tSURROGATE_LOW |\n\t\t\t\t\t\t(u & SURROGATE_BITS));\n\t\t\t} else {\n\t\t\t\t*op++ = (wchar_t) u;\n\t\t\t}\n\t\t\ts += size;\n\t\t\tlen -= size;\n\t\t} else {\n\t\t\t*op++ = *s++;\n\t\t\tlen--;\n\t\t}\n\t}\n\treturn op - pwcs;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'NLS: improve UTF8 -> UTF16 string conversion routine\n\nThe utf8s_to_utf16s conversion routine needs to be improved. Unlike\nits utf16s_to_utf8s sibling, it doesn't accept arguments specifying\nthe maximum length of the output buffer or the endianness of its\n16-bit output.\n\nThis patch (as1501) adds the two missing arguments, and adjusts the\nonly two places in the kernel where the function is called. A\nfollow-on patch will add a third caller that does utilize the new\ncapabilities.\n\nThe two conversion routines are still annoyingly inconsistent in the\nway they handle invalid byte combinations. But that's a subject for a\ndifferent patch.\n\nSigned-off-by: Alan Stern \nCC: Clemens Ladisch \nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: u64 secure_dccp_sequence_number(__be32 saddr, __be32 daddr,\n\t\t\t\t__be16 sport, __be16 dport)\n{\n\tu64 seq;\n\t__u32 hash[4];\n\tstruct keydata *keyptr = get_keyptr();\n\n\thash[0] = (__force u32)saddr;\n\thash[1] = (__force u32)daddr;\n\thash[2] = ((__force u16)sport << 16) + (__force u16)dport;\n\thash[3] = keyptr->secret[11];\n\n\tseq = half_md4_transform(hash, keyptr->secret);\n\tseq |= ((u64)keyptr->count) << (32 - HASH_BITS);\n\n\tseq += ktime_to_ns(ktime_get_real());\n\tseq &= (1ull << 48) - 1;\n\n\treturn seq;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'net: Compute protocol sequence numbers and fragment IDs using MD5.\n\nComputers have become a lot faster since we compromised on the\npartial MD4 hash which we use currently for performance reasons.\n\nMD5 is a much safer choice, and is inline with both RFC1948 and\nother ISS generators (OpenBSD, Solaris, etc.)\n\nFurthermore, only having 24-bits of the sequence number be truly\nunpredictable is a very serious limitation. So the periodic\nregeneration and 8-bit counter have been removed. We compute and\nuse a full 32-bit sequence number.\n\nFor ipv6, DCCP was found to use a 32-bit truncated initial sequence\nnumber (it needs 43-bits) and that is fixed here as well.\n\nReported-by: Dan Kaminsky \nTested-by: Willy Tarreau \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Status GetDeviceForInput(const EagerOperation& op, const EagerContext& ctx,\n TensorHandle* tensor_handle, Device** result) {\n Device* cpu_device = ctx.HostCPU();\n string device_name;\n if (tensor_handle->Type() != TensorHandle::LOCAL) {\n Device* device = tensor_handle->device();\n device_name = device != nullptr ? device->name() : cpu_device->name();\n *result = (device == nullptr ? cpu_device : device);\n } else if (tensor_handle->dtype == DT_RESOURCE) {\n // Use the resource's actual device because it is the device that will\n // influence partitioning the multi-device function.\n const Tensor* tensor;\n // TODO(fishx): Avoid blocking here.\n TF_RETURN_IF_ERROR(tensor_handle->Tensor(&tensor));\n const ResourceHandle& handle = tensor->flat()(0);\n device_name = handle.device();\n\n Device* input_device;\n TF_RETURN_IF_ERROR(\n ctx.FindDeviceFromName(device_name.c_str(), &input_device));\n *result = input_device;\n } else {\n Device* device = tensor_handle->device();\n const bool is_tpu = device != nullptr && device->device_type() == \"TPU\";\n // int32 return values can be placed on TPUs.\n const bool use_host_memory =\n is_tpu ? MTypeFromDTypeIntsOnDevice(tensor_handle->dtype)\n : MTypeFromDType(tensor_handle->dtype);\n if (use_host_memory) {\n *result = cpu_device;\n } else {\n // Eager ops executing as functions should have their preferred inputs set\n // to the op's device. This allows us to avoid expensive D2H copies if a\n // mirror of the tensor already exists on the op's device.\n if (!op.is_function() && device != nullptr && device != cpu_device) {\n device = absl::get(op.Device());\n }\n *result = (device == nullptr ? cpu_device : device);\n }\n }\n return Status::OK();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-475'], 'message': 'Fix empty resource handle vulnerability.\n\nSome ops that attempt to extract a resource handle from user input\ncan lead to nullptr dereferences. This returns an error in such\na case.\n\nPiperOrigin-RevId: 445571938'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ldb_msg_add_string(struct ldb_message *msg,\n\t\t const char *attr_name, const char *str)\n{\n\tstruct ldb_val val;\n\n\tval.data = discard_const_p(uint8_t, str);\n\tval.length = strlen(str);\n\n\tif (val.length == 0) {\n\t\t/* allow empty strings as non-existent attributes */\n\t\treturn LDB_SUCCESS;\n\t}\n\n\treturn ldb_msg_add_value(msg, attr_name, &val, NULL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2022-32746 ldb: Add functions for appending to an ldb_message\n\nCurrently, there are many places where we use ldb_msg_add_empty() to add\nan empty element to a message, and then call ldb_msg_add_value() or\nsimilar to add values to that element. However, this performs an\nunnecessary search of the message's elements to locate the new element.\nMoreover, if an element with the same attribute name already exists\nearlier in the message, the values will be added to that element,\ninstead of to the intended newly added element.\n\nA similar pattern exists where we add values to a message, and then call\nldb_msg_find_element() to locate that message element and sets its flags\nto (e.g.) LDB_FLAG_MOD_REPLACE. This also performs an unnecessary\nsearch, and may locate the wrong message element for setting the flags.\n\nTo avoid these problems, add functions for appending a value to a\nmessage, so that a particular value can be added to the end of a message\nin a single operation.\n\nFor ADD requests, it is important that no two message elements share the\nsame attribute name, otherwise things will break. (Normally,\nldb_msg_normalize() is called before processing the request to help\nensure this.) Thus, we must be careful not to append an attribute to an\nADD message, unless we are sure (e.g. through ldb_msg_find_element())\nthat an existing element for that attribute is not present.\n\nThese functions will be used in the next commit.\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: 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 (DataStream.read(&PossibleIdNSize[ReadIndex++], 1) == 0) {\n return NULL; // no more data ?\n }\n ReadSize++;\n\n } while (!bFound && MaxDataSize > ReadSize);\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( 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) {\n Result->SetSizeInfinite();\n }\n\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 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': 'Check the max size to read before actually reading\n\nThe size check waas also missing from the length 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 void recalculate_apic_map(struct kvm *kvm)\n{\n\tstruct kvm_apic_map *new, *old = NULL;\n\tstruct kvm_vcpu *vcpu;\n\tint i;\n\n\tnew = kzalloc(sizeof(struct kvm_apic_map), GFP_KERNEL);\n\n\tmutex_lock(&kvm->arch.apic_map_lock);\n\n\tif (!new)\n\t\tgoto out;\n\n\tnew->ldr_bits = 8;\n\t/* flat mode is default */\n\tnew->cid_shift = 8;\n\tnew->cid_mask = 0;\n\tnew->lid_mask = 0xff;\n\n\tkvm_for_each_vcpu(i, vcpu, kvm) {\n\t\tstruct kvm_lapic *apic = vcpu->arch.apic;\n\t\tu16 cid, lid;\n\t\tu32 ldr;\n\n\t\tif (!kvm_apic_present(vcpu))\n\t\t\tcontinue;\n\n\t\t/*\n\t\t * All APICs have to be configured in the same mode by an OS.\n\t\t * We take advatage of this while building logical id loockup\n\t\t * table. After reset APICs are in xapic/flat mode, so if we\n\t\t * find apic with different setting we assume this is the mode\n\t\t * OS wants all apics to be in; build lookup table accordingly.\n\t\t */\n\t\tif (apic_x2apic_mode(apic)) {\n\t\t\tnew->ldr_bits = 32;\n\t\t\tnew->cid_shift = 16;\n\t\t\tnew->cid_mask = new->lid_mask = 0xffff;\n\t\t} else if (kvm_apic_sw_enabled(apic) &&\n\t\t\t\t!new->cid_mask /* flat mode */ &&\n\t\t\t\tkvm_apic_get_reg(apic, APIC_DFR) == APIC_DFR_CLUSTER) {\n\t\t\tnew->cid_shift = 4;\n\t\t\tnew->cid_mask = 0xf;\n\t\t\tnew->lid_mask = 0xf;\n\t\t}\n\n\t\tnew->phys_map[kvm_apic_id(apic)] = apic;\n\n\t\tldr = kvm_apic_get_reg(apic, APIC_LDR);\n\t\tcid = apic_cluster_id(new, ldr);\n\t\tlid = apic_logical_id(new, ldr);\n\n\t\tif (lid)\n\t\t\tnew->logical_map[cid][ffs(lid) - 1] = apic;\n\t}\nout:\n\told = rcu_dereference_protected(kvm->arch.apic_map,\n\t\t\tlockdep_is_held(&kvm->arch.apic_map_lock));\n\trcu_assign_pointer(kvm->arch.apic_map, new);\n\tmutex_unlock(&kvm->arch.apic_map_lock);\n\n\tif (old)\n\t\tkfree_rcu(old, rcu);\n\n\tkvm_vcpu_request_scan_ioapic(kvm);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'KVM: x86: fix guest-initiated crash with x2apic (CVE-2013-6376)\n\nA guest can cause a BUG_ON() leading to a host kernel crash.\nWhen the guest writes to the ICR to request an IPI, while in x2apic\nmode the following things happen, the destination is read from\nICR2, which is a register that the guest can control.\n\nkvm_irq_delivery_to_apic_fast uses the high 16 bits of ICR2 as the\ncluster id. A BUG_ON is triggered, which is a protection against\naccessing map->logical_map with an out-of-bounds access and manages\nto avoid that anything really unsafe occurs.\n\nThe logic in the code is correct from real HW point of view. The problem\nis that KVM supports only one cluster with ID 0 in clustered mode, but\nthe code that has the bug does not take this into account.\n\nReported-by: Lars Bull \nCc: stable@vger.kernel.org\nSigned-off-by: Gleb Natapov \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 tipc_link_proto_rcv(struct tipc_link *l, struct sk_buff *skb,\n\t\t\t struct sk_buff_head *xmitq)\n{\n\tstruct tipc_msg *hdr = buf_msg(skb);\n\tstruct tipc_gap_ack_blks *ga = NULL;\n\tbool reply = msg_probe(hdr), retransmitted = false;\n\tu16 dlen = msg_data_sz(hdr), glen = 0;\n\tu16 peers_snd_nxt = msg_next_sent(hdr);\n\tu16 peers_tol = msg_link_tolerance(hdr);\n\tu16 peers_prio = msg_linkprio(hdr);\n\tu16 gap = msg_seq_gap(hdr);\n\tu16 ack = msg_ack(hdr);\n\tu16 rcv_nxt = l->rcv_nxt;\n\tu16 rcvgap = 0;\n\tint mtyp = msg_type(hdr);\n\tint rc = 0, released;\n\tchar *if_name;\n\tvoid *data;\n\n\ttrace_tipc_proto_rcv(skb, false, l->name);\n\tif (tipc_link_is_blocked(l) || !xmitq)\n\t\tgoto exit;\n\n\tif (tipc_own_addr(l->net) > msg_prevnode(hdr))\n\t\tl->net_plane = msg_net_plane(hdr);\n\n\tskb_linearize(skb);\n\thdr = buf_msg(skb);\n\tdata = msg_data(hdr);\n\n\tif (!tipc_link_validate_msg(l, hdr)) {\n\t\ttrace_tipc_skb_dump(skb, false, \"PROTO invalid (1)!\");\n\t\ttrace_tipc_link_dump(l, TIPC_DUMP_NONE, \"PROTO invalid (1)!\");\n\t\tgoto exit;\n\t}\n\n\tswitch (mtyp) {\n\tcase RESET_MSG:\n\tcase ACTIVATE_MSG:\n\t\t/* Complete own link name with peer's interface name */\n\t\tif_name = strrchr(l->name, ':') + 1;\n\t\tif (sizeof(l->name) - (if_name - l->name) <= TIPC_MAX_IF_NAME)\n\t\t\tbreak;\n\t\tif (msg_data_sz(hdr) < TIPC_MAX_IF_NAME)\n\t\t\tbreak;\n\t\tstrncpy(if_name, data, TIPC_MAX_IF_NAME);\n\n\t\t/* Update own tolerance if peer indicates a non-zero value */\n\t\tif (in_range(peers_tol, TIPC_MIN_LINK_TOL, TIPC_MAX_LINK_TOL)) {\n\t\t\tl->tolerance = peers_tol;\n\t\t\tl->bc_rcvlink->tolerance = peers_tol;\n\t\t}\n\t\t/* Update own priority if peer's priority is higher */\n\t\tif (in_range(peers_prio, l->priority + 1, TIPC_MAX_LINK_PRI))\n\t\t\tl->priority = peers_prio;\n\n\t\t/* If peer is going down we want full re-establish cycle */\n\t\tif (msg_peer_stopping(hdr)) {\n\t\t\trc = tipc_link_fsm_evt(l, LINK_FAILURE_EVT);\n\t\t\tbreak;\n\t\t}\n\n\t\t/* If this endpoint was re-created while peer was ESTABLISHING\n\t\t * it doesn't know current session number. Force re-synch.\n\t\t */\n\t\tif (mtyp == ACTIVATE_MSG && msg_dest_session_valid(hdr) &&\n\t\t l->session != msg_dest_session(hdr)) {\n\t\t\tif (less(l->session, msg_dest_session(hdr)))\n\t\t\t\tl->session = msg_dest_session(hdr) + 1;\n\t\t\tbreak;\n\t\t}\n\n\t\t/* ACTIVATE_MSG serves as PEER_RESET if link is already down */\n\t\tif (mtyp == RESET_MSG || !link_is_up(l))\n\t\t\trc = tipc_link_fsm_evt(l, LINK_PEER_RESET_EVT);\n\n\t\t/* ACTIVATE_MSG takes up link if it was already locally reset */\n\t\tif (mtyp == ACTIVATE_MSG && l->state == LINK_ESTABLISHING)\n\t\t\trc = TIPC_LINK_UP_EVT;\n\n\t\tl->peer_session = msg_session(hdr);\n\t\tl->in_session = true;\n\t\tl->peer_bearer_id = msg_bearer_id(hdr);\n\t\tif (l->mtu > msg_max_pkt(hdr))\n\t\t\tl->mtu = msg_max_pkt(hdr);\n\t\tbreak;\n\n\tcase STATE_MSG:\n\t\tl->rcv_nxt_state = msg_seqno(hdr) + 1;\n\n\t\t/* Update own tolerance if peer indicates a non-zero value */\n\t\tif (in_range(peers_tol, TIPC_MIN_LINK_TOL, TIPC_MAX_LINK_TOL)) {\n\t\t\tl->tolerance = peers_tol;\n\t\t\tl->bc_rcvlink->tolerance = peers_tol;\n\t\t}\n\t\t/* Update own prio if peer indicates a different value */\n\t\tif ((peers_prio != l->priority) &&\n\t\t in_range(peers_prio, 1, TIPC_MAX_LINK_PRI)) {\n\t\t\tl->priority = peers_prio;\n\t\t\trc = tipc_link_fsm_evt(l, LINK_FAILURE_EVT);\n\t\t}\n\n\t\tl->silent_intv_cnt = 0;\n\t\tl->stats.recv_states++;\n\t\tif (msg_probe(hdr))\n\t\t\tl->stats.recv_probes++;\n\n\t\tif (!link_is_up(l)) {\n\t\t\tif (l->state == LINK_ESTABLISHING)\n\t\t\t\trc = TIPC_LINK_UP_EVT;\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Receive Gap ACK blocks from peer if any */\n\t\tglen = tipc_get_gap_ack_blks(&ga, l, hdr, true);\n\n\t\ttipc_mon_rcv(l->net, data + glen, dlen - glen, l->addr,\n\t\t\t &l->mon_state, l->bearer_id);\n\n\t\t/* Send NACK if peer has sent pkts we haven't received yet */\n\t\tif ((reply || msg_is_keepalive(hdr)) &&\n\t\t more(peers_snd_nxt, rcv_nxt) &&\n\t\t !tipc_link_is_synching(l) &&\n\t\t skb_queue_empty(&l->deferdq))\n\t\t\trcvgap = peers_snd_nxt - l->rcv_nxt;\n\t\tif (rcvgap || reply)\n\t\t\ttipc_link_build_proto_msg(l, STATE_MSG, 0, reply,\n\t\t\t\t\t\t rcvgap, 0, 0, xmitq);\n\n\t\treleased = tipc_link_advance_transmq(l, l, ack, gap, ga, xmitq,\n\t\t\t\t\t\t &retransmitted, &rc);\n\t\tif (gap)\n\t\t\tl->stats.recv_nacks++;\n\t\tif (released || retransmitted)\n\t\t\ttipc_link_update_cwin(l, released, retransmitted);\n\t\tif (released)\n\t\t\ttipc_link_advance_backlog(l, xmitq);\n\t\tif (unlikely(!skb_queue_empty(&l->wakeupq)))\n\t\t\tlink_prepare_wakeup(l);\n\t}\nexit:\n\tkfree_skb(skb);\n\treturn rc;\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: void Compute(OpKernelContext* context) override {\n const Tensor& tensor_in = context->input(0);\n const Tensor& tensor_out = context->input(1);\n const Tensor& out_grad_backprop = context->input(2);\n\n // For maxpooling3d, tensor_in should have 5 dimensions.\n OP_REQUIRES(context, tensor_in.dims() == 5,\n errors::InvalidArgument(\"tensor_in must be 5-dimensional\"));\n OP_REQUIRES(context, tensor_out.dims() == 5,\n errors::InvalidArgument(\"tensor_out must be 5-dimensional\"));\n // For maxpooling3d, out_grad_backprop should have 5 dimensions.\n OP_REQUIRES(\n context, out_grad_backprop.dims() == 5,\n errors::InvalidArgument(\"out_grad_backprop must be 5-dimensional\"));\n\n Pool3dParameters params{context, ksize_, stride_,\n padding_, data_format_, tensor_in.shape()};\n\n Tensor* output = nullptr;\n OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(\n {2}, 0, tensor_out.shape(), &output));\n\n LaunchMaxPooling3dGradGradOp::launch(\n context, params, tensor_in, tensor_out, out_grad_backprop, output);\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Add missing validation to pooling_ops_3d\n\nPiperOrigin-RevId: 372218727\nChange-Id: I6b9ed4266aa7286c02f1f230d7bea922c1be547e'" }, { "text": "[INST] Given the following code containing errors, provide Common 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_bus_write_dsdt(int bus)\n{\n\tstruct businfo *bi;\n\tstruct slotinfo *si;\n\tstruct pci_vdev *dev;\n\tint count, func, slot;\n\n\t/*\n\t * If there are no devices on this 'bus' then just return.\n\t */\n\t bi = pci_businfo[bus];\n\tif (bi == NULL) {\n\t\t/*\n\t\t * Bus 0 is special because it decodes the I/O ports used\n\t\t * for PCI config space access even if there are no devices\n\t\t * on it.\n\t\t */\n\t\tif (bus != 0)\n\t\t\treturn;\n\t}\n\n\tdsdt_line(\" Device (PCI%01X)\", bus);\n\tdsdt_line(\" {\");\n\tdsdt_line(\" Name (_HID, EisaId (\\\"PNP0A03\\\"))\");\n\tdsdt_line(\" Name (_ADR, Zero)\");\n\n\tdsdt_line(\" Method (_BBN, 0, NotSerialized)\");\n\tdsdt_line(\" {\");\n\tdsdt_line(\" Return (0x%08X)\", bus);\n\tdsdt_line(\" }\");\n\tdsdt_line(\" Name (_CRS, ResourceTemplate ()\");\n\tdsdt_line(\" {\");\n\tdsdt_line(\" WordBusNumber (ResourceProducer, MinFixed, \"\n\t \"MaxFixed, PosDecode,\");\n\tdsdt_line(\" 0x0000, // Granularity\");\n\tdsdt_line(\" 0x%04X, // Range Minimum\", bus);\n\tdsdt_line(\" 0x%04X, // Range Maximum\", bus);\n\tdsdt_line(\" 0x0000, // Translation Offset\");\n\tdsdt_line(\" 0x0001, // Length\");\n\tdsdt_line(\" ,, )\");\n\n\tif (bus == 0) {\n\t\tdsdt_indent(3);\n\t\tdsdt_fixed_ioport(0xCF8, 8);\n\t\tdsdt_unindent(3);\n\n\t\tdsdt_line(\" WordIO (ResourceProducer, MinFixed, MaxFixed, \"\n\t\t \"PosDecode, EntireRange,\");\n\t\tdsdt_line(\" 0x0000, // Granularity\");\n\t\tdsdt_line(\" 0x0000, // Range Minimum\");\n\t\tdsdt_line(\" 0x0CF7, // Range Maximum\");\n\t\tdsdt_line(\" 0x0000, // Translation Offset\");\n\t\tdsdt_line(\" 0x0CF8, // Length\");\n\t\tdsdt_line(\" ,, , TypeStatic)\");\n\n\t\tdsdt_line(\" WordIO (ResourceProducer, MinFixed, MaxFixed, \"\n\t\t \"PosDecode, EntireRange,\");\n\t\tdsdt_line(\" 0x0000, // Granularity\");\n\t\tdsdt_line(\" 0x0D00, // Range Minimum\");\n\t\tdsdt_line(\" 0x%04X, // Range Maximum\",\n\t\t PCI_EMUL_IOBASE - 1);\n\t\tdsdt_line(\" 0x0000, // Translation Offset\");\n\t\tdsdt_line(\" 0x%04X, // Length\",\n\t\t PCI_EMUL_IOBASE - 0x0D00);\n\t\tdsdt_line(\" ,, , TypeStatic)\");\n\n\t\tif (bi == NULL) {\n\t\t\tdsdt_line(\" })\");\n\t\t\tgoto done;\n\t\t}\n\t}\n\tassert(bi != NULL);\n\n\t/* i/o window */\n\tdsdt_line(\" WordIO (ResourceProducer, MinFixed, MaxFixed, \"\n\t \"PosDecode, EntireRange,\");\n\tdsdt_line(\" 0x0000, // Granularity\");\n\tdsdt_line(\" 0x%04X, // Range Minimum\", bi->iobase);\n\tdsdt_line(\" 0x%04X, // Range Maximum\",\n\t bi->iolimit - 1);\n\tdsdt_line(\" 0x0000, // Translation Offset\");\n\tdsdt_line(\" 0x%04X, // Length\",\n\t bi->iolimit - bi->iobase);\n\tdsdt_line(\" ,, , TypeStatic)\");\n\n\t/* mmio window (32-bit) */\n\tdsdt_line(\" DWordMemory (ResourceProducer, PosDecode, \"\n\t \"MinFixed, MaxFixed, NonCacheable, ReadWrite,\");\n\tdsdt_line(\" 0x00000000, // Granularity\");\n\tdsdt_line(\" 0x%08X, // Range Minimum\\n\", bi->membase32);\n\tdsdt_line(\" 0x%08X, // Range Maximum\\n\",\n\t bi->memlimit32 - 1);\n\tdsdt_line(\" 0x00000000, // Translation Offset\");\n\tdsdt_line(\" 0x%08X, // Length\\n\",\n\t bi->memlimit32 - bi->membase32);\n\tdsdt_line(\" ,, , AddressRangeMemory, TypeStatic)\");\n\n\t/* mmio window (64-bit) */\n\tdsdt_line(\" QWordMemory (ResourceProducer, PosDecode, \"\n\t \"MinFixed, MaxFixed, NonCacheable, ReadWrite,\");\n\tdsdt_line(\" 0x0000000000000000, // Granularity\");\n\tdsdt_line(\" 0x%016lX, // Range Minimum\\n\", bi->membase64);\n\tdsdt_line(\" 0x%016lX, // Range Maximum\\n\",\n\t bi->memlimit64 - 1);\n\tdsdt_line(\" 0x0000000000000000, // Translation Offset\");\n\tdsdt_line(\" 0x%016lX, // Length\\n\",\n\t bi->memlimit64 - bi->membase64);\n\tdsdt_line(\" ,, , AddressRangeMemory, TypeStatic)\");\n\tdsdt_line(\" })\");\n\n\tif (!is_rtvm) {\n\t\tcount = pci_count_lintr(bus);\n\t\tif (count != 0) {\n\t\t\tdsdt_indent(2);\n\t\t\tdsdt_line(\"Name (PPRT, Package ()\");\n\t\t\tdsdt_line(\"{\");\n\t\t\tpci_walk_lintr(bus, pci_pirq_prt_entry, NULL);\n\t\t\tdsdt_line(\"})\");\n\t\t\tdsdt_line(\"Name (APRT, Package ()\");\n\t\t\tdsdt_line(\"{\");\n\t\t\tpci_walk_lintr(bus, pci_apic_prt_entry, NULL);\n\t\t\tdsdt_line(\"})\");\n\t\t\tdsdt_line(\"Method (_PRT, 0, NotSerialized)\");\n\t\t\tdsdt_line(\"{\");\n\t\t\tdsdt_line(\" If (PICM)\");\n\t\t\tdsdt_line(\" {\");\n\t\t\tdsdt_line(\" Return (APRT)\");\n\t\t\tdsdt_line(\" }\");\n\t\t\tdsdt_line(\" Else\");\n\t\t\tdsdt_line(\" {\");\n\t\t\tdsdt_line(\" Return (PPRT)\");\n\t\t\tdsdt_line(\" }\");\n\t\t\tdsdt_line(\"}\");\n\t\t\tdsdt_unindent(2);\n\t\t}\n\t}\n\n\tdsdt_indent(2);\n\tfor (slot = 0; slot < MAXSLOTS; slot++) {\n\t\tsi = &bi->slotinfo[slot];\n\t\tfor (func = 0; func < MAXFUNCS; func++) {\n\t\t\tdev = si->si_funcs[func].fi_devi;\n\t\t\tif (dev != NULL &&\n\t\t\t dev->dev_ops->vdev_write_dsdt != NULL)\n\t\t\t\tdev->dev_ops->vdev_write_dsdt(dev);\n\t\t}\n\t}\n\tdsdt_unindent(2);\ndone:\n\tdsdt_line(\" }\");\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: deinit_pci(struct vmctx *ctx)\n{\n\tstruct pci_vdev_ops *ops;\n\tstruct businfo *bi;\n\tstruct slotinfo *si;\n\tstruct funcinfo *fi;\n\tint bus, slot, func;\n\tsize_t lowmem;\n\tstruct mem_range mr;\n\n\t/* Release PCI extended config space */\n\tbzero(&mr, sizeof(struct mem_range));\n\tmr.name = \"PCI ECFG\";\n\tmr.base = PCI_EMUL_ECFG_BASE;\n\tmr.size = PCI_EMUL_ECFG_SIZE;\n\tunregister_mem(&mr);\n\n\t/* Release PCI hole space */\n\tlowmem = vm_get_lowmem_size(ctx);\n\tbzero(&mr, sizeof(struct mem_range));\n\tmr.name = \"PCI hole (32-bit)\";\n\tmr.base = lowmem;\n\tmr.size = (4ULL * 1024 * 1024 * 1024) - lowmem;\n\tunregister_mem_fallback(&mr);\n\n\t/* ditto for the 64-bit PCI host aperture */\n\tbzero(&mr, sizeof(struct mem_range));\n\tmr.name = \"PCI hole (64-bit)\";\n\tmr.base = PCI_EMUL_MEMBASE64;\n\tmr.size = PCI_EMUL_MEMLIMIT64 - PCI_EMUL_MEMBASE64;\n\tunregister_mem_fallback(&mr);\n\n\tfor (bus = 0; bus < MAXBUSES; bus++) {\n\t\tbi = pci_businfo[bus];\n\t\tif (bi == NULL)\n\t\t\tcontinue;\n\n\t\tfor (slot = 0; slot < MAXSLOTS; slot++) {\n\t\t\tsi = &bi->slotinfo[slot];\n\t\t\tfor (func = 0; func < MAXFUNCS; func++) {\n\t\t\t\tfi = &si->si_funcs[func];\n\t\t\t\tif (fi->fi_name == NULL)\n\t\t\t\t\tcontinue;\n\t\t\t\tops = pci_emul_finddev(fi->fi_name);\n\t\t\t\tassert(ops != NULL);\n\n\t\t\t\tpr_notice(\"pci deinit %s\\n\", fi->fi_name);\n\t\t\t\tpci_emul_deinit(ctx, ops, bus, slot,\n\t\t\t\t func, fi);\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-617', 'CWE-703'], 'message': 'dm: pci: clean up assert() in pci core\n\nTracked-On: #3252\nSigned-off-by: Shuo A Liu \nReviewed-by: Yonghua Huang '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: pci_lintr_assert(struct pci_vdev *dev)\n{\n\tassert(dev->lintr.pin > 0);\n\n\tpthread_mutex_lock(&dev->lintr.lock);\n\tif (dev->lintr.state == IDLE) {\n\t\tif (pci_lintr_permitted(dev)) {\n\t\t\tdev->lintr.state = ASSERTED;\n\t\t\tpci_irq_assert(dev);\n\t\t} else\n\t\t\tdev->lintr.state = PENDING;\n\t}\n\tpthread_mutex_unlock(&dev->lintr.lock);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617', 'CWE-703'], 'message': 'dm: pci: clean up assert() in pci core\n\nTracked-On: #3252\nSigned-off-by: Shuo A Liu \nReviewed-by: Yonghua Huang '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TPM2B_ATTEST_Marshal(TPM2B_ATTEST *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_MAX_BUFFER_Marshal(TPM2B_MAX_BUFFER *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: static int http_connect(URLContext *h, const char *path, const char *local_path,\n const char *hoststr, const char *auth,\n const char *proxyauth, int *new_location)\n{\n HTTPContext *s = h->priv_data;\n int post, err;\n char headers[HTTP_HEADERS_SIZE] = \"\";\n char *authstr = NULL, *proxyauthstr = NULL;\n int64_t off = s->off;\n int len = 0;\n const char *method;\n int send_expect_100 = 0;\n\n /* send http header */\n post = h->flags & AVIO_FLAG_WRITE;\n\n if (s->post_data) {\n /* force POST method and disable chunked encoding when\n * custom HTTP post data is set */\n post = 1;\n s->chunked_post = 0;\n }\n\n if (s->method)\n method = s->method;\n else\n method = post ? \"POST\" : \"GET\";\n\n authstr = ff_http_auth_create_response(&s->auth_state, auth,\n local_path, method);\n proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,\n local_path, method);\n if (post && !s->post_data) {\n send_expect_100 = s->send_expect_100;\n /* The user has supplied authentication but we don't know the auth type,\n * send Expect: 100-continue to get the 401 response including the\n * WWW-Authenticate header, or an 100 continue if no auth actually\n * is needed. */\n if (auth && *auth &&\n s->auth_state.auth_type == HTTP_AUTH_NONE &&\n s->http_code != 401)\n send_expect_100 = 1;\n }\n\n#if FF_API_HTTP_USER_AGENT\n if (strcmp(s->user_agent_deprecated, DEFAULT_USER_AGENT)) {\n av_log(s, AV_LOG_WARNING, \"the user-agent option is deprecated, please use user_agent option\\n\");\n s->user_agent = av_strdup(s->user_agent_deprecated);\n }\n#endif\n /* set default headers if needed */\n if (!has_header(s->headers, \"\\r\\nUser-Agent: \"))\n len += av_strlcatf(headers + len, sizeof(headers) - len,\n \"User-Agent: %s\\r\\n\", s->user_agent);\n if (!has_header(s->headers, \"\\r\\nAccept: \"))\n len += av_strlcpy(headers + len, \"Accept: */*\\r\\n\",\n sizeof(headers) - len);\n // Note: we send this on purpose even when s->off is 0 when we're probing,\n // since it allows us to detect more reliably if a (non-conforming)\n // server supports seeking by analysing the reply headers.\n if (!has_header(s->headers, \"\\r\\nRange: \") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {\n len += av_strlcatf(headers + len, sizeof(headers) - len,\n \"Range: bytes=%\"PRId64\"-\", s->off);\n if (s->end_off)\n len += av_strlcatf(headers + len, sizeof(headers) - len,\n \"%\"PRId64, s->end_off - 1);\n len += av_strlcpy(headers + len, \"\\r\\n\",\n sizeof(headers) - len);\n }\n if (send_expect_100 && !has_header(s->headers, \"\\r\\nExpect: \"))\n len += av_strlcatf(headers + len, sizeof(headers) - len,\n \"Expect: 100-continue\\r\\n\");\n\n if (!has_header(s->headers, \"\\r\\nConnection: \")) {\n if (s->multiple_requests)\n len += av_strlcpy(headers + len, \"Connection: keep-alive\\r\\n\",\n sizeof(headers) - len);\n else\n len += av_strlcpy(headers + len, \"Connection: close\\r\\n\",\n sizeof(headers) - len);\n }\n\n if (!has_header(s->headers, \"\\r\\nHost: \"))\n len += av_strlcatf(headers + len, sizeof(headers) - len,\n \"Host: %s\\r\\n\", hoststr);\n if (!has_header(s->headers, \"\\r\\nContent-Length: \") && s->post_data)\n len += av_strlcatf(headers + len, sizeof(headers) - len,\n \"Content-Length: %d\\r\\n\", s->post_datalen);\n\n if (!has_header(s->headers, \"\\r\\nContent-Type: \") && s->content_type)\n len += av_strlcatf(headers + len, sizeof(headers) - len,\n \"Content-Type: %s\\r\\n\", s->content_type);\n if (!has_header(s->headers, \"\\r\\nCookie: \") && s->cookies) {\n char *cookies = NULL;\n if (!get_cookies(s, &cookies, path, hoststr) && cookies) {\n len += av_strlcatf(headers + len, sizeof(headers) - len,\n \"Cookie: %s\\r\\n\", cookies);\n av_free(cookies);\n }\n }\n if (!has_header(s->headers, \"\\r\\nIcy-MetaData: \") && s->icy)\n len += av_strlcatf(headers + len, sizeof(headers) - len,\n \"Icy-MetaData: %d\\r\\n\", 1);\n\n /* now add in custom headers */\n if (s->headers)\n av_strlcpy(headers + len, s->headers, sizeof(headers) - len);\n\n snprintf(s->buffer, sizeof(s->buffer),\n \"%s %s HTTP/1.1\\r\\n\"\n \"%s\"\n \"%s\"\n \"%s\"\n \"%s%s\"\n \"\\r\\n\",\n method,\n path,\n post && s->chunked_post ? \"Transfer-Encoding: chunked\\r\\n\" : \"\",\n headers,\n authstr ? authstr : \"\",\n proxyauthstr ? \"Proxy-\" : \"\", proxyauthstr ? proxyauthstr : \"\");\n\n av_log(h, AV_LOG_DEBUG, \"request: %s\\n\", s->buffer);\n\n if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)\n goto done;\n\n if (s->post_data)\n if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)\n goto done;\n\n /* init input buffer */\n s->buf_ptr = s->buffer;\n s->buf_end = s->buffer;\n s->line_count = 0;\n s->off = 0;\n s->icy_data_read = 0;\n s->filesize = -1;\n s->willclose = 0;\n s->end_chunked_post = 0;\n s->end_header = 0;\n if (post && !s->post_data && !send_expect_100) {\n /* Pretend that it did work. We didn't read any header yet, since\n * we've still to send the POST data, but the code calling this\n * function will check http_code after we return. */\n s->http_code = 200;\n err = 0;\n goto done;\n }\n\n /* wait for header */\n err = http_read_header(h, new_location);\n if (err < 0)\n goto done;\n\n if (*new_location)\n s->off = off;\n\n err = (off == s->off) ? 0 : -1;\ndone:\n av_freep(&authstr);\n av_freep(&proxyauthstr);\n return err;\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 int try_to_unmap_cluster(unsigned long cursor, unsigned int *mapcount,\n\t\tstruct vm_area_struct *vma, struct page *check_page)\n{\n\tstruct mm_struct *mm = vma->vm_mm;\n\tpmd_t *pmd;\n\tpte_t *pte;\n\tpte_t pteval;\n\tspinlock_t *ptl;\n\tstruct page *page;\n\tunsigned long address;\n\tunsigned long mmun_start;\t/* For mmu_notifiers */\n\tunsigned long mmun_end;\t\t/* For mmu_notifiers */\n\tunsigned long end;\n\tint ret = SWAP_AGAIN;\n\tint locked_vma = 0;\n\n\taddress = (vma->vm_start + cursor) & CLUSTER_MASK;\n\tend = address + CLUSTER_SIZE;\n\tif (address < vma->vm_start)\n\t\taddress = vma->vm_start;\n\tif (end > vma->vm_end)\n\t\tend = vma->vm_end;\n\n\tpmd = mm_find_pmd(mm, address);\n\tif (!pmd)\n\t\treturn ret;\n\n\tmmun_start = address;\n\tmmun_end = end;\n\tmmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);\n\n\t/*\n\t * If we can acquire the mmap_sem for read, and vma is VM_LOCKED,\n\t * keep the sem while scanning the cluster for mlocking pages.\n\t */\n\tif (down_read_trylock(&vma->vm_mm->mmap_sem)) {\n\t\tlocked_vma = (vma->vm_flags & VM_LOCKED);\n\t\tif (!locked_vma)\n\t\t\tup_read(&vma->vm_mm->mmap_sem); /* don't need it */\n\t}\n\n\tpte = pte_offset_map_lock(mm, pmd, address, &ptl);\n\n\t/* Update high watermark before we lower rss */\n\tupdate_hiwater_rss(mm);\n\n\tfor (; address < end; pte++, address += PAGE_SIZE) {\n\t\tif (!pte_present(*pte))\n\t\t\tcontinue;\n\t\tpage = vm_normal_page(vma, address, *pte);\n\t\tBUG_ON(!page || PageAnon(page));\n\n\t\tif (locked_vma) {\n\t\t\tmlock_vma_page(page); /* no-op if already mlocked */\n\t\t\tif (page == check_page)\n\t\t\t\tret = SWAP_MLOCK;\n\t\t\tcontinue;\t/* don't unmap */\n\t\t}\n\n\t\tif (ptep_clear_flush_young_notify(vma, address, pte))\n\t\t\tcontinue;\n\n\t\t/* Nuke the page table entry. */\n\t\tflush_cache_page(vma, address, pte_pfn(*pte));\n\t\tpteval = ptep_clear_flush(vma, address, pte);\n\n\t\t/* If nonlinear, store the file page offset in the pte. */\n\t\tif (page->index != linear_page_index(vma, address)) {\n\t\t\tpte_t ptfile = pgoff_to_pte(page->index);\n\t\t\tif (pte_soft_dirty(pteval))\n\t\t\t\tpte_file_mksoft_dirty(ptfile);\n\t\t\tset_pte_at(mm, address, pte, ptfile);\n\t\t}\n\n\t\t/* Move the dirty bit to the physical page now the pte is gone. */\n\t\tif (pte_dirty(pteval))\n\t\t\tset_page_dirty(page);\n\n\t\tpage_remove_rmap(page);\n\t\tpage_cache_release(page);\n\t\tdec_mm_counter(mm, MM_FILEPAGES);\n\t\t(*mapcount)--;\n\t}\n\tpte_unmap_unlock(pte - 1, ptl);\n\tmmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);\n\tif (locked_vma)\n\t\tup_read(&vma->vm_mm->mmap_sem);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703', 'CWE-264'], 'message': 'mm: try_to_unmap_cluster() should lock_page() before mlocking\n\nA BUG_ON(!PageLocked) was triggered in mlock_vma_page() by Sasha Levin\nfuzzing with trinity. The call site try_to_unmap_cluster() does not lock\nthe pages other than its check_page parameter (which is already locked).\n\nThe BUG_ON in mlock_vma_page() is not documented and its purpose is\nsomewhat unclear, but apparently it serializes against page migration,\nwhich could otherwise fail to transfer the PG_mlocked flag. This would\nnot be fatal, as the page would be eventually encountered again, but\nNR_MLOCK accounting would become distorted nevertheless. This patch adds\na comment to the BUG_ON in mlock_vma_page() and munlock_vma_page() to that\neffect.\n\nThe call site try_to_unmap_cluster() is fixed so that for page !=\ncheck_page, trylock_page() is attempted (to avoid possible deadlocks as we\nalready have check_page locked) and mlock_vma_page() is performed only\nupon success. If the page lock cannot be obtained, the page is left\nwithout PG_mlocked, which is again not a problem in the whole unevictable\nmemory design.\n\nSigned-off-by: Vlastimil Babka \nSigned-off-by: Bob Liu \nReported-by: Sasha Levin \nCc: Wanpeng Li \nCc: Michel Lespinasse \nCc: KOSAKI Motohiro \nAcked-by: Rik van Riel \nCc: David Rientjes \nCc: Mel Gorman \nCc: Hugh Dickins \nCc: Joonsoo Kim \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Status TensorSliceReader::GetTensor(\n const string& name, std::unique_ptr* out_tensor) const {\n DataType type;\n TensorShape shape;\n TensorSlice slice;\n {\n mutex_lock l(mu_);\n const TensorSliceSet* tss = gtl::FindPtrOrNull(tensors_, name);\n if (tss == nullptr) {\n return errors::NotFound(name, \" not found in checkpoint file\");\n }\n\n if (tss->Slices().size() > 1) {\n // TODO(sherrym): Support multi-slice checkpoints.\n return errors::Unimplemented(\"Sliced checkpoints are not supported\");\n }\n\n type = tss->type();\n shape = tss->shape();\n slice = tss->Slices().begin()->second.slice;\n }\n\n std::unique_ptr t(new tensorflow::Tensor(type, shape));\n bool success = false;\n\n#define READER_COPY(dt) \\\n case dt: \\\n success = CopySliceData(name, slice, \\\n t->flat::Type>().data()); \\\n break;\n\n switch (type) {\n READER_COPY(DT_FLOAT);\n READER_COPY(DT_DOUBLE);\n READER_COPY(DT_INT32);\n READER_COPY(DT_UINT8);\n READER_COPY(DT_INT16);\n READER_COPY(DT_INT8);\n READER_COPY(DT_INT64);\n READER_COPY(DT_STRING);\n default:\n return errors::Unimplemented(\"Data type not supported\");\n }\n#undef READER_COPY\n\n if (!success) {\n return errors::NotFound(name, \" not found in checkpoint file\");\n }\n std::swap(*out_tensor, t);\n\n return Status::OK();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-345'], 'message': 'Prevent crashes when loading tensor slices with unsupported types.\n\nAlso fix the `Tensor(const TensorShape&)` constructor swapping the LOG(FATAL)\nmessages for the unset and unsupported types.\n\nPiperOrigin-RevId: 392695027\nChange-Id: I4beda7db950db951d273e3259a7c8534ece49354'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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_finished(SSL *s, int a, int b)\n\t{\n\tint al,i,ok;\n\tlong n;\n\tunsigned char *p;\n\n\t/* the mac has already been generated when we received the\n\t * change cipher spec message and is in s->s3->tmp.peer_finish_md\n\t */ \n\n\tn=s->method->ssl_get_message(s,\n\t\ta,\n\t\tb,\n\t\tSSL3_MT_FINISHED,\n\t\t64, /* should actually be 36+4 :-) */\n\t\t&ok);\n\n\tif (!ok) return((int)n);\n\n\t/* If this occurs, we have missed a message */\n\tif (!s->s3->change_cipher_spec)\n\t\t{\n\t\tal=SSL_AD_UNEXPECTED_MESSAGE;\n\t\tSSLerr(SSL_F_SSL3_GET_FINISHED,SSL_R_GOT_A_FIN_BEFORE_A_CCS);\n\t\tgoto f_err;\n\t\t}\n\ts->s3->change_cipher_spec=0;\n\n\tp = (unsigned char *)s->init_msg;\n\ti = s->s3->tmp.peer_finish_md_len;\n\n\tif (i != n)\n\t\t{\n\t\tal=SSL_AD_DECODE_ERROR;\n\t\tSSLerr(SSL_F_SSL3_GET_FINISHED,SSL_R_BAD_DIGEST_LENGTH);\n\t\tgoto f_err;\n\t\t}\n\n\tif (memcmp(p, s->s3->tmp.peer_finish_md, i) != 0)\n\t\t{\n\t\tal=SSL_AD_DECRYPT_ERROR;\n\t\tSSLerr(SSL_F_SSL3_GET_FINISHED,SSL_R_DIGEST_CHECK_FAILED);\n\t\tgoto f_err;\n\t\t}\n\n /* Copy the finished so we can use it for\n renegotiation checks */\n if(s->type == SSL_ST_ACCEPT)\n {\n OPENSSL_assert(i <= EVP_MAX_MD_SIZE);\n memcpy(s->s3->previous_client_finished, \n s->s3->tmp.peer_finish_md, i);\n s->s3->previous_client_finished_len=i;\n }\n else\n {\n OPENSSL_assert(i <= EVP_MAX_MD_SIZE);\n memcpy(s->s3->previous_server_finished, \n s->s3->tmp.peer_finish_md, i);\n s->s3->previous_server_finished_len=i;\n }\n\n\treturn(1);\nf_err:\n\tssl3_send_alert(s,SSL3_AL_FATAL,al);\n\treturn(0);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Add and use a constant-time memcmp.\n\nThis change adds CRYPTO_memcmp, which compares two vectors of bytes in\nan amount of time that's independent of their contents. It also changes\nseveral MAC compares in the code to use this over the standard memcmp,\nwhich may leak information about the size of a matching prefix.\n(cherry picked from commit 2ee798880a246d648ecddadc5b91367bee4a5d98)\n\nConflicts:\n\tcrypto/crypto.h\n\tssl/t1_lib.c\n(cherry picked from commit dc406b59f3169fe191e58906df08dce97edb727c)\n\nConflicts:\n\tcrypto/crypto.h\n\tssl/d1_pkt.c\n\tssl/s3_pkt.c'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void OpenSSL_add_all_ciphers(void)\n\t{\n\n#ifndef OPENSSL_NO_DES\n\tEVP_add_cipher(EVP_des_cfb());\n\tEVP_add_cipher(EVP_des_cfb1());\n\tEVP_add_cipher(EVP_des_cfb8());\n\tEVP_add_cipher(EVP_des_ede_cfb());\n\tEVP_add_cipher(EVP_des_ede3_cfb());\n\tEVP_add_cipher(EVP_des_ede3_cfb1());\n\tEVP_add_cipher(EVP_des_ede3_cfb8());\n\n\tEVP_add_cipher(EVP_des_ofb());\n\tEVP_add_cipher(EVP_des_ede_ofb());\n\tEVP_add_cipher(EVP_des_ede3_ofb());\n\n\tEVP_add_cipher(EVP_desx_cbc());\n\tEVP_add_cipher_alias(SN_desx_cbc,\"DESX\");\n\tEVP_add_cipher_alias(SN_desx_cbc,\"desx\");\n\n\tEVP_add_cipher(EVP_des_cbc());\n\tEVP_add_cipher_alias(SN_des_cbc,\"DES\");\n\tEVP_add_cipher_alias(SN_des_cbc,\"des\");\n\tEVP_add_cipher(EVP_des_ede_cbc());\n\tEVP_add_cipher(EVP_des_ede3_cbc());\n\tEVP_add_cipher_alias(SN_des_ede3_cbc,\"DES3\");\n\tEVP_add_cipher_alias(SN_des_ede3_cbc,\"des3\");\n\n\tEVP_add_cipher(EVP_des_ecb());\n\tEVP_add_cipher(EVP_des_ede());\n\tEVP_add_cipher(EVP_des_ede3());\n#endif\n\n#ifndef OPENSSL_NO_RC4\n\tEVP_add_cipher(EVP_rc4());\n\tEVP_add_cipher(EVP_rc4_40());\n#endif\n\n#ifndef OPENSSL_NO_IDEA\n\tEVP_add_cipher(EVP_idea_ecb());\n\tEVP_add_cipher(EVP_idea_cfb());\n\tEVP_add_cipher(EVP_idea_ofb());\n\tEVP_add_cipher(EVP_idea_cbc());\n\tEVP_add_cipher_alias(SN_idea_cbc,\"IDEA\");\n\tEVP_add_cipher_alias(SN_idea_cbc,\"idea\");\n#endif\n\n#ifndef OPENSSL_NO_SEED\n\tEVP_add_cipher(EVP_seed_ecb());\n\tEVP_add_cipher(EVP_seed_cfb());\n\tEVP_add_cipher(EVP_seed_ofb());\n\tEVP_add_cipher(EVP_seed_cbc());\n\tEVP_add_cipher_alias(SN_seed_cbc,\"SEED\");\n\tEVP_add_cipher_alias(SN_seed_cbc,\"seed\");\n#endif\n\n#ifndef OPENSSL_NO_RC2\n\tEVP_add_cipher(EVP_rc2_ecb());\n\tEVP_add_cipher(EVP_rc2_cfb());\n\tEVP_add_cipher(EVP_rc2_ofb());\n\tEVP_add_cipher(EVP_rc2_cbc());\n\tEVP_add_cipher(EVP_rc2_40_cbc());\n\tEVP_add_cipher(EVP_rc2_64_cbc());\n\tEVP_add_cipher_alias(SN_rc2_cbc,\"RC2\");\n\tEVP_add_cipher_alias(SN_rc2_cbc,\"rc2\");\n#endif\n\n#ifndef OPENSSL_NO_BF\n\tEVP_add_cipher(EVP_bf_ecb());\n\tEVP_add_cipher(EVP_bf_cfb());\n\tEVP_add_cipher(EVP_bf_ofb());\n\tEVP_add_cipher(EVP_bf_cbc());\n\tEVP_add_cipher_alias(SN_bf_cbc,\"BF\");\n\tEVP_add_cipher_alias(SN_bf_cbc,\"bf\");\n\tEVP_add_cipher_alias(SN_bf_cbc,\"blowfish\");\n#endif\n\n#ifndef OPENSSL_NO_CAST\n\tEVP_add_cipher(EVP_cast5_ecb());\n\tEVP_add_cipher(EVP_cast5_cfb());\n\tEVP_add_cipher(EVP_cast5_ofb());\n\tEVP_add_cipher(EVP_cast5_cbc());\n\tEVP_add_cipher_alias(SN_cast5_cbc,\"CAST\");\n\tEVP_add_cipher_alias(SN_cast5_cbc,\"cast\");\n\tEVP_add_cipher_alias(SN_cast5_cbc,\"CAST-cbc\");\n\tEVP_add_cipher_alias(SN_cast5_cbc,\"cast-cbc\");\n#endif\n\n#ifndef OPENSSL_NO_RC5\n\tEVP_add_cipher(EVP_rc5_32_12_16_ecb());\n\tEVP_add_cipher(EVP_rc5_32_12_16_cfb());\n\tEVP_add_cipher(EVP_rc5_32_12_16_ofb());\n\tEVP_add_cipher(EVP_rc5_32_12_16_cbc());\n\tEVP_add_cipher_alias(SN_rc5_cbc,\"rc5\");\n\tEVP_add_cipher_alias(SN_rc5_cbc,\"RC5\");\n#endif\n\n#ifndef OPENSSL_NO_AES\n\tEVP_add_cipher(EVP_aes_128_ecb());\n\tEVP_add_cipher(EVP_aes_128_cbc());\n\tEVP_add_cipher(EVP_aes_128_cfb());\n\tEVP_add_cipher(EVP_aes_128_cfb1());\n\tEVP_add_cipher(EVP_aes_128_cfb8());\n\tEVP_add_cipher(EVP_aes_128_ofb());\n#if 0\n\tEVP_add_cipher(EVP_aes_128_ctr());\n#endif\n\tEVP_add_cipher_alias(SN_aes_128_cbc,\"AES128\");\n\tEVP_add_cipher_alias(SN_aes_128_cbc,\"aes128\");\n\tEVP_add_cipher(EVP_aes_192_ecb());\n\tEVP_add_cipher(EVP_aes_192_cbc());\n\tEVP_add_cipher(EVP_aes_192_cfb());\n\tEVP_add_cipher(EVP_aes_192_cfb1());\n\tEVP_add_cipher(EVP_aes_192_cfb8());\n\tEVP_add_cipher(EVP_aes_192_ofb());\n#if 0\n\tEVP_add_cipher(EVP_aes_192_ctr());\n#endif\n\tEVP_add_cipher_alias(SN_aes_192_cbc,\"AES192\");\n\tEVP_add_cipher_alias(SN_aes_192_cbc,\"aes192\");\n\tEVP_add_cipher(EVP_aes_256_ecb());\n\tEVP_add_cipher(EVP_aes_256_cbc());\n\tEVP_add_cipher(EVP_aes_256_cfb());\n\tEVP_add_cipher(EVP_aes_256_cfb1());\n\tEVP_add_cipher(EVP_aes_256_cfb8());\n\tEVP_add_cipher(EVP_aes_256_ofb());\n#if 0\n\tEVP_add_cipher(EVP_aes_256_ctr());\n#endif\n\tEVP_add_cipher_alias(SN_aes_256_cbc,\"AES256\");\n\tEVP_add_cipher_alias(SN_aes_256_cbc,\"aes256\");\n#endif\n#endif\n\n#ifndef OPENSSL_NO_CAMELLIA\n\tEVP_add_cipher(EVP_camellia_128_ecb());\n\tEVP_add_cipher(EVP_camellia_128_cbc());\n\tEVP_add_cipher(EVP_camellia_128_cfb());\n\tEVP_add_cipher(EVP_camellia_128_cfb1());\n\tEVP_add_cipher(EVP_camellia_128_cfb8());\n\tEVP_add_cipher(EVP_camellia_128_ofb());\n\tEVP_add_cipher_alias(SN_camellia_128_cbc,\"CAMELLIA128\");\n\tEVP_add_cipher_alias(SN_camellia_128_cbc,\"camellia128\");\n\tEVP_add_cipher(EVP_camellia_192_ecb());\n\tEVP_add_cipher(EVP_camellia_192_cbc());\n\tEVP_add_cipher(EVP_camellia_192_cfb());\n\tEVP_add_cipher(EVP_camellia_192_cfb1());\n\tEVP_add_cipher(EVP_camellia_192_cfb8());\n\tEVP_add_cipher(EVP_camellia_192_ofb());\n\tEVP_add_cipher_alias(SN_camellia_192_cbc,\"CAMELLIA192\");\n\tEVP_add_cipher_alias(SN_camellia_192_cbc,\"camellia192\");\n\tEVP_add_cipher(EVP_camellia_256_ecb());\n\tEVP_add_cipher(EVP_camellia_256_cbc());\n\tEVP_add_cipher(EVP_camellia_256_cfb());\n\tEVP_add_cipher(EVP_camellia_256_cfb1());\n\tEVP_add_cipher(EVP_camellia_256_cfb8());\n\tEVP_add_cipher(EVP_camellia_256_ofb());\n\tEVP_add_cipher_alias(SN_camellia_256_cbc,\"CAMELLIA256\");\n\tEVP_add_cipher_alias(SN_camellia_256_cbc,\"camellia256\");\n#endif\n\n\tPKCS12_PBE_add();\n\tPKCS5_PBE_add();\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: static int ssl3_get_record(SSL *s)\n\t{\n\tint ssl_major,ssl_minor,al;\n\tint enc_err,n,i,ret= -1;\n\tSSL3_RECORD *rr;\n\tSSL_SESSION *sess;\n\tunsigned char *p;\n\tunsigned char md[EVP_MAX_MD_SIZE];\n\tshort version;\n\tunsigned mac_size;\n\tint clear=0;\n\tsize_t extra;\n\n\trr= &(s->s3->rrec);\n\tsess=s->session;\n\n\tif (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER)\n\t\textra=SSL3_RT_MAX_EXTRA;\n\telse\n\t\textra=0;\n\tif (extra != s->s3->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\t/* SSLerr() and ssl3_send_alert() have been called */\n\t\tgoto err;\n\t\t}\n\n#ifdef TLS_DEBUG\nprintf(\"dec %d\\n\",rr->length);\n{ unsigned int z; for (z=0; zlength; z++) printf(\"%02X%c\",rr->data[z],((z+1)%16)?' ':'\\n'); }\nprintf(\"\\n\");\n#endif\n\n\t/* r->length is now the compressed data plus mac */\n\tif (\t(sess == NULL) ||\n\t\t(s->enc_read_ctx == NULL) ||\n\t\t(s->read_hash == NULL))\n\t\tclear=1;\n\n\tif (!clear)\n\t\t{\n\t\t/* !clear => s->read_hash != NULL => mac_size != -1 */\n\t\tunsigned char *mac = NULL;\n\t\tunsigned char mac_tmp[EVP_MAX_MD_SIZE];\n\t\tmac_size=EVP_MD_size(s->read_hash);\n\t\tOPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);\n\n\t\t/* orig_len is the length of the record before any padding was\n\t\t * removed. This is public information, as is the MAC in use,\n\t\t * therefore we can safely process the record in a different\n\t\t * amount of time if it's too short to possibly contain a MAC.\n\t\t */\n\t\tif (rr->orig_len < mac_size ||\n\t\t /* CBC records must have a padding length byte too. */\n\t\t (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&\n\t\t rr->orig_len < mac_size+1))\n\t\t\t{\n\t\t\tal=SSL_AD_DECODE_ERROR;\n\t\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n\t\t\t}\n\n\t\tif (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE)\n\t\t\t{\n\t\t\t/* We update the length so that the TLS header bytes\n\t\t\t * can be constructed correctly but we need to extract\n\t\t\t * the MAC in constant time from within the record,\n\t\t\t * without leaking the contents of the padding bytes.\n\t\t\t * */\n\t\t\tmac = mac_tmp;\n\t\t\tssl3_cbc_copy_mac(mac_tmp, rr, mac_size);\n\t\t\trr->length -= mac_size;\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\t/* In this case there's no padding, so |rec->orig_len|\n\t\t\t * equals |rec->length| and we checked that there's\n\t\t\t * enough bytes for |mac_size| above. */\n\t\t\trr->length -= mac_size;\n\t\t\tmac = &rr->data[rr->length];\n\t\t\t}\n\n\t\ti=s->method->ssl3_enc->mac(s,md,0 /* not send */);\n\t\tif (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)\n\t\t\tenc_err = -1;\n\t\tif (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra+mac_size)\n\t\t\tenc_err = -1;\n\t\t}\n\n\tif (enc_err < 0)\n\t\t{\n\t\t/* A separate 'decryption_failed' alert was introduced with TLS 1.0,\n\t\t * SSL 3.0 only has 'bad_record_mac'. But unless a decryption\n\t\t * failure is directly visible from the ciphertext anyway,\n\t\t * we should not reveal which kind of error occured -- this\n\t\t * might become visible to an attacker (e.g. via a logfile) */\n\t\tal=SSL_AD_BAD_RECORD_MAC;\n\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);\n\t\tgoto f_err;\n\t\t}\n\n\t/* r->length is now just compressed */\n\tif (s->expand != NULL)\n\t\t{\n\t\tif (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra)\n\t\t\t{\n\t\t\tal=SSL_AD_RECORD_OVERFLOW;\n\t\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tif (!ssl3_do_uncompress(s))\n\t\t\t{\n\t\t\tal=SSL_AD_DECOMPRESSION_FAILURE;\n\t\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_BAD_DECOMPRESSION);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\t}\n\n\tif (rr->length > SSL3_RT_MAX_PLAIN_LENGTH+extra)\n\t\t{\n\t\tal=SSL_AD_RECORD_OVERFLOW;\n\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DATA_LENGTH_TOO_LONG);\n\t\tgoto f_err;\n\t\t}\n\n\trr->off=0;\n\t/* So at this point the following is true\n\t * ssl->s3->rrec.type \tis the type of record\n\t * ssl->s3->rrec.length\t== number of bytes in record\n\t * ssl->s3->rrec.off\t== offset to first valid byte\n\t * ssl->s3->rrec.data\t== where to take bytes from, increment\n\t *\t\t\t after use :-).\n\t */\n\n\t/* we have pulled in a full packet so zero things */\n\ts->packet_length=0;\n\n\t/* just read a 0 length packet */\n\tif (rr->length == 0) goto again;\n\n\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': '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\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': 'Timing fix mitigation for FIPS mode.\nWe have to use EVP in FIPS mode so we can only partially mitigate\ntiming differences.\n\nMake an extra call to HMAC_Update to hash additonal blocks\nto cover any timing differences caused by removal of padding.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen,\n\t\t\t\tconst unsigned char *sess_id, int sesslen,\n\t\t\t\tSSL_SESSION **psess)\n\t{\n\tSSL_SESSION *sess;\n\tunsigned char *sdec;\n\tconst unsigned char *p;\n\tint slen, mlen, renew_ticket = 0;\n\tunsigned char tick_hmac[EVP_MAX_MD_SIZE];\n\tHMAC_CTX hctx;\n\tEVP_CIPHER_CTX ctx;\n\tSSL_CTX *tctx = s->initial_ctx;\n\t/* Need at least keyname + iv + some encrypted data */\n\tif (eticklen < 48)\n\t\tgoto tickerr;\n\t/* Initialize session ticket encryption and HMAC contexts */\n\tHMAC_CTX_init(&hctx);\n\tEVP_CIPHER_CTX_init(&ctx);\n\tif (tctx->tlsext_ticket_key_cb)\n\t\t{\n\t\tunsigned char *nctick = (unsigned char *)etick;\n\t\tint rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,\n\t\t\t\t\t\t\t&ctx, &hctx, 0);\n\t\tif (rv < 0)\n\t\t\treturn -1;\n\t\tif (rv == 0)\n\t\t\tgoto tickerr;\n\t\tif (rv == 2)\n\t\t\trenew_ticket = 1;\n\t\t}\n\telse\n\t\t{\n\t\t/* Check key name matches */\n\t\tif (memcmp(etick, tctx->tlsext_tick_key_name, 16))\n\t\t\tgoto tickerr;\n\t\tHMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,\n\t\t\t\t\ttlsext_tick_md(), NULL);\n\t\tEVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,\n\t\t\t\ttctx->tlsext_tick_aes_key, etick + 16);\n\t\t}\n\t/* Attempt to process session ticket, first conduct sanity and\n \t * integrity checks on ticket.\n \t */\n\tmlen = HMAC_size(&hctx);\n\tif (mlen < 0)\n\t\t{\n\t\tEVP_CIPHER_CTX_cleanup(&ctx);\n\t\treturn -1;\n\t\t}\n\teticklen -= mlen;\n\t/* Check HMAC of encrypted ticket */\n\tHMAC_Update(&hctx, etick, eticklen);\n\tHMAC_Final(&hctx, tick_hmac, NULL);\n\tHMAC_CTX_cleanup(&hctx);\n\tif (memcmp(tick_hmac, etick + eticklen, mlen))\n\t\tgoto tickerr;\n\t/* Attempt to decrypt session data */\n\t/* Move p after IV to start of encrypted ticket, update length */\n\tp = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);\n\teticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx);\n\tsdec = OPENSSL_malloc(eticklen);\n\tif (!sdec)\n\t\t{\n\t\tEVP_CIPHER_CTX_cleanup(&ctx);\n\t\treturn -1;\n\t\t}\n\tEVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen);\n\tif (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0)\n\t\tgoto tickerr;\n\tslen += mlen;\n\tEVP_CIPHER_CTX_cleanup(&ctx);\n\tp = sdec;\n\t\t\n\tsess = d2i_SSL_SESSION(NULL, &p, slen);\n\tOPENSSL_free(sdec);\n\tif (sess)\n\t\t{\n\t\t/* The session ID if non-empty is used by some clients to\n \t\t * detect that the ticket has been accepted. So we copy it to\n \t\t * the session structure. If it is empty set length to zero\n \t\t * as required by standard.\n \t\t */\n\t\tif (sesslen)\n\t\t\tmemcpy(sess->session_id, sess_id, sesslen);\n\t\tsess->session_id_length = sesslen;\n\t\t*psess = sess;\n\t\ts->tlsext_ticket_expected = renew_ticket;\n\t\treturn 1;\n\t\t}\n\t/* If session decrypt failure indicate a cache miss and set state to\n \t * send a new ticket\n \t */\n\ttickerr:\t\n\ts->tlsext_ticket_expected = 1;\n\treturn 0;\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 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#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#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': '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: dtls1_process_record(SSL *s)\n{\n\tint i,al;\n\tint clear=0;\n\tint enc_err;\n\tSSL_SESSION *sess;\n\tSSL3_RECORD *rr;\n\tunsigned int mac_size;\n\tunsigned char md[EVP_MAX_MD_SIZE];\n\tint decryption_failed_or_bad_record_mac = 0;\n\tunsigned char *mac = NULL;\n\n\n\trr= &(s->s3->rrec);\n\tsess = s->session;\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[DTLS1_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)\n\t\t{\n\t\tal=SSL_AD_RECORD_OVERFLOW;\n\t\tSSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG);\n\t\tgoto f_err;\n\t\t}\n\n\t/* decrypt in place in 'rr->input' */\n\trr->data=rr->input;\n\trr->orig_len=rr->length;\n\n\tenc_err = s->method->ssl3_enc->enc(s,0);\n\tif (enc_err <= 0)\n\t\t{\n\t\t/* To minimize information leaked via timing, we will always\n\t\t * perform all computations before discarding the message.\n\t\t */\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\t/* !clear => s->read_hash != NULL => mac_size != -1 */\n\t\tint t;\n\t\tt=EVP_MD_CTX_size(s->read_hash);\n\t\tOPENSSL_assert(t >= 0);\n\t\tmac_size=t;\n\n\t\tif (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+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_DTLS1_PROCESS_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\trr->length = 0;\n\t\ti=s->method->ssl3_enc->mac(s,md,0);\n\t\tif (i < 0 || mac == NULL || CRYPTO_memcmp(md,mac,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/* decryption failed, silently discard message */\n\t\trr->length = 0;\n\t\ts->packet_length = 0;\n\t\tgoto 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)\n\t\t\t{\n\t\t\tal=SSL_AD_RECORD_OVERFLOW;\n\t\t\tSSLerr(SSL_F_DTLS1_PROCESS_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_DTLS1_PROCESS_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)\n\t\t{\n\t\tal=SSL_AD_RECORD_OVERFLOW;\n\t\tSSLerr(SSL_F_DTLS1_PROCESS_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\tdtls1_record_bitmap_update(s, &(s->d1->bitmap));/* Mark receipt of record. */\n\treturn(1);\n\nf_err:\n\tssl3_send_alert(s,SSL3_AL_FATAL,al);\nerr:\n\treturn(0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Update DTLS code to match CBC decoding in TLS.\n\nThis change updates the DTLS code to match the constant-time CBC\nbehaviour in the TLS.\n(cherry picked from commit 9f27de170d1b7bef3d46d41382dc4dafde8b3900)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void OpenSSL_add_all_ciphers(void)\n\t{\n\n#ifndef OPENSSL_NO_DES\n\tEVP_add_cipher(EVP_des_cfb());\n\tEVP_add_cipher(EVP_des_cfb1());\n\tEVP_add_cipher(EVP_des_cfb8());\n\tEVP_add_cipher(EVP_des_ede_cfb());\n\tEVP_add_cipher(EVP_des_ede3_cfb());\n\tEVP_add_cipher(EVP_des_ede3_cfb1());\n\tEVP_add_cipher(EVP_des_ede3_cfb8());\n\n\tEVP_add_cipher(EVP_des_ofb());\n\tEVP_add_cipher(EVP_des_ede_ofb());\n\tEVP_add_cipher(EVP_des_ede3_ofb());\n\n\tEVP_add_cipher(EVP_desx_cbc());\n\tEVP_add_cipher_alias(SN_desx_cbc,\"DESX\");\n\tEVP_add_cipher_alias(SN_desx_cbc,\"desx\");\n\n\tEVP_add_cipher(EVP_des_cbc());\n\tEVP_add_cipher_alias(SN_des_cbc,\"DES\");\n\tEVP_add_cipher_alias(SN_des_cbc,\"des\");\n\tEVP_add_cipher(EVP_des_ede_cbc());\n\tEVP_add_cipher(EVP_des_ede3_cbc());\n\tEVP_add_cipher_alias(SN_des_ede3_cbc,\"DES3\");\n\tEVP_add_cipher_alias(SN_des_ede3_cbc,\"des3\");\n\n\tEVP_add_cipher(EVP_des_ecb());\n\tEVP_add_cipher(EVP_des_ede());\n\tEVP_add_cipher(EVP_des_ede3());\n#endif\n\n#ifndef OPENSSL_NO_RC4\n\tEVP_add_cipher(EVP_rc4());\n\tEVP_add_cipher(EVP_rc4_40());\n#ifndef OPENSSL_NO_MD5\n\tEVP_add_cipher(EVP_rc4_hmac_md5());\n#endif\n#endif\n\n#ifndef OPENSSL_NO_IDEA\n\tEVP_add_cipher(EVP_idea_ecb());\n\tEVP_add_cipher(EVP_idea_cfb());\n\tEVP_add_cipher(EVP_idea_ofb());\n\tEVP_add_cipher(EVP_idea_cbc());\n\tEVP_add_cipher_alias(SN_idea_cbc,\"IDEA\");\n\tEVP_add_cipher_alias(SN_idea_cbc,\"idea\");\n#endif\n\n#ifndef OPENSSL_NO_SEED\n\tEVP_add_cipher(EVP_seed_ecb());\n\tEVP_add_cipher(EVP_seed_cfb());\n\tEVP_add_cipher(EVP_seed_ofb());\n\tEVP_add_cipher(EVP_seed_cbc());\n\tEVP_add_cipher_alias(SN_seed_cbc,\"SEED\");\n\tEVP_add_cipher_alias(SN_seed_cbc,\"seed\");\n#endif\n\n#ifndef OPENSSL_NO_RC2\n\tEVP_add_cipher(EVP_rc2_ecb());\n\tEVP_add_cipher(EVP_rc2_cfb());\n\tEVP_add_cipher(EVP_rc2_ofb());\n\tEVP_add_cipher(EVP_rc2_cbc());\n\tEVP_add_cipher(EVP_rc2_40_cbc());\n\tEVP_add_cipher(EVP_rc2_64_cbc());\n\tEVP_add_cipher_alias(SN_rc2_cbc,\"RC2\");\n\tEVP_add_cipher_alias(SN_rc2_cbc,\"rc2\");\n#endif\n\n#ifndef OPENSSL_NO_BF\n\tEVP_add_cipher(EVP_bf_ecb());\n\tEVP_add_cipher(EVP_bf_cfb());\n\tEVP_add_cipher(EVP_bf_ofb());\n\tEVP_add_cipher(EVP_bf_cbc());\n\tEVP_add_cipher_alias(SN_bf_cbc,\"BF\");\n\tEVP_add_cipher_alias(SN_bf_cbc,\"bf\");\n\tEVP_add_cipher_alias(SN_bf_cbc,\"blowfish\");\n#endif\n\n#ifndef OPENSSL_NO_CAST\n\tEVP_add_cipher(EVP_cast5_ecb());\n\tEVP_add_cipher(EVP_cast5_cfb());\n\tEVP_add_cipher(EVP_cast5_ofb());\n\tEVP_add_cipher(EVP_cast5_cbc());\n\tEVP_add_cipher_alias(SN_cast5_cbc,\"CAST\");\n\tEVP_add_cipher_alias(SN_cast5_cbc,\"cast\");\n\tEVP_add_cipher_alias(SN_cast5_cbc,\"CAST-cbc\");\n\tEVP_add_cipher_alias(SN_cast5_cbc,\"cast-cbc\");\n#endif\n\n#ifndef OPENSSL_NO_RC5\n\tEVP_add_cipher(EVP_rc5_32_12_16_ecb());\n\tEVP_add_cipher(EVP_rc5_32_12_16_cfb());\n\tEVP_add_cipher(EVP_rc5_32_12_16_ofb());\n\tEVP_add_cipher(EVP_rc5_32_12_16_cbc());\n\tEVP_add_cipher_alias(SN_rc5_cbc,\"rc5\");\n\tEVP_add_cipher_alias(SN_rc5_cbc,\"RC5\");\n#endif\n\n#ifndef OPENSSL_NO_AES\n\tEVP_add_cipher(EVP_aes_128_ecb());\n\tEVP_add_cipher(EVP_aes_128_cbc());\n\tEVP_add_cipher(EVP_aes_128_cfb());\n\tEVP_add_cipher(EVP_aes_128_cfb1());\n\tEVP_add_cipher(EVP_aes_128_cfb8());\n\tEVP_add_cipher(EVP_aes_128_ofb());\n\tEVP_add_cipher(EVP_aes_128_ctr());\n\tEVP_add_cipher(EVP_aes_128_gcm());\n\tEVP_add_cipher(EVP_aes_128_xts());\n\tEVP_add_cipher_alias(SN_aes_128_cbc,\"AES128\");\n\tEVP_add_cipher_alias(SN_aes_128_cbc,\"aes128\");\n\tEVP_add_cipher(EVP_aes_192_ecb());\n\tEVP_add_cipher(EVP_aes_192_cbc());\n\tEVP_add_cipher(EVP_aes_192_cfb());\n\tEVP_add_cipher(EVP_aes_192_cfb1());\n\tEVP_add_cipher(EVP_aes_192_cfb8());\n\tEVP_add_cipher(EVP_aes_192_ofb());\n\tEVP_add_cipher(EVP_aes_192_ctr());\n\tEVP_add_cipher(EVP_aes_192_gcm());\n\tEVP_add_cipher_alias(SN_aes_192_cbc,\"AES192\");\n\tEVP_add_cipher_alias(SN_aes_192_cbc,\"aes192\");\n\tEVP_add_cipher(EVP_aes_256_ecb());\n\tEVP_add_cipher(EVP_aes_256_cbc());\n\tEVP_add_cipher(EVP_aes_256_cfb());\n\tEVP_add_cipher(EVP_aes_256_cfb1());\n\tEVP_add_cipher(EVP_aes_256_cfb8());\n\tEVP_add_cipher(EVP_aes_256_ofb());\n\tEVP_add_cipher(EVP_aes_256_ctr());\n\tEVP_add_cipher(EVP_aes_256_gcm());\n\tEVP_add_cipher(EVP_aes_256_xts());\n\tEVP_add_cipher_alias(SN_aes_256_cbc,\"AES256\");\n\tEVP_add_cipher_alias(SN_aes_256_cbc,\"aes256\");\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#endif\n\n#ifndef OPENSSL_NO_CAMELLIA\n\tEVP_add_cipher(EVP_camellia_128_ecb());\n\tEVP_add_cipher(EVP_camellia_128_cbc());\n\tEVP_add_cipher(EVP_camellia_128_cfb());\n\tEVP_add_cipher(EVP_camellia_128_cfb1());\n\tEVP_add_cipher(EVP_camellia_128_cfb8());\n\tEVP_add_cipher(EVP_camellia_128_ofb());\n\tEVP_add_cipher_alias(SN_camellia_128_cbc,\"CAMELLIA128\");\n\tEVP_add_cipher_alias(SN_camellia_128_cbc,\"camellia128\");\n\tEVP_add_cipher(EVP_camellia_192_ecb());\n\tEVP_add_cipher(EVP_camellia_192_cbc());\n\tEVP_add_cipher(EVP_camellia_192_cfb());\n\tEVP_add_cipher(EVP_camellia_192_cfb1());\n\tEVP_add_cipher(EVP_camellia_192_cfb8());\n\tEVP_add_cipher(EVP_camellia_192_ofb());\n\tEVP_add_cipher_alias(SN_camellia_192_cbc,\"CAMELLIA192\");\n\tEVP_add_cipher_alias(SN_camellia_192_cbc,\"camellia192\");\n\tEVP_add_cipher(EVP_camellia_256_ecb());\n\tEVP_add_cipher(EVP_camellia_256_cbc());\n\tEVP_add_cipher(EVP_camellia_256_cfb());\n\tEVP_add_cipher(EVP_camellia_256_cfb1());\n\tEVP_add_cipher(EVP_camellia_256_cfb8());\n\tEVP_add_cipher(EVP_camellia_256_ofb());\n\tEVP_add_cipher_alias(SN_camellia_256_cbc,\"CAMELLIA256\");\n\tEVP_add_cipher_alias(SN_camellia_256_cbc,\"camellia256\");\n#endif\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': '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_set_base_uri (RsvgHandle * handle, const char *base_uri)\n{\n gchar *uri;\n\n g_return_if_fail (handle != NULL);\n\n if (base_uri == NULL)\n\treturn;\n\n if (rsvg_path_is_uri (base_uri)) \n uri = g_strdup (base_uri);\n else\n uri = rsvg_get_base_uri_from_filename (base_uri);\n\n if (uri) {\n if (handle->priv->base_uri)\n g_free (handle->priv->base_uri);\n handle->priv->base_uri = uri;\n }\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_do_change_cipher_spec(SSL *s)\n\t{\n\tint i;\n\tconst char *sender;\n\tint slen;\n\n\tif (s->state & SSL_ST_ACCEPT)\n\t\ti=SSL3_CHANGE_CIPHER_SERVER_READ;\n\telse\n\t\ti=SSL3_CHANGE_CIPHER_CLIENT_READ;\n\n\tif (s->s3->tmp.key_block == NULL)\n\t\t{\n\t\tif (s->session == NULL) \n\t\t\t{\n\t\t\t/* might happen if dtls1_read_bytes() calls this */\n\t\t\tSSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC,SSL_R_CCS_RECEIVED_EARLY);\n\t\t\treturn (0);\n\t\t\t}\n\n\t\ts->session->cipher=s->s3->tmp.new_cipher;\n\t\tif (!s->method->ssl3_enc->setup_key_block(s)) return(0);\n\t\t}\n\n\tif (!s->method->ssl3_enc->change_cipher_state(s,i))\n\t\treturn(0);\n\n\t/* we have to record the message digest at\n\t * this point so we can get it before we read\n\t * the finished message */\n\tif (s->state & SSL_ST_CONNECT)\n\t\t{\n\t\tsender=s->method->ssl3_enc->server_finished_label;\n\t\tslen=s->method->ssl3_enc->server_finished_label_len;\n\t\t}\n\telse\n\t\t{\n\t\tsender=s->method->ssl3_enc->client_finished_label;\n\t\tslen=s->method->ssl3_enc->client_finished_label_len;\n\t\t}\n\n\ti = s->method->ssl3_enc->final_finish_mac(s,\n\t\tsender,slen,s->s3->tmp.peer_finish_md);\n\tif (i == 0)\n\t\t{\n\t\tSSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);\n\t\treturn 0;\n\t\t}\n\ts->s3->tmp.peer_finish_md_len = i;\n\n\treturn(1);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-326'], 'message': 'Additional CVE-2014-0224 protection.\n\nReturn a fatal error if an attempt is made to use a zero length\nmaster secret.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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\tif (s->version < TLS1_2_VERSION && tls1_suiteb(s))\n\t\t{\n\t\tSSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,\n\t\t\t\tSSL_R_ONLY_TLS_1_2_ALLOWED_IN_SUITEB_MODE);\n\t\tgoto err;\n\t\t}\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 (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL))\n\t\t{\n\t\tSSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_VERSION_TOO_LOW);\n\t\tgoto err;\n\t\t}\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': '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: long ssl3_ctrl(SSL *s, int cmd, long larg, void *parg)\n\t{\n\tint ret=0;\n\n#if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_RSA)\n\tif (\n#ifndef OPENSSL_NO_RSA\n\t cmd == SSL_CTRL_SET_TMP_RSA ||\n\t cmd == SSL_CTRL_SET_TMP_RSA_CB ||\n#endif\n#ifndef OPENSSL_NO_DSA\n\t cmd == SSL_CTRL_SET_TMP_DH ||\n\t cmd == SSL_CTRL_SET_TMP_DH_CB ||\n#endif\n\t\t0)\n\t\t{\n\t\tif (!ssl_cert_inst(&s->cert))\n\t\t \t{\n\t\t\tSSLerr(SSL_F_SSL3_CTRL, ERR_R_MALLOC_FAILURE);\n\t\t\treturn(0);\n\t\t\t}\n\t\t}\n#endif\n\n\tswitch (cmd)\n\t\t{\n\tcase SSL_CTRL_GET_SESSION_REUSED:\n\t\tret=s->hit;\n\t\tbreak;\n\tcase SSL_CTRL_GET_CLIENT_CERT_REQUEST:\n\t\tbreak;\n\tcase SSL_CTRL_GET_NUM_RENEGOTIATIONS:\n\t\tret=s->s3->num_renegotiations;\n\t\tbreak;\n\tcase SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS:\n\t\tret=s->s3->num_renegotiations;\n\t\ts->s3->num_renegotiations=0;\n\t\tbreak;\n\tcase SSL_CTRL_GET_TOTAL_RENEGOTIATIONS:\n\t\tret=s->s3->total_renegotiations;\n\t\tbreak;\n\tcase SSL_CTRL_GET_FLAGS:\n\t\tret=(int)(s->s3->flags);\n\t\tbreak;\n#ifndef OPENSSL_NO_RSA\n\tcase SSL_CTRL_NEED_TMP_RSA:\n\t\tif ((s->cert != NULL) && (s->cert->rsa_tmp == NULL) &&\n\t\t ((s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL) ||\n\t\t (EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey) > (512/8))))\n\t\t\tret = 1;\n\t\tbreak;\n\tcase SSL_CTRL_SET_TMP_RSA:\n\t\t{\n\t\t\tRSA *rsa = (RSA *)parg;\n\t\t\tif (rsa == NULL)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_CTRL, ERR_R_PASSED_NULL_PARAMETER);\n\t\t\t\treturn(ret);\n\t\t\t\t}\n\t\t\tif ((rsa = RSAPrivateKey_dup(rsa)) == NULL)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_CTRL, ERR_R_RSA_LIB);\n\t\t\t\treturn(ret);\n\t\t\t\t}\n\t\t\tif (s->cert->rsa_tmp != NULL)\n\t\t\t\tRSA_free(s->cert->rsa_tmp);\n\t\t\ts->cert->rsa_tmp = rsa;\n\t\t\tret = 1;\n\t\t}\n\t\tbreak;\n\tcase SSL_CTRL_SET_TMP_RSA_CB:\n\t\t{\n\t\tSSLerr(SSL_F_SSL3_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);\n\t\treturn(ret);\n\t\t}\n\t\tbreak;\n#endif\n#ifndef OPENSSL_NO_DH\n\tcase SSL_CTRL_SET_TMP_DH:\n\t\t{\n\t\t\tDH *dh = (DH *)parg;\n\t\t\tif (dh == NULL)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_CTRL, ERR_R_PASSED_NULL_PARAMETER);\n\t\t\t\treturn(ret);\n\t\t\t\t}\n\t\t\tif ((dh = DHparams_dup(dh)) == NULL)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_CTRL, ERR_R_DH_LIB);\n\t\t\t\treturn(ret);\n\t\t\t\t}\n\t\t\tif (!(s->options & SSL_OP_SINGLE_DH_USE))\n\t\t\t\t{\n\t\t\t\tif (!DH_generate_key(dh))\n\t\t\t\t\t{\n\t\t\t\t\tDH_free(dh);\n\t\t\t\t\tSSLerr(SSL_F_SSL3_CTRL, ERR_R_DH_LIB);\n\t\t\t\t\treturn(ret);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tif (s->cert->dh_tmp != NULL)\n\t\t\t\tDH_free(s->cert->dh_tmp);\n\t\t\ts->cert->dh_tmp = dh;\n\t\t\tret = 1;\n\t\t}\n\t\tbreak;\n\tcase SSL_CTRL_SET_TMP_DH_CB:\n\t\t{\n\t\tSSLerr(SSL_F_SSL3_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);\n\t\treturn(ret);\n\t\t}\n\t\tbreak;\n#endif\n#ifndef OPENSSL_NO_ECDH\n\tcase SSL_CTRL_SET_TMP_ECDH:\n\t\t{\n\t\tEC_KEY *ecdh = NULL;\n \t\t\t\n\t\tif (parg == NULL)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_CTRL, ERR_R_PASSED_NULL_PARAMETER);\n\t\t\treturn(ret);\n\t\t\t}\n\t\tif (!EC_KEY_up_ref((EC_KEY *)parg))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_CTRL,ERR_R_ECDH_LIB);\n\t\t\treturn(ret);\n\t\t\t}\n\t\tecdh = (EC_KEY *)parg;\n\t\tif (!(s->options & SSL_OP_SINGLE_ECDH_USE))\n\t\t\t{\n\t\t\tif (!EC_KEY_generate_key(ecdh))\n\t\t\t\t{\n\t\t\t\tEC_KEY_free(ecdh);\n\t\t\t\tSSLerr(SSL_F_SSL3_CTRL,ERR_R_ECDH_LIB);\n\t\t\t\treturn(ret);\n\t\t\t\t}\n\t\t\t}\n\t\tif (s->cert->ecdh_tmp != NULL)\n\t\t\tEC_KEY_free(s->cert->ecdh_tmp);\n\t\ts->cert->ecdh_tmp = ecdh;\n\t\tret = 1;\n\t\t}\n\t\tbreak;\n\tcase SSL_CTRL_SET_TMP_ECDH_CB:\n\t\t{\n\t\tSSLerr(SSL_F_SSL3_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);\n\t\treturn(ret);\n\t\t}\n\t\tbreak;\n#endif /* !OPENSSL_NO_ECDH */\n#ifndef OPENSSL_NO_TLSEXT\n\tcase SSL_CTRL_SET_TLSEXT_HOSTNAME:\n \t\tif (larg == TLSEXT_NAMETYPE_host_name)\n\t\t\t{\n\t\t\tif (s->tlsext_hostname != NULL) \n\t\t\t\tOPENSSL_free(s->tlsext_hostname);\n\t\t\ts->tlsext_hostname = NULL;\n\n\t\t\tret = 1;\n\t\t\tif (parg == NULL) \n\t\t\t\tbreak;\n\t\t\tif (strlen((char *)parg) > TLSEXT_MAXLEN_host_name)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_CTRL, SSL_R_SSL3_EXT_INVALID_SERVERNAME);\n\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\tif ((s->tlsext_hostname = BUF_strdup((char *)parg)) == NULL)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_CTRL, ERR_R_INTERNAL_ERROR);\n\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_CTRL, SSL_R_SSL3_EXT_INVALID_SERVERNAME_TYPE);\n\t\t\treturn 0;\n\t\t\t}\n \t\tbreak;\n\tcase SSL_CTRL_SET_TLSEXT_DEBUG_ARG:\n\t\ts->tlsext_debug_arg=parg;\n\t\tret = 1;\n\t\tbreak;\n \n\tcase SSL_CTRL_SET_TLSEXT_STATUS_REQ_TYPE:\n\t\ts->tlsext_status_type=larg;\n\t\tret = 1;\n\t\tbreak;\n\n\tcase SSL_CTRL_GET_TLSEXT_STATUS_REQ_EXTS:\n\t\t*(STACK_OF(X509_EXTENSION) **)parg = s->tlsext_ocsp_exts;\n\t\tret = 1;\n\t\tbreak;\n\n\tcase SSL_CTRL_SET_TLSEXT_STATUS_REQ_EXTS:\n\t\ts->tlsext_ocsp_exts = parg;\n\t\tret = 1;\n\t\tbreak;\n\n\tcase SSL_CTRL_GET_TLSEXT_STATUS_REQ_IDS:\n\t\t*(STACK_OF(OCSP_RESPID) **)parg = s->tlsext_ocsp_ids;\n\t\tret = 1;\n\t\tbreak;\n\n\tcase SSL_CTRL_SET_TLSEXT_STATUS_REQ_IDS:\n\t\ts->tlsext_ocsp_ids = parg;\n\t\tret = 1;\n\t\tbreak;\n\n\tcase SSL_CTRL_GET_TLSEXT_STATUS_REQ_OCSP_RESP:\n\t\t*(unsigned char **)parg = s->tlsext_ocsp_resp;\n\t\treturn s->tlsext_ocsp_resplen;\n\t\t\n\tcase SSL_CTRL_SET_TLSEXT_STATUS_REQ_OCSP_RESP:\n\t\tif (s->tlsext_ocsp_resp)\n\t\t\tOPENSSL_free(s->tlsext_ocsp_resp);\n\t\ts->tlsext_ocsp_resp = parg;\n\t\ts->tlsext_ocsp_resplen = larg;\n\t\tret = 1;\n\t\tbreak;\n\n#endif /* !OPENSSL_NO_TLSEXT */\n\tdefault:\n\t\tbreak;\n\t\t}\n\treturn(ret);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Support TLS_FALLBACK_SCSV.\n\nReviewed-by: Stephen Henson '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ssl_parse_clienthello_use_srtp_ext(SSL *s, unsigned char *d, int len,int *al)\n\t{\n\tSRTP_PROTECTION_PROFILE *cprof,*sprof;\n\tSTACK_OF(SRTP_PROTECTION_PROFILE) *clnt=0,*srvr;\n int ct;\n int mki_len;\n\tint i,j;\n\tint id;\n\tint ret;\n\n /* Length value + the MKI length */\n if(len < 3)\n\t\t{ \n\t\tSSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_USE_SRTP_EXT,SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);\n\t\t*al=SSL_AD_DECODE_ERROR;\n\t\treturn 1;\n }\n\n /* Pull off the length of the cipher suite list */\n n2s(d, ct);\n len -= 2;\n \n /* Check that it is even */\n\tif(ct%2)\n\t\t{\n\t\tSSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_USE_SRTP_EXT,SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);\n\t\t*al=SSL_AD_DECODE_ERROR;\n\t\treturn 1;\n\t\t}\n \n /* Check that lengths are consistent */\n\tif(len < (ct + 1)) \n\t\t{\n\t\tSSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_USE_SRTP_EXT,SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);\n\t\t*al=SSL_AD_DECODE_ERROR;\n\t\treturn 1;\n\t\t}\n\n \n\tclnt=sk_SRTP_PROTECTION_PROFILE_new_null();\n\n\twhile(ct)\n\t\t{\n\t\tn2s(d,id);\n\t\tct-=2;\n len-=2;\n\n\t\tif(!find_profile_by_num(id,&cprof))\n\t\t\t{\n\t\t\tsk_SRTP_PROTECTION_PROFILE_push(clnt,cprof);\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\t; /* Ignore */\n\t\t\t}\n\t\t}\n\n /* Now extract the MKI value as a sanity check, but discard it for now */\n mki_len = *d;\n d++; len--;\n\n if (mki_len != len)\n\t\t{\n\t\tSSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_USE_SRTP_EXT,SSL_R_BAD_SRTP_MKI_VALUE);\n\t\t*al=SSL_AD_DECODE_ERROR;\n\t\treturn 1;\n\t\t}\n\n\tsrvr=SSL_get_srtp_profiles(s);\n\n\t/* Pick our most preferred profile. If no profiles have been\n\t configured then the outer loop doesn't run \n\t (sk_SRTP_PROTECTION_PROFILE_num() = -1)\n\t and so we just return without doing anything */\n\tfor(i=0;iid==sprof->id)\n\t\t\t\t{\n\t\t\t\ts->srtp_profile=sprof;\n\t\t\t\t*al=0;\n\t\t\t\tret=0;\n\t\t\t\tgoto done;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tret=0;\n \ndone:\n\tif(clnt) sk_SRTP_PROTECTION_PROFILE_free(clnt);\n\n\treturn ret;\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix for SRTP Memory Leak\n\nCVE-2014-3513\n\nThis issue was reported to OpenSSL on 26th September 2014, based on an origi\nissue and patch developed by the LibreSSL project. Further analysis of the i\nwas performed by the OpenSSL team.\n\nThe fix was developed by the OpenSSL team.\n\nReviewed-by: Tim Hudson '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static const SSL_METHOD *ssl23_get_server_method(int ver)\n\t{\n#ifndef OPENSSL_NO_SSL2\n\tif (ver == SSL2_VERSION)\n\t\treturn(SSLv2_server_method());\n#endif\n\tif (ver == SSL3_VERSION)\n\t\treturn(SSLv3_server_method());\n\telse if (ver == TLS1_VERSION)\n\t\treturn(TLSv1_server_method());\n\telse if (ver == TLS1_1_VERSION)\n\t\treturn(TLSv1_1_server_method());\n\telse if (ver == TLS1_2_VERSION)\n\t\treturn(TLSv1_2_server_method());\n\telse\n\t\treturn(NULL);\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 alg_k,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#ifndef OPENSSL_NO_HEARTBEATS\n\t/* If we're awaiting a HeartbeatResponse, pretend we\n\t * already got and don't await it anymore, because\n\t * Heartbeats don't make sense during handshakes anyway.\n\t */\n\tif (s->tlsext_hb_pending)\n\t\t{\n\t\ts->tlsext_hb_pending = 0;\n\t\ts->tlsext_hb_seq++;\n\t\t}\n#endif\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->renegotiate=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\n\t\t\tif (!ssl_security(s, SSL_SECOP_VERSION, 0,\n\t\t\t\t\t\t\ts->version, NULL))\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_ACCEPT, SSL_R_VERSION_TOO_LOW);\n\t\t\t\treturn -1;\n\t\t\t\t}\n\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\tBUF_MEM_free(buf);\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 &= ~TLS1_FLAGS_SKIP_CERT_VERIFY;\n\t\t\ts->s3->flags &= ~SSL3_FLAGS_CCS_OK;\n\t\t\t/* Should have been reset by ssl3_get_finished, too. */\n\t\t\ts->s3->change_cipher_spec = 0;\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\tret=ssl3_get_client_hello(s);\n\t\t\tif (ret <= 0) goto end;\n#ifndef OPENSSL_NO_SRP\n\t\t\ts->state = SSL3_ST_SR_CLNT_HELLO_D;\n\t\tcase SSL3_ST_SR_CLNT_HELLO_D:\n\t\t\t{\n\t\t\tint al;\n\t\t\tif ((ret = ssl_check_srp_ext_ClientHello(s,&al)) < 0)\n\t\t\t\t\t{\n\t\t\t\t\t/* callback indicates firther work to be done */\n\t\t\t\t\ts->rwstate=SSL_X509_LOOKUP;\n\t\t\t\t\tgoto end;\n\t\t\t\t\t}\n\t\t\tif (ret != SSL_ERROR_NONE)\n\t\t\t\t{\n\t\t\t\tssl3_send_alert(s,SSL3_AL_FATAL,al);\t\n\t\t\t\t/* This is not really an error but the only means to\n for a client to detect whether srp is supported. */\n \t\t\t\t if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY) \t\n\t\t\t\t\tSSLerr(SSL_F_SSL3_ACCEPT,SSL_R_CLIENTHELLO_TLSEXT);\t\t\t\n\t\t\t\tret = SSL_TLSEXT_ERR_ALERT_FATAL;\t\t\t\n\t\t\t\tret= -1;\n\t\t\t\tgoto end;\t\n\t\t\t\t}\n\t\t\t}\n#endif\t\t\n\t\t\t\n\t\t\ts->renegotiate = 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\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, */\n\t\t\t/* normal PSK or KRB5 or SRP */\n\t\t\tif (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aKRB5|SSL_aSRP))\n\t\t\t\t&& !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))\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\talg_k = s->s3->tmp.new_cipher->algorithm_mkey;\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&& !(alg_k & SSL_kKRB5)\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 * PSK: may send PSK identity hints\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/* PSK: send ServerKeyExchange if PSK identity\n\t\t\t * hint if provided */\n#ifndef OPENSSL_NO_PSK\n\t\t\t || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint)\n#endif\n#ifndef OPENSSL_NO_SRP\n\t\t\t /* SRP: send ServerKeyExchange */\n\t\t\t || (alg_k & SSL_kSRP)\n#endif\n\t\t\t || (alg_k & SSL_kDHE)\n\t\t\t || (alg_k & SSL_kECDHE)\n\t\t\t || ((alg_k & 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->algorithm_auth & 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\t\t\t\t /* never request cert in Kerberos ciphersuites */\n\t\t\t\t(s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) ||\n\t\t\t\t/* don't request certificate for SRP auth */\n\t\t\t\t(s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)\n\t\t\t\t/* With normal PSK Certificates and\n\t\t\t\t * Certificate Requests are omitted */\n\t\t\t\t|| (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))\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\tif (s->s3->handshake_buffer)\n\t\t\t\t\tif (!ssl3_digest_cached_records(s))\n\t\t\t\t\t\treturn -1;\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\tif (s->s3->tmp.cert_request)\n\t\t\t\t{\n\t\t\t\tret=ssl3_get_client_certificate(s);\n\t\t\t\tif (ret <= 0) goto end;\n\t\t\t\t}\n\t\t\ts->init_num=0;\n\t\t\ts->state=SSL3_ST_SR_KEY_EXCH_A;\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 * Also for GOST ciphersuites when\n\t\t\t\t * the client uses its key from the certificate\n\t\t\t\t * for key exchange.\n\t\t\t\t */\n#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)\n\t\t\t\ts->state=SSL3_ST_SR_FINISHED_A;\n#else\n\t\t\t\tif (s->s3->next_proto_neg_seen)\n\t\t\t\t\ts->state=SSL3_ST_SR_NEXT_PROTO_A;\n\t\t\t\telse\n\t\t\t\t\ts->state=SSL3_ST_SR_FINISHED_A;\n#endif\n\t\t\t\ts->init_num = 0;\n\t\t\t\t}\n\t\t\telse if (SSL_USE_SIGALGS(s))\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\t\t\t\tif (!s->session->peer)\n\t\t\t\t\tbreak;\n\t\t\t\t/* For sigalgs freeze the handshake buffer\n\t\t\t\t * at this point and digest cached records.\n\t\t\t\t */\n\t\t\t\tif (!s->s3->handshake_buffer)\n\t\t\t\t\t{\n\t\t\t\t\tSSLerr(SSL_F_SSL3_ACCEPT,ERR_R_INTERNAL_ERROR);\n\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\t\t\t\ts->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;\n\t\t\t\tif (!ssl3_digest_cached_records(s))\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\telse\n\t\t\t\t{\n\t\t\t\tint offset=0;\n\t\t\t\tint dgst_num;\n\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 * FIXME - digest processing for CertificateVerify\n\t\t\t\t * should be generalized. But it is next step\n\t\t\t\t */\n\t\t\t\tif (s->s3->handshake_buffer)\n\t\t\t\t\tif (!ssl3_digest_cached_records(s))\n\t\t\t\t\t\treturn -1;\n\t\t\t\tfor (dgst_num=0; dgst_nums3->handshake_dgst[dgst_num]) \n\t\t\t\t\t\t{\n\t\t\t\t\t\tint dgst_size;\n\n\t\t\t\t\t\ts->method->ssl3_enc->cert_verify_mac(s,EVP_MD_CTX_type(s->s3->handshake_dgst[dgst_num]),&(s->s3->tmp.cert_verify_md[offset]));\n\t\t\t\t\t\tdgst_size=EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);\n\t\t\t\t\t\tif (dgst_size < 0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\tret = -1;\n\t\t\t\t\t\t\tgoto end;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\toffset+=dgst_size;\n\t\t\t\t\t\t}\t\t\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\t\t\t/*\n\t\t\t * This *should* be the first time we enable CCS, but be\n\t\t\t * extra careful about surrounding code changes. We need\n\t\t\t * to set this here because we don't know if we're\n\t\t\t * expecting a CertificateVerify or not.\n\t\t\t */\n\t\t\tif (!s->s3->change_cipher_spec)\n\t\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#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)\n\t\t\ts->state=SSL3_ST_SR_FINISHED_A;\n#else\n\t\t\tif (s->s3->next_proto_neg_seen)\n\t\t\t\ts->state=SSL3_ST_SR_NEXT_PROTO_A;\n\t\t\telse\n\t\t\t\ts->state=SSL3_ST_SR_FINISHED_A;\n#endif\n\t\t\ts->init_num=0;\n\t\t\tbreak;\n\n#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)\n\t\tcase SSL3_ST_SR_NEXT_PROTO_A:\n\t\tcase SSL3_ST_SR_NEXT_PROTO_B:\n\t\t\t/*\n\t\t\t * Enable CCS for resumed handshakes with NPN.\n\t\t\t * In a full handshake with NPN, we end up here through\n\t\t\t * SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was\n\t\t\t * already set. Receiving a CCS clears the flag, so make\n\t\t\t * sure not to re-enable it to ban duplicates.\n\t\t\t * s->s3->change_cipher_spec is set when a CCS is\n\t\t\t * processed in s3_pkt.c, and remains set until\n\t\t\t * the client's Finished message is read.\n\t\t\t */\n\t\t\tif (!s->s3->change_cipher_spec)\n\t\t\t\ts->s3->flags |= SSL3_FLAGS_CCS_OK;\n\n\t\t\tret=ssl3_get_next_proto(s);\n\t\t\tif (ret <= 0) goto end;\n\t\t\ts->init_num = 0;\n\t\t\ts->state=SSL3_ST_SR_FINISHED_A;\n\t\t\tbreak;\n#endif\n\n\t\tcase SSL3_ST_SR_FINISHED_A:\n\t\tcase SSL3_ST_SR_FINISHED_B:\n\t\t\t/*\n\t\t\t * Enable CCS for resumed handshakes without NPN.\n\t\t\t * In a full handshake, we end up here through\n\t\t\t * SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was\n\t\t\t * already set. Receiving a CCS clears the flag, so make\n\t\t\t * sure not to re-enable it to ban duplicates.\n\t\t\t * s->s3->change_cipher_spec is set when a CCS is\n\t\t\t * processed in s3_pkt.c, and remains set until\n\t\t\t * the client's Finished message is read.\n\t\t\t */\n\t\t\tif (!s->s3->change_cipher_spec)\n\t\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\t{\n#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)\n\t\t\t\ts->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;\n#else\n\t\t\t\tif (s->s3->next_proto_neg_seen)\n\t\t\t\t\t{\n\t\t\t\t\ts->s3->tmp.next_state=SSL3_ST_SR_NEXT_PROTO_A;\n\t\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\ts->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;\n#endif\n\t\t\t\t}\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->renegotiate == 2) /* skipped if we just sent a HelloRequest */\n\t\t\t\t{\n\t\t\t\ts->renegotiate=0;\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 '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness 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_verify(i2d_of_void *i2d, X509_ALGOR *a, ASN1_BIT_STRING *signature,\n\t\tchar *data, EVP_PKEY *pkey)\n\t{\n\tEVP_MD_CTX ctx;\n\tconst EVP_MD *type;\n\tunsigned char *p,*buf_in=NULL;\n\tint ret= -1,i,inl;\n\n\tEVP_MD_CTX_init(&ctx);\n\ti=OBJ_obj2nid(a->algorithm);\n\ttype=EVP_get_digestbyname(OBJ_nid2sn(i));\n\tif (type == NULL)\n\t\t{\n\t\tASN1err(ASN1_F_ASN1_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM);\n\t\tgoto err;\n\t\t}\n\t\n\tinl=i2d(data,NULL);\n\tbuf_in=OPENSSL_malloc((unsigned int)inl);\n\tif (buf_in == NULL)\n\t\t{\n\t\tASN1err(ASN1_F_ASN1_VERIFY,ERR_R_MALLOC_FAILURE);\n\t\tgoto err;\n\t\t}\n\tp=buf_in;\n\n\ti2d(data,&p);\n\tret=\n\t\tEVP_VerifyInit_ex(&ctx,type, NULL)\n\t\t&& EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl);\n\n\tOPENSSL_cleanse(buf_in,(unsigned int)inl);\n\tOPENSSL_free(buf_in);\n\n\tif (!ret)\n\t\t{\n\t\tASN1err(ASN1_F_ASN1_VERIFY,ERR_R_EVP_LIB);\n\t\tgoto err;\n\t\t}\n\tret = -1;\n\n\n\tif (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data,\n\t\t\t(unsigned int)signature->length,pkey) <= 0)\n\t\t{\n\t\tASN1err(ASN1_F_ASN1_VERIFY,ERR_R_EVP_LIB);\n\t\tret=0;\n\t\tgoto err;\n\t\t}\n\t/* we don't need to zero the 'ctx' because we just checked\n\t * public information */\n\t/* memset(&ctx,0,sizeof(ctx)); */\n\tret=1;\nerr:\n\tEVP_MD_CTX_cleanup(&ctx);\n\treturn(ret);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Fix various certificate fingerprint issues.\n\nBy using non-DER or invalid encodings outside the signed portion of a\ncertificate the fingerprint can be changed without breaking the signature.\nAlthough no details of the signed portion of the certificate can be changed\nthis can cause problems with some applications: e.g. those using the\ncertificate fingerprint for blacklists.\n\n1. Reject signatures with non zero unused bits.\n\nIf the BIT STRING containing the signature has non zero unused bits reject\nthe signature. All current signature algorithms require zero unused bits.\n\n2. Check certificate algorithm consistency.\n\nCheck the AlgorithmIdentifier inside TBS matches the one in the\ncertificate signature. NB: this will result in signature failure\nerrors for some broken certificates.\n\n3. Check DSA/ECDSA signatures use DER.\n\nReencode DSA/ECDSA signatures and compare with the original received\nsignature. Return an error if there is a mismatch.\n\nThis will reject various cases including garbage after signature\n(thanks to Antti Karjalainen and Tuomo Untinen from the Codenomicon CROSS\nprogram for discovering this case) and use of BER or invalid ASN.1 INTEGERs\n(negative or with leading zeroes).\n\nCVE-2014-8275\nReviewed-by: Emilia K\u00e4sper '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a,\n\t\tASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey)\n\t{\n\tEVP_MD_CTX ctx;\n\tunsigned char *buf_in=NULL;\n\tint ret= -1,inl;\n\n\tint mdnid, pknid;\n\n\tif (!pkey)\n\t\t{\n\t\tASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER);\n\t\treturn -1;\n\t\t}\n\n\tif (signature->type == V_ASN1_BIT_STRING && signature->flags & 0x7)\n\t\t{\n\t\tASN1err(ASN1_F_ASN1_VERIFY, ASN1_R_INVALID_BIT_STRING_BITS_LEFT);\n\t\treturn -1;\n\t\t}\n\n\tEVP_MD_CTX_init(&ctx);\n\n\t/* Convert signature OID into digest and public key OIDs */\n\tif (!OBJ_find_sigid_algs(OBJ_obj2nid(a->algorithm), &mdnid, &pknid))\n\t\t{\n\t\tASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM);\n\t\tgoto err;\n\t\t}\n\tif (mdnid == NID_undef)\n\t\t{\n\t\tif (!pkey->ameth || !pkey->ameth->item_verify)\n\t\t\t{\n\t\t\tASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM);\n\t\t\tgoto err;\n\t\t\t}\n\t\tret = pkey->ameth->item_verify(&ctx, it, asn, a,\n\t\t\t\t\t\t\tsignature, pkey);\n\t\t/* Return value of 2 means carry on, anything else means we\n\t\t * exit straight away: either a fatal error of the underlying\n\t\t * verification routine handles all verification.\n\t\t */\n\t\tif (ret != 2)\n\t\t\tgoto err;\n\t\tret = -1;\n\t\t}\n\telse\n\t\t{\n\t\tconst EVP_MD *type;\n\t\ttype=EVP_get_digestbynid(mdnid);\n\t\tif (type == NULL)\n\t\t\t{\n\t\t\tASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM);\n\t\t\tgoto err;\n\t\t\t}\n\n\t\t/* Check public key OID matches public key type */\n\t\tif (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id)\n\t\t\t{\n\t\t\tASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE);\n\t\t\tgoto err;\n\t\t\t}\n\n\t\tif (!EVP_DigestVerifyInit(&ctx, NULL, type, NULL, pkey))\n\t\t\t{\n\t\t\tASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);\n\t\t\tret=0;\n\t\t\tgoto err;\n\t\t\t}\n\n\t\t}\n\n\tinl = ASN1_item_i2d(asn, &buf_in, it);\n\t\n\tif (buf_in == NULL)\n\t\t{\n\t\tASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE);\n\t\tgoto err;\n\t\t}\n\n\tret = EVP_DigestVerifyUpdate(&ctx,buf_in,inl);\n\n\tOPENSSL_cleanse(buf_in,(unsigned int)inl);\n\tOPENSSL_free(buf_in);\n\n\tif (!ret)\n\t\t{\n\t\tASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);\n\t\tgoto err;\n\t\t}\n\tret = -1;\n\n\tif (EVP_DigestVerifyFinal(&ctx,signature->data,\n\t\t\t(size_t)signature->length) <= 0)\n\t\t{\n\t\tASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);\n\t\tret=0;\n\t\tgoto err;\n\t\t}\n\t/* we don't need to zero the 'ctx' because we just checked\n\t * public information */\n\t/* memset(&ctx,0,sizeof(ctx)); */\n\tret=1;\nerr:\n\tEVP_MD_CTX_cleanup(&ctx);\n\treturn(ret);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'use correct function name\n\nReviewed-by: Rich Salz \nReviewed-by: Matt Caswell '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void bn_mul_comba8(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b)\n\t{\n\tr[ 8]=bn_mul_words( &(r[0]),a,8,b[0]);\n\tr[ 9]=bn_mul_add_words(&(r[1]),a,8,b[1]);\n\tr[10]=bn_mul_add_words(&(r[2]),a,8,b[2]);\n\tr[11]=bn_mul_add_words(&(r[3]),a,8,b[3]);\n\tr[12]=bn_mul_add_words(&(r[4]),a,8,b[4]);\n\tr[13]=bn_mul_add_words(&(r[5]),a,8,b[5]);\n\tr[14]=bn_mul_add_words(&(r[6]),a,8,b[6]);\n\tr[15]=bn_mul_add_words(&(r[7]),a,8,b[7]);\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: void bn_mul_comba4(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b)\n\t{\n\tr[4]=bn_mul_words( &(r[0]),a,4,b[0]);\n\tr[5]=bn_mul_add_words(&(r[1]),a,4,b[1]);\n\tr[6]=bn_mul_add_words(&(r[2]),a,4,b[2]);\n\tr[7]=bn_mul_add_words(&(r[3]),a,4,b[3]);\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_get_new_session_ticket(SSL *s)\n{\n int ok, al, ret = 0, ticklen;\n long n;\n const unsigned char *p;\n unsigned char *d;\n\n n = s->method->ssl_get_message(s,\n SSL3_ST_CR_SESSION_TICKET_A,\n SSL3_ST_CR_SESSION_TICKET_B,\n SSL3_MT_NEWSESSION_TICKET, 16384, &ok);\n\n if (!ok)\n return ((int)n);\n\n if (n < 6) {\n /* need at least ticket_lifetime_hint + ticket length */\n al = SSL_AD_DECODE_ERROR;\n SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);\n goto f_err;\n }\n\n p = d = (unsigned char *)s->init_msg;\n n2l(p, s->session->tlsext_tick_lifetime_hint);\n n2s(p, ticklen);\n /* ticket_lifetime_hint + ticket_length + ticket */\n if (ticklen + 6 != n) {\n al = SSL_AD_DECODE_ERROR;\n SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);\n goto f_err;\n }\n if (s->session->tlsext_tick) {\n OPENSSL_free(s->session->tlsext_tick);\n s->session->tlsext_ticklen = 0;\n }\n s->session->tlsext_tick = OPENSSL_malloc(ticklen);\n if (!s->session->tlsext_tick) {\n SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);\n goto err;\n }\n memcpy(s->session->tlsext_tick, p, ticklen);\n s->session->tlsext_ticklen = ticklen;\n /*\n * There are two ways to detect a resumed ticket session. One is to set\n * an appropriate session ID and then the server must return a match in\n * ServerHello. This allows the normal client session ID matching to work\n * and we know much earlier that the ticket has been accepted. The\n * other way is to set zero length session ID when the ticket is\n * presented and rely on the handshake to determine session resumption.\n * We choose the former approach because this fits in with assumptions\n * elsewhere in OpenSSL. The session ID is set to the SHA256 (or SHA1 is\n * SHA256 is disabled) hash of the ticket.\n */\n EVP_Digest(p, ticklen,\n s->session->session_id, &s->session->session_id_length,\n# ifndef OPENSSL_NO_SHA256\n EVP_sha256(), NULL);\n# else\n EVP_sha1(), NULL);\n# endif\n ret = 1;\n return (ret);\n f_err:\n ssl3_send_alert(s, SSL3_AL_FATAL, al);\n err:\n s->state = SSL_ST_ERR;\n return (-1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'Fix race condition in NewSessionTicket\n\nIf a NewSessionTicket is received by a multi-threaded client when\nattempting to reuse a previous ticket then a race condition can occur\npotentially leading to a double free of the ticket data.\n\nCVE-2015-1791\n\nThis also fixes RT#3808 where a session ID is changed for a session already\nin the client session cache. Since the session ID is the key to the cache\nthis breaks the cache access.\n\nParts of this patch were inspired by this Akamai change:\nhttps://github.com/akamai/openssl/commit/c0bf69a791239ceec64509f9f19fcafb2461b0d3\n\nReviewed-by: Rich Salz \n(cherry picked from commit 27c76b9b8010b536687318739c6f631ce4194688)\n\nConflicts:\n\tssl/ssl.h\n\tssl/ssl_err.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 asn1_template_noexp_d2i(ASN1_VALUE **val,\n const unsigned char **in, long len,\n const ASN1_TEMPLATE *tt, char opt,\n ASN1_TLC *ctx)\n{\n int flags, aclass;\n int ret;\n const unsigned char *p, *q;\n if (!val)\n return 0;\n flags = tt->flags;\n aclass = flags & ASN1_TFLG_TAG_CLASS;\n\n p = *in;\n q = p;\n\n if (flags & ASN1_TFLG_SK_MASK) {\n /* SET OF, SEQUENCE OF */\n int sktag, skaclass;\n char sk_eoc;\n /* First work out expected inner tag value */\n if (flags & ASN1_TFLG_IMPTAG) {\n sktag = tt->tag;\n skaclass = aclass;\n } else {\n skaclass = V_ASN1_UNIVERSAL;\n if (flags & ASN1_TFLG_SET_OF)\n sktag = V_ASN1_SET;\n else\n sktag = V_ASN1_SEQUENCE;\n }\n /* Get the tag */\n ret = asn1_check_tlen(&len, NULL, NULL, &sk_eoc, NULL,\n &p, len, sktag, skaclass, opt, ctx);\n if (!ret) {\n ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_NESTED_ASN1_ERROR);\n return 0;\n } else if (ret == -1)\n return -1;\n if (!*val)\n *val = (ASN1_VALUE *)sk_new_null();\n else {\n /*\n * We've got a valid STACK: free up any items present\n */\n STACK *sktmp = (STACK *) * val;\n ASN1_VALUE *vtmp;\n while (sk_num(sktmp) > 0) {\n vtmp = (ASN1_VALUE *)sk_pop(sktmp);\n ASN1_item_ex_free(&vtmp, ASN1_ITEM_ptr(tt->item));\n }\n }\n\n if (!*val) {\n ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_MALLOC_FAILURE);\n goto err;\n }\n\n /* Read as many items as we can */\n while (len > 0) {\n ASN1_VALUE *skfield;\n q = p;\n /* See if EOC found */\n if (asn1_check_eoc(&p, len)) {\n if (!sk_eoc) {\n ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I,\n ASN1_R_UNEXPECTED_EOC);\n goto err;\n }\n len -= p - q;\n sk_eoc = 0;\n break;\n }\n skfield = NULL;\n if (!ASN1_item_ex_d2i(&skfield, &p, len,\n ASN1_ITEM_ptr(tt->item), -1, 0, 0, ctx)) {\n ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I,\n ERR_R_NESTED_ASN1_ERROR);\n goto err;\n }\n len -= p - q;\n if (!sk_push((STACK *) * val, (char *)skfield)) {\n ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_MALLOC_FAILURE);\n goto err;\n }\n }\n if (sk_eoc) {\n ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ASN1_R_MISSING_EOC);\n goto err;\n }\n } else if (flags & ASN1_TFLG_IMPTAG) {\n /* IMPLICIT tagging */\n ret = ASN1_item_ex_d2i(val, &p, len,\n ASN1_ITEM_ptr(tt->item), tt->tag, aclass, opt,\n ctx);\n if (!ret) {\n ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_NESTED_ASN1_ERROR);\n goto err;\n } else if (ret == -1)\n return -1;\n } else {\n /* Nothing special */\n ret = ASN1_item_ex_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item),\n -1, 0, opt, ctx);\n if (!ret) {\n ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_NESTED_ASN1_ERROR);\n goto err;\n } else if (ret == -1)\n return -1;\n }\n\n *in = p;\n return 1;\n\n err:\n ASN1_template_free(val, tt);\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Fix leak with ASN.1 combine.\n\nWhen parsing a combined structure pass a flag to the decode routine\nso on error a pointer to the parent structure is not zeroed as\nthis will leak any additional components in the parent.\n\nThis can leak memory in any application parsing PKCS#7 or CMS structures.\n\nCVE-2015-3195.\n\nThanks to Adam Langley (Google/BoringSSL) for discovering this bug using\nlibFuzzer.\n\nPR#4131\n\nReviewed-by: Richard Levitte '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int MOD_EXP_CTIME_COPY_TO_PREBUF(const BIGNUM *b, int top,\n unsigned char *buf, int idx,\n int width)\n{\n size_t i, j;\n\n if (top > b->top)\n top = b->top; /* this works because 'buf' is explicitly\n * zeroed */\n for (i = 0, j = idx; i < top * sizeof b->d[0]; i++, j += width) {\n buf[j] = ((unsigned char *)b->d)[i];\n }\n\n return 1;\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: static int rev_body(int s, int stype, unsigned char *context)\n{\n char *buf = NULL;\n int i;\n int ret = 1;\n SSL *con;\n BIO *io, *ssl_bio, *sbio;\n\n buf = app_malloc(bufsize, \"server rev buffer\");\n io = BIO_new(BIO_f_buffer());\n ssl_bio = BIO_new(BIO_f_ssl());\n if ((io == NULL) || (ssl_bio == NULL))\n goto err;\n\n /* lets make the output buffer a reasonable size */\n if (!BIO_set_write_buffer_size(io, bufsize))\n goto err;\n\n if ((con = SSL_new(ctx)) == NULL)\n goto err;\n\n if (s_tlsextdebug) {\n SSL_set_tlsext_debug_callback(con, tlsext_cb);\n SSL_set_tlsext_debug_arg(con, bio_s_out);\n }\n if (context && !SSL_set_session_id_context(con, context,\n strlen((char *)context))) {\n ERR_print_errors(bio_err);\n goto err;\n }\n\n sbio = BIO_new_socket(s, BIO_NOCLOSE);\n SSL_set_bio(con, sbio, sbio);\n SSL_set_accept_state(con);\n\n BIO_set_ssl(ssl_bio, con, BIO_CLOSE);\n BIO_push(io, ssl_bio);\n#ifdef CHARSET_EBCDIC\n io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);\n#endif\n\n if (s_debug) {\n BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);\n BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);\n }\n if (s_msg) {\n#ifndef OPENSSL_NO_SSL_TRACE\n if (s_msg == 2)\n SSL_set_msg_callback(con, SSL_trace);\n else\n#endif\n SSL_set_msg_callback(con, msg_cb);\n SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);\n }\n\n for (;;) {\n i = BIO_do_handshake(io);\n if (i > 0)\n break;\n if (!BIO_should_retry(io)) {\n BIO_puts(bio_err, \"CONNECTION FAILURE\\n\");\n ERR_print_errors(bio_err);\n goto end;\n }\n#ifndef OPENSSL_NO_SRP\n if (BIO_should_io_special(io)\n && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {\n BIO_printf(bio_s_out, \"LOOKUP renego during accept\\n\");\n srp_callback_parm.user =\n SRP_VBASE_get_by_user(srp_callback_parm.vb,\n srp_callback_parm.login);\n if (srp_callback_parm.user)\n BIO_printf(bio_s_out, \"LOOKUP done %s\\n\",\n srp_callback_parm.user->info);\n else\n BIO_printf(bio_s_out, \"LOOKUP not successful\\n\");\n continue;\n }\n#endif\n }\n BIO_printf(bio_err, \"CONNECTION ESTABLISHED\\n\");\n print_ssl_summary(con);\n\n for (;;) {\n i = BIO_gets(io, buf, bufsize - 1);\n if (i < 0) { /* error */\n if (!BIO_should_retry(io)) {\n if (!s_quiet)\n ERR_print_errors(bio_err);\n goto err;\n } else {\n BIO_printf(bio_s_out, \"read R BLOCK\\n\");\n#ifndef OPENSSL_NO_SRP\n if (BIO_should_io_special(io)\n && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {\n BIO_printf(bio_s_out, \"LOOKUP renego during read\\n\");\n srp_callback_parm.user =\n SRP_VBASE_get_by_user(srp_callback_parm.vb,\n srp_callback_parm.login);\n if (srp_callback_parm.user)\n BIO_printf(bio_s_out, \"LOOKUP done %s\\n\",\n srp_callback_parm.user->info);\n else\n BIO_printf(bio_s_out, \"LOOKUP not successful\\n\");\n continue;\n }\n#endif\n#if defined(OPENSSL_SYS_NETWARE)\n delay(1000);\n#elif !defined(OPENSSL_SYS_MSDOS)\n sleep(1);\n#endif\n continue;\n }\n } else if (i == 0) { /* end of input */\n ret = 1;\n BIO_printf(bio_err, \"CONNECTION CLOSED\\n\");\n goto end;\n } else {\n char *p = buf + i - 1;\n while (i && (*p == '\\n' || *p == '\\r')) {\n p--;\n i--;\n }\n if (!s_ign_eof && (i == 5) && (strncmp(buf, \"CLOSE\", 5) == 0)) {\n ret = 1;\n BIO_printf(bio_err, \"CONNECTION CLOSED\\n\");\n goto end;\n }\n BUF_reverse((unsigned char *)buf, NULL, i);\n buf[i] = '\\n';\n BIO_write(io, buf, i + 1);\n for (;;) {\n i = BIO_flush(io);\n if (i > 0)\n break;\n if (!BIO_should_retry(io))\n goto end;\n }\n }\n }\n end:\n /* make sure we re-use sessions */\n SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);\n\n err:\n\n OPENSSL_free(buf);\n BIO_free_all(io);\n return (ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2016-0798: avoid memory leak in SRP\n\nThe SRP user database lookup method SRP_VBASE_get_by_user had confusing\nmemory management semantics; the returned pointer was sometimes newly\nallocated, and sometimes owned by the callee. The calling code has no\nway of distinguishing these two cases.\n\nSpecifically, SRP servers that configure a secret seed to hide valid\nlogin information are vulnerable to a memory leak: an attacker\nconnecting with an invalid username can cause a memory leak of around\n300 bytes per connection.\n\nServers that do not configure SRP, or configure SRP but do not configure\na seed are not vulnerable.\n\nIn Apache, the seed directive is known as SSLSRPUnknownUserSeed.\n\nTo mitigate the memory leak, the seed handling in SRP_VBASE_get_by_user\nis now disabled even if the user has configured a seed.\n\nApplications are advised to migrate to SRP_VBASE_get1_by_user. However,\nnote that OpenSSL makes no strong guarantees about the\nindistinguishability of valid and invalid logins. In particular,\ncomputations are currently not carried out in constant time.\n\nReviewed-by: Rich Salz '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: doapr_outch(char **sbuffer,\n char **buffer, size_t *currlen, size_t *maxlen, int c)\n{\n /* If we haven't at least one buffer, someone has doe a big booboo */\n assert(*sbuffer != NULL || buffer != NULL);\n\n /* |currlen| must always be <= |*maxlen| */\n assert(*currlen <= *maxlen);\n\n if (buffer && *currlen == *maxlen) {\n *maxlen += 1024;\n if (*buffer == NULL) {\n *buffer = OPENSSL_malloc(*maxlen);\n if (!*buffer) {\n /* Panic! Can't really do anything sensible. Just return */\n return;\n }\n if (*currlen > 0) {\n assert(*sbuffer != NULL);\n memcpy(*buffer, *sbuffer, *currlen);\n }\n *sbuffer = NULL;\n } else {\n *buffer = OPENSSL_realloc(*buffer, *maxlen);\n if (!*buffer) {\n /* Panic! Can't really do anything sensible. Just return */\n return;\n }\n }\n }\n\n if (*currlen < *maxlen) {\n if (*sbuffer)\n (*sbuffer)[(*currlen)++] = (char)c;\n else\n (*buffer)[(*currlen)++] = (char)c;\n }\n\n return;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix memory issues in BIO_*printf functions\n\nThe internal |fmtstr| function used in processing a \"%s\" format string\nin the BIO_*printf functions could overflow while calculating the length\nof a string and cause an OOB read when printing very long strings.\n\nAdditionally the internal |doapr_outch| function can attempt to write to\nan OOB memory location (at an offset from the NULL pointer) in the event of\na memory allocation failure. In 1.0.2 and below this could be caused where\nthe size of a buffer to be allocated is greater than INT_MAX. E.g. this\ncould be in processing a very long \"%s\" format string. Memory leaks can also\noccur.\n\nThese issues will only occur on certain platforms where sizeof(size_t) >\nsizeof(int). E.g. many 64 bit systems. The first issue may mask the second\nissue dependent on compiler behaviour.\n\nThese problems could enable attacks where large amounts of untrusted data\nis passed to the BIO_*printf functions. If applications use these functions\nin this way then they could be vulnerable. OpenSSL itself uses these\nfunctions when printing out human-readable dumps of ASN.1 data. Therefore\napplications that print this data could be vulnerable if the data is from\nuntrusted sources. OpenSSL command line applications could also be\nvulnerable where they print out ASN.1 data, or if untrusted data is passed\nas command line arguments.\n\nLibssl is not considered directly vulnerable. Additionally certificates etc\nreceived via remote connections via libssl are also unlikely to be able to\ntrigger these issues because of message size limits enforced within libssl.\n\nCVE-2016-0799\n\nIssue reported by Guido Vranken.\n\nReviewed-by: Andy Polyakov '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int aesni_cbc_hmac_sha1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,\n const unsigned char *in, size_t len)\n{\n EVP_AES_HMAC_SHA1 *key = data(ctx);\n unsigned int l;\n size_t plen = key->payload_length, iv = 0, /* explicit IV in TLS 1.1 and\n * later */\n sha_off = 0;\n# if defined(STITCHED_CALL)\n size_t aes_off = 0, blocks;\n\n sha_off = SHA_CBLOCK - key->md.num;\n# endif\n\n key->payload_length = NO_PAYLOAD_LENGTH;\n\n if (len % AES_BLOCK_SIZE)\n return 0;\n\n if (ctx->encrypt) {\n if (plen == NO_PAYLOAD_LENGTH)\n plen = len;\n else if (len !=\n ((plen + SHA_DIGEST_LENGTH +\n AES_BLOCK_SIZE) & -AES_BLOCK_SIZE))\n return 0;\n else if (key->aux.tls_ver >= TLS1_1_VERSION)\n iv = AES_BLOCK_SIZE;\n\n# if defined(STITCHED_CALL)\n if (plen > (sha_off + iv)\n && (blocks = (plen - (sha_off + iv)) / SHA_CBLOCK)) {\n SHA1_Update(&key->md, in + iv, sha_off);\n\n aesni_cbc_sha1_enc(in, out, blocks, &key->ks,\n ctx->iv, &key->md, in + iv + sha_off);\n blocks *= SHA_CBLOCK;\n aes_off += blocks;\n sha_off += blocks;\n key->md.Nh += blocks >> 29;\n key->md.Nl += blocks <<= 3;\n if (key->md.Nl < (unsigned int)blocks)\n key->md.Nh++;\n } else {\n sha_off = 0;\n }\n# endif\n sha_off += iv;\n SHA1_Update(&key->md, in + sha_off, plen - sha_off);\n\n if (plen != len) { /* \"TLS\" mode of operation */\n if (in != out)\n memcpy(out + aes_off, in + aes_off, plen - aes_off);\n\n /* calculate HMAC and append it to payload */\n SHA1_Final(out + plen, &key->md);\n key->md = key->tail;\n SHA1_Update(&key->md, out + plen, SHA_DIGEST_LENGTH);\n SHA1_Final(out + plen, &key->md);\n\n /* pad the payload|hmac */\n plen += SHA_DIGEST_LENGTH;\n for (l = len - plen - 1; plen < len; plen++)\n out[plen] = l;\n /* encrypt HMAC|padding at once */\n aesni_cbc_encrypt(out + aes_off, out + aes_off, len - aes_off,\n &key->ks, ctx->iv, 1);\n } else {\n aesni_cbc_encrypt(in + aes_off, out + aes_off, len - aes_off,\n &key->ks, ctx->iv, 1);\n }\n } else {\n union {\n unsigned int u[SHA_DIGEST_LENGTH / sizeof(unsigned int)];\n unsigned char c[32 + SHA_DIGEST_LENGTH];\n } mac, *pmac;\n\n /* arrange cache line alignment */\n pmac = (void *)(((size_t)mac.c + 31) & ((size_t)0 - 32));\n\n 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[SHA_CBLOCK];\n } *data = (void *)key->md.data;\n# if defined(STITCHED_DECRYPT_CALL)\n unsigned char tail_iv[AES_BLOCK_SIZE];\n int stitch = 0;\n# endif\n\n if ((key->aux.tls_aad[plen - 4] << 8 | key->aux.tls_aad[plen - 3])\n >= TLS1_1_VERSION) {\n if (len < (AES_BLOCK_SIZE + SHA_DIGEST_LENGTH + 1))\n return 0;\n\n /* omit explicit iv */\n memcpy(ctx->iv, in, AES_BLOCK_SIZE);\n in += AES_BLOCK_SIZE;\n out += AES_BLOCK_SIZE;\n len -= AES_BLOCK_SIZE;\n } else if (len < (SHA_DIGEST_LENGTH + 1))\n return 0;\n\n# if defined(STITCHED_DECRYPT_CALL)\n if (len >= 1024 && ctx->key_len == 32) {\n /* decrypt last block */\n memcpy(tail_iv, in + len - 2 * AES_BLOCK_SIZE,\n AES_BLOCK_SIZE);\n aesni_cbc_encrypt(in + len - AES_BLOCK_SIZE,\n out + len - AES_BLOCK_SIZE, AES_BLOCK_SIZE,\n &key->ks, tail_iv, 0);\n stitch = 1;\n } else\n# endif\n /* decrypt HMAC|padding at once */\n aesni_cbc_encrypt(in, out, len, &key->ks, ctx->iv, 0);\n\n /* figure out payload length */\n pad = out[len - 1];\n maxpad = len - (SHA_DIGEST_LENGTH + 1);\n maxpad |= (255 - maxpad) >> (sizeof(maxpad) * 8 - 8);\n maxpad &= 255;\n\n inp_len = len - (SHA_DIGEST_LENGTH + pad + 1);\n mask = (0 - ((inp_len - len) >> (sizeof(inp_len) * 8 - 1)));\n inp_len &= mask;\n ret &= (int)mask;\n\n key->aux.tls_aad[plen - 2] = inp_len >> 8;\n key->aux.tls_aad[plen - 1] = inp_len;\n\n /* calculate HMAC */\n key->md = key->head;\n SHA1_Update(&key->md, key->aux.tls_aad, plen);\n\n# if defined(STITCHED_DECRYPT_CALL)\n if (stitch) {\n blocks = (len - (256 + 32 + SHA_CBLOCK)) / SHA_CBLOCK;\n aes_off = len - AES_BLOCK_SIZE - blocks * SHA_CBLOCK;\n sha_off = SHA_CBLOCK - plen;\n\n aesni_cbc_encrypt(in, out, aes_off, &key->ks, ctx->iv, 0);\n\n SHA1_Update(&key->md, out, sha_off);\n aesni256_cbc_sha1_dec(in + aes_off,\n out + aes_off, blocks, &key->ks,\n ctx->iv, &key->md, out + sha_off);\n\n sha_off += blocks *= SHA_CBLOCK;\n out += sha_off;\n len -= sha_off;\n inp_len -= sha_off;\n\n key->md.Nl += (blocks << 3); /* at most 18 bits */\n memcpy(ctx->iv, tail_iv, AES_BLOCK_SIZE);\n }\n# endif\n\n# if 1\n len -= SHA_DIGEST_LENGTH; /* amend mac */\n if (len >= (256 + SHA_CBLOCK)) {\n j = (len - (256 + SHA_CBLOCK)) & (0 - SHA_CBLOCK);\n j += SHA_CBLOCK - key->md.num;\n SHA1_Update(&key->md, out, j);\n out += j;\n len -= j;\n inp_len -= j;\n }\n\n /* but pretend as if we hashed padded payload */\n bitlen = key->md.Nl + (inp_len << 3); /* at most 18 bits */\n# ifdef 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\n for (res = key->md.num, j = 0; j < len; j++) {\n size_t c = out[j];\n mask = (j - inp_len) >> (sizeof(j) * 8 - 8);\n c &= mask;\n c |= 0x80 & ~mask & ~((inp_len - j) >> (sizeof(j) * 8 - 8));\n data->c[res++] = (unsigned char)c;\n\n if (res != SHA_CBLOCK)\n continue;\n\n /* j is not incremented yet */\n mask = 0 - ((inp_len + 7 - j) >> (sizeof(j) * 8 - 1));\n data->u[SHA_LBLOCK - 1] |= bitlen & mask;\n sha1_block_data_order(&key->md, data, 1);\n mask &= 0 - ((j - inp_len - 72) >> (sizeof(j) * 8 - 1));\n pmac->u[0] |= key->md.h0 & mask;\n pmac->u[1] |= key->md.h1 & mask;\n pmac->u[2] |= key->md.h2 & mask;\n pmac->u[3] |= key->md.h3 & mask;\n pmac->u[4] |= key->md.h4 & mask;\n res = 0;\n }\n\n for (i = res; i < SHA_CBLOCK; i++, j++)\n data->c[i] = 0;\n\n if (res > SHA_CBLOCK - 8) {\n mask = 0 - ((inp_len + 8 - j) >> (sizeof(j) * 8 - 1));\n data->u[SHA_LBLOCK - 1] |= bitlen & mask;\n sha1_block_data_order(&key->md, data, 1);\n mask &= 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1));\n pmac->u[0] |= key->md.h0 & mask;\n pmac->u[1] |= key->md.h1 & mask;\n pmac->u[2] |= key->md.h2 & mask;\n pmac->u[3] |= key->md.h3 & mask;\n pmac->u[4] |= key->md.h4 & mask;\n\n memset(data, 0, SHA_CBLOCK);\n j += 64;\n }\n data->u[SHA_LBLOCK - 1] = bitlen;\n sha1_block_data_order(&key->md, data, 1);\n mask = 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1));\n pmac->u[0] |= key->md.h0 & mask;\n pmac->u[1] |= key->md.h1 & mask;\n pmac->u[2] |= key->md.h2 & mask;\n pmac->u[3] |= key->md.h3 & mask;\n pmac->u[4] |= key->md.h4 & mask;\n\n# ifdef 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# else\n for (i = 0; i < 5; i++) {\n res = pmac->u[i];\n pmac->c[4 * i + 0] = (unsigned char)(res >> 24);\n pmac->c[4 * i + 1] = (unsigned char)(res >> 16);\n pmac->c[4 * i + 2] = (unsigned char)(res >> 8);\n pmac->c[4 * i + 3] = (unsigned char)res;\n }\n# endif\n len += SHA_DIGEST_LENGTH;\n# else\n SHA1_Update(&key->md, out, inp_len);\n res = key->md.num;\n SHA1_Final(pmac->c, &key->md);\n\n {\n unsigned int inp_blocks, pad_blocks;\n\n /* but pretend as if we hashed padded payload */\n inp_blocks =\n 1 + ((SHA_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1));\n res += (unsigned int)(len - inp_len);\n pad_blocks = res / SHA_CBLOCK;\n res %= SHA_CBLOCK;\n pad_blocks +=\n 1 + ((SHA_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1));\n for (; inp_blocks < pad_blocks; inp_blocks++)\n sha1_block_data_order(&key->md, data, 1);\n }\n# endif\n key->md = key->tail;\n SHA1_Update(&key->md, pmac->c, SHA_DIGEST_LENGTH);\n SHA1_Final(pmac->c, &key->md);\n\n /* verify HMAC */\n out += inp_len;\n len -= inp_len;\n# if 1\n {\n unsigned char *p = out + len - 1 - maxpad - SHA_DIGEST_LENGTH;\n size_t off = out - p;\n unsigned int c, cmask;\n\n maxpad += SHA_DIGEST_LENGTH;\n for (res = 0, i = 0, j = 0; j < maxpad; j++) {\n c = p[j];\n cmask =\n ((int)(j - off - SHA_DIGEST_LENGTH)) >> (sizeof(int) *\n 8 - 1);\n res |= (c ^ pad) & ~cmask; /* ... and padding */\n cmask &= ((int)(off - 1 - j)) >> (sizeof(int) * 8 - 1);\n res |= (c ^ pmac->c[i]) & cmask;\n i += 1 & cmask;\n }\n maxpad -= SHA_DIGEST_LENGTH;\n\n res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1));\n ret &= (int)~res;\n }\n# else\n for (res = 0, i = 0; i < SHA_DIGEST_LENGTH; i++)\n res |= out[i] ^ pmac->c[i];\n res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1));\n ret &= (int)~res;\n\n /* verify padding */\n pad = (pad & ~res) | (maxpad & res);\n out = out + len - 1 - pad;\n for (res = 0, i = 0; i < pad; i++)\n res |= out[i] ^ pad;\n\n res = (0 - res) >> (sizeof(res) * 8 - 1);\n ret &= (int)~res;\n# endif\n return ret;\n } else {\n# if defined(STITCHED_DECRYPT_CALL)\n if (len >= 1024 && ctx->key_len == 32) {\n if (sha_off %= SHA_CBLOCK)\n blocks = (len - 3 * SHA_CBLOCK) / SHA_CBLOCK;\n else\n blocks = (len - 2 * SHA_CBLOCK) / SHA_CBLOCK;\n aes_off = len - blocks * SHA_CBLOCK;\n\n aesni_cbc_encrypt(in, out, aes_off, &key->ks, ctx->iv, 0);\n SHA1_Update(&key->md, out, sha_off);\n aesni256_cbc_sha1_dec(in + aes_off,\n out + aes_off, blocks, &key->ks,\n ctx->iv, &key->md, out + sha_off);\n\n sha_off += blocks *= SHA_CBLOCK;\n out += sha_off;\n len -= sha_off;\n\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# endif\n /* decrypt HMAC|padding at once */\n aesni_cbc_encrypt(in, out, len, &key->ks, ctx->iv, 0);\n\n SHA1_Update(&key->md, out, len);\n }\n }\n\n return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Check that we have enough padding characters.\n\nReviewed-by: Emilia K\u00e4sper \n\nCVE-2016-2107\n\nMR: #2572'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: rsvg_mask_parse (const RsvgDefs * defs, const char *str)\n{\n char *name;\n\n name = rsvg_get_url_string (str);\n if (name) {\n RsvgNode *val;\n val = rsvg_defs_lookup (defs, name);\n g_free (name);\n\n if (val && RSVG_NODE_TYPE (val) == RSVG_NODE_TYPE_MASK)\n return val;\n }\n return NULL;\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: CAMLprim value caml_blit_string(value s1, value ofs1, value s2, value ofs2,\n value n)\n{\n memmove(&Byte(s2, Long_val(ofs2)), &Byte(s1, Long_val(ofs1)), Int_val(n));\n return Val_unit;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'fix PR#7003 and a few other bugs caused by misuse of Int_val\n\ngit-svn-id: http://caml.inria.fr/svn/ocaml/trunk@16525 f963ae5c-01c2-4b8c-9fe0-0dff7051ff02'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ssl_get_prev_session(SSL *s, unsigned char *session_id, int len,\n const unsigned char *limit)\n{\n /* This is used only by servers. */\n\n SSL_SESSION *ret = NULL;\n int fatal = 0;\n int try_session_cache = 1;\n#ifndef OPENSSL_NO_TLSEXT\n int r;\n#endif\n\n if (session_id + len > limit) {\n fatal = 1;\n goto err;\n }\n\n if (len == 0)\n try_session_cache = 0;\n\n#ifndef OPENSSL_NO_TLSEXT\n /* sets s->tlsext_ticket_expected */\n r = tls1_process_ticket(s, session_id, len, limit, &ret);\n switch (r) {\n case -1: /* Error during processing */\n fatal = 1;\n goto err;\n case 0: /* No ticket found */\n case 1: /* Zero length ticket found */\n break; /* Ok to carry on processing session id. */\n case 2: /* Ticket found but not decrypted. */\n case 3: /* Ticket decrypted, *ret has been set. */\n try_session_cache = 0;\n break;\n default:\n abort();\n }\n#endif\n\n if (try_session_cache &&\n ret == NULL &&\n !(s->session_ctx->session_cache_mode &\n SSL_SESS_CACHE_NO_INTERNAL_LOOKUP)) {\n SSL_SESSION data;\n data.ssl_version = s->version;\n data.session_id_length = len;\n if (len == 0)\n return 0;\n memcpy(data.session_id, session_id, len);\n CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);\n ret = lh_SSL_SESSION_retrieve(s->session_ctx->sessions, &data);\n if (ret != NULL) {\n /* don't allow other threads to steal it: */\n CRYPTO_add(&ret->references, 1, CRYPTO_LOCK_SSL_SESSION);\n }\n CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);\n if (ret == NULL)\n s->session_ctx->stats.sess_miss++;\n }\n\n if (try_session_cache &&\n ret == NULL && s->session_ctx->get_session_cb != NULL) {\n int copy = 1;\n\n if ((ret = s->session_ctx->get_session_cb(s, session_id, len, ©))) {\n s->session_ctx->stats.sess_cb_hit++;\n\n /*\n * Increment reference count now if the session callback asks us\n * to do so (note that if the session structures returned by the\n * callback are shared between threads, it must handle the\n * reference count itself [i.e. copy == 0], or things won't be\n * thread-safe).\n */\n if (copy)\n CRYPTO_add(&ret->references, 1, CRYPTO_LOCK_SSL_SESSION);\n\n /*\n * Add the externally cached session to the internal cache as\n * well if and only if we are supposed to.\n */\n if (!\n (s->session_ctx->session_cache_mode &\n SSL_SESS_CACHE_NO_INTERNAL_STORE))\n /*\n * The following should not return 1, otherwise, things are\n * very strange\n */\n SSL_CTX_add_session(s->session_ctx, ret);\n }\n }\n\n if (ret == NULL)\n goto err;\n\n /* Now ret is non-NULL and we own one of its reference counts. */\n\n if (ret->sid_ctx_length != s->sid_ctx_length\n || memcmp(ret->sid_ctx, s->sid_ctx, ret->sid_ctx_length)) {\n /*\n * We have the session requested by the client, but we don't want to\n * use it in this context.\n */\n goto err; /* treat like cache miss */\n }\n\n if ((s->verify_mode & SSL_VERIFY_PEER) && s->sid_ctx_length == 0) {\n /*\n * We can't be sure if this session is being used out of context,\n * which is especially important for SSL_VERIFY_PEER. The application\n * should have used SSL[_CTX]_set_session_id_context. For this error\n * case, we generate an error instead of treating the event like a\n * cache miss (otherwise it would be easy for applications to\n * effectively disable the session cache by accident without anyone\n * noticing).\n */\n\n SSLerr(SSL_F_SSL_GET_PREV_SESSION,\n SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED);\n fatal = 1;\n goto err;\n }\n\n if (ret->cipher == NULL) {\n unsigned char buf[5], *p;\n unsigned long l;\n\n p = buf;\n l = ret->cipher_id;\n l2n(l, p);\n if ((ret->ssl_version >> 8) >= SSL3_VERSION_MAJOR)\n ret->cipher = ssl_get_cipher_by_char(s, &(buf[2]));\n else\n ret->cipher = ssl_get_cipher_by_char(s, &(buf[1]));\n if (ret->cipher == NULL)\n goto err;\n }\n\n if (ret->timeout < (long)(time(NULL) - ret->time)) { /* timeout */\n s->session_ctx->stats.sess_timeout++;\n if (try_session_cache) {\n /* session was from the cache, so remove it */\n SSL_CTX_remove_session(s->session_ctx, ret);\n }\n goto err;\n }\n\n s->session_ctx->stats.sess_hit++;\n\n if (s->session != NULL)\n SSL_SESSION_free(s->session);\n s->session = ret;\n s->verify_result = s->session->verify_result;\n return 1;\n\n err:\n if (ret != NULL) {\n SSL_SESSION_free(ret);\n#ifndef OPENSSL_NO_TLSEXT\n if (!try_session_cache) {\n /*\n * The session was from a ticket, so we should issue a ticket for\n * the new session\n */\n s->tlsext_ticket_expected = 1;\n }\n#endif\n }\n if (fatal)\n return -1;\n else\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: TIFFReadRawTile1(TIFF* tif, uint32 tile, void* buf, tmsize_t size, const char* module)\n{\n\tTIFFDirectory *td = &tif->tif_dir;\n\n if (!_TIFFFillStriles( tif ))\n return ((tmsize_t)(-1));\n\n\tassert((tif->tif_flags&TIFF_NOREADRAW)==0);\n\tif (!isMapped(tif)) {\n\t\ttmsize_t cc;\n\n\t\tif (!SeekOK(tif, td->td_stripoffset[tile])) {\n\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t \"Seek error at row %lu, col %lu, tile %lu\",\n\t\t\t (unsigned long) tif->tif_row,\n\t\t\t (unsigned long) tif->tif_col,\n\t\t\t (unsigned long) tile);\n\t\t\treturn ((tmsize_t)(-1));\n\t\t}\n\t\tcc = TIFFReadFile(tif, buf, size);\n\t\tif (cc != size) {\n#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))\n\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\"Read error at row %lu, col %lu; got %I64u bytes, expected %I64u\",\n\t\t\t\t (unsigned long) tif->tif_row,\n\t\t\t\t (unsigned long) tif->tif_col,\n\t\t\t\t (unsigned __int64) cc,\n\t\t\t\t (unsigned __int64) size);\n#else\n\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\"Read error at row %lu, col %lu; got %llu bytes, expected %llu\",\n\t\t\t\t (unsigned long) tif->tif_row,\n\t\t\t\t (unsigned long) tif->tif_col,\n\t\t\t\t (unsigned long long) cc,\n\t\t\t\t (unsigned long long) size);\n#endif\n\t\t\treturn ((tmsize_t)(-1));\n\t\t}\n\t} else {\n\t\ttmsize_t ma,mb;\n\t\ttmsize_t n;\n\t\tma=(tmsize_t)td->td_stripoffset[tile];\n\t\tmb=ma+size;\n\t\tif (((uint64)ma!=td->td_stripoffset[tile])||(ma>tif->tif_size))\n\t\t\tn=0;\n\t\telse if ((mbtif->tif_size))\n\t\t\tn=tif->tif_size-ma;\n\t\telse\n\t\t\tn=size;\n\t\tif (n!=size) {\n#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))\n\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\"Read error at row %lu, col %lu, tile %lu; got %I64u bytes, expected %I64u\",\n\t\t\t\t (unsigned long) tif->tif_row,\n\t\t\t\t (unsigned long) tif->tif_col,\n\t\t\t\t (unsigned long) tile,\n\t\t\t\t (unsigned __int64) n,\n\t\t\t\t (unsigned __int64) size);\n#else\n\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\"Read error at row %lu, col %lu, tile %lu; got %llu bytes, expected %llu\",\n\t\t\t\t (unsigned long) tif->tif_row,\n\t\t\t\t (unsigned long) tif->tif_col,\n\t\t\t\t (unsigned long) tile,\n\t\t\t\t (unsigned long long) n,\n\t\t\t\t (unsigned long long) size);\n#endif\n\t\t\treturn ((tmsize_t)(-1));\n\t\t}\n\t\t_TIFFmemcpy(buf, tif->tif_base + ma, size);\n\t}\n\treturn (size);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': '* libtiff/tif_read.c: Fix out-of-bounds read on\nmemory-mapped files in TIFFReadRawStrip1() and TIFFReadRawTile1()\nwhen stripoffset is beyond tmsize_t max value (reported by\nMathias Svensson)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void dtls1_clear_record_buffer(SSL *s)\n{\n pitem *item;\n\n for (item = pqueue_pop(s->d1->sent_messages);\n item != NULL; item = pqueue_pop(s->d1->sent_messages)) {\n dtls1_hm_fragment_free((hm_fragment *)item->data);\n pitem_free(item);\n }\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_server_certificate(SSL *s)\n{\n int al, i, ok, ret = -1;\n unsigned long n, nc, llen, l;\n X509 *x = NULL;\n const unsigned char *q, *p;\n unsigned char *d;\n STACK_OF(X509) *sk = NULL;\n SESS_CERT *sc;\n EVP_PKEY *pkey = NULL;\n int need_cert = 1; /* VRS: 0=> will allow null cert if auth ==\n * KRB5 */\n\n n = s->method->ssl_get_message(s,\n SSL3_ST_CR_CERT_A,\n SSL3_ST_CR_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_SERVER_KEY_EXCHANGE) ||\n ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) &&\n (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE))) {\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_SERVER_CERTIFICATE, SSL_R_BAD_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_SERVER_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_SERVER_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_SERVER_CERTIFICATE,\n SSL_R_CERT_LENGTH_MISMATCH);\n goto f_err;\n }\n\n q = p;\n x = d2i_X509(NULL, &q, l);\n if (x == NULL) {\n al = SSL_AD_BAD_CERTIFICATE;\n SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, ERR_R_ASN1_LIB);\n goto f_err;\n }\n if (q != (p + l)) {\n al = SSL_AD_DECODE_ERROR;\n SSLerr(SSL_F_SSL3_GET_SERVER_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_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);\n goto err;\n }\n x = NULL;\n nc += l + 3;\n p = q;\n }\n\n i = ssl_verify_cert_chain(s, sk);\n if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0)\n#ifndef OPENSSL_NO_KRB5\n && !((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) &&\n (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))\n#endif /* OPENSSL_NO_KRB5 */\n ) {\n al = ssl_verify_alarm_type(s->verify_result);\n SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,\n SSL_R_CERTIFICATE_VERIFY_FAILED);\n goto f_err;\n }\n ERR_clear_error(); /* but we keep s->verify_result */\n\n sc = ssl_sess_cert_new();\n if (sc == NULL)\n goto err;\n\n if (s->session->sess_cert)\n ssl_sess_cert_free(s->session->sess_cert);\n s->session->sess_cert = sc;\n\n sc->cert_chain = sk;\n /*\n * Inconsistency alert: cert_chain does include the peer's certificate,\n * which we don't include in s3_srvr.c\n */\n x = sk_X509_value(sk, 0);\n sk = NULL;\n /*\n * VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end\n */\n\n pkey = X509_get_pubkey(x);\n\n /* VRS: allow null cert if auth == KRB5 */\n need_cert = ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) &&\n (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))\n ? 0 : 1;\n\n#ifdef KSSL_DEBUG\n fprintf(stderr, \"pkey,x = %p, %p\\n\", pkey, x);\n fprintf(stderr, \"ssl_cert_type(x,pkey) = %d\\n\", ssl_cert_type(x, pkey));\n fprintf(stderr, \"cipher, alg, nc = %s, %lx, %lx, %d\\n\",\n s->s3->tmp.new_cipher->name,\n s->s3->tmp.new_cipher->algorithm_mkey,\n s->s3->tmp.new_cipher->algorithm_auth, need_cert);\n#endif /* KSSL_DEBUG */\n\n if (need_cert && ((pkey == NULL) || EVP_PKEY_missing_parameters(pkey))) {\n x = NULL;\n al = SSL3_AL_FATAL;\n SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,\n SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);\n goto f_err;\n }\n\n i = ssl_cert_type(x, pkey);\n if (need_cert && i < 0) {\n x = NULL;\n al = SSL3_AL_FATAL;\n SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,\n SSL_R_UNKNOWN_CERTIFICATE_TYPE);\n goto f_err;\n }\n\n if (need_cert) {\n sc->peer_cert_type = i;\n CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);\n /*\n * Why would the following ever happen? We just created sc a couple\n * of lines ago.\n */\n if (sc->peer_pkeys[i].x509 != NULL)\n X509_free(sc->peer_pkeys[i].x509);\n sc->peer_pkeys[i].x509 = x;\n sc->peer_key = &(sc->peer_pkeys[i]);\n\n if (s->session->peer != NULL)\n X509_free(s->session->peer);\n CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);\n s->session->peer = x;\n } else {\n sc->peer_cert_type = i;\n sc->peer_key = NULL;\n\n if (s->session->peer != NULL)\n X509_free(s->session->peer);\n s->session->peer = NULL;\n }\n s->session->verify_result = s->verify_result;\n\n x = NULL;\n ret = 1;\n\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 EVP_PKEY_free(pkey);\n X509_free(x);\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: static int init_common_variables()\n{\n umask(((~my_umask) & 0666));\n my_decimal_set_zero(&decimal_zero); // set decimal_zero constant;\n\n tzset();\t\t\t// Set tzname\n\n sf_leaking_memory= 0; // no memory leaks from now on\n\n max_system_variables.pseudo_thread_id= (ulong)~0;\n server_start_time= flush_status_time= my_time(0);\n\n rpl_filter= new Rpl_filter;\n binlog_filter= new Rpl_filter;\n if (!rpl_filter || !binlog_filter)\n {\n sql_perror(\"Could not allocate replication and binlog filters\");\n return 1;\n }\n\n if (init_thread_environment() ||\n mysql_init_variables())\n return 1;\n\n if (ignore_db_dirs_init())\n return 1;\n\n#ifdef HAVE_TZNAME\n struct tm tm_tmp;\n localtime_r(&server_start_time,&tm_tmp);\n const char *tz_name= tzname[tm_tmp.tm_isdst != 0 ? 1 : 0];\n#ifdef _WIN32\n /*\n Time zone name may be localized and contain non-ASCII characters,\n Convert from ANSI encoding to UTF8.\n */\n wchar_t wtz_name[sizeof(system_time_zone)];\n mbstowcs(wtz_name, tz_name, sizeof(system_time_zone)-1);\n WideCharToMultiByte(CP_UTF8,0, wtz_name, -1, system_time_zone, \n sizeof(system_time_zone) - 1, NULL, NULL);\n#else\n strmake_buf(system_time_zone, tz_name);\n#endif /* _WIN32 */\n#endif /* HAVE_TZNAME */\n\n /*\n We set SYSTEM time zone as reasonable default and\n also for failure of my_tz_init() and bootstrap mode.\n If user explicitly set time zone with --default-time-zone\n option we will change this value in my_tz_init().\n */\n global_system_variables.time_zone= my_tz_SYSTEM;\n\n#ifdef HAVE_PSI_INTERFACE\n /*\n Complete the mysql_bin_log initialization.\n Instrumentation keys are known only after the performance schema initialization,\n and can not be set in the MYSQL_BIN_LOG constructor (called before main()).\n */\n mysql_bin_log.set_psi_keys(key_BINLOG_LOCK_index,\n key_BINLOG_update_cond,\n key_file_binlog,\n key_file_binlog_index,\n key_BINLOG_COND_queue_busy);\n#endif\n\n /*\n Init mutexes for the global MYSQL_BIN_LOG objects.\n As safe_mutex depends on what MY_INIT() does, we can't init the mutexes of\n global MYSQL_BIN_LOGs in their constructors, because then they would be\n inited before MY_INIT(). So we do it here.\n */\n mysql_bin_log.init_pthread_objects();\n\n /* TODO: remove this when my_time_t is 64 bit compatible */\n if (!IS_TIME_T_VALID_FOR_TIMESTAMP(server_start_time))\n {\n sql_print_error(\"This MySQL server doesn't support dates later then 2038\");\n return 1;\n }\n\n if (gethostname(glob_hostname,sizeof(glob_hostname)) < 0)\n {\n /*\n Get hostname of computer (used by 'show variables') and as default\n basename for the pid file if --log-basename is not given.\n */\n strmake(glob_hostname, STRING_WITH_LEN(\"localhost\"));\n sql_print_warning(\"gethostname failed, using '%s' as hostname\",\n glob_hostname);\n opt_log_basename= const_cast(\"mysql\");\n }\n else\n opt_log_basename= glob_hostname;\n\n if (!*pidfile_name)\n {\n strmake(pidfile_name, opt_log_basename, sizeof(pidfile_name)-5);\n strmov(fn_ext(pidfile_name),\".pid\");\t\t// Add proper extension\n }\n\n /*\n The default-storage-engine entry in my_long_options should have a\n non-null default value. It was earlier intialized as\n (longlong)\"MyISAM\" in my_long_options but this triggered a\n compiler error in the Sun Studio 12 compiler. As a work-around we\n set the def_value member to 0 in my_long_options and initialize it\n to the correct value here.\n\n From MySQL 5.5 onwards, the default storage engine is InnoDB\n (except in the embedded server, where the default continues to\n be MyISAM)\n */\n#if defined(WITH_INNOBASE_STORAGE_ENGINE) || defined(WITH_XTRADB_STORAGE_ENGINE)\n default_storage_engine= const_cast(\"InnoDB\");\n#else\n default_storage_engine= const_cast(\"MyISAM\");\n#endif\n\n /*\n Add server status variables to the dynamic list of\n status variables that is shown by SHOW STATUS.\n Later, in plugin_init, and mysql_install_plugin\n new entries could be added to that list.\n */\n if (add_status_vars(status_vars))\n return 1; // an error was already reported\n\n#ifndef DBUG_OFF\n /*\n We have few debug-only commands in com_status_vars, only visible in debug\n builds. for simplicity we enable the assert only in debug builds\n\n There are 8 Com_ variables which don't have corresponding SQLCOM_ values:\n (TODO strictly speaking they shouldn't be here, should not have Com_ prefix\n that is. Perhaps Stmt_ ? Comstmt_ ? Prepstmt_ ?)\n\n Com_admin_commands => com_other\n Com_stmt_close => com_stmt_close\n Com_stmt_execute => com_stmt_execute\n Com_stmt_fetch => com_stmt_fetch\n Com_stmt_prepare => com_stmt_prepare\n Com_stmt_reprepare => com_stmt_reprepare\n Com_stmt_reset => com_stmt_reset\n Com_stmt_send_long_data => com_stmt_send_long_data\n\n With this correction the number of Com_ variables (number of elements in\n the array, excluding the last element - terminator) must match the number\n of SQLCOM_ constants.\n */\n compile_time_assert(sizeof(com_status_vars)/sizeof(com_status_vars[0]) - 1 ==\n SQLCOM_END + 8);\n#endif\n\n if (get_options(&remaining_argc, &remaining_argv))\n return 1;\n set_server_version();\n\n if (!opt_help)\n sql_print_information(\"%s (mysqld %s) starting as process %lu ...\",\n my_progname, server_version, (ulong) getpid());\n\n#ifndef EMBEDDED_LIBRARY\n if (opt_abort && !opt_verbose)\n unireg_abort(0);\n#endif /*!EMBEDDED_LIBRARY*/\n\n DBUG_PRINT(\"info\",(\"%s Ver %s for %s on %s\\n\",my_progname,\n\t\t server_version, SYSTEM_TYPE,MACHINE_TYPE));\n\n#ifdef HAVE_LARGE_PAGES\n /* Initialize large page size */\n if (opt_large_pages && (opt_large_page_size= my_get_large_page_size()))\n {\n DBUG_PRINT(\"info\", (\"Large page set, large_page_size = %d\",\n opt_large_page_size));\n my_use_large_pages= 1;\n my_large_page_size= opt_large_page_size;\n }\n else\n {\n opt_large_pages= 0;\n /* \n Either not configured to use large pages or Linux haven't\n been compiled with large page support\n */\n }\n#endif /* HAVE_LARGE_PAGES */\n#ifdef HAVE_SOLARIS_LARGE_PAGES\n#define LARGE_PAGESIZE (4*1024*1024) /* 4MB */\n#define SUPER_LARGE_PAGESIZE (256*1024*1024) /* 256MB */\n if (opt_large_pages)\n {\n /*\n tell the kernel that we want to use 4/256MB page for heap storage\n and also for the stack. We use 4 MByte as default and if the\n super-large-page is set we increase it to 256 MByte. 256 MByte\n is for server installations with GBytes of RAM memory where\n the MySQL Server will have page caches and other memory regions\n measured in a number of GBytes.\n We use as big pages as possible which isn't bigger than the above\n desired page sizes.\n */\n int nelem;\n size_t max_desired_page_size;\n if (opt_super_large_pages)\n max_desired_page_size= SUPER_LARGE_PAGESIZE;\n else\n max_desired_page_size= LARGE_PAGESIZE;\n nelem = getpagesizes(NULL, 0);\n if (nelem > 0)\n {\n size_t *pagesize = (size_t *) malloc(sizeof(size_t) * nelem);\n if (pagesize != NULL && getpagesizes(pagesize, nelem) > 0)\n {\n size_t max_page_size= 0;\n for (int i= 0; i < nelem; i++)\n {\n if (pagesize[i] > max_page_size &&\n pagesize[i] <= max_desired_page_size)\n max_page_size= pagesize[i];\n }\n free(pagesize);\n if (max_page_size > 0)\n {\n struct memcntl_mha mpss;\n\n mpss.mha_cmd= MHA_MAPSIZE_BSSBRK;\n mpss.mha_pagesize= max_page_size;\n mpss.mha_flags= 0;\n memcntl(NULL, 0, MC_HAT_ADVISE, (caddr_t)&mpss, 0, 0);\n mpss.mha_cmd= MHA_MAPSIZE_STACK;\n memcntl(NULL, 0, MC_HAT_ADVISE, (caddr_t)&mpss, 0, 0);\n }\n }\n }\n }\n#endif /* HAVE_SOLARIS_LARGE_PAGES */\n\n /* connections and databases needs lots of files */\n {\n uint files, wanted_files, max_open_files;\n\n /* MyISAM requires two file handles per table. */\n wanted_files= (10 + max_connections + extra_max_connections +\n table_cache_size*2);\n /*\n We are trying to allocate no less than max_connections*5 file\n handles (i.e. we are trying to set the limit so that they will\n be available). In addition, we allocate no less than how much\n was already allocated. However below we report a warning and\n recompute values only if we got less file handles than were\n explicitly requested. No warning and re-computation occur if we\n can't get max_connections*5 but still got no less than was\n requested (value of wanted_files).\n */\n max_open_files= max(max(wanted_files,\n (max_connections + extra_max_connections)*5),\n open_files_limit);\n files= my_set_max_open_files(max_open_files);\n\n if (files < wanted_files)\n {\n if (!open_files_limit)\n {\n /*\n If we have requested too much file handles than we bring\n max_connections in supported bounds.\n */\n max_connections= (ulong) min(files-10-TABLE_OPEN_CACHE_MIN*2,\n max_connections);\n /*\n Decrease table_cache_size according to max_connections, but\n not below TABLE_OPEN_CACHE_MIN. Outer min() ensures that we\n never increase table_cache_size automatically (that could\n happen if max_connections is decreased above).\n */\n table_cache_size= (ulong) min(max((files-10-max_connections)/2,\n TABLE_OPEN_CACHE_MIN),\n table_cache_size);\n\tDBUG_PRINT(\"warning\",\n\t\t (\"Changed limits: max_open_files: %u max_connections: %ld table_cache: %ld\",\n\t\t files, max_connections, table_cache_size));\n\tif (global_system_variables.log_warnings)\n\t sql_print_warning(\"Changed limits: max_open_files: %u max_connections: %ld table_cache: %ld\",\n\t\t\tfiles, max_connections, table_cache_size);\n }\n else if (global_system_variables.log_warnings)\n\tsql_print_warning(\"Could not increase number of max_open_files to more than %u (request: %u)\", files, wanted_files);\n }\n open_files_limit= files;\n }\n unireg_init(opt_specialflag); /* Set up extern variabels */\n if (!(my_default_lc_messages=\n my_locale_by_name(lc_messages)))\n {\n sql_print_error(\"Unknown locale: '%s'\", lc_messages);\n return 1;\n }\n global_system_variables.lc_messages= my_default_lc_messages;\n if (init_errmessage())\t/* Read error messages from file */\n return 1;\n init_client_errs();\n mysql_library_init(unused,unused,unused); /* for replication */\n lex_init();\n if (item_create_init())\n return 1;\n item_init();\n#ifndef EMBEDDED_LIBRARY\n my_regex_init(&my_charset_latin1, check_enough_stack_size);\n my_string_stack_guard= check_enough_stack_size;\n#else\n my_regex_init(&my_charset_latin1, NULL);\n#endif\n /*\n Process a comma-separated character set list and choose\n the first available character set. This is mostly for\n test purposes, to be able to start \"mysqld\" even if\n the requested character set is not available (see bug#18743).\n */\n for (;;)\n {\n char *next_character_set_name= strchr(default_character_set_name, ',');\n if (next_character_set_name)\n *next_character_set_name++= '\\0';\n if (!(default_charset_info=\n get_charset_by_csname(default_character_set_name,\n MY_CS_PRIMARY, MYF(MY_WME))))\n {\n if (next_character_set_name)\n {\n default_character_set_name= next_character_set_name;\n default_collation_name= 0; // Ignore collation\n }\n else\n return 1; // Eof of the list\n }\n else\n break;\n }\n\n if (default_collation_name)\n {\n CHARSET_INFO *default_collation;\n default_collation= get_charset_by_name(default_collation_name, MYF(0));\n if (!default_collation)\n {\n sql_print_error(ER_DEFAULT(ER_UNKNOWN_COLLATION), default_collation_name);\n return 1;\n }\n if (!my_charset_same(default_charset_info, default_collation))\n {\n sql_print_error(ER_DEFAULT(ER_COLLATION_CHARSET_MISMATCH),\n\t\t default_collation_name,\n\t\t default_charset_info->csname);\n return 1;\n }\n default_charset_info= default_collation;\n }\n /* Set collactions that depends on the default collation */\n global_system_variables.collation_server=\t default_charset_info;\n global_system_variables.collation_database=\t default_charset_info;\n global_system_variables.collation_connection= default_charset_info;\n global_system_variables.character_set_results= default_charset_info;\n global_system_variables.character_set_client= default_charset_info;\n\n if (!(character_set_filesystem=\n get_charset_by_csname(character_set_filesystem_name,\n MY_CS_PRIMARY, MYF(MY_WME))))\n return 1;\n global_system_variables.character_set_filesystem= character_set_filesystem;\n\n if (!(my_default_lc_time_names=\n my_locale_by_name(lc_time_names_name)))\n {\n sql_print_error(\"Unknown locale: '%s'\", lc_time_names_name);\n return 1;\n }\n global_system_variables.lc_time_names= my_default_lc_time_names;\n\n /* check log options and issue warnings if needed */\n if (opt_log && opt_logname && *opt_logname &&\n !(log_output_options & (LOG_FILE | LOG_NONE)))\n sql_print_warning(\"Although a path was specified for the \"\n \"--log option, log tables are used. \"\n \"To enable logging to files use the --log-output option.\");\n\n if (opt_slow_log && opt_slow_logname && *opt_slow_logname &&\n !(log_output_options & (LOG_FILE | LOG_NONE)))\n sql_print_warning(\"Although a path was specified for the \"\n \"--log-slow-queries option, log tables are used. \"\n \"To enable logging to files use the --log-output=file option.\");\n\n if (!opt_logname || !*opt_logname)\n make_default_log_name(&opt_logname, \".log\", false);\n if (!opt_slow_logname || !*opt_slow_logname)\n make_default_log_name(&opt_slow_logname, \"-slow.log\", false);\n\n#if defined(ENABLED_DEBUG_SYNC)\n /* Initialize the debug sync facility. See debug_sync.cc. */\n if (debug_sync_init())\n return 1; /* purecov: tested */\n#endif /* defined(ENABLED_DEBUG_SYNC) */\n\n#if (ENABLE_TEMP_POOL)\n if (use_temp_pool && bitmap_init(&temp_pool,0,1024,1))\n return 1;\n#else\n use_temp_pool= 0;\n#endif\n\n if (my_dboptions_cache_init())\n return 1;\n\n /*\n Ensure that lower_case_table_names is set on system where we have case\n insensitive names. If this is not done the users MyISAM tables will\n get corrupted if accesses with names of different case.\n */\n DBUG_PRINT(\"info\", (\"lower_case_table_names: %d\", lower_case_table_names));\n lower_case_file_system= test_if_case_insensitive(mysql_real_data_home);\n if (!lower_case_table_names && lower_case_file_system == 1)\n {\n if (lower_case_table_names_used)\n {\n#if MYSQL_VERSION_ID < 100100\n if (global_system_variables.log_warnings)\n sql_print_warning(\"You have forced lower_case_table_names to 0 through \"\n \"a command-line option, even though your file system \"\n \"'%s' is case insensitive. This means that you can \"\n \"corrupt your tables if you access them using names \"\n \"with different letter case. You should consider \"\n \"changing lower_case_table_names to 1 or 2\",\n mysql_real_data_home);\n#else\n sql_print_error(\"The server option 'lower_case_table_names' is \"\n \"configured to use case sensitive table names but the \"\n \"data directory resides on a case-insensitive file system. \"\n \"Please use a case sensitive file system for your data \"\n \"directory or switch to a case-insensitive table name \"\n \"mode.\");\n#endif\n return 1;\n }\n else\n {\n if (global_system_variables.log_warnings)\n\tsql_print_warning(\"Setting lower_case_table_names=2 because file system for %s is case insensitive\", mysql_real_data_home);\n lower_case_table_names= 2;\n }\n }\n else if (lower_case_table_names == 2 &&\n !(lower_case_file_system= (lower_case_file_system == 1)))\n {\n if (global_system_variables.log_warnings)\n sql_print_warning(\"lower_case_table_names was set to 2, even though your \"\n \"the file system '%s' is case sensitive. Now setting \"\n \"lower_case_table_names to 0 to avoid future problems.\",\n\t\t\tmysql_real_data_home);\n lower_case_table_names= 0;\n }\n else\n {\n lower_case_file_system= (lower_case_file_system == 1);\n }\n\n /* Reset table_alias_charset, now that lower_case_table_names is set. */\n table_alias_charset= (lower_case_table_names ?\n\t\t\tfiles_charset_info :\n\t\t\t&my_charset_bin);\n\n if (ignore_db_dirs_process_additions())\n {\n sql_print_error(\"An error occurred while storing ignore_db_dirs to a hash.\");\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': '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: static int writeBufferToContigTiles (TIFF* out, uint8* buf, uint32 imagelength,\n\t\t\t\t uint32 imagewidth, tsample_t spp, \n struct dump_opts* dump)\n {\n uint16 bps;\n uint32 tl, tw;\n uint32 row, col, nrow, ncol;\n uint32 src_rowsize, col_offset;\n uint32 tile_rowsize = TIFFTileRowSize(out);\n uint8* bufp = (uint8*) buf;\n tsize_t tile_buffsize = 0;\n tsize_t tilesize = TIFFTileSize(out);\n unsigned char *tilebuf = NULL;\n\n if( !TIFFGetField(out, TIFFTAG_TILELENGTH, &tl) ||\n !TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw) ||\n !TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps) )\n return 1;\n\n if (tilesize == 0 || tile_rowsize == 0 || tl == 0 || tw == 0)\n {\n TIFFError(\"writeBufferToContigTiles\", \"Tile size, tile row size, tile width, or tile length is zero\");\n exit(-1);\n }\n \n tile_buffsize = tilesize;\n if (tilesize < (tsize_t)(tl * tile_rowsize))\n {\n#ifdef DEBUG2\n TIFFError(\"writeBufferToContigTiles\",\n\t \"Tilesize %lu is too small, using alternate calculation %u\",\n tilesize, tl * tile_rowsize);\n#endif\n tile_buffsize = tl * tile_rowsize;\n if (tl != tile_buffsize / tile_rowsize)\n {\n\tTIFFError(\"writeBufferToContigTiles\", \"Integer overflow when calculating buffer size\");\n\texit(-1);\n }\n }\n\n tilebuf = _TIFFmalloc(tile_buffsize);\n if (tilebuf == 0)\n return 1;\n\n src_rowsize = ((imagewidth * spp * bps) + 7) / 8;\n for (row = 0; row < imagelength; row += tl)\n {\n nrow = (row + tl > imagelength) ? imagelength - row : tl;\n for (col = 0; col < imagewidth; col += tw)\n {\n /* Calculate visible portion of tile. */\n if (col + tw > imagewidth)\n\tncol = imagewidth - col;\n else\n ncol = tw;\n\n col_offset = (((col * bps * spp) + 7) / 8);\n bufp = buf + (row * src_rowsize) + col_offset;\n if (extractContigSamplesToTileBuffer(tilebuf, bufp, nrow, ncol, imagewidth,\n\t\t\t\t\t tw, 0, spp, spp, bps, dump) > 0)\n {\n\tTIFFError(\"writeBufferToContigTiles\", \n \"Unable to extract data to tile for row %lu, col %lu\",\n (unsigned long) row, (unsigned long)col);\n\t_TIFFfree(tilebuf);\n\treturn 1;\n }\n\n if (TIFFWriteTile(out, tilebuf, col, row, 0, 0) < 0)\n {\n\tTIFFError(\"writeBufferToContigTiles\",\n\t \"Cannot write tile at %lu %lu\",\n\t (unsigned long) col, (unsigned long) row);\n\t _TIFFfree(tilebuf);\n\treturn 1;\n\t}\n }\n }\n _TIFFfree(tilebuf);\n\n return 0;\n } /* end writeBufferToContigTiles */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': '* tools/tiffcrop.c: fix multiple uint32 overflows in\nwriteBufferToSeparateStrips(), writeBufferToContigTiles() and\nwriteBufferToSeparateTiles() that could cause heap buffer overflows.\nReported by Henri Salo from Nixu Corporation.\nFixes http://bugzilla.maptools.org/show_bug.cgi?id=2592'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PredictorDecodeRow(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)\n{\n\tTIFFPredictorState *sp = PredictorState(tif);\n\n\tassert(sp != NULL);\n\tassert(sp->decoderow != NULL);\n\tassert(sp->decodepfunc != NULL); \n\n\tif ((*sp->decoderow)(tif, op0, occ0, s)) {\n\t\t(*sp->decodepfunc)(tif, op0, occ0);\n\t\treturn 1;\n\t} else\n\t\treturn 0;\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: fpDiff(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;\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\t_TIFFmemcpy(tmp, cp0, cc);\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[byte * wc + count] = tmp[bps * count + byte];\n\t\t\t#else\n\t\t\tcp[(bps - byte - 1) * wc + count] =\n\t\t\t\ttmp[bps * count + byte];\n\t\t\t#endif\n\t\t}\n\t}\n\t_TIFFfree(tmp);\n\n\tcp = (uint8 *) cp0;\n\tcp += cc - stride - 1;\n\tfor (count = cc; count > stride; count -= stride)\n\t\tREPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--)\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': '* libtiff/tif_predict.h, libtiff/tif_predict.c:\nReplace assertions by runtime checks to avoid assertions in debug mode,\nor buffer overflows in release mode. Can happen when dealing with\nunusual tile size like YCbCr with subsampling. Reported as MSVR 35105\nby Axel Souchet\t& Vishal Chauhan from the MSRC Vulnerabilities & Mitigations\nteam.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int readContigTilesIntoBuffer (TIFF* in, uint8* buf, \n uint32 imagelength, \n uint32 imagewidth, \n uint32 tw, uint32 tl,\n tsample_t spp, uint16 bps)\n {\n int status = 1;\n tsample_t sample = 0;\n tsample_t count = spp; \n uint32 row, col, trow;\n uint32 nrow, ncol;\n uint32 dst_rowsize, shift_width;\n uint32 bytes_per_sample, bytes_per_pixel;\n uint32 trailing_bits, prev_trailing_bits;\n uint32 tile_rowsize = TIFFTileRowSize(in);\n uint32 src_offset, dst_offset;\n uint32 row_offset, col_offset;\n uint8 *bufp = (uint8*) buf;\n unsigned char *src = NULL;\n unsigned char *dst = NULL;\n tsize_t tbytes = 0, tile_buffsize = 0;\n tsize_t tilesize = TIFFTileSize(in);\n unsigned char *tilebuf = NULL;\n\n bytes_per_sample = (bps + 7) / 8; \n bytes_per_pixel = ((bps * spp) + 7) / 8;\n\n if ((bps % 8) == 0)\n shift_width = 0;\n else\n {\n if (bytes_per_pixel < (bytes_per_sample + 1))\n shift_width = bytes_per_pixel;\n else\n shift_width = bytes_per_sample + 1;\n }\n\n tile_buffsize = tilesize;\n if (tilesize == 0 || tile_rowsize == 0)\n {\n TIFFError(\"readContigTilesIntoBuffer\", \"Tile size or tile rowsize is zero\");\n exit(-1);\n }\n\n if (tilesize < (tsize_t)(tl * tile_rowsize))\n {\n#ifdef DEBUG2\n TIFFError(\"readContigTilesIntoBuffer\",\n\t \"Tilesize %lu is too small, using alternate calculation %u\",\n tilesize, tl * tile_rowsize);\n#endif\n tile_buffsize = tl * tile_rowsize;\n if (tl != (tile_buffsize / tile_rowsize))\n {\n \tTIFFError(\"readContigTilesIntoBuffer\", \"Integer overflow when calculating buffer size.\");\n exit(-1);\n }\n }\n\n tilebuf = _TIFFmalloc(tile_buffsize);\n if (tilebuf == 0)\n return 0;\n\n dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; \n for (row = 0; row < imagelength; row += tl)\n {\n nrow = (row + tl > imagelength) ? imagelength - row : tl;\n for (col = 0; col < imagewidth; col += tw)\n {\n tbytes = TIFFReadTile(in, tilebuf, col, row, 0, 0);\n if (tbytes < tilesize && !ignore)\n {\n\tTIFFError(TIFFFileName(in),\n\t\t \"Error, can't read tile at row %lu col %lu, Read %lu bytes of %lu\",\n\t\t (unsigned long) col, (unsigned long) row, (unsigned long)tbytes,\n (unsigned long)tilesize);\n\t\t status = 0;\n _TIFFfree(tilebuf);\n\t\t return status;\n\t}\n \n row_offset = row * dst_rowsize;\n col_offset = ((col * bps * spp) + 7)/ 8;\n bufp = buf + row_offset + col_offset;\n\n if (col + tw > imagewidth)\n\tncol = imagewidth - col;\n else\n ncol = tw;\n\n /* Each tile scanline will start on a byte boundary but it\n * has to be merged into the scanline for the entire\n * image buffer and the previous segment may not have\n * ended on a byte boundary\n */\n /* Optimization for common bit depths, all samples */\n if (((bps % 8) == 0) && (count == spp))\n {\n\tfor (trow = 0; trow < nrow; trow++)\n {\n\t src_offset = trow * tile_rowsize;\n\t _TIFFmemcpy (bufp, tilebuf + src_offset, (ncol * spp * bps) / 8);\n bufp += (imagewidth * bps * spp) / 8;\n\t }\n }\n else\n {\n\t/* Bit depths not a multiple of 8 and/or extract fewer than spp samples */\n prev_trailing_bits = trailing_bits = 0;\n trailing_bits = (ncol * bps * spp) % 8;\n\n\t/*\tfor (trow = 0; tl < nrow; trow++) */\n\tfor (trow = 0; trow < nrow; trow++)\n {\n\t src_offset = trow * tile_rowsize;\n src = tilebuf + src_offset;\n\t dst_offset = (row + trow) * dst_rowsize;\n dst = buf + dst_offset + col_offset;\n switch (shift_width)\n {\n case 0: if (extractContigSamplesBytes (src, dst, ncol, sample,\n spp, bps, count, 0, ncol))\n {\n\t\t TIFFError(\"readContigTilesIntoBuffer\",\n \"Unable to extract row %d from tile %lu\", \n\t\t\t\trow, (unsigned long)TIFFCurrentTile(in));\n\t\t return 1;\n\t\t }\n\t\t break;\n case 1: if (bps == 1)\n { \n if (extractContigSamplesShifted8bits (src, dst, ncol,\n sample, spp,\n bps, count,\n 0, ncol,\n prev_trailing_bits))\n {\n\t\t TIFFError(\"readContigTilesIntoBuffer\",\n \"Unable to extract row %d from tile %lu\", \n\t\t\t\t row, (unsigned long)TIFFCurrentTile(in));\n\t\t return 1;\n\t\t }\n\t\t break;\n\t\t }\n else\n if (extractContigSamplesShifted16bits (src, dst, ncol,\n sample, spp,\n bps, count,\n 0, ncol,\n prev_trailing_bits))\n {\n\t\t TIFFError(\"readContigTilesIntoBuffer\",\n \"Unable to extract row %d from tile %lu\", \n\t\t\t \t row, (unsigned long)TIFFCurrentTile(in));\n\t\t return 1;\n\t\t }\n\t break;\n case 2: if (extractContigSamplesShifted24bits (src, dst, ncol,\n sample, spp,\n bps, count,\n 0, ncol,\n prev_trailing_bits))\n {\n\t\t TIFFError(\"readContigTilesIntoBuffer\",\n \"Unable to extract row %d from tile %lu\", \n\t\t \t row, (unsigned long)TIFFCurrentTile(in));\n\t\t return 1;\n\t\t }\n\t\t break;\n case 3:\n case 4:\n case 5: if (extractContigSamplesShifted32bits (src, dst, ncol,\n sample, spp,\n bps, count,\n 0, ncol,\n prev_trailing_bits))\n {\n\t\t TIFFError(\"readContigTilesIntoBuffer\",\n \"Unable to extract row %d from tile %lu\", \n\t\t\t row, (unsigned long)TIFFCurrentTile(in));\n\t\t return 1;\n\t\t }\n\t\t break;\n default: TIFFError(\"readContigTilesIntoBuffer\", \"Unsupported bit depth %d\", bps);\n\t\t return 1;\n\t }\n }\n prev_trailing_bits += trailing_bits;\n /* if (prev_trailing_bits > 7) */\n\t/* prev_trailing_bits-= 8; */\n\t}\n }\n }\n\n _TIFFfree(tilebuf);\n return status;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-125', 'CWE-787'], 'message': '* tools/tiffcrop.c: fix out-of-bound read of up to 3 bytes in\nreadContigTilesIntoBuffer(). Reported as MSVR 35092 by Axel Souchet\n& Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int EC_GROUP_set_generator(EC_GROUP *group, const EC_POINT *generator, const BIGNUM *order, const BIGNUM *cofactor)\n\t{\n\tif (generator == NULL)\n\t\t{\n\t\tECerr(EC_F_EC_GROUP_SET_GENERATOR, ERR_R_PASSED_NULL_PARAMETER);\n\t\treturn 0 ;\n\t\t}\n\n\tif (group->generator == NULL)\n\t\t{\n\t\tgroup->generator = EC_POINT_new(group);\n\t\tif (group->generator == NULL) return 0;\n\t\t}\n\tif (!EC_POINT_copy(group->generator, generator)) return 0;\n\n\tif (order != NULL)\n\t\t{ if (!BN_copy(&group->order, order)) return 0; }\t\n\telse\n\t\tBN_zero(&group->order);\n\n\tif (cofactor != NULL)\n\t\t{ if (!BN_copy(&group->cofactor, cofactor)) return 0; }\t\n\telse\n\t\tBN_zero(&group->cofactor);\n\n\treturn 1;\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_ccm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr)\n{\n EVP_AES_CCM_CTX *cctx = EVP_C_DATA(EVP_AES_CCM_CTX,c);\n switch (type) {\n case EVP_CTRL_INIT:\n cctx->key_set = 0;\n cctx->iv_set = 0;\n cctx->L = 8;\n cctx->M = 12;\n cctx->tag_set = 0;\n cctx->len_set = 0;\n cctx->tls_aad_len = -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 cctx->tls_aad_len = arg;\n {\n uint16_t 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_CCM_TLS_EXPLICIT_IV_LEN;\n /* If decrypting correct for tag too */\n if (!EVP_CIPHER_CTX_encrypting(c))\n len -= cctx->M;\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 cctx->M;\n\n case EVP_CTRL_CCM_SET_IV_FIXED:\n /* Sanity check length */\n if (arg != EVP_CCM_TLS_FIXED_IV_LEN)\n return 0;\n /* Just copy to first part of IV */\n memcpy(EVP_CIPHER_CTX_iv_noconst(c), ptr, arg);\n return 1;\n\n case EVP_CTRL_AEAD_SET_IVLEN:\n arg = 15 - arg;\n case EVP_CTRL_CCM_SET_L:\n if (arg < 2 || arg > 8)\n return 0;\n cctx->L = arg;\n return 1;\n\n case EVP_CTRL_AEAD_SET_TAG:\n if ((arg & 1) || arg < 4 || arg > 16)\n return 0;\n if (EVP_CIPHER_CTX_encrypting(c) && ptr)\n return 0;\n if (ptr) {\n cctx->tag_set = 1;\n memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg);\n }\n cctx->M = arg;\n return 1;\n\n case EVP_CTRL_AEAD_GET_TAG:\n if (!EVP_CIPHER_CTX_encrypting(c) || !cctx->tag_set)\n return 0;\n if (!CRYPTO_ccm128_tag(&cctx->ccm, ptr, (size_t)arg))\n return 0;\n cctx->tag_set = 0;\n cctx->iv_set = 0;\n cctx->len_set = 0;\n return 1;\n\n case EVP_CTRL_COPY:\n {\n EVP_CIPHER_CTX *out = ptr;\n EVP_AES_CCM_CTX *cctx_out = EVP_C_DATA(EVP_AES_CCM_CTX,out);\n if (cctx->ccm.key) {\n if (cctx->ccm.key != &cctx->ks)\n return 0;\n cctx_out->ccm.key = &cctx_out->ks;\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: static int tls_construct_cke_ecdhe(SSL *s, unsigned char **p, int *len, int *al)\n{\n#ifndef OPENSSL_NO_EC\n unsigned char *encodedPoint = NULL;\n int encoded_pt_len = 0;\n EVP_PKEY *ckey = NULL, *skey = NULL;\n\n skey = s->s3->peer_tmp;\n if (skey == NULL) {\n SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR);\n return 0;\n }\n\n ckey = ssl_generate_pkey(skey);\n\n if (ssl_derive(s, ckey, skey) == 0) {\n SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EVP_LIB);\n goto err;\n }\n\n /* Generate encoding of client key */\n encoded_pt_len = EVP_PKEY_get1_tls_encodedpoint(ckey, &encodedPoint);\n\n if (encoded_pt_len == 0) {\n SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EC_LIB);\n goto err;\n }\n\n EVP_PKEY_free(ckey);\n ckey = NULL;\n\n *len = encoded_pt_len;\n\n /* length of encoded point */\n **p = *len;\n *p += 1;\n /* copy the point */\n memcpy(*p, encodedPoint, *len);\n /* increment len to account for length field */\n *len += 1;\n\n OPENSSL_free(encodedPoint);\n\n return 1;\n err:\n EVP_PKEY_free(ckey);\n return 0;\n#else\n SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR);\n *al = SSL_AD_INTERNAL_ERROR;\n return 0;\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix missing NULL checks in CKE processing\n\nReviewed-by: Rich Salz '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TIFFReadEncodedStrip(TIFF* tif, uint32 strip, void* buf, tmsize_t size)\n{\n\tstatic const char module[] = \"TIFFReadEncodedStrip\";\n\tTIFFDirectory *td = &tif->tif_dir;\n\tuint32 rowsperstrip;\n\tuint32 stripsperplane;\n\tuint32 stripinplane;\n\tuint16 plane;\n\tuint32 rows;\n\ttmsize_t stripsize;\n\tif (!TIFFCheckRead(tif,0))\n\t\treturn((tmsize_t)(-1));\n\tif (strip>=td->td_nstrips)\n\t{\n\t\tTIFFErrorExt(tif->tif_clientdata,module,\n\t\t \"%lu: Strip out of range, max %lu\",(unsigned long)strip,\n\t\t (unsigned long)td->td_nstrips);\n\t\treturn((tmsize_t)(-1));\n\t}\n\t/*\n\t * Calculate the strip size according to the number of\n\t * rows in the strip (check for truncated last strip on any\n\t * of the separations).\n\t */\n\trowsperstrip=td->td_rowsperstrip;\n\tif (rowsperstrip>td->td_imagelength)\n\t\trowsperstrip=td->td_imagelength;\n\tstripsperplane=((td->td_imagelength+rowsperstrip-1)/rowsperstrip);\n\tstripinplane=(strip%stripsperplane);\n\tplane=(uint16)(strip/stripsperplane);\n\trows=td->td_imagelength-stripinplane*rowsperstrip;\n\tif (rows>rowsperstrip)\n\t\trows=rowsperstrip;\n\tstripsize=TIFFVStripSize(tif,rows);\n\tif (stripsize==0)\n\t\treturn((tmsize_t)(-1));\n\n /* shortcut to avoid an extra memcpy() */\n if( td->td_compression == COMPRESSION_NONE &&\n size!=(tmsize_t)(-1) && size >= stripsize &&\n !isMapped(tif) &&\n ((tif->tif_flags&TIFF_NOREADRAW)==0) )\n {\n if (TIFFReadRawStrip1(tif, strip, buf, stripsize, module) != stripsize)\n return ((tmsize_t)(-1));\n\n if (!isFillOrder(tif, td->td_fillorder) &&\n (tif->tif_flags & TIFF_NOBITREV) == 0)\n TIFFReverseBits(buf,stripsize);\n\n (*tif->tif_postdecode)(tif,buf,stripsize);\n return (stripsize);\n }\n\n\tif ((size!=(tmsize_t)(-1))&&(sizetif_decodestrip)(tif,buf,stripsize,plane)<=0)\n\t\treturn((tmsize_t)(-1));\n\t(*tif->tif_postdecode)(tif,buf,stripsize);\n\treturn(stripsize);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': '* libtiff/tif_read.c, libtiff/tiffiop.h: fix uint32 overflow in\nTIFFReadEncodedStrip() that caused an integer division by zero.\nReported by Agostino Sarubbo.\nFixes http://bugzilla.maptools.org/show_bug.cgi?id=2596'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TIFFWriteDirectoryTagSampleformatArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, double* value)\n{\n\tstatic const char module[] = \"TIFFWriteDirectoryTagSampleformatArray\";\n\tvoid* conv;\n\tuint32 i;\n\tint ok;\n\tconv = _TIFFmalloc(count*sizeof(double));\n\tif (conv == NULL)\n\t{\n\t\tTIFFErrorExt(tif->tif_clientdata, module, \"Out of memory\");\n\t\treturn (0);\n\t}\n\n\tswitch (tif->tif_dir.td_sampleformat)\n\t{\n\t\tcase SAMPLEFORMAT_IEEEFP:\n\t\t\tif (tif->tif_dir.td_bitspersample<=32)\n\t\t\t{\n\t\t\t\tfor (i = 0; i < count; ++i)\n\t\t\t\t\t((float*)conv)[i] = (float)value[i];\n\t\t\t\tok = TIFFWriteDirectoryTagFloatArray(tif,ndir,dir,tag,count,(float*)conv);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tok = TIFFWriteDirectoryTagDoubleArray(tif,ndir,dir,tag,count,value);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase SAMPLEFORMAT_INT:\n\t\t\tif (tif->tif_dir.td_bitspersample<=8)\n\t\t\t{\n\t\t\t\tfor (i = 0; i < count; ++i)\n\t\t\t\t\t((int8*)conv)[i] = (int8)value[i];\n\t\t\t\tok = TIFFWriteDirectoryTagSbyteArray(tif,ndir,dir,tag,count,(int8*)conv);\n\t\t\t}\n\t\t\telse if (tif->tif_dir.td_bitspersample<=16)\n\t\t\t{\n\t\t\t\tfor (i = 0; i < count; ++i)\n\t\t\t\t\t((int16*)conv)[i] = (int16)value[i];\n\t\t\t\tok = TIFFWriteDirectoryTagSshortArray(tif,ndir,dir,tag,count,(int16*)conv);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfor (i = 0; i < count; ++i)\n\t\t\t\t\t((int32*)conv)[i] = (int32)value[i];\n\t\t\t\tok = TIFFWriteDirectoryTagSlongArray(tif,ndir,dir,tag,count,(int32*)conv);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase SAMPLEFORMAT_UINT:\n\t\t\tif (tif->tif_dir.td_bitspersample<=8)\n\t\t\t{\n\t\t\t\tfor (i = 0; i < count; ++i)\n\t\t\t\t\t((uint8*)conv)[i] = (uint8)value[i];\n\t\t\t\tok = TIFFWriteDirectoryTagByteArray(tif,ndir,dir,tag,count,(uint8*)conv);\n\t\t\t}\n\t\t\telse if (tif->tif_dir.td_bitspersample<=16)\n\t\t\t{\n\t\t\t\tfor (i = 0; i < count; ++i)\n\t\t\t\t\t((uint16*)conv)[i] = (uint16)value[i];\n\t\t\t\tok = TIFFWriteDirectoryTagShortArray(tif,ndir,dir,tag,count,(uint16*)conv);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfor (i = 0; i < count; ++i)\n\t\t\t\t\t((uint32*)conv)[i] = (uint32)value[i];\n\t\t\t\tok = TIFFWriteDirectoryTagLongArray(tif,ndir,dir,tag,count,(uint32*)conv);\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tok = 0;\n\t}\n\n\t_TIFFfree(conv);\n\treturn (ok);\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: gaussian_blur_surface (cairo_surface_t *in,\n cairo_surface_t *out,\n gdouble sx,\n gdouble sy)\n{\n gboolean use_box_blur;\n gint width, height;\n cairo_format_t in_format, out_format;\n gint in_stride;\n gint out_stride;\n guchar *in_data, *out_data;\n gint bpp;\n gboolean out_has_data;\n\n cairo_surface_flush (in);\n\n width = cairo_image_surface_get_width (in);\n height = cairo_image_surface_get_height (in);\n\n g_assert (width == cairo_image_surface_get_width (out)\n && height == cairo_image_surface_get_height (out));\n\n in_format = cairo_image_surface_get_format (in);\n out_format = cairo_image_surface_get_format (out);\n g_assert (in_format == out_format);\n g_assert (in_format == CAIRO_FORMAT_ARGB32\n || in_format == CAIRO_FORMAT_A8);\n\n if (in_format == CAIRO_FORMAT_ARGB32)\n bpp = 4;\n else if (in_format == CAIRO_FORMAT_A8)\n bpp = 1;\n else {\n g_assert_not_reached ();\n return;\n }\n\n in_stride = cairo_image_surface_get_stride (in);\n out_stride = cairo_image_surface_get_stride (out);\n\n in_data = cairo_image_surface_get_data (in);\n out_data = cairo_image_surface_get_data (out);\n\n if (sx < 0.0)\n sx = 0.0;\n\n if (sy < 0.0)\n sy = 0.0;\n\n /* For small radiuses, use a true gaussian kernel; otherwise use three box blurs with\n * clever offsets.\n */\n if (sx < 10.0 && sy < 10.0)\n use_box_blur = FALSE;\n else\n use_box_blur = TRUE;\n\n /* Bail out by just copying? */\n if ((sx == 0.0 && sy == 0.0)\n || sx > 1000 || sy > 1000) {\n cairo_t *cr;\n\n cr = cairo_create (out);\n cairo_set_source_surface (cr, in, 0, 0);\n cairo_paint (cr);\n cairo_destroy (cr);\n return;\n }\n\n if (sx != 0.0) {\n gint box_width;\n gdouble *gaussian_matrix;\n gint gaussian_matrix_len;\n int y;\n guchar *row_buffer = NULL;\n guchar *row1, *row2;\n\n if (use_box_blur) {\n box_width = compute_box_blur_width (sx);\n\n /* twice the size so we can have \"two\" scratch rows */\n row_buffer = g_new0 (guchar, width * bpp * 2);\n row1 = row_buffer;\n row2 = row_buffer + width * bpp;\n } else\n make_gaussian_convolution_matrix (sx, &gaussian_matrix, &gaussian_matrix_len);\n\n for (y = 0; y < height; y++) {\n guchar *in_row, *out_row;\n\n in_row = in_data + in_stride * y;\n out_row = out_data + out_stride * y;\n\n if (use_box_blur) {\n if (box_width % 2 != 0) {\n /* Odd-width box blur: repeat 3 times, centered on output pixel */\n\n box_blur_line (box_width, 0, in_row, row1, width, bpp);\n box_blur_line (box_width, 0, row1, row2, width, bpp);\n box_blur_line (box_width, 0, row2, out_row, width, bpp);\n } else {\n /* Even-width box blur:\n * This method is suggested by the specification for SVG.\n * One pass with width n, centered between output and right pixel\n * One pass with width n, centered between output and left pixel\n * One pass with width n+1, centered on output pixel\n */\n box_blur_line (box_width, -1, in_row, row1, width, bpp);\n box_blur_line (box_width, 1, row1, row2, width, bpp);\n box_blur_line (box_width + 1, 0, row2, out_row, width, bpp);\n }\n } else\n gaussian_blur_line (gaussian_matrix, gaussian_matrix_len, in_row, out_row, width, bpp);\n }\n\n if (!use_box_blur)\n g_free (gaussian_matrix);\n\n g_free (row_buffer);\n\n out_has_data = TRUE;\n } else\n out_has_data = FALSE;\n\n if (sy != 0.0) {\n gint box_height;\n gdouble *gaussian_matrix = NULL;\n gint gaussian_matrix_len;\n guchar *col_buffer;\n guchar *col1, *col2;\n int x;\n\n /* twice the size so we can have the source pixels and the blurred pixels */\n col_buffer = g_new0 (guchar, height * bpp * 2);\n col1 = col_buffer;\n col2 = col_buffer + height * bpp;\n\n if (use_box_blur) {\n box_height = compute_box_blur_width (sy);\n } else\n make_gaussian_convolution_matrix (sy, &gaussian_matrix, &gaussian_matrix_len);\n\n for (x = 0; x < width; x++) {\n if (out_has_data)\n get_column (col1, out_data, out_stride, bpp, height, x);\n else\n get_column (col1, in_data, in_stride, bpp, height, x);\n\n if (use_box_blur) {\n if (box_height % 2 != 0) {\n /* Odd-width box blur */\n box_blur_line (box_height, 0, col1, col2, height, bpp);\n box_blur_line (box_height, 0, col2, col1, height, bpp);\n box_blur_line (box_height, 0, col1, col2, height, bpp);\n } else {\n /* Even-width box blur */\n box_blur_line (box_height, -1, col1, col2, height, bpp);\n box_blur_line (box_height, 1, col2, col1, height, bpp);\n box_blur_line (box_height + 1, 0, col1, col2, height, bpp);\n }\n } else\n gaussian_blur_line (gaussian_matrix, gaussian_matrix_len, col1, col2, height, bpp);\n\n put_column (col2, out_data, out_stride, bpp, height, x);\n }\n\n g_free (gaussian_matrix);\n g_free (col_buffer);\n }\n\n cairo_surface_mark_dirty (out);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'bgo#783835 - Don't divide by zero in box_blur_line() for gaussian blurs\n\nWe were making the decision to use box blurs, instead of a true\nGaussian kernel, based on the size of *both* x and y dimensions. Do\nthem individually instead.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: 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 int rv;\n rv = asn1_item_embed_d2i(pval, in, len, it, tag, aclass, opt, ctx);\n if (rv <= 0)\n ASN1_item_ex_free(pval, it);\n return rv;\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: Agraph_t *agroot(void* obj)\n{\n switch (AGTYPE(obj)) {\n case AGINEDGE:\n case AGOUTEDGE:\n\treturn ((Agedge_t *) obj)->node->root;\n case AGNODE:\n\treturn ((Agnode_t *) obj)->root;\n case AGRAPH:\n\treturn ((Agraph_t *) obj)->root;\n default:\t\t\t/* actually can't occur if only 2 bit tags */\n\tagerr(AGERR, \"agroot of a bad object\");\n\treturn NILgraph;\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 RAND_DRBG *rand_drbg_new(int secure,\n int type,\n unsigned int flags,\n RAND_DRBG *parent)\n{\n RAND_DRBG *drbg = secure ? OPENSSL_secure_zalloc(sizeof(*drbg))\n : OPENSSL_zalloc(sizeof(*drbg));\n\n if (drbg == NULL) {\n RANDerr(RAND_F_RAND_DRBG_NEW, ERR_R_MALLOC_FAILURE);\n return NULL;\n }\n\n drbg->secure = secure && CRYPTO_secure_allocated(drbg);\n drbg->fork_count = rand_fork_count;\n drbg->parent = parent;\n\n if (parent == NULL) {\n drbg->get_entropy = rand_drbg_get_entropy;\n drbg->cleanup_entropy = rand_drbg_cleanup_entropy;\n#ifndef RAND_DRBG_GET_RANDOM_NONCE\n drbg->get_nonce = rand_drbg_get_nonce;\n drbg->cleanup_nonce = rand_drbg_cleanup_nonce;\n#endif\n\n drbg->reseed_interval = master_reseed_interval;\n drbg->reseed_time_interval = master_reseed_time_interval;\n } else {\n drbg->get_entropy = rand_drbg_get_entropy;\n drbg->cleanup_entropy = rand_drbg_cleanup_entropy;\n /*\n * Do not provide nonce callbacks, the child DRBGs will\n * obtain their nonce using random bits from the parent.\n */\n\n drbg->reseed_interval = slave_reseed_interval;\n drbg->reseed_time_interval = slave_reseed_time_interval;\n }\n\n if (RAND_DRBG_set(drbg, type, flags) == 0)\n goto err;\n\n if (parent != NULL) {\n rand_drbg_lock(parent);\n if (drbg->strength > parent->strength) {\n /*\n * We currently don't support the algorithm from NIST SP 800-90C\n * 10.1.2 to use a weaker DRBG as source\n */\n rand_drbg_unlock(parent);\n RANDerr(RAND_F_RAND_DRBG_NEW, RAND_R_PARENT_STRENGTH_TOO_WEAK);\n goto err;\n }\n rand_drbg_unlock(parent);\n }\n\n return drbg;\n\n err:\n RAND_DRBG_free(drbg);\n\n return NULL;\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: static int pkcs7_decrypt_rinfo(unsigned char **pek, int *peklen,\n PKCS7_RECIP_INFO *ri, EVP_PKEY *pkey)\n{\n EVP_PKEY_CTX *pctx = NULL;\n unsigned char *ek = NULL;\n size_t eklen;\n\n int ret = -1;\n\n pctx = EVP_PKEY_CTX_new(pkey, NULL);\n if (!pctx)\n return -1;\n\n if (EVP_PKEY_decrypt_init(pctx) <= 0)\n goto err;\n\n if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_DECRYPT,\n EVP_PKEY_CTRL_PKCS7_DECRYPT, 0, ri) <= 0) {\n PKCS7err(PKCS7_F_PKCS7_DECRYPT_RINFO, PKCS7_R_CTRL_ERROR);\n goto err;\n }\n\n if (EVP_PKEY_decrypt(pctx, NULL, &eklen,\n ri->enc_key->data, ri->enc_key->length) <= 0)\n goto err;\n\n ek = OPENSSL_malloc(eklen);\n\n if (ek == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DECRYPT_RINFO, ERR_R_MALLOC_FAILURE);\n goto err;\n }\n\n if (EVP_PKEY_decrypt(pctx, ek, &eklen,\n ri->enc_key->data, ri->enc_key->length) <= 0) {\n ret = 0;\n PKCS7err(PKCS7_F_PKCS7_DECRYPT_RINFO, ERR_R_EVP_LIB);\n goto err;\n }\n\n ret = 1;\n\n if (*pek) {\n OPENSSL_cleanse(*pek, *peklen);\n OPENSSL_free(*pek);\n }\n\n *pek = ek;\n *peklen = eklen;\n\n err:\n if (pctx)\n EVP_PKEY_CTX_free(pctx);\n if (!ret && ek)\n OPENSSL_free(ek);\n\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-327'], 'message': 'Fix a padding oracle in PKCS7_dataDecode and CMS_decrypt_set1_pkey\n\nAn attack is simple, if the first CMS_recipientInfo is valid but the\nsecond CMS_recipientInfo is chosen ciphertext. If the second\nrecipientInfo decodes to PKCS #1 v1.5 form plaintext, the correct\nencryption key will be replaced by garbage, and the message cannot be\ndecoded, but if the RSA decryption fails, the correct encryption key is\nused and the recipient will not notice the attack.\n\nAs a work around for this potential attack the length of the decrypted\nkey must be equal to the cipher default key length, in case the\ncertifiate is not given and all recipientInfo are tried out.\n\nThe old behaviour can be re-enabled in the CMS code by setting the\nCMS_DEBUG_DECRYPT flag.\n\nReviewed-by: Matt Caswell \n(Merged from https://github.com/openssl/openssl/pull/9777)\n\n(cherry picked from commit 5840ed0cd1e6487d247efbc1a04136a41d7b3a37)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Network::FilterStatus Context::onDownstreamData(int data_length, bool end_of_stream) {\n if (!wasm_->onDownstreamData_) {\n return Network::FilterStatus::Continue;\n }\n auto result = wasm_->onDownstreamData_(this, id_, static_cast(data_length),\n static_cast(end_of_stream));\n // TODO(PiotrSikora): pull Proxy-WASM's FilterStatus values.\n return result.u64_ == 0 ? Network::FilterStatus::Continue : Network::FilterStatus::StopIteration;\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: Network::FilterStatus Context::onNetworkNewConnection() {\n onCreate(root_context_id_);\n if (!wasm_->onNewConnection_) {\n return Network::FilterStatus::Continue;\n }\n if (wasm_->onNewConnection_(this, id_).u64_ == 0) {\n return Network::FilterStatus::Continue;\n }\n return Network::FilterStatus::StopIteration;\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_status napi_get_value_string_latin1(napi_env env,\n napi_value value,\n char* buf,\n size_t bufsize,\n size_t* result) {\n CHECK_ENV(env);\n CHECK_ARG(env, value);\n\n v8::Local val = v8impl::V8LocalValueFromJsValue(value);\n RETURN_STATUS_IF_FALSE(env, val->IsString(), napi_string_expected);\n\n if (!buf) {\n CHECK_ARG(env, result);\n *result = val.As()->Length();\n } else {\n int copied =\n val.As()->WriteOneByte(env->isolate,\n reinterpret_cast(buf),\n 0,\n bufsize - 1,\n v8::String::NO_NULL_TERMINATION);\n\n buf[copied] = '\\0';\n if (result != nullptr) {\n *result = copied;\n }\n }\n\n return napi_clear_last_error(env);\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: inline StreamWriteResult StreamBase::Write(\n uv_buf_t* bufs,\n size_t count,\n uv_stream_t* send_handle,\n v8::Local req_wrap_obj) {\n Environment* env = stream_env();\n int err;\n\n size_t total_bytes = 0;\n for (size_t i = 0; i < count; ++i)\n total_bytes += bufs[i].len;\n bytes_written_ += total_bytes;\n\n if (send_handle == nullptr) {\n err = DoTryWrite(&bufs, &count);\n if (err != 0 || count == 0) {\n return StreamWriteResult { false, err, nullptr, total_bytes };\n }\n }\n\n HandleScope handle_scope(env->isolate());\n\n if (req_wrap_obj.IsEmpty()) {\n req_wrap_obj =\n env->write_wrap_template()\n ->NewInstance(env->context()).ToLocalChecked();\n StreamReq::ResetObject(req_wrap_obj);\n }\n\n AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(GetAsyncWrap());\n WriteWrap* req_wrap = CreateWriteWrap(req_wrap_obj);\n\n err = DoWrite(req_wrap, bufs, count, send_handle);\n bool async = err == 0;\n\n if (!async) {\n req_wrap->Dispose();\n req_wrap = nullptr;\n }\n\n const char* msg = Error();\n if (msg != nullptr) {\n req_wrap_obj->Set(env->error_string(), OneByteString(env->isolate(), msg));\n ClearError();\n }\n\n return StreamWriteResult { async, err, req_wrap, total_bytes };\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 FuzzerTestOneInput(const uint8_t *buf, size_t len)\n{\n const unsigned char *p = buf;\n unsigned char *der = NULL;\n\n X509 *x509 = d2i_X509(NULL, &p, len);\n if (x509 != NULL) {\n BIO *bio = BIO_new(BIO_s_null());\n /* This will load and print the public key as well as extensions */\n X509_print(bio, x509);\n BIO_free(bio);\n\n i2d_X509(x509, &der);\n OPENSSL_free(der);\n\n X509_free(x509);\n }\n ERR_clear_error();\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Test that X509_issuer_and_serial_hash doesn't crash\n\nProvide a certificate with a bad issuer and check that\nX509_issuer_and_serial_hash doesn't crash.\n\nReviewed-by: Richard Levitte \nReviewed-by: Paul Dale '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: oauth2_jwt_body_process(const struct oauth2_settings *set, const char *alg,\n\t\t\tconst char *kid, ARRAY_TYPE(oauth2_field) *fields,\n\t\t\tstruct json_tree *tree, const char *const *blobs,\n\t\t\tconst char **error_r)\n{\n\tconst char *sub = get_field(tree, \"sub\");\n\n\tint ret;\n\tint64_t t0 = time(NULL);\n\t/* default IAT and NBF to now */\n\tint64_t iat, nbf, exp;\n\tint tz_offset ATTR_UNUSED;\n\n\tif (sub == NULL) {\n\t\t*error_r = \"Missing 'sub' field\";\n\t\treturn -1;\n\t}\n\n\tif ((ret = get_time_field(tree, \"exp\", &exp)) < 1) {\n\t\t*error_r = t_strdup_printf(\"%s 'exp' field\",\n\t\t\t\tret == 0 ? \"Missing\" : \"Malformed\");\n\t\treturn -1;\n\t}\n\n\tif ((ret = get_time_field(tree, \"nbf\", &nbf)) < 0) {\n\t\t*error_r = \"Malformed 'nbf' field\";\n\t\treturn -1;\n\t} else if (ret == 0 || nbf == 0)\n\t\tnbf = t0;\n\n\tif ((ret = get_time_field(tree, \"iat\", &iat)) < 0) {\n\t\t*error_r = \"Malformed 'iat' field\";\n\t\treturn -1;\n\t} else if (ret == 0 || iat == 0)\n\t\tiat = t0;\n\n\tif (nbf > t0) {\n\t\t*error_r = \"Token is not valid yet\";\n\t\treturn -1;\n\t}\n\tif (iat > t0) {\n\t\t*error_r = \"Token is issued in future\";\n\t\treturn -1;\n\t}\n\tif (exp < t0) {\n\t\t*error_r = \"Token has expired\";\n\t\treturn -1;\n\t}\n\n\t/* ensure token dates are not conflicting */\n\tif (nbf < iat ||\n\t exp < iat ||\n\t exp < nbf) {\n\t\t*error_r = \"Token time values are conflicting\";\n\t\treturn -1;\n\t}\n\n\tconst char *iss = get_field(tree, \"iss\");\n\tif (set->issuers != NULL && *set->issuers != NULL) {\n\t\tif (iss == NULL) {\n\t\t\t*error_r = \"Token is missing 'iss' field\";\n\t\t\treturn -1;\n\t\t}\n\t\tif (!str_array_find(set->issuers, iss)) {\n\t\t\t*error_r = t_strdup_printf(\"Issuer '%s' is not allowed\",\n\t\t\t\t\t\t str_sanitize_utf8(iss, 128));\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\t/* see if there is azp */\n\tconst char *azp = get_field(tree, \"azp\");\n\tif (azp == NULL)\n\t\tazp = \"default\";\n\n\tif (oauth2_validate_signature(set, azp, alg, kid, blobs, error_r) < 0)\n\t\treturn -1;\n\n\toauth2_jwt_copy_fields(fields, tree);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'lib-oauth2: Ensure azp is escaped too'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Http2Stream::SubmitRstStream(const uint32_t code) {\n CHECK(!this->is_destroyed());\n code_ = code;\n\n // If RST_STREAM frame is received and stream is not writable\n // because it is busy reading data, don't try force purging it.\n // Instead add the stream to pending stream list and process\n // the pending data when it is safe to do so. This is to avoid\n // double free error due to unwanted behavior of nghttp2.\n // Ref:https://github.com/nodejs/node/issues/38964\n\n // Add stream to the pending list if it is received with scope\n // below in the stack. The pending list may not get processed\n // if RST_STREAM received is not in scope and added to the list\n // causing endpoint to hang.\n if (session_->is_in_scope() &&\n !is_writable() && is_reading()) {\n session_->AddPendingRstStream(id_);\n return;\n }\n\n\n // If possible, force a purge of any currently pending data here to make sure\n // it is sent before closing the stream. If it returns non-zero then we need\n // to wait until the current write finishes and try again to avoid nghttp2\n // behaviour where it prioritizes RstStream over everything else.\n if (session_->SendPendingData() != 0) {\n session_->AddPendingRstStream(id_);\n return;\n }\n\n FlushRstStream();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'http2: update handling of rst_stream with error code NGHTTP2_CANCEL\n\nThe PR updates the handling of rst_stream frames and adds all streams\nto the pending list on receiving rst frames with the error code\nNGHTTP2_CANCEL.\n\nThe changes will remove dependency on the stream state that may allow\nbypassing the checks in certain cases. I think a better solution is to\ndelay streams in all cases if rst_stream is received for the cancel\nevents.\n\nThe rst_stream frames can be received for protocol/connection error as\nwell it should be handled immediately. Adding streams to the pending\nlist in such cases may cause errors.\n\nCVE-ID: CVE-2021-22930\nRefs: https://nvd.nist.gov/vuln/detail/CVE-2021-22930\nPR-URL: https://github.com/nodejs/node/pull/39622\nRefs: https://github.com/nodejs/node/pull/39423\nReviewed-By: Matteo Collina \nReviewed-By: James M Snell \nReviewed-By: Beth Griggs '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ia5casecmp(const char *s1, const char *s2)\n{\n return ia5ncasecmp(s1, s2, SIZE_MAX);\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: int ssl_verify_cert_chain(SSL *s, STACK_OF(X509) *sk)\n{\n X509 *x;\n int i = 0;\n X509_STORE *verify_store;\n X509_STORE_CTX *ctx = NULL;\n X509_VERIFY_PARAM *param;\n\n if ((sk == NULL) || (sk_X509_num(sk) == 0))\n return 0;\n\n if (s->cert->verify_store)\n verify_store = s->cert->verify_store;\n else\n verify_store = s->ctx->cert_store;\n\n ctx = X509_STORE_CTX_new_ex(s->ctx->libctx, s->ctx->propq);\n if (ctx == NULL) {\n ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);\n return 0;\n }\n\n x = sk_X509_value(sk, 0);\n if (!X509_STORE_CTX_init(ctx, verify_store, x, sk)) {\n ERR_raise(ERR_LIB_SSL, ERR_R_X509_LIB);\n goto end;\n }\n param = X509_STORE_CTX_get0_param(ctx);\n /*\n * XXX: Separate @AUTHSECLEVEL and @TLSSECLEVEL would be useful at some\n * point, for now a single @SECLEVEL sets the same policy for TLS crypto\n * and PKI authentication.\n */\n X509_VERIFY_PARAM_set_auth_level(param, SSL_get_security_level(s));\n\n /* Set suite B flags if needed */\n X509_STORE_CTX_set_flags(ctx, tls1_suiteb(s));\n if (!X509_STORE_CTX_set_ex_data\n (ctx, SSL_get_ex_data_X509_STORE_CTX_idx(), s)) {\n goto end;\n }\n\n /* Verify via DANE if enabled */\n if (DANETLS_ENABLED(&s->dane))\n X509_STORE_CTX_set0_dane(ctx, &s->dane);\n\n /*\n * We need to inherit the verify parameters. These can be determined by\n * the context: if its a server it will verify SSL client certificates or\n * vice versa.\n */\n\n X509_STORE_CTX_set_default(ctx, s->server ? \"ssl_client\" : \"ssl_server\");\n /*\n * Anything non-default in \"s->param\" should overwrite anything in the ctx.\n */\n X509_VERIFY_PARAM_set1(param, s->param);\n\n if (s->verify_callback)\n X509_STORE_CTX_set_verify_cb(ctx, s->verify_callback);\n\n if (s->ctx->app_verify_callback != NULL)\n i = s->ctx->app_verify_callback(ctx, s->ctx->app_verify_arg);\n else\n i = X509_verify_cert(ctx);\n\n s->verify_result = X509_STORE_CTX_get_error(ctx);\n sk_X509_pop_free(s->verified_chain, X509_free);\n s->verified_chain = NULL;\n if (X509_STORE_CTX_get0_chain(ctx) != NULL) {\n s->verified_chain = X509_STORE_CTX_get1_chain(ctx);\n if (s->verified_chain == NULL) {\n ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);\n i = 0;\n }\n }\n\n /* Move peername from the store context params to the SSL handle's */\n X509_VERIFY_PARAM_move_peername(s->param, param);\n\n end:\n X509_STORE_CTX_free(ctx);\n return i;\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: void X509Certificate::InfoAccess(const FunctionCallbackInfo& args) {\n Environment* env = Environment::GetCurrent(args);\n X509Certificate* cert;\n ASSIGN_OR_RETURN_UNWRAP(&cert, args.Holder());\n BIOPointer bio(BIO_new(BIO_s_mem()));\n Local ret;\n if (GetInfoString(env, bio, cert->get()).ToLocal(&ret))\n args.GetReturnValue().Set(ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-295'], 'message': 'crypto,tls: implement safe x509 GeneralName format\n\nThis change introduces JSON-compatible escaping rules for strings that\ninclude X.509 GeneralName components (see RFC 5280). This non-standard\nformat avoids ambiguities and prevents injection attacks that could\npreviously lead to X.509 certificates being accepted even though they\nwere not valid for the target hostname.\n\nThese changes affect the format of subject alternative names and the\nformat of authority information access. The checkServerIdentity function\nhas been modified to safely handle the new format, eliminating the\npossibility of injecting subject alternative names into the verification\nlogic.\n\nBecause each subject alternative name is only encoded as a JSON string\nliteral if necessary for security purposes, this change will only be\nvisible in rare cases.\n\nThis addresses CVE-2021-44532.\n\nCVE-ID: CVE-2021-44532\nPR-URL: https://github.com/nodejs-private/node-private/pull/300\nReviewed-By: Michael Dawson \nReviewed-By: Rich Trott '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static bool fix_vcol_expr(THD *thd, Virtual_column_info *vcol)\n{\n DBUG_ENTER(\"fix_vcol_expr\");\n\n const enum enum_column_usage saved_column_usage= thd->column_usage;\n thd->column_usage= COLUMNS_WRITE;\n\n int error= vcol->expr->fix_fields(thd, &vcol->expr);\n\n thd->column_usage= saved_column_usage;\n\n if (unlikely(error))\n {\n StringBuffer str;\n vcol->print(&str);\n my_error(ER_ERROR_EVALUATING_EXPRESSION, MYF(0), str.c_ptr_safe());\n DBUG_RETURN(1);\n }\n\n DBUG_RETURN(0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'MDEV-24176 Preparations\n\n1. moved fix_vcol_exprs() call to open_table()\n\nmysql_alter_table() doesn't do lock_tables() so it cannot win from\nfix_vcol_exprs() from there. Tests affected: main.default_session\n\n2. Vanilla cleanups and comments.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static bool check_vcol_forward_refs(Field *field, Virtual_column_info *vcol,\n bool check_constraint)\n{\n bool res;\n uint32 flags= field->flags;\n if (check_constraint)\n {\n /* Check constraints can refer it itself */\n field->flags|= NO_DEFAULT_VALUE_FLAG;\n }\n res= (vcol &&\n vcol->expr->walk(&Item::check_field_expression_processor, 0, field));\n field->flags= flags;\n 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: int TABLE::update_default_fields(bool ignore_errors)\n{\n Query_arena backup_arena;\n Field **field_ptr;\n int res= 0;\n DBUG_ENTER(\"TABLE::update_default_fields\");\n DBUG_ASSERT(default_field);\n\n in_use->set_n_backup_active_arena(expr_arena, &backup_arena);\n\n /* Iterate over fields with default functions in the table */\n for (field_ptr= default_field; *field_ptr ; field_ptr++)\n {\n Field *field= (*field_ptr);\n /*\n If an explicit default value for a field overrides the default,\n do not update the field with its automatic default value.\n */\n if (!field->has_explicit_value())\n {\n if (field->default_value &&\n (field->default_value->flags || field->flags & BLOB_FLAG))\n res|= (field->default_value->expr->save_in_field(field, 0) < 0);\n if (!ignore_errors && res)\n {\n my_error(ER_CALCULATING_DEFAULT_VALUE, MYF(0), field->field_name.str);\n break;\n }\n res= 0;\n }\n }\n in_use->restore_active_arena(expr_arena, &backup_arena);\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: Table_arena(MEM_ROOT *mem_root, enum enum_state state_arg) :\n Query_arena(mem_root, state_arg){} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'MDEV-26281 ASAN use-after-poison when complex conversion is involved in blob\n\nthe bug was that in_vector array in Item_func_in was allocated in the\nstatement arena, not in the table->expr_arena.\n\nrevert part of the 5acd391e8b2d. Instead, change the arena correctly\nin fix_all_session_vcol_exprs().\n\nRemove TABLE_ARENA, that was introduced in 5acd391e8b2d to force\nitem tree changes to be rolled back (because they were allocated in the\nwrong arena and didn't persist. now they do)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Field_new_decimal::Field_new_decimal(uchar *ptr_arg,\n uint32 len_arg, uchar *null_ptr_arg,\n uchar null_bit_arg,\n enum utype unireg_check_arg,\n const char *field_name_arg,\n uint8 dec_arg,bool zero_arg,\n bool unsigned_arg)\n :Field_num(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,\n unireg_check_arg, field_name_arg, dec_arg, zero_arg, unsigned_arg)\n{\n precision= my_decimal_length_to_precision(len_arg, dec_arg, unsigned_arg);\n set_if_smaller(precision, DECIMAL_MAX_PRECISION);\n DBUG_ASSERT((precision <= DECIMAL_MAX_PRECISION) &&\n (dec <= DECIMAL_MAX_SCALE));\n bin_size= my_decimal_get_binary_size(precision, dec);\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: xbstream_open(ds_ctxt_t *ctxt, const char *path, MY_STAT *mystat)\n{\n\tds_file_t\t\t*file;\n\tds_stream_file_t\t*stream_file;\n\tds_stream_ctxt_t\t*stream_ctxt;\n\tds_ctxt_t\t\t*dest_ctxt;\n\txb_wstream_t\t\t*xbstream;\n\txb_wstream_file_t\t*xbstream_file;\n\n\n\txb_ad(ctxt->pipe_ctxt != NULL);\n\tdest_ctxt = ctxt->pipe_ctxt;\n\n\tstream_ctxt = (ds_stream_ctxt_t *) ctxt->ptr;\n\n\tpthread_mutex_lock(&stream_ctxt->mutex);\n\tif (stream_ctxt->dest_file == NULL) {\n\t\tstream_ctxt->dest_file = ds_open(dest_ctxt, path, mystat);\n\t\tif (stream_ctxt->dest_file == NULL) {\n\t\t\treturn NULL;\n\t\t}\n\t}\n\tpthread_mutex_unlock(&stream_ctxt->mutex);\n\n\tfile = (ds_file_t *) my_malloc(sizeof(ds_file_t) +\n\t\t\t\t sizeof(ds_stream_file_t),\n\t\t\t\t MYF(MY_FAE));\n\tstream_file = (ds_stream_file_t *) (file + 1);\n\n\txbstream = stream_ctxt->xbstream;\n\n\txbstream_file = xb_stream_write_open(xbstream, path, mystat,\n\t\t stream_ctxt,\n\t\t\t\t\t my_xbstream_write_callback);\n\n\tif (xbstream_file == NULL) {\n\t\tmsg(\"xb_stream_write_open() failed.\");\n\t\tgoto err;\n\t}\n\n\tstream_file->xbstream_file = xbstream_file;\n\tstream_file->stream_ctxt = stream_ctxt;\n\tfile->ptr = stream_file;\n\tfile->path = stream_ctxt->dest_file->path;\n\n\treturn file;\n\nerr:\n\tif (stream_ctxt->dest_file) {\n\t\tds_close(stream_ctxt->dest_file);\n\t\tstream_ctxt->dest_file = NULL;\n\t}\n\tmy_free(file);\n\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-667'], 'message': 'MDEV-26574 An improper locking bug due to unreleased lock in the ds_xbstream.cc\n\nrelease lock in all as cases n xbstream_open, also fix the case where malloc would return 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: zfs_fastaccesschk_execute(znode_t *zdp, cred_t *cr)\n{\n\tboolean_t owner = B_FALSE;\n\tboolean_t groupmbr = B_FALSE;\n\tboolean_t is_attr;\n\tuid_t uid = crgetuid(cr);\n\n\tif (zdp->z_pflags & ZFS_AV_QUARANTINED)\n\t\treturn (1);\n\n\tis_attr = ((zdp->z_pflags & ZFS_XATTR) &&\n\t (ZTOV(zdp)->v_type == VDIR));\n\tif (is_attr)\n\t\treturn (1);\n\n\tif (zdp->z_pflags & ZFS_NO_EXECS_DENIED)\n\t\treturn (0);\n\n\tmutex_enter(&zdp->z_acl_lock);\n\tif (FUID_INDEX(zdp->z_uid) != 0 || FUID_INDEX(zdp->z_gid) != 0) {\n\t\tgoto out_slow;\n\t}\n\n\tif (uid == zdp->z_uid) {\n\t\towner = B_TRUE;\n\t\tif (zdp->z_mode & S_IXUSR) {\n\t\t\tgoto out;\n\t\t} else {\n\t\t\tgoto out_slow;\n\t\t}\n\t}\n\tif (groupmember(zdp->z_gid, cr)) {\n\t\tgroupmbr = B_TRUE;\n\t\tif (zdp->z_mode & S_IXGRP) {\n\t\t\tgoto out;\n\t\t} else {\n\t\t\tgoto out_slow;\n\t\t}\n\t}\n\tif (!owner && !groupmbr) {\n\t\tif (zdp->z_mode & S_IXOTH) {\n\t\t\tgoto out;\n\t\t}\n\t}\nout:\n\tmutex_exit(&zdp->z_acl_lock);\n\treturn (0);\nout_slow:\n\tmutex_exit(&zdp->z_acl_lock);\n\treturn (1);\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: inline st_select_lex_node* get_slave() { return slave; } ; 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 ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)\n{\n const unsigned char *buf = buf_;\n int tot;\n unsigned int n, split_send_fragment, maxpipes;\n#if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK\n unsigned int max_send_fragment, nw;\n unsigned int u_len = (unsigned int)len;\n#endif\n SSL3_BUFFER *wb = &s->rlayer.wbuf[0];\n int i;\n\n if (len < 0) {\n SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_NEGATIVE_LENGTH);\n return -1;\n }\n\n s->rwstate = SSL_NOTHING;\n tot = s->rlayer.wnum;\n /*\n * ensure that if we end up with a smaller value of data to write out\n * than the the original len from a write which didn't complete for\n * non-blocking I/O and also somehow ended up avoiding the check for\n * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be\n * possible to end up with (len-tot) as a large number that will then\n * promptly send beyond the end of the users buffer ... so we trap and\n * report the error in a way the user will notice\n */\n if ((unsigned int)len < s->rlayer.wnum) {\n SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_BAD_LENGTH);\n return -1;\n }\n\n s->rlayer.wnum = 0;\n\n if (SSL_in_init(s) && !ossl_statem_get_in_handshake(s)) {\n i = s->handshake_func(s);\n if (i < 0)\n return (i);\n if (i == 0) {\n SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);\n return -1;\n }\n }\n\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 (wb->left != 0) {\n i = ssl3_write_pending(s, type, &buf[tot], s->rlayer.wpend_tot);\n if (i <= 0) {\n /* XXX should we ssl3_release_write_buffer if i<0? */\n s->rlayer.wnum = tot;\n return i;\n }\n tot += i; /* this might be last fragment */\n }\n#if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK\n /*\n * Depending on platform multi-block can deliver several *times*\n * better performance. Downside is that it has to allocate\n * jumbo buffer to accommodate up to 8 records, but the\n * compromise is considered worthy.\n */\n if (type == SSL3_RT_APPLICATION_DATA &&\n u_len >= 4 * (max_send_fragment = s->max_send_fragment) &&\n s->compress == NULL && s->msg_callback == NULL &&\n !SSL_USE_ETM(s) && SSL_USE_EXPLICIT_IV(s) &&\n EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_write_ctx)) &\n EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) {\n unsigned char aad[13];\n EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;\n int packlen;\n\n /* minimize address aliasing conflicts */\n if ((max_send_fragment & 0xfff) == 0)\n max_send_fragment -= 512;\n\n if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */\n ssl3_release_write_buffer(s);\n\n packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,\n EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,\n max_send_fragment, NULL);\n\n if (u_len >= 8 * max_send_fragment)\n packlen *= 8;\n else\n packlen *= 4;\n\n if (!ssl3_setup_write_buffer(s, 1, packlen)) {\n SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_MALLOC_FAILURE);\n return -1;\n }\n } else if (tot == len) { /* done? */\n /* free jumbo buffer */\n ssl3_release_write_buffer(s);\n return tot;\n }\n\n n = (len - tot);\n for (;;) {\n if (n < 4 * max_send_fragment) {\n /* free jumbo buffer */\n ssl3_release_write_buffer(s);\n break;\n }\n\n if (s->s3->alert_dispatch) {\n i = s->method->ssl_dispatch_alert(s);\n if (i <= 0) {\n s->rlayer.wnum = tot;\n return i;\n }\n }\n\n if (n >= 8 * max_send_fragment)\n nw = max_send_fragment * (mb_param.interleave = 8);\n else\n nw = max_send_fragment * (mb_param.interleave = 4);\n\n memcpy(aad, s->rlayer.write_sequence, 8);\n aad[8] = type;\n aad[9] = (unsigned char)(s->version >> 8);\n aad[10] = (unsigned char)(s->version);\n aad[11] = 0;\n aad[12] = 0;\n mb_param.out = NULL;\n mb_param.inp = aad;\n mb_param.len = nw;\n\n packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,\n EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,\n sizeof(mb_param), &mb_param);\n\n if (packlen <= 0 || packlen > (int)wb->len) { /* never happens */\n /* free jumbo buffer */\n ssl3_release_write_buffer(s);\n break;\n }\n\n mb_param.out = wb->buf;\n mb_param.inp = &buf[tot];\n mb_param.len = nw;\n\n if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,\n EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,\n sizeof(mb_param), &mb_param) <= 0)\n return -1;\n\n s->rlayer.write_sequence[7] += mb_param.interleave;\n if (s->rlayer.write_sequence[7] < mb_param.interleave) {\n int j = 6;\n while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ;\n }\n\n wb->offset = 0;\n wb->left = packlen;\n\n s->rlayer.wpend_tot = nw;\n s->rlayer.wpend_buf = &buf[tot];\n s->rlayer.wpend_type = type;\n s->rlayer.wpend_ret = nw;\n\n i = ssl3_write_pending(s, type, &buf[tot], nw);\n if (i <= 0) {\n if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {\n /* free jumbo buffer */\n ssl3_release_write_buffer(s);\n }\n s->rlayer.wnum = tot;\n return i;\n }\n if (i == (int)n) {\n /* free jumbo buffer */\n ssl3_release_write_buffer(s);\n return tot + i;\n }\n n -= i;\n tot += i;\n }\n } else\n#endif\n if (tot == len) { /* done? */\n if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s))\n ssl3_release_write_buffer(s);\n\n return tot;\n }\n\n n = (len - tot);\n\n split_send_fragment = s->split_send_fragment;\n /*\n * If max_pipelines is 0 then this means \"undefined\" and we default to\n * 1 pipeline. Similarly if the cipher does not support pipelined\n * processing then we also only use 1 pipeline, or if we're not using\n * explicit IVs\n */\n maxpipes = s->max_pipelines;\n if (maxpipes > SSL_MAX_PIPELINES) {\n /*\n * We should have prevented this when we set max_pipelines so we\n * shouldn't get here\n */\n SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_INTERNAL_ERROR);\n return -1;\n }\n if (maxpipes == 0\n || s->enc_write_ctx == NULL\n || !(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_write_ctx))\n & EVP_CIPH_FLAG_PIPELINE)\n || !SSL_USE_EXPLICIT_IV(s))\n maxpipes = 1;\n if (s->max_send_fragment == 0 || split_send_fragment > s->max_send_fragment\n || split_send_fragment == 0) {\n /*\n * We should have prevented this when we set the split and max send\n * fragments so we shouldn't get here\n */\n SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_INTERNAL_ERROR);\n return -1;\n }\n\n for (;;) {\n unsigned int pipelens[SSL_MAX_PIPELINES], tmppipelen, remain;\n unsigned int numpipes, j;\n\n if (n == 0)\n numpipes = 1;\n else\n numpipes = ((n - 1) / split_send_fragment) + 1;\n if (numpipes > maxpipes)\n numpipes = maxpipes;\n\n if (n / numpipes >= s->max_send_fragment) {\n /*\n * We have enough data to completely fill all available\n * pipelines\n */\n for (j = 0; j < numpipes; j++) {\n pipelens[j] = s->max_send_fragment;\n }\n } else {\n /* We can partially fill all available pipelines */\n tmppipelen = n / numpipes;\n remain = n % numpipes;\n for (j = 0; j < numpipes; j++) {\n pipelens[j] = tmppipelen;\n if (j < remain)\n pipelens[j]++;\n }\n }\n\n i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0);\n if (i <= 0) {\n /* XXX should we ssl3_release_write_buffer if i<0? */\n s->rlayer.wnum = tot;\n return i;\n }\n\n if ((i == (int)n) ||\n (type == SSL3_RT_APPLICATION_DATA &&\n (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {\n /*\n * next chunk of data should get another prepended empty fragment\n * in ciphersuites with known-IV weakness:\n */\n s->s3->empty_fragment_done = 0;\n\n if ((i == (int)n) && s->mode & SSL_MODE_RELEASE_BUFFERS &&\n !SSL_IS_DTLS(s))\n ssl3_release_write_buffer(s);\n\n return tot + i;\n }\n\n n -= i;\n tot += i;\n }\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: passdb_preinit(pool_t pool, const struct auth_passdb_settings *set)\n{\n\tstatic unsigned int auth_passdb_id = 0;\n\tstruct passdb_module_interface *iface;\n\tstruct passdb_module *passdb;\n\tunsigned int idx;\n\n\tiface = passdb_interface_find(set->driver);\n\tif (iface == NULL || iface->verify_plain == NULL) {\n\t\t/* maybe it's a plugin. try to load it. */\n\t\tauth_module_load(t_strconcat(\"authdb_\", set->driver, NULL));\n\t\tiface = passdb_interface_find(set->driver);\n\t}\n\tif (iface == NULL)\n\t\ti_fatal(\"Unknown passdb driver '%s'\", set->driver);\n\tif (iface->verify_plain == NULL) {\n\t\ti_fatal(\"Support not compiled in for passdb driver '%s'\",\n\t\t\tset->driver);\n\t}\n\tif (iface->preinit == NULL && iface->init == NULL &&\n\t *set->args != '\\0') {\n\t\ti_fatal(\"passdb %s: No args are supported: %s\",\n\t\t\tset->driver, set->args);\n\t}\n\n\tpassdb = passdb_find(set->driver, set->args, &idx);\n\tif (passdb != NULL)\n\t\treturn passdb;\n\n\tif (iface->preinit == NULL)\n\t\tpassdb = p_new(pool, struct passdb_module, 1);\n\telse\n\t\tpassdb = iface->preinit(pool, set->args);\n\tpassdb->id = ++auth_passdb_id;\n\tpassdb->iface = *iface;\n\tpassdb->args = p_strdup(pool, set->args);\n\tif (*set->mechanisms == '\\0') {\n\t\tpassdb->mechanisms = NULL;\n\t} else if (strcasecmp(set->mechanisms, \"none\") == 0) {\n\t\tpassdb->mechanisms = (const char *const[]){NULL};\n\t} else {\n\t\tpassdb->mechanisms = (const char* const*)p_strsplit_spaces(pool, set->mechanisms, \" ,\");\n\t}\n\n\tif (*set->username_filter == '\\0') {\n\t\tpassdb->username_filter = NULL;\n\t} else {\n\t\tpassdb->username_filter = (const char* const*)p_strsplit_spaces(pool, set->username_filter, \" ,\");\n\t}\n\tarray_push_back(&passdb_modules, &passdb);\n\treturn passdb;\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 int php_sqlite3_collation_callback(void *context,\n\tint string1_len, const void *string1,\n\tint string2_len, const void *string2)\n{\n\tint ret;\n\tzval *zstring1, *zstring2;\n\tzval **zargs[2];\n\tzval *retval = NULL;\n\tstruct pdo_sqlite_collation *collation = (struct pdo_sqlite_collation*) context;\n\tTSRMLS_FETCH();\n\n\tcollation->fc.fci.size = sizeof(collation->fc.fci);\n\tcollation->fc.fci.function_table = EG(function_table);\n\tcollation->fc.fci.function_name = collation->callback;\n\tcollation->fc.fci.symbol_table = NULL;\n\tcollation->fc.fci.object_ptr = NULL;\n\tcollation->fc.fci.retval_ptr_ptr = &retval;\n\n\t// Prepare the arguments.\n\tMAKE_STD_ZVAL(zstring1);\n\tZVAL_STRINGL(zstring1, (char *) string1, string1_len, 1);\n\tzargs[0] = &zstring1;\n\tMAKE_STD_ZVAL(zstring2);\n\tZVAL_STRINGL(zstring2, (char *) string2, string2_len, 1);\n\tzargs[1] = &zstring2;\n\tcollation->fc.fci.param_count = 2;\n\tcollation->fc.fci.params = zargs;\n\n\tif ((ret = zend_call_function(&collation->fc.fci, &collation->fc.fcc TSRMLS_CC)) == FAILURE) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"An error occurred while invoking the callback\");\n\t}\n\telse if (retval) {\n\t\tif (Z_TYPE_P(retval) != IS_LONG) {\n\t\t\tconvert_to_long_ex(&retval);\n\t\t}\n\t\tret = 0;\n\t\tif (Z_LVAL_P(retval) > 0) {\n\t\t\tret = 1;\n\t\t}\n\t\telse if (Z_LVAL_P(retval) < 0) {\n\t\t\tret = -1;\n\t\t}\n\t\tzval_ptr_dtor(&retval);\n\t}\n\n\tzval_ptr_dtor(zargs[0]);\n\tzval_ptr_dtor(zargs[1]);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'Improve check for :memory: pseudo-filename in SQlite'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static PHP_METHOD(SQLite, sqliteCreateAggregate)\n{\n\tstruct pdo_sqlite_func *func;\n\tzval *step_callback, *fini_callback;\n\tchar *func_name;\n\tint func_name_len;\n\tlong argc = -1;\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, \"szz|l\",\n\t\t\t&func_name, &func_name_len, &step_callback, &fini_callback, &argc)) {\n\t\tRETURN_FALSE;\n\t}\n\t\n\tdbh = zend_object_store_get_object(getThis() TSRMLS_CC);\n\tPDO_CONSTRUCT_CHECK;\n\n\tif (!zend_is_callable(step_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\tif (!zend_is_callable(fini_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\t\n\tH = (pdo_sqlite_db_handle *)dbh->driver_data;\n\n\tfunc = (struct pdo_sqlite_func*)ecalloc(1, sizeof(*func));\n\n\tret = sqlite3_create_function(H->db, func_name, argc, SQLITE_UTF8,\n\t\t\tfunc, NULL, php_sqlite3_func_step_callback, php_sqlite3_func_final_callback);\n\tif (ret == SQLITE_OK) {\n\t\tfunc->funcname = estrdup(func_name);\n\t\t\n\t\tMAKE_STD_ZVAL(func->step);\n\t\tMAKE_COPY_ZVAL(&step_callback, func->step);\n\n\t\tMAKE_STD_ZVAL(func->fini);\n\t\tMAKE_COPY_ZVAL(&fini_callback, func->fini);\n\t\t\n\t\tfunc->argc = argc;\n\n\t\tfunc->next = H->funcs;\n\t\tH->funcs = func;\n\n\t\tRETURN_TRUE;\n\t}\n\n\tefree(func);\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 PHP_METHOD(SQLite, sqliteCreateFunction)\n{\n\tstruct pdo_sqlite_func *func;\n\tzval *callback;\n\tchar *func_name;\n\tint func_name_len;\n\tlong argc = -1;\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|l\",\n\t\t\t&func_name, &func_name_len, &callback, &argc)) {\n\t\tRETURN_FALSE;\n\t}\n\t\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\t\n\tH = (pdo_sqlite_db_handle *)dbh->driver_data;\n\n\tfunc = (struct pdo_sqlite_func*)ecalloc(1, sizeof(*func));\n\n\tret = sqlite3_create_function(H->db, func_name, argc, SQLITE_UTF8,\n\t\t\tfunc, php_sqlite3_func_callback, NULL, NULL);\n\tif (ret == SQLITE_OK) {\n\t\tfunc->funcname = estrdup(func_name);\n\t\t\n\t\tMAKE_STD_ZVAL(func->func);\n\t\tMAKE_COPY_ZVAL(&callback, func->func);\n\t\t\n\t\tfunc->argc = argc;\n\n\t\tfunc->next = H->funcs;\n\t\tH->funcs = func;\n\n\t\tRETURN_TRUE;\n\t}\n\n\tefree(func);\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: glue(glue(cirrus_bitblt_rop_fwd_transp_, ROP_NAME),_8)(CirrusVGAState *s,\n\t\t\t\t\t\t uint8_t *dst,const uint8_t *src,\n\t\t\t\t\t\t int dstpitch,int srcpitch,\n\t\t\t\t\t\t int bltwidth,int bltheight)\n{\n int x,y;\n uint8_t p;\n dstpitch -= bltwidth;\n srcpitch -= bltwidth;\n for (y = 0; y < bltheight; y++) {\n for (x = 0; x < bltwidth; x++) {\n\t p = *dst;\n ROP_OP(p, *src);\n\t if (p != s->gr[0x34]) *dst = p;\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 void cirrus_read_hidden_dac(CirrusVGAState * s, int *reg_value)\n{\n *reg_value = 0xff;\n if (++s->cirrus_hidden_dac_lockindex == 5) {\n *reg_value = s->cirrus_hidden_dac_data;\n\ts->cirrus_hidden_dac_lockindex = 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: cirrus_hook_read_sr(CirrusVGAState * s, unsigned reg_index, int *reg_value)\n{\n switch (reg_index) {\n case 0x00:\t\t\t// Standard VGA\n case 0x01:\t\t\t// Standard VGA\n case 0x02:\t\t\t// Standard VGA\n case 0x03:\t\t\t// Standard VGA\n case 0x04:\t\t\t// Standard VGA\n\treturn CIRRUS_HOOK_NOT_HANDLED;\n case 0x06:\t\t\t// Unlock Cirrus extensions\n\t*reg_value = s->sr[reg_index];\n\tbreak;\n case 0x10:\n case 0x30:\n case 0x50:\n case 0x70:\t\t\t// Graphics Cursor X\n case 0x90:\n case 0xb0:\n case 0xd0:\n case 0xf0:\t\t\t// Graphics Cursor X\n\t*reg_value = s->sr[0x10];\n\tbreak;\n case 0x11:\n case 0x31:\n case 0x51:\n case 0x71:\t\t\t// Graphics Cursor Y\n case 0x91:\n case 0xb1:\n case 0xd1:\n case 0xf1:\t\t\t// Graphics Cursor Y\n\t*reg_value = s->sr[0x11];\n\tbreak;\n case 0x05:\t\t\t// ???\n case 0x07:\t\t\t// Extended Sequencer Mode\n case 0x08:\t\t\t// EEPROM Control\n case 0x09:\t\t\t// Scratch Register 0\n case 0x0a:\t\t\t// Scratch Register 1\n case 0x0b:\t\t\t// VCLK 0\n case 0x0c:\t\t\t// VCLK 1\n case 0x0d:\t\t\t// VCLK 2\n case 0x0e:\t\t\t// VCLK 3\n case 0x0f:\t\t\t// DRAM Control\n case 0x12:\t\t\t// Graphics Cursor Attribute\n case 0x13:\t\t\t// Graphics Cursor Pattern Address\n case 0x14:\t\t\t// Scratch Register 2\n case 0x15:\t\t\t// Scratch Register 3\n case 0x16:\t\t\t// Performance Tuning Register\n case 0x17:\t\t\t// Configuration Readback and Extended Control\n case 0x18:\t\t\t// Signature Generator Control\n case 0x19:\t\t\t// Signal Generator Result\n case 0x1a:\t\t\t// Signal Generator Result\n case 0x1b:\t\t\t// VCLK 0 Denominator & Post\n case 0x1c:\t\t\t// VCLK 1 Denominator & Post\n case 0x1d:\t\t\t// VCLK 2 Denominator & Post\n case 0x1e:\t\t\t// VCLK 3 Denominator & Post\n case 0x1f:\t\t\t// BIOS Write Enable and MCLK select\n#ifdef DEBUG_CIRRUS\n\tprintf(\"cirrus: handled inport sr_index %02x\\n\", reg_index);\n#endif\n\t*reg_value = s->sr[reg_index];\n\tbreak;\n default:\n#ifdef DEBUG_CIRRUS\n\tprintf(\"cirrus: inport sr_index %02x\\n\", reg_index);\n#endif\n\t*reg_value = 0xff;\n\tbreak;\n }\n\n return CIRRUS_HOOK_HANDLED;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX \"bitblt\" heap overflow\n\nI have just noticed that patch for CVE-2007-1320 has never been applied\nto the QEMU CVS. Please find it below.\n\n| Multiple heap-based buffer overflows in the cirrus_invalidate_region\n| function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and\n| possibly other products, might allow local users to execute arbitrary\n| code via unspecified vectors related to \"attempting to mark\n| non-existent regions as dirty,\" aka the \"bitblt\" heap overflow.\n\n\ngit-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int cirrus_vga_load(QEMUFile *f, void *opaque, int version_id)\n{\n CirrusVGAState *s = opaque;\n int ret;\n\n if (version_id > 2)\n return -EINVAL;\n\n if (s->pci_dev && version_id >= 2) {\n ret = pci_device_load(s->pci_dev, f);\n if (ret < 0)\n return ret;\n }\n\n qemu_get_be32s(f, &s->latch);\n qemu_get_8s(f, &s->sr_index);\n qemu_get_buffer(f, s->sr, 256);\n qemu_get_8s(f, &s->gr_index);\n qemu_get_8s(f, &s->cirrus_shadow_gr0);\n qemu_get_8s(f, &s->cirrus_shadow_gr1);\n s->gr[0x00] = s->cirrus_shadow_gr0 & 0x0f;\n s->gr[0x01] = s->cirrus_shadow_gr1 & 0x0f;\n qemu_get_buffer(f, s->gr + 2, 254);\n qemu_get_8s(f, &s->ar_index);\n qemu_get_buffer(f, s->ar, 21);\n s->ar_flip_flop=qemu_get_be32(f);\n qemu_get_8s(f, &s->cr_index);\n qemu_get_buffer(f, s->cr, 256);\n qemu_get_8s(f, &s->msr);\n qemu_get_8s(f, &s->fcr);\n qemu_get_8s(f, &s->st00);\n qemu_get_8s(f, &s->st01);\n\n qemu_get_8s(f, &s->dac_state);\n qemu_get_8s(f, &s->dac_sub_index);\n qemu_get_8s(f, &s->dac_read_index);\n qemu_get_8s(f, &s->dac_write_index);\n qemu_get_buffer(f, s->dac_cache, 3);\n qemu_get_buffer(f, s->palette, 768);\n\n s->bank_offset=qemu_get_be32(f);\n\n qemu_get_8s(f, &s->cirrus_hidden_dac_lockindex);\n qemu_get_8s(f, &s->cirrus_hidden_dac_data);\n\n qemu_get_be32s(f, &s->hw_cursor_x);\n qemu_get_be32s(f, &s->hw_cursor_y);\n\n /* force refresh */\n s->graphic_mode = -1;\n cirrus_update_bank_ptr(s, 0);\n cirrus_update_bank_ptr(s, 1);\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_write_hidden_dac(CirrusVGAState * s, int reg_value)\n{\n if (s->cirrus_hidden_dac_lockindex == 4) {\n\ts->cirrus_hidden_dac_data = reg_value;\n#if defined(DEBUG_CIRRUS)\n\tprintf(\"cirrus: outport hidden DAC, value %02x\\n\", reg_value);\n#endif\n }\n s->cirrus_hidden_dac_lockindex = 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_linear_bitblt_writeb(void *opaque, target_phys_addr_t addr,\n\t\t\t\t uint32_t val)\n{\n CirrusVGAState *s = (CirrusVGAState *) opaque;\n\n if (s->cirrus_srcptr != s->cirrus_srcptr_end) {\n\t/* bitblt */\n\t*s->cirrus_srcptr++ = (uint8_t) val;\n\tif (s->cirrus_srcptr >= s->cirrus_srcptr_end) {\n\t cirrus_bitblt_cputovideo_next(s);\n\t}\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_vga_save(QEMUFile *f, void *opaque)\n{\n CirrusVGAState *s = opaque;\n\n if (s->pci_dev)\n pci_device_save(s->pci_dev, f);\n\n qemu_put_be32s(f, &s->latch);\n qemu_put_8s(f, &s->sr_index);\n qemu_put_buffer(f, s->sr, 256);\n qemu_put_8s(f, &s->gr_index);\n qemu_put_8s(f, &s->cirrus_shadow_gr0);\n qemu_put_8s(f, &s->cirrus_shadow_gr1);\n qemu_put_buffer(f, s->gr + 2, 254);\n qemu_put_8s(f, &s->ar_index);\n qemu_put_buffer(f, s->ar, 21);\n qemu_put_be32(f, s->ar_flip_flop);\n qemu_put_8s(f, &s->cr_index);\n qemu_put_buffer(f, s->cr, 256);\n qemu_put_8s(f, &s->msr);\n qemu_put_8s(f, &s->fcr);\n qemu_put_8s(f, &s->st00);\n qemu_put_8s(f, &s->st01);\n\n qemu_put_8s(f, &s->dac_state);\n qemu_put_8s(f, &s->dac_sub_index);\n qemu_put_8s(f, &s->dac_read_index);\n qemu_put_8s(f, &s->dac_write_index);\n qemu_put_buffer(f, s->dac_cache, 3);\n qemu_put_buffer(f, s->palette, 768);\n\n qemu_put_be32(f, s->bank_offset);\n\n qemu_put_8s(f, &s->cirrus_hidden_dac_lockindex);\n qemu_put_8s(f, &s->cirrus_hidden_dac_data);\n\n qemu_put_be32s(f, &s->hw_cursor_x);\n qemu_put_be32s(f, &s->hw_cursor_y);\n /* XXX: we do not save the bitblt state - we assume we do not save\n the state when the blitter is active */\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_writew(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 >> 8) & 0xff);\n cirrus_linear_writeb(opaque, addr + 1, val & 0xff);\n#else\n cirrus_linear_writeb(opaque, addr, val & 0xff);\n cirrus_linear_writeb(opaque, addr + 1, (val >> 8) & 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 uint32_t vga_ioport_read(void *opaque, uint32_t addr)\n{\n CirrusVGAState *s = opaque;\n int val, index;\n\n /* check port range access depending on color/monochrome mode */\n if ((addr >= 0x3b0 && addr <= 0x3bf && (s->msr & MSR_COLOR_EMULATION))\n\t|| (addr >= 0x3d0 && addr <= 0x3df\n\t && !(s->msr & MSR_COLOR_EMULATION))) {\n\tval = 0xff;\n } else {\n\tswitch (addr) {\n\tcase 0x3c0:\n\t if (s->ar_flip_flop == 0) {\n\t\tval = s->ar_index;\n\t } else {\n\t\tval = 0;\n\t }\n\t break;\n\tcase 0x3c1:\n\t index = s->ar_index & 0x1f;\n\t if (index < 21)\n\t\tval = s->ar[index];\n\t else\n\t\tval = 0;\n\t break;\n\tcase 0x3c2:\n\t val = s->st00;\n\t break;\n\tcase 0x3c4:\n\t val = s->sr_index;\n\t break;\n\tcase 0x3c5:\n\t if (cirrus_hook_read_sr(s, s->sr_index, &val))\n\t\tbreak;\n\t val = s->sr[s->sr_index];\n#ifdef DEBUG_VGA_REG\n\t printf(\"vga: read SR%x = 0x%02x\\n\", s->sr_index, val);\n#endif\n\t break;\n\tcase 0x3c6:\n\t cirrus_read_hidden_dac(s, &val);\n\t break;\n\tcase 0x3c7:\n\t val = s->dac_state;\n\t break;\n\tcase 0x3c8:\n\t val = s->dac_write_index;\n\t s->cirrus_hidden_dac_lockindex = 0;\n\t break;\n case 0x3c9:\n\t if (cirrus_hook_read_palette(s, &val))\n\t\tbreak;\n\t val = s->palette[s->dac_read_index * 3 + s->dac_sub_index];\n\t if (++s->dac_sub_index == 3) {\n\t\ts->dac_sub_index = 0;\n\t\ts->dac_read_index++;\n\t }\n\t break;\n\tcase 0x3ca:\n\t val = s->fcr;\n\t break;\n\tcase 0x3cc:\n\t val = s->msr;\n\t break;\n\tcase 0x3ce:\n\t val = s->gr_index;\n\t break;\n\tcase 0x3cf:\n\t if (cirrus_hook_read_gr(s, s->gr_index, &val))\n\t\tbreak;\n\t val = s->gr[s->gr_index];\n#ifdef DEBUG_VGA_REG\n\t printf(\"vga: read GR%x = 0x%02x\\n\", s->gr_index, val);\n#endif\n\t break;\n\tcase 0x3b4:\n\tcase 0x3d4:\n\t val = s->cr_index;\n\t break;\n\tcase 0x3b5:\n\tcase 0x3d5:\n\t if (cirrus_hook_read_cr(s, s->cr_index, &val))\n\t\tbreak;\n\t val = s->cr[s->cr_index];\n#ifdef DEBUG_VGA_REG\n\t printf(\"vga: read CR%x = 0x%02x\\n\", s->cr_index, val);\n#endif\n\t break;\n\tcase 0x3ba:\n\tcase 0x3da:\n\t /* just toggle to fool polling */\n\t val = s->st01 = s->retrace((VGAState *) s);\n\t s->ar_flip_flop = 0;\n\t break;\n\tdefault:\n\t val = 0x00;\n\t break;\n\t}\n }\n#if defined(DEBUG_VGA)\n printf(\"VGA: read addr=0x%04x data=0x%02x\\n\", addr, val);\n#endif\n return val;\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 unsigned long getreg(struct task_struct *child, unsigned long regno)\n{\n\tunsigned long val;\n\tswitch (regno) {\n\t\tcase offsetof(struct user_regs_struct, fs):\n\t\t\treturn child->thread.fsindex;\n\t\tcase offsetof(struct user_regs_struct, gs):\n\t\t\treturn child->thread.gsindex;\n\t\tcase offsetof(struct user_regs_struct, ds):\n\t\t\treturn child->thread.ds;\n\t\tcase offsetof(struct user_regs_struct, es):\n\t\t\treturn child->thread.es; \n\t\tcase offsetof(struct user_regs_struct, fs_base):\n\t\t\treturn child->thread.fs;\n\t\tcase offsetof(struct user_regs_struct, gs_base):\n\t\t\treturn child->thread.gs;\n\t\tdefault:\n\t\t\tregno = regno - sizeof(struct pt_regs);\n\t\t\tval = get_stack_long(child, regno);\n\t\t\tif (test_tsk_thread_flag(child, TIF_IA32))\n\t\t\t\tval &= 0xffffffff;\n\t\t\treturn val;\n\t}\n\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: long arch_ptrace(struct task_struct *child, long request, long addr, long data)\n{\n\tlong i, ret;\n\tunsigned ui;\n\n\tswitch (request) {\n\t/* when I and D space are separate, these will need to be fixed. */\n\tcase PTRACE_PEEKTEXT: /* read word at location addr. */ \n\tcase PTRACE_PEEKDATA:\n\t\tret = generic_ptrace_peekdata(child, addr, data);\n\t\tbreak;\n\n\t/* read the word at location addr in the USER area. */\n\tcase PTRACE_PEEKUSR: {\n\t\tunsigned long tmp;\n\n\t\tret = -EIO;\n\t\tif ((addr & 7) ||\n\t\t addr > sizeof(struct user) - 7)\n\t\t\tbreak;\n\n\t\tswitch (addr) { \n\t\tcase 0 ... sizeof(struct user_regs_struct) - sizeof(long):\n\t\t\ttmp = getreg(child, addr);\n\t\t\tbreak;\n\t\tcase offsetof(struct user, u_debugreg[0]):\n\t\t\ttmp = child->thread.debugreg0;\n\t\t\tbreak;\n\t\tcase offsetof(struct user, u_debugreg[1]):\n\t\t\ttmp = child->thread.debugreg1;\n\t\t\tbreak;\n\t\tcase offsetof(struct user, u_debugreg[2]):\n\t\t\ttmp = child->thread.debugreg2;\n\t\t\tbreak;\n\t\tcase offsetof(struct user, u_debugreg[3]):\n\t\t\ttmp = child->thread.debugreg3;\n\t\t\tbreak;\n\t\tcase offsetof(struct user, u_debugreg[6]):\n\t\t\ttmp = child->thread.debugreg6;\n\t\t\tbreak;\n\t\tcase offsetof(struct user, u_debugreg[7]):\n\t\t\ttmp = child->thread.debugreg7;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\ttmp = 0;\n\t\t\tbreak;\n\t\t}\n\t\tret = put_user(tmp,(unsigned long __user *) data);\n\t\tbreak;\n\t}\n\n\t/* when I and D space are separate, this will have to be fixed. */\n\tcase PTRACE_POKETEXT: /* write the word at location addr. */\n\tcase PTRACE_POKEDATA:\n\t\tret = generic_ptrace_pokedata(child, addr, data);\n\t\tbreak;\n\n\tcase PTRACE_POKEUSR: /* write the word at location addr in the USER area */\n\t{\n\t\tint dsize = test_tsk_thread_flag(child, TIF_IA32) ? 3 : 7;\n\t\tret = -EIO;\n\t\tif ((addr & 7) ||\n\t\t addr > sizeof(struct user) - 7)\n\t\t\tbreak;\n\n\t\tswitch (addr) { \n\t\tcase 0 ... sizeof(struct user_regs_struct) - sizeof(long):\n\t\t\tret = putreg(child, addr, data);\n\t\t\tbreak;\n\t\t/* Disallows to set a breakpoint into the vsyscall */\n\t\tcase offsetof(struct user, u_debugreg[0]):\n\t\t\tif (data >= TASK_SIZE_OF(child) - dsize) break;\n\t\t\tchild->thread.debugreg0 = data;\n\t\t\tret = 0;\n\t\t\tbreak;\n\t\tcase offsetof(struct user, u_debugreg[1]):\n\t\t\tif (data >= TASK_SIZE_OF(child) - dsize) break;\n\t\t\tchild->thread.debugreg1 = data;\n\t\t\tret = 0;\n\t\t\tbreak;\n\t\tcase offsetof(struct user, u_debugreg[2]):\n\t\t\tif (data >= TASK_SIZE_OF(child) - dsize) break;\n\t\t\tchild->thread.debugreg2 = data;\n\t\t\tret = 0;\n\t\t\tbreak;\n\t\tcase offsetof(struct user, u_debugreg[3]):\n\t\t\tif (data >= TASK_SIZE_OF(child) - dsize) break;\n\t\t\tchild->thread.debugreg3 = data;\n\t\t\tret = 0;\n\t\t\tbreak;\n\t\tcase offsetof(struct user, u_debugreg[6]):\n\t\t\t\t if (data >> 32)\n\t\t\t\tbreak; \n\t\t\tchild->thread.debugreg6 = data;\n\t\t\tret = 0;\n\t\t\tbreak;\n\t\tcase offsetof(struct user, u_debugreg[7]):\n\t\t\t/* See arch/i386/kernel/ptrace.c for an explanation of\n\t\t\t * this awkward check.*/\n\t\t\tdata &= ~DR_CONTROL_RESERVED;\n\t\t\tfor(i=0; i<4; i++)\n\t\t\t\tif ((0x5554 >> ((data >> (16 + 4*i)) & 0xf)) & 1)\n\t\t\t\t\tbreak;\n\t\t\tif (i == 4) {\n\t\t\t child->thread.debugreg7 = data;\n\t\t\t if (data)\n\t\t\t \tset_tsk_thread_flag(child, TIF_DEBUG);\n\t\t\t else\n\t\t\t \tclear_tsk_thread_flag(child, TIF_DEBUG);\n\t\t\t ret = 0;\n\t\t \t}\n\t\t break;\n\t\t}\n\t\tbreak;\n\t}\n\tcase PTRACE_SYSCALL: /* continue and stop at next (return from) syscall */\n\tcase PTRACE_CONT: /* restart after signal. */\n\n\t\tret = -EIO;\n\t\tif (!valid_signal(data))\n\t\t\tbreak;\n\t\tif (request == PTRACE_SYSCALL)\n\t\t\tset_tsk_thread_flag(child,TIF_SYSCALL_TRACE);\n\t\telse\n\t\t\tclear_tsk_thread_flag(child,TIF_SYSCALL_TRACE);\n\t\tclear_tsk_thread_flag(child, TIF_SINGLESTEP);\n\t\tchild->exit_code = data;\n\t\t/* make sure the single step bit is not set. */\n\t\tclear_singlestep(child);\n\t\twake_up_process(child);\n\t\tret = 0;\n\t\tbreak;\n\n#ifdef CONFIG_IA32_EMULATION\n\t\t/* This makes only sense with 32bit programs. Allow a\n\t\t 64bit debugger to fully examine them too. Better\n\t\t don't use it against 64bit processes, use\n\t\t PTRACE_ARCH_PRCTL instead. */\n\tcase PTRACE_SET_THREAD_AREA: {\n\t\tstruct user_desc __user *p;\n\t\tint old; \n\t\tp = (struct user_desc __user *)data;\n\t\tget_user(old, &p->entry_number); \n\t\tput_user(addr, &p->entry_number);\n\t\tret = do_set_thread_area(&child->thread, p);\n\t\tput_user(old, &p->entry_number); \n\t\tbreak;\n\tcase PTRACE_GET_THREAD_AREA:\n\t\tp = (struct user_desc __user *)data;\n\t\tget_user(old, &p->entry_number); \n\t\tput_user(addr, &p->entry_number);\n\t\tret = do_get_thread_area(&child->thread, p);\n\t\tput_user(old, &p->entry_number); \n\t\tbreak;\n\t} \n#endif\n\t\t/* normal 64bit interface to access TLS data. \n\t\t Works just like arch_prctl, except that the arguments\n\t\t are reversed. */\n\tcase PTRACE_ARCH_PRCTL: \n\t\tret = do_arch_prctl(child, data, addr);\n\t\tbreak;\n\n/*\n * make the child exit. Best I can do is send it a sigkill. \n * perhaps it should be put in the status that it wants to \n * exit.\n */\n\tcase PTRACE_KILL:\n\t\tret = 0;\n\t\tif (child->exit_state == EXIT_ZOMBIE)\t/* already dead */\n\t\t\tbreak;\n\t\tclear_tsk_thread_flag(child, TIF_SINGLESTEP);\n\t\tchild->exit_code = SIGKILL;\n\t\t/* make sure the single step bit is not set. */\n\t\tclear_singlestep(child);\n\t\twake_up_process(child);\n\t\tbreak;\n\n\tcase PTRACE_SINGLESTEP: /* set the trap flag. */\n\t\tret = -EIO;\n\t\tif (!valid_signal(data))\n\t\t\tbreak;\n\t\tclear_tsk_thread_flag(child,TIF_SYSCALL_TRACE);\n\t\tset_singlestep(child);\n\t\tchild->exit_code = data;\n\t\t/* give it a chance to run. */\n\t\twake_up_process(child);\n\t\tret = 0;\n\t\tbreak;\n\n\tcase PTRACE_DETACH:\n\t\t/* detach a process that was attached. */\n\t\tret = ptrace_detach(child, data);\n\t\tbreak;\n\n\tcase PTRACE_GETREGS: { /* Get all gp regs from the child. */\n\t \tif (!access_ok(VERIFY_WRITE, (unsigned __user *)data,\n\t\t\t sizeof(struct user_regs_struct))) {\n\t\t\tret = -EIO;\n\t\t\tbreak;\n\t\t}\n\t\tret = 0;\n\t\tfor (ui = 0; ui < sizeof(struct user_regs_struct); ui += sizeof(long)) {\n\t\t\tret |= __put_user(getreg(child, ui),(unsigned long __user *) data);\n\t\t\tdata += sizeof(long);\n\t\t}\n\t\tbreak;\n\t}\n\n\tcase PTRACE_SETREGS: { /* Set all gp regs in the child. */\n\t\tunsigned long tmp;\n\t \tif (!access_ok(VERIFY_READ, (unsigned __user *)data,\n\t\t\t sizeof(struct user_regs_struct))) {\n\t\t\tret = -EIO;\n\t\t\tbreak;\n\t\t}\n\t\tret = 0;\n\t\tfor (ui = 0; ui < sizeof(struct user_regs_struct); ui += sizeof(long)) {\n\t\t\tret = __get_user(tmp, (unsigned long __user *) data);\n\t\t\tif (ret)\n\t\t\t\tbreak;\n\t\t\tret = putreg(child, ui, tmp);\n\t\t\tif (ret)\n\t\t\t\tbreak;\n\t\t\tdata += sizeof(long);\n\t\t}\n\t\tbreak;\n\t}\n\n\tcase PTRACE_GETFPREGS: { /* Get the child extended FPU state. */\n\t\tif (!access_ok(VERIFY_WRITE, (unsigned __user *)data,\n\t\t\t sizeof(struct user_i387_struct))) {\n\t\t\tret = -EIO;\n\t\t\tbreak;\n\t\t}\n\t\tret = get_fpregs((struct user_i387_struct __user *)data, child);\n\t\tbreak;\n\t}\n\n\tcase PTRACE_SETFPREGS: { /* Set the child extended FPU state. */\n\t\tif (!access_ok(VERIFY_READ, (unsigned __user *)data,\n\t\t\t sizeof(struct user_i387_struct))) {\n\t\t\tret = -EIO;\n\t\t\tbreak;\n\t\t}\n\t\tset_stopped_child_used_math(child);\n\t\tret = set_fpregs(child, (struct user_i387_struct __user *)data);\n\t\tbreak;\n\t}\n\n\tdefault:\n\t\tret = ptrace_request(child, request, addr, data);\n\t\tbreak;\n\t}\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Handle bogus %cs selector in single-step instruction decoding\n\nThe code for LDT segment selectors was not robust in the face of a bogus\nselector set in %cs via ptrace before the single-step was done.\n\nSigned-off-by: Roland McGrath \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void clear_singlestep(struct task_struct *child)\n{\n\t/* Always clear TIF_SINGLESTEP... */\n\tclear_tsk_thread_flag(child, TIF_SINGLESTEP);\n\n\t/* But touch TF only if it was set by us.. */\n\tif (child->ptrace & PT_DTRACE) {\n\t\tstruct pt_regs *regs = get_child_regs(child);\n\t\tregs->eflags &= ~TRAP_FLAG;\n\t\tchild->ptrace &= ~PT_DTRACE;\n\t}\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 putreg(struct task_struct *child,\n\tunsigned long regno, unsigned long value)\n{\n\tunsigned long tmp; \n\t\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: static void usb_pwc_disconnect(struct usb_interface *intf)\n{\n\tstruct pwc_device *pdev;\n\tint hint;\n\n\tlock_kernel();\n\tpdev = usb_get_intfdata (intf);\n\tusb_set_intfdata (intf, NULL);\n\tif (pdev == NULL) {\n\t\tPWC_ERROR(\"pwc_disconnect() Called without private pointer.\\n\");\n\t\tgoto disconnect_out;\n\t}\n\tif (pdev->udev == NULL) {\n\t\tPWC_ERROR(\"pwc_disconnect() already called for %p\\n\", pdev);\n\t\tgoto disconnect_out;\n\t}\n\tif (pdev->udev != interface_to_usbdev(intf)) {\n\t\tPWC_ERROR(\"pwc_disconnect() Woops: pointer mismatch udev/pdev.\\n\");\n\t\tgoto disconnect_out;\n\t}\n\n\t/* We got unplugged; this is signalled by an EPIPE error code */\n\tif (pdev->vopen) {\n\t\tPWC_INFO(\"Disconnected while webcam is in use!\\n\");\n\t\tpdev->error_status = EPIPE;\n\t}\n\n\t/* Alert waiting processes */\n\twake_up_interruptible(&pdev->frameq);\n\t/* Wait until device is closed */\n\tif(pdev->vopen) {\n\t\tpdev->unplugged = 1;\n\t} else {\n\t\t/* Device is closed, so we can safely unregister it */\n\t\tPWC_DEBUG_PROBE(\"Unregistering video device in disconnect().\\n\");\n\t\tpwc_cleanup(pdev);\n\t\t/* Free memory (don't set pdev to 0 just yet) */\n\t\tkfree(pdev);\n\ndisconnect_out:\n\t\t/* search device_hint[] table if we occupy a slot, by any chance */\n\t\tfor (hint = 0; hint < MAX_DEV_HINTS; hint++)\n\t\t\tif (device_hint[hint].pdev == pdev)\n\t\t\t\tdevice_hint[hint].pdev = NULL;\n\t}\n\n\tunlock_kernel();\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_create_sysfs_files(struct video_device *vdev)\n{\n\tstruct pwc_device *pdev = video_get_drvdata(vdev);\n\tint rc;\n\n\trc = video_device_create_file(vdev, &class_device_attr_button);\n\tif (rc)\n\t\tgoto err;\n\tif (pdev->features & FEATURE_MOTOR_PANTILT) {\n\t\trc = video_device_create_file(vdev,&class_device_attr_pan_tilt);\n\t\tif (rc) goto err_button;\n\t}\n\n\treturn 0;\n\nerr_button:\n\tvideo_device_remove_file(vdev, &class_device_attr_button);\nerr:\n\treturn rc;\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 __init usb_pwc_init(void)\n{\n\tint i, sz;\n\tchar *sizenames[PSZ_MAX] = { \"sqcif\", \"qsif\", \"qcif\", \"sif\", \"cif\", \"vga\" };\n\n\tPWC_INFO(\"Philips webcam module version \" PWC_VERSION \" loaded.\\n\");\n\tPWC_INFO(\"Supports Philips PCA645/646, PCVC675/680/690, PCVC720[40]/730/740/750 & PCVC830/840.\\n\");\n\tPWC_INFO(\"Also supports the Askey VC010, various Logitech Quickcams, Samsung MPC-C10 and MPC-C30,\\n\");\n\tPWC_INFO(\"the Creative WebCam 5 & Pro Ex, SOTEC Afina Eye and Visionite VCS-UC300 and VCS-UM100.\\n\");\n\n\tif (fps) {\n\t\tif (fps < 4 || fps > 30) {\n\t\t\tPWC_ERROR(\"Framerate out of bounds (4-30).\\n\");\n\t\t\treturn -EINVAL;\n\t\t}\n\t\tdefault_fps = fps;\n\t\tPWC_DEBUG_MODULE(\"Default framerate set to %d.\\n\", default_fps);\n\t}\n\n\tif (size) {\n\t\t/* string; try matching with array */\n\t\tfor (sz = 0; sz < PSZ_MAX; sz++) {\n\t\t\tif (!strcmp(sizenames[sz], size)) { /* Found! */\n\t\t\t\tdefault_size = sz;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (sz == PSZ_MAX) {\n\t\t\tPWC_ERROR(\"Size not recognized; try size=[sqcif | qsif | qcif | sif | cif | vga].\\n\");\n\t\t\treturn -EINVAL;\n\t\t}\n\t\tPWC_DEBUG_MODULE(\"Default image size set to %s [%dx%d].\\n\", sizenames[default_size], pwc_image_sizes[default_size].x, pwc_image_sizes[default_size].y);\n\t}\n\tif (mbufs) {\n\t\tif (mbufs < 1 || mbufs > MAX_IMAGES) {\n\t\t\tPWC_ERROR(\"Illegal number of mmap() buffers; use a number between 1 and %d.\\n\", MAX_IMAGES);\n\t\t\treturn -EINVAL;\n\t\t}\n\t\tpwc_mbufs = mbufs;\n\t\tPWC_DEBUG_MODULE(\"Number of image buffers set to %d.\\n\", pwc_mbufs);\n\t}\n\tif (fbufs) {\n\t\tif (fbufs < 2 || fbufs > MAX_FRAMES) {\n\t\t\tPWC_ERROR(\"Illegal number of frame buffers; use a number between 2 and %d.\\n\", MAX_FRAMES);\n\t\t\treturn -EINVAL;\n\t\t}\n\t\tdefault_fbufs = fbufs;\n\t\tPWC_DEBUG_MODULE(\"Number of frame buffers set to %d.\\n\", default_fbufs);\n\t}\n#ifdef CONFIG_USB_PWC_DEBUG\n\tif (pwc_trace >= 0) {\n\t\tPWC_DEBUG_MODULE(\"Trace options: 0x%04x\\n\", pwc_trace);\n\t}\n#endif\n\tif (compression >= 0) {\n\t\tif (compression > 3) {\n\t\t\tPWC_ERROR(\"Invalid compression setting; use a number between 0 (uncompressed) and 3 (high).\\n\");\n\t\t\treturn -EINVAL;\n\t\t}\n\t\tpwc_preferred_compression = compression;\n\t\tPWC_DEBUG_MODULE(\"Preferred compression set to %d.\\n\", pwc_preferred_compression);\n\t}\n\tif (power_save)\n\t\tPWC_DEBUG_MODULE(\"Enabling power save on open/close.\\n\");\n\tif (leds[0] >= 0)\n\t\tled_on = leds[0];\n\tif (leds[1] >= 0)\n\t\tled_off = leds[1];\n\n\t/* Big device node whoopla. Basically, it allows you to assign a\n\t device node (/dev/videoX) to a camera, based on its type\n\t & serial number. The format is [type[.serialnumber]:]node.\n\n\t Any camera that isn't matched by these rules gets the next\n\t available free device node.\n\t */\n\tfor (i = 0; i < MAX_DEV_HINTS; i++) {\n\t\tchar *s, *colon, *dot;\n\n\t\t/* This loop also initializes the array */\n\t\tdevice_hint[i].pdev = NULL;\n\t\ts = dev_hint[i];\n\t\tif (s != NULL && *s != '\\0') {\n\t\t\tdevice_hint[i].type = -1; /* wildcard */\n\t\t\tstrcpy(device_hint[i].serial_number, \"*\");\n\n\t\t\t/* parse string: chop at ':' & '/' */\n\t\t\tcolon = dot = s;\n\t\t\twhile (*colon != '\\0' && *colon != ':')\n\t\t\t\tcolon++;\n\t\t\twhile (*dot != '\\0' && *dot != '.')\n\t\t\t\tdot++;\n\t\t\t/* Few sanity checks */\n\t\t\tif (*dot != '\\0' && dot > colon) {\n\t\t\t\tPWC_ERROR(\"Malformed camera hint: the colon must be after the dot.\\n\");\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\n\t\t\tif (*colon == '\\0') {\n\t\t\t\t/* No colon */\n\t\t\t\tif (*dot != '\\0') {\n\t\t\t\t\tPWC_ERROR(\"Malformed camera hint: no colon + device node given.\\n\");\n\t\t\t\t\treturn -EINVAL;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t/* No type or serial number specified, just a number. */\n\t\t\t\t\tdevice_hint[i].device_node = pwc_atoi(s);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t/* There's a colon, so we have at least a type and a device node */\n\t\t\t\tdevice_hint[i].type = pwc_atoi(s);\n\t\t\t\tdevice_hint[i].device_node = pwc_atoi(colon + 1);\n\t\t\t\tif (*dot != '\\0') {\n\t\t\t\t\t/* There's a serial number as well */\n\t\t\t\t\tint k;\n\n\t\t\t\t\tdot++;\n\t\t\t\t\tk = 0;\n\t\t\t\t\twhile (*dot != ':' && k < 29) {\n\t\t\t\t\t\tdevice_hint[i].serial_number[k++] = *dot;\n\t\t\t\t\t\tdot++;\n\t\t\t\t\t}\n\t\t\t\t\tdevice_hint[i].serial_number[k] = '\\0';\n\t\t\t\t}\n\t\t\t}\n\t\t\tPWC_TRACE(\"device_hint[%d]:\\n\", i);\n\t\t\tPWC_TRACE(\" type : %d\\n\", device_hint[i].type);\n\t\t\tPWC_TRACE(\" serial# : %s\\n\", device_hint[i].serial_number);\n\t\t\tPWC_TRACE(\" node : %d\\n\", device_hint[i].device_node);\n\t\t}\n\t\telse\n\t\t\tdevice_hint[i].type = 0; /* not filled */\n\t} /* ..for MAX_DEV_HINTS */\n\n\tPWC_DEBUG_PROBE(\"Registering driver at address 0x%p.\\n\", &pwc_driver);\n\treturn usb_register(&pwc_driver);\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 __init htab_initialize(void)\n{\n\tunsigned long table;\n\tunsigned long pteg_count;\n\tunsigned long mode_rw;\n\tunsigned long base = 0, size = 0;\n\tint i;\n\n\textern unsigned long tce_alloc_start, tce_alloc_end;\n\n\tDBG(\" -> htab_initialize()\\n\");\n\n\t/* Initialize page sizes */\n\thtab_init_page_sizes();\n\n\t/*\n\t * Calculate the required size of the htab. We want the number of\n\t * PTEGs to equal one half the number of real pages.\n\t */ \n\thtab_size_bytes = htab_get_table_size();\n\tpteg_count = htab_size_bytes >> 7;\n\n\thtab_hash_mask = pteg_count - 1;\n\n\tif (firmware_has_feature(FW_FEATURE_LPAR)) {\n\t\t/* Using a hypervisor which owns the htab */\n\t\thtab_address = NULL;\n\t\t_SDR1 = 0; \n\t} else {\n\t\t/* Find storage for the HPT. Must be contiguous in\n\t\t * the absolute address space.\n\t\t */\n\t\ttable = lmb_alloc(htab_size_bytes, htab_size_bytes);\n\n\t\tDBG(\"Hash table allocated at %lx, size: %lx\\n\", table,\n\t\t htab_size_bytes);\n\n\t\thtab_address = abs_to_virt(table);\n\n\t\t/* htab absolute addr + encoded htabsize */\n\t\t_SDR1 = table + __ilog2(pteg_count) - 11;\n\n\t\t/* Initialize the HPT with no entries */\n\t\tmemset((void *)table, 0, htab_size_bytes);\n\n\t\t/* Set SDR1 */\n\t\tmtspr(SPRN_SDR1, _SDR1);\n\t}\n\n\tmode_rw = _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_COHERENT | PP_RWXX;\n\n\t/* On U3 based machines, we need to reserve the DART area and\n\t * _NOT_ map it to avoid cache paradoxes as it's remapped non\n\t * cacheable later on\n\t */\n\n\t/* create bolted the linear mapping in the hash table */\n\tfor (i=0; i < lmb.memory.cnt; i++) {\n\t\tbase = (unsigned long)__va(lmb.memory.region[i].base);\n\t\tsize = lmb.memory.region[i].size;\n\n\t\tDBG(\"creating mapping for region: %lx : %lx\\n\", base, size);\n\n#ifdef CONFIG_U3_DART\n\t\t/* Do not map the DART space. Fortunately, it will be aligned\n\t\t * in such a way that it will not cross two lmb regions and\n\t\t * will fit within a single 16Mb page.\n\t\t * The DART space is assumed to be a full 16Mb region even if\n\t\t * we only use 2Mb of that space. We will use more of it later\n\t\t * for AGP GART. We have to use a full 16Mb large page.\n\t\t */\n\t\tDBG(\"DART base: %lx\\n\", dart_tablebase);\n\n\t\tif (dart_tablebase != 0 && dart_tablebase >= base\n\t\t && dart_tablebase < (base + size)) {\n\t\t\tunsigned long dart_table_end = dart_tablebase + 16 * MB;\n\t\t\tif (base != dart_tablebase)\n\t\t\t\tBUG_ON(htab_bolt_mapping(base, dart_tablebase,\n\t\t\t\t\t\t\t__pa(base), mode_rw,\n\t\t\t\t\t\t\tmmu_linear_psize));\n\t\t\tif ((base + size) > dart_table_end)\n\t\t\t\tBUG_ON(htab_bolt_mapping(dart_tablebase+16*MB,\n\t\t\t\t\t\t\tbase + size,\n\t\t\t\t\t\t\t__pa(dart_table_end),\n\t\t\t\t\t\t\t mode_rw,\n\t\t\t\t\t\t\t mmu_linear_psize));\n\t\t\tcontinue;\n\t\t}\n#endif /* CONFIG_U3_DART */\n\t\tBUG_ON(htab_bolt_mapping(base, base + size, __pa(base),\n\t\t\t\t\tmode_rw, mmu_linear_psize));\n }\n\n\t/*\n\t * If we have a memory_limit and we've allocated TCEs then we need to\n\t * explicitly map the TCE area at the top of RAM. We also cope with the\n\t * case that the TCEs start below memory_limit.\n\t * tce_alloc_start/end are 16MB aligned so the mapping should work\n\t * for either 4K or 16MB pages.\n\t */\n\tif (tce_alloc_start) {\n\t\ttce_alloc_start = (unsigned long)__va(tce_alloc_start);\n\t\ttce_alloc_end = (unsigned long)__va(tce_alloc_end);\n\n\t\tif (base + size >= tce_alloc_start)\n\t\t\ttce_alloc_start = base + size + 1;\n\n\t\tBUG_ON(htab_bolt_mapping(tce_alloc_start, tce_alloc_end,\n\t\t\t\t\t __pa(tce_alloc_start), mode_rw,\n\t\t\t\t\t mmu_linear_psize));\n\t}\n\n\thtab_finish_init();\n\n\tDBG(\" <- htab_initialize()\\n\");\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 void __init htab_finish_init(void)\n{\n\textern unsigned int *htab_call_hpte_insert1;\n\textern unsigned int *htab_call_hpte_insert2;\n\textern unsigned int *htab_call_hpte_remove;\n\textern unsigned int *htab_call_hpte_updatepp;\n\n#ifdef CONFIG_PPC_64K_PAGES\n\textern unsigned int *ht64_call_hpte_insert1;\n\textern unsigned int *ht64_call_hpte_insert2;\n\textern unsigned int *ht64_call_hpte_remove;\n\textern unsigned int *ht64_call_hpte_updatepp;\n\n\tmake_bl(ht64_call_hpte_insert1, ppc_md.hpte_insert);\n\tmake_bl(ht64_call_hpte_insert2, ppc_md.hpte_insert);\n\tmake_bl(ht64_call_hpte_remove, ppc_md.hpte_remove);\n\tmake_bl(ht64_call_hpte_updatepp, ppc_md.hpte_updatepp);\n#endif /* CONFIG_PPC_64K_PAGES */\n\n\tmake_bl(htab_call_hpte_insert1, ppc_md.hpte_insert);\n\tmake_bl(htab_call_hpte_insert2, ppc_md.hpte_insert);\n\tmake_bl(htab_call_hpte_remove, ppc_md.hpte_remove);\n\tmake_bl(htab_call_hpte_updatepp, ppc_md.hpte_updatepp);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': '[POWERPC] Allow drivers to map individual 4k pages to userspace\n\nSome drivers have resources that they want to be able to map into\nuserspace that are 4k in size. On a kernel configured with 64k pages\nwe currently end up mapping the 4k we want plus another 60k of\nphysical address space, which could contain anything. This can\nintroduce security problems, for example in the case of an infiniband\nadaptor where the other 60k could contain registers that some other\nprogram is using for its communications.\n\nThis patch adds a new function, remap_4k_pfn, which drivers can use to\nmap a single 4k page to userspace regardless of whether the kernel is\nusing a 4k or a 64k page size. Like remap_pfn_range, it would\ntypically be called in a driver's mmap function. It only maps a\nsingle 4k page, which on a 64k page kernel appears replicated 16 times\nthroughout a 64k page. On a 4k page kernel it reduces to a call to\nremap_pfn_range.\n\nThe way this works on a 64k kernel is that a new bit, _PAGE_4K_PFN,\ngets set on the linux PTE. This alters the way that __hash_page_4K\ncomputes the real address to put in the HPTE. The RPN field of the\nlinux PTE becomes the 4k RPN directly rather than being interpreted as\na 64k RPN. Since the RPN field is 32 bits, this means that physical\naddresses being mapped with remap_4k_pfn have to be below 2^44,\ni.e. 0x100000000000.\n\nThe patch also factors out the code in arch/powerpc/mm/hash_utils_64.c\nthat deals with demoting a process to use 4k pages into one function\nthat gets called in the various different places where we need to do\nthat. There were some discrepancies between exactly what was done in\nthe various places, such as a call to spu_flush_all_slbs in one case\nbut not in others.\n\nSigned-off-by: Paul Mackerras '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ieee80211_handle_assoc_resp(struct ieee80211_device *ieee, struct ieee80211_assoc_response\n\t\t\t\t *frame, struct ieee80211_rx_stats *stats)\n{\n\tstruct ieee80211_network network_resp = {\n\t\t.ibss_dfs = NULL,\n\t};\n\tstruct ieee80211_network *network = &network_resp;\n\tstruct net_device *dev = ieee->dev;\n\n\tnetwork->flags = 0;\n\tnetwork->qos_data.active = 0;\n\tnetwork->qos_data.supported = 0;\n\tnetwork->qos_data.param_count = 0;\n\tnetwork->qos_data.old_param_count = 0;\n\n\t//network->atim_window = le16_to_cpu(frame->aid) & (0x3FFF);\n\tnetwork->atim_window = le16_to_cpu(frame->aid);\n\tnetwork->listen_interval = le16_to_cpu(frame->status);\n\tmemcpy(network->bssid, frame->header.addr3, ETH_ALEN);\n\tnetwork->capability = le16_to_cpu(frame->capability);\n\tnetwork->last_scanned = jiffies;\n\tnetwork->rates_len = network->rates_ex_len = 0;\n\tnetwork->last_associate = 0;\n\tnetwork->ssid_len = 0;\n\tnetwork->erp_value =\n\t (network->capability & WLAN_CAPABILITY_IBSS) ? 0x3 : 0x0;\n\n\tif (stats->freq == IEEE80211_52GHZ_BAND) {\n\t\t/* for A band (No DS info) */\n\t\tnetwork->channel = stats->received_channel;\n\t} else\n\t\tnetwork->flags |= NETWORK_HAS_CCK;\n\n\tnetwork->wpa_ie_len = 0;\n\tnetwork->rsn_ie_len = 0;\n\n\tif (ieee80211_parse_info_param\n\t (frame->info_element, stats->len - sizeof(*frame), network))\n\t\treturn 1;\n\n\tnetwork->mode = 0;\n\tif (stats->freq == IEEE80211_52GHZ_BAND)\n\t\tnetwork->mode = IEEE_A;\n\telse {\n\t\tif (network->flags & NETWORK_HAS_OFDM)\n\t\t\tnetwork->mode |= IEEE_G;\n\t\tif (network->flags & NETWORK_HAS_CCK)\n\t\t\tnetwork->mode |= IEEE_B;\n\t}\n\n\tif (ieee80211_is_empty_essid(network->ssid, network->ssid_len))\n\t\tnetwork->flags |= NETWORK_EMPTY_ESSID;\n\n\tmemcpy(&network->stats, stats, sizeof(network->stats));\n\n\tif (ieee->handle_assoc_response != NULL)\n\t\tieee->handle_assoc_response(dev, frame, network);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': '[IEEE80211]: avoid integer underflow for runt rx frames\n\nReported by Chris Evans :\n\n> The summary is that an evil 80211 frame can crash out a victim's\n> machine. It only applies to drivers using the 80211 wireless code, and\n> only then to certain drivers (and even then depends on a card's\n> firmware not dropping a dubious packet). I must confess I'm not\n> keeping track of Linux wireless support, and the different protocol\n> stacks etc.\n>\n> Details are as follows:\n>\n> ieee80211_rx() does not explicitly check that \"skb->len >= hdrlen\".\n> There are other skb->len checks, but not enough to prevent a subtle\n> off-by-two error if the frame has the IEEE80211_STYPE_QOS_DATA flag\n> set.\n>\n> This leads to integer underflow and crash here:\n>\n> if (frag != 0)\n> flen -= hdrlen;\n>\n> (flen is subsequently used as a memcpy length parameter).\n\nHow about this?\n\nSigned-off-by: John W. Linville \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ieee80211_parse_qos_info_param_IE(struct ieee80211_info_element\n\t\t\t\t\t *info_element,\n\t\t\t\t\t struct ieee80211_network *network)\n{\n\tint rc = 0;\n\tstruct ieee80211_qos_parameters *qos_param = NULL;\n\tstruct ieee80211_qos_information_element qos_info_element;\n\n\trc = ieee80211_read_qos_info_element(&qos_info_element, info_element);\n\n\tif (rc == 0) {\n\t\tnetwork->qos_data.param_count = qos_info_element.ac_info & 0x0F;\n\t\tnetwork->flags |= NETWORK_HAS_QOS_INFORMATION;\n\t} else {\n\t\tstruct ieee80211_qos_parameter_info param_element;\n\n\t\trc = ieee80211_read_qos_param_element(¶m_element,\n\t\t\t\t\t\t info_element);\n\t\tif (rc == 0) {\n\t\t\tqos_param = &(network->qos_data.parameters);\n\t\t\tieee80211_qos_convert_ac_to_parameters(¶m_element,\n\t\t\t\t\t\t\t qos_param);\n\t\t\tnetwork->flags |= NETWORK_HAS_QOS_PARAMETERS;\n\t\t\tnetwork->qos_data.param_count =\n\t\t\t param_element.info_element.ac_info & 0x0F;\n\t\t}\n\t}\n\n\tif (rc == 0) {\n\t\tIEEE80211_DEBUG_QOS(\"QoS is supported\\n\");\n\t\tnetwork->qos_data.supported = 1;\n\t}\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': '[IEEE80211]: avoid integer underflow for runt rx frames\n\nReported by Chris Evans :\n\n> The summary is that an evil 80211 frame can crash out a victim's\n> machine. It only applies to drivers using the 80211 wireless code, and\n> only then to certain drivers (and even then depends on a card's\n> firmware not dropping a dubious packet). I must confess I'm not\n> keeping track of Linux wireless support, and the different protocol\n> stacks etc.\n>\n> Details are as follows:\n>\n> ieee80211_rx() does not explicitly check that \"skb->len >= hdrlen\".\n> There are other skb->len checks, but not enough to prevent a subtle\n> off-by-two error if the frame has the IEEE80211_STYPE_QOS_DATA flag\n> set.\n>\n> This leads to integer underflow and crash here:\n>\n> if (frag != 0)\n> flen -= hdrlen;\n>\n> (flen is subsequently used as a memcpy length parameter).\n\nHow about this?\n\nSigned-off-by: John W. Linville \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: isdn_net_getpeer(isdn_net_ioctl_phone *phone, isdn_net_ioctl_phone __user *peer)\n{\n\tisdn_net_dev *p = isdn_net_findif(phone->name);\n\tint ch, dv, idx;\n\n\tif (!p)\n\t\treturn -ENODEV;\n\t/*\n\t * Theoretical race: while this executes, the remote number might\n\t * become invalid (hang up) or change (new connection), resulting\n * in (partially) wrong number copied to user. This race\n\t * currently ignored.\n\t */\n\tch = p->local->isdn_channel;\n\tdv = p->local->isdn_device;\n\tif(ch < 0 && dv < 0)\n\t\treturn -ENOTCONN;\n\tidx = isdn_dc2minor(dv, ch);\n\tif (idx <0 )\n\t\treturn -ENODEV;\n\t/* for pre-bound channels, we need this extra check */\n\tif (strncmp(dev->num[idx], \"???\", 3) == 0)\n\t\treturn -ENOTCONN;\n\tstrncpy(phone->phone, dev->num[idx], ISDN_MSNLEN);\n\tphone->outgoing = USG_OUTGOING(dev->usage[idx]);\n\tif (copy_to_user(peer, phone, sizeof(*peer)))\n\t\treturn -EFAULT;\n\treturn 0;\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_rcv_skb(int idx, struct sk_buff *skb)\n{\n\tisdn_net_dev *p = dev->rx_netdev[idx];\n\n\tif (p) {\n\t\tisdn_net_local *lp = p->local;\n\t\tif ((lp->flags & ISDN_NET_CONNECTED) &&\n\t\t (!lp->dialstate)) {\n\t\t\tisdn_net_receive(p->dev, skb);\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-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 void _isdn_setup(struct net_device *dev)\n{\n\tisdn_net_local *lp = dev->priv;\n\n\tdev->flags = IFF_NOARP | IFF_POINTOPOINT;\n\tlp->p_encap = ISDN_NET_ENCAP_RAWIP;\n\tlp->magic = ISDN_NET_MAGIC;\n\tlp->last = lp;\n\tlp->next = lp;\n\tlp->isdn_device = -1;\n\tlp->isdn_channel = -1;\n\tlp->pre_device = -1;\n\tlp->pre_channel = -1;\n\tlp->exclusive = -1;\n\tlp->ppp_slot = -1;\n\tlp->pppbind = -1;\n\tskb_queue_head_init(&lp->super_tx_queue);\n\tlp->l2_proto = ISDN_PROTO_L2_X75I;\n\tlp->l3_proto = ISDN_PROTO_L3_TRANS;\n\tlp->triggercps = 6000;\n\tlp->slavedelay = 10 * HZ;\n\tlp->hupflags = ISDN_INHUP;\t/* Do hangup even on incoming calls */\n\tlp->onhtime = 10;\t/* Default hangup-time for saving costs */\n\tlp->dialmax = 1;\n\t/* Hangup before Callback, manual dial */\n\tlp->flags = ISDN_NET_CBHUP | ISDN_NET_DM_MANUAL;\n\tlp->cbdelay = 25;\t/* Wait 5 secs before Callback */\n\tlp->dialtimeout = -1; /* Infinite Dial-Timeout */\n\tlp->dialwait = 5 * HZ; /* Wait 5 sec. after failed dial */\n\tlp->dialstarted = 0; /* Jiffies of last dial-start */\n\tlp->dialwait_timer = 0; /* Jiffies of earliest next dial-start */\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_setcfg(isdn_net_ioctl_cfg * cfg)\n{\n\tisdn_net_dev *p = isdn_net_findif(cfg->name);\n\tulong features;\n\tint i;\n\tint drvidx;\n\tint chidx;\n\tchar drvid[25];\n\n\tif (p) {\n\t\tisdn_net_local *lp = p->local;\n\n\t\t/* See if any registered driver supports the features we want */\n\t\tfeatures = ((1 << cfg->l2_proto) << ISDN_FEATURE_L2_SHIFT) |\n\t\t\t((1 << cfg->l3_proto) << ISDN_FEATURE_L3_SHIFT);\n\t\tfor (i = 0; i < ISDN_MAX_DRIVERS; i++)\n\t\t\tif (dev->drv[i])\n\t\t\t\tif ((dev->drv[i]->interface->features & features) == features)\n\t\t\t\t\tbreak;\n\t\tif (i == ISDN_MAX_DRIVERS) {\n\t\t\tprintk(KERN_WARNING \"isdn_net: No driver with selected features\\n\");\n\t\t\treturn -ENODEV;\n\t\t}\n\t\tif (lp->p_encap != cfg->p_encap){\n#ifdef CONFIG_ISDN_X25\n\t\t\tstruct concap_proto * cprot = p -> cprot;\n#endif\n\t\t\tif (isdn_net_device_started(p)) {\n\t\t\t\tprintk(KERN_WARNING \"%s: cannot change encap when if is up\\n\",\n\t\t\t\t p->dev->name);\n\t\t\t\treturn -EBUSY;\n\t\t\t}\n#ifdef CONFIG_ISDN_X25\n\t\t\tif( cprot && cprot -> pops )\n\t\t\t\tcprot -> pops -> proto_del ( cprot );\n\t\t\tp -> cprot = NULL;\n\t\t\tlp -> dops = NULL;\n\t\t\t/* ... , prepare for configuration of new one ... */\n\t\t\tswitch ( cfg -> p_encap ){\n\t\t\tcase ISDN_NET_ENCAP_X25IFACE:\n\t\t\t\tlp -> dops = &isdn_concap_reliable_dl_dops;\n\t\t\t}\n\t\t\t/* ... and allocate new one ... */\n\t\t\tp -> cprot = isdn_concap_new( cfg -> p_encap );\n\t\t\t/* p -> cprot == NULL now if p_encap is not supported\n\t\t\t by means of the concap_proto mechanism */\n\t\t\t/* the protocol is not configured yet; this will\n\t\t\t happen later when isdn_net_reset() is called */\n#endif\n\t\t}\n\t\tswitch ( cfg->p_encap ) {\n\t\tcase ISDN_NET_ENCAP_SYNCPPP:\n#ifndef CONFIG_ISDN_PPP\n\t\t\tprintk(KERN_WARNING \"%s: SyncPPP support not configured\\n\",\n\t\t\t p->dev->name);\n\t\t\treturn -EINVAL;\n#else\n\t\t\tp->dev->type = ARPHRD_PPP;\t/* change ARP type */\n\t\t\tp->dev->addr_len = 0;\n\t\t\tp->dev->do_ioctl = isdn_ppp_dev_ioctl;\n#endif\n\t\t\tbreak;\n\t\tcase ISDN_NET_ENCAP_X25IFACE:\n#ifndef CONFIG_ISDN_X25\n\t\t\tprintk(KERN_WARNING \"%s: isdn-x25 support not configured\\n\",\n\t\t\t p->dev->name);\n\t\t\treturn -EINVAL;\n#else\n\t\t\tp->dev->type = ARPHRD_X25;\t/* change ARP type */\n\t\t\tp->dev->addr_len = 0;\n#endif\n\t\t\tbreak;\n\t\tcase ISDN_NET_ENCAP_CISCOHDLCK:\n\t\t\tp->dev->do_ioctl = isdn_ciscohdlck_dev_ioctl;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif( cfg->p_encap >= 0 &&\n\t\t\t cfg->p_encap <= ISDN_NET_ENCAP_MAX_ENCAP )\n\t\t\t\tbreak;\n\t\t\tprintk(KERN_WARNING\n\t\t\t \"%s: encapsulation protocol %d not supported\\n\",\n\t\t\t p->dev->name, cfg->p_encap);\n\t\t\treturn -EINVAL;\n\t\t}\n\t\tif (strlen(cfg->drvid)) {\n\t\t\t/* A bind has been requested ... */\n\t\t\tchar *c,\n\t\t\t*e;\n\n\t\t\tdrvidx = -1;\n\t\t\tchidx = -1;\n\t\t\tstrcpy(drvid, cfg->drvid);\n\t\t\tif ((c = strchr(drvid, ','))) {\n\t\t\t\t/* The channel-number is appended to the driver-Id with a comma */\n\t\t\t\tchidx = (int) simple_strtoul(c + 1, &e, 10);\n\t\t\t\tif (e == c)\n\t\t\t\t\tchidx = -1;\n\t\t\t\t*c = '\\0';\n\t\t\t}\n\t\t\tfor (i = 0; i < ISDN_MAX_DRIVERS; i++)\n\t\t\t\t/* Lookup driver-Id in array */\n\t\t\t\tif (!(strcmp(dev->drvid[i], drvid))) {\n\t\t\t\t\tdrvidx = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\tif ((drvidx == -1) || (chidx == -1))\n\t\t\t\t/* Either driver-Id or channel-number invalid */\n\t\t\t\treturn -ENODEV;\n\t\t} else {\n\t\t\t/* Parameters are valid, so get them */\n\t\t\tdrvidx = lp->pre_device;\n\t\t\tchidx = lp->pre_channel;\n\t\t}\n\t\tif (cfg->exclusive > 0) {\n\t\t\tunsigned long flags;\n\n\t\t\t/* If binding is exclusive, try to grab the channel */\n\t\t\tspin_lock_irqsave(&dev->lock, flags);\n\t\t\tif ((i = isdn_get_free_channel(ISDN_USAGE_NET,\n\t\t\t\tlp->l2_proto, lp->l3_proto, drvidx,\n\t\t\t\tchidx, lp->msn)) < 0) {\n\t\t\t\t/* Grab failed, because desired channel is in use */\n\t\t\t\tlp->exclusive = -1;\n\t\t\t\tspin_unlock_irqrestore(&dev->lock, flags);\n\t\t\t\treturn -EBUSY;\n\t\t\t}\n\t\t\t/* All went ok, so update isdninfo */\n\t\t\tdev->usage[i] = ISDN_USAGE_EXCLUSIVE;\n\t\t\tisdn_info_update();\n\t\t\tspin_unlock_irqrestore(&dev->lock, flags);\n\t\t\tlp->exclusive = i;\n\t\t} else {\n\t\t\t/* Non-exclusive binding or unbind. */\n\t\t\tlp->exclusive = -1;\n\t\t\tif ((lp->pre_device != -1) && (cfg->exclusive == -1)) {\n\t\t\t\tisdn_unexclusive_channel(lp->pre_device, lp->pre_channel);\n\t\t\t\tisdn_free_channel(lp->pre_device, lp->pre_channel, ISDN_USAGE_NET);\n\t\t\t\tdrvidx = -1;\n\t\t\t\tchidx = -1;\n\t\t\t}\n\t\t}\n\t\tstrlcpy(lp->msn, cfg->eaz, sizeof(lp->msn));\n\t\tlp->pre_device = drvidx;\n\t\tlp->pre_channel = chidx;\n\t\tlp->onhtime = cfg->onhtime;\n\t\tlp->charge = cfg->charge;\n\t\tlp->l2_proto = cfg->l2_proto;\n\t\tlp->l3_proto = cfg->l3_proto;\n\t\tlp->cbdelay = cfg->cbdelay;\n\t\tlp->dialmax = cfg->dialmax;\n\t\tlp->triggercps = cfg->triggercps;\n\t\tlp->slavedelay = cfg->slavedelay * HZ;\n\t\tlp->pppbind = cfg->pppbind;\n\t\tlp->dialtimeout = cfg->dialtimeout >= 0 ? cfg->dialtimeout * HZ : -1;\n\t\tlp->dialwait = cfg->dialwait * HZ;\n\t\tif (cfg->secure)\n\t\t\tlp->flags |= ISDN_NET_SECURE;\n\t\telse\n\t\t\tlp->flags &= ~ISDN_NET_SECURE;\n\t\tif (cfg->cbhup)\n\t\t\tlp->flags |= ISDN_NET_CBHUP;\n\t\telse\n\t\t\tlp->flags &= ~ISDN_NET_CBHUP;\n\t\tswitch (cfg->callback) {\n\t\t\tcase 0:\n\t\t\t\tlp->flags &= ~(ISDN_NET_CALLBACK | ISDN_NET_CBOUT);\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tlp->flags |= ISDN_NET_CALLBACK;\n\t\t\t\tlp->flags &= ~ISDN_NET_CBOUT;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tlp->flags |= ISDN_NET_CBOUT;\n\t\t\t\tlp->flags &= ~ISDN_NET_CALLBACK;\n\t\t\t\tbreak;\n\t\t}\n\t\tlp->flags &= ~ISDN_NET_DIALMODE_MASK;\t/* first all bits off */\n\t\tif (cfg->dialmode && !(cfg->dialmode & ISDN_NET_DIALMODE_MASK)) {\n\t\t\t/* old isdnctrl version, where only 0 or 1 is given */\n\t\t\tprintk(KERN_WARNING\n\t\t\t \"Old isdnctrl version detected! Please update.\\n\");\n\t\t\tlp->flags |= ISDN_NET_DM_OFF; /* turn on `off' bit */\n\t\t}\n\t\telse {\n\t\t\tlp->flags |= cfg->dialmode; /* turn on selected bits */\n\t\t}\n\t\tif (cfg->chargehup)\n\t\t\tlp->hupflags |= ISDN_CHARGEHUP;\n\t\telse\n\t\t\tlp->hupflags &= ~ISDN_CHARGEHUP;\n\t\tif (cfg->ihup)\n\t\t\tlp->hupflags |= ISDN_INHUP;\n\t\telse\n\t\t\tlp->hupflags &= ~ISDN_INHUP;\n\t\tif (cfg->chargeint > 10) {\n\t\t\tlp->hupflags |= ISDN_CHARGEHUP | ISDN_HAVECHARGE | ISDN_MANCHARGE;\n\t\t\tlp->chargeint = cfg->chargeint * HZ;\n\t\t}\n\t\tif (cfg->p_encap != lp->p_encap) {\n\t\t\tif (cfg->p_encap == ISDN_NET_ENCAP_RAWIP) {\n\t\t\t\tp->dev->header_ops = NULL;\n\t\t\t\tp->dev->flags = IFF_NOARP|IFF_POINTOPOINT;\n\t\t\t} else {\n\t\t\t\tp->dev->header_ops = &isdn_header_ops;\n\t\t\t\tif (cfg->p_encap == ISDN_NET_ENCAP_ETHER)\n\t\t\t\t\tp->dev->flags = IFF_BROADCAST | IFF_MULTICAST;\n\t\t\t\telse\n\t\t\t\t\tp->dev->flags = IFF_NOARP|IFF_POINTOPOINT;\n\t\t\t}\n\t\t}\n\t\tlp->p_encap = cfg->p_encap;\n\t\treturn 0;\n\t}\n\treturn -ENODEV;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'isdn: avoid copying overly-long strings\n\nAddresses http://bugzilla.kernel.org/show_bug.cgi?id=9416\n\nSigned-off-by: Karsten Keil \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: isdn_net_findif(char *name)\n{\n\tisdn_net_dev *p = dev->netdev;\n\n\twhile (p) {\n\t\tif (!strcmp(p->dev->name, name))\n\t\t\treturn p;\n\t\tp = (isdn_net_dev *) p->next;\n\t}\n\treturn (isdn_net_dev *) NULL;\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_hangup(char *name)\n{\n\tisdn_net_dev *p = isdn_net_findif(name);\n\tstruct net_device *q;\n\n\tif (p) {\n\t\tif (p->local->isdn_device < 0)\n\t\t\treturn 1;\n\t\tq = p->local->slave;\n\t\t/* If this interface has slaves, do a hangup for them also. */\n\t\twhile (q) {\n\t\t\tisdn_net_hangup(q);\n\t\t\tq = (((isdn_net_local *) q->priv)->slave);\n\t\t}\n\t\tisdn_net_hangup(p->dev);\n\t\treturn 0;\n\t}\n\treturn -ENODEV;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'isdn: avoid copying overly-long strings\n\nAddresses http://bugzilla.kernel.org/show_bug.cgi?id=9416\n\nSigned-off-by: Karsten Keil \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int esp6_init_state(struct xfrm_state *x)\n{\n\tstruct esp_data *esp;\n\tstruct crypto_aead *aead;\n\tu32 align;\n\tint err;\n\n\tif (x->encap)\n\t\treturn -EINVAL;\n\n\tesp = kzalloc(sizeof(*esp), GFP_KERNEL);\n\tif (esp == NULL)\n\t\treturn -ENOMEM;\n\n\tx->data = esp;\n\n\tif (x->aead)\n\t\terr = esp_init_aead(x);\n\telse\n\t\terr = esp_init_authenc(x);\n\n\tif (err)\n\t\tgoto error;\n\n\taead = esp->aead;\n\n\tesp->padlen = 0;\n\n\tx->props.header_len = sizeof(struct ip_esp_hdr) +\n\t\t\t crypto_aead_ivsize(aead);\n\tswitch (x->props.mode) {\n\tcase XFRM_MODE_BEET:\n\tcase XFRM_MODE_TRANSPORT:\n\t\tbreak;\n\tcase XFRM_MODE_TUNNEL:\n\t\tx->props.header_len += sizeof(struct ipv6hdr);\n\t\tbreak;\n\tdefault:\n\t\tgoto error;\n\t}\n\n\talign = ALIGN(crypto_aead_blocksize(aead), 4);\n\tif (esp->padlen)\n\t\talign = max_t(u32, align, esp->padlen);\n\tx->props.trailer_len = align + 1 + crypto_aead_authsize(esp->aead);\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 void *esp_alloc_tmp(struct crypto_aead *aead, int nfrags)\n{\n\tunsigned int len;\n\n\tlen = crypto_aead_ivsize(aead);\n\tif (len) {\n\t\tlen += crypto_aead_alignmask(aead) &\n\t\t ~(crypto_tfm_ctx_alignment() - 1);\n\t\tlen = ALIGN(len, crypto_tfm_ctx_alignment());\n\t}\n\n\tlen += sizeof(struct aead_givcrypt_request) + crypto_aead_reqsize(aead);\n\tlen = ALIGN(len, __alignof__(struct scatterlist));\n\n\tlen += sizeof(struct scatterlist) * nfrags;\n\n\treturn kmalloc(len, GFP_ATOMIC);\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 aead_request *esp_tmp_req(struct crypto_aead *aead, u8 *iv)\n{\n\tstruct aead_request *req;\n\n\treq = (void *)PTR_ALIGN(iv + crypto_aead_ivsize(aead),\n\t\t\t\tcrypto_tfm_ctx_alignment());\n\taead_request_set_tfm(req, aead);\n\treturn req;\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_statstr(void)\n{\n\tstatic char istatbuf[2048];\n\tchar *p;\n\tint i;\n\n\tsprintf(istatbuf, \"idmap:\\t\");\n\tp = istatbuf + strlen(istatbuf);\n\tfor (i = 0; i < ISDN_MAX_CHANNELS; i++) {\n\t\tsprintf(p, \"%s \", (dev->drvmap[i] < 0) ? \"-\" : dev->drvid[dev->drvmap[i]]);\n\t\tp = istatbuf + strlen(istatbuf);\n\t}\n\tsprintf(p, \"\\nchmap:\\t\");\n\tp = istatbuf + strlen(istatbuf);\n\tfor (i = 0; i < ISDN_MAX_CHANNELS; i++) {\n\t\tsprintf(p, \"%d \", dev->chanmap[i]);\n\t\tp = istatbuf + strlen(istatbuf);\n\t}\n\tsprintf(p, \"\\ndrmap:\\t\");\n\tp = istatbuf + strlen(istatbuf);\n\tfor (i = 0; i < ISDN_MAX_CHANNELS; i++) {\n\t\tsprintf(p, \"%d \", dev->drvmap[i]);\n\t\tp = istatbuf + strlen(istatbuf);\n\t}\n\tsprintf(p, \"\\nusage:\\t\");\n\tp = istatbuf + strlen(istatbuf);\n\tfor (i = 0; i < ISDN_MAX_CHANNELS; i++) {\n\t\tsprintf(p, \"%d \", dev->usage[i]);\n\t\tp = istatbuf + strlen(istatbuf);\n\t}\n\tsprintf(p, \"\\nflags:\\t\");\n\tp = istatbuf + strlen(istatbuf);\n\tfor (i = 0; i < ISDN_MAX_DRIVERS; i++) {\n\t\tif (dev->drv[i]) {\n\t\t\tsprintf(p, \"%ld \", dev->drv[i]->online);\n\t\t\tp = istatbuf + strlen(istatbuf);\n\t\t} else {\n\t\t\tsprintf(p, \"? \");\n\t\t\tp = istatbuf + strlen(istatbuf);\n\t\t}\n\t}\n\tsprintf(p, \"\\nphone:\\t\");\n\tp = istatbuf + strlen(istatbuf);\n\tfor (i = 0; i < ISDN_MAX_CHANNELS; i++) {\n\t\tsprintf(p, \"%s \", dev->num[i]);\n\t\tp = istatbuf + strlen(istatbuf);\n\t}\n\tsprintf(p, \"\\n\");\n\treturn istatbuf;\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_star(char *s, char *p)\n{\n\twhile (isdn_wildmat(s, p)) {\n\t\tif (*++s == '\\0')\n\t\t\treturn (2);\n\t}\n\treturn (0);\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_minor2drv(int minor)\n{\n\treturn (dev->drvmap[minor]);\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_command(isdn_ctrl *cmd)\n{\n\tif (cmd->driver == -1) {\n\t\tprintk(KERN_WARNING \"isdn_command command(%x) driver -1\\n\", cmd->command);\n\t\treturn(1);\n\t}\n\tif (!dev->drv[cmd->driver]) {\n\t\tprintk(KERN_WARNING \"isdn_command command(%x) dev->drv[%d] NULL\\n\",\n\t\t\tcmd->command, cmd->driver);\n\t\treturn(1);\n\t}\n\tif (!dev->drv[cmd->driver]->interface) {\n\t\tprintk(KERN_WARNING \"isdn_command command(%x) dev->drv[%d]->interface NULL\\n\",\n\t\t\tcmd->command, cmd->driver);\n\t\treturn(1);\n\t}\n\tif (cmd->command == ISDN_CMD_SETL2) {\n\t\tint idx = isdn_dc2minor(cmd->driver, cmd->arg & 255);\n\t\tunsigned long l2prot = (cmd->arg >> 8) & 255;\n\t\tunsigned long features = (dev->drv[cmd->driver]->interface->features\n\t\t\t\t\t\t>> ISDN_FEATURE_L2_SHIFT) &\n\t\t\t\t\t\tISDN_FEATURE_L2_MASK;\n\t\tunsigned long l2_feature = (1 << l2prot);\n\n\t\tswitch (l2prot) {\n\t\t\tcase ISDN_PROTO_L2_V11096:\n\t\t\tcase ISDN_PROTO_L2_V11019:\n\t\t\tcase ISDN_PROTO_L2_V11038:\n\t\t\t/* If V.110 requested, but not supported by\n\t\t\t * HL-driver, set emulator-flag and change\n\t\t\t * Layer-2 to transparent\n\t\t\t */\n\t\t\t\tif (!(features & l2_feature)) {\n\t\t\t\t\tdev->v110emu[idx] = l2prot;\n\t\t\t\t\tcmd->arg = (cmd->arg & 255) |\n\t\t\t\t\t\t(ISDN_PROTO_L2_TRANS << 8);\n\t\t\t\t} else\n\t\t\t\t\tdev->v110emu[idx] = 0;\n\t\t}\n\t}\n\treturn dev->drv[cmd->driver]->interface->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: static int shmem_unuse_inode(struct shmem_inode_info *info, swp_entry_t entry, struct page *page)\n{\n\tstruct inode *inode;\n\tunsigned long idx;\n\tunsigned long size;\n\tunsigned long limit;\n\tunsigned long stage;\n\tstruct page **dir;\n\tstruct page *subdir;\n\tswp_entry_t *ptr;\n\tint offset;\n\n\tidx = 0;\n\tptr = info->i_direct;\n\tspin_lock(&info->lock);\n\tlimit = info->next_index;\n\tsize = limit;\n\tif (size > SHMEM_NR_DIRECT)\n\t\tsize = SHMEM_NR_DIRECT;\n\toffset = shmem_find_swp(entry, ptr, ptr+size);\n\tif (offset >= 0) {\n\t\tshmem_swp_balance_unmap();\n\t\tgoto found;\n\t}\n\tif (!info->i_indirect)\n\t\tgoto lost2;\n\n\tdir = shmem_dir_map(info->i_indirect);\n\tstage = SHMEM_NR_DIRECT + ENTRIES_PER_PAGEPAGE/2;\n\n\tfor (idx = SHMEM_NR_DIRECT; idx < limit; idx += ENTRIES_PER_PAGE, dir++) {\n\t\tif (unlikely(idx == stage)) {\n\t\t\tshmem_dir_unmap(dir-1);\n\t\t\tdir = shmem_dir_map(info->i_indirect) +\n\t\t\t ENTRIES_PER_PAGE/2 + idx/ENTRIES_PER_PAGEPAGE;\n\t\t\twhile (!*dir) {\n\t\t\t\tdir++;\n\t\t\t\tidx += ENTRIES_PER_PAGEPAGE;\n\t\t\t\tif (idx >= limit)\n\t\t\t\t\tgoto lost1;\n\t\t\t}\n\t\t\tstage = idx + ENTRIES_PER_PAGEPAGE;\n\t\t\tsubdir = *dir;\n\t\t\tshmem_dir_unmap(dir);\n\t\t\tdir = shmem_dir_map(subdir);\n\t\t}\n\t\tsubdir = *dir;\n\t\tif (subdir && page_private(subdir)) {\n\t\t\tptr = shmem_swp_map(subdir);\n\t\t\tsize = limit - idx;\n\t\t\tif (size > ENTRIES_PER_PAGE)\n\t\t\t\tsize = ENTRIES_PER_PAGE;\n\t\t\toffset = shmem_find_swp(entry, ptr, ptr+size);\n\t\t\tif (offset >= 0) {\n\t\t\t\tshmem_dir_unmap(dir);\n\t\t\t\tgoto found;\n\t\t\t}\n\t\t\tshmem_swp_unmap(ptr);\n\t\t}\n\t}\nlost1:\n\tshmem_dir_unmap(dir-1);\nlost2:\n\tspin_unlock(&info->lock);\n\treturn 0;\nfound:\n\tidx += offset;\n\tinode = &info->vfs_inode;\n\tif (move_from_swap_cache(page, idx, inode->i_mapping) == 0) {\n\t\tinfo->flags |= SHMEM_PAGEIN;\n\t\tshmem_swp_set(info, ptr + offset, 0);\n\t}\n\tshmem_swp_unmap(ptr);\n\tspin_unlock(&info->lock);\n\t/*\n\t * Decrement swap count even when the entry is left behind:\n\t * try_to_unuse will skip over mms, then reincrement count.\n\t */\n\tswap_free(entry);\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'tmpfs: restore missing clear_highpage\n\ntmpfs was misconverted to __GFP_ZERO in 2.6.11. There's an unusual case in\nwhich shmem_getpage receives the page from its caller instead of allocating.\nWe must cover this case by clear_highpage before SetPageUptodate, as before.\n\nSigned-off-by: Hugh Dickins \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void shmem_free_pages(struct list_head *next)\n{\n\tstruct page *page;\n\tint freed = 0;\n\n\tdo {\n\t\tpage = container_of(next, struct page, lru);\n\t\tnext = next->next;\n\t\tshmem_dir_free(page);\n\t\tfreed++;\n\t\tif (freed >= LATENCY_LIMIT) {\n\t\t\tcond_resched();\n\t\t\tfreed = 0;\n\t\t}\n\t} while (next);\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_statfs(struct dentry *dentry, struct kstatfs *buf)\n{\n\tstruct shmem_sb_info *sbinfo = SHMEM_SB(dentry->d_sb);\n\n\tbuf->f_type = TMPFS_MAGIC;\n\tbuf->f_bsize = PAGE_CACHE_SIZE;\n\tbuf->f_namelen = NAME_MAX;\n\tspin_lock(&sbinfo->stat_lock);\n\tif (sbinfo->max_blocks) {\n\t\tbuf->f_blocks = sbinfo->max_blocks;\n\t\tbuf->f_bavail = buf->f_bfree = sbinfo->free_blocks;\n\t}\n\tif (sbinfo->max_inodes) {\n\t\tbuf->f_files = sbinfo->max_inodes;\n\t\tbuf->f_ffree = sbinfo->free_inodes;\n\t}\n\t/* else leave those fields 0 like simple_statfs */\n\tspin_unlock(&sbinfo->stat_lock);\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 int init_inodecache(void)\n{\n\tshmem_inode_cachep = kmem_cache_create(\"shmem_inode_cache\",\n\t\t\t\tsizeof(struct shmem_inode_info),\n\t\t\t\t0, SLAB_PANIC, init_once);\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 int shmem_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry)\n{\n\tstruct inode *inode = old_dentry->d_inode;\n\tint they_are_dirs = S_ISDIR(inode->i_mode);\n\n\tif (!simple_empty(new_dentry))\n\t\treturn -ENOTEMPTY;\n\n\tif (new_dentry->d_inode) {\n\t\t(void) shmem_unlink(new_dir, new_dentry);\n\t\tif (they_are_dirs)\n\t\t\tdrop_nlink(old_dir);\n\t} else if (they_are_dirs) {\n\t\tdrop_nlink(old_dir);\n\t\tinc_nlink(new_dir);\n\t}\n\n\told_dir->i_size -= BOGO_DIRENT_SIZE;\n\tnew_dir->i_size += BOGO_DIRENT_SIZE;\n\told_dir->i_ctime = old_dir->i_mtime =\n\tnew_dir->i_ctime = new_dir->i_mtime =\n\tinode->i_ctime = CURRENT_TIME;\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: shmem_write_begin(struct file *file, struct address_space *mapping,\n\t\t\tloff_t pos, unsigned len, unsigned flags,\n\t\t\tstruct page **pagep, void **fsdata)\n{\n\tstruct inode *inode = mapping->host;\n\tpgoff_t index = pos >> PAGE_CACHE_SHIFT;\n\t*pagep = NULL;\n\treturn shmem_getpage(inode, index, pagep, SGP_WRITE, NULL);\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 destroy_inodecache(void)\n{\n\tkmem_cache_destroy(shmem_inode_cachep);\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 swp_entry_t *shmem_swp_alloc(struct shmem_inode_info *info, unsigned long index, enum sgp_type sgp)\n{\n\tstruct inode *inode = &info->vfs_inode;\n\tstruct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);\n\tstruct page *page = NULL;\n\tswp_entry_t *entry;\n\n\tif (sgp != SGP_WRITE &&\n\t ((loff_t) index << PAGE_CACHE_SHIFT) >= i_size_read(inode))\n\t\treturn ERR_PTR(-EINVAL);\n\n\twhile (!(entry = shmem_swp_entry(info, index, &page))) {\n\t\tif (sgp == SGP_READ)\n\t\t\treturn shmem_swp_map(ZERO_PAGE(0));\n\t\t/*\n\t\t * Test free_blocks against 1 not 0, since we have 1 data\n\t\t * page (and perhaps indirect index pages) yet to allocate:\n\t\t * a waste to allocate index if we cannot allocate data.\n\t\t */\n\t\tif (sbinfo->max_blocks) {\n\t\t\tspin_lock(&sbinfo->stat_lock);\n\t\t\tif (sbinfo->free_blocks <= 1) {\n\t\t\t\tspin_unlock(&sbinfo->stat_lock);\n\t\t\t\treturn ERR_PTR(-ENOSPC);\n\t\t\t}\n\t\t\tsbinfo->free_blocks--;\n\t\t\tinode->i_blocks += BLOCKS_PER_PAGE;\n\t\t\tspin_unlock(&sbinfo->stat_lock);\n\t\t}\n\n\t\tspin_unlock(&info->lock);\n\t\tpage = shmem_dir_alloc(mapping_gfp_mask(inode->i_mapping));\n\t\tif (page)\n\t\t\tset_page_private(page, 0);\n\t\tspin_lock(&info->lock);\n\n\t\tif (!page) {\n\t\t\tshmem_free_blocks(inode, 1);\n\t\t\treturn ERR_PTR(-ENOMEM);\n\t\t}\n\t\tif (sgp != SGP_WRITE &&\n\t\t ((loff_t) index << PAGE_CACHE_SHIFT) >= i_size_read(inode)) {\n\t\t\tentry = ERR_PTR(-EINVAL);\n\t\t\tbreak;\n\t\t}\n\t\tif (info->next_index <= index)\n\t\t\tinfo->next_index = index + 1;\n\t}\n\tif (page) {\n\t\t/* another task gave its page, or truncated the file */\n\t\tshmem_free_blocks(inode, 1);\n\t\tshmem_dir_free(page);\n\t}\n\tif (info->next_index <= index && !IS_ERR(entry))\n\t\tinfo->next_index = index + 1;\n\treturn entry;\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: ProcShmAttach(client)\n register ClientPtr client;\n{\n SHMSTAT_TYPE buf;\n ShmDescPtr shmdesc;\n REQUEST(xShmAttachReq);\n\n REQUEST_SIZE_MATCH(xShmAttachReq);\n LEGAL_NEW_RESOURCE(stuff->shmseg, client);\n if ((stuff->readOnly != xTrue) && (stuff->readOnly != xFalse))\n {\n\tclient->errorValue = stuff->readOnly;\n return(BadValue);\n }\n for (shmdesc = Shmsegs;\n\t shmdesc && (shmdesc->shmid != stuff->shmid);\n\t shmdesc = shmdesc->next)\n\t;\n if (shmdesc)\n {\n\tif (!stuff->readOnly && !shmdesc->writable)\n\t return BadAccess;\n\tshmdesc->refcnt++;\n }\n else\n {\n\tshmdesc = (ShmDescPtr) xalloc(sizeof(ShmDescRec));\n\tif (!shmdesc)\n\t return BadAlloc;\n\tshmdesc->addr = shmat(stuff->shmid, 0,\n\t\t\t stuff->readOnly ? SHM_RDONLY : 0);\n\tif ((shmdesc->addr == ((char *)-1)) ||\n\t SHMSTAT(stuff->shmid, &buf))\n\t{\n\t xfree(shmdesc);\n\t return BadAccess;\n\t}\n\n\t/* The attach was performed with root privs. We must\n\t * do manual checking of access rights for the credentials \n\t * of the client */\n\n\tif (shm_access(client, &(SHM_PERM(buf)), stuff->readOnly) == -1) {\n\t shmdt(shmdesc->addr);\n\t xfree(shmdesc);\n\t return BadAccess;\n\t}\n\n\tshmdesc->shmid = stuff->shmid;\n\tshmdesc->refcnt = 1;\n\tshmdesc->writable = !stuff->readOnly;\n\tshmdesc->size = SHM_SEGSZ(buf);\n\tshmdesc->next = Shmsegs;\n\tShmsegs = shmdesc;\n }\n if (!AddResource(stuff->shmseg, ShmSegType, (pointer)shmdesc))\n\treturn BadAlloc;\n return(client->noClientException);\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: ShmDestroyPixmap (PixmapPtr pPixmap)\n{\n ScreenPtr\t pScreen = pPixmap->drawable.pScreen;\n Bool\t ret;\n if (pPixmap->refcnt == 1)\n {\n\tShmDescPtr shmdesc;\n\tshmdesc = (ShmDescPtr)dixLookupPrivate(&pPixmap->devPrivates,\n\t\t\t\t\t shmPixmapPrivate);\n\tif (shmdesc)\n\t ShmDetachSegment ((pointer) shmdesc, pPixmap->drawable.id);\n }\n \n pScreen->DestroyPixmap = destroyPixmap[pScreen->myNum];\n ret = (*pScreen->DestroyPixmap) (pPixmap);\n destroyPixmap[pScreen->myNum] = pScreen->DestroyPixmap;\n pScreen->DestroyPixmap = ShmDestroyPixmap;\n return ret;\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: ProcShmDetach(client)\n register ClientPtr client;\n{\n ShmDescPtr shmdesc;\n REQUEST(xShmDetachReq);\n\n REQUEST_SIZE_MATCH(xShmDetachReq);\n VERIFY_SHMSEG(stuff->shmseg, shmdesc, client);\n FreeResource(stuff->shmseg, RT_NONE);\n return(client->noClientException);\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: ShmRegisterFuncs(\n ScreenPtr pScreen,\n ShmFuncsPtr funcs)\n{\n shmFuncs[pScreen->myNum] = funcs;\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: generic_file_splice_write(struct pipe_inode_info *pipe, struct file *out,\n\t\t\t loff_t *ppos, size_t len, unsigned int flags)\n{\n\tstruct address_space *mapping = out->f_mapping;\n\tstruct inode *inode = mapping->host;\n\tint killsuid, killpriv;\n\tssize_t ret;\n\tint err = 0;\n\n\tkillpriv = security_inode_need_killpriv(out->f_path.dentry);\n\tkillsuid = should_remove_suid(out->f_path.dentry);\n\tif (unlikely(killsuid || killpriv)) {\n\t\tmutex_lock(&inode->i_mutex);\n\t\tif (killpriv)\n\t\t\terr = security_inode_killpriv(out->f_path.dentry);\n\t\tif (!err && killsuid)\n\t\t\terr = __remove_suid(out->f_path.dentry, killsuid);\n\t\tmutex_unlock(&inode->i_mutex);\n\t\tif (err)\n\t\t\treturn err;\n\t}\n\n\tret = splice_from_pipe(pipe, out, ppos, len, flags, pipe_to_file);\n\tif (ret > 0) {\n\t\tunsigned long nr_pages;\n\n\t\t*ppos += ret;\n\t\tnr_pages = (ret + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;\n\n\t\t/*\n\t\t * If file or inode is SYNC and we actually wrote some data,\n\t\t * sync it.\n\t\t */\n\t\tif (unlikely((out->f_flags & O_SYNC) || IS_SYNC(inode))) {\n\t\t\tmutex_lock(&inode->i_mutex);\n\t\t\terr = generic_osync_inode(inode, mapping,\n\t\t\t\t\t\t OSYNC_METADATA|OSYNC_DATA);\n\t\t\tmutex_unlock(&inode->i_mutex);\n\n\t\t\tif (err)\n\t\t\t\tret = err;\n\t\t}\n\t\tbalance_dirty_pages_ratelimited_nr(mapping, nr_pages);\n\t}\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-94'], 'message': 'splice: missing user pointer access verification\n\nvmsplice_to_user() must always check the user pointer and length\nwith access_ok() before copying. Likewise, for the slow path of\ncopy_from_user_mmap_sem() we need to check that we may read from\nthe user region.\n\nSigned-off-by: Jens Axboe \nCc: Wojciech Purczynski \nSigned-off-by: Greg Kroah-Hartman \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int link_ipipe_prep(struct pipe_inode_info *pipe, unsigned int flags)\n{\n\tint ret;\n\n\t/*\n\t * Check ->nrbufs without the inode lock first. This function\n\t * is speculative anyways, so missing one is ok.\n\t */\n\tif (pipe->nrbufs)\n\t\treturn 0;\n\n\tret = 0;\n\tmutex_lock(&pipe->inode->i_mutex);\n\n\twhile (!pipe->nrbufs) {\n\t\tif (signal_pending(current)) {\n\t\t\tret = -ERESTARTSYS;\n\t\t\tbreak;\n\t\t}\n\t\tif (!pipe->writers)\n\t\t\tbreak;\n\t\tif (!pipe->waiting_writers) {\n\t\t\tif (flags & SPLICE_F_NONBLOCK) {\n\t\t\t\tret = -EAGAIN;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tpipe_wait(pipe);\n\t}\n\n\tmutex_unlock(&pipe->inode->i_mutex);\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 int direct_splice_actor(struct pipe_inode_info *pipe,\n\t\t\t struct splice_desc *sd)\n{\n\tstruct file *file = sd->u.file;\n\n\treturn do_splice_from(pipe, file, &sd->pos, sd->total_len, sd->flags);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-94'], 'message': 'splice: missing user pointer access verification\n\nvmsplice_to_user() must always check the user pointer and length\nwith access_ok() before copying. Likewise, for the slow path of\ncopy_from_user_mmap_sem() we need to check that we may read from\nthe user region.\n\nSigned-off-by: Jens Axboe \nCc: Wojciech Purczynski \nSigned-off-by: Greg Kroah-Hartman \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int srcu_notifier_chain_register(struct srcu_notifier_head *nh,\n\t\tstruct notifier_block *n)\n{\n\tint ret;\n\n\t/*\n\t * This code gets used during boot-up, when task switching is\n\t * not yet working and interrupts must remain disabled. At\n\t * such times we must not call mutex_lock().\n\t */\n\tif (unlikely(system_state == SYSTEM_BOOTING))\n\t\treturn notifier_chain_register(&nh->head, n);\n\n\tmutex_lock(&nh->mutex);\n\tret = notifier_chain_register(&nh->head, n);\n\tmutex_unlock(&nh->mutex);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'CPU time limit patch / setrlimit(RLIMIT_CPU, 0) cheat fix\n\nAs discovered here today, the change in Kernel 2.6.17 intended to inhibit\nusers from setting RLIMIT_CPU to 0 (as that is equivalent to unlimited) by\n\"cheating\" and setting it to 1 in such a case, does not make a difference,\nas the check is done in the wrong place (too late), and only applies to the\nprofiling code.\n\nOn all systems I checked running kernels above 2.6.17, no matter what the\nhard and soft CPU time limits were before, a user could escape them by\nissuing in the shell (sh/bash/zsh) \"ulimit -t 0\", and then the user's\nprocess was not ever killed.\n\nAttached is a trivial patch to fix that. Simply moving the check to a\nslightly earlier location (specifically, before the line that actually\nassigns the limit - *old_rlim = new_rlim), does the trick.\n\nDo note that at least the zsh (but not ash, dash, or bash) shell has the\nproblem of \"caching\" the limits set by the ulimit command, so when running\nzsh the fix will not immediately be evident - after entering \"ulimit -t 0\",\n\"ulimit -a\" will show \"-t: cpu time (seconds) 0\", even though the actual\nlimit as returned by getrlimit(...) will be 1. It can be verified by\nopening a subshell (which will not have the values of the parent shell in\ncache) and checking in it, or just by running a CPU intensive command like\n\"echo '65536^1048576' | bc\" and verifying that it dumps core after one\nsecond.\n\nRegardless of whether that is a misfeature in the shell, perhaps it would\nbe better to return -EINVAL from setrlimit in such a case instead of\ncheating and setting to 1, as that does not really reflect the actual state\nof the process anymore. I do not however know what the ground for that\ndecision was in the original 2.6.17 change, and whether there would be any\n\"backward\" compatibility issues, so I preferred not to touch that right\nnow.\n\nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int set_user(uid_t new_ruid, int dumpclear)\n{\n\tstruct user_struct *new_user;\n\n\tnew_user = alloc_uid(new_ruid);\n\tif (!new_user)\n\t\treturn -EAGAIN;\n\n\tif (atomic_read(&new_user->processes) >=\n\t\t\t\tcurrent->signal->rlim[RLIMIT_NPROC].rlim_cur &&\n\t\t\tnew_user != &root_user) {\n\t\tfree_uid(new_user);\n\t\treturn -EAGAIN;\n\t}\n\n\tswitch_uid(new_user);\n\n\tif (dumpclear) {\n\t\tcurrent->mm->dumpable = suid_dumpable;\n\t\tsmp_wmb();\n\t}\n\tcurrent->uid = new_ruid;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'CPU time limit patch / setrlimit(RLIMIT_CPU, 0) cheat fix\n\nAs discovered here today, the change in Kernel 2.6.17 intended to inhibit\nusers from setting RLIMIT_CPU to 0 (as that is equivalent to unlimited) by\n\"cheating\" and setting it to 1 in such a case, does not make a difference,\nas the check is done in the wrong place (too late), and only applies to the\nprofiling code.\n\nOn all systems I checked running kernels above 2.6.17, no matter what the\nhard and soft CPU time limits were before, a user could escape them by\nissuing in the shell (sh/bash/zsh) \"ulimit -t 0\", and then the user's\nprocess was not ever killed.\n\nAttached is a trivial patch to fix that. Simply moving the check to a\nslightly earlier location (specifically, before the line that actually\nassigns the limit - *old_rlim = new_rlim), does the trick.\n\nDo note that at least the zsh (but not ash, dash, or bash) shell has the\nproblem of \"caching\" the limits set by the ulimit command, so when running\nzsh the fix will not immediately be evident - after entering \"ulimit -t 0\",\n\"ulimit -a\" will show \"-t: cpu time (seconds) 0\", even though the actual\nlimit as returned by getrlimit(...) will be 1. It can be verified by\nopening a subshell (which will not have the values of the parent shell in\ncache) and checking in it, or just by running a CPU intensive command like\n\"echo '65536^1048576' | bc\" and verifying that it dumps core after one\nsecond.\n\nRegardless of whether that is a misfeature in the shell, perhaps it would\nbe better to return -EINVAL from setrlimit in such a case instead of\ncheating and setting to 1, as that does not really reflect the actual state\nof the process anymore. I do not however know what the ground for that\ndecision was in the original 2.6.17 change, and whether there would be any\n\"backward\" compatibility issues, so I preferred not to touch that right\nnow.\n\nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" } ]