instruction
stringclasses
1 value
input
stringlengths
64
129k
output
int64
0
1
__index_level_0__
int64
0
30k
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static struct nls_table *find_nls(char *charset) { struct nls_table *nls; spin_lock(&nls_lock); for (nls = tables; nls; nls = nls->next) { if (!strcmp(nls->charset, charset)) break; if (nls->alias && !strcmp(nls->alias, charset)) break; } if (nls && !try_module_get(nls->owner)) nls = NULL; spin_unlock(&nls_lock); return nls; } Commit Message: NLS: improve UTF8 -> UTF16 string conversion routine The utf8s_to_utf16s conversion routine needs to be improved. Unlike its utf16s_to_utf8s sibling, it doesn't accept arguments specifying the maximum length of the output buffer or the endianness of its 16-bit output. This patch (as1501) adds the two missing arguments, and adjusts the only two places in the kernel where the function is called. A follow-on patch will add a third caller that does utilize the new capabilities. The two conversion routines are still annoyingly inconsistent in the way they handle invalid byte combinations. But that's a subject for a different patch. Signed-off-by: Alan Stern <stern@rowland.harvard.edu> CC: Clemens Ladisch <clemens@ladisch.de> Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de> CWE ID: CWE-119
0
20,373
Analyze the following 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 multi_shutdown(struct sb_uart_port *port) { struct mp_port *mtpt = (struct mp_port *)port; unsigned long flags; mtpt->ier = 0; serial_outp(mtpt, UART_IER, 0); spin_lock_irqsave(&mtpt->port.lock, flags); mtpt->port.mctrl &= ~TIOCM_OUT2; multi_set_mctrl(&mtpt->port, mtpt->port.mctrl); spin_unlock_irqrestore(&mtpt->port.lock, flags); serial_out(mtpt, UART_LCR, serial_inp(mtpt, UART_LCR) & ~UART_LCR_SBC); serial_outp(mtpt, UART_FCR, UART_FCR_ENABLE_FIFO | UART_FCR_CLEAR_RCVR | UART_FCR_CLEAR_XMIT); serial_outp(mtpt, UART_FCR, 0); (void) serial_in(mtpt, UART_RX); if ((!is_real_interrupt(mtpt->port.irq))||(mtpt->poll_type==TYPE_POLL)) { del_timer_sync(&mtpt->timer); } else { serial_unlink_irq_chain(mtpt); } } Commit Message: Staging: sb105x: info leak in mp_get_count() The icount.reserved[] array isn't initialized so it leaks stack information to userspace. Reported-by: Nico Golde <nico@ngolde.de> Reported-by: Fabian Yamaguchi <fabs@goesec.de> Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Cc: stable@kernel.org Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-200
0
25,283
Analyze the following 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 Document::DispatchBeforeUnloadEvent(ChromeClient& chrome_client, bool is_reload, bool& did_allow_navigation) { if (!dom_window_) return true; if (!body()) return true; if (ProcessingBeforeUnload()) return false; BeforeUnloadEvent* before_unload_event = BeforeUnloadEvent::Create(); before_unload_event->initEvent(EventTypeNames::beforeunload, false, true); load_event_progress_ = kBeforeUnloadEventInProgress; const TimeTicks beforeunload_event_start = CurrentTimeTicks(); dom_window_->DispatchEvent(before_unload_event, this); const TimeTicks beforeunload_event_end = CurrentTimeTicks(); load_event_progress_ = kBeforeUnloadEventCompleted; DEFINE_STATIC_LOCAL( CustomCountHistogram, beforeunload_histogram, ("DocumentEventTiming.BeforeUnloadDuration", 0, 10000000, 50)); beforeunload_histogram.Count( (beforeunload_event_end - beforeunload_event_start).InMicroseconds()); if (!before_unload_event->defaultPrevented()) DefaultEventHandler(before_unload_event); enum BeforeUnloadDialogHistogramEnum { kNoDialogNoText, kNoDialogNoUserGesture, kNoDialogMultipleConfirmationForNavigation, kShowDialog, kDialogEnumMax }; DEFINE_STATIC_LOCAL(EnumerationHistogram, beforeunload_dialog_histogram, ("Document.BeforeUnloadDialog", kDialogEnumMax)); if (before_unload_event->returnValue().IsNull()) { beforeunload_dialog_histogram.Count(kNoDialogNoText); } if (!GetFrame() || before_unload_event->returnValue().IsNull()) return true; if (!GetFrame()->HasBeenActivated()) { beforeunload_dialog_histogram.Count(kNoDialogNoUserGesture); AddConsoleMessage(ConsoleMessage::Create( kInterventionMessageSource, kErrorMessageLevel, "Blocked attempt to show a 'beforeunload' confirmation panel for a " "frame that never had a user gesture since its load. " "https://www.chromestatus.com/feature/5082396709879808")); return true; } if (did_allow_navigation) { beforeunload_dialog_histogram.Count( kNoDialogMultipleConfirmationForNavigation); AddConsoleMessage(ConsoleMessage::Create( kInterventionMessageSource, kErrorMessageLevel, "Blocked attempt to show multiple 'beforeunload' confirmation panels " "for a single navigation.")); return true; } String text = before_unload_event->returnValue(); beforeunload_dialog_histogram.Count( BeforeUnloadDialogHistogramEnum::kShowDialog); if (chrome_client.OpenBeforeUnloadConfirmPanel(text, frame_, is_reload)) { did_allow_navigation = true; return true; } return false; } Commit Message: Prevent sandboxed documents from reusing the default window Bug: 377995 Change-Id: Iff66c6d214dfd0cb7ea9c80f83afeedfff703541 Reviewed-on: https://chromium-review.googlesource.com/983558 Commit-Queue: Andy Paicu <andypaicu@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Cr-Commit-Position: refs/heads/master@{#567663} CWE ID: CWE-285
0
7,842
Analyze the following 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 is_dx_internal_node(struct inode *dir, ext4_lblk_t block, struct ext4_dir_entry *de) { struct super_block *sb = dir->i_sb; if (!is_dx(dir)) return 0; if (block == 0) return 1; if (de->inode == 0 && ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize) == sb->s_blocksize) return 1; return 0; } Commit Message: ext4: avoid hang when mounting non-journal filesystems with orphan list When trying to mount a file system which does not contain a journal, but which does have a orphan list containing an inode which needs to be truncated, the mount call with hang forever in ext4_orphan_cleanup() because ext4_orphan_del() will return immediately without removing the inode from the orphan list, leading to an uninterruptible loop in kernel code which will busy out one of the CPU's on the system. This can be trivially reproduced by trying to mount the file system found in tests/f_orphan_extents_inode/image.gz from the e2fsprogs source tree. If a malicious user were to put this on a USB stick, and mount it on a Linux desktop which has automatic mounts enabled, this could be considered a potential denial of service attack. (Not a big deal in practice, but professional paranoids worry about such things, and have even been known to allocate CVE numbers for such problems.) Signed-off-by: "Theodore Ts'o" <tytso@mit.edu> Reviewed-by: Zheng Liu <wenqing.lz@taobao.com> Cc: stable@vger.kernel.org CWE ID: CWE-399
0
19,596
Analyze the following 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 online_fair_sched_group(struct task_group *tg) { } 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
6,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: bool LayerTreeHost::SendMessageToMicroBenchmark( int id, std::unique_ptr<base::Value> value) { return micro_benchmark_controller_.SendMessage(id, std::move(value)); } Commit Message: (Reland) Discard compositor frames from unloaded web content This is a reland of https://codereview.chromium.org/2707243005/ with a small change to fix an uninitialized memory error that fails on MSAN bots. BUG=672847 TBR=danakj@chromium.org, creis@chromium.org CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2731283003 Cr-Commit-Position: refs/heads/master@{#454954} CWE ID: CWE-362
0
25,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 __net_exit packet_net_exit(struct net *net) { remove_proc_entry("packet", net->proc_net); } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <davem@davemloft.net> Suggested-by: Eric Dumazet <eric.dumazet@gmail.com> Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-20
0
14,327
Analyze the following 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 __init floppy_module_init(void) { if (floppy) parse_floppy_cfg_string(floppy); return floppy_init(); } Commit Message: floppy: don't write kernel-only members to FDRAWCMD ioctl output Do not leak kernel-only floppy_raw_cmd structure members to userspace. This includes the linked-list pointer and the pointer to the allocated DMA space. Signed-off-by: Matthew Daley <mattd@bugfuzz.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-264
0
23,448
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op, ExceptionInfo *exception) { #define ComplexImageTag "Complex/Image" CacheView *Ai_view, *Ar_view, *Bi_view, *Br_view, *Ci_view, *Cr_view; const char *artifact; const Image *Ai_image, *Ar_image, *Bi_image, *Br_image; double snr; Image *Ci_image, *complex_images, *Cr_image, *image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (images->next == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",images->filename); return((Image *) NULL); } image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImageList(image); return(image); } image->depth=32UL; complex_images=NewImageList(); AppendImageToList(&complex_images,image); image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) { complex_images=DestroyImageList(complex_images); return(complex_images); } AppendImageToList(&complex_images,image); /* Apply complex mathematics to image pixels. */ artifact=GetImageArtifact(image,"complex:snr"); snr=0.0; if (artifact != (const char *) NULL) snr=StringToDouble(artifact,(char **) NULL); Ar_image=images; Ai_image=images->next; Br_image=images; Bi_image=images->next; if ((images->next->next != (Image *) NULL) && (images->next->next->next != (Image *) NULL)) { Br_image=images->next->next; Bi_image=images->next->next->next; } Cr_image=complex_images; Ci_image=complex_images->next; Ar_view=AcquireVirtualCacheView(Ar_image,exception); Ai_view=AcquireVirtualCacheView(Ai_image,exception); Br_view=AcquireVirtualCacheView(Br_image,exception); Bi_view=AcquireVirtualCacheView(Bi_image,exception); Cr_view=AcquireAuthenticCacheView(Cr_image,exception); Ci_view=AcquireAuthenticCacheView(Ci_image,exception); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(images,complex_images,images->rows,1L) #endif for (y=0; y < (ssize_t) images->rows; y++) { register const Quantum *magick_restrict Ai, *magick_restrict Ar, *magick_restrict Bi, *magick_restrict Br; register Quantum *magick_restrict Ci, *magick_restrict Cr; register ssize_t x; if (status == MagickFalse) continue; Ar=GetCacheViewVirtualPixels(Ar_view,0,y, MagickMax(Ar_image->columns,Cr_image->columns),1,exception); Ai=GetCacheViewVirtualPixels(Ai_view,0,y, MagickMax(Ai_image->columns,Ci_image->columns),1,exception); Br=GetCacheViewVirtualPixels(Br_view,0,y, MagickMax(Br_image->columns,Cr_image->columns),1,exception); Bi=GetCacheViewVirtualPixels(Bi_view,0,y, MagickMax(Bi_image->columns,Ci_image->columns),1,exception); Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception); Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception); if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) || (Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) || (Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) images->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(images); i++) { switch (op) { case AddComplexOperator: { Cr[i]=Ar[i]+Br[i]; Ci[i]=Ai[i]+Bi[i]; break; } case ConjugateComplexOperator: default: { Cr[i]=Ar[i]; Ci[i]=(-Bi[i]); break; } case DivideComplexOperator: { double gamma; gamma=PerceptibleReciprocal(Br[i]*Br[i]+Bi[i]*Bi[i]+snr); Cr[i]=gamma*(Ar[i]*Br[i]+Ai[i]*Bi[i]); Ci[i]=gamma*(Ai[i]*Br[i]-Ar[i]*Bi[i]); break; } case MagnitudePhaseComplexOperator: { Cr[i]=sqrt(Ar[i]*Ar[i]+Ai[i]*Ai[i]); Ci[i]=atan2(Ai[i],Ar[i])/(2.0*MagickPI)+0.5; break; } case MultiplyComplexOperator: { Cr[i]=QuantumScale*(Ar[i]*Br[i]-Ai[i]*Bi[i]); Ci[i]=QuantumScale*(Ai[i]*Br[i]+Ar[i]*Bi[i]); break; } case RealImaginaryComplexOperator: { Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5)); Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5)); break; } case SubtractComplexOperator: { Cr[i]=Ar[i]-Br[i]; Ci[i]=Ai[i]-Bi[i]; break; } } } Ar+=GetPixelChannels(Ar_image); Ai+=GetPixelChannels(Ai_image); Br+=GetPixelChannels(Br_image); Bi+=GetPixelChannels(Bi_image); Cr+=GetPixelChannels(Cr_image); Ci+=GetPixelChannels(Ci_image); } if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse) status=MagickFalse; if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows); if (proceed == MagickFalse) status=MagickFalse; } } Cr_view=DestroyCacheView(Cr_view); Ci_view=DestroyCacheView(Ci_view); Br_view=DestroyCacheView(Br_view); Bi_view=DestroyCacheView(Bi_view); Ar_view=DestroyCacheView(Ar_view); Ai_view=DestroyCacheView(Ai_view); if (status == MagickFalse) complex_images=DestroyImageList(complex_images); return(complex_images); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1595 CWE ID: CWE-119
1
4,275
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static bool ValidMpegAudioFrameHeader(const uint8_t* header, int header_size, int* framesize) { DCHECK_GE(header_size, 4); *framesize = 0; BitReader reader(header, 4); // Header can only be 4 bytes long. RCHECK(ReadBits(&reader, 11) == 0x7ff); int version = ReadBits(&reader, 2); RCHECK(version != 1); // Reserved. int layer = ReadBits(&reader, 2); RCHECK(layer != 0); reader.SkipBits(1); int bitrate_index = ReadBits(&reader, 4); RCHECK(bitrate_index != 0xf); int sampling_index = ReadBits(&reader, 2); RCHECK(sampling_index != 3); int padding = ReadBits(&reader, 1); int sampling_rate = kSampleRateTable[version][sampling_index]; int bitrate; if (version == VERSION_1) { if (layer == LAYER_1) bitrate = kBitRateTableV1L1[bitrate_index]; else if (layer == LAYER_2) bitrate = kBitRateTableV1L2[bitrate_index]; else bitrate = kBitRateTableV1L3[bitrate_index]; } else { if (layer == LAYER_1) bitrate = kBitRateTableV2L1[bitrate_index]; else bitrate = kBitRateTableV2L23[bitrate_index]; } if (layer == LAYER_1) *framesize = ((12000 * bitrate) / sampling_rate + padding) * 4; else *framesize = (144000 * bitrate) / sampling_rate + padding; return (bitrate > 0 && sampling_rate > 0); } Commit Message: Cleanup media BitReader ReadBits() calls Initialize temporary values, check return values. Small tweaks to solution proposed by adtolbar@microsoft.com. Bug: 929962 Change-Id: Iaa7da7534174882d040ec7e4c353ba5cd0da5735 Reviewed-on: https://chromium-review.googlesource.com/c/1481085 Commit-Queue: Chrome Cunningham <chcunningham@chromium.org> Reviewed-by: Dan Sanders <sandersd@chromium.org> Cr-Commit-Position: refs/heads/master@{#634889} CWE ID: CWE-200
0
13,319
Analyze the following 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 TriState StateJustifyRight(LocalFrame& frame, Event*) { return StateStyle(frame, CSSPropertyTextAlign, "right"); } Commit Message: Move Editor::Transpose() out of Editor class This patch moves |Editor::Transpose()| out of |Editor| class as preparation of expanding it into |ExecutTranspose()| in "EditorCommand.cpp" to make |Editor| class simpler for improving code health. Following patch will expand |Transpose()| into |ExecutTranspose()|. Bug: 672405 Change-Id: Icde253623f31813d2b4517c4da7d4798bd5fadf6 Reviewed-on: https://chromium-review.googlesource.com/583880 Reviewed-by: Xiaocheng Hu <xiaochengh@chromium.org> Commit-Queue: Yoshifumi Inoue <yosin@chromium.org> Cr-Commit-Position: refs/heads/master@{#489518} CWE ID:
0
5,195
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void WebContentsImpl::RemoveBrowserPluginEmbedder() { if (browser_plugin_embedder_) browser_plugin_embedder_.reset(); } Commit Message: Cancel JavaScript dialogs when an interstitial appears. BUG=295695 TEST=See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/24360011 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@225026 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
0
12,414
Analyze the following 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 unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp) { struct files_struct *fd = current->files; int error = 0; if ((unshare_flags & CLONE_FILES) && (fd && atomic_read(&fd->count) > 1)) { *new_fdp = dup_fd(fd, &error); if (!*new_fdp) return error; } return 0; } Commit Message: Move "exit_robust_list" into mm_release() We don't want to get rid of the futexes just at exit() time, we want to drop them when doing an execve() too, since that gets rid of the previous VM image too. Doing it at mm_release() time means that we automatically always do it when we disassociate a VM map from the task. Reported-by: pageexec@freemail.hu Cc: Andrew Morton <akpm@linux-foundation.org> Cc: Nick Piggin <npiggin@suse.de> Cc: Hugh Dickins <hugh@veritas.com> Cc: Ingo Molnar <mingo@elte.hu> Cc: Thomas Gleixner <tglx@linutronix.de> Cc: Brad Spengler <spender@grsecurity.net> Cc: Alex Efros <powerman@powerman.name> Cc: Peter Zijlstra <a.p.zijlstra@chello.nl> Cc: Oleg Nesterov <oleg@redhat.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-264
0
11,324
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: nfsd(void *vrqstp) { struct svc_rqst *rqstp = (struct svc_rqst *) vrqstp; struct svc_xprt *perm_sock = list_entry(rqstp->rq_server->sv_permsocks.next, typeof(struct svc_xprt), xpt_list); struct net *net = perm_sock->xpt_net; struct nfsd_net *nn = net_generic(net, nfsd_net_id); int err; /* Lock module and set up kernel thread */ mutex_lock(&nfsd_mutex); /* At this point, the thread shares current->fs * with the init process. We need to create files with the * umask as defined by the client instead of init's umask. */ if (unshare_fs_struct() < 0) { printk("Unable to start nfsd thread: out of memory\n"); goto out; } current->fs->umask = 0; /* * thread is spawned with all signals set to SIG_IGN, re-enable * the ones that will bring down the thread */ allow_signal(SIGKILL); allow_signal(SIGHUP); allow_signal(SIGINT); allow_signal(SIGQUIT); nfsdstats.th_cnt++; mutex_unlock(&nfsd_mutex); set_freezable(); /* * The main request loop */ for (;;) { /* Update sv_maxconn if it has changed */ rqstp->rq_server->sv_maxconn = nn->max_connections; /* * Find a socket with data available and call its * recvfrom routine. */ while ((err = svc_recv(rqstp, 60*60*HZ)) == -EAGAIN) ; if (err == -EINTR) break; validate_process_creds(); svc_process(rqstp); validate_process_creds(); } /* Clear signals before calling svc_exit_thread() */ flush_signals(current); mutex_lock(&nfsd_mutex); nfsdstats.th_cnt --; out: rqstp->rq_server = NULL; /* Release the thread */ svc_exit_thread(rqstp); nfsd_destroy(net); /* Release module */ mutex_unlock(&nfsd_mutex); module_put_and_exit(0); return 0; } Commit Message: nfsd: check for oversized NFSv2/v3 arguments A client can append random data to the end of an NFSv2 or NFSv3 RPC call without our complaining; we'll just stop parsing at the end of the expected data and ignore the rest. Encoded arguments and replies are stored together in an array of pages, and if a call is too large it could leave inadequate space for the reply. This is normally OK because NFS RPC's typically have either short arguments and long replies (like READ) or long arguments and short replies (like WRITE). But a client that sends an incorrectly long reply can violate those assumptions. This was observed to cause crashes. Also, several operations increment rq_next_page in the decode routine before checking the argument size, which can leave rq_next_page pointing well past the end of the page array, causing trouble later in svc_free_pages. So, following a suggestion from Neil Brown, add a central check to enforce our expectation that no NFSv2/v3 call has both a large call and a large reply. As followup we may also want to rewrite the encoding routines to check more carefully that they aren't running off the end of the page array. We may also consider rejecting calls that have any extra garbage appended. That would be safer, and within our rights by spec, but given the age of our server and the NFS protocol, and the fact that we've never enforced this before, we may need to balance that against the possibility of breaking some oddball client. Reported-by: Tuomas Haanpää <thaan@synopsys.com> Reported-by: Ari Kauppi <ari@synopsys.com> Cc: stable@vger.kernel.org Reviewed-by: NeilBrown <neilb@suse.com> Signed-off-by: J. Bruce Fields <bfields@redhat.com> CWE ID: CWE-20
0
25,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: bool ndp_msg_opt_prefix_flag_auto_addr_conf(struct ndp_msg *msg, int offset) { struct nd_opt_prefix_info *pi = ndp_msg_payload_opts_offset(msg, offset); return pi->nd_opt_pi_flags_reserved & ND_OPT_PI_FLAG_AUTO; } Commit Message: libndp: validate the IPv6 hop limit None of the NDP messages should ever come from a non-local network; as stated in RFC4861's 6.1.1 (RS), 6.1.2 (RA), 7.1.1 (NS), 7.1.2 (NA), and 8.1. (redirect): - The IP Hop Limit field has a value of 255, i.e., the packet could not possibly have been forwarded by a router. This fixes CVE-2016-3698. Reported by: Julien BERNARD <julien.bernard@viagenie.ca> Signed-off-by: Lubomir Rintel <lkundrak@v3.sk> Signed-off-by: Jiri Pirko <jiri@mellanox.com> CWE ID: CWE-284
0
24,922
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: update_info_drive_adapter (Device *device) { Adapter *adapter; const gchar *adapter_object_path; adapter_object_path = NULL; adapter = daemon_local_find_enclosing_adapter (device->priv->daemon, device->priv->native_path); if (adapter != NULL) { adapter_object_path = adapter_local_get_object_path (adapter); } device_set_drive_adapter (device, adapter_object_path); return TRUE; } Commit Message: CWE ID: CWE-200
0
28,085
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: check_compat_entry_size_and_hooks(struct compat_ipt_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ipt_entry) >= limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_ipt_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct ipt_entry *)e); if (ret) return ret; off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, name, &e->ip, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ipt_get_target(e); target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET, entry_offset, off); if (ret) goto out; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; } Commit Message: netfilter: x_tables: make sure e->next_offset covers remaining blob size Otherwise this function may read data beyond the ruleset blob. Signed-off-by: Florian Westphal <fw@strlen.de> Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org> CWE ID: CWE-119
1
26,828
Analyze the following 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 tcp_v4_parse_md5_keys(struct sock *sk, char __user *optval, int optlen) { struct tcp_md5sig cmd; struct sockaddr_in *sin = (struct sockaddr_in *)&cmd.tcpm_addr; if (optlen < sizeof(cmd)) return -EINVAL; if (copy_from_user(&cmd, optval, sizeof(cmd))) return -EFAULT; if (sin->sin_family != AF_INET) return -EINVAL; if (!cmd.tcpm_keylen) return tcp_md5_do_del(sk, (union tcp_md5_addr *)&sin->sin_addr.s_addr, AF_INET); if (cmd.tcpm_keylen > TCP_MD5SIG_MAXKEYLEN) return -EINVAL; return tcp_md5_do_add(sk, (union tcp_md5_addr *)&sin->sin_addr.s_addr, AF_INET, cmd.tcpm_key, cmd.tcpm_keylen, GFP_KERNEL); } Commit Message: tcp: take care of truncations done by sk_filter() With syzkaller help, Marco Grassi found a bug in TCP stack, crashing in tcp_collapse() Root cause is that sk_filter() can truncate the incoming skb, but TCP stack was not really expecting this to happen. It probably was expecting a simple DROP or ACCEPT behavior. We first need to make sure no part of TCP header could be removed. Then we need to adjust TCP_SKB_CB(skb)->end_seq Many thanks to syzkaller team and Marco for giving us a reproducer. Signed-off-by: Eric Dumazet <edumazet@google.com> Reported-by: Marco Grassi <marco.gra@gmail.com> Reported-by: Vladis Dronov <vdronov@redhat.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-284
0
8,931
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: long SSL_SESSION_set_timeout(SSL_SESSION *s, long t) { if (s == NULL) return (0); s->timeout = t; return (1); } Commit Message: CWE ID: CWE-190
0
24,320
Analyze the following 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 QQuickWebView::mouseReleaseEvent(QMouseEvent* event) { Q_D(QQuickWebView); d->handleMouseEvent(event); } Commit Message: [Qt][WK2] There's no way to test the gesture tap on WTR https://bugs.webkit.org/show_bug.cgi?id=92895 Reviewed by Kenneth Rohde Christiansen. Source/WebKit2: Add an instance of QtViewportHandler to QQuickWebViewPrivate, so it's now available on mobile and desktop modes, as a side effect gesture tap events can now be created and sent to WebCore. This is needed to test tap gestures and to get tap gestures working when you have a WebView (in desktop mode) on notebooks equipped with touch screens. * UIProcess/API/qt/qquickwebview.cpp: (QQuickWebViewPrivate::onComponentComplete): (QQuickWebViewFlickablePrivate::onComponentComplete): Implementation moved to QQuickWebViewPrivate::onComponentComplete. * UIProcess/API/qt/qquickwebview_p_p.h: (QQuickWebViewPrivate): (QQuickWebViewFlickablePrivate): Tools: WTR doesn't create the QQuickItem from C++, not from QML, so a call to componentComplete() was added to mimic the QML behaviour. * WebKitTestRunner/qt/PlatformWebViewQt.cpp: (WTR::PlatformWebView::PlatformWebView): git-svn-id: svn://svn.chromium.org/blink/trunk@124625 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
0
6,465
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: MockProcessLauncherDelegate() {} Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
0
19,417
Analyze the following 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 RenderProcessHostImpl::FilterURL(bool empty_allowed, GURL* url) { FilterURL(this, empty_allowed, url); } Commit Message: Switching AudioOutputAuthorizationHandler from using AudioManager interface to AudioSystem one. BUG=672468 CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Review-Url: https://codereview.chromium.org/2692203003 Cr-Commit-Position: refs/heads/master@{#450939} CWE ID:
0
10,126
Analyze the following 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* MapFont(struct _FPDF_SYSFONTINFO*, int weight, int italic, int charset, int pitch_family, const char* face, int* exact) { if (!pp::Module::Get()) return nullptr; pp::BrowserFontDescription description; if (strcmp(face, "Symbol") == 0) return nullptr; if (pitch_family & FXFONT_FF_FIXEDPITCH) { description.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_MONOSPACE); } else if (pitch_family & FXFONT_FF_ROMAN) { description.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_SERIF); } static const struct { const char* pdf_name; const char* face; bool bold; bool italic; } kPdfFontSubstitutions[] = { {"Courier", "Courier New", false, false}, {"Courier-Bold", "Courier New", true, false}, {"Courier-BoldOblique", "Courier New", true, true}, {"Courier-Oblique", "Courier New", false, true}, {"Helvetica", "Arial", false, false}, {"Helvetica-Bold", "Arial", true, false}, {"Helvetica-BoldOblique", "Arial", true, true}, {"Helvetica-Oblique", "Arial", false, true}, {"Times-Roman", "Times New Roman", false, false}, {"Times-Bold", "Times New Roman", true, false}, {"Times-BoldItalic", "Times New Roman", true, true}, {"Times-Italic", "Times New Roman", false, true}, {"MS-PGothic", "MS PGothic", false, false}, {"MS-Gothic", "MS Gothic", false, false}, {"MS-PMincho", "MS PMincho", false, false}, {"MS-Mincho", "MS Mincho", false, false}, {"\x82\x6C\x82\x72\x82\x6F\x83\x53\x83\x56\x83\x62\x83\x4E", "MS PGothic", false, false}, {"\x82\x6C\x82\x72\x83\x53\x83\x56\x83\x62\x83\x4E", "MS Gothic", false, false}, {"\x82\x6C\x82\x72\x82\x6F\x96\xBE\x92\xA9", "MS PMincho", false, false}, {"\x82\x6C\x82\x72\x96\xBE\x92\xA9", "MS Mincho", false, false}, }; if (charset == FXFONT_ANSI_CHARSET && (pitch_family & FXFONT_FF_FIXEDPITCH)) face = "Courier New"; size_t i; for (i = 0; i < arraysize(kPdfFontSubstitutions); ++i) { if (strcmp(face, kPdfFontSubstitutions[i].pdf_name) == 0) { description.set_face(kPdfFontSubstitutions[i].face); if (kPdfFontSubstitutions[i].bold) description.set_weight(PP_BROWSERFONT_TRUSTED_WEIGHT_BOLD); if (kPdfFontSubstitutions[i].italic) description.set_italic(true); break; } } if (i == arraysize(kPdfFontSubstitutions)) { std::string face_utf8; if (base::IsStringUTF8(face)) { face_utf8 = face; } else { std::string encoding; if (base::DetectEncoding(face, &encoding)) { base::ConvertToUtf8AndNormalize(face, encoding, &face_utf8); } } if (face_utf8.empty()) return nullptr; description.set_face(face_utf8); description.set_weight(WeightToBrowserFontTrustedWeight(weight)); description.set_italic(italic > 0); } if (!pp::PDF::IsAvailable()) { NOTREACHED(); return nullptr; } PP_Resource font_resource = pp::PDF::GetFontFileWithFallback( pp::InstanceHandle(g_last_instance_id), &description.pp_font_description(), static_cast<PP_PrivateFontCharset>(charset)); long res_id = font_resource; return reinterpret_cast<void*>(res_id); } Commit Message: [pdf] Defer page unloading in JS callback. One of the callbacks from PDFium JavaScript into the embedder is to get the current page number. In Chromium, this will trigger a call to CalculateMostVisiblePage that method will determine the visible pages and unload any non-visible pages. But, if the originating JS is on a non-visible page we'll delete the page and annotations associated with that page. This will cause issues as we are currently working with those objects when the JavaScript returns. This Cl defers the page unloading triggered by getting the most visible page until the next event is handled by the Chromium embedder. BUG=chromium:653090 Review-Url: https://codereview.chromium.org/2418533002 Cr-Commit-Position: refs/heads/master@{#424781} CWE ID: CWE-416
0
25,431
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void RenderFrameImpl::DidChangeFramePolicy( blink::WebFrame* child_frame, blink::WebSandboxFlags flags, const blink::ParsedFeaturePolicy& container_policy) { Send(new FrameHostMsg_DidChangeFramePolicy( routing_id_, RenderFrame::GetRoutingIdForWebFrame(child_frame), {flags, container_policy})); } Commit Message: If a page calls |window.focus()|, kick it out of fullscreen. BUG=776418, 800056 Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017 Reviewed-on: https://chromium-review.googlesource.com/852378 Reviewed-by: Nasko Oskov <nasko@chromium.org> Reviewed-by: Philip Jägenstedt <foolip@chromium.org> Commit-Queue: Avi Drissman <avi@chromium.org> Cr-Commit-Position: refs/heads/master@{#533790} CWE ID:
0
14,294
Analyze the following 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 mkdir_deep(const char *szDirName, int secattr) { char DirName[260]; DirName[0] = 0; const char* p = szDirName; char* q = DirName; int ret = 0; while(*p) { if (('\\' == *p) || ('/' == *p)) { if (':' != *(p-1)) { ret = createdir(DirName, secattr); } } *q++ = *p++; *q = '\0'; } if (DirName[0]) { ret = createdir(DirName, secattr); } return ret; } Commit Message: Do not allow enters/returns in arguments (thanks to Fabio Carretto) CWE ID: CWE-93
0
29,047
Analyze the following 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 NavigationController::GoForward() { if (!CanGoForward()) { NOTREACHED(); return; } if (tab_contents_->interstitial_page()) { tab_contents_->interstitial_page()->CancelForNavigation(); } bool transient = (transient_entry_index_ != -1); int current_index = GetCurrentEntryIndex(); DiscardNonCommittedEntries(); pending_entry_index_ = current_index; if (!transient) pending_entry_index_++; entries_[pending_entry_index_]->set_transition_type( entries_[pending_entry_index_]->transition_type() | PageTransition::FORWARD_BACK); NavigateToPendingEntry(NO_RELOAD); } Commit Message: Ensure URL is updated after a cross-site navigation is pre-empted by an "ignored" navigation. BUG=77507 TEST=NavigationControllerTest.LoadURL_IgnorePreemptsPending Review URL: http://codereview.chromium.org/6826015 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@81307 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
0
205
Analyze the following 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 jas_icclut8_output(jas_iccattrval_t *attrval, jas_stream_t *out) { jas_icclut8_t *lut8 = &attrval->data.lut8; int i; int j; int n; lut8->clut = 0; lut8->intabs = 0; lut8->intabsbuf = 0; lut8->outtabs = 0; lut8->outtabsbuf = 0; if (jas_stream_putc(out, lut8->numinchans) == EOF || jas_stream_putc(out, lut8->numoutchans) == EOF || jas_stream_putc(out, lut8->clutlen) == EOF || jas_stream_putc(out, 0) == EOF) goto error; for (i = 0; i < 3; ++i) { for (j = 0; j < 3; ++j) { if (jas_iccputsint32(out, lut8->e[i][j])) goto error; } } if (jas_iccputuint16(out, lut8->numintabents) || jas_iccputuint16(out, lut8->numouttabents)) goto error; n = lut8->numinchans * lut8->numintabents; for (i = 0; i < n; ++i) { if (jas_iccputuint8(out, lut8->intabsbuf[i])) goto error; } n = lut8->numoutchans * lut8->numouttabents; for (i = 0; i < n; ++i) { if (jas_iccputuint8(out, lut8->outtabsbuf[i])) goto error; } n = jas_iccpowi(lut8->clutlen, lut8->numinchans) * lut8->numoutchans; for (i = 0; i < n; ++i) { if (jas_iccputuint8(out, lut8->clut[i])) goto error; } return 0; error: return -1; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190
0
7,088
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: iakerb_save_token(iakerb_ctx_id_t ctx, const gss_buffer_t token) { char *p; p = realloc(ctx->conv.data, ctx->conv.length + token->length); if (p == NULL) return ENOMEM; memcpy(p + ctx->conv.length, token->value, token->length); ctx->conv.data = p; ctx->conv.length += token->length; return 0; } Commit Message: Fix IAKERB context export/import [CVE-2015-2698] The patches for CVE-2015-2696 contained a regression in the newly added IAKERB iakerb_gss_export_sec_context() function, which could cause it to corrupt memory. Fix the regression by properly dereferencing the context_handle pointer before casting it. Also, the patches did not implement an IAKERB gss_import_sec_context() function, under the erroneous belief that an exported IAKERB context would be tagged as a krb5 context. Implement it now to allow IAKERB contexts to be successfully exported and imported after establishment. CVE-2015-2698: In any MIT krb5 release with the patches for CVE-2015-2696 applied, an application which calls gss_export_sec_context() may experience memory corruption if the context was established using the IAKERB mechanism. Historically, some vulnerabilities of this nature can be translated into remote code execution, though the necessary exploits must be tailored to the individual application and are usually quite complicated. CVSSv2 Vector: AV:N/AC:H/Au:S/C:C/I:C/A:C/E:POC/RL:OF/RC:C ticket: 8273 (new) target_version: 1.14 tags: pullup CWE ID: CWE-119
0
21,726
Analyze the following 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 MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info, const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception) { char message[MagickPathExtent]; MagickBooleanType status; PSDCompressionType compression; ssize_t j; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " setting up new layer image"); if (psd_info->mode != IndexedMode) (void) SetImageBackgroundColor(layer_info->image,exception); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) layer_info->image->compose=NoCompositeOp; /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name, exception); status=MagickTrue; for (j=0; j < (ssize_t) layer_info->channels; j++) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for channel %.20g",(double) j); compression=(PSDCompressionType) ReadBlobShort(layer_info->image); /* TODO: Remove this when we figure out how to support this */ if ((compression == ZipWithPrediction) && (image->depth == 32)) { (void) ThrowMagickException(exception,GetMagickModule(), TypeError,"CompressionNotSupported","ZipWithPrediction(32 bit)"); return(MagickFalse); } layer_info->image->compression=ConvertPSDCompression(compression); if (layer_info->channel_info[j].type == -1) layer_info->image->alpha_trait=BlendPixelTrait; status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info, (size_t) j,compression,exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity, MagickFalse,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateCMYK(layer_info->image,exception); if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL)) { const char *option; layer_info->mask.image->page.x=layer_info->mask.page.x; layer_info->mask.image->page.y=layer_info->mask.page.y; /* Do not composite the mask when it is disabled */ if ((layer_info->mask.flags & 0x02) == 0x02) layer_info->mask.image->compose=NoCompositeOp; else status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image, layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse, exception); option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if (IsStringTrue(option) != MagickFalse) PreservePSDOpacityMask(image,layer_info,exception); layer_info->mask.image=DestroyImage(layer_info->mask.image); } return(status); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1451 CWE ID: CWE-399
0
29,503
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static size_t out_get_buffer_size(const struct audio_stream *stream) { struct a2dp_stream_out *out = (struct a2dp_stream_out *)stream; DEBUG("buffer_size : %zu", out->common.buffer_sz); return out->common.buffer_sz; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
0
14,245
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: GF_Err tims_Read(GF_Box *s, GF_BitStream *bs) { GF_TSHintEntryBox *ptr = (GF_TSHintEntryBox *)s; ptr->timeScale = gf_bs_read_u32(bs); return GF_OK; } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125
0
15,530
Analyze the following 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 *ReadGROUP4Image(const ImageInfo *image_info, ExceptionInfo *exception) { char filename[MagickPathExtent]; FILE *file; Image *image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; size_t length; ssize_t offset, strip_offset; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Write raw CCITT Group 4 wrapped as a TIFF image file. */ file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile"); length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file); if (length != 10) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file); length=fwrite("\000\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->columns); length=fwrite("\001\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file); length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file); length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file); length=fwrite("\021\001\003\000\001\000\000\000",1,8,file); strip_offset=10+(12*14)+4+8; length=WriteLSBLong(file,(size_t) strip_offset); length=fwrite("\022\001\003\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) image_info->orientation); length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file); length=fwrite("\026\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file); offset=(ssize_t) ftell(file)-4; length=fwrite("\032\001\005\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite("\033\001\005\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file); length=fwrite("\000\000\000\000",1,4,file); length=WriteLSBLong(file,(long) image->resolution.x); length=WriteLSBLong(file,1); status=MagickTrue; for (length=0; (c=ReadBlobByte(image)) != EOF; length++) if (fputc(c,file) != c) status=MagickFalse; offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET); length=WriteLSBLong(file,(unsigned int) length); if (ferror(file) != 0) { (void) fclose(file); ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile"); } (void) fclose(file); (void) CloseBlob(image); image=DestroyImage(image); /* Read TIFF image. */ read_info=CloneImageInfo((ImageInfo *) NULL); (void) FormatLocaleString(read_info->filename,MagickPathExtent,"%s",filename); image=ReadTIFFImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) { (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick,"GROUP4",MagickPathExtent); } (void) RelinquishUniqueFileResource(filename); if (status == MagickFalse) image=DestroyImage(image); return(image); } Commit Message: Fixed possible memory leak reported in #1206 CWE ID: CWE-772
0
2,757
Analyze the following 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 strictTypeCheckingFloatAttributeAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder()); v8SetReturnValue(info, imp->strictTypeCheckingFloatAttribute()); } 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
22,319
Analyze the following 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 sk_chk_filter(struct sock_filter *filter, unsigned int flen) { /* * Valid instructions are initialized to non-0. * Invalid instructions are initialized to 0. */ static const u8 codes[] = { [BPF_ALU|BPF_ADD|BPF_K] = BPF_S_ALU_ADD_K, [BPF_ALU|BPF_ADD|BPF_X] = BPF_S_ALU_ADD_X, [BPF_ALU|BPF_SUB|BPF_K] = BPF_S_ALU_SUB_K, [BPF_ALU|BPF_SUB|BPF_X] = BPF_S_ALU_SUB_X, [BPF_ALU|BPF_MUL|BPF_K] = BPF_S_ALU_MUL_K, [BPF_ALU|BPF_MUL|BPF_X] = BPF_S_ALU_MUL_X, [BPF_ALU|BPF_DIV|BPF_X] = BPF_S_ALU_DIV_X, [BPF_ALU|BPF_MOD|BPF_K] = BPF_S_ALU_MOD_K, [BPF_ALU|BPF_MOD|BPF_X] = BPF_S_ALU_MOD_X, [BPF_ALU|BPF_AND|BPF_K] = BPF_S_ALU_AND_K, [BPF_ALU|BPF_AND|BPF_X] = BPF_S_ALU_AND_X, [BPF_ALU|BPF_OR|BPF_K] = BPF_S_ALU_OR_K, [BPF_ALU|BPF_OR|BPF_X] = BPF_S_ALU_OR_X, [BPF_ALU|BPF_XOR|BPF_K] = BPF_S_ALU_XOR_K, [BPF_ALU|BPF_XOR|BPF_X] = BPF_S_ALU_XOR_X, [BPF_ALU|BPF_LSH|BPF_K] = BPF_S_ALU_LSH_K, [BPF_ALU|BPF_LSH|BPF_X] = BPF_S_ALU_LSH_X, [BPF_ALU|BPF_RSH|BPF_K] = BPF_S_ALU_RSH_K, [BPF_ALU|BPF_RSH|BPF_X] = BPF_S_ALU_RSH_X, [BPF_ALU|BPF_NEG] = BPF_S_ALU_NEG, [BPF_LD|BPF_W|BPF_ABS] = BPF_S_LD_W_ABS, [BPF_LD|BPF_H|BPF_ABS] = BPF_S_LD_H_ABS, [BPF_LD|BPF_B|BPF_ABS] = BPF_S_LD_B_ABS, [BPF_LD|BPF_W|BPF_LEN] = BPF_S_LD_W_LEN, [BPF_LD|BPF_W|BPF_IND] = BPF_S_LD_W_IND, [BPF_LD|BPF_H|BPF_IND] = BPF_S_LD_H_IND, [BPF_LD|BPF_B|BPF_IND] = BPF_S_LD_B_IND, [BPF_LD|BPF_IMM] = BPF_S_LD_IMM, [BPF_LDX|BPF_W|BPF_LEN] = BPF_S_LDX_W_LEN, [BPF_LDX|BPF_B|BPF_MSH] = BPF_S_LDX_B_MSH, [BPF_LDX|BPF_IMM] = BPF_S_LDX_IMM, [BPF_MISC|BPF_TAX] = BPF_S_MISC_TAX, [BPF_MISC|BPF_TXA] = BPF_S_MISC_TXA, [BPF_RET|BPF_K] = BPF_S_RET_K, [BPF_RET|BPF_A] = BPF_S_RET_A, [BPF_ALU|BPF_DIV|BPF_K] = BPF_S_ALU_DIV_K, [BPF_LD|BPF_MEM] = BPF_S_LD_MEM, [BPF_LDX|BPF_MEM] = BPF_S_LDX_MEM, [BPF_ST] = BPF_S_ST, [BPF_STX] = BPF_S_STX, [BPF_JMP|BPF_JA] = BPF_S_JMP_JA, [BPF_JMP|BPF_JEQ|BPF_K] = BPF_S_JMP_JEQ_K, [BPF_JMP|BPF_JEQ|BPF_X] = BPF_S_JMP_JEQ_X, [BPF_JMP|BPF_JGE|BPF_K] = BPF_S_JMP_JGE_K, [BPF_JMP|BPF_JGE|BPF_X] = BPF_S_JMP_JGE_X, [BPF_JMP|BPF_JGT|BPF_K] = BPF_S_JMP_JGT_K, [BPF_JMP|BPF_JGT|BPF_X] = BPF_S_JMP_JGT_X, [BPF_JMP|BPF_JSET|BPF_K] = BPF_S_JMP_JSET_K, [BPF_JMP|BPF_JSET|BPF_X] = BPF_S_JMP_JSET_X, }; int pc; bool anc_found; if (flen == 0 || flen > BPF_MAXINSNS) return -EINVAL; /* check the filter code now */ for (pc = 0; pc < flen; pc++) { struct sock_filter *ftest = &filter[pc]; u16 code = ftest->code; if (code >= ARRAY_SIZE(codes)) return -EINVAL; code = codes[code]; if (!code) return -EINVAL; /* Some instructions need special checks */ switch (code) { case BPF_S_ALU_DIV_K: case BPF_S_ALU_MOD_K: /* check for division by zero */ if (ftest->k == 0) return -EINVAL; break; case BPF_S_LD_MEM: case BPF_S_LDX_MEM: case BPF_S_ST: case BPF_S_STX: /* check for invalid memory addresses */ if (ftest->k >= BPF_MEMWORDS) return -EINVAL; break; case BPF_S_JMP_JA: /* * Note, the large ftest->k might cause loops. * Compare this with conditional jumps below, * where offsets are limited. --ANK (981016) */ if (ftest->k >= (unsigned int)(flen-pc-1)) return -EINVAL; break; case BPF_S_JMP_JEQ_K: case BPF_S_JMP_JEQ_X: case BPF_S_JMP_JGE_K: case BPF_S_JMP_JGE_X: case BPF_S_JMP_JGT_K: case BPF_S_JMP_JGT_X: case BPF_S_JMP_JSET_X: case BPF_S_JMP_JSET_K: /* for conditionals both must be safe */ if (pc + ftest->jt + 1 >= flen || pc + ftest->jf + 1 >= flen) return -EINVAL; break; case BPF_S_LD_W_ABS: case BPF_S_LD_H_ABS: case BPF_S_LD_B_ABS: anc_found = false; #define ANCILLARY(CODE) case SKF_AD_OFF + SKF_AD_##CODE: \ code = BPF_S_ANC_##CODE; \ anc_found = true; \ break switch (ftest->k) { ANCILLARY(PROTOCOL); ANCILLARY(PKTTYPE); ANCILLARY(IFINDEX); ANCILLARY(NLATTR); ANCILLARY(NLATTR_NEST); ANCILLARY(MARK); ANCILLARY(QUEUE); ANCILLARY(HATYPE); ANCILLARY(RXHASH); ANCILLARY(CPU); ANCILLARY(ALU_XOR_X); ANCILLARY(VLAN_TAG); ANCILLARY(VLAN_TAG_PRESENT); ANCILLARY(PAY_OFFSET); } /* ancillary operation unknown or unsupported */ if (anc_found == false && ftest->k >= SKF_AD_OFF) return -EINVAL; } ftest->code = code; } /* last instruction must be a RET code */ switch (filter[flen - 1].code) { case BPF_S_RET_K: case BPF_S_RET_A: return check_load_and_stores(filter, flen); } return -EINVAL; } Commit Message: filter: prevent nla extensions to peek beyond the end of the message The BPF_S_ANC_NLATTR and BPF_S_ANC_NLATTR_NEST extensions fail to check for a minimal message length before testing the supplied offset to be within the bounds of the message. This allows the subtraction of the nla header to underflow and therefore -- as the data type is unsigned -- allowing far to big offset and length values for the search of the netlink attribute. The remainder calculation for the BPF_S_ANC_NLATTR_NEST extension is also wrong. It has the minuend and subtrahend mixed up, therefore calculates a huge length value, allowing to overrun the end of the message while looking for the netlink attribute. The following three BPF snippets will trigger the bugs when attached to a UNIX datagram socket and parsing a message with length 1, 2 or 3. ,-[ PoC for missing size check in BPF_S_ANC_NLATTR ]-- | ld #0x87654321 | ldx #42 | ld #nla | ret a `--- ,-[ PoC for the same bug in BPF_S_ANC_NLATTR_NEST ]-- | ld #0x87654321 | ldx #42 | ld #nlan | ret a `--- ,-[ PoC for wrong remainder calculation in BPF_S_ANC_NLATTR_NEST ]-- | ; (needs a fake netlink header at offset 0) | ld #0 | ldx #42 | ld #nlan | ret a `--- Fix the first issue by ensuring the message length fulfills the minimal size constrains of a nla header. Fix the second bug by getting the math for the remainder calculation right. Fixes: 4738c1db15 ("[SKFILTER]: Add SKF_ADF_NLATTR instruction") Fixes: d214c7537b ("filter: add SKF_AD_NLATTR_NEST to look for nested..") Cc: Patrick McHardy <kaber@trash.net> Cc: Pablo Neira Ayuso <pablo@netfilter.org> Signed-off-by: Mathias Krause <minipli@googlemail.com> Acked-by: Daniel Borkmann <dborkman@redhat.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-189
0
11,636
Analyze the following 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 encode_extended_dn_request(void *mem_ctx, void *in, DATA_BLOB *out) { struct ldb_extended_dn_control *ledc = talloc_get_type(in, struct ldb_extended_dn_control); struct asn1_data *data; if (!in) { *out = data_blob(NULL, 0); return true; } data = asn1_init(mem_ctx); if (!data) return false; if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) { return false; } if (!asn1_write_Integer(data, ledc->type)) { return false; } if (!asn1_pop_tag(data)) { return false; } *out = data_blob_talloc(mem_ctx, data->data, data->length); if (out->data == NULL) { return false; } talloc_free(data); return true; } Commit Message: CWE ID: CWE-399
0
26,491
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static Widget* widgetForNode(Node* focusedNode) { if (!focusedNode) return 0; RenderObject* renderer = focusedNode->renderer(); if (!renderer || !renderer->isWidget()) return 0; return toRenderWidget(renderer)->widget(); } Commit Message: Unreviewed, rolling out r147402. http://trac.webkit.org/changeset/147402 https://bugs.webkit.org/show_bug.cgi?id=112903 Source/WebCore: * dom/Document.cpp: (WebCore::Document::processHttpEquiv): * loader/DocumentLoader.cpp: (WebCore::DocumentLoader::responseReceived): LayoutTests: * http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body.html: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny.html: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag.html: * http/tests/security/XFrameOptions/x-frame-options-deny.html: * http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny.html: * http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny.html: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt: git-svn-id: svn://svn.chromium.org/blink/trunk@147450 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
0
18,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: vrrp_bfd_thread(thread_t * thread) { bfd_event_t evt; bfd_thread = thread_add_read(master, vrrp_bfd_thread, NULL, thread->u.fd, TIMER_NEVER); if (thread->type != THREAD_READY_FD) return 0; while (read(thread->u.fd, &evt, sizeof(bfd_event_t)) != -1) vrrp_handle_bfd_event(&evt); return 0; } Commit Message: When opening files for write, ensure they aren't symbolic links Issue #1048 identified that if, for example, a non privileged user created a symbolic link from /etc/keepalvied.data to /etc/passwd, writing to /etc/keepalived.data (which could be invoked via DBus) would cause /etc/passwd to be overwritten. This commit stops keepalived writing to pathnames where the ultimate component is a symbolic link, by setting O_NOFOLLOW whenever opening a file for writing. This might break some setups, where, for example, /etc/keepalived.data was a symbolic link to /home/fred/keepalived.data. If this was the case, instead create a symbolic link from /home/fred/keepalived.data to /tmp/keepalived.data, so that the file is still accessible via /home/fred/keepalived.data. There doesn't appear to be a way around this backward incompatibility, since even checking if the pathname is a symbolic link prior to opening for writing would create a race condition. Signed-off-by: Quentin Armitage <quentin@armitage.org.uk> CWE ID: CWE-59
0
24,234
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: char *am_ecp_service_options_str(apr_pool_t *pool, ECPServiceOptions options) { apr_array_header_t *names = apr_array_make(pool, 4, sizeof(const char *)); if (options & ECP_SERVICE_OPTION_CHANNEL_BINDING) { APR_ARRAY_PUSH(names, const char *) = "channel-binding"; options &= ~ECP_SERVICE_OPTION_CHANNEL_BINDING; } if (options & ECP_SERVICE_OPTION_HOLDER_OF_KEY) { APR_ARRAY_PUSH(names, const char *) = "holder-of-key"; options &= ~ECP_SERVICE_OPTION_HOLDER_OF_KEY; } if (options & ECP_SERVICE_OPTION_WANT_AUTHN_SIGNED) { APR_ARRAY_PUSH(names, const char *) = "want-authn-signed"; options &= ~ECP_SERVICE_OPTION_WANT_AUTHN_SIGNED; } if (options & ECP_SERVICE_OPTION_DELEGATION) { APR_ARRAY_PUSH(names, const char *) = "delegation"; options &= ~ECP_SERVICE_OPTION_DELEGATION; } if (options) { APR_ARRAY_PUSH(names, const char *) = apr_psprintf(pool, "(unknown bits = %#x)", options); } return apr_array_pstrcat(pool, names, ','); } Commit Message: Fix redirect URL validation bypass It turns out that browsers silently convert backslash characters into forward slashes, while apr_uri_parse() does not. This mismatch allows an attacker to bypass the redirect URL validation by using an URL like: https://sp.example.org/mellon/logout?ReturnTo=https:%5c%5cmalicious.example.org/ mod_auth_mellon will assume that it is a relative URL and allow the request to pass through, while the browsers will use it as an absolute url and redirect to https://malicious.example.org/ . This patch fixes this issue by rejecting all redirect URLs with backslashes. CWE ID: CWE-601
0
11,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: void Gfx::opRestore(Object args[], int numArgs) { restoreState(); } Commit Message: CWE ID: CWE-20
0
17,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: static void cleanup_timers(struct list_head *head) { cleanup_timers_list(head); cleanup_timers_list(++head); cleanup_timers_list(++head); } Commit Message: posix-timers: Sanitize overrun handling The posix timer overrun handling is broken because the forwarding functions can return a huge number of overruns which does not fit in an int. As a consequence timer_getoverrun(2) and siginfo::si_overrun can turn into random number generators. The k_clock::timer_forward() callbacks return a 64 bit value now. Make k_itimer::ti_overrun[_last] 64bit as well, so the kernel internal accounting is correct. 3Remove the temporary (int) casts. Add a helper function which clamps the overrun value returned to user space via timer_getoverrun(2) or siginfo::si_overrun limited to a positive value between 0 and INT_MAX. INT_MAX is an indicator for user space that the overrun value has been clamped. Reported-by: Team OWL337 <icytxw@gmail.com> Signed-off-by: Thomas Gleixner <tglx@linutronix.de> Acked-by: John Stultz <john.stultz@linaro.org> Cc: Peter Zijlstra <peterz@infradead.org> Cc: Michael Kerrisk <mtk.manpages@gmail.com> Link: https://lkml.kernel.org/r/20180626132705.018623573@linutronix.de CWE ID: CWE-190
0
22,276
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: cifs_demultiplex_thread(struct TCP_Server_Info *server) { int length; unsigned int pdu_length, total_read; struct smb_hdr *smb_buffer = NULL; struct smb_hdr *bigbuf = NULL; struct smb_hdr *smallbuf = NULL; struct msghdr smb_msg; struct kvec iov; struct socket *csocket = server->ssocket; struct list_head *tmp; struct cifsSesInfo *ses; struct task_struct *task_to_wake = NULL; struct mid_q_entry *mid_entry; char temp; bool isLargeBuf = false; bool isMultiRsp; int reconnect; current->flags |= PF_MEMALLOC; cFYI(1, "Demultiplex PID: %d", task_pid_nr(current)); length = atomic_inc_return(&tcpSesAllocCount); if (length > 1) mempool_resize(cifs_req_poolp, length + cifs_min_rcv, GFP_KERNEL); set_freezable(); while (server->tcpStatus != CifsExiting) { if (try_to_freeze()) continue; if (bigbuf == NULL) { bigbuf = cifs_buf_get(); if (!bigbuf) { cERROR(1, "No memory for large SMB response"); msleep(3000); /* retry will check if exiting */ continue; } } else if (isLargeBuf) { /* we are reusing a dirty large buf, clear its start */ memset(bigbuf, 0, sizeof(struct smb_hdr)); } if (smallbuf == NULL) { smallbuf = cifs_small_buf_get(); if (!smallbuf) { cERROR(1, "No memory for SMB response"); msleep(1000); /* retry will check if exiting */ continue; } /* beginning of smb buffer is cleared in our buf_get */ } else /* if existing small buf clear beginning */ memset(smallbuf, 0, sizeof(struct smb_hdr)); isLargeBuf = false; isMultiRsp = false; smb_buffer = smallbuf; iov.iov_base = smb_buffer; iov.iov_len = 4; smb_msg.msg_control = NULL; smb_msg.msg_controllen = 0; pdu_length = 4; /* enough to get RFC1001 header */ incomplete_rcv: length = kernel_recvmsg(csocket, &smb_msg, &iov, 1, pdu_length, 0 /* BB other flags? */); if (server->tcpStatus == CifsExiting) { break; } else if (server->tcpStatus == CifsNeedReconnect) { cFYI(1, "Reconnect after server stopped responding"); cifs_reconnect(server); cFYI(1, "call to reconnect done"); csocket = server->ssocket; continue; } else if ((length == -ERESTARTSYS) || (length == -EAGAIN)) { msleep(1); /* minimum sleep to prevent looping allowing socket to clear and app threads to set tcpStatus CifsNeedReconnect if server hung */ if (pdu_length < 4) { iov.iov_base = (4 - pdu_length) + (char *)smb_buffer; iov.iov_len = pdu_length; smb_msg.msg_control = NULL; smb_msg.msg_controllen = 0; goto incomplete_rcv; } else continue; } else if (length <= 0) { if (server->tcpStatus == CifsNew) { cFYI(1, "tcp session abend after SMBnegprot"); /* some servers kill the TCP session rather than returning an SMB negprot error, in which case reconnecting here is not going to help, and so simply return error to mount */ break; } if (!try_to_freeze() && (length == -EINTR)) { cFYI(1, "cifsd thread killed"); break; } cFYI(1, "Reconnect after unexpected peek error %d", length); cifs_reconnect(server); csocket = server->ssocket; wake_up(&server->response_q); continue; } else if (length < pdu_length) { cFYI(1, "requested %d bytes but only got %d bytes", pdu_length, length); pdu_length -= length; msleep(1); goto incomplete_rcv; } /* The right amount was read from socket - 4 bytes */ /* so we can now interpret the length field */ /* the first byte big endian of the length field, is actually not part of the length but the type with the most common, zero, as regular data */ temp = *((char *) smb_buffer); /* Note that FC 1001 length is big endian on the wire, but we convert it here so it is always manipulated as host byte order */ pdu_length = be32_to_cpu((__force __be32)smb_buffer->smb_buf_length); smb_buffer->smb_buf_length = pdu_length; cFYI(1, "rfc1002 length 0x%x", pdu_length+4); if (temp == (char) RFC1002_SESSION_KEEP_ALIVE) { continue; } else if (temp == (char)RFC1002_POSITIVE_SESSION_RESPONSE) { cFYI(1, "Good RFC 1002 session rsp"); continue; } else if (temp == (char)RFC1002_NEGATIVE_SESSION_RESPONSE) { /* we get this from Windows 98 instead of an error on SMB negprot response */ cFYI(1, "Negative RFC1002 Session Response Error 0x%x)", pdu_length); if (server->tcpStatus == CifsNew) { /* if nack on negprot (rather than ret of smb negprot error) reconnecting not going to help, ret error to mount */ break; } else { /* give server a second to clean up before reconnect attempt */ msleep(1000); /* always try 445 first on reconnect since we get NACK on some if we ever connected to port 139 (the NACK is since we do not begin with RFC1001 session initialize frame) */ server->addr.sockAddr.sin_port = htons(CIFS_PORT); cifs_reconnect(server); csocket = server->ssocket; wake_up(&server->response_q); continue; } } else if (temp != (char) 0) { cERROR(1, "Unknown RFC 1002 frame"); cifs_dump_mem(" Received Data: ", (char *)smb_buffer, length); cifs_reconnect(server); csocket = server->ssocket; continue; } /* else we have an SMB response */ if ((pdu_length > CIFSMaxBufSize + MAX_CIFS_HDR_SIZE - 4) || (pdu_length < sizeof(struct smb_hdr) - 1 - 4)) { cERROR(1, "Invalid size SMB length %d pdu_length %d", length, pdu_length+4); cifs_reconnect(server); csocket = server->ssocket; wake_up(&server->response_q); continue; } /* else length ok */ reconnect = 0; if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE - 4) { isLargeBuf = true; memcpy(bigbuf, smallbuf, 4); smb_buffer = bigbuf; } length = 0; iov.iov_base = 4 + (char *)smb_buffer; iov.iov_len = pdu_length; for (total_read = 0; total_read < pdu_length; total_read += length) { length = kernel_recvmsg(csocket, &smb_msg, &iov, 1, pdu_length - total_read, 0); if ((server->tcpStatus == CifsExiting) || (length == -EINTR)) { /* then will exit */ reconnect = 2; break; } else if (server->tcpStatus == CifsNeedReconnect) { cifs_reconnect(server); csocket = server->ssocket; /* Reconnect wakes up rspns q */ /* Now we will reread sock */ reconnect = 1; break; } else if ((length == -ERESTARTSYS) || (length == -EAGAIN)) { msleep(1); /* minimum sleep to prevent looping, allowing socket to clear and app threads to set tcpStatus CifsNeedReconnect if server hung*/ length = 0; continue; } else if (length <= 0) { cERROR(1, "Received no data, expecting %d", pdu_length - total_read); cifs_reconnect(server); csocket = server->ssocket; reconnect = 1; break; } } if (reconnect == 2) break; else if (reconnect == 1) continue; length += 4; /* account for rfc1002 hdr */ dump_smb(smb_buffer, length); if (checkSMB(smb_buffer, smb_buffer->Mid, total_read+4)) { cifs_dump_mem("Bad SMB: ", smb_buffer, 48); continue; } task_to_wake = NULL; spin_lock(&GlobalMid_Lock); list_for_each(tmp, &server->pending_mid_q) { mid_entry = list_entry(tmp, struct mid_q_entry, qhead); if ((mid_entry->mid == smb_buffer->Mid) && (mid_entry->midState == MID_REQUEST_SUBMITTED) && (mid_entry->command == smb_buffer->Command)) { if (check2ndT2(smb_buffer,server->maxBuf) > 0) { /* We have a multipart transact2 resp */ isMultiRsp = true; if (mid_entry->resp_buf) { /* merge response - fix up 1st*/ if (coalesce_t2(smb_buffer, mid_entry->resp_buf)) { mid_entry->multiRsp = true; break; } else { /* all parts received */ mid_entry->multiEnd = true; goto multi_t2_fnd; } } else { if (!isLargeBuf) { cERROR(1, "1st trans2 resp needs bigbuf"); /* BB maybe we can fix this up, switch to already allocated large buffer? */ } else { /* Have first buffer */ mid_entry->resp_buf = smb_buffer; mid_entry->largeBuf = true; bigbuf = NULL; } } break; } mid_entry->resp_buf = smb_buffer; mid_entry->largeBuf = isLargeBuf; multi_t2_fnd: task_to_wake = mid_entry->tsk; mid_entry->midState = MID_RESPONSE_RECEIVED; #ifdef CONFIG_CIFS_STATS2 mid_entry->when_received = jiffies; #endif /* so we do not time out requests to server which is still responding (since server could be busy but not dead) */ server->lstrp = jiffies; break; } } spin_unlock(&GlobalMid_Lock); if (task_to_wake) { /* Was previous buf put in mpx struct for multi-rsp? */ if (!isMultiRsp) { /* smb buffer will be freed by user thread */ if (isLargeBuf) bigbuf = NULL; else smallbuf = NULL; } wake_up_process(task_to_wake); } else if (!is_valid_oplock_break(smb_buffer, server) && !isMultiRsp) { cERROR(1, "No task to wake, unknown frame received! " "NumMids %d", midCount.counter); cifs_dump_mem("Received Data is: ", (char *)smb_buffer, sizeof(struct smb_hdr)); #ifdef CONFIG_CIFS_DEBUG2 cifs_dump_detail(smb_buffer); cifs_dump_mids(server); #endif /* CIFS_DEBUG2 */ } } /* end while !EXITING */ /* take it off the list, if it's not already */ write_lock(&cifs_tcp_ses_lock); list_del_init(&server->tcp_ses_list); write_unlock(&cifs_tcp_ses_lock); spin_lock(&GlobalMid_Lock); server->tcpStatus = CifsExiting; spin_unlock(&GlobalMid_Lock); wake_up_all(&server->response_q); /* check if we have blocked requests that need to free */ /* Note that cifs_max_pending is normally 50, but can be set at module install time to as little as two */ spin_lock(&GlobalMid_Lock); if (atomic_read(&server->inFlight) >= cifs_max_pending) atomic_set(&server->inFlight, cifs_max_pending - 1); /* We do not want to set the max_pending too low or we could end up with the counter going negative */ spin_unlock(&GlobalMid_Lock); /* Although there should not be any requests blocked on this queue it can not hurt to be paranoid and try to wake up requests that may haven been blocked when more than 50 at time were on the wire to the same server - they now will see the session is in exit state and get out of SendReceive. */ wake_up_all(&server->request_q); /* give those requests time to exit */ msleep(125); if (server->ssocket) { sock_release(csocket); server->ssocket = NULL; } /* buffer usuallly freed in free_mid - need to free it here on exit */ cifs_buf_release(bigbuf); if (smallbuf) /* no sense logging a debug message if NULL */ cifs_small_buf_release(smallbuf); /* * BB: we shouldn't have to do any of this. It shouldn't be * possible to exit from the thread with active SMB sessions */ read_lock(&cifs_tcp_ses_lock); if (list_empty(&server->pending_mid_q)) { /* loop through server session structures attached to this and mark them dead */ list_for_each(tmp, &server->smb_ses_list) { ses = list_entry(tmp, struct cifsSesInfo, smb_ses_list); ses->status = CifsExiting; ses->server = NULL; } read_unlock(&cifs_tcp_ses_lock); } else { /* although we can not zero the server struct pointer yet, since there are active requests which may depnd on them, mark the corresponding SMB sessions as exiting too */ list_for_each(tmp, &server->smb_ses_list) { ses = list_entry(tmp, struct cifsSesInfo, smb_ses_list); ses->status = CifsExiting; } spin_lock(&GlobalMid_Lock); list_for_each(tmp, &server->pending_mid_q) { mid_entry = list_entry(tmp, struct mid_q_entry, qhead); if (mid_entry->midState == MID_REQUEST_SUBMITTED) { cFYI(1, "Clearing Mid 0x%x - waking up ", mid_entry->mid); task_to_wake = mid_entry->tsk; if (task_to_wake) wake_up_process(task_to_wake); } } spin_unlock(&GlobalMid_Lock); read_unlock(&cifs_tcp_ses_lock); /* 1/8th of sec is more than enough time for them to exit */ msleep(125); } if (!list_empty(&server->pending_mid_q)) { /* mpx threads have not exited yet give them at least the smb send timeout time for long ops */ /* due to delays on oplock break requests, we need to wait at least 45 seconds before giving up on a request getting a response and going ahead and killing cifsd */ cFYI(1, "Wait for exit from demultiplex thread"); msleep(46000); /* if threads still have not exited they are probably never coming home not much else we can do but free the memory */ } /* last chance to mark ses pointers invalid if there are any pointing to this (e.g if a crazy root user tried to kill cifsd kernel thread explicitly this might happen) */ /* BB: This shouldn't be necessary, see above */ read_lock(&cifs_tcp_ses_lock); list_for_each(tmp, &server->smb_ses_list) { ses = list_entry(tmp, struct cifsSesInfo, smb_ses_list); ses->server = NULL; } read_unlock(&cifs_tcp_ses_lock); kfree(server->hostname); task_to_wake = xchg(&server->tsk, NULL); kfree(server); length = atomic_dec_return(&tcpSesAllocCount); if (length > 0) mempool_resize(cifs_req_poolp, length + cifs_min_rcv, GFP_KERNEL); /* if server->tsk was NULL then wait for a signal before exiting */ if (!task_to_wake) { set_current_state(TASK_INTERRUPTIBLE); while (!signal_pending(current)) { schedule(); set_current_state(TASK_INTERRUPTIBLE); } set_current_state(TASK_RUNNING); } module_put_and_exit(0); } Commit Message: cifs: clean up cifs_find_smb_ses (try #2) This patch replaces the earlier patch by the same name. The only difference is that MAX_PASSWORD_SIZE has been increased to attempt to match the limits that windows enforces. Do a better job of matching sessions by authtype. Matching by username for a Kerberos session is incorrect, and anonymous sessions need special handling. Also, in the case where we do match by username, we also need to match by password. That ensures that someone else doesn't "borrow" an existing session without needing to know the password. Finally, passwords can be longer than 16 bytes. Bump MAX_PASSWORD_SIZE to 512 to match the size that the userspace mount helper allows. Signed-off-by: Jeff Layton <jlayton@redhat.com> Signed-off-by: Steve French <sfrench@us.ibm.com> CWE ID: CWE-264
0
15,252
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: PHP_FUNCTION(mcrypt_enc_is_block_algorithm_mode) { MCRYPT_GET_TD_ARG if (mcrypt_enc_is_block_algorithm_mode(pm->td) == 1) { RETURN_TRUE } else { RETURN_FALSE } } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
0
12,503
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: inline v8::Handle<v8::Value> DialogHandler::returnValue(v8::Isolate* isolate) const { if (m_dialogContext.IsEmpty()) return v8::Undefined(isolate); v8::Context::Scope scope(m_dialogContext); v8::Handle<v8::Value> returnValue = m_dialogContext->Global()->Get(v8::String::NewSymbol("returnValue")); if (returnValue.IsEmpty()) return v8::Undefined(isolate); return returnValue; } Commit Message: Fix tracking of the id attribute string if it is shared across elements. The patch to remove AtomicStringImpl: http://src.chromium.org/viewvc/blink?view=rev&rev=154790 Exposed a lifetime issue with strings for id attributes. We simply need to use AtomicString. BUG=290566 Review URL: https://codereview.chromium.org/33793004 git-svn-id: svn://svn.chromium.org/blink/trunk@160250 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
0
8,028
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void xenvif_receive_skb(struct xenvif *vif, struct sk_buff *skb) { netif_rx_ni(skb); } 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
14,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: options_for_tty() { char *dev, *path, *p; int ret; size_t pl; dev = devnam; if ((p = strstr(dev, "/dev/")) != NULL) dev = p + 5; if (dev[0] == 0 || strcmp(dev, "tty") == 0) return 1; /* don't look for /etc/ppp/options.tty */ pl = strlen(_PATH_TTYOPT) + strlen(dev) + 1; path = malloc(pl); if (path == NULL) novm("tty init file name"); slprintf(path, pl, "%s%s", _PATH_TTYOPT, dev); /* Turn slashes into dots, for Solaris case (e.g. /dev/term/a) */ for (p = path + strlen(_PATH_TTYOPT); *p != 0; ++p) if (*p == '/') *p = '.'; option_priority = OPRIO_CFGFILE; ret = options_from_file(path, 0, 0, 1); free(path); return ret; } Commit Message: pppd: Eliminate potential integer overflow in option parsing When we are reading in a word from an options file, we maintain a count of the length we have seen so far in 'len', which is an int. When len exceeds MAXWORDLEN - 1 (i.e. 1023) we cease storing characters in the buffer but we continue to increment len. Since len is an int, it will wrap around to -2147483648 after it reaches 2147483647. At that point our test of (len < MAXWORDLEN-1) will succeed and we will start writing characters to memory again. This may enable an attacker to overwrite the heap and thereby corrupt security-relevant variables. For this reason it has been assigned a CVE identifier, CVE-2014-3158. This fixes the bug by ceasing to increment len once it reaches MAXWORDLEN. Reported-by: Lee Campbell <leecam@google.com> Signed-off-by: Paul Mackerras <paulus@samba.org> CWE ID: CWE-119
0
6,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: ATSParser::Stream::Stream( Program *program, unsigned elementaryPID, unsigned streamType, unsigned PCR_PID) : mProgram(program), mElementaryPID(elementaryPID), mStreamType(streamType), mPCR_PID(PCR_PID), mExpectedContinuityCounter(-1), mPayloadStarted(false), mEOSReached(false), mPrevPTS(0), mQueue(NULL) { switch (mStreamType) { case STREAMTYPE_H264: mQueue = new ElementaryStreamQueue( ElementaryStreamQueue::H264, (mProgram->parserFlags() & ALIGNED_VIDEO_DATA) ? ElementaryStreamQueue::kFlag_AlignedData : 0); break; case STREAMTYPE_MPEG2_AUDIO_ADTS: mQueue = new ElementaryStreamQueue(ElementaryStreamQueue::AAC); break; case STREAMTYPE_MPEG1_AUDIO: case STREAMTYPE_MPEG2_AUDIO: mQueue = new ElementaryStreamQueue( ElementaryStreamQueue::MPEG_AUDIO); break; case STREAMTYPE_MPEG1_VIDEO: case STREAMTYPE_MPEG2_VIDEO: mQueue = new ElementaryStreamQueue( ElementaryStreamQueue::MPEG_VIDEO); break; case STREAMTYPE_MPEG4_VIDEO: mQueue = new ElementaryStreamQueue( ElementaryStreamQueue::MPEG4_VIDEO); break; case STREAMTYPE_LPCM_AC3: case STREAMTYPE_AC3: mQueue = new ElementaryStreamQueue( ElementaryStreamQueue::AC3); break; case STREAMTYPE_METADATA: mQueue = new ElementaryStreamQueue( ElementaryStreamQueue::METADATA); break; default: break; } ALOGV("new stream PID 0x%02x, type 0x%02x", elementaryPID, streamType); if (mQueue != NULL) { mBuffer = new ABuffer(192 * 1024); mBuffer->setRange(0, 0); } } Commit Message: Check section size when verifying CRC Bug: 28333006 Change-Id: Ief7a2da848face78f0edde21e2f2009316076679 CWE ID: CWE-119
0
18,086
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: error::Error GLES2DecoderPassthroughImpl::DoGetAttachedShaders( GLuint program, GLsizei maxcount, GLsizei* count, GLuint* shaders) { api()->glGetAttachedShadersFn(GetProgramServiceID(program, resources_), maxcount, count, shaders); return error::kNoError; } 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
21,325
Analyze the following 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 runtimeEnabledVoidMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder()); imp->runtimeEnabledVoidMethod(); } 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
21,535
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: DefragIPv4TooLargeTest(void) { DefragContext *dc = NULL; Packet *p = NULL; int ret = 0; DefragInit(); dc = DefragContextNew(); if (dc == NULL) goto end; /* Create a fragment that would extend past the max allowable size * for an IPv4 packet. */ p = BuildTestPacket(1, 8183, 0, 'A', 71); if (p == NULL) goto end; /* We do not expect a packet returned. */ if (Defrag(NULL, NULL, p, NULL) != NULL) goto end; if (!ENGINE_ISSET_EVENT(p, IPV4_FRAG_PKT_TOO_LARGE)) goto end; /* The fragment should have been ignored so no fragments should have * been allocated from the pool. */ if (dc->frag_pool->outstanding != 0) return 0; ret = 1; end: if (dc != NULL) DefragContextDestroy(dc); if (p != NULL) SCFree(p); DefragDestroy(); return ret; } Commit Message: defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host. CWE ID: CWE-358
1
13,577
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: LayoutUnit RenderFlexibleBox::marginBoxAscentForChild(RenderBox* child) { LayoutUnit ascent = child->firstLineBoxBaseline(); if (ascent == -1) ascent = crossAxisExtentForChild(child); return ascent + flowAwareMarginBeforeForChild(child); } Commit Message: Separate repaint and layout requirements of StyleDifference (Step 1) Previously StyleDifference was an enum that proximately bigger values imply smaller values (e.g. StyleDifferenceLayout implies StyleDifferenceRepaint). This causes unnecessary repaints in some cases on layout change. Convert StyleDifference to a structure containing relatively independent flags. This change doesn't directly improve the result, but can make further repaint optimizations possible. Step 1 doesn't change any functionality. RenderStyle still generate the legacy StyleDifference enum when comparing styles and convert the result to the new StyleDifference. Implicit requirements are not handled during the conversion. Converted call sites to use the new StyleDifference according to the following conversion rules: - diff == StyleDifferenceEqual (&& !context) => diff.hasNoChange() - diff == StyleDifferenceRepaint => diff.needsRepaintObjectOnly() - diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff >= StyleDifferenceRepaint => diff.needsRepaint() || diff.needsLayout() - diff >= StyleDifferenceRepaintLayer => diff.needsRepaintLayer() || diff.needsLayout() - diff > StyleDifferenceRepaintLayer => diff.needsLayout() - diff == StyleDifferencePositionedMovementLayoutOnly => diff.needsPositionedMovementLayoutOnly() - diff == StyleDifferenceLayout => diff.needsFullLayout() BUG=358460 TEST=All existing layout tests. R=eseidel@chromium.org, esprehn@chromium.org, jchaffraix@chromium.org Committed: https://src.chromium.org/viewvc/blink?view=rev&revision=171983 Review URL: https://codereview.chromium.org/236203020 git-svn-id: svn://svn.chromium.org/blink/trunk@172331 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
0
23,200
Analyze the following 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 emulator_get_msr(struct x86_emulate_ctxt *ctxt, u32 msr_index, u64 *pdata) { struct msr_data msr; int r; msr.index = msr_index; msr.host_initiated = false; r = kvm_get_msr(emul_to_vcpu(ctxt), &msr); if (r) return r; *pdata = msr.data; return 0; } Commit Message: KVM: x86: Reload pit counters for all channels when restoring state Currently if userspace restores the pit counters with a count of 0 on channels 1 or 2 and the guest attempts to read the count on those channels, then KVM will perform a mod of 0 and crash. This will ensure that 0 values are converted to 65536 as per the spec. This is CVE-2015-7513. Signed-off-by: Andy Honig <ahonig@google.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> CWE ID:
0
26,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: status_t SampleIterator::seekTo(uint32_t sampleIndex) { ALOGV("seekTo(%d)", sampleIndex); if (sampleIndex >= mTable->mNumSampleSizes) { return ERROR_END_OF_STREAM; } if (mTable->mSampleToChunkOffset < 0 || mTable->mChunkOffsetOffset < 0 || mTable->mSampleSizeOffset < 0 || mTable->mTimeToSampleCount == 0) { return ERROR_MALFORMED; } if (mInitialized && mCurrentSampleIndex == sampleIndex) { return OK; } if (!mInitialized || sampleIndex < mFirstChunkSampleIndex) { reset(); } if (sampleIndex >= mStopChunkSampleIndex) { status_t err; if ((err = findChunkRange(sampleIndex)) != OK) { ALOGE("findChunkRange failed"); return err; } } CHECK(sampleIndex < mStopChunkSampleIndex); if (mSamplesPerChunk == 0) { ALOGE("b/22802344"); return ERROR_MALFORMED; } uint32_t chunk = (sampleIndex - mFirstChunkSampleIndex) / mSamplesPerChunk + mFirstChunk; if (!mInitialized || chunk != mCurrentChunkIndex) { mCurrentChunkIndex = chunk; status_t err; if ((err = getChunkOffset(chunk, &mCurrentChunkOffset)) != OK) { ALOGE("getChunkOffset return error"); return err; } mCurrentChunkSampleSizes.clear(); uint32_t firstChunkSampleIndex = mFirstChunkSampleIndex + mSamplesPerChunk * (mCurrentChunkIndex - mFirstChunk); for (uint32_t i = 0; i < mSamplesPerChunk; ++i) { size_t sampleSize; if ((err = getSampleSizeDirect( firstChunkSampleIndex + i, &sampleSize)) != OK) { ALOGE("getSampleSizeDirect return error"); return err; } mCurrentChunkSampleSizes.push(sampleSize); } } uint32_t chunkRelativeSampleIndex = (sampleIndex - mFirstChunkSampleIndex) % mSamplesPerChunk; mCurrentSampleOffset = mCurrentChunkOffset; for (uint32_t i = 0; i < chunkRelativeSampleIndex; ++i) { mCurrentSampleOffset += mCurrentChunkSampleSizes[i]; } mCurrentSampleSize = mCurrentChunkSampleSizes[chunkRelativeSampleIndex]; if (sampleIndex < mTTSSampleIndex) { mTimeToSampleIndex = 0; mTTSSampleIndex = 0; mTTSSampleTime = 0; mTTSCount = 0; mTTSDuration = 0; } status_t err; if ((err = findSampleTimeAndDuration( sampleIndex, &mCurrentSampleTime, &mCurrentSampleDuration)) != OK) { ALOGE("findSampleTime return error"); return err; } mCurrentSampleIndex = sampleIndex; mInitialized = true; return OK; } Commit Message: SampleIterator: clear members on seekTo error Bug: 31091777 Change-Id: Iddf99d0011961d0fd3d755e57db4365b6a6a1193 (cherry picked from commit 03237ce0f9584c98ccda76c2474a4ae84c763f5b) CWE ID: CWE-200
1
95
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: BrotliResult BrotliDecompressStream(size_t* available_in, const uint8_t** next_in, size_t* available_out, uint8_t** next_out, size_t* total_out, BrotliState* s) { BrotliResult result = BROTLI_RESULT_SUCCESS; BrotliBitReader* br = &s->br; if (s->buffer_length == 0) { /* Just connect bit reader to input stream. */ br->avail_in = *available_in; br->next_in = *next_in; } else { /* At least one byte of input is required. More than one byte of input may be required to complete the transaction -> reading more data must be done in a loop -> do it in a main loop. */ result = BROTLI_RESULT_NEEDS_MORE_INPUT; br->next_in = &s->buffer.u8[0]; } /* State machine */ for (;;) { if (result != BROTLI_RESULT_SUCCESS) { /* Error | needs more input/output */ if (result == BROTLI_RESULT_NEEDS_MORE_INPUT) { if (s->ringbuffer != 0) { /* Proactively push output. */ WriteRingBuffer(available_out, next_out, total_out, s); } if (s->buffer_length != 0) { /* Used with internal buffer. */ if (br->avail_in == 0) { /* Successfully finished read transaction. */ /* Accamulator contains less than 8 bits, because internal buffer is expanded byte-by-byte until it is enough to complete read. */ s->buffer_length = 0; /* Switch to input stream and restart. */ result = BROTLI_RESULT_SUCCESS; br->avail_in = *available_in; br->next_in = *next_in; continue; } else if (*available_in != 0) { /* Not enough data in buffer, but can take one more byte from input stream. */ result = BROTLI_RESULT_SUCCESS; s->buffer.u8[s->buffer_length] = **next_in; s->buffer_length++; br->avail_in = s->buffer_length; (*next_in)++; (*available_in)--; /* Retry with more data in buffer. */ continue; } /* Can't finish reading and no more input.*/ break; } else { /* Input stream doesn't contain enough input. */ /* Copy tail to internal buffer and return. */ *next_in = br->next_in; *available_in = br->avail_in; while (*available_in) { s->buffer.u8[s->buffer_length] = **next_in; s->buffer_length++; (*next_in)++; (*available_in)--; } break; } /* Unreachable. */ } /* Fail or needs more output. */ if (s->buffer_length != 0) { /* Just consumed the buffered input and produced some output. Otherwise it would result in "needs more input". Reset internal buffer.*/ s->buffer_length = 0; } else { /* Using input stream in last iteration. When decoder switches to input stream it has less than 8 bits in accamulator, so it is safe to return unused accamulator bits there. */ BrotliBitReaderUnload(br); *available_in = br->avail_in; *next_in = br->next_in; } break; } switch (s->state) { case BROTLI_STATE_UNINITED: /* Prepare to the first read. */ if (!BrotliWarmupBitReader(br)) { result = BROTLI_RESULT_NEEDS_MORE_INPUT; break; } /* Decode window size. */ s->window_bits = DecodeWindowBits(br); /* Reads 1..7 bits. */ BROTLI_LOG_UINT(s->window_bits); if (s->window_bits == 9) { /* Value 9 is reserved for future use. */ result = BROTLI_FAILURE(); break; } s->max_backward_distance = (1 << s->window_bits) - 16; s->max_backward_distance_minus_custom_dict_size = s->max_backward_distance - s->custom_dict_size; /* Allocate memory for both block_type_trees and block_len_trees. */ s->block_type_trees = (HuffmanCode*)BROTLI_ALLOC(s, 6 * BROTLI_HUFFMAN_MAX_TABLE_SIZE * sizeof(HuffmanCode)); if (s->block_type_trees == 0) { result = BROTLI_FAILURE(); break; } s->block_len_trees = s->block_type_trees + 3 * BROTLI_HUFFMAN_MAX_TABLE_SIZE; s->state = BROTLI_STATE_METABLOCK_BEGIN; /* No break, continue to next state */ case BROTLI_STATE_METABLOCK_BEGIN: BrotliStateMetablockBegin(s); BROTLI_LOG_UINT(s->pos); s->state = BROTLI_STATE_METABLOCK_HEADER; /* No break, continue to next state */ case BROTLI_STATE_METABLOCK_HEADER: result = DecodeMetaBlockLength(s, br); /* Reads 2 - 31 bits. */ if (result != BROTLI_RESULT_SUCCESS) { break; } BROTLI_LOG_UINT(s->is_last_metablock); BROTLI_LOG_UINT(s->meta_block_remaining_len); BROTLI_LOG_UINT(s->is_metadata); BROTLI_LOG_UINT(s->is_uncompressed); if (s->is_metadata || s->is_uncompressed) { if (!BrotliJumpToByteBoundary(br)) { result = BROTLI_FAILURE(); break; } } if (s->is_metadata) { s->state = BROTLI_STATE_METADATA; break; } if (s->meta_block_remaining_len == 0) { s->state = BROTLI_STATE_METABLOCK_DONE; break; } if (!s->ringbuffer) { if (!BrotliAllocateRingBuffer(s, br)) { result = BROTLI_FAILURE(); break; } } if (s->is_uncompressed) { s->state = BROTLI_STATE_UNCOMPRESSED; break; } s->loop_counter = 0; s->state = BROTLI_STATE_HUFFMAN_CODE_0; break; case BROTLI_STATE_UNCOMPRESSED: { int bytes_copied = s->meta_block_remaining_len; result = CopyUncompressedBlockToOutput( available_out, next_out, total_out, s); bytes_copied -= s->meta_block_remaining_len; if (result != BROTLI_RESULT_SUCCESS) { break; } s->state = BROTLI_STATE_METABLOCK_DONE; break; } case BROTLI_STATE_METADATA: for (; s->meta_block_remaining_len > 0; --s->meta_block_remaining_len) { uint32_t bits; /* Read one byte and ignore it. */ if (!BrotliSafeReadBits(br, 8, &bits)) { result = BROTLI_RESULT_NEEDS_MORE_INPUT; break; } } if (result == BROTLI_RESULT_SUCCESS) { s->state = BROTLI_STATE_METABLOCK_DONE; } break; case BROTLI_STATE_HUFFMAN_CODE_0: if (s->loop_counter >= 3) { s->state = BROTLI_STATE_METABLOCK_HEADER_2; break; } /* Reads 1..11 bits. */ result = DecodeVarLenUint8(s, br, &s->num_block_types[s->loop_counter]); if (result != BROTLI_RESULT_SUCCESS) { break; } s->num_block_types[s->loop_counter]++; BROTLI_LOG_UINT(s->num_block_types[s->loop_counter]); if (s->num_block_types[s->loop_counter] < 2) { s->loop_counter++; break; } s->state = BROTLI_STATE_HUFFMAN_CODE_1; /* No break, continue to next state */ case BROTLI_STATE_HUFFMAN_CODE_1: { int tree_offset = s->loop_counter * BROTLI_HUFFMAN_MAX_TABLE_SIZE; result = ReadHuffmanCode(s->num_block_types[s->loop_counter] + 2, &s->block_type_trees[tree_offset], NULL, s); if (result != BROTLI_RESULT_SUCCESS) break; s->state = BROTLI_STATE_HUFFMAN_CODE_2; /* No break, continue to next state */ } case BROTLI_STATE_HUFFMAN_CODE_2: { int tree_offset = s->loop_counter * BROTLI_HUFFMAN_MAX_TABLE_SIZE; result = ReadHuffmanCode(kNumBlockLengthCodes, &s->block_len_trees[tree_offset], NULL, s); if (result != BROTLI_RESULT_SUCCESS) break; s->state = BROTLI_STATE_HUFFMAN_CODE_3; /* No break, continue to next state */ } case BROTLI_STATE_HUFFMAN_CODE_3: { int tree_offset = s->loop_counter * BROTLI_HUFFMAN_MAX_TABLE_SIZE; if (!SafeReadBlockLength(s, &s->block_length[s->loop_counter], &s->block_len_trees[tree_offset], br)) { result = BROTLI_RESULT_NEEDS_MORE_INPUT; break; } BROTLI_LOG_UINT(s->block_length[s->loop_counter]); s->loop_counter++; s->state = BROTLI_STATE_HUFFMAN_CODE_0; break; } case BROTLI_STATE_METABLOCK_HEADER_2: { uint32_t bits; if (!BrotliSafeReadBits(br, 6, &bits)) { result = BROTLI_RESULT_NEEDS_MORE_INPUT; break; } s->distance_postfix_bits = bits & BitMask(2); bits >>= 2; s->num_direct_distance_codes = NUM_DISTANCE_SHORT_CODES + (bits << s->distance_postfix_bits); BROTLI_LOG_UINT(s->num_direct_distance_codes); BROTLI_LOG_UINT(s->distance_postfix_bits); s->distance_postfix_mask = (int)BitMask(s->distance_postfix_bits); s->context_modes = (uint8_t*)BROTLI_ALLOC(s, (size_t)s->num_block_types[0]); if (s->context_modes == 0) { result = BROTLI_FAILURE(); break; } s->loop_counter = 0; s->state = BROTLI_STATE_CONTEXT_MODES; /* No break, continue to next state */ } case BROTLI_STATE_CONTEXT_MODES: result = ReadContextModes(s); if (result != BROTLI_RESULT_SUCCESS) { break; } s->state = BROTLI_STATE_CONTEXT_MAP_1; /* No break, continue to next state */ case BROTLI_STATE_CONTEXT_MAP_1: { uint32_t j; result = DecodeContextMap(s->num_block_types[0] << kLiteralContextBits, &s->num_literal_htrees, &s->context_map, s); if (result != BROTLI_RESULT_SUCCESS) { break; } s->trivial_literal_context = 1; for (j = 0; j < s->num_block_types[0] << kLiteralContextBits; j++) { if (s->context_map[j] != j >> kLiteralContextBits) { s->trivial_literal_context = 0; break; } } s->state = BROTLI_STATE_CONTEXT_MAP_2; /* No break, continue to next state */ } case BROTLI_STATE_CONTEXT_MAP_2: { uint32_t num_distance_codes = s->num_direct_distance_codes + (48U << s->distance_postfix_bits); result = DecodeContextMap( s->num_block_types[2] << kDistanceContextBits, &s->num_dist_htrees, &s->dist_context_map, s); if (result != BROTLI_RESULT_SUCCESS) { break; } BrotliHuffmanTreeGroupInit(s, &s->literal_hgroup, kNumLiteralCodes, s->num_literal_htrees); BrotliHuffmanTreeGroupInit(s, &s->insert_copy_hgroup, kNumInsertAndCopyCodes, s->num_block_types[1]); BrotliHuffmanTreeGroupInit(s, &s->distance_hgroup, num_distance_codes, s->num_dist_htrees); if (s->literal_hgroup.codes == 0 || s->insert_copy_hgroup.codes == 0 || s->distance_hgroup.codes == 0) { return BROTLI_FAILURE(); } } s->loop_counter = 0; s->state = BROTLI_STATE_TREE_GROUP; /* No break, continue to next state */ case BROTLI_STATE_TREE_GROUP: { HuffmanTreeGroup* hgroup = NULL; switch (s->loop_counter) { case 0: hgroup = &s->literal_hgroup; break; case 1: hgroup = &s->insert_copy_hgroup; break; case 2: hgroup = &s->distance_hgroup; break; } result = HuffmanTreeGroupDecode(hgroup, s); } if (result != BROTLI_RESULT_SUCCESS) break; s->loop_counter++; if (s->loop_counter >= 3) { uint8_t context_mode = s->context_modes[s->block_type_rb[1]]; s->context_map_slice = s->context_map; s->dist_context_map_slice = s->dist_context_map; s->context_lookup1 = &kContextLookup[kContextLookupOffsets[context_mode]]; s->context_lookup2 = &kContextLookup[kContextLookupOffsets[context_mode + 1]]; s->htree_command = s->insert_copy_hgroup.htrees[0]; s->literal_htree = s->literal_hgroup.htrees[s->literal_htree_index]; s->state = BROTLI_STATE_COMMAND_BEGIN; } break; case BROTLI_STATE_COMMAND_BEGIN: case BROTLI_STATE_COMMAND_INNER: case BROTLI_STATE_COMMAND_POST_DECODE_LITERALS: case BROTLI_STATE_COMMAND_POST_WRAP_COPY: result = ProcessCommands(s); if (result == BROTLI_RESULT_NEEDS_MORE_INPUT) { result = SafeProcessCommands(s); } break; case BROTLI_STATE_COMMAND_INNER_WRITE: case BROTLI_STATE_COMMAND_POST_WRITE_1: case BROTLI_STATE_COMMAND_POST_WRITE_2: result = WriteRingBuffer(available_out, next_out, total_out, s); if (result != BROTLI_RESULT_SUCCESS) { break; } s->pos -= s->ringbuffer_size; s->rb_roundtrips++; s->max_distance = s->max_backward_distance; if (s->state == BROTLI_STATE_COMMAND_POST_WRITE_1) { memcpy(s->ringbuffer, s->ringbuffer_end, (size_t)s->pos); if (s->meta_block_remaining_len <= 0) { /* Next metablock, if any */ s->state = BROTLI_STATE_METABLOCK_DONE; } else { s->state = BROTLI_STATE_COMMAND_BEGIN; } break; } else if (s->state == BROTLI_STATE_COMMAND_POST_WRITE_2) { s->state = BROTLI_STATE_COMMAND_POST_WRAP_COPY; } else { /* BROTLI_STATE_COMMAND_INNER_WRITE */ if (s->loop_counter == 0) { if (s->meta_block_remaining_len <= 0) { s->state = BROTLI_STATE_METABLOCK_DONE; } else { s->state = BROTLI_STATE_COMMAND_POST_DECODE_LITERALS; } break; } s->state = BROTLI_STATE_COMMAND_INNER; } break; case BROTLI_STATE_METABLOCK_DONE: BrotliStateCleanupAfterMetablock(s); if (!s->is_last_metablock) { s->state = BROTLI_STATE_METABLOCK_BEGIN; break; } if (!BrotliJumpToByteBoundary(br)) { result = BROTLI_FAILURE(); } if (s->buffer_length == 0) { BrotliBitReaderUnload(br); *available_in = br->avail_in; *next_in = br->next_in; } s->state = BROTLI_STATE_DONE; /* No break, continue to next state */ case BROTLI_STATE_DONE: if (s->ringbuffer != 0) { result = WriteRingBuffer(available_out, next_out, total_out, s); if (result != BROTLI_RESULT_SUCCESS) { break; } } return result; } } return result; } Commit Message: Cherry pick underflow fix. BUG=583607 Review URL: https://codereview.chromium.org/1662313002 Cr-Commit-Position: refs/heads/master@{#373736} CWE ID: CWE-119
0
20,909
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: rx_print(netdissect_options *ndo, register const u_char *bp, int length, int sport, int dport, const u_char *bp2) { register const struct rx_header *rxh; int i; int32_t opcode; if (ndo->ndo_snapend - bp < (int)sizeof (struct rx_header)) { ND_PRINT((ndo, " [|rx] (%d)", length)); return; } rxh = (const struct rx_header *) bp; ND_PRINT((ndo, " rx %s", tok2str(rx_types, "type %d", rxh->type))); if (ndo->ndo_vflag) { int firstflag = 0; if (ndo->ndo_vflag > 1) ND_PRINT((ndo, " cid %08x call# %d", (int) EXTRACT_32BITS(&rxh->cid), (int) EXTRACT_32BITS(&rxh->callNumber))); ND_PRINT((ndo, " seq %d ser %d", (int) EXTRACT_32BITS(&rxh->seq), (int) EXTRACT_32BITS(&rxh->serial))); if (ndo->ndo_vflag > 2) ND_PRINT((ndo, " secindex %d serviceid %hu", (int) rxh->securityIndex, EXTRACT_16BITS(&rxh->serviceId))); if (ndo->ndo_vflag > 1) for (i = 0; i < NUM_RX_FLAGS; i++) { if (rxh->flags & rx_flags[i].flag && (!rx_flags[i].packetType || rxh->type == rx_flags[i].packetType)) { if (!firstflag) { firstflag = 1; ND_PRINT((ndo, " ")); } else { ND_PRINT((ndo, ",")); } ND_PRINT((ndo, "<%s>", rx_flags[i].s)); } } } /* * Try to handle AFS calls that we know about. Check the destination * port and make sure it's a data packet. Also, make sure the * seq number is 1 (because otherwise it's a continuation packet, * and we can't interpret that). Also, seems that reply packets * do not have the client-init flag set, so we check for that * as well. */ if (rxh->type == RX_PACKET_TYPE_DATA && EXTRACT_32BITS(&rxh->seq) == 1 && rxh->flags & RX_CLIENT_INITIATED) { /* * Insert this call into the call cache table, so we * have a chance to print out replies */ rx_cache_insert(ndo, bp, (const struct ip *) bp2, dport); switch (dport) { case FS_RX_PORT: /* AFS file service */ fs_print(ndo, bp, length); break; case CB_RX_PORT: /* AFS callback service */ cb_print(ndo, bp, length); break; case PROT_RX_PORT: /* AFS protection service */ prot_print(ndo, bp, length); break; case VLDB_RX_PORT: /* AFS VLDB service */ vldb_print(ndo, bp, length); break; case KAUTH_RX_PORT: /* AFS Kerberos auth service */ kauth_print(ndo, bp, length); break; case VOL_RX_PORT: /* AFS Volume service */ vol_print(ndo, bp, length); break; case BOS_RX_PORT: /* AFS BOS service */ bos_print(ndo, bp, length); break; default: ; } /* * If it's a reply (client-init is _not_ set, but seq is one) * then look it up in the cache. If we find it, call the reply * printing functions Note that we handle abort packets here, * because printing out the return code can be useful at times. */ } else if (((rxh->type == RX_PACKET_TYPE_DATA && EXTRACT_32BITS(&rxh->seq) == 1) || rxh->type == RX_PACKET_TYPE_ABORT) && (rxh->flags & RX_CLIENT_INITIATED) == 0 && rx_cache_find(rxh, (const struct ip *) bp2, sport, &opcode)) { switch (sport) { case FS_RX_PORT: /* AFS file service */ fs_reply_print(ndo, bp, length, opcode); break; case CB_RX_PORT: /* AFS callback service */ cb_reply_print(ndo, bp, length, opcode); break; case PROT_RX_PORT: /* AFS PT service */ prot_reply_print(ndo, bp, length, opcode); break; case VLDB_RX_PORT: /* AFS VLDB service */ vldb_reply_print(ndo, bp, length, opcode); break; case KAUTH_RX_PORT: /* AFS Kerberos auth service */ kauth_reply_print(ndo, bp, length, opcode); break; case VOL_RX_PORT: /* AFS Volume service */ vol_reply_print(ndo, bp, length, opcode); break; case BOS_RX_PORT: /* AFS BOS service */ bos_reply_print(ndo, bp, length, opcode); break; default: ; } /* * If it's an RX ack packet, then use the appropriate ack decoding * function (there isn't any service-specific information in the * ack packet, so we can use one for all AFS services) */ } else if (rxh->type == RX_PACKET_TYPE_ACK) rx_ack_print(ndo, bp, length); ND_PRINT((ndo, " (%d)", length)); } Commit Message: CVE-2017-13049/Rx: add a missing bounds check for Ubik One of the case blocks in ubik_print() didn't check bounds before fetching 32 bits of packet data and could overread past the captured packet data by that amount. This fixes a buffer over-read discovered by Henri Salo from Nixu Corporation. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
0
9,742
Analyze the following 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 LocalFrame::StartPrintingWithoutPrintingLayout() { SetPrinting(/*printing=*/true, /*use_printing_layout=*/false, FloatSize(), FloatSize(), 0); } Commit Message: Prevent sandboxed documents from reusing the default window Bug: 377995 Change-Id: Iff66c6d214dfd0cb7ea9c80f83afeedfff703541 Reviewed-on: https://chromium-review.googlesource.com/983558 Commit-Queue: Andy Paicu <andypaicu@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Cr-Commit-Position: refs/heads/master@{#567663} CWE ID: CWE-285
0
27,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: int pdf_add_line(struct pdf_doc *pdf, struct pdf_object *page, int x1, int y1, int x2, int y2, int width, uint32_t colour) { int ret; struct dstr str = {0, 0, 0}; dstr_append(&str, "BT\r\n"); dstr_printf(&str, "%d w\r\n", width); dstr_printf(&str, "%d %d m\r\n", x1, y1); dstr_printf(&str, "/DeviceRGB CS\r\n"); dstr_printf(&str, "%f %f %f RG\r\n", PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour)); dstr_printf(&str, "%d %d l S\r\n", x2, y2); dstr_append(&str, "ET"); ret = pdf_add_stream(pdf, page, str.data); dstr_free(&str); return ret; } Commit Message: jpeg: Fix another possible buffer overrun Found via the clang libfuzzer CWE ID: CWE-125
0
24,658
Analyze the following 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 DevToolsUIBindings::SetIsDocked(const DispatchCallback& callback, bool dock_requested) { delegate_->SetIsDocked(dock_requested); callback.Run(nullptr); } Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds BUG=662859 Review-Url: https://codereview.chromium.org/2607833002 Cr-Commit-Position: refs/heads/master@{#440926} CWE ID: CWE-200
0
19,120
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool RenderFrameHostManager::IsRendererTransferNeededForNavigation( RenderFrameHostImpl* rfh, const GURL& dest_url) { if (!rfh->GetSiteInstance()->HasSite()) return false; if (rfh->GetSiteInstance()->GetSiteURL().SchemeIs(kGuestScheme)) return false; BrowserContext* context = rfh->GetSiteInstance()->GetBrowserContext(); if (IsCurrentlySameSite(rfh, dest_url)) { return false; } if (rfh->GetSiteInstance()->RequiresDedicatedProcess() || SiteInstanceImpl::DoesSiteRequireDedicatedProcess(context, dest_url)) { return true; } if (SiteIsolationPolicy::IsTopDocumentIsolationEnabled() && (!frame_tree_node_->IsMainFrame() || rfh->GetSiteInstance()->IsDefaultSubframeSiteInstance())) { return true; } return false; } Commit Message: Don't show current RenderWidgetHostView while interstitial is showing. Also moves interstitial page tracking from RenderFrameHostManager to WebContents, since interstitial pages are not frame-specific. This was necessary for subframes to detect if an interstitial page is showing. BUG=729105 TEST=See comment 13 of bug for repro steps CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2938313002 Cr-Commit-Position: refs/heads/master@{#480117} CWE ID: CWE-20
0
23,311
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void GDataFileSystem::OnGetEntryInfoCompleteForOpenFile( const FilePath& file_path, const OpenFileCallback& callback, GDataFileError error, scoped_ptr<GDataEntryProto> entry_proto) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (entry_proto.get() && !entry_proto->has_file_specific_info()) error = GDATA_FILE_ERROR_NOT_FOUND; if (error == GDATA_FILE_OK) { if (entry_proto->file_specific_info().file_md5().empty() || entry_proto->file_specific_info().is_hosted_document()) { error = GDATA_FILE_ERROR_INVALID_OPERATION; } } if (error != GDATA_FILE_OK) { if (!callback.is_null()) callback.Run(error, FilePath()); return; } DCHECK(!entry_proto->resource_id().empty()); GetResolvedFileByPath( file_path, base::Bind(&GDataFileSystem::OnGetFileCompleteForOpenFile, ui_weak_ptr_, callback, GetFileCompleteForOpenParams( entry_proto->resource_id(), entry_proto->file_specific_info().file_md5())), GetDownloadDataCallback(), error, entry_proto.get()); } Commit Message: Remove parent* arg from GDataEntry ctor. * Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry. * Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry. * Add GDataDirectoryService::FromDocumentEntry and use this everywhere. * Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and CreateGDataDirectory. Make GDataEntry ctor protected. BUG=141494 TEST=unit tests. Review URL: https://chromiumcodereview.appspot.com/10854083 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
0
8,609
Analyze the following 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 mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc) { kmem_cache_free(pte_list_desc_cache, pte_list_desc); } 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
18,534
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int em_smsw(struct x86_emulate_ctxt *ctxt) { ctxt->dst.bytes = 2; ctxt->dst.val = ctxt->ops->get_cr(ctxt, 0); return X86EMUL_CONTINUE; } Commit Message: KVM: x86: fix missing checks in syscall emulation On hosts without this patch, 32bit guests will crash (and 64bit guests may behave in a wrong way) for example by simply executing following nasm-demo-application: [bits 32] global _start SECTION .text _start: syscall (I tested it with winxp and linux - both always crashed) Disassembly of section .text: 00000000 <_start>: 0: 0f 05 syscall The reason seems a missing "invalid opcode"-trap (int6) for the syscall opcode "0f05", which is not available on Intel CPUs within non-longmodes, as also on some AMD CPUs within legacy-mode. (depending on CPU vendor, MSR_EFER and cpuid) Because previous mentioned OSs may not engage corresponding syscall target-registers (STAR, LSTAR, CSTAR), they remain NULL and (non trapping) syscalls are leading to multiple faults and finally crashs. Depending on the architecture (AMD or Intel) pretended by guests, various checks according to vendor's documentation are implemented to overcome the current issue and behave like the CPUs physical counterparts. [mtosatti: cleanup/beautify code] Signed-off-by: Stephan Baerwolf <stephan.baerwolf@tu-ilmenau.de> Signed-off-by: Marcelo Tosatti <mtosatti@redhat.com> CWE ID:
0
2,208
Analyze the following 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 uint32_t in_get_sample_rate(const struct audio_stream *stream) { struct a2dp_stream_in *in = (struct a2dp_stream_in *)stream; FNLOG(); return in->common.cfg.rate; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
0
20,158
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op, ExceptionInfo *exception) { #define ComplexImageTag "Complex/Image" CacheView *Ai_view, *Ar_view, *Bi_view, *Br_view, *Ci_view, *Cr_view; const char *artifact; const Image *Ai_image, *Ar_image, *Bi_image, *Br_image; double snr; Image *Ci_image, *complex_images, *Cr_image, *image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (images->next == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",images->filename); return((Image *) NULL); } image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { image=DestroyImageList(image); return(image); } image->depth=32UL; complex_images=NewImageList(); AppendImageToList(&complex_images,image); image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) { complex_images=DestroyImageList(complex_images); return(complex_images); } AppendImageToList(&complex_images,image); /* Apply complex mathematics to image pixels. */ artifact=GetImageArtifact(image,"complex:snr"); snr=0.0; if (artifact != (const char *) NULL) snr=StringToDouble(artifact,(char **) NULL); Ar_image=images; Ai_image=images->next; Br_image=images; Bi_image=images->next; if ((images->next->next != (Image *) NULL) && (images->next->next->next != (Image *) NULL)) { Br_image=images->next->next; Bi_image=images->next->next->next; } Cr_image=complex_images; Ci_image=complex_images->next; Ar_view=AcquireVirtualCacheView(Ar_image,exception); Ai_view=AcquireVirtualCacheView(Ai_image,exception); Br_view=AcquireVirtualCacheView(Br_image,exception); Bi_view=AcquireVirtualCacheView(Bi_image,exception); Cr_view=AcquireAuthenticCacheView(Cr_image,exception); Ci_view=AcquireAuthenticCacheView(Ci_image,exception); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(images,complex_images,images->rows,1L) #endif for (y=0; y < (ssize_t) images->rows; y++) { register const PixelPacket *magick_restrict Ai, *magick_restrict Ar, *magick_restrict Bi, *magick_restrict Br; register PixelPacket *magick_restrict Ci, *magick_restrict Cr; register ssize_t x; if (status == MagickFalse) continue; Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Ar_image->columns,1,exception); Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Ai_image->columns,1,exception); Br=GetCacheViewVirtualPixels(Br_view,0,y,Br_image->columns,1,exception); Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Bi_image->columns,1,exception); Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception); Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception); if ((Ar == (const PixelPacket *) NULL) || (Ai == (const PixelPacket *) NULL) || (Br == (const PixelPacket *) NULL) || (Bi == (const PixelPacket *) NULL) || (Cr == (PixelPacket *) NULL) || (Ci == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) images->columns; x++) { switch (op) { case AddComplexOperator: { Cr->red=Ar->red+Br->red; Ci->red=Ai->red+Bi->red; Cr->green=Ar->green+Br->green; Ci->green=Ai->green+Bi->green; Cr->blue=Ar->blue+Br->blue; Ci->blue=Ai->blue+Bi->blue; if (images->matte != MagickFalse) { Cr->opacity=Ar->opacity+Br->opacity; Ci->opacity=Ai->opacity+Bi->opacity; } break; } case ConjugateComplexOperator: default: { Cr->red=Ar->red; Ci->red=(-Bi->red); Cr->green=Ar->green; Ci->green=(-Bi->green); Cr->blue=Ar->blue; Ci->blue=(-Bi->blue); if (images->matte != MagickFalse) { Cr->opacity=Ar->opacity; Ci->opacity=(-Bi->opacity); } break; } case DivideComplexOperator: { double gamma; gamma=PerceptibleReciprocal(Br->red*Br->red+Bi->red*Bi->red+snr); Cr->red=gamma*(Ar->red*Br->red+Ai->red*Bi->red); Ci->red=gamma*(Ai->red*Br->red-Ar->red*Bi->red); gamma=PerceptibleReciprocal(Br->green*Br->green+Bi->green*Bi->green+ snr); Cr->green=gamma*(Ar->green*Br->green+Ai->green*Bi->green); Ci->green=gamma*(Ai->green*Br->green-Ar->green*Bi->green); gamma=PerceptibleReciprocal(Br->blue*Br->blue+Bi->blue*Bi->blue+snr); Cr->blue=gamma*(Ar->blue*Br->blue+Ai->blue*Bi->blue); Ci->blue=gamma*(Ai->blue*Br->blue-Ar->blue*Bi->blue); if (images->matte != MagickFalse) { gamma=PerceptibleReciprocal(Br->opacity*Br->opacity+Bi->opacity* Bi->opacity+snr); Cr->opacity=gamma*(Ar->opacity*Br->opacity+Ai->opacity* Bi->opacity); Ci->opacity=gamma*(Ai->opacity*Br->opacity-Ar->opacity* Bi->opacity); } break; } case MagnitudePhaseComplexOperator: { Cr->red=sqrt(Ar->red*Ar->red+Ai->red*Ai->red); Ci->red=atan2(Ai->red,Ar->red)/(2.0*MagickPI)+0.5; Cr->green=sqrt(Ar->green*Ar->green+Ai->green*Ai->green); Ci->green=atan2(Ai->green,Ar->green)/(2.0*MagickPI)+0.5; Cr->blue=sqrt(Ar->blue*Ar->blue+Ai->blue*Ai->blue); Ci->blue=atan2(Ai->blue,Ar->blue)/(2.0*MagickPI)+0.5; if (images->matte != MagickFalse) { Cr->opacity=sqrt(Ar->opacity*Ar->opacity+Ai->opacity*Ai->opacity); Ci->opacity=atan2(Ai->opacity,Ar->opacity)/(2.0*MagickPI)+0.5; } break; } case MultiplyComplexOperator: { Cr->red=QuantumScale*(Ar->red*Br->red-Ai->red*Bi->red); Ci->red=QuantumScale*(Ai->red*Br->red+Ar->red*Bi->red); Cr->green=QuantumScale*(Ar->green*Br->green-Ai->green*Bi->green); Ci->green=QuantumScale*(Ai->green*Br->green+Ar->green*Bi->green); Cr->blue=QuantumScale*(Ar->blue*Br->blue-Ai->blue*Bi->blue); Ci->blue=QuantumScale*(Ai->blue*Br->blue+Ar->blue*Bi->blue); if (images->matte != MagickFalse) { Cr->opacity=QuantumScale*(Ar->opacity*Br->opacity-Ai->opacity* Bi->opacity); Ci->opacity=QuantumScale*(Ai->opacity*Br->opacity+Ar->opacity* Bi->opacity); } break; } case RealImaginaryComplexOperator: { Cr->red=Ar->red*cos(2.0*MagickPI*(Ai->red-0.5)); Ci->red=Ar->red*sin(2.0*MagickPI*(Ai->red-0.5)); Cr->green=Ar->green*cos(2.0*MagickPI*(Ai->green-0.5)); Ci->green=Ar->green*sin(2.0*MagickPI*(Ai->green-0.5)); Cr->blue=Ar->blue*cos(2.0*MagickPI*(Ai->blue-0.5)); Ci->blue=Ar->blue*sin(2.0*MagickPI*(Ai->blue-0.5)); if (images->matte != MagickFalse) { Cr->opacity=Ar->opacity*cos(2.0*MagickPI*(Ai->opacity-0.5)); Ci->opacity=Ar->opacity*sin(2.0*MagickPI*(Ai->opacity-0.5)); } break; } case SubtractComplexOperator: { Cr->red=Ar->red-Br->red; Ci->red=Ai->red-Bi->red; Cr->green=Ar->green-Br->green; Ci->green=Ai->green-Bi->green; Cr->blue=Ar->blue-Br->blue; Ci->blue=Ai->blue-Bi->blue; if (images->matte != MagickFalse) { Cr->opacity=Ar->opacity-Br->opacity; Ci->opacity=Ai->opacity-Bi->opacity; } break; } } Ar++; Ai++; Br++; Bi++; Cr++; Ci++; } if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse) status=MagickFalse; if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows); if (proceed == MagickFalse) status=MagickFalse; } } Cr_view=DestroyCacheView(Cr_view); Ci_view=DestroyCacheView(Ci_view); Br_view=DestroyCacheView(Br_view); Bi_view=DestroyCacheView(Bi_view); Ar_view=DestroyCacheView(Ar_view); Ai_view=DestroyCacheView(Ai_view); if (status == MagickFalse) complex_images=DestroyImageList(complex_images); return(complex_images); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1588 CWE ID: CWE-125
1
18,554
Analyze the following 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 **dbg_userword(struct kmem_cache *cachep, void *objp) { BUG_ON(!(cachep->flags & SLAB_STORE_USER)); return (void **)(objp + cachep->size - BYTES_PER_WORD); } Commit Message: mm/slab.c: fix SLAB freelist randomization duplicate entries This patch fixes a bug in the freelist randomization code. When a high random number is used, the freelist will contain duplicate entries. It will result in different allocations sharing the same chunk. It will result in odd behaviours and crashes. It should be uncommon but it depends on the machines. We saw it happening more often on some machines (every few hours of running tests). Fixes: c7ce4f60ac19 ("mm: SLAB freelist randomization") Link: http://lkml.kernel.org/r/20170103181908.143178-1-thgarnie@google.com Signed-off-by: John Sperbeck <jsperbeck@google.com> Signed-off-by: Thomas Garnier <thgarnie@google.com> Cc: Christoph Lameter <cl@linux.com> Cc: Pekka Enberg <penberg@kernel.org> Cc: David Rientjes <rientjes@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:
0
563
Analyze the following 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 CWebServer::Cmd_GetUserVariable(WebEmSession & session, const request& req, Json::Value &root) { std::string idx = request::findValue(&req, "idx"); if (idx.empty()) return; int iVarID = atoi(idx.c_str()); std::vector<std::vector<std::string> > result; result = m_sql.safe_query("SELECT ID, Name, ValueType, Value, LastUpdate FROM UserVariables WHERE (ID==%d)", iVarID); int ii = 0; for (const auto & itt : result) { std::vector<std::string> sd = itt; root["result"][ii]["idx"] = sd[0]; root["result"][ii]["Name"] = sd[1]; root["result"][ii]["Type"] = sd[2]; root["result"][ii]["Value"] = sd[3]; root["result"][ii]["LastUpdate"] = sd[4]; ii++; } root["status"] = "OK"; root["title"] = "GetUserVariable"; } Commit Message: Fixed possible SQL Injection Vulnerability (Thanks to Fabio Carretto!) CWE ID: CWE-89
0
27,236
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int proc_tgid_base_readdir(struct file *file, struct dir_context *ctx) { return proc_pident_readdir(file, ctx, tgid_base_stuff, ARRAY_SIZE(tgid_base_stuff)); } Commit Message: proc: prevent accessing /proc/<PID>/environ until it's ready If /proc/<PID>/environ gets read before the envp[] array is fully set up in create_{aout,elf,elf_fdpic,flat}_tables(), we might end up trying to read more bytes than are actually written, as env_start will already be set but env_end will still be zero, making the range calculation underflow, allowing to read beyond the end of what has been written. Fix this as it is done for /proc/<PID>/cmdline by testing env_end for zero. It is, apparently, intentionally set last in create_*_tables(). This bug was found by the PaX size_overflow plugin that detected the arithmetic underflow of 'this_len = env_end - (env_start + src)' when env_end is still zero. The expected consequence is that userland trying to access /proc/<PID>/environ of a not yet fully set up process may get inconsistent data as we're in the middle of copying in the environment variables. Fixes: https://forums.grsecurity.net/viewtopic.php?f=3&t=4363 Fixes: https://bugzilla.kernel.org/show_bug.cgi?id=116461 Signed-off-by: Mathias Krause <minipli@googlemail.com> Cc: Emese Revfy <re.emese@gmail.com> Cc: Pax Team <pageexec@freemail.hu> Cc: Al Viro <viro@zeniv.linux.org.uk> Cc: Mateusz Guzik <mguzik@redhat.com> Cc: Alexey Dobriyan <adobriyan@gmail.com> Cc: Cyrill Gorcunov <gorcunov@openvz.org> Cc: Jarod Wilson <jarod@redhat.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-362
0
2,238
Analyze the following 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 filemap_fdatawait(struct address_space *mapping) { loff_t i_size = i_size_read(mapping->host); if (i_size == 0) return 0; return wait_on_page_writeback_range(mapping, 0, (i_size - 1) >> PAGE_CACHE_SHIFT); } Commit Message: fix writev regression: pan hanging unkillable and un-straceable Frederik Himpe reported an unkillable and un-straceable pan process. Zero length iovecs can go into an infinite loop in writev, because the iovec iterator does not always advance over them. The sequence required to trigger this is not trivial. I think it requires that a zero-length iovec be followed by a non-zero-length iovec which causes a pagefault in the atomic usercopy. This causes the writev code to drop back into single-segment copy mode, which then tries to copy the 0 bytes of the zero-length iovec; a zero length copy looks like a failure though, so it loops. Put a test into iov_iter_advance to catch zero-length iovecs. We could just put the test in the fallback path, but I feel it is more robust to skip over zero-length iovecs throughout the code (iovec iterator may be used in filesystems too, so it should be robust). Signed-off-by: Nick Piggin <npiggin@suse.de> Signed-off-by: Ingo Molnar <mingo@elte.hu> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-20
0
20,412
Analyze the following 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 IsImageCursor(gfx::NativeCursor native_cursor) { return cursors_.find(native_cursor.native_type()) != cursors_.end(); } Commit Message: Introduce XGetImage() for GrabWindowSnapshot() in ChromeOS. BUG=119492 TEST=manually done Review URL: https://chromiumcodereview.appspot.com/10386124 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137556 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
0
7,098
Analyze the following 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 skb_unlink(struct sk_buff *skb, struct sk_buff_head *list) { unsigned long flags; spin_lock_irqsave(&list->lock, flags); __skb_unlink(skb, list); spin_unlock_irqrestore(&list->lock, flags); } Commit Message: skbuff: skb_segment: orphan frags before copying skb_segment copies frags around, so we need to copy them carefully to avoid accessing user memory after reporting completion to userspace through a callback. skb_segment doesn't normally happen on datapath: TSO needs to be disabled - so disabling zero copy in this case does not look like a big deal. Signed-off-by: Michael S. Tsirkin <mst@redhat.com> Acked-by: Herbert Xu <herbert@gondor.apana.org.au> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-416
0
7,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: update_title (void) { Behaviour *b = &uzbl.behave; gchar *parsed; if (b->show_status) { if (b->title_format_short) { parsed = expand(b->title_format_short, 0); if (uzbl.gui.main_window) gtk_window_set_title (GTK_WINDOW(uzbl.gui.main_window), parsed); g_free(parsed); } if (b->status_format) { parsed = expand(b->status_format, 0); gtk_label_set_markup(GTK_LABEL(uzbl.gui.mainbar_label), parsed); g_free(parsed); } if (b->status_background) { GdkColor color; gdk_color_parse (b->status_background, &color); if (uzbl.gui.main_window) gtk_widget_modify_bg (uzbl.gui.main_window, GTK_STATE_NORMAL, &color); else if (uzbl.gui.plug) gtk_widget_modify_bg (GTK_WIDGET(uzbl.gui.plug), GTK_STATE_NORMAL, &color); } } else { if (b->title_format_long) { parsed = expand(b->title_format_long, 0); if (uzbl.gui.main_window) gtk_window_set_title (GTK_WINDOW(uzbl.gui.main_window), parsed); g_free(parsed); } } } Commit Message: disable Uzbl javascript object because of security problem. CWE ID: CWE-264
0
10,742
Analyze the following 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 VirtualKeyboardController::OnMaximizeModeEnded() { if (!IsSmartVirtualKeyboardEnabled()) { SetKeyboardEnabled(false); } else { UpdateKeyboardEnabled(); } } Commit Message: Move smart deploy to tristate. BUG= Review URL: https://codereview.chromium.org/1149383006 Cr-Commit-Position: refs/heads/master@{#333058} CWE ID: CWE-399
0
9,152
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: soft_limit_tree_from_page(struct page *page) { int nid = page_to_nid(page); int zid = page_zonenum(page); return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid]; } 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
26,898
Analyze the following 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 MagickBooleanType WriteVIFFImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { #define VFF_CM_genericRGB 15 #define VFF_CM_NONE 0 #define VFF_DEP_IEEEORDER 0x2 #define VFF_DES_RAW 0 #define VFF_LOC_IMPLICIT 1 #define VFF_MAPTYP_NONE 0 #define VFF_MAPTYP_1_BYTE 1 #define VFF_MS_NONE 0 #define VFF_MS_ONEPERBAND 1 #define VFF_TYP_BIT 0 #define VFF_TYP_1_BYTE 1 typedef struct _ViffInfo { char identifier, file_type, release, version, machine_dependency, reserve[3], comment[512]; size_t rows, columns, subrows; int x_offset, y_offset; unsigned int x_bits_per_pixel, y_bits_per_pixel, location_type, location_dimension, number_of_images, number_data_bands, data_storage_type, data_encode_scheme, map_scheme, map_storage_type, map_rows, map_columns, map_subrows, map_enable, maps_per_cycle, color_space_model; } ViffInfo; const char *value; MagickBooleanType status; MagickOffsetType scene; MagickSizeType number_pixels, packets; MemoryInfo *pixel_info; register const Quantum *p; register ssize_t x; register ssize_t i; register unsigned char *q; ssize_t y; unsigned char *pixels; ViffInfo viff_info; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); (void) ResetMagickMemory(&viff_info,0,sizeof(ViffInfo)); scene=0; do { /* Initialize VIFF image structure. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); DisableMSCWarning(4310) viff_info.identifier=(char) 0xab; RestoreMSCWarning viff_info.file_type=1; viff_info.release=1; viff_info.version=3; viff_info.machine_dependency=VFF_DEP_IEEEORDER; /* IEEE byte ordering */ *viff_info.comment='\0'; value=GetImageProperty(image,"comment",exception); if (value != (const char *) NULL) (void) CopyMagickString(viff_info.comment,value,MagickMin(strlen(value), 511)+1); viff_info.rows=image->columns; viff_info.columns=image->rows; viff_info.subrows=0; viff_info.x_offset=(~0); viff_info.y_offset=(~0); viff_info.x_bits_per_pixel=0; viff_info.y_bits_per_pixel=0; viff_info.location_type=VFF_LOC_IMPLICIT; viff_info.location_dimension=0; viff_info.number_of_images=1; viff_info.data_encode_scheme=VFF_DES_RAW; viff_info.map_scheme=VFF_MS_NONE; viff_info.map_storage_type=VFF_MAPTYP_NONE; viff_info.map_rows=0; viff_info.map_columns=0; viff_info.map_subrows=0; viff_info.map_enable=1; /* no colormap */ viff_info.maps_per_cycle=0; number_pixels=(MagickSizeType) image->columns*image->rows; if (image->storage_class == DirectClass) { /* Full color VIFF raster. */ viff_info.number_data_bands=image->alpha_trait ? 4U : 3U; viff_info.color_space_model=VFF_CM_genericRGB; viff_info.data_storage_type=VFF_TYP_1_BYTE; packets=viff_info.number_data_bands*number_pixels; } else { viff_info.number_data_bands=1; viff_info.color_space_model=VFF_CM_NONE; viff_info.data_storage_type=VFF_TYP_1_BYTE; packets=number_pixels; if (SetImageGray(image,exception) == MagickFalse) { /* Colormapped VIFF raster. */ viff_info.map_scheme=VFF_MS_ONEPERBAND; viff_info.map_storage_type=VFF_MAPTYP_1_BYTE; viff_info.map_rows=3; viff_info.map_columns=(unsigned int) image->colors; } else if (image->colors <= 2) { /* Monochrome VIFF raster. */ viff_info.data_storage_type=VFF_TYP_BIT; packets=((image->columns+7) >> 3)*image->rows; } } /* Write VIFF image header (pad to 1024 bytes). */ (void) WriteBlob(image,sizeof(viff_info.identifier),(unsigned char *) &viff_info.identifier); (void) WriteBlob(image,sizeof(viff_info.file_type),(unsigned char *) &viff_info.file_type); (void) WriteBlob(image,sizeof(viff_info.release),(unsigned char *) &viff_info.release); (void) WriteBlob(image,sizeof(viff_info.version),(unsigned char *) &viff_info.version); (void) WriteBlob(image,sizeof(viff_info.machine_dependency), (unsigned char *) &viff_info.machine_dependency); (void) WriteBlob(image,sizeof(viff_info.reserve),(unsigned char *) viff_info.reserve); (void) WriteBlob(image,512,(unsigned char *) viff_info.comment); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.rows); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.columns); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.subrows); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.x_offset); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.y_offset); viff_info.x_bits_per_pixel=(unsigned int) ((63 << 24) | (128 << 16)); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.x_bits_per_pixel); viff_info.y_bits_per_pixel=(unsigned int) ((63 << 24) | (128 << 16)); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.y_bits_per_pixel); (void) WriteBlobMSBLong(image,viff_info.location_type); (void) WriteBlobMSBLong(image,viff_info.location_dimension); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.number_of_images); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.number_data_bands); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.data_storage_type); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.data_encode_scheme); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.map_scheme); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.map_storage_type); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.map_rows); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.map_columns); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.map_subrows); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.map_enable); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.maps_per_cycle); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.color_space_model); for (i=0; i < 420; i++) (void) WriteBlobByte(image,'\0'); /* Convert MIFF to VIFF raster pixels. */ pixel_info=AcquireVirtualMemory((size_t) packets,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); q=pixels; if (image->storage_class == DirectClass) { /* Convert DirectClass packet to VIFF RGB pixel. */ number_pixels=(MagickSizeType) image->columns*image->rows; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q=ScaleQuantumToChar(GetPixelRed(image,p)); *(q+number_pixels)=ScaleQuantumToChar(GetPixelGreen(image,p)); *(q+number_pixels*2)=ScaleQuantumToChar(GetPixelBlue(image,p)); if (image->alpha_trait != UndefinedPixelTrait) *(q+number_pixels*3)=ScaleQuantumToChar((Quantum) (GetPixelAlpha(image,p))); p+=GetPixelChannels(image); q++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else if (SetImageGray(image,exception) == MagickFalse) { unsigned char *viff_colormap; /* Dump colormap to file. */ viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, 3*sizeof(*viff_colormap)); if (viff_colormap == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); q=viff_colormap; for (i=0; i < (ssize_t) image->colors; i++) *q++=ScaleQuantumToChar(image->colormap[i].red); for (i=0; i < (ssize_t) image->colors; i++) *q++=ScaleQuantumToChar(image->colormap[i].green); for (i=0; i < (ssize_t) image->colors; i++) *q++=ScaleQuantumToChar(image->colormap[i].blue); (void) WriteBlob(image,3*image->colors,viff_colormap); viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap); /* Convert PseudoClass packet to VIFF colormapped pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) GetPixelIndex(image,p); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else if (image->colors <= 2) { ssize_t x, y; register unsigned char bit, byte; /* Convert PseudoClass image to a VIFF monochrome image. */ (void) SetImageType(image,BilevelType,exception); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte>>=1; if (GetPixelLuma(image,p) < (QuantumRange/2.0)) byte|=0x80; bit++; if (bit == 8) { *q++=byte; bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) *q++=byte >> (8-bit); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } else { /* Convert PseudoClass packet to VIFF grayscale pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) ClampToQuantum(GetPixelLuma(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } (void) WriteBlob(image,(size_t) packets,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/129 CWE ID: CWE-284
0
62
Analyze the following 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 _yr_emit_inst_arg_uint32( RE_EMIT_CONTEXT* emit_context, uint8_t opcode, uint32_t argument, uint8_t** instruction_addr, uint32_t** argument_addr, size_t* code_size) { FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &opcode, sizeof(uint8_t), (void**) instruction_addr)); FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &argument, sizeof(uint32_t), (void**) argument_addr)); *code_size = sizeof(uint8_t) + sizeof(uint32_t); return ERROR_SUCCESS; } Commit Message: Fix buffer overrun (issue #678). Add assert for detecting this kind of issues earlier. CWE ID: CWE-125
0
9,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: void TestDidNavigate(int page_id, const GURL& url) { ViewHostMsg_FrameNavigate_Params params; InitNavigateParams(&params, page_id, url, content::PAGE_TRANSITION_TYPED); DidNavigate(GetRenderViewHostForTesting(), params); } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
0
20,640
Analyze the following 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 AXObject::isDetached() const { return !m_axObjectCache; } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
0
21,781
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: OMX_ERRORTYPE omx_vdec::free_buffer(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_U32 port, OMX_IN OMX_BUFFERHEADERTYPE* buffer) { OMX_ERRORTYPE eRet = OMX_ErrorNone; unsigned int nPortIndex; (void) hComp; DEBUG_PRINT_LOW("In for decoder free_buffer"); if (m_state == OMX_StateIdle && (BITMASK_PRESENT(&m_flags ,OMX_COMPONENT_LOADING_PENDING))) { DEBUG_PRINT_LOW(" free buffer while Component in Loading pending"); } else if ((m_inp_bEnabled == OMX_FALSE && port == OMX_CORE_INPUT_PORT_INDEX)|| (m_out_bEnabled == OMX_FALSE && port == OMX_CORE_OUTPUT_PORT_INDEX)) { DEBUG_PRINT_LOW("Free Buffer while port %u disabled", (unsigned int)port); } else if ((port == OMX_CORE_INPUT_PORT_INDEX && BITMASK_PRESENT(&m_flags, OMX_COMPONENT_INPUT_ENABLE_PENDING)) || (port == OMX_CORE_OUTPUT_PORT_INDEX && BITMASK_PRESENT(&m_flags, OMX_COMPONENT_OUTPUT_ENABLE_PENDING))) { DEBUG_PRINT_LOW("Free Buffer while port %u enable pending", (unsigned int)port); } else if (m_state == OMX_StateExecuting || m_state == OMX_StatePause) { DEBUG_PRINT_ERROR("Invalid state to free buffer,ports need to be disabled"); post_event(OMX_EventError, OMX_ErrorPortUnpopulated, OMX_COMPONENT_GENERATE_EVENT); return OMX_ErrorIncorrectStateOperation; } else if (m_state != OMX_StateInvalid) { DEBUG_PRINT_ERROR("Invalid state to free buffer,port lost Buffers"); post_event(OMX_EventError, OMX_ErrorPortUnpopulated, OMX_COMPONENT_GENERATE_EVENT); } if (port == OMX_CORE_INPUT_PORT_INDEX) { /*Check if arbitrary bytes*/ if (!arbitrary_bytes && !input_use_buffer) nPortIndex = buffer - m_inp_mem_ptr; else nPortIndex = buffer - m_inp_heap_ptr; DEBUG_PRINT_LOW("free_buffer on i/p port - Port idx %d", nPortIndex); if (nPortIndex < drv_ctx.ip_buf.actualcount) { BITMASK_CLEAR(&m_inp_bm_count,nPortIndex); BITMASK_CLEAR(&m_heap_inp_bm_count,nPortIndex); if (input_use_buffer == true) { DEBUG_PRINT_LOW("Free pmem Buffer index %d",nPortIndex); if (m_phdr_pmem_ptr) free_input_buffer(m_phdr_pmem_ptr[nPortIndex]); } else { if (arbitrary_bytes) { if (m_phdr_pmem_ptr) free_input_buffer(nPortIndex,m_phdr_pmem_ptr[nPortIndex]); else free_input_buffer(nPortIndex,NULL); } else free_input_buffer(buffer); } m_inp_bPopulated = OMX_FALSE; if(release_input_done()) release_buffers(this, VDEC_BUFFER_TYPE_INPUT); /*Free the Buffer Header*/ if (release_input_done()) { DEBUG_PRINT_HIGH("ALL input buffers are freed/released"); free_input_buffer_header(); } } else { DEBUG_PRINT_ERROR("Error: free_buffer ,Port Index Invalid"); eRet = OMX_ErrorBadPortIndex; } if (BITMASK_PRESENT((&m_flags),OMX_COMPONENT_INPUT_DISABLE_PENDING) && release_input_done()) { DEBUG_PRINT_LOW("MOVING TO DISABLED STATE"); BITMASK_CLEAR((&m_flags),OMX_COMPONENT_INPUT_DISABLE_PENDING); post_event(OMX_CommandPortDisable, OMX_CORE_INPUT_PORT_INDEX, OMX_COMPONENT_GENERATE_EVENT); } } else if (port == OMX_CORE_OUTPUT_PORT_INDEX) { nPortIndex = buffer - client_buffers.get_il_buf_hdr(); if (nPortIndex < drv_ctx.op_buf.actualcount) { DEBUG_PRINT_LOW("free_buffer on o/p port - Port idx %d", nPortIndex); BITMASK_CLEAR(&m_out_bm_count,nPortIndex); m_out_bPopulated = OMX_FALSE; client_buffers.free_output_buffer (buffer); if(release_output_done()) { release_buffers(this, VDEC_BUFFER_TYPE_OUTPUT); } if (release_output_done()) { free_output_buffer_header(); } } else { DEBUG_PRINT_ERROR("Error: free_buffer , Port Index Invalid"); eRet = OMX_ErrorBadPortIndex; } if (BITMASK_PRESENT((&m_flags),OMX_COMPONENT_OUTPUT_DISABLE_PENDING) && release_output_done()) { DEBUG_PRINT_LOW("FreeBuffer : If any Disable event pending,post it"); DEBUG_PRINT_LOW("MOVING TO DISABLED STATE"); BITMASK_CLEAR((&m_flags),OMX_COMPONENT_OUTPUT_DISABLE_PENDING); #ifdef _ANDROID_ICS_ if (m_enable_android_native_buffers) { DEBUG_PRINT_LOW("FreeBuffer - outport disabled: reset native buffers"); memset(&native_buffer, 0 ,(sizeof(struct nativebuffer) * MAX_NUM_INPUT_OUTPUT_BUFFERS)); } #endif post_event(OMX_CommandPortDisable, OMX_CORE_OUTPUT_PORT_INDEX, OMX_COMPONENT_GENERATE_EVENT); } } else { eRet = OMX_ErrorBadPortIndex; } if ((eRet == OMX_ErrorNone) && (BITMASK_PRESENT(&m_flags ,OMX_COMPONENT_LOADING_PENDING))) { if (release_done()) { BITMASK_CLEAR((&m_flags),OMX_COMPONENT_LOADING_PENDING); post_event(OMX_CommandStateSet, OMX_StateLoaded, OMX_COMPONENT_GENERATE_EVENT); } } return eRet; } Commit Message: DO NOT MERGE mm-video-v4l2: vidc: validate omx param/config data Check the sanity of config/param strcuture objects passed to get/set _ config()/parameter() methods. Bug: 27533317 Security Vulnerability in MediaServer omx_vdec::get_config() Can lead to arbitrary write Change-Id: I6c3243afe12055ab94f1a1ecf758c10e88231809 Conflicts: mm-core/inc/OMX_QCOMExtns.h mm-video-v4l2/vidc/vdec/src/omx_vdec_msm8974.cpp mm-video-v4l2/vidc/venc/src/omx_video_base.cpp mm-video-v4l2/vidc/venc/src/omx_video_encoder.cpp CWE ID: CWE-20
0
26,220
Analyze the following 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 HTMLFormControlElement::IsDisabledFormControl() const { if (GetDocument().Fetcher()->Archive()) return true; return IsActuallyDisabled(); } Commit Message: autofocus: Fix a crash with an autofocus element in a document without browsing context. ShouldAutofocus() should check existence of the browsing context. Otherwise, doc.TopFrameOrigin() returns null. Before crrev.com/695830, ShouldAutofocus() was called only for rendered elements. That is to say, the document always had browsing context. Bug: 1003228 Change-Id: I2a941c34e9707d44869a6d7585dc7fb9f06e3bf4 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1800902 Commit-Queue: Kent Tamura <tkent@chromium.org> Reviewed-by: Keishi Hattori <keishi@chromium.org> Cr-Commit-Position: refs/heads/master@{#696291} CWE ID: CWE-704
0
20,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: void gdImageCopy (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h) { int c; int x, y; int tox, toy; int i; int colorMap[gdMaxColors]; if (dst->trueColor) { /* 2.0: much easier when the destination is truecolor. */ /* 2.0.10: needs a transparent-index check that is still valid if * the source is not truecolor. Thanks to Frank Warmerdam. */ if (src->trueColor) { for (y = 0; (y < h); y++) { for (x = 0; (x < w); x++) { int c = gdImageGetTrueColorPixel (src, srcX + x, srcY + y); if (c != src->transparent) { gdImageSetPixel (dst, dstX + x, dstY + y, c); } } } } else { /* source is palette based */ for (y = 0; (y < h); y++) { for (x = 0; (x < w); x++) { int c = gdImageGetPixel (src, srcX + x, srcY + y); if (c != src->transparent) { gdImageSetPixel(dst, dstX + x, dstY + y, gdTrueColorAlpha(src->red[c], src->green[c], src->blue[c], src->alpha[c])); } } } } return; } /* Palette based to palette based */ for (i = 0; i < gdMaxColors; i++) { colorMap[i] = (-1); } toy = dstY; for (y = srcY; y < (srcY + h); y++) { tox = dstX; for (x = srcX; x < (srcX + w); x++) { int nc; int mapTo; c = gdImageGetPixel (src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent (src) == c) { tox++; continue; } /* Have we established a mapping for this color? */ if (src->trueColor) { /* 2.05: remap to the palette available in the destination image. This is slow and * works badly, but it beats crashing! Thanks to Padhrig McCarthy. */ mapTo = gdImageColorResolveAlpha (dst, gdTrueColorGetRed (c), gdTrueColorGetGreen (c), gdTrueColorGetBlue (c), gdTrueColorGetAlpha (c)); } else if (colorMap[c] == (-1)) { /* If it's the same image, mapping is trivial */ if (dst == src) { nc = c; } else { /* Get best match possible. This function never returns error. */ nc = gdImageColorResolveAlpha (dst, src->red[c], src->green[c], src->blue[c], src->alpha[c]); } colorMap[c] = nc; mapTo = colorMap[c]; } else { mapTo = colorMap[c]; } gdImageSetPixel (dst, tox, toy, mapTo); tox++; } toy++; } } Commit Message: Fix #72696: imagefilltoborder stackoverflow on truecolor images We must not allow negative color values be passed to gdImageFillToBorder(), because that can lead to infinite recursion since the recursion termination condition will not necessarily be met. CWE ID: CWE-119
0
25,953
Analyze the following 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 ZIPARCHIVE_METHOD(setArchiveComment) { struct zip *intern; zval *self = getThis(); size_t comment_len; char * comment; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &comment, &comment_len) == FAILURE) { return; } if (zip_set_archive_comment(intern, (const char *)comment, (int)comment_len)) { RETURN_FALSE; } else { RETURN_TRUE; } } Commit Message: Fix bug #71923 - integer overflow in ZipArchive::getFrom* CWE ID: CWE-190
0
18,676
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: FoFiType1C::~FoFiType1C() { int i; if (name) { delete name; } if (encoding && encoding != fofiType1StandardEncoding && encoding != fofiType1ExpertEncoding) { for (i = 0; i < 256; ++i) { gfree(encoding[i]); } gfree(encoding); } if (privateDicts) { gfree(privateDicts); } if (fdSelect) { gfree(fdSelect); } if (charset && charset != fofiType1CISOAdobeCharset && charset != fofiType1CExpertCharset && charset != fofiType1CExpertSubsetCharset) { gfree(charset); } } Commit Message: CWE ID: CWE-125
0
6,573
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int mboxlist_do_find(struct find_rock *rock, const strarray_t *patterns) { const char *userid = rock->userid; int isadmin = rock->isadmin; int crossdomains = config_getswitch(IMAPOPT_CROSSDOMAINS); char inbox[MAX_MAILBOX_BUFFER]; size_t inboxlen = 0; size_t prefixlen, len; size_t domainlen = 0; size_t userlen = userid ? strlen(userid) : 0; char domainpat[MAX_MAILBOX_BUFFER]; /* do intra-domain fetches only */ char commonpat[MAX_MAILBOX_BUFFER]; int r = 0; int i; const char *p; if (patterns->count < 1) return 0; /* nothing to do */ for (i = 0; i < patterns->count; i++) { glob *g = glob_init(strarray_nth(patterns, i), rock->namespace->hier_sep); ptrarray_append(&rock->globs, g); } if (config_virtdomains && userid && (p = strchr(userid, '@'))) { userlen = p - userid; domainlen = strlen(p); /* includes separator */ snprintf(domainpat, sizeof(domainpat), "%s!", p+1); } else domainpat[0] = '\0'; /* calculate the inbox (with trailing .INBOX. for later use) */ if (userid && (!(p = strchr(userid, rock->namespace->hier_sep)) || ((p - userid) > (int)userlen)) && strlen(userid)+7 < MAX_MAILBOX_BUFFER) { char *t, *tmpuser = NULL; const char *inboxuser; if (domainlen) snprintf(inbox, sizeof(inbox), "%s!", userid+userlen+1); if (rock->namespace->hier_sep == '/' && (p = strchr(userid, '.'))) { tmpuser = xmalloc(userlen); memcpy(tmpuser, userid, userlen); t = tmpuser + (p - userid); while(t < (tmpuser + userlen)) { if (*t == '.') *t = '^'; t++; } inboxuser = tmpuser; } else inboxuser = userid; snprintf(inbox+domainlen, sizeof(inbox)-domainlen, "user.%.*s.INBOX.", (int)userlen, inboxuser); free(tmpuser); inboxlen = strlen(inbox) - 7; } else { userid = 0; } /* Find the common search prefix of all patterns */ const char *firstpat = strarray_nth(patterns, 0); for (prefixlen = 0; firstpat[prefixlen]; prefixlen++) { if (prefixlen >= MAX_MAILBOX_NAME) { r = IMAP_MAILBOX_BADNAME; goto done; } char c = firstpat[prefixlen]; for (i = 1; i < patterns->count; i++) { const char *pat = strarray_nth(patterns, i); if (pat[prefixlen] != c) break; } if (i < patterns->count) break; if (c == '*' || c == '%' || c == '?') break; commonpat[prefixlen] = c; } commonpat[prefixlen] = '\0'; if (patterns->count == 1) { /* Skip pattern which matches shared namespace prefix */ if (!strcmp(firstpat+prefixlen, "%")) rock->singlepercent = 2; /* output prefix regardless */ if (!strcmp(firstpat+prefixlen, "*%")) rock->singlepercent = 1; } /* * Personal (INBOX) namespace (only if not admin) */ if (userid && !isadmin) { /* first the INBOX */ rock->mb_category = MBNAME_INBOX; r = cyrusdb_forone(rock->db, inbox, inboxlen, &find_p, &find_cb, rock, NULL); if (r == CYRUSDB_DONE) r = 0; if (r) goto done; if (rock->namespace->isalt) { /* do exact INBOX subs before resetting the namebuffer */ rock->mb_category = MBNAME_INBOXSUB; r = cyrusdb_foreach(rock->db, inbox, inboxlen+7, &find_p, &find_cb, rock, NULL); if (r == CYRUSDB_DONE) r = 0; if (r) goto done; /* reset the the namebuffer */ r = (*rock->proc)(NULL, rock->procrock); if (r) goto done; } /* iterate through all the mailboxes under the user's inbox */ rock->mb_category = MBNAME_OWNER; r = cyrusdb_foreach(rock->db, inbox, inboxlen+1, &find_p, &find_cb, rock, NULL); if (r == CYRUSDB_DONE) r = 0; if (r) goto done; /* "Alt Prefix" folders */ if (rock->namespace->isalt) { /* reset the the namebuffer */ r = (*rock->proc)(NULL, rock->procrock); if (r) goto done; rock->mb_category = MBNAME_ALTINBOX; /* special case user.foo.INBOX. If we're singlepercent == 2, this could return DONE, in which case we don't need to foreach the rest of the altprefix space */ r = cyrusdb_forone(rock->db, inbox, inboxlen+6, &find_p, &find_cb, rock, NULL); if (r == CYRUSDB_DONE) goto skipalt; if (r) goto done; /* special case any other altprefix stuff */ rock->mb_category = MBNAME_ALTPREFIX; r = cyrusdb_foreach(rock->db, inbox, inboxlen+1, &find_p, &find_cb, rock, NULL); skipalt: /* we got a done, so skip out of the foreach early */ if (r == CYRUSDB_DONE) r = 0; if (r) goto done; } } /* * Other Users namespace * * If "Other Users*" can match pattern, search for those mailboxes next */ if (isadmin || rock->namespace->accessible[NAMESPACE_USER]) { len = strlen(rock->namespace->prefix[NAMESPACE_USER]); if (len) len--; // trailing separator if (!strncmp(rock->namespace->prefix[NAMESPACE_USER], commonpat, MIN(len, prefixlen))) { if (prefixlen < len) { /* we match all users */ strlcpy(domainpat+domainlen, "user.", sizeof(domainpat)-domainlen); } else { /* just those in this prefix */ strlcpy(domainpat+domainlen, "user.", sizeof(domainpat)-domainlen); strlcpy(domainpat+domainlen+5, commonpat+len+1, sizeof(domainpat)-domainlen-5); } rock->mb_category = MBNAME_OTHERUSER; /* because of how domains work, with crossdomains or admin you can't prefix at all :( */ size_t thislen = (isadmin || crossdomains) ? 0 : strlen(domainpat); /* reset the the namebuffer */ r = (*rock->proc)(NULL, rock->procrock); if (r) goto done; r = mboxlist_find_category(rock, domainpat, thislen); if (r) goto done; } } /* * Shared namespace * * search for all remaining mailboxes. * just bother looking at the ones that have the same pattern prefix. */ if (isadmin || rock->namespace->accessible[NAMESPACE_SHARED]) { len = strlen(rock->namespace->prefix[NAMESPACE_SHARED]); if (len) len--; // trailing separator if (!strncmp(rock->namespace->prefix[NAMESPACE_SHARED], commonpat, MIN(len, prefixlen))) { rock->mb_category = MBNAME_SHARED; /* reset the the namebuffer */ r = (*rock->proc)(NULL, rock->procrock); if (r) goto done; /* iterate through all the non-user folders on the server */ r = mboxlist_find_category(rock, domainpat, domainlen); if (r) goto done; } } /* finish with a reset call always */ r = (*rock->proc)(NULL, rock->procrock); done: for (i = 0; i < rock->globs.count; i++) { glob *g = ptrarray_nth(&rock->globs, i); glob_free(&g); } ptrarray_fini(&rock->globs); return r; } Commit Message: mboxlist: fix uninitialised memory use where pattern is "Other Users" CWE ID: CWE-20
1
29,535
Analyze the following 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 UserSelectionScreen::Hide() {} Commit Message: cros: Check initial auth type when showing views login. Bug: 859611 Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058 Reviewed-on: https://chromium-review.googlesource.com/1123056 Reviewed-by: Xiaoyin Hu <xiaoyinh@chromium.org> Commit-Queue: Jacob Dufault <jdufault@chromium.org> Cr-Commit-Position: refs/heads/master@{#572224} CWE ID:
0
27,921
Analyze the following 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 AppShortcutManager::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { registry->RegisterBooleanPref( prefs::kAppShortcutsHaveBeenCreated, false, user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); } 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
28,225
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void GpuCommandBufferStub::SendConsoleMessage( int32 id, const std::string& message) { GPUCommandBufferConsoleMessage console_message; console_message.id = id; console_message.message = message; IPC::Message* msg = new GpuCommandBufferMsg_ConsoleMsg( route_id_, console_message); msg->set_unblock(true); Send(msg); } 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
4,858
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: apr_status_t h2_session_process(h2_session *session, int async) { apr_status_t status = APR_SUCCESS; conn_rec *c = session->c; int rv, mpm_state, trace = APLOGctrace3(c); if (trace) { ap_log_cerror( APLOG_MARK, APLOG_TRACE3, status, c, "h2_session(%ld): process start, async=%d", session->id, async); } if (c->cs) { c->cs->state = CONN_STATE_WRITE_COMPLETION; } while (session->state != H2_SESSION_ST_DONE) { trace = APLOGctrace3(c); session->have_read = session->have_written = 0; if (session->local.accepting && !ap_mpm_query(AP_MPMQ_MPM_STATE, &mpm_state)) { if (mpm_state == AP_MPMQ_STOPPING) { dispatch_event(session, H2_SESSION_EV_MPM_STOPPING, 0, NULL); } } session->status[0] = '\0'; switch (session->state) { case H2_SESSION_ST_INIT: ap_update_child_status_from_conn(c->sbh, SERVER_BUSY_READ, c); if (!h2_is_acceptable_connection(c, 1)) { update_child_status(session, SERVER_BUSY_READ, "inadequate security"); h2_session_shutdown(session, NGHTTP2_INADEQUATE_SECURITY, NULL, 1); } else { update_child_status(session, SERVER_BUSY_READ, "init"); status = h2_session_start(session, &rv); ap_log_cerror(APLOG_MARK, APLOG_DEBUG, status, c, APLOGNO(03079) "h2_session(%ld): started on %s:%d", session->id, session->s->server_hostname, c->local_addr->port); if (status != APR_SUCCESS) { dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, NULL); } dispatch_event(session, H2_SESSION_EV_INIT, 0, NULL); } break; case H2_SESSION_ST_IDLE: /* make certain, we send everything before we idle */ h2_conn_io_flush(&session->io); if (!session->keep_sync_until && async && !session->open_streams && !session->r && session->remote.emitted_count) { if (trace) { ap_log_cerror( APLOG_MARK, APLOG_TRACE3, status, c, "h2_session(%ld): async idle, nonblock read, " "%d streams open", session->id, session->open_streams); } /* We do not return to the async mpm immediately, since under * load, mpms show the tendency to throw keep_alive connections * away very rapidly. * So, if we are still processing streams, we wait for the * normal timeout first and, on timeout, close. * If we have no streams, we still wait a short amount of * time here for the next frame to arrive, before handing * it to keep_alive processing of the mpm. */ status = h2_session_read(session, 0); if (status == APR_SUCCESS) { session->have_read = 1; dispatch_event(session, H2_SESSION_EV_DATA_READ, 0, NULL); } else if (APR_STATUS_IS_EAGAIN(status) || APR_STATUS_IS_TIMEUP(status)) { if (apr_time_now() > session->idle_until) { dispatch_event(session, H2_SESSION_EV_CONN_TIMEOUT, 0, NULL); } else { status = APR_EAGAIN; goto out; } } else { ap_log_cerror( APLOG_MARK, APLOG_DEBUG, status, c, APLOGNO(03403) "h2_session(%ld): idle, no data, error", session->id); dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, "timeout"); } } else { if (trace) { ap_log_cerror( APLOG_MARK, APLOG_TRACE3, status, c, "h2_session(%ld): sync idle, stutter 1-sec, " "%d streams open", session->id, session->open_streams); } /* We wait in smaller increments, using a 1 second timeout. * That gives us the chance to check for MPMQ_STOPPING often. */ status = h2_mplx_idle(session->mplx); if (status != APR_SUCCESS) { dispatch_event(session, H2_SESSION_EV_CONN_ERROR, H2_ERR_ENHANCE_YOUR_CALM, "less is more"); } h2_filter_cin_timeout_set(session->cin, apr_time_from_sec(1)); status = h2_session_read(session, 1); if (status == APR_SUCCESS) { session->have_read = 1; dispatch_event(session, H2_SESSION_EV_DATA_READ, 0, NULL); } else if (status == APR_EAGAIN) { /* nothing to read */ } else if (APR_STATUS_IS_TIMEUP(status)) { apr_time_t now = apr_time_now(); if (now > session->keep_sync_until) { /* if we are on an async mpm, now is the time that * we may dare to pass control to it. */ session->keep_sync_until = 0; } if (now > session->idle_until) { if (trace) { ap_log_cerror( APLOG_MARK, APLOG_TRACE3, status, c, "h2_session(%ld): keepalive timeout", session->id); } dispatch_event(session, H2_SESSION_EV_CONN_TIMEOUT, 0, "timeout"); } else if (trace) { ap_log_cerror( APLOG_MARK, APLOG_TRACE3, status, c, "h2_session(%ld): keepalive, %f sec left", session->id, (session->idle_until - now) / 1000000.0f); } /* continue reading handling */ } else if (APR_STATUS_IS_ECONNABORTED(status) || APR_STATUS_IS_ECONNRESET(status) || APR_STATUS_IS_EOF(status) || APR_STATUS_IS_EBADF(status)) { ap_log_cerror( APLOG_MARK, APLOG_TRACE3, status, c, "h2_session(%ld): input gone", session->id); dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, NULL); } else { ap_log_cerror( APLOG_MARK, APLOG_TRACE3, status, c, "h2_session(%ld): idle(1 sec timeout) " "read failed", session->id); dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, "error"); } } break; case H2_SESSION_ST_BUSY: if (nghttp2_session_want_read(session->ngh2)) { ap_update_child_status(session->c->sbh, SERVER_BUSY_READ, NULL); h2_filter_cin_timeout_set(session->cin, session->s->timeout); status = h2_session_read(session, 0); if (status == APR_SUCCESS) { session->have_read = 1; dispatch_event(session, H2_SESSION_EV_DATA_READ, 0, NULL); } else if (status == APR_EAGAIN) { /* nothing to read */ } else if (APR_STATUS_IS_TIMEUP(status)) { dispatch_event(session, H2_SESSION_EV_CONN_TIMEOUT, 0, NULL); break; } else { dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, NULL); } } /* trigger window updates, stream resumes and submits */ status = h2_mplx_dispatch_master_events(session->mplx, on_stream_resume, session); if (status != APR_SUCCESS) { ap_log_cerror(APLOG_MARK, APLOG_TRACE3, status, c, "h2_session(%ld): dispatch error", session->id); dispatch_event(session, H2_SESSION_EV_CONN_ERROR, H2_ERR_INTERNAL_ERROR, "dispatch error"); break; } if (nghttp2_session_want_write(session->ngh2)) { ap_update_child_status(session->c->sbh, SERVER_BUSY_WRITE, NULL); status = h2_session_send(session); if (status != APR_SUCCESS) { dispatch_event(session, H2_SESSION_EV_CONN_ERROR, H2_ERR_INTERNAL_ERROR, "writing"); break; } } if (session->have_read || session->have_written) { if (session->wait_us) { session->wait_us = 0; } } else if (!nghttp2_session_want_write(session->ngh2)) { dispatch_event(session, H2_SESSION_EV_NO_IO, 0, NULL); } break; case H2_SESSION_ST_WAIT: if (session->wait_us <= 0) { session->wait_us = 10; if (h2_conn_io_flush(&session->io) != APR_SUCCESS) { dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, NULL); break; } } else { /* repeating, increase timer for graceful backoff */ session->wait_us = H2MIN(session->wait_us*2, MAX_WAIT_MICROS); } if (trace) { ap_log_cerror(APLOG_MARK, APLOG_TRACE3, 0, c, "h2_session: wait for data, %ld micros", (long)session->wait_us); } status = h2_mplx_out_trywait(session->mplx, session->wait_us, session->iowait); if (status == APR_SUCCESS) { session->wait_us = 0; dispatch_event(session, H2_SESSION_EV_DATA_READ, 0, NULL); } else if (APR_STATUS_IS_TIMEUP(status)) { /* go back to checking all inputs again */ transit(session, "wait cycle", session->local.accepting? H2_SESSION_ST_BUSY : H2_SESSION_ST_DONE); } else if (APR_STATUS_IS_ECONNRESET(status) || APR_STATUS_IS_ECONNABORTED(status)) { dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, NULL); } else { ap_log_cerror(APLOG_MARK, APLOG_WARNING, status, c, APLOGNO(03404) "h2_session(%ld): waiting on conditional", session->id); h2_session_shutdown(session, H2_ERR_INTERNAL_ERROR, "cond wait error", 0); } break; default: ap_log_cerror(APLOG_MARK, APLOG_ERR, APR_EGENERAL, c, APLOGNO(03080) "h2_session(%ld): unknown state %d", session->id, session->state); dispatch_event(session, H2_SESSION_EV_PROTO_ERROR, 0, NULL); break; } if (!nghttp2_session_want_read(session->ngh2) && !nghttp2_session_want_write(session->ngh2)) { dispatch_event(session, H2_SESSION_EV_NGH2_DONE, 0, NULL); } if (session->reprioritize) { h2_mplx_reprioritize(session->mplx, stream_pri_cmp, session); session->reprioritize = 0; } } out: if (trace) { ap_log_cerror( APLOG_MARK, APLOG_TRACE3, status, c, "h2_session(%ld): [%s] process returns", session->id, state_name(session->state)); } if ((session->state != H2_SESSION_ST_DONE) && (APR_STATUS_IS_EOF(status) || APR_STATUS_IS_ECONNRESET(status) || APR_STATUS_IS_ECONNABORTED(status))) { dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, NULL); } status = APR_SUCCESS; if (session->state == H2_SESSION_ST_DONE) { status = APR_EOF; if (!session->eoc_written) { session->eoc_written = 1; h2_conn_io_write_eoc(&session->io, session); } } return status; } Commit Message: SECURITY: CVE-2016-8740 mod_http2: properly crafted, endless HTTP/2 CONTINUATION frames could be used to exhaust all server's memory. Reported by: Naveen Tiwari <naveen.tiwari@asu.edu> and CDF/SEFCOM at Arizona State University git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1772576 13f79535-47bb-0310-9956-ffa450edef68 CWE ID: CWE-20
0
1,283
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void PDFiumEngine::SearchUsingICU(const base::string16& term, bool case_sensitive, bool first_search, int character_to_start_searching_from, int current_page) { base::string16 page_text; int text_length = pages_[current_page]->GetCharCount(); if (character_to_start_searching_from) { text_length -= character_to_start_searching_from; } else if (!first_search && last_character_index_to_search_ != -1 && current_page == last_page_to_search_) { text_length = last_character_index_to_search_; } if (text_length <= 0) return; PDFiumAPIStringBufferAdapter<base::string16> api_string_adapter(&page_text, text_length, false); unsigned short* data = reinterpret_cast<unsigned short*>(api_string_adapter.GetData()); int written = FPDFText_GetText(pages_[current_page]->GetTextPage(), character_to_start_searching_from, text_length, data); api_string_adapter.Close(written); std::vector<PDFEngine::Client::SearchStringResult> results; client_->SearchString( page_text.c_str(), term.c_str(), case_sensitive, &results); for (const auto& result : results) { int temp_start = result.start_index + character_to_start_searching_from; int start = FPDFText_GetCharIndexFromTextIndex( pages_[current_page]->GetTextPage(), temp_start); int end = FPDFText_GetCharIndexFromTextIndex( pages_[current_page]->GetTextPage(), temp_start + result.length); AddFindResult(PDFiumRange(pages_[current_page], start, end - start)); } } Commit Message: [pdf] Defer page unloading in JS callback. One of the callbacks from PDFium JavaScript into the embedder is to get the current page number. In Chromium, this will trigger a call to CalculateMostVisiblePage that method will determine the visible pages and unload any non-visible pages. But, if the originating JS is on a non-visible page we'll delete the page and annotations associated with that page. This will cause issues as we are currently working with those objects when the JavaScript returns. This Cl defers the page unloading triggered by getting the most visible page until the next event is handled by the Chromium embedder. BUG=chromium:653090 Review-Url: https://codereview.chromium.org/2418533002 Cr-Commit-Position: refs/heads/master@{#424781} CWE ID: CWE-416
0
26,291
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: MediaPlayerService::~MediaPlayerService() { ALOGV("MediaPlayerService destroyed"); } Commit Message: MediaPlayerService: avoid invalid static cast Bug: 30204103 Change-Id: Ie0dd3568a375f1e9fed8615ad3d85184bcc99028 (cherry picked from commit ee0a0e39acdcf8f97e0d6945c31ff36a06a36e9d) CWE ID: CWE-264
0
7,849
Analyze the following 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 tg3_mdio_config_5785(struct tg3 *tp) { u32 val; struct phy_device *phydev; phydev = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR]; switch (phydev->drv->phy_id & phydev->drv->phy_id_mask) { case PHY_ID_BCM50610: case PHY_ID_BCM50610M: val = MAC_PHYCFG2_50610_LED_MODES; break; case PHY_ID_BCMAC131: val = MAC_PHYCFG2_AC131_LED_MODES; break; case PHY_ID_RTL8211C: val = MAC_PHYCFG2_RTL8211C_LED_MODES; break; case PHY_ID_RTL8201E: val = MAC_PHYCFG2_RTL8201E_LED_MODES; break; default: return; } if (phydev->interface != PHY_INTERFACE_MODE_RGMII) { tw32(MAC_PHYCFG2, val); val = tr32(MAC_PHYCFG1); val &= ~(MAC_PHYCFG1_RGMII_INT | MAC_PHYCFG1_RXCLK_TO_MASK | MAC_PHYCFG1_TXCLK_TO_MASK); val |= MAC_PHYCFG1_RXCLK_TIMEOUT | MAC_PHYCFG1_TXCLK_TIMEOUT; tw32(MAC_PHYCFG1, val); return; } if (!tg3_flag(tp, RGMII_INBAND_DISABLE)) val |= MAC_PHYCFG2_EMODE_MASK_MASK | MAC_PHYCFG2_FMODE_MASK_MASK | MAC_PHYCFG2_GMODE_MASK_MASK | MAC_PHYCFG2_ACT_MASK_MASK | MAC_PHYCFG2_QUAL_MASK_MASK | MAC_PHYCFG2_INBAND_ENABLE; tw32(MAC_PHYCFG2, val); val = tr32(MAC_PHYCFG1); val &= ~(MAC_PHYCFG1_RXCLK_TO_MASK | MAC_PHYCFG1_TXCLK_TO_MASK | MAC_PHYCFG1_RGMII_EXT_RX_DEC | MAC_PHYCFG1_RGMII_SND_STAT_EN); if (!tg3_flag(tp, RGMII_INBAND_DISABLE)) { if (tg3_flag(tp, RGMII_EXT_IBND_RX_EN)) val |= MAC_PHYCFG1_RGMII_EXT_RX_DEC; if (tg3_flag(tp, RGMII_EXT_IBND_TX_EN)) val |= MAC_PHYCFG1_RGMII_SND_STAT_EN; } val |= MAC_PHYCFG1_RXCLK_TIMEOUT | MAC_PHYCFG1_TXCLK_TIMEOUT | MAC_PHYCFG1_RGMII_INT | MAC_PHYCFG1_TXC_DRV; tw32(MAC_PHYCFG1, val); val = tr32(MAC_EXT_RGMII_MODE); val &= ~(MAC_RGMII_MODE_RX_INT_B | MAC_RGMII_MODE_RX_QUALITY | MAC_RGMII_MODE_RX_ACTIVITY | MAC_RGMII_MODE_RX_ENG_DET | MAC_RGMII_MODE_TX_ENABLE | MAC_RGMII_MODE_TX_LOWPWR | MAC_RGMII_MODE_TX_RESET); if (!tg3_flag(tp, RGMII_INBAND_DISABLE)) { if (tg3_flag(tp, RGMII_EXT_IBND_RX_EN)) val |= MAC_RGMII_MODE_RX_INT_B | MAC_RGMII_MODE_RX_QUALITY | MAC_RGMII_MODE_RX_ACTIVITY | MAC_RGMII_MODE_RX_ENG_DET; if (tg3_flag(tp, RGMII_EXT_IBND_TX_EN)) val |= MAC_RGMII_MODE_TX_ENABLE | MAC_RGMII_MODE_TX_LOWPWR | MAC_RGMII_MODE_TX_RESET; } tw32(MAC_EXT_RGMII_MODE, val); } Commit Message: tg3: fix length overflow in VPD firmware parsing Commit 184b89044fb6e2a74611dafa69b1dce0d98612c6 ("tg3: Use VPD fw version when present") introduced VPD parsing that contained a potential length overflow. Limit the hardware's reported firmware string length (max 255 bytes) to stay inside the driver's firmware string length (32 bytes). On overflow, truncate the formatted firmware string instead of potentially overwriting portions of the tg3 struct. http://cansecwest.com/slides/2013/PrivateCore%20CSW%202013.pdf Signed-off-by: Kees Cook <keescook@chromium.org> Reported-by: Oded Horovitz <oded@privatecore.com> Reported-by: Brad Spengler <spender@grsecurity.net> Cc: stable@vger.kernel.org Cc: Matt Carlson <mcarlson@broadcom.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-119
0
8,083
Analyze the following 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 netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask, u16 index) { struct xps_dev_maps *dev_maps, *new_dev_maps = NULL; int i, cpu, tci, numa_node_id = -2; int maps_sz, num_tc = 1, tc = 0; struct xps_map *map, *new_map; bool active = false; if (dev->num_tc) { num_tc = dev->num_tc; tc = netdev_txq_to_tc(dev, index); if (tc < 0) return -EINVAL; } maps_sz = XPS_DEV_MAPS_SIZE(num_tc); if (maps_sz < L1_CACHE_BYTES) maps_sz = L1_CACHE_BYTES; mutex_lock(&xps_map_mutex); dev_maps = xmap_dereference(dev->xps_maps); /* allocate memory for queue storage */ for_each_cpu_and(cpu, cpu_online_mask, mask) { if (!new_dev_maps) new_dev_maps = kzalloc(maps_sz, GFP_KERNEL); if (!new_dev_maps) { mutex_unlock(&xps_map_mutex); return -ENOMEM; } tci = cpu * num_tc + tc; map = dev_maps ? xmap_dereference(dev_maps->cpu_map[tci]) : NULL; map = expand_xps_map(map, cpu, index); if (!map) goto error; RCU_INIT_POINTER(new_dev_maps->cpu_map[tci], map); } if (!new_dev_maps) goto out_no_new_maps; for_each_possible_cpu(cpu) { /* copy maps belonging to foreign traffic classes */ for (i = tc, tci = cpu * num_tc; dev_maps && i--; tci++) { /* fill in the new device map from the old device map */ map = xmap_dereference(dev_maps->cpu_map[tci]); RCU_INIT_POINTER(new_dev_maps->cpu_map[tci], map); } /* We need to explicitly update tci as prevous loop * could break out early if dev_maps is NULL. */ tci = cpu * num_tc + tc; if (cpumask_test_cpu(cpu, mask) && cpu_online(cpu)) { /* add queue to CPU maps */ int pos = 0; map = xmap_dereference(new_dev_maps->cpu_map[tci]); while ((pos < map->len) && (map->queues[pos] != index)) pos++; if (pos == map->len) map->queues[map->len++] = index; #ifdef CONFIG_NUMA if (numa_node_id == -2) numa_node_id = cpu_to_node(cpu); else if (numa_node_id != cpu_to_node(cpu)) numa_node_id = -1; #endif } else if (dev_maps) { /* fill in the new device map from the old device map */ map = xmap_dereference(dev_maps->cpu_map[tci]); RCU_INIT_POINTER(new_dev_maps->cpu_map[tci], map); } /* copy maps belonging to foreign traffic classes */ for (i = num_tc - tc, tci++; dev_maps && --i; tci++) { /* fill in the new device map from the old device map */ map = xmap_dereference(dev_maps->cpu_map[tci]); RCU_INIT_POINTER(new_dev_maps->cpu_map[tci], map); } } rcu_assign_pointer(dev->xps_maps, new_dev_maps); /* Cleanup old maps */ if (!dev_maps) goto out_no_old_maps; for_each_possible_cpu(cpu) { for (i = num_tc, tci = cpu * num_tc; i--; tci++) { new_map = xmap_dereference(new_dev_maps->cpu_map[tci]); map = xmap_dereference(dev_maps->cpu_map[tci]); if (map && map != new_map) kfree_rcu(map, rcu); } } kfree_rcu(dev_maps, rcu); out_no_old_maps: dev_maps = new_dev_maps; active = true; out_no_new_maps: /* update Tx queue numa node */ netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index), (numa_node_id >= 0) ? numa_node_id : NUMA_NO_NODE); if (!dev_maps) goto out_no_maps; /* removes queue from unused CPUs */ for_each_possible_cpu(cpu) { for (i = tc, tci = cpu * num_tc; i--; tci++) active |= remove_xps_queue(dev_maps, tci, index); if (!cpumask_test_cpu(cpu, mask) || !cpu_online(cpu)) active |= remove_xps_queue(dev_maps, tci, index); for (i = num_tc - tc, tci++; --i; tci++) active |= remove_xps_queue(dev_maps, tci, index); } /* free map if not active */ if (!active) { RCU_INIT_POINTER(dev->xps_maps, NULL); kfree_rcu(dev_maps, rcu); } out_no_maps: mutex_unlock(&xps_map_mutex); return 0; error: /* remove any maps that we added */ for_each_possible_cpu(cpu) { for (i = num_tc, tci = cpu * num_tc; i--; tci++) { new_map = xmap_dereference(new_dev_maps->cpu_map[tci]); map = dev_maps ? xmap_dereference(dev_maps->cpu_map[tci]) : NULL; if (new_map && new_map != map) kfree(new_map); } } mutex_unlock(&xps_map_mutex); kfree(new_dev_maps); return -ENOMEM; } 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
24,167
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: SProcRenderCreateLinearGradient(ClientPtr client) { int len; REQUEST(xRenderCreateLinearGradientReq); REQUEST_AT_LEAST_SIZE(xRenderCreateLinearGradientReq); swaps(&stuff->length); swapl(&stuff->pid); swapl(&stuff->p1.x); swapl(&stuff->p1.y); swapl(&stuff->p2.x); swapl(&stuff->p2.y); swapl(&stuff->nStops); len = (client->req_len << 2) - sizeof(xRenderCreateLinearGradientReq); if (stuff->nStops > UINT32_MAX / (sizeof(xFixed) + sizeof(xRenderColor))) return BadLength; if (len != stuff->nStops * (sizeof(xFixed) + sizeof(xRenderColor))) return BadLength; swapStops(stuff + 1, stuff->nStops); return (*ProcRenderVector[stuff->renderReqType]) (client); } Commit Message: CWE ID: CWE-20
0
7,797
Analyze the following 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 DoReleaseShaderCompiler() { } Commit Message: Revert "Revert 100494 - Fix bug in SimulateAttrib0.""" TEST=none BUG=95625 TBR=apatrick@chromium.org Review URL: http://codereview.chromium.org/7796016 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@100507 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
0
6,743
Analyze the following 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 InspectorController::willBeDestroyed() { disconnectFrontend(); m_injectedScriptManager->disconnect(); m_inspectorClient = 0; m_page = 0; m_instrumentingAgents->reset(); m_agents.discardAgents(); } Commit Message: [4/4] Process clearBrowserCahce/cookies commands in browser. BUG=366585 Review URL: https://codereview.chromium.org/251183005 git-svn-id: svn://svn.chromium.org/blink/trunk@172984 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
0
4,441
Analyze the following 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 sas_suspend_sata(struct asd_sas_port *port) { struct domain_device *dev; mutex_lock(&port->ha->disco_mutex); list_for_each_entry(dev, &port->dev_list, dev_list_node) { struct sata_device *sata; if (!dev_is_sata(dev)) continue; sata = &dev->sata_dev; if (sata->ap->pm_mesg.event == PM_EVENT_SUSPEND) continue; ata_sas_port_suspend(sata->ap); } mutex_unlock(&port->ha->disco_mutex); sas_ata_flush_pm_eh(port, __func__); } Commit Message: scsi: libsas: direct call probe and destruct In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery competing with ata error handling") introduced disco mutex to prevent rediscovery competing with ata error handling and put the whole revalidation in the mutex. But the rphy add/remove needs to wait for the error handling which also grabs the disco mutex. This may leads to dead lock.So the probe and destruct event were introduce to do the rphy add/remove asynchronously and out of the lock. The asynchronously processed workers makes the whole discovery process not atomic, the other events may interrupt the process. For example, if a loss of signal event inserted before the probe event, the sas_deform_port() is called and the port will be deleted. And sas_port_delete() may run before the destruct event, but the port-x:x is the top parent of end device or expander. This leads to a kernel WARNING such as: [ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22' [ 82.042983] ------------[ cut here ]------------ [ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237 sysfs_remove_group+0x94/0xa0 [ 82.043059] Call trace: [ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0 [ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70 [ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308 [ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60 [ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80 [ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0 [ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50 [ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0 [ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0 [ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490 [ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128 [ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50 Make probe and destruct a direct call in the disco and revalidate function, but put them outside the lock. The whole discovery or revalidate won't be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT event are deleted as a result of the direct call. Introduce a new list to destruct the sas_port and put the port delete after the destruct. This makes sure the right order of destroying the sysfs kobject and fix the warning above. In sas_ex_revalidate_domain() have a loop to find all broadcasted device, and sometimes we have a chance to find the same expander twice. Because the sas_port will be deleted at the end of the whole revalidate process, sas_port with the same name cannot be added before this. Otherwise the sysfs will complain of creating duplicate filename. Since the LLDD will send broadcast for every device change, we can only process one expander's revalidation. [mkp: kbuild test robot warning] Signed-off-by: Jason Yan <yanaijie@huawei.com> CC: John Garry <john.garry@huawei.com> CC: Johannes Thumshirn <jthumshirn@suse.de> CC: Ewan Milne <emilne@redhat.com> CC: Christoph Hellwig <hch@lst.de> CC: Tomas Henzl <thenzl@redhat.com> CC: Dan Williams <dan.j.williams@intel.com> Reviewed-by: Hannes Reinecke <hare@suse.com> Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com> CWE ID:
0
4,785
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; unsigned int i, entries; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ entries = avio_rb32(pb); av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries); if (!entries) return 0; if (entries >= UINT_MAX / sizeof(*sc->stsc_data)) return AVERROR_INVALIDDATA; sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data)); if (!sc->stsc_data) return AVERROR(ENOMEM); sc->stsc_count = entries; for (i=0; i<entries; i++) { sc->stsc_data[i].first = avio_rb32(pb); sc->stsc_data[i].count = avio_rb32(pb); sc->stsc_data[i].id = avio_rb32(pb); } return 0; } Commit Message: mov: reset dref_count on realloc to keep values consistent. This fixes a potential crash. Signed-off-by: Michael Niedermayer <michaelni@gmx.at> CWE ID: CWE-119
0
25,400
Analyze the following 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 create_certinfo(struct curl_certinfo *ci, zval *listcode) { int i; if (ci) { zval certhash; for (i=0; i<ci->num_of_certs; i++) { struct curl_slist *slist; array_init(&certhash); for (slist = ci->certinfo[i]; slist; slist = slist->next) { int len; char s[64]; char *tmp; strncpy(s, slist->data, 64); tmp = memchr(s, ':', 64); if(tmp) { *tmp = '\0'; len = strlen(s); add_assoc_string(&certhash, s, &slist->data[len+1]); } else { php_error_docref(NULL, E_WARNING, "Could not extract hash key from certificate info"); } } add_next_index_zval(listcode, &certhash); } } } Commit Message: Fix bug #72674 - check both curl_escape and curl_unescape CWE ID: CWE-119
0
10,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 int nfc_genl_dev_up(struct sk_buff *skb, struct genl_info *info) { struct nfc_dev *dev; int rc; u32 idx; if (!info->attrs[NFC_ATTR_DEVICE_INDEX]) return -EINVAL; idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]); dev = nfc_get_device(idx); if (!dev) return -ENODEV; rc = nfc_dev_up(dev); nfc_put_device(dev); return rc; } Commit Message: nfc: Ensure presence of required attributes in the deactivate_target handler Check that the NFC_ATTR_TARGET_INDEX attributes (in addition to NFC_ATTR_DEVICE_INDEX) are provided by the netlink client prior to accessing them. This prevents potential unhandled NULL pointer dereference exceptions which can be triggered by malicious user-mode programs, if they omit one or both of these attributes. Signed-off-by: Young Xiao <92siuyang@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-476
0
13,020
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: modification_init(png_modification *pmm) { memset(pmm, 0, sizeof *pmm); pmm->next = NULL; pmm->chunk = 0; pmm->modify_fn = NULL; pmm->add = 0; modification_reset(pmm); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
0
29,020
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void WebContentsImpl::CancelModalDialogsForRenderManager() { if (dialog_manager_) dialog_manager_->ResetDialogState(this); } Commit Message: Don't call WebContents::DownloadImage() callback if the WebContents were deleted BUG=583718 Review URL: https://codereview.chromium.org/1685343004 Cr-Commit-Position: refs/heads/master@{#375700} CWE ID:
0
2,693
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static enum hrtimer_restart hlt_timer_fn(struct hrtimer *data) { struct kvm_vcpu *vcpu; wait_queue_head_t *q; vcpu = container_of(data, struct kvm_vcpu, arch.hlt_timer); q = &vcpu->wq; if (vcpu->arch.mp_state != KVM_MP_STATE_HALTED) goto out; if (waitqueue_active(q)) wake_up_interruptible(q); out: vcpu->arch.timer_fired = 1; vcpu->arch.timer_check = 1; return HRTIMER_NORESTART; } Commit Message: KVM: Ensure all vcpus are consistent with in-kernel irqchip settings (cherry picked from commit 3e515705a1f46beb1c942bb8043c16f8ac7b1e9e) If some vcpus are created before KVM_CREATE_IRQCHIP, then irqchip_in_kernel() and vcpu->arch.apic will be inconsistent, leading to potential NULL pointer dereferences. Fix by: - ensuring that no vcpus are installed when KVM_CREATE_IRQCHIP is called - ensuring that a vcpu has an apic if it is installed after KVM_CREATE_IRQCHIP This is somewhat long winded because vcpu->arch.apic is created without kvm->lock held. Based on earlier patch by Michael Ellerman. Signed-off-by: Michael Ellerman <michael@ellerman.id.au> Signed-off-by: Avi Kivity <avi@redhat.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-399
0
24,130