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: check_interlace_type(int PNG_CONST interlace_type)
{
if (interlace_type != PNG_INTERLACE_NONE)
{
/* This is an internal error - --interlace tests should be skipped, not
* attempted.
*/
fprintf(stderr, "pngvalid: no interlace support\n");
exit(99);
}
}
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,605 |
Analyze the following 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::string16 ScreenLayoutObserverTest::GetDisplayNotificationAdditionalText()
const {
const message_center::Notification* notification = GetDisplayNotification();
return notification ? notification->message() : base::string16();
}
Commit Message: Avoid Showing rotation change notification when source is accelerometer
BUG=717252
TEST=Manually rotate device with accelerometer and observe there's no notification
Review-Url: https://codereview.chromium.org/2853113005
Cr-Commit-Position: refs/heads/master@{#469058}
CWE ID: CWE-17 | 0 | 129,503 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static int compact_treesame(struct rev_info *revs, struct commit *commit, unsigned nth_parent)
{
struct treesame_state *st;
int old_same;
if (!commit->parents) {
/*
* Have just removed the only parent from a non-merge.
* Different handling, as we lack decoration.
*/
if (nth_parent != 0)
die("compact_treesame %u", nth_parent);
old_same = !!(commit->object.flags & TREESAME);
if (rev_same_tree_as_empty(revs, commit))
commit->object.flags |= TREESAME;
else
commit->object.flags &= ~TREESAME;
return old_same;
}
st = lookup_decoration(&revs->treesame, &commit->object);
if (!st || nth_parent >= st->nparents)
die("compact_treesame %u", nth_parent);
old_same = st->treesame[nth_parent];
memmove(st->treesame + nth_parent,
st->treesame + nth_parent + 1,
st->nparents - nth_parent - 1);
/*
* If we've just become a non-merge commit, update TREESAME
* immediately, and remove the no-longer-needed decoration.
* If still a merge, defer update until update_treesame().
*/
if (--st->nparents == 1) {
if (commit->parents->next)
die("compact_treesame parents mismatch");
if (st->treesame[0] && revs->dense)
commit->object.flags |= TREESAME;
else
commit->object.flags &= ~TREESAME;
free(add_decoration(&revs->treesame, &commit->object, NULL));
}
return old_same;
}
Commit Message: list-objects: pass full pathname to callbacks
When we find a blob at "a/b/c", we currently pass this to
our show_object_fn callbacks as two components: "a/b/" and
"c". Callbacks which want the full value then call
path_name(), which concatenates the two. But this is an
inefficient interface; the path is a strbuf, and we could
simply append "c" to it temporarily, then roll back the
length, without creating a new copy.
So we could improve this by teaching the callsites of
path_name() this trick (and there are only 3). But we can
also notice that no callback actually cares about the
broken-down representation, and simply pass each callback
the full path "a/b/c" as a string. The callback code becomes
even simpler, then, as we do not have to worry about freeing
an allocated buffer, nor rolling back our modification to
the strbuf.
This is theoretically less efficient, as some callbacks
would not bother to format the final path component. But in
practice this is not measurable. Since we use the same
strbuf over and over, our work to grow it is amortized, and
we really only pay to memcpy a few bytes.
Signed-off-by: Jeff King <peff@peff.net>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
CWE ID: CWE-119 | 0 | 54,983 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void CWebServer::Cmd_GetLog(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "GetLog";
time_t lastlogtime = 0;
std::string slastlogtime = request::findValue(&req, "lastlogtime");
if (slastlogtime != "")
{
std::stringstream s_str(slastlogtime);
s_str >> lastlogtime;
}
_eLogLevel lLevel = LOG_NORM;
std::string sloglevel = request::findValue(&req, "loglevel");
if (!sloglevel.empty())
{
lLevel = (_eLogLevel)atoi(sloglevel.c_str());
}
std::list<CLogger::_tLogLineStruct> logmessages = _log.GetLog(lLevel);
int ii = 0;
for (const auto & itt : logmessages)
{
if (itt.logtime > lastlogtime)
{
std::stringstream szLogTime;
szLogTime << itt.logtime;
root["LastLogTime"] = szLogTime.str();
root["result"][ii]["level"] = static_cast<int>(itt.level);
root["result"][ii]["message"] = itt.logmessage;
ii++;
}
}
}
Commit Message: Fixed possible SQL Injection Vulnerability (Thanks to Fabio Carretto!)
CWE ID: CWE-89 | 0 | 90,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: base::string16 CardUnmaskPromptViews::GetDialogButtonLabel(
ui::DialogButton button) const {
if (button == ui::DIALOG_BUTTON_OK)
return l10n_util::GetStringUTF16(IDS_AUTOFILL_CARD_UNMASK_CONFIRM_BUTTON);
return DialogDelegateView::GetDialogButtonLabel(button);
}
Commit Message: Clear out some minor TODOs.
BUG=none
Review URL: https://codereview.chromium.org/1047063002
Cr-Commit-Position: refs/heads/master@{#322959}
CWE ID: CWE-20 | 0 | 110,102 |
Analyze the following 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 msg_init_ns(struct ipc_namespace *ns)
{
ns->msg_ctlmax = MSGMAX;
ns->msg_ctlmnb = MSGMNB;
ns->msg_ctlmni = MSGMNI;
atomic_set(&ns->msg_bytes, 0);
atomic_set(&ns->msg_hdrs, 0);
ipc_init_ids(&ns->ids[IPC_MSG_IDS]);
}
Commit Message: Initialize msg/shm IPC objects before doing ipc_addid()
As reported by Dmitry Vyukov, we really shouldn't do ipc_addid() before
having initialized the IPC object state. Yes, we initialize the IPC
object in a locked state, but with all the lockless RCU lookup work,
that IPC object lock no longer means that the state cannot be seen.
We already did this for the IPC semaphore code (see commit e8577d1f0329:
"ipc/sem.c: fully initialize sem_array before making it visible") but we
clearly forgot about msg and shm.
Reported-by: Dmitry Vyukov <dvyukov@google.com>
Cc: Manfred Spraul <manfred@colorfullife.com>
Cc: Davidlohr Bueso <dbueso@suse.de>
Cc: stable@vger.kernel.org
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID: CWE-362 | 0 | 42,001 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: NavigationType NavigationControllerImpl::ClassifyNavigation(
const ViewHostMsg_FrameNavigate_Params& params) const {
if (params.page_id == -1) {
return NAVIGATION_TYPE_NAV_IGNORE;
}
if (params.page_id > web_contents_->GetMaxPageID()) {
if (PageTransitionIsMainFrame(params.transition))
return NAVIGATION_TYPE_NEW_PAGE;
if (!GetLastCommittedEntry())
return NAVIGATION_TYPE_NAV_IGNORE;
return NAVIGATION_TYPE_NEW_SUBFRAME;
}
DCHECK(!params.history_list_was_cleared);
int existing_entry_index = GetEntryIndexWithPageID(
web_contents_->GetSiteInstance(),
params.page_id);
if (existing_entry_index == -1) {
NOTREACHED();
LOG(ERROR) << "terminating renderer for bad navigation: " << params.url;
RecordAction(UserMetricsAction("BadMessageTerminate_NC"));
std::string temp = params.url.spec();
temp.append("#page");
temp.append(base::IntToString(params.page_id));
temp.append("#max");
temp.append(base::IntToString(web_contents_->GetMaxPageID()));
temp.append("#frame");
temp.append(base::IntToString(params.frame_id));
temp.append("#ids");
for (int i = 0; i < static_cast<int>(entries_.size()); ++i) {
temp.append(base::IntToString(entries_[i]->GetPageID()));
temp.append("_");
if (entries_[i]->site_instance())
temp.append(base::IntToString(entries_[i]->site_instance()->GetId()));
else
temp.append("N");
if (entries_[i]->site_instance() != web_contents_->GetSiteInstance())
temp.append("x");
temp.append(",");
}
GURL url(temp);
static_cast<RenderViewHostImpl*>(
web_contents_->GetRenderViewHost())->Send(
new ViewMsg_TempCrashWithData(url));
return NAVIGATION_TYPE_NAV_IGNORE;
}
NavigationEntryImpl* existing_entry = entries_[existing_entry_index].get();
if (!PageTransitionIsMainFrame(params.transition)) {
DCHECK(GetLastCommittedEntry());
return NAVIGATION_TYPE_AUTO_SUBFRAME;
}
if (pending_entry_ &&
!pending_entry_->is_renderer_initiated() &&
existing_entry != pending_entry_ &&
pending_entry_->GetPageID() == -1 &&
existing_entry == GetLastCommittedEntry()) {
return NAVIGATION_TYPE_SAME_PAGE;
}
if (AreURLsInPageNavigation(existing_entry->GetURL(), params.url,
params.was_within_same_page,
NAVIGATION_TYPE_UNKNOWN)) {
return NAVIGATION_TYPE_IN_PAGE;
}
return NAVIGATION_TYPE_EXISTING_PAGE;
}
Commit Message: Delete unneeded pending entries in DidFailProvisionalLoad to prevent a spoof.
BUG=280512
BUG=278899
TEST=See bug for repro steps.
Review URL: https://chromiumcodereview.appspot.com/23978003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@222146 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | 0 | 111,494 |
Analyze the following 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 voidMethodStringArgLongArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
TestObjectPythonV8Internal::voidMethodStringArgLongArgMethod(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,887 |
Analyze the following 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 edge_disconnect(struct usb_serial *serial)
{
struct edgeport_serial *edge_serial = usb_get_serial_data(serial);
cancel_delayed_work_sync(&edge_serial->heartbeat_work);
}
Commit Message: USB: serial: io_ti: fix information leak in completion handler
Add missing sanity check to the bulk-in completion handler to avoid an
integer underflow that can be triggered by a malicious device.
This avoids leaking 128 kB of memory content from after the URB transfer
buffer to user space.
Fixes: 8c209e6782ca ("USB: make actual_length in struct urb field u32")
Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
Cc: stable <stable@vger.kernel.org> # 2.6.30
Signed-off-by: Johan Hovold <johan@kernel.org>
CWE ID: CWE-191 | 0 | 66,075 |
Analyze the following 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 u32 vhost_scsi_get_default_depth(struct se_portal_group *se_tpg)
{
return 1;
}
Commit Message: vhost/scsi: potential memory corruption
This code in vhost_scsi_make_tpg() is confusing because we limit "tpgt"
to UINT_MAX but the data type of "tpg->tport_tpgt" and that is a u16.
I looked at the context and it turns out that in
vhost_scsi_set_endpoint(), "tpg->tport_tpgt" is used as an offset into
the vs_tpg[] array which has VHOST_SCSI_MAX_TARGET (256) elements so
anything higher than 255 then it is invalid. I have made that the limit
now.
In vhost_scsi_send_evt() we mask away values higher than 255, but now
that the limit has changed, we don't need the mask.
Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com>
Signed-off-by: Nicholas Bellinger <nab@linux-iscsi.org>
CWE ID: CWE-119 | 0 | 43,095 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data)
{
int rc;
struct cifs_ses *ses = sess_data->ses;
struct smb2_sess_setup_req *req;
struct smb2_sess_setup_rsp *rsp = NULL;
unsigned char *ntlmssp_blob = NULL;
bool use_spnego = false; /* else use raw ntlmssp */
u16 blob_length = 0;
rc = SMB2_sess_alloc_buffer(sess_data);
if (rc)
goto out;
req = (struct smb2_sess_setup_req *) sess_data->iov[0].iov_base;
req->hdr.sync_hdr.SessionId = ses->Suid;
rc = build_ntlmssp_auth_blob(&ntlmssp_blob, &blob_length, ses,
sess_data->nls_cp);
if (rc) {
cifs_dbg(FYI, "build_ntlmssp_auth_blob failed %d\n", rc);
goto out;
}
if (use_spnego) {
/* BB eventually need to add this */
cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
rc = -EOPNOTSUPP;
goto out;
}
sess_data->iov[1].iov_base = ntlmssp_blob;
sess_data->iov[1].iov_len = blob_length;
rc = SMB2_sess_sendreceive(sess_data);
if (rc)
goto out;
rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
ses->Suid = rsp->hdr.sync_hdr.SessionId;
ses->session_flags = le16_to_cpu(rsp->SessionFlags);
if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA)
cifs_dbg(VFS, "SMB3 encryption not supported yet\n");
rc = SMB2_sess_establish_session(sess_data);
out:
kfree(ntlmssp_blob);
SMB2_sess_free_buffer(sess_data);
kfree(ses->ntlmssp);
ses->ntlmssp = NULL;
sess_data->result = rc;
sess_data->func = NULL;
}
Commit Message: CIFS: Enable encryption during session setup phase
In order to allow encryption on SMB connection we need to exchange
a session key and generate encryption and decryption keys.
Signed-off-by: Pavel Shilovsky <pshilov@microsoft.com>
CWE ID: CWE-476 | 0 | 84,920 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void RenderProcessHostImpl::set_render_process_host_factory(
const RenderProcessHostFactory* rph_factory) {
g_render_process_host_factory_ = rph_factory;
}
Commit Message: Correct mojo::WrapSharedMemoryHandle usage
Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which
were assuming that the call actually has any control over the memory
protection applied to a handle when mapped.
Where fixing usage is infeasible for this CL, TODOs are added to
annotate follow-up work.
Also updates the API and documentation to (hopefully) improve clarity
and avoid similar mistakes from being made in the future.
BUG=792900
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477
Reviewed-on: https://chromium-review.googlesource.com/818282
Reviewed-by: Wei Li <weili@chromium.org>
Reviewed-by: Lei Zhang <thestig@chromium.org>
Reviewed-by: John Abd-El-Malek <jam@chromium.org>
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Reviewed-by: Sadrul Chowdhury <sadrul@chromium.org>
Reviewed-by: Yuzhu Shen <yzshen@chromium.org>
Reviewed-by: Robert Sesek <rsesek@chromium.org>
Commit-Queue: Ken Rockot <rockot@chromium.org>
Cr-Commit-Position: refs/heads/master@{#530268}
CWE ID: CWE-787 | 0 | 149,351 |
Analyze the following 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 ist_begin_non_atomic(struct pt_regs *regs)
{
BUG_ON(!user_mode(regs));
/*
* Sanity check: we need to be on the normal thread stack. This
* will catch asm bugs and any attempt to use ist_preempt_enable
* from double_fault.
*/
BUG_ON(!on_thread_stack());
preempt_enable_no_resched();
}
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,502 |
Analyze the following 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 voidCallbackFunctionAttributeAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder());
V8TRYCATCH_VOID(ScriptValue, cppValue, ScriptValue(jsValue, info.GetIsolate()));
imp->setVoidCallbackFunctionAttribute(cppValue);
}
Commit Message: document.location bindings fix
BUG=352374
R=jochen@chromium.org
Review URL: https://codereview.chromium.org/196343011
git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | 0 | 122,775 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: vrrp_handle_bfd_event(bfd_event_t * evt)
{
vrrp_tracked_bfd_t *vbfd;
tracking_vrrp_t *tbfd;
vrrp_t * vrrp;
element e, e1;
struct timeval time_now;
struct timeval timer_tmp;
uint32_t delivery_time;
if (__test_bit(LOG_DETAIL_BIT, &debug)) {
time_now = timer_now();
timersub(&time_now, &evt->sent_time, &timer_tmp);
delivery_time = timer_long(timer_tmp);
log_message(LOG_INFO, "Received BFD event: instance %s is in"
" state %s (delivered in %i usec)",
evt->iname, BFD_STATE_STR(evt->state), delivery_time);
}
LIST_FOREACH(vrrp_data->vrrp_track_bfds, vbfd, e) {
if (strcmp(vbfd->bname, evt->iname))
continue;
if ((vbfd->bfd_up && evt->state == BFD_STATE_UP) ||
(!vbfd->bfd_up && evt->state == BFD_STATE_DOWN))
continue;
vbfd->bfd_up = (evt->state == BFD_STATE_UP);
LIST_FOREACH(vbfd->tracking_vrrp, tbfd, e1) {
vrrp = tbfd->vrrp;
log_message(LOG_INFO, "VRRP_Instance(%s) Tracked BFD"
" instance %s is %s", vrrp->iname, evt->iname, vbfd->bfd_up ? "UP" : "DOWN");
if (tbfd->weight) {
if (vbfd->bfd_up)
vrrp->total_priority += abs(tbfd->weight);
else
vrrp->total_priority -= abs(tbfd->weight);
vrrp_set_effective_priority(vrrp);
continue;
}
if (vbfd->bfd_up)
try_up_instance(vrrp, false);
else
down_instance(vrrp);
}
break;
}
}
Commit Message: When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <quentin@armitage.org.uk>
CWE ID: CWE-59 | 0 | 76,078 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static inline void check_dl_overrun(struct task_struct *tsk)
{
if (tsk->dl.dl_overrun) {
tsk->dl.dl_overrun = 0;
__group_send_sig_info(SIGXCPU, SEND_SIG_PRIV, tsk);
}
}
Commit Message: posix-timers: Sanitize overrun handling
The posix timer overrun handling is broken because the forwarding functions
can return a huge number of overruns which does not fit in an int. As a
consequence timer_getoverrun(2) and siginfo::si_overrun can turn into
random number generators.
The k_clock::timer_forward() callbacks return a 64 bit value now. Make
k_itimer::ti_overrun[_last] 64bit as well, so the kernel internal
accounting is correct. 3Remove the temporary (int) casts.
Add a helper function which clamps the overrun value returned to user space
via timer_getoverrun(2) or siginfo::si_overrun limited to a positive value
between 0 and INT_MAX. INT_MAX is an indicator for user space that the
overrun value has been clamped.
Reported-by: Team OWL337 <icytxw@gmail.com>
Signed-off-by: Thomas Gleixner <tglx@linutronix.de>
Acked-by: John Stultz <john.stultz@linaro.org>
Cc: Peter Zijlstra <peterz@infradead.org>
Cc: Michael Kerrisk <mtk.manpages@gmail.com>
Link: https://lkml.kernel.org/r/20180626132705.018623573@linutronix.de
CWE ID: CWE-190 | 0 | 81,095 |
Analyze the following 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 u32 lshift(u32 x, unsigned int s)
{
x &= 0xFFFFFFFF;
return ((x << s) & 0xFFFFFFFF) | (x >> (32 - s));
}
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,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: static void pcnet_update_irq(PCNetState *s)
{
int isr = 0;
s->csr[0] &= ~0x0080;
#if 1
if (((s->csr[0] & ~s->csr[3]) & 0x5f00) ||
(((s->csr[4]>>1) & ~s->csr[4]) & 0x0115) ||
(((s->csr[5]>>1) & s->csr[5]) & 0x0048))
#else
if ((!(s->csr[3] & 0x4000) && !!(s->csr[0] & 0x4000)) /* BABL */ ||
(!(s->csr[3] & 0x1000) && !!(s->csr[0] & 0x1000)) /* MISS */ ||
(!(s->csr[3] & 0x0100) && !!(s->csr[0] & 0x0100)) /* IDON */ ||
(!(s->csr[3] & 0x0200) && !!(s->csr[0] & 0x0200)) /* TINT */ ||
(!(s->csr[3] & 0x0400) && !!(s->csr[0] & 0x0400)) /* RINT */ ||
(!(s->csr[3] & 0x0800) && !!(s->csr[0] & 0x0800)) /* MERR */ ||
(!(s->csr[4] & 0x0001) && !!(s->csr[4] & 0x0002)) /* JAB */ ||
(!(s->csr[4] & 0x0004) && !!(s->csr[4] & 0x0008)) /* TXSTRT */ ||
(!(s->csr[4] & 0x0010) && !!(s->csr[4] & 0x0020)) /* RCVO */ ||
(!(s->csr[4] & 0x0100) && !!(s->csr[4] & 0x0200)) /* MFCO */ ||
(!!(s->csr[5] & 0x0040) && !!(s->csr[5] & 0x0080)) /* EXDINT */ ||
(!!(s->csr[5] & 0x0008) && !!(s->csr[5] & 0x0010)) /* MPINT */)
#endif
{
isr = CSR_INEA(s);
s->csr[0] |= 0x0080;
}
if (!!(s->csr[4] & 0x0080) && CSR_INEA(s)) { /* UINT */
s->csr[4] &= ~0x0080;
s->csr[4] |= 0x0040;
s->csr[0] |= 0x0080;
isr = 1;
trace_pcnet_user_int(s);
}
#if 1
if (((s->csr[5]>>1) & s->csr[5]) & 0x0500)
#else
if ((!!(s->csr[5] & 0x0400) && !!(s->csr[5] & 0x0800)) /* SINT */ ||
(!!(s->csr[5] & 0x0100) && !!(s->csr[5] & 0x0200)) /* SLPINT */ )
#endif
{
isr = 1;
s->csr[0] |= 0x0080;
}
if (isr != s->isr) {
trace_pcnet_isr_change(s, isr, s->isr);
}
qemu_set_irq(s->irq, isr);
s->isr = isr;
}
Commit Message:
CWE ID: CWE-119 | 0 | 14,536 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: inherit_task_group(struct perf_event *event, struct task_struct *parent,
struct perf_event_context *parent_ctx,
struct task_struct *child, int ctxn,
int *inherited_all)
{
int ret;
struct perf_event_context *child_ctx;
if (!event->attr.inherit) {
*inherited_all = 0;
return 0;
}
child_ctx = child->perf_event_ctxp[ctxn];
if (!child_ctx) {
/*
* This is executed from the parent task context, so
* inherit events that have been marked for cloning.
* First allocate and initialize a context for the
* child.
*/
child_ctx = alloc_perf_context(event->pmu, child);
if (!child_ctx)
return -ENOMEM;
child->perf_event_ctxp[ctxn] = child_ctx;
}
ret = inherit_group(event, parent, parent_ctx,
child, child_ctx);
if (ret)
*inherited_all = 0;
return ret;
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <a.p.zijlstra@chello.nl>
Cc: Michael Cree <mcree@orcon.net.nz>
Cc: Will Deacon <will.deacon@arm.com>
Cc: Deng-Cheng Zhu <dengcheng.zhu@gmail.com>
Cc: Anton Blanchard <anton@samba.org>
Cc: Eric B Munson <emunson@mgebm.net>
Cc: Heiko Carstens <heiko.carstens@de.ibm.com>
Cc: Paul Mundt <lethal@linux-sh.org>
Cc: David S. Miller <davem@davemloft.net>
Cc: Frederic Weisbecker <fweisbec@gmail.com>
Cc: Jason Wessel <jason.wessel@windriver.com>
Cc: Don Zickus <dzickus@redhat.com>
Link: http://lkml.kernel.org/n/tip-agjev8eu666tvknpb3iaj0fg@git.kernel.org
Signed-off-by: Ingo Molnar <mingo@elte.hu>
CWE ID: CWE-399 | 0 | 26,014 |
Analyze the following 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 AXNodeObject::isRequired() const {
Node* n = this->getNode();
if (n && (n->isElementNode() && toElement(n)->isFormControlElement()) &&
hasAttribute(requiredAttr))
return toHTMLFormControlElement(n)->isRequired();
if (equalIgnoringCase(getAttribute(aria_requiredAttr), "true"))
return true;
return false;
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254 | 1 | 171,919 |
Analyze the following 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 kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
{
if (vcpu->guest_fpu_loaded)
return;
/*
* Restore all possible states in the guest,
* and assume host would use all available bits.
* Guest xcr0 would be loaded later.
*/
kvm_put_guest_xcr0(vcpu);
vcpu->guest_fpu_loaded = 1;
__kernel_fpu_begin();
fpu_restore_checking(&vcpu->arch.guest_fpu);
trace_kvm_fpu(1);
}
Commit Message: KVM: x86: Convert vapic synchronization to _cached functions (CVE-2013-6368)
In kvm_lapic_sync_from_vapic and kvm_lapic_sync_to_vapic there is the
potential to corrupt kernel memory if userspace provides an address that
is at the end of a page. This patches concerts those functions to use
kvm_write_guest_cached and kvm_read_guest_cached. It also checks the
vapic_address specified by userspace during ioctl processing and returns
an error to userspace if the address is not a valid GPA.
This is generally not guest triggerable, because the required write is
done by firmware that runs before the guest. Also, it only affects AMD
processors and oldish Intel that do not have the FlexPriority feature
(unless you disable FlexPriority, of course; then newer processors are
also affected).
Fixes: b93463aa59d6 ('KVM: Accelerated apic support')
Reported-by: Andrew Honig <ahonig@google.com>
Cc: stable@vger.kernel.org
Signed-off-by: Andrew Honig <ahonig@google.com>
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
CWE ID: CWE-20 | 0 | 28,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: void SimulateMediaSessionChanged(
media_session::mojom::MediaPlaybackState playback_state) {
media_controls_view_->MediaSessionChanged(base::UnguessableToken::Create());
media_session::mojom::MediaSessionInfoPtr session_info(
media_session::mojom::MediaSessionInfo::New());
session_info->playback_state = playback_state;
media_controls_view_->MediaSessionInfoChanged(session_info.Clone());
}
Commit Message: [Lock Screen Media Controls] Tweak UI based on new mocks
This CL rearranges the different components of the CrOS lock screen
media controls based on the newest mocks. This involves resizing most
of the child views and their spacings. The artwork was also resized
and re-positioned. Additionally, the close button was moved from the
main view to the header row child view.
Artist and title data about the current session will eventually be
placed to the right of the artwork, but right now this space is empty.
See the bug for before and after pictures.
Bug: 991647
Change-Id: I7b97f31982ccf2912bd2564d5241bfd849d21d92
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1746554
Reviewed-by: Xiyuan Xia <xiyuan@chromium.org>
Reviewed-by: Becca Hughes <beccahughes@chromium.org>
Commit-Queue: Mia Bergeron <miaber@google.com>
Cr-Commit-Position: refs/heads/master@{#686253}
CWE ID: CWE-200 | 0 | 136,518 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: status_t BnOMX::onTransact(
uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) {
switch (code) {
case LIVES_LOCALLY:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
pid_t pid = (pid_t)data.readInt32();
reply->writeInt32(livesLocally(node, pid));
return OK;
}
case LIST_NODES:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
List<ComponentInfo> list;
listNodes(&list);
reply->writeInt32(list.size());
for (List<ComponentInfo>::iterator it = list.begin();
it != list.end(); ++it) {
ComponentInfo &cur = *it;
reply->writeString8(cur.mName);
reply->writeInt32(cur.mRoles.size());
for (List<String8>::iterator role_it = cur.mRoles.begin();
role_it != cur.mRoles.end(); ++role_it) {
reply->writeString8(*role_it);
}
}
return NO_ERROR;
}
case ALLOCATE_NODE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
const char *name = data.readCString();
sp<IOMXObserver> observer =
interface_cast<IOMXObserver>(data.readStrongBinder());
node_id node;
status_t err = allocateNode(name, observer, &node);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)node);
}
return NO_ERROR;
}
case FREE_NODE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
reply->writeInt32(freeNode(node));
return NO_ERROR;
}
case SEND_COMMAND:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_COMMANDTYPE cmd =
static_cast<OMX_COMMANDTYPE>(data.readInt32());
OMX_S32 param = data.readInt32();
reply->writeInt32(sendCommand(node, cmd, param));
return NO_ERROR;
}
case GET_PARAMETER:
case SET_PARAMETER:
case GET_CONFIG:
case SET_CONFIG:
case SET_INTERNAL_OPTION:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_INDEXTYPE index = static_cast<OMX_INDEXTYPE>(data.readInt32());
size_t size = data.readInt64();
void *params = malloc(size);
data.read(params, size);
status_t err;
switch (code) {
case GET_PARAMETER:
err = getParameter(node, index, params, size);
break;
case SET_PARAMETER:
err = setParameter(node, index, params, size);
break;
case GET_CONFIG:
err = getConfig(node, index, params, size);
break;
case SET_CONFIG:
err = setConfig(node, index, params, size);
break;
case SET_INTERNAL_OPTION:
{
InternalOptionType type =
(InternalOptionType)data.readInt32();
err = setInternalOption(node, index, type, params, size);
break;
}
default:
TRESPASS();
}
reply->writeInt32(err);
if ((code == GET_PARAMETER || code == GET_CONFIG) && err == OK) {
reply->write(params, size);
}
free(params);
params = NULL;
return NO_ERROR;
}
case GET_STATE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_STATETYPE state = OMX_StateInvalid;
status_t err = getState(node, &state);
reply->writeInt32(state);
reply->writeInt32(err);
return NO_ERROR;
}
case ENABLE_GRAPHIC_BUFFERS:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL enable = (OMX_BOOL)data.readInt32();
status_t err = enableGraphicBuffers(node, port_index, enable);
reply->writeInt32(err);
return NO_ERROR;
}
case GET_GRAPHIC_BUFFER_USAGE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_U32 usage = 0;
status_t err = getGraphicBufferUsage(node, port_index, &usage);
reply->writeInt32(err);
reply->writeInt32(usage);
return NO_ERROR;
}
case USE_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IMemory> params =
interface_cast<IMemory>(data.readStrongBinder());
OMX_U32 allottedSize = data.readInt32();
buffer_id buffer;
status_t err = useBuffer(node, port_index, params, &buffer, allottedSize);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
}
return NO_ERROR;
}
case USE_GRAPHIC_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<GraphicBuffer> graphicBuffer = new GraphicBuffer();
data.read(*graphicBuffer);
buffer_id buffer;
status_t err = useGraphicBuffer(
node, port_index, graphicBuffer, &buffer);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
}
return NO_ERROR;
}
case UPDATE_GRAPHIC_BUFFER_IN_META:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<GraphicBuffer> graphicBuffer = new GraphicBuffer();
data.read(*graphicBuffer);
buffer_id buffer = (buffer_id)data.readInt32();
status_t err = updateGraphicBufferInMeta(
node, port_index, graphicBuffer, buffer);
reply->writeInt32(err);
return NO_ERROR;
}
case CREATE_INPUT_SURFACE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IGraphicBufferProducer> bufferProducer;
MetadataBufferType type;
status_t err = createInputSurface(node, port_index, &bufferProducer, &type);
reply->writeInt32(type);
reply->writeInt32(err);
if (err == OK) {
reply->writeStrongBinder(IInterface::asBinder(bufferProducer));
}
return NO_ERROR;
}
case CREATE_PERSISTENT_INPUT_SURFACE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
sp<IGraphicBufferProducer> bufferProducer;
sp<IGraphicBufferConsumer> bufferConsumer;
status_t err = createPersistentInputSurface(
&bufferProducer, &bufferConsumer);
reply->writeInt32(err);
if (err == OK) {
reply->writeStrongBinder(IInterface::asBinder(bufferProducer));
reply->writeStrongBinder(IInterface::asBinder(bufferConsumer));
}
return NO_ERROR;
}
case SET_INPUT_SURFACE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IGraphicBufferConsumer> bufferConsumer =
interface_cast<IGraphicBufferConsumer>(data.readStrongBinder());
MetadataBufferType type;
status_t err = setInputSurface(node, port_index, bufferConsumer, &type);
reply->writeInt32(type);
reply->writeInt32(err);
return NO_ERROR;
}
case SIGNAL_END_OF_INPUT_STREAM:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
status_t err = signalEndOfInputStream(node);
reply->writeInt32(err);
return NO_ERROR;
}
case STORE_META_DATA_IN_BUFFERS:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL enable = (OMX_BOOL)data.readInt32();
MetadataBufferType type;
status_t err = storeMetaDataInBuffers(node, port_index, enable, &type);
reply->writeInt32(type);
reply->writeInt32(err);
return NO_ERROR;
}
case PREPARE_FOR_ADAPTIVE_PLAYBACK:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL enable = (OMX_BOOL)data.readInt32();
OMX_U32 max_width = data.readInt32();
OMX_U32 max_height = data.readInt32();
status_t err = prepareForAdaptivePlayback(
node, port_index, enable, max_width, max_height);
reply->writeInt32(err);
return NO_ERROR;
}
case CONFIGURE_VIDEO_TUNNEL_MODE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL tunneled = (OMX_BOOL)data.readInt32();
OMX_U32 audio_hw_sync = data.readInt32();
native_handle_t *sideband_handle = NULL;
status_t err = configureVideoTunnelMode(
node, port_index, tunneled, audio_hw_sync, &sideband_handle);
reply->writeInt32(err);
if(err == OK){
reply->writeNativeHandle(sideband_handle);
}
return NO_ERROR;
}
case ALLOC_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
if (!isSecure(node) || port_index != 0 /* kPortIndexInput */) {
ALOGE("b/24310423");
reply->writeInt32(INVALID_OPERATION);
return NO_ERROR;
}
size_t size = data.readInt64();
buffer_id buffer;
void *buffer_data;
status_t err = allocateBuffer(
node, port_index, size, &buffer, &buffer_data);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
reply->writeInt64((uintptr_t)buffer_data);
}
return NO_ERROR;
}
case ALLOC_BUFFER_WITH_BACKUP:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IMemory> params =
interface_cast<IMemory>(data.readStrongBinder());
OMX_U32 allottedSize = data.readInt32();
buffer_id buffer;
status_t err = allocateBufferWithBackup(
node, port_index, params, &buffer, allottedSize);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
}
return NO_ERROR;
}
case FREE_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
buffer_id buffer = (buffer_id)data.readInt32();
reply->writeInt32(freeBuffer(node, port_index, buffer));
return NO_ERROR;
}
case FILL_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
buffer_id buffer = (buffer_id)data.readInt32();
bool haveFence = data.readInt32();
int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1;
reply->writeInt32(fillBuffer(node, buffer, fenceFd));
return NO_ERROR;
}
case EMPTY_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
buffer_id buffer = (buffer_id)data.readInt32();
OMX_U32 range_offset = data.readInt32();
OMX_U32 range_length = data.readInt32();
OMX_U32 flags = data.readInt32();
OMX_TICKS timestamp = data.readInt64();
bool haveFence = data.readInt32();
int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1;
reply->writeInt32(emptyBuffer(
node, buffer, range_offset, range_length, flags, timestamp, fenceFd));
return NO_ERROR;
}
case GET_EXTENSION_INDEX:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
const char *parameter_name = data.readCString();
OMX_INDEXTYPE index;
status_t err = getExtensionIndex(node, parameter_name, &index);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32(index);
}
return OK;
}
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
Commit Message: 3 uninitialized variables in IOMX.cpp
Uninitialized MetadataBufferType pointer in case:
SET_INPUT_SURFACE
STORE_META_DATA_IN_BUFFERS
CREATE_INPUT_SURFACE
Fix: initialize them to kMetadataBufferTypeInvalid
Bug: 26324358
Change-Id: Ib3bcac9bedc98bc65efa39f67cdbffbd90b374c9
CWE ID: CWE-119 | 1 | 173,892 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void WebContentsImpl::UpdateDeviceScaleFactor(double device_scale_factor) {
SendPageMessage(
new PageMsg_SetDeviceScaleFactor(MSG_ROUTING_NONE, device_scale_factor));
}
Commit Message: If JavaScript shows a dialog, cause the page to lose fullscreen.
BUG=670135, 550017, 726761, 728276
Review-Url: https://codereview.chromium.org/2906133004
Cr-Commit-Position: refs/heads/master@{#478884}
CWE ID: CWE-20 | 0 | 135,905 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: get_principal_2_svc(gprinc_arg *arg, struct svc_req *rqstp)
{
static gprinc_ret ret;
char *prime_arg, *funcname;
gss_buffer_desc client_name,
service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_gprinc_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
funcname = "kadm5_get_principal";
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (! cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ) &&
(CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context,
rqst2name(rqstp),
ACL_INQUIRE,
arg->princ,
NULL))) {
ret.code = KADM5_AUTH_GET;
log_unauth(funcname, prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_get_principal(handle, arg->princ, &ret.rec,
arg->mask);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done(funcname, prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631]
In each kadmind server stub, initialize the client_name and
server_name variables, and release them in the cleanup handler. Many
of the stubs will otherwise leak the client and server name if
krb5_unparse_name() fails. Also make sure to free the prime_arg
variables in rename_principal_2_svc(), or we can leak the first one if
unparsing the second one fails. Discovered by Simo Sorce.
CVE-2015-8631:
In all versions of MIT krb5, an authenticated attacker can cause
kadmind to leak memory by supplying a null principal name in a request
which uses one. Repeating these requests will eventually cause
kadmind to exhaust all available memory.
CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C
ticket: 8343 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
CWE ID: CWE-119 | 1 | 167,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: BGD_DECLARE(int) gdAlphaBlend (int dst, int src)
{
int src_alpha = gdTrueColorGetAlpha(src);
int dst_alpha, alpha, red, green, blue;
int src_weight, dst_weight, tot_weight;
/* -------------------------------------------------------------------- */
/* Simple cases we want to handle fast. */
/* -------------------------------------------------------------------- */
if( src_alpha == gdAlphaOpaque )
return src;
dst_alpha = gdTrueColorGetAlpha(dst);
if( src_alpha == gdAlphaTransparent )
return dst;
if( dst_alpha == gdAlphaTransparent )
return src;
/* -------------------------------------------------------------------- */
/* What will the source and destination alphas be? Note that */
/* the destination weighting is substantially reduced as the */
/* overlay becomes quite opaque. */
/* -------------------------------------------------------------------- */
src_weight = gdAlphaTransparent - src_alpha;
dst_weight = (gdAlphaTransparent - dst_alpha) * src_alpha / gdAlphaMax;
tot_weight = src_weight + dst_weight;
/* -------------------------------------------------------------------- */
/* What red, green and blue result values will we use? */
/* -------------------------------------------------------------------- */
alpha = src_alpha * dst_alpha / gdAlphaMax;
red = (gdTrueColorGetRed(src) * src_weight
+ gdTrueColorGetRed(dst) * dst_weight) / tot_weight;
green = (gdTrueColorGetGreen(src) * src_weight
+ gdTrueColorGetGreen(dst) * dst_weight) / tot_weight;
blue = (gdTrueColorGetBlue(src) * src_weight
+ gdTrueColorGetBlue(dst) * dst_weight) / tot_weight;
/* -------------------------------------------------------------------- */
/* Return merged result. */
/* -------------------------------------------------------------------- */
return ((alpha << 24) + (red << 16) + (green << 8) + blue);
}
Commit Message: Fix #340: System frozen
gdImageCreate() doesn't check for oversized images and as such is prone
to DoS vulnerabilities. We fix that by applying the same overflow check
that is already in place for gdImageCreateTrueColor().
CVE-2016-9317
CWE ID: CWE-20 | 0 | 73,029 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: hfs_convert_2_unix_time(uint32_t hfsdate)
{
if (hfsdate < NSEC_BTWN_1904_1970)
return 0;
return (uint32_t) (hfsdate - NSEC_BTWN_1904_1970);
}
Commit Message: Merge pull request #1374 from JordyZomer/develop
Fix CVE-2018-19497.
CWE ID: CWE-125 | 0 | 75,683 |
Analyze the following 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 mddev_congested(struct mddev *mddev, int bits)
{
struct md_personality *pers = mddev->pers;
int ret = 0;
rcu_read_lock();
if (mddev->suspended)
ret = 1;
else if (pers && pers->congested)
ret = pers->congested(mddev, bits);
rcu_read_unlock();
return ret;
}
Commit Message: md: use kzalloc() when bitmap is disabled
In drivers/md/md.c get_bitmap_file() uses kmalloc() for creating a
mdu_bitmap_file_t called "file".
5769 file = kmalloc(sizeof(*file), GFP_NOIO);
5770 if (!file)
5771 return -ENOMEM;
This structure is copied to user space at the end of the function.
5786 if (err == 0 &&
5787 copy_to_user(arg, file, sizeof(*file)))
5788 err = -EFAULT
But if bitmap is disabled only the first byte of "file" is initialized
with zero, so it's possible to read some bytes (up to 4095) of kernel
space memory from user space. This is an information leak.
5775 /* bitmap disabled, zero the first byte and copy out */
5776 if (!mddev->bitmap_info.file)
5777 file->pathname[0] = '\0';
Signed-off-by: Benjamin Randazzo <benjamin@randazzo.fr>
Signed-off-by: NeilBrown <neilb@suse.com>
CWE ID: CWE-200 | 0 | 42,485 |
Analyze the following 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 has_ns_capability(struct task_struct *t,
struct user_namespace *ns, int cap)
{
int ret;
rcu_read_lock();
ret = security_capable(__task_cred(t), ns, cap);
rcu_read_unlock();
return (ret == 0);
}
Commit Message: fs,userns: Change inode_capable to capable_wrt_inode_uidgid
The kernel has no concept of capabilities with respect to inodes; inodes
exist independently of namespaces. For example, inode_capable(inode,
CAP_LINUX_IMMUTABLE) would be nonsense.
This patch changes inode_capable to check for uid and gid mappings and
renames it to capable_wrt_inode_uidgid, which should make it more
obvious what it does.
Fixes CVE-2014-4014.
Cc: Theodore Ts'o <tytso@mit.edu>
Cc: Serge Hallyn <serge.hallyn@ubuntu.com>
Cc: "Eric W. Biederman" <ebiederm@xmission.com>
Cc: Dave Chinner <david@fromorbit.com>
Cc: stable@vger.kernel.org
Signed-off-by: Andy Lutomirski <luto@amacapital.net>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID: CWE-264 | 0 | 36,939 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: views::Combobox* AutofillDialogViews::ComboboxForType(
ServerFieldType type) {
for (DetailGroupMap::iterator iter = detail_groups_.begin();
iter != detail_groups_.end(); ++iter) {
const DetailsGroup& group = iter->second;
if (!delegate_->SectionIsActive(group.section))
continue;
ComboboxMap::const_iterator combo_mapping = group.comboboxes.find(type);
if (combo_mapping != group.comboboxes.end())
return combo_mapping->second;
}
return NULL;
}
Commit Message: Clear out some minor TODOs.
BUG=none
Review URL: https://codereview.chromium.org/1047063002
Cr-Commit-Position: refs/heads/master@{#322959}
CWE ID: CWE-20 | 0 | 109,943 |
Analyze the following 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 V8Window::toStringMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> domWrapper = V8Window::findInstanceInPrototypeChain(info.This(), info.GetIsolate());
if (domWrapper.IsEmpty()) {
v8SetReturnValue(info, info.This()->ObjectProtoToString());
return;
}
v8SetReturnValue(info, domWrapper->ObjectProtoToString());
}
Commit Message: Reload frame in V8Window::namedPropertyGetterCustom after js call
R=marja@chromium.org
BUG=454954
Review URL: https://codereview.chromium.org/901053006
git-svn-id: svn://svn.chromium.org/blink/trunk@189574 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | 0 | 129,081 |
Analyze the following 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 regulator_get_voltage(struct regulator *regulator)
{
int ret;
mutex_lock(®ulator->rdev->mutex);
ret = _regulator_get_voltage(regulator->rdev);
mutex_unlock(®ulator->rdev->mutex);
return ret;
}
Commit Message: regulator: core: Fix regualtor_ena_gpio_free not to access pin after freeing
After freeing pin from regulator_ena_gpio_free, loop can access
the pin. So this patch fixes not to access pin after freeing.
Signed-off-by: Seung-Woo Kim <sw0312.kim@samsung.com>
Signed-off-by: Mark Brown <broonie@kernel.org>
CWE ID: CWE-416 | 0 | 74,512 |
Analyze the following 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 ff_lock_avcodec(AVCodecContext *log_ctx, const AVCodec *codec)
{
if (!(codec->caps_internal & FF_CODEC_CAP_INIT_THREADSAFE) && codec->init)
ff_mutex_lock(&codec_mutex);
}
Commit Message: avcodec/utils: Check close before calling it
Fixes: NULL pointer dereference
Fixes: 15733/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_IDF_fuzzer-5658616977162240
Reviewed-by: Paul B Mahol <onemda@gmail.com>
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
CWE ID: | 0 | 87,333 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: WebContents* SavePackage::web_contents() const {
return WebContentsObserver::web_contents();
}
Commit Message: Fix crash with mismatched vector sizes.
BUG=169295
Review URL: https://codereview.chromium.org/11817050
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176252 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | 0 | 115,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 InitOMXParams(T *params) {
memset(params, 0, sizeof(T));
params->nSize = sizeof(T);
params->nVersion.s.nVersionMajor = 1;
params->nVersion.s.nVersionMinor = 0;
params->nVersion.s.nRevision = 0;
params->nVersion.s.nStep = 0;
}
Commit Message: IOMX: Enable buffer ptr to buffer id translation for arm32
Bug: 20634516
Change-Id: Iac9eac3cb251eccd9bbad5df7421a07edc21da0c
(cherry picked from commit 2d6b6601743c3c6960c6511a2cb774ef902759f4)
CWE ID: CWE-119 | 0 | 157,540 |
Analyze the following 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 uint32_t lnc_mchash(const uint8_t *ether_addr)
{
#define LNC_POLYNOMIAL 0xEDB88320UL
uint32_t crc = 0xFFFFFFFF;
int idx, bit;
uint8_t data;
for (idx = 0; idx < 6; idx++) {
for (data = *ether_addr++, bit = 0; bit < MULTICAST_FILTER_LEN; bit++) {
crc = (crc >> 1) ^ (((crc ^ data) & 1) ? LNC_POLYNOMIAL : 0);
data >>= 1;
}
}
return crc;
#undef LNC_POLYNOMIAL
}
Commit Message:
CWE ID: CWE-119 | 0 | 14,509 |
Analyze the following 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 __exit ebtables_fini(void)
{
nf_unregister_sockopt(&ebt_sockopts);
xt_unregister_target(&ebt_standard_target);
}
Commit Message: netfilter: ebtables: CONFIG_COMPAT: don't trust userland offsets
We need to make sure the offsets are not out of range of the
total size.
Also check that they are in ascending order.
The WARN_ON triggered by syzkaller (it sets panic_on_warn) is
changed to also bail out, no point in continuing parsing.
Briefly tested with simple ruleset of
-A INPUT --limit 1/s' --log
plus jump to custom chains using 32bit ebtables binary.
Reported-by: <syzbot+845a53d13171abf8bf29@syzkaller.appspotmail.com>
Signed-off-by: Florian Westphal <fw@strlen.de>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
CWE ID: CWE-787 | 0 | 84,875 |
Analyze the following 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 RenderViewImpl::OnSetInitialFocus(bool reverse) {
if (!webview())
return;
webview()->SetInitialFocus(reverse);
}
Commit Message: Prevent renderer initiated back navigation to cancel a browser one.
Renderer initiated back/forward navigations must not be able to cancel ongoing
browser initiated navigation if they are not user initiated.
Note: 'normal' renderer initiated navigation uses the
FrameHost::BeginNavigation() path. A code similar to this patch is done
in NavigatorImpl::OnBeginNavigation().
Test:
-----
Added: NavigationBrowserTest.
* HistoryBackInBeforeUnload
* HistoryBackInBeforeUnloadAfterSetTimeout
* HistoryBackCancelPendingNavigationNoUserGesture
* HistoryBackCancelPendingNavigationUserGesture
Fixed:
* (WPT) .../the-history-interface/traverse_the_history_2.html
* (WPT) .../the-history-interface/traverse_the_history_3.html
* (WPT) .../the-history-interface/traverse_the_history_4.html
* (WPT) .../the-history-interface/traverse_the_history_5.html
Bug: 879965
Change-Id: I1a9bfaaea1ffc219e6c32f6e676b660e746c578c
Reviewed-on: https://chromium-review.googlesource.com/1209744
Commit-Queue: Arthur Sonzogni <arthursonzogni@chromium.org>
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Reviewed-by: Mustaq Ahmed <mustaq@chromium.org>
Reviewed-by: Camille Lamy <clamy@chromium.org>
Reviewed-by: Charlie Reis <creis@chromium.org>
Cr-Commit-Position: refs/heads/master@{#592823}
CWE ID: CWE-254 | 0 | 145,147 |
Analyze the following 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 __init ip_vs_control_init(void)
{
int idx;
int ret;
EnterFunction(2);
/* Initialize svc_table, ip_vs_svc_fwm_table, rs_table */
for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
INIT_LIST_HEAD(&ip_vs_svc_table[idx]);
INIT_LIST_HEAD(&ip_vs_svc_fwm_table[idx]);
}
smp_wmb(); /* Do we really need it now ? */
ret = register_netdevice_notifier(&ip_vs_dst_notifier);
if (ret < 0)
return ret;
LeaveFunction(2);
return 0;
}
Commit Message: ipvs: fix info leak in getsockopt(IP_VS_SO_GET_TIMEOUT)
If at least one of CONFIG_IP_VS_PROTO_TCP or CONFIG_IP_VS_PROTO_UDP is
not set, __ip_vs_get_timeouts() does not fully initialize the structure
that gets copied to userland and that for leaks up to 12 bytes of kernel
stack. Add an explicit memset(0) before passing the structure to
__ip_vs_get_timeouts() to avoid the info leak.
Signed-off-by: Mathias Krause <minipli@googlemail.com>
Cc: Wensong Zhang <wensong@linux-vs.org>
Cc: Simon Horman <horms@verge.net.au>
Cc: Julian Anastasov <ja@ssi.bg>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-200 | 0 | 34,186 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: BpOMX(const sp<IBinder> &impl)
: BpInterface<IOMX>(impl) {
}
Commit Message: Fix size check for OMX_IndexParamConsumerUsageBits
since it doesn't follow the OMX convention. And remove support
for the kClientNeedsFrameBuffer flag.
Bug: 27207275
Change-Id: Ia2c119e2456ebf9e2f4e1de5104ef9032a212255
CWE ID: CWE-119 | 0 | 160,666 |
Analyze the following 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 DelayedExecutor::delayedExecute(const QString &udi)
{
Solid::Device device(udi);
QString exec = m_service.exec();
MacroExpander mx(device);
mx.expandMacros(exec);
KRun::runCommand(exec, QString(), m_service.icon(), 0);
deleteLater();
}
Commit Message:
CWE ID: CWE-78 | 1 | 165,024 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: pdf14_get_buffer_information(const gx_device * dev,
gx_pattern_trans_t *transbuff, gs_memory_t *mem,
bool free_device)
{
const pdf14_device * pdev = (pdf14_device *)dev;
pdf14_buf *buf;
gs_int_rect rect;
int x1,y1,width,height;
if ( pdev->ctx == NULL){
return 0; /* this can occur if the pattern is a clist */
}
#ifdef DEBUG
pdf14_debug_mask_stack_state(pdev->ctx);
#endif
buf = pdev->ctx->stack;
rect = buf->rect;
transbuff->dirty = &buf->dirty;
x1 = min(pdev->width, rect.q.x);
y1 = min(pdev->height, rect.q.y);
width = x1 - rect.p.x;
height = y1 - rect.p.y;
if (width <= 0 || height <= 0 || buf->data == NULL)
return 0;
transbuff->n_chan = buf->n_chan;
transbuff->has_shape = buf->has_shape;
transbuff->width = buf->rect.q.x - buf->rect.p.x;
transbuff->height = buf->rect.q.y - buf->rect.p.y;
if (free_device) {
transbuff->pdev14 = NULL;
transbuff->rect = rect;
if ((width < transbuff->width) || (height < transbuff->height)) {
/* If the bbox is smaller than the whole buffer than go ahead and
create a new one to use. This can occur if we drew in a smaller
area than was specified by the transparency group rect. */
int rowstride = (width + 3) & -4;
int planestride = rowstride * height;
int k, j;
byte *buff_ptr_src, *buff_ptr_des;
transbuff->planestride = planestride;
transbuff->rowstride = rowstride;
transbuff->transbytes = gs_alloc_bytes(mem, planestride*buf->n_chan,
"pdf14_get_buffer_information");
transbuff->mem = mem;
for (j = 0; j < transbuff->n_chan; j++) {
buff_ptr_src = buf->data + j * buf->planestride +
buf->rowstride * rect.p.y + rect.p.x;
buff_ptr_des = transbuff->transbytes + j * planestride;
for (k = 0; k < height; k++) {
memcpy(buff_ptr_des, buff_ptr_src,rowstride);
buff_ptr_des += rowstride;
buff_ptr_src += buf->rowstride;
}
}
} else {
/* The entire buffer is used. Go ahead and grab the pointer and
clear the pointer in the pdf14 device data buffer so it is not
freed when we close the device */
transbuff->planestride = buf->planestride;
transbuff->rowstride = buf->rowstride;
transbuff->transbytes = buf->data;
transbuff->mem = dev->memory;
buf->data = NULL; /* So that the buffer is not freed */
}
/* Go ahead and free up the pdf14 device */
dev_proc(dev, close_device)((gx_device *)dev);
#if RAW_DUMP
/* Dump the buffer that should be going into the pattern */;
dump_raw_buffer(height, width, transbuff->n_chan,
transbuff->planestride, transbuff->rowstride,
"pdf14_pattern_buff", transbuff->transbytes);
global_index++;
#endif
} else {
/* Here we are coming from one of the fill image / pattern / mask
operations */
transbuff->pdev14 = dev;
transbuff->planestride = buf->planestride;
transbuff->rowstride = buf->rowstride;
transbuff->transbytes = buf->data;
transbuff->mem = dev->memory;
transbuff->rect = rect;
#if RAW_DUMP
/* Dump the buffer that should be going into the pattern */;
dump_raw_buffer(height, width, buf->n_chan,
pdev->ctx->stack->planestride, pdev->ctx->stack->rowstride,
"pdf14_pattern_buff", buf->data +
transbuff->rowstride * transbuff->rect.p.y +
transbuff->rect.p.x);
global_index++;
#endif
}
return(0);
}
Commit Message:
CWE ID: CWE-476 | 0 | 13,315 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void Browser::RendererResponsive(
WebContents* source,
content::RenderWidgetHost* render_widget_host) {
TabDialogs::FromWebContents(source)->HideHungRendererDialog(
render_widget_host);
}
Commit Message: If a dialog is shown, drop fullscreen.
BUG=875066, 817809, 792876, 812769, 813815
TEST=included
Change-Id: Ic3d697fa3c4b01f5d7fea77391857177ada660db
Reviewed-on: https://chromium-review.googlesource.com/1185208
Reviewed-by: Sidney San Martín <sdy@chromium.org>
Commit-Queue: Avi Drissman <avi@chromium.org>
Cr-Commit-Position: refs/heads/master@{#586418}
CWE ID: CWE-20 | 0 | 146,037 |
Analyze the following 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 Cues* Segment::GetCues() const
{
return m_pCues;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | 1 | 174,301 |
Analyze the following 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 handle_t *ext4_get_nojournal(void)
{
handle_t *handle = current->journal_info;
unsigned long ref_cnt = (unsigned long)handle;
BUG_ON(ref_cnt >= EXT4_NOJOURNAL_MAX_REF_COUNT);
ref_cnt++;
handle = (handle_t *)ref_cnt;
current->journal_info = handle;
return handle;
}
Commit Message: ext4: fix undefined behavior in ext4_fill_flex_info()
Commit 503358ae01b70ce6909d19dd01287093f6b6271c ("ext4: avoid divide by
zero when trying to mount a corrupted file system") fixes CVE-2009-4307
by performing a sanity check on s_log_groups_per_flex, since it can be
set to a bogus value by an attacker.
sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex;
groups_per_flex = 1 << sbi->s_log_groups_per_flex;
if (groups_per_flex < 2) { ... }
This patch fixes two potential issues in the previous commit.
1) The sanity check might only work on architectures like PowerPC.
On x86, 5 bits are used for the shifting amount. That means, given a
large s_log_groups_per_flex value like 36, groups_per_flex = 1 << 36
is essentially 1 << 4 = 16, rather than 0. This will bypass the check,
leaving s_log_groups_per_flex and groups_per_flex inconsistent.
2) The sanity check relies on undefined behavior, i.e., oversized shift.
A standard-confirming C compiler could rewrite the check in unexpected
ways. Consider the following equivalent form, assuming groups_per_flex
is unsigned for simplicity.
groups_per_flex = 1 << sbi->s_log_groups_per_flex;
if (groups_per_flex == 0 || groups_per_flex == 1) {
We compile the code snippet using Clang 3.0 and GCC 4.6. Clang will
completely optimize away the check groups_per_flex == 0, leaving the
patched code as vulnerable as the original. GCC keeps the check, but
there is no guarantee that future versions will do the same.
Signed-off-by: Xi Wang <xi.wang@gmail.com>
Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
Cc: stable@vger.kernel.org
CWE ID: CWE-189 | 0 | 20,478 |
Analyze the following 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 GetMatchingURLCountAndMostRecentCreationTime(
const std::map<int64_t, OfflinePageItem>& offline_pages,
std::string name_space,
const GURL& url,
base::Time created_before,
int* matching_url_count,
base::TimeDelta* most_recent_creation_time) {
int count = 0;
base::Time latest_time;
bool matching_page = false;
for (auto& id_page_pair : offline_pages) {
if (id_page_pair.second.client_id.name_space == name_space &&
url == id_page_pair.second.url) {
count++;
base::Time page_creation_time = id_page_pair.second.creation_time;
if (page_creation_time < created_before &&
page_creation_time > latest_time) {
latest_time = page_creation_time;
matching_page = true;
}
}
}
if (matching_url_count != nullptr)
*matching_url_count = count;
if (most_recent_creation_time != nullptr && latest_time != base::Time())
*most_recent_creation_time = created_before - latest_time;
return matching_page;
}
Commit Message: Add the method to check if offline archive is in internal dir
Bug: 758690
Change-Id: I8bb4283fc40a87fa7a87df2c7e513e2e16903290
Reviewed-on: https://chromium-review.googlesource.com/828049
Reviewed-by: Filip Gorski <fgorski@chromium.org>
Commit-Queue: Jian Li <jianli@chromium.org>
Cr-Commit-Position: refs/heads/master@{#524232}
CWE ID: CWE-787 | 0 | 155,882 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void RenderProcessHostImpl::CreateMessageFilters() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
AddFilter(new ResourceSchedulerFilter(GetID()));
MediaInternals* media_internals = MediaInternals::GetInstance();
scoped_refptr<BrowserPluginMessageFilter> bp_message_filter(
new BrowserPluginMessageFilter(GetID()));
AddFilter(bp_message_filter.get());
scoped_refptr<net::URLRequestContextGetter> request_context(
storage_partition_impl_->GetURLRequestContext());
scoped_refptr<RenderMessageFilter> render_message_filter(
new RenderMessageFilter(
GetID(), GetBrowserContext(), request_context.get(),
widget_helper_.get(), media_internals,
storage_partition_impl_->GetDOMStorageContext(),
storage_partition_impl_->GetCacheStorageContext()));
AddFilter(render_message_filter.get());
render_frame_message_filter_ = new RenderFrameMessageFilter(
GetID(),
#if BUILDFLAG(ENABLE_PLUGINS)
PluginServiceImpl::GetInstance(),
#else
nullptr,
#endif
GetBrowserContext(),
request_context.get(),
widget_helper_.get());
AddFilter(render_frame_message_filter_.get());
BrowserContext* browser_context = GetBrowserContext();
ResourceContext* resource_context = browser_context->GetResourceContext();
scoped_refptr<net::URLRequestContextGetter> media_request_context(
GetStoragePartition()->GetMediaURLRequestContext());
ResourceMessageFilter::GetContextsCallback get_contexts_callback(base::Bind(
&GetContexts, resource_context, request_context, media_request_context));
scoped_refptr<ChromeBlobStorageContext> blob_storage_context =
ChromeBlobStorageContext::GetFor(browser_context);
resource_message_filter_ = new ResourceMessageFilter(
GetID(), storage_partition_impl_->GetAppCacheService(),
blob_storage_context.get(),
storage_partition_impl_->GetFileSystemContext(),
storage_partition_impl_->GetServiceWorkerContext(), get_contexts_callback,
BrowserThread::GetTaskRunnerForThread(BrowserThread::IO));
AddFilter(resource_message_filter_.get());
media::AudioManager* audio_manager =
BrowserMainLoop::GetInstance()->audio_manager();
MediaStreamManager* media_stream_manager =
BrowserMainLoop::GetInstance()->media_stream_manager();
if (!RenderFrameAudioInputStreamFactory::UseMojoFactories()) {
AddFilter(base::MakeRefCounted<AudioInputRendererHost>(
GetID(), audio_manager, media_stream_manager,
AudioMirroringManager::GetInstance(),
BrowserMainLoop::GetInstance()->user_input_monitor())
.get());
}
if (!RendererAudioOutputStreamFactoryContextImpl::UseMojoFactories()) {
AddFilter(base::MakeRefCounted<AudioRendererHost>(
GetID(), audio_manager,
BrowserMainLoop::GetInstance()->audio_system(),
AudioMirroringManager::GetInstance(), media_stream_manager)
.get());
}
AddFilter(
new MidiHost(GetID(), BrowserMainLoop::GetInstance()->midi_service()));
AddFilter(new DOMStorageMessageFilter(
storage_partition_impl_->GetDOMStorageContext()));
#if BUILDFLAG(ENABLE_WEBRTC)
peer_connection_tracker_host_ = new PeerConnectionTrackerHost(GetID());
AddFilter(peer_connection_tracker_host_.get());
AddFilter(new MediaStreamTrackMetricsHost());
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
AddFilter(new PepperRendererConnection(GetID()));
#endif
AddFilter(new SpeechRecognitionDispatcherHost(
GetID(), storage_partition_impl_->GetURLRequestContext()));
AddFilter(new FileAPIMessageFilter(
GetID(), storage_partition_impl_->GetURLRequestContext(),
storage_partition_impl_->GetFileSystemContext(),
blob_storage_context.get()));
AddFilter(new BlobDispatcherHost(GetID(), blob_storage_context));
#if defined(OS_MACOSX)
AddFilter(new TextInputClientMessageFilter());
#endif
scoped_refptr<CacheStorageDispatcherHost> cache_storage_filter =
new CacheStorageDispatcherHost();
cache_storage_filter->Init(storage_partition_impl_->GetCacheStorageContext());
AddFilter(cache_storage_filter.get());
scoped_refptr<ServiceWorkerDispatcherHost> service_worker_filter =
new ServiceWorkerDispatcherHost(GetID(), resource_context);
service_worker_filter->Init(
storage_partition_impl_->GetServiceWorkerContext());
AddFilter(service_worker_filter.get());
#if BUILDFLAG(ENABLE_WEBRTC)
p2p_socket_dispatcher_host_ = new P2PSocketDispatcherHost(
resource_context, request_context.get());
AddFilter(p2p_socket_dispatcher_host_.get());
#endif
AddFilter(new TraceMessageFilter(GetID()));
AddFilter(new ResolveProxyMsgHelper(request_context.get()));
scoped_refptr<ServiceWorkerContextWrapper> service_worker_context(
static_cast<ServiceWorkerContextWrapper*>(
storage_partition_impl_->GetServiceWorkerContext()));
notification_message_filter_ = new NotificationMessageFilter(
GetID(), storage_partition_impl_->GetPlatformNotificationContext(),
resource_context, service_worker_context, browser_context);
AddFilter(notification_message_filter_.get());
#if defined(OS_ANDROID)
synchronous_compositor_filter_ =
new SynchronousCompositorBrowserFilter(GetID());
AddFilter(synchronous_compositor_filter_.get());
#endif
}
Commit Message: Correct mojo::WrapSharedMemoryHandle usage
Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which
were assuming that the call actually has any control over the memory
protection applied to a handle when mapped.
Where fixing usage is infeasible for this CL, TODOs are added to
annotate follow-up work.
Also updates the API and documentation to (hopefully) improve clarity
and avoid similar mistakes from being made in the future.
BUG=792900
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477
Reviewed-on: https://chromium-review.googlesource.com/818282
Reviewed-by: Wei Li <weili@chromium.org>
Reviewed-by: Lei Zhang <thestig@chromium.org>
Reviewed-by: John Abd-El-Malek <jam@chromium.org>
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Reviewed-by: Sadrul Chowdhury <sadrul@chromium.org>
Reviewed-by: Yuzhu Shen <yzshen@chromium.org>
Reviewed-by: Robert Sesek <rsesek@chromium.org>
Commit-Queue: Ken Rockot <rockot@chromium.org>
Cr-Commit-Position: refs/heads/master@{#530268}
CWE ID: CWE-787 | 0 | 149,251 |
Analyze the following 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 sr_disk_status(struct cdrom_device_info *cdi)
{
Scsi_CD *cd = cdi->handle;
struct cdrom_tochdr toc_h;
struct cdrom_tocentry toc_e;
int i, rc, have_datatracks = 0;
/* look for data tracks */
rc = sr_read_tochdr(cdi, &toc_h);
if (rc)
return (rc == -ENOMEDIUM) ? CDS_NO_DISC : CDS_NO_INFO;
for (i = toc_h.cdth_trk0; i <= toc_h.cdth_trk1; i++) {
toc_e.cdte_track = i;
toc_e.cdte_format = CDROM_LBA;
if (sr_read_tocentry(cdi, &toc_e))
return CDS_NO_INFO;
if (toc_e.cdte_ctrl & CDROM_DATA_TRACK) {
have_datatracks = 1;
break;
}
}
if (!have_datatracks)
return CDS_AUDIO;
if (cd->xa_flag)
return CDS_XA_2_1;
else
return CDS_DATA_1;
}
Commit Message: sr: pass down correctly sized SCSI sense buffer
We're casting the CDROM layer request_sense to the SCSI sense
buffer, but the former is 64 bytes and the latter is 96 bytes.
As we generally allocate these on the stack, we end up blowing
up the stack.
Fix this by wrapping the scsi_execute() call with a properly
sized sense buffer, and copying back the bits for the CDROM
layer.
Cc: stable@vger.kernel.org
Reported-by: Piotr Gabriel Kosinski <pg.kosinski@gmail.com>
Reported-by: Daniel Shapira <daniel@twistlock.com>
Tested-by: Kees Cook <keescook@chromium.org>
Fixes: 82ed4db499b8 ("block: split scsi_request out of struct request")
Signed-off-by: Jens Axboe <axboe@kernel.dk>
CWE ID: CWE-119 | 0 | 82,655 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static int rsa_md_to_algor(X509_ALGOR **palg, const EVP_MD *md)
{
if (EVP_MD_type(md) == NID_sha1)
return 1;
*palg = X509_ALGOR_new();
if (!*palg)
return 0;
X509_ALGOR_set_md(*palg, md);
return 1;
}
Commit Message:
CWE ID: | 0 | 3,633 |
Analyze the following 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 hci_send_to_sock(struct hci_dev *hdev, struct sk_buff *skb)
{
struct sock *sk;
struct sk_buff *skb_copy = NULL;
BT_DBG("hdev %p len %d", hdev, skb->len);
read_lock(&hci_sk_list.lock);
sk_for_each(sk, &hci_sk_list.head) {
struct sk_buff *nskb;
if (sk->sk_state != BT_BOUND || hci_pi(sk)->hdev != hdev)
continue;
/* Don't send frame to the socket it came from */
if (skb->sk == sk)
continue;
if (hci_pi(sk)->channel == HCI_CHANNEL_RAW) {
if (is_filtered_packet(sk, skb))
continue;
} else if (hci_pi(sk)->channel == HCI_CHANNEL_USER) {
if (!bt_cb(skb)->incoming)
continue;
if (bt_cb(skb)->pkt_type != HCI_EVENT_PKT &&
bt_cb(skb)->pkt_type != HCI_ACLDATA_PKT &&
bt_cb(skb)->pkt_type != HCI_SCODATA_PKT)
continue;
} else {
/* Don't send frame to other channel types */
continue;
}
if (!skb_copy) {
/* Create a private copy with headroom */
skb_copy = __pskb_copy(skb, 1, GFP_ATOMIC);
if (!skb_copy)
continue;
/* Put type byte before the data */
memcpy(skb_push(skb_copy, 1), &bt_cb(skb)->pkt_type, 1);
}
nskb = skb_clone(skb_copy, GFP_ATOMIC);
if (!nskb)
continue;
if (sock_queue_rcv_skb(sk, nskb))
kfree_skb(nskb);
}
read_unlock(&hci_sk_list.lock);
kfree_skb(skb_copy);
}
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,354 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static long jas_iccpowi(int x, int n)
{
long y;
y = 1;
while (--n >= 0)
y *= x;
return y;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | 0 | 72,712 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void FileSystemManagerImpl::DidGetPlatformPath(GetPlatformPathCallback callback,
base::FilePath platform_path) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
std::move(callback).Run(platform_path);
}
Commit Message: Disable FileSystemManager::CreateWriter if WritableFiles isn't enabled.
Bug: 922677
Change-Id: Ib16137cbabb2ec07f1ffc0484722f1d9cc533404
Reviewed-on: https://chromium-review.googlesource.com/c/1416570
Commit-Queue: Marijn Kruisselbrink <mek@chromium.org>
Reviewed-by: Victor Costan <pwnall@chromium.org>
Cr-Commit-Position: refs/heads/master@{#623552}
CWE ID: CWE-189 | 0 | 153,033 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void comps_objmrtree_unite(COMPS_ObjMRTree *rt1, COMPS_ObjMRTree *rt2) {
COMPS_HSList *tmplist, *tmp_subnodes;
COMPS_HSListItem *it;
COMPS_ObjListIt *it2;
struct Pair {
COMPS_HSList * subnodes;
char * key;
char added;
} *pair, *parent_pair;
pair = malloc(sizeof(struct Pair));
pair->subnodes = rt2->subnodes;
pair->key = NULL;
tmplist = comps_hslist_create();
comps_hslist_init(tmplist, NULL, NULL, &free);
comps_hslist_append(tmplist, pair, 0);
while (tmplist->first != NULL) {
it = tmplist->first;
comps_hslist_remove(tmplist, tmplist->first);
tmp_subnodes = ((struct Pair*)it->data)->subnodes;
parent_pair = (struct Pair*) it->data;
free(it);
pair->added = 0;
for (it = tmp_subnodes->first; it != NULL; it=it->next) {
pair = malloc(sizeof(struct Pair));
pair->subnodes = ((COMPS_ObjMRTreeData*)it->data)->subnodes;
if (parent_pair->key != NULL) {
pair->key =
malloc(sizeof(char)
* (strlen(((COMPS_ObjMRTreeData*)it->data)->key)
+ strlen(parent_pair->key) + 1));
memcpy(pair->key, parent_pair->key,
sizeof(char) * strlen(parent_pair->key));
memcpy(pair->key+strlen(parent_pair->key),
((COMPS_ObjMRTreeData*)it->data)->key,
sizeof(char)*(strlen(((COMPS_ObjMRTreeData*)it->data)->key)+1));
} else {
pair->key = malloc(sizeof(char)*
(strlen(((COMPS_ObjMRTreeData*)it->data)->key) +
1));
memcpy(pair->key, ((COMPS_ObjMRTreeData*)it->data)->key,
sizeof(char)*(strlen(((COMPS_ObjMRTreeData*)it->data)->key)+1));
}
/* current node has data */
if (((COMPS_ObjMRTreeData*)it->data)->data->first != NULL) {
for (it2 = ((COMPS_ObjMRTreeData*)it->data)->data->first;
it2 != NULL; it2 = it2->next) {
comps_objmrtree_set(rt1, pair->key, it2->comps_obj);
}
if (((COMPS_ObjMRTreeData*)it->data)->subnodes->first) {
comps_hslist_append(tmplist, pair, 0);
} else {
free(pair->key);
free(pair);
}
/* current node hasn't data */
} else {
if (((COMPS_ObjMRTreeData*)it->data)->subnodes->first) {
comps_hslist_append(tmplist, pair, 0);
} else {
free(pair->key);
free(pair);
}
}
}
free(parent_pair->key);
free(parent_pair);
}
comps_hslist_destroy(&tmplist);
}
Commit Message: Fix UAF in comps_objmrtree_unite function
The added field is not used at all in many places and it is probably the
left-over of some copy-paste.
CWE ID: CWE-416 | 1 | 169,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: static void cache_flusharray(struct kmem_cache *cachep, struct array_cache *ac)
{
int batchcount;
struct kmem_cache_node *n;
int node = numa_mem_id();
LIST_HEAD(list);
batchcount = ac->batchcount;
check_irq_off();
n = get_node(cachep, node);
spin_lock(&n->list_lock);
if (n->shared) {
struct array_cache *shared_array = n->shared;
int max = shared_array->limit - shared_array->avail;
if (max) {
if (batchcount > max)
batchcount = max;
memcpy(&(shared_array->entry[shared_array->avail]),
ac->entry, sizeof(void *) * batchcount);
shared_array->avail += batchcount;
goto free_done;
}
}
free_block(cachep, ac->entry, batchcount, node, &list);
free_done:
#if STATS
{
int i = 0;
struct page *page;
list_for_each_entry(page, &n->slabs_free, lru) {
BUG_ON(page->active);
i++;
}
STATS_SET_FREEABLE(cachep, i);
}
#endif
spin_unlock(&n->list_lock);
slabs_destroy(cachep, &list);
ac->avail -= batchcount;
memmove(ac->entry, &(ac->entry[batchcount]), sizeof(void *)*ac->avail);
}
Commit Message: mm/slab.c: fix SLAB freelist randomization duplicate entries
This patch fixes a bug in the freelist randomization code. When a high
random number is used, the freelist will contain duplicate entries. It
will result in different allocations sharing the same chunk.
It will result in odd behaviours and crashes. It should be uncommon but
it depends on the machines. We saw it happening more often on some
machines (every few hours of running tests).
Fixes: c7ce4f60ac19 ("mm: SLAB freelist randomization")
Link: http://lkml.kernel.org/r/20170103181908.143178-1-thgarnie@google.com
Signed-off-by: John Sperbeck <jsperbeck@google.com>
Signed-off-by: Thomas Garnier <thgarnie@google.com>
Cc: Christoph Lameter <cl@linux.com>
Cc: Pekka Enberg <penberg@kernel.org>
Cc: David Rientjes <rientjes@google.com>
Cc: Joonsoo Kim <iamjoonsoo.kim@lge.com>
Cc: <stable@vger.kernel.org>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID: | 0 | 68,842 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static MagickBooleanType WriteCINImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
timestamp[MagickPathExtent];
const char
*value;
CINInfo
cin;
const StringInfo
*profile;
MagickBooleanType
status;
MagickOffsetType
offset;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register const Quantum
*p;
register ssize_t
i;
size_t
length;
ssize_t
count,
y;
struct tm
local_time;
time_t
seconds;
unsigned char
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
if (image->colorspace != LogColorspace)
(void) TransformImageColorspace(image,LogColorspace,exception);
/*
Write image information.
*/
(void) memset(&cin,0,sizeof(cin));
offset=0;
cin.file.magic=0x802A5FD7UL;
offset+=WriteBlobLong(image,(unsigned int) cin.file.magic);
cin.file.image_offset=0x800;
offset+=WriteBlobLong(image,(unsigned int) cin.file.image_offset);
cin.file.generic_length=0x400;
offset+=WriteBlobLong(image,(unsigned int) cin.file.generic_length);
cin.file.industry_length=0x400;
offset+=WriteBlobLong(image,(unsigned int) cin.file.industry_length);
cin.file.user_length=0x00;
profile=GetImageProfile(image,"dpx:user.data");
if (profile != (StringInfo *) NULL)
{
cin.file.user_length+=(size_t) GetStringInfoLength(profile);
cin.file.user_length=(((cin.file.user_length+0x2000-1)/0x2000)*0x2000);
}
offset+=WriteBlobLong(image,(unsigned int) cin.file.user_length);
cin.file.file_size=4*image->columns*image->rows+0x2000;
offset+=WriteBlobLong(image,(unsigned int) cin.file.file_size);
(void) CopyMagickString(cin.file.version,"V4.5",sizeof(cin.file.version));
offset+=WriteBlob(image,sizeof(cin.file.version),(unsigned char *)
cin.file.version);
value=GetCINProperty(image_info,image,"dpx:file.filename",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(cin.file.filename,value,sizeof(cin.file.filename));
else
(void) CopyMagickString(cin.file.filename,image->filename,
sizeof(cin.file.filename));
offset+=WriteBlob(image,sizeof(cin.file.filename),(unsigned char *)
cin.file.filename);
seconds=time((time_t *) NULL);
#if defined(MAGICKCORE_HAVE_LOCALTIME_R)
(void) localtime_r(&seconds,&local_time);
#else
(void) memcpy(&local_time,localtime(&seconds),sizeof(local_time));
#endif
(void) memset(timestamp,0,sizeof(timestamp));
(void) strftime(timestamp,MagickPathExtent,"%Y:%m:%d:%H:%M:%S%Z",&local_time);
(void) memset(cin.file.create_date,0,sizeof(cin.file.create_date));
(void) CopyMagickString(cin.file.create_date,timestamp,11);
offset+=WriteBlob(image,sizeof(cin.file.create_date),(unsigned char *)
cin.file.create_date);
(void) memset(cin.file.create_time,0,sizeof(cin.file.create_time));
(void) CopyMagickString(cin.file.create_time,timestamp+11,11);
offset+=WriteBlob(image,sizeof(cin.file.create_time),(unsigned char *)
cin.file.create_time);
offset+=WriteBlob(image,sizeof(cin.file.reserve),(unsigned char *)
cin.file.reserve);
cin.image.orientation=0x00;
offset+=WriteBlobByte(image,cin.image.orientation);
cin.image.number_channels=3;
offset+=WriteBlobByte(image,cin.image.number_channels);
offset+=WriteBlob(image,sizeof(cin.image.reserve1),(unsigned char *)
cin.image.reserve1);
for (i=0; i < 8; i++)
{
cin.image.channel[i].designator[0]=0; /* universal metric */
offset+=WriteBlobByte(image,cin.image.channel[0].designator[0]);
cin.image.channel[i].designator[1]=(unsigned char) (i > 3 ? 0 : i+1); /* channel color */;
offset+=WriteBlobByte(image,cin.image.channel[1].designator[0]);
cin.image.channel[i].bits_per_pixel=(unsigned char) image->depth;
offset+=WriteBlobByte(image,cin.image.channel[0].bits_per_pixel);
offset+=WriteBlobByte(image,cin.image.channel[0].reserve);
cin.image.channel[i].pixels_per_line=image->columns;
offset+=WriteBlobLong(image,(unsigned int)
cin.image.channel[0].pixels_per_line);
cin.image.channel[i].lines_per_image=image->rows;
offset+=WriteBlobLong(image,(unsigned int)
cin.image.channel[0].lines_per_image);
cin.image.channel[i].min_data=0;
offset+=WriteBlobFloat(image,cin.image.channel[0].min_data);
cin.image.channel[i].min_quantity=0.0;
offset+=WriteBlobFloat(image,cin.image.channel[0].min_quantity);
cin.image.channel[i].max_data=(float) ((MagickOffsetType)
GetQuantumRange(image->depth));
offset+=WriteBlobFloat(image,cin.image.channel[0].max_data);
cin.image.channel[i].max_quantity=2.048f;
offset+=WriteBlobFloat(image,cin.image.channel[0].max_quantity);
}
offset+=WriteBlobFloat(image,image->chromaticity.white_point.x);
offset+=WriteBlobFloat(image,image->chromaticity.white_point.y);
offset+=WriteBlobFloat(image,image->chromaticity.red_primary.x);
offset+=WriteBlobFloat(image,image->chromaticity.red_primary.y);
offset+=WriteBlobFloat(image,image->chromaticity.green_primary.x);
offset+=WriteBlobFloat(image,image->chromaticity.green_primary.y);
offset+=WriteBlobFloat(image,image->chromaticity.blue_primary.x);
offset+=WriteBlobFloat(image,image->chromaticity.blue_primary.y);
value=GetCINProperty(image_info,image,"dpx:image.label",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(cin.image.label,value,sizeof(cin.image.label));
offset+=WriteBlob(image,sizeof(cin.image.label),(unsigned char *)
cin.image.label);
offset+=WriteBlob(image,sizeof(cin.image.reserve),(unsigned char *)
cin.image.reserve);
/*
Write data format information.
*/
cin.data_format.interleave=0; /* pixel interleave (rgbrgbr...) */
offset+=WriteBlobByte(image,cin.data_format.interleave);
cin.data_format.packing=5; /* packing ssize_tword (32bit) boundaries */
offset+=WriteBlobByte(image,cin.data_format.packing);
cin.data_format.sign=0; /* unsigned data */
offset+=WriteBlobByte(image,cin.data_format.sign);
cin.data_format.sense=0; /* image sense: positive image */
offset+=WriteBlobByte(image,cin.data_format.sense);
cin.data_format.line_pad=0;
offset+=WriteBlobLong(image,(unsigned int) cin.data_format.line_pad);
cin.data_format.channel_pad=0;
offset+=WriteBlobLong(image,(unsigned int) cin.data_format.channel_pad);
offset+=WriteBlob(image,sizeof(cin.data_format.reserve),(unsigned char *)
cin.data_format.reserve);
/*
Write origination information.
*/
cin.origination.x_offset=0UL;
value=GetCINProperty(image_info,image,"dpx:origination.x_offset",exception);
if (value != (const char *) NULL)
cin.origination.x_offset=(ssize_t) StringToLong(value);
offset+=WriteBlobLong(image,(unsigned int) cin.origination.x_offset);
cin.origination.y_offset=0UL;
value=GetCINProperty(image_info,image,"dpx:origination.y_offset",exception);
if (value != (const char *) NULL)
cin.origination.y_offset=(ssize_t) StringToLong(value);
offset+=WriteBlobLong(image,(unsigned int) cin.origination.y_offset);
value=GetCINProperty(image_info,image,"dpx:origination.filename",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(cin.origination.filename,value,
sizeof(cin.origination.filename));
else
(void) CopyMagickString(cin.origination.filename,image->filename,
sizeof(cin.origination.filename));
offset+=WriteBlob(image,sizeof(cin.origination.filename),(unsigned char *)
cin.origination.filename);
seconds=time((time_t *) NULL);
(void) memset(timestamp,0,sizeof(timestamp));
(void) strftime(timestamp,MagickPathExtent,"%Y:%m:%d:%H:%M:%S%Z",&local_time);
(void) memset(cin.origination.create_date,0,
sizeof(cin.origination.create_date));
(void) CopyMagickString(cin.origination.create_date,timestamp,11);
offset+=WriteBlob(image,sizeof(cin.origination.create_date),(unsigned char *)
cin.origination.create_date);
(void) memset(cin.origination.create_time,0,
sizeof(cin.origination.create_time));
(void) CopyMagickString(cin.origination.create_time,timestamp+11,15);
offset+=WriteBlob(image,sizeof(cin.origination.create_time),(unsigned char *)
cin.origination.create_time);
value=GetCINProperty(image_info,image,"dpx:origination.device",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(cin.origination.device,value,
sizeof(cin.origination.device));
offset+=WriteBlob(image,sizeof(cin.origination.device),(unsigned char *)
cin.origination.device);
value=GetCINProperty(image_info,image,"dpx:origination.model",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(cin.origination.model,value,
sizeof(cin.origination.model));
offset+=WriteBlob(image,sizeof(cin.origination.model),(unsigned char *)
cin.origination.model);
value=GetCINProperty(image_info,image,"dpx:origination.serial",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(cin.origination.serial,value,
sizeof(cin.origination.serial));
offset+=WriteBlob(image,sizeof(cin.origination.serial),(unsigned char *)
cin.origination.serial);
cin.origination.x_pitch=0.0f;
value=GetCINProperty(image_info,image,"dpx:origination.x_pitch",exception);
if (value != (const char *) NULL)
cin.origination.x_pitch=StringToDouble(value,(char **) NULL);
offset+=WriteBlobFloat(image,cin.origination.x_pitch);
cin.origination.y_pitch=0.0f;
value=GetCINProperty(image_info,image,"dpx:origination.y_pitch",exception);
if (value != (const char *) NULL)
cin.origination.y_pitch=StringToDouble(value,(char **) NULL);
offset+=WriteBlobFloat(image,cin.origination.y_pitch);
cin.origination.gamma=image->gamma;
offset+=WriteBlobFloat(image,cin.origination.gamma);
offset+=WriteBlob(image,sizeof(cin.origination.reserve),(unsigned char *)
cin.origination.reserve);
/*
Image film information.
*/
cin.film.id=0;
value=GetCINProperty(image_info,image,"dpx:film.id",exception);
if (value != (const char *) NULL)
cin.film.id=(char) StringToLong(value);
offset+=WriteBlobByte(image,(unsigned char) cin.film.id);
cin.film.type=0;
value=GetCINProperty(image_info,image,"dpx:film.type",exception);
if (value != (const char *) NULL)
cin.film.type=(char) StringToLong(value);
offset+=WriteBlobByte(image,(unsigned char) cin.film.type);
cin.film.offset=0;
value=GetCINProperty(image_info,image,"dpx:film.offset",exception);
if (value != (const char *) NULL)
cin.film.offset=(char) StringToLong(value);
offset+=WriteBlobByte(image,(unsigned char) cin.film.offset);
offset+=WriteBlobByte(image,(unsigned char) cin.film.reserve1);
cin.film.prefix=0UL;
value=GetCINProperty(image_info,image,"dpx:film.prefix",exception);
if (value != (const char *) NULL)
cin.film.prefix=StringToUnsignedLong(value);
offset+=WriteBlobLong(image,(unsigned int) cin.film.prefix);
cin.film.count=0UL;
value=GetCINProperty(image_info,image,"dpx:film.count",exception);
if (value != (const char *) NULL)
cin.film.count=StringToUnsignedLong(value);
offset+=WriteBlobLong(image,(unsigned int) cin.film.count);
value=GetCINProperty(image_info,image,"dpx:film.format",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(cin.film.format,value,sizeof(cin.film.format));
offset+=WriteBlob(image,sizeof(cin.film.format),(unsigned char *)
cin.film.format);
cin.film.frame_position=0UL;
value=GetCINProperty(image_info,image,"dpx:film.frame_position",exception);
if (value != (const char *) NULL)
cin.film.frame_position=StringToUnsignedLong(value);
offset+=WriteBlobLong(image,(unsigned int) cin.film.frame_position);
cin.film.frame_rate=0.0f;
value=GetCINProperty(image_info,image,"dpx:film.frame_rate",exception);
if (value != (const char *) NULL)
cin.film.frame_rate=StringToDouble(value,(char **) NULL);
offset+=WriteBlobFloat(image,cin.film.frame_rate);
value=GetCINProperty(image_info,image,"dpx:film.frame_id",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(cin.film.frame_id,value,sizeof(cin.film.frame_id));
offset+=WriteBlob(image,sizeof(cin.film.frame_id),(unsigned char *)
cin.film.frame_id);
value=GetCINProperty(image_info,image,"dpx:film.slate_info",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(cin.film.slate_info,value,
sizeof(cin.film.slate_info));
offset+=WriteBlob(image,sizeof(cin.film.slate_info),(unsigned char *)
cin.film.slate_info);
offset+=WriteBlob(image,sizeof(cin.film.reserve),(unsigned char *)
cin.film.reserve);
if (profile != (StringInfo *) NULL)
offset+=WriteBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
while (offset < (MagickOffsetType) cin.file.image_offset)
offset+=WriteBlobByte(image,0x00);
/*
Convert pixel packets to CIN raster image.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
quantum_info->quantum=32;
quantum_info->pack=MagickFalse;
quantum_type=RGBQuantum;
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue);
DisableMSCWarning(4127)
if (0)
RestoreMSCWarning
{
quantum_type=GrayQuantum;
length=GetBytesPerRow(image->columns,1,image->depth,MagickTrue);
}
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
(void) ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
(void) CloseBlob(image);
return(status);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1472
CWE ID: CWE-400 | 0 | 90,623 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: xsltParseAttrXSLTVersion(xsltCompilerCtxtPtr cctxt, xmlNodePtr node,
int instrCategory)
{
xmlChar *value;
xmlAttrPtr attr;
if ((cctxt == NULL) || (node == NULL))
return(-1);
if (instrCategory == XSLT_ELEMENT_CATEGORY_XSLT)
attr = xmlHasNsProp(node, BAD_CAST "version", NULL);
else
attr = xmlHasNsProp(node, BAD_CAST "version", XSLT_NAMESPACE);
if (attr == NULL)
return(0);
attr->psvi = (void *) xsltXSLTAttrMarker;
if ((attr->children != NULL) &&
(attr->children->content != NULL))
value = attr->children->content;
else {
xsltTransformError(NULL, cctxt->style, node,
"Attribute 'version': Invalid value.\n");
cctxt->style->errors++;
return(1);
}
if (! xmlStrEqual(value, (const xmlChar *)"1.0")) {
cctxt->inode->forwardsCompat = 1;
/*
* TODO: To what extent do we support the
* forwards-compatible mode?
*/
/*
* Report this only once per compilation episode.
*/
if (! cctxt->hasForwardsCompat) {
cctxt->hasForwardsCompat = 1;
cctxt->errSeverity = XSLT_ERROR_SEVERITY_WARNING;
xsltTransformError(NULL, cctxt->style, node,
"Warning: the attribute xsl:version specifies a value "
"different from '1.0'. Switching to forwards-compatible "
"mode. Only features of XSLT 1.0 are supported by this "
"processor.\n");
cctxt->style->warnings++;
cctxt->errSeverity = XSLT_ERROR_SEVERITY_ERROR;
}
} else {
cctxt->inode->forwardsCompat = 0;
}
if (attr && (instrCategory == XSLT_ELEMENT_CATEGORY_LRE)) {
/*
* Set a marker on XSLT attributes.
*/
attr->psvi = (void *) xsltXSLTAttrMarker;
}
return(1);
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119 | 0 | 156,916 |
Analyze the following 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 snd_timer_tasklet(unsigned long arg)
{
struct snd_timer *timer = (struct snd_timer *) arg;
struct snd_timer_instance *ti;
struct list_head *p;
unsigned long resolution, ticks;
unsigned long flags;
spin_lock_irqsave(&timer->lock, flags);
/* now process all callbacks */
while (!list_empty(&timer->sack_list_head)) {
p = timer->sack_list_head.next; /* get first item */
ti = list_entry(p, struct snd_timer_instance, ack_list);
/* remove from ack_list and make empty */
list_del_init(p);
ticks = ti->pticks;
ti->pticks = 0;
resolution = ti->resolution;
ti->flags |= SNDRV_TIMER_IFLG_CALLBACK;
spin_unlock(&timer->lock);
if (ti->callback)
ti->callback(ti, resolution, ticks);
spin_lock(&timer->lock);
ti->flags &= ~SNDRV_TIMER_IFLG_CALLBACK;
}
spin_unlock_irqrestore(&timer->lock, flags);
}
Commit Message: ALSA: timer: Harden slave timer list handling
A slave timer instance might be still accessible in a racy way while
operating the master instance as it lacks of locking. Since the
master operation is mostly protected with timer->lock, we should cope
with it while changing the slave instance, too. Also, some linked
lists (active_list and ack_list) of slave instances aren't unlinked
immediately at stopping or closing, and this may lead to unexpected
accesses.
This patch tries to address these issues. It adds spin lock of
timer->lock (either from master or slave, which is equivalent) in a
few places. For avoiding a deadlock, we ensure that the global
slave_active_lock is always locked at first before each timer lock.
Also, ack and active_list of slave instances are properly unlinked at
snd_timer_stop() and snd_timer_close().
Last but not least, remove the superfluous call of _snd_timer_stop()
at removing slave links. This is a noop, and calling it may confuse
readers wrt locking. Further cleanup will follow in a later patch.
Actually we've got reports of use-after-free by syzkaller fuzzer, and
this hopefully fixes these issues.
Reported-by: Dmitry Vyukov <dvyukov@google.com>
Cc: <stable@vger.kernel.org>
Signed-off-by: Takashi Iwai <tiwai@suse.de>
CWE ID: CWE-20 | 0 | 54,621 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static int exofs_file_fsync(struct file *filp, loff_t start, loff_t end,
int datasync)
{
struct inode *inode = filp->f_mapping->host;
int ret;
ret = filemap_write_and_wait_range(inode->i_mapping, start, end);
if (ret)
return ret;
mutex_lock(&inode->i_mutex);
ret = sync_inode_metadata(filp->f_mapping->host, 1);
mutex_unlock(&inode->i_mutex);
return ret;
}
Commit Message: ->splice_write() via ->write_iter()
iter_file_splice_write() - a ->splice_write() instance that gathers the
pipe buffers, builds a bio_vec-based iov_iter covering those and feeds
it to ->write_iter(). A bunch of simple cases coverted to that...
[AV: fixed the braino spotted by Cyrill]
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>
CWE ID: CWE-264 | 0 | 46,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: void LoginPromptBrowserTest::SetAuthFor(LoginHandler* handler) {
const net::AuthChallengeInfo* challenge = handler->auth_info();
ASSERT_TRUE(challenge);
AuthMap::iterator i = auth_map_.find(challenge->realm);
EXPECT_TRUE(auth_map_.end() != i);
if (i != auth_map_.end()) {
const AuthInfo& info = i->second;
handler->SetAuth(UTF8ToUTF16(info.username_),
UTF8ToUTF16(info.password_));
}
}
Commit Message: Revert cross-origin auth prompt blocking.
BUG=174129
Review URL: https://chromiumcodereview.appspot.com/12183030
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@181113 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | 0 | 115,879 |
Analyze the following 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 rfcomm_connect_ind(struct rfcomm_session *s, u8 channel, struct rfcomm_dlc **d)
{
struct sock *sk, *parent;
bdaddr_t src, dst;
int result = 0;
BT_DBG("session %p channel %d", s, channel);
rfcomm_session_getaddr(s, &src, &dst);
/* Check if we have socket listening on channel */
parent = rfcomm_get_sock_by_channel(BT_LISTEN, channel, &src);
if (!parent)
return 0;
bh_lock_sock(parent);
/* Check for backlog size */
if (sk_acceptq_is_full(parent)) {
BT_DBG("backlog full %d", parent->sk_ack_backlog);
goto done;
}
sk = rfcomm_sock_alloc(sock_net(parent), NULL, BTPROTO_RFCOMM, GFP_ATOMIC, 0);
if (!sk)
goto done;
bt_sock_reclassify_lock(sk, BTPROTO_RFCOMM);
rfcomm_sock_init(sk, parent);
bacpy(&rfcomm_pi(sk)->src, &src);
bacpy(&rfcomm_pi(sk)->dst, &dst);
rfcomm_pi(sk)->channel = channel;
sk->sk_state = BT_CONFIG;
bt_accept_enqueue(parent, sk);
/* Accept connection and return socket DLC */
*d = rfcomm_pi(sk)->dlc;
result = 1;
done:
bh_unlock_sock(parent);
if (test_bit(BT_SK_DEFER_SETUP, &bt_sk(parent)->flags))
parent->sk_state_change(parent);
return result;
}
Commit Message: Bluetooth: Fix potential NULL dereference in RFCOMM bind callback
addr can be NULL and it should not be dereferenced before NULL checking.
Signed-off-by: Jaganath Kanakkassery <jaganath.k@samsung.com>
Signed-off-by: Marcel Holtmann <marcel@holtmann.org>
CWE ID: CWE-476 | 0 | 56,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 void flakey_map_bio(struct dm_target *ti, struct bio *bio)
{
struct flakey_c *fc = ti->private;
bio->bi_bdev = fc->dev->bdev;
if (bio_sectors(bio))
bio->bi_sector = flakey_map_sector(ti, bio->bi_sector);
}
Commit Message: dm: do not forward ioctls from logical volumes to the underlying device
A logical volume can map to just part of underlying physical volume.
In this case, it must be treated like a partition.
Based on a patch from Alasdair G Kergon.
Cc: Alasdair G Kergon <agk@redhat.com>
Cc: dm-devel@redhat.com
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID: CWE-264 | 0 | 23,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: cf2_getBlueMetrics( CFF_Decoder* decoder,
CF2_Fixed* blueScale,
CF2_Fixed* blueShift,
CF2_Fixed* blueFuzz )
{
FT_ASSERT( decoder && decoder->current_subfont );
*blueScale = FT_DivFix(
decoder->current_subfont->private_dict.blue_scale,
cf2_intToFixed( 1000 ) );
*blueShift = cf2_intToFixed(
decoder->current_subfont->private_dict.blue_shift );
*blueFuzz = cf2_intToFixed(
decoder->current_subfont->private_dict.blue_fuzz );
}
Commit Message:
CWE ID: CWE-20 | 0 | 13,081 |
Analyze the following 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 WebBluetoothServiceImpl::RemoteDescriptorWriteValue(
const std::string& descriptor_instance_id,
const std::vector<uint8_t>& value,
RemoteDescriptorWriteValueCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (value.size() > 512) {
CrashRendererAndClosePipe(bad_message::BDH_INVALID_WRITE_VALUE_LENGTH);
return;
}
const CacheQueryResult query_result =
QueryCacheForDescriptor(descriptor_instance_id);
if (query_result.outcome == CacheQueryOutcome::BAD_RENDERER) {
return;
}
if (query_result.outcome != CacheQueryOutcome::SUCCESS) {
RecordDescriptorWriteValueOutcome(query_result.outcome);
std::move(callback).Run(query_result.GetWebResult());
return;
}
if (BluetoothBlocklist::Get().IsExcludedFromWrites(
query_result.descriptor->GetUUID())) {
RecordDescriptorWriteValueOutcome(UMAGATTOperationOutcome::BLOCKLISTED);
std::move(callback).Run(
blink::mojom::WebBluetoothResult::BLOCKLISTED_WRITE);
return;
}
auto copyable_callback = base::AdaptCallbackForRepeating(std::move(callback));
query_result.descriptor->WriteRemoteDescriptor(
value,
base::Bind(&WebBluetoothServiceImpl::OnDescriptorWriteValueSuccess,
weak_ptr_factory_.GetWeakPtr(), copyable_callback),
base::Bind(&WebBluetoothServiceImpl::OnDescriptorWriteValueFailed,
weak_ptr_factory_.GetWeakPtr(), copyable_callback));
}
Commit Message: bluetooth: Implement getAvailability()
This change implements the getAvailability() method for
navigator.bluetooth as defined in the specification.
Bug: 707640
Change-Id: I9e9b3e7f8ea7f259e975f71cb6d9570e5f04b479
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1651516
Reviewed-by: Chris Harrelson <chrishtr@chromium.org>
Reviewed-by: Giovanni Ortuño Urquidi <ortuno@chromium.org>
Reviewed-by: Kinuko Yasuda <kinuko@chromium.org>
Commit-Queue: Ovidio de Jesús Ruiz-Henríquez <odejesush@chromium.org>
Auto-Submit: Ovidio de Jesús Ruiz-Henríquez <odejesush@chromium.org>
Cr-Commit-Position: refs/heads/master@{#688987}
CWE ID: CWE-119 | 0 | 138,142 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: long __get_user_pages(struct task_struct *tsk, struct mm_struct *mm,
unsigned long start, unsigned long nr_pages,
unsigned int gup_flags, struct page **pages,
struct vm_area_struct **vmas, int *nonblocking)
{
long i;
unsigned long vm_flags;
unsigned int page_mask;
if (!nr_pages)
return 0;
VM_BUG_ON(!!pages != !!(gup_flags & FOLL_GET));
/*
* Require read or write permissions.
* If FOLL_FORCE is set, we only require the "MAY" flags.
*/
vm_flags = (gup_flags & FOLL_WRITE) ?
(VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD);
vm_flags &= (gup_flags & FOLL_FORCE) ?
(VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE);
/*
* If FOLL_FORCE and FOLL_NUMA are both set, handle_mm_fault
* would be called on PROT_NONE ranges. We must never invoke
* handle_mm_fault on PROT_NONE ranges or the NUMA hinting
* page faults would unprotect the PROT_NONE ranges if
* _PAGE_NUMA and _PAGE_PROTNONE are sharing the same pte/pmd
* bitflag. So to avoid that, don't set FOLL_NUMA if
* FOLL_FORCE is set.
*/
if (!(gup_flags & FOLL_FORCE))
gup_flags |= FOLL_NUMA;
i = 0;
do {
struct vm_area_struct *vma;
vma = find_extend_vma(mm, start);
if (!vma && in_gate_area(mm, start)) {
unsigned long pg = start & PAGE_MASK;
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd;
pte_t *pte;
/* user gate pages are read-only */
if (gup_flags & FOLL_WRITE)
return i ? : -EFAULT;
if (pg > TASK_SIZE)
pgd = pgd_offset_k(pg);
else
pgd = pgd_offset_gate(mm, pg);
BUG_ON(pgd_none(*pgd));
pud = pud_offset(pgd, pg);
BUG_ON(pud_none(*pud));
pmd = pmd_offset(pud, pg);
if (pmd_none(*pmd))
return i ? : -EFAULT;
VM_BUG_ON(pmd_trans_huge(*pmd));
pte = pte_offset_map(pmd, pg);
if (pte_none(*pte)) {
pte_unmap(pte);
return i ? : -EFAULT;
}
vma = get_gate_vma(mm);
if (pages) {
struct page *page;
page = vm_normal_page(vma, start, *pte);
if (!page) {
if (!(gup_flags & FOLL_DUMP) &&
is_zero_pfn(pte_pfn(*pte)))
page = pte_page(*pte);
else {
pte_unmap(pte);
return i ? : -EFAULT;
}
}
pages[i] = page;
get_page(page);
}
pte_unmap(pte);
page_mask = 0;
goto next_page;
}
if (!vma ||
(vma->vm_flags & (VM_IO | VM_PFNMAP)) ||
!(vm_flags & vma->vm_flags))
return i ? : -EFAULT;
if (is_vm_hugetlb_page(vma)) {
i = follow_hugetlb_page(mm, vma, pages, vmas,
&start, &nr_pages, i, gup_flags);
continue;
}
do {
struct page *page;
unsigned int foll_flags = gup_flags;
unsigned int page_increm;
/*
* If we have a pending SIGKILL, don't keep faulting
* pages and potentially allocating memory.
*/
if (unlikely(fatal_signal_pending(current)))
return i ? i : -ERESTARTSYS;
cond_resched();
while (!(page = follow_page_mask(vma, start,
foll_flags, &page_mask))) {
int ret;
unsigned int fault_flags = 0;
/* For mlock, just skip the stack guard page. */
if (foll_flags & FOLL_MLOCK) {
if (stack_guard_page(vma, start))
goto next_page;
}
if (foll_flags & FOLL_WRITE)
fault_flags |= FAULT_FLAG_WRITE;
if (nonblocking)
fault_flags |= FAULT_FLAG_ALLOW_RETRY;
if (foll_flags & FOLL_NOWAIT)
fault_flags |= (FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT);
ret = handle_mm_fault(mm, vma, start,
fault_flags);
if (ret & VM_FAULT_ERROR) {
if (ret & VM_FAULT_OOM)
return i ? i : -ENOMEM;
if (ret & (VM_FAULT_HWPOISON |
VM_FAULT_HWPOISON_LARGE)) {
if (i)
return i;
else if (gup_flags & FOLL_HWPOISON)
return -EHWPOISON;
else
return -EFAULT;
}
if (ret & VM_FAULT_SIGBUS)
return i ? i : -EFAULT;
BUG();
}
if (tsk) {
if (ret & VM_FAULT_MAJOR)
tsk->maj_flt++;
else
tsk->min_flt++;
}
if (ret & VM_FAULT_RETRY) {
if (nonblocking)
*nonblocking = 0;
return i;
}
/*
* The VM_FAULT_WRITE bit tells us that
* do_wp_page has broken COW when necessary,
* even if maybe_mkwrite decided not to set
* pte_write. We can thus safely do subsequent
* page lookups as if they were reads. But only
* do so when looping for pte_write is futile:
* in some cases userspace may also be wanting
* to write to the gotten user page, which a
* read fault here might prevent (a readonly
* page might get reCOWed by userspace write).
*/
if ((ret & VM_FAULT_WRITE) &&
!(vma->vm_flags & VM_WRITE))
foll_flags &= ~FOLL_WRITE;
cond_resched();
}
if (IS_ERR(page))
return i ? i : PTR_ERR(page);
if (pages) {
pages[i] = page;
flush_anon_page(vma, page, start);
flush_dcache_page(page);
page_mask = 0;
}
next_page:
if (vmas) {
vmas[i] = vma;
page_mask = 0;
}
page_increm = 1 + (~(start >> PAGE_SHIFT) & page_mask);
if (page_increm > nr_pages)
page_increm = nr_pages;
i += page_increm;
start += page_increm * PAGE_SIZE;
nr_pages -= page_increm;
} while (nr_pages && start < vma->vm_end);
} while (nr_pages);
return i;
}
Commit Message: vm: add vm_iomap_memory() helper function
Various drivers end up replicating the code to mmap() their memory
buffers into user space, and our core memory remapping function may be
very flexible but it is unnecessarily complicated for the common cases
to use.
Our internal VM uses pfn's ("page frame numbers") which simplifies
things for the VM, and allows us to pass physical addresses around in a
denser and more efficient format than passing a "phys_addr_t" around,
and having to shift it up and down by the page size. But it just means
that drivers end up doing that shifting instead at the interface level.
It also means that drivers end up mucking around with internal VM things
like the vma details (vm_pgoff, vm_start/end) way more than they really
need to.
So this just exports a function to map a certain physical memory range
into user space (using a phys_addr_t based interface that is much more
natural for a driver) and hides all the complexity from the driver.
Some drivers will still end up tweaking the vm_page_prot details for
things like prefetching or cacheability etc, but that's actually
relevant to the driver, rather than caring about what the page offset of
the mapping is into the particular IO memory region.
Acked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID: CWE-189 | 0 | 94,439 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void Document::DidChangeVisibilityState() {
DispatchEvent(Event::CreateBubble(EventTypeNames::visibilitychange));
DispatchEvent(Event::CreateBubble(EventTypeNames::webkitvisibilitychange));
if (GetPageVisibilityState() == kPageVisibilityStateVisible)
Timeline().SetAllCompositorPending();
if (hidden() && canvas_font_cache_)
canvas_font_cache_->PruneAll();
}
Commit Message: Inherit CSP when we inherit the security origin
This prevents attacks that use main window navigation to get out of the
existing csp constraints such as the related bug
Bug: 747847
Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8
Reviewed-on: https://chromium-review.googlesource.com/592027
Reviewed-by: Mike West <mkwst@chromium.org>
Commit-Queue: Andy Paicu <andypaicu@chromium.org>
Cr-Commit-Position: refs/heads/master@{#492333}
CWE ID: CWE-732 | 0 | 134,050 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: const AtomicString& HTMLSelectElement::formControlType() const
{
DEFINE_STATIC_LOCAL(const AtomicString, selectMultiple, ("select-multiple", AtomicString::ConstructFromLiteral));
DEFINE_STATIC_LOCAL(const AtomicString, selectOne, ("select-one", AtomicString::ConstructFromLiteral));
return m_multiple ? selectMultiple : selectOne;
}
Commit Message: SelectElement should remove an option when null is assigned by indexed setter
Fix bug embedded in r151449
see
http://src.chromium.org/viewvc/blink?revision=151449&view=revision
R=haraken@chromium.org, tkent@chromium.org, eseidel@chromium.org
BUG=262365
TEST=fast/forms/select/select-assign-null.html
Review URL: https://chromiumcodereview.appspot.com/19947008
git-svn-id: svn://svn.chromium.org/blink/trunk@154743 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-125 | 0 | 103,066 |
Analyze the following 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 nr_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct sockaddr_ax25 *sax = (struct sockaddr_ax25 *)msg->msg_name;
size_t copied;
struct sk_buff *skb;
int er;
/*
* This works for seqpacket too. The receiver has ordered the queue for
* us! We do one quick check first though
*/
lock_sock(sk);
if (sk->sk_state != TCP_ESTABLISHED) {
release_sock(sk);
return -ENOTCONN;
}
/* Now we can treat all alike */
if ((skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &er)) == NULL) {
release_sock(sk);
return er;
}
skb_reset_transport_header(skb);
copied = skb->len;
if (copied > size) {
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
er = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (er < 0) {
skb_free_datagram(sk, skb);
release_sock(sk);
return er;
}
if (sax != NULL) {
memset(sax, 0, sizeof(sax));
sax->sax25_family = AF_NETROM;
skb_copy_from_linear_data_offset(skb, 7, sax->sax25_call.ax25_call,
AX25_ADDR_LEN);
}
msg->msg_namelen = sizeof(*sax);
skb_free_datagram(sk, skb);
release_sock(sk);
return copied;
}
Commit Message: netrom: fix invalid use of sizeof in nr_recvmsg()
sizeof() when applied to a pointer typed expression gives the size of the
pointer, not that of the pointed data.
Introduced by commit 3ce5ef(netrom: fix info leak via msg_name in nr_recvmsg)
Signed-off-by: Wei Yongjun <yongjun_wei@trendmicro.com.cn>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-200 | 1 | 169,894 |
Analyze the following 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 arch_reinit_sched_domains(void)
{
get_online_cpus();
/* Destroy domains first to force the rebuild */
partition_sched_domains(0, NULL, NULL);
rebuild_sched_domains();
put_online_cpus();
}
Commit Message: Sched: fix skip_clock_update optimization
idle_balance() drops/retakes rq->lock, leaving the previous task
vulnerable to set_tsk_need_resched(). Clear it after we return
from balancing instead, and in setup_thread_stack() as well, so
no successfully descheduled or never scheduled task has it set.
Need resched confused the skip_clock_update logic, which assumes
that the next call to update_rq_clock() will come nearly immediately
after being set. Make the optimization robust against the waking
a sleeper before it sucessfully deschedules case by checking that
the current task has not been dequeued before setting the flag,
since it is that useless clock update we're trying to save, and
clear unconditionally in schedule() proper instead of conditionally
in put_prev_task().
Signed-off-by: Mike Galbraith <efault@gmx.de>
Reported-by: Bjoern B. Brandenburg <bbb.lst@gmail.com>
Tested-by: Yong Zhang <yong.zhang0@gmail.com>
Signed-off-by: Peter Zijlstra <a.p.zijlstra@chello.nl>
Cc: stable@kernel.org
LKML-Reference: <1291802742.1417.9.camel@marge.simson.net>
Signed-off-by: Ingo Molnar <mingo@elte.hu>
CWE ID: | 0 | 22,341 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: parse_object_field(JsonLexContext *lex, JsonSemAction *sem)
{
/*
* An object field is "fieldname" : value where value can be a scalar,
* object or array. Note: in user-facing docs and error messages, we
* generally call a field name a "key".
*/
char *fname = NULL; /* keep compiler quiet */
json_ofield_action ostart = sem->object_field_start;
json_ofield_action oend = sem->object_field_end;
bool isnull;
char **fnameaddr = NULL;
JsonTokenType tok;
if (ostart != NULL || oend != NULL)
fnameaddr = &fname;
if (!lex_accept(lex, JSON_TOKEN_STRING, fnameaddr))
report_parse_error(JSON_PARSE_STRING, lex);
lex_expect(JSON_PARSE_OBJECT_LABEL, lex, JSON_TOKEN_COLON);
tok = lex_peek(lex);
isnull = tok == JSON_TOKEN_NULL;
if (ostart != NULL)
(*ostart) (sem->semstate, fname, isnull);
switch (tok)
{
case JSON_TOKEN_OBJECT_START:
parse_object(lex, sem);
break;
case JSON_TOKEN_ARRAY_START:
parse_array(lex, sem);
break;
default:
parse_scalar(lex, sem);
}
if (oend != NULL)
(*oend) (sem->semstate, fname, isnull);
}
Commit Message:
CWE ID: CWE-119 | 0 | 2,549 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: event_signal(void *eventhdl)
{
return (int)SetEvent((HANDLE)eventhdl);
}
Commit Message: Check length of memcmp
CWE ID: CWE-125 | 0 | 81,661 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void AutomationProvider::Cut(int tab_handle) {
RenderViewHost* view = GetViewForTab(tab_handle);
if (!view) {
NOTREACHED();
return;
}
view->Cut();
}
Commit Message: Rename the TabContentWrapper pieces to be "TabHelper"s. (Except for the PasswordManager... for now.) Also, just pre-create them up-front. It saves us effort, as they're all going to be eventually created anyway, so being lazy saves us nothing and creates headaches since the rules about what can be lazy differ from feature to feature.
BUG=71097
TEST=zero visible change
Review URL: http://codereview.chromium.org/6480117
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75170 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | 0 | 101,939 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static inline void VectorClamp3(DDSVector3 *value)
{
value->x = MagickMin(1.0f,MagickMax(0.0f,value->x));
value->y = MagickMin(1.0f,MagickMax(0.0f,value->y));
value->z = MagickMin(1.0f,MagickMax(0.0f,value->z));
}
Commit Message: Added check to prevent image being 0x0 (reported in #489).
CWE ID: CWE-20 | 0 | 65,115 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: findb(const png_byte *name)
{
int i = NINFO;
while (--i >= 0)
{
if (memcmp(chunk_info[i].name, name, 4) == 0)
break;
}
return i;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | 0 | 159,961 |
Analyze the following 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 setJSTestObjWithScriptExecutionContextAttributeRaises(ExecState* exec, JSObject* thisObject, JSValue value)
{
JSTestObj* castedThis = jsCast<JSTestObj*>(thisObject);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
ExceptionCode ec = 0;
ScriptExecutionContext* scriptContext = jsCast<JSDOMGlobalObject*>(exec->lexicalGlobalObject())->scriptExecutionContext();
if (!scriptContext)
return;
impl->setWithScriptExecutionContextAttributeRaises(scriptContext, toTestObj(value), ec);
setDOMException(exec, ec);
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | 0 | 101,370 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: long FS_fplength(FILE *h)
{
long pos;
long end;
pos = ftell(h);
fseek(h, 0, SEEK_END);
end = ftell(h);
fseek(h, pos, SEEK_SET);
return end;
}
Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s
CWE ID: CWE-269 | 0 | 95,843 |
Analyze the following 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 mptsas_cancel_notify(Notifier *notifier, void *data)
{
MPTSASCancelNotifier *n = container_of(notifier,
MPTSASCancelNotifier,
notifier);
/* Abusing IOCLogInfo to store the expected number of requests... */
if (++n->reply->TerminationCount == n->reply->IOCLogInfo) {
n->reply->IOCLogInfo = 0;
mptsas_fix_scsi_task_mgmt_reply_endianness(n->reply);
mptsas_post_reply(n->s, (MPIDefaultReply *)n->reply);
g_free(n->reply);
}
g_free(n);
}
Commit Message:
CWE ID: CWE-787 | 0 | 8,354 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void virtio_update_irq(VirtIODevice *vdev)
{
virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
}
Commit Message:
CWE ID: CWE-20 | 0 | 9,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: static void ipgre_destroy_tunnels(struct ipgre_net *ign, struct list_head *head)
{
int prio;
for (prio = 0; prio < 4; prio++) {
int h;
for (h = 0; h < HASH_SIZE; h++) {
struct ip_tunnel *t;
t = rtnl_dereference(ign->tunnels[prio][h]);
while (t != NULL) {
unregister_netdevice_queue(t->dev, head);
t = rtnl_dereference(t->next);
}
}
}
}
Commit Message: net: don't allow CAP_NET_ADMIN to load non-netdev kernel modules
Since a8f80e8ff94ecba629542d9b4b5f5a8ee3eb565c any process with
CAP_NET_ADMIN may load any module from /lib/modules/. This doesn't mean
that CAP_NET_ADMIN is a superset of CAP_SYS_MODULE as modules are
limited to /lib/modules/**. However, CAP_NET_ADMIN capability shouldn't
allow anybody load any module not related to networking.
This patch restricts an ability of autoloading modules to netdev modules
with explicit aliases. This fixes CVE-2011-1019.
Arnd Bergmann suggested to leave untouched the old pre-v2.6.32 behavior
of loading netdev modules by name (without any prefix) for processes
with CAP_SYS_MODULE to maintain the compatibility with network scripts
that use autoloading netdev modules by aliases like "eth0", "wlan0".
Currently there are only three users of the feature in the upstream
kernel: ipip, ip_gre and sit.
root@albatros:~# capsh --drop=$(seq -s, 0 11),$(seq -s, 13 34) --
root@albatros:~# grep Cap /proc/$$/status
CapInh: 0000000000000000
CapPrm: fffffff800001000
CapEff: fffffff800001000
CapBnd: fffffff800001000
root@albatros:~# modprobe xfs
FATAL: Error inserting xfs
(/lib/modules/2.6.38-rc6-00001-g2bf4ca3/kernel/fs/xfs/xfs.ko): Operation not permitted
root@albatros:~# lsmod | grep xfs
root@albatros:~# ifconfig xfs
xfs: error fetching interface information: Device not found
root@albatros:~# lsmod | grep xfs
root@albatros:~# lsmod | grep sit
root@albatros:~# ifconfig sit
sit: error fetching interface information: Device not found
root@albatros:~# lsmod | grep sit
root@albatros:~# ifconfig sit0
sit0 Link encap:IPv6-in-IPv4
NOARP MTU:1480 Metric:1
root@albatros:~# lsmod | grep sit
sit 10457 0
tunnel4 2957 1 sit
For CAP_SYS_MODULE module loading is still relaxed:
root@albatros:~# grep Cap /proc/$$/status
CapInh: 0000000000000000
CapPrm: ffffffffffffffff
CapEff: ffffffffffffffff
CapBnd: ffffffffffffffff
root@albatros:~# ifconfig xfs
xfs: error fetching interface information: Device not found
root@albatros:~# lsmod | grep xfs
xfs 745319 0
Reference: https://lkml.org/lkml/2011/2/24/203
Signed-off-by: Vasiliy Kulikov <segoon@openwall.com>
Signed-off-by: Michael Tokarev <mjt@tls.msk.ru>
Acked-by: David S. Miller <davem@davemloft.net>
Acked-by: Kees Cook <kees.cook@canonical.com>
Signed-off-by: James Morris <jmorris@namei.org>
CWE ID: CWE-264 | 0 | 35,313 |
Analyze the following 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::FloatPoint OutOfProcessInstance::BoundScrollOffsetToDocument(
const pp::FloatPoint& scroll_offset) {
float max_x = document_size_.width() * zoom_ - plugin_dip_size_.width();
float x = std::max(std::min(scroll_offset.x(), max_x), 0.0f);
float min_y = -top_toolbar_height_;
float max_y = document_size_.height() * zoom_ - plugin_dip_size_.height();
float y = std::max(std::min(scroll_offset.y(), max_y), min_y);
return pp::FloatPoint(x, y);
}
Commit Message: Prevent leaking PDF data cross-origin
BUG=520422
Review URL: https://codereview.chromium.org/1311973002
Cr-Commit-Position: refs/heads/master@{#345267}
CWE ID: CWE-20 | 0 | 129,409 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: PickerIndicatorElement* BaseMultipleFieldsDateAndTimeInputType::pickerIndicatorElement() const
{
return toPickerIndicatorElement(elementById(ShadowElementNames::pickerIndicator()));
}
Commit Message: Fix reentrance of BaseMultipleFieldsDateAndTimeInputType::destroyShadowSubtree.
destroyShadowSubtree could dispatch 'blur' event unexpectedly because
element()->focused() had incorrect information. We make sure it has
correct information by checking if the UA shadow root contains the
focused element.
BUG=257353
Review URL: https://chromiumcodereview.appspot.com/19067004
git-svn-id: svn://svn.chromium.org/blink/trunk@154086 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | 0 | 112,472 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static void process_service_search_rsp(tCONN_CB* p_ccb, uint8_t* p_reply,
uint8_t* p_reply_end) {
uint16_t xx;
uint16_t total, cur_handles, orig;
uint8_t cont_len;
/* Skip transaction, and param len */
p_reply += 4;
BE_STREAM_TO_UINT16(total, p_reply);
BE_STREAM_TO_UINT16(cur_handles, p_reply);
orig = p_ccb->num_handles;
p_ccb->num_handles += cur_handles;
if (p_ccb->num_handles == 0) {
SDP_TRACE_WARNING("SDP - Rcvd ServiceSearchRsp, no matches");
sdp_disconnect(p_ccb, SDP_NO_RECS_MATCH);
return;
}
/* Save the handles that match. We will can only process a certain number. */
if (total > sdp_cb.max_recs_per_search) total = sdp_cb.max_recs_per_search;
if (p_ccb->num_handles > sdp_cb.max_recs_per_search)
p_ccb->num_handles = sdp_cb.max_recs_per_search;
for (xx = orig; xx < p_ccb->num_handles; xx++)
BE_STREAM_TO_UINT32(p_ccb->handles[xx], p_reply);
BE_STREAM_TO_UINT8(cont_len, p_reply);
if (cont_len != 0) {
if (cont_len > SDP_MAX_CONTINUATION_LEN) {
sdp_disconnect(p_ccb, SDP_INVALID_CONT_STATE);
return;
}
if (p_reply + cont_len > p_reply_end) {
android_errorWriteLog(0x534e4554, "68161546");
sdp_disconnect(p_ccb, SDP_INVALID_CONT_STATE);
return;
}
/* stay in the same state */
sdp_snd_service_search_req(p_ccb, cont_len, p_reply);
} else {
/* change state */
p_ccb->disc_state = SDP_DISC_WAIT_ATTR;
/* Kick off the first attribute request */
process_service_attr_rsp(p_ccb, NULL, NULL);
}
}
Commit Message: Fix copy length calculation in sdp_copy_raw_data
Test: compilation
Bug: 110216176
Change-Id: Ic4a19c9f0fe8cd592bc6c25dcec7b1da49ff7459
(cherry picked from commit 23aa15743397b345f3d948289fe90efa2a2e2b3e)
CWE ID: CWE-787 | 0 | 162,902 |
Analyze the following 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::getRGB(GfxColor *color, GfxRGB *rgb) {
GfxColor color2;
base->getRGB(mapColorToBase(color, &color2), rgb);
}
Commit Message:
CWE ID: CWE-189 | 0 | 1,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: AppCacheDatabase::AppCacheDatabase(const base::FilePath& path)
: db_file_path_(path),
is_disabled_(false),
is_recreating_(false),
was_corruption_detected_(false) {
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <staphany@chromium.org>
> Reviewed-by: Victor Costan <pwnall@chromium.org>
> Reviewed-by: Marijn Kruisselbrink <mek@chromium.org>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <pwnall@chromium.org>
Commit-Queue: Staphany Park <staphany@chromium.org>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | 0 | 151,261 |
Analyze the following 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 print_word(BIO *bp,BN_ULONG w)
{
#ifdef SIXTY_FOUR_BIT
if (sizeof(w) > sizeof(unsigned long))
{
unsigned long h=(unsigned long)(w>>32),
l=(unsigned long)(w);
if (h) BIO_printf(bp,"%lX%08lX",h,l);
else BIO_printf(bp,"%lX",l);
return;
}
#endif
BIO_printf(bp,BN_HEX_FMT1,w);
}
Commit Message: Fix for CVE-2014-3570 (with minor bn_asm.c revamp).
Reviewed-by: Emilia Kasper <emilia@openssl.org>
CWE ID: CWE-310 | 0 | 46,494 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: error::Error GLES2DecoderImpl::HandleReadPixels(
uint32 immediate_data_size, const gles2::ReadPixels& c) {
GLint x = c.x;
GLint y = c.y;
GLsizei width = c.width;
GLsizei height = c.height;
GLenum format = c.format;
GLenum type = c.type;
if (width < 0 || height < 0) {
SetGLError(GL_INVALID_VALUE, "glReadPixels: dimensions < 0");
return error::kNoError;
}
typedef gles2::ReadPixels::Result Result;
uint32 pixels_size;
if (!GLES2Util::ComputeImageDataSize(
width, height, format, type, pack_alignment_, &pixels_size)) {
return error::kOutOfBounds;
}
void* pixels = GetSharedMemoryAs<void*>(
c.pixels_shm_id, c.pixels_shm_offset, pixels_size);
Result* result = GetSharedMemoryAs<Result*>(
c.result_shm_id, c.result_shm_offset, sizeof(*result));
if (!pixels || !result) {
return error::kOutOfBounds;
}
if (!validators_->read_pixel_format.IsValid(format)) {
SetGLError(GL_INVALID_ENUM, "glReadPixels: format GL_INVALID_ENUM");
return error::kNoError;
}
if (!validators_->pixel_type.IsValid(type)) {
SetGLError(GL_INVALID_ENUM, "glReadPixels: type GL_INVALID_ENUM");
return error::kNoError;
}
if (width == 0 || height == 0) {
return error::kNoError;
}
gfx::Size max_size = GetBoundReadFrameBufferSize();
GLint max_x;
GLint max_y;
if (!SafeAdd(x, width, &max_x) || !SafeAdd(y, height, &max_y)) {
SetGLError(GL_INVALID_VALUE, "glReadPixels: dimensions out of range");
return error::kNoError;
}
if (!CheckBoundFramebuffersValid("glReadPixels")) {
return error::kNoError;
}
CopyRealGLErrorsToWrapper();
ScopedResolvedFrameBufferBinder binder(this, false, true);
if (x < 0 || y < 0 || max_x > max_size.width() || max_y > max_size.height()) {
uint32 temp_size;
if (!GLES2Util::ComputeImageDataSize(
width, 1, format, type, pack_alignment_, &temp_size)) {
SetGLError(GL_INVALID_VALUE, "glReadPixels: dimensions out of range");
return error::kNoError;
}
GLsizei unpadded_row_size = temp_size;
if (!GLES2Util::ComputeImageDataSize(
width, 2, format, type, pack_alignment_, &temp_size)) {
SetGLError(GL_INVALID_VALUE, "glReadPixels: dimensions out of range");
return error::kNoError;
}
GLsizei padded_row_size = temp_size - unpadded_row_size;
if (padded_row_size < 0 || unpadded_row_size < 0) {
SetGLError(GL_INVALID_VALUE, "glReadPixels: dimensions out of range");
return error::kNoError;
}
GLint dest_x_offset = std::max(-x, 0);
uint32 dest_row_offset;
if (!GLES2Util::ComputeImageDataSize(
dest_x_offset, 1, format, type, pack_alignment_, &dest_row_offset)) {
SetGLError(GL_INVALID_VALUE, "glReadPixels: dimensions out of range");
return error::kNoError;
}
int8* dst = static_cast<int8*>(pixels);
GLint read_x = std::max(0, x);
GLint read_end_x = std::max(0, std::min(max_size.width(), max_x));
GLint read_width = read_end_x - read_x;
for (GLint yy = 0; yy < height; ++yy) {
GLint ry = y + yy;
memset(dst, 0, unpadded_row_size);
if (ry >= 0 && ry < max_size.height() && read_width > 0) {
glReadPixels(
read_x, ry, read_width, 1, format, type, dst + dest_row_offset);
}
dst += padded_row_size;
}
} else {
glReadPixels(x, y, width, height, format, type, pixels);
}
GLenum error = PeekGLError();
if (error == GL_NO_ERROR) {
*result = true;
GLenum read_format = GetBoundReadFrameBufferInternalFormat();
uint32 channels_exist = GLES2Util::GetChannelsForFormat(read_format);
if ((channels_exist & 0x0008) == 0) {
uint32 temp_size;
if (!GLES2Util::ComputeImageDataSize(
width, 1, format, type, pack_alignment_, &temp_size)) {
SetGLError(GL_INVALID_VALUE, "glReadPixels: dimensions out of range");
return error::kNoError;
}
GLsizei unpadded_row_size = temp_size;
if (!GLES2Util::ComputeImageDataSize(
width, 2, format, type, pack_alignment_, &temp_size)) {
SetGLError(GL_INVALID_VALUE, "glReadPixels: dimensions out of range");
return error::kNoError;
}
GLsizei padded_row_size = temp_size - unpadded_row_size;
if (padded_row_size < 0 || unpadded_row_size < 0) {
SetGLError(GL_INVALID_VALUE, "glReadPixels: dimensions out of range");
return error::kNoError;
}
if (type != GL_UNSIGNED_BYTE) {
SetGLError(GL_INVALID_OPERATION, "unsupported readPixel format");
return error::kNoError;
}
switch (format) {
case GL_RGBA:
case GL_BGRA_EXT:
case GL_ALPHA: {
int offset = (format == GL_ALPHA) ? 0 : 3;
int step = (format == GL_ALPHA) ? 1 : 4;
uint8* dst = static_cast<uint8*>(pixels) + offset;
for (GLint yy = 0; yy < height; ++yy) {
uint8* end = dst + unpadded_row_size;
for (uint8* d = dst; d < end; d += step) {
*d = 255;
}
dst += padded_row_size;
}
break;
}
default:
break;
}
}
}
return error::kNoError;
}
Commit Message: Always write data to new buffer in SimulateAttrib0
This is to work around linux nvidia driver bug.
TEST=asan
BUG=118970
Review URL: http://codereview.chromium.org/10019003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@131538 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | 0 | 109,021 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void RenderThreadImpl::IdleHandlerInForegroundTab() {
int64 new_delay_ms = idle_notification_delay_in_ms_ +
1000000 / (idle_notification_delay_in_ms_ + 2000);
if (new_delay_ms >= kLongIdleHandlerDelayMs)
new_delay_ms = kShortIdleHandlerDelayMs;
if (idle_notifications_to_skip_ > 0) {
idle_notifications_to_skip_--;
} else {
int cpu_usage = 0;
Send(new ViewHostMsg_GetCPUUsage(&cpu_usage));
int idle_hint = static_cast<int>(new_delay_ms / 10);
if (cpu_usage < kIdleCPUUsageThresholdInPercents) {
base::allocator::ReleaseFreeMemory();
bool finished_idle_work = true;
if (blink::mainThreadIsolate() &&
!blink::mainThreadIsolate()->IdleNotification(idle_hint)) {
finished_idle_work = false;
}
if (!base::DiscardableMemory::ReduceMemoryUsage())
finished_idle_work = false;
if (finished_idle_work)
new_delay_ms = kLongIdleHandlerDelayMs;
}
}
ScheduleIdleHandler(new_delay_ms);
}
Commit Message: Disable forwarding tasks to the Blink scheduler
Disable forwarding tasks to the Blink scheduler to avoid some
regressions which it has introduced.
BUG=391005,415758,415478,412714,416362,416827,417608
TBR=jamesr@chromium.org
Review URL: https://codereview.chromium.org/609483002
Cr-Commit-Position: refs/heads/master@{#296916}
CWE ID: | 0 | 126,744 |
Analyze the following 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 WebGLRenderingContextBase::scissor(GLint x,
GLint y,
GLsizei width,
GLsizei height) {
if (isContextLost())
return;
scissor_box_[0] = x;
scissor_box_[1] = y;
scissor_box_[2] = width;
scissor_box_[3] = height;
ContextGL()->Scissor(x, y, width, height);
}
Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later.
BUG=740603
TEST=new conformance test
R=kbr@chromium.org,piman@chromium.org
Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4
Reviewed-on: https://chromium-review.googlesource.com/570840
Reviewed-by: Antoine Labour <piman@chromium.org>
Reviewed-by: Kenneth Russell <kbr@chromium.org>
Commit-Queue: Zhenyao Mo <zmo@chromium.org>
Cr-Commit-Position: refs/heads/master@{#486518}
CWE ID: CWE-119 | 0 | 133,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: static MagickBooleanType WriteJPEGImage(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
const char
*dct_method,
*option,
*sampling_factor,
*value;
ErrorManager
error_manager;
Image
*volatile volatile_image;
int
colorspace,
quality;
JSAMPLE
*volatile jpeg_pixels;
JSAMPROW
scanline[1];
MagickBooleanType
status;
MemoryInfo
*memory_info;
register JSAMPLE
*q;
register ssize_t
i;
ssize_t
y;
struct jpeg_compress_struct
jpeg_info;
struct jpeg_error_mgr
jpeg_error;
unsigned short
scale;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if ((LocaleCompare(image_info->magick,"JPS") == 0) &&
(image->next != (Image *) NULL))
image=AppendImages(image,MagickFalse,exception);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
/*
Initialize JPEG parameters.
*/
(void) memset(&error_manager,0,sizeof(error_manager));
(void) memset(&jpeg_info,0,sizeof(jpeg_info));
(void) memset(&jpeg_error,0,sizeof(jpeg_error));
volatile_image=image;
jpeg_info.client_data=(void *) volatile_image;
jpeg_info.err=jpeg_std_error(&jpeg_error);
jpeg_info.err->emit_message=(void (*)(j_common_ptr,int)) JPEGWarningHandler;
jpeg_info.err->error_exit=(void (*)(j_common_ptr)) JPEGErrorHandler;
error_manager.exception=exception;
error_manager.image=volatile_image;
memory_info=(MemoryInfo *) NULL;
if (setjmp(error_manager.error_recovery) != 0)
{
jpeg_destroy_compress(&jpeg_info);
(void) CloseBlob(volatile_image);
return(MagickFalse);
}
jpeg_info.client_data=(void *) &error_manager;
jpeg_create_compress(&jpeg_info);
JPEGDestinationManager(&jpeg_info,image);
if ((image->columns != (unsigned int) image->columns) ||
(image->rows != (unsigned int) image->rows))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
jpeg_info.image_width=(unsigned int) image->columns;
jpeg_info.image_height=(unsigned int) image->rows;
jpeg_info.input_components=3;
jpeg_info.data_precision=8;
jpeg_info.in_color_space=JCS_RGB;
switch (image->colorspace)
{
case CMYKColorspace:
{
jpeg_info.input_components=4;
jpeg_info.in_color_space=JCS_CMYK;
break;
}
case YCbCrColorspace:
case Rec601YCbCrColorspace:
case Rec709YCbCrColorspace:
{
jpeg_info.in_color_space=JCS_YCbCr;
break;
}
case LinearGRAYColorspace:
case GRAYColorspace:
{
if (image_info->type == TrueColorType)
break;
jpeg_info.input_components=1;
jpeg_info.in_color_space=JCS_GRAYSCALE;
break;
}
default:
{
(void) TransformImageColorspace(image,sRGBColorspace,exception);
if (image_info->type == TrueColorType)
break;
if (SetImageGray(image,exception) != MagickFalse)
{
jpeg_info.input_components=1;
jpeg_info.in_color_space=JCS_GRAYSCALE;
}
break;
}
}
jpeg_set_defaults(&jpeg_info);
if (jpeg_info.in_color_space == JCS_CMYK)
jpeg_set_colorspace(&jpeg_info,JCS_YCCK);
if ((jpeg_info.data_precision != 12) && (image->depth <= 8))
jpeg_info.data_precision=8;
else
jpeg_info.data_precision=BITS_IN_JSAMPLE;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Image resolution: %.20g,%.20g",image->resolution.x,image->resolution.y);
if ((image->resolution.x != 0.0) && (image->resolution.y != 0.0))
{
/*
Set image resolution.
*/
jpeg_info.write_JFIF_header=TRUE;
jpeg_info.X_density=(UINT16) image->resolution.x;
jpeg_info.Y_density=(UINT16) image->resolution.y;
/*
Set image resolution units.
*/
if (image->units == PixelsPerInchResolution)
jpeg_info.density_unit=(UINT8) 1;
if (image->units == PixelsPerCentimeterResolution)
jpeg_info.density_unit=(UINT8) 2;
}
dct_method=GetImageOption(image_info,"jpeg:dct-method");
if (dct_method != (const char *) NULL)
switch (*dct_method)
{
case 'D':
case 'd':
{
if (LocaleCompare(dct_method,"default") == 0)
jpeg_info.dct_method=JDCT_DEFAULT;
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(dct_method,"fastest") == 0)
jpeg_info.dct_method=JDCT_FASTEST;
if (LocaleCompare(dct_method,"float") == 0)
jpeg_info.dct_method=JDCT_FLOAT;
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(dct_method,"ifast") == 0)
jpeg_info.dct_method=JDCT_IFAST;
if (LocaleCompare(dct_method,"islow") == 0)
jpeg_info.dct_method=JDCT_ISLOW;
break;
}
}
option=GetImageOption(image_info,"jpeg:optimize-coding");
if (option != (const char *) NULL)
jpeg_info.optimize_coding=IsStringTrue(option) != MagickFalse ? TRUE :
FALSE;
else
{
MagickSizeType
length;
length=(MagickSizeType) jpeg_info.input_components*image->columns*
image->rows*sizeof(JSAMPLE);
if (length == (MagickSizeType) ((size_t) length))
{
/*
Perform optimization only if available memory resources permit it.
*/
status=AcquireMagickResource(MemoryResource,length);
if (status != MagickFalse)
RelinquishMagickResource(MemoryResource,length);
jpeg_info.optimize_coding=status == MagickFalse ? FALSE : TRUE;
}
}
#if defined(C_ARITH_CODING_SUPPORTED)
option=GetImageOption(image_info,"jpeg:arithmetic-coding");
if (IsStringTrue(option) != MagickFalse)
{
jpeg_info.arith_code=TRUE;
jpeg_info.optimize_coding=FALSE; // Not supported.
}
#endif
#if (JPEG_LIB_VERSION >= 61) && defined(C_PROGRESSIVE_SUPPORTED)
if ((LocaleCompare(image_info->magick,"PJPEG") == 0) ||
(image_info->interlace != NoInterlace))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Interlace: progressive");
jpeg_simple_progression(&jpeg_info);
}
else
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Interlace: non-progressive");
#else
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Interlace: nonprogressive");
#endif
quality=92;
if ((image_info->compression != LosslessJPEGCompression) &&
(image->quality <= 100))
{
if (image->quality != UndefinedCompressionQuality)
quality=(int) image->quality;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Quality: %.20g",
(double) image->quality);
}
else
{
#if !defined(C_LOSSLESS_SUPPORTED)
quality=100;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Quality: 100");
#else
if (image->quality < 100)
(void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
"LosslessToLossyJPEGConversion","`%s'",image->filename);
else
{
int
point_transform,
predictor;
predictor=image->quality/100; /* range 1-7 */
point_transform=image->quality % 20; /* range 0-15 */
jpeg_simple_lossless(&jpeg_info,predictor,point_transform);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Compression: lossless");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Predictor: %d",predictor);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Point Transform: %d",point_transform);
}
}
#endif
}
option=GetImageOption(image_info,"jpeg:extent");
if (option != (const char *) NULL)
{
Image
*jpeg_image;
ImageInfo
*extent_info;
extent_info=CloneImageInfo(image_info);
extent_info->blob=NULL;
jpeg_image=CloneImage(image,0,0,MagickTrue,exception);
if (jpeg_image != (Image *) NULL)
{
MagickSizeType
extent;
size_t
maximum,
minimum;
/*
Search for compression quality that does not exceed image extent.
*/
extent_info->quality=0;
extent=(MagickSizeType) SiPrefixToDoubleInterval(option,100.0);
(void) DeleteImageOption(extent_info,"jpeg:extent");
(void) DeleteImageArtifact(jpeg_image,"jpeg:extent");
maximum=image_info->quality;
if (maximum < 2)
maximum=101;
for (minimum=2; minimum < maximum; )
{
(void) AcquireUniqueFilename(jpeg_image->filename);
jpeg_image->quality=minimum+(maximum-minimum+1)/2;
status=WriteJPEGImage(extent_info,jpeg_image,exception);
if (GetBlobSize(jpeg_image) <= extent)
minimum=jpeg_image->quality+1;
else
maximum=jpeg_image->quality-1;
(void) RelinquishUniqueFileResource(jpeg_image->filename);
}
quality=(int) minimum-1;
jpeg_image=DestroyImage(jpeg_image);
}
extent_info=DestroyImageInfo(extent_info);
}
jpeg_set_quality(&jpeg_info,quality,TRUE);
if ((dct_method == (const char *) NULL) && (quality <= 90))
jpeg_info.dct_method=JDCT_IFAST;
#if (JPEG_LIB_VERSION >= 70)
option=GetImageOption(image_info,"quality");
if (option != (const char *) NULL)
{
GeometryInfo
geometry_info;
int
flags;
/*
Set quality scaling for luminance and chrominance separately.
*/
flags=ParseGeometry(option,&geometry_info);
if (((flags & RhoValue) != 0) && ((flags & SigmaValue) != 0))
{
jpeg_info.q_scale_factor[0]=jpeg_quality_scaling((int)
(geometry_info.rho+0.5));
jpeg_info.q_scale_factor[1]=jpeg_quality_scaling((int)
(geometry_info.sigma+0.5));
jpeg_default_qtables(&jpeg_info,TRUE);
}
}
#endif
colorspace=jpeg_info.in_color_space;
value=GetImageOption(image_info,"jpeg:colorspace");
if (value == (char *) NULL)
value=GetImageProperty(image,"jpeg:colorspace",exception);
if (value != (char *) NULL)
colorspace=StringToInteger(value);
sampling_factor=(const char *) NULL;
if ((J_COLOR_SPACE) colorspace == jpeg_info.in_color_space)
{
value=GetImageOption(image_info,"jpeg:sampling-factor");
if (value == (char *) NULL)
value=GetImageProperty(image,"jpeg:sampling-factor",exception);
if (value != (char *) NULL)
{
sampling_factor=value;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Input sampling-factors=%s",sampling_factor);
}
}
value=GetImageOption(image_info,"jpeg:sampling-factor");
if (image_info->sampling_factor != (char *) NULL)
sampling_factor=image_info->sampling_factor;
if (sampling_factor == (const char *) NULL)
{
if (quality >= 90)
for (i=0; i < MAX_COMPONENTS; i++)
{
jpeg_info.comp_info[i].h_samp_factor=1;
jpeg_info.comp_info[i].v_samp_factor=1;
}
}
else
{
char
**factors;
GeometryInfo
geometry_info;
MagickStatusType
flags;
/*
Set sampling factor.
*/
i=0;
factors=SamplingFactorToList(sampling_factor);
if (factors != (char **) NULL)
{
for (i=0; i < MAX_COMPONENTS; i++)
{
if (factors[i] == (char *) NULL)
break;
flags=ParseGeometry(factors[i],&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=geometry_info.rho;
jpeg_info.comp_info[i].h_samp_factor=(int) geometry_info.rho;
jpeg_info.comp_info[i].v_samp_factor=(int) geometry_info.sigma;
factors[i]=(char *) RelinquishMagickMemory(factors[i]);
}
factors=(char **) RelinquishMagickMemory(factors);
}
for ( ; i < MAX_COMPONENTS; i++)
{
jpeg_info.comp_info[i].h_samp_factor=1;
jpeg_info.comp_info[i].v_samp_factor=1;
}
}
option=GetImageOption(image_info,"jpeg:q-table");
if (option != (const char *) NULL)
{
QuantizationTable
*table;
/*
Custom quantization tables.
*/
table=GetQuantizationTable(option,"0",exception);
if (table != (QuantizationTable *) NULL)
{
for (i=0; i < MAX_COMPONENTS; i++)
jpeg_info.comp_info[i].quant_tbl_no=0;
jpeg_add_quant_table(&jpeg_info,0,table->levels,
jpeg_quality_scaling(quality),0);
table=DestroyQuantizationTable(table);
}
table=GetQuantizationTable(option,"1",exception);
if (table != (QuantizationTable *) NULL)
{
for (i=1; i < MAX_COMPONENTS; i++)
jpeg_info.comp_info[i].quant_tbl_no=1;
jpeg_add_quant_table(&jpeg_info,1,table->levels,
jpeg_quality_scaling(quality),0);
table=DestroyQuantizationTable(table);
}
table=GetQuantizationTable(option,"2",exception);
if (table != (QuantizationTable *) NULL)
{
for (i=2; i < MAX_COMPONENTS; i++)
jpeg_info.comp_info[i].quant_tbl_no=2;
jpeg_add_quant_table(&jpeg_info,2,table->levels,
jpeg_quality_scaling(quality),0);
table=DestroyQuantizationTable(table);
}
table=GetQuantizationTable(option,"3",exception);
if (table != (QuantizationTable *) NULL)
{
for (i=3; i < MAX_COMPONENTS; i++)
jpeg_info.comp_info[i].quant_tbl_no=3;
jpeg_add_quant_table(&jpeg_info,3,table->levels,
jpeg_quality_scaling(quality),0);
table=DestroyQuantizationTable(table);
}
}
jpeg_start_compress(&jpeg_info,TRUE);
if (image->debug != MagickFalse)
{
if (image->storage_class == PseudoClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Storage class: PseudoClass");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Storage class: DirectClass");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Depth: %.20g",
(double) image->depth);
if (image->colors != 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Number of colors: %.20g",(double) image->colors);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Number of colors: unspecified");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"JPEG data precision: %d",(int) jpeg_info.data_precision);
switch (image->colorspace)
{
case CMYKColorspace:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Storage class: DirectClass");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Colorspace: CMYK");
break;
}
case YCbCrColorspace:
case Rec601YCbCrColorspace:
case Rec709YCbCrColorspace:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Colorspace: YCbCr");
break;
}
default:
break;
}
switch (image->colorspace)
{
case CMYKColorspace:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Colorspace: CMYK");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Sampling factors: %dx%d,%dx%d,%dx%d,%dx%d",
jpeg_info.comp_info[0].h_samp_factor,
jpeg_info.comp_info[0].v_samp_factor,
jpeg_info.comp_info[1].h_samp_factor,
jpeg_info.comp_info[1].v_samp_factor,
jpeg_info.comp_info[2].h_samp_factor,
jpeg_info.comp_info[2].v_samp_factor,
jpeg_info.comp_info[3].h_samp_factor,
jpeg_info.comp_info[3].v_samp_factor);
break;
}
case GRAYColorspace:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Colorspace: GRAY");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Sampling factors: %dx%d",jpeg_info.comp_info[0].h_samp_factor,
jpeg_info.comp_info[0].v_samp_factor);
break;
}
case sRGBColorspace:
case RGBColorspace:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Image colorspace is RGB");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Sampling factors: %dx%d,%dx%d,%dx%d",
jpeg_info.comp_info[0].h_samp_factor,
jpeg_info.comp_info[0].v_samp_factor,
jpeg_info.comp_info[1].h_samp_factor,
jpeg_info.comp_info[1].v_samp_factor,
jpeg_info.comp_info[2].h_samp_factor,
jpeg_info.comp_info[2].v_samp_factor);
break;
}
case YCbCrColorspace:
case Rec601YCbCrColorspace:
case Rec709YCbCrColorspace:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Colorspace: YCbCr");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Sampling factors: %dx%d,%dx%d,%dx%d",
jpeg_info.comp_info[0].h_samp_factor,
jpeg_info.comp_info[0].v_samp_factor,
jpeg_info.comp_info[1].h_samp_factor,
jpeg_info.comp_info[1].v_samp_factor,
jpeg_info.comp_info[2].h_samp_factor,
jpeg_info.comp_info[2].v_samp_factor);
break;
}
default:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Colorspace: %d",
image->colorspace);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Sampling factors: %dx%d,%dx%d,%dx%d,%dx%d",
jpeg_info.comp_info[0].h_samp_factor,
jpeg_info.comp_info[0].v_samp_factor,
jpeg_info.comp_info[1].h_samp_factor,
jpeg_info.comp_info[1].v_samp_factor,
jpeg_info.comp_info[2].h_samp_factor,
jpeg_info.comp_info[2].v_samp_factor,
jpeg_info.comp_info[3].h_samp_factor,
jpeg_info.comp_info[3].v_samp_factor);
break;
}
}
}
/*
Write JPEG profiles.
*/
value=GetImageProperty(image,"comment",exception);
if (value != (char *) NULL)
for (i=0; i < (ssize_t) strlen(value); i+=65533L)
jpeg_write_marker(&jpeg_info,JPEG_COM,(unsigned char *) value+i,
(unsigned int) MagickMin((size_t) strlen(value+i),65533L));
if (image->profiles != (void *) NULL)
WriteProfile(&jpeg_info,image,exception);
/*
Convert MIFF to JPEG raster pixels.
*/
memory_info=AcquireVirtualMemory((size_t) image->columns,
jpeg_info.input_components*sizeof(*jpeg_pixels));
if (memory_info == (MemoryInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
jpeg_pixels=(JSAMPLE *) GetVirtualMemoryBlob(memory_info);
if (setjmp(error_manager.error_recovery) != 0)
{
jpeg_destroy_compress(&jpeg_info);
if (memory_info != (MemoryInfo *) NULL)
memory_info=RelinquishVirtualMemory(memory_info);
(void) CloseBlob(image);
return(MagickFalse);
}
scanline[0]=(JSAMPROW) jpeg_pixels;
scale=65535/(unsigned short) GetQuantumRange((size_t)
jpeg_info.data_precision);
if (scale == 0)
scale=1;
if (jpeg_info.data_precision <= 8)
{
if ((jpeg_info.in_color_space == JCS_RGB) ||
(jpeg_info.in_color_space == JCS_YCbCr))
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=jpeg_pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(JSAMPLE) ScaleQuantumToChar(GetPixelRed(image,p));
*q++=(JSAMPLE) ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=(JSAMPLE) ScaleQuantumToChar(GetPixelBlue(image,p));
p+=GetPixelChannels(image);
}
(void) jpeg_write_scanlines(&jpeg_info,scanline,1);
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
else
if (jpeg_info.in_color_space == JCS_GRAYSCALE)
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=jpeg_pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(JSAMPLE) ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(
image,p)));
p+=GetPixelChannels(image);
}
(void) jpeg_write_scanlines(&jpeg_info,scanline,1);
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=jpeg_pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
/*
Convert DirectClass packets to contiguous CMYK scanlines.
*/
*q++=(JSAMPLE) (ScaleQuantumToChar((Quantum) (QuantumRange-
GetPixelCyan(image,p))));
*q++=(JSAMPLE) (ScaleQuantumToChar((Quantum) (QuantumRange-
GetPixelMagenta(image,p))));
*q++=(JSAMPLE) (ScaleQuantumToChar((Quantum) (QuantumRange-
GetPixelYellow(image,p))));
*q++=(JSAMPLE) (ScaleQuantumToChar((Quantum) (QuantumRange-
GetPixelBlack(image,p))));
p+=GetPixelChannels(image);
}
(void) jpeg_write_scanlines(&jpeg_info,scanline,1);
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
else
if (jpeg_info.in_color_space == JCS_GRAYSCALE)
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=jpeg_pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(JSAMPLE) (ScaleQuantumToShort(ClampToQuantum(GetPixelLuma(image,
p)))/scale);
p+=GetPixelChannels(image);
}
(void) jpeg_write_scanlines(&jpeg_info,scanline,1);
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
else
if ((jpeg_info.in_color_space == JCS_RGB) ||
(jpeg_info.in_color_space == JCS_YCbCr))
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=jpeg_pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(JSAMPLE) (ScaleQuantumToShort(GetPixelRed(image,p))/scale);
*q++=(JSAMPLE) (ScaleQuantumToShort(GetPixelGreen(image,p))/scale);
*q++=(JSAMPLE) (ScaleQuantumToShort(GetPixelBlue(image,p))/scale);
p+=GetPixelChannels(image);
}
(void) jpeg_write_scanlines(&jpeg_info,scanline,1);
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=jpeg_pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
/*
Convert DirectClass packets to contiguous CMYK scanlines.
*/
*q++=(JSAMPLE) (ScaleQuantumToShort(QuantumRange-GetPixelRed(
image,p))/scale);
*q++=(JSAMPLE) (ScaleQuantumToShort(QuantumRange-GetPixelGreen(
image,p))/scale);
*q++=(JSAMPLE) (ScaleQuantumToShort(QuantumRange-GetPixelBlue(
image,p))/scale);
*q++=(JSAMPLE) (ScaleQuantumToShort(QuantumRange-GetPixelBlack(
image,p))/scale);
p+=GetPixelChannels(image);
}
(void) jpeg_write_scanlines(&jpeg_info,scanline,1);
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (y == (ssize_t) image->rows)
jpeg_finish_compress(&jpeg_info);
/*
Relinquish resources.
*/
jpeg_destroy_compress(&jpeg_info);
memory_info=RelinquishVirtualMemory(memory_info);
(void) CloseBlob(image);
return(MagickTrue);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1641
CWE ID: | 0 | 87,319 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static int php_curl_ssl_mutex_unlock(void **m)
{
return tsrm_mutex_unlock(*((MUTEX_T *) m));
}
Commit Message:
CWE ID: | 0 | 5,114 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void AutofillManager::DeterminePossibleFieldTypesForUpload(
const std::vector<AutofillProfile>& profiles,
const std::vector<CreditCard>& credit_cards,
const std::string& app_locale,
FormStructure* submitted_form) {
for (size_t i = 0; i < submitted_form->field_count(); ++i) {
AutofillField* field = submitted_form->field(i);
if (!field->possible_types().empty() && field->IsEmpty()) {
DCHECK_EQ(1u, field->possible_types().size());
DCHECK_EQ(PASSWORD, *field->possible_types().begin());
continue;
}
ServerFieldTypeSet matching_types;
base::string16 value;
base::TrimWhitespace(field->value, base::TRIM_ALL, &value);
for (const AutofillProfile& profile : profiles)
profile.GetMatchingTypes(value, app_locale, &matching_types);
for (const CreditCard& card : credit_cards)
card.GetMatchingTypes(value, app_locale, &matching_types);
if (matching_types.empty())
matching_types.insert(UNKNOWN_TYPE);
field->set_possible_types(matching_types);
}
AutofillManager::DisambiguateUploadTypes(submitted_form);
}
Commit Message: [AF] Don't simplify/dedupe suggestions for (partially) filled sections.
Since Autofill does not fill field by field anymore, this simplifying
and deduping of suggestions is not useful anymore.
Bug: 858820
Cq-Include-Trybots: luci.chromium.try:ios-simulator-full-configs;master.tryserver.chromium.mac:ios-simulator-cronet
Change-Id: I36f7cfe425a0bdbf5ba7503a3d96773b405cc19b
Reviewed-on: https://chromium-review.googlesource.com/1128255
Reviewed-by: Roger McFarlane <rogerm@chromium.org>
Commit-Queue: Sebastien Seguin-Gagnon <sebsg@chromium.org>
Cr-Commit-Position: refs/heads/master@{#573315}
CWE ID: | 0 | 154,938 |
Analyze the following 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 bt_procfs_cleanup(struct net *net, const char *name)
{
}
Commit Message: Bluetooth: fix possible info leak in bt_sock_recvmsg()
In case the socket is already shutting down, bt_sock_recvmsg() returns
with 0 without updating msg_namelen leading to net/socket.c leaking the
local, uninitialized sockaddr_storage variable to userland -- 128 bytes
of kernel stack memory.
Fix this by moving the msg_namelen assignment in front of the shutdown
test.
Cc: Marcel Holtmann <marcel@holtmann.org>
Cc: Gustavo Padovan <gustavo@padovan.org>
Cc: Johan Hedberg <johan.hedberg@gmail.com>
Signed-off-by: Mathias Krause <minipli@googlemail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-200 | 0 | 30,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: _gcry_mpi_powm (gcry_mpi_t res,
gcry_mpi_t base, gcry_mpi_t expo, gcry_mpi_t mod)
{
/* Pointer to the limbs of the arguments, their size and signs. */
mpi_ptr_t rp, ep, mp, bp;
mpi_size_t esize, msize, bsize, rsize;
int msign, bsign, rsign;
/* Flags telling the secure allocation status of the arguments. */
int esec, msec, bsec;
/* Size of the result including space for temporary values. */
mpi_size_t size;
/* Helper. */
int mod_shift_cnt;
int negative_result;
mpi_ptr_t mp_marker = NULL;
mpi_ptr_t bp_marker = NULL;
mpi_ptr_t ep_marker = NULL;
mpi_ptr_t xp_marker = NULL;
unsigned int mp_nlimbs = 0;
unsigned int bp_nlimbs = 0;
unsigned int ep_nlimbs = 0;
unsigned int xp_nlimbs = 0;
mpi_ptr_t tspace = NULL;
mpi_size_t tsize = 0;
esize = expo->nlimbs;
msize = mod->nlimbs;
size = 2 * msize;
msign = mod->sign;
esec = mpi_is_secure(expo);
msec = mpi_is_secure(mod);
bsec = mpi_is_secure(base);
rp = res->d;
ep = expo->d;
MPN_NORMALIZE(ep, esize);
if (!msize)
_gcry_divide_by_zero();
if (!esize)
{
/* Exponent is zero, result is 1 mod MOD, i.e., 1 or 0 depending
on if MOD equals 1. */
res->nlimbs = (msize == 1 && mod->d[0] == 1) ? 0 : 1;
if (res->nlimbs)
{
RESIZE_IF_NEEDED (res, 1);
rp = res->d;
rp[0] = 1;
}
res->sign = 0;
goto leave;
}
/* Normalize MOD (i.e. make its most significant bit set) as
required by mpn_divrem. This will make the intermediate values
in the calculation slightly larger, but the correct result is
obtained after a final reduction using the original MOD value. */
mp_nlimbs = msec? msize:0;
mp = mp_marker = mpi_alloc_limb_space(msize, msec);
count_leading_zeros (mod_shift_cnt, mod->d[msize-1]);
if (mod_shift_cnt)
_gcry_mpih_lshift (mp, mod->d, msize, mod_shift_cnt);
else
MPN_COPY( mp, mod->d, msize );
bsize = base->nlimbs;
bsign = base->sign;
if (bsize > msize)
{
/* The base is larger than the module. Reduce it.
Allocate (BSIZE + 1) with space for remainder and quotient.
(The quotient is (bsize - msize + 1) limbs.) */
bp_nlimbs = bsec ? (bsize + 1):0;
bp = bp_marker = mpi_alloc_limb_space( bsize + 1, bsec );
MPN_COPY ( bp, base->d, bsize );
/* We don't care about the quotient, store it above the
* remainder, at BP + MSIZE. */
_gcry_mpih_divrem( bp + msize, 0, bp, bsize, mp, msize );
bsize = msize;
/* Canonicalize the base, since we are going to multiply with it
quite a few times. */
MPN_NORMALIZE( bp, bsize );
}
else
bp = base->d;
if (!bsize)
{
res->nlimbs = 0;
res->sign = 0;
goto leave;
}
/* Make BASE, EXPO and MOD not overlap with RES. */
if ( rp == bp )
{
/* RES and BASE are identical. Allocate temp. space for BASE. */
gcry_assert (!bp_marker);
bp_nlimbs = bsec? bsize:0;
bp = bp_marker = mpi_alloc_limb_space( bsize, bsec );
MPN_COPY(bp, rp, bsize);
}
if ( rp == ep )
{
/* RES and EXPO are identical. Allocate temp. space for EXPO. */
ep_nlimbs = esec? esize:0;
ep = ep_marker = mpi_alloc_limb_space( esize, esec );
MPN_COPY(ep, rp, esize);
}
if ( rp == mp )
{
/* RES and MOD are identical. Allocate temporary space for MOD.*/
gcry_assert (!mp_marker);
mp_nlimbs = msec?msize:0;
mp = mp_marker = mpi_alloc_limb_space( msize, msec );
MPN_COPY(mp, rp, msize);
}
/* Copy base to the result. */
if (res->alloced < size)
{
mpi_resize (res, size);
rp = res->d;
}
MPN_COPY ( rp, bp, bsize );
rsize = bsize;
rsign = 0;
/* Main processing. */
{
mpi_size_t i;
mpi_ptr_t xp;
int c;
mpi_limb_t e;
mpi_limb_t carry_limb;
struct karatsuba_ctx karactx;
xp_nlimbs = msec? (2 * (msize + 1)):0;
xp = xp_marker = mpi_alloc_limb_space( 2 * (msize + 1), msec );
memset( &karactx, 0, sizeof karactx );
negative_result = (ep[0] & 1) && bsign;
i = esize - 1;
e = ep[i];
count_leading_zeros (c, e);
e = (e << c) << 1; /* Shift the expo bits to the left, lose msb. */
c = BITS_PER_MPI_LIMB - 1 - c;
/* Main loop.
Make the result be pointed to alternately by XP and RP. This
helps us avoid block copying, which would otherwise be
necessary with the overlap restrictions of
_gcry_mpih_divmod. With 50% probability the result after this
loop will be in the area originally pointed by RP (==RES->d),
and with 50% probability in the area originally pointed to by XP. */
for (;;)
{
while (c)
{
mpi_ptr_t tp;
mpi_size_t xsize;
/*mpih_mul_n(xp, rp, rp, rsize);*/
if ( rsize < KARATSUBA_THRESHOLD )
_gcry_mpih_sqr_n_basecase( xp, rp, rsize );
else
{
if ( !tspace )
{
tsize = 2 * rsize;
tspace = mpi_alloc_limb_space( tsize, 0 );
}
else if ( tsize < (2*rsize) )
{
_gcry_mpi_free_limb_space (tspace, 0);
tsize = 2 * rsize;
tspace = mpi_alloc_limb_space (tsize, 0 );
}
_gcry_mpih_sqr_n (xp, rp, rsize, tspace);
}
xsize = 2 * rsize;
if ( xsize > msize )
{
_gcry_mpih_divrem(xp + msize, 0, xp, xsize, mp, msize);
xsize = msize;
}
tp = rp; rp = xp; xp = tp;
rsize = xsize;
/* To mitigate the Yarom/Falkner flush+reload cache
* side-channel attack on the RSA secret exponent, we do
* the multiplication regardless of the value of the
* high-bit of E. But to avoid this performance penalty
* we do it only if the exponent has been stored in secure
* memory and we can thus assume it is a secret exponent. */
if (esec || (mpi_limb_signed_t)e < 0)
{
/*mpih_mul( xp, rp, rsize, bp, bsize );*/
if( bsize < KARATSUBA_THRESHOLD )
_gcry_mpih_mul ( xp, rp, rsize, bp, bsize );
else
_gcry_mpih_mul_karatsuba_case (xp, rp, rsize, bp, bsize,
&karactx);
xsize = rsize + bsize;
if ( xsize > msize )
{
_gcry_mpih_divrem(xp + msize, 0, xp, xsize, mp, msize);
xsize = msize;
}
}
if ( (mpi_limb_signed_t)e < 0 )
{
tp = rp; rp = xp; xp = tp;
rsize = xsize;
}
e <<= 1;
c--;
}
i--;
if ( i < 0 )
break;
e = ep[i];
c = BITS_PER_MPI_LIMB;
}
/* We shifted MOD, the modulo reduction argument, left
MOD_SHIFT_CNT steps. Adjust the result by reducing it with the
original MOD.
Also make sure the result is put in RES->d (where it already
might be, see above). */
if ( mod_shift_cnt )
{
carry_limb = _gcry_mpih_lshift( res->d, rp, rsize, mod_shift_cnt);
rp = res->d;
if ( carry_limb )
{
rp[rsize] = carry_limb;
rsize++;
}
}
else if (res->d != rp)
{
MPN_COPY (res->d, rp, rsize);
rp = res->d;
}
if ( rsize >= msize )
{
_gcry_mpih_divrem(rp + msize, 0, rp, rsize, mp, msize);
rsize = msize;
}
/* Remove any leading zero words from the result. */
if ( mod_shift_cnt )
_gcry_mpih_rshift( rp, rp, rsize, mod_shift_cnt);
MPN_NORMALIZE (rp, rsize);
_gcry_mpih_release_karatsuba_ctx (&karactx );
}
/* Fixup for negative results. */
if ( negative_result && rsize )
{
if ( mod_shift_cnt )
_gcry_mpih_rshift( mp, mp, msize, mod_shift_cnt);
_gcry_mpih_sub( rp, mp, msize, rp, rsize);
rsize = msize;
rsign = msign;
MPN_NORMALIZE(rp, rsize);
}
gcry_assert (res->d == rp);
res->nlimbs = rsize;
res->sign = rsign;
leave:
if (mp_marker)
_gcry_mpi_free_limb_space( mp_marker, mp_nlimbs );
if (bp_marker)
_gcry_mpi_free_limb_space( bp_marker, bp_nlimbs );
if (ep_marker)
_gcry_mpi_free_limb_space( ep_marker, ep_nlimbs );
if (xp_marker)
_gcry_mpi_free_limb_space( xp_marker, xp_nlimbs );
if (tspace)
_gcry_mpi_free_limb_space( tspace, 0 );
}
Commit Message:
CWE ID: CWE-310 | 0 | 17,823 |
Analyze the following 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 tpay_del(GF_Box *s)
{
gf_free((GF_TPAYBox *)s);
}
Commit Message: fixed 2 possible heap overflows (inc. #1088)
CWE ID: CWE-125 | 0 | 80,559 |
Analyze the following 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 activityLoggingAccessPerWorldBindingsLongAttributeAttributeGetterCallbackForMainWorld(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.activityLoggingAccessPerWorldBindingsLongAttribute", 0, 0, "Getter");
TestObjectPythonV8Internal::activityLoggingAccessPerWorldBindingsLongAttributeAttributeGetterForMainWorld(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,093 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: bool AppCacheDatabase::InsertNamespaceRecords(
const std::vector<NamespaceRecord>& records) {
if (records.empty())
return true;
sql::Transaction transaction(db_.get());
if (!transaction.Begin())
return false;
for (const auto& record : records) {
if (!InsertNamespace(&record))
return false;
}
return transaction.Commit();
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <staphany@chromium.org>
> Reviewed-by: Victor Costan <pwnall@chromium.org>
> Reviewed-by: Marijn Kruisselbrink <mek@chromium.org>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <pwnall@chromium.org>
Commit-Queue: Staphany Park <staphany@chromium.org>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | 0 | 151,293 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: error::Error GLES2DecoderImpl::HandleGetShaderPrecisionFormat(
uint32 immediate_data_size, const cmds::GetShaderPrecisionFormat& c) {
GLenum shader_type = static_cast<GLenum>(c.shadertype);
GLenum precision_type = static_cast<GLenum>(c.precisiontype);
typedef cmds::GetShaderPrecisionFormat::Result Result;
Result* result = GetSharedMemoryAs<Result*>(
c.result_shm_id, c.result_shm_offset, sizeof(*result));
if (!result) {
return error::kOutOfBounds;
}
if (result->success != 0) {
return error::kInvalidArguments;
}
if (!validators_->shader_type.IsValid(shader_type)) {
LOCAL_SET_GL_ERROR_INVALID_ENUM(
"glGetShaderPrecisionFormat", shader_type, "shader_type");
return error::kNoError;
}
if (!validators_->shader_precision.IsValid(precision_type)) {
LOCAL_SET_GL_ERROR_INVALID_ENUM(
"glGetShaderPrecisionFormat", precision_type, "precision_type");
return error::kNoError;
}
result->success = 1; // true
GLint range[2] = { 0, 0 };
GLint precision = 0;
GetShaderPrecisionFormatImpl(shader_type, precision_type, range, &precision);
result->min_range = range[0];
result->max_range = range[1];
result->precision = precision;
return error::kNoError;
}
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 | 120,954 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: error::Error GLES2DecoderPassthroughImpl::DoUniform4fv(
GLint location,
GLsizei count,
const volatile GLfloat* v) {
api()->glUniform4fvFn(location, count, const_cast<const GLfloat*>(v));
return error::kNoError;
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <kbr@chromium.org>
Reviewed-by: Kentaro Hara <haraken@chromium.org>
Reviewed-by: Geoff Lang <geofflang@chromium.org>
Reviewed-by: Kenneth Russell <kbr@chromium.org>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416 | 0 | 142,156 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: message_send_paused(const char *const jid)
{
xmpp_ctx_t * const ctx = connection_get_ctx();
xmpp_stanza_t *stanza = stanza_create_chat_state(ctx, jid, STANZA_NAME_PAUSED);
_send_message_stanza(stanza);
xmpp_stanza_release(stanza);
}
Commit Message: Add carbons from check
CWE ID: CWE-346 | 0 | 68,676 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static void smbXcli_negprot_invalid_done(struct tevent_req *subreq)
{
struct tevent_req *req =
tevent_req_callback_data(subreq,
struct tevent_req);
NTSTATUS status;
/*
* we just want the low level error
*/
status = tevent_req_simple_recv_ntstatus(subreq);
TALLOC_FREE(subreq);
if (tevent_req_nterror(req, status)) {
return;
}
/* this should never happen */
tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
}
Commit Message:
CWE ID: CWE-20 | 0 | 2,480 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static void create_boundary_commit_list(struct rev_info *revs)
{
unsigned i;
struct commit *c;
struct object_array *array = &revs->boundary_commits;
struct object_array_entry *objects = array->objects;
/*
* If revs->commits is non-NULL at this point, an error occurred in
* get_revision_1(). Ignore the error and continue printing the
* boundary commits anyway. (This is what the code has always
* done.)
*/
if (revs->commits) {
free_commit_list(revs->commits);
revs->commits = NULL;
}
/*
* Put all of the actual boundary commits from revs->boundary_commits
* into revs->commits
*/
for (i = 0; i < array->nr; i++) {
c = (struct commit *)(objects[i].item);
if (!c)
continue;
if (!(c->object.flags & CHILD_SHOWN))
continue;
if (c->object.flags & (SHOWN | BOUNDARY))
continue;
c->object.flags |= BOUNDARY;
commit_list_insert(c, &revs->commits);
}
/*
* If revs->topo_order is set, sort the boundary commits
* in topological order
*/
sort_in_topological_order(&revs->commits, revs->sort_order);
}
Commit Message: list-objects: pass full pathname to callbacks
When we find a blob at "a/b/c", we currently pass this to
our show_object_fn callbacks as two components: "a/b/" and
"c". Callbacks which want the full value then call
path_name(), which concatenates the two. But this is an
inefficient interface; the path is a strbuf, and we could
simply append "c" to it temporarily, then roll back the
length, without creating a new copy.
So we could improve this by teaching the callsites of
path_name() this trick (and there are only 3). But we can
also notice that no callback actually cares about the
broken-down representation, and simply pass each callback
the full path "a/b/c" as a string. The callback code becomes
even simpler, then, as we do not have to worry about freeing
an allocated buffer, nor rolling back our modification to
the strbuf.
This is theoretically less efficient, as some callbacks
would not bother to format the final path component. But in
practice this is not measurable. Since we use the same
strbuf over and over, our work to grow it is amortized, and
we really only pay to memcpy a few bytes.
Signed-off-by: Jeff King <peff@peff.net>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
CWE ID: CWE-119 | 0 | 54,984 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.