text
stringlengths
478
227k
<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 drbg_kcapi_random(struct crypto_rng *tfm, u8 *rdata, unsigned int dlen) { struct drbg_state *drbg = crypto_rng_ctx(tfm); if (0 < dlen) { return drbg_generate_long(drbg, rdata, dlen, NULL); } else { struct drbg_gen *data = (struct drbg_gen *)rdata; struct drbg_string addtl; /* catch NULL pointer */ if (!data) return 0; drbg_set_testdata(drbg, data->test_data); /* linked list variable is now local to allow modification */ drbg_string_fill(&addtl, data->addtl->buf, data->addtl->len); return drbg_generate_long(drbg, data->outbuf, data->outlen, &addtl); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'crypto: drbg - Convert to new rng interface This patch converts the DRBG implementation to the new low-level rng interface. This allows us to get rid of struct drbg_gen by using the new RNG API instead. Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> Acked-by: Stephan Mueller <smueller@chronox.de>'</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 sum_init(int csum_type, int seed) { char s[4]; if (csum_type < 0) csum_type = parse_csum_name(NULL, 0); cursum_type = csum_type; switch (csum_type) { case CSUM_MD5: md5_begin(&md); break; case CSUM_MD4: mdfour_begin(&md); sumresidue = 0; break; case CSUM_MD4_OLD: case CSUM_MD4_BUSTED: mdfour_begin(&md); sumresidue = 0; SIVAL(s, 0, seed); sum_update(s, 4); break; case CSUM_NONE: break; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-354'], 'message': 'Handle archaic checksums properly.'</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: const std::string& get_tenant() const { ceph_assert(t != Wildcard); return u.tenant; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617'], 'message': 'rgw: Remove assertions in IAM Policy A couple of them could be triggered by user input. Signed-off-by: Adam C. Emerson <aemerson@redhat.com>'</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 struct usb_cdc_union_desc * ims_pcu_get_cdc_union_desc(struct usb_interface *intf) { const void *buf = intf->altsetting->extra; size_t buflen = intf->altsetting->extralen; struct usb_cdc_union_desc *union_desc; if (!buf) { dev_err(&intf->dev, "Missing descriptor data\n"); return NULL; } if (!buflen) { dev_err(&intf->dev, "Zero length descriptor\n"); return NULL; } while (buflen > 0) { union_desc = (struct usb_cdc_union_desc *)buf; if (union_desc->bDescriptorType == USB_DT_CS_INTERFACE && union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) { dev_dbg(&intf->dev, "Found union header\n"); return union_desc; } buflen -= union_desc->bLength; buf += union_desc->bLength; } dev_err(&intf->dev, "Missing CDC union descriptor\n"); return NULL; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Input: ims-psu - check if CDC union descriptor is sane Before trying to use CDC union descriptor, try to validate whether that it is sane by checking that intf->altsetting->extra is big enough and that descriptor bLength is not too big and not too small. Reported-by: Andrey Konovalov <andreyknvl@google.com> Signed-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.com>'</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 uprobe_dup_mmap(struct mm_struct *oldmm, struct mm_struct *newmm) { newmm->uprobes_state.xol_area = NULL; if (test_bit(MMF_HAS_UPROBES, &oldmm->flags)) { set_bit(MMF_HAS_UPROBES, &newmm->flags); /* unconditionally, dup_mmap() skips VM_DONTCOPY vmas */ set_bit(MMF_RECALC_UPROBES, &newmm->flags); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'mm, uprobes: fix multiple free of ->uprobes_state.xol_area Commit 7c051267931a ("mm, fork: make dup_mmap wait for mmap_sem for write killable") made it possible to kill a forking task while it is waiting to acquire its ->mmap_sem for write, in dup_mmap(). However, it was overlooked that this introduced an new error path before the new mm_struct's ->uprobes_state.xol_area has been set to NULL after being copied from the old mm_struct by the memcpy in dup_mm(). For a task that has previously hit a uprobe tracepoint, this resulted in the 'struct xol_area' being freed multiple times if the task was killed at just the right time while forking. Fix it by setting ->uprobes_state.xol_area to NULL in mm_init() rather than in uprobe_dup_mmap(). With CONFIG_UPROBE_EVENTS=y, the bug can be reproduced by the same C program given by commit 2b7e8665b4ff ("fork: fix incorrect fput of ->exe_file causing use-after-free"), provided that a uprobe tracepoint has been set on the fork_thread() function. For example: $ gcc reproducer.c -o reproducer -lpthread $ nm reproducer | grep fork_thread 0000000000400719 t fork_thread $ echo "p $PWD/reproducer:0x719" > /sys/kernel/debug/tracing/uprobe_events $ echo 1 > /sys/kernel/debug/tracing/events/uprobes/enable $ ./reproducer Here is the use-after-free reported by KASAN: BUG: KASAN: use-after-free in uprobe_clear_state+0x1c4/0x200 Read of size 8 at addr ffff8800320a8b88 by task reproducer/198 CPU: 1 PID: 198 Comm: reproducer Not tainted 4.13.0-rc7-00015-g36fde05f3fb5 #255 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-20170228_101828-anatol 04/01/2014 Call Trace: dump_stack+0xdb/0x185 print_address_description+0x7e/0x290 kasan_report+0x23b/0x350 __asan_report_load8_noabort+0x19/0x20 uprobe_clear_state+0x1c4/0x200 mmput+0xd6/0x360 do_exit+0x740/0x1670 do_group_exit+0x13f/0x380 get_signal+0x597/0x17d0 do_signal+0x99/0x1df0 exit_to_usermode_loop+0x166/0x1e0 syscall_return_slowpath+0x258/0x2c0 entry_SYSCALL_64_fastpath+0xbc/0xbe ... Allocated by task 199: save_stack_trace+0x1b/0x20 kasan_kmalloc+0xfc/0x180 kmem_cache_alloc_trace+0xf3/0x330 __create_xol_area+0x10f/0x780 uprobe_notify_resume+0x1674/0x2210 exit_to_usermode_loop+0x150/0x1e0 prepare_exit_to_usermode+0x14b/0x180 retint_user+0x8/0x20 Freed by task 199: save_stack_trace+0x1b/0x20 kasan_slab_free+0xa8/0x1a0 kfree+0xba/0x210 uprobe_clear_state+0x151/0x200 mmput+0xd6/0x360 copy_process.part.8+0x605f/0x65d0 _do_fork+0x1a5/0xbd0 SyS_clone+0x19/0x20 do_syscall_64+0x22f/0x660 return_from_SYSCALL_64+0x0/0x7a Note: without KASAN, you may instead see a "Bad page state" message, or simply a general protection fault. Link: http://lkml.kernel.org/r/20170830033303.17927-1-ebiggers3@gmail.com Fixes: 7c051267931a ("mm, fork: make dup_mmap wait for mmap_sem for write killable") Signed-off-by: Eric Biggers <ebiggers@google.com> Reported-by: Oleg Nesterov <oleg@redhat.com> Acked-by: Oleg Nesterov <oleg@redhat.com> Cc: Alexander Shishkin <alexander.shishkin@linux.intel.com> Cc: Arnaldo Carvalho de Melo <acme@kernel.org> Cc: Dmitry Vyukov <dvyukov@google.com> Cc: Ingo Molnar <mingo@kernel.org> Cc: Konstantin Khlebnikov <koct9i@gmail.com> Cc: Mark Rutland <mark.rutland@arm.com> Cc: Michal Hocko <mhocko@suse.com> Cc: Peter Zijlstra <peterz@infradead.org> Cc: Vlastimil Babka <vbabka@suse.cz> Cc: <stable@vger.kernel.org> [4.7+] Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</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 recv_files(int f_in, int f_out, char *local_name) { int fd1,fd2; STRUCT_STAT st; int iflags, xlen; char *fname, fbuf[MAXPATHLEN]; char xname[MAXPATHLEN]; char fnametmp[MAXPATHLEN]; char *fnamecmp, *partialptr; char fnamecmpbuf[MAXPATHLEN]; uchar fnamecmp_type; struct file_struct *file; int itemizing = am_server ? logfile_format_has_i : stdout_format_has_i; enum logcode log_code = log_before_transfer ? FLOG : FINFO; int max_phase = protocol_version >= 29 ? 2 : 1; int dflt_perms = (ACCESSPERMS & ~orig_umask); #ifdef SUPPORT_ACLS const char *parent_dirname = ""; #endif int ndx, recv_ok; if (DEBUG_GTE(RECV, 1)) rprintf(FINFO, "recv_files(%d) starting\n", cur_flist->used); if (delay_updates) delayed_bits = bitbag_create(cur_flist->used + 1); while (1) { cleanup_disable(); /* This call also sets cur_flist. */ ndx = read_ndx_and_attrs(f_in, f_out, &iflags, &fnamecmp_type, xname, &xlen); if (ndx == NDX_DONE) { if (!am_server && INFO_GTE(PROGRESS, 2) && cur_flist) { set_current_file_index(NULL, 0); end_progress(0); } if (inc_recurse && first_flist) { if (read_batch) { ndx = first_flist->used + first_flist->ndx_start; gen_wants_ndx(ndx, first_flist->flist_num); } flist_free(first_flist); if (first_flist) continue; } else if (read_batch && first_flist) { ndx = first_flist->used; gen_wants_ndx(ndx, first_flist->flist_num); } if (++phase > max_phase) break; if (DEBUG_GTE(RECV, 1)) rprintf(FINFO, "recv_files phase=%d\n", phase); if (phase == 2 && delay_updates) handle_delayed_updates(local_name); write_int(f_out, NDX_DONE); continue; } if (ndx - cur_flist->ndx_start >= 0) file = cur_flist->files[ndx - cur_flist->ndx_start]; else file = dir_flist->files[cur_flist->parent_ndx]; fname = local_name ? local_name : f_name(file, fbuf); if (DEBUG_GTE(RECV, 1)) rprintf(FINFO, "recv_files(%s)\n", fname); #ifdef SUPPORT_XATTRS if (preserve_xattrs && iflags & ITEM_REPORT_XATTR && do_xfers && !(want_xattr_optim && BITS_SET(iflags, ITEM_XNAME_FOLLOWS|ITEM_LOCAL_CHANGE))) recv_xattr_request(file, f_in); #endif if (!(iflags & ITEM_TRANSFER)) { maybe_log_item(file, iflags, itemizing, xname); #ifdef SUPPORT_XATTRS if (preserve_xattrs && iflags & ITEM_REPORT_XATTR && do_xfers && !BITS_SET(iflags, ITEM_XNAME_FOLLOWS|ITEM_LOCAL_CHANGE)) set_file_attrs(fname, file, NULL, fname, 0); #endif if (iflags & ITEM_IS_NEW) { stats.created_files++; if (S_ISREG(file->mode)) { /* Nothing further to count. */ } else if (S_ISDIR(file->mode)) stats.created_dirs++; #ifdef SUPPORT_LINKS else if (S_ISLNK(file->mode)) stats.created_symlinks++; #endif else if (IS_DEVICE(file->mode)) stats.created_devices++; else stats.created_specials++; } continue; } if (phase == 2) { rprintf(FERROR, "got transfer request in phase 2 [%s]\n", who_am_i()); exit_cleanup(RERR_PROTOCOL); } if (file->flags & FLAG_FILE_SENT) { if (csum_length == SHORT_SUM_LENGTH) { if (keep_partial && !partial_dir) make_backups = -make_backups; /* prevents double backup */ if (append_mode) sparse_files = -sparse_files; append_mode = -append_mode; csum_length = SUM_LENGTH; redoing = 1; } } else { if (csum_length != SHORT_SUM_LENGTH) { if (keep_partial && !partial_dir) make_backups = -make_backups; if (append_mode) sparse_files = -sparse_files; append_mode = -append_mode; csum_length = SHORT_SUM_LENGTH; redoing = 0; } if (iflags & ITEM_IS_NEW) stats.created_files++; } if (!am_server && INFO_GTE(PROGRESS, 1)) set_current_file_index(file, ndx); stats.xferred_files++; stats.total_transferred_size += F_LENGTH(file); cleanup_got_literal = 0; if (daemon_filter_list.head && check_filter(&daemon_filter_list, FLOG, fname, 0) < 0) { rprintf(FERROR, "attempt to hack rsync failed.\n"); exit_cleanup(RERR_PROTOCOL); } if (read_batch) { int wanted = redoing ? we_want_redo(ndx) : gen_wants_ndx(ndx, cur_flist->flist_num); if (!wanted) { rprintf(FINFO, "(Skipping batched update for%s \"%s\")\n", redoing ? " resend of" : "", fname); discard_receive_data(f_in, F_LENGTH(file)); file->flags |= FLAG_FILE_SENT; continue; } } remember_initial_stats(); if (!do_xfers) { /* log the transfer */ log_item(FCLIENT, file, iflags, NULL); if (read_batch) discard_receive_data(f_in, F_LENGTH(file)); continue; } if (write_batch < 0) { log_item(FCLIENT, file, iflags, NULL); if (!am_server) discard_receive_data(f_in, F_LENGTH(file)); if (inc_recurse) send_msg_int(MSG_SUCCESS, ndx); continue; } partialptr = partial_dir ? partial_dir_fname(fname) : fname; if (protocol_version >= 29) { switch (fnamecmp_type) { case FNAMECMP_FNAME: fnamecmp = fname; break; case FNAMECMP_PARTIAL_DIR: fnamecmp = partialptr; break; case FNAMECMP_BACKUP: fnamecmp = get_backup_name(fname); break; case FNAMECMP_FUZZY: if (file->dirname) { pathjoin(fnamecmpbuf, sizeof fnamecmpbuf, file->dirname, xname); fnamecmp = fnamecmpbuf; } else fnamecmp = xname; break; default: if (fnamecmp_type > FNAMECMP_FUZZY && fnamecmp_type-FNAMECMP_FUZZY <= basis_dir_cnt) { fnamecmp_type -= FNAMECMP_FUZZY + 1; if (file->dirname) { stringjoin(fnamecmpbuf, sizeof fnamecmpbuf, basis_dir[fnamecmp_type], "/", file->dirname, "/", xname, NULL); } else pathjoin(fnamecmpbuf, sizeof fnamecmpbuf, basis_dir[fnamecmp_type], xname); } else if (fnamecmp_type >= basis_dir_cnt) { rprintf(FERROR, "invalid basis_dir index: %d.\n", fnamecmp_type); exit_cleanup(RERR_PROTOCOL); } else pathjoin(fnamecmpbuf, sizeof fnamecmpbuf, basis_dir[fnamecmp_type], fname); fnamecmp = fnamecmpbuf; break; } if (!fnamecmp || (daemon_filter_list.head && check_filter(&daemon_filter_list, FLOG, fname, 0) < 0)) { fnamecmp = fname; fnamecmp_type = FNAMECMP_FNAME; } } else { /* Reminder: --inplace && --partial-dir are never * enabled at the same time. */ if (inplace && make_backups > 0) { if (!(fnamecmp = get_backup_name(fname))) fnamecmp = fname; else fnamecmp_type = FNAMECMP_BACKUP; } else if (partial_dir && partialptr) fnamecmp = partialptr; else fnamecmp = fname; } /* open the file */ fd1 = do_open(fnamecmp, O_RDONLY, 0); if (fd1 == -1 && protocol_version < 29) { if (fnamecmp != fname) { fnamecmp = fname; fd1 = do_open(fnamecmp, O_RDONLY, 0); } if (fd1 == -1 && basis_dir[0]) { /* pre-29 allowed only one alternate basis */ pathjoin(fnamecmpbuf, sizeof fnamecmpbuf, basis_dir[0], fname); fnamecmp = fnamecmpbuf; fd1 = do_open(fnamecmp, O_RDONLY, 0); } } updating_basis_or_equiv = inplace && (fnamecmp == fname || fnamecmp_type == FNAMECMP_BACKUP); if (fd1 == -1) { st.st_mode = 0; st.st_size = 0; } else if (do_fstat(fd1,&st) != 0) { rsyserr(FERROR_XFER, errno, "fstat %s failed", full_fname(fnamecmp)); discard_receive_data(f_in, F_LENGTH(file)); close(fd1); if (inc_recurse) send_msg_int(MSG_NO_SEND, ndx); continue; } if (fd1 != -1 && S_ISDIR(st.st_mode) && fnamecmp == fname) { /* this special handling for directories * wouldn't be necessary if robust_rename() * and the underlying robust_unlink could cope * with directories */ rprintf(FERROR_XFER, "recv_files: %s is a directory\n", full_fname(fnamecmp)); discard_receive_data(f_in, F_LENGTH(file)); close(fd1); if (inc_recurse) send_msg_int(MSG_NO_SEND, ndx); continue; } if (fd1 != -1 && !S_ISREG(st.st_mode)) { close(fd1); fd1 = -1; } /* If we're not preserving permissions, change the file-list's * mode based on the local permissions and some heuristics. */ if (!preserve_perms) { int exists = fd1 != -1; #ifdef SUPPORT_ACLS const char *dn = file->dirname ? file->dirname : "."; if (parent_dirname != dn && strcmp(parent_dirname, dn) != 0) { dflt_perms = default_perms_for_dir(dn); parent_dirname = dn; } #endif file->mode = dest_mode(file->mode, st.st_mode, dflt_perms, exists); } /* We now check to see if we are writing the file "inplace" */ if (inplace) { fd2 = do_open(fname, O_WRONLY|O_CREAT, 0600); if (fd2 == -1) { rsyserr(FERROR_XFER, errno, "open %s failed", full_fname(fname)); } else if (updating_basis_or_equiv) cleanup_set(NULL, NULL, file, fd1, fd2); } else { fd2 = open_tmpfile(fnametmp, fname, file); if (fd2 != -1) cleanup_set(fnametmp, partialptr, file, fd1, fd2); } if (fd2 == -1) { discard_receive_data(f_in, F_LENGTH(file)); if (fd1 != -1) close(fd1); if (inc_recurse) send_msg_int(MSG_NO_SEND, ndx); continue; } /* log the transfer */ if (log_before_transfer) log_item(FCLIENT, file, iflags, NULL); else if (!am_server && INFO_GTE(NAME, 1) && INFO_EQ(PROGRESS, 1)) rprintf(FINFO, "%s\n", fname); /* recv file data */ recv_ok = receive_data(f_in, fnamecmp, fd1, st.st_size, fname, fd2, F_LENGTH(file)); log_item(log_code, file, iflags, NULL); if (fd1 != -1) close(fd1); if (close(fd2) < 0) { rsyserr(FERROR, errno, "close failed on %s", full_fname(fnametmp)); exit_cleanup(RERR_FILEIO); } if ((recv_ok && (!delay_updates || !partialptr)) || inplace) { if (partialptr == fname) partialptr = NULL; if (!finish_transfer(fname, fnametmp, fnamecmp, partialptr, file, recv_ok, 1)) recv_ok = -1; else if (fnamecmp == partialptr) { do_unlink(partialptr); handle_partial_dir(partialptr, PDIR_DELETE); } } else if (keep_partial && partialptr) { if (!handle_partial_dir(partialptr, PDIR_CREATE)) { rprintf(FERROR, "Unable to create partial-dir for %s -- discarding %s.\n", local_name ? local_name : f_name(file, NULL), recv_ok ? "completed file" : "partial file"); do_unlink(fnametmp); recv_ok = -1; } else if (!finish_transfer(partialptr, fnametmp, fnamecmp, NULL, file, recv_ok, !partial_dir)) recv_ok = -1; else if (delay_updates && recv_ok) { bitbag_set_bit(delayed_bits, ndx); recv_ok = 2; } else partialptr = NULL; } else do_unlink(fnametmp); cleanup_disable(); if (read_batch) file->flags |= FLAG_FILE_SENT; switch (recv_ok) { case 2: break; case 1: if (remove_source_files || inc_recurse || (preserve_hard_links && F_IS_HLINKED(file))) send_msg_int(MSG_SUCCESS, ndx); break; case 0: { enum logcode msgtype = redoing ? FERROR_XFER : FWARNING; if (msgtype == FERROR_XFER || INFO_GTE(NAME, 1)) { char *errstr, *redostr, *keptstr; if (!(keep_partial && partialptr) && !inplace) keptstr = "discarded"; else if (partial_dir) keptstr = "put into partial-dir"; else keptstr = "retained"; if (msgtype == FERROR_XFER) { errstr = "ERROR"; redostr = ""; } else { errstr = "WARNING"; redostr = read_batch ? " (may try again)" : " (will try again)"; } rprintf(msgtype, "%s: %s failed verification -- update %s%s.\n", errstr, local_name ? f_name(file, NULL) : fname, keptstr, redostr); } if (!redoing) { if (read_batch) flist_ndx_push(&batch_redo_list, ndx); send_msg_int(MSG_REDO, ndx); file->flags |= FLAG_FILE_SENT; } else if (inc_recurse) send_msg_int(MSG_NO_SEND, ndx); break; } case -1: if (inc_recurse) send_msg_int(MSG_NO_SEND, ndx); break; } } if (make_backups < 0) make_backups = -make_backups; if (phase == 2 && delay_updates) /* for protocol_version < 29 */ handle_delayed_updates(local_name); if (DEBUG_GTE(RECV, 1)) rprintf(FINFO,"recv_files finished\n"); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-862'], 'message': 'Check fname in recv_files sooner.'</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 yajl_string_decode(yajl_buf buf, const unsigned char * str, unsigned int len) { unsigned int beg = 0; unsigned int end = 0; while (end < len) { if (str[end] == '\\') { char utf8Buf[5]; const char * unescaped = "?"; yajl_buf_append(buf, str + beg, end - beg); switch (str[++end]) { case 'r': unescaped = "\r"; break; case 'n': unescaped = "\n"; break; case '\\': unescaped = "\\"; break; case '/': unescaped = "/"; break; case '"': unescaped = "\""; break; case 'f': unescaped = "\f"; break; case 'b': unescaped = "\b"; break; case 't': unescaped = "\t"; break; case 'u': { unsigned int codepoint = 0; hexToDigit(&codepoint, str + ++end); end+=3; /* check if this is a surrogate */ if ((codepoint & 0xFC00) == 0xD800) { end++; if (str[end] == '\\' && str[end + 1] == 'u') { unsigned int surrogate = 0; hexToDigit(&surrogate, str + end + 2); codepoint = (((codepoint & 0x3F) << 10) | ((((codepoint >> 6) & 0xF) + 1) << 16) | (surrogate & 0x3FF)); end += 5; } else { unescaped = "?"; break; } } Utf32toUtf8(codepoint, utf8Buf); unescaped = utf8Buf; if (codepoint == 0) { yajl_buf_append(buf, unescaped, 1); beg = ++end; continue; } break; } default: assert("this should never happen" == NULL); } yajl_buf_append(buf, unescaped, (unsigned int)strlen(unescaped)); beg = ++end; } else { end++; } } yajl_buf_append(buf, str + beg, end - beg); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-134'], 'message': 'Don't advance our end pointer until we've checked we have enough buffer left and have peeked ahead to see that a unicode escape is approaching. Thanks @kivikakk for helping me track down the actual bug here!'</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 nfnl_cthelper_get(struct net *net, struct sock *nfnl, struct sk_buff *skb, const struct nlmsghdr *nlh, const struct nlattr * const tb[], struct netlink_ext_ack *extack) { int ret = -ENOENT; struct nf_conntrack_helper *cur; struct sk_buff *skb2; char *helper_name = NULL; struct nf_conntrack_tuple tuple; struct nfnl_cthelper *nlcth; bool tuple_set = false; if (nlh->nlmsg_flags & NLM_F_DUMP) { struct netlink_dump_control c = { .dump = nfnl_cthelper_dump_table, }; return netlink_dump_start(nfnl, skb, nlh, &c); } if (tb[NFCTH_NAME]) helper_name = nla_data(tb[NFCTH_NAME]); if (tb[NFCTH_TUPLE]) { ret = nfnl_cthelper_parse_tuple(&tuple, tb[NFCTH_TUPLE]); if (ret < 0) return ret; tuple_set = true; } list_for_each_entry(nlcth, &nfnl_cthelper_list, list) { cur = &nlcth->helper; if (helper_name && strncmp(cur->name, helper_name, NF_CT_HELPER_NAME_LEN)) continue; if (tuple_set && (tuple.src.l3num != cur->tuple.src.l3num || tuple.dst.protonum != cur->tuple.dst.protonum)) continue; skb2 = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL); if (skb2 == NULL) { ret = -ENOMEM; break; } ret = nfnl_cthelper_fill_info(skb2, NETLINK_CB(skb).portid, nlh->nlmsg_seq, NFNL_MSG_TYPE(nlh->nlmsg_type), NFNL_MSG_CTHELPER_NEW, cur); if (ret <= 0) { kfree_skb(skb2); break; } ret = netlink_unicast(nfnl, skb2, NETLINK_CB(skb).portid, MSG_DONTWAIT); if (ret > 0) ret = 0; /* this avoids a loop in nfnetlink. */ return ret == -EAGAIN ? -ENOBUFS : ret; } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-862'], 'message': 'netfilter: nfnetlink_cthelper: Add missing permission checks The capability check in nfnetlink_rcv() verifies that the caller has CAP_NET_ADMIN in the namespace that "owns" the netlink socket. However, nfnl_cthelper_list is shared by all net namespaces on the system. An unprivileged user can create user and net namespaces in which he holds CAP_NET_ADMIN to bypass the netlink_net_capable() check: $ nfct helper list nfct v1.4.4: netlink error: Operation not permitted $ vpnns -- nfct helper list { .name = ftp, .queuenum = 0, .l3protonum = 2, .l4protonum = 6, .priv_data_len = 24, .status = enabled, }; Add capable() checks in nfnetlink_cthelper, as this is cleaner than trying to generalize the solution. Signed-off-by: Kevin Cernekee <cernekee@chromium.org> Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>'</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 __rds_rdma_map(struct rds_sock *rs, struct rds_get_mr_args *args, u64 *cookie_ret, struct rds_mr **mr_ret) { struct rds_mr *mr = NULL, *found; unsigned int nr_pages; struct page **pages = NULL; struct scatterlist *sg; void *trans_private; unsigned long flags; rds_rdma_cookie_t cookie; unsigned int nents; long i; int ret; if (rs->rs_bound_addr == 0) { ret = -ENOTCONN; /* XXX not a great errno */ goto out; } if (!rs->rs_transport->get_mr) { ret = -EOPNOTSUPP; goto out; } nr_pages = rds_pages_in_vec(&args->vec); if (nr_pages == 0) { ret = -EINVAL; goto out; } /* Restrict the size of mr irrespective of underlying transport * To account for unaligned mr regions, subtract one from nr_pages */ if ((nr_pages - 1) > (RDS_MAX_MSG_SIZE >> PAGE_SHIFT)) { ret = -EMSGSIZE; goto out; } rdsdebug("RDS: get_mr addr %llx len %llu nr_pages %u\n", args->vec.addr, args->vec.bytes, nr_pages); /* XXX clamp nr_pages to limit the size of this alloc? */ pages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL); if (!pages) { ret = -ENOMEM; goto out; } mr = kzalloc(sizeof(struct rds_mr), GFP_KERNEL); if (!mr) { ret = -ENOMEM; goto out; } refcount_set(&mr->r_refcount, 1); RB_CLEAR_NODE(&mr->r_rb_node); mr->r_trans = rs->rs_transport; mr->r_sock = rs; if (args->flags & RDS_RDMA_USE_ONCE) mr->r_use_once = 1; if (args->flags & RDS_RDMA_INVALIDATE) mr->r_invalidate = 1; if (args->flags & RDS_RDMA_READWRITE) mr->r_write = 1; /* * Pin the pages that make up the user buffer and transfer the page * pointers to the mr's sg array. We check to see if we've mapped * the whole region after transferring the partial page references * to the sg array so that we can have one page ref cleanup path. * * For now we have no flag that tells us whether the mapping is * r/o or r/w. We need to assume r/w, or we'll do a lot of RDMA to * the zero page. */ ret = rds_pin_pages(args->vec.addr, nr_pages, pages, 1); if (ret < 0) goto out; nents = ret; sg = kcalloc(nents, sizeof(*sg), GFP_KERNEL); if (!sg) { ret = -ENOMEM; goto out; } WARN_ON(!nents); sg_init_table(sg, nents); /* Stick all pages into the scatterlist */ for (i = 0 ; i < nents; i++) sg_set_page(&sg[i], pages[i], PAGE_SIZE, 0); rdsdebug("RDS: trans_private nents is %u\n", nents); /* Obtain a transport specific MR. If this succeeds, the * s/g list is now owned by the MR. * Note that dma_map() implies that pending writes are * flushed to RAM, so no dma_sync is needed here. */ trans_private = rs->rs_transport->get_mr(sg, nents, rs, &mr->r_key); if (IS_ERR(trans_private)) { for (i = 0 ; i < nents; i++) put_page(sg_page(&sg[i])); kfree(sg); ret = PTR_ERR(trans_private); goto out; } mr->r_trans_private = trans_private; rdsdebug("RDS: get_mr put_user key is %x cookie_addr %p\n", mr->r_key, (void *)(unsigned long) args->cookie_addr); /* The user may pass us an unaligned address, but we can only * map page aligned regions. So we keep the offset, and build * a 64bit cookie containing <R_Key, offset> and pass that * around. */ cookie = rds_rdma_make_cookie(mr->r_key, args->vec.addr & ~PAGE_MASK); if (cookie_ret) *cookie_ret = cookie; if (args->cookie_addr && put_user(cookie, (u64 __user *)(unsigned long) args->cookie_addr)) { ret = -EFAULT; goto out; } /* Inserting the new MR into the rbtree bumps its * reference count. */ spin_lock_irqsave(&rs->rs_rdma_lock, flags); found = rds_mr_tree_walk(&rs->rs_rdma_keys, mr->r_key, mr); spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); BUG_ON(found && found != mr); rdsdebug("RDS: get_mr key is %x\n", mr->r_key); if (mr_ret) { refcount_inc(&mr->r_refcount); *mr_ret = mr; } ret = 0; out: kfree(pages); if (mr) rds_mr_put(mr); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'rds: Fix NULL pointer dereference in __rds_rdma_map This is a fix for syzkaller719569, where memory registration was attempted without any underlying transport being loaded. Analysis of the case reveals that it is the setsockopt() RDS_GET_MR (2) and RDS_GET_MR_FOR_DEST (7) that are vulnerable. Here is an example stack trace when the bug is hit: BUG: unable to handle kernel NULL pointer dereference at 00000000000000c0 IP: __rds_rdma_map+0x36/0x440 [rds] PGD 2f93d03067 P4D 2f93d03067 PUD 2f93d02067 PMD 0 Oops: 0000 [#1] SMP Modules linked in: bridge stp llc tun rpcsec_gss_krb5 nfsv4 dns_resolver nfs fscache rds binfmt_misc sb_edac intel_powerclamp coretemp kvm_intel kvm irqbypass crct10dif_pclmul c rc32_pclmul ghash_clmulni_intel pcbc aesni_intel crypto_simd glue_helper cryptd iTCO_wdt mei_me sg iTCO_vendor_support ipmi_si mei ipmi_devintf nfsd shpchp pcspkr i2c_i801 ioatd ma ipmi_msghandler wmi lpc_ich mfd_core auth_rpcgss nfs_acl lockd grace sunrpc ip_tables ext4 mbcache jbd2 mgag200 i2c_algo_bit drm_kms_helper ixgbe syscopyarea ahci sysfillrect sysimgblt libahci mdio fb_sys_fops ttm ptp libata sd_mod mlx4_core drm crc32c_intel pps_core megaraid_sas i2c_core dca dm_mirror dm_region_hash dm_log dm_mod CPU: 48 PID: 45787 Comm: repro_set2 Not tainted 4.14.2-3.el7uek.x86_64 #2 Hardware name: Oracle Corporation ORACLE SERVER X5-2L/ASM,MOBO TRAY,2U, BIOS 31110000 03/03/2017 task: ffff882f9190db00 task.stack: ffffc9002b994000 RIP: 0010:__rds_rdma_map+0x36/0x440 [rds] RSP: 0018:ffffc9002b997df0 EFLAGS: 00010202 RAX: 0000000000000000 RBX: ffff882fa2182580 RCX: 0000000000000000 RDX: 0000000000000000 RSI: ffffc9002b997e40 RDI: ffff882fa2182580 RBP: ffffc9002b997e30 R08: 0000000000000000 R09: 0000000000000002 R10: ffff885fb29e3838 R11: 0000000000000000 R12: ffff882fa2182580 R13: ffff882fa2182580 R14: 0000000000000002 R15: 0000000020000ffc FS: 00007fbffa20b700(0000) GS:ffff882fbfb80000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: 00000000000000c0 CR3: 0000002f98a66006 CR4: 00000000001606e0 Call Trace: rds_get_mr+0x56/0x80 [rds] rds_setsockopt+0x172/0x340 [rds] ? __fget_light+0x25/0x60 ? __fdget+0x13/0x20 SyS_setsockopt+0x80/0xe0 do_syscall_64+0x67/0x1b0 entry_SYSCALL64_slow_path+0x25/0x25 RIP: 0033:0x7fbff9b117f9 RSP: 002b:00007fbffa20aed8 EFLAGS: 00000293 ORIG_RAX: 0000000000000036 RAX: ffffffffffffffda RBX: 00000000000c84a4 RCX: 00007fbff9b117f9 RDX: 0000000000000002 RSI: 0000400000000114 RDI: 000000000000109b RBP: 00007fbffa20af10 R08: 0000000000000020 R09: 00007fbff9dd7860 R10: 0000000020000ffc R11: 0000000000000293 R12: 0000000000000000 R13: 00007fbffa20b9c0 R14: 00007fbffa20b700 R15: 0000000000000021 Code: 41 56 41 55 49 89 fd 41 54 53 48 83 ec 18 8b 87 f0 02 00 00 48 89 55 d0 48 89 4d c8 85 c0 0f 84 2d 03 00 00 48 8b 87 00 03 00 00 <48> 83 b8 c0 00 00 00 00 0f 84 25 03 00 0 0 48 8b 06 48 8b 56 08 The fix is to check the existence of an underlying transport in __rds_rdma_map(). Signed-off-by: Håkon Bugge <haakon.bugge@oracle.com> Reported-by: syzbot <syzkaller@googlegroups.com> Acked-by: Santosh Shilimkar <santosh.shilimkar@oracle.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xcf_load_stream (Gimp *gimp, GInputStream *input, GFile *input_file, GimpProgress *progress, GError **error) { XcfInfo info = { 0, }; const gchar *filename; GimpImage *image = NULL; gchar id[14]; gboolean success; g_return_val_if_fail (GIMP_IS_GIMP (gimp), NULL); g_return_val_if_fail (G_IS_INPUT_STREAM (input), NULL); g_return_val_if_fail (input_file == NULL || G_IS_FILE (input_file), NULL); g_return_val_if_fail (progress == NULL || GIMP_IS_PROGRESS (progress), NULL); g_return_val_if_fail (error == NULL || *error == NULL, NULL); if (input_file) filename = gimp_file_get_utf8_name (input_file); else filename = _("Memory Stream"); info.gimp = gimp; info.input = input; info.seekable = G_SEEKABLE (input); info.bytes_per_offset = 4; info.progress = progress; info.file = input_file; info.compression = COMPRESS_NONE; if (progress) gimp_progress_start (progress, FALSE, _("Opening '%s'"), filename); success = TRUE; xcf_read_int8 (&info, (guint8 *) id, 14); if (! g_str_has_prefix (id, "gimp xcf ")) { success = FALSE; } else if (strcmp (id + 9, "file") == 0) { info.file_version = 0; } else if (id[9] == 'v') { info.file_version = atoi (id + 10); } else { success = FALSE; } if (info.file_version >= 11) info.bytes_per_offset = 8; if (success) { if (info.file_version >= 0 && info.file_version < G_N_ELEMENTS (xcf_loaders)) { image = (*(xcf_loaders[info.file_version])) (gimp, &info, error); if (! image) success = FALSE; g_input_stream_close (info.input, NULL, NULL); } else { g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("XCF error: unsupported XCF file version %d " "encountered"), info.file_version); success = FALSE; } } if (progress) gimp_progress_end (progress); return image; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': '790783 - buffer overread in XCF parser if version field... ...has no null terminator Check for the presence of '\0' before using atoi() on the version string. Patch slightly modified (mitch).'</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 fli_read_lc(FILE *f, s_fli_header *fli_header, unsigned char *old_framebuf, unsigned char *framebuf) { unsigned short yc, firstline, numline; unsigned char *pos; memcpy(framebuf, old_framebuf, fli_header->width * fli_header->height); firstline = fli_read_short(f); numline = fli_read_short(f); for (yc=0; yc < numline; yc++) { unsigned short xc, pc, pcnt; pc=fli_read_char(f); xc=0; pos=framebuf+(fli_header->width * (firstline+yc)); for (pcnt=pc; pcnt>0; pcnt--) { unsigned short ps,skip; skip=fli_read_char(f); ps=fli_read_char(f); xc+=skip; if (ps & 0x80) { unsigned char val; ps=-(signed char)ps; val=fli_read_char(f); memset(&(pos[xc]), val, ps); xc+=ps; } else { fread(&(pos[xc]), ps, 1, f); xc+=ps; } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Bug 739133 - (CVE-2017-17785) Heap overflow while parsing FLI files. It is possible to trigger a heap overflow while parsing FLI files. The RLE decoder is vulnerable to out of boundary writes due to lack of boundary checks. The variable "framebuf" points to a memory area which was allocated with fli_header->width * fli_header->height bytes. The RLE decoder therefore must never write beyond that limit. If an illegal frame is detected, the parser won't stop, which means that the next valid sequence is properly parsed again. This should allow GIMP to parse FLI files as good as possible even if they are broken by an attacker or by accident. While at it, I changed the variable xc to be of type size_t, because the multiplication of width and height could overflow a 16 bit type. Signed-off-by: Tobias Stoeckmann <tobias@stoeckmann.org>'</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 WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception) { char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; Image *image; ImageInfo *image_info; char s[2]; const char *name, *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, /* ping_exclude_EXIF, */ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, /* ping_exclude_iTXt, */ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, /* ping_exclude_tRNS, */ ping_exclude_caNv, ping_exclude_zCCP, /* hex-encoded iCCP */ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; PNGErrorInfo error_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter WriteOnePNGImage()"); image = CloneImage(IMimage,0,0,MagickFalse,exception); if (image == (Image *) NULL) return(MagickFalse); image_info=(ImageInfo *) CloneImageInfo(IMimage_info); /* Define these outside of the following "if logging()" block so they will * show in debuggers. */ *im_vers='\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MagickPathExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MagickPathExtent); *libpng_vers='\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " IM version = %s", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Libpng version = %s", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " running with %s", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Zlib version = %s", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " running with %s", zlib_runv); } } /* Initialize some stuff */ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; /* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; /* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */ ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; /* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some "known invalid sRGB profiles". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. */ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { char *name; const StringInfo *profile; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile (potentially sRGB)", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " with crc=%8x",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " It is sRGB with rendering intent = %s", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got %lu-byte ICC profile not recognized as sRGB", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=UndefinedClass"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=DirectClass"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=PseudoClass"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? " image->taint=MagickTrue": " image->taint=MagickFalse"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->gamma=%g", image->gamma); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image,exception); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if (image->storage_class != PseudoClass && image->colormap != NULL) { /* Free the bogus colormap; it can cause trouble later */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Freeing bogus colormap"); (void) RelinquishMagickMemory(image->colormap); image->colormap=NULL; } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); /* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. */ if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image,exception); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reducing PNG bit depth to 8 since this is a Q8 build."); image->depth=8; } #endif /* Respect the -depth option */ if (image->depth < 4) { register Quantum *r; if (image->depth > 2) { /* Scale to 4-bit */ LBR04PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBO(image->colormap[i]); } } } else if (image->depth > 1) { /* Scale to 2-bit */ LBR02PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBO(image->colormap[i]); } } } else { /* Scale to 1-bit */ LBR01PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBO(image->colormap[i]); } } } } /* To do: set to next higher multiple of 8 */ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy */ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; number_opaque = (int) image->colors; number_transparent = 0; number_semitransparent = 0; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->alpha_trait == UndefinedPixelTrait))) { /* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. */ if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; if (image->alpha_trait != UndefinedPixelTrait) { number_transparent = 2; number_semitransparent = 1; } } if (mng_info->write_png_colortype < 7) { /* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. */ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; for (j=0; j<6; j++) { /* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->alpha_trait is MagickFalse, we ignore the alpha channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. */ int n; PixelInfo opaque[260], semitransparent[260], transparent[260]; register const Quantum *s; register Quantum *q, *r; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Enter BUILD_PALETTE:"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->columns=%.20g",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->rows=%.20g",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->alpha_trait=%.20g",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Original colormap:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,alpha)"); for (i=0; i < 256; i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " (zero means unknown)"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Regenerate the colormap"); } image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait == UndefinedPixelTrait || GetPixelAlpha(image,q) == OpaqueAlpha) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelInfoPixel(image, q, opaque); opaque[0].alpha=OpaqueAlpha; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (Magick_png_color_equal(image,q,opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelInfoPixel(image, q, opaque+i); opaque[i].alpha=OpaqueAlpha; } } } else if (GetPixelAlpha(image,q) == TransparentAlpha) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelInfoPixel(image, q, transparent); ping_trans_color.red=(unsigned short) GetPixelRed(image,q); ping_trans_color.green=(unsigned short) GetPixelGreen(image,q); ping_trans_color.blue=(unsigned short) GetPixelBlue(image,q); ping_trans_color.gray=(unsigned short) GetPixelGray(image,q); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (Magick_png_color_equal(image,q,transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelInfoPixel(image,q,transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelInfoPixel(image,q,semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (Magick_png_color_equal(image,q,semitransparent+i) && GetPixelAlpha(image,q) == semitransparent[i].alpha) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelInfoPixel(image, q, semitransparent+i); } } } q+=GetPixelChannels(image); } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { /* Add the background color to the palette, if it * isn't already there. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Check colormap for background (%d,%d,%d)", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } for (i=0; i<number_opaque; i++) { if (opaque[i].red == image->background_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (number_opaque < 259 && i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d",(int) i); } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in the colormap to add background color"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has more than 256 colors"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has %d colors",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) /* We won't need this info */ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "incompatible colorspace"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,s) != GetPixelGreen(image,s) || GetPixelRed(image,s) != GetPixelBlue(image,s)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } s+=GetPixelChannels(image); } if (ping_have_color != MagickFalse) break; /* Worst case is black-and-white; we are looking at every * pixel twice. */ if (ping_have_non_bw == MagickFalse) { s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,s) != 0 && GetPixelRed(image,s) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } s+=GetPixelChannels(image); } } } } } if (image_colors < 257) { PixelInfo colormap[260]; /* * Initialize image colormap. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Sort the new colormap"); /* Sort palette, transparent first */; n = 0; for (i=0; i<number_transparent; i++) colormap[n++] = transparent[i]; for (i=0; i<number_semitransparent; i++) colormap[n++] = semitransparent[i]; for (i=0; i<number_opaque; i++) colormap[n++] = opaque[i]; ping_background.index += (number_transparent + number_semitransparent); /* image_colors < 257; search the colormap instead of the pixels * to get ping_have_color and ping_have_non_bw */ for (i=0; i<n; i++) { if (ping_have_color == MagickFalse) { if (colormap[i].red != colormap[i].green || colormap[i].red != colormap[i].blue) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } } if (ping_have_non_bw == MagickFalse) { if (colormap[i].red != 0 && colormap[i].red != QuantumRange) ping_have_non_bw=MagickTrue; } } if ((mng_info->ping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_colors (%d) and n (%d) don't match", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireImageColormap"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors,exception) == MagickFalse) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d (%d)", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Update the pixel indexes"); } /* Sync the pixel indices with the new colormap */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->alpha_trait == UndefinedPixelTrait || image->colormap[i].alpha == GetPixelAlpha(image,q)) && image->colormap[i].red == GetPixelRed(image,q) && image->colormap[i].green == GetPixelGreen(image,q) && image->colormap[i].blue == GetPixelBlue(image,q)) { SetPixelIndex(image,i,q); break; } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,alpha)"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent = %d", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent > 256"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque = %d", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque > 256"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent = %d", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent > 256"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are black or white"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are gray"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " At least one pixel or the background is non-gray"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Exit BUILD_PALETTE:"); } if (mng_info->write_png8 == MagickFalse) break; /* Make any reductions necessary for the PNG8 format */ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; /* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. */ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Thresholding the alpha channel to binary"); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) < OpaqueAlpha/2) { SetPixelViaPixelInfo(image,&image->background_color,r); SetPixelAlpha(image,TransparentAlpha,r); } else SetPixelAlpha(image,OpaqueAlpha,r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; i<image_colors; i++) image->colormap[i].alpha = (image->colormap[i].alpha > TransparentAlpha/2 ? TransparentAlpha : OpaqueAlpha); } continue; } /* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. */ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 4-4-4"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 4-4-4"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR04PixelRGB(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 4-4-4"); for (i=0; i<image_colors; i++) { LBR04PacketRGB(image->colormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-3"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-3-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR03RGB(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-3-1"); for (i=0; i<image_colors; i++) { LBR03PacketRGB(image->colormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-2"); tried_332 = MagickTrue; /* Red and green were already done so we only quantize the blue * channel */ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR02PixelBlue(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-2-1"); for (i=0; i<image_colors; i++) { LBR02PacketBlue(image->colormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { /* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red background colors to 3-3-2-1"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(image,r)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(image,r)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(image,r)) == 0x00 && GetPixelAlpha(image,r) == OpaqueAlpha) { SetPixelRed(image,ScaleCharToQuantum(0x24),r); } r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; i<image_colors; i++) { if (ScaleQuantumToChar(image->colormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } /* END OF BUILD_PALETTE */ /* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. */ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } /* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. */ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { register const Quantum *q; for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) != TransparentAlpha && (unsigned short) GetPixelRed(image,q) == ping_trans_color.red && (unsigned short) GetPixelGreen(image,q) == ping_trans_color.green && (unsigned short) GetPixelBlue(image,q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q+=GetPixelChannels(image); } if (ping_have_cheap_transparency == MagickFalse) break; } } else { /* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. */ if (image_colors > 1) for (i=1; i<image_colors; i++) if (image->colormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is not possible."); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is possible."); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->alpha_trait != UndefinedPixelTrait ? MagickTrue : MagickFalse; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { image_info=DestroyImageInfo(image_info); image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "Cannot write PNG8 or color-type 3; colormap is NULL", "`%s'",IMimage->filename); return(MagickFalse); } /* Allocate the PNG structures */ #ifdef PNG_USER_MEM_SUPPORTED error_info.image=image; error_info.exception=exception; ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { /* PNG write failed. */ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf("PNG write has failed.\n"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); return(MagickFalse); } /* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. */ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED /* Allow benign errors */ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED /* Reject images with too many rows or columns */ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif /* PNG_SET_USER_LIMITS_SUPPORTED */ /* Prepare PNG for writing. */ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED /* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK */ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; /* Adjust requested depth to next higher valid depth if necessary */ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " width=%.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " height=%.20g",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_matte=%.20g",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative ping_bit_depth=%.20g",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->resolution.x != 0) && (image->resolution.y != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->resolution.x+0.5)/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->resolution.y+0.5)/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->resolution.x; ping_pHYs_y_resolution=(png_uint_32) image->resolution.y; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (1)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth=%d",ping_bit_depth); } ping_have_bKGD = MagickTrue; } /* Select the color type. */ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { /* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. */ number_colors=image_colors; ping_have_tRNS=MagickFalse; /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors (%d)", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 " %3ld (%3d,%3d,%3d)", #else " %5ld (%5d,%5d,%5d)", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { /* Identify which colormap entry is transparent. */ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { /* * Identify which colormap entry is the background color. */ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); } } } /* end of write_png8 */ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else /* mng_info->write_pngNN not specified */ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG colortype %d was specified:",(int) ping_color_type); } else /* write_png_colortype not specified */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selecting PNG colortype:"); ping_color_type=(png_byte) ((matte != MagickFalse)? PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } if (image_info->type == TrueColorAlphaType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } if (image_info->type == PaletteType || image_info->type == PaletteAlphaType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (mng_info->write_png_colortype == 0 && image_info->type == UndefinedType) { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selected PNG colortype=%d",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->alpha_trait == UndefinedPixelTrait && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { /* DO SOMETHING */ png_error(ping,"image has 0 colors"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %.20g",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG bit depth: %d",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG color type: %s (%.20g)", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_info->type: %.20g",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_depth: %.20g",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth: %.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth: %.20g",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } /* * Determine if there is any transparent color. */ if (number_transparent + number_semitransparent == 0) { /* No transparent pixels are present. Change 4 or 6 to 0 or 2. */ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(GetPixelInfoIntensity(image, image->colormap)) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { /* * Determine if there is one and only one transparent color * and if so if it is fully transparent. */ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (0)"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { /* Check if grayscale is reducible */ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green= ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors", number_colors); ping_have_PLTE=MagickTrue; } /* color_type is PNG_COLOR_TYPE_PALETTE */ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { /* * Set up trans_colors array. */ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (1)"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) ScaleQuantumToChar(image->colormap[i].alpha); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color from (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; /* Adjust background and transparency samples in sub-8-bit grayscale files. */ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval/65535.)* (ScaleQuantumToShort(((GetPixelInfoIntensity(image, &image->background_color))) +.5))); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (2)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color.gray from %d", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to %d", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { /* Identify which colormap entry is the background color. */ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk with index=%d",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background =(%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else /* Can't happen */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in PLTE to add bKGD color"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color type: %s (%d)", PngColorTypeToString(ping_color_type), ping_color_type); /* Initialize compression level and filtering. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up deflate compression"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression buffer size: 32768"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression mem level: 9"); png_set_compression_mem_level(ping, 9); /* Untangle the "-quality" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type "none" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: "LOCO" filtering (intrapixel differing) if writing a MNG, otherwise "none". Did not work in IM-6.7.0-9 and earlier because of a missing "else". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This will be addressed soon in a release that accomodates "-define png:compression-strategy", etc. */ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression level: %d", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression strategy: %d", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up filtering"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: ADAPTIVE"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: NONE"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: %d", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); /* Bail out if cannot meet defined png:bit-depth or png:color-type */ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image has transparency but tRNS chunk was excluded"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth=%u, Computed depth=%u", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type=%u, Computed color type=%u", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, "Cannot write image with defined png:bit-depth or png:color-type."); } if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait) { /* Add an opaque matte channel */ image->alpha_trait = BlendPixelTrait; (void) SetImageAlpha(image,OpaqueAlpha,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Added an opaque matte channel"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting ping_have_tRNS=MagickTrue."); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG header chunks"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } /* Only write the iCCP chunk if we are not writing the sRGB chunk. */ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { ping_have_iCCP = MagickTrue; if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up iCCP chunk"); png_set_iCCP(ping,ping_info,(png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); } else { /* Do not write hex-encoded ICC chunk */ name=GetNextImageProfile(image); continue; } } #endif /* WRITE_iCCP */ if (LocaleCompare(name,"exif") == 0) { /* Do not write hex-encoded ICC chunk; we will write it later as an eXIf chunk */ name=GetNextImageProfile(image); continue; } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up zTXt chunk with uuencoded %s profile", name); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); } name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { /* Note image rendering intent. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up sRGB chunk"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { /* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up gAMA chunk"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { /* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. */ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up cHRM chunk"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background color = (%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " index = %d, gray=%d", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_resolution=%lu", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " y_resolution=%lu", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " unit_type=%lu", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,"png:tIME"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,"png:tIME",exception); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reset tIME in tainted image"); timestamp=GetImageProperty(image,"date:modify",exception); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp,exception); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) == MagickFalse) png_error(ping,"WriteBlob Failed"); ping_have_blob=MagickTrue; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Calling png_set_tRNS with num_trans=%d",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tRNS color =(%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } png_write_info(ping,ping_info); /* write orNT if image->orientation is defined */ if (image->orientation != UndefinedOrientation) { unsigned char chunk[6]; (void) WriteBlobMSBULong(image,1L); /* data length=1 */ PNGType(chunk,mng_orNT); LogPNGChunk(logging,mng_orNT,1L); /* PNG uses Exif orientation values */ chunk[4]=Magick_Orientation_to_Exif_Orientation(image->orientation); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } ping_wrote_caNv = MagickFalse; /* write caNv chunk */ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); /* data length=8 */ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up oFFs chunk with x=%d, y=%d, units=0", (int) image->page.x, (int) image->page.y); } } #endif #if (PNG_LIBPNG_VER == 10206) /* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); /* Allocate memory. */ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocating %.20g bytes of memory for pixels",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,"Allocation of memory for pixels failed"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Initialize image scanlines. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,"Memory allocation for quantum_info failed"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse) { /* Palette, Bilevel, or Opaque Monochrome */ register const Quantum *p; SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { /* Convert PseudoClass image to a PNG monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (0)"); p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (mng_info->IsPalette) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE && mng_info->write_png_depth && mng_info->write_png_depth != old_bit_depth) { /* Undo pixel scaling */ for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) (*(ping_pixels+i) >> (8-old_bit_depth)); } } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); } if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (1)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else /* Not Palette, Bilevel, or Opaque Monochrome */ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY PNG pixels (2)"); } else /* PNG_COLOR_TYPE_GRAY_ALPHA */ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (2)"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (2)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (3)"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (3)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else /* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) */ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is not GRAY or GRAY_ALPHA",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA", pass); p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (4)"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of non-gray pixels (4)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_pixels[0]=%d,ping_pixels[1]=%d", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Wrote PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Width: %.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Height: %.20g",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth: %d",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG bit-depth written: %d",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type: %d",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color-type written: %d",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG Interlace method: %d",ping_interlace_method); } /* Generate text chunks after IDAT. */ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property,exception); /* Don't write any "png:" or "jpeg:" properties; those are just for * "identify" or for passing through to another JPEG */ if ((LocaleNCompare(property,"png:",4) != 0 && LocaleNCompare(property,"jpeg:",5) != 0) && /* Suppress density and units if we wrote a pHYs chunk */ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,"density") != 0 || LocaleCompare(property,"units") != 0) && /* Suppress the IM-generated Date:create and Date:modify */ (ping_exclude_date == MagickFalse || LocaleNCompare(property, "Date:",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up text chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " keyword: '%s'",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } /* write eXIf profile */ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { char *name; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { if (LocaleCompare(name,"exif") == 0) { const StringInfo *profile; profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Have eXIf profile"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); PNGType(chunk,mng_eXIf); if (length < 7) { ping_profile=DestroyStringInfo(ping_profile); break; /* otherwise crashes */ } if (*data == 'E' && *(data+1) == 'x' && *(data+2) == 'i' && *(data+3) == 'f' && *(data+4) == '\0' && *(data+5) == '\0') { /* skip the "Exif\0\0" JFIF Exif Header ID */ length -= 6; data += 6; } LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data, (uInt) length)); ping_profile=DestroyStringInfo(ping_profile); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG end info"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; /* Write FRAM 4 with clipping boundaries followed by FRAM 1. */ (void) WriteBlobMSBULong(image,27L); /* data length=27 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; /* frame name separator (no name) */ chunk[6]=1; /* flag for changing delay, for next frame only */ chunk[7]=0; /* flag for changing frame timeout */ chunk[8]=1; /* flag for changing frame clipping for next frame */ chunk[9]=0; /* flag for changing frame sync_id */ PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */ chunk[14]=0; /* clipping boundaries delta type */ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, "Cannot convert GIF with disposal method 3 to MNG-LC"); /* Free PNG resources. */ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); /* Store bit depth actually written */ s[0]=(char) ping_bit_depth; s[1]='\0'; (void) SetImageProperty(IMimage,"png:bit-depth-written",s,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteOnePNGImage()"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif /* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. */ return(MagickTrue); /* End write one PNG image */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/902'</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 cirrus_invalidate_region(CirrusVGAState * s, int off_begin, int off_pitch, int bytesperline, int lines) { int y; int off_cur; int off_cur_end; for (y = 0; y < lines; y++) { off_cur = off_begin; off_cur_end = (off_cur + bytesperline) & s->cirrus_addr_mask; memory_region_set_dirty(&s->vga.vram, off_cur, off_cur_end - off_cur); off_begin += off_pitch; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'cirrus: handle negative pitch in cirrus_invalidate_region() cirrus_invalidate_region() calls memory_region_set_dirty() on a per-line basis, always ranging from off_begin to off_begin+bytesperline. With a negative pitch off_begin marks the top most used address and thus we need to do an initial shift backwards by a line for negative pitches of backward blits, otherwise the first iteration covers the line going from the start offset forwards instead of backwards. Additionally since the start address is inclusive, if we shift by a full `bytesperline` we move to the first address *not* included in the blit, so we only shift by one less than bytesperline. Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com> Message-id: 1485352137-29367-1-git-send-email-w.bumiller@proxmox.com [ kraxel: codestyle fixes ] Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</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 ZipTest::testDecompressZip64() { std::map<std::string, Poco::UInt64> files; files["data1.bin"] = static_cast<Poco::UInt64>(KB)*4096+1; files["data2.bin"] = static_cast<Poco::UInt64>(KB)*16; files["data3.bin"] = static_cast<Poco::UInt64>(KB)*4096-1; for(std::map<std::string, Poco::UInt64>::const_iterator it = files.begin(); it != files.end(); it++) { Poco::File file(it->first); if(file.exists()) file.remove(); } std::ifstream in("zip64.zip", std::ios::binary); Decompress c(in, "."); c.decompressAllFiles(); for(std::map<std::string, Poco::UInt64>::const_iterator it = files.begin(); it != files.end(); it++) { verifyDataFile(it->first, it->second); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'merge zip entry absolute path vulnerability fix (#1968) from develop'</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 ZipTest::testDecompress() { std::string testFile = getTestFile("data", "test.zip"); std::ifstream inp(testFile.c_str(), std::ios::binary); assert (inp.good()); Decompress dec(inp, Poco::Path()); dec.EError += Poco::Delegate<ZipTest, std::pair<const Poco::Zip::ZipLocalFileHeader, const std::string> >(this, &ZipTest::onDecompressError); dec.decompressAllFiles(); dec.EError -= Poco::Delegate<ZipTest, std::pair<const Poco::Zip::ZipLocalFileHeader, const std::string> >(this, &ZipTest::onDecompressError); assert (_errCnt == 0); assert (!dec.mapping().empty()); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'merge zip entry absolute path vulnerability fix (#1968) from develop'</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 struct snd_seq_client *seq_create_client1(int client_index, int poolsize) { unsigned long flags; int c; struct snd_seq_client *client; /* init client data */ client = kzalloc(sizeof(*client), GFP_KERNEL); if (client == NULL) return NULL; client->pool = snd_seq_pool_new(poolsize); if (client->pool == NULL) { kfree(client); return NULL; } client->type = NO_CLIENT; snd_use_lock_init(&client->use_lock); rwlock_init(&client->ports_lock); mutex_init(&client->ports_mutex); INIT_LIST_HEAD(&client->ports_list_head); /* find free slot in the client table */ spin_lock_irqsave(&clients_lock, flags); if (client_index < 0) { for (c = SNDRV_SEQ_DYNAMIC_CLIENTS_BEGIN; c < SNDRV_SEQ_MAX_CLIENTS; c++) { if (clienttab[c] || clienttablock[c]) continue; clienttab[client->number = c] = client; spin_unlock_irqrestore(&clients_lock, flags); return client; } } else { if (clienttab[client_index] == NULL && !clienttablock[client_index]) { clienttab[client->number = client_index] = client; spin_unlock_irqrestore(&clients_lock, flags); return client; } } spin_unlock_irqrestore(&clients_lock, flags); snd_seq_pool_delete(&client->pool); kfree(client); return NULL; /* no free slot found or busy, return failure code */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'ALSA: seq: Make ioctls race-free The ALSA sequencer ioctls have no protection against racy calls while the concurrent operations may lead to interfere with each other. As reported recently, for example, the concurrent calls of setting client pool with a combination of write calls may lead to either the unkillable dead-lock or UAF. As a slightly big hammer solution, this patch introduces the mutex to make each ioctl exclusive. Although this may reduce performance via parallel ioctl calls, usually it's not demanded for sequencer usages, hence it should be negligible. Reported-by: Luo Quan <a4651386@163.com> Reviewed-by: Kees Cook <keescook@chromium.org> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Cc: <stable@vger.kernel.org> Signed-off-by: Takashi Iwai <tiwai@suse.de>'</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: gdImagePtr gdImageCreateFromGifCtx(gdIOCtxPtr fd) /* {{{ */ { int BitPixel; #if 0 int ColorResolution; int Background; int AspectRatio; #endif int Transparent = (-1); unsigned char buf[16]; unsigned char c; unsigned char ColorMap[3][MAXCOLORMAPSIZE]; unsigned char localColorMap[3][MAXCOLORMAPSIZE]; int imw, imh, screen_width, screen_height; int gif87a, useGlobalColormap; int bitPixel; int i; /*1.4//int imageCount = 0; */ int ZeroDataBlock = FALSE; int haveGlobalColormap; gdImagePtr im = 0; memset(ColorMap, 0, 3 * MAXCOLORMAPSIZE); memset(localColorMap, 0, 3 * MAXCOLORMAPSIZE); /*1.4//imageNumber = 1; */ if (! ReadOK(fd,buf,6)) { return 0; } if (strncmp((char *)buf,"GIF",3) != 0) { return 0; } if (memcmp((char *)buf+3, "87a", 3) == 0) { gif87a = 1; } else if (memcmp((char *)buf+3, "89a", 3) == 0) { gif87a = 0; } else { return 0; } if (! ReadOK(fd,buf,7)) { return 0; } BitPixel = 2<<(buf[4]&0x07); #if 0 ColorResolution = (int) (((buf[4]&0x70)>>3)+1); Background = buf[5]; AspectRatio = buf[6]; #endif screen_width = imw = LM_to_uint(buf[0],buf[1]); screen_height = imh = LM_to_uint(buf[2],buf[3]); haveGlobalColormap = BitSet(buf[4], LOCALCOLORMAP); /* Global Colormap */ if (haveGlobalColormap) { if (ReadColorMap(fd, BitPixel, ColorMap)) { return 0; } } for (;;) { int top, left; int width, height; if (! ReadOK(fd,&c,1)) { return 0; } if (c == ';') { /* GIF terminator */ goto terminated; } if (c == '!') { /* Extension */ if (! ReadOK(fd,&c,1)) { return 0; } DoExtension(fd, c, &Transparent, &ZeroDataBlock); continue; } if (c != ',') { /* Not a valid start character */ continue; } /*1.4//++imageCount; */ if (! ReadOK(fd,buf,9)) { return 0; } useGlobalColormap = ! BitSet(buf[8], LOCALCOLORMAP); bitPixel = 1<<((buf[8]&0x07)+1); left = LM_to_uint(buf[0], buf[1]); top = LM_to_uint(buf[2], buf[3]); width = LM_to_uint(buf[4], buf[5]); height = LM_to_uint(buf[6], buf[7]); if (left + width > screen_width || top + height > screen_height) { if (VERBOSE) { printf("Frame is not confined to screen dimension.\n"); } return 0; } if (!(im = gdImageCreate(width, height))) { return 0; } im->interlace = BitSet(buf[8], INTERLACE); if (!useGlobalColormap) { if (ReadColorMap(fd, bitPixel, localColorMap)) { gdImageDestroy(im); return 0; } ReadImage(im, fd, width, height, localColorMap, BitSet(buf[8], INTERLACE), &ZeroDataBlock); } else { if (!haveGlobalColormap) { gdImageDestroy(im); return 0; } ReadImage(im, fd, width, height, ColorMap, BitSet(buf[8], INTERLACE), &ZeroDataBlock); } if (Transparent != (-1)) { gdImageColorTransparent(im, Transparent); } goto terminated; } terminated: /* Terminator before any image was declared! */ if (!im) { return 0; } if (!im->colorsTotal) { gdImageDestroy(im); return 0; } /* Check for open colors at the end, so we can reduce colorsTotal and ultimately BitsPerPixel */ for (i=((im->colorsTotal-1)); (i>=0); i--) { if (im->open[i]) { im->colorsTotal--; } else { break; } } return im; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-681'], 'message': 'Fixed bug #75571: Potential infinite loop in gdImageCreateFromGifCtx Due to a signedness confusion in `GetCode_` a corrupt GIF file can trigger an infinite loop. Furthermore we make sure that a GIF without any palette entries is treated as invalid *after* open palette entries have been removed.'</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 (buf->currentLine == NULL || 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 || COLPOS(l, epos) < col) 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', 'CWE-787'], 'message': 'Prevent invalid columnPos() call in formUpdateBuffer() Bug-Debian: https://github.com/tats/w3m/issues/89'</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 js_Ast *logor(js_State *J, int notin) { js_Ast *a = logand(J, notin); if (jsP_accept(J, TK_OR)) a = EXP2(LOGOR, a, logor(J, notin)); return a; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-674'], 'message': 'Guard binary expressions from too much recursion.'</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 i8042_start(struct serio *serio) { struct i8042_port *port = serio->port_data; port->exists = true; mb(); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Input: i8042 - fix crash at boot time The driver checks port->exists twice in i8042_interrupt(), first when trying to assign temporary "serio" variable, and second time when deciding whether it should call serio_interrupt(). The value of port->exists may change between the 2 checks, and we may end up calling serio_interrupt() with a NULL pointer: BUG: unable to handle kernel NULL pointer dereference at 0000000000000050 IP: [<ffffffff8150feaf>] _spin_lock_irqsave+0x1f/0x40 PGD 0 Oops: 0002 [#1] SMP last sysfs file: CPU 0 Modules linked in: Pid: 1, comm: swapper Not tainted 2.6.32-358.el6.x86_64 #1 QEMU Standard PC (i440FX + PIIX, 1996) RIP: 0010:[<ffffffff8150feaf>] [<ffffffff8150feaf>] _spin_lock_irqsave+0x1f/0x40 RSP: 0018:ffff880028203cc0 EFLAGS: 00010082 RAX: 0000000000010000 RBX: 0000000000000000 RCX: 0000000000000000 RDX: 0000000000000282 RSI: 0000000000000098 RDI: 0000000000000050 RBP: ffff880028203cc0 R08: ffff88013e79c000 R09: ffff880028203ee0 R10: 0000000000000298 R11: 0000000000000282 R12: 0000000000000050 R13: 0000000000000000 R14: 0000000000000000 R15: 0000000000000098 FS: 0000000000000000(0000) GS:ffff880028200000(0000) knlGS:0000000000000000 CS: 0010 DS: 0018 ES: 0018 CR0: 000000008005003b CR2: 0000000000000050 CR3: 0000000001a85000 CR4: 00000000001407f0 DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400 Process swapper (pid: 1, threadinfo ffff88013e79c000, task ffff88013e79b500) Stack: ffff880028203d00 ffffffff813de186 ffffffffffffff02 0000000000000000 <d> 0000000000000000 0000000000000000 0000000000000000 0000000000000098 <d> ffff880028203d70 ffffffff813e0162 ffff880028203d20 ffffffff8103b8ac Call Trace: <IRQ> [<ffffffff813de186>] serio_interrupt+0x36/0xa0 [<ffffffff813e0162>] i8042_interrupt+0x132/0x3a0 [<ffffffff8103b8ac>] ? kvm_clock_read+0x1c/0x20 [<ffffffff8103b8b9>] ? kvm_clock_get_cycles+0x9/0x10 [<ffffffff810e1640>] handle_IRQ_event+0x60/0x170 [<ffffffff8103b154>] ? kvm_guest_apic_eoi_write+0x44/0x50 [<ffffffff810e3d8e>] handle_edge_irq+0xde/0x180 [<ffffffff8100de89>] handle_irq+0x49/0xa0 [<ffffffff81516c8c>] do_IRQ+0x6c/0xf0 [<ffffffff8100b9d3>] ret_from_intr+0x0/0x11 [<ffffffff81076f63>] ? __do_softirq+0x73/0x1e0 [<ffffffff8109b75b>] ? hrtimer_interrupt+0x14b/0x260 [<ffffffff8100c1cc>] ? call_softirq+0x1c/0x30 [<ffffffff8100de05>] ? do_softirq+0x65/0xa0 [<ffffffff81076d95>] ? irq_exit+0x85/0x90 [<ffffffff81516d80>] ? smp_apic_timer_interrupt+0x70/0x9b [<ffffffff8100bb93>] ? apic_timer_interrupt+0x13/0x20 To avoid the issue let's change the second check to test whether serio is NULL or not. Also, let's take i8042_lock in i8042_start() and i8042_stop() instead of trying to be overly smart and using memory barriers. Signed-off-by: Chen Hong <chenhong3@huawei.com> [dtor: take lock in i8042_start()/i8042_stop()] Cc: stable@vger.kernel.org Signed-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.com>'</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 struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb) { if (skb_cow(skb, skb_headroom(skb)) < 0) { kfree_skb(skb); return NULL; } memmove(skb->data - ETH_HLEN, skb->data - skb->mac_len - VLAN_HLEN, 2 * ETH_ALEN); skb->mac_header += VLAN_HLEN; return skb; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'net: create skb_gso_validate_mac_len() If you take a GSO skb, and split it into packets, will the MAC length (L2 + L3 + L4 headers + payload) of those packets be small enough to fit within a given length? Move skb_gso_mac_seglen() to skbuff.h with other related functions like skb_gso_network_seglen() so we can use it, and then create skb_gso_validate_mac_len to do the full calculation. Signed-off-by: Daniel Axtens <dja@axtens.net> Signed-off-by: David S. Miller <davem@davemloft.net>'</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_gif(Gif_Reader *grr, int read_flags, const char* landmark, Gif_ReadErrorHandler handler) { Gif_Stream *gfs; Gif_Image *gfi; Gif_Context gfc; int unknown_block_type = 0; if (gifgetc(grr) != 'G' || gifgetc(grr) != 'I' || gifgetc(grr) != 'F') return 0; (void)gifgetc(grr); (void)gifgetc(grr); (void)gifgetc(grr); gfs = Gif_NewStream(); gfi = Gif_NewImage(); gfc.stream = gfs; gfc.prefix = Gif_NewArray(Gif_Code, GIF_MAX_CODE); gfc.suffix = Gif_NewArray(uint8_t, GIF_MAX_CODE); gfc.length = Gif_NewArray(uint16_t, GIF_MAX_CODE); gfc.handler = handler; gfc.gfi = gfi; gfc.errors[0] = gfc.errors[1] = 0; if (!gfs || !gfi || !gfc.prefix || !gfc.suffix || !gfc.length) goto done; gfs->landmark = landmark; GIF_DEBUG(("\nGIF ")); if (!read_logical_screen_descriptor(gfs, grr)) goto done; GIF_DEBUG(("logscrdesc ")); while (!gifeof(grr)) { uint8_t block = gifgetbyte(grr); switch (block) { case ',': /* image block */ GIF_DEBUG(("imageread %d ", gfs->nimages)); gfi->identifier = last_name; last_name = 0; if (!Gif_AddImage(gfs, gfi)) goto done; else if (!read_image(grr, &gfc, gfi, read_flags)) { Gif_RemoveImage(gfs, gfs->nimages - 1); gfi = 0; goto done; } gfc.gfi = gfi = Gif_NewImage(); if (!gfi) goto done; break; case ';': /* terminator */ GIF_DEBUG(("term\n")); goto done; case '!': /* extension */ block = gifgetbyte(grr); GIF_DEBUG(("ext(0x%02X) ", block)); switch (block) { case 0xF9: read_graphic_control_extension(&gfc, gfi, grr); break; case 0xCE: last_name = suck_data(last_name, 0, grr); break; case 0xFE: if (!read_comment_extension(gfi, grr)) goto done; break; case 0xFF: read_application_extension(&gfc, grr); break; default: read_unknown_extension(&gfc, grr, block, 0, 0); break; } break; default: if (!unknown_block_type) { char buf[256]; sprintf(buf, "unknown block type %d at file offset %u", block, grr->pos - 1); gif_read_error(&gfc, 1, buf); unknown_block_type = 1; } break; } } done: /* Move comments and extensions after last image into stream. */ if (gfs && gfi) { Gif_Extension* gfex; gfs->end_comment = gfi->comment; gfi->comment = 0; gfs->end_extension_list = gfi->extension_list; gfi->extension_list = 0; for (gfex = gfs->end_extension_list; gfex; gfex = gfex->next) gfex->image = NULL; } Gif_DeleteImage(gfi); Gif_DeleteArray(last_name); Gif_DeleteArray(gfc.prefix); Gif_DeleteArray(gfc.suffix); Gif_DeleteArray(gfc.length); gfc.gfi = 0; if (gfs) gfs->errors = gfc.errors[1]; if (gfs && gfc.errors[1] == 0 && !(read_flags & GIF_READ_TRAILING_GARBAGE_OK) && !grr->eofer(grr)) gif_read_error(&gfc, 0, "trailing garbage after GIF ignored"); /* finally, export last message */ gif_read_error(&gfc, -1, 0); return gfs; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'gif_read: Set last_name = NULL unconditionally. With a non-malicious GIF, last_name is set to NULL when a name extension is followed by an image. Reported in #117, via Debian, via a KAIST fuzzing program.'</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 amd_gpio_remove(struct platform_device *pdev) { struct amd_gpio *gpio_dev; gpio_dev = platform_get_drvdata(pdev); gpiochip_remove(&gpio_dev->gc); pinctrl_unregister(gpio_dev->pctrl); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'pinctrl: amd: Use devm_pinctrl_register() for pinctrl registration Use devm_pinctrl_register() for pin control registration and clean error path. Signed-off-by: Laxman Dewangan <ldewangan@nvidia.com> Signed-off-by: Linus Walleij <linus.walleij@linaro.org>'</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: compute_U_value_R3(std::string const& user_password, QPDF::EncryptionData const& data) { // Algorithm 3.5 from the PDF 1.7 Reference Manual std::string k1 = QPDF::compute_encryption_key(user_password, data); MD5 md5; md5.encodeDataIncrementally( pad_or_truncate_password_V4("").c_str(), key_bytes); md5.encodeDataIncrementally(data.getId1().c_str(), data.getId1().length()); MD5::Digest digest; md5.digest(digest); iterate_rc4(digest, sizeof(MD5::Digest), QUtil::unsigned_char_pointer(k1), data.getLengthBytes(), 20, false); char result[key_bytes]; memcpy(result, digest, sizeof(MD5::Digest)); // pad with arbitrary data -- make it consistent for the sake of // testing for (unsigned int i = sizeof(MD5::Digest); i < key_bytes; ++i) { result[i] = static_cast<char>((i * i) % 0xff); } return std::string(result, key_bytes); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Pad keys to avoid memory errors (fixes #147)'</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: QPDFWriter::parseVersion(std::string const& version, int& major, int& minor) const { major = atoi(version.c_str()); minor = 0; size_t p = version.find('.'); if ((p != std::string::npos) && (version.length() > p)) { minor = atoi(version.substr(p + 1).c_str()); } std::string tmp = QUtil::int_to_string(major) + "." + QUtil::int_to_string(minor); if (tmp != version) { throw std::logic_error( "INTERNAL ERROR: QPDFWriter::parseVersion" " called with invalid version number " + version); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Replace all atoi calls with QUtil::string_to_int The latter catches underflow/overflow.'</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: QPDF::read_xref(qpdf_offset_t xref_offset) { std::map<int, int> free_table; while (xref_offset) { char buf[7]; memset(buf, 0, sizeof(buf)); this->m->file->seek(xref_offset, SEEK_SET); this->m->file->read(buf, sizeof(buf) - 1); // The PDF spec says xref must be followed by a line // terminator, but files exist in the wild where it is // terminated by arbitrary whitespace. if ((strncmp(buf, "xref", 4) == 0) && QUtil::is_space(buf[4])) { QTC::TC("qpdf", "QPDF xref space", ((buf[4] == '\n') ? 0 : (buf[4] == '\r') ? 1 : (buf[4] == ' ') ? 2 : 9999)); int skip = 4; // buf is null-terminated, and QUtil::is_space('\0') is // false, so this won't overrun. while (QUtil::is_space(buf[skip])) { ++skip; } xref_offset = read_xrefTable(xref_offset + skip); } else { xref_offset = read_xrefStream(xref_offset); } } if (! this->m->trailer.isInitialized()) { throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, "unable to find trailer while reading xref"); } int size = this->m->trailer.getKey("/Size").getIntValue(); int max_obj = 0; if (! this->m->xref_table.empty()) { max_obj = (*(this->m->xref_table.rbegin())).first.getObj(); } if (! this->m->deleted_objects.empty()) { max_obj = std::max(max_obj, *(this->m->deleted_objects.rbegin())); } if (size != max_obj + 1) { QTC::TC("qpdf", "QPDF xref size mismatch"); warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, std::string("reported number of objects (") + QUtil::int_to_string(size) + ") inconsistent with actual number of objects (" + QUtil::int_to_string(max_obj + 1) + ")")); } // We no longer need the deleted_objects table, so go ahead and // clear it out to make sure we never depend on its being set. this->m->deleted_objects.clear(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-835'], 'message': 'Detect xref pointer infinite loop (fixes #149)'</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: selReadStream(FILE *fp) { char *selname; char linebuf[L_BUF_SIZE]; l_int32 sy, sx, cy, cx, i, j, version, ignore; SEL *sel; PROCNAME("selReadStream"); if (!fp) return (SEL *)ERROR_PTR("stream not defined", procName, NULL); if (fscanf(fp, " Sel Version %d\n", &version) != 1) return (SEL *)ERROR_PTR("not a sel file", procName, NULL); if (version != SEL_VERSION_NUMBER) return (SEL *)ERROR_PTR("invalid sel version", procName, NULL); if (fgets(linebuf, L_BUF_SIZE, fp) == NULL) return (SEL *)ERROR_PTR("error reading into linebuf", procName, NULL); selname = stringNew(linebuf); sscanf(linebuf, " ------ %s ------", selname); if (fscanf(fp, " sy = %d, sx = %d, cy = %d, cx = %d\n", &sy, &sx, &cy, &cx) != 4) { LEPT_FREE(selname); return (SEL *)ERROR_PTR("dimensions not read", procName, NULL); } if ((sel = selCreate(sy, sx, selname)) == NULL) { LEPT_FREE(selname); return (SEL *)ERROR_PTR("sel not made", procName, NULL); } selSetOrigin(sel, cy, cx); for (i = 0; i < sy; i++) { ignore = fscanf(fp, " "); for (j = 0; j < sx; j++) ignore = fscanf(fp, "%1d", &sel->data[i][j]); ignore = fscanf(fp, "\n"); } ignore = fscanf(fp, "\n"); LEPT_FREE(selname); return sel; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Security fixes: expect final changes for release 1.75.3. * Fixed a debian security issue with fscanf() reading a string with possible buffer overflow. * There were also a few similar situations with sscanf().'</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 irc_core_deinit(void) { signal_emit("chat protocol deinit", 1, chat_protocol_find("IRC")); cap_deinit(); irc_expandos_deinit(); netsplit_deinit(); lag_deinit(); irc_commands_deinit(); ctcp_deinit(); irc_queries_deinit(); irc_channels_deinit(); irc_irc_deinit(); irc_servers_deinit(); irc_chatnets_deinit(); irc_session_deinit(); chat_protocol_unregister("IRC"); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'SASL support The only supported methods are PLAIN and EXTERNAL, the latter is untested as of now. The code gets the values from the keys named sasl_{mechanism,username,password} specified for each chatnet.'</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 sig_message_public(SERVER_REC *server, const char *msg, const char *nick, const char *address, const char *target) { CHANNEL_REC *channel; int own; channel = channel_find(server, target); if (channel != NULL) { own = nick_match_msg(channel, msg, server->nick); CHANNEL_LAST_MSG_ADD(channel, nick, own); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Merge branch 'security' into 'master' Security See merge request irssi/irssi!34 (cherry picked from commit b0d9cb33cd9ef9da7c331409e8b7c57a6f3aef3f)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static char *theme_format_expand_abstract(THEME_REC *theme, const char **formatp, theme_rm_col *last_fg, theme_rm_col *last_bg, int flags, GTree *block_list) { GString *str; const char *p, *format; char *abstract, *data, *ret; theme_rm_col default_fg, default_bg; int len; format = *formatp; default_fg = *last_fg; default_bg = *last_bg; /* get abstract name first */ p = format; while (*p != '\0' && *p != ' ' && *p != '{' && *p != '}') p++; if (*p == '\0' || p == format) return NULL; /* error */ len = (int) (p-format); abstract = g_strndup(format, len); /* skip the following space, if there's any more spaces they're treated as arguments */ if (*p == ' ') { len++; if ((flags & EXPAND_FLAG_IGNORE_EMPTY) && data_is_empty(&p)) { *formatp = p; g_free(abstract); return NULL; } } *formatp = format+len; if (block_list == NULL) { block_list = g_tree_new_full((GCompareDataFunc) g_strcmp0, NULL, g_free, NULL); } else { g_tree_ref(block_list); } /* get the abstract data */ data = g_hash_table_lookup(theme->abstracts, abstract); if (data == NULL || g_tree_lookup(block_list, abstract) != NULL) { /* unknown abstract, just display the data */ data = "$0-"; g_free(abstract); } else { g_tree_insert(block_list, abstract, abstract); } abstract = g_strdup(data); /* we'll need to get the data part. it may contain more abstracts, they are _NOT_ expanded. */ data = theme_format_expand_get(theme, formatp); len = strlen(data); if (len > 1 && i_isdigit(data[len-1]) && data[len-2] == '$') { /* ends with $<digit> .. this breaks things if next character is digit or '-' */ char digit, *tmp; tmp = data; digit = tmp[len-1]; tmp[len-1] = '\0'; data = g_strdup_printf("%s{%c}", tmp, digit); g_free(tmp); } ret = parse_special_string(abstract, NULL, NULL, data, NULL, PARSE_FLAG_ONLY_ARGS); g_free(abstract); g_free(data); str = g_string_new(NULL); p = ret; while (*p != '\0') { if (*p == '\\') { int chr; p++; chr = expand_escape(&p); g_string_append_c(str, chr != -1 ? chr : *p); } else g_string_append_c(str, *p); p++; } g_free(ret); abstract = str->str; g_string_free(str, FALSE); /* abstract may itself contain abstracts or replaces */ p = abstract; ret = theme_format_expand_data_rec(theme, &p, default_fg, default_bg, last_fg, last_bg, flags | EXPAND_FLAG_LASTCOLOR_ARG, block_list); g_free(abstract); g_tree_unref(block_list); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Do not read beyond end of escaped string Credit to OSS-Fuzz'</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 get_v4l2_framebuffer32(struct v4l2_framebuffer *kp, struct v4l2_framebuffer32 __user *up) { u32 tmp; if (!access_ok(VERIFY_READ, up, sizeof(*up)) || get_user(tmp, &up->base) || get_user(kp->capability, &up->capability) || get_user(kp->flags, &up->flags) || copy_from_user(&kp->fmt, &up->fmt, sizeof(up->fmt))) return -EFAULT; kp->base = (__force void *)compat_ptr(tmp); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'media: v4l2-compat-ioctl32.c: refactor compat ioctl32 logic The 32-bit compat v4l2 ioctl handling is implemented based on its 64-bit equivalent. It converts 32-bit data structures into its 64-bit equivalents and needs to provide the data to the 64-bit ioctl in user space memory which is commonly allocated using compat_alloc_user_space(). However, due to how that function is implemented, it can only be called a single time for every syscall invocation. Supposedly to avoid this limitation, the existing code uses a mix of memory from the kernel stack and memory allocated through compat_alloc_user_space(). Under normal circumstances, this would not work, because the 64-bit ioctl expects all pointers to point to user space memory. As a workaround, set_fs(KERNEL_DS) is called to temporarily disable this extra safety check and allow kernel pointers. However, this might introduce a security vulnerability: The result of the 32-bit to 64-bit conversion is writeable by user space because the output buffer has been allocated via compat_alloc_user_space(). A malicious user space process could then manipulate pointers inside this output buffer, and due to the previous set_fs(KERNEL_DS) call, functions like get_user() or put_user() no longer prevent kernel memory access. The new approach is to pre-calculate the total amount of user space memory that is needed, allocate it using compat_alloc_user_space() and then divide up the allocated memory to accommodate all data structures that need to be converted. An alternative approach would have been to retain the union type karg that they allocated on the kernel stack in do_video_ioctl(), copy all data from user space into karg and then back to user space. However, we decided against this approach because it does not align with other compat syscall implementations. Instead, we tried to replicate the get_user/put_user pairs as found in other places in the kernel: if (get_user(clipcount, &up->clipcount) || put_user(clipcount, &kp->clipcount)) return -EFAULT; Notes from hans.verkuil@cisco.com: This patch was taken from: https://github.com/LineageOS/android_kernel_samsung_apq8084/commit/97b733953c06e4f0398ade18850f0817778255f7 Clearly nobody could be bothered to upstream this patch or at minimum tell us :-( We only heard about this a week ago. This patch was rebased and cleaned up. Compared to the original I also swapped the order of the convert_in_user arguments so that they matched copy_in_user. It was hard to review otherwise. I also replaced the ALLOC_USER_SPACE/ALLOC_AND_GET by a normal function. Fixes: 6b5a9492ca ("v4l: introduce string control support.") Signed-off-by: Daniel Mentz <danielmentz@google.com> Co-developed-by: Hans Verkuil <hans.verkuil@cisco.com> Acked-by: Sakari Ailus <sakari.ailus@linux.intel.com> Signed-off-by: Hans Verkuil <hans.verkuil@cisco.com> Cc: <stable@vger.kernel.org> # for v4.15 and up Signed-off-by: Mauro Carvalho Chehab <mchehab@s-opensource.com>'</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 get_v4l2_edid32(struct v4l2_edid *kp, struct v4l2_edid32 __user *up) { u32 tmp; if (!access_ok(VERIFY_READ, up, sizeof(*up)) || get_user(kp->pad, &up->pad) || get_user(kp->start_block, &up->start_block) || get_user(kp->blocks, &up->blocks) || get_user(tmp, &up->edid) || copy_from_user(kp->reserved, up->reserved, sizeof(kp->reserved))) return -EFAULT; kp->edid = (__force u8 *)compat_ptr(tmp); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'media: v4l2-compat-ioctl32.c: refactor compat ioctl32 logic The 32-bit compat v4l2 ioctl handling is implemented based on its 64-bit equivalent. It converts 32-bit data structures into its 64-bit equivalents and needs to provide the data to the 64-bit ioctl in user space memory which is commonly allocated using compat_alloc_user_space(). However, due to how that function is implemented, it can only be called a single time for every syscall invocation. Supposedly to avoid this limitation, the existing code uses a mix of memory from the kernel stack and memory allocated through compat_alloc_user_space(). Under normal circumstances, this would not work, because the 64-bit ioctl expects all pointers to point to user space memory. As a workaround, set_fs(KERNEL_DS) is called to temporarily disable this extra safety check and allow kernel pointers. However, this might introduce a security vulnerability: The result of the 32-bit to 64-bit conversion is writeable by user space because the output buffer has been allocated via compat_alloc_user_space(). A malicious user space process could then manipulate pointers inside this output buffer, and due to the previous set_fs(KERNEL_DS) call, functions like get_user() or put_user() no longer prevent kernel memory access. The new approach is to pre-calculate the total amount of user space memory that is needed, allocate it using compat_alloc_user_space() and then divide up the allocated memory to accommodate all data structures that need to be converted. An alternative approach would have been to retain the union type karg that they allocated on the kernel stack in do_video_ioctl(), copy all data from user space into karg and then back to user space. However, we decided against this approach because it does not align with other compat syscall implementations. Instead, we tried to replicate the get_user/put_user pairs as found in other places in the kernel: if (get_user(clipcount, &up->clipcount) || put_user(clipcount, &kp->clipcount)) return -EFAULT; Notes from hans.verkuil@cisco.com: This patch was taken from: https://github.com/LineageOS/android_kernel_samsung_apq8084/commit/97b733953c06e4f0398ade18850f0817778255f7 Clearly nobody could be bothered to upstream this patch or at minimum tell us :-( We only heard about this a week ago. This patch was rebased and cleaned up. Compared to the original I also swapped the order of the convert_in_user arguments so that they matched copy_in_user. It was hard to review otherwise. I also replaced the ALLOC_USER_SPACE/ALLOC_AND_GET by a normal function. Fixes: 6b5a9492ca ("v4l: introduce string control support.") Signed-off-by: Daniel Mentz <danielmentz@google.com> Co-developed-by: Hans Verkuil <hans.verkuil@cisco.com> Acked-by: Sakari Ailus <sakari.ailus@linux.intel.com> Signed-off-by: Hans Verkuil <hans.verkuil@cisco.com> Cc: <stable@vger.kernel.org> # for v4.15 and up Signed-off-by: Mauro Carvalho Chehab <mchehab@s-opensource.com>'</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 __put_v4l2_format32(struct v4l2_format *kp, struct v4l2_format32 __user *up) { if (put_user(kp->type, &up->type)) return -EFAULT; switch (kp->type) { case V4L2_BUF_TYPE_VIDEO_CAPTURE: case V4L2_BUF_TYPE_VIDEO_OUTPUT: return copy_to_user(&up->fmt.pix, &kp->fmt.pix, sizeof(kp->fmt.pix)) ? -EFAULT : 0; case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE: case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE: return copy_to_user(&up->fmt.pix_mp, &kp->fmt.pix_mp, sizeof(kp->fmt.pix_mp)) ? -EFAULT : 0; case V4L2_BUF_TYPE_VIDEO_OVERLAY: case V4L2_BUF_TYPE_VIDEO_OUTPUT_OVERLAY: return put_v4l2_window32(&kp->fmt.win, &up->fmt.win); case V4L2_BUF_TYPE_VBI_CAPTURE: case V4L2_BUF_TYPE_VBI_OUTPUT: return copy_to_user(&up->fmt.vbi, &kp->fmt.vbi, sizeof(kp->fmt.vbi)) ? -EFAULT : 0; case V4L2_BUF_TYPE_SLICED_VBI_CAPTURE: case V4L2_BUF_TYPE_SLICED_VBI_OUTPUT: return copy_to_user(&up->fmt.sliced, &kp->fmt.sliced, sizeof(kp->fmt.sliced)) ? -EFAULT : 0; case V4L2_BUF_TYPE_SDR_CAPTURE: case V4L2_BUF_TYPE_SDR_OUTPUT: return copy_to_user(&up->fmt.sdr, &kp->fmt.sdr, sizeof(kp->fmt.sdr)) ? -EFAULT : 0; case V4L2_BUF_TYPE_META_CAPTURE: return copy_to_user(&up->fmt.meta, &kp->fmt.meta, sizeof(kp->fmt.meta)) ? -EFAULT : 0; default: return -EINVAL; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'media: v4l2-compat-ioctl32.c: refactor compat ioctl32 logic The 32-bit compat v4l2 ioctl handling is implemented based on its 64-bit equivalent. It converts 32-bit data structures into its 64-bit equivalents and needs to provide the data to the 64-bit ioctl in user space memory which is commonly allocated using compat_alloc_user_space(). However, due to how that function is implemented, it can only be called a single time for every syscall invocation. Supposedly to avoid this limitation, the existing code uses a mix of memory from the kernel stack and memory allocated through compat_alloc_user_space(). Under normal circumstances, this would not work, because the 64-bit ioctl expects all pointers to point to user space memory. As a workaround, set_fs(KERNEL_DS) is called to temporarily disable this extra safety check and allow kernel pointers. However, this might introduce a security vulnerability: The result of the 32-bit to 64-bit conversion is writeable by user space because the output buffer has been allocated via compat_alloc_user_space(). A malicious user space process could then manipulate pointers inside this output buffer, and due to the previous set_fs(KERNEL_DS) call, functions like get_user() or put_user() no longer prevent kernel memory access. The new approach is to pre-calculate the total amount of user space memory that is needed, allocate it using compat_alloc_user_space() and then divide up the allocated memory to accommodate all data structures that need to be converted. An alternative approach would have been to retain the union type karg that they allocated on the kernel stack in do_video_ioctl(), copy all data from user space into karg and then back to user space. However, we decided against this approach because it does not align with other compat syscall implementations. Instead, we tried to replicate the get_user/put_user pairs as found in other places in the kernel: if (get_user(clipcount, &up->clipcount) || put_user(clipcount, &kp->clipcount)) return -EFAULT; Notes from hans.verkuil@cisco.com: This patch was taken from: https://github.com/LineageOS/android_kernel_samsung_apq8084/commit/97b733953c06e4f0398ade18850f0817778255f7 Clearly nobody could be bothered to upstream this patch or at minimum tell us :-( We only heard about this a week ago. This patch was rebased and cleaned up. Compared to the original I also swapped the order of the convert_in_user arguments so that they matched copy_in_user. It was hard to review otherwise. I also replaced the ALLOC_USER_SPACE/ALLOC_AND_GET by a normal function. Fixes: 6b5a9492ca ("v4l: introduce string control support.") Signed-off-by: Daniel Mentz <danielmentz@google.com> Co-developed-by: Hans Verkuil <hans.verkuil@cisco.com> Acked-by: Sakari Ailus <sakari.ailus@linux.intel.com> Signed-off-by: Hans Verkuil <hans.verkuil@cisco.com> Cc: <stable@vger.kernel.org> # for v4.15 and up Signed-off-by: Mauro Carvalho Chehab <mchehab@s-opensource.com>'</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 f2fs_init_extent_tree(struct inode *inode, struct f2fs_extent *i_ext) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); struct extent_tree *et; struct extent_node *en; struct extent_info ei; if (!f2fs_may_extent_tree(inode)) { /* drop largest extent */ if (i_ext && i_ext->len) { i_ext->len = 0; return true; } return false; } et = __grab_extent_tree(inode); if (!i_ext || !i_ext->len) return false; get_extent_info(&ei, i_ext); write_lock(&et->lock); if (atomic_read(&et->node_cnt)) goto out; en = __init_extent_tree(sbi, et, &ei); if (en) { spin_lock(&sbi->extent_lock); list_add_tail(&en->list, &sbi->extent_list); spin_unlock(&sbi->extent_lock); } out: write_unlock(&et->lock); return false; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'f2fs: fix a bug caused by NULL extent tree Thread A: Thread B: -f2fs_remount -sbi->mount_opt.opt = 0; <--- -f2fs_iget -do_read_inode -f2fs_init_extent_tree -F2FS_I(inode)->extent_tree is NULL -default_options && parse_options -remount return <--- -f2fs_map_blocks -f2fs_lookup_extent_tree -f2fs_bug_on(sbi, !et); The same problem with f2fs_new_inode. Signed-off-by: Yunlei He <heyunlei@huawei.com> Signed-off-by: Jaegeuk Kim <jaegeuk@kernel.org>'</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 ocfs2_setattr(struct dentry *dentry, struct iattr *attr) { int status = 0, size_change; int inode_locked = 0; struct inode *inode = d_inode(dentry); struct super_block *sb = inode->i_sb; struct ocfs2_super *osb = OCFS2_SB(sb); struct buffer_head *bh = NULL; handle_t *handle = NULL; struct dquot *transfer_to[MAXQUOTAS] = { }; int qtype; int had_lock; struct ocfs2_lock_holder oh; trace_ocfs2_setattr(inode, dentry, (unsigned long long)OCFS2_I(inode)->ip_blkno, dentry->d_name.len, dentry->d_name.name, attr->ia_valid, attr->ia_mode, from_kuid(&init_user_ns, attr->ia_uid), from_kgid(&init_user_ns, attr->ia_gid)); /* ensuring we don't even attempt to truncate a symlink */ if (S_ISLNK(inode->i_mode)) attr->ia_valid &= ~ATTR_SIZE; #define OCFS2_VALID_ATTRS (ATTR_ATIME | ATTR_MTIME | ATTR_CTIME | ATTR_SIZE \ | ATTR_GID | ATTR_UID | ATTR_MODE) if (!(attr->ia_valid & OCFS2_VALID_ATTRS)) return 0; status = setattr_prepare(dentry, attr); if (status) return status; if (is_quota_modification(inode, attr)) { status = dquot_initialize(inode); if (status) return status; } size_change = S_ISREG(inode->i_mode) && attr->ia_valid & ATTR_SIZE; if (size_change) { status = ocfs2_rw_lock(inode, 1); if (status < 0) { mlog_errno(status); goto bail; } } had_lock = ocfs2_inode_lock_tracker(inode, &bh, 1, &oh); if (had_lock < 0) { status = had_lock; goto bail_unlock_rw; } else if (had_lock) { /* * As far as we know, ocfs2_setattr() could only be the first * VFS entry point in the call chain of recursive cluster * locking issue. * * For instance: * chmod_common() * notify_change() * ocfs2_setattr() * posix_acl_chmod() * ocfs2_iop_get_acl() * * But, we're not 100% sure if it's always true, because the * ordering of the VFS entry points in the call chain is out * of our control. So, we'd better dump the stack here to * catch the other cases of recursive locking. */ mlog(ML_ERROR, "Another case of recursive locking:\n"); dump_stack(); } inode_locked = 1; if (size_change) { status = inode_newsize_ok(inode, attr->ia_size); if (status) goto bail_unlock; inode_dio_wait(inode); if (i_size_read(inode) >= attr->ia_size) { if (ocfs2_should_order_data(inode)) { status = ocfs2_begin_ordered_truncate(inode, attr->ia_size); if (status) goto bail_unlock; } status = ocfs2_truncate_file(inode, bh, attr->ia_size); } else status = ocfs2_extend_file(inode, bh, attr->ia_size); if (status < 0) { if (status != -ENOSPC) mlog_errno(status); status = -ENOSPC; goto bail_unlock; } } if ((attr->ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) || (attr->ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) { /* * Gather pointers to quota structures so that allocation / * freeing of quota structures happens here and not inside * dquot_transfer() where we have problems with lock ordering */ if (attr->ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid) && OCFS2_HAS_RO_COMPAT_FEATURE(sb, OCFS2_FEATURE_RO_COMPAT_USRQUOTA)) { transfer_to[USRQUOTA] = dqget(sb, make_kqid_uid(attr->ia_uid)); if (IS_ERR(transfer_to[USRQUOTA])) { status = PTR_ERR(transfer_to[USRQUOTA]); goto bail_unlock; } } if (attr->ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid) && OCFS2_HAS_RO_COMPAT_FEATURE(sb, OCFS2_FEATURE_RO_COMPAT_GRPQUOTA)) { transfer_to[GRPQUOTA] = dqget(sb, make_kqid_gid(attr->ia_gid)); if (IS_ERR(transfer_to[GRPQUOTA])) { status = PTR_ERR(transfer_to[GRPQUOTA]); goto bail_unlock; } } handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS + 2 * ocfs2_quota_trans_credits(sb)); if (IS_ERR(handle)) { status = PTR_ERR(handle); mlog_errno(status); goto bail_unlock; } status = __dquot_transfer(inode, transfer_to); if (status < 0) goto bail_commit; } else { handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS); if (IS_ERR(handle)) { status = PTR_ERR(handle); mlog_errno(status); goto bail_unlock; } } setattr_copy(inode, attr); mark_inode_dirty(inode); status = ocfs2_mark_inode_dirty(handle, inode, bh); if (status < 0) mlog_errno(status); bail_commit: ocfs2_commit_trans(osb, handle); bail_unlock: if (status && inode_locked) { ocfs2_inode_unlock_tracker(inode, 1, &oh, had_lock); inode_locked = 0; } bail_unlock_rw: if (size_change) ocfs2_rw_unlock(inode, 1); bail: /* Release quota pointers in case we acquired them */ for (qtype = 0; qtype < OCFS2_MAXQUOTAS; qtype++) dqput(transfer_to[qtype]); if (!status && attr->ia_valid & ATTR_MODE) { status = ocfs2_acl_chmod(inode, bh); if (status < 0) mlog_errno(status); } if (inode_locked) ocfs2_inode_unlock_tracker(inode, 1, &oh, had_lock); brelse(bh); return status; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'ocfs2: should wait dio before inode lock in ocfs2_setattr() we should wait dio requests to finish before inode lock in ocfs2_setattr(), otherwise the following deadlock will happen: process 1 process 2 process 3 truncate file 'A' end_io of writing file 'A' receiving the bast messages ocfs2_setattr ocfs2_inode_lock_tracker ocfs2_inode_lock_full inode_dio_wait __inode_dio_wait -->waiting for all dio requests finish dlm_proxy_ast_handler dlm_do_local_bast ocfs2_blocking_ast ocfs2_generic_handle_bast set OCFS2_LOCK_BLOCKED flag dio_end_io dio_bio_end_aio dio_complete ocfs2_dio_end_io ocfs2_dio_end_io_write ocfs2_inode_lock __ocfs2_cluster_lock ocfs2_wait_for_mask -->waiting for OCFS2_LOCK_BLOCKED flag to be cleared, that is waiting for 'process 1' unlocking the inode lock inode_dio_end -->here dec the i_dio_count, but will never be called, so a deadlock happened. Link: http://lkml.kernel.org/r/59F81636.70508@huawei.com Signed-off-by: Alex Chen <alex.chen@huawei.com> Reviewed-by: Jun Piao <piaojun@huawei.com> Reviewed-by: Joseph Qi <jiangqi903@gmail.com> Acked-by: Changwei Ge <ge.changwei@h3c.com> Cc: Mark Fasheh <mfasheh@versity.com> Cc: Joel Becker <jlbec@evilplan.org> Cc: Junxiao Bi <junxiao.bi@oracle.com> Cc: <stable@vger.kernel.org> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</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 struct o2nm_cluster *to_o2nm_cluster_from_node(struct o2nm_node *node) { /* through the first node_set .parent * mycluster/nodes/mynode == o2nm_cluster->o2nm_node_group->o2nm_node */ return to_o2nm_cluster(node->nd_item.ci_parent->ci_parent); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-284'], 'message': 'ocfs2: subsystem.su_mutex is required while accessing the item->ci_parent The subsystem.su_mutex is required while accessing the item->ci_parent, otherwise, NULL pointer dereference to the item->ci_parent will be triggered in the following situation: add node delete node sys_write vfs_write configfs_write_file o2nm_node_store o2nm_node_local_write do_rmdir vfs_rmdir configfs_rmdir mutex_lock(&subsys->su_mutex); unlink_obj item->ci_group = NULL; item->ci_parent = NULL; to_o2nm_cluster_from_node node->nd_item.ci_parent->ci_parent BUG since of NULL pointer dereference to nd_item.ci_parent Moreover, the o2nm_cluster also should be protected by the subsystem.su_mutex. [alex.chen@huawei.com: v2] Link: http://lkml.kernel.org/r/59EEAA69.9080703@huawei.com Link: http://lkml.kernel.org/r/59E9B36A.10700@huawei.com Signed-off-by: Alex Chen <alex.chen@huawei.com> Reviewed-by: Jun Piao <piaojun@huawei.com> Reviewed-by: Joseph Qi <jiangqi903@gmail.com> Cc: Mark Fasheh <mfasheh@versity.com> Cc: Joel Becker <jlbec@evilplan.org> Cc: Junxiao Bi <junxiao.bi@oracle.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</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 __munlock_pagevec(struct pagevec *pvec, struct zone *zone) { int i; int nr = pagevec_count(pvec); int delta_munlocked; struct pagevec pvec_putback; int pgrescued = 0; pagevec_init(&pvec_putback, 0); /* Phase 1: page isolation */ spin_lock_irq(zone_lru_lock(zone)); for (i = 0; i < nr; i++) { struct page *page = pvec->pages[i]; if (TestClearPageMlocked(page)) { /* * We already have pin from follow_page_mask() * so we can spare the get_page() here. */ if (__munlock_isolate_lru_page(page, false)) continue; else __munlock_isolation_failed(page); } /* * We won't be munlocking this page in the next phase * but we still need to release the follow_page_mask() * pin. We cannot do it under lru_lock however. If it's * the last pin, __page_cache_release() would deadlock. */ pagevec_add(&pvec_putback, pvec->pages[i]); pvec->pages[i] = NULL; } delta_munlocked = -nr + pagevec_count(&pvec_putback); __mod_zone_page_state(zone, NR_MLOCK, delta_munlocked); spin_unlock_irq(zone_lru_lock(zone)); /* Now we can release pins of pages that we are not munlocking */ pagevec_release(&pvec_putback); /* Phase 2: page munlock */ for (i = 0; i < nr; i++) { struct page *page = pvec->pages[i]; if (page) { lock_page(page); if (!__putback_lru_fast_prepare(page, &pvec_putback, &pgrescued)) { /* * Slow path. We don't want to lose the last * pin before unlock_page() */ get_page(page); /* for putback_lru_page() */ __munlock_isolated_page(page); unlock_page(page); put_page(page); /* from follow_page_mask() */ } } } /* * Phase 3: page putback for pages that qualified for the fast path * This will also call put_page() to return pin from follow_page_mask() */ if (pagevec_count(&pvec_putback)) __putback_lru_fast(&pvec_putback, pgrescued); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'mlock: fix mlock count can not decrease in race condition Kefeng reported that when running the follow test, the mlock count in meminfo will increase permanently: [1] testcase linux:~ # cat test_mlockal grep Mlocked /proc/meminfo for j in `seq 0 10` do for i in `seq 4 15` do ./p_mlockall >> log & done sleep 0.2 done # wait some time to let mlock counter decrease and 5s may not enough sleep 5 grep Mlocked /proc/meminfo linux:~ # cat p_mlockall.c #include <sys/mman.h> #include <stdlib.h> #include <stdio.h> #define SPACE_LEN 4096 int main(int argc, char ** argv) { int ret; void *adr = malloc(SPACE_LEN); if (!adr) return -1; ret = mlockall(MCL_CURRENT | MCL_FUTURE); printf("mlcokall ret = %d\n", ret); ret = munlockall(); printf("munlcokall ret = %d\n", ret); free(adr); return 0; } In __munlock_pagevec() we should decrement NR_MLOCK for each page where we clear the PageMlocked flag. Commit 1ebb7cc6a583 ("mm: munlock: batch NR_MLOCK zone state updates") has introduced a bug where we don't decrement NR_MLOCK for pages where we clear the flag, but fail to isolate them from the lru list (e.g. when the pages are on some other cpu's percpu pagevec). Since PageMlocked stays cleared, the NR_MLOCK accounting gets permanently disrupted by this. Fix it by counting the number of page whose PageMlock flag is cleared. Fixes: 1ebb7cc6a583 (" mm: munlock: batch NR_MLOCK zone state updates") Link: http://lkml.kernel.org/r/1495678405-54569-1-git-send-email-xieyisheng1@huawei.com Signed-off-by: Yisheng Xie <xieyisheng1@huawei.com> Reported-by: Kefeng Wang <wangkefeng.wang@huawei.com> Tested-by: Kefeng Wang <wangkefeng.wang@huawei.com> Cc: Vlastimil Babka <vbabka@suse.cz> Cc: Joern Engel <joern@logfs.org> Cc: Mel Gorman <mgorman@suse.de> Cc: Michel Lespinasse <walken@google.com> Cc: Hugh Dickins <hughd@google.com> Cc: Rik van Riel <riel@redhat.com> Cc: Johannes Weiner <hannes@cmpxchg.org> Cc: Michal Hocko <mhocko@suse.cz> Cc: Xishi Qiu <qiuxishi@huawei.com> Cc: zhongjiang <zhongjiang@huawei.com> Cc: Hanjun Guo <guohanjun@huawei.com> Cc: <stable@vger.kernel.org> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</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 unimac_mdio_probe(struct platform_device *pdev) { struct unimac_mdio_pdata *pdata = pdev->dev.platform_data; struct unimac_mdio_priv *priv; struct device_node *np; struct mii_bus *bus; struct resource *r; int ret; np = pdev->dev.of_node; priv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; r = platform_get_resource(pdev, IORESOURCE_MEM, 0); /* Just ioremap, as this MDIO block is usually integrated into an * Ethernet MAC controller register range */ priv->base = devm_ioremap(&pdev->dev, r->start, resource_size(r)); if (!priv->base) { dev_err(&pdev->dev, "failed to remap register\n"); return -ENOMEM; } priv->mii_bus = mdiobus_alloc(); if (!priv->mii_bus) return -ENOMEM; bus = priv->mii_bus; bus->priv = priv; if (pdata) { bus->name = pdata->bus_name; priv->wait_func = pdata->wait_func; priv->wait_func_data = pdata->wait_func_data; bus->phy_mask = ~pdata->phy_mask; } else { bus->name = "unimac MII bus"; priv->wait_func_data = priv; priv->wait_func = unimac_mdio_poll; } bus->parent = &pdev->dev; bus->read = unimac_mdio_read; bus->write = unimac_mdio_write; bus->reset = unimac_mdio_reset; snprintf(bus->id, MII_BUS_ID_SIZE, "%s-%d", pdev->name, pdev->id); ret = of_mdiobus_register(bus, np); if (ret) { dev_err(&pdev->dev, "MDIO bus registration failed\n"); goto out_mdio_free; } platform_set_drvdata(pdev, priv); dev_info(&pdev->dev, "Broadcom UniMAC MDIO bus at 0x%p\n", priv->base); return 0; out_mdio_free: mdiobus_free(bus); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'net: phy: mdio-bcm-unimac: fix potential NULL dereference in unimac_mdio_probe() platform_get_resource() may fail and return NULL, so we should better check it's return value to avoid a NULL pointer dereference a bit later in the code. This is detected by Coccinelle semantic patch. @@ expression pdev, res, n, t, e, e1, e2; @@ res = platform_get_resource(pdev, t, n); + if (!res) + return -EINVAL; ... when != res == NULL e = devm_ioremap(e1, res->start, e2); Signed-off-by: Wei Yongjun <weiyongjun1@huawei.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</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 af_get_page(AFFILE *af,int64_t pagenum,unsigned char *data,size_t *bytes) { uint32_t arg=0; size_t page_len=0; if (af_trace){ fprintf(af_trace,"af_get_page(%p,pagenum=%" I64d ",buf=%p,bytes=%u)\n",af,pagenum,data,(int)*bytes); } /* Find out the size of the segment and if it is compressed or not. * If we can't find it with new nomenclature, try the old one... */ int r = af_get_page_raw(af,pagenum,&arg,0,&page_len); if(r){ /* Segment doesn't exist. * If we have been provided with a buffer, * fill buffer with the 'bad segment' flag and return. */ if(data && (af->openmode & AF_BADBLOCK_FILL) && errno == ENOENT) { for(size_t i = 0;i <= af->image_pagesize - af->image_sectorsize; i+= af->image_sectorsize){ memcpy(data+i,af->badflag,af->image_sectorsize); af->bytes_memcpy += af->image_sectorsize; } r = 0; } return r; // segment doesn't exist } /* If the segment isn't compressed, just get it*/ uint32_t pageflag = 0; if((arg & AF_PAGE_COMPRESSED)==0){ if(data==0){ // if no data provided, just return size of the segment if requested if(bytes) *bytes = page_len; // set the number of bytes in the page if requested return 0; } int ret = af_get_page_raw(af,pagenum,&pageflag,data,bytes); if(*bytes > page_len) *bytes = page_len; // we only read this much if(ret!=0) return ret; // some error happened? } else { /* Allocate memory to hold the compressed segment */ unsigned char *compressed_data = (unsigned char *)malloc(page_len); size_t compressed_data_len = page_len; if(compressed_data==0){ return -2; // memory error } /* Get the data */ if(af_get_page_raw(af,pagenum,&pageflag,compressed_data,&compressed_data_len)){ free(compressed_data); return -3; // read error } /* Now uncompress directly into the buffer provided by the caller, unless the caller didn't * provide a buffer. If that happens, allocate our own... */ int res = -1; // 0 is success bool free_data = false; if(data==0){ data = (unsigned char *)malloc(af->image_pagesize); free_data = true; *bytes = af->image_pagesize; // I can hold this much } switch((pageflag & AF_PAGE_COMP_ALG_MASK)){ case AF_PAGE_COMP_ALG_ZERO: if(compressed_data_len != 4){ (*af->error_reporter)("ALG_ZERO compressed data is %d bytes, expected 4.",compressed_data_len); break; } memset(data,0,af->image_pagesize); *bytes = ntohl(*(long *)compressed_data); res = 0; // not very hard to decompress with the ZERO compressor. break; case AF_PAGE_COMP_ALG_ZLIB: res = uncompress(data,(uLongf *)bytes,compressed_data,compressed_data_len); switch(res){ case Z_OK: break; case Z_ERRNO: (*af->error_reporter)("Z_ERRNOR decompressing segment %" I64d,pagenum); case Z_STREAM_ERROR: (*af->error_reporter)("Z_STREAM_ERROR decompressing segment %" I64d,pagenum); case Z_DATA_ERROR: (*af->error_reporter)("Z_DATA_ERROR decompressing segment %" I64d,pagenum); case Z_MEM_ERROR: (*af->error_reporter)("Z_MEM_ERROR decompressing segment %" I64d,pagenum); case Z_BUF_ERROR: (*af->error_reporter)("Z_BUF_ERROR decompressing segment %" I64d,pagenum); case Z_VERSION_ERROR: (*af->error_reporter)("Z_VERSION_ERROR decompressing segment %" I64d,pagenum); default: (*af->error_reporter)("uncompress returned an invalid value in get_segment"); } break; #ifdef USE_LZMA case AF_PAGE_COMP_ALG_LZMA: res = lzma_uncompress(data,bytes,compressed_data,compressed_data_len); if (af_trace) fprintf(af_trace," LZMA decompressed page %" I64d ". %d bytes => %u bytes\n", pagenum,(int)compressed_data_len,(int)*bytes); switch(res){ case 0:break; // OK case 1:(*af->error_reporter)("LZMA header error decompressing segment %" I64d "\n",pagenum); break; case 2:(*af->error_reporter)("LZMA memory error decompressing segment %" I64d "\n",pagenum); break; } break; #endif default: (*af->error_reporter)("Unknown compression algorithm 0x%d", pageflag & AF_PAGE_COMP_ALG_MASK); break; } if(free_data){ free(data); data = 0; // restore the way it was } free(compressed_data); // don't need this one anymore af->pages_decompressed++; if(res!=Z_OK) return -1; } /* If the page size is larger than the sector_size, * make sure that the rest of the sector is zeroed, and that the * rest after that has the 'bad block' notation. */ if(data && (af->image_pagesize > af->image_sectorsize)){ const int SECTOR_SIZE = af->image_sectorsize; // for ease of typing size_t bytes_left_in_sector = (SECTOR_SIZE - (*bytes % SECTOR_SIZE)) % SECTOR_SIZE; for(size_t i=0;i<bytes_left_in_sector;i++){ data[*bytes + i] = 0; } size_t end_of_data = *bytes + bytes_left_in_sector; /* Now fill to the end of the page... */ for(size_t i = end_of_data; i <= af->image_pagesize-SECTOR_SIZE; i+=SECTOR_SIZE){ memcpy(data+i,af->badflag,SECTOR_SIZE); af->bytes_memcpy += SECTOR_SIZE; } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-295'], 'message': 'Sanity check size passed to malloc... Add sanity check before calling malloc in af_get_page() function to avoid undefined behavior (e.g., seg fault) when dealing with a corrupt AFF image with an invalid pagesize. Issue found by Luis Rocha (luiscrocha@gmail.com).'</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: zzip_mem_disk_findfirst(ZZIP_MEM_DISK* dir) { return zzip_disk_findfirst(dir->disk); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'memdisk (.)'</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: zzip_mem_disk_findmatch(ZZIP_MEM_DISK* dir, char* filespec, ZZIP_DISK_ENTRY* after, zzip_fnmatch_fn_t compare, int flags) { return zzip_disk_findmatch(dir->disk, filespec, after, compare, flags); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'memdisk (.)'</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 vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch, oggpack_buffer *b,int n){ long i,j,entry; int chptr=0; if(book->used_entries>0){ for(i=offset/ch;i<(offset+n)/ch;){ entry = decode_packed_entry_number(book,b); if(entry==-1)return(-1); { const float *t = book->valuelist+entry*book->dim; for (j=0;j<book->dim;j++){ a[chptr++][i]+=t[j]; if(chptr==ch){ chptr=0; i++; } } } } } return(0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2018-5146: Prevent out-of-bounds write in codebook decoding. Codebooks that are not an exact divisor of the partition size are now truncated to fit within the partition.'</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 sas_init_disc(struct sas_discovery *disc, struct asd_sas_port *port) { int i; static const work_func_t sas_event_fns[DISC_NUM_EVENTS] = { [DISCE_DISCOVER_DOMAIN] = sas_discover_domain, [DISCE_REVALIDATE_DOMAIN] = sas_revalidate_domain, [DISCE_PROBE] = sas_probe_devices, [DISCE_SUSPEND] = sas_suspend_devices, [DISCE_RESUME] = sas_resume_devices, [DISCE_DESTRUCT] = sas_destruct_devices, }; disc->pending = 0; for (i = 0; i < DISC_NUM_EVENTS; i++) { INIT_SAS_WORK(&disc->disc_work[i].work, sas_event_fns[i]); disc->disc_work[i].port = port; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284'], 'message': 'scsi: libsas: direct call probe and destruct In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery competing with ata error handling") introduced disco mutex to prevent rediscovery competing with ata error handling and put the whole revalidation in the mutex. But the rphy add/remove needs to wait for the error handling which also grabs the disco mutex. This may leads to dead lock.So the probe and destruct event were introduce to do the rphy add/remove asynchronously and out of the lock. The asynchronously processed workers makes the whole discovery process not atomic, the other events may interrupt the process. For example, if a loss of signal event inserted before the probe event, the sas_deform_port() is called and the port will be deleted. And sas_port_delete() may run before the destruct event, but the port-x:x is the top parent of end device or expander. This leads to a kernel WARNING such as: [ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22' [ 82.042983] ------------[ cut here ]------------ [ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237 sysfs_remove_group+0x94/0xa0 [ 82.043059] Call trace: [ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0 [ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70 [ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308 [ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60 [ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80 [ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0 [ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50 [ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0 [ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0 [ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490 [ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128 [ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50 Make probe and destruct a direct call in the disco and revalidate function, but put them outside the lock. The whole discovery or revalidate won't be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT event are deleted as a result of the direct call. Introduce a new list to destruct the sas_port and put the port delete after the destruct. This makes sure the right order of destroying the sysfs kobject and fix the warning above. In sas_ex_revalidate_domain() have a loop to find all broadcasted device, and sometimes we have a chance to find the same expander twice. Because the sas_port will be deleted at the end of the whole revalidate process, sas_port with the same name cannot be added before this. Otherwise the sysfs will complain of creating duplicate filename. Since the LLDD will send broadcast for every device change, we can only process one expander's revalidation. [mkp: kbuild test robot warning] Signed-off-by: Jason Yan <yanaijie@huawei.com> CC: John Garry <john.garry@huawei.com> CC: Johannes Thumshirn <jthumshirn@suse.de> CC: Ewan Milne <emilne@redhat.com> CC: Christoph Hellwig <hch@lst.de> CC: Tomas Henzl <thenzl@redhat.com> CC: Dan Williams <dan.j.williams@intel.com> Reviewed-by: Hannes Reinecke <hare@suse.com> Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>'</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 build_segment_manager(struct f2fs_sb_info *sbi) { struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi); struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi); struct f2fs_sm_info *sm_info; int err; sm_info = kzalloc(sizeof(struct f2fs_sm_info), GFP_KERNEL); if (!sm_info) return -ENOMEM; /* init sm info */ sbi->sm_info = sm_info; sm_info->seg0_blkaddr = le32_to_cpu(raw_super->segment0_blkaddr); sm_info->main_blkaddr = le32_to_cpu(raw_super->main_blkaddr); sm_info->segment_count = le32_to_cpu(raw_super->segment_count); sm_info->reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count); sm_info->ovp_segments = le32_to_cpu(ckpt->overprov_segment_count); sm_info->main_segments = le32_to_cpu(raw_super->segment_count_main); sm_info->ssa_blkaddr = le32_to_cpu(raw_super->ssa_blkaddr); sm_info->rec_prefree_segments = sm_info->main_segments * DEF_RECLAIM_PREFREE_SEGMENTS / 100; if (sm_info->rec_prefree_segments > DEF_MAX_RECLAIM_PREFREE_SEGMENTS) sm_info->rec_prefree_segments = DEF_MAX_RECLAIM_PREFREE_SEGMENTS; if (!test_opt(sbi, LFS)) sm_info->ipu_policy = 1 << F2FS_IPU_FSYNC; sm_info->min_ipu_util = DEF_MIN_IPU_UTIL; sm_info->min_fsync_blocks = DEF_MIN_FSYNC_BLOCKS; sm_info->min_hot_blocks = DEF_MIN_HOT_BLOCKS; sm_info->trim_sections = DEF_BATCHED_TRIM_SECTIONS; INIT_LIST_HEAD(&sm_info->sit_entry_set); if (test_opt(sbi, FLUSH_MERGE) && !f2fs_readonly(sbi->sb)) { err = create_flush_cmd_control(sbi); if (err) return err; } err = create_discard_cmd_control(sbi); if (err) return err; err = build_sit_info(sbi); if (err) return err; err = build_free_segmap(sbi); if (err) return err; err = build_curseg(sbi); if (err) return err; /* reinit free segmap based on SIT */ build_sit_entries(sbi); init_free_segmap(sbi); err = build_dirty_segmap(sbi); if (err) return err; init_min_max_mtime(sbi); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-476'], 'message': 'f2fs: fix a panic caused by NULL flush_cmd_control Mount fs with option noflush_merge, boot failed for illegal address fcc in function f2fs_issue_flush: if (!test_opt(sbi, FLUSH_MERGE)) { ret = submit_flush_wait(sbi); atomic_inc(&fcc->issued_flush); -> Here, fcc illegal return ret; } Signed-off-by: Yunlei He <heyunlei@huawei.com> Signed-off-by: Jaegeuk Kim <jaegeuk@kernel.org>'</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_enc_enccblks(jpc_enc_t *enc) { jpc_enc_tcmpt_t *tcmpt; jpc_enc_tcmpt_t *endcomps; jpc_enc_rlvl_t *lvl; jpc_enc_rlvl_t *endlvls; jpc_enc_band_t *band; jpc_enc_band_t *endbands; jpc_enc_cblk_t *cblk; jpc_enc_cblk_t *endcblks; int i; int j; jpc_fix_t mx; jpc_fix_t bmx; jpc_fix_t v; jpc_enc_tile_t *tile; uint_fast32_t prcno; jpc_enc_prc_t *prc; tile = enc->curtile; endcomps = &tile->tcmpts[tile->numtcmpts]; for (tcmpt = tile->tcmpts; tcmpt != endcomps; ++tcmpt) { endlvls = &tcmpt->rlvls[tcmpt->numrlvls]; for (lvl = tcmpt->rlvls; lvl != endlvls; ++lvl) { if (!lvl->bands) { continue; } endbands = &lvl->bands[lvl->numbands]; for (band = lvl->bands; band != endbands; ++band) { if (!band->data) { continue; } for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) { if (!prc->cblks) { continue; } bmx = 0; endcblks = &prc->cblks[prc->numcblks]; for (cblk = prc->cblks; cblk != endcblks; ++cblk) { mx = 0; for (i = 0; i < jas_matrix_numrows(cblk->data); ++i) { for (j = 0; j < jas_matrix_numcols(cblk->data); ++j) { v = JAS_ABS(jas_matrix_get(cblk->data, i, j)); if (v > mx) { mx = v; } } } if (mx > bmx) { bmx = mx; } cblk->numbps = JAS_MAX(jpc_firstone(mx) + 1 - JPC_NUMEXTRABITS, 0); } for (cblk = prc->cblks; cblk != endcblks; ++cblk) { cblk->numimsbs = band->numbps - cblk->numbps; assert(cblk->numimsbs >= 0); } for (cblk = prc->cblks; cblk != endcblks; ++cblk) { if (jpc_enc_enccblk(enc, cblk->stream, tcmpt, band, cblk)) { return -1; } } } } } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617'], 'message': 'jpc_math: split jpc_firstone() in int/jpc_fix_t overloads Fixes CVE-2018-9055 (denial of service via a reachable assertion due to integer overflow). Based on a patch from Fridrich Strba <fstrba@suse.com>. Instead of switching to `int_fast32_t`, this patch splits jpc_firstone() into two overloads, one for `int` and one for `jpc_fix_t`. This is safer against future changes on `jpc_fix_t`. To avoid the overhead of 64 bit integer math on 32 bit CPUs, this leaves the `int` overload around. Closes https://github.com/jasper-maint/jasper/issues/9'</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: rb_dir_s_empty_p(VALUE obj, VALUE dirname) { VALUE result, orig; const char *path; enum {false_on_notdir = 1}; GlobPathValue(dirname, FALSE); orig = rb_str_dup_frozen(dirname); dirname = rb_str_encode_ospath(dirname); dirname = rb_str_dup_frozen(dirname); path = RSTRING_PTR(dirname); #if defined HAVE_GETATTRLIST && defined ATTR_DIR_ENTRYCOUNT { u_int32_t attrbuf[SIZEUP32(fsobj_tag_t)]; struct attrlist al = {ATTR_BIT_MAP_COUNT, 0, ATTR_CMN_OBJTAG,}; if (getattrlist(path, &al, attrbuf, sizeof(attrbuf), 0) != 0) rb_sys_fail_path(orig); if (*(const fsobj_tag_t *)(attrbuf+1) == VT_HFS) { al.commonattr = 0; al.dirattr = ATTR_DIR_ENTRYCOUNT; if (getattrlist(path, &al, attrbuf, sizeof(attrbuf), 0) == 0) { if (attrbuf[0] >= 2 * sizeof(u_int32_t)) return attrbuf[1] ? Qfalse : Qtrue; if (false_on_notdir) return Qfalse; } rb_sys_fail_path(orig); } } #endif result = (VALUE)rb_thread_call_without_gvl(nogvl_dir_empty_p, (void *)path, RUBY_UBF_IO, 0); if (result == Qundef) { rb_sys_fail_path(orig); } return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'dir.c: check NUL bytes * dir.c (GlobPathValue): should be used in rb_push_glob only. other methods should use FilePathValue. https://hackerone.com/reports/302338 * dir.c (rb_push_glob): expand GlobPathValue git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@62989 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: static int snd_pcm_control_ioctl(struct snd_card *card, struct snd_ctl_file *control, unsigned int cmd, unsigned long arg) { switch (cmd) { case SNDRV_CTL_IOCTL_PCM_NEXT_DEVICE: { int device; if (get_user(device, (int __user *)arg)) return -EFAULT; mutex_lock(&register_mutex); device = snd_pcm_next(card, device); mutex_unlock(&register_mutex); if (put_user(device, (int __user *)arg)) return -EFAULT; return 0; } case SNDRV_CTL_IOCTL_PCM_INFO: { struct snd_pcm_info __user *info; unsigned int device, subdevice; int stream; struct snd_pcm *pcm; struct snd_pcm_str *pstr; struct snd_pcm_substream *substream; int err; info = (struct snd_pcm_info __user *)arg; if (get_user(device, &info->device)) return -EFAULT; if (get_user(stream, &info->stream)) return -EFAULT; if (stream < 0 || stream > 1) return -EINVAL; if (get_user(subdevice, &info->subdevice)) return -EFAULT; mutex_lock(&register_mutex); pcm = snd_pcm_get(card, device); if (pcm == NULL) { err = -ENXIO; goto _error; } pstr = &pcm->streams[stream]; if (pstr->substream_count == 0) { err = -ENOENT; goto _error; } if (subdevice >= pstr->substream_count) { err = -ENXIO; goto _error; } for (substream = pstr->substream; substream; substream = substream->next) if (substream->number == (int)subdevice) break; if (substream == NULL) { err = -ENXIO; goto _error; } err = snd_pcm_info_user(substream, info); _error: mutex_unlock(&register_mutex); return err; } case SNDRV_CTL_IOCTL_PCM_PREFER_SUBDEVICE: { int val; if (get_user(val, (int __user *)arg)) return -EFAULT; control->preferred_subdevice[SND_CTL_SUBDEV_PCM] = val; return 0; } } return -ENOIOCTLCMD; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'ALSA: pcm: prevent UAF in snd_pcm_info When the device descriptor is closed, the `substream->runtime` pointer is freed. But another thread may be in the ioctl handler, case SNDRV_CTL_IOCTL_PCM_INFO. This case calls snd_pcm_info_user() which calls snd_pcm_info() which accesses the now freed `substream->runtime`. Note: this fixes CVE-2017-0861 Signed-off-by: Robb Glasser <rglasser@google.com> Signed-off-by: Nick Desaulniers <ndesaulniers@google.com> Cc: <stable@vger.kernel.org> Signed-off-by: Takashi Iwai <tiwai@suse.de>'</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))) { jas_eprintf("cannot create tile\n"); return -1; } 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_fix_firstone(mxmag) + 1; } else { actualnumbps = jpc_fix_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-617'], 'message': 'jpc_enc: jpc_abstorelstepsize() returns error instead of aborting Fixes CVE-2018-9252 Closes https://github.com/jasper-maint/jasper/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: int ParseDsdiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t infilesize, total_samples; DFFFileHeader dff_file_header; DFFChunkHeader dff_chunk_header; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&dff_file_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &dff_file_header) + 4, sizeof (DFFFileHeader) - 4, &bcount) || bcount != sizeof (DFFFileHeader) - 4) || strncmp (dff_file_header.formType, "DSD ", 4)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_file_header, sizeof (DFFFileHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackBigEndianToNative (&dff_file_header, DFFFileHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && dff_file_header.ckDataSize && dff_file_header.ckDataSize + 1 && dff_file_header.ckDataSize + 12 != infilesize) { error_line ("%s is not a valid .DFF file (by total size)!", infilename); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line ("file header indicated length = %lld", dff_file_header.ckDataSize); #endif // loop through all elements of the DSDIFF header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &dff_chunk_header, sizeof (DFFChunkHeader), &bcount) || bcount != sizeof (DFFChunkHeader)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_chunk_header, sizeof (DFFChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (debug_logging_mode) error_line ("chunk header indicated length = %lld", dff_chunk_header.ckDataSize); if (!strncmp (dff_chunk_header.ckID, "FVER", 4)) { uint32_t version; if (dff_chunk_header.ckDataSize != sizeof (version) || !DoReadFile (infile, &version, sizeof (version), &bcount) || bcount != sizeof (version)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &version, sizeof (version))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&version, "L"); if (debug_logging_mode) error_line ("dsdiff file version = 0x%08x", version); } else if (!strncmp (dff_chunk_header.ckID, "PROP", 4)) { char *prop_chunk; if (dff_chunk_header.ckDataSize < 4 || dff_chunk_header.ckDataSize > 1024) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line ("got PROP chunk of %d bytes total", (int) dff_chunk_header.ckDataSize); prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize); if (!DoReadFile (infile, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize, &bcount) || bcount != dff_chunk_header.ckDataSize) { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (prop_chunk); return WAVPACK_SOFT_ERROR; } if (!strncmp (prop_chunk, "SND ", 4)) { char *cptr = prop_chunk + 4, *eptr = prop_chunk + dff_chunk_header.ckDataSize; uint16_t numChannels, chansSpecified, chanMask = 0; uint32_t sampleRate; while (eptr - cptr >= sizeof (dff_chunk_header)) { memcpy (&dff_chunk_header, cptr, sizeof (dff_chunk_header)); cptr += sizeof (dff_chunk_header); WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (eptr - cptr >= dff_chunk_header.ckDataSize) { if (!strncmp (dff_chunk_header.ckID, "FS ", 4) && dff_chunk_header.ckDataSize == 4) { memcpy (&sampleRate, cptr, sizeof (sampleRate)); WavpackBigEndianToNative (&sampleRate, "L"); cptr += dff_chunk_header.ckDataSize; if (debug_logging_mode) error_line ("got sample rate of %u Hz", sampleRate); } else if (!strncmp (dff_chunk_header.ckID, "CHNL", 4) && dff_chunk_header.ckDataSize >= 2) { memcpy (&numChannels, cptr, sizeof (numChannels)); WavpackBigEndianToNative (&numChannels, "S"); cptr += sizeof (numChannels); chansSpecified = (int)(dff_chunk_header.ckDataSize - sizeof (numChannels)) / 4; while (chansSpecified--) { if (!strncmp (cptr, "SLFT", 4) || !strncmp (cptr, "MLFT", 4)) chanMask |= 0x1; else if (!strncmp (cptr, "SRGT", 4) || !strncmp (cptr, "MRGT", 4)) chanMask |= 0x2; else if (!strncmp (cptr, "LS ", 4)) chanMask |= 0x10; else if (!strncmp (cptr, "RS ", 4)) chanMask |= 0x20; else if (!strncmp (cptr, "C ", 4)) chanMask |= 0x4; else if (!strncmp (cptr, "LFE ", 4)) chanMask |= 0x8; else if (debug_logging_mode) error_line ("undefined channel ID %c%c%c%c", cptr [0], cptr [1], cptr [2], cptr [3]); cptr += 4; } if (debug_logging_mode) error_line ("%d channels, mask = 0x%08x", numChannels, chanMask); } else if (!strncmp (dff_chunk_header.ckID, "CMPR", 4) && dff_chunk_header.ckDataSize >= 4) { if (strncmp (cptr, "DSD ", 4)) { error_line ("DSDIFF files must be uncompressed, not \"%c%c%c%c\"!", cptr [0], cptr [1], cptr [2], cptr [3]); free (prop_chunk); return WAVPACK_SOFT_ERROR; } cptr += dff_chunk_header.ckDataSize; } else { if (debug_logging_mode) error_line ("got PROP/SND chunk type \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); cptr += dff_chunk_header.ckDataSize; } } else { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } } if (chanMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this DSDIFF file already has channel order information!"); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (chanMask) config->channel_mask = chanMask; config->bits_per_sample = 8; config->bytes_per_sample = 1; config->num_channels = numChannels; config->sample_rate = sampleRate / 8; config->qmode |= QMODE_DSD_MSB_FIRST; } else if (debug_logging_mode) error_line ("got unknown PROP chunk type \"%c%c%c%c\" of %d bytes", prop_chunk [0], prop_chunk [1], prop_chunk [2], prop_chunk [3], dff_chunk_header.ckDataSize); free (prop_chunk); } else if (!strncmp (dff_chunk_header.ckID, "DSD ", 4)) { total_samples = dff_chunk_header.ckDataSize / config->num_channels; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (int)(((dff_chunk_header.ckDataSize) + 1) & ~(int64_t)1); char *buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (debug_logging_mode) error_line ("setting configuration with %lld samples", total_samples); if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'issue #33, sanitize size of unknown chunks before malloc()'</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: virtual bool ms_verify_authorizer(Connection *con, int peer_type, int protocol, bufferlist& authorizer, bufferlist& authorizer_reply, bool& isvalid, CryptoKey& session_key) { /* always succeed */ isvalid = true; return true; }; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge Allow the accepting side of a connection to reject an initial authorizer with a random challenge. The connecting side then has to respond with an updated authorizer proving they are able to decrypt the service's challenge and that the new authorizer was produced for this specific connection instance. The accepting side requires this challenge and response unconditionally if the client side advertises they have the feature bit. Servers wishing to require this improved level of authentication simply have to require the appropriate feature. Signed-off-by: Sage Weil <sage@redhat.com> (cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b) # Conflicts: # src/auth/Auth.h # src/auth/cephx/CephxProtocol.cc # src/auth/cephx/CephxProtocol.h # src/auth/none/AuthNoneProtocol.h # src/msg/Dispatcher.h # src/msg/async/AsyncConnection.cc - const_iterator - ::decode vs decode - AsyncConnection ctor arg noise - get_random_bytes(), not cct->random()'</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 ms_deliver_verify_authorizer(Connection *con, int peer_type, int protocol, bufferlist& authorizer, bufferlist& authorizer_reply, bool& isvalid, CryptoKey& session_key) { for (list<Dispatcher*>::iterator p = dispatchers.begin(); p != dispatchers.end(); ++p) { if ((*p)->ms_verify_authorizer(con, peer_type, protocol, authorizer, authorizer_reply, isvalid, session_key)) return true; } return false; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge Allow the accepting side of a connection to reject an initial authorizer with a random challenge. The connecting side then has to respond with an updated authorizer proving they are able to decrypt the service's challenge and that the new authorizer was produced for this specific connection instance. The accepting side requires this challenge and response unconditionally if the client side advertises they have the feature bit. Servers wishing to require this improved level of authentication simply have to require the appropriate feature. Signed-off-by: Sage Weil <sage@redhat.com> (cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b) # Conflicts: # src/auth/Auth.h # src/auth/cephx/CephxProtocol.cc # src/auth/cephx/CephxProtocol.h # src/auth/none/AuthNoneProtocol.h # src/msg/Dispatcher.h # src/msg/async/AsyncConnection.cc - const_iterator - ::decode vs decode - AsyncConnection ctor arg noise - get_random_bytes(), not cct->random()'</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 MDSDaemon::ms_verify_authorizer(Connection *con, int peer_type, int protocol, bufferlist& authorizer_data, bufferlist& authorizer_reply, bool& is_valid, CryptoKey& session_key) { Mutex::Locker l(mds_lock); if (stopping) { return false; } if (beacon.get_want_state() == CEPH_MDS_STATE_DNE) return false; AuthAuthorizeHandler *authorize_handler = 0; switch (peer_type) { case CEPH_ENTITY_TYPE_MDS: authorize_handler = authorize_handler_cluster_registry->get_handler(protocol); break; default: authorize_handler = authorize_handler_service_registry->get_handler(protocol); } if (!authorize_handler) { dout(0) << "No AuthAuthorizeHandler found for protocol " << protocol << dendl; is_valid = false; return true; } AuthCapsInfo caps_info; EntityName name; uint64_t global_id; RotatingKeyRing *keys = monc->rotating_secrets.get(); if (keys) { is_valid = authorize_handler->verify_authorizer( cct, keys, authorizer_data, authorizer_reply, name, global_id, caps_info, session_key); } else { dout(10) << __func__ << " no rotating_keys (yet), denied" << dendl; is_valid = false; } if (is_valid) { entity_name_t n(con->get_peer_type(), global_id); // We allow connections and assign Session instances to connections // even if we have not been assigned a rank, because clients with // "allow *" are allowed to connect and do 'tell' operations before // we have a rank. Session *s = NULL; if (mds_rank) { // If we do hold a rank, see if this is an existing client establishing // a new connection, rather than a new client s = mds_rank->sessionmap.get_session(n); } // Wire up a Session* to this connection // It doesn't go into a SessionMap instance until it sends an explicit // request to open a session (initial state of Session is `closed`) if (!s) { s = new Session; s->info.auth_name = name; s->info.inst.addr = con->get_peer_addr(); s->info.inst.name = n; dout(10) << " new session " << s << " for " << s->info.inst << " con " << con << dendl; con->set_priv(s); s->connection = con; } else { dout(10) << " existing session " << s << " for " << s->info.inst << " existing con " << s->connection << ", new/authorizing con " << con << dendl; con->set_priv(s->get()); // Wait until we fully accept the connection before setting // s->connection. In particular, if there are multiple incoming // connection attempts, they will all get their authorizer // validated, but some of them may "lose the race" and get // dropped. We only want to consider the winner(s). See // ms_handle_accept(). This is important for Sessions we replay // from the journal on recovery that don't have established // messenger state; we want the con from only the winning // connect attempt(s). (Normal reconnects that don't follow MDS // recovery are reconnected to the existing con by the // messenger.) } if (caps_info.allow_all) { // Flag for auth providers that don't provide cap strings s->auth_caps.set_allow_all(); } else { bufferlist::iterator p = caps_info.caps.begin(); string auth_cap_str; try { ::decode(auth_cap_str, p); dout(10) << __func__ << ": parsing auth_cap_str='" << auth_cap_str << "'" << dendl; std::ostringstream errstr; if (!s->auth_caps.parse(g_ceph_context, auth_cap_str, &errstr)) { dout(1) << __func__ << ": auth cap parse error: " << errstr.str() << " parsing '" << auth_cap_str << "'" << dendl; clog->warn() << name << " mds cap '" << auth_cap_str << "' does not parse: " << errstr.str(); is_valid = false; } } catch (buffer::error& e) { // Assume legacy auth, defaults to: // * permit all filesystem ops // * permit no `tell` ops dout(1) << __func__ << ": cannot decode auth caps bl of length " << caps_info.caps.length() << dendl; is_valid = false; } } } return true; // we made a decision (see is_valid) } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge Allow the accepting side of a connection to reject an initial authorizer with a random challenge. The connecting side then has to respond with an updated authorizer proving they are able to decrypt the service's challenge and that the new authorizer was produced for this specific connection instance. The accepting side requires this challenge and response unconditionally if the client side advertises they have the feature bit. Servers wishing to require this improved level of authentication simply have to require the appropriate feature. Signed-off-by: Sage Weil <sage@redhat.com> (cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b) # Conflicts: # src/auth/Auth.h # src/auth/cephx/CephxProtocol.cc # src/auth/cephx/CephxProtocol.h # src/auth/none/AuthNoneProtocol.h # src/msg/Dispatcher.h # src/msg/async/AsyncConnection.cc - const_iterator - ::decode vs decode - AsyncConnection ctor arg noise - get_random_bytes(), not cct->random()'</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 cdrom_ioctl_media_changed(struct cdrom_device_info *cdi, unsigned long arg) { struct cdrom_changer_info *info; int ret; cd_dbg(CD_DO_IOCTL, "entering CDROM_MEDIA_CHANGED\n"); if (!CDROM_CAN(CDC_MEDIA_CHANGED)) return -ENOSYS; /* cannot select disc or select current disc */ if (!CDROM_CAN(CDC_SELECT_DISC) || arg == CDSL_CURRENT) return media_changed(cdi, 1); if ((unsigned int)arg >= cdi->capacity) return -EINVAL; info = kmalloc(sizeof(*info), GFP_KERNEL); if (!info) return -ENOMEM; ret = cdrom_read_mech_status(cdi, info); if (!ret) ret = info->slots[arg].change; kfree(info); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'cdrom: information leak in cdrom_ioctl_media_changed() This cast is wrong. "cdi->capacity" is an int and "arg" is an unsigned long. The way the check is written now, if one of the high 32 bits is set then we could read outside the info->slots[] array. This bug is pretty old and it predates git. Reviewed-by: Christoph Hellwig <hch@lst.de> Cc: stable@vger.kernel.org Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Signed-off-by: Jens Axboe <axboe@kernel.dk>'</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 ldb_kv_search_dn1(struct ldb_module *module, struct ldb_dn *dn, struct ldb_message *msg, unsigned int unpack_flags) { void *data = ldb_module_get_private(module); struct ldb_kv_private *ldb_kv = talloc_get_type(data, struct ldb_kv_private); int ret; uint8_t guid_key[LDB_KV_GUID_KEY_SIZE]; struct ldb_val key = { .data = guid_key, .length = sizeof(guid_key) }; TALLOC_CTX *tdb_key_ctx = NULL; if (ldb_kv->cache->GUID_index_attribute == NULL || ldb_dn_is_special(dn)) { tdb_key_ctx = talloc_new(msg); if (!tdb_key_ctx) { return ldb_module_oom(module); } /* form the key */ key = ldb_kv_key_dn(module, tdb_key_ctx, dn); if (!key.data) { TALLOC_FREE(tdb_key_ctx); return LDB_ERR_OPERATIONS_ERROR; } } else { /* * Look in the index to find the key for this DN. * * the tdb_key memory is allocated above, msg is just * used for internal memory. * */ ret = ldb_kv_key_dn_from_idx(module, ldb_kv, msg, dn, &key); if (ret != LDB_SUCCESS) { return ret; } } ret = ldb_kv_search_key(module, ldb_kv, key, msg, unpack_flags); TALLOC_FREE(tdb_key_ctx); if (ret != LDB_SUCCESS) { return ret; } if ((unpack_flags & LDB_UNPACK_DATA_FLAG_NO_DN) == 0) { if (!msg->dn) { msg->dn = ldb_dn_copy(msg, dn); } if (!msg->dn) { return LDB_ERR_OPERATIONS_ERROR; } } return LDB_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'CVE-2018-1140 ldb_tdb: Check for DN validity in add, rename and search This ensures we fail with a good error code before an eventual ldb_dn_get_casefold() which would otherwise fail. Signed-off-by: Andrew Bartlett <abartlet@samba.org> Reviewed-by: Douglas Bagnall <douglas.bagnall@catalyst.net.nz> BUG: https://bugzilla.samba.org/show_bug.cgi?id=13374'</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: PackLinuxElf64::check_pt_dynamic(Elf64_Phdr const *const phdr) { upx_uint64_t t = get_te64(&phdr->p_offset), s = sizeof(Elf64_Dyn) + t; upx_uint64_t filesz = get_te64(&phdr->p_filesz), memsz = get_te64(&phdr->p_memsz); if (s < t || (upx_uint64_t)file_size < s || (7 & t) || (0xf & (filesz | memsz)) // .balign 8; 16==sizeof(Elf64_Dyn) || filesz < sizeof(Elf64_Dyn) || memsz < sizeof(Elf64_Dyn) || filesz < memsz) { char msg[50]; snprintf(msg, sizeof(msg), "bad PT_DYNAMIC phdr[%u]", (unsigned)(phdr - phdri)); throwCantPack(msg); } sz_dynseg = memsz; return t; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'More checking of PT_DYNAMIC and its contents. https://github.com/upx/upx/issues/206 modified: p_lx_elf.cpp'</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 bool _is_valid_will_run_user(job_desc_msg_t *job_desc_msg, uid_t uid) { char *account = NULL; if ((uid == job_desc_msg->user_id) || validate_operator(uid)) return true; if (job_desc_msg->job_id != NO_VAL) { struct job_record *job_ptr; job_ptr = find_job_record(job_desc_msg->job_id); if (job_ptr) account = job_ptr->account; } else if (job_desc_msg->account) account = job_desc_msg->account; if (account && assoc_mgr_is_user_acct_coord(acct_db_conn, uid, account)) return true; return false; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix insecure handling of job requested gid. Only trust MUNGE signed values, unless the RPC was signed by SlurmUser or root. CVE-2018-10995.'</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: zstatus(i_ctx_t *i_ctx_p) { os_ptr op = osp; switch (r_type(op)) { case t_file: { stream *s; make_bool(op, (file_is_valid(s, op) ? 1 : 0)); } return 0; case t_string: { gs_parsed_file_name_t pname; struct stat fstat; int code = parse_file_name(op, &pname, i_ctx_p->LockFilePermissions, imemory); if (code < 0) { if (code == gs_error_undefinedfilename) { make_bool(op, 0); code = 0; } return code; } code = gs_terminate_file_name(&pname, imemory, "status"); if (code < 0) return code; code = (*pname.iodev->procs.file_status)(pname.iodev, pname.fname, &fstat); switch (code) { case 0: check_ostack(4); /* * Check to make sure that the file size fits into * a PostScript integer. (On some systems, long is * 32 bits, but file sizes are 64 bits.) */ push(4); make_int(op - 4, stat_blocks(&fstat)); make_int(op - 3, fstat.st_size); /* * We can't check the value simply by using ==, * because signed/unsigned == does the wrong thing. * Instead, since integer assignment only keeps the * bottom bits, we convert the values to double * and then test for equality. This handles all * cases of signed/unsigned or width mismatch. */ if ((double)op[-4].value.intval != (double)stat_blocks(&fstat) || (double)op[-3].value.intval != (double)fstat.st_size ) return_error(gs_error_limitcheck); make_int(op - 2, fstat.st_mtime); make_int(op - 1, fstat.st_ctime); make_bool(op, 1); break; case gs_error_undefinedfilename: make_bool(op, 0); code = 0; } gs_free_file_name(&pname, "status"); return code; } default: return_op_typecheck(op); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Bug 697193: status operator honour SAFER option'</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 stub_device_rebind(void) { #if IS_MODULE(CONFIG_USBIP_HOST) struct bus_id_priv *busid_priv; int i; /* update status to STUB_BUSID_OTHER so probe ignores the device */ spin_lock(&busid_table_lock); for (i = 0; i < MAX_BUSID; i++) { if (busid_table[i].name[0] && busid_table[i].shutdown_busid) { busid_priv = &(busid_table[i]); busid_priv->status = STUB_BUSID_OTHER; } } spin_unlock(&busid_table_lock); /* now run rebind */ for (i = 0; i < MAX_BUSID; i++) { if (busid_table[i].name[0] && busid_table[i].shutdown_busid) { busid_priv = &(busid_table[i]); do_rebind(busid_table[i].name, busid_priv); } } #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'usbip: usbip_host: fix NULL-ptr deref and use-after-free errors usbip_host updates device status without holding lock from stub probe, disconnect and rebind code paths. When multiple requests to import a device are received, these unprotected code paths step all over each other and drive fails with NULL-ptr deref and use-after-free errors. The driver uses a table lock to protect the busid array for adding and deleting busids to the table. However, the probe, disconnect and rebind paths get the busid table entry and update the status without holding the busid table lock. Add a new finer grain lock to protect the busid entry. This new lock will be held to search and update the busid entry fields from get_busid_idx(), add_match_busid() and del_match_busid(). match_busid_show() does the same to access the busid entry fields. get_busid_priv() changed to return the pointer to the busid entry holding the busid lock. stub_probe(), stub_disconnect() and stub_device_rebind() call put_busid_priv() to release the busid lock before returning. This changes fixes the unprotected code paths eliminating the race conditions in updating the busid entries. Reported-by: Jakub Jirasek Signed-off-by: Shuah Khan (Samsung OSG) <shuah@kernel.org> Cc: stable <stable@kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>'</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: Statement_Ptr Expand::operator()(Debug_Ptr d) { // eval handles this too, because warnings may occur in functions d->perform(&eval); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix segfault on empty custom properties Originally reported in sass/sassc#225 Fixes sass/sassc#225 Spec sass/sass-spec#1249'</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 controloptions (lua_State *L, int opt, const char **fmt, Header *h) { switch (opt) { case ' ': return; /* ignore white spaces */ case '>': h->endian = BIG; return; case '<': h->endian = LITTLE; return; case '!': { int a = getnum(L, fmt, MAXALIGN); if (!isp2(a)) luaL_error(L, "alignment %d is not a power of 2", a); h->align = a; return; } default: { const char *msg = lua_pushfstring(L, "invalid format option '%c'", opt); luaL_argerror(L, 1, msg); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-787'], 'message': 'Security: update Lua struct package for security. During an auditing Apple found that the "struct" Lua package we ship with Redis (http://www.inf.puc-rio.br/~roberto/struct/) contains a security problem. A bound-checking statement fails because of integer overflow. The bug exists since we initially integrated this package with Lua, when scripting was introduced, so every version of Redis with EVAL/EVALSHA capabilities exposed is affected. Instead of just fixing the bug, the library was updated to the latest version shipped by the author.'</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 mp_unpack_full(lua_State *L, int limit, int offset) { size_t len; const char *s; mp_cur c; int cnt; /* Number of objects unpacked */ int decode_all = (!limit && !offset); s = luaL_checklstring(L,1,&len); /* if no match, exits */ if (offset < 0 || limit < 0) /* requesting negative off or lim is invalid */ return luaL_error(L, "Invalid request to unpack with offset of %d and limit of %d.", offset, len); else if (offset > len) return luaL_error(L, "Start offset %d greater than input length %d.", offset, len); if (decode_all) limit = INT_MAX; mp_cur_init(&c,(const unsigned char *)s+offset,len-offset); /* We loop over the decode because this could be a stream * of multiple top-level values serialized together */ for(cnt = 0; c.left > 0 && cnt < limit; cnt++) { mp_decode_to_lua_type(L,&c); if (c.err == MP_CUR_ERROR_EOF) { return luaL_error(L,"Missing bytes in input."); } else if (c.err == MP_CUR_ERROR_BADFMT) { return luaL_error(L,"Bad data format in input."); } } if (!decode_all) { /* c->left is the remaining size of the input buffer. * subtract the entire buffer size from the unprocessed size * to get our next start offset */ int offset = len - c.left; /* Return offset -1 when we have have processed the entire buffer. */ lua_pushinteger(L, c.left == 0 ? -1 : offset); /* Results are returned with the arg elements still * in place. Lua takes care of only returning * elements above the args for us. * In this case, we have one arg on the stack * for this function, so we insert our first return * value at position 2. */ lua_insert(L, 2); cnt += 1; /* increase return count by one to make room for offset */ } return cnt; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Security: more cmsgpack fixes by @soloestoy. @soloestoy sent me this additional fixes, after searching for similar problems to the one reported in mp_pack(). I'm committing the changes because it was not possible during to make a public PR to protect Redis users and give Redis providers some time to patch their systems.'</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: create_file(ngx_cycle_t *cycle, const u_char *filename, const u_char *contents, size_t len) { FILE *f; int ret; size_t total_written = 0, written; f = fopen((const char *) filename, "w"); if (f != NULL) { /* We must do something with these return values because * otherwise on some platforms it will cause a compiler * warning. */ do { ret = fchmod(fileno(f), S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); } while (ret == -1 && errno == EINTR); do { written = fwrite(contents + total_written, 1, len - total_written, f); total_written += written; } while (total_written < len); fclose(f); return NGX_OK; } else { ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno, "could not create %s", filename); return NGX_ERROR; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Fix privilege escalation in the Nginx module The vulnerability is exploitable with a non-standard passenger_instance_registry_dir, via a race condition where after a file was created, it was chowned via the path not the file descriptor. The chown entered the code in 2010, so Passenger 4 + 5 all affected.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception) { BMPInfo bmp_info; Image *image; IndexPacket index; MagickBooleanType status; MagickOffsetType offset, start_position; MemoryInfo *pixel_info; register IndexPacket *indexes; register PixelPacket *q; register ssize_t i, x; register unsigned char *p; size_t bit, bytes_per_line, length; ssize_t count, y; unsigned char magick[12], *pixels; unsigned int blue, green, offset_bits, red; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a BMP file. */ (void) memset(&bmp_info,0,sizeof(bmp_info)); bmp_info.ba_offset=0; start_position=0; offset_bits=0; count=ReadBlob(image,2,magick); if (count != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { LongPixelPacket shift; PixelPacket quantum_bits; /* Verify BMP identifier. */ if (bmp_info.ba_offset == 0) start_position=TellBlob(image)-2; bmp_info.ba_offset=0; while (LocaleNCompare((char *) magick,"BA",2) == 0) { bmp_info.file_size=ReadBlobLSBLong(image); bmp_info.ba_offset=ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); count=ReadBlob(image,2,magick); if (count != 2) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Magick: %c%c", magick[0],magick[1]); if ((count != 2) || ((LocaleNCompare((char *) magick,"BM",2) != 0) && (LocaleNCompare((char *) magick,"CI",2) != 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bmp_info.file_size=ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " File_size in header: %u bytes",bmp_info.file_size); bmp_info.offset_bits=ReadBlobLSBLong(image); bmp_info.size=ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," BMP size: %u", bmp_info.size); if (bmp_info.size == 12) { /* OS/2 BMP image file. */ (void) CopyMagickString(image->magick,"BMP2",MaxTextExtent); bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.x_pixels=0; bmp_info.y_pixels=0; bmp_info.number_colors=0; bmp_info.compression=BI_RGB; bmp_info.image_size=0; bmp_info.alpha_mask=0; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: OS/2 Bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); } } else { /* Microsoft Windows BMP image file. */ if (bmp_info.size < 40) ThrowReaderException(CorruptImageError,"NonOS2HeaderSizeError"); bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.compression=ReadBlobLSBLong(image); bmp_info.image_size=ReadBlobLSBLong(image); bmp_info.x_pixels=ReadBlobLSBLong(image); bmp_info.y_pixels=ReadBlobLSBLong(image); bmp_info.number_colors=ReadBlobLSBLong(image); bmp_info.colors_important=ReadBlobLSBLong(image); if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: MS Windows bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Bits per pixel: %.20g",(double) bmp_info.bits_per_pixel); switch (bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RGB"); break; } case BI_RLE4: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE4"); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE8"); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_BITFIELDS"); break; } case BI_PNG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_PNG"); break; } case BI_JPEG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_JPEG"); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: UNKNOWN (%u)",bmp_info.compression); } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %u",bmp_info.number_colors); } bmp_info.red_mask=ReadBlobLSBLong(image); bmp_info.green_mask=ReadBlobLSBLong(image); bmp_info.blue_mask=ReadBlobLSBLong(image); if (bmp_info.size > 40) { double gamma; /* Read color management information. */ bmp_info.alpha_mask=ReadBlobLSBLong(image); bmp_info.colorspace=ReadBlobLSBSignedLong(image); /* Decode 2^30 fixed point formatted CIE primaries. */ # define BMP_DENOM ((double) 0x40000000) bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+ bmp_info.red_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.red_primary.x*=gamma; bmp_info.red_primary.y*=gamma; image->chromaticity.red_primary.x=bmp_info.red_primary.x; image->chromaticity.red_primary.y=bmp_info.red_primary.y; gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+ bmp_info.green_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.green_primary.x*=gamma; bmp_info.green_primary.y*=gamma; image->chromaticity.green_primary.x=bmp_info.green_primary.x; image->chromaticity.green_primary.y=bmp_info.green_primary.y; gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+ bmp_info.blue_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.blue_primary.x*=gamma; bmp_info.blue_primary.y*=gamma; image->chromaticity.blue_primary.x=bmp_info.blue_primary.x; image->chromaticity.blue_primary.y=bmp_info.blue_primary.y; /* Decode 16^16 fixed point formatted gamma_scales. */ bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000; /* Compute a single gamma from the BMP 3-channel gamma. */ image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+ bmp_info.gamma_scale.z)/3.0; } else (void) CopyMagickString(image->magick,"BMP3",MaxTextExtent); if (bmp_info.size > 108) { size_t intent; /* Read BMP Version 5 color management information. */ intent=ReadBlobLSBLong(image); switch ((int) intent) { case LCS_GM_BUSINESS: { image->rendering_intent=SaturationIntent; break; } case LCS_GM_GRAPHICS: { image->rendering_intent=RelativeIntent; break; } case LCS_GM_IMAGES: { image->rendering_intent=PerceptualIntent; break; } case LCS_GM_ABS_COLORIMETRIC: { image->rendering_intent=AbsoluteIntent; break; } } (void) ReadBlobLSBLong(image); /* Profile data */ (void) ReadBlobLSBLong(image); /* Profile size */ (void) ReadBlobLSBLong(image); /* Reserved byte */ } } if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "LengthAndFilesizeDoNotMatch","`%s'",image->filename); else if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"LengthAndFilesizeDoNotMatch","`%s'", image->filename); if (bmp_info.width <= 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.height == 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.planes != 1) ThrowReaderException(CorruptImageError,"StaticPlanesValueNotEqualToOne"); if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) && (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) && (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if (bmp_info.bits_per_pixel < 16 && bmp_info.number_colors > (1U << bmp_info.bits_per_pixel)) ThrowReaderException(CorruptImageError,"UnrecognizedNumberOfColors"); if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); switch (bmp_info.compression) { case BI_RGB: image->compression=NoCompression; break; case BI_RLE8: case BI_RLE4: image->compression=RLECompression; break; case BI_BITFIELDS: break; case BI_JPEG: ThrowReaderException(CoderError,"JPEGCompressNotSupported"); case BI_PNG: ThrowReaderException(CoderError,"PNGCompressNotSupported"); default: ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression"); } image->columns=(size_t) MagickAbsoluteValue(bmp_info.width); image->rows=(size_t) MagickAbsoluteValue(bmp_info.height); image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8; image->matte=((bmp_info.alpha_mask != 0) && (bmp_info.compression == BI_BITFIELDS)) ? MagickTrue : MagickFalse; if (bmp_info.bits_per_pixel < 16) { size_t one; image->storage_class=PseudoClass; image->colors=bmp_info.number_colors; one=1; if (image->colors == 0) image->colors=one << bmp_info.bits_per_pixel; } image->x_resolution=(double) bmp_info.x_pixels/100.0; image->y_resolution=(double) bmp_info.y_pixels/100.0; image->units=PixelsPerCentimeterResolution; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; size_t packet_size; /* Read BMP raster colormap. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading colormap of %.20g colors",(double) image->colors); if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if ((bmp_info.size == 12) || (bmp_info.size == 64)) packet_size=3; else packet_size=4; offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET); if (offset < 0) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,packet_size*image->colors,bmp_colormap); if (count != (ssize_t) (packet_size*image->colors)) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } p=bmp_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=ScaleCharToQuantum(*p++); image->colormap[i].green=ScaleCharToQuantum(*p++); image->colormap[i].red=ScaleCharToQuantum(*p++); if (packet_size == 4) p++; } bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } /* Read image data. */ if (bmp_info.offset_bits == offset_bits) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); offset_bits=bmp_info.offset_bits; offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (bmp_info.compression == BI_RLE4) bmp_info.bits_per_pixel<<=1; bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); length=(size_t) bytes_per_line*image->rows; if (((MagickSizeType) length/8) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); if ((bmp_info.compression == BI_RGB) || (bmp_info.compression == BI_BITFIELDS)) { pixel_info=AcquireVirtualMemory((size_t) image->rows, MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading pixels (%.20g bytes)",(double) length); count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } } else { /* Convert run-length encoded raster pixels. */ pixel_info=AcquireVirtualMemory((size_t) image->rows, MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); status=DecodeImage(image,bmp_info.compression,pixels, image->columns*image->rows); if (status == MagickFalse) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnableToRunlengthDecodeImage"); } } /* Convert BMP raster image to pixel packets. */ if (bmp_info.compression == BI_RGB) { /* We should ignore the alpha value in BMP3 files but there have been reports about 32 bit files with alpha. We do a quick check to see if the alpha channel contains a value that is not zero (default value). If we find a non zero value we asume the program that wrote the file wants to use the alpha channel. */ if ((image->matte == MagickFalse) && (bmp_info.size == 40) && (bmp_info.bits_per_pixel == 32)) { bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { if (*(p+3) != 0) { image->matte=MagickTrue; y=-1; break; } p+=4; } } } bmp_info.alpha_mask=image->matte != MagickFalse ? 0xff000000U : 0U; bmp_info.red_mask=0x00ff0000U; bmp_info.green_mask=0x0000ff00U; bmp_info.blue_mask=0x000000ffU; if (bmp_info.bits_per_pixel == 16) { /* RGB555. */ bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; } } (void) memset(&shift,0,sizeof(shift)); (void) memset(&quantum_bits,0,sizeof(quantum_bits)); if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32)) { register size_t sample; /* Get shift and quantum bits info from bitfield masks. */ if (bmp_info.red_mask != 0) while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0) { shift.red++; if (shift.red > 32U) break; } if (bmp_info.green_mask != 0) while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0) { shift.green++; if (shift.green > 32U) break; } if (bmp_info.blue_mask != 0) while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0) { shift.blue++; if (shift.blue > 32U) break; } if (bmp_info.alpha_mask != 0) while (((bmp_info.alpha_mask << shift.opacity) & 0x80000000UL) == 0) { shift.opacity++; if (shift.opacity > 32U) break; } sample=shift.red; while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample > 32U) break; } quantum_bits.red=ClampToQuantum((MagickRealType) sample-shift.red); sample=shift.green; while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample > 32U) break; } quantum_bits.green=ClampToQuantum((MagickRealType) sample-shift.green); sample=shift.blue; while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample > 32U) break; } quantum_bits.blue=ClampToQuantum((MagickRealType) sample-shift.blue); sample=shift.opacity; while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample > 32U) break; } quantum_bits.opacity=ClampToQuantum((MagickRealType) sample- shift.opacity); } switch (bmp_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); q++; } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (image->columns % 8); bit++) { index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 4: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-1); x+=2) { (void) IsValidColormapIndex(image,(ssize_t) ((*p >> 4) & 0x0f), &index,exception); SetPixelIndex(indexes+x,index); (void) IsValidColormapIndex(image,(ssize_t) (*p & 0x0f),&index, exception); SetPixelIndex(indexes+x+1,index); p++; } if ((image->columns % 2) != 0) { (void) IsValidColormapIndex(image,(ssize_t) ((*p >> 4) & 0xf), &index,exception); SetPixelIndex(indexes+(x++),index); p++; } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 8: { /* Convert PseudoColor scanline. */ if ((bmp_info.compression == BI_RLE8) || (bmp_info.compression == BI_RLE4)) bytes_per_line=image->columns; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=(ssize_t) image->columns; x != 0; --x) { (void) IsValidColormapIndex(image,(ssize_t) *p,&index,exception); SetPixelIndex(indexes,index); indexes++; p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 16: { unsigned int alpha, pixel; /* Convert bitfield encoded 16-bit PseudoColor scanline. */ if (bmp_info.compression != BI_RGB && bmp_info.compression != BI_BITFIELDS) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=2*(image->columns+image->columns % 2); image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=(*p++) << 8; red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 5) red|=((red & 0xe000) >> 5); if (quantum_bits.red <= 8) red|=((red & 0xff00) >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 5) green|=((green & 0xe000) >> 5); if (quantum_bits.green == 6) green|=((green & 0xc000) >> 6); if (quantum_bits.green <= 8) green|=((green & 0xff00) >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 5) blue|=((blue & 0xe000) >> 5); if (quantum_bits.blue <= 8) blue|=((blue & 0xff00) >> 8); SetPixelRed(q,ScaleShortToQuantum((unsigned short) red)); SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green)); SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16; if (quantum_bits.opacity <= 8) alpha|=((alpha & 0xff00) >> 8); SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha)); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectColor scanline. */ bytes_per_line=4*((image->columns*24+31)/32); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelOpacity(q,OpaqueOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert bitfield encoded DirectColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { unsigned int alpha, pixel; p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=((unsigned int) *p++ << 8); pixel|=((unsigned int) *p++ << 16); pixel|=((unsigned int) *p++ << 24); red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 8) red|=(red >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 8) green|=(green >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 8) blue|=(blue >> 8); SetPixelRed(q,ScaleShortToQuantum((unsigned short) red)); SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green)); SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue)); SetPixelAlpha(q,OpaqueOpacity); if (image->matte != MagickFalse) { alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16; if (quantum_bits.opacity == 8) alpha|=(alpha >> 8); SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha)); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } default: { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } } pixel_info=RelinquishVirtualMemory(pixel_info); if (y > 0) break; if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if (bmp_info.height < 0) { Image *flipped_image; /* Correct image orientation. */ flipped_image=FlipImage(image,exception); if (flipped_image != (Image *) NULL) { DuplicateBlob(flipped_image,image); ReplaceImageInList(&image, flipped_image); image=flipped_image; } } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; *magick='\0'; if (bmp_info.ba_offset != 0) { offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,2,magick); if ((count == 2) && (IsBMP(magick,2) != MagickFalse)) { /* Acquire next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (IsBMP(magick,2) != MagickFalse); (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1177'</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 handle_vmptrst(struct kvm_vcpu *vcpu) { unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION); u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO); gva_t vmcs_gva; struct x86_exception e; if (!nested_vmx_check_permission(vcpu)) return 1; if (get_vmx_mem_address(vcpu, exit_qualification, vmx_instruction_info, true, &vmcs_gva)) return 1; /* ok to use *_system, as hardware has verified cpl=0 */ if (kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, vmcs_gva, (void *)&to_vmx(vcpu)->nested.current_vmptr, sizeof(u64), &e)) { kvm_inject_page_fault(vcpu, &e); return 1; } nested_vmx_succeed(vcpu); return kvm_skip_emulated_instruction(vcpu); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284'], 'message': 'kvm: nVMX: Enforce cpl=0 for VMX instructions VMX instructions executed inside a L1 VM will always trigger a VM exit even when executed with cpl 3. This means we must perform the privilege check in software. Fixes: 70f3aac964ae("kvm: nVMX: Remove superfluous VMX instruction fault checks") Cc: stable@vger.kernel.org Signed-off-by: Felix Wilhelm <fwilhelm@google.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>'</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 Mounter::umountResult(int st) { QProcess *proc=dynamic_cast<QProcess *>(sender()); if (proc) { procCount--; proc->close(); proc->deleteLater(); emit umountStatus(proc->property("mp").toString(), proc->property("pid").toInt(), st); } startTimer(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-22'], 'message': 'Remove internal Samba shre mounting code, this had some privilege escalation issues, and is not well tested'</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 bool mpOk(const QString &mp) { return !mp.isEmpty() && mp.startsWith("/home/"); // ) && mp.contains("cantata"); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-22'], 'message': 'Remove internal Samba shre mounting code, this had some privilege escalation issues, and is not well tested'</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 Mounter::mount(const QString &url, const QString &mountPoint, int uid, int gid, int pid) { if (calledFromDBus()) { registerPid(pid); } qWarning() << url << mountPoint << uid << gid; QUrl u(url); int st=-1; if (u.scheme()=="smb" && mpOk(mountPoint)) { QString user=u.userName(); QString domain; QString password=u.password(); int port=u.port(); #if QT_VERSION < 0x050000 if (u.hasQueryItem("domain")) { domain=u.queryItemValue("domain"); } #else QUrlQuery q(u); if (q.hasQueryItem("domain")) { domain=q.queryItemValue("domain"); } #endif QTemporaryFile *temp=0; if (!password.isEmpty()) { temp=new QTemporaryFile(); if (temp && temp->open()) { QTextStream str(temp); if (!user.isEmpty()) { str << "username=" << user << endl; } str << "password=" << password << endl; if (!domain.isEmpty()) { str << "domain=" << domain << endl; } } } QString path=fixPath(u.host()+"/"+u.path()); while (!path.startsWith("//")) { path="/"+path; } // qWarning() << "EXEC" << "mount.cifs" << path << mountPoint // << "-o" << // (temp ? ("credentials="+temp->fileName()+",") : QString())+ // "uid="+QString::number(uid)+",gid="+QString::number(gid)+ // (445==port || port<1 ? QString() : ",port="+QString::number(port))+ // (temp || user.isEmpty() ? QString() : (",username="+user))+ // (temp || domain.isEmpty() ? QString() : (",domain="+domain))+ // (temp ? QString() : ",password="); QProcess *proc=new QProcess(this); connect(proc, SIGNAL(finished(int)), SLOT(mountResult(int))); proc->setProperty("mp", mountPoint); proc->setProperty("pid", pid); proc->start(QLatin1String(INSTALL_PREFIX"/share/cantata/scripts/mount.cifs.wrapper"), QStringList() << path << mountPoint << "-o" << (temp ? ("credentials="+temp->fileName()+",") : QString())+ "uid="+QString::number(uid)+",gid="+QString::number(gid)+ (445==port || port<1 ? QString() : ",port="+QString::number(port))+ (temp || user.isEmpty() ? QString() : (",username="+user))+ (temp || domain.isEmpty() ? QString() : (",domain="+domain))+ (temp ? QString() : ",password="), QIODevice::WriteOnly); if (temp) { tempFiles.insert(proc, temp); } procCount++; return; } emit mountStatus(mountPoint, pid, st); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-22'], 'message': 'Remove internal Samba shre mounting code, this had some privilege escalation issues, and is not well tested'</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 bool isLocalDomain(const QString &d) { return QLatin1String("local")==d.section('.', -1, -1).toLower(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-22'], 'message': 'Remove internal Samba shre mounting code, this had some privilege escalation issues, and is not well tested'</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 xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op) { int total = 0; int equal, ret; xmlXPathCompExprPtr comp; xmlXPathObjectPtr arg1, arg2; CHECK_ERROR0; comp = ctxt->comp; switch (op->op) { case XPATH_OP_END: return (0); case XPATH_OP_AND: total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; xmlXPathBooleanFunction(ctxt, 1); if ((ctxt->value == NULL) || (ctxt->value->boolval == 0)) return (total); arg2 = valuePop(ctxt); total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error) { xmlXPathFreeObject(arg2); return(0); } xmlXPathBooleanFunction(ctxt, 1); arg1 = valuePop(ctxt); arg1->boolval &= arg2->boolval; valuePush(ctxt, arg1); xmlXPathReleaseObject(ctxt->context, arg2); return (total); case XPATH_OP_OR: total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; xmlXPathBooleanFunction(ctxt, 1); if ((ctxt->value == NULL) || (ctxt->value->boolval == 1)) return (total); arg2 = valuePop(ctxt); total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error) { xmlXPathFreeObject(arg2); return(0); } xmlXPathBooleanFunction(ctxt, 1); arg1 = valuePop(ctxt); arg1->boolval |= arg2->boolval; valuePush(ctxt, arg1); xmlXPathReleaseObject(ctxt->context, arg2); return (total); case XPATH_OP_EQUAL: total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; if (op->value) equal = xmlXPathEqualValues(ctxt); else equal = xmlXPathNotEqualValues(ctxt); valuePush(ctxt, xmlXPathCacheNewBoolean(ctxt->context, equal)); return (total); case XPATH_OP_CMP: total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; ret = xmlXPathCompareValues(ctxt, op->value, op->value2); valuePush(ctxt, xmlXPathCacheNewBoolean(ctxt->context, ret)); return (total); case XPATH_OP_PLUS: total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if (op->ch2 != -1) { total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); } CHECK_ERROR0; if (op->value == 0) xmlXPathSubValues(ctxt); else if (op->value == 1) xmlXPathAddValues(ctxt); else if (op->value == 2) xmlXPathValueFlipSign(ctxt); else if (op->value == 3) { CAST_TO_NUMBER; CHECK_TYPE0(XPATH_NUMBER); } return (total); case XPATH_OP_MULT: total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; if (op->value == 0) xmlXPathMultValues(ctxt); else if (op->value == 1) xmlXPathDivValues(ctxt); else if (op->value == 2) xmlXPathModValues(ctxt); return (total); case XPATH_OP_UNION: total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; arg2 = valuePop(ctxt); arg1 = valuePop(ctxt); if ((arg1 == NULL) || (arg1->type != XPATH_NODESET) || (arg2 == NULL) || (arg2->type != XPATH_NODESET)) { xmlXPathReleaseObject(ctxt->context, arg1); xmlXPathReleaseObject(ctxt->context, arg2); XP_ERROR0(XPATH_INVALID_TYPE); } if ((arg1->nodesetval == NULL) || ((arg2->nodesetval != NULL) && (arg2->nodesetval->nodeNr != 0))) { arg1->nodesetval = xmlXPathNodeSetMerge(arg1->nodesetval, arg2->nodesetval); } valuePush(ctxt, arg1); xmlXPathReleaseObject(ctxt->context, arg2); return (total); case XPATH_OP_ROOT: xmlXPathRoot(ctxt); return (total); case XPATH_OP_NODE: if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; valuePush(ctxt, xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node)); return (total); case XPATH_OP_COLLECT:{ if (op->ch1 == -1) return (total); total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; total += xmlXPathNodeCollectAndTest(ctxt, op, NULL, NULL, 0); return (total); } case XPATH_OP_VALUE: valuePush(ctxt, xmlXPathCacheObjectCopy(ctxt->context, (xmlXPathObjectPtr) op->value4)); return (total); case XPATH_OP_VARIABLE:{ xmlXPathObjectPtr val; if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); if (op->value5 == NULL) { val = xmlXPathVariableLookup(ctxt->context, op->value4); if (val == NULL) XP_ERROR0(XPATH_UNDEF_VARIABLE_ERROR); valuePush(ctxt, val); } else { const xmlChar *URI; URI = xmlXPathNsLookup(ctxt->context, op->value5); if (URI == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: variable %s bound to undefined prefix %s\n", (char *) op->value4, (char *)op->value5); ctxt->error = XPATH_UNDEF_PREFIX_ERROR; return (total); } val = xmlXPathVariableLookupNS(ctxt->context, op->value4, URI); if (val == NULL) XP_ERROR0(XPATH_UNDEF_VARIABLE_ERROR); valuePush(ctxt, val); } return (total); } case XPATH_OP_FUNCTION:{ xmlXPathFunction func; const xmlChar *oldFunc, *oldFuncURI; int i; int frame; frame = xmlXPathSetFrame(ctxt); if (op->ch1 != -1) { total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); if (ctxt->error != XPATH_EXPRESSION_OK) { xmlXPathPopFrame(ctxt, frame); return (total); } } if (ctxt->valueNr < ctxt->valueFrame + op->value) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: parameter error\n"); ctxt->error = XPATH_INVALID_OPERAND; xmlXPathPopFrame(ctxt, frame); return (total); } for (i = 0; i < op->value; i++) { if (ctxt->valueTab[(ctxt->valueNr - 1) - i] == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: parameter error\n"); ctxt->error = XPATH_INVALID_OPERAND; xmlXPathPopFrame(ctxt, frame); return (total); } } if (op->cache != NULL) func = op->cache; else { const xmlChar *URI = NULL; if (op->value5 == NULL) func = xmlXPathFunctionLookup(ctxt->context, op->value4); else { URI = xmlXPathNsLookup(ctxt->context, op->value5); if (URI == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: function %s bound to undefined prefix %s\n", (char *)op->value4, (char *)op->value5); xmlXPathPopFrame(ctxt, frame); ctxt->error = XPATH_UNDEF_PREFIX_ERROR; return (total); } func = xmlXPathFunctionLookupNS(ctxt->context, op->value4, URI); } if (func == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: function %s not found\n", (char *)op->value4); XP_ERROR0(XPATH_UNKNOWN_FUNC_ERROR); } op->cache = func; op->cacheURI = (void *) URI; } oldFunc = ctxt->context->function; oldFuncURI = ctxt->context->functionURI; ctxt->context->function = op->value4; ctxt->context->functionURI = op->cacheURI; func(ctxt, op->value); ctxt->context->function = oldFunc; ctxt->context->functionURI = oldFuncURI; xmlXPathPopFrame(ctxt, frame); return (total); } case XPATH_OP_ARG: if (op->ch1 != -1) { total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; } if (op->ch2 != -1) { total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; } return (total); case XPATH_OP_PREDICATE: case XPATH_OP_FILTER:{ xmlXPathObjectPtr res; xmlXPathObjectPtr obj, tmp; xmlNodeSetPtr newset = NULL; xmlNodeSetPtr oldset; xmlNodePtr oldnode; xmlDocPtr oldDoc; int oldcs, oldpp; int i; /* * Optimization for ()[1] selection i.e. the first elem */ if ((op->ch1 != -1) && (op->ch2 != -1) && #ifdef XP_OPTIMIZED_FILTER_FIRST /* * FILTER TODO: Can we assume that the inner processing * will result in an ordered list if we have an * XPATH_OP_FILTER? * What about an additional field or flag on * xmlXPathObject like @sorted ? This way we wouln'd need * to assume anything, so it would be more robust and * easier to optimize. */ ((comp->steps[op->ch1].op == XPATH_OP_SORT) || /* 18 */ (comp->steps[op->ch1].op == XPATH_OP_FILTER)) && /* 17 */ #else (comp->steps[op->ch1].op == XPATH_OP_SORT) && #endif (comp->steps[op->ch2].op == XPATH_OP_VALUE)) { /* 12 */ xmlXPathObjectPtr val; val = comp->steps[op->ch2].value4; if ((val != NULL) && (val->type == XPATH_NUMBER) && (val->floatval == 1.0)) { xmlNodePtr first = NULL; total += xmlXPathCompOpEvalFirst(ctxt, &comp->steps[op->ch1], &first); CHECK_ERROR0; /* * The nodeset should be in document order, * Keep only the first value */ if ((ctxt->value != NULL) && (ctxt->value->type == XPATH_NODESET) && (ctxt->value->nodesetval != NULL) && (ctxt->value->nodesetval->nodeNr > 1)) xmlXPathNodeSetClearFromPos(ctxt->value->nodesetval, 1, 1); return (total); } } /* * Optimization for ()[last()] selection i.e. the last elem */ if ((op->ch1 != -1) && (op->ch2 != -1) && (comp->steps[op->ch1].op == XPATH_OP_SORT) && (comp->steps[op->ch2].op == XPATH_OP_SORT)) { int f = comp->steps[op->ch2].ch1; if ((f != -1) && (comp->steps[f].op == XPATH_OP_FUNCTION) && (comp->steps[f].value5 == NULL) && (comp->steps[f].value == 0) && (comp->steps[f].value4 != NULL) && (xmlStrEqual (comp->steps[f].value4, BAD_CAST "last"))) { xmlNodePtr last = NULL; total += xmlXPathCompOpEvalLast(ctxt, &comp->steps[op->ch1], &last); CHECK_ERROR0; /* * The nodeset should be in document order, * Keep only the last value */ if ((ctxt->value != NULL) && (ctxt->value->type == XPATH_NODESET) && (ctxt->value->nodesetval != NULL) && (ctxt->value->nodesetval->nodeTab != NULL) && (ctxt->value->nodesetval->nodeNr > 1)) xmlXPathNodeSetKeepLast(ctxt->value->nodesetval); return (total); } } /* * Process inner predicates first. * Example "index[parent::book][1]": * ... * PREDICATE <-- we are here "[1]" * PREDICATE <-- process "[parent::book]" first * SORT * COLLECT 'parent' 'name' 'node' book * NODE * ELEM Object is a number : 1 */ if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if (op->ch2 == -1) return (total); if (ctxt->value == NULL) return (total); #ifdef LIBXML_XPTR_ENABLED /* * Hum are we filtering the result of an XPointer expression */ if (ctxt->value->type == XPATH_LOCATIONSET) { xmlLocationSetPtr newlocset = NULL; xmlLocationSetPtr oldlocset; /* * Extract the old locset, and then evaluate the result of the * expression for all the element in the locset. use it to grow * up a new locset. */ CHECK_TYPE0(XPATH_LOCATIONSET); if ((ctxt->value->user == NULL) || (((xmlLocationSetPtr) ctxt->value->user)->locNr == 0)) return (total); obj = valuePop(ctxt); oldlocset = obj->user; oldnode = ctxt->context->node; oldcs = ctxt->context->contextSize; oldpp = ctxt->context->proximityPosition; newlocset = xmlXPtrLocationSetCreate(NULL); for (i = 0; i < oldlocset->locNr; i++) { /* * Run the evaluation with a node list made of a * single item in the nodelocset. */ ctxt->context->node = oldlocset->locTab[i]->user; ctxt->context->contextSize = oldlocset->locNr; ctxt->context->proximityPosition = i + 1; tmp = xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node); valuePush(ctxt, tmp); if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { xmlXPtrFreeLocationSet(newlocset); goto filter_xptr_error; } /* * The result of the evaluation need to be tested to * decided whether the filter succeeded or not */ res = valuePop(ctxt); if (xmlXPathEvaluatePredicateResult(ctxt, res)) { xmlXPtrLocationSetAdd(newlocset, xmlXPathObjectCopy (oldlocset->locTab[i])); } /* * Cleanup */ if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } if (ctxt->value == tmp) { res = valuePop(ctxt); xmlXPathReleaseObject(ctxt->context, res); } } /* * The result is used as the new evaluation locset. */ valuePush(ctxt, xmlXPtrWrapLocationSet(newlocset)); filter_xptr_error: xmlXPathReleaseObject(ctxt->context, obj); ctxt->context->node = oldnode; ctxt->context->contextSize = oldcs; ctxt->context->proximityPosition = oldpp; return (total); } #endif /* LIBXML_XPTR_ENABLED */ /* * Extract the old set, and then evaluate the result of the * expression for all the element in the set. use it to grow * up a new set. */ CHECK_TYPE0(XPATH_NODESET); if ((ctxt->value->nodesetval != NULL) && (ctxt->value->nodesetval->nodeNr != 0)) { obj = valuePop(ctxt); oldset = obj->nodesetval; oldnode = ctxt->context->node; oldDoc = ctxt->context->doc; oldcs = ctxt->context->contextSize; oldpp = ctxt->context->proximityPosition; tmp = NULL; /* * Initialize the new set. * Also set the xpath document in case things like * key() evaluation are attempted on the predicate */ newset = xmlXPathNodeSetCreate(NULL); /* * SPEC XPath 1.0: * "For each node in the node-set to be filtered, the * PredicateExpr is evaluated with that node as the * context node, with the number of nodes in the * node-set as the context size, and with the proximity * position of the node in the node-set with respect to * the axis as the context position;" * @oldset is the node-set" to be filtered. * * SPEC XPath 1.0: * "only predicates change the context position and * context size (see [2.4 Predicates])." * Example: * node-set context pos * nA 1 * nB 2 * nC 3 * After applying predicate [position() > 1] : * node-set context pos * nB 1 * nC 2 * * removed the first node in the node-set, then * the context position of the */ for (i = 0; i < oldset->nodeNr; i++) { /* * Run the evaluation with a node list made of * a single item in the nodeset. */ ctxt->context->node = oldset->nodeTab[i]; if ((oldset->nodeTab[i]->type != XML_NAMESPACE_DECL) && (oldset->nodeTab[i]->doc != NULL)) ctxt->context->doc = oldset->nodeTab[i]->doc; if (tmp == NULL) { tmp = xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node); } else { if (xmlXPathNodeSetAddUnique(tmp->nodesetval, ctxt->context->node) < 0) { ctxt->error = XPATH_MEMORY_ERROR; } } valuePush(ctxt, tmp); ctxt->context->contextSize = oldset->nodeNr; ctxt->context->proximityPosition = i + 1; /* * Evaluate the predicate against the context node. * Can/should we optimize position() predicates * here (e.g. "[1]")? */ if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { xmlXPathFreeNodeSet(newset); goto filter_error; } /* * The result of the evaluation needs to be tested to * decide whether the filter succeeded or not */ /* * OPTIMIZE TODO: Can we use * xmlXPathNodeSetAdd*Unique()* instead? */ res = valuePop(ctxt); if (xmlXPathEvaluatePredicateResult(ctxt, res)) { if (xmlXPathNodeSetAdd(newset, oldset->nodeTab[i]) < 0) ctxt->error = XPATH_MEMORY_ERROR; } /* * Cleanup */ if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } if (ctxt->value == tmp) { valuePop(ctxt); xmlXPathNodeSetClear(tmp->nodesetval, 1); /* * Don't free the temporary nodeset * in order to avoid massive recreation inside this * loop. */ } else tmp = NULL; } if (tmp != NULL) xmlXPathReleaseObject(ctxt->context, tmp); /* * The result is used as the new evaluation set. */ valuePush(ctxt, xmlXPathCacheWrapNodeSet(ctxt->context, newset)); filter_error: xmlXPathReleaseObject(ctxt->context, obj); ctxt->context->node = oldnode; ctxt->context->doc = oldDoc; ctxt->context->contextSize = oldcs; ctxt->context->proximityPosition = oldpp; } return (total); } case XPATH_OP_SORT: if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if ((ctxt->value != NULL) && (ctxt->value->type == XPATH_NODESET) && (ctxt->value->nodesetval != NULL) && (ctxt->value->nodesetval->nodeNr > 1)) { xmlXPathNodeSetSort(ctxt->value->nodesetval); } return (total); #ifdef LIBXML_XPTR_ENABLED case XPATH_OP_RANGETO:{ xmlXPathObjectPtr range; xmlXPathObjectPtr res, obj; xmlXPathObjectPtr tmp; xmlLocationSetPtr newlocset = NULL; xmlLocationSetPtr oldlocset; xmlNodeSetPtr oldset; xmlNodePtr oldnode = ctxt->context->node; int oldcs = ctxt->context->contextSize; int oldpp = ctxt->context->proximityPosition; int i, j; if (op->ch1 != -1) { total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; } if (ctxt->value == NULL) { XP_ERROR0(XPATH_INVALID_OPERAND); } if (op->ch2 == -1) return (total); if (ctxt->value->type == XPATH_LOCATIONSET) { /* * Extract the old locset, and then evaluate the result of the * expression for all the element in the locset. use it to grow * up a new locset. */ CHECK_TYPE0(XPATH_LOCATIONSET); if ((ctxt->value->user == NULL) || (((xmlLocationSetPtr) ctxt->value->user)->locNr == 0)) return (total); obj = valuePop(ctxt); oldlocset = obj->user; newlocset = xmlXPtrLocationSetCreate(NULL); for (i = 0; i < oldlocset->locNr; i++) { /* * Run the evaluation with a node list made of a * single item in the nodelocset. */ ctxt->context->node = oldlocset->locTab[i]->user; ctxt->context->contextSize = oldlocset->locNr; ctxt->context->proximityPosition = i + 1; tmp = xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node); valuePush(ctxt, tmp); if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { xmlXPtrFreeLocationSet(newlocset); goto rangeto_error; } res = valuePop(ctxt); if (res->type == XPATH_LOCATIONSET) { xmlLocationSetPtr rloc = (xmlLocationSetPtr)res->user; for (j=0; j<rloc->locNr; j++) { range = xmlXPtrNewRange( oldlocset->locTab[i]->user, oldlocset->locTab[i]->index, rloc->locTab[j]->user2, rloc->locTab[j]->index2); if (range != NULL) { xmlXPtrLocationSetAdd(newlocset, range); } } } else { range = xmlXPtrNewRangeNodeObject( (xmlNodePtr)oldlocset->locTab[i]->user, res); if (range != NULL) { xmlXPtrLocationSetAdd(newlocset,range); } } /* * Cleanup */ if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } if (ctxt->value == tmp) { res = valuePop(ctxt); xmlXPathReleaseObject(ctxt->context, res); } } } else { /* Not a location set */ CHECK_TYPE0(XPATH_NODESET); obj = valuePop(ctxt); oldset = obj->nodesetval; newlocset = xmlXPtrLocationSetCreate(NULL); if (oldset != NULL) { for (i = 0; i < oldset->nodeNr; i++) { /* * Run the evaluation with a node list made of a single item * in the nodeset. */ ctxt->context->node = oldset->nodeTab[i]; /* * OPTIMIZE TODO: Avoid recreation for every iteration. */ tmp = xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node); valuePush(ctxt, tmp); if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { xmlXPtrFreeLocationSet(newlocset); goto rangeto_error; } res = valuePop(ctxt); range = xmlXPtrNewRangeNodeObject(oldset->nodeTab[i], res); if (range != NULL) { xmlXPtrLocationSetAdd(newlocset, range); } /* * Cleanup */ if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } if (ctxt->value == tmp) { res = valuePop(ctxt); xmlXPathReleaseObject(ctxt->context, res); } } } } /* * The result is used as the new evaluation set. */ valuePush(ctxt, xmlXPtrWrapLocationSet(newlocset)); rangeto_error: xmlXPathReleaseObject(ctxt->context, obj); ctxt->context->node = oldnode; ctxt->context->contextSize = oldcs; ctxt->context->proximityPosition = oldpp; return (total); } #endif /* LIBXML_XPTR_ENABLED */ } xmlGenericError(xmlGenericErrorContext, "XPath: unknown precompiled operation %d\n", op->op); ctxt->error = XPATH_INVALID_OPERAND; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix nullptr deref with XPath logic ops If the XPath stack is corrupted, for example by a misbehaving extension function, the "and" and "or" XPath operators could dereference NULL pointers. Check that the XPath stack isn't empty and optimize the logic operators slightly. Closes: https://gitlab.gnome.org/GNOME/libxml2/issues/5 Also see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=901817 https://bugzilla.redhat.com/show_bug.cgi?id=1595985 This is CVE-2018-14404. Thanks to Guy Inbar for the report.'</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 ext4_check_descriptors(struct super_block *sb, ext4_fsblk_t sb_block, ext4_group_t *first_not_zeroed) { struct ext4_sb_info *sbi = EXT4_SB(sb); ext4_fsblk_t first_block = le32_to_cpu(sbi->s_es->s_first_data_block); ext4_fsblk_t last_block; ext4_fsblk_t block_bitmap; ext4_fsblk_t inode_bitmap; ext4_fsblk_t inode_table; int flexbg_flag = 0; ext4_group_t i, grp = sbi->s_groups_count; if (ext4_has_feature_flex_bg(sb)) flexbg_flag = 1; ext4_debug("Checking group descriptors"); for (i = 0; i < sbi->s_groups_count; i++) { struct ext4_group_desc *gdp = ext4_get_group_desc(sb, i, NULL); if (i == sbi->s_groups_count - 1 || flexbg_flag) last_block = ext4_blocks_count(sbi->s_es) - 1; else last_block = first_block + (EXT4_BLOCKS_PER_GROUP(sb) - 1); if ((grp == sbi->s_groups_count) && !(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED))) grp = i; block_bitmap = ext4_block_bitmap(sb, gdp); if (block_bitmap == sb_block) { ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: " "Block bitmap for group %u overlaps " "superblock", i); if (!sb_rdonly(sb)) return 0; } if (block_bitmap < first_block || block_bitmap > last_block) { ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: " "Block bitmap for group %u not in group " "(block %llu)!", i, block_bitmap); return 0; } inode_bitmap = ext4_inode_bitmap(sb, gdp); if (inode_bitmap == sb_block) { ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: " "Inode bitmap for group %u overlaps " "superblock", i); if (!sb_rdonly(sb)) return 0; } if (inode_bitmap < first_block || inode_bitmap > last_block) { ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: " "Inode bitmap for group %u not in group " "(block %llu)!", i, inode_bitmap); return 0; } inode_table = ext4_inode_table(sb, gdp); if (inode_table == sb_block) { ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: " "Inode table for group %u overlaps " "superblock", i); if (!sb_rdonly(sb)) return 0; } if (inode_table < first_block || inode_table + sbi->s_itb_per_group - 1 > last_block) { ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: " "Inode table for group %u not in group " "(block %llu)!", i, inode_table); return 0; } ext4_lock_group(sb, i); if (!ext4_group_desc_csum_verify(sb, i, gdp)) { ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: " "Checksum for group %u failed (%u!=%u)", i, le16_to_cpu(ext4_group_desc_csum(sb, i, gdp)), le16_to_cpu(gdp->bg_checksum)); if (!sb_rdonly(sb)) { ext4_unlock_group(sb, i); return 0; } } ext4_unlock_group(sb, i); if (!flexbg_flag) first_block += EXT4_BLOCKS_PER_GROUP(sb); } if (NULL != first_not_zeroed) *first_not_zeroed = grp; return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'ext4: make sure bitmaps and the inode table don't overlap with bg descriptors It's really bad when the allocation bitmaps and the inode table overlap with the block group descriptors, since it causes random corruption of the bg descriptors. So we really want to head those off at the pass. https://bugzilla.kernel.org/show_bug.cgi?id=199865 Signed-off-by: Theodore Ts'o <tytso@mit.edu> Cc: stable@kernel.org'</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 ext4_da_write_inline_data_begin(struct address_space *mapping, struct inode *inode, loff_t pos, unsigned len, unsigned flags, struct page **pagep, void **fsdata) { int ret, inline_size; handle_t *handle; struct page *page; struct ext4_iloc iloc; int retries; ret = ext4_get_inode_loc(inode, &iloc); if (ret) return ret; retry_journal: handle = ext4_journal_start(inode, EXT4_HT_INODE, 1); if (IS_ERR(handle)) { ret = PTR_ERR(handle); goto out; } inline_size = ext4_get_max_inline_size(inode); ret = -ENOSPC; if (inline_size >= pos + len) { ret = ext4_prepare_inline_data(handle, inode, pos + len); if (ret && ret != -ENOSPC) goto out_journal; } /* * We cannot recurse into the filesystem as the transaction * is already started. */ flags |= AOP_FLAG_NOFS; if (ret == -ENOSPC) { ret = ext4_da_convert_inline_data_to_extent(mapping, inode, flags, fsdata); ext4_journal_stop(handle); if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries)) goto retry_journal; goto out; } page = grab_cache_page_write_begin(mapping, 0, flags); if (!page) { ret = -ENOMEM; goto out_journal; } down_read(&EXT4_I(inode)->xattr_sem); if (!ext4_has_inline_data(inode)) { ret = 0; goto out_release_page; } if (!PageUptodate(page)) { ret = ext4_read_inline_page(inode, page); if (ret < 0) goto out_release_page; } up_read(&EXT4_I(inode)->xattr_sem); *pagep = page; brelse(iloc.bh); return 1; out_release_page: up_read(&EXT4_I(inode)->xattr_sem); unlock_page(page); put_page(page); out_journal: ext4_journal_stop(handle); out: brelse(iloc.bh); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'ext4: avoid running out of journal credits when appending to an inline file Use a separate journal transaction if it turns out that we need to convert an inline file to use an data block. Otherwise we could end up failing due to not having journal credits. This addresses CVE-2018-10883. https://bugzilla.kernel.org/show_bug.cgi?id=200071 Signed-off-by: Theodore Ts'o <tytso@mit.edu> Cc: stable@kernel.org'</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 lock_flags) __releases(RCU) { struct inode *inode = VFS_I(ip); struct xfs_mount *mp = ip->i_mount; int error; /* * check for re-use of an inode within an RCU grace period due to the * radix tree nodes not being updated yet. We monitor for this by * setting the inode number to zero before freeing the inode structure. * If the inode has been reallocated and set up, then the inode number * will not match, so check for that, too. */ spin_lock(&ip->i_flags_lock); if (ip->i_ino != ino) { trace_xfs_iget_skip(ip); XFS_STATS_INC(mp, xs_ig_frecycle); error = -EAGAIN; goto out_error; } /* * If we are racing with another cache hit that is currently * instantiating this inode or currently recycling it out of * reclaimabe state, wait for the initialisation to complete * before continuing. * * XXX(hch): eventually we should do something equivalent to * wait_on_inode to wait for these flags to be cleared * instead of polling for it. */ if (ip->i_flags & (XFS_INEW|XFS_IRECLAIM)) { trace_xfs_iget_skip(ip); XFS_STATS_INC(mp, xs_ig_frecycle); error = -EAGAIN; goto out_error; } /* * If lookup is racing with unlink return an error immediately. */ if (VFS_I(ip)->i_mode == 0 && !(flags & XFS_IGET_CREATE)) { error = -ENOENT; goto out_error; } /* * If IRECLAIMABLE is set, we've torn down the VFS inode already. * Need to carefully get it back into useable state. */ if (ip->i_flags & XFS_IRECLAIMABLE) { trace_xfs_iget_reclaim(ip); if (flags & XFS_IGET_INCORE) { error = -EAGAIN; goto out_error; } /* * We need to set XFS_IRECLAIM to prevent xfs_reclaim_inode * from stomping over us while we recycle the inode. We can't * clear the radix tree reclaimable tag yet as it requires * pag_ici_lock to be held exclusive. */ ip->i_flags |= XFS_IRECLAIM; spin_unlock(&ip->i_flags_lock); rcu_read_unlock(); error = xfs_reinit_inode(mp, inode); if (error) { bool wake; /* * Re-initializing the inode failed, and we are in deep * trouble. Try to re-add it to the reclaim list. */ rcu_read_lock(); spin_lock(&ip->i_flags_lock); wake = !!__xfs_iflags_test(ip, XFS_INEW); ip->i_flags &= ~(XFS_INEW | XFS_IRECLAIM); if (wake) wake_up_bit(&ip->i_flags, __XFS_INEW_BIT); ASSERT(ip->i_flags & XFS_IRECLAIMABLE); trace_xfs_iget_reclaim_fail(ip); goto out_error; } spin_lock(&pag->pag_ici_lock); spin_lock(&ip->i_flags_lock); /* * Clear the per-lifetime state in the inode as we are now * effectively a new inode and need to return to the initial * state before reuse occurs. */ ip->i_flags &= ~XFS_IRECLAIM_RESET_FLAGS; ip->i_flags |= XFS_INEW; xfs_inode_clear_reclaim_tag(pag, ip->i_ino); inode->i_state = I_NEW; ASSERT(!rwsem_is_locked(&inode->i_rwsem)); init_rwsem(&inode->i_rwsem); spin_unlock(&ip->i_flags_lock); spin_unlock(&pag->pag_ici_lock); } else { /* If the VFS inode is being torn down, pause and try again. */ if (!igrab(inode)) { trace_xfs_iget_skip(ip); error = -EAGAIN; goto out_error; } /* We've got a live one. */ spin_unlock(&ip->i_flags_lock); rcu_read_unlock(); trace_xfs_iget_hit(ip); } if (lock_flags != 0) xfs_ilock(ip, lock_flags); if (!(flags & XFS_IGET_INCORE)) xfs_iflags_clear(ip, XFS_ISTALE | XFS_IDONTCACHE); XFS_STATS_INC(mp, xs_ig_found); return 0; out_error: spin_unlock(&ip->i_flags_lock); rcu_read_unlock(); return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'xfs: validate cached inodes are free when allocated A recent fuzzed filesystem image cached random dcache corruption when the reproducer was run. This often showed up as panics in lookup_slow() on a null inode->i_ops pointer when doing pathwalks. BUG: unable to handle kernel NULL pointer dereference at 0000000000000000 .... Call Trace: lookup_slow+0x44/0x60 walk_component+0x3dd/0x9f0 link_path_walk+0x4a7/0x830 path_lookupat+0xc1/0x470 filename_lookup+0x129/0x270 user_path_at_empty+0x36/0x40 path_listxattr+0x98/0x110 SyS_listxattr+0x13/0x20 do_syscall_64+0xf5/0x280 entry_SYSCALL_64_after_hwframe+0x42/0xb7 but had many different failure modes including deadlocks trying to lock the inode that was just allocated or KASAN reports of use-after-free violations. The cause of the problem was a corrupt INOBT on a v4 fs where the root inode was marked as free in the inobt record. Hence when we allocated an inode, it chose the root inode to allocate, found it in the cache and re-initialised it. We recently fixed a similar inode allocation issue caused by inobt record corruption problem in xfs_iget_cache_miss() in commit ee457001ed6c ("xfs: catch inode allocation state mismatch corruption"). This change adds similar checks to the cache-hit path to catch it, and turns the reproducer into a corruption shutdown situation. Reported-by: Wen Xu <wen.xu@gatech.edu> Signed-Off-By: Dave Chinner <dchinner@redhat.com> Reviewed-by: Christoph Hellwig <hch@lst.de> Reviewed-by: Carlos Maiolino <cmaiolino@redhat.com> Reviewed-by: Darrick J. Wong <darrick.wong@oracle.com> [darrick: fix typos in comment] Signed-off-by: Darrick J. Wong <darrick.wong@oracle.com>'</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_delta_apply( void **out, size_t *out_len, const unsigned char *base, size_t base_len, const unsigned char *delta, size_t delta_len) { const unsigned char *delta_end = delta + delta_len; size_t base_sz, res_sz, alloc_sz; unsigned char *res_dp; *out = NULL; *out_len = 0; /* * Check that the base size matches the data we were given; * if not we would underflow while accessing data from the * base object, resulting in data corruption or segfault. */ if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } if (hdr_sz(&res_sz, &delta, delta_end) < 0) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1); res_dp = git__malloc(alloc_sz); GITERR_CHECK_ALLOC(res_dp); res_dp[res_sz] = '\0'; *out = res_dp; *out_len = res_sz; while (delta < delta_end) { unsigned char cmd = *delta++; if (cmd & 0x80) { /* cmd is a copy instruction; copy from the base. */ size_t off = 0, len = 0; if (cmd & 0x01) off = *delta++; if (cmd & 0x02) off |= *delta++ << 8UL; if (cmd & 0x04) off |= *delta++ << 16UL; if (cmd & 0x08) off |= ((unsigned) *delta++ << 24UL); if (cmd & 0x10) len = *delta++; if (cmd & 0x20) len |= *delta++ << 8UL; if (cmd & 0x40) len |= *delta++ << 16UL; if (!len) len = 0x10000; if (base_len < off + len || res_sz < len) goto fail; memcpy(res_dp, base + off, len); res_dp += len; res_sz -= len; } else if (cmd) { /* * cmd is a literal insert instruction; copy from * the delta stream itself. */ if (delta_end - delta < cmd || res_sz < cmd) goto fail; memcpy(res_dp, delta, cmd); delta += cmd; res_dp += cmd; res_sz -= cmd; } else { /* cmd == 0 is reserved for future encodings. */ goto fail; } } if (delta != delta_end || res_sz) goto fail; return 0; fail: git__free(*out); *out = NULL; *out_len = 0; giterr_set(GITERR_INVALID, "failed to apply delta"); return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'delta: fix out-of-bounds read of delta When computing the offset and length of the delta base, we repeatedly increment the `delta` pointer without checking whether we have advanced past its end already, which can thus result in an out-of-bounds read. Fix this by repeatedly checking whether we have reached the end. Add a test which would cause Valgrind to produce an error. Reported-by: Riccardo Schirone <rschiron@redhat.com> Test-provided-by: Riccardo Schirone <rschiron@redhat.com>'</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 TDStretch::setChannels(int numChannels) { assert(numChannels > 0); if (channels == numChannels) return; // assert(numChannels == 1 || numChannels == 2); channels = numChannels; inputBuffer.setChannels(channels); outputBuffer.setChannels(channels); // re-init overlap/buffer overlapLength=0; setParameters(sampleRate); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617'], 'message': 'Replaced illegal-number-of-channel assertions with run-time exception'</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 msg_cache_check (const char *id, body_cache_t *bcache, void *data) { CONTEXT *ctx; POP_DATA *pop_data; int i; if (!(ctx = (CONTEXT *)data)) return -1; if (!(pop_data = (POP_DATA *)ctx->data)) return -1; #ifdef USE_HCACHE /* keep hcache file if hcache == bcache */ if (strcmp (HC_FNAME "." HC_FEXT, id) == 0) return 0; #endif for (i = 0; i < ctx->msgcount; i++) /* if the id we get is known for a header: done (i.e. keep in cache) */ if (ctx->hdrs[i]->data && mutt_strcmp (ctx->hdrs[i]->data, id) == 0) return 0; /* message not found in context -> remove it from cache * return the result of bcache, so we stop upon its first error */ return mutt_bcache_del (bcache, id); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Sanitize POP bcache paths. Protect against bcache directory path traversal for UID values. Thanks for Jeriko One for the bug report and patch, which this commit is based upon.'</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 imap_munge_mbox_name(struct ImapData *idata, char *dest, size_t dlen, const char *src) { char *buf = mutt_str_strdup(src); imap_utf_encode(idata, &buf); imap_quote_string(dest, dlen, buf); FREE(&buf); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-78', 'CWE-77'], 'message': 'quote imap strings more carefully Co-authored-by: JerikoOne <jeriko.one@gmx.us>'</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 _imap_quote_string (char *dest, size_t dlen, const char *src, const char *to_quote) { char *pt; const char *s; pt = dest; s = src; *pt++ = '"'; /* save room for trailing quote-char */ dlen -= 2; for (; *s && dlen; s++) { if (strchr (to_quote, *s)) { dlen -= 2; if (!dlen) break; *pt++ = '\\'; *pt++ = *s; } else { *pt++ = *s; dlen--; } } *pt++ = '"'; *pt = 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-191', 'CWE-787'], 'message': 'Fix imap_quote_string() length check errors. The function wasn't properly checking for dlen<2 before quoting, and wasn't properly pre-adjusting dlen to include the initial quote. Thanks to Jeriko One for reporting these issues.'</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 *md_config_set_notify_cmd(cmd_parms *cmd, void *arg, const char *value) { md_srv_conf_t *sc = md_config_get(cmd->server); const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY); if (err) { return err; } sc->mc->notify_cmd = value; (void)arg; return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'v1.1.12, notifycmd improvements'</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: _ppdCreateFromIPP(char *buffer, /* I - Filename buffer */ size_t bufsize, /* I - Size of filename buffer */ ipp_t *response) /* I - Get-Printer-Attributes response */ { cups_file_t *fp; /* PPD file */ cups_array_t *sizes; /* Media sizes we've added */ ipp_attribute_t *attr, /* xxx-supported */ *defattr, /* xxx-default */ *x_dim, *y_dim; /* Media dimensions */ ipp_t *media_size; /* Media size collection */ char make[256], /* Make and model */ *model, /* Model name */ ppdname[PPD_MAX_NAME]; /* PPD keyword */ int i, j, /* Looping vars */ count, /* Number of values */ bottom, /* Largest bottom margin */ left, /* Largest left margin */ right, /* Largest right margin */ top, /* Largest top margin */ is_apple = 0, /* Does the printer support Apple raster? */ is_pdf = 0, /* Does the printer support PDF? */ is_pwg = 0; /* Does the printer support PWG Raster? */ pwg_media_t *pwg; /* PWG media size */ int xres, yres; /* Resolution values */ cups_lang_t *lang = cupsLangDefault(); /* Localization info */ struct lconv *loc = localeconv(); /* Locale data */ static const char * const finishings[][2] = { /* Finishings strings */ { "bale", _("Bale") }, { "bind", _("Bind") }, { "bind-bottom", _("Bind (Reverse Landscape)") }, { "bind-left", _("Bind (Portrait)") }, { "bind-right", _("Bind (Reverse Portrait)") }, { "bind-top", _("Bind (Landscape)") }, { "booklet-maker", _("Booklet Maker") }, { "coat", _("Coat") }, { "cover", _("Cover") }, { "edge-stitch", _("Staple Edge") }, { "edge-stitch-bottom", _("Staple Edge (Reverse Landscape)") }, { "edge-stitch-left", _("Staple Edge (Portrait)") }, { "edge-stitch-right", _("Staple Edge (Reverse Portrait)") }, { "edge-stitch-top", _("Staple Edge (Landscape)") }, { "fold", _("Fold") }, { "fold-accordian", _("Accordian Fold") }, { "fold-double-gate", _("Double Gate Fold") }, { "fold-engineering-z", _("Engineering Z Fold") }, { "fold-gate", _("Gate Fold") }, { "fold-half", _("Half Fold") }, { "fold-half-z", _("Half Z Fold") }, { "fold-left-gate", _("Left Gate Fold") }, { "fold-letter", _("Letter Fold") }, { "fold-parallel", _("Parallel Fold") }, { "fold-poster", _("Poster Fold") }, { "fold-right-gate", _("Right Gate Fold") }, { "fold-z", _("Z Fold") }, { "jog-offset", _("Jog") }, { "laminate", _("Laminate") }, { "punch", _("Punch") }, { "punch-bottom-left", _("Single Punch (Reverse Landscape)") }, { "punch-bottom-right", _("Single Punch (Reverse Portrait)") }, { "punch-double-bottom", _("2-Hole Punch (Reverse Portrait)") }, { "punch-double-left", _("2-Hole Punch (Reverse Landscape)") }, { "punch-double-right", _("2-Hole Punch (Landscape)") }, { "punch-double-top", _("2-Hole Punch (Portrait)") }, { "punch-quad-bottom", _("4-Hole Punch (Reverse Landscape)") }, { "punch-quad-left", _("4-Hole Punch (Portrait)") }, { "punch-quad-right", _("4-Hole Punch (Reverse Portrait)") }, { "punch-quad-top", _("4-Hole Punch (Landscape)") }, { "punch-top-left", _("Single Punch (Portrait)") }, { "punch-top-right", _("Single Punch (Landscape)") }, { "punch-triple-bottom", _("3-Hole Punch (Reverse Landscape)") }, { "punch-triple-left", _("3-Hole Punch (Portrait)") }, { "punch-triple-right", _("3-Hole Punch (Reverse Portrait)") }, { "punch-triple-top", _("3-Hole Punch (Landscape)") }, { "punch-multiple-bottom", _("Multi-Hole Punch (Reverse Landscape)") }, { "punch-multiple-left", _("Multi-Hole Punch (Portrait)") }, { "punch-multiple-right", _("Multi-Hole Punch (Reverse Portrait)") }, { "punch-multiple-top", _("Multi-Hole Punch (Landscape)") }, { "saddle-stitch", _("Saddle Stitch") }, { "staple", _("Staple") }, { "staple-bottom-left", _("Single Staple (Reverse Landscape)") }, { "staple-bottom-right", _("Single Staple (Reverse Portrait)") }, { "staple-dual-bottom", _("Double Staple (Reverse Landscape)") }, { "staple-dual-left", _("Double Staple (Portrait)") }, { "staple-dual-right", _("Double Staple (Reverse Portrait)") }, { "staple-dual-top", _("Double Staple (Landscape)") }, { "staple-top-left", _("Single Staple (Portrait)") }, { "staple-top-right", _("Single Staple (Landscape)") }, { "staple-triple-bottom", _("Triple Staple (Reverse Landscape)") }, { "staple-triple-left", _("Triple Staple (Portrait)") }, { "staple-triple-right", _("Triple Staple (Reverse Portrait)") }, { "staple-triple-top", _("Triple Staple (Landscape)") }, { "trim", _("Cut Media") } }; /* * Range check input... */ if (buffer) *buffer = '\0'; if (!buffer || bufsize < 1 || !response) return (NULL); /* * Open a temporary file for the PPD... */ if ((fp = cupsTempFile2(buffer, (int)bufsize)) == NULL) return (NULL); /* * Standard stuff for PPD file... */ cupsFilePuts(fp, "*PPD-Adobe: \"4.3\"\n"); cupsFilePuts(fp, "*FormatVersion: \"4.3\"\n"); cupsFilePrintf(fp, "*FileVersion: \"%d.%d\"\n", CUPS_VERSION_MAJOR, CUPS_VERSION_MINOR); cupsFilePuts(fp, "*LanguageVersion: English\n"); cupsFilePuts(fp, "*LanguageEncoding: ISOLatin1\n"); cupsFilePuts(fp, "*PSVersion: \"(3010.000) 0\"\n"); cupsFilePuts(fp, "*LanguageLevel: \"3\"\n"); cupsFilePuts(fp, "*FileSystem: False\n"); cupsFilePuts(fp, "*PCFileName: \"ippeve.ppd\"\n"); if ((attr = ippFindAttribute(response, "printer-make-and-model", IPP_TAG_TEXT)) != NULL) strlcpy(make, ippGetString(attr, 0, NULL), sizeof(make)); else strlcpy(make, "Unknown Printer", sizeof(make)); if (!_cups_strncasecmp(make, "Hewlett Packard ", 16) || !_cups_strncasecmp(make, "Hewlett-Packard ", 16)) { model = make + 16; strlcpy(make, "HP", sizeof(make)); } else if ((model = strchr(make, ' ')) != NULL) *model++ = '\0'; else model = make; cupsFilePrintf(fp, "*Manufacturer: \"%s\"\n", make); cupsFilePrintf(fp, "*ModelName: \"%s\"\n", model); cupsFilePrintf(fp, "*Product: \"(%s)\"\n", model); cupsFilePrintf(fp, "*NickName: \"%s\"\n", model); cupsFilePrintf(fp, "*ShortNickName: \"%s\"\n", model); if ((attr = ippFindAttribute(response, "color-supported", IPP_TAG_BOOLEAN)) != NULL && ippGetBoolean(attr, 0)) cupsFilePuts(fp, "*ColorDevice: True\n"); else cupsFilePuts(fp, "*ColorDevice: False\n"); cupsFilePrintf(fp, "*cupsVersion: %d.%d\n", CUPS_VERSION_MAJOR, CUPS_VERSION_MINOR); cupsFilePuts(fp, "*cupsSNMPSupplies: False\n"); cupsFilePuts(fp, "*cupsLanguages: \"en\"\n"); /* * Filters... */ if ((attr = ippFindAttribute(response, "document-format-supported", IPP_TAG_MIMETYPE)) != NULL) { is_apple = ippContainsString(attr, "image/urf"); is_pdf = ippContainsString(attr, "application/pdf"); is_pwg = ippContainsString(attr, "image/pwg-raster"); for (i = 0, count = ippGetCount(attr); i < count; i ++) { const char *format = ippGetString(attr, i, NULL); /* PDL */ /* * Write cupsFilter2 lines for supported formats, except for PostScript * (which has compatibility problems over IPP with some vendors), text, * TIFF, and vendor MIME media types... */ if (!_cups_strcasecmp(format, "application/pdf")) cupsFilePuts(fp, "*cupsFilter2: \"application/vnd.cups-pdf application/pdf 10 -\"\n"); else if (!_cups_strcasecmp(format, "image/jpeg") || !_cups_strcasecmp(format, "image/png")) cupsFilePrintf(fp, "*cupsFilter2: \"%s %s 0 -\"\n", format, format); else if (!_cups_strcasecmp(format, "image/pwg-raster") || !_cups_strcasecmp(format, "image/urf")) cupsFilePrintf(fp, "*cupsFilter2: \"%s %s 100 -\"\n", format, format); else if (_cups_strcasecmp(format, "application/octet-stream") && _cups_strcasecmp(format, "application/postscript") && _cups_strncasecmp(format, "application/vnd.", 16) && _cups_strncasecmp(format, "image/vnd.", 10) && _cups_strcasecmp(format, "image/tiff") && _cups_strncasecmp(format, "text/", 5)) cupsFilePrintf(fp, "*cupsFilter2: \"%s %s 10 -\"\n", format, format); } } if (!is_apple && !is_pdf && !is_pwg) goto bad_ppd; /* * PageSize/PageRegion/ImageableArea/PaperDimension */ if ((attr = ippFindAttribute(response, "media-bottom-margin-supported", IPP_TAG_INTEGER)) != NULL) { for (i = 1, bottom = ippGetInteger(attr, 0), count = ippGetCount(attr); i < count; i ++) if (ippGetInteger(attr, i) > bottom) bottom = ippGetInteger(attr, i); } else bottom = 1270; if ((attr = ippFindAttribute(response, "media-left-margin-supported", IPP_TAG_INTEGER)) != NULL) { for (i = 1, left = ippGetInteger(attr, 0), count = ippGetCount(attr); i < count; i ++) if (ippGetInteger(attr, i) > left) left = ippGetInteger(attr, i); } else left = 635; if ((attr = ippFindAttribute(response, "media-right-margin-supported", IPP_TAG_INTEGER)) != NULL) { for (i = 1, right = ippGetInteger(attr, 0), count = ippGetCount(attr); i < count; i ++) if (ippGetInteger(attr, i) > right) right = ippGetInteger(attr, i); } else right = 635; if ((attr = ippFindAttribute(response, "media-top-margin-supported", IPP_TAG_INTEGER)) != NULL) { for (i = 1, top = ippGetInteger(attr, 0), count = ippGetCount(attr); i < count; i ++) if (ippGetInteger(attr, i) > top) top = ippGetInteger(attr, i); } else top = 1270; if ((defattr = ippFindAttribute(response, "media-col-default", IPP_TAG_BEGIN_COLLECTION)) != NULL) { if ((attr = ippFindAttribute(ippGetCollection(defattr, 0), "media-size", IPP_TAG_BEGIN_COLLECTION)) != NULL) { media_size = ippGetCollection(attr, 0); x_dim = ippFindAttribute(media_size, "x-dimension", IPP_TAG_INTEGER); y_dim = ippFindAttribute(media_size, "y-dimension", IPP_TAG_INTEGER); if (x_dim && y_dim && (pwg = pwgMediaForSize(ippGetInteger(x_dim, 0), ippGetInteger(y_dim, 0))) != NULL) strlcpy(ppdname, pwg->ppd, sizeof(ppdname)); else strlcpy(ppdname, "Unknown", sizeof(ppdname)); } else strlcpy(ppdname, "Unknown", sizeof(ppdname)); } else if ((pwg = pwgMediaForPWG(ippGetString(ippFindAttribute(response, "media-default", IPP_TAG_ZERO), 0, NULL))) != NULL) strlcpy(ppdname, pwg->ppd, sizeof(ppdname)); else strlcpy(ppdname, "Unknown", sizeof(ppdname)); if ((attr = ippFindAttribute(response, "media-size-supported", IPP_TAG_BEGIN_COLLECTION)) == NULL) attr = ippFindAttribute(response, "media-supported", IPP_TAG_ZERO); if (attr) { cupsFilePrintf(fp, "*OpenUI *PageSize: PickOne\n" "*OrderDependency: 10 AnySetup *PageSize\n" "*DefaultPageSize: %s\n", ppdname); sizes = cupsArrayNew3((cups_array_func_t)strcmp, NULL, NULL, 0, (cups_acopy_func_t)strdup, (cups_afree_func_t)free); for (i = 0, count = ippGetCount(attr); i < count; i ++) { if (ippGetValueTag(attr) == IPP_TAG_BEGIN_COLLECTION) { media_size = ippGetCollection(attr, i); x_dim = ippFindAttribute(media_size, "x-dimension", IPP_TAG_INTEGER); y_dim = ippFindAttribute(media_size, "y-dimension", IPP_TAG_INTEGER); pwg = pwgMediaForSize(ippGetInteger(x_dim, 0), ippGetInteger(y_dim, 0)); } else pwg = pwgMediaForPWG(ippGetString(attr, i, NULL)); if (pwg) { char twidth[256], /* Width string */ tlength[256]; /* Length string */ if (cupsArrayFind(sizes, (void *)pwg->ppd)) { cupsFilePrintf(fp, "*%% warning: Duplicate size '%s' reported by printer.\n", pwg->ppd); continue; } cupsArrayAdd(sizes, (void *)pwg->ppd); _cupsStrFormatd(twidth, twidth + sizeof(twidth), pwg->width * 72.0 / 2540.0, loc); _cupsStrFormatd(tlength, tlength + sizeof(tlength), pwg->length * 72.0 / 2540.0, loc); cupsFilePrintf(fp, "*PageSize %s: \"<</PageSize[%s %s]>>setpagedevice\"\n", pwg->ppd, twidth, tlength); } } cupsFilePuts(fp, "*CloseUI: *PageSize\n"); cupsArrayDelete(sizes); sizes = cupsArrayNew3((cups_array_func_t)strcmp, NULL, NULL, 0, (cups_acopy_func_t)strdup, (cups_afree_func_t)free); cupsFilePrintf(fp, "*OpenUI *PageRegion: PickOne\n" "*OrderDependency: 10 AnySetup *PageRegion\n" "*DefaultPageRegion: %s\n", ppdname); for (i = 0, count = ippGetCount(attr); i < count; i ++) { if (ippGetValueTag(attr) == IPP_TAG_BEGIN_COLLECTION) { media_size = ippGetCollection(attr, i); x_dim = ippFindAttribute(media_size, "x-dimension", IPP_TAG_INTEGER); y_dim = ippFindAttribute(media_size, "y-dimension", IPP_TAG_INTEGER); pwg = pwgMediaForSize(ippGetInteger(x_dim, 0), ippGetInteger(y_dim, 0)); } else pwg = pwgMediaForPWG(ippGetString(attr, i, NULL)); if (pwg) { char twidth[256], /* Width string */ tlength[256]; /* Length string */ if (cupsArrayFind(sizes, (void *)pwg->ppd)) continue; cupsArrayAdd(sizes, (void *)pwg->ppd); _cupsStrFormatd(twidth, twidth + sizeof(twidth), pwg->width * 72.0 / 2540.0, loc); _cupsStrFormatd(tlength, tlength + sizeof(tlength), pwg->length * 72.0 / 2540.0, loc); cupsFilePrintf(fp, "*PageRegion %s: \"<</PageSize[%s %s]>>setpagedevice\"\n", pwg->ppd, twidth, tlength); } } cupsFilePuts(fp, "*CloseUI: *PageRegion\n"); cupsArrayDelete(sizes); sizes = cupsArrayNew3((cups_array_func_t)strcmp, NULL, NULL, 0, (cups_acopy_func_t)strdup, (cups_afree_func_t)free); cupsFilePrintf(fp, "*DefaultImageableArea: %s\n" "*DefaultPaperDimension: %s\n", ppdname, ppdname); for (i = 0, count = ippGetCount(attr); i < count; i ++) { if (ippGetValueTag(attr) == IPP_TAG_BEGIN_COLLECTION) { media_size = ippGetCollection(attr, i); x_dim = ippFindAttribute(media_size, "x-dimension", IPP_TAG_INTEGER); y_dim = ippFindAttribute(media_size, "y-dimension", IPP_TAG_INTEGER); pwg = pwgMediaForSize(ippGetInteger(x_dim, 0), ippGetInteger(y_dim, 0)); } else pwg = pwgMediaForPWG(ippGetString(attr, i, NULL)); if (pwg) { char tleft[256], /* Left string */ tbottom[256], /* Bottom string */ tright[256], /* Right string */ ttop[256], /* Top string */ twidth[256], /* Width string */ tlength[256]; /* Length string */ if (cupsArrayFind(sizes, (void *)pwg->ppd)) continue; cupsArrayAdd(sizes, (void *)pwg->ppd); _cupsStrFormatd(tleft, tleft + sizeof(tleft), left * 72.0 / 2540.0, loc); _cupsStrFormatd(tbottom, tbottom + sizeof(tbottom), bottom * 72.0 / 2540.0, loc); _cupsStrFormatd(tright, tright + sizeof(tright), (pwg->width - right) * 72.0 / 2540.0, loc); _cupsStrFormatd(ttop, ttop + sizeof(ttop), (pwg->length - top) * 72.0 / 2540.0, loc); _cupsStrFormatd(twidth, twidth + sizeof(twidth), pwg->width * 72.0 / 2540.0, loc); _cupsStrFormatd(tlength, tlength + sizeof(tlength), pwg->length * 72.0 / 2540.0, loc); cupsFilePrintf(fp, "*ImageableArea %s: \"%s %s %s %s\"\n", pwg->ppd, tleft, tbottom, tright, ttop); cupsFilePrintf(fp, "*PaperDimension %s: \"%s %s\"\n", pwg->ppd, twidth, tlength); } } cupsArrayDelete(sizes); } else goto bad_ppd; /* * InputSlot... */ if ((attr = ippFindAttribute(ippGetCollection(defattr, 0), "media-source", IPP_TAG_ZERO)) != NULL) pwg_ppdize_name(ippGetString(attr, 0, NULL), ppdname, sizeof(ppdname)); else strlcpy(ppdname, "Unknown", sizeof(ppdname)); if ((attr = ippFindAttribute(response, "media-source-supported", IPP_TAG_ZERO)) != NULL && (count = ippGetCount(attr)) > 1) { static const char * const sources[][2] = { /* "media-source" strings */ { "Auto", _("Automatic") }, { "Main", _("Main") }, { "Alternate", _("Alternate") }, { "LargeCapacity", _("Large Capacity") }, { "Manual", _("Manual") }, { "Envelope", _("Envelope") }, { "Disc", _("Disc") }, { "Photo", _("Photo") }, { "Hagaki", _("Hagaki") }, { "MainRoll", _("Main Roll") }, { "AlternateRoll", _("Alternate Roll") }, { "Top", _("Top") }, { "Middle", _("Middle") }, { "Bottom", _("Bottom") }, { "Side", _("Side") }, { "Left", _("Left") }, { "Right", _("Right") }, { "Center", _("Center") }, { "Rear", _("Rear") }, { "ByPassTray", _("Multipurpose") }, { "Tray1", _("Tray 1") }, { "Tray2", _("Tray 2") }, { "Tray3", _("Tray 3") }, { "Tray4", _("Tray 4") }, { "Tray5", _("Tray 5") }, { "Tray6", _("Tray 6") }, { "Tray7", _("Tray 7") }, { "Tray8", _("Tray 8") }, { "Tray9", _("Tray 9") }, { "Tray10", _("Tray 10") }, { "Tray11", _("Tray 11") }, { "Tray12", _("Tray 12") }, { "Tray13", _("Tray 13") }, { "Tray14", _("Tray 14") }, { "Tray15", _("Tray 15") }, { "Tray16", _("Tray 16") }, { "Tray17", _("Tray 17") }, { "Tray18", _("Tray 18") }, { "Tray19", _("Tray 19") }, { "Tray20", _("Tray 20") }, { "Roll1", _("Roll 1") }, { "Roll2", _("Roll 2") }, { "Roll3", _("Roll 3") }, { "Roll4", _("Roll 4") }, { "Roll5", _("Roll 5") }, { "Roll6", _("Roll 6") }, { "Roll7", _("Roll 7") }, { "Roll8", _("Roll 8") }, { "Roll9", _("Roll 9") }, { "Roll10", _("Roll 10") } }; cupsFilePrintf(fp, "*OpenUI *InputSlot: PickOne\n" "*OrderDependency: 10 AnySetup *InputSlot\n" "*DefaultInputSlot: %s\n", ppdname); for (i = 0, count = ippGetCount(attr); i < count; i ++) { pwg_ppdize_name(ippGetString(attr, i, NULL), ppdname, sizeof(ppdname)); for (j = 0; j < (int)(sizeof(sources) / sizeof(sources[0])); j ++) if (!strcmp(sources[j][0], ppdname)) { cupsFilePrintf(fp, "*InputSlot %s/%s: \"<</MediaPosition %d>>setpagedevice\"\n", ppdname, _cupsLangString(lang, sources[j][1]), j); break; } } cupsFilePuts(fp, "*CloseUI: *InputSlot\n"); } /* * MediaType... */ if ((attr = ippFindAttribute(ippGetCollection(defattr, 0), "media-type", IPP_TAG_ZERO)) != NULL) pwg_ppdize_name(ippGetString(attr, 0, NULL), ppdname, sizeof(ppdname)); else strlcpy(ppdname, "Unknown", sizeof(ppdname)); if ((attr = ippFindAttribute(response, "media-type-supported", IPP_TAG_ZERO)) != NULL && (count = ippGetCount(attr)) > 1) { static const char * const media_types[][2] = { /* "media-type" strings */ { "aluminum", _("Aluminum") }, { "auto", _("Automatic") }, { "back-print-film", _("Back Print Film") }, { "cardboard", _("Cardboard") }, { "cardstock", _("Cardstock") }, { "cd", _("CD") }, { "continuous", _("Continuous") }, { "continuous-long", _("Continuous Long") }, { "continuous-short", _("Continuous Short") }, { "disc", _("Optical Disc") }, { "disc-glossy", _("Glossy Optical Disc") }, { "disc-high-gloss", _("High Gloss Optical Disc") }, { "disc-matte", _("Matte Optical Disc") }, { "disc-satin", _("Satin Optical Disc") }, { "disc-semi-gloss", _("Semi-Gloss Optical Disc") }, { "double-wall", _("Double Wall Cardboard") }, { "dry-film", _("Dry Film") }, { "dvd", _("DVD") }, { "embossing-foil", _("Embossing Foil") }, { "end-board", _("End Board") }, { "envelope", _("Envelope") }, { "envelope-archival", _("Archival Envelope") }, { "envelope-bond", _("Bond Envelope") }, { "envelope-coated", _("Coated Envelope") }, { "envelope-cotton", _("Cotton Envelope") }, { "envelope-fine", _("Fine Envelope") }, { "envelope-heavyweight", _("Heavyweight Envelope") }, { "envelope-inkjet", _("Inkjet Envelope") }, { "envelope-lightweight", _("Lightweight Envelope") }, { "envelope-plain", _("Plain Envelope") }, { "envelope-preprinted", _("Preprinted Envelope") }, { "envelope-window", _("Windowed Envelope") }, { "fabric", _("Fabric") }, { "fabric-archival", _("Archival Fabric") }, { "fabric-glossy", _("Glossy Fabric") }, { "fabric-high-gloss", _("High Gloss Fabric") }, { "fabric-matte", _("Matte Fabric") }, { "fabric-semi-gloss", _("Semi-Gloss Fabric") }, { "fabric-waterproof", _("Waterproof Fabric") }, { "film", _("Film") }, { "flexo-base", _("Flexo Base") }, { "flexo-photo-polymer", _("Flexo Photo Polymer") }, { "flute", _("Flute") }, { "foil", _("Foil") }, { "full-cut-tabs", _("Full Cut Tabs") }, { "glass", _("Glass") }, { "glass-colored", _("Glass Colored") }, { "glass-opaque", _("Glass Opaque") }, { "glass-surfaced", _("Glass Surfaced") }, { "glass-textured", _("Glass Textured") }, { "gravure-cylinder", _("Gravure Cylinder") }, { "image-setter-paper", _("Image Setter Paper") }, { "imaging-cylinder", _("Imaging Cylinder") }, { "labels", _("Labels") }, { "labels-colored", _("Colored Labels") }, { "labels-glossy", _("Glossy Labels") }, { "labels-high-gloss", _("High Gloss Labels") }, { "labels-inkjet", _("Inkjet Labels") }, { "labels-matte", _("Matte Labels") }, { "labels-permanent", _("Permanent Labels") }, { "labels-satin", _("Satin Labels") }, { "labels-security", _("Security Labels") }, { "labels-semi-gloss", _("Semi-Gloss Labels") }, { "laminating-foil", _("Laminating Foil") }, { "letterhead", _("Letterhead") }, { "metal", _("Metal") }, { "metal-glossy", _("Metal Glossy") }, { "metal-high-gloss", _("Metal High Gloss") }, { "metal-matte", _("Metal Matte") }, { "metal-satin", _("Metal Satin") }, { "metal-semi-gloss", _("Metal Semi Gloss") }, { "mounting-tape", _("Mounting Tape") }, { "multi-layer", _("Multi Layer") }, { "multi-part-form", _("Multi Part Form") }, { "other", _("Other") }, { "paper", _("Paper") }, { "photographic", _("Photo Paper") }, { "photographic-archival", _("Photographic Archival") }, { "photographic-film", _("Photo Film") }, { "photographic-glossy", _("Glossy Photo Paper") }, { "photographic-high-gloss", _("High Gloss Photo Paper") }, { "photographic-matte", _("Matte Photo Paper") }, { "photographic-satin", _("Satin Photo Paper") }, { "photographic-semi-gloss", _("Semi-Gloss Photo Paper") }, { "plastic", _("Plastic") }, { "plastic-archival", _("Plastic Archival") }, { "plastic-colored", _("Plastic Colored") }, { "plastic-glossy", _("Plastic Glossy") }, { "plastic-high-gloss", _("Plastic High Gloss") }, { "plastic-matte", _("Plastic Matte") }, { "plastic-satin", _("Plastic Satin") }, { "plastic-semi-gloss", _("Plastic Semi Gloss") }, { "plate", _("Plate") }, { "polyester", _("Polyester") }, { "pre-cut-tabs", _("Pre Cut Tabs") }, { "roll", _("Roll") }, { "screen", _("Screen") }, { "screen-paged", _("Screen Paged") }, { "self-adhesive", _("Self Adhesive") }, { "self-adhesive-film", _("Self Adhesive Film") }, { "shrink-foil", _("Shrink Foil") }, { "single-face", _("Single Face") }, { "single-wall", _("Single Wall Cardboard") }, { "sleeve", _("Sleeve") }, { "stationery", _("Stationery") }, { "stationery-archival", _("Stationery Archival") }, { "stationery-coated", _("Coated Paper") }, { "stationery-cotton", _("Stationery Cotton") }, { "stationery-fine", _("Vellum Paper") }, { "stationery-heavyweight", _("Heavyweight Paper") }, { "stationery-heavyweight-coated", _("Stationery Heavyweight Coated") }, { "stationery-inkjet", _("Stationery Inkjet Paper") }, { "stationery-letterhead", _("Letterhead") }, { "stationery-lightweight", _("Lightweight Paper") }, { "stationery-preprinted", _("Preprinted Paper") }, { "stationery-prepunched", _("Punched Paper") }, { "tab-stock", _("Tab Stock") }, { "tractor", _("Tractor") }, { "transfer", _("Transfer") }, { "transparency", _("Transparency") }, { "triple-wall", _("Triple Wall Cardboard") }, { "wet-film", _("Wet Film") } }; cupsFilePrintf(fp, "*OpenUI *MediaType: PickOne\n" "*OrderDependency: 10 AnySetup *MediaType\n" "*DefaultMediaType: %s\n", ppdname); for (i = 0; i < (int)(sizeof(media_types) / sizeof(media_types[0])); i ++) { if (!ippContainsString(attr, media_types[i][0])) continue; pwg_ppdize_name(media_types[i][0], ppdname, sizeof(ppdname)); cupsFilePrintf(fp, "*MediaType %s/%s: \"<</MediaType(%s)>>setpagedevice\"\n", ppdname, _cupsLangString(lang, media_types[i][1]), ppdname); } cupsFilePuts(fp, "*CloseUI: *MediaType\n"); } /* * ColorModel... */ if ((attr = ippFindAttribute(response, "pwg-raster-document-type-supported", IPP_TAG_KEYWORD)) == NULL) if ((attr = ippFindAttribute(response, "urf-supported", IPP_TAG_KEYWORD)) == NULL) if ((attr = ippFindAttribute(response, "print-color-mode-supported", IPP_TAG_KEYWORD)) == NULL) attr = ippFindAttribute(response, "output-mode-supported", IPP_TAG_KEYWORD); if (attr) { const char *default_color = NULL; /* Default */ for (i = 0, count = ippGetCount(attr); i < count; i ++) { const char *keyword = ippGetString(attr, i, NULL); /* Keyword for color/bit depth */ if (!strcmp(keyword, "black_1") || !strcmp(keyword, "bi-level") || !strcmp(keyword, "process-bi-level")) { if (!default_color) cupsFilePrintf(fp, "*OpenUI *ColorModel/%s: PickOne\n" "*OrderDependency: 10 AnySetup *ColorModel\n", _cupsLangString(lang, _("Color Mode"))); cupsFilePrintf(fp, "*ColorModel FastGray/%s: \"<</cupsColorSpace 3/cupsBitsPerColor 1/cupsColorOrder 0/cupsCompression 0>>setpagedevice\"\n", _cupsLangString(lang, _("Fast Grayscale"))); if (!default_color) default_color = "FastGray"; } else if (!strcmp(keyword, "sgray_8") || !strcmp(keyword, "W8") || !strcmp(keyword, "monochrome") || !strcmp(keyword, "process-monochrome")) { if (!default_color) cupsFilePrintf(fp, "*OpenUI *ColorModel/%s: PickOne\n" "*OrderDependency: 10 AnySetup *ColorModel\n", _cupsLangString(lang, _("Color Mode"))); cupsFilePrintf(fp, "*ColorModel Gray/%s: \"<</cupsColorSpace 18/cupsBitsPerColor 8/cupsColorOrder 0/cupsCompression 0>>setpagedevice\"\n", _cupsLangString(lang, _("Grayscale"))); if (!default_color || !strcmp(default_color, "FastGray")) default_color = "Gray"; } else if (!strcmp(keyword, "srgb_8") || !strcmp(keyword, "SRGB24") || !strcmp(keyword, "color")) { if (!default_color) cupsFilePrintf(fp, "*OpenUI *ColorModel/%s: PickOne\n" "*OrderDependency: 10 AnySetup *ColorModel\n", _cupsLangString(lang, _("Color Mode"))); cupsFilePrintf(fp, "*ColorModel RGB/%s: \"<</cupsColorSpace 19/cupsBitsPerColor 8/cupsColorOrder 0/cupsCompression 0>>setpagedevice\"\n", _cupsLangString(lang, _("Color"))); default_color = "RGB"; } else if (!strcmp(keyword, "adobe-rgb_16") || !strcmp(keyword, "ADOBERGB48")) { if (!default_color) cupsFilePrintf(fp, "*OpenUI *ColorModel/%s: PickOne\n" "*OrderDependency: 10 AnySetup *ColorModel\n", _cupsLangString(lang, _("Color Mode"))); cupsFilePrintf(fp, "*ColorModel AdobeRGB/%s: \"<</cupsColorSpace 20/cupsBitsPerColor 16/cupsColorOrder 0/cupsCompression 0>>setpagedevice\"\n", _cupsLangString(lang, _("Deep Color"))); if (!default_color) default_color = "AdobeRGB"; } } if (default_color) { cupsFilePrintf(fp, "*DefaultColorModel: %s\n", default_color); cupsFilePuts(fp, "*CloseUI: *ColorModel\n"); } } /* * Duplex... */ if ((attr = ippFindAttribute(response, "sides-supported", IPP_TAG_KEYWORD)) != NULL && ippContainsString(attr, "two-sided-long-edge")) { cupsFilePrintf(fp, "*OpenUI *Duplex/%s: PickOne\n" "*OrderDependency: 10 AnySetup *Duplex\n" "*DefaultDuplex: None\n" "*Duplex None/%s: \"<</Duplex false>>setpagedevice\"\n" "*Duplex DuplexNoTumble/%s: \"<</Duplex true/Tumble false>>setpagedevice\"\n" "*Duplex DuplexTumble/%s: \"<</Duplex true/Tumble true>>setpagedevice\"\n" "*CloseUI: *Duplex\n", _cupsLangString(lang, _("2-Sided Printing")), _cupsLangString(lang, _("Off (1-Sided)")), _cupsLangString(lang, _("Long-Edge (Portrait)")), _cupsLangString(lang, _("Short-Edge (Landscape)"))); if ((attr = ippFindAttribute(response, "pwg-raster-document-sheet-back", IPP_TAG_KEYWORD)) != NULL) { const char *keyword = ippGetString(attr, 0, NULL); /* Keyword value */ if (!strcmp(keyword, "flipped")) cupsFilePuts(fp, "*cupsBackSide: Flipped\n"); else if (!strcmp(keyword, "manual-tumble")) cupsFilePuts(fp, "*cupsBackSide: ManualTumble\n"); else if (!strcmp(keyword, "normal")) cupsFilePuts(fp, "*cupsBackSide: Normal\n"); else cupsFilePuts(fp, "*cupsBackSide: Rotated\n"); } else if ((attr = ippFindAttribute(response, "urf-supported", IPP_TAG_KEYWORD)) != NULL) { for (i = 0, count = ippGetCount(attr); i < count; i ++) { const char *dm = ippGetString(attr, i, NULL); /* DM value */ if (!_cups_strcasecmp(dm, "DM1")) { cupsFilePuts(fp, "*cupsBackSide: Normal\n"); break; } else if (!_cups_strcasecmp(dm, "DM2")) { cupsFilePuts(fp, "*cupsBackSide: Flipped\n"); break; } else if (!_cups_strcasecmp(dm, "DM3")) { cupsFilePuts(fp, "*cupsBackSide: Rotated\n"); break; } else if (!_cups_strcasecmp(dm, "DM4")) { cupsFilePuts(fp, "*cupsBackSide: ManualTumble\n"); break; } } } } /* * Finishing options... */ if ((attr = ippFindAttribute(response, "finishings-col-database", IPP_TAG_BEGIN_COLLECTION)) != NULL) { ipp_t *col; /* Collection value */ ipp_attribute_t *template; /* "finishing-template" member */ const char *name; /* String name */ int value; /* Enum value, if any */ cups_array_t *names; /* Names we've added */ count = ippGetCount(attr); names = cupsArrayNew3((cups_array_func_t)strcmp, NULL, NULL, 0, (cups_acopy_func_t)strdup, (cups_afree_func_t)free); cupsFilePrintf(fp, "*OpenUI *cupsFinishingTemplate/%s: PickMany\n" "*OrderDependency: 10 AnySetup *cupsFinishingTemplate\n" "*DefaultcupsFinishingTemplate: none\n" "*cupsFinishingTemplate none/%s: \"\"\n" "*cupsIPPFinishings 3/none: \"*cupsFinishingTemplate none\"\n", _cupsLangString(lang, _("Finishing")), _cupsLangString(lang, _("No Finishing"))); for (i = 0; i < count; i ++) { col = ippGetCollection(attr, i); template = ippFindAttribute(col, "finishing-template", IPP_TAG_ZERO); if ((name = ippGetString(template, 0, NULL)) == NULL || !strcmp(name, "none")) continue; if (cupsArrayFind(names, (char *)name)) continue; /* Already did this finishing template */ cupsArrayAdd(names, (char *)name); for (j = 0; j < (int)(sizeof(finishings) / sizeof(finishings[0])); j ++) { if (!strcmp(finishings[j][0], name)) { cupsFilePrintf(fp, "*cupsFinishingTemplate %s/%s: \"\"\n", name, _cupsLangString(lang, finishings[j][1])); value = ippEnumValue("finishings", name); if (value) cupsFilePrintf(fp, "*cupsIPPFinishings %d/%s: \"*cupsFinishingTemplate %s\"\n", value, name, name); break; } } } cupsArrayDelete(names); cupsFilePuts(fp, "*CloseUI: *cupsFinishingTemplate\n"); } else if ((attr = ippFindAttribute(response, "finishings-supported", IPP_TAG_ENUM)) != NULL && (count = ippGetCount(attr)) > 1 ) { const char *name; /* String name */ int value; /* Enum value, if any */ count = ippGetCount(attr); cupsFilePrintf(fp, "*OpenUI *cupsFinishingTemplate/%s: PickMany\n" "*OrderDependency: 10 AnySetup *cupsFinishingTemplate\n" "*DefaultcupsFinishingTemplate: none\n" "*cupsFinishingTemplate none/%s: \"\"\n" "*cupsIPPFinishings 3/none: \"*cupsFinishingTemplate none\"\n", _cupsLangString(lang, _("Finishing")), _cupsLangString(lang, _("No Finishing"))); for (i = 0; i < count; i ++) { if ((value = ippGetInteger(attr, i)) == 3) continue; name = ippEnumString("finishings", value); for (j = 0; j < (int)(sizeof(finishings) / sizeof(finishings[0])); j ++) { if (!strcmp(finishings[j][0], name)) { cupsFilePrintf(fp, "*cupsFinishingTemplate %s/%s: \"\"\n", name, _cupsLangString(lang, finishings[j][1])); cupsFilePrintf(fp, "*cupsIPPFinishings %d/%s: \"*cupsFinishingTemplate %s\"\n", value, name, name); break; } } } cupsFilePuts(fp, "*CloseUI: *cupsFinishingTemplate\n"); } /* * cupsPrintQuality and DefaultResolution... */ if ((attr = ippFindAttribute(response, "pwg-raster-document-resolution-supported", IPP_TAG_RESOLUTION)) != NULL) { count = ippGetCount(attr); pwg_ppdize_resolution(attr, count / 2, &xres, &yres, ppdname, sizeof(ppdname)); cupsFilePrintf(fp, "*DefaultResolution: %s\n", ppdname); cupsFilePrintf(fp, "*OpenUI *cupsPrintQuality/%s: PickOne\n" "*OrderDependency: 10 AnySetup *cupsPrintQuality\n" "*DefaultcupsPrintQuality: Normal\n", _cupsLangString(lang, _("Print Quality"))); if (count > 2) { pwg_ppdize_resolution(attr, 0, &xres, &yres, NULL, 0); cupsFilePrintf(fp, "*cupsPrintQuality Draft/%s: \"<</HWResolution[%d %d]>>setpagedevice\"\n", _cupsLangString(lang, _("Draft")), xres, yres); } pwg_ppdize_resolution(attr, count / 2, &xres, &yres, NULL, 0); cupsFilePrintf(fp, "*cupsPrintQuality Normal/%s: \"<</HWResolution[%d %d]>>setpagedevice\"\n", _cupsLangString(lang, _("Normal")), xres, yres); if (count > 1) { pwg_ppdize_resolution(attr, count - 1, &xres, &yres, NULL, 0); cupsFilePrintf(fp, "*cupsPrintQuality High/%s: \"<</HWResolution[%d %d]>>setpagedevice\"\n", _cupsLangString(lang, _("High")), xres, yres); } cupsFilePuts(fp, "*CloseUI: *cupsPrintQuality\n"); } else if ((attr = ippFindAttribute(response, "urf-supported", IPP_TAG_KEYWORD)) != NULL) { int lowdpi = 0, hidpi = 0; /* Lower and higher resolution */ for (i = 0, count = ippGetCount(attr); i < count; i ++) { const char *rs = ippGetString(attr, i, NULL); /* RS value */ if (_cups_strncasecmp(rs, "RS", 2)) continue; lowdpi = atoi(rs + 2); if ((rs = strrchr(rs, '-')) != NULL) hidpi = atoi(rs + 1); else hidpi = lowdpi; break; } if (lowdpi == 0) { /* * Invalid "urf-supported" value... */ goto bad_ppd; } else { /* * Generate print qualities based on low and high DPIs... */ cupsFilePrintf(fp, "*DefaultResolution: %ddpi\n", lowdpi); cupsFilePrintf(fp, "*OpenUI *cupsPrintQuality/%s: PickOne\n" "*OrderDependency: 10 AnySetup *cupsPrintQuality\n" "*DefaultcupsPrintQuality: Normal\n", _cupsLangString(lang, _("Print Quality"))); if ((lowdpi & 1) == 0) cupsFilePrintf(fp, "*cupsPrintQuality Draft/%s: \"<</HWResolution[%d %d]>>setpagedevice\"\n", _cupsLangString(lang, _("Draft")), lowdpi, lowdpi / 2); cupsFilePrintf(fp, "*cupsPrintQuality Normal/%s: \"<</HWResolution[%d %d]>>setpagedevice\"\n", _cupsLangString(lang, _("Normal")), lowdpi, lowdpi); if (hidpi > lowdpi) cupsFilePrintf(fp, "*cupsPrintQuality High/%s: \"<</HWResolution[%d %d]>>setpagedevice\"\n", _cupsLangString(lang, _("High")), hidpi, hidpi); cupsFilePuts(fp, "*CloseUI: *cupsPrintQuality\n"); } } else if (is_apple || is_pwg) goto bad_ppd; else if ((attr = ippFindAttribute(response, "printer-resolution-default", IPP_TAG_RESOLUTION)) != NULL) { pwg_ppdize_resolution(attr, 0, &xres, &yres, ppdname, sizeof(ppdname)); cupsFilePrintf(fp, "*DefaultResolution: %s\n", ppdname); } else cupsFilePuts(fp, "*DefaultResolution: 300dpi\n"); /* * Close up and return... */ cupsFileClose(fp); return (buffer); /* * If we get here then there was a problem creating the PPD... */ bad_ppd: cupsFileClose(fp); unlink(buffer); *buffer = '\0'; return (NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-93'], 'message': 'Only list supported PDLs (Issue #4923)'</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 WriteMIFFImage(const ImageInfo *image_info, Image *image) { #if defined(MAGICKCORE_BZLIB_DELEGATE) bz_stream bzip_info; #endif char buffer[MaxTextExtent]; CompressionType compression; const char *property, *value; IndexPacket index; #if defined(MAGICKCORE_LZMA_DELEGATE) lzma_allocator allocator; lzma_stream initialize_lzma = LZMA_STREAM_INIT, lzma_info; #endif MagickBooleanType status; MagickOffsetType scene; PixelPacket pixel; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t imageListLength, length, packet_size; ssize_t y; unsigned char *compress_pixels, *pixels, *q; #if defined(MAGICKCORE_ZLIB_DELEGATE) z_stream zip_info; #endif /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); scene=0; imageListLength=GetImageListLength(image); do { /* Allocate image pixels. */ if ((image->storage_class == PseudoClass) && (image->colors > (size_t) (GetQuantumRange(image->depth)+1))) (void) SetImageStorageClass(image,DirectClass); image->depth=image->depth <= 8 ? 8UL : image->depth <= 16 ? 16UL : image->depth <= 32 ? 32UL : 64UL; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if ((image->storage_class != PseudoClass) && (image->depth >= 16) && (quantum_info->format == UndefinedQuantumFormat) && (IsHighDynamicRangeImage(image,&image->exception) != MagickFalse)) { status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) { quantum_info=DestroyQuantumInfo(quantum_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } } else if (image->depth < 16) (void) DeleteImageProperty(image,"quantum:format"); compression=UndefinedCompression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { #if !defined(MAGICKCORE_LZMA_DELEGATE) case LZMACompression: compression=NoCompression; break; #endif #if !defined(MAGICKCORE_ZLIB_DELEGATE) case LZWCompression: case ZipCompression: compression=NoCompression; break; #endif #if !defined(MAGICKCORE_BZLIB_DELEGATE) case BZipCompression: compression=NoCompression; break; #endif case RLECompression: { if (quantum_info->format == FloatingPointQuantumFormat) compression=NoCompression; break; } default: break; } packet_size=(size_t) (quantum_info->depth/8); if (image->storage_class == DirectClass) packet_size=(size_t) (3*quantum_info->depth/8); if (IsGrayColorspace(image->colorspace) != MagickFalse) packet_size=(size_t) (quantum_info->depth/8); if (image->matte != MagickFalse) packet_size+=quantum_info->depth/8; if (image->colorspace == CMYKColorspace) packet_size+=quantum_info->depth/8; if (compression == RLECompression) packet_size++; length=MagickMax(BZipMaxExtent(packet_size*image->columns),ZipMaxExtent( packet_size*image->columns)); if ((compression == BZipCompression) || (compression == ZipCompression)) if (length != (size_t) ((unsigned int) length)) compression=NoCompression; compress_pixels=(unsigned char *) AcquireQuantumMemory(length, sizeof(*compress_pixels)); if (compress_pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Write MIFF header. */ (void) WriteBlobString(image,"id=ImageMagick version=1.0\n"); (void) FormatLocaleString(buffer,MaxTextExtent, "class=%s colors=%.20g matte=%s\n",CommandOptionToMnemonic( MagickClassOptions,image->storage_class),(double) image->colors, CommandOptionToMnemonic(MagickBooleanOptions,(ssize_t) image->matte)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"columns=%.20g rows=%.20g " "depth=%.20g\n",(double) image->columns,(double) image->rows,(double) image->depth); (void) WriteBlobString(image,buffer); if (image->type != UndefinedType) { (void) FormatLocaleString(buffer,MaxTextExtent,"type=%s\n", CommandOptionToMnemonic(MagickTypeOptions,image->type)); (void) WriteBlobString(image,buffer); } if (image->colorspace != UndefinedColorspace) { (void) FormatLocaleString(buffer,MaxTextExtent,"colorspace=%s\n", CommandOptionToMnemonic(MagickColorspaceOptions,image->colorspace)); (void) WriteBlobString(image,buffer); } if (image->intensity != UndefinedPixelIntensityMethod) { (void) FormatLocaleString(buffer,MaxTextExtent,"pixel-intensity=%s\n", CommandOptionToMnemonic(MagickPixelIntensityOptions, image->intensity)); (void) WriteBlobString(image,buffer); } if (image->endian != UndefinedEndian) { (void) FormatLocaleString(buffer,MaxTextExtent,"endian=%s\n", CommandOptionToMnemonic(MagickEndianOptions,image->endian)); (void) WriteBlobString(image,buffer); } if (compression != UndefinedCompression) { (void) FormatLocaleString(buffer,MaxTextExtent,"compression=%s " "quality=%.20g\n",CommandOptionToMnemonic(MagickCompressOptions, compression),(double) image->quality); (void) WriteBlobString(image,buffer); } if (image->units != UndefinedResolution) { (void) FormatLocaleString(buffer,MaxTextExtent,"units=%s\n", CommandOptionToMnemonic(MagickResolutionOptions,image->units)); (void) WriteBlobString(image,buffer); } if ((image->x_resolution != 0) || (image->y_resolution != 0)) { (void) FormatLocaleString(buffer,MaxTextExtent, "resolution=%gx%g\n",image->x_resolution,image->y_resolution); (void) WriteBlobString(image,buffer); } if ((image->page.width != 0) || (image->page.height != 0)) { (void) FormatLocaleString(buffer,MaxTextExtent, "page=%.20gx%.20g%+.20g%+.20g\n",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); (void) WriteBlobString(image,buffer); } else if ((image->page.x != 0) || (image->page.y != 0)) { (void) FormatLocaleString(buffer,MaxTextExtent,"page=%+ld%+ld\n", (long) image->page.x,(long) image->page.y); (void) WriteBlobString(image,buffer); } if ((image->tile_offset.x != 0) || (image->tile_offset.y != 0)) { (void) FormatLocaleString(buffer,MaxTextExtent,"tile-offset=%+ld%+ld\n", (long) image->tile_offset.x,(long) image->tile_offset.y); (void) WriteBlobString(image,buffer); } if ((GetNextImageInList(image) != (Image *) NULL) || (GetPreviousImageInList(image) != (Image *) NULL)) { if (image->scene == 0) (void) FormatLocaleString(buffer,MaxTextExtent,"iterations=%.20g " "delay=%.20g ticks-per-second=%.20g\n",(double) image->iterations, (double) image->delay,(double) image->ticks_per_second); else (void) FormatLocaleString(buffer,MaxTextExtent,"scene=%.20g " "iterations=%.20g delay=%.20g ticks-per-second=%.20g\n",(double) image->scene,(double) image->iterations,(double) image->delay, (double) image->ticks_per_second); (void) WriteBlobString(image,buffer); } else { if (image->scene != 0) { (void) FormatLocaleString(buffer,MaxTextExtent,"scene=%.20g\n", (double) image->scene); (void) WriteBlobString(image,buffer); } if (image->iterations != 0) { (void) FormatLocaleString(buffer,MaxTextExtent,"iterations=%.20g\n", (double) image->iterations); (void) WriteBlobString(image,buffer); } if (image->delay != 0) { (void) FormatLocaleString(buffer,MaxTextExtent,"delay=%.20g\n", (double) image->delay); (void) WriteBlobString(image,buffer); } if (image->ticks_per_second != UndefinedTicksPerSecond) { (void) FormatLocaleString(buffer,MaxTextExtent, "ticks-per-second=%.20g\n",(double) image->ticks_per_second); (void) WriteBlobString(image,buffer); } } if (image->gravity != UndefinedGravity) { (void) FormatLocaleString(buffer,MaxTextExtent,"gravity=%s\n", CommandOptionToMnemonic(MagickGravityOptions,image->gravity)); (void) WriteBlobString(image,buffer); } if (image->dispose != UndefinedDispose) { (void) FormatLocaleString(buffer,MaxTextExtent,"dispose=%s\n", CommandOptionToMnemonic(MagickDisposeOptions,image->dispose)); (void) WriteBlobString(image,buffer); } if (image->rendering_intent != UndefinedIntent) { (void) FormatLocaleString(buffer,MaxTextExtent, "rendering-intent=%s\n", CommandOptionToMnemonic(MagickIntentOptions,image->rendering_intent)); (void) WriteBlobString(image,buffer); } if (image->gamma != 0.0) { (void) FormatLocaleString(buffer,MaxTextExtent,"gamma=%g\n", image->gamma); (void) WriteBlobString(image,buffer); } if (image->chromaticity.white_point.x != 0.0) { /* Note chomaticity points. */ (void) FormatLocaleString(buffer,MaxTextExtent,"red-primary=%g," "%g green-primary=%g,%g blue-primary=%g,%g\n", image->chromaticity.red_primary.x,image->chromaticity.red_primary.y, image->chromaticity.green_primary.x, image->chromaticity.green_primary.y, image->chromaticity.blue_primary.x, image->chromaticity.blue_primary.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "white-point=%g,%g\n",image->chromaticity.white_point.x, image->chromaticity.white_point.y); (void) WriteBlobString(image,buffer); } if (image->orientation != UndefinedOrientation) { (void) FormatLocaleString(buffer,MaxTextExtent,"orientation=%s\n", CommandOptionToMnemonic(MagickOrientationOptions,image->orientation)); (void) WriteBlobString(image,buffer); } if (image->profiles != (void *) NULL) { const char *name; const StringInfo *profile; /* Write image profile names. */ ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { (void) FormatLocaleString(buffer,MagickPathExtent,"profile=%s\n", name); (void) WriteBlobString(image,buffer); } name=GetNextImageProfile(image); } } if (image->montage != (char *) NULL) { (void) FormatLocaleString(buffer,MaxTextExtent,"montage=%s\n", image->montage); (void) WriteBlobString(image,buffer); } if (quantum_info->format == FloatingPointQuantumFormat) (void) SetImageProperty(image,"quantum:format","floating-point"); ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { (void) FormatLocaleString(buffer,MaxTextExtent,"%s=",property); (void) WriteBlobString(image,buffer); value=GetImageProperty(image,property); if (value != (const char *) NULL) { size_t length; length=strlen(value); for (i=0; i < (ssize_t) length; i++) if ((isspace((int) ((unsigned char) value[i])) != 0) || (value[i] == '}')) break; if ((i == (ssize_t) length) && (i != 0)) (void) WriteBlob(image,length,(const unsigned char *) value); else { (void) WriteBlobByte(image,'{'); if (strchr(value,'}') == (char *) NULL) (void) WriteBlob(image,length,(const unsigned char *) value); else for (i=0; i < (ssize_t) length; i++) { if (value[i] == (int) '}') (void) WriteBlobByte(image,'\\'); (void) WriteBlobByte(image,(unsigned char) value[i]); } (void) WriteBlobByte(image,'}'); } } (void) WriteBlobByte(image,'\n'); property=GetNextImageProperty(image); } (void) WriteBlobString(image,"\f\n:\032"); if (image->montage != (char *) NULL) { /* Write montage tile directory. */ if (image->directory != (char *) NULL) (void) WriteBlob(image,strlen(image->directory),(unsigned char *) image->directory); (void) WriteBlobByte(image,'\0'); } if (image->profiles != 0) { const char *name; const StringInfo *profile; /* Write image profile blob. */ ResetImageProfileIterator(image); name=GetNextImageProfile(image); while (name != (const char *) NULL) { profile=GetImageProfile(image,name); (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength(profile)); (void) WriteBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); name=GetNextImageProfile(image); } } if (image->storage_class == PseudoClass) { size_t packet_size; unsigned char *colormap, *q; /* Allocate colormap. */ packet_size=(size_t) (3*quantum_info->depth/8); colormap=(unsigned char *) AcquireQuantumMemory(image->colors, packet_size*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Write colormap to file. */ q=colormap; for (i=0; i < (ssize_t) image->colors; i++) { switch (quantum_info->depth) { default: ThrowWriterException(CorruptImageError,"ImageDepthNotSupported"); case 32: { register unsigned int pixel; pixel=ScaleQuantumToLong(image->colormap[i].red); q=PopLongPixel(MSBEndian,pixel,q); pixel=ScaleQuantumToLong(image->colormap[i].green); q=PopLongPixel(MSBEndian,pixel,q); pixel=ScaleQuantumToLong(image->colormap[i].blue); q=PopLongPixel(MSBEndian,pixel,q); break; } case 16: { register unsigned short pixel; pixel=ScaleQuantumToShort(image->colormap[i].red); q=PopShortPixel(MSBEndian,pixel,q); pixel=ScaleQuantumToShort(image->colormap[i].green); q=PopShortPixel(MSBEndian,pixel,q); pixel=ScaleQuantumToShort(image->colormap[i].blue); q=PopShortPixel(MSBEndian,pixel,q); break; } case 8: { register unsigned char pixel; pixel=(unsigned char) ScaleQuantumToChar(image->colormap[i].red); q=PopCharPixel(pixel,q); pixel=(unsigned char) ScaleQuantumToChar( image->colormap[i].green); q=PopCharPixel(pixel,q); pixel=(unsigned char) ScaleQuantumToChar(image->colormap[i].blue); q=PopCharPixel(pixel,q); break; } } } (void) WriteBlob(image,packet_size*image->colors,colormap); colormap=(unsigned char *) RelinquishMagickMemory(colormap); } /* Write image pixels to file. */ status=MagickTrue; switch (compression) { #if defined(MAGICKCORE_BZLIB_DELEGATE) case BZipCompression: { int code; bzip_info.bzalloc=AcquireBZIPMemory; bzip_info.bzfree=RelinquishBZIPMemory; bzip_info.opaque=(void *) NULL; code=BZ2_bzCompressInit(&bzip_info,(int) (image->quality == UndefinedCompressionQuality ? 7 : MagickMin(image->quality/10, 9)),(int) image_info->verbose,0); if (code != BZ_OK) status=MagickFalse; break; } #endif #if defined(MAGICKCORE_LZMA_DELEGATE) case LZMACompression: { int code; allocator.alloc=AcquireLZMAMemory; allocator.free=RelinquishLZMAMemory; allocator.opaque=(void *) NULL; lzma_info=initialize_lzma; lzma_info.allocator=&allocator; code=lzma_easy_encoder(&lzma_info,image->quality/10,LZMA_CHECK_SHA256); if (code != LZMA_OK) status=MagickTrue; break; } #endif #if defined(MAGICKCORE_ZLIB_DELEGATE) case LZWCompression: case ZipCompression: { int code; zip_info.zalloc=AcquireZIPMemory; zip_info.zfree=RelinquishZIPMemory; zip_info.opaque=(void *) NULL; code=deflateInit(&zip_info,(int) (image->quality == UndefinedCompressionQuality ? 7 : MagickMin(image->quality/10,9))); if (code != Z_OK) status=MagickFalse; break; } #endif default: break; } quantum_type=GetQuantumType(image,&image->exception); pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; if (status == MagickFalse) break; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); q=pixels; switch (compression) { #if defined(MAGICKCORE_BZLIB_DELEGATE) case BZipCompression: { bzip_info.next_in=(char *) pixels; bzip_info.avail_in=(unsigned int) (packet_size*image->columns); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); do { int code; bzip_info.next_out=(char *) compress_pixels; bzip_info.avail_out=(unsigned int) BZipMaxExtent(packet_size* image->columns); code=BZ2_bzCompress(&bzip_info,BZ_FLUSH); if (code != BZ_OK) status=MagickFalse; length=(size_t) (bzip_info.next_out-(char *) compress_pixels); if (length != 0) { (void) WriteBlobMSBLong(image,(unsigned int) length); (void) WriteBlob(image,length,compress_pixels); } } while (bzip_info.avail_in != 0); break; } #endif #if defined(MAGICKCORE_LZMA_DELEGATE) case LZMACompression: { lzma_info.next_in=pixels; lzma_info.avail_in=packet_size*image->columns; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); do { int code; lzma_info.next_out=compress_pixels; lzma_info.avail_out=packet_size*image->columns; code=lzma_code(&lzma_info,LZMA_RUN); if (code != LZMA_OK) status=MagickFalse; length=(size_t) (lzma_info.next_out-compress_pixels); if (length != 0) { (void) WriteBlobMSBLong(image,(unsigned int) length); (void) WriteBlob(image,length,compress_pixels); } } while (lzma_info.avail_in != 0); break; } #endif #if defined(MAGICKCORE_ZLIB_DELEGATE) case LZWCompression: case ZipCompression: { zip_info.next_in=pixels; zip_info.avail_in=(uInt) (packet_size*image->columns); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); do { int code; zip_info.next_out=compress_pixels; zip_info.avail_out=(uInt) ZipMaxExtent(packet_size*image->columns); code=deflate(&zip_info,Z_SYNC_FLUSH); if (code != Z_OK) status=MagickFalse; length=(size_t) (zip_info.next_out-compress_pixels); if (length != 0) { (void) WriteBlobMSBLong(image,(unsigned int) length); (void) WriteBlob(image,length,compress_pixels); } } while (zip_info.avail_in != 0); break; } #endif case RLECompression: { pixel=(*p); index=(IndexPacket) 0; if (indexes != (IndexPacket *) NULL) index=(*indexes); length=255; for (x=0; x < (ssize_t) image->columns; x++) { if ((length < 255) && (x < (ssize_t) (image->columns-1)) && (IsColorEqual(p,&pixel) != MagickFalse) && ((image->matte == MagickFalse) || (GetPixelOpacity(p) == pixel.opacity)) && ((indexes == (IndexPacket *) NULL) || (index == GetPixelIndex(indexes+x)))) length++; else { if (x > 0) q=PopRunlengthPacket(image,q,length,pixel,index); length=0; } pixel=(*p); if (indexes != (IndexPacket *) NULL) index=GetPixelIndex(indexes+x); p++; } q=PopRunlengthPacket(image,q,length,pixel,index); (void) WriteBlob(image,(size_t) (q-pixels),pixels); break; } default: { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); (void) WriteBlob(image,packet_size*image->columns,pixels); break; } } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } switch (compression) { #if defined(MAGICKCORE_BZLIB_DELEGATE) case BZipCompression: { int code; for ( ; ; ) { if (status == MagickFalse) break; bzip_info.next_out=(char *) compress_pixels; bzip_info.avail_out=(unsigned int) BZipMaxExtent(packet_size* image->columns); code=BZ2_bzCompress(&bzip_info,BZ_FINISH); length=(size_t) (bzip_info.next_out-(char *) compress_pixels); if (length != 0) { (void) WriteBlobMSBLong(image,(unsigned int) length); (void) WriteBlob(image,length,compress_pixels); } if (code == BZ_STREAM_END) break; } code=BZ2_bzCompressEnd(&bzip_info); if (code != BZ_OK) status=MagickFalse; break; } #endif #if defined(MAGICKCORE_LZMA_DELEGATE) case LZMACompression: { int code; for ( ; ; ) { if (status == MagickFalse) break; lzma_info.next_out=compress_pixels; lzma_info.avail_out=packet_size*image->columns; code=lzma_code(&lzma_info,LZMA_FINISH); length=(size_t) (lzma_info.next_out-compress_pixels); if (length > 6) { (void) WriteBlobMSBLong(image,(unsigned int) length); (void) WriteBlob(image,length,compress_pixels); } if (code == LZMA_STREAM_END) break; } lzma_end(&lzma_info); break; } #endif #if defined(MAGICKCORE_ZLIB_DELEGATE) case LZWCompression: case ZipCompression: { int code; for ( ; ; ) { if (status == MagickFalse) break; zip_info.next_out=compress_pixels; zip_info.avail_out=(uInt) ZipMaxExtent(packet_size*image->columns); code=deflate(&zip_info,Z_FINISH); length=(size_t) (zip_info.next_out-compress_pixels); if (length > 6) { (void) WriteBlobMSBLong(image,(unsigned int) length); (void) WriteBlob(image,length,compress_pixels); } if (code == Z_STREAM_END) break; } code=deflateEnd(&zip_info); if (code != Z_OK) status=MagickFalse; break; } #endif default: break; } quantum_info=DestroyQuantumInfo(quantum_info); compress_pixels=(unsigned char *) RelinquishMagickMemory(compress_pixels); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(status); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1191'</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 chmd_read_headers(struct mspack_system *sys, struct mspack_file *fh, struct mschmd_header *chm, int entire) { unsigned int section, name_len, x, errors, num_chunks; unsigned char buf[0x54], *chunk = NULL, *name, *p, *end; struct mschmd_file *fi, *link = NULL; off_t offset, length; int num_entries; /* initialise pointers */ chm->files = NULL; chm->sysfiles = NULL; chm->chunk_cache = NULL; chm->sec0.base.chm = chm; chm->sec0.base.id = 0; chm->sec1.base.chm = chm; chm->sec1.base.id = 1; chm->sec1.content = NULL; chm->sec1.control = NULL; chm->sec1.spaninfo = NULL; chm->sec1.rtable = NULL; /* read the first header */ if (sys->read(fh, &buf[0], chmhead_SIZEOF) != chmhead_SIZEOF) { return MSPACK_ERR_READ; } /* check ITSF signature */ if (EndGetI32(&buf[chmhead_Signature]) != 0x46535449) { return MSPACK_ERR_SIGNATURE; } /* check both header GUIDs */ if (mspack_memcmp(&buf[chmhead_GUID1], &guids[0], 32L) != 0) { D(("incorrect GUIDs")) return MSPACK_ERR_SIGNATURE; } chm->version = EndGetI32(&buf[chmhead_Version]); chm->timestamp = EndGetM32(&buf[chmhead_Timestamp]); chm->language = EndGetI32(&buf[chmhead_LanguageID]); if (chm->version > 3) { sys->message(fh, "WARNING; CHM version > 3"); } /* read the header section table */ if (sys->read(fh, &buf[0], chmhst3_SIZEOF) != chmhst3_SIZEOF) { return MSPACK_ERR_READ; } /* chmhst3_OffsetCS0 does not exist in version 1 or 2 CHM files. * The offset will be corrected later, once HS1 is read. */ if (read_off64(&offset, &buf[chmhst_OffsetHS0], sys, fh) || read_off64(&chm->dir_offset, &buf[chmhst_OffsetHS1], sys, fh) || read_off64(&chm->sec0.offset, &buf[chmhst3_OffsetCS0], sys, fh)) { return MSPACK_ERR_DATAFORMAT; } /* seek to header section 0 */ if (sys->seek(fh, offset, MSPACK_SYS_SEEK_START)) { return MSPACK_ERR_SEEK; } /* read header section 0 */ if (sys->read(fh, &buf[0], chmhs0_SIZEOF) != chmhs0_SIZEOF) { return MSPACK_ERR_READ; } if (read_off64(&chm->length, &buf[chmhs0_FileLen], sys, fh)) { return MSPACK_ERR_DATAFORMAT; } /* seek to header section 1 */ if (sys->seek(fh, chm->dir_offset, MSPACK_SYS_SEEK_START)) { return MSPACK_ERR_SEEK; } /* read header section 1 */ if (sys->read(fh, &buf[0], chmhs1_SIZEOF) != chmhs1_SIZEOF) { return MSPACK_ERR_READ; } chm->dir_offset = sys->tell(fh); chm->chunk_size = EndGetI32(&buf[chmhs1_ChunkSize]); chm->density = EndGetI32(&buf[chmhs1_Density]); chm->depth = EndGetI32(&buf[chmhs1_Depth]); chm->index_root = EndGetI32(&buf[chmhs1_IndexRoot]); chm->num_chunks = EndGetI32(&buf[chmhs1_NumChunks]); chm->first_pmgl = EndGetI32(&buf[chmhs1_FirstPMGL]); chm->last_pmgl = EndGetI32(&buf[chmhs1_LastPMGL]); if (chm->version < 3) { /* versions before 3 don't have chmhst3_OffsetCS0 */ chm->sec0.offset = chm->dir_offset + (chm->chunk_size * chm->num_chunks); } /* check if content offset or file size is wrong */ if (chm->sec0.offset > chm->length) { D(("content section begins after file has ended")) return MSPACK_ERR_DATAFORMAT; } /* ensure there are chunks and that chunk size is * large enough for signature and num_entries */ if (chm->chunk_size < (pmgl_Entries + 2)) { D(("chunk size not large enough")) return MSPACK_ERR_DATAFORMAT; } if (chm->num_chunks == 0) { D(("no chunks")) return MSPACK_ERR_DATAFORMAT; } /* The chunk_cache data structure is not great; large values for num_chunks * or num_chunks*chunk_size can exhaust all memory. Until a better chunk * cache is implemented, put arbitrary limits on num_chunks and chunk size. */ if (chm->num_chunks > 100000) { D(("more than 100,000 chunks")) return MSPACK_ERR_DATAFORMAT; } if ((off_t)chm->chunk_size * (off_t)chm->num_chunks > chm->length) { D(("chunks larger than entire file")) return MSPACK_ERR_DATAFORMAT; } /* common sense checks on header section 1 fields */ if ((chm->chunk_size & (chm->chunk_size - 1)) != 0) { sys->message(fh, "WARNING; chunk size is not a power of two"); } if (chm->first_pmgl != 0) { sys->message(fh, "WARNING; first PMGL chunk is not zero"); } if (chm->first_pmgl > chm->last_pmgl) { D(("first pmgl chunk is after last pmgl chunk")) return MSPACK_ERR_DATAFORMAT; } if (chm->index_root != 0xFFFFFFFF && chm->index_root > chm->num_chunks) { D(("index_root outside valid range")) return MSPACK_ERR_DATAFORMAT; } /* if we are doing a quick read, stop here! */ if (!entire) { return MSPACK_ERR_OK; } /* seek to the first PMGL chunk, and reduce the number of chunks to read */ if ((x = chm->first_pmgl) != 0) { if (sys->seek(fh,(off_t) (x * chm->chunk_size), MSPACK_SYS_SEEK_CUR)) { return MSPACK_ERR_SEEK; } } num_chunks = chm->last_pmgl - x + 1; if (!(chunk = (unsigned char *) sys->alloc(sys, (size_t)chm->chunk_size))) { return MSPACK_ERR_NOMEMORY; } /* read and process all chunks from FirstPMGL to LastPMGL */ errors = 0; while (num_chunks--) { /* read next chunk */ if (sys->read(fh, chunk, (int)chm->chunk_size) != (int)chm->chunk_size) { sys->free(chunk); return MSPACK_ERR_READ; } /* process only directory (PMGL) chunks */ if (EndGetI32(&chunk[pmgl_Signature]) != 0x4C474D50) continue; if (EndGetI32(&chunk[pmgl_QuickRefSize]) < 2) { sys->message(fh, "WARNING; PMGL quickref area is too small"); } if (EndGetI32(&chunk[pmgl_QuickRefSize]) > ((int)chm->chunk_size - pmgl_Entries)) { sys->message(fh, "WARNING; PMGL quickref area is too large"); } p = &chunk[pmgl_Entries]; end = &chunk[chm->chunk_size - 2]; num_entries = EndGetI16(end); while (num_entries--) { READ_ENCINT(name_len); if (name_len > (unsigned int) (end - p)) goto chunk_end; name = p; p += name_len; READ_ENCINT(section); READ_ENCINT(offset); READ_ENCINT(length); /* empty files and directory names are stored as a file entry at * offset 0 with length 0. We want to keep empty files, but not * directory names, which end with a "/" */ if ((offset == 0) && (length == 0)) { if ((name_len > 0) && (name[name_len-1] == '/')) continue; } if (section > 1) { sys->message(fh, "invalid section number '%u'.", section); continue; } if (!(fi = (struct mschmd_file *) sys->alloc(sys, sizeof(struct mschmd_file) + name_len + 1))) { sys->free(chunk); return MSPACK_ERR_NOMEMORY; } fi->next = NULL; fi->filename = (char *) &fi[1]; fi->section = ((section == 0) ? (struct mschmd_section *) (&chm->sec0) : (struct mschmd_section *) (&chm->sec1)); fi->offset = offset; fi->length = length; sys->copy(name, fi->filename, (size_t) name_len); fi->filename[name_len] = '\0'; if (name[0] == ':' && name[1] == ':') { /* system file */ if (mspack_memcmp(&name[2], &content_name[2], 31L) == 0) { if (mspack_memcmp(&name[33], &content_name[33], 8L) == 0) { chm->sec1.content = fi; } else if (mspack_memcmp(&name[33], &control_name[33], 11L) == 0) { chm->sec1.control = fi; } else if (mspack_memcmp(&name[33], &spaninfo_name[33], 8L) == 0) { chm->sec1.spaninfo = fi; } else if (mspack_memcmp(&name[33], &rtable_name[33], 72L) == 0) { chm->sec1.rtable = fi; } } fi->next = chm->sysfiles; chm->sysfiles = fi; } else { /* normal file */ if (link) link->next = fi; else chm->files = fi; link = fi; } } /* this is reached either when num_entries runs out, or if * reading data from the chunk reached a premature end of chunk */ chunk_end: if (num_entries >= 0) { D(("chunk ended before all entries could be read")) errors++; } } sys->free(chunk); return (errors > 0) ? MSPACK_ERR_DATAFORMAT : MSPACK_ERR_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-193', 'CWE-682'], 'message': 'Fix off-by-one bounds check on CHM PMGI/PMGL chunk numbers and reject empty filenames. Thanks to Hanno Böck for reporting'</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: char *pointer(const char *fmt, char *buf, char *end, void *ptr, struct printf_spec spec) { const int default_width = 2 * sizeof(void *); if (!ptr && *fmt != 'K') { /* * Print (null) with the same width as a pointer so it makes * tabular output look nice. */ if (spec.field_width == -1) spec.field_width = default_width; return string(buf, end, "(null)", spec); } switch (*fmt) { case 'F': case 'f': ptr = dereference_function_descriptor(ptr); /* Fallthrough */ case 'S': case 's': case 'B': return symbol_string(buf, end, ptr, spec, fmt); case 'R': case 'r': return resource_string(buf, end, ptr, spec, fmt); case 'h': return hex_string(buf, end, ptr, spec, fmt); case 'b': switch (fmt[1]) { case 'l': return bitmap_list_string(buf, end, ptr, spec, fmt); default: return bitmap_string(buf, end, ptr, spec, fmt); } case 'M': /* Colon separated: 00:01:02:03:04:05 */ case 'm': /* Contiguous: 000102030405 */ /* [mM]F (FDDI) */ /* [mM]R (Reverse order; Bluetooth) */ return mac_address_string(buf, end, ptr, spec, fmt); case 'I': /* Formatted IP supported * 4: 1.2.3.4 * 6: 0001:0203:...:0708 * 6c: 1::708 or 1::1.2.3.4 */ case 'i': /* Contiguous: * 4: 001.002.003.004 * 6: 000102...0f */ switch (fmt[1]) { case '6': return ip6_addr_string(buf, end, ptr, spec, fmt); case '4': return ip4_addr_string(buf, end, ptr, spec, fmt); case 'S': { const union { struct sockaddr raw; struct sockaddr_in v4; struct sockaddr_in6 v6; } *sa = ptr; switch (sa->raw.sa_family) { case AF_INET: return ip4_addr_string_sa(buf, end, &sa->v4, spec, fmt); case AF_INET6: return ip6_addr_string_sa(buf, end, &sa->v6, spec, fmt); default: return string(buf, end, "(invalid address)", spec); }} } break; case 'E': return escaped_string(buf, end, ptr, spec, fmt); case 'U': return uuid_string(buf, end, ptr, spec, fmt); case 'V': { va_list va; va_copy(va, *((struct va_format *)ptr)->va); buf += vsnprintf(buf, end > buf ? end - buf : 0, ((struct va_format *)ptr)->fmt, va); va_end(va); return buf; } case 'K': return restricted_pointer(buf, end, ptr, spec); case 'N': return netdev_bits(buf, end, ptr, fmt); case 'a': return address_val(buf, end, ptr, fmt); case 'd': return dentry_name(buf, end, ptr, spec, fmt); case 'C': return clock(buf, end, ptr, spec, fmt); case 'D': return dentry_name(buf, end, ((const struct file *)ptr)->f_path.dentry, spec, fmt); #ifdef CONFIG_BLOCK case 'g': return bdev_name(buf, end, ptr, spec, fmt); #endif case 'G': return flags_string(buf, end, ptr, fmt); case 'O': switch (fmt[1]) { case 'F': return device_node_string(buf, end, ptr, spec, fmt + 1); } } spec.flags |= SMALL; if (spec.field_width == -1) { spec.field_width = default_width; spec.flags |= ZEROPAD; } spec.base = 16; return number(buf, end, (unsigned long) ptr, spec); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'printk: hash addresses printed with %p Currently there exist approximately 14 000 places in the kernel where addresses are being printed using an unadorned %p. This potentially leaks sensitive information regarding the Kernel layout in memory. Many of these calls are stale, instead of fixing every call lets hash the address by default before printing. This will of course break some users, forcing code printing needed addresses to be updated. Code that _really_ needs the address will soon be able to use the new printk specifier %px to print the address. For what it's worth, usage of unadorned %p can be broken down as follows (thanks to Joe Perches). $ git grep -E '%p[^A-Za-z0-9]' | cut -f1 -d"/" | sort | uniq -c 1084 arch 20 block 10 crypto 32 Documentation 8121 drivers 1221 fs 143 include 101 kernel 69 lib 100 mm 1510 net 40 samples 7 scripts 11 security 166 sound 152 tools 2 virt Add function ptr_to_id() to map an address to a 32 bit unique identifier. Hash any unadorned usage of specifier %p and any malformed specifiers. Signed-off-by: Tobin C. Harding <me@tobin.cc>'</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: ExprResolveBoolean(struct xkb_context *ctx, const ExprDef *expr, bool *set_rtrn) { bool ok = false; const char *ident; switch (expr->expr.op) { case EXPR_VALUE: if (expr->expr.value_type != EXPR_TYPE_BOOLEAN) { log_err(ctx, "Found constant of type %s where boolean was expected\n", expr_value_type_to_string(expr->expr.value_type)); return false; } *set_rtrn = expr->boolean.set; return true; case EXPR_IDENT: ident = xkb_atom_text(ctx, expr->ident.ident); if (ident) { if (istreq(ident, "true") || istreq(ident, "yes") || istreq(ident, "on")) { *set_rtrn = true; return true; } else if (istreq(ident, "false") || istreq(ident, "no") || istreq(ident, "off")) { *set_rtrn = false; return true; } } log_err(ctx, "Identifier \"%s\" of type boolean is unknown\n", ident); return false; case EXPR_FIELD_REF: log_err(ctx, "Default \"%s.%s\" of type boolean is unknown\n", xkb_atom_text(ctx, expr->field_ref.element), xkb_atom_text(ctx, expr->field_ref.field)); return false; case EXPR_INVERT: case EXPR_NOT: ok = ExprResolveBoolean(ctx, expr, set_rtrn); if (ok) *set_rtrn = !*set_rtrn; return ok; case EXPR_ADD: case EXPR_SUBTRACT: case EXPR_MULTIPLY: case EXPR_DIVIDE: case EXPR_ASSIGN: case EXPR_NEGATE: case EXPR_UNARY_PLUS: log_err(ctx, "%s of boolean values not permitted\n", expr_op_type_to_string(expr->expr.op)); break; default: log_wsgo(ctx, "Unknown operator %d in ResolveBoolean\n", expr->expr.op); break; } return false; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'xkbcomp: fix stack overflow when evaluating boolean negation The expression evaluator would go into an infinite recursion when evaluating something like this as a boolean: `!True`. Instead of recursing to just `True` and negating, it recursed to `!True` itself again. Bug inherited from xkbcomp. Caught with the afl fuzzer. Signed-off-by: Ran Benita <ran234@gmail.com>'</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 ssize_t yurex_read(struct file *file, char __user *buffer, size_t count, loff_t *ppos) { struct usb_yurex *dev; int retval = 0; int bytes_read = 0; char in_buffer[20]; unsigned long flags; dev = file->private_data; mutex_lock(&dev->io_mutex); if (!dev->interface) { /* already disconnected */ retval = -ENODEV; goto exit; } spin_lock_irqsave(&dev->lock, flags); bytes_read = snprintf(in_buffer, 20, "%lld\n", dev->bbu); spin_unlock_irqrestore(&dev->lock, flags); if (*ppos < bytes_read) { if (copy_to_user(buffer, in_buffer + *ppos, bytes_read - *ppos)) retval = -EFAULT; else { retval = bytes_read - *ppos; *ppos += bytes_read; } } exit: mutex_unlock(&dev->io_mutex); return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-200'], 'message': 'USB: yurex: fix out-of-bounds uaccess in read handler In general, accessing userspace memory beyond the length of the supplied buffer in VFS read/write handlers can lead to both kernel memory corruption (via kernel_read()/kernel_write(), which can e.g. be triggered via sys_splice()) and privilege escalation inside userspace. Fix it by using simple_read_from_buffer() instead of custom logic. Fixes: 6bc235a2e24a ("USB: add driver for Meywa-Denki & Kayac YUREX") Signed-off-by: Jann Horn <jannh@google.com> Cc: stable <stable@vger.kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>'</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: __zzip_parse_root_directory(int fd, struct _disk_trailer *trailer, struct zzip_dir_hdr **hdr_return, zzip_plugin_io_t io, zzip_off_t filesize) { auto struct zzip_disk_entry dirent; struct zzip_dir_hdr *hdr; struct zzip_dir_hdr *hdr0; uint16_t *p_reclen = 0; zzip_off64_t entries; zzip_off64_t zz_offset; /* offset from start of root directory */ char *fd_map = 0; zzip_off64_t zz_fd_gap = 0; zzip_off64_t zz_entries = _disk_trailer_localentries(trailer); zzip_off64_t zz_rootsize = _disk_trailer_rootsize(trailer); zzip_off64_t zz_rootseek = _disk_trailer_rootseek(trailer); __correct_rootseek(zz_rootseek, zz_rootsize, trailer); if (zz_entries <= 0 || zz_rootsize < 0 || zz_rootseek < 0 || zz_rootseek >= filesize) return ZZIP_CORRUPTED; hdr0 = (struct zzip_dir_hdr *) malloc(zz_rootsize); if (! hdr0) return ZZIP_DIRSIZE; hdr = hdr0; __debug_dir_hdr(hdr); if (USE_MMAP && io->fd.sys) { zz_fd_gap = zz_rootseek & (_zzip_getpagesize(io->fd.sys) - 1); HINT4(" fd_gap=%ld, mapseek=0x%lx, maplen=%ld", (long) (zz_fd_gap), (long) (zz_rootseek - zz_fd_gap), (long) (zz_rootsize + zz_fd_gap)); fd_map = _zzip_mmap(io->fd.sys, fd, zz_rootseek - zz_fd_gap, zz_rootsize + zz_fd_gap); /* if mmap failed we will fallback to seek/read mode */ if (fd_map == MAP_FAILED) { NOTE2("map failed: %s", strerror(errno)); fd_map = 0; } else { HINT3("mapped *%p len=%li", fd_map, (long) (zz_rootsize + zz_fd_gap)); } } for (entries=0, zz_offset=0; ; entries++) { register struct zzip_disk_entry *d; uint16_t u_extras, u_comment, u_namlen; # ifndef ZZIP_ALLOW_MODULO_ENTRIES if (entries >= zz_entries) { if (zz_offset + 256 < zz_rootsize) { FAIL4("%li's entry is long before the end of directory - enable modulo_entries? (O:%li R:%li)", (long) entries, (long) (zz_offset), (long) zz_rootsize); } break; } # endif if (fd_map) { d = (void*)(fd_map+zz_fd_gap+zz_offset); /* fd_map+fd_gap==u_rootseek */ } else { if (io->fd.seeks(fd, zz_rootseek + zz_offset, SEEK_SET) < 0) return ZZIP_DIR_SEEK; if (io->fd.read(fd, &dirent, sizeof(dirent)) < __sizeof(dirent)) return ZZIP_DIR_READ; d = &dirent; } if ((zzip_off64_t) (zz_offset + sizeof(*d)) > zz_rootsize || (zzip_off64_t) (zz_offset + sizeof(*d)) < 0) { FAIL4("%li's entry stretches beyond root directory (O:%li R:%li)", (long) entries, (long) (zz_offset), (long) zz_rootsize); break; } if (! zzip_disk_entry_check_magic(d)) { # ifndef ZZIP_ALLOW_MODULO_ENTRIES FAIL4("%li's entry has no disk_entry magic indicator (O:%li R:%li)", (long) entries, (long) (zz_offset), (long) zz_rootsize); # endif break; } # if 0 && defined DEBUG zzip_debug_xbuf((unsigned char *) d, sizeof(*d) + 8); # endif u_extras = zzip_disk_entry_get_extras(d); u_comment = zzip_disk_entry_get_comment(d); u_namlen = zzip_disk_entry_get_namlen(d); HINT5("offset=0x%lx, size %ld, dirent *%p, hdr %p\n", (long) (zz_offset + zz_rootseek), (long) zz_rootsize, d, hdr); /* writes over the read buffer, Since the structure where data is copied is smaller than the data in buffer this can be done. It is important that the order of setting the fields is considered when filling the structure, so that some data is not trashed in first structure read. at the end the whole copied list of structures is copied into newly allocated buffer */ hdr->d_crc32 = zzip_disk_entry_get_crc32(d); hdr->d_csize = zzip_disk_entry_get_csize(d); hdr->d_usize = zzip_disk_entry_get_usize(d); hdr->d_off = zzip_disk_entry_get_offset(d); hdr->d_compr = zzip_disk_entry_get_compr(d); if (hdr->d_compr > _255) hdr->d_compr = 255; if ((zzip_off64_t) (zz_offset + sizeof(*d) + u_namlen) > zz_rootsize || (zzip_off64_t) (zz_offset + sizeof(*d) + u_namlen) < 0) { FAIL4("%li's name stretches beyond root directory (O:%li N:%li)", (long) entries, (long) (zz_offset), (long) (u_namlen)); break; } if (fd_map) { memcpy(hdr->d_name, fd_map+zz_fd_gap + zz_offset+sizeof(*d), u_namlen); } else { io->fd.read(fd, hdr->d_name, u_namlen); } hdr->d_name[u_namlen] = '\0'; hdr->d_namlen = u_namlen; /* update offset by the total length of this entry -> next entry */ zz_offset += sizeof(*d) + u_namlen + u_extras + u_comment; if (zz_offset > zz_rootsize) { FAIL3("%li's entry stretches beyond root directory (O:%li)", (long) entries, (long) (zz_offset)); entries ++; break; } HINT5("file %ld { compr=%d crc32=$%x offset=%d", (long) entries, hdr->d_compr, hdr->d_crc32, hdr->d_off); HINT5("csize=%d usize=%d namlen=%d extras=%d", hdr->d_csize, hdr->d_usize, u_namlen, u_extras); HINT5("comment=%d name='%s' %s <sizeof %d> } ", u_comment, hdr->d_name, "", (int) sizeof(*d)); p_reclen = &hdr->d_reclen; { register char *p = (char *) hdr; register char *q = aligned4(p + sizeof(*hdr) + u_namlen + 1); *p_reclen = (uint16_t) (q - p); hdr = (struct zzip_dir_hdr *) q; } } /*for */ if (USE_MMAP && fd_map) { HINT3("unmap *%p len=%li", fd_map, (long) (zz_rootsize + zz_fd_gap)); _zzip_munmap(io->fd.sys, fd_map, zz_rootsize + zz_fd_gap); } if (p_reclen) { *p_reclen = 0; /* mark end of list */ if (hdr_return) *hdr_return = hdr0; } /* else zero (sane) entries */ # ifndef ZZIP_ALLOW_MODULO_ENTRIES return (entries != zz_entries ? ZZIP_CORRUPTED : 0); # else return ((entries & (unsigned)0xFFFF) != zz_entries ? ZZIP_CORRUPTED : 0); # endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-772'], 'message': 'Avoid memory leak from __zzip_parse_root_directory().'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Image *ReadPICTImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define ThrowPICTException(exception,message) \ { \ if (tile_image != (Image *) NULL) \ tile_image=DestroyImage(tile_image); \ if (read_info != (ImageInfo *) NULL) \ read_info=DestroyImageInfo(read_info); \ ThrowReaderException((exception),(message)); \ } char geometry[MaxTextExtent], header_ole[4]; Image *image, *tile_image; ImageInfo *read_info; IndexPacket index; int c, code; MagickBooleanType jpeg, status; PICTRectangle frame; PICTPixmap pixmap; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; size_t extent, length; ssize_t count, flags, j, version, y; StringInfo *profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read PICT header. */ read_info=(ImageInfo *) NULL; tile_image=(Image *) NULL; pixmap.bits_per_pixel=0; pixmap.component_count=0; /* Skip header : 512 for standard PICT and 4, ie "PICT" for OLE2 */ header_ole[0]=ReadBlobByte(image); header_ole[1]=ReadBlobByte(image); header_ole[2]=ReadBlobByte(image); header_ole[3]=ReadBlobByte(image); if (!((header_ole[0] == 0x50) && (header_ole[1] == 0x49) && (header_ole[2] == 0x43) && (header_ole[3] == 0x54))) for (i=0; i < 508; i++) if (ReadBlobByte(image) == EOF) break; (void) ReadBlobMSBShort(image); /* skip picture size */ if (ReadRectangle(image,&frame) == MagickFalse) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); while ((c=ReadBlobByte(image)) == 0) ; if (c != 0x11) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); version=(ssize_t) ReadBlobByte(image); if (version == 2) { c=ReadBlobByte(image); if (c != 0xff) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); } else if (version != 1) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); if ((frame.left < 0) || (frame.right < 0) || (frame.top < 0) || (frame.bottom < 0) || (frame.left >= frame.right) || (frame.top >= frame.bottom)) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); /* Create black canvas. */ flags=0; image->depth=8; image->columns=(unsigned int) (frame.right-frame.left); image->rows=(unsigned int) (frame.bottom-frame.top); image->x_resolution=DefaultResolution; image->y_resolution=DefaultResolution; image->units=UndefinedResolution; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status != MagickFalse) status=ResetImagePixels(image,exception); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Interpret PICT opcodes. */ jpeg=MagickFalse; for (code=0; EOFBlob(image) == MagickFalse; ) { if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((version == 1) || ((TellBlob(image) % 2) != 0)) code=ReadBlobByte(image); if (version == 2) code=ReadBlobMSBSignedShort(image); if (code < 0) break; if (code == 0) continue; if (code > 0xa1) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"%04X:",code); } else { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %04X %s: %s",code,codes[code].name,codes[code].description); switch (code) { case 0x01: { /* Clipping rectangle. */ length=ReadBlobMSBShort(image); if (length != 0x000a) { for (i=0; i < (ssize_t) (length-2); i++) if (ReadBlobByte(image) == EOF) break; break; } if (ReadRectangle(image,&frame) == MagickFalse) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); if (((frame.left & 0x8000) != 0) || ((frame.top & 0x8000) != 0)) break; image->columns=(size_t) (frame.right-frame.left); image->rows=(size_t) (frame.bottom-frame.top); status=SetImageExtent(image,image->columns,image->rows); if (status != MagickFalse) status=ResetImagePixels(image,&image->exception); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } break; } case 0x12: case 0x13: case 0x14: { ssize_t pattern; size_t height, width; /* Skip pattern definition. */ pattern=(ssize_t) ReadBlobMSBShort(image); for (i=0; i < 8; i++) if (ReadBlobByte(image) == EOF) break; if (pattern == 2) { for (i=0; i < 5; i++) if (ReadBlobByte(image) == EOF) break; break; } if (pattern != 1) ThrowPICTException(CorruptImageError,"UnknownPatternType"); length=ReadBlobMSBShort(image); if (ReadRectangle(image,&frame) == MagickFalse) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); if (ReadPixmap(image,&pixmap) == MagickFalse) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); image->depth=(size_t) pixmap.component_size; image->x_resolution=1.0*pixmap.horizontal_resolution; image->y_resolution=1.0*pixmap.vertical_resolution; image->units=PixelsPerInchResolution; (void) ReadBlobMSBLong(image); flags=(ssize_t) ReadBlobMSBShort(image); length=ReadBlobMSBShort(image); for (i=0; i <= (ssize_t) length; i++) (void) ReadBlobMSBLong(image); width=(size_t) (frame.bottom-frame.top); height=(size_t) (frame.right-frame.left); if (pixmap.bits_per_pixel <= 8) length&=0x7fff; if (pixmap.bits_per_pixel == 16) width<<=1; if (length == 0) length=width; if (length < 8) { for (i=0; i < (ssize_t) (length*height); i++) if (ReadBlobByte(image) == EOF) break; } else for (i=0; i < (ssize_t) height; i++) { if (EOFBlob(image) != MagickFalse) break; if (length > 200) { for (j=0; j < (ssize_t) ReadBlobMSBShort(image); j++) if (ReadBlobByte(image) == EOF) break; } else for (j=0; j < (ssize_t) ReadBlobByte(image); j++) if (ReadBlobByte(image) == EOF) break; } break; } case 0x1b: { /* Initialize image background color. */ image->background_color.red=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); image->background_color.green=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); image->background_color.blue=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); break; } case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: { /* Skip polygon or region. */ length=ReadBlobMSBShort(image); for (i=0; i < (ssize_t) (length-2); i++) if (ReadBlobByte(image) == EOF) break; break; } case 0x90: case 0x91: case 0x98: case 0x99: case 0x9a: case 0x9b: { ssize_t bytes_per_line; PICTRectangle source, destination; register unsigned char *p; size_t j; unsigned char *pixels; /* Pixmap clipped by a rectangle. */ bytes_per_line=0; if ((code != 0x9a) && (code != 0x9b)) bytes_per_line=(ssize_t) ReadBlobMSBShort(image); else { (void) ReadBlobMSBShort(image); (void) ReadBlobMSBShort(image); (void) ReadBlobMSBShort(image); } if (ReadRectangle(image,&frame) == MagickFalse) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); /* Initialize tile image. */ tile_image=CloneImage(image,(size_t) (frame.right-frame.left), (size_t) (frame.bottom-frame.top),MagickTrue,exception); if (tile_image == (Image *) NULL) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); if ((code == 0x9a) || (code == 0x9b) || ((bytes_per_line & 0x8000) != 0)) { if (ReadPixmap(image,&pixmap) == MagickFalse) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); tile_image->depth=(size_t) pixmap.component_size; tile_image->matte=pixmap.component_count == 4 ? MagickTrue : MagickFalse; tile_image->x_resolution=(double) pixmap.horizontal_resolution; tile_image->y_resolution=(double) pixmap.vertical_resolution; tile_image->units=PixelsPerInchResolution; if (tile_image->matte != MagickFalse) (void) SetImageAlphaChannel(tile_image,OpaqueAlphaChannel); } if ((code != 0x9a) && (code != 0x9b)) { /* Initialize colormap. */ tile_image->colors=2; if ((bytes_per_line & 0x8000) != 0) { (void) ReadBlobMSBLong(image); flags=(ssize_t) ReadBlobMSBShort(image); tile_image->colors=1UL*ReadBlobMSBShort(image)+1; } status=AcquireImageColormap(tile_image,tile_image->colors); if (status == MagickFalse) ThrowPICTException(ResourceLimitError, "MemoryAllocationFailed"); if ((bytes_per_line & 0x8000) != 0) { for (i=0; i < (ssize_t) tile_image->colors; i++) { j=ReadBlobMSBShort(image) % tile_image->colors; if ((flags & 0x8000) != 0) j=(size_t) i; tile_image->colormap[j].red=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); tile_image->colormap[j].green=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); tile_image->colormap[j].blue=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); } } else { for (i=0; i < (ssize_t) tile_image->colors; i++) { tile_image->colormap[i].red=(Quantum) (QuantumRange- tile_image->colormap[i].red); tile_image->colormap[i].green=(Quantum) (QuantumRange- tile_image->colormap[i].green); tile_image->colormap[i].blue=(Quantum) (QuantumRange- tile_image->colormap[i].blue); } } } if (EOFBlob(image) != MagickFalse) ThrowPICTException(CorruptImageError, "InsufficientImageDataInFile"); if (ReadRectangle(image,&source) == MagickFalse) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); if (ReadRectangle(image,&destination) == MagickFalse) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlobMSBShort(image); if ((code == 0x91) || (code == 0x99) || (code == 0x9b)) { /* Skip region. */ length=ReadBlobMSBShort(image); for (i=0; i < (ssize_t) (length-2); i++) if (ReadBlobByte(image) == EOF) break; } if ((code != 0x9a) && (code != 0x9b) && (bytes_per_line & 0x8000) == 0) pixels=DecodeImage(image,tile_image,(size_t) bytes_per_line,1, &extent); else pixels=DecodeImage(image,tile_image,(unsigned int) bytes_per_line, (unsigned int) pixmap.bits_per_pixel,&extent); if (pixels == (unsigned char *) NULL) ThrowPICTException(CorruptImageError,"UnableToUncompressImage"); /* Convert PICT tile image to pixel packets. */ p=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { if (p > (pixels+extent+image->columns)) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowPICTException(CorruptImageError,"NotEnoughPixelData"); } q=QueueAuthenticPixels(tile_image,0,y,tile_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(tile_image); for (x=0; x < (ssize_t) tile_image->columns; x++) { if (tile_image->storage_class == PseudoClass) { index=ConstrainColormapIndex(tile_image,*p); SetPixelIndex(indexes+x,index); SetPixelRed(q, tile_image->colormap[(ssize_t) index].red); SetPixelGreen(q, tile_image->colormap[(ssize_t) index].green); SetPixelBlue(q, tile_image->colormap[(ssize_t) index].blue); } else { if (pixmap.bits_per_pixel == 16) { i=(ssize_t) (*p++); j=(*p); SetPixelRed(q,ScaleCharToQuantum( (unsigned char) ((i & 0x7c) << 1))); SetPixelGreen(q,ScaleCharToQuantum( (unsigned char) (((i & 0x03) << 6) | ((j & 0xe0) >> 2)))); SetPixelBlue(q,ScaleCharToQuantum( (unsigned char) ((j & 0x1f) << 3))); } else if (tile_image->matte == MagickFalse) { if (p > (pixels+extent+2*image->columns)) ThrowPICTException(CorruptImageError, "NotEnoughPixelData"); SetPixelRed(q,ScaleCharToQuantum(*p)); SetPixelGreen(q,ScaleCharToQuantum( *(p+tile_image->columns))); SetPixelBlue(q,ScaleCharToQuantum( *(p+2*tile_image->columns))); } else { if (p > (pixels+extent+3*image->columns)) ThrowPICTException(CorruptImageError, "NotEnoughPixelData"); SetPixelAlpha(q,ScaleCharToQuantum(*p)); SetPixelRed(q,ScaleCharToQuantum( *(p+tile_image->columns))); SetPixelGreen(q,ScaleCharToQuantum( *(p+2*tile_image->columns))); SetPixelBlue(q,ScaleCharToQuantum( *(p+3*tile_image->columns))); } } p++; q++; } if (SyncAuthenticPixels(tile_image,exception) == MagickFalse) break; if ((tile_image->storage_class == DirectClass) && (pixmap.bits_per_pixel != 16)) { p+=(pixmap.component_count-1)*tile_image->columns; if (p < pixels) break; } status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, tile_image->rows); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if ((jpeg == MagickFalse) && (EOFBlob(image) == MagickFalse)) if ((code == 0x9a) || (code == 0x9b) || ((bytes_per_line & 0x8000) != 0)) (void) CompositeImage(image,CopyCompositeOp,tile_image, (ssize_t) destination.left,(ssize_t) destination.top); tile_image=DestroyImage(tile_image); break; } case 0xa1: { unsigned char *info; size_t type; /* Comment. */ type=ReadBlobMSBShort(image); length=ReadBlobMSBShort(image); if (length == 0) break; (void) ReadBlobMSBLong(image); length-=MagickMin(length,4); if (length == 0) break; info=(unsigned char *) AcquireQuantumMemory(length,sizeof(*info)); if (info == (unsigned char *) NULL) break; count=ReadBlob(image,length,info); if (count != (ssize_t) length) { info=(unsigned char *) RelinquishMagickMemory(info); ThrowPICTException(ResourceLimitError,"UnableToReadImageData"); } switch (type) { case 0xe0: { profile=BlobToStringInfo((const void *) NULL,length); SetStringInfoDatum(profile,info); status=SetImageProfile(image,"icc",profile); profile=DestroyStringInfo(profile); if (status == MagickFalse) { info=(unsigned char *) RelinquishMagickMemory(info); ThrowPICTException(ResourceLimitError, "MemoryAllocationFailed"); } break; } case 0x1f2: { profile=BlobToStringInfo((const void *) NULL,length); SetStringInfoDatum(profile,info); status=SetImageProfile(image,"iptc",profile); if (status == MagickFalse) { info=(unsigned char *) RelinquishMagickMemory(info); ThrowPICTException(ResourceLimitError, "MemoryAllocationFailed"); } profile=DestroyStringInfo(profile); break; } default: break; } info=(unsigned char *) RelinquishMagickMemory(info); break; } default: { /* Skip to next op code. */ if (codes[code].length == -1) (void) ReadBlobMSBShort(image); else for (i=0; i < (ssize_t) codes[code].length; i++) if (ReadBlobByte(image) == EOF) break; } } } if (code == 0xc00) { /* Skip header. */ for (i=0; i < 24; i++) if (ReadBlobByte(image) == EOF) break; continue; } if (((code >= 0xb0) && (code <= 0xcf)) || ((code >= 0x8000) && (code <= 0x80ff))) continue; if (code == 0x8200) { char filename[MaxTextExtent]; FILE *file; int unique_file; /* Embedded JPEG. */ jpeg=MagickTrue; read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); (void) FormatLocaleString(read_info->filename,MaxTextExtent,"jpeg:%s", filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) { (void) RelinquishUniqueFileResource(read_info->filename); (void) CopyMagickString(image->filename,read_info->filename, MaxTextExtent); ThrowPICTException(FileOpenError,"UnableToCreateTemporaryFile"); } length=ReadBlobMSBLong(image); if (length > 154) { for (i=0; i < 6; i++) (void) ReadBlobMSBLong(image); if (ReadRectangle(image,&frame) == MagickFalse) { (void) fclose(file); (void) RelinquishUniqueFileResource(read_info->filename); ThrowPICTException(CorruptImageError,"ImproperImageHeader"); } for (i=0; i < 122; i++) if (ReadBlobByte(image) == EOF) break; for (i=0; i < (ssize_t) (length-154); i++) { c=ReadBlobByte(image); if (c == EOF) break; (void) fputc(c,file); } } (void) fclose(file); (void) close(unique_file); tile_image=ReadImage(read_info,exception); (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); if (tile_image == (Image *) NULL) continue; (void) FormatLocaleString(geometry,MaxTextExtent,"%.20gx%.20g", (double) MagickMax(image->columns,tile_image->columns), (double) MagickMax(image->rows,tile_image->rows)); (void) SetImageExtent(image, MagickMax(image->columns,tile_image->columns), MagickMax(image->rows,tile_image->rows)); (void) TransformImageColorspace(image,tile_image->colorspace); (void) CompositeImage(image,CopyCompositeOp,tile_image,(ssize_t) frame.left,(ssize_t) frame.right); image->compression=tile_image->compression; tile_image=DestroyImage(tile_image); continue; } if ((code == 0xff) || (code == 0xffff)) break; if (((code >= 0xd0) && (code <= 0xfe)) || ((code >= 0x8100) && (code <= 0xffff))) { /* Skip reserved. */ length=ReadBlobMSBShort(image); for (i=0; i < (ssize_t) length; i++) if (ReadBlobByte(image) == EOF) break; continue; } if ((code >= 0x100) && (code <= 0x7fff)) { /* Skip reserved. */ length=(size_t) ((code >> 7) & 0xff); for (i=0; i < (ssize_t) length; i++) if (ReadBlobByte(image) == EOF) break; continue; } } (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-252'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1199'</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 formatIPTCfromBuffer(Image *ofile, char *s, ssize_t len) { char temp[MaxTextExtent]; unsigned int foundiptc, tagsfound; unsigned char recnum, dataset; unsigned char *readable, *str; ssize_t tagindx, taglen; int i, tagcount = (int) (sizeof(tags) / sizeof(tag_spec)); int c; foundiptc = 0; /* found the IPTC-Header */ tagsfound = 0; /* number of tags found */ while (len > 0) { c = *s++; len--; if (c == 0x1c) foundiptc = 1; else { if (foundiptc) return -1; else continue; } /* We found the 0x1c tag and now grab the dataset and record number tags. */ c = *s++; len--; if (len < 0) return -1; dataset = (unsigned char) c; c = *s++; len--; if (len < 0) return -1; recnum = (unsigned char) c; /* try to match this record to one of the ones in our named table */ for (i=0; i< tagcount; i++) if (tags[i].id == (short) recnum) break; if (i < tagcount) readable=(unsigned char *) tags[i].name; else readable=(unsigned char *) ""; /* We decode the length of the block that follows - ssize_t or short fmt. */ c=(*s++); len--; if (len < 0) return(-1); if (c & (unsigned char) 0x80) return(0); else { s--; len++; taglen=readWordFromBuffer(&s, &len); } if (taglen < 0) return(-1); if (taglen > 65535) return(-1); /* make a buffer to hold the tag datand snag it from the input stream */ str=(unsigned char *) AcquireQuantumMemory((size_t) (taglen+MaxTextExtent), sizeof(*str)); if (str == (unsigned char *) NULL) return 0; for (tagindx=0; tagindx<taglen; tagindx++) { c = *s++; len--; if (len < 0) return(-1); str[tagindx]=(unsigned char) c; } str[taglen]=0; /* now finish up by formatting this binary data into ASCII equivalent */ if (strlen((char *)readable) > 0) (void) FormatLocaleString(temp,MaxTextExtent,"%d#%d#%s=", (unsigned int) dataset,(unsigned int) recnum, readable); else (void) FormatLocaleString(temp,MaxTextExtent,"%d#%d=", (unsigned int) dataset,(unsigned int) recnum); (void) WriteBlobString(ofile,temp); formatString( ofile, (char *)str, taglen ); str=(unsigned char *) RelinquishMagickMemory(str); tagsfound++; } return ((int) tagsfound); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1118'</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 gemsafe_get_cert_len(sc_card_t *card) { int r; u8 ibuf[GEMSAFE_MAX_OBJLEN]; u8 *iptr; struct sc_path path; struct sc_file *file; size_t objlen, certlen; unsigned int ind, i=0; sc_format_path(GEMSAFE_PATH, &path); r = sc_select_file(card, &path, &file); if (r != SC_SUCCESS || !file) return SC_ERROR_INTERNAL; /* Initial read */ r = sc_read_binary(card, 0, ibuf, GEMSAFE_READ_QUANTUM, 0); if (r < 0) return SC_ERROR_INTERNAL; /* Actual stored object size is encoded in first 2 bytes * (allocated EF space is much greater!) */ objlen = (((size_t) ibuf[0]) << 8) | ibuf[1]; sc_log(card->ctx, "Stored object is of size: %"SC_FORMAT_LEN_SIZE_T"u", objlen); if (objlen < 1 || objlen > GEMSAFE_MAX_OBJLEN) { sc_log(card->ctx, "Invalid object size: %"SC_FORMAT_LEN_SIZE_T"u", objlen); return SC_ERROR_INTERNAL; } /* It looks like the first thing in the block is a table of * which keys are allocated. The table is small and is in the * first 248 bytes. Example for a card with 10 key containers: * 01 f0 00 03 03 b0 00 03 <= 1st key unallocated * 01 f0 00 04 03 b0 00 04 <= 2nd key unallocated * 01 fe 14 00 05 03 b0 00 05 <= 3rd key allocated * 01 fe 14 01 06 03 b0 00 06 <= 4th key allocated * 01 f0 00 07 03 b0 00 07 <= 5th key unallocated * ... * 01 f0 00 0c 03 b0 00 0c <= 10th key unallocated * For allocated keys, the fourth byte seems to indicate the * default key and the fifth byte indicates the key_ref of * the private key. */ ind = 2; /* skip length */ while (ibuf[ind] == 0x01) { if (ibuf[ind+1] == 0xFE) { gemsafe_prkeys[i].ref = ibuf[ind+4]; sc_log(card->ctx, "Key container %d is allocated and uses key_ref %d", i+1, gemsafe_prkeys[i].ref); ind += 9; } else { gemsafe_prkeys[i].label = NULL; gemsafe_cert[i].label = NULL; sc_log(card->ctx, "Key container %d is unallocated", i+1); ind += 8; } i++; } /* Delete additional key containers from the data structures if * this card can't accommodate them. */ for (; i < gemsafe_cert_max; i++) { gemsafe_prkeys[i].label = NULL; gemsafe_cert[i].label = NULL; } /* Read entire file, then dissect in memory. * Gemalto ClassicClient seems to do it the same way. */ iptr = ibuf + GEMSAFE_READ_QUANTUM; while ((size_t)(iptr - ibuf) < objlen) { r = sc_read_binary(card, iptr - ibuf, iptr, MIN(GEMSAFE_READ_QUANTUM, objlen - (iptr - ibuf)), 0); if (r < 0) { sc_log(card->ctx, "Could not read cert object"); return SC_ERROR_INTERNAL; } iptr += GEMSAFE_READ_QUANTUM; } /* Search buffer for certificates, they start with 0x3082. */ i = 0; while (ind < objlen - 1) { if (ibuf[ind] == 0x30 && ibuf[ind+1] == 0x82) { /* Find next allocated key container */ while (i < gemsafe_cert_max && gemsafe_cert[i].label == NULL) i++; if (i == gemsafe_cert_max) { sc_log(card->ctx, "Warning: Found orphaned certificate at offset %d", ind); return SC_SUCCESS; } /* DER cert len is encoded this way */ if (ind+3 >= sizeof ibuf) return SC_ERROR_INVALID_DATA; certlen = ((((size_t) ibuf[ind+2]) << 8) | ibuf[ind+3]) + 4; sc_log(card->ctx, "Found certificate of key container %d at offset %d, len %"SC_FORMAT_LEN_SIZE_T"u", i+1, ind, certlen); gemsafe_cert[i].index = ind; gemsafe_cert[i].count = certlen; ind += certlen; i++; } else ind++; } /* Delete additional key containers from the data structures if * they're missing on the card. */ for (; i < gemsafe_cert_max; i++) { if (gemsafe_cert[i].label) { sc_log(card->ctx, "Warning: Certificate of key container %d is missing", i+1); gemsafe_prkeys[i].label = NULL; gemsafe_cert[i].label = NULL; } } return SC_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415', 'CWE-119'], 'message': 'fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems.'</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 read_file(struct sc_card *card, char *str_path, unsigned char **data, size_t *data_len) { struct sc_path path; struct sc_file *file; unsigned char *p; int ok = 0; int r; size_t len; sc_format_path(str_path, &path); if (SC_SUCCESS != sc_select_file(card, &path, &file)) { goto err; } len = file ? file->size : 4096; p = realloc(*data, len); if (!p) { goto err; } *data = p; *data_len = len; r = sc_read_binary(card, 0, p, len, 0); if (r < 0) goto err; *data_len = r; ok = 1; err: sc_file_free(file); return ok; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415', 'CWE-119'], 'message': 'fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems.'</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 show_opcodes(u8 *rip, const char *loglvl) { #define PROLOGUE_SIZE 42 #define EPILOGUE_SIZE 21 #define OPCODE_BUFSIZE (PROLOGUE_SIZE + 1 + EPILOGUE_SIZE) u8 opcodes[OPCODE_BUFSIZE]; if (probe_kernel_read(opcodes, rip - PROLOGUE_SIZE, OPCODE_BUFSIZE)) { printk("%sCode: Bad RIP value.\n", loglvl); } else { printk("%sCode: %" __stringify(PROLOGUE_SIZE) "ph <%02x> %" __stringify(EPILOGUE_SIZE) "ph\n", loglvl, opcodes, opcodes[PROLOGUE_SIZE], opcodes + PROLOGUE_SIZE + 1); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'x86/dumpstack: Don't dump kernel memory based on usermode RIP show_opcodes() is used both for dumping kernel instructions and for dumping user instructions. If userspace causes #PF by jumping to a kernel address, show_opcodes() can be reached with regs->ip controlled by the user, pointing to kernel code. Make sure that userspace can't trick us into dumping kernel memory into dmesg. Fixes: 7cccf0725cf7 ("x86/dumpstack: Add a show_ip() function") Signed-off-by: Jann Horn <jannh@google.com> Signed-off-by: Thomas Gleixner <tglx@linutronix.de> Reviewed-by: Kees Cook <keescook@chromium.org> Reviewed-by: Borislav Petkov <bp@suse.de> Cc: "H. Peter Anvin" <hpa@zytor.com> Cc: Andy Lutomirski <luto@kernel.org> Cc: security@kernel.org Cc: stable@vger.kernel.org Link: https://lkml.kernel.org/r/20180828154901.112726-1-jannh@google.com'</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 l2tp_eth_create(struct net *net, u32 tunnel_id, u32 session_id, u32 peer_session_id, struct l2tp_session_cfg *cfg) { unsigned char name_assign_type; struct net_device *dev; char name[IFNAMSIZ]; struct l2tp_tunnel *tunnel; struct l2tp_session *session; struct l2tp_eth *priv; struct l2tp_eth_sess *spriv; int rc; struct l2tp_eth_net *pn; tunnel = l2tp_tunnel_find(net, tunnel_id); if (!tunnel) { rc = -ENODEV; goto out; } if (cfg->ifname) { strlcpy(name, cfg->ifname, IFNAMSIZ); name_assign_type = NET_NAME_USER; } else { strcpy(name, L2TP_ETH_DEV_NAME); name_assign_type = NET_NAME_ENUM; } session = l2tp_session_create(sizeof(*spriv), tunnel, session_id, peer_session_id, cfg); if (IS_ERR(session)) { rc = PTR_ERR(session); goto out; } dev = alloc_netdev(sizeof(*priv), name, name_assign_type, l2tp_eth_dev_setup); if (!dev) { rc = -ENOMEM; goto out_del_session; } dev_net_set(dev, net); dev->min_mtu = 0; dev->max_mtu = ETH_MAX_MTU; l2tp_eth_adjust_mtu(tunnel, session, dev); priv = netdev_priv(dev); priv->dev = dev; priv->session = session; INIT_LIST_HEAD(&priv->list); priv->tunnel_sock = tunnel->sock; session->recv_skb = l2tp_eth_dev_recv; session->session_close = l2tp_eth_delete; #if IS_ENABLED(CONFIG_L2TP_DEBUGFS) session->show = l2tp_eth_show; #endif spriv = l2tp_session_priv(session); spriv->dev = dev; rc = register_netdev(dev); if (rc < 0) goto out_del_dev; __module_get(THIS_MODULE); /* Must be done after register_netdev() */ strlcpy(session->ifname, dev->name, IFNAMSIZ); dev_hold(dev); pn = l2tp_eth_pernet(dev_net(dev)); spin_lock(&pn->l2tp_eth_lock); list_add(&priv->list, &pn->l2tp_eth_dev_list); spin_unlock(&pn->l2tp_eth_lock); return 0; out_del_dev: free_netdev(dev); spriv->dev = NULL; out_del_session: l2tp_session_delete(session); out: return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'l2tp: pass tunnel pointer to ->session_create() Using l2tp_tunnel_find() in pppol2tp_session_create() and l2tp_eth_create() is racy, because no reference is held on the returned session. These functions are only used to implement the ->session_create callback which is run by l2tp_nl_cmd_session_create(). Therefore searching for the parent tunnel isn't necessary because l2tp_nl_cmd_session_create() already has a pointer to it and holds a reference. This patch modifies ->session_create()'s prototype to directly pass the the parent tunnel as parameter, thus avoiding searching for it in pppol2tp_session_create() and l2tp_eth_create(). Since we have to touch the ->session_create() call in l2tp_nl_cmd_session_create(), let's also remove the useless conditional: we know that ->session_create isn't NULL at this point because it's already been checked earlier in this same function. Finally, one might be tempted to think that the removed l2tp_tunnel_find() calls were harmless because they would return the same tunnel as the one held by l2tp_nl_cmd_session_create() anyway. But that tunnel might be removed and a new one created with same tunnel Id before the l2tp_tunnel_find() call. In this case l2tp_tunnel_find() would return the new tunnel which wouldn't be protected by the reference held by l2tp_nl_cmd_session_create(). Fixes: 309795f4bec2 ("l2tp: Add netlink control API for L2TP") Fixes: d9e31d17ceba ("l2tp: Add L2TP ethernet pseudowire support") Signed-off-by: Guillaume Nault <g.nault@alphalink.fr> Signed-off-by: David S. Miller <davem@davemloft.net>'</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 dump_mm(const struct mm_struct *mm) { pr_emerg("mm %px mmap %px seqnum %d task_size %lu\n" #ifdef CONFIG_MMU "get_unmapped_area %px\n" #endif "mmap_base %lu mmap_legacy_base %lu highest_vm_end %lu\n" "pgd %px mm_users %d mm_count %d pgtables_bytes %lu map_count %d\n" "hiwater_rss %lx hiwater_vm %lx total_vm %lx locked_vm %lx\n" "pinned_vm %lx data_vm %lx exec_vm %lx stack_vm %lx\n" "start_code %lx end_code %lx start_data %lx end_data %lx\n" "start_brk %lx brk %lx start_stack %lx\n" "arg_start %lx arg_end %lx env_start %lx env_end %lx\n" "binfmt %px flags %lx core_state %px\n" #ifdef CONFIG_AIO "ioctx_table %px\n" #endif #ifdef CONFIG_MEMCG "owner %px " #endif "exe_file %px\n" #ifdef CONFIG_MMU_NOTIFIER "mmu_notifier_mm %px\n" #endif #ifdef CONFIG_NUMA_BALANCING "numa_next_scan %lu numa_scan_offset %lu numa_scan_seq %d\n" #endif "tlb_flush_pending %d\n" "def_flags: %#lx(%pGv)\n", mm, mm->mmap, mm->vmacache_seqnum, mm->task_size, #ifdef CONFIG_MMU mm->get_unmapped_area, #endif mm->mmap_base, mm->mmap_legacy_base, mm->highest_vm_end, mm->pgd, atomic_read(&mm->mm_users), atomic_read(&mm->mm_count), mm_pgtables_bytes(mm), mm->map_count, mm->hiwater_rss, mm->hiwater_vm, mm->total_vm, mm->locked_vm, mm->pinned_vm, mm->data_vm, mm->exec_vm, mm->stack_vm, mm->start_code, mm->end_code, mm->start_data, mm->end_data, mm->start_brk, mm->brk, mm->start_stack, mm->arg_start, mm->arg_end, mm->env_start, mm->env_end, mm->binfmt, mm->flags, mm->core_state, #ifdef CONFIG_AIO mm->ioctx_table, #endif #ifdef CONFIG_MEMCG mm->owner, #endif mm->exe_file, #ifdef CONFIG_MMU_NOTIFIER mm->mmu_notifier_mm, #endif #ifdef CONFIG_NUMA_BALANCING mm->numa_next_scan, mm->numa_scan_offset, mm->numa_scan_seq, #endif atomic_read(&mm->tlb_flush_pending), mm->def_flags, &mm->def_flags ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'mm: get rid of vmacache_flush_all() entirely Jann Horn points out that the vmacache_flush_all() function is not only potentially expensive, it's buggy too. It also happens to be entirely unnecessary, because the sequence number overflow case can be avoided by simply making the sequence number be 64-bit. That doesn't even grow the data structures in question, because the other adjacent fields are already 64-bit. So simplify the whole thing by just making the sequence number overflow case go away entirely, which gets rid of all the complications and makes the code faster too. Win-win. [ Oleg Nesterov points out that the VMACACHE_FULL_FLUSHES statistics also just goes away entirely with this ] Reported-by: Jann Horn <jannh@google.com> Suggested-by: Will Deacon <will.deacon@arm.com> Acked-by: Davidlohr Bueso <dave@stgolabs.net> Cc: Oleg Nesterov <oleg@redhat.com> Cc: stable@kernel.org Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</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: Try<JWT, JWTError> JWT::parse(const string& token, const string& secret) { const vector<string> components = strings::split(token, "."); if (components.size() != 3) { return JWTError( "Expected 3 components in token, got " + stringify(components.size()), JWTError::Type::INVALID_TOKEN); } Try<JWT::Header> header = parse_header(components[0]); if (header.isError()) { return JWTError(header.error(), JWTError::Type::INVALID_TOKEN); } if (header->alg != JWT::Alg::HS256) { return JWTError( "Token 'alg' value \"" + stringify(header->alg) + "\" does not match, expected \"HS256\"", JWTError::Type::INVALID_TOKEN); } Try<JSON::Object> payload = parse_payload(components[1]); if (payload.isError()) { return JWTError(payload.error(), JWTError::Type::INVALID_TOKEN); } const Try<string> signature = base64::decode_url_safe(components[2]); if (signature.isError()) { return JWTError( "Failed to base64url-decode token signature: " + signature.error(), JWTError::Type::INVALID_TOKEN); } // Validate HMAC SHA256 signature. Try<string> hmac = generate_hmac_sha256( components[0] + "." + components[1], secret); if (hmac.isError()) { return JWTError( "Failed to generate HMAC signature: " + hmac.error(), JWTError::Type::UNKNOWN); } const bool valid = hmac.get() == signature.get(); if (!valid) { return JWTError( "Token signature does not match", JWTError::Type::INVALID_TOKEN); } return JWT(header.get(), payload.get(), signature.get()); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Added constant time comparison of JWT signatures. A vulnerability in our JWT implementation allows an unauthenticated remote attacker to execute to execute timing attacks [1]. This patch removes the vulnerability by adding a constant time comparison of hashes, where the whole message is visited during the comparison instead of returning at the first failure. [1] https://codahale.com/a-lesson-in-timing-attacks/ Review: https://reviews.apache.org/r/67357'</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 WritePDBImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { const char *comment; int bits; MagickBooleanType status; PDBImage pdb_image; PDBInfo pdb_info; QuantumInfo *quantum_info; register const Quantum *p; register ssize_t x; register unsigned char *q; size_t bits_per_pixel, literal, packets, packet_size, repeat; ssize_t y; unsigned char *buffer, *runlength, *scanline; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); (void) TransformImageColorspace(image,sRGBColorspace,exception); if (SetImageMonochrome(image,exception) != MagickFalse) { bits_per_pixel=1; } else if (image->colors <= 4) { bits_per_pixel=2; } else if (image->colors <= 8) { bits_per_pixel=3; } else { bits_per_pixel=4; } (void) memset(&pdb_info,0,sizeof(pdb_info)); (void) memset(&pdb_image,0,sizeof(pdb_image)); (void) CopyMagickString(pdb_info.name,image_info->filename, sizeof(pdb_info.name)); pdb_info.attributes=0; pdb_info.version=0; pdb_info.create_time=time(NULL); pdb_info.modify_time=pdb_info.create_time; pdb_info.archive_time=0; pdb_info.modify_number=0; pdb_info.application_info=0; pdb_info.sort_info=0; (void) memcpy(pdb_info.type,"vIMG",4); (void) memcpy(pdb_info.id,"View",4); pdb_info.seed=0; pdb_info.next_record=0; comment=GetImageProperty(image,"comment",exception); pdb_info.number_records=(comment == (const char *) NULL ? 1 : 2); (void) WriteBlob(image,sizeof(pdb_info.name),(unsigned char *) pdb_info.name); (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.attributes); (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.version); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.create_time); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_time); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.archive_time); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_number); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.application_info); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.sort_info); (void) WriteBlob(image,4,(unsigned char *) pdb_info.type); (void) WriteBlob(image,4,(unsigned char *) pdb_info.id); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.seed); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.next_record); (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.number_records); (void) CopyMagickString(pdb_image.name,pdb_info.name,sizeof(pdb_image.name)); pdb_image.version=1; /* RLE Compressed */ switch (bits_per_pixel) { case 1: pdb_image.type=(unsigned char) 0xff; break; /* monochrome */ case 2: pdb_image.type=(unsigned char) 0x00; break; /* 2 bit gray */ default: pdb_image.type=(unsigned char) 0x02; /* 4 bit gray */ } pdb_image.reserved_1=0; pdb_image.note=0; pdb_image.x_last=0; pdb_image.y_last=0; pdb_image.reserved_2=0; pdb_image.x_anchor=(unsigned short) 0xffff; pdb_image.y_anchor=(unsigned short) 0xffff; pdb_image.width=(short) image->columns; if (image->columns % 16) pdb_image.width=(short) (16*(image->columns/16+1)); pdb_image.height=(short) image->rows; packets=((bits_per_pixel*image->columns+7)/8); packet_size=(size_t) (image->depth > 8 ? 2 : 1); runlength=(unsigned char *) AcquireQuantumMemory(9UL*packets, image->rows*sizeof(*runlength)); buffer=(unsigned char *) AcquireQuantumMemory(512,sizeof(*buffer)); scanline=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size* sizeof(*scanline)); if ((runlength == (unsigned char *) NULL) || (buffer == (unsigned char *) NULL) || (scanline == (unsigned char *) NULL)) { if (runlength != (unsigned char *) NULL) runlength=(unsigned char *) RelinquishMagickMemory(runlength); if (buffer != (unsigned char *) NULL) buffer=(unsigned char *) RelinquishMagickMemory(buffer); if (scanline != (unsigned char *) NULL) scanline=(unsigned char *) RelinquishMagickMemory(scanline); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } (void) ResetMagickMemory(buffer,0,512*sizeof(*buffer)); if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); /* Convert to GRAY raster scanline. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumDepth(image,quantum_info,image->depth > 8 ? 16 : 8); bits=8/(int) bits_per_pixel-1; /* start at most significant bits */ literal=0; repeat=0; q=runlength; buffer[0]=0x00; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; (void) ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,scanline,exception); for (x=0; x < (ssize_t) pdb_image.width; x++) { if (x < (ssize_t) image->columns) buffer[literal+repeat]|=(0xff-scanline[x*packet_size]) >> (8-bits_per_pixel) << bits*bits_per_pixel; bits--; if (bits < 0) { if (((literal+repeat) > 0) && (buffer[literal+repeat] == buffer[literal+repeat-1])) { if (repeat == 0) { literal--; repeat++; } repeat++; if (0x7f < repeat) { q=EncodeRLE(q,buffer,literal,repeat); literal=0; repeat=0; } } else { if (repeat >= 2) literal+=repeat; else { q=EncodeRLE(q,buffer,literal,repeat); buffer[0]=buffer[literal+repeat]; literal=0; } literal++; repeat=0; if (0x7f < literal) { q=EncodeRLE(q,buffer,(literal < 0x80 ? literal : 0x80),0); (void) memmove(buffer,buffer+literal+repeat,0x80); literal-=0x80; } } bits=8/(int) bits_per_pixel-1; buffer[literal+repeat]=0x00; } } status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } q=EncodeRLE(q,buffer,literal,repeat); scanline=(unsigned char *) RelinquishMagickMemory(scanline); buffer=(unsigned char *) RelinquishMagickMemory(buffer); quantum_info=DestroyQuantumInfo(quantum_info); /* Write the Image record header. */ (void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8*pdb_info.number_records)); (void) WriteBlobByte(image,0x40); (void) WriteBlobByte(image,0x6f); (void) WriteBlobByte(image,0x80); (void) WriteBlobByte(image,0); if (pdb_info.number_records > 1) { /* Write the comment record header. */ (void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8+58+q- runlength)); (void) WriteBlobByte(image,0x40); (void) WriteBlobByte(image,0x6f); (void) WriteBlobByte(image,0x80); (void) WriteBlobByte(image,1); } /* Write the Image data. */ (void) WriteBlob(image,sizeof(pdb_image.name),(unsigned char *) pdb_image.name); (void) WriteBlobByte(image,(unsigned char) pdb_image.version); (void) WriteBlobByte(image,pdb_image.type); (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_1); (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.note); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.x_last); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.y_last); (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_2); (void) WriteBlobMSBShort(image,pdb_image.x_anchor); (void) WriteBlobMSBShort(image,pdb_image.y_anchor); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.width); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.height); (void) WriteBlob(image,(size_t) (q-runlength),runlength); runlength=(unsigned char *) RelinquishMagickMemory(runlength); if (pdb_info.number_records > 1) (void) WriteBlobString(image,comment); (void) CloseBlob(image); return(MagickTrue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1050'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception) { BMPInfo bmp_info; Image *image; MagickBooleanType status; MagickOffsetType offset, start_position; MemoryInfo *pixel_info; Quantum index; register Quantum *q; register ssize_t i, x; register unsigned char *p; size_t bit, bytes_per_line, length; ssize_t count, y; unsigned char magick[12], *pixels; unsigned int blue, green, offset_bits, red; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a BMP file. */ (void) memset(&bmp_info,0,sizeof(bmp_info)); bmp_info.ba_offset=0; start_position=0; offset_bits=0; count=ReadBlob(image,2,magick); if (count != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { PixelInfo quantum_bits; PixelPacket shift; /* Verify BMP identifier. */ if (bmp_info.ba_offset == 0) start_position=TellBlob(image)-2; bmp_info.ba_offset=0; while (LocaleNCompare((char *) magick,"BA",2) == 0) { bmp_info.file_size=ReadBlobLSBLong(image); bmp_info.ba_offset=ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); count=ReadBlob(image,2,magick); if (count != 2) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Magick: %c%c", magick[0],magick[1]); if ((count != 2) || ((LocaleNCompare((char *) magick,"BM",2) != 0) && (LocaleNCompare((char *) magick,"CI",2) != 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bmp_info.file_size=ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); bmp_info.size=ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," BMP size: %u", bmp_info.size); if (bmp_info.size == 12) { /* OS/2 BMP image file. */ (void) CopyMagickString(image->magick,"BMP2",MagickPathExtent); bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.x_pixels=0; bmp_info.y_pixels=0; bmp_info.number_colors=0; bmp_info.compression=BI_RGB; bmp_info.image_size=0; bmp_info.alpha_mask=0; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: OS/2 Bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); } } else { /* Microsoft Windows BMP image file. */ if (bmp_info.size < 40) ThrowReaderException(CorruptImageError,"NonOS2HeaderSizeError"); bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.compression=ReadBlobLSBLong(image); bmp_info.image_size=ReadBlobLSBLong(image); bmp_info.x_pixels=ReadBlobLSBLong(image); bmp_info.y_pixels=ReadBlobLSBLong(image); bmp_info.number_colors=ReadBlobLSBLong(image); if (bmp_info.number_colors > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); bmp_info.colors_important=ReadBlobLSBLong(image); if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: MS Windows bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Bits per pixel: %.20g",(double) bmp_info.bits_per_pixel); switch (bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RGB"); break; } case BI_RLE4: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE4"); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE8"); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_BITFIELDS"); break; } case BI_PNG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_PNG"); break; } case BI_JPEG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_JPEG"); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: UNKNOWN (%u)",bmp_info.compression); } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %u",bmp_info.number_colors); } bmp_info.red_mask=ReadBlobLSBLong(image); bmp_info.green_mask=ReadBlobLSBLong(image); bmp_info.blue_mask=ReadBlobLSBLong(image); if (bmp_info.size > 40) { double gamma; /* Read color management information. */ bmp_info.alpha_mask=ReadBlobLSBLong(image); bmp_info.colorspace=ReadBlobLSBSignedLong(image); /* Decode 2^30 fixed point formatted CIE primaries. */ # define BMP_DENOM ((double) 0x40000000) bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+ bmp_info.red_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.red_primary.x*=gamma; bmp_info.red_primary.y*=gamma; image->chromaticity.red_primary.x=bmp_info.red_primary.x; image->chromaticity.red_primary.y=bmp_info.red_primary.y; gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+ bmp_info.green_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.green_primary.x*=gamma; bmp_info.green_primary.y*=gamma; image->chromaticity.green_primary.x=bmp_info.green_primary.x; image->chromaticity.green_primary.y=bmp_info.green_primary.y; gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+ bmp_info.blue_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.blue_primary.x*=gamma; bmp_info.blue_primary.y*=gamma; image->chromaticity.blue_primary.x=bmp_info.blue_primary.x; image->chromaticity.blue_primary.y=bmp_info.blue_primary.y; /* Decode 16^16 fixed point formatted gamma_scales. */ bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000; /* Compute a single gamma from the BMP 3-channel gamma. */ image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+ bmp_info.gamma_scale.z)/3.0; } else (void) CopyMagickString(image->magick,"BMP3",MagickPathExtent); if (bmp_info.size > 108) { size_t intent; /* Read BMP Version 5 color management information. */ intent=ReadBlobLSBLong(image); switch ((int) intent) { case LCS_GM_BUSINESS: { image->rendering_intent=SaturationIntent; break; } case LCS_GM_GRAPHICS: { image->rendering_intent=RelativeIntent; break; } case LCS_GM_IMAGES: { image->rendering_intent=PerceptualIntent; break; } case LCS_GM_ABS_COLORIMETRIC: { image->rendering_intent=AbsoluteIntent; break; } } (void) ReadBlobLSBLong(image); /* Profile data */ (void) ReadBlobLSBLong(image); /* Profile size */ (void) ReadBlobLSBLong(image); /* Reserved byte */ } } if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "LengthAndFilesizeDoNotMatch","`%s'",image->filename); else if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"LengthAndFilesizeDoNotMatch","`%s'", image->filename); if (bmp_info.width <= 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.height == 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.planes != 1) ThrowReaderException(CorruptImageError,"StaticPlanesValueNotEqualToOne"); if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) && (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) && (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if (bmp_info.bits_per_pixel < 16 && bmp_info.number_colors > (1U << bmp_info.bits_per_pixel)) ThrowReaderException(CorruptImageError,"UnrecognizedNumberOfColors"); if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); switch (bmp_info.compression) { case BI_RGB: image->compression=NoCompression; break; case BI_RLE8: case BI_RLE4: image->compression=RLECompression; break; case BI_BITFIELDS: break; case BI_JPEG: ThrowReaderException(CoderError,"JPEGCompressNotSupported"); case BI_PNG: ThrowReaderException(CoderError,"PNGCompressNotSupported"); default: ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression"); } image->columns=(size_t) MagickAbsoluteValue(bmp_info.width); image->rows=(size_t) MagickAbsoluteValue(bmp_info.height); image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8; image->alpha_trait=((bmp_info.alpha_mask != 0) && (bmp_info.compression == BI_BITFIELDS)) ? BlendPixelTrait : UndefinedPixelTrait; if (bmp_info.bits_per_pixel < 16) { size_t one; image->storage_class=PseudoClass; image->colors=bmp_info.number_colors; one=1; if (image->colors == 0) image->colors=one << bmp_info.bits_per_pixel; } image->resolution.x=(double) bmp_info.x_pixels/100.0; image->resolution.y=(double) bmp_info.y_pixels/100.0; image->units=PixelsPerCentimeterResolution; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; size_t packet_size; /* Read BMP raster colormap. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading colormap of %.20g colors",(double) image->colors); if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if ((bmp_info.size == 12) || (bmp_info.size == 64)) packet_size=3; else packet_size=4; offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET); if (offset < 0) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,packet_size*image->colors,bmp_colormap); if (count != (ssize_t) (packet_size*image->colors)) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } p=bmp_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*p++); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*p++); image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p++); if (packet_size == 4) p++; } bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } /* Read image data. */ if (bmp_info.offset_bits == offset_bits) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); offset_bits=bmp_info.offset_bits; offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (bmp_info.compression == BI_RLE4) bmp_info.bits_per_pixel<<=1; bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); length=(size_t) bytes_per_line*image->rows; if (((MagickSizeType) length/8) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); if ((bmp_info.compression == BI_RGB) || (bmp_info.compression == BI_BITFIELDS)) { pixel_info=AcquireVirtualMemory(image->rows, MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading pixels (%.20g bytes)",(double) length); count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } } else { /* Convert run-length encoded raster pixels. */ pixel_info=AcquireVirtualMemory(image->rows, MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); status=DecodeImage(image,bmp_info.compression,pixels, image->columns*image->rows); if (status == MagickFalse) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnableToRunlengthDecodeImage"); } } /* Convert BMP raster image to pixel packets. */ if (bmp_info.compression == BI_RGB) { /* We should ignore the alpha value in BMP3 files but there have been reports about 32 bit files with alpha. We do a quick check to see if the alpha channel contains a value that is not zero (default value). If we find a non zero value we asume the program that wrote the file wants to use the alpha channel. */ if ((image->alpha_trait == UndefinedPixelTrait) && (bmp_info.size == 40) && (bmp_info.bits_per_pixel == 32)) { bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { if (*(p+3) != 0) { image->alpha_trait=BlendPixelTrait; y=-1; break; } p+=4; } } } bmp_info.alpha_mask=image->alpha_trait != UndefinedPixelTrait ? 0xff000000U : 0U; bmp_info.red_mask=0x00ff0000U; bmp_info.green_mask=0x0000ff00U; bmp_info.blue_mask=0x000000ffU; if (bmp_info.bits_per_pixel == 16) { /* RGB555. */ bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; } } (void) memset(&shift,0,sizeof(shift)); (void) memset(&quantum_bits,0,sizeof(quantum_bits)); if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32)) { register unsigned int sample; /* Get shift and quantum bits info from bitfield masks. */ if (bmp_info.red_mask != 0) while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0) { shift.red++; if (shift.red >= 32U) break; } if (bmp_info.green_mask != 0) while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0) { shift.green++; if (shift.green >= 32U) break; } if (bmp_info.blue_mask != 0) while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0) { shift.blue++; if (shift.blue >= 32U) break; } if (bmp_info.alpha_mask != 0) while (((bmp_info.alpha_mask << shift.alpha) & 0x80000000UL) == 0) { shift.alpha++; if (shift.alpha >= 32U) break; } sample=shift.red; while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.red=(MagickRealType) (sample-shift.red); sample=shift.green; while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.green=(MagickRealType) (sample-shift.green); sample=shift.blue; while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.blue=(MagickRealType) (sample-shift.blue); sample=shift.alpha; while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.alpha=(MagickRealType) (sample-shift.alpha); } switch (bmp_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (image->columns % 8); bit++) { index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 4: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0x0f),&index, exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); ValidateColormapValue(image,(ssize_t) (*p & 0x0f),&index,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; } if ((image->columns % 2) != 0) { ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0xf),&index, exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; x++; } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 8: { /* Convert PseudoColor scanline. */ if ((bmp_info.compression == BI_RLE8) || (bmp_info.compression == BI_RLE4)) bytes_per_line=image->columns; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns; x != 0; --x) { ValidateColormapValue(image,(ssize_t) *p++,&index,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 16: { unsigned int alpha, pixel; /* Convert bitfield encoded 16-bit PseudoColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=2*(image->columns+image->columns % 2); image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=(*p++) << 8; red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 5) red|=((red & 0xe000) >> 5); if (quantum_bits.red <= 8) red|=((red & 0xff00) >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 5) green|=((green & 0xe000) >> 5); if (quantum_bits.green == 6) green|=((green & 0xc000) >> 6); if (quantum_bits.green <= 8) green|=((green & 0xff00) >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 5) blue|=((blue & 0xe000) >> 5); if (quantum_bits.blue <= 8) blue|=((blue & 0xff00) >> 8); SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16; if (quantum_bits.alpha <= 8) alpha|=((alpha & 0xff00) >> 8); SetPixelAlpha(image,ScaleShortToQuantum( (unsigned short) alpha),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectColor scanline. */ bytes_per_line=4*((image->columns*24+31)/32); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert bitfield encoded DirectColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { unsigned int alpha, pixel; p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=((unsigned int) *p++ << 8); pixel|=((unsigned int) *p++ << 16); pixel|=((unsigned int) *p++ << 24); red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 8) red|=(red >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 8) green|=(green >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 8) blue|=(blue >> 8); SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16; if (quantum_bits.alpha == 8) alpha|=(alpha >> 8); SetPixelAlpha(image,ScaleShortToQuantum( (unsigned short) alpha),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } default: { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } } pixel_info=RelinquishVirtualMemory(pixel_info); if (y > 0) break; if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if (bmp_info.height < 0) { Image *flipped_image; /* Correct image orientation. */ flipped_image=FlipImage(image,exception); if (flipped_image != (Image *) NULL) { DuplicateBlob(flipped_image,image); ReplaceImageInList(&image, flipped_image); image=flipped_image; } } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; *magick='\0'; if (bmp_info.ba_offset != 0) { offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,2,magick); if ((count == 2) && (IsBMP(magick,2) != MagickFalse)) { /* Acquire next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (IsBMP(magick,2) != MagickFalse); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1337'</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 link_acquire_conf(Link *link) { int r; assert(link); assert(link->network); assert(link->manager); assert(link->manager->event); if (link_ipv4ll_enabled(link)) { assert(link->ipv4ll); log_link_debug(link, "Acquiring IPv4 link-local address"); r = sd_ipv4ll_start(link->ipv4ll); if (r < 0) return log_link_warning_errno(link, r, "Could not acquire IPv4 link-local address: %m"); } if (link_dhcp4_enabled(link)) { assert(link->dhcp_client); log_link_debug(link, "Acquiring DHCPv4 lease"); r = sd_dhcp_client_start(link->dhcp_client); if (r < 0) return log_link_warning_errno(link, r, "Could not acquire DHCPv4 lease: %m"); } if (link_dhcp6_enabled(link)) { assert(link->ndisc_router_discovery); log_link_debug(link, "Discovering IPv6 routers"); r = sd_ndisc_router_discovery_start(link->ndisc_router_discovery); if (r < 0) return log_link_warning_errno(link, r, "Could not start IPv6 Router Discovery: %m"); } if (link_lldp_enabled(link)) { assert(link->lldp); log_link_debug(link, "Starting LLDP"); r = sd_lldp_start(link->lldp); if (r < 0) return log_link_warning_errno(link, r, "Could not start LLDP: %m"); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'networkd: IPv6 router discovery - follow IPv6AcceptRouterAdvertisemnt= The previous behavior: When DHCPv6 was enabled, router discover was performed first, and then DHCPv6 was enabled only if the relevant flags were passed in the Router Advertisement message. Moreover, router discovery was performed even if AcceptRouterAdvertisements=false, moreover, even if router advertisements were accepted (by the kernel) the flags indicating that DHCPv6 should be performed were ignored. New behavior: If RouterAdvertisements are accepted, and either no routers are found, or an advertisement is received indicating DHCPv6 should be performed, the DHCPv6 client is started. Moreover, the DHCP option now truly enables the DHCPv6 client regardless of router discovery (though it will probably not be very useful to get a lease withotu any routes, this seems the more consistent approach). The recommended default setting should be to set DHCP=ipv4 and to leave IPv6AcceptRouterAdvertisements unset.'</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: xfs_attr_shortform_addname(xfs_da_args_t *args) { int newsize, forkoff, retval; trace_xfs_attr_sf_addname(args); retval = xfs_attr_shortform_lookup(args); if ((args->flags & ATTR_REPLACE) && (retval == -ENOATTR)) { return retval; } else if (retval == -EEXIST) { if (args->flags & ATTR_CREATE) return retval; retval = xfs_attr_shortform_remove(args); ASSERT(retval == 0); } if (args->namelen >= XFS_ATTR_SF_ENTSIZE_MAX || args->valuelen >= XFS_ATTR_SF_ENTSIZE_MAX) return -ENOSPC; newsize = XFS_ATTR_SF_TOTSIZE(args->dp); newsize += XFS_ATTR_SF_ENTSIZE_BYNAME(args->namelen, args->valuelen); forkoff = xfs_attr_shortform_bytesfit(args->dp, newsize); if (!forkoff) return -ENOSPC; xfs_attr_shortform_add(args, forkoff); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-241', 'CWE-754'], 'message': 'xfs: don't fail when converting shortform attr to long form during ATTR_REPLACE Kanda Motohiro reported that expanding a tiny xattr into a large xattr fails on XFS because we remove the tiny xattr from a shortform fork and then try to re-add it after converting the fork to extents format having not removed the ATTR_REPLACE flag. This fails because the attr is no longer present, causing a fs shutdown. This is derived from the patch in his bug report, but we really shouldn't ignore a nonzero retval from the remove call. Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=199119 Reported-by: kanda.motohiro@gmail.com Reviewed-by: Dave Chinner <dchinner@redhat.com> Reviewed-by: Christoph Hellwig <hch@lst.de> Signed-off-by: Darrick J. Wong <darrick.wong@oracle.com>'</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: std::vector<Option> get_rgw_options() { return std::vector<Option>({ Option("rgw_acl_grants_max_num", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(100) .set_description("Max number of ACL grants in a single request"), Option("rgw_rados_tracing", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(false) .set_description("true if LTTng-UST tracepoints should be enabled"), Option("rgw_op_tracing", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(false) .set_description("true if LTTng-UST tracepoints should be enabled"), Option("rgw_max_chunk_size", Option::TYPE_SIZE, Option::LEVEL_ADVANCED) .set_default(4_M) .set_description("Set RGW max chunk size") .set_long_description( "The chunk size is the size of RADOS I/O requests that RGW sends when accessing " "data objects. RGW read and write operation will never request more than this amount " "in a single request. This also defines the rgw object head size, as head operations " "need to be atomic, and anything larger than this would require more than a single " "operation."), Option("rgw_put_obj_min_window_size", Option::TYPE_SIZE, Option::LEVEL_ADVANCED) .set_default(16_M) .set_description("The minimum RADOS write window size (in bytes).") .set_long_description( "The window size determines the total concurrent RADOS writes of a single rgw object. " "When writing an object RGW will send multiple chunks to RADOS. The total size of the " "writes does not exceed the window size. The window size can be automatically " "in order to better utilize the pipe.") .add_see_also({"rgw_put_obj_max_window_size", "rgw_max_chunk_size"}), Option("rgw_put_obj_max_window_size", Option::TYPE_SIZE, Option::LEVEL_ADVANCED) .set_default(64_M) .set_description("The maximum RADOS write window size (in bytes).") .set_long_description("The window size may be dynamically adjusted, but will not surpass this value.") .add_see_also({"rgw_put_obj_min_window_size", "rgw_max_chunk_size"}), Option("rgw_max_put_size", Option::TYPE_SIZE, Option::LEVEL_ADVANCED) .set_default(5_G) .set_description("Max size (in bytes) of regular (non multi-part) object upload.") .set_long_description( "Plain object upload is capped at this amount of data. In order to upload larger " "objects, a special upload mechanism is required. The S3 API provides the " "multi-part upload, and Swift provides DLO and SLO."), Option("rgw_max_put_param_size", Option::TYPE_SIZE, Option::LEVEL_ADVANCED) .set_default(1_M) .set_description("The maximum size (in bytes) of data input of certain RESTful requests."), Option("rgw_max_attr_size", Option::TYPE_SIZE, Option::LEVEL_ADVANCED) .set_default(0) .set_description("The maximum length of metadata value. 0 skips the check"), Option("rgw_max_attr_name_len", Option::TYPE_UINT, Option::LEVEL_ADVANCED) .set_default(0) .set_description("The maximum length of metadata name. 0 skips the check"), Option("rgw_max_attrs_num_in_req", Option::TYPE_UINT, Option::LEVEL_ADVANCED) .set_default(0) .set_description("The maximum number of metadata items that can be put via single request"), Option("rgw_override_bucket_index_max_shards", Option::TYPE_UINT, Option::LEVEL_DEV) .set_default(0) .set_description(""), Option("rgw_bucket_index_max_aio", Option::TYPE_UINT, Option::LEVEL_ADVANCED) .set_default(8) .set_description("Max number of concurrent RADOS requests when handling bucket shards."), Option("rgw_enable_quota_threads", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(true) .set_description("Enables the quota maintenance thread.") .set_long_description( "The quota maintenance thread is responsible for quota related maintenance work. " "The thread itself can be disabled, but in order for quota to work correctly, at " "least one RGW in each zone needs to have this thread running. Having the thread " "enabled on multiple RGW processes within the same zone can spread " "some of the maintenance work between them.") .add_see_also({"rgw_enable_gc_threads", "rgw_enable_lc_threads"}), Option("rgw_enable_gc_threads", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(true) .set_description("Enables the garbage collection maintenance thread.") .set_long_description( "The garbage collection maintenance thread is responsible for garbage collector " "maintenance work. The thread itself can be disabled, but in order for garbage " "collection to work correctly, at least one RGW in each zone needs to have this " "thread running. Having the thread enabled on multiple RGW processes within the " "same zone can spread some of the maintenance work between them.") .add_see_also({"rgw_enable_quota_threads", "rgw_enable_lc_threads"}), Option("rgw_enable_lc_threads", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(true) .set_description("Enables the lifecycle maintenance thread. This is required on at least on rgw for each zone.") .set_long_description( "The lifecycle maintenance thread is responsible for lifecycle related maintenance " "work. The thread itself can be disabled, but in order for lifecycle to work " "correctly, at least one RGW in each zone needs to have this thread running. Having" "the thread enabled on multiple RGW processes within the same zone can spread " "some of the maintenance work between them.") .add_see_also({"rgw_enable_gc_threads", "rgw_enable_quota_threads"}), Option("rgw_data", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("/var/lib/ceph/radosgw/$cluster-$id") .set_flag(Option::FLAG_NO_MON_UPDATE) .set_description("Alternative location for RGW configuration.") .set_long_description( "If this is set, the different Ceph system configurables (such as the keyring file " "will be located in the path that is specified here. "), Option("rgw_enable_apis", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("s3, s3website, swift, swift_auth, admin") .set_description("A list of set of RESTful APIs that rgw handles."), Option("rgw_cache_enabled", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(true) .set_description("Enable RGW metadata cache.") .set_long_description( "The metadata cache holds metadata entries that RGW requires for processing " "requests. Metadata entries can be user info, bucket info, and bucket instance " "info. If not found in the cache, entries will be fetched from the backing " "RADOS store.") .add_see_also("rgw_cache_lru_size"), Option("rgw_cache_lru_size", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(10000) .set_description("Max number of items in RGW metadata cache.") .set_long_description( "When full, the RGW metadata cache evicts least recently used entries.") .add_see_also("rgw_cache_enabled"), Option("rgw_socket_path", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("RGW FastCGI socket path (for FastCGI over Unix domain sockets).") .add_see_also("rgw_fcgi_socket_backlog"), Option("rgw_host", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("RGW FastCGI host name (for FastCGI over TCP)") .add_see_also({"rgw_port", "rgw_fcgi_socket_backlog"}), Option("rgw_port", Option::TYPE_STR, Option::LEVEL_BASIC) .set_default("") .set_description("RGW FastCGI port number (for FastCGI over TCP)") .add_see_also({"rgw_host", "rgw_fcgi_socket_backlog"}), Option("rgw_dns_name", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("The host name that RGW uses.") .set_long_description( "This is Needed for virtual hosting of buckets to work properly, unless configured " "via zonegroup configuration."), Option("rgw_dns_s3website_name", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("The host name that RGW uses for static websites (S3)") .set_long_description( "This is needed for virtual hosting of buckets, unless configured via zonegroup " "configuration."), Option("rgw_content_length_compat", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(false) .set_description("Multiple content length headers compatibility") .set_long_description( "Try to handle requests with abiguous multiple content length headers " "(Content-Length, Http-Content-Length)."), Option("rgw_lifecycle_work_time", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("00:00-06:00") .set_description("Lifecycle allowed work time") .set_long_description("Local time window in which the lifecycle maintenance thread can work."), Option("rgw_lc_lock_max_time", Option::TYPE_INT, Option::LEVEL_DEV) .set_default(60) .set_description(""), Option("rgw_lc_max_objs", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(32) .set_description("Number of lifecycle data shards") .set_long_description( "Number of RADOS objects to use for storing lifecycle index. This can affect " "concurrency of lifecycle maintenance, but requires multiple RGW processes " "running on the zone to be utilized."), Option("rgw_lc_max_rules", Option::TYPE_UINT, Option::LEVEL_ADVANCED) .set_default(1000) .set_description("Max number of lifecycle rules set on one bucket") .set_long_description("Number of lifecycle rules set on one bucket should be limited."), Option("rgw_lc_debug_interval", Option::TYPE_INT, Option::LEVEL_DEV) .set_default(-1) .set_description(""), Option("rgw_mp_lock_max_time", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(600) .set_description("Multipart upload max completion time") .set_long_description( "Time length to allow completion of a multipart upload operation. This is done " "to prevent concurrent completions on the same object with the same upload id."), Option("rgw_script_uri", Option::TYPE_STR, Option::LEVEL_DEV) .set_default("") .set_description(""), Option("rgw_request_uri", Option::TYPE_STR, Option::LEVEL_DEV) .set_default("") .set_description(""), Option("rgw_ignore_get_invalid_range", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(false) .set_description("Treat invalid (e.g., negative) range request as full") .set_long_description("Treat invalid (e.g., negative) range request " "as request for the full object (AWS compatibility)"), Option("rgw_swift_url", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("Swift-auth storage URL") .set_long_description( "Used in conjunction with rgw internal swift authentication. This affects the " "X-Storage-Url response header value.") .add_see_also("rgw_swift_auth_entry"), Option("rgw_swift_url_prefix", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("swift") .set_description("Swift URL prefix") .set_long_description("The URL path prefix for swift requests."), Option("rgw_swift_auth_url", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("Swift auth URL") .set_long_description( "Default url to which RGW connects and verifies tokens for v1 auth (if not using " "internal swift auth)."), Option("rgw_swift_auth_entry", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("auth") .set_description("Swift auth URL prefix") .set_long_description("URL path prefix for internal swift auth requests.") .add_see_also("rgw_swift_url"), Option("rgw_swift_tenant_name", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("Swift tenant name") .set_long_description("Tenant name that is used when constructing the swift path.") .add_see_also("rgw_swift_account_in_url"), Option("rgw_swift_account_in_url", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(false) .set_description("Swift account encoded in URL") .set_long_description("Whether the swift account is encoded in the uri path (AUTH_<account>).") .add_see_also("rgw_swift_tenant_name"), Option("rgw_swift_enforce_content_length", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(false) .set_description("Send content length when listing containers (Swift)") .set_long_description( "Whether content length header is needed when listing containers. When this is " "set to false, RGW will send extra info for each entry in the response."), Option("rgw_keystone_url", Option::TYPE_STR, Option::LEVEL_BASIC) .set_default("") .set_description("The URL to the Keystone server."), Option("rgw_keystone_admin_token", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("The admin token (shared secret) that is used for the Keystone requests."), Option("rgw_keystone_admin_user", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("Keystone admin user."), Option("rgw_keystone_admin_password", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("Keystone admin password."), Option("rgw_keystone_admin_tenant", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("Keystone admin user tenant."), Option("rgw_keystone_admin_project", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("Keystone admin user project (for Keystone v3)."), Option("rgw_keystone_admin_domain", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("Keystone admin user domain (for Keystone v3)."), Option("rgw_keystone_barbican_user", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("Keystone user to access barbican secrets."), Option("rgw_keystone_barbican_password", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("Keystone password for barbican user."), Option("rgw_keystone_barbican_tenant", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("Keystone barbican user tenant (Keystone v2.0)."), Option("rgw_keystone_barbican_project", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("Keystone barbican user project (Keystone v3)."), Option("rgw_keystone_barbican_domain", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("Keystone barbican user domain."), Option("rgw_keystone_api_version", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(2) .set_description("Version of Keystone API to use (2 or 3)."), Option("rgw_keystone_accepted_roles", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("Member, admin") .set_description("Only users with one of these roles will be served when doing Keystone authentication."), Option("rgw_keystone_accepted_admin_roles", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("List of roles allowing user to gain admin privileges (Keystone)."), Option("rgw_keystone_token_cache_size", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(10000) .set_description("Keystone token cache size") .set_long_description( "Max number of Keystone tokens that will be cached. Token that is not cached " "requires RGW to access the Keystone server when authenticating."), Option("rgw_keystone_revocation_interval", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(15_min) .set_description("Keystone cache revocation interval") .set_long_description( "Time (in seconds) that RGW waits between requests to Keystone for getting a list " "of revoked tokens. A revoked token might still be considered valid by RGW for " "this amount of time."), Option("rgw_keystone_verify_ssl", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(true) .set_description("Should RGW verify the Keystone server SSL certificate."), Option("rgw_keystone_implicit_tenants", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(false) .set_description("RGW Keystone implicit tenants creation") .set_long_description( "Implicitly create new users in their own tenant with the same name when " "authenticating via Keystone."), Option("rgw_cross_domain_policy", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("<allow-access-from domain=\"*\" secure=\"false\" />") .set_description("RGW handle cross domain policy") .set_long_description("Returned cross domain policy when accessing the crossdomain.xml " "resource (Swift compatiility)."), Option("rgw_healthcheck_disabling_path", Option::TYPE_STR, Option::LEVEL_DEV) .set_default("") .set_description("Swift health check api can be disabled if a file can be accessed in this path."), Option("rgw_s3_auth_use_rados", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(true) .set_description("Should S3 authentication use credentials stored in RADOS backend."), Option("rgw_s3_auth_use_keystone", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(false) .set_description("Should S3 authentication use Keystone."), Option("rgw_s3_auth_order", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("external, local") .set_description("Authentication strategy order to use for s3 authentication") .set_long_description( "Order of authentication strategies to try for s3 authentication, the allowed " "options are a comma separated list of engines external, local. The " "default order is to try all the externally configured engines before " "attempting local rados based authentication"), Option("rgw_barbican_url", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("URL to barbican server."), Option("rgw_ldap_uri", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("ldaps://<ldap.your.domain>") .set_description("Space-separated list of LDAP servers in URI format."), Option("rgw_ldap_binddn", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("uid=admin,cn=users,dc=example,dc=com") .set_description("LDAP entry RGW will bind with (user match)."), Option("rgw_ldap_searchdn", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("cn=users,cn=accounts,dc=example,dc=com") .set_description("LDAP search base (basedn)."), Option("rgw_ldap_dnattr", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("uid") .set_description("LDAP attribute containing RGW user names (to form binddns)."), Option("rgw_ldap_secret", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("/etc/openldap/secret") .set_description("Path to file containing credentials for rgw_ldap_binddn."), Option("rgw_s3_auth_use_ldap", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(false) .set_description("Should S3 authentication use LDAP."), Option("rgw_ldap_searchfilter", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("LDAP search filter."), Option("rgw_admin_entry", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("admin") .set_description("Path prefix to be used for accessing RGW RESTful admin API."), Option("rgw_enforce_swift_acls", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(true) .set_description("RGW enforce swift acls") .set_long_description( "Should RGW enforce special Swift-only ACLs. Swift has a special ACL that gives " "permission to access all objects in a container."), Option("rgw_swift_token_expiration", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(1_day) .set_description("Expiration time (in seconds) for token generated through RGW Swift auth."), Option("rgw_print_continue", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(true) .set_description("RGW support of 100-continue") .set_long_description( "Should RGW explicitly send 100 (continue) responses. This is mainly relevant when " "using FastCGI, as some FastCGI modules do not fully support this feature."), Option("rgw_print_prohibited_content_length", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(false) .set_description("RGW RFC-7230 compatibility") .set_long_description( "Specifies whether RGW violates RFC 7230 and sends Content-Length with 204 or 304 " "statuses."), Option("rgw_remote_addr_param", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("REMOTE_ADDR") .set_description("HTTP header that holds the remote address in incoming requests.") .set_long_description( "RGW will use this header to extract requests origin. When RGW runs behind " "a reverse proxy, the remote address header will point at the proxy's address " "and not at the originator's address. Therefore it is sometimes possible to " "have the proxy add the originator's address in a separate HTTP header, which " "will allow RGW to log it correctly." ) .add_see_also("rgw_enable_ops_log"), Option("rgw_op_thread_timeout", Option::TYPE_INT, Option::LEVEL_DEV) .set_default(10*60) .set_description("Timeout for async rados coroutine operations."), Option("rgw_op_thread_suicide_timeout", Option::TYPE_INT, Option::LEVEL_DEV) .set_default(0) .set_description(""), Option("rgw_thread_pool_size", Option::TYPE_INT, Option::LEVEL_BASIC) .set_default(512) .set_description("RGW requests handling thread pool size.") .set_long_description( "This parameter determines the number of concurrent requests RGW can process " "when using either the civetweb, or the fastcgi frontends. The higher this " "number is, RGW will be able to deal with more concurrent requests at the " "cost of more resource utilization."), Option("rgw_num_control_oids", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(8) .set_description("Number of control objects used for cross-RGW communication.") .set_long_description( "RGW uses certain control objects to send messages between different RGW " "processes running on the same zone. These messages include metadata cache " "invalidation info that is being sent when metadata is modified (such as " "user or bucket information). A higher number of control objects allows " "better concurrency of these messages, at the cost of more resource " "utilization."), Option("rgw_num_rados_handles", Option::TYPE_UINT, Option::LEVEL_ADVANCED) .set_default(1) .set_description("Number of librados handles that RGW uses.") .set_long_description( "This param affects the number of separate librados handles it uses to " "connect to the RADOS backend, which directly affects the number of connections " "RGW will have to each OSD. A higher number affects resource utilization."), Option("rgw_verify_ssl", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(true) .set_description("Should RGW verify SSL when connecing to a remote HTTP server") .set_long_description( "RGW can send requests to other RGW servers (e.g., in multi-site sync work). " "This configurable selects whether RGW should verify the certificate for " "the remote peer and host.") .add_see_also("rgw_keystone_verify_ssl"), Option("rgw_nfs_lru_lanes", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(5) .set_description(""), Option("rgw_nfs_lru_lane_hiwat", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(911) .set_description(""), Option("rgw_nfs_fhcache_partitions", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(3) .set_description(""), Option("rgw_nfs_fhcache_size", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(2017) .set_description(""), Option("rgw_nfs_namespace_expire_secs", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(300) .set_min(1) .set_description(""), Option("rgw_nfs_max_gc", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(300) .set_min(1) .set_description(""), Option("rgw_nfs_write_completion_interval_s", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(10) .set_description(""), Option("rgw_zone", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("Zone name") .add_see_also({"rgw_zonegroup", "rgw_realm"}), Option("rgw_zone_root_pool", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default(".rgw.root") .set_description("Zone root pool name") .set_long_description( "The zone root pool, is the pool where the RGW zone configuration located." ) .add_see_also({"rgw_zonegroup_root_pool", "rgw_realm_root_pool", "rgw_period_root_pool"}), Option("rgw_default_zone_info_oid", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("default.zone") .set_description("Default zone info object id") .set_long_description( "Name of the RADOS object that holds the default zone information." ), Option("rgw_region", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("Region name") .set_long_description( "Obsolete config option. The rgw_zonegroup option should be used instead.") .add_see_also("rgw_zonegroup"), Option("rgw_region_root_pool", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default(".rgw.root") .set_description("Region root pool") .set_long_description( "Obsolete config option. The rgw_zonegroup_root_pool should be used instead.") .add_see_also("rgw_zonegroup_root_pool"), Option("rgw_default_region_info_oid", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("default.region") .set_description("Default region info object id") .set_long_description( "Obsolete config option. The rgw_default_zonegroup_info_oid should be used instead.") .add_see_also("rgw_default_zonegroup_info_oid"), Option("rgw_zonegroup", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("Zonegroup name") .add_see_also({"rgw_zone", "rgw_realm"}), Option("rgw_zonegroup_root_pool", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default(".rgw.root") .set_description("Zonegroup root pool") .set_long_description( "The zonegroup root pool, is the pool where the RGW zonegroup configuration located." ) .add_see_also({"rgw_zone_root_pool", "rgw_realm_root_pool", "rgw_period_root_pool"}), Option("rgw_default_zonegroup_info_oid", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("default.zonegroup") .set_description(""), Option("rgw_realm", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description(""), Option("rgw_realm_root_pool", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default(".rgw.root") .set_description("Realm root pool") .set_long_description( "The realm root pool, is the pool where the RGW realm configuration located." ) .add_see_also({"rgw_zonegroup_root_pool", "rgw_zone_root_pool", "rgw_period_root_pool"}), Option("rgw_default_realm_info_oid", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("default.realm") .set_description(""), Option("rgw_period_root_pool", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default(".rgw.root") .set_description("Period root pool") .set_long_description( "The realm root pool, is the pool where the RGW realm configuration located." ) .add_see_also({"rgw_zonegroup_root_pool", "rgw_zone_root_pool", "rgw_realm_root_pool"}), Option("rgw_period_latest_epoch_info_oid", Option::TYPE_STR, Option::LEVEL_DEV) .set_default(".latest_epoch") .set_description(""), Option("rgw_log_nonexistent_bucket", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(false) .set_description("Should RGW log operations on bucket that does not exist") .set_long_description( "This config option applies to the ops log. When this option is set, the ops log " "will log operations that are sent to non existing buckets. These operations " "inherently fail, and do not correspond to a specific user.") .add_see_also("rgw_enable_ops_log"), Option("rgw_log_object_name", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("%Y-%m-%d-%H-%i-%n") .set_description("Ops log object name format") .set_long_description( "Defines the format of the RADOS objects names that ops log uses to store ops " "log data") .add_see_also("rgw_enable_ops_log"), Option("rgw_log_object_name_utc", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(false) .set_description("Should ops log object name based on UTC") .set_long_description( "If set, the names of the RADOS objects that hold the ops log data will be based " "on UTC time zone. If not set, it will use the local time zone.") .add_see_also({"rgw_enable_ops_log", "rgw_log_object_name"}), Option("rgw_usage_max_shards", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(32) .set_description("Number of shards for usage log.") .set_long_description( "The number of RADOS objects that RGW will use in order to store the usage log " "data.") .add_see_also("rgw_enable_usage_log"), Option("rgw_usage_max_user_shards", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(1) .set_min(1) .set_description("Number of shards for single user in usage log") .set_long_description( "The number of shards that a single user will span over in the usage log.") .add_see_also("rgw_enable_usage_log"), Option("rgw_enable_ops_log", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(false) .set_description("Enable ops log") .add_see_also({"rgw_log_nonexistent_bucket", "rgw_log_object_name", "rgw_ops_log_rados", "rgw_ops_log_socket_path"}), Option("rgw_enable_usage_log", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(false) .set_description("Enable usage log") .add_see_also("rgw_usage_max_shards"), Option("rgw_ops_log_rados", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(true) .set_description("Use RADOS for ops log") .set_long_description( "If set, RGW will store ops log information in RADOS.") .add_see_also({"rgw_enable_ops_log"}), Option("rgw_ops_log_socket_path", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("Unix domain socket path for ops log.") .set_long_description( "Path to unix domain socket that RGW will listen for connection on. When connected, " "RGW will send ops log data through it.") .add_see_also({"rgw_enable_ops_log", "rgw_ops_log_data_backlog"}), Option("rgw_ops_log_data_backlog", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(5 << 20) .set_description("Ops log socket backlog") .set_long_description( "Maximum amount of data backlog that RGW can keep when ops log is configured to " "send info through unix domain socket. When data backlog is higher than this, " "ops log entries will be lost. In order to avoid ops log information loss, the " "listener needs to clear data (by reading it) quickly enough.") .add_see_also({"rgw_enable_ops_log", "rgw_ops_log_socket_path"}), Option("rgw_fcgi_socket_backlog", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(1024) .set_description("FastCGI socket connection backlog") .set_long_description( "Size of FastCGI connection backlog. This reflects the maximum number of new " "connection requests that RGW can handle concurrently without dropping any. ") .add_see_also({"rgw_host", "rgw_socket_path"}), Option("rgw_usage_log_flush_threshold", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(1024) .set_description("Number of entries in usage log before flushing") .set_long_description( "This is the max number of entries that will be held in the usage log, before it " "will be flushed to the backend. Note that the usage log is periodically flushed, " "even if number of entries does not reach this threshold. A usage log entry " "corresponds to one or more operations on a single bucket.i") .add_see_also({"rgw_enable_usage_log", "rgw_usage_log_tick_interval"}), Option("rgw_usage_log_tick_interval", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(30) .set_description("Number of seconds between usage log flush cycles") .set_long_description( "The number of seconds between consecutive usage log flushes. The usage log will " "also flush itself to the backend if the number of pending entries reaches a " "certain threshold.") .add_see_also({"rgw_enable_usage_log", "rgw_usage_log_flush_threshold"}), Option("rgw_init_timeout", Option::TYPE_INT, Option::LEVEL_BASIC) .set_default(300) .set_description("Initialization timeout") .set_long_description( "The time length (in seconds) that RGW will allow for its initialization. RGW " "process will give up and quit if initialization is not complete after this amount " "of time."), Option("rgw_mime_types_file", Option::TYPE_STR, Option::LEVEL_BASIC) .set_default("/etc/mime.types") .set_description("Path to local mime types file") .set_long_description( "The mime types file is needed in Swift when uploading an object. If object's " "content type is not specified, RGW will use data from this file to assign " "a content type to the object."), Option("rgw_gc_max_objs", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(32) .set_description("Number of shards for garbage collector data") .set_long_description( "The number of garbage collector data shards, is the number of RADOS objects that " "RGW will use to store the garbage collection information on.") .add_see_also({"rgw_gc_obj_min_wait", "rgw_gc_processor_max_time", "rgw_gc_processor_period", "rgw_gc_max_concurrent_io"}), Option("rgw_gc_obj_min_wait", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(2_hr) .set_description("Garabge collection object expiration time") .set_long_description( "The length of time (in seconds) that the RGW collector will wait before purging " "a deleted object's data. RGW will not remove object immediately, as object could " "still have readers. A mechanism exists to increase the object's expiration time " "when it's being read.") .add_see_also({"rgw_gc_max_objs", "rgw_gc_processor_max_time", "rgw_gc_processor_period", "rgw_gc_max_concurrent_io"}), Option("rgw_gc_processor_max_time", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(1_hr) .set_description("Length of time GC processor can lease shard") .set_long_description( "Garbage collection thread in RGW process holds a lease on its data shards. These " "objects contain the information about the objects that need to be removed. RGW " "takes a lease in order to prevent multiple RGW processes from handling the same " "objects concurrently. This time signifies that maximum amount of time that RGW " "is allowed to hold that lease. In the case where RGW goes down uncleanly, this " "is the amount of time where processing of that data shard will be blocked.") .add_see_also({"rgw_gc_max_objs", "rgw_gc_obj_min_wait", "rgw_gc_processor_period", "rgw_gc_max_concurrent_io"}), Option("rgw_gc_processor_period", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(1_hr) .set_description("Garbage collector cycle run time") .set_long_description( "The amount of time between the start of consecutive runs of the garbage collector " "threads. If garbage collector runs takes more than this period, it will not wait " "before running again.") .add_see_also({"rgw_gc_max_objs", "rgw_gc_obj_min_wait", "rgw_gc_processor_max_time", "rgw_gc_max_concurrent_io", "rgw_gc_max_trim_chunk"}), Option("rgw_gc_max_concurrent_io", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(10) .set_description("Max concurrent RADOS IO operations for garbage collection") .set_long_description( "The maximum number of concurrent IO operations that the RGW garbage collection " "thread will use when purging old data.") .add_see_also({"rgw_gc_max_objs", "rgw_gc_obj_min_wait", "rgw_gc_processor_max_time", "rgw_gc_max_trim_chunk"}), Option("rgw_gc_max_trim_chunk", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(16) .set_description("Max number of keys to remove from garbage collector log in a single operation") .add_see_also({"rgw_gc_max_objs", "rgw_gc_obj_min_wait", "rgw_gc_processor_max_time", "rgw_gc_max_concurrent_io"}), Option("rgw_s3_success_create_obj_status", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(0) .set_description("HTTP return code override for object creation") .set_long_description( "If not zero, this is the HTTP return code that will be returned on a successful S3 " "object creation."), Option("rgw_resolve_cname", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(false) .set_description("Support vanity domain names via CNAME") .set_long_description( "If true, RGW will query DNS when detecting that it's serving a request that was " "sent to a host in another domain. If a CNAME record is configured for that domain " "it will use it instead. This gives user to have the ability of creating a unique " "domain of their own to point at data in their bucket."), Option("rgw_obj_stripe_size", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(4_M) .set_description("RGW object stripe size") .set_long_description( "The size of an object stripe for RGW objects. This is the maximum size a backing " "RADOS object will have. RGW objects that are larger than this will span over " "multiple objects."), Option("rgw_extended_http_attrs", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("RGW support extended HTTP attrs") .set_long_description( "Add new set of attributes that could be set on an object. These extra attributes " "can be set through HTTP header fields when putting the objects. If set, these " "attributes will return as HTTP fields when doing GET/HEAD on the object."), Option("rgw_exit_timeout_secs", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(120) .set_description("RGW shutdown timeout") .set_long_description("Number of seconds to wait for a process before exiting unconditionally."), Option("rgw_get_obj_window_size", Option::TYPE_SIZE, Option::LEVEL_ADVANCED) .set_default(16_M) .set_description("RGW object read window size") .set_long_description("The window size in bytes for a single object read request"), Option("rgw_get_obj_max_req_size", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(4_M) .set_description("RGW object read chunk size") .set_long_description( "The maximum request size of a single object read operation sent to RADOS"), Option("rgw_relaxed_s3_bucket_names", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(false) .set_description("RGW enable relaxed S3 bucket names") .set_long_description("RGW enable relaxed S3 bucket name rules for US region buckets."), Option("rgw_defer_to_bucket_acls", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("Bucket ACLs override object ACLs") .set_long_description( "If not empty, a string that selects that mode of operation. 'recurse' will use " "bucket's ACL for the authorizaton. 'full-control' will allow users that users " "that have full control permission on the bucket have access to the object."), Option("rgw_list_buckets_max_chunk", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(1000) .set_description("Max number of buckets to retrieve in a single listing operation") .set_long_description( "When RGW fetches lists of user's buckets from the backend, this is the max number " "of entries it will try to retrieve in a single operation. Note that the backend " "may choose to return a smaller number of entries."), Option("rgw_md_log_max_shards", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(64) .set_description("RGW number of metadata log shards") .set_long_description( "The number of shards the RGW metadata log entries will reside in. This affects " "the metadata sync parallelism as a shard can only be processed by a single " "RGW at a time"), Option("rgw_num_zone_opstate_shards", Option::TYPE_INT, Option::LEVEL_DEV) .set_default(128) .set_description(""), Option("rgw_opstate_ratelimit_sec", Option::TYPE_INT, Option::LEVEL_DEV) .set_default(30) .set_description(""), Option("rgw_curl_wait_timeout_ms", Option::TYPE_INT, Option::LEVEL_DEV) .set_default(1000) .set_description(""), Option("rgw_curl_low_speed_limit", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(1024) .set_long_description( "It contains the average transfer speed in bytes per second that the " "transfer should be below during rgw_curl_low_speed_time seconds for libcurl " "to consider it to be too slow and abort. Set it zero to disable this."), Option("rgw_curl_low_speed_time", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(300) .set_long_description( "It contains the time in number seconds that the transfer speed should be below " "the rgw_curl_low_speed_limit for the library to consider it too slow and abort. " "Set it zero to disable this."), Option("rgw_copy_obj_progress", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(true) .set_description("Send progress report through copy operation") .set_long_description( "If true, RGW will send progress information when copy operation is executed. "), Option("rgw_copy_obj_progress_every_bytes", Option::TYPE_SIZE, Option::LEVEL_ADVANCED) .set_default(1_M) .set_description("Send copy-object progress info after these many bytes"), Option("rgw_obj_tombstone_cache_size", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(1000) .set_description("Max number of entries to keep in tombstone cache") .set_long_description( "The tombstone cache is used when doing a multi-zone data sync. RGW keeps " "there information about removed objects which is needed in order to prevent " "re-syncing of objects that were already removed."), Option("rgw_data_log_window", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(30) .set_description("Data log time window") .set_long_description( "The data log keeps information about buckets that have objectst that were " "modified within a specific timeframe. The sync process then knows which buckets " "are needed to be scanned for data sync."), Option("rgw_data_log_changes_size", Option::TYPE_INT, Option::LEVEL_DEV) .set_default(1000) .set_description("Max size of pending changes in data log") .set_long_description( "RGW will trigger update to the data log if the number of pending entries reached " "this number."), Option("rgw_data_log_num_shards", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(128) .set_description("Number of data log shards") .set_long_description( "The number of shards the RGW data log entries will reside in. This affects the " "data sync parallelism as a shard can only be processed by a single RGW at a time."), Option("rgw_data_log_obj_prefix", Option::TYPE_STR, Option::LEVEL_DEV) .set_default("data_log") .set_description(""), Option("rgw_replica_log_obj_prefix", Option::TYPE_STR, Option::LEVEL_DEV) .set_default("replica_log") .set_description(""), Option("rgw_bucket_quota_ttl", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(600) .set_description("Bucket quota stats cache TTL") .set_long_description( "Length of time for bucket stats to be cached within RGW instance."), Option("rgw_bucket_quota_soft_threshold", Option::TYPE_FLOAT, Option::LEVEL_BASIC) .set_default(0.95) .set_description("RGW quota soft threshold") .set_long_description( "Threshold from which RGW doesn't rely on cached info for quota " "decisions. This is done for higher accuracy of the quota mechanism at " "cost of performance, when getting close to the quota limit. The value " "configured here is the ratio between the data usage to the max usage " "as specified by the quota."), Option("rgw_bucket_quota_cache_size", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(10000) .set_description("RGW quota stats cache size") .set_long_description( "Maximum number of entries in the quota stats cache."), Option("rgw_bucket_default_quota_max_objects", Option::TYPE_INT, Option::LEVEL_BASIC) .set_default(-1) .set_description("Default quota for max objects in a bucket") .set_long_description( "The default quota configuration for max number of objects in a bucket. A " "negative number means 'unlimited'."), Option("rgw_bucket_default_quota_max_size", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(-1) .set_description("Default quota for total size in a bucket") .set_long_description( "The default quota configuration for total size of objects in a bucket. A " "negative number means 'unlimited'."), Option("rgw_expose_bucket", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(false) .set_description("Send Bucket HTTP header with the response") .set_long_description( "If true, RGW will send a Bucket HTTP header with the responses. The header will " "contain the name of the bucket the operation happened on."), Option("rgw_frontends", Option::TYPE_STR, Option::LEVEL_BASIC) .set_default("civetweb port=7480") .set_description("RGW frontends configuration") .set_long_description( "A comma delimited list of frontends configuration. Each configuration contains " "the type of the frontend followed by an optional space delimited set of " "key=value config parameters."), Option("rgw_user_quota_bucket_sync_interval", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(180) .set_description("User quota bucket sync interval") .set_long_description( "Time period for accumulating modified buckets before syncing these stats."), Option("rgw_user_quota_sync_interval", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(1_day) .set_description("User quota sync interval") .set_long_description( "Time period for accumulating modified buckets before syncing entire user stats."), Option("rgw_user_quota_sync_idle_users", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(false) .set_description("Should sync idle users quota") .set_long_description( "Whether stats for idle users be fully synced."), Option("rgw_user_quota_sync_wait_time", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(1_day) .set_description("User quota full-sync wait time") .set_long_description( "Minimum time between two full stats sync for non-idle users."), Option("rgw_user_default_quota_max_objects", Option::TYPE_INT, Option::LEVEL_BASIC) .set_default(-1) .set_description("User quota max objects") .set_long_description( "The default quota configuration for total number of objects for a single user. A " "negative number means 'unlimited'."), Option("rgw_user_default_quota_max_size", Option::TYPE_INT, Option::LEVEL_BASIC) .set_default(-1) .set_description("User quota max size") .set_long_description( "The default quota configuration for total size of objects for a single user. A " "negative number means 'unlimited'."), Option("rgw_multipart_min_part_size", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(5_M) .set_description("Minimum S3 multipart-upload part size") .set_long_description( "When doing a multipart upload, each part (other than the last part) should be " "at least this size."), Option("rgw_multipart_part_upload_limit", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(10000) .set_description("Max number of parts in multipart upload"), Option("rgw_max_slo_entries", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(1000) .set_description("Max number of entries in Swift Static Large Object manifest"), Option("rgw_olh_pending_timeout_sec", Option::TYPE_INT, Option::LEVEL_DEV) .set_default(1_hr) .set_description("Max time for pending OLH change to complete") .set_long_description( "OLH is a versioned object's logical head. Operations on it are journaled and " "as pending before completion. If an operation doesn't complete with this amount " "of seconds, we remove the operation from the journal."), Option("rgw_user_max_buckets", Option::TYPE_INT, Option::LEVEL_BASIC) .set_default(1000) .set_description("Max number of buckets per user") .set_long_description( "A user can create this many buckets. Zero means unlimmited, negative number means " "user cannot create any buckets (although user will retain buckets already created."), Option("rgw_objexp_gc_interval", Option::TYPE_UINT, Option::LEVEL_ADVANCED) .set_default(10_min) .set_description("Swift objects expirer garbage collector interval"), Option("rgw_objexp_hints_num_shards", Option::TYPE_UINT, Option::LEVEL_ADVANCED) .set_default(127) .set_description("Number of object expirer data shards") .set_long_description( "The number of shards the (Swift) object expirer will store its data on."), Option("rgw_objexp_chunk_size", Option::TYPE_UINT, Option::LEVEL_DEV) .set_default(100) .set_description(""), Option("rgw_enable_static_website", Option::TYPE_BOOL, Option::LEVEL_BASIC) .set_default(false) .set_description("Enable static website APIs") .set_long_description( "This configurable controls whether RGW handles the website control APIs. RGW can " "server static websites if s3website hostnames are configured, and unrelated to " "this configurable."), Option("rgw_log_http_headers", Option::TYPE_STR, Option::LEVEL_BASIC) .set_default("") .set_description("List of HTTP headers to log") .set_long_description( "A comma delimited list of HTTP headers to log when seen, ignores case (e.g., " "http_x_forwarded_for)."), Option("rgw_num_async_rados_threads", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(32) .set_description("Number of concurrent RADOS operations in multisite sync") .set_long_description( "The number of concurrent RADOS IO operations that will be triggered for handling " "multisite sync operations. This includes control related work, and not the actual " "sync operations."), Option("rgw_md_notify_interval_msec", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(200) .set_description("Length of time to aggregate metadata changes") .set_long_description( "Length of time (in milliseconds) in which the master zone aggregates all the " "metadata changes that occurred, before sending notifications to all the other " "zones."), Option("rgw_run_sync_thread", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(true) .set_description("Should run sync thread"), Option("rgw_sync_lease_period", Option::TYPE_INT, Option::LEVEL_DEV) .set_default(120) .set_description(""), Option("rgw_sync_log_trim_interval", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(1200) .set_description("Sync log trim interval") .set_long_description( "Time in seconds between attempts to trim sync logs."), Option("rgw_sync_log_trim_max_buckets", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(16) .set_description("Maximum number of buckets to trim per interval") .set_long_description("The maximum number of buckets to consider for bucket index log trimming each trim interval, regardless of the number of bucket index shards. Priority is given to buckets with the most sync activity over the last trim interval.") .add_see_also("rgw_sync_log_trim_interval") .add_see_also("rgw_sync_log_trim_min_cold_buckets") .add_see_also("rgw_sync_log_trim_concurrent_buckets"), Option("rgw_sync_log_trim_min_cold_buckets", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(4) .set_description("Minimum number of cold buckets to trim per interval") .set_long_description("Of the `rgw_sync_log_trim_max_buckets` selected for bucket index log trimming each trim interval, at least this many of them must be 'cold' buckets. These buckets are selected in order from the list of all bucket instances, to guarantee that all buckets will be visited eventually.") .add_see_also("rgw_sync_log_trim_interval") .add_see_also("rgw_sync_log_trim_max_buckets") .add_see_also("rgw_sync_log_trim_concurrent_buckets"), Option("rgw_sync_log_trim_concurrent_buckets", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(4) .set_description("Maximum number of buckets to trim in parallel") .add_see_also("rgw_sync_log_trim_interval") .add_see_also("rgw_sync_log_trim_max_buckets") .add_see_also("rgw_sync_log_trim_min_cold_buckets"), Option("rgw_sync_data_inject_err_probability", Option::TYPE_FLOAT, Option::LEVEL_DEV) .set_default(0) .set_description(""), Option("rgw_sync_meta_inject_err_probability", Option::TYPE_FLOAT, Option::LEVEL_DEV) .set_default(0) .set_description(""), Option("rgw_sync_trace_history_size", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(4096) .set_description("Sync trace history size") .set_long_description( "Maximum number of complete sync trace entries to keep."), Option("rgw_sync_trace_per_node_log_size", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(32) .set_description("Sync trace per-node log size") .set_long_description( "The number of log entries to keep per sync-trace node."), Option("rgw_sync_trace_servicemap_update_interval", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(10) .set_description("Sync-trace service-map update interval") .set_long_description( "Number of seconds between service-map updates of sync-trace events."), Option("rgw_period_push_interval", Option::TYPE_FLOAT, Option::LEVEL_ADVANCED) .set_default(2) .set_description("Period push interval") .set_long_description( "Number of seconds to wait before retrying 'period push' operation."), Option("rgw_period_push_interval_max", Option::TYPE_FLOAT, Option::LEVEL_ADVANCED) .set_default(30) .set_description("Period push maximum interval") .set_long_description( "The max number of seconds to wait before retrying 'period push' after exponential " "backoff."), Option("rgw_safe_max_objects_per_shard", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(100*1024) .set_description("Safe number of objects per shard") .set_long_description( "This is the max number of objects per bucket index shard that RGW considers " "safe. RGW will warn if it identifies a bucket where its per-shard count is " "higher than a percentage of this number.") .add_see_also("rgw_shard_warning_threshold"), Option("rgw_shard_warning_threshold", Option::TYPE_FLOAT, Option::LEVEL_ADVANCED) .set_default(90) .set_description("Warn about max objects per shard") .set_long_description( "Warn if number of objects per shard in a specific bucket passed this percentage " "of the safe number.") .add_see_also("rgw_safe_max_objects_per_shard"), Option("rgw_swift_versioning_enabled", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(false) .set_description("Enable Swift versioning"), Option("rgw_swift_custom_header", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("Enable swift custom header") .set_long_description( "If not empty, specifies a name of HTTP header that can include custom data. When " "uploading an object, if this header is passed RGW will store this header info " "and it will be available when listing the bucket."), Option("rgw_swift_need_stats", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(true) .set_description("Enable stats on bucket listing in Swift"), Option("rgw_reshard_num_logs", Option::TYPE_INT, Option::LEVEL_DEV) .set_default(16) .set_description(""), Option("rgw_reshard_bucket_lock_duration", Option::TYPE_INT, Option::LEVEL_DEV) .set_default(120) .set_description(""), Option("rgw_trust_forwarded_https", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(false) .set_description("Trust Forwarded and X-Forwarded-Proto headers") .set_long_description( "When a proxy in front of radosgw is used for ssl termination, radosgw " "does not know whether incoming http connections are secure. Enable " "this option to trust the Forwarded and X-Forwarded-Proto headers sent " "by the proxy when determining whether the connection is secure. This " "is required for some features, such as server side encryption.") .add_see_also("rgw_crypt_require_ssl"), Option("rgw_crypt_require_ssl", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(true) .set_description("Requests including encryption key headers must be sent over ssl"), Option("rgw_crypt_default_encryption_key", Option::TYPE_STR, Option::LEVEL_DEV) .set_default("") .set_description(""), Option("rgw_crypt_s3_kms_encryption_keys", Option::TYPE_STR, Option::LEVEL_DEV) .set_default("") .set_description(""), Option("rgw_crypt_suppress_logs", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(true) .set_description("Suppress logs that might print client key"), Option("rgw_list_bucket_min_readahead", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(1000) .set_description("Minimum number of entries to request from rados for bucket listing"), Option("rgw_rest_getusage_op_compat", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(false) .set_description("REST GetUsage request backward compatibility"), Option("rgw_torrent_flag", Option::TYPE_BOOL, Option::LEVEL_ADVANCED) .set_default(false) .set_description("When true, uploaded objects will calculate and store " "a SHA256 hash of object data so the object can be " "retrieved as a torrent file"), Option("rgw_torrent_tracker", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("Torrent field announce and announce list"), Option("rgw_torrent_createby", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("torrent field created by"), Option("rgw_torrent_comment", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("Torrent field comment"), Option("rgw_torrent_encoding", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("torrent field encoding"), Option("rgw_data_notify_interval_msec", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(200) .set_description("data changes notification interval to followers"), Option("rgw_torrent_origin", Option::TYPE_STR, Option::LEVEL_ADVANCED) .set_default("") .set_description("Torrent origin"), Option("rgw_torrent_sha_unit", Option::TYPE_INT, Option::LEVEL_ADVANCED) .set_default(512*1024) .set_description(""), Option("rgw_dynamic_resharding", Option::TYPE_BOOL, Option::LEVEL_BASIC) .set_default(true) .set_description("Enable dynamic resharding") .set_long_description( "If true, RGW will dynamicall increase the number of shards in buckets that have " "a high number of objects per shard.") .add_see_also("rgw_max_objs_per_shard"), Option("rgw_max_objs_per_shard", Option::TYPE_INT, Option::LEVEL_BASIC) .set_default(100000) .set_description("Max objects per shard for dynamic resharding") .set_long_description( "This is the max number of objects per bucket index shard that RGW will " "allow with dynamic resharding. RGW will trigger an automatic reshard operation " "on the bucket if it exceeds this number.") .add_see_also("rgw_dynamic_resharding"), Option("rgw_reshard_thread_interval", Option::TYPE_UINT, Option::LEVEL_ADVANCED) .set_default(10_min) .set_description(""), Option("rgw_cache_expiry_interval", Option::TYPE_UINT, Option::LEVEL_ADVANCED) .set_default(15_min) .set_description("Number of seconds before entries in the cache are " "assumed stale and re-fetched. Zero is never.") .add_tag("performance") .add_service("rgw") .set_long_description("The Rados Gateway stores metadata and objects in " "an internal cache. This should be kept consistent " "by the OSD's relaying notify events between " "multiple watching RGW processes. In the event " "that this notification protocol fails, bounding " "the length of time that any data in the cache will " "be assumed valid will ensure that any RGW instance " "that falls out of sync will eventually recover. " "This seems to be an issue mostly for large numbers " "of RGW instances under heavy use. If you would like " "to turn off cache expiry, set this value to zero."), Option("rgw_max_listing_results", Option::TYPE_UINT, Option::LEVEL_ADVANCED) .set_default(1000) .set_min_max(1, 100000) .add_service("rgw") .set_description("Upper bound on results in listing operations, ListBucket max-keys"), .set_long_description("This caps the maximum permitted value for listing-like operations in RGW S3. " "Affects ListBucket(max-keys), " "ListBucketVersions(max-keys), " "ListBucketMultiPartUploads(max-uploads), " "ListMultipartUploadParts(max-parts)"), }); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-770'], 'message': 'rgw: fix issues with 'enforce bounds' patch The patch to enforce bounds on max-keys/max-uploads/max-parts had a few issues that would prevent us from compiling it. Instead of changing the code provided by the submitter, we're addressing them in a separate commit to maintain the DCO. Signed-off-by: Joao Eduardo Luis <joao@suse.de> Signed-off-by: Abhishek Lekshmanan <abhishek@suse.com> (cherry picked from commit 29bc434a6a81a2e5c5b8cfc4c8d5c82ca5bf538a) mimic specific fixes: As the largeish change from master g_conf() isn't in mimic yet, use the g_conf global structure, also make rgw_op use the value from req_info ceph context as we do for all the requests'</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: snmpDecodePacket(SnmpRequest * rq) { struct snmp_pdu *PDU; u_char *Community; u_char *buf = rq->buf; int len = rq->len; allow_t allow = ACCESS_DENIED; if (!Config.accessList.snmp) { debugs(49, DBG_IMPORTANT, "WARNING: snmp_access not configured. agent query DENIED from : " << rq->from); return; } debugs(49, 5, HERE << "Called."); PDU = snmp_pdu_create(0); /* Allways answer on SNMPv1 */ rq->session.Version = SNMP_VERSION_1; Community = snmp_parse(&rq->session, PDU, buf, len); /* Check if we have explicit permission to access SNMP data. * default (set above) is to deny all */ if (Community) { ACLFilledChecklist checklist(Config.accessList.snmp, NULL, NULL); checklist.src_addr = rq->from; checklist.snmp_community = (char *) Community; allow = checklist.fastCheck(); if (allow == ACCESS_ALLOWED && (snmp_coexist_V2toV1(PDU))) { rq->community = Community; rq->PDU = PDU; debugs(49, 5, "snmpAgentParse: reqid=[" << PDU->reqid << "]"); snmpConstructReponse(rq); } else { debugs(49, DBG_IMPORTANT, "WARNING: SNMP agent query DENIED from : " << rq->from); } xfree(Community); } else { debugs(49, DBG_IMPORTANT, "WARNING: Failed SNMP agent query from : " << rq->from); snmp_free_pdu(PDU); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-772'], 'message': 'Fix memory leak when parsing SNMP packet (#313) SNMP queries denied by snmp_access rules and queries with certain unsupported SNMPv2 commands were leaking a few hundred bytes each. Such queries trigger "SNMP agent query DENIED from..." WARNINGs in cache.log.'</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 url_stream_auth (auth_client *auth_user) { ice_config_t *config; int port; client_t *client = auth_user->client; auth_url *url = client->auth->state; char *mount, *host, *user, *pass, *ipaddr, *admin=""; char post [4096]; if (strchr (url->stream_auth, '@') == NULL) { if (url->userpwd) curl_easy_setopt (url->handle, CURLOPT_USERPWD, url->userpwd); else curl_easy_setopt (url->handle, CURLOPT_USERPWD, ""); } else curl_easy_setopt (url->handle, CURLOPT_USERPWD, ""); curl_easy_setopt (url->handle, CURLOPT_URL, url->stream_auth); curl_easy_setopt (url->handle, CURLOPT_POSTFIELDS, post); curl_easy_setopt (url->handle, CURLOPT_WRITEHEADER, auth_user); if (strcmp (auth_user->mount, httpp_getvar (client->parser, HTTPP_VAR_URI)) != 0) admin = "&admin=1"; mount = util_url_escape (auth_user->mount); config = config_get_config (); host = util_url_escape (config->hostname); port = config->port; config_release_config (); ipaddr = util_url_escape (client->con->ip); if (client->username) { user = util_url_escape(client->username); } else { user = strdup(""); } if (client->password) { pass = util_url_escape(client->password); } else { pass = strdup(""); } snprintf (post, sizeof (post), "action=stream_auth&mount=%s&ip=%s&server=%s&port=%d&user=%s&pass=%s%s", mount, ipaddr, host, port, user, pass, admin); free (ipaddr); free (user); free (pass); free (mount); free (host); client->authenticated = 0; if (curl_easy_perform (url->handle)) ICECAST_LOG_WARN("auth to server %s failed with %s", url->stream_auth, url->errormsg); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix: Fixed buffer overflows in URL auth code. See: #2342'</s>