text
stringlengths
478
227k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int fpm_request_is_idle(struct fpm_child_s *child) /* {{{ */ { struct fpm_scoreboard_proc_s *proc; /* no need in atomicity here */ proc = fpm_scoreboard_proc_get(child->wp->scoreboard, child->scoreboard_i); if (!proc) { return 0; } return proc->request_stage == FPM_REQUEST_ACCEPTING; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix bug #81026 (PHP-FPM oob R/W in root process leading to priv escalation) The main change is to store scoreboard procs directly to the variable sized array rather than indirectly through the pointer. Signed-off-by: Stanislav Malyshev <stas@php.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int selinux_msg_queue_msgrcv(struct kern_ipc_perm *msq, struct msg_msg *msg, struct task_struct *target, long type, int mode) { struct ipc_security_struct *isec; struct msg_security_struct *msec; struct common_audit_data ad; u32 sid = task_sid_subj(target); int rc; isec = selinux_ipc(msq); msec = selinux_msg_msg(msg); ad.type = LSM_AUDIT_DATA_IPC; ad.u.ipc_id = msq->key; rc = avc_has_perm(&selinux_state, sid, isec->sid, SECCLASS_MSGQ, MSGQ__READ, &ad); if (!rc) rc = avc_has_perm(&selinux_state, sid, msec->sid, SECCLASS_MSG, MSG__RECEIVE, &ad); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'selinux,smack: fix subjective/objective credential use mixups Jann Horn reported a problem with commit eb1231f73c4d ("selinux: clarify task subjective and objective credentials") where some LSM hooks were attempting to access the subjective credentials of a task other than the current task. Generally speaking, it is not safe to access another task's subjective credentials and doing so can cause a number of problems. Further, while looking into the problem, I realized that Smack was suffering from a similar problem brought about by a similar commit 1fb057dcde11 ("smack: differentiate between subjective and objective task credentials"). This patch addresses this problem by restoring the use of the task's objective credentials in those cases where the task is other than the current executing task. Not only does this resolve the problem reported by Jann, it is arguably the correct thing to do in these cases. Cc: stable@vger.kernel.org Fixes: eb1231f73c4d ("selinux: clarify task subjective and objective credentials") Fixes: 1fb057dcde11 ("smack: differentiate between subjective and objective task credentials") Reported-by: Jann Horn <jannh@google.com> Acked-by: Eric W. Biederman <ebiederm@xmission.com> Acked-by: Casey Schaufler <casey@schaufler-ca.com> Signed-off-by: Paul Moore <paul@paul-moore.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void chrc_read_cb(struct gatt_db_attribute *attrib, unsigned int id, uint16_t offset, uint8_t opcode, struct bt_att *att, void *user_data) { struct external_chrc *chrc = user_data; struct btd_device *device; if (chrc->attrib != attrib) { error("Read callback called with incorrect attribute"); goto fail; } device = att_get_device(att); if (!device) { error("Unable to find device object"); goto fail; } if (send_read(device, attrib, chrc->proxy, chrc->pending_reads, id, offset, bt_att_get_link_type(att))) return; fail: gatt_db_attribute_read_result(attrib, id, BT_ATT_ERROR_UNLIKELY, NULL, 0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'gatt: Fix not cleaning up when disconnected There is a current use after free possible on a gatt server if a client disconnects while a WriteValue call is being processed with dbus. This patch includes the addition of a pending disconnect callback to handle cleanup better if a disconnect occurs during a write, an acquire write or read operation using bt_att_register_disconnect with the cb.'</s>
<s>[INST] Given the following code containing errors, provide 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 scsi_disk_check_mode_select(SCSIDiskState *s, int page, uint8_t *inbuf, int inlen) { uint8_t mode_current[SCSI_MAX_MODE_LEN]; uint8_t mode_changeable[SCSI_MAX_MODE_LEN]; uint8_t *p; int len, expected_len, changeable_len, i; /* The input buffer does not include the page header, so it is * off by 2 bytes. */ expected_len = inlen + 2; if (expected_len > SCSI_MAX_MODE_LEN) { return -1; } p = mode_current; memset(mode_current, 0, inlen + 2); len = mode_sense_page(s, page, &p, 0); if (len < 0 || len != expected_len) { return -1; } p = mode_changeable; memset(mode_changeable, 0, inlen + 2); changeable_len = mode_sense_page(s, page, &p, 1); assert(changeable_len == len); /* Check that unchangeable bits are the same as what MODE SENSE * would return. */ for (i = 2; i < len; i++) { if (((mode_current[i] ^ inbuf[i - 2]) & ~mode_changeable[i]) != 0) { return -1; } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-193'], 'message': 'hw/scsi/scsi-disk: MODE_PAGE_ALLS not allowed in MODE SELECT commands This avoids an off-by-one read of 'mode_sense_valid' buffer in hw/scsi/scsi-disk.c:mode_sense_page(). Fixes: CVE-2021-3930 Cc: qemu-stable@nongnu.org Reported-by: Alexander Bulekov <alxndr@bu.edu> Fixes: a8f4bbe2900 ("scsi-disk: store valid mode pages in a table") Fixes: #546 Reported-by: Qiuhao Li <Qiuhao.Li@outlook.com> Signed-off-by: Mauro Matteo Cascella <mcascell@redhat.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: set_fflags_platform(struct archive_write_disk *a, int fd, const char *name, mode_t mode, unsigned long set, unsigned long clear) { int ret; int myfd = fd; int newflags, oldflags; /* * Linux has no define for the flags that are only settable by * the root user. This code may seem a little complex, but * there seem to be some Linux systems that lack these * defines. (?) The code below degrades reasonably gracefully * if sf_mask is incomplete. */ const int sf_mask = 0 #if defined(FS_IMMUTABLE_FL) | FS_IMMUTABLE_FL #elif defined(EXT2_IMMUTABLE_FL) | EXT2_IMMUTABLE_FL #endif #if defined(FS_APPEND_FL) | FS_APPEND_FL #elif defined(EXT2_APPEND_FL) | EXT2_APPEND_FL #endif #if defined(FS_JOURNAL_DATA_FL) | FS_JOURNAL_DATA_FL #endif ; if (set == 0 && clear == 0) return (ARCHIVE_OK); /* Only regular files and dirs can have flags. */ if (!S_ISREG(mode) && !S_ISDIR(mode)) return (ARCHIVE_OK); /* If we weren't given an fd, open it ourselves. */ if (myfd < 0) { myfd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY | O_CLOEXEC); __archive_ensure_cloexec_flag(myfd); } if (myfd < 0) return (ARCHIVE_OK); /* * XXX As above, this would be way simpler if we didn't have * to read the current flags from disk. XXX */ ret = ARCHIVE_OK; /* Read the current file flags. */ if (ioctl(myfd, #ifdef FS_IOC_GETFLAGS FS_IOC_GETFLAGS, #else EXT2_IOC_GETFLAGS, #endif &oldflags) < 0) goto fail; /* Try setting the flags as given. */ newflags = (oldflags & ~clear) | set; if (ioctl(myfd, #ifdef FS_IOC_SETFLAGS FS_IOC_SETFLAGS, #else EXT2_IOC_SETFLAGS, #endif &newflags) >= 0) goto cleanup; if (errno != EPERM) goto fail; /* If we couldn't set all the flags, try again with a subset. */ newflags &= ~sf_mask; oldflags &= sf_mask; newflags |= oldflags; if (ioctl(myfd, #ifdef FS_IOC_SETFLAGS FS_IOC_SETFLAGS, #else EXT2_IOC_SETFLAGS, #endif &newflags) >= 0) goto cleanup; /* We couldn't set the flags, so report the failure. */ fail: archive_set_error(&a->archive, errno, "Failed to set file flags"); ret = ARCHIVE_WARN; cleanup: if (fd < 0) close(myfd); return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'Never follow symlinks when setting file flags on Linux When opening a file descriptor to set file flags on linux, ensure no symbolic links are followed. This fixes the case when an archive contains a directory entry followed by a symlink entry with the same path. The fixup code would modify file flags of the symlink target.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: set_richacl(struct archive *a, int fd, const char *name, struct archive_acl *abstract_acl, __LA_MODE_T mode, int ae_requested_type, const char *tname) { int ae_type, ae_permset, ae_tag, ae_id; uid_t ae_uid; gid_t ae_gid; const char *ae_name; int entries; int i; int ret; int e = 0; struct richacl *richacl = NULL; struct richace *richace; ret = ARCHIVE_OK; entries = archive_acl_reset(abstract_acl, ae_requested_type); if (entries == 0) return (ARCHIVE_OK); if (ae_requested_type != ARCHIVE_ENTRY_ACL_TYPE_NFS4) { errno = ENOENT; archive_set_error(a, errno, "Unsupported ACL type"); return (ARCHIVE_FAILED); } richacl = richacl_alloc(entries); if (richacl == NULL) { archive_set_error(a, errno, "Failed to initialize RichACL working storage"); return (ARCHIVE_FAILED); } e = 0; while (archive_acl_next(a, abstract_acl, ae_requested_type, &ae_type, &ae_permset, &ae_tag, &ae_id, &ae_name) == ARCHIVE_OK) { richace = &(richacl->a_entries[e]); richace->e_flags = 0; richace->e_mask = 0; switch (ae_tag) { case ARCHIVE_ENTRY_ACL_USER: ae_uid = archive_write_disk_uid(a, ae_name, ae_id); richace->e_id = ae_uid; break; case ARCHIVE_ENTRY_ACL_GROUP: ae_gid = archive_write_disk_gid(a, ae_name, ae_id); richace->e_id = ae_gid; richace->e_flags |= RICHACE_IDENTIFIER_GROUP; break; case ARCHIVE_ENTRY_ACL_USER_OBJ: richace->e_flags |= RICHACE_SPECIAL_WHO; richace->e_id = RICHACE_OWNER_SPECIAL_ID; break; case ARCHIVE_ENTRY_ACL_GROUP_OBJ: richace->e_flags |= RICHACE_SPECIAL_WHO; richace->e_id = RICHACE_GROUP_SPECIAL_ID; break; case ARCHIVE_ENTRY_ACL_EVERYONE: richace->e_flags |= RICHACE_SPECIAL_WHO; richace->e_id = RICHACE_EVERYONE_SPECIAL_ID; break; default: archive_set_error(a, ARCHIVE_ERRNO_MISC, "Unsupported ACL tag"); ret = ARCHIVE_FAILED; goto exit_free; } switch (ae_type) { case ARCHIVE_ENTRY_ACL_TYPE_ALLOW: richace->e_type = RICHACE_ACCESS_ALLOWED_ACE_TYPE; break; case ARCHIVE_ENTRY_ACL_TYPE_DENY: richace->e_type = RICHACE_ACCESS_DENIED_ACE_TYPE; break; case ARCHIVE_ENTRY_ACL_TYPE_AUDIT: case ARCHIVE_ENTRY_ACL_TYPE_ALARM: break; default: archive_set_error(a, ARCHIVE_ERRNO_MISC, "Unsupported ACL entry type"); ret = ARCHIVE_FAILED; goto exit_free; } for (i = 0; i < acl_nfs4_perm_map_size; ++i) { if (ae_permset & acl_nfs4_perm_map[i].a_perm) richace->e_mask |= acl_nfs4_perm_map[i].p_perm; } for (i = 0; i < acl_nfs4_flag_map_size; ++i) { if (ae_permset & acl_nfs4_flag_map[i].a_perm) richace->e_flags |= acl_nfs4_flag_map[i].p_perm; } e++; } /* Fill RichACL masks */ _richacl_mode_to_masks(richacl, mode); if (fd >= 0) { if (richacl_set_fd(fd, richacl) == 0) ret = ARCHIVE_OK; else { if (errno == EOPNOTSUPP) { /* Filesystem doesn't support ACLs */ ret = ARCHIVE_OK; } else { archive_set_error(a, errno, "Failed to set richacl on fd: %s", tname); ret = ARCHIVE_WARN; } } } else if (richacl_set_file(name, richacl) != 0) { if (errno == EOPNOTSUPP) { /* Filesystem doesn't support ACLs */ ret = ARCHIVE_OK; } else { archive_set_error(a, errno, "Failed to set richacl: %s", tname); ret = ARCHIVE_WARN; } } exit_free: richacl_free(richacl); return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'Fix handling of symbolic link ACLs On Linux ACLs on symbolic links are not supported. We must avoid calling acl_set_file() on symbolic links as their targets are modified instead. While here, do not try to set default ACLs on non-directories. Fixes #1565'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static char *get_data(struct libmnt_fs *fs, int num) { char *str = NULL; const char *t = NULL, *v = NULL; int col_id = get_column_id(num); switch (col_id) { case COL_SOURCES: /* print all devices with the same tag (LABEL, UUID) */ if ((flags & FL_EVALUATE) && mnt_fs_get_tag(fs, &t, &v) == 0) { blkid_dev_iterate iter; blkid_dev dev; blkid_cache cache = NULL; struct ul_buffer buf = UL_INIT_BUFFER; int i = 0; if (blkid_get_cache(&cache, NULL) < 0) break; blkid_probe_all(cache); iter = blkid_dev_iterate_begin(cache); blkid_dev_set_search(iter, t, v); while (blkid_dev_next(iter, &dev) == 0) { dev = blkid_verify(cache, dev); if (!dev) continue; if (i != 0) ul_buffer_append_data(&buf, "\n", 1); ul_buffer_append_string(&buf, blkid_dev_devname(dev)); i++; } blkid_dev_iterate_end(iter); str = ul_buffer_get_data(&buf, NULL, NULL); break; } /* fallthrough */ case COL_SOURCE: { const char *root = mnt_fs_get_root(fs); const char *spec = mnt_fs_get_srcpath(fs); char *cn = NULL; if (spec && (flags & FL_CANONICALIZE)) spec = cn = mnt_resolve_path(spec, cache); if (!spec) { spec = mnt_fs_get_source(fs); if (spec && (flags & FL_EVALUATE)) spec = cn = mnt_resolve_spec(spec, cache); } if (root && spec && !(flags & FL_NOFSROOT) && strcmp(root, "/") != 0) xasprintf(&str, "%s[%s]", spec, root); else if (spec) str = xstrdup(spec); if (!cache) free(cn); break; } case COL_TARGET: if (mnt_fs_get_target(fs)) str = xstrdup(mnt_fs_get_target(fs)); break; case COL_FSTYPE: if (mnt_fs_get_fstype(fs)) str = xstrdup(mnt_fs_get_fstype(fs)); break; case COL_OPTIONS: if (mnt_fs_get_options(fs)) str = xstrdup(mnt_fs_get_options(fs)); break; case COL_VFS_OPTIONS: if (flags & FL_VFS_ALL) str = mnt_fs_get_vfs_options_all(fs); else if (mnt_fs_get_vfs_options(fs)) str = xstrdup(mnt_fs_get_vfs_options(fs)); break; case COL_FS_OPTIONS: if (mnt_fs_get_fs_options(fs)) str = xstrdup(mnt_fs_get_fs_options(fs)); break; case COL_OPT_FIELDS: if (mnt_fs_get_optional_fields(fs)) str = xstrdup(mnt_fs_get_optional_fields(fs)); break; case COL_UUID: str = get_tag(fs, "UUID", col_id); break; case COL_PARTUUID: str = get_tag(fs, "PARTUUID", col_id); break; case COL_LABEL: str = get_tag(fs, "LABEL", col_id); break; case COL_PARTLABEL: str = get_tag(fs, "PARTLABEL", col_id); break; case COL_MAJMIN: { dev_t devno = mnt_fs_get_devno(fs); if (!devno) break; if ((flags & FL_RAW) || (flags & FL_EXPORT) || (flags & FL_JSON)) xasprintf(&str, "%u:%u", major(devno), minor(devno)); else xasprintf(&str, "%3u:%-3u", major(devno), minor(devno)); break; } case COL_SIZE: case COL_AVAIL: case COL_USED: case COL_USEPERC: str = get_vfs_attr(fs, col_id); break; case COL_FSROOT: if (mnt_fs_get_root(fs)) str = xstrdup(mnt_fs_get_root(fs)); break; case COL_TID: if (mnt_fs_get_tid(fs)) xasprintf(&str, "%d", mnt_fs_get_tid(fs)); break; case COL_ID: if (mnt_fs_get_id(fs)) xasprintf(&str, "%d", mnt_fs_get_id(fs)); break; case COL_PARENT: if (mnt_fs_get_parent_id(fs)) xasprintf(&str, "%d", mnt_fs_get_parent_id(fs)); break; case COL_PROPAGATION: if (mnt_fs_is_kernel(fs)) { unsigned long fl = 0; char *n = NULL; if (mnt_fs_get_propagation(fs, &fl) != 0) break; n = xstrdup((fl & MS_SHARED) ? "shared" : "private"); if (fl & MS_SLAVE) { xasprintf(&str, "%s,slave", n); free(n); n = str; } if (fl & MS_UNBINDABLE) { xasprintf(&str, "%s,unbindable", n); free(n); n = str; } str = n; } break; case COL_FREQ: if (!mnt_fs_is_kernel(fs)) xasprintf(&str, "%d", mnt_fs_get_freq(fs)); break; case COL_PASSNO: if (!mnt_fs_is_kernel(fs)) xasprintf(&str, "%d", mnt_fs_get_passno(fs)); break; case COL_DELETED: str = xstrdup(mnt_fs_is_deleted(fs) ? "1" : "0"); break; default: break; } return str; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-552', 'CWE-703'], 'message': 'libmount: remove support for deleted mount table entries The "(deleted)" suffix has been originally used by kernel for deleted mountpoints. Since kernel commit 9d4d65748a5ca26ea8650e50ba521295549bf4e3 (Dec 2014) kernel does not use this suffix for mount stuff in /proc at all. Let's remove this support from libmount too. Signed-off-by: Karel Zak <kzak@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: get_visual_text( cmdarg_T *cap, char_u **pp, // return: start of selected text int *lenp) // return: length of selected text { if (VIsual_mode != 'V') unadjust_for_sel(); if (VIsual.lnum != curwin->w_cursor.lnum) { if (cap != NULL) clearopbeep(cap->oap); return FAIL; } if (VIsual_mode == 'V') { *pp = ml_get_curline(); *lenp = (int)STRLEN(*pp); } else { if (LT_POS(curwin->w_cursor, VIsual)) { *pp = ml_get_pos(&curwin->w_cursor); *lenp = VIsual.col - curwin->w_cursor.col + 1; } else { *pp = ml_get_pos(&VIsual); *lenp = curwin->w_cursor.col - VIsual.col + 1; } if (has_mbyte) // Correct the length to include the whole last character. *lenp += (*mb_ptr2len)(*pp + (*lenp - 1)) - 1; } reset_VIsual_and_resel(); return OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-122'], 'message': 'patch 8.2.3611: crash when using CTRL-W f without finding a file name Problem: Crash when using CTRL-W f without finding a file name. Solution: Bail out when the file name length is zero.'</s>
<s>[INST] Given the following code containing errors, provide 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 bpf_map_is_rdonly(const struct bpf_map *map) { return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-367'], 'message': 'bpf: Fix toctou on read-only map's constant scalar tracking Commit a23740ec43ba ("bpf: Track contents of read-only maps as scalars") is checking whether maps are read-only both from BPF program side and user space side, and then, given their content is constant, reading out their data via map->ops->map_direct_value_addr() which is then subsequently used as known scalar value for the register, that is, it is marked as __mark_reg_known() with the read value at verification time. Before a23740ec43ba, the register content was marked as an unknown scalar so the verifier could not make any assumptions about the map content. The current implementation however is prone to a TOCTOU race, meaning, the value read as known scalar for the register is not guaranteed to be exactly the same at a later point when the program is executed, and as such, the prior made assumptions of the verifier with regards to the program will be invalid which can cause issues such as OOB access, etc. While the BPF_F_RDONLY_PROG map flag is always fixed and required to be specified at map creation time, the map->frozen property is initially set to false for the map given the map value needs to be populated, e.g. for global data sections. Once complete, the loader "freezes" the map from user space such that no subsequent updates/deletes are possible anymore. For the rest of the lifetime of the map, this freeze one-time trigger cannot be undone anymore after a successful BPF_MAP_FREEZE cmd return. Meaning, any new BPF_* cmd calls which would update/delete map entries will be rejected with -EPERM since map_get_sys_perms() removes the FMODE_CAN_WRITE permission. This also means that pending update/delete map entries must still complete before this guarantee is given. This corner case is not an issue for loaders since they create and prepare such program private map in successive steps. However, a malicious user is able to trigger this TOCTOU race in two different ways: i) via userfaultfd, and ii) via batched updates. For i) userfaultfd is used to expand the competition interval, so that map_update_elem() can modify the contents of the map after map_freeze() and bpf_prog_load() were executed. This works, because userfaultfd halts the parallel thread which triggered a map_update_elem() at the time where we copy key/value from the user buffer and this already passed the FMODE_CAN_WRITE capability test given at that time the map was not "frozen". Then, the main thread performs the map_freeze() and bpf_prog_load(), and once that had completed successfully, the other thread is woken up to complete the pending map_update_elem() which then changes the map content. For ii) the idea of the batched update is similar, meaning, when there are a large number of updates to be processed, it can increase the competition interval between the two. It is therefore possible in practice to modify the contents of the map after executing map_freeze() and bpf_prog_load(). One way to fix both i) and ii) at the same time is to expand the use of the map's map->writecnt. The latter was introduced in fc9702273e2e ("bpf: Add mmap() support for BPF_MAP_TYPE_ARRAY") and further refined in 1f6cb19be2e2 ("bpf: Prevent re-mmap()'ing BPF map as writable for initially r/o mapping") with the rationale to make a writable mmap()'ing of a map mutually exclusive with read-only freezing. The counter indicates writable mmap() mappings and then prevents/fails the freeze operation. Its semantics can be expanded beyond just mmap() by generally indicating ongoing write phases. This would essentially span any parallel regular and batched flavor of update/delete operation and then also have map_freeze() fail with -EBUSY. For the check_mem_access() in the verifier we expand upon the bpf_map_is_rdonly() check ensuring that all last pending writes have completed via bpf_map_write_active() test. Once the map->frozen is set and bpf_map_write_active() indicates a map->writecnt of 0 only then we are really guaranteed to use the map's data as known constants. For map->frozen being set and pending writes in process of still being completed we fall back to marking that register as unknown scalar so we don't end up making assumptions about it. With this, both TOCTOU reproducers from i) and ii) are fixed. Note that the map->writecnt has been converted into a atomic64 in the fix in order to avoid a double freeze_mutex mutex_{un,}lock() pair when updating map->writecnt in the various map update/delete BPF_* cmd flavors. Spanning the freeze_mutex over entire map update/delete operations in syscall side would not be possible due to then causing everything to be serialized. Similarly, something like synchronize_rcu() after setting map->frozen to wait for update/deletes to complete is not possible either since it would also have to span the user copy which can sleep. On the libbpf side, this won't break d66562fba1ce ("libbpf: Add BPF object skeleton support") as the anonymous mmap()-ed "map initialization image" is remapped as a BPF map-backed mmap()-ed memory where for .rodata it's non-writable. Fixes: a23740ec43ba ("bpf: Track contents of read-only maps as scalars") Reported-by: w1tcher.bupt@gmail.com Signed-off-by: Daniel Borkmann <daniel@iogearbox.net> Acked-by: Andrii Nakryiko <andrii@kernel.org> Signed-off-by: Alexei Starovoitov <ast@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: find_help_tags( char_u *arg, int *num_matches, char_u ***matches, int keep_lang) { char_u *s, *d; int i; // Specific tags that either have a specific replacement or won't go // through the generic rules. static char *(except_tbl[][2]) = { {"*", "star"}, {"g*", "gstar"}, {"[*", "[star"}, {"]*", "]star"}, {":*", ":star"}, {"/*", "/star"}, {"/\\*", "/\\\\star"}, {"\"*", "quotestar"}, {"**", "starstar"}, {"cpo-*", "cpo-star"}, {"/\\(\\)", "/\\\\(\\\\)"}, {"/\\%(\\)", "/\\\\%(\\\\)"}, {"?", "?"}, {"??", "??"}, {":?", ":?"}, {"?<CR>", "?<CR>"}, {"g?", "g?"}, {"g?g?", "g?g?"}, {"g??", "g??"}, {"-?", "-?"}, {"q?", "q?"}, {"v_g?", "v_g?"}, {"/\\?", "/\\\\?"}, {"/\\z(\\)", "/\\\\z(\\\\)"}, {"\\=", "\\\\="}, {":s\\=", ":s\\\\="}, {"[count]", "\\[count]"}, {"[quotex]", "\\[quotex]"}, {"[range]", "\\[range]"}, {":[range]", ":\\[range]"}, {"[pattern]", "\\[pattern]"}, {"\\|", "\\\\bar"}, {"\\%$", "/\\\\%\\$"}, {"s/\\~", "s/\\\\\\~"}, {"s/\\U", "s/\\\\U"}, {"s/\\L", "s/\\\\L"}, {"s/\\1", "s/\\\\1"}, {"s/\\2", "s/\\\\2"}, {"s/\\3", "s/\\\\3"}, {"s/\\9", "s/\\\\9"}, {NULL, NULL} }; static char *(expr_table[]) = {"!=?", "!~?", "<=?", "<?", "==?", "=~?", ">=?", ">?", "is?", "isnot?"}; int flags; d = IObuff; // assume IObuff is long enough! d[0] = NUL; if (STRNICMP(arg, "expr-", 5) == 0) { // When the string starting with "expr-" and containing '?' and matches // the table, it is taken literally (but ~ is escaped). Otherwise '?' // is recognized as a wildcard. for (i = (int)ARRAY_LENGTH(expr_table); --i >= 0; ) if (STRCMP(arg + 5, expr_table[i]) == 0) { int si = 0, di = 0; for (;;) { if (arg[si] == '~') d[di++] = '\\'; d[di++] = arg[si]; if (arg[si] == NUL) break; ++si; } break; } } else { // Recognize a few exceptions to the rule. Some strings that contain // '*'are changed to "star", otherwise '*' is recognized as a wildcard. for (i = 0; except_tbl[i][0] != NULL; ++i) if (STRCMP(arg, except_tbl[i][0]) == 0) { STRCPY(d, except_tbl[i][1]); break; } } if (d[0] == NUL) // no match in table { // Replace "\S" with "/\\S", etc. Otherwise every tag is matched. // Also replace "\%^" and "\%(", they match every tag too. // Also "\zs", "\z1", etc. // Also "\@<", "\@=", "\@<=", etc. // And also "\_$" and "\_^". if (arg[0] == '\\' && ((arg[1] != NUL && arg[2] == NUL) || (vim_strchr((char_u *)"%_z@", arg[1]) != NULL && arg[2] != NUL))) { STRCPY(d, "/\\\\"); STRCPY(d + 3, arg + 1); // Check for "/\\_$", should be "/\\_\$" if (d[3] == '_' && d[4] == '$') STRCPY(d + 4, "\\$"); } else { // Replace: // "[:...:]" with "\[:...:]" // "[++...]" with "\[++...]" // "\{" with "\\{" -- matching "} \}" if ((arg[0] == '[' && (arg[1] == ':' || (arg[1] == '+' && arg[2] == '+'))) || (arg[0] == '\\' && arg[1] == '{')) *d++ = '\\'; // If tag starts with "('", skip the "(". Fixes CTRL-] on ('option'. if (*arg == '(' && arg[1] == '\'') arg++; for (s = arg; *s; ++s) { // Replace "|" with "bar" and '"' with "quote" to match the name of // the tags for these commands. // Replace "*" with ".*" and "?" with "." to match command line // completion. // Insert a backslash before '~', '$' and '.' to avoid their // special meaning. if (d - IObuff > IOSIZE - 10) // getting too long!? break; switch (*s) { case '|': STRCPY(d, "bar"); d += 3; continue; case '"': STRCPY(d, "quote"); d += 5; continue; case '*': *d++ = '.'; break; case '?': *d++ = '.'; continue; case '$': case '.': case '~': *d++ = '\\'; break; } // Replace "^x" by "CTRL-X". Don't do this for "^_" to make // ":help i_^_CTRL-D" work. // Insert '-' before and after "CTRL-X" when applicable. if (*s < ' ' || (*s == '^' && s[1] && (ASCII_ISALPHA(s[1]) || vim_strchr((char_u *)"?@[\\]^", s[1]) != NULL))) { if (d > IObuff && d[-1] != '_' && d[-1] != '\\') *d++ = '_'; // prepend a '_' to make x_CTRL-x STRCPY(d, "CTRL-"); d += 5; if (*s < ' ') { #ifdef EBCDIC *d++ = CtrlChar(*s); #else *d++ = *s + '@'; #endif if (d[-1] == '\\') *d++ = '\\'; // double a backslash } else *d++ = *++s; if (s[1] != NUL && s[1] != '_') *d++ = '_'; // append a '_' continue; } else if (*s == '^') // "^" or "CTRL-^" or "^_" *d++ = '\\'; // Insert a backslash before a backslash after a slash, for search // pattern tags: "/\|" --> "/\\|". else if (s[0] == '\\' && s[1] != '\\' && *arg == '/' && s == arg + 1) *d++ = '\\'; // "CTRL-\_" -> "CTRL-\\_" to avoid the special meaning of "\_" in // "CTRL-\_CTRL-N" if (STRNICMP(s, "CTRL-\\_", 7) == 0) { STRCPY(d, "CTRL-\\\\"); d += 7; s += 6; } *d++ = *s; // If tag contains "({" or "([", tag terminates at the "(". // This is for help on functions, e.g.: abs({expr}). if (*s == '(' && (s[1] == '{' || s[1] =='[')) break; // If tag starts with ', toss everything after a second '. Fixes // CTRL-] on 'option'. (would include the trailing '.'). if (*s == '\'' && s > arg && *arg == '\'') break; // Also '{' and '}'. if (*s == '}' && s > arg && *arg == '{') break; } *d = NUL; if (*IObuff == '`') { if (d > IObuff + 2 && d[-1] == '`') { // remove the backticks from `command` mch_memmove(IObuff, IObuff + 1, STRLEN(IObuff)); d[-2] = NUL; } else if (d > IObuff + 3 && d[-2] == '`' && d[-1] == ',') { // remove the backticks and comma from `command`, mch_memmove(IObuff, IObuff + 1, STRLEN(IObuff)); d[-3] = NUL; } else if (d > IObuff + 4 && d[-3] == '`' && d[-2] == '\\' && d[-1] == '.') { // remove the backticks and dot from `command`\. mch_memmove(IObuff, IObuff + 1, STRLEN(IObuff)); d[-4] = NUL; } } } } *matches = (char_u **)""; *num_matches = 0; flags = TAG_HELP | TAG_REGEXP | TAG_NAMES | TAG_VERBOSE | TAG_NO_TAGFUNC; if (keep_lang) flags |= TAG_KEEP_LANG; if (find_tags(IObuff, num_matches, matches, flags, (int)MAXCOL, NULL) == OK && *num_matches > 0) { // Sort the matches found on the heuristic number that is after the // tag name. qsort((void *)*matches, (size_t)*num_matches, sizeof(char_u *), help_compare); // Delete more than TAG_MANY to reduce the size of the listing. while (*num_matches > TAG_MANY) vim_free((*matches)[--*num_matches]); } return OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-122', 'CWE-787'], 'message': 'patch 8.2.3669: buffer overflow with long help argument Problem: Buffer overflow with long help argument. Solution: Use snprintf().'</s>
<s>[INST] Given the following code containing errors, provide 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 kvm_xen_shared_info_init(struct kvm *kvm, gfn_t gfn) { struct gfn_to_pfn_cache *gpc = &kvm->arch.xen.shinfo_cache; gpa_t gpa = gfn_to_gpa(gfn); int wc_ofs, sec_hi_ofs; int ret = 0; int idx = srcu_read_lock(&kvm->srcu); if (gfn == GPA_INVALID) { kvm_gfn_to_pfn_cache_destroy(kvm, gpc); goto out; } ret = kvm_gfn_to_pfn_cache_init(kvm, gpc, NULL, false, true, gpa, PAGE_SIZE, false); if (ret) goto out; /* Paranoia checks on the 32-bit struct layout */ BUILD_BUG_ON(offsetof(struct compat_shared_info, wc) != 0x900); BUILD_BUG_ON(offsetof(struct compat_shared_info, arch.wc_sec_hi) != 0x924); BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0); /* 32-bit location by default */ wc_ofs = offsetof(struct compat_shared_info, wc); sec_hi_ofs = offsetof(struct compat_shared_info, arch.wc_sec_hi); #ifdef CONFIG_X86_64 /* Paranoia checks on the 64-bit struct layout */ BUILD_BUG_ON(offsetof(struct shared_info, wc) != 0xc00); BUILD_BUG_ON(offsetof(struct shared_info, wc_sec_hi) != 0xc0c); if (kvm->arch.xen.long_mode) { wc_ofs = offsetof(struct shared_info, wc); sec_hi_ofs = offsetof(struct shared_info, wc_sec_hi); } #endif kvm_write_wall_clock(kvm, gpa + wc_ofs, sec_hi_ofs - wc_ofs); kvm_make_all_cpus_request(kvm, KVM_REQ_MASTERCLOCK_UPDATE); out: srcu_read_unlock(&kvm->srcu, idx); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'KVM: x86: Fix wall clock writes in Xen shared_info not to mark page dirty When dirty ring logging is enabled, any dirty logging without an active vCPU context will cause a kernel oops. But we've already declared that the shared_info page doesn't get dirty tracking anyway, since it would be kind of insane to mark it dirty every time we deliver an event channel interrupt. Userspace is supposed to just assume it's always dirty any time a vCPU can run or event channels are routed. So stop using the generic kvm_write_wall_clock() and just write directly through the gfn_to_pfn_cache that we already have set up. We can make kvm_write_wall_clock() static in x86.c again now, but let's not remove the 'sec_hi_ofs' argument even though it's not used yet. At some point we *will* want to use that for KVM guests too. Fixes: 629b5348841a ("KVM: x86/xen: update wallclock region") Reported-by: butt3rflyh4ck <butterflyhuangxx@gmail.com> Signed-off-by: David Woodhouse <dwmw@amazon.co.uk> Message-Id: <20211210163625.2886-6-dwmw2@infradead.org> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int LUKS2_config_get_requirements(struct crypt_device *cd, struct luks2_hdr *hdr, uint32_t *reqs) { json_object *jobj_config, *jobj_requirements, *jobj_mandatory, *jobj; int i, len; uint32_t req; assert(hdr); if (!hdr || !reqs) return -EINVAL; *reqs = 0; if (!json_object_object_get_ex(hdr->jobj, "config", &jobj_config)) return 0; if (!json_object_object_get_ex(jobj_config, "requirements", &jobj_requirements)) return 0; if (!json_object_object_get_ex(jobj_requirements, "mandatory", &jobj_mandatory)) return 0; len = (int) json_object_array_length(jobj_mandatory); if (len <= 0) return 0; log_dbg(cd, "LUKS2 requirements detected:"); for (i = 0; i < len; i++) { jobj = json_object_array_get_idx(jobj_mandatory, i); req = get_requirement_by_name(json_object_get_string(jobj)); log_dbg(cd, "%s - %sknown", json_object_get_string(jobj), reqs_unknown(req) ? "un" : ""); *reqs |= req; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-345'], 'message': 'Fix CVE-2021-4122 - LUKS2 reencryption crash recovery attack Fix possible attacks against data confidentiality through LUKS2 online reencryption extension crash recovery. An attacker can modify on-disk metadata to simulate decryption in progress with crashed (unfinished) reencryption step and persistently decrypt part of the LUKS device. This attack requires repeated physical access to the LUKS device but no knowledge of user passphrases. The decryption step is performed after a valid user activates the device with a correct passphrase and modified metadata. There are no visible warnings for the user that such recovery happened (except using the luksDump command). The attack can also be reversed afterward (simulating crashed encryption from a plaintext) with possible modification of revealed plaintext. The problem was caused by reusing a mechanism designed for actual reencryption operation without reassessing the security impact for new encryption and decryption operations. While the reencryption requires calculating and verifying both key digests, no digest was needed to initiate decryption recovery if the destination is plaintext (no encryption key). Also, some metadata (like encryption cipher) is not protected, and an attacker could change it. Note that LUKS2 protects visible metadata only when a random change occurs. It does not protect against intentional modification but such modification must not cause a violation of data confidentiality. The fix introduces additional digest protection of reencryption metadata. The digest is calculated from known keys and critical reencryption metadata. Now an attacker cannot create correct metadata digest without knowledge of a passphrase for used keyslots. For more details, see LUKS2 On-Disk Format Specification version 1.1.0.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: libxlDomainCleanup(libxlDriverPrivate *driver, virDomainObj *vm) { libxlDomainObjPrivate *priv = vm->privateData; g_autoptr(libxlDriverConfig) cfg = libxlDriverConfigGet(driver); int vnc_port; char *file; virHostdevManager *hostdev_mgr = driver->hostdevMgr; unsigned int hostdev_flags = VIR_HOSTDEV_SP_PCI; VIR_DEBUG("Cleaning up domain with id '%d' and name '%s'", vm->def->id, vm->def->name); hostdev_flags |= VIR_HOSTDEV_SP_USB; /* Call hook with stopped operation. Ignore error and continue with cleanup */ ignore_value(libxlDomainHookRun(driver, vm->def, 0, VIR_HOOK_LIBXL_OP_STOPPED, VIR_HOOK_SUBOP_END, NULL)); virHostdevReAttachDomainDevices(hostdev_mgr, LIBXL_DRIVER_INTERNAL_NAME, vm->def, hostdev_flags); if (priv->lockProcessRunning) { VIR_FREE(priv->lockState); if (virDomainLockProcessPause(driver->lockManager, vm, &priv->lockState) < 0) VIR_WARN("Unable to release lease on %s", vm->def->name); else priv->lockProcessRunning = false; VIR_DEBUG("Preserving lock state '%s'", NULLSTR(priv->lockState)); } libxlLoggerCloseFile(cfg->logger, vm->def->id); vm->def->id = -1; if (priv->deathW) { libxl_evdisable_domain_death(cfg->ctx, priv->deathW); priv->deathW = NULL; } priv->ignoreDeathEvent = false; if (!!g_atomic_int_dec_and_test(&driver->nactive) && driver->inhibitCallback) driver->inhibitCallback(false, driver->inhibitOpaque); if ((vm->def->ngraphics == 1) && vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC && vm->def->graphics[0]->data.vnc.autoport) { vnc_port = vm->def->graphics[0]->data.vnc.port; if (vnc_port >= LIBXL_VNC_PORT_MIN) { if (virPortAllocatorRelease(vnc_port) < 0) VIR_DEBUG("Could not mark port %d as unused", vnc_port); } } libxlNetworkUnwindDevices(vm->def); file = g_strdup_printf("%s/%s.xml", cfg->stateDir, vm->def->name); if (unlink(file) < 0 && errno != ENOENT && errno != ENOTDIR) VIR_DEBUG("Failed to remove domain XML for %s", vm->def->name); VIR_FREE(file); /* Call hook with release operation. Ignore error and continue with cleanup */ ignore_value(libxlDomainHookRun(driver, vm->def, 0, VIR_HOOK_LIBXL_OP_RELEASE, VIR_HOOK_SUBOP_END, NULL)); virDomainObjRemoveTransientDef(vm); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-667'], 'message': 'libxl: Disable death events after receiving a shutdown event The libxl driver will handle all domain destruction and cleanup when receiving a domain shutdown event from libxl. Commit fa30ee04a2a introduced the ignoreDeathEvent boolean in the DomainObjPrivate struct to ignore subsequent death events from libxl. But libxl already provides a mechanism to disable death events via libxl_evdisable_domain_death. This patch partially reverts commit fa30ee04a2a and instead uses libxl_evdisable_domain_death to disable subsequent death events when processing a shutdown event. Signed-off-by: Jim Fehlig <jfehlig@suse.com> Reviewed-by: Daniel P. Berrangé <berrange@redhat.com> Reviewed-by: Ján Tomko <jtomko@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: libxlDomainShutdownThread(void *opaque) { struct libxlEventHandlerThreadInfo *shutdown_info = opaque; virDomainObj *vm = shutdown_info->vm; libxl_event *ev = shutdown_info->event; libxlDriverPrivate *driver = shutdown_info->driver; virObjectEvent *dom_event = NULL; libxl_shutdown_reason xl_reason = ev->u.domain_shutdown.shutdown_reason; g_autoptr(libxlDriverConfig) cfg = libxlDriverConfigGet(driver); libxl_domain_config d_config; libxl_domain_config_init(&d_config); if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0) goto cleanup; if (xl_reason == LIBXL_SHUTDOWN_REASON_POWEROFF) { virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF, VIR_DOMAIN_SHUTOFF_SHUTDOWN); dom_event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED, VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN); switch ((virDomainLifecycleAction) vm->def->onPoweroff) { case VIR_DOMAIN_LIFECYCLE_ACTION_DESTROY: libxlDomainShutdownHandleDestroy(driver, vm); goto endjob; case VIR_DOMAIN_LIFECYCLE_ACTION_RESTART: case VIR_DOMAIN_LIFECYCLE_ACTION_RESTART_RENAME: libxlDomainShutdownHandleRestart(driver, vm); goto endjob; case VIR_DOMAIN_LIFECYCLE_ACTION_PRESERVE: case VIR_DOMAIN_LIFECYCLE_ACTION_COREDUMP_DESTROY: case VIR_DOMAIN_LIFECYCLE_ACTION_COREDUMP_RESTART: case VIR_DOMAIN_LIFECYCLE_ACTION_LAST: goto endjob; } } else if (xl_reason == LIBXL_SHUTDOWN_REASON_CRASH) { virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF, VIR_DOMAIN_SHUTOFF_CRASHED); dom_event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED, VIR_DOMAIN_EVENT_STOPPED_CRASHED); switch ((virDomainLifecycleAction) vm->def->onCrash) { case VIR_DOMAIN_LIFECYCLE_ACTION_DESTROY: libxlDomainShutdownHandleDestroy(driver, vm); goto endjob; case VIR_DOMAIN_LIFECYCLE_ACTION_RESTART: case VIR_DOMAIN_LIFECYCLE_ACTION_RESTART_RENAME: libxlDomainShutdownHandleRestart(driver, vm); goto endjob; case VIR_DOMAIN_LIFECYCLE_ACTION_PRESERVE: case VIR_DOMAIN_LIFECYCLE_ACTION_LAST: goto endjob; case VIR_DOMAIN_LIFECYCLE_ACTION_COREDUMP_DESTROY: libxlDomainAutoCoreDump(driver, vm); libxlDomainShutdownHandleDestroy(driver, vm); goto endjob; case VIR_DOMAIN_LIFECYCLE_ACTION_COREDUMP_RESTART: libxlDomainAutoCoreDump(driver, vm); libxlDomainShutdownHandleRestart(driver, vm); goto endjob; } } else if (xl_reason == LIBXL_SHUTDOWN_REASON_REBOOT) { virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF, VIR_DOMAIN_SHUTOFF_SHUTDOWN); dom_event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED, VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN); switch ((virDomainLifecycleAction) vm->def->onReboot) { case VIR_DOMAIN_LIFECYCLE_ACTION_DESTROY: libxlDomainShutdownHandleDestroy(driver, vm); goto endjob; case VIR_DOMAIN_LIFECYCLE_ACTION_RESTART: case VIR_DOMAIN_LIFECYCLE_ACTION_RESTART_RENAME: libxlDomainShutdownHandleRestart(driver, vm); goto endjob; case VIR_DOMAIN_LIFECYCLE_ACTION_PRESERVE: case VIR_DOMAIN_LIFECYCLE_ACTION_COREDUMP_DESTROY: case VIR_DOMAIN_LIFECYCLE_ACTION_COREDUMP_RESTART: case VIR_DOMAIN_LIFECYCLE_ACTION_LAST: goto endjob; } } else if (xl_reason == LIBXL_SHUTDOWN_REASON_SOFT_RESET) { libxlDomainObjPrivate *priv = vm->privateData; if (libxlRetrieveDomainConfigurationWrapper(cfg->ctx, vm->def->id, &d_config) != 0) { VIR_ERROR(_("Failed to retrieve config for VM '%s'. " "Unable to perform soft reset. Destroying VM"), vm->def->name); libxlDomainShutdownHandleDestroy(driver, vm); goto endjob; } if (priv->deathW) { libxl_evdisable_domain_death(cfg->ctx, priv->deathW); priv->deathW = NULL; } if (libxl_domain_soft_reset(cfg->ctx, &d_config, vm->def->id, NULL, NULL) != 0) { VIR_ERROR(_("Failed to soft reset VM '%s'. Destroying VM"), vm->def->name); libxlDomainShutdownHandleDestroy(driver, vm); goto endjob; } libxl_evenable_domain_death(cfg->ctx, vm->def->id, 0, &priv->deathW); libxlDomainUnpauseWrapper(cfg->ctx, vm->def->id); } else { VIR_INFO("Unhandled shutdown_reason %d", xl_reason); } endjob: libxlDomainObjEndJob(driver, vm); cleanup: virDomainObjEndAPI(&vm); virObjectEventStateQueue(driver->domainEventState, dom_event); libxl_event_free(cfg->ctx, ev); VIR_FREE(shutdown_info); libxl_domain_config_dispose(&d_config); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-667'], 'message': 'libxl: Search for virDomainObj in event handler threads libxl can deliver events and invoke callbacks on any application thread calling into libxl. This can cause deadlock in the libvirt libxl driver Thread 19 (Thread 0x7f31411ec700 (LWP 14068) "libvirtd"): #0 0x00007f318520cc7d in __lll_lock_wait () from /lib64/libpthread.so.0 #1 0x00007f3185205ed5 in pthread_mutex_lock () from /lib64/libpthread.so.0 #2 0x00007f3189488015 in virMutexLock (m=<optimized out>) at ../../src/util/virthread.c:79 #3 0x00007f3189463f3b in virObjectLock (anyobj=<optimized out>) at ../../src/util/virobject.c:433 #4 0x00007f31894f2f41 in virDomainObjListSearchID (payload=0x7f317400a6d0, name=<optimized out>, data=0x7f31411eaeac) at ../../src/conf/virdomainobjlist.c:105 #5 0x00007f3189437ac5 in virHashSearch (ctable=0x7f3124025a30, iter=iter@entry=0x7f31894f2f30 <virDomainObjListSearchID>, data=data@entry=0x7f31411eaeac, name=name@entry=0x0) at ../../src/util/virhash.c:745 #6 0x00007f31894f3919 in virDomainObjListFindByID (doms=0x7f3124025430, id=<optimized out>) at ../../src/conf/virdomainobjlist.c:121 #7 0x00007f3152f292e5 in libxlDomainEventHandler (data=0x7f3124023d80, event=0x7f310c010ae0) at ../../src/libxl/libxl_domain.c:660 #8 0x00007f3152c6ff5d in egc_run_callbacks (egc=egc@entry=0x7f31411eaf50) at libxl_event.c:1427 #9 0x00007f3152c718bd in libxl__egc_cleanup (egc=0x7f31411eaf50) at libxl_event.c:1458 #10 libxl__ao_inprogress (ao=ao@entry=0x7f310c00b8a0, file=file@entry=0x7f3152cce987 "libxl_domain.c", line=line@entry=730, func=func@entry=0x7f3152ccf750 <__func__.22238> "libxl_domain_unpause") at libxl_event.c:2047 #11 0x00007f3152c8c5b8 in libxl_domain_unpause (ctx=0x7f3124015a40, domid=<optimized out>, ao_how=ao_how@entry=0x0) at libxl_domain.c:730 #12 0x00007f3152f2a584 in libxl_domain_unpause_0x041200 (domid=<optimized out>, ctx=<optimized out>) at /usr/include/libxl.h:1756 #13 libxlDomainStart (driver=driver@entry=0x7f3124023d80, vm=vm@entry=0x7f317400a6d0, start_paused=start_paused@entry=false, restore_fd=restore_fd@entry=-1, restore_ver=<optimized out>, restore_ver@entry=2) at ../../src/libxl/libxl_domain.c:1482 #14 0x00007f3152f2a6e3 in libxlDomainStartNew (driver=driver@entry=0x7f3124023d80, vm=vm@entry=0x7f317400a6d0, start_paused=start_paused@entry=false) at ../../src/libxl/libxl_domain.c:1545 #15 0x00007f3152f2a789 in libxlDomainShutdownHandleRestart (driver=0x7f3124023d80, vm=0x7f317400a6d0) at ../../src/libxl/libxl_domain.c:464 #16 0x00007f3152f2a9e4 in libxlDomainShutdownThread (opaque=<optimized out>) at ../../src/libxl/libxl_domain.c:559 #17 0x00007f3189487ee2 in virThreadHelper (data=<optimized out>) at ../../src/util/virthread.c:196 #18 0x00007f3185203539 in start_thread () from /lib64/libpthread.so.0 #19 0x00007f3184f3becf in clone () from /lib64/libc.so.6 Frame 16 runs a thread created to handle domain shutdown processing for domid 28712. In this case the event contained the reboot reason, so the old domain is destroyed and a new one is created by libxlDomainStart new. After starting the domain, it is unpaused by calling libxl_domain_unpause in frame 12. While the thread is running within libxl, libxl takes the opportunity to deliver a pending domain shutdown event for unrelated domid 28710. While searching for the associated virDomainObj by ID, a deadlock is encountered when attempting to lock the virDomainObj for domid 28712, which is already locked since this thread is processing its shutdown event. The deadlock can be avoided by moving the search for a virDomainObj associated with the event domid to the shutdown thread. The same is done for the death thread. Signed-off-by: Jim Fehlig <jfehlig@suse.com> Reviewed-by: Daniel P. Berrangé <berrange@redhat.com> Reviewed-by: Ján Tomko <jtomko@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void addDbAdminAnyDbPrivileges(PrivilegeVector* privileges) { Privilege::addPrivilegeToPrivilegeVector( privileges, Privilege(ResourcePattern::forClusterResource(), ActionType::listDatabases)); Privilege::addPrivilegeToPrivilegeVector( privileges, Privilege(ResourcePattern::forAnyNormalResource(), dbAdminRoleActions)); Privilege::addPrivilegeToPrivilegeVector( privileges, Privilege(ResourcePattern::forCollectionName("system.indexes"), readRoleActions)); Privilege::addPrivilegeToPrivilegeVector( privileges, Privilege(ResourcePattern::forCollectionName("system.namespaces"), readRoleActions)); ActionSet profileActions = readRoleActions; profileActions.addAction(ActionType::convertToCapped); profileActions.addAction(ActionType::createCollection); profileActions.addAction(ActionType::dropCollection); Privilege::addPrivilegeToPrivilegeVector( privileges, Privilege(ResourcePattern::forCollectionName("system.profile"), profileActions)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'SERVER-36263 Bypassing operation validation in applyOps should require special privilege'</s>
<s>[INST] Given the following code containing errors, provide 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_arg_all( int count, int forceit, // hide buffers in current windows int keep_tabs) // keep current tabs, for ":tab drop file" { int i; win_T *wp, *wpnext; char_u *opened; // Array of weight for which args are open: // 0: not opened // 1: opened in other tab // 2: opened in curtab // 3: opened in curtab and curwin // int opened_len; // length of opened[] int use_firstwin = FALSE; // use first window for arglist int tab_drop_empty_window = FALSE; int split_ret = OK; int p_ea_save; alist_T *alist; // argument list to be used buf_T *buf; tabpage_T *tpnext; int had_tab = cmdmod.cmod_tab; win_T *old_curwin, *last_curwin; tabpage_T *old_curtab, *last_curtab; win_T *new_curwin = NULL; tabpage_T *new_curtab = NULL; #ifdef FEAT_CMDWIN if (cmdwin_type != 0) { emsg(_(e_invalid_in_cmdline_window)); return; } #endif if (ARGCOUNT <= 0) { // Don't give an error message. We don't want it when the ":all" // command is in the .vimrc. return; } setpcmark(); opened_len = ARGCOUNT; opened = alloc_clear(opened_len); if (opened == NULL) return; // Autocommands may do anything to the argument list. Make sure it's not // freed while we are working here by "locking" it. We still have to // watch out for its size to be changed. alist = curwin->w_alist; ++alist->al_refcount; old_curwin = curwin; old_curtab = curtab; # ifdef FEAT_GUI need_mouse_correct = TRUE; # endif // Try closing all windows that are not in the argument list. // Also close windows that are not full width; // When 'hidden' or "forceit" set the buffer becomes hidden. // Windows that have a changed buffer and can't be hidden won't be closed. // When the ":tab" modifier was used do this for all tab pages. if (had_tab > 0) goto_tabpage_tp(first_tabpage, TRUE, TRUE); for (;;) { tpnext = curtab->tp_next; for (wp = firstwin; wp != NULL; wp = wpnext) { wpnext = wp->w_next; buf = wp->w_buffer; if (buf->b_ffname == NULL || (!keep_tabs && (buf->b_nwindows > 1 || wp->w_width != Columns))) i = opened_len; else { // check if the buffer in this window is in the arglist for (i = 0; i < opened_len; ++i) { if (i < alist->al_ga.ga_len && (AARGLIST(alist)[i].ae_fnum == buf->b_fnum || fullpathcmp(alist_name(&AARGLIST(alist)[i]), buf->b_ffname, TRUE, TRUE) & FPC_SAME)) { int weight = 1; if (old_curtab == curtab) { ++weight; if (old_curwin == wp) ++weight; } if (weight > (int)opened[i]) { opened[i] = (char_u)weight; if (i == 0) { if (new_curwin != NULL) new_curwin->w_arg_idx = opened_len; new_curwin = wp; new_curtab = curtab; } } else if (keep_tabs) i = opened_len; if (wp->w_alist != alist) { // Use the current argument list for all windows // containing a file from it. alist_unlink(wp->w_alist); wp->w_alist = alist; ++wp->w_alist->al_refcount; } break; } } } wp->w_arg_idx = i; if (i == opened_len && !keep_tabs)// close this window { if (buf_hide(buf) || forceit || buf->b_nwindows > 1 || !bufIsChanged(buf)) { // If the buffer was changed, and we would like to hide it, // try autowriting. if (!buf_hide(buf) && buf->b_nwindows <= 1 && bufIsChanged(buf)) { bufref_T bufref; set_bufref(&bufref, buf); (void)autowrite(buf, FALSE); // check if autocommands removed the window if (!win_valid(wp) || !bufref_valid(&bufref)) { wpnext = firstwin; // start all over... continue; } } // don't close last window if (ONE_WINDOW && (first_tabpage->tp_next == NULL || !had_tab)) use_firstwin = TRUE; else { win_close(wp, !buf_hide(buf) && !bufIsChanged(buf)); // check if autocommands removed the next window if (!win_valid(wpnext)) wpnext = firstwin; // start all over... } } } } // Without the ":tab" modifier only do the current tab page. if (had_tab == 0 || tpnext == NULL) break; // check if autocommands removed the next tab page if (!valid_tabpage(tpnext)) tpnext = first_tabpage; // start all over... goto_tabpage_tp(tpnext, TRUE, TRUE); } // Open a window for files in the argument list that don't have one. // ARGCOUNT may change while doing this, because of autocommands. if (count > opened_len || count <= 0) count = opened_len; // Don't execute Win/Buf Enter/Leave autocommands here. ++autocmd_no_enter; ++autocmd_no_leave; last_curwin = curwin; last_curtab = curtab; win_enter(lastwin, FALSE); // ":tab drop file" should re-use an empty window to avoid "--remote-tab" // leaving an empty tab page when executed locally. if (keep_tabs && BUFEMPTY() && curbuf->b_nwindows == 1 && curbuf->b_ffname == NULL && !curbuf->b_changed) { use_firstwin = TRUE; tab_drop_empty_window = TRUE; } for (i = 0; i < count && !got_int; ++i) { if (alist == &global_alist && i == global_alist.al_ga.ga_len - 1) arg_had_last = TRUE; if (opened[i] > 0) { // Move the already present window to below the current window if (curwin->w_arg_idx != i) { FOR_ALL_WINDOWS(wpnext) { if (wpnext->w_arg_idx == i) { if (keep_tabs) { new_curwin = wpnext; new_curtab = curtab; } else if (wpnext->w_frame->fr_parent != curwin->w_frame->fr_parent) { emsg(_("E249: window layout changed unexpectedly")); i = count; break; } else win_move_after(wpnext, curwin); break; } } } } else if (split_ret == OK) { // trigger events for tab drop if (tab_drop_empty_window && i == count - 1) --autocmd_no_enter; if (!use_firstwin) // split current window { p_ea_save = p_ea; p_ea = TRUE; // use space from all windows split_ret = win_split(0, WSP_ROOM | WSP_BELOW); p_ea = p_ea_save; if (split_ret == FAIL) continue; } else // first window: do autocmd for leaving this buffer --autocmd_no_leave; // edit file "i" curwin->w_arg_idx = i; if (i == 0) { new_curwin = curwin; new_curtab = curtab; } (void)do_ecmd(0, alist_name(&AARGLIST(alist)[i]), NULL, NULL, ECMD_ONE, ((buf_hide(curwin->w_buffer) || bufIsChanged(curwin->w_buffer)) ? ECMD_HIDE : 0) + ECMD_OLDBUF, curwin); if (tab_drop_empty_window && i == count - 1) ++autocmd_no_enter; if (use_firstwin) ++autocmd_no_leave; use_firstwin = FALSE; } ui_breakcheck(); // When ":tab" was used open a new tab for a new window repeatedly. if (had_tab > 0 && tabpage_index(NULL) <= p_tpm) cmdmod.cmod_tab = 9999; } // Remove the "lock" on the argument list. alist_unlink(alist); --autocmd_no_enter; // restore last referenced tabpage's curwin if (last_curtab != new_curtab) { if (valid_tabpage(last_curtab)) goto_tabpage_tp(last_curtab, TRUE, TRUE); if (win_valid(last_curwin)) win_enter(last_curwin, FALSE); } // to window with first arg if (valid_tabpage(new_curtab)) goto_tabpage_tp(new_curtab, TRUE, TRUE); if (win_valid(new_curwin)) win_enter(new_curwin, FALSE); --autocmd_no_leave; vim_free(opened); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-125'], 'message': 'patch 8.2.3884: crash when clearing the argument list while using it Problem: Crash when clearing the argument list while using it. Solution: Lock the argument list for ":all".'</s>
<s>[INST] Given the following code containing errors, provide 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 __always_inline int kvm_handle_hva_range_no_flush(struct mmu_notifier *mn, unsigned long start, unsigned long end, hva_handler_t handler) { struct kvm *kvm = mmu_notifier_to_kvm(mn); const struct kvm_hva_range range = { .start = start, .end = end, .pte = __pte(0), .handler = handler, .on_lock = (void *)kvm_null_fn, .flush_on_ret = false, .may_block = false, }; return __kvm_handle_hva_range(kvm, &range); ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-459'], 'message': 'KVM: SEV: add cache flush to solve SEV cache incoherency issues Flush the CPU caches when memory is reclaimed from an SEV guest (where reclaim also includes it being unmapped from KVM's memslots). Due to lack of coherency for SEV encrypted memory, failure to flush results in silent data corruption if userspace is malicious/broken and doesn't ensure SEV guest memory is properly pinned and unpinned. Cache coherency is not enforced across the VM boundary in SEV (AMD APM vol.2 Section 15.34.7). Confidential cachelines, generated by confidential VM guests have to be explicitly flushed on the host side. If a memory page containing dirty confidential cachelines was released by VM and reallocated to another user, the cachelines may corrupt the new user at a later time. KVM takes a shortcut by assuming all confidential memory remain pinned until the end of VM lifetime. Therefore, KVM does not flush cache at mmu_notifier invalidation events. Because of this incorrect assumption and the lack of cache flushing, malicous userspace can crash the host kernel: creating a malicious VM and continuously allocates/releases unpinned confidential memory pages when the VM is running. Add cache flush operations to mmu_notifier operations to ensure that any physical memory leaving the guest VM get flushed. In particular, hook mmu_notifier_invalidate_range_start and mmu_notifier_release events and flush cache accordingly. The hook after releasing the mmu lock to avoid contention with other vCPUs. Cc: stable@vger.kernel.org Suggested-by: Sean Christpherson <seanjc@google.com> Reported-by: Mingwei Zhang <mizhang@google.com> Signed-off-by: Mingwei Zhang <mizhang@google.com> Message-Id: <20220421031407.2516575-4-mizhang@google.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ex_function(exarg_T *eap) { char_u *line_to_free = NULL; (void)define_function(eap, NULL, &line_to_free); vim_free(line_to_free); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'patch 8.2.4040: keeping track of allocated lines is too complicated Problem: Keeping track of allocated lines in user functions is too complicated. Solution: Instead of freeing individual lines keep them all until the end.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ga_init2(garray_T *gap, int itemsize, int growsize) { ga_init(gap); gap->ga_itemsize = itemsize; gap->ga_growsize = growsize; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'patch 8.2.4040: keeping track of allocated lines is too complicated Problem: Keeping track of allocated lines in user functions is too complicated. Solution: Instead of freeing individual lines keep them all until the end.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: struct sctp_chunk *sctp_make_strreset_req( const struct sctp_association *asoc, __u16 stream_num, __be16 *stream_list, bool out, bool in) { __u16 stream_len = stream_num * sizeof(__u16); struct sctp_strreset_outreq outreq; struct sctp_strreset_inreq inreq; struct sctp_chunk *retval; __u16 outlen, inlen; outlen = (sizeof(outreq) + stream_len) * out; inlen = (sizeof(inreq) + stream_len) * in; retval = sctp_make_reconf(asoc, outlen + inlen); if (!retval) return NULL; if (outlen) { outreq.param_hdr.type = SCTP_PARAM_RESET_OUT_REQUEST; outreq.param_hdr.length = htons(outlen); outreq.request_seq = htonl(asoc->strreset_outseq); outreq.response_seq = htonl(asoc->strreset_inseq - 1); outreq.send_reset_at_tsn = htonl(asoc->next_tsn - 1); sctp_addto_chunk(retval, sizeof(outreq), &outreq); if (stream_len) sctp_addto_chunk(retval, stream_len, stream_list); } if (inlen) { inreq.param_hdr.type = SCTP_PARAM_RESET_IN_REQUEST; inreq.param_hdr.length = htons(inlen); inreq.request_seq = htonl(asoc->strreset_outseq + out); sctp_addto_chunk(retval, sizeof(inreq), &inreq); if (stream_len) sctp_addto_chunk(retval, stream_len, stream_list); } return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-704'], 'message': 'sctp: account stream padding length for reconf chunk sctp_make_strreset_req() makes repeated calls to sctp_addto_chunk() which will automatically account for padding on each call. inreq and outreq are already 4 bytes aligned, but the payload is not and doing SCTP_PAD4(a + b) (which _sctp_make_chunk() did implicitly here) is different from SCTP_PAD4(a) + SCTP_PAD4(b) and not enough. It led to possible attempt to use more buffer than it was allocated and triggered a BUG_ON. Cc: Vlad Yasevich <vyasevich@gmail.com> Cc: Neil Horman <nhorman@tuxdriver.com> Cc: Greg KH <gregkh@linuxfoundation.org> Fixes: cc16f00f6529 ("sctp: add support for generating stream reconf ssn reset request chunk") Reported-by: Eiichi Tsukata <eiichi.tsukata@nutanix.com> Signed-off-by: Eiichi Tsukata <eiichi.tsukata@nutanix.com> Signed-off-by: Marcelo Ricardo Leitner <marcelo.leitner@gmail.com> Signed-off-by: Marcelo Ricardo Leitner <mleitner@redhat.com> Reviewed-by: Xin Long <lucien.xin@gmail.com> Link: https://lore.kernel.org/r/b97c1f8b0c7ff79ac4ed206fc2c49d3612e0850c.1634156849.git.mleitner@redhat.com Signed-off-by: Jakub Kicinski <kuba@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: compile_def_function( ufunc_T *ufunc, int check_return_type, compiletype_T compile_type, cctx_T *outer_cctx) { char_u *line = NULL; char_u *line_to_free = NULL; char_u *p; char *errormsg = NULL; // error message cctx_T cctx; garray_T *instr; int did_emsg_before = did_emsg; int did_emsg_silent_before = did_emsg_silent; int ret = FAIL; sctx_T save_current_sctx = current_sctx; int save_estack_compiling = estack_compiling; int save_cmod_flags = cmdmod.cmod_flags; int do_estack_push; int new_def_function = FALSE; #ifdef FEAT_PROFILE int prof_lnum = -1; #endif int debug_lnum = -1; // When using a function that was compiled before: Free old instructions. // The index is reused. Otherwise add a new entry in "def_functions". if (ufunc->uf_dfunc_idx > 0) { dfunc_T *dfunc = ((dfunc_T *)def_functions.ga_data) + ufunc->uf_dfunc_idx; isn_T *instr_dest = NULL; switch (compile_type) { case CT_PROFILE: #ifdef FEAT_PROFILE instr_dest = dfunc->df_instr_prof; break; #endif case CT_NONE: instr_dest = dfunc->df_instr; break; case CT_DEBUG: instr_dest = dfunc->df_instr_debug; break; } if (instr_dest != NULL) // Was compiled in this mode before: Free old instructions. delete_def_function_contents(dfunc, FALSE); ga_clear_strings(&dfunc->df_var_names); } else { if (add_def_function(ufunc) == FAIL) return FAIL; new_def_function = TRUE; } ufunc->uf_def_status = UF_COMPILING; CLEAR_FIELD(cctx); cctx.ctx_compile_type = compile_type; cctx.ctx_ufunc = ufunc; cctx.ctx_lnum = -1; cctx.ctx_outer = outer_cctx; ga_init2(&cctx.ctx_locals, sizeof(lvar_T), 10); // Each entry on the type stack consists of two type pointers. ga_init2(&cctx.ctx_type_stack, sizeof(type2_T), 50); ga_init2(&cctx.ctx_imports, sizeof(imported_T), 10); cctx.ctx_type_list = &ufunc->uf_type_list; ga_init2(&cctx.ctx_instr, sizeof(isn_T), 50); instr = &cctx.ctx_instr; // Set the context to the function, it may be compiled when called from // another script. Set the script version to the most modern one. // The line number will be set in next_line_from_context(). current_sctx = ufunc->uf_script_ctx; current_sctx.sc_version = SCRIPT_VERSION_VIM9; // Don't use the flag from ":legacy" here. cmdmod.cmod_flags &= ~CMOD_LEGACY; // Make sure error messages are OK. do_estack_push = !estack_top_is_ufunc(ufunc, 1); if (do_estack_push) estack_push_ufunc(ufunc, 1); estack_compiling = TRUE; if (check_args_shadowing(ufunc, &cctx) == FAIL) goto erret; if (ufunc->uf_def_args.ga_len > 0) { int count = ufunc->uf_def_args.ga_len; int first_def_arg = ufunc->uf_args.ga_len - count; int i; char_u *arg; int off = STACK_FRAME_SIZE + (ufunc->uf_va_name != NULL ? 1 : 0); int did_set_arg_type = FALSE; // Produce instructions for the default values of optional arguments. SOURCING_LNUM = 0; // line number unknown for (i = 0; i < count; ++i) { type_T *val_type; int arg_idx = first_def_arg + i; where_T where = WHERE_INIT; int r; int jump_instr_idx = instr->ga_len; isn_T *isn; // Use a JUMP_IF_ARG_SET instruction to skip if the value was given. if (generate_JUMP_IF_ARG_SET(&cctx, i - count - off) == FAIL) goto erret; // Make sure later arguments are not found. ufunc->uf_args_visible = arg_idx; arg = ((char_u **)(ufunc->uf_def_args.ga_data))[i]; r = compile_expr0(&arg, &cctx); if (r == FAIL) goto erret; // If no type specified use the type of the default value. // Otherwise check that the default value type matches the // specified type. val_type = get_type_on_stack(&cctx, 0); where.wt_index = arg_idx + 1; if (ufunc->uf_arg_types[arg_idx] == &t_unknown) { did_set_arg_type = TRUE; ufunc->uf_arg_types[arg_idx] = val_type; } else if (need_type_where(val_type, ufunc->uf_arg_types[arg_idx], -1, where, &cctx, FALSE, FALSE) == FAIL) goto erret; if (generate_STORE(&cctx, ISN_STORE, i - count - off, NULL) == FAIL) goto erret; // set instruction index in JUMP_IF_ARG_SET to here isn = ((isn_T *)instr->ga_data) + jump_instr_idx; isn->isn_arg.jumparg.jump_where = instr->ga_len; } if (did_set_arg_type) set_function_type(ufunc); } ufunc->uf_args_visible = ufunc->uf_args.ga_len; /* * Loop over all the lines of the function and generate instructions. */ for (;;) { exarg_T ea; int starts_with_colon = FALSE; char_u *cmd; cmdmod_T local_cmdmod; // Bail out on the first error to avoid a flood of errors and report // the right line number when inside try/catch. if (did_emsg_before != did_emsg) goto erret; if (line != NULL && *line == '|') // the line continues after a '|' ++line; else if (line != NULL && *skipwhite(line) != NUL && !(*line == '#' && (line == cctx.ctx_line_start || VIM_ISWHITE(line[-1])))) { semsg(_(e_trailing_characters_str), line); goto erret; } else if (line != NULL && vim9_bad_comment(skipwhite(line))) goto erret; else { line = next_line_from_context(&cctx, FALSE); if (cctx.ctx_lnum >= ufunc->uf_lines.ga_len) { // beyond the last line #ifdef FEAT_PROFILE if (cctx.ctx_skip != SKIP_YES) may_generate_prof_end(&cctx, prof_lnum); #endif break; } // Make a copy, splitting off nextcmd and removing trailing spaces // may change it. if (line != NULL) { line = vim_strsave(line); vim_free(line_to_free); line_to_free = line; } } CLEAR_FIELD(ea); ea.cmdlinep = &line; ea.cmd = skipwhite(line); if (*ea.cmd == '#') { // "#" starts a comment line = (char_u *)""; continue; } #ifdef FEAT_PROFILE if (cctx.ctx_compile_type == CT_PROFILE && cctx.ctx_lnum != prof_lnum && cctx.ctx_skip != SKIP_YES) { may_generate_prof_end(&cctx, prof_lnum); prof_lnum = cctx.ctx_lnum; generate_instr(&cctx, ISN_PROF_START); } #endif if (cctx.ctx_compile_type == CT_DEBUG && cctx.ctx_lnum != debug_lnum && cctx.ctx_skip != SKIP_YES) { debug_lnum = cctx.ctx_lnum; generate_instr_debug(&cctx); } cctx.ctx_prev_lnum = cctx.ctx_lnum + 1; // Some things can be recognized by the first character. switch (*ea.cmd) { case '}': { // "}" ends a block scope scopetype_T stype = cctx.ctx_scope == NULL ? NO_SCOPE : cctx.ctx_scope->se_type; if (stype == BLOCK_SCOPE) { compile_endblock(&cctx); line = ea.cmd; } else { emsg(_(e_using_rcurly_outside_if_block_scope)); goto erret; } if (line != NULL) line = skipwhite(ea.cmd + 1); continue; } case '{': // "{" starts a block scope // "{'a': 1}->func() is something else if (ends_excmd(*skipwhite(ea.cmd + 1))) { line = compile_block(ea.cmd, &cctx); continue; } break; } /* * COMMAND MODIFIERS */ cctx.ctx_has_cmdmod = FALSE; if (parse_command_modifiers(&ea, &errormsg, &local_cmdmod, FALSE) == FAIL) { if (errormsg != NULL) goto erret; // empty line or comment line = (char_u *)""; continue; } generate_cmdmods(&cctx, &local_cmdmod); undo_cmdmod(&local_cmdmod); // Check if there was a colon after the last command modifier or before // the current position. for (p = ea.cmd; p >= line; --p) { if (*p == ':') starts_with_colon = TRUE; if (p < ea.cmd && !VIM_ISWHITE(*p)) break; } // Skip ":call" to get to the function name, unless using :legacy p = ea.cmd; if (!(local_cmdmod.cmod_flags & CMOD_LEGACY)) { if (checkforcmd(&ea.cmd, "call", 3)) { if (*ea.cmd == '(') // not for "call()" ea.cmd = p; else ea.cmd = skipwhite(ea.cmd); } if (!starts_with_colon) { int assign; // Check for assignment after command modifiers. assign = may_compile_assignment(&ea, &line, &cctx); if (assign == OK) goto nextline; if (assign == FAIL) goto erret; } } /* * COMMAND after range * 'text'->func() should not be confused with 'a mark * "++nr" and "--nr" are eval commands * in "$ENV->func()" the "$" is not a range */ cmd = ea.cmd; if ((*cmd != '$' || starts_with_colon) && (starts_with_colon || !(*cmd == '\'' || (cmd[0] == cmd[1] && (*cmd == '+' || *cmd == '-'))))) { ea.cmd = skip_range(ea.cmd, TRUE, NULL); if (ea.cmd > cmd) { if (!starts_with_colon && !(local_cmdmod.cmod_flags & CMOD_LEGACY)) { semsg(_(e_colon_required_before_range_str), cmd); goto erret; } ea.addr_count = 1; if (ends_excmd2(line, ea.cmd)) { // A range without a command: jump to the line. generate_EXEC(&cctx, ISN_EXECRANGE, vim_strnsave(cmd, ea.cmd - cmd)); line = ea.cmd; goto nextline; } } } p = find_ex_command(&ea, NULL, starts_with_colon || (local_cmdmod.cmod_flags & CMOD_LEGACY) ? NULL : item_exists, &cctx); if (p == NULL) { if (cctx.ctx_skip != SKIP_YES) emsg(_(e_ambiguous_use_of_user_defined_command)); goto erret; } // When using ":legacy cmd" always use compile_exec(). if (local_cmdmod.cmod_flags & CMOD_LEGACY) { char_u *start = ea.cmd; switch (ea.cmdidx) { case CMD_if: case CMD_elseif: case CMD_else: case CMD_endif: case CMD_for: case CMD_endfor: case CMD_continue: case CMD_break: case CMD_while: case CMD_endwhile: case CMD_try: case CMD_catch: case CMD_finally: case CMD_endtry: semsg(_(e_cannot_use_legacy_with_command_str), ea.cmd); goto erret; default: break; } // ":legacy return expr" needs to be handled differently. if (checkforcmd(&start, "return", 4)) ea.cmdidx = CMD_return; else ea.cmdidx = CMD_legacy; } if (p == ea.cmd && ea.cmdidx != CMD_SIZE) { if (cctx.ctx_skip == SKIP_YES && ea.cmdidx != CMD_eval) { line += STRLEN(line); goto nextline; } else if (ea.cmdidx != CMD_eval) { // CMD_var cannot happen, compile_assignment() above would be // used. Most likely an assignment to a non-existing variable. semsg(_(e_command_not_recognized_str), ea.cmd); goto erret; } } if (cctx.ctx_had_return && ea.cmdidx != CMD_elseif && ea.cmdidx != CMD_else && ea.cmdidx != CMD_endif && ea.cmdidx != CMD_endfor && ea.cmdidx != CMD_endwhile && ea.cmdidx != CMD_catch && ea.cmdidx != CMD_finally && ea.cmdidx != CMD_endtry) { emsg(_(e_unreachable_code_after_return)); goto erret; } p = skipwhite(p); if (ea.cmdidx != CMD_SIZE && ea.cmdidx != CMD_write && ea.cmdidx != CMD_read) { if (ea.cmdidx >= 0) ea.argt = excmd_get_argt(ea.cmdidx); if ((ea.argt & EX_BANG) && *p == '!') { ea.forceit = TRUE; p = skipwhite(p + 1); } } switch (ea.cmdidx) { case CMD_def: case CMD_function: ea.arg = p; line = compile_nested_function(&ea, &cctx, &line_to_free); break; case CMD_return: line = compile_return(p, check_return_type, local_cmdmod.cmod_flags & CMOD_LEGACY, &cctx); cctx.ctx_had_return = TRUE; break; case CMD_let: emsg(_(e_cannot_use_let_in_vim9_script)); break; case CMD_var: case CMD_final: case CMD_const: case CMD_increment: case CMD_decrement: line = compile_assignment(p, &ea, ea.cmdidx, &cctx); if (line == p) line = NULL; break; case CMD_unlet: case CMD_unlockvar: case CMD_lockvar: line = compile_unletlock(p, &ea, &cctx); break; case CMD_import: emsg(_(e_import_can_only_be_used_in_script)); line = NULL; break; case CMD_if: line = compile_if(p, &cctx); break; case CMD_elseif: line = compile_elseif(p, &cctx); cctx.ctx_had_return = FALSE; break; case CMD_else: line = compile_else(p, &cctx); cctx.ctx_had_return = FALSE; break; case CMD_endif: line = compile_endif(p, &cctx); break; case CMD_while: line = compile_while(p, &cctx); break; case CMD_endwhile: line = compile_endwhile(p, &cctx); cctx.ctx_had_return = FALSE; break; case CMD_for: line = compile_for(p, &cctx); break; case CMD_endfor: line = compile_endfor(p, &cctx); cctx.ctx_had_return = FALSE; break; case CMD_continue: line = compile_continue(p, &cctx); break; case CMD_break: line = compile_break(p, &cctx); break; case CMD_try: line = compile_try(p, &cctx); break; case CMD_catch: line = compile_catch(p, &cctx); cctx.ctx_had_return = FALSE; break; case CMD_finally: line = compile_finally(p, &cctx); cctx.ctx_had_return = FALSE; break; case CMD_endtry: line = compile_endtry(p, &cctx); cctx.ctx_had_return = FALSE; break; case CMD_throw: line = compile_throw(p, &cctx); break; case CMD_eval: line = compile_eval(p, &cctx); break; case CMD_echo: case CMD_echon: case CMD_execute: case CMD_echomsg: case CMD_echoerr: case CMD_echoconsole: line = compile_mult_expr(p, ea.cmdidx, &cctx); break; case CMD_put: ea.cmd = cmd; line = compile_put(p, &ea, &cctx); break; case CMD_substitute: if (check_global_and_subst(ea.cmd, p) == FAIL) goto erret; if (cctx.ctx_skip == SKIP_YES) line = (char_u *)""; else { ea.arg = p; line = compile_substitute(line, &ea, &cctx); } break; case CMD_redir: ea.arg = p; line = compile_redir(line, &ea, &cctx); break; case CMD_cexpr: case CMD_lexpr: case CMD_caddexpr: case CMD_laddexpr: case CMD_cgetexpr: case CMD_lgetexpr: #ifdef FEAT_QUICKFIX ea.arg = p; line = compile_cexpr(line, &ea, &cctx); #else ex_ni(&ea); line = NULL; #endif break; case CMD_append: case CMD_change: case CMD_insert: case CMD_k: case CMD_t: case CMD_xit: not_in_vim9(&ea); goto erret; case CMD_SIZE: if (cctx.ctx_skip != SKIP_YES) { semsg(_(e_invalid_command_str), ea.cmd); goto erret; } // We don't check for a next command here. line = (char_u *)""; break; case CMD_lua: case CMD_mzscheme: case CMD_perl: case CMD_py3: case CMD_python3: case CMD_python: case CMD_pythonx: case CMD_ruby: case CMD_tcl: ea.arg = p; if (vim_strchr(line, '\n') == NULL) line = compile_exec(line, &ea, &cctx); else // heredoc lines have been concatenated with NL // characters in get_function_body() line = compile_script(line, &cctx); break; case CMD_global: if (check_global_and_subst(ea.cmd, p) == FAIL) goto erret; // FALLTHROUGH default: // Not recognized, execute with do_cmdline_cmd(). ea.arg = p; line = compile_exec(line, &ea, &cctx); break; } nextline: if (line == NULL) goto erret; line = skipwhite(line); // Undo any command modifiers. generate_undo_cmdmods(&cctx); if (cctx.ctx_type_stack.ga_len < 0) { iemsg("Type stack underflow"); goto erret; } } if (cctx.ctx_scope != NULL) { if (cctx.ctx_scope->se_type == IF_SCOPE) emsg(_(e_missing_endif)); else if (cctx.ctx_scope->se_type == WHILE_SCOPE) emsg(_(e_missing_endwhile)); else if (cctx.ctx_scope->se_type == FOR_SCOPE) emsg(_(e_missing_endfor)); else emsg(_(e_missing_rcurly)); goto erret; } if (!cctx.ctx_had_return) { if (ufunc->uf_ret_type->tt_type == VAR_UNKNOWN) ufunc->uf_ret_type = &t_void; else if (ufunc->uf_ret_type->tt_type != VAR_VOID) { emsg(_(e_missing_return_statement)); goto erret; } // Return void if there is no return at the end. generate_instr(&cctx, ISN_RETURN_VOID); } // When compiled with ":silent!" and there was an error don't consider the // function compiled. if (emsg_silent == 0 || did_emsg_silent == did_emsg_silent_before) { dfunc_T *dfunc = ((dfunc_T *)def_functions.ga_data) + ufunc->uf_dfunc_idx; dfunc->df_deleted = FALSE; dfunc->df_script_seq = current_sctx.sc_seq; #ifdef FEAT_PROFILE if (cctx.ctx_compile_type == CT_PROFILE) { dfunc->df_instr_prof = instr->ga_data; dfunc->df_instr_prof_count = instr->ga_len; } else #endif if (cctx.ctx_compile_type == CT_DEBUG) { dfunc->df_instr_debug = instr->ga_data; dfunc->df_instr_debug_count = instr->ga_len; } else { dfunc->df_instr = instr->ga_data; dfunc->df_instr_count = instr->ga_len; } dfunc->df_varcount = dfunc->df_var_names.ga_len; dfunc->df_has_closure = cctx.ctx_has_closure; if (cctx.ctx_outer_used) ufunc->uf_flags |= FC_CLOSURE; ufunc->uf_def_status = UF_COMPILED; } ret = OK; erret: if (ufunc->uf_def_status == UF_COMPILING) { dfunc_T *dfunc = ((dfunc_T *)def_functions.ga_data) + ufunc->uf_dfunc_idx; // Compiling aborted, free the generated instructions. clear_instr_ga(instr); VIM_CLEAR(dfunc->df_name); ga_clear_strings(&dfunc->df_var_names); // If using the last entry in the table and it was added above, we // might as well remove it. if (!dfunc->df_deleted && new_def_function && ufunc->uf_dfunc_idx == def_functions.ga_len - 1) { --def_functions.ga_len; ufunc->uf_dfunc_idx = 0; } ufunc->uf_def_status = UF_COMPILE_ERROR; while (cctx.ctx_scope != NULL) drop_scope(&cctx); if (errormsg != NULL) emsg(errormsg); else if (did_emsg == did_emsg_before) emsg(_(e_compiling_def_function_failed)); } if (cctx.ctx_redir_lhs.lhs_name != NULL) { if (ret == OK) { emsg(_(e_missing_redir_end)); ret = FAIL; } vim_free(cctx.ctx_redir_lhs.lhs_name); vim_free(cctx.ctx_redir_lhs.lhs_whole); } current_sctx = save_current_sctx; estack_compiling = save_estack_compiling; cmdmod.cmod_flags = save_cmod_flags; if (do_estack_push) estack_pop(); vim_free(line_to_free); free_imported(&cctx); free_locals(&cctx); ga_clear(&cctx.ctx_type_stack); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'patch 8.2.4009: reading one byte beyond the end of the line Problem: Reading one byte beyond the end of the line. Solution: Check for NUL byte first.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: struct ucounts *alloc_ucounts(struct user_namespace *ns, kuid_t uid) { struct hlist_head *hashent = ucounts_hashentry(ns, uid); struct ucounts *ucounts, *new; bool wrapped; spin_lock_irq(&ucounts_lock); ucounts = find_ucounts(ns, uid, hashent); if (!ucounts) { spin_unlock_irq(&ucounts_lock); new = kzalloc(sizeof(*new), GFP_KERNEL); if (!new) return NULL; new->ns = ns; new->uid = uid; atomic_set(&new->count, 1); spin_lock_irq(&ucounts_lock); ucounts = find_ucounts(ns, uid, hashent); if (ucounts) { kfree(new); } else { hlist_add_head(&new->node, hashent); spin_unlock_irq(&ucounts_lock); return new; } } wrapped = !get_ucounts_or_wrap(ucounts); spin_unlock_irq(&ucounts_lock); if (wrapped) { put_ucounts(ucounts); return NULL; } return ucounts; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'ucount: Make get_ucount a safe get_user replacement When the ucount code was refactored to create get_ucount it was missed that some of the contexts in which a rlimit is kept elevated can be the only reference to the user/ucount in the system. Ordinary ucount references exist in places that also have a reference to the user namspace, but in POSIX message queues, the SysV shm code, and the SIGPENDING code there is no independent user namespace reference. Inspection of the the user_namespace show no instance of circular references between struct ucounts and the user_namespace. So hold a reference from struct ucount to i's user_namespace to resolve this problem. Link: https://lore.kernel.org/lkml/YZV7Z+yXbsx9p3JN@fixkernel.com/ Reported-by: Qian Cai <quic_qiancai@quicinc.com> Reported-by: Mathias Krause <minipli@grsecurity.net> Tested-by: Mathias Krause <minipli@grsecurity.net> Reviewed-by: Mathias Krause <minipli@grsecurity.net> Reviewed-by: Alexey Gladkov <legion@kernel.org> Fixes: d64696905554 ("Reimplement RLIMIT_SIGPENDING on top of ucounts") Fixes: 6e52a9f0532f ("Reimplement RLIMIT_MSGQUEUE on top of ucounts") Fixes: d7c9e99aee48 ("Reimplement RLIMIT_MEMLOCK on top of ucounts") Cc: stable@vger.kernel.org Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: tabstop_set(char_u *var, int **array) { int valcount = 1; int t; char_u *cp; if (var[0] == NUL || (var[0] == '0' && var[1] == NUL)) { *array = NULL; return OK; } for (cp = var; *cp != NUL; ++cp) { if (cp == var || cp[-1] == ',') { char_u *end; if (strtol((char *)cp, (char **)&end, 10) <= 0) { if (cp != end) emsg(_(e_argument_must_be_positive)); else semsg(_(e_invalid_argument_str), cp); return FAIL; } } if (VIM_ISDIGIT(*cp)) continue; if (cp[0] == ',' && cp > var && cp[-1] != ',' && cp[1] != NUL) { ++valcount; continue; } semsg(_(e_invalid_argument_str), var); return FAIL; } *array = ALLOC_MULT(int, valcount + 1); if (*array == NULL) return FAIL; (*array)[0] = valcount; t = 1; for (cp = var; *cp != NUL;) { int n = atoi((char *)cp); // Catch negative values, overflow and ridiculous big values. if (n < 0 || n > 9999) { semsg(_(e_invalid_argument_str), cp); vim_free(*array); *array = NULL; return FAIL; } (*array)[t++] = n; while (*cp != NUL && *cp != ',') ++cp; if (*cp != NUL) ++cp; } return OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-122', 'CWE-787'], 'message': 'patch 8.2.4245: ":retab 0" may cause illegal memory access Problem: ":retab 0" may cause illegal memory access. Solution: Limit the value of 'tabstop' to 10000.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: null_asynch_zero (struct rw *rw, struct command *command, nbd_completion_callback cb, bool allocate) { int dummy = 0; if (cb.callback (cb.user_data, &dummy) == -1) { perror (rw->name); exit (EXIT_FAILURE); } return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-252'], 'message': 'copy: CVE-2022-0485: Fail nbdcopy if NBD read or write fails nbdcopy has a nasty bug when performing multi-threaded copies using asynchronous nbd calls - it was blindly treating the completion of an asynchronous command as successful, rather than checking the *error parameter. This can result in the silent creation of a corrupted image in two different ways: when a read fails, we blindly wrote garbage to the destination; when a write fails, we did not flag that the destination was not written. Since nbdcopy already calls exit() on a synchronous read or write failure to a file, doing the same for an asynchronous op to an NBD server is the simplest solution. A nicer solution, but more invasive to code and thus not done here, might be to allow up to N retries of the transaction (in case the read or write failure was transient), or even having a mode where as much data is copied as possible (portions of the copy that failed would be logged on stderr, and nbdcopy would still fail with a non-zero exit status, but this would copy more than just stopping at the first error, as can be done with rsync or ddrescue). Note that since we rely on auto-retiring and do NOT call nbd_aio_command_completed, our completion callbacks must always return 1 (if they do not exit() first), even when acting on *error, so as not leave the command allocated until nbd_close. As such, there is no sane way to return an error to a manual caller of the callback, and therefore we can drop dead code that calls perror() and exit() if the callback "failed". It is also worth documenting the contract on when we must manually call the callback during the asynch_zero callback, so that we do not leak or double-free the command; thankfully, all the existing code paths were correct. The added testsuite script demonstrates several scenarios, some of which fail without the rest of this patch in place, and others which showcase ways in which sparse images can bypass errors. Once backports are complete, a followup patch on the main branch will edit docs/libnbd-security.pod with the mailing list announcement of the stable branch commit ids and release versions that incorporate this fix. Reported-by: Nir Soffer <nsoffer@redhat.com> Fixes: bc896eec4d ("copy: Implement multi-conn, multiple threads, multiple requests in flight.", v1.5.6) Fixes: https://bugzilla.redhat.com/2046194 Message-Id: <20220203202558.203013-6-eblake@redhat.com> Acked-by: Richard W.M. Jones <rjones@redhat.com> Acked-by: Nir Soffer <nsoffer@redhat.com> [eblake: fix error message per Nir, tweak requires lines in unit test per Rich] Reviewed-by: Laszlo Ersek <lersek@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static bool load_buffer(RBinFile *bf, void **bin_obj, RBuffer *buf, ut64 loadaddr, Sdb *sdb) { RBuffer *fbuf = r_buf_ref (buf); struct MACH0_(opts_t) opts; MACH0_(opts_set_default) (&opts, bf); struct MACH0_(obj_t) *main_mach0 = MACH0_(new_buf) (fbuf, &opts); if (!main_mach0) { return false; } RRebaseInfo *rebase_info = r_rebase_info_new_from_mach0 (fbuf, main_mach0); RKernelCacheObj *obj = NULL; RPrelinkRange *prelink_range = get_prelink_info_range_from_mach0 (main_mach0); if (!prelink_range) { goto beach; } obj = R_NEW0 (RKernelCacheObj); if (!obj) { R_FREE (prelink_range); goto beach; } RCFValueDict *prelink_info = NULL; if (main_mach0->hdr.filetype != MH_FILESET && prelink_range->range.size) { prelink_info = r_cf_value_dict_parse (fbuf, prelink_range->range.offset, prelink_range->range.size, R_CF_OPTION_SKIP_NSDATA); if (!prelink_info) { R_FREE (prelink_range); R_FREE (obj); goto beach; } } if (!pending_bin_files) { pending_bin_files = r_list_new (); if (!pending_bin_files) { R_FREE (prelink_range); R_FREE (obj); R_FREE (prelink_info); goto beach; } } obj->mach0 = main_mach0; obj->rebase_info = rebase_info; obj->prelink_info = prelink_info; obj->cache_buf = fbuf; obj->pa2va_exec = prelink_range->pa2va_exec; obj->pa2va_data = prelink_range->pa2va_data; R_FREE (prelink_range); *bin_obj = obj; r_list_push (pending_bin_files, bf); if (rebase_info || main_mach0->chained_starts) { RIO *io = bf->rbin->iob.io; swizzle_io_read (obj, io); } return true; beach: r_buf_free (fbuf); obj->cache_buf = NULL; MACH0_(mach0_free) (main_mach0); return false; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix null deref in xnu.kernelcache ##crash * Reported by @xshad3 via huntr.dev'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: RawTile KakaduImage::getRegion( int seq, int ang, unsigned int res, int layers, int x, int y, unsigned int w, unsigned int h ) { // Scale up our output bit depth to the nearest factor of 8 unsigned int obpc = bpc; if( bpc <= 16 && bpc > 8 ) obpc = 16; else if( bpc <= 8 ) obpc = 8; #ifdef DEBUG Timer timer; timer.start(); #endif RawTile rawtile( 0, res, seq, ang, w, h, channels, obpc ); if( obpc == 16 ) rawtile.data = new unsigned short[w*h*channels]; else if( obpc == 8 ) rawtile.data = new unsigned char[w*h*channels]; else throw file_error( "Kakadu :: Unsupported number of bits" ); rawtile.dataLength = w*h*channels*(obpc/8); rawtile.filename = getImagePath(); rawtile.timestamp = timestamp; process( res, layers, x, y, w, h, rawtile.data ); #ifdef DEBUG logfile << "Kakadu :: getRegion() :: " << timer.getTime() << " microseconds" << endl; #endif return rawtile; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': '- Modified TileManager.cc to verify that malloc() has correctly allocated memory. - Updated numerical types to std::size_t in RawTile.h, TileManager.cc, KakaduImage.cc, OpenJPEG.cc and Transforms.cc when allocating memory via new to avoid integer overflow - fixes remaining problems identified in https://github.com/ruven/iipsrv/issues/223.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static char *shell_name_generator(const char *text, int state) { static size_t len; char *s; if (!state) { setusershell(); len = strlen(text); } while ((s = getusershell())) { if (strncmp(s, text, len) == 0) return xstrdup(s); } return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-209'], 'message': 'chsh, chfn: remove readline support [CVE-2022-0563] The readline library uses INPUTRC= environment variable to get a path to the library config file. When the library cannot parse the specified file, it prints an error message containing data from the file. Unfortunately, the library does not use secure_getenv() (or a similar concept) to avoid vulnerabilities that could occur if set-user-ID or set-group-ID programs. Reported-by: Rory Mackie <rory.mackie@trailofbits.com> Signed-off-by: Karel Zak <kzak@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr) { struct dev_data *dev = fd->private_data; ssize_t value, length = len; unsigned total; u32 tag; char *kbuf; spin_lock_irq(&dev->lock); if (dev->state > STATE_DEV_OPENED) { value = ep0_write(fd, buf, len, ptr); spin_unlock_irq(&dev->lock); return value; } spin_unlock_irq(&dev->lock); if ((len < (USB_DT_CONFIG_SIZE + USB_DT_DEVICE_SIZE + 4)) || (len > PAGE_SIZE * 4)) return -EINVAL; /* we might need to change message format someday */ if (copy_from_user (&tag, buf, 4)) return -EFAULT; if (tag != 0) return -EINVAL; buf += 4; length -= 4; kbuf = memdup_user(buf, length); if (IS_ERR(kbuf)) return PTR_ERR(kbuf); spin_lock_irq (&dev->lock); value = -EINVAL; if (dev->buf) { spin_unlock_irq(&dev->lock); kfree(kbuf); return value; } dev->buf = kbuf; /* full or low speed config */ dev->config = (void *) kbuf; total = le16_to_cpu(dev->config->wTotalLength); if (!is_valid_config(dev->config, total) || total > length - USB_DT_DEVICE_SIZE) goto fail; kbuf += total; length -= total; /* optional high speed config */ if (kbuf [1] == USB_DT_CONFIG) { dev->hs_config = (void *) kbuf; total = le16_to_cpu(dev->hs_config->wTotalLength); if (!is_valid_config(dev->hs_config, total) || total > length - USB_DT_DEVICE_SIZE) goto fail; kbuf += total; length -= total; } else { dev->hs_config = NULL; } /* could support multiple configs, using another encoding! */ /* device descriptor (tweaked for paranoia) */ if (length != USB_DT_DEVICE_SIZE) goto fail; dev->dev = (void *)kbuf; if (dev->dev->bLength != USB_DT_DEVICE_SIZE || dev->dev->bDescriptorType != USB_DT_DEVICE || dev->dev->bNumConfigurations != 1) goto fail; dev->dev->bcdUSB = cpu_to_le16 (0x0200); /* triggers gadgetfs_bind(); then we can enumerate. */ spin_unlock_irq (&dev->lock); if (dev->hs_config) gadgetfs_driver.max_speed = USB_SPEED_HIGH; else gadgetfs_driver.max_speed = USB_SPEED_FULL; value = usb_gadget_probe_driver(&gadgetfs_driver); if (value != 0) { kfree (dev->buf); dev->buf = NULL; } else { /* at this point "good" hardware has for the first time * let the USB the host see us. alternatively, if users * unplug/replug that will clear all the error state. * * note: everything running before here was guaranteed * to choke driver model style diagnostics. from here * on, they can work ... except in cleanup paths that * kick in after the ep0 descriptor is closed. */ value = len; dev->gadget_registered = true; } return value; fail: spin_unlock_irq (&dev->lock); pr_debug ("%s: %s fail %zd, %p\n", shortname, __func__, value, dev); kfree (dev->buf); dev->buf = NULL; return value; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-763'], 'message': 'usb: gadget: clear related members when goto fail dev->config and dev->hs_config and dev->dev need to be cleaned if dev_config fails to avoid UAF. Acked-by: Alan Stern <stern@rowland.harvard.edu> Signed-off-by: Hangyu Hua <hbh25y@gmail.com> Link: https://lore.kernel.org/r/20211231172138.7993-3-hbh25y@gmail.com Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: R_API RBinJavaAttrInfo *r_bin_java_inner_classes_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) { RBinJavaClassesAttribute *icattr; RBinJavaAttrInfo *attr = NULL; RBinJavaCPTypeObj *obj; ut32 i = 0; ut64 offset = 0, curpos; attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset); offset += 6; if (buf_offset + offset + 8 > sz) { eprintf ("Invalid amount of inner classes\n"); return NULL; } if (attr == NULL) { // TODO eprintf return attr; } attr->type = R_BIN_JAVA_ATTR_TYPE_INNER_CLASSES_ATTR; attr->info.inner_classes_attr.number_of_classes = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; attr->info.inner_classes_attr.classes = r_list_newf (r_bin_java_inner_classes_attr_entry_free); for (i = 0; i < attr->info.inner_classes_attr.number_of_classes; i++) { curpos = buf_offset + offset; if (buf_offset + offset + 8 > sz) { eprintf ("Invalid amount of inner classes\n"); break; } icattr = R_NEW0 (RBinJavaClassesAttribute); if (!icattr) { break; } icattr->inner_class_info_idx = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; icattr->outer_class_info_idx = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; icattr->inner_name_idx = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; icattr->inner_class_access_flags = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; icattr->flags_str = retrieve_class_method_access_string (icattr->inner_class_access_flags); icattr->file_offset = curpos; icattr->size = 8; obj = r_bin_java_get_item_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, icattr->inner_name_idx); if (!obj) { eprintf ("BINCPLIS IS HULL %d\n", icattr->inner_name_idx); } icattr->name = r_bin_java_get_item_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, obj); if (!icattr->name) { obj = r_bin_java_get_item_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, icattr->inner_class_info_idx); if (!obj) { eprintf ("BINCPLIST IS NULL %d\n", icattr->inner_class_info_idx); } icattr->name = r_bin_java_get_item_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, obj); if (!icattr->name) { icattr->name = r_str_dup (NULL, "NULL"); eprintf ("r_bin_java_inner_classes_attr: Unable to find the name for %d index.\n", icattr->inner_name_idx); free (icattr); break; } } IFDBG eprintf ("r_bin_java_inner_classes_attr: Inner class name %d is %s.\n", icattr->inner_name_idx, icattr->name); r_list_append (attr->info.inner_classes_attr.classes, (void *) icattr); } attr->size = offset; // IFDBG r_bin_java_print_inner_classes_attr_summary(attr); return attr; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-788'], 'message': 'Improve boundary checks to fix oobread segfaults ##crash * Reported by Cen Zhang via huntr.dev * Reproducer: bins/fuzzed/javaoob-havoc.class'</s>
<s>[INST] Given the following code containing errors, provide 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 RBinJavaVerificationObj *r_bin_java_verification_info_from_type(RBinJavaObj *bin, R_BIN_JAVA_STACKMAP_TYPE type, ut32 value) { RBinJavaVerificationObj *se = R_NEW0 (RBinJavaVerificationObj); if (!se) { return NULL; } se->tag = type; if (se->tag == R_BIN_JAVA_STACKMAP_OBJECT) { se->info.obj_val_cp_idx = (ut16) value; } else if (se->tag == R_BIN_JAVA_STACKMAP_UNINIT) { /*if (bin->offset_sz == 4) { se->info.uninit_offset = value; } else { se->info.uninit_offset = (ut16) value; }*/ se->info.uninit_offset = (ut16) value; } return se; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-788'], 'message': 'Improve boundary checks to fix oobread segfaults ##crash * Reported by Cen Zhang via huntr.dev * Reproducer: bins/fuzzed/javaoob-havoc.class'</s>
<s>[INST] Given the following code containing errors, provide 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 pyc_object *get_set_object(RBuffer *buffer) { pyc_object *ret = NULL; bool error = false; ut32 n = get_ut32 (buffer, &error); if (n > ST32_MAX) { eprintf ("bad marshal data (set size out of range)\n"); return NULL; } if (error) { return NULL; } ret = get_array_object_generic (buffer, n); if (!ret) { return NULL; } ret->type = TYPE_SET; return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-825'], 'message': 'Fix UAF in pyc parser ##crash * Reported by Cen Zhang via huntr.dev * Reproducer: bins/fuzzed/harep2.pyc'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: copyString(const XML_Char *s, const XML_Memory_Handling_Suite *memsuite) { int charsRequired = 0; XML_Char *result; /* First determine how long the string is */ while (s[charsRequired] != 0) { charsRequired++; } /* Include the terminator */ charsRequired++; /* Now allocate space for the copy */ result = memsuite->malloc_fcn(charsRequired * sizeof(XML_Char)); if (result == NULL) return NULL; /* Copy the original into place */ memcpy(result, s, charsRequired * sizeof(XML_Char)); return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-787'], 'message': 'Prevent integer overflow in copyString The copyString function is only used for encoding string supplied by the library user.'</s>
<s>[INST] Given the following code containing errors, provide 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 RList *create_cache_bins(RBinFile *bf, RDyldCache *cache) { RList *bins = r_list_newf ((RListFree)free_bin); if (!bins) { return NULL; } char *target_libs = NULL; RList *target_lib_names = NULL; int *deps = NULL; target_libs = r_sys_getenv ("R_DYLDCACHE_FILTER"); if (target_libs) { target_lib_names = r_str_split_list (target_libs, ":", 0); if (!target_lib_names) { r_list_free (bins); return NULL; } deps = R_NEWS0 (int, cache->hdr->imagesCount); if (!deps) { r_list_free (bins); r_list_free (target_lib_names); return NULL; } } ut32 i; for (i = 0; i < cache->n_hdr; i++) { cache_hdr_t *hdr = &cache->hdr[i]; ut64 hdr_offset = cache->hdr_offset[i]; ut32 maps_index = cache->maps_index[i]; cache_img_t *img = read_cache_images (cache->buf, hdr, hdr_offset); if (!img) { goto next; } ut32 j; ut16 *depArray = NULL; cache_imgxtr_t *extras = NULL; if (target_libs) { HtPU *path_to_idx = NULL; if (cache->accel) { depArray = R_NEWS0 (ut16, cache->accel->depListCount); if (!depArray) { goto next; } if (r_buf_fread_at (cache->buf, cache->accel->depListOffset, (ut8*) depArray, "s", cache->accel->depListCount) != cache->accel->depListCount * 2) { goto next; } extras = read_cache_imgextra (cache->buf, hdr, cache->accel); if (!extras) { goto next; } } else { path_to_idx = create_path_to_index (cache->buf, img, hdr); } for (j = 0; j < hdr->imagesCount; j++) { bool printing = !deps[j]; char *lib_name = get_lib_name (cache->buf, &img[j]); if (!lib_name) { break; } if (strstr (lib_name, "libobjc.A.dylib")) { deps[j]++; } if (!r_list_find (target_lib_names, lib_name, string_contains)) { R_FREE (lib_name); continue; } if (printing) { eprintf ("FILTER: %s\n", lib_name); } R_FREE (lib_name); deps[j]++; if (extras && depArray) { ut32 k; for (k = extras[j].dependentsStartArrayIndex; depArray[k] != 0xffff; k++) { ut16 dep_index = depArray[k] & 0x7fff; deps[dep_index]++; char *dep_name = get_lib_name (cache->buf, &img[dep_index]); if (!dep_name) { break; } if (printing) { eprintf ("-> %s\n", dep_name); } free (dep_name); } } else if (path_to_idx) { carve_deps_at_address (cache, img, path_to_idx, img[j].address, deps, printing); } } ht_pu_free (path_to_idx); R_FREE (depArray); R_FREE (extras); } for (j = 0; j < hdr->imagesCount; j++) { if (deps && !deps[j]) { continue; } ut64 pa = va2pa (img[j].address, hdr->mappingCount, &cache->maps[maps_index], cache->buf, 0, NULL, NULL); if (pa == UT64_MAX) { continue; } ut8 magicbytes[4]; r_buf_read_at (cache->buf, pa, magicbytes, 4); int magic = r_read_le32 (magicbytes); switch (magic) { case MH_MAGIC_64: { char file[256]; RDyldBinImage *bin = R_NEW0 (RDyldBinImage); if (!bin) { goto next; } bin->header_at = pa; bin->hdr_offset = hdr_offset; bin->symbols_off = resolve_symbols_off (cache, pa); bin->va = img[j].address; if (r_buf_read_at (cache->buf, img[j].pathFileOffset, (ut8*) &file, sizeof (file)) == sizeof (file)) { file[255] = 0; char *last_slash = strrchr (file, '/'); if (last_slash && *last_slash) { if (last_slash > file) { char *scan = last_slash - 1; while (scan > file && *scan != '/') { scan--; } if (*scan == '/') { bin->file = strdup (scan + 1); } else { bin->file = strdup (last_slash + 1); } } else { bin->file = strdup (last_slash + 1); } } else { bin->file = strdup (file); } } r_list_append (bins, bin); break; } default: eprintf ("Unknown sub-bin\n"); break; } } next: R_FREE (depArray); R_FREE (extras); R_FREE (img); } if (r_list_empty (bins)) { r_list_free (bins); bins = NULL; } R_FREE (deps); R_FREE (target_libs); r_list_free (target_lib_names); return bins; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix heap buffer overflow in dyldcache parser ##crash * Reported by: Lazymio via huntr.dev * Reproducer: dyldovf'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: struct nft_flow_rule *nft_flow_rule_create(struct net *net, const struct nft_rule *rule) { struct nft_offload_ctx *ctx; struct nft_flow_rule *flow; int num_actions = 0, err; struct nft_expr *expr; expr = nft_expr_first(rule); while (nft_expr_more(rule, expr)) { if (expr->ops->offload_flags & NFT_OFFLOAD_F_ACTION) num_actions++; expr = nft_expr_next(expr); } if (num_actions == 0) return ERR_PTR(-EOPNOTSUPP); flow = nft_flow_rule_alloc(num_actions); if (!flow) return ERR_PTR(-ENOMEM); expr = nft_expr_first(rule); ctx = kzalloc(sizeof(struct nft_offload_ctx), GFP_KERNEL); if (!ctx) { err = -ENOMEM; goto err_out; } ctx->net = net; ctx->dep.type = NFT_OFFLOAD_DEP_UNSPEC; while (nft_expr_more(rule, expr)) { if (!expr->ops->offload) { err = -EOPNOTSUPP; goto err_out; } err = expr->ops->offload(ctx, flow, expr); if (err < 0) goto err_out; expr = nft_expr_next(expr); } nft_flow_rule_transfer_vlan(ctx, flow); flow->proto = ctx->dep.l3num; kfree(ctx); return flow; err_out: kfree(ctx); nft_flow_rule_destroy(flow); return ERR_PTR(err); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-269'], 'message': 'netfilter: nf_tables_offload: incorrect flow offload action array size immediate verdict expression needs to allocate one slot in the flow offload action array, however, immediate data expression does not need to do so. fwd and dup expression need to allocate one slot, this is missing. Add a new offload_action interface to report if this expression needs to allocate one slot in the flow offload action array. Fixes: be2861dc36d7 ("netfilter: nft_{fwd,dup}_netdev: add offload support") Reported-and-tested-by: Nick Gregory <Nick.Gregory@Sophos.com> Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: RCoreSymCacheElement *r_coresym_cache_element_new(RBinFile *bf, RBuffer *buf, ut64 off, int bits, char * file_name) { RCoreSymCacheElement *result = NULL; ut8 *b = NULL; RCoreSymCacheElementHdr *hdr = r_coresym_cache_element_header_new (buf, off, bits); if (!hdr) { return NULL; } if (hdr->version != 1) { eprintf ("Unsupported CoreSymbolication cache version (%d)\n", hdr->version); goto beach; } if (hdr->size == 0 || hdr->size > r_buf_size (buf) - off) { eprintf ("Corrupted CoreSymbolication header: size out of bounds (0x%x)\n", hdr->size); goto beach; } result = R_NEW0 (RCoreSymCacheElement); if (!result) { goto beach; } result->hdr = hdr; b = malloc (hdr->size); if (!b) { goto beach; } if (r_buf_read_at (buf, off, b, hdr->size) != hdr->size) { goto beach; } ut8 *end = b + hdr->size; if (file_name) { result->file_name = file_name; } else if (hdr->file_name_off) { result->file_name = str_dup_safe (b, b + (size_t)hdr->file_name_off, end); } if (hdr->version_off) { result->binary_version = str_dup_safe (b, b + (size_t)hdr->version_off, end); } const size_t word_size = bits / 8; const ut64 start_of_sections = (ut64)hdr->n_segments * R_CS_EL_SIZE_SEG + R_CS_EL_OFF_SEGS; const ut64 sect_size = (bits == 32) ? R_CS_EL_SIZE_SECT_32 : R_CS_EL_SIZE_SECT_64; const ut64 start_of_symbols = start_of_sections + (ut64)hdr->n_sections * sect_size; const ut64 start_of_lined_symbols = start_of_symbols + (ut64)hdr->n_symbols * R_CS_EL_SIZE_SYM; const ut64 start_of_line_info = start_of_lined_symbols + (ut64)hdr->n_lined_symbols * R_CS_EL_SIZE_LSYM; const ut64 start_of_unknown_pairs = start_of_line_info + (ut64)hdr->n_line_info * R_CS_EL_SIZE_LINFO; const ut64 start_of_strings = start_of_unknown_pairs + (ut64)hdr->n_symbols * 8; ut64 page_zero_size = 0; size_t page_zero_idx = 0; if (UT32_MUL_OVFCHK (hdr->n_segments, sizeof (RCoreSymCacheElementSegment))) { goto beach; } else if (UT32_MUL_OVFCHK (hdr->n_sections, sizeof (RCoreSymCacheElementSection))) { goto beach; } else if (UT32_MUL_OVFCHK (hdr->n_symbols, sizeof (RCoreSymCacheElementSymbol))) { goto beach; } else if (UT32_MUL_OVFCHK (hdr->n_lined_symbols, sizeof (RCoreSymCacheElementLinedSymbol))) { goto beach; } else if (UT32_MUL_OVFCHK (hdr->n_line_info, sizeof (RCoreSymCacheElementLineInfo))) { goto beach; } if (hdr->n_segments > 0) { result->segments = R_NEWS0 (RCoreSymCacheElementSegment, hdr->n_segments); if (!result->segments) { goto beach; } size_t i; ut8 *cursor = b + R_CS_EL_OFF_SEGS; for (i = 0; i < hdr->n_segments && cursor < end; i++) { RCoreSymCacheElementSegment *seg = &result->segments[i]; seg->paddr = seg->vaddr = r_read_le64 (cursor); cursor += 8; if (cursor >= end) { break; } seg->size = seg->vsize = r_read_le64 (cursor); cursor += 8; if (cursor >= end) { break; } seg->name = str_dup_safe_fixed (b, cursor, 16, end); cursor += 16; if (!seg->name) { continue; } if (!strcmp (seg->name, "__PAGEZERO")) { page_zero_size = seg->size; page_zero_idx = i; seg->paddr = seg->vaddr = 0; seg->size = 0; } } for (i = 0; i < hdr->n_segments && page_zero_size > 0; i++) { if (i == page_zero_idx) { continue; } RCoreSymCacheElementSegment *seg = &result->segments[i]; if (seg->vaddr < page_zero_size) { seg->vaddr += page_zero_size; } } } bool relative_to_strings = false; ut8* string_origin; if (hdr->n_sections > 0) { result->sections = R_NEWS0 (RCoreSymCacheElementSection, hdr->n_sections); if (!result->sections) { goto beach; } size_t i; ut8 *cursor = b + start_of_sections; for (i = 0; i < hdr->n_sections && cursor < end; i++) { ut8 *sect_start = cursor; RCoreSymCacheElementSection *sect = &result->sections[i]; sect->vaddr = sect->paddr = r_read_ble (cursor, false, bits); if (sect->vaddr < page_zero_size) { sect->vaddr += page_zero_size; } cursor += word_size; if (cursor >= end) { break; } sect->size = r_read_ble (cursor, false, bits); cursor += word_size; if (cursor >= end) { break; } ut64 sect_name_off = r_read_ble (cursor, false, bits); if (!i && !sect_name_off) { relative_to_strings = true; } cursor += word_size; if (bits == 32) { cursor += word_size; } string_origin = relative_to_strings? b + start_of_strings : sect_start; sect->name = str_dup_safe (b, string_origin + (size_t)sect_name_off, end); } } if (hdr->n_symbols) { result->symbols = R_NEWS0 (RCoreSymCacheElementSymbol, hdr->n_symbols); if (!result->symbols) { goto beach; } size_t i; ut8 *cursor = b + start_of_symbols; for (i = 0; i < hdr->n_symbols && cursor + R_CS_EL_SIZE_SYM <= end; i++) { RCoreSymCacheElementSymbol *sym = &result->symbols[i]; sym->paddr = r_read_le32 (cursor); sym->size = r_read_le32 (cursor + 0x4); sym->unk1 = r_read_le32 (cursor + 0x8); size_t name_off = r_read_le32 (cursor + 0xc); size_t mangled_name_off = r_read_le32 (cursor + 0x10); sym->unk2 = (st32)r_read_le32 (cursor + 0x14); string_origin = relative_to_strings? b + start_of_strings : cursor; sym->name = str_dup_safe (b, string_origin + name_off, end); if (!sym->name) { cursor += R_CS_EL_SIZE_SYM; continue; } string_origin = relative_to_strings? b + start_of_strings : cursor; sym->mangled_name = str_dup_safe (b, string_origin + mangled_name_off, end); if (!sym->mangled_name) { cursor += R_CS_EL_SIZE_SYM; continue; } cursor += R_CS_EL_SIZE_SYM; } } if (hdr->n_lined_symbols) { result->lined_symbols = R_NEWS0 (RCoreSymCacheElementLinedSymbol, hdr->n_lined_symbols); if (!result->lined_symbols) { goto beach; } size_t i; ut8 *cursor = b + start_of_lined_symbols; for (i = 0; i < hdr->n_lined_symbols && cursor + R_CS_EL_SIZE_LSYM <= end; i++) { RCoreSymCacheElementLinedSymbol *lsym = &result->lined_symbols[i]; lsym->sym.paddr = r_read_le32 (cursor); lsym->sym.size = r_read_le32 (cursor + 0x4); lsym->sym.unk1 = r_read_le32 (cursor + 0x8); size_t name_off = r_read_le32 (cursor + 0xc); size_t mangled_name_off = r_read_le32 (cursor + 0x10); lsym->sym.unk2 = (st32)r_read_le32 (cursor + 0x14); size_t file_name_off = r_read_le32 (cursor + 0x18); lsym->flc.line = r_read_le32 (cursor + 0x1c); lsym->flc.col = r_read_le32 (cursor + 0x20); string_origin = relative_to_strings? b + start_of_strings : cursor; lsym->sym.name = str_dup_safe (b, string_origin + name_off, end); if (!lsym->sym.name) { cursor += R_CS_EL_SIZE_LSYM; continue; } string_origin = relative_to_strings? b + start_of_strings : cursor; lsym->sym.mangled_name = str_dup_safe (b, string_origin + mangled_name_off, end); if (!lsym->sym.mangled_name) { cursor += R_CS_EL_SIZE_LSYM; continue; } string_origin = relative_to_strings? b + start_of_strings : cursor; lsym->flc.file = str_dup_safe (b, string_origin + file_name_off, end); if (!lsym->flc.file) { cursor += R_CS_EL_SIZE_LSYM; continue; } cursor += R_CS_EL_SIZE_LSYM; meta_add_fileline (bf, r_coresym_cache_element_pa2va (result, lsym->sym.paddr), lsym->sym.size, &lsym->flc); } } if (hdr->n_line_info) { result->line_info = R_NEWS0 (RCoreSymCacheElementLineInfo, hdr->n_line_info); if (!result->line_info) { goto beach; } size_t i; ut8 *cursor = b + start_of_line_info; for (i = 0; i < hdr->n_line_info && cursor + R_CS_EL_SIZE_LINFO <= end; i++) { RCoreSymCacheElementLineInfo *info = &result->line_info[i]; info->paddr = r_read_le32 (cursor); info->size = r_read_le32 (cursor + 4); size_t file_name_off = r_read_le32 (cursor + 8); info->flc.line = r_read_le32 (cursor + 0xc); info->flc.col = r_read_le32 (cursor + 0x10); string_origin = relative_to_strings? b + start_of_strings : cursor; info->flc.file = str_dup_safe (b, string_origin + file_name_off, end); if (!info->flc.file) { break; } cursor += R_CS_EL_SIZE_LINFO; meta_add_fileline (bf, r_coresym_cache_element_pa2va (result, info->paddr), info->size, &info->flc); } } /* * TODO: * Figure out the meaning of the 2 arrays of hdr->n_symbols * 32-bit integers located at the end of line info. * Those are the last info before the strings at the end. */ beach: free (b); return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Fix oobread in macho core symbolication ##crash * Reported by @cnitlrt via huntr.dev'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: struct r_bin_pe_addr_t *PE_(check_unknow)(RBinPEObj *pe) { struct r_bin_pe_addr_t *entry; if (!pe || !pe->b) { return 0LL; } ut8 b[512]; ZERO_FILL (b); entry = PE_ (r_bin_pe_get_entrypoint) (pe); // option2: /x 8bff558bec83ec20 if (r_buf_read_at (pe->b, entry->paddr, b, 512) < 1) { pe_printf ("Warning: Cannot read entry at 0x%08"PFMT64x"\n", entry->paddr); free (entry); return NULL; } /* Decode the jmp instruction, this gets the address of the 'main' function for PE produced by a compiler whose name someone forgot to write down. */ // this is dirty only a single byte check, can return false positives if (b[367] == 0xe8) { follow_offset (entry, pe->b, b, sizeof (b), pe->big_endian, 367); return entry; } size_t i; for (i = 0; i < 512 - 16 ; i++) { // 5. ff 15 .. .. .. .. 50 e8 [main] if (!memcmp (b + i, "\xff\x15", 2)) { if (b[i + 6] == 0x50) { if (b[i + 7] == 0xe8) { follow_offset (entry, pe->b, b, sizeof (b), pe->big_endian, i + 7); return entry; } } } } free (entry); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Fix DoS in PE/QNX/DYLDCACHE/PSX parsers ##crash * Reported by lazymio * Reproducer: AAA4AAAAAB4='</s>
<s>[INST] Given the following code containing errors, provide 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 st64 buf_format(RBuffer *dst, RBuffer *src, const char *fmt, int n) { st64 res = 0; int i; for (i = 0; i < n; i++) { int j; int m = 1; int tsize = 2; bool bigendian = true; for (j = 0; fmt[j]; j++) { switch (fmt[j]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (m == 1) { m = r_num_get (NULL, &fmt[j]); } continue; case 's': tsize = 2; bigendian = false; break; case 'S': tsize = 2; bigendian = true; break; case 'i': tsize = 4; bigendian = false; break; case 'I': tsize = 4; bigendian = true; break; case 'l': tsize = 8; bigendian = false; break; case 'L': tsize = 8; bigendian = true; break; case 'c': tsize = 1; bigendian = false; break; default: return -1; } int k; for (k = 0; k < m; k++) { ut8 tmp[sizeof (ut64)]; ut8 d1; ut16 d2; ut32 d3; ut64 d4; st64 r = r_buf_read (src, tmp, tsize); if (r < tsize) { return -1; } switch (tsize) { case 1: d1 = r_read_ble8 (tmp); r = r_buf_write (dst, (ut8 *)&d1, 1); break; case 2: d2 = r_read_ble16 (tmp, bigendian); r = r_buf_write (dst, (ut8 *)&d2, 2); break; case 4: d3 = r_read_ble32 (tmp, bigendian); r = r_buf_write (dst, (ut8 *)&d3, 4); break; case 8: d4 = r_read_ble64 (tmp, bigendian); r = r_buf_write (dst, (ut8 *)&d4, 8); break; } if (r < 0) { return -1; } res += r; } m = 1; } } return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Fix DoS in PE/QNX/DYLDCACHE/PSX parsers ##crash * Reported by lazymio * Reproducer: AAA4AAAAAB4='</s>
<s>[INST] Given the following code containing errors, provide 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 rndis_set_response(struct rndis_params *params, rndis_set_msg_type *buf) { u32 BufLength, BufOffset; rndis_set_cmplt_type *resp; rndis_resp_t *r; r = rndis_add_response(params, sizeof(rndis_set_cmplt_type)); if (!r) return -ENOMEM; resp = (rndis_set_cmplt_type *)r->buf; BufLength = le32_to_cpu(buf->InformationBufferLength); BufOffset = le32_to_cpu(buf->InformationBufferOffset); #ifdef VERBOSE_DEBUG pr_debug("%s: Length: %d\n", __func__, BufLength); pr_debug("%s: Offset: %d\n", __func__, BufOffset); pr_debug("%s: InfoBuffer: ", __func__); for (i = 0; i < BufLength; i++) { pr_debug("%02x ", *(((u8 *) buf) + i + 8 + BufOffset)); } pr_debug("\n"); #endif resp->MessageType = cpu_to_le32(RNDIS_MSG_SET_C); resp->MessageLength = cpu_to_le32(16); resp->RequestID = buf->RequestID; /* Still LE in msg buffer */ if (gen_ndis_set_resp(params, le32_to_cpu(buf->OID), ((u8 *)buf) + 8 + BufOffset, BufLength, r)) resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED); else resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS); params->resp_avail(params->v); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-668'], 'message': 'usb: gadget: rndis: check size of RNDIS_MSG_SET command Check the size of the RNDIS_MSG_SET command given to us before attempting to respond to an invalid message size. Reported-by: Szymon Heidrich <szymon.heidrich@gmail.com> Cc: stable@kernel.org Tested-by: Szymon Heidrich <szymon.heidrich@gmail.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static loff_t find_tree_dqentry(struct qtree_mem_dqinfo *info, struct dquot *dquot, uint blk, int depth) { char *buf = kmalloc(info->dqi_usable_bs, GFP_NOFS); loff_t ret = 0; __le32 *ref = (__le32 *)buf; if (!buf) return -ENOMEM; ret = read_blk(info, blk, buf); if (ret < 0) { quota_error(dquot->dq_sb, "Can't read quota tree block %u", blk); goto out_buf; } ret = 0; blk = le32_to_cpu(ref[get_index(info, dquot->dq_id, depth)]); if (!blk) /* No reference? */ goto out_buf; if (depth < info->dqi_qtree_depth - 1) ret = find_tree_dqentry(info, dquot, blk, depth+1); else ret = find_block_dqentry(info, dquot, blk); out_buf: kfree(buf); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'quota: check block number when reading the block in quota file The block number in the quota tree on disk should be smaller than the v2_disk_dqinfo.dqi_blocks. If the quota file was corrupted, we may be allocating an 'allocated' block and that would lead to a loop in a tree, which will probably trigger oops later. This patch adds a check for the block number in the quota tree to prevent such potential issue. Link: https://lore.kernel.org/r/20211008093821.1001186-2-yi.zhang@huawei.com Signed-off-by: Zhang Yi <yi.zhang@huawei.com> Cc: stable@kernel.org Signed-off-by: Jan Kara <jack@suse.cz>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: local block_state deflate_slow(s, flush) deflate_state *s; int flush; { IPos hash_head; /* head of hash chain */ int bflush; /* set if current block must be flushed */ /* Process the input block. */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s->lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { return need_more; } if (s->lookahead == 0) break; /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = NIL; if (s->lookahead >= MIN_MATCH) { INSERT_STRING(s, s->strstart, hash_head); } /* Find the longest match, discarding those <= prev_length. */ s->prev_length = s->match_length, s->prev_match = s->match_start; s->match_length = MIN_MATCH-1; if (hash_head != NIL && s->prev_length < s->max_lazy_match && s->strstart - hash_head <= MAX_DIST(s)) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s->match_length = longest_match (s, hash_head); /* longest_match() sets match_start */ if (s->match_length <= 5 && (s->strategy == Z_FILTERED #if TOO_FAR <= 32767 || (s->match_length == MIN_MATCH && s->strstart - s->match_start > TOO_FAR) #endif )) { /* If prev_match is also MIN_MATCH, match_start is garbage * but we will ignore the current match anyway. */ s->match_length = MIN_MATCH-1; } } /* If there was a match at the previous step and the current * match is not better, output the previous match: */ if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; /* Do not insert strings in hash table beyond this. */ check_match(s, s->strstart-1, s->prev_match, s->prev_length); _tr_tally_dist(s, s->strstart -1 - s->prev_match, s->prev_length - MIN_MATCH, bflush); /* Insert in hash table all strings up to the end of the match. * strstart-1 and strstart are already inserted. If there is not * enough lookahead, the last two strings are not inserted in * the hash table. */ s->lookahead -= s->prev_length-1; s->prev_length -= 2; do { if (++s->strstart <= max_insert) { INSERT_STRING(s, s->strstart, hash_head); } } while (--s->prev_length != 0); s->match_available = 0; s->match_length = MIN_MATCH-1; s->strstart++; if (bflush) FLUSH_BLOCK(s, 0); } else if (s->match_available) { /* If there was no match at the previous position, output a * single literal. If there was a match but the current match * is longer, truncate the previous match to a single literal. */ Tracevv((stderr,"%c", s->window[s->strstart-1])); _tr_tally_lit(s, s->window[s->strstart-1], bflush); if (bflush) { FLUSH_BLOCK_ONLY(s, 0); } s->strstart++; s->lookahead--; if (s->strm->avail_out == 0) return need_more; } else { /* There is no previous match to compare with, wait for * the next step to decide. */ s->match_available = 1; s->strstart++; s->lookahead--; } } Assert (flush != Z_NO_FLUSH, "no flush?"); if (s->match_available) { Tracevv((stderr,"%c", s->window[s->strstart-1])); _tr_tally_lit(s, s->window[s->strstart-1], bflush); s->match_available = 0; } s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; if (flush == Z_FINISH) { FLUSH_BLOCK(s, 1); return finish_done; } if (s->last_lit) FLUSH_BLOCK(s, 0); return block_done; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-787'], 'message': 'Fix a bug that can crash deflate on some input when using Z_FIXED. This bug was reported by Danilo Ramos of Eideticom, Inc. It has lain in wait 13 years before being found! The bug was introduced in zlib 1.2.2.2, with the addition of the Z_FIXED option. That option forces the use of fixed Huffman codes. For rare inputs with a large number of distant matches, the pending buffer into which the compressed data is written can overwrite the distance symbol table which it overlays. That results in corrupted output due to invalid distances, and can result in out-of-bound accesses, crashing the application. The fix here combines the distance buffer and literal/length buffers into a single symbol buffer. Now three bytes of pending buffer space are opened up for each literal or length/distance pair consumed, instead of the previous two bytes. This assures that the pending buffer cannot overwrite the symbol table, since the maximum fixed code compressed length/distance is 31 bits, and since there are four bytes of pending space for every three bytes of symbol space.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: struct MACH0_(obj_t) { struct MACH0_(mach_header) hdr; struct MACH0_(segment_command) *segs; char *intrp; char *compiler; int nsegs; struct r_dyld_chained_starts_in_segment **chained_starts; struct dyld_chained_fixups_header fixups_header; ut64 fixups_offset; ut64 fixups_size; struct MACH0_(section) *sects; int nsects; struct MACH0_(nlist) *symtab; ut8 *symstr; ut8 *func_start; //buffer that hold the data from LC_FUNCTION_STARTS int symstrlen; int nsymtab; ut32 *indirectsyms; int nindirectsyms; RBinImport **imports_by_ord; size_t imports_by_ord_size; HtPP *imports_by_name; struct dysymtab_command dysymtab; struct load_command main_cmd; struct dyld_info_command *dyld_info; struct dylib_table_of_contents *toc; int ntoc; struct MACH0_(dylib_module) *modtab; int nmodtab; struct thread_command thread; ut8 *signature; union { struct x86_thread_state32 x86_32; struct x86_thread_state64 x86_64; struct ppc_thread_state32 ppc_32; struct ppc_thread_state64 ppc_64; struct arm_thread_state32 arm_32; struct arm_thread_state64 arm_64; } thread_state; char (*libs)[R_BIN_MACH0_STRING_LENGTH]; int nlibs; int size; ut64 baddr; ut64 entry; bool big_endian; const char *file; RBuffer *b; int os; Sdb *kv; int has_crypto; int has_canary; int has_retguard; int has_sanitizers; int has_blocks_ext; int dbg_info; const char *lang; int uuidn; int func_size; bool verbose; ut64 header_at; ut64 symbols_off; void *user; ut64 (*va2pa)(ut64 p, ut32 *offset, ut32 *left, RBinFile *bf); struct symbol_t *symbols; ut64 main_addr; int (*original_io_read)(RIO *io, RIODesc *fd, ut8 *buf, int count); bool rebasing_buffer; }; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Fix heap OOB read in macho.iterate_chained_fixups ##crash * Reported by peacock-doris via huntr.dev * Reproducer 'tests_65305' mrmacete: * Return early if segs_count is 0 * Initialize segs_count also for reconstructed fixups Co-authored-by: pancake <pancake@nopcode.org> Co-authored-by: Francesco Tamagni <mrmacete@protonmail.ch>'</s>
<s>[INST] Given the following code containing errors, provide 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 stimer_set_config(struct kvm_vcpu_hv_stimer *stimer, u64 config, bool host) { union hv_stimer_config new_config = {.as_uint64 = config}, old_config = {.as_uint64 = stimer->config.as_uint64}; struct kvm_vcpu *vcpu = hv_stimer_to_vcpu(stimer); struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu); struct kvm_vcpu_hv_synic *synic = to_hv_synic(vcpu); if (!synic->active && !host) return 1; if (unlikely(!host && hv_vcpu->enforce_cpuid && new_config.direct_mode && !(hv_vcpu->cpuid_cache.features_edx & HV_STIMER_DIRECT_MODE_AVAILABLE))) return 1; trace_kvm_hv_stimer_set_config(hv_stimer_to_vcpu(stimer)->vcpu_id, stimer->index, config, host); stimer_cleanup(stimer); if (old_config.enable && !new_config.direct_mode && new_config.sintx == 0) new_config.enable = 0; stimer->config.as_uint64 = new_config.as_uint64; if (stimer->config.enable) stimer_mark_pending(stimer, false); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'KVM: x86: Forbid VMM to set SYNIC/STIMER MSRs when SynIC wasn't activated Setting non-zero values to SYNIC/STIMER MSRs activates certain features, this should not happen when KVM_CAP_HYPERV_SYNIC{,2} was not activated. Note, it would've been better to forbid writing anything to SYNIC/STIMER MSRs, including zeroes, however, at least QEMU tries clearing HV_X64_MSR_STIMER0_CONFIG without SynIC. HV_X64_MSR_EOM MSR is somewhat 'special' as writing zero there triggers an action, this also should not happen when SynIC wasn't activated. Signed-off-by: Vitaly Kuznetsov <vkuznets@redhat.com> Message-Id: <20220325132140.25650-4-vkuznets@redhat.com> Cc: stable@vger.kernel.org Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void ax25_kill_by_device(struct net_device *dev) { ax25_dev *ax25_dev; ax25_cb *s; struct sock *sk; if ((ax25_dev = ax25_dev_ax25dev(dev)) == NULL) return; spin_lock_bh(&ax25_list_lock); again: ax25_for_each(s, &ax25_list) { if (s->ax25_dev == ax25_dev) { sk = s->sk; sock_hold(sk); spin_unlock_bh(&ax25_list_lock); lock_sock(sk); s->ax25_dev = NULL; dev_put_track(ax25_dev->dev, &ax25_dev->dev_tracker); ax25_dev_put(ax25_dev); ax25_disconnect(s, ENETUNREACH); release_sock(sk); spin_lock_bh(&ax25_list_lock); sock_put(sk); /* The entry could have been deleted from the * list meanwhile and thus the next pointer is * no longer valid. Play it safe and restart * the scan. Forward progress is ensured * because we set s->ax25_dev to NULL and we * are never passed a NULL 'dev' argument. */ goto again; } } spin_unlock_bh(&ax25_list_lock); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'ax25: Fix NULL pointer dereference in ax25_kill_by_device When two ax25 devices attempted to establish connection, the requester use ax25_create(), ax25_bind() and ax25_connect() to initiate connection. The receiver use ax25_rcv() to accept connection and use ax25_create_cb() in ax25_rcv() to create ax25_cb, but the ax25_cb->sk is NULL. When the receiver is detaching, a NULL pointer dereference bug caused by sock_hold(sk) in ax25_kill_by_device() will happen. The corresponding fail log is shown below: =============================================================== BUG: KASAN: null-ptr-deref in ax25_device_event+0xfd/0x290 Call Trace: ... ax25_device_event+0xfd/0x290 raw_notifier_call_chain+0x5e/0x70 dev_close_many+0x174/0x220 unregister_netdevice_many+0x1f7/0xa60 unregister_netdevice_queue+0x12f/0x170 unregister_netdev+0x13/0x20 mkiss_close+0xcd/0x140 tty_ldisc_release+0xc0/0x220 tty_release_struct+0x17/0xa0 tty_release+0x62d/0x670 ... This patch add condition check in ax25_kill_by_device(). If s->sk is NULL, it will goto if branch to kill device. Fixes: 4e0f718daf97 ("ax25: improve the incomplete fix to avoid UAF and NPD bugs") Reported-by: Thomas Osterried <thomas@osterried.de> Signed-off-by: Duoming Zhou <duoming@zju.edu.cn> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void ax25_kill_by_device(struct net_device *dev) { ax25_dev *ax25_dev; ax25_cb *s; struct sock *sk; if ((ax25_dev = ax25_dev_ax25dev(dev)) == NULL) return; spin_lock_bh(&ax25_list_lock); again: ax25_for_each(s, &ax25_list) { if (s->ax25_dev == ax25_dev) { sk = s->sk; sock_hold(sk); spin_unlock_bh(&ax25_list_lock); lock_sock(sk); s->ax25_dev = NULL; release_sock(sk); ax25_disconnect(s, ENETUNREACH); spin_lock_bh(&ax25_list_lock); sock_put(sk); /* The entry could have been deleted from the * list meanwhile and thus the next pointer is * no longer valid. Play it safe and restart * the scan. Forward progress is ensured * because we set s->ax25_dev to NULL and we * are never passed a NULL 'dev' argument. */ goto again; } } spin_unlock_bh(&ax25_list_lock); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'ax25: add refcount in ax25_dev to avoid UAF bugs If we dereference ax25_dev after we call kfree(ax25_dev) in ax25_dev_device_down(), it will lead to concurrency UAF bugs. There are eight syscall functions suffer from UAF bugs, include ax25_bind(), ax25_release(), ax25_connect(), ax25_ioctl(), ax25_getname(), ax25_sendmsg(), ax25_getsockopt() and ax25_info_show(). One of the concurrency UAF can be shown as below: (USE) | (FREE) | ax25_device_event | ax25_dev_device_down ax25_bind | ... ... | kfree(ax25_dev) ax25_fillin_cb() | ... ax25_fillin_cb_from_dev() | ... | The root cause of UAF bugs is that kfree(ax25_dev) in ax25_dev_device_down() is not protected by any locks. When ax25_dev, which there are still pointers point to, is released, the concurrency UAF bug will happen. This patch introduces refcount into ax25_dev in order to guarantee that there are no pointers point to it when ax25_dev is released. Signed-off-by: Duoming Zhou <duoming@zju.edu.cn> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ax25_fwd_ioctl(unsigned int cmd, struct ax25_fwd_struct *fwd) { ax25_dev *ax25_dev, *fwd_dev; if ((ax25_dev = ax25_addr_ax25dev(&fwd->port_from)) == NULL) return -EINVAL; switch (cmd) { case SIOCAX25ADDFWD: if ((fwd_dev = ax25_addr_ax25dev(&fwd->port_to)) == NULL) return -EINVAL; if (ax25_dev->forward != NULL) return -EINVAL; ax25_dev->forward = fwd_dev->dev; ax25_dev_put(fwd_dev); break; case SIOCAX25DELFWD: if (ax25_dev->forward == NULL) return -EINVAL; ax25_dev->forward = NULL; break; default: return -EINVAL; } ax25_dev_put(ax25_dev); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'ax25: fix reference count leaks of ax25_dev The previous commit d01ffb9eee4a ("ax25: add refcount in ax25_dev to avoid UAF bugs") introduces refcount into ax25_dev, but there are reference leak paths in ax25_ctl_ioctl(), ax25_fwd_ioctl(), ax25_rt_add(), ax25_rt_del() and ax25_rt_opt(). This patch uses ax25_dev_put() and adjusts the position of ax25_addr_ax25dev() to fix reference cout leaks of ax25_dev. Fixes: d01ffb9eee4a ("ax25: add refcount in ax25_dev to avoid UAF bugs") Signed-off-by: Duoming Zhou <duoming@zju.edu.cn> Reviewed-by: Dan Carpenter <dan.carpenter@oracle.com> Link: https://lore.kernel.org/r/20220203150811.42256-1-duoming@zju.edu.cn Signed-off-by: Jakub Kicinski <kuba@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static netdev_tx_t ems_usb_start_xmit(struct sk_buff *skb, struct net_device *netdev) { struct ems_usb *dev = netdev_priv(netdev); struct ems_tx_urb_context *context = NULL; struct net_device_stats *stats = &netdev->stats; struct can_frame *cf = (struct can_frame *)skb->data; struct ems_cpc_msg *msg; struct urb *urb; u8 *buf; int i, err; size_t size = CPC_HEADER_SIZE + CPC_MSG_HEADER_LEN + sizeof(struct cpc_can_msg); if (can_dropped_invalid_skb(netdev, skb)) return NETDEV_TX_OK; /* create a URB, and a buffer for it, and copy the data to the URB */ urb = usb_alloc_urb(0, GFP_ATOMIC); if (!urb) goto nomem; buf = usb_alloc_coherent(dev->udev, size, GFP_ATOMIC, &urb->transfer_dma); if (!buf) { netdev_err(netdev, "No memory left for USB buffer\n"); usb_free_urb(urb); goto nomem; } msg = (struct ems_cpc_msg *)&buf[CPC_HEADER_SIZE]; msg->msg.can_msg.id = cpu_to_le32(cf->can_id & CAN_ERR_MASK); msg->msg.can_msg.length = cf->len; if (cf->can_id & CAN_RTR_FLAG) { msg->type = cf->can_id & CAN_EFF_FLAG ? CPC_CMD_TYPE_EXT_RTR_FRAME : CPC_CMD_TYPE_RTR_FRAME; msg->length = CPC_CAN_MSG_MIN_SIZE; } else { msg->type = cf->can_id & CAN_EFF_FLAG ? CPC_CMD_TYPE_EXT_CAN_FRAME : CPC_CMD_TYPE_CAN_FRAME; for (i = 0; i < cf->len; i++) msg->msg.can_msg.msg[i] = cf->data[i]; msg->length = CPC_CAN_MSG_MIN_SIZE + cf->len; } for (i = 0; i < MAX_TX_URBS; i++) { if (dev->tx_contexts[i].echo_index == MAX_TX_URBS) { context = &dev->tx_contexts[i]; break; } } /* * May never happen! When this happens we'd more URBs in flight as * allowed (MAX_TX_URBS). */ if (!context) { usb_free_coherent(dev->udev, size, buf, urb->transfer_dma); usb_free_urb(urb); netdev_warn(netdev, "couldn't find free context\n"); return NETDEV_TX_BUSY; } context->dev = dev; context->echo_index = i; usb_fill_bulk_urb(urb, dev->udev, usb_sndbulkpipe(dev->udev, 2), buf, size, ems_usb_write_bulk_callback, context); urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; usb_anchor_urb(urb, &dev->tx_submitted); can_put_echo_skb(skb, netdev, context->echo_index, 0); atomic_inc(&dev->active_tx_urbs); err = usb_submit_urb(urb, GFP_ATOMIC); if (unlikely(err)) { can_free_echo_skb(netdev, context->echo_index, NULL); usb_unanchor_urb(urb); usb_free_coherent(dev->udev, size, buf, urb->transfer_dma); dev_kfree_skb(skb); atomic_dec(&dev->active_tx_urbs); if (err == -ENODEV) { netif_device_detach(netdev); } else { netdev_warn(netdev, "failed tx_urb %d\n", err); stats->tx_dropped++; } } else { netif_trans_update(netdev); /* Slow down tx path */ if (atomic_read(&dev->active_tx_urbs) >= MAX_TX_URBS || dev->free_slots < CPC_TX_QUEUE_TRIGGER_LOW) { netif_stop_queue(netdev); } } /* * Release our reference to this URB, the USB core will eventually free * it entirely. */ usb_free_urb(urb); return NETDEV_TX_OK; nomem: dev_kfree_skb(skb); stats->tx_dropped++; return NETDEV_TX_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'can: ems_usb: ems_usb_start_xmit(): fix double dev_kfree_skb() in error path There is no need to call dev_kfree_skb() when usb_submit_urb() fails beacause can_put_echo_skb() deletes the original skb and can_free_echo_skb() deletes the cloned skb. Link: https://lore.kernel.org/all/20220228083639.38183-1-hbh25y@gmail.com Fixes: 702171adeed3 ("ems_usb: Added support for EMS CPC-USB/ARM7 CAN/USB interface") Cc: stable@vger.kernel.org Cc: Sebastian Haas <haas@ems-wuensche.com> Signed-off-by: Hangyu Hua <hbh25y@gmail.com> Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: RList *r_bin_ne_get_relocs(r_bin_ne_obj_t *bin) { RList *segments = bin->segments; if (!segments) { return NULL; } RList *entries = bin->entries; if (!entries) { return NULL; } RList *symbols = bin->symbols; if (!symbols) { return NULL; } ut16 *modref = malloc (bin->ne_header->ModRefs * sizeof (ut16)); if (!modref) { return NULL; } r_buf_read_at (bin->buf, (ut64)bin->ne_header->ModRefTable + bin->header_offset, (ut8 *)modref, bin->ne_header->ModRefs * sizeof (ut16)); RList *relocs = r_list_newf (free); if (!relocs) { free (modref); return NULL; } RListIter *it; RBinSection *seg; int index = -1; r_list_foreach (segments, it, seg) { index++; if (!(bin->segment_entries[index].flags & RELOCINFO)) { continue; } ut32 off, start = off = seg->paddr + seg->size; ut16 length = r_buf_read_le16_at (bin->buf, off); if (!length) { continue; } off += 2; while (off < start + length * sizeof (NE_image_reloc_item)) { RBinReloc *reloc = R_NEW0 (RBinReloc); if (!reloc) { return NULL; } NE_image_reloc_item rel; r_buf_read_at (bin->buf, off, (ut8 *)&rel, sizeof (rel)); reloc->paddr = seg->paddr + rel.offset; switch (rel.type) { case LOBYTE: reloc->type = R_BIN_RELOC_8; break; case SEL_16: case OFF_16: reloc->type = R_BIN_RELOC_16; break; case POI_32: case OFF_32: reloc->type = R_BIN_RELOC_32; break; case POI_48: reloc->type = R_BIN_RELOC_64; break; } ut32 offset; if (rel.flags & (IMPORTED_ORD | IMPORTED_NAME)) { RBinImport *imp = R_NEW0 (RBinImport); if (!imp) { free (reloc); break; } char *name; if (rel.index > bin->ne_header->ModRefs) { name = r_str_newf ("UnknownModule%d_%x", rel.index, off); // ???? } else { offset = modref[rel.index - 1] + bin->header_offset + bin->ne_header->ImportNameTable; name = __read_nonnull_str_at (bin->buf, offset); } if (rel.flags & IMPORTED_ORD) { imp->ordinal = rel.func_ord; imp->name = r_str_newf ("%s.%s", name, __func_name_from_ord(name, rel.func_ord)); } else { offset = bin->header_offset + bin->ne_header->ImportNameTable + rel.name_off; char *func = __read_nonnull_str_at (bin->buf, offset); imp->name = r_str_newf ("%s.%s", name, func); free (func); } free (name); reloc->import = imp; } else if (rel.flags & OSFIXUP) { // TODO } else { if (strstr (seg->name, "FIXED")) { RBinSection *s = r_list_get_n (segments, rel.segnum - 1); if (s) { offset = s->paddr + rel.segoff; } else { offset = -1; } } else { RBinAddr *entry = r_list_get_n (entries, rel.entry_ordinal - 1); if (entry) { offset = entry->paddr; } else { offset = -1; } } reloc->addend = offset; RBinSymbol *sym = NULL; RListIter *sit; r_list_foreach (symbols, sit, sym) { if (sym->paddr == reloc->addend) { reloc->symbol = sym; break; } } } if (rel.flags & ADDITIVE) { reloc->additive = 1; r_list_append (relocs, reloc); } else { do { r_list_append (relocs, reloc); offset = r_buf_read_le16_at (bin->buf, reloc->paddr); RBinReloc *tmp = reloc; reloc = R_NEW0 (RBinReloc); if (!reloc) { break; } *reloc = *tmp; reloc->paddr = seg->paddr + offset; } while (offset != 0xFFFF); free (reloc); } off += sizeof (NE_image_reloc_item); } } free (modref); return relocs; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-129'], 'message': 'Fix oobread segfaults in the NE bin parser ##crash * Reported by @han0nly via huntr.dev * Reproducers: seed1 seed2 * BountyID: ad3c9c4c-76e7-40c8-bd4a-c095acd8bb40'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: CImg<T>& _load_pandore(std::FILE *const file, const char *const filename) { #define __cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,ndim,stype) \ cimg::fread(dims,nbdim,nfile); \ if (endian) cimg::invert_endianness(dims,nbdim); \ assign(nwidth,nheight,ndepth,ndim); \ const size_t siz = size(); \ stype *buffer = new stype[siz]; \ cimg::fread(buffer,siz,nfile); \ if (endian) cimg::invert_endianness(buffer,siz); \ T *ptrd = _data; \ cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); \ buffer-=siz; \ delete[] buffer #define _cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,dim,stype1,stype2,stype3,ltype) { \ if (sizeof(stype1)==ltype) { __cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,dim,stype1); } \ else if (sizeof(stype2)==ltype) { __cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,dim,stype2); } \ else if (sizeof(stype3)==ltype) { __cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,dim,stype3); } \ else throw CImgIOException(_cimg_instance \ "load_pandore(): Unknown pixel datatype in file '%s'.", \ cimg_instance, \ filename?filename:"(FILE*)"); } if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_pandore(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); CImg<charT> header(32); cimg::fread(header._data,12,nfile); if (cimg::strncasecmp("PANDORE",header,7)) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pandore(): PANDORE header not found in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } unsigned int imageid, dims[8] = { 0 }; int ptbuf[4] = { 0 }; cimg::fread(&imageid,1,nfile); const bool endian = imageid>255; if (endian) cimg::invert_endianness(imageid); cimg::fread(header._data,20,nfile); switch (imageid) { case 2 : _cimg_load_pandore_case(2,dims[1],1,1,1,unsigned char,unsigned char,unsigned char,1); break; case 3 : _cimg_load_pandore_case(2,dims[1],1,1,1,long,int,short,4); break; case 4 : _cimg_load_pandore_case(2,dims[1],1,1,1,double,float,float,4); break; case 5 : _cimg_load_pandore_case(3,dims[2],dims[1],1,1,unsigned char,unsigned char,unsigned char,1); break; case 6 : _cimg_load_pandore_case(3,dims[2],dims[1],1,1,long,int,short,4); break; case 7 : _cimg_load_pandore_case(3,dims[2],dims[1],1,1,double,float,float,4); break; case 8 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],1,unsigned char,unsigned char,unsigned char,1); break; case 9 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],1,long,int,short,4); break; case 10 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],1,double,float,float,4); break; case 11 : { // Region 1D cimg::fread(dims,3,nfile); if (endian) cimg::invert_endianness(dims,3); assign(dims[1],1,1,1); const unsigned siz = size(); if (dims[2]<256) { unsigned char *buffer = new unsigned char[siz]; cimg::fread(buffer,siz,nfile); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } else { if (dims[2]<65536) { unsigned short *buffer = new unsigned short[siz]; cimg::fread(buffer,siz,nfile); if (endian) cimg::invert_endianness(buffer,siz); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } else { unsigned int *buffer = new unsigned int[siz]; cimg::fread(buffer,siz,nfile); if (endian) cimg::invert_endianness(buffer,siz); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } } } break; case 12 : { // Region 2D cimg::fread(dims,4,nfile); if (endian) cimg::invert_endianness(dims,4); assign(dims[2],dims[1],1,1); const size_t siz = size(); if (dims[3]<256) { unsigned char *buffer = new unsigned char[siz]; cimg::fread(buffer,siz,nfile); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } else { if (dims[3]<65536) { unsigned short *buffer = new unsigned short[siz]; cimg::fread(buffer,siz,nfile); if (endian) cimg::invert_endianness(buffer,siz); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } else { unsigned int *buffer = new unsigned int[siz]; cimg::fread(buffer,siz,nfile); if (endian) cimg::invert_endianness(buffer,siz); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } } } break; case 13 : { // Region 3D cimg::fread(dims,5,nfile); if (endian) cimg::invert_endianness(dims,5); assign(dims[3],dims[2],dims[1],1); const size_t siz = size(); if (dims[4]<256) { unsigned char *buffer = new unsigned char[siz]; cimg::fread(buffer,siz,nfile); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } else { if (dims[4]<65536) { unsigned short *buffer = new unsigned short[siz]; cimg::fread(buffer,siz,nfile); if (endian) cimg::invert_endianness(buffer,siz); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } else { unsigned int *buffer = new unsigned int[siz]; cimg::fread(buffer,siz,nfile); if (endian) cimg::invert_endianness(buffer,siz); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } } } break; case 16 : _cimg_load_pandore_case(4,dims[2],dims[1],1,3,unsigned char,unsigned char,unsigned char,1); break; case 17 : _cimg_load_pandore_case(4,dims[2],dims[1],1,3,long,int,short,4); break; case 18 : _cimg_load_pandore_case(4,dims[2],dims[1],1,3,double,float,float,4); break; case 19 : _cimg_load_pandore_case(5,dims[3],dims[2],dims[1],3,unsigned char,unsigned char,unsigned char,1); break; case 20 : _cimg_load_pandore_case(5,dims[3],dims[2],dims[1],3,long,int,short,4); break; case 21 : _cimg_load_pandore_case(5,dims[3],dims[2],dims[1],3,double,float,float,4); break; case 22 : _cimg_load_pandore_case(2,dims[1],1,1,dims[0],unsigned char,unsigned char,unsigned char,1); break; case 23 : _cimg_load_pandore_case(2,dims[1],1,1,dims[0],long,int,short,4); break; case 24 : _cimg_load_pandore_case(2,dims[1],1,1,dims[0],unsigned long,unsigned int,unsigned short,4); break; case 25 : _cimg_load_pandore_case(2,dims[1],1,1,dims[0],double,float,float,4); break; case 26 : _cimg_load_pandore_case(3,dims[2],dims[1],1,dims[0],unsigned char,unsigned char,unsigned char,1); break; case 27 : _cimg_load_pandore_case(3,dims[2],dims[1],1,dims[0],long,int,short,4); break; case 28 : _cimg_load_pandore_case(3,dims[2],dims[1],1,dims[0],unsigned long,unsigned int,unsigned short,4); break; case 29 : _cimg_load_pandore_case(3,dims[2],dims[1],1,dims[0],double,float,float,4); break; case 30 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],dims[0],unsigned char,unsigned char,unsigned char,1); break; case 31 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],dims[0],long,int,short,4); break; case 32 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],dims[0],unsigned long,unsigned int,unsigned short,4); break; case 33 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],dims[0],double,float,float,4); break; case 34 : { // Points 1D cimg::fread(ptbuf,1,nfile); if (endian) cimg::invert_endianness(ptbuf,1); assign(1); (*this)(0) = (T)ptbuf[0]; } break; case 35 : { // Points 2D cimg::fread(ptbuf,2,nfile); if (endian) cimg::invert_endianness(ptbuf,2); assign(2); (*this)(0) = (T)ptbuf[1]; (*this)(1) = (T)ptbuf[0]; } break; case 36 : { // Points 3D cimg::fread(ptbuf,3,nfile); if (endian) cimg::invert_endianness(ptbuf,3); assign(3); (*this)(0) = (T)ptbuf[2]; (*this)(1) = (T)ptbuf[1]; (*this)(2) = (T)ptbuf[0]; } break; default : if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pandore(): Unable to load data with ID_type %u in file '%s'.", cimg_instance, imageid,filename?filename:"(FILE*)"); } if (!file) cimg::fclose(nfile); return *this; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-770'], 'message': 'CImg<>::load_bmp() and CImg<>::load_pandore(): Check that dimensions encoded in file does not exceed file size.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: evdev_log_msg(struct evdev_device *device, enum libinput_log_priority priority, const char *format, ...) { va_list args; char buf[1024]; if (!is_logged(evdev_libinput_context(device), priority)) return; /* Anything info and above is user-visible, use the device name */ snprintf(buf, sizeof(buf), "%-7s - %s%s%s", evdev_device_get_sysname(device), (priority > LIBINPUT_LOG_PRIORITY_DEBUG) ? device->devname : "", (priority > LIBINPUT_LOG_PRIORITY_DEBUG) ? ": " : "", format); va_start(args, format); log_msg_va(evdev_libinput_context(device), priority, buf, args); va_end(args); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-134'], 'message': 'evdev: strip the device name of format directives This fixes a format string vulnerabilty. evdev_log_message() composes a format string consisting of a fixed prefix (including the rendered device name) and the passed-in format buffer. This format string is then passed with the arguments to the actual log handler, which usually and eventually ends up being printf. If the device name contains a printf-style format directive, these ended up in the format string and thus get interpreted correctly, e.g. for a device "Foo%sBar" the log message vs printf invocation ends up being: evdev_log_message(device, "some message %s", "some argument"); printf("event9 - Foo%sBar: some message %s", "some argument"); This can enable an attacker to execute malicious code with the privileges of the process using libinput. To exploit this, an attacker needs to be able to create a kernel device with a malicious name, e.g. through /dev/uinput or a Bluetooth device. To fix this, convert any potential format directives in the device name by duplicating percentages. Pre-rendering the device to avoid the issue altogether would be nicer but the current log level hooks do not easily allow for this. The device name is the only user-controlled part of the format string. A second potential issue is the sysname of the device which is also sanitized. This issue was found by Albin Eldstål-Ahrens and Benjamin Svensson from Assured AB, and independently by Lukas Lamster. Fixes #752 Signed-off-by: Peter Hutterer <peter.hutterer@who-t.net> (cherry picked from commit a423d7d3269dc32a87384f79e29bb5ac021c83d1)'</s>
<s>[INST] Given the following code containing errors, provide 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 rtrs_clt_dev_release(struct device *dev) { struct rtrs_clt_sess *clt = container_of(dev, struct rtrs_clt_sess, dev); kfree(clt); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'RDMA/rtrs-clt: Fix possible double free in error case Callback function rtrs_clt_dev_release() for put_device() calls kfree(clt) to free memory. We shouldn't call kfree(clt) again, and we can't use the clt after kfree too. Replace device_register() with device_initialize() and device_add() so that dev_set_name can() be used appropriately. Move mutex_destroy() to the release function so it can be called in the alloc_clt err path. Fixes: eab098246625 ("RDMA/rtrs-clt: Refactor the failure cases in alloc_clt") Link: https://lore.kernel.org/r/20220217030929.323849-1-haris.iqbal@ionos.com Reported-by: Miaoqian Lin <linmq006@gmail.com> Signed-off-by: Md Haris Iqbal <haris.iqbal@ionos.com> Reviewed-by: Jack Wang <jinpu.wang@ionos.com> Signed-off-by: Jason Gunthorpe <jgg@nvidia.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: eval_lambda( char_u **arg, typval_T *rettv, evalarg_T *evalarg, int verbose) // give error messages { int evaluate = evalarg != NULL && (evalarg->eval_flags & EVAL_EVALUATE); typval_T base = *rettv; int ret; rettv->v_type = VAR_UNKNOWN; if (**arg == '{') { // ->{lambda}() ret = get_lambda_tv(arg, rettv, FALSE, evalarg); } else { // ->(lambda)() ++*arg; ret = eval1(arg, rettv, evalarg); *arg = skipwhite_and_linebreak(*arg, evalarg); if (**arg == ')') { ++*arg; } else { emsg(_(e_missing_closing_paren)); ret = FAIL; } } if (ret != OK) return FAIL; else if (**arg != '(') { if (verbose) { if (*skipwhite(*arg) == '(') emsg(_(e_no_white_space_allowed_before_parenthesis)); else semsg(_(e_missing_parenthesis_str), "lambda"); } clear_tv(rettv); ret = FAIL; } else ret = call_func_rettv(arg, evalarg, rettv, evaluate, NULL, &base); // Clear the funcref afterwards, so that deleting it while // evaluating the arguments is possible (see test55). if (evaluate) clear_tv(&base); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-823'], 'message': 'patch 8.2.4774: crash when using a number for lambda name Problem: Crash when using a number for lambda name. Solution: Check the type of the lambda reference.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: __must_hold(&ctx->completion_lock) { u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts); spin_lock_irq(&ctx->timeout_lock); while (!list_empty(&ctx->timeout_list)) { u32 events_needed, events_got; struct io_kiocb *req = list_first_entry(&ctx->timeout_list, struct io_kiocb, timeout.list); if (io_is_timeout_noseq(req)) break; /* * Since seq can easily wrap around over time, subtract * the last seq at which timeouts were flushed before comparing. * Assuming not more than 2^31-1 events have happened since, * these subtractions won't have wrapped, so we can check if * target is in [last_seq, current_seq] by comparing the two. */ events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush; events_got = seq - ctx->cq_last_tm_flush; if (events_got < events_needed) break; list_del_init(&req->timeout.list); io_kill_timeout(req, 0); } ctx->cq_last_tm_flush = seq; spin_unlock_irq(&ctx->timeout_lock); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'io_uring: fix race between timeout flush and removal io_flush_timeouts() assumes the timeout isn't in progress of triggering or being removed/canceled, so it unconditionally removes it from the timeout list and attempts to cancel it. Leave it on the list and let the normal timeout cancelation take care of it. Cc: stable@vger.kernel.org # 5.5+ Signed-off-by: Jens Axboe <axboe@kernel.dk>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gif_internal_decode_frame(gif_animation *gif, unsigned int frame, bool clear_image) { unsigned int index = 0; const unsigned char *gif_data, *gif_end; ssize_t gif_bytes; unsigned int width, height, offset_x, offset_y; unsigned int flags, colour_table_size, interlace; unsigned int *colour_table; unsigned int *frame_data = 0; // Set to 0 for no warnings unsigned int *frame_scanline; ssize_t save_buffer_position; unsigned int return_value = 0; unsigned int x, y, decode_y, burst_bytes; register unsigned char colour; /* Ensure this frame is supposed to be decoded */ if (gif->frames[frame].display == false) { return GIF_OK; } /* Ensure the frame is in range to decode */ if (frame > gif->frame_count_partial) { return GIF_INSUFFICIENT_DATA; } /* done if frame is already decoded */ if ((!clear_image) && ((int)frame == gif->decoded_frame)) { return GIF_OK; } /* Get the start of our frame data and the end of the GIF data */ gif_data = gif->gif_data + gif->frames[frame].frame_pointer; gif_end = gif->gif_data + gif->buffer_size; gif_bytes = (gif_end - gif_data); /* * Ensure there is a minimal amount of data to proceed. The shortest * block of data is a 10-byte image descriptor + 1-byte gif trailer */ if (gif_bytes < 12) { return GIF_INSUFFICIENT_FRAME_DATA; } /* Save the buffer position */ save_buffer_position = gif->buffer_position; gif->buffer_position = gif_data - gif->gif_data; /* Skip any extensions because they have allready been processed */ if ((return_value = gif_skip_frame_extensions(gif)) != GIF_OK) { goto gif_decode_frame_exit; } gif_data = (gif->gif_data + gif->buffer_position); gif_bytes = (gif_end - gif_data); /* Ensure we have enough data for the 10-byte image descriptor + 1-byte * gif trailer */ if (gif_bytes < 12) { return_value = GIF_INSUFFICIENT_FRAME_DATA; goto gif_decode_frame_exit; } /* 10-byte Image Descriptor is: * * +0 CHAR Image Separator (0x2c) * +1 SHORT Image Left Position * +3 SHORT Image Top Position * +5 SHORT Width * +7 SHORT Height * +9 CHAR __Packed Fields__ * 1BIT Local Colour Table Flag * 1BIT Interlace Flag * 1BIT Sort Flag * 2BITS Reserved * 3BITS Size of Local Colour Table */ if (gif_data[0] != GIF_IMAGE_SEPARATOR) { return_value = GIF_DATA_ERROR; goto gif_decode_frame_exit; } offset_x = gif_data[1] | (gif_data[2] << 8); offset_y = gif_data[3] | (gif_data[4] << 8); width = gif_data[5] | (gif_data[6] << 8); height = gif_data[7] | (gif_data[8] << 8); /* Boundary checking - shouldn't ever happen except unless the data has * been modified since initialisation. */ if ((offset_x + width > gif->width) || (offset_y + height > gif->height)) { return_value = GIF_DATA_ERROR; goto gif_decode_frame_exit; } /* Decode the flags */ flags = gif_data[9]; colour_table_size = 2 << (flags & GIF_COLOUR_TABLE_SIZE_MASK); interlace = flags & GIF_INTERLACE_MASK; /* Advance data pointer to next block either colour table or image * data. */ gif_data += 10; gif_bytes = (gif_end - gif_data); /* Set up the colour table */ if (flags & GIF_COLOUR_TABLE_MASK) { if (gif_bytes < (int)(3 * colour_table_size)) { return_value = GIF_INSUFFICIENT_FRAME_DATA; goto gif_decode_frame_exit; } colour_table = gif->local_colour_table; if (!clear_image) { for (index = 0; index < colour_table_size; index++) { /* Gif colour map contents are r,g,b. * * We want to pack them bytewise into the * colour table, such that the red component * is in byte 0 and the alpha component is in * byte 3. */ unsigned char *entry = (unsigned char *) &colour_table[index]; entry[0] = gif_data[0]; /* r */ entry[1] = gif_data[1]; /* g */ entry[2] = gif_data[2]; /* b */ entry[3] = 0xff; /* a */ gif_data += 3; } } else { gif_data += 3 * colour_table_size; } gif_bytes = (gif_end - gif_data); } else { colour_table = gif->global_colour_table; } /* Ensure sufficient data remains */ if (gif_bytes < 1) { return_value = GIF_INSUFFICIENT_FRAME_DATA; goto gif_decode_frame_exit; } /* check for an end marker */ if (gif_data[0] == GIF_TRAILER) { return_value = GIF_OK; goto gif_decode_frame_exit; } /* Get the frame data */ assert(gif->bitmap_callbacks.bitmap_get_buffer); frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image); if (!frame_data) { return GIF_INSUFFICIENT_MEMORY; } /* If we are clearing the image we just clear, if not decode */ if (!clear_image) { lzw_result res; const uint8_t *stack_base; const uint8_t *stack_pos; /* Ensure we have enough data for a 1-byte LZW code size + * 1-byte gif trailer */ if (gif_bytes < 2) { return_value = GIF_INSUFFICIENT_FRAME_DATA; goto gif_decode_frame_exit; } /* If we only have a 1-byte LZW code size + 1-byte gif trailer, * we're finished */ if ((gif_bytes == 2) && (gif_data[1] == GIF_TRAILER)) { return_value = GIF_OK; goto gif_decode_frame_exit; } /* If the previous frame's disposal method requires we restore * the background colour or this is the first frame, clear * the frame data */ if ((frame == 0) || (gif->decoded_frame == GIF_INVALID_FRAME)) { memset((char*)frame_data, GIF_TRANSPARENT_COLOUR, gif->width * gif->height * sizeof(int)); gif->decoded_frame = frame; /* The line below would fill the image with its * background color, but because GIFs support * transparency we likely wouldn't want to do that. */ /* memset((char*)frame_data, colour_table[gif->background_index], gif->width * gif->height * sizeof(int)); */ } else if ((frame != 0) && (gif->frames[frame - 1].disposal_method == GIF_FRAME_CLEAR)) { return_value = gif_internal_decode_frame(gif, (frame - 1), true); if (return_value != GIF_OK) { goto gif_decode_frame_exit; } } else if ((frame != 0) && (gif->frames[frame - 1].disposal_method == GIF_FRAME_RESTORE)) { /* * If the previous frame's disposal method requires we * restore the previous image, find the last image set * to "do not dispose" and get that frame data */ int last_undisposed_frame = frame - 2; while ((last_undisposed_frame >= 0) && (gif->frames[last_undisposed_frame].disposal_method == GIF_FRAME_RESTORE)) { last_undisposed_frame--; } /* If we don't find one, clear the frame data */ if (last_undisposed_frame == -1) { /* see notes above on transparency * vs. background color */ memset((char*)frame_data, GIF_TRANSPARENT_COLOUR, gif->width * gif->height * sizeof(int)); } else { return_value = gif_internal_decode_frame(gif, last_undisposed_frame, false); if (return_value != GIF_OK) { goto gif_decode_frame_exit; } /* Get this frame's data */ assert(gif->bitmap_callbacks.bitmap_get_buffer); frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image); if (!frame_data) { return GIF_INSUFFICIENT_MEMORY; } } } gif->decoded_frame = frame; gif->buffer_position = (gif_data - gif->gif_data) + 1; /* Initialise the LZW decoding */ res = lzw_decode_init(gif->lzw_ctx, gif->gif_data, gif->buffer_size, gif->buffer_position, gif_data[0], &stack_base, &stack_pos); if (res != LZW_OK) { return gif_error_from_lzw(res); } /* Decompress the data */ for (y = 0; y < height; y++) { if (interlace) { decode_y = gif_interlaced_line(height, y) + offset_y; } else { decode_y = y + offset_y; } frame_scanline = frame_data + offset_x + (decode_y * gif->width); /* Rather than decoding pixel by pixel, we try to burst * out streams of data to remove the need for end-of * data checks every pixel. */ x = width; while (x > 0) { burst_bytes = (stack_pos - stack_base); if (burst_bytes > 0) { if (burst_bytes > x) { burst_bytes = x; } x -= burst_bytes; while (burst_bytes-- > 0) { colour = *--stack_pos; if (((gif->frames[frame].transparency) && (colour != gif->frames[frame].transparency_index)) || (!gif->frames[frame].transparency)) { *frame_scanline = colour_table[colour]; } frame_scanline++; } } else { res = lzw_decode(gif->lzw_ctx, &stack_pos); if (res != LZW_OK) { /* Unexpected end of frame, try to recover */ if (res == LZW_OK_EOD) { return_value = GIF_OK; } else { return_value = gif_error_from_lzw(res); } goto gif_decode_frame_exit; } } } } } else { /* Clear our frame */ if (gif->frames[frame].disposal_method == GIF_FRAME_CLEAR) { for (y = 0; y < height; y++) { frame_scanline = frame_data + offset_x + ((offset_y + y) * gif->width); if (gif->frames[frame].transparency) { memset(frame_scanline, GIF_TRANSPARENT_COLOUR, width * 4); } else { memset(frame_scanline, colour_table[gif->background_index], width * 4); } } } } gif_decode_frame_exit: /* Check if we should test for optimisation */ if (gif->frames[frame].virgin) { if (gif->bitmap_callbacks.bitmap_test_opaque) { gif->frames[frame].opaque = gif->bitmap_callbacks.bitmap_test_opaque(gif->frame_image); } else { gif->frames[frame].opaque = false; } gif->frames[frame].virgin = false; } if (gif->bitmap_callbacks.bitmap_set_opaque) { gif->bitmap_callbacks.bitmap_set_opaque(gif->frame_image, gif->frames[frame].opaque); } if (gif->bitmap_callbacks.bitmap_modified) { gif->bitmap_callbacks.bitmap_modified(gif->frame_image); } /* Restore the buffer position */ gif->buffer_position = save_buffer_position; return return_value; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'libnsgif: Fix null pointer deref on frameless GIF input A crafted GIF file with no frame data could cause a null pointer dereference leading to denial of service (crash). Reported by @JieyongMa via huntr.dev.'</s>
<s>[INST] Given the following code containing errors, provide 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 SDL_Surface *Create_Surface_Blended(int width, int height, SDL_Color fg, Uint32 *color) { const int alignment = Get_Alignement() - 1; SDL_Surface *textbuf = NULL; Uint32 bgcolor; /* Background color */ bgcolor = (fg.r << 16) | (fg.g << 8) | fg.b; /* Underline/Strikethrough color style */ *color = bgcolor | (fg.a << 24); /* Create the target surface if required */ if (width != 0) { /* Create a surface with memory: * - pitch is rounded to alignment * - adress is aligned */ Sint64 size; void *pixels, *ptr; /* Worse case at the end of line pulling 'alignment' extra blank pixels */ Sint64 pitch = (width + alignment) * 4; pitch += alignment; pitch &= ~alignment; size = height * pitch + sizeof (void *) + alignment; if (size < 0 || size > SDL_MAX_SINT32) { /* Overflow... */ return NULL; } ptr = SDL_malloc((size_t)size); if (ptr == NULL) { return NULL; } /* address is aligned */ pixels = (void *)(((uintptr_t)ptr + sizeof(void *) + alignment) & ~alignment); ((void **)pixels)[-1] = ptr; textbuf = SDL_CreateRGBSurfaceWithFormatFrom(pixels, width, height, 0, pitch, SDL_PIXELFORMAT_ARGB8888); if (textbuf == NULL) { SDL_free(ptr); return NULL; } /* Let SDL handle the memory allocation */ textbuf->flags &= ~SDL_PREALLOC; textbuf->flags |= SDL_SIMD_ALIGNED; /* Initialize with fg and 0 alpha */ SDL_memset4(pixels, bgcolor, (height * pitch) / 4); /* Support alpha blending */ if (fg.a != SDL_ALPHA_OPAQUE) { SDL_SetSurfaceBlendMode(textbuf, SDL_BLENDMODE_BLEND); } } return textbuf; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-787'], 'message': 'More integer overflow (see bug #187) Make sure that 'width + alignment' doesn't overflow, otherwise it could create a SDL_Surface of 'width' but with wrong 'pitch''</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlBufCCat(xmlBufPtr buf, const char *str) { const char *cur; if ((buf == NULL) || (buf->error)) return(-1); CHECK_COMPAT(buf) if (buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) return -1; if (str == NULL) { #ifdef DEBUG_BUFFER xmlGenericError(xmlGenericErrorContext, "xmlBufCCat: str == NULL\n"); #endif return -1; } for (cur = str;*cur != 0;cur++) { if (buf->use + 10 >= buf->size) { if (!xmlBufResize(buf, buf->use+10)){ xmlBufMemoryError(buf, "growing buffer"); return XML_ERR_NO_MEMORY; } } buf->content[buf->use++] = *cur; } buf->content[buf->use] = 0; UPDATE_COMPAT(buf) return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': '[CVE-2022-29824] Fix integer overflows in xmlBuf and xmlBuffer In several places, the code handling string buffers didn't check for integer overflow or used wrong types for buffer sizes. This could result in out-of-bounds writes or other memory errors when working on large, multi-gigabyte buffers. Thanks to Felix Wilhelm for the report.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: fname_match( regmatch_T *rmp, char_u *name, int ignore_case) // when TRUE ignore case, when FALSE use 'fic' { char_u *match = NULL; char_u *p; if (name != NULL) { // Ignore case when 'fileignorecase' or the argument is set. rmp->rm_ic = p_fic || ignore_case; if (vim_regexec(rmp, name, (colnr_T)0)) match = name; else { // Replace $(HOME) with '~' and try matching again. p = home_replace_save(NULL, name); if (p != NULL && vim_regexec(rmp, p, (colnr_T)0)) match = name; vim_free(p); } } return match; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'patch 8.2.4901: NULL pointer access when using invalid pattern Problem: NULL pointer access when using invalid pattern. Solution: Check for failed regexp program.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline bool kdb_check_flags(kdb_cmdflags_t flags, int permissions, bool no_args) { /* permissions comes from userspace so needs massaging slightly */ permissions &= KDB_ENABLE_MASK; permissions |= KDB_ENABLE_ALWAYS_SAFE; /* some commands change group when launched with no arguments */ if (no_args) permissions |= permissions << KDB_ENABLE_NO_ARGS_SHIFT; flags |= KDB_ENABLE_ALL; return permissions & flags; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'lockdown: also lock down previous kgdb use KGDB and KDB allow read and write access to kernel memory, and thus should be restricted during lockdown. An attacker with access to a serial port (for example, via a hypervisor console, which some cloud vendors provide over the network) could trigger the debugger so it is important that the debugger respect the lockdown mode when/if it is triggered. Fix this by integrating lockdown into kdb's existing permissions mechanism. Unfortunately kgdb does not have any permissions mechanism (although it certainly could be added later) so, for now, kgdb is simply and brutally disabled by immediately exiting the gdb stub without taking any action. For lockdowns established early in the boot (e.g. the normal case) then this should be fine but on systems where kgdb has set breakpoints before the lockdown is enacted than "bad things" will happen. CVE: CVE-2022-21499 Co-developed-by: Stephen Brennan <stephen.s.brennan@oracle.com> Signed-off-by: Stephen Brennan <stephen.s.brennan@oracle.com> Reviewed-by: Douglas Anderson <dianders@chromium.org> Signed-off-by: Daniel Thompson <daniel.thompson@linaro.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int nfc_register_device(struct nfc_dev *dev) { int rc; pr_debug("dev_name=%s\n", dev_name(&dev->dev)); mutex_lock(&nfc_devlist_mutex); nfc_devlist_generation++; rc = device_add(&dev->dev); mutex_unlock(&nfc_devlist_mutex); if (rc < 0) return rc; rc = nfc_llcp_register_device(dev); if (rc) pr_err("Could not register llcp device\n"); device_lock(&dev->dev); dev->rfkill = rfkill_alloc(dev_name(&dev->dev), &dev->dev, RFKILL_TYPE_NFC, &nfc_rfkill_ops, dev); if (dev->rfkill) { if (rfkill_register(dev->rfkill) < 0) { rfkill_destroy(dev->rfkill); dev->rfkill = NULL; } } device_unlock(&dev->dev); rc = nfc_genl_device_added(dev); if (rc) pr_debug("The userspace won't be notified that the device %s was added\n", dev_name(&dev->dev)); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'nfc: replace improper check device_is_registered() in netlink related functions The device_is_registered() in nfc core is used to check whether nfc device is registered in netlink related functions such as nfc_fw_download(), nfc_dev_up() and so on. Although device_is_registered() is protected by device_lock, there is still a race condition between device_del() and device_is_registered(). The root cause is that kobject_del() in device_del() is not protected by device_lock. (cleanup task) | (netlink task) | nfc_unregister_device | nfc_fw_download device_del | device_lock ... | if (!device_is_registered)//(1) kobject_del//(2) | ... ... | device_unlock The device_is_registered() returns the value of state_in_sysfs and the state_in_sysfs is set to zero in kobject_del(). If we pass check in position (1), then set zero in position (2). As a result, the check in position (1) is useless. This patch uses bool variable instead of device_is_registered() to judge whether the nfc device is registered, which is well synchronized. Fixes: 3e256b8f8dfa ("NFC: add nfc subsystem core") Signed-off-by: Duoming Zhou <duoming@zju.edu.cn> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ptrace_setoptions(struct task_struct *child, unsigned long data) { unsigned flags; if (data & ~(unsigned long)PTRACE_O_MASK) return -EINVAL; if (unlikely(data & PTRACE_O_SUSPEND_SECCOMP)) { if (!IS_ENABLED(CONFIG_CHECKPOINT_RESTORE) || !IS_ENABLED(CONFIG_SECCOMP)) return -EINVAL; if (!capable(CAP_SYS_ADMIN)) return -EPERM; if (seccomp_mode(&current->seccomp) != SECCOMP_MODE_DISABLED || current->ptrace & PT_SUSPEND_SECCOMP) return -EPERM; } /* Avoid intermediate state when all opts are cleared */ flags = child->ptrace; flags &= ~(PTRACE_O_MASK << PT_OPT_FLAG_SHIFT); flags |= (data << PT_OPT_FLAG_SHIFT); child->ptrace = flags; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-276', 'CWE-703', 'CWE-863'], 'message': 'ptrace: Check PTRACE_O_SUSPEND_SECCOMP permission on PTRACE_SEIZE Setting PTRACE_O_SUSPEND_SECCOMP is supposed to be a highly privileged operation because it allows the tracee to completely bypass all seccomp filters on kernels with CONFIG_CHECKPOINT_RESTORE=y. It is only supposed to be settable by a process with global CAP_SYS_ADMIN, and only if that process is not subject to any seccomp filters at all. However, while these permission checks were done on the PTRACE_SETOPTIONS path, they were missing on the PTRACE_SEIZE path, which also sets user-specified ptrace flags. Move the permissions checks out into a helper function and let both ptrace_attach() and ptrace_setoptions() call it. Cc: stable@kernel.org Fixes: 13c4a90119d2 ("seccomp: add ptrace options for suspend/resume") Signed-off-by: Jann Horn <jannh@google.com> Link: https://lkml.kernel.org/r/20220319010838.1386861-1-jannh@google.com Signed-off-by: Eric W. Biederman <ebiederm@xmission.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xcf_load_old_path (XcfInfo *info, GimpImage *image) { gchar *name; guint32 locked; guint8 state; guint32 closed; guint32 num_points; guint32 version; /* changed from num_paths */ GimpTattoo tattoo = 0; GimpVectors *vectors; GimpVectorsCompatPoint *points; gint i; xcf_read_string (info, &name, 1); xcf_read_int32 (info, &locked, 1); xcf_read_int8 (info, &state, 1); xcf_read_int32 (info, &closed, 1); xcf_read_int32 (info, &num_points, 1); xcf_read_int32 (info, &version, 1); if (version == 2) { guint32 dummy; /* Had extra type field and points are stored as doubles */ xcf_read_int32 (info, (guint32 *) &dummy, 1); } else if (version == 3) { guint32 dummy; /* Has extra tattoo field */ xcf_read_int32 (info, (guint32 *) &dummy, 1); xcf_read_int32 (info, (guint32 *) &tattoo, 1); } else if (version != 1) { g_printerr ("Unknown path type. Possibly corrupt XCF file"); g_free (name); return FALSE; } /* skip empty compatibility paths */ if (num_points == 0) { g_free (name); return FALSE; } points = g_new0 (GimpVectorsCompatPoint, num_points); for (i = 0; i < num_points; i++) { if (version == 1) { gint32 x; gint32 y; xcf_read_int32 (info, &points[i].type, 1); xcf_read_int32 (info, (guint32 *) &x, 1); xcf_read_int32 (info, (guint32 *) &y, 1); points[i].x = x; points[i].y = y; } else { gfloat x; gfloat y; xcf_read_int32 (info, &points[i].type, 1); xcf_read_float (info, &x, 1); xcf_read_float (info, &y, 1); points[i].x = x; points[i].y = y; } } vectors = gimp_vectors_compat_new (image, name, points, num_points, closed); g_free (name); g_free (points); if (locked) info->linked_paths = g_list_prepend (info->linked_paths, vectors); if (tattoo) gimp_item_set_tattoo (GIMP_ITEM (vectors), tattoo); gimp_image_add_vectors (image, vectors, NULL, /* can't be a tree */ gimp_container_get_n_children (gimp_image_get_vectors (image)), FALSE); return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'app: fix #8120 GIMP 2.10.30 crashed when allocate large memory GIMP could crash if the information regarding old path properties read from XCF was incorrect. It did not check if xcf_old_path succeeded and kept trying to load more paths even if the last one failed to load. Instead we now stop loading paths as soon as that function fails. In case we have a failure here we also try to skip to the next property based on the size of the path property, in hopes that the only problem was this property.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ex_substitute(exarg_T *eap) { linenr_T lnum; long i = 0; regmmatch_T regmatch; static subflags_T subflags = {FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, 0}; #ifdef FEAT_EVAL subflags_T subflags_save; #endif int save_do_all; // remember user specified 'g' flag int save_do_ask; // remember user specified 'c' flag char_u *pat = NULL, *sub = NULL; // init for GCC char_u *sub_copy = NULL; int delimiter; int sublen; int got_quit = FALSE; int got_match = FALSE; int temp; int which_pat; char_u *cmd; int save_State; linenr_T first_line = 0; // first changed line linenr_T last_line= 0; // below last changed line AFTER the // change linenr_T old_line_count = curbuf->b_ml.ml_line_count; linenr_T line2; long nmatch; // number of lines in match char_u *sub_firstline; // allocated copy of first sub line int endcolumn = FALSE; // cursor in last column when done pos_T old_cursor = curwin->w_cursor; int start_nsubs; #ifdef FEAT_EVAL int save_ma = 0; #endif cmd = eap->arg; if (!global_busy) { sub_nsubs = 0; sub_nlines = 0; } start_nsubs = sub_nsubs; if (eap->cmdidx == CMD_tilde) which_pat = RE_LAST; // use last used regexp else which_pat = RE_SUBST; // use last substitute regexp // new pattern and substitution if (eap->cmd[0] == 's' && *cmd != NUL && !VIM_ISWHITE(*cmd) && vim_strchr((char_u *)"0123456789cegriIp|\"", *cmd) == NULL) { // don't accept alphanumeric for separator if (check_regexp_delim(*cmd) == FAIL) return; #ifdef FEAT_EVAL if (in_vim9script() && check_global_and_subst(eap->cmd, eap->arg) == FAIL) return; #endif /* * undocumented vi feature: * "\/sub/" and "\?sub?" use last used search pattern (almost like * //sub/r). "\&sub&" use last substitute pattern (like //sub/). */ if (*cmd == '\\') { if (in_vim9script()) { emsg(_(e_cannot_use_s_backslash_in_vim9_script)); return; } ++cmd; if (vim_strchr((char_u *)"/?&", *cmd) == NULL) { emsg(_(e_backslash_should_be_followed_by)); return; } if (*cmd != '&') which_pat = RE_SEARCH; // use last '/' pattern pat = (char_u *)""; // empty search pattern delimiter = *cmd++; // remember delimiter character } else // find the end of the regexp { which_pat = RE_LAST; // use last used regexp delimiter = *cmd++; // remember delimiter character pat = cmd; // remember start of search pat cmd = skip_regexp_ex(cmd, delimiter, magic_isset(), &eap->arg, NULL, NULL); if (cmd[0] == delimiter) // end delimiter found *cmd++ = NUL; // replace it with a NUL } /* * Small incompatibility: vi sees '\n' as end of the command, but in * Vim we want to use '\n' to find/substitute a NUL. */ sub = cmd; // remember the start of the substitution cmd = skip_substitute(cmd, delimiter); if (!eap->skip) { // In POSIX vi ":s/pat/%/" uses the previous subst. string. if (STRCMP(sub, "%") == 0 && vim_strchr(p_cpo, CPO_SUBPERCENT) != NULL) { if (old_sub == NULL) // there is no previous command { emsg(_(e_no_previous_substitute_regular_expression)); return; } sub = old_sub; } else { vim_free(old_sub); old_sub = vim_strsave(sub); } } } else if (!eap->skip) // use previous pattern and substitution { if (old_sub == NULL) // there is no previous command { emsg(_(e_no_previous_substitute_regular_expression)); return; } pat = NULL; // search_regcomp() will use previous pattern sub = old_sub; // Vi compatibility quirk: repeating with ":s" keeps the cursor in the // last column after using "$". endcolumn = (curwin->w_curswant == MAXCOL); } // Recognize ":%s/\n//" and turn it into a join command, which is much // more efficient. // TODO: find a generic solution to make line-joining operations more // efficient, avoid allocating a string that grows in size. if (pat != NULL && STRCMP(pat, "\\n") == 0 && *sub == NUL && (*cmd == NUL || (cmd[1] == NUL && (*cmd == 'g' || *cmd == 'l' || *cmd == 'p' || *cmd == '#')))) { linenr_T joined_lines_count; if (eap->skip) return; curwin->w_cursor.lnum = eap->line1; if (*cmd == 'l') eap->flags = EXFLAG_LIST; else if (*cmd == '#') eap->flags = EXFLAG_NR; else if (*cmd == 'p') eap->flags = EXFLAG_PRINT; // The number of lines joined is the number of lines in the range plus // one. One less when the last line is included. joined_lines_count = eap->line2 - eap->line1 + 1; if (eap->line2 < curbuf->b_ml.ml_line_count) ++joined_lines_count; if (joined_lines_count > 1) { (void)do_join(joined_lines_count, FALSE, TRUE, FALSE, TRUE); sub_nsubs = joined_lines_count - 1; sub_nlines = 1; (void)do_sub_msg(FALSE); ex_may_print(eap); } if ((cmdmod.cmod_flags & CMOD_KEEPPATTERNS) == 0) save_re_pat(RE_SUBST, pat, magic_isset()); // put pattern in history add_to_history(HIST_SEARCH, pat, TRUE, NUL); return; } /* * Find trailing options. When '&' is used, keep old options. */ if (*cmd == '&') ++cmd; else { #ifdef FEAT_EVAL if (in_vim9script()) { // ignore 'gdefault' and 'edcompatible' subflags.do_all = FALSE; subflags.do_ask = FALSE; } else #endif if (!p_ed) { if (p_gd) // default is global on subflags.do_all = TRUE; else subflags.do_all = FALSE; subflags.do_ask = FALSE; } subflags.do_error = TRUE; subflags.do_print = FALSE; subflags.do_list = FALSE; subflags.do_count = FALSE; subflags.do_number = FALSE; subflags.do_ic = 0; } while (*cmd) { /* * Note that 'g' and 'c' are always inverted, also when p_ed is off. * 'r' is never inverted. */ if (*cmd == 'g') subflags.do_all = !subflags.do_all; else if (*cmd == 'c') subflags.do_ask = !subflags.do_ask; else if (*cmd == 'n') subflags.do_count = TRUE; else if (*cmd == 'e') subflags.do_error = !subflags.do_error; else if (*cmd == 'r') // use last used regexp which_pat = RE_LAST; else if (*cmd == 'p') subflags.do_print = TRUE; else if (*cmd == '#') { subflags.do_print = TRUE; subflags.do_number = TRUE; } else if (*cmd == 'l') { subflags.do_print = TRUE; subflags.do_list = TRUE; } else if (*cmd == 'i') // ignore case subflags.do_ic = 'i'; else if (*cmd == 'I') // don't ignore case subflags.do_ic = 'I'; else break; ++cmd; } if (subflags.do_count) subflags.do_ask = FALSE; save_do_all = subflags.do_all; save_do_ask = subflags.do_ask; /* * check for a trailing count */ cmd = skipwhite(cmd); if (VIM_ISDIGIT(*cmd)) { i = getdigits(&cmd); if (i <= 0 && !eap->skip && subflags.do_error) { emsg(_(e_positive_count_required)); return; } eap->line1 = eap->line2; eap->line2 += i - 1; if (eap->line2 > curbuf->b_ml.ml_line_count) eap->line2 = curbuf->b_ml.ml_line_count; } /* * check for trailing command or garbage */ cmd = skipwhite(cmd); if (*cmd && *cmd != '"') // if not end-of-line or comment { set_nextcmd(eap, cmd); if (eap->nextcmd == NULL) { semsg(_(e_trailing_characters_str), cmd); return; } } if (eap->skip) // not executing commands, only parsing return; if (!subflags.do_count && !curbuf->b_p_ma) { // Substitution is not allowed in non-'modifiable' buffer emsg(_(e_cannot_make_changes_modifiable_is_off)); return; } if (search_regcomp(pat, RE_SUBST, which_pat, SEARCH_HIS, &regmatch) == FAIL) { if (subflags.do_error) emsg(_(e_invalid_command)); return; } // the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase' if (subflags.do_ic == 'i') regmatch.rmm_ic = TRUE; else if (subflags.do_ic == 'I') regmatch.rmm_ic = FALSE; sub_firstline = NULL; /* * If the substitute pattern starts with "\=" then it's an expression. * Make a copy, a recursive function may free it. * Otherwise, '~' in the substitute pattern is replaced with the old * pattern. We do it here once to avoid it to be replaced over and over * again. */ if (sub[0] == '\\' && sub[1] == '=') { sub = vim_strsave(sub); if (sub == NULL) return; sub_copy = sub; } else sub = regtilde(sub, magic_isset()); /* * Check for a match on each line. */ line2 = eap->line2; for (lnum = eap->line1; lnum <= line2 && !(got_quit #if defined(FEAT_EVAL) || aborting() #endif ); ++lnum) { nmatch = vim_regexec_multi(&regmatch, curwin, curbuf, lnum, (colnr_T)0, NULL, NULL); if (nmatch) { colnr_T copycol; colnr_T matchcol; colnr_T prev_matchcol = MAXCOL; char_u *new_end, *new_start = NULL; unsigned new_start_len = 0; char_u *p1; int did_sub = FALSE; int lastone; int len, copy_len, needed_len; long nmatch_tl = 0; // nr of lines matched below lnum int do_again; // do it again after joining lines int skip_match = FALSE; linenr_T sub_firstlnum; // nr of first sub line #ifdef FEAT_PROP_POPUP int apc_flags = APC_SAVE_FOR_UNDO | APC_SUBSTITUTE; colnr_T total_added = 0; #endif /* * The new text is build up step by step, to avoid too much * copying. There are these pieces: * sub_firstline The old text, unmodified. * copycol Column in the old text where we started * looking for a match; from here old text still * needs to be copied to the new text. * matchcol Column number of the old text where to look * for the next match. It's just after the * previous match or one further. * prev_matchcol Column just after the previous match (if any). * Mostly equal to matchcol, except for the first * match and after skipping an empty match. * regmatch.*pos Where the pattern matched in the old text. * new_start The new text, all that has been produced so * far. * new_end The new text, where to append new text. * * lnum The line number where we found the start of * the match. Can be below the line we searched * when there is a \n before a \zs in the * pattern. * sub_firstlnum The line number in the buffer where to look * for a match. Can be different from "lnum" * when the pattern or substitute string contains * line breaks. * * Special situations: * - When the substitute string contains a line break, the part up * to the line break is inserted in the text, but the copy of * the original line is kept. "sub_firstlnum" is adjusted for * the inserted lines. * - When the matched pattern contains a line break, the old line * is taken from the line at the end of the pattern. The lines * in the match are deleted later, "sub_firstlnum" is adjusted * accordingly. * * The new text is built up in new_start[]. It has some extra * room to avoid using alloc()/free() too often. new_start_len is * the length of the allocated memory at new_start. * * Make a copy of the old line, so it won't be taken away when * updating the screen or handling a multi-line match. The "old_" * pointers point into this copy. */ sub_firstlnum = lnum; copycol = 0; matchcol = 0; // At first match, remember current cursor position. if (!got_match) { setpcmark(); got_match = TRUE; } /* * Loop until nothing more to replace in this line. * 1. Handle match with empty string. * 2. If do_ask is set, ask for confirmation. * 3. substitute the string. * 4. if do_all is set, find next match * 5. break if there isn't another match in this line */ for (;;) { // Advance "lnum" to the line where the match starts. The // match does not start in the first line when there is a line // break before \zs. if (regmatch.startpos[0].lnum > 0) { lnum += regmatch.startpos[0].lnum; sub_firstlnum += regmatch.startpos[0].lnum; nmatch -= regmatch.startpos[0].lnum; VIM_CLEAR(sub_firstline); } // Match might be after the last line for "\n\zs" matching at // the end of the last line. if (lnum > curbuf->b_ml.ml_line_count) break; if (sub_firstline == NULL) { sub_firstline = vim_strsave(ml_get(sub_firstlnum)); if (sub_firstline == NULL) { vim_free(new_start); goto outofmem; } } // Save the line number of the last change for the final // cursor position (just like Vi). curwin->w_cursor.lnum = lnum; do_again = FALSE; /* * 1. Match empty string does not count, except for first * match. This reproduces the strange vi behaviour. * This also catches endless loops. */ if (matchcol == prev_matchcol && regmatch.endpos[0].lnum == 0 && matchcol == regmatch.endpos[0].col) { if (sub_firstline[matchcol] == NUL) // We already were at the end of the line. Don't look // for a match in this line again. skip_match = TRUE; else { // search for a match at next column if (has_mbyte) matchcol += mb_ptr2len(sub_firstline + matchcol); else ++matchcol; } goto skip; } // Normally we continue searching for a match just after the // previous match. matchcol = regmatch.endpos[0].col; prev_matchcol = matchcol; /* * 2. If do_count is set only increase the counter. * If do_ask is set, ask for confirmation. */ if (subflags.do_count) { // For a multi-line match, put matchcol at the NUL at // the end of the line and set nmatch to one, so that // we continue looking for a match on the next line. // Avoids that ":s/\nB\@=//gc" get stuck. if (nmatch > 1) { matchcol = (colnr_T)STRLEN(sub_firstline); nmatch = 1; skip_match = TRUE; } sub_nsubs++; did_sub = TRUE; #ifdef FEAT_EVAL // Skip the substitution, unless an expression is used, // then it is evaluated in the sandbox. if (!(sub[0] == '\\' && sub[1] == '=')) #endif goto skip; } if (subflags.do_ask) { int typed = 0; // change State to MODE_CONFIRM, so that the mouse works // properly save_State = State; State = MODE_CONFIRM; setmouse(); // disable mouse in xterm curwin->w_cursor.col = regmatch.startpos[0].col; if (curwin->w_p_crb) do_check_cursorbind(); // When 'cpoptions' contains "u" don't sync undo when // asking for confirmation. if (vim_strchr(p_cpo, CPO_UNDO) != NULL) ++no_u_sync; /* * Loop until 'y', 'n', 'q', CTRL-E or CTRL-Y typed. */ while (subflags.do_ask) { if (exmode_active) { char_u *resp; colnr_T sc, ec; print_line_no_prefix(lnum, subflags.do_number, subflags.do_list); getvcol(curwin, &curwin->w_cursor, &sc, NULL, NULL); curwin->w_cursor.col = regmatch.endpos[0].col - 1; if (curwin->w_cursor.col < 0) curwin->w_cursor.col = 0; getvcol(curwin, &curwin->w_cursor, NULL, NULL, &ec); curwin->w_cursor.col = regmatch.startpos[0].col; if (subflags.do_number || curwin->w_p_nu) { int numw = number_width(curwin) + 1; sc += numw; ec += numw; } msg_start(); for (i = 0; i < (long)sc; ++i) msg_putchar(' '); for ( ; i <= (long)ec; ++i) msg_putchar('^'); resp = getexmodeline('?', NULL, 0, TRUE); if (resp != NULL) { typed = *resp; vim_free(resp); // When ":normal" runs out of characters we get // an empty line. Use "q" to get out of the // loop. if (ex_normal_busy && typed == NUL) typed = 'q'; } } else { char_u *orig_line = NULL; int len_change = 0; int save_p_lz = p_lz; #ifdef FEAT_FOLDING int save_p_fen = curwin->w_p_fen; curwin->w_p_fen = FALSE; #endif // Invert the matched string. // Remove the inversion afterwards. temp = RedrawingDisabled; RedrawingDisabled = 0; // avoid calling update_screen() in vgetorpeek() p_lz = FALSE; if (new_start != NULL) { // There already was a substitution, we would // like to show this to the user. We cannot // really update the line, it would change // what matches. Temporarily replace the line // and change it back afterwards. orig_line = vim_strsave(ml_get(lnum)); if (orig_line != NULL) { char_u *new_line = concat_str(new_start, sub_firstline + copycol); if (new_line == NULL) VIM_CLEAR(orig_line); else { // Position the cursor relative to the // end of the line, the previous // substitute may have inserted or // deleted characters before the // cursor. len_change = (int)STRLEN(new_line) - (int)STRLEN(orig_line); curwin->w_cursor.col += len_change; ml_replace(lnum, new_line, FALSE); } } } search_match_lines = regmatch.endpos[0].lnum - regmatch.startpos[0].lnum; search_match_endcol = regmatch.endpos[0].col + len_change; highlight_match = TRUE; update_topline(); validate_cursor(); update_screen(SOME_VALID); highlight_match = FALSE; redraw_later(SOME_VALID); #ifdef FEAT_FOLDING curwin->w_p_fen = save_p_fen; #endif if (msg_row == Rows - 1) msg_didout = FALSE; // avoid a scroll-up msg_starthere(); i = msg_scroll; msg_scroll = 0; // truncate msg when // needed msg_no_more = TRUE; // write message same highlighting as for // wait_return smsg_attr(HL_ATTR(HLF_R), _("replace with %s (y/n/a/q/l/^E/^Y)?"), sub); msg_no_more = FALSE; msg_scroll = i; showruler(TRUE); windgoto(msg_row, msg_col); RedrawingDisabled = temp; #ifdef USE_ON_FLY_SCROLL dont_scroll = FALSE; // allow scrolling here #endif ++no_mapping; // don't map this key ++allow_keys; // allow special keys typed = plain_vgetc(); --allow_keys; --no_mapping; // clear the question msg_didout = FALSE; // don't scroll up msg_col = 0; gotocmdline(TRUE); p_lz = save_p_lz; // restore the line if (orig_line != NULL) ml_replace(lnum, orig_line, FALSE); } need_wait_return = FALSE; // no hit-return prompt if (typed == 'q' || typed == ESC || typed == Ctrl_C #ifdef UNIX || typed == intr_char #endif ) { got_quit = TRUE; break; } if (typed == 'n') break; if (typed == 'y') break; if (typed == 'l') { // last: replace and then stop subflags.do_all = FALSE; line2 = lnum; break; } if (typed == 'a') { subflags.do_ask = FALSE; break; } if (typed == Ctrl_E) scrollup_clamp(); else if (typed == Ctrl_Y) scrolldown_clamp(); } State = save_State; setmouse(); if (vim_strchr(p_cpo, CPO_UNDO) != NULL) --no_u_sync; if (typed == 'n') { // For a multi-line match, put matchcol at the NUL at // the end of the line and set nmatch to one, so that // we continue looking for a match on the next line. // Avoids that ":%s/\nB\@=//gc" and ":%s/\n/,\r/gc" // get stuck when pressing 'n'. if (nmatch > 1) { matchcol = (colnr_T)STRLEN(sub_firstline); skip_match = TRUE; } goto skip; } if (got_quit) goto skip; } // Move the cursor to the start of the match, so that we can // use "\=col("."). curwin->w_cursor.col = regmatch.startpos[0].col; /* * 3. substitute the string. */ #ifdef FEAT_EVAL save_ma = curbuf->b_p_ma; if (subflags.do_count) { // prevent accidentally changing the buffer by a function curbuf->b_p_ma = FALSE; sandbox++; } // Save flags for recursion. They can change for e.g. // :s/^/\=execute("s#^##gn") subflags_save = subflags; #endif // get length of substitution part sublen = vim_regsub_multi(&regmatch, sub_firstlnum - regmatch.startpos[0].lnum, sub, sub_firstline, FALSE, magic_isset(), TRUE); #ifdef FEAT_EVAL // If getting the substitute string caused an error, don't do // the replacement. // Don't keep flags set by a recursive call. subflags = subflags_save; if (aborting() || subflags.do_count) { curbuf->b_p_ma = save_ma; if (sandbox > 0) sandbox--; goto skip; } #endif // When the match included the "$" of the last line it may // go beyond the last line of the buffer. if (nmatch > curbuf->b_ml.ml_line_count - sub_firstlnum + 1) { nmatch = curbuf->b_ml.ml_line_count - sub_firstlnum + 1; skip_match = TRUE; } // Need room for: // - result so far in new_start (not for first sub in line) // - original text up to match // - length of substituted part // - original text after match // Adjust text properties here, since we have all information // needed. if (nmatch == 1) { p1 = sub_firstline; #ifdef FEAT_PROP_POPUP if (curbuf->b_has_textprop) { int bytes_added = sublen - 1 - (regmatch.endpos[0].col - regmatch.startpos[0].col); // When text properties are changed, need to save for // undo first, unless done already. if (adjust_prop_columns(lnum, total_added + regmatch.startpos[0].col, bytes_added, apc_flags)) apc_flags &= ~APC_SAVE_FOR_UNDO; // Offset for column byte number of the text property // in the resulting buffer afterwards. total_added += bytes_added; } #endif } else { p1 = ml_get(sub_firstlnum + nmatch - 1); nmatch_tl += nmatch - 1; } copy_len = regmatch.startpos[0].col - copycol; needed_len = copy_len + ((unsigned)STRLEN(p1) - regmatch.endpos[0].col) + sublen + 1; if (new_start == NULL) { /* * Get some space for a temporary buffer to do the * substitution into (and some extra space to avoid * too many calls to alloc()/free()). */ new_start_len = needed_len + 50; if ((new_start = alloc(new_start_len)) == NULL) goto outofmem; *new_start = NUL; new_end = new_start; } else { /* * Check if the temporary buffer is long enough to do the * substitution into. If not, make it larger (with a bit * extra to avoid too many calls to alloc()/free()). */ len = (unsigned)STRLEN(new_start); needed_len += len; if (needed_len > (int)new_start_len) { new_start_len = needed_len + 50; if ((p1 = alloc(new_start_len)) == NULL) { vim_free(new_start); goto outofmem; } mch_memmove(p1, new_start, (size_t)(len + 1)); vim_free(new_start); new_start = p1; } new_end = new_start + len; } /* * copy the text up to the part that matched */ mch_memmove(new_end, sub_firstline + copycol, (size_t)copy_len); new_end += copy_len; (void)vim_regsub_multi(&regmatch, sub_firstlnum - regmatch.startpos[0].lnum, sub, new_end, TRUE, magic_isset(), TRUE); sub_nsubs++; did_sub = TRUE; // Move the cursor to the start of the line, to avoid that it // is beyond the end of the line after the substitution. curwin->w_cursor.col = 0; // For a multi-line match, make a copy of the last matched // line and continue in that one. if (nmatch > 1) { sub_firstlnum += nmatch - 1; vim_free(sub_firstline); sub_firstline = vim_strsave(ml_get(sub_firstlnum)); // When going beyond the last line, stop substituting. if (sub_firstlnum <= line2) do_again = TRUE; else subflags.do_all = FALSE; } // Remember next character to be copied. copycol = regmatch.endpos[0].col; if (skip_match) { // Already hit end of the buffer, sub_firstlnum is one // less than what it ought to be. vim_free(sub_firstline); sub_firstline = vim_strsave((char_u *)""); copycol = 0; } /* * Now the trick is to replace CTRL-M chars with a real line * break. This would make it impossible to insert a CTRL-M in * the text. The line break can be avoided by preceding the * CTRL-M with a backslash. To be able to insert a backslash, * they must be doubled in the string and are halved here. * That is Vi compatible. */ for (p1 = new_end; *p1; ++p1) { if (p1[0] == '\\' && p1[1] != NUL) // remove backslash { STRMOVE(p1, p1 + 1); #ifdef FEAT_PROP_POPUP if (curbuf->b_has_textprop) { // When text properties are changed, need to save // for undo first, unless done already. if (adjust_prop_columns(lnum, (colnr_T)(p1 - new_start), -1, apc_flags)) apc_flags &= ~APC_SAVE_FOR_UNDO; } #endif } else if (*p1 == CAR) { if (u_inssub(lnum) == OK) // prepare for undo { colnr_T plen = (colnr_T)(p1 - new_start + 1); *p1 = NUL; // truncate up to the CR ml_append(lnum - 1, new_start, plen, FALSE); mark_adjust(lnum + 1, (linenr_T)MAXLNUM, 1L, 0L); if (subflags.do_ask) appended_lines(lnum - 1, 1L); else { if (first_line == 0) first_line = lnum; last_line = lnum + 1; } #ifdef FEAT_PROP_POPUP adjust_props_for_split(lnum + 1, lnum, plen, 1); #endif // all line numbers increase ++sub_firstlnum; ++lnum; ++line2; // move the cursor to the new line, like Vi ++curwin->w_cursor.lnum; // copy the rest STRMOVE(new_start, p1 + 1); p1 = new_start - 1; } } else if (has_mbyte) p1 += (*mb_ptr2len)(p1) - 1; } /* * 4. If do_all is set, find next match. * Prevent endless loop with patterns that match empty * strings, e.g. :s/$/pat/g or :s/[a-z]* /(&)/g. * But ":s/\n/#/" is OK. */ skip: // We already know that we did the last subst when we are at // the end of the line, except that a pattern like // "bar\|\nfoo" may match at the NUL. "lnum" can be below // "line2" when there is a \zs in the pattern after a line // break. lastone = (skip_match || got_int || got_quit || lnum > line2 || !(subflags.do_all || do_again) || (sub_firstline[matchcol] == NUL && nmatch <= 1 && !re_multiline(regmatch.regprog))); nmatch = -1; /* * Replace the line in the buffer when needed. This is * skipped when there are more matches. * The check for nmatch_tl is needed for when multi-line * matching must replace the lines before trying to do another * match, otherwise "\@<=" won't work. * When the match starts below where we start searching also * need to replace the line first (using \zs after \n). */ if (lastone || nmatch_tl > 0 || (nmatch = vim_regexec_multi(&regmatch, curwin, curbuf, sub_firstlnum, matchcol, NULL, NULL)) == 0 || regmatch.startpos[0].lnum > 0) { if (new_start != NULL) { /* * Copy the rest of the line, that didn't match. * "matchcol" has to be adjusted, we use the end of * the line as reference, because the substitute may * have changed the number of characters. Same for * "prev_matchcol". */ STRCAT(new_start, sub_firstline + copycol); matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol; prev_matchcol = (colnr_T)STRLEN(sub_firstline) - prev_matchcol; if (u_savesub(lnum) != OK) break; ml_replace(lnum, new_start, TRUE); if (nmatch_tl > 0) { /* * Matched lines have now been substituted and are * useless, delete them. The part after the match * has been appended to new_start, we don't need * it in the buffer. */ ++lnum; if (u_savedel(lnum, nmatch_tl) != OK) break; for (i = 0; i < nmatch_tl; ++i) ml_delete(lnum); mark_adjust(lnum, lnum + nmatch_tl - 1, (long)MAXLNUM, -nmatch_tl); if (subflags.do_ask) deleted_lines(lnum, nmatch_tl); --lnum; line2 -= nmatch_tl; // nr of lines decreases nmatch_tl = 0; } // When asking, undo is saved each time, must also set // changed flag each time. if (subflags.do_ask) changed_bytes(lnum, 0); else { if (first_line == 0) first_line = lnum; last_line = lnum + 1; } sub_firstlnum = lnum; vim_free(sub_firstline); // free the temp buffer sub_firstline = new_start; new_start = NULL; matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol; prev_matchcol = (colnr_T)STRLEN(sub_firstline) - prev_matchcol; copycol = 0; } if (nmatch == -1 && !lastone) nmatch = vim_regexec_multi(&regmatch, curwin, curbuf, sub_firstlnum, matchcol, NULL, NULL); /* * 5. break if there isn't another match in this line */ if (nmatch <= 0) { // If the match found didn't start where we were // searching, do the next search in the line where we // found the match. if (nmatch == -1) lnum -= regmatch.startpos[0].lnum; break; } } line_breakcheck(); } if (did_sub) ++sub_nlines; vim_free(new_start); // for when substitute was cancelled VIM_CLEAR(sub_firstline); // free the copy of the original line } line_breakcheck(); } if (first_line != 0) { // Need to subtract the number of added lines from "last_line" to get // the line number before the change (same as adding the number of // deleted lines). i = curbuf->b_ml.ml_line_count - old_line_count; changed_lines(first_line, 0, last_line - i, i); } outofmem: vim_free(sub_firstline); // may have to free allocated copy of the line // ":s/pat//n" doesn't move the cursor if (subflags.do_count) curwin->w_cursor = old_cursor; if (sub_nsubs > start_nsubs) { if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) { // Set the '[ and '] marks. curbuf->b_op_start.lnum = eap->line1; curbuf->b_op_end.lnum = line2; curbuf->b_op_start.col = curbuf->b_op_end.col = 0; } if (!global_busy) { // when interactive leave cursor on the match if (!subflags.do_ask) { if (endcolumn) coladvance((colnr_T)MAXCOL); else beginline(BL_WHITE | BL_FIX); } if (!do_sub_msg(subflags.do_count) && subflags.do_ask) msg(""); } else global_need_beginline = TRUE; if (subflags.do_print) print_line(curwin->w_cursor.lnum, subflags.do_number, subflags.do_list); } else if (!global_busy) { if (got_int) // interrupted emsg(_(e_interrupted)); else if (got_match) // did find something but nothing substituted msg(""); else if (subflags.do_error) // nothing found semsg(_(e_pattern_not_found_str), get_search_pat()); } #ifdef FEAT_FOLDING if (subflags.do_ask && hasAnyFolding(curwin)) // Cursor position may require updating changed_window_setting(); #endif vim_regfree(regmatch.regprog); vim_free(sub_copy); // Restore the flag values, they can be used for ":&&". subflags.do_all = save_do_all; subflags.do_ask = save_do_ask; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'patch 8.2.4977: memory access error when substitute expression changes window Problem: Memory access error when substitute expression changes window. Solution: Disallow changing window in substitute expression.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: op_format( oparg_T *oap, int keep_cursor) // keep cursor on same text char { long old_line_count = curbuf->b_ml.ml_line_count; // Place the cursor where the "gq" or "gw" command was given, so that "u" // can put it back there. curwin->w_cursor = oap->cursor_start; if (u_save((linenr_T)(oap->start.lnum - 1), (linenr_T)(oap->end.lnum + 1)) == FAIL) return; curwin->w_cursor = oap->start; if (oap->is_VIsual) // When there is no change: need to remove the Visual selection redraw_curbuf_later(INVERTED); if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) // Set '[ mark at the start of the formatted area curbuf->b_op_start = oap->start; // For "gw" remember the cursor position and put it back below (adjusted // for joined and split lines). if (keep_cursor) saved_cursor = oap->cursor_start; format_lines(oap->line_count, keep_cursor); // Leave the cursor at the first non-blank of the last formatted line. // If the cursor was moved one line back (e.g. with "Q}") go to the next // line, so "." will do the next lines. if (oap->end_adjusted && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count) ++curwin->w_cursor.lnum; beginline(BL_WHITE | BL_FIX); old_line_count = curbuf->b_ml.ml_line_count - old_line_count; msgmore(old_line_count); if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) // put '] mark on the end of the formatted area curbuf->b_op_end = curwin->w_cursor; if (keep_cursor) { curwin->w_cursor = saved_cursor; saved_cursor.lnum = 0; } if (oap->is_VIsual) { win_T *wp; FOR_ALL_WINDOWS(wp) { if (wp->w_old_cursor_lnum != 0) { // When lines have been inserted or deleted, adjust the end of // the Visual area to be redrawn. if (wp->w_old_cursor_lnum > wp->w_old_visual_lnum) wp->w_old_cursor_lnum += old_line_count; else wp->w_old_visual_lnum += old_line_count; } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'patch 8.2.5013: after text formatting cursor may be in an invalid position Problem: After text formatting the cursor may be in an invalid position. Solution: Correct the cursor position after formatting.'</s>
<s>[INST] Given the following code containing errors, provide 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 io_match_task_safe(struct io_kiocb *head, struct task_struct *task, bool cancel_all) { if (task && head->task != task) return false; return cancel_all; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'io_uring: reinstate the inflight tracking After some debugging, it was realized that we really do still need the old inflight tracking for any file type that has io_uring_fops assigned. If we don't, then trivial circular references will mean that we never get the ctx cleaned up and hence it'll leak. Just bring back the inflight tracking, which then also means we can eliminate the conditional dropping of the file when task_work is queued. Fixes: d5361233e9ab ("io_uring: drop the old style inflight file tracking") Signed-off-by: Jens Axboe <axboe@kernel.dk>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static struct file *io_file_get_normal(struct io_kiocb *req, int fd) { struct file *file = fget(fd); trace_io_uring_file_get(req->ctx, req, req->cqe.user_data, fd); /* we don't allow fixed io_uring files */ if (file && file->f_op == &io_uring_fops) req->flags |= REQ_F_INFLIGHT; return file; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'io_uring: reinstate the inflight tracking After some debugging, it was realized that we really do still need the old inflight tracking for any file type that has io_uring_fops assigned. If we don't, then trivial circular references will mean that we never get the ctx cleaned up and hence it'll leak. Just bring back the inflight tracking, which then also means we can eliminate the conditional dropping of the file when task_work is queued. Fixes: d5361233e9ab ("io_uring: drop the old style inflight file tracking") Signed-off-by: Jens Axboe <axboe@kernel.dk>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static MOBI_RET mobi_parse_index_entry(MOBIIndx *indx, const MOBIIdxt idxt, const MOBITagx *tagx, const MOBIOrdt *ordt, MOBIBuffer *buf, const size_t curr_number) { if (indx == NULL) { debug_print("%s", "INDX structure not initialized\n"); return MOBI_INIT_FAILED; } const size_t entry_offset = indx->entries_count; const size_t entry_length = idxt.offsets[curr_number + 1] - idxt.offsets[curr_number]; mobi_buffer_setpos(buf, idxt.offsets[curr_number]); size_t entry_number = curr_number + entry_offset; if (entry_number >= indx->total_entries_count) { debug_print("Entry number beyond array: %zu\n", entry_number); return MOBI_DATA_CORRUPT; } /* save original record maxlen */ const size_t buf_maxlen = buf->maxlen; if (buf->offset + entry_length >= buf_maxlen) { debug_print("Entry length too long: %zu\n", entry_length); return MOBI_DATA_CORRUPT; } buf->maxlen = buf->offset + entry_length; size_t label_length = mobi_buffer_get8(buf); if (label_length > entry_length) { debug_print("Label length too long: %zu\n", label_length); return MOBI_DATA_CORRUPT; } char text[INDX_LABEL_SIZEMAX]; /* FIXME: what is ORDT1 for? */ if (ordt->ordt2) { label_length = mobi_getstring_ordt(ordt, buf, (unsigned char*) text, label_length); } else { label_length = mobi_indx_get_label((unsigned char*) text, buf, label_length, indx->ligt_entries_count); } indx->entries[entry_number].label = malloc(label_length + 1); if (indx->entries[entry_number].label == NULL) { debug_print("Memory allocation failed (%zu bytes)\n", label_length); return MOBI_MALLOC_FAILED; } strncpy(indx->entries[entry_number].label, text, label_length + 1); //debug_print("tag label[%zu]: %s\n", entry_number, indx->entries[entry_number].label); unsigned char *control_bytes; control_bytes = buf->data + buf->offset; mobi_buffer_seek(buf, (int) tagx->control_byte_count); indx->entries[entry_number].tags_count = 0; indx->entries[entry_number].tags = NULL; if (tagx->tags_count > 0) { typedef struct { uint8_t tag; uint8_t tag_value_count; uint32_t value_count; uint32_t value_bytes; } MOBIPtagx; MOBIPtagx *ptagx = malloc(tagx->tags_count * sizeof(MOBIPtagx)); if (ptagx == NULL) { debug_print("Memory allocation failed (%zu bytes)\n", tagx->tags_count * sizeof(MOBIPtagx)); return MOBI_MALLOC_FAILED; } uint32_t ptagx_count = 0; size_t len; size_t i = 0; while (i < tagx->tags_count) { if (tagx->tags[i].control_byte == 1) { control_bytes++; i++; continue; } uint32_t value = control_bytes[0] & tagx->tags[i].bitmask; if (value != 0) { /* FIXME: is it safe to use MOBI_NOTSET? */ uint32_t value_count = MOBI_NOTSET; uint32_t value_bytes = MOBI_NOTSET; /* all bits of masked value are set */ if (value == tagx->tags[i].bitmask) { /* more than 1 bit set */ if (mobi_bitcount(tagx->tags[i].bitmask) > 1) { /* read value bytes from entry */ len = 0; value_bytes = mobi_buffer_get_varlen(buf, &len); } else { value_count = 1; } } else { uint8_t mask = tagx->tags[i].bitmask; while ((mask & 1) == 0) { mask >>= 1; value >>= 1; } value_count = value; } ptagx[ptagx_count].tag = tagx->tags[i].tag; ptagx[ptagx_count].tag_value_count = tagx->tags[i].values_count; ptagx[ptagx_count].value_count = value_count; ptagx[ptagx_count].value_bytes = value_bytes; ptagx_count++; } i++; } indx->entries[entry_number].tags = malloc(tagx->tags_count * sizeof(MOBIIndexTag)); if (indx->entries[entry_number].tags == NULL) { debug_print("Memory allocation failed (%zu bytes)\n", tagx->tags_count * sizeof(MOBIIndexTag)); free(ptagx); return MOBI_MALLOC_FAILED; } i = 0; while (i < ptagx_count) { uint32_t tagvalues_count = 0; /* FIXME: is it safe to use MOBI_NOTSET? */ /* value count is set */ uint32_t tagvalues[INDX_TAGVALUES_MAX]; if (ptagx[i].value_count != MOBI_NOTSET) { size_t count = ptagx[i].value_count * ptagx[i].tag_value_count; while (count-- && tagvalues_count < INDX_TAGVALUES_MAX) { len = 0; const uint32_t value_bytes = mobi_buffer_get_varlen(buf, &len); tagvalues[tagvalues_count++] = value_bytes; } /* value count is not set */ } else { /* read value_bytes bytes */ len = 0; while (len < ptagx[i].value_bytes && tagvalues_count < INDX_TAGVALUES_MAX) { const uint32_t value_bytes = mobi_buffer_get_varlen(buf, &len); tagvalues[tagvalues_count++] = value_bytes; } } if (tagvalues_count) { const size_t arr_size = tagvalues_count * sizeof(*indx->entries[entry_number].tags[i].tagvalues); indx->entries[entry_number].tags[i].tagvalues = malloc(arr_size); if (indx->entries[entry_number].tags[i].tagvalues == NULL) { debug_print("Memory allocation failed (%zu bytes)\n", arr_size); free(ptagx); return MOBI_MALLOC_FAILED; } memcpy(indx->entries[entry_number].tags[i].tagvalues, tagvalues, arr_size); } else { indx->entries[entry_number].tags[i].tagvalues = NULL; } indx->entries[entry_number].tags[i].tagid = ptagx[i].tag; indx->entries[entry_number].tags[i].tagvalues_count = tagvalues_count; indx->entries[entry_number].tags_count++; i++; } free(ptagx); } /* restore buffer maxlen */ buf->maxlen = buf_maxlen; return MOBI_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix: index entry label not being zero-terminated with corrupt input'</s>
<s>[INST] Given the following code containing errors, provide 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 open_shell(void) { EUID_ASSERT(); assert(cfg.shell); if (arg_debug) printf("Opening shell %s\n", cfg.shell); // file descriptor will leak if not opened with O_CLOEXEC !! int fd = open(cfg.shell, O_PATH|O_CLOEXEC); if (fd == -1) { fprintf(stderr, "Error: cannot open shell %s\n", cfg.shell); exit(1); } // pass file descriptor through to the final fexecve if (asprintf(&cfg.keep_fd, "%s,%d", cfg.keep_fd ? cfg.keep_fd : "", fd) == -1) errExit("asprintf"); return fd; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-269', 'CWE-94'], 'message': 'fixing CVE-2022-31214'</s>
<s>[INST] Given the following code containing errors, provide 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 preproc_build_firejail_dir(void) { struct stat s; // CentOS 6 doesn't have /run directory if (stat(RUN_FIREJAIL_BASEDIR, &s)) { create_empty_dir_as_root(RUN_FIREJAIL_BASEDIR, 0755); } if (stat(RUN_FIREJAIL_DIR, &s)) { create_empty_dir_as_root(RUN_FIREJAIL_DIR, 0755); } if (stat(RUN_FIREJAIL_NETWORK_DIR, &s)) { create_empty_dir_as_root(RUN_FIREJAIL_NETWORK_DIR, 0755); } if (stat(RUN_FIREJAIL_BANDWIDTH_DIR, &s)) { create_empty_dir_as_root(RUN_FIREJAIL_BANDWIDTH_DIR, 0755); } if (stat(RUN_FIREJAIL_NAME_DIR, &s)) { create_empty_dir_as_root(RUN_FIREJAIL_NAME_DIR, 0755); } if (stat(RUN_FIREJAIL_PROFILE_DIR, &s)) { create_empty_dir_as_root(RUN_FIREJAIL_PROFILE_DIR, 0755); } if (stat(RUN_FIREJAIL_X11_DIR, &s)) { create_empty_dir_as_root(RUN_FIREJAIL_X11_DIR, 0755); } if (stat(RUN_FIREJAIL_DBUS_DIR, &s)) { create_empty_dir_as_root(RUN_FIREJAIL_DBUS_DIR, 0755); if (arg_debug) printf("Remounting the " RUN_FIREJAIL_DBUS_DIR " directory as noexec\n"); if (mount(RUN_FIREJAIL_DBUS_DIR, RUN_FIREJAIL_DBUS_DIR, NULL, MS_BIND, NULL) == -1) errExit("mounting " RUN_FIREJAIL_DBUS_DIR); if (mount(NULL, RUN_FIREJAIL_DBUS_DIR, NULL, MS_REMOUNT | MS_BIND | MS_NOSUID | MS_NOEXEC | MS_NODEV, "mode=755,gid=0") == -1) errExit("remounting " RUN_FIREJAIL_DBUS_DIR); } if (stat(RUN_FIREJAIL_APPIMAGE_DIR, &s)) { create_empty_dir_as_root(RUN_FIREJAIL_APPIMAGE_DIR, 0755); } if (stat(RUN_FIREJAIL_LIB_DIR, &s)) { create_empty_dir_as_root(RUN_FIREJAIL_LIB_DIR, 0755); } if (stat(RUN_MNT_DIR, &s)) { create_empty_dir_as_root(RUN_MNT_DIR, 0755); } create_empty_file_as_root(RUN_RO_FILE, S_IRUSR); fs_remount(RUN_RO_FILE, MOUNT_READONLY, 0); create_empty_dir_as_root(RUN_RO_DIR, S_IRUSR); fs_remount(RUN_RO_DIR, MOUNT_READONLY, 0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-269', 'CWE-94'], 'message': 'fixing CVE-2022-31214'</s>
<s>[INST] Given the following code containing errors, provide 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 extract_cgroup(pid_t pid) { char *fname; if (asprintf(&fname, "/proc/%d/root%s", pid, RUN_CGROUP_CFG) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == -1) { free(fname); return; } // there is a cgroup file CGROUP_CFG, load it! load_cgroup(fname); free(fname); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-269', 'CWE-94'], 'message': 'fixing CVE-2022-31214'</s>
<s>[INST] Given the following code containing errors, provide 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 build_dirs(char *src, char *dst, size_t src_prefix_len, size_t dst_prefix_len) { char *p = src + src_prefix_len + 1; char *q = dst + dst_prefix_len + 1; char *r = dst + dst_prefix_len; struct stat s; bool last = false; *r = '\0'; for (; !last; p++, q++) { if (*p == '\0') { last = true; } if (*p == '\0' || (*p == '/' && *(p - 1) != '/')) { // We found a new component of our src path. // Null-terminate it temporarily here so that we can work // with it. *p = '\0'; if (stat(src, &s) == 0 && S_ISDIR(s.st_mode)) { // Null-terminate the dst path and undo its previous // termination. *q = '\0'; *r = '/'; r = q; create_empty_dir_as_root(dst, s.st_mode); } if (!last) { // If we're not at the final terminating null, restore // the slash so that we can continue our traversal. *p = '/'; } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-269', 'CWE-94'], 'message': 'CVE-2022-31214: fixing the fix'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static size_t php_mysqlnd_change_auth_response_write(MYSQLND_CONN_DATA * conn, void * _packet) { MYSQLND_PACKET_CHANGE_AUTH_RESPONSE *packet= (MYSQLND_PACKET_CHANGE_AUTH_RESPONSE *) _packet; MYSQLND_ERROR_INFO * error_info = conn->error_info; MYSQLND_PFC * pfc = conn->protocol_frame_codec; MYSQLND_VIO * vio = conn->vio; MYSQLND_STATS * stats = conn->stats; MYSQLND_CONNECTION_STATE * connection_state = &conn->state; zend_uchar * const buffer = pfc->cmd_buffer.length >= packet->auth_data_len? pfc->cmd_buffer.buffer : mnd_emalloc(packet->auth_data_len); zend_uchar * p = buffer + MYSQLND_HEADER_SIZE; /* start after the header */ DBG_ENTER("php_mysqlnd_change_auth_response_write"); if (packet->auth_data_len) { memcpy(p, packet->auth_data, packet->auth_data_len); p+= packet->auth_data_len; } { /* The auth handshake packet has no command in it. Thus we can't go over conn->command directly. Well, we can have a command->no_command(conn, payload) */ const size_t sent = pfc->data->m.send(pfc, vio, buffer, p - buffer - MYSQLND_HEADER_SIZE, stats, error_info); if (buffer != pfc->cmd_buffer.buffer) { mnd_efree(buffer); } if (!sent) { SET_CONNECTION_STATE(connection_state, CONN_QUIT_SENT); } DBG_RETURN(sent); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'Fix bug #81719: mysqlnd/pdo password buffer 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: gopherToHTML(GopherStateData * gopherState, char *inbuf, int len) { char *pos = inbuf; char *lpos = NULL; char *tline = NULL; LOCAL_ARRAY(char, line, TEMP_BUF_SIZE); LOCAL_ARRAY(char, tmpbuf, TEMP_BUF_SIZE); char *name = NULL; char *selector = NULL; char *host = NULL; char *port = NULL; char *escaped_selector = NULL; const char *icon_url = NULL; char gtype; StoreEntry *entry = NULL; memset(tmpbuf, '\0', TEMP_BUF_SIZE); memset(line, '\0', TEMP_BUF_SIZE); entry = gopherState->entry; if (gopherState->conversion == GopherStateData::HTML_INDEX_PAGE) { char *html_url = html_quote(entry->url()); gopherHTMLHeader(entry, "Gopher Index %s", html_url); storeAppendPrintf(entry, "<p>This is a searchable Gopher index. Use the search\n" "function of your browser to enter search terms.\n" "<ISINDEX>\n"); gopherHTMLFooter(entry); /* now let start sending stuff to client */ entry->flush(); gopherState->HTML_header_added = 1; return; } if (gopherState->conversion == GopherStateData::HTML_CSO_PAGE) { char *html_url = html_quote(entry->url()); gopherHTMLHeader(entry, "CSO Search of %s", html_url); storeAppendPrintf(entry, "<P>A CSO database usually contains a phonebook or\n" "directory. Use the search function of your browser to enter\n" "search terms.</P><ISINDEX>\n"); gopherHTMLFooter(entry); /* now let start sending stuff to client */ entry->flush(); gopherState->HTML_header_added = 1; return; } String outbuf; if (!gopherState->HTML_header_added) { if (gopherState->conversion == GopherStateData::HTML_CSO_RESULT) gopherHTMLHeader(entry, "CSO Search Result", NULL); else gopherHTMLHeader(entry, "Gopher Menu", NULL); outbuf.append ("<PRE>"); gopherState->HTML_header_added = 1; gopherState->HTML_pre = 1; } while (pos < inbuf + len) { int llen; int left = len - (pos - inbuf); lpos = (char *)memchr(pos, '\n', left); if (lpos) { ++lpos; /* Next line is after \n */ llen = lpos - pos; } else { llen = left; } if (gopherState->len + llen >= TEMP_BUF_SIZE) { debugs(10, DBG_IMPORTANT, "GopherHTML: Buffer overflow. Lost some data on URL: " << entry->url() ); llen = TEMP_BUF_SIZE - gopherState->len - 1; } if (!lpos) { /* there is no complete line in inbuf */ /* copy it to temp buffer */ /* note: llen is adjusted above */ memcpy(gopherState->buf + gopherState->len, pos, llen); gopherState->len += llen; break; } if (gopherState->len != 0) { /* there is something left from last tx. */ memcpy(line, gopherState->buf, gopherState->len); memcpy(line + gopherState->len, pos, llen); llen += gopherState->len; gopherState->len = 0; } else { memcpy(line, pos, llen); } line[llen + 1] = '\0'; /* move input to next line */ pos = lpos; /* at this point. We should have one line in buffer to process */ if (*line == '.') { /* skip it */ memset(line, '\0', TEMP_BUF_SIZE); continue; } switch (gopherState->conversion) { case GopherStateData::HTML_INDEX_RESULT: case GopherStateData::HTML_DIR: { tline = line; gtype = *tline; ++tline; name = tline; selector = strchr(tline, TAB); if (selector) { *selector = '\0'; ++selector; host = strchr(selector, TAB); if (host) { *host = '\0'; ++host; port = strchr(host, TAB); if (port) { char *junk; port[0] = ':'; junk = strchr(host, TAB); if (junk) *junk++ = 0; /* Chop port */ else { junk = strchr(host, '\r'); if (junk) *junk++ = 0; /* Chop port */ else { junk = strchr(host, '\n'); if (junk) *junk++ = 0; /* Chop port */ } } if ((port[1] == '0') && (!port[2])) port[0] = 0; /* 0 means none */ } /* escape a selector here */ escaped_selector = xstrdup(rfc1738_escape_part(selector)); switch (gtype) { case GOPHER_DIRECTORY: icon_url = mimeGetIconURL("internal-menu"); break; case GOPHER_HTML: case GOPHER_FILE: icon_url = mimeGetIconURL("internal-text"); break; case GOPHER_INDEX: case GOPHER_CSO: icon_url = mimeGetIconURL("internal-index"); break; case GOPHER_IMAGE: case GOPHER_GIF: case GOPHER_PLUS_IMAGE: icon_url = mimeGetIconURL("internal-image"); break; case GOPHER_SOUND: case GOPHER_PLUS_SOUND: icon_url = mimeGetIconURL("internal-sound"); break; case GOPHER_PLUS_MOVIE: icon_url = mimeGetIconURL("internal-movie"); break; case GOPHER_TELNET: case GOPHER_3270: icon_url = mimeGetIconURL("internal-telnet"); break; case GOPHER_BIN: case GOPHER_MACBINHEX: case GOPHER_DOSBIN: case GOPHER_UUENCODED: icon_url = mimeGetIconURL("internal-binary"); break; case GOPHER_INFO: icon_url = NULL; break; default: icon_url = mimeGetIconURL("internal-unknown"); break; } memset(tmpbuf, '\0', TEMP_BUF_SIZE); if ((gtype == GOPHER_TELNET) || (gtype == GOPHER_3270)) { if (strlen(escaped_selector) != 0) snprintf(tmpbuf, TEMP_BUF_SIZE, "<IMG border=\"0\" SRC=\"%s\"> <A HREF=\"telnet://%s@%s%s%s/\">%s</A>\n", icon_url, escaped_selector, rfc1738_escape_part(host), *port ? ":" : "", port, html_quote(name)); else snprintf(tmpbuf, TEMP_BUF_SIZE, "<IMG border=\"0\" SRC=\"%s\"> <A HREF=\"telnet://%s%s%s/\">%s</A>\n", icon_url, rfc1738_escape_part(host), *port ? ":" : "", port, html_quote(name)); } else if (gtype == GOPHER_INFO) { snprintf(tmpbuf, TEMP_BUF_SIZE, "\t%s\n", html_quote(name)); } else { if (strncmp(selector, "GET /", 5) == 0) { /* WWW link */ snprintf(tmpbuf, TEMP_BUF_SIZE, "<IMG border=\"0\" SRC=\"%s\"> <A HREF=\"http://%s/%s\">%s</A>\n", icon_url, host, rfc1738_escape_unescaped(selector + 5), html_quote(name)); } else { /* Standard link */ snprintf(tmpbuf, TEMP_BUF_SIZE, "<IMG border=\"0\" SRC=\"%s\"> <A HREF=\"gopher://%s/%c%s\">%s</A>\n", icon_url, host, gtype, escaped_selector, html_quote(name)); } } safe_free(escaped_selector); outbuf.append(tmpbuf); } else { memset(line, '\0', TEMP_BUF_SIZE); continue; } } else { memset(line, '\0', TEMP_BUF_SIZE); continue; } break; } /* HTML_DIR, HTML_INDEX_RESULT */ case GopherStateData::HTML_CSO_RESULT: { if (line[0] == '-') { int code, recno; char *s_code, *s_recno, *result; s_code = strtok(line + 1, ":\n"); s_recno = strtok(NULL, ":\n"); result = strtok(NULL, "\n"); if (!result) break; code = atoi(s_code); recno = atoi(s_recno); if (code != 200) break; if (gopherState->cso_recno != recno) { snprintf(tmpbuf, TEMP_BUF_SIZE, "</PRE><HR noshade size=\"1px\"><H2>Record# %d<br><i>%s</i></H2>\n<PRE>", recno, html_quote(result)); gopherState->cso_recno = recno; } else { snprintf(tmpbuf, TEMP_BUF_SIZE, "%s\n", html_quote(result)); } outbuf.append(tmpbuf); break; } else { int code; char *s_code, *result; s_code = strtok(line, ":"); result = strtok(NULL, "\n"); if (!result) break; code = atoi(s_code); switch (code) { case 200: { /* OK */ /* Do nothing here */ break; } case 102: /* Number of matches */ case 501: /* No Match */ case 502: { /* Too Many Matches */ /* Print the message the server returns */ snprintf(tmpbuf, TEMP_BUF_SIZE, "</PRE><HR noshade size=\"1px\"><H2>%s</H2>\n<PRE>", html_quote(result)); outbuf.append(tmpbuf); break; } } } } /* HTML_CSO_RESULT */ default: break; /* do nothing */ } /* switch */ } /* while loop */ if (outbuf.size() > 0) { entry->append(outbuf.rawBuf(), outbuf.size()); /* now let start sending stuff to client */ entry->flush(); } outbuf.clean(); return; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'Improve handling of Gopher responses (#1022)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ins_bs( int c, int mode, int *inserted_space_p) { linenr_T lnum; int cc; int temp = 0; // init for GCC colnr_T save_col; colnr_T mincol; int did_backspace = FALSE; int in_indent; int oldState; int cpc[MAX_MCO]; // composing characters int call_fix_indent = FALSE; /* * can't delete anything in an empty file * can't backup past first character in buffer * can't backup past starting point unless 'backspace' > 1 * can backup to a previous line if 'backspace' == 0 */ if ( BUFEMPTY() || ( #ifdef FEAT_RIGHTLEFT !revins_on && #endif ((curwin->w_cursor.lnum == 1 && curwin->w_cursor.col == 0) || (!can_bs(BS_START) && ((arrow_used #ifdef FEAT_JOB_CHANNEL && !bt_prompt(curbuf) #endif ) || (curwin->w_cursor.lnum == Insstart_orig.lnum && curwin->w_cursor.col <= Insstart_orig.col))) || (!can_bs(BS_INDENT) && !arrow_used && ai_col > 0 && curwin->w_cursor.col <= ai_col) || (!can_bs(BS_EOL) && curwin->w_cursor.col == 0)))) { vim_beep(BO_BS); return FALSE; } if (stop_arrow() == FAIL) return FALSE; in_indent = inindent(0); if (in_indent) can_cindent = FALSE; end_comment_pending = NUL; // After BS, don't auto-end comment #ifdef FEAT_RIGHTLEFT if (revins_on) // put cursor after last inserted char inc_cursor(); #endif // Virtualedit: // BACKSPACE_CHAR eats a virtual space // BACKSPACE_WORD eats all coladd // BACKSPACE_LINE eats all coladd and keeps going if (curwin->w_cursor.coladd > 0) { if (mode == BACKSPACE_CHAR) { --curwin->w_cursor.coladd; return TRUE; } if (mode == BACKSPACE_WORD) { curwin->w_cursor.coladd = 0; return TRUE; } curwin->w_cursor.coladd = 0; } /* * Delete newline! */ if (curwin->w_cursor.col == 0) { lnum = Insstart.lnum; if (curwin->w_cursor.lnum == lnum #ifdef FEAT_RIGHTLEFT || revins_on #endif ) { if (u_save((linenr_T)(curwin->w_cursor.lnum - 2), (linenr_T)(curwin->w_cursor.lnum + 1)) == FAIL) return FALSE; --Insstart.lnum; Insstart.col = (colnr_T)STRLEN(ml_get(Insstart.lnum)); } /* * In replace mode: * cc < 0: NL was inserted, delete it * cc >= 0: NL was replaced, put original characters back */ cc = -1; if (State & REPLACE_FLAG) cc = replace_pop(); // returns -1 if NL was inserted /* * In replace mode, in the line we started replacing, we only move the * cursor. */ if ((State & REPLACE_FLAG) && curwin->w_cursor.lnum <= lnum) { dec_cursor(); } else { if (!(State & VREPLACE_FLAG) || curwin->w_cursor.lnum > orig_line_count) { temp = gchar_cursor(); // remember current char --curwin->w_cursor.lnum; // When "aw" is in 'formatoptions' we must delete the space at // the end of the line, otherwise the line will be broken // again when auto-formatting. if (has_format_option(FO_AUTO) && has_format_option(FO_WHITE_PAR)) { char_u *ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE); int len; len = (int)STRLEN(ptr); if (len > 0 && ptr[len - 1] == ' ') ptr[len - 1] = NUL; } (void)do_join(2, FALSE, FALSE, FALSE, FALSE); if (temp == NUL && gchar_cursor() != NUL) inc_cursor(); } else dec_cursor(); /* * In MODE_REPLACE mode we have to put back the text that was * replaced by the NL. On the replace stack is first a * NUL-terminated sequence of characters that were deleted and then * the characters that NL replaced. */ if (State & REPLACE_FLAG) { /* * Do the next ins_char() in MODE_NORMAL state, to * prevent ins_char() from replacing characters and * avoiding showmatch(). */ oldState = State; State = MODE_NORMAL; /* * restore characters (blanks) deleted after cursor */ while (cc > 0) { save_col = curwin->w_cursor.col; mb_replace_pop_ins(cc); curwin->w_cursor.col = save_col; cc = replace_pop(); } // restore the characters that NL replaced replace_pop_ins(); State = oldState; } } did_ai = FALSE; } else { /* * Delete character(s) before the cursor. */ #ifdef FEAT_RIGHTLEFT if (revins_on) // put cursor on last inserted char dec_cursor(); #endif mincol = 0; // keep indent if (mode == BACKSPACE_LINE && (curbuf->b_p_ai || cindent_on()) #ifdef FEAT_RIGHTLEFT && !revins_on #endif ) { save_col = curwin->w_cursor.col; beginline(BL_WHITE); if (curwin->w_cursor.col < save_col) { mincol = curwin->w_cursor.col; // should now fix the indent to match with the previous line call_fix_indent = TRUE; } curwin->w_cursor.col = save_col; } /* * Handle deleting one 'shiftwidth' or 'softtabstop'. */ if ( mode == BACKSPACE_CHAR && ((p_sta && in_indent) || ((get_sts_value() != 0 #ifdef FEAT_VARTABS || tabstop_count(curbuf->b_p_vsts_array) #endif ) && curwin->w_cursor.col > 0 && (*(ml_get_cursor() - 1) == TAB || (*(ml_get_cursor() - 1) == ' ' && (!*inserted_space_p || arrow_used)))))) { int ts; colnr_T vcol; colnr_T want_vcol; colnr_T start_vcol; *inserted_space_p = FALSE; // Compute the virtual column where we want to be. Since // 'showbreak' may get in the way, need to get the last column of // the previous character. getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL); start_vcol = vcol; dec_cursor(); getvcol(curwin, &curwin->w_cursor, NULL, NULL, &want_vcol); inc_cursor(); #ifdef FEAT_VARTABS if (p_sta && in_indent) { ts = (int)get_sw_value(curbuf); want_vcol = (want_vcol / ts) * ts; } else want_vcol = tabstop_start(want_vcol, get_sts_value(), curbuf->b_p_vsts_array); #else if (p_sta && in_indent) ts = (int)get_sw_value(curbuf); else ts = (int)get_sts_value(); want_vcol = (want_vcol / ts) * ts; #endif // delete characters until we are at or before want_vcol while (vcol > want_vcol && (cc = *(ml_get_cursor() - 1), VIM_ISWHITE(cc))) ins_bs_one(&vcol); // insert extra spaces until we are at want_vcol while (vcol < want_vcol) { // Remember the first char we inserted if (curwin->w_cursor.lnum == Insstart_orig.lnum && curwin->w_cursor.col < Insstart_orig.col) Insstart_orig.col = curwin->w_cursor.col; if (State & VREPLACE_FLAG) ins_char(' '); else { ins_str((char_u *)" "); if ((State & REPLACE_FLAG)) replace_push(NUL); } getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL); } // If we are now back where we started delete one character. Can // happen when using 'sts' and 'linebreak'. if (vcol >= start_vcol) ins_bs_one(&vcol); } /* * Delete up to starting point, start of line or previous word. */ else { int cclass = 0, prev_cclass = 0; if (has_mbyte) cclass = mb_get_class(ml_get_cursor()); do { #ifdef FEAT_RIGHTLEFT if (!revins_on) // put cursor on char to be deleted #endif dec_cursor(); cc = gchar_cursor(); // look multi-byte character class if (has_mbyte) { prev_cclass = cclass; cclass = mb_get_class(ml_get_cursor()); } // start of word? if (mode == BACKSPACE_WORD && !vim_isspace(cc)) { mode = BACKSPACE_WORD_NOT_SPACE; temp = vim_iswordc(cc); } // end of word? else if (mode == BACKSPACE_WORD_NOT_SPACE && ((vim_isspace(cc) || vim_iswordc(cc) != temp) || prev_cclass != cclass)) { #ifdef FEAT_RIGHTLEFT if (!revins_on) #endif inc_cursor(); #ifdef FEAT_RIGHTLEFT else if (State & REPLACE_FLAG) dec_cursor(); #endif break; } if (State & REPLACE_FLAG) replace_do_bs(-1); else { if (enc_utf8 && p_deco) (void)utfc_ptr2char(ml_get_cursor(), cpc); (void)del_char(FALSE); /* * If there are combining characters and 'delcombine' is set * move the cursor back. Don't back up before the base * character. */ if (enc_utf8 && p_deco && cpc[0] != NUL) inc_cursor(); #ifdef FEAT_RIGHTLEFT if (revins_chars) { revins_chars--; revins_legal++; } if (revins_on && gchar_cursor() == NUL) break; #endif } // Just a single backspace?: if (mode == BACKSPACE_CHAR) break; } while ( #ifdef FEAT_RIGHTLEFT revins_on || #endif (curwin->w_cursor.col > mincol && (can_bs(BS_NOSTOP) || (curwin->w_cursor.lnum != Insstart_orig.lnum || curwin->w_cursor.col != Insstart_orig.col) ))); } did_backspace = TRUE; } did_si = FALSE; can_si = FALSE; can_si_back = FALSE; if (curwin->w_cursor.col <= 1) did_ai = FALSE; if (call_fix_indent) fix_indent(); /* * It's a little strange to put backspaces into the redo * buffer, but it makes auto-indent a lot easier to deal * with. */ AppendCharToRedobuff(c); // If deleted before the insertion point, adjust it if (curwin->w_cursor.lnum == Insstart_orig.lnum && curwin->w_cursor.col < Insstart_orig.col) Insstart_orig.col = curwin->w_cursor.col; // vi behaviour: the cursor moves backward but the character that // was there remains visible // Vim behaviour: the cursor moves backward and the character that // was there is erased from the screen. // We can emulate the vi behaviour by pretending there is a dollar // displayed even when there isn't. // --pkv Sun Jan 19 01:56:40 EST 2003 if (vim_strchr(p_cpo, CPO_BACKSPACE) != NULL && dollar_vcol == -1) dollar_vcol = curwin->w_virtcol; #ifdef FEAT_FOLDING // When deleting a char the cursor line must never be in a closed fold. // E.g., when 'foldmethod' is indent and deleting the first non-white // char before a Tab. if (did_backspace) foldOpenCursor(); #endif return did_backspace; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-122', 'CWE-787'], 'message': 'patch 8.2.5162: reading before the start of the line with BS in Replace mode Problem: Reading before the start of the line with BS in Replace mode. Solution: Check the cursor column is more than zero.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: check_termcode( int max_offset, char_u *buf, int bufsize, int *buflen) { char_u *tp; char_u *p; int slen = 0; // init for GCC int modslen; int len; int retval = 0; int offset; char_u key_name[2]; int modifiers; char_u *modifiers_start = NULL; int key; int new_slen; // Length of what will replace the termcode char_u string[MAX_KEY_CODE_LEN + 1]; int i, j; int idx = 0; int cpo_koffset; cpo_koffset = (vim_strchr(p_cpo, CPO_KOFFSET) != NULL); /* * Speed up the checks for terminal codes by gathering all first bytes * used in termleader[]. Often this is just a single <Esc>. */ if (need_gather) gather_termleader(); /* * Check at several positions in typebuf.tb_buf[], to catch something like * "x<Up>" that can be mapped. Stop at max_offset, because characters * after that cannot be used for mapping, and with @r commands * typebuf.tb_buf[] can become very long. * This is used often, KEEP IT FAST! */ for (offset = 0; offset < max_offset; ++offset) { if (buf == NULL) { if (offset >= typebuf.tb_len) break; tp = typebuf.tb_buf + typebuf.tb_off + offset; len = typebuf.tb_len - offset; // length of the input } else { if (offset >= *buflen) break; tp = buf + offset; len = *buflen - offset; } /* * Don't check characters after K_SPECIAL, those are already * translated terminal chars (avoid translating ~@^Hx). */ if (*tp == K_SPECIAL) { offset += 2; // there are always 2 extra characters continue; } /* * Skip this position if the character does not appear as the first * character in term_strings. This speeds up a lot, since most * termcodes start with the same character (ESC or CSI). */ i = *tp; for (p = termleader; *p && *p != i; ++p) ; if (*p == NUL) continue; /* * Skip this position if p_ek is not set and tp[0] is an ESC and we * are in Insert mode. */ if (*tp == ESC && !p_ek && (State & MODE_INSERT)) continue; key_name[0] = NUL; // no key name found yet key_name[1] = NUL; // no key name found yet modifiers = 0; // no modifiers yet #ifdef FEAT_GUI if (gui.in_use) { /* * GUI special key codes are all of the form [CSI xx]. */ if (*tp == CSI) // Special key from GUI { if (len < 3) return -1; // Shouldn't happen slen = 3; key_name[0] = tp[1]; key_name[1] = tp[2]; } } else #endif // FEAT_GUI { int mouse_index_found = -1; for (idx = 0; idx < tc_len; ++idx) { /* * Ignore the entry if we are not at the start of * typebuf.tb_buf[] * and there are not enough characters to make a match. * But only when the 'K' flag is in 'cpoptions'. */ slen = termcodes[idx].len; modifiers_start = NULL; if (cpo_koffset && offset && len < slen) continue; if (STRNCMP(termcodes[idx].code, tp, (size_t)(slen > len ? len : slen)) == 0) { int looks_like_mouse_start = FALSE; if (len < slen) // got a partial sequence return -1; // need to get more chars /* * When found a keypad key, check if there is another key * that matches and use that one. This makes <Home> to be * found instead of <kHome> when they produce the same * key code. */ if (termcodes[idx].name[0] == 'K' && VIM_ISDIGIT(termcodes[idx].name[1])) { for (j = idx + 1; j < tc_len; ++j) if (termcodes[j].len == slen && STRNCMP(termcodes[idx].code, termcodes[j].code, slen) == 0) { idx = j; break; } } if (slen == 2 && len > 2 && termcodes[idx].code[0] == ESC && termcodes[idx].code[1] == '[') { // The mouse termcode "ESC [" is also the prefix of // "ESC [ I" (focus gained) and other keys. Check some // more bytes to find out. if (!isdigit(tp[2])) { // ESC [ without number following: Only use it when // there is no other match. looks_like_mouse_start = TRUE; } else if (termcodes[idx].name[0] == KS_DEC_MOUSE) { char_u *nr = tp + 2; int count = 0; // If a digit is following it could be a key with // modifier, e.g., ESC [ 1;2P. Can be confused // with DEC_MOUSE, which requires four numbers // following. If not then it can't be a DEC_MOUSE // code. for (;;) { ++count; (void)getdigits(&nr); if (nr >= tp + len) return -1; // partial sequence if (*nr != ';') break; ++nr; if (nr >= tp + len) return -1; // partial sequence } if (count < 4) continue; // no match } } if (looks_like_mouse_start) { // Only use it when there is no other match. if (mouse_index_found < 0) mouse_index_found = idx; } else { key_name[0] = termcodes[idx].name[0]; key_name[1] = termcodes[idx].name[1]; break; } } /* * Check for code with modifier, like xterm uses: * <Esc>[123;*X (modslen == slen - 3) * <Esc>[@;*X (matches <Esc>[X and <Esc>[1;9X ) * Also <Esc>O*X and <M-O>*X (modslen == slen - 2). * When there is a modifier the * matches a number. * When there is no modifier the ;* or * is omitted. */ if (termcodes[idx].modlen > 0 && mouse_index_found < 0) { int at_code; modslen = termcodes[idx].modlen; if (cpo_koffset && offset && len < modslen) continue; at_code = termcodes[idx].code[modslen] == '@'; if (STRNCMP(termcodes[idx].code, tp, (size_t)(modslen > len ? len : modslen)) == 0) { int n; if (len <= modslen) // got a partial sequence return -1; // need to get more chars if (tp[modslen] == termcodes[idx].code[slen - 1]) // no modifiers slen = modslen + 1; else if (tp[modslen] != ';' && modslen == slen - 3) // no match for "code;*X" with "code;" continue; else if (at_code && tp[modslen] != '1') // no match for "<Esc>[@" with "<Esc>[1" continue; else { // Skip over the digits, the final char must // follow. URXVT can use a negative value, thus // also accept '-'. for (j = slen - 2; j < len && (isdigit(tp[j]) || tp[j] == '-' || tp[j] == ';'); ++j) ; ++j; if (len < j) // got a partial sequence return -1; // need to get more chars if (tp[j - 1] != termcodes[idx].code[slen - 1]) continue; // no match modifiers_start = tp + slen - 2; // Match! Convert modifier bits. n = atoi((char *)modifiers_start); modifiers |= decode_modifiers(n); slen = j; } key_name[0] = termcodes[idx].name[0]; key_name[1] = termcodes[idx].name[1]; break; } } } if (idx == tc_len && mouse_index_found >= 0) { key_name[0] = termcodes[mouse_index_found].name[0]; key_name[1] = termcodes[mouse_index_found].name[1]; } } #ifdef FEAT_TERMRESPONSE if (key_name[0] == NUL // Mouse codes of DEC and pterm start with <ESC>[. When // detecting the start of these mouse codes they might as well be // another key code or terminal response. # ifdef FEAT_MOUSE_DEC || key_name[0] == KS_DEC_MOUSE # endif # ifdef FEAT_MOUSE_PTERM || key_name[0] == KS_PTERM_MOUSE # endif ) { char_u *argp = tp[0] == ESC ? tp + 2 : tp + 1; /* * Check for responses from the terminal starting with {lead}: * "<Esc>[" or CSI followed by [0-9>?] * * - Xterm version string: {lead}>{x};{vers};{y}c * Also eat other possible responses to t_RV, rxvt returns * "{lead}?1;2c". * * - Cursor position report: {lead}{row};{col}R * The final byte must be 'R'. It is used for checking the * ambiguous-width character state. * * - window position reply: {lead}3;{x};{y}t * * - key with modifiers when modifyOtherKeys is enabled: * {lead}27;{modifier};{key}~ * {lead}{key};{modifier}u */ if (((tp[0] == ESC && len >= 3 && tp[1] == '[') || (tp[0] == CSI && len >= 2)) && (VIM_ISDIGIT(*argp) || *argp == '>' || *argp == '?')) { int resp = handle_csi(tp, len, argp, offset, buf, bufsize, buflen, key_name, &slen); if (resp != 0) { # ifdef DEBUG_TERMRESPONSE if (resp == -1) LOG_TR(("Not enough characters for CSI sequence")); # endif return resp; } } // Check for fore/background color response from the terminal, // starting} with <Esc>] or OSC else if ((*T_RBG != NUL || *T_RFG != NUL) && ((tp[0] == ESC && len >= 2 && tp[1] == ']') || tp[0] == OSC)) { if (handle_osc(tp, argp, len, key_name, &slen) == FAIL) return -1; } // Check for key code response from xterm, // starting with <Esc>P or DCS else if ((check_for_codes || rcs_status.tr_progress == STATUS_SENT) && ((tp[0] == ESC && len >= 2 && tp[1] == 'P') || tp[0] == DCS)) { if (handle_dcs(tp, argp, len, key_name, &slen) == FAIL) return -1; } } #endif if (key_name[0] == NUL) continue; // No match at this position, try next one // We only get here when we have a complete termcode match #ifdef FEAT_GUI /* * Only in the GUI: Fetch the pointer coordinates of the scroll event * so that we know which window to scroll later. */ if (gui.in_use && key_name[0] == (int)KS_EXTRA && (key_name[1] == (int)KE_X1MOUSE || key_name[1] == (int)KE_X2MOUSE || key_name[1] == (int)KE_MOUSEMOVE_XY || key_name[1] == (int)KE_MOUSELEFT || key_name[1] == (int)KE_MOUSERIGHT || key_name[1] == (int)KE_MOUSEDOWN || key_name[1] == (int)KE_MOUSEUP)) { char_u bytes[6]; int num_bytes = get_bytes_from_buf(tp + slen, bytes, 4); if (num_bytes == -1) // not enough coordinates return -1; mouse_col = 128 * (bytes[0] - ' ' - 1) + bytes[1] - ' ' - 1; mouse_row = 128 * (bytes[2] - ' ' - 1) + bytes[3] - ' ' - 1; slen += num_bytes; // equal to K_MOUSEMOVE if (key_name[1] == (int)KE_MOUSEMOVE_XY) key_name[1] = (int)KE_MOUSEMOVE; } else #endif /* * If it is a mouse click, get the coordinates. */ if (key_name[0] == KS_MOUSE #ifdef FEAT_MOUSE_GPM || key_name[0] == KS_GPM_MOUSE #endif #ifdef FEAT_MOUSE_JSB || key_name[0] == KS_JSBTERM_MOUSE #endif #ifdef FEAT_MOUSE_NET || key_name[0] == KS_NETTERM_MOUSE #endif #ifdef FEAT_MOUSE_DEC || key_name[0] == KS_DEC_MOUSE #endif #ifdef FEAT_MOUSE_PTERM || key_name[0] == KS_PTERM_MOUSE #endif #ifdef FEAT_MOUSE_URXVT || key_name[0] == KS_URXVT_MOUSE #endif || key_name[0] == KS_SGR_MOUSE || key_name[0] == KS_SGR_MOUSE_RELEASE) { if (check_termcode_mouse(tp, &slen, key_name, modifiers_start, idx, &modifiers) == -1) return -1; } #ifdef FEAT_GUI /* * If using the GUI, then we get menu and scrollbar events. * * A menu event is encoded as K_SPECIAL, KS_MENU, KE_FILLER followed by * four bytes which are to be taken as a pointer to the vimmenu_T * structure. * * A tab line event is encoded as K_SPECIAL KS_TABLINE nr, where "nr" * is one byte with the tab index. * * A scrollbar event is K_SPECIAL, KS_VER_SCROLLBAR, KE_FILLER followed * by one byte representing the scrollbar number, and then four bytes * representing a long_u which is the new value of the scrollbar. * * A horizontal scrollbar event is K_SPECIAL, KS_HOR_SCROLLBAR, * KE_FILLER followed by four bytes representing a long_u which is the * new value of the scrollbar. */ # ifdef FEAT_MENU else if (key_name[0] == (int)KS_MENU) { long_u val; int num_bytes = get_long_from_buf(tp + slen, &val); if (num_bytes == -1) return -1; current_menu = (vimmenu_T *)val; slen += num_bytes; // The menu may have been deleted right after it was used, check // for that. if (check_menu_pointer(root_menu, current_menu) == FAIL) { key_name[0] = KS_EXTRA; key_name[1] = (int)KE_IGNORE; } } # endif # ifdef FEAT_GUI_TABLINE else if (key_name[0] == (int)KS_TABLINE) { // Selecting tabline tab or using its menu. char_u bytes[6]; int num_bytes = get_bytes_from_buf(tp + slen, bytes, 1); if (num_bytes == -1) return -1; current_tab = (int)bytes[0]; if (current_tab == 255) // -1 in a byte gives 255 current_tab = -1; slen += num_bytes; } else if (key_name[0] == (int)KS_TABMENU) { // Selecting tabline tab or using its menu. char_u bytes[6]; int num_bytes = get_bytes_from_buf(tp + slen, bytes, 2); if (num_bytes == -1) return -1; current_tab = (int)bytes[0]; current_tabmenu = (int)bytes[1]; slen += num_bytes; } # endif # ifndef USE_ON_FLY_SCROLL else if (key_name[0] == (int)KS_VER_SCROLLBAR) { long_u val; char_u bytes[6]; int num_bytes; // Get the last scrollbar event in the queue of the same type j = 0; for (i = 0; tp[j] == CSI && tp[j + 1] == KS_VER_SCROLLBAR && tp[j + 2] != NUL; ++i) { j += 3; num_bytes = get_bytes_from_buf(tp + j, bytes, 1); if (num_bytes == -1) break; if (i == 0) current_scrollbar = (int)bytes[0]; else if (current_scrollbar != (int)bytes[0]) break; j += num_bytes; num_bytes = get_long_from_buf(tp + j, &val); if (num_bytes == -1) break; scrollbar_value = val; j += num_bytes; slen = j; } if (i == 0) // not enough characters to make one return -1; } else if (key_name[0] == (int)KS_HOR_SCROLLBAR) { long_u val; int num_bytes; // Get the last horiz. scrollbar event in the queue j = 0; for (i = 0; tp[j] == CSI && tp[j + 1] == KS_HOR_SCROLLBAR && tp[j + 2] != NUL; ++i) { j += 3; num_bytes = get_long_from_buf(tp + j, &val); if (num_bytes == -1) break; scrollbar_value = val; j += num_bytes; slen = j; } if (i == 0) // not enough characters to make one return -1; } # endif // !USE_ON_FLY_SCROLL #endif // FEAT_GUI #if (defined(UNIX) || defined(VMS)) /* * Handle FocusIn/FocusOut event sequences reported by XTerm. * (CSI I/CSI O) */ if (key_name[0] == KS_EXTRA # ifdef FEAT_GUI && !gui.in_use # endif ) { if (key_name[1] == KE_FOCUSGAINED) { if (!focus_state) { ui_focus_change(TRUE); did_cursorhold = TRUE; focus_state = TRUE; } key_name[1] = (int)KE_IGNORE; } else if (key_name[1] == KE_FOCUSLOST) { if (focus_state) { ui_focus_change(FALSE); did_cursorhold = TRUE; focus_state = FALSE; } key_name[1] = (int)KE_IGNORE; } } #endif /* * Change <xHome> to <Home>, <xUp> to <Up>, etc. */ key = handle_x_keys(TERMCAP2KEY(key_name[0], key_name[1])); /* * Add any modifier codes to our string. */ new_slen = modifiers2keycode(modifiers, &key, string); // Finally, add the special key code to our string key_name[0] = KEY2TERMCAP0(key); key_name[1] = KEY2TERMCAP1(key); if (key_name[0] == KS_KEY) { // from ":set <M-b>=xx" if (has_mbyte) new_slen += (*mb_char2bytes)(key_name[1], string + new_slen); else string[new_slen++] = key_name[1]; } else if (new_slen == 0 && key_name[0] == KS_EXTRA && key_name[1] == KE_IGNORE) { // Do not put K_IGNORE into the buffer, do return KEYLEN_REMOVED // to indicate what happened. retval = KEYLEN_REMOVED; } else { string[new_slen++] = K_SPECIAL; string[new_slen++] = key_name[0]; string[new_slen++] = key_name[1]; } if (put_string_in_typebuf(offset, slen, string, new_slen, buf, bufsize, buflen) == FAIL) return -1; return retval == 0 ? (len + new_slen - slen + offset) : retval; } #ifdef FEAT_TERMRESPONSE LOG_TR(("normal character")); #endif return 0; // no match found } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-787'], 'message': 'patch 9.0.0018: going over the end of the typahead Problem: Going over the end of the typahead. Solution: Put a NUL after the typeahead.'</s>
<s>[INST] Given the following code containing errors, provide 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 rose_start_hbtimer(struct sock *sk) { struct rose_sock *rose = rose_sk(sk); del_timer(&rose->timer); rose->timer.function = rose_timer_expiry; rose->timer.expires = jiffies + rose->hb; add_timer(&rose->timer); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'net: rose: fix UAF bugs caused by timer handler There are UAF bugs in rose_heartbeat_expiry(), rose_timer_expiry() and rose_idletimer_expiry(). The root cause is that del_timer() could not stop the timer handler that is running and the refcount of sock is not managed properly. One of the UAF bugs is shown below: (thread 1) | (thread 2) | rose_bind | rose_connect | rose_start_heartbeat rose_release | (wait a time) case ROSE_STATE_0 | rose_destroy_socket | rose_heartbeat_expiry rose_stop_heartbeat | sock_put(sk) | ... sock_put(sk) // FREE | | bh_lock_sock(sk) // USE The sock is deallocated by sock_put() in rose_release() and then used by bh_lock_sock() in rose_heartbeat_expiry(). Although rose_destroy_socket() calls rose_stop_heartbeat(), it could not stop the timer that is running. The KASAN report triggered by POC is shown below: BUG: KASAN: use-after-free in _raw_spin_lock+0x5a/0x110 Write of size 4 at addr ffff88800ae59098 by task swapper/3/0 ... Call Trace: <IRQ> dump_stack_lvl+0xbf/0xee print_address_description+0x7b/0x440 print_report+0x101/0x230 ? irq_work_single+0xbb/0x140 ? _raw_spin_lock+0x5a/0x110 kasan_report+0xed/0x120 ? _raw_spin_lock+0x5a/0x110 kasan_check_range+0x2bd/0x2e0 _raw_spin_lock+0x5a/0x110 rose_heartbeat_expiry+0x39/0x370 ? rose_start_heartbeat+0xb0/0xb0 call_timer_fn+0x2d/0x1c0 ? rose_start_heartbeat+0xb0/0xb0 expire_timers+0x1f3/0x320 __run_timers+0x3ff/0x4d0 run_timer_softirq+0x41/0x80 __do_softirq+0x233/0x544 irq_exit_rcu+0x41/0xa0 sysvec_apic_timer_interrupt+0x8c/0xb0 </IRQ> <TASK> asm_sysvec_apic_timer_interrupt+0x1b/0x20 RIP: 0010:default_idle+0xb/0x10 RSP: 0018:ffffc9000012fea0 EFLAGS: 00000202 RAX: 000000000000bcae RBX: ffff888006660f00 RCX: 000000000000bcae RDX: 0000000000000001 RSI: ffffffff843a11c0 RDI: ffffffff843a1180 RBP: dffffc0000000000 R08: dffffc0000000000 R09: ffffed100da36d46 R10: dfffe9100da36d47 R11: ffffffff83cf0950 R12: 0000000000000000 R13: 1ffff11000ccc1e0 R14: ffffffff8542af28 R15: dffffc0000000000 ... Allocated by task 146: __kasan_kmalloc+0xc4/0xf0 sk_prot_alloc+0xdd/0x1a0 sk_alloc+0x2d/0x4e0 rose_create+0x7b/0x330 __sock_create+0x2dd/0x640 __sys_socket+0xc7/0x270 __x64_sys_socket+0x71/0x80 do_syscall_64+0x43/0x90 entry_SYSCALL_64_after_hwframe+0x46/0xb0 Freed by task 152: kasan_set_track+0x4c/0x70 kasan_set_free_info+0x1f/0x40 ____kasan_slab_free+0x124/0x190 kfree+0xd3/0x270 __sk_destruct+0x314/0x460 rose_release+0x2fa/0x3b0 sock_close+0xcb/0x230 __fput+0x2d9/0x650 task_work_run+0xd6/0x160 exit_to_user_mode_loop+0xc7/0xd0 exit_to_user_mode_prepare+0x4e/0x80 syscall_exit_to_user_mode+0x20/0x40 do_syscall_64+0x4f/0x90 entry_SYSCALL_64_after_hwframe+0x46/0xb0 This patch adds refcount of sock when we use functions such as rose_start_heartbeat() and so on to start timer, and decreases the refcount of sock when timer is finished or deleted by functions such as rose_stop_heartbeat() and so on. As a result, the UAF bugs could be mitigated. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Signed-off-by: Duoming Zhou <duoming@zju.edu.cn> Tested-by: Duoming Zhou <duoming@zju.edu.cn> Link: https://lore.kernel.org/r/20220629002640.5693-1-duoming@zju.edu.cn Signed-off-by: Paolo Abeni <pabeni@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void luaV_concat (lua_State *L, int total) { if (total == 1) return; /* "all" values already concatenated */ do { StkId top = L->top; int n = 2; /* number of elements handled in this pass (at least 2) */ if (!(ttisstring(s2v(top - 2)) || cvt2str(s2v(top - 2))) || !tostring(L, s2v(top - 1))) luaT_tryconcatTM(L); else if (isemptystr(s2v(top - 1))) /* second operand is empty? */ cast_void(tostring(L, s2v(top - 2))); /* result is first operand */ else if (isemptystr(s2v(top - 2))) { /* first operand is empty string? */ setobjs2s(L, top - 2, top - 1); /* result is second op. */ } else { /* at least two non-empty string values; get as many as possible */ size_t tl = vslen(s2v(top - 1)); TString *ts; /* collect total length and number of strings */ for (n = 1; n < total && tostring(L, s2v(top - n - 1)); n++) { size_t l = vslen(s2v(top - n - 1)); if (l_unlikely(l >= (MAX_SIZE/sizeof(char)) - tl)) luaG_runerror(L, "string length overflow"); tl += l; } if (tl <= LUAI_MAXSHORTLEN) { /* is result a short string? */ char buff[LUAI_MAXSHORTLEN]; copy2buff(top, n, buff); /* copy strings to buffer */ ts = luaS_newlstr(L, buff, tl); } else { /* long string; copy strings directly to final result */ ts = luaS_createlngstrobj(L, tl); copy2buff(top, n, getstr(ts)); } setsvalue2s(L, top - n, ts); /* create result */ } total -= n-1; /* got 'n' strings to create 1 new */ L->top -= n-1; /* popped 'n' strings and pushed one */ } while (total > 1); /* repeat until only 1 result left */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Save stack space while handling errors Because error handling (luaG_errormsg) uses slots from EXTRA_STACK, and some errors can recur (e.g., string overflow while creating an error message in 'luaG_runerror', or a C-stack overflow before calling the message handler), the code should use stack slots with parsimony. This commit fixes the bug "Lua-stack overflow when C stack overflows while handling an error".'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: DU_getStringDOElement(DcmItem *obj, DcmTagKey t, char *s, size_t bufsize) { DcmByteString *elem; DcmStack stack; OFCondition ec = EC_Normal; char* aString; ec = obj->search(t, stack); elem = (DcmByteString*) stack.top(); if (ec == EC_Normal && elem != NULL) { if (elem->getLength() == 0) { s[0] = '\0'; } else { ec = elem->getString(aString); OFStandard::strlcpy(s, aString, bufsize); } } return (ec == EC_Normal); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-787'], 'message': 'Fixed possible NULL pointer dereference. Thanks to Jinsheng Ba <bajinsheng@u.nus.edu> for the report and patch.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: private int save_cont(struct magic_set *ms, struct cont *c) { size_t len; *c = ms->c; len = c->len * sizeof(*c->li); ms->c.li = CAST(struct level_info *, malloc(len)); if (ms->c.li == NULL) { ms->c = *c; return -1; } memcpy(ms->c.li, c->li, len); ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix #81723: Memory corruption in finfo_buffer() We need to use the same memory allocator throughout.'</s>
<s>[INST] Given the following code containing errors, provide 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 con_install(struct tty_driver *driver, struct tty_struct *tty) { unsigned int currcons = tty->index; struct vc_data *vc; int ret; console_lock(); ret = vc_allocate(currcons); if (ret) goto unlock; vc = vc_cons[currcons].d; /* Still being freed */ if (vc->port.tty) { ret = -ERESTARTSYS; goto unlock; } ret = tty_port_install(&vc->port, driver, tty); if (ret) goto unlock; tty->driver_data = vc; vc->port.tty = tty; if (!tty->winsize.ws_row && !tty->winsize.ws_col) { tty->winsize.ws_row = vc_cons[currcons].d->vc_rows; tty->winsize.ws_col = vc_cons[currcons].d->vc_cols; } if (vc->vc_utf) tty->termios.c_iflag |= IUTF8; else tty->termios.c_iflag &= ~IUTF8; unlock: console_unlock(); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-362'], 'message': 'vt: vt_ioctl: fix VT_DISALLOCATE freeing in-use virtual console The VT_DISALLOCATE ioctl can free a virtual console while tty_release() is still running, causing a use-after-free in con_shutdown(). This occurs because VT_DISALLOCATE considers a virtual console's 'struct vc_data' to be unused as soon as the corresponding tty's refcount hits 0. But actually it may be still being closed. Fix this by making vc_data be reference-counted via the embedded 'struct tty_port'. A newly allocated virtual console has refcount 1. Opening it for the first time increments the refcount to 2. Closing it for the last time decrements the refcount (in tty_operations::cleanup() so that it happens late enough), as does VT_DISALLOCATE. Reproducer: #include <fcntl.h> #include <linux/vt.h> #include <sys/ioctl.h> #include <unistd.h> int main() { if (fork()) { for (;;) close(open("/dev/tty5", O_RDWR)); } else { int fd = open("/dev/tty10", O_RDWR); for (;;) ioctl(fd, VT_DISALLOCATE, 5); } } KASAN report: BUG: KASAN: use-after-free in con_shutdown+0x76/0x80 drivers/tty/vt/vt.c:3278 Write of size 8 at addr ffff88806a4ec108 by task syz_vt/129 CPU: 0 PID: 129 Comm: syz_vt Not tainted 5.6.0-rc2 #11 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS ?-20191223_100556-anatol 04/01/2014 Call Trace: [...] con_shutdown+0x76/0x80 drivers/tty/vt/vt.c:3278 release_tty+0xa8/0x410 drivers/tty/tty_io.c:1514 tty_release_struct+0x34/0x50 drivers/tty/tty_io.c:1629 tty_release+0x984/0xed0 drivers/tty/tty_io.c:1789 [...] Allocated by task 129: [...] kzalloc include/linux/slab.h:669 [inline] vc_allocate drivers/tty/vt/vt.c:1085 [inline] vc_allocate+0x1ac/0x680 drivers/tty/vt/vt.c:1066 con_install+0x4d/0x3f0 drivers/tty/vt/vt.c:3229 tty_driver_install_tty drivers/tty/tty_io.c:1228 [inline] tty_init_dev+0x94/0x350 drivers/tty/tty_io.c:1341 tty_open_by_driver drivers/tty/tty_io.c:1987 [inline] tty_open+0x3ca/0xb30 drivers/tty/tty_io.c:2035 [...] Freed by task 130: [...] kfree+0xbf/0x1e0 mm/slab.c:3757 vt_disallocate drivers/tty/vt/vt_ioctl.c:300 [inline] vt_ioctl+0x16dc/0x1e30 drivers/tty/vt/vt_ioctl.c:818 tty_ioctl+0x9db/0x11b0 drivers/tty/tty_io.c:2660 [...] Fixes: 4001d7b7fc27 ("vt: push down the tty lock so we can see what is left to tackle") Cc: <stable@vger.kernel.org> # v3.4+ Reported-by: syzbot+522643ab5729b0421998@syzkaller.appspotmail.com Acked-by: Jiri Slaby <jslaby@suse.cz> Signed-off-by: Eric Biggers <ebiggers@google.com> Link: https://lore.kernel.org/r/20200322034305.210082-2-ebiggers@kernel.org Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: asmlinkage __visible void __init xen_start_kernel(void) { struct physdev_set_iopl set_iopl; unsigned long initrd_start = 0; int rc; if (!xen_start_info) return; __text_gen_insn(&early_xen_iret_patch, JMP32_INSN_OPCODE, &early_xen_iret_patch, &xen_iret, JMP32_INSN_SIZE); xen_domain_type = XEN_PV_DOMAIN; xen_start_flags = xen_start_info->flags; xen_setup_features(); /* Install Xen paravirt ops */ pv_info = xen_info; pv_ops.cpu = xen_cpu_ops.cpu; xen_init_irq_ops(); /* * Setup xen_vcpu early because it is needed for * local_irq_disable(), irqs_disabled(), e.g. in printk(). * * Don't do the full vcpu_info placement stuff until we have * the cpu_possible_mask and a non-dummy shared_info. */ xen_vcpu_info_reset(0); x86_platform.get_nmi_reason = xen_get_nmi_reason; x86_init.resources.memory_setup = xen_memory_setup; x86_init.irqs.intr_mode_select = x86_init_noop; x86_init.irqs.intr_mode_init = x86_init_noop; x86_init.oem.arch_setup = xen_arch_setup; x86_init.oem.banner = xen_banner; x86_init.hyper.init_platform = xen_pv_init_platform; x86_init.hyper.guest_late_init = xen_pv_guest_late_init; /* * Set up some pagetable state before starting to set any ptes. */ xen_setup_machphys_mapping(); xen_init_mmu_ops(); /* Prevent unwanted bits from being set in PTEs. */ __supported_pte_mask &= ~_PAGE_GLOBAL; __default_kernel_pte_mask &= ~_PAGE_GLOBAL; /* Get mfn list */ xen_build_dynamic_phys_to_machine(); /* Work out if we support NX */ get_cpu_cap(&boot_cpu_data); x86_configure_nx(); /* * Set up kernel GDT and segment registers, mainly so that * -fstack-protector code can be executed. */ xen_setup_gdt(0); /* Determine virtual and physical address sizes */ get_cpu_address_sizes(&boot_cpu_data); /* Let's presume PV guests always boot on vCPU with id 0. */ per_cpu(xen_vcpu_id, 0) = 0; idt_setup_early_handler(); xen_init_capabilities(); #ifdef CONFIG_X86_LOCAL_APIC /* * set up the basic apic ops. */ xen_init_apic(); #endif machine_ops = xen_machine_ops; /* * The only reliable way to retain the initial address of the * percpu gdt_page is to remember it here, so we can go and * mark it RW later, when the initial percpu area is freed. */ xen_initial_gdt = &per_cpu(gdt_page, 0); xen_smp_init(); #ifdef CONFIG_ACPI_NUMA /* * The pages we from Xen are not related to machine pages, so * any NUMA information the kernel tries to get from ACPI will * be meaningless. Prevent it from trying. */ disable_srat(); #endif WARN_ON(xen_cpuhp_setup(xen_cpu_up_prepare_pv, xen_cpu_dead_pv)); local_irq_disable(); early_boot_irqs_disabled = true; xen_raw_console_write("mapping kernel into physical memory\n"); xen_setup_kernel_pagetable((pgd_t *)xen_start_info->pt_base, xen_start_info->nr_pages); xen_reserve_special_pages(); /* * We used to do this in xen_arch_setup, but that is too late * on AMD were early_cpu_init (run before ->arch_setup()) calls * early_amd_init which pokes 0xcf8 port. */ set_iopl.iopl = 1; rc = HYPERVISOR_physdev_op(PHYSDEVOP_set_iopl, &set_iopl); if (rc != 0) xen_raw_printk("physdev_op failed %d\n", rc); if (xen_start_info->mod_start) { if (xen_start_info->flags & SIF_MOD_START_PFN) initrd_start = PFN_PHYS(xen_start_info->mod_start); else initrd_start = __pa(xen_start_info->mod_start); } /* Poke various useful things into boot_params */ boot_params.hdr.type_of_loader = (9 << 4) | 0; boot_params.hdr.ramdisk_image = initrd_start; boot_params.hdr.ramdisk_size = xen_start_info->mod_len; boot_params.hdr.cmd_line_ptr = __pa(xen_start_info->cmd_line); boot_params.hdr.hardware_subarch = X86_SUBARCH_XEN; if (!xen_initial_domain()) { if (pci_xen) x86_init.pci.arch_init = pci_xen_init; x86_platform.set_legacy_features = xen_domu_set_legacy_features; } else { const struct dom0_vga_console_info *info = (void *)((char *)xen_start_info + xen_start_info->console.dom0.info_off); struct xen_platform_op op = { .cmd = XENPF_firmware_info, .interface_version = XENPF_INTERFACE_VERSION, .u.firmware_info.type = XEN_FW_KBD_SHIFT_FLAGS, }; x86_platform.set_legacy_features = xen_dom0_set_legacy_features; xen_init_vga(info, xen_start_info->console.dom0.info_size); xen_start_info->console.domU.mfn = 0; xen_start_info->console.domU.evtchn = 0; if (HYPERVISOR_platform_op(&op) == 0) boot_params.kbd_status = op.u.firmware_info.u.kbd_shift_flags; /* Make sure ACS will be enabled */ pci_request_acs(); xen_acpi_sleep_register(); xen_boot_params_init_edd(); #ifdef CONFIG_ACPI /* * Disable selecting "Firmware First mode" for correctable * memory errors, as this is the duty of the hypervisor to * decide. */ acpi_disable_cmcff = 1; #endif } xen_add_preferred_consoles(); #ifdef CONFIG_PCI /* PCI BIOS service won't work from a PV guest. */ pci_probe &= ~PCI_PROBE_BIOS; #endif xen_raw_console_write("about to get started...\n"); /* We need this for printk timestamps */ xen_setup_runstate_info(0); xen_efi_init(&boot_params); /* Start the world */ cr4_init_shadow(); /* 32b kernel does this in i386_start_kernel() */ x86_64_start_reservations((char *)__pa_symbol(&boot_params)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'x86/xen: Use clear_bss() for Xen PV guests Instead of clearing the bss area in assembly code, use the clear_bss() function. This requires to pass the start_info address as parameter to xen_start_kernel() in order to avoid the xen_start_info being zeroed again. Signed-off-by: Juergen Gross <jgross@suse.com> Signed-off-by: Borislav Petkov <bp@suse.de> Reviewed-by: Jan Beulich <jbeulich@suse.com> Reviewed-by: Boris Ostrovsky <boris.ostrovsky@oracle.com> Link: https://lore.kernel.org/r/20220630071441.28576-2-jgross@suse.com'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ZEXPORT inflate(strm, flush) z_streamp strm; int flush; { struct inflate_state FAR *state; z_const unsigned char FAR *next; /* next input */ unsigned char FAR *put; /* next output */ unsigned have, left; /* available input and output */ unsigned long hold; /* bit buffer */ unsigned bits; /* bits in bit buffer */ unsigned in, out; /* save starting available input and output */ unsigned copy; /* number of stored or match bytes to copy */ unsigned char FAR *from; /* where to copy match bytes from */ code here; /* current decoding table entry */ code last; /* parent table entry */ unsigned len; /* length to copy for repeats, bits to drop */ int ret; /* return code */ #ifdef GUNZIP unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ #endif static const unsigned short order[19] = /* permutation of code lengths */ {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; if (inflateStateCheck(strm) || strm->next_out == Z_NULL || (strm->next_in == Z_NULL && strm->avail_in != 0)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ LOAD(); in = have; out = left; ret = Z_OK; for (;;) switch (state->mode) { case HEAD: if (state->wrap == 0) { state->mode = TYPEDO; break; } NEEDBITS(16); #ifdef GUNZIP if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ if (state->wbits == 0) state->wbits = 15; state->check = crc32(0L, Z_NULL, 0); CRC2(state->check, hold); INITBITS(); state->mode = FLAGS; break; } if (state->head != Z_NULL) state->head->done = -1; if (!(state->wrap & 1) || /* check if zlib header allowed */ #else if ( #endif ((BITS(8) << 8) + (hold >> 8)) % 31) { strm->msg = (char *)"incorrect header check"; state->mode = BAD; break; } if (BITS(4) != Z_DEFLATED) { strm->msg = (char *)"unknown compression method"; state->mode = BAD; break; } DROPBITS(4); len = BITS(4) + 8; if (state->wbits == 0) state->wbits = len; if (len > 15 || len > state->wbits) { strm->msg = (char *)"invalid window size"; state->mode = BAD; break; } state->dmax = 1U << len; state->flags = 0; /* indicate zlib header */ Tracev((stderr, "inflate: zlib header ok\n")); strm->adler = state->check = adler32(0L, Z_NULL, 0); state->mode = hold & 0x200 ? DICTID : TYPE; INITBITS(); break; #ifdef GUNZIP case FLAGS: NEEDBITS(16); state->flags = (int)(hold); if ((state->flags & 0xff) != Z_DEFLATED) { strm->msg = (char *)"unknown compression method"; state->mode = BAD; break; } if (state->flags & 0xe000) { strm->msg = (char *)"unknown header flags set"; state->mode = BAD; break; } if (state->head != Z_NULL) state->head->text = (int)((hold >> 8) & 1); if ((state->flags & 0x0200) && (state->wrap & 4)) CRC2(state->check, hold); INITBITS(); state->mode = TIME; /* fallthrough */ case TIME: NEEDBITS(32); if (state->head != Z_NULL) state->head->time = hold; if ((state->flags & 0x0200) && (state->wrap & 4)) CRC4(state->check, hold); INITBITS(); state->mode = OS; /* fallthrough */ case OS: NEEDBITS(16); if (state->head != Z_NULL) { state->head->xflags = (int)(hold & 0xff); state->head->os = (int)(hold >> 8); } if ((state->flags & 0x0200) && (state->wrap & 4)) CRC2(state->check, hold); INITBITS(); state->mode = EXLEN; /* fallthrough */ case EXLEN: if (state->flags & 0x0400) { NEEDBITS(16); state->length = (unsigned)(hold); if (state->head != Z_NULL) state->head->extra_len = (unsigned)hold; if ((state->flags & 0x0200) && (state->wrap & 4)) CRC2(state->check, hold); INITBITS(); } else if (state->head != Z_NULL) state->head->extra = Z_NULL; state->mode = EXTRA; /* fallthrough */ case EXTRA: if (state->flags & 0x0400) { copy = state->length; if (copy > have) copy = have; if (copy) { if (state->head != Z_NULL && state->head->extra != Z_NULL) { len = state->head->extra_len - state->length; zmemcpy(state->head->extra + len, next, len + copy > state->head->extra_max ? state->head->extra_max - len : copy); } if ((state->flags & 0x0200) && (state->wrap & 4)) state->check = crc32(state->check, next, copy); have -= copy; next += copy; state->length -= copy; } if (state->length) goto inf_leave; } state->length = 0; state->mode = NAME; /* fallthrough */ case NAME: if (state->flags & 0x0800) { if (have == 0) goto inf_leave; copy = 0; do { len = (unsigned)(next[copy++]); if (state->head != Z_NULL && state->head->name != Z_NULL && state->length < state->head->name_max) state->head->name[state->length++] = (Bytef)len; } while (len && copy < have); if ((state->flags & 0x0200) && (state->wrap & 4)) state->check = crc32(state->check, next, copy); have -= copy; next += copy; if (len) goto inf_leave; } else if (state->head != Z_NULL) state->head->name = Z_NULL; state->length = 0; state->mode = COMMENT; /* fallthrough */ case COMMENT: if (state->flags & 0x1000) { if (have == 0) goto inf_leave; copy = 0; do { len = (unsigned)(next[copy++]); if (state->head != Z_NULL && state->head->comment != Z_NULL && state->length < state->head->comm_max) state->head->comment[state->length++] = (Bytef)len; } while (len && copy < have); if ((state->flags & 0x0200) && (state->wrap & 4)) state->check = crc32(state->check, next, copy); have -= copy; next += copy; if (len) goto inf_leave; } else if (state->head != Z_NULL) state->head->comment = Z_NULL; state->mode = HCRC; /* fallthrough */ case HCRC: if (state->flags & 0x0200) { NEEDBITS(16); if ((state->wrap & 4) && hold != (state->check & 0xffff)) { strm->msg = (char *)"header crc mismatch"; state->mode = BAD; break; } INITBITS(); } if (state->head != Z_NULL) { state->head->hcrc = (int)((state->flags >> 9) & 1); state->head->done = 1; } strm->adler = state->check = crc32(0L, Z_NULL, 0); state->mode = TYPE; break; #endif case DICTID: NEEDBITS(32); strm->adler = state->check = ZSWAP32(hold); INITBITS(); state->mode = DICT; /* fallthrough */ case DICT: if (state->havedict == 0) { RESTORE(); return Z_NEED_DICT; } strm->adler = state->check = adler32(0L, Z_NULL, 0); state->mode = TYPE; /* fallthrough */ case TYPE: if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave; /* fallthrough */ case TYPEDO: if (state->last) { BYTEBITS(); state->mode = CHECK; break; } NEEDBITS(3); state->last = BITS(1); DROPBITS(1); switch (BITS(2)) { case 0: /* stored block */ Tracev((stderr, "inflate: stored block%s\n", state->last ? " (last)" : "")); state->mode = STORED; break; case 1: /* fixed block */ fixedtables(state); Tracev((stderr, "inflate: fixed codes block%s\n", state->last ? " (last)" : "")); state->mode = LEN_; /* decode codes */ if (flush == Z_TREES) { DROPBITS(2); goto inf_leave; } break; case 2: /* dynamic block */ Tracev((stderr, "inflate: dynamic codes block%s\n", state->last ? " (last)" : "")); state->mode = TABLE; break; case 3: strm->msg = (char *)"invalid block type"; state->mode = BAD; } DROPBITS(2); break; case STORED: BYTEBITS(); /* go to byte boundary */ NEEDBITS(32); if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { strm->msg = (char *)"invalid stored block lengths"; state->mode = BAD; break; } state->length = (unsigned)hold & 0xffff; Tracev((stderr, "inflate: stored length %u\n", state->length)); INITBITS(); state->mode = COPY_; if (flush == Z_TREES) goto inf_leave; /* fallthrough */ case COPY_: state->mode = COPY; /* fallthrough */ case COPY: copy = state->length; if (copy) { if (copy > have) copy = have; if (copy > left) copy = left; if (copy == 0) goto inf_leave; zmemcpy(put, next, copy); have -= copy; next += copy; left -= copy; put += copy; state->length -= copy; break; } Tracev((stderr, "inflate: stored end\n")); state->mode = TYPE; break; case TABLE: NEEDBITS(14); state->nlen = BITS(5) + 257; DROPBITS(5); state->ndist = BITS(5) + 1; DROPBITS(5); state->ncode = BITS(4) + 4; DROPBITS(4); #ifndef PKZIP_BUG_WORKAROUND if (state->nlen > 286 || state->ndist > 30) { strm->msg = (char *)"too many length or distance symbols"; state->mode = BAD; break; } #endif Tracev((stderr, "inflate: table sizes ok\n")); state->have = 0; state->mode = LENLENS; /* fallthrough */ case LENLENS: while (state->have < state->ncode) { NEEDBITS(3); state->lens[order[state->have++]] = (unsigned short)BITS(3); DROPBITS(3); } while (state->have < 19) state->lens[order[state->have++]] = 0; state->next = state->codes; state->lencode = (const code FAR *)(state->next); state->lenbits = 7; ret = inflate_table(CODES, state->lens, 19, &(state->next), &(state->lenbits), state->work); if (ret) { strm->msg = (char *)"invalid code lengths set"; state->mode = BAD; break; } Tracev((stderr, "inflate: code lengths ok\n")); state->have = 0; state->mode = CODELENS; /* fallthrough */ case CODELENS: while (state->have < state->nlen + state->ndist) { for (;;) { here = state->lencode[BITS(state->lenbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if (here.val < 16) { DROPBITS(here.bits); state->lens[state->have++] = here.val; } else { if (here.val == 16) { NEEDBITS(here.bits + 2); DROPBITS(here.bits); if (state->have == 0) { strm->msg = (char *)"invalid bit length repeat"; state->mode = BAD; break; } len = state->lens[state->have - 1]; copy = 3 + BITS(2); DROPBITS(2); } else if (here.val == 17) { NEEDBITS(here.bits + 3); DROPBITS(here.bits); len = 0; copy = 3 + BITS(3); DROPBITS(3); } else { NEEDBITS(here.bits + 7); DROPBITS(here.bits); len = 0; copy = 11 + BITS(7); DROPBITS(7); } if (state->have + copy > state->nlen + state->ndist) { strm->msg = (char *)"invalid bit length repeat"; state->mode = BAD; break; } while (copy--) state->lens[state->have++] = (unsigned short)len; } } /* handle error breaks in while */ if (state->mode == BAD) break; /* check for end-of-block code (better have one) */ if (state->lens[256] == 0) { strm->msg = (char *)"invalid code -- missing end-of-block"; state->mode = BAD; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state->next = state->codes; state->lencode = (const code FAR *)(state->next); state->lenbits = 9; ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), &(state->lenbits), state->work); if (ret) { strm->msg = (char *)"invalid literal/lengths set"; state->mode = BAD; break; } state->distcode = (const code FAR *)(state->next); state->distbits = 6; ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, &(state->next), &(state->distbits), state->work); if (ret) { strm->msg = (char *)"invalid distances set"; state->mode = BAD; break; } Tracev((stderr, "inflate: codes ok\n")); state->mode = LEN_; if (flush == Z_TREES) goto inf_leave; /* fallthrough */ case LEN_: state->mode = LEN; /* fallthrough */ case LEN: if (have >= 6 && left >= 258) { RESTORE(); inflate_fast(strm, out); LOAD(); if (state->mode == TYPE) state->back = -1; break; } state->back = 0; for (;;) { here = state->lencode[BITS(state->lenbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if (here.op && (here.op & 0xf0) == 0) { last = here; for (;;) { here = state->lencode[last.val + (BITS(last.bits + last.op) >> last.bits)]; if ((unsigned)(last.bits + here.bits) <= bits) break; PULLBYTE(); } DROPBITS(last.bits); state->back += last.bits; } DROPBITS(here.bits); state->back += here.bits; state->length = (unsigned)here.val; if ((int)(here.op) == 0) { Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? "inflate: literal '%c'\n" : "inflate: literal 0x%02x\n", here.val)); state->mode = LIT; break; } if (here.op & 32) { Tracevv((stderr, "inflate: end of block\n")); state->back = -1; state->mode = TYPE; break; } if (here.op & 64) { strm->msg = (char *)"invalid literal/length code"; state->mode = BAD; break; } state->extra = (unsigned)(here.op) & 15; state->mode = LENEXT; /* fallthrough */ case LENEXT: if (state->extra) { NEEDBITS(state->extra); state->length += BITS(state->extra); DROPBITS(state->extra); state->back += state->extra; } Tracevv((stderr, "inflate: length %u\n", state->length)); state->was = state->length; state->mode = DIST; /* fallthrough */ case DIST: for (;;) { here = state->distcode[BITS(state->distbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if ((here.op & 0xf0) == 0) { last = here; for (;;) { here = state->distcode[last.val + (BITS(last.bits + last.op) >> last.bits)]; if ((unsigned)(last.bits + here.bits) <= bits) break; PULLBYTE(); } DROPBITS(last.bits); state->back += last.bits; } DROPBITS(here.bits); state->back += here.bits; if (here.op & 64) { strm->msg = (char *)"invalid distance code"; state->mode = BAD; break; } state->offset = (unsigned)here.val; state->extra = (unsigned)(here.op) & 15; state->mode = DISTEXT; /* fallthrough */ case DISTEXT: if (state->extra) { NEEDBITS(state->extra); state->offset += BITS(state->extra); DROPBITS(state->extra); state->back += state->extra; } #ifdef INFLATE_STRICT if (state->offset > state->dmax) { strm->msg = (char *)"invalid distance too far back"; state->mode = BAD; break; } #endif Tracevv((stderr, "inflate: distance %u\n", state->offset)); state->mode = MATCH; /* fallthrough */ case MATCH: if (left == 0) goto inf_leave; copy = out - left; if (state->offset > copy) { /* copy from window */ copy = state->offset - copy; if (copy > state->whave) { if (state->sane) { strm->msg = (char *)"invalid distance too far back"; state->mode = BAD; break; } #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR Trace((stderr, "inflate.c too far\n")); copy -= state->whave; if (copy > state->length) copy = state->length; if (copy > left) copy = left; left -= copy; state->length -= copy; do { *put++ = 0; } while (--copy); if (state->length == 0) state->mode = LEN; break; #endif } if (copy > state->wnext) { copy -= state->wnext; from = state->window + (state->wsize - copy); } else from = state->window + (state->wnext - copy); if (copy > state->length) copy = state->length; } else { /* copy from output */ from = put - state->offset; copy = state->length; } if (copy > left) copy = left; left -= copy; state->length -= copy; do { *put++ = *from++; } while (--copy); if (state->length == 0) state->mode = LEN; break; case LIT: if (left == 0) goto inf_leave; *put++ = (unsigned char)(state->length); left--; state->mode = LEN; break; case CHECK: if (state->wrap) { NEEDBITS(32); out -= left; strm->total_out += out; state->total += out; if ((state->wrap & 4) && out) strm->adler = state->check = UPDATE_CHECK(state->check, put - out, out); out = left; if ((state->wrap & 4) && ( #ifdef GUNZIP state->flags ? hold : #endif ZSWAP32(hold)) != state->check) { strm->msg = (char *)"incorrect data check"; state->mode = BAD; break; } INITBITS(); Tracev((stderr, "inflate: check matches trailer\n")); } #ifdef GUNZIP state->mode = LENGTH; /* fallthrough */ case LENGTH: if (state->wrap && state->flags) { NEEDBITS(32); if ((state->wrap & 4) && hold != (state->total & 0xffffffff)) { strm->msg = (char *)"incorrect length check"; state->mode = BAD; break; } INITBITS(); Tracev((stderr, "inflate: length matches trailer\n")); } #endif state->mode = DONE; /* fallthrough */ case DONE: ret = Z_STREAM_END; goto inf_leave; case BAD: ret = Z_DATA_ERROR; goto inf_leave; case MEM: return Z_MEM_ERROR; case SYNC: /* fallthrough */ default: return Z_STREAM_ERROR; } /* Return from inflate(), updating the total counts and the check value. If there was no progress during the inflate() call, return a buffer error. Call updatewindow() to create and/or update the window state. Note: a memory error from inflate() is non-recoverable. */ inf_leave: RESTORE(); if (state->wsize || (out != strm->avail_out && state->mode < BAD && (state->mode < CHECK || flush != Z_FINISH))) if (updatewindow(strm, strm->next_out, out - strm->avail_out)) { state->mode = MEM; return Z_MEM_ERROR; } in -= strm->avail_in; out -= strm->avail_out; strm->total_in += in; strm->total_out += out; state->total += out; if ((state->wrap & 4) && out) strm->adler = state->check = UPDATE_CHECK(state->check, strm->next_out - out, out); strm->data_type = (int)state->bits + (state->last ? 64 : 0) + (state->mode == TYPE ? 128 : 0) + (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0); if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) ret = Z_BUF_ERROR; return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix a bug when getting a gzip header extra field with inflate(). If the extra field was larger than the space the user provided with inflateGetHeader(), and if multiple calls of inflate() delivered the extra header data, then there could be a buffer overflow of the provided space. This commit assures that provided space is not exceeded.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: dns64_inform_super(struct module_qstate* qstate, int id, struct module_qstate* super) { struct dns64_qstate* super_dq = (struct dns64_qstate*)super->minfo[id]; log_query_info(VERB_ALGO, "dns64: inform_super, sub is", &qstate->qinfo); log_query_info(VERB_ALGO, "super is", &super->qinfo); /* * Signal that the sub-query is finished, no matter whether we are * successful or not. This lets the state machine terminate. */ if(!super_dq) { super_dq = (struct dns64_qstate*)regional_alloc(super->region, sizeof(*super_dq)); if(!super_dq) { log_err("out of memory"); super->return_rcode = LDNS_RCODE_SERVFAIL; super->return_msg = NULL; return; } super->minfo[id] = super_dq; memset(super_dq, 0, sizeof(*super_dq)); super_dq->started_no_cache_store = super->no_cache_store; } super_dq->state = DNS64_SUBQUERY_FINISHED; /* If there is no successful answer, we're done. */ if (qstate->return_rcode != LDNS_RCODE_NOERROR || !qstate->return_msg || !qstate->return_msg->rep) { return; } /* Use return code from A query in response to client. */ if (super->return_rcode != LDNS_RCODE_NOERROR) super->return_rcode = qstate->return_rcode; /* Generate a response suitable for the original query. */ if (qstate->qinfo.qtype == LDNS_RR_TYPE_A) { dns64_adjust_a(id, super, qstate); } else { log_assert(qstate->qinfo.qtype == LDNS_RR_TYPE_PTR); dns64_adjust_ptr(qstate, super); } /* Store the generated response in cache. */ if ( (!super_dq || !super_dq->started_no_cache_store) && !dns_cache_store(super->env, &super->qinfo, super->return_msg->rep, 0, 0, 0, NULL, super->query_flags)) log_err("out of memory"); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-613', 'CWE-703'], 'message': '- Fix the novel ghost domain issues CVE-2022-30698 and CVE-2022-30699.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: dns_cache_find_delegation(struct module_env* env, uint8_t* qname, size_t qnamelen, uint16_t qtype, uint16_t qclass, struct regional* region, struct dns_msg** msg, time_t now) { /* try to find closest NS rrset */ struct ub_packed_rrset_key* nskey; struct packed_rrset_data* nsdata; struct delegpt* dp; nskey = find_closest_of_type(env, qname, qnamelen, qclass, now, LDNS_RR_TYPE_NS, 0); if(!nskey) /* hope the caller has hints to prime or something */ return NULL; nsdata = (struct packed_rrset_data*)nskey->entry.data; /* got the NS key, create delegation point */ dp = delegpt_create(region); if(!dp || !delegpt_set_name(dp, region, nskey->rk.dname)) { lock_rw_unlock(&nskey->entry.lock); log_err("find_delegation: out of memory"); return NULL; } /* create referral message */ if(msg) { /* allocate the array to as much as we could need: * NS rrset + DS/NSEC rrset + * A rrset for every NS RR * AAAA rrset for every NS RR */ *msg = dns_msg_create(qname, qnamelen, qtype, qclass, region, 2 + nsdata->count*2); if(!*msg || !dns_msg_authadd(*msg, region, nskey, now)) { lock_rw_unlock(&nskey->entry.lock); log_err("find_delegation: out of memory"); return NULL; } } if(!delegpt_rrset_add_ns(dp, region, nskey, 0)) log_err("find_delegation: addns out of memory"); lock_rw_unlock(&nskey->entry.lock); /* first unlock before next lookup*/ /* find and add DS/NSEC (if any) */ if(msg) find_add_ds(env, region, *msg, dp, now); /* find and add A entries */ if(!find_add_addrs(env, qclass, region, dp, now, msg)) log_err("find_delegation: addrs out of memory"); return dp; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-613', 'CWE-703'], 'message': '- Fix the novel ghost domain issues CVE-2022-30698 and CVE-2022-30699.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: cmdopts_t *cmdopts_parse(int argc, char **argv) { enum { CMDOPT_HELP = 0, CMDOPT_VERBOSE, CMDOPT_QUIET, CMDOPT_INFILE, CMDOPT_INFMT, CMDOPT_INOPT, CMDOPT_OUTFILE, CMDOPT_OUTFMT, CMDOPT_OUTOPT, CMDOPT_VERSION, CMDOPT_DEBUG, CMDOPT_CMPTNO, CMDOPT_SRGB, CMDOPT_MAXMEM, CMDOPT_LIST_ENABLED_CODECS, CMDOPT_LIST_ALL_CODECS, CMDOPT_ENABLE_FORMAT, CMDOPT_ENABLE_ALL_FORMATS, }; static const jas_opt_t cmdoptions[] = { {CMDOPT_HELP, "help", 0}, {CMDOPT_VERBOSE, "verbose", 0}, {CMDOPT_QUIET, "quiet", 0}, {CMDOPT_QUIET, "q", 0}, {CMDOPT_INFILE, "input", JAS_OPT_HASARG}, {CMDOPT_INFILE, "f", JAS_OPT_HASARG}, {CMDOPT_INFMT, "input-format", JAS_OPT_HASARG}, {CMDOPT_INFMT, "t", JAS_OPT_HASARG}, {CMDOPT_INOPT, "input-option", JAS_OPT_HASARG}, {CMDOPT_INOPT, "o", JAS_OPT_HASARG}, {CMDOPT_OUTFILE, "output", JAS_OPT_HASARG}, {CMDOPT_OUTFILE, "F", JAS_OPT_HASARG}, {CMDOPT_OUTFMT, "output-format", JAS_OPT_HASARG}, {CMDOPT_OUTFMT, "T", JAS_OPT_HASARG}, {CMDOPT_OUTOPT, "output-option", JAS_OPT_HASARG}, {CMDOPT_OUTOPT, "O", JAS_OPT_HASARG}, {CMDOPT_VERSION, "version", 0}, {CMDOPT_DEBUG, "debug-level", JAS_OPT_HASARG}, {CMDOPT_CMPTNO, "cmptno", JAS_OPT_HASARG}, {CMDOPT_SRGB, "force-srgb", 0}, {CMDOPT_SRGB, "S", 0}, {CMDOPT_MAXMEM, "memory-limit", JAS_OPT_HASARG}, {CMDOPT_LIST_ENABLED_CODECS, "list-enabled-formats", 0}, {CMDOPT_LIST_ALL_CODECS, "list-all-formats", 0}, {CMDOPT_ENABLE_FORMAT, "enable-format", JAS_OPT_HASARG}, {CMDOPT_ENABLE_ALL_FORMATS, "enable-all-formats", 0}, {-1, 0, 0} }; cmdopts_t *cmdopts; int c; if (!(cmdopts = malloc(sizeof(cmdopts_t)))) { fprintf(stderr, "error: insufficient memory\n"); exit(EXIT_FAILURE); } cmdopts->infile = 0; cmdopts->infmt = -1; cmdopts->infmt_str = 0; cmdopts->inopts = 0; cmdopts->inoptsbuf[0] = '\0'; cmdopts->outfile = 0; cmdopts->outfmt = -1; cmdopts->outfmt_str = 0; cmdopts->outopts = 0; cmdopts->outoptsbuf[0] = '\0'; cmdopts->verbose = 0; cmdopts->version = 0; cmdopts->cmptno = -1; cmdopts->debug = 0; cmdopts->srgb = 0; cmdopts->list_codecs = 0; cmdopts->list_codecs_all = 0; cmdopts->help = 0; cmdopts->max_mem = get_default_max_mem_usage(); cmdopts->enable_format = 0; cmdopts->enable_all_formats = 0; while ((c = jas_getopt(argc, argv, cmdoptions)) != EOF) { switch (c) { case CMDOPT_HELP: cmdopts->help = 1; break; case CMDOPT_VERBOSE: cmdopts->verbose = 1; break; case CMDOPT_QUIET: cmdopts->verbose = -1; break; case CMDOPT_VERSION: cmdopts->version = 1; break; case CMDOPT_LIST_ENABLED_CODECS: cmdopts->list_codecs = 1; cmdopts->list_codecs_all = 0; break; case CMDOPT_LIST_ALL_CODECS: cmdopts->list_codecs = 1; cmdopts->list_codecs_all = 1; break; case CMDOPT_DEBUG: cmdopts->debug = atoi(jas_optarg); break; case CMDOPT_INFILE: cmdopts->infile = jas_optarg; break; case CMDOPT_INFMT: cmdopts->infmt_str= jas_optarg; break; case CMDOPT_INOPT: addopt(cmdopts->inoptsbuf, OPTSMAX, jas_optarg); cmdopts->inopts = cmdopts->inoptsbuf; break; case CMDOPT_OUTFILE: cmdopts->outfile = jas_optarg; break; case CMDOPT_OUTFMT: cmdopts->outfmt_str = jas_optarg; break; case CMDOPT_OUTOPT: addopt(cmdopts->outoptsbuf, OPTSMAX, jas_optarg); cmdopts->outopts = cmdopts->outoptsbuf; break; case CMDOPT_CMPTNO: cmdopts->cmptno = atoi(jas_optarg); break; case CMDOPT_SRGB: cmdopts->srgb = 1; break; case CMDOPT_MAXMEM: cmdopts->max_mem = strtoull(jas_optarg, 0, 10); break; case CMDOPT_ENABLE_FORMAT: cmdopts->enable_format = jas_optarg; break; case CMDOPT_ENABLE_ALL_FORMATS: cmdopts->enable_all_formats = 1; break; default: badusage(); break; } } while (jas_optind < argc) { fprintf(stderr, "warning: ignoring bogus command line argument %s\n", argv[jas_optind]); ++jas_optind; } if (cmdopts->version || cmdopts->list_codecs || cmdopts->help) { goto done; } if (!cmdopts->outfmt_str && !cmdopts->outfile) { fprintf(stderr, "error: cannot determine output format\n"); badusage(); } done: return cmdopts; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-401'], 'message': 'fix memory leaks in function cmdopts_parse'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: eval_next_line(char_u *arg, evalarg_T *evalarg) { garray_T *gap = &evalarg->eval_ga; char_u *line; if (arg != NULL) { if (*arg == NL) return newline_skip_comments(arg); // Truncate before a trailing comment, so that concatenating the lines // won't turn the rest into a comment. if (*skipwhite(arg) == '#') *arg = NUL; } if (evalarg->eval_cookie != NULL) line = evalarg->eval_getline(0, evalarg->eval_cookie, 0, GETLINE_CONCAT_ALL); else line = next_line_from_context(evalarg->eval_cctx, TRUE); if (line == NULL) return NULL; ++evalarg->eval_break_count; if (gap->ga_itemsize > 0 && ga_grow(gap, 1) == OK) { char_u *p = skipwhite(line); // Going to concatenate the lines after parsing. For an empty or // comment line use an empty string. if (*p == NUL || vim9_comment_start(p)) { vim_free(line); line = vim_strsave((char_u *)""); } ((char_u **)gap->ga_data)[gap->ga_len] = line; ++gap->ga_len; } else if (evalarg->eval_cookie != NULL) { vim_free(evalarg->eval_tofree); evalarg->eval_tofree = line; } // Advanced to the next line, "arg" no longer points into the previous // line. evalarg->eval_using_cmdline = FALSE; return skipwhite(line); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'patch 9.0.0225: using freed memory with multiple line breaks in expression Problem: Using freed memory with multiple line breaks in expression. Solution: Free eval_tofree later.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: __poll_t psi_trigger_poll(void **trigger_ptr, struct file *file, poll_table *wait) { __poll_t ret = DEFAULT_POLLMASK; struct psi_trigger *t; if (static_branch_likely(&psi_disabled)) return DEFAULT_POLLMASK | EPOLLERR | EPOLLPRI; rcu_read_lock(); t = rcu_dereference(*(void __rcu __force **)trigger_ptr); if (!t) { rcu_read_unlock(); return DEFAULT_POLLMASK | EPOLLERR | EPOLLPRI; } kref_get(&t->refcount); rcu_read_unlock(); poll_wait(file, &t->event_wait, wait); if (cmpxchg(&t->event, 1, 0) == 1) ret |= EPOLLPRI; kref_put(&t->refcount, psi_trigger_destroy); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'psi: Fix uaf issue when psi trigger is destroyed while being polled With write operation on psi files replacing old trigger with a new one, the lifetime of its waitqueue is totally arbitrary. Overwriting an existing trigger causes its waitqueue to be freed and pending poll() will stumble on trigger->event_wait which was destroyed. Fix this by disallowing to redefine an existing psi trigger. If a write operation is used on a file descriptor with an already existing psi trigger, the operation will fail with EBUSY error. Also bypass a check for psi_disabled in the psi_trigger_destroy as the flag can be flipped after the trigger is created, leading to a memory leak. Fixes: 0e94682b73bf ("psi: introduce psi monitor") Reported-by: syzbot+cdb5dd11c97cc532efad@syzkaller.appspotmail.com Suggested-by: Linus Torvalds <torvalds@linux-foundation.org> Analyzed-by: Eric Biggers <ebiggers@kernel.org> Signed-off-by: Suren Baghdasaryan <surenb@google.com> Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org> Reviewed-by: Eric Biggers <ebiggers@google.com> Acked-by: Johannes Weiner <hannes@cmpxchg.org> Cc: stable@vger.kernel.org Link: https://lore.kernel.org/r/20220111232309.1786347-1-surenb@google.com'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static ssize_t waiting_for_supplier_show(struct device *dev, struct device_attribute *attr, char *buf) { bool val; device_lock(dev); mutex_lock(&wfs_lock); val = !list_empty(&dev->links.needs_suppliers) && dev->links.need_for_probe; mutex_unlock(&wfs_lock); device_unlock(dev); return sprintf(buf, "%u\n", val); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'drivers core: Use sysfs_emit and sysfs_emit_at for show(device *...) functions Convert the various sprintf fmaily calls in sysfs device show functions to sysfs_emit and sysfs_emit_at for PAGE_SIZE buffer safety. Done with: $ spatch -sp-file sysfs_emit_dev.cocci --in-place --max-width=80 . And cocci script: $ cat sysfs_emit_dev.cocci @@ identifier d_show; identifier dev, attr, buf; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... return - sprintf(buf, + sysfs_emit(buf, ...); ...> } @@ identifier d_show; identifier dev, attr, buf; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... return - snprintf(buf, PAGE_SIZE, + sysfs_emit(buf, ...); ...> } @@ identifier d_show; identifier dev, attr, buf; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... return - scnprintf(buf, PAGE_SIZE, + sysfs_emit(buf, ...); ...> } @@ identifier d_show; identifier dev, attr, buf; expression chr; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... return - strcpy(buf, chr); + sysfs_emit(buf, chr); ...> } @@ identifier d_show; identifier dev, attr, buf; identifier len; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... len = - sprintf(buf, + sysfs_emit(buf, ...); ...> return len; } @@ identifier d_show; identifier dev, attr, buf; identifier len; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... len = - snprintf(buf, PAGE_SIZE, + sysfs_emit(buf, ...); ...> return len; } @@ identifier d_show; identifier dev, attr, buf; identifier len; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... len = - scnprintf(buf, PAGE_SIZE, + sysfs_emit(buf, ...); ...> return len; } @@ identifier d_show; identifier dev, attr, buf; identifier len; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... - len += scnprintf(buf + len, PAGE_SIZE - len, + len += sysfs_emit_at(buf, len, ...); ...> return len; } @@ identifier d_show; identifier dev, attr, buf; expression chr; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { ... - strcpy(buf, chr); - return strlen(buf); + return sysfs_emit(buf, chr); } Signed-off-by: Joe Perches <joe@perches.com> Link: https://lore.kernel.org/r/3d033c33056d88bbe34d4ddb62afd05ee166ab9a.1600285923.git.joe@perches.com Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static ssize_t pm_qos_no_power_off_show(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "%d\n", !!(dev_pm_qos_requested_flags(dev) & PM_QOS_FLAG_NO_POWER_OFF)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'drivers core: Use sysfs_emit and sysfs_emit_at for show(device *...) functions Convert the various sprintf fmaily calls in sysfs device show functions to sysfs_emit and sysfs_emit_at for PAGE_SIZE buffer safety. Done with: $ spatch -sp-file sysfs_emit_dev.cocci --in-place --max-width=80 . And cocci script: $ cat sysfs_emit_dev.cocci @@ identifier d_show; identifier dev, attr, buf; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... return - sprintf(buf, + sysfs_emit(buf, ...); ...> } @@ identifier d_show; identifier dev, attr, buf; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... return - snprintf(buf, PAGE_SIZE, + sysfs_emit(buf, ...); ...> } @@ identifier d_show; identifier dev, attr, buf; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... return - scnprintf(buf, PAGE_SIZE, + sysfs_emit(buf, ...); ...> } @@ identifier d_show; identifier dev, attr, buf; expression chr; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... return - strcpy(buf, chr); + sysfs_emit(buf, chr); ...> } @@ identifier d_show; identifier dev, attr, buf; identifier len; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... len = - sprintf(buf, + sysfs_emit(buf, ...); ...> return len; } @@ identifier d_show; identifier dev, attr, buf; identifier len; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... len = - snprintf(buf, PAGE_SIZE, + sysfs_emit(buf, ...); ...> return len; } @@ identifier d_show; identifier dev, attr, buf; identifier len; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... len = - scnprintf(buf, PAGE_SIZE, + sysfs_emit(buf, ...); ...> return len; } @@ identifier d_show; identifier dev, attr, buf; identifier len; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... - len += scnprintf(buf + len, PAGE_SIZE - len, + len += sysfs_emit_at(buf, len, ...); ...> return len; } @@ identifier d_show; identifier dev, attr, buf; expression chr; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { ... - strcpy(buf, chr); - return strlen(buf); + return sysfs_emit(buf, chr); } Signed-off-by: Joe Perches <joe@perches.com> Link: https://lore.kernel.org/r/3d033c33056d88bbe34d4ddb62afd05ee166ab9a.1600285923.git.joe@perches.com Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static ssize_t print_cpus_nohz_full(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "%*pbl\n", cpumask_pr_args(tick_nohz_full_mask)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'drivers core: Use sysfs_emit and sysfs_emit_at for show(device *...) functions Convert the various sprintf fmaily calls in sysfs device show functions to sysfs_emit and sysfs_emit_at for PAGE_SIZE buffer safety. Done with: $ spatch -sp-file sysfs_emit_dev.cocci --in-place --max-width=80 . And cocci script: $ cat sysfs_emit_dev.cocci @@ identifier d_show; identifier dev, attr, buf; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... return - sprintf(buf, + sysfs_emit(buf, ...); ...> } @@ identifier d_show; identifier dev, attr, buf; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... return - snprintf(buf, PAGE_SIZE, + sysfs_emit(buf, ...); ...> } @@ identifier d_show; identifier dev, attr, buf; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... return - scnprintf(buf, PAGE_SIZE, + sysfs_emit(buf, ...); ...> } @@ identifier d_show; identifier dev, attr, buf; expression chr; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... return - strcpy(buf, chr); + sysfs_emit(buf, chr); ...> } @@ identifier d_show; identifier dev, attr, buf; identifier len; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... len = - sprintf(buf, + sysfs_emit(buf, ...); ...> return len; } @@ identifier d_show; identifier dev, attr, buf; identifier len; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... len = - snprintf(buf, PAGE_SIZE, + sysfs_emit(buf, ...); ...> return len; } @@ identifier d_show; identifier dev, attr, buf; identifier len; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... len = - scnprintf(buf, PAGE_SIZE, + sysfs_emit(buf, ...); ...> return len; } @@ identifier d_show; identifier dev, attr, buf; identifier len; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... - len += scnprintf(buf + len, PAGE_SIZE - len, + len += sysfs_emit_at(buf, len, ...); ...> return len; } @@ identifier d_show; identifier dev, attr, buf; expression chr; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { ... - strcpy(buf, chr); - return strlen(buf); + return sysfs_emit(buf, chr); } Signed-off-by: Joe Perches <joe@perches.com> Link: https://lore.kernel.org/r/3d033c33056d88bbe34d4ddb62afd05ee166ab9a.1600285923.git.joe@perches.com Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static ssize_t cpu_capacity_show(struct device *dev, struct device_attribute *attr, char *buf) { struct cpu *cpu = container_of(dev, struct cpu, dev); return sprintf(buf, "%lu\n", topology_get_cpu_scale(cpu->dev.id)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'drivers core: Use sysfs_emit and sysfs_emit_at for show(device *...) functions Convert the various sprintf fmaily calls in sysfs device show functions to sysfs_emit and sysfs_emit_at for PAGE_SIZE buffer safety. Done with: $ spatch -sp-file sysfs_emit_dev.cocci --in-place --max-width=80 . And cocci script: $ cat sysfs_emit_dev.cocci @@ identifier d_show; identifier dev, attr, buf; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... return - sprintf(buf, + sysfs_emit(buf, ...); ...> } @@ identifier d_show; identifier dev, attr, buf; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... return - snprintf(buf, PAGE_SIZE, + sysfs_emit(buf, ...); ...> } @@ identifier d_show; identifier dev, attr, buf; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... return - scnprintf(buf, PAGE_SIZE, + sysfs_emit(buf, ...); ...> } @@ identifier d_show; identifier dev, attr, buf; expression chr; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... return - strcpy(buf, chr); + sysfs_emit(buf, chr); ...> } @@ identifier d_show; identifier dev, attr, buf; identifier len; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... len = - sprintf(buf, + sysfs_emit(buf, ...); ...> return len; } @@ identifier d_show; identifier dev, attr, buf; identifier len; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... len = - snprintf(buf, PAGE_SIZE, + sysfs_emit(buf, ...); ...> return len; } @@ identifier d_show; identifier dev, attr, buf; identifier len; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... len = - scnprintf(buf, PAGE_SIZE, + sysfs_emit(buf, ...); ...> return len; } @@ identifier d_show; identifier dev, attr, buf; identifier len; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... - len += scnprintf(buf + len, PAGE_SIZE - len, + len += sysfs_emit_at(buf, len, ...); ...> return len; } @@ identifier d_show; identifier dev, attr, buf; expression chr; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { ... - strcpy(buf, chr); - return strlen(buf); + return sysfs_emit(buf, chr); } Signed-off-by: Joe Perches <joe@perches.com> Link: https://lore.kernel.org/r/3d033c33056d88bbe34d4ddb62afd05ee166ab9a.1600285923.git.joe@perches.com Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ssize_t __weak cpu_show_meltdown(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "Not affected\n"); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'drivers core: Use sysfs_emit and sysfs_emit_at for show(device *...) functions Convert the various sprintf fmaily calls in sysfs device show functions to sysfs_emit and sysfs_emit_at for PAGE_SIZE buffer safety. Done with: $ spatch -sp-file sysfs_emit_dev.cocci --in-place --max-width=80 . And cocci script: $ cat sysfs_emit_dev.cocci @@ identifier d_show; identifier dev, attr, buf; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... return - sprintf(buf, + sysfs_emit(buf, ...); ...> } @@ identifier d_show; identifier dev, attr, buf; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... return - snprintf(buf, PAGE_SIZE, + sysfs_emit(buf, ...); ...> } @@ identifier d_show; identifier dev, attr, buf; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... return - scnprintf(buf, PAGE_SIZE, + sysfs_emit(buf, ...); ...> } @@ identifier d_show; identifier dev, attr, buf; expression chr; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... return - strcpy(buf, chr); + sysfs_emit(buf, chr); ...> } @@ identifier d_show; identifier dev, attr, buf; identifier len; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... len = - sprintf(buf, + sysfs_emit(buf, ...); ...> return len; } @@ identifier d_show; identifier dev, attr, buf; identifier len; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... len = - snprintf(buf, PAGE_SIZE, + sysfs_emit(buf, ...); ...> return len; } @@ identifier d_show; identifier dev, attr, buf; identifier len; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... len = - scnprintf(buf, PAGE_SIZE, + sysfs_emit(buf, ...); ...> return len; } @@ identifier d_show; identifier dev, attr, buf; identifier len; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... - len += scnprintf(buf + len, PAGE_SIZE - len, + len += sysfs_emit_at(buf, len, ...); ...> return len; } @@ identifier d_show; identifier dev, attr, buf; expression chr; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { ... - strcpy(buf, chr); - return strlen(buf); + return sysfs_emit(buf, chr); } Signed-off-by: Joe Perches <joe@perches.com> Link: https://lore.kernel.org/r/3d033c33056d88bbe34d4ddb62afd05ee166ab9a.1600285923.git.joe@perches.com Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static ssize_t runtime_active_time_show(struct device *dev, struct device_attribute *attr, char *buf) { int ret; u64 tmp = pm_runtime_active_time(dev); do_div(tmp, NSEC_PER_MSEC); ret = sprintf(buf, "%llu\n", tmp); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'drivers core: Use sysfs_emit and sysfs_emit_at for show(device *...) functions Convert the various sprintf fmaily calls in sysfs device show functions to sysfs_emit and sysfs_emit_at for PAGE_SIZE buffer safety. Done with: $ spatch -sp-file sysfs_emit_dev.cocci --in-place --max-width=80 . And cocci script: $ cat sysfs_emit_dev.cocci @@ identifier d_show; identifier dev, attr, buf; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... return - sprintf(buf, + sysfs_emit(buf, ...); ...> } @@ identifier d_show; identifier dev, attr, buf; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... return - snprintf(buf, PAGE_SIZE, + sysfs_emit(buf, ...); ...> } @@ identifier d_show; identifier dev, attr, buf; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... return - scnprintf(buf, PAGE_SIZE, + sysfs_emit(buf, ...); ...> } @@ identifier d_show; identifier dev, attr, buf; expression chr; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... return - strcpy(buf, chr); + sysfs_emit(buf, chr); ...> } @@ identifier d_show; identifier dev, attr, buf; identifier len; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... len = - sprintf(buf, + sysfs_emit(buf, ...); ...> return len; } @@ identifier d_show; identifier dev, attr, buf; identifier len; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... len = - snprintf(buf, PAGE_SIZE, + sysfs_emit(buf, ...); ...> return len; } @@ identifier d_show; identifier dev, attr, buf; identifier len; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... len = - scnprintf(buf, PAGE_SIZE, + sysfs_emit(buf, ...); ...> return len; } @@ identifier d_show; identifier dev, attr, buf; identifier len; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { <... - len += scnprintf(buf + len, PAGE_SIZE - len, + len += sysfs_emit_at(buf, len, ...); ...> return len; } @@ identifier d_show; identifier dev, attr, buf; expression chr; @@ ssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf) { ... - strcpy(buf, chr); - return strlen(buf); + return sysfs_emit(buf, chr); } Signed-off-by: Joe Perches <joe@perches.com> Link: https://lore.kernel.org/r/3d033c33056d88bbe34d4ddb62afd05ee166ab9a.1600285923.git.joe@perches.com Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: compile_nested_function(exarg_T *eap, cctx_T *cctx, garray_T *lines_to_free) { int is_global = *eap->arg == 'g' && eap->arg[1] == ':'; char_u *name_start = eap->arg; char_u *name_end = to_name_end(eap->arg, TRUE); int off; char_u *func_name; char_u *lambda_name; ufunc_T *ufunc; int r = FAIL; compiletype_T compile_type; isn_T *funcref_isn = NULL; if (eap->forceit) { emsg(_(e_cannot_use_bang_with_nested_def)); return NULL; } if (*name_start == '/') { name_end = skip_regexp(name_start + 1, '/', TRUE); if (*name_end == '/') ++name_end; set_nextcmd(eap, name_end); } if (name_end == name_start || *skipwhite(name_end) != '(') { if (!ends_excmd2(name_start, name_end)) { if (*skipwhite(name_end) == '.') semsg(_(e_cannot_define_dict_func_in_vim9_script_str), eap->cmd); else semsg(_(e_invalid_command_str), eap->cmd); return NULL; } // "def" or "def Name": list functions if (generate_DEF(cctx, name_start, name_end - name_start) == FAIL) return NULL; return eap->nextcmd == NULL ? (char_u *)"" : eap->nextcmd; } // Only g:Func() can use a namespace. if (name_start[1] == ':' && !is_global) { semsg(_(e_namespace_not_supported_str), name_start); return NULL; } if (cctx->ctx_skip != SKIP_YES && check_defined(name_start, name_end - name_start, cctx, NULL, FALSE) == FAIL) return NULL; if (!ASCII_ISUPPER(is_global ? name_start[2] : name_start[0])) { semsg(_(e_function_name_must_start_with_capital_str), name_start); return NULL; } eap->arg = name_end; fill_exarg_from_cctx(eap, cctx); eap->forceit = FALSE; // We use the special <Lamba>99 name, but it's not really a lambda. lambda_name = vim_strsave(get_lambda_name()); if (lambda_name == NULL) return NULL; // This may free the current line, make a copy of the name. off = is_global ? 2 : 0; func_name = vim_strnsave(name_start + off, name_end - name_start - off); if (func_name == NULL) { r = FAIL; goto theend; } ufunc = define_function(eap, lambda_name, lines_to_free); if (ufunc == NULL) { r = eap->skip ? OK : FAIL; goto theend; } if (eap->nextcmd != NULL) { semsg(_(e_text_found_after_str_str), eap->cmdidx == CMD_def ? "enddef" : "endfunction", eap->nextcmd); r = FAIL; func_ptr_unref(ufunc); goto theend; } // copy over the block scope IDs before compiling if (!is_global && cctx->ctx_ufunc->uf_block_depth > 0) { int block_depth = cctx->ctx_ufunc->uf_block_depth; ufunc->uf_block_ids = ALLOC_MULT(int, block_depth); if (ufunc->uf_block_ids != NULL) { mch_memmove(ufunc->uf_block_ids, cctx->ctx_ufunc->uf_block_ids, sizeof(int) * block_depth); ufunc->uf_block_depth = block_depth; } } // Define the funcref before compiling, so that it is found by any // recursive call. if (is_global) { r = generate_NEWFUNC(cctx, lambda_name, func_name); func_name = NULL; lambda_name = NULL; } else { // Define a local variable for the function reference. lvar_T *lvar = reserve_local(cctx, func_name, name_end - name_start, TRUE, ufunc->uf_func_type); if (lvar == NULL) goto theend; if (generate_FUNCREF(cctx, ufunc, &funcref_isn) == FAIL) goto theend; r = generate_STORE(cctx, ISN_STORE, lvar->lv_idx, NULL); } compile_type = get_compile_type(ufunc); #ifdef FEAT_PROFILE // If the outer function is profiled, also compile the nested function for // profiling. if (cctx->ctx_compile_type == CT_PROFILE) compile_type = CT_PROFILE; #endif if (func_needs_compiling(ufunc, compile_type) && compile_def_function(ufunc, TRUE, compile_type, cctx) == FAIL) { func_ptr_unref(ufunc); goto theend; } #ifdef FEAT_PROFILE // When the outer function is compiled for profiling, the nested function // may be called without profiling. Compile it here in the right context. if (compile_type == CT_PROFILE && func_needs_compiling(ufunc, CT_NONE)) compile_def_function(ufunc, FALSE, CT_NONE, cctx); #endif // If a FUNCREF instruction was generated, set the index after compiling. if (funcref_isn != NULL && ufunc->uf_def_status == UF_COMPILED) funcref_isn->isn_arg.funcref.fr_dfunc_idx = ufunc->uf_dfunc_idx; theend: vim_free(lambda_name); vim_free(func_name); return r == FAIL ? NULL : (char_u *)""; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'patch 9.0.0221: accessing freed memory if compiling nested function fails Problem: Accessing freed memory if compiling nested function fails. Solution: Mess up the variable name so that it won't be found.'</s>
<s>[INST] Given the following code containing errors, provide 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 crxFreeImageData(CrxImage *img) { CrxTile *tile = img->tiles; int nTiles = img->tileRows * img->tileCols; if (img->tiles) { for (int32_t curTile = 0; curTile < nTiles; curTile++, tile++) if (tile[curTile].comps) for (int32_t curPlane = 0; curPlane < img->nPlanes; curPlane++) crxFreeSubbandData(img, tile[curTile].comps + curPlane); free(img->tiles); img->tiles = 0; } if (img->planeBuf) { free(img->planeBuf); img->planeBuf = 0; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-770'], 'message': 'CR3 decoder: use mempool for memory'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: jinit_merged_upsampler(j_decompress_ptr cinfo) { my_upsample_ptr upsample; upsample = (my_upsample_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE, sizeof(my_upsampler)); cinfo->upsample = (struct jpeg_upsampler *)upsample; upsample->pub.start_pass = start_pass_merged_upsample; upsample->pub.need_context_rows = FALSE; upsample->out_row_width = cinfo->output_width * cinfo->out_color_components; if (cinfo->max_v_samp_factor == 2) { upsample->pub.upsample = merged_2v_upsample; if (jsimd_can_h2v2_merged_upsample()) upsample->upmethod = jsimd_h2v2_merged_upsample; else upsample->upmethod = h2v2_merged_upsample; if (cinfo->out_color_space == JCS_RGB565) { if (cinfo->dither_mode != JDITHER_NONE) { upsample->upmethod = h2v2_merged_upsample_565D; } else { upsample->upmethod = h2v2_merged_upsample_565; } } /* Allocate a spare row buffer */ upsample->spare_row = (JSAMPROW) (*cinfo->mem->alloc_large) ((j_common_ptr)cinfo, JPOOL_IMAGE, (size_t)(upsample->out_row_width * sizeof(JSAMPLE))); } else { upsample->pub.upsample = merged_1v_upsample; if (jsimd_can_h2v1_merged_upsample()) upsample->upmethod = jsimd_h2v1_merged_upsample; else upsample->upmethod = h2v1_merged_upsample; if (cinfo->out_color_space == JCS_RGB565) { if (cinfo->dither_mode != JDITHER_NONE) { upsample->upmethod = h2v1_merged_upsample_565D; } else { upsample->upmethod = h2v1_merged_upsample_565; } } /* No spare row needed */ upsample->spare_row = NULL; } build_ycc_rgb_table(cinfo); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix jpeg_skip_scanlines() segfault w/merged upsamp The additional segfault mentioned in #244 was due to the fact that the merged upsamplers use a different private structure than the non-merged upsamplers. jpeg_skip_scanlines() was assuming the latter, so when merged upsampling was enabled, jpeg_skip_scanlines() clobbered one of the IDCT method pointers in the merged upsampler's private structure. For reasons unknown, the test image in #441 did not encounter this segfault (too small?), but it encountered an issue similar to the one fixed in 5bc43c7821df982f65aa1c738f67fbf7cba8bd69, whereby it was necessary to set up a dummy postprocessing function in read_and_discard_scanlines() when merged upsampling was enabled. Failing to do so caused either a segfault in merged_2v_upsample() (due to a NULL pointer being passed to jcopy_sample_rows()) or an error ("Corrupt JPEG data: premature end of data segment"), depending on the number of scanlines skipped and whether the first scanline skipped was an odd- or even-numbered row. Fixes #441 Fixes #244 (for real this time)'</s>
<s>[INST] Given the following code containing errors, provide 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 ExportIndexAlphaQuantum(const Image *image, QuantumInfo *quantum_info,const MagickSizeType number_pixels, const PixelPacket *magick_restrict p, const IndexPacket *magick_restrict indexes,unsigned char *magick_restrict q, ExceptionInfo *exception) { ssize_t x; ssize_t bit; if (image->storage_class != PseudoClass) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ColormappedImageRequired","`%s'",image->filename); return; } switch (quantum_info->depth) { case 1: { unsigned char pixel; for (x=((ssize_t) number_pixels-3); x > 0; x-=4) { pixel=(unsigned char) *indexes++; *q=((pixel & 0x01) << 7); pixel=(unsigned char) (GetPixelOpacity(p) == (Quantum) TransparentOpacity ? 1 : 0); *q|=((pixel & 0x01) << 6); p++; pixel=(unsigned char) *indexes++; *q|=((pixel & 0x01) << 5); pixel=(unsigned char) (GetPixelOpacity(p) == (Quantum) TransparentOpacity ? 1 : 0); *q|=((pixel & 0x01) << 4); p++; pixel=(unsigned char) *indexes++; *q|=((pixel & 0x01) << 3); pixel=(unsigned char) (GetPixelOpacity(p) == (Quantum) TransparentOpacity ? 1 : 0); *q|=((pixel & 0x01) << 2); p++; pixel=(unsigned char) *indexes++; *q|=((pixel & 0x01) << 1); pixel=(unsigned char) (GetPixelOpacity(p) == (Quantum) TransparentOpacity ? 1 : 0); *q|=((pixel & 0x01) << 0); p++; q++; } if ((number_pixels % 4) != 0) { *q='\0'; for (bit=3; bit >= (ssize_t) (4-(number_pixels % 4)); bit-=2) { pixel=(unsigned char) *indexes++; *q|=((pixel & 0x01) << (unsigned char) (bit+4)); pixel=(unsigned char) (GetPixelOpacity(p) == (Quantum) TransparentOpacity ? 1 : 0); *q|=((pixel & 0x01) << (unsigned char) (bit+4-1)); p++; } q++; } break; } case 4: { unsigned char pixel; for (x=0; x < (ssize_t) number_pixels ; x++) { pixel=(unsigned char) *indexes++; *q=((pixel & 0xf) << 4); pixel=(unsigned char) (16*QuantumScale*((Quantum) (QuantumRange- GetPixelOpacity(p)))+0.5); *q|=((pixel & 0xf) << 0); p++; q++; } break; } case 8: { unsigned char pixel; for (x=0; x < (ssize_t) number_pixels; x++) { q=PopCharPixel((unsigned char) GetPixelIndex(indexes+x),q); pixel=ScaleQuantumToChar((Quantum) (QuantumRange-GetPixelOpacity(p))); q=PopCharPixel(pixel,q); p++; q+=quantum_info->pad; } break; } case 16: { unsigned short pixel; if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { q=PopShortPixel(quantum_info->endian,(unsigned short) GetPixelIndex(indexes+x),q); pixel=SinglePrecisionToHalf(QuantumScale*GetPixelAlpha(p)); q=PopShortPixel(quantum_info->endian,pixel,q); p++; q+=quantum_info->pad; } break; } for (x=0; x < (ssize_t) number_pixels; x++) { q=PopShortPixel(quantum_info->endian,(unsigned short) GetPixelIndex(indexes+x),q); pixel=ScaleQuantumToShort((Quantum) (QuantumRange-GetPixelOpacity(p))); q=PopShortPixel(quantum_info->endian,pixel,q); p++; q+=quantum_info->pad; } break; } case 32: { unsigned int pixel; if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { float pixel; q=PopFloatPixel(quantum_info,(float) GetPixelIndex(indexes+x),q); pixel=(float) (GetPixelAlpha(p)); q=PopFloatPixel(quantum_info,pixel,q); p++; q+=quantum_info->pad; } break; } for (x=0; x < (ssize_t) number_pixels; x++) { q=PopLongPixel(quantum_info->endian,(unsigned int) GetPixelIndex(indexes+x),q); pixel=ScaleQuantumToLong((Quantum) (QuantumRange-GetPixelOpacity(p))); q=PopLongPixel(quantum_info->endian,pixel,q); p++; q+=quantum_info->pad; } break; } case 64: { if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { double pixel; q=PopDoublePixel(quantum_info,(double) GetPixelIndex(indexes+x), q); pixel=(double) (GetPixelAlpha(p)); q=PopDoublePixel(quantum_info,pixel,q); p++; q+=quantum_info->pad; } break; } } default: { QuantumAny range; range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { q=PopQuantumPixel(quantum_info, GetPixelIndex(indexes+x),q); q=PopQuantumPixel(quantum_info, ScaleQuantumToAny((Quantum) (GetPixelAlpha(p)),range),q); p++; q+=quantum_info->pad; } break; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'https://github.com/ImageMagick/ImageMagick/pull/3083'</s>
<s>[INST] Given the following code containing errors, provide 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 RzDyldRebaseInfos *get_rebase_infos(RzDyldCache *cache) { RzDyldRebaseInfos *result = RZ_NEW0(RzDyldRebaseInfos); if (!result) { return NULL; } if (!cache->hdr->slideInfoOffset || !cache->hdr->slideInfoSize) { ut32 total_slide_infos = 0; ut32 n_slide_infos[MAX_N_HDR]; ut32 i; for (i = 0; i < cache->n_hdr && i < MAX_N_HDR; i++) { ut64 hdr_offset = cache->hdr_offset[i]; if (!rz_buf_read_le32_at(cache->buf, 0x13c + hdr_offset, &n_slide_infos[i])) { goto beach; } total_slide_infos += n_slide_infos[i]; } if (!total_slide_infos) { goto beach; } RzDyldRebaseInfosEntry *infos = RZ_NEWS0(RzDyldRebaseInfosEntry, total_slide_infos); if (!infos) { goto beach; } ut32 k = 0; for (i = 0; i < cache->n_hdr && i < MAX_N_HDR; i++) { ut64 hdr_offset = cache->hdr_offset[i]; if (!n_slide_infos[i]) { continue; } ut32 sio; if (!rz_buf_read_le32_at(cache->buf, 0x138 + hdr_offset, &sio)) { continue; } ut64 slide_infos_offset = sio; if (!slide_infos_offset) { continue; } slide_infos_offset += hdr_offset; ut32 j; RzDyldRebaseInfo *prev_info = NULL; for (j = 0; j < n_slide_infos[i]; j++) { ut64 offset = slide_infos_offset + j * sizeof(cache_mapping_slide); cache_mapping_slide entry; if (rz_buf_fread_at(cache->buf, offset, (ut8 *)&entry, "6lii", 1) != sizeof(cache_mapping_slide)) { break; } if (entry.slideInfoOffset && entry.slideInfoSize) { infos[k].start = entry.fileOffset + hdr_offset; infos[k].end = infos[k].start + entry.size; ut64 slide = prev_info ? prev_info->slide : UT64_MAX; infos[k].info = get_rebase_info(cache, entry.slideInfoOffset + hdr_offset, entry.slideInfoSize, entry.fileOffset + hdr_offset, slide); prev_info = infos[k].info; k++; } } } if (!k) { free(infos); goto beach; } if (k < total_slide_infos) { RzDyldRebaseInfosEntry *pruned_infos = RZ_NEWS0(RzDyldRebaseInfosEntry, k); if (!pruned_infos) { free(infos); goto beach; } memcpy(pruned_infos, infos, sizeof(RzDyldRebaseInfosEntry) * k); free(infos); infos = pruned_infos; } result->entries = infos; result->length = k; return result; } if (cache->hdr->mappingCount > 1) { RzDyldRebaseInfosEntry *infos = RZ_NEWS0(RzDyldRebaseInfosEntry, 1); if (!infos) { goto beach; } infos[0].start = cache->maps[1].fileOffset; infos[0].end = infos[0].start + cache->maps[1].size; infos[0].info = get_rebase_info(cache, cache->hdr->slideInfoOffset, cache->hdr->slideInfoSize, infos[0].start, UT64_MAX); result->entries = infos; result->length = 1; return result; } beach: free(result); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix oob write in dyldcache When the individual n_slide_infos were too high, the sum would overflow and too few entries would be allocated.'</s>
<s>[INST] Given the following code containing errors, provide 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_tag( char_u *tag, // tag (pattern) to jump to int type, int count, int forceit, // :ta with ! int verbose) // print "tag not found" message { taggy_T *tagstack = curwin->w_tagstack; int tagstackidx = curwin->w_tagstackidx; int tagstacklen = curwin->w_tagstacklen; int cur_match = 0; int cur_fnum = curbuf->b_fnum; int oldtagstackidx = tagstackidx; int prevtagstackidx = tagstackidx; int prev_num_matches; int new_tag = FALSE; int i; int ic; int no_regexp = FALSE; int error_cur_match = 0; int save_pos = FALSE; fmark_T saved_fmark; #ifdef FEAT_CSCOPE int jumped_to_tag = FALSE; #endif int new_num_matches; char_u **new_matches; int use_tagstack; int skip_msg = FALSE; char_u *buf_ffname = curbuf->b_ffname; // name to use for // priority computation int use_tfu = 1; char_u *tofree = NULL; // remember the matches for the last used tag static int num_matches = 0; static int max_num_matches = 0; // limit used for match search static char_u **matches = NULL; static int flags; #ifdef FEAT_EVAL if (tfu_in_use) { emsg(_(e_cannot_modify_tag_stack_within_tagfunc)); return FALSE; } #endif #ifdef EXITFREE if (type == DT_FREE) { // remove the list of matches FreeWild(num_matches, matches); # ifdef FEAT_CSCOPE cs_free_tags(); # endif num_matches = 0; return FALSE; } #endif if (type == DT_HELP) { type = DT_TAG; no_regexp = TRUE; use_tfu = 0; } prev_num_matches = num_matches; free_string_option(nofile_fname); nofile_fname = NULL; CLEAR_POS(&saved_fmark.mark); // shutup gcc 4.0 saved_fmark.fnum = 0; /* * Don't add a tag to the tagstack if 'tagstack' has been reset. */ if ((!p_tgst && *tag != NUL)) { use_tagstack = FALSE; new_tag = TRUE; #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { tagstack_clear_entry(&ptag_entry); if ((ptag_entry.tagname = vim_strsave(tag)) == NULL) goto end_do_tag; } #endif } else { #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) use_tagstack = FALSE; else #endif use_tagstack = TRUE; // new pattern, add to the tag stack if (*tag != NUL && (type == DT_TAG || type == DT_SELECT || type == DT_JUMP #ifdef FEAT_QUICKFIX || type == DT_LTAG #endif #ifdef FEAT_CSCOPE || type == DT_CSCOPE #endif )) { #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { if (ptag_entry.tagname != NULL && STRCMP(ptag_entry.tagname, tag) == 0) { // Jumping to same tag: keep the current match, so that // the CursorHold autocommand example works. cur_match = ptag_entry.cur_match; cur_fnum = ptag_entry.cur_fnum; } else { tagstack_clear_entry(&ptag_entry); if ((ptag_entry.tagname = vim_strsave(tag)) == NULL) goto end_do_tag; } } else #endif { /* * If the last used entry is not at the top, delete all tag * stack entries above it. */ while (tagstackidx < tagstacklen) tagstack_clear_entry(&tagstack[--tagstacklen]); // if the tagstack is full: remove oldest entry if (++tagstacklen > TAGSTACKSIZE) { tagstacklen = TAGSTACKSIZE; tagstack_clear_entry(&tagstack[0]); for (i = 1; i < tagstacklen; ++i) tagstack[i - 1] = tagstack[i]; --tagstackidx; } /* * put the tag name in the tag stack */ if ((tagstack[tagstackidx].tagname = vim_strsave(tag)) == NULL) { curwin->w_tagstacklen = tagstacklen - 1; goto end_do_tag; } curwin->w_tagstacklen = tagstacklen; save_pos = TRUE; // save the cursor position below } new_tag = TRUE; } else { if ( #if defined(FEAT_QUICKFIX) g_do_tagpreview != 0 ? ptag_entry.tagname == NULL : #endif tagstacklen == 0) { // empty stack emsg(_(e_tag_stack_empty)); goto end_do_tag; } if (type == DT_POP) // go to older position { #ifdef FEAT_FOLDING int old_KeyTyped = KeyTyped; #endif if ((tagstackidx -= count) < 0) { emsg(_(e_at_bottom_of_tag_stack)); if (tagstackidx + count == 0) { // We did [num]^T from the bottom of the stack tagstackidx = 0; goto end_do_tag; } // We weren't at the bottom of the stack, so jump all the // way to the bottom now. tagstackidx = 0; } else if (tagstackidx >= tagstacklen) // count == 0? { emsg(_(e_at_top_of_tag_stack)); goto end_do_tag; } // Make a copy of the fmark, autocommands may invalidate the // tagstack before it's used. saved_fmark = tagstack[tagstackidx].fmark; if (saved_fmark.fnum != curbuf->b_fnum) { /* * Jump to other file. If this fails (e.g. because the * file was changed) keep original position in tag stack. */ if (buflist_getfile(saved_fmark.fnum, saved_fmark.mark.lnum, GETF_SETMARK, forceit) == FAIL) { tagstackidx = oldtagstackidx; // back to old posn goto end_do_tag; } // An BufReadPost autocommand may jump to the '" mark, but // we don't what that here. curwin->w_cursor.lnum = saved_fmark.mark.lnum; } else { setpcmark(); curwin->w_cursor.lnum = saved_fmark.mark.lnum; } curwin->w_cursor.col = saved_fmark.mark.col; curwin->w_set_curswant = TRUE; check_cursor(); #ifdef FEAT_FOLDING if ((fdo_flags & FDO_TAG) && old_KeyTyped) foldOpenCursor(); #endif // remove the old list of matches FreeWild(num_matches, matches); #ifdef FEAT_CSCOPE cs_free_tags(); #endif num_matches = 0; tag_freematch(); goto end_do_tag; } if (type == DT_TAG #if defined(FEAT_QUICKFIX) || type == DT_LTAG #endif ) { #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { cur_match = ptag_entry.cur_match; cur_fnum = ptag_entry.cur_fnum; } else #endif { // ":tag" (no argument): go to newer pattern save_pos = TRUE; // save the cursor position below if ((tagstackidx += count - 1) >= tagstacklen) { /* * Beyond the last one, just give an error message and * go to the last one. Don't store the cursor * position. */ tagstackidx = tagstacklen - 1; emsg(_(e_at_top_of_tag_stack)); save_pos = FALSE; } else if (tagstackidx < 0) // must have been count == 0 { emsg(_(e_at_bottom_of_tag_stack)); tagstackidx = 0; goto end_do_tag; } cur_match = tagstack[tagstackidx].cur_match; cur_fnum = tagstack[tagstackidx].cur_fnum; } new_tag = TRUE; } else // go to other matching tag { // Save index for when selection is cancelled. prevtagstackidx = tagstackidx; #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { cur_match = ptag_entry.cur_match; cur_fnum = ptag_entry.cur_fnum; } else #endif { if (--tagstackidx < 0) tagstackidx = 0; cur_match = tagstack[tagstackidx].cur_match; cur_fnum = tagstack[tagstackidx].cur_fnum; } switch (type) { case DT_FIRST: cur_match = count - 1; break; case DT_SELECT: case DT_JUMP: #ifdef FEAT_CSCOPE case DT_CSCOPE: #endif case DT_LAST: cur_match = MAXCOL - 1; break; case DT_NEXT: cur_match += count; break; case DT_PREV: cur_match -= count; break; } if (cur_match >= MAXCOL) cur_match = MAXCOL - 1; else if (cur_match < 0) { emsg(_(e_cannot_go_before_first_matching_tag)); skip_msg = TRUE; cur_match = 0; cur_fnum = curbuf->b_fnum; } } } #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { if (type != DT_SELECT && type != DT_JUMP) { ptag_entry.cur_match = cur_match; ptag_entry.cur_fnum = cur_fnum; } } else #endif { /* * For ":tag [arg]" or ":tselect" remember position before the jump. */ saved_fmark = tagstack[tagstackidx].fmark; if (save_pos) { tagstack[tagstackidx].fmark.mark = curwin->w_cursor; tagstack[tagstackidx].fmark.fnum = curbuf->b_fnum; } // Curwin will change in the call to jumpto_tag() if ":stag" was // used or an autocommand jumps to another window; store value of // tagstackidx now. curwin->w_tagstackidx = tagstackidx; if (type != DT_SELECT && type != DT_JUMP) { curwin->w_tagstack[tagstackidx].cur_match = cur_match; curwin->w_tagstack[tagstackidx].cur_fnum = cur_fnum; } } } // When not using the current buffer get the name of buffer "cur_fnum". // Makes sure that the tag order doesn't change when using a remembered // position for "cur_match". if (cur_fnum != curbuf->b_fnum) { buf_T *buf = buflist_findnr(cur_fnum); if (buf != NULL) buf_ffname = buf->b_ffname; } /* * Repeat searching for tags, when a file has not been found. */ for (;;) { int other_name; char_u *name; /* * When desired match not found yet, try to find it (and others). */ if (use_tagstack) { // make a copy, the tagstack may change in 'tagfunc' name = vim_strsave(tagstack[tagstackidx].tagname); vim_free(tofree); tofree = name; } #if defined(FEAT_QUICKFIX) else if (g_do_tagpreview != 0) name = ptag_entry.tagname; #endif else name = tag; other_name = (tagmatchname == NULL || STRCMP(tagmatchname, name) != 0); if (new_tag || (cur_match >= num_matches && max_num_matches != MAXCOL) || other_name) { if (other_name) { vim_free(tagmatchname); tagmatchname = vim_strsave(name); } if (type == DT_SELECT || type == DT_JUMP #if defined(FEAT_QUICKFIX) || type == DT_LTAG #endif ) cur_match = MAXCOL - 1; if (type == DT_TAG) max_num_matches = MAXCOL; else max_num_matches = cur_match + 1; // when the argument starts with '/', use it as a regexp if (!no_regexp && *name == '/') { flags = TAG_REGEXP; ++name; } else flags = TAG_NOIC; #ifdef FEAT_CSCOPE if (type == DT_CSCOPE) flags = TAG_CSCOPE; #endif if (verbose) flags |= TAG_VERBOSE; if (!use_tfu) flags |= TAG_NO_TAGFUNC; if (find_tags(name, &new_num_matches, &new_matches, flags, max_num_matches, buf_ffname) == OK && new_num_matches < max_num_matches) max_num_matches = MAXCOL; // If less than max_num_matches // found: all matches found. // If there already were some matches for the same name, move them // to the start. Avoids that the order changes when using // ":tnext" and jumping to another file. if (!new_tag && !other_name) { int j, k; int idx = 0; tagptrs_T tagp, tagp2; // Find the position of each old match in the new list. Need // to use parse_match() to find the tag line. for (j = 0; j < num_matches; ++j) { parse_match(matches[j], &tagp); for (i = idx; i < new_num_matches; ++i) { parse_match(new_matches[i], &tagp2); if (STRCMP(tagp.tagname, tagp2.tagname) == 0) { char_u *p = new_matches[i]; for (k = i; k > idx; --k) new_matches[k] = new_matches[k - 1]; new_matches[idx++] = p; break; } } } } FreeWild(num_matches, matches); num_matches = new_num_matches; matches = new_matches; } if (num_matches <= 0) { if (verbose) semsg(_(e_tag_not_found_str), name); #if defined(FEAT_QUICKFIX) g_do_tagpreview = 0; #endif } else { int ask_for_selection = FALSE; #ifdef FEAT_CSCOPE if (type == DT_CSCOPE && num_matches > 1) { cs_print_tags(); ask_for_selection = TRUE; } else #endif if (type == DT_TAG && *tag != NUL) // If a count is supplied to the ":tag <name>" command, then // jump to count'th matching tag. cur_match = count > 0 ? count - 1 : 0; else if (type == DT_SELECT || (type == DT_JUMP && num_matches > 1)) { print_tag_list(new_tag, use_tagstack, num_matches, matches); ask_for_selection = TRUE; } #if defined(FEAT_QUICKFIX) && defined(FEAT_EVAL) else if (type == DT_LTAG) { if (add_llist_tags(tag, num_matches, matches) == FAIL) goto end_do_tag; cur_match = 0; // Jump to the first tag } #endif if (ask_for_selection == TRUE) { /* * Ask to select a tag from the list. */ i = prompt_for_number(NULL); if (i <= 0 || i > num_matches || got_int) { // no valid choice: don't change anything if (use_tagstack) { tagstack[tagstackidx].fmark = saved_fmark; tagstackidx = prevtagstackidx; } #ifdef FEAT_CSCOPE cs_free_tags(); jumped_to_tag = TRUE; #endif break; } cur_match = i - 1; } if (cur_match >= num_matches) { // Avoid giving this error when a file wasn't found and we're // looking for a match in another file, which wasn't found. // There will be an emsg("file doesn't exist") below then. if ((type == DT_NEXT || type == DT_FIRST) && nofile_fname == NULL) { if (num_matches == 1) emsg(_(e_there_is_only_one_matching_tag)); else emsg(_(e_cannot_go_beyond_last_matching_tag)); skip_msg = TRUE; } cur_match = num_matches - 1; } if (use_tagstack) { tagptrs_T tagp; tagstack[tagstackidx].cur_match = cur_match; tagstack[tagstackidx].cur_fnum = cur_fnum; // store user-provided data originating from tagfunc if (use_tfu && parse_match(matches[cur_match], &tagp) == OK && tagp.user_data) { VIM_CLEAR(tagstack[tagstackidx].user_data); tagstack[tagstackidx].user_data = vim_strnsave( tagp.user_data, tagp.user_data_end - tagp.user_data); } ++tagstackidx; } #if defined(FEAT_QUICKFIX) else if (g_do_tagpreview != 0) { ptag_entry.cur_match = cur_match; ptag_entry.cur_fnum = cur_fnum; } #endif /* * Only when going to try the next match, report that the previous * file didn't exist. Otherwise an emsg() is given below. */ if (nofile_fname != NULL && error_cur_match != cur_match) smsg(_("File \"%s\" does not exist"), nofile_fname); ic = (matches[cur_match][0] & MT_IC_OFF); if (type != DT_TAG && type != DT_SELECT && type != DT_JUMP #ifdef FEAT_CSCOPE && type != DT_CSCOPE #endif && (num_matches > 1 || ic) && !skip_msg) { // Give an indication of the number of matching tags sprintf((char *)IObuff, _("tag %d of %d%s"), cur_match + 1, num_matches, max_num_matches != MAXCOL ? _(" or more") : ""); if (ic) STRCAT(IObuff, _(" Using tag with different case!")); if ((num_matches > prev_num_matches || new_tag) && num_matches > 1) { if (ic) msg_attr((char *)IObuff, HL_ATTR(HLF_W)); else msg((char *)IObuff); msg_scroll = TRUE; // don't overwrite this message } else give_warning(IObuff, ic); if (ic && !msg_scrolled && msg_silent == 0) { out_flush(); ui_delay(1007L, TRUE); } } #if defined(FEAT_EVAL) // Let the SwapExists event know what tag we are jumping to. vim_snprintf((char *)IObuff, IOSIZE, ":ta %s\r", name); set_vim_var_string(VV_SWAPCOMMAND, IObuff, -1); #endif /* * Jump to the desired match. */ i = jumpto_tag(matches[cur_match], forceit, type != DT_CSCOPE); #if defined(FEAT_EVAL) set_vim_var_string(VV_SWAPCOMMAND, NULL, -1); #endif if (i == NOTAGFILE) { // File not found: try again with another matching tag if ((type == DT_PREV && cur_match > 0) || ((type == DT_TAG || type == DT_NEXT || type == DT_FIRST) && (max_num_matches != MAXCOL || cur_match < num_matches - 1))) { error_cur_match = cur_match; if (use_tagstack) --tagstackidx; if (type == DT_PREV) --cur_match; else { type = DT_NEXT; ++cur_match; } continue; } semsg(_(e_file_str_does_not_exist), nofile_fname); } else { // We may have jumped to another window, check that // tagstackidx is still valid. if (use_tagstack && tagstackidx > curwin->w_tagstacklen) tagstackidx = curwin->w_tagstackidx; #ifdef FEAT_CSCOPE jumped_to_tag = TRUE; #endif } } break; } end_do_tag: // Only store the new index when using the tagstack and it's valid. if (use_tagstack && tagstackidx <= curwin->w_tagstacklen) curwin->w_tagstackidx = tagstackidx; postponed_split = 0; // don't split next time # ifdef FEAT_QUICKFIX g_do_tagpreview = 0; // don't do tag preview next time # endif vim_free(tofree); #ifdef FEAT_CSCOPE return jumped_to_tag; #else return FALSE; #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'patch 9.0.0389: crash when 'tagfunc' closes the window Problem: Crash when 'tagfunc' closes the window. Solution: Bail out when the window was closed.'</s>
<s>[INST] Given the following code containing errors, provide 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 RzList *entries(RzBinFile *bf) { if (!bf) { return NULL; } LuacBinInfo *bin_info_obj = GET_INTERNAL_BIN_INFO_OBJ(bf); if (!bin_info_obj) { return NULL; } return bin_info_obj->entry_list; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-787'], 'message': 'Fix oob read on _luac_build_info and luac memleaks'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bgp_capability_vty_out (struct vty *vty, struct peer *peer) { char *pnt; char *end; struct capability cap; pnt = peer->notify.data; end = pnt + peer->notify.length; while (pnt < end) { memcpy(&cap, pnt, sizeof(struct capability)); if (pnt + 2 > end) return; if (pnt + (cap.length + 2) > end) return; if (cap.code == CAPABILITY_CODE_MP) { vty_out (vty, " Capability error for: Multi protocol "); switch (ntohs (cap.mpc.afi)) { case AFI_IP: vty_out (vty, "AFI IPv4, "); break; case AFI_IP6: vty_out (vty, "AFI IPv6, "); break; default: vty_out (vty, "AFI Unknown %d, ", ntohs (cap.mpc.afi)); break; } switch (cap.mpc.safi) { case SAFI_UNICAST: vty_out (vty, "SAFI Unicast"); break; case SAFI_MULTICAST: vty_out (vty, "SAFI Multicast"); break; case SAFI_UNICAST_MULTICAST: vty_out (vty, "SAFI Unicast Multicast"); break; case BGP_SAFI_VPNV4: vty_out (vty, "SAFI MPLS-VPN"); break; default: vty_out (vty, "SAFI Unknown %d ", cap.mpc.safi); break; } vty_out (vty, "%s", VTY_NEWLINE); } else if (cap.code >= 128) vty_out (vty, " Capability error: vendor specific capability code %d", cap.code); else vty_out (vty, " Capability error: unknown capability code %d", cap.code); pnt += cap.length + 2; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': '[bgpd] cleanup, compact and consolidate capability parsing code 2007-07-26 Paul Jakma <paul.jakma@sun.com> * (general) Clean up and compact capability parsing slightly. Consolidate validation of length and logging of generic TLV, and memcpy of capability data, thus removing such from cap specifc code (not always present or correct). * bgp_open.h: Add structures for the generic capability TLV header and for the data formats of the various specific capabilities we support. Hence remove the badly named, or else misdefined, struct capability. * bgp_open.c: (bgp_capability_vty_out) Use struct capability_mp_data. Do the length checks *before* memcpy()'ing based on that length (stored capability - should have been validated anyway on input, but..). (bgp_afi_safi_valid_indices) new function to validate (afi,safi) which is about to be used as index into arrays, consolidates several instances of same, at least one of which appeared to be incomplete.. (bgp_capability_mp) Much condensed. (bgp_capability_orf_entry) New, process one ORF entry (bgp_capability_orf) Condensed. Fixed to process all ORF entries. (bgp_capability_restart) Condensed, and fixed to use a cap-specific type, rather than abusing capability_mp. (struct message capcode_str) added to aid generic logging. (size_t cap_minsizes[]) added to aid generic validation of capability length field. (bgp_capability_parse) Generic logging and validation of TLV consolidated here. Code compacted as much as possible. * bgp_packet.c: (bgp_open_receive) Capability parsers now use streams, so no more need here to manually fudge the input stream getp. (bgp_capability_msg_parse) use struct capability_mp_data. Validate lengths /before/ memcpy. Use bgp_afi_safi_valid_indices. (bgp_capability_receive) Exported for use by test harness. * bgp_vty.c: (bgp_show_summary) fix conversion warning (bgp_show_peer) ditto * bgp_debug.h: Fix storage 'extern' after type 'const'. * lib/log.c: (mes_lookup) warning about code not being in same-number array slot should be debug, not warning. E.g. BGP has several discontigious number spaces, allocating from different parts of a space is not uncommon (e.g. IANA assigned versus vendor-assigned code points in some number space).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bgp_capability_parse (struct peer *peer, u_char *pnt, u_char length, u_char **error) { int ret; u_char *end; struct capability cap; end = pnt + length; while (pnt < end) { afi_t afi; safi_t safi; /* Fetch structure to the byte stream. */ memcpy (&cap, pnt, sizeof (struct capability)); afi = ntohs(cap.mpc.afi); safi = cap.mpc.safi; if (BGP_DEBUG (normal, NORMAL)) zlog_debug ("%s OPEN has CAPABILITY code: %d, length %d", peer->host, cap.code, cap.length); /* We need at least capability code and capability length. */ if (pnt + 2 > end) { zlog_info ("%s Capability length error", peer->host); bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0); return -1; } /* Capability length check. */ if (pnt + (cap.length + 2) > end) { zlog_info ("%s Capability length error", peer->host); bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0); return -1; } /* We know MP Capability Code. */ if (cap.code == CAPABILITY_CODE_MP) { if (BGP_DEBUG (normal, NORMAL)) zlog_debug ("%s OPEN has MP_EXT CAP for afi/safi: %u/%u", peer->host, afi, safi); /* Ignore capability when override-capability is set. */ if (! CHECK_FLAG (peer->flags, PEER_FLAG_OVERRIDE_CAPABILITY)) { /* Set negotiated value. */ ret = bgp_capability_mp (peer, &cap); /* Unsupported Capability. */ if (ret < 0) { /* Store return data. */ memcpy (*error, &cap, cap.length + 2); *error += cap.length + 2; } } } else if (cap.code == CAPABILITY_CODE_REFRESH || cap.code == CAPABILITY_CODE_REFRESH_OLD) { /* Check length. */ if (cap.length != CAPABILITY_CODE_REFRESH_LEN) { zlog_info ("%s Route Refresh Capability length error %d", peer->host, cap.length); bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0); return -1; } if (BGP_DEBUG (normal, NORMAL)) zlog_debug ("%s OPEN has ROUTE-REFRESH capability(%s) for all address-families", peer->host, cap.code == CAPABILITY_CODE_REFRESH_OLD ? "old" : "new"); /* BGP refresh capability */ if (cap.code == CAPABILITY_CODE_REFRESH_OLD) SET_FLAG (peer->cap, PEER_CAP_REFRESH_OLD_RCV); else SET_FLAG (peer->cap, PEER_CAP_REFRESH_NEW_RCV); } else if (cap.code == CAPABILITY_CODE_ORF || cap.code == CAPABILITY_CODE_ORF_OLD) bgp_capability_orf (peer, &cap, pnt + sizeof (struct capability)); else if (cap.code == CAPABILITY_CODE_RESTART) { struct graceful_restart_af graf; u_int16_t restart_flag_time; int restart_bit = 0; u_char *restart_pnt; u_char *restart_end; /* Check length. */ if (cap.length < CAPABILITY_CODE_RESTART_LEN) { zlog_info ("%s Graceful Restart Capability length error %d", peer->host, cap.length); bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0); return -1; } SET_FLAG (peer->cap, PEER_CAP_RESTART_RCV); restart_flag_time = ntohs(cap.mpc.afi); if (CHECK_FLAG (restart_flag_time, RESTART_R_BIT)) restart_bit = 1; UNSET_FLAG (restart_flag_time, 0xF000); peer->v_gr_restart = restart_flag_time; if (BGP_DEBUG (normal, NORMAL)) { zlog_debug ("%s OPEN has Graceful Restart capability", peer->host); zlog_debug ("%s Peer has%srestarted. Restart Time : %d", peer->host, restart_bit ? " " : " not ", peer->v_gr_restart); } restart_pnt = pnt + 4; restart_end = pnt + cap.length + 2; while (restart_pnt < restart_end) { memcpy (&graf, restart_pnt, sizeof (struct graceful_restart_af)); afi = ntohs(graf.afi); safi = graf.safi; if (CHECK_FLAG (graf.flag, RESTART_F_BIT)) SET_FLAG (peer->af_cap[afi][safi], PEER_CAP_RESTART_AF_PRESERVE_RCV); if (strcmp (afi_safi_print (afi, safi), "Unknown") == 0) { if (BGP_DEBUG (normal, NORMAL)) zlog_debug ("%s Addr-family %d/%d(afi/safi) not supported. I gnore the Graceful Restart capability", peer->host, afi, safi); } else if (! peer->afc[afi][safi]) { if (BGP_DEBUG (normal, NORMAL)) zlog_debug ("%s Addr-family %d/%d(afi/safi) not enabled. Ignore the Graceful Restart capability", peer->host, afi, safi); } else { if (BGP_DEBUG (normal, NORMAL)) zlog_debug ("%s Address family %s is%spreserved", peer->host, afi_safi_print (afi, safi), CHECK_FLAG (peer->af_cap[afi][safi], PEER_CAP_RESTART_AF_PRESERVE_RCV) ? " " : " not "); SET_FLAG (peer->af_cap[afi][safi], PEER_CAP_RESTART_AF_RCV); } restart_pnt += 4; } } else if (cap.code == CAPABILITY_CODE_DYNAMIC) { /* Check length. */ if (cap.length != CAPABILITY_CODE_DYNAMIC_LEN) { zlog_info ("%s Dynamic Capability length error %d", peer->host, cap.length); bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0); return -1; } if (BGP_DEBUG (normal, NORMAL)) zlog_debug ("%s OPEN has DYNAMIC capability", peer->host); SET_FLAG (peer->cap, PEER_CAP_DYNAMIC_RCV); } else if (cap.code > 128) { /* We don't send Notification for unknown vendor specific capabilities. It seems reasonable for now... */ zlog_warn ("%s Vendor specific capability %d", peer->host, cap.code); } else { zlog_warn ("%s unrecognized capability code: %d - ignored", peer->host, cap.code); memcpy (*error, &cap, cap.length + 2); *error += cap.length + 2; } pnt += cap.length + 2; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': '[bgpd] cleanup, compact and consolidate capability parsing code 2007-07-26 Paul Jakma <paul.jakma@sun.com> * (general) Clean up and compact capability parsing slightly. Consolidate validation of length and logging of generic TLV, and memcpy of capability data, thus removing such from cap specifc code (not always present or correct). * bgp_open.h: Add structures for the generic capability TLV header and for the data formats of the various specific capabilities we support. Hence remove the badly named, or else misdefined, struct capability. * bgp_open.c: (bgp_capability_vty_out) Use struct capability_mp_data. Do the length checks *before* memcpy()'ing based on that length (stored capability - should have been validated anyway on input, but..). (bgp_afi_safi_valid_indices) new function to validate (afi,safi) which is about to be used as index into arrays, consolidates several instances of same, at least one of which appeared to be incomplete.. (bgp_capability_mp) Much condensed. (bgp_capability_orf_entry) New, process one ORF entry (bgp_capability_orf) Condensed. Fixed to process all ORF entries. (bgp_capability_restart) Condensed, and fixed to use a cap-specific type, rather than abusing capability_mp. (struct message capcode_str) added to aid generic logging. (size_t cap_minsizes[]) added to aid generic validation of capability length field. (bgp_capability_parse) Generic logging and validation of TLV consolidated here. Code compacted as much as possible. * bgp_packet.c: (bgp_open_receive) Capability parsers now use streams, so no more need here to manually fudge the input stream getp. (bgp_capability_msg_parse) use struct capability_mp_data. Validate lengths /before/ memcpy. Use bgp_afi_safi_valid_indices. (bgp_capability_receive) Exported for use by test harness. * bgp_vty.c: (bgp_show_summary) fix conversion warning (bgp_show_peer) ditto * bgp_debug.h: Fix storage 'extern' after type 'const'. * lib/log.c: (mes_lookup) warning about code not being in same-number array slot should be debug, not warning. E.g. BGP has several discontigious number spaces, allocating from different parts of a space is not uncommon (e.g. IANA assigned versus vendor-assigned code points in some number space).'</s>