text
stringlengths
478
483k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: do_conversion (const char *tocode, const char *fromcode, char const *in_org, size_t inlen, char **out) { iconv_t cd; /* sXXXav : hummm hard to guess... */ size_t len, done, outlen; int invalid = 0, tooshort = 0; char *s, *in, *in_save; cd = iconv_open (tocode, fromcode); if (cd == (iconv_t)(-1)) { logprintf (LOG_VERBOSE, _("Conversion from %s to %s isn't supported\n"), quote (fromcode), quote (tocode)); *out = NULL; return false; } /* iconv() has to work on an unescaped string */ in_save = in = xstrndup (in_org, inlen); url_unescape_except_reserved (in); inlen = strlen(in); len = outlen = inlen * 2; *out = s = xmalloc (outlen + 1); done = 0; for (;;) { if (iconv (cd, (ICONV_CONST char **) &in, &inlen, out, &outlen) != (size_t)(-1) && iconv (cd, NULL, NULL, out, &outlen) != (size_t)(-1)) { *out = s; *(s + len - outlen - done) = '\0'; xfree(in_save); iconv_close(cd); IF_DEBUG { /* not not print out embedded passwords, in_org might be an URL */ if (!strchr(in_org, '@') && !strchr(*out, '@')) debug_logprintf ("converted '%s' (%s) -> '%s' (%s)\n", in_org, fromcode, *out, tocode); else debug_logprintf ("logging suppressed, strings may contain password\n"); } return true; } /* Incomplete or invalid multibyte sequence */ if (errno == EINVAL || errno == EILSEQ) { if (!invalid) logprintf (LOG_VERBOSE, _("Incomplete or invalid multibyte sequence encountered\n")); invalid++; **out = *in; in++; inlen--; (*out)++; outlen--; } else if (errno == E2BIG) /* Output buffer full */ { tooshort++; done = len; len = outlen = done + inlen * 2; s = xrealloc (s, outlen + 1); *out = s + done; } else /* Weird, we got an unspecified error */ { logprintf (LOG_VERBOSE, _("Unhandled errno %d\n"), errno); break; } } xfree(in_save); iconv_close(cd); IF_DEBUG { /* not not print out embedded passwords, in_org might be an URL */ if (!strchr(in_org, '@') && !strchr(*out, '@')) debug_logprintf ("converted '%s' (%s) -> '%s' (%s)\n", in_org, fromcode, *out, tocode); else debug_logprintf ("logging suppressed, strings may contain password\n"); } return false; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix a buffer overflow vulnerability * src/iri.c(do_conversion): Reallocate the output buffer to a larger size if it is already full'</s>
<s>[INST] Given the following code containing errors, provide 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 process_peer_commit (pwd_session_t *session, uint8_t *in, size_t in_len, BN_CTX *bnctx) { uint8_t *ptr; size_t data_len; BIGNUM *x = NULL, *y = NULL, *cofactor = NULL; EC_POINT *K = NULL, *point = NULL; int res = 1; if (((session->peer_scalar = BN_new()) == NULL) || ((session->k = BN_new()) == NULL) || ((cofactor = BN_new()) == NULL) || ((x = BN_new()) == NULL) || ((y = BN_new()) == NULL) || ((point = EC_POINT_new(session->group)) == NULL) || ((K = EC_POINT_new(session->group)) == NULL) || ((session->peer_element = EC_POINT_new(session->group)) == NULL)) { DEBUG2("pwd: failed to allocate room to process peer's commit"); goto finish; } if (!EC_GROUP_get_cofactor(session->group, cofactor, NULL)) { DEBUG2("pwd: unable to get group co-factor"); goto finish; } /* element, x then y, followed by scalar */ ptr = (uint8_t *)in; data_len = BN_num_bytes(session->prime); /* * Did the peer send enough data? */ if (in_len < (2 * data_len + BN_num_bytes(session->order))) { DEBUG("pwd: Invalid commit packet"); goto finish; } BN_bin2bn(ptr, data_len, x); ptr += data_len; BN_bin2bn(ptr, data_len, y); ptr += data_len; data_len = BN_num_bytes(session->order); BN_bin2bn(ptr, data_len, session->peer_scalar); if (!EC_POINT_set_affine_coordinates_GFp(session->group, session->peer_element, x, y, bnctx)) { DEBUG2("pwd: unable to get coordinates of peer's element"); goto finish; } /* check to ensure peer's element is not in a small sub-group */ if (BN_cmp(cofactor, BN_value_one())) { if (!EC_POINT_mul(session->group, point, NULL, session->peer_element, cofactor, NULL)) { DEBUG2("pwd: unable to multiply element by co-factor"); goto finish; } if (EC_POINT_is_at_infinity(session->group, point)) { DEBUG2("pwd: peer's element is in small sub-group"); goto finish; } } /* compute the shared key, k */ if ((!EC_POINT_mul(session->group, K, NULL, session->pwe, session->peer_scalar, bnctx)) || (!EC_POINT_add(session->group, K, K, session->peer_element, bnctx)) || (!EC_POINT_mul(session->group, K, NULL, K, session->private_value, bnctx))) { DEBUG2("pwd: unable to compute shared key, k"); goto finish; } /* ensure that the shared key isn't in a small sub-group */ if (BN_cmp(cofactor, BN_value_one())) { if (!EC_POINT_mul(session->group, K, NULL, K, cofactor, NULL)) { DEBUG2("pwd: unable to multiply k by co-factor"); goto finish; } } /* * This check is strictly speaking just for the case above where * co-factor > 1 but it was suggested that even though this is probably * never going to happen it is a simple and safe check "just to be * sure" so let's be safe. */ if (EC_POINT_is_at_infinity(session->group, K)) { DEBUG2("pwd: k is point-at-infinity!"); goto finish; } if (!EC_POINT_get_affine_coordinates_GFp(session->group, K, session->k, NULL, bnctx)) { DEBUG2("pwd: unable to get shared secret from K"); goto finish; } res = 0; finish: EC_POINT_clear_free(K); EC_POINT_clear_free(point); BN_clear_free(cofactor); BN_clear_free(x); BN_clear_free(y); return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-345'], 'message': 'When processing an EAP-pwd Commit frame, the peer's scalar and elliptic curve point were not validated. This allowed an adversary to bypass authentication, and impersonate any user. Fix this vulnerability by assuring the received scalar lies within the valid range, and by checking that the received element is not the point at infinity and lies on the elliptic curve being used.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: handle_new_connection(struct qb_ipcs_service *s, int32_t auth_result, int32_t sock, void *msg, size_t len, struct ipc_auth_ugp *ugp) { struct qb_ipcs_connection *c = NULL; struct qb_ipc_connection_request *req = msg; int32_t res = auth_result; int32_t res2 = 0; uint32_t max_buffer_size = QB_MAX(req->max_msg_size, s->max_buffer_size); struct qb_ipc_connection_response response; c = qb_ipcs_connection_alloc(s); if (c == NULL) { qb_ipcc_us_sock_close(sock); return -ENOMEM; } c->receive_buf = calloc(1, max_buffer_size); if (c->receive_buf == NULL) { free(c); qb_ipcc_us_sock_close(sock); return -ENOMEM; } c->setup.u.us.sock = sock; c->request.max_msg_size = max_buffer_size; c->response.max_msg_size = max_buffer_size; c->event.max_msg_size = max_buffer_size; c->pid = ugp->pid; c->auth.uid = c->euid = ugp->uid; c->auth.gid = c->egid = ugp->gid; c->auth.mode = 0600; c->stats.client_pid = ugp->pid; snprintf(c->description, CONNECTION_DESCRIPTION, "%d-%d-%d", s->pid, ugp->pid, c->setup.u.us.sock); if (auth_result == 0 && c->service->serv_fns.connection_accept) { res = c->service->serv_fns.connection_accept(c, c->euid, c->egid); } if (res != 0) { goto send_response; } qb_util_log(LOG_DEBUG, "IPC credentials authenticated (%s)", c->description); memset(&response, 0, sizeof(response)); if (s->funcs.connect) { res = s->funcs.connect(s, c, &response); if (res != 0) { goto send_response; } } /* * The connection is good, add it to the active connection list */ c->state = QB_IPCS_CONNECTION_ACTIVE; qb_list_add(&c->list, &s->connections); send_response: response.hdr.id = QB_IPC_MSG_AUTHENTICATE; response.hdr.size = sizeof(response); response.hdr.error = res; if (res == 0) { response.connection = (intptr_t) c; response.connection_type = s->type; response.max_msg_size = c->request.max_msg_size; s->stats.active_connections++; } res2 = qb_ipc_us_send(&c->setup, &response, response.hdr.size); if (res == 0 && res2 != response.hdr.size) { res = res2; } if (res == 0) { qb_ipcs_connection_ref(c); if (s->serv_fns.connection_created) { s->serv_fns.connection_created(c); } if (c->state == QB_IPCS_CONNECTION_ACTIVE) { c->state = QB_IPCS_CONNECTION_ESTABLISHED; } qb_ipcs_connection_unref(c); } else { if (res == -EACCES) { qb_util_log(LOG_ERR, "Invalid IPC credentials (%s).", c->description); } else if (res == -EAGAIN) { qb_util_log(LOG_WARNING, "Denied connection, is not ready (%s)", c->description); } else { errno = -res; qb_util_perror(LOG_ERR, "Error in connection setup (%s)", c->description); } if (c->state == QB_IPCS_CONNECTION_INACTIVE) { /* This removes the initial alloc ref */ qb_ipcs_connection_unref(c); qb_ipcc_us_sock_close(sock); } else { qb_ipcs_disconnect(c); } } return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'ipc: use O_EXCL on SHM files, and randomize the names Signed-off-by: Christine Caulfield <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: qb_ipcs_us_connect(struct qb_ipcs_service *s, struct qb_ipcs_connection *c, struct qb_ipc_connection_response *r) { char path[PATH_MAX]; int32_t fd_hdr; int32_t res = 0; struct ipc_us_control *ctl; char *shm_ptr; qb_util_log(LOG_DEBUG, "connecting to client (%s)", c->description); c->request.u.us.sock = c->setup.u.us.sock; c->response.u.us.sock = c->setup.u.us.sock; snprintf(r->request, NAME_MAX, "qb-%s-control-%s", s->name, c->description); snprintf(r->response, NAME_MAX, "qb-%s-%s", s->name, c->description); fd_hdr = qb_sys_mmap_file_open(path, r->request, SHM_CONTROL_SIZE, O_CREAT | O_TRUNC | O_RDWR); if (fd_hdr < 0) { res = fd_hdr; errno = -fd_hdr; qb_util_perror(LOG_ERR, "couldn't create file for mmap (%s)", c->description); return res; } (void)strlcpy(r->request, path, PATH_MAX); (void)strlcpy(c->request.u.us.shared_file_name, r->request, NAME_MAX); res = chown(r->request, c->auth.uid, c->auth.gid); if (res != 0) { /* ignore res, this is just for the compiler warnings. */ res = 0; } res = chmod(r->request, c->auth.mode); if (res != 0) { /* ignore res, this is just for the compiler warnings. */ res = 0; } shm_ptr = mmap(0, SHM_CONTROL_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd_hdr, 0); if (shm_ptr == MAP_FAILED) { res = -errno; qb_util_perror(LOG_ERR, "couldn't create mmap for header (%s)", c->description); goto cleanup_hdr; } c->request.u.us.shared_data = shm_ptr; c->response.u.us.shared_data = shm_ptr + sizeof(struct ipc_us_control); c->event.u.us.shared_data = shm_ptr + (2 * sizeof(struct ipc_us_control)); ctl = (struct ipc_us_control *)c->request.u.us.shared_data; ctl->sent = 0; ctl->flow_control = 0; ctl = (struct ipc_us_control *)c->response.u.us.shared_data; ctl->sent = 0; ctl->flow_control = 0; ctl = (struct ipc_us_control *)c->event.u.us.shared_data; ctl->sent = 0; ctl->flow_control = 0; close(fd_hdr); fd_hdr = -1; /* request channel */ res = qb_ipc_dgram_sock_setup(r->response, "request", &c->request.u.us.sock, c->egid); if (res < 0) { goto cleanup_hdr; } res = set_sock_size(c->request.u.us.sock, c->request.max_msg_size); if (res != 0) { goto cleanup_hdr; } c->setup.u.us.sock_name = NULL; c->request.u.us.sock_name = NULL; /* response channel */ c->response.u.us.sock = c->request.u.us.sock; snprintf(path, PATH_MAX, "%s-%s", r->response, "response"); c->response.u.us.sock_name = strdup(path); /* event channel */ res = qb_ipc_dgram_sock_setup(r->response, "event-tx", &c->event.u.us.sock, c->egid); if (res < 0) { goto cleanup_hdr; } res = set_sock_size(c->event.u.us.sock, c->event.max_msg_size); if (res != 0) { goto cleanup_hdr; } snprintf(path, PATH_MAX, "%s-%s", r->response, "event"); c->event.u.us.sock_name = strdup(path); res = _sock_add_to_mainloop(c); if (res < 0) { goto cleanup_hdr; } return res; cleanup_hdr: free(c->response.u.us.sock_name); free(c->event.u.us.sock_name); if (fd_hdr >= 0) { close(fd_hdr); } unlink(r->request); munmap(c->request.u.us.shared_data, SHM_CONTROL_SIZE); return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'ipc: use O_EXCL on SHM files, and randomize the names Signed-off-by: Christine Caulfield <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: qb_log_blackbox_write_to_file(const char *filename) { ssize_t written_size = 0; struct qb_log_target *t; struct _blackbox_file_header header; int fd = open(filename, O_CREAT | O_RDWR, 0700); if (fd < 0) { return -errno; } /* Write header, so we know this is a 'new' format blackbox */ header.word_size = QB_BLACKBOX_HEADER_WORDSIZE; header.read_pt = QB_BLACKBOX_HEADER_READPT; header.write_pt = QB_BLACKBOX_HEADER_WRITEPT; header.version = QB_BLACKBOX_HEADER_VERSION; header.hash = QB_BLACKBOX_HEADER_HASH; written_size = write(fd, &header, sizeof(header)); if (written_size < sizeof(header)) { close(fd); return written_size; } t = qb_log_target_get(QB_LOG_BLACKBOX); if (t->instance) { written_size += qb_rb_write_to_file(t->instance, fd); } else { written_size = -ENOENT; } close(fd); return written_size; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'ipc: use O_EXCL on SHM files, and randomize the names Signed-off-by: Christine Caulfield <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: qb_log_blackbox_write_to_file(const char *filename) { ssize_t written_size = 0; struct qb_log_target *t; struct _blackbox_file_header header; int fd = open(filename, O_CREAT | O_RDWR | O_EXCL, 0700); if (fd < 0) { return -errno; } /* Write header, so we know this is a 'new' format blackbox */ header.word_size = QB_BLACKBOX_HEADER_WORDSIZE; header.read_pt = QB_BLACKBOX_HEADER_READPT; header.write_pt = QB_BLACKBOX_HEADER_WRITEPT; header.version = QB_BLACKBOX_HEADER_VERSION; header.hash = QB_BLACKBOX_HEADER_HASH; written_size = write(fd, &header, sizeof(header)); if (written_size < sizeof(header)) { close(fd); return written_size; } t = qb_log_target_get(QB_LOG_BLACKBOX); if (t->instance) { written_size += qb_rb_write_to_file(t->instance, fd); } else { written_size = -ENOENT; } close(fd); return written_size; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'ipc: fixes Use O_EXCL on IPC files'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: main (int argc, char **argv) { mode_t old_umask; cleanup_free char *base_path = NULL; int clone_flags; char *old_cwd = NULL; pid_t pid; int event_fd = -1; int child_wait_fd = -1; int setup_finished_pipe[] = {-1, -1}; const char *new_cwd; uid_t ns_uid; gid_t ns_gid; struct stat sbuf; uint64_t val; int res UNUSED; cleanup_free char *seccomp_data = NULL; size_t seccomp_len; struct sock_fprog seccomp_prog; cleanup_free char *args_data = NULL; /* Handle --version early on before we try to acquire/drop * any capabilities so it works in a build environment; * right now flatpak's build runs bubblewrap --version. * https://github.com/projectatomic/bubblewrap/issues/185 */ if (argc == 2 && (strcmp (argv[1], "--version") == 0)) print_version_and_exit (); real_uid = getuid (); real_gid = getgid (); /* Get the (optional) privileges we need */ acquire_privs (); /* Never gain any more privs during exec */ if (prctl (PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) die_with_error ("prctl(PR_SET_NO_NEW_CAPS) failed"); /* The initial code is run with high permissions (i.e. CAP_SYS_ADMIN), so take lots of care. */ read_overflowids (); argv0 = argv[0]; if (isatty (1)) host_tty_dev = ttyname (1); argv++; argc--; if (argc == 0) usage (EXIT_FAILURE, stderr); parse_args (&argc, (const char ***) &argv); /* suck the args into a cleanup_free variable to control their lifecycle */ args_data = opt_args_data; opt_args_data = NULL; if ((requested_caps[0] || requested_caps[1]) && is_privileged) die ("--cap-add in setuid mode can be used only by root"); if (opt_userns_block_fd != -1 && !opt_unshare_user) die ("--userns-block-fd requires --unshare-user"); if (opt_userns_block_fd != -1 && opt_info_fd == -1) die ("--userns-block-fd requires --info-fd"); /* We have to do this if we weren't installed setuid (and we're not * root), so let's just DWIM */ if (!is_privileged && getuid () != 0) opt_unshare_user = TRUE; #ifdef ENABLE_REQUIRE_USERNS /* In this build option, we require userns. */ if (is_privileged && getuid () != 0) opt_unshare_user = TRUE; #endif if (opt_unshare_user_try && stat ("/proc/self/ns/user", &sbuf) == 0) { bool disabled = FALSE; /* RHEL7 has a kernel module parameter that lets you enable user namespaces */ if (stat ("/sys/module/user_namespace/parameters/enable", &sbuf) == 0) { cleanup_free char *enable = NULL; enable = load_file_at (AT_FDCWD, "/sys/module/user_namespace/parameters/enable"); if (enable != NULL && enable[0] == 'N') disabled = TRUE; } /* Check for max_user_namespaces */ if (stat ("/proc/sys/user/max_user_namespaces", &sbuf) == 0) { cleanup_free char *max_user_ns = NULL; max_user_ns = load_file_at (AT_FDCWD, "/proc/sys/user/max_user_namespaces"); if (max_user_ns != NULL && strcmp(max_user_ns, "0\n") == 0) disabled = TRUE; } /* Debian lets you disable *unprivileged* user namespaces. However this is not a problem if we're privileged, and if we're not opt_unshare_user is TRUE already, and there is not much we can do, its just a non-working setup. */ if (!disabled) opt_unshare_user = TRUE; } if (argc == 0) usage (EXIT_FAILURE, stderr); __debug__ (("Creating root mount point\n")); if (opt_sandbox_uid == -1) opt_sandbox_uid = real_uid; if (opt_sandbox_gid == -1) opt_sandbox_gid = real_gid; if (!opt_unshare_user && opt_sandbox_uid != real_uid) die ("Specifying --uid requires --unshare-user"); if (!opt_unshare_user && opt_sandbox_gid != real_gid) die ("Specifying --gid requires --unshare-user"); if (!opt_unshare_uts && opt_sandbox_hostname != NULL) die ("Specifying --hostname requires --unshare-uts"); if (opt_as_pid_1 && !opt_unshare_pid) die ("Specifying --as-pid-1 requires --unshare-pid"); if (opt_as_pid_1 && lock_files != NULL) die ("Specifying --as-pid-1 and --lock-file is not permitted"); /* We need to read stuff from proc during the pivot_root dance, etc. Lets keep a fd to it open */ proc_fd = open ("/proc", O_PATH); if (proc_fd == -1) die_with_error ("Can't open /proc"); /* We need *some* mountpoint where we can mount the root tmpfs. We first try in /run, and if that fails, try in /tmp. */ base_path = xasprintf ("/run/user/%d/.bubblewrap", real_uid); if (ensure_dir (base_path, 0755)) { free (base_path); base_path = xasprintf ("/tmp/.bubblewrap-%d", real_uid); if (ensure_dir (base_path, 0755)) die_with_error ("Creating root mountpoint failed"); } __debug__ (("creating new namespace\n")); if (opt_unshare_pid && !opt_as_pid_1) { event_fd = eventfd (0, EFD_CLOEXEC | EFD_NONBLOCK); if (event_fd == -1) die_with_error ("eventfd()"); } /* We block sigchild here so that we can use signalfd in the monitor. */ block_sigchild (); clone_flags = SIGCHLD | CLONE_NEWNS; if (opt_unshare_user) clone_flags |= CLONE_NEWUSER; if (opt_unshare_pid) clone_flags |= CLONE_NEWPID; if (opt_unshare_net) clone_flags |= CLONE_NEWNET; if (opt_unshare_ipc) clone_flags |= CLONE_NEWIPC; if (opt_unshare_uts) clone_flags |= CLONE_NEWUTS; if (opt_unshare_cgroup) { if (stat ("/proc/self/ns/cgroup", &sbuf)) { if (errno == ENOENT) die ("Cannot create new cgroup namespace because the kernel does not support it"); else die_with_error ("stat on /proc/self/ns/cgroup failed"); } clone_flags |= CLONE_NEWCGROUP; } if (opt_unshare_cgroup_try) if (!stat ("/proc/self/ns/cgroup", &sbuf)) clone_flags |= CLONE_NEWCGROUP; child_wait_fd = eventfd (0, EFD_CLOEXEC); if (child_wait_fd == -1) die_with_error ("eventfd()"); /* Track whether pre-exec setup finished if we're reporting process exit */ if (opt_json_status_fd != -1) { int ret; ret = pipe2 (setup_finished_pipe, O_CLOEXEC); if (ret == -1) die_with_error ("pipe2()"); } pid = raw_clone (clone_flags, NULL); if (pid == -1) { if (opt_unshare_user) { if (errno == EINVAL) die ("Creating new namespace failed, likely because the kernel does not support user namespaces. bwrap must be installed setuid on such systems."); else if (errno == EPERM && !is_privileged) die ("No permissions to creating new namespace, likely because the kernel does not allow non-privileged user namespaces. On e.g. debian this can be enabled with 'sysctl kernel.unprivileged_userns_clone=1'."); } die_with_error ("Creating new namespace failed"); } ns_uid = opt_sandbox_uid; ns_gid = opt_sandbox_gid; if (pid != 0) { /* Parent, outside sandbox, privileged (initially) */ if (is_privileged && opt_unshare_user && opt_userns_block_fd == -1) { /* We're running as euid 0, but the uid we want to map is * not 0. This means we're not allowed to write this from * the child user namespace, so we do it from the parent. * * Also, we map uid/gid 0 in the namespace (to overflowuid) * if opt_needs_devpts is true, because otherwise the mount * of devpts fails due to root not being mapped. */ write_uid_gid_map (ns_uid, real_uid, ns_gid, real_gid, pid, TRUE, opt_needs_devpts); } /* Initial launched process, wait for exec:ed command to exit */ /* We don't need any privileges in the launcher, drop them immediately. */ drop_privs (FALSE); /* Optionally bind our lifecycle to that of the parent */ handle_die_with_parent (); if (opt_info_fd != -1) { cleanup_free char *output = xasprintf ("{\n \"child-pid\": %i\n}\n", pid); dump_info (opt_info_fd, output, TRUE); close (opt_info_fd); } if (opt_json_status_fd != -1) { cleanup_free char *output = xasprintf ("{ \"child-pid\": %i }\n", pid); dump_info (opt_json_status_fd, output, TRUE); } if (opt_userns_block_fd != -1) { char b[1]; (void) TEMP_FAILURE_RETRY (read (opt_userns_block_fd, b, 1)); close (opt_userns_block_fd); } /* Let child run now that the uid maps are set up */ val = 1; res = write (child_wait_fd, &val, 8); /* Ignore res, if e.g. the child died and closed child_wait_fd we don't want to error out here */ close (child_wait_fd); return monitor_child (event_fd, pid, setup_finished_pipe[0]); } /* Child, in sandbox, privileged in the parent or in the user namespace (if --unshare-user). * * Note that for user namespaces we run as euid 0 during clone(), so * the child user namespace is owned by euid 0., This means that the * regular user namespace parent (with uid != 0) doesn't have any * capabilities in it, which is nice as we can't exploit those. In * particular the parent user namespace doesn't have CAP_PTRACE * which would otherwise allow the parent to hijack of the child * after this point. * * Unfortunately this also means you can't ptrace the final * sandboxed process from outside the sandbox either. */ if (opt_info_fd != -1) close (opt_info_fd); if (opt_json_status_fd != -1) close (opt_json_status_fd); /* Wait for the parent to init uid/gid maps and drop caps */ res = read (child_wait_fd, &val, 8); close (child_wait_fd); /* At this point we can completely drop root uid, but retain the * required permitted caps. This allow us to do full setup as * the user uid, which makes e.g. fuse access work. */ switch_to_user_with_privs (); if (opt_unshare_net) loopback_setup (); /* Will exit if unsuccessful */ ns_uid = opt_sandbox_uid; ns_gid = opt_sandbox_gid; if (!is_privileged && opt_unshare_user && opt_userns_block_fd == -1) { /* In the unprivileged case we have to write the uid/gid maps in * the child, because we have no caps in the parent */ if (opt_needs_devpts) { /* This is a bit hacky, but we need to first map the real uid/gid to 0, otherwise we can't mount the devpts filesystem because root is not mapped. Later we will create another child user namespace and map back to the real uid */ ns_uid = 0; ns_gid = 0; } write_uid_gid_map (ns_uid, real_uid, ns_gid, real_gid, -1, TRUE, FALSE); } old_umask = umask (0); /* Need to do this before the chroot, but after we're the real uid */ resolve_symlinks_in_ops (); /* Mark everything as slave, so that we still * receive mounts from the real root, but don't * propagate mounts to the real root. */ if (mount (NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0) die_with_error ("Failed to make / slave"); /* Create a tmpfs which we will use as / in the namespace */ if (mount ("tmpfs", base_path, "tmpfs", MS_NODEV | MS_NOSUID, NULL) != 0) die_with_error ("Failed to mount tmpfs"); old_cwd = get_current_dir_name (); /* Chdir to the new root tmpfs mount. This will be the CWD during the entire setup. Access old or new root via "oldroot" and "newroot". */ if (chdir (base_path) != 0) die_with_error ("chdir base_path"); /* We create a subdir "$base_path/newroot" for the new root, that * way we can pivot_root to base_path, and put the old root at * "$base_path/oldroot". This avoids problems accessing the oldroot * dir if the user requested to bind mount something over / */ if (mkdir ("newroot", 0755)) die_with_error ("Creating newroot failed"); if (mount ("newroot", "newroot", NULL, MS_MGC_VAL | MS_BIND | MS_REC, NULL) < 0) die_with_error ("setting up newroot bind"); if (mkdir ("oldroot", 0755)) die_with_error ("Creating oldroot failed"); if (pivot_root (base_path, "oldroot")) die_with_error ("pivot_root"); if (chdir ("/") != 0) die_with_error ("chdir / (base path)"); if (is_privileged) { pid_t child; int privsep_sockets[2]; if (socketpair (AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, privsep_sockets) != 0) die_with_error ("Can't create privsep socket"); child = fork (); if (child == -1) die_with_error ("Can't fork unprivileged helper"); if (child == 0) { /* Unprivileged setup process */ drop_privs (FALSE); close (privsep_sockets[0]); setup_newroot (opt_unshare_pid, privsep_sockets[1]); exit (0); } else { int status; uint32_t buffer[2048]; /* 8k, but is int32 to guarantee nice alignment */ uint32_t op, flags; const char *arg1, *arg2; cleanup_fd int unpriv_socket = -1; unpriv_socket = privsep_sockets[0]; close (privsep_sockets[1]); do { op = read_priv_sec_op (unpriv_socket, buffer, sizeof (buffer), &flags, &arg1, &arg2); privileged_op (-1, op, flags, arg1, arg2); if (write (unpriv_socket, buffer, 1) != 1) die ("Can't write to op_socket"); } while (op != PRIV_SEP_OP_DONE); waitpid (child, &status, 0); /* Continue post setup */ } } else { setup_newroot (opt_unshare_pid, -1); } close_ops_fd (); /* The old root better be rprivate or we will send unmount events to the parent namespace */ if (mount ("oldroot", "oldroot", NULL, MS_REC | MS_PRIVATE, NULL) != 0) die_with_error ("Failed to make old root rprivate"); if (umount2 ("oldroot", MNT_DETACH)) die_with_error ("unmount old root"); /* This is our second pivot. It's like we're a Silicon Valley startup flush * with cash but short on ideas! * * We're aiming to make /newroot the real root, and get rid of /oldroot. To do * that we need a temporary place to store it before we can unmount it. */ { cleanup_fd int oldrootfd = open ("/", O_DIRECTORY | O_RDONLY); if (oldrootfd < 0) die_with_error ("can't open /"); if (chdir ("/newroot") != 0) die_with_error ("chdir /newroot"); /* While the documentation claims that put_old must be underneath * new_root, it is perfectly fine to use the same directory as the * kernel checks only if old_root is accessible from new_root. * * Both runc and LXC are using this "alternative" method for * setting up the root of the container: * * https://github.com/opencontainers/runc/blob/master/libcontainer/rootfs_linux.go#L671 * https://github.com/lxc/lxc/blob/master/src/lxc/conf.c#L1121 */ if (pivot_root (".", ".") != 0) die_with_error ("pivot_root(/newroot)"); if (fchdir (oldrootfd) < 0) die_with_error ("fchdir to oldroot"); if (umount2 (".", MNT_DETACH) < 0) die_with_error ("umount old root"); if (chdir ("/") != 0) die_with_error ("chdir /"); } if (opt_unshare_user && (ns_uid != opt_sandbox_uid || ns_gid != opt_sandbox_gid) && opt_userns_block_fd == -1) { /* Now that devpts is mounted and we've no need for mount permissions we can create a new userspace and map our uid 1:1 */ if (unshare (CLONE_NEWUSER)) die_with_error ("unshare user ns"); write_uid_gid_map (opt_sandbox_uid, ns_uid, opt_sandbox_gid, ns_gid, -1, FALSE, FALSE); } /* All privileged ops are done now, so drop caps we don't need */ drop_privs (!is_privileged); if (opt_block_fd != -1) { char b[1]; (void) TEMP_FAILURE_RETRY (read (opt_block_fd, b, 1)); close (opt_block_fd); } if (opt_seccomp_fd != -1) { seccomp_data = load_file_data (opt_seccomp_fd, &seccomp_len); if (seccomp_data == NULL) die_with_error ("Can't read seccomp data"); if (seccomp_len % 8 != 0) die ("Invalid seccomp data, must be multiple of 8"); seccomp_prog.len = seccomp_len / 8; seccomp_prog.filter = (struct sock_filter *) seccomp_data; close (opt_seccomp_fd); } umask (old_umask); new_cwd = "/"; if (opt_chdir_path) { if (chdir (opt_chdir_path)) die_with_error ("Can't chdir to %s", opt_chdir_path); new_cwd = opt_chdir_path; } else if (chdir (old_cwd) == 0) { /* If the old cwd is mapped in the sandbox, go there */ new_cwd = old_cwd; } else { /* If the old cwd is not mapped, go to home */ const char *home = getenv ("HOME"); if (home != NULL && chdir (home) == 0) new_cwd = home; } xsetenv ("PWD", new_cwd, 1); free (old_cwd); if (opt_new_session && setsid () == (pid_t) -1) die_with_error ("setsid"); if (label_exec (opt_exec_label) == -1) die_with_error ("label_exec %s", argv[0]); __debug__ (("forking for child\n")); if (!opt_as_pid_1 && (opt_unshare_pid || lock_files != NULL || opt_sync_fd != -1)) { /* We have to have a pid 1 in the pid namespace, because * otherwise we'll get a bunch of zombies as nothing reaps * them. Alternatively if we're using sync_fd or lock_files we * need some process to own these. */ pid = fork (); if (pid == -1) die_with_error ("Can't fork for pid 1"); if (pid != 0) { drop_all_caps (FALSE); /* Close fds in pid 1, except stdio and optionally event_fd (for syncing pid 2 lifetime with monitor_child) and opt_sync_fd (for syncing sandbox lifetime with outside process). Any other fds will been passed on to the child though. */ { int dont_close[3]; int j = 0; if (event_fd != -1) dont_close[j++] = event_fd; if (opt_sync_fd != -1) dont_close[j++] = opt_sync_fd; dont_close[j++] = -1; fdwalk (proc_fd, close_extra_fds, dont_close); } return do_init (event_fd, pid, seccomp_data != NULL ? &seccomp_prog : NULL); } } __debug__ (("launch executable %s\n", argv[0])); if (proc_fd != -1) close (proc_fd); /* If we are using --as-pid-1 leak the sync fd into the sandbox. --sync-fd will still work unless the container process doesn't close this file. */ if (!opt_as_pid_1) { if (opt_sync_fd != -1) close (opt_sync_fd); } /* We want sigchild in the child */ unblock_sigchild (); /* Optionally bind our lifecycle */ handle_die_with_parent (); if (!is_privileged) set_ambient_capabilities (); /* Should be the last thing before execve() so that filters don't * need to handle anything above */ if (seccomp_data != NULL && prctl (PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &seccomp_prog) != 0) die_with_error ("prctl(PR_SET_SECCOMP)"); if (setup_finished_pipe[1] != -1) { char data = 0; res = write_to_fd (setup_finished_pipe[1], &data, 1); /* Ignore res, if e.g. the parent died and closed setup_finished_pipe[0] we don't want to error out here */ } if (execvp (argv[0], argv) == -1) { if (setup_finished_pipe[1] != -1) { int saved_errno = errno; char data = 0; res = write_to_fd (setup_finished_pipe[1], &data, 1); errno = saved_errno; /* Ignore res, if e.g. the parent died and closed setup_finished_pipe[0] we don't want to error out here */ } die_with_error ("execvp %s", argv[0]); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-269'], 'message': 'Don't create our own temporary mount point for pivot_root An attacker could pre-create /tmp/.bubblewrap-$UID and make it a non-directory, non-symlink (in which case mounting our tmpfs would fail, causing denial of service), or make it a symlink under their control (potentially allowing bad things if the protected_symlinks sysctl is not enabled). Instead, temporarily mount the tmpfs on a directory that we are sure exists and is not attacker-controlled. /tmp (the directory itself, not a subdirectory) will do. Fixes: #304 Bug-Debian: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=923557 Signed-off-by: Simon McVittie <[email protected]> Closes: #305 Approved by: cgwalters'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: setup_seccomp (FlatpakBwrap *bwrap, const char *arch, gulong allowed_personality, FlatpakRunFlags run_flags, GError **error) { gboolean multiarch = (run_flags & FLATPAK_RUN_FLAG_MULTIARCH) != 0; gboolean devel = (run_flags & FLATPAK_RUN_FLAG_DEVEL) != 0; __attribute__((cleanup (cleanup_seccomp))) scmp_filter_ctx seccomp = NULL; /**** BEGIN NOTE ON CODE SHARING * * There are today a number of different Linux container * implementations. That will likely continue for long into the * future. But we can still try to share code, and it's important * to do so because it affects what library and application writers * can do, and we should support code portability between different * container tools. * * This syscall blacklist is copied from linux-user-chroot, which was in turn * clearly influenced by the Sandstorm.io blacklist. * * If you make any changes here, I suggest sending the changes along * to other sandbox maintainers. Using the libseccomp list is also * an appropriate venue: * https://groups.google.com/forum/#!topic/libseccomp * * A non-exhaustive list of links to container tooling that might * want to share this blacklist: * * https://github.com/sandstorm-io/sandstorm * in src/sandstorm/supervisor.c++ * https://github.com/flatpak/flatpak.git * in common/flatpak-run.c * https://git.gnome.org/browse/linux-user-chroot * in src/setup-seccomp.c * **** END NOTE ON CODE SHARING */ struct { int scall; struct scmp_arg_cmp *arg; } syscall_blacklist[] = { /* Block dmesg */ {SCMP_SYS (syslog)}, /* Useless old syscall */ {SCMP_SYS (uselib)}, /* Don't allow disabling accounting */ {SCMP_SYS (acct)}, /* 16-bit code is unnecessary in the sandbox, and modify_ldt is a historic source of interesting information leaks. */ {SCMP_SYS (modify_ldt)}, /* Don't allow reading current quota use */ {SCMP_SYS (quotactl)}, /* Don't allow access to the kernel keyring */ {SCMP_SYS (add_key)}, {SCMP_SYS (keyctl)}, {SCMP_SYS (request_key)}, /* Scary VM/NUMA ops */ {SCMP_SYS (move_pages)}, {SCMP_SYS (mbind)}, {SCMP_SYS (get_mempolicy)}, {SCMP_SYS (set_mempolicy)}, {SCMP_SYS (migrate_pages)}, /* Don't allow subnamespace setups: */ {SCMP_SYS (unshare)}, {SCMP_SYS (mount)}, {SCMP_SYS (pivot_root)}, {SCMP_SYS (clone), &SCMP_A0 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)}, /* Don't allow faking input to the controlling tty (CVE-2017-5226) */ {SCMP_SYS (ioctl), &SCMP_A1 (SCMP_CMP_EQ, (int) TIOCSTI)}, }; struct { int scall; struct scmp_arg_cmp *arg; } syscall_nondevel_blacklist[] = { /* Profiling operations; we expect these to be done by tools from outside * the sandbox. In particular perf has been the source of many CVEs. */ {SCMP_SYS (perf_event_open)}, /* Don't allow you to switch to bsd emulation or whatnot */ {SCMP_SYS (personality), &SCMP_A0 (SCMP_CMP_NE, allowed_personality)}, {SCMP_SYS (ptrace)} }; /* Blacklist all but unix, inet, inet6 and netlink */ struct { int family; FlatpakRunFlags flags_mask; } socket_family_whitelist[] = { /* NOTE: Keep in numerical order */ { AF_UNSPEC, 0 }, { AF_LOCAL, 0 }, { AF_INET, 0 }, { AF_INET6, 0 }, { AF_NETLINK, 0 }, { AF_CAN, FLATPAK_RUN_FLAG_CANBUS }, { AF_BLUETOOTH, FLATPAK_RUN_FLAG_BLUETOOTH }, }; int last_allowed_family; int i, r; g_auto(GLnxTmpfile) seccomp_tmpf = { 0, }; seccomp = seccomp_init (SCMP_ACT_ALLOW); if (!seccomp) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Initialize seccomp failed")); if (arch != NULL) { uint32_t arch_id = 0; const uint32_t *extra_arches = NULL; if (strcmp (arch, "i386") == 0) { arch_id = SCMP_ARCH_X86; } else if (strcmp (arch, "x86_64") == 0) { arch_id = SCMP_ARCH_X86_64; extra_arches = seccomp_x86_64_extra_arches; } else if (strcmp (arch, "arm") == 0) { arch_id = SCMP_ARCH_ARM; } #ifdef SCMP_ARCH_AARCH64 else if (strcmp (arch, "aarch64") == 0) { arch_id = SCMP_ARCH_AARCH64; extra_arches = seccomp_aarch64_extra_arches; } #endif /* We only really need to handle arches on multiarch systems. * If only one arch is supported the default is fine */ if (arch_id != 0) { /* This *adds* the target arch, instead of replacing the native one. This is not ideal, because we'd like to only allow the target arch, but we can't really disallow the native arch at this point, because then bubblewrap couldn't continue running. */ r = seccomp_arch_add (seccomp, arch_id); if (r < 0 && r != -EEXIST) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Failed to add architecture to seccomp filter")); if (multiarch && extra_arches != NULL) { unsigned i; for (i = 0; extra_arches[i] != 0; i++) { r = seccomp_arch_add (seccomp, extra_arches[i]); if (r < 0 && r != -EEXIST) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Failed to add multiarch architecture to seccomp filter")); } } } } /* TODO: Should we filter the kernel keyring syscalls in some way? * We do want them to be used by desktop apps, but they could also perhaps * leak system stuff or secrets from other apps. */ for (i = 0; i < G_N_ELEMENTS (syscall_blacklist); i++) { int scall = syscall_blacklist[i].scall; if (syscall_blacklist[i].arg) r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 1, *syscall_blacklist[i].arg); else r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 0); if (r < 0 && r == -EFAULT /* unknown syscall */) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Failed to block syscall %d"), scall); } if (!devel) { for (i = 0; i < G_N_ELEMENTS (syscall_nondevel_blacklist); i++) { int scall = syscall_nondevel_blacklist[i].scall; if (syscall_nondevel_blacklist[i].arg) r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 1, *syscall_nondevel_blacklist[i].arg); else r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 0); if (r < 0 && r == -EFAULT /* unknown syscall */) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Failed to block syscall %d"), scall); } } /* Socket filtering doesn't work on e.g. i386, so ignore failures here * However, we need to user seccomp_rule_add_exact to avoid libseccomp doing * something else: https://github.com/seccomp/libseccomp/issues/8 */ last_allowed_family = -1; for (i = 0; i < G_N_ELEMENTS (socket_family_whitelist); i++) { int family = socket_family_whitelist[i].family; int disallowed; if (socket_family_whitelist[i].flags_mask != 0 && (socket_family_whitelist[i].flags_mask & run_flags) != socket_family_whitelist[i].flags_mask) continue; for (disallowed = last_allowed_family + 1; disallowed < family; disallowed++) { /* Blacklist the in-between valid families */ seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_EQ, disallowed)); } last_allowed_family = family; } /* Blacklist the rest */ seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_GE, last_allowed_family + 1)); if (!glnx_open_anonymous_tmpfile (O_RDWR | O_CLOEXEC, &seccomp_tmpf, error)) return FALSE; if (seccomp_export_bpf (seccomp, seccomp_tmpf.fd) != 0) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Failed to export bpf")); lseek (seccomp_tmpf.fd, 0, SEEK_SET); flatpak_bwrap_add_args_data_fd (bwrap, "--seccomp", glnx_steal_fd (&seccomp_tmpf.fd), NULL); return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'run: Only compare the lowest 32 ioctl arg bits for TIOCSTI Closes #2782. Closes: #2783 Approved by: alexlarsson'</s>
<s>[INST] Given the following code containing errors, provide 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 binder_buffer *binder_alloc_prepare_to_free_locked( struct binder_alloc *alloc, uintptr_t user_ptr) { struct rb_node *n = alloc->allocated_buffers.rb_node; struct binder_buffer *buffer; void *kern_ptr; kern_ptr = (void *)(user_ptr - alloc->user_buffer_offset); while (n) { buffer = rb_entry(n, struct binder_buffer, rb_node); BUG_ON(buffer->free); if (kern_ptr < buffer->data) n = n->rb_left; else if (kern_ptr > buffer->data) n = n->rb_right; else { /* * Guard against user threads attempting to * free the buffer twice */ if (buffer->free_in_progress) { binder_alloc_debug(BINDER_DEBUG_USER_ERROR, "%d:%d FREE_BUFFER u%016llx user freed buffer twice\n", alloc->pid, current->pid, (u64)user_ptr); return NULL; } buffer->free_in_progress = 1; return buffer; } } return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'binder: fix race that allows malicious free of live buffer Malicious code can attempt to free buffers using the BC_FREE_BUFFER ioctl to binder. There are protections against a user freeing a buffer while in use by the kernel, however there was a window where BC_FREE_BUFFER could be used to free a recently allocated buffer that was not completely initialized. This resulted in a use-after-free detected by KASAN with a malicious test program. This window is closed by setting the buffer's allow_user_free attribute to 0 when the buffer is allocated or when the user has previously freed it instead of waiting for the caller to set it. The problem was that when the struct buffer was recycled, allow_user_free was stale and set to 1 allowing a free to go through. Signed-off-by: Todd Kjos <[email protected]> Acked-by: Arve Hjønnevåg <[email protected]> Cc: stable <[email protected]> # 4.14 Signed-off-by: Greg Kroah-Hartman <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int binder_thread_write(struct binder_proc *proc, struct binder_thread *thread, binder_uintptr_t binder_buffer, size_t size, binder_size_t *consumed) { uint32_t cmd; struct binder_context *context = proc->context; void __user *buffer = (void __user *)(uintptr_t)binder_buffer; void __user *ptr = buffer + *consumed; void __user *end = buffer + size; while (ptr < end && thread->return_error.cmd == BR_OK) { int ret; if (get_user(cmd, (uint32_t __user *)ptr)) return -EFAULT; ptr += sizeof(uint32_t); trace_binder_command(cmd); if (_IOC_NR(cmd) < ARRAY_SIZE(binder_stats.bc)) { atomic_inc(&binder_stats.bc[_IOC_NR(cmd)]); atomic_inc(&proc->stats.bc[_IOC_NR(cmd)]); atomic_inc(&thread->stats.bc[_IOC_NR(cmd)]); } switch (cmd) { case BC_INCREFS: case BC_ACQUIRE: case BC_RELEASE: case BC_DECREFS: { uint32_t target; const char *debug_string; bool strong = cmd == BC_ACQUIRE || cmd == BC_RELEASE; bool increment = cmd == BC_INCREFS || cmd == BC_ACQUIRE; struct binder_ref_data rdata; if (get_user(target, (uint32_t __user *)ptr)) return -EFAULT; ptr += sizeof(uint32_t); ret = -1; if (increment && !target) { struct binder_node *ctx_mgr_node; mutex_lock(&context->context_mgr_node_lock); ctx_mgr_node = context->binder_context_mgr_node; if (ctx_mgr_node) ret = binder_inc_ref_for_node( proc, ctx_mgr_node, strong, NULL, &rdata); mutex_unlock(&context->context_mgr_node_lock); } if (ret) ret = binder_update_ref_for_handle( proc, target, increment, strong, &rdata); if (!ret && rdata.desc != target) { binder_user_error("%d:%d tried to acquire reference to desc %d, got %d instead\n", proc->pid, thread->pid, target, rdata.desc); } switch (cmd) { case BC_INCREFS: debug_string = "IncRefs"; break; case BC_ACQUIRE: debug_string = "Acquire"; break; case BC_RELEASE: debug_string = "Release"; break; case BC_DECREFS: default: debug_string = "DecRefs"; break; } if (ret) { binder_user_error("%d:%d %s %d refcount change on invalid ref %d ret %d\n", proc->pid, thread->pid, debug_string, strong, target, ret); break; } binder_debug(BINDER_DEBUG_USER_REFS, "%d:%d %s ref %d desc %d s %d w %d\n", proc->pid, thread->pid, debug_string, rdata.debug_id, rdata.desc, rdata.strong, rdata.weak); break; } case BC_INCREFS_DONE: case BC_ACQUIRE_DONE: { binder_uintptr_t node_ptr; binder_uintptr_t cookie; struct binder_node *node; bool free_node; if (get_user(node_ptr, (binder_uintptr_t __user *)ptr)) return -EFAULT; ptr += sizeof(binder_uintptr_t); if (get_user(cookie, (binder_uintptr_t __user *)ptr)) return -EFAULT; ptr += sizeof(binder_uintptr_t); node = binder_get_node(proc, node_ptr); if (node == NULL) { binder_user_error("%d:%d %s u%016llx no match\n", proc->pid, thread->pid, cmd == BC_INCREFS_DONE ? "BC_INCREFS_DONE" : "BC_ACQUIRE_DONE", (u64)node_ptr); break; } if (cookie != node->cookie) { binder_user_error("%d:%d %s u%016llx node %d cookie mismatch %016llx != %016llx\n", proc->pid, thread->pid, cmd == BC_INCREFS_DONE ? "BC_INCREFS_DONE" : "BC_ACQUIRE_DONE", (u64)node_ptr, node->debug_id, (u64)cookie, (u64)node->cookie); binder_put_node(node); break; } binder_node_inner_lock(node); if (cmd == BC_ACQUIRE_DONE) { if (node->pending_strong_ref == 0) { binder_user_error("%d:%d BC_ACQUIRE_DONE node %d has no pending acquire request\n", proc->pid, thread->pid, node->debug_id); binder_node_inner_unlock(node); binder_put_node(node); break; } node->pending_strong_ref = 0; } else { if (node->pending_weak_ref == 0) { binder_user_error("%d:%d BC_INCREFS_DONE node %d has no pending increfs request\n", proc->pid, thread->pid, node->debug_id); binder_node_inner_unlock(node); binder_put_node(node); break; } node->pending_weak_ref = 0; } free_node = binder_dec_node_nilocked(node, cmd == BC_ACQUIRE_DONE, 0); WARN_ON(free_node); binder_debug(BINDER_DEBUG_USER_REFS, "%d:%d %s node %d ls %d lw %d tr %d\n", proc->pid, thread->pid, cmd == BC_INCREFS_DONE ? "BC_INCREFS_DONE" : "BC_ACQUIRE_DONE", node->debug_id, node->local_strong_refs, node->local_weak_refs, node->tmp_refs); binder_node_inner_unlock(node); binder_put_node(node); break; } case BC_ATTEMPT_ACQUIRE: pr_err("BC_ATTEMPT_ACQUIRE not supported\n"); return -EINVAL; case BC_ACQUIRE_RESULT: pr_err("BC_ACQUIRE_RESULT not supported\n"); return -EINVAL; case BC_FREE_BUFFER: { binder_uintptr_t data_ptr; struct binder_buffer *buffer; if (get_user(data_ptr, (binder_uintptr_t __user *)ptr)) return -EFAULT; ptr += sizeof(binder_uintptr_t); buffer = binder_alloc_prepare_to_free(&proc->alloc, data_ptr); if (buffer == NULL) { binder_user_error("%d:%d BC_FREE_BUFFER u%016llx no match\n", proc->pid, thread->pid, (u64)data_ptr); break; } if (!buffer->allow_user_free) { binder_user_error("%d:%d BC_FREE_BUFFER u%016llx matched unreturned buffer\n", proc->pid, thread->pid, (u64)data_ptr); break; } binder_debug(BINDER_DEBUG_FREE_BUFFER, "%d:%d BC_FREE_BUFFER u%016llx found buffer %d for %s transaction\n", proc->pid, thread->pid, (u64)data_ptr, buffer->debug_id, buffer->transaction ? "active" : "finished"); binder_free_buf(proc, buffer); break; } case BC_TRANSACTION_SG: case BC_REPLY_SG: { struct binder_transaction_data_sg tr; if (copy_from_user(&tr, ptr, sizeof(tr))) return -EFAULT; ptr += sizeof(tr); binder_transaction(proc, thread, &tr.transaction_data, cmd == BC_REPLY_SG, tr.buffers_size); break; } case BC_TRANSACTION: case BC_REPLY: { struct binder_transaction_data tr; if (copy_from_user(&tr, ptr, sizeof(tr))) return -EFAULT; ptr += sizeof(tr); binder_transaction(proc, thread, &tr, cmd == BC_REPLY, 0); break; } case BC_REGISTER_LOOPER: binder_debug(BINDER_DEBUG_THREADS, "%d:%d BC_REGISTER_LOOPER\n", proc->pid, thread->pid); binder_inner_proc_lock(proc); if (thread->looper & BINDER_LOOPER_STATE_ENTERED) { thread->looper |= BINDER_LOOPER_STATE_INVALID; binder_user_error("%d:%d ERROR: BC_REGISTER_LOOPER called after BC_ENTER_LOOPER\n", proc->pid, thread->pid); } else if (proc->requested_threads == 0) { thread->looper |= BINDER_LOOPER_STATE_INVALID; binder_user_error("%d:%d ERROR: BC_REGISTER_LOOPER called without request\n", proc->pid, thread->pid); } else { proc->requested_threads--; proc->requested_threads_started++; } thread->looper |= BINDER_LOOPER_STATE_REGISTERED; binder_inner_proc_unlock(proc); break; case BC_ENTER_LOOPER: binder_debug(BINDER_DEBUG_THREADS, "%d:%d BC_ENTER_LOOPER\n", proc->pid, thread->pid); if (thread->looper & BINDER_LOOPER_STATE_REGISTERED) { thread->looper |= BINDER_LOOPER_STATE_INVALID; binder_user_error("%d:%d ERROR: BC_ENTER_LOOPER called after BC_REGISTER_LOOPER\n", proc->pid, thread->pid); } thread->looper |= BINDER_LOOPER_STATE_ENTERED; break; case BC_EXIT_LOOPER: binder_debug(BINDER_DEBUG_THREADS, "%d:%d BC_EXIT_LOOPER\n", proc->pid, thread->pid); thread->looper |= BINDER_LOOPER_STATE_EXITED; break; case BC_REQUEST_DEATH_NOTIFICATION: case BC_CLEAR_DEATH_NOTIFICATION: { uint32_t target; binder_uintptr_t cookie; struct binder_ref *ref; struct binder_ref_death *death = NULL; if (get_user(target, (uint32_t __user *)ptr)) return -EFAULT; ptr += sizeof(uint32_t); if (get_user(cookie, (binder_uintptr_t __user *)ptr)) return -EFAULT; ptr += sizeof(binder_uintptr_t); if (cmd == BC_REQUEST_DEATH_NOTIFICATION) { /* * Allocate memory for death notification * before taking lock */ death = kzalloc(sizeof(*death), GFP_KERNEL); if (death == NULL) { WARN_ON(thread->return_error.cmd != BR_OK); thread->return_error.cmd = BR_ERROR; binder_enqueue_thread_work( thread, &thread->return_error.work); binder_debug( BINDER_DEBUG_FAILED_TRANSACTION, "%d:%d BC_REQUEST_DEATH_NOTIFICATION failed\n", proc->pid, thread->pid); break; } } binder_proc_lock(proc); ref = binder_get_ref_olocked(proc, target, false); if (ref == NULL) { binder_user_error("%d:%d %s invalid ref %d\n", proc->pid, thread->pid, cmd == BC_REQUEST_DEATH_NOTIFICATION ? "BC_REQUEST_DEATH_NOTIFICATION" : "BC_CLEAR_DEATH_NOTIFICATION", target); binder_proc_unlock(proc); kfree(death); break; } binder_debug(BINDER_DEBUG_DEATH_NOTIFICATION, "%d:%d %s %016llx ref %d desc %d s %d w %d for node %d\n", proc->pid, thread->pid, cmd == BC_REQUEST_DEATH_NOTIFICATION ? "BC_REQUEST_DEATH_NOTIFICATION" : "BC_CLEAR_DEATH_NOTIFICATION", (u64)cookie, ref->data.debug_id, ref->data.desc, ref->data.strong, ref->data.weak, ref->node->debug_id); binder_node_lock(ref->node); if (cmd == BC_REQUEST_DEATH_NOTIFICATION) { if (ref->death) { binder_user_error("%d:%d BC_REQUEST_DEATH_NOTIFICATION death notification already set\n", proc->pid, thread->pid); binder_node_unlock(ref->node); binder_proc_unlock(proc); kfree(death); break; } binder_stats_created(BINDER_STAT_DEATH); INIT_LIST_HEAD(&death->work.entry); death->cookie = cookie; ref->death = death; if (ref->node->proc == NULL) { ref->death->work.type = BINDER_WORK_DEAD_BINDER; binder_inner_proc_lock(proc); binder_enqueue_work_ilocked( &ref->death->work, &proc->todo); binder_wakeup_proc_ilocked(proc); binder_inner_proc_unlock(proc); } } else { if (ref->death == NULL) { binder_user_error("%d:%d BC_CLEAR_DEATH_NOTIFICATION death notification not active\n", proc->pid, thread->pid); binder_node_unlock(ref->node); binder_proc_unlock(proc); break; } death = ref->death; if (death->cookie != cookie) { binder_user_error("%d:%d BC_CLEAR_DEATH_NOTIFICATION death notification cookie mismatch %016llx != %016llx\n", proc->pid, thread->pid, (u64)death->cookie, (u64)cookie); binder_node_unlock(ref->node); binder_proc_unlock(proc); break; } ref->death = NULL; binder_inner_proc_lock(proc); if (list_empty(&death->work.entry)) { death->work.type = BINDER_WORK_CLEAR_DEATH_NOTIFICATION; if (thread->looper & (BINDER_LOOPER_STATE_REGISTERED | BINDER_LOOPER_STATE_ENTERED)) binder_enqueue_thread_work_ilocked( thread, &death->work); else { binder_enqueue_work_ilocked( &death->work, &proc->todo); binder_wakeup_proc_ilocked( proc); } } else { BUG_ON(death->work.type != BINDER_WORK_DEAD_BINDER); death->work.type = BINDER_WORK_DEAD_BINDER_AND_CLEAR; } binder_inner_proc_unlock(proc); } binder_node_unlock(ref->node); binder_proc_unlock(proc); } break; case BC_DEAD_BINDER_DONE: { struct binder_work *w; binder_uintptr_t cookie; struct binder_ref_death *death = NULL; if (get_user(cookie, (binder_uintptr_t __user *)ptr)) return -EFAULT; ptr += sizeof(cookie); binder_inner_proc_lock(proc); list_for_each_entry(w, &proc->delivered_death, entry) { struct binder_ref_death *tmp_death = container_of(w, struct binder_ref_death, work); if (tmp_death->cookie == cookie) { death = tmp_death; break; } } binder_debug(BINDER_DEBUG_DEAD_BINDER, "%d:%d BC_DEAD_BINDER_DONE %016llx found %pK\n", proc->pid, thread->pid, (u64)cookie, death); if (death == NULL) { binder_user_error("%d:%d BC_DEAD_BINDER_DONE %016llx not found\n", proc->pid, thread->pid, (u64)cookie); binder_inner_proc_unlock(proc); break; } binder_dequeue_work_ilocked(&death->work); if (death->work.type == BINDER_WORK_DEAD_BINDER_AND_CLEAR) { death->work.type = BINDER_WORK_CLEAR_DEATH_NOTIFICATION; if (thread->looper & (BINDER_LOOPER_STATE_REGISTERED | BINDER_LOOPER_STATE_ENTERED)) binder_enqueue_thread_work_ilocked( thread, &death->work); else { binder_enqueue_work_ilocked( &death->work, &proc->todo); binder_wakeup_proc_ilocked(proc); } } binder_inner_proc_unlock(proc); } break; default: pr_err("%d:%d unknown command %d\n", proc->pid, thread->pid, cmd); return -EINVAL; } *consumed = ptr - buffer; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'binder: fix race that allows malicious free of live buffer Malicious code can attempt to free buffers using the BC_FREE_BUFFER ioctl to binder. There are protections against a user freeing a buffer while in use by the kernel, however there was a window where BC_FREE_BUFFER could be used to free a recently allocated buffer that was not completely initialized. This resulted in a use-after-free detected by KASAN with a malicious test program. This window is closed by setting the buffer's allow_user_free attribute to 0 when the buffer is allocated or when the user has previously freed it instead of waiting for the caller to set it. The problem was that when the struct buffer was recycled, allow_user_free was stale and set to 1 allowing a free to go through. Signed-off-by: Todd Kjos <[email protected]> Acked-by: Arve Hjønnevåg <[email protected]> Cc: stable <[email protected]> # 4.14 Signed-off-by: Greg Kroah-Hartman <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void CWebServer::GetFloorplanImage(WebEmSession & session, const request& req, reply & rep) { std::string idx = request::findValue(&req, "idx"); if (idx == "") { return; } std::vector<std::vector<std::string> > result; result = m_sql.safe_queryBlob("SELECT Image FROM Floorplans WHERE ID=%s", idx.c_str()); if (result.empty()) return; reply::set_content(&rep, result[0][0].begin(), result[0][0].end()); std::string oname = "floorplan"; if (result[0][0].size() > 10) { if (result[0][0][0] == 'P') oname += ".png"; else if (result[0][0][0] == -1) oname += ".jpg"; else if (result[0][0][0] == 'B') oname += ".bmp"; else if (result[0][0][0] == 'G') oname += ".gif"; } reply::add_header_attachment(&rep, oname); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-89'], 'message': 'Fixed possible SQL Injection Vulnerability (Thanks to Fabio Carretto!)'</s>
<s>[INST] Given the following code containing errors, provide 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 burl_normalize_2F_to_slash_fix (buffer *b, int qs, int i) { char * const s = b->ptr; const int blen = (int)buffer_string_length(b); const int used = qs < 0 ? blen : qs; int j = i; for (; i < used; ++i, ++j) { s[j] = s[i]; if (s[i] == '%' && s[i+1] == '2' && s[i+2] == 'F') { s[j] = '/'; i+=2; } } if (qs >= 0) { memmove(s+j, s+qs, blen - qs); j += blen - qs; } buffer_string_set_length(b, j); return qs; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': '[core] fix abort in http-parseopts (fixes #2945) fix abort in server.http-parseopts with url-path-2f-decode enabled (thx stze) x-ref: "Security - SIGABRT during GET request handling with url-path-2f-decode enabled" https://redmine.lighttpd.net/issues/2945'</s>
<s>[INST] Given the following code containing errors, provide 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 FontInfoScanner::scanFonts(XRef *xrefA, Dict *resDict, std::vector<FontInfo*> *fontsList) { GfxFontDict *gfxFontDict; GfxFont *font; // scan the fonts in this resource dictionary gfxFontDict = nullptr; const Object &fontObj = resDict->lookupNF("Font"); if (fontObj.isRef()) { Object obj2 = fontObj.fetch(xrefA); if (obj2.isDict()) { Ref r = fontObj.getRef(); gfxFontDict = new GfxFontDict(xrefA, &r, obj2.getDict()); } } else if (fontObj.isDict()) { gfxFontDict = new GfxFontDict(xrefA, nullptr, fontObj.getDict()); } if (gfxFontDict) { for (int i = 0; i < gfxFontDict->getNumFonts(); ++i) { if ((font = gfxFontDict->getFont(i))) { Ref fontRef = *font->getID(); // add this font to the list if not already found if (fonts.find(fontRef.num) == fonts.end()) { fontsList->push_back(new FontInfo(font, xrefA)); fonts.insert(fontRef.num); } } } delete gfxFontDict; } // recursively scan any resource dictionaries in objects in this // resource dictionary const char *resTypes[] = { "XObject", "Pattern" }; for (unsigned int resType = 0; resType < sizeof(resTypes) / sizeof(resTypes[0]); ++resType) { Object objDict = resDict->lookup(resTypes[resType]); if (objDict.isDict()) { for (int i = 0; i < objDict.dictGetLength(); ++i) { const Object &dictObjI = objDict.dictGetValNF(i); if (dictObjI.isRef()) { // check for an already-seen object const Ref r = dictObjI.getRef(); if (visitedObjects.find(r.num) != visitedObjects.end()) { continue; } visitedObjects.insert(r.num); } Object obj2 = dictObjI.fetch(xrefA); if (obj2.isStream()) { Object resObj = obj2.streamGetDict()->lookup("Resources"); if (resObj.isDict() && resObj.getDict() != resDict) { scanFonts(xrefA, resObj.getDict(), fontsList); } } } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-674'], 'message': 'FontInfoScanner::scanFonts Fix infinite loop in broken files Fixes #752'</s>
<s>[INST] Given the following code containing errors, provide 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 WriteTIFFImage(const ImageInfo *image_info, Image *image) { const char *mode, *option; CompressionType compression; EndianType endian_type; MagickBooleanType debug, status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t imageListLength; ssize_t y; TIFF *tiff; TIFFInfo tiff_info; uint16 bits_per_sample, compress_tag, endian, photometric, predictor; unsigned char *pixels; /* Open TIFF 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); (void) SetMagickThreadValue(tiff_exception,&image->exception); endian_type=UndefinedEndian; option=GetImageOption(image_info,"tiff:endian"); if (option != (const char *) NULL) { if (LocaleNCompare(option,"msb",3) == 0) endian_type=MSBEndian; if (LocaleNCompare(option,"lsb",3) == 0) endian_type=LSBEndian;; } switch (endian_type) { case LSBEndian: mode="wl"; break; case MSBEndian: mode="wb"; break; default: mode="w"; break; } #if defined(TIFF_VERSION_BIG) if (LocaleCompare(image_info->magick,"TIFF64") == 0) switch (endian_type) { case LSBEndian: mode="wl8"; break; case MSBEndian: mode="wb8"; break; default: mode="w8"; break; } #endif tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) return(MagickFalse); if (exception->severity > ErrorException) { TIFFClose(tiff); return(MagickFalse); } (void) DeleteImageProfile(image,"tiff:37724"); scene=0; debug=IsEventLogging(); (void) debug; imageListLength=GetImageListLength(image); do { /* Initialize TIFF fields. */ if ((image_info->type != UndefinedType) && (image_info->type != OptimizeType)) (void) SetImageType(image,image_info->type); compression=UndefinedCompression; if (image->compression != JPEGCompression) compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { (void) SetImageType(image,BilevelType); (void) SetImageDepth(image,1); break; } case JPEGCompression: { (void) SetImageStorageClass(image,DirectClass); (void) SetImageDepth(image,8); break; } default: break; } quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if ((image->storage_class != PseudoClass) && (image->depth >= 32) && (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"); } } if ((LocaleCompare(image_info->magick,"PTIF") == 0) && (GetPreviousImageInList(image) != (Image *) NULL)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE); if ((image->columns != (uint32) image->columns) || (image->rows != (uint32) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); (void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows); (void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns); switch (compression) { case FaxCompression: { compress_tag=COMPRESSION_CCITTFAX3; option=GetImageOption(image_info,"quantum:polarity"); if (option == (const char *) NULL) SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } case Group4Compression: { compress_tag=COMPRESSION_CCITTFAX4; option=GetImageOption(image_info,"quantum:polarity"); if (option == (const char *) NULL) SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } #if defined(COMPRESSION_JBIG) case JBIG1Compression: { compress_tag=COMPRESSION_JBIG; break; } #endif case JPEGCompression: { compress_tag=COMPRESSION_JPEG; break; } #if defined(COMPRESSION_LZMA) case LZMACompression: { compress_tag=COMPRESSION_LZMA; break; } #endif case LZWCompression: { compress_tag=COMPRESSION_LZW; break; } case RLECompression: { compress_tag=COMPRESSION_PACKBITS; break; } #if defined(COMPRESSION_WEBP) case WebPCompression: { compress_tag=COMPRESSION_WEBP; break; } #endif case ZipCompression: { compress_tag=COMPRESSION_ADOBE_DEFLATE; break; } #if defined(COMPRESSION_ZSTD) case ZstdCompression: { compress_tag=COMPRESSION_ZSTD; break; } #endif case NoCompression: default: { compress_tag=COMPRESSION_NONE; break; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; } #else switch (compress_tag) { #if defined(CCITT_SUPPORT) case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: #endif #if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT) case COMPRESSION_JPEG: #endif #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: #endif #if defined(LZW_SUPPORT) case COMPRESSION_LZW: #endif #if defined(PACKBITS_SUPPORT) case COMPRESSION_PACKBITS: #endif #if defined(ZIP_SUPPORT) case COMPRESSION_ADOBE_DEFLATE: #endif case COMPRESSION_NONE: break; default: { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; break; } } #endif if (image->colorspace == CMYKColorspace) { photometric=PHOTOMETRIC_SEPARATED; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4); (void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK); } else { /* Full color TIFF raster. */ if (image->colorspace == LabColorspace) { photometric=PHOTOMETRIC_CIELAB; EncodeLabImage(image,&image->exception); } else if (image->colorspace == YCbCrColorspace) { photometric=PHOTOMETRIC_YCBCR; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1); (void) SetImageStorageClass(image,DirectClass); (void) SetImageDepth(image,8); } else photometric=PHOTOMETRIC_RGB; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3); if ((image_info->type != TrueColorType) && (image_info->type != TrueColorMatteType)) { if ((image_info->type != PaletteType) && (SetImageGray(image,&image->exception) != MagickFalse)) { photometric=(uint16) (quantum_info->min_is_white != MagickFalse ? PHOTOMETRIC_MINISWHITE : PHOTOMETRIC_MINISBLACK); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); if ((image->depth == 1) && (image->matte == MagickFalse)) SetImageMonochrome(image,&image->exception); } else if (image->storage_class == PseudoClass) { size_t depth; /* Colormapped TIFF raster. */ (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); photometric=PHOTOMETRIC_PALETTE; depth=1; while ((GetQuantumRange(depth)+1) < image->colors) depth<<=1; status=SetQuantumDepth(image,quantum_info,depth); if (status == MagickFalse) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); } } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian); if ((compress_tag == COMPRESSION_CCITTFAX3) || (compress_tag == COMPRESSION_CCITTFAX4)) { if ((photometric != PHOTOMETRIC_MINISWHITE) && (photometric != PHOTOMETRIC_MINISBLACK)) { compress_tag=COMPRESSION_NONE; endian=FILLORDER_MSB2LSB; } } option=GetImageOption(image_info,"tiff:fill-order"); if (option != (const char *) NULL) { if (LocaleNCompare(option,"msb",3) == 0) endian=FILLORDER_MSB2LSB; if (LocaleNCompare(option,"lsb",3) == 0) endian=FILLORDER_LSB2MSB; } (void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag); (void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian); (void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth); if (image->matte != MagickFalse) { uint16 extra_samples, sample_info[1], samples_per_pixel; /* TIFF has a matte channel. */ extra_samples=1; sample_info[0]=EXTRASAMPLE_UNASSALPHA; option=GetImageOption(image_info,"tiff:alpha"); if (option != (const char *) NULL) { if (LocaleCompare(option,"associated") == 0) sample_info[0]=EXTRASAMPLE_ASSOCALPHA; else if (LocaleCompare(option,"unspecified") == 0) sample_info[0]=EXTRASAMPLE_UNSPECIFIED; } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1); (void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples, &sample_info); if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA) SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha); } (void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric); switch (quantum_info->format) { case FloatingPointQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP); (void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum); (void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum); break; } case SignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT); break; } case UnsignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT); break; } default: break; } (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); if (photometric == PHOTOMETRIC_RGB) if ((image_info->interlace == PlaneInterlace) || (image_info->interlace == PartitionInterlace)) (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE); predictor=0; switch (compress_tag) { case COMPRESSION_JPEG: { #if defined(JPEG_SUPPORT) if (image_info->quality != UndefinedCompressionQuality) (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality); (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW); if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) { const char *value; (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB); if (image->colorspace == YCbCrColorspace) { const char *sampling_factor; GeometryInfo geometry_info; MagickStatusType flags; sampling_factor=(const char *) NULL; value=GetImageProperty(image,"jpeg:sampling-factor"); if (value != (char *) NULL) { sampling_factor=value; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Input sampling-factors=%s",sampling_factor); } if (image_info->sampling_factor != (char *) NULL) sampling_factor=image_info->sampling_factor; if (sampling_factor != (const char *) NULL) { flags=ParseGeometry(sampling_factor,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16) geometry_info.rho,(uint16) geometry_info.sigma); } } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (bits_per_sample == 12) (void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT); #endif break; } case COMPRESSION_ADOBE_DEFLATE: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; (void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } case COMPRESSION_CCITTFAX3: { /* Byte-aligned EOL. */ (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4); break; } case COMPRESSION_CCITTFAX4: break; #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: { if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; (void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } #endif case COMPRESSION_LZW: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; break; } #if defined(WEBP_SUPPORT) && defined(COMPRESSION_WEBP) case COMPRESSION_WEBP: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; (void) TIFFSetField(tiff,TIFFTAG_WEBP_LEVEL,mage_info->quality); if (image_info->quality >= 100) (void) TIFFSetField(tiff,TIFFTAG_WEBP_LOSSLESS,1); break; } #endif #if defined(ZSTD_SUPPORT) && defined(COMPRESSION_ZSTD) case COMPRESSION_ZSTD: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; (void) TIFFSetField(tiff,TIFFTAG_ZSTD_LEVEL,22*image_info->quality/ 100.0); break; } #endif default: break; } option=GetImageOption(image_info,"tiff:predictor"); if (option != (const char * ) NULL) predictor=(size_t) strtol(option,(char **) NULL,10); if (predictor != 0) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,predictor); if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0)) { unsigned short units; /* Set image resolution. */ units=RESUNIT_NONE; if (image->units == PixelsPerInchResolution) units=RESUNIT_INCH; if (image->units == PixelsPerCentimeterResolution) units=RESUNIT_CENTIMETER; (void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units); (void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->x_resolution); (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->y_resolution); if ((image->page.x < 0) || (image->page.y < 0)) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"TIFF: negative image positions unsupported","%s", image->filename); if ((image->page.x > 0) && (image->x_resolution > 0.0)) { /* Set horizontal image position. */ (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/ image->x_resolution); } if ((image->page.y > 0) && (image->y_resolution > 0.0)) { /* Set vertical image position. */ (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/ image->y_resolution); } } if (image->chromaticity.white_point.x != 0.0) { float chromaticity[6]; /* Set image chromaticity. */ chromaticity[0]=(float) image->chromaticity.red_primary.x; chromaticity[1]=(float) image->chromaticity.red_primary.y; chromaticity[2]=(float) image->chromaticity.green_primary.x; chromaticity[3]=(float) image->chromaticity.green_primary.y; chromaticity[4]=(float) image->chromaticity.blue_primary.x; chromaticity[5]=(float) image->chromaticity.blue_primary.y; (void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity); chromaticity[0]=(float) image->chromaticity.white_point.x; chromaticity[1]=(float) image->chromaticity.white_point.y; (void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity); } if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (image_info->adjoin != MagickFalse) && (imageListLength > 1)) { (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); if (image->scene != 0) (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene, imageListLength); } if (image->orientation != UndefinedOrientation) (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation); else (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT); (void) TIFFSetProfiles(tiff,image); { uint16 page, pages; page=(uint16) scene; pages=(uint16) imageListLength; if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (image_info->adjoin != MagickFalse) && (pages > 1)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages); } (void) TIFFSetProperties(tiff,image_info,image); DisableMSCWarning(4127) if (0) RestoreMSCWarning (void) TIFFSetEXIFProperties(tiff,image); /* Write image scanlines. */ if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); quantum_info->endian=LSBEndian; pixels=GetQuantumPixels(quantum_info); tiff_info.scanline=GetQuantumPixels(quantum_info); switch (photometric) { case PHOTOMETRIC_CIELAB: case PHOTOMETRIC_YCBCR: case PHOTOMETRIC_RGB: { /* RGB TIFF image. */ switch (image_info->interlace) { case NoInterlace: default: { quantum_type=RGBQuantum; if (image->matte != MagickFalse) quantum_type=RGBAQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: case PartitionInterlace: { /* Plane interlacing: RRRRRR...GGGGGG...BBBBBB... */ for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,100,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GreenQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,200,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,BlueQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,300,400); if (status == MagickFalse) break; } if (image->matte != MagickFalse) for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,AlphaQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,400,400); if (status == MagickFalse) break; } break; } } break; } case PHOTOMETRIC_SEPARATED: { /* CMYK TIFF image. */ quantum_type=CMYKQuantum; if (image->matte != MagickFalse) quantum_type=CMYKAQuantum; if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PHOTOMETRIC_PALETTE: { uint16 *blue, *green, *red; /* Colormapped TIFF image. */ red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red)); green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green)); blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue)); if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) || (blue == (uint16 *) NULL)) { if (red != (uint16 *) NULL) red=(uint16 *) RelinquishMagickMemory(red); if (green != (uint16 *) NULL) green=(uint16 *) RelinquishMagickMemory(green); if (blue != (uint16 *) NULL) blue=(uint16 *) RelinquishMagickMemory(blue); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } /* Initialize TIFF colormap. */ (void) memset(red,0,65536*sizeof(*red)); (void) memset(green,0,65536*sizeof(*green)); (void) memset(blue,0,65536*sizeof(*blue)); for (i=0; i < (ssize_t) image->colors; i++) { red[i]=ScaleQuantumToShort(image->colormap[i].red); green[i]=ScaleQuantumToShort(image->colormap[i].green); blue[i]=ScaleQuantumToShort(image->colormap[i].blue); } (void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue); red=(uint16 *) RelinquishMagickMemory(red); green=(uint16 *) RelinquishMagickMemory(green); blue=(uint16 *) RelinquishMagickMemory(blue); } default: { /* Convert PseudoClass packets to contiguous grayscale scanlines. */ quantum_type=IndexQuantum; if (image->matte != MagickFalse) { if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayAlphaQuantum; else quantum_type=IndexAlphaQuantum; } else if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } } quantum_info=DestroyQuantumInfo(quantum_info); if (image->colorspace == LabColorspace) DecodeLabImage(image,&image->exception); DestroyTIFFInfo(&tiff_info); DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) RestoreMSCWarning TIFFPrintDirectory(tiff,stdout,MagickFalse); (void) TIFFWriteDirectory(tiff); image=SyncNextImageInList(image); if (image == (Image *) NULL) break; status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); TIFFClose(tiff); return(MagickTrue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1532'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: brcmf_wowl_nd_results(struct brcmf_if *ifp, const struct brcmf_event_msg *e, void *data) { struct brcmf_cfg80211_info *cfg = ifp->drvr->config; struct wiphy *wiphy = cfg_to_wiphy(cfg); struct brcmf_pno_scanresults_le *pfn_result; struct brcmf_pno_net_info_le *netinfo; brcmf_dbg(SCAN, "Enter\n"); if (e->datalen < (sizeof(*pfn_result) + sizeof(*netinfo))) { brcmf_dbg(SCAN, "Event data to small. Ignore\n"); return 0; } pfn_result = (struct brcmf_pno_scanresults_le *)data; if (e->event_code == BRCMF_E_PFN_NET_LOST) { brcmf_dbg(SCAN, "PFN NET LOST event. Ignore\n"); return 0; } if (le32_to_cpu(pfn_result->count) < 1) { bphy_err(wiphy, "Invalid result count, expected 1 (%d)\n", le32_to_cpu(pfn_result->count)); return -EINVAL; } netinfo = brcmf_get_netinfo_array(pfn_result); memcpy(cfg->wowl.nd->ssid.ssid, netinfo->SSID, netinfo->SSID_len); cfg->wowl.nd->ssid.ssid_len = netinfo->SSID_len; cfg->wowl.nd->n_channels = 1; cfg->wowl.nd->channels[0] = ieee80211_channel_to_frequency(netinfo->channel, netinfo->channel <= CH_MAX_2G_CHANNEL ? NL80211_BAND_2GHZ : NL80211_BAND_5GHZ); cfg->wowl.nd_info->n_matches = 1; cfg->wowl.nd_info->matches[0] = cfg->wowl.nd; /* Inform (the resume task) that the net detect information was recvd */ cfg->wowl.nd_data_completed = true; wake_up(&cfg->wowl.nd_data_wait); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'brcmfmac: assure SSID length from firmware is limited The SSID length as received from firmware should not exceed IEEE80211_MAX_SSID_LEN as that would result in heap overflow. Reviewed-by: Hante Meuleman <[email protected]> Reviewed-by: Pieter-Paul Giesberts <[email protected]> Reviewed-by: Franky Lin <[email protected]> Signed-off-by: Arend van Spriel <[email protected]> Signed-off-by: Kalle Valo <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: find_lively_task_by_vpid(pid_t vpid) { struct task_struct *task; int err; rcu_read_lock(); if (!vpid) task = current; else task = find_task_by_vpid(vpid); if (task) get_task_struct(task); rcu_read_unlock(); if (!task) return ERR_PTR(-ESRCH); /* Reuse ptrace permission checks for now. */ err = -EACCES; if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) goto errout; return task; errout: put_task_struct(task); return ERR_PTR(err); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-667'], 'message': 'perf/core: Fix perf_event_open() vs. execve() race Jann reported that the ptrace_may_access() check in find_lively_task_by_vpid() is racy against exec(). Specifically: perf_event_open() execve() ptrace_may_access() commit_creds() ... if (get_dumpable() != SUID_DUMP_USER) perf_event_exit_task(); perf_install_in_context() would result in installing a counter across the creds boundary. Fix this by wrapping lots of perf_event_open() in cred_guard_mutex. This should be fine as perf_event_exit_task() is already called with cred_guard_mutex held, so all perf locks already nest inside it. Reported-by: Jann Horn <[email protected]> Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Alexander Shishkin <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Stephane Eranian <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: Vince Weaver <[email protected]> Signed-off-by: Ingo Molnar <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void brcmf_rx_frame(struct device *dev, struct sk_buff *skb, bool handle_event) { struct brcmf_if *ifp; struct brcmf_bus *bus_if = dev_get_drvdata(dev); struct brcmf_pub *drvr = bus_if->drvr; brcmf_dbg(DATA, "Enter: %s: rxp=%p\n", dev_name(dev), skb); if (brcmf_rx_hdrpull(drvr, skb, &ifp)) return; if (brcmf_proto_is_reorder_skb(skb)) { brcmf_proto_rxreorder(ifp, skb); } else { /* Process special event packets */ if (handle_event) brcmf_fweh_process_skb(ifp->drvr, skb); brcmf_netif_rx(ifp, skb); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'brcmfmac: add subtype check for event handling in data path For USB there is no separate channel being used to pass events from firmware to the host driver and as such are passed over the data path. In order to detect mock event messages an additional check is needed on event subtype. This check is added conditionally using unlikely() keyword. Reviewed-by: Hante Meuleman <[email protected]> Reviewed-by: Pieter-Paul Giesberts <[email protected]> Reviewed-by: Franky Lin <[email protected]> Signed-off-by: Arend van Spriel <[email protected]> Signed-off-by: Kalle Valo <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void brcmf_rx_event(struct device *dev, struct sk_buff *skb) { struct brcmf_if *ifp; struct brcmf_bus *bus_if = dev_get_drvdata(dev); struct brcmf_pub *drvr = bus_if->drvr; brcmf_dbg(EVENT, "Enter: %s: rxp=%p\n", dev_name(dev), skb); if (brcmf_rx_hdrpull(drvr, skb, &ifp)) return; brcmf_fweh_process_skb(ifp->drvr, skb); brcmu_pkt_buf_free_skb(skb); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'brcmfmac: add subtype check for event handling in data path For USB there is no separate channel being used to pass events from firmware to the host driver and as such are passed over the data path. In order to detect mock event messages an additional check is needed on event subtype. This check is added conditionally using unlikely() keyword. Reviewed-by: Hante Meuleman <[email protected]> Reviewed-by: Pieter-Paul Giesberts <[email protected]> Reviewed-by: Franky Lin <[email protected]> Signed-off-by: Arend van Spriel <[email protected]> Signed-off-by: Kalle Valo <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: plugin_init (Ekiga::KickStart& kickstart) { #ifdef DEBUG // should make it easier to test ekiga without installing gchar* path = g_build_path (G_DIR_SEPARATOR_S, g_get_tmp_dir (), "ekiga_debug_plugins", NULL); plugin_parse_directory (kickstart, path); g_free (path); #else plugin_parse_directory (kickstart, EKIGA_PLUGIN_DIR); #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-94'], 'message': 'Fixed plugin load I have no idea when I broke this...'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void exif_process_COM (image_info_type *image_info, char *value, size_t length) { exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_STRING, length-2, value+2); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed bug #77831 - Heap-buffer-overflow in exif_iif_add_value in EXIF'</s>
<s>[INST] Given the following code containing errors, provide 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 exif_process_CME (image_info_type *image_info, char *value, size_t length) { if (length>3) { switch(value[2]) { case 0: exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_UNDEFINED, length, value); break; case 1: exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_STRING, length, value); break; default: php_error_docref(NULL, E_NOTICE, "Undefined JPEG2000 comment encoding"); break; } } else { exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_UNDEFINED, 0, NULL); php_error_docref(NULL, E_NOTICE, "JPEG2000 comment section too small"); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed bug #77831 - Heap-buffer-overflow in exif_iif_add_value in EXIF'</s>
<s>[INST] Given the following code containing errors, provide 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 exif_process_APP12(image_info_type *ImageInfo, char *buffer, size_t length) { size_t l1, l2=0; if ((l1 = php_strnlen(buffer+2, length-2)) > 0) { exif_iif_add_tag(ImageInfo, SECTION_APP12, "Company", TAG_NONE, TAG_FMT_STRING, l1, buffer+2); if (length > 2+l1+1) { l2 = php_strnlen(buffer+2+l1+1, length-2-l1-1); exif_iif_add_tag(ImageInfo, SECTION_APP12, "Info", TAG_NONE, TAG_FMT_STRING, l2, buffer+2+l1+1); } } #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process section APP12 with l1=%d, l2=%d done", l1, l2); #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed bug #77831 - Heap-buffer-overflow in exif_iif_add_value in EXIF'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(exif_read_data) { zend_string *z_sections_needed = NULL; zend_bool sub_arrays = 0, read_thumbnail = 0, read_all = 0; zval *stream; int i, ret, sections_needed = 0; image_info_type ImageInfo; char tmp[64], *sections_str, *s; /* Parse arguments */ ZEND_PARSE_PARAMETERS_START(1, 4) Z_PARAM_ZVAL(stream) Z_PARAM_OPTIONAL Z_PARAM_STR(z_sections_needed) Z_PARAM_BOOL(sub_arrays) Z_PARAM_BOOL(read_thumbnail) ZEND_PARSE_PARAMETERS_END(); memset(&ImageInfo, 0, sizeof(ImageInfo)); if (z_sections_needed) { spprintf(&sections_str, 0, ",%s,", ZSTR_VAL(z_sections_needed)); /* sections_str DOES start with , and SPACES are NOT allowed in names */ s = sections_str; while (*++s) { if (*s == ' ') { *s = ','; } } for (i = 0; i < SECTION_COUNT; i++) { snprintf(tmp, sizeof(tmp), ",%s,", exif_get_sectionname(i)); if (strstr(sections_str, tmp)) { sections_needed |= 1<<i; } } EFREE_IF(sections_str); /* now see what we need */ #ifdef EXIF_DEBUG sections_str = exif_get_sectionlist(sections_needed); if (!sections_str) { RETURN_FALSE; } exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Sections needed: %s", sections_str[0] ? sections_str : "None"); EFREE_IF(sections_str); #endif } if (Z_TYPE_P(stream) == IS_RESOURCE) { php_stream *p_stream = NULL; php_stream_from_res(p_stream, Z_RES_P(stream)); ret = exif_read_from_stream(&ImageInfo, p_stream, read_thumbnail, read_all); } else { convert_to_string(stream); if (!Z_STRLEN_P(stream)) { exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_WARNING, "Filename cannot be empty"); RETURN_FALSE; } ret = exif_read_from_file(&ImageInfo, Z_STRVAL_P(stream), read_thumbnail, read_all); } sections_str = exif_get_sectionlist(ImageInfo.sections_found); #ifdef EXIF_DEBUG if (sections_str) { exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Sections found: %s", sections_str[0] ? sections_str : "None"); } #endif ImageInfo.sections_found |= FOUND_COMPUTED|FOUND_FILE;/* do not inform about in debug*/ if (ret == FALSE || (sections_needed && !(sections_needed&ImageInfo.sections_found))) { /* array_init must be checked at last! otherwise the array must be freed if a later test fails. */ exif_discard_imageinfo(&ImageInfo); EFREE_IF(sections_str); RETURN_FALSE; } array_init(return_value); #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Generate section FILE"); #endif /* now we can add our information */ exif_iif_add_str(&ImageInfo, SECTION_FILE, "FileName", ImageInfo.FileName); exif_iif_add_int(&ImageInfo, SECTION_FILE, "FileDateTime", ImageInfo.FileDateTime); exif_iif_add_int(&ImageInfo, SECTION_FILE, "FileSize", ImageInfo.FileSize); exif_iif_add_int(&ImageInfo, SECTION_FILE, "FileType", ImageInfo.FileType); exif_iif_add_str(&ImageInfo, SECTION_FILE, "MimeType", (char*)php_image_type_to_mime_type(ImageInfo.FileType)); exif_iif_add_str(&ImageInfo, SECTION_FILE, "SectionsFound", sections_str ? sections_str : "NONE"); #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Generate section COMPUTED"); #endif if (ImageInfo.Width>0 && ImageInfo.Height>0) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "html" , "width=\"%d\" height=\"%d\"", ImageInfo.Width, ImageInfo.Height); exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Height", ImageInfo.Height); exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Width", ImageInfo.Width); } exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "IsColor", ImageInfo.IsColor); if (ImageInfo.motorola_intel != -1) { exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "ByteOrderMotorola", ImageInfo.motorola_intel); } if (ImageInfo.FocalLength) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "FocalLength", "%4.1Fmm", ImageInfo.FocalLength); if(ImageInfo.CCDWidth) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "35mmFocalLength", "%dmm", (int)(ImageInfo.FocalLength/ImageInfo.CCDWidth*35+0.5)); } } if(ImageInfo.CCDWidth) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "CCDWidth", "%dmm", (int)ImageInfo.CCDWidth); } if(ImageInfo.ExposureTime>0) { if(ImageInfo.ExposureTime <= 0.5) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "ExposureTime", "%0.3F s (1/%d)", ImageInfo.ExposureTime, (int)(0.5 + 1/ImageInfo.ExposureTime)); } else { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "ExposureTime", "%0.3F s", ImageInfo.ExposureTime); } } if(ImageInfo.ApertureFNumber) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "ApertureFNumber", "f/%.1F", ImageInfo.ApertureFNumber); } if(ImageInfo.Distance) { if(ImageInfo.Distance<0) { exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "FocusDistance", "Infinite"); } else { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "FocusDistance", "%0.2Fm", ImageInfo.Distance); } } if (ImageInfo.UserComment) { exif_iif_add_buffer(&ImageInfo, SECTION_COMPUTED, "UserComment", ImageInfo.UserCommentLength, ImageInfo.UserComment); if (ImageInfo.UserCommentEncoding && strlen(ImageInfo.UserCommentEncoding)) { exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "UserCommentEncoding", ImageInfo.UserCommentEncoding); } } exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Copyright", ImageInfo.Copyright); exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Copyright.Photographer", ImageInfo.CopyrightPhotographer); exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Copyright.Editor", ImageInfo.CopyrightEditor); for (i=0; i<ImageInfo.xp_fields.count; i++) { exif_iif_add_str(&ImageInfo, SECTION_WINXP, exif_get_tagname(ImageInfo.xp_fields.list[i].tag, NULL, 0, exif_get_tag_table(SECTION_WINXP)), ImageInfo.xp_fields.list[i].value); } if (ImageInfo.Thumbnail.size) { if (read_thumbnail) { /* not exif_iif_add_str : this is a buffer */ exif_iif_add_tag(&ImageInfo, SECTION_THUMBNAIL, "THUMBNAIL", TAG_NONE, TAG_FMT_UNDEFINED, ImageInfo.Thumbnail.size, ImageInfo.Thumbnail.data); } if (!ImageInfo.Thumbnail.width || !ImageInfo.Thumbnail.height) { /* try to evaluate if thumbnail data is present */ exif_scan_thumbnail(&ImageInfo); } exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Thumbnail.FileType", ImageInfo.Thumbnail.filetype); exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Thumbnail.MimeType", (char*)php_image_type_to_mime_type(ImageInfo.Thumbnail.filetype)); } if (ImageInfo.Thumbnail.width && ImageInfo.Thumbnail.height) { exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Thumbnail.Height", ImageInfo.Thumbnail.height); exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Thumbnail.Width", ImageInfo.Thumbnail.width); } EFREE_IF(sections_str); #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Adding image infos"); #endif add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_FILE ); add_assoc_image_info(return_value, 1, &ImageInfo, SECTION_COMPUTED ); add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_ANY_TAG ); add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_IFD0 ); add_assoc_image_info(return_value, 1, &ImageInfo, SECTION_THUMBNAIL ); add_assoc_image_info(return_value, 1, &ImageInfo, SECTION_COMMENT ); add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_EXIF ); add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_GPS ); add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_INTEROP ); add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_FPIX ); add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_APP12 ); add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_WINXP ); add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_MAKERNOTE ); #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Discarding info"); #endif exif_discard_imageinfo(&ImageInfo); #ifdef EXIF_DEBUG php_error_docref1(NULL, (Z_TYPE_P(stream) == IS_RESOURCE ? "<stream>" : Z_STRVAL_P(stream)), E_NOTICE, "Done"); #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed bug #77831 - Heap-buffer-overflow in exif_iif_add_value in EXIF'</s>
<s>[INST] Given the following code containing errors, provide 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 exif_process_IFD_in_MAKERNOTE(image_info_type *ImageInfo, char * value_ptr, int value_len, char *offset_base, size_t IFDlength, size_t displacement) { size_t i; int de, section_index = SECTION_MAKERNOTE; int NumDirEntries, old_motorola_intel, offset_diff; const maker_note_type *maker_note; char *dir_start; int data_len; for (i=0; i<=sizeof(maker_note_array)/sizeof(maker_note_type); i++) { if (i==sizeof(maker_note_array)/sizeof(maker_note_type)) { #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "No maker note data found. Detected maker: %s (length = %d)", ImageInfo->make, strlen(ImageInfo->make)); #endif /* unknown manufacturer, not an error, use it as a string */ return TRUE; } maker_note = maker_note_array+i; /*exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "check (%s,%s)", maker_note->make?maker_note->make:"", maker_note->model?maker_note->model:"");*/ if (maker_note->make && (!ImageInfo->make || strcmp(maker_note->make, ImageInfo->make))) continue; if (maker_note->model && (!ImageInfo->model || strcmp(maker_note->model, ImageInfo->model))) continue; if (maker_note->id_string && strncmp(maker_note->id_string, value_ptr, maker_note->id_string_len)) continue; break; } if (value_len < 2 || maker_note->offset >= value_len - 1) { /* Do not go past the value end */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "IFD data too short: 0x%04X offset 0x%04X", value_len, maker_note->offset); return FALSE; } dir_start = value_ptr + maker_note->offset; #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process %s @x%04X + 0x%04X=%d: %s", exif_get_sectionname(section_index), (int)dir_start-(int)offset_base+maker_note->offset+displacement, value_len, value_len, exif_char_dump(value_ptr, value_len, (int)dir_start-(int)offset_base+maker_note->offset+displacement)); #endif ImageInfo->sections_found |= FOUND_MAKERNOTE; old_motorola_intel = ImageInfo->motorola_intel; switch (maker_note->byte_order) { case MN_ORDER_INTEL: ImageInfo->motorola_intel = 0; break; case MN_ORDER_MOTOROLA: ImageInfo->motorola_intel = 1; break; default: case MN_ORDER_NORMAL: break; } NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel); switch (maker_note->offset_mode) { case MN_OFFSET_MAKER: offset_base = value_ptr; data_len = value_len; break; case MN_OFFSET_GUESS: if (maker_note->offset + 10 + 4 >= value_len) { /* Can not read dir_start+10 since it's beyond value end */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "IFD data too short: 0x%04X", value_len); return FALSE; } offset_diff = 2 + NumDirEntries*12 + 4 - php_ifd_get32u(dir_start+10, ImageInfo->motorola_intel); #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Using automatic offset correction: 0x%04X", ((int)dir_start-(int)offset_base+maker_note->offset+displacement) + offset_diff); #endif if (offset_diff < 0 || offset_diff >= value_len ) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "IFD data bad offset: 0x%04X length 0x%04X", offset_diff, value_len); return FALSE; } offset_base = value_ptr + offset_diff; data_len = value_len - offset_diff; break; default: case MN_OFFSET_NORMAL: data_len = value_len; break; } if ((2+NumDirEntries*12) > value_len) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD size: 2 + 0x%04X*12 = 0x%04X > 0x%04X", NumDirEntries, 2+NumDirEntries*12, value_len); return FALSE; } for (de=0;de<NumDirEntries;de++) { if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de, offset_base, data_len, displacement, section_index, 0, maker_note->tag_table)) { return FALSE; } } ImageInfo->motorola_intel = old_motorola_intel; /* NextDirOffset (must be NULL) = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel);*/ #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Subsection %s done", exif_get_sectionname(SECTION_MAKERNOTE)); #endif return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #77753 - Heap-buffer-overflow in php_ifd_get32s'</s>
<s>[INST] Given the following code containing errors, provide 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 exif_process_IFD_in_MAKERNOTE(image_info_type *ImageInfo, char * value_ptr, int value_len, char *offset_base, size_t IFDlength, size_t displacement) { size_t i; int de, section_index = SECTION_MAKERNOTE; int NumDirEntries, old_motorola_intel; #ifdef KALLE_0 int offset_diff; #endif const maker_note_type *maker_note; char *dir_start; int data_len; for (i=0; i<=sizeof(maker_note_array)/sizeof(maker_note_type); i++) { if (i==sizeof(maker_note_array)/sizeof(maker_note_type)) { #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "No maker note data found. Detected maker: %s (length = %d)", ImageInfo->make, strlen(ImageInfo->make)); #endif /* unknown manufacturer, not an error, use it as a string */ return TRUE; } maker_note = maker_note_array+i; /*exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "check (%s,%s)", maker_note->make?maker_note->make:"", maker_note->model?maker_note->model:"");*/ if (maker_note->make && (!ImageInfo->make || strcmp(maker_note->make, ImageInfo->make))) continue; if (maker_note->model && (!ImageInfo->model || strcmp(maker_note->model, ImageInfo->model))) continue; if (maker_note->id_string && strncmp(maker_note->id_string, value_ptr, maker_note->id_string_len)) continue; break; } if (value_len < 2 || maker_note->offset >= value_len - 1) { /* Do not go past the value end */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "IFD data too short: 0x%04X offset 0x%04X", value_len, maker_note->offset); return FALSE; } dir_start = value_ptr + maker_note->offset; #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process %s @x%04X + 0x%04X=%d: %s", exif_get_sectionname(section_index), (int)dir_start-(int)offset_base+maker_note->offset+displacement, value_len, value_len, exif_char_dump(value_ptr, value_len, (int)dir_start-(int)offset_base+maker_note->offset+displacement)); #endif ImageInfo->sections_found |= FOUND_MAKERNOTE; old_motorola_intel = ImageInfo->motorola_intel; switch (maker_note->byte_order) { case MN_ORDER_INTEL: ImageInfo->motorola_intel = 0; break; case MN_ORDER_MOTOROLA: ImageInfo->motorola_intel = 1; break; default: case MN_ORDER_NORMAL: break; } NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel); switch (maker_note->offset_mode) { case MN_OFFSET_MAKER: offset_base = value_ptr; data_len = value_len; break; #ifdef KALLE_0 case MN_OFFSET_GUESS: if (maker_note->offset + 10 + 4 >= value_len) { /* Can not read dir_start+10 since it's beyond value end */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "IFD data too short: 0x%04X", value_len); return FALSE; } offset_diff = 2 + NumDirEntries*12 + 4 - php_ifd_get32u(dir_start+10, ImageInfo->motorola_intel); #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Using automatic offset correction: 0x%04X", ((int)dir_start-(int)offset_base+maker_note->offset+displacement) + offset_diff); #endif if (offset_diff < 0 || offset_diff >= value_len ) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "IFD data bad offset: 0x%04X length 0x%04X", offset_diff, value_len); return FALSE; } offset_base = value_ptr + offset_diff; data_len = value_len - offset_diff; break; #endif default: case MN_OFFSET_NORMAL: data_len = value_len; break; } if ((2+NumDirEntries*12) > value_len) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD size: 2 + 0x%04X*12 = 0x%04X > 0x%04X", NumDirEntries, 2+NumDirEntries*12, value_len); return FALSE; } for (de=0;de<NumDirEntries;de++) { if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de, offset_base, data_len, displacement, section_index, 0, maker_note->tag_table)) { return FALSE; } } ImageInfo->motorola_intel = old_motorola_intel; /* NextDirOffset (must be NULL) = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel);*/ #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Subsection %s done", exif_get_sectionname(SECTION_MAKERNOTE)); #endif return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #77753 - Heap-buffer-overflow in php_ifd_get32s'</s>
<s>[INST] Given the following code containing errors, provide 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 format8BIM(Image *ifile, Image *ofile) { char temp[MagickPathExtent]; unsigned int foundOSType; int ID, resCount, i, c; ssize_t count; unsigned char *PString, *str; resCount=0; foundOSType=0; /* found the OSType */ (void) foundOSType; c=ReadBlobByte(ifile); while (c != EOF) { if (c == '8') { unsigned char buffer[5]; buffer[0]=(unsigned char) c; for (i=1; i<4; i++) { c=ReadBlobByte(ifile); if (c == EOF) return(-1); buffer[i] = (unsigned char) c; } buffer[4]=0; if (strcmp((const char *)buffer, "8BIM") == 0) foundOSType=1; else continue; } else { c=ReadBlobByte(ifile); continue; } /* We found the OSType (8BIM) and now grab the ID, PString, and Size fields. */ ID=ReadBlobMSBSignedShort(ifile); if (ID < 0) return(-1); { unsigned char plen; c=ReadBlobByte(ifile); if (c == EOF) return(-1); plen = (unsigned char) c; PString=(unsigned char *) AcquireQuantumMemory((size_t) (plen+ MagickPathExtent),sizeof(*PString)); if (PString == (unsigned char *) NULL) return 0; for (i=0; i<plen; i++) { c=ReadBlobByte(ifile); if (c == EOF) { PString=(unsigned char *) RelinquishMagickMemory(PString); return -1; } PString[i] = (unsigned char) c; } PString[ plen ] = 0; if ((plen & 0x01) == 0) { c=ReadBlobByte(ifile); if (c == EOF) { PString=(unsigned char *) RelinquishMagickMemory(PString); return -1; } } } count=(ssize_t) ReadBlobMSBSignedLong(ifile); if ((count < 0) || (count > GetBlobSize(ifile))) { PString=(unsigned char *) RelinquishMagickMemory(PString); return -1; } /* make a buffer to hold the data and snag it from the input stream */ str=(unsigned char *) AcquireQuantumMemory((size_t) count,sizeof(*str)); if (str == (unsigned char *) NULL) { PString=(unsigned char *) RelinquishMagickMemory(PString); return 0; } for (i=0; i < (ssize_t) count; i++) { c=ReadBlobByte(ifile); if (c == EOF) { str=(unsigned char *) RelinquishMagickMemory(str); PString=(unsigned char *) RelinquishMagickMemory(PString); return -1; } str[i]=(unsigned char) c; } /* we currently skip thumbnails, since it does not make * any sense preserving them in a real world application */ if (ID != THUMBNAIL_ID) { /* now finish up by formatting this binary data into * ASCII equivalent */ if (strlen((const char *)PString) > 0) (void) FormatLocaleString(temp,MagickPathExtent,"8BIM#%d#%s=",ID, PString); else (void) FormatLocaleString(temp,MagickPathExtent,"8BIM#%d=",ID); (void) WriteBlobString(ofile,temp); if (ID == IPTC_ID) { formatString(ofile, "IPTC", 4); formatIPTCfromBuffer(ofile, (char *)str, (ssize_t) count); } else formatString(ofile, (char *)str, (ssize_t) count); } str=(unsigned char *) RelinquishMagickMemory(str); PString=(unsigned char *) RelinquishMagickMemory(PString); resCount++; c=ReadBlobByte(ifile); } return resCount; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-119', 'CWE-193'], 'message': '...'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void setup_private_mount(const char *snap_name) { uid_t uid = getuid(); gid_t gid = getgid(); char tmpdir[MAX_BUF] = { 0 }; // Create a 0700 base directory, this is the base dir that is // protected from other users. // // Under that basedir, we put a 1777 /tmp dir that is then bind // mounted for the applications to use sc_must_snprintf(tmpdir, sizeof(tmpdir), "/tmp/snap.%s_XXXXXX", snap_name); if (mkdtemp(tmpdir) == NULL) { die("cannot create temporary directory essential for private /tmp"); } // now we create a 1777 /tmp inside our private dir mode_t old_mask = umask(0); char *d = sc_strdup(tmpdir); sc_must_snprintf(tmpdir, sizeof(tmpdir), "%s/tmp", d); free(d); if (mkdir(tmpdir, 01777) != 0) { die("cannot create temporary directory for private /tmp"); } umask(old_mask); // chdir to '/' since the mount won't apply to the current directory char *pwd = get_current_dir_name(); if (pwd == NULL) die("cannot get current working directory"); if (chdir("/") != 0) die("cannot change directory to '/'"); // MS_BIND is there from linux 2.4 sc_do_mount(tmpdir, "/tmp", NULL, MS_BIND, NULL); // MS_PRIVATE needs linux > 2.6.11 sc_do_mount("none", "/tmp", NULL, MS_PRIVATE, NULL); // do the chown after the bind mount to avoid potential shenanigans if (chown("/tmp/", uid, gid) < 0) { die("cannot change ownership of /tmp"); } // chdir to original directory if (chdir(pwd) != 0) die("cannot change current working directory to the original directory"); free(pwd); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-703'], 'message': 'cmd/snap-confine: chown private /tmp parent to root.root When snap-confine creates a private /tmp directory for a given snap it first creates a temporary directory in /tmp/ named after the snap, along with a random name. Inside that directory it creates a /tmp directory with permissions appropriate for a future /tmp, namely 1777. Up until recently the that directory was owned by the user who first invoked snap-confine. Since the directory is reused by all the users on the system this logic makes no sense. This patch changes the related logic so that the private /tmp directory is owned by root, just like the real one. Signed-off-by: Zygmunt Krynicki <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info, Image *image) { const char *mode, *option; CompressionType compression; EndianType endian_type; MagickBooleanType debug, status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t imageListLength; ssize_t y; TIFF *tiff; TIFFInfo tiff_info; uint16 bits_per_sample, compress_tag, endian, photometric, predictor; unsigned char *pixels; /* Open TIFF 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); (void) SetMagickThreadValue(tiff_exception,&image->exception); endian_type=UndefinedEndian; option=GetImageOption(image_info,"tiff:endian"); if (option != (const char *) NULL) { if (LocaleNCompare(option,"msb",3) == 0) endian_type=MSBEndian; if (LocaleNCompare(option,"lsb",3) == 0) endian_type=LSBEndian;; } switch (endian_type) { case LSBEndian: mode="wl"; break; case MSBEndian: mode="wb"; break; default: mode="w"; break; } #if defined(TIFF_VERSION_BIG) if (LocaleCompare(image_info->magick,"TIFF64") == 0) switch (endian_type) { case LSBEndian: mode="wl8"; break; case MSBEndian: mode="wb8"; break; default: mode="w8"; break; } #endif tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) return(MagickFalse); if (image->exception.severity > ErrorException) { TIFFClose(tiff); return(MagickFalse); } (void) DeleteImageProfile(image,"tiff:37724"); scene=0; debug=IsEventLogging(); (void) debug; imageListLength=GetImageListLength(image); do { /* Initialize TIFF fields. */ if ((image_info->type != UndefinedType) && (image_info->type != OptimizeType)) (void) SetImageType(image,image_info->type); compression=UndefinedCompression; if (image->compression != JPEGCompression) compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { (void) SetImageType(image,BilevelType); (void) SetImageDepth(image,1); break; } case JPEGCompression: { (void) SetImageStorageClass(image,DirectClass); (void) SetImageDepth(image,8); break; } default: break; } quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if ((image->storage_class != PseudoClass) && (image->depth >= 32) && (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"); } } if ((LocaleCompare(image_info->magick,"PTIF") == 0) && (GetPreviousImageInList(image) != (Image *) NULL)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE); if ((image->columns != (uint32) image->columns) || (image->rows != (uint32) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); (void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows); (void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns); switch (compression) { case FaxCompression: { compress_tag=COMPRESSION_CCITTFAX3; option=GetImageOption(image_info,"quantum:polarity"); if (option == (const char *) NULL) SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } case Group4Compression: { compress_tag=COMPRESSION_CCITTFAX4; option=GetImageOption(image_info,"quantum:polarity"); if (option == (const char *) NULL) SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } #if defined(COMPRESSION_JBIG) case JBIG1Compression: { compress_tag=COMPRESSION_JBIG; break; } #endif case JPEGCompression: { compress_tag=COMPRESSION_JPEG; break; } #if defined(COMPRESSION_LZMA) case LZMACompression: { compress_tag=COMPRESSION_LZMA; break; } #endif case LZWCompression: { compress_tag=COMPRESSION_LZW; break; } case RLECompression: { compress_tag=COMPRESSION_PACKBITS; break; } #if defined(COMPRESSION_WEBP) case WebPCompression: { compress_tag=COMPRESSION_WEBP; break; } #endif case ZipCompression: { compress_tag=COMPRESSION_ADOBE_DEFLATE; break; } #if defined(COMPRESSION_ZSTD) case ZstdCompression: { compress_tag=COMPRESSION_ZSTD; break; } #endif case NoCompression: default: { compress_tag=COMPRESSION_NONE; break; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; } #else switch (compress_tag) { #if defined(CCITT_SUPPORT) case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: #endif #if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT) case COMPRESSION_JPEG: #endif #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: #endif #if defined(LZW_SUPPORT) case COMPRESSION_LZW: #endif #if defined(PACKBITS_SUPPORT) case COMPRESSION_PACKBITS: #endif #if defined(ZIP_SUPPORT) case COMPRESSION_ADOBE_DEFLATE: #endif case COMPRESSION_NONE: break; default: { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; break; } } #endif if (image->colorspace == CMYKColorspace) { photometric=PHOTOMETRIC_SEPARATED; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4); (void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK); } else { /* Full color TIFF raster. */ if (image->colorspace == LabColorspace) { photometric=PHOTOMETRIC_CIELAB; EncodeLabImage(image,&image->exception); } else if (image->colorspace == YCbCrColorspace) { photometric=PHOTOMETRIC_YCBCR; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1); (void) SetImageStorageClass(image,DirectClass); (void) SetImageDepth(image,8); } else photometric=PHOTOMETRIC_RGB; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3); if ((image_info->type != TrueColorType) && (image_info->type != TrueColorMatteType)) { if ((image_info->type != PaletteType) && (SetImageGray(image,&image->exception) != MagickFalse)) { photometric=(uint16) (quantum_info->min_is_white != MagickFalse ? PHOTOMETRIC_MINISWHITE : PHOTOMETRIC_MINISBLACK); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); if ((image->depth == 1) && (image->matte == MagickFalse)) SetImageMonochrome(image,&image->exception); } else if (image->storage_class == PseudoClass) { size_t depth; /* Colormapped TIFF raster. */ (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); photometric=PHOTOMETRIC_PALETTE; depth=1; while ((GetQuantumRange(depth)+1) < image->colors) depth<<=1; status=SetQuantumDepth(image,quantum_info,depth); if (status == MagickFalse) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); } } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian); if ((compress_tag == COMPRESSION_CCITTFAX3) || (compress_tag == COMPRESSION_CCITTFAX4)) { if ((photometric != PHOTOMETRIC_MINISWHITE) && (photometric != PHOTOMETRIC_MINISBLACK)) { compress_tag=COMPRESSION_NONE; endian=FILLORDER_MSB2LSB; } } option=GetImageOption(image_info,"tiff:fill-order"); if (option != (const char *) NULL) { if (LocaleNCompare(option,"msb",3) == 0) endian=FILLORDER_MSB2LSB; if (LocaleNCompare(option,"lsb",3) == 0) endian=FILLORDER_LSB2MSB; } (void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag); (void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian); (void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth); if (image->matte != MagickFalse) { uint16 extra_samples, sample_info[1], samples_per_pixel; /* TIFF has a matte channel. */ extra_samples=1; sample_info[0]=EXTRASAMPLE_UNASSALPHA; option=GetImageOption(image_info,"tiff:alpha"); if (option != (const char *) NULL) { if (LocaleCompare(option,"associated") == 0) sample_info[0]=EXTRASAMPLE_ASSOCALPHA; else if (LocaleCompare(option,"unspecified") == 0) sample_info[0]=EXTRASAMPLE_UNSPECIFIED; } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1); (void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples, &sample_info); if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA) SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha); } (void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric); switch (quantum_info->format) { case FloatingPointQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP); (void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum); (void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum); break; } case SignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT); break; } case UnsignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT); break; } default: break; } (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); if (photometric == PHOTOMETRIC_RGB) if ((image_info->interlace == PlaneInterlace) || (image_info->interlace == PartitionInterlace)) (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE); predictor=0; switch (compress_tag) { case COMPRESSION_JPEG: { #if defined(JPEG_SUPPORT) if (image_info->quality != UndefinedCompressionQuality) (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality); (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW); if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) { const char *value; (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB); if (image->colorspace == YCbCrColorspace) { const char *sampling_factor; GeometryInfo geometry_info; MagickStatusType flags; sampling_factor=(const char *) NULL; value=GetImageProperty(image,"jpeg:sampling-factor"); if (value != (char *) NULL) { sampling_factor=value; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Input sampling-factors=%s",sampling_factor); } if (image_info->sampling_factor != (char *) NULL) sampling_factor=image_info->sampling_factor; if (sampling_factor != (const char *) NULL) { flags=ParseGeometry(sampling_factor,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16) geometry_info.rho,(uint16) geometry_info.sigma); } } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (bits_per_sample == 12) (void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT); #endif break; } case COMPRESSION_ADOBE_DEFLATE: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; (void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } case COMPRESSION_CCITTFAX3: { /* Byte-aligned EOL. */ (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4); break; } case COMPRESSION_CCITTFAX4: break; #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: { if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; (void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } #endif case COMPRESSION_LZW: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; break; } #if defined(WEBP_SUPPORT) && defined(COMPRESSION_WEBP) case COMPRESSION_WEBP: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; (void) TIFFSetField(tiff,TIFFTAG_WEBP_LEVEL,mage_info->quality); if (image_info->quality >= 100) (void) TIFFSetField(tiff,TIFFTAG_WEBP_LOSSLESS,1); break; } #endif #if defined(ZSTD_SUPPORT) && defined(COMPRESSION_ZSTD) case COMPRESSION_ZSTD: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; (void) TIFFSetField(tiff,TIFFTAG_ZSTD_LEVEL,22*image_info->quality/ 100.0); break; } #endif default: break; } option=GetImageOption(image_info,"tiff:predictor"); if (option != (const char * ) NULL) predictor=(size_t) strtol(option,(char **) NULL,10); if (predictor != 0) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,predictor); if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0)) { unsigned short units; /* Set image resolution. */ units=RESUNIT_NONE; if (image->units == PixelsPerInchResolution) units=RESUNIT_INCH; if (image->units == PixelsPerCentimeterResolution) units=RESUNIT_CENTIMETER; (void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units); (void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->x_resolution); (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->y_resolution); if ((image->page.x < 0) || (image->page.y < 0)) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"TIFF: negative image positions unsupported","%s", image->filename); if ((image->page.x > 0) && (image->x_resolution > 0.0)) { /* Set horizontal image position. */ (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/ image->x_resolution); } if ((image->page.y > 0) && (image->y_resolution > 0.0)) { /* Set vertical image position. */ (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/ image->y_resolution); } } if (image->chromaticity.white_point.x != 0.0) { float chromaticity[6]; /* Set image chromaticity. */ chromaticity[0]=(float) image->chromaticity.red_primary.x; chromaticity[1]=(float) image->chromaticity.red_primary.y; chromaticity[2]=(float) image->chromaticity.green_primary.x; chromaticity[3]=(float) image->chromaticity.green_primary.y; chromaticity[4]=(float) image->chromaticity.blue_primary.x; chromaticity[5]=(float) image->chromaticity.blue_primary.y; (void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity); chromaticity[0]=(float) image->chromaticity.white_point.x; chromaticity[1]=(float) image->chromaticity.white_point.y; (void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity); } if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (image_info->adjoin != MagickFalse) && (imageListLength > 1)) { (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); if (image->scene != 0) (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene, imageListLength); } if (image->orientation != UndefinedOrientation) (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation); else (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT); (void) TIFFSetProfiles(tiff,image); { uint16 page, pages; page=(uint16) scene; pages=(uint16) imageListLength; if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (image_info->adjoin != MagickFalse) && (pages > 1)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages); } (void) TIFFSetProperties(tiff,image_info,image); DisableMSCWarning(4127) if (0) RestoreMSCWarning (void) TIFFSetEXIFProperties(tiff,image); /* Write image scanlines. */ if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); quantum_info->endian=LSBEndian; pixels=GetQuantumPixels(quantum_info); tiff_info.scanline=GetQuantumPixels(quantum_info); switch (photometric) { case PHOTOMETRIC_CIELAB: case PHOTOMETRIC_YCBCR: case PHOTOMETRIC_RGB: { /* RGB TIFF image. */ switch (image_info->interlace) { case NoInterlace: default: { quantum_type=RGBQuantum; if (image->matte != MagickFalse) quantum_type=RGBAQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: case PartitionInterlace: { /* Plane interlacing: RRRRRR...GGGGGG...BBBBBB... */ for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,100,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GreenQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,200,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,BlueQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,300,400); if (status == MagickFalse) break; } if (image->matte != MagickFalse) for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,AlphaQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,400,400); if (status == MagickFalse) break; } break; } } break; } case PHOTOMETRIC_SEPARATED: { /* CMYK TIFF image. */ quantum_type=CMYKQuantum; if (image->matte != MagickFalse) quantum_type=CMYKAQuantum; if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PHOTOMETRIC_PALETTE: { uint16 *blue, *green, *red; /* Colormapped TIFF image. */ red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red)); green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green)); blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue)); if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) || (blue == (uint16 *) NULL)) { if (red != (uint16 *) NULL) red=(uint16 *) RelinquishMagickMemory(red); if (green != (uint16 *) NULL) green=(uint16 *) RelinquishMagickMemory(green); if (blue != (uint16 *) NULL) blue=(uint16 *) RelinquishMagickMemory(blue); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } /* Initialize TIFF colormap. */ (void) memset(red,0,65536*sizeof(*red)); (void) memset(green,0,65536*sizeof(*green)); (void) memset(blue,0,65536*sizeof(*blue)); for (i=0; i < (ssize_t) image->colors; i++) { red[i]=ScaleQuantumToShort(image->colormap[i].red); green[i]=ScaleQuantumToShort(image->colormap[i].green); blue[i]=ScaleQuantumToShort(image->colormap[i].blue); } (void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue); red=(uint16 *) RelinquishMagickMemory(red); green=(uint16 *) RelinquishMagickMemory(green); blue=(uint16 *) RelinquishMagickMemory(blue); } default: { /* Convert PseudoClass packets to contiguous grayscale scanlines. */ quantum_type=IndexQuantum; if (image->matte != MagickFalse) { if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayAlphaQuantum; else quantum_type=IndexAlphaQuantum; } else if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } } quantum_info=DestroyQuantumInfo(quantum_info); if (image->colorspace == LabColorspace) DecodeLabImage(image,&image->exception); DestroyTIFFInfo(&tiff_info); DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) RestoreMSCWarning TIFFPrintDirectory(tiff,stdout,MagickFalse); (void) TIFFWriteDirectory(tiff); image=SyncNextImageInList(image); if (image == (Image *) NULL) break; status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); TIFFClose(tiff); return(MagickTrue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1555'</s>
<s>[INST] Given the following code containing errors, provide 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 SetGrayscaleImage(Image *image) { CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; PixelPacket *colormap; register ssize_t i; ssize_t *colormap_index, j, y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); exception=(&image->exception); if (image->type != GrayscaleType) (void) TransformImageColorspace(image,GRAYColorspace); if (image->storage_class == PseudoClass) colormap_index=(ssize_t *) AcquireQuantumMemory(image->colors+1, sizeof(*colormap_index)); else colormap_index=(ssize_t *) AcquireQuantumMemory(MaxColormapSize+1, sizeof(*colormap_index)); if (colormap_index == (ssize_t *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); if (image->storage_class != PseudoClass) { (void) memset(colormap_index,(-1),MaxColormapSize* sizeof(*colormap_index)); if (AcquireImageColormap(image,MaxColormapSize) == MagickFalse) { colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } image->colors=0; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { register size_t intensity; intensity=ScaleQuantumToMap(GetPixelRed(q)); if (colormap_index[intensity] < 0) { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SetGrayscaleImage) #endif if (colormap_index[intensity] < 0) { colormap_index[intensity]=(ssize_t) image->colors; image->colormap[image->colors].red=GetPixelRed(q); image->colormap[image->colors].green=GetPixelGreen(q); image->colormap[image->colors].blue=GetPixelBlue(q); image->colors++; } } SetPixelIndex(indexes+x,colormap_index[intensity]); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); } for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].opacity=(unsigned short) i; qsort((void *) image->colormap,image->colors,sizeof(PixelPacket), IntensityCompare); colormap=(PixelPacket *) AcquireQuantumMemory(image->colors, sizeof(*colormap)); if (colormap == (PixelPacket *) NULL) { colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } j=0; colormap[j]=image->colormap[0]; for (i=0; i < (ssize_t) image->colors; i++) { if (IsSameColor(image,&colormap[j],&image->colormap[i]) == MagickFalse) { j++; colormap[j]=image->colormap[i]; } colormap_index[(ssize_t) image->colormap[i].opacity]=j; } image->colors=(size_t) (j+1); image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap); image->colormap=colormap; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,colormap_index[ScaleQuantumToMap(GetPixelIndex( indexes+x))]); if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index); image->type=GrayscaleType; if (SetImageMonochrome(image,&image->exception) != MagickFalse) image->type=BilevelType; return(status); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1540'</s>
<s>[INST] Given the following code containing errors, provide 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 userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx, struct userfaultfd_wait_queue *ewq) { struct userfaultfd_ctx *release_new_ctx; if (WARN_ON_ONCE(current->flags & PF_EXITING)) goto out; ewq->ctx = ctx; init_waitqueue_entry(&ewq->wq, current); release_new_ctx = NULL; spin_lock(&ctx->event_wqh.lock); /* * After the __add_wait_queue the uwq is visible to userland * through poll/read(). */ __add_wait_queue(&ctx->event_wqh, &ewq->wq); for (;;) { set_current_state(TASK_KILLABLE); if (ewq->msg.event == 0) break; if (READ_ONCE(ctx->released) || fatal_signal_pending(current)) { /* * &ewq->wq may be queued in fork_event, but * __remove_wait_queue ignores the head * parameter. It would be a problem if it * didn't. */ __remove_wait_queue(&ctx->event_wqh, &ewq->wq); if (ewq->msg.event == UFFD_EVENT_FORK) { struct userfaultfd_ctx *new; new = (struct userfaultfd_ctx *) (unsigned long) ewq->msg.arg.reserved.reserved1; release_new_ctx = new; } break; } spin_unlock(&ctx->event_wqh.lock); wake_up_poll(&ctx->fd_wqh, EPOLLIN); schedule(); spin_lock(&ctx->event_wqh.lock); } __set_current_state(TASK_RUNNING); spin_unlock(&ctx->event_wqh.lock); if (release_new_ctx) { struct vm_area_struct *vma; struct mm_struct *mm = release_new_ctx->mm; /* the various vma->vm_userfaultfd_ctx still points to it */ down_write(&mm->mmap_sem); for (vma = mm->mmap; vma; vma = vma->vm_next) if (vma->vm_userfaultfd_ctx.ctx == release_new_ctx) { vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX; vma->vm_flags &= ~(VM_UFFD_WP | VM_UFFD_MISSING); } up_write(&mm->mmap_sem); userfaultfd_ctx_put(release_new_ctx); } /* * ctx may go away after this if the userfault pseudo fd is * already released. */ out: WRITE_ONCE(ctx->mmap_changing, false); userfaultfd_ctx_put(ctx); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362', 'CWE-703', 'CWE-667'], 'message': 'coredump: fix race condition between mmget_not_zero()/get_task_mm() and core dumping The core dumping code has always run without holding the mmap_sem for writing, despite that is the only way to ensure that the entire vma layout will not change from under it. Only using some signal serialization on the processes belonging to the mm is not nearly enough. This was pointed out earlier. For example in Hugh's post from Jul 2017: https://lkml.kernel.org/r/[email protected] "Not strictly relevant here, but a related note: I was very surprised to discover, only quite recently, how handle_mm_fault() may be called without down_read(mmap_sem) - when core dumping. That seems a misguided optimization to me, which would also be nice to correct" In particular because the growsdown and growsup can move the vm_start/vm_end the various loops the core dump does around the vma will not be consistent if page faults can happen concurrently. Pretty much all users calling mmget_not_zero()/get_task_mm() and then taking the mmap_sem had the potential to introduce unexpected side effects in the core dumping code. Adding mmap_sem for writing around the ->core_dump invocation is a viable long term fix, but it requires removing all copy user and page faults and to replace them with get_dump_page() for all binary formats which is not suitable as a short term fix. For the time being this solution manually covers the places that can confuse the core dump either by altering the vma layout or the vma flags while it runs. Once ->core_dump runs under mmap_sem for writing the function mmget_still_valid() can be dropped. Allowing mmap_sem protected sections to run in parallel with the coredump provides some minor parallelism advantage to the swapoff code (which seems to be safe enough by never mangling any vma field and can keep doing swapins in parallel to the core dumping) and to some other corner case. In order to facilitate the backporting I added "Fixes: 86039bd3b4e6" however the side effect of this same race condition in /proc/pid/mem should be reproducible since before 2.6.12-rc2 so I couldn't add any other "Fixes:" because there's no hash beyond the git genesis commit. Because find_extend_vma() is the only location outside of the process context that could modify the "mm" structures under mmap_sem for reading, by adding the mmget_still_valid() check to it, all other cases that take the mmap_sem for reading don't need the new check after mmget_not_zero()/get_task_mm(). The expand_stack() in page fault context also doesn't need the new check, because all tasks under core dumping are frozen. Link: http://lkml.kernel.org/r/[email protected] Fixes: 86039bd3b4e6 ("userfaultfd: add new syscall to provide memory externalization") Signed-off-by: Andrea Arcangeli <[email protected]> Reported-by: Jann Horn <[email protected]> Suggested-by: Oleg Nesterov <[email protected]> Acked-by: Peter Xu <[email protected]> Reviewed-by: Mike Rapoport <[email protected]> Reviewed-by: Oleg Nesterov <[email protected]> Reviewed-by: Jann Horn <[email protected]> Acked-by: Jason Gunthorpe <[email protected]> Acked-by: Michal Hocko <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: find_extend_vma(struct mm_struct *mm, unsigned long addr) { struct vm_area_struct *vma, *prev; addr &= PAGE_MASK; vma = find_vma_prev(mm, addr, &prev); if (vma && (vma->vm_start <= addr)) return vma; if (!prev || expand_stack(prev, addr)) return NULL; if (prev->vm_flags & VM_LOCKED) populate_vma_page_range(prev, addr, prev->vm_end, NULL); return prev; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362', 'CWE-703', 'CWE-667'], 'message': 'coredump: fix race condition between mmget_not_zero()/get_task_mm() and core dumping The core dumping code has always run without holding the mmap_sem for writing, despite that is the only way to ensure that the entire vma layout will not change from under it. Only using some signal serialization on the processes belonging to the mm is not nearly enough. This was pointed out earlier. For example in Hugh's post from Jul 2017: https://lkml.kernel.org/r/[email protected] "Not strictly relevant here, but a related note: I was very surprised to discover, only quite recently, how handle_mm_fault() may be called without down_read(mmap_sem) - when core dumping. That seems a misguided optimization to me, which would also be nice to correct" In particular because the growsdown and growsup can move the vm_start/vm_end the various loops the core dump does around the vma will not be consistent if page faults can happen concurrently. Pretty much all users calling mmget_not_zero()/get_task_mm() and then taking the mmap_sem had the potential to introduce unexpected side effects in the core dumping code. Adding mmap_sem for writing around the ->core_dump invocation is a viable long term fix, but it requires removing all copy user and page faults and to replace them with get_dump_page() for all binary formats which is not suitable as a short term fix. For the time being this solution manually covers the places that can confuse the core dump either by altering the vma layout or the vma flags while it runs. Once ->core_dump runs under mmap_sem for writing the function mmget_still_valid() can be dropped. Allowing mmap_sem protected sections to run in parallel with the coredump provides some minor parallelism advantage to the swapoff code (which seems to be safe enough by never mangling any vma field and can keep doing swapins in parallel to the core dumping) and to some other corner case. In order to facilitate the backporting I added "Fixes: 86039bd3b4e6" however the side effect of this same race condition in /proc/pid/mem should be reproducible since before 2.6.12-rc2 so I couldn't add any other "Fixes:" because there's no hash beyond the git genesis commit. Because find_extend_vma() is the only location outside of the process context that could modify the "mm" structures under mmap_sem for reading, by adding the mmget_still_valid() check to it, all other cases that take the mmap_sem for reading don't need the new check after mmget_not_zero()/get_task_mm(). The expand_stack() in page fault context also doesn't need the new check, because all tasks under core dumping are frozen. Link: http://lkml.kernel.org/r/[email protected] Fixes: 86039bd3b4e6 ("userfaultfd: add new syscall to provide memory externalization") Signed-off-by: Andrea Arcangeli <[email protected]> Reported-by: Jann Horn <[email protected]> Suggested-by: Oleg Nesterov <[email protected]> Acked-by: Peter Xu <[email protected]> Reviewed-by: Mike Rapoport <[email protected]> Reviewed-by: Oleg Nesterov <[email protected]> Reviewed-by: Jann Horn <[email protected]> Acked-by: Jason Gunthorpe <[email protected]> Acked-by: Michal Hocko <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: find_extend_vma(struct mm_struct *mm, unsigned long addr) { struct vm_area_struct *vma; unsigned long start; addr &= PAGE_MASK; vma = find_vma(mm, addr); if (!vma) return NULL; if (vma->vm_start <= addr) return vma; if (!(vma->vm_flags & VM_GROWSDOWN)) return NULL; start = vma->vm_start; if (expand_stack(vma, addr)) return NULL; if (vma->vm_flags & VM_LOCKED) populate_vma_page_range(vma, addr, start, NULL); return vma; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362', 'CWE-703', 'CWE-667'], 'message': 'coredump: fix race condition between mmget_not_zero()/get_task_mm() and core dumping The core dumping code has always run without holding the mmap_sem for writing, despite that is the only way to ensure that the entire vma layout will not change from under it. Only using some signal serialization on the processes belonging to the mm is not nearly enough. This was pointed out earlier. For example in Hugh's post from Jul 2017: https://lkml.kernel.org/r/[email protected] "Not strictly relevant here, but a related note: I was very surprised to discover, only quite recently, how handle_mm_fault() may be called without down_read(mmap_sem) - when core dumping. That seems a misguided optimization to me, which would also be nice to correct" In particular because the growsdown and growsup can move the vm_start/vm_end the various loops the core dump does around the vma will not be consistent if page faults can happen concurrently. Pretty much all users calling mmget_not_zero()/get_task_mm() and then taking the mmap_sem had the potential to introduce unexpected side effects in the core dumping code. Adding mmap_sem for writing around the ->core_dump invocation is a viable long term fix, but it requires removing all copy user and page faults and to replace them with get_dump_page() for all binary formats which is not suitable as a short term fix. For the time being this solution manually covers the places that can confuse the core dump either by altering the vma layout or the vma flags while it runs. Once ->core_dump runs under mmap_sem for writing the function mmget_still_valid() can be dropped. Allowing mmap_sem protected sections to run in parallel with the coredump provides some minor parallelism advantage to the swapoff code (which seems to be safe enough by never mangling any vma field and can keep doing swapins in parallel to the core dumping) and to some other corner case. In order to facilitate the backporting I added "Fixes: 86039bd3b4e6" however the side effect of this same race condition in /proc/pid/mem should be reproducible since before 2.6.12-rc2 so I couldn't add any other "Fixes:" because there's no hash beyond the git genesis commit. Because find_extend_vma() is the only location outside of the process context that could modify the "mm" structures under mmap_sem for reading, by adding the mmget_still_valid() check to it, all other cases that take the mmap_sem for reading don't need the new check after mmget_not_zero()/get_task_mm(). The expand_stack() in page fault context also doesn't need the new check, because all tasks under core dumping are frozen. Link: http://lkml.kernel.org/r/[email protected] Fixes: 86039bd3b4e6 ("userfaultfd: add new syscall to provide memory externalization") Signed-off-by: Andrea Arcangeli <[email protected]> Reported-by: Jann Horn <[email protected]> Suggested-by: Oleg Nesterov <[email protected]> Acked-by: Peter Xu <[email protected]> Reviewed-by: Mike Rapoport <[email protected]> Reviewed-by: Oleg Nesterov <[email protected]> Reviewed-by: Jann Horn <[email protected]> Acked-by: Jason Gunthorpe <[email protected]> Acked-by: Michal Hocko <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int userfaultfd_release(struct inode *inode, struct file *file) { struct userfaultfd_ctx *ctx = file->private_data; struct mm_struct *mm = ctx->mm; struct vm_area_struct *vma, *prev; /* len == 0 means wake all */ struct userfaultfd_wake_range range = { .len = 0, }; unsigned long new_flags; WRITE_ONCE(ctx->released, true); if (!mmget_not_zero(mm)) goto wakeup; /* * Flush page faults out of all CPUs. NOTE: all page faults * must be retried without returning VM_FAULT_SIGBUS if * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx * changes while handle_userfault released the mmap_sem. So * it's critical that released is set to true (above), before * taking the mmap_sem for writing. */ down_write(&mm->mmap_sem); prev = NULL; for (vma = mm->mmap; vma; vma = vma->vm_next) { cond_resched(); BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^ !!(vma->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP))); if (vma->vm_userfaultfd_ctx.ctx != ctx) { prev = vma; continue; } new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP); prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end, new_flags, vma->anon_vma, vma->vm_file, vma->vm_pgoff, vma_policy(vma), NULL_VM_UFFD_CTX); if (prev) vma = prev; else prev = vma; vma->vm_flags = new_flags; vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX; } up_write(&mm->mmap_sem); mmput(mm); wakeup: /* * After no new page faults can wait on this fault_*wqh, flush * the last page faults that may have been already waiting on * the fault_*wqh. */ spin_lock(&ctx->fault_pending_wqh.lock); __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range); __wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, &range); spin_unlock(&ctx->fault_pending_wqh.lock); /* Flush pending events that may still wait on event_wqh */ wake_up_all(&ctx->event_wqh); wake_up_poll(&ctx->fd_wqh, EPOLLHUP); userfaultfd_ctx_put(ctx); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362', 'CWE-703', 'CWE-667'], 'message': 'coredump: fix race condition between mmget_not_zero()/get_task_mm() and core dumping The core dumping code has always run without holding the mmap_sem for writing, despite that is the only way to ensure that the entire vma layout will not change from under it. Only using some signal serialization on the processes belonging to the mm is not nearly enough. This was pointed out earlier. For example in Hugh's post from Jul 2017: https://lkml.kernel.org/r/[email protected] "Not strictly relevant here, but a related note: I was very surprised to discover, only quite recently, how handle_mm_fault() may be called without down_read(mmap_sem) - when core dumping. That seems a misguided optimization to me, which would also be nice to correct" In particular because the growsdown and growsup can move the vm_start/vm_end the various loops the core dump does around the vma will not be consistent if page faults can happen concurrently. Pretty much all users calling mmget_not_zero()/get_task_mm() and then taking the mmap_sem had the potential to introduce unexpected side effects in the core dumping code. Adding mmap_sem for writing around the ->core_dump invocation is a viable long term fix, but it requires removing all copy user and page faults and to replace them with get_dump_page() for all binary formats which is not suitable as a short term fix. For the time being this solution manually covers the places that can confuse the core dump either by altering the vma layout or the vma flags while it runs. Once ->core_dump runs under mmap_sem for writing the function mmget_still_valid() can be dropped. Allowing mmap_sem protected sections to run in parallel with the coredump provides some minor parallelism advantage to the swapoff code (which seems to be safe enough by never mangling any vma field and can keep doing swapins in parallel to the core dumping) and to some other corner case. In order to facilitate the backporting I added "Fixes: 86039bd3b4e6" however the side effect of this same race condition in /proc/pid/mem should be reproducible since before 2.6.12-rc2 so I couldn't add any other "Fixes:" because there's no hash beyond the git genesis commit. Because find_extend_vma() is the only location outside of the process context that could modify the "mm" structures under mmap_sem for reading, by adding the mmget_still_valid() check to it, all other cases that take the mmap_sem for reading don't need the new check after mmget_not_zero()/get_task_mm(). The expand_stack() in page fault context also doesn't need the new check, because all tasks under core dumping are frozen. Link: http://lkml.kernel.org/r/[email protected] Fixes: 86039bd3b4e6 ("userfaultfd: add new syscall to provide memory externalization") Signed-off-by: Andrea Arcangeli <[email protected]> Reported-by: Jann Horn <[email protected]> Suggested-by: Oleg Nesterov <[email protected]> Acked-by: Peter Xu <[email protected]> Reviewed-by: Mike Rapoport <[email protected]> Reviewed-by: Oleg Nesterov <[email protected]> Reviewed-by: Jann Horn <[email protected]> Acked-by: Jason Gunthorpe <[email protected]> Acked-by: Michal Hocko <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Compound_Selector_Ptr Simple_Selector::unify_with(Compound_Selector_Ptr rhs) { for (size_t i = 0, L = rhs->length(); i < L; ++i) { if (to_string() == rhs->at(i)->to_string()) return rhs; } // check for pseudo elements because they are always last size_t i, L; bool found = false; if (typeid(*this) == typeid(Pseudo_Selector) || typeid(*this) == typeid(Wrapped_Selector)) { for (i = 0, L = rhs->length(); i < L; ++i) { if ((Cast<Pseudo_Selector>((*rhs)[i]) || Cast<Wrapped_Selector>((*rhs)[i])) && (*rhs)[L-1]->is_pseudo_element()) { found = true; break; } } } else { for (i = 0, L = rhs->length(); i < L; ++i) { if (Cast<Pseudo_Selector>((*rhs)[i]) || Cast<Wrapped_Selector>((*rhs)[i])) { found = true; break; } } } if (!found) { rhs->append(this); return rhs; } rhs->elements().insert(rhs->elements().begin() + i, this); return rhs; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-674'], 'message': 'Fix minor issue with attribute selector unification'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: String_Schema_Obj Parser::parse_css_variable_value(bool top_level) { String_Schema_Obj schema = SASS_MEMORY_NEW(String_Schema, pstate); String_Schema_Obj tok; if (!(tok = parse_css_variable_value_token(top_level))) { return {}; } schema->concat(tok); while ((tok = parse_css_variable_value_token(top_level))) { schema->concat(tok); } return schema.detach(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-674'], 'message': 'Make `parse_css_variable_value` non-recursive Fixes #2658 stack 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: static int exif_process_IFD_TAG(image_info_type *ImageInfo, char *dir_entry, char *offset_base, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table) { size_t length; unsigned int tag, format, components; char *value_ptr, tagname[64], cbuf[32], *outside=NULL; size_t byte_count, offset_val, fpos, fgot; int64_t byte_count_signed; xp_field_type *tmp_xp; #ifdef EXIF_DEBUG char *dump_data; int dump_free; #endif /* EXIF_DEBUG */ /* Protect against corrupt headers */ if (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "corrupt EXIF header: maximum directory nesting level reached"); return FALSE; } ImageInfo->ifd_nesting_level++; tag = php_ifd_get16u(dir_entry, ImageInfo->motorola_intel); format = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel); components = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel); if (!format || format > NUM_FORMATS) { /* (-1) catches illegal zero case as unsigned underflows to positive large. */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal format code 0x%04X, suppose BYTE", tag, exif_get_tagname(tag, tagname, -12, tag_table), format); format = TAG_FMT_BYTE; /*return TRUE;*/ } if (components < 0) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal components(%d)", tag, exif_get_tagname(tag, tagname, -12, tag_table), components); return FALSE; } byte_count_signed = (int64_t)components * php_tiff_bytes_per_format[format]; if (byte_count_signed < 0 || (byte_count_signed > INT32_MAX)) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal byte_count", tag, exif_get_tagname(tag, tagname, -12, tag_table)); return FALSE; } byte_count = (size_t)byte_count_signed; if (byte_count > 4) { offset_val = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel); /* If its bigger than 4 bytes, the dir entry contains an offset. */ value_ptr = offset_base+offset_val; /* dir_entry is ImageInfo->file.list[sn].data+2+i*12 offset_base is ImageInfo->file.list[sn].data-dir_offset dir_entry - offset_base is dir_offset+2+i*12 */ if (byte_count > IFDlength || offset_val > IFDlength-byte_count || value_ptr < dir_entry || offset_val < (size_t)(dir_entry-offset_base)) { /* It is important to check for IMAGE_FILETYPE_TIFF * JPEG does not use absolute pointers instead its pointers are * relative to the start of the TIFF header in APP1 section. */ if (byte_count > ImageInfo->FileSize || offset_val>ImageInfo->FileSize-byte_count || (ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_II && ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_MM && ImageInfo->FileType!=IMAGE_FILETYPE_JPEG)) { if (value_ptr < dir_entry) { /* we can read this if offset_val > 0 */ /* some files have their values in other parts of the file */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal pointer offset(x%04X < x%04X)", tag, exif_get_tagname(tag, tagname, -12, tag_table), offset_val, dir_entry); } else { /* this is for sure not allowed */ /* exception are IFD pointers */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal pointer offset(x%04X + x%04X = x%04X > x%04X)", tag, exif_get_tagname(tag, tagname, -12, tag_table), offset_val, byte_count, offset_val+byte_count, IFDlength); } return FALSE; } if (byte_count>sizeof(cbuf)) { /* mark as outside range and get buffer */ value_ptr = safe_emalloc(byte_count, 1, 0); outside = value_ptr; } else { /* In most cases we only access a small range so * it is faster to use a static buffer there * BUT it offers also the possibility to have * pointers read without the need to free them * explicitley before returning. */ memset(&cbuf, 0, sizeof(cbuf)); value_ptr = cbuf; } fpos = php_stream_tell(ImageInfo->infile); php_stream_seek(ImageInfo->infile, displacement+offset_val, SEEK_SET); fgot = php_stream_tell(ImageInfo->infile); if (fgot!=displacement+offset_val) { EFREE_IF(outside); exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Wrong file pointer: 0x%08X != 0x%08X", fgot, displacement+offset_val); return FALSE; } fgot = php_stream_read(ImageInfo->infile, value_ptr, byte_count); php_stream_seek(ImageInfo->infile, fpos, SEEK_SET); if (fgot<byte_count) { EFREE_IF(outside); EXIF_ERRLOG_FILEEOF(ImageInfo) return FALSE; } } } else { /* 4 bytes or less and value is in the dir entry itself */ value_ptr = dir_entry+8; offset_val= value_ptr-offset_base; } ImageInfo->sections_found |= FOUND_ANY_TAG; #ifdef EXIF_DEBUG dump_data = exif_dump_data(&dump_free, format, components, length, ImageInfo->motorola_intel, value_ptr); exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process tag(x%04X=%s,@x%04X + x%04X(=%d)): %s%s %s", tag, exif_get_tagname(tag, tagname, -12, tag_table), offset_val+displacement, byte_count, byte_count, (components>1)&&format!=TAG_FMT_UNDEFINED&&format!=TAG_FMT_STRING?"ARRAY OF ":"", exif_get_tagformat(format), dump_data); if (dump_free) { efree(dump_data); } #endif if (section_index==SECTION_THUMBNAIL) { if (!ImageInfo->Thumbnail.data) { switch(tag) { case TAG_IMAGEWIDTH: case TAG_COMP_IMAGE_WIDTH: ImageInfo->Thumbnail.width = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_IMAGEHEIGHT: case TAG_COMP_IMAGE_HEIGHT: ImageInfo->Thumbnail.height = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_STRIP_OFFSETS: case TAG_JPEG_INTERCHANGE_FORMAT: /* accept both formats */ ImageInfo->Thumbnail.offset = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_STRIP_BYTE_COUNTS: if (ImageInfo->FileType == IMAGE_FILETYPE_TIFF_II || ImageInfo->FileType == IMAGE_FILETYPE_TIFF_MM) { ImageInfo->Thumbnail.filetype = ImageInfo->FileType; } else { /* motorola is easier to read */ ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_TIFF_MM; } ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_JPEG_INTERCHANGE_FORMAT_LEN: if (ImageInfo->Thumbnail.filetype == IMAGE_FILETYPE_UNKNOWN) { ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_JPEG; ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); } break; } } } else { if (section_index==SECTION_IFD0 || section_index==SECTION_EXIF) switch(tag) { case TAG_COPYRIGHT: /* check for "<photographer> NUL <editor> NUL" */ if (byte_count>1 && (length=php_strnlen(value_ptr, byte_count)) > 0) { if (length<byte_count-1) { /* When there are any characters after the first NUL */ ImageInfo->CopyrightPhotographer = estrdup(value_ptr); ImageInfo->CopyrightEditor = estrndup(value_ptr+length+1, byte_count-length-1); spprintf(&ImageInfo->Copyright, 0, "%s, %s", ImageInfo->CopyrightPhotographer, ImageInfo->CopyrightEditor); /* format = TAG_FMT_UNDEFINED; this musn't be ASCII */ /* but we are not supposed to change this */ /* keep in mind that image_info does not store editor value */ } else { ImageInfo->Copyright = estrndup(value_ptr, byte_count); } } break; case TAG_USERCOMMENT: ImageInfo->UserCommentLength = exif_process_user_comment(ImageInfo, &(ImageInfo->UserComment), &(ImageInfo->UserCommentEncoding), value_ptr, byte_count); break; case TAG_XP_TITLE: case TAG_XP_COMMENTS: case TAG_XP_AUTHOR: case TAG_XP_KEYWORDS: case TAG_XP_SUBJECT: tmp_xp = (xp_field_type*)safe_erealloc(ImageInfo->xp_fields.list, (ImageInfo->xp_fields.count+1), sizeof(xp_field_type), 0); ImageInfo->sections_found |= FOUND_WINXP; ImageInfo->xp_fields.list = tmp_xp; ImageInfo->xp_fields.count++; exif_process_unicode(ImageInfo, &(ImageInfo->xp_fields.list[ImageInfo->xp_fields.count-1]), tag, value_ptr, byte_count); break; case TAG_FNUMBER: /* Simplest way of expressing aperture, so I trust it the most. (overwrite previously computed value if there is one) */ ImageInfo->ApertureFNumber = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_APERTURE: case TAG_MAX_APERTURE: /* More relevant info always comes earlier, so only use this field if we don't have appropriate aperture information yet. */ if (ImageInfo->ApertureFNumber == 0) { ImageInfo->ApertureFNumber = (float)exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel)*log(2)*0.5); } break; case TAG_SHUTTERSPEED: /* More complicated way of expressing exposure time, so only use this value if we don't already have it from somewhere else. SHUTTERSPEED comes after EXPOSURE TIME */ if (ImageInfo->ExposureTime == 0) { ImageInfo->ExposureTime = (float)(1/exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel)*log(2))); } break; case TAG_EXPOSURETIME: ImageInfo->ExposureTime = -1; break; case TAG_COMP_IMAGE_WIDTH: ImageInfo->ExifImageWidth = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_FOCALPLANE_X_RES: ImageInfo->FocalplaneXRes = exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_SUBJECT_DISTANCE: /* Inidcates the distacne the autofocus camera is focused to. Tends to be less accurate as distance increases. */ ImageInfo->Distance = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_FOCALPLANE_RESOLUTION_UNIT: switch((int)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel)) { case 1: ImageInfo->FocalplaneUnits = 25.4; break; /* inch */ case 2: /* According to the information I was using, 2 measn meters. But looking at the Cannon powershot's files, inches is the only sensible value. */ ImageInfo->FocalplaneUnits = 25.4; break; case 3: ImageInfo->FocalplaneUnits = 10; break; /* centimeter */ case 4: ImageInfo->FocalplaneUnits = 1; break; /* milimeter */ case 5: ImageInfo->FocalplaneUnits = .001; break; /* micrometer */ } break; case TAG_SUB_IFD: if (format==TAG_FMT_IFD) { /* If this is called we are either in a TIFFs thumbnail or a JPEG where we cannot handle it */ /* TIFF thumbnail: our data structure cannot store a thumbnail of a thumbnail */ /* JPEG do we have the data area and what to do with it */ exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Skip SUB IFD"); } break; case TAG_MAKE: ImageInfo->make = estrndup(value_ptr, byte_count); break; case TAG_MODEL: ImageInfo->model = estrndup(value_ptr, byte_count); break; case TAG_MAKER_NOTE: if (!exif_process_IFD_in_MAKERNOTE(ImageInfo, value_ptr, byte_count, offset_base, IFDlength, displacement)) { EFREE_IF(outside); return FALSE; } break; case TAG_EXIF_IFD_POINTER: case TAG_GPS_IFD_POINTER: case TAG_INTEROP_IFD_POINTER: if (ReadNextIFD) { char *Subdir_start; int sub_section_index = 0; switch(tag) { case TAG_EXIF_IFD_POINTER: #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found EXIF"); #endif ImageInfo->sections_found |= FOUND_EXIF; sub_section_index = SECTION_EXIF; break; case TAG_GPS_IFD_POINTER: #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found GPS"); #endif ImageInfo->sections_found |= FOUND_GPS; sub_section_index = SECTION_GPS; break; case TAG_INTEROP_IFD_POINTER: #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found INTEROPERABILITY"); #endif ImageInfo->sections_found |= FOUND_INTEROP; sub_section_index = SECTION_INTEROP; break; } Subdir_start = offset_base + php_ifd_get32u(value_ptr, ImageInfo->motorola_intel); if (Subdir_start < offset_base || Subdir_start > offset_base+IFDlength) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD Pointer"); return FALSE; } if (!exif_process_IFD_in_JPEG(ImageInfo, Subdir_start, offset_base, IFDlength, displacement, sub_section_index)) { return FALSE; } #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Subsection %s done", exif_get_sectionname(sub_section_index)); #endif } } } exif_iif_add_tag(ImageInfo, section_index, exif_get_tagname(tag, tagname, sizeof(tagname), tag_table), tag, format, components, value_ptr, byte_count); EFREE_IF(outside); return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #77950 - Heap-buffer-overflow in _estrndup via exif_process_IFD_TAG I do not completely understand what is going on there, but I am pretty sure dir_entry <= offset_base if not a normal situation, so we better not to rely on such dir_entry.'</s>
<s>[INST] Given the following code containing errors, provide 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 *ReadXWDImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define CheckOverflowException(length,width,height) \ (((height) != 0) && ((length)/((size_t) height) != ((size_t) width))) char *comment; Image *image; IndexPacket index; int x_status; MagickBooleanType authentic_colormap; MagickStatusType status; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register size_t pixel; size_t length; ssize_t count, y; unsigned long lsb_first; XColor *colors; XImage *ximage; XWDFileHeader header; /* 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 in header information. */ count=ReadBlob(image,sz_XWDheader,(unsigned char *) &header); if (count != sz_XWDheader) ThrowReaderException(CorruptImageError,"UnableToReadImageHeader"); /* Ensure the header byte-order is most-significant byte first. */ lsb_first=1; if ((int) (*(char *) &lsb_first) != 0) MSBOrderLong((unsigned char *) &header,sz_XWDheader); /* Check to see if the dump file is in the proper format. */ if (header.file_version != XWD_FILE_VERSION) ThrowReaderException(CorruptImageError,"FileFormatVersionMismatch"); if (header.header_size < sz_XWDheader) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((header.bits_per_pixel == 0) || (header.bits_per_pixel > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (((header.bitmap_pad % 8) != 0) || (header.bitmap_pad > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (header.bitmap_unit > 32) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (header.ncolors > 256) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); switch (header.visual_class) { case StaticGray: case GrayScale: case StaticColor: case PseudoColor: case TrueColor: case DirectColor: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } switch (header.pixmap_format) { case XYBitmap: case XYPixmap: case ZPixmap: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } length=(size_t) (header.header_size-sz_XWDheader); if ((length+1) != ((size_t) ((CARD32) (length+1)))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); comment=(char *) AcquireQuantumMemory(length+1,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,length,(unsigned char *) comment); comment[length]='\0'; (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); if (count != (ssize_t) length) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); /* Initialize the X image. */ ximage=(XImage *) AcquireMagickMemory(sizeof(*ximage)); if (ximage == (XImage *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); ximage->depth=(int) header.pixmap_depth; ximage->format=(int) header.pixmap_format; ximage->xoffset=(int) header.xoffset; ximage->data=(char *) NULL; ximage->width=(int) header.pixmap_width; ximage->height=(int) header.pixmap_height; ximage->bitmap_pad=(int) header.bitmap_pad; ximage->bytes_per_line=(int) header.bytes_per_line; ximage->byte_order=(int) header.byte_order; ximage->bitmap_unit=(int) header.bitmap_unit; ximage->bitmap_bit_order=(int) header.bitmap_bit_order; ximage->bits_per_pixel=(int) header.bits_per_pixel; ximage->red_mask=header.red_mask; ximage->green_mask=header.green_mask; ximage->blue_mask=header.blue_mask; if ((ximage->width < 0) || (ximage->height < 0) || (ximage->depth < 0) || (ximage->format < 0) || (ximage->byte_order < 0) || (ximage->bitmap_bit_order < 0) || (ximage->bitmap_pad < 0) || (ximage->bytes_per_line < 0)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if ((ximage->width > 65535) || (ximage->height > 65535)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if ((ximage->bits_per_pixel > 32) || (ximage->bitmap_unit > 32)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } x_status=XInitImage(ximage); if (x_status == 0) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } /* Read colormap. */ authentic_colormap=MagickFalse; colors=(XColor *) NULL; if (header.ncolors != 0) { XWDColor color; length=(size_t) header.ncolors; if (length > ((~0UL)/sizeof(*colors))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); colors=(XColor *) AcquireQuantumMemory(length,sizeof(*colors)); if (colors == (XColor *) NULL) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) header.ncolors; i++) { count=ReadBlob(image,sz_XWDColor,(unsigned char *) &color); if (count != sz_XWDColor) { colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } colors[i].pixel=color.pixel; colors[i].red=color.red; colors[i].green=color.green; colors[i].blue=color.blue; colors[i].flags=(char) color.flags; if (color.flags != 0) authentic_colormap=MagickTrue; } /* Ensure the header byte-order is most-significant byte first. */ lsb_first=1; if ((int) (*(char *) &lsb_first) != 0) for (i=0; i < (ssize_t) header.ncolors; i++) { MSBOrderLong((unsigned char *) &colors[i].pixel, sizeof(colors[i].pixel)); MSBOrderShort((unsigned char *) &colors[i].red,3* sizeof(colors[i].red)); } } /* Allocate the pixel buffer. */ length=(size_t) ximage->bytes_per_line*ximage->height; if (CheckOverflowException(length,ximage->bytes_per_line,ximage->height)) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (ximage->format != ZPixmap) { size_t extent; extent=length; length*=ximage->depth; if (CheckOverflowException(length,extent,ximage->depth)) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } } ximage->data=(char *) AcquireQuantumMemory(length,sizeof(*ximage->data)); if (ximage->data == (char *) NULL) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } count=ReadBlob(image,length,(unsigned char *) ximage->data); if (count != (ssize_t) length) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } /* Convert image to MIFF format. */ image->columns=(size_t) ximage->width; image->rows=(size_t) ximage->height; image->depth=8; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); InheritException(exception,&image->exception); return(DestroyImageList(image)); } if ((header.ncolors == 0U) || (ximage->red_mask != 0) || (ximage->green_mask != 0) || (ximage->blue_mask != 0)) image->storage_class=DirectClass; else image->storage_class=PseudoClass; image->colors=header.ncolors; if (image_info->ping == MagickFalse) switch (image->storage_class) { case DirectClass: default: { register size_t color; size_t blue_mask, blue_shift, green_mask, green_shift, red_mask, red_shift; /* Determine shift and mask for red, green, and blue. */ red_mask=ximage->red_mask; red_shift=0; while ((red_mask != 0) && ((red_mask & 0x01) == 0)) { red_mask>>=1; red_shift++; } green_mask=ximage->green_mask; green_shift=0; while ((green_mask != 0) && ((green_mask & 0x01) == 0)) { green_mask>>=1; green_shift++; } blue_mask=ximage->blue_mask; blue_shift=0; while ((blue_mask != 0) && ((blue_mask & 0x01) == 0)) { blue_mask>>=1; blue_shift++; } /* Convert X image to DirectClass packets. */ if ((image->colors != 0) && (authentic_colormap != MagickFalse)) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(ximage,(int) x,(int) y); index=ConstrainColormapIndex(image,(ssize_t) (pixel >> red_shift) & red_mask); SetPixelRed(q,ScaleShortToQuantum(colors[(ssize_t) index].red)); index=ConstrainColormapIndex(image,(ssize_t) (pixel >> green_shift) & green_mask); SetPixelGreen(q,ScaleShortToQuantum(colors[(ssize_t) index].green)); index=ConstrainColormapIndex(image,(ssize_t) (pixel >> blue_shift) & blue_mask); SetPixelBlue(q,ScaleShortToQuantum(colors[(ssize_t) index].blue)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } else for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(ximage,(int) x,(int) y); color=(pixel >> red_shift) & red_mask; if (red_mask != 0) color=(color*65535UL)/red_mask; SetPixelRed(q,ScaleShortToQuantum((unsigned short) color)); color=(pixel >> green_shift) & green_mask; if (green_mask != 0) color=(color*65535UL)/green_mask; SetPixelGreen(q,ScaleShortToQuantum((unsigned short) color)); color=(pixel >> blue_shift) & blue_mask; if (blue_mask != 0) color=(color*65535UL)/blue_mask; SetPixelBlue(q,ScaleShortToQuantum((unsigned short) color)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } break; } case PseudoClass: { /* Convert X image to PseudoClass packets. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleShortToQuantum(colors[i].red); image->colormap[i].green=ScaleShortToQuantum(colors[i].green); image->colormap[i].blue=ScaleShortToQuantum(colors[i].blue); } for (y=0; y < (ssize_t) image->rows; y++) { 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; x++) { index=ConstrainColormapIndex(image,(ssize_t) XGetPixel(ximage,(int) x,(int) y)); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } break; } } /* Free image and colormap. */ if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-369'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1546'</s>
<s>[INST] Given the following code containing errors, provide 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 *ReadCINImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define MonoColorType 1 #define RGBColorType 3 char property[MagickPathExtent]; CINInfo cin; const unsigned char *pixels; Image *image; MagickBooleanType status; MagickOffsetType offset; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; register Quantum *q; size_t length; ssize_t count, y; unsigned char magick[4]; /* 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); } /* File information. */ offset=0; count=ReadBlob(image,4,magick); offset+=count; if ((count != 4) || ((LocaleNCompare((char *) magick,"\200\052\137\327",4) != 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); memset(&cin,0,sizeof(cin)); image->endian=(magick[0] == 0x80) && (magick[1] == 0x2a) && (magick[2] == 0x5f) && (magick[3] == 0xd7) ? MSBEndian : LSBEndian; cin.file.image_offset=ReadBlobLong(image); offset+=4; cin.file.generic_length=ReadBlobLong(image); offset+=4; cin.file.industry_length=ReadBlobLong(image); offset+=4; cin.file.user_length=ReadBlobLong(image); offset+=4; cin.file.file_size=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(cin.file.version),(unsigned char *) cin.file.version); (void) CopyMagickString(property,cin.file.version,sizeof(cin.file.version)); (void) SetImageProperty(image,"dpx:file.version",property,exception); offset+=ReadBlob(image,sizeof(cin.file.filename),(unsigned char *) cin.file.filename); (void) CopyMagickString(property,cin.file.filename,sizeof(cin.file.filename)); (void) SetImageProperty(image,"dpx:file.filename",property,exception); offset+=ReadBlob(image,sizeof(cin.file.create_date),(unsigned char *) cin.file.create_date); (void) CopyMagickString(property,cin.file.create_date, sizeof(cin.file.create_date)); (void) SetImageProperty(image,"dpx:file.create_date",property,exception); offset+=ReadBlob(image,sizeof(cin.file.create_time),(unsigned char *) cin.file.create_time); (void) CopyMagickString(property,cin.file.create_time, sizeof(cin.file.create_time)); (void) SetImageProperty(image,"dpx:file.create_time",property,exception); offset+=ReadBlob(image,sizeof(cin.file.reserve),(unsigned char *) cin.file.reserve); /* Image information. */ cin.image.orientation=(unsigned char) ReadBlobByte(image); offset++; if (cin.image.orientation != (unsigned char) (~0)) (void) FormatImageProperty(image,"dpx:image.orientation","%d", cin.image.orientation); switch (cin.image.orientation) { default: case 0: image->orientation=TopLeftOrientation; break; case 1: image->orientation=TopRightOrientation; break; case 2: image->orientation=BottomLeftOrientation; break; case 3: image->orientation=BottomRightOrientation; break; case 4: image->orientation=LeftTopOrientation; break; case 5: image->orientation=RightTopOrientation; break; case 6: image->orientation=LeftBottomOrientation; break; case 7: image->orientation=RightBottomOrientation; break; } cin.image.number_channels=(unsigned char) ReadBlobByte(image); offset++; offset+=ReadBlob(image,sizeof(cin.image.reserve1),(unsigned char *) cin.image.reserve1); for (i=0; i < 8; i++) { cin.image.channel[i].designator[0]=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].designator[1]=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].bits_per_pixel=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].reserve=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].pixels_per_line=ReadBlobLong(image); offset+=4; cin.image.channel[i].lines_per_image=ReadBlobLong(image); offset+=4; cin.image.channel[i].min_data=ReadBlobFloat(image); offset+=4; cin.image.channel[i].min_quantity=ReadBlobFloat(image); offset+=4; cin.image.channel[i].max_data=ReadBlobFloat(image); offset+=4; cin.image.channel[i].max_quantity=ReadBlobFloat(image); offset+=4; } cin.image.white_point[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.white_point[0]) != MagickFalse) image->chromaticity.white_point.x=cin.image.white_point[0]; cin.image.white_point[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.white_point[1]) != MagickFalse) image->chromaticity.white_point.y=cin.image.white_point[1]; cin.image.red_primary_chromaticity[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.red_primary_chromaticity[0]) != MagickFalse) image->chromaticity.red_primary.x=cin.image.red_primary_chromaticity[0]; cin.image.red_primary_chromaticity[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.red_primary_chromaticity[1]) != MagickFalse) image->chromaticity.red_primary.y=cin.image.red_primary_chromaticity[1]; cin.image.green_primary_chromaticity[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.green_primary_chromaticity[0]) != MagickFalse) image->chromaticity.red_primary.x=cin.image.green_primary_chromaticity[0]; cin.image.green_primary_chromaticity[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.green_primary_chromaticity[1]) != MagickFalse) image->chromaticity.green_primary.y=cin.image.green_primary_chromaticity[1]; cin.image.blue_primary_chromaticity[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.blue_primary_chromaticity[0]) != MagickFalse) image->chromaticity.blue_primary.x=cin.image.blue_primary_chromaticity[0]; cin.image.blue_primary_chromaticity[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.blue_primary_chromaticity[1]) != MagickFalse) image->chromaticity.blue_primary.y=cin.image.blue_primary_chromaticity[1]; offset+=ReadBlob(image,sizeof(cin.image.label),(unsigned char *) cin.image.label); (void) CopyMagickString(property,cin.image.label,sizeof(cin.image.label)); (void) SetImageProperty(image,"dpx:image.label",property,exception); offset+=ReadBlob(image,sizeof(cin.image.reserve),(unsigned char *) cin.image.reserve); /* Image data format information. */ cin.data_format.interleave=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.packing=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.sign=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.sense=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.line_pad=ReadBlobLong(image); offset+=4; cin.data_format.channel_pad=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(cin.data_format.reserve),(unsigned char *) cin.data_format.reserve); /* Image origination information. */ cin.origination.x_offset=ReadBlobSignedLong(image); offset+=4; if ((size_t) cin.origination.x_offset != ~0UL) (void) FormatImageProperty(image,"dpx:origination.x_offset","%.20g", (double) cin.origination.x_offset); cin.origination.y_offset=(ssize_t) ReadBlobLong(image); offset+=4; if ((size_t) cin.origination.y_offset != ~0UL) (void) FormatImageProperty(image,"dpx:origination.y_offset","%.20g", (double) cin.origination.y_offset); offset+=ReadBlob(image,sizeof(cin.origination.filename),(unsigned char *) cin.origination.filename); (void) CopyMagickString(property,cin.origination.filename, sizeof(cin.origination.filename)); (void) SetImageProperty(image,"dpx:origination.filename",property,exception); offset+=ReadBlob(image,sizeof(cin.origination.create_date),(unsigned char *) cin.origination.create_date); (void) CopyMagickString(property,cin.origination.create_date, sizeof(cin.origination.create_date)); (void) SetImageProperty(image,"dpx:origination.create_date",property, exception); offset+=ReadBlob(image,sizeof(cin.origination.create_time),(unsigned char *) cin.origination.create_time); (void) CopyMagickString(property,cin.origination.create_time, sizeof(cin.origination.create_time)); (void) SetImageProperty(image,"dpx:origination.create_time",property, exception); offset+=ReadBlob(image,sizeof(cin.origination.device),(unsigned char *) cin.origination.device); (void) CopyMagickString(property,cin.origination.device, sizeof(cin.origination.device)); (void) SetImageProperty(image,"dpx:origination.device",property,exception); offset+=ReadBlob(image,sizeof(cin.origination.model),(unsigned char *) cin.origination.model); (void) CopyMagickString(property,cin.origination.model, sizeof(cin.origination.model)); (void) SetImageProperty(image,"dpx:origination.model",property,exception); (void) memset(cin.origination.serial,0, sizeof(cin.origination.serial)); offset+=ReadBlob(image,sizeof(cin.origination.serial),(unsigned char *) cin.origination.serial); (void) CopyMagickString(property,cin.origination.serial, sizeof(cin.origination.serial)); (void) SetImageProperty(image,"dpx:origination.serial",property,exception); cin.origination.x_pitch=ReadBlobFloat(image); offset+=4; cin.origination.y_pitch=ReadBlobFloat(image); offset+=4; cin.origination.gamma=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.origination.gamma) != MagickFalse) image->gamma=cin.origination.gamma; offset+=ReadBlob(image,sizeof(cin.origination.reserve),(unsigned char *) cin.origination.reserve); if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0)) { int c; /* Image film information. */ cin.film.id=ReadBlobByte(image); offset++; c=cin.film.id; if (c != ~0) (void) FormatImageProperty(image,"dpx:film.id","%d",cin.film.id); cin.film.type=ReadBlobByte(image); offset++; c=cin.film.type; if (c != ~0) (void) FormatImageProperty(image,"dpx:film.type","%d",cin.film.type); cin.film.offset=ReadBlobByte(image); offset++; c=cin.film.offset; if (c != ~0) (void) FormatImageProperty(image,"dpx:film.offset","%d", cin.film.offset); cin.film.reserve1=ReadBlobByte(image); offset++; cin.film.prefix=ReadBlobLong(image); offset+=4; if (cin.film.prefix != ~0UL) (void) FormatImageProperty(image,"dpx:film.prefix","%.20g",(double) cin.film.prefix); cin.film.count=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(cin.film.format),(unsigned char *) cin.film.format); (void) CopyMagickString(property,cin.film.format,sizeof(cin.film.format)); (void) SetImageProperty(image,"dpx:film.format",property,exception); cin.film.frame_position=ReadBlobLong(image); offset+=4; if (cin.film.frame_position != ~0UL) (void) FormatImageProperty(image,"dpx:film.frame_position","%.20g", (double) cin.film.frame_position); cin.film.frame_rate=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.film.frame_rate) != MagickFalse) (void) FormatImageProperty(image,"dpx:film.frame_rate","%g", cin.film.frame_rate); offset+=ReadBlob(image,sizeof(cin.film.frame_id),(unsigned char *) cin.film.frame_id); (void) CopyMagickString(property,cin.film.frame_id, sizeof(cin.film.frame_id)); (void) SetImageProperty(image,"dpx:film.frame_id",property,exception); offset+=ReadBlob(image,sizeof(cin.film.slate_info),(unsigned char *) cin.film.slate_info); (void) CopyMagickString(property,cin.film.slate_info, sizeof(cin.film.slate_info)); (void) SetImageProperty(image,"dpx:film.slate_info",property,exception); offset+=ReadBlob(image,sizeof(cin.film.reserve),(unsigned char *) cin.film.reserve); } if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0)) { StringInfo *profile; /* User defined data. */ if (cin.file.user_length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); profile=BlobToStringInfo((const unsigned char *) NULL, cin.file.user_length); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); offset+=ReadBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); (void) SetImageProfile(image,"dpx:user.data",profile,exception); profile=DestroyStringInfo(profile); } image->depth=cin.image.channel[0].bits_per_pixel; image->columns=cin.image.channel[0].pixels_per_line; image->rows=cin.image.channel[0].lines_per_image; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(image); } for ( ; offset < (MagickOffsetType) cin.file.image_offset; offset++) { int c; c=ReadBlobByte(image); if (c == EOF) break; } if (offset < (MagickOffsetType) cin.file.image_offset) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); (void) SetImageBackgroundColor(image,exception); /* Convert CIN raster image to pixel packets. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); quantum_info->quantum=32; quantum_info->pack=MagickFalse; quantum_type=RGBQuantum; length=GetQuantumExtent(image,quantum_info,quantum_type); length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue); if (cin.image.number_channels == 1) { quantum_type=GrayQuantum; length=GetBytesPerRow(image->columns,1,image->depth,MagickTrue); } for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if ((size_t) count != length) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } SetQuantumImageType(image,quantum_type); quantum_info=DestroyQuantumInfo(quantum_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); SetImageColorspace(image,LogColorspace,exception); (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1472'</s>
<s>[INST] Given the following code containing errors, provide 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 smp_task_timedout(struct timer_list *t) { struct sas_task_slow *slow = from_timer(slow, t, timer); struct sas_task *task = slow->task; unsigned long flags; spin_lock_irqsave(&task->task_state_lock, flags); if (!(task->task_state_flags & SAS_TASK_STATE_DONE)) task->task_state_flags |= SAS_TASK_STATE_ABORTED; spin_unlock_irqrestore(&task->task_state_lock, flags); complete(&task->slow_task->completion); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-362', 'CWE-703'], 'message': 'scsi: libsas: fix a race condition when smp task timeout When the lldd is processing the complete sas task in interrupt and set the task stat as SAS_TASK_STATE_DONE, the smp timeout timer is able to be triggered at the same time. And smp_task_timedout() will complete the task wheter the SAS_TASK_STATE_DONE is set or not. Then the sas task may freed before lldd end the interrupt process. Thus a use-after-free will happen. Fix this by calling the complete() only when SAS_TASK_STATE_DONE is not set. And remove the check of the return value of the del_timer(). Once the LLDD sets DONE, it must call task->done(), which will call smp_task_done()->complete() and the task will be completed and freed correctly. Reported-by: chenxiang <[email protected]> Signed-off-by: Jason Yan <[email protected]> CC: John Garry <[email protected]> CC: Johannes Thumshirn <[email protected]> CC: Ewan Milne <[email protected]> CC: Christoph Hellwig <[email protected]> CC: Tomas Henzl <[email protected]> CC: Dan Williams <[email protected]> CC: Hannes Reinecke <[email protected]> Reviewed-by: Hannes Reinecke <[email protected]> Reviewed-by: John Garry <[email protected]> Reviewed-by: Johannes Thumshirn <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int resolveExprStep(Walker *pWalker, Expr *pExpr){ NameContext *pNC; Parse *pParse; pNC = pWalker->u.pNC; assert( pNC!=0 ); pParse = pNC->pParse; assert( pParse==pWalker->pParse ); #ifndef NDEBUG if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){ SrcList *pSrcList = pNC->pSrcList; int i; for(i=0; i<pNC->pSrcList->nSrc; i++){ assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab); } } #endif switch( pExpr->op ){ #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) /* The special operator TK_ROW means use the rowid for the first ** column in the FROM clause. This is used by the LIMIT and ORDER BY ** clause processing on UPDATE and DELETE statements. */ case TK_ROW: { SrcList *pSrcList = pNC->pSrcList; struct SrcList_item *pItem; assert( pSrcList && pSrcList->nSrc==1 ); pItem = pSrcList->a; assert( HasRowid(pItem->pTab) && pItem->pTab->pSelect==0 ); pExpr->op = TK_COLUMN; pExpr->y.pTab = pItem->pTab; pExpr->iTable = pItem->iCursor; pExpr->iColumn = -1; pExpr->affinity = SQLITE_AFF_INTEGER; break; } #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */ /* A column name: ID ** Or table name and column name: ID.ID ** Or a database, table and column: ID.ID.ID ** ** The TK_ID and TK_OUT cases are combined so that there will only ** be one call to lookupName(). Then the compiler will in-line ** lookupName() for a size reduction and performance increase. */ case TK_ID: case TK_DOT: { const char *zColumn; const char *zTable; const char *zDb; Expr *pRight; if( pExpr->op==TK_ID ){ zDb = 0; zTable = 0; zColumn = pExpr->u.zToken; }else{ Expr *pLeft = pExpr->pLeft; notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr); pRight = pExpr->pRight; if( pRight->op==TK_ID ){ zDb = 0; }else{ assert( pRight->op==TK_DOT ); zDb = pLeft->u.zToken; pLeft = pRight->pLeft; pRight = pRight->pRight; } zTable = pLeft->u.zToken; zColumn = pRight->u.zToken; if( IN_RENAME_OBJECT ){ sqlite3RenameTokenRemap(pParse, (void*)pExpr, (void*)pRight); sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft); } } return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr); } /* Resolve function names */ case TK_FUNCTION: { ExprList *pList = pExpr->x.pList; /* The argument list */ int n = pList ? pList->nExpr : 0; /* Number of arguments */ int no_such_func = 0; /* True if no such function exists */ int wrong_num_args = 0; /* True if wrong number of arguments */ int is_agg = 0; /* True if is an aggregate function */ int nId; /* Number of characters in function name */ const char *zId; /* The function name. */ FuncDef *pDef; /* Information about the function */ u8 enc = ENC(pParse->db); /* The database encoding */ assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); zId = pExpr->u.zToken; nId = sqlite3Strlen30(zId); pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0); if( pDef==0 ){ pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0); if( pDef==0 ){ no_such_func = 1; }else{ wrong_num_args = 1; } }else{ is_agg = pDef->xFinalize!=0; if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){ ExprSetProperty(pExpr, EP_Unlikely|EP_Skip); if( n==2 ){ pExpr->iTable = exprProbability(pList->a[1].pExpr); if( pExpr->iTable<0 ){ sqlite3ErrorMsg(pParse, "second argument to likelihood() must be a " "constant between 0.0 and 1.0"); pNC->nErr++; } }else{ /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is ** equivalent to likelihood(X, 0.0625). ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is ** short-hand for likelihood(X,0.0625). ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand ** for likelihood(X,0.9375). ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent ** to likelihood(X,0.9375). */ /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */ pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120; } } #ifndef SQLITE_OMIT_AUTHORIZATION { int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0); if( auth!=SQLITE_OK ){ if( auth==SQLITE_DENY ){ sqlite3ErrorMsg(pParse, "not authorized to use function: %s", pDef->zName); pNC->nErr++; } pExpr->op = TK_NULL; return WRC_Prune; } } #endif if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){ /* For the purposes of the EP_ConstFunc flag, date and time ** functions and other functions that change slowly are considered ** constant because they are constant for the duration of one query */ ExprSetProperty(pExpr,EP_ConstFunc); } if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){ /* Date/time functions that use 'now', and other functions like ** sqlite_version() that might change over time cannot be used ** in an index. */ notValid(pParse, pNC, "non-deterministic functions", NC_IdxExpr|NC_PartIdx); } if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0 && pParse->nested==0 && sqlite3Config.bInternalFunctions==0 ){ /* Internal-use-only functions are disallowed unless the ** SQL is being compiled using sqlite3NestedParse() */ no_such_func = 1; pDef = 0; } } if( 0==IN_RENAME_OBJECT ){ #ifndef SQLITE_OMIT_WINDOWFUNC assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX) || (pDef->xValue==0 && pDef->xInverse==0) || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize) ); if( pDef && pDef->xValue==0 && ExprHasProperty(pExpr, EP_WinFunc) ){ sqlite3ErrorMsg(pParse, "%.*s() may not be used as a window function", nId, zId ); pNC->nErr++; }else if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pExpr->y.pWin) || (is_agg && pExpr->y.pWin && (pNC->ncFlags & NC_AllowWin)==0) ){ const char *zType; if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pExpr->y.pWin ){ zType = "window"; }else{ zType = "aggregate"; } sqlite3ErrorMsg(pParse, "misuse of %s function %.*s()",zType,nId,zId); pNC->nErr++; is_agg = 0; } #else if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){ sqlite3ErrorMsg(pParse,"misuse of aggregate function %.*s()",nId,zId); pNC->nErr++; is_agg = 0; } #endif else if( no_such_func && pParse->db->init.busy==0 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION && pParse->explain==0 #endif ){ sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId); pNC->nErr++; }else if( wrong_num_args ){ sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()", nId, zId); pNC->nErr++; } if( is_agg ){ #ifndef SQLITE_OMIT_WINDOWFUNC pNC->ncFlags &= ~(pExpr->y.pWin ? NC_AllowWin : NC_AllowAgg); #else pNC->ncFlags &= ~NC_AllowAgg; #endif } } sqlite3WalkExprList(pWalker, pList); if( is_agg ){ #ifndef SQLITE_OMIT_WINDOWFUNC if( pExpr->y.pWin ){ Select *pSel = pNC->pWinSelect; sqlite3WindowUpdate(pParse, pSel->pWinDefn, pExpr->y.pWin, pDef); sqlite3WalkExprList(pWalker, pExpr->y.pWin->pPartition); sqlite3WalkExprList(pWalker, pExpr->y.pWin->pOrderBy); sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter); if( 0==pSel->pWin || 0==sqlite3WindowCompare(pParse, pSel->pWin, pExpr->y.pWin) ){ pExpr->y.pWin->pNextWin = pSel->pWin; pSel->pWin = pExpr->y.pWin; } pNC->ncFlags |= NC_AllowWin; }else #endif /* SQLITE_OMIT_WINDOWFUNC */ { NameContext *pNC2 = pNC; pExpr->op = TK_AGG_FUNCTION; pExpr->op2 = 0; while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){ pExpr->op2++; pNC2 = pNC2->pNext; } assert( pDef!=0 ); if( pNC2 ){ assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg ); testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 ); pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX); } pNC->ncFlags |= NC_AllowAgg; } } /* FIX ME: Compute pExpr->affinity based on the expected return ** type of the function */ return WRC_Prune; } #ifndef SQLITE_OMIT_SUBQUERY case TK_SELECT: case TK_EXISTS: testcase( pExpr->op==TK_EXISTS ); #endif case TK_IN: { testcase( pExpr->op==TK_IN ); if( ExprHasProperty(pExpr, EP_xIsSelect) ){ int nRef = pNC->nRef; notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr); sqlite3WalkSelect(pWalker, pExpr->x.pSelect); assert( pNC->nRef>=nRef ); if( nRef!=pNC->nRef ){ ExprSetProperty(pExpr, EP_VarSelect); pNC->ncFlags |= NC_VarSelect; } } break; } case TK_VARIABLE: { notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr); break; } case TK_IS: case TK_ISNOT: { Expr *pRight; assert( !ExprHasProperty(pExpr, EP_Reduced) ); /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE", ** and "x IS NOT FALSE". */ if( (pRight = pExpr->pRight)->op==TK_ID ){ int rc = resolveExprStep(pWalker, pRight); if( rc==WRC_Abort ) return WRC_Abort; if( pRight->op==TK_TRUEFALSE ){ pExpr->op2 = pExpr->op; pExpr->op = TK_TRUTH; return WRC_Continue; } } /* Fall thru */ } case TK_BETWEEN: case TK_EQ: case TK_NE: case TK_LT: case TK_LE: case TK_GT: case TK_GE: { int nLeft, nRight; if( pParse->db->mallocFailed ) break; assert( pExpr->pLeft!=0 ); nLeft = sqlite3ExprVectorSize(pExpr->pLeft); if( pExpr->op==TK_BETWEEN ){ nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr); if( nRight==nLeft ){ nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr); } }else{ assert( pExpr->pRight!=0 ); nRight = sqlite3ExprVectorSize(pExpr->pRight); } if( nLeft!=nRight ){ testcase( pExpr->op==TK_EQ ); testcase( pExpr->op==TK_NE ); testcase( pExpr->op==TK_LT ); testcase( pExpr->op==TK_LE ); testcase( pExpr->op==TK_GT ); testcase( pExpr->op==TK_GE ); testcase( pExpr->op==TK_IS ); testcase( pExpr->op==TK_ISNOT ); testcase( pExpr->op==TK_BETWEEN ); sqlite3ErrorMsg(pParse, "row value misused"); } break; } } return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Prevent aliases of window functions expressions from being used as arguments to aggregate or other window functions. FossilOrigin-Name: 1e16d3e8fc60d39ca3899759ff15d355fdd7d3e23b325d8d2b0f954e11ce8dce'</s>
<s>[INST] Given the following code containing errors, provide 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 lookupName( Parse *pParse, /* The parsing context */ const char *zDb, /* Name of the database containing table, or NULL */ const char *zTab, /* Name of table containing column, or NULL */ const char *zCol, /* Name of the column. */ NameContext *pNC, /* The name context used to resolve the name */ Expr *pExpr /* Make this EXPR node point to the selected column */ ){ int i, j; /* Loop counters */ int cnt = 0; /* Number of matching column names */ int cntTab = 0; /* Number of matching table names */ int nSubquery = 0; /* How many levels of subquery */ sqlite3 *db = pParse->db; /* The database connection */ struct SrcList_item *pItem; /* Use for looping over pSrcList items */ struct SrcList_item *pMatch = 0; /* The matching pSrcList item */ NameContext *pTopNC = pNC; /* First namecontext in the list */ Schema *pSchema = 0; /* Schema of the expression */ int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */ Table *pTab = 0; /* Table hold the row */ Column *pCol; /* A column of pTab */ assert( pNC ); /* the name context cannot be NULL. */ assert( zCol ); /* The Z in X.Y.Z cannot be NULL */ assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); /* Initialize the node to no-match */ pExpr->iTable = -1; ExprSetVVAProperty(pExpr, EP_NoReduce); /* Translate the schema name in zDb into a pointer to the corresponding ** schema. If not found, pSchema will remain NULL and nothing will match ** resulting in an appropriate error message toward the end of this routine */ if( zDb ){ testcase( pNC->ncFlags & NC_PartIdx ); testcase( pNC->ncFlags & NC_IsCheck ); if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){ /* Silently ignore database qualifiers inside CHECK constraints and ** partial indices. Do not raise errors because that might break ** legacy and because it does not hurt anything to just ignore the ** database name. */ zDb = 0; }else{ for(i=0; i<db->nDb; i++){ assert( db->aDb[i].zDbSName ); if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){ pSchema = db->aDb[i].pSchema; break; } } } } /* Start at the inner-most context and move outward until a match is found */ assert( pNC && cnt==0 ); do{ ExprList *pEList; SrcList *pSrcList = pNC->pSrcList; if( pSrcList ){ for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){ pTab = pItem->pTab; assert( pTab!=0 && pTab->zName!=0 ); assert( pTab->nCol>0 ); if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){ int hit = 0; pEList = pItem->pSelect->pEList; for(j=0; j<pEList->nExpr; j++){ if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){ cnt++; cntTab = 2; pMatch = pItem; pExpr->iColumn = j; hit = 1; } } if( hit || zTab==0 ) continue; } if( zDb && pTab->pSchema!=pSchema ){ continue; } if( zTab ){ const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName; assert( zTabName!=0 ); if( sqlite3StrICmp(zTabName, zTab)!=0 ){ continue; } if( IN_RENAME_OBJECT && pItem->zAlias ){ sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab); } } if( 0==(cntTab++) ){ pMatch = pItem; } for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){ if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ /* If there has been exactly one prior match and this match ** is for the right-hand table of a NATURAL JOIN or is in a ** USING clause, then skip this match. */ if( cnt==1 ){ if( pItem->fg.jointype & JT_NATURAL ) continue; if( nameInUsingClause(pItem->pUsing, zCol) ) continue; } cnt++; pMatch = pItem; /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */ pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j; break; } } } if( pMatch ){ pExpr->iTable = pMatch->iCursor; pExpr->y.pTab = pMatch->pTab; /* RIGHT JOIN not (yet) supported */ assert( (pMatch->fg.jointype & JT_RIGHT)==0 ); if( (pMatch->fg.jointype & JT_LEFT)!=0 ){ ExprSetProperty(pExpr, EP_CanBeNull); } pSchema = pExpr->y.pTab->pSchema; } } /* if( pSrcList ) */ #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) /* If we have not already resolved the name, then maybe ** it is a new.* or old.* trigger argument reference. Or ** maybe it is an excluded.* from an upsert. */ if( zDb==0 && zTab!=0 && cntTab==0 ){ pTab = 0; #ifndef SQLITE_OMIT_TRIGGER if( pParse->pTriggerTab!=0 ){ int op = pParse->eTriggerOp; assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT ); if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){ pExpr->iTable = 1; pTab = pParse->pTriggerTab; }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){ pExpr->iTable = 0; pTab = pParse->pTriggerTab; } } #endif /* SQLITE_OMIT_TRIGGER */ #ifndef SQLITE_OMIT_UPSERT if( (pNC->ncFlags & NC_UUpsert)!=0 ){ Upsert *pUpsert = pNC->uNC.pUpsert; if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){ pTab = pUpsert->pUpsertSrc->a[0].pTab; pExpr->iTable = 2; } } #endif /* SQLITE_OMIT_UPSERT */ if( pTab ){ int iCol; pSchema = pTab->pSchema; cntTab++; for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){ if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ if( iCol==pTab->iPKey ){ iCol = -1; } break; } } if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){ /* IMP: R-51414-32910 */ iCol = -1; } if( iCol<pTab->nCol ){ cnt++; #ifndef SQLITE_OMIT_UPSERT if( pExpr->iTable==2 ){ testcase( iCol==(-1) ); if( IN_RENAME_OBJECT ){ pExpr->iColumn = iCol; pExpr->y.pTab = pTab; eNewExprOp = TK_COLUMN; }else{ pExpr->iTable = pNC->uNC.pUpsert->regData + iCol; eNewExprOp = TK_REGISTER; ExprSetProperty(pExpr, EP_Alias); } }else #endif /* SQLITE_OMIT_UPSERT */ { #ifndef SQLITE_OMIT_TRIGGER if( iCol<0 ){ pExpr->affinity = SQLITE_AFF_INTEGER; }else if( pExpr->iTable==0 ){ testcase( iCol==31 ); testcase( iCol==32 ); pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol)); }else{ testcase( iCol==31 ); testcase( iCol==32 ); pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol)); } pExpr->y.pTab = pTab; pExpr->iColumn = (i16)iCol; eNewExprOp = TK_TRIGGER; #endif /* SQLITE_OMIT_TRIGGER */ } } } } #endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */ /* ** Perhaps the name is a reference to the ROWID */ if( cnt==0 && cntTab==1 && pMatch && (pNC->ncFlags & NC_IdxExpr)==0 && sqlite3IsRowid(zCol) && VisibleRowid(pMatch->pTab) ){ cnt = 1; pExpr->iColumn = -1; pExpr->affinity = SQLITE_AFF_INTEGER; } /* ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z ** might refer to an result-set alias. This happens, for example, when ** we are resolving names in the WHERE clause of the following command: ** ** SELECT a+b AS x FROM table WHERE x<10; ** ** In cases like this, replace pExpr with a copy of the expression that ** forms the result set entry ("a+b" in the example) and return immediately. ** Note that the expression in the result set should have already been ** resolved by the time the WHERE clause is resolved. ** ** The ability to use an output result-set column in the WHERE, GROUP BY, ** or HAVING clauses, or as part of a larger expression in the ORDER BY ** clause is not standard SQL. This is a (goofy) SQLite extension, that ** is supported for backwards compatibility only. Hence, we issue a warning ** on sqlite3_log() whenever the capability is used. */ if( (pNC->ncFlags & NC_UEList)!=0 && cnt==0 && zTab==0 ){ pEList = pNC->uNC.pEList; assert( pEList!=0 ); for(j=0; j<pEList->nExpr; j++){ char *zAs = pEList->a[j].zName; if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ Expr *pOrig; assert( pExpr->pLeft==0 && pExpr->pRight==0 ); assert( pExpr->x.pList==0 ); assert( pExpr->x.pSelect==0 ); pOrig = pEList->a[j].pExpr; if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){ sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs); return WRC_Abort; } if( sqlite3ExprVectorSize(pOrig)!=1 ){ sqlite3ErrorMsg(pParse, "row value misused"); return WRC_Abort; } resolveAlias(pParse, pEList, j, pExpr, "", nSubquery); cnt = 1; pMatch = 0; assert( zTab==0 && zDb==0 ); if( IN_RENAME_OBJECT ){ sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr); } goto lookupname_end; } } } /* Advance to the next name context. The loop will exit when either ** we have a match (cnt>0) or when we run out of name contexts. */ if( cnt ) break; pNC = pNC->pNext; nSubquery++; }while( pNC ); /* ** If X and Y are NULL (in other words if only the column name Z is ** supplied) and the value of Z is enclosed in double-quotes, then ** Z is a string literal if it doesn't match any column names. In that ** case, we need to return right away and not make any changes to ** pExpr. ** ** Because no reference was made to outer contexts, the pNC->nRef ** fields are not changed in any context. */ if( cnt==0 && zTab==0 ){ assert( pExpr->op==TK_ID ); if( ExprHasProperty(pExpr,EP_DblQuoted) ){ /* If a double-quoted identifier does not match any known column name, ** then treat it as a string. ** ** This hack was added in the early days of SQLite in a misguided attempt ** to be compatible with MySQL 3.x, which used double-quotes for strings. ** I now sorely regret putting in this hack. The effect of this hack is ** that misspelled identifier names are silently converted into strings ** rather than causing an error, to the frustration of countless ** programmers. To all those frustrated programmers, my apologies. ** ** Someday, I hope to get rid of this hack. Unfortunately there is ** a huge amount of legacy SQL that uses it. So for now, we just ** issue a warning. */ sqlite3_log(SQLITE_WARNING, "double-quoted string literal: \"%w\"", zCol); #ifdef SQLITE_ENABLE_NORMALIZE sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol); #endif pExpr->op = TK_STRING; pExpr->y.pTab = 0; return WRC_Prune; } if( sqlite3ExprIdToTrueFalse(pExpr) ){ return WRC_Prune; } } /* ** cnt==0 means there was not match. cnt>1 means there were two or ** more matches. Either way, we have an error. */ if( cnt!=1 ){ const char *zErr; zErr = cnt==0 ? "no such column" : "ambiguous column name"; if( zDb ){ sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol); }else if( zTab ){ sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol); }else{ sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol); } pParse->checkSchema = 1; pTopNC->nErr++; } /* If a column from a table in pSrcList is referenced, then record ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the ** column number is greater than the number of bits in the bitmask ** then set the high-order bit of the bitmask. */ if( pExpr->iColumn>=0 && pMatch!=0 ){ int n = pExpr->iColumn; testcase( n==BMS-1 ); if( n>=BMS ){ n = BMS-1; } assert( pMatch->iCursor==pExpr->iTable ); pMatch->colUsed |= ((Bitmask)1)<<n; } /* Clean up and return */ sqlite3ExprDelete(db, pExpr->pLeft); pExpr->pLeft = 0; sqlite3ExprDelete(db, pExpr->pRight); pExpr->pRight = 0; pExpr->op = eNewExprOp; ExprSetProperty(pExpr, EP_Leaf); lookupname_end: if( cnt==1 ){ assert( pNC!=0 ); if( !ExprHasProperty(pExpr, EP_Alias) ){ sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList); } /* Increment the nRef value on all name contexts from TopNC up to ** the point where the name matched. */ for(;;){ assert( pTopNC!=0 ); pTopNC->nRef++; if( pTopNC==pNC ) break; pTopNC = pTopNC->pNext; } return WRC_Prune; } else { return WRC_Abort; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Prevent aliases of window functions expressions from being used as arguments to aggregate or other window functions. FossilOrigin-Name: 1e16d3e8fc60d39ca3899759ff15d355fdd7d3e23b325d8d2b0f954e11ce8dce'</s>
<s>[INST] Given the following code containing errors, provide 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 rds_tcp_kill_sock(struct net *net) { struct rds_tcp_connection *tc, *_tc; LIST_HEAD(tmp_list); struct rds_tcp_net *rtn = net_generic(net, rds_tcp_netid); struct socket *lsock = rtn->rds_tcp_listen_sock; rtn->rds_tcp_listen_sock = NULL; rds_tcp_listen_stop(lsock, &rtn->rds_tcp_accept_w); spin_lock_irq(&rds_tcp_conn_lock); list_for_each_entry_safe(tc, _tc, &rds_tcp_conn_list, t_tcp_node) { struct net *c_net = read_pnet(&tc->t_cpath->cp_conn->c_net); if (net != c_net || !tc->t_sock) continue; if (!list_has_conn(&tmp_list, tc->t_cpath->cp_conn)) { list_move_tail(&tc->t_tcp_node, &tmp_list); } else { list_del(&tc->t_tcp_node); tc->t_tcp_node_detached = true; } } spin_unlock_irq(&rds_tcp_conn_lock); list_for_each_entry_safe(tc, _tc, &tmp_list, t_tcp_node) rds_conn_destroy(tc->t_cpath->cp_conn); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-362'], 'message': 'net: rds: force to destroy connection if t_sock is NULL in rds_tcp_kill_sock(). When it is to cleanup net namespace, rds_tcp_exit_net() will call rds_tcp_kill_sock(), if t_sock is NULL, it will not call rds_conn_destroy(), rds_conn_path_destroy() and rds_tcp_conn_free() to free connection, and the worker cp_conn_w is not stopped, afterwards the net is freed in net_drop_ns(); While cp_conn_w rds_connect_worker() will call rds_tcp_conn_path_connect() and reference 'net' which has already been freed. In rds_tcp_conn_path_connect(), rds_tcp_set_callbacks() will set t_sock = sock before sock->ops->connect, but if connect() is failed, it will call rds_tcp_restore_callbacks() and set t_sock = NULL, if connect is always failed, rds_connect_worker() will try to reconnect all the time, so rds_tcp_kill_sock() will never to cancel worker cp_conn_w and free the connections. Therefore, the condition !tc->t_sock is not needed if it is going to do cleanup_net->rds_tcp_exit_net->rds_tcp_kill_sock, because tc->t_sock is always NULL, and there is on other path to cancel cp_conn_w and free connection. So this patch is to fix this. rds_tcp_kill_sock(): ... if (net != c_net || !tc->t_sock) ... Acked-by: Santosh Shilimkar <[email protected]> ================================================================== BUG: KASAN: use-after-free in inet_create+0xbcc/0xd28 net/ipv4/af_inet.c:340 Read of size 4 at addr ffff8003496a4684 by task kworker/u8:4/3721 CPU: 3 PID: 3721 Comm: kworker/u8:4 Not tainted 5.1.0 #11 Hardware name: linux,dummy-virt (DT) Workqueue: krdsd rds_connect_worker Call trace: dump_backtrace+0x0/0x3c0 arch/arm64/kernel/time.c:53 show_stack+0x28/0x38 arch/arm64/kernel/traps.c:152 __dump_stack lib/dump_stack.c:77 [inline] dump_stack+0x120/0x188 lib/dump_stack.c:113 print_address_description+0x68/0x278 mm/kasan/report.c:253 kasan_report_error mm/kasan/report.c:351 [inline] kasan_report+0x21c/0x348 mm/kasan/report.c:409 __asan_report_load4_noabort+0x30/0x40 mm/kasan/report.c:429 inet_create+0xbcc/0xd28 net/ipv4/af_inet.c:340 __sock_create+0x4f8/0x770 net/socket.c:1276 sock_create_kern+0x50/0x68 net/socket.c:1322 rds_tcp_conn_path_connect+0x2b4/0x690 net/rds/tcp_connect.c:114 rds_connect_worker+0x108/0x1d0 net/rds/threads.c:175 process_one_work+0x6e8/0x1700 kernel/workqueue.c:2153 worker_thread+0x3b0/0xdd0 kernel/workqueue.c:2296 kthread+0x2f0/0x378 kernel/kthread.c:255 ret_from_fork+0x10/0x18 arch/arm64/kernel/entry.S:1117 Allocated by task 687: save_stack mm/kasan/kasan.c:448 [inline] set_track mm/kasan/kasan.c:460 [inline] kasan_kmalloc+0xd4/0x180 mm/kasan/kasan.c:553 kasan_slab_alloc+0x14/0x20 mm/kasan/kasan.c:490 slab_post_alloc_hook mm/slab.h:444 [inline] slab_alloc_node mm/slub.c:2705 [inline] slab_alloc mm/slub.c:2713 [inline] kmem_cache_alloc+0x14c/0x388 mm/slub.c:2718 kmem_cache_zalloc include/linux/slab.h:697 [inline] net_alloc net/core/net_namespace.c:384 [inline] copy_net_ns+0xc4/0x2d0 net/core/net_namespace.c:424 create_new_namespaces+0x300/0x658 kernel/nsproxy.c:107 unshare_nsproxy_namespaces+0xa0/0x198 kernel/nsproxy.c:206 ksys_unshare+0x340/0x628 kernel/fork.c:2577 __do_sys_unshare kernel/fork.c:2645 [inline] __se_sys_unshare kernel/fork.c:2643 [inline] __arm64_sys_unshare+0x38/0x58 kernel/fork.c:2643 __invoke_syscall arch/arm64/kernel/syscall.c:35 [inline] invoke_syscall arch/arm64/kernel/syscall.c:47 [inline] el0_svc_common+0x168/0x390 arch/arm64/kernel/syscall.c:83 el0_svc_handler+0x60/0xd0 arch/arm64/kernel/syscall.c:129 el0_svc+0x8/0xc arch/arm64/kernel/entry.S:960 Freed by task 264: save_stack mm/kasan/kasan.c:448 [inline] set_track mm/kasan/kasan.c:460 [inline] __kasan_slab_free+0x114/0x220 mm/kasan/kasan.c:521 kasan_slab_free+0x10/0x18 mm/kasan/kasan.c:528 slab_free_hook mm/slub.c:1370 [inline] slab_free_freelist_hook mm/slub.c:1397 [inline] slab_free mm/slub.c:2952 [inline] kmem_cache_free+0xb8/0x3a8 mm/slub.c:2968 net_free net/core/net_namespace.c:400 [inline] net_drop_ns.part.6+0x78/0x90 net/core/net_namespace.c:407 net_drop_ns net/core/net_namespace.c:406 [inline] cleanup_net+0x53c/0x6d8 net/core/net_namespace.c:569 process_one_work+0x6e8/0x1700 kernel/workqueue.c:2153 worker_thread+0x3b0/0xdd0 kernel/workqueue.c:2296 kthread+0x2f0/0x378 kernel/kthread.c:255 ret_from_fork+0x10/0x18 arch/arm64/kernel/entry.S:1117 The buggy address belongs to the object at ffff8003496a3f80 which belongs to the cache net_namespace of size 7872 The buggy address is located 1796 bytes inside of 7872-byte region [ffff8003496a3f80, ffff8003496a5e40) The buggy address belongs to the page: page:ffff7e000d25a800 count:1 mapcount:0 mapping:ffff80036ce4b000 index:0x0 compound_mapcount: 0 flags: 0xffffe0000008100(slab|head) raw: 0ffffe0000008100 dead000000000100 dead000000000200 ffff80036ce4b000 raw: 0000000000000000 0000000080040004 00000001ffffffff 0000000000000000 page dumped because: kasan: bad access detected Memory state around the buggy address: ffff8003496a4580: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff8003496a4600: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb >ffff8003496a4680: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ^ ffff8003496a4700: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff8003496a4780: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ================================================================== Fixes: 467fa15356ac("RDS-TCP: Support multiple RDS-TCP listen endpoints, one per netns.") Reported-by: Hulk Robot <[email protected]> Signed-off-by: Mao Wenan <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Image *ReadTIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; float *chromaticity, x_position, y_position, x_resolution, y_resolution; Image *image; int tiff_status; MagickBooleanType status; MagickSizeType number_pixels; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t pad; ssize_t y; TIFF *tiff; TIFFMethodType method; uint16 compress_tag, bits_per_sample, endian, extra_samples, interlace, max_sample_value, min_sample_value, orientation, pages, photometric, *sample_info, sample_format, samples_per_pixel, units, value; uint32 height, rows_per_strip, width; unsigned char *tiff_pixels; /* Open image. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) SetMagickThreadValue(tiff_exception,exception); tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } if (image_info->number_scenes != 0) { /* Generate blank images for subimage specification (e.g. image.tif[4]. We need to check the number of directores because it is possible that the subimage(s) are stored in the photoshop profile. */ if (image_info->scene < (size_t)TIFFNumberOfDirectories(tiff)) { for (i=0; i < (ssize_t) image_info->scene; i++) { status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status == MagickFalse) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } } } do { DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) TIFFPrintDirectory(tiff,stdout,MagickFalse); RestoreMSCWarning if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1)) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (sample_format == SAMPLEFORMAT_IEEEFP) (void) SetImageProperty(image,"quantum:format","floating-point"); switch (photometric) { case PHOTOMETRIC_MINISBLACK: { (void) SetImageProperty(image,"tiff:photometric","min-is-black"); break; } case PHOTOMETRIC_MINISWHITE: { (void) SetImageProperty(image,"tiff:photometric","min-is-white"); break; } case PHOTOMETRIC_PALETTE: { (void) SetImageProperty(image,"tiff:photometric","palette"); break; } case PHOTOMETRIC_RGB: { (void) SetImageProperty(image,"tiff:photometric","RGB"); break; } case PHOTOMETRIC_CIELAB: { (void) SetImageProperty(image,"tiff:photometric","CIELAB"); break; } case PHOTOMETRIC_LOGL: { (void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)"); break; } case PHOTOMETRIC_LOGLUV: { (void) SetImageProperty(image,"tiff:photometric","LOGLUV"); break; } #if defined(PHOTOMETRIC_MASK) case PHOTOMETRIC_MASK: { (void) SetImageProperty(image,"tiff:photometric","MASK"); break; } #endif case PHOTOMETRIC_SEPARATED: { (void) SetImageProperty(image,"tiff:photometric","separated"); break; } case PHOTOMETRIC_YCBCR: { (void) SetImageProperty(image,"tiff:photometric","YCBCR"); break; } default: { (void) SetImageProperty(image,"tiff:photometric","unknown"); break; } } if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u", (unsigned int) width,(unsigned int) height); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u", interlace); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Bits per sample: %u",bits_per_sample); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Min sample value: %u",min_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Max sample value: %u",max_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric " "interpretation: %s",GetImageProperty(image,"tiff:photometric")); } image->columns=(size_t) width; image->rows=(size_t) height; image->depth=(size_t) bits_per_sample; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g", (double) image->depth); image->endian=MSBEndian; if (endian == FILLORDER_LSB2MSB) image->endian=LSBEndian; #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN) if (TIFFIsBigEndian(tiff) == 0) { (void) SetImageProperty(image,"tiff:endian","lsb"); image->endian=LSBEndian; } else { (void) SetImageProperty(image,"tiff:endian","msb"); image->endian=MSBEndian; } #endif if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) SetImageColorspace(image,GRAYColorspace); if (photometric == PHOTOMETRIC_SEPARATED) SetImageColorspace(image,CMYKColorspace); if (photometric == PHOTOMETRIC_CIELAB) SetImageColorspace(image,LabColorspace); TIFFGetProfiles(tiff,image); TIFFGetProperties(tiff,image); option=GetImageOption(image_info,"tiff:exif-properties"); if ((option == (const char *) NULL) || (IsMagickTrue(option) != MagickFalse)) TIFFGetEXIFProperties(tiff,image); if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1)) { image->x_resolution=x_resolution; image->y_resolution=y_resolution; } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1) { if (units == RESUNIT_INCH) image->units=PixelsPerInchResolution; if (units == RESUNIT_CENTIMETER) image->units=PixelsPerCentimeterResolution; } if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1)) { image->page.x=(ssize_t) ceil(x_position*image->x_resolution-0.5); image->page.y=(ssize_t) ceil(y_position*image->y_resolution-0.5); } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1) image->orientation=(OrientationType) orientation; if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.white_point.x=chromaticity[0]; image->chromaticity.white_point.y=chromaticity[1]; } } if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { TIFFClose(tiff); ThrowReaderException(CoderError,"CompressNotSupported"); } #endif switch (compress_tag) { case COMPRESSION_NONE: image->compression=NoCompression; break; case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break; case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break; case COMPRESSION_JPEG: { image->compression=JPEGCompression; #if defined(JPEG_SUPPORT) { char sampling_factor[MaxTextExtent]; int tiff_status; uint16 horizontal, vertical; tiff_status=TIFFGetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,&horizontal, &vertical); if (tiff_status == 1) { (void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d", horizontal,vertical); (void) SetImageProperty(image,"jpeg:sampling-factor", sampling_factor); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling Factors: %s",sampling_factor); } } #endif break; } case COMPRESSION_OJPEG: image->compression=JPEGCompression; break; #if defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: image->compression=LZMACompression; break; #endif case COMPRESSION_LZW: image->compression=LZWCompression; break; case COMPRESSION_DEFLATE: image->compression=ZipCompression; break; case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break; default: image->compression=RLECompression; break; } quantum_info=(QuantumInfo *) NULL; if ((photometric == PHOTOMETRIC_PALETTE) && (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize)) { size_t colors; colors=(size_t) GetQuantumRange(bits_per_sample)+1; if (AcquireImageColormap(image,colors) == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1) image->scene=value; if (image->storage_class == PseudoClass) { int tiff_status; size_t range; uint16 *blue_colormap, *green_colormap, *red_colormap; /* Initialize colormap. */ tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap, &green_colormap,&blue_colormap); if (tiff_status == 1) { if ((red_colormap != (uint16 *) NULL) && (green_colormap != (uint16 *) NULL) && (blue_colormap != (uint16 *) NULL)) { range=255; /* might be old style 8-bit colormap */ for (i=0; i < (ssize_t) image->colors; i++) if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) || (blue_colormap[i] >= 256)) { range=65535; break; } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ClampToQuantum(((double) QuantumRange*red_colormap[i])/range); image->colormap[i].green=ClampToQuantum(((double) QuantumRange*green_colormap[i])/range); image->colormap[i].blue=ClampToQuantum(((double) QuantumRange*blue_colormap[i])/range); } } } } if (image_info->ping != MagickFalse) { if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; goto next_tiff_frame; } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Allocate memory for the image and pixel buffer. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } if (sample_format == SAMPLEFORMAT_UINT) status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat); if (sample_format == SAMPLEFORMAT_INT) status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat); if (sample_format == SAMPLEFORMAT_IEEEFP) status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) { TIFFClose(tiff); quantum_info=DestroyQuantumInfo(quantum_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } status=MagickTrue; switch (photometric) { case PHOTOMETRIC_MINISBLACK: { quantum_info->min_is_white=MagickFalse; break; } case PHOTOMETRIC_MINISWHITE: { quantum_info->min_is_white=MagickTrue; break; } default: break; } tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples, &sample_info); if (tiff_status == 1) { (void) SetImageProperty(image,"tiff:alpha","unspecified"); if (extra_samples == 0) { if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB)) image->matte=MagickTrue; } else for (i=0; i < extra_samples; i++) { image->matte=MagickTrue; if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA) { SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha); (void) SetImageProperty(image,"tiff:alpha","associated"); } else if (sample_info[i] == EXTRASAMPLE_UNASSALPHA) (void) SetImageProperty(image,"tiff:alpha","unassociated"); } } method=ReadGenericMethod; if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1) { char value[MaxTextExtent]; method=ReadStripMethod; (void) FormatLocaleString(value,MaxTextExtent,"%u",(unsigned int) rows_per_strip); (void) SetImageProperty(image,"tiff:rows-per-strip",value); } if ((samples_per_pixel >= 3) && (interlace == PLANARCONFIG_CONTIG)) if ((image->matte == MagickFalse) || (samples_per_pixel >= 4)) method=ReadRGBAMethod; if ((samples_per_pixel >= 4) && (interlace == PLANARCONFIG_SEPARATE)) if ((image->matte == MagickFalse) || (samples_per_pixel >= 5)) method=ReadCMYKAMethod; if ((photometric != PHOTOMETRIC_RGB) && (photometric != PHOTOMETRIC_CIELAB) && (photometric != PHOTOMETRIC_SEPARATED)) method=ReadGenericMethod; if (image->storage_class == PseudoClass) method=ReadSingleSampleMethod; if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) method=ReadSingleSampleMethod; if ((photometric != PHOTOMETRIC_SEPARATED) && (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64)) method=ReadGenericMethod; if (image->compression == JPEGCompression) method=GetJPEGMethod(image,tiff,photometric,bits_per_sample, samples_per_pixel); if (compress_tag == COMPRESSION_JBIG) method=ReadStripMethod; if (TIFFIsTiled(tiff) != MagickFalse) method=ReadTileMethod; quantum_info->endian=LSBEndian; quantum_type=RGBQuantum; tiff_pixels=(unsigned char *) AcquireMagickMemory(MagickMax( TIFFScanlineSize(tiff),(image->columns*samples_per_pixel* pow(2.0,ceil(log(bits_per_sample)/log(2.0)))))); if (tiff_pixels == (unsigned char *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } switch (method) { case ReadSingleSampleMethod: { /* Convert TIFF image to PseudoClass MIFF image. */ quantum_type=IndexQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); if (image->matte != MagickFalse) { if (image->storage_class != PseudoClass) { quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } else { quantum_type=IndexAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } } else if (image->storage_class != PseudoClass) { quantum_type=GrayQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); } status=SetQuantumPad(image,quantum_info,pad*pow(2,ceil(log( bits_per_sample)/log(2)))); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (y=0; y < (ssize_t) image->rows; y++) { int status; register PixelPacket *magick_restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) tiff_pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,tiff_pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadRGBAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0); quantum_type=RGBQuantum; if (image->matte != MagickFalse) { quantum_type=RGBAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); } if (image->colorspace == CMYKColorspace) { pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); quantum_type=CMYKQuantum; if (image->matte != MagickFalse) { quantum_type=CMYKAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0); } } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (y=0; y < (ssize_t) image->rows; y++) { int status; register PixelPacket *magick_restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) tiff_pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,tiff_pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadCMYKAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ for (i=0; i < (ssize_t) samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; int status; status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *) tiff_pixels); if (status == -1) break; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (image->colorspace != CMYKColorspace) switch (i) { case 0: quantum_type=RedQuantum; break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } else switch (i) { case 0: quantum_type=CyanQuantum; break; case 1: quantum_type=MagentaQuantum; break; case 2: quantum_type=YellowQuantum; break; case 3: quantum_type=BlackQuantum; break; case 4: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,tiff_pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadYCCKMethod: { for (y=0; y < (ssize_t) image->rows; y++) { int status; register IndexPacket *indexes; register PixelPacket *magick_restrict q; register ssize_t x; unsigned char *p; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) tiff_pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=tiff_pixels; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.402*(double) *(p+2))-179.456))); SetPixelMagenta(q,ScaleCharToQuantum(ClampYCC((double) *p- (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+ 135.45984))); SetPixelYellow(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.772*(double) *(p+1))-226.816))); SetPixelBlack(indexes+x,ScaleCharToQuantum((unsigned char)*(p+3))); q++; p+=4; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadStripMethod: { register uint32 *p; /* Convert stripped TIFF image to DirectClass MIFF image. */ i=0; p=(uint32 *) NULL; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (i == 0) { if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) tiff_pixels) == 0) break; i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t) image->rows-y); } i--; p=((uint32 *) tiff_pixels)+image->columns*i; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) (TIFFGetR(*p)))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) (TIFFGetG(*p)))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) (TIFFGetB(*p)))); if (image->matte != MagickFalse) SetPixelOpacity(q,ScaleCharToQuantum((unsigned char) (TIFFGetA(*p)))); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadTileMethod: { register uint32 *p; uint32 *tile_pixels, columns, rows; /* Convert tiled TIFF image to DirectClass MIFF image. */ if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) || (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1)) { TIFFClose(tiff); ThrowReaderException(CoderError,"ImageIsNotTiled"); } (void) SetImageStorageClass(image,DirectClass); number_pixels=(MagickSizeType) columns*rows; if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } tile_pixels=(uint32 *) AcquireQuantumMemory(columns,rows* sizeof(*tile_pixels)); if (tile_pixels == (uint32 *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (y=0; y < (ssize_t) image->rows; y+=rows) { PixelPacket *tile; register ssize_t x; register PixelPacket *magick_restrict q; size_t columns_remaining, rows_remaining; rows_remaining=image->rows-y; if ((ssize_t) (y+rows) < (ssize_t) image->rows) rows_remaining=rows; tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining, exception); if (tile == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x+=columns) { size_t column, row; if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0) break; columns_remaining=image->columns-x; if ((ssize_t) (x+columns) < (ssize_t) image->columns) columns_remaining=columns; p=tile_pixels+(rows-rows_remaining)*columns; q=tile+(image->columns*(rows_remaining-1)+x); for (row=rows_remaining; row > 0; row--) { if (image->matte != MagickFalse) for (column=columns_remaining; column > 0; column--) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); q++; p++; } else for (column=columns_remaining; column > 0; column--) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); q++; p++; } p+=columns-columns_remaining; q-=(image->columns+columns_remaining); } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels); break; } case ReadGenericMethod: default: { MemoryInfo *pixel_info; register uint32 *p; uint32 *pixels; /* Convert TIFF image to DirectClass MIFF image. */ number_pixels=(MagickSizeType) image->columns*image->rows; if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixel_info=AcquireVirtualMemory(image->columns,image->rows* sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info); (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32) image->rows,(uint32 *) pixels,0); /* Convert image to DirectClass pixel packets. */ p=pixels+number_pixels-1; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; q+=image->columns-1; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); p--; q--; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixel_info=RelinquishVirtualMemory(pixel_info); break; } } tiff_pixels=(unsigned char *) RelinquishMagickMemory(tiff_pixels); SetQuantumImageType(image,quantum_type); next_tiff_frame: if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (photometric == PHOTOMETRIC_CIELAB) DecodeLabImage(image,exception); if ((photometric == PHOTOMETRIC_LOGL) || (photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) { image->type=GrayscaleType; if (bits_per_sample == 1) image->type=BilevelType; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status != MagickFalse) { /* Allocate 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,image->scene-1, image->scene); if (status == MagickFalse) break; } } while (status != MagickFalse); TIFFClose(tiff); TIFFReadPhotoshopLayers(image,image_info,exception); if (image_info->number_scenes != 0) { if (image_info->scene >= GetImageListLength(image)) { /* Subimage was not found in the Photoshop layer */ image = DestroyImageList(image); return((Image *)NULL); } } return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/664'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: adv_error adv_png_read_ihdr( unsigned* pix_width, unsigned* pix_height, unsigned* pix_pixel, unsigned char** dat_ptr, unsigned* dat_size, unsigned char** pix_ptr, unsigned* pix_scanline, unsigned char** pal_ptr, unsigned* pal_size, unsigned char** rns_ptr, unsigned* rns_size, adv_fz* f, const unsigned char* data, unsigned data_size) { unsigned char* ptr; unsigned ptr_size; unsigned type; unsigned long res_size; unsigned pixel; unsigned width; unsigned width_align; unsigned height; unsigned depth; int r; z_stream z; adv_bool has_palette; *dat_ptr = 0; *pix_ptr = 0; *pal_ptr = 0; *pal_size = 0; *rns_ptr = 0; *rns_size = 0; if (data_size != 13) { error_set("Invalid IHDR size %d instead of 13", data_size); goto err; } *pix_width = width = be_uint32_read(data + 0); *pix_height = height = be_uint32_read(data + 4); depth = data[8]; if (data[9] == 3 && depth == 8) { pixel = 1; width_align = width; has_palette = 1; } else if (data[9] == 3 && depth == 4) { pixel = 1; width_align = (width + 1) & ~1; has_palette = 1; } else if (data[9] == 3 && depth == 2) { pixel = 1; width_align = (width + 3) & ~3; has_palette = 1; } else if (data[9] == 3 && depth == 1) { pixel = 1; width_align = (width + 7) & ~7; has_palette = 1; } else if (data[9] == 2 && depth == 8) { pixel = 3; width_align = width; has_palette = 0; } else if (data[9] == 6 && depth == 8) { pixel = 4; width_align = width; has_palette = 0; } else { error_unsupported_set("Unsupported bit depth/color type, %d/%d", (unsigned)data[8], (unsigned)data[9]); goto err; } *pix_pixel = pixel; if (data[10] != 0) { /* compression */ error_unsupported_set("Unsupported compression, %d instead of 0", (unsigned)data[10]); goto err; } if (data[11] != 0) { /* filter */ error_unsupported_set("Unsupported filter, %d instead of 0", (unsigned)data[11]); goto err; } if (data[12] != 0) { /* interlace */ error_unsupported_set("Unsupported interlace %d", (unsigned)data[12]); goto err; } if (adv_png_read_chunk(f, &ptr, &ptr_size, &type) != 0) goto err; while (type != ADV_PNG_CN_IDAT) { if (type == ADV_PNG_CN_PLTE) { if (ptr_size > 256*3) { error_set("Invalid palette size in PLTE chunk"); goto err_ptr; } if (*pal_ptr) { error_set("Double palette specification"); goto err_ptr; } *pal_ptr = ptr; *pal_size = ptr_size; } else if (type == ADV_PNG_CN_tRNS) { if (*rns_ptr) { error_set("Double rns specification"); goto err_ptr; } *rns_ptr = ptr; *rns_size = ptr_size; } else { /* ancillary bit. bit 5 of first byte. 0 (uppercase) = critical, 1 (lowercase) = ancillary. */ if ((type & 0x20000000) == 0) { char buf[4]; be_uint32_write(buf, type); error_unsupported_set("Unsupported critical chunk '%c%c%c%c'", buf[0], buf[1], buf[2], buf[3]); goto err_ptr; } free(ptr); } if (adv_png_read_chunk(f, &ptr, &ptr_size, &type) != 0) goto err; } if (has_palette && !*pal_ptr) { error_set("Missing PLTE chunk"); goto err_ptr; } if (!has_palette && *pal_ptr) { error_set("Unexpected PLTE chunk"); goto err_ptr; } *dat_size = height * (width_align * pixel + 1); *dat_ptr = malloc(*dat_size); *pix_scanline = width_align * pixel + 1; *pix_ptr = *dat_ptr + 1; z.zalloc = 0; z.zfree = 0; z.next_out = *dat_ptr; z.avail_out = *dat_size; z.next_in = 0; z.avail_in = 0; r = inflateInit(&z); while (r == Z_OK && type == ADV_PNG_CN_IDAT) { z.next_in = ptr; z.avail_in = ptr_size; r = inflate(&z, Z_NO_FLUSH); free(ptr); if (adv_png_read_chunk(f, &ptr, &ptr_size, &type) != 0) { inflateEnd(&z); goto err; } } res_size = z.total_out; inflateEnd(&z); if (r != Z_STREAM_END) { error_set("Invalid compressed data"); goto err_ptr; } if (depth == 8) { if (res_size != *dat_size) { error_set("Invalid decompressed size"); goto err_ptr; } if (pixel == 1) adv_png_unfilter_8(width * pixel, height, *dat_ptr, width_align * pixel + 1); else if (pixel == 3) adv_png_unfilter_24(width * pixel, height, *dat_ptr, width_align * pixel + 1); else if (pixel == 4) adv_png_unfilter_32(width * pixel, height, *dat_ptr, width_align * pixel + 1); else { error_set("Unsupported format"); goto err_ptr; } } else if (depth == 4) { if (res_size != height * (width_align / 2 + 1)) { error_set("Invalid decompressed size"); goto err_ptr; } adv_png_unfilter_8(width_align / 2, height, *dat_ptr, width_align / 2 + 1); adv_png_expand_4(width_align, height, *dat_ptr); } else if (depth == 2) { if (res_size != height * (width_align / 4 + 1)) { error_set("Invalid decompressed size"); goto err_ptr; } adv_png_unfilter_8(width_align / 4, height, *dat_ptr, width_align / 4 + 1); adv_png_expand_2(width_align, height, *dat_ptr); } else if (depth == 1) { if (res_size != height * (width_align / 8 + 1)) { error_set("Invalid decompressed size"); goto err_ptr; } adv_png_unfilter_8(width_align / 8, height, *dat_ptr, width_align / 8 + 1); adv_png_expand_1(width_align, height, *dat_ptr); } if (adv_png_read_iend(f, ptr, ptr_size, type)!=0) { goto err_ptr; } free(ptr); return 0; err_ptr: free(ptr); err: free(*dat_ptr); free(*pal_ptr); free(*rns_ptr); return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix a buffer overflow caused by invalid images'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_METHOD(imagickkernel, frommatrix) { zval *kernel_array; zval *origin_array; HashTable *inner_array; KernelInfo *kernel_info; long num_rows, num_columns = 0; int previous_num_columns; int row, column; zval *pzval_outer; zval *pzval_inner; int count = 0; size_t origin_x, origin_y; zval *tmp; KernelValueType *values = NULL; double notanumber = sqrt((double)-1.0); /* Special Value : Not A Number */ previous_num_columns = -1; count = 0; row = 0; origin_array = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|a", &kernel_array, &origin_array) == FAILURE) { return; } num_rows = zend_hash_num_elements(Z_ARRVAL_P(kernel_array)); if (num_rows == 0) { //error - array has zero elements. php_imagick_throw_exception(IMAGICKKERNEL_CLASS, MATRIX_ERROR_EMPTY TSRMLS_CC); return; } for (row=0 ; row<num_rows ; row++) { pzval_outer = zend_hash_index_find(Z_ARRVAL_P(kernel_array), row); if (pzval_outer == NULL) { php_imagick_throw_exception(IMAGICKKERNEL_CLASS, MATRIX_ERROR_UNEVEN TSRMLS_CC); goto cleanup; } ZVAL_DEREF(pzval_outer); column = 0; if (Z_TYPE_P(pzval_outer) == IS_ARRAY ) { inner_array = Z_ARRVAL_P(pzval_outer); num_columns = zend_hash_num_elements(inner_array); if (num_columns == 0) { php_imagick_throw_exception(IMAGICKKERNEL_CLASS, MATRIX_ERROR_EMPTY TSRMLS_CC); goto cleanup; } if (values == NULL) { values = (KernelValueType *)AcquireAlignedMemory(num_columns, num_rows*sizeof(KernelValueType)); } if (previous_num_columns != -1) { if (previous_num_columns != num_columns) { php_imagick_throw_exception(IMAGICKKERNEL_CLASS, MATRIX_ERROR_UNEVEN TSRMLS_CC); goto cleanup; } } previous_num_columns = num_columns; for (column=0; column<num_columns ; column++) { pzval_inner = zend_hash_index_find(inner_array, column); if (pzval_inner == NULL) { php_imagick_throw_exception(IMAGICKKERNEL_CLASS, MATRIX_ERROR_UNEVEN TSRMLS_CC); goto cleanup; } ZVAL_DEREF(pzval_inner); if (Z_TYPE_P(pzval_inner) == IS_DOUBLE) { //It's a float lets use it. values[count] = Z_DVAL_P(pzval_inner); } else if (Z_TYPE_P(pzval_inner) == IS_LONG) { //It's a long lets use it. values[count] = (float)Z_LVAL_P(pzval_inner); } else if (Z_TYPE_P(pzval_inner) == IS_FALSE) { //It's false, use nan values[count] = notanumber; } else { php_imagick_throw_exception(IMAGICKKERNEL_CLASS, MATRIX_ERROR_BAD_VALUE TSRMLS_CC); goto cleanup; } count++; } } else { php_imagick_throw_exception(IMAGICKKERNEL_CLASS, MATRIX_ERROR_UNEVEN TSRMLS_CC); goto cleanup; } } if (origin_array == NULL) { if (((num_columns%2) == 0) || ((num_rows%2) == 0)) { php_imagick_throw_exception(IMAGICKKERNEL_CLASS, MATRIX_ORIGIN_REQUIRED TSRMLS_CC); goto cleanup; } origin_x = (num_columns - 1) >> 1; origin_y = (num_rows - 1) >> 1; } else { HashTable *origin_array_ht; origin_array_ht = Z_ARRVAL_P(origin_array); tmp = zend_hash_index_find(origin_array_ht, 0); if (tmp != NULL) { ZVAL_DEREF(tmp); origin_x = Z_LVAL_P(tmp); } else { php_imagick_throw_exception(IMAGICKKERNEL_CLASS, MATRIX_ORIGIN_REQUIRED TSRMLS_CC); goto cleanup; } tmp = zend_hash_index_find(origin_array_ht, 1); if (tmp != NULL) { ZVAL_DEREF(tmp); origin_y = Z_LVAL_P(tmp); } else { php_imagick_throw_exception(IMAGICKKERNEL_CLASS, MATRIX_ORIGIN_REQUIRED TSRMLS_CC); goto cleanup; } } kernel_info = imagick_createKernel(values, num_columns, num_rows, origin_x, origin_y); createKernelZval(return_value, kernel_info TSRMLS_CC); return; cleanup: if (values != NULL) { RelinquishAlignedMemory(values); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Bounds check kernel origin position.'</s>
<s>[INST] Given the following code containing errors, provide 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 try_smi_init(struct smi_info *new_smi) { int rv = 0; int i; char *init_name = NULL; pr_info("Trying %s-specified %s state machine at %s address 0x%lx, slave address 0x%x, irq %d\n", ipmi_addr_src_to_str(new_smi->io.addr_source), si_to_str[new_smi->io.si_type], addr_space_to_str[new_smi->io.addr_type], new_smi->io.addr_data, new_smi->io.slave_addr, new_smi->io.irq); switch (new_smi->io.si_type) { case SI_KCS: new_smi->handlers = &kcs_smi_handlers; break; case SI_SMIC: new_smi->handlers = &smic_smi_handlers; break; case SI_BT: new_smi->handlers = &bt_smi_handlers; break; default: /* No support for anything else yet. */ rv = -EIO; goto out_err; } new_smi->si_num = smi_num; /* Do this early so it's available for logs. */ if (!new_smi->io.dev) { init_name = kasprintf(GFP_KERNEL, "ipmi_si.%d", new_smi->si_num); /* * If we don't already have a device from something * else (like PCI), then register a new one. */ new_smi->pdev = platform_device_alloc("ipmi_si", new_smi->si_num); if (!new_smi->pdev) { pr_err("Unable to allocate platform device\n"); rv = -ENOMEM; goto out_err; } new_smi->io.dev = &new_smi->pdev->dev; new_smi->io.dev->driver = &ipmi_platform_driver.driver; /* Nulled by device_add() */ new_smi->io.dev->init_name = init_name; } /* Allocate the state machine's data and initialize it. */ new_smi->si_sm = kmalloc(new_smi->handlers->size(), GFP_KERNEL); if (!new_smi->si_sm) { rv = -ENOMEM; goto out_err; } new_smi->io.io_size = new_smi->handlers->init_data(new_smi->si_sm, &new_smi->io); /* Now that we know the I/O size, we can set up the I/O. */ rv = new_smi->io.io_setup(&new_smi->io); if (rv) { dev_err(new_smi->io.dev, "Could not set up I/O space\n"); goto out_err; } /* Do low-level detection first. */ if (new_smi->handlers->detect(new_smi->si_sm)) { if (new_smi->io.addr_source) dev_err(new_smi->io.dev, "Interface detection failed\n"); rv = -ENODEV; goto out_err; } /* * Attempt a get device id command. If it fails, we probably * don't have a BMC here. */ rv = try_get_dev_id(new_smi); if (rv) { if (new_smi->io.addr_source) dev_err(new_smi->io.dev, "There appears to be no BMC at this location\n"); goto out_err; } setup_oem_data_handler(new_smi); setup_xaction_handlers(new_smi); check_for_broken_irqs(new_smi); new_smi->waiting_msg = NULL; new_smi->curr_msg = NULL; atomic_set(&new_smi->req_events, 0); new_smi->run_to_completion = false; for (i = 0; i < SI_NUM_STATS; i++) atomic_set(&new_smi->stats[i], 0); new_smi->interrupt_disabled = true; atomic_set(&new_smi->need_watch, 0); rv = try_enable_event_buffer(new_smi); if (rv == 0) new_smi->has_event_buffer = true; /* * Start clearing the flags before we enable interrupts or the * timer to avoid racing with the timer. */ start_clear_flags(new_smi); /* * IRQ is defined to be set when non-zero. req_events will * cause a global flags check that will enable interrupts. */ if (new_smi->io.irq) { new_smi->interrupt_disabled = false; atomic_set(&new_smi->req_events, 1); } if (new_smi->pdev && !new_smi->pdev_registered) { rv = platform_device_add(new_smi->pdev); if (rv) { dev_err(new_smi->io.dev, "Unable to register system interface device: %d\n", rv); goto out_err; } new_smi->pdev_registered = true; } dev_set_drvdata(new_smi->io.dev, new_smi); rv = device_add_group(new_smi->io.dev, &ipmi_si_dev_attr_group); if (rv) { dev_err(new_smi->io.dev, "Unable to add device attributes: error %d\n", rv); goto out_err; } new_smi->dev_group_added = true; rv = ipmi_register_smi(&handlers, new_smi, new_smi->io.dev, new_smi->io.slave_addr); if (rv) { dev_err(new_smi->io.dev, "Unable to register device: error %d\n", rv); goto out_err; } /* Don't increment till we know we have succeeded. */ smi_num++; dev_info(new_smi->io.dev, "IPMI %s interface initialized\n", si_to_str[new_smi->io.si_type]); WARN_ON(new_smi->io.dev->init_name != NULL); out_err: kfree(init_name); return rv; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'ipmi_si: fix use-after-free of resource->name When we excute the following commands, we got oops rmmod ipmi_si cat /proc/ioports [ 1623.482380] Unable to handle kernel paging request at virtual address ffff00000901d478 [ 1623.482382] Mem abort info: [ 1623.482383] ESR = 0x96000007 [ 1623.482385] Exception class = DABT (current EL), IL = 32 bits [ 1623.482386] SET = 0, FnV = 0 [ 1623.482387] EA = 0, S1PTW = 0 [ 1623.482388] Data abort info: [ 1623.482389] ISV = 0, ISS = 0x00000007 [ 1623.482390] CM = 0, WnR = 0 [ 1623.482393] swapper pgtable: 4k pages, 48-bit VAs, pgdp = 00000000d7d94a66 [ 1623.482395] [ffff00000901d478] pgd=000000dffbfff003, pud=000000dffbffe003, pmd=0000003f5d06e003, pte=0000000000000000 [ 1623.482399] Internal error: Oops: 96000007 [#1] SMP [ 1623.487407] Modules linked in: ipmi_si(E) nls_utf8 isofs rpcrdma ib_iser ib_srpt target_core_mod ib_srp scsi_transport_srp ib_ipoib rdma_ucm ib_umad rdma_cm ib_cm dm_mirror dm_region_hash dm_log iw_cm dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ses ghash_ce sha2_ce enclosure sha256_arm64 sg sha1_ce hisi_sas_v2_hw hibmc_drm sbsa_gwdt hisi_sas_main ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe mdio hns_dsaf ipmi_devintf hns_enet_drv ipmi_msghandler hns_mdio [last unloaded: ipmi_si] [ 1623.532410] CPU: 30 PID: 11438 Comm: cat Kdump: loaded Tainted: G E 5.0.0-rc3+ #168 [ 1623.541498] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017 [ 1623.548822] pstate: a0000005 (NzCv daif -PAN -UAO) [ 1623.553684] pc : string+0x28/0x98 [ 1623.557040] lr : vsnprintf+0x368/0x5e8 [ 1623.560837] sp : ffff000013213a80 [ 1623.564191] x29: ffff000013213a80 x28: ffff00001138abb5 [ 1623.569577] x27: ffff000013213c18 x26: ffff805f67d06049 [ 1623.574963] x25: 0000000000000000 x24: ffff00001138abb5 [ 1623.580349] x23: 0000000000000fb7 x22: ffff0000117ed000 [ 1623.585734] x21: ffff000011188fd8 x20: ffff805f67d07000 [ 1623.591119] x19: ffff805f67d06061 x18: ffffffffffffffff [ 1623.596505] x17: 0000000000000200 x16: 0000000000000000 [ 1623.601890] x15: ffff0000117ed748 x14: ffff805f67d07000 [ 1623.607276] x13: ffff805f67d0605e x12: 0000000000000000 [ 1623.612661] x11: 0000000000000000 x10: 0000000000000000 [ 1623.618046] x9 : 0000000000000000 x8 : 000000000000000f [ 1623.623432] x7 : ffff805f67d06061 x6 : fffffffffffffffe [ 1623.628817] x5 : 0000000000000012 x4 : ffff00000901d478 [ 1623.634203] x3 : ffff0a00ffffff04 x2 : ffff805f67d07000 [ 1623.639588] x1 : ffff805f67d07000 x0 : ffffffffffffffff [ 1623.644974] Process cat (pid: 11438, stack limit = 0x000000008d4cbc10) [ 1623.651592] Call trace: [ 1623.654068] string+0x28/0x98 [ 1623.657071] vsnprintf+0x368/0x5e8 [ 1623.660517] seq_vprintf+0x70/0x98 [ 1623.668009] seq_printf+0x7c/0xa0 [ 1623.675530] r_show+0xc8/0xf8 [ 1623.682558] seq_read+0x330/0x440 [ 1623.689877] proc_reg_read+0x78/0xd0 [ 1623.697346] __vfs_read+0x60/0x1a0 [ 1623.704564] vfs_read+0x94/0x150 [ 1623.711339] ksys_read+0x6c/0xd8 [ 1623.717939] __arm64_sys_read+0x24/0x30 [ 1623.725077] el0_svc_common+0x120/0x148 [ 1623.732035] el0_svc_handler+0x30/0x40 [ 1623.738757] el0_svc+0x8/0xc [ 1623.744520] Code: d1000406 aa0103e2 54000149 b4000080 (39400085) [ 1623.753441] ---[ end trace f91b6a4937de9835 ]--- [ 1623.760871] Kernel panic - not syncing: Fatal exception [ 1623.768935] SMP: stopping secondary CPUs [ 1623.775718] Kernel Offset: disabled [ 1623.781998] CPU features: 0x002,21006008 [ 1623.788777] Memory Limit: none [ 1623.798329] Starting crashdump kernel... [ 1623.805202] Bye! If io_setup is called successful in try_smi_init() but try_smi_init() goes out_err before calling ipmi_register_smi(), so ipmi_unregister_smi() will not be called while removing module. It leads to the resource that allocated in io_setup() can not be freed, but the name(DEVICE_NAME) of resource is freed while removing the module. It causes use-after-free when cat /proc/ioports. Fix this by calling io_cleanup() while try_smi_init() goes to out_err. and don't call io_cleanup() until io_setup() returns successful to avoid warning prints. Fixes: 93c303d2045b ("ipmi_si: Clean up shutdown a bit") Cc: [email protected] Reported-by: NuoHan Qiao <[email protected]> Suggested-by: Corey Minyard <[email protected]> Signed-off-by: Yang Yingliang <[email protected]> Signed-off-by: Corey Minyard <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ipmi_si_port_setup(struct si_sm_io *io) { unsigned int addr = io->addr_data; int idx; if (!addr) return -ENODEV; io->io_cleanup = port_cleanup; /* * Figure out the actual inb/inw/inl/etc routine to use based * upon the register size. */ switch (io->regsize) { case 1: io->inputb = port_inb; io->outputb = port_outb; break; case 2: io->inputb = port_inw; io->outputb = port_outw; break; case 4: io->inputb = port_inl; io->outputb = port_outl; break; default: dev_warn(io->dev, "Invalid register size: %d\n", io->regsize); return -EINVAL; } /* * Some BIOSes reserve disjoint I/O regions in their ACPI * tables. This causes problems when trying to register the * entire I/O region. Therefore we must register each I/O * port separately. */ for (idx = 0; idx < io->io_size; idx++) { if (request_region(addr + idx * io->regspacing, io->regsize, DEVICE_NAME) == NULL) { /* Undo allocations */ while (idx--) release_region(addr + idx * io->regspacing, io->regsize); return -EIO; } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'ipmi_si: fix use-after-free of resource->name When we excute the following commands, we got oops rmmod ipmi_si cat /proc/ioports [ 1623.482380] Unable to handle kernel paging request at virtual address ffff00000901d478 [ 1623.482382] Mem abort info: [ 1623.482383] ESR = 0x96000007 [ 1623.482385] Exception class = DABT (current EL), IL = 32 bits [ 1623.482386] SET = 0, FnV = 0 [ 1623.482387] EA = 0, S1PTW = 0 [ 1623.482388] Data abort info: [ 1623.482389] ISV = 0, ISS = 0x00000007 [ 1623.482390] CM = 0, WnR = 0 [ 1623.482393] swapper pgtable: 4k pages, 48-bit VAs, pgdp = 00000000d7d94a66 [ 1623.482395] [ffff00000901d478] pgd=000000dffbfff003, pud=000000dffbffe003, pmd=0000003f5d06e003, pte=0000000000000000 [ 1623.482399] Internal error: Oops: 96000007 [#1] SMP [ 1623.487407] Modules linked in: ipmi_si(E) nls_utf8 isofs rpcrdma ib_iser ib_srpt target_core_mod ib_srp scsi_transport_srp ib_ipoib rdma_ucm ib_umad rdma_cm ib_cm dm_mirror dm_region_hash dm_log iw_cm dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ses ghash_ce sha2_ce enclosure sha256_arm64 sg sha1_ce hisi_sas_v2_hw hibmc_drm sbsa_gwdt hisi_sas_main ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe mdio hns_dsaf ipmi_devintf hns_enet_drv ipmi_msghandler hns_mdio [last unloaded: ipmi_si] [ 1623.532410] CPU: 30 PID: 11438 Comm: cat Kdump: loaded Tainted: G E 5.0.0-rc3+ #168 [ 1623.541498] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017 [ 1623.548822] pstate: a0000005 (NzCv daif -PAN -UAO) [ 1623.553684] pc : string+0x28/0x98 [ 1623.557040] lr : vsnprintf+0x368/0x5e8 [ 1623.560837] sp : ffff000013213a80 [ 1623.564191] x29: ffff000013213a80 x28: ffff00001138abb5 [ 1623.569577] x27: ffff000013213c18 x26: ffff805f67d06049 [ 1623.574963] x25: 0000000000000000 x24: ffff00001138abb5 [ 1623.580349] x23: 0000000000000fb7 x22: ffff0000117ed000 [ 1623.585734] x21: ffff000011188fd8 x20: ffff805f67d07000 [ 1623.591119] x19: ffff805f67d06061 x18: ffffffffffffffff [ 1623.596505] x17: 0000000000000200 x16: 0000000000000000 [ 1623.601890] x15: ffff0000117ed748 x14: ffff805f67d07000 [ 1623.607276] x13: ffff805f67d0605e x12: 0000000000000000 [ 1623.612661] x11: 0000000000000000 x10: 0000000000000000 [ 1623.618046] x9 : 0000000000000000 x8 : 000000000000000f [ 1623.623432] x7 : ffff805f67d06061 x6 : fffffffffffffffe [ 1623.628817] x5 : 0000000000000012 x4 : ffff00000901d478 [ 1623.634203] x3 : ffff0a00ffffff04 x2 : ffff805f67d07000 [ 1623.639588] x1 : ffff805f67d07000 x0 : ffffffffffffffff [ 1623.644974] Process cat (pid: 11438, stack limit = 0x000000008d4cbc10) [ 1623.651592] Call trace: [ 1623.654068] string+0x28/0x98 [ 1623.657071] vsnprintf+0x368/0x5e8 [ 1623.660517] seq_vprintf+0x70/0x98 [ 1623.668009] seq_printf+0x7c/0xa0 [ 1623.675530] r_show+0xc8/0xf8 [ 1623.682558] seq_read+0x330/0x440 [ 1623.689877] proc_reg_read+0x78/0xd0 [ 1623.697346] __vfs_read+0x60/0x1a0 [ 1623.704564] vfs_read+0x94/0x150 [ 1623.711339] ksys_read+0x6c/0xd8 [ 1623.717939] __arm64_sys_read+0x24/0x30 [ 1623.725077] el0_svc_common+0x120/0x148 [ 1623.732035] el0_svc_handler+0x30/0x40 [ 1623.738757] el0_svc+0x8/0xc [ 1623.744520] Code: d1000406 aa0103e2 54000149 b4000080 (39400085) [ 1623.753441] ---[ end trace f91b6a4937de9835 ]--- [ 1623.760871] Kernel panic - not syncing: Fatal exception [ 1623.768935] SMP: stopping secondary CPUs [ 1623.775718] Kernel Offset: disabled [ 1623.781998] CPU features: 0x002,21006008 [ 1623.788777] Memory Limit: none [ 1623.798329] Starting crashdump kernel... [ 1623.805202] Bye! If io_setup is called successful in try_smi_init() but try_smi_init() goes out_err before calling ipmi_register_smi(), so ipmi_unregister_smi() will not be called while removing module. It leads to the resource that allocated in io_setup() can not be freed, but the name(DEVICE_NAME) of resource is freed while removing the module. It causes use-after-free when cat /proc/ioports. Fix this by calling io_cleanup() while try_smi_init() goes to out_err. and don't call io_cleanup() until io_setup() returns successful to avoid warning prints. Fixes: 93c303d2045b ("ipmi_si: Clean up shutdown a bit") Cc: [email protected] Reported-by: NuoHan Qiao <[email protected]> Suggested-by: Corey Minyard <[email protected]> Signed-off-by: Yang Yingliang <[email protected]> Signed-off-by: Corey Minyard <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int do_hidp_sock_ioctl(struct socket *sock, unsigned int cmd, void __user *argp) { struct hidp_connadd_req ca; struct hidp_conndel_req cd; struct hidp_connlist_req cl; struct hidp_conninfo ci; struct socket *csock; struct socket *isock; int err; BT_DBG("cmd %x arg %p", cmd, argp); switch (cmd) { case HIDPCONNADD: if (!capable(CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(&ca, argp, sizeof(ca))) return -EFAULT; csock = sockfd_lookup(ca.ctrl_sock, &err); if (!csock) return err; isock = sockfd_lookup(ca.intr_sock, &err); if (!isock) { sockfd_put(csock); return err; } err = hidp_connection_add(&ca, csock, isock); if (!err && copy_to_user(argp, &ca, sizeof(ca))) err = -EFAULT; sockfd_put(csock); sockfd_put(isock); return err; case HIDPCONNDEL: if (!capable(CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(&cd, argp, sizeof(cd))) return -EFAULT; return hidp_connection_del(&cd); case HIDPGETCONNLIST: if (copy_from_user(&cl, argp, sizeof(cl))) return -EFAULT; if (cl.cnum <= 0) return -EINVAL; err = hidp_get_connlist(&cl); if (!err && copy_to_user(argp, &cl, sizeof(cl))) return -EFAULT; return err; case HIDPGETCONNINFO: if (copy_from_user(&ci, argp, sizeof(ci))) return -EFAULT; err = hidp_get_conninfo(&ci); if (!err && copy_to_user(argp, &ci, sizeof(ci))) return -EFAULT; return err; } return -EINVAL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-77'], 'message': 'Bluetooth: hidp: fix buffer overflow Struct ca is copied from userspace. It is not checked whether the "name" field is NULL terminated, which allows local users to obtain potentially sensitive information from kernel stack memory, via a HIDPCONNADD command. This vulnerability is similar to CVE-2011-1079. Signed-off-by: Young Xiao <[email protected]> Signed-off-by: Marcel Holtmann <[email protected]> Cc: [email protected]'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int intel_vgpu_mmap(struct mdev_device *mdev, struct vm_area_struct *vma) { unsigned int index; u64 virtaddr; unsigned long req_size, pgoff = 0; pgprot_t pg_prot; struct intel_vgpu *vgpu = mdev_get_drvdata(mdev); index = vma->vm_pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT); if (index >= VFIO_PCI_ROM_REGION_INDEX) return -EINVAL; if (vma->vm_end < vma->vm_start) return -EINVAL; if ((vma->vm_flags & VM_SHARED) == 0) return -EINVAL; if (index != VFIO_PCI_BAR2_REGION_INDEX) return -EINVAL; pg_prot = vma->vm_page_prot; virtaddr = vma->vm_start; req_size = vma->vm_end - vma->vm_start; pgoff = vgpu_aperture_pa_base(vgpu) >> PAGE_SHIFT; return remap_pfn_range(vma, virtaddr, pgoff, req_size, pg_prot); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'drm/i915/gvt: Fix mmap range check This is to fix missed mmap range check on vGPU bar2 region and only allow to map vGPU allocated GMADDR range, which means user space should support sparse mmap to get proper offset for mmap vGPU aperture. And this takes care of actual pgoff in mmap request as original code always does from beginning of vGPU aperture. Fixes: 659643f7d814 ("drm/i915/gvt/kvmgt: add vfio/mdev support to KVMGT") Cc: "Monroy, Rodrigo Axel" <[email protected]> Cc: "Orrala Contreras, Alfredo" <[email protected]> Cc: [email protected] # v4.10+ Reviewed-by: Hang Yuan <[email protected]> Signed-off-by: Zhenyu Wang <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void copyIPv6IfDifferent(void * dest, const void * src) { if(dest != src) { memcpy(dest, src, sizeof(struct in6_addr)); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'pcpserver.c: copyIPv6IfDifferent() check for NULL src argument'</s>
<s>[INST] Given the following code containing errors, provide 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_ext_split(handle_t *handle, struct inode *inode, unsigned int flags, struct ext4_ext_path *path, struct ext4_extent *newext, int at) { struct buffer_head *bh = NULL; int depth = ext_depth(inode); struct ext4_extent_header *neh; struct ext4_extent_idx *fidx; int i = at, k, m, a; ext4_fsblk_t newblock, oldblock; __le32 border; ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */ int err = 0; /* make decision: where to split? */ /* FIXME: now decision is simplest: at current extent */ /* if current leaf will be split, then we should use * border from split point */ if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) { EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!"); return -EFSCORRUPTED; } if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) { border = path[depth].p_ext[1].ee_block; ext_debug("leaf will be split." " next leaf starts at %d\n", le32_to_cpu(border)); } else { border = newext->ee_block; ext_debug("leaf will be added." " next leaf starts at %d\n", le32_to_cpu(border)); } /* * If error occurs, then we break processing * and mark filesystem read-only. index won't * be inserted and tree will be in consistent * state. Next mount will repair buffers too. */ /* * Get array to track all allocated blocks. * We need this to handle errors and free blocks * upon them. */ ablocks = kcalloc(depth, sizeof(ext4_fsblk_t), GFP_NOFS); if (!ablocks) return -ENOMEM; /* allocate all needed blocks */ ext_debug("allocate %d blocks for indexes/leaf\n", depth - at); for (a = 0; a < depth - at; a++) { newblock = ext4_ext_new_meta_block(handle, inode, path, newext, &err, flags); if (newblock == 0) goto cleanup; ablocks[a] = newblock; } /* initialize new leaf */ newblock = ablocks[--a]; if (unlikely(newblock == 0)) { EXT4_ERROR_INODE(inode, "newblock == 0!"); err = -EFSCORRUPTED; goto cleanup; } bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS); if (unlikely(!bh)) { err = -ENOMEM; goto cleanup; } lock_buffer(bh); err = ext4_journal_get_create_access(handle, bh); if (err) goto cleanup; neh = ext_block_hdr(bh); neh->eh_entries = 0; neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0)); neh->eh_magic = EXT4_EXT_MAGIC; neh->eh_depth = 0; /* move remainder of path[depth] to the new leaf */ if (unlikely(path[depth].p_hdr->eh_entries != path[depth].p_hdr->eh_max)) { EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!", path[depth].p_hdr->eh_entries, path[depth].p_hdr->eh_max); err = -EFSCORRUPTED; goto cleanup; } /* start copy from next extent */ m = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++; ext4_ext_show_move(inode, path, newblock, depth); if (m) { struct ext4_extent *ex; ex = EXT_FIRST_EXTENT(neh); memmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m); le16_add_cpu(&neh->eh_entries, m); } ext4_extent_block_csum_set(inode, neh); set_buffer_uptodate(bh); unlock_buffer(bh); err = ext4_handle_dirty_metadata(handle, inode, bh); if (err) goto cleanup; brelse(bh); bh = NULL; /* correct old leaf */ if (m) { err = ext4_ext_get_access(handle, inode, path + depth); if (err) goto cleanup; le16_add_cpu(&path[depth].p_hdr->eh_entries, -m); err = ext4_ext_dirty(handle, inode, path + depth); if (err) goto cleanup; } /* create intermediate indexes */ k = depth - at - 1; if (unlikely(k < 0)) { EXT4_ERROR_INODE(inode, "k %d < 0!", k); err = -EFSCORRUPTED; goto cleanup; } if (k) ext_debug("create %d intermediate indices\n", k); /* insert new index into current index block */ /* current depth stored in i var */ i = depth - 1; while (k--) { oldblock = newblock; newblock = ablocks[--a]; bh = sb_getblk(inode->i_sb, newblock); if (unlikely(!bh)) { err = -ENOMEM; goto cleanup; } lock_buffer(bh); err = ext4_journal_get_create_access(handle, bh); if (err) goto cleanup; neh = ext_block_hdr(bh); neh->eh_entries = cpu_to_le16(1); neh->eh_magic = EXT4_EXT_MAGIC; neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0)); neh->eh_depth = cpu_to_le16(depth - i); fidx = EXT_FIRST_INDEX(neh); fidx->ei_block = border; ext4_idx_store_pblock(fidx, oldblock); ext_debug("int.index at %d (block %llu): %u -> %llu\n", i, newblock, le32_to_cpu(border), oldblock); /* move remainder of path[i] to the new index block */ if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) != EXT_LAST_INDEX(path[i].p_hdr))) { EXT4_ERROR_INODE(inode, "EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!", le32_to_cpu(path[i].p_ext->ee_block)); err = -EFSCORRUPTED; goto cleanup; } /* start copy indexes */ m = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++; ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx, EXT_MAX_INDEX(path[i].p_hdr)); ext4_ext_show_move(inode, path, newblock, i); if (m) { memmove(++fidx, path[i].p_idx, sizeof(struct ext4_extent_idx) * m); le16_add_cpu(&neh->eh_entries, m); } ext4_extent_block_csum_set(inode, neh); set_buffer_uptodate(bh); unlock_buffer(bh); err = ext4_handle_dirty_metadata(handle, inode, bh); if (err) goto cleanup; brelse(bh); bh = NULL; /* correct old index */ if (m) { err = ext4_ext_get_access(handle, inode, path + i); if (err) goto cleanup; le16_add_cpu(&path[i].p_hdr->eh_entries, -m); err = ext4_ext_dirty(handle, inode, path + i); if (err) goto cleanup; } i--; } /* insert new index */ err = ext4_ext_insert_index(handle, inode, path + at, le32_to_cpu(border), newblock); cleanup: if (bh) { if (buffer_locked(bh)) unlock_buffer(bh); brelse(bh); } if (err) { /* free all allocated blocks in error case */ for (i = 0; i < depth; i++) { if (!ablocks[i]) continue; ext4_free_blocks(handle, inode, NULL, ablocks[i], 1, EXT4_FREE_BLOCKS_METADATA); } } kfree(ablocks); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-908'], 'message': 'ext4: zero out the unused memory region in the extent tree block This commit zeroes out the unused memory region in the buffer_head corresponding to the extent metablock after writing the extent header and the corresponding extent node entries. This is done to prevent random uninitialized data from getting into the filesystem when the extent block is synced. This fixes CVE-2019-11833. Signed-off-by: Sriram Rajagopalan <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> Cc: [email protected]'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void JPXStream::init() { Object oLen, cspace, smaskInData; if (getDict()) { oLen = getDict()->lookup("Length"); cspace = getDict()->lookup("ColorSpace"); smaskInData = getDict()->lookup("SMaskInData"); } int bufSize = BUFFER_INITIAL_SIZE; if (oLen.isInt()) bufSize = oLen.getInt(); bool indexed = false; if (cspace.isArray() && cspace.arrayGetLength() > 0) { const Object cstype = cspace.arrayGet(0); if (cstype.isName("Indexed")) indexed = true; } priv->smaskInData = 0; if (smaskInData.isInt()) priv->smaskInData = smaskInData.getInt(); int length = 0; unsigned char *buf = str->toUnsignedChars(&length, bufSize); priv->init2(OPJ_CODEC_JP2, buf, length, indexed); gfree(buf); if (priv->image) { int numComps = (priv->image) ? priv->image->numcomps : 1; int alpha = 0; if (priv->image) { if (priv->image->color_space == OPJ_CLRSPC_SRGB && numComps == 4) { numComps = 3; alpha = 1; } else if (priv->image->color_space == OPJ_CLRSPC_SYCC && numComps == 4) { numComps = 3; alpha = 1; } else if (numComps == 2) { numComps = 1; alpha = 1; } else if (numComps > 4) { numComps = 4; alpha = 1; } else { alpha = 0; } } priv->npixels = priv->image->comps[0].w * priv->image->comps[0].h; priv->ncomps = priv->image->numcomps; if (alpha == 1 && priv->smaskInData == 0) priv->ncomps--; for (int component = 0; component < priv->ncomps; component++) { if (priv->image->comps[component].data == nullptr) { close(); break; } unsigned char *cdata = (unsigned char *)priv->image->comps[component].data; int adjust = 0; int depth = priv->image->comps[component].prec; if (priv->image->comps[component].prec > 8) adjust = priv->image->comps[component].prec - 8; int sgndcorr = 0; if (priv->image->comps[component].sgnd) sgndcorr = 1 << (priv->image->comps[0].prec - 1); for (int i = 0; i < priv->npixels; i++) { int r = priv->image->comps[component].data[i]; *(cdata++) = adjustComp(r, adjust, depth, sgndcorr, indexed); } } } else { priv->npixels = 0; } priv->counter = 0; priv->ccounter = 0; priv->inited = true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'JPEG2000Stream: fail gracefully if not all components have the same WxH I think this is just a mistake, or at least the only file we have with this scenario is a fuzzed one'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: upnp_redirect(const char * rhost, unsigned short eport, const char * iaddr, unsigned short iport, const char * protocol, const char * desc, unsigned int leaseduration) { int proto, r; char iaddr_old[32]; char rhost_old[32]; unsigned short iport_old; struct in_addr address; unsigned int timestamp; proto = proto_atoi(protocol); if(inet_aton(iaddr, &address) <= 0) { syslog(LOG_ERR, "inet_aton(%s) FAILED", iaddr); return -1; } if(!check_upnp_rule_against_permissions(upnppermlist, num_upnpperm, eport, address, iport)) { syslog(LOG_INFO, "redirection permission check failed for " "%hu->%s:%hu %s", eport, iaddr, iport, protocol); return -3; } /* IGDv1 (WANIPConnection:1 Service Template Version 1.01 / Nov 12, 2001) * - 2.2.20.PortMappingDescription : * Overwriting Previous / Existing Port Mappings: * If the RemoteHost, ExternalPort, PortMappingProtocol and InternalClient * are exactly the same as an existing mapping, the existing mapping values * for InternalPort, PortMappingDescription, PortMappingEnabled and * PortMappingLeaseDuration are overwritten. * Rejecting a New Port Mapping: * In cases where the RemoteHost, ExternalPort and PortMappingProtocol * are the same as an existing mapping, but the InternalClient is * different, the action is rejected with an appropriate error. * Add or Reject New Port Mapping behavior based on vendor implementation: * In cases where the ExternalPort, PortMappingProtocol and InternalClient * are the same, but RemoteHost is different, the vendor can choose to * support both mappings simultaneously, or reject the second mapping * with an appropriate error. * * - 2.4.16.AddPortMapping * This action creates a new port mapping or overwrites an existing * mapping with the same internal client. If the ExternalPort and * PortMappingProtocol pair is already mapped to another internal client, * an error is returned. * * IGDv2 (WANIPConnection:2 Service Standardized DCP (SDCP) Sep 10, 2010) * Protocol ExternalPort RemoteHost InternalClient Result * = = ≠ ≠ Failure * = = ≠ = Failure or success * (vendor specific) * = = = ≠ Failure * = = = = Success (overwrite) */ rhost_old[0] = '\0'; r = get_redirect_rule(ext_if_name, eport, proto, iaddr_old, sizeof(iaddr_old), &iport_old, 0, 0, rhost_old, sizeof(rhost_old), &timestamp, 0, 0); if(r == 0) { if(strcmp(iaddr, iaddr_old)==0 && ((rhost == NULL && rhost_old[0]=='\0') || (rhost && (strcmp(rhost, "*") == 0) && rhost_old[0]=='\0') || (rhost && (strcmp(rhost, rhost_old) == 0)))) { syslog(LOG_INFO, "updating existing port mapping %hu %s (rhost '%s') => %s:%hu", eport, protocol, rhost_old, iaddr_old, iport_old); timestamp = (leaseduration > 0) ? upnp_time() + leaseduration : 0; if(iport != iport_old) { r = update_portmapping(ext_if_name, eport, proto, iport, desc, timestamp); } else { r = update_portmapping_desc_timestamp(ext_if_name, eport, proto, desc, timestamp); } #ifdef ENABLE_LEASEFILE if(r == 0) { lease_file_remove(eport, proto); lease_file_add(eport, iaddr, iport, proto, desc, timestamp); } #endif /* ENABLE_LEASEFILE */ return r; } else { syslog(LOG_INFO, "port %hu %s (rhost '%s') already redirected to %s:%hu", eport, protocol, rhost_old, iaddr_old, iport_old); return -2; } #ifdef CHECK_PORTINUSE } else if (port_in_use(ext_if_name, eport, proto, iaddr, iport) > 0) { syslog(LOG_INFO, "port %hu protocol %s already in use", eport, protocol); return -4; #endif /* CHECK_PORTINUSE */ } else { timestamp = (leaseduration > 0) ? upnp_time() + leaseduration : 0; syslog(LOG_INFO, "redirecting port %hu to %s:%hu protocol %s for: %s", eport, iaddr, iport, protocol, desc); return upnp_redirect_internal(rhost, eport, iaddr, iport, proto, desc, timestamp); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'upnp_redirect(): accept NULL desc argument'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns) { int r; static const char resp[] = "<u:%sResponse " "xmlns:u=\"%s\">" "<OutboundPinholeTimeout>%d</OutboundPinholeTimeout>" "</u:%sResponse>"; char body[512]; int bodylen; struct NameValueParserData data; char * int_ip, * int_port, * rem_host, * rem_port, * protocol; int opt=0; /*int proto=0;*/ unsigned short iport, rport; if (GETFLAG(IPV6FCFWDISABLEDMASK)) { SoapError(h, 702, "FirewallDisabled"); return; } ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data); int_ip = GetValueFromNameValueList(&data, "InternalClient"); int_port = GetValueFromNameValueList(&data, "InternalPort"); rem_host = GetValueFromNameValueList(&data, "RemoteHost"); rem_port = GetValueFromNameValueList(&data, "RemotePort"); protocol = GetValueFromNameValueList(&data, "Protocol"); if (!int_port || !ext_port || !protocol) { ClearNameValueList(&data); SoapError(h, 402, "Invalid Args"); return; } rport = (unsigned short)atoi(rem_port); iport = (unsigned short)atoi(int_port); /*proto = atoi(protocol);*/ syslog(LOG_INFO, "%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s", action, int_ip, iport,rem_host, rport, protocol); /* TODO */ r = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/ switch(r) { case 1: /* success */ bodylen = snprintf(body, sizeof(body), resp, action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/, opt, action); BuildSendAndCloseSoapResp(h, body, bodylen); break; case -5: /* Protocol not supported */ SoapError(h, 705, "ProtocolNotSupported"); break; default: SoapError(h, 501, "ActionFailed"); } ClearNameValueList(&data); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'fix error from commit 13585f15c7f7dc28bbbba1661efb280d530d114c'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: updateDevice(const struct header * headers, time_t t) { struct device ** pp = &devlist; struct device * p = *pp; /* = devlist; */ while(p) { if( p->headers[HEADER_NT].l == headers[HEADER_NT].l && (0==memcmp(p->headers[HEADER_NT].p, headers[HEADER_NT].p, headers[HEADER_NT].l)) && p->headers[HEADER_USN].l == headers[HEADER_USN].l && (0==memcmp(p->headers[HEADER_USN].p, headers[HEADER_USN].p, headers[HEADER_USN].l)) ) { /*printf("found! %d\n", (int)(t - p->t));*/ syslog(LOG_DEBUG, "device updated : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p); p->t = t; /* update Location ! */ if(headers[HEADER_LOCATION].l > p->headers[HEADER_LOCATION].l) { struct device * tmp; tmp = realloc(p, sizeof(struct device) + headers[0].l+headers[1].l+headers[2].l); if(!tmp) /* allocation error */ { syslog(LOG_ERR, "updateDevice() : memory allocation error"); free(p); return 0; } p = tmp; *pp = p; } memcpy(p->data + p->headers[0].l + p->headers[1].l, headers[2].p, headers[2].l); /* TODO : check p->headers[HEADER_LOCATION].l */ return 0; } pp = &p->next; p = *pp; /* p = p->next; */ } syslog(LOG_INFO, "new device discovered : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p); /* add */ { char * pc; int i; p = malloc( sizeof(struct device) + headers[0].l+headers[1].l+headers[2].l ); if(!p) { syslog(LOG_ERR, "updateDevice(): cannot allocate memory"); return -1; } p->next = devlist; p->t = t; pc = p->data; for(i = 0; i < 3; i++) { p->headers[i].p = pc; p->headers[i].l = headers[i].l; memcpy(pc, headers[i].p, headers[i].l); pc += headers[i].l; } devlist = p; sendNotifications(NOTIF_NEW, p, NULL); } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'updateDevice() remove element from the list when realloc fails'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: queue_action(uschar *id, int action, uschar **argv, int argc, int recipients_arg) { int i, j; BOOL yield = TRUE; BOOL removed = FALSE; struct passwd *pw; uschar *doing = NULL; uschar *username; uschar *errmsg; uschar spoolname[32]; /* Set the global message_id variable, used when re-writing spool files. This also causes message ids to be added to log messages. */ Ustrcpy(message_id, id); /* The "actions" that just list the files do not require any locking to be done. Only admin users may read the spool files. */ if (action >= MSG_SHOW_BODY) { int fd, i, rc; uschar *subdirectory, *suffix; if (!f.admin_user) { printf("Permission denied\n"); return FALSE; } if (recipients_arg < argc) { printf("*** Only one message can be listed at once\n"); return FALSE; } if (action == MSG_SHOW_BODY) { subdirectory = US"input"; suffix = US"-D"; } else if (action == MSG_SHOW_HEADER) { subdirectory = US"input"; suffix = US"-H"; } else { subdirectory = US"msglog"; suffix = US""; } for (i = 0; i < 2; i++) { message_subdir[0] = split_spool_directory == (i == 0) ? id[5] : 0; if ((fd = Uopen(spool_fname(subdirectory, message_subdir, id, suffix), O_RDONLY, 0)) >= 0) break; if (i == 0) continue; printf("Failed to open %s file for %s%s: %s\n", subdirectory, id, suffix, strerror(errno)); if (action == MSG_SHOW_LOG && !message_logs) printf("(No message logs are being created because the message_logs " "option is false.)\n"); return FALSE; } while((rc = read(fd, big_buffer, big_buffer_size)) > 0) rc = write(fileno(stdout), big_buffer, rc); (void)close(fd); return TRUE; } /* For actions that actually act, open and lock the data file to ensure that no other process is working on this message. If the file does not exist, continue only if the action is remove and the user is an admin user, to allow for tidying up broken states. */ if ((deliver_datafile = spool_open_datafile(id)) < 0) if (errno == ENOENT) { yield = FALSE; printf("Spool data file for %s does not exist\n", id); if (action != MSG_REMOVE || !f.admin_user) return FALSE; printf("Continuing, to ensure all files removed\n"); } else { if (errno == 0) printf("Message %s is locked\n", id); else printf("Couldn't open spool file for %s: %s\n", id, strerror(errno)); return FALSE; } /* Read the spool header file for the message. Again, continue after an error only in the case of deleting by an administrator. Setting the third argument false causes it to look both in the main spool directory and in the appropriate subdirectory, and set message_subdir according to where it found the message. */ sprintf(CS spoolname, "%s-H", id); if (spool_read_header(spoolname, TRUE, FALSE) != spool_read_OK) { yield = FALSE; if (errno != ERRNO_SPOOLFORMAT) printf("Spool read error for %s: %s\n", spoolname, strerror(errno)); else printf("Spool format error for %s\n", spoolname); if (action != MSG_REMOVE || !f.admin_user) { (void)close(deliver_datafile); deliver_datafile = -1; return FALSE; } printf("Continuing to ensure all files removed\n"); } /* Check that the user running this process is entitled to operate on this message. Only admin users may freeze/thaw, add/cancel recipients, or otherwise mess about, but the original sender is permitted to remove a message. That's why we leave this check until after the headers are read. */ if (!f.admin_user && (action != MSG_REMOVE || real_uid != originator_uid)) { printf("Permission denied\n"); (void)close(deliver_datafile); deliver_datafile = -1; return FALSE; } /* Set up the user name for logging. */ pw = getpwuid(real_uid); username = (pw != NULL)? US pw->pw_name : string_sprintf("uid %ld", (long int)real_uid); /* Take the necessary action. */ if (action != MSG_SHOW_COPY) printf("Message %s ", id); switch(action) { case MSG_SHOW_COPY: { transport_ctx tctx = {{0}}; deliver_in_buffer = store_malloc(DELIVER_IN_BUFFER_SIZE); deliver_out_buffer = store_malloc(DELIVER_OUT_BUFFER_SIZE); tctx.u.fd = 1; transport_write_message(&tctx, 0); break; } case MSG_FREEZE: if (f.deliver_freeze) { yield = FALSE; printf("is already frozen\n"); } else { f.deliver_freeze = TRUE; f.deliver_manual_thaw = FALSE; deliver_frozen_at = time(NULL); if (spool_write_header(id, SW_MODIFYING, &errmsg) >= 0) { printf("is now frozen\n"); log_write(0, LOG_MAIN, "frozen by %s", username); } else { yield = FALSE; printf("could not be frozen: %s\n", errmsg); } } break; case MSG_THAW: if (!f.deliver_freeze) { yield = FALSE; printf("is not frozen\n"); } else { f.deliver_freeze = FALSE; f.deliver_manual_thaw = TRUE; if (spool_write_header(id, SW_MODIFYING, &errmsg) >= 0) { printf("is no longer frozen\n"); log_write(0, LOG_MAIN, "unfrozen by %s", username); } else { yield = FALSE; printf("could not be unfrozen: %s\n", errmsg); } } break; /* We must ensure all files are removed from both the input directory and the appropriate subdirectory, to clean up cases when there are odd files left lying around in odd places. In the normal case message_subdir will have been set correctly by spool_read_header, but as this is a rare operation, just run everything twice. */ case MSG_REMOVE: { uschar suffix[3]; suffix[0] = '-'; suffix[2] = 0; message_subdir[0] = id[5]; for (j = 0; j < 2; message_subdir[0] = 0, j++) { uschar * fname = spool_fname(US"msglog", message_subdir, id, US""); DEBUG(D_any) debug_printf(" removing %s", fname); if (Uunlink(fname) < 0) { if (errno != ENOENT) { yield = FALSE; printf("Error while removing %s: %s\n", fname, strerror(errno)); } else DEBUG(D_any) debug_printf(" (no file)\n"); } else { removed = TRUE; DEBUG(D_any) debug_printf(" (ok)\n"); } for (i = 0; i < 3; i++) { uschar * fname; suffix[1] = (US"DHJ")[i]; fname = spool_fname(US"input", message_subdir, id, suffix); DEBUG(D_any) debug_printf(" removing %s", fname); if (Uunlink(fname) < 0) { if (errno != ENOENT) { yield = FALSE; printf("Error while removing %s: %s\n", fname, strerror(errno)); } else DEBUG(D_any) debug_printf(" (no file)\n"); } else { removed = TRUE; DEBUG(D_any) debug_printf(" (done)\n"); } } } /* In the common case, the datafile is open (and locked), so give the obvious message. Otherwise be more specific. */ if (deliver_datafile >= 0) printf("has been removed\n"); else printf("has been removed or did not exist\n"); if (removed) { log_write(0, LOG_MAIN, "removed by %s", username); log_write(0, LOG_MAIN, "Completed"); } break; } case MSG_MARK_ALL_DELIVERED: for (i = 0; i < recipients_count; i++) { tree_add_nonrecipient(recipients_list[i].address); } if (spool_write_header(id, SW_MODIFYING, &errmsg) >= 0) { printf("has been modified\n"); for (i = 0; i < recipients_count; i++) log_write(0, LOG_MAIN, "address <%s> marked delivered by %s", recipients_list[i].address, username); } else { yield = FALSE; printf("- could not mark all delivered: %s\n", errmsg); } break; case MSG_EDIT_SENDER: if (recipients_arg < argc - 1) { yield = FALSE; printf("- only one sender address can be specified\n"); break; } doing = US"editing sender"; /* Fall through */ case MSG_ADD_RECIPIENT: if (doing == NULL) doing = US"adding recipient"; /* Fall through */ case MSG_MARK_DELIVERED: if (doing == NULL) doing = US"marking as delivered"; /* Common code for EDIT_SENDER, ADD_RECIPIENT, & MARK_DELIVERED */ if (recipients_arg >= argc) { yield = FALSE; printf("- error while %s: no address given\n", doing); break; } for (; recipients_arg < argc; recipients_arg++) { int start, end, domain; uschar *errmess; uschar *recipient = parse_extract_address(argv[recipients_arg], &errmess, &start, &end, &domain, (action == MSG_EDIT_SENDER)); if (recipient == NULL) { yield = FALSE; printf("- error while %s:\n bad address %s: %s\n", doing, argv[recipients_arg], errmess); } else if (recipient[0] != 0 && domain == 0) { yield = FALSE; printf("- error while %s:\n bad address %s: " "domain missing\n", doing, argv[recipients_arg]); } else { if (action == MSG_ADD_RECIPIENT) { #ifdef SUPPORT_I18N if (string_is_utf8(recipient)) allow_utf8_domains = message_smtputf8 = TRUE; #endif receive_add_recipient(recipient, -1); log_write(0, LOG_MAIN, "recipient <%s> added by %s", recipient, username); } else if (action == MSG_MARK_DELIVERED) { for (i = 0; i < recipients_count; i++) if (Ustrcmp(recipients_list[i].address, recipient) == 0) break; if (i >= recipients_count) { printf("- error while %s:\n %s is not a recipient:" " message not updated\n", doing, recipient); yield = FALSE; } else { tree_add_nonrecipient(recipients_list[i].address); log_write(0, LOG_MAIN, "address <%s> marked delivered by %s", recipient, username); } } else /* MSG_EDIT_SENDER */ { #ifdef SUPPORT_I18N if (string_is_utf8(recipient)) allow_utf8_domains = message_smtputf8 = TRUE; #endif sender_address = recipient; log_write(0, LOG_MAIN, "sender address changed to <%s> by %s", recipient, username); } } } if (yield) if (spool_write_header(id, SW_MODIFYING, &errmsg) >= 0) printf("has been modified\n"); else { yield = FALSE; printf("- while %s: %s\n", doing, errmsg); } break; } /* Closing the datafile releases the lock and permits other processes to operate on the message (if it still exists). */ if (deliver_datafile >= 0) { (void)close(deliver_datafile); deliver_datafile = -1; } return yield; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-78'], 'message': 'Events: raise msg:fail:internal & msg:complete for -Mrm. Bug 2310'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: deliver_message(uschar *id, BOOL forced, BOOL give_up) { int i, rc; int final_yield = DELIVER_ATTEMPTED_NORMAL; time_t now = time(NULL); address_item *addr_last = NULL; uschar *filter_message = NULL; int process_recipients = RECIP_ACCEPT; open_db dbblock; open_db *dbm_file; extern int acl_where; uschar *info = queue_run_pid == (pid_t)0 ? string_sprintf("delivering %s", id) : string_sprintf("delivering %s (queue run pid %d)", id, queue_run_pid); /* If the D_process_info bit is on, set_process_info() will output debugging information. If not, we want to show this initial information if D_deliver or D_queue_run is set or in verbose mode. */ set_process_info("%s", info); if ( !(debug_selector & D_process_info) && (debug_selector & (D_deliver|D_queue_run|D_v)) ) debug_printf("%s\n", info); /* Ensure that we catch any subprocesses that are created. Although Exim sets SIG_DFL as its initial default, some routes through the code end up here with it set to SIG_IGN - cases where a non-synchronous delivery process has been forked, but no re-exec has been done. We use sigaction rather than plain signal() on those OS where SA_NOCLDWAIT exists, because we want to be sure it is turned off. (There was a problem on AIX with this.) */ #ifdef SA_NOCLDWAIT { struct sigaction act; act.sa_handler = SIG_DFL; sigemptyset(&(act.sa_mask)); act.sa_flags = 0; sigaction(SIGCHLD, &act, NULL); } #else signal(SIGCHLD, SIG_DFL); #endif /* Make the forcing flag available for routers and transports, set up the global message id field, and initialize the count for returned files and the message size. This use of strcpy() is OK because the length id is checked when it is obtained from a command line (the -M or -q options), and otherwise it is known to be a valid message id. */ Ustrcpy(message_id, id); f.deliver_force = forced; return_count = 0; message_size = 0; /* Initialize some flags */ update_spool = FALSE; remove_journal = TRUE; /* Set a known context for any ACLs we call via expansions */ acl_where = ACL_WHERE_DELIVERY; /* Reset the random number generator, so that if several delivery processes are started from a queue runner that has already used random numbers (for sorting), they don't all get the same sequence. */ random_seed = 0; /* Open and lock the message's data file. Exim locks on this one because the header file may get replaced as it is re-written during the delivery process. Any failures cause messages to be written to the log, except for missing files while queue running - another process probably completed delivery. As part of opening the data file, message_subdir gets set. */ if ((deliver_datafile = spool_open_datafile(id)) < 0) return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */ /* The value of message_size at this point has been set to the data length, plus one for the blank line that notionally precedes the data. */ /* Now read the contents of the header file, which will set up the headers in store, and also the list of recipients and the tree of non-recipients and assorted flags. It updates message_size. If there is a reading or format error, give up; if the message has been around for sufficiently long, remove it. */ { uschar * spoolname = string_sprintf("%s-H", id); if ((rc = spool_read_header(spoolname, TRUE, TRUE)) != spool_read_OK) { if (errno == ERRNO_SPOOLFORMAT) { struct stat statbuf; if (Ustat(spool_fname(US"input", message_subdir, spoolname, US""), &statbuf) == 0) log_write(0, LOG_MAIN, "Format error in spool file %s: " "size=" OFF_T_FMT, spoolname, statbuf.st_size); else log_write(0, LOG_MAIN, "Format error in spool file %s", spoolname); } else log_write(0, LOG_MAIN, "Error reading spool file %s: %s", spoolname, strerror(errno)); /* If we managed to read the envelope data, received_time contains the time the message was received. Otherwise, we can calculate it from the message id. */ if (rc != spool_read_hdrerror) { received_time.tv_sec = received_time.tv_usec = 0; /*XXX subsec precision?*/ for (i = 0; i < 6; i++) received_time.tv_sec = received_time.tv_sec * BASE_62 + tab62[id[i] - '0']; } /* If we've had this malformed message too long, sling it. */ if (now - received_time.tv_sec > keep_malformed) { Uunlink(spool_fname(US"msglog", message_subdir, id, US"")); Uunlink(spool_fname(US"input", message_subdir, id, US"-D")); Uunlink(spool_fname(US"input", message_subdir, id, US"-H")); Uunlink(spool_fname(US"input", message_subdir, id, US"-J")); log_write(0, LOG_MAIN, "Message removed because older than %s", readconf_printtime(keep_malformed)); } (void)close(deliver_datafile); deliver_datafile = -1; return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */ } } /* The spool header file has been read. Look to see if there is an existing journal file for this message. If there is, it means that a previous delivery attempt crashed (program or host) before it could update the spool header file. Read the list of delivered addresses from the journal and add them to the nonrecipients tree. Then update the spool file. We can leave the journal in existence, as it will get further successful deliveries added to it in this run, and it will be deleted if this function gets to its end successfully. Otherwise it might be needed again. */ { uschar * fname = spool_fname(US"input", message_subdir, id, US"-J"); FILE * jread; if ( (journal_fd = Uopen(fname, O_RDWR|O_APPEND #ifdef O_CLOEXEC | O_CLOEXEC #endif #ifdef O_NOFOLLOW | O_NOFOLLOW #endif , SPOOL_MODE)) >= 0 && lseek(journal_fd, 0, SEEK_SET) == 0 && (jread = fdopen(journal_fd, "rb")) ) { while (Ufgets(big_buffer, big_buffer_size, jread)) { int n = Ustrlen(big_buffer); big_buffer[n-1] = 0; tree_add_nonrecipient(big_buffer); DEBUG(D_deliver) debug_printf("Previously delivered address %s taken from " "journal file\n", big_buffer); } rewind(jread); if ((journal_fd = dup(fileno(jread))) < 0) journal_fd = fileno(jread); else (void) fclose(jread); /* Try to not leak the FILE resource */ /* Panic-dies on error */ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } else if (errno != ENOENT) { log_write(0, LOG_MAIN|LOG_PANIC, "attempt to open journal for reading gave: " "%s", strerror(errno)); return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */ } /* A null recipients list indicates some kind of disaster. */ if (!recipients_list) { (void)close(deliver_datafile); deliver_datafile = -1; log_write(0, LOG_MAIN, "Spool error: no recipients for %s", fname); return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */ } } /* Handle a message that is frozen. There are a number of different things that can happen, but in the default situation, unless forced, no delivery is attempted. */ if (f.deliver_freeze) { #ifdef SUPPORT_MOVE_FROZEN_MESSAGES /* Moving to another directory removes the message from Exim's view. Other tools must be used to deal with it. Logging of this action happens in spool_move_message() and its subfunctions. */ if ( move_frozen_messages && spool_move_message(id, message_subdir, US"", US"F") ) return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */ #endif /* For all frozen messages (bounces or not), timeout_frozen_after sets the maximum time to keep messages that are frozen. Thaw if we reach it, with a flag causing all recipients to be failed. The time is the age of the message, not the time since freezing. */ if (timeout_frozen_after > 0 && message_age >= timeout_frozen_after) { log_write(0, LOG_MAIN, "cancelled by timeout_frozen_after"); process_recipients = RECIP_FAIL_TIMEOUT; } /* For bounce messages (and others with no sender), thaw if the error message ignore timer is exceeded. The message will be discarded if this delivery fails. */ else if (!*sender_address && message_age >= ignore_bounce_errors_after) log_write(0, LOG_MAIN, "Unfrozen by errmsg timer"); /* If this is a bounce message, or there's no auto thaw, or we haven't reached the auto thaw time yet, and this delivery is not forced by an admin user, do not attempt delivery of this message. Note that forced is set for continuing messages down the same channel, in order to skip load checking and ignore hold domains, but we don't want unfreezing in that case. */ else { if ( ( sender_address[0] == 0 || auto_thaw <= 0 || now <= deliver_frozen_at + auto_thaw ) && ( !forced || !f.deliver_force_thaw || !f.admin_user || continue_hostname ) ) { (void)close(deliver_datafile); deliver_datafile = -1; log_write(L_skip_delivery, LOG_MAIN, "Message is frozen"); return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */ } /* If delivery was forced (by an admin user), assume a manual thaw. Otherwise it's an auto thaw. */ if (forced) { f.deliver_manual_thaw = TRUE; log_write(0, LOG_MAIN, "Unfrozen by forced delivery"); } else log_write(0, LOG_MAIN, "Unfrozen by auto-thaw"); } /* We get here if any of the rules for unfreezing have triggered. */ f.deliver_freeze = FALSE; update_spool = TRUE; } /* Open the message log file if we are using them. This records details of deliveries, deferments, and failures for the benefit of the mail administrator. The log is not used by exim itself to track the progress of a message; that is done by rewriting the header spool file. */ if (message_logs) { uschar * fname = spool_fname(US"msglog", message_subdir, id, US""); uschar * error; int fd; if ((fd = open_msglog_file(fname, SPOOL_MODE, &error)) < 0) { log_write(0, LOG_MAIN|LOG_PANIC, "Couldn't %s message log %s: %s", error, fname, strerror(errno)); return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */ } /* Make a C stream out of it. */ if (!(message_log = fdopen(fd, "a"))) { log_write(0, LOG_MAIN|LOG_PANIC, "Couldn't fdopen message log %s: %s", fname, strerror(errno)); return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */ } } /* If asked to give up on a message, log who did it, and set the action for all the addresses. */ if (give_up) { struct passwd *pw = getpwuid(real_uid); log_write(0, LOG_MAIN, "cancelled by %s", pw ? US pw->pw_name : string_sprintf("uid %ld", (long int)real_uid)); process_recipients = RECIP_FAIL; } /* Otherwise, if there are too many Received: headers, fail all recipients. */ else if (received_count > received_headers_max) process_recipients = RECIP_FAIL_LOOP; /* Otherwise, if a system-wide, address-independent message filter is specified, run it now, except in the case when we are failing all recipients as a result of timeout_frozen_after. If the system filter yields "delivered", then ignore the true recipients of the message. Failure of the filter file is logged, and the delivery attempt fails. */ else if (system_filter && process_recipients != RECIP_FAIL_TIMEOUT) { int rc; int filtertype; ugid_block ugid; redirect_block redirect; if (system_filter_uid_set) { ugid.uid = system_filter_uid; ugid.gid = system_filter_gid; ugid.uid_set = ugid.gid_set = TRUE; } else { ugid.uid_set = ugid.gid_set = FALSE; } return_path = sender_address; f.enable_dollar_recipients = TRUE; /* Permit $recipients in system filter */ f.system_filtering = TRUE; /* Any error in the filter file causes a delivery to be abandoned. */ redirect.string = system_filter; redirect.isfile = TRUE; redirect.check_owner = redirect.check_group = FALSE; redirect.owners = NULL; redirect.owngroups = NULL; redirect.pw = NULL; redirect.modemask = 0; DEBUG(D_deliver|D_filter) debug_printf("running system filter\n"); rc = rda_interpret( &redirect, /* Where the data is */ RDO_DEFER | /* Turn on all the enabling options */ RDO_FAIL | /* Leave off all the disabling options */ RDO_FILTER | RDO_FREEZE | RDO_REALLOG | RDO_REWRITE, NULL, /* No :include: restriction (not used in filter) */ NULL, /* No sieve vacation directory (not sieve!) */ NULL, /* No sieve enotify mailto owner (not sieve!) */ NULL, /* No sieve user address (not sieve!) */ NULL, /* No sieve subaddress (not sieve!) */ &ugid, /* uid/gid data */ &addr_new, /* Where to hang generated addresses */ &filter_message, /* Where to put error message */ NULL, /* Don't skip syntax errors */ &filtertype, /* Will always be set to FILTER_EXIM for this call */ US"system filter"); /* For error messages */ DEBUG(D_deliver|D_filter) debug_printf("system filter returned %d\n", rc); if (rc == FF_ERROR || rc == FF_NONEXIST) { (void)close(deliver_datafile); deliver_datafile = -1; log_write(0, LOG_MAIN|LOG_PANIC, "Error in system filter: %s", string_printing(filter_message)); return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */ } /* Reset things. If the filter message is an empty string, which can happen for a filter "fail" or "freeze" command with no text, reset it to NULL. */ f.system_filtering = FALSE; f.enable_dollar_recipients = FALSE; if (filter_message && filter_message[0] == 0) filter_message = NULL; /* Save the values of the system filter variables so that user filters can use them. */ memcpy(filter_sn, filter_n, sizeof(filter_sn)); /* The filter can request that delivery of the original addresses be deferred. */ if (rc == FF_DEFER) { process_recipients = RECIP_DEFER; deliver_msglog("Delivery deferred by system filter\n"); log_write(0, LOG_MAIN, "Delivery deferred by system filter"); } /* The filter can request that a message be frozen, but this does not take place if the message has been manually thawed. In that case, we must unset "delivered", which is forced by the "freeze" command to make -bF work properly. */ else if (rc == FF_FREEZE && !f.deliver_manual_thaw) { f.deliver_freeze = TRUE; deliver_frozen_at = time(NULL); process_recipients = RECIP_DEFER; frozen_info = string_sprintf(" by the system filter%s%s", filter_message ? US": " : US"", filter_message ? filter_message : US""); } /* The filter can request that a message be failed. The error message may be quite long - it is sent back to the sender in the bounce - but we don't want to fill up the log with repetitions of it. If it starts with << then the text between << and >> is written to the log, with the rest left for the bounce message. */ else if (rc == FF_FAIL) { uschar *colon = US""; uschar *logmsg = US""; int loglen = 0; process_recipients = RECIP_FAIL_FILTER; if (filter_message) { uschar *logend; colon = US": "; if ( filter_message[0] == '<' && filter_message[1] == '<' && (logend = Ustrstr(filter_message, ">>")) ) { logmsg = filter_message + 2; loglen = logend - logmsg; filter_message = logend + 2; if (filter_message[0] == 0) filter_message = NULL; } else { logmsg = filter_message; loglen = Ustrlen(filter_message); } } log_write(0, LOG_MAIN, "cancelled by system filter%s%.*s", colon, loglen, logmsg); } /* Delivery can be restricted only to those recipients (if any) that the filter specified. */ else if (rc == FF_DELIVERED) { process_recipients = RECIP_IGNORE; if (addr_new) log_write(0, LOG_MAIN, "original recipients ignored (system filter)"); else log_write(0, LOG_MAIN, "=> discarded (system filter)"); } /* If any new addresses were created by the filter, fake up a "parent" for them. This is necessary for pipes, etc., which are expected to have parents, and it also gives some sensible logging for others. Allow pipes, files, and autoreplies, and run them as the filter uid if set, otherwise as the current uid. */ if (addr_new) { int uid = (system_filter_uid_set)? system_filter_uid : geteuid(); int gid = (system_filter_gid_set)? system_filter_gid : getegid(); /* The text "system-filter" is tested in transport_set_up_command() and in set_up_shell_command() in the pipe transport, to enable them to permit $recipients, so don't change it here without also changing it there. */ address_item *p = addr_new; address_item *parent = deliver_make_addr(US"system-filter", FALSE); parent->domain = string_copylc(qualify_domain_recipient); parent->local_part = US"system-filter"; /* As part of this loop, we arrange for addr_last to end up pointing at the final address. This is used if we go on to add addresses for the original recipients. */ while (p) { if (parent->child_count == USHRT_MAX) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "system filter generated more " "than %d delivery addresses", USHRT_MAX); parent->child_count++; p->parent = parent; if (testflag(p, af_pfr)) { uschar *tpname; uschar *type; p->uid = uid; p->gid = gid; setflag(p, af_uid_set); setflag(p, af_gid_set); setflag(p, af_allow_file); setflag(p, af_allow_pipe); setflag(p, af_allow_reply); /* Find the name of the system filter's appropriate pfr transport */ if (p->address[0] == '|') { type = US"pipe"; tpname = system_filter_pipe_transport; address_pipe = p->address; } else if (p->address[0] == '>') { type = US"reply"; tpname = system_filter_reply_transport; } else { if (p->address[Ustrlen(p->address)-1] == '/') { type = US"directory"; tpname = system_filter_directory_transport; } else { type = US"file"; tpname = system_filter_file_transport; } address_file = p->address; } /* Now find the actual transport, first expanding the name. We have set address_file or address_pipe above. */ if (tpname) { uschar *tmp = expand_string(tpname); address_file = address_pipe = NULL; if (!tmp) p->message = string_sprintf("failed to expand \"%s\" as a " "system filter transport name", tpname); tpname = tmp; } else p->message = string_sprintf("system_filter_%s_transport is unset", type); if (tpname) { transport_instance *tp; for (tp = transports; tp; tp = tp->next) if (Ustrcmp(tp->name, tpname) == 0) { p->transport = tp; break; } if (!tp) p->message = string_sprintf("failed to find \"%s\" transport " "for system filter delivery", tpname); } /* If we couldn't set up a transport, defer the delivery, putting the error on the panic log as well as the main log. */ if (!p->transport) { address_item *badp = p; p = p->next; if (!addr_last) addr_new = p; else addr_last->next = p; badp->local_part = badp->address; /* Needed for log line */ post_process_one(badp, DEFER, LOG_MAIN|LOG_PANIC, EXIM_DTYPE_ROUTER, 0); continue; } } /* End of pfr handling */ /* Either a non-pfr delivery, or we found a transport */ DEBUG(D_deliver|D_filter) debug_printf("system filter added %s\n", p->address); addr_last = p; p = p->next; } /* Loop through all addr_new addresses */ } } /* Scan the recipients list, and for every one that is not in the non- recipients tree, add an addr item to the chain of new addresses. If the pno value is non-negative, we must set the onetime parent from it. This which points to the relevant entry in the recipients list. This processing can be altered by the setting of the process_recipients variable, which is changed if recipients are to be ignored, failed, or deferred. This can happen as a result of system filter activity, or if the -Mg option is used to fail all of them. Duplicate addresses are handled later by a different tree structure; we can't just extend the non-recipients tree, because that will be re-written to the spool if the message is deferred, and in any case there are casing complications for local addresses. */ if (process_recipients != RECIP_IGNORE) for (i = 0; i < recipients_count; i++) if (!tree_search(tree_nonrecipients, recipients_list[i].address)) { recipient_item *r = recipients_list + i; address_item *new = deliver_make_addr(r->address, FALSE); new->prop.errors_address = r->errors_to; #ifdef SUPPORT_I18N if ((new->prop.utf8_msg = message_smtputf8)) { new->prop.utf8_downcvt = message_utf8_downconvert == 1; new->prop.utf8_downcvt_maybe = message_utf8_downconvert == -1; DEBUG(D_deliver) debug_printf("utf8, downconvert %s\n", new->prop.utf8_downcvt ? "yes" : new->prop.utf8_downcvt_maybe ? "ifneeded" : "no"); } #endif if (r->pno >= 0) new->onetime_parent = recipients_list[r->pno].address; /* If DSN support is enabled, set the dsn flags and the original receipt to be passed on to other DSN enabled MTAs */ new->dsn_flags = r->dsn_flags & rf_dsnflags; new->dsn_orcpt = r->orcpt; DEBUG(D_deliver) debug_printf("DSN: set orcpt: %s flags: %d\n", new->dsn_orcpt ? new->dsn_orcpt : US"", new->dsn_flags); switch (process_recipients) { /* RECIP_DEFER is set when a system filter freezes a message. */ case RECIP_DEFER: new->next = addr_defer; addr_defer = new; break; /* RECIP_FAIL_FILTER is set when a system filter has obeyed a "fail" command. */ case RECIP_FAIL_FILTER: new->message = filter_message ? filter_message : US"delivery cancelled"; setflag(new, af_pass_message); goto RECIP_QUEUE_FAILED; /* below */ /* RECIP_FAIL_TIMEOUT is set when a message is frozen, but is older than the value in timeout_frozen_after. Treat non-bounce messages similarly to -Mg; for bounce messages we just want to discard, so don't put the address on the failed list. The timeout has already been logged. */ case RECIP_FAIL_TIMEOUT: new->message = US"delivery cancelled; message timed out"; goto RECIP_QUEUE_FAILED; /* below */ /* RECIP_FAIL is set when -Mg has been used. */ case RECIP_FAIL: new->message = US"delivery cancelled by administrator"; /* Fall through */ /* Common code for the failure cases above. If this is not a bounce message, put the address on the failed list so that it is used to create a bounce. Otherwise do nothing - this just discards the address. The incident has already been logged. */ RECIP_QUEUE_FAILED: if (sender_address[0]) { new->next = addr_failed; addr_failed = new; } break; /* RECIP_FAIL_LOOP is set when there are too many Received: headers in the message. Process each address as a routing failure; if this is a bounce message, it will get frozen. */ case RECIP_FAIL_LOOP: new->message = US"Too many \"Received\" headers - suspected mail loop"; post_process_one(new, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); break; /* Value should be RECIP_ACCEPT; take this as the safe default. */ default: if (!addr_new) addr_new = new; else addr_last->next = new; addr_last = new; break; } #ifndef DISABLE_EVENT if (process_recipients != RECIP_ACCEPT) { uschar * save_local = deliver_localpart; const uschar * save_domain = deliver_domain; deliver_localpart = expand_string( string_sprintf("${local_part:%s}", new->address)); deliver_domain = expand_string( string_sprintf("${domain:%s}", new->address)); (void) event_raise(event_action, US"msg:fail:internal", new->message); deliver_localpart = save_local; deliver_domain = save_domain; } #endif } DEBUG(D_deliver) { address_item *p; debug_printf("Delivery address list:\n"); for (p = addr_new; p; p = p->next) debug_printf(" %s %s\n", p->address, p->onetime_parent ? p->onetime_parent : US""); } /* Set up the buffers used for copying over the file when delivering. */ deliver_in_buffer = store_malloc(DELIVER_IN_BUFFER_SIZE); deliver_out_buffer = store_malloc(DELIVER_OUT_BUFFER_SIZE); /* Until there are no more new addresses, handle each one as follows: . If this is a generated address (indicated by the presence of a parent pointer) then check to see whether it is a pipe, file, or autoreply, and if so, handle it directly here. The router that produced the address will have set the allow flags into the address, and also set the uid/gid required. Having the routers generate new addresses and then checking them here at the outer level is tidier than making each router do the checking, and means that routers don't need access to the failed address queue. . Break up the address into local part and domain, and make lowercased versions of these strings. We also make unquoted versions of the local part. . Handle the percent hack for those domains for which it is valid. . For child addresses, determine if any of the parents have the same address. If so, generate a different string for previous delivery checking. Without this code, if the address spqr generates spqr via a forward or alias file, delivery of the generated spqr stops further attempts at the top level spqr, which is not what is wanted - it may have generated other addresses. . Check on the retry database to see if routing was previously deferred, but only if in a queue run. Addresses that are to be routed are put on the addr_route chain. Addresses that are to be deferred are put on the addr_defer chain. We do all the checking first, so as not to keep the retry database open any longer than necessary. . Now we run the addresses through the routers. A router may put the address on either the addr_local or the addr_remote chain for local or remote delivery, respectively, or put it on the addr_failed chain if it is undeliveable, or it may generate child addresses and put them on the addr_new chain, or it may defer an address. All the chain anchors are passed as arguments so that the routers can be called for verification purposes as well. . If new addresses have been generated by the routers, da capo. */ f.header_rewritten = FALSE; /* No headers rewritten yet */ while (addr_new) /* Loop until all addresses dealt with */ { address_item *addr, *parent; /* Failure to open the retry database is treated the same as if it does not exist. In both cases, dbm_file is NULL. */ if (!(dbm_file = dbfn_open(US"retry", O_RDONLY, &dbblock, FALSE))) DEBUG(D_deliver|D_retry|D_route|D_hints_lookup) debug_printf("no retry data available\n"); /* Scan the current batch of new addresses, to handle pipes, files and autoreplies, and determine which others are ready for routing. */ while (addr_new) { int rc; uschar *p; tree_node *tnode; dbdata_retry *domain_retry_record; dbdata_retry *address_retry_record; addr = addr_new; addr_new = addr->next; DEBUG(D_deliver|D_retry|D_route) { debug_printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"); debug_printf("Considering: %s\n", addr->address); } /* Handle generated address that is a pipe or a file or an autoreply. */ if (testflag(addr, af_pfr)) { /* If an autoreply in a filter could not generate a syntactically valid address, give up forthwith. Set af_ignore_error so that we don't try to generate a bounce. */ if (testflag(addr, af_bad_reply)) { addr->basic_errno = ERRNO_BADADDRESS2; addr->local_part = addr->address; addr->message = US"filter autoreply generated syntactically invalid recipient"; addr->prop.ignore_error = TRUE; (void) post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; /* with the next new address */ } /* If two different users specify delivery to the same pipe or file or autoreply, there should be two different deliveries, so build a unique string that incorporates the original address, and use this for duplicate testing and recording delivery, and also for retrying. */ addr->unique = string_sprintf("%s:%s", addr->address, addr->parent->unique + (testflag(addr->parent, af_homonym)? 3:0)); addr->address_retry_key = addr->domain_retry_key = string_sprintf("T:%s", addr->unique); /* If a filter file specifies two deliveries to the same pipe or file, we want to de-duplicate, but this is probably not wanted for two mail commands to the same address, where probably both should be delivered. So, we have to invent a different unique string in that case. Just keep piling '>' characters on the front. */ if (addr->address[0] == '>') { while (tree_search(tree_duplicates, addr->unique)) addr->unique = string_sprintf(">%s", addr->unique); } else if ((tnode = tree_search(tree_duplicates, addr->unique))) { DEBUG(D_deliver|D_route) debug_printf("%s is a duplicate address: discarded\n", addr->address); addr->dupof = tnode->data.ptr; addr->next = addr_duplicate; addr_duplicate = addr; continue; } DEBUG(D_deliver|D_route) debug_printf("unique = %s\n", addr->unique); /* Check for previous delivery */ if (tree_search(tree_nonrecipients, addr->unique)) { DEBUG(D_deliver|D_route) debug_printf("%s was previously delivered: discarded\n", addr->address); child_done(addr, tod_stamp(tod_log)); continue; } /* Save for checking future duplicates */ tree_add_duplicate(addr->unique, addr); /* Set local part and domain */ addr->local_part = addr->address; addr->domain = addr->parent->domain; /* Ensure that the delivery is permitted. */ if (testflag(addr, af_file)) { if (!testflag(addr, af_allow_file)) { addr->basic_errno = ERRNO_FORBIDFILE; addr->message = US"delivery to file forbidden"; (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; /* with the next new address */ } } else if (addr->address[0] == '|') { if (!testflag(addr, af_allow_pipe)) { addr->basic_errno = ERRNO_FORBIDPIPE; addr->message = US"delivery to pipe forbidden"; (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; /* with the next new address */ } } else if (!testflag(addr, af_allow_reply)) { addr->basic_errno = ERRNO_FORBIDREPLY; addr->message = US"autoreply forbidden"; (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; /* with the next new address */ } /* If the errno field is already set to BADTRANSPORT, it indicates failure to expand a transport string, or find the associated transport, or an unset transport when one is required. Leave this test till now so that the forbid errors are given in preference. */ if (addr->basic_errno == ERRNO_BADTRANSPORT) { (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; } /* Treat /dev/null as a special case and abandon the delivery. This avoids having to specify a uid on the transport just for this case. Arrange for the transport name to be logged as "**bypassed**". */ if (Ustrcmp(addr->address, "/dev/null") == 0) { uschar *save = addr->transport->name; addr->transport->name = US"**bypassed**"; (void)post_process_one(addr, OK, LOG_MAIN, EXIM_DTYPE_TRANSPORT, '='); addr->transport->name = save; continue; /* with the next new address */ } /* Pipe, file, or autoreply delivery is to go ahead as a normal local delivery. */ DEBUG(D_deliver|D_route) debug_printf("queued for %s transport\n", addr->transport->name); addr->next = addr_local; addr_local = addr; continue; /* with the next new address */ } /* Handle normal addresses. First, split up into local part and domain, handling the %-hack if necessary. There is the possibility of a defer from a lookup in percent_hack_domains. */ if ((rc = deliver_split_address(addr)) == DEFER) { addr->message = US"cannot check percent_hack_domains"; addr->basic_errno = ERRNO_LISTDEFER; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_NONE, 0); continue; } /* Check to see if the domain is held. If so, proceed only if the delivery was forced by hand. */ deliver_domain = addr->domain; /* set $domain */ if ( !forced && hold_domains && (rc = match_isinlist(addr->domain, (const uschar **)&hold_domains, 0, &domainlist_anchor, addr->domain_cache, MCL_DOMAIN, TRUE, NULL)) != FAIL ) { if (rc == DEFER) { addr->message = US"hold_domains lookup deferred"; addr->basic_errno = ERRNO_LISTDEFER; } else { addr->message = US"domain is held"; addr->basic_errno = ERRNO_HELD; } (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_NONE, 0); continue; } /* Now we can check for duplicates and previously delivered addresses. In order to do this, we have to generate a "unique" value for each address, because there may be identical actual addresses in a line of descendents. The "unique" field is initialized to the same value as the "address" field, but gets changed here to cope with identically-named descendents. */ for (parent = addr->parent; parent; parent = parent->parent) if (strcmpic(addr->address, parent->address) == 0) break; /* If there's an ancestor with the same name, set the homonym flag. This influences how deliveries are recorded. Then add a prefix on the front of the unique address. We use \n\ where n starts at 0 and increases each time. It is unlikely to pass 9, but if it does, it may look odd but will still work. This means that siblings or cousins with the same names are treated as duplicates, which is what we want. */ if (parent) { setflag(addr, af_homonym); if (parent->unique[0] != '\\') addr->unique = string_sprintf("\\0\\%s", addr->address); else addr->unique = string_sprintf("\\%c\\%s", parent->unique[1] + 1, addr->address); } /* Ensure that the domain in the unique field is lower cased, because domains are always handled caselessly. */ p = Ustrrchr(addr->unique, '@'); while (*p != 0) { *p = tolower(*p); p++; } DEBUG(D_deliver|D_route) debug_printf("unique = %s\n", addr->unique); if (tree_search(tree_nonrecipients, addr->unique)) { DEBUG(D_deliver|D_route) debug_printf("%s was previously delivered: discarded\n", addr->unique); child_done(addr, tod_stamp(tod_log)); continue; } /* Get the routing retry status, saving the two retry keys (with and without the local part) for subsequent use. If there is no retry record for the standard address routing retry key, we look for the same key with the sender attached, because this form is used by the smtp transport after a 4xx response to RCPT when address_retry_include_sender is true. */ addr->domain_retry_key = string_sprintf("R:%s", addr->domain); addr->address_retry_key = string_sprintf("R:%s@%s", addr->local_part, addr->domain); if (dbm_file) { domain_retry_record = dbfn_read(dbm_file, addr->domain_retry_key); if ( domain_retry_record && now - domain_retry_record->time_stamp > retry_data_expire ) domain_retry_record = NULL; /* Ignore if too old */ address_retry_record = dbfn_read(dbm_file, addr->address_retry_key); if ( address_retry_record && now - address_retry_record->time_stamp > retry_data_expire ) address_retry_record = NULL; /* Ignore if too old */ if (!address_retry_record) { uschar *altkey = string_sprintf("%s:<%s>", addr->address_retry_key, sender_address); address_retry_record = dbfn_read(dbm_file, altkey); if ( address_retry_record && now - address_retry_record->time_stamp > retry_data_expire) address_retry_record = NULL; /* Ignore if too old */ } } else domain_retry_record = address_retry_record = NULL; DEBUG(D_deliver|D_retry) { if (!domain_retry_record) debug_printf("no domain retry record\n"); if (!address_retry_record) debug_printf("no address retry record\n"); } /* If we are sending a message down an existing SMTP connection, we must assume that the message which created the connection managed to route an address to that connection. We do not want to run the risk of taking a long time over routing here, because if we do, the server at the other end of the connection may time it out. This is especially true for messages with lots of addresses. For this kind of delivery, queue_running is not set, so we would normally route all addresses. We take a pragmatic approach and defer routing any addresses that have any kind of domain retry record. That is, we don't even look at their retry times. It doesn't matter if this doesn't work occasionally. This is all just an optimization, after all. The reason for not doing the same for address retries is that they normally arise from 4xx responses, not DNS timeouts. */ if (continue_hostname && domain_retry_record) { addr->message = US"reusing SMTP connection skips previous routing defer"; addr->basic_errno = ERRNO_RRETRY; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } /* If we are in a queue run, defer routing unless there is no retry data or we've passed the next retry time, or this message is forced. In other words, ignore retry data when not in a queue run. However, if the domain retry time has expired, always allow the routing attempt. If it fails again, the address will be failed. This ensures that each address is routed at least once, even after long-term routing failures. If there is an address retry, check that too; just wait for the next retry time. This helps with the case when the temporary error on the address was really message-specific rather than address specific, since it allows other messages through. We also wait for the next retry time if this is a message sent down an existing SMTP connection (even though that will be forced). Otherwise there will be far too many attempts for an address that gets a 4xx error. In fact, after such an error, we should not get here because, the host should not be remembered as one this message needs. However, there was a bug that used to cause this to happen, so it is best to be on the safe side. Even if we haven't reached the retry time in the hints, there is one more check to do, which is for the ultimate address timeout. We only do this check if there is an address retry record and there is not a domain retry record; this implies that previous attempts to handle the address had the retry_use_local_parts option turned on. We use this as an approximation for the destination being like a local delivery, for example delivery over LMTP to an IMAP message store. In this situation users are liable to bump into their quota and thereby have intermittently successful deliveries, which keep the retry record fresh, which can lead to us perpetually deferring messages. */ else if ( ( f.queue_running && !f.deliver_force || continue_hostname ) && ( ( domain_retry_record && now < domain_retry_record->next_try && !domain_retry_record->expired ) || ( address_retry_record && now < address_retry_record->next_try ) ) && ( domain_retry_record || !address_retry_record || !retry_ultimate_address_timeout(addr->address_retry_key, addr->domain, address_retry_record, now) ) ) { addr->message = US"retry time not reached"; addr->basic_errno = ERRNO_RRETRY; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } /* The domain is OK for routing. Remember if retry data exists so it can be cleaned up after a successful delivery. */ else { if (domain_retry_record || address_retry_record) setflag(addr, af_dr_retry_exists); addr->next = addr_route; addr_route = addr; DEBUG(D_deliver|D_route) debug_printf("%s: queued for routing\n", addr->address); } } /* The database is closed while routing is actually happening. Requests to update it are put on a chain and all processed together at the end. */ if (dbm_file) dbfn_close(dbm_file); /* If queue_domains is set, we don't even want to try routing addresses in those domains. During queue runs, queue_domains is forced to be unset. Optimize by skipping this pass through the addresses if nothing is set. */ if (!f.deliver_force && queue_domains) { address_item *okaddr = NULL; while (addr_route) { address_item *addr = addr_route; addr_route = addr->next; deliver_domain = addr->domain; /* set $domain */ if ((rc = match_isinlist(addr->domain, (const uschar **)&queue_domains, 0, &domainlist_anchor, addr->domain_cache, MCL_DOMAIN, TRUE, NULL)) != OK) if (rc == DEFER) { addr->basic_errno = ERRNO_LISTDEFER; addr->message = US"queue_domains lookup deferred"; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } else { addr->next = okaddr; okaddr = addr; } else { addr->basic_errno = ERRNO_QUEUE_DOMAIN; addr->message = US"domain is in queue_domains"; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } } addr_route = okaddr; } /* Now route those addresses that are not deferred. */ while (addr_route) { int rc; address_item *addr = addr_route; const uschar *old_domain = addr->domain; uschar *old_unique = addr->unique; addr_route = addr->next; addr->next = NULL; /* Just in case some router parameter refers to it. */ if (!(return_path = addr->prop.errors_address)) return_path = sender_address; /* If a router defers an address, add a retry item. Whether or not to use the local part in the key is a property of the router. */ if ((rc = route_address(addr, &addr_local, &addr_remote, &addr_new, &addr_succeed, v_none)) == DEFER) retry_add_item(addr, addr->router->retry_use_local_part ? string_sprintf("R:%s@%s", addr->local_part, addr->domain) : string_sprintf("R:%s", addr->domain), 0); /* Otherwise, if there is an existing retry record in the database, add retry items to delete both forms. We must also allow for the possibility of a routing retry that includes the sender address. Since the domain might have been rewritten (expanded to fully qualified) as a result of routing, ensure that the rewritten form is also deleted. */ else if (testflag(addr, af_dr_retry_exists)) { uschar *altkey = string_sprintf("%s:<%s>", addr->address_retry_key, sender_address); retry_add_item(addr, altkey, rf_delete); retry_add_item(addr, addr->address_retry_key, rf_delete); retry_add_item(addr, addr->domain_retry_key, rf_delete); if (Ustrcmp(addr->domain, old_domain) != 0) retry_add_item(addr, string_sprintf("R:%s", old_domain), rf_delete); } /* DISCARD is given for :blackhole: and "seen finish". The event has been logged, but we need to ensure the address (and maybe parents) is marked done. */ if (rc == DISCARD) { address_done(addr, tod_stamp(tod_log)); continue; /* route next address */ } /* The address is finished with (failed or deferred). */ if (rc != OK) { (void)post_process_one(addr, rc, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; /* route next address */ } /* The address has been routed. If the router changed the domain, it will also have changed the unique address. We have to test whether this address has already been delivered, because it's the unique address that finally gets recorded. */ if ( addr->unique != old_unique && tree_search(tree_nonrecipients, addr->unique) != 0 ) { DEBUG(D_deliver|D_route) debug_printf("%s was previously delivered: " "discarded\n", addr->address); if (addr_remote == addr) addr_remote = addr->next; else if (addr_local == addr) addr_local = addr->next; } /* If the router has same_domain_copy_routing set, we are permitted to copy the routing for any other addresses with the same domain. This is an optimisation to save repeated DNS lookups for "standard" remote domain routing. The option is settable only on routers that generate host lists. We play it very safe, and do the optimization only if the address is routed to a remote transport, there are no header changes, and the domain was not modified by the router. */ if ( addr_remote == addr && addr->router->same_domain_copy_routing && !addr->prop.extra_headers && !addr->prop.remove_headers && old_domain == addr->domain ) { address_item **chain = &addr_route; while (*chain) { address_item *addr2 = *chain; if (Ustrcmp(addr2->domain, addr->domain) != 0) { chain = &(addr2->next); continue; } /* Found a suitable address; take it off the routing list and add it to the remote delivery list. */ *chain = addr2->next; addr2->next = addr_remote; addr_remote = addr2; /* Copy the routing data */ addr2->domain = addr->domain; addr2->router = addr->router; addr2->transport = addr->transport; addr2->host_list = addr->host_list; addr2->fallback_hosts = addr->fallback_hosts; addr2->prop.errors_address = addr->prop.errors_address; copyflag(addr2, addr, af_hide_child); copyflag(addr2, addr, af_local_host_removed); DEBUG(D_deliver|D_route) debug_printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n" "routing %s\n" "Routing for %s copied from %s\n", addr2->address, addr2->address, addr->address); } } } /* Continue with routing the next address. */ } /* Loop to process any child addresses that the routers created, and any rerouted addresses that got put back on the new chain. */ /* Debugging: show the results of the routing */ DEBUG(D_deliver|D_retry|D_route) { address_item *p; debug_printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"); debug_printf("After routing:\n Local deliveries:\n"); for (p = addr_local; p; p = p->next) debug_printf(" %s\n", p->address); debug_printf(" Remote deliveries:\n"); for (p = addr_remote; p; p = p->next) debug_printf(" %s\n", p->address); debug_printf(" Failed addresses:\n"); for (p = addr_failed; p; p = p->next) debug_printf(" %s\n", p->address); debug_printf(" Deferred addresses:\n"); for (p = addr_defer; p; p = p->next) debug_printf(" %s\n", p->address); } /* Free any resources that were cached during routing. */ search_tidyup(); route_tidyup(); /* These two variables are set only during routing, after check_local_user. Ensure they are not set in transports. */ local_user_gid = (gid_t)(-1); local_user_uid = (uid_t)(-1); /* Check for any duplicate addresses. This check is delayed until after routing, because the flexibility of the routing configuration means that identical addresses with different parentage may end up being redirected to different addresses. Checking for duplicates too early (as we previously used to) makes this kind of thing not work. */ do_duplicate_check(&addr_local); do_duplicate_check(&addr_remote); /* When acting as an MUA wrapper, we proceed only if all addresses route to a remote transport. The check that they all end up in one transaction happens in the do_remote_deliveries() function. */ if ( mua_wrapper && (addr_local || addr_failed || addr_defer) ) { address_item *addr; uschar *which, *colon, *msg; if (addr_local) { addr = addr_local; which = US"local"; } else if (addr_defer) { addr = addr_defer; which = US"deferred"; } else { addr = addr_failed; which = US"failed"; } while (addr->parent) addr = addr->parent; if (addr->message) { colon = US": "; msg = addr->message; } else colon = msg = US""; /* We don't need to log here for a forced failure as it will already have been logged. Defer will also have been logged, but as a defer, so we do need to do the failure logging. */ if (addr != addr_failed) log_write(0, LOG_MAIN, "** %s routing yielded a %s delivery", addr->address, which); /* Always write an error to the caller */ fprintf(stderr, "routing %s yielded a %s delivery%s%s\n", addr->address, which, colon, msg); final_yield = DELIVER_MUA_FAILED; addr_failed = addr_defer = NULL; /* So that we remove the message */ goto DELIVERY_TIDYUP; } /* If this is a run to continue deliveries to an external channel that is already set up, defer any local deliveries. */ if (continue_transport) { if (addr_defer) { address_item *addr = addr_defer; while (addr->next) addr = addr->next; addr->next = addr_local; } else addr_defer = addr_local; addr_local = NULL; } /* Because address rewriting can happen in the routers, we should not really do ANY deliveries until all addresses have been routed, so that all recipients of the message get the same headers. However, this is in practice not always possible, since sometimes remote addresses give DNS timeouts for days on end. The pragmatic approach is to deliver what we can now, saving any rewritten headers so that at least the next lot of recipients benefit from the rewriting that has already been done. If any headers have been rewritten during routing, update the spool file to remember them for all subsequent deliveries. This can be delayed till later if there is only address to be delivered - if it succeeds the spool write need not happen. */ if ( f.header_rewritten && ( addr_local && (addr_local->next || addr_remote) || addr_remote && addr_remote->next ) ) { /* Panic-dies on error */ (void)spool_write_header(message_id, SW_DELIVERING, NULL); f.header_rewritten = FALSE; } /* If there are any deliveries to be and we do not already have the journal file, create it. This is used to record successful deliveries as soon as possible after each delivery is known to be complete. A file opened with O_APPEND is used so that several processes can run simultaneously. The journal is just insurance against crashes. When the spool file is ultimately updated at the end of processing, the journal is deleted. If a journal is found to exist at the start of delivery, the addresses listed therein are added to the non-recipients. */ if (addr_local || addr_remote) { if (journal_fd < 0) { uschar * fname = spool_fname(US"input", message_subdir, id, US"-J"); if ((journal_fd = Uopen(fname, #ifdef O_CLOEXEC O_CLOEXEC | #endif O_WRONLY|O_APPEND|O_CREAT|O_EXCL, SPOOL_MODE)) < 0) { log_write(0, LOG_MAIN|LOG_PANIC, "Couldn't open journal file %s: %s", fname, strerror(errno)); return DELIVER_NOT_ATTEMPTED; } /* Set the close-on-exec flag, make the file owned by Exim, and ensure that the mode is correct - the group setting doesn't always seem to get set automatically. */ if( fchown(journal_fd, exim_uid, exim_gid) || fchmod(journal_fd, SPOOL_MODE) #ifndef O_CLOEXEC || fcntl(journal_fd, F_SETFD, fcntl(journal_fd, F_GETFD) | FD_CLOEXEC) #endif ) { int ret = Uunlink(fname); log_write(0, LOG_MAIN|LOG_PANIC, "Couldn't set perms on journal file %s: %s", fname, strerror(errno)); if(ret && errno != ENOENT) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to unlink %s: %s", fname, strerror(errno)); return DELIVER_NOT_ATTEMPTED; } } } else if (journal_fd >= 0) { close(journal_fd); journal_fd = -1; } /* Now we can get down to the business of actually doing deliveries. Local deliveries are done first, then remote ones. If ever the problems of how to handle fallback transports are figured out, this section can be put into a loop for handling fallbacks, though the uid switching will have to be revised. */ /* Precompile a regex that is used to recognize a parameter in response to an LHLO command, if is isn't already compiled. This may be used on both local and remote LMTP deliveries. */ if (!regex_IGNOREQUOTA) regex_IGNOREQUOTA = regex_must_compile(US"\\n250[\\s\\-]IGNOREQUOTA(\\s|\\n|$)", FALSE, TRUE); /* Handle local deliveries */ if (addr_local) { DEBUG(D_deliver|D_transport) debug_printf(">>>>>>>>>>>>>>>> Local deliveries >>>>>>>>>>>>>>>>\n"); do_local_deliveries(); f.disable_logging = FALSE; } /* If queue_run_local is set, we do not want to attempt any remote deliveries, so just queue them all. */ if (f.queue_run_local) while (addr_remote) { address_item *addr = addr_remote; addr_remote = addr->next; addr->next = NULL; addr->basic_errno = ERRNO_LOCAL_ONLY; addr->message = US"remote deliveries suppressed"; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_TRANSPORT, 0); } /* Handle remote deliveries */ if (addr_remote) { DEBUG(D_deliver|D_transport) debug_printf(">>>>>>>>>>>>>>>> Remote deliveries >>>>>>>>>>>>>>>>\n"); /* Precompile some regex that are used to recognize parameters in response to an EHLO command, if they aren't already compiled. */ deliver_init(); /* Now sort the addresses if required, and do the deliveries. The yield of do_remote_deliveries is FALSE when mua_wrapper is set and all addresses cannot be delivered in one transaction. */ if (remote_sort_domains) sort_remote_deliveries(); if (!do_remote_deliveries(FALSE)) { log_write(0, LOG_MAIN, "** mua_wrapper is set but recipients cannot all " "be delivered in one transaction"); fprintf(stderr, "delivery to smarthost failed (configuration problem)\n"); final_yield = DELIVER_MUA_FAILED; addr_failed = addr_defer = NULL; /* So that we remove the message */ goto DELIVERY_TIDYUP; } /* See if any of the addresses that failed got put on the queue for delivery to their fallback hosts. We do it this way because often the same fallback host is used for many domains, so all can be sent in a single transaction (if appropriately configured). */ if (addr_fallback && !mua_wrapper) { DEBUG(D_deliver) debug_printf("Delivering to fallback hosts\n"); addr_remote = addr_fallback; addr_fallback = NULL; if (remote_sort_domains) sort_remote_deliveries(); do_remote_deliveries(TRUE); } f.disable_logging = FALSE; } /* All deliveries are now complete. Ignore SIGTERM during this tidying up phase, to minimize cases of half-done things. */ DEBUG(D_deliver) debug_printf(">>>>>>>>>>>>>>>> deliveries are done >>>>>>>>>>>>>>>>\n"); cancel_cutthrough_connection(TRUE, US"deliveries are done"); /* Root privilege is no longer needed */ exim_setugid(exim_uid, exim_gid, FALSE, US"post-delivery tidying"); set_process_info("tidying up after delivering %s", message_id); signal(SIGTERM, SIG_IGN); /* When we are acting as an MUA wrapper, the smtp transport will either have succeeded for all addresses, or failed them all in normal cases. However, there are some setup situations (e.g. when a named port does not exist) that cause an immediate exit with deferral of all addresses. Convert those into failures. We do not ever want to retry, nor do we want to send a bounce message. */ if (mua_wrapper) { if (addr_defer) { address_item *addr, *nextaddr; for (addr = addr_defer; addr; addr = nextaddr) { log_write(0, LOG_MAIN, "** %s mua_wrapper forced failure for deferred " "delivery", addr->address); nextaddr = addr->next; addr->next = addr_failed; addr_failed = addr; } addr_defer = NULL; } /* Now all should either have succeeded or failed. */ if (!addr_failed) final_yield = DELIVER_MUA_SUCCEEDED; else { host_item * host; uschar *s = addr_failed->user_message; if (!s) s = addr_failed->message; fprintf(stderr, "Delivery failed: "); if (addr_failed->basic_errno > 0) { fprintf(stderr, "%s", strerror(addr_failed->basic_errno)); if (s) fprintf(stderr, ": "); } if ((host = addr_failed->host_used)) fprintf(stderr, "H=%s [%s]: ", host->name, host->address); if (s) fprintf(stderr, "%s", CS s); else if (addr_failed->basic_errno <= 0) fprintf(stderr, "unknown error"); fprintf(stderr, "\n"); final_yield = DELIVER_MUA_FAILED; addr_failed = NULL; } } /* In a normal configuration, we now update the retry database. This is done in one fell swoop at the end in order not to keep opening and closing (and locking) the database. The code for handling retries is hived off into a separate module for convenience. We pass it the addresses of the various chains, because deferred addresses can get moved onto the failed chain if the retry cutoff time has expired for all alternative destinations. Bypass the updating of the database if the -N flag is set, which is a debugging thing that prevents actual delivery. */ else if (!f.dont_deliver) retry_update(&addr_defer, &addr_failed, &addr_succeed); /* Send DSN for successful messages if requested */ addr_senddsn = NULL; for (addr_dsntmp = addr_succeed; addr_dsntmp; addr_dsntmp = addr_dsntmp->next) { /* af_ignore_error not honored here. it's not an error */ DEBUG(D_deliver) debug_printf("DSN: processing router : %s\n" "DSN: processing successful delivery address: %s\n" "DSN: Sender_address: %s\n" "DSN: orcpt: %s flags: %d\n" "DSN: envid: %s ret: %d\n" "DSN: Final recipient: %s\n" "DSN: Remote SMTP server supports DSN: %d\n", addr_dsntmp->router ? addr_dsntmp->router->name : US"(unknown)", addr_dsntmp->address, sender_address, addr_dsntmp->dsn_orcpt ? addr_dsntmp->dsn_orcpt : US"NULL", addr_dsntmp->dsn_flags, dsn_envid ? dsn_envid : US"NULL", dsn_ret, addr_dsntmp->address, addr_dsntmp->dsn_aware ); /* send report if next hop not DSN aware or a router flagged "last DSN hop" and a report was requested */ if ( ( addr_dsntmp->dsn_aware != dsn_support_yes || addr_dsntmp->dsn_flags & rf_dsnlasthop ) && addr_dsntmp->dsn_flags & rf_dsnflags && addr_dsntmp->dsn_flags & rf_notify_success ) { /* copy and relink address_item and send report with all of them at once later */ address_item * addr_next = addr_senddsn; addr_senddsn = store_get(sizeof(address_item)); *addr_senddsn = *addr_dsntmp; addr_senddsn->next = addr_next; } else DEBUG(D_deliver) debug_printf("DSN: not sending DSN success message\n"); } if (addr_senddsn) { pid_t pid; int fd; /* create exim process to send message */ pid = child_open_exim(&fd); DEBUG(D_deliver) debug_printf("DSN: child_open_exim returns: %d\n", pid); if (pid < 0) /* Creation of child failed */ { log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Process %d (parent %d) failed to " "create child process to send failure message: %s", getpid(), getppid(), strerror(errno)); DEBUG(D_deliver) debug_printf("DSN: child_open_exim failed\n"); } else /* Creation of child succeeded */ { FILE *f = fdopen(fd, "wb"); /* header only as required by RFC. only failure DSN needs to honor RET=FULL */ uschar * bound; transport_ctx tctx = {{0}}; DEBUG(D_deliver) debug_printf("sending error message to: %s\n", sender_address); /* build unique id for MIME boundary */ bound = string_sprintf(TIME_T_FMT "-eximdsn-%d", time(NULL), rand()); DEBUG(D_deliver) debug_printf("DSN: MIME boundary: %s\n", bound); if (errors_reply_to) fprintf(f, "Reply-To: %s\n", errors_reply_to); fprintf(f, "Auto-Submitted: auto-generated\n" "From: Mail Delivery System <Mailer-Daemon@%s>\n" "To: %s\n" "Subject: Delivery Status Notification\n" "Content-Type: multipart/report; report-type=delivery-status; boundary=%s\n" "MIME-Version: 1.0\n\n" "--%s\n" "Content-type: text/plain; charset=us-ascii\n\n" "This message was created automatically by mail delivery software.\n" " ----- The following addresses had successful delivery notifications -----\n", qualify_domain_sender, sender_address, bound, bound); for (addr_dsntmp = addr_senddsn; addr_dsntmp; addr_dsntmp = addr_dsntmp->next) fprintf(f, "<%s> (relayed %s)\n\n", addr_dsntmp->address, (addr_dsntmp->dsn_flags & rf_dsnlasthop) == 1 ? "via non DSN router" : addr_dsntmp->dsn_aware == dsn_support_no ? "to non-DSN-aware mailer" : "via non \"Remote SMTP\" router" ); fprintf(f, "--%s\n" "Content-type: message/delivery-status\n\n" "Reporting-MTA: dns; %s\n", bound, smtp_active_hostname); if (dsn_envid) { /* must be decoded from xtext: see RFC 3461:6.3a */ uschar *xdec_envid; if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0) fprintf(f, "Original-Envelope-ID: %s\n", dsn_envid); else fprintf(f, "X-Original-Envelope-ID: error decoding xtext formatted ENVID\n"); } fputc('\n', f); for (addr_dsntmp = addr_senddsn; addr_dsntmp; addr_dsntmp = addr_dsntmp->next) { if (addr_dsntmp->dsn_orcpt) fprintf(f,"Original-Recipient: %s\n", addr_dsntmp->dsn_orcpt); fprintf(f, "Action: delivered\n" "Final-Recipient: rfc822;%s\n" "Status: 2.0.0\n", addr_dsntmp->address); if (addr_dsntmp->host_used && addr_dsntmp->host_used->name) fprintf(f, "Remote-MTA: dns; %s\nDiagnostic-Code: smtp; 250 Ok\n\n", addr_dsntmp->host_used->name); else fprintf(f, "Diagnostic-Code: X-Exim; relayed via non %s router\n\n", (addr_dsntmp->dsn_flags & rf_dsnlasthop) == 1 ? "DSN" : "SMTP"); } fprintf(f, "--%s\nContent-type: text/rfc822-headers\n\n", bound); fflush(f); transport_filter_argv = NULL; /* Just in case */ return_path = sender_address; /* In case not previously set */ /* Write the original email out */ tctx.u.fd = fileno(f); tctx.options = topt_add_return_path | topt_no_body; transport_write_message(&tctx, 0); fflush(f); fprintf(f,"\n--%s--\n", bound); fflush(f); fclose(f); rc = child_close(pid, 0); /* Waits for child to close, no timeout */ } } /* If any addresses failed, we must send a message to somebody, unless af_ignore_error is set, in which case no action is taken. It is possible for several messages to get sent if there are addresses with different requirements. */ while (addr_failed) { pid_t pid; int fd; uschar *logtod = tod_stamp(tod_log); address_item *addr; address_item *handled_addr = NULL; address_item **paddr; address_item *msgchain = NULL; address_item **pmsgchain = &msgchain; /* There are weird cases when logging is disabled in the transport. However, there may not be a transport (address failed by a router). */ f.disable_logging = FALSE; if (addr_failed->transport) f.disable_logging = addr_failed->transport->disable_logging; DEBUG(D_deliver) debug_printf("processing failed address %s\n", addr_failed->address); /* There are only two ways an address in a bounce message can get here: (1) When delivery was initially deferred, but has now timed out (in the call to retry_update() above). We can detect this by testing for af_retry_timedout. If the address does not have its own errors address, we arrange to ignore the error. (2) If delivery failures for bounce messages are being ignored. We can detect this by testing for af_ignore_error. This will also be set if a bounce message has been autothawed and the ignore_bounce_errors_after time has passed. It might also be set if a router was explicitly configured to ignore errors (errors_to = ""). If neither of these cases obtains, something has gone wrong. Log the incident, but then ignore the error. */ if (sender_address[0] == 0 && !addr_failed->prop.errors_address) { if ( !testflag(addr_failed, af_retry_timedout) && !addr_failed->prop.ignore_error) log_write(0, LOG_MAIN|LOG_PANIC, "internal error: bounce message " "failure is neither frozen nor ignored (it's been ignored)"); addr_failed->prop.ignore_error = TRUE; } /* If the first address on the list has af_ignore_error set, just remove it from the list, throw away any saved message file, log it, and mark the recipient done. */ if ( addr_failed->prop.ignore_error || ( addr_failed->dsn_flags & rf_dsnflags && (addr_failed->dsn_flags & rf_notify_failure) != rf_notify_failure ) ) { addr = addr_failed; addr_failed = addr->next; if (addr->return_filename) Uunlink(addr->return_filename); log_write(0, LOG_MAIN, "%s%s%s%s: error ignored", addr->address, !addr->parent ? US"" : US" <", !addr->parent ? US"" : addr->parent->address, !addr->parent ? US"" : US">"); address_done(addr, logtod); child_done(addr, logtod); /* Panic-dies on error */ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } /* Otherwise, handle the sending of a message. Find the error address for the first address, then send a message that includes all failed addresses that have the same error address. Note the bounce_recipient is a global so that it can be accessed by $bounce_recipient while creating a customized error message. */ else { if (!(bounce_recipient = addr_failed->prop.errors_address)) bounce_recipient = sender_address; /* Make a subprocess to send a message */ if ((pid = child_open_exim(&fd)) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Process %d (parent %d) failed to " "create child process to send failure message: %s", getpid(), getppid(), strerror(errno)); /* Creation of child succeeded */ else { int ch, rc; int filecount = 0; int rcount = 0; uschar *bcc, *emf_text; FILE * fp = fdopen(fd, "wb"); FILE * emf = NULL; BOOL to_sender = strcmpic(sender_address, bounce_recipient) == 0; int max = (bounce_return_size_limit/DELIVER_IN_BUFFER_SIZE + 1) * DELIVER_IN_BUFFER_SIZE; uschar * bound; uschar *dsnlimitmsg; uschar *dsnnotifyhdr; int topt; DEBUG(D_deliver) debug_printf("sending error message to: %s\n", bounce_recipient); /* Scan the addresses for all that have the same errors address, removing them from the addr_failed chain, and putting them on msgchain. */ paddr = &addr_failed; for (addr = addr_failed; addr; addr = *paddr) if (Ustrcmp(bounce_recipient, addr->prop.errors_address ? addr->prop.errors_address : sender_address) == 0) { /* The same - dechain */ *paddr = addr->next; *pmsgchain = addr; addr->next = NULL; pmsgchain = &(addr->next); } else paddr = &addr->next; /* Not the same; skip */ /* Include X-Failed-Recipients: for automatic interpretation, but do not let any one header line get too long. We do this by starting a new header every 50 recipients. Omit any addresses for which the "hide_child" flag is set. */ for (addr = msgchain; addr; addr = addr->next) { if (testflag(addr, af_hide_child)) continue; if (rcount >= 50) { fprintf(fp, "\n"); rcount = 0; } fprintf(fp, "%s%s", rcount++ == 0 ? "X-Failed-Recipients: " : ",\n ", testflag(addr, af_pfr) && addr->parent ? string_printing(addr->parent->address) : string_printing(addr->address)); } if (rcount > 0) fprintf(fp, "\n"); /* Output the standard headers */ if (errors_reply_to) fprintf(fp, "Reply-To: %s\n", errors_reply_to); fprintf(fp, "Auto-Submitted: auto-replied\n"); moan_write_from(fp); fprintf(fp, "To: %s\n", bounce_recipient); /* generate boundary string and output MIME-Headers */ bound = string_sprintf(TIME_T_FMT "-eximdsn-%d", time(NULL), rand()); fprintf(fp, "Content-Type: multipart/report;" " report-type=delivery-status; boundary=%s\n" "MIME-Version: 1.0\n", bound); /* Open a template file if one is provided. Log failure to open, but carry on - default texts will be used. */ if (bounce_message_file) if (!(emf = Ufopen(bounce_message_file, "rb"))) log_write(0, LOG_MAIN|LOG_PANIC, "Failed to open %s for error " "message texts: %s", bounce_message_file, strerror(errno)); /* Quietly copy to configured additional addresses if required. */ if ((bcc = moan_check_errorcopy(bounce_recipient))) fprintf(fp, "Bcc: %s\n", bcc); /* The texts for the message can be read from a template file; if there isn't one, or if it is too short, built-in texts are used. The first emf text is a Subject: and any other headers. */ if ((emf_text = next_emf(emf, US"header"))) fprintf(fp, "%s\n", emf_text); else fprintf(fp, "Subject: Mail delivery failed%s\n\n", to_sender? ": returning message to sender" : ""); /* output human readable part as text/plain section */ fprintf(fp, "--%s\n" "Content-type: text/plain; charset=us-ascii\n\n", bound); if ((emf_text = next_emf(emf, US"intro"))) fprintf(fp, "%s", CS emf_text); else { fprintf(fp, /* This message has been reworded several times. It seems to be confusing to somebody, however it is worded. I have retreated to the original, simple wording. */ "This message was created automatically by mail delivery software.\n"); if (bounce_message_text) fprintf(fp, "%s", CS bounce_message_text); if (to_sender) fprintf(fp, "\nA message that you sent could not be delivered to one or more of its\n" "recipients. This is a permanent error. The following address(es) failed:\n"); else fprintf(fp, "\nA message sent by\n\n <%s>\n\n" "could not be delivered to one or more of its recipients. The following\n" "address(es) failed:\n", sender_address); } fputc('\n', fp); /* Process the addresses, leaving them on the msgchain if they have a file name for a return message. (There has already been a check in post_process_one() for the existence of data in the message file.) A TRUE return from print_address_information() means that the address is not hidden. */ paddr = &msgchain; for (addr = msgchain; addr; addr = *paddr) { if (print_address_information(addr, fp, US" ", US"\n ", US"")) print_address_error(addr, fp, US""); /* End the final line for the address */ fputc('\n', fp); /* Leave on msgchain if there's a return file. */ if (addr->return_file >= 0) { paddr = &(addr->next); filecount++; } /* Else save so that we can tick off the recipient when the message is sent. */ else { *paddr = addr->next; addr->next = handled_addr; handled_addr = addr; } } fputc('\n', fp); /* Get the next text, whether we need it or not, so as to be positioned for the one after. */ emf_text = next_emf(emf, US"generated text"); /* If there were any file messages passed by the local transports, include them in the message. Then put the address on the handled chain. In the case of a batch of addresses that were all sent to the same transport, the return_file field in all of them will contain the same fd, and the return_filename field in the *last* one will be set (to the name of the file). */ if (msgchain) { address_item *nextaddr; if (emf_text) fprintf(fp, "%s", CS emf_text); else fprintf(fp, "The following text was generated during the delivery " "attempt%s:\n", (filecount > 1)? "s" : ""); for (addr = msgchain; addr; addr = nextaddr) { FILE *fm; address_item *topaddr = addr; /* List all the addresses that relate to this file */ fputc('\n', fp); while(addr) /* Insurance */ { print_address_information(addr, fp, US"------ ", US"\n ", US" ------\n"); if (addr->return_filename) break; addr = addr->next; } fputc('\n', fp); /* Now copy the file */ if (!(fm = Ufopen(addr->return_filename, "rb"))) fprintf(fp, " +++ Exim error... failed to open text file: %s\n", strerror(errno)); else { while ((ch = fgetc(fm)) != EOF) fputc(ch, fp); (void)fclose(fm); } Uunlink(addr->return_filename); /* Can now add to handled chain, first fishing off the next address on the msgchain. */ nextaddr = addr->next; addr->next = handled_addr; handled_addr = topaddr; } fputc('\n', fp); } /* output machine readable part */ #ifdef SUPPORT_I18N if (message_smtputf8) fprintf(fp, "--%s\n" "Content-type: message/global-delivery-status\n\n" "Reporting-MTA: dns; %s\n", bound, smtp_active_hostname); else #endif fprintf(fp, "--%s\n" "Content-type: message/delivery-status\n\n" "Reporting-MTA: dns; %s\n", bound, smtp_active_hostname); if (dsn_envid) { /* must be decoded from xtext: see RFC 3461:6.3a */ uschar *xdec_envid; if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0) fprintf(fp, "Original-Envelope-ID: %s\n", dsn_envid); else fprintf(fp, "X-Original-Envelope-ID: error decoding xtext formatted ENVID\n"); } fputc('\n', fp); for (addr = handled_addr; addr; addr = addr->next) { host_item * hu; fprintf(fp, "Action: failed\n" "Final-Recipient: rfc822;%s\n" "Status: 5.0.0\n", addr->address); if ((hu = addr->host_used) && hu->name) { fprintf(fp, "Remote-MTA: dns; %s\n", hu->name); #ifdef EXPERIMENTAL_DSN_INFO { const uschar * s; if (hu->address) { uschar * p = hu->port == 25 ? US"" : string_sprintf(":%d", hu->port); fprintf(fp, "Remote-MTA: X-ip; [%s]%s\n", hu->address, p); } if ((s = addr->smtp_greeting) && *s) fprintf(fp, "X-Remote-MTA-smtp-greeting: X-str; %s\n", s); if ((s = addr->helo_response) && *s) fprintf(fp, "X-Remote-MTA-helo-response: X-str; %s\n", s); if ((s = addr->message) && *s) fprintf(fp, "X-Exim-Diagnostic: X-str; %s\n", s); } #endif print_dsn_diagnostic_code(addr, fp); } fputc('\n', fp); } /* Now copy the message, trying to give an intelligible comment if it is too long for it all to be copied. The limit isn't strictly applied because of the buffering. There is, however, an option to suppress copying altogether. */ emf_text = next_emf(emf, US"copy"); /* add message body we ignore the intro text from template and add the text for bounce_return_size_limit at the end. bounce_return_message is ignored in case RET= is defined we honor these values otherwise bounce_return_body is honored. bounce_return_size_limit is always honored. */ fprintf(fp, "--%s\n", bound); dsnlimitmsg = US"X-Exim-DSN-Information: Due to administrative limits only headers are returned"; dsnnotifyhdr = NULL; topt = topt_add_return_path; /* RET=HDRS? top priority */ if (dsn_ret == dsn_ret_hdrs) topt |= topt_no_body; else { struct stat statbuf; /* no full body return at all? */ if (!bounce_return_body) { topt |= topt_no_body; /* add header if we overrule RET=FULL */ if (dsn_ret == dsn_ret_full) dsnnotifyhdr = dsnlimitmsg; } /* line length limited... return headers only if oversize */ /* size limited ... return headers only if limit reached */ else if ( max_received_linelength > bounce_return_linesize_limit || ( bounce_return_size_limit > 0 && fstat(deliver_datafile, &statbuf) == 0 && statbuf.st_size > max ) ) { topt |= topt_no_body; dsnnotifyhdr = dsnlimitmsg; } } #ifdef SUPPORT_I18N if (message_smtputf8) fputs(topt & topt_no_body ? "Content-type: message/global-headers\n\n" : "Content-type: message/global\n\n", fp); else #endif fputs(topt & topt_no_body ? "Content-type: text/rfc822-headers\n\n" : "Content-type: message/rfc822\n\n", fp); fflush(fp); transport_filter_argv = NULL; /* Just in case */ return_path = sender_address; /* In case not previously set */ { /* Dummy transport for headers add */ transport_ctx tctx = {{0}}; transport_instance tb = {0}; tctx.u.fd = fileno(fp); tctx.tblock = &tb; tctx.options = topt; tb.add_headers = dsnnotifyhdr; transport_write_message(&tctx, 0); } fflush(fp); /* we never add the final text. close the file */ if (emf) (void)fclose(emf); fprintf(fp, "\n--%s--\n", bound); /* Close the file, which should send an EOF to the child process that is receiving the message. Wait for it to finish. */ (void)fclose(fp); rc = child_close(pid, 0); /* Waits for child to close, no timeout */ /* In the test harness, let the child do it's thing first. */ if (f.running_in_test_harness) millisleep(500); /* If the process failed, there was some disaster in setting up the error message. Unless the message is very old, ensure that addr_defer is non-null, which will have the effect of leaving the message on the spool. The failed addresses will get tried again next time. However, we don't really want this to happen too often, so freeze the message unless there are some genuine deferred addresses to try. To do this we have to call spool_write_header() here, because with no genuine deferred addresses the normal code below doesn't get run. */ if (rc != 0) { uschar *s = US""; if (now - received_time.tv_sec < retry_maximum_timeout && !addr_defer) { addr_defer = (address_item *)(+1); f.deliver_freeze = TRUE; deliver_frozen_at = time(NULL); /* Panic-dies on error */ (void)spool_write_header(message_id, SW_DELIVERING, NULL); s = US" (frozen)"; } deliver_msglog("Process failed (%d) when writing error message " "to %s%s", rc, bounce_recipient, s); log_write(0, LOG_MAIN, "Process failed (%d) when writing error message " "to %s%s", rc, bounce_recipient, s); } /* The message succeeded. Ensure that the recipients that failed are now marked finished with on the spool and their parents updated. */ else { for (addr = handled_addr; addr; addr = addr->next) { address_done(addr, logtod); child_done(addr, logtod); } /* Panic-dies on error */ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } } } } f.disable_logging = FALSE; /* In case left set */ /* Come here from the mua_wrapper case if routing goes wrong */ DELIVERY_TIDYUP: /* If there are now no deferred addresses, we are done. Preserve the message log if so configured, and we are using them. Otherwise, sling it. Then delete the message itself. */ if (!addr_defer) { uschar * fname; if (message_logs) { fname = spool_fname(US"msglog", message_subdir, id, US""); if (preserve_message_logs) { int rc; uschar * moname = spool_fname(US"msglog.OLD", US"", id, US""); if ((rc = Urename(fname, moname)) < 0) { (void)directory_make(spool_directory, spool_sname(US"msglog.OLD", US""), MSGLOG_DIRECTORY_MODE, TRUE); rc = Urename(fname, moname); } if (rc < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to move %s to the " "msglog.OLD directory", fname); } else if (Uunlink(fname) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to unlink %s: %s", fname, strerror(errno)); } /* Remove the two message files. */ fname = spool_fname(US"input", message_subdir, id, US"-D"); if (Uunlink(fname) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to unlink %s: %s", fname, strerror(errno)); fname = spool_fname(US"input", message_subdir, id, US"-H"); if (Uunlink(fname) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to unlink %s: %s", fname, strerror(errno)); /* Log the end of this message, with queue time if requested. */ if (LOGGING(queue_time_overall)) log_write(0, LOG_MAIN, "Completed QT=%s", string_timesince(&received_time)); else log_write(0, LOG_MAIN, "Completed"); /* Unset deliver_freeze so that we won't try to move the spool files further down */ f.deliver_freeze = FALSE; #ifndef DISABLE_EVENT (void) event_raise(event_action, US"msg:complete", NULL); #endif } /* If there are deferred addresses, we are keeping this message because it is not yet completed. Lose any temporary files that were catching output from pipes for any of the deferred addresses, handle one-time aliases, and see if the message has been on the queue for so long that it is time to send a warning message to the sender, unless it is a mailer-daemon. If all deferred addresses have the same domain, we can set deliver_domain for the expansion of delay_warning_ condition - if any of them are pipes, files, or autoreplies, use the parent's domain. If all the deferred addresses have an error number that indicates "retry time not reached", skip sending the warning message, because it won't contain the reason for the delay. It will get sent at the next real delivery attempt. However, if at least one address has tried, we'd better include all of them in the message. If we can't make a process to send the message, don't worry. For mailing list expansions we want to send the warning message to the mailing list manager. We can't do a perfect job here, as some addresses may have different errors addresses, but if we take the errors address from each deferred address it will probably be right in most cases. If addr_defer == +1, it means there was a problem sending an error message for failed addresses, and there were no "real" deferred addresses. The value was set just to keep the message on the spool, so there is nothing to do here. */ else if (addr_defer != (address_item *)(+1)) { address_item *addr; uschar *recipients = US""; BOOL delivery_attempted = FALSE; deliver_domain = testflag(addr_defer, af_pfr) ? addr_defer->parent->domain : addr_defer->domain; for (addr = addr_defer; addr; addr = addr->next) { address_item *otaddr; if (addr->basic_errno > ERRNO_RETRY_BASE) delivery_attempted = TRUE; if (deliver_domain) { const uschar *d = testflag(addr, af_pfr) ? addr->parent->domain : addr->domain; /* The domain may be unset for an address that has never been routed because the system filter froze the message. */ if (!d || Ustrcmp(d, deliver_domain) != 0) deliver_domain = NULL; } if (addr->return_filename) Uunlink(addr->return_filename); /* Handle the case of one-time aliases. If any address in the ancestry of this one is flagged, ensure it is in the recipients list, suitably flagged, and that its parent is marked delivered. */ for (otaddr = addr; otaddr; otaddr = otaddr->parent) if (otaddr->onetime_parent) break; if (otaddr) { int i; int t = recipients_count; for (i = 0; i < recipients_count; i++) { uschar *r = recipients_list[i].address; if (Ustrcmp(otaddr->onetime_parent, r) == 0) t = i; if (Ustrcmp(otaddr->address, r) == 0) break; } /* Didn't find the address already in the list, and did find the ultimate parent's address in the list, and they really are different (i.e. not from an identity-redirect). After adding the recipient, update the errors address in the recipients list. */ if ( i >= recipients_count && t < recipients_count && Ustrcmp(otaddr->address, otaddr->parent->address) != 0) { DEBUG(D_deliver) debug_printf("one_time: adding %s in place of %s\n", otaddr->address, otaddr->parent->address); receive_add_recipient(otaddr->address, t); recipients_list[recipients_count-1].errors_to = otaddr->prop.errors_address; tree_add_nonrecipient(otaddr->parent->address); update_spool = TRUE; } } /* Except for error messages, ensure that either the errors address for this deferred address or, if there is none, the sender address, is on the list of recipients for a warning message. */ if (sender_address[0]) { uschar * s = addr->prop.errors_address; if (!s) s = sender_address; if (Ustrstr(recipients, s) == NULL) recipients = string_sprintf("%s%s%s", recipients, recipients[0] ? "," : "", s); } } /* Send a warning message if the conditions are right. If the condition check fails because of a lookup defer, there is nothing we can do. The warning is not sent. Another attempt will be made at the next delivery attempt (if it also defers). */ if ( !f.queue_2stage && delivery_attempted && ( ((addr_defer->dsn_flags & rf_dsnflags) == 0) || (addr_defer->dsn_flags & rf_notify_delay) == rf_notify_delay ) && delay_warning[1] > 0 && sender_address[0] != 0 && ( !delay_warning_condition || expand_check_condition(delay_warning_condition, US"delay_warning", US"option") ) ) { int count; int show_time; int queue_time = time(NULL) - received_time.tv_sec; /* When running in the test harness, there's an option that allows us to fudge this time so as to get repeatability of the tests. Take the first time off the list. In queue runs, the list pointer gets updated in the calling process. */ if (f.running_in_test_harness && fudged_queue_times[0] != 0) { int qt = readconf_readtime(fudged_queue_times, '/', FALSE); if (qt >= 0) { DEBUG(D_deliver) debug_printf("fudged queue_times = %s\n", fudged_queue_times); queue_time = qt; } } /* See how many warnings we should have sent by now */ for (count = 0; count < delay_warning[1]; count++) if (queue_time < delay_warning[count+2]) break; show_time = delay_warning[count+1]; if (count >= delay_warning[1]) { int extra; int last_gap = show_time; if (count > 1) last_gap -= delay_warning[count]; extra = (queue_time - delay_warning[count+1])/last_gap; show_time += last_gap * extra; count += extra; } DEBUG(D_deliver) { debug_printf("time on queue = %s\n", readconf_printtime(queue_time)); debug_printf("warning counts: required %d done %d\n", count, warning_count); } /* We have computed the number of warnings there should have been by now. If there haven't been enough, send one, and up the count to what it should have been. */ if (warning_count < count) { header_line *h; int fd; pid_t pid = child_open_exim(&fd); if (pid > 0) { uschar *wmf_text; FILE *wmf = NULL; FILE *f = fdopen(fd, "wb"); uschar * bound; transport_ctx tctx = {{0}}; if (warn_message_file) if (!(wmf = Ufopen(warn_message_file, "rb"))) log_write(0, LOG_MAIN|LOG_PANIC, "Failed to open %s for warning " "message texts: %s", warn_message_file, strerror(errno)); warnmsg_recipients = recipients; warnmsg_delay = queue_time < 120*60 ? string_sprintf("%d minutes", show_time/60) : string_sprintf("%d hours", show_time/3600); if (errors_reply_to) fprintf(f, "Reply-To: %s\n", errors_reply_to); fprintf(f, "Auto-Submitted: auto-replied\n"); moan_write_from(f); fprintf(f, "To: %s\n", recipients); /* generated boundary string and output MIME-Headers */ bound = string_sprintf(TIME_T_FMT "-eximdsn-%d", time(NULL), rand()); fprintf(f, "Content-Type: multipart/report;" " report-type=delivery-status; boundary=%s\n" "MIME-Version: 1.0\n", bound); if ((wmf_text = next_emf(wmf, US"header"))) fprintf(f, "%s\n", wmf_text); else fprintf(f, "Subject: Warning: message %s delayed %s\n\n", message_id, warnmsg_delay); /* output human readable part as text/plain section */ fprintf(f, "--%s\n" "Content-type: text/plain; charset=us-ascii\n\n", bound); if ((wmf_text = next_emf(wmf, US"intro"))) fprintf(f, "%s", CS wmf_text); else { fprintf(f, "This message was created automatically by mail delivery software.\n"); if (Ustrcmp(recipients, sender_address) == 0) fprintf(f, "A message that you sent has not yet been delivered to one or more of its\n" "recipients after more than "); else fprintf(f, "A message sent by\n\n <%s>\n\n" "has not yet been delivered to one or more of its recipients after more than \n", sender_address); fprintf(f, "%s on the queue on %s.\n\n" "The message identifier is: %s\n", warnmsg_delay, primary_hostname, message_id); for (h = header_list; h; h = h->next) if (strncmpic(h->text, US"Subject:", 8) == 0) fprintf(f, "The subject of the message is: %s", h->text + 9); else if (strncmpic(h->text, US"Date:", 5) == 0) fprintf(f, "The date of the message is: %s", h->text + 6); fputc('\n', f); fprintf(f, "The address%s to which the message has not yet been " "delivered %s:\n", !addr_defer->next ? "" : "es", !addr_defer->next ? "is": "are"); } /* List the addresses, with error information if allowed */ /* store addr_defer for machine readable part */ address_item *addr_dsndefer = addr_defer; fputc('\n', f); while (addr_defer) { address_item *addr = addr_defer; addr_defer = addr->next; if (print_address_information(addr, f, US" ", US"\n ", US"")) print_address_error(addr, f, US"Delay reason: "); fputc('\n', f); } fputc('\n', f); /* Final text */ if (wmf) { if ((wmf_text = next_emf(wmf, US"final"))) fprintf(f, "%s", CS wmf_text); (void)fclose(wmf); } else { fprintf(f, "No action is required on your part. Delivery attempts will continue for\n" "some time, and this warning may be repeated at intervals if the message\n" "remains undelivered. Eventually the mail delivery software will give up,\n" "and when that happens, the message will be returned to you.\n"); } /* output machine readable part */ fprintf(f, "\n--%s\n" "Content-type: message/delivery-status\n\n" "Reporting-MTA: dns; %s\n", bound, smtp_active_hostname); if (dsn_envid) { /* must be decoded from xtext: see RFC 3461:6.3a */ uschar *xdec_envid; if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0) fprintf(f,"Original-Envelope-ID: %s\n", dsn_envid); else fprintf(f,"X-Original-Envelope-ID: error decoding xtext formatted ENVID\n"); } fputc('\n', f); for ( ; addr_dsndefer; addr_dsndefer = addr_dsndefer->next) { if (addr_dsndefer->dsn_orcpt) fprintf(f, "Original-Recipient: %s\n", addr_dsndefer->dsn_orcpt); fprintf(f, "Action: delayed\n" "Final-Recipient: rfc822;%s\n" "Status: 4.0.0\n", addr_dsndefer->address); if (addr_dsndefer->host_used && addr_dsndefer->host_used->name) { fprintf(f, "Remote-MTA: dns; %s\n", addr_dsndefer->host_used->name); print_dsn_diagnostic_code(addr_dsndefer, f); } fputc('\n', f); } fprintf(f, "--%s\n" "Content-type: text/rfc822-headers\n\n", bound); fflush(f); /* header only as required by RFC. only failure DSN needs to honor RET=FULL */ tctx.u.fd = fileno(f); tctx.options = topt_add_return_path | topt_no_body; transport_filter_argv = NULL; /* Just in case */ return_path = sender_address; /* In case not previously set */ /* Write the original email out */ transport_write_message(&tctx, 0); fflush(f); fprintf(f,"\n--%s--\n", bound); fflush(f); /* Close and wait for child process to complete, without a timeout. If there's an error, don't update the count. */ (void)fclose(f); if (child_close(pid, 0) == 0) { warning_count = count; update_spool = TRUE; /* Ensure spool rewritten */ } } } } /* Clear deliver_domain */ deliver_domain = NULL; /* If this was a first delivery attempt, unset the first time flag, and ensure that the spool gets updated. */ if (f.deliver_firsttime) { f.deliver_firsttime = FALSE; update_spool = TRUE; } /* If delivery was frozen and freeze_tell is set, generate an appropriate message, unless the message is a local error message (to avoid loops). Then log the freezing. If the text in "frozen_info" came from a system filter, it has been escaped into printing characters so as not to mess up log lines. For the "tell" message, we turn \n back into newline. Also, insert a newline near the start instead of the ": " string. */ if (f.deliver_freeze) { if (freeze_tell && freeze_tell[0] != 0 && !f.local_error_message) { uschar *s = string_copy(frozen_info); uschar *ss = Ustrstr(s, " by the system filter: "); if (ss != NULL) { ss[21] = '.'; ss[22] = '\n'; } ss = s; while (*ss != 0) { if (*ss == '\\' && ss[1] == 'n') { *ss++ = ' '; *ss++ = '\n'; } else ss++; } moan_tell_someone(freeze_tell, addr_defer, US"Message frozen", "Message %s has been frozen%s.\nThe sender is <%s>.\n", message_id, s, sender_address); } /* Log freezing just before we update the -H file, to minimize the chance of a race problem. */ deliver_msglog("*** Frozen%s\n", frozen_info); log_write(0, LOG_MAIN, "Frozen%s", frozen_info); } /* If there have been any updates to the non-recipients list, or other things that get written to the spool, we must now update the spool header file so that it has the right information for the next delivery attempt. If there was more than one address being delivered, the header_change update is done earlier, in case one succeeds and then something crashes. */ DEBUG(D_deliver) debug_printf("delivery deferred: update_spool=%d header_rewritten=%d\n", update_spool, f.header_rewritten); if (update_spool || f.header_rewritten) /* Panic-dies on error */ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } /* Finished with the message log. If the message is complete, it will have been unlinked or renamed above. */ if (message_logs) (void)fclose(message_log); /* Now we can close and remove the journal file. Its only purpose is to record successfully completed deliveries asap so that this information doesn't get lost if Exim (or the machine) crashes. Forgetting about a failed delivery is not serious, as trying it again is not harmful. The journal might not be open if all addresses were deferred at routing or directing. Nevertheless, we must remove it if it exists (may have been lying around from a crash during the previous delivery attempt). We don't remove the journal if a delivery subprocess failed to pass back delivery information; this is controlled by the remove_journal flag. When the journal is left, we also don't move the message off the main spool if frozen and the option is set. It should get moved at the next attempt, after the journal has been inspected. */ if (journal_fd >= 0) (void)close(journal_fd); if (remove_journal) { uschar * fname = spool_fname(US"input", message_subdir, id, US"-J"); if (Uunlink(fname) < 0 && errno != ENOENT) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to unlink %s: %s", fname, strerror(errno)); /* Move the message off the spool if requested */ #ifdef SUPPORT_MOVE_FROZEN_MESSAGES if (f.deliver_freeze && move_frozen_messages) (void)spool_move_message(id, message_subdir, US"", US"F"); #endif } /* Closing the data file frees the lock; if the file has been unlinked it will go away. Otherwise the message becomes available for another process to try delivery. */ (void)close(deliver_datafile); deliver_datafile = -1; DEBUG(D_deliver) debug_printf("end delivery of %s\n", id); /* It is unlikely that there will be any cached resources, since they are released after routing, and in the delivery subprocesses. However, it's possible for an expansion for something afterwards (for example, expand_check_condition) to do a lookup. We must therefore be sure everything is released. */ search_tidyup(); acl_where = ACL_WHERE_UNKNOWN; return final_yield; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-78'], 'message': 'Events: raise msg:fail:internal & msg:complete for -Mrm. Bug 2310'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: con_insert_unipair(struct uni_pagedir *p, u_short unicode, u_short fontpos) { int i, n; u16 **p1, *p2; p1 = p->uni_pgdir[n = unicode >> 11]; if (!p1) { p1 = p->uni_pgdir[n] = kmalloc_array(32, sizeof(u16 *), GFP_KERNEL); if (!p1) return -ENOMEM; for (i = 0; i < 32; i++) p1[i] = NULL; } p2 = p1[n = (unicode >> 6) & 0x1f]; if (!p2) { p2 = p1[n] = kmalloc_array(64, sizeof(u16), GFP_KERNEL); if (!p2) return -ENOMEM; memset(p2, 0xff, 64*sizeof(u16)); /* No glyphs for the characters (yet) */ } p2[unicode & 0x3f] = fontpos; p->sum += (fontpos << 20) + unicode; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'consolemap: Fix a memory leaking bug in drivers/tty/vt/consolemap.c In function con_insert_unipair(), when allocation for p2 and p1[n] fails, ENOMEM is returned, but previously allocated p1 is not freed, remains as leaking memory. Thus we should free p1 as well when this allocation fails. Signed-off-by: Gen Zhang <[email protected]> Reviewed-by: Kees Cook <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: pgd_t * __init efi_call_phys_prolog(void) { unsigned long vaddr, addr_pgd, addr_p4d, addr_pud; pgd_t *save_pgd, *pgd_k, *pgd_efi; p4d_t *p4d, *p4d_k, *p4d_efi; pud_t *pud; int pgd; int n_pgds, i, j; if (!efi_enabled(EFI_OLD_MEMMAP)) { efi_switch_mm(&efi_mm); return NULL; } early_code_mapping_set_exec(1); n_pgds = DIV_ROUND_UP((max_pfn << PAGE_SHIFT), PGDIR_SIZE); save_pgd = kmalloc_array(n_pgds, sizeof(*save_pgd), GFP_KERNEL); /* * Build 1:1 identity mapping for efi=old_map usage. Note that * PAGE_OFFSET is PGDIR_SIZE aligned when KASLR is disabled, while * it is PUD_SIZE ALIGNED with KASLR enabled. So for a given physical * address X, the pud_index(X) != pud_index(__va(X)), we can only copy * PUD entry of __va(X) to fill in pud entry of X to build 1:1 mapping. * This means here we can only reuse the PMD tables of the direct mapping. */ for (pgd = 0; pgd < n_pgds; pgd++) { addr_pgd = (unsigned long)(pgd * PGDIR_SIZE); vaddr = (unsigned long)__va(pgd * PGDIR_SIZE); pgd_efi = pgd_offset_k(addr_pgd); save_pgd[pgd] = *pgd_efi; p4d = p4d_alloc(&init_mm, pgd_efi, addr_pgd); if (!p4d) { pr_err("Failed to allocate p4d table!\n"); goto out; } for (i = 0; i < PTRS_PER_P4D; i++) { addr_p4d = addr_pgd + i * P4D_SIZE; p4d_efi = p4d + p4d_index(addr_p4d); pud = pud_alloc(&init_mm, p4d_efi, addr_p4d); if (!pud) { pr_err("Failed to allocate pud table!\n"); goto out; } for (j = 0; j < PTRS_PER_PUD; j++) { addr_pud = addr_p4d + j * PUD_SIZE; if (addr_pud > (max_pfn << PAGE_SHIFT)) break; vaddr = (unsigned long)__va(addr_pud); pgd_k = pgd_offset_k(vaddr); p4d_k = p4d_offset(pgd_k, vaddr); pud[j] = *pud_offset(p4d_k, vaddr); } } pgd_offset_k(pgd * PGDIR_SIZE)->pgd &= ~_PAGE_NX; } out: __flush_tlb_all(); return save_pgd; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-388'], 'message': 'efi/x86/Add missing error handling to old_memmap 1:1 mapping code The old_memmap flow in efi_call_phys_prolog() performs numerous memory allocations, and either does not check for failure at all, or it does but fails to propagate it back to the caller, which may end up calling into the firmware with an incomplete 1:1 mapping. So let's fix this by returning NULL from efi_call_phys_prolog() on memory allocation failures only, and by handling this condition in the caller. Also, clean up any half baked sets of page tables that we may have created before returning with a NULL return value. Note that any failure at this level will trigger a panic() two levels up, so none of this makes a huge difference, but it is a nice cleanup nonetheless. [ardb: update commit log, add efi_call_phys_epilog() call on error path] Signed-off-by: Gen Zhang <[email protected]> Signed-off-by: Ard Biesheuvel <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Rob Bradford <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: [email protected] Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ip_ra_control(struct sock *sk, unsigned char on, void (*destructor)(struct sock *)) { struct ip_ra_chain *ra, *new_ra; struct ip_ra_chain __rcu **rap; struct net *net = sock_net(sk); if (sk->sk_type != SOCK_RAW || inet_sk(sk)->inet_num == IPPROTO_RAW) return -EINVAL; new_ra = on ? kmalloc(sizeof(*new_ra), GFP_KERNEL) : NULL; mutex_lock(&net->ipv4.ra_mutex); for (rap = &net->ipv4.ra_chain; (ra = rcu_dereference_protected(*rap, lockdep_is_held(&net->ipv4.ra_mutex))) != NULL; rap = &ra->next) { if (ra->sk == sk) { if (on) { mutex_unlock(&net->ipv4.ra_mutex); kfree(new_ra); return -EADDRINUSE; } /* dont let ip_call_ra_chain() use sk again */ ra->sk = NULL; RCU_INIT_POINTER(*rap, ra->next); mutex_unlock(&net->ipv4.ra_mutex); if (ra->destructor) ra->destructor(sk); /* * Delay sock_put(sk) and kfree(ra) after one rcu grace * period. This guarantee ip_call_ra_chain() dont need * to mess with socket refcounts. */ ra->saved_sk = sk; call_rcu(&ra->rcu, ip_ra_destroy_rcu); return 0; } } if (!new_ra) { mutex_unlock(&net->ipv4.ra_mutex); return -ENOBUFS; } new_ra->sk = sk; new_ra->destructor = destructor; RCU_INIT_POINTER(new_ra->next, ra); rcu_assign_pointer(*rap, new_ra); sock_hold(sk); mutex_unlock(&net->ipv4.ra_mutex); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'ip_sockglue: Fix missing-check bug in ip_ra_control() In function ip_ra_control(), the pointer new_ra is allocated a memory space via kmalloc(). And it is used in the following codes. However, when there is a memory allocation error, kmalloc() fails. Thus null pointer dereference may happen. And it will cause the kernel to crash. Therefore, we should check the return value and handle the error. Signed-off-by: Gen Zhang <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: tiff_document_get_thumbnail (EvDocument *document, EvRenderContext *rc) { TiffDocument *tiff_document = TIFF_DOCUMENT (document); int width, height; int scaled_width, scaled_height; float x_res, y_res; gint rowstride, bytes; guchar *pixels = NULL; GdkPixbuf *pixbuf; GdkPixbuf *scaled_pixbuf; GdkPixbuf *rotated_pixbuf; push_handlers (); if (TIFFSetDirectory (tiff_document->tiff, rc->page->index) != 1) { pop_handlers (); return NULL; } if (!TIFFGetField (tiff_document->tiff, TIFFTAG_IMAGEWIDTH, &width)) { pop_handlers (); return NULL; } if (! TIFFGetField (tiff_document->tiff, TIFFTAG_IMAGELENGTH, &height)) { pop_handlers (); return NULL; } tiff_document_get_resolution (tiff_document, &x_res, &y_res); pop_handlers (); /* Sanity check the doc */ if (width <= 0 || height <= 0) return NULL; if (width >= INT_MAX / 4) /* overflow */ return NULL; rowstride = width * 4; if (height >= INT_MAX / rowstride) /* overflow */ return NULL; bytes = height * rowstride; pixels = g_try_malloc (bytes); if (!pixels) return NULL; pixbuf = gdk_pixbuf_new_from_data (pixels, GDK_COLORSPACE_RGB, TRUE, 8, width, height, rowstride, (GdkPixbufDestroyNotify) g_free, NULL); TIFFReadRGBAImageOriented (tiff_document->tiff, width, height, (uint32 *)pixels, ORIENTATION_TOPLEFT, 0); pop_handlers (); ev_render_context_compute_scaled_size (rc, width, height * (x_res / y_res), &scaled_width, &scaled_height); scaled_pixbuf = gdk_pixbuf_scale_simple (pixbuf, scaled_width, scaled_height, GDK_INTERP_BILINEAR); g_object_unref (pixbuf); rotated_pixbuf = gdk_pixbuf_rotate_simple (scaled_pixbuf, 360 - rc->rotation); g_object_unref (scaled_pixbuf); return rotated_pixbuf; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-754'], 'message': 'tiff: Handle failure from TIFFReadRGBAImageOriented The TIFFReadRGBAImageOriented function returns zero if it was unable to read the image. Return NULL in this case instead of displaying uninitialized memory. Fixes #1129'</s>
<s>[INST] Given the following code containing errors, provide 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 tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr) { struct tun_struct *tun; struct tun_file *tfile = file->private_data; struct net_device *dev; int err; if (tfile->detached) return -EINVAL; dev = __dev_get_by_name(net, ifr->ifr_name); if (dev) { if (ifr->ifr_flags & IFF_TUN_EXCL) return -EBUSY; if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops) tun = netdev_priv(dev); else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops) tun = netdev_priv(dev); else return -EINVAL; if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) != !!(tun->flags & IFF_MULTI_QUEUE)) return -EINVAL; if (tun_not_capable(tun)) return -EPERM; err = security_tun_dev_open(tun->security); if (err < 0) return err; err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER); if (err < 0) return err; if (tun->flags & IFF_MULTI_QUEUE && (tun->numqueues + tun->numdisabled > 1)) { /* One or more queue has already been attached, no need * to initialize the device again. */ return 0; } } else { char *name; unsigned long flags = 0; int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ? MAX_TAP_QUEUES : 1; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) return -EPERM; err = security_tun_dev_create(); if (err < 0) return err; /* Set dev type */ if (ifr->ifr_flags & IFF_TUN) { /* TUN device */ flags |= IFF_TUN; name = "tun%d"; } else if (ifr->ifr_flags & IFF_TAP) { /* TAP device */ flags |= IFF_TAP; name = "tap%d"; } else return -EINVAL; if (*ifr->ifr_name) name = ifr->ifr_name; dev = alloc_netdev_mqs(sizeof(struct tun_struct), name, NET_NAME_UNKNOWN, tun_setup, queues, queues); if (!dev) return -ENOMEM; dev_net_set(dev, net); dev->rtnl_link_ops = &tun_link_ops; dev->ifindex = tfile->ifindex; dev->sysfs_groups[0] = &tun_attr_group; tun = netdev_priv(dev); tun->dev = dev; tun->flags = flags; tun->txflt.count = 0; tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr); tun->align = NET_SKB_PAD; tun->filter_attached = false; tun->sndbuf = tfile->socket.sk->sk_sndbuf; tun->rx_batched = 0; tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats); if (!tun->pcpu_stats) { err = -ENOMEM; goto err_free_dev; } spin_lock_init(&tun->lock); err = security_tun_dev_alloc_security(&tun->security); if (err < 0) goto err_free_stat; tun_net_init(dev); tun_flow_init(tun); dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST | TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_TX; dev->features = dev->hw_features | NETIF_F_LLTX; dev->vlan_features = dev->features & ~(NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_TX); INIT_LIST_HEAD(&tun->disabled); err = tun_attach(tun, file, false); if (err < 0) goto err_free_flow; err = register_netdevice(tun->dev); if (err < 0) goto err_detach; } netif_carrier_on(tun->dev); tun_debug(KERN_INFO, tun, "tun_set_iff\n"); tun->flags = (tun->flags & ~TUN_FEATURES) | (ifr->ifr_flags & TUN_FEATURES); /* Make sure persistent devices do not get stuck in * xoff state. */ if (netif_running(tun->dev)) netif_tx_wake_all_queues(tun->dev); strcpy(ifr->ifr_name, tun->dev->name); return 0; err_detach: tun_detach_all(dev); /* register_netdevice() already called tun_free_netdev() */ goto err_free_dev; err_free_flow: tun_flow_uninit(tun); security_tun_dev_free_security(tun->security); err_free_stat: free_percpu(tun->pcpu_stats); err_free_dev: free_netdev(dev); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'tun: call dev_get_valid_name() before register_netdevice() register_netdevice() could fail early when we have an invalid dev name, in which case ->ndo_uninit() is not called. For tun device, this is a problem because a timer etc. are already initialized and it expects ->ndo_uninit() to clean them up. We could move these initializations into a ->ndo_init() so that register_netdevice() knows better, however this is still complicated due to the logic in tun_detach(). Therefore, I choose to just call dev_get_valid_name() before register_netdevice(), which is quicker and much easier to audit. And for this specific case, it is already enough. Fixes: 96442e42429e ("tuntap: choose the txq based on rxq") Reported-by: Dmitry Alexeev <[email protected]> Cc: Jason Wang <[email protected]> Cc: "Michael S. Tsirkin" <[email protected]> Signed-off-by: Cong Wang <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: exsltDynMapFunction(xmlXPathParserContextPtr ctxt, int nargs) { xmlChar *str = NULL; xmlNodeSetPtr nodeset = NULL; xsltTransformContextPtr tctxt; xmlXPathCompExprPtr comp = NULL; xmlXPathObjectPtr ret = NULL; xmlDocPtr oldDoc, container = NULL; xmlNodePtr oldNode; int oldContextSize; int oldProximityPosition; int i, j; if (nargs != 2) { xmlXPathSetArityError(ctxt); return; } str = xmlXPathPopString(ctxt); if (xmlXPathCheckError(ctxt)) { xmlXPathSetTypeError(ctxt); return; } nodeset = xmlXPathPopNodeSet(ctxt); if (xmlXPathCheckError(ctxt)) { xmlXPathSetTypeError(ctxt); return; } if (str == NULL || !xmlStrlen(str) || !(comp = xmlXPathCompile(str))) { if (nodeset != NULL) xmlXPathFreeNodeSet(nodeset); if (str != NULL) xmlFree(str); valuePush(ctxt, xmlXPathNewNodeSet(NULL)); return; } ret = xmlXPathNewNodeSet(NULL); if (ret == NULL) { xsltGenericError(xsltGenericErrorContext, "exsltDynMapFunction: ret == NULL\n"); goto cleanup; } oldDoc = ctxt->context->doc; oldNode = ctxt->context->node; oldContextSize = ctxt->context->contextSize; oldProximityPosition = ctxt->context->proximityPosition; /** * since we really don't know we're going to be adding node(s) * down the road we create the RVT regardless */ tctxt = xsltXPathGetTransformContext(ctxt); if (tctxt == NULL) { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "dyn:map : internal error tctxt == NULL\n"); goto cleanup; } container = xsltCreateRVT(tctxt); if (container == NULL) { xsltTransformError(tctxt, NULL, NULL, "dyn:map : internal error container == NULL\n"); goto cleanup; } xsltRegisterLocalRVT(tctxt, container); if (nodeset && nodeset->nodeNr > 0) { xmlXPathNodeSetSort(nodeset); ctxt->context->contextSize = nodeset->nodeNr; ctxt->context->proximityPosition = 0; for (i = 0; i < nodeset->nodeNr; i++) { xmlXPathObjectPtr subResult = NULL; ctxt->context->proximityPosition++; ctxt->context->node = nodeset->nodeTab[i]; ctxt->context->doc = nodeset->nodeTab[i]->doc; subResult = xmlXPathCompiledEval(comp, ctxt->context); if (subResult != NULL) { switch (subResult->type) { case XPATH_NODESET: if (subResult->nodesetval != NULL) for (j = 0; j < subResult->nodesetval->nodeNr; j++) xmlXPathNodeSetAdd(ret->nodesetval, subResult->nodesetval-> nodeTab[j]); break; case XPATH_BOOLEAN: if (container != NULL) { xmlNodePtr cur = xmlNewChild((xmlNodePtr) container, NULL, BAD_CAST "boolean", BAD_CAST (subResult-> boolval ? "true" : "")); if (cur != NULL) { cur->ns = xmlNewNs(cur, BAD_CAST "http://exslt.org/common", BAD_CAST "exsl"); xmlXPathNodeSetAddUnique(ret->nodesetval, cur); } xsltExtensionInstructionResultRegister(tctxt, ret); } break; case XPATH_NUMBER: if (container != NULL) { xmlChar *val = xmlXPathCastNumberToString(subResult-> floatval); xmlNodePtr cur = xmlNewChild((xmlNodePtr) container, NULL, BAD_CAST "number", val); if (val != NULL) xmlFree(val); if (cur != NULL) { cur->ns = xmlNewNs(cur, BAD_CAST "http://exslt.org/common", BAD_CAST "exsl"); xmlXPathNodeSetAddUnique(ret->nodesetval, cur); } xsltExtensionInstructionResultRegister(tctxt, ret); } break; case XPATH_STRING: if (container != NULL) { xmlNodePtr cur = xmlNewChild((xmlNodePtr) container, NULL, BAD_CAST "string", subResult->stringval); if (cur != NULL) { cur->ns = xmlNewNs(cur, BAD_CAST "http://exslt.org/common", BAD_CAST "exsl"); xmlXPathNodeSetAddUnique(ret->nodesetval, cur); } xsltExtensionInstructionResultRegister(tctxt, ret); } break; default: break; } xmlXPathFreeObject(subResult); } } } ctxt->context->doc = oldDoc; ctxt->context->node = oldNode; ctxt->context->contextSize = oldContextSize; ctxt->context->proximityPosition = oldProximityPosition; cleanup: /* restore the xpath context */ if (comp != NULL) xmlXPathFreeCompExpr(comp); if (nodeset != NULL) xmlXPathFreeNodeSet(nodeset); if (str != NULL) xmlFree(str); valuePush(ctxt, ret); return; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix dyn:map with namespace nodes exsltDynMapFunction didn't handle namespace nodes correctly. Namespace nodes are actually an xmlNs, not an xmlNode and must be special-cased. The old code initialized the doc pointer in the XPath context struct with a value read from past the end of the xmlNs struct. Typically, this resulted in a segfault. Found with afl-fuzz and ASan.'</s>
<s>[INST] Given the following code containing errors, provide 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 sandbox(void* sandbox_arg) { // Get rid of unused parameter warning (void)sandbox_arg; pid_t child_pid = getpid(); if (arg_debug) printf("Initializing child process\n"); // close each end of the unused pipes close(parent_to_child_fds[1]); close(child_to_parent_fds[0]); // wait for parent to do base setup wait_for_other(parent_to_child_fds[0]); if (arg_debug && child_pid == 1) printf("PID namespace installed\n"); //**************************** // set hostname //**************************** if (cfg.hostname) { if (sethostname(cfg.hostname, strlen(cfg.hostname)) < 0) errExit("sethostname"); } //**************************** // mount namespace //**************************** // mount events are not forwarded between the host the sandbox if (mount(NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0) { chk_chroot(); } // ... and mount a tmpfs on top of /run/firejail/mnt directory preproc_mount_mnt_dir(); // bind-mount firejail binaries and helper programs if (mount(LIBDIR "/firejail", RUN_FIREJAIL_LIB_DIR, "none", MS_BIND, NULL) < 0) errExit("mounting " RUN_FIREJAIL_LIB_DIR); //**************************** // log sandbox data //**************************** if (cfg.name) fs_logger2("sandbox name:", cfg.name); fs_logger2int("sandbox pid:", (int) sandbox_pid); if (cfg.chrootdir) fs_logger("sandbox filesystem: chroot"); else if (arg_overlay) fs_logger("sandbox filesystem: overlay"); else fs_logger("sandbox filesystem: local"); fs_logger("install mount namespace"); //**************************** // netfilter //**************************** if (arg_netfilter && any_bridge_configured()) { // assuming by default the client filter netfilter(arg_netfilter_file); } if (arg_netfilter6 && any_bridge_configured()) { // assuming by default the client filter netfilter6(arg_netfilter6_file); } //**************************** // networking //**************************** int gw_cfg_failed = 0; // default gw configuration flag if (arg_nonetwork) { net_if_up("lo"); if (arg_debug) printf("Network namespace enabled, only loopback interface available\n"); } else if (arg_netns) { netns(arg_netns); if (arg_debug) printf("Network namespace '%s' activated\n", arg_netns); } else if (any_bridge_configured() || any_interface_configured()) { // configure lo and eth0...eth3 net_if_up("lo"); if (mac_not_zero(cfg.bridge0.macsandbox)) net_config_mac(cfg.bridge0.devsandbox, cfg.bridge0.macsandbox); sandbox_if_up(&cfg.bridge0); if (mac_not_zero(cfg.bridge1.macsandbox)) net_config_mac(cfg.bridge1.devsandbox, cfg.bridge1.macsandbox); sandbox_if_up(&cfg.bridge1); if (mac_not_zero(cfg.bridge2.macsandbox)) net_config_mac(cfg.bridge2.devsandbox, cfg.bridge2.macsandbox); sandbox_if_up(&cfg.bridge2); if (mac_not_zero(cfg.bridge3.macsandbox)) net_config_mac(cfg.bridge3.devsandbox, cfg.bridge3.macsandbox); sandbox_if_up(&cfg.bridge3); // moving an interface in a namespace using --interface will reset the interface configuration; // we need to put the configuration back if (cfg.interface0.configured && cfg.interface0.ip) { if (arg_debug) printf("Configuring %d.%d.%d.%d address on interface %s\n", PRINT_IP(cfg.interface0.ip), cfg.interface0.dev); net_config_interface(cfg.interface0.dev, cfg.interface0.ip, cfg.interface0.mask, cfg.interface0.mtu); } if (cfg.interface1.configured && cfg.interface1.ip) { if (arg_debug) printf("Configuring %d.%d.%d.%d address on interface %s\n", PRINT_IP(cfg.interface1.ip), cfg.interface1.dev); net_config_interface(cfg.interface1.dev, cfg.interface1.ip, cfg.interface1.mask, cfg.interface1.mtu); } if (cfg.interface2.configured && cfg.interface2.ip) { if (arg_debug) printf("Configuring %d.%d.%d.%d address on interface %s\n", PRINT_IP(cfg.interface2.ip), cfg.interface2.dev); net_config_interface(cfg.interface2.dev, cfg.interface2.ip, cfg.interface2.mask, cfg.interface2.mtu); } if (cfg.interface3.configured && cfg.interface3.ip) { if (arg_debug) printf("Configuring %d.%d.%d.%d address on interface %s\n", PRINT_IP(cfg.interface3.ip), cfg.interface3.dev); net_config_interface(cfg.interface3.dev, cfg.interface3.ip, cfg.interface3.mask, cfg.interface3.mtu); } // add a default route if (cfg.defaultgw) { // set the default route if (net_add_route(0, 0, cfg.defaultgw)) { fwarning("cannot configure default route\n"); gw_cfg_failed = 1; } } if (arg_debug) printf("Network namespace enabled\n"); } // print network configuration if (!arg_quiet) { if (any_bridge_configured() || any_interface_configured() || cfg.defaultgw || cfg.dns1) { fmessage("\n"); if (any_bridge_configured() || any_interface_configured()) { if (arg_scan) sbox_run(SBOX_ROOT | SBOX_CAPS_NETWORK | SBOX_SECCOMP, 3, PATH_FNET, "printif", "scan"); else sbox_run(SBOX_ROOT | SBOX_CAPS_NETWORK | SBOX_SECCOMP, 2, PATH_FNET, "printif"); } if (cfg.defaultgw != 0) { if (gw_cfg_failed) fmessage("Default gateway configuration failed\n"); else fmessage("Default gateway %d.%d.%d.%d\n", PRINT_IP(cfg.defaultgw)); } if (cfg.dns1 != NULL) fmessage("DNS server %s\n", cfg.dns1); if (cfg.dns2 != NULL) fmessage("DNS server %s\n", cfg.dns2); if (cfg.dns3 != NULL) fmessage("DNS server %s\n", cfg.dns3); if (cfg.dns4 != NULL) fmessage("DNS server %s\n", cfg.dns4); fmessage("\n"); } } // load IBUS env variables if (arg_nonetwork || any_bridge_configured() || any_interface_configured()) { // do nothing - there are problems with ibus version 1.5.11 } else { EUID_USER(); env_ibus_load(); EUID_ROOT(); } //**************************** // fs pre-processing: // - build seccomp filters // - create an empty /etc/ld.so.preload //**************************** #ifdef HAVE_SECCOMP if (cfg.protocol) { if (arg_debug) printf("Build protocol filter: %s\n", cfg.protocol); // build the seccomp filter as a regular user int rv = sbox_run(SBOX_USER | SBOX_CAPS_NONE | SBOX_SECCOMP, 5, PATH_FSECCOMP, "protocol", "build", cfg.protocol, RUN_SECCOMP_PROTOCOL); if (rv) exit(rv); } if (arg_seccomp && (cfg.seccomp_list || cfg.seccomp_list_drop || cfg.seccomp_list_keep)) arg_seccomp_postexec = 1; #endif // need ld.so.preload if tracing or seccomp with any non-default lists bool need_preload = arg_trace || arg_tracelog || arg_seccomp_postexec; // for --appimage, --chroot and --overlay* we force NO_NEW_PRIVS // and drop all capabilities if (getuid() != 0 && (arg_appimage || cfg.chrootdir || arg_overlay)) { enforce_filters(); need_preload = arg_trace || arg_tracelog; } // trace pre-install if (need_preload) fs_trace_preload(); // store hosts file if (cfg.hosts_file) fs_store_hosts_file(); //**************************** // configure filesystem //**************************** #ifdef HAVE_CHROOT if (cfg.chrootdir) { fs_chroot(cfg.chrootdir); //**************************** // trace pre-install, this time inside chroot //**************************** if (need_preload) fs_trace_preload(); } else #endif #ifdef HAVE_OVERLAYFS if (arg_overlay) fs_overlayfs(); else #endif fs_basic_fs(); //**************************** // private mode //**************************** if (arg_private) { if (cfg.home_private) { // --private= if (cfg.chrootdir) fwarning("private=directory feature is disabled in chroot\n"); else if (arg_overlay) fwarning("private=directory feature is disabled in overlay\n"); else fs_private_homedir(); } else if (cfg.home_private_keep) { // --private-home= if (cfg.chrootdir) fwarning("private-home= feature is disabled in chroot\n"); else if (arg_overlay) fwarning("private-home= feature is disabled in overlay\n"); else fs_private_home_list(); } else // --private fs_private(); } if (arg_private_dev) fs_private_dev(); if (arg_private_etc) { if (cfg.chrootdir) fwarning("private-etc feature is disabled in chroot\n"); else if (arg_overlay) fwarning("private-etc feature is disabled in overlay\n"); else { fs_private_dir_list("/etc", RUN_ETC_DIR, cfg.etc_private_keep); // create /etc/ld.so.preload file again if (need_preload) fs_trace_preload(); } } if (arg_private_opt) { if (cfg.chrootdir) fwarning("private-opt feature is disabled in chroot\n"); else if (arg_overlay) fwarning("private-opt feature is disabled in overlay\n"); else { fs_private_dir_list("/opt", RUN_OPT_DIR, cfg.opt_private_keep); } } if (arg_private_srv) { if (cfg.chrootdir) fwarning("private-srv feature is disabled in chroot\n"); else if (arg_overlay) fwarning("private-srv feature is disabled in overlay\n"); else { fs_private_dir_list("/srv", RUN_SRV_DIR, cfg.srv_private_keep); } } // private-bin is disabled for appimages if (arg_private_bin && !arg_appimage) { if (cfg.chrootdir) fwarning("private-bin feature is disabled in chroot\n"); else if (arg_overlay) fwarning("private-bin feature is disabled in overlay\n"); else { // for --x11=xorg we need to add xauth command if (arg_x11_xorg) { EUID_USER(); char *tmp; if (asprintf(&tmp, "%s,xauth", cfg.bin_private_keep) == -1) errExit("asprintf"); cfg.bin_private_keep = tmp; EUID_ROOT(); } fs_private_bin_list(); } } // private-lib is disabled for appimages if (arg_private_lib && !arg_appimage) { if (cfg.chrootdir) fwarning("private-lib feature is disabled in chroot\n"); else if (arg_overlay) fwarning("private-lib feature is disabled in overlay\n"); else { fs_private_lib(); } } if (arg_private_cache) { if (cfg.chrootdir) fwarning("private-cache feature is disabled in chroot\n"); else if (arg_overlay) fwarning("private-cache feature is disabled in overlay\n"); else fs_private_cache(); } if (arg_private_tmp) { // private-tmp is implemented as a whitelist EUID_USER(); fs_private_tmp(); EUID_ROOT(); } //**************************** // Session D-BUS //**************************** if (arg_nodbus) dbus_session_disable(); //**************************** // hosts and hostname //**************************** if (cfg.hostname) fs_hostname(cfg.hostname); if (cfg.hosts_file) fs_mount_hosts_file(); //**************************** // /etc overrides from the network namespace //**************************** if (arg_netns) netns_mounts(arg_netns); //**************************** // update /proc, /sys, /dev, /boot directory //**************************** fs_proc_sys_dev_boot(); //**************************** // handle /mnt and /media //**************************** if (checkcfg(CFG_DISABLE_MNT)) fs_mnt(1); else if (arg_disable_mnt) fs_mnt(0); //**************************** // apply the profile file //**************************** // apply all whitelist commands ... fs_whitelist(); // ... followed by blacklist commands fs_blacklist(); // mkdir and mkfile are processed all over again //**************************** // nosound/no3d/notv/novideo and fix for pulseaudio 7.0 //**************************** if (arg_nosound) { // disable pulseaudio pulseaudio_disable(); // disable /dev/snd fs_dev_disable_sound(); } else if (!arg_noautopulse) pulseaudio_init(); if (arg_no3d) fs_dev_disable_3d(); if (arg_notv) fs_dev_disable_tv(); if (arg_nodvd) fs_dev_disable_dvd(); if (arg_nou2f) fs_dev_disable_u2f(); if (arg_novideo) fs_dev_disable_video(); //**************************** // install trace //**************************** if (need_preload) fs_trace(); //**************************** // set dns //**************************** fs_resolvconf(); //**************************** // fs post-processing //**************************** fs_logger_print(); fs_logger_change_owner(); //**************************** // set application environment //**************************** EUID_USER(); int cwd = 0; if (cfg.cwd) { if (chdir(cfg.cwd) == 0) cwd = 1; } if (!cwd) { if (chdir("/") < 0) errExit("chdir"); if (cfg.homedir) { struct stat s; if (stat(cfg.homedir, &s) == 0) { /* coverity[toctou] */ if (chdir(cfg.homedir) < 0) errExit("chdir"); } } } if (arg_debug) { char *cpath = get_current_dir_name(); if (cpath) { printf("Current directory: %s\n", cpath); free(cpath); } } EUID_ROOT(); // clean /tmp/.X11-unix sockets fs_x11(); if (arg_x11_xorg) x11_xorg(); // save original umask save_umask(); //**************************** // set security filters //**************************** // save state of nonewprivs save_nonewprivs(); // set capabilities set_caps(); // save cpu affinity mask to CPU_CFG file save_cpu(); // save cgroup in CGROUP_CFG file save_cgroup(); // set seccomp #ifdef HAVE_SECCOMP // install protocol filter #ifdef SYS_socket if (cfg.protocol) { if (arg_debug) printf("Install protocol filter: %s\n", cfg.protocol); seccomp_load(RUN_SECCOMP_PROTOCOL); // install filter protocol_filter_save(); // save filter in RUN_PROTOCOL_CFG } else { int rv = unlink(RUN_SECCOMP_PROTOCOL); (void) rv; } #endif // if a keep list is available, disregard the drop list if (arg_seccomp == 1) { if (cfg.seccomp_list_keep) seccomp_filter_keep(); else seccomp_filter_drop(); } else { // clean seccomp files under /run/firejail/mnt int rv = unlink(RUN_SECCOMP_CFG); rv |= unlink(RUN_SECCOMP_32); (void) rv; } if (arg_memory_deny_write_execute) { if (arg_debug) printf("Install memory write&execute filter\n"); seccomp_load(RUN_SECCOMP_MDWX); // install filter } else { int rv = unlink(RUN_SECCOMP_MDWX); (void) rv; } #endif //**************************************** // communicate progress of sandbox set up // to --join //**************************************** FILE *rj = create_ready_for_join_file(); //**************************************** // create a new user namespace // - too early to drop privileges //**************************************** save_nogroups(); if (arg_noroot) { int rv = unshare(CLONE_NEWUSER); if (rv == -1) { fwarning("cannot create a new user namespace, going forward without it...\n"); arg_noroot = 0; } } // notify parent that new user namespace has been created so a proper // UID/GID map can be setup notify_other(child_to_parent_fds[1]); close(child_to_parent_fds[1]); // wait for parent to finish setting up a proper UID/GID map wait_for_other(parent_to_child_fds[0]); close(parent_to_child_fds[0]); // somehow, the new user namespace resets capabilities; // we need to do them again if (arg_noroot) { if (arg_debug) printf("noroot user namespace installed\n"); set_caps(); } //**************************************** // Set NO_NEW_PRIVS if desired //**************************************** if (arg_nonewprivs) { prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); if (prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0) != 1) { fwarning("cannot set NO_NEW_PRIVS, it requires a Linux kernel version 3.5 or newer.\n"); if (force_nonewprivs) { fprintf(stderr, "Error: NO_NEW_PRIVS required for this sandbox, exiting ...\n"); exit(1); } } else if (arg_debug) printf("NO_NEW_PRIVS set\n"); } //**************************************** // drop privileges //**************************************** drop_privs(arg_nogroups); // kill the sandbox in case the parent died prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); //**************************************** // set cpu affinity //**************************************** if (cfg.cpus) set_cpu_affinity(); //**************************************** // fork the application and monitor it //**************************************** pid_t app_pid = fork(); if (app_pid == -1) errExit("fork"); if (app_pid == 0) { #ifdef HAVE_APPARMOR if (checkcfg(CFG_APPARMOR) && arg_apparmor) { errno = 0; if (aa_change_onexec("firejail-default")) { fwarning("Cannot confine the application using AppArmor.\n" "Maybe firejail-default AppArmor profile is not loaded into the kernel.\n" "As root, run \"aa-enforce firejail-default\" to load it.\n"); } else if (arg_debug) printf("AppArmor enabled\n"); } #endif // set nice and rlimits if (arg_nice) set_nice(cfg.nice); set_rlimits(); start_application(0, rj); } fclose(rj); int status = monitor_application(app_pid); // monitor application flush_stdin(); if (WIFEXITED(status)) { // if we had a proper exit, return that exit status return WEXITSTATUS(status); } else { // something else went wrong! return -1; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-732'], 'message': 'mount runtime seccomp files read-only (#2602) avoid creating locations in the file system that are both writable and executable (in this case for processes with euid of the user). for the same reason also remove user owned libfiles when it is not needed any more'</s>
<s>[INST] Given the following code containing errors, provide 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 rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){ char *zText = 0; RtreeNode node; Rtree tree; int ii; UNUSED_PARAMETER(nArg); memset(&node, 0, sizeof(RtreeNode)); memset(&tree, 0, sizeof(Rtree)); tree.nDim = (u8)sqlite3_value_int(apArg[0]); tree.nDim2 = tree.nDim*2; tree.nBytesPerCell = 8 + 8 * tree.nDim; node.zData = (u8 *)sqlite3_value_blob(apArg[1]); for(ii=0; ii<NCELL(&node); ii++){ char zCell[512]; int nCell = 0; RtreeCell cell; int jj; nodeGetCell(&tree, &node, ii, &cell); sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid); nCell = (int)strlen(zCell); for(jj=0; jj<tree.nDim2; jj++){ #ifndef SQLITE_RTREE_INT_ONLY sqlite3_snprintf(512-nCell,&zCell[nCell], " %g", (double)cell.aCoord[jj].f); #else sqlite3_snprintf(512-nCell,&zCell[nCell], " %d", cell.aCoord[jj].i); #endif nCell = (int)strlen(zCell); } if( zText ){ char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell); sqlite3_free(zText); zText = zTextNew; }else{ zText = sqlite3_mprintf("{%s}", zCell); } } sqlite3_result_text(ctx, zText, -1, sqlite3_free); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Enhance the rtreenode() function of rtree (used for testing) so that it uses the newer sqlite3_str object for better performance and improved error reporting. FossilOrigin-Name: 90acdbfce9c088582d5165589f7eac462b00062bbfffacdcc786eb9cf3ea5377'</s>
<s>[INST] Given the following code containing errors, provide 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 parse_cfg(int flags, int argc, const char **argv, cfg_t *cfg) { int i; memset(cfg, 0, sizeof(cfg_t)); cfg->debug_file = stderr; for (i = 0; i < argc; i++) { if (strncmp(argv[i], "max_devices=", 12) == 0) sscanf(argv[i], "max_devices=%u", &cfg->max_devs); if (strcmp(argv[i], "manual") == 0) cfg->manual = 1; if (strcmp(argv[i], "debug") == 0) cfg->debug = 1; if (strcmp(argv[i], "nouserok") == 0) cfg->nouserok = 1; if (strcmp(argv[i], "openasuser") == 0) cfg->openasuser = 1; if (strcmp(argv[i], "alwaysok") == 0) cfg->alwaysok = 1; if (strcmp(argv[i], "interactive") == 0) cfg->interactive = 1; if (strcmp(argv[i], "cue") == 0) cfg->cue = 1; if (strcmp(argv[i], "nodetect") == 0) cfg->nodetect = 1; if (strncmp(argv[i], "authfile=", 9) == 0) cfg->auth_file = argv[i] + 9; if (strncmp(argv[i], "authpending_file=", 17) == 0) cfg->authpending_file = argv[i] + 17; if (strncmp(argv[i], "origin=", 7) == 0) cfg->origin = argv[i] + 7; if (strncmp(argv[i], "appid=", 6) == 0) cfg->appid = argv[i] + 6; if (strncmp(argv[i], "prompt=", 7) == 0) cfg->prompt = argv[i] + 7; if (strncmp (argv[i], "debug_file=", 11) == 0) { const char *filename = argv[i] + 11; if(strncmp (filename, "stdout", 6) == 0) { cfg->debug_file = stdout; } else if(strncmp (filename, "stderr", 6) == 0) { cfg->debug_file = stderr; } else if( strncmp (filename, "syslog", 6) == 0) { cfg->debug_file = (FILE *)-1; } else { struct stat st; FILE *file; if(lstat(filename, &st) == 0) { if(S_ISREG(st.st_mode)) { file = fopen(filename, "a"); if(file != NULL) { cfg->debug_file = file; } } } } } } if (cfg->debug) { D(cfg->debug_file, "called."); D(cfg->debug_file, "flags %d argc %d", flags, argc); for (i = 0; i < argc; i++) { D(cfg->debug_file, "argv[%d]=%s", i, argv[i]); } D(cfg->debug_file, "max_devices=%d", cfg->max_devs); D(cfg->debug_file, "debug=%d", cfg->debug); D(cfg->debug_file, "interactive=%d", cfg->interactive); D(cfg->debug_file, "cue=%d", cfg->cue); D(cfg->debug_file, "nodetect=%d", cfg->nodetect); D(cfg->debug_file, "manual=%d", cfg->manual); D(cfg->debug_file, "nouserok=%d", cfg->nouserok); D(cfg->debug_file, "openasuser=%d", cfg->openasuser); D(cfg->debug_file, "alwaysok=%d", cfg->alwaysok); D(cfg->debug_file, "authfile=%s", cfg->auth_file ? cfg->auth_file : "(null)"); D(cfg->debug_file, "authpending_file=%s", cfg->authpending_file ? cfg->authpending_file : "(null)"); D(cfg->debug_file, "origin=%s", cfg->origin ? cfg->origin : "(null)"); D(cfg->debug_file, "appid=%s", cfg->appid ? cfg->appid : "(null)"); D(cfg->debug_file, "prompt=%s", cfg->prompt ? cfg->prompt : "(null)"); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Do not leak file descriptor when doing exec When opening a custom debug file, the descriptor would stay open when calling exec and leak to the child process. Make sure all files are opened with close-on-exec. This fixes CVE-2019-12210. Thanks to Matthias Gerstner of the SUSE Security Team for reporting the issue.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: const char *get_icalcomponent_errstr(icalcomponent *ical) { icalcomponent *comp; for (comp = icalcomponent_get_first_component(ical, ICAL_ANY_COMPONENT); comp; comp = icalcomponent_get_next_component(ical, ICAL_ANY_COMPONENT)) { icalproperty *prop; for (prop = icalcomponent_get_first_property(comp, ICAL_ANY_PROPERTY); prop; prop = icalcomponent_get_next_property(comp, ICAL_ANY_PROPERTY)) { if (icalproperty_isa(prop) == ICAL_XLICERROR_PROPERTY) { icalparameter *param; const char *errstr = icalproperty_get_xlicerror(prop); if (!errstr) return "Unknown iCal parsing error"; param = icalproperty_get_first_parameter( prop, ICAL_XLICERRORTYPE_PARAMETER); if (icalparameter_get_xlicerrortype(param) == ICAL_XLICERRORTYPE_VALUEPARSEERROR) { /* Check if this is an empty property error */ char propname[256]; if (sscanf(errstr, "No value for %s property", propname) == 1) { /* Empty LOCATION is OK */ if (!strcasecmp(propname, "LOCATION")) continue; if (!strcasecmp(propname, "COMMENT")) continue; if (!strcasecmp(propname, "DESCRIPTION")) continue; } } } } } return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'HTTP: don't overrun buffer when parsing strings 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: _server_connect_start_portal_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { GVariant *result; GError *error = NULL; result = g_dbus_connection_call_finish (G_DBUS_CONNECTION (source_object), res, &error); if (result != NULL) { g_variant_unref (result); } else { g_print ("portal is not running: %s\n", error->message); g_error_free (error); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-862'], 'message': 'bus: Implement GDBusAuthObserver callback ibus uses a GDBusServer with G_DBUS_SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS, and doesn't set a GDBusAuthObserver, which allows anyone who can connect to its AF_UNIX socket to authenticate and be authorized to send method calls. It also seems to use an abstract AF_UNIX socket, which does not have filesystem permissions, so the practical effect might be that a local attacker can connect to another user's ibus service and make arbitrary method calls. BUGS=rhbz#1717958'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bus_server_init (void) { GError *error = NULL; dbus = bus_dbus_impl_get_default (); ibus = bus_ibus_impl_get_default (); bus_dbus_impl_register_object (dbus, (IBusService *)ibus); /* init server */ GDBusServerFlags flags = G_DBUS_SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS; gchar *guid = g_dbus_generate_guid (); if (!g_str_has_prefix (g_address, "unix:tmpdir=") && !g_str_has_prefix (g_address, "unix:path=")) { g_error ("Your socket address does not have the format unix:tmpdir=$DIR " "or unix:path=$FILE; %s", g_address); } server = g_dbus_server_new_sync ( g_address, /* the place where the socket file lives, e.g. /tmp, abstract namespace, etc. */ flags, guid, NULL /* observer */, NULL /* cancellable */, &error); if (server == NULL) { g_error ("g_dbus_server_new_sync() is failed with address %s " "and guid %s: %s", g_address, guid, error->message); } g_free (guid); g_signal_connect (server, "new-connection", G_CALLBACK (bus_new_connection_cb), NULL); g_dbus_server_start (server); address = g_strdup_printf ("%s,guid=%s", g_dbus_server_get_client_address (server), g_dbus_server_get_guid (server)); /* write address to file */ ibus_write_address (address); /* own a session bus name so that third parties can easily track our life-cycle */ g_bus_own_name (G_BUS_TYPE_SESSION, IBUS_SERVICE_IBUS, G_BUS_NAME_OWNER_FLAGS_NONE, bus_acquired_handler, NULL, NULL, NULL, NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-862'], 'message': 'bus: Implement GDBusAuthObserver callback ibus uses a GDBusServer with G_DBUS_SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS, and doesn't set a GDBusAuthObserver, which allows anyone who can connect to its AF_UNIX socket to authenticate and be authorized to send method calls. It also seems to use an abstract AF_UNIX socket, which does not have filesystem permissions, so the practical effect might be that a local attacker can connect to another user's ibus service and make arbitrary method calls. BUGS=rhbz#1717958'</s>
<s>[INST] Given the following code containing errors, provide 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 property *dlpar_parse_cc_property(struct cc_workarea *ccwa) { struct property *prop; char *name; char *value; prop = kzalloc(sizeof(*prop), GFP_KERNEL); if (!prop) return NULL; name = (char *)ccwa + be32_to_cpu(ccwa->name_offset); prop->name = kstrdup(name, GFP_KERNEL); prop->length = be32_to_cpu(ccwa->prop_length); value = (char *)ccwa + be32_to_cpu(ccwa->prop_offset); prop->value = kmemdup(value, prop->length, GFP_KERNEL); if (!prop->value) { dlpar_free_cc_property(prop); return NULL; } return prop; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'powerpc/pseries/dlpar: Fix a missing check in dlpar_parse_cc_property() In dlpar_parse_cc_property(), 'prop->name' is allocated by kstrdup(). kstrdup() may return NULL, so it should be checked and handle error. And prop should be freed if 'prop->name' is NULL. Signed-off-by: Gen Zhang <[email protected]> Signed-off-by: Michael Ellerman <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: openscript( char_u *name, int directly) /* when TRUE execute directly */ { if (curscript + 1 == NSCRIPT) { emsg(_(e_nesting)); return; } #ifdef FEAT_EVAL if (ignore_script) /* Not reading from script, also don't open one. Warning message? */ return; #endif if (scriptin[curscript] != NULL) /* already reading script */ ++curscript; /* use NameBuff for expanded name */ expand_env(name, NameBuff, MAXPATHL); if ((scriptin[curscript] = mch_fopen((char *)NameBuff, READBIN)) == NULL) { semsg(_(e_notopen), name); if (curscript) --curscript; return; } if (save_typebuf() == FAIL) return; /* * Execute the commands from the file right now when using ":source!" * after ":global" or ":argdo" or in a loop. Also when another command * follows. This means the display won't be updated. Don't do this * always, "make test" would fail. */ if (directly) { oparg_T oa; int oldcurscript; int save_State = State; int save_restart_edit = restart_edit; int save_insertmode = p_im; int save_finish_op = finish_op; int save_msg_scroll = msg_scroll; State = NORMAL; msg_scroll = FALSE; /* no msg scrolling in Normal mode */ restart_edit = 0; /* don't go to Insert mode */ p_im = FALSE; /* don't use 'insertmode' */ clear_oparg(&oa); finish_op = FALSE; oldcurscript = curscript; do { update_topline_cursor(); // update cursor position and topline normal_cmd(&oa, FALSE); // execute one command vpeekc(); // check for end of file } while (scriptin[oldcurscript] != NULL); State = save_State; msg_scroll = save_msg_scroll; restart_edit = save_restart_edit; p_im = save_insertmode; finish_op = save_finish_op; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-78'], 'message': 'patch 8.1.1365: source command doesn't check for the sandbox Problem: Source command doesn't check for the sandbox. (Armin Razmjou) Solution: Check for the sandbox when sourcing a file.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static bool tcp_collapse_retrans(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *next_skb = skb_rb_next(skb); int next_skb_size; next_skb_size = next_skb->len; BUG_ON(tcp_skb_pcount(skb) != 1 || tcp_skb_pcount(next_skb) != 1); if (next_skb_size) { if (next_skb_size <= skb_availroom(skb)) skb_copy_bits(next_skb, 0, skb_put(skb, next_skb_size), next_skb_size); else if (!skb_shift(skb, next_skb, next_skb_size)) return false; } tcp_highest_sack_replace(sk, next_skb, skb); /* Update sequence range on original skb. */ TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(next_skb)->end_seq; /* Merge over control information. This moves PSH/FIN etc. over */ TCP_SKB_CB(skb)->tcp_flags |= TCP_SKB_CB(next_skb)->tcp_flags; /* All done, get rid of second SKB and account for it so * packet counting does not break. */ TCP_SKB_CB(skb)->sacked |= TCP_SKB_CB(next_skb)->sacked & TCPCB_EVER_RETRANS; TCP_SKB_CB(skb)->eor = TCP_SKB_CB(next_skb)->eor; /* changed transmit queue under us so clear hints */ tcp_clear_retrans_hints_partial(tp); if (next_skb == tp->retransmit_skb_hint) tp->retransmit_skb_hint = skb; tcp_adjust_pcount(sk, next_skb, tcp_skb_pcount(next_skb)); tcp_skb_collapse_tstamp(skb, next_skb); tcp_rtx_queue_unlink_and_free(next_skb, sk); return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'tcp: limit payload size of sacked skbs Jonathan Looney reported that TCP can trigger the following crash in tcp_shifted_skb() : BUG_ON(tcp_skb_pcount(skb) < pcount); This can happen if the remote peer has advertized the smallest MSS that linux TCP accepts : 48 An skb can hold 17 fragments, and each fragment can hold 32KB on x86, or 64KB on PowerPC. This means that the 16bit witdh of TCP_SKB_CB(skb)->tcp_gso_segs can overflow. Note that tcp_sendmsg() builds skbs with less than 64KB of payload, so this problem needs SACK to be enabled. SACK blocks allow TCP to coalesce multiple skbs in the retransmit queue, thus filling the 17 fragments to maximal capacity. CVE-2019-11477 -- u16 overflow of TCP_SKB_CB(skb)->tcp_gso_segs Fixes: 832d11c5cd07 ("tcp: Try to restore large SKBs while SACK processing") Signed-off-by: Eric Dumazet <[email protected]> Reported-by: Jonathan Looney <[email protected]> Acked-by: Neal Cardwell <[email protected]> Reviewed-by: Tyler Hicks <[email protected]> Cc: Yuchung Cheng <[email protected]> Cc: Bruce Curtis <[email protected]> Cc: Jonathan Lemon <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void __init tcp_init(void) { int max_rshare, max_wshare, cnt; unsigned long limit; unsigned int i; BUILD_BUG_ON(sizeof(struct tcp_skb_cb) > FIELD_SIZEOF(struct sk_buff, cb)); percpu_counter_init(&tcp_sockets_allocated, 0, GFP_KERNEL); percpu_counter_init(&tcp_orphan_count, 0, GFP_KERNEL); inet_hashinfo_init(&tcp_hashinfo); inet_hashinfo2_init(&tcp_hashinfo, "tcp_listen_portaddr_hash", thash_entries, 21, /* one slot per 2 MB*/ 0, 64 * 1024); tcp_hashinfo.bind_bucket_cachep = kmem_cache_create("tcp_bind_bucket", sizeof(struct inet_bind_bucket), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL); /* Size and allocate the main established and bind bucket * hash tables. * * The methodology is similar to that of the buffer cache. */ tcp_hashinfo.ehash = alloc_large_system_hash("TCP established", sizeof(struct inet_ehash_bucket), thash_entries, 17, /* one slot per 128 KB of memory */ 0, NULL, &tcp_hashinfo.ehash_mask, 0, thash_entries ? 0 : 512 * 1024); for (i = 0; i <= tcp_hashinfo.ehash_mask; i++) INIT_HLIST_NULLS_HEAD(&tcp_hashinfo.ehash[i].chain, i); if (inet_ehash_locks_alloc(&tcp_hashinfo)) panic("TCP: failed to alloc ehash_locks"); tcp_hashinfo.bhash = alloc_large_system_hash("TCP bind", sizeof(struct inet_bind_hashbucket), tcp_hashinfo.ehash_mask + 1, 17, /* one slot per 128 KB of memory */ 0, &tcp_hashinfo.bhash_size, NULL, 0, 64 * 1024); tcp_hashinfo.bhash_size = 1U << tcp_hashinfo.bhash_size; for (i = 0; i < tcp_hashinfo.bhash_size; i++) { spin_lock_init(&tcp_hashinfo.bhash[i].lock); INIT_HLIST_HEAD(&tcp_hashinfo.bhash[i].chain); } cnt = tcp_hashinfo.ehash_mask + 1; sysctl_tcp_max_orphans = cnt / 2; tcp_init_mem(); /* Set per-socket limits to no more than 1/128 the pressure threshold */ limit = nr_free_buffer_pages() << (PAGE_SHIFT - 7); max_wshare = min(4UL*1024*1024, limit); max_rshare = min(6UL*1024*1024, limit); init_net.ipv4.sysctl_tcp_wmem[0] = SK_MEM_QUANTUM; init_net.ipv4.sysctl_tcp_wmem[1] = 16*1024; init_net.ipv4.sysctl_tcp_wmem[2] = max(64*1024, max_wshare); init_net.ipv4.sysctl_tcp_rmem[0] = SK_MEM_QUANTUM; init_net.ipv4.sysctl_tcp_rmem[1] = 131072; init_net.ipv4.sysctl_tcp_rmem[2] = max(131072, max_rshare); pr_info("Hash tables configured (established %u bind %u)\n", tcp_hashinfo.ehash_mask + 1, tcp_hashinfo.bhash_size); tcp_v4_init(); tcp_metrics_init(); BUG_ON(tcp_register_congestion_control(&tcp_reno) != 0); tcp_tasklet_init(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'tcp: limit payload size of sacked skbs Jonathan Looney reported that TCP can trigger the following crash in tcp_shifted_skb() : BUG_ON(tcp_skb_pcount(skb) < pcount); This can happen if the remote peer has advertized the smallest MSS that linux TCP accepts : 48 An skb can hold 17 fragments, and each fragment can hold 32KB on x86, or 64KB on PowerPC. This means that the 16bit witdh of TCP_SKB_CB(skb)->tcp_gso_segs can overflow. Note that tcp_sendmsg() builds skbs with less than 64KB of payload, so this problem needs SACK to be enabled. SACK blocks allow TCP to coalesce multiple skbs in the retransmit queue, thus filling the 17 fragments to maximal capacity. CVE-2019-11477 -- u16 overflow of TCP_SKB_CB(skb)->tcp_gso_segs Fixes: 832d11c5cd07 ("tcp: Try to restore large SKBs while SACK processing") Signed-off-by: Eric Dumazet <[email protected]> Reported-by: Jonathan Looney <[email protected]> Acked-by: Neal Cardwell <[email protected]> Reviewed-by: Tyler Hicks <[email protected]> Cc: Yuchung Cheng <[email protected]> Cc: Bruce Curtis <[email protected]> Cc: Jonathan Lemon <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int tcp_fragment(struct sock *sk, enum tcp_queue tcp_queue, struct sk_buff *skb, u32 len, unsigned int mss_now, gfp_t gfp) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *buff; int nsize, old_factor; int nlen; u8 flags; if (WARN_ON(len > skb->len)) return -EINVAL; nsize = skb_headlen(skb) - len; if (nsize < 0) nsize = 0; if (skb_unclone(skb, gfp)) return -ENOMEM; /* Get a new skb... force flag on. */ buff = sk_stream_alloc_skb(sk, nsize, gfp, true); if (!buff) return -ENOMEM; /* We'll just try again later. */ sk->sk_wmem_queued += buff->truesize; sk_mem_charge(sk, buff->truesize); nlen = skb->len - len - nsize; buff->truesize += nlen; skb->truesize -= nlen; /* Correct the sequence numbers. */ TCP_SKB_CB(buff)->seq = TCP_SKB_CB(skb)->seq + len; TCP_SKB_CB(buff)->end_seq = TCP_SKB_CB(skb)->end_seq; TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(buff)->seq; /* PSH and FIN should only be set in the second packet. */ flags = TCP_SKB_CB(skb)->tcp_flags; TCP_SKB_CB(skb)->tcp_flags = flags & ~(TCPHDR_FIN | TCPHDR_PSH); TCP_SKB_CB(buff)->tcp_flags = flags; TCP_SKB_CB(buff)->sacked = TCP_SKB_CB(skb)->sacked; tcp_skb_fragment_eor(skb, buff); skb_split(skb, buff, len); buff->ip_summed = CHECKSUM_PARTIAL; buff->tstamp = skb->tstamp; tcp_fragment_tstamp(skb, buff); old_factor = tcp_skb_pcount(skb); /* Fix up tso_factor for both original and new SKB. */ tcp_set_skb_tso_segs(skb, mss_now); tcp_set_skb_tso_segs(buff, mss_now); /* Update delivered info for the new segment */ TCP_SKB_CB(buff)->tx = TCP_SKB_CB(skb)->tx; /* If this packet has been sent out already, we must * adjust the various packet counters. */ if (!before(tp->snd_nxt, TCP_SKB_CB(buff)->end_seq)) { int diff = old_factor - tcp_skb_pcount(skb) - tcp_skb_pcount(buff); if (diff) tcp_adjust_pcount(sk, skb, diff); } /* Link BUFF into the send queue. */ __skb_header_release(buff); tcp_insert_write_queue_after(skb, buff, sk, tcp_queue); if (tcp_queue == TCP_FRAG_IN_RTX_QUEUE) list_add(&buff->tcp_tsorted_anchor, &skb->tcp_tsorted_anchor); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'tcp: tcp_fragment() should apply sane memory limits Jonathan Looney reported that a malicious peer can force a sender to fragment its retransmit queue into tiny skbs, inflating memory usage and/or overflow 32bit counters. TCP allows an application to queue up to sk_sndbuf bytes, so we need to give some allowance for non malicious splitting of retransmit queue. A new SNMP counter is added to monitor how many times TCP did not allow to split an skb if the allowance was exceeded. Note that this counter might increase in the case applications use SO_SNDBUF socket option to lower sk_sndbuf. CVE-2019-11478 : tcp_fragment, prevent fragmenting a packet when the socket is already using more than half the allowed space Signed-off-by: Eric Dumazet <[email protected]> Reported-by: Jonathan Looney <[email protected]> Acked-by: Neal Cardwell <[email protected]> Acked-by: Yuchung Cheng <[email protected]> Reviewed-by: Tyler Hicks <[email protected]> Cc: Bruce Curtis <[email protected]> Cc: Jonathan Lemon <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: file_copy_fallback (GFile *source, GFile *destination, GFileCopyFlags flags, GCancellable *cancellable, GFileProgressCallback progress_callback, gpointer progress_callback_data, GError **error) { gboolean ret = FALSE; GFileInputStream *file_in = NULL; GInputStream *in = NULL; GOutputStream *out = NULL; GFileInfo *info = NULL; const char *target; char *attrs_to_read; gboolean do_set_attributes = FALSE; /* need to know the file type */ info = g_file_query_info (source, G_FILE_ATTRIBUTE_STANDARD_TYPE "," G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, cancellable, error); if (!info) goto out; /* Maybe copy the symlink? */ if ((flags & G_FILE_COPY_NOFOLLOW_SYMLINKS) && g_file_info_get_file_type (info) == G_FILE_TYPE_SYMBOLIC_LINK) { target = g_file_info_get_symlink_target (info); if (target) { if (!copy_symlink (destination, flags, cancellable, target, error)) goto out; ret = TRUE; goto out; } /* ... else fall back on a regular file copy */ } /* Handle "special" files (pipes, device nodes, ...)? */ else if (g_file_info_get_file_type (info) == G_FILE_TYPE_SPECIAL) { /* FIXME: could try to recreate device nodes and others? */ g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, _("Can’t copy special file")); goto out; } /* Everything else should just fall back on a regular copy. */ file_in = open_source_for_copy (source, destination, flags, cancellable, error); if (!file_in) goto out; in = G_INPUT_STREAM (file_in); if (!build_attribute_list_for_copy (destination, flags, &attrs_to_read, cancellable, error)) goto out; if (attrs_to_read != NULL) { GError *tmp_error = NULL; /* Ok, ditch the previous lightweight info (on Unix we just * called lstat()); at this point we gather all the information * we need about the source from the opened file descriptor. */ g_object_unref (info); info = g_file_input_stream_query_info (file_in, attrs_to_read, cancellable, &tmp_error); if (!info) { /* Not all gvfs backends implement query_info_on_read(), we * can just fall back to the pathname again. * https://bugzilla.gnome.org/706254 */ if (g_error_matches (tmp_error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED)) { g_clear_error (&tmp_error); info = g_file_query_info (source, attrs_to_read, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, cancellable, error); } else { g_free (attrs_to_read); g_propagate_error (error, tmp_error); goto out; } } g_free (attrs_to_read); if (!info) goto out; do_set_attributes = TRUE; } /* In the local file path, we pass down the source info which * includes things like unix::mode, to ensure that the target file * is not created with different permissions from the source file. * * If a future API like g_file_replace_with_info() is added, switch * this code to use that. */ if (G_IS_LOCAL_FILE (destination)) { if (flags & G_FILE_COPY_OVERWRITE) out = (GOutputStream*)_g_local_file_output_stream_replace (_g_local_file_get_filename (G_LOCAL_FILE (destination)), FALSE, NULL, flags & G_FILE_COPY_BACKUP, G_FILE_CREATE_REPLACE_DESTINATION, info, cancellable, error); else out = (GOutputStream*)_g_local_file_output_stream_create (_g_local_file_get_filename (G_LOCAL_FILE (destination)), FALSE, 0, info, cancellable, error); } else if (flags & G_FILE_COPY_OVERWRITE) { out = (GOutputStream *)g_file_replace (destination, NULL, flags & G_FILE_COPY_BACKUP, G_FILE_CREATE_REPLACE_DESTINATION, cancellable, error); } else { out = (GOutputStream *)g_file_create (destination, 0, cancellable, error); } if (!out) goto out; #ifdef __linux__ if (G_IS_FILE_DESCRIPTOR_BASED (in) && G_IS_FILE_DESCRIPTOR_BASED (out)) { GError *reflink_err = NULL; if (!btrfs_reflink_with_progress (in, out, info, cancellable, progress_callback, progress_callback_data, &reflink_err)) { if (g_error_matches (reflink_err, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED)) { g_clear_error (&reflink_err); } else { g_propagate_error (error, reflink_err); goto out; } } else { ret = TRUE; goto out; } } #endif #ifdef HAVE_SPLICE if (G_IS_FILE_DESCRIPTOR_BASED (in) && G_IS_FILE_DESCRIPTOR_BASED (out)) { GError *splice_err = NULL; if (!splice_stream_with_progress (in, out, cancellable, progress_callback, progress_callback_data, &splice_err)) { if (g_error_matches (splice_err, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED)) { g_clear_error (&splice_err); } else { g_propagate_error (error, splice_err); goto out; } } else { ret = TRUE; goto out; } } #endif /* A plain read/write loop */ if (!copy_stream_with_progress (in, out, source, cancellable, progress_callback, progress_callback_data, error)) goto out; ret = TRUE; out: if (in) { /* Don't care about errors in source here */ (void) g_input_stream_close (in, cancellable, NULL); g_object_unref (in); } if (out) { /* But write errors on close are bad! */ if (!g_output_stream_close (out, cancellable, ret ? error : NULL)) ret = FALSE; g_object_unref (out); } /* Ignore errors here. Failure to copy metadata is not a hard error */ /* TODO: set these attributes /before/ we do the rename() on Unix */ if (ret && do_set_attributes) { g_file_set_attributes_from_info (destination, info, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, cancellable, NULL); } g_clear_object (&info); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'gfile: Limit access to files when copying file_copy_fallback creates new files with default permissions and set the correct permissions after the operation is finished. This might cause that the files can be accessible by more users during the operation than expected. Use G_FILE_CREATE_PRIVATE for the new files to limit access to those files.'</s>
<s>[INST] Given the following code containing errors, provide 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 hash__init_new_context(struct mm_struct *mm) { int index; index = hash__alloc_context_id(); if (index < 0) return index; /* * The old code would re-promote on fork, we don't do that when using * slices as it could cause problem promoting slices that have been * forced down to 4K. * * For book3s we have MMU_NO_CONTEXT set to be ~0. Hence check * explicitly against context.id == 0. This ensures that we properly * initialize context slice details for newly allocated mm's (which will * have id == 0) and don't alter context slice inherited via fork (which * will have id != 0). * * We should not be calling init_new_context() on init_mm. Hence a * check against 0 is OK. */ if (mm->context.id == 0) slice_init_new_context_exec(mm); subpage_prot_init_new_context(mm); pkey_mm_init(mm); return index; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'powerpc/mm/64s/hash: Reallocate context ids on fork When using the Hash Page Table (HPT) MMU, userspace memory mappings are managed at two levels. Firstly in the Linux page tables, much like other architectures, and secondly in the SLB (Segment Lookaside Buffer) and HPT. It's the SLB and HPT that are actually used by the hardware to do translations. As part of the series adding support for 4PB user virtual address space using the hash MMU, we added support for allocating multiple "context ids" per process, one for each 512TB chunk of address space. These are tracked in an array called extended_id in the mm_context_t of a process that has done a mapping above 512TB. If such a process forks (ie. clone(2) without CLONE_VM set) it's mm is copied, including the mm_context_t, and then init_new_context() is called to reinitialise parts of the mm_context_t as appropriate to separate the address spaces of the two processes. The key step in ensuring the two processes have separate address spaces is to allocate a new context id for the process, this is done at the beginning of hash__init_new_context(). If we didn't allocate a new context id then the two processes would share mappings as far as the SLB and HPT are concerned, even though their Linux page tables would be separate. For mappings above 512TB, which use the extended_id array, we neglected to allocate new context ids on fork, meaning the parent and child use the same ids and therefore share those mappings even though they're supposed to be separate. This can lead to the parent seeing writes done by the child, which is essentially memory corruption. There is an additional exposure which is that if the child process exits, all its context ids are freed, including the context ids that are still in use by the parent for mappings above 512TB. One or more of those ids can then be reallocated to a third process, that process can then read/write to the parent's mappings above 512TB. Additionally if the freed id is used for the third process's primary context id, then the parent is able to read/write to the third process's mappings *below* 512TB. All of these are fundamental failures to enforce separation between processes. The only mitigating factor is that the bug only occurs if a process creates mappings above 512TB, and most applications still do not create such mappings. Only machines using the hash page table MMU are affected, eg. PowerPC 970 (G5), PA6T, Power5/6/7/8/9. By default Power9 bare metal machines (powernv) use the Radix MMU and are not affected, unless the machine has been explicitly booted in HPT mode (using disable_radix on the kernel command line). KVM guests on Power9 may be affected if the host or guest is configured to use the HPT MMU. LPARs under PowerVM on Power9 are affected as they always use the HPT MMU. Kernels built with PAGE_SIZE=4K are not affected. The fix is relatively simple, we need to reallocate context ids for all extended mappings on fork. Fixes: f384796c40dc ("powerpc/mm: Add support for handling > 512TB address in SLB miss") Cc: [email protected] # v4.17+ Signed-off-by: Michael Ellerman <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int nfc_llcp_build_gb(struct nfc_llcp_local *local) { u8 *gb_cur, *version_tlv, version, version_length; u8 *lto_tlv, lto_length; u8 *wks_tlv, wks_length; u8 *miux_tlv, miux_length; __be16 wks = cpu_to_be16(local->local_wks); u8 gb_len = 0; int ret = 0; version = LLCP_VERSION_11; version_tlv = nfc_llcp_build_tlv(LLCP_TLV_VERSION, &version, 1, &version_length); gb_len += version_length; lto_tlv = nfc_llcp_build_tlv(LLCP_TLV_LTO, &local->lto, 1, &lto_length); gb_len += lto_length; pr_debug("Local wks 0x%lx\n", local->local_wks); wks_tlv = nfc_llcp_build_tlv(LLCP_TLV_WKS, (u8 *)&wks, 2, &wks_length); gb_len += wks_length; miux_tlv = nfc_llcp_build_tlv(LLCP_TLV_MIUX, (u8 *)&local->miux, 0, &miux_length); gb_len += miux_length; gb_len += ARRAY_SIZE(llcp_magic); if (gb_len > NFC_MAX_GT_LEN) { ret = -EINVAL; goto out; } gb_cur = local->gb; memcpy(gb_cur, llcp_magic, ARRAY_SIZE(llcp_magic)); gb_cur += ARRAY_SIZE(llcp_magic); memcpy(gb_cur, version_tlv, version_length); gb_cur += version_length; memcpy(gb_cur, lto_tlv, lto_length); gb_cur += lto_length; memcpy(gb_cur, wks_tlv, wks_length); gb_cur += wks_length; memcpy(gb_cur, miux_tlv, miux_length); gb_cur += miux_length; local->gb_len = gb_len; out: kfree(version_tlv); kfree(lto_tlv); kfree(wks_tlv); kfree(miux_tlv); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'net: nfc: Fix NULL dereference on nfc_llcp_build_tlv fails KASAN report this: BUG: KASAN: null-ptr-deref in nfc_llcp_build_gb+0x37f/0x540 [nfc] Read of size 3 at addr 0000000000000000 by task syz-executor.0/5401 CPU: 0 PID: 5401 Comm: syz-executor.0 Not tainted 5.0.0-rc7+ #45 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014 Call Trace: __dump_stack lib/dump_stack.c:77 [inline] dump_stack+0xfa/0x1ce lib/dump_stack.c:113 kasan_report+0x171/0x18d mm/kasan/report.c:321 memcpy+0x1f/0x50 mm/kasan/common.c:130 nfc_llcp_build_gb+0x37f/0x540 [nfc] nfc_llcp_register_device+0x6eb/0xb50 [nfc] nfc_register_device+0x50/0x1d0 [nfc] nfcsim_device_new+0x394/0x67d [nfcsim] ? 0xffffffffc1080000 nfcsim_init+0x6b/0x1000 [nfcsim] do_one_initcall+0xfa/0x5ca init/main.c:887 do_init_module+0x204/0x5f6 kernel/module.c:3460 load_module+0x66b2/0x8570 kernel/module.c:3808 __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902 do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe RIP: 0033:0x462e99 Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007f9cb79dcc58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139 RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99 RDX: 0000000000000000 RSI: 0000000020000280 RDI: 0000000000000003 RBP: 00007f9cb79dcc70 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 00007f9cb79dd6bc R13: 00000000004bcefb R14: 00000000006f7030 R15: 0000000000000004 nfc_llcp_build_tlv will return NULL on fails, caller should check it, otherwise will trigger a NULL dereference. Reported-by: Hulk Robot <[email protected]> Fixes: eda21f16a5ed ("NFC: Set MIU and RW values from CONNECT and CC LLCP frames") Fixes: d646960f7986 ("NFC: Initial LLCP support") Signed-off-by: YueHaibing <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int nfc_llcp_send_cc(struct nfc_llcp_sock *sock) { struct nfc_llcp_local *local; struct sk_buff *skb; u8 *miux_tlv = NULL, miux_tlv_length; u8 *rw_tlv = NULL, rw_tlv_length, rw; int err; u16 size = 0; __be16 miux; pr_debug("Sending CC\n"); local = sock->local; if (local == NULL) return -ENODEV; /* If the socket parameters are not set, use the local ones */ miux = be16_to_cpu(sock->miux) > LLCP_MAX_MIUX ? local->miux : sock->miux; rw = sock->rw > LLCP_MAX_RW ? local->rw : sock->rw; miux_tlv = nfc_llcp_build_tlv(LLCP_TLV_MIUX, (u8 *)&miux, 0, &miux_tlv_length); size += miux_tlv_length; rw_tlv = nfc_llcp_build_tlv(LLCP_TLV_RW, &rw, 0, &rw_tlv_length); size += rw_tlv_length; skb = llcp_allocate_pdu(sock, LLCP_PDU_CC, size); if (skb == NULL) { err = -ENOMEM; goto error_tlv; } llcp_add_tlv(skb, miux_tlv, miux_tlv_length); llcp_add_tlv(skb, rw_tlv, rw_tlv_length); skb_queue_tail(&local->tx_queue, skb); err = 0; error_tlv: if (err) pr_err("error %d\n", err); kfree(miux_tlv); kfree(rw_tlv); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'net: nfc: Fix NULL dereference on nfc_llcp_build_tlv fails KASAN report this: BUG: KASAN: null-ptr-deref in nfc_llcp_build_gb+0x37f/0x540 [nfc] Read of size 3 at addr 0000000000000000 by task syz-executor.0/5401 CPU: 0 PID: 5401 Comm: syz-executor.0 Not tainted 5.0.0-rc7+ #45 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014 Call Trace: __dump_stack lib/dump_stack.c:77 [inline] dump_stack+0xfa/0x1ce lib/dump_stack.c:113 kasan_report+0x171/0x18d mm/kasan/report.c:321 memcpy+0x1f/0x50 mm/kasan/common.c:130 nfc_llcp_build_gb+0x37f/0x540 [nfc] nfc_llcp_register_device+0x6eb/0xb50 [nfc] nfc_register_device+0x50/0x1d0 [nfc] nfcsim_device_new+0x394/0x67d [nfcsim] ? 0xffffffffc1080000 nfcsim_init+0x6b/0x1000 [nfcsim] do_one_initcall+0xfa/0x5ca init/main.c:887 do_init_module+0x204/0x5f6 kernel/module.c:3460 load_module+0x66b2/0x8570 kernel/module.c:3808 __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902 do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe RIP: 0033:0x462e99 Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007f9cb79dcc58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139 RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99 RDX: 0000000000000000 RSI: 0000000020000280 RDI: 0000000000000003 RBP: 00007f9cb79dcc70 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 00007f9cb79dd6bc R13: 00000000004bcefb R14: 00000000006f7030 R15: 0000000000000004 nfc_llcp_build_tlv will return NULL on fails, caller should check it, otherwise will trigger a NULL dereference. Reported-by: Hulk Robot <[email protected]> Fixes: eda21f16a5ed ("NFC: Set MIU and RW values from CONNECT and CC LLCP frames") Fixes: d646960f7986 ("NFC: Initial LLCP support") Signed-off-by: YueHaibing <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: R_API int r_egg_compile(REgg *egg) { r_buf_seek (egg->src, 0, R_BUF_SET); char b; int r = r_buf_read (egg->src, (ut8 *)&b, sizeof (b)); if (r != sizeof (b) || !egg->remit) { return true; } // only emit begin if code is found r_egg_lang_init (egg); for (; b; ) { r_egg_lang_parsechar (egg, b); int r = r_buf_read (egg->src, (ut8 *)&b, sizeof (b)); if (r != sizeof (b)) { break; } // XXX: some parse fail errors are false positives :( } if (egg->context>0) { eprintf ("ERROR: expected '}' at the end of the file. %d left\n", egg->context); return false; } // TODO: handle errors here return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'patch #14211 heap buffer overflow in large ragg2 inputs. this should be refactored to use an RBuffer to enable dynamic resizing, but for now just patching it to bail out if we are about to overwrite the allocated statically sized buffer'</s>
<s>[INST] Given the following code containing errors, provide 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 hllMerge(uint8_t *max, robj *hll) { struct hllhdr *hdr = hll->ptr; int i; if (hdr->encoding == HLL_DENSE) { uint8_t val; for (i = 0; i < HLL_REGISTERS; i++) { HLL_DENSE_GET_REGISTER(val,hdr->registers,i); if (val > max[i]) max[i] = val; } } else { uint8_t *p = hll->ptr, *end = p + sdslen(hll->ptr); long runlen, regval; p += HLL_HDR_SIZE; i = 0; while(p < end) { if (HLL_SPARSE_IS_ZERO(p)) { runlen = HLL_SPARSE_ZERO_LEN(p); i += runlen; p++; } else if (HLL_SPARSE_IS_XZERO(p)) { runlen = HLL_SPARSE_XZERO_LEN(p); i += runlen; p += 2; } else { runlen = HLL_SPARSE_VAL_LEN(p); regval = HLL_SPARSE_VAL_VALUE(p); if ((runlen + i) > HLL_REGISTERS) return C_ERR; while(runlen--) { if (regval > max[i]) max[i] = regval; i++; } p++; } } if (i != HLL_REGISTERS) return C_ERR; } return C_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'HyperLogLog: handle wrong offset in the base case.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int hllSparseToDense(robj *o) { sds sparse = o->ptr, dense; struct hllhdr *hdr, *oldhdr = (struct hllhdr*)sparse; int idx = 0, runlen, regval; uint8_t *p = (uint8_t*)sparse, *end = p+sdslen(sparse); /* If the representation is already the right one return ASAP. */ hdr = (struct hllhdr*) sparse; if (hdr->encoding == HLL_DENSE) return C_OK; /* Create a string of the right size filled with zero bytes. * Note that the cached cardinality is set to 0 as a side effect * that is exactly the cardinality of an empty HLL. */ dense = sdsnewlen(NULL,HLL_DENSE_SIZE); hdr = (struct hllhdr*) dense; *hdr = *oldhdr; /* This will copy the magic and cached cardinality. */ hdr->encoding = HLL_DENSE; /* Now read the sparse representation and set non-zero registers * accordingly. */ p += HLL_HDR_SIZE; while(p < end) { if (HLL_SPARSE_IS_ZERO(p)) { runlen = HLL_SPARSE_ZERO_LEN(p); idx += runlen; p++; } else if (HLL_SPARSE_IS_XZERO(p)) { runlen = HLL_SPARSE_XZERO_LEN(p); idx += runlen; p += 2; } else { runlen = HLL_SPARSE_VAL_LEN(p); regval = HLL_SPARSE_VAL_VALUE(p); while(runlen--) { HLL_DENSE_SET_REGISTER(hdr->registers,idx,regval); idx++; } p++; } } /* If the sparse representation was valid, we expect to find idx * set to HLL_REGISTERS. */ if (idx != HLL_REGISTERS) { sdsfree(dense); return C_ERR; } /* Free the old representation and set the new one. */ sdsfree(o->ptr); o->ptr = dense; return C_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix hyperloglog corruption'</s>
<s>[INST] Given the following code containing errors, provide 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 gdImageCreateFromXbm(FILE * fd) { char fline[MAX_XBM_LINE_SIZE]; char iname[MAX_XBM_LINE_SIZE]; char *type; int value; unsigned int width = 0, height = 0; int fail = 0; int max_bit = 0; gdImagePtr im; int bytes = 0, i; int bit, x = 0, y = 0; int ch; char h[8]; unsigned int b; rewind(fd); while (fgets(fline, MAX_XBM_LINE_SIZE, fd)) { fline[MAX_XBM_LINE_SIZE-1] = '\0'; if (strlen(fline) == MAX_XBM_LINE_SIZE-1) { return 0; } if (sscanf(fline, "#define %s %d", iname, &value) == 2) { if (!(type = strrchr(iname, '_'))) { type = iname; } else { type++; } if (!strcmp("width", type)) { width = (unsigned int) value; } if (!strcmp("height", type)) { height = (unsigned int) value; } } else { if ( sscanf(fline, "static unsigned char %s = {", iname) == 1 || sscanf(fline, "static char %s = {", iname) == 1) { max_bit = 128; } else if (sscanf(fline, "static unsigned short %s = {", iname) == 1 || sscanf(fline, "static short %s = {", iname) == 1) { max_bit = 32768; } if (max_bit) { bytes = (width + 7) / 8 * height; if (!bytes) { return 0; } if (!(type = strrchr(iname, '_'))) { type = iname; } else { type++; } if (!strcmp("bits[]", type)) { break; } } } } if (!bytes || !max_bit) { return 0; } if(!(im = gdImageCreate(width, height))) { return 0; } gdImageColorAllocate(im, 255, 255, 255); gdImageColorAllocate(im, 0, 0, 0); h[2] = '\0'; h[4] = '\0'; for (i = 0; i < bytes; i++) { while (1) { if ((ch=getc(fd)) == EOF) { fail = 1; break; } if (ch == 'x') { break; } } if (fail) { break; } /* Get hex value */ if ((ch=getc(fd)) == EOF) { break; } h[0] = ch; if ((ch=getc(fd)) == EOF) { break; } h[1] = ch; if (max_bit == 32768) { if ((ch=getc(fd)) == EOF) { break; } h[2] = ch; if ((ch=getc(fd)) == EOF) { break; } h[3] = ch; } sscanf(h, "%x", &b); for (bit = 1; bit <= max_bit; bit = bit << 1) { gdImageSetPixel(im, x++, y, (b & bit) ? 1 : 0); if (x == im->sx) { x = 0; y++; if (y == im->sy) { return im; } break; } } } php_gd_error("EOF before image was complete"); gdImageDestroy(im); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-908'], 'message': 'Fix #77973: Uninitialized read in gdImageCreateFromXbm We have to ensure that `sscanf()` does indeed read a hex value here, and bail out otherwise.'</s>
<s>[INST] Given the following code containing errors, provide 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 php_iconv_err_t _php_iconv_mime_decode(smart_str *pretval, const char *str, size_t str_nbytes, const char *enc, const char **next_pos, int mode) { php_iconv_err_t err = PHP_ICONV_ERR_SUCCESS; iconv_t cd = (iconv_t)(-1), cd_pl = (iconv_t)(-1); const char *p1; size_t str_left; unsigned int scan_stat = 0; const char *csname = NULL; size_t csname_len; const char *encoded_text = NULL; size_t encoded_text_len = 0; const char *encoded_word = NULL; const char *spaces = NULL; php_iconv_enc_scheme_t enc_scheme = PHP_ICONV_ENC_SCHEME_BASE64; if (next_pos != NULL) { *next_pos = NULL; } cd_pl = iconv_open(enc, ICONV_ASCII_ENCODING); if (cd_pl == (iconv_t)(-1)) { #if ICONV_SUPPORTS_ERRNO if (errno == EINVAL) { err = PHP_ICONV_ERR_WRONG_CHARSET; } else { err = PHP_ICONV_ERR_CONVERTER; } #else err = PHP_ICONV_ERR_UNKNOWN; #endif goto out; } p1 = str; for (str_left = str_nbytes; str_left > 0; str_left--, p1++) { int eos = 0; switch (scan_stat) { case 0: /* expecting any character */ switch (*p1) { case '\r': /* part of an EOL sequence? */ scan_stat = 7; break; case '\n': scan_stat = 8; break; case '=': /* first letter of an encoded chunk */ encoded_word = p1; scan_stat = 1; break; case ' ': case '\t': /* a chunk of whitespaces */ spaces = p1; scan_stat = 11; break; default: /* first letter of a non-encoded word */ err = _php_iconv_appendc(pretval, *p1, cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { if (mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR) { err = PHP_ICONV_ERR_SUCCESS; } else { goto out; } } encoded_word = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } break; } break; case 1: /* expecting a delimiter */ if (*p1 != '?') { if (*p1 == '\r' || *p1 == '\n') { --p1; } err = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } encoded_word = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } else { scan_stat = 0; } break; } csname = p1 + 1; scan_stat = 2; break; case 2: /* expecting a charset name */ switch (*p1) { case '?': /* normal delimiter: encoding scheme follows */ scan_stat = 3; break; case '*': /* new style delimiter: locale id follows */ scan_stat = 10; break; case '\r': case '\n': /* not an encoded-word */ --p1; _php_iconv_appendc(pretval, '=', cd_pl); _php_iconv_appendc(pretval, '?', cd_pl); err = _php_iconv_appendl(pretval, csname, (size_t)((p1 + 1) - csname), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } csname = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } else { scan_stat = 0; } continue; } if (scan_stat != 2) { char tmpbuf[80]; if (csname == NULL) { err = PHP_ICONV_ERR_MALFORMED; goto out; } csname_len = (size_t)(p1 - csname); if (csname_len > sizeof(tmpbuf) - 1) { if ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) { err = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } encoded_word = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } else { scan_stat = 0; } break; } else { err = PHP_ICONV_ERR_MALFORMED; goto out; } } memcpy(tmpbuf, csname, csname_len); tmpbuf[csname_len] = '\0'; if (cd != (iconv_t)(-1)) { iconv_close(cd); } cd = iconv_open(enc, tmpbuf); if (cd == (iconv_t)(-1)) { if ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) { /* Bad character set, but the user wants us to * press on. In this case, we'll just insert the * undecoded encoded word, since there isn't really * a more sensible behaviour available; the only * other options are to swallow the encoded word * entirely or decode it with an arbitrarily chosen * single byte encoding, both of which seem to have * a higher WTF factor than leaving it undecoded. * * Given this approach, we need to skip ahead to * the end of the encoded word. */ int qmarks = 2; while (qmarks > 0 && str_left > 1) { if (*(++p1) == '?') { --qmarks; } --str_left; } /* Look ahead to check for the terminating = that * should be there as well; if it's there, we'll * also include that. If it's not, there isn't much * we can do at this point. */ if (*(p1 + 1) == '=') { ++p1; --str_left; } err = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } /* Let's go back and see if there are further * encoded words or bare content, and hope they * might actually have a valid character set. */ scan_stat = 12; break; } else { #if ICONV_SUPPORTS_ERRNO if (errno == EINVAL) { err = PHP_ICONV_ERR_WRONG_CHARSET; } else { err = PHP_ICONV_ERR_CONVERTER; } #else err = PHP_ICONV_ERR_UNKNOWN; #endif goto out; } } } break; case 3: /* expecting a encoding scheme specifier */ switch (*p1) { case 'b': case 'B': enc_scheme = PHP_ICONV_ENC_SCHEME_BASE64; scan_stat = 4; break; case 'q': case 'Q': enc_scheme = PHP_ICONV_ENC_SCHEME_QPRINT; scan_stat = 4; break; default: if ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) { err = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } encoded_word = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } else { scan_stat = 0; } break; } else { err = PHP_ICONV_ERR_MALFORMED; goto out; } } break; case 4: /* expecting a delimiter */ if (*p1 != '?') { if ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) { /* pass the entire chunk through the converter */ err = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } encoded_word = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } else { scan_stat = 0; } break; } else { err = PHP_ICONV_ERR_MALFORMED; goto out; } } encoded_text = p1 + 1; scan_stat = 5; break; case 5: /* expecting an encoded portion */ if (*p1 == '?') { encoded_text_len = (size_t)(p1 - encoded_text); scan_stat = 6; } break; case 7: /* expecting a "\n" character */ if (*p1 == '\n') { scan_stat = 8; } else { /* bare CR */ _php_iconv_appendc(pretval, '\r', cd_pl); _php_iconv_appendc(pretval, *p1, cd_pl); scan_stat = 0; } break; case 8: /* checking whether the following line is part of a folded header */ if (*p1 != ' ' && *p1 != '\t') { --p1; str_left = 1; /* quit_loop */ break; } if (encoded_word == NULL) { _php_iconv_appendc(pretval, ' ', cd_pl); } spaces = NULL; scan_stat = 11; break; case 6: /* expecting a End-Of-Chunk character "=" */ if (*p1 != '=') { if ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) { /* pass the entire chunk through the converter */ err = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } encoded_word = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } else { scan_stat = 0; } break; } else { err = PHP_ICONV_ERR_MALFORMED; goto out; } } scan_stat = 9; if (str_left == 1) { eos = 1; } else { break; } case 9: /* choice point, seeing what to do next.*/ switch (*p1) { default: /* Handle non-RFC-compliant formats * * RFC2047 requires the character that comes right * after an encoded word (chunk) to be a whitespace, * while there are lots of broken implementations that * generate such malformed headers that don't fulfill * that requirement. */ if (!eos) { if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { /* pass the entire chunk through the converter */ err = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } scan_stat = 12; break; } } /* break is omitted intentionally */ case '\r': case '\n': case ' ': case '\t': { zend_string *decoded_text; switch (enc_scheme) { case PHP_ICONV_ENC_SCHEME_BASE64: decoded_text = php_base64_decode((unsigned char*)encoded_text, encoded_text_len); break; case PHP_ICONV_ENC_SCHEME_QPRINT: decoded_text = php_quot_print_decode((unsigned char*)encoded_text, encoded_text_len, 1); break; default: decoded_text = NULL; break; } if (decoded_text == NULL) { if ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) { /* pass the entire chunk through the converter */ err = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } encoded_word = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } else { scan_stat = 0; } break; } else { err = PHP_ICONV_ERR_UNKNOWN; goto out; } } err = _php_iconv_appendl(pretval, ZSTR_VAL(decoded_text), ZSTR_LEN(decoded_text), cd); zend_string_release_ex(decoded_text, 0); if (err != PHP_ICONV_ERR_SUCCESS) { if ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) { /* pass the entire chunk through the converter */ err = _php_iconv_appendl(pretval, encoded_word, (size_t)(p1 - encoded_word), cd_pl); encoded_word = NULL; if (err != PHP_ICONV_ERR_SUCCESS) { break; } } else { goto out; } } if (eos) { /* reached end-of-string. done. */ scan_stat = 0; break; } switch (*p1) { case '\r': /* part of an EOL sequence? */ scan_stat = 7; break; case '\n': scan_stat = 8; break; case '=': /* first letter of an encoded chunk */ scan_stat = 1; break; case ' ': case '\t': /* medial whitespaces */ spaces = p1; scan_stat = 11; break; default: /* first letter of a non-encoded word */ _php_iconv_appendc(pretval, *p1, cd_pl); scan_stat = 12; break; } } break; } break; case 10: /* expects a language specifier. dismiss it for now */ if (*p1 == '?') { scan_stat = 3; } break; case 11: /* expecting a chunk of whitespaces */ switch (*p1) { case '\r': /* part of an EOL sequence? */ scan_stat = 7; break; case '\n': scan_stat = 8; break; case '=': /* first letter of an encoded chunk */ if (spaces != NULL && encoded_word == NULL) { _php_iconv_appendl(pretval, spaces, (size_t)(p1 - spaces), cd_pl); spaces = NULL; } encoded_word = p1; scan_stat = 1; break; case ' ': case '\t': break; default: /* first letter of a non-encoded word */ if (spaces != NULL) { _php_iconv_appendl(pretval, spaces, (size_t)(p1 - spaces), cd_pl); spaces = NULL; } _php_iconv_appendc(pretval, *p1, cd_pl); encoded_word = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } else { scan_stat = 0; } break; } break; case 12: /* expecting a non-encoded word */ switch (*p1) { case '\r': /* part of an EOL sequence? */ scan_stat = 7; break; case '\n': scan_stat = 8; break; case ' ': case '\t': spaces = p1; scan_stat = 11; break; case '=': /* first letter of an encoded chunk */ if (!(mode & PHP_ICONV_MIME_DECODE_STRICT)) { encoded_word = p1; scan_stat = 1; break; } /* break is omitted intentionally */ default: _php_iconv_appendc(pretval, *p1, cd_pl); break; } break; } } switch (scan_stat) { case 0: case 8: case 11: case 12: break; default: if ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) { if (scan_stat == 1) { _php_iconv_appendc(pretval, '=', cd_pl); } err = PHP_ICONV_ERR_SUCCESS; } else { err = PHP_ICONV_ERR_MALFORMED; goto out; } } if (next_pos != NULL) { *next_pos = p1; } smart_str_0(pretval); out: if (cd != (iconv_t)(-1)) { iconv_close(cd); } if (cd_pl != (iconv_t)(-1)) { iconv_close(cd_pl); } return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #78069 - Out-of-bounds read in iconv.c:_php_iconv_mime_decode() due to integer overflow (cherry picked from commit 7cf7148a8f8f4f55fb04de2a517d740bb6253eac)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Int32 BZ2_decompress ( DState* s ) { UChar uc; Int32 retVal; Int32 minLen, maxLen; bz_stream* strm = s->strm; /* stuff that needs to be saved/restored */ Int32 i; Int32 j; Int32 t; Int32 alphaSize; Int32 nGroups; Int32 nSelectors; Int32 EOB; Int32 groupNo; Int32 groupPos; Int32 nextSym; Int32 nblockMAX; Int32 nblock; Int32 es; Int32 N; Int32 curr; Int32 zt; Int32 zn; Int32 zvec; Int32 zj; Int32 gSel; Int32 gMinlen; Int32* gLimit; Int32* gBase; Int32* gPerm; if (s->state == BZ_X_MAGIC_1) { /*initialise the save area*/ s->save_i = 0; s->save_j = 0; s->save_t = 0; s->save_alphaSize = 0; s->save_nGroups = 0; s->save_nSelectors = 0; s->save_EOB = 0; s->save_groupNo = 0; s->save_groupPos = 0; s->save_nextSym = 0; s->save_nblockMAX = 0; s->save_nblock = 0; s->save_es = 0; s->save_N = 0; s->save_curr = 0; s->save_zt = 0; s->save_zn = 0; s->save_zvec = 0; s->save_zj = 0; s->save_gSel = 0; s->save_gMinlen = 0; s->save_gLimit = NULL; s->save_gBase = NULL; s->save_gPerm = NULL; } /*restore from the save area*/ i = s->save_i; j = s->save_j; t = s->save_t; alphaSize = s->save_alphaSize; nGroups = s->save_nGroups; nSelectors = s->save_nSelectors; EOB = s->save_EOB; groupNo = s->save_groupNo; groupPos = s->save_groupPos; nextSym = s->save_nextSym; nblockMAX = s->save_nblockMAX; nblock = s->save_nblock; es = s->save_es; N = s->save_N; curr = s->save_curr; zt = s->save_zt; zn = s->save_zn; zvec = s->save_zvec; zj = s->save_zj; gSel = s->save_gSel; gMinlen = s->save_gMinlen; gLimit = s->save_gLimit; gBase = s->save_gBase; gPerm = s->save_gPerm; retVal = BZ_OK; switch (s->state) { GET_UCHAR(BZ_X_MAGIC_1, uc); if (uc != BZ_HDR_B) RETURN(BZ_DATA_ERROR_MAGIC); GET_UCHAR(BZ_X_MAGIC_2, uc); if (uc != BZ_HDR_Z) RETURN(BZ_DATA_ERROR_MAGIC); GET_UCHAR(BZ_X_MAGIC_3, uc) if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC); GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8) if (s->blockSize100k < (BZ_HDR_0 + 1) || s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC); s->blockSize100k -= BZ_HDR_0; if (s->smallDecompress) { s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) ); s->ll4 = BZALLOC( ((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar) ); if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR); } else { s->tt = BZALLOC( s->blockSize100k * 100000 * sizeof(Int32) ); if (s->tt == NULL) RETURN(BZ_MEM_ERROR); } GET_UCHAR(BZ_X_BLKHDR_1, uc); if (uc == 0x17) goto endhdr_2; if (uc != 0x31) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_2, uc); if (uc != 0x41) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_3, uc); if (uc != 0x59) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_4, uc); if (uc != 0x26) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_5, uc); if (uc != 0x53) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_6, uc); if (uc != 0x59) RETURN(BZ_DATA_ERROR); s->currBlockNo++; if (s->verbosity >= 2) VPrintf1 ( "\n [%d: huff+mtf ", s->currBlockNo ); s->storedBlockCRC = 0; GET_UCHAR(BZ_X_BCRC_1, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_2, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_3, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_4, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_BITS(BZ_X_RANDBIT, s->blockRandomised, 1); s->origPtr = 0; GET_UCHAR(BZ_X_ORIGPTR_1, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); GET_UCHAR(BZ_X_ORIGPTR_2, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); GET_UCHAR(BZ_X_ORIGPTR_3, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); if (s->origPtr < 0) RETURN(BZ_DATA_ERROR); if (s->origPtr > 10 + 100000*s->blockSize100k) RETURN(BZ_DATA_ERROR); /*--- Receive the mapping table ---*/ for (i = 0; i < 16; i++) { GET_BIT(BZ_X_MAPPING_1, uc); if (uc == 1) s->inUse16[i] = True; else s->inUse16[i] = False; } for (i = 0; i < 256; i++) s->inUse[i] = False; for (i = 0; i < 16; i++) if (s->inUse16[i]) for (j = 0; j < 16; j++) { GET_BIT(BZ_X_MAPPING_2, uc); if (uc == 1) s->inUse[i * 16 + j] = True; } makeMaps_d ( s ); if (s->nInUse == 0) RETURN(BZ_DATA_ERROR); alphaSize = s->nInUse+2; /*--- Now the selectors ---*/ GET_BITS(BZ_X_SELECTOR_1, nGroups, 3); if (nGroups < 2 || nGroups > 6) RETURN(BZ_DATA_ERROR); GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15); if (nSelectors < 1) RETURN(BZ_DATA_ERROR); for (i = 0; i < nSelectors; i++) { j = 0; while (True) { GET_BIT(BZ_X_SELECTOR_3, uc); if (uc == 0) break; j++; if (j >= nGroups) RETURN(BZ_DATA_ERROR); } s->selectorMtf[i] = j; } /*--- Undo the MTF values for the selectors. ---*/ { UChar pos[BZ_N_GROUPS], tmp, v; for (v = 0; v < nGroups; v++) pos[v] = v; for (i = 0; i < nSelectors; i++) { v = s->selectorMtf[i]; tmp = pos[v]; while (v > 0) { pos[v] = pos[v-1]; v--; } pos[0] = tmp; s->selector[i] = tmp; } } /*--- Now the coding tables ---*/ for (t = 0; t < nGroups; t++) { GET_BITS(BZ_X_CODING_1, curr, 5); for (i = 0; i < alphaSize; i++) { while (True) { if (curr < 1 || curr > 20) RETURN(BZ_DATA_ERROR); GET_BIT(BZ_X_CODING_2, uc); if (uc == 0) break; GET_BIT(BZ_X_CODING_3, uc); if (uc == 0) curr++; else curr--; } s->len[t][i] = curr; } } /*--- Create the Huffman decoding tables ---*/ for (t = 0; t < nGroups; t++) { minLen = 32; maxLen = 0; for (i = 0; i < alphaSize; i++) { if (s->len[t][i] > maxLen) maxLen = s->len[t][i]; if (s->len[t][i] < minLen) minLen = s->len[t][i]; } BZ2_hbCreateDecodeTables ( &(s->limit[t][0]), &(s->base[t][0]), &(s->perm[t][0]), &(s->len[t][0]), minLen, maxLen, alphaSize ); s->minLens[t] = minLen; } /*--- Now the MTF values ---*/ EOB = s->nInUse+1; nblockMAX = 100000 * s->blockSize100k; groupNo = -1; groupPos = 0; for (i = 0; i <= 255; i++) s->unzftab[i] = 0; /*-- MTF init --*/ { Int32 ii, jj, kk; kk = MTFA_SIZE-1; for (ii = 256 / MTFL_SIZE - 1; ii >= 0; ii--) { for (jj = MTFL_SIZE-1; jj >= 0; jj--) { s->mtfa[kk] = (UChar)(ii * MTFL_SIZE + jj); kk--; } s->mtfbase[ii] = kk + 1; } } /*-- end MTF init --*/ nblock = 0; GET_MTF_VAL(BZ_X_MTF_1, BZ_X_MTF_2, nextSym); while (True) { if (nextSym == EOB) break; if (nextSym == BZ_RUNA || nextSym == BZ_RUNB) { es = -1; N = 1; do { /* Check that N doesn't get too big, so that es doesn't go negative. The maximum value that can be RUNA/RUNB encoded is equal to the block size (post the initial RLE), viz, 900k, so bounding N at 2 million should guard against overflow without rejecting any legitimate inputs. */ if (N >= 2*1024*1024) RETURN(BZ_DATA_ERROR); if (nextSym == BZ_RUNA) es = es + (0+1) * N; else if (nextSym == BZ_RUNB) es = es + (1+1) * N; N = N * 2; GET_MTF_VAL(BZ_X_MTF_3, BZ_X_MTF_4, nextSym); } while (nextSym == BZ_RUNA || nextSym == BZ_RUNB); es++; uc = s->seqToUnseq[ s->mtfa[s->mtfbase[0]] ]; s->unzftab[uc] += es; if (s->smallDecompress) while (es > 0) { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); s->ll16[nblock] = (UInt16)uc; nblock++; es--; } else while (es > 0) { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); s->tt[nblock] = (UInt32)uc; nblock++; es--; }; continue; } else { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); /*-- uc = MTF ( nextSym-1 ) --*/ { Int32 ii, jj, kk, pp, lno, off; UInt32 nn; nn = (UInt32)(nextSym - 1); if (nn < MTFL_SIZE) { /* avoid general-case expense */ pp = s->mtfbase[0]; uc = s->mtfa[pp+nn]; while (nn > 3) { Int32 z = pp+nn; s->mtfa[(z) ] = s->mtfa[(z)-1]; s->mtfa[(z)-1] = s->mtfa[(z)-2]; s->mtfa[(z)-2] = s->mtfa[(z)-3]; s->mtfa[(z)-3] = s->mtfa[(z)-4]; nn -= 4; } while (nn > 0) { s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--; }; s->mtfa[pp] = uc; } else { /* general case */ lno = nn / MTFL_SIZE; off = nn % MTFL_SIZE; pp = s->mtfbase[lno] + off; uc = s->mtfa[pp]; while (pp > s->mtfbase[lno]) { s->mtfa[pp] = s->mtfa[pp-1]; pp--; }; s->mtfbase[lno]++; while (lno > 0) { s->mtfbase[lno]--; s->mtfa[s->mtfbase[lno]] = s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1]; lno--; } s->mtfbase[0]--; s->mtfa[s->mtfbase[0]] = uc; if (s->mtfbase[0] == 0) { kk = MTFA_SIZE-1; for (ii = 256 / MTFL_SIZE-1; ii >= 0; ii--) { for (jj = MTFL_SIZE-1; jj >= 0; jj--) { s->mtfa[kk] = s->mtfa[s->mtfbase[ii] + jj]; kk--; } s->mtfbase[ii] = kk + 1; } } } } /*-- end uc = MTF ( nextSym-1 ) --*/ s->unzftab[s->seqToUnseq[uc]]++; if (s->smallDecompress) s->ll16[nblock] = (UInt16)(s->seqToUnseq[uc]); else s->tt[nblock] = (UInt32)(s->seqToUnseq[uc]); nblock++; GET_MTF_VAL(BZ_X_MTF_5, BZ_X_MTF_6, nextSym); continue; } } /* Now we know what nblock is, we can do a better sanity check on s->origPtr. */ if (s->origPtr < 0 || s->origPtr >= nblock) RETURN(BZ_DATA_ERROR); /*-- Set up cftab to facilitate generation of T^(-1) --*/ /* Check: unzftab entries in range. */ for (i = 0; i <= 255; i++) { if (s->unzftab[i] < 0 || s->unzftab[i] > nblock) RETURN(BZ_DATA_ERROR); } /* Actually generate cftab. */ s->cftab[0] = 0; for (i = 1; i <= 256; i++) s->cftab[i] = s->unzftab[i-1]; for (i = 1; i <= 256; i++) s->cftab[i] += s->cftab[i-1]; /* Check: cftab entries in range. */ for (i = 0; i <= 256; i++) { if (s->cftab[i] < 0 || s->cftab[i] > nblock) { /* s->cftab[i] can legitimately be == nblock */ RETURN(BZ_DATA_ERROR); } } /* Check: cftab entries non-descending. */ for (i = 1; i <= 256; i++) { if (s->cftab[i-1] > s->cftab[i]) { RETURN(BZ_DATA_ERROR); } } s->state_out_len = 0; s->state_out_ch = 0; BZ_INITIALISE_CRC ( s->calculatedBlockCRC ); s->state = BZ_X_OUTPUT; if (s->verbosity >= 2) VPrintf0 ( "rt+rld" ); if (s->smallDecompress) { /*-- Make a copy of cftab, used in generation of T --*/ for (i = 0; i <= 256; i++) s->cftabCopy[i] = s->cftab[i]; /*-- compute the T vector --*/ for (i = 0; i < nblock; i++) { uc = (UChar)(s->ll16[i]); SET_LL(i, s->cftabCopy[uc]); s->cftabCopy[uc]++; } /*-- Compute T^(-1) by pointer reversal on T --*/ i = s->origPtr; j = GET_LL(i); do { Int32 tmp = GET_LL(j); SET_LL(j, i); i = j; j = tmp; } while (i != s->origPtr); s->tPos = s->origPtr; s->nblock_used = 0; if (s->blockRandomised) { BZ_RAND_INIT_MASK; BZ_GET_SMALL(s->k0); s->nblock_used++; BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; } else { BZ_GET_SMALL(s->k0); s->nblock_used++; } } else { /*-- compute the T^(-1) vector --*/ for (i = 0; i < nblock; i++) { uc = (UChar)(s->tt[i] & 0xff); s->tt[s->cftab[uc]] |= (i << 8); s->cftab[uc]++; } s->tPos = s->tt[s->origPtr] >> 8; s->nblock_used = 0; if (s->blockRandomised) { BZ_RAND_INIT_MASK; BZ_GET_FAST(s->k0); s->nblock_used++; BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; } else { BZ_GET_FAST(s->k0); s->nblock_used++; } } RETURN(BZ_OK); endhdr_2: GET_UCHAR(BZ_X_ENDHDR_2, uc); if (uc != 0x72) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_3, uc); if (uc != 0x45) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_4, uc); if (uc != 0x38) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_5, uc); if (uc != 0x50) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_6, uc); if (uc != 0x90) RETURN(BZ_DATA_ERROR); s->storedCombinedCRC = 0; GET_UCHAR(BZ_X_CCRC_1, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_2, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_3, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_4, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); s->state = BZ_X_IDLE; RETURN(BZ_STREAM_END); default: AssertH ( False, 4001 ); } AssertH ( False, 4002 ); save_state_and_return: s->save_i = i; s->save_j = j; s->save_t = t; s->save_alphaSize = alphaSize; s->save_nGroups = nGroups; s->save_nSelectors = nSelectors; s->save_EOB = EOB; s->save_groupNo = groupNo; s->save_groupPos = groupPos; s->save_nextSym = nextSym; s->save_nblockMAX = nblockMAX; s->save_nblock = nblock; s->save_es = es; s->save_N = N; s->save_curr = curr; s->save_zt = zt; s->save_zn = zn; s->save_zvec = zvec; s->save_zj = zj; s->save_gSel = gSel; s->save_gMinlen = gMinlen; s->save_gLimit = gLimit; s->save_gBase = gBase; s->save_gPerm = gPerm; return retVal; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Make sure nSelectors is not out of range nSelectors is used in a loop from 0 to nSelectors to access selectorMtf which is UChar selectorMtf[BZ_MAX_SELECTORS]; so if nSelectors is bigger than BZ_MAX_SELECTORS it'll do an invalid memory access Fixes out of bounds access discovered while fuzzying karchive'</s>
<s>[INST] Given the following code containing errors, provide 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 nfc_genl_deactivate_target(struct sk_buff *skb, struct genl_info *info) { struct nfc_dev *dev; u32 device_idx, target_idx; int rc; if (!info->attrs[NFC_ATTR_DEVICE_INDEX]) return -EINVAL; device_idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]); dev = nfc_get_device(device_idx); if (!dev) return -ENODEV; target_idx = nla_get_u32(info->attrs[NFC_ATTR_TARGET_INDEX]); rc = nfc_deactivate_target(dev, target_idx, NFC_TARGET_MODE_SLEEP); nfc_put_device(dev); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'nfc: Ensure presence of required attributes in the deactivate_target handler Check that the NFC_ATTR_TARGET_INDEX attributes (in addition to NFC_ATTR_DEVICE_INDEX) are provided by the netlink client prior to accessing them. This prevents potential unhandled NULL pointer dereference exceptions which can be triggered by malicious user-mode programs, if they omit one or both of these attributes. Signed-off-by: Young Xiao <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: char *url_decode_r(char *to, char *url, size_t size) { char *s = url, // source *d = to, // destination *e = &to[size - 1]; // destination end while(*s && d < e) { if(unlikely(*s == '%')) { if(likely(s[1] && s[2])) { *d++ = from_hex(s[1]) << 4 | from_hex(s[2]); s += 2; } } else if(unlikely(*s == '+')) *d++ = ' '; else *d++ = *s; s++; } *d = '\0'; return to; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-113', 'CWE-200', 'CWE-94', 'CWE-74'], 'message': 'fixed vulnerabilities identified by red4sec.com (#4521)'</s>
<s>[INST] Given the following code containing errors, provide 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 am_handle_probe_discovery(request_rec *r) { am_dir_cfg_rec *cfg = am_get_dir_cfg(r); LassoServer *server; const char *disco_idp = NULL; int timeout; char *return_to; char *idp_param; char *redirect_url; int ret; server = am_get_lasso_server(r); if(server == NULL) { return HTTP_INTERNAL_SERVER_ERROR; } /* * If built-in IdP discovery is not configured, return error. * For now we only have the get-metadata metadata method, so this * information is not saved in configuration nor it is checked here. */ timeout = cfg->probe_discovery_timeout; if (timeout == -1) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "probe discovery handler invoked but not " "configured. Plase set MellonProbeDiscoveryTimeout."); return HTTP_INTERNAL_SERVER_ERROR; } /* * Check for mandatory arguments early to avoid sending * probles for nothing. */ return_to = am_extract_query_parameter(r->pool, r->args, "return"); if(return_to == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Missing required return parameter."); return HTTP_BAD_REQUEST; } ret = am_urldecode(return_to); if (ret != OK) { ap_log_rerror(APLOG_MARK, APLOG_ERR, ret, r, "Could not urldecode return value."); return HTTP_BAD_REQUEST; } idp_param = am_extract_query_parameter(r->pool, r->args, "returnIDParam"); if(idp_param == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Missing required returnIDParam parameter."); return HTTP_BAD_REQUEST; } ret = am_urldecode(idp_param); if (ret != OK) { ap_log_rerror(APLOG_MARK, APLOG_ERR, ret, r, "Could not urldecode returnIDParam value."); return HTTP_BAD_REQUEST; } /* * Proceed with built-in IdP discovery. * * First try sending probes to IdP configured for discovery. * Second send probes for all configured IdP * The first to answer is chosen. * If none answer, use the first configured IdP */ if (!apr_is_empty_table(cfg->probe_discovery_idp)) { const apr_array_header_t *header; apr_table_entry_t *elts; const char *url; const char *idp; int i; header = apr_table_elts(cfg->probe_discovery_idp); elts = (apr_table_entry_t *)header->elts; for (i = 0; i < header->nelts; i++) { idp = elts[i].key; url = elts[i].val; if (am_probe_url(r, url, timeout) == OK) { disco_idp = idp; break; } } } else { GList *iter; GList *idp_list; const char *idp; idp_list = g_hash_table_get_keys(server->providers); for (iter = idp_list; iter != NULL; iter = iter->next) { idp = iter->data; if (am_probe_url(r, idp, timeout) == OK) { disco_idp = idp; break; } } g_list_free(idp_list); } /* * On failure, try default */ if (disco_idp == NULL) { disco_idp = am_first_idp(r); if (disco_idp == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "probeDiscovery found no usable IdP."); return HTTP_INTERNAL_SERVER_ERROR; } else { ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, "probeDiscovery " "failed, trying default IdP %s", disco_idp); } } else { ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, "probeDiscovery using %s", disco_idp); } redirect_url = apr_psprintf(r->pool, "%s%s%s=%s", return_to, strchr(return_to, '?') ? "&" : "?", am_urlencode(r->pool, idp_param), am_urlencode(r->pool, disco_idp)); apr_table_setn(r->headers_out, "Location", redirect_url); return HTTP_SEE_OTHER; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-601'], 'message': 'Add MellonRedirectDomains option. Limit the domains that we will redirect to after login / logout to a set of trusted domains. By default we only allow redirects to the current domain. This change breaks backwards compatibility with any site that relies on redirects to separate domains. Fixes #35'</s>
<s>[INST] Given the following code containing errors, provide 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 am_handle_reply_common(request_rec *r, LassoLogin *login, char *relay_state, char *saml_response, bool is_paos) { char *url; char *chr; const char *name_id; LassoSamlp2Response *response; LassoSaml2Assertion *assertion; const char *in_response_to; am_dir_cfg_rec *dir_cfg; am_cache_entry_t *session; int rc; const char *idp; url = am_reconstruct_url(r); chr = strchr(url, '?'); if (! chr) { chr = strchr(url, ';'); } if (chr) { *chr = '\0'; } dir_cfg = am_get_dir_cfg(r); if(LASSO_PROFILE(login)->nameIdentifier == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "No acceptable name identifier found in" " SAML 2.0 response."); lasso_login_destroy(login); return HTTP_BAD_REQUEST; } name_id = LASSO_SAML2_NAME_ID(LASSO_PROFILE(login)->nameIdentifier) ->content; response = LASSO_SAMLP2_RESPONSE(LASSO_PROFILE(login)->response); if (response->parent.Destination) { if (strcmp(response->parent.Destination, url)) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Invalid Destination on Response. Should be: %s", url); lasso_login_destroy(login); return HTTP_BAD_REQUEST; } } if (g_list_length(response->Assertion) == 0) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "No Assertion in response."); lasso_login_destroy(login); return HTTP_BAD_REQUEST; } if (g_list_length(response->Assertion) > 1) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "More than one Assertion in response."); lasso_login_destroy(login); return HTTP_BAD_REQUEST; } assertion = g_list_first(response->Assertion)->data; if (!LASSO_IS_SAML2_ASSERTION(assertion)) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Wrong type of Assertion node."); lasso_login_destroy(login); return HTTP_BAD_REQUEST; } rc = am_validate_subject(r, assertion, url); if (rc != OK) { lasso_login_destroy(login); return rc; } rc = am_validate_conditions(r, assertion, LASSO_PROVIDER(LASSO_PROFILE(login)->server)->ProviderID); if (rc != OK) { lasso_login_destroy(login); return rc; } in_response_to = response->parent.InResponseTo; if (!is_paos) { if(in_response_to != NULL) { /* This is SP-initiated login. Check that we have a cookie. */ if(am_cookie_get(r) == NULL) { /* Missing cookie. */ ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, "User has disabled cookies, or has lost" " the cookie before returning from the SAML2" " login server."); if(dir_cfg->no_cookie_error_page != NULL) { apr_table_setn(r->headers_out, "Location", dir_cfg->no_cookie_error_page); lasso_login_destroy(login); return HTTP_SEE_OTHER; } else { /* Return 400 Bad Request when the user hasn't set a * no-cookie error page. */ lasso_login_destroy(login); return HTTP_BAD_REQUEST; } } } } /* Check AuthnContextClassRef */ rc = am_validate_authn_context_class_ref(r, assertion); if (rc != OK) { lasso_login_destroy(login); return rc; } /* Create a new session. */ session = am_new_request_session(r); if(session == NULL) { ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, "am_new_request_session() failed"); return HTTP_INTERNAL_SERVER_ERROR; } rc = add_attributes(session, r, name_id, assertion); if(rc != OK) { am_release_request_session(r, session); lasso_login_destroy(login); return rc; } /* If requested, save the IdP ProviderId */ if(dir_cfg->idpattr != NULL) { idp = LASSO_PROFILE(login)->remote_providerID; if(idp != NULL) { rc = am_cache_env_append(session, dir_cfg->idpattr, idp); if(rc != OK) { am_release_request_session(r, session); lasso_login_destroy(login); return rc; } } } rc = lasso_login_accept_sso(login); if(rc < 0) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Unable to accept SSO message." " Lasso error: [%i] %s", rc, lasso_strerror(rc)); am_release_request_session(r, session); lasso_login_destroy(login); return HTTP_INTERNAL_SERVER_ERROR; } /* Save the profile state. */ rc = am_save_lasso_profile_state(r, session, LASSO_PROFILE(login), saml_response); if(rc != OK) { am_release_request_session(r, session); lasso_login_destroy(login); return rc; } /* Mark user as logged in. */ session->logged_in = 1; am_release_request_session(r, session); lasso_login_destroy(login); /* No RelayState - we don't know what to do. Use default login path. */ if(relay_state == NULL || strlen(relay_state) == 0) { dir_cfg = am_get_dir_cfg(r); apr_table_setn(r->headers_out, "Location", dir_cfg->login_path); return HTTP_SEE_OTHER; } rc = am_urldecode(relay_state); if (rc != OK) { ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r, "Could not urldecode RelayState value."); return HTTP_BAD_REQUEST; } /* Check for bad characters in RelayState. */ rc = am_check_url(r, relay_state); if (rc != OK) { return rc; } apr_table_setn(r->headers_out, "Location", relay_state); /* HTTP_SEE_OTHER should be a redirect where the browser doesn't repeat * the POST data to the new page. */ return HTTP_SEE_OTHER; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-601'], 'message': 'Add MellonRedirectDomains option. Limit the domains that we will redirect to after login / logout to a set of trusted domains. By default we only allow redirects to the current domain. This change breaks backwards compatibility with any site that relies on redirects to separate domains. Fixes #35'</s>
<s>[INST] Given the following code containing errors, provide 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 am_init_logout_request(request_rec *r, LassoLogout *logout) { char *return_to; int rc; am_cache_entry_t *mellon_session; gint res; char *redirect_to; LassoProfile *profile; LassoSession *session; GList *assertion_list; LassoNode *assertion_n; LassoSaml2Assertion *assertion; LassoSaml2AuthnStatement *authnStatement; LassoSamlp2LogoutRequest *request; return_to = am_extract_query_parameter(r->pool, r->args, "ReturnTo"); rc = am_urldecode(return_to); if (rc != OK) { ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r, "Could not urldecode ReturnTo value."); return HTTP_BAD_REQUEST; } /* Disable the the local session (in case the IdP doesn't respond). */ mellon_session = am_get_request_session(r); if(mellon_session != NULL) { am_restore_lasso_profile_state(r, &logout->parent, mellon_session); mellon_session->logged_in = 0; am_release_request_session(r, mellon_session); } /* Create the logout request message. */ res = lasso_logout_init_request(logout, NULL, LASSO_HTTP_METHOD_REDIRECT); /* Early non failing return. */ if (res != 0) { if(res == LASSO_PROFILE_ERROR_SESSION_NOT_FOUND) { ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, "User attempted to initiate logout without being" " loggged in."); } else if (res == LASSO_LOGOUT_ERROR_UNSUPPORTED_PROFILE || res == LASSO_PROFILE_ERROR_UNSUPPORTED_PROFILE) { ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, "Current identity provider " "does not support single logout. Destroying local session only."); } else if(res != 0) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Unable to create logout request." " Lasso error: [%i] %s", res, lasso_strerror(res)); lasso_logout_destroy(logout); return HTTP_INTERNAL_SERVER_ERROR; } lasso_logout_destroy(logout); /* Check for bad characters in ReturnTo. */ rc = am_check_url(r, return_to); if (rc != OK) { return rc; } /* Redirect to the page the user should be sent to after logout. */ apr_table_setn(r->headers_out, "Location", return_to); return HTTP_SEE_OTHER; } profile = LASSO_PROFILE(logout); /* We need to set the SessionIndex in the LogoutRequest to the SessionIndex * we received during the login operation. This is not needed since release * 2.3.0. */ if (lasso_check_version(2, 3, 0, LASSO_CHECK_VERSION_NUMERIC) == 0) { session = lasso_profile_get_session(profile); assertion_list = lasso_session_get_assertions( session, profile->remote_providerID); if(! assertion_list || LASSO_IS_SAML2_ASSERTION(assertion_list->data) == FALSE) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "No assertions found for the current session."); lasso_logout_destroy(logout); return HTTP_INTERNAL_SERVER_ERROR; } /* We currently only look at the first assertion in the list * lasso_session_get_assertions returns. */ assertion_n = assertion_list->data; assertion = LASSO_SAML2_ASSERTION(assertion_n); /* We assume that the first authnStatement contains the data we want. */ authnStatement = LASSO_SAML2_AUTHN_STATEMENT(assertion->AuthnStatement->data); if(!authnStatement) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "No AuthnStatement found in the current assertion."); lasso_logout_destroy(logout); return HTTP_INTERNAL_SERVER_ERROR; } if(authnStatement->SessionIndex) { request = LASSO_SAMLP2_LOGOUT_REQUEST(profile->request); request->SessionIndex = g_strdup(authnStatement->SessionIndex); } } /* Set the RelayState parameter to the return url (if we have one). */ if(return_to) { profile->msg_relayState = g_strdup(return_to); } /* Serialize the request message into a url which we can redirect to. */ res = lasso_logout_build_request_msg(logout); if(res != 0) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Unable to serialize lasso logout message." " Lasso error: [%i] %s", res, lasso_strerror(res)); lasso_logout_destroy(logout); return HTTP_INTERNAL_SERVER_ERROR; } /* Set the redirect url. */ redirect_to = apr_pstrdup(r->pool, LASSO_PROFILE(logout)->msg_url); /* Check if the lasso library added the RelayState. If lasso didn't add * a RelayState parameter, then we add one ourself. This should hopefully * be removed in the future. */ if(return_to != NULL && strstr(redirect_to, "&RelayState=") == NULL && strstr(redirect_to, "?RelayState=") == NULL) { /* The url didn't contain the relaystate parameter. */ redirect_to = apr_pstrcat( r->pool, redirect_to, "&RelayState=", am_urlencode(r->pool, return_to), NULL ); } apr_table_setn(r->headers_out, "Location", redirect_to); lasso_logout_destroy(logout); /* Redirect (without including POST data if this was a POST request. */ return HTTP_SEE_OTHER; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-601'], 'message': 'Add MellonRedirectDomains option. Limit the domains that we will redirect to after login / logout to a set of trusted domains. By default we only allow redirects to the current domain. This change breaks backwards compatibility with any site that relies on redirects to separate domains. Fixes #35'</s>
<s>[INST] Given the following code containing errors, provide 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 am_handle_repost(request_rec *r) { am_mod_cfg_rec *mod_cfg; const char *query; const char *enctype; char *charset; char *psf_id; char *cp; char *psf_filename; char *post_data; const char *post_form; char *output; char *return_url; const char *(*post_mkform)(request_rec *, const char *); if (am_cookie_get(r) == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Repost query without a session"); return HTTP_FORBIDDEN; } mod_cfg = am_get_mod_cfg(r->server); if (!mod_cfg->post_dir) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Repost query without MellonPostDirectory."); return HTTP_NOT_FOUND; } query = r->parsed_uri.query; enctype = am_extract_query_parameter(r->pool, query, "enctype"); if (enctype == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Bad repost query: missing enctype"); return HTTP_BAD_REQUEST; } if (strcmp(enctype, "urlencoded") == 0) { enctype = "application/x-www-form-urlencoded"; post_mkform = am_post_mkform_urlencoded; } else if (strcmp(enctype, "multipart") == 0) { enctype = "multipart/form-data"; post_mkform = am_post_mkform_multipart; } else { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Bad repost query: invalid enctype \"%s\".", enctype); return HTTP_BAD_REQUEST; } charset = am_extract_query_parameter(r->pool, query, "charset"); if (charset != NULL) { if (am_urldecode(charset) != OK) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Bad repost query: invalid charset \"%s\"", charset); return HTTP_BAD_REQUEST; } /* Check that charset is sane */ for (cp = charset; *cp; cp++) { if (!apr_isalnum(*cp) && (*cp != '-') && (*cp != '_')) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Bad repost query: invalid charset \"%s\"", charset); return HTTP_BAD_REQUEST; } } } psf_id = am_extract_query_parameter(r->pool, query, "id"); if (psf_id == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Bad repost query: missing id"); return HTTP_BAD_REQUEST; } /* Check that Id is sane */ for (cp = psf_id; *cp; cp++) { if (!apr_isalnum(*cp)) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Bad repost query: invalid id \"%s\"", psf_id); return HTTP_BAD_REQUEST; } } return_url = am_extract_query_parameter(r->pool, query, "ReturnTo"); if (return_url == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Invalid or missing query ReturnTo parameter."); return HTTP_BAD_REQUEST; } if (am_urldecode(return_url) != OK) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Bad repost query: return"); return HTTP_BAD_REQUEST; } psf_filename = apr_psprintf(r->pool, "%s/%s", mod_cfg->post_dir, psf_id); post_data = am_getfile(r->pool, r->server, psf_filename); if (post_data == NULL) { /* Unable to load repost data. Just redirect us instead. */ ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, "Bad repost query: cannot find \"%s\"", psf_filename); apr_table_setn(r->headers_out, "Location", return_url); return HTTP_SEE_OTHER; } if ((post_form = (*post_mkform)(r, post_data)) == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "am_post_mkform() failed"); return HTTP_INTERNAL_SERVER_ERROR; } if (charset != NULL) { ap_set_content_type(r, apr_psprintf(r->pool, "text/html; charset=\"%s\"", charset)); charset = apr_psprintf(r->pool, " accept-charset=\"%s\"", charset); } else { ap_set_content_type(r, "text/html"); charset = (char *)""; } output = apr_psprintf(r->pool, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" "<html>\n" " <head>\n" " <title>SAML rePOST request</title>\n" " </head>\n" " <body onload=\"document.getElementById('form').submit();\">\n" " <noscript>\n" " Your browser does not support Javascript, \n" " you must click the button below to proceed.\n" " </noscript>\n" " <form id=\"form\" method=\"POST\" action=\"%s\" enctype=\"%s\"%s>\n%s" " <noscript>\n" " <input type=\"submit\">\n" " </noscript>\n" " </form>\n" " </body>\n" "</html>\n", am_htmlencode(r, return_url), enctype, charset, post_form); ap_rputs(output, r); return OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-601'], 'message': 'Add MellonRedirectDomains option. Limit the domains that we will redirect to after login / logout to a set of trusted domains. By default we only allow redirects to the current domain. This change breaks backwards compatibility with any site that relies on redirects to separate domains. Fixes #35'</s>
<s>[INST] Given the following code containing errors, provide 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 *ReadVIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define VFF_CM_genericRGB 15 #define VFF_CM_ntscRGB 1 #define VFF_CM_NONE 0 #define VFF_DEP_DECORDER 0x4 #define VFF_DEP_NSORDER 0x8 #define VFF_DES_RAW 0 #define VFF_LOC_IMPLICIT 1 #define VFF_MAPTYP_NONE 0 #define VFF_MAPTYP_1_BYTE 1 #define VFF_MAPTYP_2_BYTE 2 #define VFF_MAPTYP_4_BYTE 4 #define VFF_MAPTYP_FLOAT 5 #define VFF_MAPTYP_DOUBLE 7 #define VFF_MS_NONE 0 #define VFF_MS_ONEPERBAND 1 #define VFF_MS_SHARED 3 #define VFF_TYP_BIT 0 #define VFF_TYP_1_BYTE 1 #define VFF_TYP_2_BYTE 2 #define VFF_TYP_4_BYTE 4 #define VFF_TYP_FLOAT 5 #define VFF_TYP_DOUBLE 9 typedef struct _ViffInfo { unsigned char identifier, file_type, release, version, machine_dependency, reserve[3]; char comment[512]; unsigned int rows, columns, subrows; int x_offset, y_offset; float x_bits_per_pixel, y_bits_per_pixel; unsigned int location_type, location_dimension, number_of_images, number_data_bands, data_storage_type, data_encode_scheme, map_scheme, map_storage_type, map_rows, map_columns, map_subrows, map_enable, maps_per_cycle, color_space_model; } ViffInfo; double min_value, scale_factor, value; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register ssize_t x; register Quantum *q; register ssize_t i; register unsigned char *p; size_t bytes_per_pixel, max_packets, quantum; ssize_t count, y; unsigned char *pixels; unsigned long lsb_first; ViffInfo viff_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read VIFF header (1024 bytes). */ count=ReadBlob(image,1,&viff_info.identifier); do { /* Verify VIFF identifier. */ if ((count != 1) || ((unsigned char) viff_info.identifier != 0xab)) ThrowReaderException(CorruptImageError,"NotAVIFFImage"); /* Initialize VIFF image. */ (void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type); (void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release); (void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version); (void) ReadBlob(image,sizeof(viff_info.machine_dependency), &viff_info.machine_dependency); (void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve); count=ReadBlob(image,512,(unsigned char *) viff_info.comment); if (count != 512) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); viff_info.comment[511]='\0'; if (strlen(viff_info.comment) > 4) (void) SetImageProperty(image,"comment",viff_info.comment,exception); if ((viff_info.machine_dependency == VFF_DEP_DECORDER) || (viff_info.machine_dependency == VFF_DEP_NSORDER)) image->endian=LSBEndian; else image->endian=MSBEndian; viff_info.rows=ReadBlobLong(image); viff_info.columns=ReadBlobLong(image); viff_info.subrows=ReadBlobLong(image); viff_info.x_offset=ReadBlobSignedLong(image); viff_info.y_offset=ReadBlobSignedLong(image); viff_info.x_bits_per_pixel=(float) ReadBlobLong(image); viff_info.y_bits_per_pixel=(float) ReadBlobLong(image); viff_info.location_type=ReadBlobLong(image); viff_info.location_dimension=ReadBlobLong(image); viff_info.number_of_images=ReadBlobLong(image); viff_info.number_data_bands=ReadBlobLong(image); viff_info.data_storage_type=ReadBlobLong(image); viff_info.data_encode_scheme=ReadBlobLong(image); viff_info.map_scheme=ReadBlobLong(image); viff_info.map_storage_type=ReadBlobLong(image); viff_info.map_rows=ReadBlobLong(image); viff_info.map_columns=ReadBlobLong(image); viff_info.map_subrows=ReadBlobLong(image); viff_info.map_enable=ReadBlobLong(image); viff_info.maps_per_cycle=ReadBlobLong(image); viff_info.color_space_model=ReadBlobLong(image); for (i=0; i < 420; i++) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows; if (number_pixels > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); if (number_pixels != (size_t) number_pixels) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (number_pixels == 0) ThrowReaderException(CoderError,"ImageColumnOrRowSizeIsNotSupported"); image->columns=viff_info.rows; image->rows=viff_info.columns; image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL : MAGICKCORE_QUANTUM_DEPTH; image->alpha_trait=viff_info.number_data_bands == 4 ? BlendPixelTrait : UndefinedPixelTrait; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); (void) SetImageBackgroundColor(image,exception); /* Verify that we can read this VIFF image. */ if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((viff_info.data_storage_type != VFF_TYP_BIT) && (viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.data_storage_type != VFF_TYP_2_BYTE) && (viff_info.data_storage_type != VFF_TYP_4_BYTE) && (viff_info.data_storage_type != VFF_TYP_FLOAT) && (viff_info.data_storage_type != VFF_TYP_DOUBLE)) ThrowReaderException(CoderError,"DataStorageTypeIsNotSupported"); if (viff_info.data_encode_scheme != VFF_DES_RAW) ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) && (viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_FLOAT) && (viff_info.map_storage_type != VFF_MAPTYP_DOUBLE)) ThrowReaderException(CoderError,"MapStorageTypeIsNotSupported"); if ((viff_info.color_space_model != VFF_CM_NONE) && (viff_info.color_space_model != VFF_CM_ntscRGB) && (viff_info.color_space_model != VFF_CM_genericRGB)) ThrowReaderException(CoderError,"ColorspaceModelIsNotSupported"); if (viff_info.location_type != VFF_LOC_IMPLICIT) ThrowReaderException(CoderError,"LocationTypeIsNotSupported"); if (viff_info.number_of_images != 1) ThrowReaderException(CoderError,"NumberOfImagesIsNotSupported"); if (viff_info.map_rows == 0) viff_info.map_scheme=VFF_MS_NONE; switch ((int) viff_info.map_scheme) { case VFF_MS_NONE: { if (viff_info.number_data_bands < 3) { /* Create linear color ramp. */ if (viff_info.data_storage_type == VFF_TYP_BIT) image->colors=2; else if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE) image->colors=256UL; else image->colors=image->depth <= 8 ? 256UL : 65536UL; status=AcquireImageColormap(image,image->colors,exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } break; } case VFF_MS_ONEPERBAND: case VFF_MS_SHARED: { unsigned char *viff_colormap; /* Allocate VIFF colormap. */ switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break; case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break; case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break; case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break; case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } image->colors=viff_info.map_columns; if ((MagickSizeType) (viff_info.map_rows*image->colors) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if ((MagickSizeType) viff_info.map_rows > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); if ((MagickSizeType) viff_info.map_rows > (viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap)); if (viff_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Read VIFF raster colormap. */ count=ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows, viff_colormap); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: { MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } case VFF_MAPTYP_4_BYTE: case VFF_MAPTYP_FLOAT: { MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } default: break; } for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++) { switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break; case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break; case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break; case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break; default: value=1.0*viff_colormap[i]; break; } if (i < (ssize_t) image->colors) { image->colormap[i].red=(MagickRealType) ScaleCharToQuantum((unsigned char) value); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum((unsigned char) value); image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum((unsigned char) value); } else if (i < (ssize_t) (2*image->colors)) image->colormap[i % image->colors].green=(MagickRealType) ScaleCharToQuantum((unsigned char) value); else if (i < (ssize_t) (3*image->colors)) image->colormap[i % image->colors].blue=(MagickRealType) ScaleCharToQuantum((unsigned char) value); } viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap); break; } default: ThrowReaderException(CoderError,"ColormapTypeNotSupported"); } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (viff_info.data_storage_type == VFF_TYP_BIT) { /* Create bi-level colormap. */ image->colors=2; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); image->colorspace=GRAYColorspace; } /* Allocate VIFF pixels. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: bytes_per_pixel=2; break; case VFF_TYP_4_BYTE: bytes_per_pixel=4; break; case VFF_TYP_FLOAT: bytes_per_pixel=4; break; case VFF_TYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } if (viff_info.data_storage_type == VFF_TYP_BIT) { if (HeapOverflowSanityCheck((image->columns+7UL) >> 3UL,image->rows) != MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); max_packets=((image->columns+7UL) >> 3UL)*image->rows; } else { if (HeapOverflowSanityCheck((size_t) number_pixels,viff_info.number_data_bands) != MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); max_packets=(size_t) (number_pixels*viff_info.number_data_bands); } if ((MagickSizeType) (bytes_per_pixel*max_packets) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); pixels=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax( number_pixels,max_packets),bytes_per_pixel*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(pixels,0,MagickMax(number_pixels,max_packets)* bytes_per_pixel*sizeof(*pixels)); count=ReadBlob(image,bytes_per_pixel*max_packets,pixels); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: { MSBOrderShort(pixels,bytes_per_pixel*max_packets); break; } case VFF_TYP_4_BYTE: case VFF_TYP_FLOAT: { MSBOrderLong(pixels,bytes_per_pixel*max_packets); break; } default: break; } min_value=0.0; scale_factor=1.0; if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.map_scheme == VFF_MS_NONE)) { double max_value; /* Determine scale factor. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break; default: value=1.0*pixels[0]; break; } max_value=value; min_value=value; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (value > max_value) max_value=value; else if (value < min_value) min_value=value; } if ((min_value == 0) && (max_value == 0)) scale_factor=0; else if (min_value == max_value) { scale_factor=(double) QuantumRange/min_value; min_value=0; } else scale_factor=(double) QuantumRange/(max_value-min_value); } /* Convert pixels to Quantum size. */ p=(unsigned char *) pixels; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (viff_info.map_scheme == VFF_MS_NONE) { value=(value-min_value)*scale_factor; if (value > QuantumRange) value=QuantumRange; else if (value < 0) value=0; } *p=(unsigned char) ((Quantum) value); p++; } /* Convert VIFF raster image to pixel packets. */ p=(unsigned char *) pixels; if (viff_info.data_storage_type == VFF_TYP_BIT) { /* Convert bitmap scanline. */ for (y=0; y < (ssize_t) image->rows; y++) { 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++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(image,quantum == 0 ? 0 : QuantumRange,q); SetPixelGreen(image,quantum == 0 ? 0 : QuantumRange,q); SetPixelBlue(image,quantum == 0 ? 0 : QuantumRange,q); if (image->storage_class == PseudoClass) SetPixelIndex(image,(Quantum) quantum,q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (int) (image->columns % 8); bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(image,quantum == 0 ? 0 : QuantumRange,q); SetPixelGreen(image,quantum == 0 ? 0 : QuantumRange,q); SetPixelBlue(image,quantum == 0 ? 0 : QuantumRange,q); if (image->storage_class == PseudoClass) SetPixelIndex(image,(Quantum) quantum,q); q+=GetPixelChannels(image); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else if (image->storage_class == PseudoClass) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p++,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else { /* Convert DirectColor scanline. */ number_pixels=(MagickSizeType) image->columns*image->rows; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p),q); SetPixelGreen(image,ScaleCharToQuantum(*(p+number_pixels)),q); SetPixelBlue(image,ScaleCharToQuantum(*(p+2*number_pixels)),q); if (image->colors != 0) { ssize_t index; index=(ssize_t) GetPixelRed(image,q); SetPixelRed(image,ClampToQuantum(image->colormap[ ConstrainColormapIndex(image,index,exception)].red),q); index=(ssize_t) GetPixelGreen(image,q); SetPixelGreen(image,ClampToQuantum(image->colormap[ ConstrainColormapIndex(image,index,exception)].green),q); index=(ssize_t) GetPixelBlue(image,q); SetPixelBlue(image,ClampToQuantum(image->colormap[ ConstrainColormapIndex(image,index,exception)].blue),q); } SetPixelAlpha(image,image->alpha_trait != UndefinedPixelTrait ? ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueAlpha,q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (image->storage_class == PseudoClass) (void) SyncImage(image,exception); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; count=ReadBlob(image,1,&viff_info.identifier); if ((count == 1) && (viff_info.identifier == 0xab)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); 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 ((count != 0) && (viff_info.identifier == 0xab)); (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-399', 'CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1600'</s>
<s>[INST] Given the following code containing errors, provide 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 WriteHEICImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { long x, y; MagickBooleanType status; MagickOffsetType scene; struct heif_context *heif_context; struct heif_encoder *heif_encoder; struct heif_image *heif_image; /* 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,exception); if (status == MagickFalse) return(status); scene=0; heif_context=heif_context_alloc(); heif_image=(struct heif_image*) NULL; heif_encoder=(struct heif_encoder*) NULL; do { const PixelPacket *p; int stride_y, stride_cb, stride_cr; struct heif_error error; struct heif_writer writer; uint8_t *p_y, *p_cb, *p_cr; /* Transform colorspace to YCbCr. */ if (image->colorspace != YCbCrColorspace) status=TransformImageColorspace(image,YCbCrColorspace); if (status == MagickFalse) break; /* Initialize HEIF encoder context */ error=heif_image_create((int) image->columns,(int) image->rows, heif_colorspace_YCbCr,heif_chroma_420,&heif_image); status=IsHeifSuccess(&error,image); if (status == MagickFalse) break; error=heif_image_add_plane(heif_image,heif_channel_Y,(int) image->columns, (int) image->rows,8); status=IsHeifSuccess(&error,image); if (status == MagickFalse) break; error=heif_image_add_plane(heif_image,heif_channel_Cb, ((int) image->columns+1)/2,((int) image->rows+1)/2,8); status=IsHeifSuccess(&error,image); if (status == MagickFalse) break; error=heif_image_add_plane(heif_image,heif_channel_Cr, ((int) image->columns+1)/2,((int) image->rows+1)/2,8); status=IsHeifSuccess(&error,image); if (status == MagickFalse) break; p_y=heif_image_get_plane(heif_image,heif_channel_Y,&stride_y); p_cb=heif_image_get_plane(heif_image,heif_channel_Cb,&stride_cb); p_cr=heif_image_get_plane(heif_image,heif_channel_Cr,&stride_cr); /* Copy image to heif_image */ for (y=0; y < (long) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } if ((y & 1)==0) { for (x=0; x < (long) image->columns; x+=2) { p_y[y*stride_y+x]=ScaleQuantumToChar(GetPixelRed(p)); p_cb[y/2*stride_cb+x/2]=ScaleQuantumToChar(GetPixelGreen(p)); p_cr[y/2*stride_cr+x/2]=ScaleQuantumToChar(GetPixelBlue(p)); p++; if (x+1 < image->columns) { p_y[y*stride_y + x+1]=ScaleQuantumToChar(GetPixelRed(p)); p++; } } } else { for (x=0; x < (long) image->columns; x++) { p_y[y*stride_y + x]=ScaleQuantumToChar(GetPixelRed(p)); p++; } } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (status == MagickFalse) break; /* Code and actually write the HEIC image */ error=heif_context_get_encoder_for_format(heif_context, heif_compression_HEVC,&heif_encoder); status=IsHeifSuccess(&error,image); if (status == MagickFalse) break; if (image_info->quality != UndefinedCompressionQuality) { error=heif_encoder_set_lossy_quality(heif_encoder, (int) image_info->quality); status=IsHeifSuccess(&error,image); if (status == MagickFalse) break; } error=heif_context_encode_image(heif_context,heif_image,heif_encoder, (const struct heif_encoding_options*) NULL, (struct heif_image_handle**) NULL); status=IsHeifSuccess(&error,image); if (status == MagickFalse) break; writer.writer_api_version=1; writer.write=heif_write_func; error=heif_context_write(heif_context,&writer,image); status=IsHeifSuccess(&error,image); if (status == MagickFalse) break; if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene, GetImageListLength(image)); if (status == MagickFalse) break; heif_encoder_release(heif_encoder); heif_encoder=(struct heif_encoder*) NULL; heif_image_release(heif_image); heif_image=(struct heif_image*) NULL; scene++; } while (image_info->adjoin != MagickFalse); if (heif_encoder != (struct heif_encoder*) NULL) heif_encoder_release(heif_encoder); if (heif_image != (struct heif_image*) NULL) heif_image_release(heif_image); heif_context_free(heif_context); (void) CloseBlob(image); return(status); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'</s>
<s>[INST] Given the following code containing errors, provide 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 *ReadMTVImage(const ImageInfo *image_info,ExceptionInfo *exception) { char buffer[MaxTextExtent]; Image *image; MagickBooleanType status; register ssize_t x; register PixelPacket *q; register unsigned char *p; ssize_t count, y; unsigned char *pixels; unsigned long columns, rows; /* 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 MTV image. */ (void) memset(buffer,0,sizeof(buffer)); (void) ReadBlobString(image,buffer); count=(ssize_t) sscanf(buffer,"%lu %lu\n",&columns,&rows); if (count != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { /* Initialize image structure. */ image->columns=columns; image->rows=rows; image->depth=8; 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)); } /* Convert MTV raster image to pixel packets. */ pixels=(unsigned char *) AcquireQuantumMemory(image->columns, 3UL*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { count=(ssize_t) ReadBlob(image,(size_t) (3*image->columns),pixels); if (count != (ssize_t) (3*image->columns)) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelOpacity(q,OpaqueOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; *buffer='\0'; count=0; if (ReadBlobString(image,buffer) == (char *) NULL) break; count=(ssize_t) sscanf(buffer,"%lu %lu\n",&columns,&rows); if (count > 0) { /* Allocate 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 (count > 0); (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'</s>
<s>[INST] Given the following code containing errors, provide 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 *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define RMT_EQUAL_RGB 1 #define RMT_NONE 0 #define RMT_RAW 2 #define RT_STANDARD 1 #define RT_ENCODED 2 #define RT_FORMAT_RGB 3 typedef struct _SUNInfo { unsigned int magic, width, height, depth, length, type, maptype, maplength; } SUNInfo; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register IndexPacket *indexes; register PixelPacket *q; register ssize_t i, x; register unsigned char *p; size_t bytes_per_line, extent, height, pixels_length, quantum; ssize_t count, y; SUNInfo sun_info; unsigned char *sun_data, *sun_pixels; /* 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 SUN raster header. */ (void) memset(&sun_info,0,sizeof(sun_info)); sun_info.magic=ReadBlobMSBLong(image); do { /* Verify SUN identifier. */ if (sun_info.magic != 0x59a66a95) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); sun_info.width=ReadBlobMSBLong(image); sun_info.height=ReadBlobMSBLong(image); sun_info.depth=ReadBlobMSBLong(image); sun_info.length=ReadBlobMSBLong(image); sun_info.type=ReadBlobMSBLong(image); sun_info.maptype=ReadBlobMSBLong(image); sun_info.maplength=ReadBlobMSBLong(image); if (sun_info.maplength > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); extent=sun_info.height*sun_info.width; if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) && (sun_info.type != RT_FORMAT_RGB)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.depth != 1) && (sun_info.depth != 8) && (sun_info.depth != 24) && (sun_info.depth != 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) && (sun_info.maptype != RMT_RAW)) ThrowReaderException(CoderError,"ColormapTypeNotSupported"); image->columns=sun_info.width; image->rows=sun_info.height; image->depth=sun_info.depth <= 8 ? sun_info.depth : MAGICKCORE_QUANTUM_DEPTH; if (sun_info.depth < 24) { size_t one; image->colors=sun_info.maplength; one=1; if (sun_info.maptype == RMT_NONE) image->colors=one << sun_info.depth; if (sun_info.maptype == RMT_EQUAL_RGB) image->colors=sun_info.maplength/3; if (image->colors == 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } switch (sun_info.maptype) { case RMT_NONE: break; case RMT_EQUAL_RGB: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) { sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum(sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) { sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum(sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) { sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum(sun_colormap[i]); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } case RMT_RAW: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,sun_info.maplength,sun_colormap); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); if (count != (ssize_t) sun_info.maplength) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); break; } default: break; } image->matte=sun_info.depth == 32 ? MagickTrue : MagickFalse; image->columns=sun_info.width; image->rows=sun_info.height; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (sun_info.length == 0) ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); number_pixels=(MagickSizeType) (image->columns*image->rows); if ((sun_info.type != RT_ENCODED) && ((number_pixels*sun_info.depth) > (8UL*sun_info.length))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (HeapOverflowSanityCheck(sun_info.width,sun_info.depth) != MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bytes_per_line=sun_info.width*sun_info.depth; if (sun_info.length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); sun_data=(unsigned char *) AcquireQuantumMemory(sun_info.length, sizeof(*sun_data)); if (sun_data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=(ssize_t) ReadBlob(image,sun_info.length,sun_data); if (count != (ssize_t) sun_info.length) { sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } height=sun_info.height; if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) || ((bytes_per_line/sun_info.depth) != sun_info.width)) { sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); } quantum=sun_info.depth == 1 ? 15 : 7; bytes_per_line+=quantum; bytes_per_line<<=1; if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+quantum)) { sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); } bytes_per_line>>=4; if (HeapOverflowSanityCheck(height,bytes_per_line) != MagickFalse) { sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); } pixels_length=height*bytes_per_line; sun_pixels=(unsigned char *) AcquireQuantumMemory(pixels_length+image->rows, sizeof(*sun_pixels)); if (sun_pixels == (unsigned char *) NULL) { sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } (void) memset(sun_pixels,0,(pixels_length+image->rows)* sizeof(*sun_pixels)); if (sun_info.type == RT_ENCODED) { status=DecodeImage(sun_data,sun_info.length,sun_pixels,pixels_length); if (status == MagickFalse) { sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } } else { if (sun_info.length > pixels_length) { sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels); ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); } (void) memcpy(sun_pixels,sun_data,sun_info.length); } sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); /* Convert SUN raster image to pixel packets. */ p=sun_pixels; if (sun_info.depth == 1) for (y=0; y < (ssize_t) image->rows; y++) { 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=7; bit >= 0; bit--) SetPixelIndex(indexes+x+7-bit,((*p) & (0x01 << bit) ? 0x00 : 0x01)); p++; } if ((image->columns % 8) != 0) { for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--) SetPixelIndex(indexes+x+7-bit,(*p) & (0x01 << bit) ? 0x00 : 0x01); p++; } if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else if (image->storage_class == PseudoClass) { for (y=0; y < (ssize_t) image->rows; y++) { 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; x++) { SetPixelIndex(indexes+x,ConstrainColormapIndex(image,*p)); p++; } if ((image->columns % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { size_t bytes_per_pixel; bytes_per_pixel=3; if (image->matte != MagickFalse) bytes_per_pixel++; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleCharToQuantum(*p++)); if (sun_info.type == RT_STANDARD) { SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelRed(q,ScaleCharToQuantum(*p++)); } else { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); } if (image->colors != 0) { SetPixelRed(q,image->colormap[(ssize_t) GetPixelRed(q)].red); SetPixelGreen(q,image->colormap[(ssize_t) GetPixelGreen(q)].green); SetPixelBlue(q,image->colormap[(ssize_t) GetPixelBlue(q)].blue); } q++; } if (((bytes_per_pixel*image->columns) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (image->storage_class == PseudoClass) (void) SyncImage(image); sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; sun_info.magic=ReadBlobMSBLong(image); if (sun_info.magic == 0x59a66a95) { /* Allocate 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 (sun_info.magic == 0x59a66a95); (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'</s>
<s>[INST] Given the following code containing errors, provide 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 *ReadAAIImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; register ssize_t x; register PixelPacket *q; register unsigned char *p; size_t height, length, width; ssize_t count, y; unsigned char *pixels; /* 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 AAI Dune image. */ width=ReadBlobLSBLong(image); height=ReadBlobLSBLong(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((width == 0UL) || (height == 0UL)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { /* Convert AAI raster image to pixel packets. */ image->columns=width; image->rows=height; image->depth=8; 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)); } pixels=(unsigned char *) AcquireQuantumMemory(image->columns, 4*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); length=(size_t) 4*image->columns; for (y=0; y < (ssize_t) image->rows; y++) { count=ReadBlob(image,length,pixels); if ((size_t) count != length) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels; 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++)); if (*p == 254) *p=255; SetPixelAlpha(q,ScaleCharToQuantum(*p++)); if (q->opacity != OpaqueOpacity) image->matte=MagickTrue; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; width=ReadBlobLSBLong(image); height=ReadBlobLSBLong(image); if ((width != 0UL) && (height != 0UL)) { /* Allocate 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 ((width != 0UL) && (height != 0UL)); (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'</s>
<s>[INST] Given the following code containing errors, provide 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 *ReadRGBImage(const ImageInfo *image_info,ExceptionInfo *exception) { const unsigned char *pixels; Image *canvas_image, *image; MagickBooleanType status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t length; ssize_t count, y; /* 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); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); if (image_info->interlace != PartitionInterlace) { status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,(MagickSizeType) image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); } /* Create virtual canvas to support cropping (i.e. image.rgb[100x100+10+20]). */ canvas_image=CloneImage(image,image->extract_info.width,1,MagickFalse, exception); if (canvas_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetImageVirtualPixelMethod(canvas_image,BlackVirtualPixelMethod); quantum_info=AcquireQuantumInfo(image_info,canvas_image); if (quantum_info == (QuantumInfo *) NULL) { canvas_image=DestroyImage(canvas_image); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } quantum_type=RGBQuantum; if (LocaleCompare(image_info->magick,"RGBA") == 0) { quantum_type=RGBAQuantum; image->matte=MagickTrue; } if (LocaleCompare(image_info->magick,"RGBO") == 0) { quantum_type=RGBOQuantum; image->matte=MagickTrue; } pixels=(const unsigned char *) NULL; if (image_info->number_scenes != 0) while (image->scene < image_info->scene) { /* Skip to next image. */ image->scene++; length=GetQuantumExtent(canvas_image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) length) break; } } count=0; length=0; scene=0; status=MagickTrue; do { /* Read pixels to virtual canvas image then push to image. */ 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) break; switch (image_info->interlace) { case NoInterlace: default: { /* No interlacing: RGBRGBRGBRGBRGBRGB... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,quantum_type); pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,quantum_type,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=QueueAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); SetPixelGreen(q,GetPixelGreen(p)); SetPixelBlue(q,GetPixelBlue(p)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } break; } case LineInterlace: { static QuantumType quantum_types[4] = { RedQuantum, GreenQuantum, BlueQuantum, AlphaQuantum }; /* Line interlacing: RRR...GGG...BBB...RRR...GGG...BBB... */ if (LocaleCompare(image_info->magick,"RGBO") == 0) quantum_types[3]=OpacityQuantum; if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { for (i=0; i < (ssize_t) (image->matte != MagickFalse ? 4 : 3); i++) { register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } quantum_type=quantum_types[i]; q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,quantum_type,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x, 0,canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { switch (quantum_type) { case RedQuantum: { SetPixelRed(q,GetPixelRed(p)); break; } case GreenQuantum: { SetPixelGreen(q,GetPixelGreen(p)); break; } case BlueQuantum: { SetPixelBlue(q,GetPixelBlue(p)); break; } case OpacityQuantum: { SetPixelOpacity(q,GetPixelOpacity(p)); break; } case AlphaQuantum: { SetPixelAlpha(q,GetPixelAlpha(p)); break; } default: break; } p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: { /* Plane interlacing: RRRRRR...GGGGGG...BBBBBB... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) length) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,RedQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,1,6); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,GreenQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(q,GetPixelGreen(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,2,6); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,GetPixelBlue(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,3,6); if (status == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,4,6); if (status == MagickFalse) break; } if (image->matte != MagickFalse) { for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,AlphaQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image, canvas_image->extract_info.x,0,canvas_image->columns,1, exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,5,6); if (status == MagickFalse) break; } } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,6,6); if (status == MagickFalse) break; } break; } case PartitionInterlace: { /* Partition interlacing: RRRRRR..., GGGGGG..., BBBBBB... */ AppendImageFormat("R",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) break; if (DiscardBlobBytes(image,(MagickSizeType) image->offset) == MagickFalse) { status=MagickFalse; ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); for (i=0; i < (ssize_t) scene; i++) { for (y=0; y < (ssize_t) image->extract_info.height; y++) { (void) ReadBlobStream(image,length,GetQuantumPixels(quantum_info), &count); if (count != (ssize_t) length) break; } if (count != (ssize_t) length) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,RedQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,1,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("G",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) break; length=GetQuantumExtent(canvas_image,quantum_info,GreenQuantum); for (i=0; i < (ssize_t) scene; i++) { for (y=0; y < (ssize_t) image->extract_info.height; y++) { (void) ReadBlobStream(image,length,GetQuantumPixels(quantum_info), &count); if (count != (ssize_t) length) break; } if (count != (ssize_t) length) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,GreenQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(q,GetPixelGreen(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,2,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("B",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) break; length=GetQuantumExtent(canvas_image,quantum_info,BlueQuantum); for (i=0; i < (ssize_t) scene; i++) { for (y=0; y < (ssize_t) image->extract_info.height; y++) { (void) ReadBlobStream(image,length,GetQuantumPixels(quantum_info), &count); if (count != (ssize_t) length) break; } if (count != (ssize_t) length) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,GetPixelBlue(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,3,5); if (status == MagickFalse) break; } if (image->matte != MagickFalse) { (void) CloseBlob(image); AppendImageFormat("A",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) break; length=GetQuantumExtent(canvas_image,quantum_info,AlphaQuantum); for (i=0; i < (ssize_t) scene; i++) { for (y=0; y < (ssize_t) image->extract_info.height; y++) { (void) ReadBlobStream(image,length,GetQuantumPixels( quantum_info),&count); if (count != (ssize_t) length) break; } if (count != (ssize_t) length) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x, 0,canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,4,5); if (status == MagickFalse) break; } } (void) CloseBlob(image); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,5,5); if (status == MagickFalse) break; } break; } } if (status == MagickFalse) break; SetQuantumImageType(image,quantum_type); /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (count == (ssize_t) length) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } scene++; } while (count == (ssize_t) length); quantum_info=DestroyQuantumInfo(quantum_info); InheritException(&image->exception,&canvas_image->exception); canvas_image=DestroyImage(canvas_image); (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-401'], 'message': 'Fix ultra rare but potential memory-leak'</s>
<s>[INST] Given the following code containing errors, provide 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 *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception) { char cache_filename[MaxTextExtent], id[MaxTextExtent], keyword[MaxTextExtent], *options; const unsigned char *p; GeometryInfo geometry_info; Image *image; int c; LinkedListInfo *profiles; MagickBooleanType status; MagickOffsetType offset; MagickStatusType flags; register ssize_t i; size_t depth, length; ssize_t count; unsigned int signature; /* 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); } (void) CopyMagickString(cache_filename,image->filename,MaxTextExtent-6); AppendImageFormat("cache",cache_filename); c=ReadBlobByte(image); if (c == EOF) { image=DestroyImage(image); return((Image *) NULL); } *id='\0'; (void) memset(keyword,0,sizeof(keyword)); offset=0; do { /* Decode image header; header terminates one character beyond a ':'. */ SetGeometryInfo(&geometry_info); profiles=(LinkedListInfo *) NULL; length=MaxTextExtent; options=AcquireString((char *) NULL); signature=GetMagickCoreSignature((const StringInfo *) NULL); image->depth=8; image->compression=NoCompression; while ((isgraph(c) != MagickFalse) && (c != (int) ':')) { register char *p; if (c == (int) '{') { char *comment; /* Read comment-- any text between { }. */ length=MaxTextExtent; comment=AcquireString((char *) NULL); for (p=comment; comment != (char *) NULL; p++) { c=ReadBlobByte(image); if (c == (int) '\\') c=ReadBlobByte(image); else if ((c == EOF) || (c == (int) '}')) break; if ((size_t) (p-comment+1) >= length) { *p='\0'; length<<=1; comment=(char *) ResizeQuantumMemory(comment,length+ MaxTextExtent,sizeof(*comment)); if (comment == (char *) NULL) break; p=comment+strlen(comment); } *p=(char) c; } if (comment == (char *) NULL) { options=DestroyString(options); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } *p='\0'; (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); c=ReadBlobByte(image); } else if (isalnum(c) != MagickFalse) { /* Get the keyword. */ length=MaxTextExtent-1; p=keyword; do { if (c == (int) '=') break; if ((size_t) (p-keyword) < (MaxTextExtent-1)) *p++=(char) c; c=ReadBlobByte(image); } while (c != EOF); *p='\0'; p=options; while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); if (c == (int) '=') { /* Get the keyword value. */ c=ReadBlobByte(image); while ((c != (int) '}') && (c != EOF)) { if ((size_t) (p-options+1) >= length) { *p='\0'; length<<=1; options=(char *) ResizeQuantumMemory(options,length+ MaxTextExtent,sizeof(*options)); if (options == (char *) NULL) break; p=options+strlen(options); } *p++=(char) c; c=ReadBlobByte(image); if (c == '\\') { c=ReadBlobByte(image); if (c == (int) '}') { *p++=(char) c; c=ReadBlobByte(image); } } if (*options != '{') if (isspace((int) ((unsigned char) c)) != 0) break; } if (options == (char *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } *p='\0'; if (*options == '{') (void) CopyMagickString(options,options+1,strlen(options)); /* Assign a value to the specified keyword. */ switch (*keyword) { case 'b': case 'B': { if (LocaleCompare(keyword,"background-color") == 0) { (void) QueryColorDatabase(options,&image->background_color, exception); break; } if (LocaleCompare(keyword,"blue-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.blue_primary.x=geometry_info.rho; image->chromaticity.blue_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.blue_primary.y= image->chromaticity.blue_primary.x; break; } if (LocaleCompare(keyword,"border-color") == 0) { (void) QueryColorDatabase(options,&image->border_color, exception); break; } (void) SetImageProperty(image,keyword,options); break; } case 'c': case 'C': { if (LocaleCompare(keyword,"class") == 0) { ssize_t storage_class; storage_class=ParseCommandOption(MagickClassOptions, MagickFalse,options); if (storage_class < 0) break; image->storage_class=(ClassType) storage_class; break; } if (LocaleCompare(keyword,"colors") == 0) { image->colors=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"colorspace") == 0) { ssize_t colorspace; colorspace=ParseCommandOption(MagickColorspaceOptions, MagickFalse,options); if (colorspace < 0) break; image->colorspace=(ColorspaceType) colorspace; break; } if (LocaleCompare(keyword,"compression") == 0) { ssize_t compression; compression=ParseCommandOption(MagickCompressOptions, MagickFalse,options); if (compression < 0) break; image->compression=(CompressionType) compression; break; } if (LocaleCompare(keyword,"columns") == 0) { image->columns=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'd': case 'D': { if (LocaleCompare(keyword,"delay") == 0) { image->delay=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"depth") == 0) { image->depth=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"dispose") == 0) { ssize_t dispose; dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse, options); if (dispose < 0) break; image->dispose=(DisposeType) dispose; break; } (void) SetImageProperty(image,keyword,options); break; } case 'e': case 'E': { if (LocaleCompare(keyword,"endian") == 0) { ssize_t endian; endian=ParseCommandOption(MagickEndianOptions,MagickFalse, options); if (endian < 0) break; image->endian=(EndianType) endian; break; } if (LocaleCompare(keyword,"error") == 0) { image->error.mean_error_per_pixel=StringToDouble(options, (char **) NULL); break; } (void) SetImageProperty(image,keyword,options); break; } case 'g': case 'G': { if (LocaleCompare(keyword,"gamma") == 0) { image->gamma=StringToDouble(options,(char **) NULL); break; } if (LocaleCompare(keyword,"green-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.green_primary.x=geometry_info.rho; image->chromaticity.green_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.green_primary.y= image->chromaticity.green_primary.x; break; } (void) SetImageProperty(image,keyword,options); break; } case 'i': case 'I': { if (LocaleCompare(keyword,"id") == 0) { (void) CopyMagickString(id,options,MaxTextExtent); break; } if (LocaleCompare(keyword,"iterations") == 0) { image->iterations=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'm': case 'M': { if (LocaleCompare(keyword,"magick-signature") == 0) { signature=(unsigned int) StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"matte") == 0) { ssize_t matte; matte=ParseCommandOption(MagickBooleanOptions,MagickFalse, options); if (matte < 0) break; image->matte=(MagickBooleanType) matte; break; } if (LocaleCompare(keyword,"matte-color") == 0) { (void) QueryColorDatabase(options,&image->matte_color, exception); break; } if (LocaleCompare(keyword,"maximum-error") == 0) { image->error.normalized_maximum_error=StringToDouble( options,(char **) NULL); break; } if (LocaleCompare(keyword,"mean-error") == 0) { image->error.normalized_mean_error=StringToDouble(options, (char **) NULL); break; } if (LocaleCompare(keyword,"montage") == 0) { (void) CloneString(&image->montage,options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'o': case 'O': { if (LocaleCompare(keyword,"opaque") == 0) { ssize_t matte; matte=ParseCommandOption(MagickBooleanOptions,MagickFalse, options); if (matte < 0) break; image->matte=(MagickBooleanType) matte; break; } if (LocaleCompare(keyword,"orientation") == 0) { ssize_t orientation; orientation=ParseCommandOption(MagickOrientationOptions, MagickFalse,options); if (orientation < 0) break; image->orientation=(OrientationType) orientation; break; } (void) SetImageProperty(image,keyword,options); break; } case 'p': case 'P': { if (LocaleCompare(keyword,"page") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); break; } if (LocaleCompare(keyword,"pixel-intensity") == 0) { ssize_t intensity; intensity=ParseCommandOption(MagickPixelIntensityOptions, MagickFalse,options); if (intensity < 0) break; image->intensity=(PixelIntensityMethod) intensity; break; } if (LocaleCompare(keyword,"profile") == 0) { if (profiles == (LinkedListInfo *) NULL) profiles=NewLinkedList(0); (void) AppendValueToLinkedList(profiles, AcquireString(options)); break; } (void) SetImageProperty(image,keyword,options); break; } case 'q': case 'Q': { if (LocaleCompare(keyword,"quality") == 0) { image->quality=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'r': case 'R': { if (LocaleCompare(keyword,"red-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.red_primary.x=geometry_info.rho; if ((flags & SigmaValue) != 0) image->chromaticity.red_primary.y=geometry_info.sigma; break; } if (LocaleCompare(keyword,"rendering-intent") == 0) { ssize_t rendering_intent; rendering_intent=ParseCommandOption(MagickIntentOptions, MagickFalse,options); if (rendering_intent < 0) break; image->rendering_intent=(RenderingIntent) rendering_intent; break; } if (LocaleCompare(keyword,"resolution") == 0) { flags=ParseGeometry(options,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; break; } if (LocaleCompare(keyword,"rows") == 0) { image->rows=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 's': case 'S': { if (LocaleCompare(keyword,"scene") == 0) { image->scene=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 't': case 'T': { if (LocaleCompare(keyword,"ticks-per-second") == 0) { image->ticks_per_second=(ssize_t) StringToLong(options); break; } if (LocaleCompare(keyword,"tile-offset") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->tile_offset); geometry=DestroyString(geometry); } if (LocaleCompare(keyword,"type") == 0) { ssize_t type; type=ParseCommandOption(MagickTypeOptions,MagickFalse, options); if (type < 0) break; image->type=(ImageType) type; break; } (void) SetImageProperty(image,keyword,options); break; } case 'u': case 'U': { if (LocaleCompare(keyword,"units") == 0) { ssize_t units; units=ParseCommandOption(MagickResolutionOptions,MagickFalse, options); if (units < 0) break; image->units=(ResolutionType) units; break; } (void) SetImageProperty(image,keyword,options); break; } case 'w': case 'W': { if (LocaleCompare(keyword,"white-point") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.white_point.x=geometry_info.rho; image->chromaticity.white_point.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.white_point.y= image->chromaticity.white_point.x; break; } (void) SetImageProperty(image,keyword,options); break; } default: { (void) SetImageProperty(image,keyword,options); break; } } } else c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } options=DestroyString(options); (void) ReadBlobByte(image); /* Verify that required image information is defined. */ if ((LocaleCompare(id,"MagickCache") != 0) || (image->depth > 128) || (image->storage_class == UndefinedClass) || (image->compression == UndefinedCompression) || (image->columns == 0) || (image->rows == 0)) { if (profiles != (LinkedListInfo *) NULL) profiles=DestroyLinkedList(profiles,RelinquishMagickMemory); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (signature != GetMagickCoreSignature((const StringInfo *) NULL)) { if (profiles != (LinkedListInfo *) NULL) profiles=DestroyLinkedList(profiles,RelinquishMagickMemory); ThrowReaderException(CacheError,"IncompatibleAPI"); } if (image->montage != (char *) NULL) { register char *p; /* Image directory. */ length=MaxTextExtent; image->directory=AcquireString((char *) NULL); p=image->directory; do { *p='\0'; if ((strlen(image->directory)+MaxTextExtent) >= length) { /* Allocate more memory for the image directory. */ length<<=1; image->directory=(char *) ResizeQuantumMemory(image->directory, length+MaxTextExtent,sizeof(*image->directory)); if (image->directory == (char *) NULL) { if (profiles != (LinkedListInfo *) NULL) profiles=DestroyLinkedList(profiles,RelinquishMagickMemory); ThrowReaderException(CorruptImageError, "UnableToReadImageData"); } p=image->directory+strlen(image->directory); } c=ReadBlobByte(image); if (c == EOF) break; *p++=(char) c; } while (c != (int) '\0'); } if (profiles != (LinkedListInfo *) NULL) { const char *name; StringInfo *profile; /* Read image profile blobs. */ ResetLinkedListIterator(profiles); name=(const char *) GetNextValueInLinkedList(profiles); while (name != (const char *) NULL) { length=ReadBlobMSBLong(image); if ((MagickSizeType) length > GetBlobSize(image)) break; profile=AcquireStringInfo(length); if (profile == (StringInfo *) NULL) break; count=ReadBlob(image,length,GetStringInfoDatum(profile)); if (count != (ssize_t) length) { profile=DestroyStringInfo(profile); break; } status=SetImageProfile(image,name,profile); profile=DestroyStringInfo(profile); if (status == MagickFalse) break; name=(const char *) GetNextValueInLinkedList(profiles); } profiles=DestroyLinkedList(profiles,RelinquishMagickMemory); } depth=GetImageQuantumDepth(image,MagickFalse); if (image->storage_class == PseudoClass) { size_t packet_size; unsigned char *colormap; /* Create image colormap. */ packet_size=(size_t) (3UL*depth/8UL); if ((MagickSizeType) (packet_size*image->colors) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); image->colormap=(PixelPacket *) AcquireQuantumMemory(image->colors+1, sizeof(*image->colormap)); if (image->colormap == (PixelPacket *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->colors != 0) { /* Read image colormap from file. */ colormap=(unsigned char *) AcquireQuantumMemory(image->colors, packet_size*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,packet_size*image->colors,colormap); if (count != (ssize_t) (packet_size*image->colors)) { colormap=(unsigned char *) RelinquishMagickMemory(colormap); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } p=colormap; switch (depth) { default: colormap=(unsigned char *) RelinquishMagickMemory(colormap); ThrowReaderException(CorruptImageError, "ImageDepthNotSupported"); case 8: { unsigned char pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushCharPixel(p,&pixel); image->colormap[i].red=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].green=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].blue=ScaleCharToQuantum(pixel); } break; } case 16: { unsigned short pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleShortToQuantum(pixel); } break; } case 32: { unsigned int pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleLongToQuantum(pixel); } break; } } colormap=(unsigned char *) RelinquishMagickMemory(colormap); } } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) || (AcquireMagickResource(HeightResource,image->rows) == MagickFalse)) ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit"); /* Attach persistent pixel cache. */ status=PersistPixelCache(image,cache_filename,MagickTrue,&offset,exception); if (status == MagickFalse) { status=SetImageExtent(image,image->columns,image->rows); ThrowReaderException(CacheError,"UnableToPersistPixelCache"); } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ do { c=ReadBlobByte(image); } while ((isgraph(c) == MagickFalse) && (c != EOF)); if (c != EOF) { /* Allocate 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 (c != EOF); (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'</s>
<s>[INST] Given the following code containing errors, provide 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 *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define SkipLinesOp 0x01 #define SetColorOp 0x02 #define SkipPixelsOp 0x03 #define ByteDataOp 0x05 #define RunDataOp 0x06 #define EOFOp 0x07 #define ThrowRLEException(exception,message) \ { \ if (colormap != (unsigned char *) NULL) \ colormap=(unsigned char *) RelinquishMagickMemory(colormap); \ if (pixel_info != (MemoryInfo *) NULL) \ pixel_info=RelinquishVirtualMemory(pixel_info); \ ThrowReaderException((exception),(message)); \ } char magick[12]; Image *image; IndexPacket index; int opcode, operand, status; MagickStatusType flags; MagickSizeType number_pixels; MemoryInfo *pixel_info; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p; size_t bits_per_pixel, map_length, number_colormaps, number_planes, number_planes_filled, one, pixel_info_length; ssize_t count, offset, y; unsigned char background_color[256], *colormap, pixel, plane, *pixels; /* 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) return(DestroyImageList(image)); /* Determine if this a RLE file. */ colormap=(unsigned char *) NULL; pixel_info=(MemoryInfo *) NULL; count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 2) || (memcmp(magick,"\122\314",2) != 0)) ThrowRLEException(CorruptImageError,"ImproperImageHeader"); do { /* Read image header. */ image->page.x=(ssize_t) ReadBlobLSBShort(image); image->page.y=(ssize_t) ReadBlobLSBShort(image); image->columns=ReadBlobLSBShort(image); image->rows=ReadBlobLSBShort(image); flags=(MagickStatusType) ReadBlobByte(image); image->matte=flags & 0x04 ? MagickTrue : MagickFalse; number_planes=(size_t) ReadBlobByte(image); bits_per_pixel=(size_t) ReadBlobByte(image); number_colormaps=(size_t) ReadBlobByte(image); map_length=(unsigned char) ReadBlobByte(image); if (map_length >= 22) ThrowRLEException(CorruptImageError,"ImproperImageHeader"); if (EOFBlob(image) != MagickFalse) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); one=1; map_length=one << map_length; if ((number_planes == 0) || (number_planes == 2) || ((flags & 0x04) && ((number_planes <= 2) || number_planes > 254)) || (bits_per_pixel != 8)) ThrowRLEException(CorruptImageError,"ImproperImageHeader"); if (number_planes > 4) ThrowRLEException(CorruptImageError,"ImproperImageHeader"); if ((image->columns == 0) || (image->columns >= 32768) || (image->rows == 0) || (image->rows >= 32768)) ThrowRLEException(CorruptImageError,"ImproperImageHeader"); if (flags & 0x02) { /* No background color-- initialize to black. */ for (i=0; i < (ssize_t) number_planes; i++) background_color[i]=0; (void) ReadBlobByte(image); } else { /* Initialize background color. */ p=background_color; for (i=0; i < (ssize_t) number_planes; i++) *p++=(unsigned char) ReadBlobByte(image); } if ((number_planes & 0x01) == 0) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); if (image->matte != MagickFalse) number_planes++; number_pixels=(MagickSizeType) image->columns*image->rows; if ((GetBlobSize(image) == 0) || ((((MagickSizeType) number_pixels* number_planes*bits_per_pixel/8)/GetBlobSize(image)) > 254.0)) ThrowRLEException(CorruptImageError,"InsufficientImageDataInFile") if (((MagickSizeType) number_colormaps*map_length) > GetBlobSize(image)) ThrowRLEException(CorruptImageError,"InsufficientImageDataInFile") if (number_colormaps != 0) { /* Read image colormaps. */ colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps, 3*map_length*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowRLEException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(colormap,0,3*number_colormaps*map_length* sizeof(*colormap)); p=colormap; for (i=0; i < (ssize_t) number_colormaps; i++) for (x=0; x < (ssize_t) map_length; x++) { *p++=(unsigned char) ScaleQuantumToChar(ScaleShortToQuantum( ReadBlobLSBShort(image))); if (EOFBlob(image) != MagickFalse) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } } if ((flags & 0x08) != 0) { char *comment; size_t length; /* Read image comment. */ length=ReadBlobLSBShort(image); if (length != 0) { comment=(char *) AcquireQuantumMemory(length,sizeof(*comment)); if (comment == (char *) NULL) ThrowRLEException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,length-1,(unsigned char *) comment); if (count != (length-1)) { comment=DestroyString(comment); ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } comment[length-1]='\0'; (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); if ((length & 0x01) == 0) (void) ReadBlobByte(image); } } if (EOFBlob(image) != MagickFalse) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); 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) { if (colormap != (unsigned char *) NULL) colormap=(unsigned char *) RelinquishMagickMemory(colormap); if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Allocate RLE pixels. */ number_planes_filled=(number_planes % 2 == 0) ? number_planes : number_planes+1; if ((number_pixels*number_planes_filled) != (size_t) (number_pixels* number_planes_filled)) ThrowRLEException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info=AcquireVirtualMemory(image->columns,image->rows* MagickMax(number_planes_filled,4)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowRLEException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info_length=image->columns*image->rows* MagickMax(number_planes_filled,4); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) memset(pixels,0,pixel_info_length); if ((flags & 0x01) && !(flags & 0x02)) { ssize_t j; /* Set background color. */ p=pixels; for (i=0; i < (ssize_t) number_pixels; i++) { if (image->matte == MagickFalse) for (j=0; j < (ssize_t) number_planes; j++) *p++=background_color[j]; else { for (j=0; j < (ssize_t) (number_planes-1); j++) *p++=background_color[j]; *p++=0; /* initialize matte channel */ } } } /* Read runlength-encoded image. */ plane=0; x=0; y=0; opcode=ReadBlobByte(image); if (opcode == EOF) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } do { switch (opcode & 0x3f) { case SkipLinesOp: { operand=ReadBlobByte(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); if (opcode & 0x40) { operand=ReadBlobLSBSignedShort(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } x=0; y+=operand; break; } case SetColorOp: { operand=ReadBlobByte(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); plane=(unsigned char) operand; if (plane == 255) plane=(unsigned char) (number_planes-1); x=0; break; } case SkipPixelsOp: { operand=ReadBlobByte(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); if (opcode & 0x40) { operand=ReadBlobLSBSignedShort(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } x+=operand; break; } case ByteDataOp: { operand=ReadBlobByte(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); if (opcode & 0x40) { operand=ReadBlobLSBSignedShort(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } offset=(ssize_t) (((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane); operand++; if ((offset < 0) || ((size_t) (offset+operand*number_planes) > pixel_info_length)) ThrowRLEException(CorruptImageError,"UnableToReadImageData"); p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { pixel=(unsigned char) ReadBlobByte(image); if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } if (operand & 0x01) (void) ReadBlobByte(image); x+=operand; break; } case RunDataOp: { operand=ReadBlobByte(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); if (opcode & 0x40) { operand=ReadBlobLSBSignedShort(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } pixel=(unsigned char) ReadBlobByte(image); (void) ReadBlobByte(image); operand++; offset=(ssize_t) (((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane); if ((offset < 0) || ((size_t) (offset+operand*number_planes) > pixel_info_length)) ThrowRLEException(CorruptImageError,"UnableToReadImageData"); p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } x+=operand; break; } default: break; } opcode=ReadBlobByte(image); if (opcode == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } while (((opcode & 0x3f) != EOFOp) && (opcode != EOF)); if (number_colormaps != 0) { MagickStatusType mask; /* Apply colormap affineation to image. */ mask=(MagickStatusType) (map_length-1); p=pixels; x=(ssize_t) number_planes; if (number_colormaps == 1) for (i=0; i < (ssize_t) number_pixels; i++) { if (IsValidColormapIndex(image,(ssize_t) (*p & mask),&index,exception) == MagickFalse) break; *p=colormap[(ssize_t) index]; p++; } else if ((number_planes >= 3) && (number_colormaps >= 3)) for (i=0; i < (ssize_t) number_pixels; i++) for (x=0; x < (ssize_t) number_planes; x++) { if (IsValidColormapIndex(image,(ssize_t) (x*map_length+ (*p & mask)),&index,exception) == MagickFalse) break; *p=colormap[(ssize_t) index]; p++; } if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes)) ThrowRLEException(CorruptImageError,"UnableToReadImageData"); } /* Initialize image structure. */ if (number_planes >= 3) { /* Convert raster image to DirectClass pixel packets. */ p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleCharToQuantum(*p++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Create colormap. */ if (number_colormaps == 0) map_length=256; if (AcquireImageColormap(image,map_length) == MagickFalse) ThrowRLEException(ResourceLimitError,"MemoryAllocationFailed"); p=colormap; if (number_colormaps == 1) for (i=0; i < (ssize_t) image->colors; i++) { /* Pseudocolor. */ image->colormap[i].red=ScaleCharToQuantum((unsigned char) i); image->colormap[i].green=ScaleCharToQuantum((unsigned char) i); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i); } else if (number_colormaps > 1) for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(*p); image->colormap[i].green=ScaleCharToQuantum(*(p+map_length)); image->colormap[i].blue=ScaleCharToQuantum(*(p+map_length*2)); p++; } p=pixels; if (image->matte == MagickFalse) { /* Convert raster image to PseudoClass pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { 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; x++) SetPixelIndex(indexes+x,*p++); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); } else { /* Image has a matte channel-- promote to DirectClass. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsValidColormapIndex(image,(ssize_t) *p++,&index,exception) == MagickFalse) break; SetPixelRed(q,image->colormap[(ssize_t) index].red); if (IsValidColormapIndex(image,(ssize_t) *p++,&index,exception) == MagickFalse) break; SetPixelGreen(q,image->colormap[(ssize_t) index].green); if (IsValidColormapIndex(image,(ssize_t) *p++,&index,exception) == MagickFalse) break; SetPixelBlue(q,image->colormap[(ssize_t) index].blue); SetPixelAlpha(q,ScaleCharToQuantum(*p++)); q++; } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } image->colormap=(PixelPacket *) RelinquishMagickMemory( image->colormap); image->storage_class=DirectClass; image->colors=0; } } if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; (void) ReadBlobByte(image); count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 0) && (memcmp(magick,"\122\314",2) == 0)) { /* Allocate 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 ((count != 0) && (memcmp(magick,"\122\314",2) == 0)); (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'</s>
<s>[INST] Given the following code containing errors, provide 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 *ReadICONImage(const ImageInfo *image_info, ExceptionInfo *exception) { IconFile icon_file; IconInfo icon_info; Image *image; MagickBooleanType status; MagickSizeType extent; register IndexPacket *indexes; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; size_t bit, byte, bytes_per_line, one, scanline_pad; ssize_t count, offset, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); (void) LogMagickEvent(CoderEvent,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); } icon_file.reserved=(short) ReadBlobLSBShort(image); icon_file.resource_type=(short) ReadBlobLSBShort(image); icon_file.count=(short) ReadBlobLSBShort(image); if ((icon_file.reserved != 0) || ((icon_file.resource_type != 1) && (icon_file.resource_type != 2)) || (icon_file.count > MaxIcons)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); extent=0; for (i=0; i < icon_file.count; i++) { icon_file.directory[i].width=(unsigned char) ReadBlobByte(image); icon_file.directory[i].height=(unsigned char) ReadBlobByte(image); icon_file.directory[i].colors=(unsigned char) ReadBlobByte(image); icon_file.directory[i].reserved=(unsigned char) ReadBlobByte(image); icon_file.directory[i].planes=(unsigned short) ReadBlobLSBShort(image); icon_file.directory[i].bits_per_pixel=(unsigned short) ReadBlobLSBShort(image); icon_file.directory[i].size=ReadBlobLSBLong(image); icon_file.directory[i].offset=ReadBlobLSBLong(image); if (EOFBlob(image) != MagickFalse) break; extent=MagickMax(extent,icon_file.directory[i].size); } if ((EOFBlob(image) != MagickFalse) || (extent > GetBlobSize(image))) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); one=1; for (i=0; i < icon_file.count; i++) { /* Verify Icon identifier. */ offset=(ssize_t) SeekBlob(image,(MagickOffsetType) icon_file.directory[i].offset,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); icon_info.size=ReadBlobLSBLong(image); icon_info.width=(unsigned char) ReadBlobLSBSignedLong(image); icon_info.height=(unsigned char) (ReadBlobLSBSignedLong(image)/2); icon_info.planes=ReadBlobLSBShort(image); icon_info.bits_per_pixel=ReadBlobLSBShort(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if (((icon_info.planes == 18505) && (icon_info.bits_per_pixel == 21060)) || (icon_info.size == 0x474e5089)) { Image *icon_image; ImageInfo *read_info; size_t length; unsigned char *png; /* Icon image encoded as a compressed PNG image. */ length=icon_file.directory[i].size; if ((length < 16) || (~length < 16)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); png=(unsigned char *) AcquireQuantumMemory(length+16,sizeof(*png)); if (png == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) memcpy(png,"\211PNG\r\n\032\n\000\000\000\015",12); png[12]=(unsigned char) icon_info.planes; png[13]=(unsigned char) (icon_info.planes >> 8); png[14]=(unsigned char) icon_info.bits_per_pixel; png[15]=(unsigned char) (icon_info.bits_per_pixel >> 8); count=ReadBlob(image,length,png+16); if (count != (ssize_t) length) { png=(unsigned char *) RelinquishMagickMemory(png); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } read_info=CloneImageInfo(image_info); (void) CopyMagickString(read_info->magick,"PNG",MaxTextExtent); icon_image=BlobToImage(read_info,png,length+16,exception); read_info=DestroyImageInfo(read_info); png=(unsigned char *) RelinquishMagickMemory(png); if (icon_image == (Image *) NULL) return(DestroyImageList(image)); DestroyBlob(icon_image); icon_image->blob=ReferenceBlob(image->blob); ReplaceImageInList(&image,icon_image); icon_image->scene=i; } else { if (icon_info.bits_per_pixel > 32) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); icon_info.compression=ReadBlobLSBLong(image); icon_info.image_size=ReadBlobLSBLong(image); icon_info.x_pixels=ReadBlobLSBLong(image); icon_info.y_pixels=ReadBlobLSBLong(image); icon_info.number_colors=ReadBlobLSBLong(image); if (icon_info.number_colors > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); icon_info.colors_important=ReadBlobLSBLong(image); image->matte=MagickTrue; image->columns=(size_t) icon_file.directory[i].width; if ((ssize_t) image->columns > icon_info.width) image->columns=(size_t) icon_info.width; if (image->columns == 0) image->columns=256; image->rows=(size_t) icon_file.directory[i].height; if ((ssize_t) image->rows > icon_info.height) image->rows=(size_t) icon_info.height; if (image->rows == 0) image->rows=256; image->depth=icon_info.bits_per_pixel; if (image->depth > 16) image->depth=8; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene = %.20g",(double) i); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " size = %.20g",(double) icon_info.size); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " width = %.20g",(double) icon_file.directory[i].width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " height = %.20g",(double) icon_file.directory[i].height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " colors = %.20g",(double ) icon_info.number_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " planes = %.20g",(double) icon_info.planes); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " bpp = %.20g",(double) icon_info.bits_per_pixel); } if ((icon_info.number_colors != 0) || (icon_info.bits_per_pixel <= 16U)) { image->storage_class=PseudoClass; image->colors=icon_info.number_colors; if ((image->colors == 0) || (image->colors > 256)) image->colors=one << icon_info.bits_per_pixel; } if (image->storage_class == PseudoClass) { register ssize_t i; unsigned char *icon_colormap; /* Read Icon raster colormap. */ if (image->colors > GetBlobSize(image)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); icon_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4UL*sizeof(*icon_colormap)); if (icon_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) (4*image->colors),icon_colormap); if (count != (ssize_t) (4*image->colors)) { icon_colormap=(unsigned char *) RelinquishMagickMemory( icon_colormap); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } p=icon_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=(Quantum) ScaleCharToQuantum(*p++); image->colormap[i].green=(Quantum) ScaleCharToQuantum(*p++); image->colormap[i].red=(Quantum) ScaleCharToQuantum(*p++); p++; } icon_colormap=(unsigned char *) RelinquishMagickMemory(icon_colormap); } /* Convert Icon raster image to pixel packets. */ 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)); } bytes_per_line=(((image->columns*icon_info.bits_per_pixel)+31) & ~31) >> 3; (void) bytes_per_line; scanline_pad=((((image->columns*icon_info.bits_per_pixel)+31) & ~31)- (image->columns*icon_info.bits_per_pixel)) >> 3; switch (icon_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { 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) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < 8; bit++) SetPixelIndex(indexes+x+bit,((byte & (0x80 >> bit)) != 0 ? 0x01 : 0x00)); } if ((image->columns % 8) != 0) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < (image->columns % 8); bit++) SetPixelIndex(indexes+x+bit,((byte & (0x80 >> bit)) != 0 ? 0x01 : 0x00)); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 4: { /* Read 4-bit Icon scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { 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) { byte=(size_t) ReadBlobByte(image); SetPixelIndex(indexes+x,((byte >> 4) & 0xf)); SetPixelIndex(indexes+x+1,((byte) & 0xf)); } if ((image->columns % 2) != 0) { byte=(size_t) ReadBlobByte(image); SetPixelIndex(indexes+x,((byte >> 4) & 0xf)); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 8: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { 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; x++) { byte=(size_t) ReadBlobByte(image); SetPixelIndex(indexes+x,byte); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 16: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { 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; x++) { byte=(size_t) ReadBlobByte(image); byte|=((size_t) ReadBlobByte(image) << 8); SetPixelIndex(indexes+x,byte); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 24: case 32: { /* Convert DirectColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { 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((unsigned char) ReadBlobByte(image))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelRed(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); if (icon_info.bits_per_pixel == 32) SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); q++; } if (icon_info.bits_per_pixel == 24) for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if ((image_info->ping == MagickFalse) && (icon_info.bits_per_pixel <= 16)) (void) SyncImage(image); if (icon_info.bits_per_pixel != 32) { /* Read the ICON alpha mask. */ image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < 8; bit++) SetPixelOpacity(q+x+bit,(((byte & (0x80 >> bit)) != 0) ? TransparentOpacity : OpaqueOpacity)); } if ((image->columns % 8) != 0) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < (image->columns % 8); bit++) SetPixelOpacity(q+x+bit,(((byte & (0x80 >> bit)) != 0) ? TransparentOpacity : OpaqueOpacity)); } if ((image->columns % 32) != 0) for (x=0; x < (ssize_t) ((32-(image->columns % 32))/8); x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (i < (ssize_t) (icon_file.count-1)) { /* Allocate 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; } } (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'</s>
<s>[INST] Given the following code containing errors, provide 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 *ReadPIXImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; IndexPacket index; MagickBooleanType status; Quantum blue, green, red; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; size_t bits_per_pixel, height, length, width; ssize_t y; /* 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 PIX image. */ width=ReadBlobMSBShort(image); height=ReadBlobMSBShort(image); (void) ReadBlobMSBShort(image); /* x-offset */ (void) ReadBlobMSBShort(image); /* y-offset */ bits_per_pixel=ReadBlobMSBShort(image); if ((width == 0UL) || (height == 0UL) || ((bits_per_pixel != 8) && (bits_per_pixel != 24))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { /* Initialize image structure. */ image->columns=width; image->rows=height; if (bits_per_pixel == 8) if (AcquireImageColormap(image,256) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); 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)); } status=ResetImagePixels(image,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Convert PIX raster image to pixel packets. */ red=(Quantum) 0; green=(Quantum) 0; blue=(Quantum) 0; index=(IndexPacket) 0; length=0; for (y=0; y < (ssize_t) image->rows; y++) { 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; x++) { if (length == 0) { int c; c=ReadBlobByte(image); if ((c == 0) || (c == EOF)) break; length=(size_t) c; if (bits_per_pixel == 8) index=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); else { blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); } } if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x,index); SetPixelBlue(q,blue); SetPixelGreen(q,green); SetPixelRed(q,red); length--; q++; } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (image->storage_class == PseudoClass) (void) SyncImage(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; width=ReadBlobMSBLong(image); height=ReadBlobMSBLong(image); (void) ReadBlobMSBShort(image); (void) ReadBlobMSBShort(image); bits_per_pixel=ReadBlobMSBShort(image); status=(width != 0UL) && (height == 0UL) && ((bits_per_pixel == 8) || (bits_per_pixel == 24)) ? MagickTrue : MagickFalse; if (status != MagickFalse) { /* Allocate 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 (status != MagickFalse); (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'</s>