instruction
stringclasses
1 value
input
stringlengths
56
241k
output
int64
0
1
__index_level_0__
int64
0
175k
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: virDomainReset(virDomainPtr domain, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainReset) { int ret; ret = conn->driver->domainReset(domain, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } Commit Message: virDomainGetTime: Deny on RO connections We have a policy that if API may end up talking to a guest agent it should require RW connection. We don't obey the rule in virDomainGetTime(). Signed-off-by: Michal Privoznik <mprivozn@redhat.com> CWE ID: CWE-254
0
93,901
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: gfx::Point AwContents::GetLocationOnScreen() { DCHECK_CURRENTLY_ON(BrowserThread::UI); JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> obj = java_ref_.get(env); if (obj.is_null()) return gfx::Point(); std::vector<int> location; base::android::JavaIntArrayToIntVector( env, Java_AwContents_getLocationOnScreen(env, obj.obj()).obj(), &location); return gfx::Point(location[0], location[1]); } Commit Message: sync compositor: pass simple gfx types by const ref See bug for reasoning BUG=159273 Review URL: https://codereview.chromium.org/1417893006 Cr-Commit-Position: refs/heads/master@{#356653} CWE ID: CWE-399
0
119,589
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 request *__get_request(struct request_list *rl, unsigned int op, struct bio *bio, blk_mq_req_flags_t flags, gfp_t gfp_mask) { struct request_queue *q = rl->q; struct request *rq; struct elevator_type *et = q->elevator->type; struct io_context *ioc = rq_ioc(bio); struct io_cq *icq = NULL; const bool is_sync = op_is_sync(op); int may_queue; req_flags_t rq_flags = RQF_ALLOCED; lockdep_assert_held(q->queue_lock); if (unlikely(blk_queue_dying(q))) return ERR_PTR(-ENODEV); may_queue = elv_may_queue(q, op); if (may_queue == ELV_MQUEUE_NO) goto rq_starved; if (rl->count[is_sync]+1 >= queue_congestion_on_threshold(q)) { if (rl->count[is_sync]+1 >= q->nr_requests) { /* * The queue will fill after this allocation, so set * it as full, and mark this process as "batching". * This process will be allowed to complete a batch of * requests, others will be blocked. */ if (!blk_rl_full(rl, is_sync)) { ioc_set_batching(q, ioc); blk_set_rl_full(rl, is_sync); } else { if (may_queue != ELV_MQUEUE_MUST && !ioc_batching(q, ioc)) { /* * The queue is full and the allocating * process is not a "batcher", and not * exempted by the IO scheduler */ return ERR_PTR(-ENOMEM); } } } blk_set_congested(rl, is_sync); } /* * Only allow batching queuers to allocate up to 50% over the defined * limit of requests, otherwise we could have thousands of requests * allocated with any setting of ->nr_requests */ if (rl->count[is_sync] >= (3 * q->nr_requests / 2)) return ERR_PTR(-ENOMEM); q->nr_rqs[is_sync]++; rl->count[is_sync]++; rl->starved[is_sync] = 0; /* * Decide whether the new request will be managed by elevator. If * so, mark @rq_flags and increment elvpriv. Non-zero elvpriv will * prevent the current elevator from being destroyed until the new * request is freed. This guarantees icq's won't be destroyed and * makes creating new ones safe. * * Flush requests do not use the elevator so skip initialization. * This allows a request to share the flush and elevator data. * * Also, lookup icq while holding queue_lock. If it doesn't exist, * it will be created after releasing queue_lock. */ if (!op_is_flush(op) && !blk_queue_bypass(q)) { rq_flags |= RQF_ELVPRIV; q->nr_rqs_elvpriv++; if (et->icq_cache && ioc) icq = ioc_lookup_icq(ioc, q); } if (blk_queue_io_stat(q)) rq_flags |= RQF_IO_STAT; spin_unlock_irq(q->queue_lock); /* allocate and init request */ rq = mempool_alloc(rl->rq_pool, gfp_mask); if (!rq) goto fail_alloc; blk_rq_init(q, rq); blk_rq_set_rl(rq, rl); rq->cmd_flags = op; rq->rq_flags = rq_flags; if (flags & BLK_MQ_REQ_PREEMPT) rq->rq_flags |= RQF_PREEMPT; /* init elvpriv */ if (rq_flags & RQF_ELVPRIV) { if (unlikely(et->icq_cache && !icq)) { if (ioc) icq = ioc_create_icq(ioc, q, gfp_mask); if (!icq) goto fail_elvpriv; } rq->elv.icq = icq; if (unlikely(elv_set_request(q, rq, bio, gfp_mask))) goto fail_elvpriv; /* @rq->elv.icq holds io_context until @rq is freed */ if (icq) get_io_context(icq->ioc); } out: /* * ioc may be NULL here, and ioc_batching will be false. That's * OK, if the queue is under the request limit then requests need * not count toward the nr_batch_requests limit. There will always * be some limit enforced by BLK_BATCH_TIME. */ if (ioc_batching(q, ioc)) ioc->nr_batch_requests--; trace_block_getrq(q, bio, op); return rq; fail_elvpriv: /* * elvpriv init failed. ioc, icq and elvpriv aren't mempool backed * and may fail indefinitely under memory pressure and thus * shouldn't stall IO. Treat this request as !elvpriv. This will * disturb iosched and blkcg but weird is bettern than dead. */ printk_ratelimited(KERN_WARNING "%s: dev %s: request aux data allocation failed, iosched may be disturbed\n", __func__, dev_name(q->backing_dev_info->dev)); rq->rq_flags &= ~RQF_ELVPRIV; rq->elv.icq = NULL; spin_lock_irq(q->queue_lock); q->nr_rqs_elvpriv--; spin_unlock_irq(q->queue_lock); goto out; fail_alloc: /* * Allocation failed presumably due to memory. Undo anything we * might have messed up. * * Allocating task should really be put onto the front of the wait * queue, but this is pretty rare. */ spin_lock_irq(q->queue_lock); freed_request(rl, is_sync, rq_flags); /* * in the very unlikely event that allocation failed and no * requests for this direction was pending, mark us starved so that * freeing of a request in the other direction will notice * us. another possible fix would be to split the rq mempool into * READ and WRITE */ rq_starved: if (unlikely(rl->count[is_sync] == 0)) rl->starved[is_sync] = 1; return ERR_PTR(-ENOMEM); } Commit Message: block: blk_init_allocated_queue() set q->fq as NULL in the fail case We find the memory use-after-free issue in __blk_drain_queue() on the kernel 4.14. After read the latest kernel 4.18-rc6 we think it has the same problem. Memory is allocated for q->fq in the blk_init_allocated_queue(). If the elevator init function called with error return, it will run into the fail case to free the q->fq. Then the __blk_drain_queue() uses the same memory after the free of the q->fq, it will lead to the unpredictable event. The patch is to set q->fq as NULL in the fail case of blk_init_allocated_queue(). Fixes: commit 7c94e1c157a2 ("block: introduce blk_flush_queue to drive flush machinery") Cc: <stable@vger.kernel.org> Reviewed-by: Ming Lei <ming.lei@redhat.com> Reviewed-by: Bart Van Assche <bart.vanassche@wdc.com> Signed-off-by: xiao jin <jin.xiao@intel.com> Signed-off-by: Jens Axboe <axboe@kernel.dk> CWE ID: CWE-416
0
91,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: static void WriteIndices(Image *image, const DDSVector3 start, const DDSVector3 end, unsigned char* indices) { register ssize_t i; size_t a, b; unsigned char remapped[16]; const unsigned char *ind; a = ColorTo565(start); b = ColorTo565(end); for (i=0; i<16; i++) { if( a < b ) remapped[i] = (indices[i] ^ 0x1) & 0x3; else if( a == b ) remapped[i] = 0; else remapped[i] = indices[i]; } if( a < b ) Swap(a,b); (void) WriteBlobByte(image,(unsigned char) (a & 0xff)); (void) WriteBlobByte(image,(unsigned char) (a >> 8)); (void) WriteBlobByte(image,(unsigned char) (b & 0xff)); (void) WriteBlobByte(image,(unsigned char) (b >> 8)); for (i=0; i<4; i++) { ind = remapped + 4*i; (void) WriteBlobByte(image,ind[0] | (ind[1] << 2) | (ind[2] << 4) | (ind[3] << 6)); } } Commit Message: Added check to prevent image being 0x0 (reported in #489). CWE ID: CWE-20
0
65,132
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static inline u64 btrfs_inc_tree_mod_seq(struct btrfs_fs_info *fs_info) { return atomic64_inc_return(&fs_info->tree_mod_seq); } 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
45,305
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 page_referenced(struct page *page, int is_locked, struct mem_cgroup *memcg, unsigned long *vm_flags) { int ret; int we_locked = 0; struct page_referenced_arg pra = { .mapcount = page_mapcount(page), .memcg = memcg, }; struct rmap_walk_control rwc = { .rmap_one = page_referenced_one, .arg = (void *)&pra, .anon_lock = page_lock_anon_vma_read, }; *vm_flags = 0; if (!page_mapped(page)) return 0; if (!page_rmapping(page)) return 0; if (!is_locked && (!PageAnon(page) || PageKsm(page))) { we_locked = trylock_page(page); if (!we_locked) return 1; } /* * If we are reclaiming on behalf of a cgroup, skip * counting on behalf of references from different * cgroups */ if (memcg) { rwc.invalid_vma = invalid_page_referenced_vma; } ret = rmap_walk(page, &rwc); *vm_flags = pra.vm_flags; if (we_locked) unlock_page(page); return pra.referenced; } Commit Message: mm: try_to_unmap_cluster() should lock_page() before mlocking A BUG_ON(!PageLocked) was triggered in mlock_vma_page() by Sasha Levin fuzzing with trinity. The call site try_to_unmap_cluster() does not lock the pages other than its check_page parameter (which is already locked). The BUG_ON in mlock_vma_page() is not documented and its purpose is somewhat unclear, but apparently it serializes against page migration, which could otherwise fail to transfer the PG_mlocked flag. This would not be fatal, as the page would be eventually encountered again, but NR_MLOCK accounting would become distorted nevertheless. This patch adds a comment to the BUG_ON in mlock_vma_page() and munlock_vma_page() to that effect. The call site try_to_unmap_cluster() is fixed so that for page != check_page, trylock_page() is attempted (to avoid possible deadlocks as we already have check_page locked) and mlock_vma_page() is performed only upon success. If the page lock cannot be obtained, the page is left without PG_mlocked, which is again not a problem in the whole unevictable memory design. Signed-off-by: Vlastimil Babka <vbabka@suse.cz> Signed-off-by: Bob Liu <bob.liu@oracle.com> Reported-by: Sasha Levin <sasha.levin@oracle.com> Cc: Wanpeng Li <liwanp@linux.vnet.ibm.com> Cc: Michel Lespinasse <walken@google.com> Cc: KOSAKI Motohiro <kosaki.motohiro@jp.fujitsu.com> Acked-by: Rik van Riel <riel@redhat.com> Cc: David Rientjes <rientjes@google.com> Cc: Mel Gorman <mgorman@suse.de> Cc: Hugh Dickins <hughd@google.com> Cc: Joonsoo Kim <iamjoonsoo.kim@lge.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-264
0
38,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: OxideQQuickWebView::ContentType OxideQQuickWebView::blockedContent() const { Q_D(const OxideQQuickWebView); Q_STATIC_ASSERT( ContentTypeNone == static_cast<ContentTypeFlags>(oxide::qt::CONTENT_TYPE_NONE)); Q_STATIC_ASSERT( ContentTypeMixedDisplay == static_cast<ContentTypeFlags>(oxide::qt::CONTENT_TYPE_MIXED_DISPLAY)); Q_STATIC_ASSERT( ContentTypeMixedScript == static_cast<ContentTypeFlags>(oxide::qt::CONTENT_TYPE_MIXED_SCRIPT)); if (!d->proxy_) { return ContentTypeNone; } return static_cast<ContentType>(d->proxy_->blockedContent()); } Commit Message: CWE ID: CWE-20
0
17,069
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 MemBackendImpl::CalculateSizeOfEntriesBetween( base::Time initial_time, base::Time end_time, const CompletionCallback& callback) { if (end_time.is_null()) end_time = Time::Max(); DCHECK_GE(end_time, initial_time); int size = 0; base::LinkNode<MemEntryImpl>* node = lru_list_.head(); while (node != lru_list_.end() && node->value()->GetLastUsed() < initial_time) node = node->next(); while (node != lru_list_.end() && node->value()->GetLastUsed() < end_time) { MemEntryImpl* entry = node->value(); size += entry->GetStorageSize(); node = node->next(); } return size; } Commit Message: [MemCache] Fix bug while iterating LRU list in eviction It was possible to reanalyze a previously doomed entry. Bug: 827492 Change-Id: I5d34d2ae87c96e0d2099e926e6eb2c1b30b01d63 Reviewed-on: https://chromium-review.googlesource.com/987919 Commit-Queue: Josh Karlin <jkarlin@chromium.org> Reviewed-by: Maks Orlovich <morlovich@chromium.org> Cr-Commit-Position: refs/heads/master@{#547236} CWE ID: CWE-416
0
147,359
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: R_API RBinFile *r_bin_file_new(RBin *bin, const char *file, const ut8 *bytes, ut64 sz, ut64 file_sz, int rawstr, int fd, const char *xtrname, Sdb *sdb, bool steal_ptr) { RBinFile *binfile = R_NEW0 (RBinFile); if (!binfile) { return NULL; } if (!r_id_pool_grab_id (bin->file_ids, &binfile->id)) { if (steal_ptr) { // we own the ptr, free on error free ((void*) bytes); } free (binfile); //no id means no binfile return NULL; } int res = r_bin_file_set_bytes (binfile, bytes, sz, steal_ptr); if (!res && steal_ptr) { // we own the ptr, free on error free((void*) bytes); } binfile->rbin = bin; binfile->file = file? strdup (file): NULL; binfile->rawstr = rawstr; binfile->fd = fd; binfile->curxtr = r_bin_get_xtrplugin_by_name (bin, xtrname); binfile->sdb = sdb; binfile->size = file_sz; binfile->xtr_data = r_list_newf ((RListFree)r_bin_xtrdata_free); binfile->objs = r_list_newf ((RListFree)r_bin_object_free); binfile->xtr_obj = NULL; if (!binfile->buf) { binfile->buf = r_buf_new (); } if (sdb) { binfile->sdb = sdb_ns (sdb, sdb_fmt ("fd.%d", fd), 1); sdb_set (binfile->sdb, "archs", "0:0:x86:32", 0); // x86?? /* NOTE */ /* Those refs++ are necessary because sdb_ns() doesnt rerefs all * sub-namespaces */ /* And if any namespace is referenced backwards it gets * double-freed */ binfile->sdb_addrinfo = sdb_ns (binfile->sdb, "addrinfo", 1); binfile->sdb_addrinfo->refs++; sdb_ns_set (sdb, "cur", binfile->sdb); binfile->sdb->refs++; } return binfile; } Commit Message: Fix #9902 - Fix oobread in RBin.string_scan_range CWE ID: CWE-125
0
82,812
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 DevToolsWindow::DoAction() { UpdateFrontendDockSide(); switch (action_on_load_.type()) { case DevToolsToggleAction::kShowConsole: CallClientFunction("InspectorFrontendAPI.showConsole", NULL, NULL, NULL); break; case DevToolsToggleAction::kInspect: CallClientFunction("InspectorFrontendAPI.enterInspectElementMode", NULL, NULL, NULL); break; case DevToolsToggleAction::kShow: case DevToolsToggleAction::kToggle: break; case DevToolsToggleAction::kReveal: { const DevToolsToggleAction::RevealParams* params = action_on_load_.params(); CHECK(params); base::StringValue url_value(params->url); base::FundamentalValue line_value(static_cast<int>(params->line_number)); base::FundamentalValue column_value( static_cast<int>(params->column_number)); CallClientFunction("InspectorFrontendAPI.revealSourceLine", &url_value, &line_value, &column_value); break; } default: NOTREACHED(); break; } action_on_load_ = DevToolsToggleAction::Show(); } Commit Message: DevTools: handle devtools renderer unresponsiveness during beforeunload event interception This patch fixes the crash which happenes under the following conditions: 1. DevTools window is in undocked state 2. DevTools renderer is unresponsive 3. User attempts to close inspected page BUG=322380 Review URL: https://codereview.chromium.org/84883002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@237611 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
0
113,144
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: file_getbuffer(struct magic_set *ms) { char *pbuf, *op, *np; size_t psize, len; if (ms->event_flags & EVENT_HAD_ERR) return NULL; if (ms->flags & MAGIC_RAW) return ms->o.buf; if (ms->o.buf == NULL) return NULL; /* * 4 is for octal representation, + 1 is for NUL */ len = strlen(ms->o.buf); if (len > (SIZE_MAX - 1) / 4) { file_oomem(ms, len); return NULL; } psize = len * 4 + 1; if ((pbuf = CAST(char *, realloc(ms->o.pbuf, psize))) == NULL) { file_oomem(ms, psize); return NULL; } ms->o.pbuf = pbuf; #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH) { mbstate_t state; wchar_t nextchar; int mb_conv = 1; size_t bytesconsumed; char *eop; (void)memset(&state, 0, sizeof(mbstate_t)); np = ms->o.pbuf; op = ms->o.buf; eop = op + len; while (op < eop) { bytesconsumed = mbrtowc(&nextchar, op, (size_t)(eop - op), &state); if (bytesconsumed == (size_t)(-1) || bytesconsumed == (size_t)(-2)) { mb_conv = 0; break; } if (iswprint(nextchar)) { (void)memcpy(np, op, bytesconsumed); op += bytesconsumed; np += bytesconsumed; } else { while (bytesconsumed-- > 0) OCTALIFY(np, op); } } *np = '\0'; /* Parsing succeeded as a multi-byte sequence */ if (mb_conv != 0) return ms->o.pbuf; } #endif for (np = ms->o.pbuf, op = ms->o.buf; *op;) { if (isprint((unsigned char)*op)) { *np++ = *op++; } else { OCTALIFY(np, op); } } *np = '\0'; return ms->o.pbuf; } Commit Message: - reduce recursion level from 20 to 10 and make a symbolic constant for it. - pull out the guts of saving and restoring the output buffer into functions and take care not to overwrite the error message if an error happened. CWE ID: CWE-399
0
35,637
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: asn1_der_decoding (asn1_node * element, const void *ider, int ider_len, char *errorDescription) { return asn1_der_decoding2 (element, ider, &ider_len, 0, errorDescription); } Commit Message: CWE ID: CWE-399
0
11,282
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_INI_MH(OnUpdateDecode) { if (new_value) { const zend_encoding **return_list; size_t return_size; if (FAILURE == zend_multibyte_parse_encoding_list(new_value, new_value_length, &return_list, &return_size, 0 TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Illegal encoding ignored: '%s'", new_value); return FAILURE; } efree(return_list); } return OnUpdateString(entry, new_value, new_value_length, mh_arg1, mh_arg2, mh_arg3, stage TSRMLS_CC); } Commit Message: CWE ID:
0
6,401
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: UsbTabHelper::GetPermissionProvider(RenderFrameHost* render_frame_host) { FrameUsbServices* frame_usb_services = GetFrameUsbService(render_frame_host); if (!frame_usb_services->permission_provider) { frame_usb_services->permission_provider.reset( new WebUSBPermissionProvider(render_frame_host)); } return frame_usb_services->permission_provider->GetWeakPtr(); } Commit Message: Ensure device choosers are closed on navigation The requestDevice() IPCs can race with navigation. This change ensures that choosers are closed on navigation and adds browser tests to exercise this for Web Bluetooth and WebUSB. Bug: 723503 Change-Id: I66760161220e17bd2be9309cca228d161fe76e9c Reviewed-on: https://chromium-review.googlesource.com/1099961 Commit-Queue: Reilly Grant <reillyg@chromium.org> Reviewed-by: Michael Wasserman <msw@chromium.org> Reviewed-by: Jeffrey Yasskin <jyasskin@chromium.org> Cr-Commit-Position: refs/heads/master@{#569900} CWE ID: CWE-362
0
155,090
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 Textfield::SetReadOnly(bool read_only) { read_only_ = read_only; if (GetInputMethod()) GetInputMethod()->OnTextInputTypeChanged(this); SetColor(GetTextColor()); UpdateBackgroundColor(); } Commit Message: MacViews: Enable secure text input for password Textfields. In Cocoa the NSTextInputContext automatically enables secure text input when activated and it's in the secure text entry mode. RenderWidgetHostViewMac did the similar thing for ages following the WebKit example. views::Textfield needs to do the same thing in a fashion that's sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions are possible when the Textfield gets focus, activates the secure text input mode and the RWHVM loses focus immediately afterwards and disables the secure text input instead of leaving it in the enabled state. BUG=818133,677220 Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b Reviewed-on: https://chromium-review.googlesource.com/943064 Commit-Queue: Michail Pishchagin <mblsha@yandex-team.ru> Reviewed-by: Pavel Feldman <pfeldman@chromium.org> Reviewed-by: Avi Drissman <avi@chromium.org> Reviewed-by: Peter Kasting <pkasting@chromium.org> Cr-Commit-Position: refs/heads/master@{#542517} CWE ID:
0
126,424
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 gint on_key_press_event_in_item_list(GtkTreeView *treeview, GdkEventKey *key, gpointer unused) { int k = key->keyval; if (k == GDK_KEY_Delete || k == GDK_KEY_KP_Delete) { delete_item(treeview); return TRUE; } return FALSE; } Commit Message: wizard: fix save users changes after reviewing dump dir files If the user reviewed the dump dir's files during reporting the crash, the changes was thrown away and original data was passed to the bugzilla bug report. report-gtk saves the first text view buffer and then reloads data from the reported problem directory, which causes that the changes made to those text views are thrown away. Function save_text_if_changed(), except of saving text, also reload the files from dump dir and update gui state from the dump dir. The commit moves the reloading and updating gui functions away from this function. Related to rhbz#1270235 Signed-off-by: Matej Habrnal <mhabrnal@redhat.com> CWE ID: CWE-200
0
42,847
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void Curl_up_free(struct Curl_easy *data) { struct urlpieces *up = &data->state.up; Curl_safefree(up->scheme); Curl_safefree(up->hostname); Curl_safefree(up->port); Curl_safefree(up->user); Curl_safefree(up->password); Curl_safefree(up->options); Curl_safefree(up->path); Curl_safefree(up->query); curl_url_cleanup(data->state.uh); data->state.uh = NULL; } 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
77,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: size_t HTMLSelectElement::searchOptionsForValue(const String& value, size_t listIndexStart, size_t listIndexEnd) const { const Vector<HTMLElement*>& items = listItems(); size_t loopEndIndex = std::min(items.size(), listIndexEnd); for (size_t i = listIndexStart; i < loopEndIndex; ++i) { if (!items[i]->hasLocalName(optionTag)) continue; if (toHTMLOptionElement(items[i])->value() == value) return i; } return notFound; } Commit Message: SelectElement should remove an option when null is assigned by indexed setter Fix bug embedded in r151449 see http://src.chromium.org/viewvc/blink?revision=151449&view=revision R=haraken@chromium.org, tkent@chromium.org, eseidel@chromium.org BUG=262365 TEST=fast/forms/select/select-assign-null.html Review URL: https://chromiumcodereview.appspot.com/19947008 git-svn-id: svn://svn.chromium.org/blink/trunk@154743 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-125
0
103,105
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 VoidMethodDefaultNullableTestInterfaceArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { TestObject* impl = V8TestObject::ToImpl(info.Holder()); TestInterfaceImplementation* default_test_interface_arg; if (!info[0]->IsUndefined()) { default_test_interface_arg = V8TestInterface::ToImplWithTypeCheck(info.GetIsolate(), info[0]); if (!default_test_interface_arg && !IsUndefinedOrNull(info[0])) { V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::FailedToExecute("voidMethodDefaultNullableTestInterfaceArg", "TestObject", ExceptionMessages::ArgumentNotOfType(0, "TestInterface"))); return; } } else { default_test_interface_arg = nullptr; } impl->voidMethodDefaultNullableTestInterfaceArg(default_test_interface_arg); } 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
135,383
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: WandExport void ProcessScriptOptions(MagickCLI *cli_wand,const char *filename, int argc,char **argv,int index) { ScriptTokenInfo *token_info; CommandOptionFlags option_type; int count; char *option, *arg1, *arg2; assert(filename != (char *) NULL ); /* at least one argument - script name */ assert(cli_wand != (MagickCLI *) NULL); assert(cli_wand->signature == MagickWandSignature); if (cli_wand->wand.debug != MagickFalse) (void) LogMagickEvent(CommandEvent,GetMagickModule(), "Processing script \"%s\"", filename); /* open file script or stream, and set up tokenizer */ token_info = AcquireScriptTokenInfo(filename); if (token_info == (ScriptTokenInfo *) NULL) { CLIWandExceptionFile(OptionFatalError,"UnableToOpenScript",filename); return; } /* define the error location string for use in exceptions order of localtion format escapes: filename, line, column */ cli_wand->location="in \"%s\" at line %u,column %u"; if ( LocaleCompare("-", filename) == 0 ) cli_wand->filename="stdin"; else cli_wand->filename=filename; /* Process Options from Script */ option = arg1 = arg2 = (char*) NULL; DisableMSCWarning(4127) while (1) { RestoreMSCWarning { MagickBooleanType status = GetScriptToken(token_info); cli_wand->line=token_info->token_line; cli_wand->column=token_info->token_column; if (status == MagickFalse) break; /* error or end of options */ } do { /* use break to loop to exception handler and loop */ /* save option details */ CloneString(&option,token_info->token); /* get option, its argument count, and option type */ cli_wand->command = GetCommandOptionInfo(option); count=cli_wand->command->type; option_type=(CommandOptionFlags) cli_wand->command->flags; #if 0 (void) FormatLocaleFile(stderr, "Script: %u,%u: \"%s\" matched \"%s\"\n", cli_wand->line, cli_wand->line, option, cli_wand->command->mnemonic ); #endif /* handle a undefined option - image read - always for "magick-script" */ if ( option_type == UndefinedOptionFlag || (option_type & NonMagickOptionFlag) != 0 ) { #if MagickCommandDebug >= 3 (void) FormatLocaleFile(stderr, "Script %u,%u Non-Option: \"%s\"\n", cli_wand->line, cli_wand->line, option); #endif if (IsCommandOption(option) == MagickFalse) { /* non-option -- treat as a image read */ cli_wand->command=(const OptionInfo *) NULL; CLIOption(cli_wand,"-read",option); break; /* next option */ } CLIWandException(OptionFatalError,"UnrecognizedOption",option); break; /* next option */ } if ( count >= 1 ) { if (GetScriptToken(token_info) == MagickFalse) CLIWandException(OptionFatalError,"MissingArgument",option); CloneString(&arg1,token_info->token); } else CloneString(&arg1,(char *) NULL); if ( count >= 2 ) { if (GetScriptToken(token_info) == MagickFalse) CLIWandExceptionBreak(OptionFatalError,"MissingArgument",option); CloneString(&arg2,token_info->token); } else CloneString(&arg2,(char *) NULL); /* Process Options */ #if MagickCommandDebug >= 3 (void) FormatLocaleFile(stderr, "Script %u,%u Option: \"%s\" Count: %d Flags: %04x Args: \"%s\" \"%s\"\n", cli_wand->line,cli_wand->line,option,count,option_type,arg1,arg2); #endif /* Hard Deprecated Options, no code to execute - error */ if ( (option_type & DeprecateOptionFlag) != 0 ) { CLIWandException(OptionError,"DeprecatedOptionNoCode",option); break; /* next option */ } /* MagickCommandGenesis() options have no place in a magick script */ if ( (option_type & GenesisOptionFlag) != 0 ) { CLIWandException(OptionError,"InvalidUseOfOption",option); break; /* next option */ } /* handle any special 'script' options */ if ( (option_type & SpecialOptionFlag) != 0 ) { if ( LocaleCompare(option,"-exit") == 0 ) { goto loop_exit; /* break out of loop - return from script */ } if ( LocaleCompare(option,"-script") == 0 ) { /* FUTURE: call new script from this script - error for now */ CLIWandException(OptionError,"InvalidUseOfOption",option); break; /* next option */ } /* FUTURE: handle special script-argument options here */ /* handle any other special operators now */ CLIWandException(OptionError,"InvalidUseOfOption",option); break; /* next option */ } /* Process non-specific Option */ CLIOption(cli_wand, option, arg1, arg2); (void) fflush(stdout); (void) fflush(stderr); DisableMSCWarning(4127) } while (0); /* break block to next option */ RestoreMSCWarning #if MagickCommandDebug >= 5 fprintf(stderr, "Script Image Count = %ld\n", GetImageListLength(cli_wand->wand.images) ); #endif if (CLICatchException(cli_wand, MagickFalse) != MagickFalse) break; /* exit loop */ } /* Loop exit - check for some tokenization error */ loop_exit: #if MagickCommandDebug >= 3 (void) FormatLocaleFile(stderr, "Script End: %d\n", token_info->status); #endif switch( token_info->status ) { case TokenStatusOK: case TokenStatusEOF: if (cli_wand->image_list_stack != (Stack *) NULL) CLIWandException(OptionError,"UnbalancedParenthesis", "(eof)"); else if (cli_wand->image_info_stack != (Stack *) NULL) CLIWandException(OptionError,"UnbalancedBraces", "(eof)"); break; case TokenStatusBadQuotes: /* Ensure last token has a sane length for error report */ if( strlen(token_info->token) > INITAL_TOKEN_LENGTH-1 ) { token_info->token[INITAL_TOKEN_LENGTH-4] = '.'; token_info->token[INITAL_TOKEN_LENGTH-3] = '.'; token_info->token[INITAL_TOKEN_LENGTH-2] = '.'; token_info->token[INITAL_TOKEN_LENGTH-1] = '\0'; } CLIWandException(OptionFatalError,"ScriptUnbalancedQuotes", token_info->token); break; case TokenStatusMemoryFailed: CLIWandException(OptionFatalError,"ScriptTokenMemoryFailed",""); break; case TokenStatusBinary: CLIWandException(OptionFatalError,"ScriptIsBinary",""); break; } (void) fflush(stdout); (void) fflush(stderr); if (cli_wand->wand.debug != MagickFalse) (void) LogMagickEvent(CommandEvent,GetMagickModule(), "Script End \"%s\"", filename); /* Clean up */ token_info = DestroyScriptTokenInfo(token_info); CloneString(&option,(char *) NULL); CloneString(&arg1,(char *) NULL); CloneString(&arg2,(char *) NULL); return; } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/196 CWE ID: CWE-20
0
71,915
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: Track::~Track() { Info& info = const_cast<Info&>(m_info); info.Clear(); ContentEncoding** i = content_encoding_entries_; ContentEncoding** const j = content_encoding_entries_end_; while (i != j) { ContentEncoding* const encoding = *i++; delete encoding; } delete [] content_encoding_entries_; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
1
174,472
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 mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFTrack *track = arg; switch(tag) { case 0x4801: track->track_id = avio_rb32(pb); break; case 0x4804: avio_read(pb, track->track_number, 4); break; case 0x4802: mxf_read_utf16be_string(pb, size, &track->name); break; case 0x4b01: track->edit_rate.num = avio_rb32(pb); track->edit_rate.den = avio_rb32(pb); break; case 0x4803: avio_read(pb, track->sequence_ref, 16); break; } return 0; } Commit Message: avformat/mxfdec: Fix DoS issues in mxf_read_index_entry_array() Fixes: 20170829A.mxf Co-Author: 张洪亮(望初)" <wangchu.zhl@alibaba-inc.com> Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-834
0
61,618
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int pfkey_xfrm_policy2msg_size(const struct xfrm_policy *xp) { const struct xfrm_tmpl *t; int sockaddr_size = pfkey_sockaddr_size(xp->family); int socklen = 0; int i; for (i=0; i<xp->xfrm_nr; i++) { t = xp->xfrm_vec + i; socklen += pfkey_sockaddr_len(t->encap_family); } return sizeof(struct sadb_msg) + (sizeof(struct sadb_lifetime) * 3) + (sizeof(struct sadb_address) * 2) + (sockaddr_size * 2) + sizeof(struct sadb_x_policy) + (xp->xfrm_nr * sizeof(struct sadb_x_ipsecrequest)) + (socklen * 2) + pfkey_xfrm_policy2sec_ctx_size(xp); } Commit Message: af_key: initialize satype in key_notify_policy_flush() This field was left uninitialized. Some user daemons perform check against this field. Signed-off-by: Nicolas Dichtel <nicolas.dichtel@6wind.com> Signed-off-by: Steffen Klassert <steffen.klassert@secunet.com> CWE ID: CWE-119
0
31,475
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 perf_event_task_tick(void) { struct list_head *head = &__get_cpu_var(rotation_list); struct perf_cpu_context *cpuctx, *tmp; struct perf_event_context *ctx; int throttled; WARN_ON(!irqs_disabled()); __this_cpu_inc(perf_throttled_seq); throttled = __this_cpu_xchg(perf_throttled_count, 0); list_for_each_entry_safe(cpuctx, tmp, head, rotation_list) { ctx = &cpuctx->ctx; perf_adjust_freq_unthr_context(ctx, throttled); ctx = cpuctx->task_ctx; if (ctx) perf_adjust_freq_unthr_context(ctx, throttled); if (cpuctx->jiffies_interval == 1 || !(jiffies % cpuctx->jiffies_interval)) perf_rotate_context(cpuctx); } } Commit Message: perf: Treat attr.config as u64 in perf_swevent_init() Trinity discovered that we fail to check all 64 bits of attr.config passed by user space, resulting to out-of-bounds access of the perf_swevent_enabled array in sw_perf_event_destroy(). Introduced in commit b0a873ebb ("perf: Register PMU implementations"). Signed-off-by: Tommi Rantala <tt.rantala@gmail.com> Cc: Peter Zijlstra <a.p.zijlstra@chello.nl> Cc: davej@redhat.com Cc: Paul Mackerras <paulus@samba.org> Cc: Arnaldo Carvalho de Melo <acme@ghostprotocols.net> Link: http://lkml.kernel.org/r/1365882554-30259-1-git-send-email-tt.rantala@gmail.com Signed-off-by: Ingo Molnar <mingo@kernel.org> CWE ID: CWE-189
0
31,955
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 RenderView::didReceiveDocumentData( WebFrame* frame, const char* data, size_t data_len, bool& prevent_default) { NavigationState* navigation_state = NavigationState::FromDataSource(frame->dataSource()); navigation_state->set_use_error_page(false); } Commit Message: DevTools: move DevToolsAgent/Client into content. BUG=84078 TEST= Review URL: http://codereview.chromium.org/7461019 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
0
99,019
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void save_state_to_tss32(struct x86_emulate_ctxt *ctxt, struct tss_segment_32 *tss) { /* CR3 and ldt selector are not saved intentionally */ tss->eip = ctxt->_eip; tss->eflags = ctxt->eflags; tss->eax = reg_read(ctxt, VCPU_REGS_RAX); tss->ecx = reg_read(ctxt, VCPU_REGS_RCX); tss->edx = reg_read(ctxt, VCPU_REGS_RDX); tss->ebx = reg_read(ctxt, VCPU_REGS_RBX); tss->esp = reg_read(ctxt, VCPU_REGS_RSP); tss->ebp = reg_read(ctxt, VCPU_REGS_RBP); tss->esi = reg_read(ctxt, VCPU_REGS_RSI); tss->edi = reg_read(ctxt, VCPU_REGS_RDI); tss->es = get_segment_selector(ctxt, VCPU_SREG_ES); tss->cs = get_segment_selector(ctxt, VCPU_SREG_CS); tss->ss = get_segment_selector(ctxt, VCPU_SREG_SS); tss->ds = get_segment_selector(ctxt, VCPU_SREG_DS); tss->fs = get_segment_selector(ctxt, VCPU_SREG_FS); tss->gs = get_segment_selector(ctxt, VCPU_SREG_GS); } Commit Message: KVM: emulate: avoid accessing NULL ctxt->memopp A failure to decode the instruction can cause a NULL pointer access. This is fixed simply by moving the "done" label as close as possible to the return. This fixes CVE-2014-8481. Reported-by: Andy Lutomirski <luto@amacapital.net> Cc: stable@vger.kernel.org Fixes: 41061cdb98a0bec464278b4db8e894a3121671f5 Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> CWE ID: CWE-399
0
35,598
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int ext4_map_blocks(handle_t *handle, struct inode *inode, struct ext4_map_blocks *map, int flags) { struct extent_status es; int retval; int ret = 0; #ifdef ES_AGGRESSIVE_TEST struct ext4_map_blocks orig_map; memcpy(&orig_map, map, sizeof(*map)); #endif map->m_flags = 0; ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u," "logical block %lu\n", inode->i_ino, flags, map->m_len, (unsigned long) map->m_lblk); /* * ext4_map_blocks returns an int, and m_len is an unsigned int */ if (unlikely(map->m_len > INT_MAX)) map->m_len = INT_MAX; /* We can handle the block number less than EXT_MAX_BLOCKS */ if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS)) return -EFSCORRUPTED; /* Lookup extent status tree firstly */ if (ext4_es_lookup_extent(inode, map->m_lblk, &es)) { if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) { map->m_pblk = ext4_es_pblock(&es) + map->m_lblk - es.es_lblk; map->m_flags |= ext4_es_is_written(&es) ? EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN; retval = es.es_len - (map->m_lblk - es.es_lblk); if (retval > map->m_len) retval = map->m_len; map->m_len = retval; } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) { map->m_pblk = 0; retval = es.es_len - (map->m_lblk - es.es_lblk); if (retval > map->m_len) retval = map->m_len; map->m_len = retval; retval = 0; } else { BUG_ON(1); } #ifdef ES_AGGRESSIVE_TEST ext4_map_blocks_es_recheck(handle, inode, map, &orig_map, flags); #endif goto found; } /* * Try to see if we can get the block without requesting a new * file system block. */ down_read(&EXT4_I(inode)->i_data_sem); if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) { retval = ext4_ext_map_blocks(handle, inode, map, flags & EXT4_GET_BLOCKS_KEEP_SIZE); } else { retval = ext4_ind_map_blocks(handle, inode, map, flags & EXT4_GET_BLOCKS_KEEP_SIZE); } if (retval > 0) { unsigned int status; if (unlikely(retval != map->m_len)) { ext4_warning(inode->i_sb, "ES len assertion failed for inode " "%lu: retval %d != map->m_len %d", inode->i_ino, retval, map->m_len); WARN_ON(1); } status = map->m_flags & EXT4_MAP_UNWRITTEN ? EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN; if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) && !(status & EXTENT_STATUS_WRITTEN) && ext4_find_delalloc_range(inode, map->m_lblk, map->m_lblk + map->m_len - 1)) status |= EXTENT_STATUS_DELAYED; ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len, map->m_pblk, status); if (ret < 0) retval = ret; } up_read((&EXT4_I(inode)->i_data_sem)); found: if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) { ret = check_block_validity(inode, map); if (ret != 0) return ret; } /* If it is only a block(s) look up */ if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) return retval; /* * Returns if the blocks have already allocated * * Note that if blocks have been preallocated * ext4_ext_get_block() returns the create = 0 * with buffer head unmapped. */ if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) /* * If we need to convert extent to unwritten * we continue and do the actual work in * ext4_ext_map_blocks() */ if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN)) return retval; /* * Here we clear m_flags because after allocating an new extent, * it will be set again. */ map->m_flags &= ~EXT4_MAP_FLAGS; /* * New blocks allocate and/or writing to unwritten extent * will possibly result in updating i_data, so we take * the write lock of i_data_sem, and call get_block() * with create == 1 flag. */ down_write(&EXT4_I(inode)->i_data_sem); /* * We need to check for EXT4 here because migrate * could have changed the inode type in between */ if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) { retval = ext4_ext_map_blocks(handle, inode, map, flags); } else { retval = ext4_ind_map_blocks(handle, inode, map, flags); if (retval > 0 && map->m_flags & EXT4_MAP_NEW) { /* * We allocated new blocks which will result in * i_data's format changing. Force the migrate * to fail by clearing migrate flags */ ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE); } /* * Update reserved blocks/metadata blocks after successful * block allocation which had been deferred till now. We don't * support fallocate for non extent files. So we can update * reserve space here. */ if ((retval > 0) && (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)) ext4_da_update_reserve_space(inode, retval, 1); } if (retval > 0) { unsigned int status; if (unlikely(retval != map->m_len)) { ext4_warning(inode->i_sb, "ES len assertion failed for inode " "%lu: retval %d != map->m_len %d", inode->i_ino, retval, map->m_len); WARN_ON(1); } /* * We have to zeroout blocks before inserting them into extent * status tree. Otherwise someone could look them up there and * use them before they are really zeroed. */ if (flags & EXT4_GET_BLOCKS_ZERO && map->m_flags & EXT4_MAP_MAPPED && map->m_flags & EXT4_MAP_NEW) { ret = ext4_issue_zeroout(inode, map->m_lblk, map->m_pblk, map->m_len); if (ret) { retval = ret; goto out_sem; } } /* * If the extent has been zeroed out, we don't need to update * extent status tree. */ if ((flags & EXT4_GET_BLOCKS_PRE_IO) && ext4_es_lookup_extent(inode, map->m_lblk, &es)) { if (ext4_es_is_written(&es)) goto out_sem; } status = map->m_flags & EXT4_MAP_UNWRITTEN ? EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN; if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) && !(status & EXTENT_STATUS_WRITTEN) && ext4_find_delalloc_range(inode, map->m_lblk, map->m_lblk + map->m_len - 1)) status |= EXTENT_STATUS_DELAYED; ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len, map->m_pblk, status); if (ret < 0) { retval = ret; goto out_sem; } } out_sem: up_write((&EXT4_I(inode)->i_data_sem)); if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) { ret = check_block_validity(inode, map); if (ret != 0) return ret; } return retval; } Commit Message: ext4: fix data exposure after a crash Huang has reported that in his powerfail testing he is seeing stale block contents in some of recently allocated blocks although he mounts ext4 in data=ordered mode. After some investigation I have found out that indeed when delayed allocation is used, we don't add inode to transaction's list of inodes needing flushing before commit. Originally we were doing that but commit f3b59291a69d removed the logic with a flawed argument that it is not needed. The problem is that although for delayed allocated blocks we write their contents immediately after allocating them, there is no guarantee that the IO scheduler or device doesn't reorder things and thus transaction allocating blocks and attaching them to inode can reach stable storage before actual block contents. Actually whenever we attach freshly allocated blocks to inode using a written extent, we should add inode to transaction's ordered inode list to make sure we properly wait for block contents to be written before committing the transaction. So that is what we do in this patch. This also handles other cases where stale data exposure was possible - like filling hole via mmap in data=ordered,nodelalloc mode. The only exception to the above rule are extending direct IO writes where blkdev_direct_IO() waits for IO to complete before increasing i_size and thus stale data exposure is not possible. For now we don't complicate the code with optimizing this special case since the overhead is pretty low. In case this is observed to be a performance problem we can always handle it using a special flag to ext4_map_blocks(). CC: stable@vger.kernel.org Fixes: f3b59291a69d0b734be1fc8be489fef2dd846d3d Reported-by: "HUANG Weller (CM/ESW12-CN)" <Weller.Huang@cn.bosch.com> Tested-by: "HUANG Weller (CM/ESW12-CN)" <Weller.Huang@cn.bosch.com> Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Theodore Ts'o <tytso@mit.edu> CWE ID: CWE-200
1
168,270
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 AutofillManager::DisambiguateNameUploadTypes( FormStructure* form, size_t current_index, const ServerFieldTypeSet& upload_types) { bool has_found_previous_type = false; bool is_previous_credit_card = false; size_t index = current_index; while (index != 0 && !has_found_previous_type) { --index; AutofillField* prev_field = form->field(index); if (!IsNameType(*prev_field)) { has_found_previous_type = true; is_previous_credit_card = prev_field->Type().group() == CREDIT_CARD; } } bool has_found_next_type = false; bool is_next_credit_card = false; index = current_index; while (++index < form->field_count() && !has_found_next_type) { AutofillField* next_field = form->field(index); if (!IsNameType(*next_field)) { has_found_next_type = true; is_next_credit_card = next_field->Type().group() == CREDIT_CARD; } } if (has_found_previous_type || has_found_next_type) { if (has_found_previous_type && has_found_next_type && (is_previous_credit_card != is_next_credit_card)) { return; } ServerFieldTypeSet matching_types; if (has_found_previous_type) { SelectRightNameType(upload_types, &matching_types, is_previous_credit_card); } else { SelectRightNameType(upload_types, &matching_types, is_next_credit_card); } AutofillField* field = form->field(current_index); field->set_possible_types(matching_types); } } Commit Message: [AF] Don't simplify/dedupe suggestions for (partially) filled sections. Since Autofill does not fill field by field anymore, this simplifying and deduping of suggestions is not useful anymore. Bug: 858820 Cq-Include-Trybots: luci.chromium.try:ios-simulator-full-configs;master.tryserver.chromium.mac:ios-simulator-cronet Change-Id: I36f7cfe425a0bdbf5ba7503a3d96773b405cc19b Reviewed-on: https://chromium-review.googlesource.com/1128255 Reviewed-by: Roger McFarlane <rogerm@chromium.org> Commit-Queue: Sebastien Seguin-Gagnon <sebsg@chromium.org> Cr-Commit-Position: refs/heads/master@{#573315} CWE ID:
0
154,941
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void tty_ldisc_deref(struct tty_ldisc *ld) { ldsem_up_read(&ld->tty->ldisc_sem); } Commit Message: tty: Prevent ldisc drivers from re-using stale tty fields Line discipline drivers may mistakenly misuse ldisc-related fields when initializing. For example, a failure to initialize tty->receive_room in the N_GIGASET_M101 line discipline was recently found and fixed [1]. Now, the N_X25 line discipline has been discovered accessing the previous line discipline's already-freed private data [2]. Harden the ldisc interface against misuse by initializing revelant tty fields before instancing the new line discipline. [1] commit fd98e9419d8d622a4de91f76b306af6aa627aa9c Author: Tilman Schmidt <tilman@imap.cc> Date: Tue Jul 14 00:37:13 2015 +0200 isdn/gigaset: reset tty->receive_room when attaching ser_gigaset [2] Report from Sasha Levin <sasha.levin@oracle.com> [ 634.336761] ================================================================== [ 634.338226] BUG: KASAN: use-after-free in x25_asy_open_tty+0x13d/0x490 at addr ffff8800a743efd0 [ 634.339558] Read of size 4 by task syzkaller_execu/8981 [ 634.340359] ============================================================================= [ 634.341598] BUG kmalloc-512 (Not tainted): kasan: bad access detected ... [ 634.405018] Call Trace: [ 634.405277] dump_stack (lib/dump_stack.c:52) [ 634.405775] print_trailer (mm/slub.c:655) [ 634.406361] object_err (mm/slub.c:662) [ 634.406824] kasan_report_error (mm/kasan/report.c:138 mm/kasan/report.c:236) [ 634.409581] __asan_report_load4_noabort (mm/kasan/report.c:279) [ 634.411355] x25_asy_open_tty (drivers/net/wan/x25_asy.c:559 (discriminator 1)) [ 634.413997] tty_ldisc_open.isra.2 (drivers/tty/tty_ldisc.c:447) [ 634.414549] tty_set_ldisc (drivers/tty/tty_ldisc.c:567) [ 634.415057] tty_ioctl (drivers/tty/tty_io.c:2646 drivers/tty/tty_io.c:2879) [ 634.423524] do_vfs_ioctl (fs/ioctl.c:43 fs/ioctl.c:607) [ 634.427491] SyS_ioctl (fs/ioctl.c:622 fs/ioctl.c:613) [ 634.427945] entry_SYSCALL_64_fastpath (arch/x86/entry/entry_64.S:188) Cc: Tilman Schmidt <tilman@imap.cc> Cc: Sasha Levin <sasha.levin@oracle.com> Signed-off-by: Peter Hurley <peter@hurleysoftware.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-200
0
55,989
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 messagePortArrayAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { TestObject* imp = V8TestObject::toNative(info.Holder()); v8SetReturnValue(info, v8Array(imp->messagePortArray(), info.GetIsolate())); } 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
121,761
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 dump_header(struct oom_control *oc, struct task_struct *p) { pr_warn("%s invoked oom-killer: gfp_mask=%#x(%pGg), nodemask=%*pbl, order=%d, oom_score_adj=%hd\n", current->comm, oc->gfp_mask, &oc->gfp_mask, nodemask_pr_args(oc->nodemask), oc->order, current->signal->oom_score_adj); if (!IS_ENABLED(CONFIG_COMPACTION) && oc->order) pr_warn("COMPACTION is disabled!!!\n"); cpuset_print_current_mems_allowed(); dump_stack(); if (is_memcg_oom(oc)) mem_cgroup_print_oom_info(oc->memcg, p); else { show_mem(SHOW_MEM_FILTER_NODES, oc->nodemask); if (is_dump_unreclaim_slabs()) dump_unreclaimable_slab(); } if (sysctl_oom_dump_tasks) dump_tasks(oc->memcg, oc->nodemask); } Commit Message: mm, oom_reaper: gather each vma to prevent leaking TLB entry tlb_gather_mmu(&tlb, mm, 0, -1) means gathering the whole virtual memory space. In this case, tlb->fullmm is true. Some archs like arm64 doesn't flush TLB when tlb->fullmm is true: commit 5a7862e83000 ("arm64: tlbflush: avoid flushing when fullmm == 1"). Which causes leaking of tlb entries. Will clarifies his patch: "Basically, we tag each address space with an ASID (PCID on x86) which is resident in the TLB. This means we can elide TLB invalidation when pulling down a full mm because we won't ever assign that ASID to another mm without doing TLB invalidation elsewhere (which actually just nukes the whole TLB). I think that means that we could potentially not fault on a kernel uaccess, because we could hit in the TLB" There could be a window between complete_signal() sending IPI to other cores and all threads sharing this mm are really kicked off from cores. In this window, the oom reaper may calls tlb_flush_mmu_tlbonly() to flush TLB then frees pages. However, due to the above problem, the TLB entries are not really flushed on arm64. Other threads are possible to access these pages through TLB entries. Moreover, a copy_to_user() can also write to these pages without generating page fault, causes use-after-free bugs. This patch gathers each vma instead of gathering full vm space. In this case tlb->fullmm is not true. The behavior of oom reaper become similar to munmapping before do_exit, which should be safe for all archs. Link: http://lkml.kernel.org/r/20171107095453.179940-1-wangnan0@huawei.com Fixes: aac453635549 ("mm, oom: introduce oom reaper") Signed-off-by: Wang Nan <wangnan0@huawei.com> Acked-by: Michal Hocko <mhocko@suse.com> Acked-by: David Rientjes <rientjes@google.com> Cc: Minchan Kim <minchan@kernel.org> Cc: Will Deacon <will.deacon@arm.com> Cc: Bob Liu <liubo95@huawei.com> Cc: Ingo Molnar <mingo@kernel.org> Cc: Roman Gushchin <guro@fb.com> Cc: Konstantin Khlebnikov <khlebnikov@yandex-team.ru> Cc: Andrea Arcangeli <aarcange@redhat.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-416
0
85,975
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 mlx5_ib_dct_query_qp(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *mqp, struct ib_qp_attr *qp_attr, int qp_attr_mask, struct ib_qp_init_attr *qp_init_attr) { struct mlx5_core_dct *dct = &mqp->dct.mdct; u32 *out; u32 access_flags = 0; int outlen = MLX5_ST_SZ_BYTES(query_dct_out); void *dctc; int err; int supported_mask = IB_QP_STATE | IB_QP_ACCESS_FLAGS | IB_QP_PORT | IB_QP_MIN_RNR_TIMER | IB_QP_AV | IB_QP_PATH_MTU | IB_QP_PKEY_INDEX; if (qp_attr_mask & ~supported_mask) return -EINVAL; if (mqp->state != IB_QPS_RTR) return -EINVAL; out = kzalloc(outlen, GFP_KERNEL); if (!out) return -ENOMEM; err = mlx5_core_dct_query(dev->mdev, dct, out, outlen); if (err) goto out; dctc = MLX5_ADDR_OF(query_dct_out, out, dct_context_entry); if (qp_attr_mask & IB_QP_STATE) qp_attr->qp_state = IB_QPS_RTR; if (qp_attr_mask & IB_QP_ACCESS_FLAGS) { if (MLX5_GET(dctc, dctc, rre)) access_flags |= IB_ACCESS_REMOTE_READ; if (MLX5_GET(dctc, dctc, rwe)) access_flags |= IB_ACCESS_REMOTE_WRITE; if (MLX5_GET(dctc, dctc, rae)) access_flags |= IB_ACCESS_REMOTE_ATOMIC; qp_attr->qp_access_flags = access_flags; } if (qp_attr_mask & IB_QP_PORT) qp_attr->port_num = MLX5_GET(dctc, dctc, port); if (qp_attr_mask & IB_QP_MIN_RNR_TIMER) qp_attr->min_rnr_timer = MLX5_GET(dctc, dctc, min_rnr_nak); if (qp_attr_mask & IB_QP_AV) { qp_attr->ah_attr.grh.traffic_class = MLX5_GET(dctc, dctc, tclass); qp_attr->ah_attr.grh.flow_label = MLX5_GET(dctc, dctc, flow_label); qp_attr->ah_attr.grh.sgid_index = MLX5_GET(dctc, dctc, my_addr_index); qp_attr->ah_attr.grh.hop_limit = MLX5_GET(dctc, dctc, hop_limit); } if (qp_attr_mask & IB_QP_PATH_MTU) qp_attr->path_mtu = MLX5_GET(dctc, dctc, mtu); if (qp_attr_mask & IB_QP_PKEY_INDEX) qp_attr->pkey_index = MLX5_GET(dctc, dctc, pkey_index); out: kfree(out); return err; } Commit Message: IB/mlx5: Fix leaking stack memory to userspace mlx5_ib_create_qp_resp was never initialized and only the first 4 bytes were written. Fixes: 41d902cb7c32 ("RDMA/mlx5: Fix definition of mlx5_ib_create_qp_resp") Cc: <stable@vger.kernel.org> Acked-by: Leon Romanovsky <leonro@mellanox.com> Signed-off-by: Jason Gunthorpe <jgg@mellanox.com> CWE ID: CWE-119
0
92,143
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 linear_map_bio(struct dm_target *ti, struct bio *bio) { struct linear_c *lc = ti->private; bio->bi_bdev = lc->dev->bdev; if (bio_sectors(bio)) bio->bi_sector = linear_map_sector(ti, bio->bi_sector); } Commit Message: dm: do not forward ioctls from logical volumes to the underlying device A logical volume can map to just part of underlying physical volume. In this case, it must be treated like a partition. Based on a patch from Alasdair G Kergon. Cc: Alasdair G Kergon <agk@redhat.com> Cc: dm-devel@redhat.com Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-264
0
23,564
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 GetTransforms(const Cmd& cmd, GLuint num_paths, GLenum transform_type, const GLfloat** out_transforms) { if (transform_type == GL_NONE) { *out_transforms = nullptr; return true; } uint32_t transforms_shm_id = static_cast<uint32_t>(cmd.transformValues_shm_id); uint32_t transforms_shm_offset = static_cast<uint32_t>(cmd.transformValues_shm_offset); uint32_t transforms_component_count = GLES2Util::GetComponentCountForGLTransformType(transform_type); DCHECK_LE(transforms_component_count, 12U); uint32_t one_transform_size = sizeof(GLfloat) * transforms_component_count; uint32_t transforms_size = 0; if (!base::CheckMul(one_transform_size, num_paths) .AssignIfValid(&transforms_size)) { error_ = error::kOutOfBounds; return false; } const GLfloat* transforms = nullptr; if (transforms_shm_id != 0 || transforms_shm_offset != 0) transforms = decoder_->GetSharedMemoryAs<const GLfloat*>( transforms_shm_id, transforms_shm_offset, transforms_size); if (!transforms) { error_ = error::kOutOfBounds; return false; } *out_transforms = transforms; return true; } 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
0
141,498
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 xenvif_up(struct xenvif *vif) { xen_netbk_add_xenvif(vif); enable_irq(vif->irq); xen_netbk_check_rx_xenvif(vif); } Commit Message: xen/netback: shutdown the ring if it contains garbage. A buggy or malicious frontend should not be able to confuse netback. If we spot anything which is not as it should be then shutdown the device and don't try to continue with the ring in a potentially hostile state. Well behaved and non-hostile frontends will not be penalised. As well as making the existing checks for such errors fatal also add a new check that ensures that there isn't an insane number of requests on the ring (i.e. more than would fit in the ring). If the ring contains garbage then previously is was possible to loop over this insane number, getting an error each time and therefore not generating any more pending requests and therefore not exiting the loop in xen_netbk_tx_build_gops for an externded period. Also turn various netdev_dbg calls which no precipitate a fatal error into netdev_err, they are rate limited because the device is shutdown afterwards. This fixes at least one known DoS/softlockup of the backend domain. Signed-off-by: Ian Campbell <ian.campbell@citrix.com> Reviewed-by: Konrad Rzeszutek Wilk <konrad.wilk@oracle.com> Acked-by: Jan Beulich <JBeulich@suse.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-20
0
34,036
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 ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path) { int k, l = path->p_depth; ext_debug("path:"); for (k = 0; k <= l; k++, path++) { if (path->p_idx) { ext_debug(" %d->%llu", le32_to_cpu(path->p_idx->ei_block), ext4_idx_pblock(path->p_idx)); } else if (path->p_ext) { ext_debug(" %d:[%d]%d:%llu ", le32_to_cpu(path->p_ext->ee_block), ext4_ext_is_unwritten(path->p_ext), ext4_ext_get_actual_len(path->p_ext), ext4_ext_pblock(path->p_ext)); } else ext_debug(" []"); } ext_debug("\n"); } Commit Message: ext4: allocate entire range in zero range Currently there is a bug in zero range code which causes zero range calls to only allocate block aligned portion of the range, while ignoring the rest in some cases. In some cases, namely if the end of the range is past i_size, we do attempt to preallocate the last nonaligned block. However this might cause kernel to BUG() in some carefully designed zero range requests on setups where page size > block size. Fix this problem by first preallocating the entire range, including the nonaligned edges and converting the written extents to unwritten in the next step. This approach will also give us the advantage of having the range to be as linearly contiguous as possible. Signed-off-by: Lukas Czerner <lczerner@redhat.com> Signed-off-by: Theodore Ts'o <tytso@mit.edu> CWE ID: CWE-17
0
44,884
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: tt_cmap4_next( TT_CMap4 cmap ) { FT_UInt charcode; if ( cmap->cur_charcode >= 0xFFFFUL ) goto Fail; charcode = cmap->cur_charcode + 1; if ( charcode < cmap->cur_start ) charcode = cmap->cur_start; for ( ;; ) { FT_Byte* values = cmap->cur_values; FT_UInt end = cmap->cur_end; FT_Int delta = cmap->cur_delta; if ( charcode <= end ) { if ( values ) { FT_Byte* p = values + 2 * ( charcode - cmap->cur_start ); do { FT_UInt gindex = FT_NEXT_USHORT( p ); if ( gindex != 0 ) { gindex = (FT_UInt)( ( gindex + delta ) & 0xFFFFU ); if ( gindex != 0 ) { cmap->cur_charcode = charcode; cmap->cur_gindex = gindex; return; } } } while ( ++charcode <= end ); } else { do { FT_UInt gindex = (FT_UInt)( ( charcode + delta ) & 0xFFFFU ); if ( gindex != 0 ) { cmap->cur_charcode = charcode; cmap->cur_gindex = gindex; return; } } while ( ++charcode <= end ); } } /* we need to find another range */ if ( tt_cmap4_set_range( cmap, cmap->cur_range + 1 ) < 0 ) break; if ( charcode < cmap->cur_start ) charcode = cmap->cur_start; } Fail: cmap->cur_charcode = 0xFFFFFFFFUL; cmap->cur_gindex = 0; } Commit Message: CWE ID: CWE-189
0
4,190
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: test_bson_clear (void) { bson_t *doc = NULL; bson_clear (&doc); BSON_ASSERT (doc == NULL); doc = bson_new (); BSON_ASSERT (doc != NULL); bson_clear (&doc); BSON_ASSERT (doc == NULL); } Commit Message: Fix for CVE-2018-16790 -- Verify bounds before binary length read. As reported here: https://jira.mongodb.org/browse/CDRIVER-2819, a heap overread occurs due a failure to correctly verify data bounds. In the original check, len - o returns the data left including the sizeof(l) we just read. Instead, the comparison should check against the data left NOT including the binary int32, i.e. just subtype (byte*) instead of int32 subtype (byte*). Added in test for corrupted BSON example. CWE ID: CWE-125
0
77,905
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: CloudPolicyCacheBase::CloudPolicyCacheBase() : notifier_(NULL), initialization_complete_(false), is_unmanaged_(false) { public_key_version_.version = 0; public_key_version_.valid = false; } Commit Message: Reset the device policy machinery upon retrying enrollment. BUG=chromium-os:18208 TEST=See bug description Review URL: http://codereview.chromium.org/7676005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
0
97,745
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 ping_proc_register(struct net *net, struct ping_seq_afinfo *afinfo) { struct proc_dir_entry *p; p = proc_create_data(afinfo->name, S_IRUGO, net->proc_net, afinfo->seq_fops, afinfo); if (!p) return -ENOMEM; return 0; } Commit Message: ping: prevent NULL pointer dereference on write to msg_name A plain read() on a socket does set msg->msg_name to NULL. So check for NULL pointer first. Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID:
0
28,377
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 FrameLoader::numPendingOrLoadingRequests(bool recurse) const { if (!recurse) return m_frame->document()->fetcher()->requestCount(); int count = 0; for (Frame* frame = m_frame; frame; frame = frame->tree()->traverseNext(m_frame)) count += frame->document()->fetcher()->requestCount(); return count; } Commit Message: Don't wait to notify client of spoof attempt if a modal dialog is created. BUG=281256 TEST=See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/23620020 git-svn-id: svn://svn.chromium.org/blink/trunk@157196 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
0
111,661
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 RenderLayerScrollableArea::usesCompositedScrolling() const { if (box().isIntristicallyScrollable(VerticalScrollbar) || box().isIntristicallyScrollable(HorizontalScrollbar)) return false; DisableCompositingQueryAsserts disabler; return layer()->hasCompositedLayerMapping() && layer()->compositedLayerMapping()->scrollingLayer(); } Commit Message: Defer call to updateWidgetPositions() outside of RenderLayerScrollableArea. updateWidgetPositions() can destroy the render tree, so it should never be called from inside RenderLayerScrollableArea. Leaving it there allows for the potential of use-after-free bugs. BUG=402407 R=vollick@chromium.org Review URL: https://codereview.chromium.org/490473003 git-svn-id: svn://svn.chromium.org/blink/trunk@180681 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-416
0
120,046
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int cifs_ci_hash(const struct dentry *dentry, const struct inode *inode, struct qstr *q) { struct nls_table *codepage = CIFS_SB(dentry->d_sb)->local_nls; unsigned long hash; int i; hash = init_name_hash(); for (i = 0; i < q->len; i++) hash = partial_name_hash(nls_tolower(codepage, q->name[i]), hash); q->hash = end_name_hash(hash); return 0; } Commit Message: cifs: fix dentry refcount leak when opening a FIFO on lookup commit 5bccda0ebc7c0331b81ac47d39e4b920b198b2cd upstream. The cifs code will attempt to open files on lookup under certain circumstances. What happens though if we find that the file we opened was actually a FIFO or other special file? Currently, the open filehandle just ends up being leaked leading to a dentry refcount mismatch and oops on umount. Fix this by having the code close the filehandle on the server if it turns out not to be a regular file. While we're at it, change this spaghetti if statement into a switch too. Reported-by: CAI Qian <caiqian@redhat.com> Tested-by: CAI Qian <caiqian@redhat.com> Reviewed-by: Shirish Pargaonkar <shirishpargaonkar@gmail.com> Signed-off-by: Jeff Layton <jlayton@redhat.com> Signed-off-by: Steve French <smfrench@gmail.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-264
0
21,477
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: UWORD32 ih264d_correct_level_idc(UWORD32 u4_level_idc, UWORD32 u4_total_mbs) { UWORD32 u4_max_mbs_allowed; switch(u4_level_idc) { case H264_LEVEL_1_0: u4_max_mbs_allowed = MAX_MBS_LEVEL_10; break; case H264_LEVEL_1_1: u4_max_mbs_allowed = MAX_MBS_LEVEL_11; break; case H264_LEVEL_1_2: u4_max_mbs_allowed = MAX_MBS_LEVEL_12; break; case H264_LEVEL_1_3: u4_max_mbs_allowed = MAX_MBS_LEVEL_13; break; case H264_LEVEL_2_0: u4_max_mbs_allowed = MAX_MBS_LEVEL_20; break; case H264_LEVEL_2_1: u4_max_mbs_allowed = MAX_MBS_LEVEL_21; break; case H264_LEVEL_2_2: u4_max_mbs_allowed = MAX_MBS_LEVEL_22; break; case H264_LEVEL_3_0: u4_max_mbs_allowed = MAX_MBS_LEVEL_30; break; case H264_LEVEL_3_1: u4_max_mbs_allowed = MAX_MBS_LEVEL_31; break; case H264_LEVEL_3_2: u4_max_mbs_allowed = MAX_MBS_LEVEL_32; break; case H264_LEVEL_4_0: u4_max_mbs_allowed = MAX_MBS_LEVEL_40; break; case H264_LEVEL_4_1: u4_max_mbs_allowed = MAX_MBS_LEVEL_41; break; case H264_LEVEL_4_2: u4_max_mbs_allowed = MAX_MBS_LEVEL_42; break; case H264_LEVEL_5_0: u4_max_mbs_allowed = MAX_MBS_LEVEL_50; break; case H264_LEVEL_5_1: default: u4_max_mbs_allowed = MAX_MBS_LEVEL_51; break; } /*correct of the level is incorrect*/ if(u4_total_mbs > u4_max_mbs_allowed) { if(u4_total_mbs > MAX_MBS_LEVEL_50) u4_level_idc = H264_LEVEL_5_1; else if(u4_total_mbs > MAX_MBS_LEVEL_42) u4_level_idc = H264_LEVEL_5_0; else if(u4_total_mbs > MAX_MBS_LEVEL_41) u4_level_idc = H264_LEVEL_4_2; else if(u4_total_mbs > MAX_MBS_LEVEL_40) u4_level_idc = H264_LEVEL_4_1; else if(u4_total_mbs > MAX_MBS_LEVEL_32) u4_level_idc = H264_LEVEL_4_0; else if(u4_total_mbs > MAX_MBS_LEVEL_31) u4_level_idc = H264_LEVEL_3_2; else if(u4_total_mbs > MAX_MBS_LEVEL_30) u4_level_idc = H264_LEVEL_3_1; else if(u4_total_mbs > MAX_MBS_LEVEL_21) u4_level_idc = H264_LEVEL_3_0; else if(u4_total_mbs > MAX_MBS_LEVEL_20) u4_level_idc = H264_LEVEL_2_1; else if(u4_total_mbs > MAX_MBS_LEVEL_10) u4_level_idc = H264_LEVEL_2_0; } return (u4_level_idc); } Commit Message: Decoder: Fix slice number increment for error clips Bug: 28673410 CWE ID: CWE-119
0
159,553
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 SoftVorbis::initPorts() { OMX_PARAM_PORTDEFINITIONTYPE def; InitOMXParams(&def); def.nPortIndex = 0; def.eDir = OMX_DirInput; def.nBufferCountMin = kNumBuffers; def.nBufferCountActual = def.nBufferCountMin; def.nBufferSize = 8192; def.bEnabled = OMX_TRUE; def.bPopulated = OMX_FALSE; def.eDomain = OMX_PortDomainAudio; def.bBuffersContiguous = OMX_FALSE; def.nBufferAlignment = 1; def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_VORBIS); def.format.audio.pNativeRender = NULL; def.format.audio.bFlagErrorConcealment = OMX_FALSE; def.format.audio.eEncoding = OMX_AUDIO_CodingVORBIS; addPort(def); def.nPortIndex = 1; def.eDir = OMX_DirOutput; def.nBufferCountMin = kNumBuffers; def.nBufferCountActual = def.nBufferCountMin; def.nBufferSize = kMaxNumSamplesPerBuffer * sizeof(int16_t); def.bEnabled = OMX_TRUE; def.bPopulated = OMX_FALSE; def.eDomain = OMX_PortDomainAudio; def.bBuffersContiguous = OMX_FALSE; def.nBufferAlignment = 2; def.format.audio.cMIMEType = const_cast<char *>("audio/raw"); def.format.audio.pNativeRender = NULL; def.format.audio.bFlagErrorConcealment = OMX_FALSE; def.format.audio.eEncoding = OMX_AUDIO_CodingPCM; addPort(def); } Commit Message: DO NOT MERGE codecs: check OMX buffer size before use in (vorbis|opus)dec Bug: 27833616 Change-Id: I1ccdd16a00741da072527a6d13e87fd7c7fe8c54 CWE ID: CWE-20
0
160,621
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 set_breakpoint(struct arch_hw_breakpoint *brk) { preempt_disable(); __set_breakpoint(brk); preempt_enable(); } Commit Message: powerpc/tm: Check for already reclaimed tasks Currently we can hit a scenario where we'll tm_reclaim() twice. This results in a TM bad thing exception because the second reclaim occurs when not in suspend mode. The scenario in which this can happen is the following. We attempt to deliver a signal to userspace. To do this we need obtain the stack pointer to write the signal context. To get this stack pointer we must tm_reclaim() in case we need to use the checkpointed stack pointer (see get_tm_stackpointer()). Normally we'd then return directly to userspace to deliver the signal without going through __switch_to(). Unfortunatley, if at this point we get an error (such as a bad userspace stack pointer), we need to exit the process. The exit will result in a __switch_to(). __switch_to() will attempt to save the process state which results in another tm_reclaim(). This tm_reclaim() now causes a TM Bad Thing exception as this state has already been saved and the processor is no longer in TM suspend mode. Whee! This patch checks the state of the MSR to ensure we are TM suspended before we attempt the tm_reclaim(). If we've already saved the state away, we should no longer be in TM suspend mode. This has the additional advantage of checking for a potential TM Bad Thing exception. Found using syscall fuzzer. Fixes: fb09692e71f1 ("powerpc: Add reclaim and recheckpoint functions for context switching transactional memory processes") Cc: stable@vger.kernel.org # v3.9+ Signed-off-by: Michael Neuling <mikey@neuling.org> Signed-off-by: Michael Ellerman <mpe@ellerman.id.au> CWE ID: CWE-284
0
56,450
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 calc_group_runnable(struct cfs_rq *cfs_rq, long shares) { long runnable, load_avg; load_avg = max(cfs_rq->avg.load_avg, scale_load_down(cfs_rq->load.weight)); runnable = max(cfs_rq->avg.runnable_load_avg, scale_load_down(cfs_rq->runnable_weight)); runnable *= shares; if (load_avg) runnable /= load_avg; return clamp_t(long, runnable, MIN_SHARES, shares); } Commit Message: sched/fair: Fix infinite loop in update_blocked_averages() by reverting a9e7f6544b9c Zhipeng Xie, Xie XiuQi and Sargun Dhillon reported lockups in the scheduler under high loads, starting at around the v4.18 time frame, and Zhipeng Xie tracked it down to bugs in the rq->leaf_cfs_rq_list manipulation. Do a (manual) revert of: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path") It turns out that the list_del_leaf_cfs_rq() introduced by this commit is a surprising property that was not considered in followup commits such as: 9c2791f936ef ("sched/fair: Fix hierarchical order in rq->leaf_cfs_rq_list") As Vincent Guittot explains: "I think that there is a bigger problem with commit a9e7f6544b9c and cfs_rq throttling: Let take the example of the following topology TG2 --> TG1 --> root: 1) The 1st time a task is enqueued, we will add TG2 cfs_rq then TG1 cfs_rq to leaf_cfs_rq_list and we are sure to do the whole branch in one path because it has never been used and can't be throttled so tmp_alone_branch will point to leaf_cfs_rq_list at the end. 2) Then TG1 is throttled 3) and we add TG3 as a new child of TG1. 4) The 1st enqueue of a task on TG3 will add TG3 cfs_rq just before TG1 cfs_rq and tmp_alone_branch will stay on rq->leaf_cfs_rq_list. With commit a9e7f6544b9c, we can del a cfs_rq from rq->leaf_cfs_rq_list. So if the load of TG1 cfs_rq becomes NULL before step 2) above, TG1 cfs_rq is removed from the list. Then at step 4), TG3 cfs_rq is added at the beginning of rq->leaf_cfs_rq_list but tmp_alone_branch still points to TG3 cfs_rq because its throttled parent can't be enqueued when the lock is released. tmp_alone_branch doesn't point to rq->leaf_cfs_rq_list whereas it should. So if TG3 cfs_rq is removed or destroyed before tmp_alone_branch points on another TG cfs_rq, the next TG cfs_rq that will be added, will be linked outside rq->leaf_cfs_rq_list - which is bad. In addition, we can break the ordering of the cfs_rq in rq->leaf_cfs_rq_list but this ordering is used to update and propagate the update from leaf down to root." Instead of trying to work through all these cases and trying to reproduce the very high loads that produced the lockup to begin with, simplify the code temporarily by reverting a9e7f6544b9c - which change was clearly not thought through completely. This (hopefully) gives us a kernel that doesn't lock up so people can continue to enjoy their holidays without worrying about regressions. ;-) [ mingo: Wrote changelog, fixed weird spelling in code comment while at it. ] Analyzed-by: Xie XiuQi <xiexiuqi@huawei.com> Analyzed-by: Vincent Guittot <vincent.guittot@linaro.org> Reported-by: Zhipeng Xie <xiezhipeng1@huawei.com> Reported-by: Sargun Dhillon <sargun@sargun.me> Reported-by: Xie XiuQi <xiexiuqi@huawei.com> Tested-by: Zhipeng Xie <xiezhipeng1@huawei.com> Tested-by: Sargun Dhillon <sargun@sargun.me> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> Acked-by: Vincent Guittot <vincent.guittot@linaro.org> Cc: <stable@vger.kernel.org> # v4.13+ Cc: Bin Li <huawei.libin@huawei.com> Cc: Mike Galbraith <efault@gmx.de> Cc: Peter Zijlstra <peterz@infradead.org> Cc: Tejun Heo <tj@kernel.org> Cc: Thomas Gleixner <tglx@linutronix.de> Fixes: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path") Link: http://lkml.kernel.org/r/1545879866-27809-1-git-send-email-xiexiuqi@huawei.com Signed-off-by: Ingo Molnar <mingo@kernel.org> CWE ID: CWE-400
0
92,471
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 FileUtilProxy::Truncate( scoped_refptr<MessageLoopProxy> message_loop_proxy, PlatformFile file, int64 length, StatusCallback* callback) { return Start(FROM_HERE, message_loop_proxy, new RelayTruncatePlatformFile(file, length, callback)); } Commit Message: Fix a small leak in FileUtilProxy BUG=none TEST=green mem bots Review URL: http://codereview.chromium.org/7669046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97451 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
0
97,689
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 select_idle_cpu(struct task_struct *p, struct sched_domain *sd, int target) { struct sched_domain *this_sd; u64 avg_cost, avg_idle; u64 time, cost; s64 delta; int cpu, nr = INT_MAX; this_sd = rcu_dereference(*this_cpu_ptr(&sd_llc)); if (!this_sd) return -1; /* * Due to large variance we need a large fuzz factor; hackbench in * particularly is sensitive here. */ avg_idle = this_rq()->avg_idle / 512; avg_cost = this_sd->avg_scan_cost + 1; if (sched_feat(SIS_AVG_CPU) && avg_idle < avg_cost) return -1; if (sched_feat(SIS_PROP)) { u64 span_avg = sd->span_weight * avg_idle; if (span_avg > 4*avg_cost) nr = div_u64(span_avg, avg_cost); else nr = 4; } time = local_clock(); for_each_cpu_wrap(cpu, sched_domain_span(sd), target) { if (!--nr) return -1; if (!cpumask_test_cpu(cpu, &p->cpus_allowed)) continue; if (available_idle_cpu(cpu)) break; } time = local_clock() - time; cost = this_sd->avg_scan_cost; delta = (s64)(time - cost) / 8; this_sd->avg_scan_cost += delta; return cpu; } Commit Message: sched/fair: Fix infinite loop in update_blocked_averages() by reverting a9e7f6544b9c Zhipeng Xie, Xie XiuQi and Sargun Dhillon reported lockups in the scheduler under high loads, starting at around the v4.18 time frame, and Zhipeng Xie tracked it down to bugs in the rq->leaf_cfs_rq_list manipulation. Do a (manual) revert of: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path") It turns out that the list_del_leaf_cfs_rq() introduced by this commit is a surprising property that was not considered in followup commits such as: 9c2791f936ef ("sched/fair: Fix hierarchical order in rq->leaf_cfs_rq_list") As Vincent Guittot explains: "I think that there is a bigger problem with commit a9e7f6544b9c and cfs_rq throttling: Let take the example of the following topology TG2 --> TG1 --> root: 1) The 1st time a task is enqueued, we will add TG2 cfs_rq then TG1 cfs_rq to leaf_cfs_rq_list and we are sure to do the whole branch in one path because it has never been used and can't be throttled so tmp_alone_branch will point to leaf_cfs_rq_list at the end. 2) Then TG1 is throttled 3) and we add TG3 as a new child of TG1. 4) The 1st enqueue of a task on TG3 will add TG3 cfs_rq just before TG1 cfs_rq and tmp_alone_branch will stay on rq->leaf_cfs_rq_list. With commit a9e7f6544b9c, we can del a cfs_rq from rq->leaf_cfs_rq_list. So if the load of TG1 cfs_rq becomes NULL before step 2) above, TG1 cfs_rq is removed from the list. Then at step 4), TG3 cfs_rq is added at the beginning of rq->leaf_cfs_rq_list but tmp_alone_branch still points to TG3 cfs_rq because its throttled parent can't be enqueued when the lock is released. tmp_alone_branch doesn't point to rq->leaf_cfs_rq_list whereas it should. So if TG3 cfs_rq is removed or destroyed before tmp_alone_branch points on another TG cfs_rq, the next TG cfs_rq that will be added, will be linked outside rq->leaf_cfs_rq_list - which is bad. In addition, we can break the ordering of the cfs_rq in rq->leaf_cfs_rq_list but this ordering is used to update and propagate the update from leaf down to root." Instead of trying to work through all these cases and trying to reproduce the very high loads that produced the lockup to begin with, simplify the code temporarily by reverting a9e7f6544b9c - which change was clearly not thought through completely. This (hopefully) gives us a kernel that doesn't lock up so people can continue to enjoy their holidays without worrying about regressions. ;-) [ mingo: Wrote changelog, fixed weird spelling in code comment while at it. ] Analyzed-by: Xie XiuQi <xiexiuqi@huawei.com> Analyzed-by: Vincent Guittot <vincent.guittot@linaro.org> Reported-by: Zhipeng Xie <xiezhipeng1@huawei.com> Reported-by: Sargun Dhillon <sargun@sargun.me> Reported-by: Xie XiuQi <xiexiuqi@huawei.com> Tested-by: Zhipeng Xie <xiezhipeng1@huawei.com> Tested-by: Sargun Dhillon <sargun@sargun.me> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> Acked-by: Vincent Guittot <vincent.guittot@linaro.org> Cc: <stable@vger.kernel.org> # v4.13+ Cc: Bin Li <huawei.libin@huawei.com> Cc: Mike Galbraith <efault@gmx.de> Cc: Peter Zijlstra <peterz@infradead.org> Cc: Tejun Heo <tj@kernel.org> Cc: Thomas Gleixner <tglx@linutronix.de> Fixes: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path") Link: http://lkml.kernel.org/r/1545879866-27809-1-git-send-email-xiexiuqi@huawei.com Signed-off-by: Ingo Molnar <mingo@kernel.org> CWE ID: CWE-400
0
92,669
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 cdrom_ioctl_closetray(struct cdrom_device_info *cdi) { cd_dbg(CD_DO_IOCTL, "entering CDROMCLOSETRAY\n"); if (!CDROM_CAN(CDC_CLOSE_TRAY)) return -ENOSYS; return cdi->ops->tray_move(cdi, 0); } Commit Message: cdrom: fix improper type cast, which can leat to information leak. There is another cast from unsigned long to int which causes a bounds check to fail with specially crafted input. The value is then used as an index in the slot array in cdrom_slot_status(). This issue is similar to CVE-2018-16658 and CVE-2018-10940. Signed-off-by: Young_X <YangX92@hotmail.com> Signed-off-by: Jens Axboe <axboe@kernel.dk> CWE ID: CWE-200
0
76,227
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: dump_xml_element(xmlNode * data, int options, char **buffer, int *offset, int *max, int depth) { const char *name = NULL; CRM_ASSERT(max != NULL); CRM_ASSERT(offset != NULL); CRM_ASSERT(buffer != NULL); if (data == NULL) { crm_trace("Nothing to dump"); return; } if (*buffer == NULL) { *offset = 0; *max = 0; } name = crm_element_name(data); CRM_ASSERT(name != NULL); insert_prefix(options, buffer, offset, max, depth); buffer_print(*buffer, *max, *offset, "<%s", name); if (options & xml_log_option_filtered) { dump_filtered_xml(data, options, buffer, offset, max); } else { xmlAttrPtr xIter = NULL; for (xIter = crm_first_attr(data); xIter != NULL; xIter = xIter->next) { dump_xml_attr(xIter, options, buffer, offset, max); } } if (data->children == NULL) { buffer_print(*buffer, *max, *offset, "/>"); } else { buffer_print(*buffer, *max, *offset, ">"); } if (options & xml_log_option_formatted) { buffer_print(*buffer, *max, *offset, "\n"); } if (data->children) { xmlNode *xChild = NULL; for (xChild = __xml_first_child(data); xChild != NULL; xChild = __xml_next(xChild)) { crm_xml_dump(xChild, options, buffer, offset, max, depth + 1); } insert_prefix(options, buffer, offset, max, depth); buffer_print(*buffer, *max, *offset, "</%s>", name); if (options & xml_log_option_formatted) { buffer_print(*buffer, *max, *offset, "\n"); } } } Commit Message: Fix: acl: Do not delay evaluation of added nodes in some situations It is not appropriate when the node has no children as it is not a placeholder CWE ID: CWE-264
0
44,041
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int nfs_mount_req(struct nfs_priv *npriv) { uint32_t data[1024]; uint32_t *p; int len; int pathlen; struct packet *nfs_packet; pathlen = strlen(npriv->path); debug("%s: %s\n", __func__, npriv->path); p = &(data[0]); p = rpc_add_credentials(p); *p++ = hton32(pathlen); if (pathlen & 3) *(p + pathlen / 4) = 0; memcpy (p, npriv->path, pathlen); p += (pathlen + 3) / 4; len = p - &(data[0]); nfs_packet = rpc_req(npriv, PROG_MOUNT, MOUNT_ADDENTRY, data, len); if (IS_ERR(nfs_packet)) return PTR_ERR(nfs_packet); p = (void *)nfs_packet->data + sizeof(struct rpc_reply) + 4; npriv->rootfh.size = ntoh32(net_read_uint32(p++)); if (npriv->rootfh.size > NFS3_FHSIZE) { printf("%s: file handle too big: %lu\n", __func__, (unsigned long)npriv->rootfh.size); free(nfs_packet); return -EIO; } memcpy(npriv->rootfh.data, p, npriv->rootfh.size); free(nfs_packet); return 0; } Commit Message: CWE ID: CWE-119
0
1,344
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 main(int argc, char **argv) { int frame_cnt = 0; FILE *outfile = NULL; vpx_codec_ctx_t codec; VpxVideoReader *reader = NULL; const VpxVideoInfo *info = NULL; const VpxInterface *decoder = NULL; exec_name = argv[0]; if (argc != 3) die("Invalid number of arguments."); reader = vpx_video_reader_open(argv[1]); if (!reader) die("Failed to open %s for reading.", argv[1]); if (!(outfile = fopen(argv[2], "wb"))) die("Failed to open %s for writing.", argv[2]); info = vpx_video_reader_get_info(reader); decoder = get_vpx_decoder_by_fourcc(info->codec_fourcc); if (!decoder) die("Unknown input codec."); printf("Using %s\n", vpx_codec_iface_name(decoder->interface())); if (vpx_codec_dec_init(&codec, decoder->interface(), NULL, 0)) die_codec(&codec, "Failed to initialize decoder"); while (vpx_video_reader_read_frame(reader)) { vpx_codec_iter_t iter = NULL; vpx_image_t *img = NULL; size_t frame_size = 0; const unsigned char *frame = vpx_video_reader_get_frame(reader, &frame_size); if (vpx_codec_decode(&codec, frame, (unsigned int)frame_size, NULL, 0)) die_codec(&codec, "Failed to decode frame"); while ((img = vpx_codec_get_frame(&codec, &iter)) != NULL) { unsigned char digest[16]; get_image_md5(img, digest); print_md5(outfile, digest); fprintf(outfile, " img-%dx%d-%04d.i420\n", img->d_w, img->d_h, ++frame_cnt); } } printf("Processed %d frames.\n", frame_cnt); if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec."); vpx_video_reader_close(reader); fclose(outfile); return EXIT_SUCCESS; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
1
174,474
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 ep_loop_check(struct eventpoll *ep, struct file *file) { int ret; struct eventpoll *ep_cur, *ep_next; ret = ep_call_nested(&poll_loop_ncalls, EP_MAX_NESTS, ep_loop_check_proc, file, ep, current); /* clear visited list */ list_for_each_entry_safe(ep_cur, ep_next, &visited_list, visited_list_link) { ep_cur->visited = 0; list_del(&ep_cur->visited_list_link); } return ret; } Commit Message: epoll: clear the tfile_check_list on -ELOOP An epoll_ctl(,EPOLL_CTL_ADD,,) operation can return '-ELOOP' to prevent circular epoll dependencies from being created. However, in that case we do not properly clear the 'tfile_check_list'. Thus, add a call to clear_tfile_check_list() for the -ELOOP case. Signed-off-by: Jason Baron <jbaron@redhat.com> Reported-by: Yurij M. Plotnikov <Yurij.Plotnikov@oktetlabs.ru> Cc: Nelson Elhage <nelhage@nelhage.com> Cc: Davide Libenzi <davidel@xmailserver.org> Tested-by: Alexandra N. Kossovsky <Alexandra.Kossovsky@oktetlabs.ru> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID:
0
19,567
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int everybody_uninteresting(struct commit_list *orig, struct commit **interesting_cache) { struct commit_list *list = orig; if (*interesting_cache) { struct commit *commit = *interesting_cache; if (!(commit->object.flags & UNINTERESTING)) return 0; } while (list) { struct commit *commit = list->item; list = list->next; if (commit->object.flags & UNINTERESTING) continue; *interesting_cache = commit; return 0; } return 1; } Commit Message: list-objects: pass full pathname to callbacks When we find a blob at "a/b/c", we currently pass this to our show_object_fn callbacks as two components: "a/b/" and "c". Callbacks which want the full value then call path_name(), which concatenates the two. But this is an inefficient interface; the path is a strbuf, and we could simply append "c" to it temporarily, then roll back the length, without creating a new copy. So we could improve this by teaching the callsites of path_name() this trick (and there are only 3). But we can also notice that no callback actually cares about the broken-down representation, and simply pass each callback the full path "a/b/c" as a string. The callback code becomes even simpler, then, as we do not have to worry about freeing an allocated buffer, nor rolling back our modification to the strbuf. This is theoretically less efficient, as some callbacks would not bother to format the final path component. But in practice this is not measurable. Since we use the same strbuf over and over, our work to grow it is amortized, and we really only pay to memcpy a few bytes. Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com> CWE ID: CWE-119
0
54,987
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_vf_guid(struct net_device *dev, struct ifla_vf_guid *ivt, int guid_type) { if (dev->type != ARPHRD_INFINIBAND) return -EOPNOTSUPP; return handle_infiniband_guid(dev, ivt, guid_type); } Commit Message: net: fix infoleak in rtnetlink The stack object “map” has a total size of 32 bytes. Its last 4 bytes are padding generated by compiler. These padding bytes are not initialized and sent out via “nla_put”. Signed-off-by: Kangjie Lu <kjlu@gatech.edu> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-200
0
53,121
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 dm_dax_direct_access(struct dax_device *dax_dev, pgoff_t pgoff, long nr_pages, void **kaddr, pfn_t *pfn) { struct mapped_device *md = dax_get_private(dax_dev); sector_t sector = pgoff * PAGE_SECTORS; struct dm_target *ti; long len, ret = -EIO; int srcu_idx; ti = dm_dax_get_live_target(md, sector, &srcu_idx); if (!ti) goto out; if (!ti->type->direct_access) goto out; len = max_io_len(sector, ti) / PAGE_SECTORS; if (len < 1) goto out; nr_pages = min(len, nr_pages); if (ti->type->direct_access) ret = ti->type->direct_access(ti, pgoff, nr_pages, kaddr, pfn); out: dm_put_live_table(md, srcu_idx); return ret; } Commit Message: dm: fix race between dm_get_from_kobject() and __dm_destroy() The following BUG_ON was hit when testing repeat creation and removal of DM devices: kernel BUG at drivers/md/dm.c:2919! CPU: 7 PID: 750 Comm: systemd-udevd Not tainted 4.1.44 Call Trace: [<ffffffff81649e8b>] dm_get_from_kobject+0x34/0x3a [<ffffffff81650ef1>] dm_attr_show+0x2b/0x5e [<ffffffff817b46d1>] ? mutex_lock+0x26/0x44 [<ffffffff811df7f5>] sysfs_kf_seq_show+0x83/0xcf [<ffffffff811de257>] kernfs_seq_show+0x23/0x25 [<ffffffff81199118>] seq_read+0x16f/0x325 [<ffffffff811de994>] kernfs_fop_read+0x3a/0x13f [<ffffffff8117b625>] __vfs_read+0x26/0x9d [<ffffffff8130eb59>] ? security_file_permission+0x3c/0x44 [<ffffffff8117bdb8>] ? rw_verify_area+0x83/0xd9 [<ffffffff8117be9d>] vfs_read+0x8f/0xcf [<ffffffff81193e34>] ? __fdget_pos+0x12/0x41 [<ffffffff8117c686>] SyS_read+0x4b/0x76 [<ffffffff817b606e>] system_call_fastpath+0x12/0x71 The bug can be easily triggered, if an extra delay (e.g. 10ms) is added between the test of DMF_FREEING & DMF_DELETING and dm_get() in dm_get_from_kobject(). To fix it, we need to ensure the test of DMF_FREEING & DMF_DELETING and dm_get() are done in an atomic way, so _minor_lock is used. The other callers of dm_get() have also been checked to be OK: some callers invoke dm_get() under _minor_lock, some callers invoke it under _hash_lock, and dm_start_request() invoke it after increasing md->open_count. Cc: stable@vger.kernel.org Signed-off-by: Hou Tao <houtao1@huawei.com> Signed-off-by: Mike Snitzer <snitzer@redhat.com> CWE ID: CWE-362
0
85,878
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: xsltExtModuleFunctionLookup(const xmlChar * name, const xmlChar * URI) { xmlXPathFunction ret; if ((xsltFunctionsHash == NULL) || (name == NULL) || (URI == NULL)) return (NULL); xmlMutexLock(xsltExtMutex); XML_CAST_FPTR(ret) = xmlHashLookup2(xsltFunctionsHash, name, URI); xmlMutexUnlock(xsltExtMutex); /* if lookup fails, attempt a dynamic load on supported platforms */ if (NULL == ret) { if (!xsltExtModuleRegisterDynamic(URI)) { xmlMutexLock(xsltExtMutex); XML_CAST_FPTR(ret) = xmlHashLookup2(xsltFunctionsHash, name, URI); xmlMutexUnlock(xsltExtMutex); } } return ret; } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
0
156,678
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::FocusToolbar() { std::unique_ptr<ImmersiveRevealedLock> focus_reveal_lock( immersive_mode_controller_->GetRevealedLock( ImmersiveModeController::ANIMATE_REVEAL_YES)); toolbar_button_provider_->FocusToolbar(); } Commit Message: Mac: turn popups into new tabs while in fullscreen. It's platform convention to show popups as new tabs while in non-HTML5 fullscreen. (Popups cause tabs to lose HTML5 fullscreen.) This was implemented for Cocoa in a BrowserWindow override, but it makes sense to just stick it into Browser and remove a ton of override code put in just to support this. BUG=858929, 868416 TEST=as in bugs Change-Id: I43471f242813ec1159d9c690bab73dab3e610b7d Reviewed-on: https://chromium-review.googlesource.com/1153455 Reviewed-by: Sidney San Martín <sdy@chromium.org> Commit-Queue: Avi Drissman <avi@chromium.org> Cr-Commit-Position: refs/heads/master@{#578755} CWE ID: CWE-20
0
155,160
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 override_release(char __user *release, int len) { int ret = 0; char buf[65]; if (current->personality & UNAME26) { char *rest = UTS_RELEASE; int ndots = 0; unsigned v; while (*rest) { if (*rest == '.' && ++ndots >= 3) break; if (!isdigit(*rest) && *rest != '.') break; rest++; } v = ((LINUX_VERSION_CODE >> 8) & 0xff) + 40; snprintf(buf, len, "2.6.%u%s", v, rest); ret = copy_to_user(release, buf, len); } return ret; } Commit Message: kernel/sys.c: fix stack memory content leak via UNAME26 Calling uname() with the UNAME26 personality set allows a leak of kernel stack contents. This fixes it by defensively calculating the length of copy_to_user() call, making the len argument unsigned, and initializing the stack buffer to zero (now technically unneeded, but hey, overkill). CVE-2012-0957 Reported-by: PaX Team <pageexec@freemail.hu> Signed-off-by: Kees Cook <keescook@chromium.org> Cc: Andi Kleen <ak@linux.intel.com> Cc: PaX Team <pageexec@freemail.hu> Cc: Brad Spengler <spender@grsecurity.net> 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-16
1
165,647
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 mptsas_scsi_device_find(MPTSASState *s, int bus, int target, uint8_t *lun, SCSIDevice **sdev) { if (bus != 0) { return MPI_IOCSTATUS_SCSI_INVALID_BUS; } if (target >= s->max_devices) { return MPI_IOCSTATUS_SCSI_INVALID_TARGETID; } *sdev = scsi_device_find(&s->bus, bus, target, lun[1]); if (!*sdev) { return MPI_IOCSTATUS_SCSI_DEVICE_NOT_THERE; } return 0; } Commit Message: CWE ID: CWE-787
0
8,384
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 iscsi_release_extra_responses(struct iscsi_param_list *param_list) { struct iscsi_extra_response *er, *er_tmp; list_for_each_entry_safe(er, er_tmp, &param_list->extra_response_list, er_list) { list_del(&er->er_list); kfree(er); } } Commit Message: iscsi-target: fix heap buffer overflow on error If a key was larger than 64 bytes, as checked by iscsi_check_key(), the error response packet, generated by iscsi_add_notunderstood_response(), would still attempt to copy the entire key into the packet, overflowing the structure on the heap. Remote preauthentication kernel memory corruption was possible if a target was configured and listening on the network. CVE-2013-2850 Signed-off-by: Kees Cook <keescook@chromium.org> Cc: stable@vger.kernel.org Signed-off-by: Nicholas Bellinger <nab@linux-iscsi.org> CWE ID: CWE-119
0
30,986
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 ipgre_open(struct net_device *dev) { struct ip_tunnel *t = netdev_priv(dev); if (ipv4_is_multicast(t->parms.iph.daddr)) { struct flowi fl = { .oif = t->parms.link, .nl_u = { .ip4_u = { .daddr = t->parms.iph.daddr, .saddr = t->parms.iph.saddr, .tos = RT_TOS(t->parms.iph.tos) } }, .proto = IPPROTO_GRE }; struct rtable *rt; if (ip_route_output_key(dev_net(dev), &rt, &fl)) return -EADDRNOTAVAIL; dev = rt->u.dst.dev; ip_rt_put(rt); if (__in_dev_get_rtnl(dev) == NULL) return -EADDRNOTAVAIL; t->mlink = dev->ifindex; ip_mc_inc_group(__in_dev_get_rtnl(dev), t->parms.iph.daddr); } return 0; } Commit Message: gre: fix netns vs proto registration ordering GRE protocol receive hook can be called right after protocol addition is done. If netns stuff is not yet initialized, we're going to oops in net_generic(). This is remotely oopsable if ip_gre is compiled as module and packet comes at unfortunate moment of module loading. Signed-off-by: Alexey Dobriyan <adobriyan@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID:
0
27,493
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void RenderWidgetHostImpl::OnSyntheticGestureCompleted( SyntheticGesture::Result result) { Send(new InputMsg_SyntheticGestureCompleted(GetRoutingID())); } Commit Message: Check that RWHI isn't deleted manually while owned by a scoped_ptr in RVHI BUG=590284 Review URL: https://codereview.chromium.org/1747183002 Cr-Commit-Position: refs/heads/master@{#378844} CWE ID:
0
131,002
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static inline void add_to_write_order(struct object_entry **wo, unsigned int *endp, struct object_entry *e) { if (e->filled) return; wo[(*endp)++] = e; e->filled = 1; } Commit Message: list-objects: pass full pathname to callbacks When we find a blob at "a/b/c", we currently pass this to our show_object_fn callbacks as two components: "a/b/" and "c". Callbacks which want the full value then call path_name(), which concatenates the two. But this is an inefficient interface; the path is a strbuf, and we could simply append "c" to it temporarily, then roll back the length, without creating a new copy. So we could improve this by teaching the callsites of path_name() this trick (and there are only 3). But we can also notice that no callback actually cares about the broken-down representation, and simply pass each callback the full path "a/b/c" as a string. The callback code becomes even simpler, then, as we do not have to worry about freeing an allocated buffer, nor rolling back our modification to the strbuf. This is theoretically less efficient, as some callbacks would not bother to format the final path component. But in practice this is not measurable. Since we use the same strbuf over and over, our work to grow it is amortized, and we really only pay to memcpy a few bytes. Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com> CWE ID: CWE-119
0
54,830
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 mem_cgroup_event_ratelimit(struct mem_cgroup *memcg, enum mem_cgroup_events_target target) { unsigned long val, next; val = __this_cpu_read(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT]); next = __this_cpu_read(memcg->stat->targets[target]); /* from time_after() in jiffies.h */ if ((long)next - (long)val < 0) { switch (target) { case MEM_CGROUP_TARGET_THRESH: next = val + THRESHOLDS_EVENTS_TARGET; break; case MEM_CGROUP_TARGET_SOFTLIMIT: next = val + SOFTLIMIT_EVENTS_TARGET; break; case MEM_CGROUP_TARGET_NUMAINFO: next = val + NUMAINFO_EVENTS_TARGET; break; default: break; } __this_cpu_write(memcg->stat->targets[target], next); return true; } return false; } Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream. In some cases it may happen that pmd_none_or_clear_bad() is called with the mmap_sem hold in read mode. In those cases the huge page faults can allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a false positive from pmd_bad() that will not like to see a pmd materializing as trans huge. It's not khugepaged causing the problem, khugepaged holds the mmap_sem in write mode (and all those sites must hold the mmap_sem in read mode to prevent pagetables to go away from under them, during code review it seems vm86 mode on 32bit kernels requires that too unless it's restricted to 1 thread per process or UP builds). The race is only with the huge pagefaults that can convert a pmd_none() into a pmd_trans_huge(). Effectively all these pmd_none_or_clear_bad() sites running with mmap_sem in read mode are somewhat speculative with the page faults, and the result is always undefined when they run simultaneously. This is probably why it wasn't common to run into this. For example if the madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page fault, the hugepage will not be zapped, if the page fault runs first it will be zapped. Altering pmd_bad() not to error out if it finds hugepmds won't be enough to fix this, because zap_pmd_range would then proceed to call zap_pte_range (which would be incorrect if the pmd become a pmd_trans_huge()). The simplest way to fix this is to read the pmd in the local stack (regardless of what we read, no need of actual CPU barriers, only compiler barrier needed), and be sure it is not changing under the code that computes its value. Even if the real pmd is changing under the value we hold on the stack, we don't care. If we actually end up in zap_pte_range it means the pmd was not none already and it was not huge, and it can't become huge from under us (khugepaged locking explained above). All we need is to enforce that there is no way anymore that in a code path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad can run into a hugepmd. The overhead of a barrier() is just a compiler tweak and should not be measurable (I only added it for THP builds). I don't exclude different compiler versions may have prevented the race too by caching the value of *pmd on the stack (that hasn't been verified, but it wouldn't be impossible considering pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines and there's no external function called in between pmd_trans_huge and pmd_none_or_clear_bad). if (pmd_trans_huge(*pmd)) { if (next-addr != HPAGE_PMD_SIZE) { VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); split_huge_page_pmd(vma->vm_mm, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) continue; /* fall through */ } if (pmd_none_or_clear_bad(pmd)) Because this race condition could be exercised without special privileges this was reported in CVE-2012-1179. The race was identified and fully explained by Ulrich who debugged it. I'm quoting his accurate explanation below, for reference. ====== start quote ======= mapcount 0 page_mapcount 1 kernel BUG at mm/huge_memory.c:1384! At some point prior to the panic, a "bad pmd ..." message similar to the following is logged on the console: mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7). The "bad pmd ..." message is logged by pmd_clear_bad() before it clears the page's PMD table entry. 143 void pmd_clear_bad(pmd_t *pmd) 144 { -> 145 pmd_ERROR(*pmd); 146 pmd_clear(pmd); 147 } After the PMD table entry has been cleared, there is an inconsistency between the actual number of PMD table entries that are mapping the page and the page's map count (_mapcount field in struct page). When the page is subsequently reclaimed, __split_huge_page() detects this inconsistency. 1381 if (mapcount != page_mapcount(page)) 1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n", 1383 mapcount, page_mapcount(page)); -> 1384 BUG_ON(mapcount != page_mapcount(page)); The root cause of the problem is a race of two threads in a multithreaded process. Thread B incurs a page fault on a virtual address that has never been accessed (PMD entry is zero) while Thread A is executing an madvise() system call on a virtual address within the same 2 MB (huge page) range. virtual address space .---------------------. | | | | .-|---------------------| | | | | | |<-- B(fault) | | | 2 MB | |/////////////////////|-. huge < |/////////////////////| > A(range) page | |/////////////////////|-' | | | | | | '-|---------------------| | | | | '---------------------' - Thread A is executing an madvise(..., MADV_DONTNEED) system call on the virtual address range "A(range)" shown in the picture. sys_madvise // Acquire the semaphore in shared mode. down_read(&current->mm->mmap_sem) ... madvise_vma switch (behavior) case MADV_DONTNEED: madvise_dontneed zap_page_range unmap_vmas unmap_page_range zap_pud_range zap_pmd_range // // Assume that this huge page has never been accessed. // I.e. content of the PMD entry is zero (not mapped). // if (pmd_trans_huge(*pmd)) { // We don't get here due to the above assumption. } // // Assume that Thread B incurred a page fault and .---------> // sneaks in here as shown below. | // | if (pmd_none_or_clear_bad(pmd)) | { | if (unlikely(pmd_bad(*pmd))) | pmd_clear_bad | { | pmd_ERROR | // Log "bad pmd ..." message here. | pmd_clear | // Clear the page's PMD entry. | // Thread B incremented the map count | // in page_add_new_anon_rmap(), but | // now the page is no longer mapped | // by a PMD entry (-> inconsistency). | } | } | v - Thread B is handling a page fault on virtual address "B(fault)" shown in the picture. ... do_page_fault __do_page_fault // Acquire the semaphore in shared mode. down_read_trylock(&mm->mmap_sem) ... handle_mm_fault if (pmd_none(*pmd) && transparent_hugepage_enabled(vma)) // We get here due to the above assumption (PMD entry is zero). do_huge_pmd_anonymous_page alloc_hugepage_vma // Allocate a new transparent huge page here. ... __do_huge_pmd_anonymous_page ... spin_lock(&mm->page_table_lock) ... page_add_new_anon_rmap // Here we increment the page's map count (starts at -1). atomic_set(&page->_mapcount, 0) set_pmd_at // Here we set the page's PMD entry which will be cleared // when Thread A calls pmd_clear_bad(). ... spin_unlock(&mm->page_table_lock) The mmap_sem does not prevent the race because both threads are acquiring it in shared mode (down_read). Thread B holds the page_table_lock while the page's map count and PMD table entry are updated. However, Thread A does not synchronize on that lock. ====== end quote ======= [akpm@linux-foundation.org: checkpatch fixes] Reported-by: Ulrich Obergfell <uobergfe@redhat.com> Signed-off-by: Andrea Arcangeli <aarcange@redhat.com> Acked-by: Johannes Weiner <hannes@cmpxchg.org> Cc: Mel Gorman <mgorman@suse.de> Cc: Hugh Dickins <hughd@google.com> Cc: Dave Jones <davej@redhat.com> Acked-by: Larry Woodman <lwoodman@redhat.com> Acked-by: Rik van Riel <riel@redhat.com> Cc: Mark Salter <msalter@redhat.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-264
0
21,057
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 munlock_vma_pages_range(struct vm_area_struct *vma, unsigned long start, unsigned long end) { vma->vm_flags &= ~VM_LOCKED; while (start < end) { struct page *page = NULL; unsigned int page_mask; unsigned long page_increm; struct pagevec pvec; struct zone *zone; int zoneid; pagevec_init(&pvec, 0); /* * Although FOLL_DUMP is intended for get_dump_page(), * it just so happens that its special treatment of the * ZERO_PAGE (returning an error instead of doing get_page) * suits munlock very well (and if somehow an abnormal page * has sneaked into the range, we won't oops here: great). */ page = follow_page_mask(vma, start, FOLL_GET | FOLL_DUMP, &page_mask); if (page && !IS_ERR(page)) { if (PageTransHuge(page)) { lock_page(page); /* * Any THP page found by follow_page_mask() may * have gotten split before reaching * munlock_vma_page(), so we need to recompute * the page_mask here. */ page_mask = munlock_vma_page(page); unlock_page(page); put_page(page); /* follow_page_mask() */ } else { /* * Non-huge pages are handled in batches via * pagevec. The pin from follow_page_mask() * prevents them from collapsing by THP. */ pagevec_add(&pvec, page); zone = page_zone(page); zoneid = page_zone_id(page); /* * Try to fill the rest of pagevec using fast * pte walk. This will also update start to * the next page to process. Then munlock the * pagevec. */ start = __munlock_pagevec_fill(&pvec, vma, zoneid, start, end); __munlock_pagevec(&pvec, zone); goto next; } } /* It's a bug to munlock in the middle of a THP page */ VM_BUG_ON((start >> PAGE_SHIFT) & page_mask); page_increm = 1 + page_mask; start += page_increm * PAGE_SIZE; next: cond_resched(); } } Commit Message: mm: try_to_unmap_cluster() should lock_page() before mlocking A BUG_ON(!PageLocked) was triggered in mlock_vma_page() by Sasha Levin fuzzing with trinity. The call site try_to_unmap_cluster() does not lock the pages other than its check_page parameter (which is already locked). The BUG_ON in mlock_vma_page() is not documented and its purpose is somewhat unclear, but apparently it serializes against page migration, which could otherwise fail to transfer the PG_mlocked flag. This would not be fatal, as the page would be eventually encountered again, but NR_MLOCK accounting would become distorted nevertheless. This patch adds a comment to the BUG_ON in mlock_vma_page() and munlock_vma_page() to that effect. The call site try_to_unmap_cluster() is fixed so that for page != check_page, trylock_page() is attempted (to avoid possible deadlocks as we already have check_page locked) and mlock_vma_page() is performed only upon success. If the page lock cannot be obtained, the page is left without PG_mlocked, which is again not a problem in the whole unevictable memory design. Signed-off-by: Vlastimil Babka <vbabka@suse.cz> Signed-off-by: Bob Liu <bob.liu@oracle.com> Reported-by: Sasha Levin <sasha.levin@oracle.com> Cc: Wanpeng Li <liwanp@linux.vnet.ibm.com> Cc: Michel Lespinasse <walken@google.com> Cc: KOSAKI Motohiro <kosaki.motohiro@jp.fujitsu.com> Acked-by: Rik van Riel <riel@redhat.com> Cc: David Rientjes <rientjes@google.com> Cc: Mel Gorman <mgorman@suse.de> Cc: Hugh Dickins <hughd@google.com> Cc: Joonsoo Kim <iamjoonsoo.kim@lge.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-264
0
38,277
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: WebKit::WebString TestWebKitPlatformSupport::queryLocalizedString( WebKit::WebLocalizedString::Name name) { switch (name) { case WebKit::WebLocalizedString::ValidationValueMissing: case WebKit::WebLocalizedString::ValidationValueMissingForCheckbox: case WebKit::WebLocalizedString::ValidationValueMissingForFile: case WebKit::WebLocalizedString::ValidationValueMissingForMultipleFile: case WebKit::WebLocalizedString::ValidationValueMissingForRadio: case WebKit::WebLocalizedString::ValidationValueMissingForSelect: return ASCIIToUTF16("value missing"); case WebKit::WebLocalizedString::ValidationTypeMismatch: case WebKit::WebLocalizedString::ValidationTypeMismatchForEmail: case WebKit::WebLocalizedString::ValidationTypeMismatchForMultipleEmail: case WebKit::WebLocalizedString::ValidationTypeMismatchForURL: return ASCIIToUTF16("type mismatch"); case WebKit::WebLocalizedString::ValidationPatternMismatch: return ASCIIToUTF16("pattern mismatch"); case WebKit::WebLocalizedString::ValidationTooLong: return ASCIIToUTF16("too long"); case WebKit::WebLocalizedString::ValidationRangeUnderflow: return ASCIIToUTF16("range underflow"); case WebKit::WebLocalizedString::ValidationRangeOverflow: return ASCIIToUTF16("range overflow"); case WebKit::WebLocalizedString::ValidationStepMismatch: return ASCIIToUTF16("step mismatch"); default: return WebKitPlatformSupportImpl::queryLocalizedString(name); } } Commit Message: Use a new scheme for swapping out RenderViews. BUG=118664 TEST=none Review URL: http://codereview.chromium.org/9720004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@127986 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
0
108,638
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static ssize_t lbs_lowrssi_read(struct file *file, char __user *userbuf, size_t count, loff_t *ppos) { return lbs_threshold_read(TLV_TYPE_RSSI_LOW, CMD_SUBSCRIBE_RSSI_LOW, file, userbuf, count, ppos); } Commit Message: libertas: potential oops in debugfs If we do a zero size allocation then it will oops. Also we can't be sure the user passes us a NUL terminated string so I've added a terminator. This code can only be triggered by root. Reported-by: Nico Golde <nico@ngolde.de> Reported-by: Fabian Yamaguchi <fabs@goesec.de> Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Acked-by: Dan Williams <dcbw@redhat.com> Signed-off-by: John W. Linville <linville@tuxdriver.com> CWE ID: CWE-189
0
28,688
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void cypress_unthrottle(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct cypress_private *priv = usb_get_serial_port_data(port); int actually_throttled, result; spin_lock_irq(&priv->lock); actually_throttled = priv->rx_flags & ACTUALLY_THROTTLED; priv->rx_flags = 0; spin_unlock_irq(&priv->lock); if (!priv->comm_is_ok) return; if (actually_throttled) { result = usb_submit_urb(port->interrupt_in_urb, GFP_KERNEL); if (result) { dev_err(&port->dev, "%s - failed submitting read urb, " "error %d\n", __func__, result); cypress_set_dead(port); } } } Commit Message: USB: cypress_m8: add endpoint sanity check An attack using missing endpoints exists. CVE-2016-3137 Signed-off-by: Oliver Neukum <ONeukum@suse.com> CC: stable@vger.kernel.org Signed-off-by: Johan Hovold <johan@kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID:
0
54,249
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: poppler_page_finalize (GObject *object) { PopplerPage *page = POPPLER_PAGE (object); g_object_unref (page->document); page->document = NULL; if (page->annots != NULL) delete page->annots; #if defined (HAVE_CAIRO) if (page->text != NULL) page->text->decRefCnt(); #else if (page->gfx != NULL) delete page->gfx; if (page->text_dev != NULL) delete page->text_dev; #endif /* page->page is owned by the document */ } Commit Message: CWE ID: CWE-189
0
769
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 do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask) { if (p->sched_class && p->sched_class->set_cpus_allowed) p->sched_class->set_cpus_allowed(p, new_mask); else { cpumask_copy(&p->cpus_allowed, new_mask); p->rt.nr_cpus_allowed = cpumask_weight(new_mask); } } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <a.p.zijlstra@chello.nl> Cc: Michael Cree <mcree@orcon.net.nz> Cc: Will Deacon <will.deacon@arm.com> Cc: Deng-Cheng Zhu <dengcheng.zhu@gmail.com> Cc: Anton Blanchard <anton@samba.org> Cc: Eric B Munson <emunson@mgebm.net> Cc: Heiko Carstens <heiko.carstens@de.ibm.com> Cc: Paul Mundt <lethal@linux-sh.org> Cc: David S. Miller <davem@davemloft.net> Cc: Frederic Weisbecker <fweisbec@gmail.com> Cc: Jason Wessel <jason.wessel@windriver.com> Cc: Don Zickus <dzickus@redhat.com> Link: http://lkml.kernel.org/n/tip-agjev8eu666tvknpb3iaj0fg@git.kernel.org Signed-off-by: Ingo Molnar <mingo@elte.hu> CWE ID: CWE-399
0
26,279
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 PaintArtifactCompositor::Update( const PaintArtifact& paint_artifact, CompositorElementIdSet& composited_element_ids) { DCHECK(root_layer_); cc::LayerTreeHost* host = root_layer_->layer_tree_host(); if (!host) return; if (extra_data_for_testing_enabled_) extra_data_for_testing_.reset(new ExtraDataForTesting); RemoveChildLayers(); root_layer_->set_property_tree_sequence_number( g_s_property_tree_sequence_number); PropertyTreeManager property_tree_manager(*this, *host->property_trees(), root_layer_.get(), g_s_property_tree_sequence_number); Vector<PendingLayer, 0> pending_layers; CollectPendingLayers(paint_artifact, pending_layers); Vector<std::unique_ptr<ContentLayerClientImpl>> new_content_layer_clients; new_content_layer_clients.ReserveCapacity(pending_layers.size()); Vector<scoped_refptr<cc::Layer>> new_scroll_hit_test_layers; for (auto& entry : synthesized_clip_cache_) entry.in_use = false; for (auto& pending_layer : pending_layers) { const auto& property_state = pending_layer.property_tree_state; const auto* transform = property_state.Transform(); const auto* clip = property_state.Clip(); if (clip->LocalTransformSpace() == transform) { pending_layer.bounds.Intersect(clip->ClipRect().Rect()); } else if (const auto* scroll = transform->ScrollNode()) { pending_layer.bounds.Intersect(FloatRect(scroll->ContentsRect())); } gfx::Vector2dF layer_offset; scoped_refptr<cc::Layer> layer = CompositedLayerForPendingLayer( paint_artifact, pending_layer, layer_offset, new_content_layer_clients, new_scroll_hit_test_layers); int transform_id = property_tree_manager.EnsureCompositorTransformNode(transform); int clip_id = property_tree_manager.EnsureCompositorClipNode(clip); int effect_id = property_tree_manager.SwitchToEffectNodeWithSynthesizedClip( *property_state.Effect(), *clip); const auto& scroll_translation = ScrollTranslationForPendingLayer(paint_artifact, pending_layer); int scroll_id = property_tree_manager.EnsureCompositorScrollNode(&scroll_translation); layer->set_offset_to_transform_parent(layer_offset); CompositorElementId element_id = layer->scrollable() ? layer->element_id() : property_state.GetCompositorElementId(composited_element_ids); if (element_id) { layer->SetElementId(element_id); composited_element_ids.insert(element_id); } root_layer_->AddChild(layer); if (element_id) { host->RegisterElement(element_id, cc::ElementListType::ACTIVE, layer.get()); } layer->set_property_tree_sequence_number(g_s_property_tree_sequence_number); layer->SetTransformTreeIndex(transform_id); layer->SetScrollTreeIndex(scroll_id); layer->SetClipTreeIndex(clip_id); layer->SetEffectTreeIndex(effect_id); bool backface_hidden = IsBackfaceHidden(pending_layer.property_tree_state.Transform()); layer->SetDoubleSided(!backface_hidden); layer->SetShouldCheckBackfaceVisibility(backface_hidden); } property_tree_manager.Finalize(); content_layer_clients_.swap(new_content_layer_clients); scroll_hit_test_layers_.swap(new_scroll_hit_test_layers); synthesized_clip_cache_.erase( std::remove_if(synthesized_clip_cache_.begin(), synthesized_clip_cache_.end(), [](const auto& entry) { return !entry.in_use; }), synthesized_clip_cache_.end()); if (extra_data_for_testing_enabled_) { for (const auto& entry : synthesized_clip_cache_) { extra_data_for_testing_->synthesized_clip_layers.push_back( entry.synthesized_clip->GetLayer()); } } host->property_trees()->sequence_number = g_s_property_tree_sequence_number; host->property_trees()->needs_rebuild = false; host->property_trees()->ResetCachedData(); g_s_property_tree_sequence_number++; #if DCHECK_IS_ON() if (VLOG_IS_ON(2)) { static String s_previous_output; LayerTreeFlags flags = VLOG_IS_ON(3) ? 0xffffffff : 0; String new_output = LayersAsJSON(flags)->ToPrettyJSONString(); if (new_output != s_previous_output) { LOG(ERROR) << "PaintArtifactCompositor::Update() done\n" << "Composited layers:\n" << new_output.Utf8().data(); s_previous_output = new_output; } } #endif } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <trchen@chromium.org> > > Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org> > > Cr-Commit-Position: refs/heads/master@{#554626} > > TBR=wangxianzhu@chromium.org,trchen@chromium.org,chrishtr@chromium.org > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <wangxianzhu@chromium.org> > Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org> > Cr-Commit-Position: refs/heads/master@{#554653} TBR=wangxianzhu@chromium.org,trchen@chromium.org,chrishtr@chromium.org # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org> Reviewed-by: Xianzhu Wang <wangxianzhu@chromium.org> Cr-Commit-Position: refs/heads/master@{#563930} CWE ID:
0
125,542
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: PersistentMemoryAllocator::Reference PersistentSampleMapRecords::GetNext() { DCHECK(user_); if (records_.size() == seen_) { if (!data_manager_->LoadRecords(this)) return false; } DCHECK_LT(seen_, records_.size()); return records_[seen_++]; } Commit Message: Remove UMA.CreatePersistentHistogram.Result This histogram isn't showing anything meaningful and the problems it could show are better observed by looking at the allocators directly. Bug: 831013 Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9 Reviewed-on: https://chromium-review.googlesource.com/1008047 Commit-Queue: Brian White <bcwhite@chromium.org> Reviewed-by: Alexei Svitkine <asvitkine@chromium.org> Cr-Commit-Position: refs/heads/master@{#549986} CWE ID: CWE-264
0
131,118
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: jbig2_image_compose_unopt(Jbig2Ctx *ctx, Jbig2Image *dst, Jbig2Image *src, int x, int y, Jbig2ComposeOp op) { int i, j; int sw = src->width; int sh = src->height; int sx = 0; int sy = 0; /* clip to the dst image boundaries */ if (x < 0) { sx += -x; sw -= -x; x = 0; } if (y < 0) { sy += -y; sh -= -y; y = 0; } if (x + sw >= dst->width) sw = dst->width - x; if (y + sh >= dst->height) sh = dst->height - y; switch (op) { case JBIG2_COMPOSE_OR: for (j = 0; j < sh; j++) { for (i = 0; i < sw; i++) { jbig2_image_set_pixel(dst, i + x, j + y, jbig2_image_get_pixel(src, i + sx, j + sy) | jbig2_image_get_pixel(dst, i + x, j + y)); } } break; case JBIG2_COMPOSE_AND: for (j = 0; j < sh; j++) { for (i = 0; i < sw; i++) { jbig2_image_set_pixel(dst, i + x, j + y, jbig2_image_get_pixel(src, i + sx, j + sy) & jbig2_image_get_pixel(dst, i + x, j + y)); } } break; case JBIG2_COMPOSE_XOR: for (j = 0; j < sh; j++) { for (i = 0; i < sw; i++) { jbig2_image_set_pixel(dst, i + x, j + y, jbig2_image_get_pixel(src, i + sx, j + sy) ^ jbig2_image_get_pixel(dst, i + x, j + y)); } } break; case JBIG2_COMPOSE_XNOR: for (j = 0; j < sh; j++) { for (i = 0; i < sw; i++) { jbig2_image_set_pixel(dst, i + x, j + y, (jbig2_image_get_pixel(src, i + sx, j + sy) == jbig2_image_get_pixel(dst, i + x, j + y))); } } break; case JBIG2_COMPOSE_REPLACE: for (j = 0; j < sh; j++) { for (i = 0; i < sw; i++) { jbig2_image_set_pixel(dst, i + x, j + y, jbig2_image_get_pixel(src, i + sx, j + sy)); } } break; } return 0; } Commit Message: CWE ID: CWE-119
1
165,490
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void DeviceTokenFetcher::Initialize(DeviceManagementService* service, CloudPolicyCacheBase* cache, CloudPolicyDataStore* data_store, PolicyNotifier* notifier, DelayedWorkScheduler* scheduler) { service_ = service; cache_ = cache; notifier_ = notifier; data_store_ = data_store; effective_token_fetch_error_delay_ms_ = kTokenFetchErrorDelayMilliseconds; state_ = STATE_INACTIVE; scheduler_.reset(scheduler); if (cache_->is_unmanaged()) SetState(STATE_UNMANAGED); } Commit Message: Reset the device policy machinery upon retrying enrollment. BUG=chromium-os:18208 TEST=See bug description Review URL: http://codereview.chromium.org/7676005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
0
97,790
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 CreateMagnetometer() { auto callback = base::Bind(&PlatformSensorFusionTest::MagnetometerCallback, base::Unretained(this)); provider_->CreateSensor(SensorType::MAGNETOMETER, callback); EXPECT_TRUE(magnetometer_callback_called_); EXPECT_TRUE(magnetometer_); EXPECT_EQ(SensorType::MAGNETOMETER, magnetometer_->GetType()); } Commit Message: android: Fix sensors in device service. This patch fixes a bug that prevented more than one sensor data to be available at once when using the device motion/orientation API. The issue was introduced by this other patch [1] which fixed some security-related issues in the way shared memory region handles are managed throughout Chromium (more details at https://crbug.com/789959). The device service´s sensor implementation doesn´t work correctly because it assumes it is possible to create a writable mapping of a given shared memory region at any time. This assumption is not correct on Android, once an Ashmem region has been turned read-only, such mappings are no longer possible. To fix the implementation, this CL changes the following: - PlatformSensor used to require moving a mojo::ScopedSharedBufferMapping into the newly-created instance. Said mapping being owned by and destroyed with the PlatformSensor instance. With this patch, the constructor instead takes a single pointer to the corresponding SensorReadingSharedBuffer, i.e. the area in memory where the sensor-specific reading data is located, and can be either updated or read-from. Note that the PlatformSensor does not own the mapping anymore. - PlatformSensorProviderBase holds the *single* writable mapping that is used to store all SensorReadingSharedBuffer buffers. It is created just after the region itself, and thus can be used even after the region's access mode has been changed to read-only. Addresses within the mapping will be passed to PlatformSensor constructors, computed from the mapping's base address plus a sensor-specific offset. The mapping is now owned by the PlatformSensorProviderBase instance. Note that, security-wise, nothing changes, because all mojo::ScopedSharedBufferMapping before the patch actually pointed to the same writable-page in memory anyway. Since unit or integration tests didn't catch the regression when [1] was submitted, this patch was tested manually by running a newly-built Chrome apk in the Android emulator and on a real device running Android O. [1] https://chromium-review.googlesource.com/c/chromium/src/+/805238 BUG=805146 R=mattcary@chromium.org,alexilin@chromium.org,juncai@chromium.org,reillyg@chromium.org Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44 Reviewed-on: https://chromium-review.googlesource.com/891180 Commit-Queue: David Turner <digit@chromium.org> Reviewed-by: Reilly Grant <reillyg@chromium.org> Reviewed-by: Matthew Cary <mattcary@chromium.org> Reviewed-by: Alexandr Ilin <alexilin@chromium.org> Cr-Commit-Position: refs/heads/master@{#532607} CWE ID: CWE-732
0
148,963
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 RenderThreadImpl::IsWebFrameValid(WebKit::WebFrame* web_frame) { if (!web_frame) return false; // We must be shutting down. RenderViewImpl* render_view = RenderViewImpl::FromWebView(web_frame->view()); if (!render_view) return false; // We must be shutting down. return true; } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
0
107,093
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 stringAttrAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); TestObjectV8Internal::stringAttrAttributeSetter(jsValue, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } 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
121,998
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 __f2fs_replace_block(struct f2fs_sb_info *sbi, struct f2fs_summary *sum, block_t old_blkaddr, block_t new_blkaddr, bool recover_curseg, bool recover_newaddr) { struct sit_info *sit_i = SIT_I(sbi); struct curseg_info *curseg; unsigned int segno, old_cursegno; struct seg_entry *se; int type; unsigned short old_blkoff; segno = GET_SEGNO(sbi, new_blkaddr); se = get_seg_entry(sbi, segno); type = se->type; if (!recover_curseg) { /* for recovery flow */ if (se->valid_blocks == 0 && !IS_CURSEG(sbi, segno)) { if (old_blkaddr == NULL_ADDR) type = CURSEG_COLD_DATA; else type = CURSEG_WARM_DATA; } } else { if (!IS_CURSEG(sbi, segno)) type = CURSEG_WARM_DATA; } curseg = CURSEG_I(sbi, type); mutex_lock(&curseg->curseg_mutex); mutex_lock(&sit_i->sentry_lock); old_cursegno = curseg->segno; old_blkoff = curseg->next_blkoff; /* change the current segment */ if (segno != curseg->segno) { curseg->next_segno = segno; change_curseg(sbi, type); } curseg->next_blkoff = GET_BLKOFF_FROM_SEG0(sbi, new_blkaddr); __add_sum_entry(sbi, type, sum); if (!recover_curseg || recover_newaddr) update_sit_entry(sbi, new_blkaddr, 1); if (GET_SEGNO(sbi, old_blkaddr) != NULL_SEGNO) update_sit_entry(sbi, old_blkaddr, -1); locate_dirty_segment(sbi, GET_SEGNO(sbi, old_blkaddr)); locate_dirty_segment(sbi, GET_SEGNO(sbi, new_blkaddr)); locate_dirty_segment(sbi, old_cursegno); if (recover_curseg) { if (old_cursegno != curseg->segno) { curseg->next_segno = old_cursegno; change_curseg(sbi, type); } curseg->next_blkoff = old_blkoff; } mutex_unlock(&sit_i->sentry_lock); mutex_unlock(&curseg->curseg_mutex); } Commit Message: f2fs: fix potential panic during fstrim As Ju Hyung Park reported: "When 'fstrim' is called for manual trim, a BUG() can be triggered randomly with this patch. I'm seeing this issue on both x86 Desktop and arm64 Android phone. On x86 Desktop, this was caused during Ubuntu boot-up. I have a cronjob installed which calls 'fstrim -v /' during boot. On arm64 Android, this was caused during GC looping with 1ms gc_min_sleep_time & gc_max_sleep_time." Root cause of this issue is that f2fs_wait_discard_bios can only be used by f2fs_put_super, because during put_super there must be no other referrers, so it can ignore discard entry's reference count when removing the entry, otherwise in other caller we will hit bug_on in __remove_discard_cmd as there may be other issuer added reference count in discard entry. Thread A Thread B - issue_discard_thread - f2fs_ioc_fitrim - f2fs_trim_fs - f2fs_wait_discard_bios - __issue_discard_cmd - __submit_discard_cmd - __wait_discard_cmd - dc->ref++ - __wait_one_discard_bio - __wait_discard_cmd - __remove_discard_cmd - f2fs_bug_on(sbi, dc->ref) Fixes: 969d1b180d987c2be02de890d0fff0f66a0e80de Reported-by: Ju Hyung Park <qkrwngud825@gmail.com> Signed-off-by: Chao Yu <yuchao0@huawei.com> Signed-off-by: Jaegeuk Kim <jaegeuk@kernel.org> CWE ID: CWE-20
0
86,002
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: context_switch(struct rq *rq, struct task_struct *prev, struct task_struct *next, struct pin_cookie cookie) { struct mm_struct *mm, *oldmm; prepare_task_switch(rq, prev, next); mm = next->mm; oldmm = prev->active_mm; /* * For paravirt, this is coupled with an exit in switch_to to * combine the page table reload and the switch backend into * one hypercall. */ arch_start_context_switch(prev); if (!mm) { next->active_mm = oldmm; atomic_inc(&oldmm->mm_count); enter_lazy_tlb(oldmm, next); } else switch_mm_irqs_off(oldmm, mm, next); if (!prev->mm) { prev->active_mm = NULL; rq->prev_mm = oldmm; } /* * Since the runqueue lock will be released by the next * task (which is an invalid locking op but in the case * of the scheduler it's an obvious special-case), so we * do an early lockdep release here: */ lockdep_unpin_lock(&rq->lock, cookie); spin_release(&rq->lock.dep_map, 1, _THIS_IP_); /* Here we just switch the register state and the stack. */ switch_to(prev, next, prev); barrier(); return finish_task_switch(prev); } Commit Message: Merge branch 'stacking-fixes' (vfs stacking fixes from Jann) Merge filesystem stacking fixes from Jann Horn. * emailed patches from Jann Horn <jannh@google.com>: sched: panic on corrupted stack end ecryptfs: forbid opening files without mmap handler proc: prevent stacking filesystems on top CWE ID: CWE-119
0
55,498
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 setcalrgbspace(i_ctx_t * i_ctx_p, ref *r, int *stage, int *cont, int CIESubst) { ref rgbdict; int code = 0; float gamma[3], white[3], black[3], matrix[9]; static const float dflt_gamma[3] = { 1.0, 1.0, 1.0 }; static const float dflt_black[3] = {0,0,0}, dflt_white[3] = {0,0,0}; static const float dflt_matrix[9] = {1,0,0,0,1,0,0,0,1}; int i; gs_client_color cc; *cont = 0; code = array_get(imemory, r, 1, &rgbdict); if (code < 0) return code; /* Get all the parts */ code = dict_floats_param( imemory, &rgbdict, "Gamma", 3, gamma, dflt_gamma ); if (code < 0) return code; if (gamma[0] <= 0 || gamma[1] <= 0 || gamma[2] <= 0) return_error(gs_error_rangecheck); code = dict_floats_param( imemory, &rgbdict, "BlackPoint", 3, black, dflt_black ); if (code < 0) return code; code = dict_floats_param( imemory, &rgbdict, "WhitePoint", 3, white, dflt_white ); if (code < 0) return code; if (white[0] <= 0 || white[1] != 1.0 || white[2] <= 0) return_error(gs_error_rangecheck); code = dict_floats_param( imemory, &rgbdict, "Matrix", 9, matrix, dflt_matrix ); if (code < 0) return code; code = seticc_cal(i_ctx_p, white, black, gamma, matrix, 3, rgbdict.value.saveid); if ( code < 0) return gs_rethrow(code, "setting CalRGB color space"); cc.pattern = 0x00; for (i=0;i<3;i++) cc.paint.values[i] = 0; code = gs_setcolor(igs, &cc); return code; } Commit Message: CWE ID: CWE-704
0
3,134
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: ExtensionUninstallDialog* AppLauncherHandler::GetExtensionUninstallDialog() { if (!extension_uninstall_dialog_.get()) { Browser* browser = chrome::FindBrowserWithWebContents( web_ui()->GetWebContents()); extension_uninstall_dialog_.reset( ExtensionUninstallDialog::Create(extension_service_->profile(), browser, this)); } return extension_uninstall_dialog_.get(); } Commit Message: Remove --disable-app-shims. App shims have been enabled by default for 3 milestones (since r242711). BUG=350161 Review URL: https://codereview.chromium.org/298953002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@272786 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
0
110,332
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: IntPoint FrameView::convertFromRenderer(const RenderObject& renderer, const IntPoint& rendererPoint) const { IntPoint point = roundedIntPoint(renderer.localToAbsolute(rendererPoint, UseTransforms)); point.moveBy(-scrollPosition()); return point; } Commit Message: Defer call to updateWidgetPositions() outside of RenderLayerScrollableArea. updateWidgetPositions() can destroy the render tree, so it should never be called from inside RenderLayerScrollableArea. Leaving it there allows for the potential of use-after-free bugs. BUG=402407 R=vollick@chromium.org Review URL: https://codereview.chromium.org/490473003 git-svn-id: svn://svn.chromium.org/blink/trunk@180681 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-416
0
119,818
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 sctp_getsockopt_sctp_status(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_status status; struct sctp_association *asoc = NULL; struct sctp_transport *transport; sctp_assoc_t associd; int retval = 0; if (len < sizeof(status)) { retval = -EINVAL; goto out; } len = sizeof(status); if (copy_from_user(&status, optval, len)) { retval = -EFAULT; goto out; } associd = status.sstat_assoc_id; asoc = sctp_id2assoc(sk, associd); if (!asoc) { retval = -EINVAL; goto out; } transport = asoc->peer.primary_path; status.sstat_assoc_id = sctp_assoc2id(asoc); status.sstat_state = asoc->state; status.sstat_rwnd = asoc->peer.rwnd; status.sstat_unackdata = asoc->unack_data; status.sstat_penddata = sctp_tsnmap_pending(&asoc->peer.tsn_map); status.sstat_instrms = asoc->c.sinit_max_instreams; status.sstat_outstrms = asoc->c.sinit_num_ostreams; status.sstat_fragmentation_point = asoc->frag_point; status.sstat_primary.spinfo_assoc_id = sctp_assoc2id(transport->asoc); memcpy(&status.sstat_primary.spinfo_address, &transport->ipaddr, transport->af_specific->sockaddr_len); /* Map ipv4 address into v4-mapped-on-v6 address. */ sctp_get_pf_specific(sk->sk_family)->addr_v4map(sctp_sk(sk), (union sctp_addr *)&status.sstat_primary.spinfo_address); status.sstat_primary.spinfo_state = transport->state; status.sstat_primary.spinfo_cwnd = transport->cwnd; status.sstat_primary.spinfo_srtt = transport->srtt; status.sstat_primary.spinfo_rto = jiffies_to_msecs(transport->rto); status.sstat_primary.spinfo_mtu = transport->pathmtu; if (status.sstat_primary.spinfo_state == SCTP_UNKNOWN) status.sstat_primary.spinfo_state = SCTP_ACTIVE; if (put_user(len, optlen)) { retval = -EFAULT; goto out; } SCTP_DEBUG_PRINTK("sctp_getsockopt_sctp_status(%d): %d %d %d\n", len, status.sstat_state, status.sstat_rwnd, status.sstat_assoc_id); if (copy_to_user(optval, &status, len)) { retval = -EFAULT; goto out; } out: return retval; } Commit Message: net/sctp: Validate parameter size for SCTP_GET_ASSOC_STATS Building sctp may fail with: In function ‘copy_from_user’, inlined from ‘sctp_getsockopt_assoc_stats’ at net/sctp/socket.c:5656:20: arch/x86/include/asm/uaccess_32.h:211:26: error: call to ‘copy_from_user_overflow’ declared with attribute error: copy_from_user() buffer size is not provably correct if built with W=1 due to a missing parameter size validation before the call to copy_from_user. Signed-off-by: Guenter Roeck <linux@roeck-us.net> Acked-by: Vlad Yasevich <vyasevich@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-20
0
33,019
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static Image *ReadXCFImage(const ImageInfo *image_info,ExceptionInfo *exception) { char magick[14]; Image *image; int foundPropEnd = 0; MagickBooleanType status; MagickOffsetType offset; register ssize_t i; size_t image_type, length; ssize_t count; XCFDocInfo doc_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } count=ReadBlob(image,14,(unsigned char *) magick); if ((count != 14) || (LocaleNCompare((char *) magick,"gimp xcf",8) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ResetMagickMemory(&doc_info,0,sizeof(XCFDocInfo)); doc_info.exception=exception; doc_info.width=ReadBlobMSBLong(image); doc_info.height=ReadBlobMSBLong(image); if ((doc_info.width > 262144) || (doc_info.height > 262144)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); doc_info.image_type=ReadBlobMSBLong(image); /* Initialize image attributes. */ image->columns=doc_info.width; image->rows=doc_info.height; image_type=doc_info.image_type; doc_info.file_size=GetBlobSize(image); image->compression=NoCompression; image->depth=8; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (image_type == GIMP_RGB) ; else if (image_type == GIMP_GRAY) image->colorspace=GRAYColorspace; else if (image_type == GIMP_INDEXED) ThrowReaderException(CoderError,"ColormapTypeNotSupported"); (void) SetImageOpacity(image,OpaqueOpacity); (void) SetImageBackgroundColor(image); /* Read properties. */ while ((foundPropEnd == MagickFalse) && (EOFBlob(image) == MagickFalse)) { PropType prop_type = (PropType) ReadBlobMSBLong(image); size_t prop_size = ReadBlobMSBLong(image); switch (prop_type) { case PROP_END: foundPropEnd=1; break; case PROP_COLORMAP: { /* Cannot rely on prop_size here--the value is set incorrectly by some Gimp versions. */ size_t num_colours = ReadBlobMSBLong(image); if (DiscardBlobBytes(image,3*num_colours) == MagickFalse) ThrowFileException(&image->exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); /* if (info->file_version == 0) { gint i; g_message (_("XCF warning: version 0 of XCF file format\n" "did not save indexed colormaps correctly.\n" "Substituting grayscale map.")); info->cp += xcf_read_int32 (info->fp, (guint32*) &gimage->num_cols, 1); gimage->cmap = g_new (guchar, gimage->num_cols*3); xcf_seek_pos (info, info->cp + gimage->num_cols); for (i = 0; i<gimage->num_cols; i++) { gimage->cmap[i*3+0] = i; gimage->cmap[i*3+1] = i; gimage->cmap[i*3+2] = i; } } else { info->cp += xcf_read_int32 (info->fp, (guint32*) &gimage->num_cols, 1); gimage->cmap = g_new (guchar, gimage->num_cols*3); info->cp += xcf_read_int8 (info->fp, (guint8*) gimage->cmap, gimage->num_cols*3); } */ break; } case PROP_COMPRESSION: { doc_info.compression = ReadBlobByte(image); if ((doc_info.compression != COMPRESS_NONE) && (doc_info.compression != COMPRESS_RLE) && (doc_info.compression != COMPRESS_ZLIB) && (doc_info.compression != COMPRESS_FRACTAL)) ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression"); } break; case PROP_GUIDES: { /* just skip it - we don't care about guides */ if (DiscardBlobBytes(image,prop_size) == MagickFalse) ThrowFileException(&image->exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); } break; case PROP_RESOLUTION: { /* float xres = (float) */ (void) ReadBlobMSBLong(image); /* float yres = (float) */ (void) ReadBlobMSBLong(image); /* if (xres < GIMP_MIN_RESOLUTION || xres > GIMP_MAX_RESOLUTION || yres < GIMP_MIN_RESOLUTION || yres > GIMP_MAX_RESOLUTION) { g_message ("Warning, resolution out of range in XCF file"); xres = gimage->gimp->config->default_xresolution; yres = gimage->gimp->config->default_yresolution; } */ /* BOGUS: we don't write these yet because we aren't reading them properly yet :( image->x_resolution = xres; image->y_resolution = yres; */ } break; case PROP_TATTOO: { /* we need to read it, even if we ignore it */ /*size_t tattoo_state = */ (void) ReadBlobMSBLong(image); } break; case PROP_PARASITES: { /* BOGUS: we may need these for IPTC stuff */ if (DiscardBlobBytes(image,prop_size) == MagickFalse) ThrowFileException(&image->exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); /* gssize_t base = info->cp; GimpParasite *p; while (info->cp - base < prop_size) { p = xcf_load_parasite (info); gimp_image_parasite_attach (gimage, p); gimp_parasite_free (p); } if (info->cp - base != prop_size) g_message ("Error detected while loading an image's parasites"); */ } break; case PROP_UNIT: { /* BOGUS: ignore for now... */ /*size_t unit = */ (void) ReadBlobMSBLong(image); } break; case PROP_PATHS: { /* BOGUS: just skip it for now */ if (DiscardBlobBytes(image,prop_size) == MagickFalse) ThrowFileException(&image->exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); /* PathList *paths = xcf_load_bzpaths (gimage, info); gimp_image_set_paths (gimage, paths); */ } break; case PROP_USER_UNIT: { char unit_string[1000]; /*BOGUS: ignored for now */ /*float factor = (float) */ (void) ReadBlobMSBLong(image); /* size_t digits = */ (void) ReadBlobMSBLong(image); for (i=0; i<5; i++) (void) ReadBlobStringWithLongSize(image, unit_string, sizeof(unit_string)); } break; default: { int buf[16]; ssize_t amount; /* read over it... */ while ((prop_size > 0) && (EOFBlob(image) == MagickFalse)) { amount=(ssize_t) MagickMin(16, prop_size); amount=(ssize_t) ReadBlob(image,(size_t) amount,(unsigned char *) &buf); if (!amount) ThrowReaderException(CorruptImageError,"CorruptImage"); prop_size -= (size_t) MagickMin(16,(size_t) amount); } } break; } } if (foundPropEnd == MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) { ; /* do nothing, were just pinging! */ } else { int current_layer = 0, foundAllLayers = MagickFalse, number_layers = 0; MagickOffsetType oldPos=TellBlob(image); XCFLayerInfo *layer_info; /* The read pointer. */ do { ssize_t offset = ReadBlobMSBSignedLong(image); if (offset == 0) foundAllLayers=MagickTrue; else number_layers++; if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } } while (foundAllLayers == MagickFalse); doc_info.number_layers=number_layers; offset=SeekBlob(image,oldPos,SEEK_SET); /* restore the position! */ if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* allocate our array of layer info blocks */ length=(size_t) number_layers; layer_info=(XCFLayerInfo *) AcquireQuantumMemory(length, sizeof(*layer_info)); if (layer_info == (XCFLayerInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(layer_info,0,number_layers*sizeof(XCFLayerInfo)); for ( ; ; ) { MagickBooleanType layer_ok; MagickOffsetType offset, saved_pos; /* read in the offset of the next layer */ offset=(MagickOffsetType) ReadBlobMSBLong(image); /* if the offset is 0 then we are at the end * of the layer list. */ if (offset == 0) break; /* save the current position as it is where the * next layer offset is stored. */ saved_pos=TellBlob(image); /* seek to the layer offset */ if (SeekBlob(image,offset,SEEK_SET) != offset) ThrowReaderException(ResourceLimitError,"NotEnoughPixelData"); /* read in the layer */ layer_ok=ReadOneLayer(image_info,image,&doc_info, &layer_info[current_layer],current_layer); if (layer_ok == MagickFalse) { int j; for (j=0; j < current_layer; j++) layer_info[j].image=DestroyImage(layer_info[j].image); layer_info=(XCFLayerInfo *) RelinquishMagickMemory(layer_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } /* restore the saved position so we'll be ready to * read the next offset. */ offset=SeekBlob(image, saved_pos, SEEK_SET); current_layer++; } #if 0 { /* NOTE: XCF layers are REVERSED from composite order! */ signed int j; for (j=number_layers-1; j>=0; j--) { /* BOGUS: need to consider layer blending modes!! */ if ( layer_info[j].visible ) { /* only visible ones, please! */ CompositeImage(image, OverCompositeOp, layer_info[j].image, layer_info[j].offset_x, layer_info[j].offset_y ); layer_info[j].image =DestroyImage( layer_info[j].image ); /* If we do this, we'll get REAL gray images! */ if ( image_type == GIMP_GRAY ) { QuantizeInfo qi; GetQuantizeInfo(&qi); qi.colorspace = GRAYColorspace; QuantizeImage( &qi, layer_info[j].image ); } } } } #else { /* NOTE: XCF layers are REVERSED from composite order! */ ssize_t j; /* now reverse the order of the layers as they are put into subimages */ for (j=(long) number_layers-1; j >= 0; j--) AppendImageToList(&image,layer_info[j].image); } #endif layer_info=(XCFLayerInfo *) RelinquishMagickMemory(layer_info); #if 0 /* BOGUS: do we need the channels?? */ while (MagickTrue) { /* read in the offset of the next channel */ info->cp += xcf_read_int32 (info->fp, &offset, 1); /* if the offset is 0 then we are at the end * of the channel list. */ if (offset == 0) break; /* save the current position as it is where the * next channel offset is stored. */ saved_pos = info->cp; /* seek to the channel offset */ xcf_seek_pos (info, offset); /* read in the layer */ channel = xcf_load_channel (info, gimage); if (channel == 0) goto error; num_successful_elements++; /* add the channel to the image if its not the selection */ if (channel != gimage->selection_mask) gimp_image_add_channel (gimage, channel, -1); /* restore the saved position so we'll be ready to * read the next offset. */ xcf_seek_pos (info, saved_pos); } #endif } (void) CloseBlob(image); DestroyImage(RemoveFirstImageFromList(&image)); if (image_type == GIMP_GRAY) image->type=GrayscaleType; return(GetFirstImageInList(image)); } Commit Message: Check for image list before we destroy the last image in XCF coder (patch sent privately by Андрей Черный) CWE ID: CWE-476
1
168,329
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret, struct net_device *orig_dev) { #ifdef CONFIG_NETFILTER_INGRESS if (nf_hook_ingress_active(skb)) { int ingress_retval; if (*pt_prev) { *ret = deliver_skb(skb, *pt_prev, orig_dev); *pt_prev = NULL; } rcu_read_lock(); ingress_retval = nf_hook_ingress(skb); rcu_read_unlock(); return ingress_retval; } #endif /* CONFIG_NETFILTER_INGRESS */ return 0; } Commit Message: tun: call dev_get_valid_name() before register_netdevice() register_netdevice() could fail early when we have an invalid dev name, in which case ->ndo_uninit() is not called. For tun device, this is a problem because a timer etc. are already initialized and it expects ->ndo_uninit() to clean them up. We could move these initializations into a ->ndo_init() so that register_netdevice() knows better, however this is still complicated due to the logic in tun_detach(). Therefore, I choose to just call dev_get_valid_name() before register_netdevice(), which is quicker and much easier to audit. And for this specific case, it is already enough. Fixes: 96442e42429e ("tuntap: choose the txq based on rxq") Reported-by: Dmitry Alexeev <avekceeb@gmail.com> Cc: Jason Wang <jasowang@redhat.com> Cc: "Michael S. Tsirkin" <mst@redhat.com> Signed-off-by: Cong Wang <xiyou.wangcong@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-476
0
93,453
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: media_status_t AMediaCodec_releaseOutputBuffer(AMediaCodec *mData, size_t idx, bool render) { if (render) { return translate_error(mData->mCodec->renderOutputBufferAndRelease(idx)); } else { return translate_error(mData->mCodec->releaseOutputBuffer(idx)); } } Commit Message: Check for overflow of crypto size Bug: 111603051 Test: CTS Change-Id: Ib5b1802b9b35769a25c16e2b977308cf7a810606 (cherry picked from commit d1fd02761236b35a336434367131f71bef7405c9) CWE ID: CWE-190
0
163,005
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void GLES2DecoderPassthroughImpl::RestoreDeviceWindowRectangles() const {} 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
0
141,818
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 paging64_init_context_common(struct kvm_vcpu *vcpu, struct kvm_mmu *context, int level) { context->nx = is_nx(vcpu); context->root_level = level; reset_rsvds_bits_mask(vcpu, context); update_permission_bitmask(vcpu, context, false); update_last_pte_bitmap(vcpu, context); ASSERT(is_pae(vcpu)); context->new_cr3 = paging_new_cr3; context->page_fault = paging64_page_fault; context->gva_to_gpa = paging64_gva_to_gpa; context->sync_page = paging64_sync_page; context->invlpg = paging64_invlpg; context->update_pte = paging64_update_pte; context->free = paging_free; context->shadow_root_level = level; context->root_hpa = INVALID_PAGE; context->direct_map = false; return 0; } Commit Message: nEPT: Nested INVEPT If we let L1 use EPT, we should probably also support the INVEPT instruction. In our current nested EPT implementation, when L1 changes its EPT table for L2 (i.e., EPT12), L0 modifies the shadow EPT table (EPT02), and in the course of this modification already calls INVEPT. But if last level of shadow page is unsync not all L1's changes to EPT12 are intercepted, which means roots need to be synced when L1 calls INVEPT. Global INVEPT should not be different since roots are synced by kvm_mmu_load() each time EPTP02 changes. Reviewed-by: Xiao Guangrong <xiaoguangrong@linux.vnet.ibm.com> Signed-off-by: Nadav Har'El <nyh@il.ibm.com> Signed-off-by: Jun Nakajima <jun.nakajima@intel.com> Signed-off-by: Xinhao Xu <xinhao.xu@intel.com> Signed-off-by: Yang Zhang <yang.z.zhang@Intel.com> Signed-off-by: Gleb Natapov <gleb@redhat.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> CWE ID: CWE-20
0
37,565
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: json_t *json_rpc_call(CURL *curl, const char *url, const char *userpass, const char *rpc_req, bool probe, bool longpoll, int *rolltime, struct pool *pool, bool share) { long timeout = longpoll ? (60 * 60) : 60; struct data_buffer all_data = {NULL, 0}; struct header_info hi = {NULL, 0, NULL, NULL, false, false, false}; char len_hdr[64], user_agent_hdr[128]; char curl_err_str[CURL_ERROR_SIZE]; struct curl_slist *headers = NULL; struct upload_buffer upload_data; json_t *val, *err_val, *res_val; bool probing = false; double byte_count; json_error_t err; int rc; memset(&err, 0, sizeof(err)); /* it is assumed that 'curl' is freshly [re]initialized at this pt */ if (probe) probing = !pool->probed; curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout); curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb); curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool); curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_ENCODING, ""); curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1); /* Shares are staggered already and delays in submission can be costly * so do not delay them */ if (!opt_delaynet || share) curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data); curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb); curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data); curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb); curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi); curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY); if (pool->rpc_proxy) { curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy); curl_easy_setopt(curl, CURLOPT_PROXYTYPE, pool->rpc_proxytype); } else if (opt_socks_proxy) { curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy); curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4); } if (userpass) { curl_easy_setopt(curl, CURLOPT_USERPWD, userpass); curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); } if (longpoll) keep_curlalive(curl); curl_easy_setopt(curl, CURLOPT_POST, 1); if (opt_protocol) applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req); upload_data.buf = rpc_req; upload_data.len = strlen(rpc_req); sprintf(len_hdr, "Content-Length: %lu", (unsigned long) upload_data.len); sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING); headers = curl_slist_append(headers, "Content-type: application/json"); headers = curl_slist_append(headers, "X-Mining-Extensions: longpoll midstate rollntime submitold"); if (likely(global_hashrate)) { char ghashrate[255]; sprintf(ghashrate, "X-Mining-Hashrate: %llu", global_hashrate); headers = curl_slist_append(headers, ghashrate); } headers = curl_slist_append(headers, len_hdr); headers = curl_slist_append(headers, user_agent_hdr); headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/ curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); if (opt_delaynet) { /* Don't delay share submission, but still track the nettime */ if (!share) { long long now_msecs, last_msecs; struct timeval now, last; cgtime(&now); last_nettime(&last); now_msecs = (long long)now.tv_sec * 1000; now_msecs += now.tv_usec / 1000; last_msecs = (long long)last.tv_sec * 1000; last_msecs += last.tv_usec / 1000; if (now_msecs > last_msecs && now_msecs - last_msecs < 250) { struct timespec rgtp; rgtp.tv_sec = 0; rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000; nanosleep(&rgtp, NULL); } } set_nettime(); } rc = curl_easy_perform(curl); if (rc) { applog(LOG_INFO, "HTTP request failed: %s", curl_err_str); goto err_out; } if (!all_data.buf) { applog(LOG_DEBUG, "Empty data received in json_rpc_call."); goto err_out; } pool->cgminer_pool_stats.times_sent++; if (curl_easy_getinfo(curl, CURLINFO_SIZE_UPLOAD, &byte_count) == CURLE_OK) pool->cgminer_pool_stats.bytes_sent += byte_count; pool->cgminer_pool_stats.times_received++; if (curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &byte_count) == CURLE_OK) pool->cgminer_pool_stats.bytes_received += byte_count; if (probing) { pool->probed = true; /* If X-Long-Polling was found, activate long polling */ if (hi.lp_path) { if (pool->hdr_path != NULL) free(pool->hdr_path); pool->hdr_path = hi.lp_path; } else pool->hdr_path = NULL; if (hi.stratum_url) { pool->stratum_url = hi.stratum_url; hi.stratum_url = NULL; } } else { if (hi.lp_path) { free(hi.lp_path); hi.lp_path = NULL; } if (hi.stratum_url) { free(hi.stratum_url); hi.stratum_url = NULL; } } *rolltime = hi.rolltime; pool->cgminer_pool_stats.rolltime = hi.rolltime; pool->cgminer_pool_stats.hadrolltime = hi.hadrolltime; pool->cgminer_pool_stats.canroll = hi.canroll; pool->cgminer_pool_stats.hadexpire = hi.hadexpire; val = JSON_LOADS(all_data.buf, &err); if (!val) { applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text); if (opt_protocol) applog(LOG_DEBUG, "JSON protocol response:\n%s", (char *)(all_data.buf)); goto err_out; } if (opt_protocol) { char *s = json_dumps(val, JSON_INDENT(3)); applog(LOG_DEBUG, "JSON protocol response:\n%s", s); free(s); } /* JSON-RPC valid response returns a non-null 'result', * and a null 'error'. */ res_val = json_object_get(val, "result"); err_val = json_object_get(val, "error"); if (!res_val ||(err_val && !json_is_null(err_val))) { char *s; if (err_val) s = json_dumps(err_val, JSON_INDENT(3)); else s = strdup("(unknown reason)"); applog(LOG_INFO, "JSON-RPC call failed: %s", s); free(s); goto err_out; } if (hi.reason) { json_object_set_new(val, "reject-reason", json_string(hi.reason)); free(hi.reason); hi.reason = NULL; } successful_connect = true; databuf_free(&all_data); curl_slist_free_all(headers); curl_easy_reset(curl); return val; err_out: databuf_free(&all_data); curl_slist_free_all(headers); curl_easy_reset(curl); if (!successful_connect) applog(LOG_DEBUG, "Failed to connect in json_rpc_call"); curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1); return NULL; } Commit Message: Do some random sanity checking for stratum message parsing CWE ID: CWE-119
0
36,663
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: SegmentInfo::SegmentInfo( Segment* pSegment, long long start, long long size_, long long element_start, long long element_size) : m_pSegment(pSegment), m_start(start), m_size(size_), m_element_start(element_start), m_element_size(element_size), m_pMuxingAppAsUTF8(NULL), m_pWritingAppAsUTF8(NULL), m_pTitleAsUTF8(NULL) { } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
1
174,439
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: FilePath GDataCache::GetCacheRootPath(Profile* profile) { FilePath cache_base_path; chrome::GetUserCacheDirectory(profile->GetPath(), &cache_base_path); FilePath cache_root_path = cache_base_path.Append(chrome::kGDataCacheDirname); return cache_root_path.Append(kGDataCacheVersionDir); } Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories Broke linux_chromeos_valgrind: http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio In theory, we shouldn't have any invalid files left in the cache directories, but things can go wrong and invalid files may be left if the device shuts down unexpectedly, for instance. Besides, it's good to be defensive. BUG=134862 TEST=added unit tests Review URL: https://chromiumcodereview.appspot.com/10693020 TBR=satorux@chromium.org git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
0
105,929
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 split_huge_page(struct page *page) { struct anon_vma *anon_vma; int ret = 1; BUG_ON(!PageAnon(page)); anon_vma = page_lock_anon_vma(page); if (!anon_vma) goto out; ret = 0; if (!PageCompound(page)) goto out_unlock; BUG_ON(!PageSwapBacked(page)); __split_huge_page(page, anon_vma); count_vm_event(THP_SPLIT); BUG_ON(PageCompound(page)); out_unlock: page_unlock_anon_vma(anon_vma); out: return ret; } Commit Message: mm: thp: fix /dev/zero MAP_PRIVATE and vm_flags cleanups The huge_memory.c THP page fault was allowed to run if vm_ops was null (which would succeed for /dev/zero MAP_PRIVATE, as the f_op->mmap wouldn't setup a special vma->vm_ops and it would fallback to regular anonymous memory) but other THP logics weren't fully activated for vmas with vm_file not NULL (/dev/zero has a not NULL vma->vm_file). So this removes the vm_file checks so that /dev/zero also can safely use THP (the other albeit safer approach to fix this bug would have been to prevent the THP initial page fault to run if vm_file was set). After removing the vm_file checks, this also makes huge_memory.c stricter in khugepaged for the DEBUG_VM=y case. It doesn't replace the vm_file check with a is_pfn_mapping check (but it keeps checking for VM_PFNMAP under VM_BUG_ON) because for a is_cow_mapping() mapping VM_PFNMAP should only be allowed to exist before the first page fault, and in turn when vma->anon_vma is null (so preventing khugepaged registration). So I tend to think the previous comment saying if vm_file was set, VM_PFNMAP might have been set and we could still be registered in khugepaged (despite anon_vma was not NULL to be registered in khugepaged) was too paranoid. The is_linear_pfn_mapping check is also I think superfluous (as described by comment) but under DEBUG_VM it is safe to stay. Addresses https://bugzilla.kernel.org/show_bug.cgi?id=33682 Signed-off-by: Andrea Arcangeli <aarcange@redhat.com> Reported-by: Caspar Zhang <bugs@casparzhang.com> Acked-by: Mel Gorman <mel@csn.ul.ie> Acked-by: Rik van Riel <riel@redhat.com> Cc: <stable@kernel.org> [2.6.38.x] Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-399
0
35,135
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: _kdc_fix_time(time_t **t) { if(*t == NULL){ ALLOC(*t); **t = MAX_TIME; } if(**t == 0) **t = MAX_TIME; /* fix for old clients */ } Commit Message: Security: Avoid NULL structure pointer member dereference This can happen in the error path when processing malformed AS requests with a NULL client name. Bug originally introduced on Fri Feb 13 09:26:01 2015 +0100 in commit: a873e21d7c06f22943a90a41dc733ae76799390d kdc: base _kdc_fast_mk_error() on krb5_mk_error_ext() Original patch by Jeffrey Altman <jaltman@secure-endpoints.com> CWE ID: CWE-476
0
59,222
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: ctx_pinned_sched_in(struct perf_event_context *ctx, struct perf_cpu_context *cpuctx) { struct perf_event *event; list_for_each_entry(event, &ctx->pinned_groups, group_entry) { if (event->state <= PERF_EVENT_STATE_OFF) continue; if (!event_filter_match(event)) continue; /* may need to reset tstamp_enabled */ if (is_cgroup_event(event)) perf_cgroup_mark_enabled(event, ctx); if (group_can_go_on(event, cpuctx, 1)) group_sched_in(event, cpuctx, ctx); /* * If this pinned group hasn't been scheduled, * put it in error state. */ if (event->state == PERF_EVENT_STATE_INACTIVE) { update_group_times(event); event->state = PERF_EVENT_STATE_ERROR; } } } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <a.p.zijlstra@chello.nl> Cc: Michael Cree <mcree@orcon.net.nz> Cc: Will Deacon <will.deacon@arm.com> Cc: Deng-Cheng Zhu <dengcheng.zhu@gmail.com> Cc: Anton Blanchard <anton@samba.org> Cc: Eric B Munson <emunson@mgebm.net> Cc: Heiko Carstens <heiko.carstens@de.ibm.com> Cc: Paul Mundt <lethal@linux-sh.org> Cc: David S. Miller <davem@davemloft.net> Cc: Frederic Weisbecker <fweisbec@gmail.com> Cc: Jason Wessel <jason.wessel@windriver.com> Cc: Don Zickus <dzickus@redhat.com> Link: http://lkml.kernel.org/n/tip-agjev8eu666tvknpb3iaj0fg@git.kernel.org Signed-off-by: Ingo Molnar <mingo@elte.hu> CWE ID: CWE-399
0
25,991
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 StartServerOnHandlerThread( base::WeakPtr<DevToolsHttpHandler> handler, std::unique_ptr<base::Thread> thread, std::unique_ptr<DevToolsSocketFactory> socket_factory, const base::FilePath& output_directory, const base::FilePath& debug_frontend_dir, const std::string& browser_guid, bool bundles_resources) { DCHECK(thread->task_runner()->BelongsToCurrentThread()); std::unique_ptr<ServerWrapper> server_wrapper; std::unique_ptr<net::ServerSocket> server_socket = socket_factory->CreateForHttpServer(); std::unique_ptr<net::IPEndPoint> ip_address(new net::IPEndPoint); if (server_socket) { server_wrapper.reset(new ServerWrapper(handler, std::move(server_socket), debug_frontend_dir, bundles_resources)); if (server_wrapper->GetLocalAddress(ip_address.get()) != net::OK) ip_address.reset(); } else { ip_address.reset(); } if (ip_address) { std::string message = base::StringPrintf( "\nDevTools listening on ws://%s%s\n", ip_address->ToString().c_str(), browser_guid.c_str()); fprintf(stderr, "%s", message.c_str()); fflush(stderr); if (!output_directory.empty()) { base::FilePath path = output_directory.Append(kDevToolsActivePortFileName); std::string port_target_string = base::StringPrintf( "%d\n%s", ip_address->port(), browser_guid.c_str()); if (base::WriteFile(path, port_target_string.c_str(), static_cast<int>(port_target_string.length())) < 0) { LOG(ERROR) << "Error writing DevTools active port to file"; } } } else { LOG(ERROR) << "Cannot start http server for devtools. Stop devtools."; } BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::BindOnce(&ServerStartedOnUI, std::move(handler), thread.release(), server_wrapper.release(), socket_factory.release(), std::move(ip_address))); } Commit Message: DevTools: check Host header for being IP or localhost when connecting over RDP. Bug: 813540 Change-Id: I9338aa2475c15090b8a60729be25502eb866efb7 Reviewed-on: https://chromium-review.googlesource.com/952522 Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Commit-Queue: Pavel Feldman <pfeldman@chromium.org> Cr-Commit-Position: refs/heads/master@{#541547} CWE ID: CWE-20
0
148,278
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: WebKit::WebNotificationPresenter* RenderView::notificationPresenter() { return notification_provider_; } Commit Message: DevTools: move DevToolsAgent/Client into content. BUG=84078 TEST= Review URL: http://codereview.chromium.org/7461019 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
0
99,033
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void DataReductionProxyConfigServiceClient::RetrieveRemoteConfig() { DCHECK(thread_checker_.CalledOnValidThread()); CreateClientConfigRequest request; std::string serialized_request; #if defined(OS_ANDROID) request.set_telephony_network_operator( net::android::GetTelephonyNetworkOperator()); #endif data_reduction_proxy::ConfigDeviceInfo* device_info = request.mutable_device_info(); device_info->set_total_device_memory_kb( base::SysInfo::AmountOfPhysicalMemory() / 1024); const std::string& session_key = request_options_->GetSecureSession(); if (!session_key.empty()) request.set_session_key(request_options_->GetSecureSession()); request.set_dogfood_group( base::FeatureList::IsEnabled(features::kDogfood) ? CreateClientConfigRequest_DogfoodGroup_DOGFOOD : CreateClientConfigRequest_DogfoodGroup_NONDOGFOOD); data_reduction_proxy::VersionInfo* version_info = request.mutable_version_info(); uint32_t build; uint32_t patch; util::GetChromiumBuildAndPatchAsInts(util::ChromiumVersion(), &build, &patch); version_info->set_client(util::GetStringForClient(io_data_->client())); version_info->set_build(build); version_info->set_patch(patch); version_info->set_channel(io_data_->channel()); request.SerializeToString(&serialized_request); net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("data_reduction_proxy_config", R"( semantics { sender: "Data Reduction Proxy" description: "Requests a configuration that specifies how to connect to the " "data reduction proxy." trigger: "Requested when Data Saver is enabled and the browser does not " "have a configuration that is not older than a threshold set by " "the server." data: "None." destination: GOOGLE_OWNED_SERVICE } policy { cookies_allowed: NO setting: "Users can control Data Saver on Android via 'Data Saver' setting. " "Data Saver is not available on iOS, and on desktop it is enabled " "by insalling the Data Saver extension." policy_exception_justification: "Not implemented." })"); fetch_in_progress_ = true; auto resource_request = std::make_unique<network::ResourceRequest>(); resource_request->url = config_service_url_; resource_request->method = "POST"; resource_request->load_flags = net::LOAD_BYPASS_PROXY; resource_request->allow_credentials = false; url_loader_ = variations::CreateSimpleURLLoaderWithVariationsHeader( std::move(resource_request), variations::InIncognito::kNo, variations::SignedIn::kNo, traffic_annotation); url_loader_->AttachStringForUpload(serialized_request, "application/x-protobuf"); static const int kMaxRetries = 5; url_loader_->SetRetryOptions( kMaxRetries, network::SimpleURLLoader::RETRY_ON_NETWORK_CHANGE); url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie( url_loader_factory_.get(), base::BindOnce(&DataReductionProxyConfigServiceClient::OnURLLoadComplete, base::Unretained(this))); } Commit Message: Disable all DRP URL fetches when holdback is enabled Disable secure proxy checker, warmup url fetcher and client config fetch when the client is in DRP (Data Reduction Proxy) holdback. This CL does not disable pingbacks when client is in the holdback, but the pingback code is going away soon. Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51 Bug: 984964 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965 Commit-Queue: Tarun Bansal <tbansal@chromium.org> Reviewed-by: Robert Ogden <robertogden@chromium.org> Cr-Commit-Position: refs/heads/master@{#679649} CWE ID: CWE-416
1
172,420
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: xdr_cpol_arg(XDR *xdrs, cpol_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!_xdr_kadm5_policy_ent_rec(xdrs, &objp->rec, objp->api_version)) { return (FALSE); } if (!xdr_long(xdrs, &objp->mask)) { return (FALSE); } return (TRUE); } Commit Message: Fix kadm5/gssrpc XDR double free [CVE-2014-9421] [MITKRB5-SA-2015-001] In auth_gssapi_unwrap_data(), do not free partial deserialization results upon failure to deserialize. This responsibility belongs to the callers, svctcp_getargs() and svcudp_getargs(); doing it in the unwrap function results in freeing the results twice. In xdr_krb5_tl_data() and xdr_krb5_principal(), null out the pointers we are freeing, as other XDR functions such as xdr_bytes() and xdr_string(). ticket: 8056 (new) target_version: 1.13.1 tags: pullup CWE ID:
0
46,046