instruction
stringclasses
1 value
input
stringlengths
64
129k
output
int64
0
1
__index_level_0__
int64
0
30k
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 enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSshortShort(uint16 value) { if (value>0x7FFF) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } Commit Message: * libtiff/tif_dirread.c: modify ChopUpSingleUncompressedStrip() to instanciate compute ntrips as TIFFhowmany_32(td->td_imagelength, rowsperstrip), instead of a logic based on the total size of data. Which is faulty is the total size of data is not sufficient to fill the whole image, and thus results in reading outside of the StripByCounts/StripOffsets arrays when using TIFFReadScanline(). Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2608. * libtiff/tif_strip.c: revert the change in TIFFNumberOfStrips() done for http://bugzilla.maptools.org/show_bug.cgi?id=2587 / CVE-2016-9273 since the above change is a better fix that makes it unnecessary. CWE ID: CWE-125
0
23,952
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 BaseRenderingContext2D::ComputeDirtyRect(const FloatRect& local_rect, SkIRect* dirty_rect) { SkIRect clip_bounds; if (!DrawingCanvas()->getDeviceClipBounds(&clip_bounds)) return false; return ComputeDirtyRect(local_rect, clip_bounds, dirty_rect); } 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
15,978
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: add_property_to_cc(CClassNode* cc, const char* propname, int not, ScanEnv* env) { int ctype = propname2ctype(env, propname); if (ctype < 0) return ctype; return add_ctype_to_cc(cc, ctype, not, 0, env); } Commit Message: Merge pull request #134 from k-takata/fix-segv-in-error-str Fix SEGV in onig_error_code_to_str() (Fix #132) CWE ID: CWE-476
0
3,209
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_video_get_event(unsigned int fd, unsigned int cmd, struct compat_video_event __user *up) { struct video_event kevent; mm_segment_t old_fs = get_fs(); int err; set_fs(KERNEL_DS); err = sys_ioctl(fd, cmd, (unsigned long) &kevent); set_fs(old_fs); if (!err) { err = put_user(kevent.type, &up->type); err |= put_user(kevent.timestamp, &up->timestamp); err |= put_user(kevent.u.size.w, &up->u.size.w); err |= put_user(kevent.u.size.h, &up->u.size.h); err |= put_user(kevent.u.size.aspect_ratio, &up->u.size.aspect_ratio); if (err) err = -EFAULT; } return err; } Commit Message: fs/compat_ioctl.c: VIDEO_SET_SPU_PALETTE missing error check The compat ioctl for VIDEO_SET_SPU_PALETTE was missing an error check while converting ioctl arguments. This could lead to leaking kernel stack contents into userspace. Patch extracted from existing fix in grsecurity. Signed-off-by: Kees Cook <keescook@chromium.org> Cc: David Miller <davem@davemloft.net> Cc: Brad Spengler <spender@grsecurity.net> Cc: PaX Team <pageexec@freemail.hu> Cc: <stable@vger.kernel.org> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-200
0
13,342
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 ip6_dgram_sock_seq_show(struct seq_file *seq, struct sock *sp, __u16 srcp, __u16 destp, int bucket) { const struct in6_addr *dest, *src; dest = &sp->sk_v6_daddr; src = &sp->sk_v6_rcv_saddr; seq_printf(seq, "%5d: %08X%08X%08X%08X:%04X %08X%08X%08X%08X:%04X " "%02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %d\n", bucket, src->s6_addr32[0], src->s6_addr32[1], src->s6_addr32[2], src->s6_addr32[3], srcp, dest->s6_addr32[0], dest->s6_addr32[1], dest->s6_addr32[2], dest->s6_addr32[3], destp, sp->sk_state, sk_wmem_alloc_get(sp), sk_rmem_alloc_get(sp), 0, 0L, 0, from_kuid_munged(seq_user_ns(seq), sock_i_uid(sp)), 0, sock_i_ino(sp), atomic_read(&sp->sk_refcnt), sp, atomic_read(&sp->sk_drops)); } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <dvyukov@google.com> Signed-off-by: Eric Dumazet <edumazet@google.com> Acked-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-416
0
6,120
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 fuse_read_update_size(struct inode *inode, loff_t size, u64 attr_ver) { struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_inode *fi = get_fuse_inode(inode); spin_lock(&fc->lock); if (attr_ver == fi->attr_version && size < inode->i_size && !test_bit(FUSE_I_SIZE_UNSTABLE, &fi->state)) { fi->attr_version = ++fc->attr_version; i_size_write(inode, size); } spin_unlock(&fc->lock); } Commit Message: fuse: break infinite loop in fuse_fill_write_pages() I got a report about unkillable task eating CPU. Further investigation shows, that the problem is in the fuse_fill_write_pages() function. If iov's first segment has zero length, we get an infinite loop, because we never reach iov_iter_advance() call. Fix this by calling iov_iter_advance() before repeating an attempt to copy data from userspace. A similar problem is described in 124d3b7041f ("fix writev regression: pan hanging unkillable and un-straceable"). If zero-length segmend is followed by segment with invalid address, iov_iter_fault_in_readable() checks only first segment (zero-length), iov_iter_copy_from_user_atomic() skips it, fails at second and returns zero -> goto again without skipping zero-length segment. Patch calls iov_iter_advance() before goto again: we'll skip zero-length segment at second iteraction and iov_iter_fault_in_readable() will detect invalid address. Special thanks to Konstantin Khlebnikov, who helped a lot with the commit description. Cc: Andrew Morton <akpm@linux-foundation.org> Cc: Maxim Patlasov <mpatlasov@parallels.com> Cc: Konstantin Khlebnikov <khlebnikov@yandex-team.ru> Signed-off-by: Roman Gushchin <klamm@yandex-team.ru> Signed-off-by: Miklos Szeredi <miklos@szeredi.hu> Fixes: ea9b9907b82a ("fuse: implement perform_write") Cc: <stable@vger.kernel.org> CWE ID: CWE-399
0
12,148
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: dissect_PRINTER_DATATYPE(tvbuff_t *tvb, int offset, packet_info *pinfo, proto_tree *tree, dcerpc_info *di, guint8 *drep _U_) { if (di->conformant_run) return offset; offset = dissect_ndr_cvstring( tvb, offset, pinfo, tree, di, drep, sizeof(guint16), hf_datatype, TRUE, NULL); return offset; } Commit Message: SPOOLSS: Try to avoid an infinite loop. Use tvb_reported_length_remaining in dissect_spoolss_uint16uni. Make sure our offset always increments in dissect_spoolss_keybuffer. Change-Id: I7017c9685bb2fa27161d80a03b8fca4ef630e793 Reviewed-on: https://code.wireshark.org/review/14687 Reviewed-by: Gerald Combs <gerald@wireshark.org> Petri-Dish: Gerald Combs <gerald@wireshark.org> Tested-by: Petri Dish Buildbot <buildbot-no-reply@wireshark.org> Reviewed-by: Michael Mann <mmann78@netscape.net> CWE ID: CWE-399
0
28,712
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_pause(struct kvm_vcpu *vcpu) { if (!kvm_pause_in_guest(vcpu->kvm)) grow_ple_window(vcpu); /* * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting" * VM-execution control is ignored if CPL > 0. OTOH, KVM * never set PAUSE_EXITING and just set PLE if supported, * so the vcpu must be CPL=0 if it gets a PAUSE exit. */ kvm_vcpu_on_spin(vcpu, true); return kvm_skip_emulated_instruction(vcpu); } Commit Message: kvm: nVMX: Enforce cpl=0 for VMX instructions VMX instructions executed inside a L1 VM will always trigger a VM exit even when executed with cpl 3. This means we must perform the privilege check in software. Fixes: 70f3aac964ae("kvm: nVMX: Remove superfluous VMX instruction fault checks") Cc: stable@vger.kernel.org Signed-off-by: Felix Wilhelm <fwilhelm@google.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> CWE ID:
0
9,848
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: HandleSignalsState DataPipeProducerDispatcher::GetHandleSignalsState() const { base::AutoLock lock(lock_); return GetHandleSignalsStateNoLock(); } Commit Message: [mojo-core] Validate data pipe endpoint metadata Ensures that we don't blindly trust specified buffer size and offset metadata when deserializing data pipe consumer and producer handles. Bug: 877182 Change-Id: I30f3eceafb5cee06284c2714d08357ef911d6fd9 Reviewed-on: https://chromium-review.googlesource.com/1192922 Reviewed-by: Reilly Grant <reillyg@chromium.org> Commit-Queue: Ken Rockot <rockot@chromium.org> Cr-Commit-Position: refs/heads/master@{#586704} CWE ID: CWE-20
0
22,682
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 piv_validate_general_authentication(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { piv_private_data_t * priv = PIV_DATA(card); int r; u8 *p; const u8 *tag; size_t taglen; const u8 *body; size_t bodylen; unsigned int real_alg_id; u8 sbuf[4096]; /* needs work. for 3072 keys, needs 384+10 or so */ u8 *rbuf = NULL; size_t rbuflen = 0; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* should assume large send data */ p = sbuf; put_tag_and_len(0x7c, (2 + put_tag_and_len(0, datalen, NULL)) , &p); put_tag_and_len(0x82, 0, &p); if (priv->operation == SC_SEC_OPERATION_DERIVE && priv->algorithm == SC_ALGORITHM_EC) put_tag_and_len(0x85, datalen, &p); else put_tag_and_len(0x81, datalen, &p); memcpy(p, data, datalen); p += datalen; /* * alg_id=06 is a place holder for all RSA keys. * Derive the real alg_id based on the size of the * the data, as we are always using raw mode. * Non RSA keys needs some work in thia area. */ real_alg_id = priv->alg_id; if (priv->alg_id == 0x06) { switch (datalen) { case 128: real_alg_id = 0x06; break; case 256: real_alg_id = 0x07; break; case 384: real_alg_id = 0x05; break; default: SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_NO_CARD_SUPPORT); } } /* EC alg_id was already set */ r = piv_general_io(card, 0x87, real_alg_id, priv->key_ref, sbuf, p - sbuf, &rbuf, &rbuflen); if ( r >= 0) { body = sc_asn1_find_tag(card->ctx, rbuf, rbuflen, 0x7c, &bodylen); if (body) { tag = sc_asn1_find_tag(card->ctx, body, bodylen, 0x82, &taglen); if (tag) { memcpy(out, tag, taglen); r = taglen; } } else r = SC_ERROR_INVALID_DATA; } if (rbuf) free(rbuf); LOG_FUNC_RETURN(card->ctx, r); } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125
0
25,225
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 btpan_close_handle(btpan_conn_t *p) { BTIF_TRACE_DEBUG("btpan_close_handle : close handle %d", p->handle); p->handle = -1; p->local_role = -1; p->remote_role = -1; memset(&p->peer, 0, 6); } 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
22,151
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: UNCURL_EXPORT int32_t uncurl_set_cacert_file(struct uncurl_tls_ctx *uc_tls, char *cacert_file) { return tlss_load_cacert_file(uc_tls->tlss, cacert_file); } Commit Message: origin matching must come at str end CWE ID: CWE-352
0
11,215
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 OnConnectionTypeChanged( net::NetworkChangeNotifier::ConnectionType type) { process_host_->Send(new PpapiMsg_SetNetworkState( type != net::NetworkChangeNotifier::CONNECTION_NONE)); } Commit Message: Handle crashing Pepper plug-ins the same as crashing NPAPI plug-ins. BUG=151895 Review URL: https://chromiumcodereview.appspot.com/10956065 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158364 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
0
66
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 V8TestObject::ClearMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_clear"); test_object_v8_internal::ClearMethod(info); } 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
12,773
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 RenderFrameHostImpl::OnTextSurroundingSelectionResponse( const base::string16& content, uint32_t start_offset, uint32_t end_offset) { if (text_surrounding_selection_callback_.is_null()) return; text_surrounding_selection_callback_.Run(content, start_offset, end_offset); text_surrounding_selection_callback_.Reset(); } 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
27,094
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 RenderFrameDevToolsAgentHost::InspectElement(RenderFrameHost* frame_host, int x, int y) { FrameTreeNode* ftn = static_cast<RenderFrameHostImpl*>(frame_host)->frame_tree_node(); RenderFrameDevToolsAgentHost* host = static_cast<RenderFrameDevToolsAgentHost*>(GetOrCreateFor(ftn).get()); gfx::Point point(x, y); if (host->frame_host_) { if (RenderWidgetHostView* view = host->frame_host_->GetView()) { point = gfx::ToRoundedPoint( view->TransformRootPointToViewCoordSpace(gfx::PointF(point))); } } if (host->EnsureAgent()) host->agent_ptr_->InspectElement(point); } Commit Message: [DevTools] Do not create target handler for restricted sessions Bug: 805224 Change-Id: I08528e44e79d0a097cfe72ab4949dda538efd098 Reviewed-on: https://chromium-review.googlesource.com/988695 Reviewed-by: Pavel Feldman <pfeldman@chromium.org> Commit-Queue: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#547496} CWE ID: CWE-20
0
4,932
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 btrfs_removexattr(struct dentry *dentry, const char *name) { struct btrfs_root *root = BTRFS_I(dentry->d_inode)->root; /* * The permission on security.* and system.* is not checked * in permission(). */ if (btrfs_root_readonly(root)) return -EROFS; /* * If this is a request for a synthetic attribute in the system.* * namespace use the generic infrastructure to resolve a handler * for it via sb->s_xattr. */ if (!strncmp(name, XATTR_SYSTEM_PREFIX, XATTR_SYSTEM_PREFIX_LEN)) return generic_removexattr(dentry, name); if (!btrfs_is_valid_xattr(name)) return -EOPNOTSUPP; if (!strncmp(name, XATTR_BTRFS_PREFIX, XATTR_BTRFS_PREFIX_LEN)) return btrfs_set_prop(dentry->d_inode, name, NULL, 0, XATTR_REPLACE); return __btrfs_setxattr(NULL, dentry->d_inode, name, NULL, 0, XATTR_REPLACE); } Commit Message: Btrfs: make xattr replace operations atomic Replacing a xattr consists of doing a lookup for its existing value, delete the current value from the respective leaf, release the search path and then finally insert the new value. This leaves a time window where readers (getxattr, listxattrs) won't see any value for the xattr. Xattrs are used to store ACLs, so this has security implications. This change also fixes 2 other existing issues which were: *) Deleting the old xattr value without verifying first if the new xattr will fit in the existing leaf item (in case multiple xattrs are packed in the same item due to name hash collision); *) Returning -EEXIST when the flag XATTR_CREATE is given and the xattr doesn't exist but we have have an existing item that packs muliple xattrs with the same name hash as the input xattr. In this case we should return ENOSPC. A test case for xfstests follows soon. Thanks to Alexandre Oliva for reporting the non-atomicity of the xattr replace implementation. Reported-by: Alexandre Oliva <oliva@gnu.org> Signed-off-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: Chris Mason <clm@fb.com> CWE ID: CWE-362
0
26,243
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 xfpregs_get(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, void *kbuf, void __user *ubuf) { struct fpu *fpu = &target->thread.fpu; if (!boot_cpu_has(X86_FEATURE_FXSR)) return -ENODEV; fpu__activate_fpstate_read(fpu); fpstate_sanitize_xstate(fpu); return user_regset_copyout(&pos, &count, &kbuf, &ubuf, &fpu->state.fxsave, 0, -1); } Commit Message: x86/fpu: Don't let userspace set bogus xcomp_bv On x86, userspace can use the ptrace() or rt_sigreturn() system calls to set a task's extended state (xstate) or "FPU" registers. ptrace() can set them for another task using the PTRACE_SETREGSET request with NT_X86_XSTATE, while rt_sigreturn() can set them for the current task. In either case, registers can be set to any value, but the kernel assumes that the XSAVE area itself remains valid in the sense that the CPU can restore it. However, in the case where the kernel is using the uncompacted xstate format (which it does whenever the XSAVES instruction is unavailable), it was possible for userspace to set the xcomp_bv field in the xstate_header to an arbitrary value. However, all bits in that field are reserved in the uncompacted case, so when switching to a task with nonzero xcomp_bv, the XRSTOR instruction failed with a #GP fault. This caused the WARN_ON_FPU(err) in copy_kernel_to_xregs() to be hit. In addition, since the error is otherwise ignored, the FPU registers from the task previously executing on the CPU were leaked. Fix the bug by checking that the user-supplied value of xcomp_bv is 0 in the uncompacted case, and returning an error otherwise. The reason for validating xcomp_bv rather than simply overwriting it with 0 is that we want userspace to see an error if it (incorrectly) provides an XSAVE area in compacted format rather than in uncompacted format. Note that as before, in case of error we clear the task's FPU state. This is perhaps non-ideal, especially for PTRACE_SETREGSET; it might be better to return an error before changing anything. But it seems the "clear on error" behavior is fine for now, and it's a little tricky to do otherwise because it would mean we couldn't simply copy the full userspace state into kernel memory in one __copy_from_user(). This bug was found by syzkaller, which hit the above-mentioned WARN_ON_FPU(): WARNING: CPU: 1 PID: 0 at ./arch/x86/include/asm/fpu/internal.h:373 __switch_to+0x5b5/0x5d0 CPU: 1 PID: 0 Comm: swapper/1 Not tainted 4.13.0 #453 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011 task: ffff9ba2bc8e42c0 task.stack: ffffa78cc036c000 RIP: 0010:__switch_to+0x5b5/0x5d0 RSP: 0000:ffffa78cc08bbb88 EFLAGS: 00010082 RAX: 00000000fffffffe RBX: ffff9ba2b8bf2180 RCX: 00000000c0000100 RDX: 00000000ffffffff RSI: 000000005cb10700 RDI: ffff9ba2b8bf36c0 RBP: ffffa78cc08bbbd0 R08: 00000000929fdf46 R09: 0000000000000001 R10: 0000000000000000 R11: 0000000000000000 R12: ffff9ba2bc8e42c0 R13: 0000000000000000 R14: ffff9ba2b8bf3680 R15: ffff9ba2bf5d7b40 FS: 00007f7e5cb10700(0000) GS:ffff9ba2bf400000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: 00000000004005cc CR3: 0000000079fd5000 CR4: 00000000001406e0 Call Trace: Code: 84 00 00 00 00 00 e9 11 fd ff ff 0f ff 66 0f 1f 84 00 00 00 00 00 e9 e7 fa ff ff 0f ff 66 0f 1f 84 00 00 00 00 00 e9 c2 fa ff ff <0f> ff 66 0f 1f 84 00 00 00 00 00 e9 d4 fc ff ff 66 66 2e 0f 1f Here is a C reproducer. The expected behavior is that the program spin forever with no output. However, on a buggy kernel running on a processor with the "xsave" feature but without the "xsaves" feature (e.g. Sandy Bridge through Broadwell for Intel), within a second or two the program reports that the xmm registers were corrupted, i.e. were not restored correctly. With CONFIG_X86_DEBUG_FPU=y it also hits the above kernel warning. #define _GNU_SOURCE #include <stdbool.h> #include <inttypes.h> #include <linux/elf.h> #include <stdio.h> #include <sys/ptrace.h> #include <sys/uio.h> #include <sys/wait.h> #include <unistd.h> int main(void) { int pid = fork(); uint64_t xstate[512]; struct iovec iov = { .iov_base = xstate, .iov_len = sizeof(xstate) }; if (pid == 0) { bool tracee = true; for (int i = 0; i < sysconf(_SC_NPROCESSORS_ONLN) && tracee; i++) tracee = (fork() != 0); uint32_t xmm0[4] = { [0 ... 3] = tracee ? 0x00000000 : 0xDEADBEEF }; asm volatile(" movdqu %0, %%xmm0\n" " mov %0, %%rbx\n" "1: movdqu %%xmm0, %0\n" " mov %0, %%rax\n" " cmp %%rax, %%rbx\n" " je 1b\n" : "+m" (xmm0) : : "rax", "rbx", "xmm0"); printf("BUG: xmm registers corrupted! tracee=%d, xmm0=%08X%08X%08X%08X\n", tracee, xmm0[0], xmm0[1], xmm0[2], xmm0[3]); } else { usleep(100000); ptrace(PTRACE_ATTACH, pid, 0, 0); wait(NULL); ptrace(PTRACE_GETREGSET, pid, NT_X86_XSTATE, &iov); xstate[65] = -1; ptrace(PTRACE_SETREGSET, pid, NT_X86_XSTATE, &iov); ptrace(PTRACE_CONT, pid, 0, 0); wait(NULL); } return 1; } Note: the program only tests for the bug using the ptrace() system call. The bug can also be reproduced using the rt_sigreturn() system call, but only when called from a 32-bit program, since for 64-bit programs the kernel restores the FPU state from the signal frame by doing XRSTOR directly from userspace memory (with proper error checking). Reported-by: Dmitry Vyukov <dvyukov@google.com> Signed-off-by: Eric Biggers <ebiggers@google.com> Reviewed-by: Kees Cook <keescook@chromium.org> Reviewed-by: Rik van Riel <riel@redhat.com> Acked-by: Dave Hansen <dave.hansen@linux.intel.com> Cc: <stable@vger.kernel.org> [v3.17+] Cc: Andrew Morton <akpm@linux-foundation.org> Cc: Andy Lutomirski <luto@amacapital.net> Cc: Andy Lutomirski <luto@kernel.org> Cc: Borislav Petkov <bp@alien8.de> Cc: Eric Biggers <ebiggers3@gmail.com> Cc: Fenghua Yu <fenghua.yu@intel.com> Cc: Kevin Hao <haokexin@gmail.com> Cc: Linus Torvalds <torvalds@linux-foundation.org> Cc: Michael Halcrow <mhalcrow@google.com> Cc: Oleg Nesterov <oleg@redhat.com> Cc: Peter Zijlstra <peterz@infradead.org> Cc: Thomas Gleixner <tglx@linutronix.de> Cc: Wanpeng Li <wanpeng.li@hotmail.com> Cc: Yu-cheng Yu <yu-cheng.yu@intel.com> Cc: kernel-hardening@lists.openwall.com Fixes: 0b29643a5843 ("x86/xsaves: Change compacted format xsave area header") Link: http://lkml.kernel.org/r/20170922174156.16780-2-ebiggers3@gmail.com Link: http://lkml.kernel.org/r/20170923130016.21448-25-mingo@kernel.org Signed-off-by: Ingo Molnar <mingo@kernel.org> CWE ID: CWE-200
0
20,288
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 cgtimer_time(cgtimer_t *ts_start) { clock_gettime(CLOCK_MONOTONIC, ts_start); } Commit Message: stratum: parse_notify(): Don't die on malformed bbversion/prev_hash/nbit/ntime. Might have introduced a memory leak, don't have time to check. :( Should the other hex2bin()'s be checked? Thanks to Mick Ayzenberg <mick.dejavusecurity.com> for finding this. CWE ID: CWE-20
0
22,702
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: BluetoothOptionsHandler::BluetoothOptionsHandler() : chromeos::CrosOptionsPageUIHandler( new chromeos::SystemSettingsProvider()) { } Commit Message: Implement methods for pairing of bluetooth devices. BUG=chromium:100392,chromium:102139 TEST= Review URL: http://codereview.chromium.org/8495018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109094 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
0
23,787
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 perf_cgroup_attach(struct cgroup_taskset *tset) { struct task_struct *task; struct cgroup_subsys_state *css; cgroup_taskset_for_each(task, css, tset) task_function_call(task, __perf_cgroup_move, task); } Commit Message: perf/core: Fix concurrent sys_perf_event_open() vs. 'move_group' race Di Shen reported a race between two concurrent sys_perf_event_open() calls where both try and move the same pre-existing software group into a hardware context. The problem is exactly that described in commit: f63a8daa5812 ("perf: Fix event->ctx locking") ... where, while we wait for a ctx->mutex acquisition, the event->ctx relation can have changed under us. That very same commit failed to recognise sys_perf_event_context() as an external access vector to the events and thereby didn't apply the established locking rules correctly. So while one sys_perf_event_open() call is stuck waiting on mutex_lock_double(), the other (which owns said locks) moves the group about. So by the time the former sys_perf_event_open() acquires the locks, the context we've acquired is stale (and possibly dead). Apply the established locking rules as per perf_event_ctx_lock_nested() to the mutex_lock_double() for the 'move_group' case. This obviously means we need to validate state after we acquire the locks. Reported-by: Di Shen (Keen Lab) Tested-by: John Dias <joaodias@google.com> Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org> Cc: Alexander Shishkin <alexander.shishkin@linux.intel.com> Cc: Arnaldo Carvalho de Melo <acme@kernel.org> Cc: Arnaldo Carvalho de Melo <acme@redhat.com> Cc: Jiri Olsa <jolsa@redhat.com> Cc: Kees Cook <keescook@chromium.org> Cc: Linus Torvalds <torvalds@linux-foundation.org> Cc: Min Chong <mchong@google.com> Cc: Peter Zijlstra <peterz@infradead.org> Cc: Stephane Eranian <eranian@google.com> Cc: Thomas Gleixner <tglx@linutronix.de> Cc: Vince Weaver <vincent.weaver@maine.edu> Fixes: f63a8daa5812 ("perf: Fix event->ctx locking") Link: http://lkml.kernel.org/r/20170106131444.GZ3174@twins.programming.kicks-ass.net Signed-off-by: Ingo Molnar <mingo@kernel.org> CWE ID: CWE-362
0
23,491
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: BluetoothSocketSendFunction::BluetoothSocketSendFunction() : io_buffer_size_(0) {} Commit Message: chrome.bluetoothSocket: Fix regression in send() In https://crrev.com/c/997098, params_ was changed to a local variable, but it needs to last longer than that since net::WrappedIOBuffer may use the data after the local variable goes out of scope. This CL changed it back to be an instance variable. Bug: 851799 Change-Id: I392f8acaef4c6473d6ea4fbee7209445aa09112e Reviewed-on: https://chromium-review.googlesource.com/1103676 Reviewed-by: Toni Barzic <tbarzic@chromium.org> Commit-Queue: Sonny Sasaka <sonnysasaka@chromium.org> Cr-Commit-Position: refs/heads/master@{#568137} CWE ID: CWE-416
0
29,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: static int vm_stat_get_per_vm(void *data, u64 *val) { struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data; *val = *(ulong *)((void *)stat_data->kvm + stat_data->offset); return 0; } Commit Message: KVM: use after free in kvm_ioctl_create_device() We should move the ops->destroy(dev) after the list_del(&dev->vm_node) so that we don't use "dev" after freeing it. Fixes: a28ebea2adc4 ("KVM: Protect device ops->create and list_add with kvm->lock") Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Reviewed-by: David Hildenbrand <david@redhat.com> Signed-off-by: Radim Krčmář <rkrcmar@redhat.com> CWE ID: CWE-416
0
20,235
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 BrowserContextDestroyer::RenderProcessHostDestroyed( content::RenderProcessHost* host) { DCHECK_GT(pending_hosts_, 0U); if (--pending_hosts_ != 0) { return; } //// static if (content::RenderProcessHost::run_renderer_in_process()) { FinishDestroyContext(); } else { base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&BrowserContextDestroyer::FinishDestroyContext, base::Unretained(this))); } } Commit Message: CWE ID: CWE-20
1
19,247
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 GLES2DecoderPassthroughImpl::IsEmulatedQueryTarget(GLenum target) const { switch (target) { case GL_COMMANDS_COMPLETED_CHROMIUM: case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM: case GL_COMMANDS_ISSUED_CHROMIUM: case GL_LATENCY_QUERY_CHROMIUM: case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM: case GL_GET_ERROR_QUERY_CHROMIUM: return true; default: return false; } } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <kbr@chromium.org> Reviewed-by: Kentaro Hara <haraken@chromium.org> Reviewed-by: Geoff Lang <geofflang@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416
1
2,440
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 fslib_duplicate(const char *full_path) { assert(full_path); struct stat s; if (stat(full_path, &s) != 0 || s.st_uid != 0 || access(full_path, R_OK)) return; char *dest_dir = build_dest_dir(full_path); char *ptr = strrchr(full_path, '/'); if (!ptr) return; ptr++; if (*ptr == '\0') return; char *name; if (asprintf(&name, "%s/%s", dest_dir, ptr) == -1) errExit("asprintf"); if (stat(name, &s) == 0) { free(name); return; } free(name); if (arg_debug || arg_debug_private_lib) printf(" copying %s to private %s\n", full_path, dest_dir); sbox_run(SBOX_ROOT| SBOX_SECCOMP, 4, PATH_FCOPY, "--follow-link", full_path, dest_dir); report_duplication(full_path); lib_cnt++; } Commit Message: mount runtime seccomp files read-only (#2602) avoid creating locations in the file system that are both writable and executable (in this case for processes with euid of the user). for the same reason also remove user owned libfiles when it is not needed any more CWE ID: CWE-284
0
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: iasecc_sdo_get_tagged_data(struct sc_card *card, int sdo_tag, struct iasecc_sdo *sdo) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; unsigned char sbuf[0x100]; size_t offs = sizeof(sbuf) - 1; unsigned char rbuf[0x400]; int rv; LOG_FUNC_CALLED(ctx); sbuf[offs--] = 0x80; sbuf[offs--] = sdo_tag & 0xFF; if ((sdo_tag >> 8) & 0xFF) sbuf[offs--] = (sdo_tag >> 8) & 0xFF; sbuf[offs] = sizeof(sbuf) - offs - 1; offs--; sbuf[offs--] = sdo->sdo_ref & 0x9F; sbuf[offs--] = sdo->sdo_class | IASECC_OBJECT_REF_LOCAL; sbuf[offs--] = IASECC_SDO_TAG_HEADER; sbuf[offs] = sizeof(sbuf) - offs - 1; offs--; sbuf[offs--] = IASECC_SDO_TEMPLATE_TAG; sbuf[offs] = sizeof(sbuf) - offs - 1; offs--; sbuf[offs] = 0x4D; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xCB, 0x3F, 0xFF); apdu.data = sbuf + offs; apdu.datalen = sizeof(sbuf) - offs; apdu.lc = sizeof(sbuf) - offs; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0x100; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "SDO get data error"); rv = iasecc_sdo_parse(card, apdu.resp, apdu.resplen, sdo); LOG_TEST_RET(ctx, rv, "cannot parse SDO data"); LOG_FUNC_RETURN(ctx, rv); } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125
0
3,788
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: ps_parser_load_field( PS_Parser parser, const T1_Field field, void** objects, FT_UInt max_objects, FT_ULong* pflags ) { T1_TokenRec token; FT_Byte* cur; FT_Byte* limit; FT_UInt count; FT_UInt idx; FT_Error error; T1_FieldType type; /* this also skips leading whitespace */ ps_parser_to_token( parser, &token ); if ( !token.type ) goto Fail; count = 1; idx = 0; cur = token.start; limit = token.limit; type = field->type; /* we must detect arrays in /FontBBox */ if ( type == T1_FIELD_TYPE_BBOX ) { T1_TokenRec token2; FT_Byte* old_cur = parser->cursor; FT_Byte* old_limit = parser->limit; /* don't include delimiters */ parser->cursor = token.start + 1; parser->limit = token.limit - 1; ps_parser_to_token( parser, &token2 ); parser->cursor = old_cur; parser->limit = old_limit; if ( token2.type == T1_TOKEN_TYPE_ARRAY ) { type = T1_FIELD_TYPE_MM_BBOX; goto FieldArray; } } else if ( token.type == T1_TOKEN_TYPE_ARRAY ) { count = max_objects; FieldArray: /* if this is an array and we have no blend, an error occurs */ if ( max_objects == 0 ) goto Fail; idx = 1; /* don't include delimiters */ cur++; limit--; } for ( ; count > 0; count--, idx++ ) { FT_Byte* q = (FT_Byte*)objects[idx] + field->offset; FT_Long val; FT_String* string = NULL; skip_spaces( &cur, limit ); switch ( type ) { case T1_FIELD_TYPE_BOOL: val = ps_tobool( &cur, limit ); goto Store_Integer; case T1_FIELD_TYPE_FIXED: val = PS_Conv_ToFixed( &cur, limit, 0 ); goto Store_Integer; case T1_FIELD_TYPE_FIXED_1000: val = PS_Conv_ToFixed( &cur, limit, 3 ); goto Store_Integer; case T1_FIELD_TYPE_INTEGER: val = PS_Conv_ToInt( &cur, limit ); /* fall through */ Store_Integer: switch ( field->size ) { case (8 / FT_CHAR_BIT): *(FT_Byte*)q = (FT_Byte)val; break; case (16 / FT_CHAR_BIT): *(FT_UShort*)q = (FT_UShort)val; break; case (32 / FT_CHAR_BIT): *(FT_UInt32*)q = (FT_UInt32)val; break; default: /* for 64-bit systems */ *(FT_Long*)q = val; } break; case T1_FIELD_TYPE_STRING: case T1_FIELD_TYPE_KEY: { FT_Memory memory = parser->memory; FT_UInt len = (FT_UInt)( limit - cur ); if ( cur >= limit ) break; /* we allow both a string or a name */ /* for cases like /FontName (foo) def */ if ( token.type == T1_TOKEN_TYPE_KEY ) { /* don't include leading `/' */ len--; cur++; } else if ( token.type == T1_TOKEN_TYPE_STRING ) { /* don't include delimiting parentheses */ /* XXX we don't handle <<...>> here */ /* XXX should we convert octal escapes? */ /* if so, what encoding should we use? */ cur++; len -= 2; } else { FT_ERROR(( "ps_parser_load_field:" " expected a name or string\n" " " " but found token of type %d instead\n", token.type )); error = FT_THROW( Invalid_File_Format ); goto Exit; } /* for this to work (FT_String**)q must have been */ /* initialized to NULL */ if ( *(FT_String**)q ) { FT_TRACE0(( "ps_parser_load_field: overwriting field %s\n", field->ident )); FT_FREE( *(FT_String**)q ); *(FT_String**)q = NULL; } if ( FT_ALLOC( string, len + 1 ) ) goto Exit; FT_MEM_COPY( string, cur, len ); string[len] = 0; *(FT_String**)q = string; } break; case T1_FIELD_TYPE_BBOX: { FT_Fixed temp[4]; FT_BBox* bbox = (FT_BBox*)q; FT_Int result; result = ps_tofixedarray( &cur, limit, 4, temp, 0 ); if ( result < 4 ) { FT_ERROR(( "ps_parser_load_field:" " expected four integers in bounding box\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } bbox->xMin = FT_RoundFix( temp[0] ); bbox->yMin = FT_RoundFix( temp[1] ); bbox->xMax = FT_RoundFix( temp[2] ); bbox->yMax = FT_RoundFix( temp[3] ); } break; case T1_FIELD_TYPE_MM_BBOX: { FT_Memory memory = parser->memory; FT_Fixed* temp = NULL; FT_Int result; FT_UInt i; if ( FT_NEW_ARRAY( temp, max_objects * 4 ) ) goto Exit; for ( i = 0; i < 4; i++ ) { result = ps_tofixedarray( &cur, limit, (FT_Int)max_objects, temp + i * max_objects, 0 ); if ( result < 0 || (FT_UInt)result < max_objects ) { FT_ERROR(( "ps_parser_load_field:" " expected %d integer%s in the %s subarray\n" " " " of /FontBBox in the /Blend dictionary\n", max_objects, max_objects > 1 ? "s" : "", i == 0 ? "first" : ( i == 1 ? "second" : ( i == 2 ? "third" : "fourth" ) ) )); error = FT_THROW( Invalid_File_Format ); FT_FREE( temp ); goto Exit; } skip_spaces( &cur, limit ); } for ( i = 0; i < max_objects; i++ ) { FT_BBox* bbox = (FT_BBox*)objects[i]; bbox->xMin = FT_RoundFix( temp[i ] ); bbox->yMin = FT_RoundFix( temp[i + max_objects] ); bbox->xMax = FT_RoundFix( temp[i + 2 * max_objects] ); bbox->yMax = FT_RoundFix( temp[i + 3 * max_objects] ); } FT_FREE( temp ); } break; default: /* an error occurred */ goto Fail; } } #if 0 /* obsolete -- keep for reference */ if ( pflags ) *pflags |= 1L << field->flag_bit; #else FT_UNUSED( pflags ); #endif error = FT_Err_Ok; Exit: return error; Fail: error = FT_THROW( Invalid_File_Format ); goto Exit; } Commit Message: CWE ID: CWE-119
0
10,982
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 lo_write_bvec(struct file *file, struct bio_vec *bvec, loff_t *ppos) { struct iov_iter i; ssize_t bw; iov_iter_bvec(&i, ITER_BVEC, bvec, 1, bvec->bv_len); file_start_write(file); bw = vfs_iter_write(file, &i, ppos, 0); file_end_write(file); if (likely(bw == bvec->bv_len)) return 0; printk_ratelimited(KERN_ERR "loop: Write error at byte offset %llu, length %i.\n", (unsigned long long)*ppos, bvec->bv_len); if (bw >= 0) bw = -EIO; return bw; } Commit Message: loop: fix concurrent lo_open/lo_release 范龙飞 reports that KASAN can report a use-after-free in __lock_acquire. The reason is due to insufficient serialization in lo_release(), which will continue to use the loop device even after it has decremented the lo_refcnt to zero. In the meantime, another process can come in, open the loop device again as it is being shut down. Confusion ensues. Reported-by: 范龙飞 <long7573@126.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> Signed-off-by: Jens Axboe <axboe@kernel.dk> CWE ID: CWE-416
0
16,162
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 tipc_sk_create(struct net *net, struct socket *sock, int protocol, int kern) { const struct proto_ops *ops; socket_state state; struct sock *sk; struct tipc_port *tp_ptr; /* Validate arguments */ if (unlikely(protocol != 0)) return -EPROTONOSUPPORT; switch (sock->type) { case SOCK_STREAM: ops = &stream_ops; state = SS_UNCONNECTED; break; case SOCK_SEQPACKET: ops = &packet_ops; state = SS_UNCONNECTED; break; case SOCK_DGRAM: case SOCK_RDM: ops = &msg_ops; state = SS_READY; break; default: return -EPROTOTYPE; } /* Allocate socket's protocol area */ if (!kern) sk = sk_alloc(net, AF_TIPC, GFP_KERNEL, &tipc_proto); else sk = sk_alloc(net, AF_TIPC, GFP_KERNEL, &tipc_proto_kern); if (sk == NULL) return -ENOMEM; /* Allocate TIPC port for socket to use */ tp_ptr = tipc_createport(sk, &dispatch, &wakeupdispatch, TIPC_LOW_IMPORTANCE); if (unlikely(!tp_ptr)) { sk_free(sk); return -ENOMEM; } /* Finish initializing socket data structures */ sock->ops = ops; sock->state = state; sock_init_data(sock, sk); sk->sk_backlog_rcv = backlog_rcv; sk->sk_rcvbuf = sysctl_tipc_rmem[1]; sk->sk_data_ready = tipc_data_ready; sk->sk_write_space = tipc_write_space; tipc_sk(sk)->p = tp_ptr; tipc_sk(sk)->conn_timeout = CONN_TIMEOUT_DEFAULT; spin_unlock_bh(tp_ptr->lock); if (sock->state == SS_READY) { tipc_set_portunreturnable(tp_ptr->ref, 1); if (sock->type == SOCK_DGRAM) tipc_set_portunreliable(tp_ptr->ref, 1); } return 0; } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <davem@davemloft.net> Suggested-by: Eric Dumazet <eric.dumazet@gmail.com> Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-20
0
3,367
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 AudioOutputDevice::OnStreamCreated( base::SharedMemoryHandle handle, base::SyncSocket::Handle socket_handle, int length) { DCHECK(message_loop()->BelongsToCurrentThread()); #if defined(OS_WIN) DCHECK(handle); DCHECK(socket_handle); #else DCHECK_GE(handle.fd, 0); DCHECK_GE(socket_handle, 0); #endif DCHECK(stream_id_); if (!audio_thread_.get()) return; DCHECK(audio_thread_->IsStopped()); audio_callback_.reset(new AudioOutputDevice::AudioThreadCallback( audio_parameters_, input_channels_, handle, length, callback_)); audio_thread_->Start( audio_callback_.get(), socket_handle, "AudioOutputDevice"); is_started_ = true; if (play_on_start_) PlayOnIOThread(); } Commit Message: Revert r157378 as it caused WebRTC to dereference null pointers when restarting a call. I've kept my unit test changes intact but disabled until I get a proper fix. BUG=147499,150805 TBR=henrika Review URL: https://codereview.chromium.org/10946040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@157626 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
1
8,590
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 SkiaOutputSurfaceImpl::SetNeedsSwapSizeNotifications( bool needs_swap_size_notifications) { needs_swap_size_notifications_ = needs_swap_size_notifications; } Commit Message: SkiaRenderer: Support changing color space SkiaOutputSurfaceImpl did not handle the color space changing after it was created previously. The SkSurfaceCharacterization color space was only set during the first time Reshape() ran when the charactization is returned from the GPU thread. If the color space was changed later the SkSurface and SkDDL color spaces no longer matched and draw failed. Bug: 1009452 Change-Id: Ib6d2083efc7e7eb6f94782342e92a809b69d6fdc Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1841811 Reviewed-by: Peng Huang <penghuang@chromium.org> Commit-Queue: kylechar <kylechar@chromium.org> Cr-Commit-Position: refs/heads/master@{#702946} CWE ID: CWE-704
0
778
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 RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { ssize_t quantum; quantum=PSDQuantum(count)+12; if ((quantum >= 12) && (quantum < (ssize_t) length)) { if ((q+quantum < (datum+length-16))) (void) memmove(q,q+quantum,length-quantum-(q-datum)); SetStringInfoLength(bim_profile,length-quantum); } break; } p+=count; if ((count & 0x01) != 0) p++; } } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1451 CWE ID: CWE-399
0
20,816
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 __net_exit packet_net_exit(struct net *net) { remove_proc_entry("packet", net->proc_net); } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <davem@davemloft.net> Suggested-by: Eric Dumazet <eric.dumazet@gmail.com> Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-20
0
11,697
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 ContentSecurityPolicy::ShouldBypassContentSecurityPolicy( const KURL& url, ExecutionContext* execution_context, SchemeRegistry::PolicyAreas area) { bool should_bypass_csp; if (SecurityOrigin::ShouldUseInnerURL(url)) { should_bypass_csp = SchemeRegistry::SchemeShouldBypassContentSecurityPolicy( SecurityOrigin::ExtractInnerURL(url).Protocol(), area); if (should_bypass_csp) { UseCounter::Count(execution_context, WebFeature::kInnerSchemeBypassesCSP); } } else { should_bypass_csp = SchemeRegistry::SchemeShouldBypassContentSecurityPolicy( url.Protocol(), area); } if (should_bypass_csp) { UseCounter::Count(execution_context, WebFeature::kSchemeBypassesCSP); } return should_bypass_csp; } Commit Message: Inherit the navigation initiator when navigating instead of the parent/opener Spec PR: https://github.com/w3c/webappsec-csp/pull/358 Bug: 905301, 894228, 836148 Change-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a Reviewed-on: https://chromium-review.googlesource.com/c/1314633 Commit-Queue: Andy Paicu <andypaicu@chromium.org> Reviewed-by: Mike West <mkwst@chromium.org> Cr-Commit-Position: refs/heads/master@{#610850} CWE ID: CWE-20
0
12,189
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 apply_vma_lock_flags(unsigned long start, size_t len, vm_flags_t flags) { unsigned long nstart, end, tmp; struct vm_area_struct * vma, * prev; int error; VM_BUG_ON(offset_in_page(start)); VM_BUG_ON(len != PAGE_ALIGN(len)); end = start + len; if (end < start) return -EINVAL; if (end == start) return 0; vma = find_vma(current->mm, start); if (!vma || vma->vm_start > start) return -ENOMEM; prev = vma->vm_prev; if (start > vma->vm_start) prev = vma; for (nstart = start ; ; ) { vm_flags_t newflags = vma->vm_flags & VM_LOCKED_CLEAR_MASK; newflags |= flags; /* Here we know that vma->vm_start <= nstart < vma->vm_end. */ tmp = vma->vm_end; if (tmp > end) tmp = end; error = mlock_fixup(vma, &prev, nstart, tmp, newflags); if (error) break; nstart = tmp; if (nstart < prev->vm_end) nstart = prev->vm_end; if (nstart >= end) break; vma = prev->vm_next; if (!vma || vma->vm_start != nstart) { error = -ENOMEM; break; } } return error; } Commit Message: mlock: fix mlock count can not decrease in race condition Kefeng reported that when running the follow test, the mlock count in meminfo will increase permanently: [1] testcase linux:~ # cat test_mlockal grep Mlocked /proc/meminfo for j in `seq 0 10` do for i in `seq 4 15` do ./p_mlockall >> log & done sleep 0.2 done # wait some time to let mlock counter decrease and 5s may not enough sleep 5 grep Mlocked /proc/meminfo linux:~ # cat p_mlockall.c #include <sys/mman.h> #include <stdlib.h> #include <stdio.h> #define SPACE_LEN 4096 int main(int argc, char ** argv) { int ret; void *adr = malloc(SPACE_LEN); if (!adr) return -1; ret = mlockall(MCL_CURRENT | MCL_FUTURE); printf("mlcokall ret = %d\n", ret); ret = munlockall(); printf("munlcokall ret = %d\n", ret); free(adr); return 0; } In __munlock_pagevec() we should decrement NR_MLOCK for each page where we clear the PageMlocked flag. Commit 1ebb7cc6a583 ("mm: munlock: batch NR_MLOCK zone state updates") has introduced a bug where we don't decrement NR_MLOCK for pages where we clear the flag, but fail to isolate them from the lru list (e.g. when the pages are on some other cpu's percpu pagevec). Since PageMlocked stays cleared, the NR_MLOCK accounting gets permanently disrupted by this. Fix it by counting the number of page whose PageMlock flag is cleared. Fixes: 1ebb7cc6a583 (" mm: munlock: batch NR_MLOCK zone state updates") Link: http://lkml.kernel.org/r/1495678405-54569-1-git-send-email-xieyisheng1@huawei.com Signed-off-by: Yisheng Xie <xieyisheng1@huawei.com> Reported-by: Kefeng Wang <wangkefeng.wang@huawei.com> Tested-by: Kefeng Wang <wangkefeng.wang@huawei.com> Cc: Vlastimil Babka <vbabka@suse.cz> Cc: Joern Engel <joern@logfs.org> Cc: Mel Gorman <mgorman@suse.de> Cc: Michel Lespinasse <walken@google.com> Cc: Hugh Dickins <hughd@google.com> Cc: Rik van Riel <riel@redhat.com> Cc: Johannes Weiner <hannes@cmpxchg.org> Cc: Michal Hocko <mhocko@suse.cz> Cc: Xishi Qiu <qiuxishi@huawei.com> Cc: zhongjiang <zhongjiang@huawei.com> Cc: Hanjun Guo <guohanjun@huawei.com> Cc: <stable@vger.kernel.org> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-20
0
14,838
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: svcauth_gss_set_svc_name(gss_name_t name) { OM_uint32 maj_stat, min_stat; log_debug("in svcauth_gss_set_svc_name()"); if (svcauth_gss_name != NULL) { maj_stat = gss_release_name(&min_stat, &svcauth_gss_name); if (maj_stat != GSS_S_COMPLETE) { log_status("gss_release_name", maj_stat, min_stat); return (FALSE); } svcauth_gss_name = NULL; } if (svcauth_gss_name == GSS_C_NO_NAME) return (TRUE); maj_stat = gss_duplicate_name(&min_stat, name, &svcauth_gss_name); if (maj_stat != GSS_S_COMPLETE) { log_status("gss_duplicate_name", maj_stat, min_stat); return (FALSE); } return (TRUE); } Commit Message: Fix gssrpc data leakage [CVE-2014-9423] [MITKRB5-SA-2015-001] In svcauth_gss_accept_sec_context(), do not copy bytes from the union context into the handle field we send to the client. We do not use this handle field, so just supply a fixed string of "xxxx". In gss_union_ctx_id_struct, remove the unused "interposer" field which was causing part of the union context to remain uninitialized. ticket: 8058 (new) target_version: 1.13.1 tags: pullup CWE ID: CWE-200
0
15,240
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: OMX_ERRORTYPE omx_vdec::set_parameter(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_INDEXTYPE paramIndex, OMX_IN OMX_PTR paramData) { OMX_ERRORTYPE eRet = OMX_ErrorNone; int ret=0; struct v4l2_format fmt; #ifdef _ANDROID_ char property_value[PROPERTY_VALUE_MAX] = {0}; #endif if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("Set Param in Invalid State"); return OMX_ErrorInvalidState; } if (paramData == NULL) { DEBUG_PRINT_ERROR("Get Param in Invalid paramData"); return OMX_ErrorBadParameter; } if ((m_state != OMX_StateLoaded) && BITMASK_ABSENT(&m_flags,OMX_COMPONENT_OUTPUT_ENABLE_PENDING) && (m_out_bEnabled == OMX_TRUE) && BITMASK_ABSENT(&m_flags, OMX_COMPONENT_INPUT_ENABLE_PENDING) && (m_inp_bEnabled == OMX_TRUE)) { DEBUG_PRINT_ERROR("Set Param in Invalid State"); return OMX_ErrorIncorrectStateOperation; } switch ((unsigned long)paramIndex) { case OMX_IndexParamPortDefinition: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_PORTDEFINITIONTYPE); OMX_PARAM_PORTDEFINITIONTYPE *portDefn; portDefn = (OMX_PARAM_PORTDEFINITIONTYPE *) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPortDefinition H= %d, W = %d", (int)portDefn->format.video.nFrameHeight, (int)portDefn->format.video.nFrameWidth); if (OMX_DirOutput == portDefn->eDir) { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPortDefinition OP port"); bool port_format_changed = false; m_display_id = portDefn->format.video.pNativeWindow; unsigned int buffer_size; /* update output port resolution with client supplied dimensions in case scaling is enabled, else it follows input resolution set */ if (is_down_scalar_enabled) { DEBUG_PRINT_LOW("SetParam OP: WxH(%u x %u)", (unsigned int)portDefn->format.video.nFrameWidth, (unsigned int)portDefn->format.video.nFrameHeight); if (portDefn->format.video.nFrameHeight != 0x0 && portDefn->format.video.nFrameWidth != 0x0) { memset(&fmt, 0x0, sizeof(struct v4l2_format)); fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; fmt.fmt.pix_mp.pixelformat = capture_capability; ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_G_FMT, &fmt); if (ret) { DEBUG_PRINT_ERROR("Get Resolution failed"); eRet = OMX_ErrorHardware; break; } if ((portDefn->format.video.nFrameHeight != (unsigned int)fmt.fmt.pix_mp.height) || (portDefn->format.video.nFrameWidth != (unsigned int)fmt.fmt.pix_mp.width)) { port_format_changed = true; } update_resolution(portDefn->format.video.nFrameWidth, portDefn->format.video.nFrameHeight, portDefn->format.video.nFrameWidth, portDefn->format.video.nFrameHeight); /* set crop info */ rectangle.nLeft = 0; rectangle.nTop = 0; rectangle.nWidth = portDefn->format.video.nFrameWidth; rectangle.nHeight = portDefn->format.video.nFrameHeight; eRet = is_video_session_supported(); if (eRet) break; memset(&fmt, 0x0, sizeof(struct v4l2_format)); fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; fmt.fmt.pix_mp.height = drv_ctx.video_resolution.frame_height; fmt.fmt.pix_mp.width = drv_ctx.video_resolution.frame_width; fmt.fmt.pix_mp.pixelformat = capture_capability; DEBUG_PRINT_LOW("fmt.fmt.pix_mp.height = %d , fmt.fmt.pix_mp.width = %d", fmt.fmt.pix_mp.height, fmt.fmt.pix_mp.width); ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_FMT, &fmt); if (ret) { DEBUG_PRINT_ERROR("Set Resolution failed"); eRet = OMX_ErrorUnsupportedSetting; } else eRet = get_buffer_req(&drv_ctx.op_buf); } if (eRet) { break; } if (secure_mode) { struct v4l2_control control; control.id = V4L2_CID_MPEG_VIDC_VIDEO_SECURE_SCALING_THRESHOLD; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_G_CTRL, &control) < 0) { DEBUG_PRINT_ERROR("Failed getting secure scaling threshold : %d, id was : %x", errno, control.id); eRet = OMX_ErrorHardware; } else { /* This is a workaround for a bug in fw which uses stride * and slice instead of width and height to check against * the threshold. */ OMX_U32 stride, slice; if (drv_ctx.output_format == VDEC_YUV_FORMAT_NV12) { stride = VENUS_Y_STRIDE(COLOR_FMT_NV12, portDefn->format.video.nFrameWidth); slice = VENUS_Y_SCANLINES(COLOR_FMT_NV12, portDefn->format.video.nFrameHeight); } else { stride = portDefn->format.video.nFrameWidth; slice = portDefn->format.video.nFrameHeight; } DEBUG_PRINT_LOW("Stride is %d, slice is %d, sxs is %d\n", stride, slice, stride * slice); DEBUG_PRINT_LOW("Threshold value is %d\n", control.value); if (stride * slice <= (OMX_U32)control.value) { secure_scaling_to_non_secure_opb = true; DEBUG_PRINT_HIGH("Enabling secure scalar out of CPZ"); control.id = V4L2_CID_MPEG_VIDC_VIDEO_NON_SECURE_OUTPUT2; control.value = 1; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control) < 0) { DEBUG_PRINT_ERROR("Enabling non-secure output2 failed"); eRet = OMX_ErrorUnsupportedSetting; } } } } } if (eRet) { break; } if (!client_buffers.get_buffer_req(buffer_size)) { DEBUG_PRINT_ERROR("Error in getting buffer requirements"); eRet = OMX_ErrorBadParameter; } else if (!port_format_changed) { if ( portDefn->nBufferCountActual >= drv_ctx.op_buf.mincount && portDefn->nBufferSize >= drv_ctx.op_buf.buffer_size ) { drv_ctx.op_buf.actualcount = portDefn->nBufferCountActual; drv_ctx.op_buf.buffer_size = portDefn->nBufferSize; drv_ctx.extradata_info.count = drv_ctx.op_buf.actualcount; drv_ctx.extradata_info.size = drv_ctx.extradata_info.count * drv_ctx.extradata_info.buffer_size; eRet = set_buffer_req(&drv_ctx.op_buf); if (eRet == OMX_ErrorNone) m_port_def = *portDefn; } else { DEBUG_PRINT_ERROR("ERROR: OP Requirements(#%d: %u) Requested(#%u: %u)", drv_ctx.op_buf.mincount, (unsigned int)drv_ctx.op_buf.buffer_size, (unsigned int)portDefn->nBufferCountActual, (unsigned int)portDefn->nBufferSize); eRet = OMX_ErrorBadParameter; } } } else if (OMX_DirInput == portDefn->eDir) { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPortDefinition IP port"); bool port_format_changed = false; if ((portDefn->format.video.xFramerate >> 16) > 0 && (portDefn->format.video.xFramerate >> 16) <= MAX_SUPPORTED_FPS) { DEBUG_PRINT_HIGH("set_parameter: frame rate set by omx client : %u", (unsigned int)portDefn->format.video.xFramerate >> 16); Q16ToFraction(portDefn->format.video.xFramerate, drv_ctx.frame_rate.fps_numerator, drv_ctx.frame_rate.fps_denominator); if (!drv_ctx.frame_rate.fps_numerator) { DEBUG_PRINT_ERROR("Numerator is zero setting to 30"); drv_ctx.frame_rate.fps_numerator = 30; } if (drv_ctx.frame_rate.fps_denominator) drv_ctx.frame_rate.fps_numerator = (int) drv_ctx.frame_rate.fps_numerator / drv_ctx.frame_rate.fps_denominator; drv_ctx.frame_rate.fps_denominator = 1; frm_int = drv_ctx.frame_rate.fps_denominator * 1e6 / drv_ctx.frame_rate.fps_numerator; DEBUG_PRINT_LOW("set_parameter: frm_int(%u) fps(%.2f)", (unsigned int)frm_int, drv_ctx.frame_rate.fps_numerator / (float)drv_ctx.frame_rate.fps_denominator); struct v4l2_outputparm oparm; /*XXX: we're providing timing info as seconds per frame rather than frames * per second.*/ oparm.timeperframe.numerator = drv_ctx.frame_rate.fps_denominator; oparm.timeperframe.denominator = drv_ctx.frame_rate.fps_numerator; struct v4l2_streamparm sparm; sparm.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; sparm.parm.output = oparm; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_PARM, &sparm)) { DEBUG_PRINT_ERROR("Unable to convey fps info to driver, performance might be affected"); eRet = OMX_ErrorHardware; break; } } if (drv_ctx.video_resolution.frame_height != portDefn->format.video.nFrameHeight || drv_ctx.video_resolution.frame_width != portDefn->format.video.nFrameWidth) { DEBUG_PRINT_LOW("SetParam IP: WxH(%u x %u)", (unsigned int)portDefn->format.video.nFrameWidth, (unsigned int)portDefn->format.video.nFrameHeight); port_format_changed = true; OMX_U32 frameWidth = portDefn->format.video.nFrameWidth; OMX_U32 frameHeight = portDefn->format.video.nFrameHeight; if (frameHeight != 0x0 && frameWidth != 0x0) { if (m_smoothstreaming_mode && ((frameWidth * frameHeight) < (m_smoothstreaming_width * m_smoothstreaming_height))) { frameWidth = m_smoothstreaming_width; frameHeight = m_smoothstreaming_height; DEBUG_PRINT_LOW("NOTE: Setting resolution %u x %u " "for adaptive-playback/smooth-streaming", (unsigned int)frameWidth, (unsigned int)frameHeight); } update_resolution(frameWidth, frameHeight, frameWidth, frameHeight); eRet = is_video_session_supported(); if (eRet) break; memset(&fmt, 0x0, sizeof(struct v4l2_format)); fmt.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; fmt.fmt.pix_mp.height = drv_ctx.video_resolution.frame_height; fmt.fmt.pix_mp.width = drv_ctx.video_resolution.frame_width; fmt.fmt.pix_mp.pixelformat = output_capability; DEBUG_PRINT_LOW("fmt.fmt.pix_mp.height = %d , fmt.fmt.pix_mp.width = %d",fmt.fmt.pix_mp.height,fmt.fmt.pix_mp.width); ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_FMT, &fmt); if (ret) { DEBUG_PRINT_ERROR("Set Resolution failed"); eRet = OMX_ErrorUnsupportedSetting; } else { if (!is_down_scalar_enabled) eRet = get_buffer_req(&drv_ctx.op_buf); } } } if (m_custom_buffersize.input_buffersize && (portDefn->nBufferSize > m_custom_buffersize.input_buffersize)) { DEBUG_PRINT_ERROR("ERROR: Custom buffer size set by client: %d, trying to set: %d", m_custom_buffersize.input_buffersize, portDefn->nBufferSize); eRet = OMX_ErrorBadParameter; break; } if (portDefn->nBufferCountActual >= drv_ctx.ip_buf.mincount || portDefn->nBufferSize != drv_ctx.ip_buf.buffer_size) { port_format_changed = true; vdec_allocatorproperty *buffer_prop = &drv_ctx.ip_buf; drv_ctx.ip_buf.actualcount = portDefn->nBufferCountActual; drv_ctx.ip_buf.buffer_size = (portDefn->nBufferSize + buffer_prop->alignment - 1) & (~(buffer_prop->alignment - 1)); eRet = set_buffer_req(buffer_prop); } if (false == port_format_changed) { DEBUG_PRINT_ERROR("ERROR: IP Requirements(#%d: %u) Requested(#%u: %u)", drv_ctx.ip_buf.mincount, (unsigned int)drv_ctx.ip_buf.buffer_size, (unsigned int)portDefn->nBufferCountActual, (unsigned int)portDefn->nBufferSize); eRet = OMX_ErrorBadParameter; } } else if (portDefn->eDir == OMX_DirMax) { DEBUG_PRINT_ERROR(" Set_parameter: Bad Port idx %d", (int)portDefn->nPortIndex); eRet = OMX_ErrorBadPortIndex; } } break; case OMX_IndexParamVideoPortFormat: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_PORTFORMATTYPE); OMX_VIDEO_PARAM_PORTFORMATTYPE *portFmt = (OMX_VIDEO_PARAM_PORTFORMATTYPE *)paramData; int ret=0; struct v4l2_format fmt; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoPortFormat 0x%x, port: %u", portFmt->eColorFormat, (unsigned int)portFmt->nPortIndex); memset(&fmt, 0x0, sizeof(struct v4l2_format)); if (1 == portFmt->nPortIndex) { fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; fmt.fmt.pix_mp.height = drv_ctx.video_resolution.frame_height; fmt.fmt.pix_mp.width = drv_ctx.video_resolution.frame_width; fmt.fmt.pix_mp.pixelformat = capture_capability; enum vdec_output_fromat op_format; if (portFmt->eColorFormat == (OMX_COLOR_FORMATTYPE) QOMX_COLOR_FORMATYUV420PackedSemiPlanar32m || portFmt->eColorFormat == (OMX_COLOR_FORMATTYPE) QOMX_COLOR_FORMATYUV420PackedSemiPlanar32mMultiView || portFmt->eColorFormat == OMX_COLOR_FormatYUV420Planar || portFmt->eColorFormat == OMX_COLOR_FormatYUV420SemiPlanar) op_format = (enum vdec_output_fromat)VDEC_YUV_FORMAT_NV12; else eRet = OMX_ErrorBadParameter; if (eRet == OMX_ErrorNone) { drv_ctx.output_format = op_format; ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_FMT, &fmt); if (ret) { DEBUG_PRINT_ERROR("Set output format failed"); eRet = OMX_ErrorUnsupportedSetting; /*TODO: How to handle this case */ } else { eRet = get_buffer_req(&drv_ctx.op_buf); } } if (eRet == OMX_ErrorNone) { if (!client_buffers.set_color_format(portFmt->eColorFormat)) { DEBUG_PRINT_ERROR("Set color format failed"); eRet = OMX_ErrorBadParameter; } } } } break; case OMX_QcomIndexPortDefn: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_PARAM_PORTDEFINITIONTYPE); OMX_QCOM_PARAM_PORTDEFINITIONTYPE *portFmt = (OMX_QCOM_PARAM_PORTDEFINITIONTYPE *) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexQcomParamPortDefinitionType %u", (unsigned int)portFmt->nFramePackingFormat); /* Input port */ if (portFmt->nPortIndex == 0) { if (portFmt->nFramePackingFormat == OMX_QCOM_FramePacking_Arbitrary) { if (secure_mode) { arbitrary_bytes = false; DEBUG_PRINT_ERROR("setparameter: cannot set to arbitary bytes mode in secure session"); eRet = OMX_ErrorUnsupportedSetting; } else { arbitrary_bytes = true; } } else if (portFmt->nFramePackingFormat == OMX_QCOM_FramePacking_OnlyOneCompleteFrame) { arbitrary_bytes = false; #ifdef _ANDROID_ property_get("vidc.dec.debug.arbitrarybytes.mode", property_value, "0"); if (atoi(property_value)) { DEBUG_PRINT_HIGH("arbitrary_bytes enabled via property command"); arbitrary_bytes = true; } #endif } else { DEBUG_PRINT_ERROR("Setparameter: unknown FramePacking format %u", (unsigned int)portFmt->nFramePackingFormat); eRet = OMX_ErrorUnsupportedSetting; } } else if (portFmt->nPortIndex == OMX_CORE_OUTPUT_PORT_INDEX) { DEBUG_PRINT_HIGH("set_parameter: OMX_IndexQcomParamPortDefinitionType OP Port"); if ( (portFmt->nMemRegion > OMX_QCOM_MemRegionInvalid && portFmt->nMemRegion < OMX_QCOM_MemRegionMax) && portFmt->nCacheAttr == OMX_QCOM_CacheAttrNone) { m_out_mem_region_smi = OMX_TRUE; if ((m_out_mem_region_smi && m_out_pvt_entry_pmem)) { DEBUG_PRINT_HIGH("set_parameter: OMX_IndexQcomParamPortDefinitionType OP Port: out pmem set"); m_use_output_pmem = OMX_TRUE; } } } } break; case OMX_IndexParamStandardComponentRole: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_COMPONENTROLETYPE); OMX_PARAM_COMPONENTROLETYPE *comp_role; comp_role = (OMX_PARAM_COMPONENTROLETYPE *) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamStandardComponentRole %s", comp_role->cRole); if ((m_state == OMX_StateLoaded)&& !BITMASK_PRESENT(&m_flags,OMX_COMPONENT_IDLE_PENDING)) { DEBUG_PRINT_LOW("Set Parameter called in valid state"); } else { DEBUG_PRINT_ERROR("Set Parameter called in Invalid State"); return OMX_ErrorIncorrectStateOperation; } if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.avc",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((char*)comp_role->cRole,"video_decoder.avc",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_decoder.avc",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.mvc", OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((char*)comp_role->cRole, "video_decoder.mvc", OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole, "video_decoder.mvc", OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.mpeg4",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_decoder.mpeg4",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_decoder.mpeg4",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet = OMX_ErrorUnsupportedSetting; } } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.h263",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_decoder.h263",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_decoder.h263",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.mpeg2",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_decoder.mpeg2",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_decoder.mpeg2",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet = OMX_ErrorUnsupportedSetting; } } else if ((!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.divx",OMX_MAX_STRINGNAME_SIZE)) || (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.divx311", OMX_MAX_STRINGNAME_SIZE)) || (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.divx4", OMX_MAX_STRINGNAME_SIZE)) ) { if (!strncmp((const char*)comp_role->cRole,"video_decoder.divx",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_decoder.divx",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if ( (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.vc1",OMX_MAX_STRINGNAME_SIZE)) || (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.wmv",OMX_MAX_STRINGNAME_SIZE)) ) { if (!strncmp((const char*)comp_role->cRole,"video_decoder.vc1",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_decoder.vc1",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.vp8",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_decoder.vp8",OMX_MAX_STRINGNAME_SIZE) || (!strncmp((const char*)comp_role->cRole,"video_decoder.vpx",OMX_MAX_STRINGNAME_SIZE))) { strlcpy((char*)m_cRole,"video_decoder.vp8",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet = OMX_ErrorUnsupportedSetting; } } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.hevc", OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole, "video_decoder.hevc", OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole, "video_decoder.hevc", OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet = OMX_ErrorUnsupportedSetting; } } else { DEBUG_PRINT_ERROR("Setparameter: unknown param %s", drv_ctx.kind); eRet = OMX_ErrorInvalidComponentName; } break; } case OMX_IndexParamPriorityMgmt: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_PRIORITYMGMTTYPE); if (m_state != OMX_StateLoaded) { DEBUG_PRINT_ERROR("Set Parameter called in Invalid State"); return OMX_ErrorIncorrectStateOperation; } OMX_PRIORITYMGMTTYPE *priorityMgmtype = (OMX_PRIORITYMGMTTYPE*) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPriorityMgmt %u", (unsigned int)priorityMgmtype->nGroupID); DEBUG_PRINT_LOW("set_parameter: priorityMgmtype %u", (unsigned int)priorityMgmtype->nGroupPriority); m_priority_mgm.nGroupID = priorityMgmtype->nGroupID; m_priority_mgm.nGroupPriority = priorityMgmtype->nGroupPriority; break; } case OMX_IndexParamCompBufferSupplier: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_BUFFERSUPPLIERTYPE); OMX_PARAM_BUFFERSUPPLIERTYPE *bufferSupplierType = (OMX_PARAM_BUFFERSUPPLIERTYPE*) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamCompBufferSupplier %d", bufferSupplierType->eBufferSupplier); if (bufferSupplierType->nPortIndex == 0 || bufferSupplierType->nPortIndex ==1) m_buffer_supplier.eBufferSupplier = bufferSupplierType->eBufferSupplier; else eRet = OMX_ErrorBadPortIndex; break; } case OMX_IndexParamVideoAvc: { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoAvc %d", paramIndex); break; } case (OMX_INDEXTYPE)QOMX_IndexParamVideoMvc: { DEBUG_PRINT_LOW("set_parameter: QOMX_IndexParamVideoMvc %d", paramIndex); break; } case OMX_IndexParamVideoH263: { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoH263 %d", paramIndex); break; } case OMX_IndexParamVideoMpeg4: { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoMpeg4 %d", paramIndex); break; } case OMX_IndexParamVideoMpeg2: { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoMpeg2 %d", paramIndex); break; } case OMX_QcomIndexParamVideoDecoderPictureOrder: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_VIDEO_DECODER_PICTURE_ORDER); QOMX_VIDEO_DECODER_PICTURE_ORDER *pictureOrder = (QOMX_VIDEO_DECODER_PICTURE_ORDER *)paramData; struct v4l2_control control; int pic_order,rc=0; DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexParamVideoDecoderPictureOrder %d", pictureOrder->eOutputPictureOrder); if (pictureOrder->eOutputPictureOrder == QOMX_VIDEO_DISPLAY_ORDER) { pic_order = V4L2_MPEG_VIDC_VIDEO_OUTPUT_ORDER_DISPLAY; } else if (pictureOrder->eOutputPictureOrder == QOMX_VIDEO_DECODE_ORDER) { pic_order = V4L2_MPEG_VIDC_VIDEO_OUTPUT_ORDER_DECODE; time_stamp_dts.set_timestamp_reorder_mode(false); } else eRet = OMX_ErrorBadParameter; if (eRet == OMX_ErrorNone) { control.id = V4L2_CID_MPEG_VIDC_VIDEO_OUTPUT_ORDER; control.value = pic_order; rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control); if (rc) { DEBUG_PRINT_ERROR("Set picture order failed"); eRet = OMX_ErrorUnsupportedSetting; } } break; } case OMX_QcomIndexParamConcealMBMapExtraData: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(VDEC_EXTRADATA_MB_ERROR_MAP, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamFrameInfoExtraData: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_FRAMEINFO_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_ExtraDataFrameDimension: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_FRAMEDIMENSION_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamInterlaceExtraData: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_INTERLACE_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamH264TimeInfo: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_TIMEINFO_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamVideoFramePackingExtradata: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_FRAMEPACK_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamVideoQPExtraData: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_QP_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamVideoInputBitsInfoExtraData: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_BITSINFO_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexEnableExtnUserData: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_EXTNUSER_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamMpeg2SeqDispExtraData: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_MPEG2SEQDISP_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamVideoDivx: { QOMX_VIDEO_PARAM_DIVXTYPE* divXType = (QOMX_VIDEO_PARAM_DIVXTYPE *) paramData; } break; case OMX_QcomIndexPlatformPvt: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_PLATFORMPRIVATE_EXTN); DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexPlatformPvt OP Port"); OMX_QCOM_PLATFORMPRIVATE_EXTN* entryType = (OMX_QCOM_PLATFORMPRIVATE_EXTN *) paramData; if (entryType->type != OMX_QCOM_PLATFORM_PRIVATE_PMEM) { DEBUG_PRINT_HIGH("set_parameter: Platform Private entry type (%d) not supported.", entryType->type); eRet = OMX_ErrorUnsupportedSetting; } else { m_out_pvt_entry_pmem = OMX_TRUE; if ((m_out_mem_region_smi && m_out_pvt_entry_pmem)) { DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexPlatformPvt OP Port: out pmem set"); m_use_output_pmem = OMX_TRUE; } } } break; case OMX_QcomIndexParamVideoSyncFrameDecodingMode: { DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexParamVideoSyncFrameDecodingMode"); DEBUG_PRINT_HIGH("set idr only decoding for thumbnail mode"); struct v4l2_control control; int rc; drv_ctx.idr_only_decoding = 1; control.id = V4L2_CID_MPEG_VIDC_VIDEO_OUTPUT_ORDER; control.value = V4L2_MPEG_VIDC_VIDEO_OUTPUT_ORDER_DECODE; rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control); if (rc) { DEBUG_PRINT_ERROR("Set picture order failed"); eRet = OMX_ErrorUnsupportedSetting; } else { control.id = V4L2_CID_MPEG_VIDC_VIDEO_SYNC_FRAME_DECODE; control.value = V4L2_MPEG_VIDC_VIDEO_SYNC_FRAME_DECODE_ENABLE; rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control); if (rc) { DEBUG_PRINT_ERROR("Sync frame setting failed"); eRet = OMX_ErrorUnsupportedSetting; } /*Setting sync frame decoding on driver might change buffer * requirements so update them here*/ if (get_buffer_req(&drv_ctx.ip_buf)) { DEBUG_PRINT_ERROR("Sync frame setting failed: falied to get buffer i/p requirements"); eRet = OMX_ErrorUnsupportedSetting; } if (get_buffer_req(&drv_ctx.op_buf)) { DEBUG_PRINT_ERROR("Sync frame setting failed: falied to get buffer o/p requirements"); eRet = OMX_ErrorUnsupportedSetting; } } } break; case OMX_QcomIndexParamIndexExtraDataType: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_INDEXEXTRADATATYPE); QOMX_INDEXEXTRADATATYPE *extradataIndexType = (QOMX_INDEXEXTRADATATYPE *) paramData; if ((extradataIndexType->nIndex == OMX_IndexParamPortDefinition) && (extradataIndexType->bEnabled == OMX_TRUE) && (extradataIndexType->nPortIndex == 1)) { DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexParamIndexExtraDataType SmoothStreaming"); eRet = enable_extradata(OMX_PORTDEF_EXTRADATA, false, extradataIndexType->bEnabled); } } break; case OMX_QcomIndexParamEnableSmoothStreaming: { #ifndef SMOOTH_STREAMING_DISABLED eRet = enable_smoothstreaming(); #else eRet = OMX_ErrorUnsupportedSetting; #endif } break; #if defined (_ANDROID_HONEYCOMB_) || defined (_ANDROID_ICS_) /* Need to allow following two set_parameters even in Idle * state. This is ANDROID architecture which is not in sync * with openmax standard. */ case OMX_GoogleAndroidIndexEnableAndroidNativeBuffers: { VALIDATE_OMX_PARAM_DATA(paramData, EnableAndroidNativeBuffersParams); EnableAndroidNativeBuffersParams* enableNativeBuffers = (EnableAndroidNativeBuffersParams *) paramData; if (enableNativeBuffers) { m_enable_android_native_buffers = enableNativeBuffers->enable; } #if !defined(FLEXYUV_SUPPORTED) if (m_enable_android_native_buffers) { if(!client_buffers.set_color_format(getPreferredColorFormatDefaultMode(0))) { DEBUG_PRINT_ERROR("Failed to set native color format!"); eRet = OMX_ErrorUnsupportedSetting; } } #endif } break; case OMX_GoogleAndroidIndexUseAndroidNativeBuffer: { VALIDATE_OMX_PARAM_DATA(paramData, UseAndroidNativeBufferParams); eRet = use_android_native_buffer(hComp, paramData); } break; #endif case OMX_QcomIndexParamEnableTimeStampReorder: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_INDEXTIMESTAMPREORDER); QOMX_INDEXTIMESTAMPREORDER *reorder = (QOMX_INDEXTIMESTAMPREORDER *)paramData; if (drv_ctx.picture_order == (vdec_output_order)QOMX_VIDEO_DISPLAY_ORDER) { if (reorder->bEnable == OMX_TRUE) { frm_int =0; time_stamp_dts.set_timestamp_reorder_mode(true); } else time_stamp_dts.set_timestamp_reorder_mode(false); } else { time_stamp_dts.set_timestamp_reorder_mode(false); if (reorder->bEnable == OMX_TRUE) { eRet = OMX_ErrorUnsupportedSetting; } } } break; case OMX_IndexParamVideoProfileLevelCurrent: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_PROFILELEVELTYPE); OMX_VIDEO_PARAM_PROFILELEVELTYPE* pParam = (OMX_VIDEO_PARAM_PROFILELEVELTYPE*)paramData; if (pParam) { m_profile_lvl.eProfile = pParam->eProfile; m_profile_lvl.eLevel = pParam->eLevel; } break; } case OMX_QcomIndexParamVideoMetaBufferMode: { VALIDATE_OMX_PARAM_DATA(paramData, StoreMetaDataInBuffersParams); StoreMetaDataInBuffersParams *metabuffer = (StoreMetaDataInBuffersParams *)paramData; if (!metabuffer) { DEBUG_PRINT_ERROR("Invalid param: %p", metabuffer); eRet = OMX_ErrorBadParameter; break; } if (m_disable_dynamic_buf_mode) { DEBUG_PRINT_HIGH("Dynamic buffer mode disabled by setprop"); eRet = OMX_ErrorUnsupportedSetting; break; } if (metabuffer->nPortIndex == OMX_CORE_OUTPUT_PORT_INDEX) { struct v4l2_control control; struct v4l2_format fmt; control.id = V4L2_CID_MPEG_VIDC_VIDEO_ALLOC_MODE_OUTPUT; if (metabuffer->bStoreMetaData == true) { control.value = V4L2_MPEG_VIDC_VIDEO_DYNAMIC; } else { control.value = V4L2_MPEG_VIDC_VIDEO_STATIC; } int rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL,&control); if (!rc) { DEBUG_PRINT_HIGH("%s buffer mode", (metabuffer->bStoreMetaData == true)? "Enabled dynamic" : "Disabled dynamic"); dynamic_buf_mode = metabuffer->bStoreMetaData; } else { DEBUG_PRINT_ERROR("Failed to %s buffer mode", (metabuffer->bStoreMetaData == true)? "enable dynamic" : "disable dynamic"); eRet = OMX_ErrorUnsupportedSetting; } } else { DEBUG_PRINT_ERROR( "OMX_QcomIndexParamVideoMetaBufferMode not supported for port: %u", (unsigned int)metabuffer->nPortIndex); eRet = OMX_ErrorUnsupportedSetting; } break; } case OMX_QcomIndexParamVideoDownScalar: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_INDEXDOWNSCALAR); QOMX_INDEXDOWNSCALAR* pParam = (QOMX_INDEXDOWNSCALAR*)paramData; struct v4l2_control control; int rc; if (pParam) { is_down_scalar_enabled = pParam->bEnable; if (is_down_scalar_enabled) { control.id = V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_MODE; control.value = V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_SECONDARY; DEBUG_PRINT_LOW("set_parameter: OMX_QcomIndexParamVideoDownScalar value = %d", pParam->bEnable); rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control); if (rc < 0) { DEBUG_PRINT_ERROR("Failed to set down scalar on driver."); eRet = OMX_ErrorUnsupportedSetting; } control.id = V4L2_CID_MPEG_VIDC_VIDEO_KEEP_ASPECT_RATIO; control.value = 1; rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control); if (rc < 0) { DEBUG_PRINT_ERROR("Failed to set keep aspect ratio on driver."); eRet = OMX_ErrorUnsupportedSetting; } } } break; } #ifdef ADAPTIVE_PLAYBACK_SUPPORTED case OMX_QcomIndexParamVideoAdaptivePlaybackMode: { VALIDATE_OMX_PARAM_DATA(paramData, PrepareForAdaptivePlaybackParams); DEBUG_PRINT_LOW("set_parameter: OMX_GoogleAndroidIndexPrepareForAdaptivePlayback"); PrepareForAdaptivePlaybackParams* pParams = (PrepareForAdaptivePlaybackParams *) paramData; if (pParams->nPortIndex == OMX_CORE_OUTPUT_PORT_INDEX) { if (!pParams->bEnable) { return OMX_ErrorNone; } if (pParams->nMaxFrameWidth > maxSmoothStreamingWidth || pParams->nMaxFrameHeight > maxSmoothStreamingHeight) { DEBUG_PRINT_ERROR( "Adaptive playback request exceeds max supported resolution : [%u x %u] vs [%u x %u]", (unsigned int)pParams->nMaxFrameWidth, (unsigned int)pParams->nMaxFrameHeight, (unsigned int)maxSmoothStreamingWidth, (unsigned int)maxSmoothStreamingHeight); eRet = OMX_ErrorBadParameter; } else { eRet = enable_adaptive_playback(pParams->nMaxFrameWidth, pParams->nMaxFrameHeight); } } else { DEBUG_PRINT_ERROR( "Prepare for adaptive playback supported only on output port"); eRet = OMX_ErrorBadParameter; } break; } #endif case OMX_QcomIndexParamVideoCustomBufferSize: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_VIDEO_CUSTOM_BUFFERSIZE); DEBUG_PRINT_LOW("set_parameter: OMX_QcomIndexParamVideoCustomBufferSize"); QOMX_VIDEO_CUSTOM_BUFFERSIZE* pParam = (QOMX_VIDEO_CUSTOM_BUFFERSIZE*)paramData; if (pParam->nPortIndex == OMX_CORE_INPUT_PORT_INDEX) { struct v4l2_control control; control.id = V4L2_CID_MPEG_VIDC_VIDEO_BUFFER_SIZE_LIMIT; control.value = pParam->nBufferSize; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control)) { DEBUG_PRINT_ERROR("Failed to set input buffer size"); eRet = OMX_ErrorUnsupportedSetting; } else { eRet = get_buffer_req(&drv_ctx.ip_buf); if (eRet == OMX_ErrorNone) { m_custom_buffersize.input_buffersize = drv_ctx.ip_buf.buffer_size; DEBUG_PRINT_HIGH("Successfully set custom input buffer size = %d", m_custom_buffersize.input_buffersize); } else { DEBUG_PRINT_ERROR("Failed to get buffer requirement"); } } } else { DEBUG_PRINT_ERROR("ERROR: Custom buffer size in not supported on output port"); eRet = OMX_ErrorBadParameter; } break; } default: { DEBUG_PRINT_ERROR("Setparameter: unknown param %d", paramIndex); eRet = OMX_ErrorUnsupportedIndex; } } if (eRet != OMX_ErrorNone) DEBUG_PRINT_ERROR("set_parameter: Error: 0x%x, setting param 0x%x", eRet, paramIndex); return eRet; } Commit Message: DO NOT MERGE mm-video-v4l2: vdec: deprecate unused config OMX_IndexVendorVideoExtraData This config (used to set header offline) is no longer used. Remove handling this config since it uses non-process-safe ways to pass memory pointers. Fixes: Security Vulnerability - Segfault in MediaServer (libOmxVdec problem #2) Bug: 27475409 Change-Id: I7a535a3da485cbe83cf4605a05f9faf70dcca42f CWE ID: CWE-20
0
19,288
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 char **get_groupnames(void) { int ngroups; gid_t *group_ids; int ret, i; char **groupnames; struct group *gr; ngroups = getgroups(0, NULL); if (ngroups == -1) { fprintf(stderr, "Failed to get number of groups user belongs to: %s\n", strerror(errno)); return NULL; } if (ngroups == 0) return NULL; group_ids = (gid_t *)malloc(sizeof(gid_t)*ngroups); if (group_ids == NULL) { fprintf(stderr, "Out of memory while getting groups the user belongs to\n"); return NULL; } ret = getgroups(ngroups, group_ids); if (ret < 0) { free(group_ids); fprintf(stderr, "Failed to get process groups: %s\n", strerror(errno)); return NULL; } groupnames = (char **)malloc(sizeof(char *)*(ngroups+1)); if (groupnames == NULL) { free(group_ids); fprintf(stderr, "Out of memory while getting group names\n"); return NULL; } memset(groupnames, 0, sizeof(char *)*(ngroups+1)); for (i=0; i<ngroups; i++ ) { gr = getgrgid(group_ids[i]); if (gr == NULL) { fprintf(stderr, "Failed to get group name\n"); free(group_ids); free_groupnames(groupnames); return NULL; } groupnames[i] = strdup(gr->gr_name); if (groupnames[i] == NULL) { fprintf(stderr, "Failed to copy group name: %s", gr->gr_name); free(group_ids); free_groupnames(groupnames); return NULL; } } free(group_ids); return groupnames; } Commit Message: CVE-2017-5985: Ensure target netns is caller-owned Before this commit, lxc-user-nic could potentially have been tricked into operating on a network namespace over which the caller did not hold privilege. This commit ensures that the caller is privileged over the network namespace by temporarily dropping privilege. Launchpad: https://bugs.launchpad.net/ubuntu/+source/lxc/+bug/1654676 Reported-by: Jann Horn <jannh@google.com> Signed-off-by: Christian Brauner <christian.brauner@ubuntu.com> CWE ID: CWE-862
0
25,085
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 NuMediaExtractor::releaseTrackSamples() { for (size_t i = 0; i < mSelectedTracks.size(); ++i) { TrackInfo *info = &mSelectedTracks.editItemAt(i); if (info->mSample != NULL) { info->mSample->release(); info->mSample = NULL; info->mSampleTimeUs = -1ll; } } } Commit Message: Fix integer overflow and divide-by-zero Bug: 35763994 Test: ran CTS with and without fix Change-Id: If835e97ce578d4fa567e33e349e48fb7b2559e0e (cherry picked from commit 8538a603ef992e75f29336499cb783f3ec19f18c) CWE ID: CWE-190
0
17,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: ZEND_API void zend_update_property_null(zend_class_entry *scope, zval *object, const char *name, int name_length TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_LONG(tmp, value); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ Commit Message: CWE ID: CWE-416
0
26,052
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: cancel_activate_callback (gpointer callback_data) { ActivateParameters *parameters = callback_data; parameters->timed_wait_active = FALSE; g_cancellable_cancel (parameters->cancellable); if (parameters->files_handle) { nautilus_file_list_cancel_call_when_ready (parameters->files_handle); parameters->files_handle = NULL; activation_parameters_free (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
24,409
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 BrowserView::OnWindowBeginUserBoundsChange() { WebContents* web_contents = GetActiveWebContents(); if (!web_contents) return; web_contents->GetRenderViewHost()->NotifyMoveOrResizeStarted(); } 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
14,151
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: const char * gdJpegGetVersionString() { switch(JPEG_LIB_VERSION) { case 62: return "6b"; break; case 70: return "7"; break; case 80: return "8"; break; case 90: return "9 compatible"; break; default: return "unknown"; } } Commit Message: Sync with upstream Even though libgd/libgd#492 is not a relevant bug fix for PHP, since the binding doesn't use the `gdImage*Ptr()` functions at all, we're porting the fix to stay in sync here. CWE ID: CWE-415
0
8,870
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: xmlParseDocument(xmlParserCtxtPtr ctxt) { xmlChar start[4]; xmlCharEncoding enc; xmlInitParser(); if ((ctxt == NULL) || (ctxt->input == NULL)) return(-1); GROW; /* * SAX: detecting the level. */ xmlDetectSAX2(ctxt); /* * SAX: beginning of the document processing. */ if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); if ((ctxt->encoding == (const xmlChar *)XML_CHAR_ENCODING_NONE) && ((ctxt->input->end - ctxt->input->cur) >= 4)) { /* * Get the 4 first bytes and decode the charset * if enc != XML_CHAR_ENCODING_NONE * plug some encoding conversion routines. */ start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(&start[0], 4); if (enc != XML_CHAR_ENCODING_NONE) { xmlSwitchEncoding(ctxt, enc); } } if (CUR == 0) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL); } /* * Check for the XMLDecl in the Prolog. * do not GROW here to avoid the detected encoder to decode more * than just the first line, unless the amount of data is really * too small to hold "<?xml version="1.0" encoding="foo" */ if ((ctxt->input->end - ctxt->input->cur) < 35) { GROW; } if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) { /* * Note that we will switch encoding on the fly. */ xmlParseXMLDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing right here */ return(-1); } ctxt->standalone = ctxt->input->standalone; SKIP_BLANKS; } else { ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION); } if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); /* * The Misc part of the Prolog */ GROW; xmlParseMisc(ctxt); /* * Then possibly doc type declaration(s) and more Misc * (doctypedecl Misc*)? */ GROW; if (CMP9(CUR_PTR, '<', '!', 'D', 'O', 'C', 'T', 'Y', 'P', 'E')) { ctxt->inSubset = 1; xmlParseDocTypeDecl(ctxt); if (RAW == '[') { ctxt->instate = XML_PARSER_DTD; xmlParseInternalSubset(ctxt); } /* * Create and update the external subset. */ ctxt->inSubset = 2; if ((ctxt->sax != NULL) && (ctxt->sax->externalSubset != NULL) && (!ctxt->disableSAX)) ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, ctxt->extSubSystem, ctxt->extSubURI); ctxt->inSubset = 0; xmlCleanSpecialAttr(ctxt); ctxt->instate = XML_PARSER_PROLOG; xmlParseMisc(ctxt); } /* * Time to start parsing the tree itself */ GROW; if (RAW != '<') { xmlFatalErrMsg(ctxt, XML_ERR_DOCUMENT_EMPTY, "Start tag expected, '<' not found\n"); } else { ctxt->instate = XML_PARSER_CONTENT; xmlParseElement(ctxt); ctxt->instate = XML_PARSER_EPILOG; /* * The Misc part at the end */ xmlParseMisc(ctxt); if (RAW != 0) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL); } ctxt->instate = XML_PARSER_EOF; } /* * SAX: end of the document processing. */ if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); /* * Remove locally kept entity definitions if the tree was not built */ if ((ctxt->myDoc != NULL) && (xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE))) { xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } if ((ctxt->wellFormed) && (ctxt->myDoc != NULL)) { ctxt->myDoc->properties |= XML_DOC_WELLFORMED; if (ctxt->valid) ctxt->myDoc->properties |= XML_DOC_DTDVALID; if (ctxt->nsWellFormed) ctxt->myDoc->properties |= XML_DOC_NSVALID; if (ctxt->options & XML_PARSE_OLD10) ctxt->myDoc->properties |= XML_DOC_OLD10; } if (! ctxt->wellFormed) { ctxt->valid = 0; return(-1); } 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
19,623
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 walk_hugetlb_range(struct vm_area_struct *vma, unsigned long addr, unsigned long end, struct mm_walk *walk) { struct hstate *h = hstate_vma(vma); unsigned long next; unsigned long hmask = huge_page_mask(h); pte_t *pte; int err = 0; do { next = hugetlb_entry_end(h, addr, end); pte = huge_pte_offset(walk->mm, addr & hmask); if (pte && walk->hugetlb_entry) err = walk->hugetlb_entry(pte, hmask, addr, next, walk); if (err) return err; } while (addr = next, addr != end); return 0; } 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
25,891
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 *__alloc_simple_buffer(struct device *dev, size_t size, gfp_t gfp, struct page **ret_page) { struct page *page; page = __dma_alloc_buffer(dev, size, gfp); if (!page) return NULL; *ret_page = page; return page_address(page); } Commit Message: ARM: dma-mapping: don't allow DMA mappings to be marked executable DMA mapping permissions were being derived from pgprot_kernel directly without using PAGE_KERNEL. This causes them to be marked with executable permission, which is not what we want. Fix this. Signed-off-by: Russell King <rmk+kernel@arm.linux.org.uk> CWE ID: CWE-264
0
21,352
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 bool access_pmu_evcntr(struct kvm_vcpu *vcpu, struct sys_reg_params *p, const struct sys_reg_desc *r) { u64 idx; if (!kvm_arm_pmu_v3_ready(vcpu)) return trap_raz_wi(vcpu, p, r); if (r->CRn == 9 && r->CRm == 13) { if (r->Op2 == 2) { /* PMXEVCNTR_EL0 */ if (pmu_access_event_counter_el0_disabled(vcpu)) return false; idx = vcpu_sys_reg(vcpu, PMSELR_EL0) & ARMV8_PMU_COUNTER_MASK; } else if (r->Op2 == 0) { /* PMCCNTR_EL0 */ if (pmu_access_cycle_counter_el0_disabled(vcpu)) return false; idx = ARMV8_PMU_CYCLE_IDX; } else { BUG(); } } else if (r->CRn == 14 && (r->CRm & 12) == 8) { /* PMEVCNTRn_EL0 */ if (pmu_access_event_counter_el0_disabled(vcpu)) return false; idx = ((r->CRm & 3) << 3) | (r->Op2 & 7); } else { BUG(); } if (!pmu_counter_idx_valid(vcpu, idx)) return false; if (p->is_write) { if (pmu_access_el0_disabled(vcpu)) return false; kvm_pmu_set_counter_value(vcpu, idx, p->regval); } else { p->regval = kvm_pmu_get_counter_value(vcpu, idx); } return true; } Commit Message: arm64: KVM: pmu: Fix AArch32 cycle counter access We're missing the handling code for the cycle counter accessed from a 32bit guest, leading to unexpected results. Cc: stable@vger.kernel.org # 4.6+ Signed-off-by: Wei Huang <wei@redhat.com> Signed-off-by: Marc Zyngier <marc.zyngier@arm.com> CWE ID: CWE-617
1
11,655
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: RenderFrameSubmissionObserver::~RenderFrameSubmissionObserver() { render_frame_metadata_provider_->RemoveObserver(this); render_frame_metadata_provider_->ReportAllFrameSubmissionsForTesting(false); } Commit Message: Apply ExtensionNavigationThrottle filesystem/blob checks to all frames. BUG=836858 Change-Id: I34333a72501129fd40b5a9aa6378c9f35f1e7fc2 Reviewed-on: https://chromium-review.googlesource.com/1028511 Reviewed-by: Devlin <rdevlin.cronin@chromium.org> Reviewed-by: Alex Moshchuk <alexmos@chromium.org> Reviewed-by: Nick Carter <nick@chromium.org> Commit-Queue: Charlie Reis <creis@chromium.org> Cr-Commit-Position: refs/heads/master@{#553867} CWE ID: CWE-20
0
19,736
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_strings_2_svc(gstrings_arg *arg, struct svc_req *rqstp) { static gstrings_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_gstrings_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (! cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ) && (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_INQUIRE, arg->princ, NULL))) { ret.code = KADM5_AUTH_GET; log_unauth("kadm5_get_strings", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_get_strings((void *)handle, arg->princ, &ret.strings, &ret.count); if (ret.code != 0) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_get_strings", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
1
6,385
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 FlateStream::getRawChars(int nChars, int *buffer) { for (int i = 0; i < nChars; ++i) buffer[i] = doGetRawChar(); } Commit Message: CWE ID: CWE-119
0
27,537
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 WebGL2RenderingContextBase::uniformBlockBinding( WebGLProgram* program, GLuint uniform_block_index, GLuint uniform_block_binding) { if (isContextLost() || !ValidateWebGLObject("uniformBlockBinding", program)) return; if (!ValidateUniformBlockIndex("uniformBlockBinding", program, uniform_block_index)) return; ContextGL()->UniformBlockBinding(ObjectOrZero(program), uniform_block_index, uniform_block_binding); } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test R=kbr@chromium.org,piman@chromium.org Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <piman@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Commit-Queue: Zhenyao Mo <zmo@chromium.org> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119
0
7,866
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 tsro_del(GF_Box *s) { GF_TimeOffHintEntryBox *tsro = (GF_TimeOffHintEntryBox *)s; gf_free(tsro); } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125
0
21,784
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 FLTIsSupportedFilterType(CPLXMLNode *psXMLNode) { if (psXMLNode) { if (FLTIsLogicalFilterType(psXMLNode->pszValue) || FLTIsSpatialFilterType(psXMLNode->pszValue) || FLTIsComparisonFilterType(psXMLNode->pszValue) || FLTIsFeatureIdFilterType(psXMLNode->pszValue) || FLTIsTemporalFilterType(psXMLNode->pszValue)) return MS_TRUE; } return MS_FALSE; } Commit Message: security fix (patch by EvenR) CWE ID: CWE-119
0
5,690
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: Ins_DEPTH( TT_ExecContext exc, FT_Long* args ) { args[0] = exc->top; } Commit Message: CWE ID: CWE-476
0
1,918
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 mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag) { int64_t curpos, entryPos; int i, index = 0; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); // size ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps"); avio_wb32(pb, 0); // version & flags entryPos = avio_tell(pb); avio_wb32(pb, track->entry); // entry count for (i = 0; i < track->entry; i++) { if (track->cluster[i].flags & flag) { avio_wb32(pb, i + 1); index++; } } curpos = avio_tell(pb); avio_seek(pb, entryPos, SEEK_SET); avio_wb32(pb, index); // rewrite size avio_seek(pb, curpos, SEEK_SET); return update_size(pb, pos); } Commit Message: avformat/movenc: Write version 2 of audio atom if channels is not known The version 1 needs the channel count and would divide by 0 Fixes: division by 0 Fixes: fpe_movenc.c_1108_1.ogg Fixes: fpe_movenc.c_1108_2.ogg Fixes: fpe_movenc.c_1108_3.wav Found-by: #CHEN HONGXU# <HCHEN017@e.ntu.edu.sg> Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-369
0
11,177
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: write_byte(struct file *file, int b) /* Write one byte to the output - this causes a fatal error if the write * fails and the read of this PNG file immediately terminates. Just * increments the write count if there is no output file. */ { if (file->out != NULL) { if (putc(b, file->out) != b) { file->write_errno = errno; file->status_code |= WRITE_ERROR; stop(file, WRITE_ERROR_CODE, "write byte"); } } ++(file->write_count); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
0
8,709
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: int32_t PepperDeviceEnumerationHostHelper::OnEnumerateDevices( HostMessageContext* context) { if (enumerate_devices_context_.is_valid()) return PP_ERROR_INPROGRESS; enumerate_.reset(new ScopedRequest( this, base::Bind(&PepperDeviceEnumerationHostHelper::OnEnumerateDevicesComplete, base::Unretained(this)))); if (!enumerate_->requested()) return PP_ERROR_FAILED; enumerate_devices_context_ = context->MakeReplyMessageContext(); return PP_OK_COMPLETIONPENDING; } Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr Its lifetime is scoped to the RenderFrame, and it might go away before the hosts that refer to it. BUG=423030 Review URL: https://codereview.chromium.org/653243003 Cr-Commit-Position: refs/heads/master@{#299897} CWE ID: CWE-399
0
1,855
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 udf_setsize(struct inode *inode, loff_t newsize) { int err; struct udf_inode_info *iinfo; int bsize = 1 << inode->i_blkbits; if (!(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))) return -EINVAL; if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) return -EPERM; iinfo = UDF_I(inode); if (newsize > inode->i_size) { down_write(&iinfo->i_data_sem); if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { if (bsize < (udf_file_entry_alloc_offset(inode) + newsize)) { err = udf_expand_file_adinicb(inode); if (err) return err; down_write(&iinfo->i_data_sem); } else { iinfo->i_lenAlloc = newsize; goto set_size; } } err = udf_extend_file(inode, newsize); if (err) { up_write(&iinfo->i_data_sem); return err; } set_size: truncate_setsize(inode, newsize); up_write(&iinfo->i_data_sem); } else { if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { down_write(&iinfo->i_data_sem); udf_clear_extent_cache(inode); memset(iinfo->i_ext.i_data + iinfo->i_lenEAttr + newsize, 0x00, bsize - newsize - udf_file_entry_alloc_offset(inode)); iinfo->i_lenAlloc = newsize; truncate_setsize(inode, newsize); up_write(&iinfo->i_data_sem); goto update_time; } err = block_truncate_page(inode->i_mapping, newsize, udf_get_block); if (err) return err; down_write(&iinfo->i_data_sem); udf_clear_extent_cache(inode); truncate_setsize(inode, newsize); udf_truncate_extents(inode); up_write(&iinfo->i_data_sem); } update_time: inode->i_mtime = inode->i_ctime = current_fs_time(inode->i_sb); if (IS_SYNC(inode)) udf_sync_inode(inode); else mark_inode_dirty(inode); return 0; } Commit Message: udf: Check length of extended attributes and allocation descriptors Check length of extended attributes and allocation descriptors when loading inodes from disk. Otherwise corrupted filesystems could confuse the code and make the kernel oops. Reported-by: Carl Henrik Lunde <chlunde@ping.uio.no> CC: stable@vger.kernel.org Signed-off-by: Jan Kara <jack@suse.cz> CWE ID: CWE-189
0
21,984
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: GF_Err def_cont_box_dump(GF_Box *a, FILE *trace) { char *name = "SubTrackDefinitionBox"; //only one using generic box container for now gf_isom_box_dump_start(a, name, trace); fprintf(trace, ">\n"); gf_isom_box_dump_done(name, a, trace); return GF_OK; } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125
0
26,467
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: set_eecd(E1000State *s, int index, uint32_t val) { uint32_t oldval = s->eecd_state.old_eecd; s->eecd_state.old_eecd = val & (E1000_EECD_SK | E1000_EECD_CS | E1000_EECD_DI|E1000_EECD_FWE_MASK|E1000_EECD_REQ); if (!(E1000_EECD_CS & val)) // CS inactive; nothing to do return; if (E1000_EECD_CS & (val ^ oldval)) { // CS rise edge; reset state s->eecd_state.val_in = 0; s->eecd_state.bitnum_in = 0; s->eecd_state.bitnum_out = 0; s->eecd_state.reading = 0; } if (!(E1000_EECD_SK & (val ^ oldval))) // no clock edge return; if (!(E1000_EECD_SK & val)) { // falling edge s->eecd_state.bitnum_out++; return; } s->eecd_state.val_in <<= 1; if (val & E1000_EECD_DI) s->eecd_state.val_in |= 1; if (++s->eecd_state.bitnum_in == 9 && !s->eecd_state.reading) { s->eecd_state.bitnum_out = ((s->eecd_state.val_in & 0x3f)<<4)-1; s->eecd_state.reading = (((s->eecd_state.val_in >> 6) & 7) == EEPROM_READ_OPCODE_MICROWIRE); } DBGOUT(EEPROM, "eeprom bitnum in %d out %d, reading %d\n", s->eecd_state.bitnum_in, s->eecd_state.bitnum_out, s->eecd_state.reading); } Commit Message: CWE ID: CWE-119
0
23,909
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: OMX_ERRORTYPE omx_vdec::empty_this_buffer(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_BUFFERHEADERTYPE* buffer) { OMX_ERRORTYPE ret1 = OMX_ErrorNone; unsigned int nBufferIndex = drv_ctx.ip_buf.actualcount; if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("Empty this buffer in Invalid State"); return OMX_ErrorInvalidState; } if (buffer == NULL) { DEBUG_PRINT_ERROR("ERROR:ETB Buffer is NULL"); return OMX_ErrorBadParameter; } if (!m_inp_bEnabled) { DEBUG_PRINT_ERROR("ERROR:ETB incorrect state operation, input port is disabled."); return OMX_ErrorIncorrectStateOperation; } if (buffer->nInputPortIndex != OMX_CORE_INPUT_PORT_INDEX) { DEBUG_PRINT_ERROR("ERROR:ETB invalid port in header %u", (unsigned int)buffer->nInputPortIndex); return OMX_ErrorBadPortIndex; } #ifdef _ANDROID_ if (iDivXDrmDecrypt) { OMX_ERRORTYPE drmErr = iDivXDrmDecrypt->Decrypt(buffer); if (drmErr != OMX_ErrorNone) { DEBUG_PRINT_LOW("ERROR:iDivXDrmDecrypt->Decrypt %d", drmErr); } } #endif //_ANDROID_ if (perf_flag) { if (!latency) { dec_time.stop(); latency = dec_time.processing_time_us(); dec_time.start(); } } if (arbitrary_bytes) { nBufferIndex = buffer - m_inp_heap_ptr; } else { if (input_use_buffer == true) { nBufferIndex = buffer - m_inp_heap_ptr; m_inp_mem_ptr[nBufferIndex].nFilledLen = m_inp_heap_ptr[nBufferIndex].nFilledLen; m_inp_mem_ptr[nBufferIndex].nTimeStamp = m_inp_heap_ptr[nBufferIndex].nTimeStamp; m_inp_mem_ptr[nBufferIndex].nFlags = m_inp_heap_ptr[nBufferIndex].nFlags; buffer = &m_inp_mem_ptr[nBufferIndex]; DEBUG_PRINT_LOW("Non-Arbitrary mode - buffer address is: malloc %p, pmem%p in Index %d, buffer %p of size %u", &m_inp_heap_ptr[nBufferIndex], &m_inp_mem_ptr[nBufferIndex],nBufferIndex, buffer, (unsigned int)buffer->nFilledLen); } else { nBufferIndex = buffer - m_inp_mem_ptr; } } if (nBufferIndex > drv_ctx.ip_buf.actualcount ) { DEBUG_PRINT_ERROR("ERROR:ETB nBufferIndex is invalid"); return OMX_ErrorBadParameter; } if (buffer->nFlags & OMX_BUFFERFLAG_CODECCONFIG) { codec_config_flag = true; DEBUG_PRINT_LOW("%s: codec_config buffer", __FUNCTION__); } DEBUG_PRINT_LOW("[ETB] BHdr(%p) pBuf(%p) nTS(%lld) nFL(%u)", buffer, buffer->pBuffer, buffer->nTimeStamp, (unsigned int)buffer->nFilledLen); if (arbitrary_bytes) { post_event ((unsigned long)hComp,(unsigned long)buffer, OMX_COMPONENT_GENERATE_ETB_ARBITRARY); } else { post_event ((unsigned long)hComp,(unsigned long)buffer,OMX_COMPONENT_GENERATE_ETB); } time_stamp_dts.insert_timestamp(buffer); return OMX_ErrorNone; } Commit Message: DO NOT MERGE mm-video-v4l2: vdec: Avoid processing ETBs/FTBs in invalid states (per the spec) ETB/FTB should not be handled in states other than Executing, Paused and Idle. This avoids accessing invalid buffers. Also add a lock to protect the private-buffers from being deleted while accessing from another thread. Bug: 27890802 Security Vulnerability - Heap Use-After-Free and Possible LPE in MediaServer (libOmxVdec problem #6) CRs-Fixed: 1008882 Change-Id: Iaac2e383cd53cf9cf8042c9ed93ddc76dba3907e CWE ID:
1
8,850
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: handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName) { if (parser->m_unknownEncodingHandler) { XML_Encoding info; int i; for (i = 0; i < 256; i++) info.map[i] = -1; info.convert = NULL; info.data = NULL; info.release = NULL; if (parser->m_unknownEncodingHandler(parser->m_unknownEncodingHandlerData, encodingName, &info)) { ENCODING *enc; parser->m_unknownEncodingMem = MALLOC(parser, XmlSizeOfUnknownEncoding()); if (! parser->m_unknownEncodingMem) { if (info.release) info.release(info.data); return XML_ERROR_NO_MEMORY; } enc = (parser->m_ns ? XmlInitUnknownEncodingNS : XmlInitUnknownEncoding)( parser->m_unknownEncodingMem, info.map, info.convert, info.data); if (enc) { parser->m_unknownEncodingData = info.data; parser->m_unknownEncodingRelease = info.release; parser->m_encoding = enc; return XML_ERROR_NONE; } } if (info.release != NULL) info.release(info.data); } return XML_ERROR_UNKNOWN_ENCODING; } Commit Message: xmlparse.c: Deny internal entities closing the doctype CWE ID: CWE-611
0
3,646
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: IntRect WebPagePrivate::mapFromViewportToContents(const IntRect& rect) const { return m_backingStoreClient->mapFromViewportToContents(rect); } Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API https://bugs.webkit.org/show_bug.cgi?id=105143 RIM PR 171941 Reviewed by Rob Buis. Internally reviewed by George Staikos. Source/WebCore: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. Also adapt to new method names and encapsulation of TouchPoint data members. No change in behavior, no new tests. * platform/blackberry/PlatformTouchPointBlackBerry.cpp: (WebCore::PlatformTouchPoint::PlatformTouchPoint): Source/WebKit/blackberry: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. One exception is when passing events to a full screen plugin. Also adapt to new method names and encapsulation of TouchPoint data members. * Api/WebPage.cpp: (BlackBerry::WebKit::WebPage::touchEvent): (BlackBerry::WebKit::WebPage::touchPointAsMouseEvent): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin): * WebKitSupport/InputHandler.cpp: (BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint): * WebKitSupport/InputHandler.h: (InputHandler): * WebKitSupport/TouchEventHandler.cpp: (BlackBerry::WebKit::TouchEventHandler::doFatFingers): (BlackBerry::WebKit::TouchEventHandler::handleTouchPoint): * WebKitSupport/TouchEventHandler.h: (TouchEventHandler): Tools: Adapt to new method names and encapsulation of TouchPoint data members. * DumpRenderTree/blackberry/EventSender.cpp: (addTouchPointCallback): (updateTouchPointCallback): (touchEndCallback): (releaseTouchPointCallback): (sendTouchEvent): git-svn-id: svn://svn.chromium.org/blink/trunk@137880 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
0
26,339
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: UnloadController::~UnloadController() { browser_->tab_strip_model()->RemoveObserver(this); } 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
27,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 size_t all_data_cb(const void *ptr, size_t size, size_t nmemb, void *user_data) { struct data_buffer *db = user_data; size_t len = size * nmemb; size_t oldlen, newlen; void *newmem; static const unsigned char zero = 0; oldlen = db->len; newlen = oldlen + len; newmem = realloc(db->buf, newlen + 1); if (!newmem) return 0; db->buf = newmem; db->len = newlen; memcpy(db->buf + oldlen, ptr, len); memcpy(db->buf + newlen, &zero, 1); /* null terminate */ return len; } Commit Message: Do some random sanity checking for stratum message parsing CWE ID: CWE-119
0
19,507
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 OxideQQuickWebView::setPromptDialog(QQmlComponent* promptDialog) { Q_D(OxideQQuickWebView); if (d->prompt_dialog_ == promptDialog) { return; } d->prompt_dialog_ = promptDialog; emit promptDialogChanged(); } Commit Message: CWE ID: CWE-20
0
29,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: const FontRenderParams& PlatformFontSkia::GetFontRenderParams() { TRACE_EVENT0("fonts", "PlatformFontSkia::GetFontRenderParams"); float current_scale_factor = GetFontRenderParamsDeviceScaleFactor(); if (current_scale_factor != device_scale_factor_) { FontRenderParamsQuery query; query.families.push_back(font_family_); query.pixel_size = font_size_pixels_; query.style = style_; query.weight = weight_; query.device_scale_factor = current_scale_factor; font_render_params_ = gfx::GetFontRenderParams(query, nullptr); device_scale_factor_ = current_scale_factor; } return font_render_params_; } Commit Message: Take default system font size from PlatformFont The default font returned by Skia should take the initial size from the default value kDefaultBaseFontSize specified in PlatformFont. R=robliao@chromium.org, asvitkine@chromium.org CC=benck@google.com Bug: 944227 Change-Id: I6b230b80c349abbe5968edb3cebdd6e89db4c4a6 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1642738 Reviewed-by: Robert Liao <robliao@chromium.org> Reviewed-by: Alexei Svitkine <asvitkine@chromium.org> Commit-Queue: Etienne Bergeron <etienneb@chromium.org> Cr-Commit-Position: refs/heads/master@{#666299} CWE ID: CWE-862
0
28,074
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 CustomButton::OnMouseEntered(const ui::MouseEvent& event) { if (state_ != STATE_DISABLED) SetState(STATE_HOVERED); } Commit Message: Custom buttons should only handle accelerators when focused. BUG=541415 Review URL: https://codereview.chromium.org/1437523005 Cr-Commit-Position: refs/heads/master@{#360130} CWE ID: CWE-254
0
7,845
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: CURLcode Curl_protocol_doing(struct connectdata *conn, bool *done) { CURLcode result = CURLE_OK; if(conn && conn->handler->doing) { *done = FALSE; result = conn->handler->doing(conn, done); } else *done = TRUE; return result; } Commit Message: Curl_close: clear data->multi_easy on free to avoid use-after-free Regression from b46cfbc068 (7.59.0) CVE-2018-16840 Reported-by: Brian Carpenter (Geeknik Labs) Bug: https://curl.haxx.se/docs/CVE-2018-16840.html CWE ID: CWE-416
0
10,573
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 do_mincore(unsigned long addr, unsigned long pages, unsigned char *vec) { struct vm_area_struct *vma; unsigned long end; int err; struct mm_walk mincore_walk = { .pmd_entry = mincore_pte_range, .pte_hole = mincore_unmapped_range, .hugetlb_entry = mincore_hugetlb, .private = vec, }; vma = find_vma(current->mm, addr); if (!vma || addr < vma->vm_start) return -ENOMEM; mincore_walk.mm = vma->vm_mm; end = min(vma->vm_end, addr + (pages << PAGE_SHIFT)); err = walk_page_range(addr, end, &mincore_walk); if (err < 0) return err; return (end - addr) >> PAGE_SHIFT; } Commit Message: Change mincore() to count "mapped" pages rather than "cached" pages The semantics of what "in core" means for the mincore() system call are somewhat unclear, but Linux has always (since 2.3.52, which is when mincore() was initially done) treated it as "page is available in page cache" rather than "page is mapped in the mapping". The problem with that traditional semantic is that it exposes a lot of system cache state that it really probably shouldn't, and that users shouldn't really even care about. So let's try to avoid that information leak by simply changing the semantics to be that mincore() counts actual mapped pages, not pages that might be cheaply mapped if they were faulted (note the "might be" part of the old semantics: being in the cache doesn't actually guarantee that you can access them without IO anyway, since things like network filesystems may have to revalidate the cache before use). In many ways the old semantics were somewhat insane even aside from the information leak issue. From the very beginning (and that beginning is a long time ago: 2.3.52 was released in March 2000, I think), the code had a comment saying Later we can get more picky about what "in core" means precisely. and this is that "later". Admittedly it is much later than is really comfortable. NOTE! This is a real semantic change, and it is for example known to change the output of "fincore", since that program literally does a mmmap without populating it, and then doing "mincore()" on that mapping that doesn't actually have any pages in it. I'm hoping that nobody actually has any workflow that cares, and the info leak is real. We may have to do something different if it turns out that people have valid reasons to want the old semantics, and if we can limit the information leak sanely. Cc: Kevin Easton <kevin@guarana.org> Cc: Jiri Kosina <jikos@kernel.org> Cc: Masatake YAMATO <yamato@redhat.com> Cc: Andrew Morton <akpm@linux-foundation.org> Cc: Greg KH <gregkh@linuxfoundation.org> Cc: Peter Zijlstra <peterz@infradead.org> Cc: Michal Hocko <mhocko@suse.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-200
0
3,923
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: Gif_SetErrorHandler(Gif_ReadErrorHandler handler) { default_error_handler = handler; } Commit Message: gif_read: Set last_name = NULL unconditionally. With a non-malicious GIF, last_name is set to NULL when a name extension is followed by an image. Reported in #117, via Debian, via a KAIST fuzzing program. CWE ID: CWE-415
0
6,109
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 request_end(struct fuse_conn *fc, struct fuse_req *req) { struct fuse_iqueue *fiq = &fc->iq; if (test_and_set_bit(FR_FINISHED, &req->flags)) goto put_request; /* * test_and_set_bit() implies smp_mb() between bit * changing and below intr_entry check. Pairs with * smp_mb() from queue_interrupt(). */ if (!list_empty(&req->intr_entry)) { spin_lock(&fiq->waitq.lock); list_del_init(&req->intr_entry); spin_unlock(&fiq->waitq.lock); } WARN_ON(test_bit(FR_PENDING, &req->flags)); WARN_ON(test_bit(FR_SENT, &req->flags)); if (test_bit(FR_BACKGROUND, &req->flags)) { spin_lock(&fc->bg_lock); clear_bit(FR_BACKGROUND, &req->flags); if (fc->num_background == fc->max_background) { fc->blocked = 0; wake_up(&fc->blocked_waitq); } else if (!fc->blocked) { /* * Wake up next waiter, if any. It's okay to use * waitqueue_active(), as we've already synced up * fc->blocked with waiters with the wake_up() call * above. */ if (waitqueue_active(&fc->blocked_waitq)) wake_up(&fc->blocked_waitq); } if (fc->num_background == fc->congestion_threshold && fc->sb) { clear_bdi_congested(fc->sb->s_bdi, BLK_RW_SYNC); clear_bdi_congested(fc->sb->s_bdi, BLK_RW_ASYNC); } fc->num_background--; fc->active_background--; flush_bg_queue(fc); spin_unlock(&fc->bg_lock); } else { /* Wake up waiter sleeping in request_wait_answer() */ wake_up(&req->waitq); } if (req->end) req->end(fc, req); put_request: fuse_put_request(fc, req); } Commit Message: Merge branch 'page-refs' (page ref overflow) Merge page ref overflow branch. Jann Horn reported that he can overflow the page ref count with sufficient memory (and a filesystem that is intentionally extremely slow). Admittedly it's not exactly easy. To have more than four billion references to a page requires a minimum of 32GB of kernel memory just for the pointers to the pages, much less any metadata to keep track of those pointers. Jann needed a total of 140GB of memory and a specially crafted filesystem that leaves all reads pending (in order to not ever free the page references and just keep adding more). Still, we have a fairly straightforward way to limit the two obvious user-controllable sources of page references: direct-IO like page references gotten through get_user_pages(), and the splice pipe page duplication. So let's just do that. * branch page-refs: fs: prevent page refcount overflow in pipe_buf_get mm: prevent get_user_pages() from overflowing page refcount mm: add 'try_get_page()' helper function mm: make page ref count overflow check tighter and more explicit CWE ID: CWE-416
0
24,197
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 fuse_do_truncate(struct file *file) { struct inode *inode = file->f_mapping->host; struct iattr attr; attr.ia_valid = ATTR_SIZE; attr.ia_size = i_size_read(inode); attr.ia_file = file; attr.ia_valid |= ATTR_FILE; fuse_do_setattr(inode, &attr, file); } Commit Message: fuse: break infinite loop in fuse_fill_write_pages() I got a report about unkillable task eating CPU. Further investigation shows, that the problem is in the fuse_fill_write_pages() function. If iov's first segment has zero length, we get an infinite loop, because we never reach iov_iter_advance() call. Fix this by calling iov_iter_advance() before repeating an attempt to copy data from userspace. A similar problem is described in 124d3b7041f ("fix writev regression: pan hanging unkillable and un-straceable"). If zero-length segmend is followed by segment with invalid address, iov_iter_fault_in_readable() checks only first segment (zero-length), iov_iter_copy_from_user_atomic() skips it, fails at second and returns zero -> goto again without skipping zero-length segment. Patch calls iov_iter_advance() before goto again: we'll skip zero-length segment at second iteraction and iov_iter_fault_in_readable() will detect invalid address. Special thanks to Konstantin Khlebnikov, who helped a lot with the commit description. Cc: Andrew Morton <akpm@linux-foundation.org> Cc: Maxim Patlasov <mpatlasov@parallels.com> Cc: Konstantin Khlebnikov <khlebnikov@yandex-team.ru> Signed-off-by: Roman Gushchin <klamm@yandex-team.ru> Signed-off-by: Miklos Szeredi <miklos@szeredi.hu> Fixes: ea9b9907b82a ("fuse: implement perform_write") Cc: <stable@vger.kernel.org> CWE ID: CWE-399
0
19,734
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: std::string GetDriveAppIdFromSyncId(const std::string& sync_id) { if (!IsDriveAppSyncId(sync_id)) return std::string(); return sync_id.substr(strlen(kDriveAppSyncIdPrefix)); } 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
4,315
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 size_t ZSTD_resetCCtx_byAttachingCDict( ZSTD_CCtx* cctx, const ZSTD_CDict* cdict, ZSTD_CCtx_params params, U64 pledgedSrcSize, ZSTD_buffered_policy_e zbuff) { { const ZSTD_compressionParameters *cdict_cParams = &cdict->matchState.cParams; unsigned const windowLog = params.cParams.windowLog; assert(windowLog != 0); /* Resize working context table params for input only, since the dict * has its own tables. */ params.cParams = ZSTD_adjustCParams_internal(*cdict_cParams, pledgedSrcSize, 0); params.cParams.windowLog = windowLog; ZSTD_resetCCtx_internal(cctx, params, pledgedSrcSize, ZSTDcrp_continue, zbuff); assert(cctx->appliedParams.cParams.strategy == cdict_cParams->strategy); } { const U32 cdictEnd = (U32)( cdict->matchState.window.nextSrc - cdict->matchState.window.base); const U32 cdictLen = cdictEnd - cdict->matchState.window.dictLimit; if (cdictLen == 0) { /* don't even attach dictionaries with no contents */ DEBUGLOG(4, "skipping attaching empty dictionary"); } else { DEBUGLOG(4, "attaching dictionary into context"); cctx->blockState.matchState.dictMatchState = &cdict->matchState; /* prep working match state so dict matches never have negative indices * when they are translated to the working context's index space. */ if (cctx->blockState.matchState.window.dictLimit < cdictEnd) { cctx->blockState.matchState.window.nextSrc = cctx->blockState.matchState.window.base + cdictEnd; ZSTD_window_clear(&cctx->blockState.matchState.window); } cctx->blockState.matchState.loadedDictEnd = cctx->blockState.matchState.window.dictLimit; } } cctx->dictID = cdict->dictID; /* copy block state */ memcpy(cctx->blockState.prevCBlock, &cdict->cBlockState, sizeof(cdict->cBlockState)); return 0; } Commit Message: fixed T36302429 CWE ID: CWE-362
0
17,545
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 InputHandler::setDelayKeyboardVisibilityChange(bool value) { m_delayKeyboardVisibilityChange = value; m_pendingKeyboardVisibilityChange = NoChange; } Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API https://bugs.webkit.org/show_bug.cgi?id=105143 RIM PR 171941 Reviewed by Rob Buis. Internally reviewed by George Staikos. Source/WebCore: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. Also adapt to new method names and encapsulation of TouchPoint data members. No change in behavior, no new tests. * platform/blackberry/PlatformTouchPointBlackBerry.cpp: (WebCore::PlatformTouchPoint::PlatformTouchPoint): Source/WebKit/blackberry: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. One exception is when passing events to a full screen plugin. Also adapt to new method names and encapsulation of TouchPoint data members. * Api/WebPage.cpp: (BlackBerry::WebKit::WebPage::touchEvent): (BlackBerry::WebKit::WebPage::touchPointAsMouseEvent): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin): * WebKitSupport/InputHandler.cpp: (BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint): * WebKitSupport/InputHandler.h: (InputHandler): * WebKitSupport/TouchEventHandler.cpp: (BlackBerry::WebKit::TouchEventHandler::doFatFingers): (BlackBerry::WebKit::TouchEventHandler::handleTouchPoint): * WebKitSupport/TouchEventHandler.h: (TouchEventHandler): Tools: Adapt to new method names and encapsulation of TouchPoint data members. * DumpRenderTree/blackberry/EventSender.cpp: (addTouchPointCallback): (updateTouchPointCallback): (touchEndCallback): (releaseTouchPointCallback): (sendTouchEvent): git-svn-id: svn://svn.chromium.org/blink/trunk@137880 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
0
15,859
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 __init int fsnotify_init(void) { int ret; BUG_ON(hweight32(ALL_FSNOTIFY_EVENTS) != 23); ret = init_srcu_struct(&fsnotify_mark_srcu); if (ret) panic("initializing fsnotify_mark_srcu"); fsnotify_mark_connector_cachep = KMEM_CACHE(fsnotify_mark_connector, SLAB_PANIC); return 0; } Commit Message: dentry name snapshots take_dentry_name_snapshot() takes a safe snapshot of dentry name; if the name is a short one, it gets copied into caller-supplied structure, otherwise an extra reference to external name is grabbed (those are never modified). In either case the pointer to stable string is stored into the same structure. dentry must be held by the caller of take_dentry_name_snapshot(), but may be freely dropped afterwards - the snapshot will stay until destroyed by release_dentry_name_snapshot(). Intended use: struct name_snapshot s; take_dentry_name_snapshot(&s, dentry); ... access s.name ... release_dentry_name_snapshot(&s); Replaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name to pass down with event. Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> CWE ID: CWE-362
0
10,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: void MPEG4Extractor::populateMetrics() { ALOGV("MPEG4Extractor::populateMetrics"); } Commit Message: Skip track if verification fails Bug: 62187433 Test: ran poc, CTS Change-Id: Ib9b0b6de88d046d8149e9ea5073d6c40ffec7b0c (cherry picked from commit ef8c7830d838d877e6b37b75b47294b064c79397) CWE ID:
0
16,882
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 BlinkTestRunner::DisableAutoResizeMode(const WebSize& new_size) { content::DisableAutoResizeMode(render_view(), new_size); if (!new_size.isEmpty()) ForceResizeRenderView(render_view(), new_size); } Commit Message: content: Rename webkit_test_helpers.{cc,h} to blink_test_helpers.{cc,h} Now that webkit/ is gone, we are preparing ourselves for the merge of third_party/WebKit into //blink. BUG=None BUG=content_shell && content_unittests R=avi@chromium.org Review URL: https://codereview.chromium.org/1118183003 Cr-Commit-Position: refs/heads/master@{#328202} CWE ID: CWE-399
0
15,330
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 RaisesExceptionLongAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); TestObject* impl = V8TestObject::ToImpl(holder); ExceptionState exception_state(info.GetIsolate(), ExceptionState::kGetterContext, "TestObject", "raisesExceptionLongAttribute"); int32_t cpp_value(impl->raisesExceptionLongAttribute(exception_state)); if (UNLIKELY(exception_state.HadException())) return; V8SetReturnValueInt(info, cpp_value); } 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
26,099
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: ChromePluginPrintContext(LocalFrame* frame, WebPluginContainerImpl* plugin, const WebPrintParams& print_params) : ChromePrintContext(frame), plugin_(plugin), print_params_(print_params) {} Commit Message: Inherit CSP when we inherit the security origin This prevents attacks that use main window navigation to get out of the existing csp constraints such as the related bug Bug: 747847 Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8 Reviewed-on: https://chromium-review.googlesource.com/592027 Reviewed-by: Mike West <mkwst@chromium.org> Commit-Queue: Andy Paicu <andypaicu@chromium.org> Cr-Commit-Position: refs/heads/master@{#492333} CWE ID: CWE-732
0
9,456
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: AXObjectCacheImpl::AXObjectCacheImpl(Document& document) : m_document(document), m_modificationCount(0), m_notificationPostTimer( TaskRunnerHelper::get(TaskType::UnspecedTimer, &document), this, &AXObjectCacheImpl::notificationPostTimerFired) {} 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
13,104
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: long keyctl_keyring_search(key_serial_t ringid, const char __user *_type, const char __user *_description, key_serial_t destringid) { struct key_type *ktype; key_ref_t keyring_ref, key_ref, dest_ref; char type[32], *description; long ret; /* pull the type and description into kernel space */ ret = key_get_type_from_user(type, _type, sizeof(type)); if (ret < 0) goto error; description = strndup_user(_description, KEY_MAX_DESC_SIZE); if (IS_ERR(description)) { ret = PTR_ERR(description); goto error; } /* get the keyring at which to begin the search */ keyring_ref = lookup_user_key(ringid, 0, KEY_NEED_SEARCH); if (IS_ERR(keyring_ref)) { ret = PTR_ERR(keyring_ref); goto error2; } /* get the destination keyring if specified */ dest_ref = NULL; if (destringid) { dest_ref = lookup_user_key(destringid, KEY_LOOKUP_CREATE, KEY_NEED_WRITE); if (IS_ERR(dest_ref)) { ret = PTR_ERR(dest_ref); goto error3; } } /* find the key type */ ktype = key_type_lookup(type); if (IS_ERR(ktype)) { ret = PTR_ERR(ktype); goto error4; } /* do the search */ key_ref = keyring_search(keyring_ref, ktype, description); if (IS_ERR(key_ref)) { ret = PTR_ERR(key_ref); /* treat lack or presence of a negative key the same */ if (ret == -EAGAIN) ret = -ENOKEY; goto error5; } /* link the resulting key to the destination keyring if we can */ if (dest_ref) { ret = key_permission(key_ref, KEY_NEED_LINK); if (ret < 0) goto error6; ret = key_link(key_ref_to_ptr(dest_ref), key_ref_to_ptr(key_ref)); if (ret < 0) goto error6; } ret = key_ref_to_ptr(key_ref)->serial; error6: key_ref_put(key_ref); error5: key_type_put(ktype); error4: key_ref_put(dest_ref); error3: key_ref_put(keyring_ref); error2: kfree(description); error: return ret; } Commit Message: KEYS: Fix race between read and revoke This fixes CVE-2015-7550. There's a race between keyctl_read() and keyctl_revoke(). If the revoke happens between keyctl_read() checking the validity of a key and the key's semaphore being taken, then the key type read method will see a revoked key. This causes a problem for the user-defined key type because it assumes in its read method that there will always be a payload in a non-revoked key and doesn't check for a NULL pointer. Fix this by making keyctl_read() check the validity of a key after taking semaphore instead of before. I think the bug was introduced with the original keyrings code. This was discovered by a multithreaded test program generated by syzkaller (http://github.com/google/syzkaller). Here's a cleaned up version: #include <sys/types.h> #include <keyutils.h> #include <pthread.h> void *thr0(void *arg) { key_serial_t key = (unsigned long)arg; keyctl_revoke(key); return 0; } void *thr1(void *arg) { key_serial_t key = (unsigned long)arg; char buffer[16]; keyctl_read(key, buffer, 16); return 0; } int main() { key_serial_t key = add_key("user", "%", "foo", 3, KEY_SPEC_USER_KEYRING); pthread_t th[5]; pthread_create(&th[0], 0, thr0, (void *)(unsigned long)key); pthread_create(&th[1], 0, thr1, (void *)(unsigned long)key); pthread_create(&th[2], 0, thr0, (void *)(unsigned long)key); pthread_create(&th[3], 0, thr1, (void *)(unsigned long)key); pthread_join(th[0], 0); pthread_join(th[1], 0); pthread_join(th[2], 0); pthread_join(th[3], 0); return 0; } Build as: cc -o keyctl-race keyctl-race.c -lkeyutils -lpthread Run as: while keyctl-race; do :; done as it may need several iterations to crash the kernel. The crash can be summarised as: BUG: unable to handle kernel NULL pointer dereference at 0000000000000010 IP: [<ffffffff81279b08>] user_read+0x56/0xa3 ... Call Trace: [<ffffffff81276aa9>] keyctl_read_key+0xb6/0xd7 [<ffffffff81277815>] SyS_keyctl+0x83/0xe0 [<ffffffff815dbb97>] entry_SYSCALL_64_fastpath+0x12/0x6f Reported-by: Dmitry Vyukov <dvyukov@google.com> Signed-off-by: David Howells <dhowells@redhat.com> Tested-by: Dmitry Vyukov <dvyukov@google.com> Cc: stable@vger.kernel.org Signed-off-by: James Morris <james.l.morris@oracle.com> CWE ID: CWE-362
0
26,859
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 net_device_stats *airo_get_stats(struct net_device *dev) { struct airo_info *local = dev->ml_priv; if (!test_bit(JOB_STATS, &local->jobs)) { /* Get stats out of the card if available */ if (down_trylock(&local->sem) != 0) { set_bit(JOB_STATS, &local->jobs); wake_up_interruptible(&local->thr_wait); } else airo_read_stats(dev); } return &dev->stats; } Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared After the last patch, We are left in a state in which only drivers calling ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real hardware call ether_setup for their net_devices and don't hold any state in their skbs. There are a handful of drivers that violate this assumption of course, and need to be fixed up. This patch identifies those drivers, and marks them as not being able to support the safe transmission of skbs by clearning the IFF_TX_SKB_SHARING flag in priv_flags Signed-off-by: Neil Horman <nhorman@tuxdriver.com> CC: Karsten Keil <isdn@linux-pingi.de> CC: "David S. Miller" <davem@davemloft.net> CC: Jay Vosburgh <fubar@us.ibm.com> CC: Andy Gospodarek <andy@greyhouse.net> CC: Patrick McHardy <kaber@trash.net> CC: Krzysztof Halasa <khc@pm.waw.pl> CC: "John W. Linville" <linville@tuxdriver.com> CC: Greg Kroah-Hartman <gregkh@suse.de> CC: Marcel Holtmann <marcel@holtmann.org> CC: Johannes Berg <johannes@sipsolutions.net> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-264
0
23,460
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: http_req_get_intercept_rule(struct proxy *px, struct list *rules, struct session *s, struct http_txn *txn) { struct connection *cli_conn; struct http_req_rule *rule; struct hdr_ctx ctx; const char *auth_realm; list_for_each_entry(rule, rules, list) { if (rule->action >= HTTP_REQ_ACT_MAX) continue; /* check optional condition */ if (rule->cond) { int ret; ret = acl_exec_cond(rule->cond, px, s, txn, SMP_OPT_DIR_REQ|SMP_OPT_FINAL); ret = acl_pass(ret); if (rule->cond->pol == ACL_COND_UNLESS) ret = !ret; if (!ret) /* condition not matched */ continue; } switch (rule->action) { case HTTP_REQ_ACT_ALLOW: return HTTP_RULE_RES_STOP; case HTTP_REQ_ACT_DENY: return HTTP_RULE_RES_DENY; case HTTP_REQ_ACT_TARPIT: txn->flags |= TX_CLTARPIT; return HTTP_RULE_RES_DENY; case HTTP_REQ_ACT_AUTH: /* Auth might be performed on regular http-req rules as well as on stats */ auth_realm = rule->arg.auth.realm; if (!auth_realm) { if (px->uri_auth && rules == &px->uri_auth->http_req_rules) auth_realm = STATS_DEFAULT_REALM; else auth_realm = px->id; } /* send 401/407 depending on whether we use a proxy or not. We still * count one error, because normal browsing won't significantly * increase the counter but brute force attempts will. */ chunk_printf(&trash, (txn->flags & TX_USE_PX_CONN) ? HTTP_407_fmt : HTTP_401_fmt, auth_realm); txn->status = (txn->flags & TX_USE_PX_CONN) ? 407 : 401; stream_int_retnclose(&s->si[0], &trash); session_inc_http_err_ctr(s); return HTTP_RULE_RES_ABRT; case HTTP_REQ_ACT_REDIR: if (!http_apply_redirect_rule(rule->arg.redir, s, txn)) return HTTP_RULE_RES_BADREQ; return HTTP_RULE_RES_DONE; case HTTP_REQ_ACT_SET_NICE: s->task->nice = rule->arg.nice; break; case HTTP_REQ_ACT_SET_TOS: if ((cli_conn = objt_conn(s->req->prod->end)) && conn_ctrl_ready(cli_conn)) inet_set_tos(cli_conn->t.sock.fd, cli_conn->addr.from, rule->arg.tos); break; case HTTP_REQ_ACT_SET_MARK: #ifdef SO_MARK if ((cli_conn = objt_conn(s->req->prod->end)) && conn_ctrl_ready(cli_conn)) setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &rule->arg.mark, sizeof(rule->arg.mark)); #endif break; case HTTP_REQ_ACT_SET_LOGL: s->logs.level = rule->arg.loglevel; break; case HTTP_REQ_ACT_REPLACE_HDR: case HTTP_REQ_ACT_REPLACE_VAL: if (http_transform_header(s, &txn->req, rule->arg.hdr_add.name, rule->arg.hdr_add.name_len, txn->req.chn->buf->p, &txn->hdr_idx, &rule->arg.hdr_add.fmt, &rule->arg.hdr_add.re, &ctx, rule->action)) return HTTP_RULE_RES_BADREQ; break; case HTTP_REQ_ACT_DEL_HDR: case HTTP_REQ_ACT_SET_HDR: ctx.idx = 0; /* remove all occurrences of the header */ while (http_find_header2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len, txn->req.chn->buf->p, &txn->hdr_idx, &ctx)) { http_remove_header2(&txn->req, &txn->hdr_idx, &ctx); } if (rule->action == HTTP_REQ_ACT_DEL_HDR) break; /* now fall through to header addition */ case HTTP_REQ_ACT_ADD_HDR: chunk_printf(&trash, "%s: ", rule->arg.hdr_add.name); memcpy(trash.str, rule->arg.hdr_add.name, rule->arg.hdr_add.name_len); trash.len = rule->arg.hdr_add.name_len; trash.str[trash.len++] = ':'; trash.str[trash.len++] = ' '; trash.len += build_logline(s, trash.str + trash.len, trash.size - trash.len, &rule->arg.hdr_add.fmt); http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.str, trash.len); break; case HTTP_REQ_ACT_DEL_ACL: case HTTP_REQ_ACT_DEL_MAP: { struct pat_ref *ref; char *key; int len; /* collect reference */ ref = pat_ref_lookup(rule->arg.map.ref); if (!ref) continue; /* collect key */ len = build_logline(s, trash.str, trash.size, &rule->arg.map.key); key = trash.str; key[len] = '\0'; /* perform update */ /* returned code: 1=ok, 0=ko */ pat_ref_delete(ref, key); break; } case HTTP_REQ_ACT_ADD_ACL: { struct pat_ref *ref; char *key; struct chunk *trash_key; int len; trash_key = get_trash_chunk(); /* collect reference */ ref = pat_ref_lookup(rule->arg.map.ref); if (!ref) continue; /* collect key */ len = build_logline(s, trash_key->str, trash_key->size, &rule->arg.map.key); key = trash_key->str; key[len] = '\0'; /* perform update */ /* add entry only if it does not already exist */ if (pat_ref_find_elt(ref, key) == NULL) pat_ref_add(ref, key, NULL, NULL); break; } case HTTP_REQ_ACT_SET_MAP: { struct pat_ref *ref; char *key, *value; struct chunk *trash_key, *trash_value; int len; trash_key = get_trash_chunk(); trash_value = get_trash_chunk(); /* collect reference */ ref = pat_ref_lookup(rule->arg.map.ref); if (!ref) continue; /* collect key */ len = build_logline(s, trash_key->str, trash_key->size, &rule->arg.map.key); key = trash_key->str; key[len] = '\0'; /* collect value */ len = build_logline(s, trash_value->str, trash_value->size, &rule->arg.map.value); value = trash_value->str; value[len] = '\0'; /* perform update */ if (pat_ref_find_elt(ref, key) != NULL) /* update entry if it exists */ pat_ref_set(ref, key, value, NULL); else /* insert a new entry */ pat_ref_add(ref, key, value, NULL); break; } case HTTP_REQ_ACT_CUSTOM_CONT: rule->action_ptr(rule, px, s, txn); break; case HTTP_REQ_ACT_CUSTOM_STOP: rule->action_ptr(rule, px, s, txn); return HTTP_RULE_RES_DONE; } } /* we reached the end of the rules, nothing to report */ return HTTP_RULE_RES_CONT; } Commit Message: CWE ID: CWE-189
0
14,655
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 php_zip_ops_close(php_stream *stream, int close_handle TSRMLS_DC) { STREAM_DATA_FROM_STREAM(); if (close_handle) { if (self->zf) { zip_fclose(self->zf); self->zf = NULL; } if (self->za) { zip_close(self->za); self->za = NULL; } } efree(self); stream->abstract = NULL; return EOF; } Commit Message: CWE ID: CWE-119
0
12,050
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 auth_count_scoreboard(cmd_rec *cmd, char *user) { char *key; void *v; pr_scoreboard_entry_t *score = NULL; long cur = 0, hcur = 0, ccur = 0, hostsperuser = 1, usersessions = 0; config_rec *c = NULL, *maxc = NULL; /* First, check to see which Max* directives are configured. If none * are configured, then there is no need for us to needlessly scan the * ScoreboardFile. */ if (have_client_limits(cmd) == FALSE) { return 0; } /* Determine how many users are currently connected. */ /* We use this call to get the possibly-changed user name. */ (void) pr_auth_get_anon_config(cmd->tmp_pool, &user, NULL, NULL); /* Gather our statistics. */ if (user) { char curr_server_addr[80] = {'\0'}; snprintf(curr_server_addr, sizeof(curr_server_addr), "%s:%d", pr_netaddr_get_ipstr(session.c->local_addr), main_server->ServerPort); curr_server_addr[sizeof(curr_server_addr)-1] = '\0'; if (pr_rewind_scoreboard() < 0) { pr_log_pri(PR_LOG_NOTICE, "error rewinding scoreboard: %s", strerror(errno)); } while ((score = pr_scoreboard_entry_read()) != NULL) { unsigned char same_host = FALSE; pr_signals_handle(); /* Make sure it matches our current server. */ if (strcmp(score->sce_server_addr, curr_server_addr) == 0) { if ((c && c->config_type == CONF_ANON && !strcmp(score->sce_user, user)) || !c) { /* This small hack makes sure that cur is incremented properly * when dealing with anonymous logins (the timing of anonymous * login updates to the scoreboard makes this...odd). */ if (c && c->config_type == CONF_ANON && cur == 0) cur = 1; /* Only count authenticated clients, as per the documentation. */ if (strncmp(score->sce_user, "(none)", 7) == 0) continue; cur++; /* Count up sessions on a per-host basis. */ if (!strcmp(score->sce_client_addr, pr_netaddr_get_ipstr(session.c->remote_addr))) { same_host = TRUE; /* This small hack makes sure that hcur is incremented properly * when dealing with anonymous logins (the timing of anonymous * login updates to the scoreboard makes this...odd). */ if (c && c->config_type == CONF_ANON && hcur == 0) hcur = 1; hcur++; } /* Take a per-user count of connections. */ if (strcmp(score->sce_user, user) == 0) { usersessions++; /* Count up unique hosts. */ if (!same_host) hostsperuser++; } } if (session.conn_class != NULL && strcasecmp(score->sce_class, session.conn_class->cls_name) == 0) { ccur++; } } } pr_restore_scoreboard(); PRIVS_RELINQUISH } key = "client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = cur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } if (session.conn_class != NULL) { key = "class-client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = ccur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } } /* Try to determine what MaxClients/MaxHosts limits apply to this session * (if any) and count through the runtime file to see if this limit would * be exceeded. */ maxc = find_config(cmd->server->conf, CONF_PARAM, "MaxClientsPerClass", FALSE); while (session.conn_class != NULL && maxc) { char *maxstr = "Sorry, the maximum number of clients (%m) from your class " "are already connected."; unsigned int *max = maxc->argv[1]; if (strcmp(maxc->argv[0], session.conn_class->cls_name) != 0) { maxc = find_config_next(maxc, maxc->next, CONF_PARAM, "MaxClientsPerClass", FALSE); continue; } if (maxc->argc > 2) maxstr = maxc->argv[2]; if (*max && ccur > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients-per-class", session.conn_class->cls_name); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClientsPerClass %s %u)", session.conn_class->cls_name, *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClientsPerClass"); } break; } maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerHost", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of clients (%m) from your host " "are already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) maxstr = maxc->argv[1]; if (*max && hcur > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients-per-host", session.c); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClientsPerHost %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClientsPerHost"); } } /* Check for any configured MaxClientsPerUser. */ maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerUser", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of clients (%m) for this user " "are already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) maxstr = maxc->argv[1]; if (*max && usersessions > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients-per-user", user); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClientsPerUser %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClientsPerUser"); } } maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClients", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of allowed clients (%m) are " "already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) maxstr = maxc->argv[1]; if (*max && cur > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients", NULL); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClients %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClients"); } } maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxHostsPerUser", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of hosts (%m) for this user are " "already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) maxstr = maxc->argv[1]; if (*max && hostsperuser > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-hosts-per-user", user); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxHostsPerHost %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxHostsPerUser"); } } return 0; } Commit Message: Backporting recursive handling of DefaultRoot path, when AllowChrootSymlinks is off, to 1.3.5 branch. CWE ID: CWE-59
0
6,862
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: XmlReader::XmlReader() : reader_(NULL) { } Commit Message: Roll libxml to 3939178e4cb797417ff033b1e04ab4b038e224d9 Removes a few patches fixed upstream: https://git.gnome.org/browse/libxml2/commit/?id=e26630548e7d138d2c560844c43820b6767251e3 https://git.gnome.org/browse/libxml2/commit/?id=94691dc884d1a8ada39f073408b4bb92fe7fe882 Stops using the NOXXE flag which was reverted upstream: https://git.gnome.org/browse/libxml2/commit/?id=030b1f7a27c22f9237eddca49ec5e620b6258d7d Changes the patch to uri.c to not add limits.h, which is included upstream. Bug: 722079 Change-Id: I4b8449ed33f95de23c54c2cde99970c2df2781ac Reviewed-on: https://chromium-review.googlesource.com/535233 Reviewed-by: Scott Graham <scottmg@chromium.org> Commit-Queue: Dominic Cooney <dominicc@chromium.org> Cr-Commit-Position: refs/heads/master@{#480755} CWE ID: CWE-787
0
6,937
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 activityLoggedAttrGetter2AttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { ExceptionState exceptionState(ExceptionState::SetterContext, "activityLoggedAttrGetter2", "TestObject", info.Holder(), info.GetIsolate()); TestObject* imp = V8TestObject::toNative(info.Holder()); V8TRYCATCH_EXCEPTION_VOID(int, cppValue, toInt32(jsValue, exceptionState), exceptionState); imp->setActivityLoggedAttrGetter2(cppValue); } Commit Message: document.location bindings fix BUG=352374 R=jochen@chromium.org Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
0
26,364
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: marker_to_position (const MARK_ID_POS *m, uint16_t n, int marksize) { int i ; for (i = 0 ; i < marksize ; i++) if (m [i].markerID == n) return m [i].position ; return 0 ; } /* marker_to_position */ Commit Message: src/aiff.c: Fix a buffer read overflow Secunia Advisory SA76717. Found by: Laurent Delosieres, Secunia Research at Flexera Software CWE ID: CWE-119
0
2,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: static int gfs2_open(struct inode *inode, struct file *file) { struct gfs2_inode *ip = GFS2_I(inode); struct gfs2_holder i_gh; int error; bool need_unlock = false; if (S_ISREG(ip->i_inode.i_mode)) { error = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, LM_FLAG_ANY, &i_gh); if (error) return error; need_unlock = true; } error = gfs2_open_common(inode, file); if (need_unlock) gfs2_glock_dq_uninit(&i_gh); return error; } Commit Message: ->splice_write() via ->write_iter() iter_file_splice_write() - a ->splice_write() instance that gathers the pipe buffers, builds a bio_vec-based iov_iter covering those and feeds it to ->write_iter(). A bunch of simple cases coverted to that... [AV: fixed the braino spotted by Cyrill] Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> CWE ID: CWE-264
0
25,707
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: xmlXPtrOriginFunction(xmlXPathParserContextPtr ctxt, int nargs) { CHECK_ARITY(0); if (ctxt->context->origin == NULL) XP_ERROR(XPTR_SYNTAX_ERROR); valuePush(ctxt, xmlXPtrNewLocationSetNodes(ctxt->context->origin, NULL)); } Commit Message: Fix XPointer bug. BUG=125462 AUTHOR=asd@ut.ee R=cevans@chromium.org Review URL: https://chromiumcodereview.appspot.com/10344022 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@135174 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
0
19,913
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 SafeBrowsingPrivateEventRouter::OnDangerousDownloadOpened( const GURL& url, const std::string& file_name, const std::string& download_digest_sha256) { api::safe_browsing_private::DangerousDownloadInfo params; params.url = url.spec(); params.file_name = file_name; params.download_digest_sha256 = download_digest_sha256; params.user_name = GetProfileUserName(); if (event_router_) { auto event_value = std::make_unique<base::ListValue>(); event_value->Append(params.ToValue()); auto extension_event = std::make_unique<Event>( events::SAFE_BROWSING_PRIVATE_ON_DANGEROUS_DOWNLOAD_OPENED, api::safe_browsing_private::OnDangerousDownloadOpened::kEventName, std::move(event_value)); event_router_->BroadcastEvent(std::move(extension_event)); } if (client_) { base::Value event(base::Value::Type::DICTIONARY); event.SetStringKey(kKeyUrl, params.url); event.SetStringKey(kKeyFileName, params.file_name); event.SetStringKey(kKeyDownloadDigestSha256, params.download_digest_sha256); event.SetStringKey(kKeyProfileUserName, params.user_name); ReportRealtimeEvent(kKeyDangerousDownloadEvent, std::move(event)); } } Commit Message: Add reporting for DLP deep scanning For each triggered rule in the DLP response, we report the download as violating that rule. This also implements the UnsafeReportingEnabled enterprise policy, which controls whether or not we do any reporting. Bug: 980777 Change-Id: I48100cfb4dd5aa92ed80da1f34e64a6e393be2fa Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1772381 Commit-Queue: Daniel Rubery <drubery@chromium.org> Reviewed-by: Karan Bhatia <karandeepb@chromium.org> Reviewed-by: Roger Tawa <rogerta@chromium.org> Cr-Commit-Position: refs/heads/master@{#691371} CWE ID: CWE-416
0
16,758
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: mspack_create_chm_decompressor(struct mspack_system *sys) { struct mschm_decompressor_p *self = NULL; if (!sys) sys = mspack_default_system; if (!mspack_valid_system(sys)) return NULL; if ((self = (struct mschm_decompressor_p *) sys->alloc(sys, sizeof(struct mschm_decompressor_p)))) { self->base.open = &chmd_open; self->base.close = &chmd_close; self->base.extract = &chmd_extract; self->base.last_error = &chmd_error; self->base.fast_open = &chmd_fast_open; self->base.fast_find = &chmd_fast_find; self->system = sys; self->error = MSPACK_ERR_OK; self->d = NULL; } return (struct mschm_decompressor *) self; } Commit Message: Avoid returning CHM file entries that are "blank" because they have embedded null bytes CWE ID: CWE-476
0
1,073
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: vips_tracked_init_mutex( void ) { vips_tracked_mutex = vips_g_mutex_new(); } Commit Message: zero memory on malloc to prevent write of uninit memory under some error conditions thanks Balint CWE ID: CWE-200
0
7,670
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 op_attr_bignum_clear(void *attr) { struct bignum **bn = attr; crypto_bignum_clear(*bn); } Commit Message: svc: check for allocation overflow in crypto calls part 2 Without checking for overflow there is a risk of allocating a buffer with size smaller than anticipated and as a consequence of that it might lead to a heap based overflow with attacker controlled data written outside the boundaries of the buffer. Fixes: OP-TEE-2018-0011: "Integer overflow in crypto system calls (x2)" Signed-off-by: Joakim Bech <joakim.bech@linaro.org> Tested-by: Joakim Bech <joakim.bech@linaro.org> (QEMU v7, v8) Reviewed-by: Jens Wiklander <jens.wiklander@linaro.org> Reported-by: Riscure <inforequest@riscure.com> Reported-by: Alyssa Milburn <a.a.milburn@vu.nl> Acked-by: Etienne Carriere <etienne.carriere@linaro.org> CWE ID: CWE-119
0
6,527
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 mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp) { MOVContext *mov = s->priv_data; MOVStreamContext *sc = st->priv_data; int i, j; if (!mov->fragment_index_complete) return 0; for (i = 0; i < mov->fragment_index_count; i++) { if (mov->fragment_index_data[i]->track_id == st->id || !sc->has_sidx) { MOVFragmentIndex *index = mov->fragment_index_data[i]; for (j = index->item_count - 1; j >= 0; j--) { if (index->items[j].time <= timestamp) { if (index->items[j].headers_read) return 0; return mov_switch_root(s, index->items[j].moof_offset); } } } } return 0; } Commit Message: avformat/mov: Fix DoS in read_tfra() 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-834
0
27,162
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_priority(vector_t *strvec, const char *process) { int priority; if (vector_size(strvec) < 2) { report_config_error(CONFIG_GENERAL_ERROR, "No %s process priority specified", process); return 0; } if (!read_int_strvec(strvec, 1, &priority, -20, 19, true)) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid %s process priority specified", process); return 0; } return (int8_t)priority; } Commit Message: Add command line and configuration option to set umask Issue #1048 identified that files created by keepalived are created with mode 0666. This commit changes the default to 0644, and also allows the umask to be specified in the configuration or as a command line option. Signed-off-by: Quentin Armitage <quentin@armitage.org.uk> CWE ID: CWE-200
0
15,486
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: JSObject* createTypeError(ExecState* exec, const UString& message) { return createTypeError(exec->lexicalGlobalObject(), message); } 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
27,947