instruction
stringclasses
1 value
input
stringlengths
56
241k
output
int64
0
1
__index_level_0__
int64
0
175k
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void ExtensionTabUtil::CreateTab(WebContents* web_contents, const std::string& extension_id, WindowOpenDisposition disposition, const gfx::Rect& initial_pos, bool user_gesture) { NOTIMPLEMENTED(); } Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the "tabs" permission. BUG=168442 Review URL: https://chromiumcodereview.appspot.com/11824004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
0
116,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 ResourceDispatcherHostImpl::SetDelegate( ResourceDispatcherHostDelegate* delegate) { delegate_ = delegate; } Commit Message: Make chrome.appWindow.create() provide access to the child window at a predictable time. When you first create a window with chrome.appWindow.create(), it won't have loaded any resources. So, at create time, you are guaranteed that: child_window.location.href == 'about:blank' child_window.document.documentElement.outerHTML == '<html><head></head><body></body></html>' This is in line with the behaviour of window.open(). BUG=131735 TEST=browser_tests:PlatformAppBrowserTest.WindowsApi Committed: http://src.chromium.org/viewvc/chrome?view=rev&revision=144072 Review URL: https://chromiumcodereview.appspot.com/10644006 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@144356 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
0
105,422
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: dotraplinkage void do_debug(struct pt_regs *regs, long error_code) { struct task_struct *tsk = current; int user_icebp = 0; unsigned long dr6; int si_code; ist_enter(regs); get_debugreg(dr6, 6); /* * The Intel SDM says: * * Certain debug exceptions may clear bits 0-3. The remaining * contents of the DR6 register are never cleared by the * processor. To avoid confusion in identifying debug * exceptions, debug handlers should clear the register before * returning to the interrupted task. * * Keep it simple: clear DR6 immediately. */ set_debugreg(0, 6); /* Filter out all the reserved bits which are preset to 1 */ dr6 &= ~DR6_RESERVED; /* * The SDM says "The processor clears the BTF flag when it * generates a debug exception." Clear TIF_BLOCKSTEP to keep * TIF_BLOCKSTEP in sync with the hardware BTF flag. */ clear_tsk_thread_flag(tsk, TIF_BLOCKSTEP); if (unlikely(!user_mode(regs) && (dr6 & DR_STEP) && is_sysenter_singlestep(regs))) { dr6 &= ~DR_STEP; if (!dr6) goto exit; /* * else we might have gotten a single-step trap and hit a * watchpoint at the same time, in which case we should fall * through and handle the watchpoint. */ } /* * If dr6 has no reason to give us about the origin of this trap, * then it's very likely the result of an icebp/int01 trap. * User wants a sigtrap for that. */ if (!dr6 && user_mode(regs)) user_icebp = 1; /* Store the virtualized DR6 value */ tsk->thread.debugreg6 = dr6; #ifdef CONFIG_KPROBES if (kprobe_debug_handler(regs)) goto exit; #endif if (notify_die(DIE_DEBUG, "debug", regs, (long)&dr6, error_code, SIGTRAP) == NOTIFY_STOP) goto exit; /* * Let others (NMI) know that the debug stack is in use * as we may switch to the interrupt stack. */ debug_stack_usage_inc(); /* It's safe to allow irq's after DR6 has been saved */ cond_local_irq_enable(regs); if (v8086_mode(regs)) { handle_vm86_trap((struct kernel_vm86_regs *) regs, error_code, X86_TRAP_DB); cond_local_irq_disable(regs); debug_stack_usage_dec(); goto exit; } if (WARN_ON_ONCE((dr6 & DR_STEP) && !user_mode(regs))) { /* * Historical junk that used to handle SYSENTER single-stepping. * This should be unreachable now. If we survive for a while * without anyone hitting this warning, we'll turn this into * an oops. */ tsk->thread.debugreg6 &= ~DR_STEP; set_tsk_thread_flag(tsk, TIF_SINGLESTEP); regs->flags &= ~X86_EFLAGS_TF; } si_code = get_si_code(tsk->thread.debugreg6); if (tsk->thread.debugreg6 & (DR_STEP | DR_TRAP_BITS) || user_icebp) send_sigtrap(tsk, regs, error_code, si_code); cond_local_irq_disable(regs); debug_stack_usage_dec(); exit: ist_exit(regs); } Commit Message: x86/entry/64: Don't use IST entry for #BP stack There's nothing IST-worthy about #BP/int3. We don't allow kprobes in the small handful of places in the kernel that run at CPL0 with an invalid stack, and 32-bit kernels have used normal interrupt gates for #BP forever. Furthermore, we don't allow kprobes in places that have usergs while in kernel mode, so "paranoid" is also unnecessary. Signed-off-by: Andy Lutomirski <luto@kernel.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> Signed-off-by: Thomas Gleixner <tglx@linutronix.de> Cc: stable@vger.kernel.org CWE ID: CWE-362
0
83,487
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: uint32_t GLES2DecoderImpl::GetAndClearBackbufferClearBitsForTest() { uint32_t clear_bits = backbuffer_needs_clear_bits_; backbuffer_needs_clear_bits_ = 0; return clear_bits; } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <kbr@chromium.org> Reviewed-by: Kentaro Hara <haraken@chromium.org> Reviewed-by: Geoff Lang <geofflang@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416
0
141,440
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void Document::nodeWillBeRemoved(Node* n) { HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end(); for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it) (*it)->nodeWillBeRemoved(n); if (!m_ranges.isEmpty()) { HashSet<Range*>::const_iterator rangesEnd = m_ranges.end(); for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it) (*it)->nodeWillBeRemoved(n); } if (Frame* frame = this->frame()) { frame->eventHandler()->nodeWillBeRemoved(n); frame->selection()->nodeWillBeRemoved(n); frame->page()->dragCaretController()->nodeWillBeRemoved(n); } } 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
105,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: bool parse_method(struct pool *pool, char *s) { json_t *val = NULL, *method, *err_val, *params; json_error_t err; bool ret = false; char *buf; if (!s) goto out; val = JSON_LOADS(s, &err); if (!val) { applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text); goto out; } method = json_object_get(val, "method"); if (!method) goto out_decref; err_val = json_object_get(val, "error"); params = json_object_get(val, "params"); if (err_val && !json_is_null(err_val)) { char *ss; if (err_val) ss = json_dumps(err_val, JSON_INDENT(3)); else ss = strdup("(unknown reason)"); applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss); free(ss); goto out_decref; } buf = (char *)json_string_value(method); if (!buf) goto out_decref; if (!strncasecmp(buf, "mining.notify", 13)) { if (parse_notify(pool, params)) pool->stratum_notify = ret = true; else pool->stratum_notify = ret = false; goto out_decref; } if (!strncasecmp(buf, "mining.set_difficulty", 21)) { ret = parse_diff(pool, params); goto out_decref; } if (!strncasecmp(buf, "client.reconnect", 16)) { ret = parse_reconnect(pool, params); goto out_decref; } if (!strncasecmp(buf, "client.get_version", 18)) { ret = send_version(pool, val); goto out_decref; } if (!strncasecmp(buf, "client.show_message", 19)) { ret = show_message(pool, params); goto out_decref; } out_decref: json_decref(val); out: return ret; } Commit Message: Do some random sanity checking for stratum message parsing CWE ID: CWE-119
0
36,668
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq, struct sched_entity *se, int cpu, struct sched_entity *parent) { struct rq *rq = cpu_rq(cpu); cfs_rq->tg = tg; cfs_rq->rq = rq; init_cfs_rq_runtime(cfs_rq); tg->cfs_rq[cpu] = cfs_rq; tg->se[cpu] = se; /* se could be NULL for root_task_group */ if (!se) return; if (!parent) { se->cfs_rq = &rq->cfs; se->depth = 0; } else { se->cfs_rq = parent->my_q; se->depth = parent->depth + 1; } se->my_q = cfs_rq; /* guarantee group entities always have weight */ update_load_set(&se->load, NICE_0_LOAD); se->parent = parent; } Commit Message: sched/fair: Fix infinite loop in update_blocked_averages() by reverting a9e7f6544b9c Zhipeng Xie, Xie XiuQi and Sargun Dhillon reported lockups in the scheduler under high loads, starting at around the v4.18 time frame, and Zhipeng Xie tracked it down to bugs in the rq->leaf_cfs_rq_list manipulation. Do a (manual) revert of: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path") It turns out that the list_del_leaf_cfs_rq() introduced by this commit is a surprising property that was not considered in followup commits such as: 9c2791f936ef ("sched/fair: Fix hierarchical order in rq->leaf_cfs_rq_list") As Vincent Guittot explains: "I think that there is a bigger problem with commit a9e7f6544b9c and cfs_rq throttling: Let take the example of the following topology TG2 --> TG1 --> root: 1) The 1st time a task is enqueued, we will add TG2 cfs_rq then TG1 cfs_rq to leaf_cfs_rq_list and we are sure to do the whole branch in one path because it has never been used and can't be throttled so tmp_alone_branch will point to leaf_cfs_rq_list at the end. 2) Then TG1 is throttled 3) and we add TG3 as a new child of TG1. 4) The 1st enqueue of a task on TG3 will add TG3 cfs_rq just before TG1 cfs_rq and tmp_alone_branch will stay on rq->leaf_cfs_rq_list. With commit a9e7f6544b9c, we can del a cfs_rq from rq->leaf_cfs_rq_list. So if the load of TG1 cfs_rq becomes NULL before step 2) above, TG1 cfs_rq is removed from the list. Then at step 4), TG3 cfs_rq is added at the beginning of rq->leaf_cfs_rq_list but tmp_alone_branch still points to TG3 cfs_rq because its throttled parent can't be enqueued when the lock is released. tmp_alone_branch doesn't point to rq->leaf_cfs_rq_list whereas it should. So if TG3 cfs_rq is removed or destroyed before tmp_alone_branch points on another TG cfs_rq, the next TG cfs_rq that will be added, will be linked outside rq->leaf_cfs_rq_list - which is bad. In addition, we can break the ordering of the cfs_rq in rq->leaf_cfs_rq_list but this ordering is used to update and propagate the update from leaf down to root." Instead of trying to work through all these cases and trying to reproduce the very high loads that produced the lockup to begin with, simplify the code temporarily by reverting a9e7f6544b9c - which change was clearly not thought through completely. This (hopefully) gives us a kernel that doesn't lock up so people can continue to enjoy their holidays without worrying about regressions. ;-) [ mingo: Wrote changelog, fixed weird spelling in code comment while at it. ] Analyzed-by: Xie XiuQi <xiexiuqi@huawei.com> Analyzed-by: Vincent Guittot <vincent.guittot@linaro.org> Reported-by: Zhipeng Xie <xiezhipeng1@huawei.com> Reported-by: Sargun Dhillon <sargun@sargun.me> Reported-by: Xie XiuQi <xiexiuqi@huawei.com> Tested-by: Zhipeng Xie <xiezhipeng1@huawei.com> Tested-by: Sargun Dhillon <sargun@sargun.me> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> Acked-by: Vincent Guittot <vincent.guittot@linaro.org> Cc: <stable@vger.kernel.org> # v4.13+ Cc: Bin Li <huawei.libin@huawei.com> Cc: Mike Galbraith <efault@gmx.de> Cc: Peter Zijlstra <peterz@infradead.org> Cc: Tejun Heo <tj@kernel.org> Cc: Thomas Gleixner <tglx@linutronix.de> Fixes: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path") Link: http://lkml.kernel.org/r/1545879866-27809-1-git-send-email-xiexiuqi@huawei.com Signed-off-by: Ingo Molnar <mingo@kernel.org> CWE ID: CWE-400
0
92,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: ResourceRequestBlockedReason CanRequest() { return CanRequestInternal(SecurityViolationReportingPolicy::kReport); } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <pfeldman@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Commit-Queue: Andrey Lushnikov <lushnikov@chromium.org> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119
0
138,783
Analyze the following 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 PrintRenderFrameHelper::OnMessageReceived(const IPC::Message& message) { ++ipc_nesting_level_; bool handled = true; IPC_BEGIN_MESSAGE_MAP(PrintRenderFrameHelper, message) #if BUILDFLAG(ENABLE_BASIC_PRINTING) IPC_MESSAGE_HANDLER(PrintMsg_PrintPages, OnPrintPages) IPC_MESSAGE_HANDLER(PrintMsg_PrintForSystemDialog, OnPrintForSystemDialog) #endif // BUILDFLAG(ENABLE_BASIC_PRINTING) #if BUILDFLAG(ENABLE_BASIC_PRINTING) && BUILDFLAG(ENABLE_PRINT_PREVIEW) IPC_MESSAGE_HANDLER(PrintMsg_PrintForPrintPreview, OnPrintForPrintPreview) #endif #if BUILDFLAG(ENABLE_PRINT_PREVIEW) IPC_MESSAGE_HANDLER(PrintMsg_InitiatePrintPreview, OnInitiatePrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintPreview, OnPrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintingDone, OnPrintingDone) IPC_MESSAGE_HANDLER(PrintMsg_ClosePrintPreviewDialog, OnClosePrintPreviewDialog) #endif // BUILDFLAG(ENABLE_PRINT_PREVIEW) IPC_MESSAGE_HANDLER(PrintMsg_SetPrintingEnabled, OnSetPrintingEnabled) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() --ipc_nesting_level_; if (ipc_nesting_level_ == 0 && render_frame_gone_) base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this); return handled; } Commit Message: DevTools: allow styling the page number element when printing over the protocol. Bug: none Change-Id: I13e6afbd86a7c6bcdedbf0645183194b9de7cfb4 Reviewed-on: https://chromium-review.googlesource.com/809759 Commit-Queue: Pavel Feldman <pfeldman@chromium.org> Reviewed-by: Lei Zhang <thestig@chromium.org> Reviewed-by: Tom Sepez <tsepez@chromium.org> Reviewed-by: Jianzhou Feng <jzfeng@chromium.org> Cr-Commit-Position: refs/heads/master@{#523966} CWE ID: CWE-20
0
149,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: int assoc_array_iterate(const struct assoc_array *array, int (*iterator)(const void *object, void *iterator_data), void *iterator_data) { struct assoc_array_ptr *root = ACCESS_ONCE(array->root); if (!root) return 0; return assoc_array_subtree_iterate(root, NULL, iterator, iterator_data); } Commit Message: KEYS: Fix termination condition in assoc array garbage collection This fixes CVE-2014-3631. It is possible for an associative array to end up with a shortcut node at the root of the tree if there are more than fan-out leaves in the tree, but they all crowd into the same slot in the lowest level (ie. they all have the same first nibble of their index keys). When assoc_array_gc() returns back up the tree after scanning some leaves, it can fall off of the root and crash because it assumes that the back pointer from a shortcut (after label ascend_old_tree) must point to a normal node - which isn't true of a shortcut node at the root. Should we find we're ascending rootwards over a shortcut, we should check to see if the backpointer is zero - and if it is, we have completed the scan. This particular bug cannot occur if the root node is not a shortcut - ie. if you have fewer than 17 keys in a keyring or if you have at least two keys that sit into separate slots (eg. a keyring and a non keyring). This can be reproduced by: ring=`keyctl newring bar @s` for ((i=1; i<=18; i++)); do last_key=`keyctl newring foo$i $ring`; done keyctl timeout $last_key 2 Doing this: echo 3 >/proc/sys/kernel/keys/gc_delay first will speed things up. If we do fall off of the top of the tree, we get the following oops: BUG: unable to handle kernel NULL pointer dereference at 0000000000000018 IP: [<ffffffff8136cea7>] assoc_array_gc+0x2f7/0x540 PGD dae15067 PUD cfc24067 PMD 0 Oops: 0000 [#1] SMP Modules linked in: xt_nat xt_mark nf_conntrack_netbios_ns nf_conntrack_broadcast ip6t_rpfilter ip6t_REJECT xt_conntrack ebtable_nat ebtable_broute bridge stp llc ebtable_filter ebtables ip6table_ni CPU: 0 PID: 26011 Comm: kworker/0:1 Not tainted 3.14.9-200.fc20.x86_64 #1 Hardware name: Bochs Bochs, BIOS Bochs 01/01/2011 Workqueue: events key_garbage_collector task: ffff8800918bd580 ti: ffff8800aac14000 task.ti: ffff8800aac14000 RIP: 0010:[<ffffffff8136cea7>] [<ffffffff8136cea7>] assoc_array_gc+0x2f7/0x540 RSP: 0018:ffff8800aac15d40 EFLAGS: 00010206 RAX: 0000000000000000 RBX: 0000000000000000 RCX: ffff8800aaecacc0 RDX: ffff8800daecf440 RSI: 0000000000000001 RDI: ffff8800aadc2bc0 RBP: ffff8800aac15da8 R08: 0000000000000001 R09: 0000000000000003 R10: ffffffff8136ccc7 R11: 0000000000000000 R12: 0000000000000000 R13: 0000000000000000 R14: 0000000000000070 R15: 0000000000000001 FS: 0000000000000000(0000) GS:ffff88011fc00000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b CR2: 0000000000000018 CR3: 00000000db10d000 CR4: 00000000000006f0 Stack: ffff8800aac15d50 0000000000000011 ffff8800aac15db8 ffffffff812e2a70 ffff880091a00600 0000000000000000 ffff8800aadc2bc3 00000000cd42c987 ffff88003702df20 ffff88003702dfa0 0000000053b65c09 ffff8800aac15fd8 Call Trace: [<ffffffff812e2a70>] ? keyring_detect_cycle_iterator+0x30/0x30 [<ffffffff812e3e75>] keyring_gc+0x75/0x80 [<ffffffff812e1424>] key_garbage_collector+0x154/0x3c0 [<ffffffff810a67b6>] process_one_work+0x176/0x430 [<ffffffff810a744b>] worker_thread+0x11b/0x3a0 [<ffffffff810a7330>] ? rescuer_thread+0x3b0/0x3b0 [<ffffffff810ae1a8>] kthread+0xd8/0xf0 [<ffffffff810ae0d0>] ? insert_kthread_work+0x40/0x40 [<ffffffff816ffb7c>] ret_from_fork+0x7c/0xb0 [<ffffffff810ae0d0>] ? insert_kthread_work+0x40/0x40 Code: 08 4c 8b 22 0f 84 bf 00 00 00 41 83 c7 01 49 83 e4 fc 41 83 ff 0f 4c 89 65 c0 0f 8f 5a fe ff ff 48 8b 45 c0 4d 63 cf 49 83 c1 02 <4e> 8b 34 c8 4d 85 f6 0f 84 be 00 00 00 41 f6 c6 01 0f 84 92 RIP [<ffffffff8136cea7>] assoc_array_gc+0x2f7/0x540 RSP <ffff8800aac15d40> CR2: 0000000000000018 ---[ end trace 1129028a088c0cbd ]--- Signed-off-by: David Howells <dhowells@redhat.com> Acked-by: Don Zickus <dzickus@redhat.com> Signed-off-by: James Morris <james.l.morris@oracle.com> CWE ID:
0
37,702
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void tcp_push(struct sock *sk, int flags, int mss_now, int nonagle, int size_goal) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; if (!tcp_send_head(sk)) return; skb = tcp_write_queue_tail(sk); if (!(flags & MSG_MORE) || forced_push(tp)) tcp_mark_push(tp, skb); tcp_mark_urg(tp, flags); if (tcp_should_autocork(sk, skb, size_goal)) { /* avoid atomic op if TSQ_THROTTLED bit is already set */ if (!test_bit(TSQ_THROTTLED, &sk->sk_tsq_flags)) { NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPAUTOCORKING); set_bit(TSQ_THROTTLED, &sk->sk_tsq_flags); } /* It is possible TX completion already happened * before we set TSQ_THROTTLED. */ if (atomic_read(&sk->sk_wmem_alloc) > skb->truesize) return; } if (flags & MSG_MORE) nonagle = TCP_NAGLE_CORK; __tcp_push_pending_frames(sk, mss_now, nonagle); } Commit Message: tcp: initialize rcv_mss to TCP_MIN_MSS instead of 0 When tcp_disconnect() is called, inet_csk_delack_init() sets icsk->icsk_ack.rcv_mss to 0. This could potentially cause tcp_recvmsg() => tcp_cleanup_rbuf() => __tcp_select_window() call path to have division by 0 issue. So this patch initializes rcv_mss to TCP_MIN_MSS instead of 0. Reported-by: Andrey Konovalov <andreyknvl@google.com> Signed-off-by: Wei Wang <weiwan@google.com> Signed-off-by: Eric Dumazet <edumazet@google.com> Signed-off-by: Neal Cardwell <ncardwell@google.com> Signed-off-by: Yuchung Cheng <ycheng@google.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-369
0
61,756
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: ImageBuffer* WebGLRenderingContextBase::LRUImageBufferCache::GetImageBuffer( const IntSize& size) { int i; for (i = 0; i < capacity_; ++i) { ImageBuffer* buf = buffers_[i].get(); if (!buf) break; if (buf->Size() != size) continue; BubbleToFront(i); return buf; } std::unique_ptr<ImageBuffer> temp(ImageBuffer::Create(size)); if (!temp) return nullptr; i = std::min(capacity_ - 1, i); buffers_[i] = std::move(temp); ImageBuffer* buf = buffers_[i].get(); BubbleToFront(i); return buf; } Commit Message: Tighten about IntRect use in WebGL with overflow detection BUG=784183 TEST=test case in the bug in ASAN build R=kbr@chromium.org Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: Ie25ca328af99de7828e28e6a6e3d775f1bebc43f Reviewed-on: https://chromium-review.googlesource.com/811826 Reviewed-by: Kenneth Russell <kbr@chromium.org> Commit-Queue: Zhenyao Mo <zmo@chromium.org> Cr-Commit-Position: refs/heads/master@{#522213} CWE ID: CWE-125
0
146,493
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void rawsock_write_queue_purge(struct sock *sk) { pr_debug("sk=%p\n", sk); spin_lock_bh(&sk->sk_write_queue.lock); __skb_queue_purge(&sk->sk_write_queue); nfc_rawsock(sk)->tx_work_scheduled = false; spin_unlock_bh(&sk->sk_write_queue.lock); } 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
40,598
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void Camera3Device::setErrorState(const char *fmt, ...) { Mutex::Autolock l(mLock); va_list args; va_start(args, fmt); setErrorStateLockedV(fmt, args); va_end(args); } Commit Message: Camera3Device: Validate template ID Validate template ID before creating a default request. Bug: 26866110 Bug: 27568958 Change-Id: Ifda457024f1d5c2b1382f189c1a8d5fda852d30d CWE ID: CWE-264
0
161,091
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void local_socket_ready_notify(asocket* s) { s->ready = local_socket_ready; s->shutdown = NULL; s->close = local_socket_close; SendOkay(s->fd); s->ready(s); } Commit Message: adb: use asocket's close function when closing. close_all_sockets was assuming that all registered local sockets used local_socket_close as their close function. However, this is not true for JDWP sockets. Bug: http://b/28347842 Change-Id: I40a1174845cd33f15f30ce70828a7081cd5a087e (cherry picked from commit 53eb31d87cb84a4212f4850bf745646e1fb12814) CWE ID: CWE-264
0
158,232
Analyze the following 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 nfs4_proc_exchange_id(struct nfs_client *clp, struct rpc_cred *cred) { nfs4_verifier verifier; struct nfs41_exchange_id_args args = { .client = clp, .flags = EXCHGID4_FLAG_SUPP_MOVED_REFER, }; struct nfs41_exchange_id_res res = { .client = clp, }; int status; struct rpc_message msg = { .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_EXCHANGE_ID], .rpc_argp = &args, .rpc_resp = &res, .rpc_cred = cred, }; __be32 *p; dprintk("--> %s\n", __func__); BUG_ON(clp == NULL); p = (u32 *)verifier.data; *p++ = htonl((u32)clp->cl_boot_time.tv_sec); *p = htonl((u32)clp->cl_boot_time.tv_nsec); args.verifier = &verifier; args.id_len = scnprintf(args.id, sizeof(args.id), "%s/%s.%s/%u", clp->cl_ipaddr, init_utsname()->nodename, init_utsname()->domainname, clp->cl_rpcclient->cl_auth->au_flavor); res.server_scope = kzalloc(sizeof(struct server_scope), GFP_KERNEL); if (unlikely(!res.server_scope)) return -ENOMEM; status = rpc_call_sync(clp->cl_rpcclient, &msg, RPC_TASK_TIMEOUT); if (!status) status = nfs4_check_cl_exchange_flags(clp->cl_exchange_flags); if (!status) { if (clp->server_scope && !nfs41_same_server_scope(clp->server_scope, res.server_scope)) { dprintk("%s: server_scope mismatch detected\n", __func__); set_bit(NFS4CLNT_SERVER_SCOPE_MISMATCH, &clp->cl_state); kfree(clp->server_scope); clp->server_scope = NULL; } if (!clp->server_scope) clp->server_scope = res.server_scope; else kfree(res.server_scope); } dprintk("<-- %s status= %d\n", __func__, status); return status; } Commit Message: NFSv4: include bitmap in nfsv4 get acl data The NFSv4 bitmap size is unbounded: a server can return an arbitrary sized bitmap in an FATTR4_WORD0_ACL request. Replace using the nfs4_fattr_bitmap_maxsz as a guess to the maximum bitmask returned by a server with the inclusion of the bitmap (xdr length plus bitmasks) and the acl data xdr length to the (cached) acl page data. This is a general solution to commit e5012d1f "NFSv4.1: update nfs4_fattr_bitmap_maxsz" and fixes hitting a BUG_ON in xdr_shrink_bufhead when getting ACLs. Fix a bug in decode_getacl that returned -EINVAL on ACLs > page when getxattr was called with a NULL buffer, preventing ACL > PAGE_SIZE from being retrieved. Cc: stable@kernel.org Signed-off-by: Andy Adamson <andros@netapp.com> Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID: CWE-189
0
23,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: const char* menu_cache_item_get_comment( MenuCacheItem* item ) { return item->comment; } Commit Message: CWE ID: CWE-20
0
6,440
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: pp::Var Plugin::GetInstanceObject() { PLUGIN_PRINTF(("Plugin::GetInstanceObject (this=%p)\n", static_cast<void*>(this))); ScriptablePlugin* handle = static_cast<ScriptablePlugin*>(scriptable_plugin()->AddRef()); pp::Var* handle_var = handle->var(); PLUGIN_PRINTF(("Plugin::GetInstanceObject (handle=%p, handle_var=%p)\n", static_cast<void*>(handle), static_cast<void*>(handle_var))); return *handle_var; // make a copy } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 TBR=bbudge@chromium.org Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
0
103,343
Analyze the following 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 InputType::StepUp(double n, ExceptionState& exception_state) { if (!IsSteppable()) { exception_state.ThrowDOMException(kInvalidStateError, "This form element is not steppable."); return; } const Decimal current = ParseToNumber(GetElement().value(), 0); ApplyStep(current, n, kRejectAny, kDispatchNoEvent, exception_state); } Commit Message: MacViews: Enable secure text input for password Textfields. In Cocoa the NSTextInputContext automatically enables secure text input when activated and it's in the secure text entry mode. RenderWidgetHostViewMac did the similar thing for ages following the WebKit example. views::Textfield needs to do the same thing in a fashion that's sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions are possible when the Textfield gets focus, activates the secure text input mode and the RWHVM loses focus immediately afterwards and disables the secure text input instead of leaving it in the enabled state. BUG=818133,677220 Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b Reviewed-on: https://chromium-review.googlesource.com/943064 Commit-Queue: Michail Pishchagin <mblsha@yandex-team.ru> Reviewed-by: Pavel Feldman <pfeldman@chromium.org> Reviewed-by: Avi Drissman <avi@chromium.org> Reviewed-by: Peter Kasting <pkasting@chromium.org> Cr-Commit-Position: refs/heads/master@{#542517} CWE ID:
0
126,248
Analyze the following 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 HTMLFormControlElement::ParseAttribute( const AttributeModificationParams& params) { const QualifiedName& name = params.name; if (name == kFormAttr) { FormAttributeChanged(); UseCounter::Count(GetDocument(), WebFeature::kFormAttribute); } else if (name == kReadonlyAttr) { if (params.old_value.IsNull() != params.new_value.IsNull()) { UpdateWillValidateCache(); PseudoStateChanged(CSSSelector::kPseudoReadOnly); PseudoStateChanged(CSSSelector::kPseudoReadWrite); if (LayoutObject* o = GetLayoutObject()) o->InvalidateIfControlStateChanged(kReadOnlyControlState); } } else if (name == kRequiredAttr) { if (params.old_value.IsNull() != params.new_value.IsNull()) RequiredAttributeChanged(); UseCounter::Count(GetDocument(), WebFeature::kRequiredAttribute); } else if (name == kAutofocusAttr) { HTMLElement::ParseAttribute(params); UseCounter::Count(GetDocument(), WebFeature::kAutoFocusAttribute); } else { HTMLElement::ParseAttribute(params); } } 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
136,564
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void preempt_notifier_inc(void) { static_key_slow_inc(&preempt_notifier_key); } Commit Message: Merge branch 'stacking-fixes' (vfs stacking fixes from Jann) Merge filesystem stacking fixes from Jann Horn. * emailed patches from Jann Horn <jannh@google.com>: sched: panic on corrupted stack end ecryptfs: forbid opening files without mmap handler proc: prevent stacking filesystems on top CWE ID: CWE-119
0
55,575
Analyze the following 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 ExtensionInstallDialogView::AddPermissions( views::GridLayout* layout, ui::ResourceBundle& rb, int column_set_id, int left_column_width, ExtensionInstallPrompt::PermissionsType perm_type) { if (prompt_->GetPermissionCount(perm_type) == 0) return false; const int vertical_padding = LayoutDelegate::Get()->GetMetric( LayoutDelegate::Metric::RELATED_CONTROL_VERTICAL_SPACING); layout->AddPaddingRow(0, vertical_padding); layout->StartRow(0, column_set_id); views::Label* permissions_header = new views::Label(prompt_->GetPermissionsHeading(perm_type)); permissions_header->SetMultiLine(true); permissions_header->SetHorizontalAlignment(gfx::ALIGN_LEFT); permissions_header->SizeToFit(left_column_width); layout->AddView(permissions_header); for (size_t i = 0; i < prompt_->GetPermissionCount(perm_type); ++i) { layout->AddPaddingRow(0, vertical_padding); layout->StartRow(0, column_set_id); views::Label* permission_label = new views::Label(prompt_->GetPermission(i, perm_type)); permission_label->SetMultiLine(true); permission_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); permission_label->SizeToFit(left_column_width - kBulletWidth); layout->AddView(new BulletedView(permission_label)); if (!prompt_->GetPermissionsDetails(i, perm_type).empty()) { layout->StartRow(0, column_set_id); PermissionDetails details; details.push_back(PrepareForDisplay( prompt_->GetPermissionsDetails(i, perm_type), false)); ExpandableContainerView* details_container = new ExpandableContainerView(details, left_column_width, true); layout->AddView(details_container); } } return true; } Commit Message: [Extensions UI] Initially disabled OK button for extension install prompts and enable them after a 500 ms time period. BUG=394518 Review-Url: https://codereview.chromium.org/2716353003 Cr-Commit-Position: refs/heads/master@{#461933} CWE ID: CWE-20
0
154,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 SetUpColoredUnitQuad(const GLfloat* color) { GLuint program1 = SetupColoredVertexProgram(); GLuint position_loc1 = glGetAttribLocation(program1, "a_position"); GLuint color_loc1 = glGetAttribLocation(program1, "a_color"); GLTestHelper::SetupUnitQuad(position_loc1); GLTestHelper::SetupColorsForUnitQuad(color_loc1, color, GL_STATIC_DRAW); } Commit Message: Fix tabs sharing TEXTURE_2D_ARRAY/TEXTURE_3D data. In linux and android, we are seeing an issue where texture data from one tab overwrites the texture data of another tab. This is happening for apps which are using webgl2 texture of type TEXTURE_2D_ARRAY/TEXTURE_3D. Due to a bug in virtual context save/restore code for above texture formats, the texture data is not properly restored while switching tabs. Hence texture data from one tab overwrites other. This CL has fix for that issue, an update for existing test expectations and a new unit test for this bug. Bug: 788448 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: Ie933984cdd2d1381f42eb4638f730c8245207a28 Reviewed-on: https://chromium-review.googlesource.com/930327 Reviewed-by: Zhenyao Mo <zmo@chromium.org> Commit-Queue: vikas soni <vikassoni@chromium.org> Cr-Commit-Position: refs/heads/master@{#539111} CWE ID: CWE-200
0
150,070
Analyze the following 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 InputType::TypeMismatch() const { return false; } Commit Message: MacViews: Enable secure text input for password Textfields. In Cocoa the NSTextInputContext automatically enables secure text input when activated and it's in the secure text entry mode. RenderWidgetHostViewMac did the similar thing for ages following the WebKit example. views::Textfield needs to do the same thing in a fashion that's sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions are possible when the Textfield gets focus, activates the secure text input mode and the RWHVM loses focus immediately afterwards and disables the secure text input instead of leaving it in the enabled state. BUG=818133,677220 Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b Reviewed-on: https://chromium-review.googlesource.com/943064 Commit-Queue: Michail Pishchagin <mblsha@yandex-team.ru> Reviewed-by: Pavel Feldman <pfeldman@chromium.org> Reviewed-by: Avi Drissman <avi@chromium.org> Reviewed-by: Peter Kasting <pkasting@chromium.org> Cr-Commit-Position: refs/heads/master@{#542517} CWE ID:
0
126,259
Analyze the following 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 read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb) { int i, j, v; if (get_bits1(gb)) { if (get_bits_left(gb) < 64*8) return AVERROR_INVALIDDATA; /* intra_quantiser_matrix */ for (i = 0; i < 64; i++) { v = get_bits(gb, 8); j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->intra_matrix[j] = v; s->chroma_intra_matrix[j] = v; } } if (get_bits1(gb)) { if (get_bits_left(gb) < 64*8) return AVERROR_INVALIDDATA; /* non_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { get_bits(gb, 8); } } if (get_bits1(gb)) { if (get_bits_left(gb) < 64*8) return AVERROR_INVALIDDATA; /* chroma_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { v = get_bits(gb, 8); j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->chroma_intra_matrix[j] = v; } } if (get_bits1(gb)) { if (get_bits_left(gb) < 64*8) return AVERROR_INVALIDDATA; /* chroma_non_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { get_bits(gb, 8); } } next_start_code_studio(gb); return 0; } Commit Message: avcodec/mpeg4videodec: Check idx in mpeg4_decode_studio_block() Fixes: Out of array access Fixes: 13500/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_MPEG4_fuzzer-5769760178962432 Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg Reviewed-by: Kieran Kunhya <kierank@obe.tv> Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-125
0
90,751
Analyze the following 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 virtio_load(VirtIODevice *vdev, QEMUFile *f) { int i, ret; uint32_t num; uint32_t features; uint32_t supported_features; VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus); if (k->load_config) { ret = k->load_config(qbus->parent, f); if (ret) return ret; } qemu_get_8s(f, &vdev->status); qemu_get_8s(f, &vdev->isr); qemu_get_be16s(f, &vdev->queue_sel); if (vdev->queue_sel >= VIRTIO_PCI_QUEUE_MAX) { return -1; } qemu_get_be32s(f, &features); if (virtio_set_features(vdev, features) < 0) { supported_features = k->get_features(qbus->parent); error_report("Features 0x%x unsupported. Allowed features: 0x%x", features, supported_features); features, supported_features); return -1; } vdev->config_len = qemu_get_be32(f); qemu_get_buffer(f, vdev->config, vdev->config_len); num = qemu_get_be32(f); for (i = 0; i < num; i++) { vdev->vq[i].vring.num = qemu_get_be32(f); if (k->has_variable_vring_alignment) { vdev->vq[i].vring.align = qemu_get_be32(f); } vdev->vq[i].pa = qemu_get_be64(f); qemu_get_be16s(f, &vdev->vq[i].last_avail_idx); vdev->vq[i].signalled_used_valid = false; vdev->vq[i].notification = true; if (vdev->vq[i].pa) { uint16_t nheads; virtqueue_init(&vdev->vq[i]); nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx; /* Check it isn't doing very strange things with descriptor numbers. */ if (nheads > vdev->vq[i].vring.num) { error_report("VQ %d size 0x%x Guest index 0x%x " "inconsistent with Host index 0x%x: delta 0x%x", i, vdev->vq[i].vring.num, vring_avail_idx(&vdev->vq[i]), vdev->vq[i].last_avail_idx, nheads); return -1; } } else if (vdev->vq[i].last_avail_idx) { error_report("VQ %d address 0x0 " "inconsistent with Host index 0x%x", i, vdev->vq[i].last_avail_idx); return -1; } if (k->load_queue) { ret = k->load_queue(qbus->parent, i, f); if (ret) return ret; } } virtio_notify_vector(vdev, VIRTIO_NO_VECTOR); return 0; } Commit Message: CWE ID: CWE-119
1
165,285
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void replaceCharsetInMediaType(String& mediaType, const String& charsetValue) { unsigned int pos = 0, len = 0; findCharsetInMediaType(mediaType, pos, len); if (!len) { return; } while (len) { mediaType.replace(pos, len, charsetValue); unsigned int start = pos + charsetValue.length(); findCharsetInMediaType(mediaType, pos, len, start); } } Commit Message: Don't dispatch events when XHR is set to sync mode Any of readystatechange, progress, abort, error, timeout and loadend event are not specified to be dispatched in sync mode in the latest spec. Just an exception corresponding to the failure is thrown. Clean up for readability done in this CL - factor out dispatchEventAndLoadEnd calling code - make didTimeout() private - give error handling methods more descriptive names - set m_exceptionCode in failure type specific methods -- Note that for didFailRedirectCheck, m_exceptionCode was not set in networkError(), but was set at the end of createRequest() This CL is prep for fixing crbug.com/292422 BUG=292422 Review URL: https://chromiumcodereview.appspot.com/24225002 git-svn-id: svn://svn.chromium.org/blink/trunk@158046 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
0
110,933
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void smp_send_app_cback(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { tSMP_EVT_DATA cb_data; tSMP_STATUS callback_rc; SMP_TRACE_DEBUG("%s p_cb->cb_evt=%d", __func__, p_cb->cb_evt); if (p_cb->p_callback && p_cb->cb_evt != 0) { switch (p_cb->cb_evt) { case SMP_IO_CAP_REQ_EVT: cb_data.io_req.auth_req = p_cb->peer_auth_req; cb_data.io_req.oob_data = SMP_OOB_NONE; cb_data.io_req.io_cap = SMP_DEFAULT_IO_CAPS; cb_data.io_req.max_key_size = SMP_MAX_ENC_KEY_SIZE; cb_data.io_req.init_keys = p_cb->local_i_key; cb_data.io_req.resp_keys = p_cb->local_r_key; SMP_TRACE_WARNING("io_cap = %d", cb_data.io_req.io_cap); break; case SMP_NC_REQ_EVT: cb_data.passkey = p_data->passkey; break; case SMP_SC_OOB_REQ_EVT: cb_data.req_oob_type = p_data->req_oob_type; break; case SMP_SC_LOC_OOB_DATA_UP_EVT: cb_data.loc_oob_data = p_cb->sc_oob_data.loc_oob_data; break; case SMP_BR_KEYS_REQ_EVT: cb_data.io_req.auth_req = 0; cb_data.io_req.oob_data = SMP_OOB_NONE; cb_data.io_req.io_cap = 0; cb_data.io_req.max_key_size = SMP_MAX_ENC_KEY_SIZE; cb_data.io_req.init_keys = SMP_BR_SEC_DEFAULT_KEY; cb_data.io_req.resp_keys = SMP_BR_SEC_DEFAULT_KEY; break; default: break; } callback_rc = (*p_cb->p_callback)(p_cb->cb_evt, p_cb->pairing_bda, &cb_data); SMP_TRACE_DEBUG("%s: callback_rc=%d p_cb->cb_evt=%d", __func__, callback_rc, p_cb->cb_evt); if (callback_rc == SMP_SUCCESS) { switch (p_cb->cb_evt) { case SMP_IO_CAP_REQ_EVT: p_cb->loc_auth_req = cb_data.io_req.auth_req; p_cb->local_io_capability = cb_data.io_req.io_cap; p_cb->loc_oob_flag = cb_data.io_req.oob_data; p_cb->loc_enc_size = cb_data.io_req.max_key_size; p_cb->local_i_key = cb_data.io_req.init_keys; p_cb->local_r_key = cb_data.io_req.resp_keys; if (!(p_cb->loc_auth_req & SMP_AUTH_BOND)) { SMP_TRACE_WARNING("Non bonding: No keys will be exchanged"); p_cb->local_i_key = 0; p_cb->local_r_key = 0; } SMP_TRACE_WARNING( "rcvd auth_req: 0x%02x, io_cap: %d " "loc_oob_flag: %d loc_enc_size: %d, " "local_i_key: 0x%02x, local_r_key: 0x%02x", p_cb->loc_auth_req, p_cb->local_io_capability, p_cb->loc_oob_flag, p_cb->loc_enc_size, p_cb->local_i_key, p_cb->local_r_key); p_cb->secure_connections_only_mode_required = (btm_cb.security_mode == BTM_SEC_MODE_SC) ? true : false; /* just for PTS, force SC bit */ if (p_cb->secure_connections_only_mode_required) { p_cb->loc_auth_req |= SMP_SC_SUPPORT_BIT; } if (!p_cb->secure_connections_only_mode_required && (!(p_cb->loc_auth_req & SMP_SC_SUPPORT_BIT) || lmp_version_below(p_cb->pairing_bda, HCI_PROTO_VERSION_4_2) || interop_match_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, (const RawAddress*)&p_cb->pairing_bda))) { p_cb->loc_auth_req &= ~SMP_SC_SUPPORT_BIT; p_cb->loc_auth_req &= ~SMP_KP_SUPPORT_BIT; p_cb->local_i_key &= ~SMP_SEC_KEY_TYPE_LK; p_cb->local_r_key &= ~SMP_SEC_KEY_TYPE_LK; } if (lmp_version_below(p_cb->pairing_bda, HCI_PROTO_VERSION_5_0)) { p_cb->loc_auth_req &= ~SMP_H7_SUPPORT_BIT; } SMP_TRACE_WARNING( "set auth_req: 0x%02x, local_i_key: 0x%02x, local_r_key: 0x%02x", p_cb->loc_auth_req, p_cb->local_i_key, p_cb->local_r_key); smp_sm_event(p_cb, SMP_IO_RSP_EVT, NULL); break; case SMP_BR_KEYS_REQ_EVT: p_cb->loc_enc_size = cb_data.io_req.max_key_size; p_cb->local_i_key = cb_data.io_req.init_keys; p_cb->local_r_key = cb_data.io_req.resp_keys; p_cb->loc_auth_req |= SMP_H7_SUPPORT_BIT; p_cb->local_i_key &= ~SMP_SEC_KEY_TYPE_LK; p_cb->local_r_key &= ~SMP_SEC_KEY_TYPE_LK; SMP_TRACE_WARNING( "for SMP over BR max_key_size: 0x%02x, local_i_key: 0x%02x, " "local_r_key: 0x%02x, p_cb->loc_auth_req: 0x%02x", p_cb->loc_enc_size, p_cb->local_i_key, p_cb->local_r_key, p_cb->loc_auth_req); smp_br_state_machine_event(p_cb, SMP_BR_KEYS_RSP_EVT, NULL); break; } } } if (!p_cb->cb_evt && p_cb->discard_sec_req) { p_cb->discard_sec_req = false; smp_sm_event(p_cb, SMP_DISCARD_SEC_REQ_EVT, NULL); } SMP_TRACE_DEBUG("%s: return", __func__); } Commit Message: Checks the SMP length to fix OOB read Bug: 111937065 Test: manual Change-Id: I330880a6e1671d0117845430db4076dfe1aba688 Merged-In: I330880a6e1671d0117845430db4076dfe1aba688 (cherry picked from commit fceb753bda651c4135f3f93a510e5fcb4c7542b8) CWE ID: CWE-200
0
162,774
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: UINT CSoundFile::GetNumInstruments() const { UINT n=0; for (UINT i=0; i<MAX_INSTRUMENTS; i++) if (Ins[i].pSample) n++; return n; } Commit Message: CWE ID:
0
8,481
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static inline int compute_score2(struct sock *sk, struct net *net, __be32 saddr, __be16 sport, __be32 daddr, unsigned int hnum, int dif) { int score = -1; if (net_eq(sock_net(sk), net) && !ipv6_only_sock(sk)) { struct inet_sock *inet = inet_sk(sk); if (inet->inet_rcv_saddr != daddr) return -1; if (inet->inet_num != hnum) return -1; score = (sk->sk_family == PF_INET ? 1 : 0); if (inet->inet_daddr) { if (inet->inet_daddr != saddr) return -1; score += 2; } if (inet->inet_dport) { if (inet->inet_dport != sport) return -1; score += 2; } if (sk->sk_bound_dev_if) { if (sk->sk_bound_dev_if != dif) return -1; score += 2; } } return score; } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com> Cc: Herbert Xu <herbert@gondor.apana.org.au> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-362
0
19,061
Analyze the following 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 reset_all_signal_handlers(void) { int sig; for (sig = 1; sig < _NSIG; sig++) { struct sigaction sa; if (sig == SIGKILL || sig == SIGSTOP) continue; zero(sa); sa.sa_handler = SIG_DFL; sa.sa_flags = SA_RESTART; /* On Linux the first two RT signals are reserved by * glibc, and sigaction() will return EINVAL for them. */ if ((sigaction(sig, &sa, NULL) < 0)) if (errno != EINVAL) return -errno; } return 0; } Commit Message: CWE ID: CWE-362
0
11,580
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int reds_init_ssl(void) { #if OPENSSL_VERSION_NUMBER >= 0x10000000L const SSL_METHOD *ssl_method; #else SSL_METHOD *ssl_method; #endif int return_code; long ssl_options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3; /* Global system initialization*/ SSL_library_init(); SSL_load_error_strings(); /* Create our context*/ ssl_method = TLSv1_method(); reds->ctx = SSL_CTX_new(ssl_method); if (!reds->ctx) { spice_warning("Could not allocate new SSL context"); return -1; } /* Limit connection to TLSv1 only */ #ifdef SSL_OP_NO_COMPRESSION ssl_options |= SSL_OP_NO_COMPRESSION; #endif SSL_CTX_set_options(reds->ctx, ssl_options); /* Load our keys and certificates*/ return_code = SSL_CTX_use_certificate_chain_file(reds->ctx, ssl_parameters.certs_file); if (return_code == 1) { spice_info("Loaded certificates from %s", ssl_parameters.certs_file); } else { spice_warning("Could not load certificates from %s", ssl_parameters.certs_file); return -1; } SSL_CTX_set_default_passwd_cb(reds->ctx, ssl_password_cb); return_code = SSL_CTX_use_PrivateKey_file(reds->ctx, ssl_parameters.private_key_file, SSL_FILETYPE_PEM); if (return_code == 1) { spice_info("Using private key from %s", ssl_parameters.private_key_file); } else { spice_warning("Could not use private key file"); return -1; } /* Load the CAs we trust*/ return_code = SSL_CTX_load_verify_locations(reds->ctx, ssl_parameters.ca_certificate_file, 0); if (return_code == 1) { spice_info("Loaded CA certificates from %s", ssl_parameters.ca_certificate_file); } else { spice_warning("Could not use CA file %s", ssl_parameters.ca_certificate_file); return -1; } #if (OPENSSL_VERSION_NUMBER < 0x00905100L) SSL_CTX_set_verify_depth(reds->ctx, 1); #endif if (strlen(ssl_parameters.dh_key_file) > 0) { if (load_dh_params(reds->ctx, ssl_parameters.dh_key_file) < 0) { return -1; } } SSL_CTX_set_session_id_context(reds->ctx, (const unsigned char *)"SPICE", 5); if (strlen(ssl_parameters.ciphersuite) > 0) { if (!SSL_CTX_set_cipher_list(reds->ctx, ssl_parameters.ciphersuite)) { return -1; } } openssl_thread_setup(); #ifndef SSL_OP_NO_COMPRESSION STACK *cmp_stack = SSL_COMP_get_compression_methods(); sk_zero(cmp_stack); #endif return 0; } Commit Message: CWE ID: CWE-119
0
1,891
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int skcipher_walk_aead_encrypt(struct skcipher_walk *walk, struct aead_request *req, bool atomic) { walk->total = req->cryptlen; return skcipher_walk_aead_common(walk, req, atomic); } Commit Message: crypto: skcipher - Add missing API setkey checks The API setkey checks for key sizes and alignment went AWOL during the skcipher conversion. This patch restores them. Cc: <stable@vger.kernel.org> Fixes: 4e6c3df4d729 ("crypto: skcipher - Add low-level skcipher...") Reported-by: Baozeng <sploving1@gmail.com> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> CWE ID: CWE-476
0
64,810
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: String MediaRecorder::state() const { return StateToString(state_); } Commit Message: Check context is attached before creating MediaRecorder Bug: 896736 Change-Id: I3ccfd2188fb15704af14c8af050e0a5667855d34 Reviewed-on: https://chromium-review.googlesource.com/c/1324231 Commit-Queue: Emircan Uysaler <emircan@chromium.org> Reviewed-by: Miguel Casas <mcasas@chromium.org> Cr-Commit-Position: refs/heads/master@{#606242} CWE ID: CWE-119
0
143,545
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static const char *set_errorlog(cmd_parms *cmd, void *dummy, const char *arg1, const char *arg2) { ap_errorlog_provider *provider; const char *err; cmd->server->errorlog_provider = NULL; if (!arg2) { /* Stay backward compatible and check for "syslog" */ if (strncmp("syslog", arg1, 6) == 0) { arg2 = arg1 + 7; /* skip the ':' if any */ arg1 = "syslog"; } else { /* Admin can define only "ErrorLog provider" and we should * still handle that using the defined provider, but with empty * error_fname. */ provider = ap_lookup_provider(AP_ERRORLOG_PROVIDER_GROUP, arg1, AP_ERRORLOG_PROVIDER_VERSION); if (provider) { arg2 = ""; } else { return set_server_string_slot(cmd, dummy, arg1); } } } if (strcmp("file", arg1) == 0) { return set_server_string_slot(cmd, dummy, arg2); } provider = ap_lookup_provider(AP_ERRORLOG_PROVIDER_GROUP, arg1, AP_ERRORLOG_PROVIDER_VERSION); if (!provider) { return apr_psprintf(cmd->pool, "Unknown ErrorLog provider: %s", arg1); } err = provider->parse_errorlog_arg(cmd, arg2); if (err) { return err; } cmd->server->errorlog_provider = provider; return set_server_string_slot(cmd, dummy, arg2); } Commit Message: core: Disallow Methods' registration at run time (.htaccess), they may be used only if registered at init time (httpd.conf). Calling ap_method_register() in children processes is not the right scope since it won't be shared for all requests. git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1807655 13f79535-47bb-0310-9956-ffa450edef68 CWE ID: CWE-416
0
64,281
Analyze the following 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 VideoCaptureManager::OnClosed( MediaStreamType stream_type, media::VideoCaptureSessionId capture_session_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); for (auto& listener : listeners_) listener.Closed(stream_type, capture_session_id); } Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame. Instead of having RenderFrameHost own a single MSDH to handle all requests from a frame, MSDH objects will be owned by a strong binding. A consequence of this is that an additional requester ID is added to requests to MediaStreamManager, so that an MSDH is able to cancel only requests generated by it. In practice, MSDH will continue to be per frame in most cases since each frame normally makes a single request for an MSDH object. This fixes a lifetime issue caused by the IO thread executing tasks after the RenderFrameHost dies. Drive-by: Fix some minor lint issues. Bug: 912520 Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516 Reviewed-on: https://chromium-review.googlesource.com/c/1369799 Reviewed-by: Emircan Uysaler <emircan@chromium.org> Reviewed-by: Ken Buchanan <kenrb@chromium.org> Reviewed-by: Olga Sharonova <olka@chromium.org> Commit-Queue: Guido Urdaneta <guidou@chromium.org> Cr-Commit-Position: refs/heads/master@{#616347} CWE ID: CWE-189
0
153,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: int ssl3_new(SSL *s) { SSL3_STATE *s3; if ((s3=OPENSSL_malloc(sizeof *s3)) == NULL) goto err; memset(s3,0,sizeof *s3); memset(s3->rrec.seq_num,0,sizeof(s3->rrec.seq_num)); memset(s3->wrec.seq_num,0,sizeof(s3->wrec.seq_num)); s->s3=s3; #ifndef OPENSSL_NO_SRP SSL_SRP_CTX_init(s); #endif s->method->ssl_clear(s); return(1); err: return(0); } Commit Message: CWE ID: CWE-310
0
88
Analyze the following 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(openssl_csr_get_subject) { zval ** zcsr; zend_bool use_shortnames = 1; long csr_resource; X509_NAME * subject; X509_REQ * csr; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z|b", &zcsr, &use_shortnames) == FAILURE) { return; } csr = php_openssl_csr_from_zval(zcsr, 0, &csr_resource TSRMLS_CC); if (csr == NULL) { RETURN_FALSE; } subject = X509_REQ_get_subject_name(csr); array_init(return_value); add_assoc_name_entry(return_value, NULL, subject, use_shortnames TSRMLS_CC); return; } Commit Message: CWE ID: CWE-119
0
109
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: virtual int create() { int ret; ret = mMsg.create(GOOGLE_OUI, WIFI_SUBCMD_SET_COUNTRY_CODE); if (ret < 0) { ALOGE("Can't create message to send to driver - %d", ret); return ret; } nlattr *data = mMsg.attr_start(NL80211_ATTR_VENDOR_DATA); ret = mMsg.put_string(ATTR_COUNTRY_CODE, mCountryCode); if (ret < 0) { return ret; } mMsg.attr_end(data); return WIFI_SUCCESS; } Commit Message: Fix use-after-free in wifi_cleanup() Release reference to cmd only after possibly calling getType(). BUG: 25753768 Change-Id: Id2156ce51acec04e8364706cf7eafc7d4adae9eb (cherry picked from commit d7f3cb9915d9ac514393d0ad7767662958054b8f https://googleplex-android-review.git.corp.google.com/#/c/815223) CWE ID: CWE-264
0
161,941
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void __audit_syscall_entry(int major, unsigned long a1, unsigned long a2, unsigned long a3, unsigned long a4) { struct task_struct *tsk = current; struct audit_context *context = tsk->audit_context; enum audit_state state; if (!context) return; BUG_ON(context->in_syscall || context->name_count); if (!audit_enabled) return; context->arch = syscall_get_arch(); context->major = major; context->argv[0] = a1; context->argv[1] = a2; context->argv[2] = a3; context->argv[3] = a4; state = context->state; context->dummy = !audit_n_rules; if (!context->dummy && state == AUDIT_BUILD_CONTEXT) { context->prio = 0; state = audit_filter_syscall(tsk, context, &audit_filter_list[AUDIT_FILTER_ENTRY]); } if (state == AUDIT_DISABLED) return; context->serial = 0; context->ctime = CURRENT_TIME; context->in_syscall = 1; context->current_state = state; context->ppid = 0; } Commit Message: audit: fix a double fetch in audit_log_single_execve_arg() There is a double fetch problem in audit_log_single_execve_arg() where we first check the execve(2) argumnets for any "bad" characters which would require hex encoding and then re-fetch the arguments for logging in the audit record[1]. Of course this leaves a window of opportunity for an unsavory application to munge with the data. This patch reworks things by only fetching the argument data once[2] into a buffer where it is scanned and logged into the audit records(s). In addition to fixing the double fetch, this patch improves on the original code in a few other ways: better handling of large arguments which require encoding, stricter record length checking, and some performance improvements (completely unverified, but we got rid of some strlen() calls, that's got to be a good thing). As part of the development of this patch, I've also created a basic regression test for the audit-testsuite, the test can be tracked on GitHub at the following link: * https://github.com/linux-audit/audit-testsuite/issues/25 [1] If you pay careful attention, there is actually a triple fetch problem due to a strnlen_user() call at the top of the function. [2] This is a tiny white lie, we do make a call to strnlen_user() prior to fetching the argument data. I don't like it, but due to the way the audit record is structured we really have no choice unless we copy the entire argument at once (which would require a rather wasteful allocation). The good news is that with this patch the kernel no longer relies on this strnlen_user() value for anything beyond recording it in the log, we also update it with a trustworthy value whenever possible. Reported-by: Pengfei Wang <wpengfeinudt@gmail.com> Cc: <stable@vger.kernel.org> Signed-off-by: Paul Moore <paul@paul-moore.com> CWE ID: CWE-362
0
51,140
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int a2d_ASN1_OBJECT(unsigned char *out, int olen, const char *buf, int num) { int i,first,len=0,c, use_bn; char ftmp[24], *tmp = ftmp; int tmpsize = sizeof ftmp; const char *p; unsigned long l; BIGNUM *bl = NULL; if (num == 0) return(0); else if (num == -1) num=strlen(buf); p=buf; c= *(p++); num--; if ((c >= '0') && (c <= '2')) { first= c-'0'; } else { ASN1err(ASN1_F_A2D_ASN1_OBJECT,ASN1_R_FIRST_NUM_TOO_LARGE); goto err; } if (num <= 0) { ASN1err(ASN1_F_A2D_ASN1_OBJECT,ASN1_R_MISSING_SECOND_NUMBER); goto err; } c= *(p++); num--; for (;;) { if (num <= 0) break; if ((c != '.') && (c != ' ')) { ASN1err(ASN1_F_A2D_ASN1_OBJECT,ASN1_R_INVALID_SEPARATOR); goto err; } l=0; use_bn = 0; for (;;) { if (num <= 0) break; num--; c= *(p++); if ((c == ' ') || (c == '.')) break; if ((c < '0') || (c > '9')) { ASN1err(ASN1_F_A2D_ASN1_OBJECT,ASN1_R_INVALID_DIGIT); goto err; } if (!use_bn && l >= ((ULONG_MAX - 80) / 10L)) { use_bn = 1; if (!bl) bl = BN_new(); if (!bl || !BN_set_word(bl, l)) goto err; } if (use_bn) { if (!BN_mul_word(bl, 10L) || !BN_add_word(bl, c-'0')) goto err; } else l=l*10L+(long)(c-'0'); } if (len == 0) { if ((first < 2) && (l >= 40)) { ASN1err(ASN1_F_A2D_ASN1_OBJECT,ASN1_R_SECOND_NUMBER_TOO_LARGE); goto err; } if (use_bn) { if (!BN_add_word(bl, first * 40)) goto err; } else l+=(long)first*40; } i=0; if (use_bn) { int blsize; blsize = BN_num_bits(bl); blsize = (blsize + 6)/7; if (blsize > tmpsize) { if (tmp != ftmp) OPENSSL_free(tmp); tmpsize = blsize + 32; tmp = OPENSSL_malloc(tmpsize); if (!tmp) goto err; } while(blsize--) tmp[i++] = (unsigned char)BN_div_word(bl, 0x80L); } else { for (;;) { tmp[i++]=(unsigned char)l&0x7f; l>>=7L; if (l == 0L) break; } } if (out != NULL) { if (len+i > olen) { ASN1err(ASN1_F_A2D_ASN1_OBJECT,ASN1_R_BUFFER_TOO_SMALL); goto err; } while (--i > 0) out[len++]=tmp[i]|0x80; out[len++]=tmp[0]; } else len+=i; } if (tmp != ftmp) OPENSSL_free(tmp); if (bl) BN_free(bl); return(len); err: if (tmp != ftmp) OPENSSL_free(tmp); if (bl) BN_free(bl); return(0); } Commit Message: CWE ID: CWE-200
0
12,464
Analyze the following 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 qeth_qdio_activate(struct qeth_card *card) { QETH_DBF_TEXT(SETUP, 3, "qdioact"); return qdio_activate(CARD_DDEV(card)); } Commit Message: qeth: avoid buffer overflow in snmp ioctl Check user-defined length in snmp ioctl request and allow request only if it fits into a qeth command buffer. Signed-off-by: Ursula Braun <ursula.braun@de.ibm.com> Signed-off-by: Frank Blaschka <frank.blaschka@de.ibm.com> Reviewed-by: Heiko Carstens <heicars2@linux.vnet.ibm.com> Reported-by: Nico Golde <nico@ngolde.de> Reported-by: Fabian Yamaguchi <fabs@goesec.de> Cc: <stable@vger.kernel.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-119
0
28,604
Analyze the following 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 SaveCardBubbleControllerImpl::ReshowBubble() { is_reshow_ = true; AutofillMetrics::LogSaveCardPromptMetric( AutofillMetrics::SAVE_CARD_PROMPT_SHOW_REQUESTED, is_uploading_, is_reshow_, pref_service_->GetInteger( prefs::kAutofillAcceptSaveCreditCardPromptState)); ShowBubble(); } Commit Message: [autofill] Avoid duplicate instances of the SaveCardBubble. autofill::SaveCardBubbleControllerImpl::ShowBubble() expects (via DCHECK) to only be called when the save card bubble is not already visible. This constraint is violated if the user clicks multiple times on a submit button. If the underlying page goes away, the last SaveCardBubbleView created by the controller will be automatically cleaned up, but any others are left visible on the screen... holding a refence to a possibly-deleted controller. This CL early exits the ShowBubbleFor*** and ReshowBubble logic if the bubble is already visible. BUG=708819 Review-Url: https://codereview.chromium.org/2862933002 Cr-Commit-Position: refs/heads/master@{#469768} CWE ID: CWE-416
1
172,384
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: perform_transform_test(png_modifier *pm) { png_byte colour_type = 0; png_byte bit_depth = 0; unsigned int palette_number = 0; while (next_format(&colour_type, &bit_depth, &palette_number, 0)) { png_uint_32 counter = 0; size_t base_pos; char name[64]; base_pos = safecat(name, sizeof name, 0, "transform:"); for (;;) { size_t pos = base_pos; PNG_CONST image_transform *list = 0; /* 'max' is currently hardwired to '1'; this should be settable on the * command line. */ counter = image_transform_add(&list, 1/*max*/, counter, name, sizeof name, &pos, colour_type, bit_depth); if (counter == 0) break; /* The command line can change this to checking interlaced images. */ do { pm->repeat = 0; transform_test(pm, FILEID(colour_type, bit_depth, palette_number, pm->interlace_type, 0, 0, 0), list, name); if (fail(pm)) return; } while (pm->repeat); } } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
1
173,684
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static inline int managed_dentry_rcu(const struct path *path) { return (path->dentry->d_flags & DCACHE_MANAGE_TRANSIT) ? path->dentry->d_op->d_manage(path, true) : 0; } Commit Message: dentry name snapshots take_dentry_name_snapshot() takes a safe snapshot of dentry name; if the name is a short one, it gets copied into caller-supplied structure, otherwise an extra reference to external name is grabbed (those are never modified). In either case the pointer to stable string is stored into the same structure. dentry must be held by the caller of take_dentry_name_snapshot(), but may be freely dropped afterwards - the snapshot will stay until destroyed by release_dentry_name_snapshot(). Intended use: struct name_snapshot s; take_dentry_name_snapshot(&s, dentry); ... access s.name ... release_dentry_name_snapshot(&s); Replaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name to pass down with event. Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> CWE ID: CWE-362
0
67,447
Analyze the following 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 IOThread::InitAsync() { TRACE_EVENT0("startup", "IOThread::InitAsync"); DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); #if defined(USE_NSS) || defined(OS_IOS) net::SetMessageLoopForNSSHttpIO(); #endif const CommandLine& command_line = *CommandLine::ForCurrentProcess(); DCHECK(!globals_); globals_ = new Globals; network_change_observer_.reset( new LoggingNetworkChangeObserver(net_log_)); net::NetworkChangeNotifier::InitHistogramWatcher(); globals_->extension_event_router_forwarder = extension_event_router_forwarder_; ChromeNetworkDelegate* network_delegate = new ChromeNetworkDelegate(extension_event_router_forwarder_, &system_enable_referrers_); if (command_line.HasSwitch(switches::kEnableClientHints)) network_delegate->SetEnableClientHints(); if (command_line.HasSwitch(switches::kDisableExtensionsHttpThrottling)) network_delegate->NeverThrottleRequests(); globals_->system_network_delegate.reset(network_delegate); globals_->host_resolver = CreateGlobalHostResolver(net_log_); UpdateDnsClientEnabled(); globals_->cert_verifier.reset(net::CertVerifier::CreateDefault()); globals_->transport_security_state.reset(new net::TransportSecurityState()); #if !defined(USE_OPENSSL) net::MultiLogCTVerifier* ct_verifier = new net::MultiLogCTVerifier(); globals_->cert_transparency_verifier.reset(ct_verifier); ct_verifier->AddLog(net::ct::CreateGooglePilotLogVerifier().Pass()); ct_verifier->AddLog(net::ct::CreateGoogleAviatorLogVerifier().Pass()); ct_verifier->AddLog(net::ct::CreateGoogleRocketeerLogVerifier().Pass()); if (command_line.HasSwitch(switches::kCertificateTransparencyLog)) { std::string switch_value = command_line.GetSwitchValueASCII( switches::kCertificateTransparencyLog); size_t delim_pos = switch_value.find(":"); CHECK(delim_pos != std::string::npos) << "CT log description not provided (switch format" " is 'description:base64_key')"; std::string log_description(switch_value.substr(0, delim_pos)); std::string ct_public_key_data; CHECK(base::Base64Decode( switch_value.substr(delim_pos + 1), &ct_public_key_data)) << "Unable to decode CT public key."; scoped_ptr<net::CTLogVerifier> external_log_verifier( net::CTLogVerifier::Create(ct_public_key_data, log_description)); CHECK(external_log_verifier) << "Unable to parse CT public key."; ct_verifier->AddLog(external_log_verifier.Pass()); } #else if (command_line.HasSwitch(switches::kCertificateTransparencyLog)) { LOG(DFATAL) << "Certificate Transparency is not yet supported in Chrome " "builds using OpenSSL."; } #endif globals_->ssl_config_service = GetSSLConfigService(); #if defined(OS_ANDROID) || defined(OS_IOS) if (DataReductionProxySettings::IsDataReductionProxyAllowed()) { spdyproxy_auth_origins_ = DataReductionProxySettings::GetDataReductionProxies(); } #endif // defined(OS_ANDROID) || defined(OS_IOS) globals_->http_auth_handler_factory.reset(CreateDefaultAuthHandlerFactory( globals_->host_resolver.get())); globals_->http_server_properties.reset(new net::HttpServerPropertiesImpl()); globals_->proxy_script_fetcher_proxy_service.reset( net::ProxyService::CreateDirectWithNetLog(net_log_)); globals_->system_cookie_store = new net::CookieMonster(NULL, NULL); globals_->system_server_bound_cert_service.reset( new net::ServerBoundCertService( new net::DefaultServerBoundCertStore(NULL), base::WorkerPool::GetTaskRunner(true))); globals_->dns_probe_service.reset(new chrome_browser_net::DnsProbeService()); globals_->load_time_stats.reset(new chrome_browser_net::LoadTimeStats()); globals_->host_mapping_rules.reset(new net::HostMappingRules()); globals_->http_user_agent_settings.reset( new BasicHttpUserAgentSettings(std::string())); if (command_line.HasSwitch(switches::kHostRules)) { TRACE_EVENT_BEGIN0("startup", "IOThread::InitAsync:SetRulesFromString"); globals_->host_mapping_rules->SetRulesFromString( command_line.GetSwitchValueASCII(switches::kHostRules)); TRACE_EVENT_END0("startup", "IOThread::InitAsync:SetRulesFromString"); } if (command_line.HasSwitch(switches::kIgnoreCertificateErrors)) globals_->ignore_certificate_errors = true; if (command_line.HasSwitch(switches::kTestingFixedHttpPort)) { globals_->testing_fixed_http_port = GetSwitchValueAsInt(command_line, switches::kTestingFixedHttpPort); } if (command_line.HasSwitch(switches::kTestingFixedHttpsPort)) { globals_->testing_fixed_https_port = GetSwitchValueAsInt(command_line, switches::kTestingFixedHttpsPort); } ConfigureQuic(command_line); if (command_line.HasSwitch( switches::kEnableUserAlternateProtocolPorts)) { globals_->enable_user_alternate_protocol_ports = true; } InitializeNetworkOptions(command_line); net::HttpNetworkSession::Params session_params; InitializeNetworkSessionParams(&session_params); session_params.net_log = net_log_; session_params.proxy_service = globals_->proxy_script_fetcher_proxy_service.get(); TRACE_EVENT_BEGIN0("startup", "IOThread::InitAsync:HttpNetworkSession"); scoped_refptr<net::HttpNetworkSession> network_session( new net::HttpNetworkSession(session_params)); globals_->proxy_script_fetcher_http_transaction_factory .reset(new net::HttpNetworkLayer(network_session.get())); TRACE_EVENT_END0("startup", "IOThread::InitAsync:HttpNetworkSession"); scoped_ptr<net::URLRequestJobFactoryImpl> job_factory( new net::URLRequestJobFactoryImpl()); job_factory->SetProtocolHandler(chrome::kDataScheme, new net::DataProtocolHandler()); job_factory->SetProtocolHandler( chrome::kFileScheme, new net::FileProtocolHandler( content::BrowserThread::GetBlockingPool()-> GetTaskRunnerWithShutdownBehavior( base::SequencedWorkerPool::SKIP_ON_SHUTDOWN))); #if !defined(DISABLE_FTP_SUPPORT) globals_->proxy_script_fetcher_ftp_transaction_factory.reset( new net::FtpNetworkLayer(globals_->host_resolver.get())); job_factory->SetProtocolHandler( content::kFtpScheme, new net::FtpProtocolHandler( globals_->proxy_script_fetcher_ftp_transaction_factory.get())); #endif globals_->proxy_script_fetcher_url_request_job_factory = job_factory.PassAs<net::URLRequestJobFactory>(); globals_->throttler_manager.reset(new net::URLRequestThrottlerManager()); globals_->throttler_manager->set_net_log(net_log_); globals_->throttler_manager->set_enable_thread_checks(true); globals_->proxy_script_fetcher_context.reset( ConstructProxyScriptFetcherContext(globals_, net_log_)); globals_->network_time_notifier.reset( new net::NetworkTimeNotifier( scoped_ptr<base::TickClock>(new base::DefaultTickClock()))); sdch_manager_ = new net::SdchManager(); #if defined(OS_MACOSX) && !defined(OS_IOS) BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&ObserveKeychainEvents)); #endif BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&IOThread::InitSystemRequestContext, weak_factory_.GetWeakPtr())); } Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416
0
113,515
Analyze the following 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 MagickBooleanType GammaImage(Image *image,const double gamma, ExceptionInfo *exception) { #define GammaImageTag "Gamma/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; Quantum *gamma_map; register ssize_t i; ssize_t y; /* Allocate and initialize gamma maps. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (gamma == 1.0) return(MagickTrue); gamma_map=(Quantum *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*gamma_map)); if (gamma_map == (Quantum *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); (void) memset(gamma_map,0,(MaxMap+1)*sizeof(*gamma_map)); if (gamma != 0.0) for (i=0; i <= (ssize_t) MaxMap; i++) gamma_map[i]=ScaleMapToQuantum((double) (MaxMap*pow((double) i/ MaxMap,1.0/gamma))); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Gamma-correct colormap. */ if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].red))]; if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].green))]; if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].blue))]; if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].alpha))]; } /* Gamma-correct image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=gamma_map[ScaleQuantumToMap(ClampToQuantum((MagickRealType) q[j]))]; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,GammaImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); gamma_map=(Quantum *) RelinquishMagickMemory(gamma_map); if (image->gamma != 0.0) image->gamma*=gamma; return(status); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1611 CWE ID: CWE-119
0
88,997
Analyze the following 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 UpdateButtonMap() { XButtonMap::GetInstance()->UpdateMapping(); } Commit Message: Make shared memory segments writable only by their rightful owners. BUG=143859 TEST=Chrome's UI still works on Linux and Chrome OS Review URL: https://chromiumcodereview.appspot.com/10854242 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158289 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
0
119,217
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: kdc_get_ticket_renewtime(kdc_realm_t *realm, krb5_kdc_req *request, krb5_enc_tkt_part *tgt, krb5_db_entry *client, krb5_db_entry *server, krb5_enc_tkt_part *tkt) { krb5_timestamp rtime, max_rlife; clear(tkt->flags, TKT_FLG_RENEWABLE); tkt->times.renew_till = 0; /* Don't issue renewable tickets if the client or server don't allow it, * or if this is a TGS request and the TGT isn't renewable. */ if (server->attributes & KRB5_KDB_DISALLOW_RENEWABLE) return; if (client != NULL && (client->attributes & KRB5_KDB_DISALLOW_RENEWABLE)) return; if (tgt != NULL && !(tgt->flags & TKT_FLG_RENEWABLE)) return; /* Determine the requested renewable time. */ if (isflagset(request->kdc_options, KDC_OPT_RENEWABLE)) rtime = request->rtime ? request->rtime : kdc_infinity; else if (isflagset(request->kdc_options, KDC_OPT_RENEWABLE_OK) && ts_after(request->till, tkt->times.endtime)) rtime = request->till; else return; /* Truncate it to the allowable renewable time. */ if (tgt != NULL) rtime = ts_min(rtime, tgt->times.renew_till); max_rlife = min(server->max_renewable_life, realm->realm_maxrlife); if (client != NULL) max_rlife = min(max_rlife, client->max_renewable_life); rtime = ts_min(rtime, ts_incr(tkt->times.starttime, max_rlife)); /* If the client only specified renewable-ok, don't issue a renewable * ticket unless the truncated renew time exceeds the ticket end time. */ if (!isflagset(request->kdc_options, KDC_OPT_RENEWABLE) && !ts_after(rtime, tkt->times.endtime)) return; setflag(tkt->flags, TKT_FLG_RENEWABLE); tkt->times.renew_till = rtime; } Commit Message: Ignore password attributes for S4U2Self requests For consistency with Windows KDCs, allow protocol transition to work even if the password has expired or needs changing. Also, when looking up an enterprise principal with an AS request, treat ERR_KEY_EXP as confirmation that the client is present in the realm. [ghudson@mit.edu: added comment in kdc_process_s4u2self_req(); edited commit message] ticket: 8763 (new) tags: pullup target_version: 1.17 CWE ID: CWE-617
0
75,476
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: pvscsi_on_command_data(PVSCSIState *s, uint32_t value) { size_t bytes_arrived = s->curr_cmd_data_cntr * sizeof(uint32_t); assert(bytes_arrived < sizeof(s->curr_cmd_data)); s->curr_cmd_data[s->curr_cmd_data_cntr++] = value; pvscsi_do_command_processing(s); } Commit Message: CWE ID: CWE-399
0
8,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: static void activityLoggingGetterForAllWorldsLongAttributeAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); V8PerContextData* contextData = V8PerContextData::from(info.GetIsolate()->GetCurrentContext()); if (contextData && contextData->activityLogger()) contextData->activityLogger()->log("TestObjectPython.activityLoggingGetterForAllWorldsLongAttribute", 0, 0, "Getter"); TestObjectPythonV8Internal::activityLoggingGetterForAllWorldsLongAttributeAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } Commit Message: document.location bindings fix BUG=352374 R=jochen@chromium.org Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
0
122,108
Analyze the following 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 dom_document_recover_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->recover = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } Commit Message: CWE ID: CWE-254
0
15,072
Analyze the following 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 AppLayerProtoDetectConfProtoDetectionEnabled(const char *ipproto, const char *alproto) { SCEnter(); BUG_ON(ipproto == NULL || alproto == NULL); int enabled = 1; char param[100]; ConfNode *node; int r; #ifdef AFLFUZZ_APPLAYER goto enabled; #endif if (RunmodeIsUnittests()) goto enabled; r = snprintf(param, sizeof(param), "%s%s%s", "app-layer.protocols.", alproto, ".enabled"); if (r < 0) { SCLogError(SC_ERR_FATAL, "snprintf failure."); exit(EXIT_FAILURE); } else if (r > (int)sizeof(param)) { SCLogError(SC_ERR_FATAL, "buffer not big enough to write param."); exit(EXIT_FAILURE); } node = ConfGetNode(param); if (node == NULL) { SCLogDebug("Entry for %s not found.", param); r = snprintf(param, sizeof(param), "%s%s%s%s%s", "app-layer.protocols.", alproto, ".", ipproto, ".enabled"); if (r < 0) { SCLogError(SC_ERR_FATAL, "snprintf failure."); exit(EXIT_FAILURE); } else if (r > (int)sizeof(param)) { SCLogError(SC_ERR_FATAL, "buffer not big enough to write param."); exit(EXIT_FAILURE); } node = ConfGetNode(param); if (node == NULL) { SCLogDebug("Entry for %s not found.", param); goto enabled; } } if (node->val) { if (ConfValIsTrue(node->val)) { goto enabled; } else if (ConfValIsFalse(node->val)) { goto disabled; } else if (strcasecmp(node->val, "detection-only") == 0) { goto enabled; } } /* Invalid or null value. */ SCLogError(SC_ERR_FATAL, "Invalid value found for %s.", param); exit(EXIT_FAILURE); disabled: enabled = 0; enabled: SCReturnInt(enabled); } Commit Message: proto/detect: workaround dns misdetected as dcerpc The DCERPC UDP detection would misfire on DNS with transaction ID 0x0400. This would happen as the protocol detection engine gives preference to pattern based detection over probing parsers for performance reasons. This hack/workaround fixes this specific case by still running the probing parser if DCERPC has been detected on UDP. The probing parser result will take precedence. Bug #2736. CWE ID: CWE-20
0
96,467
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: transpose_path(gx_path *path) { segment *s = (segment *)path->first_subpath; exch(path->bbox.p.x, path->bbox.p.y); exch(path->bbox.q.x, path->bbox.q.y); for (; s; s = s->next) { if (s->type == s_curve) { curve_segment *c = (curve_segment *)s; exch(c->p1.x, c->p1.y); exch(c->p2.x, c->p2.y); } exch(s->pt.x, s->pt.y); } } Commit Message: CWE ID: CWE-125
0
5,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: main(int argc, char * * argv) { const char command0[] = { 0x00, 0x00 }; char command1[] = "\x01\x00urn:schemas-upnp-org:device:InternetGatewayDevice"; char command2[] = "\x02\x00uuid:fc4ec57e-b051-11db-88f8-0060085db3f6::upnp:rootdevice"; const char command3[] = { 0x03, 0x00 }; /* old versions of minissdpd would reject a command with * a zero length string argument */ char command3compat[] = "\x03\x00ssdp:all"; char command4[] = "\x04\x00test:test:test"; const char bad_command[] = { 0xff, 0xff }; const char overflow[] = { 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; const char command5[] = { 0x05, 0x00 }; int s; int i; void * tmp; unsigned char * resp = NULL; size_t respsize = 0; unsigned char buf[4096]; ssize_t n; int total = 0; const char * sockpath = "/var/run/minissdpd.sock"; for(i=0; i<argc-1; i++) { if(0==strcmp(argv[i], "-s")) sockpath = argv[++i]; } command1[1] = sizeof(command1) - 3; command2[1] = sizeof(command2) - 3; command3compat[1] = sizeof(command3compat) - 3; command4[1] = sizeof(command4) - 3; s = connect_unix_socket(sockpath); n = SENDCOMMAND(command0, sizeof(command0)); n = read(s, buf, sizeof(buf)); printf("Response received %d bytes\n", (int)n); if(n > 0) { printversion(buf, n); } else { printf("Command 0 (get version) not supported\n"); close(s); s = connect_unix_socket(sockpath); } n = SENDCOMMAND(command1, sizeof(command1) - 1); n = read(s, buf, sizeof(buf)); printf("Response received %d bytes\n", (int)n); printresponse(buf, n); if(n == 0) { close(s); s = connect_unix_socket(sockpath); } n = SENDCOMMAND(command2, sizeof(command2) - 1); n = read(s, buf, sizeof(buf)); printf("Response received %d bytes\n", (int)n); printresponse(buf, n); if(n == 0) { close(s); s = connect_unix_socket(sockpath); } buf[0] = 0; /* Slight hack for printing num devices when 0 */ n = SENDCOMMAND(command3, sizeof(command3)); n = read(s, buf, sizeof(buf)); if(n == 0) { printf("command3 failed, testing compatible one\n"); close(s); s = connect_unix_socket(sockpath); n = SENDCOMMAND(command3compat, sizeof(command3compat) - 1); n = read(s, buf, sizeof(buf)); } printf("Response received %d bytes\n", (int)n); printf("Number of devices %d\n", (int)buf[0]); while(n > 0) { tmp = realloc(resp, respsize + n); if(tmp == NULL) { fprintf(stderr, "memory allocation error\n"); break; } resp = tmp; respsize += n; if (n > 0) { memcpy(resp + total, buf, n); total += n; } if (n < (ssize_t)sizeof(buf)) { break; } n = read(s, buf, sizeof(buf)); printf("response received %d bytes\n", (int)n); } if(resp != NULL) { printresponse(resp, total); free(resp); resp = NULL; } if(n == 0) { close(s); s = connect_unix_socket(sockpath); } n = SENDCOMMAND(command4, sizeof(command4)); /* no response for request type 4 */ n = SENDCOMMAND(bad_command, sizeof(bad_command)); n = read(s, buf, sizeof(buf)); printf("Response received %d bytes\n", (int)n); printresponse(buf, n); if(n == 0) { close(s); s = connect_unix_socket(sockpath); } n = SENDCOMMAND(overflow, sizeof(overflow)); n = read(s, buf, sizeof(buf)); printf("Response received %d bytes\n", (int)n); printresponse(buf, n); if(n == 0) { close(s); s = connect_unix_socket(sockpath); } n = SENDCOMMAND(command5, sizeof(command5)); n = read(s, buf, sizeof(buf)); printf("Response received %d bytes\n", (int)n); printresponse(buf, n); close(s); return 0; } Commit Message: minissdpd: Fix broken overflow test (p+l > buf+n) thanks to Salva Piero CWE ID: CWE-125
1
168,845
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int sha1_neon_final(struct shash_desc *desc, u8 *out) { struct sha1_state *sctx = shash_desc_ctx(desc); unsigned int i, index, padlen; __be32 *dst = (__be32 *)out; __be64 bits; static const u8 padding[SHA1_BLOCK_SIZE] = { 0x80, }; bits = cpu_to_be64(sctx->count << 3); /* Pad out to 56 mod 64 and append length */ index = sctx->count % SHA1_BLOCK_SIZE; padlen = (index < 56) ? (56 - index) : ((SHA1_BLOCK_SIZE+56) - index); if (!may_use_simd()) { sha1_update_arm(desc, padding, padlen); sha1_update_arm(desc, (const u8 *)&bits, sizeof(bits)); } else { kernel_neon_begin(); /* We need to fill a whole block for __sha1_neon_update() */ if (padlen <= 56) { sctx->count += padlen; memcpy(sctx->buffer + index, padding, padlen); } else { __sha1_neon_update(desc, padding, padlen, index); } __sha1_neon_update(desc, (const u8 *)&bits, sizeof(bits), 56); kernel_neon_end(); } /* Store state in digest */ for (i = 0; i < 5; i++) dst[i] = cpu_to_be32(sctx->state[i]); /* Wipe context */ memset(sctx, 0, sizeof(*sctx)); return 0; } Commit Message: crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <keescook@chromium.org> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> CWE ID: CWE-264
0
46,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: void BeginInstallWithManifestFunction::OnParseSuccess( const SkBitmap& icon, DictionaryValue* parsed_manifest) { CHECK(parsed_manifest); icon_ = icon; parsed_manifest_.reset(parsed_manifest); std::string init_errors; dummy_extension_ = Extension::Create( FilePath(), Extension::INTERNAL, *static_cast<DictionaryValue*>(parsed_manifest_.get()), Extension::NO_FLAGS, &init_errors); if (!dummy_extension_.get()) { OnParseFailure(MANIFEST_ERROR, std::string(kInvalidManifestError)); return; } if (icon_.empty()) icon_ = Extension::GetDefaultIcon(dummy_extension_->is_app()); ShowExtensionInstallDialog(profile(), this, dummy_extension_.get(), &icon_, dummy_extension_->GetPermissionMessageStrings(), ExtensionInstallUI::INSTALL_PROMPT); } Commit Message: Adding tests for new webstore beginInstallWithManifest method. BUG=75821 TEST=none Review URL: http://codereview.chromium.org/6900059 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@83080 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
1
170,405
Analyze the following 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 GfxIndexedColorSpace::getDefaultColor(GfxColor *color) { color->c[0] = 0; } Commit Message: CWE ID: CWE-189
0
1,035
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: base::TerminationStatus WebContentsImpl::GetCrashedStatus() const { return crashed_status_; } 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
110,628
Analyze the following 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 strictTypeCheckingTestInterfaceAttributeAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); TestObjectPythonV8Internal::strictTypeCheckingTestInterfaceAttributeAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } Commit Message: document.location bindings fix BUG=352374 R=jochen@chromium.org Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
0
122,667
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static u16 llcp_tlv16(u8 *tlv, u8 type) { if (tlv[0] != type || tlv[1] != llcp_tlv_length[tlv[0]]) return 0; return be16_to_cpu(*((__be16 *)(tlv + 2))); } Commit Message: net: nfc: Fix NULL dereference on nfc_llcp_build_tlv fails KASAN report this: BUG: KASAN: null-ptr-deref in nfc_llcp_build_gb+0x37f/0x540 [nfc] Read of size 3 at addr 0000000000000000 by task syz-executor.0/5401 CPU: 0 PID: 5401 Comm: syz-executor.0 Not tainted 5.0.0-rc7+ #45 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014 Call Trace: __dump_stack lib/dump_stack.c:77 [inline] dump_stack+0xfa/0x1ce lib/dump_stack.c:113 kasan_report+0x171/0x18d mm/kasan/report.c:321 memcpy+0x1f/0x50 mm/kasan/common.c:130 nfc_llcp_build_gb+0x37f/0x540 [nfc] nfc_llcp_register_device+0x6eb/0xb50 [nfc] nfc_register_device+0x50/0x1d0 [nfc] nfcsim_device_new+0x394/0x67d [nfcsim] ? 0xffffffffc1080000 nfcsim_init+0x6b/0x1000 [nfcsim] do_one_initcall+0xfa/0x5ca init/main.c:887 do_init_module+0x204/0x5f6 kernel/module.c:3460 load_module+0x66b2/0x8570 kernel/module.c:3808 __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902 do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe RIP: 0033:0x462e99 Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007f9cb79dcc58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139 RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99 RDX: 0000000000000000 RSI: 0000000020000280 RDI: 0000000000000003 RBP: 00007f9cb79dcc70 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 00007f9cb79dd6bc R13: 00000000004bcefb R14: 00000000006f7030 R15: 0000000000000004 nfc_llcp_build_tlv will return NULL on fails, caller should check it, otherwise will trigger a NULL dereference. Reported-by: Hulk Robot <hulkci@huawei.com> Fixes: eda21f16a5ed ("NFC: Set MIU and RW values from CONNECT and CC LLCP frames") Fixes: d646960f7986 ("NFC: Initial LLCP support") Signed-off-by: YueHaibing <yuehaibing@huawei.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-476
0
89,662
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: float LayerTreeHostImpl::TopControlsHeight() const { return active_tree_->top_controls_height(); } 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
137,388
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: ScopedFrameBufferBinder::ScopedFrameBufferBinder(GLES2DecoderImpl* decoder, GLuint id) : decoder_(decoder) { ScopedGLErrorSuppressor suppressor( "ScopedFrameBufferBinder::ctor", decoder_->GetErrorState()); glBindFramebufferEXT(GL_FRAMEBUFFER, id); decoder->OnFboChanged(); } Commit Message: Framebuffer clear() needs to consider the situation some draw buffers are disabled. This is when we expose DrawBuffers extension. BUG=376951 TEST=the attached test case, webgl conformance R=kbr@chromium.org,bajones@chromium.org Review URL: https://codereview.chromium.org/315283002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@275338 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
0
121,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: static int md5_init(struct shash_desc *desc) { struct md5_state *mctx = shash_desc_ctx(desc); mctx->hash[0] = 0x67452301; mctx->hash[1] = 0xefcdab89; mctx->hash[2] = 0x98badcfe; mctx->hash[3] = 0x10325476; mctx->byte_count = 0; return 0; } Commit Message: crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <keescook@chromium.org> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> CWE ID: CWE-264
0
47,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: PreconnectManager::PreconnectManager(base::WeakPtr<Delegate> delegate, Profile* profile) : delegate_(std::move(delegate)), profile_(profile), inflight_preresolves_count_(0) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(profile_); } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <lukasza@chromium.org> Reviewed-by: Alex Ilin <alexilin@chromium.org> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125
0
136,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: int csum_len_for_type(int cst) { switch (cst) { case CSUM_NONE: return 1; case CSUM_MD4_ARCHAIC: return 2; case CSUM_MD4: case CSUM_MD4_OLD: case CSUM_MD4_BUSTED: return MD4_DIGEST_LEN; case CSUM_MD5: return MD5_DIGEST_LEN; } return 0; } Commit Message: CWE ID: CWE-354
0
1,626
Analyze the following 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 atalk_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct sockaddr_at sat; struct sock *sk = sock->sk; struct atalk_sock *at = at_sk(sk); int err; lock_sock(sk); err = -ENOBUFS; if (sock_flag(sk, SOCK_ZAPPED)) if (atalk_autobind(sk) < 0) goto out; *uaddr_len = sizeof(struct sockaddr_at); memset(&sat, 0, sizeof(sat)); if (peer) { err = -ENOTCONN; if (sk->sk_state != TCP_ESTABLISHED) goto out; sat.sat_addr.s_net = at->dest_net; sat.sat_addr.s_node = at->dest_node; sat.sat_port = at->dest_port; } else { sat.sat_addr.s_net = at->src_net; sat.sat_addr.s_node = at->src_node; sat.sat_port = at->src_port; } err = 0; sat.sat_family = AF_APPLETALK; memcpy(uaddr, &sat, sizeof(sat)); out: release_sock(sk); return err; } 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
40,314
Analyze the following 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 ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt) { int nblanks = 0; struct logblank_t blanks[4]; char *str; int slen; /* * For outgoing packets, pkt->length represents the length of the * whole packet starting at pkt->data (including some header), and * pkt->body refers to the point within that where the log-worthy * payload begins. However, incoming packets expect pkt->length to * represent only the payload length (that is, it's measured from * pkt->body not from pkt->data). Temporarily adjust our outgoing * packet to conform to the incoming-packet semantics, so that we * can analyse it with the ssh_pkt_get functions. */ pkt->length -= (pkt->body - pkt->data); pkt->savedpos = 0; if (ssh->logomitdata && (pkt->type == SSH1_CMSG_STDIN_DATA || pkt->type == SSH1_MSG_CHANNEL_DATA)) { /* "Session data" packets - omit the data string. */ if (pkt->type == SSH1_MSG_CHANNEL_DATA) ssh_pkt_getuint32(pkt); /* skip channel id */ blanks[nblanks].offset = pkt->savedpos + 4; blanks[nblanks].type = PKTLOG_OMIT; ssh_pkt_getstring(pkt, &str, &slen); if (str) { blanks[nblanks].len = slen; nblanks++; } } if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD || pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE || pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) && conf_get_int(ssh->conf, CONF_logomitpass)) { /* If this is a password or similar packet, blank the password(s). */ blanks[nblanks].offset = 0; blanks[nblanks].len = pkt->length; blanks[nblanks].type = PKTLOG_BLANK; nblanks++; } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING && conf_get_int(ssh->conf, CONF_logomitpass)) { /* * If this is an X forwarding request packet, blank the fake * auth data. * * Note that while we blank the X authentication data here, we * don't take any special action to blank the start of an X11 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening * an X connection without having session blanking enabled is * likely to leak your cookie into the log. */ pkt->savedpos = 0; ssh_pkt_getstring(pkt, &str, &slen); blanks[nblanks].offset = pkt->savedpos; blanks[nblanks].type = PKTLOG_BLANK; ssh_pkt_getstring(pkt, &str, &slen); if (str) { blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset; nblanks++; } } log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12], ssh1_pkt_type(pkt->data[12]), pkt->body, pkt->length, nblanks, blanks, NULL, 0, NULL); /* * Undo the above adjustment of pkt->length, to put the packet * back in the state we found it. */ pkt->length += (pkt->body - pkt->data); } Commit Message: CWE ID: CWE-119
0
8,528
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool GLES2DecoderPassthroughImpl::ClearCompressedTextureLevel(Texture* texture, unsigned target, int level, unsigned format, int width, int height) { return true; } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <kbr@chromium.org> Reviewed-by: Kentaro Hara <haraken@chromium.org> Reviewed-by: Geoff Lang <geofflang@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416
0
141,736
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void eventHandlerAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); TestInterfaceNode* impl = V8TestInterfaceNode::toImpl(holder); EventListener* cppValue(WTF::getPtr(impl->eventHandlerAttribute())); v8SetReturnValue(info, cppValue ? V8AbstractEventListener::cast(cppValue)->getListenerOrNull(info.GetIsolate(), impl->getExecutionContext()) : v8::Null(info.GetIsolate()).As<v8::Value>()); } Commit Message: binding: Removes unused code in templates/attributes.cpp. Faking {{cpp_class}} and {{c8_class}} doesn't make sense. Probably it made sense before the introduction of virtual ScriptWrappable::wrap(). Checking the existence of window->document() doesn't seem making sense to me, and CQ tests seem passing without the check. BUG= Review-Url: https://codereview.chromium.org/2268433002 Cr-Commit-Position: refs/heads/master@{#413375} CWE ID: CWE-189
0
119,257
Analyze the following 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 UpdateWebTouchEventAfterDispatch(WebKit::WebTouchEvent* event, WebKit::WebTouchPoint* point) { if (point->state != WebKit::WebTouchPoint::StateReleased && point->state != WebKit::WebTouchPoint::StateCancelled) return; --event->touchesLength; for (unsigned i = point - event->touches; i < event->touchesLength; ++i) { event->touches[i] = event->touches[i + 1]; } } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
0
114,913
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static double KernelBessel_Q1(const double x) { double p, q; register long i; static const double Pone[] = { 0.3511751914303552822533318e+3, 0.7210391804904475039280863e+3, 0.4259873011654442389886993e+3, 0.831898957673850827325226e+2, 0.45681716295512267064405e+1, 0.3532840052740123642735e-1 }, Qone[] = { 0.74917374171809127714519505e+4, 0.154141773392650970499848051e+5, 0.91522317015169922705904727e+4, 0.18111867005523513506724158e+4, 0.1038187585462133728776636e+3, 0.1e+1 }; p = Pone[5]; q = Qone[5]; for (i=4; i >= 0; i--) { p = p*(8.0/x)*(8.0/x)+Pone[i]; q = q*(8.0/x)*(8.0/x)+Qone[i]; } return (double)(p/q); } Commit Message: gdImageScaleTwoPass memory leak fix Fixing memory leak in gdImageScaleTwoPass, as reported by @cmb69 and confirmed by @vapier. This bug actually bit me in production and I'm very thankful that it was reported with an easy fix. Fixes #173. CWE ID: CWE-399
0
56,306
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: rdpsnd_init(char *optarg) { struct audio_driver *pos; char *driver = NULL, *options = NULL; drivers = NULL; packet.data = (uint8 *) xmalloc(65536); packet.p = packet.end = packet.data; packet.size = 0; rdpsnd_channel = channel_register("rdpsnd", CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP, rdpsnd_process); rdpsnddbg_channel = channel_register("snddbg", CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP, rdpsnddbg_process); if ((rdpsnd_channel == NULL) || (rdpsnddbg_channel == NULL)) { logger(Sound, Error, "rdpsnd_init(), failed to register rdpsnd / snddbg virtual channels"); return False; } rdpsnd_queue_init(); if (optarg != NULL && strlen(optarg) > 0) { driver = options = optarg; while (*options != '\0' && *options != ':') options++; if (*options == ':') { *options = '\0'; options++; } if (*options == '\0') options = NULL; } rdpsnd_register_drivers(options); if (!driver) return True; pos = drivers; while (pos != NULL) { if (!strcmp(pos->name, driver)) { logger(Sound, Debug, "rdpsnd_init(), using driver '%s'", pos->name); current_driver = pos; return True; } pos = pos->next; } return False; } Commit Message: Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182 CWE ID: CWE-119
0
93,061
Analyze the following 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 bool SearchBuffer::isWordStartMatch(size_t start, size_t length) const { ASSERT(m_options & AtWordStarts); if (!start) return true; int size = m_buffer.size(); int offset = start; UChar32 firstCharacter; U16_GET(m_buffer.data(), 0, offset, size, firstCharacter); if (m_options & TreatMedialCapitalAsWordStart) { UChar32 previousCharacter; U16_PREV(m_buffer.data(), 0, offset, previousCharacter); if (isSeparator(firstCharacter)) { if (!isSeparator(previousCharacter)) return true; } else if (isASCIIUpper(firstCharacter)) { if (!isASCIIUpper(previousCharacter)) return true; offset = start; U16_FWD_1(m_buffer.data(), offset, size); UChar32 nextCharacter = 0; if (offset < size) U16_GET(m_buffer.data(), 0, offset, size, nextCharacter); if (!isASCIIUpper(nextCharacter) && !isASCIIDigit(nextCharacter) && !isSeparator(nextCharacter)) return true; } else if (isASCIIDigit(firstCharacter)) { if (!isASCIIDigit(previousCharacter)) return true; } else if (isSeparator(previousCharacter) || isASCIIDigit(previousCharacter)) { return true; } } if (Font::isCJKIdeographOrSymbol(firstCharacter)) return true; size_t wordBreakSearchStart = start + length; while (wordBreakSearchStart > start) wordBreakSearchStart = findNextWordFromIndex(m_buffer.data(), m_buffer.size(), wordBreakSearchStart, false /* backwards */); return wordBreakSearchStart == start; } Commit Message: Upgrade a TextIterator ASSERT to a RELEASE_ASSERT as a defensive measure. BUG=156930,177197 R=inferno@chromium.org Review URL: https://codereview.chromium.org/15057010 git-svn-id: svn://svn.chromium.org/blink/trunk@150123 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
0
113,334
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: blink::WebNavigationPolicy RenderFrameImpl::decidePolicyForNavigation( const NavigationPolicyInfo& info) { DCHECK(!frame_ || frame_ == info.frame); return DecidePolicyForNavigation(this, info); } Commit Message: Connect WebUSB client interface to the devices app This provides a basic WebUSB client interface in content/renderer. Most of the interface is unimplemented, but this CL hooks up navigator.usb.getDevices() to the browser's Mojo devices app to enumerate available USB devices. BUG=492204 Review URL: https://codereview.chromium.org/1293253002 Cr-Commit-Position: refs/heads/master@{#344881} CWE ID: CWE-399
0
123,213
Analyze the following 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 ExtensionOptionsGuest::GetTaskPrefix() const { return IDS_EXTENSION_TASK_MANAGER_EXTENSIONOPTIONS_TAG_PREFIX; } Commit Message: Make extensions use a correct same-origin check. GURL::GetOrigin does not do the right thing for all types of URLs. BUG=573317 Review URL: https://codereview.chromium.org/1658913002 Cr-Commit-Position: refs/heads/master@{#373381} CWE ID: CWE-284
0
132,979
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: InputHandlerProxy::EventDisposition InputHandlerProxy::HitTestTouchEvent( const blink::WebTouchEvent& touch_event, bool* is_touching_scrolling_layer, cc::TouchAction* white_listed_touch_action) { *is_touching_scrolling_layer = false; EventDisposition result = DROP_EVENT; for (size_t i = 0; i < touch_event.touches_length; ++i) { if (touch_event.touch_start_or_first_touch_move) DCHECK(white_listed_touch_action); else DCHECK(!white_listed_touch_action); if (touch_event.GetType() == WebInputEvent::kTouchStart && touch_event.touches[i].state != WebTouchPoint::kStatePressed) { continue; } cc::TouchAction touch_action = cc::kTouchActionAuto; cc::InputHandler::TouchStartOrMoveEventListenerType event_listener_type = input_handler_->EventListenerTypeForTouchStartOrMoveAt( gfx::Point(touch_event.touches[i].PositionInWidget().x, touch_event.touches[i].PositionInWidget().y), &touch_action); if (white_listed_touch_action) *white_listed_touch_action &= touch_action; if (event_listener_type != cc::InputHandler::TouchStartOrMoveEventListenerType::NO_HANDLER) { *is_touching_scrolling_layer = event_listener_type == cc::InputHandler::TouchStartOrMoveEventListenerType:: HANDLER_ON_SCROLLING_LAYER; if (compositor_touch_action_enabled_ && white_listed_touch_action && *white_listed_touch_action != cc::kTouchActionNone) result = DID_HANDLE_NON_BLOCKING; else result = DID_NOT_HANDLE; break; } } if (result == DROP_EVENT) { switch (input_handler_->GetEventListenerProperties( cc::EventListenerClass::kTouchStartOrMove)) { case cc::EventListenerProperties::kPassive: result = DID_HANDLE_NON_BLOCKING; break; case cc::EventListenerProperties::kBlocking: result = DROP_EVENT; break; case cc::EventListenerProperties::kBlockingAndPassive: result = DID_HANDLE_NON_BLOCKING; break; case cc::EventListenerProperties::kNone: result = DROP_EVENT; break; default: NOTREACHED(); result = DROP_EVENT; break; } } if (result == DROP_EVENT && (skip_touch_filter_all_ || (skip_touch_filter_discrete_ && touch_event.GetType() == WebInputEvent::kTouchStart))) result = DID_HANDLE_NON_BLOCKING; if (touch_result_ == kEventDispositionUndefined || touch_result_ == DROP_EVENT || result == DID_NOT_HANDLE) touch_result_ = result; return result; } Commit Message: Revert "Add explicit flag for compositor scrollbar injected gestures" This reverts commit d9a56afcbdf9850bc39bb3edb56d07d11a1eb2b2. Reason for revert: Findit (https://goo.gl/kROfz5) identified CL at revision 669086 as the culprit for flakes in the build cycles as shown on: https://analysis.chromium.org/p/chromium/flake-portal/analysis/culprit?key=ag9zfmZpbmRpdC1mb3ItbWVyQwsSDEZsYWtlQ3VscHJpdCIxY2hyb21pdW0vZDlhNTZhZmNiZGY5ODUwYmMzOWJiM2VkYjU2ZDA3ZDExYTFlYjJiMgw Sample Failed Build: https://ci.chromium.org/buildbot/chromium.chromiumos/linux-chromeos-rel/25818 Sample Failed Step: content_browsertests on Ubuntu-16.04 Sample Flaky Test: ScrollLatencyScrollbarBrowserTest.ScrollbarThumbDragLatency Original change's description: > Add explicit flag for compositor scrollbar injected gestures > > The original change to enable scrollbar latency for the composited > scrollbars incorrectly used an existing member to try and determine > whether a GestureScrollUpdate was the first one in an injected sequence > or not. is_first_gesture_scroll_update_ was incorrect because it is only > updated when input is actually dispatched to InputHandlerProxy, and the > flag is cleared for all GSUs before the location where it was being > read. > > This bug was missed because of incorrect tests. The > VerifyRecordedSamplesForHistogram method doesn't actually assert or > expect anything - the return value must be inspected. > > As part of fixing up the tests, I made a few other changes to get them > passing consistently across all platforms: > - turn on main thread scrollbar injection feature (in case it's ever > turned off we don't want the tests to start failing) > - enable mock scrollbars > - disable smooth scrolling > - don't run scrollbar tests on Android > > The composited scrollbar button test is disabled due to a bug in how > the mock theme reports its button sizes, which throws off the region > detection in ScrollbarLayerImplBase::IdentifyScrollbarPart (filed > crbug.com/974063 for this issue). > > Change-Id: Ie1a762a5f6ecc264d22f0256db68f141fc76b950 > > Bug: 954007 > Change-Id: Ib258e08e083e79da90ba2e4e4216e4879cf00cf7 > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1652741 > Commit-Queue: Daniel Libby <dlibby@microsoft.com> > Reviewed-by: David Bokan <bokan@chromium.org> > Cr-Commit-Position: refs/heads/master@{#669086} Change-Id: Icc743e48fa740fe27f0cb0cfa21b209a696f518c No-Presubmit: true No-Tree-Checks: true No-Try: true Bug: 954007 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1660114 Cr-Commit-Position: refs/heads/master@{#669150} CWE ID: CWE-281
0
137,977
Analyze the following 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 crypto_rng_init_tfm(struct crypto_tfm *tfm) { struct crypto_rng *rng = __crypto_rng_cast(tfm); struct rng_alg *alg = crypto_rng_alg(rng); struct old_rng_alg *oalg = crypto_old_rng_alg(rng); if (oalg->rng_make_random) { rng->generate = generate; rng->seed = rngapi_reset; rng->seedsize = oalg->seedsize; return 0; } rng->generate = alg->generate; rng->seed = alg->seed; rng->seedsize = alg->seedsize; return 0; } Commit Message: crypto: rng - Remove old low-level rng interface Now that all rng implementations have switched over to the new interface, we can remove the old low-level interface. Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> CWE ID: CWE-476
1
167,731
Analyze the following 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_reconnect(struct TCP_Server_Info *server) { int rc = 0; struct list_head *tmp, *tmp2; struct cifsSesInfo *ses; struct cifsTconInfo *tcon; struct mid_q_entry *mid_entry; spin_lock(&GlobalMid_Lock); if (server->tcpStatus == CifsExiting) { /* the demux thread will exit normally next time through the loop */ spin_unlock(&GlobalMid_Lock); return rc; } else server->tcpStatus = CifsNeedReconnect; spin_unlock(&GlobalMid_Lock); server->maxBuf = 0; cFYI(1, "Reconnecting tcp session"); /* before reconnecting the tcp session, mark the smb session (uid) and the tid bad so they are not used until reconnected */ read_lock(&cifs_tcp_ses_lock); list_for_each(tmp, &server->smb_ses_list) { ses = list_entry(tmp, struct cifsSesInfo, smb_ses_list); ses->need_reconnect = true; ses->ipc_tid = 0; list_for_each(tmp2, &ses->tcon_list) { tcon = list_entry(tmp2, struct cifsTconInfo, tcon_list); tcon->need_reconnect = true; } } read_unlock(&cifs_tcp_ses_lock); /* do not want to be sending data on a socket we are freeing */ mutex_lock(&server->srv_mutex); if (server->ssocket) { cFYI(1, "State: 0x%x Flags: 0x%lx", server->ssocket->state, server->ssocket->flags); kernel_sock_shutdown(server->ssocket, SHUT_WR); cFYI(1, "Post shutdown state: 0x%x Flags: 0x%lx", server->ssocket->state, server->ssocket->flags); sock_release(server->ssocket); server->ssocket = 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->midState == MID_REQUEST_SUBMITTED) { /* Mark other intransit requests as needing retry so we do not immediately mark the session bad again (ie after we reconnect below) as they timeout too */ mid_entry->midState = MID_RETRY_NEEDED; } } spin_unlock(&GlobalMid_Lock); mutex_unlock(&server->srv_mutex); while ((server->tcpStatus != CifsExiting) && (server->tcpStatus != CifsGood)) { try_to_freeze(); if (server->addr.sockAddr6.sin6_family == AF_INET6) rc = ipv6_connect(server); else rc = ipv4_connect(server); if (rc) { cFYI(1, "reconnect error %d", rc); msleep(3000); } else { atomic_inc(&tcpSesReconnectCount); spin_lock(&GlobalMid_Lock); if (server->tcpStatus != CifsExiting) server->tcpStatus = CifsGood; server->sequence_number = 0; spin_unlock(&GlobalMid_Lock); /* atomic_set(&server->inFlight,0);*/ wake_up(&server->response_q); } } return rc; } 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
35,150
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int rewrite_data_page(struct f2fs_io_info *fio) { fio->new_blkaddr = fio->old_blkaddr; stat_inc_inplace_blocks(fio->sbi); return f2fs_submit_page_bio(fio); } Commit Message: f2fs: fix a panic caused by NULL flush_cmd_control Mount fs with option noflush_merge, boot failed for illegal address fcc in function f2fs_issue_flush: if (!test_opt(sbi, FLUSH_MERGE)) { ret = submit_flush_wait(sbi); atomic_inc(&fcc->issued_flush); -> Here, fcc illegal return ret; } Signed-off-by: Yunlei He <heyunlei@huawei.com> Signed-off-by: Jaegeuk Kim <jaegeuk@kernel.org> CWE ID: CWE-476
0
85,423
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: keydirection2ascii (int kd, bool remote) { if (kd == KEY_DIRECTION_BIDIRECTIONAL) return NULL; else if (kd == KEY_DIRECTION_NORMAL) return remote ? "1" : "0"; else if (kd == KEY_DIRECTION_INVERSE) return remote ? "0" : "1"; else { ASSERT (0); } return NULL; /* NOTREACHED */ } Commit Message: Use constant time memcmp when comparing HMACs in openvpn_decrypt. Signed-off-by: Steffan Karger <steffan.karger@fox-it.com> Acked-by: Gert Doering <gert@greenie.muc.de> Signed-off-by: Gert Doering <gert@greenie.muc.de> CWE ID: CWE-200
0
32,018
Analyze the following 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 ahci_check_irq(AHCIState *s) { int i; DPRINTF(-1, "check irq %#x\n", s->control_regs.irqstatus); s->control_regs.irqstatus = 0; for (i = 0; i < s->ports; i++) { AHCIPortRegs *pr = &s->dev[i].port_regs; if (pr->irq_stat & pr->irq_mask) { s->control_regs.irqstatus |= (1 << i); } } if (s->control_regs.irqstatus && (s->control_regs.ghc & HOST_CTL_IRQ_EN)) { ahci_irq_raise(s, NULL); } else { ahci_irq_lower(s, NULL); } } Commit Message: CWE ID: CWE-772
0
5,854
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: OfflinerPolicy* policy() const { return policy_.get(); } Commit Message: Remove unused histograms from the background loader offliner. Bug: 975512 Change-Id: I87b0a91bed60e3a9e8a1fd9ae9b18cac27a0859f Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1683361 Reviewed-by: Cathy Li <chili@chromium.org> Reviewed-by: Steven Holte <holte@chromium.org> Commit-Queue: Peter Williamson <petewil@chromium.org> Cr-Commit-Position: refs/heads/master@{#675332} CWE ID: CWE-119
0
139,165
Analyze the following 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 unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg, enum mem_cgroup_events_index idx) { unsigned long val = 0; int cpu; for_each_online_cpu(cpu) val += per_cpu(memcg->stat->events[idx], cpu); #ifdef CONFIG_HOTPLUG_CPU spin_lock(&memcg->pcp_counter_lock); val += memcg->nocpu_base.events[idx]; spin_unlock(&memcg->pcp_counter_lock); #endif return val; } Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream. In some cases it may happen that pmd_none_or_clear_bad() is called with the mmap_sem hold in read mode. In those cases the huge page faults can allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a false positive from pmd_bad() that will not like to see a pmd materializing as trans huge. It's not khugepaged causing the problem, khugepaged holds the mmap_sem in write mode (and all those sites must hold the mmap_sem in read mode to prevent pagetables to go away from under them, during code review it seems vm86 mode on 32bit kernels requires that too unless it's restricted to 1 thread per process or UP builds). The race is only with the huge pagefaults that can convert a pmd_none() into a pmd_trans_huge(). Effectively all these pmd_none_or_clear_bad() sites running with mmap_sem in read mode are somewhat speculative with the page faults, and the result is always undefined when they run simultaneously. This is probably why it wasn't common to run into this. For example if the madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page fault, the hugepage will not be zapped, if the page fault runs first it will be zapped. Altering pmd_bad() not to error out if it finds hugepmds won't be enough to fix this, because zap_pmd_range would then proceed to call zap_pte_range (which would be incorrect if the pmd become a pmd_trans_huge()). The simplest way to fix this is to read the pmd in the local stack (regardless of what we read, no need of actual CPU barriers, only compiler barrier needed), and be sure it is not changing under the code that computes its value. Even if the real pmd is changing under the value we hold on the stack, we don't care. If we actually end up in zap_pte_range it means the pmd was not none already and it was not huge, and it can't become huge from under us (khugepaged locking explained above). All we need is to enforce that there is no way anymore that in a code path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad can run into a hugepmd. The overhead of a barrier() is just a compiler tweak and should not be measurable (I only added it for THP builds). I don't exclude different compiler versions may have prevented the race too by caching the value of *pmd on the stack (that hasn't been verified, but it wouldn't be impossible considering pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines and there's no external function called in between pmd_trans_huge and pmd_none_or_clear_bad). if (pmd_trans_huge(*pmd)) { if (next-addr != HPAGE_PMD_SIZE) { VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); split_huge_page_pmd(vma->vm_mm, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) continue; /* fall through */ } if (pmd_none_or_clear_bad(pmd)) Because this race condition could be exercised without special privileges this was reported in CVE-2012-1179. The race was identified and fully explained by Ulrich who debugged it. I'm quoting his accurate explanation below, for reference. ====== start quote ======= mapcount 0 page_mapcount 1 kernel BUG at mm/huge_memory.c:1384! At some point prior to the panic, a "bad pmd ..." message similar to the following is logged on the console: mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7). The "bad pmd ..." message is logged by pmd_clear_bad() before it clears the page's PMD table entry. 143 void pmd_clear_bad(pmd_t *pmd) 144 { -> 145 pmd_ERROR(*pmd); 146 pmd_clear(pmd); 147 } After the PMD table entry has been cleared, there is an inconsistency between the actual number of PMD table entries that are mapping the page and the page's map count (_mapcount field in struct page). When the page is subsequently reclaimed, __split_huge_page() detects this inconsistency. 1381 if (mapcount != page_mapcount(page)) 1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n", 1383 mapcount, page_mapcount(page)); -> 1384 BUG_ON(mapcount != page_mapcount(page)); The root cause of the problem is a race of two threads in a multithreaded process. Thread B incurs a page fault on a virtual address that has never been accessed (PMD entry is zero) while Thread A is executing an madvise() system call on a virtual address within the same 2 MB (huge page) range. virtual address space .---------------------. | | | | .-|---------------------| | | | | | |<-- B(fault) | | | 2 MB | |/////////////////////|-. huge < |/////////////////////| > A(range) page | |/////////////////////|-' | | | | | | '-|---------------------| | | | | '---------------------' - Thread A is executing an madvise(..., MADV_DONTNEED) system call on the virtual address range "A(range)" shown in the picture. sys_madvise // Acquire the semaphore in shared mode. down_read(&current->mm->mmap_sem) ... madvise_vma switch (behavior) case MADV_DONTNEED: madvise_dontneed zap_page_range unmap_vmas unmap_page_range zap_pud_range zap_pmd_range // // Assume that this huge page has never been accessed. // I.e. content of the PMD entry is zero (not mapped). // if (pmd_trans_huge(*pmd)) { // We don't get here due to the above assumption. } // // Assume that Thread B incurred a page fault and .---------> // sneaks in here as shown below. | // | if (pmd_none_or_clear_bad(pmd)) | { | if (unlikely(pmd_bad(*pmd))) | pmd_clear_bad | { | pmd_ERROR | // Log "bad pmd ..." message here. | pmd_clear | // Clear the page's PMD entry. | // Thread B incremented the map count | // in page_add_new_anon_rmap(), but | // now the page is no longer mapped | // by a PMD entry (-> inconsistency). | } | } | v - Thread B is handling a page fault on virtual address "B(fault)" shown in the picture. ... do_page_fault __do_page_fault // Acquire the semaphore in shared mode. down_read_trylock(&mm->mmap_sem) ... handle_mm_fault if (pmd_none(*pmd) && transparent_hugepage_enabled(vma)) // We get here due to the above assumption (PMD entry is zero). do_huge_pmd_anonymous_page alloc_hugepage_vma // Allocate a new transparent huge page here. ... __do_huge_pmd_anonymous_page ... spin_lock(&mm->page_table_lock) ... page_add_new_anon_rmap // Here we increment the page's map count (starts at -1). atomic_set(&page->_mapcount, 0) set_pmd_at // Here we set the page's PMD entry which will be cleared // when Thread A calls pmd_clear_bad(). ... spin_unlock(&mm->page_table_lock) The mmap_sem does not prevent the race because both threads are acquiring it in shared mode (down_read). Thread B holds the page_table_lock while the page's map count and PMD table entry are updated. However, Thread A does not synchronize on that lock. ====== end quote ======= [akpm@linux-foundation.org: checkpatch fixes] Reported-by: Ulrich Obergfell <uobergfe@redhat.com> Signed-off-by: Andrea Arcangeli <aarcange@redhat.com> Acked-by: Johannes Weiner <hannes@cmpxchg.org> Cc: Mel Gorman <mgorman@suse.de> Cc: Hugh Dickins <hughd@google.com> Cc: Dave Jones <davej@redhat.com> Acked-by: Larry Woodman <lwoodman@redhat.com> Acked-by: Rik van Riel <riel@redhat.com> Cc: Mark Salter <msalter@redhat.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-264
0
21,112
Analyze the following 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 BrowserView::HasClientEdge() const { return frame()->GetFrameView()->HasClientEdge(); } Commit Message: Mac: turn popups into new tabs while in fullscreen. It's platform convention to show popups as new tabs while in non-HTML5 fullscreen. (Popups cause tabs to lose HTML5 fullscreen.) This was implemented for Cocoa in a BrowserWindow override, but it makes sense to just stick it into Browser and remove a ton of override code put in just to support this. BUG=858929, 868416 TEST=as in bugs Change-Id: I43471f242813ec1159d9c690bab73dab3e610b7d Reviewed-on: https://chromium-review.googlesource.com/1153455 Reviewed-by: Sidney San Martín <sdy@chromium.org> Commit-Queue: Avi Drissman <avi@chromium.org> Cr-Commit-Position: refs/heads/master@{#578755} CWE ID: CWE-20
0
155,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: ModuleExport size_t RegisterDCMImage(void) { MagickInfo *entry; static const char *DCMNote= { "DICOM is used by the medical community for images like X-rays. The\n" "specification, \"Digital Imaging and Communications in Medicine\n" "(DICOM)\", is available at http://medical.nema.org/. In particular,\n" "see part 5 which describes the image encoding (RLE, JPEG, JPEG-LS),\n" "and supplement 61 which adds JPEG-2000 encoding." }; entry=SetMagickInfo("DCM"); entry->decoder=(DecodeImageHandler *) ReadDCMImage; entry->magick=(IsImageFormatHandler *) IsDCM; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString( "Digital Imaging and Communications in Medicine image"); entry->note=ConstantString(DCMNote); entry->module=ConstantString("DCM"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/551 CWE ID: CWE-772
0
62,746
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void SyncBackendHost::Core::OnClearServerDataFailed() { if (!sync_loop_) return; DCHECK_EQ(MessageLoop::current(), sync_loop_); host_.Call( FROM_HERE, &SyncBackendHost::HandleClearServerDataFailedOnFrontendLoop); } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
0
104,871
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: pcf_get_bitmaps( FT_Stream stream, PCF_Face face ) { FT_Error error; FT_Memory memory = FT_FACE( face )->memory; FT_Long* offsets = NULL; FT_Long bitmapSizes[GLYPHPADOPTIONS]; FT_ULong format, size; FT_ULong nbitmaps, i, sizebitmaps = 0; error = pcf_seek_to_table_type( stream, face->toc.tables, face->toc.count, PCF_BITMAPS, &format, &size ); if ( error ) return error; error = FT_Stream_EnterFrame( stream, 8 ); if ( error ) return error; format = FT_GET_ULONG_LE(); if ( PCF_BYTE_ORDER( format ) == MSBFirst ) nbitmaps = FT_GET_ULONG(); else nbitmaps = FT_GET_ULONG_LE(); FT_Stream_ExitFrame( stream ); if ( !PCF_FORMAT_MATCH( format, PCF_DEFAULT_FORMAT ) ) return FT_THROW( Invalid_File_Format ); FT_TRACE4(( "pcf_get_bitmaps:\n" )); FT_TRACE4(( " number of bitmaps: %d\n", nbitmaps )); /* XXX: PCF_Face->nmetrics is singed FT_Long, see pcf.h */ if ( face->nmetrics < 0 || nbitmaps != ( FT_ULong )face->nmetrics ) return FT_THROW( Invalid_File_Format ); if ( FT_NEW_ARRAY( offsets, nbitmaps ) ) return error; for ( i = 0; i < nbitmaps; i++ ) { if ( PCF_BYTE_ORDER( format ) == MSBFirst ) (void)FT_READ_LONG( offsets[i] ); else (void)FT_READ_LONG_LE( offsets[i] ); FT_TRACE5(( " bitmap %d: offset %ld (0x%lX)\n", i, offsets[i], offsets[i] )); } if ( error ) goto Bail; for ( i = 0; i < GLYPHPADOPTIONS; i++ ) { if ( PCF_BYTE_ORDER( format ) == MSBFirst ) (void)FT_READ_LONG( bitmapSizes[i] ); else (void)FT_READ_LONG_LE( bitmapSizes[i] ); if ( error ) goto Bail; sizebitmaps = bitmapSizes[PCF_GLYPH_PAD_INDEX( format )]; FT_TRACE4(( " padding %d implies a size of %ld\n", i, bitmapSizes[i] )); } FT_TRACE4(( " %d bitmaps, padding index %ld\n", nbitmaps, PCF_GLYPH_PAD_INDEX( format ) )); FT_TRACE4(( " bitmap size = %d\n", sizebitmaps )); FT_UNUSED( sizebitmaps ); /* only used for debugging */ for ( i = 0; i < nbitmaps; i++ ) { /* rough estimate */ if ( ( offsets[i] < 0 ) || ( (FT_ULong)offsets[i] > size ) ) { FT_TRACE0(( "pcf_get_bitmaps:" " invalid offset to bitmap data of glyph %d\n", i )); } else face->metrics[i].bits = stream->pos + offsets[i]; } face->bitmapsFormat = format; Bail: FT_FREE( offsets ); return error; } Commit Message: CWE ID: CWE-189
0
6,962
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static unsigned int sec_attr_to_method(unsigned int attr) { if (attr == 0xFF) return SC_AC_NEVER; else if (attr == 0) return SC_AC_NONE; else if (attr & 0x03) return SC_AC_CHV; else return SC_AC_UNKNOWN; } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125
0
78,679
Analyze the following 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 imap_error(const char *where, const char *msg) { mutt_error("%s [%s]\n", where, msg); } Commit Message: quote imap strings more carefully Co-authored-by: JerikoOne <jeriko.one@gmx.us> CWE ID: CWE-77
0
79,620
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void SyncBackendHost::HandleSyncCycleCompletedOnFrontendLoop( const SyncSessionSnapshot& snapshot) { if (!frontend_) return; DCHECK_EQ(MessageLoop::current(), frontend_loop_); last_snapshot_ = snapshot; SDVLOG(1) << "Got snapshot " << snapshot.ToString(); const syncable::ModelTypeSet to_migrate = snapshot.syncer_status().types_needing_local_migration; if (!to_migrate.Empty()) frontend_->OnMigrationNeededForTypes(to_migrate); if (initialized()) AddExperimentalTypes(); if (pending_download_state_.get()) { const syncable::ModelTypeSet types_to_add = pending_download_state_->types_to_add; const syncable::ModelTypeSet added_types = pending_download_state_->added_types; DCHECK(types_to_add.HasAll(added_types)); const syncable::ModelTypeSet initial_sync_ended = snapshot.initial_sync_ended(); const syncable::ModelTypeSet failed_configuration_types = Difference(added_types, initial_sync_ended); SDVLOG(1) << "Added types: " << syncable::ModelTypeSetToString(added_types) << ", configured types: " << syncable::ModelTypeSetToString(initial_sync_ended) << ", failed configuration types: " << syncable::ModelTypeSetToString(failed_configuration_types); if (!failed_configuration_types.Empty() && snapshot.retry_scheduled()) { if (!pending_download_state_->retry_in_progress) { pending_download_state_->retry_callback.Run(); pending_download_state_->retry_in_progress = true; } return; } scoped_ptr<PendingConfigureDataTypesState> state( pending_download_state_.release()); state->ready_task.Run(failed_configuration_types); if (!failed_configuration_types.Empty()) return; } if (initialized()) frontend_->OnSyncCycleCompleted(); } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
0
104,857
Analyze the following 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 WebsiteSettingsPopupView::ButtonPressed(views::Button* button, const ui::Event& event) { if (button == reset_decisions_button_) presenter_->OnRevokeSSLErrorBypassButtonPressed(); GetWidget()->Close(); } Commit Message: Fix UAF in Origin Info Bubble and permission settings UI. In addition to fixing the UAF, will this also fix the problem of the bubble showing over the previous tab (if the bubble is open when the tab it was opened for closes). BUG=490492 TBR=tedchoc Review URL: https://codereview.chromium.org/1317443002 Cr-Commit-Position: refs/heads/master@{#346023} CWE ID:
0
125,217
Analyze the following 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 write_register_operand(struct operand *op) { /* The 4-byte case *is* correct: in 64-bit mode we zero-extend. */ switch (op->bytes) { case 1: *(u8 *)op->addr.reg = (u8)op->val; break; case 2: *(u16 *)op->addr.reg = (u16)op->val; break; case 4: *op->addr.reg = (u32)op->val; break; /* 64b: zero-extend */ case 8: *op->addr.reg = op->val; break; } } Commit Message: KVM: x86: Handle errors when RIP is set during far jumps Far jmp/call/ret may fault while loading a new RIP. Currently KVM does not handle this case, and may result in failed vm-entry once the assignment is done. The tricky part of doing so is that loading the new CS affects the VMCS/VMCB state, so if we fail during loading the new RIP, we are left in unconsistent state. Therefore, this patch saves on 64-bit the old CS descriptor and restores it if loading RIP failed. This fixes CVE-2014-3647. Cc: stable@vger.kernel.org Signed-off-by: Nadav Amit <namit@cs.technion.ac.il> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> CWE ID: CWE-264
0
37,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 int cypress_write_room(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct cypress_private *priv = usb_get_serial_port_data(port); int room = 0; unsigned long flags; spin_lock_irqsave(&priv->lock, flags); room = kfifo_avail(&priv->write_fifo); spin_unlock_irqrestore(&priv->lock, flags); dev_dbg(&port->dev, "%s - returns %d\n", __func__, room); return room; } Commit Message: USB: cypress_m8: add endpoint sanity check An attack using missing endpoints exists. CVE-2016-3137 Signed-off-by: Oliver Neukum <ONeukum@suse.com> CC: stable@vger.kernel.org Signed-off-by: Johan Hovold <johan@kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID:
0
54,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: WebInsecureRequestPolicy DocumentInit::GetInsecureRequestPolicy() const { DCHECK(MasterDocumentLoader()); Frame* parent_frame = MasterDocumentLoader()->GetFrame()->Tree().Parent(); if (!parent_frame) return kLeaveInsecureRequestsAlone; return parent_frame->GetSecurityContext()->GetInsecureRequestPolicy(); } Commit Message: Inherit CSP when self-navigating to local-scheme URL As the linked bug example shows, we should inherit CSP when we navigate to a local-scheme URL (even if we are in a main browsing context). Bug: 799747 Change-Id: I8413aa8e8049461ebcf0ffbf7b04c41d1340af02 Reviewed-on: https://chromium-review.googlesource.com/c/1234337 Reviewed-by: Mike West <mkwst@chromium.org> Commit-Queue: Andy Paicu <andypaicu@chromium.org> Cr-Commit-Position: refs/heads/master@{#597889} CWE ID:
0
144,067
Analyze the following 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 _call_console_drivers(unsigned start, unsigned end, int msg_log_level) { trace_console(&LOG_BUF(0), start, end, log_buf_len); if ((msg_log_level < console_loglevel || ignore_loglevel) && console_drivers && start != end) { if ((start & LOG_BUF_MASK) > (end & LOG_BUF_MASK)) { /* wrapped write */ __call_console_drivers(start & LOG_BUF_MASK, log_buf_len); __call_console_drivers(0, end & LOG_BUF_MASK); } else { __call_console_drivers(start, end); } } } Commit Message: printk: fix buffer overflow when calling log_prefix function from call_console_drivers This patch corrects a buffer overflow in kernels from 3.0 to 3.4 when calling log_prefix() function from call_console_drivers(). This bug existed in previous releases but has been revealed with commit 162a7e7500f9664636e649ba59defe541b7c2c60 (2.6.39 => 3.0) that made changes about how to allocate memory for early printk buffer (use of memblock_alloc). It disappears with commit 7ff9554bb578ba02166071d2d487b7fc7d860d62 (3.4 => 3.5) that does a refactoring of printk buffer management. In log_prefix(), the access to "p[0]", "p[1]", "p[2]" or "simple_strtoul(&p[1], &endp, 10)" may cause a buffer overflow as this function is called from call_console_drivers by passing "&LOG_BUF(cur_index)" where the index must be masked to do not exceed the buffer's boundary. The trick is to prepare in call_console_drivers() a buffer with the necessary data (PRI field of syslog message) to be safely evaluated in log_prefix(). This patch can be applied to stable kernel branches 3.0.y, 3.2.y and 3.4.y. Without this patch, one can freeze a server running this loop from shell : $ export DUMMY=`cat /dev/urandom | tr -dc '12345AZERTYUIOPQSDFGHJKLMWXCVBNazertyuiopqsdfghjklmwxcvbn' | head -c255` $ while true do ; echo $DUMMY > /dev/kmsg ; done The "server freeze" depends on where memblock_alloc does allocate printk buffer : if the buffer overflow is inside another kernel allocation the problem may not be revealed, else the server may hangs up. Signed-off-by: Alexandre SIMON <Alexandre.Simon@univ-lorraine.fr> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-119
0
33,427
Analyze the following 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 video_sample_entry_AddBox(GF_Box *s, GF_Box *a) { GF_MPEGVisualSampleEntryBox *ptr = (GF_MPEGVisualSampleEntryBox *)s; switch (a->type) { case GF_ISOM_BOX_TYPE_ESDS: if (ptr->esd) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->esd = (GF_ESDBox *)a; break; case GF_ISOM_BOX_TYPE_SINF: gf_list_add(ptr->protections, a); break; case GF_ISOM_BOX_TYPE_RINF: if (ptr->rinf) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->rinf = (GF_RestrictedSchemeInfoBox *) a; break; case GF_ISOM_BOX_TYPE_AVCC: if (ptr->avc_config) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->avc_config = (GF_AVCConfigurationBox *)a; break; case GF_ISOM_BOX_TYPE_HVCC: if (ptr->hevc_config) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->hevc_config = (GF_HEVCConfigurationBox *)a; break; case GF_ISOM_BOX_TYPE_SVCC: if (ptr->svc_config) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->svc_config = (GF_AVCConfigurationBox *)a; break; case GF_ISOM_BOX_TYPE_MVCC: if (ptr->mvc_config) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->mvc_config = (GF_AVCConfigurationBox *)a; break; case GF_ISOM_BOX_TYPE_LHVC: if (ptr->lhvc_config) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->lhvc_config = (GF_HEVCConfigurationBox *)a; break; case GF_ISOM_BOX_TYPE_AV1C: if (ptr->av1_config) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->av1_config = (GF_AV1ConfigurationBox *)a; break; case GF_ISOM_BOX_TYPE_VPCC: if (ptr->vp_config) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->vp_config = (GF_VPConfigurationBox *)a; break; case GF_ISOM_BOX_TYPE_M4DS: if (ptr->descr) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->descr = (GF_MPEG4ExtensionDescriptorsBox *)a; break; case GF_ISOM_BOX_TYPE_UUID: if (! memcmp(((GF_UnknownUUIDBox*)a)->uuid, GF_ISOM_IPOD_EXT, 16)) { if (ptr->ipod_ext) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->ipod_ext = (GF_UnknownUUIDBox *)a; } else { return gf_isom_box_add_default(s, a); } break; case GF_ISOM_BOX_TYPE_D263: ptr->cfg_3gpp = (GF_3GPPConfigBox *)a; /*for 3GP config, remember sample entry type in config*/ ptr->cfg_3gpp->cfg.type = ptr->type; break; break; case GF_ISOM_BOX_TYPE_PASP: if (ptr->pasp) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->pasp = (GF_PixelAspectRatioBox *)a; break; case GF_ISOM_BOX_TYPE_CLAP: if (ptr->clap) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->clap = (GF_CleanApertureBox *)a; break; case GF_ISOM_BOX_TYPE_CCST: if (ptr->ccst) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->ccst = (GF_CodingConstraintsBox *)a; break; case GF_ISOM_BOX_TYPE_AUXI: if (ptr->auxi) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->auxi = (GF_AuxiliaryTypeInfoBox *)a; break; case GF_ISOM_BOX_TYPE_RVCC: if (ptr->rvcc) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->rvcc = (GF_RVCConfigurationBox *)a; break; default: return gf_isom_box_add_default(s, a); } return GF_OK; } Commit Message: prevent dref memleak on invalid input (#1183) CWE ID: CWE-400
0
91,899
Analyze the following 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 OmniboxViewWin::SchemeEnd(LPTSTR edit_text, int current_pos, int length) { return (current_pos >= 0) && ((length - current_pos) > 2) && (edit_text[current_pos] == ':') && (edit_text[current_pos + 1] == '/') && (edit_text[current_pos + 2] == '/'); } Commit Message: Change omnibox behavior when stripping javascript schema to navigate after stripping the schema on drag drop. BUG=109245 TEST=N/A Review URL: http://codereview.chromium.org/9116016 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@116692 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
0
107,520
Analyze the following 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 WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info,Image *image) { char s[2]; char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; const char *name, *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, /* ping_exclude_EXIF, */ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, /* ping_exclude_iTXt, */ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, /* ping_exclude_tRNS, */ ping_exclude_vpAg, ping_exclude_caNv, ping_exclude_zCCP, /* hex-encoded iCCP */ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter WriteOnePNGImage()"); /* Define these outside of the following "if logging()" block so they will * show in debuggers. */ *im_vers='\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MaxTextExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MaxTextExtent); *libpng_vers='\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," IM version = %s", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule()," Libpng version = %s", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", zlib_runv); } } /* Initialize some stuff */ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; /* ping_exclude_EXIF=mng_info->ping_exclude_EXIF; */ ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; /* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; /* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */ ping_exclude_vpAg=mng_info->ping_exclude_vpAg; ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; property=(const char *) NULL; /* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some "known invalid sRGB profiles". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. */ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { char *name; const StringInfo *profile; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile (potentially sRGB)", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " with crc=%8x",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " It is sRGB with rendering intent = %s", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile not recognized as sRGB", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=UndefinedClass"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=DirectClass"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=PseudoClass"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_info->magick= %s",image_info->magick); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? " image->taint=MagickTrue": " image->taint=MagickFalse"); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if (image->storage_class != PseudoClass && image->colormap != NULL) { /* Free the bogus colormap; it can cause trouble later */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Freeing bogus colormap"); (void) RelinquishMagickMemory(image->colormap); image->colormap=NULL; } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace); /* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. */ if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reducing PNG bit depth to 8 since this is a Q8 build."); image->depth=8; } #endif /* Respect the -depth option */ if (image->depth < 4) { register PixelPacket *r; ExceptionInfo *exception; exception=(&image->exception); if (image->depth > 2) { /* Scale to 4-bit */ LBR04PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBO(image->colormap[i]); } } } else if (image->depth > 1) { /* Scale to 2-bit */ LBR02PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBO(image->colormap[i]); } } } else { /* Scale to 1-bit */ LBR01PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBO(image->colormap[i]); } } } } /* To do: set to next higher multiple of 8 */ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy */ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->matte == MagickFalse))) { /* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. */ number_opaque = (int) image->colors; if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; else ping_have_color=MagickTrue; ping_have_non_bw=MagickFalse; if (image->matte != MagickFalse) { number_transparent = 2; number_semitransparent = 1; } else { number_transparent = 0; number_semitransparent = 0; } } if (mng_info->write_png_colortype < 7) { /* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. */ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; for (j=0; j<6; j++) { /* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->matte is MagickFalse, we ignore the opacity channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. */ ExceptionInfo *exception; int n; PixelPacket opaque[260], semitransparent[260], transparent[260]; register IndexPacket *indexes; register const PixelPacket *s, *q; register PixelPacket *r; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Enter BUILD_PALETTE:"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->columns=%.20g",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->rows=%.20g",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->matte=%.20g",(double) image->matte); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Original colormap:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,opacity)"); for (i=0; i < 256; i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " (zero means unknown)"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Regenerate the colormap"); } exception=(&image->exception); image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->matte == MagickFalse || GetPixelOpacity(q) == OpaqueOpacity) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelRGB(q, opaque); opaque[0].opacity=OpaqueOpacity; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (IsColorEqual(q, opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelRGB(q, opaque+i); opaque[i].opacity=OpaqueOpacity; } } } else if (q->opacity == TransparentOpacity) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelRGBO(q, transparent); ping_trans_color.red= (unsigned short) GetPixelRed(q); ping_trans_color.green= (unsigned short) GetPixelGreen(q); ping_trans_color.blue= (unsigned short) GetPixelBlue(q); ping_trans_color.gray= (unsigned short) GetPixelRed(q); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (IsColorEqual(q, transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelRGBO(q, transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelRGBO(q, semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (IsColorEqual(q, semitransparent+i) && GetPixelOpacity(q) == semitransparent[i].opacity) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelRGBO(q, semitransparent+i); } } } q++; } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { /* Add the background color to the palette, if it * isn't already there. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Check colormap for background (%d,%d,%d)", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } for (i=0; i<number_opaque; i++) { if (opaque[i].red == image->background_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (number_opaque < 259 && i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d",(int) i); } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in the colormap to add background color"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has more than 256 colors"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has %d colors",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) /* We won't need this info */ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "incompatible colorspace"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(s) != GetPixelGreen(s) || GetPixelRed(s) != GetPixelBlue(s)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } s++; } if (ping_have_color != MagickFalse) break; /* Worst case is black-and-white; we are looking at every * pixel twice. */ if (ping_have_non_bw == MagickFalse) { s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(s) != 0 && GetPixelRed(s) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } s++; } } } } } if (image_colors < 257) { PixelPacket colormap[260]; /* * Initialize image colormap. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Sort the new colormap"); /* Sort palette, transparent first */; n = 0; for (i=0; i<number_transparent; i++) colormap[n++] = transparent[i]; for (i=0; i<number_semitransparent; i++) colormap[n++] = semitransparent[i]; for (i=0; i<number_opaque; i++) colormap[n++] = opaque[i]; ping_background.index += (number_transparent + number_semitransparent); /* image_colors < 257; search the colormap instead of the pixels * to get ping_have_color and ping_have_non_bw */ for (i=0; i<n; i++) { if (ping_have_color == MagickFalse) { if (colormap[i].red != colormap[i].green || colormap[i].red != colormap[i].blue) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } } if (ping_have_non_bw == MagickFalse) { if (colormap[i].red != 0 && colormap[i].red != QuantumRange) ping_have_non_bw=MagickTrue; } } if ((mng_info->ping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_colors (%d) and n (%d) don't match", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireImageColormap"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors) == MagickFalse) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d (%d)", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Update the pixel indexes"); } /* Sync the pixel indices with the new colormap */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->matte == MagickFalse || image->colormap[i].opacity == GetPixelOpacity(q)) && image->colormap[i].red == GetPixelRed(q) && image->colormap[i].green == GetPixelGreen(q) && image->colormap[i].blue == GetPixelBlue(q)) { SetPixelIndex(indexes+x,i); break; } } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,opacity)"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent = %d", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent > 256"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque = %d", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque > 256"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent = %d", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent > 256"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are black or white"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are gray"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " At least one pixel or the background is non-gray"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Exit BUILD_PALETTE:"); } if (mng_info->write_png8 == MagickFalse) break; /* Make any reductions necessary for the PNG8 format */ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; /* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. */ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Thresholding the alpha channel to binary"); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) > TransparentOpacity/2) { SetPixelOpacity(r,TransparentOpacity); SetPixelRgb(r,&image->background_color); } else SetPixelOpacity(r,OpaqueOpacity); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; i<image_colors; i++) image->colormap[i].opacity = (image->colormap[i].opacity > TransparentOpacity/2 ? TransparentOpacity : OpaqueOpacity); } continue; } /* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. */ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 4-4-4"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 4-4-4"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR04PixelRGB(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 4-4-4"); for (i=0; i<image_colors; i++) { LBR04PacketRGB(image->colormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-3"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-3-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR03PixelRGB(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-3-1"); for (i=0; i<image_colors; i++) { LBR03PacketRGB(image->colormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-2"); tried_332 = MagickTrue; /* Red and green were already done so we only quantize the blue * channel */ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR02PixelBlue(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-2-1"); for (i=0; i<image_colors; i++) { LBR02PacketBlue(image->colormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { /* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red background colors to 3-3-2-1"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(r)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(r)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(r)) == 0x00 && GetPixelOpacity(r) == OpaqueOpacity) { SetPixelRed(r,ScaleCharToQuantum(0x24)); } r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; i<image_colors; i++) { if (ScaleQuantumToChar(image->colormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } /* END OF BUILD_PALETTE */ /* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. */ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } /* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. */ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { ExceptionInfo *exception; register const PixelPacket *q; exception=(&image->exception); for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (q->opacity != TransparentOpacity && (unsigned short) GetPixelRed(q) == ping_trans_color.red && (unsigned short) GetPixelGreen(q) == ping_trans_color.green && (unsigned short) GetPixelBlue(q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q++; } if (ping_have_cheap_transparency == MagickFalse) break; } } else { /* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. */ if (image_colors > 1) for (i=1; i<image_colors; i++) if (image->colormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is not possible."); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is possible."); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->matte; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "Cannot write PNG8 or color-type 3; colormap is NULL", "`%s'",image->filename); return(MagickFalse); } /* Allocate the PNG structures */ #ifdef PNG_USER_MEM_SUPPORTED ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,image, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,image, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { /* PNG write failed. */ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf("PNG write has failed.\n"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); return(MagickFalse); } /* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. */ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED /* Allow benign errors */ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED /* Reject images with too many rows or columns */ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif /* PNG_SET_USER_LIMITS_SUPPORTED */ /* Prepare PNG for writing. */ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED /* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK */ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; /* Adjust requested depth to next higher valid depth if necessary */ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " width=%.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " height=%.20g",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_matte=%.20g",(double) image->matte); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative ping_bit_depth=%.20g",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->x_resolution != 0) && (image->y_resolution != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->x_resolution+0.5)/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->y_resolution+0.5)/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->x_resolution+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->y_resolution+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->x_resolution; ping_pHYs_y_resolution=(png_uint_32) image->y_resolution; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (1)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth=%d",ping_bit_depth); } ping_have_bKGD = MagickTrue; } /* Select the color type. */ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { /* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. */ number_colors=image_colors; ping_have_tRNS=MagickFalse; /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors (%d)", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 " %3ld (%3d,%3d,%3d)", #else " %5ld (%5d,%5d,%5d)", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { /* Identify which colormap entry is transparent. */ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { /* * Identify which colormap entry is the background color. */ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); } } } /* end of write_png8 */ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else /* mng_info->write_pngNN not specified */ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG colortype %d was specified:",(int) ping_color_type); } else /* write_png_colortype not specified */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selecting PNG colortype:"); ping_color_type=(png_byte) ((matte != MagickFalse)? PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } if (image_info->type == TrueColorMatteType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } if (image_info->type == PaletteType || image_info->type == PaletteMatteType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (mng_info->write_png_colortype == 0 && image_info->type == UndefinedType) { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selected PNG colortype=%d",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->matte == MagickFalse && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { /* DO SOMETHING */ png_error(ping,"image has 0 colors"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %.20g",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG bit depth: %d",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG color type: %s (%.20g)", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_info->type: %.20g",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_depth: %.20g",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth: %.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth: %.20g",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } /* * Determine if there is any transparent color. */ if (number_transparent + number_semitransparent == 0) { /* No transparent pixels are present. Change 4 or 6 to 0 or 2. */ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(ClampToQuantum(GetPixelLuma(image, image->colormap))) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { /* * Determine if there is one and only one transparent color * and if so if it is fully transparent. */ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (0)"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { /* Check if grayscale is reducible */ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors", number_colors); ping_have_PLTE=MagickTrue; } /* color_type is PNG_COLOR_TYPE_PALETTE */ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { /* * Set up trans_colors array. */ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (1)"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) (255- ScaleQuantumToChar(image->colormap[i].opacity)); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color from (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; /* Adjust background and transparency samples in sub-8-bit grayscale files. */ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval/65535.)*(ScaleQuantumToShort((Quantum) GetPixelLuma(image,&image->background_color)))+.5); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (2)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_background.index is %d", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_background.gray is %d", (int) ping_background.gray); } ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color.gray from %d", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to %d", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { /* Identify which colormap entry is the background color. */ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk with index=%d",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background =(%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else /* Can't happen */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in PLTE to add bKGD color"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color type: %s (%d)", PngColorTypeToString(ping_color_type), ping_color_type); /* Initialize compression level and filtering. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up deflate compression"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression buffer size: 32768"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression mem level: 9"); png_set_compression_mem_level(ping, 9); /* Untangle the "-quality" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type "none" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: "LOCO" filtering (intrapixel differing) if writing a MNG, otherwise "none". Did not work in IM-6.7.0-9 and earlier because of a missing "else". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This is addressed by using "-define png:compression-strategy", etc., which takes precedence over -quality. */ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression level: %d", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression strategy: %d", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up filtering"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: ADAPTIVE"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: NONE"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: %d", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); /* Bail out if cannot meet defined png:bit-depth or png:color-type */ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image has transparency but tRNS chunk was excluded"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth=%u, Computed depth=%u", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type=%u, Computed color type=%u", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, "Cannot write image with defined png:bit-depth or png:color-type."); } if (image_matte != MagickFalse && image->matte == MagickFalse) { /* Add an opaque matte channel */ image->matte = MagickTrue; (void) SetImageOpacity(image,0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Added an opaque matte channel"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting ping_have_tRNS=MagickTrue."); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG header chunks"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { if (mng_info->have_write_global_plte && matte == MagickFalse) { png_set_PLTE(ping,ping_info,NULL,0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up empty PLTE chunk"); } else png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } /* Only write the iCCP chunk if we are not writing the sRGB chunk. */ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up iCCP chunk"); png_set_iCCP(ping,ping_info,(const png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); ping_have_iCCP = MagickTrue; } } else #endif if (ping_exclude_zCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up zTXT chunk with uuencoded ICC"); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); ping_have_iCCP = MagickTrue; } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up text chunk with %s profile",name); name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { /* Note image rendering intent. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up sRGB chunk"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { /* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up gAMA chunk"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { /* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. */ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up cHRM chunk"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background color = (%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " index = %d, gray=%d", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_resolution=%lu", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " y_resolution=%lu", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " unit_type=%lu", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,"png:tIME"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,"png:tIME"); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reset tIME in tainted image"); timestamp=GetImageProperty(image,"date:modify"); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception) == MagickFalse) png_error(ping,"WriteBlob Failed"); ping_have_blob=MagickTrue; (void) ping_have_blob; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Calling png_set_tRNS with num_trans=%d",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tRNS color =(%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } /* write any png-chunk-b profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-b",logging); png_write_info(ping,ping_info); /* write any PNG-chunk-m profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-m",logging); ping_wrote_caNv = MagickFalse; /* write caNv chunk */ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); /* data length=8 */ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up oFFs chunk with x=%d, y=%d, units=0", (int) image->page.x, (int) image->page.y); } } #endif /* write vpAg chunk (deprecated, replaced by caNv) */ if (ping_exclude_vpAg == MagickFalse && ping_wrote_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows)) { unsigned char chunk[14]; (void) WriteBlobMSBULong(image,9L); /* data length=8 */ PNGType(chunk,mng_vpAg); LogPNGChunk(logging,mng_vpAg,9L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); chunk[12]=0; /* unit = pixels */ (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } } #if (PNG_LIBPNG_VER == 10206) /* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); /* Allocate memory. */ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocating %.20g bytes of memory for pixels",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,"Allocation of memory for pixels failed"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Initialize image scanlines. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,"Memory allocation for quantum_info failed"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse) { /* Palette, Bilevel, or Opaque Monochrome */ register const PixelPacket *p; SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { /* Convert PseudoClass image to a PNG monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (0)"); p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; if (mng_info->IsPalette) { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE && mng_info->write_png_depth && mng_info->write_png_depth != old_bit_depth) { /* Undo pixel scaling */ for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) (*(ping_pixels+i) >> (8-old_bit_depth)); } } else { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); } if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (1)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else /* Not Palette, Bilevel, or Opaque Monochrome */ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const PixelPacket *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY PNG pixels (2)"); } else /* PNG_COLOR_TYPE_GRAY_ALPHA */ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (2)"); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,&image->exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (2)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const PixelPacket *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, &image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (3)"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (3)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else /* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) */ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is not GRAY or GRAY_ALPHA",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA",pass); p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (4)"); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, &image->exception); } else { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of non-gray pixels (4)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_pixels[0]=%d,ping_pixels[1]=%d", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Wrote PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Width: %.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Height: %.20g",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth: %d",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG bit-depth written: %d",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type: %d",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color-type written: %d",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG Interlace method: %d",ping_interlace_method); } /* Generate text chunks after IDAT. */ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property); /* Don't write any "png:" or "jpeg:" properties; those are just for * "identify" or for passing through to another JPEG */ if ((LocaleNCompare(property,"png:",4) != 0 && LocaleNCompare(property,"jpeg:",5) != 0) && /* Suppress density and units if we wrote a pHYs chunk */ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,"density") != 0 || LocaleCompare(property,"units") != 0) && /* Suppress the IM-generated Date:create and Date:modify */ (ping_exclude_date == MagickFalse || LocaleNCompare(property, "Date:",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up text chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " keyword: '%s'",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } /* write any PNG-chunk-e profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-e",logging); /* write exIf profile */ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { char *name; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { if (LocaleCompare(name,"exif") == 0) { const StringInfo *profile; profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Have eXIf profile"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); #if 0 /* eXIf chunk is registered */ PNGType(chunk,mng_eXIf); #else /* eXIf chunk not yet registered; write exIf instead */ PNGType(chunk,mng_exIf); #endif if (length < 7) break; /* othewise crashes */ /* skip the "Exif\0\0" JFIF Exif Header ID */ length -= 6; LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data+6); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data+6, (uInt) length)); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG end info"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; /* Write FRAM 4 with clipping boundaries followed by FRAM 1. */ (void) WriteBlobMSBULong(image,27L); /* data length=27 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; /* frame name separator (no name) */ chunk[6]=1; /* flag for changing delay, for next frame only */ chunk[7]=0; /* flag for changing frame timeout */ chunk[8]=1; /* flag for changing frame clipping for next frame */ chunk[9]=0; /* flag for changing frame sync_id */ PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */ chunk[14]=0; /* clipping boundaries delta type */ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, "Cannot convert GIF with disposal method 3 to MNG-LC"); /* Free PNG resources. */ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); /* Store bit depth actually written */ s[0]=(char) ping_bit_depth; s[1]='\0'; (void) SetImageProperty(image,"png:bit-depth-written",s); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteOnePNGImage()"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif /* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. */ return(MagickTrue); /* End write one PNG image */ } Commit Message: ... CWE ID: CWE-754
0
62,153
Analyze the following 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 Document::mediaQueryAffectingValueChanged() { styleResolverChanged(); m_evaluateMediaQueriesOnStyleRecalc = true; styleEngine().clearMediaQueryRuleSetStyleSheets(); InspectorInstrumentation::mediaQueryResultChanged(this); } Commit Message: Change Document::detach() to RELEASE_ASSERT all subframes are gone. BUG=556724,577105 Review URL: https://codereview.chromium.org/1667573002 Cr-Commit-Position: refs/heads/master@{#373642} CWE ID: CWE-264
0
124,437