text
stringlengths
478
483k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ptr_t GC_wince_get_mem(word bytes) { ptr_t result = 0; /* initialized to prevent warning. */ word i; bytes = ROUNDUP_PAGESIZE(bytes); /* Try to find reserved, uncommitted pages */ for (i = 0; i < GC_n_heap_bases; i++) { if (((word)(-(signed_word)GC_heap_lengths[i]) & (GC_sysinfo.dwAllocationGranularity-1)) >= bytes) { result = GC_heap_bases[i] + GC_heap_lengths[i]; break; } } if (i == GC_n_heap_bases) { /* Reserve more pages */ word res_bytes = (bytes + GC_sysinfo.dwAllocationGranularity-1) & ~(GC_sysinfo.dwAllocationGranularity-1); /* If we ever support MPROTECT_VDB here, we will probably need to */ /* ensure that res_bytes is strictly > bytes, so that VirtualProtect */ /* never spans regions. It seems to be OK for a VirtualFree */ /* argument to span regions, so we should be OK for now. */ result = (ptr_t) VirtualAlloc(NULL, res_bytes, MEM_RESERVE | MEM_TOP_DOWN, GC_pages_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE); if (HBLKDISPL(result) != 0) ABORT("Bad VirtualAlloc result"); /* If I read the documentation correctly, this can */ /* only happen if HBLKSIZE > 64k or not a power of 2. */ if (GC_n_heap_bases >= MAX_HEAP_SECTS) ABORT("Too many heap sections"); if (result == NULL) return NULL; GC_heap_bases[GC_n_heap_bases] = result; GC_heap_lengths[GC_n_heap_bases] = 0; GC_n_heap_bases++; } /* Commit pages */ result = (ptr_t) VirtualAlloc(result, bytes, MEM_COMMIT, GC_pages_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE); # undef IGNORE_PAGES_EXECUTABLE if (result != NULL) { if (HBLKDISPL(result) != 0) ABORT("Bad VirtualAlloc result"); GC_heap_lengths[i] += bytes; } return(result); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix malloc routines to prevent size value wrap-around See issue #135 on Github. * allchblk.c (GC_allochblk, GC_allochblk_nth): Use OBJ_SZ_TO_BLOCKS_CHECKED instead of OBJ_SZ_TO_BLOCKS. * malloc.c (GC_alloc_large): Likewise. * alloc.c (GC_expand_hp_inner): Type of "bytes" local variable changed from word to size_t; cast ROUNDUP_PAGESIZE argument to size_t; prevent overflow when computing GC_heapsize+bytes > GC_max_heapsize. * dbg_mlc.c (GC_debug_malloc, GC_debug_malloc_ignore_off_page, GC_debug_malloc_atomic_ignore_off_page, GC_debug_generic_malloc, GC_debug_generic_malloc_inner, GC_debug_generic_malloc_inner_ignore_off_page, GC_debug_malloc_stubborn, GC_debug_malloc_atomic, GC_debug_malloc_uncollectable, GC_debug_malloc_atomic_uncollectable): Use SIZET_SAT_ADD (instead of "+" operator) to add extra bytes to lb value. * fnlz_mlc.c (GC_finalized_malloc): Likewise. * gcj_mlc.c (GC_debug_gcj_malloc): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, ROUNDUP_PAGESIZE): Likewise. * include/private/gcconfig.h (GET_MEM): Likewise. * mallocx.c (GC_malloc_many, GC_memalign): Likewise. * os_dep.c (GC_wince_get_mem, GC_win32_get_mem): Likewise. * typd_mlc.c (GC_malloc_explicitly_typed, GC_malloc_explicitly_typed_ignore_off_page, GC_calloc_explicitly_typed): Likewise. * headers.c (GC_scratch_alloc): Change type of bytes_to_get from word to size_t (because ROUNDUP_PAGESIZE_IF_MMAP result type changed). * include/private/gc_priv.h: Include limits.h (unless SIZE_MAX already defined). * include/private/gc_priv.h (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Move from malloc.c file. * include/private/gc_priv.h (SIZET_SAT_ADD): New macro (defined before include gcconfig.h). * include/private/gc_priv.h (EXTRA_BYTES, GC_page_size): Change type to size_t. * os_dep.c (GC_page_size): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, ROUNDUP_PAGESIZE): Add comment about the argument. * include/private/gcconfig.h (GET_MEM): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, OBJ_SZ_TO_BLOCKS, ROUNDUP_PAGESIZE, ROUNDUP_PAGESIZE_IF_MMAP): Rename argument to "lb". * include/private/gc_priv.h (OBJ_SZ_TO_BLOCKS_CHECKED): New macro. * include/private/gcconfig.h (GC_win32_get_mem, GC_wince_get_mem, GC_unix_get_mem): Change argument type from word to int. * os_dep.c (GC_unix_mmap_get_mem, GC_unix_get_mem, GC_unix_sbrk_get_mem, GC_wince_get_mem, GC_win32_get_mem): Likewise. * malloc.c (GC_alloc_large_and_clear): Call OBJ_SZ_TO_BLOCKS only if no value wrap around is guaranteed. * malloc.c (GC_generic_malloc): Do not check for lb_rounded < lb case (because ROUNDED_UP_GRANULES and GRANULES_TO_BYTES guarantees no value wrap around). * mallocx.c (GC_generic_malloc_ignore_off_page): Likewise. * misc.c (GC_init_size_map): Change "i" local variable type from int to size_t. * os_dep.c (GC_write_fault_handler, catch_exception_raise): Likewise. * misc.c (GC_envfile_init): Cast len to size_t when passed to ROUNDUP_PAGESIZE_IF_MMAP. * os_dep.c (GC_setpagesize): Cast GC_sysinfo.dwPageSize and GETPAGESIZE() to size_t (when setting GC_page_size). * os_dep.c (GC_unix_mmap_get_mem, GC_unmap_start, GC_remove_protection): Expand ROUNDUP_PAGESIZE macro but without value wrap-around checking (the argument is of word type). * os_dep.c (GC_unix_mmap_get_mem): Replace -GC_page_size with ~GC_page_size+1 (because GC_page_size is unsigned); remove redundant cast to size_t. * os_dep.c (GC_unix_sbrk_get_mem): Add explicit cast of GC_page_size to SBRK_ARG_T. * os_dep.c (GC_wince_get_mem): Change type of res_bytes local variable to size_t. * typd_mlc.c: Do not include limits.h. * typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Remove (as defined in gc_priv.h now).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: STATIC ptr_t GC_unix_sbrk_get_mem(word bytes) { ptr_t result; # ifdef IRIX5 /* Bare sbrk isn't thread safe. Play by malloc rules. */ /* The equivalent may be needed on other systems as well. */ __LOCK_MALLOC(); # endif { ptr_t cur_brk = (ptr_t)sbrk(0); SBRK_ARG_T lsbs = (word)cur_brk & (GC_page_size-1); if ((SBRK_ARG_T)bytes < 0) { result = 0; /* too big */ goto out; } if (lsbs != 0) { if((ptr_t)sbrk(GC_page_size - lsbs) == (ptr_t)(-1)) { result = 0; goto out; } } # ifdef ADD_HEAP_GUARD_PAGES /* This is useful for catching severe memory overwrite problems that */ /* span heap sections. It shouldn't otherwise be turned on. */ { ptr_t guard = (ptr_t)sbrk((SBRK_ARG_T)GC_page_size); if (mprotect(guard, GC_page_size, PROT_NONE) != 0) ABORT("ADD_HEAP_GUARD_PAGES: mprotect failed"); } # endif /* ADD_HEAP_GUARD_PAGES */ result = (ptr_t)sbrk((SBRK_ARG_T)bytes); if (result == (ptr_t)(-1)) result = 0; } out: # ifdef IRIX5 __UNLOCK_MALLOC(); # endif return(result); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix malloc routines to prevent size value wrap-around See issue #135 on Github. * allchblk.c (GC_allochblk, GC_allochblk_nth): Use OBJ_SZ_TO_BLOCKS_CHECKED instead of OBJ_SZ_TO_BLOCKS. * malloc.c (GC_alloc_large): Likewise. * alloc.c (GC_expand_hp_inner): Type of "bytes" local variable changed from word to size_t; cast ROUNDUP_PAGESIZE argument to size_t; prevent overflow when computing GC_heapsize+bytes > GC_max_heapsize. * dbg_mlc.c (GC_debug_malloc, GC_debug_malloc_ignore_off_page, GC_debug_malloc_atomic_ignore_off_page, GC_debug_generic_malloc, GC_debug_generic_malloc_inner, GC_debug_generic_malloc_inner_ignore_off_page, GC_debug_malloc_stubborn, GC_debug_malloc_atomic, GC_debug_malloc_uncollectable, GC_debug_malloc_atomic_uncollectable): Use SIZET_SAT_ADD (instead of "+" operator) to add extra bytes to lb value. * fnlz_mlc.c (GC_finalized_malloc): Likewise. * gcj_mlc.c (GC_debug_gcj_malloc): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, ROUNDUP_PAGESIZE): Likewise. * include/private/gcconfig.h (GET_MEM): Likewise. * mallocx.c (GC_malloc_many, GC_memalign): Likewise. * os_dep.c (GC_wince_get_mem, GC_win32_get_mem): Likewise. * typd_mlc.c (GC_malloc_explicitly_typed, GC_malloc_explicitly_typed_ignore_off_page, GC_calloc_explicitly_typed): Likewise. * headers.c (GC_scratch_alloc): Change type of bytes_to_get from word to size_t (because ROUNDUP_PAGESIZE_IF_MMAP result type changed). * include/private/gc_priv.h: Include limits.h (unless SIZE_MAX already defined). * include/private/gc_priv.h (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Move from malloc.c file. * include/private/gc_priv.h (SIZET_SAT_ADD): New macro (defined before include gcconfig.h). * include/private/gc_priv.h (EXTRA_BYTES, GC_page_size): Change type to size_t. * os_dep.c (GC_page_size): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, ROUNDUP_PAGESIZE): Add comment about the argument. * include/private/gcconfig.h (GET_MEM): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, OBJ_SZ_TO_BLOCKS, ROUNDUP_PAGESIZE, ROUNDUP_PAGESIZE_IF_MMAP): Rename argument to "lb". * include/private/gc_priv.h (OBJ_SZ_TO_BLOCKS_CHECKED): New macro. * include/private/gcconfig.h (GC_win32_get_mem, GC_wince_get_mem, GC_unix_get_mem): Change argument type from word to int. * os_dep.c (GC_unix_mmap_get_mem, GC_unix_get_mem, GC_unix_sbrk_get_mem, GC_wince_get_mem, GC_win32_get_mem): Likewise. * malloc.c (GC_alloc_large_and_clear): Call OBJ_SZ_TO_BLOCKS only if no value wrap around is guaranteed. * malloc.c (GC_generic_malloc): Do not check for lb_rounded < lb case (because ROUNDED_UP_GRANULES and GRANULES_TO_BYTES guarantees no value wrap around). * mallocx.c (GC_generic_malloc_ignore_off_page): Likewise. * misc.c (GC_init_size_map): Change "i" local variable type from int to size_t. * os_dep.c (GC_write_fault_handler, catch_exception_raise): Likewise. * misc.c (GC_envfile_init): Cast len to size_t when passed to ROUNDUP_PAGESIZE_IF_MMAP. * os_dep.c (GC_setpagesize): Cast GC_sysinfo.dwPageSize and GETPAGESIZE() to size_t (when setting GC_page_size). * os_dep.c (GC_unix_mmap_get_mem, GC_unmap_start, GC_remove_protection): Expand ROUNDUP_PAGESIZE macro but without value wrap-around checking (the argument is of word type). * os_dep.c (GC_unix_mmap_get_mem): Replace -GC_page_size with ~GC_page_size+1 (because GC_page_size is unsigned); remove redundant cast to size_t. * os_dep.c (GC_unix_sbrk_get_mem): Add explicit cast of GC_page_size to SBRK_ARG_T. * os_dep.c (GC_wince_get_mem): Change type of res_bytes local variable to size_t. * typd_mlc.c: Do not include limits.h. * typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Remove (as defined in gc_priv.h now).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: STATIC void GC_init_size_map(void) { int i; /* Map size 0 to something bigger. */ /* This avoids problems at lower levels. */ GC_size_map[0] = 1; for (i = 1; i <= GRANULES_TO_BYTES(TINY_FREELISTS-1) - EXTRA_BYTES; i++) { GC_size_map[i] = (unsigned)ROUNDED_UP_GRANULES(i); # ifndef _MSC_VER GC_ASSERT(GC_size_map[i] < TINY_FREELISTS); /* Seems to tickle bug in VC++ 2008 for AMD64 */ # endif } /* We leave the rest of the array to be filled in on demand. */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix malloc routines to prevent size value wrap-around See issue #135 on Github. * allchblk.c (GC_allochblk, GC_allochblk_nth): Use OBJ_SZ_TO_BLOCKS_CHECKED instead of OBJ_SZ_TO_BLOCKS. * malloc.c (GC_alloc_large): Likewise. * alloc.c (GC_expand_hp_inner): Type of "bytes" local variable changed from word to size_t; cast ROUNDUP_PAGESIZE argument to size_t; prevent overflow when computing GC_heapsize+bytes > GC_max_heapsize. * dbg_mlc.c (GC_debug_malloc, GC_debug_malloc_ignore_off_page, GC_debug_malloc_atomic_ignore_off_page, GC_debug_generic_malloc, GC_debug_generic_malloc_inner, GC_debug_generic_malloc_inner_ignore_off_page, GC_debug_malloc_stubborn, GC_debug_malloc_atomic, GC_debug_malloc_uncollectable, GC_debug_malloc_atomic_uncollectable): Use SIZET_SAT_ADD (instead of "+" operator) to add extra bytes to lb value. * fnlz_mlc.c (GC_finalized_malloc): Likewise. * gcj_mlc.c (GC_debug_gcj_malloc): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, ROUNDUP_PAGESIZE): Likewise. * include/private/gcconfig.h (GET_MEM): Likewise. * mallocx.c (GC_malloc_many, GC_memalign): Likewise. * os_dep.c (GC_wince_get_mem, GC_win32_get_mem): Likewise. * typd_mlc.c (GC_malloc_explicitly_typed, GC_malloc_explicitly_typed_ignore_off_page, GC_calloc_explicitly_typed): Likewise. * headers.c (GC_scratch_alloc): Change type of bytes_to_get from word to size_t (because ROUNDUP_PAGESIZE_IF_MMAP result type changed). * include/private/gc_priv.h: Include limits.h (unless SIZE_MAX already defined). * include/private/gc_priv.h (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Move from malloc.c file. * include/private/gc_priv.h (SIZET_SAT_ADD): New macro (defined before include gcconfig.h). * include/private/gc_priv.h (EXTRA_BYTES, GC_page_size): Change type to size_t. * os_dep.c (GC_page_size): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, ROUNDUP_PAGESIZE): Add comment about the argument. * include/private/gcconfig.h (GET_MEM): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, OBJ_SZ_TO_BLOCKS, ROUNDUP_PAGESIZE, ROUNDUP_PAGESIZE_IF_MMAP): Rename argument to "lb". * include/private/gc_priv.h (OBJ_SZ_TO_BLOCKS_CHECKED): New macro. * include/private/gcconfig.h (GC_win32_get_mem, GC_wince_get_mem, GC_unix_get_mem): Change argument type from word to int. * os_dep.c (GC_unix_mmap_get_mem, GC_unix_get_mem, GC_unix_sbrk_get_mem, GC_wince_get_mem, GC_win32_get_mem): Likewise. * malloc.c (GC_alloc_large_and_clear): Call OBJ_SZ_TO_BLOCKS only if no value wrap around is guaranteed. * malloc.c (GC_generic_malloc): Do not check for lb_rounded < lb case (because ROUNDED_UP_GRANULES and GRANULES_TO_BYTES guarantees no value wrap around). * mallocx.c (GC_generic_malloc_ignore_off_page): Likewise. * misc.c (GC_init_size_map): Change "i" local variable type from int to size_t. * os_dep.c (GC_write_fault_handler, catch_exception_raise): Likewise. * misc.c (GC_envfile_init): Cast len to size_t when passed to ROUNDUP_PAGESIZE_IF_MMAP. * os_dep.c (GC_setpagesize): Cast GC_sysinfo.dwPageSize and GETPAGESIZE() to size_t (when setting GC_page_size). * os_dep.c (GC_unix_mmap_get_mem, GC_unmap_start, GC_remove_protection): Expand ROUNDUP_PAGESIZE macro but without value wrap-around checking (the argument is of word type). * os_dep.c (GC_unix_mmap_get_mem): Replace -GC_page_size with ~GC_page_size+1 (because GC_page_size is unsigned); remove redundant cast to size_t. * os_dep.c (GC_unix_sbrk_get_mem): Add explicit cast of GC_page_size to SBRK_ARG_T. * os_dep.c (GC_wince_get_mem): Change type of res_bytes local variable to size_t. * typd_mlc.c: Do not include limits.h. * typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Remove (as defined in gc_priv.h now).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: GC_debug_malloc_ignore_off_page(size_t lb, GC_EXTRA_PARAMS) { void * result = GC_malloc_ignore_off_page(lb + DEBUG_BYTES); if (result == 0) { GC_err_printf("GC_debug_malloc_ignore_off_page(%lu)" " returning NULL (%s:%d)\n", (unsigned long)lb, s, i); return(0); } if (!GC_debugging_started) { GC_start_debugging(); } ADD_CALL_CHAIN(result, ra); return (GC_store_debug_info(result, (word)lb, s, i)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix malloc routines to prevent size value wrap-around See issue #135 on Github. * allchblk.c (GC_allochblk, GC_allochblk_nth): Use OBJ_SZ_TO_BLOCKS_CHECKED instead of OBJ_SZ_TO_BLOCKS. * malloc.c (GC_alloc_large): Likewise. * alloc.c (GC_expand_hp_inner): Type of "bytes" local variable changed from word to size_t; cast ROUNDUP_PAGESIZE argument to size_t; prevent overflow when computing GC_heapsize+bytes > GC_max_heapsize. * dbg_mlc.c (GC_debug_malloc, GC_debug_malloc_ignore_off_page, GC_debug_malloc_atomic_ignore_off_page, GC_debug_generic_malloc, GC_debug_generic_malloc_inner, GC_debug_generic_malloc_inner_ignore_off_page, GC_debug_malloc_stubborn, GC_debug_malloc_atomic, GC_debug_malloc_uncollectable, GC_debug_malloc_atomic_uncollectable): Use SIZET_SAT_ADD (instead of "+" operator) to add extra bytes to lb value. * fnlz_mlc.c (GC_finalized_malloc): Likewise. * gcj_mlc.c (GC_debug_gcj_malloc): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, ROUNDUP_PAGESIZE): Likewise. * include/private/gcconfig.h (GET_MEM): Likewise. * mallocx.c (GC_malloc_many, GC_memalign): Likewise. * os_dep.c (GC_wince_get_mem, GC_win32_get_mem): Likewise. * typd_mlc.c (GC_malloc_explicitly_typed, GC_malloc_explicitly_typed_ignore_off_page, GC_calloc_explicitly_typed): Likewise. * headers.c (GC_scratch_alloc): Change type of bytes_to_get from word to size_t (because ROUNDUP_PAGESIZE_IF_MMAP result type changed). * include/private/gc_priv.h: Include limits.h (unless SIZE_MAX already defined). * include/private/gc_priv.h (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Move from malloc.c file. * include/private/gc_priv.h (SIZET_SAT_ADD): New macro (defined before include gcconfig.h). * include/private/gc_priv.h (EXTRA_BYTES, GC_page_size): Change type to size_t. * os_dep.c (GC_page_size): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, ROUNDUP_PAGESIZE): Add comment about the argument. * include/private/gcconfig.h (GET_MEM): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, OBJ_SZ_TO_BLOCKS, ROUNDUP_PAGESIZE, ROUNDUP_PAGESIZE_IF_MMAP): Rename argument to "lb". * include/private/gc_priv.h (OBJ_SZ_TO_BLOCKS_CHECKED): New macro. * include/private/gcconfig.h (GC_win32_get_mem, GC_wince_get_mem, GC_unix_get_mem): Change argument type from word to int. * os_dep.c (GC_unix_mmap_get_mem, GC_unix_get_mem, GC_unix_sbrk_get_mem, GC_wince_get_mem, GC_win32_get_mem): Likewise. * malloc.c (GC_alloc_large_and_clear): Call OBJ_SZ_TO_BLOCKS only if no value wrap around is guaranteed. * malloc.c (GC_generic_malloc): Do not check for lb_rounded < lb case (because ROUNDED_UP_GRANULES and GRANULES_TO_BYTES guarantees no value wrap around). * mallocx.c (GC_generic_malloc_ignore_off_page): Likewise. * misc.c (GC_init_size_map): Change "i" local variable type from int to size_t. * os_dep.c (GC_write_fault_handler, catch_exception_raise): Likewise. * misc.c (GC_envfile_init): Cast len to size_t when passed to ROUNDUP_PAGESIZE_IF_MMAP. * os_dep.c (GC_setpagesize): Cast GC_sysinfo.dwPageSize and GETPAGESIZE() to size_t (when setting GC_page_size). * os_dep.c (GC_unix_mmap_get_mem, GC_unmap_start, GC_remove_protection): Expand ROUNDUP_PAGESIZE macro but without value wrap-around checking (the argument is of word type). * os_dep.c (GC_unix_mmap_get_mem): Replace -GC_page_size with ~GC_page_size+1 (because GC_page_size is unsigned); remove redundant cast to size_t. * os_dep.c (GC_unix_sbrk_get_mem): Add explicit cast of GC_page_size to SBRK_ARG_T. * os_dep.c (GC_wince_get_mem): Change type of res_bytes local variable to size_t. * typd_mlc.c: Do not include limits.h. * typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Remove (as defined in gc_priv.h now).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: GC_API GC_ATTR_MALLOC void * GC_CALL GC_calloc_explicitly_typed(size_t n, size_t lb, GC_descr d) { word *op; size_t lg; GC_descr simple_descr; complex_descriptor *complex_descr; int descr_type; struct LeafDescriptor leaf; GC_ASSERT(GC_explicit_typing_initialized); descr_type = GC_make_array_descriptor((word)n, (word)lb, d, &simple_descr, &complex_descr, &leaf); if ((lb | n) > GC_SQRT_SIZE_MAX /* fast initial check */ && lb > 0 && n > GC_SIZE_MAX / lb) return NULL; /* n*lb overflow */ lb *= n; switch(descr_type) { case NO_MEM: return(0); case SIMPLE: return GC_malloc_explicitly_typed(lb, simple_descr); case LEAF: lb += sizeof(struct LeafDescriptor) + TYPD_EXTRA_BYTES; break; case COMPLEX: lb += TYPD_EXTRA_BYTES; break; } op = GC_malloc_kind(lb, GC_array_kind); if (EXPECT(NULL == op, FALSE)) return NULL; lg = SMALL_OBJ(lb) ? GC_size_map[lb] : BYTES_TO_GRANULES(GC_size(op)); if (descr_type == LEAF) { /* Set up the descriptor inside the object itself. */ volatile struct LeafDescriptor * lp = (struct LeafDescriptor *) (op + GRANULES_TO_WORDS(lg) - (BYTES_TO_WORDS(sizeof(struct LeafDescriptor)) + 1)); lp -> ld_tag = LEAF_TAG; lp -> ld_size = leaf.ld_size; lp -> ld_nelements = leaf.ld_nelements; lp -> ld_descriptor = leaf.ld_descriptor; ((volatile word *)op)[GRANULES_TO_WORDS(lg) - 1] = (word)lp; } else { # ifndef GC_NO_FINALIZATION size_t lw = GRANULES_TO_WORDS(lg); op[lw - 1] = (word)complex_descr; /* Make sure the descriptor is cleared once there is any danger */ /* it may have been collected. */ if (EXPECT(GC_general_register_disappearing_link( (void **)(op + lw - 1), op) == GC_NO_MEMORY, FALSE)) # endif { /* Couldn't register it due to lack of memory. Punt. */ /* This will probably fail too, but gives the recovery code */ /* a chance. */ return GC_malloc(lb); } } return op; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix malloc routines to prevent size value wrap-around See issue #135 on Github. * allchblk.c (GC_allochblk, GC_allochblk_nth): Use OBJ_SZ_TO_BLOCKS_CHECKED instead of OBJ_SZ_TO_BLOCKS. * malloc.c (GC_alloc_large): Likewise. * alloc.c (GC_expand_hp_inner): Type of "bytes" local variable changed from word to size_t; cast ROUNDUP_PAGESIZE argument to size_t; prevent overflow when computing GC_heapsize+bytes > GC_max_heapsize. * dbg_mlc.c (GC_debug_malloc, GC_debug_malloc_ignore_off_page, GC_debug_malloc_atomic_ignore_off_page, GC_debug_generic_malloc, GC_debug_generic_malloc_inner, GC_debug_generic_malloc_inner_ignore_off_page, GC_debug_malloc_stubborn, GC_debug_malloc_atomic, GC_debug_malloc_uncollectable, GC_debug_malloc_atomic_uncollectable): Use SIZET_SAT_ADD (instead of "+" operator) to add extra bytes to lb value. * fnlz_mlc.c (GC_finalized_malloc): Likewise. * gcj_mlc.c (GC_debug_gcj_malloc): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, ROUNDUP_PAGESIZE): Likewise. * include/private/gcconfig.h (GET_MEM): Likewise. * mallocx.c (GC_malloc_many, GC_memalign): Likewise. * os_dep.c (GC_wince_get_mem, GC_win32_get_mem): Likewise. * typd_mlc.c (GC_malloc_explicitly_typed, GC_malloc_explicitly_typed_ignore_off_page, GC_calloc_explicitly_typed): Likewise. * headers.c (GC_scratch_alloc): Change type of bytes_to_get from word to size_t (because ROUNDUP_PAGESIZE_IF_MMAP result type changed). * include/private/gc_priv.h: Include limits.h (unless SIZE_MAX already defined). * include/private/gc_priv.h (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Move from malloc.c file. * include/private/gc_priv.h (SIZET_SAT_ADD): New macro (defined before include gcconfig.h). * include/private/gc_priv.h (EXTRA_BYTES, GC_page_size): Change type to size_t. * os_dep.c (GC_page_size): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, ROUNDUP_PAGESIZE): Add comment about the argument. * include/private/gcconfig.h (GET_MEM): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, OBJ_SZ_TO_BLOCKS, ROUNDUP_PAGESIZE, ROUNDUP_PAGESIZE_IF_MMAP): Rename argument to "lb". * include/private/gc_priv.h (OBJ_SZ_TO_BLOCKS_CHECKED): New macro. * include/private/gcconfig.h (GC_win32_get_mem, GC_wince_get_mem, GC_unix_get_mem): Change argument type from word to int. * os_dep.c (GC_unix_mmap_get_mem, GC_unix_get_mem, GC_unix_sbrk_get_mem, GC_wince_get_mem, GC_win32_get_mem): Likewise. * malloc.c (GC_alloc_large_and_clear): Call OBJ_SZ_TO_BLOCKS only if no value wrap around is guaranteed. * malloc.c (GC_generic_malloc): Do not check for lb_rounded < lb case (because ROUNDED_UP_GRANULES and GRANULES_TO_BYTES guarantees no value wrap around). * mallocx.c (GC_generic_malloc_ignore_off_page): Likewise. * misc.c (GC_init_size_map): Change "i" local variable type from int to size_t. * os_dep.c (GC_write_fault_handler, catch_exception_raise): Likewise. * misc.c (GC_envfile_init): Cast len to size_t when passed to ROUNDUP_PAGESIZE_IF_MMAP. * os_dep.c (GC_setpagesize): Cast GC_sysinfo.dwPageSize and GETPAGESIZE() to size_t (when setting GC_page_size). * os_dep.c (GC_unix_mmap_get_mem, GC_unmap_start, GC_remove_protection): Expand ROUNDUP_PAGESIZE macro but without value wrap-around checking (the argument is of word type). * os_dep.c (GC_unix_mmap_get_mem): Replace -GC_page_size with ~GC_page_size+1 (because GC_page_size is unsigned); remove redundant cast to size_t. * os_dep.c (GC_unix_sbrk_get_mem): Add explicit cast of GC_page_size to SBRK_ARG_T. * os_dep.c (GC_wince_get_mem): Change type of res_bytes local variable to size_t. * typd_mlc.c: Do not include limits.h. * typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Remove (as defined in gc_priv.h now).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: catch_exception_raise(mach_port_t exception_port GC_ATTR_UNUSED, mach_port_t thread, mach_port_t task GC_ATTR_UNUSED, exception_type_t exception, exception_data_t code, mach_msg_type_number_t code_count GC_ATTR_UNUSED) { kern_return_t r; char *addr; struct hblk *h; unsigned int i; thread_state_flavor_t flavor = DARWIN_EXC_STATE; mach_msg_type_number_t exc_state_count = DARWIN_EXC_STATE_COUNT; DARWIN_EXC_STATE_T exc_state; if (exception != EXC_BAD_ACCESS || code[0] != KERN_PROTECTION_FAILURE) { # ifdef DEBUG_EXCEPTION_HANDLING /* We aren't interested, pass it on to the old handler */ GC_log_printf("Exception: 0x%x Code: 0x%x 0x%x in catch...\n", exception, code_count > 0 ? code[0] : -1, code_count > 1 ? code[1] : -1); # endif return FWD(); } r = thread_get_state(thread, flavor, (natural_t*)&exc_state, &exc_state_count); if(r != KERN_SUCCESS) { /* The thread is supposed to be suspended while the exception */ /* handler is called. This shouldn't fail. */ # ifdef BROKEN_EXCEPTION_HANDLING GC_err_printf("thread_get_state failed in catch_exception_raise\n"); return KERN_SUCCESS; # else ABORT("thread_get_state failed in catch_exception_raise"); # endif } /* This is the address that caused the fault */ addr = (char*) exc_state.DARWIN_EXC_STATE_DAR; if (HDR(addr) == 0) { /* Ugh... just like the SIGBUS problem above, it seems we get */ /* a bogus KERN_PROTECTION_FAILURE every once and a while. We wait */ /* till we get a bunch in a row before doing anything about it. */ /* If a "real" fault ever occurs it'll just keep faulting over and */ /* over and we'll hit the limit pretty quickly. */ # ifdef BROKEN_EXCEPTION_HANDLING static char *last_fault; static int last_fault_count; if(addr != last_fault) { last_fault = addr; last_fault_count = 0; } if(++last_fault_count < 32) { if(last_fault_count == 1) WARN("Ignoring KERN_PROTECTION_FAILURE at %p\n", addr); return KERN_SUCCESS; } GC_err_printf( "Unexpected KERN_PROTECTION_FAILURE at %p; aborting...\n", addr); /* Can't pass it along to the signal handler because that is */ /* ignoring SIGBUS signals. We also shouldn't call ABORT here as */ /* signals don't always work too well from the exception handler. */ EXIT(); # else /* BROKEN_EXCEPTION_HANDLING */ /* Pass it along to the next exception handler (which should call SIGBUS/SIGSEGV) */ return FWD(); # endif /* !BROKEN_EXCEPTION_HANDLING */ } # ifdef BROKEN_EXCEPTION_HANDLING /* Reset the number of consecutive SIGBUSs */ GC_sigbus_count = 0; # endif if (GC_mprotect_state == GC_MP_NORMAL) { /* common case */ h = (struct hblk*)((word)addr & ~(GC_page_size-1)); UNPROTECT(h, GC_page_size); for (i = 0; i < divHBLKSZ(GC_page_size); i++) { register int index = PHT_HASH(h+i); async_set_pht_entry_from_index(GC_dirty_pages, index); } } else if (GC_mprotect_state == GC_MP_DISCARDING) { /* Lie to the thread for now. No sense UNPROTECT()ing the memory when we're just going to PROTECT() it again later. The thread will just fault again once it resumes */ } else { /* Shouldn't happen, i don't think */ GC_err_printf("KERN_PROTECTION_FAILURE while world is stopped\n"); return FWD(); } return KERN_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix malloc routines to prevent size value wrap-around See issue #135 on Github. * allchblk.c (GC_allochblk, GC_allochblk_nth): Use OBJ_SZ_TO_BLOCKS_CHECKED instead of OBJ_SZ_TO_BLOCKS. * malloc.c (GC_alloc_large): Likewise. * alloc.c (GC_expand_hp_inner): Type of "bytes" local variable changed from word to size_t; cast ROUNDUP_PAGESIZE argument to size_t; prevent overflow when computing GC_heapsize+bytes > GC_max_heapsize. * dbg_mlc.c (GC_debug_malloc, GC_debug_malloc_ignore_off_page, GC_debug_malloc_atomic_ignore_off_page, GC_debug_generic_malloc, GC_debug_generic_malloc_inner, GC_debug_generic_malloc_inner_ignore_off_page, GC_debug_malloc_stubborn, GC_debug_malloc_atomic, GC_debug_malloc_uncollectable, GC_debug_malloc_atomic_uncollectable): Use SIZET_SAT_ADD (instead of "+" operator) to add extra bytes to lb value. * fnlz_mlc.c (GC_finalized_malloc): Likewise. * gcj_mlc.c (GC_debug_gcj_malloc): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, ROUNDUP_PAGESIZE): Likewise. * include/private/gcconfig.h (GET_MEM): Likewise. * mallocx.c (GC_malloc_many, GC_memalign): Likewise. * os_dep.c (GC_wince_get_mem, GC_win32_get_mem): Likewise. * typd_mlc.c (GC_malloc_explicitly_typed, GC_malloc_explicitly_typed_ignore_off_page, GC_calloc_explicitly_typed): Likewise. * headers.c (GC_scratch_alloc): Change type of bytes_to_get from word to size_t (because ROUNDUP_PAGESIZE_IF_MMAP result type changed). * include/private/gc_priv.h: Include limits.h (unless SIZE_MAX already defined). * include/private/gc_priv.h (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Move from malloc.c file. * include/private/gc_priv.h (SIZET_SAT_ADD): New macro (defined before include gcconfig.h). * include/private/gc_priv.h (EXTRA_BYTES, GC_page_size): Change type to size_t. * os_dep.c (GC_page_size): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, ROUNDUP_PAGESIZE): Add comment about the argument. * include/private/gcconfig.h (GET_MEM): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, OBJ_SZ_TO_BLOCKS, ROUNDUP_PAGESIZE, ROUNDUP_PAGESIZE_IF_MMAP): Rename argument to "lb". * include/private/gc_priv.h (OBJ_SZ_TO_BLOCKS_CHECKED): New macro. * include/private/gcconfig.h (GC_win32_get_mem, GC_wince_get_mem, GC_unix_get_mem): Change argument type from word to int. * os_dep.c (GC_unix_mmap_get_mem, GC_unix_get_mem, GC_unix_sbrk_get_mem, GC_wince_get_mem, GC_win32_get_mem): Likewise. * malloc.c (GC_alloc_large_and_clear): Call OBJ_SZ_TO_BLOCKS only if no value wrap around is guaranteed. * malloc.c (GC_generic_malloc): Do not check for lb_rounded < lb case (because ROUNDED_UP_GRANULES and GRANULES_TO_BYTES guarantees no value wrap around). * mallocx.c (GC_generic_malloc_ignore_off_page): Likewise. * misc.c (GC_init_size_map): Change "i" local variable type from int to size_t. * os_dep.c (GC_write_fault_handler, catch_exception_raise): Likewise. * misc.c (GC_envfile_init): Cast len to size_t when passed to ROUNDUP_PAGESIZE_IF_MMAP. * os_dep.c (GC_setpagesize): Cast GC_sysinfo.dwPageSize and GETPAGESIZE() to size_t (when setting GC_page_size). * os_dep.c (GC_unix_mmap_get_mem, GC_unmap_start, GC_remove_protection): Expand ROUNDUP_PAGESIZE macro but without value wrap-around checking (the argument is of word type). * os_dep.c (GC_unix_mmap_get_mem): Replace -GC_page_size with ~GC_page_size+1 (because GC_page_size is unsigned); remove redundant cast to size_t. * os_dep.c (GC_unix_sbrk_get_mem): Add explicit cast of GC_page_size to SBRK_ARG_T. * os_dep.c (GC_wince_get_mem): Change type of res_bytes local variable to size_t. * typd_mlc.c: Do not include limits.h. * typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Remove (as defined in gc_priv.h now).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: GC_API GC_ATTR_MALLOC void * GC_CALL GC_debug_malloc(size_t lb, GC_EXTRA_PARAMS) { void * result; /* Note that according to malloc() specification, if size is 0 then */ /* malloc() returns either NULL, or a unique pointer value that can */ /* later be successfully passed to free(). We always do the latter. */ result = GC_malloc(lb + DEBUG_BYTES); # ifdef GC_ADD_CALLER if (s == NULL) { GC_caller_func_offset(ra, &s, &i); } # endif if (result == 0) { GC_err_printf("GC_debug_malloc(%lu) returning NULL (%s:%d)\n", (unsigned long)lb, s, i); return(0); } if (!GC_debugging_started) { GC_start_debugging(); } ADD_CALL_CHAIN(result, ra); return (GC_store_debug_info(result, (word)lb, s, i)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix malloc routines to prevent size value wrap-around See issue #135 on Github. * allchblk.c (GC_allochblk, GC_allochblk_nth): Use OBJ_SZ_TO_BLOCKS_CHECKED instead of OBJ_SZ_TO_BLOCKS. * malloc.c (GC_alloc_large): Likewise. * alloc.c (GC_expand_hp_inner): Type of "bytes" local variable changed from word to size_t; cast ROUNDUP_PAGESIZE argument to size_t; prevent overflow when computing GC_heapsize+bytes > GC_max_heapsize. * dbg_mlc.c (GC_debug_malloc, GC_debug_malloc_ignore_off_page, GC_debug_malloc_atomic_ignore_off_page, GC_debug_generic_malloc, GC_debug_generic_malloc_inner, GC_debug_generic_malloc_inner_ignore_off_page, GC_debug_malloc_stubborn, GC_debug_malloc_atomic, GC_debug_malloc_uncollectable, GC_debug_malloc_atomic_uncollectable): Use SIZET_SAT_ADD (instead of "+" operator) to add extra bytes to lb value. * fnlz_mlc.c (GC_finalized_malloc): Likewise. * gcj_mlc.c (GC_debug_gcj_malloc): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, ROUNDUP_PAGESIZE): Likewise. * include/private/gcconfig.h (GET_MEM): Likewise. * mallocx.c (GC_malloc_many, GC_memalign): Likewise. * os_dep.c (GC_wince_get_mem, GC_win32_get_mem): Likewise. * typd_mlc.c (GC_malloc_explicitly_typed, GC_malloc_explicitly_typed_ignore_off_page, GC_calloc_explicitly_typed): Likewise. * headers.c (GC_scratch_alloc): Change type of bytes_to_get from word to size_t (because ROUNDUP_PAGESIZE_IF_MMAP result type changed). * include/private/gc_priv.h: Include limits.h (unless SIZE_MAX already defined). * include/private/gc_priv.h (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Move from malloc.c file. * include/private/gc_priv.h (SIZET_SAT_ADD): New macro (defined before include gcconfig.h). * include/private/gc_priv.h (EXTRA_BYTES, GC_page_size): Change type to size_t. * os_dep.c (GC_page_size): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, ROUNDUP_PAGESIZE): Add comment about the argument. * include/private/gcconfig.h (GET_MEM): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, OBJ_SZ_TO_BLOCKS, ROUNDUP_PAGESIZE, ROUNDUP_PAGESIZE_IF_MMAP): Rename argument to "lb". * include/private/gc_priv.h (OBJ_SZ_TO_BLOCKS_CHECKED): New macro. * include/private/gcconfig.h (GC_win32_get_mem, GC_wince_get_mem, GC_unix_get_mem): Change argument type from word to int. * os_dep.c (GC_unix_mmap_get_mem, GC_unix_get_mem, GC_unix_sbrk_get_mem, GC_wince_get_mem, GC_win32_get_mem): Likewise. * malloc.c (GC_alloc_large_and_clear): Call OBJ_SZ_TO_BLOCKS only if no value wrap around is guaranteed. * malloc.c (GC_generic_malloc): Do not check for lb_rounded < lb case (because ROUNDED_UP_GRANULES and GRANULES_TO_BYTES guarantees no value wrap around). * mallocx.c (GC_generic_malloc_ignore_off_page): Likewise. * misc.c (GC_init_size_map): Change "i" local variable type from int to size_t. * os_dep.c (GC_write_fault_handler, catch_exception_raise): Likewise. * misc.c (GC_envfile_init): Cast len to size_t when passed to ROUNDUP_PAGESIZE_IF_MMAP. * os_dep.c (GC_setpagesize): Cast GC_sysinfo.dwPageSize and GETPAGESIZE() to size_t (when setting GC_page_size). * os_dep.c (GC_unix_mmap_get_mem, GC_unmap_start, GC_remove_protection): Expand ROUNDUP_PAGESIZE macro but without value wrap-around checking (the argument is of word type). * os_dep.c (GC_unix_mmap_get_mem): Replace -GC_page_size with ~GC_page_size+1 (because GC_page_size is unsigned); remove redundant cast to size_t. * os_dep.c (GC_unix_sbrk_get_mem): Add explicit cast of GC_page_size to SBRK_ARG_T. * os_dep.c (GC_wince_get_mem): Change type of res_bytes local variable to size_t. * typd_mlc.c: Do not include limits.h. * typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Remove (as defined in gc_priv.h now).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: STATIC ptr_t GC_unix_mmap_get_mem(word bytes) { void *result; static ptr_t last_addr = HEAP_START; # ifndef USE_MMAP_ANON static GC_bool initialized = FALSE; if (!EXPECT(initialized, TRUE)) { # ifdef SYMBIAN char* path = GC_get_private_path_and_zero_file(); zero_fd = open(path, O_RDWR | O_CREAT, 0666); free(path); # else zero_fd = open("/dev/zero", O_RDONLY); # endif if (zero_fd == -1) ABORT("Could not open /dev/zero"); if (fcntl(zero_fd, F_SETFD, FD_CLOEXEC) == -1) WARN("Could not set FD_CLOEXEC for /dev/zero\n", 0); initialized = TRUE; } # endif if (bytes & (GC_page_size - 1)) ABORT("Bad GET_MEM arg"); result = mmap(last_addr, bytes, (PROT_READ | PROT_WRITE) | (GC_pages_executable ? PROT_EXEC : 0), GC_MMAP_FLAGS | OPT_MAP_ANON, zero_fd, 0/* offset */); # undef IGNORE_PAGES_EXECUTABLE if (result == MAP_FAILED) return(0); last_addr = (ptr_t)ROUNDUP_PAGESIZE((word)result + bytes); # if !defined(LINUX) if (last_addr == 0) { /* Oops. We got the end of the address space. This isn't */ /* usable by arbitrary C code, since one-past-end pointers */ /* don't work, so we discard it and try again. */ munmap(result, (size_t)(-GC_page_size) - (size_t)result); /* Leave last page mapped, so we can't repeat. */ return GC_unix_mmap_get_mem(bytes); } # else GC_ASSERT(last_addr != 0); # endif if (((word)result % HBLKSIZE) != 0) ABORT( "GC_unix_get_mem: Memory returned by mmap is not aligned to HBLKSIZE."); return((ptr_t)result); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix malloc routines to prevent size value wrap-around See issue #135 on Github. * allchblk.c (GC_allochblk, GC_allochblk_nth): Use OBJ_SZ_TO_BLOCKS_CHECKED instead of OBJ_SZ_TO_BLOCKS. * malloc.c (GC_alloc_large): Likewise. * alloc.c (GC_expand_hp_inner): Type of "bytes" local variable changed from word to size_t; cast ROUNDUP_PAGESIZE argument to size_t; prevent overflow when computing GC_heapsize+bytes > GC_max_heapsize. * dbg_mlc.c (GC_debug_malloc, GC_debug_malloc_ignore_off_page, GC_debug_malloc_atomic_ignore_off_page, GC_debug_generic_malloc, GC_debug_generic_malloc_inner, GC_debug_generic_malloc_inner_ignore_off_page, GC_debug_malloc_stubborn, GC_debug_malloc_atomic, GC_debug_malloc_uncollectable, GC_debug_malloc_atomic_uncollectable): Use SIZET_SAT_ADD (instead of "+" operator) to add extra bytes to lb value. * fnlz_mlc.c (GC_finalized_malloc): Likewise. * gcj_mlc.c (GC_debug_gcj_malloc): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, ROUNDUP_PAGESIZE): Likewise. * include/private/gcconfig.h (GET_MEM): Likewise. * mallocx.c (GC_malloc_many, GC_memalign): Likewise. * os_dep.c (GC_wince_get_mem, GC_win32_get_mem): Likewise. * typd_mlc.c (GC_malloc_explicitly_typed, GC_malloc_explicitly_typed_ignore_off_page, GC_calloc_explicitly_typed): Likewise. * headers.c (GC_scratch_alloc): Change type of bytes_to_get from word to size_t (because ROUNDUP_PAGESIZE_IF_MMAP result type changed). * include/private/gc_priv.h: Include limits.h (unless SIZE_MAX already defined). * include/private/gc_priv.h (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Move from malloc.c file. * include/private/gc_priv.h (SIZET_SAT_ADD): New macro (defined before include gcconfig.h). * include/private/gc_priv.h (EXTRA_BYTES, GC_page_size): Change type to size_t. * os_dep.c (GC_page_size): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, ROUNDUP_PAGESIZE): Add comment about the argument. * include/private/gcconfig.h (GET_MEM): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, OBJ_SZ_TO_BLOCKS, ROUNDUP_PAGESIZE, ROUNDUP_PAGESIZE_IF_MMAP): Rename argument to "lb". * include/private/gc_priv.h (OBJ_SZ_TO_BLOCKS_CHECKED): New macro. * include/private/gcconfig.h (GC_win32_get_mem, GC_wince_get_mem, GC_unix_get_mem): Change argument type from word to int. * os_dep.c (GC_unix_mmap_get_mem, GC_unix_get_mem, GC_unix_sbrk_get_mem, GC_wince_get_mem, GC_win32_get_mem): Likewise. * malloc.c (GC_alloc_large_and_clear): Call OBJ_SZ_TO_BLOCKS only if no value wrap around is guaranteed. * malloc.c (GC_generic_malloc): Do not check for lb_rounded < lb case (because ROUNDED_UP_GRANULES and GRANULES_TO_BYTES guarantees no value wrap around). * mallocx.c (GC_generic_malloc_ignore_off_page): Likewise. * misc.c (GC_init_size_map): Change "i" local variable type from int to size_t. * os_dep.c (GC_write_fault_handler, catch_exception_raise): Likewise. * misc.c (GC_envfile_init): Cast len to size_t when passed to ROUNDUP_PAGESIZE_IF_MMAP. * os_dep.c (GC_setpagesize): Cast GC_sysinfo.dwPageSize and GETPAGESIZE() to size_t (when setting GC_page_size). * os_dep.c (GC_unix_mmap_get_mem, GC_unmap_start, GC_remove_protection): Expand ROUNDUP_PAGESIZE macro but without value wrap-around checking (the argument is of word type). * os_dep.c (GC_unix_mmap_get_mem): Replace -GC_page_size with ~GC_page_size+1 (because GC_page_size is unsigned); remove redundant cast to size_t. * os_dep.c (GC_unix_sbrk_get_mem): Add explicit cast of GC_page_size to SBRK_ARG_T. * os_dep.c (GC_wince_get_mem): Change type of res_bytes local variable to size_t. * typd_mlc.c: Do not include limits.h. * typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Remove (as defined in gc_priv.h now).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form) { Buffer save; char *p; int spos, epos, rows, c_rows, pos, col = 0; Line *l; copyBuffer(&save, buf); gotoLine(buf, a->start.line); switch (form->type) { case FORM_TEXTAREA: case FORM_INPUT_TEXT: case FORM_INPUT_FILE: case FORM_INPUT_PASSWORD: case FORM_INPUT_CHECKBOX: case FORM_INPUT_RADIO: #ifdef MENU_SELECT case FORM_SELECT: #endif /* MENU_SELECT */ spos = a->start.pos; epos = a->end.pos; break; default: spos = a->start.pos + 1; epos = a->end.pos - 1; } switch (form->type) { case FORM_INPUT_CHECKBOX: case FORM_INPUT_RADIO: if (form->checked) buf->currentLine->lineBuf[spos] = '*'; else buf->currentLine->lineBuf[spos] = ' '; break; case FORM_INPUT_TEXT: case FORM_INPUT_FILE: case FORM_INPUT_PASSWORD: case FORM_TEXTAREA: #ifdef MENU_SELECT case FORM_SELECT: if (form->type == FORM_SELECT) { p = form->label->ptr; updateSelectOption(form, form->select_option); } else #endif /* MENU_SELECT */ if (!form->value) break; p = form->value->ptr; l = buf->currentLine; if (!l) break; if (form->type == FORM_TEXTAREA) { int n = a->y - buf->currentLine->linenumber; if (n > 0) for (; l && n; l = l->prev, n--) ; else if (n < 0) for (; l && n; l = l->prev, n++) ; if (!l) break; } rows = form->rows ? form->rows : 1; col = COLPOS(l, a->start.pos); for (c_rows = 0; c_rows < rows; c_rows++, l = l->next) { if (rows > 1) { pos = columnPos(l, col); a = retrieveAnchor(buf->formitem, l->linenumber, pos); if (a == NULL) break; spos = a->start.pos; epos = a->end.pos; } if (a->start.line != a->end.line || spos > epos || epos >= l->len) break; pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col, rows > 1, form->type == FORM_INPUT_PASSWORD); if (pos != epos) { shiftAnchorPosition(buf->href, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->name, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->img, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->formitem, buf->hmarklist, a->start.line, spos, pos - epos); } } break; } copyBuffer(buf, &save); arrangeLine(buf); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Prevent global-buffer-overflow write in formUpdateBuffer Bug-Debian: https://github.com/tats/w3m/issues/29'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: process_input(struct parsed_tag *tag) { int i = 20, v, x, y, z, iw, ih, size = 20; char *q, *p, *r, *p2, *s; Str tmp = NULL; char *qq = ""; int qlen = 0; if (cur_form_id < 0) { char *s = "<form_int method=internal action=none>"; tmp = process_form(parse_tag(&s, TRUE)); } if (tmp == NULL) tmp = Strnew(); p = "text"; parsedtag_get_value(tag, ATTR_TYPE, &p); q = NULL; parsedtag_get_value(tag, ATTR_VALUE, &q); r = ""; parsedtag_get_value(tag, ATTR_NAME, &r); parsedtag_get_value(tag, ATTR_SIZE, &size); if (size > MAX_INPUT_SIZE) size = MAX_INPUT_SIZE; parsedtag_get_value(tag, ATTR_MAXLENGTH, &i); p2 = NULL; parsedtag_get_value(tag, ATTR_ALT, &p2); x = parsedtag_exists(tag, ATTR_CHECKED); y = parsedtag_exists(tag, ATTR_ACCEPT); z = parsedtag_exists(tag, ATTR_READONLY); v = formtype(p); if (v == FORM_UNKNOWN) return NULL; if (!q) { switch (v) { case FORM_INPUT_IMAGE: case FORM_INPUT_SUBMIT: case FORM_INPUT_BUTTON: q = "SUBMIT"; break; case FORM_INPUT_RESET: q = "RESET"; break; /* if no VALUE attribute is specified in * <INPUT TYPE=CHECKBOX> tag, then the value "on" is used * as a default value. It is not a part of HTML4.0 * specification, but an imitation of Netscape behaviour. */ case FORM_INPUT_CHECKBOX: q = "on"; } } /* VALUE attribute is not allowed in <INPUT TYPE=FILE> tag. */ if (v == FORM_INPUT_FILE) q = NULL; if (q) { qq = html_quote(q); qlen = get_strwidth(q); } Strcat_charp(tmp, "<pre_int>"); switch (v) { case FORM_INPUT_PASSWORD: case FORM_INPUT_TEXT: case FORM_INPUT_FILE: case FORM_INPUT_CHECKBOX: if (displayLinkNumber) Strcat(tmp, getLinkNumberStr(0)); Strcat_char(tmp, '['); break; case FORM_INPUT_RADIO: if (displayLinkNumber) Strcat(tmp, getLinkNumberStr(0)); Strcat_char(tmp, '('); } Strcat(tmp, Sprintf("<input_alt hseq=\"%d\" fid=\"%d\" type=%s " "name=\"%s\" width=%d maxlength=%d value=\"%s\"", cur_hseq++, cur_form_id, p, html_quote(r), size, i, qq)); if (x) Strcat_charp(tmp, " checked"); if (y) Strcat_charp(tmp, " accept"); if (z) Strcat_charp(tmp, " readonly"); Strcat_char(tmp, '>'); if (v == FORM_INPUT_HIDDEN) Strcat_charp(tmp, "</input_alt></pre_int>"); else { switch (v) { case FORM_INPUT_PASSWORD: case FORM_INPUT_TEXT: case FORM_INPUT_FILE: Strcat_charp(tmp, "<u>"); break; case FORM_INPUT_IMAGE: s = NULL; parsedtag_get_value(tag, ATTR_SRC, &s); if (s) { Strcat(tmp, Sprintf("<img src=\"%s\"", html_quote(s))); if (p2) Strcat(tmp, Sprintf(" alt=\"%s\"", html_quote(p2))); if (parsedtag_get_value(tag, ATTR_WIDTH, &iw)) Strcat(tmp, Sprintf(" width=\"%d\"", iw)); if (parsedtag_get_value(tag, ATTR_HEIGHT, &ih)) Strcat(tmp, Sprintf(" height=\"%d\"", ih)); Strcat_charp(tmp, " pre_int>"); Strcat_charp(tmp, "</input_alt></pre_int>"); return tmp; } case FORM_INPUT_SUBMIT: case FORM_INPUT_BUTTON: case FORM_INPUT_RESET: if (displayLinkNumber) Strcat(tmp, getLinkNumberStr(-1)); Strcat_charp(tmp, "["); break; } switch (v) { case FORM_INPUT_PASSWORD: i = 0; if (q) { for (; i < qlen && i < size; i++) Strcat_char(tmp, '*'); } for (; i < size; i++) Strcat_char(tmp, ' '); break; case FORM_INPUT_TEXT: case FORM_INPUT_FILE: if (q) Strcat(tmp, textfieldrep(Strnew_charp(q), size)); else { for (i = 0; i < size; i++) Strcat_char(tmp, ' '); } break; case FORM_INPUT_SUBMIT: case FORM_INPUT_BUTTON: if (p2) Strcat_charp(tmp, html_quote(p2)); else Strcat_charp(tmp, qq); break; case FORM_INPUT_RESET: Strcat_charp(tmp, qq); break; case FORM_INPUT_RADIO: case FORM_INPUT_CHECKBOX: if (x) Strcat_char(tmp, '*'); else Strcat_char(tmp, ' '); break; } switch (v) { case FORM_INPUT_PASSWORD: case FORM_INPUT_TEXT: case FORM_INPUT_FILE: Strcat_charp(tmp, "</u>"); break; case FORM_INPUT_IMAGE: case FORM_INPUT_SUBMIT: case FORM_INPUT_BUTTON: case FORM_INPUT_RESET: Strcat_charp(tmp, "]"); } Strcat_charp(tmp, "</input_alt>"); switch (v) { case FORM_INPUT_PASSWORD: case FORM_INPUT_TEXT: case FORM_INPUT_FILE: case FORM_INPUT_CHECKBOX: Strcat_char(tmp, ']'); break; case FORM_INPUT_RADIO: Strcat_char(tmp, ')'); } Strcat_charp(tmp, "</pre_int>"); } return tmp; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Prevent segfault with malformed input type Bug-Debian: https://github.com/tats/w3m/issues/7'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form) { Buffer save; char *p; int spos, epos, rows, c_rows, pos, col = 0; Line *l; copyBuffer(&save, buf); gotoLine(buf, a->start.line); switch (form->type) { case FORM_TEXTAREA: case FORM_INPUT_TEXT: case FORM_INPUT_FILE: case FORM_INPUT_PASSWORD: case FORM_INPUT_CHECKBOX: case FORM_INPUT_RADIO: #ifdef MENU_SELECT case FORM_SELECT: #endif /* MENU_SELECT */ spos = a->start.pos; epos = a->end.pos; break; default: spos = a->start.pos + 1; epos = a->end.pos - 1; } switch (form->type) { case FORM_INPUT_CHECKBOX: case FORM_INPUT_RADIO: if (form->checked) buf->currentLine->lineBuf[spos] = '*'; else buf->currentLine->lineBuf[spos] = ' '; break; case FORM_INPUT_TEXT: case FORM_INPUT_FILE: case FORM_INPUT_PASSWORD: case FORM_TEXTAREA: #ifdef MENU_SELECT case FORM_SELECT: if (form->type == FORM_SELECT) { p = form->label->ptr; updateSelectOption(form, form->select_option); } else #endif /* MENU_SELECT */ p = form->value->ptr; l = buf->currentLine; if (!l) break; if (form->type == FORM_TEXTAREA) { int n = a->y - buf->currentLine->linenumber; if (n > 0) for (; l && n; l = l->prev, n--) ; else if (n < 0) for (; l && n; l = l->prev, n++) ; if (!l) break; } rows = form->rows ? form->rows : 1; col = COLPOS(l, a->start.pos); for (c_rows = 0; c_rows < rows; c_rows++, l = l->next) { if (rows > 1) { pos = columnPos(l, col); a = retrieveAnchor(buf->formitem, l->linenumber, pos); if (a == NULL) break; spos = a->start.pos; epos = a->end.pos; } if (a->start.line != a->end.line || spos > epos || epos > l->len) epos = spos; pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col, rows > 1, form->type == FORM_INPUT_PASSWORD); if (pos != epos) { shiftAnchorPosition(buf->href, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->name, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->img, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->formitem, buf->hmarklist, a->start.line, spos, pos - epos); } } break; } copyBuffer(buf, &save); arrangeLine(buf); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Prevent segfault for formUpdateBuffer Bug-Debian: https://github.com/tats/w3m/issues/13#issuecomment-242981906'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: process_form_int(struct parsed_tag *tag, int fid) { char *p, *q, *r, *s, *tg, *n; p = "get"; parsedtag_get_value(tag, ATTR_METHOD, &p); q = "!CURRENT_URL!"; parsedtag_get_value(tag, ATTR_ACTION, &q); q = url_encode(remove_space(q), cur_baseURL, cur_document_charset); r = NULL; #ifdef USE_M17N if (parsedtag_get_value(tag, ATTR_ACCEPT_CHARSET, &r)) r = check_accept_charset(r); if (!r && parsedtag_get_value(tag, ATTR_CHARSET, &r)) r = check_charset(r); #endif s = NULL; parsedtag_get_value(tag, ATTR_ENCTYPE, &s); tg = NULL; parsedtag_get_value(tag, ATTR_TARGET, &tg); n = NULL; parsedtag_get_value(tag, ATTR_NAME, &n); if (fid < 0) { form_max++; form_sp++; fid = form_max; } else { /* <form_int> */ if (form_max < fid) form_max = fid; form_sp = fid; } if (forms_size == 0) { forms_size = INITIAL_FORM_SIZE; forms = New_N(FormList *, forms_size); form_stack = NewAtom_N(int, forms_size); } else if (forms_size <= form_max) { forms_size += form_max; forms = New_Reuse(FormList *, forms, forms_size); form_stack = New_Reuse(int, form_stack, forms_size); } form_stack[form_sp] = fid; if (w3m_halfdump) { Str tmp = Sprintf("<form_int fid=\"%d\" action=\"%s\" method=\"%s\"", fid, html_quote(q), html_quote(p)); if (s) Strcat(tmp, Sprintf(" enctype=\"%s\"", html_quote(s))); if (tg) Strcat(tmp, Sprintf(" target=\"%s\"", html_quote(tg))); if (n) Strcat(tmp, Sprintf(" name=\"%s\"", html_quote(n))); #ifdef USE_M17N if (r) Strcat(tmp, Sprintf(" accept-charset=\"%s\"", html_quote(r))); #endif Strcat_charp(tmp, ">"); return tmp; } forms[fid] = newFormList(q, p, r, s, tg, n, NULL); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Prevent segfault with incorrect form_int fid Bug-Debian: https://github.com/tats/w3m/issues/15'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: HTMLtagproc1(struct parsed_tag *tag, struct html_feed_environ *h_env) { char *p, *q, *r; int i, w, x, y, z, count, width; struct readbuffer *obuf = h_env->obuf; struct environment *envs = h_env->envs; Str tmp; int hseq; int cmd; #ifdef ID_EXT char *id = NULL; #endif /* ID_EXT */ cmd = tag->tagid; if (obuf->flag & RB_PRE) { switch (cmd) { case HTML_NOBR: case HTML_N_NOBR: case HTML_PRE_INT: case HTML_N_PRE_INT: return 1; } } switch (cmd) { case HTML_B: obuf->in_bold++; if (obuf->in_bold > 1) return 1; return 0; case HTML_N_B: if (obuf->in_bold == 1 && close_effect0(obuf, HTML_B)) obuf->in_bold = 0; if (obuf->in_bold > 0) { obuf->in_bold--; if (obuf->in_bold == 0) return 0; } return 1; case HTML_I: obuf->in_italic++; if (obuf->in_italic > 1) return 1; return 0; case HTML_N_I: if (obuf->in_italic == 1 && close_effect0(obuf, HTML_I)) obuf->in_italic = 0; if (obuf->in_italic > 0) { obuf->in_italic--; if (obuf->in_italic == 0) return 0; } return 1; case HTML_U: obuf->in_under++; if (obuf->in_under > 1) return 1; return 0; case HTML_N_U: if (obuf->in_under == 1 && close_effect0(obuf, HTML_U)) obuf->in_under = 0; if (obuf->in_under > 0) { obuf->in_under--; if (obuf->in_under == 0) return 0; } return 1; case HTML_EM: HTMLlineproc1("<i>", h_env); return 1; case HTML_N_EM: HTMLlineproc1("</i>", h_env); return 1; case HTML_STRONG: HTMLlineproc1("<b>", h_env); return 1; case HTML_N_STRONG: HTMLlineproc1("</b>", h_env); return 1; case HTML_Q: HTMLlineproc1("`", h_env); return 1; case HTML_N_Q: HTMLlineproc1("'", h_env); return 1; case HTML_P: case HTML_N_P: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 1, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } obuf->flag |= RB_IGNORE_P; if (cmd == HTML_P) { set_alignment(obuf, tag); obuf->flag |= RB_P; } return 1; case HTML_BR: flushline(h_env, obuf, envs[h_env->envc].indent, 1, h_env->limit); h_env->blank_lines = 0; return 1; case HTML_H: if (!(obuf->flag & (RB_PREMODE | RB_IGNORE_P))) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } HTMLlineproc1("<b>", h_env); set_alignment(obuf, tag); return 1; case HTML_N_H: HTMLlineproc1("</b>", h_env); if (!(obuf->flag & RB_PREMODE)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); close_anchor(h_env, obuf); obuf->flag |= RB_IGNORE_P; return 1; case HTML_UL: case HTML_OL: case HTML_BLQ: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!(obuf->flag & RB_PREMODE) && (h_env->envc == 0 || cmd == HTML_BLQ)) do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } PUSH_ENV(cmd); if (cmd == HTML_UL || cmd == HTML_OL) { if (parsedtag_get_value(tag, ATTR_START, &count)) { envs[h_env->envc].count = count - 1; } } if (cmd == HTML_OL) { envs[h_env->envc].type = '1'; if (parsedtag_get_value(tag, ATTR_TYPE, &p)) { envs[h_env->envc].type = (int)*p; } } if (cmd == HTML_UL) envs[h_env->envc].type = ul_type(tag, 0); flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); return 1; case HTML_N_UL: case HTML_N_OL: case HTML_N_DL: case HTML_N_BLQ: CLOSE_DT; CLOSE_A; if (h_env->envc > 0) { flushline(h_env, obuf, envs[h_env->envc - 1].indent, 0, h_env->limit); POP_ENV; if (!(obuf->flag & RB_PREMODE) && (h_env->envc == 0 || cmd == HTML_N_DL || cmd == HTML_N_BLQ)) { do_blankline(h_env, obuf, envs[h_env->envc].indent, INDENT_INCR, h_env->limit); obuf->flag |= RB_IGNORE_P; } } close_anchor(h_env, obuf); return 1; case HTML_DL: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!(obuf->flag & RB_PREMODE)) do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } PUSH_ENV(cmd); if (parsedtag_exists(tag, ATTR_COMPACT)) envs[h_env->envc].env = HTML_DL_COMPACT; obuf->flag |= RB_IGNORE_P; return 1; case HTML_LI: CLOSE_A; CLOSE_DT; if (h_env->envc > 0) { Str num; flushline(h_env, obuf, envs[h_env->envc - 1].indent, 0, h_env->limit); envs[h_env->envc].count++; if (parsedtag_get_value(tag, ATTR_VALUE, &p)) { count = atoi(p); if (count > 0) envs[h_env->envc].count = count; else envs[h_env->envc].count = 0; } switch (envs[h_env->envc].env) { case HTML_UL: envs[h_env->envc].type = ul_type(tag, envs[h_env->envc].type); for (i = 0; i < INDENT_INCR - 3; i++) push_charp(obuf, 1, NBSP, PC_ASCII); tmp = Strnew(); switch (envs[h_env->envc].type) { case 'd': push_symbol(tmp, UL_SYMBOL_DISC, symbol_width, 1); break; case 'c': push_symbol(tmp, UL_SYMBOL_CIRCLE, symbol_width, 1); break; case 's': push_symbol(tmp, UL_SYMBOL_SQUARE, symbol_width, 1); break; default: push_symbol(tmp, UL_SYMBOL((h_env->envc_real - 1) % MAX_UL_LEVEL), symbol_width, 1); break; } if (symbol_width == 1) push_charp(obuf, 1, NBSP, PC_ASCII); push_str(obuf, symbol_width, tmp, PC_ASCII); push_charp(obuf, 1, NBSP, PC_ASCII); set_space_to_prevchar(obuf->prevchar); break; case HTML_OL: if (parsedtag_get_value(tag, ATTR_TYPE, &p)) envs[h_env->envc].type = (int)*p; switch ((envs[h_env->envc].count > 0)? envs[h_env->envc].type: '1') { case 'i': num = romanNumeral(envs[h_env->envc].count); break; case 'I': num = romanNumeral(envs[h_env->envc].count); Strupper(num); break; case 'a': num = romanAlphabet(envs[h_env->envc].count); break; case 'A': num = romanAlphabet(envs[h_env->envc].count); Strupper(num); break; default: num = Sprintf("%d", envs[h_env->envc].count); break; } if (INDENT_INCR >= 4) Strcat_charp(num, ". "); else Strcat_char(num, '.'); push_spaces(obuf, 1, INDENT_INCR - num->length); push_str(obuf, num->length, num, PC_ASCII); if (INDENT_INCR >= 4) set_space_to_prevchar(obuf->prevchar); break; default: push_spaces(obuf, 1, INDENT_INCR); break; } } else { flushline(h_env, obuf, 0, 0, h_env->limit); } obuf->flag |= RB_IGNORE_P; return 1; case HTML_DT: CLOSE_A; if (h_env->envc == 0 || (h_env->envc_real < h_env->nenv && envs[h_env->envc].env != HTML_DL && envs[h_env->envc].env != HTML_DL_COMPACT)) { PUSH_ENV(HTML_DL); } if (h_env->envc > 0) { flushline(h_env, obuf, envs[h_env->envc - 1].indent, 0, h_env->limit); } if (!(obuf->flag & RB_IN_DT)) { HTMLlineproc1("<b>", h_env); obuf->flag |= RB_IN_DT; } obuf->flag |= RB_IGNORE_P; return 1; case HTML_DD: CLOSE_A; CLOSE_DT; if (envs[h_env->envc].env == HTML_DL_COMPACT) { if (obuf->pos > envs[h_env->envc].indent) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); else push_spaces(obuf, 1, envs[h_env->envc].indent - obuf->pos); } else flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); /* obuf->flag |= RB_IGNORE_P; */ return 1; case HTML_TITLE: close_anchor(h_env, obuf); process_title(tag); obuf->flag |= RB_TITLE; obuf->end_tag = HTML_N_TITLE; return 1; case HTML_N_TITLE: if (!(obuf->flag & RB_TITLE)) return 1; obuf->flag &= ~RB_TITLE; obuf->end_tag = 0; tmp = process_n_title(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_TITLE_ALT: if (parsedtag_get_value(tag, ATTR_TITLE, &p)) h_env->title = html_unquote(p); return 0; case HTML_FRAMESET: PUSH_ENV(cmd); push_charp(obuf, 9, "--FRAME--", PC_ASCII); flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); return 0; case HTML_N_FRAMESET: if (h_env->envc > 0) { POP_ENV; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } return 0; case HTML_NOFRAMES: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= (RB_NOFRAMES | RB_IGNORE_P); /* istr = str; */ return 1; case HTML_N_NOFRAMES: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag &= ~RB_NOFRAMES; return 1; case HTML_FRAME: q = r = NULL; parsedtag_get_value(tag, ATTR_SRC, &q); parsedtag_get_value(tag, ATTR_NAME, &r); if (q) { q = html_quote(q); push_tag(obuf, Sprintf("<a hseq=\"%d\" href=\"%s\">", cur_hseq++, q)->ptr, HTML_A); if (r) q = html_quote(r); push_charp(obuf, get_strwidth(q), q, PC_ASCII); push_tag(obuf, "</a>", HTML_N_A); } flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); return 0; case HTML_HR: close_anchor(h_env, obuf); tmp = process_hr(tag, h_env->limit, envs[h_env->envc].indent); HTMLlineproc1(tmp->ptr, h_env); set_space_to_prevchar(obuf->prevchar); return 1; case HTML_PRE: x = parsedtag_exists(tag, ATTR_FOR_TABLE); CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!x) do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } else fillline(obuf, envs[h_env->envc].indent); obuf->flag |= (RB_PRE | RB_IGNORE_P); /* istr = str; */ return 1; case HTML_N_PRE: flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!(obuf->flag & RB_IGNORE_P)) { do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; h_env->blank_lines++; } obuf->flag &= ~RB_PRE; close_anchor(h_env, obuf); return 1; case HTML_PRE_INT: i = obuf->line->length; append_tags(obuf); if (!(obuf->flag & RB_SPECIAL)) { set_breakpoint(obuf, obuf->line->length - i); } obuf->flag |= RB_PRE_INT; return 0; case HTML_N_PRE_INT: push_tag(obuf, "</pre_int>", HTML_N_PRE_INT); obuf->flag &= ~RB_PRE_INT; if (!(obuf->flag & RB_SPECIAL) && obuf->pos > obuf->bp.pos) { set_prevchar(obuf->prevchar, "", 0); obuf->prev_ctype = PC_CTRL; } return 1; case HTML_NOBR: obuf->flag |= RB_NOBR; obuf->nobr_level++; return 0; case HTML_N_NOBR: if (obuf->nobr_level > 0) obuf->nobr_level--; if (obuf->nobr_level == 0) obuf->flag &= ~RB_NOBR; return 0; case HTML_PRE_PLAIN: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } obuf->flag |= (RB_PRE | RB_IGNORE_P); return 1; case HTML_N_PRE_PLAIN: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; } obuf->flag &= ~RB_PRE; return 1; case HTML_LISTING: case HTML_XMP: case HTML_PLAINTEXT: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } obuf->flag |= (RB_PLAIN | RB_IGNORE_P); switch (cmd) { case HTML_LISTING: obuf->end_tag = HTML_N_LISTING; break; case HTML_XMP: obuf->end_tag = HTML_N_XMP; break; case HTML_PLAINTEXT: obuf->end_tag = MAX_HTMLTAG; break; } return 1; case HTML_N_LISTING: case HTML_N_XMP: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; } obuf->flag &= ~RB_PLAIN; obuf->end_tag = 0; return 1; case HTML_SCRIPT: obuf->flag |= RB_SCRIPT; obuf->end_tag = HTML_N_SCRIPT; return 1; case HTML_STYLE: obuf->flag |= RB_STYLE; obuf->end_tag = HTML_N_STYLE; return 1; case HTML_N_SCRIPT: obuf->flag &= ~RB_SCRIPT; obuf->end_tag = 0; return 1; case HTML_N_STYLE: obuf->flag &= ~RB_STYLE; obuf->end_tag = 0; return 1; case HTML_A: if (obuf->anchor.url) close_anchor(h_env, obuf); hseq = 0; if (parsedtag_get_value(tag, ATTR_HREF, &p)) obuf->anchor.url = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_TARGET, &p)) obuf->anchor.target = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_REFERER, &p)) obuf->anchor.referer = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_TITLE, &p)) obuf->anchor.title = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_ACCESSKEY, &p)) obuf->anchor.accesskey = (unsigned char)*p; if (parsedtag_get_value(tag, ATTR_HSEQ, &hseq)) obuf->anchor.hseq = hseq; if (hseq == 0 && obuf->anchor.url) { obuf->anchor.hseq = cur_hseq; tmp = process_anchor(tag, h_env->tagbuf->ptr); push_tag(obuf, tmp->ptr, HTML_A); if (displayLinkNumber) HTMLlineproc1(getLinkNumberStr(-1)->ptr, h_env); return 1; } return 0; case HTML_N_A: close_anchor(h_env, obuf); return 1; case HTML_IMG: tmp = process_img(tag, h_env->limit); HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_IMG_ALT: if (parsedtag_get_value(tag, ATTR_SRC, &p)) obuf->img_alt = Strnew_charp(p); #ifdef USE_IMAGE i = 0; if (parsedtag_get_value(tag, ATTR_TOP_MARGIN, &i)) { if (i > obuf->top_margin) obuf->top_margin = i; } i = 0; if (parsedtag_get_value(tag, ATTR_BOTTOM_MARGIN, &i)) { if (i > obuf->bottom_margin) obuf->bottom_margin = i; } #endif return 0; case HTML_N_IMG_ALT: if (obuf->img_alt) { if (!close_effect0(obuf, HTML_IMG_ALT)) push_tag(obuf, "</img_alt>", HTML_N_IMG_ALT); obuf->img_alt = NULL; } return 1; case HTML_INPUT_ALT: i = 0; if (parsedtag_get_value(tag, ATTR_TOP_MARGIN, &i)) { if (i > obuf->top_margin) obuf->top_margin = i; } i = 0; if (parsedtag_get_value(tag, ATTR_BOTTOM_MARGIN, &i)) { if (i > obuf->bottom_margin) obuf->bottom_margin = i; } if (parsedtag_get_value(tag, ATTR_HSEQ, &hseq)) { obuf->input_alt.hseq = hseq; } if (parsedtag_get_value(tag, ATTR_FID, &i)) { obuf->input_alt.fid = i; } if (parsedtag_get_value(tag, ATTR_TYPE, &p)) { obuf->input_alt.type = Strnew_charp(p); } if (parsedtag_get_value(tag, ATTR_VALUE, &p)) { obuf->input_alt.value = Strnew_charp(p); } if (parsedtag_get_value(tag, ATTR_NAME, &p)) { obuf->input_alt.name = Strnew_charp(p); } obuf->input_alt.in = 1; return 0; case HTML_N_INPUT_ALT: if (obuf->input_alt.in) { if (!close_effect0(obuf, HTML_INPUT_ALT)) push_tag(obuf, "</input_alt>", HTML_N_INPUT_ALT); obuf->input_alt.hseq = 0; obuf->input_alt.fid = -1; obuf->input_alt.in = 0; obuf->input_alt.type = NULL; obuf->input_alt.name = NULL; obuf->input_alt.value = NULL; } return 1; case HTML_TABLE: close_anchor(h_env, obuf); obuf->table_level++; if (obuf->table_level >= MAX_TABLE) break; w = BORDER_NONE; /* x: cellspacing, y: cellpadding */ x = 2; y = 1; z = 0; width = 0; if (parsedtag_exists(tag, ATTR_BORDER)) { if (parsedtag_get_value(tag, ATTR_BORDER, &w)) { if (w > 2) w = BORDER_THICK; else if (w < 0) { /* weird */ w = BORDER_THIN; } } else w = BORDER_THIN; } if (DisplayBorders && w == BORDER_NONE) w = BORDER_THIN; if (parsedtag_get_value(tag, ATTR_WIDTH, &i)) { if (obuf->table_level == 0) width = REAL_WIDTH(i, h_env->limit - envs[h_env->envc].indent); else width = RELATIVE_WIDTH(i); } if (parsedtag_exists(tag, ATTR_HBORDER)) w = BORDER_NOWIN; #define MAX_CELLSPACING 1000 #define MAX_CELLPADDING 1000 #define MAX_VSPACE 1000 parsedtag_get_value(tag, ATTR_CELLSPACING, &x); parsedtag_get_value(tag, ATTR_CELLPADDING, &y); parsedtag_get_value(tag, ATTR_VSPACE, &z); if (x > MAX_CELLSPACING) x = MAX_CELLSPACING; if (y > MAX_CELLPADDING) y = MAX_CELLPADDING; if (z > MAX_VSPACE) z = MAX_VSPACE; #ifdef ID_EXT parsedtag_get_value(tag, ATTR_ID, &id); #endif /* ID_EXT */ tables[obuf->table_level] = begin_table(w, x, y, z); #ifdef ID_EXT if (id != NULL) tables[obuf->table_level]->id = Strnew_charp(id); #endif /* ID_EXT */ table_mode[obuf->table_level].pre_mode = 0; table_mode[obuf->table_level].indent_level = 0; table_mode[obuf->table_level].nobr_level = 0; table_mode[obuf->table_level].caption = 0; table_mode[obuf->table_level].end_tag = 0; /* HTML_UNKNOWN */ #ifndef TABLE_EXPAND tables[obuf->table_level]->total_width = width; #else tables[obuf->table_level]->real_width = width; tables[obuf->table_level]->total_width = 0; #endif return 1; case HTML_N_TABLE: /* should be processed in HTMLlineproc() */ return 1; case HTML_CENTER: CLOSE_A; if (!(obuf->flag & (RB_PREMODE | RB_IGNORE_P))) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_SAVE_FLAG(obuf); RB_SET_ALIGN(obuf, RB_CENTER); return 1; case HTML_N_CENTER: CLOSE_A; if (!(obuf->flag & RB_PREMODE)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); return 1; case HTML_DIV: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); set_alignment(obuf, tag); return 1; case HTML_N_DIV: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); return 1; case HTML_DIV_INT: CLOSE_P; if (!(obuf->flag & RB_IGNORE_P)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); set_alignment(obuf, tag); return 1; case HTML_N_DIV_INT: CLOSE_P; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); return 1; case HTML_FORM: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); tmp = process_form(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_N_FORM: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; process_n_form(); return 1; case HTML_INPUT: close_anchor(h_env, obuf); tmp = process_input(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_BUTTON: tmp = process_button(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_N_BUTTON: tmp = process_n_button(); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_SELECT: close_anchor(h_env, obuf); tmp = process_select(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); obuf->flag |= RB_INSELECT; obuf->end_tag = HTML_N_SELECT; return 1; case HTML_N_SELECT: obuf->flag &= ~RB_INSELECT; obuf->end_tag = 0; tmp = process_n_select(); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_OPTION: /* nothing */ return 1; case HTML_TEXTAREA: close_anchor(h_env, obuf); tmp = process_textarea(tag, h_env->limit); if (tmp) HTMLlineproc1(tmp->ptr, h_env); obuf->flag |= RB_INTXTA; obuf->end_tag = HTML_N_TEXTAREA; return 1; case HTML_N_TEXTAREA: obuf->flag &= ~RB_INTXTA; obuf->end_tag = 0; tmp = process_n_textarea(); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_ISINDEX: p = ""; q = "!CURRENT_URL!"; parsedtag_get_value(tag, ATTR_PROMPT, &p); parsedtag_get_value(tag, ATTR_ACTION, &q); tmp = Strnew_m_charp("<form method=get action=\"", html_quote(q), "\">", html_quote(p), "<input type=text name=\"\" accept></form>", NULL); HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_META: p = q = r = NULL; parsedtag_get_value(tag, ATTR_HTTP_EQUIV, &p); parsedtag_get_value(tag, ATTR_CONTENT, &q); #ifdef USE_M17N parsedtag_get_value(tag, ATTR_CHARSET, &r); if (r) { /* <meta charset=""> */ SKIP_BLANKS(r); meta_charset = wc_guess_charset(r, 0); } else if (p && q && !strcasecmp(p, "Content-Type") && (q = strcasestr(q, "charset")) != NULL) { q += 7; SKIP_BLANKS(q); if (*q == '=') { q++; SKIP_BLANKS(q); meta_charset = wc_guess_charset(q, 0); } } else #endif if (p && q && !strcasecmp(p, "refresh")) { int refresh_interval; tmp = NULL; refresh_interval = getMetaRefreshParam(q, &tmp); if (tmp) { q = html_quote(tmp->ptr); tmp = Sprintf("Refresh (%d sec) <a href=\"%s\">%s</a>", refresh_interval, q, q); } else if (refresh_interval > 0) tmp = Sprintf("Refresh (%d sec)", refresh_interval); if (tmp) { HTMLlineproc1(tmp->ptr, h_env); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!is_redisplay && !((obuf->flag & RB_NOFRAMES) && RenderFrame)) { tag->need_reconstruct = TRUE; return 0; } } } return 1; case HTML_BASE: #if defined(USE_M17N) || defined(USE_IMAGE) p = NULL; if (parsedtag_get_value(tag, ATTR_HREF, &p)) { cur_baseURL = New(ParsedURL); parseURL(p, cur_baseURL, NULL); } #endif case HTML_MAP: case HTML_N_MAP: case HTML_AREA: return 0; case HTML_DEL: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag |= RB_DEL; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>[DEL:</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: obuf->in_strike++; if (obuf->in_strike == 1) { push_tag(obuf, "<s>", HTML_S); } break; } return 1; case HTML_N_DEL: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag &= ~RB_DEL; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>:DEL]</U>", h_env); case DISPLAY_INS_DEL_FONTIFY: if (obuf->in_strike == 0) return 1; if (obuf->in_strike == 1 && close_effect0(obuf, HTML_S)) obuf->in_strike = 0; if (obuf->in_strike > 0) { obuf->in_strike--; if (obuf->in_strike == 0) { push_tag(obuf, "</s>", HTML_N_S); } } break; } return 1; case HTML_S: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag |= RB_S; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>[S:</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: obuf->in_strike++; if (obuf->in_strike == 1) { push_tag(obuf, "<s>", HTML_S); } break; } return 1; case HTML_N_S: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag &= ~RB_S; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>:S]</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: if (obuf->in_strike == 0) return 1; if (obuf->in_strike == 1 && close_effect0(obuf, HTML_S)) obuf->in_strike = 0; if (obuf->in_strike > 0) { obuf->in_strike--; if (obuf->in_strike == 0) { push_tag(obuf, "</s>", HTML_N_S); } } } return 1; case HTML_INS: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>[INS:</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: obuf->in_ins++; if (obuf->in_ins == 1) { push_tag(obuf, "<ins>", HTML_INS); } break; } return 1; case HTML_N_INS: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>:INS]</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: if (obuf->in_ins == 0) return 1; if (obuf->in_ins == 1 && close_effect0(obuf, HTML_INS)) obuf->in_ins = 0; if (obuf->in_ins > 0) { obuf->in_ins--; if (obuf->in_ins == 0) { push_tag(obuf, "</ins>", HTML_N_INS); } } break; } return 1; case HTML_SUP: if (!(obuf->flag & (RB_DEL | RB_S))) HTMLlineproc1("^", h_env); return 1; case HTML_N_SUP: return 1; case HTML_SUB: if (!(obuf->flag & (RB_DEL | RB_S))) HTMLlineproc1("[", h_env); return 1; case HTML_N_SUB: if (!(obuf->flag & (RB_DEL | RB_S))) HTMLlineproc1("]", h_env); return 1; case HTML_FONT: case HTML_N_FONT: case HTML_NOP: return 1; case HTML_BGSOUND: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_SRC, &p)) { Str s; q = html_quote(p); s = Sprintf("<A HREF=\"%s\">bgsound(%s)</A>", q, q); HTMLlineproc1(s->ptr, h_env); } } return 1; case HTML_EMBED: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_SRC, &p)) { Str s; q = html_quote(p); s = Sprintf("<A HREF=\"%s\">embed(%s)</A>", q, q); HTMLlineproc1(s->ptr, h_env); } } return 1; case HTML_APPLET: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_ARCHIVE, &p)) { Str s; q = html_quote(p); s = Sprintf("<A HREF=\"%s\">applet archive(%s)</A>", q, q); HTMLlineproc1(s->ptr, h_env); } } return 1; case HTML_BODY: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_BACKGROUND, &p)) { Str s; q = html_quote(p); s = Sprintf("<IMG SRC=\"%s\" ALT=\"bg image(%s)\"><BR>", q, q); HTMLlineproc1(s->ptr, h_env); } } case HTML_N_HEAD: if (obuf->flag & RB_TITLE) HTMLlineproc1("</title>", h_env); case HTML_HEAD: case HTML_N_BODY: return 1; default: /* obuf->prevchar = '\0'; */ return 0; } /* not reached */ return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-476'], 'message': 'Fix uninitialised values for <i> and <dd> Bug-Debian: https://github.com/tats/w3m/issues/16'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: flushline(struct html_feed_environ *h_env, struct readbuffer *obuf, int indent, int force, int width) { TextLineList *buf = h_env->buf; FILE *f = h_env->f; Str line = obuf->line, pass = NULL; char *hidden_anchor = NULL, *hidden_img = NULL, *hidden_bold = NULL, *hidden_under = NULL, *hidden_italic = NULL, *hidden_strike = NULL, *hidden_ins = NULL, *hidden_input = NULL, *hidden = NULL; #ifdef DEBUG if (w3m_debug) { FILE *df = fopen("zzzproc1", "a"); fprintf(df, "flushline(%s,%d,%d,%d)\n", obuf->line->ptr, indent, force, width); if (buf) { TextLineListItem *p; for (p = buf->first; p; p = p->next) { fprintf(df, "buf=\"%s\"\n", p->ptr->line->ptr); } } fclose(df); } #endif if (!(obuf->flag & (RB_SPECIAL & ~RB_NOBR)) && Strlastchar(line) == ' ') { Strshrink(line, 1); obuf->pos--; } append_tags(obuf); if (obuf->anchor.url) hidden = hidden_anchor = has_hidden_link(obuf, HTML_A); if (obuf->img_alt) { if ((hidden_img = has_hidden_link(obuf, HTML_IMG_ALT)) != NULL) { if (!hidden || hidden_img < hidden) hidden = hidden_img; } } if (obuf->input_alt.in) { if ((hidden_input = has_hidden_link(obuf, HTML_INPUT_ALT)) != NULL) { if (!hidden || hidden_input < hidden) hidden = hidden_input; } } if (obuf->in_bold) { if ((hidden_bold = has_hidden_link(obuf, HTML_B)) != NULL) { if (!hidden || hidden_bold < hidden) hidden = hidden_bold; } } if (obuf->in_italic) { if ((hidden_italic = has_hidden_link(obuf, HTML_I)) != NULL) { if (!hidden || hidden_italic < hidden) hidden = hidden_italic; } } if (obuf->in_under) { if ((hidden_under = has_hidden_link(obuf, HTML_U)) != NULL) { if (!hidden || hidden_under < hidden) hidden = hidden_under; } } if (obuf->in_strike) { if ((hidden_strike = has_hidden_link(obuf, HTML_S)) != NULL) { if (!hidden || hidden_strike < hidden) hidden = hidden_strike; } } if (obuf->in_ins) { if ((hidden_ins = has_hidden_link(obuf, HTML_INS)) != NULL) { if (!hidden || hidden_ins < hidden) hidden = hidden_ins; } } if (hidden) { pass = Strnew_charp(hidden); Strshrink(line, line->ptr + line->length - hidden); } if (!(obuf->flag & (RB_SPECIAL & ~RB_NOBR)) && obuf->pos > width) { char *tp = &line->ptr[obuf->bp.len - obuf->bp.tlen]; char *ep = &line->ptr[line->length]; if (obuf->bp.pos == obuf->pos && tp <= ep && tp > line->ptr && tp[-1] == ' ') { bcopy(tp, tp - 1, ep - tp + 1); line->length--; obuf->pos--; } } if (obuf->anchor.url && !hidden_anchor) Strcat_charp(line, "</a>"); if (obuf->img_alt && !hidden_img) Strcat_charp(line, "</img_alt>"); if (obuf->input_alt.in && !hidden_input) Strcat_charp(line, "</input_alt>"); if (obuf->in_bold && !hidden_bold) Strcat_charp(line, "</b>"); if (obuf->in_italic && !hidden_italic) Strcat_charp(line, "</i>"); if (obuf->in_under && !hidden_under) Strcat_charp(line, "</u>"); if (obuf->in_strike && !hidden_strike) Strcat_charp(line, "</s>"); if (obuf->in_ins && !hidden_ins) Strcat_charp(line, "</ins>"); if (obuf->top_margin > 0) { int i; struct html_feed_environ h; struct readbuffer o; struct environment e[1]; init_henv(&h, &o, e, 1, NULL, width, indent); o.line = Strnew_size(width + 20); o.pos = obuf->pos; o.flag = obuf->flag; o.top_margin = -1; o.bottom_margin = -1; Strcat_charp(o.line, "<pre_int>"); for (i = 0; i < o.pos; i++) Strcat_char(o.line, ' '); Strcat_charp(o.line, "</pre_int>"); for (i = 0; i < obuf->top_margin; i++) flushline(h_env, &o, indent, force, width); } if (force == 1 || obuf->flag & RB_NFLUSHED) { TextLine *lbuf = newTextLine(line, obuf->pos); if (RB_GET_ALIGN(obuf) == RB_CENTER) { align(lbuf, width, ALIGN_CENTER); } else if (RB_GET_ALIGN(obuf) == RB_RIGHT) { align(lbuf, width, ALIGN_RIGHT); } else if (RB_GET_ALIGN(obuf) == RB_LEFT && obuf->flag & RB_INTABLE) { align(lbuf, width, ALIGN_LEFT); } #ifdef FORMAT_NICE else if (obuf->flag & RB_FILL) { char *p; int rest, rrest; int nspace, d, i; rest = width - get_Str_strwidth(line); if (rest > 1) { nspace = 0; for (p = line->ptr + indent; *p; p++) { if (*p == ' ') nspace++; } if (nspace > 0) { int indent_here = 0; d = rest / nspace; p = line->ptr; while (IS_SPACE(*p)) { p++; indent_here++; } rrest = rest - d * nspace; line = Strnew_size(width + 1); for (i = 0; i < indent_here; i++) Strcat_char(line, ' '); for (; *p; p++) { Strcat_char(line, *p); if (*p == ' ') { for (i = 0; i < d; i++) Strcat_char(line, ' '); if (rrest > 0) { Strcat_char(line, ' '); rrest--; } } } lbuf = newTextLine(line, width); } } } #endif /* FORMAT_NICE */ #ifdef TABLE_DEBUG if (w3m_debug) { FILE *f = fopen("zzzproc1", "a"); fprintf(f, "pos=%d,%d, maxlimit=%d\n", visible_length(lbuf->line->ptr), lbuf->pos, h_env->maxlimit); fclose(f); } #endif if (lbuf->pos > h_env->maxlimit) h_env->maxlimit = lbuf->pos; if (buf) pushTextLine(buf, lbuf); else if (f) { Strfputs(Str_conv_to_halfdump(lbuf->line), f); fputc('\n', f); } if (obuf->flag & RB_SPECIAL || obuf->flag & RB_NFLUSHED) h_env->blank_lines = 0; else h_env->blank_lines++; } else { char *p = line->ptr, *q; Str tmp = Strnew(), tmp2 = Strnew(); #define APPEND(str) \ if (buf) \ appendTextLine(buf,(str),0); \ else if (f) \ Strfputs((str),f) while (*p) { q = p; if (sloppy_parse_line(&p)) { Strcat_charp_n(tmp, q, p - q); if (force == 2) { APPEND(tmp); } else Strcat(tmp2, tmp); Strclear(tmp); } } if (force == 2) { if (pass) { APPEND(pass); } pass = NULL; } else { if (pass) Strcat(tmp2, pass); pass = tmp2; } } if (obuf->bottom_margin > 0) { int i; struct html_feed_environ h; struct readbuffer o; struct environment e[1]; init_henv(&h, &o, e, 1, NULL, width, indent); o.line = Strnew_size(width + 20); o.pos = obuf->pos; o.flag = obuf->flag; o.top_margin = -1; o.bottom_margin = -1; Strcat_charp(o.line, "<pre_int>"); for (i = 0; i < o.pos; i++) Strcat_char(o.line, ' '); Strcat_charp(o.line, "</pre_int>"); for (i = 0; i < obuf->bottom_margin; i++) flushline(h_env, &o, indent, force, width); } if (obuf->top_margin < 0 || obuf->bottom_margin < 0) return; obuf->line = Strnew_size(256); obuf->pos = 0; obuf->top_margin = 0; obuf->bottom_margin = 0; set_space_to_prevchar(obuf->prevchar); obuf->bp.init_flag = 1; obuf->flag &= ~RB_NFLUSHED; set_breakpoint(obuf, 0); obuf->prev_ctype = PC_ASCII; link_stack = NULL; fillline(obuf, indent); if (pass) passthrough(obuf, pass->ptr, 0); if (!hidden_anchor && obuf->anchor.url) { Str tmp; if (obuf->anchor.hseq > 0) obuf->anchor.hseq = -obuf->anchor.hseq; tmp = Sprintf("<A HSEQ=\"%d\" HREF=\"", obuf->anchor.hseq); Strcat_charp(tmp, html_quote(obuf->anchor.url)); if (obuf->anchor.target) { Strcat_charp(tmp, "\" TARGET=\""); Strcat_charp(tmp, html_quote(obuf->anchor.target)); } if (obuf->anchor.referer) { Strcat_charp(tmp, "\" REFERER=\""); Strcat_charp(tmp, html_quote(obuf->anchor.referer)); } if (obuf->anchor.title) { Strcat_charp(tmp, "\" TITLE=\""); Strcat_charp(tmp, html_quote(obuf->anchor.title)); } if (obuf->anchor.accesskey) { char *c = html_quote_char(obuf->anchor.accesskey); Strcat_charp(tmp, "\" ACCESSKEY=\""); if (c) Strcat_charp(tmp, c); else Strcat_char(tmp, obuf->anchor.accesskey); } Strcat_charp(tmp, "\">"); push_tag(obuf, tmp->ptr, HTML_A); } if (!hidden_img && obuf->img_alt) { Str tmp = Strnew_charp("<IMG_ALT SRC=\""); Strcat_charp(tmp, html_quote(obuf->img_alt->ptr)); Strcat_charp(tmp, "\">"); push_tag(obuf, tmp->ptr, HTML_IMG_ALT); } if (!hidden_input && obuf->input_alt.in) { Str tmp; if (obuf->input_alt.hseq > 0) obuf->input_alt.hseq = - obuf->input_alt.hseq; tmp = Sprintf("<INPUT_ALT hseq=\"%d\" fid=\"%d\" name=\"%s\" type=\"%s\" value=\"%s\">", obuf->input_alt.hseq, obuf->input_alt.fid, obuf->input_alt.name->ptr, obuf->input_alt.type->ptr, obuf->input_alt.value->ptr); push_tag(obuf, tmp->ptr, HTML_INPUT_ALT); } if (!hidden_bold && obuf->in_bold) push_tag(obuf, "<B>", HTML_B); if (!hidden_italic && obuf->in_italic) push_tag(obuf, "<I>", HTML_I); if (!hidden_under && obuf->in_under) push_tag(obuf, "<U>", HTML_U); if (!hidden_strike && obuf->in_strike) push_tag(obuf, "<S>", HTML_S); if (!hidden_ins && obuf->in_ins) push_tag(obuf, "<INS>", HTML_INS); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Prevent segfault with malformed input_alt Bug-Debian: https://github.com/tats/w3m/issues/18'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: renderCoTable(struct table *tbl, int maxlimit) { struct readbuffer obuf; struct html_feed_environ h_env; struct environment envs[MAX_ENV_LEVEL]; struct table *t; int i, col, row; int indent, maxwidth; if (cotable_level >= MAX_COTABLE_LEVEL) return; /* workaround to prevent infinite recursion */ cotable_level++; for (i = 0; i < tbl->ntable; i++) { t = tbl->tables[i].ptr; col = tbl->tables[i].col; row = tbl->tables[i].row; indent = tbl->tables[i].indent; init_henv(&h_env, &obuf, envs, MAX_ENV_LEVEL, tbl->tables[i].buf, get_spec_cell_width(tbl, row, col), indent); check_row(tbl, row); if (h_env.limit > maxlimit) h_env.limit = maxlimit; if (t->total_width == 0) maxwidth = h_env.limit - indent; else if (t->total_width > 0) maxwidth = t->total_width; else maxwidth = t->total_width = -t->total_width * h_env.limit / 100; renderTable(t, maxwidth, &h_env); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Prevent deref null pointer in renderCoTable() Bug-Debian: https://github.com/tats/w3m/issues/20#issuecomment-260649537'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: do_refill(struct table *tbl, int row, int col, int maxlimit) { TextList *orgdata; TextListItem *l; struct readbuffer obuf; struct html_feed_environ h_env; struct environment envs[MAX_ENV_LEVEL]; int colspan, icell; if (tbl->tabdata[row] == NULL || tbl->tabdata[row][col] == NULL) return; orgdata = (TextList *)tbl->tabdata[row][col]; tbl->tabdata[row][col] = newGeneralList(); init_henv(&h_env, &obuf, envs, MAX_ENV_LEVEL, (TextLineList *)tbl->tabdata[row][col], get_spec_cell_width(tbl, row, col), 0); obuf.flag |= RB_INTABLE; if (h_env.limit > maxlimit) h_env.limit = maxlimit; if (tbl->border_mode != BORDER_NONE && tbl->vcellpadding > 0) do_blankline(&h_env, &obuf, 0, 0, h_env.limit); for (l = orgdata->first; l != NULL; l = l->next) { if (TAG_IS(l->ptr, "<table_alt", 10)) { int id = -1; char *p = l->ptr; struct parsed_tag *tag; if ((tag = parse_tag(&p, TRUE)) != NULL) parsedtag_get_value(tag, ATTR_TID, &id); if (id >= 0 && id < tbl->ntable) { int alignment; TextLineListItem *ti; struct table *t = tbl->tables[id].ptr; int limit = tbl->tables[id].indent + t->total_width; tbl->tables[id].ptr = NULL; save_fonteffect(&h_env, h_env.obuf); flushline(&h_env, &obuf, 0, 2, h_env.limit); if (t->vspace > 0 && !(obuf.flag & RB_IGNORE_P)) do_blankline(&h_env, &obuf, 0, 0, h_env.limit); if (RB_GET_ALIGN(h_env.obuf) == RB_CENTER) alignment = ALIGN_CENTER; else if (RB_GET_ALIGN(h_env.obuf) == RB_RIGHT) alignment = ALIGN_RIGHT; else alignment = ALIGN_LEFT; if (alignment != ALIGN_LEFT) { for (ti = tbl->tables[id].buf->first; ti != NULL; ti = ti->next) align(ti->ptr, h_env.limit, alignment); } appendTextLineList(h_env.buf, tbl->tables[id].buf); if (h_env.maxlimit < limit) h_env.maxlimit = limit; restore_fonteffect(&h_env, h_env.obuf); obuf.flag &= ~RB_IGNORE_P; h_env.blank_lines = 0; if (t->vspace > 0) { do_blankline(&h_env, &obuf, 0, 0, h_env.limit); obuf.flag |= RB_IGNORE_P; } } } else HTMLlineproc1(l->ptr, &h_env); } if (obuf.status != R_ST_NORMAL) { obuf.status = R_ST_EOL; HTMLlineproc1("\n", &h_env); } completeHTMLstream(&h_env, &obuf); flushline(&h_env, &obuf, 0, 2, h_env.limit); if (tbl->border_mode == BORDER_NONE) { int rowspan = table_rowspan(tbl, row, col); if (row + rowspan <= tbl->maxrow) { if (tbl->vcellpadding > 0 && !(obuf.flag & RB_IGNORE_P)) do_blankline(&h_env, &obuf, 0, 0, h_env.limit); } else { if (tbl->vspace > 0) purgeline(&h_env); } } else { if (tbl->vcellpadding > 0) { if (!(obuf.flag & RB_IGNORE_P)) do_blankline(&h_env, &obuf, 0, 0, h_env.limit); } else purgeline(&h_env); } if ((colspan = table_colspan(tbl, row, col)) > 1) { struct table_cell *cell = &tbl->cell; int k; k = bsearch_2short(colspan, cell->colspan, col, cell->col, MAXCOL, cell->index, cell->maxcell + 1); icell = cell->index[k]; if (cell->minimum_width[icell] < h_env.maxlimit) cell->minimum_width[icell] = h_env.maxlimit; } else { if (tbl->minimum_width[col] < h_env.maxlimit) tbl->minimum_width[col] = h_env.maxlimit; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Prevent segfault with malformed table_alt Bug-Debian: https://github.com/tats/w3m/issues/24'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form) { Buffer save; char *p; int spos, epos, rows, c_rows, pos, col = 0; Line *l; copyBuffer(&save, buf); gotoLine(buf, a->start.line); switch (form->type) { case FORM_TEXTAREA: case FORM_INPUT_TEXT: case FORM_INPUT_FILE: case FORM_INPUT_PASSWORD: case FORM_INPUT_CHECKBOX: case FORM_INPUT_RADIO: #ifdef MENU_SELECT case FORM_SELECT: #endif /* MENU_SELECT */ spos = a->start.pos; epos = a->end.pos; break; default: spos = a->start.pos + 1; epos = a->end.pos - 1; } switch (form->type) { case FORM_INPUT_CHECKBOX: case FORM_INPUT_RADIO: if (spos >= buf->currentLine->len || spos < 0) break; if (form->checked) buf->currentLine->lineBuf[spos] = '*'; else buf->currentLine->lineBuf[spos] = ' '; break; case FORM_INPUT_TEXT: case FORM_INPUT_FILE: case FORM_INPUT_PASSWORD: case FORM_TEXTAREA: #ifdef MENU_SELECT case FORM_SELECT: if (form->type == FORM_SELECT) { p = form->label->ptr; updateSelectOption(form, form->select_option); } else #endif /* MENU_SELECT */ if (!form->value) break; p = form->value->ptr; l = buf->currentLine; if (!l) break; if (form->type == FORM_TEXTAREA) { int n = a->y - buf->currentLine->linenumber; if (n > 0) for (; l && n; l = l->prev, n--) ; else if (n < 0) for (; l && n; l = l->prev, n++) ; if (!l) break; } rows = form->rows ? form->rows : 1; col = COLPOS(l, a->start.pos); for (c_rows = 0; c_rows < rows; c_rows++, l = l->next) { if (rows > 1) { pos = columnPos(l, col); a = retrieveAnchor(buf->formitem, l->linenumber, pos); if (a == NULL) break; spos = a->start.pos; epos = a->end.pos; } if (a->start.line != a->end.line || spos > epos || epos >= l->len || spos < 0 || epos < 0) break; pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col, rows > 1, form->type == FORM_INPUT_PASSWORD); if (pos != epos) { shiftAnchorPosition(buf->href, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->name, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->img, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->formitem, buf->hmarklist, a->start.line, spos, pos - epos); } } break; } copyBuffer(buf, &save); arrangeLine(buf); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix incorrect dereference in formUpdateBuffer when MENU_SELECT cf. https://github.com/tats/w3m/commit/ec9eb22e008a69ea9dc21fdca4b9b836679965ee'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: HTMLtagproc1(struct parsed_tag *tag, struct html_feed_environ *h_env) { char *p, *q, *r; int i, w, x, y, z, count, width; struct readbuffer *obuf = h_env->obuf; struct environment *envs = h_env->envs; Str tmp; int hseq; int cmd; #ifdef ID_EXT char *id = NULL; #endif /* ID_EXT */ cmd = tag->tagid; if (obuf->flag & RB_PRE) { switch (cmd) { case HTML_NOBR: case HTML_N_NOBR: case HTML_PRE_INT: case HTML_N_PRE_INT: return 1; } } switch (cmd) { case HTML_B: obuf->in_bold++; if (obuf->in_bold > 1) return 1; return 0; case HTML_N_B: if (obuf->in_bold == 1 && close_effect0(obuf, HTML_B)) obuf->in_bold = 0; if (obuf->in_bold > 0) { obuf->in_bold--; if (obuf->in_bold == 0) return 0; } return 1; case HTML_I: obuf->in_italic++; if (obuf->in_italic > 1) return 1; return 0; case HTML_N_I: if (obuf->in_italic == 1 && close_effect0(obuf, HTML_I)) obuf->in_italic = 0; if (obuf->in_italic > 0) { obuf->in_italic--; if (obuf->in_italic == 0) return 0; } return 1; case HTML_U: obuf->in_under++; if (obuf->in_under > 1) return 1; return 0; case HTML_N_U: if (obuf->in_under == 1 && close_effect0(obuf, HTML_U)) obuf->in_under = 0; if (obuf->in_under > 0) { obuf->in_under--; if (obuf->in_under == 0) return 0; } return 1; case HTML_EM: HTMLlineproc1("<i>", h_env); return 1; case HTML_N_EM: HTMLlineproc1("</i>", h_env); return 1; case HTML_STRONG: HTMLlineproc1("<b>", h_env); return 1; case HTML_N_STRONG: HTMLlineproc1("</b>", h_env); return 1; case HTML_Q: HTMLlineproc1("`", h_env); return 1; case HTML_N_Q: HTMLlineproc1("'", h_env); return 1; case HTML_P: case HTML_N_P: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 1, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } obuf->flag |= RB_IGNORE_P; if (cmd == HTML_P) { set_alignment(obuf, tag); obuf->flag |= RB_P; } return 1; case HTML_BR: flushline(h_env, obuf, envs[h_env->envc].indent, 1, h_env->limit); h_env->blank_lines = 0; return 1; case HTML_H: if (!(obuf->flag & (RB_PREMODE | RB_IGNORE_P))) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } HTMLlineproc1("<b>", h_env); set_alignment(obuf, tag); return 1; case HTML_N_H: HTMLlineproc1("</b>", h_env); if (!(obuf->flag & RB_PREMODE)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); close_anchor(h_env, obuf); obuf->flag |= RB_IGNORE_P; return 1; case HTML_UL: case HTML_OL: case HTML_BLQ: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!(obuf->flag & RB_PREMODE) && (h_env->envc == 0 || cmd == HTML_BLQ)) do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } PUSH_ENV(cmd); if (cmd == HTML_UL || cmd == HTML_OL) { if (parsedtag_get_value(tag, ATTR_START, &count)) { envs[h_env->envc].count = count - 1; } } if (cmd == HTML_OL) { envs[h_env->envc].type = '1'; if (parsedtag_get_value(tag, ATTR_TYPE, &p)) { envs[h_env->envc].type = (int)*p; } } if (cmd == HTML_UL) envs[h_env->envc].type = ul_type(tag, 0); flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); return 1; case HTML_N_UL: case HTML_N_OL: case HTML_N_DL: case HTML_N_BLQ: CLOSE_DT; CLOSE_A; if (h_env->envc > 0) { flushline(h_env, obuf, envs[h_env->envc - 1].indent, 0, h_env->limit); POP_ENV; if (!(obuf->flag & RB_PREMODE) && (h_env->envc == 0 || cmd == HTML_N_DL || cmd == HTML_N_BLQ)) { do_blankline(h_env, obuf, envs[h_env->envc].indent, INDENT_INCR, h_env->limit); obuf->flag |= RB_IGNORE_P; } } close_anchor(h_env, obuf); return 1; case HTML_DL: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!(obuf->flag & RB_PREMODE)) do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } PUSH_ENV(cmd); if (parsedtag_exists(tag, ATTR_COMPACT)) envs[h_env->envc].env = HTML_DL_COMPACT; obuf->flag |= RB_IGNORE_P; return 1; case HTML_LI: CLOSE_A; CLOSE_DT; if (h_env->envc > 0) { Str num; flushline(h_env, obuf, envs[h_env->envc - 1].indent, 0, h_env->limit); envs[h_env->envc].count++; if (parsedtag_get_value(tag, ATTR_VALUE, &p)) { count = atoi(p); if (count > 0) envs[h_env->envc].count = count; else envs[h_env->envc].count = 0; } switch (envs[h_env->envc].env) { case HTML_UL: envs[h_env->envc].type = ul_type(tag, envs[h_env->envc].type); for (i = 0; i < INDENT_INCR - 3; i++) push_charp(obuf, 1, NBSP, PC_ASCII); tmp = Strnew(); switch (envs[h_env->envc].type) { case 'd': push_symbol(tmp, UL_SYMBOL_DISC, symbol_width, 1); break; case 'c': push_symbol(tmp, UL_SYMBOL_CIRCLE, symbol_width, 1); break; case 's': push_symbol(tmp, UL_SYMBOL_SQUARE, symbol_width, 1); break; default: push_symbol(tmp, UL_SYMBOL((h_env->envc_real - 1) % MAX_UL_LEVEL), symbol_width, 1); break; } if (symbol_width == 1) push_charp(obuf, 1, NBSP, PC_ASCII); push_str(obuf, symbol_width, tmp, PC_ASCII); push_charp(obuf, 1, NBSP, PC_ASCII); set_space_to_prevchar(obuf->prevchar); break; case HTML_OL: if (parsedtag_get_value(tag, ATTR_TYPE, &p)) envs[h_env->envc].type = (int)*p; switch ((envs[h_env->envc].count > 0)? envs[h_env->envc].type: '1') { case 'i': num = romanNumeral(envs[h_env->envc].count); break; case 'I': num = romanNumeral(envs[h_env->envc].count); Strupper(num); break; case 'a': num = romanAlphabet(envs[h_env->envc].count); break; case 'A': num = romanAlphabet(envs[h_env->envc].count); Strupper(num); break; default: num = Sprintf("%d", envs[h_env->envc].count); break; } if (INDENT_INCR >= 4) Strcat_charp(num, ". "); else Strcat_char(num, '.'); push_spaces(obuf, 1, INDENT_INCR - num->length); push_str(obuf, num->length, num, PC_ASCII); if (INDENT_INCR >= 4) set_space_to_prevchar(obuf->prevchar); break; default: push_spaces(obuf, 1, INDENT_INCR); break; } } else { flushline(h_env, obuf, 0, 0, h_env->limit); } obuf->flag |= RB_IGNORE_P; return 1; case HTML_DT: CLOSE_A; if (h_env->envc == 0 || (h_env->envc_real < h_env->nenv && envs[h_env->envc].env != HTML_DL && envs[h_env->envc].env != HTML_DL_COMPACT)) { PUSH_ENV(HTML_DL); } if (h_env->envc > 0) { flushline(h_env, obuf, envs[h_env->envc - 1].indent, 0, h_env->limit); } if (!(obuf->flag & RB_IN_DT)) { HTMLlineproc1("<b>", h_env); obuf->flag |= RB_IN_DT; } obuf->flag |= RB_IGNORE_P; return 1; case HTML_DD: CLOSE_A; CLOSE_DT; if (h_env->envc == 0 || (h_env->envc_real < h_env->nenv && envs[h_env->envc].env != HTML_DL && envs[h_env->envc].env != HTML_DL_COMPACT)) { PUSH_ENV(HTML_DL); } if (envs[h_env->envc].env == HTML_DL_COMPACT) { if (obuf->pos > envs[h_env->envc].indent) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); else push_spaces(obuf, 1, envs[h_env->envc].indent - obuf->pos); } else flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); /* obuf->flag |= RB_IGNORE_P; */ return 1; case HTML_TITLE: close_anchor(h_env, obuf); process_title(tag); obuf->flag |= RB_TITLE; obuf->end_tag = HTML_N_TITLE; return 1; case HTML_N_TITLE: if (!(obuf->flag & RB_TITLE)) return 1; obuf->flag &= ~RB_TITLE; obuf->end_tag = 0; tmp = process_n_title(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_TITLE_ALT: if (parsedtag_get_value(tag, ATTR_TITLE, &p)) h_env->title = html_unquote(p); return 0; case HTML_FRAMESET: PUSH_ENV(cmd); push_charp(obuf, 9, "--FRAME--", PC_ASCII); flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); return 0; case HTML_N_FRAMESET: if (h_env->envc > 0) { POP_ENV; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } return 0; case HTML_NOFRAMES: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= (RB_NOFRAMES | RB_IGNORE_P); /* istr = str; */ return 1; case HTML_N_NOFRAMES: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag &= ~RB_NOFRAMES; return 1; case HTML_FRAME: q = r = NULL; parsedtag_get_value(tag, ATTR_SRC, &q); parsedtag_get_value(tag, ATTR_NAME, &r); if (q) { q = html_quote(q); push_tag(obuf, Sprintf("<a hseq=\"%d\" href=\"%s\">", cur_hseq++, q)->ptr, HTML_A); if (r) q = html_quote(r); push_charp(obuf, get_strwidth(q), q, PC_ASCII); push_tag(obuf, "</a>", HTML_N_A); } flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); return 0; case HTML_HR: close_anchor(h_env, obuf); tmp = process_hr(tag, h_env->limit, envs[h_env->envc].indent); HTMLlineproc1(tmp->ptr, h_env); set_space_to_prevchar(obuf->prevchar); return 1; case HTML_PRE: x = parsedtag_exists(tag, ATTR_FOR_TABLE); CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!x) do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } else fillline(obuf, envs[h_env->envc].indent); obuf->flag |= (RB_PRE | RB_IGNORE_P); /* istr = str; */ return 1; case HTML_N_PRE: flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!(obuf->flag & RB_IGNORE_P)) { do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; h_env->blank_lines++; } obuf->flag &= ~RB_PRE; close_anchor(h_env, obuf); return 1; case HTML_PRE_INT: i = obuf->line->length; append_tags(obuf); if (!(obuf->flag & RB_SPECIAL)) { set_breakpoint(obuf, obuf->line->length - i); } obuf->flag |= RB_PRE_INT; return 0; case HTML_N_PRE_INT: push_tag(obuf, "</pre_int>", HTML_N_PRE_INT); obuf->flag &= ~RB_PRE_INT; if (!(obuf->flag & RB_SPECIAL) && obuf->pos > obuf->bp.pos) { set_prevchar(obuf->prevchar, "", 0); obuf->prev_ctype = PC_CTRL; } return 1; case HTML_NOBR: obuf->flag |= RB_NOBR; obuf->nobr_level++; return 0; case HTML_N_NOBR: if (obuf->nobr_level > 0) obuf->nobr_level--; if (obuf->nobr_level == 0) obuf->flag &= ~RB_NOBR; return 0; case HTML_PRE_PLAIN: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } obuf->flag |= (RB_PRE | RB_IGNORE_P); return 1; case HTML_N_PRE_PLAIN: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; } obuf->flag &= ~RB_PRE; return 1; case HTML_LISTING: case HTML_XMP: case HTML_PLAINTEXT: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } obuf->flag |= (RB_PLAIN | RB_IGNORE_P); switch (cmd) { case HTML_LISTING: obuf->end_tag = HTML_N_LISTING; break; case HTML_XMP: obuf->end_tag = HTML_N_XMP; break; case HTML_PLAINTEXT: obuf->end_tag = MAX_HTMLTAG; break; } return 1; case HTML_N_LISTING: case HTML_N_XMP: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; } obuf->flag &= ~RB_PLAIN; obuf->end_tag = 0; return 1; case HTML_SCRIPT: obuf->flag |= RB_SCRIPT; obuf->end_tag = HTML_N_SCRIPT; return 1; case HTML_STYLE: obuf->flag |= RB_STYLE; obuf->end_tag = HTML_N_STYLE; return 1; case HTML_N_SCRIPT: obuf->flag &= ~RB_SCRIPT; obuf->end_tag = 0; return 1; case HTML_N_STYLE: obuf->flag &= ~RB_STYLE; obuf->end_tag = 0; return 1; case HTML_A: if (obuf->anchor.url) close_anchor(h_env, obuf); hseq = 0; if (parsedtag_get_value(tag, ATTR_HREF, &p)) obuf->anchor.url = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_TARGET, &p)) obuf->anchor.target = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_REFERER, &p)) obuf->anchor.referer = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_TITLE, &p)) obuf->anchor.title = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_ACCESSKEY, &p)) obuf->anchor.accesskey = (unsigned char)*p; if (parsedtag_get_value(tag, ATTR_HSEQ, &hseq)) obuf->anchor.hseq = hseq; if (hseq == 0 && obuf->anchor.url) { obuf->anchor.hseq = cur_hseq; tmp = process_anchor(tag, h_env->tagbuf->ptr); push_tag(obuf, tmp->ptr, HTML_A); if (displayLinkNumber) HTMLlineproc1(getLinkNumberStr(-1)->ptr, h_env); return 1; } return 0; case HTML_N_A: close_anchor(h_env, obuf); return 1; case HTML_IMG: tmp = process_img(tag, h_env->limit); HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_IMG_ALT: if (parsedtag_get_value(tag, ATTR_SRC, &p)) obuf->img_alt = Strnew_charp(p); #ifdef USE_IMAGE i = 0; if (parsedtag_get_value(tag, ATTR_TOP_MARGIN, &i)) { if (i > obuf->top_margin) obuf->top_margin = i; } i = 0; if (parsedtag_get_value(tag, ATTR_BOTTOM_MARGIN, &i)) { if (i > obuf->bottom_margin) obuf->bottom_margin = i; } #endif return 0; case HTML_N_IMG_ALT: if (obuf->img_alt) { if (!close_effect0(obuf, HTML_IMG_ALT)) push_tag(obuf, "</img_alt>", HTML_N_IMG_ALT); obuf->img_alt = NULL; } return 1; case HTML_INPUT_ALT: i = 0; if (parsedtag_get_value(tag, ATTR_TOP_MARGIN, &i)) { if (i > obuf->top_margin) obuf->top_margin = i; } i = 0; if (parsedtag_get_value(tag, ATTR_BOTTOM_MARGIN, &i)) { if (i > obuf->bottom_margin) obuf->bottom_margin = i; } if (parsedtag_get_value(tag, ATTR_HSEQ, &hseq)) { obuf->input_alt.hseq = hseq; } if (parsedtag_get_value(tag, ATTR_FID, &i)) { obuf->input_alt.fid = i; } if (parsedtag_get_value(tag, ATTR_TYPE, &p)) { obuf->input_alt.type = Strnew_charp(p); } if (parsedtag_get_value(tag, ATTR_VALUE, &p)) { obuf->input_alt.value = Strnew_charp(p); } if (parsedtag_get_value(tag, ATTR_NAME, &p)) { obuf->input_alt.name = Strnew_charp(p); } obuf->input_alt.in = 1; return 0; case HTML_N_INPUT_ALT: if (obuf->input_alt.in) { if (!close_effect0(obuf, HTML_INPUT_ALT)) push_tag(obuf, "</input_alt>", HTML_N_INPUT_ALT); obuf->input_alt.hseq = 0; obuf->input_alt.fid = -1; obuf->input_alt.in = 0; obuf->input_alt.type = NULL; obuf->input_alt.name = NULL; obuf->input_alt.value = NULL; } return 1; case HTML_TABLE: close_anchor(h_env, obuf); obuf->table_level++; if (obuf->table_level >= MAX_TABLE) break; w = BORDER_NONE; /* x: cellspacing, y: cellpadding */ x = 2; y = 1; z = 0; width = 0; if (parsedtag_exists(tag, ATTR_BORDER)) { if (parsedtag_get_value(tag, ATTR_BORDER, &w)) { if (w > 2) w = BORDER_THICK; else if (w < 0) { /* weird */ w = BORDER_THIN; } } else w = BORDER_THIN; } if (DisplayBorders && w == BORDER_NONE) w = BORDER_THIN; if (parsedtag_get_value(tag, ATTR_WIDTH, &i)) { if (obuf->table_level == 0) width = REAL_WIDTH(i, h_env->limit - envs[h_env->envc].indent); else width = RELATIVE_WIDTH(i); } if (parsedtag_exists(tag, ATTR_HBORDER)) w = BORDER_NOWIN; #define MAX_CELLSPACING 1000 #define MAX_CELLPADDING 1000 #define MAX_VSPACE 1000 parsedtag_get_value(tag, ATTR_CELLSPACING, &x); parsedtag_get_value(tag, ATTR_CELLPADDING, &y); parsedtag_get_value(tag, ATTR_VSPACE, &z); if (x > MAX_CELLSPACING) x = MAX_CELLSPACING; if (y > MAX_CELLPADDING) y = MAX_CELLPADDING; if (z > MAX_VSPACE) z = MAX_VSPACE; #ifdef ID_EXT parsedtag_get_value(tag, ATTR_ID, &id); #endif /* ID_EXT */ tables[obuf->table_level] = begin_table(w, x, y, z); #ifdef ID_EXT if (id != NULL) tables[obuf->table_level]->id = Strnew_charp(id); #endif /* ID_EXT */ table_mode[obuf->table_level].pre_mode = 0; table_mode[obuf->table_level].indent_level = 0; table_mode[obuf->table_level].nobr_level = 0; table_mode[obuf->table_level].caption = 0; table_mode[obuf->table_level].end_tag = 0; /* HTML_UNKNOWN */ #ifndef TABLE_EXPAND tables[obuf->table_level]->total_width = width; #else tables[obuf->table_level]->real_width = width; tables[obuf->table_level]->total_width = 0; #endif return 1; case HTML_N_TABLE: /* should be processed in HTMLlineproc() */ return 1; case HTML_CENTER: CLOSE_A; if (!(obuf->flag & (RB_PREMODE | RB_IGNORE_P))) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_SAVE_FLAG(obuf); RB_SET_ALIGN(obuf, RB_CENTER); return 1; case HTML_N_CENTER: CLOSE_A; if (!(obuf->flag & RB_PREMODE)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); return 1; case HTML_DIV: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); set_alignment(obuf, tag); return 1; case HTML_N_DIV: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); return 1; case HTML_DIV_INT: CLOSE_P; if (!(obuf->flag & RB_IGNORE_P)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); set_alignment(obuf, tag); return 1; case HTML_N_DIV_INT: CLOSE_P; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); return 1; case HTML_FORM: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); tmp = process_form(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_N_FORM: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; process_n_form(); return 1; case HTML_INPUT: close_anchor(h_env, obuf); tmp = process_input(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_BUTTON: tmp = process_button(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_N_BUTTON: tmp = process_n_button(); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_SELECT: close_anchor(h_env, obuf); tmp = process_select(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); obuf->flag |= RB_INSELECT; obuf->end_tag = HTML_N_SELECT; return 1; case HTML_N_SELECT: obuf->flag &= ~RB_INSELECT; obuf->end_tag = 0; tmp = process_n_select(); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_OPTION: /* nothing */ return 1; case HTML_TEXTAREA: close_anchor(h_env, obuf); tmp = process_textarea(tag, h_env->limit); if (tmp) HTMLlineproc1(tmp->ptr, h_env); obuf->flag |= RB_INTXTA; obuf->end_tag = HTML_N_TEXTAREA; return 1; case HTML_N_TEXTAREA: obuf->flag &= ~RB_INTXTA; obuf->end_tag = 0; tmp = process_n_textarea(); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_ISINDEX: p = ""; q = "!CURRENT_URL!"; parsedtag_get_value(tag, ATTR_PROMPT, &p); parsedtag_get_value(tag, ATTR_ACTION, &q); tmp = Strnew_m_charp("<form method=get action=\"", html_quote(q), "\">", html_quote(p), "<input type=text name=\"\" accept></form>", NULL); HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_META: p = q = r = NULL; parsedtag_get_value(tag, ATTR_HTTP_EQUIV, &p); parsedtag_get_value(tag, ATTR_CONTENT, &q); #ifdef USE_M17N parsedtag_get_value(tag, ATTR_CHARSET, &r); if (r) { /* <meta charset=""> */ SKIP_BLANKS(r); meta_charset = wc_guess_charset(r, 0); } else if (p && q && !strcasecmp(p, "Content-Type") && (q = strcasestr(q, "charset")) != NULL) { q += 7; SKIP_BLANKS(q); if (*q == '=') { q++; SKIP_BLANKS(q); meta_charset = wc_guess_charset(q, 0); } } else #endif if (p && q && !strcasecmp(p, "refresh")) { int refresh_interval; tmp = NULL; refresh_interval = getMetaRefreshParam(q, &tmp); if (tmp) { q = html_quote(tmp->ptr); tmp = Sprintf("Refresh (%d sec) <a href=\"%s\">%s</a>", refresh_interval, q, q); } else if (refresh_interval > 0) tmp = Sprintf("Refresh (%d sec)", refresh_interval); if (tmp) { HTMLlineproc1(tmp->ptr, h_env); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!is_redisplay && !((obuf->flag & RB_NOFRAMES) && RenderFrame)) { tag->need_reconstruct = TRUE; return 0; } } } return 1; case HTML_BASE: #if defined(USE_M17N) || defined(USE_IMAGE) p = NULL; if (parsedtag_get_value(tag, ATTR_HREF, &p)) { cur_baseURL = New(ParsedURL); parseURL(p, cur_baseURL, NULL); } #endif case HTML_MAP: case HTML_N_MAP: case HTML_AREA: return 0; case HTML_DEL: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag |= RB_DEL; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>[DEL:</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: obuf->in_strike++; if (obuf->in_strike == 1) { push_tag(obuf, "<s>", HTML_S); } break; } return 1; case HTML_N_DEL: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag &= ~RB_DEL; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>:DEL]</U>", h_env); case DISPLAY_INS_DEL_FONTIFY: if (obuf->in_strike == 0) return 1; if (obuf->in_strike == 1 && close_effect0(obuf, HTML_S)) obuf->in_strike = 0; if (obuf->in_strike > 0) { obuf->in_strike--; if (obuf->in_strike == 0) { push_tag(obuf, "</s>", HTML_N_S); } } break; } return 1; case HTML_S: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag |= RB_S; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>[S:</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: obuf->in_strike++; if (obuf->in_strike == 1) { push_tag(obuf, "<s>", HTML_S); } break; } return 1; case HTML_N_S: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag &= ~RB_S; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>:S]</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: if (obuf->in_strike == 0) return 1; if (obuf->in_strike == 1 && close_effect0(obuf, HTML_S)) obuf->in_strike = 0; if (obuf->in_strike > 0) { obuf->in_strike--; if (obuf->in_strike == 0) { push_tag(obuf, "</s>", HTML_N_S); } } } return 1; case HTML_INS: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>[INS:</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: obuf->in_ins++; if (obuf->in_ins == 1) { push_tag(obuf, "<ins>", HTML_INS); } break; } return 1; case HTML_N_INS: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>:INS]</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: if (obuf->in_ins == 0) return 1; if (obuf->in_ins == 1 && close_effect0(obuf, HTML_INS)) obuf->in_ins = 0; if (obuf->in_ins > 0) { obuf->in_ins--; if (obuf->in_ins == 0) { push_tag(obuf, "</ins>", HTML_N_INS); } } break; } return 1; case HTML_SUP: if (!(obuf->flag & (RB_DEL | RB_S))) HTMLlineproc1("^", h_env); return 1; case HTML_N_SUP: return 1; case HTML_SUB: if (!(obuf->flag & (RB_DEL | RB_S))) HTMLlineproc1("[", h_env); return 1; case HTML_N_SUB: if (!(obuf->flag & (RB_DEL | RB_S))) HTMLlineproc1("]", h_env); return 1; case HTML_FONT: case HTML_N_FONT: case HTML_NOP: return 1; case HTML_BGSOUND: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_SRC, &p)) { Str s; q = html_quote(p); s = Sprintf("<A HREF=\"%s\">bgsound(%s)</A>", q, q); HTMLlineproc1(s->ptr, h_env); } } return 1; case HTML_EMBED: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_SRC, &p)) { Str s; q = html_quote(p); s = Sprintf("<A HREF=\"%s\">embed(%s)</A>", q, q); HTMLlineproc1(s->ptr, h_env); } } return 1; case HTML_APPLET: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_ARCHIVE, &p)) { Str s; q = html_quote(p); s = Sprintf("<A HREF=\"%s\">applet archive(%s)</A>", q, q); HTMLlineproc1(s->ptr, h_env); } } return 1; case HTML_BODY: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_BACKGROUND, &p)) { Str s; q = html_quote(p); s = Sprintf("<IMG SRC=\"%s\" ALT=\"bg image(%s)\"><BR>", q, q); HTMLlineproc1(s->ptr, h_env); } } case HTML_N_HEAD: if (obuf->flag & RB_TITLE) HTMLlineproc1("</title>", h_env); case HTML_HEAD: case HTML_N_BODY: return 1; default: /* obuf->prevchar = '\0'; */ return 0; } /* not reached */ return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Prevent crash after allocate string of negative size Bug-Debian: https://github.com/tats/w3m/issues/33'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: HTMLtagproc1(struct parsed_tag *tag, struct html_feed_environ *h_env) { char *p, *q, *r; int i, w, x, y, z, count, width; struct readbuffer *obuf = h_env->obuf; struct environment *envs = h_env->envs; Str tmp; int hseq; int cmd; #ifdef ID_EXT char *id = NULL; #endif /* ID_EXT */ cmd = tag->tagid; if (obuf->flag & RB_PRE) { switch (cmd) { case HTML_NOBR: case HTML_N_NOBR: case HTML_PRE_INT: case HTML_N_PRE_INT: return 1; } } switch (cmd) { case HTML_B: obuf->in_bold++; if (obuf->in_bold > 1) return 1; return 0; case HTML_N_B: if (obuf->in_bold == 1 && close_effect0(obuf, HTML_B)) obuf->in_bold = 0; if (obuf->in_bold > 0) { obuf->in_bold--; if (obuf->in_bold == 0) return 0; } return 1; case HTML_I: obuf->in_italic++; if (obuf->in_italic > 1) return 1; return 0; case HTML_N_I: if (obuf->in_italic == 1 && close_effect0(obuf, HTML_I)) obuf->in_italic = 0; if (obuf->in_italic > 0) { obuf->in_italic--; if (obuf->in_italic == 0) return 0; } return 1; case HTML_U: obuf->in_under++; if (obuf->in_under > 1) return 1; return 0; case HTML_N_U: if (obuf->in_under == 1 && close_effect0(obuf, HTML_U)) obuf->in_under = 0; if (obuf->in_under > 0) { obuf->in_under--; if (obuf->in_under == 0) return 0; } return 1; case HTML_EM: HTMLlineproc1("<i>", h_env); return 1; case HTML_N_EM: HTMLlineproc1("</i>", h_env); return 1; case HTML_STRONG: HTMLlineproc1("<b>", h_env); return 1; case HTML_N_STRONG: HTMLlineproc1("</b>", h_env); return 1; case HTML_Q: HTMLlineproc1("`", h_env); return 1; case HTML_N_Q: HTMLlineproc1("'", h_env); return 1; case HTML_P: case HTML_N_P: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 1, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } obuf->flag |= RB_IGNORE_P; if (cmd == HTML_P) { set_alignment(obuf, tag); obuf->flag |= RB_P; } return 1; case HTML_BR: flushline(h_env, obuf, envs[h_env->envc].indent, 1, h_env->limit); h_env->blank_lines = 0; return 1; case HTML_H: if (!(obuf->flag & (RB_PREMODE | RB_IGNORE_P))) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } HTMLlineproc1("<b>", h_env); set_alignment(obuf, tag); return 1; case HTML_N_H: HTMLlineproc1("</b>", h_env); if (!(obuf->flag & RB_PREMODE)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); close_anchor(h_env, obuf); obuf->flag |= RB_IGNORE_P; return 1; case HTML_UL: case HTML_OL: case HTML_BLQ: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!(obuf->flag & RB_PREMODE) && (h_env->envc == 0 || cmd == HTML_BLQ)) do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } PUSH_ENV(cmd); if (cmd == HTML_UL || cmd == HTML_OL) { if (parsedtag_get_value(tag, ATTR_START, &count)) { envs[h_env->envc].count = count - 1; } } if (cmd == HTML_OL) { envs[h_env->envc].type = '1'; if (parsedtag_get_value(tag, ATTR_TYPE, &p)) { envs[h_env->envc].type = (int)*p; } } if (cmd == HTML_UL) envs[h_env->envc].type = ul_type(tag, 0); flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); return 1; case HTML_N_UL: case HTML_N_OL: case HTML_N_DL: case HTML_N_BLQ: CLOSE_DT; CLOSE_A; if (h_env->envc > 0) { flushline(h_env, obuf, envs[h_env->envc - 1].indent, 0, h_env->limit); POP_ENV; if (!(obuf->flag & RB_PREMODE) && (h_env->envc == 0 || cmd == HTML_N_DL || cmd == HTML_N_BLQ)) { do_blankline(h_env, obuf, envs[h_env->envc].indent, INDENT_INCR, h_env->limit); obuf->flag |= RB_IGNORE_P; } } close_anchor(h_env, obuf); return 1; case HTML_DL: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!(obuf->flag & RB_PREMODE)) do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } PUSH_ENV(cmd); if (parsedtag_exists(tag, ATTR_COMPACT)) envs[h_env->envc].env = HTML_DL_COMPACT; obuf->flag |= RB_IGNORE_P; return 1; case HTML_LI: CLOSE_A; CLOSE_DT; if (h_env->envc > 0) { Str num; flushline(h_env, obuf, envs[h_env->envc - 1].indent, 0, h_env->limit); envs[h_env->envc].count++; if (parsedtag_get_value(tag, ATTR_VALUE, &p)) { count = atoi(p); if (count > 0) envs[h_env->envc].count = count; else envs[h_env->envc].count = 0; } switch (envs[h_env->envc].env) { case HTML_UL: envs[h_env->envc].type = ul_type(tag, envs[h_env->envc].type); for (i = 0; i < INDENT_INCR - 3; i++) push_charp(obuf, 1, NBSP, PC_ASCII); tmp = Strnew(); switch (envs[h_env->envc].type) { case 'd': push_symbol(tmp, UL_SYMBOL_DISC, symbol_width, 1); break; case 'c': push_symbol(tmp, UL_SYMBOL_CIRCLE, symbol_width, 1); break; case 's': push_symbol(tmp, UL_SYMBOL_SQUARE, symbol_width, 1); break; default: push_symbol(tmp, UL_SYMBOL((h_env->envc_real - 1) % MAX_UL_LEVEL), symbol_width, 1); break; } if (symbol_width == 1) push_charp(obuf, 1, NBSP, PC_ASCII); push_str(obuf, symbol_width, tmp, PC_ASCII); push_charp(obuf, 1, NBSP, PC_ASCII); set_space_to_prevchar(obuf->prevchar); break; case HTML_OL: if (parsedtag_get_value(tag, ATTR_TYPE, &p)) envs[h_env->envc].type = (int)*p; switch ((envs[h_env->envc].count > 0)? envs[h_env->envc].type: '1') { case 'i': num = romanNumeral(envs[h_env->envc].count); break; case 'I': num = romanNumeral(envs[h_env->envc].count); Strupper(num); break; case 'a': num = romanAlphabet(envs[h_env->envc].count); break; case 'A': num = romanAlphabet(envs[h_env->envc].count); Strupper(num); break; default: num = Sprintf("%d", envs[h_env->envc].count); break; } if (INDENT_INCR >= 4) Strcat_charp(num, ". "); else Strcat_char(num, '.'); push_spaces(obuf, 1, INDENT_INCR - num->length); push_str(obuf, num->length, num, PC_ASCII); if (INDENT_INCR >= 4) set_space_to_prevchar(obuf->prevchar); break; default: push_spaces(obuf, 1, INDENT_INCR); break; } } else { flushline(h_env, obuf, 0, 0, h_env->limit); } obuf->flag |= RB_IGNORE_P; return 1; case HTML_DT: CLOSE_A; if (h_env->envc == 0 || (h_env->envc_real < h_env->nenv && envs[h_env->envc].env != HTML_DL && envs[h_env->envc].env != HTML_DL_COMPACT)) { PUSH_ENV(HTML_DL); } if (h_env->envc > 0) { flushline(h_env, obuf, envs[h_env->envc - 1].indent, 0, h_env->limit); } if (!(obuf->flag & RB_IN_DT)) { HTMLlineproc1("<b>", h_env); obuf->flag |= RB_IN_DT; } obuf->flag |= RB_IGNORE_P; return 1; case HTML_DD: CLOSE_A; CLOSE_DT; if (h_env->envc == 0 || (h_env->envc_real < h_env->nenv && envs[h_env->envc].env != HTML_DL && envs[h_env->envc].env != HTML_DL_COMPACT)) { PUSH_ENV(HTML_DL); } if (envs[h_env->envc].env == HTML_DL_COMPACT) { if (obuf->pos > envs[h_env->envc].indent) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); else push_spaces(obuf, 1, envs[h_env->envc].indent - obuf->pos); } else flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); /* obuf->flag |= RB_IGNORE_P; */ return 1; case HTML_TITLE: close_anchor(h_env, obuf); process_title(tag); obuf->flag |= RB_TITLE; obuf->end_tag = HTML_N_TITLE; return 1; case HTML_N_TITLE: if (!(obuf->flag & RB_TITLE)) return 1; obuf->flag &= ~RB_TITLE; obuf->end_tag = 0; tmp = process_n_title(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_TITLE_ALT: if (parsedtag_get_value(tag, ATTR_TITLE, &p)) h_env->title = html_unquote(p); return 0; case HTML_FRAMESET: PUSH_ENV(cmd); push_charp(obuf, 9, "--FRAME--", PC_ASCII); flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); return 0; case HTML_N_FRAMESET: if (h_env->envc > 0) { POP_ENV; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } return 0; case HTML_NOFRAMES: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= (RB_NOFRAMES | RB_IGNORE_P); /* istr = str; */ return 1; case HTML_N_NOFRAMES: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag &= ~RB_NOFRAMES; return 1; case HTML_FRAME: q = r = NULL; parsedtag_get_value(tag, ATTR_SRC, &q); parsedtag_get_value(tag, ATTR_NAME, &r); if (q) { q = html_quote(q); push_tag(obuf, Sprintf("<a hseq=\"%d\" href=\"%s\">", cur_hseq++, q)->ptr, HTML_A); if (r) q = html_quote(r); push_charp(obuf, get_strwidth(q), q, PC_ASCII); push_tag(obuf, "</a>", HTML_N_A); } flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); return 0; case HTML_HR: close_anchor(h_env, obuf); tmp = process_hr(tag, h_env->limit, envs[h_env->envc].indent); HTMLlineproc1(tmp->ptr, h_env); set_space_to_prevchar(obuf->prevchar); return 1; case HTML_PRE: x = parsedtag_exists(tag, ATTR_FOR_TABLE); CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!x) do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } else fillline(obuf, envs[h_env->envc].indent); obuf->flag |= (RB_PRE | RB_IGNORE_P); /* istr = str; */ return 1; case HTML_N_PRE: flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!(obuf->flag & RB_IGNORE_P)) { do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; h_env->blank_lines++; } obuf->flag &= ~RB_PRE; close_anchor(h_env, obuf); return 1; case HTML_PRE_INT: i = obuf->line->length; append_tags(obuf); if (!(obuf->flag & RB_SPECIAL)) { set_breakpoint(obuf, obuf->line->length - i); } obuf->flag |= RB_PRE_INT; return 0; case HTML_N_PRE_INT: push_tag(obuf, "</pre_int>", HTML_N_PRE_INT); obuf->flag &= ~RB_PRE_INT; if (!(obuf->flag & RB_SPECIAL) && obuf->pos > obuf->bp.pos) { set_prevchar(obuf->prevchar, "", 0); obuf->prev_ctype = PC_CTRL; } return 1; case HTML_NOBR: obuf->flag |= RB_NOBR; obuf->nobr_level++; return 0; case HTML_N_NOBR: if (obuf->nobr_level > 0) obuf->nobr_level--; if (obuf->nobr_level == 0) obuf->flag &= ~RB_NOBR; return 0; case HTML_PRE_PLAIN: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } obuf->flag |= (RB_PRE | RB_IGNORE_P); return 1; case HTML_N_PRE_PLAIN: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; } obuf->flag &= ~RB_PRE; return 1; case HTML_LISTING: case HTML_XMP: case HTML_PLAINTEXT: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } obuf->flag |= (RB_PLAIN | RB_IGNORE_P); switch (cmd) { case HTML_LISTING: obuf->end_tag = HTML_N_LISTING; break; case HTML_XMP: obuf->end_tag = HTML_N_XMP; break; case HTML_PLAINTEXT: obuf->end_tag = MAX_HTMLTAG; break; } return 1; case HTML_N_LISTING: case HTML_N_XMP: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; } obuf->flag &= ~RB_PLAIN; obuf->end_tag = 0; return 1; case HTML_SCRIPT: obuf->flag |= RB_SCRIPT; obuf->end_tag = HTML_N_SCRIPT; return 1; case HTML_STYLE: obuf->flag |= RB_STYLE; obuf->end_tag = HTML_N_STYLE; return 1; case HTML_N_SCRIPT: obuf->flag &= ~RB_SCRIPT; obuf->end_tag = 0; return 1; case HTML_N_STYLE: obuf->flag &= ~RB_STYLE; obuf->end_tag = 0; return 1; case HTML_A: if (obuf->anchor.url) close_anchor(h_env, obuf); hseq = 0; if (parsedtag_get_value(tag, ATTR_HREF, &p)) obuf->anchor.url = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_TARGET, &p)) obuf->anchor.target = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_REFERER, &p)) obuf->anchor.referer = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_TITLE, &p)) obuf->anchor.title = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_ACCESSKEY, &p)) obuf->anchor.accesskey = (unsigned char)*p; if (parsedtag_get_value(tag, ATTR_HSEQ, &hseq)) obuf->anchor.hseq = hseq; if (hseq == 0 && obuf->anchor.url) { obuf->anchor.hseq = cur_hseq; tmp = process_anchor(tag, h_env->tagbuf->ptr); push_tag(obuf, tmp->ptr, HTML_A); if (displayLinkNumber) HTMLlineproc1(getLinkNumberStr(-1)->ptr, h_env); return 1; } return 0; case HTML_N_A: close_anchor(h_env, obuf); return 1; case HTML_IMG: tmp = process_img(tag, h_env->limit); HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_IMG_ALT: if (parsedtag_get_value(tag, ATTR_SRC, &p)) obuf->img_alt = Strnew_charp(p); #ifdef USE_IMAGE i = 0; if (parsedtag_get_value(tag, ATTR_TOP_MARGIN, &i)) { if (i > obuf->top_margin) obuf->top_margin = i; } i = 0; if (parsedtag_get_value(tag, ATTR_BOTTOM_MARGIN, &i)) { if (i > obuf->bottom_margin) obuf->bottom_margin = i; } #endif return 0; case HTML_N_IMG_ALT: if (obuf->img_alt) { if (!close_effect0(obuf, HTML_IMG_ALT)) push_tag(obuf, "</img_alt>", HTML_N_IMG_ALT); obuf->img_alt = NULL; } return 1; case HTML_INPUT_ALT: i = 0; if (parsedtag_get_value(tag, ATTR_TOP_MARGIN, &i)) { if (i > obuf->top_margin) obuf->top_margin = i; } i = 0; if (parsedtag_get_value(tag, ATTR_BOTTOM_MARGIN, &i)) { if (i > obuf->bottom_margin) obuf->bottom_margin = i; } if (parsedtag_get_value(tag, ATTR_HSEQ, &hseq)) { obuf->input_alt.hseq = hseq; } if (parsedtag_get_value(tag, ATTR_FID, &i)) { obuf->input_alt.fid = i; } if (parsedtag_get_value(tag, ATTR_TYPE, &p)) { obuf->input_alt.type = Strnew_charp(p); } if (parsedtag_get_value(tag, ATTR_VALUE, &p)) { obuf->input_alt.value = Strnew_charp(p); } if (parsedtag_get_value(tag, ATTR_NAME, &p)) { obuf->input_alt.name = Strnew_charp(p); } obuf->input_alt.in = 1; return 0; case HTML_N_INPUT_ALT: if (obuf->input_alt.in) { if (!close_effect0(obuf, HTML_INPUT_ALT)) push_tag(obuf, "</input_alt>", HTML_N_INPUT_ALT); obuf->input_alt.hseq = 0; obuf->input_alt.fid = -1; obuf->input_alt.in = 0; obuf->input_alt.type = NULL; obuf->input_alt.name = NULL; obuf->input_alt.value = NULL; } return 1; case HTML_TABLE: close_anchor(h_env, obuf); obuf->table_level++; if (obuf->table_level >= MAX_TABLE) break; w = BORDER_NONE; /* x: cellspacing, y: cellpadding */ x = 2; y = 1; z = 0; width = 0; if (parsedtag_exists(tag, ATTR_BORDER)) { if (parsedtag_get_value(tag, ATTR_BORDER, &w)) { if (w > 2) w = BORDER_THICK; else if (w < 0) { /* weird */ w = BORDER_THIN; } } else w = BORDER_THIN; } if (DisplayBorders && w == BORDER_NONE) w = BORDER_THIN; if (parsedtag_get_value(tag, ATTR_WIDTH, &i)) { if (obuf->table_level == 0) width = REAL_WIDTH(i, h_env->limit - envs[h_env->envc].indent); else width = RELATIVE_WIDTH(i); } if (parsedtag_exists(tag, ATTR_HBORDER)) w = BORDER_NOWIN; #define MAX_CELLSPACING 1000 #define MAX_CELLPADDING 1000 #define MAX_VSPACE 1000 parsedtag_get_value(tag, ATTR_CELLSPACING, &x); parsedtag_get_value(tag, ATTR_CELLPADDING, &y); parsedtag_get_value(tag, ATTR_VSPACE, &z); if (x < 0) x = 0; if (y < 0) y = 0; if (z < 0) z = 0; if (x > MAX_CELLSPACING) x = MAX_CELLSPACING; if (y > MAX_CELLPADDING) y = MAX_CELLPADDING; if (z > MAX_VSPACE) z = MAX_VSPACE; #ifdef ID_EXT parsedtag_get_value(tag, ATTR_ID, &id); #endif /* ID_EXT */ tables[obuf->table_level] = begin_table(w, x, y, z); #ifdef ID_EXT if (id != NULL) tables[obuf->table_level]->id = Strnew_charp(id); #endif /* ID_EXT */ table_mode[obuf->table_level].pre_mode = 0; table_mode[obuf->table_level].indent_level = 0; table_mode[obuf->table_level].nobr_level = 0; table_mode[obuf->table_level].caption = 0; table_mode[obuf->table_level].end_tag = 0; /* HTML_UNKNOWN */ #ifndef TABLE_EXPAND tables[obuf->table_level]->total_width = width; #else tables[obuf->table_level]->real_width = width; tables[obuf->table_level]->total_width = 0; #endif return 1; case HTML_N_TABLE: /* should be processed in HTMLlineproc() */ return 1; case HTML_CENTER: CLOSE_A; if (!(obuf->flag & (RB_PREMODE | RB_IGNORE_P))) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_SAVE_FLAG(obuf); RB_SET_ALIGN(obuf, RB_CENTER); return 1; case HTML_N_CENTER: CLOSE_A; if (!(obuf->flag & RB_PREMODE)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); return 1; case HTML_DIV: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); set_alignment(obuf, tag); return 1; case HTML_N_DIV: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); return 1; case HTML_DIV_INT: CLOSE_P; if (!(obuf->flag & RB_IGNORE_P)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); set_alignment(obuf, tag); return 1; case HTML_N_DIV_INT: CLOSE_P; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); return 1; case HTML_FORM: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); tmp = process_form(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_N_FORM: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; process_n_form(); return 1; case HTML_INPUT: close_anchor(h_env, obuf); tmp = process_input(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_BUTTON: tmp = process_button(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_N_BUTTON: tmp = process_n_button(); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_SELECT: close_anchor(h_env, obuf); tmp = process_select(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); obuf->flag |= RB_INSELECT; obuf->end_tag = HTML_N_SELECT; return 1; case HTML_N_SELECT: obuf->flag &= ~RB_INSELECT; obuf->end_tag = 0; tmp = process_n_select(); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_OPTION: /* nothing */ return 1; case HTML_TEXTAREA: close_anchor(h_env, obuf); tmp = process_textarea(tag, h_env->limit); if (tmp) HTMLlineproc1(tmp->ptr, h_env); obuf->flag |= RB_INTXTA; obuf->end_tag = HTML_N_TEXTAREA; return 1; case HTML_N_TEXTAREA: obuf->flag &= ~RB_INTXTA; obuf->end_tag = 0; tmp = process_n_textarea(); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_ISINDEX: p = ""; q = "!CURRENT_URL!"; parsedtag_get_value(tag, ATTR_PROMPT, &p); parsedtag_get_value(tag, ATTR_ACTION, &q); tmp = Strnew_m_charp("<form method=get action=\"", html_quote(q), "\">", html_quote(p), "<input type=text name=\"\" accept></form>", NULL); HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_META: p = q = r = NULL; parsedtag_get_value(tag, ATTR_HTTP_EQUIV, &p); parsedtag_get_value(tag, ATTR_CONTENT, &q); #ifdef USE_M17N parsedtag_get_value(tag, ATTR_CHARSET, &r); if (r) { /* <meta charset=""> */ SKIP_BLANKS(r); meta_charset = wc_guess_charset(r, 0); } else if (p && q && !strcasecmp(p, "Content-Type") && (q = strcasestr(q, "charset")) != NULL) { q += 7; SKIP_BLANKS(q); if (*q == '=') { q++; SKIP_BLANKS(q); meta_charset = wc_guess_charset(q, 0); } } else #endif if (p && q && !strcasecmp(p, "refresh")) { int refresh_interval; tmp = NULL; refresh_interval = getMetaRefreshParam(q, &tmp); if (tmp) { q = html_quote(tmp->ptr); tmp = Sprintf("Refresh (%d sec) <a href=\"%s\">%s</a>", refresh_interval, q, q); } else if (refresh_interval > 0) tmp = Sprintf("Refresh (%d sec)", refresh_interval); if (tmp) { HTMLlineproc1(tmp->ptr, h_env); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!is_redisplay && !((obuf->flag & RB_NOFRAMES) && RenderFrame)) { tag->need_reconstruct = TRUE; return 0; } } } return 1; case HTML_BASE: #if defined(USE_M17N) || defined(USE_IMAGE) p = NULL; if (parsedtag_get_value(tag, ATTR_HREF, &p)) { cur_baseURL = New(ParsedURL); parseURL(p, cur_baseURL, NULL); } #endif case HTML_MAP: case HTML_N_MAP: case HTML_AREA: return 0; case HTML_DEL: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag |= RB_DEL; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>[DEL:</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: obuf->in_strike++; if (obuf->in_strike == 1) { push_tag(obuf, "<s>", HTML_S); } break; } return 1; case HTML_N_DEL: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag &= ~RB_DEL; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>:DEL]</U>", h_env); case DISPLAY_INS_DEL_FONTIFY: if (obuf->in_strike == 0) return 1; if (obuf->in_strike == 1 && close_effect0(obuf, HTML_S)) obuf->in_strike = 0; if (obuf->in_strike > 0) { obuf->in_strike--; if (obuf->in_strike == 0) { push_tag(obuf, "</s>", HTML_N_S); } } break; } return 1; case HTML_S: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag |= RB_S; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>[S:</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: obuf->in_strike++; if (obuf->in_strike == 1) { push_tag(obuf, "<s>", HTML_S); } break; } return 1; case HTML_N_S: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag &= ~RB_S; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>:S]</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: if (obuf->in_strike == 0) return 1; if (obuf->in_strike == 1 && close_effect0(obuf, HTML_S)) obuf->in_strike = 0; if (obuf->in_strike > 0) { obuf->in_strike--; if (obuf->in_strike == 0) { push_tag(obuf, "</s>", HTML_N_S); } } } return 1; case HTML_INS: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>[INS:</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: obuf->in_ins++; if (obuf->in_ins == 1) { push_tag(obuf, "<ins>", HTML_INS); } break; } return 1; case HTML_N_INS: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>:INS]</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: if (obuf->in_ins == 0) return 1; if (obuf->in_ins == 1 && close_effect0(obuf, HTML_INS)) obuf->in_ins = 0; if (obuf->in_ins > 0) { obuf->in_ins--; if (obuf->in_ins == 0) { push_tag(obuf, "</ins>", HTML_N_INS); } } break; } return 1; case HTML_SUP: if (!(obuf->flag & (RB_DEL | RB_S))) HTMLlineproc1("^", h_env); return 1; case HTML_N_SUP: return 1; case HTML_SUB: if (!(obuf->flag & (RB_DEL | RB_S))) HTMLlineproc1("[", h_env); return 1; case HTML_N_SUB: if (!(obuf->flag & (RB_DEL | RB_S))) HTMLlineproc1("]", h_env); return 1; case HTML_FONT: case HTML_N_FONT: case HTML_NOP: return 1; case HTML_BGSOUND: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_SRC, &p)) { Str s; q = html_quote(p); s = Sprintf("<A HREF=\"%s\">bgsound(%s)</A>", q, q); HTMLlineproc1(s->ptr, h_env); } } return 1; case HTML_EMBED: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_SRC, &p)) { Str s; q = html_quote(p); s = Sprintf("<A HREF=\"%s\">embed(%s)</A>", q, q); HTMLlineproc1(s->ptr, h_env); } } return 1; case HTML_APPLET: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_ARCHIVE, &p)) { Str s; q = html_quote(p); s = Sprintf("<A HREF=\"%s\">applet archive(%s)</A>", q, q); HTMLlineproc1(s->ptr, h_env); } } return 1; case HTML_BODY: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_BACKGROUND, &p)) { Str s; q = html_quote(p); s = Sprintf("<IMG SRC=\"%s\" ALT=\"bg image(%s)\"><BR>", q, q); HTMLlineproc1(s->ptr, h_env); } } case HTML_N_HEAD: if (obuf->flag & RB_TITLE) HTMLlineproc1("</title>", h_env); case HTML_HEAD: case HTML_N_BODY: return 1; default: /* obuf->prevchar = '\0'; */ return 0; } /* not reached */ return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Prevent infinite recursion in HTMLlineproc0 Bug-Debian: https://github.com/tats/w3m/issues/36'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: feed_table_block_tag(struct table *tbl, char *line, struct table_mode *mode, int indent, int cmd) { int offset; if (mode->indent_level <= 0 && indent == -1) return; setwidth(tbl, mode); feed_table_inline_tag(tbl, line, mode, -1); clearcontentssize(tbl, mode); if (indent == 1) { mode->indent_level++; if (mode->indent_level <= MAX_INDENT_LEVEL) tbl->indent += INDENT_INCR; } else if (indent == -1) { mode->indent_level--; if (mode->indent_level < MAX_INDENT_LEVEL) tbl->indent -= INDENT_INCR; } offset = tbl->indent; if (cmd == HTML_DT) { if (mode->indent_level > 0 && mode->indent_level <= MAX_INDENT_LEVEL) offset -= INDENT_INCR; } if (tbl->indent > 0) { check_minimum0(tbl, 0); addcontentssize(tbl, offset); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Check indent_level to prevent infinite recursion Bug-Debian: https://github.com/tats/w3m/issues/37'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: addChar(char c, Lineprop mode) { addMChar(&c, mode, 1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Prevent array index out of bounds for symbol Bug-Debian: https://github.com/tats/w3m/issues/38'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: push_symbol(Str str, char symbol, int width, int n) { char buf[2], *p; int i; #ifdef USE_M17N if (width == 2) p = alt2_symbol[(int)symbol]; else #endif p = alt_symbol[(int)symbol]; for (i = 0; i < 2 && *p; i++, p++) buf[i] = (*p == ' ') ? NBSP_CODE : *p; Strcat(str, Sprintf("<_SYMBOL TYPE=%d>", symbol)); for (; n > 0; n--) Strcat_charp_n(str, buf, i); Strcat_charp(str, "</_SYMBOL>"); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Prevent array index out of bounds for symbol Bug-Debian: https://github.com/tats/w3m/issues/38'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: parseURL(char *url, ParsedURL *p_url, ParsedURL *current) { char *p, *q, *qq; Str tmp; url = url_quote(url); /* quote 0x01-0x20, 0x7F-0xFF */ p = url; copyParsedURL(p_url, NULL); p_url->scheme = SCM_MISSING; /* RFC1808: Relative Uniform Resource Locators * 4. Resolving Relative URLs */ if (*url == '\0' || *url == '#') { if (current) copyParsedURL(p_url, current); goto do_label; } #if defined( __EMX__ ) || defined( __CYGWIN__ ) if (!strncasecmp(url, "file://localhost/", 17)) { p_url->scheme = SCM_LOCAL; p += 17 - 1; url += 17 - 1; } #endif #ifdef SUPPORT_DOS_DRIVE_PREFIX if (IS_ALPHA(*p) && (p[1] == ':' || p[1] == '|')) { p_url->scheme = SCM_LOCAL; goto analyze_file; } #endif /* SUPPORT_DOS_DRIVE_PREFIX */ /* search for scheme */ p_url->scheme = getURLScheme(&p); if (p_url->scheme == SCM_MISSING) { /* scheme part is not found in the url. This means either * (a) the url is relative to the current or (b) the url * denotes a filename (therefore the scheme is SCM_LOCAL). */ if (current) { switch (current->scheme) { case SCM_LOCAL: case SCM_LOCAL_CGI: p_url->scheme = SCM_LOCAL; break; case SCM_FTP: case SCM_FTPDIR: p_url->scheme = SCM_FTP; break; #ifdef USE_NNTP case SCM_NNTP: case SCM_NNTP_GROUP: p_url->scheme = SCM_NNTP; break; case SCM_NEWS: case SCM_NEWS_GROUP: p_url->scheme = SCM_NEWS; break; #endif default: p_url->scheme = current->scheme; break; } } else p_url->scheme = SCM_LOCAL; p = url; if (!strncmp(p, "//", 2)) { /* URL begins with // */ /* it means that 'scheme:' is abbreviated */ p += 2; goto analyze_url; } /* the url doesn't begin with '//' */ goto analyze_file; } /* scheme part has been found */ if (p_url->scheme == SCM_UNKNOWN) { p_url->file = allocStr(url, -1); return; } /* get host and port */ if (p[0] != '/' || p[1] != '/') { /* scheme:foo or scheme:/foo */ p_url->host = NULL; if (p_url->scheme != SCM_UNKNOWN) p_url->port = DefaultPort[p_url->scheme]; else p_url->port = 0; goto analyze_file; } /* after here, p begins with // */ if (p_url->scheme == SCM_LOCAL) { /* file://foo */ #ifdef __EMX__ p += 2; goto analyze_file; #else if (p[2] == '/' || p[2] == '~' /* <A HREF="file:///foo">file:///foo</A> or <A HREF="file://~user">file://~user</A> */ #ifdef SUPPORT_DOS_DRIVE_PREFIX || (IS_ALPHA(p[2]) && (p[3] == ':' || p[3] == '|')) /* <A HREF="file://DRIVE/foo">file://DRIVE/foo</A> */ #endif /* SUPPORT_DOS_DRIVE_PREFIX */ ) { p += 2; goto analyze_file; } #endif /* __EMX__ */ } p += 2; /* scheme://foo */ /* ^p is here */ analyze_url: q = p; #ifdef INET6 if (*q == '[') { /* rfc2732,rfc2373 compliance */ p++; while (IS_XDIGIT(*p) || *p == ':' || *p == '.') p++; if (*p != ']' || (*(p + 1) && strchr(":/?#", *(p + 1)) == NULL)) p = q; } #endif while (*p && strchr(":/@?#", *p) == NULL) p++; switch (*p) { case ':': /* scheme://user:pass@host or * scheme://host:port */ qq = q; q = ++p; while (*p && strchr("@/?#", *p) == NULL) p++; if (*p == '@') { /* scheme://user:pass@... */ p_url->user = copyPath(qq, q - 1 - qq, COPYPATH_SPC_IGNORE); p_url->pass = copyPath(q, p - q, COPYPATH_SPC_ALLOW); p++; goto analyze_url; } /* scheme://host:port/ */ p_url->host = copyPath(qq, q - 1 - qq, COPYPATH_SPC_IGNORE | COPYPATH_LOWERCASE); tmp = Strnew_charp_n(q, p - q); p_url->port = atoi(tmp->ptr); /* *p is one of ['\0', '/', '?', '#'] */ break; case '@': /* scheme://user@... */ p_url->user = copyPath(q, p - q, COPYPATH_SPC_IGNORE); p++; goto analyze_url; case '\0': /* scheme://host */ case '/': case '?': case '#': p_url->host = copyPath(q, p - q, COPYPATH_SPC_IGNORE | COPYPATH_LOWERCASE); p_url->port = DefaultPort[p_url->scheme]; break; } analyze_file: #ifndef SUPPORT_NETBIOS_SHARE if (p_url->scheme == SCM_LOCAL && p_url->user == NULL && p_url->host != NULL && *p_url->host != '\0' && strcmp(p_url->host, "localhost")) { /* * In the environments other than CYGWIN, a URL like * file://host/file is regarded as ftp://host/file. * On the other hand, file://host/file on CYGWIN is * regarded as local access to the file //host/file. * `host' is a netbios-hostname, drive, or any other * name; It is CYGWIN system call who interprets that. */ p_url->scheme = SCM_FTP; /* ftp://host/... */ if (p_url->port == 0) p_url->port = DefaultPort[SCM_FTP]; } #endif if ((*p == '\0' || *p == '#' || *p == '?') && p_url->host == NULL) { p_url->file = ""; goto do_query; } #ifdef SUPPORT_DOS_DRIVE_PREFIX if (p_url->scheme == SCM_LOCAL) { q = p; if (*q == '/') q++; if (IS_ALPHA(q[0]) && (q[1] == ':' || q[1] == '|')) { if (q[1] == '|') { p = allocStr(q, -1); p[1] = ':'; } else p = q; } } #endif q = p; #ifdef USE_GOPHER if (p_url->scheme == SCM_GOPHER) { if (*q == '/') q++; if (*q && q[0] != '/' && q[1] != '/' && q[2] == '/') q++; } #endif /* USE_GOPHER */ if (*p == '/') p++; if (*p == '\0' || *p == '#' || *p == '?') { /* scheme://host[:port]/ */ p_url->file = DefaultFile(p_url->scheme); goto do_query; } #ifdef USE_GOPHER if (p_url->scheme == SCM_GOPHER && *p == 'R') { p++; tmp = Strnew(); Strcat_char(tmp, *(p++)); while (*p && *p != '/') p++; Strcat_charp(tmp, p); while (*p) p++; p_url->file = copyPath(tmp->ptr, -1, COPYPATH_SPC_IGNORE); } else #endif /* USE_GOPHER */ { char *cgi = strchr(p, '?'); again: while (*p && *p != '#' && p != cgi) p++; if (*p == '#' && p_url->scheme == SCM_LOCAL) { /* * According to RFC2396, # means the beginning of * URI-reference, and # should be escaped. But, * if the scheme is SCM_LOCAL, the special * treatment will apply to # for convinience. */ if (p > q && *(p - 1) == '/' && (cgi == NULL || p < cgi)) { /* * # comes as the first character of the file name * that means, # is not a label but a part of the file * name. */ p++; goto again; } else if (*(p + 1) == '\0') { /* * # comes as the last character of the file name that * means, # is not a label but a part of the file * name. */ p++; } } if (p_url->scheme == SCM_LOCAL || p_url->scheme == SCM_MISSING) p_url->file = copyPath(q, p - q, COPYPATH_SPC_ALLOW); else p_url->file = copyPath(q, p - q, COPYPATH_SPC_IGNORE); } do_query: if (*p == '?') { q = ++p; while (*p && *p != '#') p++; p_url->query = copyPath(q, p - q, COPYPATH_SPC_ALLOW); } do_label: if (p_url->scheme == SCM_MISSING) { p_url->scheme = SCM_LOCAL; p_url->file = allocStr(p, -1); p_url->label = NULL; } else if (*p == '#') p_url->label = allocStr(p + 1, -1); else p_url->label = NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Prevent global-buffer-overflow in parseURL() Bug-Debian: https://github.com/tats/w3m/issues/41'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u, int closing, int tx_ring) { struct pgv *pg_vec = NULL; struct packet_sock *po = pkt_sk(sk); int was_running, order = 0; struct packet_ring_buffer *rb; struct sk_buff_head *rb_queue; __be16 num; int err = -EINVAL; /* Added to avoid minimal code churn */ struct tpacket_req *req = &req_u->req; /* Opening a Tx-ring is NOT supported in TPACKET_V3 */ if (!closing && tx_ring && (po->tp_version > TPACKET_V2)) { net_warn_ratelimited("Tx-ring is not supported.\n"); goto out; } rb = tx_ring ? &po->tx_ring : &po->rx_ring; rb_queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue; err = -EBUSY; if (!closing) { if (atomic_read(&po->mapped)) goto out; if (packet_read_pending(rb)) goto out; } if (req->tp_block_nr) { /* Sanity tests and some calculations */ err = -EBUSY; if (unlikely(rb->pg_vec)) goto out; switch (po->tp_version) { case TPACKET_V1: po->tp_hdrlen = TPACKET_HDRLEN; break; case TPACKET_V2: po->tp_hdrlen = TPACKET2_HDRLEN; break; case TPACKET_V3: po->tp_hdrlen = TPACKET3_HDRLEN; break; } err = -EINVAL; if (unlikely((int)req->tp_block_size <= 0)) goto out; if (unlikely(!PAGE_ALIGNED(req->tp_block_size))) goto out; if (po->tp_version >= TPACKET_V3 && (int)(req->tp_block_size - BLK_PLUS_PRIV(req_u->req3.tp_sizeof_priv)) <= 0) goto out; if (unlikely(req->tp_frame_size < po->tp_hdrlen + po->tp_reserve)) goto out; if (unlikely(req->tp_frame_size & (TPACKET_ALIGNMENT - 1))) goto out; rb->frames_per_block = req->tp_block_size / req->tp_frame_size; if (unlikely(rb->frames_per_block == 0)) goto out; if (unlikely((rb->frames_per_block * req->tp_block_nr) != req->tp_frame_nr)) goto out; err = -ENOMEM; order = get_order(req->tp_block_size); pg_vec = alloc_pg_vec(req, order); if (unlikely(!pg_vec)) goto out; switch (po->tp_version) { case TPACKET_V3: /* Transmit path is not supported. We checked * it above but just being paranoid */ if (!tx_ring) init_prb_bdqc(po, rb, pg_vec, req_u); break; default: break; } } /* Done */ else { err = -EINVAL; if (unlikely(req->tp_frame_nr)) goto out; } lock_sock(sk); /* Detach socket from network */ spin_lock(&po->bind_lock); was_running = po->running; num = po->num; if (was_running) { po->num = 0; __unregister_prot_hook(sk, false); } spin_unlock(&po->bind_lock); synchronize_net(); err = -EBUSY; mutex_lock(&po->pg_vec_lock); if (closing || atomic_read(&po->mapped) == 0) { err = 0; spin_lock_bh(&rb_queue->lock); swap(rb->pg_vec, pg_vec); rb->frame_max = (req->tp_frame_nr - 1); rb->head = 0; rb->frame_size = req->tp_frame_size; spin_unlock_bh(&rb_queue->lock); swap(rb->pg_vec_order, order); swap(rb->pg_vec_len, req->tp_block_nr); rb->pg_vec_pages = req->tp_block_size/PAGE_SIZE; po->prot_hook.func = (po->rx_ring.pg_vec) ? tpacket_rcv : packet_rcv; skb_queue_purge(rb_queue); if (atomic_read(&po->mapped)) pr_err("packet_mmap: vma is busy: %d\n", atomic_read(&po->mapped)); } mutex_unlock(&po->pg_vec_lock); spin_lock(&po->bind_lock); if (was_running) { po->num = num; register_prot_hook(sk); } spin_unlock(&po->bind_lock); if (closing && (po->tp_version > TPACKET_V2)) { /* Because we don't support block-based V3 on tx-ring */ if (!tx_ring) prb_shutdown_retire_blk_timer(po, rb_queue); } release_sock(sk); if (pg_vec) free_pg_vec(pg_vec, order, req->tp_block_nr); out: return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-362'], 'message': 'packet: fix race condition in packet_set_ring When packet_set_ring creates a ring buffer it will initialize a struct timer_list if the packet version is TPACKET_V3. This value can then be raced by a different thread calling setsockopt to set the version to TPACKET_V1 before packet_set_ring has finished. This leads to a use-after-free on a function pointer in the struct timer_list when the socket is closed as the previously initialized timer will not be deleted. The bug is fixed by taking lock_sock(sk) in packet_setsockopt when changing the packet version while also taking the lock at the start of packet_set_ring. Fixes: f6fb8f100b80 ("af-packet: TPACKET_V3 flexible buffer implementation.") Signed-off-by: Philip Pettersson <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: sg_common_write(Sg_fd * sfp, Sg_request * srp, unsigned char *cmnd, int timeout, int blocking) { int k, at_head; Sg_device *sdp = sfp->parentdp; sg_io_hdr_t *hp = &srp->header; srp->data.cmd_opcode = cmnd[0]; /* hold opcode of command */ hp->status = 0; hp->masked_status = 0; hp->msg_status = 0; hp->info = 0; hp->host_status = 0; hp->driver_status = 0; hp->resid = 0; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_common_write: scsi opcode=0x%02x, cmd_size=%d\n", (int) cmnd[0], (int) hp->cmd_len)); k = sg_start_req(srp, cmnd); if (k) { SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp, "sg_common_write: start_req err=%d\n", k)); sg_finish_rem_req(srp); return k; /* probably out of space --> ENOMEM */ } if (atomic_read(&sdp->detaching)) { if (srp->bio) blk_end_request_all(srp->rq, -EIO); sg_finish_rem_req(srp); return -ENODEV; } hp->duration = jiffies_to_msecs(jiffies); if (hp->interface_id != '\0' && /* v3 (or later) interface */ (SG_FLAG_Q_AT_TAIL & hp->flags)) at_head = 0; else at_head = 1; srp->rq->timeout = timeout; kref_get(&sfp->f_ref); /* sg_rq_end_io() does kref_put(). */ blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk, srp->rq, at_head, sg_rq_end_io); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'sg: Fix double-free when drives detach during SG_IO In sg_common_write(), we free the block request and return -ENODEV if the device is detached in the middle of the SG_IO ioctl(). Unfortunately, sg_finish_rem_req() also tries to free srp->rq, so we end up freeing rq->cmd in the already free rq object, and then free the object itself out from under the current user. This ends up corrupting random memory via the list_head on the rq object. The most common crash trace I saw is this: ------------[ cut here ]------------ kernel BUG at block/blk-core.c:1420! Call Trace: [<ffffffff81281eab>] blk_put_request+0x5b/0x80 [<ffffffffa0069e5b>] sg_finish_rem_req+0x6b/0x120 [sg] [<ffffffffa006bcb9>] sg_common_write.isra.14+0x459/0x5a0 [sg] [<ffffffff8125b328>] ? selinux_file_alloc_security+0x48/0x70 [<ffffffffa006bf95>] sg_new_write.isra.17+0x195/0x2d0 [sg] [<ffffffffa006cef4>] sg_ioctl+0x644/0xdb0 [sg] [<ffffffff81170f80>] do_vfs_ioctl+0x90/0x520 [<ffffffff81258967>] ? file_has_perm+0x97/0xb0 [<ffffffff811714a1>] SyS_ioctl+0x91/0xb0 [<ffffffff81602afb>] tracesys+0xdd/0xe2 RIP [<ffffffff81281e04>] __blk_put_request+0x154/0x1a0 The solution is straightforward: just set srp->rq to NULL in the failure branch so that sg_finish_rem_req() doesn't attempt to re-free it. Additionally, since sg_rq_end_io() will never be called on the object when this happens, we need to free memory backing ->cmd if it isn't embedded in the object itself. KASAN was extremely helpful in finding the root cause of this bug. Signed-off-by: Calvin Owens <[email protected]> Acked-by: Douglas Gilbert <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: MagickExport Image *ReadStream(const ImageInfo *image_info,StreamHandler stream, ExceptionInfo *exception) { CacheMethods cache_methods; Image *image; ImageInfo *read_info; /* Stream image pixels. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); read_info=CloneImageInfo(image_info); read_info->cache=AcquirePixelCache(0); GetPixelCacheMethods(&cache_methods); cache_methods.get_virtual_pixel_handler=GetVirtualPixelStream; cache_methods.get_virtual_pixels_handler=GetVirtualPixelsStream; cache_methods.get_virtual_metacontent_from_handler= GetVirtualMetacontentFromStream; cache_methods.get_authentic_pixels_handler=GetAuthenticPixelsStream; cache_methods.queue_authentic_pixels_handler=QueueAuthenticPixelsStream; cache_methods.sync_authentic_pixels_handler=SyncAuthenticPixelsStream; cache_methods.get_authentic_pixels_from_handler=GetAuthenticPixelsFromStream; cache_methods.get_authentic_metacontent_from_handler= GetAuthenticMetacontentFromStream; cache_methods.get_one_virtual_pixel_from_handler=GetOneVirtualPixelFromStream; cache_methods.get_one_authentic_pixel_from_handler= GetOneAuthenticPixelFromStream; cache_methods.destroy_pixel_handler=DestroyPixelStream; SetPixelCacheMethods(read_info->cache,&cache_methods); read_info->stream=stream; image=ReadImage(read_info,exception); if (image != (Image *) NULL) InitializePixelChannelMap(image); read_info=DestroyImageInfo(read_info); return(image); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/312'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void snd_pcm_period_elapsed(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime; unsigned long flags; if (PCM_RUNTIME_CHECK(substream)) return; runtime = substream->runtime; snd_pcm_stream_lock_irqsave(substream, flags); if (!snd_pcm_running(substream) || snd_pcm_update_hw_ptr0(substream, 1) < 0) goto _end; #ifdef CONFIG_SND_PCM_TIMER if (substream->timer_running) snd_timer_interrupt(substream->timer, 1); #endif _end: snd_pcm_stream_unlock_irqrestore(substream, flags); kill_fasync(&runtime->fasync, SIGIO, POLL_IN); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-362'], 'message': 'ALSA: pcm : Call kill_fasync() in stream lock Currently kill_fasync() is called outside the stream lock in snd_pcm_period_elapsed(). This is potentially racy, since the stream may get released even during the irq handler is running. Although snd_pcm_release_substream() calls snd_pcm_drop(), this doesn't guarantee that the irq handler finishes, thus the kill_fasync() call outside the stream spin lock may be invoked after the substream is detached, as recently reported by KASAN. As a quick workaround, move kill_fasync() call inside the stream lock. The fasync is rarely used interface, so this shouldn't have a big impact from the performance POV. Ideally, we should implement some sync mechanism for the proper finish of stream and irq handler. But this oneliner should suffice for most cases, so far. Reported-by: Baozeng Ding <[email protected]> Signed-off-by: Takashi Iwai <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gst_flxdec_chain (GstPad * pad, GstObject * parent, GstBuffer * buf) { GstCaps *caps; guint avail; GstFlowReturn res = GST_FLOW_OK; GstFlxDec *flxdec; FlxHeader *flxh; g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR); flxdec = (GstFlxDec *) parent; g_return_val_if_fail (flxdec != NULL, GST_FLOW_ERROR); gst_adapter_push (flxdec->adapter, buf); avail = gst_adapter_available (flxdec->adapter); if (flxdec->state == GST_FLXDEC_READ_HEADER) { if (avail >= FlxHeaderSize) { const guint8 *data = gst_adapter_map (flxdec->adapter, FlxHeaderSize); GstCaps *templ; memcpy ((gchar *) & flxdec->hdr, data, FlxHeaderSize); FLX_HDR_FIX_ENDIANNESS (&(flxdec->hdr)); gst_adapter_unmap (flxdec->adapter); gst_adapter_flush (flxdec->adapter, FlxHeaderSize); flxh = &flxdec->hdr; /* check header */ if (flxh->type != FLX_MAGICHDR_FLI && flxh->type != FLX_MAGICHDR_FLC && flxh->type != FLX_MAGICHDR_FLX) goto wrong_type; GST_LOG ("size : %d", flxh->size); GST_LOG ("frames : %d", flxh->frames); GST_LOG ("width : %d", flxh->width); GST_LOG ("height : %d", flxh->height); GST_LOG ("depth : %d", flxh->depth); GST_LOG ("speed : %d", flxh->speed); flxdec->next_time = 0; if (flxh->type == FLX_MAGICHDR_FLI) { flxdec->frame_time = JIFFIE * flxh->speed; } else if (flxh->speed == 0) { flxdec->frame_time = GST_SECOND / 70; } else { flxdec->frame_time = flxh->speed * GST_MSECOND; } flxdec->duration = flxh->frames * flxdec->frame_time; GST_LOG ("duration : %" GST_TIME_FORMAT, GST_TIME_ARGS (flxdec->duration)); templ = gst_pad_get_pad_template_caps (flxdec->srcpad); caps = gst_caps_copy (templ); gst_caps_unref (templ); gst_caps_set_simple (caps, "width", G_TYPE_INT, flxh->width, "height", G_TYPE_INT, flxh->height, "framerate", GST_TYPE_FRACTION, (gint) GST_MSECOND, (gint) flxdec->frame_time / 1000, NULL); gst_pad_set_caps (flxdec->srcpad, caps); gst_caps_unref (caps); if (flxh->depth <= 8) flxdec->converter = flx_colorspace_converter_new (flxh->width, flxh->height); if (flxh->type == FLX_MAGICHDR_FLC || flxh->type == FLX_MAGICHDR_FLX) { GST_LOG ("(FLC) aspect_dx : %d", flxh->aspect_dx); GST_LOG ("(FLC) aspect_dy : %d", flxh->aspect_dy); GST_LOG ("(FLC) oframe1 : 0x%08x", flxh->oframe1); GST_LOG ("(FLC) oframe2 : 0x%08x", flxh->oframe2); } flxdec->size = ((guint) flxh->width * (guint) flxh->height); /* create delta and output frame */ flxdec->frame_data = g_malloc (flxdec->size); flxdec->delta_data = g_malloc (flxdec->size); flxdec->state = GST_FLXDEC_PLAYING; } } else if (flxdec->state == GST_FLXDEC_PLAYING) { GstBuffer *out; /* while we have enough data in the adapter */ while (avail >= FlxFrameChunkSize && res == GST_FLOW_OK) { FlxFrameChunk flxfh; guchar *chunk; const guint8 *data; GstMapInfo map; chunk = NULL; data = gst_adapter_map (flxdec->adapter, FlxFrameChunkSize); memcpy (&flxfh, data, FlxFrameChunkSize); FLX_FRAME_CHUNK_FIX_ENDIANNESS (&flxfh); gst_adapter_unmap (flxdec->adapter); switch (flxfh.id) { case FLX_FRAME_TYPE: /* check if we have the complete frame */ if (avail < flxfh.size) goto need_more_data; /* flush header */ gst_adapter_flush (flxdec->adapter, FlxFrameChunkSize); chunk = gst_adapter_take (flxdec->adapter, flxfh.size - FlxFrameChunkSize); FLX_FRAME_TYPE_FIX_ENDIANNESS ((FlxFrameType *) chunk); if (((FlxFrameType *) chunk)->chunks == 0) break; /* create 32 bits output frame */ // res = gst_pad_alloc_buffer_and_set_caps (flxdec->srcpad, // GST_BUFFER_OFFSET_NONE, // flxdec->size * 4, GST_PAD_CAPS (flxdec->srcpad), &out); // if (res != GST_FLOW_OK) // break; out = gst_buffer_new_and_alloc (flxdec->size * 4); /* decode chunks */ if (!flx_decode_chunks (flxdec, ((FlxFrameType *) chunk)->chunks, chunk + FlxFrameTypeSize, flxdec->frame_data)) { GST_ELEMENT_ERROR (flxdec, STREAM, DECODE, ("%s", "Could not decode chunk"), NULL); return GST_FLOW_ERROR; } /* save copy of the current frame for possible delta. */ memcpy (flxdec->delta_data, flxdec->frame_data, flxdec->size); gst_buffer_map (out, &map, GST_MAP_WRITE); /* convert current frame. */ flx_colorspace_convert (flxdec->converter, flxdec->frame_data, map.data); gst_buffer_unmap (out, &map); GST_BUFFER_TIMESTAMP (out) = flxdec->next_time; flxdec->next_time += flxdec->frame_time; res = gst_pad_push (flxdec->srcpad, out); break; default: /* check if we have the complete frame */ if (avail < flxfh.size) goto need_more_data; gst_adapter_flush (flxdec->adapter, flxfh.size); break; } g_free (chunk); avail = gst_adapter_available (flxdec->adapter); } } need_more_data: return res; /* ERRORS */ wrong_type: { GST_ELEMENT_ERROR (flxdec, STREAM, WRONG_TYPE, (NULL), ("not a flx file (type %x)", flxh->type)); gst_object_unref (flxdec); return GST_FLOW_ERROR; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'flxdec: Don't unref() parent in the chain function We don't own the reference here, it is owned by the caller and given to us for the scope of this function. Leftover mistake from 0.10 porting. https://bugzilla.gnome.org/show_bug.cgi?id=774897'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gst_mpegts_section_new (guint16 pid, guint8 * data, gsize data_size) { GstMpegtsSection *res = NULL; guint8 tmp; guint8 table_id; guint16 section_length; /* Check for length */ section_length = GST_READ_UINT16_BE (data + 1) & 0x0FFF; if (G_UNLIKELY (data_size < section_length + 3)) goto short_packet; /* Table id is in first byte */ table_id = *data; res = _gst_mpegts_section_init (pid, table_id); res->data = data; /* table_id (already parsed) : 8 bit */ data++; /* section_syntax_indicator : 1 bit * other_fields (reserved) : 3 bit*/ res->short_section = (*data & 0x80) == 0x00; /* section_length (already parsed) : 12 bit */ res->section_length = section_length + 3; if (!res->short_section) { /* CRC is after section_length (-4 for the size of the CRC) */ res->crc = GST_READ_UINT32_BE (res->data + res->section_length - 4); /* Skip to after section_length */ data += 2; /* subtable extension : 16 bit */ res->subtable_extension = GST_READ_UINT16_BE (data); data += 2; /* reserved : 2 bit * version_number : 5 bit * current_next_indicator : 1 bit */ tmp = *data++; res->version_number = tmp >> 1 & 0x1f; res->current_next_indicator = tmp & 0x01; /* section_number : 8 bit */ res->section_number = *data++; /* last_section_number : 8 bit */ res->last_section_number = *data; } return res; short_packet: { GST_WARNING ("PID 0x%04x section extends past provided data (got:%" G_GSIZE_FORMAT ", need:%d)", pid, data_size, section_length + 3); g_free (data); return NULL; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'mpegtssection: Add more section size checks The smallest section ever needs to be at least 3 bytes (i.e. just the short header). Non-short headers need to be at least 11 bytes long (3 for the minimum header, 5 for the non-short header, and 4 for the CRC). https://bugzilla.gnome.org/show_bug.cgi?id=775048'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int val; int valbool; struct linger ling; int ret = 0; /* * Options without arguments */ if (optname == SO_BINDTODEVICE) return sock_setbindtodevice(sk, optval, optlen); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; valbool = val ? 1 : 0; lock_sock(sk); switch (optname) { case SO_DEBUG: if (val && !capable(CAP_NET_ADMIN)) ret = -EACCES; else sock_valbool_flag(sk, SOCK_DBG, valbool); break; case SO_REUSEADDR: sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE); break; case SO_REUSEPORT: sk->sk_reuseport = valbool; break; case SO_TYPE: case SO_PROTOCOL: case SO_DOMAIN: case SO_ERROR: ret = -ENOPROTOOPT; break; case SO_DONTROUTE: sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool); break; case SO_BROADCAST: sock_valbool_flag(sk, SOCK_BROADCAST, valbool); break; case SO_SNDBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_wmem_max); set_sndbuf: sk->sk_userlocks |= SOCK_SNDBUF_LOCK; sk->sk_sndbuf = max_t(u32, val * 2, SOCK_MIN_SNDBUF); /* Wake up sending tasks if we upped the value. */ sk->sk_write_space(sk); break; case SO_SNDBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_sndbuf; case SO_RCVBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_rmem_max); set_rcvbuf: sk->sk_userlocks |= SOCK_RCVBUF_LOCK; /* * We double it on the way in to account for * "struct sk_buff" etc. overhead. Applications * assume that the SO_RCVBUF setting they make will * allow that much actual data to be received on that * socket. * * Applications are unaware that "struct sk_buff" and * other overheads allocate from the receive buffer * during socket buffer allocation. * * And after considering the possible alternatives, * returning the value we actually used in getsockopt * is the most desirable behavior. */ sk->sk_rcvbuf = max_t(u32, val * 2, SOCK_MIN_RCVBUF); break; case SO_RCVBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_rcvbuf; case SO_KEEPALIVE: #ifdef CONFIG_INET if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) tcp_set_keepalive(sk, valbool); #endif sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool); break; case SO_OOBINLINE: sock_valbool_flag(sk, SOCK_URGINLINE, valbool); break; case SO_NO_CHECK: sk->sk_no_check_tx = valbool; break; case SO_PRIORITY: if ((val >= 0 && val <= 6) || ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) sk->sk_priority = val; else ret = -EPERM; break; case SO_LINGER: if (optlen < sizeof(ling)) { ret = -EINVAL; /* 1003.1g */ break; } if (copy_from_user(&ling, optval, sizeof(ling))) { ret = -EFAULT; break; } if (!ling.l_onoff) sock_reset_flag(sk, SOCK_LINGER); else { #if (BITS_PER_LONG == 32) if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ) sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT; else #endif sk->sk_lingertime = (unsigned int)ling.l_linger * HZ; sock_set_flag(sk, SOCK_LINGER); } break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism("setsockopt"); break; case SO_PASSCRED: if (valbool) set_bit(SOCK_PASSCRED, &sock->flags); else clear_bit(SOCK_PASSCRED, &sock->flags); break; case SO_TIMESTAMP: case SO_TIMESTAMPNS: if (valbool) { if (optname == SO_TIMESTAMP) sock_reset_flag(sk, SOCK_RCVTSTAMPNS); else sock_set_flag(sk, SOCK_RCVTSTAMPNS); sock_set_flag(sk, SOCK_RCVTSTAMP); sock_enable_timestamp(sk, SOCK_TIMESTAMP); } else { sock_reset_flag(sk, SOCK_RCVTSTAMP); sock_reset_flag(sk, SOCK_RCVTSTAMPNS); } break; case SO_TIMESTAMPING: if (val & ~SOF_TIMESTAMPING_MASK) { ret = -EINVAL; break; } if (val & SOF_TIMESTAMPING_OPT_ID && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)) { if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) { if ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)) { ret = -EINVAL; break; } sk->sk_tskey = tcp_sk(sk)->snd_una; } else { sk->sk_tskey = 0; } } sk->sk_tsflags = val; if (val & SOF_TIMESTAMPING_RX_SOFTWARE) sock_enable_timestamp(sk, SOCK_TIMESTAMPING_RX_SOFTWARE); else sock_disable_timestamp(sk, (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE)); break; case SO_RCVLOWAT: if (val < 0) val = INT_MAX; sk->sk_rcvlowat = val ? : 1; break; case SO_RCVTIMEO: ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen); break; case SO_SNDTIMEO: ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen); break; case SO_ATTACH_FILTER: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_attach_filter(&fprog, sk); } break; case SO_ATTACH_BPF: ret = -EINVAL; if (optlen == sizeof(u32)) { u32 ufd; ret = -EFAULT; if (copy_from_user(&ufd, optval, sizeof(ufd))) break; ret = sk_attach_bpf(ufd, sk); } break; case SO_ATTACH_REUSEPORT_CBPF: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_reuseport_attach_filter(&fprog, sk); } break; case SO_ATTACH_REUSEPORT_EBPF: ret = -EINVAL; if (optlen == sizeof(u32)) { u32 ufd; ret = -EFAULT; if (copy_from_user(&ufd, optval, sizeof(ufd))) break; ret = sk_reuseport_attach_bpf(ufd, sk); } break; case SO_DETACH_FILTER: ret = sk_detach_filter(sk); break; case SO_LOCK_FILTER: if (sock_flag(sk, SOCK_FILTER_LOCKED) && !valbool) ret = -EPERM; else sock_valbool_flag(sk, SOCK_FILTER_LOCKED, valbool); break; case SO_PASSSEC: if (valbool) set_bit(SOCK_PASSSEC, &sock->flags); else clear_bit(SOCK_PASSSEC, &sock->flags); break; case SO_MARK: if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) ret = -EPERM; else sk->sk_mark = val; break; case SO_RXQ_OVFL: sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool); break; case SO_WIFI_STATUS: sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool); break; case SO_PEEK_OFF: if (sock->ops->set_peek_off) ret = sock->ops->set_peek_off(sk, val); else ret = -EOPNOTSUPP; break; case SO_NOFCS: sock_valbool_flag(sk, SOCK_NOFCS, valbool); break; case SO_SELECT_ERR_QUEUE: sock_valbool_flag(sk, SOCK_SELECT_ERR_QUEUE, valbool); break; #ifdef CONFIG_NET_RX_BUSY_POLL case SO_BUSY_POLL: /* allow unprivileged users to decrease the value */ if ((val > sk->sk_ll_usec) && !capable(CAP_NET_ADMIN)) ret = -EPERM; else { if (val < 0) ret = -EINVAL; else sk->sk_ll_usec = val; } break; #endif case SO_MAX_PACING_RATE: sk->sk_max_pacing_rate = val; sk->sk_pacing_rate = min(sk->sk_pacing_rate, sk->sk_max_pacing_rate); break; case SO_INCOMING_CPU: sk->sk_incoming_cpu = val; break; case SO_CNX_ADVICE: if (val == 1) dst_negative_advice(sk); break; default: ret = -ENOPROTOOPT; break; } release_sock(sk); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'net: avoid signed overflows for SO_{SND|RCV}BUFFORCE CAP_NET_ADMIN users should not be allowed to set negative sk_sndbuf or sk_rcvbuf values, as it can lead to various memory corruptions, crashes, OOM... Note that before commit 82981930125a ("net: cleanups in sock_setsockopt()"), the bug was even more serious, since SO_SNDBUF and SO_RCVBUF were vulnerable. This needs to be backported to all known linux kernels. Again, many thanks to syzkaller team for discovering this gem. Signed-off-by: Eric Dumazet <[email protected]> Reported-by: Andrey Konovalov <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int val; int valbool; struct linger ling; int ret = 0; /* * Options without arguments */ if (optname == SO_BINDTODEVICE) return sock_bindtodevice(sk, optval, optlen); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; valbool = val ? 1 : 0; lock_sock(sk); switch (optname) { case SO_DEBUG: if (val && !capable(CAP_NET_ADMIN)) ret = -EACCES; else sock_valbool_flag(sk, SOCK_DBG, valbool); break; case SO_REUSEADDR: sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE); break; case SO_TYPE: case SO_PROTOCOL: case SO_DOMAIN: case SO_ERROR: ret = -ENOPROTOOPT; break; case SO_DONTROUTE: sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool); break; case SO_BROADCAST: sock_valbool_flag(sk, SOCK_BROADCAST, valbool); break; case SO_SNDBUF: /* Don't error on this BSD doesn't and if you think about it this is right. Otherwise apps have to play 'guess the biggest size' games. RCVBUF/SNDBUF are treated in BSD as hints */ if (val > sysctl_wmem_max) val = sysctl_wmem_max; set_sndbuf: sk->sk_userlocks |= SOCK_SNDBUF_LOCK; if ((val * 2) < SOCK_MIN_SNDBUF) sk->sk_sndbuf = SOCK_MIN_SNDBUF; else sk->sk_sndbuf = val * 2; /* * Wake up sending tasks if we * upped the value. */ sk->sk_write_space(sk); break; case SO_SNDBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_sndbuf; case SO_RCVBUF: /* Don't error on this BSD doesn't and if you think about it this is right. Otherwise apps have to play 'guess the biggest size' games. RCVBUF/SNDBUF are treated in BSD as hints */ if (val > sysctl_rmem_max) val = sysctl_rmem_max; set_rcvbuf: sk->sk_userlocks |= SOCK_RCVBUF_LOCK; /* * We double it on the way in to account for * "struct sk_buff" etc. overhead. Applications * assume that the SO_RCVBUF setting they make will * allow that much actual data to be received on that * socket. * * Applications are unaware that "struct sk_buff" and * other overheads allocate from the receive buffer * during socket buffer allocation. * * And after considering the possible alternatives, * returning the value we actually used in getsockopt * is the most desirable behavior. */ if ((val * 2) < SOCK_MIN_RCVBUF) sk->sk_rcvbuf = SOCK_MIN_RCVBUF; else sk->sk_rcvbuf = val * 2; break; case SO_RCVBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_rcvbuf; case SO_KEEPALIVE: #ifdef CONFIG_INET if (sk->sk_protocol == IPPROTO_TCP) tcp_set_keepalive(sk, valbool); #endif sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool); break; case SO_OOBINLINE: sock_valbool_flag(sk, SOCK_URGINLINE, valbool); break; case SO_NO_CHECK: sk->sk_no_check = valbool; break; case SO_PRIORITY: if ((val >= 0 && val <= 6) || capable(CAP_NET_ADMIN)) sk->sk_priority = val; else ret = -EPERM; break; case SO_LINGER: if (optlen < sizeof(ling)) { ret = -EINVAL; /* 1003.1g */ break; } if (copy_from_user(&ling, optval, sizeof(ling))) { ret = -EFAULT; break; } if (!ling.l_onoff) sock_reset_flag(sk, SOCK_LINGER); else { #if (BITS_PER_LONG == 32) if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ) sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT; else #endif sk->sk_lingertime = (unsigned int)ling.l_linger * HZ; sock_set_flag(sk, SOCK_LINGER); } break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism("setsockopt"); break; case SO_PASSCRED: if (valbool) set_bit(SOCK_PASSCRED, &sock->flags); else clear_bit(SOCK_PASSCRED, &sock->flags); break; case SO_TIMESTAMP: case SO_TIMESTAMPNS: if (valbool) { if (optname == SO_TIMESTAMP) sock_reset_flag(sk, SOCK_RCVTSTAMPNS); else sock_set_flag(sk, SOCK_RCVTSTAMPNS); sock_set_flag(sk, SOCK_RCVTSTAMP); sock_enable_timestamp(sk, SOCK_TIMESTAMP); } else { sock_reset_flag(sk, SOCK_RCVTSTAMP); sock_reset_flag(sk, SOCK_RCVTSTAMPNS); } break; case SO_TIMESTAMPING: if (val & ~SOF_TIMESTAMPING_MASK) { ret = -EINVAL; break; } sock_valbool_flag(sk, SOCK_TIMESTAMPING_TX_HARDWARE, val & SOF_TIMESTAMPING_TX_HARDWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_TX_SOFTWARE, val & SOF_TIMESTAMPING_TX_SOFTWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_RX_HARDWARE, val & SOF_TIMESTAMPING_RX_HARDWARE); if (val & SOF_TIMESTAMPING_RX_SOFTWARE) sock_enable_timestamp(sk, SOCK_TIMESTAMPING_RX_SOFTWARE); else sock_disable_timestamp(sk, (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE)); sock_valbool_flag(sk, SOCK_TIMESTAMPING_SOFTWARE, val & SOF_TIMESTAMPING_SOFTWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_SYS_HARDWARE, val & SOF_TIMESTAMPING_SYS_HARDWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_RAW_HARDWARE, val & SOF_TIMESTAMPING_RAW_HARDWARE); break; case SO_RCVLOWAT: if (val < 0) val = INT_MAX; sk->sk_rcvlowat = val ? : 1; break; case SO_RCVTIMEO: ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen); break; case SO_SNDTIMEO: ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen); break; case SO_ATTACH_FILTER: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_attach_filter(&fprog, sk); } break; case SO_DETACH_FILTER: ret = sk_detach_filter(sk); break; case SO_PASSSEC: if (valbool) set_bit(SOCK_PASSSEC, &sock->flags); else clear_bit(SOCK_PASSSEC, &sock->flags); break; case SO_MARK: if (!capable(CAP_NET_ADMIN)) ret = -EPERM; else sk->sk_mark = val; break; /* We implement the SO_SNDLOWAT etc to not be settable (1003.1g 5.3) */ case SO_RXQ_OVFL: sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool); break; case SO_WIFI_STATUS: sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool); break; case SO_PEEK_OFF: if (sock->ops->set_peek_off) sock->ops->set_peek_off(sk, val); else ret = -EOPNOTSUPP; break; case SO_NOFCS: sock_valbool_flag(sk, SOCK_NOFCS, valbool); break; default: ret = -ENOPROTOOPT; break; } release_sock(sk); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'net: cleanups in sock_setsockopt() Use min_t()/max_t() macros, reformat two comments, use !!test_bit() to match !!sock_flag() Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work) codetype type; unsigned short FAR *lens; unsigned codes; code FAR * FAR *table; unsigned FAR *bits; unsigned short FAR *work; { unsigned len; /* a code's length in bits */ unsigned sym; /* index of code symbols */ unsigned min, max; /* minimum and maximum code lengths */ unsigned root; /* number of index bits for root table */ unsigned curr; /* number of index bits for current table */ unsigned drop; /* code bits to drop for sub-table */ int left; /* number of prefix codes available */ unsigned used; /* code entries in table used */ unsigned huff; /* Huffman code */ unsigned incr; /* for incrementing code, index */ unsigned fill; /* index for replicating entries */ unsigned low; /* low bits for current root entry */ unsigned mask; /* mask for low root bits */ code here; /* table entry for duplication */ code FAR *next; /* next available space in table */ const unsigned short FAR *base; /* base value table to use */ const unsigned short FAR *extra; /* extra bits table to use */ int end; /* use base and extra for symbol > end */ unsigned short count[MAXBITS+1]; /* number of codes of each length */ unsigned short offs[MAXBITS+1]; /* offsets in table for each length */ static const unsigned short lbase[31] = { /* Length codes 257..285 base */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; static const unsigned short lext[31] = { /* Length codes 257..285 extra */ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 203, 198}; static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0}; static const unsigned short dext[32] = { /* Distance codes 0..29 extra */ 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64}; /* Process a set of code lengths to create a canonical Huffman code. The code lengths are lens[0..codes-1]. Each length corresponds to the symbols 0..codes-1. The Huffman code is generated by first sorting the symbols by length from short to long, and retaining the symbol order for codes with equal lengths. Then the code starts with all zero bits for the first code of the shortest length, and the codes are integer increments for the same length, and zeros are appended as the length increases. For the deflate format, these bits are stored backwards from their more natural integer increment ordering, and so when the decoding tables are built in the large loop below, the integer codes are incremented backwards. This routine assumes, but does not check, that all of the entries in lens[] are in the range 0..MAXBITS. The caller must assure this. 1..MAXBITS is interpreted as that code length. zero means that that symbol does not occur in this code. The codes are sorted by computing a count of codes for each length, creating from that a table of starting indices for each length in the sorted table, and then entering the symbols in order in the sorted table. The sorted table is work[], with that space being provided by the caller. The length counts are used for other purposes as well, i.e. finding the minimum and maximum length codes, determining if there are any codes at all, checking for a valid set of lengths, and looking ahead at length counts to determine sub-table sizes when building the decoding tables. */ /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ for (len = 0; len <= MAXBITS; len++) count[len] = 0; for (sym = 0; sym < codes; sym++) count[lens[sym]]++; /* bound code lengths, force root to be within code lengths */ root = *bits; for (max = MAXBITS; max >= 1; max--) if (count[max] != 0) break; if (root > max) root = max; if (max == 0) { /* no symbols to code at all */ here.op = (unsigned char)64; /* invalid code marker */ here.bits = (unsigned char)1; here.val = (unsigned short)0; *(*table)++ = here; /* make a table to force an error */ *(*table)++ = here; *bits = 1; return 0; /* no symbols, but wait for decoding to report error */ } for (min = 1; min < max; min++) if (count[min] != 0) break; if (root < min) root = min; /* check for an over-subscribed or incomplete set of lengths */ left = 1; for (len = 1; len <= MAXBITS; len++) { left <<= 1; left -= count[len]; if (left < 0) return -1; /* over-subscribed */ } if (left > 0 && (type == CODES || max != 1)) return -1; /* incomplete set */ /* generate offsets into symbol table for each length for sorting */ offs[1] = 0; for (len = 1; len < MAXBITS; len++) offs[len + 1] = offs[len] + count[len]; /* sort symbols by length, by symbol order within each length */ for (sym = 0; sym < codes; sym++) if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym; /* Create and fill in decoding tables. In this loop, the table being filled is at next and has curr index bits. The code being used is huff with length len. That code is converted to an index by dropping drop bits off of the bottom. For codes where len is less than drop + curr, those top drop + curr - len bits are incremented through all values to fill the table with replicated entries. root is the number of index bits for the root table. When len exceeds root, sub-tables are created pointed to by the root entry with an index of the low root bits of huff. This is saved in low to check for when a new sub-table should be started. drop is zero when the root table is being filled, and drop is root when sub-tables are being filled. When a new sub-table is needed, it is necessary to look ahead in the code lengths to determine what size sub-table is needed. The length counts are used for this, and so count[] is decremented as codes are entered in the tables. used keeps track of how many table entries have been allocated from the provided *table space. It is checked for LENS and DIST tables against the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in the initial root table size constants. See the comments in inftrees.h for more information. sym increments through all symbols, and the loop terminates when all codes of length max, i.e. all codes, have been processed. This routine permits incomplete codes, so another loop after this one fills in the rest of the decoding tables with invalid code markers. */ /* set up for code type */ switch (type) { case CODES: base = extra = work; /* dummy value--not used */ end = 19; break; case LENS: base = lbase; base -= 257; extra = lext; extra -= 257; end = 256; break; default: /* DISTS */ base = dbase; extra = dext; end = -1; } /* initialize state for loop */ huff = 0; /* starting code */ sym = 0; /* starting code symbol */ len = min; /* starting code length */ next = *table; /* current table to fill in */ curr = root; /* current table index bits */ drop = 0; /* current bits to drop from code for index */ low = (unsigned)(-1); /* trigger new sub-table when len > root */ used = 1U << root; /* use root table entries */ mask = used - 1; /* mask for comparing low */ /* check available table space */ if ((type == LENS && used > ENOUGH_LENS) || (type == DISTS && used > ENOUGH_DISTS)) return 1; /* process all codes and make table entries */ for (;;) { /* create table entry */ here.bits = (unsigned char)(len - drop); if ((int)(work[sym]) < end) { here.op = (unsigned char)0; here.val = work[sym]; } else if ((int)(work[sym]) > end) { here.op = (unsigned char)(extra[work[sym]]); here.val = base[work[sym]]; } else { here.op = (unsigned char)(32 + 64); /* end of block */ here.val = 0; } /* replicate for those indices with low len bits equal to huff */ incr = 1U << (len - drop); fill = 1U << curr; min = fill; /* save offset to next table */ do { fill -= incr; next[(huff >> drop) + fill] = here; } while (fill != 0); /* backwards increment the len-bit code huff */ incr = 1U << (len - 1); while (huff & incr) incr >>= 1; if (incr != 0) { huff &= incr - 1; huff += incr; } else huff = 0; /* go to next symbol, update count, len */ sym++; if (--(count[len]) == 0) { if (len == max) break; len = lens[work[sym]]; } /* create new sub-table if needed */ if (len > root && (huff & mask) != low) { /* if first time, transition to sub-tables */ if (drop == 0) drop = root; /* increment past last table */ next += min; /* here min is 1 << curr */ /* determine length of next table */ curr = len - drop; left = (int)(1 << curr); while (curr + drop < max) { left -= count[curr + drop]; if (left <= 0) break; curr++; left <<= 1; } /* check for enough space */ used += 1U << curr; if ((type == LENS && used > ENOUGH_LENS) || (type == DISTS && used > ENOUGH_DISTS)) return 1; /* point entry in root table to sub-table */ low = huff & mask; (*table)[low].op = (unsigned char)curr; (*table)[low].bits = (unsigned char)root; (*table)[low].val = (unsigned short)(next - *table); } } /* fill in remaining table entry if code is incomplete (guaranteed to have at most one remaining entry, since if the code is incomplete, the maximum code length that was allowed to get this far is one bit) */ if (huff != 0) { here.op = (unsigned char)64; /* invalid code marker */ here.bits = (unsigned char)(len - drop); here.val = (unsigned short)0; next[huff] = here; } /* set return parameters */ *table += used; *bits = root; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Remove offset pointer optimization in inftrees.c. inftrees.c was subtracting an offset from a pointer to an array, in order to provide a pointer that allowed indexing starting at the offset. This is not compliant with the C standard, for which the behavior of a pointer decremented before its allocated memory is undefined. Per the recommendation of a security audit of the zlib code by Trail of Bits and TrustInSoft, in support of the Mozilla Foundation, this tiny optimization was removed, in order to avoid the possibility of undefined behavior.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: long ZEXPORT inflateMark(strm) z_streamp strm; { struct inflate_state FAR *state; if (strm == Z_NULL || strm->state == Z_NULL) return -1L << 16; state = (struct inflate_state FAR *)strm->state; return ((long)(state->back) << 16) + (state->mode == COPY ? state->length : (state->mode == MATCH ? state->was - state->length : 0)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Avoid shifts of negative values inflateMark(). The C standard says that bit shifts of negative integers is undefined. This casts to unsigned values to assure a known result.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: local unsigned long crc32_big(crc, buf, len) unsigned long crc; const unsigned char FAR *buf; unsigned len; { register z_crc_t c; register const z_crc_t FAR *buf4; c = ZSWAP32((z_crc_t)crc); c = ~c; while (len && ((ptrdiff_t)buf & 3)) { c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); len--; } buf4 = (const z_crc_t FAR *)(const void FAR *)buf; buf4--; while (len >= 32) { DOBIG32; len -= 32; } while (len >= 4) { DOBIG4; len -= 4; } buf4++; buf = (const unsigned char FAR *)buf4; if (len) do { c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); } while (--len); c = ~c; return (unsigned long)(ZSWAP32(c)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Avoid pre-decrement of pointer in big-endian CRC calculation. There was a small optimization for PowerPCs to pre-increment a pointer when accessing a word, instead of post-incrementing. This required prefacing the loop with a decrement of the pointer, possibly pointing before the object passed. This is not compliant with the C standard, for which decrementing a pointer before its allocated memory is undefined. When tested on a modern PowerPC with a modern compiler, the optimization no longer has any effect. Due to all that, and per the recommendation of a security audit of the zlib code by Trail of Bits and TrustInSoft, in support of the Mozilla Foundation, this "optimization" was removed, in order to avoid the possibility of undefined behavior.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void qemu_chr_be_event(CharDriverState *s, int event) { /* Keep track if the char device is open */ switch (event) { case CHR_EVENT_OPENED: s->be_open = 1; break; case CHR_EVENT_CLOSED: s->be_open = 0; break; } if (!s->chr_event) return; s->chr_event(s->handler_opaque, event); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'char: move front end handlers in CharBackend Since the hanlders are associated with a CharBackend, rather than the CharDriverState, it is more appropriate to store in CharBackend. This avoids the handler copy dance in qemu_chr_fe_set_handlers() then mux_chr_update_read_handler(), by storing the CharBackend pointer directly. Also a mux CharDriver should go through mux->backends[focused], since chr->be will stay NULL. Before that, it was possible to call chr->handler by mistake with surprising results, for ex through qemu_chr_be_can_write(), which would result in calling the last set handler front end, not the one with focus. Signed-off-by: Marc-André Lureau <[email protected]> Message-Id: <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void qemu_chr_fe_set_handlers(CharBackend *b, IOCanReadHandler *fd_can_read, IOReadHandler *fd_read, IOEventHandler *fd_event, void *opaque, GMainContext *context) { CharDriverState *s; int fe_open; s = b->chr; if (!s) { return; } if (!opaque && !fd_can_read && !fd_read && !fd_event) { fe_open = 0; remove_fd_in_watch(s); } else { fe_open = 1; } s->chr_can_read = fd_can_read; s->chr_read = fd_read; s->chr_event = fd_event; s->handler_opaque = opaque; if (s->chr_update_read_handler) { s->chr_update_read_handler(s, context, b->tag); } if (!s->explicit_fe_open) { qemu_chr_fe_set_open(b, fe_open); } if (fe_open) { qemu_chr_fe_take_focus(b); /* We're connecting to an already opened device, so let's make sure we also get the open event */ if (s->be_open) { qemu_chr_be_generic_open(s); } } if (s->is_mux) { mux_chr_set_handlers(s, context); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'char: move front end handlers in CharBackend Since the hanlders are associated with a CharBackend, rather than the CharDriverState, it is more appropriate to store in CharBackend. This avoids the handler copy dance in qemu_chr_fe_set_handlers() then mux_chr_update_read_handler(), by storing the CharBackend pointer directly. Also a mux CharDriver should go through mux->backends[focused], since chr->be will stay NULL. Before that, it was possible to call chr->handler by mistake with surprising results, for ex through qemu_chr_be_can_write(), which would result in calling the last set handler front end, not the one with focus. Signed-off-by: Marc-André Lureau <[email protected]> Message-Id: <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void mux_chr_accept_input(CharDriverState *chr) { MuxDriver *d = chr->opaque; int m = d->focus; while (d->prod[m] != d->cons[m] && d->chr_can_read[m] && d->chr_can_read[m](d->ext_opaque[m])) { d->chr_read[m](d->ext_opaque[m], &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'char: move front end handlers in CharBackend Since the hanlders are associated with a CharBackend, rather than the CharDriverState, it is more appropriate to store in CharBackend. This avoids the handler copy dance in qemu_chr_fe_set_handlers() then mux_chr_update_read_handler(), by storing the CharBackend pointer directly. Also a mux CharDriver should go through mux->backends[focused], since chr->be will stay NULL. Before that, it was possible to call chr->handler by mistake with surprising results, for ex through qemu_chr_be_can_write(), which would result in calling the last set handler front end, not the one with focus. Signed-off-by: Marc-André Lureau <[email protected]> Message-Id: <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void mux_chr_update_read_handler(CharDriverState *chr, GMainContext *context, int tag) { MuxDriver *d = chr->opaque; assert(tag >= 0); assert(tag < d->mux_cnt); d->ext_opaque[tag] = chr->handler_opaque; d->chr_can_read[tag] = chr->chr_can_read; d->chr_read[tag] = chr->chr_read; d->chr_event[tag] = chr->chr_event; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'char: move front end handlers in CharBackend Since the hanlders are associated with a CharBackend, rather than the CharDriverState, it is more appropriate to store in CharBackend. This avoids the handler copy dance in qemu_chr_fe_set_handlers() then mux_chr_update_read_handler(), by storing the CharBackend pointer directly. Also a mux CharDriver should go through mux->backends[focused], since chr->be will stay NULL. Before that, it was possible to call chr->handler by mistake with surprising results, for ex through qemu_chr_be_can_write(), which would result in calling the last set handler front end, not the one with focus. Signed-off-by: Marc-André Lureau <[email protected]> Message-Id: <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int mux_chr_new_handler_tag(CharDriverState *chr, Error **errp) { MuxDriver *d = chr->opaque; if (d->mux_cnt >= MAX_MUX) { fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n"); return -1; } return d->mux_cnt++; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'char: move front end handlers in CharBackend Since the hanlders are associated with a CharBackend, rather than the CharDriverState, it is more appropriate to store in CharBackend. This avoids the handler copy dance in qemu_chr_fe_set_handlers() then mux_chr_update_read_handler(), by storing the CharBackend pointer directly. Also a mux CharDriver should go through mux->backends[focused], since chr->be will stay NULL. Before that, it was possible to call chr->handler by mistake with surprising results, for ex through qemu_chr_be_can_write(), which would result in calling the last set handler front end, not the one with focus. Signed-off-by: Marc-André Lureau <[email protected]> Message-Id: <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline void csrhci_fifo_wake(struct csrhci_s *s) { if (!s->enable || !s->out_len) return; /* XXX: Should wait for s->modem_state & CHR_TIOCM_RTS? */ if (s->chr.chr_can_read && s->chr.chr_can_read(s->chr.handler_opaque) && s->chr.chr_read) { s->chr.chr_read(s->chr.handler_opaque, s->outfifo + s->out_start ++, 1); s->out_len --; if (s->out_start >= s->out_size) { s->out_start = 0; s->out_size = FIFO_LEN; } } if (s->out_len) timer_mod(s->out_tm, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->baud_delay); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'char: move front end handlers in CharBackend Since the hanlders are associated with a CharBackend, rather than the CharDriverState, it is more appropriate to store in CharBackend. This avoids the handler copy dance in qemu_chr_fe_set_handlers() then mux_chr_update_read_handler(), by storing the CharBackend pointer directly. Also a mux CharDriver should go through mux->backends[focused], since chr->be will stay NULL. Before that, it was possible to call chr->handler by mistake with surprising results, for ex through qemu_chr_be_can_write(), which would result in calling the last set handler front end, not the one with focus. Signed-off-by: Marc-André Lureau <[email protected]> Message-Id: <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool qemu_chr_fe_init(CharBackend *b, CharDriverState *s, Error **errp) { int tag = 0; if (s->is_mux) { tag = mux_chr_new_handler_tag(s, errp); if (tag < 0) { return false; } } b->tag = tag; b->chr = s; return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'char: move front end handlers in CharBackend Since the hanlders are associated with a CharBackend, rather than the CharDriverState, it is more appropriate to store in CharBackend. This avoids the handler copy dance in qemu_chr_fe_set_handlers() then mux_chr_update_read_handler(), by storing the CharBackend pointer directly. Also a mux CharDriver should go through mux->backends[focused], since chr->be will stay NULL. Before that, it was possible to call chr->handler by mistake with surprising results, for ex through qemu_chr_be_can_write(), which would result in calling the last set handler front end, not the one with focus. Signed-off-by: Marc-André Lureau <[email protected]> Message-Id: <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void tcp_chr_update_read_handler(CharDriverState *chr, GMainContext *context, int tag) { TCPCharDriver *s = chr->opaque; if (!s->connected) { return; } remove_fd_in_watch(chr); if (s->ioc) { chr->fd_in_tag = io_add_watch_poll(s->ioc, tcp_chr_read_poll, tcp_chr_read, chr, context); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'char: move front end handlers in CharBackend Since the hanlders are associated with a CharBackend, rather than the CharDriverState, it is more appropriate to store in CharBackend. This avoids the handler copy dance in qemu_chr_fe_set_handlers() then mux_chr_update_read_handler(), by storing the CharBackend pointer directly. Also a mux CharDriver should go through mux->backends[focused], since chr->be will stay NULL. Before that, it was possible to call chr->handler by mistake with surprising results, for ex through qemu_chr_be_can_write(), which would result in calling the last set handler front end, not the one with focus. Signed-off-by: Marc-André Lureau <[email protected]> Message-Id: <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void kbd_put_keysym_console(QemuConsole *s, int keysym) { uint8_t buf[16], *q; int c; if (!s || (s->console_type == GRAPHIC_CONSOLE)) return; switch(keysym) { case QEMU_KEY_CTRL_UP: console_scroll(s, -1); break; case QEMU_KEY_CTRL_DOWN: console_scroll(s, 1); break; case QEMU_KEY_CTRL_PAGEUP: console_scroll(s, -10); break; case QEMU_KEY_CTRL_PAGEDOWN: console_scroll(s, 10); break; default: /* convert the QEMU keysym to VT100 key string */ q = buf; if (keysym >= 0xe100 && keysym <= 0xe11f) { *q++ = '\033'; *q++ = '['; c = keysym - 0xe100; if (c >= 10) *q++ = '0' + (c / 10); *q++ = '0' + (c % 10); *q++ = '~'; } else if (keysym >= 0xe120 && keysym <= 0xe17f) { *q++ = '\033'; *q++ = '['; *q++ = keysym & 0xff; } else if (s->echo && (keysym == '\r' || keysym == '\n')) { console_puts(s->chr, (const uint8_t *) "\r", 1); *q++ = '\n'; } else { *q++ = keysym; } if (s->echo) { console_puts(s->chr, buf, q - buf); } if (s->chr->chr_read) { qemu_fifo_write(&s->out_fifo, buf, q - buf); kbd_send_chars(s); } break; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'char: move front end handlers in CharBackend Since the hanlders are associated with a CharBackend, rather than the CharDriverState, it is more appropriate to store in CharBackend. This avoids the handler copy dance in qemu_chr_fe_set_handlers() then mux_chr_update_read_handler(), by storing the CharBackend pointer directly. Also a mux CharDriver should go through mux->backends[focused], since chr->be will stay NULL. Before that, it was possible to call chr->handler by mistake with surprising results, for ex through qemu_chr_be_can_write(), which would result in calling the last set handler front end, not the one with focus. Signed-off-by: Marc-André Lureau <[email protected]> Message-Id: <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event) { if (d->chr_event[mux_nr]) d->chr_event[mux_nr](d->ext_opaque[mux_nr], event); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'char: move front end handlers in CharBackend Since the hanlders are associated with a CharBackend, rather than the CharDriverState, it is more appropriate to store in CharBackend. This avoids the handler copy dance in qemu_chr_fe_set_handlers() then mux_chr_update_read_handler(), by storing the CharBackend pointer directly. Also a mux CharDriver should go through mux->backends[focused], since chr->be will stay NULL. Before that, it was possible to call chr->handler by mistake with surprising results, for ex through qemu_chr_be_can_write(), which would result in calling the last set handler front end, not the one with focus. Signed-off-by: Marc-André Lureau <[email protected]> Message-Id: <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int qemu_chr_be_can_write(CharDriverState *s) { if (!s->chr_can_read) return 0; return s->chr_can_read(s->handler_opaque); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'char: move front end handlers in CharBackend Since the hanlders are associated with a CharBackend, rather than the CharDriverState, it is more appropriate to store in CharBackend. This avoids the handler copy dance in qemu_chr_fe_set_handlers() then mux_chr_update_read_handler(), by storing the CharBackend pointer directly. Also a mux CharDriver should go through mux->backends[focused], since chr->be will stay NULL. Before that, it was possible to call chr->handler by mistake with surprising results, for ex through qemu_chr_be_can_write(), which would result in calling the last set handler front end, not the one with focus. Signed-off-by: Marc-André Lureau <[email protected]> Message-Id: <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static CharDriverState *qemu_chr_open_mux(const char *id, ChardevBackend *backend, ChardevReturn *ret, Error **errp) { ChardevMux *mux = backend->u.mux.data; CharDriverState *chr, *drv; MuxDriver *d; ChardevCommon *common = qapi_ChardevMux_base(mux); drv = qemu_chr_find(mux->chardev); if (drv == NULL) { error_setg(errp, "mux: base chardev %s not found", mux->chardev); return NULL; } chr = qemu_chr_alloc(common, errp); if (!chr) { return NULL; } d = g_new0(MuxDriver, 1); chr->opaque = d; d->focus = -1; chr->chr_close = mux_chr_close; chr->chr_write = mux_chr_write; chr->chr_update_read_handler = mux_chr_update_read_handler; chr->chr_accept_input = mux_chr_accept_input; /* Frontend guest-open / -close notification is not support with muxes */ chr->chr_set_fe_open = NULL; if (drv->chr_add_watch) { chr->chr_add_watch = mux_chr_add_watch; } /* only default to opened state if we've realized the initial * set of muxes */ chr->explicit_be_open = muxes_realized ? 0 : 1; chr->is_mux = 1; if (!qemu_chr_fe_init(&d->chr, drv, errp)) { qemu_chr_free(chr); return NULL; } return chr; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'char: move front end handlers in CharBackend Since the hanlders are associated with a CharBackend, rather than the CharDriverState, it is more appropriate to store in CharBackend. This avoids the handler copy dance in qemu_chr_fe_set_handlers() then mux_chr_update_read_handler(), by storing the CharBackend pointer directly. Also a mux CharDriver should go through mux->backends[focused], since chr->be will stay NULL. Before that, it was possible to call chr->handler by mistake with surprising results, for ex through qemu_chr_be_can_write(), which would result in calling the last set handler front end, not the one with focus. Signed-off-by: Marc-André Lureau <[email protected]> Message-Id: <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: tar_directory_for_file (GsfInfileTar *dir, const char *name, gboolean last) { const char *s = name; while (1) { const char *s0 = s; char *dirname; /* Find a directory component, if any. */ while (1) { if (*s == 0) { if (last && s != s0) break; else return dir; } /* This is deliberately slash-only. */ if (*s == '/') break; s++; } dirname = g_strndup (s0, s - s0); while (*s == '/') s++; if (strcmp (dirname, ".") != 0) { GsfInput *subdir = gsf_infile_child_by_name (GSF_INFILE (dir), dirname); if (subdir) { /* Undo the ref. */ g_object_unref (subdir); dir = GSF_INFILE_TAR (subdir); } else dir = tar_create_dir (dir, dirname); } g_free (dirname); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'tar: fix crash on broken tar file.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: asmlinkage long sys_oabi_fcntl64(unsigned int fd, unsigned int cmd, unsigned long arg) { struct oabi_flock64 user; struct flock64 kernel; mm_segment_t fs = USER_DS; /* initialized to kill a warning */ unsigned long local_arg = arg; int ret; switch (cmd) { case F_OFD_GETLK: case F_OFD_SETLK: case F_OFD_SETLKW: case F_GETLK64: case F_SETLK64: case F_SETLKW64: if (copy_from_user(&user, (struct oabi_flock64 __user *)arg, sizeof(user))) return -EFAULT; kernel.l_type = user.l_type; kernel.l_whence = user.l_whence; kernel.l_start = user.l_start; kernel.l_len = user.l_len; kernel.l_pid = user.l_pid; local_arg = (unsigned long)&kernel; fs = get_fs(); set_fs(KERNEL_DS); } ret = sys_fcntl64(fd, cmd, local_arg); switch (cmd) { case F_GETLK64: if (!ret) { user.l_type = kernel.l_type; user.l_whence = kernel.l_whence; user.l_start = kernel.l_start; user.l_len = kernel.l_len; user.l_pid = kernel.l_pid; if (copy_to_user((struct oabi_flock64 __user *)arg, &user, sizeof(user))) ret = -EFAULT; } case F_SETLK64: case F_SETLKW64: set_fs(fs); } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': '[PATCH] arm: fix handling of F_OFD_... in oabi_fcntl64() Cc: [email protected] # 3.15+ Reviewed-by: Jeff Layton <[email protected]> Signed-off-by: Al Viro <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int perf_event_refresh(struct perf_event *event, int refresh) { /* * not supported on inherited events */ if (event->attr.inherit || !is_sampling_event(event)) return -EINVAL; atomic_add(refresh, &event->event_limit); perf_event_enable(event); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'perf: Fix event->ctx locking There have been a few reported issues wrt. the lack of locking around changing event->ctx. This patch tries to address those. It avoids the whole rwsem thing; and while it appears to work, please give it some thought in review. What I did fail at is sensible runtime checks on the use of event->ctx, the RCU use makes it very hard. Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Paul E. McKenney <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { struct perf_event *event = file->private_data; return perf_read_hw(event, buf, count); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'perf: Fix event->ctx locking There have been a few reported issues wrt. the lack of locking around changing event->ctx. This patch tries to address those. It avoids the whole rwsem thing; and while it appears to work, please give it some thought in review. What I did fail at is sensible runtime checks on the use of event->ctx, the RCU use makes it very hard. Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Paul E. McKenney <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void perf_event_for_each(struct perf_event *event, void (*func)(struct perf_event *)) { struct perf_event_context *ctx = event->ctx; struct perf_event *sibling; WARN_ON_ONCE(ctx->parent_ctx); mutex_lock(&ctx->mutex); event = event->group_leader; perf_event_for_each_child(event, func); list_for_each_entry(sibling, &event->sibling_list, group_entry) perf_event_for_each_child(sibling, func); mutex_unlock(&ctx->mutex); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'perf: Fix event->ctx locking There have been a few reported issues wrt. the lack of locking around changing event->ctx. This patch tries to address those. It avoids the whole rwsem thing; and while it appears to work, please give it some thought in review. What I did fail at is sensible runtime checks on the use of event->ctx, the RCU use makes it very hard. Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Paul E. McKenney <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void perf_event_reset(struct perf_event *event) { (void)perf_event_read(event); local64_set(&event->count, 0); perf_event_update_userpage(event); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'perf: Fix event->ctx locking There have been a few reported issues wrt. the lack of locking around changing event->ctx. This patch tries to address those. It avoids the whole rwsem thing; and while it appears to work, please give it some thought in review. What I did fail at is sensible runtime checks on the use of event->ctx, the RCU use makes it very hard. Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Paul E. McKenney <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int perf_event_task_disable(void) { struct perf_event *event; mutex_lock(&current->perf_event_mutex); list_for_each_entry(event, &current->perf_event_list, owner_entry) perf_event_for_each_child(event, perf_event_disable); mutex_unlock(&current->perf_event_mutex); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'perf: Fix event->ctx locking There have been a few reported issues wrt. the lack of locking around changing event->ctx. This patch tries to address those. It avoids the whole rwsem thing; and while it appears to work, please give it some thought in review. What I did fail at is sensible runtime checks on the use of event->ctx, the RCU use makes it very hard. Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Paul E. McKenney <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SYSCALL_DEFINE5(perf_event_open, struct perf_event_attr __user *, attr_uptr, pid_t, pid, int, cpu, int, group_fd, unsigned long, flags) { struct perf_event *group_leader = NULL, *output_event = NULL; struct perf_event *event, *sibling; struct perf_event_attr attr; struct perf_event_context *ctx; struct file *event_file = NULL; struct fd group = {NULL, 0}; struct task_struct *task = NULL; struct pmu *pmu; int event_fd; int move_group = 0; int err; int f_flags = O_RDWR; /* for future expandability... */ if (flags & ~PERF_FLAG_ALL) return -EINVAL; err = perf_copy_attr(attr_uptr, &attr); if (err) return err; if (!attr.exclude_kernel) { if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN)) return -EACCES; } if (attr.freq) { if (attr.sample_freq > sysctl_perf_event_sample_rate) return -EINVAL; } else { if (attr.sample_period & (1ULL << 63)) return -EINVAL; } /* * In cgroup mode, the pid argument is used to pass the fd * opened to the cgroup directory in cgroupfs. The cpu argument * designates the cpu on which to monitor threads from that * cgroup. */ if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1)) return -EINVAL; if (flags & PERF_FLAG_FD_CLOEXEC) f_flags |= O_CLOEXEC; event_fd = get_unused_fd_flags(f_flags); if (event_fd < 0) return event_fd; if (group_fd != -1) { err = perf_fget_light(group_fd, &group); if (err) goto err_fd; group_leader = group.file->private_data; if (flags & PERF_FLAG_FD_OUTPUT) output_event = group_leader; if (flags & PERF_FLAG_FD_NO_GROUP) group_leader = NULL; } if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) { task = find_lively_task_by_vpid(pid); if (IS_ERR(task)) { err = PTR_ERR(task); goto err_group_fd; } } if (task && group_leader && group_leader->attr.inherit != attr.inherit) { err = -EINVAL; goto err_task; } get_online_cpus(); event = perf_event_alloc(&attr, cpu, task, group_leader, NULL, NULL, NULL); if (IS_ERR(event)) { err = PTR_ERR(event); goto err_cpus; } if (flags & PERF_FLAG_PID_CGROUP) { err = perf_cgroup_connect(pid, event, &attr, group_leader); if (err) { __free_event(event); goto err_cpus; } } if (is_sampling_event(event)) { if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) { err = -ENOTSUPP; goto err_alloc; } } account_event(event); /* * Special case software events and allow them to be part of * any hardware group. */ pmu = event->pmu; if (group_leader && (is_software_event(event) != is_software_event(group_leader))) { if (is_software_event(event)) { /* * If event and group_leader are not both a software * event, and event is, then group leader is not. * * Allow the addition of software events to !software * groups, this is safe because software events never * fail to schedule. */ pmu = group_leader->pmu; } else if (is_software_event(group_leader) && (group_leader->group_flags & PERF_GROUP_SOFTWARE)) { /* * In case the group is a pure software group, and we * try to add a hardware event, move the whole group to * the hardware context. */ move_group = 1; } } /* * Get the target context (task or percpu): */ ctx = find_get_context(pmu, task, event->cpu); if (IS_ERR(ctx)) { err = PTR_ERR(ctx); goto err_alloc; } if (task) { put_task_struct(task); task = NULL; } /* * Look up the group leader (we will attach this event to it): */ if (group_leader) { err = -EINVAL; /* * Do not allow a recursive hierarchy (this new sibling * becoming part of another group-sibling): */ if (group_leader->group_leader != group_leader) goto err_context; /* * Do not allow to attach to a group in a different * task or CPU context: */ if (move_group) { /* * Make sure we're both on the same task, or both * per-cpu events. */ if (group_leader->ctx->task != ctx->task) goto err_context; /* * Make sure we're both events for the same CPU; * grouping events for different CPUs is broken; since * you can never concurrently schedule them anyhow. */ if (group_leader->cpu != event->cpu) goto err_context; } else { if (group_leader->ctx != ctx) goto err_context; } /* * Only a group leader can be exclusive or pinned */ if (attr.exclusive || attr.pinned) goto err_context; } if (output_event) { err = perf_event_set_output(event, output_event); if (err) goto err_context; } event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, f_flags); if (IS_ERR(event_file)) { err = PTR_ERR(event_file); goto err_context; } if (move_group) { struct perf_event_context *gctx = group_leader->ctx; mutex_lock(&gctx->mutex); perf_remove_from_context(group_leader, false); /* * Removing from the context ends up with disabled * event. What we want here is event in the initial * startup state, ready to be add into new context. */ perf_event__state_init(group_leader); list_for_each_entry(sibling, &group_leader->sibling_list, group_entry) { perf_remove_from_context(sibling, false); perf_event__state_init(sibling); put_ctx(gctx); } mutex_unlock(&gctx->mutex); put_ctx(gctx); } WARN_ON_ONCE(ctx->parent_ctx); mutex_lock(&ctx->mutex); if (move_group) { synchronize_rcu(); perf_install_in_context(ctx, group_leader, group_leader->cpu); get_ctx(ctx); list_for_each_entry(sibling, &group_leader->sibling_list, group_entry) { perf_install_in_context(ctx, sibling, sibling->cpu); get_ctx(ctx); } } perf_install_in_context(ctx, event, event->cpu); perf_unpin_context(ctx); mutex_unlock(&ctx->mutex); put_online_cpus(); event->owner = current; mutex_lock(&current->perf_event_mutex); list_add_tail(&event->owner_entry, &current->perf_event_list); mutex_unlock(&current->perf_event_mutex); /* * Precalculate sample_data sizes */ perf_event__header_size(event); perf_event__id_header_size(event); /* * Drop the reference on the group_event after placing the * new event on the sibling_list. This ensures destruction * of the group leader will find the pointer to itself in * perf_group_detach(). */ fdput(group); fd_install(event_fd, event_file); return event_fd; err_context: perf_unpin_context(ctx); put_ctx(ctx); err_alloc: free_event(event); err_cpus: put_online_cpus(); err_task: if (task) put_task_struct(task); err_group_fd: fdput(group); err_fd: put_unused_fd(event_fd); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'perf: Fix event->ctx locking There have been a few reported issues wrt. the lack of locking around changing event->ctx. This patch tries to address those. It avoids the whole rwsem thing; and while it appears to work, please give it some thought in review. What I did fail at is sensible runtime checks on the use of event->ctx, the RCU use makes it very hard. Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Paul E. McKenney <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void perf_event_enable(struct perf_event *event) { struct perf_event_context *ctx = event->ctx; struct task_struct *task = ctx->task; if (!task) { /* * Enable the event on the cpu that it's on */ cpu_function_call(event->cpu, __perf_event_enable, event); return; } raw_spin_lock_irq(&ctx->lock); if (event->state >= PERF_EVENT_STATE_INACTIVE) goto out; /* * If the event is in error state, clear that first. * That way, if we see the event in error state below, we * know that it has gone back into error state, as distinct * from the task having been scheduled away before the * cross-call arrived. */ if (event->state == PERF_EVENT_STATE_ERROR) event->state = PERF_EVENT_STATE_OFF; retry: if (!ctx->is_active) { __perf_event_mark_enabled(event); goto out; } raw_spin_unlock_irq(&ctx->lock); if (!task_function_call(task, __perf_event_enable, event)) return; raw_spin_lock_irq(&ctx->lock); /* * If the context is active and the event is still off, * we need to retry the cross-call. */ if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) { /* * task could have been flipped by a concurrent * perf_event_context_sched_out() */ task = ctx->task; goto retry; } out: raw_spin_unlock_irq(&ctx->lock); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'perf: Fix event->ctx locking There have been a few reported issues wrt. the lack of locking around changing event->ctx. This patch tries to address those. It avoids the whole rwsem thing; and while it appears to work, please give it some thought in review. What I did fail at is sensible runtime checks on the use of event->ctx, the RCU use makes it very hard. Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Paul E. McKenney <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int mcryptd_create_hash(struct crypto_template *tmpl, struct rtattr **tb, struct mcryptd_queue *queue) { struct hashd_instance_ctx *ctx; struct ahash_instance *inst; struct hash_alg_common *halg; struct crypto_alg *alg; u32 type = 0; u32 mask = 0; int err; mcryptd_check_internal(tb, &type, &mask); halg = ahash_attr_alg(tb[1], type, mask); if (IS_ERR(halg)) return PTR_ERR(halg); alg = &halg->base; pr_debug("crypto: mcryptd hash alg: %s\n", alg->cra_name); inst = mcryptd_alloc_instance(alg, ahash_instance_headroom(), sizeof(*ctx)); err = PTR_ERR(inst); if (IS_ERR(inst)) goto out_put_alg; ctx = ahash_instance_ctx(inst); ctx->queue = queue; err = crypto_init_ahash_spawn(&ctx->spawn, halg, ahash_crypto_instance(inst)); if (err) goto out_free_inst; type = CRYPTO_ALG_ASYNC; if (alg->cra_flags & CRYPTO_ALG_INTERNAL) type |= CRYPTO_ALG_INTERNAL; inst->alg.halg.base.cra_flags = type; inst->alg.halg.digestsize = halg->digestsize; inst->alg.halg.statesize = halg->statesize; inst->alg.halg.base.cra_ctxsize = sizeof(struct mcryptd_hash_ctx); inst->alg.halg.base.cra_init = mcryptd_hash_init_tfm; inst->alg.halg.base.cra_exit = mcryptd_hash_exit_tfm; inst->alg.init = mcryptd_hash_init_enqueue; inst->alg.update = mcryptd_hash_update_enqueue; inst->alg.final = mcryptd_hash_final_enqueue; inst->alg.finup = mcryptd_hash_finup_enqueue; inst->alg.export = mcryptd_hash_export; inst->alg.import = mcryptd_hash_import; inst->alg.setkey = mcryptd_hash_setkey; inst->alg.digest = mcryptd_hash_digest_enqueue; err = ahash_register_instance(tmpl, inst); if (err) { crypto_drop_ahash(&ctx->spawn); out_free_inst: kfree(inst); } out_put_alg: crypto_mod_put(alg); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-284'], 'message': 'crypto: mcryptd - Check mcryptd algorithm compatibility Algorithms not compatible with mcryptd could be spawned by mcryptd with a direct crypto_alloc_tfm invocation using a "mcryptd(alg)" name construct. This causes mcryptd to crash the kernel if an arbitrary "alg" is incompatible and not intended to be used with mcryptd. It is an issue if AF_ALG tries to spawn mcryptd(alg) to expose it externally. But such algorithms must be used internally and not be exposed. We added a check to enforce that only internal algorithms are allowed with mcryptd at the time mcryptd is spawning an algorithm. Link: http://marc.info/?l=linux-crypto-vger&m=148063683310477&w=2 Cc: [email protected] Reported-by: Mikulas Patocka <[email protected]> Signed-off-by: Tim Chen <[email protected]> Signed-off-by: Herbert Xu <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void tty_set_termios_ldisc(struct tty_struct *tty, int num) { down_write(&tty->termios_rwsem); tty->termios.c_line = num; up_write(&tty->termios_rwsem); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'tty: Prevent ldisc drivers from re-using stale tty fields Line discipline drivers may mistakenly misuse ldisc-related fields when initializing. For example, a failure to initialize tty->receive_room in the N_GIGASET_M101 line discipline was recently found and fixed [1]. Now, the N_X25 line discipline has been discovered accessing the previous line discipline's already-freed private data [2]. Harden the ldisc interface against misuse by initializing revelant tty fields before instancing the new line discipline. [1] commit fd98e9419d8d622a4de91f76b306af6aa627aa9c Author: Tilman Schmidt <[email protected]> Date: Tue Jul 14 00:37:13 2015 +0200 isdn/gigaset: reset tty->receive_room when attaching ser_gigaset [2] Report from Sasha Levin <[email protected]> [ 634.336761] ================================================================== [ 634.338226] BUG: KASAN: use-after-free in x25_asy_open_tty+0x13d/0x490 at addr ffff8800a743efd0 [ 634.339558] Read of size 4 by task syzkaller_execu/8981 [ 634.340359] ============================================================================= [ 634.341598] BUG kmalloc-512 (Not tainted): kasan: bad access detected ... [ 634.405018] Call Trace: [ 634.405277] dump_stack (lib/dump_stack.c:52) [ 634.405775] print_trailer (mm/slub.c:655) [ 634.406361] object_err (mm/slub.c:662) [ 634.406824] kasan_report_error (mm/kasan/report.c:138 mm/kasan/report.c:236) [ 634.409581] __asan_report_load4_noabort (mm/kasan/report.c:279) [ 634.411355] x25_asy_open_tty (drivers/net/wan/x25_asy.c:559 (discriminator 1)) [ 634.413997] tty_ldisc_open.isra.2 (drivers/tty/tty_ldisc.c:447) [ 634.414549] tty_set_ldisc (drivers/tty/tty_ldisc.c:567) [ 634.415057] tty_ioctl (drivers/tty/tty_io.c:2646 drivers/tty/tty_io.c:2879) [ 634.423524] do_vfs_ioctl (fs/ioctl.c:43 fs/ioctl.c:607) [ 634.427491] SyS_ioctl (fs/ioctl.c:622 fs/ioctl.c:613) [ 634.427945] entry_SYSCALL_64_fastpath (arch/x86/entry/entry_64.S:188) Cc: Tilman Schmidt <[email protected]> Cc: Sasha Levin <[email protected]> Signed-off-by: Peter Hurley <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: BGD_DECLARE(void) gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color) { int lastBorder; /* Seek left */ int leftLimit, rightLimit; int i; int restoreAlphaBleding; if (border < 0) { /* Refuse to fill to a non-solid border */ return; } leftLimit = (-1); restoreAlphaBleding = im->alphaBlendingFlag; im->alphaBlendingFlag = 0; if (x >= im->sx) { x = im->sx - 1; } else if (x < 0) { x = 0; } if (y >= im->sy) { y = im->sy - 1; } else if (y < 0) { y = 0; } for (i = x; (i >= 0); i--) { if (gdImageGetPixel (im, i, y) == border) { break; } gdImageSetPixel (im, i, y, color); leftLimit = i; } if (leftLimit == (-1)) { im->alphaBlendingFlag = restoreAlphaBleding; return; } /* Seek right */ rightLimit = x; for (i = (x + 1); (i < im->sx); i++) { if (gdImageGetPixel (im, i, y) == border) { break; } gdImageSetPixel (im, i, y, color); rightLimit = i; } /* Look at lines above and below and start paints */ /* Above */ if (y > 0) { lastBorder = 1; for (i = leftLimit; (i <= rightLimit); i++) { int c; c = gdImageGetPixel (im, i, y - 1); if (lastBorder) { if ((c != border) && (c != color)) { gdImageFillToBorder (im, i, y - 1, border, color); lastBorder = 0; } } else if ((c == border) || (c == color)) { lastBorder = 1; } } } /* Below */ if (y < ((im->sy) - 1)) { lastBorder = 1; for (i = leftLimit; (i <= rightLimit); i++) { int c = gdImageGetPixel (im, i, y + 1); if (lastBorder) { if ((c != border) && (c != color)) { gdImageFillToBorder (im, i, y + 1, border, color); lastBorder = 0; } } else if ((c == border) || (c == color)) { lastBorder = 1; } } } im->alphaBlendingFlag = restoreAlphaBleding; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'fix #215 gdImageFillToBorder stack-overflow when invalid color is used'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void pdo_stmt_init(TSRMLS_D) { zend_class_entry ce; INIT_CLASS_ENTRY(ce, "PDOStatement", pdo_dbstmt_functions); pdo_dbstmt_ce = zend_register_internal_class(&ce TSRMLS_CC); pdo_dbstmt_ce->get_iterator = pdo_stmt_iter_get; pdo_dbstmt_ce->create_object = pdo_dbstmt_new; zend_class_implements(pdo_dbstmt_ce TSRMLS_CC, 1, zend_ce_traversable); zend_declare_property_null(pdo_dbstmt_ce, "queryString", sizeof("queryString")-1, ZEND_ACC_PUBLIC TSRMLS_CC); memcpy(&pdo_dbstmt_object_handlers, &std_object_handlers, sizeof(zend_object_handlers)); pdo_dbstmt_object_handlers.write_property = dbstmt_prop_write; pdo_dbstmt_object_handlers.unset_property = dbstmt_prop_delete; pdo_dbstmt_object_handlers.get_method = dbstmt_method_get; pdo_dbstmt_object_handlers.compare_objects = dbstmt_compare; pdo_dbstmt_object_handlers.clone_obj = dbstmt_clone_obj; INIT_CLASS_ENTRY(ce, "PDORow", pdo_row_functions); pdo_row_ce = zend_register_internal_class(&ce TSRMLS_CC); pdo_row_ce->ce_flags |= ZEND_ACC_FINAL_CLASS; /* when removing this a lot of handlers need to be redone */ pdo_row_ce->create_object = pdo_row_new; pdo_row_ce->serialize = pdo_row_serialize; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix bug #73331 - do not try to serialize/unserialize objects wddx can not handle Proper soltion would be to call serialize/unserialize and deal with the result, but this requires more work that should be done by wddx maintainer (not me).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: */ static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts) { st_entry ent; wddx_stack *stack = (wddx_stack *)user_data; if (!strcmp(name, EL_PACKET)) { int i; if (atts) for (i=0; atts[i]; i++) { if (!strcmp(atts[i], EL_VERSION)) { /* nothing for now */ } } } else if (!strcmp(name, EL_STRING)) { ent.type = ST_STRING; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BINARY)) { ent.type = ST_BINARY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_CHAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_CHAR_CODE) && atts[i+1] && atts[i+1][0]) { char tmp_buf[2]; snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i+1], NULL, 16)); php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf)); break; } } } else if (!strcmp(name, EL_NUMBER)) { ent.type = ST_NUMBER; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; Z_LVAL_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BOOLEAN)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) { ent.type = ST_BOOLEAN; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_BOOL; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); php_wddx_process_data(user_data, atts[i+1], strlen(atts[i+1])); break; } } } else if (!strcmp(name, EL_NULL)) { ent.type = ST_NULL; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); ZVAL_NULL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_ARRAY)) { ent.type = ST_ARRAY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_STRUCT)) { ent.type = ST_STRUCT; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_VAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { if (stack->varname) efree(stack->varname); stack->varname = estrdup(atts[i+1]); break; } } } else if (!strcmp(name, EL_RECORDSET)) { int i; ent.type = ST_RECORDSET; SET_STACK_VARNAME; MAKE_STD_ZVAL(ent.data); array_init(ent.data); if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], "fieldNames") && atts[i+1] && atts[i+1][0]) { zval *tmp; char *key; char *p1, *p2, *endp; i++; endp = (char *)atts[i] + strlen(atts[i]); p1 = (char *)atts[i]; while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) { key = estrndup(p1, p2 - p1); MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp); p1 = p2 + sizeof(",")-1; efree(key); } if (p1 <= endp) { MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp); } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_FIELD)) { int i; st_entry ent; ent.type = ST_FIELD; ent.varname = NULL; ent.data = NULL; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { st_entry *recordset; zval **field; if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS && recordset->type == ST_RECORDSET && zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i+1], strlen(atts[i+1])+1, (void**)&field) == SUCCESS) { ent.data = *field; } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_DATETIME)) { ent.type = ST_DATETIME; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-94'], 'message': 'Fix bug #73631 - Invalid read when wddx decodes empty boolean element'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(unserialize) { char *buf = NULL; size_t buf_len; const unsigned char *p; php_unserialize_data_t var_hash; zval *options = NULL, *classes = NULL; HashTable *class_hash = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|a", &buf, &buf_len, &options) == FAILURE) { RETURN_FALSE; } if (buf_len == 0) { RETURN_FALSE; } p = (const unsigned char*) buf; PHP_VAR_UNSERIALIZE_INIT(var_hash); if(options != NULL) { classes = zend_hash_str_find(Z_ARRVAL_P(options), "allowed_classes", sizeof("allowed_classes")-1); if(classes && (Z_TYPE_P(classes) == IS_ARRAY || !zend_is_true(classes))) { ALLOC_HASHTABLE(class_hash); zend_hash_init(class_hash, (Z_TYPE_P(classes) == IS_ARRAY)?zend_hash_num_elements(Z_ARRVAL_P(classes)):0, NULL, NULL, 0); } if(class_hash && Z_TYPE_P(classes) == IS_ARRAY) { zval *entry; zend_string *lcname; ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(classes), entry) { convert_to_string_ex(entry); lcname = zend_string_tolower(Z_STR_P(entry)); zend_hash_add_empty_element(class_hash, lcname); zend_string_release(lcname); } ZEND_HASH_FOREACH_END(); } } if (!php_var_unserialize_ex(return_value, &p, p + buf_len, &var_hash, class_hash)) { PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (class_hash) { zend_hash_destroy(class_hash); FREE_HASHTABLE(class_hash); } zval_ptr_dtor(return_value); if (!EG(exception)) { php_error_docref(NULL, E_NOTICE, "Error at offset " ZEND_LONG_FMT " of %zd bytes", (zend_long)((char*)p - buf), buf_len); } RETURN_FALSE; } /* We should keep an reference to return_value to prevent it from being dtor in case nesting calls to unserialize */ var_push_dtor(&var_hash, return_value); PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (class_hash) { zend_hash_destroy(class_hash); FREE_HASHTABLE(class_hash); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Complete the fix of bug #70172 for PHP 7'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int jpc_pi_nextpcrl(register jpc_pi_t *pi) { int rlvlno; jpc_pirlvl_t *pirlvl; jpc_pchg_t *pchg; int prchind; int prcvind; int *prclyrno; int compno; jpc_picomp_t *picomp; int xstep; int ystep; uint_fast32_t trx0; uint_fast32_t try0; uint_fast32_t r; uint_fast32_t rpx; uint_fast32_t rpy; pchg = pi->pchg; if (!pi->prgvolfirst) { goto skip; } else { pi->xstep = 0; pi->ystep = 0; for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { // Check for the potential for overflow problems. if (pirlvl->prcwidthexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2 || pirlvl->prcheightexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2) { return -1; } xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1)); ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1)); pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); } } pi->prgvolfirst = 0; } for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - (pi->y % pi->ystep)) { for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - (pi->x % pi->xstep)) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < pi->numcomps && pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++pi->picomp) { for (pi->rlvlno = pchg->rlvlnostart, pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) { if (pi->pirlvl->numprcs == 0) { continue; } r = pi->picomp->numrlvls - 1 - pi->rlvlno; trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); rpx = r + pi->pirlvl->prcwidthexpn; rpy = r + pi->pirlvl->prcheightexpn; if (((pi->x == pi->xstart && ((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx))) || !(pi->x % (pi->picomp->hsamp << rpx))) && ((pi->y == pi->ystart && ((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy))) || !(pi->y % (pi->picomp->vsamp << rpy)))) { prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; assert(pi->prcno < pi->pirlvl->numprcs); for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; if (pi->lyrno >= *prclyrno) { ++(*prclyrno); return 0; } skip: ; } } } } } } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Apply a patch for the following bug report: https://github.com/mdadams/jasper/issues/103 Heap-Buffer-Overflow or Null-pointer-dereference vulnerability due to a programming mistake (off-by-1)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int jpc_pi_nextcprl(register jpc_pi_t *pi) { int rlvlno; jpc_pirlvl_t *pirlvl; jpc_pchg_t *pchg; int prchind; int prcvind; int *prclyrno; uint_fast32_t trx0; uint_fast32_t try0; uint_fast32_t r; uint_fast32_t rpx; uint_fast32_t rpy; pchg = pi->pchg; if (!pi->prgvolfirst) { goto skip; } else { pi->prgvolfirst = 0; } for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno, ++pi->picomp) { pirlvl = pi->picomp->pirlvls; pi->xstep = pi->picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn + pi->picomp->numrlvls - 1)); pi->ystep = pi->picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn + pi->picomp->numrlvls - 1)); for (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1]; rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) { pi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn + pi->picomp->numrlvls - rlvlno - 1))); pi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn + pi->picomp->numrlvls - rlvlno - 1))); } for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - (pi->y % pi->ystep)) { for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - (pi->x % pi->xstep)) { for (pi->rlvlno = pchg->rlvlnostart, pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) { if (pi->pirlvl->numprcs == 0) { continue; } r = pi->picomp->numrlvls - 1 - pi->rlvlno; trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); rpx = r + pi->pirlvl->prcwidthexpn; rpy = r + pi->pirlvl->prcheightexpn; if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) || !(pi->x % (pi->picomp->hsamp << rpx))) && ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) || !(pi->y % (pi->picomp->vsamp << rpy)))) { prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; assert(pi->prcno < pi->pirlvl->numprcs); for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; if (pi->lyrno >= *prclyrno) { ++(*prclyrno); return 0; } skip: ; } } } } } } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed numerous integer overflow problems in the code for packet iterators in the JPC decoder.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int jpc_dec_decodepkts(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in) { jpc_dec_tile_t *tile; jpc_pi_t *pi; int ret; tile = dec->curtile; pi = tile->pi; for (;;) { if (!tile->pkthdrstream || jas_stream_peekc(tile->pkthdrstream) == EOF) { switch (jpc_dec_lookahead(in)) { case JPC_MS_EOC: case JPC_MS_SOT: return 0; break; case JPC_MS_SOP: case JPC_MS_EPH: case 0: break; default: return -1; break; } } if ((ret = jpc_pi_next(pi))) { return ret; } if (dec->maxpkts >= 0 && dec->numpkts >= dec->maxpkts) { jas_eprintf("warning: stopping decode prematurely as requested\n"); return 0; } if (jas_getdbglevel() >= 1) { jas_eprintf("packet offset=%08ld prg=%d cmptno=%02d " "rlvlno=%02d prcno=%03d lyrno=%02d\n", (long) jas_stream_getrwcount(in), jpc_pi_prg(pi), jpc_pi_cmptno(pi), jpc_pi_rlvlno(pi), jpc_pi_prcno(pi), jpc_pi_lyrno(pi)); } if (jpc_dec_decodepkt(dec, pkthdrstream, in, jpc_pi_cmptno(pi), jpc_pi_rlvlno(pi), jpc_pi_prcno(pi), jpc_pi_lyrno(pi))) { return -1; } ++dec->numpkts; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed numerous integer overflow problems in the code for packet iterators in the JPC decoder.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int jpc_pi_nextrpcl(register jpc_pi_t *pi) { int rlvlno; jpc_pirlvl_t *pirlvl; jpc_pchg_t *pchg; int prchind; int prcvind; int *prclyrno; int compno; jpc_picomp_t *picomp; int xstep; int ystep; uint_fast32_t r; uint_fast32_t rpx; uint_fast32_t rpy; uint_fast32_t trx0; uint_fast32_t try0; pchg = pi->pchg; if (!pi->prgvolfirst) { goto skip; } else { pi->xstep = 0; pi->ystep = 0; for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { // Check for the potential for overflow problems. if (pirlvl->prcwidthexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2 || pirlvl->prcheightexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2) { return -1; } xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1)); ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1)); pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); } } pi->prgvolfirst = 0; } for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend && pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) { for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - (pi->y % pi->ystep)) { for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - (pi->x % pi->xstep)) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno, ++pi->picomp) { if (pi->rlvlno >= pi->picomp->numrlvls) { continue; } pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; if (pi->pirlvl->numprcs == 0) { continue; } r = pi->picomp->numrlvls - 1 - pi->rlvlno; rpx = r + pi->pirlvl->prcwidthexpn; rpy = r + pi->pirlvl->prcheightexpn; trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); if (((pi->x == pi->xstart && ((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx))) || !(pi->x % (JAS_CAST(uint_fast32_t, 1) << rpx))) && ((pi->y == pi->ystart && ((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy))) || !(pi->y % (JAS_CAST(uint_fast32_t, 1) << rpy)))) { prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; assert(pi->prcno < pi->pirlvl->numprcs); for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; if (pi->lyrno >= *prclyrno) { ++(*prclyrno); return 0; } skip: ; } } } } } } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed a bug in the packet iterator code. Added a new regression test case.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: rend_decrypt_introduction_points(char **ipos_decrypted, size_t *ipos_decrypted_size, const char *descriptor_cookie, const char *ipos_encrypted, size_t ipos_encrypted_size) { tor_assert(ipos_encrypted); tor_assert(descriptor_cookie); if (ipos_encrypted_size < 2) { log_warn(LD_REND, "Size of encrypted introduction points is too " "small."); return -1; } if (ipos_encrypted[0] == (int)REND_BASIC_AUTH) { char iv[CIPHER_IV_LEN], client_id[REND_BASIC_AUTH_CLIENT_ID_LEN], session_key[CIPHER_KEY_LEN], *dec; int declen, client_blocks; size_t pos = 0, len, client_entries_len; crypto_digest_t *digest; crypto_cipher_t *cipher; client_blocks = (int) ipos_encrypted[1]; client_entries_len = client_blocks * REND_BASIC_AUTH_CLIENT_MULTIPLE * REND_BASIC_AUTH_CLIENT_ENTRY_LEN; if (ipos_encrypted_size < 2 + client_entries_len + CIPHER_IV_LEN + 1) { log_warn(LD_REND, "Size of encrypted introduction points is too " "small."); return -1; } memcpy(iv, ipos_encrypted + 2 + client_entries_len, CIPHER_IV_LEN); digest = crypto_digest_new(); crypto_digest_add_bytes(digest, descriptor_cookie, REND_DESC_COOKIE_LEN); crypto_digest_add_bytes(digest, iv, CIPHER_IV_LEN); crypto_digest_get_digest(digest, client_id, REND_BASIC_AUTH_CLIENT_ID_LEN); crypto_digest_free(digest); for (pos = 2; pos < 2 + client_entries_len; pos += REND_BASIC_AUTH_CLIENT_ENTRY_LEN) { if (tor_memeq(ipos_encrypted + pos, client_id, REND_BASIC_AUTH_CLIENT_ID_LEN)) { /* Attempt to decrypt introduction points. */ cipher = crypto_cipher_new(descriptor_cookie); if (crypto_cipher_decrypt(cipher, session_key, ipos_encrypted + pos + REND_BASIC_AUTH_CLIENT_ID_LEN, CIPHER_KEY_LEN) < 0) { log_warn(LD_REND, "Could not decrypt session key for client."); crypto_cipher_free(cipher); return -1; } crypto_cipher_free(cipher); len = ipos_encrypted_size - 2 - client_entries_len - CIPHER_IV_LEN; dec = tor_malloc(len); declen = crypto_cipher_decrypt_with_iv(session_key, dec, len, ipos_encrypted + 2 + client_entries_len, ipos_encrypted_size - 2 - client_entries_len); if (declen < 0) { log_warn(LD_REND, "Could not decrypt introduction point string."); tor_free(dec); return -1; } if (fast_memcmpstart(dec, declen, "introduction-point ")) { log_warn(LD_REND, "Decrypted introduction points don't " "look like we could parse them."); tor_free(dec); continue; } *ipos_decrypted = dec; *ipos_decrypted_size = declen; return 0; } } log_warn(LD_REND, "Could not decrypt introduction points. Please " "check your authorization for this service!"); return -1; } else if (ipos_encrypted[0] == (int)REND_STEALTH_AUTH) { char *dec; int declen; if (ipos_encrypted_size < CIPHER_IV_LEN + 2) { log_warn(LD_REND, "Size of encrypted introduction points is too " "small."); return -1; } dec = tor_malloc_zero(ipos_encrypted_size - CIPHER_IV_LEN - 1); declen = crypto_cipher_decrypt_with_iv(descriptor_cookie, dec, ipos_encrypted_size - CIPHER_IV_LEN - 1, ipos_encrypted + 1, ipos_encrypted_size - 1); if (declen < 0) { log_warn(LD_REND, "Decrypting introduction points failed!"); tor_free(dec); return -1; } *ipos_decrypted = dec; *ipos_decrypted_size = declen; return 0; } else { log_warn(LD_REND, "Unknown authorization type number: %d", ipos_encrypted[0]); return -1; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix parsing bug with unecognized token at EOS In get_token(), we could read one byte past the end of the region. This is only a big problem in the case where the region itself is (a) potentially hostile, and (b) not explicitly nul-terminated. This patch fixes the underlying bug, and also makes sure that the one remaining case of not-NUL-terminated potentially hostile data gets NUL-terminated. Fix for bug 21018, TROVE-2016-12-002, and CVE-2016-1254'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void nfnetlink_rcv_batch(struct sk_buff *skb, struct nlmsghdr *nlh, u_int16_t subsys_id) { struct sk_buff *oskb = skb; struct net *net = sock_net(skb->sk); const struct nfnetlink_subsystem *ss; const struct nfnl_callback *nc; static LIST_HEAD(err_list); u32 status; int err; if (subsys_id >= NFNL_SUBSYS_COUNT) return netlink_ack(skb, nlh, -EINVAL); replay: status = 0; skb = netlink_skb_clone(oskb, GFP_KERNEL); if (!skb) return netlink_ack(oskb, nlh, -ENOMEM); nfnl_lock(subsys_id); ss = nfnl_dereference_protected(subsys_id); if (!ss) { #ifdef CONFIG_MODULES nfnl_unlock(subsys_id); request_module("nfnetlink-subsys-%d", subsys_id); nfnl_lock(subsys_id); ss = nfnl_dereference_protected(subsys_id); if (!ss) #endif { nfnl_unlock(subsys_id); netlink_ack(oskb, nlh, -EOPNOTSUPP); return kfree_skb(skb); } } if (!ss->commit || !ss->abort) { nfnl_unlock(subsys_id); netlink_ack(oskb, nlh, -EOPNOTSUPP); return kfree_skb(skb); } while (skb->len >= nlmsg_total_size(0)) { int msglen, type; nlh = nlmsg_hdr(skb); err = 0; if (nlmsg_len(nlh) < sizeof(struct nfgenmsg) || skb->len < nlh->nlmsg_len) { err = -EINVAL; goto ack; } /* Only requests are handled by the kernel */ if (!(nlh->nlmsg_flags & NLM_F_REQUEST)) { err = -EINVAL; goto ack; } type = nlh->nlmsg_type; if (type == NFNL_MSG_BATCH_BEGIN) { /* Malformed: Batch begin twice */ nfnl_err_reset(&err_list); status |= NFNL_BATCH_FAILURE; goto done; } else if (type == NFNL_MSG_BATCH_END) { status |= NFNL_BATCH_DONE; goto done; } else if (type < NLMSG_MIN_TYPE) { err = -EINVAL; goto ack; } /* We only accept a batch with messages for the same * subsystem. */ if (NFNL_SUBSYS_ID(type) != subsys_id) { err = -EINVAL; goto ack; } nc = nfnetlink_find_client(type, ss); if (!nc) { err = -EINVAL; goto ack; } { int min_len = nlmsg_total_size(sizeof(struct nfgenmsg)); u_int8_t cb_id = NFNL_MSG_TYPE(nlh->nlmsg_type); struct nlattr *cda[ss->cb[cb_id].attr_count + 1]; struct nlattr *attr = (void *)nlh + min_len; int attrlen = nlh->nlmsg_len - min_len; err = nla_parse(cda, ss->cb[cb_id].attr_count, attr, attrlen, ss->cb[cb_id].policy); if (err < 0) goto ack; if (nc->call_batch) { err = nc->call_batch(net, net->nfnl, skb, nlh, (const struct nlattr **)cda); } /* The lock was released to autoload some module, we * have to abort and start from scratch using the * original skb. */ if (err == -EAGAIN) { status |= NFNL_BATCH_REPLAY; goto next; } } ack: if (nlh->nlmsg_flags & NLM_F_ACK || err) { /* Errors are delivered once the full batch has been * processed, this avoids that the same error is * reported several times when replaying the batch. */ if (nfnl_err_add(&err_list, nlh, err) < 0) { /* We failed to enqueue an error, reset the * list of errors and send OOM to userspace * pointing to the batch header. */ nfnl_err_reset(&err_list); netlink_ack(oskb, nlmsg_hdr(oskb), -ENOMEM); status |= NFNL_BATCH_FAILURE; goto done; } /* We don't stop processing the batch on errors, thus, * userspace gets all the errors that the batch * triggers. */ if (err) status |= NFNL_BATCH_FAILURE; } next: msglen = NLMSG_ALIGN(nlh->nlmsg_len); if (msglen > skb->len) msglen = skb->len; skb_pull(skb, msglen); } done: if (status & NFNL_BATCH_REPLAY) { ss->abort(net, oskb); nfnl_err_reset(&err_list); nfnl_unlock(subsys_id); kfree_skb(skb); goto replay; } else if (status == NFNL_BATCH_DONE) { ss->commit(net, oskb); } else { ss->abort(net, oskb); } nfnl_err_deliver(&err_list, oskb); nfnl_unlock(subsys_id); kfree_skb(skb); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-125'], 'message': 'netfilter: nfnetlink: correctly validate length of batch messages If nlh->nlmsg_len is zero then an infinite loop is triggered because 'skb_pull(skb, msglen);' pulls zero bytes. The calculation in nlmsg_len() underflows if 'nlh->nlmsg_len < NLMSG_HDRLEN' which bypasses the length validation and will later trigger an out-of-bound read. If the length validation does fail then the malformed batch message is copied back to userspace. However, we cannot do this because the nlh->nlmsg_len can be invalid. This leads to an out-of-bounds read in netlink_ack: [ 41.455421] ================================================================== [ 41.456431] BUG: KASAN: slab-out-of-bounds in memcpy+0x1d/0x40 at addr ffff880119e79340 [ 41.456431] Read of size 4294967280 by task a.out/987 [ 41.456431] ============================================================================= [ 41.456431] BUG kmalloc-512 (Not tainted): kasan: bad access detected [ 41.456431] ----------------------------------------------------------------------------- ... [ 41.456431] Bytes b4 ffff880119e79310: 00 00 00 00 d5 03 00 00 b0 fb fe ff 00 00 00 00 ................ [ 41.456431] Object ffff880119e79320: 20 00 00 00 10 00 05 00 00 00 00 00 00 00 00 00 ............... [ 41.456431] Object ffff880119e79330: 14 00 0a 00 01 03 fc 40 45 56 11 22 33 10 00 05 .......@EV."3... [ 41.456431] Object ffff880119e79340: f0 ff ff ff 88 99 aa bb 00 14 00 0a 00 06 fe fb ................ ^^ start of batch nlmsg with nlmsg_len=4294967280 ... [ 41.456431] Memory state around the buggy address: [ 41.456431] ffff880119e79400: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [ 41.456431] ffff880119e79480: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [ 41.456431] >ffff880119e79500: 00 00 00 00 fc fc fc fc fc fc fc fc fc fc fc fc [ 41.456431] ^ [ 41.456431] ffff880119e79580: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc [ 41.456431] ffff880119e79600: fc fc fc fc fc fc fc fc fc fc fb fb fb fb fb fb [ 41.456431] ================================================================== Fix this with better validation of nlh->nlmsg_len and by setting NFNL_BATCH_FAILURE if any batch message fails length validation. CAP_NET_ADMIN is required to trigger the bugs. Fixes: 9ea2aa8b7dba ("netfilter: nfnetlink: validate nfnetlink header from batch") Signed-off-by: Phil Turnbull <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static jpc_enc_prc_t *prc_create(jpc_enc_prc_t *prc, jpc_enc_cp_t *cp, jpc_enc_band_t *band) { uint_fast32_t prcno; uint_fast32_t prcxind; uint_fast32_t prcyind; uint_fast32_t cbgtlx; uint_fast32_t cbgtly; uint_fast32_t tlprctlx; uint_fast32_t tlprctly; uint_fast32_t tlcbgtlx; uint_fast32_t tlcbgtly; uint_fast16_t rlvlno; jpc_enc_rlvl_t *rlvl; uint_fast32_t tlcblktlx; uint_fast32_t tlcblktly; uint_fast32_t brcblkbrx; uint_fast32_t brcblkbry; uint_fast32_t cblkno; jpc_enc_cblk_t *cblk; jpc_enc_tcmpt_t *tcmpt; prc->cblks = 0; prc->incltree = 0; prc->savincltree = 0; prc->nlibtree = 0; prc->savnlibtree = 0; rlvl = band->rlvl; tcmpt = rlvl->tcmpt; rlvlno = rlvl - tcmpt->rlvls; prcno = prc - band->prcs; prcxind = prcno % rlvl->numhprcs; prcyind = prcno / rlvl->numhprcs; prc->band = band; tlprctlx = JPC_FLOORTOMULTPOW2(rlvl->tlx, rlvl->prcwidthexpn); tlprctly = JPC_FLOORTOMULTPOW2(rlvl->tly, rlvl->prcheightexpn); if (!rlvlno) { tlcbgtlx = tlprctlx; tlcbgtly = tlprctly; } else { tlcbgtlx = JPC_CEILDIVPOW2(tlprctlx, 1); tlcbgtly = JPC_CEILDIVPOW2(tlprctly, 1); } /* Compute the coordinates of the top-left and bottom-right corners of the precinct. */ cbgtlx = tlcbgtlx + (prcxind << rlvl->cbgwidthexpn); cbgtly = tlcbgtly + (prcyind << rlvl->cbgheightexpn); prc->tlx = JAS_MAX(jas_seq2d_xstart(band->data), cbgtlx); prc->tly = JAS_MAX(jas_seq2d_ystart(band->data), cbgtly); prc->brx = JAS_MIN(jas_seq2d_xend(band->data), cbgtlx + (1 << rlvl->cbgwidthexpn)); prc->bry = JAS_MIN(jas_seq2d_yend(band->data), cbgtly + (1 << rlvl->cbgheightexpn)); if (prc->tlx < prc->brx && prc->tly < prc->bry) { /* The precinct contains at least one code block. */ tlcblktlx = JPC_FLOORTOMULTPOW2(prc->tlx, rlvl->cblkwidthexpn); tlcblktly = JPC_FLOORTOMULTPOW2(prc->tly, rlvl->cblkheightexpn); brcblkbrx = JPC_CEILTOMULTPOW2(prc->brx, rlvl->cblkwidthexpn); brcblkbry = JPC_CEILTOMULTPOW2(prc->bry, rlvl->cblkheightexpn); prc->numhcblks = JPC_FLOORDIVPOW2(brcblkbrx - tlcblktlx, rlvl->cblkwidthexpn); prc->numvcblks = JPC_FLOORDIVPOW2(brcblkbry - tlcblktly, rlvl->cblkheightexpn); prc->numcblks = prc->numhcblks * prc->numvcblks; if (!(prc->incltree = jpc_tagtree_create(prc->numhcblks, prc->numvcblks))) { goto error; } if (!(prc->nlibtree = jpc_tagtree_create(prc->numhcblks, prc->numvcblks))) { goto error; } if (!(prc->savincltree = jpc_tagtree_create(prc->numhcblks, prc->numvcblks))) { goto error; } if (!(prc->savnlibtree = jpc_tagtree_create(prc->numhcblks, prc->numvcblks))) { goto error; } if (!(prc->cblks = jas_alloc2(prc->numcblks, sizeof(jpc_enc_cblk_t)))) { goto error; } for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks; ++cblkno, ++cblk) { cblk->passes = 0; cblk->stream = 0; cblk->mqenc = 0; cblk->data = 0; cblk->flags = 0; cblk->prc = prc; } for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks; ++cblkno, ++cblk) { if (!cblk_create(cblk, cp, prc)) { goto error; } } } else { /* The precinct does not contain any code blocks. */ prc->tlx = prc->brx; prc->tly = prc->bry; prc->numcblks = 0; prc->numhcblks = 0; prc->numvcblks = 0; prc->cblks = 0; prc->incltree = 0; prc->nlibtree = 0; prc->savincltree = 0; prc->savnlibtree = 0; } return prc; error: prc_destroy(prc); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed some potential double-free problems in the JPC codec.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void band_destroy(jpc_enc_band_t *band) { jpc_enc_prc_t *prc; jpc_enc_rlvl_t *rlvl; uint_fast32_t prcno; if (band->prcs) { rlvl = band->rlvl; for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; ++prcno, ++prc) { prc_destroy(prc); } jas_free(band->prcs); } if (band->data) { jas_seq2d_destroy(band->data); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed some potential double-free problems in the JPC codec.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void jpc_enc_tile_destroy(jpc_enc_tile_t *tile) { jpc_enc_tcmpt_t *tcmpt; uint_fast16_t cmptno; if (tile->tcmpts) { for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < tile->numtcmpts; ++cmptno, ++tcmpt) { tcmpt_destroy(tcmpt); } jas_free(tile->tcmpts); } if (tile->lyrsizes) { jas_free(tile->lyrsizes); } if (tile->pi) { jpc_pi_destroy(tile->pi); } jas_free(tile); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed some potential double-free problems in the JPC codec.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int jpc_enc_encodemainbody(jpc_enc_t *enc) { int tileno; int tilex; int tiley; int i; jpc_sot_t *sot; jpc_enc_tcmpt_t *comp; jpc_enc_tcmpt_t *endcomps; jpc_enc_band_t *band; jpc_enc_band_t *endbands; jpc_enc_rlvl_t *lvl; int rlvlno; jpc_qcc_t *qcc; jpc_cod_t *cod; int adjust; int j; int absbandno; long numbytes; long tilehdrlen; long tilelen; jpc_enc_tile_t *tile; jpc_enc_cp_t *cp; double rho; int lyrno; int cmptno; int samestepsizes; jpc_enc_ccp_t *ccps; jpc_enc_tccp_t *tccp; int bandno; uint_fast32_t x; uint_fast32_t y; int mingbits; int actualnumbps; jpc_fix_t mxmag; jpc_fix_t mag; int numgbits; cp = enc->cp; /* Avoid compile warnings. */ numbytes = 0; for (tileno = 0; tileno < JAS_CAST(int, cp->numtiles); ++tileno) { tilex = tileno % cp->numhtiles; tiley = tileno / cp->numhtiles; if (!(enc->curtile = jpc_enc_tile_create(enc->cp, enc->image, tileno))) { abort(); } tile = enc->curtile; if (jas_getdbglevel() >= 10) { jpc_enc_dump(enc); } endcomps = &tile->tcmpts[tile->numtcmpts]; for (cmptno = 0, comp = tile->tcmpts; cmptno < tile->numtcmpts; ++cmptno, ++comp) { if (!cp->ccps[cmptno].sgnd) { adjust = 1 << (cp->ccps[cmptno].prec - 1); for (i = 0; i < jas_matrix_numrows(comp->data); ++i) { for (j = 0; j < jas_matrix_numcols(comp->data); ++j) { *jas_matrix_getref(comp->data, i, j) -= adjust; } } } } if (!tile->intmode) { endcomps = &tile->tcmpts[tile->numtcmpts]; for (comp = tile->tcmpts; comp != endcomps; ++comp) { jas_matrix_asl(comp->data, JPC_FIX_FRACBITS); } } switch (tile->mctid) { case JPC_MCT_RCT: assert(jas_image_numcmpts(enc->image) == 3); jpc_rct(tile->tcmpts[0].data, tile->tcmpts[1].data, tile->tcmpts[2].data); break; case JPC_MCT_ICT: assert(jas_image_numcmpts(enc->image) == 3); jpc_ict(tile->tcmpts[0].data, tile->tcmpts[1].data, tile->tcmpts[2].data); break; default: break; } for (i = 0; i < jas_image_numcmpts(enc->image); ++i) { comp = &tile->tcmpts[i]; jpc_tsfb_analyze(comp->tsfb, comp->data); } endcomps = &tile->tcmpts[tile->numtcmpts]; for (cmptno = 0, comp = tile->tcmpts; comp != endcomps; ++cmptno, ++comp) { mingbits = 0; absbandno = 0; /* All bands must have a corresponding quantizer step size, even if they contain no samples and are never coded. */ /* Some bands may not be hit by the loop below, so we must initialize all of the step sizes to a sane value. */ memset(comp->stepsizes, 0, sizeof(comp->stepsizes)); for (rlvlno = 0, lvl = comp->rlvls; rlvlno < comp->numrlvls; ++rlvlno, ++lvl) { if (!lvl->bands) { absbandno += rlvlno ? 3 : 1; continue; } endbands = &lvl->bands[lvl->numbands]; for (band = lvl->bands; band != endbands; ++band) { if (!band->data) { ++absbandno; continue; } actualnumbps = 0; mxmag = 0; for (y = 0; y < JAS_CAST(uint_fast32_t, jas_matrix_numrows(band->data)); ++y) { for (x = 0; x < JAS_CAST(uint_fast32_t, jas_matrix_numcols(band->data)); ++x) { mag = JAS_ABS(jas_matrix_get(band->data, y, x)); if (mag > mxmag) { mxmag = mag; } } } if (tile->intmode) { actualnumbps = jpc_firstone(mxmag) + 1; } else { actualnumbps = jpc_firstone(mxmag) + 1 - JPC_FIX_FRACBITS; } numgbits = actualnumbps - (cp->ccps[cmptno].prec - 1 + band->analgain); #if 0 jas_eprintf("%d %d mag=%d actual=%d numgbits=%d\n", cp->ccps[cmptno].prec, band->analgain, mxmag, actualnumbps, numgbits); #endif if (numgbits > mingbits) { mingbits = numgbits; } if (!tile->intmode) { band->absstepsize = jpc_fix_div(jpc_inttofix(1 << (band->analgain + 1)), band->synweight); } else { band->absstepsize = jpc_inttofix(1); } band->stepsize = jpc_abstorelstepsize( band->absstepsize, cp->ccps[cmptno].prec + band->analgain); band->numbps = cp->tccp.numgbits + JPC_QCX_GETEXPN(band->stepsize) - 1; if ((!tile->intmode) && band->data) { jpc_quantize(band->data, band->absstepsize); } comp->stepsizes[absbandno] = band->stepsize; ++absbandno; } } assert(JPC_FIX_FRACBITS >= JPC_NUMEXTRABITS); if (!tile->intmode) { jas_matrix_divpow2(comp->data, JPC_FIX_FRACBITS - JPC_NUMEXTRABITS); } else { jas_matrix_asl(comp->data, JPC_NUMEXTRABITS); } #if 0 jas_eprintf("mingbits %d\n", mingbits); #endif if (mingbits > cp->tccp.numgbits) { jas_eprintf("error: too few guard bits (need at least %d)\n", mingbits); return -1; } } if (!(enc->tmpstream = jas_stream_memopen(0, 0))) { jas_eprintf("cannot open tmp file\n"); return -1; } /* Write the tile header. */ if (!(enc->mrk = jpc_ms_create(JPC_MS_SOT))) { return -1; } sot = &enc->mrk->parms.sot; sot->len = 0; sot->tileno = tileno; sot->partno = 0; sot->numparts = 1; if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) { jas_eprintf("cannot write SOT marker\n"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; /************************************************************************/ /************************************************************************/ /************************************************************************/ tccp = &cp->tccp; for (cmptno = 0; cmptno < JAS_CAST(int, cp->numcmpts); ++cmptno) { comp = &tile->tcmpts[cmptno]; if (comp->numrlvls != tccp->maxrlvls) { if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) { return -1; } /* XXX = this is not really correct. we are using comp #0's precint sizes and other characteristics */ comp = &tile->tcmpts[0]; cod = &enc->mrk->parms.cod; cod->compparms.csty = 0; cod->compparms.numdlvls = comp->numrlvls - 1; cod->prg = tile->prg; cod->numlyrs = tile->numlyrs; cod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(comp->cblkwidthexpn); cod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(comp->cblkheightexpn); cod->compparms.cblksty = comp->cblksty; cod->compparms.qmfbid = comp->qmfbid; cod->mctrans = (tile->mctid != JPC_MCT_NONE); for (i = 0; i < comp->numrlvls; ++i) { cod->compparms.rlvls[i].parwidthval = comp->rlvls[i].prcwidthexpn; cod->compparms.rlvls[i].parheightval = comp->rlvls[i].prcheightexpn; } if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) { return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; } } for (cmptno = 0, comp = tile->tcmpts; cmptno < JAS_CAST(int, cp->numcmpts); ++cmptno, ++comp) { ccps = &cp->ccps[cmptno]; if (JAS_CAST(int, ccps->numstepsizes) == comp->numstepsizes) { samestepsizes = 1; for (bandno = 0; bandno < JAS_CAST(int, ccps->numstepsizes); ++bandno) { if (ccps->stepsizes[bandno] != comp->stepsizes[bandno]) { samestepsizes = 0; break; } } } else { samestepsizes = 0; } if (!samestepsizes) { if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) { return -1; } qcc = &enc->mrk->parms.qcc; qcc->compno = cmptno; qcc->compparms.numguard = cp->tccp.numgbits; qcc->compparms.qntsty = (comp->qmfbid == JPC_COX_INS) ? JPC_QCX_SEQNT : JPC_QCX_NOQNT; qcc->compparms.numstepsizes = comp->numstepsizes; qcc->compparms.stepsizes = comp->stepsizes; if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) { return -1; } qcc->compparms.stepsizes = 0; jpc_ms_destroy(enc->mrk); enc->mrk = 0; } } /* Write a SOD marker to indicate the end of the tile header. */ if (!(enc->mrk = jpc_ms_create(JPC_MS_SOD))) { return -1; } if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) { jas_eprintf("cannot write SOD marker\n"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; tilehdrlen = jas_stream_getrwcount(enc->tmpstream); assert(tilehdrlen >= 0); /************************************************************************/ /************************************************************************/ /************************************************************************/ if (jpc_enc_enccblks(enc)) { abort(); return -1; } cp = enc->cp; rho = (double) (tile->brx - tile->tlx) * (tile->bry - tile->tly) / ((cp->refgrdwidth - cp->imgareatlx) * (cp->refgrdheight - cp->imgareatly)); tile->rawsize = cp->rawsize * rho; for (lyrno = 0; lyrno < tile->numlyrs - 1; ++lyrno) { tile->lyrsizes[lyrno] = tile->rawsize * jpc_fixtodbl( cp->tcp.ilyrrates[lyrno]); } #if !defined(__clang__) // WARNING: // Some versions of Clang (e.g., 3.7.1 and 3.8.1) appear to generate // incorrect code for the following line. tile->lyrsizes[tile->numlyrs - 1] = (cp->totalsize != UINT_FAST32_MAX) ? (rho * enc->mainbodysize) : UINT_FAST32_MAX; #else if (cp->totalsize != UINT_FAST32_MAX) { tile->lyrsizes[tile->numlyrs - 1] = (rho * enc->mainbodysize); } else { tile->lyrsizes[tile->numlyrs - 1] = UINT_FAST32_MAX; } #endif //jas_eprintf("TESTING %ld %ld\n", cp->totalsize != UINT_FAST32_MAX, tile->lyrsizes[0]); for (lyrno = 0; lyrno < tile->numlyrs; ++lyrno) { if (tile->lyrsizes[lyrno] != UINT_FAST32_MAX) { if (JAS_CAST(uint_fast32_t, tilehdrlen) <= tile->lyrsizes[lyrno]) { tile->lyrsizes[lyrno] -= tilehdrlen; } else { tile->lyrsizes[lyrno] = 0; } } } if (rateallocate(enc, tile->numlyrs, tile->lyrsizes)) { return -1; } #if 0 jas_eprintf("ENCODE TILE DATA\n"); #endif if (jpc_enc_encodetiledata(enc)) { jas_eprintf("dotile failed\n"); return -1; } /************************************************************************/ /************************************************************************/ /************************************************************************/ /************************************************************************/ /************************************************************************/ /************************************************************************/ tilelen = jas_stream_tell(enc->tmpstream); if (jas_stream_seek(enc->tmpstream, 6, SEEK_SET) < 0) { return -1; } jpc_putuint32(enc->tmpstream, tilelen); if (jas_stream_seek(enc->tmpstream, 0, SEEK_SET) < 0) { return -1; } if (jpc_putdata(enc->out, enc->tmpstream, -1)) { return -1; } enc->len += tilelen; jas_stream_close(enc->tmpstream); enc->tmpstream = 0; jpc_enc_tile_destroy(enc->curtile); enc->curtile = 0; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed some potential double-free problems in the JPC codec.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void prc_destroy(jpc_enc_prc_t *prc) { jpc_enc_cblk_t *cblk; uint_fast32_t cblkno; if (prc->cblks) { for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks; ++cblkno, ++cblk) { cblk_destroy(cblk); } jas_free(prc->cblks); } if (prc->incltree) { jpc_tagtree_destroy(prc->incltree); } if (prc->nlibtree) { jpc_tagtree_destroy(prc->nlibtree); } if (prc->savincltree) { jpc_tagtree_destroy(prc->savincltree); } if (prc->savnlibtree) { jpc_tagtree_destroy(prc->savnlibtree); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed some potential double-free problems in the JPC codec.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: png_free_data(png_const_structrp png_ptr, png_inforp info_ptr, png_uint_32 mask, int num) { png_debug(1, "in png_free_data"); if (png_ptr == NULL || info_ptr == NULL) return; #ifdef PNG_TEXT_SUPPORTED /* Free text item num or (if num == -1) all text items */ if (info_ptr->text != NULL && ((mask & PNG_FREE_TEXT) & info_ptr->free_me) != 0) { if (num != -1) { png_free(png_ptr, info_ptr->text[num].key); info_ptr->text[num].key = NULL; } else { int i; for (i = 0; i < info_ptr->num_text; i++) png_free(png_ptr, info_ptr->text[i].key); png_free(png_ptr, info_ptr->text); info_ptr->text = NULL; info_ptr->num_text = 0; } } #endif #ifdef PNG_tRNS_SUPPORTED /* Free any tRNS entry */ if (((mask & PNG_FREE_TRNS) & info_ptr->free_me) != 0) { info_ptr->valid &= ~PNG_INFO_tRNS; png_free(png_ptr, info_ptr->trans_alpha); info_ptr->trans_alpha = NULL; info_ptr->num_trans = 0; } #endif #ifdef PNG_sCAL_SUPPORTED /* Free any sCAL entry */ if (((mask & PNG_FREE_SCAL) & info_ptr->free_me) != 0) { png_free(png_ptr, info_ptr->scal_s_width); png_free(png_ptr, info_ptr->scal_s_height); info_ptr->scal_s_width = NULL; info_ptr->scal_s_height = NULL; info_ptr->valid &= ~PNG_INFO_sCAL; } #endif #ifdef PNG_pCAL_SUPPORTED /* Free any pCAL entry */ if (((mask & PNG_FREE_PCAL) & info_ptr->free_me) != 0) { png_free(png_ptr, info_ptr->pcal_purpose); png_free(png_ptr, info_ptr->pcal_units); info_ptr->pcal_purpose = NULL; info_ptr->pcal_units = NULL; if (info_ptr->pcal_params != NULL) { int i; for (i = 0; i < info_ptr->pcal_nparams; i++) png_free(png_ptr, info_ptr->pcal_params[i]); png_free(png_ptr, info_ptr->pcal_params); info_ptr->pcal_params = NULL; } info_ptr->valid &= ~PNG_INFO_pCAL; } #endif #ifdef PNG_iCCP_SUPPORTED /* Free any profile entry */ if (((mask & PNG_FREE_ICCP) & info_ptr->free_me) != 0) { png_free(png_ptr, info_ptr->iccp_name); png_free(png_ptr, info_ptr->iccp_profile); info_ptr->iccp_name = NULL; info_ptr->iccp_profile = NULL; info_ptr->valid &= ~PNG_INFO_iCCP; } #endif #ifdef PNG_sPLT_SUPPORTED /* Free a given sPLT entry, or (if num == -1) all sPLT entries */ if (info_ptr->splt_palettes != NULL && ((mask & PNG_FREE_SPLT) & info_ptr->free_me) != 0) { if (num != -1) { png_free(png_ptr, info_ptr->splt_palettes[num].name); png_free(png_ptr, info_ptr->splt_palettes[num].entries); info_ptr->splt_palettes[num].name = NULL; info_ptr->splt_palettes[num].entries = NULL; } else { int i; for (i = 0; i < info_ptr->splt_palettes_num; i++) { png_free(png_ptr, info_ptr->splt_palettes[i].name); png_free(png_ptr, info_ptr->splt_palettes[i].entries); } png_free(png_ptr, info_ptr->splt_palettes); info_ptr->splt_palettes = NULL; info_ptr->splt_palettes_num = 0; info_ptr->valid &= ~PNG_INFO_sPLT; } } #endif #ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED if (info_ptr->unknown_chunks != NULL && ((mask & PNG_FREE_UNKN) & info_ptr->free_me) != 0) { if (num != -1) { png_free(png_ptr, info_ptr->unknown_chunks[num].data); info_ptr->unknown_chunks[num].data = NULL; } else { int i; for (i = 0; i < info_ptr->unknown_chunks_num; i++) png_free(png_ptr, info_ptr->unknown_chunks[i].data); png_free(png_ptr, info_ptr->unknown_chunks); info_ptr->unknown_chunks = NULL; info_ptr->unknown_chunks_num = 0; } } #endif #ifdef PNG_hIST_SUPPORTED /* Free any hIST entry */ if (((mask & PNG_FREE_HIST) & info_ptr->free_me) != 0) { png_free(png_ptr, info_ptr->hist); info_ptr->hist = NULL; info_ptr->valid &= ~PNG_INFO_hIST; } #endif /* Free any PLTE entry that was internally allocated */ if (((mask & PNG_FREE_PLTE) & info_ptr->free_me) != 0) { png_free(png_ptr, info_ptr->palette); info_ptr->palette = NULL; info_ptr->valid &= ~PNG_INFO_PLTE; info_ptr->num_palette = 0; } #ifdef PNG_INFO_IMAGE_SUPPORTED /* Free any image bits attached to the info structure */ if (((mask & PNG_FREE_ROWS) & info_ptr->free_me) != 0) { if (info_ptr->row_pointers != NULL) { png_uint_32 row; for (row = 0; row < info_ptr->height; row++) png_free(png_ptr, info_ptr->row_pointers[row]); png_free(png_ptr, info_ptr->row_pointers); info_ptr->row_pointers = NULL; } info_ptr->valid &= ~PNG_INFO_IDAT; } #endif if (num != -1) mask &= ~PNG_FREE_MUL; info_ptr->free_me &= ~mask; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': '[libpng16] Fixed a potential null pointer dereference in png_set_text_2() (bug report and patch by Patrick Keshishian).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void FillRectangle(rfbClient* client, int x, int y, int w, int h, uint32_t colour) { int i,j; if (client->frameBuffer == NULL) { return; } #define FILL_RECT(BPP) \ for(j=y*client->width;j<(y+h)*client->width;j+=client->width) \ for(i=x;i<x+w;i++) \ ((uint##BPP##_t*)client->frameBuffer)[j+i]=colour; switch(client->format.bitsPerPixel) { case 8: FILL_RECT(8); break; case 16: FILL_RECT(16); break; case 32: FILL_RECT(32); break; default: rfbClientLog("Unsupported bitsPerPixel: %d\n",client->format.bitsPerPixel); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix heap overflows in the various rectangle fill functions Altough rfbproto.c does check whether the overall FramebufferUpdate rectangle is too large, some of the individual encoding decoders do not, which allows a malicious server to overwrite parts of the heap.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void CopyRectangleFromRectangle(rfbClient* client, int src_x, int src_y, int w, int h, int dest_x, int dest_y) { int i,j; if (client->frameBuffer == NULL) { return; } #define COPY_RECT_FROM_RECT(BPP) \ { \ uint##BPP##_t* _buffer=((uint##BPP##_t*)client->frameBuffer)+(src_y-dest_y)*client->width+src_x-dest_x; \ if (dest_y < src_y) { \ for(j = dest_y*client->width; j < (dest_y+h)*client->width; j += client->width) { \ if (dest_x < src_x) { \ for(i = dest_x; i < dest_x+w; i++) { \ ((uint##BPP##_t*)client->frameBuffer)[j+i]=_buffer[j+i]; \ } \ } else { \ for(i = dest_x+w-1; i >= dest_x; i--) { \ ((uint##BPP##_t*)client->frameBuffer)[j+i]=_buffer[j+i]; \ } \ } \ } \ } else { \ for(j = (dest_y+h-1)*client->width; j >= dest_y*client->width; j-=client->width) { \ if (dest_x < src_x) { \ for(i = dest_x; i < dest_x+w; i++) { \ ((uint##BPP##_t*)client->frameBuffer)[j+i]=_buffer[j+i]; \ } \ } else { \ for(i = dest_x+w-1; i >= dest_x; i--) { \ ((uint##BPP##_t*)client->frameBuffer)[j+i]=_buffer[j+i]; \ } \ } \ } \ } \ } switch(client->format.bitsPerPixel) { case 8: COPY_RECT_FROM_RECT(8); break; case 16: COPY_RECT_FROM_RECT(16); break; case 32: COPY_RECT_FROM_RECT(32); break; default: rfbClientLog("Unsupported bitsPerPixel: %d\n",client->format.bitsPerPixel); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix heap overflows in the various rectangle fill functions Altough rfbproto.c does check whether the overall FramebufferUpdate rectangle is too large, some of the individual encoding decoders do not, which allows a malicious server to overwrite parts of the heap.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: HandleUltraBPP (rfbClient* client, int rx, int ry, int rw, int rh) { rfbZlibHeader hdr; int toRead=0; int inflateResult=0; lzo_uint uncompressedBytes = (( rw * rh ) * ( BPP / 8 )); if (!ReadFromRFBServer(client, (char *)&hdr, sz_rfbZlibHeader)) return FALSE; toRead = rfbClientSwap32IfLE(hdr.nBytes); if (toRead==0) return TRUE; if (uncompressedBytes==0) { rfbClientLog("ultra error: rectangle has 0 uncomressed bytes ((%dw * %dh) * (%d / 8))\n", rw, rh, BPP); return FALSE; } /* First make sure we have a large enough raw buffer to hold the * decompressed data. In practice, with a fixed BPP, fixed frame * buffer size and the first update containing the entire frame * buffer, this buffer allocation should only happen once, on the * first update. */ if ( client->raw_buffer_size < (int)uncompressedBytes) { if ( client->raw_buffer != NULL ) { free( client->raw_buffer ); } client->raw_buffer_size = uncompressedBytes; /* buffer needs to be aligned on 4-byte boundaries */ if ((client->raw_buffer_size % 4)!=0) client->raw_buffer_size += (4-(client->raw_buffer_size % 4)); client->raw_buffer = (char*) malloc( client->raw_buffer_size ); } /* allocate enough space to store the incoming compressed packet */ if ( client->ultra_buffer_size < toRead ) { if ( client->ultra_buffer != NULL ) { free( client->ultra_buffer ); } client->ultra_buffer_size = toRead; /* buffer needs to be aligned on 4-byte boundaries */ if ((client->ultra_buffer_size % 4)!=0) client->ultra_buffer_size += (4-(client->ultra_buffer_size % 4)); client->ultra_buffer = (char*) malloc( client->ultra_buffer_size ); } /* Fill the buffer, obtaining data from the server. */ if (!ReadFromRFBServer(client, client->ultra_buffer, toRead)) return FALSE; /* uncompress the data */ uncompressedBytes = client->raw_buffer_size; inflateResult = lzo1x_decompress( (lzo_byte *)client->ultra_buffer, toRead, (lzo_byte *)client->raw_buffer, (lzo_uintp) &uncompressedBytes, NULL); if ((rw * rh * (BPP / 8)) != uncompressedBytes) rfbClientLog("Ultra decompressed too little (%d < %d)", (rw * rh * (BPP / 8)), uncompressedBytes); /* Put the uncompressed contents of the update on the screen. */ if ( inflateResult == LZO_E_OK ) { CopyRectangle(client, (unsigned char *)client->raw_buffer, rx, ry, rw, rh); } else { rfbClientLog("ultra decompress returned error: %d\n", inflateResult); return FALSE; } return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix heap overflow in the ultra.c decoder The Ultra type tile decoder does not use the _safe variant of the LZO decompress function, which allows a maliciuous server to overwrite parts of the heap by sending a larger-than-specified LZO data stream.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static MagickBooleanType ConcatenateImages(int argc,char **argv, ExceptionInfo *exception ) { FILE *input, *output; int c; register ssize_t i; if (ExpandFilenames(&argc,&argv) == MagickFalse) ThrowFileException(exception,ResourceLimitError,"MemoryAllocationFailed", GetExceptionMessage(errno)); output=fopen_utf8(argv[argc-1],"wb"); if (output == (FILE *) NULL) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile",argv[argc-1]); return(MagickFalse); } for (i=2; i < (ssize_t) (argc-1); i++) { #if 0 fprintf(stderr, "DEBUG: Concatenate Image: \"%s\"\n", argv[i]); #endif input=fopen_utf8(argv[i],"rb"); if (input == (FILE *) NULL) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile",argv[i]); continue; } for (c=fgetc(input); c != EOF; c=fgetc(input)) (void) fputc((char) c,output); (void) fclose(input); (void) remove_utf8(argv[i]); } (void) fclose(output); return(MagickTrue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-703', 'CWE-252'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/196'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void ImportGrayQuantum(const Image *image,QuantumInfo *quantum_info, const MagickSizeType number_pixels,const unsigned char *magick_restrict p, Quantum *magick_restrict q,ExceptionInfo *exception) { QuantumAny range; register ssize_t x; ssize_t bit; unsigned int pixel; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); switch (quantum_info->depth) { case 1: { register Quantum black, white; black=0; white=QuantumRange; if (quantum_info->min_is_white != MagickFalse) { black=QuantumRange; white=0; } for (x=0; x < ((ssize_t) number_pixels-7); x+=8) { for (bit=0; bit < 8; bit++) { SetPixelGray(image,((*p) & (1 << (7-bit))) == 0 ? black : white,q); q+=GetPixelChannels(image); } p++; } for (bit=0; bit < (ssize_t) (number_pixels % 8); bit++) { SetPixelGray(image,((*p) & (0x01 << (7-bit))) == 0 ? black : white,q); q+=GetPixelChannels(image); } if (bit != 0) p++; break; } case 4: { register unsigned char pixel; range=GetQuantumRange(quantum_info->depth); for (x=0; x < ((ssize_t) number_pixels-1); x+=2) { pixel=(unsigned char) ((*p >> 4) & 0xf); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); pixel=(unsigned char) ((*p) & 0xf); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); p++; q+=GetPixelChannels(image); } for (bit=0; bit < (ssize_t) (number_pixels % 2); bit++) { pixel=(unsigned char) (*p++ >> 4); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); } break; } case 8: { unsigned char pixel; if (quantum_info->min_is_white != MagickFalse) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleCharToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleCharToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 10: { range=GetQuantumRange(quantum_info->depth); if (quantum_info->pack == MagickFalse) { if (image->endian == LSBEndian) { for (x=0; x < (ssize_t) (number_pixels-2); x+=3) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum((pixel >> 22) & 0x3ff, range),q); q+=GetPixelChannels(image); SetPixelGray(image,ScaleAnyToQuantum((pixel >> 12) & 0x3ff, range),q); q+=GetPixelChannels(image); SetPixelGray(image,ScaleAnyToQuantum((pixel >> 2) & 0x3ff, range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } p=PushLongPixel(quantum_info->endian,p,&pixel); if (x++ < (ssize_t) (number_pixels-1)) { SetPixelGray(image,ScaleAnyToQuantum((pixel >> 22) & 0x3ff, range),q); q+=GetPixelChannels(image); } if (x++ < (ssize_t) number_pixels) { SetPixelGray(image,ScaleAnyToQuantum((pixel >> 12) & 0x3ff, range),q); q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) (number_pixels-2); x+=3) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum((pixel >> 2) & 0x3ff,range), q); q+=GetPixelChannels(image); SetPixelGray(image,ScaleAnyToQuantum((pixel >> 12) & 0x3ff,range), q); q+=GetPixelChannels(image); SetPixelGray(image,ScaleAnyToQuantum((pixel >> 22) & 0x3ff,range), q); p+=quantum_info->pad; q+=GetPixelChannels(image); } p=PushLongPixel(quantum_info->endian,p,&pixel); if (x++ < (ssize_t) (number_pixels-1)) { SetPixelGray(image,ScaleAnyToQuantum((pixel >> 2) & 0x3ff, range),q); q+=GetPixelChannels(image); } if (x++ < (ssize_t) number_pixels) { SetPixelGray(image,ScaleAnyToQuantum((pixel >> 12) & 0x3ff, range),q); q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 12: { range=GetQuantumRange(quantum_info->depth); if (quantum_info->pack == MagickFalse) { unsigned short pixel; for (x=0; x < (ssize_t) (number_pixels-1); x+=2) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); q+=GetPixelChannels(image); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } for (bit=0; bit < (ssize_t) (number_pixels % 2); bit++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } if (bit != 0) p++; break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; if (quantum_info->min_is_white != MagickFalse) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; if (quantum_info->format == FloatingPointQuantumFormat) { float pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushFloatPixel(quantum_info,p,&pixel); SetPixelGray(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleLongToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 64: { if (quantum_info->format == FloatingPointQuantumFormat) { double pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushDoublePixel(quantum_info,p,&pixel); SetPixelGray(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } default: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/129'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int format_expand_styles(GString *out, const char **format, int *flags) { int retval = 1; char *p, fmt; /* storage for numerical parsing code for %x/X formats. */ int tmp; unsigned int tmp2; fmt = **format; switch (fmt) { case '{': case '}': case '%': /* escaped char */ g_string_append_c(out, fmt); break; case 'U': /* Underline on/off */ g_string_append_c(out, 4); g_string_append_c(out, FORMAT_STYLE_UNDERLINE); break; case '9': case '_': /* bold on/off */ g_string_append_c(out, 4); g_string_append_c(out, FORMAT_STYLE_BOLD); break; case '8': /* reverse */ g_string_append_c(out, 4); g_string_append_c(out, FORMAT_STYLE_REVERSE); break; case 'I': /* italic */ g_string_append_c(out, 4); g_string_append_c(out, FORMAT_STYLE_ITALIC); break; case ':': /* Newline */ g_string_append_c(out, '\n'); break; case '|': /* Indent here */ g_string_append_c(out, 4); g_string_append_c(out, FORMAT_STYLE_INDENT); break; case 'F': /* blink */ g_string_append_c(out, 4); g_string_append_c(out, FORMAT_STYLE_BLINK); break; case 'n': case 'N': /* default color */ g_string_append_c(out, 4); g_string_append_c(out, FORMAT_STYLE_DEFAULTS); break; case '>': /* clear to end of line */ g_string_append_c(out, 4); g_string_append_c(out, FORMAT_STYLE_CLRTOEOL); break; case '#': g_string_append_c(out, 4); g_string_append_c(out, FORMAT_STYLE_MONOSPACE); break; case '[': /* code */ format_expand_code(format, out, flags); break; case 'x': case 'X': if ((*format)[1] < '0' || (*format)[1] > '7') break; tmp = 16 + ((*format)[1]-'0'-1)*36; if (tmp > 231) { if (!isalpha((*format)[2])) break; tmp += (*format)[2] >= 'a' ? (*format)[2] - 'a' : (*format)[2] - 'A'; if (tmp > 255) break; } else if (tmp > 0) { if (!isalnum((*format)[2])) break; if ((*format)[2] >= 'a') tmp += 10 + (*format)[2] - 'a'; else if ((*format)[2] >= 'A') tmp += 10 + (*format)[2] - 'A'; else tmp += (*format)[2] - '0'; } else { if (!isxdigit((*format)[2])) break; tmp = g_ascii_xdigit_value((*format)[2]); } retval += 2; format_ext_color(out, fmt == 'x', tmp); break; case 'z': case 'Z': tmp2 = 0; for (tmp = 1; tmp < 7; ++tmp) { if (!isxdigit((*format)[tmp])) { tmp2 = UINT_MAX; break; } tmp2 <<= 4; tmp2 |= g_ascii_xdigit_value((*format)[tmp]); } if (tmp2 == UINT_MAX) break; retval += 6; format_24bit_color(out, fmt == 'z', tmp2); break; default: /* check if it's a background color */ p = strchr(format_backs, fmt); if (p != NULL) { g_string_append_c(out, 4); g_string_append_c(out, FORMAT_COLOR_NOCHANGE); g_string_append_c(out, (char) ((int) (p-format_backs)+'0')); break; } /* check if it's a foreground color */ if (fmt == 'p') fmt = 'm'; p = strchr(format_fores, fmt); if (p != NULL) { g_string_append_c(out, 4); g_string_append_c(out, (char) ((int) (p-format_fores)+'0')); g_string_append_c(out, FORMAT_COLOR_NOCHANGE); break; } /* check if it's a bold foreground color */ if (fmt == 'P') fmt = 'M'; p = strchr(format_boldfores, fmt); if (p != NULL) { g_string_append_c(out, 4); g_string_append_c(out, (char) (8+(int) (p-format_boldfores)+'0')); g_string_append_c(out, FORMAT_COLOR_NOCHANGE); break; } return FALSE; } return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Merge branch 'security' into 'master' See merge request !7'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static const char *get_ansi_color(THEME_REC *theme, const char *str, int *fg_ret, int *bg_ret, int *flags_ret) { static char ansitab[8] = { 0, 4, 2, 6, 1, 5, 3, 7 }; const char *start; int fg, bg, flags, num, i; unsigned int num2; if (*str != '[') return str; start = str++; fg = fg_ret == NULL || *fg_ret < 0 ? theme->default_color : *fg_ret; bg = bg_ret == NULL || *bg_ret < 0 ? -1 : *bg_ret; flags = flags_ret == NULL ? 0 : *flags_ret; num = 0; for (;; str++) { if (*str == '\0') return start; if (i_isdigit(*str)) { num = num*10 + (*str-'0'); continue; } if (*str != ';' && *str != 'm') return start; switch (num) { case 0: /* reset colors and attributes back to default */ fg = theme->default_color; bg = -1; flags &= ~(GUI_PRINT_FLAG_INDENT | GUI_PRINT_FLAG_BOLD | GUI_PRINT_FLAG_ITALIC | GUI_PRINT_FLAG_UNDERLINE | GUI_PRINT_FLAG_BLINK | GUI_PRINT_FLAG_REVERSE | GUI_PRINT_FLAG_COLOR_24_FG | GUI_PRINT_FLAG_COLOR_24_BG); break; case 1: /* hilight */ flags |= GUI_PRINT_FLAG_BOLD; break; case 22: /* normal */ flags &= ~GUI_PRINT_FLAG_BOLD; break; case 3: /* italic */ flags |= GUI_PRINT_FLAG_ITALIC; break; case 23: /* not italic */ flags &= ~GUI_PRINT_FLAG_ITALIC; break; case 4: /* underline */ flags |= GUI_PRINT_FLAG_UNDERLINE; break; case 24: /* not underline */ flags &= ~GUI_PRINT_FLAG_UNDERLINE; break; case 5: /* blink */ flags |= GUI_PRINT_FLAG_BLINK; break; case 25: /* steady */ flags &= ~GUI_PRINT_FLAG_BLINK; break; case 7: /* reverse */ flags |= GUI_PRINT_FLAG_REVERSE; break; case 27: /* positive */ flags &= ~GUI_PRINT_FLAG_REVERSE; break; case 39: /* reset fg */ flags &= ~GUI_PRINT_FLAG_COLOR_24_FG; fg = theme->default_color; break; case 49: /* reset bg */ bg = -1; flags &= ~(GUI_PRINT_FLAG_COLOR_24_BG | GUI_PRINT_FLAG_INDENT); break; case 38: case 48: /* ANSI indexed color or RGB color */ if (*str != ';') break; str++; for (num2 = 0; i_isdigit(*str); str++) num2 = num2*10 + (*str-'0'); switch (num2) { case 2: /* RGB */ num2 = 0; for (i = 0; i < 3; ++i) { num2 <<= 8; if (*str != ';' && *str != ':') { i = -1; break; } str++; for (; i_isdigit(*str); str++) num2 = (num2&~0xff) | (((num2&0xff) * 10 + (*str-'0'))&0xff); } if (i == -1) break; #ifdef TERM_TRUECOLOR if (num == 38) { flags |= GUI_PRINT_FLAG_COLOR_24_FG; fg = num2; } else if (num == 48) { flags |= GUI_PRINT_FLAG_COLOR_24_BG; bg = num2; } #else /* !TERM_TRUECOLOR */ if (num == 38) { flags &= ~GUI_PRINT_FLAG_COLOR_24_FG; fg = color_24bit_256_int(num2); } else if (num == 48) { flags &= ~GUI_PRINT_FLAG_COLOR_24_BG; bg = color_24bit_256_int(num2); } #endif break; case 5: /* indexed */ if (*str != ';') break; str++; for (num2 = 0; i_isdigit(*str); str++) num2 = num2*10 + (*str-'0'); if (num == 38) { flags &= ~GUI_PRINT_FLAG_COLOR_24_FG; fg = num2; } else if (num == 48) { flags &= ~GUI_PRINT_FLAG_COLOR_24_BG; bg = num2; } break; } break; default: if (num >= 30 && num <= 37) { flags &= ~GUI_PRINT_FLAG_COLOR_24_FG; fg = ansitab[num-30]; } else if (num >= 40 && num <= 47) { flags &= ~GUI_PRINT_FLAG_COLOR_24_BG; bg = ansitab[num-40]; } else if (num >= 90 && num <= 97) { flags &= ~GUI_PRINT_FLAG_COLOR_24_FG; fg = 8 + ansitab[num-90]; } else if (num >= 100 && num <= 107) { flags &= ~GUI_PRINT_FLAG_COLOR_24_BG; bg = 8 + ansitab[num-100]; } break; } num = 0; if (*str == 'm') { if (fg_ret != NULL) *fg_ret = fg; if (bg_ret != NULL) *bg_ret = bg; if (flags_ret != NULL) *flags_ret = flags; str++; break; } } return str; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Merge branch 'security' into 'master' See merge request !7'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void format_expand_code(const char **format, GString *out, int *flags) { int set; if (flags == NULL) { /* flags are being ignored - skip the code */ while (**format != ']') (*format)++; return; } set = TRUE; (*format)++; while (**format != ']' && **format != '\0') { if (**format == '+') set = TRUE; else if (**format == '-') set = FALSE; else switch (**format) { case 's': case 'S': *flags |= !set ? PRINT_FLAG_UNSET_LINE_START : **format == 's' ? PRINT_FLAG_SET_LINE_START : PRINT_FLAG_SET_LINE_START_IRSSI; break; case 't': *flags |= set ? PRINT_FLAG_SET_TIMESTAMP : PRINT_FLAG_UNSET_TIMESTAMP; break; case 'T': *flags |= set ? PRINT_FLAG_SET_SERVERTAG : PRINT_FLAG_UNSET_SERVERTAG; break; } (*format)++; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Merge branch 'security' into 'master' See merge request !7'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline void perf_event_exit_cpu(int cpu) { } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-362'], 'message': 'perf: Fix race in swevent hash There's a race on CPU unplug where we free the swevent hash array while it can still have events on. This will result in a use-after-free which is BAD. Simply do not free the hash array on unplug. This leaves the thing around and no use-after-free takes place. When the last swevent dies, we do a for_each_possible_cpu() iteration anyway to clean these up, at which time we'll free it, so no leakage will occur. Reported-by: Sasha Levin <[email protected]> Tested-by: Sasha Levin <[email protected]> Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Stephane Eranian <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: Vince Weaver <[email protected]> Signed-off-by: Ingo Molnar <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void perf_event_exit_cpu(int cpu) { struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); perf_event_exit_cpu_context(cpu); mutex_lock(&swhash->hlist_mutex); swhash->online = false; swevent_hlist_release(swhash); mutex_unlock(&swhash->hlist_mutex); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-362'], 'message': 'perf: Fix race in swevent hash There's a race on CPU unplug where we free the swevent hash array while it can still have events on. This will result in a use-after-free which is BAD. Simply do not free the hash array on unplug. This leaves the thing around and no use-after-free takes place. When the last swevent dies, we do a for_each_possible_cpu() iteration anyway to clean these up, at which time we'll free it, so no leakage will occur. Reported-by: Sasha Levin <[email protected]> Tested-by: Sasha Levin <[email protected]> Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Stephane Eranian <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: Vince Weaver <[email protected]> Signed-off-by: Ingo Molnar <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int perf_swevent_add(struct perf_event *event, int flags) { struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable); struct hw_perf_event *hwc = &event->hw; struct hlist_head *head; if (is_sampling_event(event)) { hwc->last_period = hwc->sample_period; perf_swevent_set_period(event); } hwc->state = !(flags & PERF_EF_START); head = find_swevent_head(swhash, event); if (!head) { /* * We can race with cpu hotplug code. Do not * WARN if the cpu just got unplugged. */ WARN_ON_ONCE(swhash->online); return -EINVAL; } hlist_add_head_rcu(&event->hlist_entry, head); perf_event_update_userpage(event); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-362'], 'message': 'perf: Fix race in swevent hash There's a race on CPU unplug where we free the swevent hash array while it can still have events on. This will result in a use-after-free which is BAD. Simply do not free the hash array on unplug. This leaves the thing around and no use-after-free takes place. When the last swevent dies, we do a for_each_possible_cpu() iteration anyway to clean these up, at which time we'll free it, so no leakage will occur. Reported-by: Sasha Levin <[email protected]> Tested-by: Sasha Levin <[email protected]> Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Stephane Eranian <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: Vince Weaver <[email protected]> Signed-off-by: Ingo Molnar <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: check_offset(char *memory, int total_size, char *name, void *offset, int size) { ptrdiff_t need_size = (char *) offset - memory + size; /*debug("check_offset: size=%x vs %x offset=%x size=%x\n", need_size, total_size, (char *) offset - memory, size);*/ if (need_size < 0 || need_size > total_size) { warn(_("%s: premature end"), name); return false; } return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'wrestool: Make check_offset more stringent'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int gnutls_x509_ext_import_proxy(const gnutls_datum_t * ext, int *pathlen, char **policyLanguage, char **policy, size_t * sizeof_policy) { ASN1_TYPE c2 = ASN1_TYPE_EMPTY; int result; gnutls_datum_t value = { NULL, 0 }; if ((result = asn1_create_element (_gnutls_get_pkix(), "PKIX1.ProxyCertInfo", &c2)) != ASN1_SUCCESS) { gnutls_assert(); return _gnutls_asn2err(result); } result = _asn1_strict_der_decode(&c2, ext->data, ext->size, NULL); if (result != ASN1_SUCCESS) { gnutls_assert(); result = _gnutls_asn2err(result); goto cleanup; } if (pathlen) { result = _gnutls_x509_read_uint(c2, "pCPathLenConstraint", (unsigned int *) pathlen); if (result == GNUTLS_E_ASN1_ELEMENT_NOT_FOUND) *pathlen = -1; else if (result != GNUTLS_E_SUCCESS) { gnutls_assert(); result = _gnutls_asn2err(result); goto cleanup; } } result = _gnutls_x509_read_value(c2, "proxyPolicy.policyLanguage", &value); if (result < 0) { gnutls_assert(); goto cleanup; } if (policyLanguage) { *policyLanguage = (char *)value.data; } else { gnutls_free(value.data); value.data = NULL; } result = _gnutls_x509_read_value(c2, "proxyPolicy.policy", &value); if (result == GNUTLS_E_ASN1_ELEMENT_NOT_FOUND) { if (policy) *policy = NULL; if (sizeof_policy) *sizeof_policy = 0; } else if (result < 0) { gnutls_assert(); goto cleanup; } else { if (policy) { *policy = (char *)value.data; value.data = NULL; } if (sizeof_policy) *sizeof_policy = value.size; } result = 0; cleanup: gnutls_free(value.data); asn1_delete_structure(&c2); return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'gnutls_x509_ext_import_proxy: fix issue reading the policy language If the language was set but the policy wasn't, that could lead to a double free, as the value returned to the user was freed.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int git_pkt_parse_line( git_pkt **head, const char *line, const char **out, size_t bufflen) { int ret; int32_t len; /* Not even enough for the length */ if (bufflen > 0 && bufflen < PKT_LEN_SIZE) return GIT_EBUFS; len = parse_len(line); if (len < 0) { /* * If we fail to parse the length, it might be because the * server is trying to send us the packfile already. */ if (bufflen >= 4 && !git__prefixcmp(line, "PACK")) { giterr_clear(); *out = line; return pack_pkt(head); } return (int)len; } /* * If we were given a buffer length, then make sure there is * enough in the buffer to satisfy this line */ if (bufflen > 0 && bufflen < (size_t)len) return GIT_EBUFS; line += PKT_LEN_SIZE; /* * TODO: How do we deal with empty lines? Try again? with the next * line? */ if (len == PKT_LEN_SIZE) { *head = NULL; *out = line; return 0; } if (len == 0) { /* Flush pkt */ *out = line; return flush_pkt(head); } len -= PKT_LEN_SIZE; /* the encoded length includes its own size */ if (*line == GIT_SIDE_BAND_DATA) ret = data_pkt(head, line, len); else if (*line == GIT_SIDE_BAND_PROGRESS) ret = sideband_progress_pkt(head, line, len); else if (*line == GIT_SIDE_BAND_ERROR) ret = sideband_error_pkt(head, line, len); else if (!git__prefixcmp(line, "ACK")) ret = ack_pkt(head, line, len); else if (!git__prefixcmp(line, "NAK")) ret = nak_pkt(head); else if (!git__prefixcmp(line, "ERR ")) ret = err_pkt(head, line, len); else if (*line == '#') ret = comment_pkt(head, line, len); else if (!git__prefixcmp(line, "ok")) ret = ok_pkt(head, line, len); else if (!git__prefixcmp(line, "ng")) ret = ng_pkt(head, line, len); else if (!git__prefixcmp(line, "unpack")) ret = unpack_pkt(head, line, len); else ret = ref_pkt(head, line, len); *out = line + len; return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'smart_pkt: verify packet length exceeds PKT_LEN_SIZE Each packet line in the Git protocol is prefixed by a four-byte length of how much data will follow, which we parse in `git_pkt_parse_line`. The transmitted length can either be equal to zero in case of a flush packet or has to be at least of length four, as it also includes the encoded length itself. Not checking this may result in a buffer overflow as we directly pass the length to functions which accept a `size_t` length as parameter. Fix the issue by verifying that non-flush packets have at least a length of `PKT_LEN_SIZE`.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int parse_report(transport_smart *transport, git_push *push) { git_pkt *pkt = NULL; const char *line_end = NULL; gitno_buffer *buf = &transport->buffer; int error, recvd; git_buf data_pkt_buf = GIT_BUF_INIT; for (;;) { if (buf->offset > 0) error = git_pkt_parse_line(&pkt, buf->data, &line_end, buf->offset); else error = GIT_EBUFS; if (error < 0 && error != GIT_EBUFS) { error = -1; goto done; } if (error == GIT_EBUFS) { if ((recvd = gitno_recv(buf)) < 0) { error = recvd; goto done; } if (recvd == 0) { giterr_set(GITERR_NET, "early EOF"); error = GIT_EEOF; goto done; } continue; } gitno_consume(buf, line_end); error = 0; if (pkt == NULL) continue; switch (pkt->type) { case GIT_PKT_DATA: /* This is a sideband packet which contains other packets */ error = add_push_report_sideband_pkt(push, (git_pkt_data *)pkt, &data_pkt_buf); break; case GIT_PKT_ERR: giterr_set(GITERR_NET, "report-status: Error reported: %s", ((git_pkt_err *)pkt)->error); error = -1; break; case GIT_PKT_PROGRESS: if (transport->progress_cb) { git_pkt_progress *p = (git_pkt_progress *) pkt; error = transport->progress_cb(p->data, p->len, transport->message_cb_payload); } break; default: error = add_push_report_pkt(push, pkt); break; } git_pkt_free(pkt); /* add_push_report_pkt returns GIT_ITEROVER when it receives a flush */ if (error == GIT_ITEROVER) { error = 0; if (data_pkt_buf.size > 0) { /* If there was data remaining in the pack data buffer, * then the server sent a partial pkt-line */ giterr_set(GITERR_NET, "Incomplete pack data pkt-line"); error = GIT_ERROR; } goto done; } if (error < 0) { goto done; } } done: git_buf_free(&data_pkt_buf); return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-119'], 'message': 'smart_pkt: treat empty packet lines as error The Git protocol does not specify what should happen in the case of an empty packet line (that is a packet line "0004"). We currently indicate success, but do not return a packet in the case where we hit an empty line. The smart protocol was not prepared to handle such packets in all cases, though, resulting in a `NULL` pointer dereference. Fix the issue by returning an error instead. As such kind of packets is not even specified by upstream, this is the right thing to do.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: read_old_length(cdk_stream_t inp, int ctb, size_t * r_len, size_t * r_size) { int llen = ctb & 0x03; if (llen == 0) { *r_len = cdk_stream_getc(inp); (*r_size)++; } else if (llen == 1) { *r_len = read_16(inp); (*r_size) += 2; } else if (llen == 2) { *r_len = read_32(inp); (*r_size) += 4; } else { *r_len = 0; *r_size = 0; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'opencdk: added error checking in the stream reading functions This addresses an out of memory error. Issue found using oss-fuzz: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=337 Signed-off-by: Nikos Mavrogiannopoulos <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static u32 read_32(cdk_stream_t s) { byte buf[4]; size_t nread; assert(s != NULL); stream_read(s, buf, 4, &nread); if (nread != 4) return (u32) - 1; return buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3]; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'opencdk: added error checking in the stream reading functions This addresses an out of memory error. Issue found using oss-fuzz: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=337 Signed-off-by: Nikos Mavrogiannopoulos <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static u16 read_16(cdk_stream_t s) { byte buf[2]; size_t nread; assert(s != NULL); stream_read(s, buf, 2, &nread); if (nread != 2) return (u16) - 1; return buf[0] << 8 | buf[1]; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'opencdk: added error checking in the stream reading functions This addresses an out of memory error. Issue found using oss-fuzz: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=337 Signed-off-by: Nikos Mavrogiannopoulos <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: u32 cdk_pk_get_keyid(cdk_pubkey_t pk, u32 * keyid) { u32 lowbits = 0; byte buf[24]; if (pk && (!pk->keyid[0] || !pk->keyid[1])) { if (pk->version < 4 && is_RSA(pk->pubkey_algo)) { byte p[MAX_MPI_BYTES]; size_t n; n = MAX_MPI_BYTES; _gnutls_mpi_print(pk->mpi[0], p, &n); pk->keyid[0] = p[n - 8] << 24 | p[n - 7] << 16 | p[n - 6] << 8 | p[n - 5]; pk->keyid[1] = p[n - 4] << 24 | p[n - 3] << 16 | p[n - 2] << 8 | p[n - 1]; } else if (pk->version == 4) { cdk_pk_get_fingerprint(pk, buf); pk->keyid[0] = _cdk_buftou32(buf + 12); pk->keyid[1] = _cdk_buftou32(buf + 16); } } lowbits = pk ? pk->keyid[1] : 0; if (keyid && pk) { keyid[0] = pk->keyid[0]; keyid[1] = pk->keyid[1]; } return lowbits; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'opencdk: cdk_pk_get_keyid: fix stack overflow Issue found using oss-fuzz: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=340 Signed-off-by: Nikos Mavrogiannopoulos <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: extract_group_icon_cursor_resource(WinLibrary *fi, WinResource *wr, char *lang, int *ressize, bool is_icon) { Win32CursorIconDir *icondir; Win32CursorIconFileDir *fileicondir; char *memory; int c, size, offset, skipped; /* get resource data and size */ icondir = (Win32CursorIconDir *) get_resource_entry(fi, wr, &size); if (icondir == NULL) { /* get_resource_entry will print error */ return NULL; } /* calculate total size of output file */ RETURN_IF_BAD_POINTER(NULL, icondir->count); skipped = 0; for (c = 0 ; c < icondir->count ; c++) { int level; int iconsize; char name[14]; WinResource *fwr; RETURN_IF_BAD_POINTER(NULL, icondir->entries[c]); /*printf("%d. bytes_in_res=%d width=%d height=%d planes=%d bit_count=%d\n", c, icondir->entries[c].bytes_in_res, (is_icon ? icondir->entries[c].res_info.icon.width : icondir->entries[c].res_info.cursor.width), (is_icon ? icondir->entries[c].res_info.icon.height : icondir->entries[c].res_info.cursor.height), icondir->entries[c].plane_count, icondir->entries[c].bit_count);*/ /* find the corresponding icon resource */ snprintf(name, sizeof(name)/sizeof(char), "-%d", icondir->entries[c].res_id); fwr = find_resource(fi, (is_icon ? "-3" : "-1"), name, lang, &level); if (fwr == NULL) { warn(_("%s: could not find `%s' in `%s' resource."), fi->name, &name[1], (is_icon ? "group_icon" : "group_cursor")); return NULL; } if (get_resource_entry(fi, fwr, &iconsize) != NULL) { if (iconsize == 0) { warn(_("%s: icon resource `%s' is empty, skipping"), fi->name, name); skipped++; continue; } if (iconsize != icondir->entries[c].bytes_in_res) { warn(_("%s: mismatch of size in icon resource `%s' and group (%d vs %d)"), fi->name, name, iconsize, icondir->entries[c].bytes_in_res); } size += iconsize < icondir->entries[c].bytes_in_res ? icondir->entries[c].bytes_in_res : iconsize; /* cursor resources have two additional WORDs that contain * hotspot info */ if (!is_icon) size -= sizeof(uint16_t)*2; } } offset = sizeof(Win32CursorIconFileDir) + (icondir->count-skipped) * sizeof(Win32CursorIconFileDirEntry); size += offset; *ressize = size; /* allocate that much memory */ memory = xmalloc(size); fileicondir = (Win32CursorIconFileDir *) memory; /* transfer Win32CursorIconDir structure members */ fileicondir->reserved = icondir->reserved; fileicondir->type = icondir->type; fileicondir->count = icondir->count - skipped; /* transfer each cursor/icon: Win32CursorIconDirEntry and data */ skipped = 0; for (c = 0 ; c < icondir->count ; c++) { int level; char name[14]; WinResource *fwr; char *data; /* find the corresponding icon resource */ snprintf(name, sizeof(name)/sizeof(char), "-%d", icondir->entries[c].res_id); fwr = find_resource(fi, (is_icon ? "-3" : "-1"), name, lang, &level); if (fwr == NULL) { warn(_("%s: could not find `%s' in `%s' resource."), fi->name, &name[1], (is_icon ? "group_icon" : "group_cursor")); return NULL; } /* get data and size of that resource */ data = get_resource_entry(fi, fwr, &size); if (data == NULL) { /* get_resource_entry has printed error */ return NULL; } if (size == 0) { skipped++; continue; } /* copy ICONDIRENTRY (not including last dwImageOffset) */ memcpy(&fileicondir->entries[c-skipped], &icondir->entries[c], sizeof(Win32CursorIconFileDirEntry)-sizeof(uint32_t)); /* special treatment for cursors */ if (!is_icon) { fileicondir->entries[c-skipped].width = icondir->entries[c].res_info.cursor.width; fileicondir->entries[c-skipped].height = icondir->entries[c].res_info.cursor.height / 2; fileicondir->entries[c-skipped].color_count = 0; fileicondir->entries[c-skipped].reserved = 0; } /* set image offset and increase it */ fileicondir->entries[c-skipped].dib_offset = offset; /* transfer resource into file memory */ if (is_icon) { memcpy(&memory[offset], data, icondir->entries[c].bytes_in_res); } else { fileicondir->entries[c-skipped].hotspot_x = ((uint16_t *) data)[0]; fileicondir->entries[c-skipped].hotspot_y = ((uint16_t *) data)[1]; memcpy(&memory[offset], data+sizeof(uint16_t)*2, icondir->entries[c].bytes_in_res-sizeof(uint16_t)*2); offset -= sizeof(uint16_t)*2; } /* increase the offset pointer */ offset += icondir->entries[c].bytes_in_res; } return (void *) memory; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'prevent access to unallocated memory in wrestool (BZ #1249276)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: unsigned char *base64decode(const char *buf, size_t *size) { if (!buf || !size) return NULL; size_t len = (*size > 0) ? *size : strlen(buf); if (len <= 0) return NULL; unsigned char *outbuf = (unsigned char*)malloc((len/4)*3+3); const char *ptr = buf; int p = 0; size_t l = 0; do { ptr += strspn(ptr, "\r\n\t "); if (*ptr == '\0' || ptr >= buf+len) { break; } l = strcspn(ptr, "\r\n\t "); if (l > 3 && ptr+l <= buf+len) { p+=base64decode_block(outbuf+p, ptr, l); ptr += l; } else { break; } } while (1); outbuf[p] = 0; *size = p; return outbuf; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'base64: Rework base64decode to handle split encoded data correctly'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: initialize(int argc, VALUE argv[], VALUE self) { ffi_cif * cif; ffi_type **arg_types; ffi_status result; VALUE ptr, args, ret_type, abi, kwds; long i; rb_scan_args(argc, argv, "31:", &ptr, &args, &ret_type, &abi, &kwds); if(NIL_P(abi)) abi = INT2NUM(FFI_DEFAULT_ABI); Check_Type(args, T_ARRAY); Check_Max_Args("args", RARRAY_LENINT(args)); rb_iv_set(self, "@ptr", ptr); rb_iv_set(self, "@args", args); rb_iv_set(self, "@return_type", ret_type); rb_iv_set(self, "@abi", abi); if (!NIL_P(kwds)) rb_hash_foreach(kwds, parse_keyword_arg_i, self); TypedData_Get_Struct(self, ffi_cif, &function_data_type, cif); arg_types = xcalloc(RARRAY_LEN(args) + 1, sizeof(ffi_type *)); for (i = 0; i < RARRAY_LEN(args); i++) { int type = NUM2INT(RARRAY_AREF(args, i)); arg_types[i] = INT2FFI_TYPE(type); } arg_types[RARRAY_LEN(args)] = NULL; result = ffi_prep_cif ( cif, NUM2INT(abi), RARRAY_LENINT(args), INT2FFI_TYPE(NUM2INT(ret_type)), arg_types); if (result) rb_raise(rb_eRuntimeError, "error creating CIF %d", result); return self; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'function.c: check arguments * ext/fiddle/function.c (initialize): check all arguments first. reported by Marcin 'Icewall' Noga of Cisco Talos. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@53082 b2dd03c8-39d4-4d8f-98ff-823fe69b080e'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void silk_NLSF_stabilize( opus_int16 *NLSF_Q15, /* I/O Unstable/stabilized normalized LSF vector in Q15 [L] */ const opus_int16 *NDeltaMin_Q15, /* I Min distance vector, NDeltaMin_Q15[L] must be >= 1 [L+1] */ const opus_int L /* I Number of NLSF parameters in the input vector */ ) { opus_int i, I=0, k, loops; opus_int16 center_freq_Q15; opus_int32 diff_Q15, min_diff_Q15, min_center_Q15, max_center_Q15; /* This is necessary to ensure an output within range of a opus_int16 */ silk_assert( NDeltaMin_Q15[L] >= 1 ); for( loops = 0; loops < MAX_LOOPS; loops++ ) { /**************************/ /* Find smallest distance */ /**************************/ /* First element */ min_diff_Q15 = NLSF_Q15[0] - NDeltaMin_Q15[0]; I = 0; /* Middle elements */ for( i = 1; i <= L-1; i++ ) { diff_Q15 = NLSF_Q15[i] - ( NLSF_Q15[i-1] + NDeltaMin_Q15[i] ); if( diff_Q15 < min_diff_Q15 ) { min_diff_Q15 = diff_Q15; I = i; } } /* Last element */ diff_Q15 = ( 1 << 15 ) - ( NLSF_Q15[L-1] + NDeltaMin_Q15[L] ); if( diff_Q15 < min_diff_Q15 ) { min_diff_Q15 = diff_Q15; I = L; } /***************************************************/ /* Now check if the smallest distance non-negative */ /***************************************************/ if( min_diff_Q15 >= 0 ) { return; } if( I == 0 ) { /* Move away from lower limit */ NLSF_Q15[0] = NDeltaMin_Q15[0]; } else if( I == L) { /* Move away from higher limit */ NLSF_Q15[L-1] = ( 1 << 15 ) - NDeltaMin_Q15[L]; } else { /* Find the lower extreme for the location of the current center frequency */ min_center_Q15 = 0; for( k = 0; k < I; k++ ) { min_center_Q15 += NDeltaMin_Q15[k]; } min_center_Q15 += silk_RSHIFT( NDeltaMin_Q15[I], 1 ); /* Find the upper extreme for the location of the current center frequency */ max_center_Q15 = 1 << 15; for( k = L; k > I; k-- ) { max_center_Q15 -= NDeltaMin_Q15[k]; } max_center_Q15 -= silk_RSHIFT( NDeltaMin_Q15[I], 1 ); /* Move apart, sorted by value, keeping the same center frequency */ center_freq_Q15 = (opus_int16)silk_LIMIT_32( silk_RSHIFT_ROUND( (opus_int32)NLSF_Q15[I-1] + (opus_int32)NLSF_Q15[I], 1 ), min_center_Q15, max_center_Q15 ); NLSF_Q15[I-1] = center_freq_Q15 - silk_RSHIFT( NDeltaMin_Q15[I], 1 ); NLSF_Q15[I] = NLSF_Q15[I-1] + NDeltaMin_Q15[I]; } } /* Safe and simple fall back method, which is less ideal than the above */ if( loops == MAX_LOOPS ) { /* Insertion sort (fast for already almost sorted arrays): */ /* Best case: O(n) for an already sorted array */ /* Worst case: O(n^2) for an inversely sorted array */ silk_insertion_sort_increasing_all_values_int16( &NLSF_Q15[0], L ); /* First NLSF should be no less than NDeltaMin[0] */ NLSF_Q15[0] = silk_max_int( NLSF_Q15[0], NDeltaMin_Q15[0] ); /* Keep delta_min distance between the NLSFs */ for( i = 1; i < L; i++ ) NLSF_Q15[i] = silk_max_int( NLSF_Q15[i], NLSF_Q15[i-1] + NDeltaMin_Q15[i] ); /* Last NLSF should be no higher than 1 - NDeltaMin[L] */ NLSF_Q15[L-1] = silk_min_int( NLSF_Q15[L-1], (1<<15) - NDeltaMin_Q15[L] ); /* Keep NDeltaMin distance between the NLSFs */ for( i = L-2; i >= 0; i-- ) NLSF_Q15[i] = silk_min_int( NLSF_Q15[i], NLSF_Q15[i+1] - NDeltaMin_Q15[i+1] ); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Ensure that NLSF cannot be negative when computing a min distance between them Signed-off-by: Jean-Marc Valin <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static size_t WritePSDChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, MagickOffsetType size_offset,const MagickBooleanType separate, ExceptionInfo *exception) { Image *mask; MagickOffsetType rows_offset; size_t channels, count, length, offset_length; unsigned char *compact_pixels; count=0; offset_length=0; rows_offset=0; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=AcquireCompactPixels(image,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } channels=1; if (separate == MagickFalse) { if (next_image->storage_class != PseudoClass) { if (IsImageGray(next_image) == MagickFalse) channels=next_image->colorspace == CMYKColorspace ? 4 : 3; if (next_image->alpha_trait != UndefinedPixelTrait) channels++; } rows_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,channels); offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); } size_offset+=2; if (next_image->storage_class == PseudoClass) { length=WritePSDChannel(psd_info,image_info,image,next_image, IndexQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (IsImageGray(next_image) != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, GrayQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); length=WritePSDChannel(psd_info,image_info,image,next_image, RedQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, GreenQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, BlueQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; if (next_image->colorspace == CMYKColorspace) { length=WritePSDChannel(psd_info,image_info,image,next_image, BlackQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } if (next_image->alpha_trait != UndefinedPixelTrait) { length=WritePSDChannel(psd_info,image_info,image,next_image, AlphaQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (separate != MagickFalse) { const char *property; property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, exception); if (mask != (Image *) NULL) { if (mask->compression == RLECompression) { compact_pixels=AcquireCompactPixels(mask,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } length=WritePSDChannel(psd_info,image_info,image,mask, RedQuantum,compact_pixels,rows_offset,MagickTrue,exception); (void) WritePSDSize(psd_info,image,length,size_offset); count+=length; compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); } } } return(count); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/350'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static unsigned char *AcquireCompactPixels(const Image *image, ExceptionInfo *exception) { size_t packet_size; unsigned char *compact_pixels; packet_size=image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) AcquireQuantumMemory((9* image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); } return(compact_pixels); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/350'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; register ssize_t i; ssize_t count, j, number_layers; size=GetPSDSize(psd_info,image); if (size == 0) { /* Skip layers & masks. */ (void) ReadBlobLong(image); count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); status=MagickFalse; if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) return(MagickTrue); else { count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0)) size=GetPSDSize(psd_info,image); else return(MagickTrue); } } status=MagickTrue; if (size != 0) { layer_info=(LayerInfo *) NULL; number_layers=(short) ReadBlobShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->alpha_trait=BlendPixelTrait; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(layer_info,0,(size_t) number_layers* sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t x, y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); layer_info[i].page.y=ReadBlobSignedLong(image); layer_info[i].page.x=ReadBlobSignedLong(image); y=ReadBlobSignedLong(image); x=ReadBlobSignedLong(image); layer_info[i].page.width=(size_t) (x-layer_info[i].page.x); layer_info[i].page.height=(size_t) (y-layer_info[i].page.y); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); ReversePSDString(image,layer_info[i].blendkey,4); layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=ReadBlobSignedLong(image); layer_info[i].mask.page.x=ReadBlobSignedLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width, (double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); /* We read it, but don't use it... */ for (j=0; j < (ssize_t) length; j+=8) { size_t blend_source=ReadBlobLong(image); size_t blend_dest=ReadBlobLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " source(%x), dest(%x)",(unsigned int) blend_source,(unsigned int) blend_dest); } } /* Layer name. */ length=(MagickSizeType) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); if ((length % 4) != 0) { length=4-(length % 4); combined_length+=length; /* Skip over the padding of the layer name */ if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=(MagickSizeType) size-combined_length; if (length > 0) { unsigned char *info; layer_info[i].info=AcquireStringInfo((const size_t) length); info=GetStringInfoDatum(layer_info[i].info); (void) ReadBlob(image,(const size_t) length,info); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (layer_info[i].info != (StringInfo *) NULL) { (void) SetImageProfile(layer_info[i].image,"psd:additional-info", layer_info[i].info,exception); layer_info[i].info=DestroyStringInfo(layer_info[i].info); } } if (image_info->ping == MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=0; j < layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i], exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType) number_layers); if (status == MagickFalse) break; } } if (status != MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers > 0) { for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; } layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } else layer_info=DestroyLayerInfo(layer_info,number_layers); } return(status); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-401'], 'message': 'Fix improper cast that could cause an overflow as demonstrated in #347.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: inbound_cap_ls (server *serv, char *nick, char *extensions_str, const message_tags_data *tags_data) { char buffer[256]; /* buffer for requesting capabilities and emitting the signal */ guint32 want_cap; /* format the CAP REQ string based on previous capabilities being requested or not */ guint32 want_sasl; /* CAP END shouldn't be sent when SASL is requested, it needs further responses */ char **extensions; int i; EMIT_SIGNAL_TIMESTAMP (XP_TE_CAPLIST, serv->server_session, nick, extensions_str, NULL, NULL, 0, tags_data->timestamp); want_cap = 0; want_sasl = 0; extensions = g_strsplit (extensions_str, " ", 0); strcpy (buffer, "CAP REQ :"); for (i=0; extensions[i]; i++) { const char *extension = extensions[i]; if (!strcmp (extension, "identify-msg")) { strcat (buffer, "identify-msg "); want_cap = 1; } if (!strcmp (extension, "multi-prefix")) { strcat (buffer, "multi-prefix "); want_cap = 1; } if (!strcmp (extension, "away-notify")) { strcat (buffer, "away-notify "); want_cap = 1; } if (!strcmp (extension, "account-notify")) { strcat (buffer, "account-notify "); want_cap = 1; } if (!strcmp (extension, "extended-join")) { strcat (buffer, "extended-join "); want_cap = 1; } if (!strcmp (extension, "userhost-in-names")) { strcat (buffer, "userhost-in-names "); want_cap = 1; } /* bouncers can prefix a name space to the extension so we should use. * znc <= 1.0 uses "znc.in/server-time" and newer use "znc.in/server-time-iso". */ if (!strcmp (extension, "znc.in/server-time-iso")) { strcat (buffer, "znc.in/server-time-iso "); want_cap = 1; } if (!strcmp (extension, "znc.in/server-time")) { strcat (buffer, "znc.in/server-time "); want_cap = 1; } if (prefs.hex_irc_cap_server_time && !strcmp (extension, "server-time")) { strcat (buffer, "server-time "); want_cap = 1; } /* if the SASL password is set AND auth mode is set to SASL, request SASL auth */ if (!strcmp (extension, "sasl") && ((serv->loginmethod == LOGIN_SASL && strlen (serv->password) != 0) || (serv->loginmethod == LOGIN_SASLEXTERNAL && serv->have_cert))) { strcat (buffer, "sasl "); want_cap = 1; want_sasl = 1; } } g_strfreev (extensions); if (want_cap) { /* buffer + 9 = emit buffer without "CAP REQ :" */ EMIT_SIGNAL_TIMESTAMP (XP_TE_CAPREQ, serv->server_session, buffer + 9, NULL, NULL, NULL, 0, tags_data->timestamp); tcp_sendf (serv, "%s\r\n", g_strchomp (buffer)); } if (!want_sasl) { /* if we use SASL, CAP END is dealt via raw numerics */ serv->sent_capend = TRUE; tcp_send_len (serv, "CAP END\r\n", 9); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'Clean up handling CAP LS'</s>